@rebasepro/server-postgres 0.30.1 → 0.31.0-canary.g902a0ce

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 (248) hide show
  1. package/README.md +11 -8
  2. package/dist/{BranchService-CrXvcES2.js → BranchService-USp1AvZB.js} +3 -3
  3. package/dist/{BranchService-CrXvcES2.js.map → BranchService-USp1AvZB.js.map} +1 -1
  4. package/dist/PostgresBackendDriver.d.ts +99 -54
  5. package/dist/PostgresBootstrapper.d.ts +12 -27
  6. package/dist/auth/ensure-tables.d.ts +16 -5
  7. package/dist/auth/schema-version.d.ts +2 -2
  8. package/dist/auth/services.d.ts +2 -3
  9. package/dist/{auth-users-columns-C72EMoDJ.js → auth-users-columns-BpfgbkxZ.js} +2 -16
  10. package/dist/auth-users-columns-BpfgbkxZ.js.map +1 -0
  11. package/dist/{backup-cli-CTKCOLpX.js → backup-cli-DbKyEj6c.js} +4 -4
  12. package/dist/{backup-cli-CTKCOLpX.js.map → backup-cli-DbKyEj6c.js.map} +1 -1
  13. package/dist/{boot-ddl-CqGIwSYx.js → boot-ddl-5H2bL_80.js} +2 -2
  14. package/dist/{boot-ddl-CqGIwSYx.js.map → boot-ddl-5H2bL_80.js.map} +1 -1
  15. package/dist/{cli-console-DBPw-oAz.js → cli-console-DsRgGSBR.js} +65 -39
  16. package/dist/cli-console-DsRgGSBR.js.map +1 -0
  17. package/dist/cli-console.d.ts +16 -13
  18. package/dist/cli-flags.d.ts +8 -9
  19. package/dist/cli-helpers.d.ts +15 -11
  20. package/dist/{cli-errors-DYTxnLbW.js → cli-schema-dir-CiN0ephV.js} +184 -70
  21. package/dist/cli-schema-dir-CiN0ephV.js.map +1 -0
  22. package/dist/cli-schema-dir.d.ts +64 -0
  23. package/dist/cli.js +192 -257
  24. package/dist/cli.js.map +1 -1
  25. package/dist/data-transformer.d.ts +50 -19
  26. package/dist/{database-preflight-iBpT7-vv.js → database-preflight-bfnIBnjM.js} +5 -5
  27. package/dist/database-preflight-bfnIBnjM.js.map +1 -0
  28. package/dist/{deferred-index-build-BCU9RoHK.js → deferred-index-build-CcSDA7wE.js} +69 -13
  29. package/dist/deferred-index-build-CcSDA7wE.js.map +1 -0
  30. package/dist/{ensure-collection-policies-Bo-_fDAy.js → ensure-policies-rRmXb5bt.js} +31 -31
  31. package/dist/ensure-policies-rRmXb5bt.js.map +1 -0
  32. package/dist/{ensure-collection-tables-DCJINkT_.js → ensure-tables-Bvm-F2wW.js} +44 -37
  33. package/dist/ensure-tables-Bvm-F2wW.js.map +1 -0
  34. package/dist/{ensure-tables-BPGaGh0y.js → ensure-tables-CC8p_AK3.js} +34 -29
  35. package/dist/ensure-tables-CC8p_AK3.js.map +1 -0
  36. package/dist/{enum-labels-kept-YAgOZS4I.js → enum-labels-kept-FlX9SHdf.js} +8 -8
  37. package/dist/enum-labels-kept-FlX9SHdf.js.map +1 -0
  38. package/dist/{generate-drizzle-schema-DcrFr7YX.js → generate-drizzle-schema-SJMXxzPI.js} +12 -12
  39. package/dist/generate-drizzle-schema-SJMXxzPI.js.map +1 -0
  40. package/dist/{generate-drizzle-schema-logic-LTLZvt6r.js → generate-drizzle-schema-logic-DL7R1rAF.js} +15 -8
  41. package/dist/generate-drizzle-schema-logic-DL7R1rAF.js.map +1 -0
  42. package/dist/{generate-files-CsaVzatS.js → generate-files-tlJ9_lGI.js} +23 -30
  43. package/dist/generate-files-tlJ9_lGI.js.map +1 -0
  44. package/dist/{generate-next-step-DgK5BlBn.js → generate-next-step-CO09dovd.js} +3 -3
  45. package/dist/generate-next-step-CO09dovd.js.map +1 -0
  46. package/dist/{generate-postgres-ddl-logic-Dg0bcENZ.js → generate-postgres-ddl-logic-B8huc03c.js} +51 -21
  47. package/dist/generate-postgres-ddl-logic-B8huc03c.js.map +1 -0
  48. package/dist/{generated-schema-diff-By4dxyTH.js → generated-schema-diff-DoT2dYDe.js} +297 -279
  49. package/dist/generated-schema-diff-DoT2dYDe.js.map +1 -0
  50. package/dist/{generated-schema-staleness-BvNF3i-s.js → generated-schema-staleness-YBVq2kTn.js} +21 -29
  51. package/dist/generated-schema-staleness-YBVq2kTn.js.map +1 -0
  52. package/dist/history/ensure-history-table.d.ts +22 -0
  53. package/dist/index.d.ts +8 -2
  54. package/dist/index.es.js +201 -25
  55. package/dist/index.es.js.map +1 -1
  56. package/dist/interfaces.d.ts +3 -4
  57. package/dist/{introspect-db-queries-DevUrzll.js → introspect-db-queries-BgiRQqtR.js} +7 -2
  58. package/dist/introspect-db-queries-BgiRQqtR.js.map +1 -0
  59. package/dist/introspect-tables-Cw_A-kk4.js +2086 -0
  60. package/dist/introspect-tables-Cw_A-kk4.js.map +1 -0
  61. package/dist/load-tables-B1Re74ng.js +92 -0
  62. package/dist/load-tables-B1Re74ng.js.map +1 -0
  63. package/dist/{migrate-baseline-CmWXL7qx.js → migrate-baseline-DZmekgpD.js} +19 -32
  64. package/dist/migrate-baseline-DZmekgpD.js.map +1 -0
  65. package/dist/{migrate-policy-stamps-BN_Qad6c.js → migrate-policy-stamps-B_acrUQB.js} +18 -19
  66. package/dist/migrate-policy-stamps-B_acrUQB.js.map +1 -0
  67. package/dist/model/PostgresTableRegistry.d.ts +159 -0
  68. package/dist/model/build-registry.d.ts +25 -0
  69. package/dist/model/refresh-relational-schema.d.ts +24 -0
  70. package/dist/model/runtime-table.d.ts +53 -0
  71. package/dist/{collections → model}/validate-relations.d.ts +15 -21
  72. package/dist/{open-rebase-40paQfVW.js → open-rebase-4kisUF_k.js} +3946 -3870
  73. package/dist/open-rebase-4kisUF_k.js.map +1 -0
  74. package/dist/open-rebase.d.ts +16 -15
  75. package/dist/{pg-error-utils-DJHjCF7-.js → pg-error-utils-BT5NzGFZ.js} +17 -20
  76. package/dist/pg-error-utils-BT5NzGFZ.js.map +1 -0
  77. package/dist/plan-schema-Hbtjhge3.js +1633 -0
  78. package/dist/plan-schema-Hbtjhge3.js.map +1 -0
  79. package/dist/{policy-drift-C-m0uWHH.js → policy-drift-BVMyqHSa.js} +29 -29
  80. package/dist/policy-drift-BVMyqHSa.js.map +1 -0
  81. package/dist/{push-index-adoption-Cp7oZxSl.js → push-index-adoption-hpHTyXMR.js} +7 -7
  82. package/dist/push-index-adoption-hpHTyXMR.js.map +1 -0
  83. package/dist/{push-index-prebuild-DbwKGtQT.js → push-index-prebuild-Bty9F7bD.js} +6 -6
  84. package/dist/push-index-prebuild-Bty9F7bD.js.map +1 -0
  85. package/dist/{push-kept-defaults-CLcgsEPt.js → push-kept-defaults-Bst4MDup.js} +13 -16
  86. package/dist/push-kept-defaults-Bst4MDup.js.map +1 -0
  87. package/dist/{push-legacy-renames-BthD0E9W.js → push-legacy-renames-bB4bM6br.js} +6 -6
  88. package/dist/push-legacy-renames-bB4bM6br.js.map +1 -0
  89. package/dist/{push-policy-plan-BgcrroxQ.js → push-policy-plan-BI8U4BOD.js} +11 -11
  90. package/dist/push-policy-plan-BI8U4BOD.js.map +1 -0
  91. package/dist/{render-ddl-Ci3S_SoI.js → render-ddl-D4n86NHz.js} +14 -7
  92. package/dist/render-ddl-D4n86NHz.js.map +1 -0
  93. package/dist/{request-role-cli-Dy1EgJU9.js → request-role-cli-BdRzdE87.js} +11 -11
  94. package/dist/{request-role-cli-Dy1EgJU9.js.map → request-role-cli-BdRzdE87.js.map} +1 -1
  95. package/dist/{request-role-migration-GHTJnPMV.js → request-role-migration-C8aq_TO3.js} +2 -2
  96. package/dist/{request-role-migration-GHTJnPMV.js.map → request-role-migration-C8aq_TO3.js.map} +1 -1
  97. package/dist/{rls-enforcement-Cc_UhOxb.js → rls-enforcement-DB5HHj96.js} +19 -19
  98. package/dist/rls-enforcement-DB5HHj96.js.map +1 -0
  99. package/dist/{rls-settings-BCGMIig3.js → rls-settings-CmGK2U0a.js} +2 -2
  100. package/dist/rls-settings-CmGK2U0a.js.map +1 -0
  101. package/dist/schema/auth-users-columns.d.ts +1 -11
  102. package/dist/schema/catalogue-schema.d.ts +33 -29
  103. package/dist/schema/classify-change.d.ts +23 -16
  104. package/dist/schema/column-type-drift.d.ts +16 -0
  105. package/dist/schema/config-relations.d.ts +10 -9
  106. package/dist/schema/deferred-index-build.d.ts +1 -1
  107. package/dist/schema/doctor-cli.js +1544 -66
  108. package/dist/schema/doctor-cli.js.map +1 -1
  109. package/dist/schema/doctor-database.d.ts +7 -7
  110. package/dist/schema/doctor-policy-checks.d.ts +4 -4
  111. package/dist/schema/doctor-search-scale.d.ts +14 -14
  112. package/dist/schema/doctor.d.ts +27 -27
  113. package/dist/schema/dynamic-tables.d.ts +6 -5
  114. package/dist/schema/{ensure-collection-policies.d.ts → ensure-policies.d.ts} +20 -20
  115. package/dist/schema/{ensure-collection-tables.d.ts → ensure-tables.d.ts} +11 -11
  116. package/dist/schema/enum-labels-kept.d.ts +6 -6
  117. package/dist/schema/generate-drizzle-schema-logic.d.ts +3 -3
  118. package/dist/schema/generate-drizzle-schema.js +1 -1
  119. package/dist/schema/generate-files.d.ts +6 -6
  120. package/dist/schema/generate-postgres-ddl-logic.d.ts +23 -20
  121. package/dist/schema/generate-postgres-ddl.js +11 -11
  122. package/dist/schema/generate-postgres-ddl.js.map +1 -1
  123. package/dist/schema/generate-schema-commit.d.ts +13 -8
  124. package/dist/schema/generated-schema-diff.d.ts +16 -16
  125. package/dist/schema/generated-schema-staleness.d.ts +11 -11
  126. package/dist/schema/index-adoption.d.ts +4 -4
  127. package/dist/schema/introspect-db-customization.d.ts +47 -0
  128. package/dist/schema/introspect-db-inference.d.ts +30 -9
  129. package/dist/schema/introspect-db-logic.d.ts +79 -110
  130. package/dist/schema/introspect-db-project.d.ts +15 -18
  131. package/dist/schema/introspect-db-queries.d.ts +1 -1
  132. package/dist/schema/introspect-db-search.d.ts +25 -4
  133. package/dist/schema/introspect-db-storage.d.ts +4 -74
  134. package/dist/schema/introspect-db.js +102 -90
  135. package/dist/schema/introspect-db.js.map +1 -1
  136. package/dist/schema/introspect-runtime.d.ts +47 -36
  137. package/dist/schema/introspect-tables.d.ts +182 -0
  138. package/dist/schema/load-tables.d.ts +55 -0
  139. package/dist/schema/migrate-policy-stamps.d.ts +4 -4
  140. package/dist/schema/migration-freshness.d.ts +13 -13
  141. package/dist/schema/plan/column-order.d.ts +82 -0
  142. package/dist/schema/plan/diff-plan.d.ts +9 -3
  143. package/dist/schema/plan/plan-schema.d.ts +55 -52
  144. package/dist/schema/plan/render-drizzle.d.ts +1 -1
  145. package/dist/schema/plan/types.d.ts +24 -15
  146. package/dist/schema/push-index-adoption.d.ts +3 -3
  147. package/dist/schema/push-index-prebuild.d.ts +3 -3
  148. package/dist/schema/push-kept-defaults.d.ts +7 -7
  149. package/dist/schema/push-legacy-renames.d.ts +3 -3
  150. package/dist/schema/push-policy-plan.d.ts +5 -5
  151. package/dist/schema/reconcile-schema.d.ts +5 -5
  152. package/dist/schema/relation-names.d.ts +15 -20
  153. package/dist/schema/render-outputs.d.ts +76 -0
  154. package/dist/schema/search-column.d.ts +11 -43
  155. package/dist/schema/{collection-index.d.ts → table-index.d.ts} +21 -42
  156. package/dist/schema/{collections-schema-version.d.ts → tables-schema-version.d.ts} +8 -2
  157. package/dist/schema/vector-index.d.ts +24 -28
  158. package/dist/{search-column-BM-GV6vH.js → search-column-BO-WND-B.js} +86 -149
  159. package/dist/search-column-BO-WND-B.js.map +1 -0
  160. package/dist/security/caller-sql-columns.d.ts +9 -6
  161. package/dist/security/policy-drift.d.ts +14 -14
  162. package/dist/security/rls-enforcement.d.ts +19 -25
  163. package/dist/security/rls-settings.d.ts +2 -2
  164. package/dist/security/served-table-protection.d.ts +125 -0
  165. package/dist/services/FetchService.d.ts +22 -133
  166. package/dist/services/PersistService.d.ts +6 -17
  167. package/dist/services/RelationService.d.ts +57 -106
  168. package/dist/services/RelationWriteService.d.ts +59 -66
  169. package/dist/services/cdc/identity-columns.d.ts +7 -5
  170. package/dist/services/cdc/junction-tables.d.ts +14 -14
  171. package/dist/services/collection-helpers.d.ts +52 -95
  172. package/dist/services/dataService.d.ts +15 -12
  173. package/dist/services/field-op-sql.d.ts +11 -9
  174. package/dist/services/field-viewer.d.ts +12 -11
  175. package/dist/services/hidden-columns.d.ts +30 -0
  176. package/dist/services/index.d.ts +1 -1
  177. package/dist/services/junction-writes.d.ts +37 -18
  178. package/dist/services/nested-path.d.ts +18 -18
  179. package/dist/services/read-field-access.d.ts +23 -7
  180. package/dist/services/read-scope.d.ts +10 -9
  181. package/dist/services/realtimeService.d.ts +25 -10
  182. package/dist/services/relation-tables.d.ts +97 -0
  183. package/dist/services/row-pipeline.d.ts +50 -69
  184. package/dist/services/soft-delete.d.ts +25 -24
  185. package/dist/services/table-hooks.d.ts +146 -0
  186. package/dist/services/view-access.d.ts +7 -7
  187. package/dist/services/write-transaction-scope.d.ts +1 -1
  188. package/dist/{source-fZb92pN8.js → source-VxbrQojV.js} +111 -79
  189. package/dist/source-VxbrQojV.js.map +1 -0
  190. package/dist/{collections-schema-version-D7bDI0PJ.js → tables-schema-version-YvZIBlOP.js} +12 -6
  191. package/dist/tables-schema-version-YvZIBlOP.js.map +1 -0
  192. package/dist/utils/drizzle-conditions.d.ts +70 -84
  193. package/dist/utils/pg-array-null-patch.d.ts +27 -10
  194. package/dist/utils/pg-error-utils.d.ts +4 -4
  195. package/dist/{vector-index-DsQ3V2d2.js → vector-index-VSh3ufTd.js} +62 -54
  196. package/dist/vector-index-VSh3ufTd.js.map +1 -0
  197. package/dist/{websocket-B7ex6AQM.js → websocket-BevXvwfo.js} +51 -40
  198. package/dist/websocket-BevXvwfo.js.map +1 -0
  199. package/dist/websocket.d.ts +2 -2
  200. package/package.json +7 -7
  201. package/dist/auth-users-columns-C72EMoDJ.js.map +0 -1
  202. package/dist/cli-collections-path.d.ts +0 -31
  203. package/dist/cli-console-DBPw-oAz.js.map +0 -1
  204. package/dist/cli-errors-DYTxnLbW.js.map +0 -1
  205. package/dist/collections/PostgresCollectionRegistry.d.ts +0 -47
  206. package/dist/collections/buildRegistry.d.ts +0 -27
  207. package/dist/collections-schema-version-D7bDI0PJ.js.map +0 -1
  208. package/dist/column-plan-helpers-BeSztMor.js +0 -161
  209. package/dist/column-plan-helpers-BeSztMor.js.map +0 -1
  210. package/dist/database-preflight-iBpT7-vv.js.map +0 -1
  211. package/dist/deferred-index-build-BCU9RoHK.js.map +0 -1
  212. package/dist/doctor-Kg1oUK0Q.js +0 -1458
  213. package/dist/doctor-Kg1oUK0Q.js.map +0 -1
  214. package/dist/ensure-collection-policies-Bo-_fDAy.js.map +0 -1
  215. package/dist/ensure-collection-tables-DCJINkT_.js.map +0 -1
  216. package/dist/ensure-tables-BPGaGh0y.js.map +0 -1
  217. package/dist/enum-labels-kept-YAgOZS4I.js.map +0 -1
  218. package/dist/generate-drizzle-schema-DcrFr7YX.js.map +0 -1
  219. package/dist/generate-drizzle-schema-logic-LTLZvt6r.js.map +0 -1
  220. package/dist/generate-files-CsaVzatS.js.map +0 -1
  221. package/dist/generate-next-step-DgK5BlBn.js.map +0 -1
  222. package/dist/generate-postgres-ddl-logic-Dg0bcENZ.js.map +0 -1
  223. package/dist/generated-schema-diff-By4dxyTH.js.map +0 -1
  224. package/dist/generated-schema-staleness-BvNF3i-s.js.map +0 -1
  225. package/dist/introspect-db-logic-DWqAEURB.js +0 -2047
  226. package/dist/introspect-db-logic-DWqAEURB.js.map +0 -1
  227. package/dist/introspect-db-queries-DevUrzll.js.map +0 -1
  228. package/dist/migrate-baseline-CmWXL7qx.js.map +0 -1
  229. package/dist/migrate-policy-stamps-BN_Qad6c.js.map +0 -1
  230. package/dist/open-rebase-40paQfVW.js.map +0 -1
  231. package/dist/pg-error-utils-DJHjCF7-.js.map +0 -1
  232. package/dist/plan-schema-vJd3UEmT.js +0 -1604
  233. package/dist/plan-schema-vJd3UEmT.js.map +0 -1
  234. package/dist/policy-drift-C-m0uWHH.js.map +0 -1
  235. package/dist/push-index-adoption-Cp7oZxSl.js.map +0 -1
  236. package/dist/push-index-prebuild-DbwKGtQT.js.map +0 -1
  237. package/dist/push-kept-defaults-CLcgsEPt.js.map +0 -1
  238. package/dist/push-legacy-renames-BthD0E9W.js.map +0 -1
  239. package/dist/push-policy-plan-BgcrroxQ.js.map +0 -1
  240. package/dist/render-ddl-Ci3S_SoI.js.map +0 -1
  241. package/dist/rls-enforcement-Cc_UhOxb.js.map +0 -1
  242. package/dist/rls-settings-BCGMIig3.js.map +0 -1
  243. package/dist/schema/column-plan-helpers.d.ts +0 -161
  244. package/dist/schema/introspect-db-naming.d.ts +0 -10
  245. package/dist/search-column-BM-GV6vH.js.map +0 -1
  246. package/dist/source-fZb92pN8.js.map +0 -1
  247. package/dist/vector-index-DsQ3V2d2.js.map +0 -1
  248. package/dist/websocket-B7ex6AQM.js.map +0 -1
@@ -1,13 +1,12 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { u as pinSearchPath } from "./connection-C1zXTPJq.js";
4
- import { U as withAppClient } from "./cli-errors-DYTxnLbW.js";
5
- import { a as outWarn, r as out, t as chalk } from "./source-fZb92pN8.js";
6
- import { c as planCollectionPolicies } from "./generate-postgres-ddl-logic-Dg0bcENZ.js";
7
- import { n as loadCollections } from "./doctor-Kg1oUK0Q.js";
8
- import { ensureCollectionPolicies, policyStampSql, probeRenderedPolicies, readPolicyStamps } from "./ensure-collection-policies-Bo-_fDAy.js";
9
- import { underSearchPath } from "./push-policy-plan-BgcrroxQ.js";
10
- import path from "path";
4
+ import { G as withAppClient } from "./cli-schema-dir-CiN0ephV.js";
5
+ import { a as outWarn, r as out, t as chalk } from "./source-VxbrQojV.js";
6
+ import { u as planTablePolicies } from "./generate-postgres-ddl-logic-B8huc03c.js";
7
+ import { r as loadTables } from "./load-tables-B1Re74ng.js";
8
+ import { ensureTablePolicies, policyStampSql, probeRenderedPolicies, readPolicyStamps } from "./ensure-policies-rRmXb5bt.js";
9
+ import { underSearchPath } from "./push-policy-plan-BI8U4BOD.js";
11
10
  //#region src/schema/migrate-policy-stamps.ts
12
11
  /**
13
12
  * The stamps `rebase db migrate` leaves on the policies it applied.
@@ -21,7 +20,7 @@ import path from "path";
21
20
  * blog scaffold.
22
21
  *
23
22
  * Migrate cannot stamp what the files hold, the way push stamps what it just
24
- * ran: a migration was written from the collections of its day, and the
23
+ * ran: a migration was written from the tables of its day, and the
25
24
  * database may hold something a later one, or a hand, made since. A stamp
26
25
  * there would tell the boot a policy is what the rule makes when it is not, and
27
26
  * the boot would never put it right. So each declared policy without a current
@@ -37,11 +36,11 @@ import path from "path";
37
36
  * unstamped costs the next boot a re-apply of its table, which is what every
38
37
  * boot after a migrate did before this.
39
38
  */
40
- async function stampMigratedPolicies(databaseUrl, collectionsPath, adminRoleAvailable = true) {
39
+ async function stampMigratedPolicies(databaseUrl, schemaDir, adminRoleAvailable = true) {
41
40
  try {
42
- const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
41
+ const compiledTables = await loadTables(schemaDir);
43
42
  const searchPath = pinSearchPath(databaseUrl) === databaseUrl ? void 0 : "public";
44
- const { stamped } = await withAppClient(databaseUrl, (client) => stampPoliciesStoredAsRendered({ query: async (text, values) => ({ rows: (await client.query(text, values)).rows }) }, collections, {
43
+ const { stamped } = await withAppClient(databaseUrl, (client) => stampPoliciesStoredAsRendered({ query: async (text, values) => ({ rows: (await client.query(text, values)).rows }) }, compiledTables, {
45
44
  searchPath,
46
45
  adminRoleAvailable
47
46
  }));
@@ -59,11 +58,11 @@ async function stampMigratedPolicies(databaseUrl, collectionsPath, adminRoleAvai
59
58
  * whose spelling depends on it. See `PolicyStamping.searchPath`.
60
59
  * @returns how many policies were stamped.
61
60
  */
62
- async function stampPoliciesStoredAsRendered(client, collections, options = {}) {
61
+ async function stampPoliciesStoredAsRendered(client, compiledTables, options = {}) {
63
62
  const { adminRoleAvailable } = options;
64
- const plans = planCollectionPolicies(collections, { adminRoleAvailable });
63
+ const plans = planTablePolicies(compiledTables, { adminRoleAvailable });
65
64
  if (plans.length === 0) return { stamped: 0 };
66
- const states = await underSearchPath(client, options.searchPath, () => readPolicyStamps(client, collections, { adminRoleAvailable }));
65
+ const states = await underSearchPath(client, options.searchPath, () => readPolicyStamps(client, compiledTables, { adminRoleAvailable }));
67
66
  const unsure = [];
68
67
  for (const plan of plans) for (const [name, state] of states.get(plan.qualified) ?? []) if (state !== "current") unsure.push({
69
68
  schema: plan.schema,
@@ -71,7 +70,7 @@ async function stampPoliciesStoredAsRendered(client, collections, options = {})
71
70
  name
72
71
  });
73
72
  if (unsure.length === 0) return { stamped: 0 };
74
- const confirmed = await probeRenderedPolicies(client, collections, unsure, {
73
+ const confirmed = await probeRenderedPolicies(client, compiledTables, unsure, {
75
74
  searchPath: options.searchPath,
76
75
  adminRoleAvailable
77
76
  });
@@ -106,13 +105,13 @@ async function stampPoliciesStoredAsRendered(client, collections, options = {})
106
105
  *
107
106
  * @returns how many policies were written again.
108
107
  */
109
- async function moveMigratedAdminPoliciesToPublic(client, collections, log) {
110
- if (!planCollectionPolicies(collections).some((plan) => plan.policies.some((policy) => policy.adminTarget))) return 0;
111
- const outcome = await ensureCollectionPolicies(client, collections, log, { adminRoleAvailable: false });
108
+ async function moveMigratedAdminPoliciesToPublic(client, compiledTables, log) {
109
+ if (!planTablePolicies(compiledTables).some((plan) => plan.policies.some((policy) => policy.adminTarget))) return 0;
110
+ const outcome = await ensureTablePolicies(client, compiledTables, log, { adminRoleAvailable: false });
112
111
  if (outcome.failures.length > 0) throw new Error(outcome.failures.map((f) => `${f.table}: ${f.error}`).join("; "));
113
112
  return outcome.policiesApplied;
114
113
  }
115
114
  //#endregion
116
115
  export { moveMigratedAdminPoliciesToPublic, stampMigratedPolicies };
117
116
 
118
- //# sourceMappingURL=migrate-policy-stamps-BN_Qad6c.js.map
117
+ //# sourceMappingURL=migrate-policy-stamps-B_acrUQB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migrate-policy-stamps-B_acrUQB.js","names":[],"sources":["../src/schema/migrate-policy-stamps.ts"],"sourcesContent":["/**\n * The stamps `rebase db migrate` leaves on the policies it applied.\n *\n * A boot leaves a table's policies alone only when each carries the stamp a\n * boot or a push writes (`COMMENT ON POLICY … IS 'rebase:<hash>'`, see\n * `policyStampSql`). `db push` stamps what `policies.sql` just created. A\n * migration runs the same statements — `db generate` appends `policies.sql` to\n * it — and stamped nothing, so the first boot after every migrate dropped and\n * re-created every policy once, an ACCESS EXCLUSIVE lock per table: 44 on the\n * blog scaffold.\n *\n * Migrate cannot stamp what the files hold, the way push stamps what it just\n * ran: a migration was written from the tables of its day, and the\n * database may hold something a later one, or a hand, made since. A stamp\n * there would tell the boot a policy is what the rule makes when it is not, and\n * the boot would never put it right. So each declared policy without a current\n * stamp is asked of Postgres instead, as `db push --dry-run` asks it\n * (`probeRenderedPolicies`): made again from its rule under a probe name, in a\n * transaction that is rolled back, and compared. Only a policy whose stored\n * definition is exactly what its rule makes is stamped. Any other keeps no\n * stamp, and the boot re-applies its table, as before.\n */\nimport chalk from \"chalk\";\nimport type { CompiledTable } from \"@rebasepro/types\";\nimport type { Queryable } from \"../security/policy-drift\";\nimport { withAppClient } from \"../cli-helpers\";\nimport { out, outWarn } from \"../cli-output\";\nimport { pinSearchPath } from \"../connection\";\nimport { planTablePolicies } from \"./generate-postgres-ddl-logic\";\nimport { ensureTablePolicies, policyStampSql, probeRenderedPolicies, readPolicyStamps } from \"./ensure-policies\";\nimport { underSearchPath } from \"./push-policy-plan\";\nimport { loadTables } from \"./load-tables\";\n\n/**\n * `rebase db migrate`'s last step: stamp what the migration left as its rules\n * make it, on this process's connection. Never fatal — a policy left\n * unstamped costs the next boot a re-apply of its table, which is what every\n * boot after a migrate did before this.\n */\nexport async function stampMigratedPolicies(databaseUrl: string, schemaDir: string, adminRoleAvailable = true): Promise<void> {\n try {\n const compiledTables = await loadTables(schemaDir);\n // The rule the boot's connections follow: `search_path=public` unless\n // the URL pins one of its own, in which case this connection has it too.\n const searchPath = pinSearchPath(databaseUrl) === databaseUrl ? undefined : \"public\";\n const { stamped } = await withAppClient(databaseUrl, client => stampPoliciesStoredAsRendered(\n { query: async (text, values) => ({ rows: (await client.query(text, values)).rows }) },\n compiledTables,\n { searchPath, adminRoleAvailable }\n ));\n if (stamped > 0) {\n out(chalk.gray(` ✓ Stamped ${stamped} RLS ${stamped === 1 ? \"policy\" : \"policies\"} as their rules make them, so the next boot leaves ${stamped === 1 ? \"it\" : \"them\"} alone.`));\n }\n } catch (err) {\n outWarn(chalk.yellow(` ⚠️ The policies could not be stamped (${err instanceof Error ? err.message : String(err)}); the next boot applies them again.`));\n }\n}\n\n/**\n * Stamp every declared policy whose stored definition its rule would store\n * as it is, and none other.\n *\n * @param options.searchPath the `search_path` a boot reads policies under,\n * when the connection's own differs — the stamp hashes `pg_get_expr`,\n * whose spelling depends on it. See `PolicyStamping.searchPath`.\n * @returns how many policies were stamped.\n */\nexport async function stampPoliciesStoredAsRendered(\n client: Queryable,\n compiledTables: readonly CompiledTable[],\n options: { searchPath?: string; adminRoleAvailable?: boolean } = {}\n): Promise<{ stamped: number }> {\n const { adminRoleAvailable } = options;\n const plans = planTablePolicies(compiledTables, { adminRoleAvailable });\n if (plans.length === 0) return { stamped: 0 };\n\n const states = await underSearchPath(client, options.searchPath, () => readPolicyStamps(client, compiledTables, { adminRoleAvailable }));\n const unsure: { schema: string; table: string; name: string }[] = [];\n for (const plan of plans) {\n for (const [name, state] of states.get(plan.qualified) ?? []) {\n if (state !== \"current\") unsure.push({ schema: plan.schema, table: plan.table, name });\n }\n }\n if (unsure.length === 0) return { stamped: 0 };\n\n const confirmed = await probeRenderedPolicies(client, compiledTables, unsure, { searchPath: options.searchPath, adminRoleAvailable });\n const statements: string[] = [];\n let stamped = 0;\n for (const plan of plans) {\n const names = new Set(unsure\n .filter(p => p.schema === plan.schema && p.table === plan.table\n && confirmed.get(`${p.schema}.${p.table}.${p.name}`) === true)\n .map(p => p.name));\n const statement = names.size > 0 ? policyStampSql(plan, names) : undefined;\n if (!statement) continue;\n statements.push(statement);\n stamped += names.size;\n }\n if (statements.length === 0) return { stamped: 0 };\n\n await underSearchPath(client, options.searchPath, async () => {\n for (const statement of statements) await client.query(statement);\n });\n return { stamped };\n}\n\n/**\n * Where the admin switch is not live, move the server-or-admin policies a\n * migration just wrote `TO rebase_admin` back `TO public`, as `db push` and a\n * provisioning boot write them.\n *\n * A migration replays `policies.sql` as `db generate` wrote it, and that cannot\n * know the database it will run on. Left `TO rebase_admin` while admin requests\n * still run as the request role, those policies refuse every admin caller —\n * `dataAsAdmin` in crons, jobs and functions included — and a boot with\n * `REBASE_PROVISION=false` never puts them right.\n *\n * This is the boot's own ensure under the fallback plan, so a table whose\n * policies are already what that plan makes is left alone.\n *\n * @returns how many policies were written again.\n */\nexport async function moveMigratedAdminPoliciesToPublic(\n client: Queryable,\n compiledTables: readonly CompiledTable[],\n log?: (message: string) => void\n): Promise<number> {\n if (!planTablePolicies(compiledTables).some(plan => plan.policies.some(policy => policy.adminTarget))) return 0;\n const outcome = await ensureTablePolicies(client, compiledTables, log, { adminRoleAvailable: false });\n if (outcome.failures.length > 0) {\n throw new Error(outcome.failures.map(f => `${f.table}: ${f.error}`).join(\"; \"));\n }\n return outcome.policiesApplied;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,eAAsB,sBAAsB,aAAqB,WAAmB,qBAAqB,MAAqB;CAC1H,IAAI;EACA,MAAM,iBAAiB,MAAM,WAAW,SAAS;EAGjD,MAAM,aAAa,cAAc,WAAW,MAAM,cAAc,KAAA,IAAY;EAC5E,MAAM,EAAE,YAAY,MAAM,cAAc,cAAa,WAAU,8BAC3D,EAAE,OAAO,OAAO,MAAM,YAAY,EAAE,OAAO,MAAM,OAAO,MAAM,MAAM,MAAM,EAAA,CAAG,KAAK,GAAG,GACrF,gBACA;GAAE;GAAY;EAAmB,CACrC,CAAC;EACD,IAAI,UAAU,GACV,IAAI,MAAM,KAAK,eAAe,QAAQ,OAAO,YAAY,IAAI,WAAW,WAAW,qDAAqD,YAAY,IAAI,OAAO,OAAO,QAAQ,CAAC;CAEvL,SAAS,KAAK;EACV,QAAQ,MAAM,OAAO,4CAA4C,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EAAE,qCAAqC,CAAC;CAC5J;AACJ;;;;;;;;;;AAWA,eAAsB,8BAClB,QACA,gBACA,UAAiE,CAAC,GACtC;CAC5B,MAAM,EAAE,uBAAuB;CAC/B,MAAM,QAAQ,kBAAkB,gBAAgB,EAAE,mBAAmB,CAAC;CACtE,IAAI,MAAM,WAAW,GAAG,OAAO,EAAE,SAAS,EAAE;CAE5C,MAAM,SAAS,MAAM,gBAAgB,QAAQ,QAAQ,kBAAkB,iBAAiB,QAAQ,gBAAgB,EAAE,mBAAmB,CAAC,CAAC;CACvI,MAAM,SAA4D,CAAC;CACnE,KAAK,MAAM,QAAQ,OACf,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,IAAI,KAAK,SAAS,KAAK,CAAC,GACvD,IAAI,UAAU,WAAW,OAAO,KAAK;EAAE,QAAQ,KAAK;EAAQ,OAAO,KAAK;EAAO;CAAK,CAAC;CAG7F,IAAI,OAAO,WAAW,GAAG,OAAO,EAAE,SAAS,EAAE;CAE7C,MAAM,YAAY,MAAM,sBAAsB,QAAQ,gBAAgB,QAAQ;EAAE,YAAY,QAAQ;EAAY;CAAmB,CAAC;CACpI,MAAM,aAAuB,CAAC;CAC9B,IAAI,UAAU;CACd,KAAK,MAAM,QAAQ,OAAO;EACtB,MAAM,QAAQ,IAAI,IAAI,OACjB,QAAO,MAAK,EAAE,WAAW,KAAK,UAAU,EAAE,UAAU,KAAK,SACnD,UAAU,IAAI,GAAG,EAAE,OAAO,GAAG,EAAE,MAAM,GAAG,EAAE,MAAM,MAAM,IAAI,CAAC,CACjE,KAAI,MAAK,EAAE,IAAI,CAAC;EACrB,MAAM,YAAY,MAAM,OAAO,IAAI,eAAe,MAAM,KAAK,IAAI,KAAA;EACjE,IAAI,CAAC,WAAW;EAChB,WAAW,KAAK,SAAS;EACzB,WAAW,MAAM;CACrB;CACA,IAAI,WAAW,WAAW,GAAG,OAAO,EAAE,SAAS,EAAE;CAEjD,MAAM,gBAAgB,QAAQ,QAAQ,YAAY,YAAY;EAC1D,KAAK,MAAM,aAAa,YAAY,MAAM,OAAO,MAAM,SAAS;CACpE,CAAC;CACD,OAAO,EAAE,QAAQ;AACrB;;;;;;;;;;;;;;;;;AAkBA,eAAsB,kCAClB,QACA,gBACA,KACe;CACf,IAAI,CAAC,kBAAkB,cAAc,CAAC,CAAC,MAAK,SAAQ,KAAK,SAAS,MAAK,WAAU,OAAO,WAAW,CAAC,GAAG,OAAO;CAC9G,MAAM,UAAU,MAAM,oBAAoB,QAAQ,gBAAgB,KAAK,EAAE,oBAAoB,MAAM,CAAC;CACpG,IAAI,QAAQ,SAAS,SAAS,GAC1B,MAAM,IAAI,MAAM,QAAQ,SAAS,KAAI,MAAK,GAAG,EAAE,MAAM,IAAI,EAAE,OAAO,CAAC,CAAC,KAAK,IAAI,CAAC;CAElF,OAAO,QAAQ;AACnB"}
@@ -0,0 +1,159 @@
1
+ import { type CompiledTable, type RelationDescriptor, type TableHooks, type TableRegistryInterface } from "@rebasepro/types";
2
+ import { type RelatedTables } from "@rebasepro/common";
3
+ import { PgEnum, PgTable } from "drizzle-orm/pg-core";
4
+ import { Relations } from "drizzle-orm";
5
+ import { type RuntimeTable } from "./runtime-table.js";
6
+ /**
7
+ * The tables one Postgres driver serves.
8
+ *
9
+ * Holds, per table, its {@link RuntimeTable} — the compiled table the server
10
+ * handed over, with its catalogue table and lookups — and the drizzle tables,
11
+ * enums and relations read back from this database (junction tables
12
+ * included, which have no runtime table of their own).
13
+ *
14
+ * Tables only: nothing here holds a collection. From a call site that holds
15
+ * a slug: `registry.requireTable(slug)`; that holds a data path (a slug, a
16
+ * table name, or `authors/1/posts`): `registry.tableAt(path)`.
17
+ */
18
+ export declare class PostgresTableRegistry implements TableRegistryInterface {
19
+ private readonly runtimeTables;
20
+ /** Tables declared but not served, by slug: their SQL name and what a caller is told. */
21
+ private readonly withheldTables;
22
+ /** {@link tables}, built once per change: callers cache on its identity. */
23
+ private tableList?;
24
+ private readonly pgTables;
25
+ private readonly enums;
26
+ private readonly relations;
27
+ private globalTableHooks?;
28
+ /**
29
+ * Register compiled tables. Each becomes a {@link RuntimeTable} over the
30
+ * catalogue table of the same SQL name, when one is registered (now or
31
+ * later, through {@link registerPgTable}). A slug registered again is
32
+ * replaced.
33
+ */
34
+ registerTables(tables: readonly CompiledTable[]): void;
35
+ /** The runtime table served at `/api/data/<slug>`, or `undefined`. */
36
+ getTable(slug: string): RuntimeTable | undefined;
37
+ /**
38
+ * Stop serving a declared table: it leaves the runtime tables (so no
39
+ * read, write, include or subscription reaches it), and a request that
40
+ * names it — by slug, kebab-case slug or SQL name, as a root or as a
41
+ * relation's target — is refused with `message` (503 `TABLE_WITHHELD`)
42
+ * rather than "not found". Its catalogue table stays registered: a
43
+ * junction or a policy subquery may still name it.
44
+ *
45
+ * What the boot and a live refresh do with a table the database does not
46
+ * protect (see `security/served-table-protection`).
47
+ */
48
+ withhold(slug: string, message: string): void;
49
+ /** The slugs of the tables {@link withhold} took out, each with what a caller is told. */
50
+ withheld(): ReadonlyMap<string, string>;
51
+ /** Throw the refusal for a withheld table `name` (slug, kebab slug or SQL name) names, if it names one. */
52
+ private refuseWithheld;
53
+ /**
54
+ * The runtime table served at `/api/data/<slug>`. Throws, naming the slug
55
+ * and every table this driver does serve, when there is none — a request
56
+ * that reached the driver for a table it was never given is a wiring
57
+ * defect, never an answer.
58
+ */
59
+ requireTable(slug: string): RuntimeTable;
60
+ /**
61
+ * The runtime table whose SQL name is `name` (unqualified), or `undefined`.
62
+ * The name of a table, never of a junction: those have no runtime table.
63
+ */
64
+ getTableBySqlName(name: string): RuntimeTable | undefined;
65
+ /**
66
+ * Every served table's descriptor, by slug or by SQL name: what a
67
+ * relation's join passes through, for the read gates that judge every
68
+ * column it reads (`relationJoinColumns` in `@rebasepro/common`).
69
+ */
70
+ relatedTables(): RelatedTables;
71
+ /**
72
+ * Refuse a `via` whose steps pass through a withheld table — any step's
73
+ * table, or a `table.column` its join conditions name — with that table's
74
+ * reason (503 `TABLE_WITHHELD`), as a relation into a withheld target is
75
+ * refused. Every caller: the server does not read through a table it
76
+ * refuses to serve, on a read or a write. Any other relation: nothing to do
77
+ * here (a many-to-many over an unprotected junction withholds its owner).
78
+ */
79
+ refuseWithheldJoin(relation: RelationDescriptor): void;
80
+ /** The withheld entry `name` (slug, kebab slug or SQL name) names, if any. */
81
+ private withheldNamed;
82
+ /**
83
+ * The runtime table a root path names: its slug, the slug spelled with
84
+ * hyphens (`blog-posts` for `blog_posts` — URLs are kebab-case), then the
85
+ * table's SQL name. `undefined` when none matches.
86
+ */
87
+ tableNamed(name: string): RuntimeTable | undefined;
88
+ /**
89
+ * The runtime table a data path addresses: a root (`posts`, see
90
+ * {@link tableNamed}) or a walk through relations (`authors/1/posts` — the
91
+ * target of `authors`' relation `posts`). `undefined` for a root that
92
+ * names no table; throws, naming the table and the relation, for a nested
93
+ * path that is malformed or names a relation the table does not have.
94
+ *
95
+ * The walk reads every relation the table declares: whether the caller
96
+ * may address it is the nested-path walk's question (`resolveNestedPath`),
97
+ * not this lookup's.
98
+ */
99
+ tableAt(path: string): RuntimeTable | undefined;
100
+ /**
101
+ * Take the global hooks — the ones that run for every table this driver
102
+ * serves, before each table's own (`initializeRebaseBackend({ hooks })`,
103
+ * `openRebase({ hooks })`). Replaces any set before; `undefined` clears.
104
+ */
105
+ setGlobalHooks(hooks: TableHooks | undefined): void;
106
+ /** The global hooks, when any were set. */
107
+ globalHooks(): TableHooks | undefined;
108
+ /**
109
+ * Replace one table's own hooks after boot (`backend.setTableHooks`).
110
+ * Assignment, not a merge: the hooks the table was compiled with stop
111
+ * running. The descriptor and the column transforms stay as compiled.
112
+ *
113
+ * @returns whether this driver serves the table.
114
+ */
115
+ setTableHooks(slug: string, hooks: TableHooks): boolean;
116
+ /**
117
+ * Every runtime table, in registration order. The same array until a
118
+ * table is registered or replaced, so a caller may cache on its identity.
119
+ */
120
+ tables(): readonly RuntimeTable[];
121
+ /**
122
+ * Serve what `next` holds from now on: its runtime tables, drizzle tables,
123
+ * enums and relations replace this registry's, in one synchronous step —
124
+ * every holder of this registry (the driver, its services, the realtime
125
+ * service, the server's hook wiring) sees the tables before the call or
126
+ * those after it, never a mixture. The global hooks stay: they belong to
127
+ * the backend, not to a schema. `next` is built off to the side (by
128
+ * `buildTableRegistry`, which checks its relations) and not used after.
129
+ *
130
+ * What a live schema apply calls once the driver has read the edited
131
+ * tables back from its catalogue (`refreshTables` on the driver).
132
+ */
133
+ replaceWith(next: PostgresTableRegistry): void;
134
+ /**
135
+ * Register a drizzle table read back from the catalogue, under its SQL
136
+ * name. The runtime table of that name, when there is one, is rebuilt over
137
+ * it.
138
+ */
139
+ registerPgTable(table: PgTable, tableName: string): void;
140
+ /** The drizzle table with this SQL name — a served table or a junction — or `undefined`. */
141
+ getPgTable(tableName: string): PgTable | undefined;
142
+ /** Whether a drizzle table with this SQL name is registered. */
143
+ hasPgTable(tableName: string): boolean;
144
+ /** The SQL names of every registered drizzle table. */
145
+ getPgTableNames(): string[];
146
+ /** Every registered drizzle table, by SQL name. */
147
+ getAllPgTables(): Record<string, PgTable>;
148
+ registerEnums(enums: Record<string, PgEnum<[string, ...string[]]>>): void;
149
+ registerRelations(relations: Record<string, Relations>): void;
150
+ getEnum(name: string): PgEnum<[string, ...string[]]> | undefined;
151
+ getRelation(name: string): Relations | undefined;
152
+ getAllEnums(): Record<string, PgEnum<[string, ...string[]]>>;
153
+ getAllRelations(): Record<string, Relations>;
154
+ /**
155
+ * Get the merged schema object (tables + relations) for use with Drizzle's
156
+ * relational query API (`db.query`).
157
+ */
158
+ getMergedSchema(): Record<string, unknown>;
159
+ }
@@ -0,0 +1,25 @@
1
+ import { Relations } from "drizzle-orm";
2
+ import { PgEnum } from "drizzle-orm/pg-core";
3
+ import type { CompiledTable } from "@rebasepro/types";
4
+ import { PostgresTableRegistry } from "./PostgresTableRegistry.js";
5
+ /**
6
+ * Everything a registry is built from: the compiled tables and the drizzle
7
+ * schema read back from this database. In BaaS mode both are introspected
8
+ * from the live database.
9
+ */
10
+ export interface RegistrySchema {
11
+ /** The compiled tables, one per served table. */
12
+ compiledTables?: readonly CompiledTable[];
13
+ /** The drizzle tables read back from the catalogue, served tables and junctions alike. */
14
+ tables?: Record<string, unknown>;
15
+ enums?: Record<string, PgEnum<[string, ...string[]]>>;
16
+ relations?: Record<string, Relations>;
17
+ }
18
+ /**
19
+ * Build the table registry for a driver.
20
+ *
21
+ * Order matters: the catalogue tables are registered before the relation
22
+ * check, which reads them, and the compiled tables before them so each
23
+ * runtime table is built over its catalogue table.
24
+ */
25
+ export declare function buildTableRegistry(schema: RegistrySchema): PostgresTableRegistry;
@@ -0,0 +1,24 @@
1
+ import { type TablesRelationalConfig } from "drizzle-orm";
2
+ import { PgDatabase, type PgQueryResultHKT } from "drizzle-orm/pg-core";
3
+ /**
4
+ * Give a drizzle database handle another relational schema (tables and
5
+ * relations), in place.
6
+ *
7
+ * The handle is held by every service of a driver — the fetch, persist and
8
+ * relation services, the realtime service, every request-scoped driver — so a
9
+ * live schema apply cannot hand them a new one. Drizzle builds its relational
10
+ * config once, in the handle's constructor, into three objects the handle,
11
+ * its session (and so every transaction it opens) and each `db.query.<table>`
12
+ * builder share: the table configs, the full schema and the table-name map.
13
+ * Those objects are refilled here, and the `db.query` builders rebuilt over
14
+ * them, synchronously: a request sees the schema before the call or the one
15
+ * after it, never a mixture.
16
+ *
17
+ * The builders' dialect is a fresh `PgDialect`, which is what
18
+ * `drizzle(client, { schema })` builds for a handle opened without a `casing`
19
+ * option (every driver handle is).
20
+ *
21
+ * @param db The handle, opened with a relational schema (`drizzle(client, { schema })`).
22
+ * @param schema The drizzle tables and relations to serve from now on.
23
+ */
24
+ export declare function refreshRelationalSchema(db: PgDatabase<PgQueryResultHKT, Record<string, unknown>, TablesRelationalConfig>, schema: Record<string, unknown>): void;
@@ -0,0 +1,53 @@
1
+ import type { PgTable } from "drizzle-orm/pg-core";
2
+ import type { ColumnDescriptor, CompiledTable, RelationDescriptor, TableDescriptor } from "@rebasepro/types";
3
+ import { type TableKeyColumn } from "@rebasepro/common";
4
+ /**
5
+ * One table as this driver runs it: the compiled table the server handed over
6
+ * (`CompiledTable` — descriptor, hooks, field-level hooks, definition), the
7
+ * drizzle table read back from this database's catalogue, and the lookups
8
+ * every request makes, built once.
9
+ *
10
+ * Two sources, each the truth for its own facts:
11
+ *
12
+ * - the **descriptor** says what the table *is*: which columns it has and
13
+ * under which keys, which of them form the key, what each stamps, who may
14
+ * read it, which relations it has (each naming its target by slug);
15
+ * - the **catalogue table** (`pg`) is what Postgres holds right now, and what
16
+ * every statement is built on — the SQL truth. It is `undefined` when this
17
+ * database holds no such table: a table routed to another data source, or
18
+ * one the schema has not been applied for yet.
19
+ *
20
+ * Built by the registry (`PostgresTableRegistry.registerTables`), never by
21
+ * hand, and replaced — not mutated — when the catalogue table is registered
22
+ * after it.
23
+ */
24
+ export interface RuntimeTable {
25
+ /** What the server compiled. */
26
+ readonly compiled: CompiledTable;
27
+ /** `compiled.descriptor`, for the overwhelmingly common read. */
28
+ readonly descriptor: TableDescriptor;
29
+ /** The table's slug: what the registry, the routes and scopes name it by. */
30
+ readonly slug: string;
31
+ /** The drizzle table read back from this database's catalogue, when it holds the table. */
32
+ readonly pg: PgTable | undefined;
33
+ /** Every column by key. */
34
+ readonly columnsByKey: ReadonlyMap<string, ColumnDescriptor>;
35
+ /** Every column by SQL name. */
36
+ readonly columnsBySqlName: ReadonlyMap<string, ColumnDescriptor>;
37
+ /**
38
+ * Every relation by name. A relation's `target` is the target table's
39
+ * slug: look it up in the registry (`requireTable(relation.target)`).
40
+ */
41
+ readonly relations: ReadonlyMap<string, RelationDescriptor>;
42
+ /** The primary-key columns, in key order (`keyColumns`). Empty only for an introspected keyless table. */
43
+ readonly keys: readonly TableKeyColumn[];
44
+ }
45
+ /**
46
+ * The runtime record of one compiled table over its catalogue table.
47
+ *
48
+ * @param pg The drizzle table this database's catalogue holds for it, or
49
+ * `undefined` when it holds none.
50
+ */
51
+ export declare function buildRuntimeTable(compiled: CompiledTable, pg: PgTable | undefined): RuntimeTable;
52
+ /** The same runtime record over another catalogue table. */
53
+ export declare function withCatalogueTable(table: RuntimeTable, pg: PgTable | undefined): RuntimeTable;
@@ -1,20 +1,20 @@
1
- import { CollectionConfig, ResolvedRelation } from "@rebasepro/types";
2
- import { PostgresCollectionRegistry } from "./PostgresCollectionRegistry.js";
1
+ import type { RelationDescriptor } from "@rebasepro/types";
2
+ import type { PostgresTableRegistry } from "./PostgresTableRegistry.js";
3
3
  /**
4
4
  * Check every relation against the schema it actually runs on, at boot.
5
5
  *
6
- * "Actually runs on" is now literal: the registry's tables are read back from
7
- * `information_schema` (see `catalogue-schema.ts`), so this compares the
8
- * collections against the database. It used to compare them against the
6
+ * "Actually runs on" is literal: the registry's catalogue tables are read back
7
+ * from `information_schema` (see `catalogue-schema.ts`), so this compares each
8
+ * table's relation descriptors against the database. It used to compare them against the
9
9
  * committed `schema.generated.ts`, which made a *stale file* able to refuse a
10
10
  * boot — the exact incident class from 0.13, where boot-ensure had already
11
11
  * renamed the column and the file had not caught up.
12
12
  *
13
13
  * The tagged union made the *shape* of a relation impossible to get wrong: a
14
- * `manyToMany` cannot carry a `foreignKeyOnTarget`, a to-many cannot carry a
14
+ * `manyToMany` cannot carry a `foreignKey`, a to-many cannot carry a
15
15
  * `localKey`. What it cannot know is whether any of the names are real —
16
16
  * whether `posts_tags` is a table, whether `author_id` is a column, whether a
17
- * `joinPath` connects the tables it claims to. Those are facts about the
17
+ * `via` relation's steps connect the tables it claims to. Those are facts about the
18
18
  * database, and the type system never sees them.
19
19
  *
20
20
  * Until now nothing checked them until a query ran, and the failures were the
@@ -30,10 +30,10 @@ import { PostgresCollectionRegistry } from "./PostgresCollectionRegistry.js";
30
30
  * unrelated.
31
31
  */
32
32
  export interface RelationDefect {
33
- /** Slug of the collection declaring the relation. */
34
- collection: string;
33
+ /** Slug of the table declaring the relation. */
34
+ table: string;
35
35
  relationName: string;
36
- kind: ResolvedRelation["kind"];
36
+ kind: RelationDescriptor["kind"];
37
37
  /** What is wrong, in terms of the schema. */
38
38
  problem: string;
39
39
  /** The edit that fixes it. */
@@ -42,17 +42,11 @@ export interface RelationDefect {
42
42
  /**
43
43
  * Relations whose names do not resolve against the registered schema.
44
44
  *
45
- * Fails open wherever it cannot see enough to be sure — an unregistered source
46
- * table, a target belonging to another backend — because a false alarm here
47
- * costs more than a missed one: it would block boot on a working app.
45
+ * Fails open wherever it cannot see enough to be sure — a table this database
46
+ * does not hold, a target this driver does not serve — because a false alarm
47
+ * here costs more than a missed one: it would block boot on a working app.
48
48
  */
49
- export declare function findRelationDefects(collections: CollectionConfig[], registry: PostgresCollectionRegistry,
50
- /**
51
- * The collections the backend was given, when the registry also holds
52
- * ones it reached only as a relation's target. A target outside them has
53
- * no table built for it, and the fix is the array, not the database.
54
- */
55
- given?: readonly CollectionConfig[]): RelationDefect[];
49
+ export declare function findRelationDefects(registry: PostgresTableRegistry): RelationDefect[];
56
50
  /**
57
51
  * Fail boot on any relation that cannot resolve, listing all of them at once.
58
52
  *
@@ -63,4 +57,4 @@ given?: readonly CollectionConfig[]): RelationDefect[];
63
57
  * "nothing" is the kind of bug found in production, weeks later, by a user
64
58
  * asking where their data went.
65
59
  */
66
- export declare function assertRelationsResolve(collections: CollectionConfig[], registry: PostgresCollectionRegistry, given?: readonly CollectionConfig[]): void;
60
+ export declare function assertRelationsResolve(registry: PostgresTableRegistry): void;