@mistriwork/engine 0.0.0 → 1.0.0-rc.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (572) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +16 -1
  3. package/dist/adapters/adapter.d.ts +726 -0
  4. package/dist/adapters/adapter.js +444 -0
  5. package/dist/adapters/cache/cacheStore.d.ts +75 -0
  6. package/dist/adapters/cache/cacheStore.js +160 -0
  7. package/dist/adapters/cache/resp.d.ts +52 -0
  8. package/dist/adapters/cache/resp.js +237 -0
  9. package/dist/adapters/commands/canonicalJson.d.ts +19 -0
  10. package/dist/adapters/commands/canonicalJson.js +154 -0
  11. package/dist/adapters/connect.d.ts +29 -0
  12. package/dist/adapters/connect.js +40 -0
  13. package/dist/adapters/connectionBudget.d.ts +101 -0
  14. package/dist/adapters/connectionBudget.js +128 -0
  15. package/dist/adapters/dbLatency.d.ts +35 -0
  16. package/dist/adapters/dbLatency.js +79 -0
  17. package/dist/adapters/epochCache.d.ts +50 -0
  18. package/dist/adapters/epochCache.js +85 -0
  19. package/dist/adapters/http/egress.d.ts +48 -0
  20. package/dist/adapters/http/egress.js +175 -0
  21. package/dist/adapters/http/httpAdapter.d.ts +71 -0
  22. package/dist/adapters/http/httpAdapter.js +512 -0
  23. package/dist/adapters/http/httpDescription.d.ts +32 -0
  24. package/dist/adapters/http/httpDescription.js +246 -0
  25. package/dist/adapters/http/openapi.d.ts +98 -0
  26. package/dist/adapters/http/openapi.js +487 -0
  27. package/dist/adapters/layoutRefusal.d.ts +24 -0
  28. package/dist/adapters/layoutRefusal.js +35 -0
  29. package/dist/adapters/net/networkPolicy.d.ts +44 -0
  30. package/dist/adapters/net/networkPolicy.js +123 -0
  31. package/dist/adapters/net/untrustedDatabase.d.ts +18 -0
  32. package/dist/adapters/net/untrustedDatabase.js +120 -0
  33. package/dist/adapters/poolAdmission.d.ts +43 -0
  34. package/dist/adapters/poolAdmission.js +184 -0
  35. package/dist/adapters/poolMetrics.d.ts +121 -0
  36. package/dist/adapters/poolMetrics.js +185 -0
  37. package/dist/adapters/postgres.d.ts +441 -0
  38. package/dist/adapters/postgres.js +1841 -0
  39. package/dist/adapters/postgresCatalog.d.ts +107 -0
  40. package/dist/adapters/postgresCatalog.js +421 -0
  41. package/dist/adapters/postgresCatalogDigest.d.ts +30 -0
  42. package/dist/adapters/postgresCatalogDigest.js +93 -0
  43. package/dist/adapters/postgresCatalogRows.d.ts +64 -0
  44. package/dist/adapters/postgresCatalogRows.js +37 -0
  45. package/dist/adapters/postgresDates.d.ts +1 -0
  46. package/dist/adapters/postgresDates.js +39 -0
  47. package/dist/adapters/postgresMaintenance.d.ts +33 -0
  48. package/dist/adapters/postgresMaintenance.js +179 -0
  49. package/dist/adapters/postgresPool.d.ts +255 -0
  50. package/dist/adapters/postgresPool.js +838 -0
  51. package/dist/adapters/postgresPooler.d.ts +28 -0
  52. package/dist/adapters/postgresPooler.js +267 -0
  53. package/dist/adapters/postgresReadCatalog.d.ts +31 -0
  54. package/dist/adapters/postgresReadCatalog.js +226 -0
  55. package/dist/adapters/postgresReadSnapshot.d.ts +46 -0
  56. package/dist/adapters/postgresReadSnapshot.js +133 -0
  57. package/dist/adapters/postgresSchemaEpoch.d.ts +24 -0
  58. package/dist/adapters/postgresSchemaEpoch.js +149 -0
  59. package/dist/adapters/postgresTransactionHandle.d.ts +173 -0
  60. package/dist/adapters/postgresTransactionHandle.js +524 -0
  61. package/dist/adapters/postgresValues.d.ts +30 -0
  62. package/dist/adapters/postgresValues.js +75 -0
  63. package/dist/adapters/postgresWriteAhead.d.ts +47 -0
  64. package/dist/adapters/postgresWriteAhead.js +209 -0
  65. package/dist/adapters/replicas.d.ts +70 -0
  66. package/dist/adapters/replicas.js +208 -0
  67. package/dist/adapters/reservedSql.d.ts +38 -0
  68. package/dist/adapters/reservedSql.js +264 -0
  69. package/dist/adapters/rolePrivileges.d.ts +17 -0
  70. package/dist/adapters/rolePrivileges.js +22 -0
  71. package/dist/adapters/scoped/keyRows.d.ts +65 -0
  72. package/dist/adapters/scoped/keyRows.js +179 -0
  73. package/dist/adapters/scoped/keyTypes.d.ts +34 -0
  74. package/dist/adapters/scoped/keyTypes.js +66 -0
  75. package/dist/adapters/scoped/postgresScopeCatalog.d.ts +34 -0
  76. package/dist/adapters/scoped/postgresScopeCatalog.js +457 -0
  77. package/dist/adapters/scoped/postgresTriggers.d.ts +137 -0
  78. package/dist/adapters/scoped/postgresTriggers.js +1545 -0
  79. package/dist/adapters/scoped/scopeTriggers.d.ts +122 -0
  80. package/dist/adapters/scoped/scopeTriggers.js +131 -0
  81. package/dist/adapters/scoped/scopedCommandOperations.d.ts +5 -0
  82. package/dist/adapters/scoped/scopedCommandOperations.js +48 -0
  83. package/dist/adapters/scoped/scopedReads.d.ts +22 -0
  84. package/dist/adapters/scoped/scopedReads.js +192 -0
  85. package/dist/adapters/scoped/scopedTransaction.d.ts +159 -0
  86. package/dist/adapters/scoped/scopedTransaction.js +547 -0
  87. package/dist/adapters/scoped/sqliteScopeCatalog.d.ts +32 -0
  88. package/dist/adapters/scoped/sqliteScopeCatalog.js +420 -0
  89. package/dist/adapters/scoped/sqliteTriggerSession.d.ts +64 -0
  90. package/dist/adapters/scoped/sqliteTriggerSession.js +245 -0
  91. package/dist/adapters/scoped/sqliteTriggers.d.ts +20 -0
  92. package/dist/adapters/scoped/sqliteTriggers.js +822 -0
  93. package/dist/adapters/scoped/storedText.d.ts +45 -0
  94. package/dist/adapters/scoped/storedText.js +61 -0
  95. package/dist/adapters/scoped/triggerEffects.d.ts +98 -0
  96. package/dist/adapters/scoped/triggerEffects.js +189 -0
  97. package/dist/adapters/scoped/triggerProof.d.ts +124 -0
  98. package/dist/adapters/scoped/triggerProof.js +366 -0
  99. package/dist/adapters/scoped/updateGuard.d.ts +3 -0
  100. package/dist/adapters/scoped/updateGuard.js +40 -0
  101. package/dist/adapters/serverSettings.d.ts +45 -0
  102. package/dist/adapters/serverSettings.js +46 -0
  103. package/dist/adapters/snapshotRead.d.ts +8 -0
  104. package/dist/adapters/snapshotRead.js +37 -0
  105. package/dist/adapters/sqlite.d.ts +273 -0
  106. package/dist/adapters/sqlite.js +1557 -0
  107. package/dist/adapters/sqliteCostlyReads.d.ts +33 -0
  108. package/dist/adapters/sqliteCostlyReads.js +49 -0
  109. package/dist/adapters/sqliteDecimals.d.ts +22 -0
  110. package/dist/adapters/sqliteDecimals.js +51 -0
  111. package/dist/adapters/sqliteHandles.d.ts +43 -0
  112. package/dist/adapters/sqliteHandles.js +143 -0
  113. package/dist/adapters/sqliteStatementProcess.d.ts +29 -0
  114. package/dist/adapters/sqliteStatementProcess.js +131 -0
  115. package/dist/adapters/statementControl.d.ts +34 -0
  116. package/dist/adapters/statementControl.js +90 -0
  117. package/dist/adapters/storeHost.d.ts +133 -0
  118. package/dist/adapters/storeHost.js +13 -0
  119. package/dist/adapters/telemetry/drivers.d.ts +21 -0
  120. package/dist/adapters/telemetry/drivers.js +321 -0
  121. package/dist/adapters/telemetry/metrics.d.ts +63 -0
  122. package/dist/adapters/telemetry/metrics.js +122 -0
  123. package/dist/adapters/telemetry/otlp.d.ts +12 -0
  124. package/dist/adapters/telemetry/otlp.js +320 -0
  125. package/dist/adapters/telemetry/otlpEncode.d.ts +48 -0
  126. package/dist/adapters/telemetry/otlpEncode.js +366 -0
  127. package/dist/adapters/telemetry/otlpEnv.d.ts +1 -0
  128. package/dist/adapters/telemetry/otlpEnv.js +12 -0
  129. package/dist/adapters/telemetry/serverTiming.d.ts +83 -0
  130. package/dist/adapters/telemetry/serverTiming.js +503 -0
  131. package/dist/adapters/telemetry/start.d.ts +10 -0
  132. package/dist/adapters/telemetry/start.js +25 -0
  133. package/dist/adapters/telemetry/statement.d.ts +16 -0
  134. package/dist/adapters/telemetry/statement.js +134 -0
  135. package/dist/adapters/telemetry/trace.d.ts +127 -0
  136. package/dist/adapters/telemetry/trace.js +295 -0
  137. package/dist/adapters/writeAhead.d.ts +27 -0
  138. package/dist/adapters/writeAhead.js +46 -0
  139. package/dist/adapters/writeAttribution.d.ts +18 -0
  140. package/dist/adapters/writeAttribution.js +23 -0
  141. package/dist/adapters/writeCapture.d.ts +80 -0
  142. package/dist/adapters/writeCapture.js +20 -0
  143. package/dist/adapters/writeLanes.d.ts +94 -0
  144. package/dist/adapters/writeLanes.js +232 -0
  145. package/dist/engine.d.ts +15 -0
  146. package/dist/engine.js +13 -0
  147. package/dist/server/auth/credentials.d.ts +61 -0
  148. package/dist/server/auth/credentials.js +260 -0
  149. package/dist/server/cacheService.d.ts +50 -0
  150. package/dist/server/cacheService.js +110 -0
  151. package/dist/server/cli/args.d.ts +182 -0
  152. package/dist/server/cli/args.js +348 -0
  153. package/dist/server/cli/bin.d.ts +5 -0
  154. package/dist/server/cli/bin.js +66 -0
  155. package/dist/server/cli/browser.d.ts +15 -0
  156. package/dist/server/cli/browser.js +37 -0
  157. package/dist/server/cli/config.d.ts +50 -0
  158. package/dist/server/cli/config.js +206 -0
  159. package/dist/server/cli/startup.d.ts +36 -0
  160. package/dist/server/cli/startup.js +128 -0
  161. package/dist/server/cli/startupOptions.d.ts +63 -0
  162. package/dist/server/cli/startupOptions.js +143 -0
  163. package/dist/server/cli/subcommand.d.ts +28 -0
  164. package/dist/server/cli/subcommand.js +32 -0
  165. package/dist/server/cli/usage.d.ts +13 -0
  166. package/dist/server/cli/usage.js +31 -0
  167. package/dist/server/clientHttp.d.ts +184 -0
  168. package/dist/server/clientHttp.js +700 -0
  169. package/dist/server/clientSurface.d.ts +128 -0
  170. package/dist/server/clientSurface.js +182 -0
  171. package/dist/server/columnGrants.d.ts +106 -0
  172. package/dist/server/columnGrants.js +741 -0
  173. package/dist/server/compileCache.d.ts +1 -0
  174. package/dist/server/compileCache.js +30 -0
  175. package/dist/server/config/locations.d.ts +1 -0
  176. package/dist/server/config/locations.js +15 -0
  177. package/dist/server/config/profile.d.ts +123 -0
  178. package/dist/server/config/profile.js +236 -0
  179. package/dist/server/configPaths.d.ts +7 -0
  180. package/dist/server/configPaths.js +34 -0
  181. package/dist/server/configSections.d.ts +64 -0
  182. package/dist/server/configSections.js +72 -0
  183. package/dist/server/connectionRedaction.d.ts +30 -0
  184. package/dist/server/connectionRedaction.js +77 -0
  185. package/dist/server/connections.d.ts +358 -0
  186. package/dist/server/connections.js +988 -0
  187. package/dist/server/constraints.d.ts +82 -0
  188. package/dist/server/constraints.js +169 -0
  189. package/dist/server/demo.d.ts +9 -0
  190. package/dist/server/demo.js +554 -0
  191. package/dist/server/devclient.d.ts +108 -0
  192. package/dist/server/devclient.js +361 -0
  193. package/dist/server/evidence.d.ts +55 -0
  194. package/dist/server/evidence.js +323 -0
  195. package/dist/server/hiddenColumns.d.ts +32 -0
  196. package/dist/server/hiddenColumns.js +244 -0
  197. package/dist/server/http/baselineHeaders.d.ts +24 -0
  198. package/dist/server/http/baselineHeaders.js +12 -0
  199. package/dist/server/http/captured.d.ts +35 -0
  200. package/dist/server/http/captured.js +73 -0
  201. package/dist/server/http/clock.d.ts +1 -0
  202. package/dist/server/http/clock.js +14 -0
  203. package/dist/server/http/connectionSource.d.ts +4 -0
  204. package/dist/server/http/connectionSource.js +48 -0
  205. package/dist/server/http/context.d.ts +189 -0
  206. package/dist/server/http/context.js +11 -0
  207. package/dist/server/http/crawlerText.d.ts +15 -0
  208. package/dist/server/http/crawlerText.js +32 -0
  209. package/dist/server/http/dataRoutes.d.ts +88 -0
  210. package/dist/server/http/dataRoutes.js +137 -0
  211. package/dist/server/http/door.d.ts +57 -0
  212. package/dist/server/http/door.js +39 -0
  213. package/dist/server/http/exportRoute.d.ts +15 -0
  214. package/dist/server/http/exportRoute.js +320 -0
  215. package/dist/server/http/firstPaint.d.ts +108 -0
  216. package/dist/server/http/firstPaint.js +262 -0
  217. package/dist/server/http/httpOperationRoutes.d.ts +11 -0
  218. package/dist/server/http/httpOperationRoutes.js +50 -0
  219. package/dist/server/http/pageReads.d.ts +20 -0
  220. package/dist/server/http/pageReads.js +205 -0
  221. package/dist/server/http/pageRoutes.d.ts +39 -0
  222. package/dist/server/http/pageRoutes.js +291 -0
  223. package/dist/server/http/probes.d.ts +22 -0
  224. package/dist/server/http/probes.js +27 -0
  225. package/dist/server/http/rateLimit.d.ts +131 -0
  226. package/dist/server/http/rateLimit.js +351 -0
  227. package/dist/server/http/readRoutes.d.ts +9 -0
  228. package/dist/server/http/readRoutes.js +131 -0
  229. package/dist/server/http/readRouting.d.ts +20 -0
  230. package/dist/server/http/readRouting.js +80 -0
  231. package/dist/server/http/recordCompose.d.ts +67 -0
  232. package/dist/server/http/recordCompose.js +167 -0
  233. package/dist/server/http/recordWrites.d.ts +89 -0
  234. package/dist/server/http/recordWrites.js +298 -0
  235. package/dist/server/http/refusalReport.d.ts +38 -0
  236. package/dist/server/http/refusalReport.js +75 -0
  237. package/dist/server/http/reply.d.ts +130 -0
  238. package/dist/server/http/reply.js +394 -0
  239. package/dist/server/http/requestOrigin.d.ts +11 -0
  240. package/dist/server/http/requestOrigin.js +8 -0
  241. package/dist/server/http/router.d.ts +45 -0
  242. package/dist/server/http/router.js +22 -0
  243. package/dist/server/http/serverCore.d.ts +68 -0
  244. package/dist/server/http/serverCore.js +177 -0
  245. package/dist/server/http/traceRequest.d.ts +30 -0
  246. package/dist/server/http/traceRequest.js +224 -0
  247. package/dist/server/http/trust.d.ts +261 -0
  248. package/dist/server/http/trust.js +472 -0
  249. package/dist/server/http/writeRefusal.d.ts +33 -0
  250. package/dist/server/http/writeRefusal.js +24 -0
  251. package/dist/server/httpConnection.d.ts +49 -0
  252. package/dist/server/httpConnection.js +170 -0
  253. package/dist/server/impact.d.ts +55 -0
  254. package/dist/server/impact.js +47 -0
  255. package/dist/server/journal.d.ts +134 -0
  256. package/dist/server/journal.js +398 -0
  257. package/dist/server/keysetReadHttp.d.ts +52 -0
  258. package/dist/server/keysetReadHttp.js +85 -0
  259. package/dist/server/layouts.d.ts +49 -0
  260. package/dist/server/layouts.js +192 -0
  261. package/dist/server/migrate/cli.d.ts +102 -0
  262. package/dist/server/migrate/cli.js +702 -0
  263. package/dist/server/migrate/database.d.ts +37 -0
  264. package/dist/server/migrate/database.js +247 -0
  265. package/dist/server/migrate/desired.d.ts +76 -0
  266. package/dist/server/migrate/desired.js +292 -0
  267. package/dist/server/migrate/files.d.ts +34 -0
  268. package/dist/server/migrate/files.js +141 -0
  269. package/dist/server/migrate/flyway.d.ts +7 -0
  270. package/dist/server/migrate/flyway.js +69 -0
  271. package/dist/server/migrate/history.d.ts +70 -0
  272. package/dist/server/migrate/history.js +211 -0
  273. package/dist/server/migrate/runner.d.ts +100 -0
  274. package/dist/server/migrate/runner.js +413 -0
  275. package/dist/server/migrate/snapshot.d.ts +30 -0
  276. package/dist/server/migrate/snapshot.js +239 -0
  277. package/dist/server/migrate/target.d.ts +33 -0
  278. package/dist/server/migrate/target.js +82 -0
  279. package/dist/server/openapiDraft.d.ts +25 -0
  280. package/dist/server/openapiDraft.js +171 -0
  281. package/dist/server/operations/diagnostics.d.ts +101 -0
  282. package/dist/server/operations/diagnostics.js +284 -0
  283. package/dist/server/operations/requestMetrics.d.ts +33 -0
  284. package/dist/server/operations/requestMetrics.js +94 -0
  285. package/dist/server/packageVersion.d.ts +1 -0
  286. package/dist/server/packageVersion.js +11 -0
  287. package/dist/server/poolConfig.d.ts +34 -0
  288. package/dist/server/poolConfig.js +114 -0
  289. package/dist/server/product.d.ts +20 -0
  290. package/dist/server/product.js +12 -0
  291. package/dist/server/recordHistoryOperations.d.ts +39 -0
  292. package/dist/server/recordHistoryOperations.js +43 -0
  293. package/dist/server/recordWriteOperations.d.ts +111 -0
  294. package/dist/server/recordWriteOperations.js +329 -0
  295. package/dist/server/resourceReadHttp.d.ts +81 -0
  296. package/dist/server/resourceReadHttp.js +606 -0
  297. package/dist/server/resourceReadOperations.d.ts +147 -0
  298. package/dist/server/resourceReadOperations.js +452 -0
  299. package/dist/server/scaffoldMachine.d.ts +54 -0
  300. package/dist/server/scaffoldMachine.js +184 -0
  301. package/dist/server/seed/cli.d.ts +20 -0
  302. package/dist/server/seed/cli.js +164 -0
  303. package/dist/server/seed/lexicon.d.ts +26 -0
  304. package/dist/server/seed/lexicon.js +585 -0
  305. package/dist/server/seed/seed.d.ts +70 -0
  306. package/dist/server/seed/seed.js +779 -0
  307. package/dist/server/seed/words.d.ts +21 -0
  308. package/dist/server/seed/words.js +164 -0
  309. package/dist/server/serverRequests.d.ts +6 -0
  310. package/dist/server/serverRequests.js +33 -0
  311. package/dist/server/serverTimeouts.d.ts +33 -0
  312. package/dist/server/serverTimeouts.js +32 -0
  313. package/dist/server/shapeonly.d.ts +32 -0
  314. package/dist/server/shapeonly.js +115 -0
  315. package/dist/server/startupWarnings.d.ts +32 -0
  316. package/dist/server/startupWarnings.js +92 -0
  317. package/dist/shared/addressParams.d.ts +28 -0
  318. package/dist/shared/addressParams.js +47 -0
  319. package/dist/shared/aggregate.d.ts +49 -0
  320. package/dist/shared/aggregate.js +107 -0
  321. package/dist/shared/appCards.d.ts +123 -0
  322. package/dist/shared/appCards.js +385 -0
  323. package/dist/shared/appComponents.d.ts +177 -0
  324. package/dist/shared/appComponents.js +422 -0
  325. package/dist/shared/appDocuments.d.ts +43 -0
  326. package/dist/shared/appDocuments.js +131 -0
  327. package/dist/shared/appEmbeds.d.ts +21 -0
  328. package/dist/shared/appEmbeds.js +24 -0
  329. package/dist/shared/appIcons.d.ts +28 -0
  330. package/dist/shared/appIcons.js +223 -0
  331. package/dist/shared/appLinks.d.ts +17 -0
  332. package/dist/shared/appLinks.js +124 -0
  333. package/dist/shared/appListColumns.d.ts +3 -0
  334. package/dist/shared/appListColumns.js +66 -0
  335. package/dist/shared/appLocale.d.ts +36 -0
  336. package/dist/shared/appLocale.js +86 -0
  337. package/dist/shared/appMessages.d.ts +44 -0
  338. package/dist/shared/appMessages.js +78 -0
  339. package/dist/shared/appNoun.d.ts +21 -0
  340. package/dist/shared/appNoun.js +32 -0
  341. package/dist/shared/autoBucket.d.ts +98 -0
  342. package/dist/shared/autoBucket.js +305 -0
  343. package/dist/shared/autoValues.d.ts +25 -0
  344. package/dist/shared/autoValues.js +25 -0
  345. package/dist/shared/breakdown.d.ts +228 -0
  346. package/dist/shared/breakdown.js +570 -0
  347. package/dist/shared/breakdowntext.d.ts +41 -0
  348. package/dist/shared/breakdowntext.js +400 -0
  349. package/dist/shared/builtInThemes.d.ts +2 -0
  350. package/dist/shared/builtInThemes.js +771 -0
  351. package/dist/shared/chartSeparation.d.ts +11 -0
  352. package/dist/shared/chartSeparation.js +58 -0
  353. package/dist/shared/clauses.d.ts +22 -0
  354. package/dist/shared/clauses.js +97 -0
  355. package/dist/shared/columnCaption.d.ts +16 -0
  356. package/dist/shared/columnCaption.js +90 -0
  357. package/dist/shared/commandFieldPath.d.ts +2 -0
  358. package/dist/shared/commandFieldPath.js +7 -0
  359. package/dist/shared/commandWire.d.ts +26 -0
  360. package/dist/shared/commandWire.js +41 -0
  361. package/dist/shared/computed.d.ts +161 -0
  362. package/dist/shared/computed.js +378 -0
  363. package/dist/shared/computedParse.d.ts +13 -0
  364. package/dist/shared/computedParse.js +278 -0
  365. package/dist/shared/computedValue.d.ts +47 -0
  366. package/dist/shared/computedValue.js +191 -0
  367. package/dist/shared/connection.d.ts +30 -0
  368. package/dist/shared/connection.js +1 -0
  369. package/dist/shared/csv.d.ts +20 -0
  370. package/dist/shared/csv.js +63 -0
  371. package/dist/shared/dashLayout.d.ts +30 -0
  372. package/dist/shared/dashLayout.js +132 -0
  373. package/dist/shared/dashboardAsks.d.ts +93 -0
  374. package/dist/shared/dashboardAsks.js +129 -0
  375. package/dist/shared/dashboardTrend.d.ts +20 -0
  376. package/dist/shared/dashboardTrend.js +50 -0
  377. package/dist/shared/decimals.d.ts +37 -0
  378. package/dist/shared/decimals.js +148 -0
  379. package/dist/shared/declaredReferences.d.ts +50 -0
  380. package/dist/shared/declaredReferences.js +202 -0
  381. package/dist/shared/definedFields.d.ts +63 -0
  382. package/dist/shared/definedFields.js +103 -0
  383. package/dist/shared/definedValues.d.ts +63 -0
  384. package/dist/shared/definedValues.js +184 -0
  385. package/dist/shared/displayDefaults.d.ts +135 -0
  386. package/dist/shared/displayDefaults.js +543 -0
  387. package/dist/shared/dueDate.d.ts +6 -0
  388. package/dist/shared/dueDate.js +6 -0
  389. package/dist/shared/duration.d.ts +4 -0
  390. package/dist/shared/duration.js +23 -0
  391. package/dist/shared/fileBounds.d.ts +9 -0
  392. package/dist/shared/fileBounds.js +9 -0
  393. package/dist/shared/filter.d.ts +238 -0
  394. package/dist/shared/filter.js +332 -0
  395. package/dist/shared/firstPaint.d.ts +24 -0
  396. package/dist/shared/firstPaint.js +33 -0
  397. package/dist/shared/form.d.ts +21 -0
  398. package/dist/shared/form.js +25 -0
  399. package/dist/shared/formValues.d.ts +104 -0
  400. package/dist/shared/formValues.js +352 -0
  401. package/dist/shared/funnel.d.ts +45 -0
  402. package/dist/shared/funnel.js +108 -0
  403. package/dist/shared/httpOperations.d.ts +48 -0
  404. package/dist/shared/httpOperations.js +9 -0
  405. package/dist/shared/iconGlyphs.d.ts +4 -0
  406. package/dist/shared/iconGlyphs.js +151 -0
  407. package/dist/shared/iconWeights.d.ts +3 -0
  408. package/dist/shared/iconWeights.js +162 -0
  409. package/dist/shared/imageWidths.d.ts +32 -0
  410. package/dist/shared/imageWidths.js +38 -0
  411. package/dist/shared/keysetPage.d.ts +64 -0
  412. package/dist/shared/keysetPage.js +161 -0
  413. package/dist/shared/like.d.ts +20 -0
  414. package/dist/shared/like.js +29 -0
  415. package/dist/shared/listEmpty.d.ts +12 -0
  416. package/dist/shared/listEmpty.js +36 -0
  417. package/dist/shared/listFilters.d.ts +28 -0
  418. package/dist/shared/listFilters.js +84 -0
  419. package/dist/shared/listPresentations.d.ts +199 -0
  420. package/dist/shared/listPresentations.js +7 -0
  421. package/dist/shared/listQuestion.d.ts +52 -0
  422. package/dist/shared/listQuestion.js +137 -0
  423. package/dist/shared/lookPalettes.d.ts +62 -0
  424. package/dist/shared/lookPalettes.js +306 -0
  425. package/dist/shared/maskQuoted.d.ts +24 -0
  426. package/dist/shared/maskQuoted.js +48 -0
  427. package/dist/shared/mentionLabel.d.ts +19 -0
  428. package/dist/shared/mentionLabel.js +38 -0
  429. package/dist/shared/mentionLookup.d.ts +17 -0
  430. package/dist/shared/mentionLookup.js +64 -0
  431. package/dist/shared/menuCounts.d.ts +16 -0
  432. package/dist/shared/menuCounts.js +74 -0
  433. package/dist/shared/model.d.ts +79 -0
  434. package/dist/shared/model.js +153 -0
  435. package/dist/shared/money.d.ts +53 -0
  436. package/dist/shared/money.js +98 -0
  437. package/dist/shared/moneyEntry.d.ts +7 -0
  438. package/dist/shared/moneyEntry.js +27 -0
  439. package/dist/shared/mount.d.ts +118 -0
  440. package/dist/shared/mount.js +248 -0
  441. package/dist/shared/niceTicks.d.ts +26 -0
  442. package/dist/shared/niceTicks.js +50 -0
  443. package/dist/shared/order.d.ts +59 -0
  444. package/dist/shared/order.js +133 -0
  445. package/dist/shared/page.d.ts +135 -0
  446. package/dist/shared/page.js +1187 -0
  447. package/dist/shared/pageAnatomy.d.ts +99 -0
  448. package/dist/shared/pageAnatomy.js +370 -0
  449. package/dist/shared/pageConfig.d.ts +25 -0
  450. package/dist/shared/pageConfig.js +1308 -0
  451. package/dist/shared/pageEmptyActions.d.ts +12 -0
  452. package/dist/shared/pageEmptyActions.js +20 -0
  453. package/dist/shared/pageLayouts.d.ts +72 -0
  454. package/dist/shared/pageLayouts.js +205 -0
  455. package/dist/shared/pageModel.d.ts +785 -0
  456. package/dist/shared/pageModel.js +121 -0
  457. package/dist/shared/pagePaths.d.ts +180 -0
  458. package/dist/shared/pagePaths.js +869 -0
  459. package/dist/shared/pagePlans.d.ts +52 -0
  460. package/dist/shared/pagePlans.js +108 -0
  461. package/dist/shared/pageRoutes.d.ts +9 -0
  462. package/dist/shared/pageRoutes.js +9 -0
  463. package/dist/shared/query.d.ts +166 -0
  464. package/dist/shared/query.js +1302 -0
  465. package/dist/shared/queryDates.d.ts +12 -0
  466. package/dist/shared/queryDates.js +101 -0
  467. package/dist/shared/queryOperands.d.ts +99 -0
  468. package/dist/shared/queryOperands.js +131 -0
  469. package/dist/shared/reads.d.ts +103 -0
  470. package/dist/shared/reads.js +154 -0
  471. package/dist/shared/recordLabel.d.ts +51 -0
  472. package/dist/shared/recordLabel.js +123 -0
  473. package/dist/shared/recordReadKeys.d.ts +30 -0
  474. package/dist/shared/recordReadKeys.js +51 -0
  475. package/dist/shared/recordReads.d.ts +268 -0
  476. package/dist/shared/recordReads.js +368 -0
  477. package/dist/shared/recordview.d.ts +198 -0
  478. package/dist/shared/recordview.js +356 -0
  479. package/dist/shared/referenceModel.d.ts +58 -0
  480. package/dist/shared/referenceModel.js +194 -0
  481. package/dist/shared/refusal.d.ts +80 -0
  482. package/dist/shared/refusal.js +184 -0
  483. package/dist/shared/relatedCreate.d.ts +30 -0
  484. package/dist/shared/relatedCreate.js +162 -0
  485. package/dist/shared/resourceHttp.d.ts +464 -0
  486. package/dist/shared/resourceHttp.js +1 -0
  487. package/dist/shared/richText.d.ts +85 -0
  488. package/dist/shared/richText.js +305 -0
  489. package/dist/shared/rollups.d.ts +143 -0
  490. package/dist/shared/rollups.js +64 -0
  491. package/dist/shared/rowScope.d.ts +72 -0
  492. package/dist/shared/rowScope.js +376 -0
  493. package/dist/shared/runtimeTables.d.ts +44 -0
  494. package/dist/shared/runtimeTables.js +79 -0
  495. package/dist/shared/schema.d.ts +529 -0
  496. package/dist/shared/schema.js +627 -0
  497. package/dist/shared/schematext.d.ts +38 -0
  498. package/dist/shared/schematext.js +101 -0
  499. package/dist/shared/scopeCatalog.d.ts +29 -0
  500. package/dist/shared/scopeCatalog.js +472 -0
  501. package/dist/shared/servedApp.d.ts +686 -0
  502. package/dist/shared/servedApp.js +45 -0
  503. package/dist/shared/sessionLease.d.ts +34 -0
  504. package/dist/shared/sessionLease.js +3 -0
  505. package/dist/shared/shape.d.ts +55 -0
  506. package/dist/shared/shape.js +168 -0
  507. package/dist/shared/slug.d.ts +1 -0
  508. package/dist/shared/slug.js +12 -0
  509. package/dist/shared/sortText.d.ts +14 -0
  510. package/dist/shared/sortText.js +26 -0
  511. package/dist/shared/sqlRelation.d.ts +4 -0
  512. package/dist/shared/sqlRelation.js +8 -0
  513. package/dist/shared/sqlsaved.d.ts +44 -0
  514. package/dist/shared/sqlsaved.js +63 -0
  515. package/dist/shared/stitchedPaths.d.ts +27 -0
  516. package/dist/shared/stitchedPaths.js +38 -0
  517. package/dist/shared/structuredFilter.d.ts +22 -0
  518. package/dist/shared/structuredFilter.js +1 -0
  519. package/dist/shared/subtitlePath.d.ts +20 -0
  520. package/dist/shared/subtitlePath.js +24 -0
  521. package/dist/shared/suggest.d.ts +18 -0
  522. package/dist/shared/suggest.js +59 -0
  523. package/dist/shared/tableSizing.d.ts +4 -0
  524. package/dist/shared/tableSizing.js +9 -0
  525. package/dist/shared/tagLists.d.ts +57 -0
  526. package/dist/shared/tagLists.js +34 -0
  527. package/dist/shared/textRules.d.ts +54 -0
  528. package/dist/shared/textRules.js +133 -0
  529. package/dist/shared/theme.d.ts +94 -0
  530. package/dist/shared/theme.js +800 -0
  531. package/dist/shared/themeColor.d.ts +34 -0
  532. package/dist/shared/themeColor.js +109 -0
  533. package/dist/shared/themeFaces.d.ts +30 -0
  534. package/dist/shared/themeFaces.js +42 -0
  535. package/dist/shared/themeInk.d.ts +20 -0
  536. package/dist/shared/themeInk.js +52 -0
  537. package/dist/shared/themeLooks.d.ts +9 -0
  538. package/dist/shared/themeLooks.js +572 -0
  539. package/dist/shared/themeParts.d.ts +26 -0
  540. package/dist/shared/themeParts.js +71 -0
  541. package/dist/shared/themePartsCheck.d.ts +21 -0
  542. package/dist/shared/themePartsCheck.js +91 -0
  543. package/dist/shared/themePresets.d.ts +85 -0
  544. package/dist/shared/themePresets.js +139 -0
  545. package/dist/shared/themeRecipeWords.d.ts +156 -0
  546. package/dist/shared/themeRecipeWords.js +156 -0
  547. package/dist/shared/themeRecipes.d.ts +213 -0
  548. package/dist/shared/themeRecipes.js +234 -0
  549. package/dist/shared/themeResolve.d.ts +55 -0
  550. package/dist/shared/themeResolve.js +52 -0
  551. package/dist/shared/themeTokens.d.ts +107 -0
  552. package/dist/shared/themeTokens.js +116 -0
  553. package/dist/shared/themeType.d.ts +38 -0
  554. package/dist/shared/themeType.js +205 -0
  555. package/dist/shared/unitWord.d.ts +4 -0
  556. package/dist/shared/unitWord.js +37 -0
  557. package/dist/shared/view.d.ts +195 -0
  558. package/dist/shared/view.js +987 -0
  559. package/dist/shared/viewLabels.d.ts +47 -0
  560. package/dist/shared/viewLabels.js +459 -0
  561. package/dist/shared/viewPaths.d.ts +248 -0
  562. package/dist/shared/viewPaths.js +294 -0
  563. package/dist/shared/viewtext.d.ts +57 -0
  564. package/dist/shared/viewtext.js +282 -0
  565. package/dist/shared/vocabulary.d.ts +71 -0
  566. package/dist/shared/vocabulary.js +249 -0
  567. package/dist/shared/weekStart.d.ts +7 -0
  568. package/dist/shared/weekStart.js +36 -0
  569. package/mark.svg +1 -0
  570. package/package.json +266 -3
  571. package/schema/model.d.ts +298 -0
  572. package/schema/theme.d.ts +587 -0
@@ -0,0 +1,1545 @@
1
+ /**
2
+ * A PostgreSQL trigger read from the catalog: the writes that fire it, and
3
+ * whether it is validation-only (scopeTriggers.ts).
4
+ *
5
+ * Which writes fire it is the catalog's own answer: `tgtype` says INSERT,
6
+ * UPDATE and DELETE, `tgattr` the `UPDATE OF` columns. A WHEN clause narrows
7
+ * when it fires, never which writes may; a trigger with one still counts.
8
+ *
9
+ * Validation-only has to be proven of the function the trigger runs, and
10
+ * PostgreSQL keeps a PL/pgSQL body only as text (`prosrc`). The proof has two
11
+ * halves, and only the first is read here:
12
+ *
13
+ * - the statements, by a grammar, which is narrow: the trigger FOR EACH ROW,
14
+ * not a constraint trigger (a deferred one runs at COMMIT, past every
15
+ * check), no transition tables; the function LANGUAGE plpgsql, no SECURITY
16
+ * DEFINER, no SET clause, no arguments, and a body that is exactly
17
+ *
18
+ * BEGIN
19
+ * IF <condition> THEN RAISE EXCEPTION '<literal>' [USING …]; END IF; …
20
+ * RETURN NEW;
21
+ * END
22
+ *
23
+ * with IF/ELSIF/ELSE nesting, `RAISE [EXCEPTION] '<literal>' [USING <option>
24
+ * = '<literal>', …]`, `NULL;` and one RETURN (NEW for a BEFORE INSERT or
25
+ * UPDATE, OLD for a BEFORE DELETE, any of NEW, OLD or NULL after). No
26
+ * DECLARE, no assignment (writing NEW is writing the row, past the checks
27
+ * on what the write set), no PERFORM, EXECUTE, SELECT, INSERT, UPDATE or
28
+ * DELETE.
29
+ * - the conditions, by PostgreSQL. Which function an operator, a call or an
30
+ * implicit cast runs is chosen by argument types, against every function,
31
+ * operator and cast the database holds, under the session's search_path:
32
+ * re-implementing that in JavaScript is how a review found `NEW.n <U+00A0>
33
+ * lower(…)`, an implicit cast of a literal through someone's function, and
34
+ * citext's `<` refusing a trigger on an integer. So each condition is
35
+ * handed, exactly as PL/pgSQL would cut it from the body, to PostgreSQL
36
+ * itself — in a temporary view selecting it over the trigger's table as
37
+ * `"new"` and `"old"`, made and dropped inside a savepoint on the very
38
+ * session that will write — and the expression tree it stores is judged as
39
+ * a WHEN clause's stored tree (`tgqual`) is: node kinds that cannot read a
40
+ * table, coerce through a type's own code or run a domain's checks; every
41
+ * function and operator immutable and either the database's own (an oid
42
+ * below FirstNormalObjectId) or C a superuser installed (an extension's,
43
+ * such as citext's); a boolean result.
44
+ *
45
+ * What the view sees differs from what PL/pgSQL runs in two ways, both
46
+ * chosen: a string literal becomes NULL and TG_OP `(NULL::text)`. Both
47
+ * resolve as the literal does — an untyped constant, chosen by the type of
48
+ * what it meets — but NULL runs no type input function while the view is
49
+ * made, so nothing in a domain's CHECK runs on the writer to prove it. The
50
+ * lexer that cuts the conditions is PostgreSQL's to the character (its six
51
+ * whitespace characters, its comments, its quoting), and anything it does
52
+ * not read the same way — a character past ASCII outside a literal, a `$`, a
53
+ * backslash string, a cast, a subscript — is not proven: those are the
54
+ * places where a different reading would hide a call (`::` is refused
55
+ * because a cast of a literal names a type whose input runs at parse time,
56
+ * where NULL would run none).
57
+ *
58
+ * The keyed-effect grammar (docs/trigger-effects.md) adds these statements,
59
+ * each with a schema-qualified table — an unqualified one resolves through the
60
+ * search_path the function runs with, where a schema the caller controls (or
61
+ * pg_temp, searched first for tables) could put a table of the same name:
62
+ *
63
+ * UPDATE <schema>.<table> SET <column> = <expression>, … WHERE <key> = NEW.<column> [AND …];
64
+ * INSERT INTO <schema>.<table> (<column>, …) VALUES (<expression>, …);
65
+ * DELETE FROM <schema>.<table> WHERE <key> = OLD.<column> [AND …];
66
+ *
67
+ * and, in an IF's condition, a keyed read `(SELECT <column> FROM
68
+ * <schema>.<table> WHERE <key> = NEW.<column> …)`. Their shape — which table,
69
+ * which key, which columns — is read here; every expression in them is
70
+ * PostgreSQL's to judge, in the same view as the conditions and by the same
71
+ * rules. A keyed read goes in as itself; an update's key and each of its
72
+ * values as a scalar subquery over the table it names, so that a bare name is
73
+ * that table's column, as it is in the statement. One rule is added: a value
74
+ * that is not a bare literal has the column's type, or reaches it by a cast
75
+ * of the database's own or a binary one, since an assignment cast runs the
76
+ * cast's function. CURRENT_DATE, CURRENT_TIMESTAMP and LOCALTIMESTAMP are
77
+ * keywords, not functions a search_path could shadow, and go in as a NULL of
78
+ * their type.
79
+ *
80
+ * The verdict is only as old as what it was made from. A function can be
81
+ * replaced without a lock on the table (CREATE OR REPLACE FUNCTION), and a new
82
+ * function, operator or cast can change what a condition resolves to. So the
83
+ * proof keeps the versions it was made from — the trigger function's row
84
+ * version, and those of every function, operator and cast a user made — and a
85
+ * transaction that relied on it reads them again before COMMIT
86
+ * (attestPostgresTriggers): anything changed while the write ran refuses it.
87
+ */
88
+ import { createHash } from 'node:crypto';
89
+ import { PLAIN, plainDefinition, } from './scopeTriggers.js';
90
+ /** Oids below this are the database's own (FirstNormalObjectId): made by initdb, never by a user. */
91
+ const FIRST_NORMAL_OID = 16384;
92
+ /*
93
+ * The operators the proof's own catalog reads compare by, named in pg_catalog. An operator is found through the
94
+ * search_path like a table is, and one of the same argument types in a schema ahead of pg_catalog wins: with
95
+ * `public, pg_catalog`, `CREATE OPERATOR public.= (leftarg = oid, rightarg = oid, function = oidne)` would turn
96
+ * every `=` here into its opposite. The key operators the proof accepts are judged by what they are, not their
97
+ * name (keyOperators below); these are the proof's own. Functions and types here are named in pg_catalog too.
98
+ */
99
+ const EQ = 'OPERATOR(pg_catalog.=)';
100
+ const NE = 'OPERATOR(pg_catalog.<>)';
101
+ const LT = 'OPERATOR(pg_catalog.<)';
102
+ const GT = 'OPERATOR(pg_catalog.>)';
103
+ const PLUS = 'OPERATOR(pg_catalog.+)';
104
+ export const CATALOG_OPERATORS = { EQ, NE, LT, GT, PLUS };
105
+ /** B-tree's access method (pg_am.dat): fixed by the server's source, the same in every database. */
106
+ const BTREE = '403::pg_catalog.oid';
107
+ /**
108
+ * A type with its domains unwrapped, and the type modifier of the last one that has one (a domain over varchar(3)
109
+ * compares as varchar(3)), as a subquery of `(type, typmod)` over the type and modifier expressions given.
110
+ */
111
+ export const baseType = (type, typmod) => `(WITH RECURSIVE d(type, typmod, depth) AS (
112
+ SELECT ${type}, ${typmod}, 0
113
+ UNION ALL
114
+ SELECT t.typbasetype, CASE WHEN t.typtypmod ${NE} -1 THEN t.typtypmod ELSE d.typmod END, d.depth ${PLUS} 1
115
+ FROM d JOIN pg_catalog.pg_type t ON t.oid ${EQ} d.type WHERE t.typtype ${EQ} 'd' AND d.depth ${LT} 32)
116
+ SELECT d.type, d.typmod FROM d ORDER BY depth DESC LIMIT 1)`;
117
+ /**
118
+ * The default B-tree operator class of a (base) type, as a scalar subquery: its own, or the one class a binary cast
119
+ * from it (varchar to text), an enum or an array reaches; NULL where there is none or more than one. What an index
120
+ * of the type is built with unless it says otherwise, and so what its equality means.
121
+ */
122
+ export const defaultBtreeClass = (type) => `(SELECT coalesce(
123
+ (SELECT oc.oid FROM pg_catalog.pg_opclass oc
124
+ WHERE oc.opcmethod ${EQ} ${BTREE} AND oc.opcdefault AND oc.opcintype ${EQ} ${type}),
125
+ (SELECT pg_catalog.min(oc.oid) FROM pg_catalog.pg_opclass oc JOIN pg_catalog.pg_type bt ON bt.oid ${EQ} ${type}
126
+ WHERE oc.opcmethod ${EQ} ${BTREE} AND oc.opcdefault
127
+ AND (EXISTS (SELECT 1 FROM pg_catalog.pg_cast c
128
+ WHERE c.castsource ${EQ} ${type} AND c.casttarget ${EQ} oc.opcintype AND c.castmethod ${EQ} 'b')
129
+ OR (oc.opcintype ${EQ} 'pg_catalog.anyenum'::pg_catalog.regtype AND bt.typtype ${EQ} 'e')
130
+ OR (oc.opcintype ${EQ} 'pg_catalog.anyarray'::pg_catalog.regtype AND bt.typcategory ${EQ} 'A'))
131
+ HAVING pg_catalog.count(*) ${EQ} 1)))`;
132
+ /*
133
+ * Every function, operator and type the catalog reads below name is named in pg_catalog, as the proof's own reads
134
+ * are (EQ above): one of those the search_path finds first can be anyone's. An exact signature in pg_catalog wins
135
+ * over the search_path only where pg_catalog is searched first, and a polymorphic one (cardinality(anyarray),
136
+ * array_agg(anynonarray), to_jsonb(anyelement), format(text, VARIADIC "any"), anyarray || anyarray) loses to an
137
+ * exact one anywhere on the path: `CREATE FUNCTION public.cardinality(text[])` by a role with nothing but CREATE on
138
+ * public made every table's triggers read as none, and a scoped write fire them unproven.
139
+ */
140
+ const CAT = 'OPERATOR(pg_catalog.||)';
141
+ const NOT_LIKE = 'OPERATOR(pg_catalog.!~)';
142
+ const GE = 'OPERATOR(pg_catalog.>=)';
143
+ const JSON_TEXT = 'OPERATOR(pg_catalog.->>)';
144
+ /** The versions of everything a user made that decides what a condition resolves to: functions, operators, casts. */
145
+ const AROUND = `(SELECT pg_catalog.md5(coalesce(pg_catalog.string_agg(f.oid::pg_catalog.text ${CAT} ':' ${CAT} f.xmin::pg_catalog.text, ',' ORDER BY f.oid), ''))
146
+ FROM pg_catalog.pg_proc f WHERE f.oid ${GE} ${FIRST_NORMAL_OID}::pg_catalog.oid)
147
+ ${CAT} (SELECT pg_catalog.md5(coalesce(pg_catalog.string_agg(o.oid::pg_catalog.text ${CAT} ':' ${CAT} o.xmin::pg_catalog.text, ',' ORDER BY o.oid), ''))
148
+ FROM pg_catalog.pg_operator o WHERE o.oid ${GE} ${FIRST_NORMAL_OID}::pg_catalog.oid)
149
+ ${CAT} (SELECT pg_catalog.md5(coalesce(pg_catalog.string_agg(k.oid::pg_catalog.text ${CAT} ':' ${CAT} k.xmin::pg_catalog.text, ',' ORDER BY k.oid), ''))
150
+ FROM pg_catalog.pg_cast k WHERE k.oid ${GE} ${FIRST_NORMAL_OID}::pg_catalog.oid)`;
151
+ /**
152
+ * The relations a write to `root` (an oid expression) may reach, itself first: its partitions and inheritance
153
+ * children, to any depth. A write through a partitioned table lands in a leaf, and an update or delete through an
154
+ * inheritance parent reaches its children's rows; each fires its own triggers.
155
+ */
156
+ const tree = (root) => `WITH RECURSIVE tree(relid) AS (
157
+ SELECT ${root} UNION SELECT i.inhrelid FROM tree JOIN pg_catalog.pg_inherits i ON i.inhparent ${EQ} tree.relid)`;
158
+ /**
159
+ * Whether trigger `t` is one of a write to `root`'s own, rather than a clone a partition keeps of a trigger on a
160
+ * relation in the same tree (`tgparentid`, PostgreSQL 13 and later; earlier, clones are internal), which is
161
+ * judged once, where it was made. Read through to_jsonb so a server without the column reads none.
162
+ */
163
+ const own = (t) => `NOT ${t}.tgisinternal AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_trigger parent
164
+ WHERE parent.oid ${EQ} coalesce((pg_catalog.to_jsonb(${t}) ${JSON_TEXT} 'tgparentid')::pg_catalog.oid, 0::pg_catalog.oid)
165
+ AND parent.tgrelid ${EQ} ANY (SELECT relid FROM tree))`;
166
+ /** A trigger's name as a refusal says it: its own, or `relation.name` when it is on a partition or child. */
167
+ const named = (t, root, relation) => `CASE WHEN ${t}.tgrelid ${EQ} ${root} THEN ${t}.tgname::pg_catalog.text ELSE ${relation}.relname::pg_catalog.text ${CAT} '.' ${CAT} ${t}.tgname::pg_catalog.text END`;
168
+ /** The names of the triggers a write to `root` (an oid expression) may fire, sorted: what the scope catalog's facts count. */
169
+ export const postgresTreeTriggerNames = (root) => `(${tree(root)}
170
+ SELECT coalesce(pg_catalog.array_agg(fired.name ORDER BY fired.name), '{}'::pg_catalog.text[]) FROM (
171
+ SELECT ${named('t', root, 'k')} AS name FROM tree
172
+ JOIN pg_catalog.pg_trigger t ON t.tgrelid ${EQ} tree.relid JOIN pg_catalog.pg_class k ON k.oid ${EQ} t.tgrelid
173
+ WHERE ${own('t')}) AS fired)`;
174
+ /**
175
+ * Every user trigger a write to a table may fire, with what the proof reads: the table's own and each of its
176
+ * partitions' and children's, keyed by the table written. `wanted` reads those of the tables named by `$1`
177
+ * (schemas) and `$2` (names); otherwise every ordinary or partitioned table outside the system's schemas, with no
178
+ * parameters (for `mistri check`).
179
+ */
180
+ export function postgresTriggerStatement(wanted) {
181
+ const filter = wanted
182
+ ? `EXISTS (SELECT 1 FROM ROWS FROM (pg_catalog.unnest($1::pg_catalog.text[]), pg_catalog.unnest($2::pg_catalog.text[])) AS w(schema, name)
183
+ WHERE n.nspname ${EQ} w.schema AND r.relname ${EQ} w.name)`
184
+ : `r.relkind ${EQ} ANY (ARRAY['r', 'p']::pg_catalog."char"[])
185
+ AND n.nspname::pg_catalog.text ${NE} ALL (ARRAY['pg_catalog', 'information_schema']::pg_catalog.text[])
186
+ AND n.nspname::pg_catalog.text ${NOT_LIKE} '^pg_(toast_)?temp_'`;
187
+ return `WITH around AS MATERIALIZED (SELECT ${AROUND} AS around)
188
+ SELECT n.nspname::pg_catalog.text AS schema, r.relname::pg_catalog.text AS "table",
189
+ pg_catalog.format('%I.%I', cn.nspname, c.relname) AS relation,
190
+ fired.name, t.tgtype::pg_catalog.int4 AS type,
191
+ ARRAY(SELECT a.attname::pg_catalog.text FROM pg_catalog.unnest(t.tgattr::pg_catalog.int2[]) WITH ORDINALITY AS k(attnum, ord)
192
+ JOIN pg_catalog.pg_attribute a ON a.attrelid ${EQ} c.oid AND a.attnum ${EQ} k.attnum ORDER BY k.ord) AS columns,
193
+ pg_catalog.cardinality(t.tgattr::pg_catalog.int2[]) AS listed,
194
+ EXISTS (SELECT 1 FROM pg_catalog.unnest(t.tgattr::pg_catalog.int2[]) AS k(attnum)
195
+ JOIN pg_catalog.pg_attribute a ON a.attrelid ${EQ} c.oid AND a.attnum ${EQ} k.attnum WHERE a.attgenerated ${NE} '') AS generated,
196
+ t.tgconstraint ${NE} 0::pg_catalog.oid AS "constraint",
197
+ (t.tgoldtable IS NOT NULL OR t.tgnewtable IS NOT NULL) AS transition,
198
+ coalesce(t.tgqual::pg_catalog.text, '') AS qual,
199
+ l.lanname::pg_catalog.text AS language, p.prokind::pg_catalog.text AS kind, p.prosecdef AS definer,
200
+ p.proconfig IS NOT NULL AS configured, p.pronargs::pg_catalog.int4 AS arguments, p.prosrc AS source,
201
+ p.oid::pg_catalog.text ${CAT} ':' ${CAT} p.xmin::pg_catalog.text AS version,
202
+ around.around
203
+ FROM pg_catalog.pg_class r
204
+ JOIN pg_catalog.pg_namespace n ON n.oid ${EQ} r.relnamespace
205
+ CROSS JOIN LATERAL (${tree('r.oid')}
206
+ SELECT t.oid, ${named('t', 'r.oid', 'k')} AS name FROM tree
207
+ JOIN pg_catalog.pg_trigger t ON t.tgrelid ${EQ} tree.relid JOIN pg_catalog.pg_class k ON k.oid ${EQ} t.tgrelid
208
+ WHERE ${own('t')}) AS fired
209
+ JOIN pg_catalog.pg_trigger t ON t.oid ${EQ} fired.oid
210
+ JOIN pg_catalog.pg_class c ON c.oid ${EQ} t.tgrelid
211
+ JOIN pg_catalog.pg_namespace cn ON cn.oid ${EQ} c.relnamespace
212
+ JOIN pg_catalog.pg_proc p ON p.oid ${EQ} t.tgfoid
213
+ JOIN pg_catalog.pg_language l ON l.oid ${EQ} p.prolang
214
+ CROSS JOIN around
215
+ WHERE ${filter}
216
+ ORDER BY 1, 2, 4`;
217
+ }
218
+ /** Whether a row has the shape the statement answers; anything else is a catalog this code does not know. */
219
+ function isPostgresTriggerRow(row) {
220
+ if (!row || typeof row !== 'object')
221
+ return false;
222
+ const r = row;
223
+ const strings = ['schema', 'table', 'relation', 'name', 'qual', 'language', 'kind', 'source', 'version', 'around'];
224
+ const booleans = ['generated', 'constraint', 'transition', 'definer', 'configured'];
225
+ const numbers = ['type', 'listed', 'arguments'];
226
+ return (strings.every((key) => typeof r[key] === 'string') &&
227
+ booleans.every((key) => typeof r[key] === 'boolean') &&
228
+ numbers.every((key) => Number.isInteger(r[key])) &&
229
+ Array.isArray(r.columns) &&
230
+ r.columns.every((column) => typeof column === 'string'));
231
+ }
232
+ /** What a trigger's proof was made from: changes to any of it change this. */
233
+ const triggerVersion = (row) => `${row.name}=${row.version}/${row.around}`;
234
+ // pg_trigger.tgtype bits (catalog/pg_trigger.h).
235
+ const ROW = 1 << 0;
236
+ const BEFORE = 1 << 1;
237
+ const INSERT = 1 << 2;
238
+ const DELETE = 1 << 3;
239
+ const UPDATE = 1 << 4;
240
+ const INSTEAD = 1 << 6;
241
+ /** The expression nodes a condition may hold: nothing that reads a table, coerces through a type's own code or runs a domain's checks. */
242
+ const EXPRESSION_NODES = new Set([
243
+ 'OPEXPR',
244
+ 'VAR',
245
+ 'CONST',
246
+ 'BOOLEXPR',
247
+ 'NULLTEST',
248
+ 'BOOLEANTEST',
249
+ 'RELABELTYPE',
250
+ 'SCALARARRAYOPEXPR',
251
+ 'DISTINCTEXPR',
252
+ 'NULLIFEXPR',
253
+ 'CASEEXPR',
254
+ 'CASEWHEN',
255
+ 'CASETESTEXPR',
256
+ 'COALESCEEXPR',
257
+ 'FUNCEXPR',
258
+ 'ARRAYEXPR',
259
+ ]);
260
+ /** What the view selecting the conditions adds around them: one query over the trigger's table twice. */
261
+ const VIEW_NODES = new Set([
262
+ ...EXPRESSION_NODES,
263
+ 'QUERY',
264
+ 'RANGETBLENTRY',
265
+ 'ALIAS',
266
+ 'RTEPERMISSIONINFO',
267
+ 'FROMEXPR',
268
+ 'RANGETBLREF',
269
+ 'TARGETENTRY',
270
+ ]);
271
+ /**
272
+ * What one key equality, alone in a scalar subquery over its table, may parse to: the view and the subquery around
273
+ * it, the operator, the two columns, the subquery's `true`, and a relabel (a domain to its base type, varchar to
274
+ * text), which changes no value. A cast or a conversion of either side (`char(3)` to text drops trailing spaces,
275
+ * int8 to float8 rounds) would compare a value other than the one the proof reads the row by.
276
+ */
277
+ const KEY_NODES = new Set([
278
+ 'QUERY',
279
+ 'RANGETBLENTRY',
280
+ 'ALIAS',
281
+ 'RTEPERMISSIONINFO',
282
+ 'FROMEXPR',
283
+ 'RANGETBLREF',
284
+ 'TARGETENTRY',
285
+ 'SUBLINK',
286
+ 'OPEXPR',
287
+ 'VAR',
288
+ 'CONST',
289
+ 'RELABELTYPE',
290
+ ]);
291
+ const KEY_CAST = "a key of it compares through a cast or a conversion of one side: a key's two sides must be columns of the same type";
292
+ const KEY_OPERATOR = "a key of it compares by an operator that is not its column's own equality (the equality of the type's default B-tree operator class): an `=` found first on the search_path can be any function";
293
+ /** The fields of a stored tree that name code it runs: a function, or an operator (whose function runs). */
294
+ const FUNCTION_FIELDS = new Set([':funcid', ':opfuncid', ':hashfuncid', ':negfuncid', ':aggfnoid', ':winfnoid']);
295
+ /**
296
+ * The tokens of a stored tree, as pg_strtok cuts them: `(`, `)`, `{` and `}`
297
+ * alone, anything else up to whitespace or one of those, a backslash taking
298
+ * the character after it. A name inside the tree (an alias, a column) is
299
+ * written with every such character escaped, so it can neither open a node
300
+ * nor end one.
301
+ */
302
+ function treeTokens(text) {
303
+ const tokens = [];
304
+ let i = 0;
305
+ while (i < text.length) {
306
+ const char = text[i];
307
+ if (char === ' ' || char === '\n' || char === '\t')
308
+ i += 1;
309
+ else if ('(){}'.includes(char)) {
310
+ tokens.push(char);
311
+ i += 1;
312
+ }
313
+ else {
314
+ let end = i;
315
+ while (end < text.length && !' \n\t(){}'.includes(text[end]))
316
+ end += text[end] === '\\' && end + 1 < text.length ? 2 : 1;
317
+ tokens.push(text.slice(i, end));
318
+ i = end;
319
+ }
320
+ }
321
+ return tokens;
322
+ }
323
+ /** A stored tree, read structurally: every node, and the functions and operators it names. Undefined when it is not one this reader knows. */
324
+ export function readPostgresTree(text) {
325
+ const tokens = treeTokens(text);
326
+ let at = 0;
327
+ const nodes = new Map();
328
+ const functions = new Set();
329
+ const operators = new Set();
330
+ const opexprs = [];
331
+ const domains = new Set();
332
+ const constants = new Set();
333
+ const oid = (token) => {
334
+ if (!token || !/^[0-9]+$/.test(token))
335
+ throw new Unproven();
336
+ return Number(token);
337
+ };
338
+ const value = () => {
339
+ const token = tokens[at++];
340
+ if (token === undefined || token === ')' || token === '}')
341
+ throw new Unproven();
342
+ if (token === '{')
343
+ node();
344
+ else if (token === '(') {
345
+ while (tokens[at] !== ')') {
346
+ if (at >= tokens.length)
347
+ throw new Unproven();
348
+ value();
349
+ }
350
+ at += 1;
351
+ }
352
+ };
353
+ const node = () => {
354
+ const name = tokens[at++];
355
+ if (!name || !/^[A-Z_]+$/.test(name))
356
+ throw new Unproven();
357
+ nodes.set(name, (nodes.get(name) ?? 0) + 1);
358
+ for (;;) {
359
+ const label = tokens[at++];
360
+ if (label === '}')
361
+ return;
362
+ if (!label?.startsWith(':'))
363
+ throw new Unproven();
364
+ if (label === ':constvalue' && tokens[at] !== '<>') {
365
+ // A datum: its length, then its bytes in brackets (readDatum).
366
+ oid(tokens[at++]);
367
+ if (tokens[at++] !== '[')
368
+ throw new Unproven();
369
+ while (tokens[at] !== ']') {
370
+ if (at >= tokens.length || !/^-?[0-9]+$/.test(tokens[at]))
371
+ throw new Unproven();
372
+ at += 1;
373
+ }
374
+ at += 1;
375
+ }
376
+ else if (FUNCTION_FIELDS.has(label)) {
377
+ const id = oid(tokens[at++]);
378
+ if (id)
379
+ functions.add(id);
380
+ }
381
+ else if (label === ':opno') {
382
+ const id = oid(tokens[at++]);
383
+ operators.add(id);
384
+ if (name === 'OPEXPR')
385
+ opexprs.push(id);
386
+ }
387
+ else if (label === ':opnos' && tokens[at] === '(') {
388
+ // A row comparison's operators, an oid list: `(o 96 97)`.
389
+ at += 1;
390
+ if (tokens[at++] !== 'o')
391
+ throw new Unproven();
392
+ while (tokens[at] !== ')')
393
+ operators.add(oid(tokens[at++]));
394
+ at += 1;
395
+ }
396
+ else if (label === ':resulttype' && name === 'COERCETODOMAIN')
397
+ domains.add(oid(tokens[at++]));
398
+ else if (label === ':consttype' && name === 'CONST')
399
+ constants.add(oid(tokens[at++]));
400
+ else
401
+ value();
402
+ }
403
+ };
404
+ try {
405
+ if (!text)
406
+ return { nodes, functions, operators, opexprs, domains, constants };
407
+ value();
408
+ if (at !== tokens.length)
409
+ return undefined;
410
+ return { nodes, functions, operators, opexprs, domains, constants };
411
+ }
412
+ catch (error) {
413
+ if (error instanceof Unproven)
414
+ return undefined;
415
+ throw error;
416
+ }
417
+ }
418
+ class Unproven extends Error {
419
+ }
420
+ const fail = () => {
421
+ throw new Unproven();
422
+ };
423
+ /** The operator spellings a condition may use: each one PostgreSQL's lexer also reads as one operator. */
424
+ const OPERATORS = new Set(['=', '<>', '!=', '<', '<=', '>', '>=', '+', '-', '*', '/', '%', '||']);
425
+ const OPERATOR_CHARS = '+-*/<>=~!@#%^&|`?';
426
+ /** PostgreSQL's whitespace (scan.l `space`), exactly: not Unicode's, which takes U+00A0 for a space PostgreSQL reads as a letter. */
427
+ const whitespace = (char) => char === ' ' || (char >= '\t' && char <= '\r');
428
+ const wide = (char) => char > '\x7f';
429
+ /**
430
+ * PL/pgSQL's tokens, as PostgreSQL's lexer cuts them, as far as the grammar
431
+ * reads them. Anything it would read differently refuses: a dollar quote or
432
+ * any `$`, `:=` or `::`, a backslash string or one with a prefix (E'', U&'',
433
+ * B'', X'', N''), a number running into a letter or a dot, a subscript, and
434
+ * a character past ASCII outside a literal or quoted name — each a place
435
+ * where a different reading would hide a token.
436
+ */
437
+ function tokenize(source) {
438
+ const tokens = [];
439
+ let i = 0;
440
+ while (i < source.length) {
441
+ const char = source[i];
442
+ const start = i;
443
+ if (whitespace(char)) {
444
+ i += 1;
445
+ }
446
+ else if (source.startsWith('--', i)) {
447
+ // A line comment ends at either newline character (scan.l `non_newline`).
448
+ while (i < source.length && source[i] !== '\n' && source[i] !== '\r')
449
+ i += 1;
450
+ }
451
+ else if (source.startsWith('/*', i)) {
452
+ // PostgreSQL nests block comments; one that holds another is refused rather than matched.
453
+ const end = source.indexOf('*/', i + 2);
454
+ if (end === -1 || source.slice(i + 2, end).includes('/*'))
455
+ return fail();
456
+ i = end + 2;
457
+ }
458
+ else if (char === "'") {
459
+ let end = i + 1;
460
+ for (;;) {
461
+ if (end >= source.length)
462
+ return fail();
463
+ if (source[end] === "'") {
464
+ if (source[end + 1] === "'") {
465
+ end += 2;
466
+ continue;
467
+ }
468
+ break;
469
+ }
470
+ // Where a backslash string ends depends on standard_conforming_strings: refused, not guessed.
471
+ if (source[end] === '\\')
472
+ return fail();
473
+ end += 1;
474
+ }
475
+ i = end + 1;
476
+ tokens.push({ kind: 'string', start, end: i });
477
+ }
478
+ else if (char === '"') {
479
+ let end = i + 1;
480
+ for (;;) {
481
+ if (end >= source.length)
482
+ return fail();
483
+ if (source[end] === '"') {
484
+ if (source[end + 1] === '"') {
485
+ end += 2;
486
+ continue;
487
+ }
488
+ break;
489
+ }
490
+ end += 1;
491
+ }
492
+ i = end + 1;
493
+ tokens.push({ kind: 'id', start, end: i });
494
+ }
495
+ else if (/[0-9]/.test(char) || (char === '.' && /[0-9]/.test(source[i + 1] ?? ''))) {
496
+ const match = /^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(source.slice(i));
497
+ i += match[0].length;
498
+ // `0x1F`, `1_000`, `1..2`: PostgreSQL's readings of these vary by version.
499
+ if (i < source.length && /[A-Za-z_0-9.]/.test(source[i]))
500
+ return fail();
501
+ tokens.push({ kind: 'number', start, end: i });
502
+ }
503
+ else if (/[A-Za-z_]/.test(char)) {
504
+ let end = i + 1;
505
+ while (end < source.length && /[A-Za-z0-9_]/.test(source[end]))
506
+ end += 1;
507
+ // A letter past ASCII or a `$` continues the name for PostgreSQL; `E'…'`, `U&'…'`, `B'…'` are strings with their own rules.
508
+ if (end < source.length && (wide(source[end]) || "$'&".includes(source[end])))
509
+ return fail();
510
+ tokens.push({ kind: 'word', upper: source.slice(i, end).toUpperCase(), start, end });
511
+ i = end;
512
+ }
513
+ else if (OPERATOR_CHARS.includes(char)) {
514
+ // The whole run of operator characters, as PostgreSQL's lexer takes it, must be one operator spelled here.
515
+ let end = i;
516
+ while (end < source.length && OPERATOR_CHARS.includes(source[end]) && !source.startsWith('--', end) && !source.startsWith('/*', end))
517
+ end += 1;
518
+ const text = source.slice(i, end);
519
+ if (!OPERATORS.has(text))
520
+ return fail();
521
+ tokens.push({ kind: 'op', text, start, end });
522
+ i = end;
523
+ }
524
+ else if ('(),;.'.includes(char)) {
525
+ tokens.push({ kind: 'op', text: char, start, end: i + 1 });
526
+ i += 1;
527
+ }
528
+ else {
529
+ // `$`, `:`, `[`, a character past ASCII, and anything else.
530
+ return fail();
531
+ }
532
+ }
533
+ return tokens;
534
+ }
535
+ class Cursor {
536
+ tokens;
537
+ source;
538
+ at = 0;
539
+ /** Each condition, as the SQL handed to PostgreSQL to parse; a keyed write's key is one too. */
540
+ conditions = [];
541
+ effects = [];
542
+ /** Each value a keyed write gives that is not a bare literal, as SQL to parse, with the column it is assigned to. */
543
+ values = [];
544
+ /** How many scalar subqueries the conditions and values hold: each a keyed read's or a keyed write's own. */
545
+ sublinks = 0;
546
+ /** Each equality of each key, alone, as a scalar subquery over its table: parsed apart, so its tree is its own. */
547
+ keys = [];
548
+ /** For each of `keys`, the table and the key column it compares. */
549
+ keyColumns = [];
550
+ constructor(tokens, source) {
551
+ this.tokens = tokens;
552
+ this.source = source;
553
+ }
554
+ word(offset = 0) {
555
+ const token = this.tokens[this.at + offset];
556
+ return token?.kind === 'word' ? token.upper : undefined;
557
+ }
558
+ op(offset = 0) {
559
+ const token = this.tokens[this.at + offset];
560
+ return token?.kind === 'op' ? token.text : undefined;
561
+ }
562
+ take() {
563
+ return this.tokens[this.at++] ?? fail();
564
+ }
565
+ expectWord(word) {
566
+ if (this.word() !== word)
567
+ fail();
568
+ this.at += 1;
569
+ }
570
+ expectOp(op) {
571
+ if (this.op() !== op)
572
+ fail();
573
+ this.at += 1;
574
+ }
575
+ text(token) {
576
+ return this.source.slice(token.start, token.end);
577
+ }
578
+ /** An identifier as PostgreSQL names it: a bare word folded to lower case, a quoted one exactly. */
579
+ name() {
580
+ const token = this.take();
581
+ if (token.kind === 'word')
582
+ return this.text(token).toLowerCase();
583
+ if (token.kind === 'id')
584
+ return this.text(token).slice(1, -1).replace(/""/g, '"');
585
+ return fail();
586
+ }
587
+ }
588
+ /**
589
+ * One condition, cut where PL/pgSQL cuts it (pl_gram.y read_sql_construct):
590
+ * at the first THEN outside every parenthesis — a CASE's THEN included, which
591
+ * PL/pgSQL reads as the IF's, so a CASE in a condition has to be in
592
+ * parentheses — and noted on the cursor as the SQL PostgreSQL will parse.
593
+ * Only what the parse cannot be trusted with is refused here: the row whole
594
+ * (`NEW`) rather than a column of it, a column's own field (`NEW.c.f`), a
595
+ * cast, a qualified name. Everything else — which operator, which function,
596
+ * whether it reads a table — is PostgreSQL's to say.
597
+ */
598
+ function condition(cursor) {
599
+ cursor.conditions.push(cut(cursor, (at) => at.word() === 'THEN', 'condition'));
600
+ }
601
+ /**
602
+ * One expression as the SQL PostgreSQL is to parse in its place, up to the
603
+ * first token `stop` accepts outside every parenthesis. In a condition, a
604
+ * keyed read goes in as itself; in a write's value, the clock keywords go in
605
+ * as a NULL of their type, and a function variable of PL/pgSQL's other than
606
+ * NEW, OLD and TG_OP, or a subquery, is refused.
607
+ */
608
+ function cut(cursor, stop, as) {
609
+ let depth = 0;
610
+ const parts = [];
611
+ for (;;) {
612
+ if (cursor.at >= cursor.tokens.length)
613
+ fail();
614
+ if (!depth && parts.length && stop(cursor))
615
+ break;
616
+ const token = cursor.take();
617
+ const text = cursor.source.slice(token.start, token.end);
618
+ if (token.kind === 'string') {
619
+ parts.push('NULL');
620
+ }
621
+ else if (token.kind === 'number' || token.kind === 'id') {
622
+ parts.push(text);
623
+ }
624
+ else if (token.kind === 'op') {
625
+ if (token.text === '(' && as === 'condition' && cursor.word() === 'SELECT') {
626
+ parts.push(keyedRead(cursor));
627
+ continue;
628
+ }
629
+ if (token.text === '(')
630
+ depth += 1;
631
+ else if (token.text === ')' && --depth < 0)
632
+ fail();
633
+ else if (token.text === '.' || token.text === ';')
634
+ fail();
635
+ parts.push(text);
636
+ }
637
+ else if (token.upper === 'NEW' || token.upper === 'OLD') {
638
+ cursor.expectOp('.');
639
+ const column = cursor.take();
640
+ // `NEW.then` is a column to SQL and the end of the condition to PL/pgSQL's lexer: not guessed.
641
+ if (column.kind === 'word' && column.upper === 'THEN')
642
+ fail();
643
+ if (column.kind !== 'word' && column.kind !== 'id')
644
+ fail();
645
+ // `NEW.col.field` reads into a composite through its type's own code.
646
+ if (cursor.op() === '.')
647
+ fail();
648
+ parts.push(`"${token.upper.toLowerCase()}".${cursor.source.slice(column.start, column.end)}`);
649
+ }
650
+ else if (token.upper === 'TG_OP') {
651
+ parts.push('(NULL::pg_catalog.text)');
652
+ }
653
+ else if (token.upper === 'CAST') {
654
+ // A literal cast to a type runs that type's input function when the condition is parsed: refused, as `::` is.
655
+ fail();
656
+ }
657
+ else if (as === 'value' && CLOCK.has(token.upper) && cursor.op() !== '(') {
658
+ parts.push(CLOCK.get(token.upper));
659
+ }
660
+ else if (as === 'value' && (token.upper === 'SELECT' || token.upper === 'FOUND' || token.upper.startsWith('TG_'))) {
661
+ fail();
662
+ }
663
+ else {
664
+ parts.push(text);
665
+ }
666
+ }
667
+ if (depth)
668
+ fail();
669
+ return parts.join(' ');
670
+ }
671
+ /** The clock keywords a write's value may give, each as the NULL of its type PostgreSQL parses in its place. */
672
+ const CLOCK = new Map([
673
+ ['CURRENT_DATE', '(NULL::pg_catalog.date)'],
674
+ ['CURRENT_TIMESTAMP', '(NULL::pg_catalog.timestamptz)'],
675
+ ['LOCALTIMESTAMP', '(NULL::pg_catalog."timestamp")'],
676
+ ]);
677
+ /** Words a bare key column can never be: SQL's own, and the names PL/pgSQL gives a trigger function's variables. */
678
+ const NOT_COLUMNS = new Set([
679
+ 'SELECT',
680
+ 'FROM',
681
+ 'WHERE',
682
+ 'AND',
683
+ 'OR',
684
+ 'NOT',
685
+ 'NULL',
686
+ 'TRUE',
687
+ 'FALSE',
688
+ 'NEW',
689
+ 'OLD',
690
+ 'FOUND',
691
+ 'SET',
692
+ 'VALUES',
693
+ ]);
694
+ /** A keyed effect's table, `<schema>.<table>` (an unqualified name would resolve through the function's search_path): its name and its SQL. */
695
+ function effectTable(cursor) {
696
+ const start = cursor.tokens[cursor.at] ?? fail();
697
+ const schema = cursor.name();
698
+ cursor.expectOp('.');
699
+ const table = cursor.name();
700
+ if (cursor.op() === '.')
701
+ fail();
702
+ return { name: `${schema}.${table}`, sql: `ONLY ${cursor.source.slice(start.start, cursor.tokens[cursor.at - 1].end)}` };
703
+ }
704
+ /** `<column> = NEW.<column>` (either way round), joined by AND, up to a token `end` accepts: the key, and its SQL. */
705
+ function keyEqualities(cursor, { name: table, sql: relation }, end) {
706
+ const key = {};
707
+ const parts = [];
708
+ const bare = table.slice(table.indexOf('.') + 1);
709
+ const side = () => {
710
+ const word = cursor.word();
711
+ if ((word === 'NEW' || word === 'OLD') && cursor.op(1) === '.') {
712
+ cursor.at += 2;
713
+ const column = cursor.take();
714
+ if (column.kind !== 'word' && column.kind !== 'id')
715
+ fail();
716
+ if (cursor.op() === '.')
717
+ fail();
718
+ const text = cursor.text(column);
719
+ // NEW's columns as PL/pgSQL names them: a bare word folded, a quoted one exact.
720
+ const name = column.kind === 'word' ? text.toLowerCase() : text.slice(1, -1).replace(/""/g, '"');
721
+ return { value: { row: word === 'NEW' ? 'new' : 'old', column: name }, sql: `"${word.toLowerCase()}".${text}` };
722
+ }
723
+ const start = cursor.tokens[cursor.at] ?? fail();
724
+ const first = cursor.name();
725
+ if (cursor.op() !== '.') {
726
+ // A bare key column is never one of PL/pgSQL's own variables, which would shadow it.
727
+ if (first.toUpperCase().startsWith('TG_') || NOT_COLUMNS.has(first.toUpperCase()))
728
+ fail();
729
+ return { value: first, sql: cursor.text(start) };
730
+ }
731
+ // `account.id`: the target itself, never another table.
732
+ if (first !== bare)
733
+ fail();
734
+ cursor.at += 1;
735
+ const name = cursor.name();
736
+ return { value: name, sql: cursor.source.slice(start.start, cursor.tokens[cursor.at - 1].end) };
737
+ };
738
+ for (;;) {
739
+ const left = side();
740
+ cursor.expectOp('=');
741
+ const right = side();
742
+ const column = typeof left.value === 'string' ? left.value : typeof right.value === 'string' ? right.value : fail();
743
+ const ref = typeof left.value === 'string' ? right.value : left.value;
744
+ if (typeof ref === 'string' || Object.hasOwn(key, column))
745
+ fail();
746
+ key[column] = ref;
747
+ parts.push(`${left.sql} = ${right.sql}`);
748
+ cursor.keys.push(`(SELECT true FROM ${relation} WHERE ${left.sql} = ${right.sql})`);
749
+ cursor.keyColumns.push({ relation: relation.slice('ONLY '.length), column });
750
+ if (end(cursor))
751
+ return { key, sql: parts.join(' AND ') };
752
+ cursor.expectWord('AND');
753
+ }
754
+ }
755
+ /** `SELECT <column> FROM <schema>.<table> WHERE <key> …)`, its opening parenthesis taken: noted, and the SQL that parses in its place. */
756
+ function keyedRead(cursor) {
757
+ cursor.expectWord('SELECT');
758
+ const start = cursor.tokens[cursor.at] ?? fail();
759
+ const read = cursor.name();
760
+ if (cursor.op() === '.' || cursor.op() === '(')
761
+ fail();
762
+ cursor.expectWord('FROM');
763
+ const table = effectTable(cursor);
764
+ cursor.expectWord('WHERE');
765
+ const { key, sql } = keyEqualities(cursor, table, (at) => at.op() === ')');
766
+ cursor.expectOp(')');
767
+ cursor.effects.push({ kind: 'read', table: table.name, key, values: { [read]: { literal: null } } });
768
+ cursor.sublinks += 1;
769
+ return `(SELECT ${cursor.text(start)} FROM ${table.sql} WHERE ${sql})`;
770
+ }
771
+ /** What a value's tokens are known to be before the trigger runs. */
772
+ function term(cursor, tokens) {
773
+ const [first, second, third] = tokens;
774
+ const text = (token) => cursor.text(token);
775
+ if (tokens.length === 3 && first.kind === 'word' && (first.upper === 'NEW' || first.upper === 'OLD') && second.kind === 'op') {
776
+ const column = third.kind === 'word' ? text(third).toLowerCase() : text(third).slice(1, -1).replace(/""/g, '"');
777
+ return { row: first.upper === 'NEW' ? 'new' : 'old', column };
778
+ }
779
+ if (tokens.length === 1 && first.kind === 'string')
780
+ return { literal: text(first).slice(1, -1).replace(/''/g, "'") };
781
+ if (tokens.length === 1 && first.kind === 'word' && first.upper === 'NULL')
782
+ return { literal: null };
783
+ if (tokens.length === 1 && first.kind === 'number' && /^[0-9]+$/.test(text(first)) && Number.isSafeInteger(Number(text(first))))
784
+ return { literal: Number(text(first)) };
785
+ return { expression: true };
786
+ }
787
+ /**
788
+ * One value a keyed write gives, cut and noted: what it is known to be. `over` is the target's SQL where a bare name
789
+ * in the value is that table's column (an update's SET).
790
+ */
791
+ function value(cursor, stop, table, column, over) {
792
+ const start = cursor.at;
793
+ const sql = cut(cursor, stop, 'value');
794
+ const known = term(cursor, cursor.tokens.slice(start, cursor.at));
795
+ // A bare literal is read by the column's own type; anything else is a value of a type of its own, assigned.
796
+ if (!('literal' in known)) {
797
+ cursor.values.push({ sql: over ? `(SELECT (${sql}) FROM ${over})` : sql, relation: table.sql.slice('ONLY '.length), column });
798
+ if (over)
799
+ cursor.sublinks += 1;
800
+ }
801
+ return known;
802
+ }
803
+ /** One keyed write statement, from its first word to (not past) its semicolon. */
804
+ function keyedWrite(cursor) {
805
+ const word = cursor.word();
806
+ cursor.at += 1;
807
+ if (word === 'UPDATE') {
808
+ const table = effectTable(cursor);
809
+ cursor.expectWord('SET');
810
+ const values = {};
811
+ for (;;) {
812
+ const column = cursor.name();
813
+ if (Object.hasOwn(values, column) || cursor.op() === '.')
814
+ fail();
815
+ cursor.expectOp('=');
816
+ values[column] = value(cursor, (at) => at.op() === ',' || at.word() === 'WHERE', table, column, table.sql);
817
+ if (cursor.op() !== ',')
818
+ break;
819
+ cursor.at += 1;
820
+ }
821
+ cursor.expectWord('WHERE');
822
+ const { key, sql } = keyEqualities(cursor, table, (at) => at.op() === ';');
823
+ cursor.conditions.push(`(SELECT true FROM ${table.sql} WHERE ${sql})`);
824
+ cursor.sublinks += 1;
825
+ return { kind: 'update', table: table.name, key, values };
826
+ }
827
+ if (word === 'INSERT') {
828
+ cursor.expectWord('INTO');
829
+ const table = effectTable(cursor);
830
+ cursor.expectOp('(');
831
+ const columns = [cursor.name()];
832
+ while (cursor.op() === ',') {
833
+ cursor.at += 1;
834
+ columns.push(cursor.name());
835
+ }
836
+ cursor.expectOp(')');
837
+ if (new Set(columns).size !== columns.length)
838
+ fail();
839
+ cursor.expectWord('VALUES');
840
+ cursor.expectOp('(');
841
+ const values = {};
842
+ for (const [index, column] of columns.entries()) {
843
+ if (index)
844
+ cursor.expectOp(',');
845
+ values[column] = value(cursor, (at) => at.op() === ',' || at.op() === ')', table, column);
846
+ }
847
+ cursor.expectOp(')');
848
+ // One row, nothing after it: no second row, ON CONFLICT or RETURNING.
849
+ if (cursor.op() !== ';')
850
+ fail();
851
+ return { kind: 'insert', table: table.name, values };
852
+ }
853
+ cursor.expectWord('FROM');
854
+ const table = effectTable(cursor);
855
+ cursor.expectWord('WHERE');
856
+ const { key, sql } = keyEqualities(cursor, table, (at) => at.op() === ';');
857
+ cursor.conditions.push(`(SELECT true FROM ${table.sql} WHERE ${sql})`);
858
+ cursor.sublinks += 1;
859
+ return { kind: 'delete', table: table.name, key };
860
+ }
861
+ /** The statements of a block, up to (not past) END, ELSIF, ELSEIF or ELSE. */
862
+ function statements(cursor, returns) {
863
+ for (;;) {
864
+ const word = cursor.word();
865
+ if (word === 'END' || word === 'ELSIF' || word === 'ELSEIF' || word === 'ELSE')
866
+ return;
867
+ if (word === 'IF') {
868
+ cursor.at += 1;
869
+ condition(cursor);
870
+ cursor.expectWord('THEN');
871
+ statements(cursor, returns);
872
+ while (cursor.word() === 'ELSIF' || cursor.word() === 'ELSEIF') {
873
+ cursor.at += 1;
874
+ condition(cursor);
875
+ cursor.expectWord('THEN');
876
+ statements(cursor, returns);
877
+ }
878
+ if (cursor.word() === 'ELSE') {
879
+ cursor.at += 1;
880
+ statements(cursor, returns);
881
+ }
882
+ cursor.expectWord('END');
883
+ cursor.expectWord('IF');
884
+ cursor.expectOp(';');
885
+ }
886
+ else if (word === 'RAISE') {
887
+ cursor.at += 1;
888
+ if (cursor.word() === 'EXCEPTION')
889
+ cursor.at += 1;
890
+ if (cursor.take().kind !== 'string')
891
+ fail();
892
+ if (cursor.word() === 'USING') {
893
+ cursor.at += 1;
894
+ for (;;) {
895
+ if (!['ERRCODE', 'MESSAGE', 'DETAIL', 'HINT', 'COLUMN', 'CONSTRAINT', 'DATATYPE', 'TABLE', 'SCHEMA'].includes(cursor.word() ?? ''))
896
+ fail();
897
+ cursor.at += 1;
898
+ cursor.expectOp('=');
899
+ if (cursor.take().kind !== 'string')
900
+ fail();
901
+ if (cursor.op() !== ',')
902
+ break;
903
+ cursor.at += 1;
904
+ }
905
+ }
906
+ cursor.expectOp(';');
907
+ }
908
+ else if (word === 'RETURN') {
909
+ cursor.at += 1;
910
+ const value = cursor.word();
911
+ if (!value || !returns.has(value))
912
+ fail();
913
+ cursor.at += 1;
914
+ cursor.expectOp(';');
915
+ }
916
+ else if (word === 'NULL') {
917
+ cursor.at += 1;
918
+ cursor.expectOp(';');
919
+ }
920
+ else if (word === 'UPDATE' || word === 'INSERT' || word === 'DELETE') {
921
+ cursor.effects.push(keyedWrite(cursor));
922
+ cursor.expectOp(';');
923
+ }
924
+ else {
925
+ fail();
926
+ }
927
+ }
928
+ }
929
+ /**
930
+ * Whether a trigger function's body is in the grammar, and if it is, its
931
+ * conditions, each as the SQL PostgreSQL is to parse in its place (a literal
932
+ * as NULL, TG_OP as a NULL text, NEW and OLD as the view's `"new"` and
933
+ * `"old"`). `returns` is what its RETURN may give back.
934
+ */
935
+ export function plpgsqlConditions(source, returns) {
936
+ const body = plpgsqlBody(source, returns);
937
+ return body && !body.effects.length ? body.conditions : undefined;
938
+ }
939
+ /** The body in the grammar, keyed effects included; undefined where it is not. */
940
+ function plpgsqlBody(source, returns) {
941
+ try {
942
+ const cursor = new Cursor(tokenize(source), source);
943
+ cursor.expectWord('BEGIN');
944
+ statements(cursor, returns);
945
+ cursor.expectWord('END');
946
+ if (cursor.op() === ';')
947
+ cursor.at += 1;
948
+ if (cursor.at !== cursor.tokens.length)
949
+ fail();
950
+ return {
951
+ conditions: cursor.conditions,
952
+ effects: cursor.effects,
953
+ values: cursor.values,
954
+ sublinks: cursor.sublinks,
955
+ keys: cursor.keys,
956
+ keyColumns: cursor.keyColumns,
957
+ };
958
+ }
959
+ catch (error) {
960
+ if (error instanceof Unproven)
961
+ return undefined;
962
+ throw error;
963
+ }
964
+ }
965
+ /** The body as tokens, one space apart, where it tokenizes; its text where it does not. */
966
+ function normalized(source) {
967
+ try {
968
+ return tokenize(source)
969
+ .map((token) => (token.kind === 'word' ? token.upper : source.slice(token.start, token.end)))
970
+ .join(' ');
971
+ }
972
+ catch {
973
+ return source;
974
+ }
975
+ }
976
+ /**
977
+ * `sha256:<hex>` of what decides what the trigger does: its timing and events, its column list and WHEN, and its
978
+ * function's language, attributes and body. Comments, spacing and keyword case never move it.
979
+ */
980
+ function digestOf(row) {
981
+ const definition = JSON.stringify([
982
+ row.type,
983
+ row.columns,
984
+ row.constraint,
985
+ row.transition,
986
+ row.qual.replace(/:location -?\d+/g, ''),
987
+ row.language,
988
+ row.kind,
989
+ row.definer,
990
+ row.configured,
991
+ row.arguments,
992
+ normalized(row.source),
993
+ ]);
994
+ return `sha256:${createHash('sha256').update(`postgres\n${definition}`).digest('hex')}`;
995
+ }
996
+ /** Why a body that is not validation-only is not, from its words. */
997
+ function why(source) {
998
+ if (/\b(INSERT|UPDATE|DELETE|MERGE|TRUNCATE|EXECUTE|PERFORM|COPY|CALL|NOTIFY)\b/i.test(source) || /:=/.test(source))
999
+ return 'it writes rows';
1000
+ if (/\b(SELECT|FROM|EXISTS)\b/i.test(source))
1001
+ return 'it reads another table';
1002
+ return 'it runs a function mistri cannot prove writes nothing';
1003
+ }
1004
+ const SAVEPOINT = 'mistri_trigger_proof';
1005
+ /**
1006
+ * Whether a value of type `w.source` is assigned to column `a` without running a function of the database's: the
1007
+ * same type, or a cast from it that is binary or runs a pure function (`pure`, over `p`), each side taken through
1008
+ * its domains to their base type. Coercing to a domain runs the domain's checks, which are the column's own code
1009
+ * (readPostgresTableCode) and judged there.
1010
+ */
1011
+ const ASSIGNABLE = (pure) => `WITH RECURSIVE
1012
+ target(type) AS (SELECT a.atttypid UNION SELECT t.typbasetype FROM target JOIN pg_catalog.pg_type t ON t.oid ${EQ} target.type WHERE t.typtype ${EQ} 'd'),
1013
+ source(type) AS (SELECT w.source UNION SELECT t.typbasetype FROM source JOIN pg_catalog.pg_type t ON t.oid ${EQ} source.type WHERE t.typtype ${EQ} 'd')
1014
+ SELECT 1 FROM source JOIN target ON target.type ${EQ} source.type
1015
+ UNION ALL
1016
+ SELECT 1 FROM source JOIN pg_catalog.pg_cast c ON c.castsource ${EQ} source.type JOIN target ON target.type ${EQ} c.casttarget
1017
+ LEFT JOIN pg_catalog.pg_proc p ON p.oid ${EQ} c.castfunc
1018
+ WHERE c.castcontext ${EQ} ANY (ARRAY['a', 'i']::pg_catalog."char"[])
1019
+ AND (c.castmethod ${EQ} 'b' OR (c.castmethod ${EQ} 'f' AND ${pure}))`;
1020
+ /**
1021
+ * The analyzer on `client`, which must be inside a transaction that may write
1022
+ * (a read-only one cannot make even a temporary view). Each parse is made and
1023
+ * undone inside a savepoint, so the transaction is left as it was, and a
1024
+ * condition PostgreSQL rejects only fails its own proof.
1025
+ */
1026
+ export function postgresTriggerAnalyzer(client) {
1027
+ return {
1028
+ async conditions(relation, conditions, values = []) {
1029
+ if (!conditions.length && !values.length)
1030
+ return { tree: '', boolean: true };
1031
+ // Each condition on lines of its own: a comment in one could not run past it (it has none; they are cut out).
1032
+ const selected = [...conditions, ...values].map((condition, index) => `(\n${condition}\n) AS c${index}`).join(', ');
1033
+ await client.query(`SAVEPOINT ${SAVEPOINT}`);
1034
+ try {
1035
+ // Extended protocol: exactly one statement, whatever the text holds.
1036
+ await client.query({
1037
+ text: `CREATE TEMPORARY VIEW ${SAVEPOINT} AS SELECT ${selected} FROM ONLY ${relation} AS "new", ONLY ${relation} AS "old"`,
1038
+ values: [],
1039
+ queryMode: 'extended',
1040
+ });
1041
+ const read = await client.query(`SELECT r.ev_action::pg_catalog.text AS tree,
1042
+ ARRAY(SELECT a.atttypid::pg_catalog.int4 FROM pg_catalog.pg_attribute a
1043
+ WHERE a.attrelid ${EQ} r.ev_class AND a.attnum ${GT} 0 ORDER BY a.attnum) AS types
1044
+ FROM pg_catalog.pg_rewrite r WHERE r.ev_class ${EQ} 'pg_temp.${SAVEPOINT}'::pg_catalog.regclass`);
1045
+ const row = read.rows[0];
1046
+ if (read.rows.length !== 1 || typeof row?.tree !== 'string' || !Array.isArray(row.types))
1047
+ return undefined;
1048
+ if (row.types.length !== conditions.length + values.length)
1049
+ return undefined;
1050
+ // 16 is boolean: a condition of another type is cast to it by PL/pgSQL at run time, through a cast of anyone's.
1051
+ return {
1052
+ tree: row.tree,
1053
+ boolean: row.types.slice(0, conditions.length).every((type) => type === 16),
1054
+ ...(values.length ? { types: row.types.slice(conditions.length).map(Number) } : {}),
1055
+ };
1056
+ }
1057
+ catch {
1058
+ return undefined;
1059
+ }
1060
+ finally {
1061
+ await client.query(`ROLLBACK TO SAVEPOINT ${SAVEPOINT}`);
1062
+ await client.query(`RELEASE SAVEPOINT ${SAVEPOINT}`);
1063
+ }
1064
+ },
1065
+ async impure(functions, operators, types, assignments = [], keys = []) {
1066
+ if (!functions.length && !operators.length && !types.length && !assignments.length && !keys.length)
1067
+ return new Set();
1068
+ // Immutable, and the database's own or C a superuser installed: an extension's (citext), never a user's PL.
1069
+ const pure = `p.provolatile ${EQ} 'i' AND p.prokind ${EQ} 'f'
1070
+ AND (p.oid ${LT} ${FIRST_NORMAL_OID}::pg_catalog.oid OR EXISTS (SELECT 1 FROM pg_catalog.pg_language g
1071
+ WHERE g.oid ${EQ} p.prolang AND g.lanname ${EQ} ANY (ARRAY['c', 'internal']::pg_catalog.name[])))`;
1072
+ /* A key column's own equality: strategy 3 of the default B-tree class of its type, between two of that type. */
1073
+ const equality = `SELECT 1 FROM ${baseType('a.atttypid', 'a.atttypmod')} AS b(type, typmod)
1074
+ JOIN pg_catalog.pg_opclass oc ON oc.oid ${EQ} ${defaultBtreeClass('b.type')}
1075
+ JOIN pg_catalog.pg_amop m ON m.amopfamily ${EQ} oc.opcfamily AND m.amopmethod ${EQ} ${BTREE}
1076
+ WHERE m.amopstrategy ${EQ} 3 AND m.amoplefttype ${EQ} oc.opcintype AND m.amoprighttype ${EQ} oc.opcintype
1077
+ AND m.amopopr ${EQ} w.operator`;
1078
+ const read = await client.query(`SELECT 'f' AS kind, w.oid::pg_catalog.text AS id FROM pg_catalog.unnest($1::pg_catalog.oid[]) AS w(oid)
1079
+ LEFT JOIN pg_catalog.pg_proc p ON p.oid ${EQ} w.oid WHERE p.oid IS NULL OR NOT (${pure})
1080
+ UNION ALL
1081
+ SELECT 'o', w.oid::pg_catalog.text FROM pg_catalog.unnest($2::pg_catalog.oid[]) AS w(oid)
1082
+ LEFT JOIN pg_catalog.pg_operator o ON o.oid ${EQ} w.oid
1083
+ LEFT JOIN pg_catalog.pg_proc p ON p.oid ${EQ} o.oprcode WHERE p.oid IS NULL OR NOT (${pure})
1084
+ UNION ALL
1085
+ SELECT DISTINCT 't', w.oid::pg_catalog.text FROM pg_catalog.unnest($3::pg_catalog.oid[]) AS w(oid)
1086
+ WHERE EXISTS (WITH RECURSIVE under(type) AS (SELECT w.oid UNION SELECT inner_type.oid FROM under ${TYPE_STEP('under')})
1087
+ SELECT 1 FROM under JOIN pg_catalog.pg_type t ON t.oid ${EQ} under.type WHERE t.typtype ${EQ} 'd')
1088
+ UNION ALL
1089
+ SELECT 'c', w.i::pg_catalog.text
1090
+ FROM ROWS FROM (pg_catalog.unnest($4::pg_catalog.int4[]), pg_catalog.unnest($5::pg_catalog.oid[]), pg_catalog.unnest($6::pg_catalog.text[]), pg_catalog.unnest($7::pg_catalog.text[]))
1091
+ AS w(i, source, relation, attname)
1092
+ LEFT JOIN pg_catalog.pg_attribute a
1093
+ ON a.attrelid ${EQ} pg_catalog.to_regclass(w.relation) AND a.attname ${EQ} w.attname AND a.attnum ${GT} 0 AND NOT a.attisdropped
1094
+ WHERE a.attrelid IS NULL OR NOT EXISTS (${ASSIGNABLE(pure)})
1095
+ UNION ALL
1096
+ SELECT 'k', w.i::pg_catalog.text
1097
+ FROM ROWS FROM (pg_catalog.unnest($8::pg_catalog.int4[]), pg_catalog.unnest($9::pg_catalog.oid[]), pg_catalog.unnest($10::pg_catalog.text[]), pg_catalog.unnest($11::pg_catalog.text[]))
1098
+ AS w(i, operator, relation, attname)
1099
+ LEFT JOIN pg_catalog.pg_attribute a
1100
+ ON a.attrelid ${EQ} pg_catalog.to_regclass(w.relation) AND a.attname ${EQ} w.attname AND a.attnum ${GT} 0 AND NOT a.attisdropped
1101
+ WHERE a.attrelid IS NULL OR NOT EXISTS (${equality})`, [
1102
+ functions.map(String),
1103
+ operators.map(String),
1104
+ types.map(String),
1105
+ assignments.map((_, index) => index),
1106
+ assignments.map((assignment) => String(assignment.from)),
1107
+ assignments.map((assignment) => assignment.relation),
1108
+ assignments.map((assignment) => assignment.column),
1109
+ keys.map((_, index) => index),
1110
+ keys.map((key) => String(key.operator)),
1111
+ keys.map((key) => key.relation),
1112
+ keys.map((key) => key.column),
1113
+ ]);
1114
+ return new Set(read.rows.map((row) => `${String(row.kind)}${String(row.id)}`));
1115
+ },
1116
+ };
1117
+ }
1118
+ const RUNS = 'it runs a function mistri cannot prove writes nothing';
1119
+ function plan(row) {
1120
+ const events = [];
1121
+ if (row.type & INSERT)
1122
+ events.push('insert');
1123
+ if (row.type & UPDATE)
1124
+ events.push('update');
1125
+ if (row.type & DELETE)
1126
+ events.push('delete');
1127
+ // A column list the catalog could not name in full, or one with a generated column, is taken as every update.
1128
+ const columns = row.listed > 0 && row.columns.length === row.listed && !row.generated ? row.columns : undefined;
1129
+ const fired = { name: row.name, events, ...(columns ? { columns } : {}), digest: digestOf(row) };
1130
+ const not = (reason) => ({ decided: { ...fired, validates: false, why: reason } });
1131
+ if (!(row.type & ROW))
1132
+ return not('it runs once per statement');
1133
+ if (row.type & INSTEAD || row.constraint || row.transition)
1134
+ return not('it is a kind of trigger mistri does not prove');
1135
+ const qual = row.qual ? readPostgresTree(row.qual) : undefined;
1136
+ if (row.qual && (!qual || ![...qual.nodes.keys()].every((node) => EXPRESSION_NODES.has(node))))
1137
+ return not('its WHEN runs a function mistri cannot prove writes nothing');
1138
+ if (row.language !== 'plpgsql' || row.kind !== 'f' || row.definer || row.configured || row.arguments !== 0)
1139
+ return not(RUNS);
1140
+ const before = Boolean(row.type & BEFORE);
1141
+ const returns = new Set(before ? (row.type & DELETE ? ['OLD'] : ['NEW']) : ['NEW', 'OLD', 'NULL']);
1142
+ // A BEFORE trigger on both deletes and inserts or updates returns OLD for one and NEW for the other: not proven.
1143
+ if (before && row.type & DELETE && row.type & (INSERT | UPDATE))
1144
+ return not(RUNS);
1145
+ const body = plpgsqlBody(row.source, returns);
1146
+ if (!body)
1147
+ return not(why(row.source));
1148
+ const { conditions, ...keyed } = body;
1149
+ return {
1150
+ fired,
1151
+ ...(qual ? { qual } : {}),
1152
+ conditions,
1153
+ relation: row.relation,
1154
+ ...(keyed.effects.length
1155
+ ? { keyed: { ...keyed, why: why(row.source), plain: plainDefinition(row.source, tokenize(row.source), 'postgres') } }
1156
+ : {}),
1157
+ };
1158
+ }
1159
+ /**
1160
+ * Each trigger the rows describe, its conditions judged by PostgreSQL through
1161
+ * `analyzer`; without one (a reader that cannot make a view), a trigger with
1162
+ * conditions is not proven.
1163
+ */
1164
+ async function readPostgresTriggers(rows, analyzer) {
1165
+ const planned = rows.map(plan);
1166
+ // Each trigger's conditions as PostgreSQL parsed them, or why they could not be judged.
1167
+ const trees = new Map();
1168
+ // Each keyed write's value as an assignment to judge, by its index in `assignments`.
1169
+ const assignments = [];
1170
+ const assigned = new Map();
1171
+ for (const [index, entry] of planned.entries()) {
1172
+ if ('decided' in entry)
1173
+ continue;
1174
+ const values = entry.keyed?.values ?? [];
1175
+ if (!entry.conditions.length && !values.length)
1176
+ continue;
1177
+ const said = analyzer
1178
+ ? values.length
1179
+ ? await analyzer.conditions(entry.relation, entry.conditions, values.map((value) => value.sql))
1180
+ : await analyzer.conditions(entry.relation, entry.conditions)
1181
+ : undefined;
1182
+ const tree = said && readPostgresTree(said.tree);
1183
+ // The scalar subqueries the grammar wrote, one for each keyed read and each keyed write's key and values: no more.
1184
+ const sublinks = entry.keyed?.sublinks ?? 0;
1185
+ trees.set(index, !analyzer
1186
+ ? 'mistri could not have PostgreSQL read its conditions'
1187
+ : !said || !tree || (values.length > 0 && said.types?.length !== values.length)
1188
+ ? 'PostgreSQL does not read a condition of it as a check of NEW and OLD alone'
1189
+ : !said.boolean
1190
+ ? 'a condition of it is not a boolean'
1191
+ : (tree.nodes.get('SUBLINK') ?? 0) !== sublinks ||
1192
+ tree.nodes.get('QUERY') !== 1 + sublinks ||
1193
+ tree.nodes.get('RANGETBLENTRY') !== 2 + sublinks
1194
+ ? 'it reads another table'
1195
+ : ![...tree.nodes.keys()].every((node) => VIEW_NODES.has(node) || (sublinks > 0 && node === 'SUBLINK'))
1196
+ ? 'a condition of it does more than compare the row'
1197
+ : tree);
1198
+ const types = said?.types;
1199
+ if (types && values.length)
1200
+ assigned.set(index, values.map((value, at) => assignments.push({ from: types[at], relation: value.relation, column: value.column }) - 1));
1201
+ }
1202
+ /* Each key's equalities, parsed apart from everything else, so the tree is theirs alone: one operator each between
1203
+ two columns, and nothing that converts either. The type and collation of the two columns are the catalog's to
1204
+ compare (triggerEffects.ts); this is what PostgreSQL resolved the equality to. */
1205
+ const castKeys = new Set();
1206
+ const keyOperators = [];
1207
+ const keyOwners = [];
1208
+ for (const [index, entry] of planned.entries()) {
1209
+ if ('decided' in entry || !entry.keyed?.keys.length || !analyzer)
1210
+ continue;
1211
+ const keys = entry.keyed.keys;
1212
+ const said = await analyzer.conditions(entry.relation, keys);
1213
+ const tree = said && readPostgresTree(said.tree);
1214
+ if (!said?.boolean ||
1215
+ !tree ||
1216
+ tree.nodes.get('SUBLINK') !== keys.length ||
1217
+ tree.nodes.get('QUERY') !== 1 + keys.length ||
1218
+ tree.nodes.get('RANGETBLENTRY') !== 2 + keys.length ||
1219
+ tree.nodes.get('OPEXPR') !== keys.length ||
1220
+ ![...tree.nodes.keys()].every((node) => KEY_NODES.has(node))) {
1221
+ castKeys.add(index);
1222
+ continue;
1223
+ }
1224
+ /* And each equality is its column's own: `=` is whichever operator the search_path finds first, and one a
1225
+ person created in a schema ahead of pg_catalog can match any row, or none. */
1226
+ tree.opexprs.forEach((operator, at) => {
1227
+ const column = entry.keyed?.keyColumns[at];
1228
+ keyOperators.push({ operator, relation: column?.relation ?? '', column: column?.column ?? '' });
1229
+ keyOwners.push(index);
1230
+ });
1231
+ }
1232
+ const functions = new Set();
1233
+ const operators = new Set();
1234
+ const types = new Set();
1235
+ for (const [index, entry] of planned.entries()) {
1236
+ if ('decided' in entry)
1237
+ continue;
1238
+ for (const tree of [entry.qual, trees.get(index)]) {
1239
+ if (!tree || typeof tree === 'string')
1240
+ continue;
1241
+ for (const oid of tree.functions)
1242
+ functions.add(oid);
1243
+ for (const oid of tree.operators)
1244
+ operators.add(oid);
1245
+ }
1246
+ // A WHEN's constants were read when it was made; a condition's literals are read each time PL/pgSQL parses it.
1247
+ const tree = trees.get(index);
1248
+ if (tree && typeof tree !== 'string')
1249
+ for (const oid of tree.constants)
1250
+ types.add(oid);
1251
+ }
1252
+ const impure = analyzer
1253
+ ? assignments.length || keyOperators.length
1254
+ ? await analyzer.impure([...functions], [...operators], [...types], assignments, keyOperators)
1255
+ : await analyzer.impure([...functions], [...operators], [...types])
1256
+ : undefined;
1257
+ const offKeys = new Set(keyOwners.filter((_, at) => impure?.has(`k${at}`)));
1258
+ return planned.map((entry, index) => {
1259
+ if ('decided' in entry)
1260
+ return entry.decided;
1261
+ // A keyed trigger's expressions are its writes' values and keys as well as its conditions.
1262
+ const not = (reason) => ({
1263
+ ...entry.fired,
1264
+ validates: false,
1265
+ why: entry.keyed ? reason.replace('a condition of it', 'an expression of it') : reason,
1266
+ });
1267
+ const pure = (tree) => impure !== undefined &&
1268
+ [...tree.functions].every((oid) => !impure.has(`f${oid}`)) &&
1269
+ [...tree.operators].every((oid) => !impure.has(`o${oid}`));
1270
+ if (entry.qual && !pure(entry.qual))
1271
+ return not('its WHEN runs a function mistri cannot prove writes nothing');
1272
+ const tree = trees.get(index);
1273
+ if (typeof tree === 'string')
1274
+ return not(tree);
1275
+ if (tree && !pure(tree))
1276
+ return not('a condition of it runs a function mistri cannot prove writes nothing');
1277
+ /* `NEW.codes = '{zz}'` on an array of a domain reads the literal through the domain's input, which runs its
1278
+ checks, every time PL/pgSQL parses the condition — though the view, given NULL, ran none. */
1279
+ if (tree && [...tree.constants].some((oid) => impure?.has(`t${oid}`)))
1280
+ return not("a literal in a condition of it is read as a domain's value, which runs the domain's checks");
1281
+ if (!entry.keyed)
1282
+ return { ...entry.fired, validates: true };
1283
+ if ((assigned.get(index) ?? []).some((at) => impure?.has(`c${at}`)))
1284
+ return not("a value it writes is not of its column's type, and no cast mistri can prove writes nothing makes it one");
1285
+ return {
1286
+ ...entry.fired,
1287
+ validates: false,
1288
+ why: entry.keyed.why,
1289
+ effects: entry.keyed.effects,
1290
+ ...(castKeys.has(index)
1291
+ ? { unaccepted: KEY_CAST }
1292
+ : offKeys.has(index)
1293
+ ? { unaccepted: KEY_OPERATOR }
1294
+ : entry.keyed.plain
1295
+ ? {}
1296
+ : { unaccepted: PLAIN }),
1297
+ };
1298
+ });
1299
+ }
1300
+ /**
1301
+ * Each table's triggers, keyed `schema.name`, from the statement's rows, and
1302
+ * what each table's proof was read from. Throws on a row of an unknown shape.
1303
+ */
1304
+ export async function postgresTriggersByTable(rows, analyzer) {
1305
+ if (!rows.every(isPostgresTriggerRow))
1306
+ throw new Error('A trigger row of an unknown shape.');
1307
+ const triggers = await readPostgresTriggers(rows, analyzer);
1308
+ const result = new Map();
1309
+ for (const [index, row] of rows.entries()) {
1310
+ const key = `${row.schema}.${row.table}`;
1311
+ const entry = result.get(key) ?? { triggers: [], version: '' };
1312
+ entry.triggers.push(triggers[index]);
1313
+ entry.version += `${entry.version ? ';' : ''}${triggerVersion(row)}`;
1314
+ result.set(key, entry);
1315
+ }
1316
+ return result;
1317
+ }
1318
+ /** What each table's proof was read from, keyed `schema.name`, without proving anything again: what an attestation compares. */
1319
+ export function postgresTriggerVersions(rows) {
1320
+ if (!rows.every(isPostgresTriggerRow))
1321
+ throw new Error('A trigger row of an unknown shape.');
1322
+ const result = new Map();
1323
+ for (const row of rows) {
1324
+ const key = `${row.schema}.${row.table}`;
1325
+ const version = result.get(key);
1326
+ result.set(key, `${version ? `${version};` : ''}${triggerVersion(row)}`);
1327
+ }
1328
+ return result;
1329
+ }
1330
+ /**
1331
+ * One step into a type (`from`.type) toward the types its values hold: a domain's base type, an array's element, a
1332
+ * composite's fields, a range's subtype, a multirange's range. A value is read through each one's input in turn.
1333
+ */
1334
+ const TYPE_STEP = (from) => `JOIN pg_catalog.pg_type t ON t.oid ${EQ} ${from}.type
1335
+ CROSS JOIN LATERAL (
1336
+ SELECT t.typbasetype WHERE t.typtype ${EQ} 'd'
1337
+ UNION ALL SELECT t.typelem WHERE t.typcategory ${EQ} 'A' AND t.typelem ${NE} 0
1338
+ UNION ALL SELECT a.atttypid FROM pg_catalog.pg_attribute a
1339
+ WHERE t.typtype ${EQ} 'c' AND a.attrelid ${EQ} t.typrelid AND a.attnum ${GT} 0 AND NOT a.attisdropped
1340
+ UNION ALL SELECT g.rngsubtype FROM pg_catalog.pg_range g WHERE g.rngtypid ${EQ} t.oid
1341
+ UNION ALL SELECT g.rngtypid FROM pg_catalog.pg_range g WHERE g.rngmultitypid ${EQ} t.oid) AS inner_type(oid)`;
1342
+ /** The relations a write to each wanted table reaches, and the types every column of them holds, to any depth. */
1343
+ const CODE_TYPES = `wanted AS (
1344
+ SELECT r.oid AS root, n.nspname::pg_catalog.text AS schema, r.relname::pg_catalog.text AS "table"
1345
+ FROM pg_catalog.pg_class r JOIN pg_catalog.pg_namespace n ON n.oid ${EQ} r.relnamespace
1346
+ WHERE EXISTS (SELECT 1 FROM ROWS FROM (pg_catalog.unnest($1::pg_catalog.text[]), pg_catalog.unnest($2::pg_catalog.text[])) AS w(schema, name)
1347
+ WHERE n.nspname ${EQ} w.schema AND r.relname ${EQ} w.name)),
1348
+ tree(root, relid) AS (
1349
+ SELECT root, root FROM wanted
1350
+ UNION SELECT tree.root, i.inhrelid FROM tree JOIN pg_catalog.pg_inherits i ON i.inhparent ${EQ} tree.relid),
1351
+ typed(root, name, type) AS (
1352
+ SELECT tree.root, a.attname::pg_catalog.text, a.atttypid FROM tree
1353
+ JOIN pg_catalog.pg_attribute a ON a.attrelid ${EQ} tree.relid AND a.attnum ${GT} 0 AND NOT a.attisdropped
1354
+ UNION
1355
+ SELECT typed.root, typed.name, inner_type.oid FROM typed ${TYPE_STEP('typed')})`;
1356
+ const NO_TEXTS = `'{}'::pg_catalog.text[]`;
1357
+ /** A domain's constraints and default, the expressions coercing to it runs. */
1358
+ const domainCode = (from, column) => `
1359
+ SELECT ${from}, 'domain' AS kind, pg_catalog.format('%I.%I', tn.nspname, t.typname) AS name, ${column} AS "column", 'iu' AS events,
1360
+ ARRAY(SELECT c.conbin::pg_catalog.text FROM pg_catalog.pg_constraint c WHERE c.contypid ${EQ} t.oid AND c.conbin IS NOT NULL)
1361
+ ${CAT} CASE WHEN t.typdefaultbin IS NULL THEN ${NO_TEXTS} ELSE ARRAY[t.typdefaultbin::pg_catalog.text] END AS trees,
1362
+ ${NO_TEXTS} AS operators`;
1363
+ /**
1364
+ * Every expression a write to the tables named by `$1` (schemas) and `$2`
1365
+ * (names) may run, with the table it is reached through: theirs, their
1366
+ * partitions' and children's, and their columns' domains'.
1367
+ */
1368
+ function postgresTableCodeStatement() {
1369
+ const generated = `a.attgenerated ${NE} ''`;
1370
+ return `WITH RECURSIVE ${CODE_TYPES}
1371
+ SELECT wanted.schema, wanted."table", code.kind, code.name, code.column_name AS "column", code.events, code.trees, code.operators
1372
+ FROM (
1373
+ SELECT tree.root, CASE WHEN ${generated} THEN 'generated column' ELSE 'default of column' END AS kind,
1374
+ a.attname::pg_catalog.text AS name, CASE WHEN ${generated} THEN NULL ELSE a.attname::pg_catalog.text END AS column_name,
1375
+ CASE WHEN ${generated} THEN 'iu' ELSE 'i' END AS events, ARRAY[d.adbin::pg_catalog.text] AS trees, ${NO_TEXTS} AS operators
1376
+ FROM tree JOIN pg_catalog.pg_attrdef d ON d.adrelid ${EQ} tree.relid
1377
+ JOIN pg_catalog.pg_attribute a ON a.attrelid ${EQ} d.adrelid AND a.attnum ${EQ} d.adnum AND NOT a.attisdropped
1378
+ UNION ALL
1379
+ SELECT tree.root, CASE WHEN c.contype ${EQ} 'c' THEN 'CHECK constraint' ELSE 'exclusion constraint' END, c.conname::pg_catalog.text, NULL, 'iu',
1380
+ CASE WHEN c.conbin IS NULL THEN ${NO_TEXTS} ELSE ARRAY[c.conbin::pg_catalog.text] END, coalesce(c.conexclop::pg_catalog.text[], ${NO_TEXTS})
1381
+ FROM tree JOIN pg_catalog.pg_constraint c ON c.conrelid ${EQ} tree.relid AND c.contype ${EQ} ANY (ARRAY['c', 'x']::pg_catalog."char"[])
1382
+ UNION ALL
1383
+ SELECT tree.root, 'index', k.relname::pg_catalog.text, NULL, 'iu',
1384
+ ARRAY(SELECT e FROM pg_catalog.unnest(ARRAY[i.indexprs::pg_catalog.text, i.indpred::pg_catalog.text]) AS e WHERE e IS NOT NULL), ${NO_TEXTS}
1385
+ FROM tree JOIN pg_catalog.pg_index i ON i.indrelid ${EQ} tree.relid JOIN pg_catalog.pg_class k ON k.oid ${EQ} i.indexrelid
1386
+ WHERE i.indexprs IS NOT NULL OR i.indpred IS NOT NULL
1387
+ UNION ALL
1388
+ SELECT tree.root, 'partition key of', k.relname::pg_catalog.text, NULL, 'iu', ARRAY[p.partexprs::pg_catalog.text], ${NO_TEXTS}
1389
+ FROM tree JOIN pg_catalog.pg_partitioned_table p ON p.partrelid ${EQ} tree.relid JOIN pg_catalog.pg_class k ON k.oid ${EQ} p.partrelid
1390
+ WHERE p.partexprs IS NOT NULL
1391
+ UNION ALL ${domainCode('typed.root', 'typed.name')}
1392
+ FROM typed JOIN pg_catalog.pg_type t ON t.oid ${EQ} typed.type AND t.typtype ${EQ} 'd'
1393
+ JOIN pg_catalog.pg_namespace tn ON tn.oid ${EQ} t.typnamespace
1394
+ ) AS code(root, kind, name, column_name, events, trees, operators)
1395
+ JOIN wanted ON wanted.root ${EQ} code.root
1396
+ ORDER BY 1, 2, 3, 4, 5`;
1397
+ }
1398
+ /** The domains `$1` (oids) and every domain under each, as {@link postgresTableCodeStatement}'s rows (no table). */
1399
+ const POSTGRES_DOMAIN_CODE = `WITH RECURSIVE under(type) AS (
1400
+ SELECT pg_catalog.unnest($1::pg_catalog.oid[])
1401
+ UNION SELECT t.typbasetype FROM under JOIN pg_catalog.pg_type t ON t.oid ${EQ} under.type WHERE t.typtype ${EQ} 'd')
1402
+ ${domainCode(`'' AS schema, '' AS "table"`, 'NULL::pg_catalog.text')}
1403
+ FROM under JOIN pg_catalog.pg_type t ON t.oid ${EQ} under.type AND t.typtype ${EQ} 'd'
1404
+ JOIN pg_catalog.pg_namespace tn ON tn.oid ${EQ} t.typnamespace`;
1405
+ /** PostgreSQL's own functions that run a query given to them as text or a cursor, or read a table whole. */
1406
+ const RUNS_SQL = [
1407
+ 'query_to_xml',
1408
+ 'query_to_xmlschema',
1409
+ 'query_to_xml_and_xmlschema',
1410
+ 'cursor_to_xml',
1411
+ 'cursor_to_xmlschema',
1412
+ 'table_to_xml',
1413
+ 'table_to_xmlschema',
1414
+ 'table_to_xml_and_xmlschema',
1415
+ 'schema_to_xml',
1416
+ 'schema_to_xmlschema',
1417
+ 'schema_to_xml_and_xmlschema',
1418
+ 'database_to_xml',
1419
+ 'database_to_xmlschema',
1420
+ 'database_to_xml_and_xmlschema',
1421
+ 'ts_stat',
1422
+ 'ts_rewrite',
1423
+ ];
1424
+ /** Whether a function (`f`, a pg_proc row or none) is code the database did not make. */
1425
+ const untrusted = (f) => `(${f}.oid IS NULL
1426
+ OR NOT ((${f}.oid ${LT} ${FIRST_NORMAL_OID}::pg_catalog.oid
1427
+ AND ${f}.proname::pg_catalog.text ${NE} ALL (ARRAY[${RUNS_SQL.map((name) => `'${name}'`).join(', ')}]::pg_catalog.text[]))
1428
+ OR ${f}.prolang ${EQ} ANY (SELECT g.oid FROM pg_catalog.pg_language g
1429
+ WHERE g.lanname ${EQ} ANY (ARRAY['c', 'internal']::pg_catalog.name[]))))`;
1430
+ /**
1431
+ * Of the functions `$1` and operators `$2` (oids), those whose code is the
1432
+ * database's own making, keyed `f<oid>` or `o<oid>`, with the function each
1433
+ * runs as `name(argument types)`: neither PostgreSQL's own (bar those that run
1434
+ * a query) nor C a superuser installed.
1435
+ */
1436
+ const POSTGRES_UNTRUSTED_CODE = `SELECT 'f' ${CAT} w.oid::pg_catalog.text AS key,
1437
+ coalesce(f.oid::pg_catalog.regprocedure::pg_catalog.text, w.oid::pg_catalog.text) AS name
1438
+ FROM pg_catalog.unnest($1::pg_catalog.oid[]) AS w(oid) LEFT JOIN pg_catalog.pg_proc f ON f.oid ${EQ} w.oid
1439
+ WHERE ${untrusted('f')}
1440
+ UNION ALL
1441
+ SELECT 'o' ${CAT} w.oid::pg_catalog.text, coalesce(f.oid::pg_catalog.regprocedure::pg_catalog.text, 'operator ' ${CAT} w.oid::pg_catalog.text)
1442
+ FROM pg_catalog.unnest($2::pg_catalog.oid[]) AS w(oid) LEFT JOIN pg_catalog.pg_operator o ON o.oid ${EQ} w.oid
1443
+ LEFT JOIN pg_catalog.pg_proc f ON f.oid ${EQ} o.oprcode
1444
+ WHERE ${untrusted('f')}`;
1445
+ function isCodeRow(row) {
1446
+ if (!row || typeof row !== 'object')
1447
+ return false;
1448
+ const r = row;
1449
+ return (['schema', 'table', 'kind', 'name', 'events'].every((key) => typeof r[key] === 'string') &&
1450
+ (r.column === null || typeof r.column === 'string') &&
1451
+ [r.trees, r.operators].every((list) => Array.isArray(list) && list.every((item) => typeof item === 'string')));
1452
+ }
1453
+ /**
1454
+ * The code each wanted table's writes may run that calls a function the
1455
+ * database made, as the triggers a write is judged by (never validation-only),
1456
+ * keyed `schema.name`. `client` answers on the writer.
1457
+ */
1458
+ export async function readPostgresTableCode(client, tables) {
1459
+ const result = new Map();
1460
+ if (!tables.length)
1461
+ return result;
1462
+ const read = await client.query(postgresTableCodeStatement(), [tables.map((table) => table.schema), tables.map((table) => table.name)]);
1463
+ if (!read.rows.every(isCodeRow))
1464
+ throw new Error('A row of table code of an unknown shape.');
1465
+ const rows = read.rows;
1466
+ // A domain an expression casts to brings its own constraints, read once each.
1467
+ const domains = new Map();
1468
+ const domainCodeOf = (oid) => {
1469
+ if (!domains.has(oid))
1470
+ domains.set(oid, client.query(POSTGRES_DOMAIN_CODE, [[String(oid)]]).then((domain) => {
1471
+ if (!domain.rows.every(isCodeRow))
1472
+ throw new Error('A row of domain code of an unknown shape.');
1473
+ return domain.rows;
1474
+ }));
1475
+ return domains.get(oid);
1476
+ };
1477
+ const collect = async (row, into) => {
1478
+ for (const oid of row.operators)
1479
+ into.operators.add(Number(oid));
1480
+ for (const text of row.trees) {
1481
+ const tree = readPostgresTree(text);
1482
+ if (!tree) {
1483
+ into.unread = true;
1484
+ continue;
1485
+ }
1486
+ for (const oid of tree.functions)
1487
+ into.functions.add(oid);
1488
+ for (const oid of tree.operators)
1489
+ into.operators.add(oid);
1490
+ for (const oid of tree.domains) {
1491
+ if (into.domains.has(oid))
1492
+ continue;
1493
+ into.domains.add(oid);
1494
+ for (const domain of await domainCodeOf(oid))
1495
+ await collect(domain, into);
1496
+ }
1497
+ }
1498
+ };
1499
+ const named = new Map();
1500
+ for (const row of rows) {
1501
+ const into = { functions: new Set(), operators: new Set(), domains: new Set(), unread: false };
1502
+ await collect(row, into);
1503
+ named.set(row, into);
1504
+ }
1505
+ // One question for every function and operator any of it names.
1506
+ const functions = new Set([...named.values()].flatMap((entry) => [...entry.functions]));
1507
+ const operators = new Set([...named.values()].flatMap((entry) => [...entry.operators]));
1508
+ const calls = new Map();
1509
+ if (functions.size || operators.size) {
1510
+ const asked = await client.query(POSTGRES_UNTRUSTED_CODE, [[...functions].map(String), [...operators].map(String)]);
1511
+ for (const row of asked.rows)
1512
+ calls.set(String(row.key), String(row.name));
1513
+ }
1514
+ const said = new Set();
1515
+ for (const [row, entry] of named) {
1516
+ const called = [
1517
+ ...new Set([...[...entry.functions].map((oid) => calls.get(`f${oid}`)), ...[...entry.operators].map((oid) => calls.get(`o${oid}`))]),
1518
+ ].filter((name) => name !== undefined);
1519
+ if (!called.length && !entry.unread)
1520
+ continue;
1521
+ const key = `${row.schema}.${row.table}`;
1522
+ // An inherited CHECK, or two columns of one domain under the same name, is said once.
1523
+ const once = `${key}\u0000${row.kind}\u0000${row.name}\u0000${row.column ?? ''}`;
1524
+ if (said.has(once))
1525
+ continue;
1526
+ said.add(once);
1527
+ const events = [];
1528
+ if (row.events.includes('i'))
1529
+ events.push('insert');
1530
+ if (row.events.includes('u'))
1531
+ events.push('update');
1532
+ result.set(key, [
1533
+ ...(result.get(key) ?? []),
1534
+ {
1535
+ name: row.name,
1536
+ kind: row.kind,
1537
+ events,
1538
+ ...(row.kind === 'domain' && row.column !== null ? { columns: [row.column] } : {}),
1539
+ validates: false,
1540
+ why: called.length ? `it calls ${called.sort().join(', ')}` : 'it holds an expression mistri cannot read',
1541
+ },
1542
+ ]);
1543
+ }
1544
+ return result;
1545
+ }