@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,1841 @@
1
+ /**
2
+ * Postgres adapter, on `pg`: connecting, querying, transactions and writes.
3
+ *
4
+ * Describing a database is the one job this file does not do itself. The
5
+ * catalog queries and their reading live in `postgresCatalog.ts`, which holds
6
+ * the ordering that makes two reads of one database agree; `describe` below is
7
+ * the seam, and it is called on whichever handle is asking — the reader on
8
+ * connect, or the leased writer inside a scoped transaction.
9
+ */
10
+ import { isProxy } from 'node:util/types';
11
+ import { POSTGRES_STYLE, buildWhere, clampLimit, boundStatement, dedupe, looksWrappable, refuseStacked, trimStatement, clampOffset, Refusal, WriteConflict, TransactionOperations, queueRecordLock, recordLockFilter, TransactionOutcomeUnknown, refuseAnalyze, countStatement, countEachStatement, countEachRows, countsTogether, orderClause, } from './adapter.js';
12
+ import { compileAggregate } from '../shared/aggregate.js';
13
+ import { coerceForColumn } from '../shared/schema.js';
14
+ import { buildUpdateGuard } from './scoped/updateGuard.js';
15
+ import { createScopedTransaction, foreignKeyRefusal, isForeignKeyViolation, referencesStatement, wholeWithin, } from './scoped/scopedTransaction.js';
16
+ import { attestPostgresTriggers, effectCatalogFacts, readPostgresScopeCatalog, } from './scoped/postgresScopeCatalog.js';
17
+ import { postgresTriggerAnalyzer, postgresTriggersByTable, postgresTriggerStatement, readPostgresTableCode, } from './scoped/postgresTriggers.js';
18
+ import { captureScopeCatalog, mapScopeCatalog } from '../shared/scopeCatalog.js';
19
+ import { createPinnedPostgresReadOwner } from './postgresReadCatalog.js';
20
+ import { isRuntimeRelation, qualified, redact, valueSafe, withBytes, toJsonSafe } from './postgresValues.js';
21
+ import { beginWriteCapture, capturesWrites, committedWriteCapture, finishWriteCapture } from './writeCapture.js';
22
+ import { lendStoreHost, } from './storeHost.js';
23
+ import { compileView, compileViewCount } from '../shared/view.js';
24
+ import { compileBreakdown, compileBreakdownCount } from '../shared/breakdown.js';
25
+ import { PgConnectionManager, sharedPgConnections } from './postgresPool.js';
26
+ import { aheadReport, behindWrite, generationOf, redoWithoutAhead, sendsAhead, waitsAhead, RolledBackAtCommit, transactionHandle, attestedOn, keepAttestedOn, forgetAttestations, noteCatalogVersion, readsCatalogVersion, suspectsStores, } from './postgresTransactionHandle.js';
27
+ import { snapshotRead, withoutSnapshotRead } from './snapshotRead.js';
28
+ import { withoutWriteAhead, writeAhead } from './writeAhead.js';
29
+ import { KeyRows } from './scoped/keyRows.js';
30
+ import { PLAIN_SCOPE, catalogId, heldLocks, heldRows, lockKey, plainStatement, plainTable, reportWriteAhead, rowLockKey, rowLockStatement, scopedStatement, sendPlainAhead, sendWriteAhead, } from './postgresWriteAhead.js';
31
+ import { postgresRowEstimate } from './postgresCatalogRows.js';
32
+ import { describePostgresCatalog, postgresScopeStyle, SYSTEM_SCHEMAS, postgresColumnsOf, assertPostgresTable, } from './postgresCatalog.js';
33
+ import { postgresCatalogDigestOf, postgresCatalogDigestStatement } from './postgresCatalogDigest.js';
34
+ import { epochlessEpoch, SCHEMA_EPOCH_TABLE, schemaEpochOf, schemaEpochStatement, schemaMoved } from './postgresSchemaEpoch.js';
35
+ import { EpochCache } from './epochCache.js';
36
+ import { keepDatesAsText } from './postgresDates.js';
37
+ import { captureRowScope, snapshotRowScope } from '../shared/rowScope.js';
38
+ import { createScopedReads } from './scoped/scopedReads.js';
39
+ import { scopedCommandInvoker } from './scoped/scopedCommandOperations.js';
40
+ import { postgresPrivileges } from './rolePrivileges.js';
41
+ import { RESERVED_SCHEMAS, refusePostgresReserved, refuseReservedPlan, refuseReservedText } from './reservedSql.js';
42
+ import { statementCap } from './statementControl.js';
43
+ import { WriteLanes, keyedLane, lockTimedOut } from './writeLanes.js';
44
+ import { primaryReads } from './replicas.js';
45
+ import { readSnapshotOn } from './postgresReadSnapshot.js';
46
+ const pinnedReaders = new WeakMap();
47
+ /** Constructor-issued source identity, checked without reading receiver data. */
48
+ export const isPostgresVerifiedCommandSource = (value) => !!value && typeof value === 'object' && !isProxy(value) && pinnedReaders.has(value);
49
+ const SCOPED_CATALOG_DIGEST = postgresCatalogDigestStatement(SYSTEM_SCHEMAS);
50
+ /* Every adapter of one database in this process describes the same catalog, and a tenant App's start made a dozen
51
+ of them, each describing it afresh in a snapshot of its own: startup's two checks, its trial enrollment and the
52
+ host's, each read source, the first scoped transaction, every platform source twice — sixteen descriptions of
53
+ two databases, six round trips each, before the port opened. A description is kept here under the exact version
54
+ it was read at — the catalog digest read in its own snapshot, or the schema epoch — and any adapter of the same
55
+ database and schemas that reads the same version is handed a copy: the same version is the same catalog rows
56
+ (postgresCatalogDigest.ts), so nothing is trusted that a fresh description would not have said. A time-filed
57
+ version (epochlessEpoch) is never shared: it stands only for the adapter that took the risk.
58
+
59
+ A write reads its version, then describes, each statement seeing what had committed when it ran (READ COMMITTED):
60
+ it reads the version again and files the description only if that has not moved, so nothing is kept under a
61
+ version its description never saw. A snapshot describes the catalog its digest was read in, and files at once.
62
+
63
+ Two things a description carries move without the version: comments, and the planner's row estimates
64
+ (`approxRows`, which ANALYZE and autovacuum change, and which decide whether a large table's count is estimated,
65
+ resourceReadOperations.ts). A kept description is therefore served for a few minutes only, after which the next
66
+ reader describes again: a table that grew is counted as large a few minutes later rather than never, and a start,
67
+ whose readers come within seconds, still describes each catalog once. */
68
+ const sharedDescriptions = new EpochCache(32);
69
+ const SHARED_DESCRIPTION_MS = 5 * 60_000;
70
+ let descriptionsRead = 0, descriptionsKept = 0;
71
+ /** For the budget tests: how many times this process described a PostgreSQL catalog, and how many were found kept. */
72
+ export function postgresDescriptionCounts() {
73
+ return { described: descriptionsRead, kept: descriptionsKept };
74
+ }
75
+ /**
76
+ * An adapter on the manager every adapter of `url` with this `shape` shares (sharedPgConnections): its own catalog,
77
+ * lanes and stores, the pools of its neighbors. Closing it lets its share go; the pools close with the last one.
78
+ */
79
+ export function sharedPostgresAdapter(url, label, shape = {}) {
80
+ return new PostgresAdapter(url, label, [], sharedPgConnections(url, shape, keepDatesAsText));
81
+ }
82
+ /**
83
+ * Whether a statement sent ahead behind a write's BEGIN (writeAhead.ts) failed, so the transaction must begin again
84
+ * without them. Not when one waited out its lock (55P03): begun again, the transaction asked for the same lock and
85
+ * waited for it a second time, so a held row was answered `row_locked` after twice the lock timeout, ten seconds
86
+ * where five are documented (a live load test). That wait is the transaction's own answer, and it is thrown.
87
+ */
88
+ async function aheadsFailed(aheads) {
89
+ const settled = await Promise.allSettled(aheads);
90
+ const waited = settled.find((outcome) => outcome.status === 'rejected' && lockTimedOut(outcome.reason));
91
+ if (waited)
92
+ throw waited.reason;
93
+ return settled.some((outcome) => outcome.status === 'rejected');
94
+ }
95
+ export class PostgresAdapter {
96
+ label;
97
+ schemas;
98
+ dialect = 'postgres';
99
+ connections;
100
+ /* The order writes run in (writeLanes.ts): one at a time for the database
101
+ browser, by record for an App, each on a writer of its own. Raw SQL
102
+ waits for everything before it, in either. */
103
+ writes = new WriteLanes();
104
+ /* What a description is shared under (sharedDescriptions): the database, and the schemas this adapter describes. */
105
+ describes;
106
+ /* The database alone: what a store attestation is shared under (noteCatalogVersion), whatever schemas are described. */
107
+ database;
108
+ /* What a write transaction asks the catalog — the journal's layout, the
109
+ scope catalog, a relation's kind, its columns and key — kept under the
110
+ schema epoch the transaction read in the message that began it
111
+ (openWrite, postgresSchemaEpoch.ts). A warm command asks nothing. */
112
+ catalogCache = new EpochCache();
113
+ /** The epoch each open write transaction read, by the handle it runs on. */
114
+ txEpochs = new WeakMap();
115
+ /* Whether the database holds the epoch store: learned from the first
116
+ write transaction; absent, every transaction reads the digest as before. */
117
+ epochStore;
118
+ /** `work`, forgetting the kept catalog if it dies on a table or column that is gone: what was kept is wrong. */
119
+ watched(work) {
120
+ return work.catch((error) => {
121
+ if (schemaMoved(error)) {
122
+ this.catalogCache.clear();
123
+ sharedDescriptions.forget(this.describes);
124
+ }
125
+ throw error;
126
+ });
127
+ }
128
+ constructor(connectionString, label = redact(connectionString),
129
+ /** Restrict to these schemas. Empty means every non-system schema. */
130
+ schemas = [], connections,
131
+ /** The reader count the connection's config names; the process defaults fill the rest. */
132
+ pool) {
133
+ this.label = label;
134
+ this.schemas = schemas;
135
+ this.connections = connections ?? new PgConnectionManager(connectionString, keepDatesAsText, undefined, pool);
136
+ this.describes = `${connectionString}\0${schemas.join('\0')}`;
137
+ this.database = connectionString;
138
+ readsCatalogVersion(this, connectionString, async (db) => `digest:${postgresCatalogDigestOf(await db.query(SCOPED_CATALOG_DIGEST))}`);
139
+ if (this.connections instanceof PgConnectionManager)
140
+ pinnedReaders.set(this, this.connections);
141
+ /* The App stores this database may hold read and write through these (stores/appStores.ts). */
142
+ lendStoreHost(this, {
143
+ dialect: 'postgres',
144
+ withReadClient: (work) => this.connections.withReadClient(work),
145
+ withWriteClient: (work) => this.connections.withWriteClient(work),
146
+ attestedStore: (client, store, read) => this.attestedStore(client, store, read),
147
+ verifiedSource: () => this.verifiedSource(),
148
+ journalTransaction: (journal, run, options) => this.journalTransaction(journal, run, options),
149
+ readSnapshot: (run) => this.readSnapshot(run, true),
150
+ hasReplicas: () => this.connections.hasReplicas(),
151
+ onHealthyReplicas: (work) => this.connections.onHealthyReplicas(work),
152
+ });
153
+ }
154
+ /* Constructor-issued, over the connections it was built with: what a verified transaction is allowed to run on. */
155
+ verifiedSource() {
156
+ return isPostgresVerifiedCommandSource(this) && pinnedReaders.get(this) === this.connections;
157
+ }
158
+ /** The pools' meters, for the operator surface. */
159
+ poolStats() {
160
+ return this.connections.stats();
161
+ }
162
+ /** Each replica's state, when the connection names any (replicas.ts). */
163
+ replicaHealth() {
164
+ return this.connections.replicaHealth();
165
+ }
166
+ conn() {
167
+ return this.connections.read();
168
+ }
169
+ /**
170
+ * Run a statement the user wrote.
171
+ *
172
+ * The session already carries `default_transaction_read_only = on`, and for
173
+ * everything else in this adapter that is enough, because every statement is
174
+ * one this file built. It is **not** enough here: `SET
175
+ * default_transaction_read_only = off` is itself a statement, and a user who
176
+ * typed it followed by a `DELETE` would get both.
177
+ *
178
+ * `BEGIN READ ONLY` is the version that holds, for one statement. Postgres
179
+ * refuses `SET TRANSACTION READ WRITE` once the transaction has taken its
180
+ * first snapshot, and one statement takes it before it runs. It does not hold
181
+ * against several: `COMMIT; BEGIN READ WRITE; DELETE …` ends the read-only
182
+ * transaction and opens a writable one. So the text goes on the extended
183
+ * protocol (`queryMode: 'extended'`), where Postgres itself refuses a second
184
+ * statement; refuseStacked is the earlier, clearer refusal, not the guard.
185
+ * (node-postgres sends a query with an empty `values` on the simple protocol,
186
+ * which runs every statement in the string.) The `ROLLBACK` afterwards also
187
+ * discards any session state the statement set, so one run cannot change what
188
+ * the next one means.
189
+ *
190
+ * The rollback runs in a `finally`: a statement that errors has still opened
191
+ * a transaction, and leaving it open would leave the connection in an aborted
192
+ * state where every later query fails with "current transaction is aborted".
193
+ *
194
+ * `write: true` is the other half, and it is a different request rather than
195
+ * a relaxation of this one: a separate handle, no READ ONLY transaction, and
196
+ * a decision made further up about whether this connection may write at all.
197
+ * The two paths share the statement text and nothing else.
198
+ */
199
+ async runSql(request) {
200
+ const stacked = refuseStacked(request.text, 'postgres');
201
+ if (stacked)
202
+ throw new Error(stacked);
203
+ if (request.refuseReserved)
204
+ refusePostgresReserved(request.text, request.write);
205
+ const limit = clampLimit(request.limit);
206
+ /* A write is never wrapped in a bounding subquery: `UPDATE … RETURNING`
207
+ inside `SELECT * FROM (…)` is a different statement, and one Postgres
208
+ refuses outright. The caller asked for this text; it runs as typed. */
209
+ const bounded = !request.write && looksWrappable(request.text);
210
+ const text = bounded ? boundStatement(request.text, limit) : trimStatement(request.text);
211
+ if (request.write) {
212
+ /* On the write handle, and outside the READ ONLY transaction every other
213
+ statement here gets — which is the whole difference. Whether this is
214
+ allowed at all was decided before the request arrived: the connection
215
+ has to be marked writable in the config, and that check does not live
216
+ in the adapter.
217
+
218
+ No wrapper transaction of our own. One statement is already atomic in
219
+ Postgres, and a BEGIN/COMMIT around it would only add a way to leave a
220
+ transaction open on a connection that outlives the request. */
221
+ return this.writes.run('all', () => this.connections.withWriteClient(async (write) => {
222
+ const started = performance.now();
223
+ // Extended protocol: one statement, as on the read path below.
224
+ const result = await write.query({ text, values: [], rowMode: 'array', queryMode: 'extended' });
225
+ return {
226
+ /* A write that returns rows — `RETURNING` — is worth showing, and one
227
+ that does not returns an empty grid rather than a fabricated one.
228
+ Array rows, so two columns of one name keep both values. */
229
+ columns: dedupe(result.fields?.map((f) => f.name) ?? []),
230
+ rows: (result.rows ?? []).map((row) => row.map(valueSafe)),
231
+ ms: Math.round(performance.now() - started),
232
+ truncated: false,
233
+ bounded: false,
234
+ affected: Number(result.rowCount ?? 0),
235
+ sql: { text, params: [] },
236
+ };
237
+ }, true));
238
+ }
239
+ return this.connections.withReadClient(async (db) => {
240
+ const started = performance.now();
241
+ /* The statement's cap, set where it dies with the transaction, so the
242
+ session's own is untouched — and statementCap's floor stops a caller
243
+ asking for a timeout so low that even the fast path loses races to it. */
244
+ const cap = statementCap(request.timeoutMs);
245
+ const begin = () => db.query('BEGIN READ ONLY').then(() => db.query(`SET LOCAL statement_timeout = ${cap}`));
246
+ await begin();
247
+ try {
248
+ if (request.refuseReserved)
249
+ await refuseReservedPlan(db, request.text, []);
250
+ /* `rowMode: 'array'` so two output columns of the same name keep both
251
+ values; the default object rows would let the second overwrite the
252
+ first. `queryMode: 'extended'` is what carries exactly one statement:
253
+ an empty `values` alone leaves node-postgres on the simple protocol,
254
+ which would run a stacked COMMIT and a write after it. */
255
+ let wrapped = bounded;
256
+ const result = await db.query({ text, values: [], rowMode: 'array', queryMode: 'extended' }).catch(async (err) => {
257
+ /* The wrap is an optimisation that is allowed to fail — not every
258
+ legal statement survives being made a derived table. Run as
259
+ written and reported as unbounded. The transaction has to be
260
+ restarted: a failed statement aborts it, and every later query in
261
+ it would fail with "current transaction is aborted". A statement
262
+ that was stopped — cancelled, or past its cap (57014) — is not a
263
+ wrap that failed, and running it again would spend the cap twice. */
264
+ if (!bounded || err.code === '57014')
265
+ throw err;
266
+ wrapped = false;
267
+ await db.query('ROLLBACK');
268
+ await begin();
269
+ return db.query({ text: trimStatement(request.text), values: [], rowMode: 'array', queryMode: 'extended' });
270
+ });
271
+ const truncated = result.rows.length > limit;
272
+ return {
273
+ columns: dedupe(result.fields.map((f) => f.name)),
274
+ rows: (truncated ? result.rows.slice(0, limit) : result.rows).map((row) => row.map(valueSafe)),
275
+ ms: Math.round(performance.now() - started),
276
+ truncated,
277
+ bounded: wrapped,
278
+ sql: { text: wrapped ? text : trimStatement(request.text), params: [] },
279
+ };
280
+ }
281
+ finally {
282
+ await db.query('ROLLBACK').catch(() => {
283
+ /* The connection is already unusable if this fails; the original error
284
+ is the one worth reporting. */
285
+ });
286
+ }
287
+ }, true);
288
+ }
289
+ /**
290
+ * EXPLAIN, plain — never the analysing variant that executes to time.
291
+ *
292
+ * `runSql`'s bounding wrap is precisely wrong here: a statement made a
293
+ * derived table is a different statement, with a different plan. The text
294
+ * goes to the planner as written, inside the same READ ONLY transaction
295
+ * every user statement gets — so even a smuggled write is only ever
296
+ * planned, and an execution attempt is the transaction's to refuse, not a
297
+ * string check's.
298
+ */
299
+ async explainSql(request) {
300
+ const stacked = refuseStacked(request.text, 'postgres');
301
+ if (stacked)
302
+ throw new Error(stacked);
303
+ const analyze = refuseAnalyze(request.text);
304
+ if (analyze)
305
+ throw new Error(analyze);
306
+ if (request.refuseReserved)
307
+ refuseReservedText(request.text, 'postgres');
308
+ return this.connections.withReadClient(async (db) => {
309
+ const started = performance.now();
310
+ await db.query('BEGIN READ ONLY');
311
+ try {
312
+ /* Planning runs nothing, but planning a wide join still takes time. */
313
+ await db.query(`SET LOCAL statement_timeout = ${statementCap()}`);
314
+ if (request.refuseReserved)
315
+ await refuseReservedPlan(db, request.text, (request.params ?? []));
316
+ const result = await db.query({
317
+ text: `EXPLAIN ${trimStatement(request.text)}`,
318
+ values: (request.params ?? []),
319
+ rowMode: 'array',
320
+ // One statement, whether or not there are parameters: see runSql.
321
+ queryMode: 'extended',
322
+ });
323
+ return {
324
+ plan: result.rows.map((r) => String(r[0])),
325
+ ms: Math.round(performance.now() - started),
326
+ };
327
+ }
328
+ finally {
329
+ await db.query('ROLLBACK').catch(() => { });
330
+ }
331
+ }, true);
332
+ }
333
+ /**
334
+ * The planner's own statistics, read rather than computed.
335
+ *
336
+ * `pg_stats` already holds the null share, the distinct estimate, the most
337
+ * common values with their frequencies, and the histogram — ANALYZE paid
338
+ * for them, reading them touches no user table. The numbers are
339
+ * sample-based and stale until the next ANALYZE, which is what
340
+ * `source: 'statistics'` tells the caller; a column ANALYZE has never
341
+ * visited simply has no numbers, which beats invented ones.
342
+ */
343
+ async profile(table) {
344
+ const { schema, name } = await this.readTable(table);
345
+ const db = await this.conn();
346
+ const started = performance.now();
347
+ const rel = await db.query(`SELECT CASE WHEN c.reltuples < 0 THEN NULL ELSE c.reltuples END AS approx_rows
348
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
349
+ WHERE n.nspname = $1 AND c.relname = $2`, [schema, name]);
350
+ const approx = rel.rows[0]?.approx_rows;
351
+ const rows = postgresRowEstimate(approx);
352
+ /* Every live column, with its stats row where ANALYZE has made one.
353
+ `most_common_vals` and `histogram_bounds` are `anyarray`, which the
354
+ driver has no parser for; the ::text::text[] two-step turns them into
355
+ the text array it can parse. */
356
+ const stats = await db.query(`SELECT a.attname::text AS column,
357
+ format_type(a.atttypid, a.atttypmod) AS type,
358
+ s.null_frac,
359
+ s.n_distinct,
360
+ s.most_common_vals::text::text[] AS common_values,
361
+ s.most_common_freqs AS common_freqs,
362
+ s.histogram_bounds::text::text[] AS bounds
363
+ FROM pg_attribute a
364
+ JOIN pg_class c ON c.oid = a.attrelid
365
+ JOIN pg_namespace n ON n.oid = c.relnamespace
366
+ LEFT JOIN pg_stats s ON s.schemaname = n.nspname AND s.tablename = c.relname AND s.attname = a.attname
367
+ WHERE n.nspname = $1 AND c.relname = $2 AND a.attnum > 0 AND NOT a.attisdropped
368
+ ORDER BY a.attnum`, [schema, name]);
369
+ const columns = stats.rows.map((r) => {
370
+ /* Negative n_distinct is a ratio — "-0.3 of the rows are distinct" —
371
+ which only converts when a row estimate exists to multiply by. */
372
+ const distinct = r.n_distinct == null
373
+ ? undefined
374
+ : Number(r.n_distinct) >= 0
375
+ ? Math.round(Number(r.n_distinct))
376
+ : rows === undefined
377
+ ? undefined
378
+ : Math.round(-Number(r.n_distinct) * rows);
379
+ const common = r.common_values?.length && r.common_freqs?.length
380
+ ? r.common_values.map((v, i) => ({ value: v, frac: Number(r.common_freqs?.[i] ?? 0) }))
381
+ : undefined;
382
+ return {
383
+ column: r.column,
384
+ type: r.type,
385
+ nullFrac: r.null_frac == null ? undefined : Number(r.null_frac),
386
+ distinct,
387
+ /* The histogram's outer edges, as text from the sample. A column too
388
+ uniform to earn a histogram gets no min/max — its common values
389
+ sorted lexically would call 9 larger than 10. */
390
+ min: r.bounds?.length ? r.bounds[0] : undefined,
391
+ max: r.bounds?.length ? r.bounds[r.bounds.length - 1] : undefined,
392
+ common,
393
+ };
394
+ });
395
+ return { table, rows, columns, source: 'statistics', ms: Math.round(performance.now() - started) };
396
+ }
397
+ /* The catalog is the primary's, whatever route asks for it first: a
398
+ replica a migration has not reached yet would describe the old one, and
399
+ every read after compiles against this copy. */
400
+ introspect() {
401
+ return primaryReads(() => this.introspectNow());
402
+ }
403
+ async introspectNow() {
404
+ const db = await this.conn();
405
+ const schema = await this.describe(db);
406
+ /* The server's version, read with the catalog it goes with, so a row
407
+ scope compiles for it (scopeReads) without a statement of its own. */
408
+ this.scopeStyleRead = postgresScopeStyle(db).catch(() => POSTGRES_STYLE);
409
+ await this.scopeStyleRead;
410
+ /* Seeded, not only returned: the registry introspects on connect, and the
411
+ view, breakdown and read paths resolve against this copy. Without it the
412
+ first of them described the whole catalog again. */
413
+ this.cachedSchema = schema;
414
+ return schema;
415
+ }
416
+ scopeStyleRead;
417
+ /**
418
+ * The style a row-scoped read compiles with on this server: its CTEs
419
+ * inlined from Postgres 12 on (POSTGRES_INLINE_STYLE). Asked once per
420
+ * adapter; a failed ask is not remembered, and that read compiles as
421
+ * before — the hint is a plan, never a rule about rows.
422
+ */
423
+ scopeStyle() {
424
+ this.scopeStyleRead ??= primaryReads(() => this.conn().then(postgresScopeStyle)).catch(() => {
425
+ this.scopeStyleRead = undefined;
426
+ return POSTGRES_STYLE;
427
+ });
428
+ return this.scopeStyleRead;
429
+ }
430
+ /** The role's reach, asked of the catalog on the reader (rolePrivileges.ts). */
431
+ async privileges() {
432
+ return primaryReads(async () => postgresPrivileges(await this.conn(), this.schemas, SYSTEM_SCHEMAS));
433
+ }
434
+ /**
435
+ * Each table's triggers, read as a scoped write reads them on its writer. On
436
+ * a writer, inside a transaction rolled back: the proof has PostgreSQL parse
437
+ * each condition into a temporary view (postgresTriggers.ts), which a
438
+ * read-only transaction may not make. Without a writer nothing with a
439
+ * condition is proven, and such a trigger is then said to block.
440
+ */
441
+ async triggers() {
442
+ const schema = await this.introspect();
443
+ const tables = schema.tables.filter((table) => !table.isView);
444
+ // Triggers, and the code a write runs that is not one (a CHECK, a default, a domain calling a function of the database's).
445
+ const read = async (db, analyzer) => {
446
+ const triggers = await postgresTriggersByTable((await db.query(postgresTriggerStatement(false))).rows, analyzer);
447
+ const code = await readPostgresTableCode(db, tables);
448
+ return (key) => [...(triggers.get(key)?.triggers ?? []), ...(code.get(key) ?? [])];
449
+ };
450
+ const byTable = await this.connections
451
+ .withWriteClient(async (write) => {
452
+ await write.query('BEGIN');
453
+ try {
454
+ return await read(write, postgresTriggerAnalyzer(write));
455
+ }
456
+ finally {
457
+ await write.query('ROLLBACK');
458
+ }
459
+ })
460
+ .catch(() => primaryReads(async () => read(await this.conn(), undefined)));
461
+ const found = new Map();
462
+ for (const table of tables) {
463
+ const triggers = byTable(`${table.schema}.${table.name}`);
464
+ if (triggers.length)
465
+ found.set(table.id, triggers);
466
+ }
467
+ return found;
468
+ }
469
+ /**
470
+ * What a write reads of `tables` to judge a trigger's effects (postgresScopeCatalog.ts effectCatalogFacts): their
471
+ * keys, which are in a partition or inheritance hierarchy, and which a scoped write cannot target. On a writer where there is one,
472
+ * inside a transaction rolled back, so the privileges read are the writer's, as `triggers` reads.
473
+ */
474
+ async triggerKeys(tables) {
475
+ return this.connections
476
+ .withWriteClient(async (write) => {
477
+ await write.query('BEGIN');
478
+ try {
479
+ return await effectCatalogFacts(write, tables);
480
+ }
481
+ finally {
482
+ await write.query('ROLLBACK');
483
+ }
484
+ })
485
+ .catch(() => primaryReads(async () => effectCatalogFacts(await this.conn(), tables)));
486
+ }
487
+ /** The catalog as one handle sees it, read by postgresCatalog.ts: the
488
+ * reader on connect, or the leased writer inside a scoped transaction,
489
+ * where the same description is the evidence the deployed permissions are
490
+ * attested against. */
491
+ /* Still `async`: a caller holding this as a value gets a rejected promise
492
+ rather than a synchronous throw, exactly as the method it replaced did. */
493
+ async describe(db) {
494
+ descriptionsRead++;
495
+ return describePostgresCatalog(db, { schemas: this.schemas, label: this.label, dialect: this.dialect });
496
+ }
497
+ /** The catalog as `db` sees it at `version`, read there before: a copy of the one kept under it (sharedDescriptions),
498
+ * or described now and kept. Another adapter's copy carries this one's label. */
499
+ async describedAt(version, db, reread) {
500
+ const shared = !version.startsWith('ttl:');
501
+ const found = shared ? sharedDescriptions.get(version, this.describes) : undefined;
502
+ const kept = found && Date.now() - found.at < SHARED_DESCRIPTION_MS
503
+ ? found.schema
504
+ : shared
505
+ ? undefined
506
+ : this.catalogCache.get(version, 'describe');
507
+ if (kept) {
508
+ if (shared)
509
+ descriptionsKept++;
510
+ return { ...structuredClone(kept), label: this.label };
511
+ }
512
+ const schema = await this.describe(db);
513
+ // A write's version is read again: a description that saw DDL committed after it is not kept under it.
514
+ if (shared) {
515
+ if (!reread || (await reread()) === version)
516
+ sharedDescriptions.set(version, this.describes, Object.freeze({ schema: Object.freeze(structuredClone(schema)), at: Date.now() }));
517
+ }
518
+ else
519
+ this.catalogCache.set(version, 'describe', Object.freeze(structuredClone(schema)));
520
+ return schema;
521
+ }
522
+ /** A snapshot's description: the digest first, in the same snapshot, then the description kept under it or a new one. */
523
+ async describeSnapshot(db, committed = false) {
524
+ const version = `digest:${postgresCatalogDigestOf(await db.query(SCOPED_CATALOG_DIGEST))}`;
525
+ const reread = committed ? this.rereadOf(db, version) : undefined;
526
+ return this.describedAt(this.versionRead(db, version, reread), db, reread);
527
+ }
528
+ /** `version`, the exact one `db`'s transaction just read, said for what it attests next (noteCatalogVersion); a time-filed one is not said. */
529
+ versionRead(db, version, reread) {
530
+ if (!version.startsWith('ttl:'))
531
+ noteCatalogVersion(db, this.database, version, reread);
532
+ return version;
533
+ }
534
+ /** How a write (READ COMMITTED) reads `version` again, the digest or the epoch as it read it; a time-filed one is not read. */
535
+ rereadOf(db, version) {
536
+ if (version.startsWith('ttl:'))
537
+ return undefined;
538
+ if (version.startsWith('digest:'))
539
+ return async () => `digest:${postgresCatalogDigestOf(await db.query(SCOPED_CATALOG_DIGEST))}`;
540
+ return async () => schemaEpochOf(await db.query(schemaEpochStatement()));
541
+ }
542
+ /**
543
+ * The catalog as a scoped transaction's writer sees it, described again
544
+ * only when it has moved. Every transaction reads the catalog digest
545
+ * (postgresCatalogDigest.ts) — one statement where a description is six —
546
+ * and reuses a description read just after the same digest was, by this
547
+ * adapter or another of the same database (sharedDescriptions). Read
548
+ * before, never after: DDL committing
549
+ * between the two then leaves a digest no later read can match, so the
550
+ * description is taken again rather than trusted on a digest it postdates.
551
+ * The digest covers every schema but the system's, a superset of what
552
+ * this adapter describes, and moves with privileges and roles too. What it
553
+ * does not see, comments and the planner's row estimates, is display and
554
+ * never authority.
555
+ */
556
+ async describeScoped(db) {
557
+ // Under an epoch this transaction read, a description kept under it, by any adapter of this database, is exact.
558
+ const epoch = this.txEpochs.get(db);
559
+ return epoch !== undefined ? this.describedAt(epoch, db, this.rereadOf(db, epoch)) : this.describeSnapshot(db, true);
560
+ }
561
+ /**
562
+ * Begin a write transaction and read the schema epoch in the same message:
563
+ * `BEGIN`, the LOCK a scope pinned last time under the epoch it expects,
564
+ * and the epoch statement, in one round trip (the simple protocol carries
565
+ * several statements when none has parameters). The LOCK comes first, so
566
+ * DDL on a pinned table after the epoch was read has to wait for this
567
+ * transaction; whether the lock was the right one is then decided by the
568
+ * epoch alone. A message that fails — the store gone, a pinned table
569
+ * dropped, a privilege revoked — is only a miss: rolled back, begun again
570
+ * plainly, and the transaction describes what it needs as before.
571
+ */
572
+ async openWrite(write, options, began) {
573
+ const begin = beginOf(write) + (options.session ?? '');
574
+ // Begun again on the same handle (a scope's retry), what the last transaction read is not this one's.
575
+ noteCatalogVersion(write, this.database, undefined);
576
+ if (this.epochStore === false) {
577
+ if (options.digest)
578
+ return this.openWithDigest(write, options, began);
579
+ const opening = write.query(begin);
580
+ options.sent?.();
581
+ await opening;
582
+ began();
583
+ const epoch = epochlessEpoch();
584
+ this.txEpochs.set(write, epoch);
585
+ return { epoch };
586
+ }
587
+ const statement = schemaEpochStatement();
588
+ let answered;
589
+ try {
590
+ const opening = write.query(`${begin};${options.lock?.length ? ` LOCK TABLE ${options.lock.join(', ')} IN ROW EXCLUSIVE MODE;` : ''}${options.pin ? ` ${options.pin};` : ''} ${statement}`);
591
+ // Behind it, in the same flight: what the transaction opens with (sendWriteAhead).
592
+ options.sent?.();
593
+ answered = await opening;
594
+ }
595
+ catch (error) {
596
+ const failure = error;
597
+ if ((failure.code === '42P01' || failure.code === '42501') && String(failure.message).includes(SCHEMA_EPOCH_TABLE))
598
+ this.epochStore = false;
599
+ try {
600
+ await write.query('ROLLBACK');
601
+ }
602
+ catch {
603
+ /* The BEGIN below says whether this client can go on. */
604
+ }
605
+ if (this.epochStore === false && options.digest)
606
+ return this.openWithDigest(write, options, began);
607
+ await write.query(begin);
608
+ began();
609
+ return {};
610
+ }
611
+ began();
612
+ this.epochStore = true;
613
+ const results = (Array.isArray(answered) ? answered : [answered]);
614
+ const last = results.at(-1);
615
+ const epoch = schemaEpochOf(last);
616
+ if (epoch !== undefined)
617
+ this.txEpochs.set(write, this.versionRead(write, epoch, this.rereadOf(write, epoch)));
618
+ // The store is there but not whole (its trigger disabled): the digest stands in, read after the LOCK above.
619
+ else if (options.digest) {
620
+ const read = `digest:${postgresCatalogDigestOf(await write.query(SCOPED_CATALOG_DIGEST))}`;
621
+ const digest = this.versionRead(write, read, this.rereadOf(write, read));
622
+ this.txEpochs.set(write, digest);
623
+ return { epoch: digest };
624
+ }
625
+ return { epoch };
626
+ }
627
+ /**
628
+ * Without the epoch store, a scoped transaction reads the catalog digest
629
+ * (postgresCatalogDigest.ts) — it always did, to describe the scope — and
630
+ * the digest is then its epoch: one statement that moves with every catalog
631
+ * row the scope, a relation's kind and columns, and the journal's layout
632
+ * depend on, role membership, and (for a command) the journal's meta row.
633
+ * Read in the message that begins the transaction, after the LOCK the scope
634
+ * pinned last time, as the epoch is. Slower than the epoch store's one row,
635
+ * never less exact; a message that fails begins again the long way.
636
+ */
637
+ async openWithDigest(write, options, began) {
638
+ const begin = beginOf(write) + (options.session ?? '');
639
+ let answered;
640
+ try {
641
+ const opening = write.query(`${begin};${options.lock?.length ? ` LOCK TABLE ${options.lock.join(', ')} IN ROW EXCLUSIVE MODE;` : ''}${options.pin ? ` ${options.pin};` : ''} ${SCOPED_CATALOG_DIGEST}`);
642
+ options.sent?.();
643
+ answered = await opening;
644
+ }
645
+ catch {
646
+ try {
647
+ await write.query('ROLLBACK');
648
+ }
649
+ catch {
650
+ /* The BEGIN below says whether this client can go on. */
651
+ }
652
+ await write.query(begin);
653
+ began();
654
+ return {};
655
+ }
656
+ began();
657
+ const results = (Array.isArray(answered) ? answered : [answered]);
658
+ const read = `digest:${postgresCatalogDigestOf(results.at(-1))}`;
659
+ const epoch = this.versionRead(write, read, this.rereadOf(write, read));
660
+ this.txEpochs.set(write, epoch);
661
+ return { epoch };
662
+ }
663
+ /**
664
+ * A reserved store's layout, attested the first time this adapter reads it
665
+ * and not again (attestOnce, postgresTransactionHandle.ts): told whether it
666
+ * stands attested. A read that fails the way a moved catalog fails one
667
+ * forgets it, and the next read attests in full.
668
+ */
669
+ async attestedStore(client, store, read) {
670
+ const key = `store:${store.name}`, attested = attestedOn(this, key);
671
+ try {
672
+ const result = await read(attested);
673
+ if (!attested)
674
+ keepAttestedOn(this, key);
675
+ return result;
676
+ }
677
+ catch (error) {
678
+ if (suspectsStores(error))
679
+ forgetAttestations(this, client);
680
+ throw error;
681
+ }
682
+ }
683
+ /** A journal's layout and meta row, attested the first time this adapter opens a transaction with it (a journal
684
+ that names no meta row, in every transaction). */
685
+ async attestJournal(write, journal) {
686
+ if (!journal.meta)
687
+ return void (await journal.attest(write));
688
+ const key = `journal:${journal.meta.name}`;
689
+ if (attestedOn(this, key))
690
+ return;
691
+ await journal.attest(write);
692
+ keepAttestedOn(this, key);
693
+ }
694
+ async query(request) {
695
+ return this.queryOn(request, await this.conn(), true);
696
+ }
697
+ async scopeReads(input) {
698
+ // Capture before metadata I/O: callers cannot change an in-flight policy.
699
+ const scope = captureRowScope(input);
700
+ const schema = await this.schema();
701
+ /* Inlined only where the catalog read at connect said the server can;
702
+ otherwise as before. Never a statement here: a scoped read's I/O is
703
+ its own reads (tenant sources ask scopeStyle() once, at construction). */
704
+ const style = this.scopeStyleRead ? await this.scopeStyleRead : POSTGRES_STYLE;
705
+ return createScopedReads(schema, scope, style, async (compiled, hint) => {
706
+ // Resolve the reader per operation so capabilities cannot bypass shutdown.
707
+ const db = await this.conn();
708
+ const started = performance.now();
709
+ const result = await db.query(compiled.text, compiled.params);
710
+ return {
711
+ columns: result.fields.map((field) => field.name),
712
+ rows: result.rows.map(hint?.binary ? withBytes : toJsonSafe),
713
+ ms: Math.round(performance.now() - started),
714
+ sql: { text: compiled.text, params: compiled.params },
715
+ };
716
+ });
717
+ }
718
+ async queryOn(request, db, read = false) {
719
+ const { schema, name } = read ? await this.readTable(request.table) : await this.assertTable(request.table, db);
720
+ const qualified = `${POSTGRES_STYLE.quote(schema)}.${POSTGRES_STYLE.quote(name)}`;
721
+ const where = buildWhere(request.filter, POSTGRES_STYLE);
722
+ const cols = request.columns?.length ? request.columns.map((c) => POSTGRES_STYLE.quote(c)).join(', ') : '*';
723
+ const order = orderClause(request.orderBy, request.orderBy?.length ? (await this.schema()).tables.find((t) => t.id === request.table) : undefined, POSTGRES_STYLE, where.params.length + 1);
724
+ /* Every read is bounded. There is no code path that reaches the database
725
+ without a LIMIT, including one that forgot to ask for one. */
726
+ const limit = clampLimit(request.limit);
727
+ /* LIMIT and OFFSET continue the placeholder numbering the WHERE clause
728
+ started, which is the one thing Postgres needs that SQLite does not. */
729
+ const n = where.params.length + order.params.length;
730
+ const text = `SELECT ${cols} FROM ${qualified}${where.text}${order.text} LIMIT $${n + 1} OFFSET $${n + 2}`;
731
+ const params = [...where.params, ...order.params, limit, clampOffset(request.offset)];
732
+ const started = performance.now();
733
+ const result = await db.query(text, params);
734
+ const ms = Math.round(performance.now() - started);
735
+ return {
736
+ // Taking columns from `fields` rather than the first row means an empty
737
+ // result still renders its headers instead of collapsing to nothing.
738
+ columns: result.fields.map((f) => f.name),
739
+ rows: result.rows.map(request.binary ? withBytes : toJsonSafe),
740
+ ms,
741
+ sql: { text, params },
742
+ };
743
+ }
744
+ /**
745
+ * Run a compiled view.
746
+ *
747
+ * Note what is *not* here: any check that the tables named in the view
748
+ * exist. `compileView` resolves the base table and every hop against the
749
+ * introspected catalog and refuses anything it cannot find, so the only
750
+ * identifiers that reach the quoting step are ones the catalog produced.
751
+ * The user's contribution — the values — never leaves the parameter array.
752
+ *
753
+ * The dialect difference this exercises is placeholder numbering:
754
+ * `POSTGRES_STYLE` counts $1..$n across the whole statement, and the joins
755
+ * sitting between the SELECT list and the WHERE clause are exactly what
756
+ * makes an off-by-one here easy and invisible.
757
+ */
758
+ async runView(view, offset = 0) {
759
+ const db = await this.conn();
760
+ const schema = await this.schema();
761
+ const compiled = compileView(schema, view, POSTGRES_STYLE, offset);
762
+ const started = performance.now();
763
+ const result = await db.query(compiled.text, compiled.params);
764
+ const ms = Math.round(performance.now() - started);
765
+ return {
766
+ columns: compiled.columns.map((c) => c.name),
767
+ rows: result.rows.map(toJsonSafe),
768
+ ms,
769
+ sql: { text: compiled.text, params: compiled.params },
770
+ resolved: compiled.columns,
771
+ joins: compiled.joins,
772
+ };
773
+ }
774
+ async runBreakdown(breakdown, offset = 0) {
775
+ const db = await this.conn();
776
+ const compiled = compileBreakdown(await this.schema(), breakdown, POSTGRES_STYLE, offset);
777
+ const started = performance.now();
778
+ const result = await db.query(compiled.text, compiled.params);
779
+ return {
780
+ columns: compiled.columns.map((c) => c.name),
781
+ rows: result.rows.map(toJsonSafe),
782
+ ms: Math.round(performance.now() - started),
783
+ sql: { text: compiled.text, params: compiled.params },
784
+ resolved: compiled.columns,
785
+ };
786
+ }
787
+ async countBreakdown(breakdown, limit) {
788
+ const db = await this.conn();
789
+ const compiled = compileBreakdownCount(await this.schema(), breakdown, POSTGRES_STYLE, undefined, limit);
790
+ const result = await db.query(compiled.text, compiled.params);
791
+ return Number(result.rows[0]?.n ?? 0);
792
+ }
793
+ async countView(view, limit) {
794
+ const db = await this.conn();
795
+ const compiled = compileViewCount(await this.schema(), view, POSTGRES_STYLE, undefined, limit);
796
+ const result = await db.query(compiled.text, compiled.params);
797
+ return Number(result.rows[0]?.n ?? 0);
798
+ }
799
+ /* Introspection here is three catalog queries; a view preview runs on every
800
+ keystroke. Caching it is the difference between a live preview and a
801
+ stutter. The registry refreshes by discarding the adapter, so a stale
802
+ cache cannot outlive an explicit reload. */
803
+ cachedSchema = null;
804
+ async schema() {
805
+ if (!this.cachedSchema)
806
+ this.cachedSchema = await this.introspect();
807
+ return this.cachedSchema;
808
+ }
809
+ /**
810
+ * The planner's row estimate, straight from `pg_class`.
811
+ *
812
+ * `reltuples` is what the planner itself uses to decide how to run a query,
813
+ * so it is the number Postgres is already trusting. It is -1 on a table that
814
+ * has never been analysed, which is a "do not know" rather than a zero —
815
+ * returning undefined there gets an exact count instead of confidently
816
+ * reporting an empty table that is not empty.
817
+ */
818
+ async estimateCount(table) {
819
+ const db = await this.conn();
820
+ const { schema, name } = await this.readTable(table);
821
+ const result = await db.query(`SELECT c.reltuples AS n
822
+ FROM pg_class c JOIN pg_namespace ns ON ns.oid = c.relnamespace
823
+ WHERE ns.nspname = $1 AND c.relname = $2`, [schema, name]);
824
+ return postgresRowEstimate(result.rows[0]?.n);
825
+ }
826
+ async count(table, filter, limit) {
827
+ return this.countOn(table, filter, await this.conn(), limit, true);
828
+ }
829
+ async aggregate(request) {
830
+ return this.aggregateOn(request, await this.conn());
831
+ }
832
+ async countEach(items, limit) {
833
+ const relations = await Promise.all(items.map(async (item) => {
834
+ const { schema, name } = await this.readTable(item.table);
835
+ return { relation: `${POSTGRES_STYLE.quote(schema)}.${POSTGRES_STYLE.quote(name)}`, filter: item.filter };
836
+ }));
837
+ const statement = countEachStatement(relations, POSTGRES_STYLE, { limit, together: countsTogether(this.cachedSchema, items, limit) });
838
+ const result = await (await this.conn()).query(statement.text, statement.params);
839
+ return countEachRows(result.rows, items.length);
840
+ }
841
+ async countOn(table, filter, db, limit, read = false) {
842
+ const { schema, name } = read ? await this.readTable(table) : await this.assertTable(table, db);
843
+ const where = buildWhere(filter, POSTGRES_STYLE);
844
+ const text = countStatement(`${POSTGRES_STYLE.quote(schema)}.${POSTGRES_STYLE.quote(name)}${where.text}`, limit);
845
+ const result = await db.query(text, where.params);
846
+ return Number(result.rows[0]?.n ?? 0);
847
+ }
848
+ /* A command's aggregate on its own transaction's client (shared/aggregate.ts): one statement over the table as
849
+ `countOn` names it, its numeric and bigint answers the exact text the driver reads them as. */
850
+ async aggregateOn(request, db) {
851
+ const { schema: namespace, name } = await this.assertTable(request.table, db);
852
+ const catalog = await this.schema();
853
+ const compiled = compileAggregate(catalog, { ...request, table: `${namespace}.${name}` }, POSTGRES_STYLE);
854
+ const result = await db.query(compiled.text, compiled.params);
855
+ return { rows: result.rows.map(toJsonSafe) };
856
+ }
857
+ async columnsOf(schema, name, db) {
858
+ return postgresColumnsOf(schema, name, db, this.epochOf(db), this.catalogCache, () => this.conn());
859
+ }
860
+ /**
861
+ * Update one row, having proved it is one row.
862
+ *
863
+ * The pre-flight count runs on the *read* handle, so the check that decides
864
+ * whether to write cannot itself write. A key that matches anything other
865
+ * than exactly one row stops here rather than at the UPDATE — the danger in
866
+ * a cell editor was never injection, it is a WHERE broader than its author
867
+ * believed.
868
+ */
869
+ async update(request) {
870
+ // A table that keeps a history is written with its row, or not at all.
871
+ const lane = keyedLane(request);
872
+ if (this.recordsHistory(request))
873
+ return this.transact(lane, (tx) => tx.update(request));
874
+ return this.watched(this.writes.run(lane, () => this.connections.withWriteClient((write) => this.updateNow(request, write))));
875
+ }
876
+ async updateNow(request, write, read) {
877
+ const transactional = read !== undefined;
878
+ read ??= await this.conn();
879
+ const found = await this.assertTable(request.table, read);
880
+ const id = `${found.schema}.${found.name}`;
881
+ /* Postgres updates through a simple view, and the update lands on the
882
+ table underneath. Refused: what the editor showed and what changed are
883
+ then two different objects. */
884
+ if (found.isView)
885
+ throw new Refusal(`${id} is a view, so no single row can be identified.`);
886
+ const meta = await this.columnsOf(found.schema, found.name, read);
887
+ const pk = meta.filter((c) => c.is_pk).map((c) => c.name);
888
+ if (!pk.length)
889
+ throw new Refusal(`${id} has no primary key, so no single row can be identified.`);
890
+ const keyColumns = Object.keys(request.key);
891
+ /* The key must be the whole primary key and nothing else. A partial key
892
+ would let a two-column key match a whole group of rows, and extra
893
+ columns would let the caller widen the match. */
894
+ const same = keyColumns.length === pk.length && pk.every((c) => keyColumns.includes(c));
895
+ if (!same)
896
+ throw new Refusal(`Updating ${id} needs exactly its primary key (${pk.join(', ')}).`);
897
+ const entries = Object.entries(request.values ?? {});
898
+ if (!entries.length)
899
+ throw new Refusal('Nothing to update.');
900
+ const applied = {};
901
+ for (const [column, raw] of entries) {
902
+ const declared = meta.find((c) => c.name === column);
903
+ if (!declared)
904
+ throw new Refusal(`${id} has no column called "${column}".`);
905
+ if (pk.includes(column)) {
906
+ // Editing a key in place silently repoints every row that referenced
907
+ // it, or fails on the constraint. Neither belongs behind an editor.
908
+ throw new Refusal(`"${column}" is part of the primary key and cannot be edited here.`);
909
+ }
910
+ /* Coerced against the declared type, because everything typed into a
911
+ text box arrives as a string — and Postgres, unlike SQLite, rejects
912
+ "17901" for a numeric column rather than quietly taking it. */
913
+ applied[column] = coerceForColumn(declared.written || declared.type || '', raw);
914
+ if (applied[column] === null && declared.notnull) {
915
+ throw new Refusal(`"${column}" is NOT NULL and cannot be emptied.`);
916
+ }
917
+ }
918
+ const filter = {
919
+ groups: [pk.map((column) => ({ column, op: '=', value: request.key[column] }))],
920
+ };
921
+ /* Outside a transaction the count runs first, on the read handle. Inside
922
+ one the UPDATE's own row count is the check: the key is the whole
923
+ primary key, so it matches one row or none, and a refusal rolls the
924
+ transaction back. */
925
+ const refuseMatches = (matches) => {
926
+ if (request.expected !== undefined && matches === 0)
927
+ throw new WriteConflict();
928
+ throw new Refusal(`Refused: that key matches ${matches} rows, not 1. An update is only allowed when it is certain which row it changes.`);
929
+ };
930
+ const matches = transactional ? 1 : await this.count(id, filter);
931
+ if (matches !== 1)
932
+ refuseMatches(matches);
933
+ /* The WHERE is built after the SET, so its placeholders continue the same
934
+ numbering — `$1, $2` for the assignments, `$3…` for the key. Postgres
935
+ numbers parameters rather than taking them in order, which is the one
936
+ place this differs from the other two adapters. */
937
+ const columns = Object.keys(applied);
938
+ const assignments = columns.map((c, i) => `${POSTGRES_STYLE.quote(c)} = ${POSTGRES_STYLE.placeholder(i + 1)}`).join(', ');
939
+ const where = buildWhere(filter, POSTGRES_STYLE, columns.length + 1);
940
+ const guard = buildUpdateGuard(request, Object.fromEntries(meta.map((column) => [column.name, column.type])), POSTGRES_STYLE, 'postgres', columns.length + where.params.length + 1);
941
+ const text = `UPDATE ${qualified(found)} SET ${assignments}${where.text}${guard.text}`;
942
+ const params = [...Object.values(applied), ...where.params, ...guard.params];
943
+ const result = await write.query(text, params);
944
+ if (request.expected !== undefined && Number(result.rowCount ?? 0) === 0)
945
+ throw new WriteConflict();
946
+ if (transactional && Number(result.rowCount ?? 0) !== 1)
947
+ refuseMatches(Number(result.rowCount ?? 0));
948
+ /* Postgres counts rows matched, not rows whose bytes changed, so saving a
949
+ cell without changing its value still reports 1 — the editor would
950
+ otherwise tell the user a successful write failed. */
951
+ return { affected: Number(result.rowCount ?? 0), applied, sql: { text, params } };
952
+ }
953
+ /**
954
+ * Add one row.
955
+ *
956
+ * `update`'s guards where they apply, with the key rules inverted: a primary
957
+ * key may be supplied (a country code somebody types) or left for the
958
+ * database to assign. What is deliberately *not* pre-checked is
959
+ * completeness — a missing NOT NULL column with no default is the database's
960
+ * refusal to make, and its message names the column better than a paraphrase
961
+ * would.
962
+ *
963
+ * `RETURNING *` rather than a re-read by key: one statement gives back the
964
+ * row as stored, defaults filled and the assigned key included, with no
965
+ * window for another write to land in between.
966
+ */
967
+ async insert(request) {
968
+ // A new row has no lane of its own: nothing earlier can be writing it.
969
+ if (this.recordsHistory(request))
970
+ return this.transact([], (tx) => tx.insert(request));
971
+ return this.watched(this.writes.run([], () => this.connections.withWriteClient((write) => this.insertNow(request, write))));
972
+ }
973
+ async insertNow(request, write, read, scoped = false) {
974
+ read ??= await this.conn();
975
+ const found = await this.assertTable(request.table, read);
976
+ const id = `${found.schema}.${found.name}`;
977
+ if (found.isView)
978
+ throw new Refusal(`${id} is a view. Insert into the table underneath it.`);
979
+ const meta = await this.columnsOf(found.schema, found.name, read);
980
+ const entries = Object.entries(request.values ?? {});
981
+ const applied = {};
982
+ for (const [column, raw] of entries) {
983
+ const declared = meta.find((c) => c.name === column);
984
+ if (!declared)
985
+ throw new Refusal(`${id} has no column called "${column}".`);
986
+ applied[column] = coerceForColumn(declared.written || declared.type || '', raw);
987
+ if (applied[column] === null && declared.notnull) {
988
+ throw new Refusal(`"${column}" is NOT NULL and cannot be null. Leave it out to use its default, if it has one.`);
989
+ }
990
+ }
991
+ const columns = Object.keys(applied);
992
+ const text = `INSERT INTO ${qualified(found)}` +
993
+ (columns.length
994
+ ? ` (${columns.map((c) => POSTGRES_STYLE.quote(c)).join(', ')}) VALUES (${columns.map((_, i) => POSTGRES_STYLE.placeholder(i + 1)).join(', ')})`
995
+ : ' DEFAULT VALUES') +
996
+ ' RETURNING *';
997
+ const params = Object.values(applied);
998
+ const result = await write.query(text, params);
999
+ const row = result.rows[0] ? toJsonSafe(result.rows[0]) : undefined;
1000
+ const pk = meta.filter((c) => c.is_pk).map((c) => c.name);
1001
+ /* A scope re-reads the stored row by this key. A bytea key would come
1002
+ back as its "<n bytes>" label, which matches nothing and proves
1003
+ nothing; refuse rather than let a label stand in for the value. */
1004
+ if (scoped &&
1005
+ pk.some((column) => {
1006
+ const value = result.rows[0]?.[column];
1007
+ return !(typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value)));
1008
+ }))
1009
+ throw new Refusal('The stored key cannot be checked in this row scope.');
1010
+ /* Read off the returned row rather than off what was sent: a key the
1011
+ database assigned is only knowable from what came back, and a key that
1012
+ was supplied comes back identical. */
1013
+ const key = {};
1014
+ if (row)
1015
+ for (const c of pk)
1016
+ key[c] = row[c];
1017
+ return { key, row, applied, sql: { text, params } };
1018
+ }
1019
+ /**
1020
+ * Remove one row, having proved it is one row.
1021
+ *
1022
+ * What is *not* checked here is whether the row should go: what references
1023
+ * it, and what the database will do to those references, is answered above
1024
+ * this layer where the schema is in hand. A `RESTRICT` that fires is the
1025
+ * correct outcome in the engine's own words.
1026
+ */
1027
+ async remove(request) {
1028
+ const lane = keyedLane(request);
1029
+ if (this.recordsHistory(request))
1030
+ return this.transact(lane, (tx) => tx.remove(request));
1031
+ return this.watched(this.writes.run(lane, () => this.connections.withWriteClient((write) => this.removeNow(request, write))));
1032
+ }
1033
+ recordsHistory(request) {
1034
+ return capturesWrites(this, request?.table);
1035
+ }
1036
+ /* What rides beneath one transaction's writes on its leased writer, beneath
1037
+ every facade (writeCapture.ts): the App's record history and notices. The
1038
+ before image is read under the row's lock, so it is the one the write
1039
+ replaces. */
1040
+ historyWrites(write, base,
1041
+ /* The capture's read of the row it keeps a before image of: an unscoped transaction's reads by key, which a row
1042
+ sent ahead may answer (plainReads). */
1043
+ query = (request) => this.queryOn(request, write)) {
1044
+ const history = beginWriteCapture(this, {
1045
+ writer: { dialect: 'postgres', client: write },
1046
+ read: async (table, key, columns, lock) => {
1047
+ if (lock)
1048
+ await this.lockRecordNow({ table, key }, write);
1049
+ const result = await query({
1050
+ table,
1051
+ ...(columns ? { columns } : {}),
1052
+ limit: 2,
1053
+ offset: 0,
1054
+ filter: { groups: [Object.entries(key).map(([column, value]) => ({ column, op: '=', value }))] },
1055
+ });
1056
+ return result.rows.length === 1 ? result.rows[0] : undefined;
1057
+ },
1058
+ rows: async (table, where, columns, limit) => (await this.queryOn({
1059
+ table,
1060
+ columns,
1061
+ limit,
1062
+ offset: 0,
1063
+ filter: { groups: [Object.entries(where).map(([column, value]) => ({ column, op: '=', value }))] },
1064
+ }, write)).rows,
1065
+ behind: (table, ride) => {
1066
+ // The table as updateNow names it: assertPostgresTable reads a bare name in the public schema.
1067
+ const update = `UPDATE ${qualified(plainTable(table))} SET `;
1068
+ return behindWrite(write, (text) => text.startsWith(update), ride);
1069
+ },
1070
+ });
1071
+ if (!history)
1072
+ return { ...base, finish: async () => { }, committed: () => { }, triggered: async () => { } };
1073
+ return {
1074
+ insert: (r) => history.insert(r, base.insert),
1075
+ update: (r) => history.update(r, base.update),
1076
+ remove: (r) => history.remove(r, base.remove),
1077
+ tell: (r) => history.tell(r),
1078
+ finish: () => finishWriteCapture(history),
1079
+ committed: () => committedWriteCapture(history),
1080
+ triggered: async (change) => history.triggered?.(change),
1081
+ };
1082
+ }
1083
+ async removeNow(request, write, read) {
1084
+ const transactional = read !== undefined;
1085
+ read ??= await this.conn();
1086
+ const found = await this.assertTable(request.table, read);
1087
+ const id = `${found.schema}.${found.name}`;
1088
+ if (found.isView)
1089
+ throw new Refusal(`${id} is a view, so no single row can be identified.`);
1090
+ const meta = await this.columnsOf(found.schema, found.name, read);
1091
+ const pk = meta.filter((c) => c.is_pk).map((c) => c.name);
1092
+ if (!pk.length)
1093
+ throw new Refusal(`${id} has no primary key, so no single row can be identified.`);
1094
+ const keyColumns = Object.keys(request.key);
1095
+ const same = keyColumns.length === pk.length && pk.every((c) => keyColumns.includes(c));
1096
+ if (!same)
1097
+ throw new Refusal(`Deleting from ${id} needs exactly its primary key (${pk.join(', ')}).`);
1098
+ const filter = {
1099
+ groups: [pk.map((column) => ({ column, op: '=', value: request.key[column] }))],
1100
+ };
1101
+ // As an update's: inside a transaction the DELETE's own count is the check.
1102
+ const refuseMatches = (matches) => {
1103
+ throw new Refusal(`Refused: that key matches ${matches} rows, not 1. A delete is only allowed when it is certain which row it removes.`);
1104
+ };
1105
+ const matches = transactional ? 1 : await this.count(id, filter);
1106
+ if (matches !== 1)
1107
+ refuseMatches(matches);
1108
+ const where = buildWhere(filter, POSTGRES_STYLE);
1109
+ const text = `DELETE FROM ${qualified(found)}${where.text}`;
1110
+ const result = await write.query(text, where.params);
1111
+ if (transactional && Number(result.rowCount ?? 0) !== 1)
1112
+ refuseMatches(Number(result.rowCount ?? 0));
1113
+ return { affected: Number(result.rowCount ?? 0), sql: { text, params: where.params } };
1114
+ }
1115
+ /**
1116
+ * Several writes as one, or none of them.
1117
+ *
1118
+ * Plain `BEGIN` / `COMMIT` on the write connection. The callback is handed
1119
+ * the same write bodies the public methods call, so every guard — the whole
1120
+ * key, the pre-flight count, the type coercion — applies inside a
1121
+ * transaction exactly as it does outside one.
1122
+ *
1123
+ * Reads, metadata checks, and preflight counts use the same leased client.
1124
+ * This preserves read-after-write visibility; it does not promise serializable
1125
+ * isolation. Call lockRecord explicitly before capturing protected originals:
1126
+ * where an App writes, other transactions of this process run beside this
1127
+ * one (writeLanes.ts), and a row read without its lock may change before
1128
+ * the write that depends on it, as a row read in another pod always could.
1129
+ */
1130
+ async transaction(run) {
1131
+ return this.transact([], run);
1132
+ }
1133
+ /* A transaction in the lanes `lane` names: a single record's write that
1134
+ keeps a history names its record, so it keeps its place behind that
1135
+ record's earlier writes. */
1136
+ async transact(lane, run) {
1137
+ const hint = writeAhead();
1138
+ const snapshot = snapshotRead();
1139
+ const schema = hint ? await this.schema().catch(() => undefined) : undefined;
1140
+ return this.watched(this.writes.run(lane, () => this.connections.withWriteClient(async (leased) => {
1141
+ // Its own handle, as a journal's: what it was told leaves behind its BEGIN, and writes nothing reads with its COMMIT.
1142
+ // A writer that pipelines sends reads asked together in one flight (TransactionOperations.read).
1143
+ const write = transactionHandle(leased, this), operations = new TransactionOperations(sendsAhead(write));
1144
+ if (snapshot)
1145
+ snapshotHandles.add(write);
1146
+ let began = false;
1147
+ let commitAttempted = false;
1148
+ let committed = false;
1149
+ try {
1150
+ const reads = await this.openPlain(write, schema, undefined, hint, () => {
1151
+ began = true;
1152
+ });
1153
+ const writes = this.historyWrites(write, {
1154
+ insert: (r) => this.insertNow(r, write, write),
1155
+ remove: (r) => this.removeNow(r, write, write),
1156
+ update: (r) => this.updateNow(r, write, write),
1157
+ }, reads);
1158
+ // The transaction's own work runs without the hint: a transaction it opens is not this one.
1159
+ const out = await withoutWriteAhead(() => withoutSnapshotRead(() => run({
1160
+ lockRecord: (r) => queueRecordLock(operations, r, (request) => this.lockRecordNow(request, write)),
1161
+ query: (r) => operations.read(() => reads(r)),
1162
+ count: (table, filter) => operations.read(() => this.countOn(table, filter, write)),
1163
+ aggregate: (r) => operations.read(() => this.aggregateOn(r, write)),
1164
+ insert: (r) => operations.run(() => writes.insert(r)),
1165
+ remove: (r) => operations.run(() => writes.remove(r)),
1166
+ update: (r) => operations.run(() => writes.update(r)),
1167
+ ...(writes.tell ? { tell: (r) => operations.run(() => writes.tell(r)) } : {}),
1168
+ })));
1169
+ await operations.finish();
1170
+ await writes.finish();
1171
+ commitAttempted = true;
1172
+ await write.query('COMMIT');
1173
+ committed = true;
1174
+ writes.committed();
1175
+ return out;
1176
+ }
1177
+ catch (err) {
1178
+ await operations.finish().catch(() => { });
1179
+ let rolledBack = false;
1180
+ if (began) {
1181
+ try {
1182
+ await write.query('ROLLBACK');
1183
+ rolledBack = true;
1184
+ }
1185
+ catch {
1186
+ /* A failed acknowledgement cannot establish the outcome. */
1187
+ }
1188
+ }
1189
+ // A write sent with the COMMIT failed and the server answered it as a ROLLBACK: nothing committed.
1190
+ if (err instanceof RolledBackAtCommit)
1191
+ throw err.cause;
1192
+ // withWriteClient destroys on any callback error, including a failed
1193
+ // BEGIN and a lost COMMIT acknowledgement followed by successful rollback.
1194
+ if (commitAttempted || (began && !rolledBack))
1195
+ throw new TransactionOutcomeUnknown(err);
1196
+ throw err;
1197
+ }
1198
+ finally {
1199
+ this.txEpochs.delete(write);
1200
+ reportWriteAhead(aheadReport(write), committed);
1201
+ }
1202
+ })));
1203
+ }
1204
+ /**
1205
+ * Begin an unscoped write transaction with what it was told it opens with
1206
+ * (writeAhead.ts) behind its BEGIN, as a scoped one does (sendWriteAhead):
1207
+ * the journal's receipt lookup, and for each target its lock and its whole
1208
+ * row, kept to answer the transaction's reads of it by key (keyRows.ts) —
1209
+ * the command's own read of its target, its handler's, the history
1210
+ * capture's before image. The lock goes first, so the row is read under it
1211
+ * and cannot move until this transaction ends; its own writes move the
1212
+ * statement generation and are read again. One that fails aborts the
1213
+ * opening, which begins again without them. Answers the transaction's
1214
+ * reader: by key from the kept rows where they answer, else in its turn.
1215
+ */
1216
+ async openPlain(write, schema, journal, hint, began) {
1217
+ const keyRows = new KeyRows(() => generationOf(write));
1218
+ let aheads = [];
1219
+ await this.openWrite(write, schema && hint ? { sent: () => void (aheads = sendPlainAhead(this, write, schema, keyRows, journal, hint)) } : {}, began);
1220
+ if (aheads.length && (await aheadsFailed(aheads))) {
1221
+ redoWithoutAhead(write);
1222
+ keyRows.forget();
1223
+ // Its ROLLBACK lets go of every lock it held.
1224
+ heldLocks.delete(write);
1225
+ heldRows.delete(write);
1226
+ await write.query('ROLLBACK');
1227
+ await this.openWrite(write, {}, began);
1228
+ }
1229
+ const plain = (request) => this.queryOn(request, write);
1230
+ if (!schema || !aheads.length)
1231
+ return plain;
1232
+ /* A table is asked for bare (`task`) or by its id (`public.task`), as assertPostgresTable reads either: the kept
1233
+ rows are filed under the id, and a read asked in its turn is sent as it was asked. */
1234
+ const asked = new WeakMap();
1235
+ const kept = keyRows.over({ query: (request) => plain(asked.get(request) ?? request) }, PLAIN_SCOPE, schema, (request) => plainStatement(request), (row, request) => (request.binary ? withBytes : toJsonSafe)(row), false,
1236
+ /* A row the opening locked FOR UPDATE cannot move until this transaction ends: read by key after a write of
1237
+ the transaction's own has dropped what was kept of it, it is read whole once, and the reads of it that follow
1238
+ (the machine's columns, the history capture's before image) are answered from that read, as a scoped
1239
+ transaction's are (keyRows.ts, `widen`). The driver's own rows, formatted as each read asks. */
1240
+ {
1241
+ held: (table, key) => heldRows.get(write)?.has(lockKey(...rowLockStatement(table, key))) === true,
1242
+ reads: {
1243
+ query: async (request) => {
1244
+ const sql = plainStatement(request);
1245
+ const result = await write.query(sql.text, sql.params);
1246
+ return { columns: result.fields.map((field) => field.name), rows: result.rows, ms: 0, sql };
1247
+ },
1248
+ },
1249
+ }).query;
1250
+ return (request) => {
1251
+ const id = typeof request?.table === 'string' ? catalogId(request.table) : request?.table;
1252
+ if (id === request?.table)
1253
+ return kept(request);
1254
+ const named = { ...request, table: id };
1255
+ asked.set(named, request);
1256
+ return kept(named);
1257
+ };
1258
+ }
1259
+ /**
1260
+ * Same-source records and a durable journal in one transaction, the
1261
+ * journal lent by the App framework (storeHost.ts TransactionJournal): the
1262
+ * command journal, or a public placement's. Lent through the store host,
1263
+ * never on the class, so the database browser has no journal path at all.
1264
+ *
1265
+ * The SQLite version opens `BEGIN IMMEDIATE`, which serialises every writer
1266
+ * in the file; here the transaction is plain `BEGIN` at the server's
1267
+ * default READ COMMITTED, and the journal's per-scope advisory lock does
1268
+ * the one piece of that serialisation a command needs — two deliveries of
1269
+ * the same command cannot both execute. SERIALIZABLE was the alternative
1270
+ * and was refused: it would turn unrelated concurrent commands into 40001
1271
+ * retries the SQLite path never has, and a conditional `expected` update
1272
+ * already refuses a stale row in the write itself.
1273
+ *
1274
+ * The journal is attested inside the transaction and before the callback,
1275
+ * so an unmigrated or altered layout refuses without a write. The outcome
1276
+ * contract is SQLite's: a failure after COMMIT was sent, or a rollback that
1277
+ * was not acknowledged, is `unknown`; everything else is `not_applied`.
1278
+ * `withWriteClient` destroys the client on any failure, so a connection in
1279
+ * an uncertain state is never handed to the next write.
1280
+ */
1281
+ async journalTransaction(journal, run, options = {}) {
1282
+ if (options.scope === undefined) {
1283
+ /* The verifier supplies current authority, never actor/receipt scope or record filtering. */
1284
+ if (options.ordinaryVerify !== undefined && !this.verifiedSource())
1285
+ throw new Refusal('This verified command transaction is unavailable.');
1286
+ const verify = options.ordinaryVerify;
1287
+ return this.ordinaryJournalTransaction(journal, run, verify && (async () => void (await verify())));
1288
+ }
1289
+ return this.scopedTransact(options.scope, journal, run, options.verify, options.bound, options.triggers);
1290
+ }
1291
+ async ordinaryJournalTransaction(journal, run, verify) {
1292
+ /* The command host supplies target and receipt lanes through inWriteLanes.
1293
+ Extra records discovered inside the handler still rely on row locks and
1294
+ compare-and-set, as they do across processes. */
1295
+ const hint = writeAhead();
1296
+ const snapshot = snapshotRead();
1297
+ const schema = hint ? await this.schema().catch(() => undefined) : undefined;
1298
+ return this.watched(this.writes.run([], () => this.connections.withWriteClient(async (leased) => {
1299
+ // Its own handle, as a scoped transaction's: writes nothing reads leave with its COMMIT (beforeCommit).
1300
+ // A writer that pipelines sends reads asked together in one flight (TransactionOperations.read).
1301
+ const write = transactionHandle(leased, this), operations = new TransactionOperations(sendsAhead(write));
1302
+ if (snapshot)
1303
+ snapshotHandles.add(write);
1304
+ let began = false;
1305
+ let commitAttempted = false;
1306
+ let committed = false;
1307
+ try {
1308
+ const reads = await this.openPlain(write, schema, journal, hint, () => {
1309
+ began = true;
1310
+ });
1311
+ await this.attestJournal(write, journal);
1312
+ if (verify)
1313
+ await verify();
1314
+ const writes = this.historyWrites(write, {
1315
+ insert: (r) => this.insertNow(r, write, write),
1316
+ remove: (r) => this.removeNow(r, write, write),
1317
+ update: (r) => this.updateNow(r, write, write),
1318
+ }, reads);
1319
+ const records = {
1320
+ lockRecord: (r) => queueRecordLock(operations, r, (request) => this.lockRecordNow(request, write)),
1321
+ query: (r) => operations.read(() => reads(r)),
1322
+ count: (table, filter) => operations.read(() => this.countOn(table, filter, write)),
1323
+ aggregate: (r) => operations.read(() => this.aggregateOn(r, write)),
1324
+ insert: (r) => operations.run(() => writes.insert(r)),
1325
+ remove: (r) => operations.run(() => writes.remove(r)),
1326
+ update: (r) => operations.run(() => writes.update(r)),
1327
+ ...(writes.tell ? { tell: (r) => operations.run(() => writes.tell(r)) } : {}),
1328
+ };
1329
+ // The transaction's own work runs without the hint: a transaction it opens is not this one.
1330
+ const out = await withoutWriteAhead(() => withoutSnapshotRead(() => run(Object.freeze(records), journal.open(write, operations))));
1331
+ await operations.finish();
1332
+ await writes.finish();
1333
+ if (verify) {
1334
+ // All storage work precedes the final native observation. No further
1335
+ // asynchronous work is allowed here except the COMMIT itself. Separate
1336
+ // auth/business databases still do not provide atomic revocation.
1337
+ await verify();
1338
+ }
1339
+ commitAttempted = true;
1340
+ await write.query('COMMIT');
1341
+ committed = true;
1342
+ writes.committed();
1343
+ return out;
1344
+ }
1345
+ catch (error) {
1346
+ await operations.finish().catch(() => { });
1347
+ let rolledBack = false;
1348
+ if (began) {
1349
+ try {
1350
+ await write.query('ROLLBACK');
1351
+ rolledBack = true;
1352
+ }
1353
+ catch {
1354
+ /* A failed acknowledgement cannot establish the outcome. */
1355
+ }
1356
+ }
1357
+ // A write sent with the COMMIT failed and the COMMIT rolled back: nothing committed, and its failure is what is said.
1358
+ if (error instanceof RolledBackAtCommit)
1359
+ throw journal.failure(error.cause, 'not_applied');
1360
+ throw journal.failure(error, commitAttempted || (began && !rolledBack) ? 'unknown' : 'not_applied');
1361
+ }
1362
+ finally {
1363
+ this.txEpochs.delete(write);
1364
+ reportWriteAhead(aheadReport(write), committed);
1365
+ }
1366
+ })));
1367
+ }
1368
+ /**
1369
+ * Private same-source row enforcement, with the SQLite guarantees.
1370
+ *
1371
+ * SQLite gets "the row the scope checked is the row the write changes"
1372
+ * from `BEGIN IMMEDIATE`, which excludes every other writer for the whole
1373
+ * transaction. Here the transaction is plain `BEGIN` at the server's
1374
+ * default READ COMMITTED, and the guarantee is made per row instead: before
1375
+ * a target is scope-checked its row is taken `FOR UPDATE`, and before a
1376
+ * parent is checked its row is taken `FOR SHARE`. A lock waits for any
1377
+ * in-flight writer of that row to finish, and the guard read that follows
1378
+ * takes a fresh snapshot — READ COMMITTED gives one per statement — so it
1379
+ * sees the version that writer committed and nobody can commit another
1380
+ * until this transaction ends. A row a concurrent writer moved out of scope
1381
+ * is therefore refused, whether it moved before the check or while the
1382
+ * check waited. SERIALIZABLE would prove the same thing by aborting one of
1383
+ * the two with 40001, which the SQLite path never does and every handler
1384
+ * would have to learn to retry; the explicit locks make the refusal an
1385
+ * ordinary one.
1386
+ *
1387
+ * The catalog is read on the writer inside the transaction after the
1388
+ * scope's tables are pinned against DDL (`postgresScopeCatalog.ts`), and
1389
+ * handed out as detached evidence for the caller to attest. Outcomes are
1390
+ * the transaction contract's: a failure after COMMIT was sent, or a
1391
+ * rollback that was not acknowledged, is unknown, and the client is
1392
+ * discarded rather than reused. Everything else did not commit.
1393
+ */
1394
+ async scopeTransaction(input, run, triggers) {
1395
+ const scope = captureRowScope(input);
1396
+ return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), undefined, undefined, triggers);
1397
+ }
1398
+ /**
1399
+ * Private source-owner boundary, deliberately absent from Adapter: the
1400
+ * PostgreSQL counterpart of `SqliteAdapter.scopeVerifiedTransaction`. The
1401
+ * verifier is trusted host code — the tenant write source's attestation and
1402
+ * the store's membership fence (`assertPostgresTenantMembershipFence`) —
1403
+ * never a business callback or a wire value, and must not retain the
1404
+ * client. It runs on the leased writer inside the transaction twice: after
1405
+ * the scope's tables are pinned and the catalog read, before the callback;
1406
+ * and after the callback's operations drain, before COMMIT. It is handed the
1407
+ * catalog evidence and the adapter's own introspection on the writer, for
1408
+ * anything it pins itself. SQLite also re-verifies around every operation,
1409
+ * because its fence is a snapshot check; here the fence is row locks held
1410
+ * to the end of the transaction, so the two checks bound its lifetime.
1411
+ */
1412
+ async scopeVerifiedTransaction(input, verify, run) {
1413
+ const scope = captureRowScope(input);
1414
+ if (typeof verify !== 'function' || typeof run !== 'function' || Object.keys(scope).some(isRuntimeRelation))
1415
+ throw new Refusal('This verified transaction is unavailable.');
1416
+ return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), verify);
1417
+ }
1418
+ /**
1419
+ * Private source-owner boundary, deliberately absent from Adapter: one
1420
+ * `REPEATABLE READ, READ ONLY` transaction on a leased reader, for trusted
1421
+ * host code that pins, attests and reads inside a single snapshot (the
1422
+ * PostgreSQL tenant read source). It is what a deferred `BEGIN` on its
1423
+ * read-only handle gives the SQLite tenant reader: every statement sees one
1424
+ * committed state. PostgreSQL takes that snapshot at the first query, not at
1425
+ * BEGIN, so an owner that takes its locks before its first query attests
1426
+ * what committed before them, and DDL after them waits. A ROLLBACK that
1427
+ * fails surfaces as TransactionOutcomeUnknown; any failure discards the
1428
+ * client rather than returning it to the pool.
1429
+ */
1430
+ async readSnapshot(run, observeCheckout = false, prologue, ahead = false,
1431
+ /* The prologue is the snapshot's whole question (a membership fence): BEGIN, the prologue and COMMIT in one
1432
+ round trip where they were two. `run` is handed its answers and nothing it can ask. */
1433
+ whole = false) {
1434
+ return readSnapshotOn(this.connections, (db, checkout) => (checkout ? PostgresAdapter.prototype.describe.call(this, db) : this.describeSnapshot(db)), run, observeCheckout, prologue, ahead, whole);
1435
+ }
1436
+ /** Private source-shape owner, not an authorization proof or generic Adapter
1437
+ * capability. Only this actual adapter's native snapshot runner is used. */
1438
+ capturePinnedReadSnapshot(dependencies, assertCurrent) {
1439
+ if (typeof assertCurrent !== 'function' || isProxy(assertCurrent)) {
1440
+ throw new Refusal('The pinned PostgreSQL read snapshot is unavailable.');
1441
+ }
1442
+ const connections = pinnedReaders.get(this);
1443
+ const nativeCurrent = () => {
1444
+ if (!connections)
1445
+ throw new Refusal('The pinned PostgreSQL read snapshot is unavailable.');
1446
+ const descriptor = Object.getOwnPropertyDescriptor(this, 'connections');
1447
+ if (!descriptor || !('value' in descriptor) || descriptor.value !== connections) {
1448
+ throw new Refusal('The pinned PostgreSQL read snapshot is unavailable.');
1449
+ }
1450
+ };
1451
+ nativeCurrent();
1452
+ return createPinnedPostgresReadOwner((run) => {
1453
+ nativeCurrent();
1454
+ return (PostgresAdapter.prototype.readSnapshot).call(this, run, true);
1455
+ }, dependencies, () => {
1456
+ nativeCurrent();
1457
+ assertCurrent();
1458
+ nativeCurrent();
1459
+ });
1460
+ }
1461
+ /* Scoped records and, for a command, the durable journal and fresh catalog
1462
+ evidence in one transaction. The journal is attested before the catalog
1463
+ is read, so an unmigrated layout refuses before any lock is taken. */
1464
+ async scopedTransact(scope, journal, run, verify, bound, triggers) {
1465
+ /* The proof is loaded where a transaction accepts triggers, not at startup; and awaited in the transaction's turn,
1466
+ not before it is queued: a write asked after this one would otherwise take its turn while the module loads. */
1467
+ const loading = triggers && !journal?.fixedRecords ? import('./scoped/triggerProof.js') : undefined;
1468
+ loading?.catch(() => { }); // Rejected or not, it is awaited in its turn below.
1469
+ // This transaction's own handle: what its verifier learns is kept on it, never on the pooled client.
1470
+ /* No lane: every target is taken FOR UPDATE and every parent FOR SHARE
1471
+ before it is checked (below), which is what orders two of these
1472
+ across connections, in this process as across pods. */
1473
+ const hint = writeAhead();
1474
+ const snapshot = snapshotRead();
1475
+ return this.writes.run([], () => this.connections.withWriteClient(async (leased) => {
1476
+ const proving = await loading;
1477
+ // A writer that pipelines sends reads asked together in one flight (TransactionOperations.read).
1478
+ const write = transactionHandle(leased, this), operations = new TransactionOperations(sendsAhead(write));
1479
+ if (snapshot)
1480
+ snapshotHandles.add(write);
1481
+ let began = false;
1482
+ let commitAttempted = false;
1483
+ let committed = false;
1484
+ // The proof of the validation-only triggers this transaction's writes fired, read again (attestPostgresTriggers).
1485
+ let attest;
1486
+ try {
1487
+ /* The scope catalog is kept per set of scoped tables under the epoch;
1488
+ the tables it pinned last time are pinned in the message that reads
1489
+ the epoch, so a hit asks the catalog nothing (openWrite). */
1490
+ const scopeKey = `scope:${Object.keys(scope).sort().join('\u0000')}`;
1491
+ const peeked = this.catalogCache.peek(scopeKey)?.value;
1492
+ const pinned = peeked?.pinned;
1493
+ const pin = verifierPin(verify);
1494
+ /* What the transaction opens with leaves behind its BEGIN, in the
1495
+ same round trip (writeAhead.ts): the verifier's fence, the
1496
+ journal's receipt lookup, each target's lock and row. Each answers
1497
+ the identical statement once when the transaction asks it, and a
1498
+ target's row answers its reads by key (keyRows.ts). */
1499
+ const keyRows = new KeyRows(() => generationOf(write));
1500
+ // The rows whose locks were sent ahead, held from the moment their answers came back (sendWriteAhead).
1501
+ const lockedAhead = new Set();
1502
+ let aheads = [];
1503
+ const opening = { lock: pinned, pin, digest: true, session: SCOPED_SESSION };
1504
+ let opened = await this.openWrite(write, {
1505
+ ...opening,
1506
+ sent: () => void (aheads = sendWriteAhead(this, write, scope, peeked, keyRows, journal, verify, hint, lockedAhead)),
1507
+ }, () => {
1508
+ began = true;
1509
+ });
1510
+ if (aheads.length && (await aheadsFailed(aheads))) {
1511
+ /* One failed, which aborted the transaction before anything took
1512
+ an answer: it begins again without them. Rare, and counted. */
1513
+ lockedAhead.clear();
1514
+ redoWithoutAhead(write);
1515
+ began = false;
1516
+ await write.query('ROLLBACK');
1517
+ opened = await this.openWrite(write, opening, () => {
1518
+ began = true;
1519
+ });
1520
+ }
1521
+ if (journal)
1522
+ await this.attestJournal(write, journal);
1523
+ const catalog = this.catalogCache.get(opened.epoch, scopeKey) ??
1524
+ this.catalogCache.set(opened.epoch, scopeKey, await readPostgresScopeCatalog(write, scope, (db) => this.describeScoped(db)));
1525
+ // Rows read under another epoch's catalog answer nothing: the statements sent ahead were built from it.
1526
+ if (catalog !== peeked) {
1527
+ keyRows.forget();
1528
+ lockedAhead.clear();
1529
+ }
1530
+ const described = () => this.describeScoped(write);
1531
+ // The epoch is passed only when it was read after the verifier's own pin: then it vouches for what that pin holds.
1532
+ if (verify)
1533
+ await verify(write, catalog, described, pin !== undefined ? this.txEpochs.get(write) : undefined);
1534
+ if (journal?.admit)
1535
+ await journal.admit(write, catalog, scope);
1536
+ // Runtime state is not command-handler evidence; the complete graph
1537
+ // stays behind for row/FK enforcement exactly as on SQLite.
1538
+ const evidence = journal
1539
+ ? mapScopeCatalog(catalog.schema, new Map(catalog.schema.tables.filter((table) => !isRuntimeRelation(table.id)).map((table) => [table.id, table.id])))
1540
+ : captureScopeCatalog(catalog.schema);
1541
+ // Guards keep the stored scalars: a bytea's byte-count label is
1542
+ // not a key, and a numeric's text is exactly its value.
1543
+ const formatted = (guard, binary) => (row) => guard ? { ...row } : binary ? withBytes(row) : toJsonSafe(row);
1544
+ // Row locks this transaction holds: a lock is held to its end, so a row taken once is not taken again.
1545
+ const held = new Map();
1546
+ /* Whether this transaction holds a row FOR UPDATE: taken in its turn, or sent ahead behind the BEGIN. Such a
1547
+ row cannot move until the transaction ends, so a read of it by key may be kept to answer the reads after
1548
+ it (keyRows.ts, `widen`) until the transaction changes something of its own. */
1549
+ const holds = (table, key) => {
1550
+ const pk = table.columns.filter((column) => column.primaryKey).map((column) => column.name);
1551
+ const at = rowLockKey(table, { groups: [pk.map((column) => ({ column, op: '=', value: key[column] }))] });
1552
+ return held.get(at) === 'UPDATE' || lockedAhead.has(at);
1553
+ };
1554
+ const executor = (guard) => async (sql, hint) => {
1555
+ const started = performance.now();
1556
+ const result = await write.query(sql.text, sql.params);
1557
+ return {
1558
+ columns: result.fields.map((field) => field.name),
1559
+ rows: result.rows.map(formatted(guard, hint?.binary)),
1560
+ ms: Math.round(performance.now() - started),
1561
+ sql,
1562
+ };
1563
+ };
1564
+ /* Each scope this transaction reads under, checked against its catalog once. A command's scope arrives as
1565
+ a copy (captureRowScope), which no check has seen, and every scoped reader and statement checked it
1566
+ again in full: eleven times in one prepare. Checked here, each finds it checked (rowScope.ts). The rows
1567
+ kept by key are kept under the scope as given, the one the statements sent ahead were keyed by
1568
+ (keyRows.ts names a scope by its object), so that is the one they are asked under. */
1569
+ const checkedScopes = new WeakMap();
1570
+ const checkedScope = (given) => {
1571
+ let checked = checkedScopes.get(given);
1572
+ if (!checked)
1573
+ checkedScopes.set(given, (checked = snapshotRowScope(catalog.schema, given)));
1574
+ return checked;
1575
+ };
1576
+ const scopedReads = (guard, given = scope, within = checkedScope(given)) => keyRows.over(createScopedReads(catalog.schema, within, POSTGRES_STYLE, executor(guard), guard), given, catalog.schema, (request) => scopedStatement(catalog.schema, within, request), (row, request) => formatted(guard, request.binary)(row), guard, guard ? undefined : { held: holds, reads: createScopedReads(catalog.schema, within, POSTGRES_STYLE, executor(true)) });
1577
+ const lock = (mode) => async (table, filter) => {
1578
+ // A parent the role cannot update cannot be held; its FK's own KEY
1579
+ // SHARE still stops deletion, and the visibility check is one read.
1580
+ if (!catalog.lockable.has(table.id)) {
1581
+ if (mode === 'UPDATE')
1582
+ throw new Refusal('This operation is not available in the current row scope.');
1583
+ return;
1584
+ }
1585
+ const at = rowLockKey(table, filter);
1586
+ const had = held.get(at);
1587
+ if (had === 'UPDATE' || had === mode)
1588
+ return;
1589
+ // A parent is held by the key its reference names as the foreign key compares it (Condition.equality).
1590
+ const where = buildWhere(filter, POSTGRES_STYLE, 1, undefined, undefined, undefined, undefined, mode === 'SHARE');
1591
+ const text = `SELECT 1 FROM ${qualified(table)}${where.text} FOR ${mode}`;
1592
+ /* Sent ahead behind the BEGIN and granted, its answer since dropped by a write of the transaction's own:
1593
+ the row is held all the same, to the transaction's end. While that answer still waits, asking takes it. */
1594
+ if (lockedAhead.has(at) && !waitsAhead(write, { text, values: where.params })) {
1595
+ held.set(at, 'UPDATE');
1596
+ return;
1597
+ }
1598
+ await write.query(text, where.params);
1599
+ held.set(at, mode);
1600
+ };
1601
+ const writes = this.historyWrites(write, {
1602
+ insert: (r) => this.insertNow(r, write, write, true),
1603
+ remove: (r) => this.removeNow(r, write, write),
1604
+ update: (r) => this.updateNow(r, write, write),
1605
+ });
1606
+ // The tables whose validation-only triggers a write of this transaction fired: their proof is read again before COMMIT.
1607
+ const relied = new Set();
1608
+ attest = () => attestPostgresTriggers(write, catalog, relied);
1609
+ let records = createScopedTransaction(catalog, {
1610
+ query: (r) => this.queryOn(r, write),
1611
+ count: (table, filter) => this.countOn(table, filter, write),
1612
+ insert: writes.insert,
1613
+ remove: writes.remove,
1614
+ update: writes.update,
1615
+ }, scopedReads(false), scopedReads(true), {
1616
+ target: lock('UPDATE'),
1617
+ parent: lock('SHARE'),
1618
+ behind: (table, ride) => {
1619
+ const update = `UPDATE ${qualified(table)} SET `;
1620
+ return behindWrite(write, (text) => text.startsWith(update), ride);
1621
+ },
1622
+ together: sendsAhead(write),
1623
+ relied: (table) => void relied.add(table.id),
1624
+ }, bound && {
1625
+ reads: scopedReads(true, bound),
1626
+ whole: wholeWithin(scope, bound),
1627
+ references: async (fk, key) => {
1628
+ const statement = referencesStatement(catalog.schema, fk, key, POSTGRES_STYLE);
1629
+ return Number((await write.query(statement.text, statement.params)).rows[0]?.n ?? 0);
1630
+ },
1631
+ },
1632
+ // A public intake writes exactly its fixed rows; only a principal's own transaction counts its new parents in.
1633
+ journal?.fixedRecords ? undefined : { scope, reads: (within, guard) => scopedReads(guard, within) },
1634
+ // Triggers the App names, on a principal's own transaction: their effects proven per write (triggerProof.ts).
1635
+ triggers && proving
1636
+ ? {
1637
+ prove: proving.createTriggerProof,
1638
+ acceptance: {
1639
+ ...triggers,
1640
+ // Kept and announced as the transaction's own writes are (writeCapture.ts).
1641
+ changed: async (change) => {
1642
+ await writes.triggered(change);
1643
+ await triggers.changed?.(change);
1644
+ },
1645
+ },
1646
+ scope,
1647
+ }
1648
+ : undefined);
1649
+ if (journal?.fixedRecords)
1650
+ records = journal.fixedRecords(records);
1651
+ const invoke = scopedCommandInvoker(operations, true, journal !== undefined, isRuntimeRelation);
1652
+ // The transaction's own work runs without the hint: a transaction it opens is not this one.
1653
+ const out = await withoutWriteAhead(() => withoutSnapshotRead(() => run(Object.freeze({
1654
+ // The scoped policy facade deliberately has no generic lock capability.
1655
+ query: (r) => invoke(r, (r) => records.query(r), true),
1656
+ count: (table, filter) => invoke({ table, filter }, (r) => records.count(r.table, r.filter), true),
1657
+ ...(records.aggregate ? { aggregate: (r) => invoke(r, (r) => records.aggregate(r), true) } : {}),
1658
+ insert: (r) => invoke(r, (r) => records.insert(r)),
1659
+ remove: (r) => invoke(r, (r) => records.remove(r)),
1660
+ update: (r) => invoke(r, (r) => records.update(r)),
1661
+ // Beneath the row scope: the flows' command tells only of its own target, which it read through the scope.
1662
+ ...(writes.tell ? { tell: (r) => invoke(r, (r) => writes.tell(r)) } : {}),
1663
+ }), journal?.open(write, operations), evidence)));
1664
+ await operations.finish();
1665
+ await writes.finish();
1666
+ if (verify)
1667
+ await verify(write, catalog, described);
1668
+ await attestPostgresTriggers(write, catalog, relied);
1669
+ commitAttempted = true;
1670
+ try {
1671
+ await write.query('COMMIT');
1672
+ }
1673
+ catch (error) {
1674
+ /* A deferred foreign key the COMMIT found broken: the server answered, so nothing committed, and the
1675
+ refusal is a hidden parent's (foreignKeyRefusal). */
1676
+ if (!isForeignKeyViolation(error))
1677
+ throw error;
1678
+ commitAttempted = false;
1679
+ throw foreignKeyRefusal(error);
1680
+ }
1681
+ committed = true;
1682
+ writes.committed();
1683
+ return out;
1684
+ }
1685
+ catch (err) {
1686
+ await operations.finish().catch(() => { });
1687
+ let rolledBack = false;
1688
+ if (began) {
1689
+ try {
1690
+ await write.query('ROLLBACK');
1691
+ rolledBack = true;
1692
+ }
1693
+ catch {
1694
+ /* A failed acknowledgement cannot establish the outcome. */
1695
+ }
1696
+ }
1697
+ /* A write sent with the COMMIT failed, and the server answered the
1698
+ COMMIT as a ROLLBACK: nothing committed, and that write's failure is
1699
+ what is said. */
1700
+ const refused = err instanceof RolledBackAtCommit;
1701
+ let failure = refused ? err.cause : err;
1702
+ /* A write that fired a trigger proven validation-only failed, and what the trigger raised is in its error,
1703
+ said to the caller. A trigger's function can be replaced without a lock on its table: replaced since the
1704
+ proof, it raised whatever its replacement read. So the proof is read again, once the transaction is
1705
+ rolled back, before that error is said; changed, the write is refused instead. */
1706
+ if (rolledBack && attest && !(failure instanceof Refusal))
1707
+ failure = await attest().then(() => failure, (refusal) => refusal);
1708
+ // withWriteClient destroys the client on any failure, so a connection
1709
+ // in an uncertain state is never handed to the next write.
1710
+ const unknown = !refused && (commitAttempted || (began && !rolledBack));
1711
+ // The verified owner composes native outcomes itself, as on SQLite.
1712
+ if (journal && !verify)
1713
+ throw journal.failure(failure, unknown ? 'unknown' : 'not_applied');
1714
+ if (unknown)
1715
+ throw new TransactionOutcomeUnknown(failure);
1716
+ throw failure;
1717
+ }
1718
+ finally {
1719
+ reportWriteAhead(aheadReport(write), committed);
1720
+ }
1721
+ }));
1722
+ }
1723
+ /**
1724
+ * Internal runtime-owner composition, deliberately absent from Adapter: the
1725
+ * PostgreSQL counterpart of `SqliteAdapter.runtimeMaintenanceTransaction`,
1726
+ * for trusted runtime code (tenant administration) that composes its own
1727
+ * bounded maintenance facades on the leased writer and the ordinary write
1728
+ * queue. `verify` runs after BEGIN and again after the work's operations
1729
+ * drain, before COMMIT; the synchronous `assertCurrent` handed to the work
1730
+ * refuses once the transaction has ended. Raw handles must never reach
1731
+ * business handlers, policies or request callbacks. Outcomes are the
1732
+ * transaction contract's: unknown after COMMIT was sent or an unacknowledged
1733
+ * ROLLBACK, and the client is discarded rather than reused.
1734
+ */
1735
+ async runtimeMaintenanceTransaction(verify, run) {
1736
+ if (typeof verify !== 'function' || typeof run !== 'function')
1737
+ throw new Refusal('Runtime maintenance is unavailable.');
1738
+ // No lane: `verify` fences what the work depends on, twice, on the writer (tenantAdministration.ts).
1739
+ return this.writes.run([], () => this.connections.withWriteClient(async (leased) => {
1740
+ const write = transactionHandle(leased, this), operations = new TransactionOperations();
1741
+ let began = false, commitAttempted = false, open = true;
1742
+ const assertCurrent = () => {
1743
+ if (!open)
1744
+ throw new Refusal('The maintenance transaction is no longer active.');
1745
+ };
1746
+ try {
1747
+ await write.query('BEGIN');
1748
+ began = true;
1749
+ await verify(write);
1750
+ const out = await run(write, operations, assertCurrent);
1751
+ await operations.finish();
1752
+ await verify(write);
1753
+ commitAttempted = true;
1754
+ await write.query('COMMIT');
1755
+ return out;
1756
+ }
1757
+ catch (err) {
1758
+ await operations.finish().catch(() => { });
1759
+ let rolledBack = false;
1760
+ if (began) {
1761
+ try {
1762
+ await write.query('ROLLBACK');
1763
+ rolledBack = true;
1764
+ }
1765
+ catch {
1766
+ /* A failed acknowledgement cannot establish the outcome. */
1767
+ }
1768
+ }
1769
+ if (commitAttempted || (began && !rolledBack))
1770
+ throw new TransactionOutcomeUnknown(err);
1771
+ throw err;
1772
+ }
1773
+ finally {
1774
+ open = false;
1775
+ }
1776
+ }));
1777
+ }
1778
+ async close() {
1779
+ await this.writes.run('all', () => this.connections.close());
1780
+ }
1781
+ async lockRecordNow(request, write) {
1782
+ const found = await this.assertTable(request.table, write);
1783
+ if (found.isView || !['r', 'p'].includes(found.kind))
1784
+ throw new Refusal('Record locks require a local keyed table.');
1785
+ const meta = await this.columnsOf(found.schema, found.name, write);
1786
+ const pk = meta.filter((column) => column.is_pk).map((column) => column.name);
1787
+ const where = buildWhere(recordLockFilter(request, pk), POSTGRES_STYLE);
1788
+ const text = `SELECT ${pk.map(POSTGRES_STYLE.quote).join(', ')} FROM ${qualified(found)}${where.text} FOR UPDATE`;
1789
+ // Locked already, behind this transaction's BEGIN (openPlain): it holds the lock until it ends.
1790
+ const held = heldLocks.get(write)?.get(lockKey(text, where.params));
1791
+ if (held)
1792
+ return held();
1793
+ const result = await write.query(text, where.params);
1794
+ if (result.rows.length > 1)
1795
+ throw new Refusal('That primary key does not identify a single record.');
1796
+ }
1797
+ /**
1798
+ * Identifiers cannot be bound, so a table name is checked against the
1799
+ * catalog before it is quoted into a statement. The check is a parameterised
1800
+ * query, which means the untrusted string never reaches SQL as syntax.
1801
+ */
1802
+ /**
1803
+ * The same check for a read, answered from the catalog read on connect when
1804
+ * it holds the name. That probe was a round trip before every list and
1805
+ * every count — two per page of rows, one per reference counted — to learn
1806
+ * what the catalog already said. A name the catalog does not hold (made
1807
+ * since) is still asked of the server; writes always are (assertTable),
1808
+ * because a view created since connecting must still refuse one.
1809
+ */
1810
+ async readTable(id) {
1811
+ const dot = id.indexOf('.');
1812
+ const schema = dot === -1 ? 'public' : id.slice(0, dot);
1813
+ if (RESERVED_SCHEMAS.includes(schema))
1814
+ throw new Refusal('Reserved resources are runtime-only.');
1815
+ const known = this.cachedSchema?.tables.find((table) => table.id === id);
1816
+ if (known?.schema && !RESERVED_SCHEMAS.includes(known.schema)) {
1817
+ return { schema: known.schema, name: known.name, kind: known.isView ? 'v' : 'r', isView: known.isView };
1818
+ }
1819
+ return this.assertTable(id);
1820
+ }
1821
+ epochOf = (db) => (db ? this.txEpochs.get(db) : undefined) ?? (this.epochStore === false ? epochlessEpoch() : undefined);
1822
+ async assertTable(id, db) {
1823
+ return assertPostgresTable(id, db, this.epochOf(db), this.catalogCache, () => this.conn());
1824
+ }
1825
+ }
1826
+ /** A verifier's pin, when it is only LOCK statements with no parameters (it rides in the simple-protocol message).
1827
+ Anything else is not taken: the transaction then runs as it would without one, and its verifier attests in full. */
1828
+ function verifierPin(verify) {
1829
+ const pin = verify?.pin;
1830
+ return typeof pin === 'string' && /^LOCK TABLE [^;$]+ IN [A-Z ]+ MODE(; LOCK TABLE [^;$]+ IN [A-Z ]+ MODE)*$/.test(pin) ? pin : undefined;
1831
+ }
1832
+ /* Handles whose transaction reads one snapshot (snapshotRead.ts): REPEATABLE READ from its BEGIN, so every statement
1833
+ reads as of its first. Kept on the handle, as its epoch is, so a retry of the opening begins the same way. */
1834
+ const snapshotHandles = new WeakSet();
1835
+ const beginOf = (write) => (snapshotHandles.has(write) ? 'BEGIN ISOLATION LEVEL REPEATABLE READ' : 'BEGIN');
1836
+ /* What a scoped transaction's BEGIN also says, in its one message: the text a date is read as, whatever the role or
1837
+ database set. A check binds a key's stored text and the database reads it back (storedText.ts, keyTypes.ts); under
1838
+ `DateStyle = 'SQL, YMD'` a date said as 01/02/2026 reads back as another day. Only the output style is set: the
1839
+ field order, which decides how a person's own 01/02/2026 is read, stays the database's. The float and interval
1840
+ text, which no key is (keyTypes.ts), is pinned as well, so a value a trigger's proof compares reads as stored. */
1841
+ const SCOPED_SESSION = '; SET LOCAL DateStyle = ISO; SET LOCAL IntervalStyle = postgres; SET LOCAL extra_float_digits = 3';