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

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,8 +1,8 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
- import { _ as sortIndexSpecs } from "./source-fZb92pN8.js";
4
- import { n as planSchema } from "./plan-schema-vJd3UEmT.js";
5
- import { E as readIndexShapes, T as planIndexAdoptions } from "./migrate-baseline-CmWXL7qx.js";
3
+ import { m as sortIndexSpecs } from "./source-VxbrQojV.js";
4
+ import { n as planSchema } from "./plan-schema-Hbtjhge3.js";
5
+ import { E as readIndexShapes, T as planIndexAdoptions } from "./migrate-baseline-DZmekgpD.js";
6
6
  import { declaredDatabaseExtensions } from "@rebasepro/types";
7
7
  //#region src/schema/push-index-adoption.ts
8
8
  /**
@@ -11,12 +11,12 @@ import { declaredDatabaseExtensions } from "@rebasepro/types";
11
11
  * one's name, so the plan finds it there instead of creating a twin beside it.
12
12
  * Boot does the same through its own plan (`diffPlanAgainstCatalogue`).
13
13
  */
14
- /** The renames that make the database's identical indexes the collections' declared ones. */
15
- async function pushIndexAdoptions(client, collections) {
16
- const schema = planSchema(collections, { databaseExtensions: declaredDatabaseExtensions() });
14
+ /** The renames that make the database's identical indexes the tables' declared ones. */
15
+ async function pushIndexAdoptions(client, tables) {
16
+ const schema = planSchema(tables, { databaseExtensions: declaredDatabaseExtensions() });
17
17
  return planIndexAdoptions(sortIndexSpecs(schema.tables.flatMap((table) => table.indexes)), await readIndexShapes(client, Array.from(new Set(schema.tables.map((table) => table.schema)))));
18
18
  }
19
19
  //#endregion
20
20
  export { pushIndexAdoptions };
21
21
 
22
- //# sourceMappingURL=push-index-adoption-Cp7oZxSl.js.map
22
+ //# sourceMappingURL=push-index-adoption-hpHTyXMR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"push-index-adoption-hpHTyXMR.js","names":[],"sources":["../src/schema/push-index-adoption.ts"],"sourcesContent":["/**\n * `db push`'s half of index adoption (`index-adoption.ts`): before Atlas\n * plans, an existing index identical to a declared one takes the declared\n * one's name, so the plan finds it there instead of creating a twin beside it.\n * Boot does the same through its own plan (`diffPlanAgainstCatalogue`).\n */\nimport { declaredDatabaseExtensions, type CompiledTable } from \"@rebasepro/types\";\nimport { planSchema } from \"./plan/plan-schema\";\nimport { sortIndexSpecs } from \"./table-index\";\nimport { planIndexAdoptions, readIndexShapes, type IndexAdoption, type ShapeQueryable } from \"./index-adoption\";\n\n/** The renames that make the database's identical indexes the tables' declared ones. */\nexport async function pushIndexAdoptions(client: ShapeQueryable, tables: readonly CompiledTable[]): Promise<IndexAdoption[]> {\n const schema = planSchema(tables, { databaseExtensions: declaredDatabaseExtensions() });\n const specs = sortIndexSpecs(schema.tables.flatMap(table => table.indexes));\n const shapes = await readIndexShapes(client, Array.from(new Set(schema.tables.map(table => table.schema))));\n return planIndexAdoptions(specs, shapes);\n}\n"],"mappings":";;;;;;;;;;;;;;AAYA,eAAsB,mBAAmB,QAAwB,QAA4D;CACzH,MAAM,SAAS,WAAW,QAAQ,EAAE,oBAAoB,2BAA2B,EAAE,CAAC;CAGtF,OAAO,mBAFO,eAAe,OAAO,OAAO,SAAQ,UAAS,MAAM,OAAO,CAE/C,GAAO,MADZ,gBAAgB,QAAQ,MAAM,KAAK,IAAI,IAAI,OAAO,OAAO,KAAI,UAAS,MAAM,MAAM,CAAC,CAAC,CAAC,CACnE;AAC3C"}
@@ -1,8 +1,8 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
- import { n as planSchema } from "./plan-schema-vJd3UEmT.js";
4
- import { s as diffPlanAgainstCatalogue } from "./deferred-index-build-BCU9RoHK.js";
5
- import { i as readExistingSchema } from "./ensure-collection-tables-DCJINkT_.js";
3
+ import { n as planSchema } from "./plan-schema-Hbtjhge3.js";
4
+ import { s as diffPlanAgainstCatalogue } from "./deferred-index-build-CcSDA7wE.js";
5
+ import { i as readExistingSchema } from "./ensure-tables-Bvm-F2wW.js";
6
6
  import { declaredDatabaseExtensions } from "@rebasepro/types";
7
7
  //#region src/schema/push-index-prebuild.ts
8
8
  /**
@@ -26,8 +26,8 @@ import { declaredDatabaseExtensions } from "@rebasepro/types";
26
26
  * created by Atlas, and its index with it, on a column that holds no values.
27
27
  */
28
28
  /** The derived foreign-key indexes a live table lacks (or holds INVALID) whose columns it already has. */
29
- async function missingForeignKeyIndexes(client, collections) {
30
- const schema = planSchema(collections, { databaseExtensions: declaredDatabaseExtensions() });
29
+ async function missingForeignKeyIndexes(client, tables) {
30
+ const schema = planSchema(tables, { databaseExtensions: declaredDatabaseExtensions() });
31
31
  const existing = await readExistingSchema(client, Array.from(new Set(schema.tables.map((table) => table.schema))), { probeTables: () => [] });
32
32
  const plan = diffPlanAgainstCatalogue(schema, existing);
33
33
  const specs = new Map(schema.tables.flatMap((table) => table.indexes).map((spec) => [`${spec.schema}.${spec.indexName}`, spec]));
@@ -42,4 +42,4 @@ async function missingForeignKeyIndexes(client, collections) {
42
42
  //#endregion
43
43
  export { missingForeignKeyIndexes };
44
44
 
45
- //# sourceMappingURL=push-index-prebuild-DbwKGtQT.js.map
45
+ //# sourceMappingURL=push-index-prebuild-Bty9F7bD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"push-index-prebuild-Bty9F7bD.js","names":[],"sources":["../src/schema/push-index-prebuild.ts"],"sourcesContent":["/**\n * The foreign-key indexes `rebase db push` builds before Atlas plans.\n *\n * Rebase derives a btree for every `belongsTo` key and every junction's target\n * column (15b00afcd). On a table that already exists — every table of a\n * project upgraded across that release — the index is missing, and a push left\n * it to Atlas, which builds it inside the push's one transaction: a plain\n * `CREATE INDEX`, holding writes to the table for the whole build, about 0.4 s\n * at a million rows and 6 s at ten million. Atlas's own concurrent mode would\n * run the entire apply outside a transaction, which the push relies on.\n *\n * So the push builds those first, `CONCURRENTLY`, with the builder the boot\n * uses for the same indexes (`deferred-index-build.ts`: one at a time, a lock\n * budget for getting the table, an INVALID leftover dropped and rebuilt, a\n * claim shared with booting instances). Atlas then finds them and plans\n * nothing for them. One it could not build is still Atlas's, as before.\n *\n * Only an index whose columns are already there: a column this push adds is\n * created by Atlas, and its index with it, on a column that holds no values.\n */\nimport { declaredDatabaseExtensions, type CompiledTable } from \"@rebasepro/types\";\nimport { planSchema } from \"./plan/plan-schema\";\nimport { diffPlanAgainstCatalogue, type DeferredIndexBuild } from \"./plan/diff-plan\";\nimport { readExistingSchema, type Queryable } from \"./ensure-tables\";\n\n/** The derived foreign-key indexes a live table lacks (or holds INVALID) whose columns it already has. */\nexport async function missingForeignKeyIndexes(\n client: Queryable,\n tables: readonly CompiledTable[]\n): Promise<DeferredIndexBuild[]> {\n const schema = planSchema(tables, { databaseExtensions: declaredDatabaseExtensions() });\n const schemas = Array.from(new Set(schema.tables.map(table => table.schema)));\n // No row probes: whether a table holds rows decides only constraints on a\n // column being added, which this does not plan.\n const existing = await readExistingSchema(client, schemas, { probeTables: () => [] });\n const plan = diffPlanAgainstCatalogue(schema, existing);\n\n const specs = new Map(schema.tables.flatMap(table => table.indexes)\n .map(spec => [`${spec.schema}.${spec.indexName}`, spec]));\n return plan.deferredIndexes.filter(build => {\n const spec = specs.get(`${build.schema}.${build.indexName}`);\n if (spec?.derived !== \"foreign-key\") return false;\n const columns = existing.tables.get(`${build.schema}.${build.table}`);\n if (!columns) return false;\n return [...spec.keys.map(key => key.column), ...spec.include].every(column => columns.has(column));\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,eAAsB,yBAClB,QACA,QAC6B;CAC7B,MAAM,SAAS,WAAW,QAAQ,EAAE,oBAAoB,2BAA2B,EAAE,CAAC;CAItF,MAAM,WAAW,MAAM,mBAAmB,QAH1B,MAAM,KAAK,IAAI,IAAI,OAAO,OAAO,KAAI,UAAS,MAAM,MAAM,CAAC,CAGzB,GAAS,EAAE,mBAAmB,CAAC,EAAE,CAAC;CACpF,MAAM,OAAO,yBAAyB,QAAQ,QAAQ;CAEtD,MAAM,QAAQ,IAAI,IAAI,OAAO,OAAO,SAAQ,UAAS,MAAM,OAAO,CAAC,CAC9D,KAAI,SAAQ,CAAC,GAAG,KAAK,OAAO,GAAG,KAAK,aAAa,IAAI,CAAC,CAAC;CAC5D,OAAO,KAAK,gBAAgB,QAAO,UAAS;EACxC,MAAM,OAAO,MAAM,IAAI,GAAG,MAAM,OAAO,GAAG,MAAM,WAAW;EAC3D,IAAI,MAAM,YAAY,eAAe,OAAO;EAC5C,MAAM,UAAU,SAAS,OAAO,IAAI,GAAG,MAAM,OAAO,GAAG,MAAM,OAAO;EACpE,IAAI,CAAC,SAAS,OAAO;EACrB,OAAO,CAAC,GAAG,KAAK,KAAK,KAAI,QAAO,IAAI,MAAM,GAAG,GAAG,KAAK,OAAO,CAAC,CAAC,OAAM,WAAU,QAAQ,IAAI,MAAM,CAAC;CACrG,CAAC;AACL"}
@@ -1,8 +1,8 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
- import { u as resolveColumnName } from "./column-plan-helpers-BeSztMor.js";
4
- import { n as planSchema } from "./plan-schema-vJd3UEmT.js";
3
+ import { n as planSchema } from "./plan-schema-Hbtjhge3.js";
5
4
  import { declaredDatabaseExtensions } from "@rebasepro/types";
5
+ import { databaseOwnsDefault } from "@rebasepro/common";
6
6
  //#region src/schema/push-kept-defaults.ts
7
7
  /**
8
8
  * The DEFAULTs `db push` keeps because a property says the database owns them.
@@ -31,21 +31,19 @@ import { declaredDatabaseExtensions } from "@rebasepro/types";
31
31
  * it is in `schema.sql`; adding it would only change the error.
32
32
  */
33
33
  /**
34
- * Every column declared `databaseDefault: true` that the planner writes no
35
- * DEFAULT for. An id strategy or `autoValue` writes one of its own, and that
36
- * one is the planner's to keep.
34
+ * Every column declared `.dbDefault()` that the planner writes no DEFAULT
35
+ * for. A key strategy or a stamp writes one of its own, and that one is the
36
+ * planner's to keep.
37
37
  */
38
- function databaseOwnedDefaultColumns(collections) {
39
- const declared = collections.filter((collection) => Object.values(collection.properties ?? {}).some((prop) => isDatabaseOwned(prop)));
40
- if (declared.length === 0) return [];
41
- const plan = planSchema(collections, { databaseExtensions: declaredDatabaseExtensions() });
38
+ function databaseOwnedDefaultColumns(tables) {
39
+ const declared = new Map(tables.map((table) => [table.descriptor.slug, table.descriptor.columns.filter(databaseOwnsDefault)]).filter(([, columns]) => columns.length > 0));
40
+ if (declared.size === 0) return [];
41
+ const plan = planSchema(tables, { databaseExtensions: declaredDatabaseExtensions() });
42
42
  const found = [];
43
43
  for (const table of plan.tables) {
44
- const collection = declared.find((each) => each.slug === table.slug);
45
- if (!collection) continue;
46
- for (const [key, prop] of Object.entries(collection.properties ?? {})) {
47
- if (!isDatabaseOwned(prop)) continue;
48
- const name = resolveColumnName(key, prop);
44
+ const owned = table.slug ? declared.get(table.slug) : void 0;
45
+ if (!owned) continue;
46
+ for (const { column: name } of owned) {
49
47
  const column = table.columns.find((each) => each.column === name);
50
48
  if (!column || column.default || column.generated) continue;
51
49
  found.push({
@@ -57,7 +55,6 @@ function databaseOwnedDefaultColumns(collections) {
57
55
  }
58
56
  return found;
59
57
  }
60
- var isDatabaseOwned = (prop) => typeof prop === "object" && prop !== null && prop.databaseDefault === true;
61
58
  /**
62
59
  * Every column DEFAULT outside the system schemas, and whether Atlas can carry
63
60
  * it (see the module comment for the two it cannot).
@@ -134,4 +131,4 @@ ${keptDefaultStatements(kept).join("\n")}\n`;
134
131
  //#endregion
135
132
  export { databaseOwnedDefaultColumns, readKeptDefaults, withKeptDefaults };
136
133
 
137
- //# sourceMappingURL=push-kept-defaults-CLcgsEPt.js.map
134
+ //# sourceMappingURL=push-kept-defaults-Bst4MDup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"push-kept-defaults-Bst4MDup.js","names":[],"sources":["../src/schema/push-kept-defaults.ts"],"sourcesContent":["/**\n * The DEFAULTs `db push` keeps because a property says the database owns them.\n *\n * `databaseDefault: true` declares a DEFAULT somebody else wrote: a DBA's\n * `now()`, a migration's `'X-' || gen_random_uuid()`. The planner writes no\n * DEFAULT for it, since it has no expression to write, so `schema.sql` holds\n * the column without one. Atlas reads that file as the whole desired state and\n * planned `ALTER COLUMN … DROP DEFAULT`. The API kept letting creates through\n * without the field, and the database then refused them on NOT NULL.\n *\n * Atlas has no way to leave one column's DEFAULT alone: `--exclude` names\n * objects, and a DEFAULT is not one. So the desired state is made to agree with\n * the database instead. Before Atlas plans, the live DEFAULT of each such\n * column is read and appended to `schema.sql` as `ALTER TABLE … SET DEFAULT`,\n * and Atlas finds nothing to change.\n *\n * Two kinds are left out, because Atlas already does something else with them:\n *\n * - a DEFAULT reading a sequence (`nextval(…)`). Atlas does not manage\n * sequences and leaves those DEFAULTs alone, and the sequence does not exist\n * in the scratch database Atlas loads `schema.sql` into.\n * - a DEFAULT calling a function or operator the database defines (an\n * extension's `uuid_generate_v4()`, a project's own function). The scratch\n * database has none of them, and Atlas refuses such a column whether or not\n * it is in `schema.sql`; adding it would only change the error.\n */\nimport { declaredDatabaseExtensions, type CompiledTable } from \"@rebasepro/types\";\nimport { databaseOwnsDefault } from \"@rebasepro/common\";\nimport { planSchema } from \"./plan/plan-schema\";\nimport type { Queryable } from \"./ensure-tables\";\n\n/** A column whose DEFAULT the tables leave to the database. */\nexport interface DatabaseOwnedDefaultColumn {\n schema: string;\n table: string;\n column: string;\n}\n\n/** A DEFAULT the database holds for one of those columns, as SQL. */\nexport interface KeptDefault extends DatabaseOwnedDefaultColumn {\n expression: string;\n}\n\n/**\n * Every column declared `.dbDefault()` that the planner writes no DEFAULT\n * for. A key strategy or a stamp writes one of its own, and that one is the\n * planner's to keep.\n */\nexport function databaseOwnedDefaultColumns(tables: readonly CompiledTable[]): DatabaseOwnedDefaultColumn[] {\n const declared = new Map(tables\n .map(table => [table.descriptor.slug, table.descriptor.columns.filter(databaseOwnsDefault)] as const)\n .filter(([, columns]) => columns.length > 0));\n if (declared.size === 0) return [];\n\n const plan = planSchema(tables, { databaseExtensions: declaredDatabaseExtensions() });\n const found: DatabaseOwnedDefaultColumn[] = [];\n for (const table of plan.tables) {\n const owned = table.slug ? declared.get(table.slug) : undefined;\n if (!owned) continue;\n for (const { column: name } of owned) {\n const column = table.columns.find(each => each.column === name);\n if (!column || column.default || column.generated) continue;\n found.push({ schema: table.schema, table: table.table, column: name });\n }\n }\n return found;\n}\n\n/**\n * Every column DEFAULT outside the system schemas, and whether Atlas can carry\n * it (see the module comment for the two it cannot).\n *\n * Rendered with only `pg_catalog` on the search path, so anything outside it\n * comes back schema-qualified and reads the same in whichever database\n * `schema.sql` is loaded into.\n */\nconst LIVE_DEFAULTS_SQL = `\n SELECT n.nspname AS \"schema\",\n c.relname AS \"table\",\n a.attname AS \"column\",\n pg_get_expr(d.adbin, d.adrelid) AS \"expression\",\n EXISTS (\n SELECT 1\n FROM pg_depend dep\n WHERE dep.classid = 'pg_attrdef'::regclass\n AND dep.objid = d.oid\n AND (\n (dep.refclassid = 'pg_class'::regclass\n AND EXISTS (SELECT 1 FROM pg_class s WHERE s.oid = dep.refobjid AND s.relkind = 'S'))\n OR (dep.refclassid IN ('pg_proc'::regclass, 'pg_operator'::regclass)\n AND dep.refobjid >= 16384)\n )\n ) AS \"uncarried\"\n FROM pg_attrdef d\n JOIN pg_attribute a ON a.attrelid = d.adrelid AND a.attnum = d.adnum\n JOIN pg_class c ON c.oid = d.adrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE NOT a.attisdropped\n AND a.attgenerated = ''\n AND n.nspname NOT IN ('pg_catalog', 'information_schema')\n AND n.nspname NOT LIKE 'pg\\\\_%'\n`;\n\ninterface LiveDefaultRow extends KeptDefault {\n uncarried: boolean;\n}\n\n/**\n * The live DEFAULTs of `columns` that the desired state must carry so Atlas\n * plans no `DROP DEFAULT`. A column with no DEFAULT, or one Atlas cannot carry,\n * is not listed.\n *\n * Read in a transaction of its own, so the search path it narrows goes back\n * when it ends.\n */\nexport async function readKeptDefaults(client: Queryable, columns: DatabaseOwnedDefaultColumn[]): Promise<KeptDefault[]> {\n if (columns.length === 0) return [];\n const wanted = new Set(columns.map(keyOf));\n let rows: LiveDefaultRow[];\n await client.query(\"BEGIN READ ONLY\");\n try {\n await client.query(\"SET LOCAL search_path TO pg_catalog\");\n rows = (await client.query<LiveDefaultRow>(LIVE_DEFAULTS_SQL)).rows;\n } finally {\n await client.query(\"ROLLBACK\");\n }\n return rows\n .filter(row => wanted.has(keyOf(row)) && !row.uncarried && row.expression)\n .map(({ schema, table, column, expression }) => ({ schema, table, column, expression }))\n .sort((a, b) => keyOf(a).localeCompare(keyOf(b)));\n}\n\nconst keyOf = (column: DatabaseOwnedDefaultColumn): string => `${column.schema}\\u0000${column.table}\\u0000${column.column}`;\n\nconst ident = (name: string): string => `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n\n/** What is appended to `schema.sql`: one `SET DEFAULT` per kept DEFAULT. */\nexport function keptDefaultStatements(kept: KeptDefault[]): string[] {\n return kept.map(({ schema, table, column, expression }) =>\n `ALTER TABLE ${ident(schema)}.${ident(table)} ALTER COLUMN ${ident(column)} SET DEFAULT ${expression};`);\n}\n\n/** `schema.sql` with the kept DEFAULTs appended, under a comment saying why. */\nexport function withKeptDefaults(desiredSql: string, kept: KeptDefault[]): string {\n if (kept.length === 0) return desiredSql;\n return `${desiredSql.replace(/\\s*$/, \"\\n\")}\\n` +\n \"-- DEFAULTs the database holds for columns declared `databaseDefault: true`,\\n\" +\n \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OAAO,MAAM,UAAU;CACjC;CACA,OAAO,KACF,QAAO,QAAO,OAAO,IAAI,MAAM,GAAG,CAAC,KAAK,CAAC,IAAI,aAAa,IAAI,UAAU,CAAC,CACzE,KAAK,EAAE,QAAQ,OAAO,QAAQ,kBAAkB;EAAE;EAAQ;EAAO;EAAQ;CAAW,EAAE,CAAC,CACvF,MAAM,GAAG,MAAM,MAAM,CAAC,CAAC,CAAC,cAAc,MAAM,CAAC,CAAC,CAAC;AACxD;AAEA,IAAM,SAAS,WAA+C,GAAG,OAAO,OAAO,QAAQ,OAAO,MAAM,QAAQ,OAAO;AAEnH,IAAM,SAAS,SAAyB,IAAI,KAAK,QAAQ,MAAM,MAAM,EAAE;;AAGvE,SAAgB,sBAAsB,MAA+B;CACjE,OAAO,KAAK,KAAK,EAAE,QAAQ,OAAO,QAAQ,iBACtC,eAAe,MAAM,MAAM,EAAE,GAAG,MAAM,KAAK,EAAE,gBAAgB,MAAM,MAAM,EAAE,eAAe,WAAW,EAAE;AAC/G;;AAGA,SAAgB,iBAAiB,YAAoB,MAA6B;CAC9E,IAAI,KAAK,WAAW,GAAG,OAAO;CAC9B,OAAO,GAAG,WAAW,QAAQ,QAAQ,IAAI,EAAE;;EAGpC,sBAAsB,IAAI,CAAC,CAAC,KAAK,IAAI,EAAE;AAClD"}
@@ -1,8 +1,8 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
- import { n as planSchema } from "./plan-schema-vJd3UEmT.js";
4
- import { s as diffPlanAgainstCatalogue } from "./deferred-index-build-BCU9RoHK.js";
5
- import { i as readExistingSchema } from "./ensure-collection-tables-DCJINkT_.js";
3
+ import { n as planSchema } from "./plan-schema-Hbtjhge3.js";
4
+ import { s as diffPlanAgainstCatalogue } from "./deferred-index-build-CcSDA7wE.js";
5
+ import { i as readExistingSchema } from "./ensure-tables-Bvm-F2wW.js";
6
6
  import { declaredDatabaseExtensions } from "@rebasepro/types";
7
7
  //#region src/schema/push-legacy-renames.ts
8
8
  /**
@@ -17,8 +17,8 @@ import { declaredDatabaseExtensions } from "@rebasepro/types";
17
17
  * could not upgrade an aged database at all. Renaming first — the same
18
18
  * metadata-only statement boot runs — leaves Atlas nothing to plan.
19
19
  */
20
- async function legacyForeignKeyRenames(client, collections) {
21
- const schema = planSchema(collections, { databaseExtensions: declaredDatabaseExtensions() });
20
+ async function legacyForeignKeyRenames(client, tables) {
21
+ const schema = planSchema(tables, { databaseExtensions: declaredDatabaseExtensions() });
22
22
  const plan = diffPlanAgainstCatalogue(schema, await readExistingSchema(client, Array.from(new Set(schema.tables.map((table) => table.schema))), { probeTables: () => [] }));
23
23
  return plan.legacyForeignKeys.map((legacy) => {
24
24
  const action = plan.actions.find((a) => a.kind === "rename-column" && a.target === `${legacy.table}.${legacy.expected}`);
@@ -31,4 +31,4 @@ async function legacyForeignKeyRenames(client, collections) {
31
31
  //#endregion
32
32
  export { legacyForeignKeyRenames };
33
33
 
34
- //# sourceMappingURL=push-legacy-renames-BthD0E9W.js.map
34
+ //# sourceMappingURL=push-legacy-renames-bB4bM6br.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"push-legacy-renames-bB4bM6br.js","names":[],"sources":["../src/schema/push-legacy-renames.ts"],"sourcesContent":["/**\n * The relation columns an aged database still holds under the name Rebase\n * derived before 0.13 (`categorie_id`, `people_id`), for `db push` to rename\n * before Atlas plans.\n *\n * Boot renames them losslessly (`diff-plan.ts`, `renameLegacyColumn`). Push\n * runs Atlas, which sees only \"drop `categorie_id`, add `category_id` NOT\n * NULL\": it listed the links as destructive changes to approve, and with\n * `--allow-destructive` dropped them. A pipeline that runs only `db push`\n * could not upgrade an aged database at all. Renaming first — the same\n * metadata-only statement boot runs — leaves Atlas nothing to plan.\n */\nimport { declaredDatabaseExtensions, type CompiledTable } from \"@rebasepro/types\";\nimport { planSchema } from \"./plan/plan-schema\";\nimport { diffPlanAgainstCatalogue, type LegacyForeignKey } from \"./plan/diff-plan\";\nimport { readExistingSchema, type Queryable } from \"./ensure-tables\";\n\nexport interface LegacyRename extends LegacyForeignKey {\n /** `ALTER TABLE … RENAME COLUMN …;` */\n sql: string;\n}\n\nexport async function legacyForeignKeyRenames(client: Queryable, tables: readonly CompiledTable[]): Promise<LegacyRename[]> {\n const schema = planSchema(tables, { databaseExtensions: declaredDatabaseExtensions() });\n const schemas = Array.from(new Set(schema.tables.map(table => table.schema)));\n const existing = await readExistingSchema(client, schemas, { probeTables: () => [] });\n const plan = diffPlanAgainstCatalogue(schema, existing);\n return plan.legacyForeignKeys.map(legacy => {\n const action = plan.actions.find(a => a.kind === \"rename-column\" && a.target === `${legacy.table}.${legacy.expected}`);\n return { ...legacy, sql: action?.sql ?? \"\" };\n }).filter(rename => rename.sql !== \"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsBA,eAAsB,wBAAwB,QAAmB,QAA2D;CACxH,MAAM,SAAS,WAAW,QAAQ,EAAE,oBAAoB,2BAA2B,EAAE,CAAC;CAGtF,MAAM,OAAO,yBAAyB,QAAQ,MADvB,mBAAmB,QAD1B,MAAM,KAAK,IAAI,IAAI,OAAO,OAAO,KAAI,UAAS,MAAM,MAAM,CAAC,CACzB,GAAS,EAAE,mBAAmB,CAAC,EAAE,CAAC,CAC9B;CACtD,OAAO,KAAK,kBAAkB,KAAI,WAAU;EACxC,MAAM,SAAS,KAAK,QAAQ,MAAK,MAAK,EAAE,SAAS,mBAAmB,EAAE,WAAW,GAAG,OAAO,MAAM,GAAG,OAAO,UAAU;EACrH,OAAO;GAAE,GAAG;GAAQ,KAAK,QAAQ,OAAO;EAAG;CAC/C,CAAC,CAAC,CAAC,QAAO,WAAU,OAAO,QAAQ,EAAE;AACzC"}
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
- import { c as resolveAdminPolicies, n as expectedPolicies, o as partitionOrphans, t as checkPolicyDrift } from "./policy-drift-C-m0uWHH.js";
4
- import { probeRenderedPolicies, readPolicyStamps, tablesRlsWouldEnable } from "./ensure-collection-policies-Bo-_fDAy.js";
3
+ import { c as resolveAdminPolicies, n as expectedPolicies, o as partitionOrphans, t as checkPolicyDrift } from "./policy-drift-BVMyqHSa.js";
4
+ import { probeRenderedPolicies, readPolicyStamps, tablesRlsWouldEnable } from "./ensure-policies-rRmXb5bt.js";
5
5
  //#region src/schema/push-policy-plan.ts
6
6
  var keyOf = (p) => `${p.schema}.${p.table}.${p.name}`;
7
7
  /** What a stamp that no longer matches says. */
@@ -18,19 +18,19 @@ var UNSTAMPED_DIFFERS = "it carries no stamp of Rebase's, and its rule defines i
18
18
  * policies (`TO rebase_admin`, or `TO public` where the admin switch is
19
19
  * not live); `"detect"` reads it off the database. Left out, as compiled.
20
20
  */
21
- async function planPolicyPush(client, collections, options = {}) {
21
+ async function planPolicyPush(client, compiledTables, options = {}) {
22
22
  const adminRoleAvailable = await resolveAdminPolicies(client, options.adminRoleAvailable);
23
- const drift = await checkPolicyDrift(client, collections, { adminRoleAvailable });
24
- const { dropped, kept } = partitionOrphans(drift, collections);
25
- const enableRls = await tablesRlsWouldEnable(client, collections);
26
- const stamps = await underSearchPath(client, options.searchPath, () => readPolicyStamps(client, collections, { adminRoleAvailable }));
23
+ const drift = await checkPolicyDrift(client, compiledTables, { adminRoleAvailable });
24
+ const { dropped, kept } = partitionOrphans(drift, compiledTables);
25
+ const enableRls = await tablesRlsWouldEnable(client, compiledTables);
26
+ const stamps = await underSearchPath(client, options.searchPath, () => readPolicyStamps(client, compiledTables, { adminRoleAvailable }));
27
27
  const replace = drift.diverged.map((d) => ({
28
28
  policy: d.expected,
29
29
  why: d.differences
30
30
  }));
31
31
  const settled = new Set([...drift.missing, ...drift.diverged.map((d) => d.expected)].map(keyOf));
32
32
  const unsure = [];
33
- for (const policy of expectedPolicies(collections, adminRoleAvailable)) {
33
+ for (const policy of expectedPolicies(compiledTables, adminRoleAvailable)) {
34
34
  if (settled.has(keyOf(policy))) continue;
35
35
  const state = stamps.get(`${policy.schema}.${policy.table}`)?.get(policy.name);
36
36
  if (state === "stale" || state === "unstamped") unsure.push({
@@ -38,7 +38,7 @@ async function planPolicyPush(client, collections, options = {}) {
38
38
  state
39
39
  });
40
40
  }
41
- const rendersAsStored = unsure.length === 0 ? /* @__PURE__ */ new Map() : await probeRenderedPolicies(client, collections, unsure.map((entry) => entry.policy), {
41
+ const rendersAsStored = unsure.length === 0 ? /* @__PURE__ */ new Map() : await probeRenderedPolicies(client, compiledTables, unsure.map((entry) => entry.policy), {
42
42
  searchPath: options.searchPath,
43
43
  adminRoleAvailable
44
44
  });
@@ -91,7 +91,7 @@ function formatPolicyPushPlan(plan) {
91
91
  for (const p of plan.unstamped) notes.push(` ${describe(p)}`);
92
92
  }
93
93
  if (plan.keep.length > 0) {
94
- notes.push(" Policies in the database that no collection describes, which the push leaves in force:");
94
+ notes.push(" Policies in the database that no table describes, which the push leaves in force:");
95
95
  for (const p of plan.keep) notes.push(` ${describe(p)}`);
96
96
  }
97
97
  return {
@@ -130,4 +130,4 @@ async function underSearchPath(client, searchPath, read) {
130
130
  //#endregion
131
131
  export { formatPolicyPushPlan, planPolicyPush, summarizePolicyPushPlan, underSearchPath };
132
132
 
133
- //# sourceMappingURL=push-policy-plan-BgcrroxQ.js.map
133
+ //# sourceMappingURL=push-policy-plan-BI8U4BOD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"push-policy-plan-BI8U4BOD.js","names":[],"sources":["../src/schema/push-policy-plan.ts"],"sourcesContent":["/**\n * What `rebase db push` will do to row-level security, read before it does it.\n *\n * Atlas has no model for a policy: its free tier neither plans nor reads one.\n * So its plan, which was everything `db push --dry-run` showed, never named\n * one. After `schema introspect` on a database whose tables had policies of\n * their own and no admin baseline, the dry run said \"No changes: the database\n * already matches these tables\", and the push then created eight\n * `<table>_default_admin_*` policies that let an admin read and write every\n * row.\n *\n * The plan is the push's own steps, read instead of run:\n *\n * - **RLS switched on:** the tables `lockTables` switches on\n * ({@link tablesRlsWouldEnable}).\n * - **Policies created and replaced:** `policies.sql`, which DROPs and CREATEs\n * every declared policy, against the database as `checkPolicyDrift` reads\n * it: by name, `TO` list, command, mode and which clauses there are. Text\n * is compared through the stamp the push and every boot write\n * ({@link readPolicyStamps}), which is what catches a rule whose SQL changed\n * under the same name. Where the stamp does not match, or there is none (a\n * policy `db migrate` or a hand made), the policy is made again under a probe\n * name and rolled back ({@link probeRenderedPolicies}): one Postgres would\n * store exactly as it is now is no change. Only one that could not be probed\n * is listed as unstamped.\n * - **Policies dropped and kept:** {@link partitionOrphans}, which is how the\n * push's reconcile step decides.\n */\nimport type { CompiledTable } from \"@rebasepro/types\";\nimport {\n checkPolicyDrift,\n expectedPolicies,\n partitionOrphans,\n resolveAdminPolicies,\n type AdminPoliciesExpectation,\n type PolicyRef,\n type Queryable\n} from \"../security/policy-drift\";\nimport { probeRenderedPolicies, readPolicyStamps, tablesRlsWouldEnable } from \"./ensure-policies\";\n\nexport interface PolicyPushPlan {\n /** Declared tables in the database with row-level security off, as `schema.table`: the push switches it on. */\n enableRls: string[];\n /** Declared policies the database does not have: the push creates them. */\n create: PolicyRef[];\n /** Declared policies the database has under the same name, defined otherwise: the push replaces them. */\n replace: { policy: PolicyRef; why: string[] }[];\n /** Policies an earlier push generated from a rule edited since: the push drops them. */\n drop: PolicyRef[];\n /** Policies no table describes, which the push leaves in force. */\n keep: PolicyRef[];\n /** Declared policies the database has with no stamp of Rebase's: re-created from their rules, changed or not. */\n unstamped: PolicyRef[];\n}\n\nconst keyOf = (p: PolicyRef): string => `${p.schema}.${p.table}.${p.name}`;\n\n/** What a stamp that no longer matches says. */\nconst STALE = \"its rule, or the policy itself, has changed since Rebase wrote it\";\n\n/** What a policy with no stamp, whose rule stores something else, says. */\nconst UNSTAMPED_DIFFERS = \"it carries no stamp of Rebase's, and its rule defines it otherwise\";\n\n/**\n * Read the plan.\n *\n * @param options.searchPath the `search_path` the stamps were written under\n * when the connection's own differs — the one `db push` stamps under.\n * See {@link readPolicyStamps}.\n * @param options.adminRoleAvailable where the push writes the server-or-admin\n * policies (`TO rebase_admin`, or `TO public` where the admin switch is\n * not live); `\"detect\"` reads it off the database. Left out, as compiled.\n */\nexport async function planPolicyPush(\n client: Queryable,\n compiledTables: readonly CompiledTable[],\n options: { searchPath?: string; adminRoleAvailable?: AdminPoliciesExpectation } = {}\n): Promise<PolicyPushPlan> {\n const adminRoleAvailable = await resolveAdminPolicies(client, options.adminRoleAvailable);\n const drift = await checkPolicyDrift(client, compiledTables, { adminRoleAvailable });\n const { dropped, kept } = partitionOrphans(drift, compiledTables);\n const enableRls = await tablesRlsWouldEnable(client, compiledTables);\n const stamps = await underSearchPath(client, options.searchPath, () => readPolicyStamps(client, compiledTables, { adminRoleAvailable }));\n\n const replace = drift.diverged.map(d => ({ policy: d.expected, why: d.differences }));\n const settled = new Set([...drift.missing, ...drift.diverged.map(d => d.expected)].map(keyOf));\n const unsure: { policy: PolicyRef; state: \"stale\" | \"unstamped\" }[] = [];\n for (const policy of expectedPolicies(compiledTables, adminRoleAvailable)) {\n if (settled.has(keyOf(policy))) continue;\n const state = stamps.get(`${policy.schema}.${policy.table}`)?.get(policy.name);\n if (state === \"stale\" || state === \"unstamped\") unsure.push({ policy, state });\n }\n // What the stamp cannot say, asked of Postgres: would the push store the\n // definition that is there? A policy it would re-create exactly is no change.\n const rendersAsStored = unsure.length === 0\n ? new Map<string, boolean>()\n : await probeRenderedPolicies(client, compiledTables, unsure.map(entry => entry.policy), { searchPath: options.searchPath, adminRoleAvailable });\n const unstamped: PolicyRef[] = [];\n for (const { policy, state } of unsure) {\n const same = rendersAsStored.get(keyOf(policy));\n if (same === true) continue;\n if (state === \"stale\") replace.push({ policy, why: [STALE] });\n else if (same === false) replace.push({ policy, why: [UNSTAMPED_DIFFERS] });\n else unstamped.push(policy);\n }\n\n return { enableRls, create: drift.missing, replace, drop: dropped, keep: kept, unstamped };\n}\n\n/** Whether the push would change any row-level security. Kept and unstamped policies are not changes. */\nexport function policyPlanChanges(plan: PolicyPushPlan): boolean {\n return plan.enableRls.length + plan.create.length + plan.replace.length + plan.drop.length > 0;\n}\n\nconst describe = (p: PolicyRef): string => `${p.schema}.${p.table} → \"${p.name}\" (${p.command} TO ${p.roles.join(\", \")})`;\n\n/**\n * The plan as `db push --dry-run` prints it: `changes`, what the push does,\n * and `notes`, what it leaves or cannot tell. Both empty when there is\n * nothing to say.\n */\nexport function formatPolicyPushPlan(plan: PolicyPushPlan): { changes: string[]; notes: string[] } {\n const changes: string[] = [];\n if (policyPlanChanges(plan)) {\n changes.push(\" Planned row-level security changes:\");\n for (const table of plan.enableRls) changes.push(` switch RLS on ${table}`);\n for (const p of plan.create) changes.push(` create policy ${describe(p)}`);\n for (const { policy, why } of plan.replace) changes.push(` replace policy ${describe(policy)}: ${why.join(\"; \")}`);\n for (const p of plan.drop) changes.push(` drop policy ${describe(p)}, left by a rule edited since`);\n }\n\n const notes: string[] = [];\n if (plan.unstamped.length > 0) {\n notes.push(` ${plan.unstamped.length} declared ${plan.unstamped.length === 1 ? \"policy carries\" : \"policies carry\"} ` +\n \"no stamp of Rebase's, so the push re-creates each from its rule\");\n notes.push(\" and cannot tell beforehand whether that changes it:\");\n for (const p of plan.unstamped) notes.push(` ${describe(p)}`);\n }\n if (plan.keep.length > 0) {\n notes.push(\" Policies in the database that no table describes, which the push leaves in force:\");\n for (const p of plan.keep) notes.push(` ${describe(p)}`);\n }\n return { changes, notes };\n}\n\n/** One line for the push itself: the counts, or `null` when it changes no row-level security. */\nexport function summarizePolicyPushPlan(plan: PolicyPushPlan): string | null {\n if (!policyPlanChanges(plan)) return null;\n const count = (n: number, one: string, many: string): string => `${n} ${n === 1 ? one : many}`;\n const parts = [\n plan.create.length > 0 ? count(plan.create.length, \"policy to create\", \"policies to create\") : \"\",\n plan.replace.length > 0 ? `${plan.replace.length} to replace` : \"\",\n plan.drop.length > 0 ? `${plan.drop.length} to drop` : \"\",\n plan.enableRls.length > 0 ? `RLS to switch on for ${count(plan.enableRls.length, \"table\", \"tables\")}` : \"\"\n ].filter(Boolean);\n return ` Row-level security: ${parts.join(\", \")}. \\`rebase db push --dry-run\\` lists them.`;\n}\n\n/**\n * Run `read` under `searchPath`, set for one transaction and gone after it, or\n * as the connection is when there is none to set.\n */\nexport async function underSearchPath<T>(client: Queryable, searchPath: string | undefined, read: () => Promise<T>): Promise<T> {\n if (!searchPath) return read();\n await client.query(\"BEGIN\");\n try {\n await client.query(`SET LOCAL search_path TO ${searchPath}`);\n const result = await read();\n await client.query(\"COMMIT\");\n return result;\n } catch (err) {\n await client.query(\"ROLLBACK\").catch(() => undefined);\n throw err;\n }\n}\n"],"mappings":";;;;;AAuDA,IAAM,SAAS,MAAyB,GAAG,EAAE,OAAO,GAAG,EAAE,MAAM,GAAG,EAAE;;AAGpE,IAAM,QAAQ;;AAGd,IAAM,oBAAoB;;;;;;;;;;;AAY1B,eAAsB,eAClB,QACA,gBACA,UAAkF,CAAC,GAC5D;CACvB,MAAM,qBAAqB,MAAM,qBAAqB,QAAQ,QAAQ,kBAAkB;CACxF,MAAM,QAAQ,MAAM,iBAAiB,QAAQ,gBAAgB,EAAE,mBAAmB,CAAC;CACnF,MAAM,EAAE,SAAS,SAAS,iBAAiB,OAAO,cAAc;CAChE,MAAM,YAAY,MAAM,qBAAqB,QAAQ,cAAc;CACnE,MAAM,SAAS,MAAM,gBAAgB,QAAQ,QAAQ,kBAAkB,iBAAiB,QAAQ,gBAAgB,EAAE,mBAAmB,CAAC,CAAC;CAEvI,MAAM,UAAU,MAAM,SAAS,KAAI,OAAM;EAAE,QAAQ,EAAE;EAAU,KAAK,EAAE;CAAY,EAAE;CACpF,MAAM,UAAU,IAAI,IAAI,CAAC,GAAG,MAAM,SAAS,GAAG,MAAM,SAAS,KAAI,MAAK,EAAE,QAAQ,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC;CAC7F,MAAM,SAAgE,CAAC;CACvE,KAAK,MAAM,UAAU,iBAAiB,gBAAgB,kBAAkB,GAAG;EACvE,IA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,CAAA,CAAM,KAAK,IAAI,EAAE;AACrD;;;;;AAMA,eAAsB,gBAAmB,QAAmB,YAAgC,MAAoC;CAC5H,IAAI,CAAC,YAAY,OAAO,KAAK;CAC7B,MAAM,OAAO,MAAM,OAAO;CAC1B,IAAI;EACA,MAAM,OAAO,MAAM,4BAA4B,YAAY;EAC3D,MAAM,SAAS,MAAM,KAAK;EAC1B,MAAM,OAAO,MAAM,QAAQ;EAC3B,OAAO;CACX,SAAS,KAAK;EACV,MAAM,OAAO,MAAM,UAAU,CAAC,CAAC,YAAY,KAAA,CAAS;EACpD,MAAM;CACV;AACJ"}
@@ -1,11 +1,11 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
- import { c as searchColumnDefinition, f as searchExtensionStatements, g as searchStampGuards, h as searchIndexStatements, m as searchIndexNames, o as fuzzyColumnDefinition, p as searchHelperFunctions, u as searchColumnStamps } from "./search-column-BM-GV6vH.js";
3
+ import { a as fuzzyColumnDefinition, c as searchColumnStamps, d as searchHelperFunctions, f as searchIndexNames, m as searchStampGuards, p as searchIndexStatements, s as searchColumnDefinition, u as searchExtensionStatements } from "./search-column-BO-WND-B.js";
4
4
  import { n as VIEW_ROWS_COMMENT_PREFIX, r as viewRowsName } from "./view-names-Dscp6--B.js";
5
5
  import { t as ADMIN_POLICY_ROLE_SQL } from "./rls-bootstrap-sql-kPX4-MB1.js";
6
- import { a as vectorDimensionGuard, c as vectorExtensionStatement, d as vectorIndexStatements, i as vectorColumnDefinition, l as vectorIndexNames, o as vectorExtensionDeclared, t as VECTOR_EXTENSION_OPT_IN } from "./vector-index-DsQ3V2d2.js";
7
- import { o as atlasExcludePattern, u as collectionIndexStatements } from "./source-fZb92pN8.js";
8
- import { a as triggerStatements, r as quoteSqlLiteral } from "./plan-schema-vJd3UEmT.js";
6
+ import { a as vectorDimensionGuard, c as vectorExtensionStatement, d as vectorIndexStatements, i as vectorColumnDefinition, l as vectorIndexNames, o as vectorExtensionDeclared, t as VECTOR_EXTENSION_OPT_IN } from "./vector-index-VSh3ufTd.js";
7
+ import { g as tableIndexStatements, o as atlasExcludePattern } from "./source-VxbrQojV.js";
8
+ import { o as triggerStatements, r as quoteSqlLiteral } from "./plan-schema-Hbtjhge3.js";
9
9
  import { REBASE_ADMIN_REQUEST_ROLE, REBASE_ADMIN_ROLE } from "@rebasepro/types";
10
10
  import { REBASE_USER_ROLE } from "@rebasepro/common";
11
11
  import { adminRequestPolicyName } from "@rebasepro/utils";
@@ -68,6 +68,7 @@ var renderPgType = (type) => {
68
68
  case "bytea": return "BYTEA";
69
69
  case "tsvector": return "tsvector";
70
70
  case "array": return `${renderPgType(type.of)}[]`;
71
+ case "custom": return type.sqlType;
71
72
  }
72
73
  };
73
74
  /**
@@ -80,7 +81,13 @@ var renderPgType = (type) => {
80
81
  */
81
82
  var renderColumnDefinition = (column) => {
82
83
  if (column.sqlDefinition) return column.sqlDefinition;
83
- if (column.generated) return `${renderPgType(column.type)} GENERATED ALWAYS AS (${column.generated.expression}) STORED`;
84
+ if (column.generated) {
85
+ let generated = `${renderPgType(column.type)} GENERATED ALWAYS AS (${column.generated.expression}) STORED`;
86
+ if (column.primaryKey) generated += " PRIMARY KEY";
87
+ if (column.unique) generated += " UNIQUE";
88
+ if (!column.nullable && !column.primaryKey) generated += " NOT NULL";
89
+ return generated;
90
+ }
84
91
  let definition = renderPgType(column.type);
85
92
  if (column.default?.kind === "identity") definition += " GENERATED BY DEFAULT AS IDENTITY";
86
93
  if (column.primaryKey) definition += " PRIMARY KEY";
@@ -202,7 +209,7 @@ function renderPostgresDdl(plan, options = {}) {
202
209
  indexStatements.push(...vectorIndexStatements(table.vector));
203
210
  for (const skip of table.vector.skipped) indexStatements.push(`-- No ANN index on "${skip.schema}"."${skip.table}"."${skip.column}": ${skip.reason}`);
204
211
  }
205
- indexStatements.push(...collectionIndexStatements(table.indexes));
212
+ indexStatements.push(...tableIndexStatements(table.indexes));
206
213
  if (includePolicies) {
207
214
  ddl += `${renderEnableRls(table)}\n`;
208
215
  ddl += "\n";
@@ -478,4 +485,4 @@ function renderViewsDdl(plan) {
478
485
  //#endregion
479
486
  export { renderPoliciesDdl as a, renderPrimaryKeyConstraint as c, renderVectorDdl as d, renderViewsDdl as f, vectorExcludePatternsOf as h, renderPgType as i, renderSearchDdl as l, triggerExcludePatternsOf as m, renderDenyingPolicyStatements as n, renderPolicyStatements as o, searchExcludePatternsOf as p, renderEnableRls as r, renderPostgresDdl as s, renderColumnDefinition as t, renderTriggersDdl as u };
480
487
 
481
- //# sourceMappingURL=render-ddl-Ci3S_SoI.js.map
488
+ //# sourceMappingURL=render-ddl-D4n86NHz.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-ddl-D4n86NHz.js","names":[],"sources":["../src/schema/plan/render-ddl.ts"],"sourcesContent":["/**\n * The SQL files, rendered from a {@link SchemaPlan}.\n *\n * Four files, because Atlas owns exactly one of them:\n *\n * - `schema.sql` — the desired state Atlas diffs the database against.\n * - `policies.sql` — the RLS policies. Atlas has no model for a policy.\n * - `search.sql` — the generated `tsvector` column, its GIN index and the\n * IMMUTABLE helpers its expression calls. Atlas's free tier refuses to\n * *parse* a file containing a function, and it wipes the dev database it\n * diffs against, so a helper seeded there is gone by the time the plan runs.\n * - `vector.sql` — the `vector` columns and their ANN indexes. Atlas cannot\n * *execute* these: it materialises `schema.sql` in a dev database that is\n * created empty and emptied again on every run, so `VECTOR(384)` resolves\n * against a database that structurally cannot have pgvector.\n * - `triggers.sql` — `autoValue: \"on_update\"`, which is a function plus a\n * binding, so it is out for the same reason search is.\n *\n * Everything not in `schema.sql` is excluded from Atlas's view by pattern\n * (`…ExcludePatterns` below) and applied by Rebase — at push time by the CLI,\n * at boot by the schema ensure. Without the excludes a desired state that omits\n * an object reads to Atlas as an instruction to drop it.\n */\nimport { REBASE_ADMIN_REQUEST_ROLE, REBASE_ADMIN_ROLE } from \"@rebasepro/types\";\nimport { adminRequestPolicyName } from \"@rebasepro/utils\";\nimport { ADMIN_POLICY_ROLE_SQL } from \"../rls-bootstrap-sql\";\nimport {\n fuzzyColumnDefinition,\n searchColumnDefinition,\n searchColumnStamps,\n searchExtensionStatements,\n searchHelperFunctions,\n searchIndexNames,\n searchIndexStatements,\n searchStampGuards\n} from \"../search-column\";\nimport {\n VECTOR_EXTENSION_OPT_IN,\n vectorColumnDefinition,\n vectorDimensionGuard,\n vectorExtensionDeclared,\n vectorExtensionStatement,\n vectorIndexNames,\n vectorIndexStatements\n} from \"../vector-index\";\nimport { atlasExcludePattern } from \"../atlas-exclude\";\nimport { tableIndexStatements } from \"../table-index\";\nimport { quoteSqlLiteral } from \"./plan-schema\";\nimport { triggerStatements } from \"./updated-at-trigger\";\nimport { VIEW_ROWS_COMMENT_PREFIX, viewRowsName } from \"./view-names\";\nimport { REBASE_USER_ROLE } from \"@rebasepro/common\";\nimport type { ColumnPlan, PgType, PolicyPlan, SchemaPlan, TablePlan, ViewPlan } from \"./types\";\n\n/** What `schema.sql` may leave out, because another file owns it. */\nexport interface DdlRenderOptions {\n /** RLS policies. `false` puts them in `policies.sql` alone. */\n includePolicies?: boolean;\n /** The search column, its helpers and its index. See `search.sql`. */\n includeSearch?: boolean;\n /** The vector columns and their ANN indexes. See `vector.sql`. */\n includeVector?: boolean;\n}\n\n/**\n * A {@link PgType} as Postgres spells it.\n *\n * The one place. `getSqlColumnType` and `getDrizzleColumn` each carried their\n * own ladder and disagreed about `VARCHAR` widths, about `geopoint`, and about\n * whether an `increment` id honours `columnType`.\n */\nexport const renderPgType = (type: PgType): string => {\n switch (type.kind) {\n case \"text\": return \"TEXT\";\n case \"varchar\": return `VARCHAR(${type.length})`;\n case \"char\": return `CHAR(${type.length})`;\n case \"uuid\": return \"UUID\";\n case \"enum\": return `\"${type.schema}\".\"${type.name}\"`;\n case \"smallint\": return \"SMALLINT\";\n case \"integer\": return \"INTEGER\";\n case \"bigint\": return \"BIGINT\";\n case \"smallserial\": return \"SMALLSERIAL\";\n case \"serial\": return \"SERIAL\";\n case \"bigserial\": return \"BIGSERIAL\";\n case \"real\": return \"REAL\";\n case \"doublePrecision\": return \"DOUBLE PRECISION\";\n case \"numeric\":\n if (type.precision === undefined) return \"NUMERIC\";\n return type.scale === undefined\n ? `NUMERIC(${type.precision})`\n : `NUMERIC(${type.precision}, ${type.scale})`;\n case \"boolean\": return \"BOOLEAN\";\n case \"timestamptz\": return \"TIMESTAMP WITH TIME ZONE\";\n case \"date\": return \"DATE\";\n case \"time\": return \"TIME\";\n case \"json\": return \"JSON\";\n case \"jsonb\": return \"JSONB\";\n case \"vector\": return `VECTOR(${type.dimensions})`;\n case \"bytea\": return \"BYTEA\";\n case \"tsvector\": return \"tsvector\";\n case \"array\": return `${renderPgType(type.of)}[]`;\n // Verbatim: `assertCustomSqlType` admitted it as a type name that\n // cannot leave the statement.\n case \"custom\": return type.sqlType;\n }\n};\n\n/**\n * Everything after the column name, in one order for every SQL emitter.\n *\n * `CREATE TABLE` and `ADD COLUMN` used to assemble this separately, which is\n * how a required relation column came out `NOT NULL` after `db push` and\n * nullable after a boot-ensure. `identity` is part of the type rather than a\n * DEFAULT, which is why it is rendered here and not in the DEFAULT slot.\n */\nexport const renderColumnDefinition = (column: ColumnPlan): string => {\n // `auth-users-columns` is the single description of what an auth user\n // table's columns must be, and it hands over a rendered definition.\n if (column.sqlDefinition) return column.sqlDefinition;\n\n // A generated column takes no DEFAULT (Postgres refuses one beside the\n // expression); its key, UNIQUE and NOT NULL follow it as on any column.\n if (column.generated) {\n let generated = `${renderPgType(column.type)} GENERATED ALWAYS AS (${column.generated.expression}) STORED`;\n if (column.primaryKey) generated += \" PRIMARY KEY\";\n if (column.unique) generated += \" UNIQUE\";\n if (!column.nullable && !column.primaryKey) generated += \" NOT NULL\";\n return generated;\n }\n\n let definition = renderPgType(column.type);\n if (column.default?.kind === \"identity\") definition += \" GENERATED BY DEFAULT AS IDENTITY\";\n if (column.primaryKey) definition += \" PRIMARY KEY\";\n if (column.unique) definition += \" UNIQUE\";\n if (column.default && column.default.kind !== \"identity\") {\n definition += ` DEFAULT ${column.default.kind === \"sql\" ? column.default.expression : column.default.sql}`;\n }\n if (!column.nullable && !column.primaryKey) definition += \" NOT NULL\";\n return definition;\n};\n\n/**\n * `PRIMARY KEY (\"a\", \"b\")`, the clause a composite key takes inside a\n * `CREATE TABLE`. Shared by `schema.sql` and boot-ensure's `CREATE TABLE`, so\n * the two cannot list the columns differently.\n */\nexport const renderPrimaryKeyConstraint = (table: Pick<TablePlan, \"primaryKey\">): string =>\n `PRIMARY KEY (${table.primaryKey.map(c => `\"${c}\"`).join(\", \")})`;\n\n/** `\"col\" TYPE …`, as it appears inside a `CREATE TABLE`. */\nconst renderColumn = (column: ColumnPlan): string =>\n `\"${column.column}\" ${renderColumnDefinition(column)}`;\n\n// ── Policies ─────────────────────────────────────────────────────────────────\n\n/**\n * One policy as its `DROP` / `CREATE` pair — each a complete statement.\n *\n * This is the primitive the boot-time RLS applier runs one statement at a time\n * (the runtime's DB handle speaks the extended query protocol, which forbids\n * multiple commands in one execute), while `db push` writes the joined string.\n */\nexport const renderPolicyStatements = (\n table: Pick<TablePlan, \"schema\" | \"table\">,\n policy: PolicyPlan\n): string[] => {\n const target = `\"${table.schema}\".\"${table.table}\"`;\n let create = `CREATE POLICY \"${policy.name}\" ON ${target} AS ${policy.mode.toUpperCase()} ` +\n `FOR ${policy.operation.toUpperCase()} TO ${policy.roles.map(r => `\"${r}\"`).join(\", \")}`;\n if (policy.using) create += ` USING (${policy.using})`;\n if (policy.withCheck) create += ` WITH CHECK (${policy.withCheck})`;\n // The one policy an older naming stored this rule's operations under —\n // see `PolicyPlan.supersedes`. In the same per-table transaction, so a\n // request sees the old policy or the new ones, never neither.\n const superseded = (policy.supersedes ?? []).map(name => `DROP POLICY IF EXISTS \"${name}\" ON ${target};`);\n // The admin-request companion a boot may have written beside this policy\n // (`USING (true)` for every admin) goes with it unless the policy, as\n // written now, still earns one: a rule narrowed to `admin AND owner`, moved\n // TO public, or changed in any way that keeps its name must not leave\n // every admin reading every row. Here rather than in the boot alone, so\n // `db push`, a migration and a boot that provisions nothing all drop it.\n //\n // A policy that does earn one keeps it — unless the one there was written\n // for something else under the same name: a named rule moved from SELECT\n // to DELETE keeps its name, and the SELECT companion would go on admitting\n // every admin to every row nobody may read now. Dropped then, by a check in\n // the statement itself, so the DDL heals whoever runs it.\n const keepsCompanion = policy.adminRequestCompanion !== undefined && policy.roles.includes(REBASE_ADMIN_ROLE);\n const isCompanion = policy.roles.includes(REBASE_ADMIN_REQUEST_ROLE);\n const companionName = adminRequestPolicyName(policy.name);\n const companion = isCompanion\n ? []\n : keepsCompanion\n ? [mismatchedCompanionDropSql(table, companionName, policy.operation)]\n : [`DROP POLICY IF EXISTS \"${companionName}\" ON ${target};`];\n return [...superseded, ...companion, `DROP POLICY IF EXISTS \"${policy.name}\" ON ${target};`, `${create};`];\n};\n\n/**\n * Drop the companion `name` on the table unless it is exactly what a boot\n * writes for a policy of this operation: permissive, `TO rebase_admin_request`\n * alone, `FOR <operation>`, its clauses `true` or absent. One `DO` statement,\n * so it runs on a handle that refuses several commands in one string.\n */\nfunction mismatchedCompanionDropSql(table: Pick<TablePlan, \"schema\" | \"table\">, name: string, operation: string): string {\n const literal = (value: string) => `'${value.replace(/'/g, \"''\")}'`;\n const ident = (value: string) => `\"${value.replace(/\"/g, \"\\\"\\\"\")}\"`;\n // One line, as every policy statement is: the boot sends a table's\n // statements joined by newlines, one per line.\n return `DO $rebase_companion$ BEGIN IF EXISTS (SELECT 1 FROM pg_policies p ` +\n `WHERE p.schemaname = ${literal(table.schema)} AND p.tablename = ${literal(table.table)} AND p.policyname = ${literal(name)} ` +\n `AND NOT (p.cmd = ${literal(operation.toUpperCase())} AND p.permissive = 'PERMISSIVE' ` +\n `AND p.roles = ARRAY[${literal(REBASE_ADMIN_REQUEST_ROLE)}]::name[] ` +\n `AND COALESCE(p.qual, 'true') = 'true' AND COALESCE(p.with_check, 'true') = 'true')) ` +\n `THEN EXECUTE ${literal(`DROP POLICY ${ident(name)} ON ${ident(table.schema)}.${ident(table.table)}`)}; END IF; END $rebase_companion$;`;\n}\n\n/**\n * A restrictive policy, under its own name, command and roles, that passes no\n * row: `USING (false)` / `WITH CHECK (false)` for the clauses its command takes.\n *\n * What the boot applier puts in place of a restrictive policy whose own\n * `CREATE` failed. A restrictive policy is a gate ANDed over every permissive\n * one, so its absence does not deny — it opens whatever the permissive policies\n * grant. Standing in for it with a gate nothing passes keeps the failure on\n * the denying side until the rule can be created.\n */\nexport const renderDenyingPolicyStatements = (\n table: Pick<TablePlan, \"schema\" | \"table\">,\n policy: PolicyPlan\n): string[] => {\n const target = `\"${table.schema}\".\"${table.table}\"`;\n let create = `CREATE POLICY \"${policy.name}\" ON ${target} AS RESTRICTIVE ` +\n `FOR ${policy.operation.toUpperCase()} TO ${policy.roles.map(r => `\"${r}\"`).join(\", \")}`;\n if (policy.operation !== \"insert\") create += \" USING (false)\";\n if (policy.operation !== \"select\" && policy.operation !== \"delete\") create += \" WITH CHECK (false)\";\n return [`DROP POLICY IF EXISTS \"${policy.name}\" ON ${target};`, `${create};`];\n};\n\n/** `ALTER TABLE … ENABLE ROW LEVEL SECURITY;` — every generated table is locked. */\nexport const renderEnableRls = (table: Pick<TablePlan, \"schema\" | \"table\">): string =>\n `ALTER TABLE \"${table.schema}\".\"${table.table}\" ENABLE ROW LEVEL SECURITY;`;\n\nconst statementsToDdl = (statements: string[]): string => statements.map(s => `${s}\\n`).join(\"\");\n\n// ── schema.sql ───────────────────────────────────────────────────────────────\n\nexport function renderPostgresDdl(plan: SchemaPlan, options: DdlRenderOptions = {}): string {\n const includePolicies = options.includePolicies !== false;\n const includeSearch = options.includeSearch !== false;\n const includeVector = options.includeVector !== false;\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\\n\";\n\n // 1. Custom schemas.\n //\n // `rebase` is unconditional and load-bearing. The RLS helper functions live\n // in it, so the migration preamble creates it — which puts it in Atlas's\n // replayed state, and anything in that state but absent from this desired\n // schema gets a `DROP SCHEMA … CASCADE` planned against it. That would take\n // the auth tables.\n plan.schemas.forEach(schema => { ddl += `CREATE SCHEMA IF NOT EXISTS \"${schema}\";\\n`; });\n if (plan.schemas.length > 0) ddl += \"\\n\";\n\n // 1b. Search support, for collections that opted in.\n //\n // Extensions and helper functions come before every CREATE TABLE because a\n // generated column's expression is resolved at creation time: a table whose\n // search column calls `rebase_search_text` cannot be created before that\n // function exists. Both are `IF NOT EXISTS` / `OR REPLACE`, so a file\n // replayed against a live database is a no-op here.\n const searchTables = plan.tables.filter(t => t.search);\n if (searchTables.length > 0) {\n if (!includeSearch) {\n ddl += \"-- Full-text search support lives in `search.sql`, applied separately.\\n\\n\";\n } else {\n const extensions = Array.from(new Set(searchTables.flatMap(t => searchExtensionStatements(t.search!))));\n const helpers = Array.from(new Set(searchTables.flatMap(t => searchHelperFunctions(t.search!))));\n ddl += \"-- Full-text search support (collections declaring a `search` block)\\n\";\n extensions.forEach(s => { ddl += `${s}\\n`; });\n if (extensions.length > 0) ddl += \"\\n\";\n helpers.forEach(s => { ddl += `${s}\\n\\n`; });\n }\n }\n\n // 1c. Vector support. Only ever a note, never a statement — unlike 1b.\n // `CREATE EXTENSION vector` is the one thing this file must never carry\n // whichever way the flag goes: Atlas rejects an extension in a desired\n // state as a paid feature.\n if (!includeVector && plan.tables.some(t => t.vectorColumns.length > 0)) {\n ddl += \"-- Vector columns and their ANN indexes live in `vector.sql`, applied separately.\\n\\n\";\n }\n\n // 1d. `autoValue: \"on_update\"`. A trigger is a function plus a binding, so\n // it is out of Atlas's sight for the reason search is — and out\n // unconditionally, because `schema.sql` has no flag that would make Atlas\n // able to read one.\n if (plan.tables.some(t => t.triggers.length > 0)) {\n ddl += \"-- `autoValue: \\\"on_update\\\"` triggers live in `triggers.sql`, applied separately.\\n\\n\";\n }\n\n // 2. Enum types.\n plan.enums.forEach(enumPlan => {\n ddl += `CREATE TYPE \"${enumPlan.schema}\".\"${enumPlan.name}\" AS ENUM (${enumPlan.labels.map(quoteSqlLiteral).join(\", \")});\\n`;\n });\n if (ddl.endsWith(\";\\n\")) ddl += \"\\n\";\n\n // 3. Tables, in the plan's order — each collection, then any junction its\n // relations imply.\n const fkStatements: string[] = [];\n // Indexes follow the tables for the same reason the FK constraints do: the\n // table has to exist first.\n const indexStatements: string[] = [];\n // Policies are emitted after every CREATE TABLE, like the FK constraints: a\n // policy may reference other tables (a junction's derived policies always\n // reference both endpoints; `policy.existsIn` references a join table), and\n // CREATE POLICY validates those relations at creation time.\n const policyStatements: string[] = [];\n\n for (const table of plan.tables) {\n const emitted = table.columns.filter(column => {\n // A vector column is not Atlas's — `vector.sql` adds it. Filtered\n // here rather than upstream so the column keeps its place in the\n // generator's order when it *is* included, which is what the\n // derived-names contract renders.\n if (!includeVector && column.type.kind === \"vector\") return false;\n if (!includeSearch && column.source.kind === \"search\") return false;\n // A declared property already emits this column (an explicit\n // `postId` beside the `belongsTo` that uses it); the relation\n // contributes only the constraint.\n if (column.columnOwnedByProperty) return false;\n return true;\n });\n\n ddl += `CREATE TABLE \"${table.schema}\".\"${table.table}\" (\\n`;\n const lines = emitted.map(column => ` ${renderColumn(column)}`);\n // A key over several columns — a junction's two endpoints, or a\n // collection with several `isId` properties — is one table constraint;\n // a single-column key is already inline on its column.\n if (table.primaryKey.length > 1) {\n lines.push(` ${renderPrimaryKeyConstraint(table)}`);\n }\n ddl += lines.join(\",\\n\");\n ddl += \"\\n);\\n\\n\";\n\n for (const column of table.columns) {\n if (column.foreignKey) fkStatements.push(`${column.foreignKey.sql};`);\n }\n\n if (includeSearch && table.search) {\n indexStatements.push(...searchIndexStatements(table.search));\n }\n // ANN indexes are emitted with the other indexes rather than inline,\n // because `CREATE INDEX` is a statement and a column definition is not\n // — and because a column too wide for pgvector to index still needs its\n // column. Absent alongside their column when vector is carved out.\n if (includeVector && table.vector) {\n indexStatements.push(...vectorIndexStatements(table.vector));\n for (const skip of table.vector.skipped) {\n indexStatements.push(`-- No ANN index on \"${skip.schema}\".\"${skip.table}\".\"${skip.column}\": ${skip.reason}`);\n }\n }\n // The collection's own `indexes:` block. Last of the three index\n // producers, and the only one the developer wrote deliberately rather\n // than getting as a side effect of another feature.\n indexStatements.push(...tableIndexStatements(table.indexes));\n\n if (includePolicies) {\n // No FORCE: authenticated requests run as the non-owner\n // `rebase_user` role, which plain ENABLE already binds. The owner\n // (server context) must bypass — it is the trusted plane.\n ddl += `${renderEnableRls(table)}\\n`;\n ddl += \"\\n\";\n for (const policy of table.policies) {\n policyStatements.push(statementsToDdl(renderPolicyStatements(table, policy)));\n }\n }\n }\n\n // Indexes before foreign keys. Today every FK targets a primary key created\n // inline, so the order is safe by accident; the moment a declared\n // `unique: true` index can back an FK target, a constraint emitted first\n // would reference an index that does not exist yet.\n if (indexStatements.length > 0) {\n ddl += \"-- Indexes\\n\";\n ddl += indexStatements.join(\"\\n\") + \"\\n\\n\";\n }\n\n if (fkStatements.length > 0) {\n ddl += \"-- Foreign Key Constraints\\n\";\n ddl += fkStatements.join(\"\\n\") + \"\\n\\n\";\n }\n\n if (policyStatements.length > 0) {\n ddl += \"-- Row Level Security Policies\\n\";\n ddl += adminRolePreamble(plan);\n ddl += policyStatements.join(\"\");\n ddl += \"\\n\";\n }\n\n return ddl;\n}\n\n// ── policies.sql ─────────────────────────────────────────────────────────────\n\n/**\n * The statement that creates `rebase_admin`, when a policy in the plan is\n * written `TO` it — so a file of policies is self-contained, as it is for the\n * RLS helpers: CREATE POLICY refuses a role that does not exist. Empty when no\n * policy names it (`rls.adminPolicies: \"public\"`).\n */\nexport function adminRolePreamble(plan: SchemaPlan): string {\n const named = plan.tables.some(table => table.policies.some(policy => policy.roles.includes(REBASE_ADMIN_ROLE)));\n return named ? `${ADMIN_POLICY_ROLE_SQL};\\n\\n` : \"\";\n}\n\nexport function renderPoliciesDdl(plan: SchemaPlan): string {\n let ddl = \"-- This file contains RLS policies generated by Rebase. Applied separately from migrations.\\n\\n\";\n ddl += adminRolePreamble(plan);\n\n // Collections first, then the junctions no collection declares — the order\n // the boot-time applier plans them in.\n for (const table of plan.tables.filter(t => t.kind === \"collection\")) {\n ddl += `${renderEnableRls(table)}\\n`;\n ddl += \"\\n\";\n if (table.policies.length === 0) continue;\n let announced: string | undefined;\n for (const policy of table.policies) {\n // Say which policies the author did not write. They are permissive,\n // so they OR with the declared rules and widen the final ACL beyond\n // what the declared rules read like — and re-appear after any manual\n // DROP, because a push asserts the declared state. Once per *rule*:\n // one rule with four operations is one thing the author did not\n // write, not four.\n if (policy.injected && policy.ruleKey !== announced) {\n ddl += \"-- Injected by Rebase (not from this collection's securityRules).\\n\";\n ddl += `-- Set \\`disableDefaultPolicies: true\\` on \"${table.slug}\" to drop these and own its RLS outright.\\n`;\n }\n announced = policy.ruleKey;\n ddl += statementsToDdl(renderPolicyStatements(table, policy));\n }\n ddl += \"\\n\";\n }\n\n for (const table of plan.tables.filter(t => t.kind === \"junction\")) {\n ddl += `${renderEnableRls(table)}\\n`;\n ddl += \"\\n\";\n if (table.policies.length === 0) continue;\n const declaringSlugs = (table.declaringSlugs ?? []).join('\", \"');\n ddl += `-- Derived by Rebase for the junction \"${table.table}\" (no collection declares it).\\n`;\n ddl += \"-- Reads require both endpoint rows to be visible; writes follow the update\\n\";\n ddl += `-- rules of \"${declaringSlugs}\". Set \\`disableDefaultPolicies: true\\` on the\\n`;\n ddl += \"-- declaring collection(s) to drop these and police the junction yourself.\\n\";\n for (const policy of table.policies) {\n ddl += statementsToDdl(renderPolicyStatements(table, policy));\n }\n ddl += \"\\n\";\n }\n\n return ddl;\n}\n\n// ── search.sql ───────────────────────────────────────────────────────────────\n\nexport function renderSearchDdl(plan: SchemaPlan): string {\n const tables = plan.tables.filter(t => t.search);\n if (tables.length === 0) return \"\";\n\n const extensions = Array.from(new Set(tables.flatMap(t => searchExtensionStatements(t.search!))));\n const helpers = Array.from(new Set(tables.flatMap(t => searchHelperFunctions(t.search!))));\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\";\n ddl += \"--\\n\";\n ddl += \"-- Full-text search for the collections declaring a `search` block.\\n\";\n ddl += \"-- Applied by Rebase, not by Atlas — see generatePostgresSearchDdl.\\n\\n\";\n\n extensions.forEach(s => { ddl += `${s}\\n`; });\n if (extensions.length > 0) ddl += \"\\n\";\n helpers.forEach(s => { ddl += `${s}\\n\\n`; });\n\n for (const table of tables) {\n const spec = table.search!;\n const target = `\"${table.schema}\".\"${table.table}\"`;\n // ADD COLUMN IF NOT EXISTS rather than the inline definition the\n // CREATE TABLE would use: by the time this runs the table exists,\n // whether Atlas just created it or it has been live for a year. The\n // guard first, because `ADD COLUMN IF NOT EXISTS` is a no-op against an\n // existing column — without it the file would report success, leave the\n // old expression in place, and then stamp it as current.\n searchStampGuards(spec).forEach(s => { ddl += `${s}\\n`; });\n ddl += `ALTER TABLE ${target} ADD COLUMN IF NOT EXISTS ${searchColumnDefinition(spec)};\\n`;\n const fuzzy = fuzzyColumnDefinition(spec);\n if (fuzzy) ddl += `ALTER TABLE ${target} ADD COLUMN IF NOT EXISTS ${fuzzy};\\n`;\n searchColumnStamps(spec).forEach(s => { ddl += `${s.sql}\\n`; });\n searchIndexStatements(spec).forEach(s => { ddl += `${s}\\n`; });\n ddl += \"\\n\";\n }\n\n return ddl;\n}\n\n/**\n * Glob patterns telling Atlas to leave an object alone.\n *\n * Fully qualified, `schema.table.object`, matching the include list. The\n * two-part form is what Atlas wants when the connection URL scopes it to one\n * schema and is *silently ignored* otherwise: it reads `posts.search_vector` as\n * a table named `search_vector` in a schema named `posts`, matches nothing, and\n * reports no error for the pattern that never fired. Each name is spelled by\n * `atlasExcludePattern`, so one holding a `.` or glob syntax still matches.\n */\nexport const searchExcludePatternsOf = (plan: SchemaPlan): string[] => {\n const patterns: string[] = [];\n for (const table of plan.tables) {\n if (!table.search) continue;\n for (const column of table.columns) {\n if (column.source.kind !== \"search\") continue;\n patterns.push(atlasExcludePattern(table.schema, table.table, column.column));\n }\n for (const index of searchIndexNames(table.search)) {\n patterns.push(atlasExcludePattern(table.schema, table.table, index));\n }\n }\n return patterns;\n};\n\n// ── vector.sql ───────────────────────────────────────────────────────────────\n\nexport function renderVectorDdl(plan: SchemaPlan): string {\n const tables = plan.tables.filter(t => t.vectorColumns.length > 0);\n if (tables.length === 0) return \"\";\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\";\n ddl += \"--\\n\";\n ddl += \"-- Vector columns and their ANN indexes, for the collections declaring a\\n\";\n ddl += \"-- `vector` property. Applied by Rebase, not by Atlas — see\\n\";\n ddl += \"-- generatePostgresVectorDdl.\\n\\n\";\n // The note is not decoration. Someone reading this file after a failed push\n // is looking for the reason the type does not exist, and \"no CREATE\n // EXTENSION here\" is invisible unless it is written down.\n ddl += vectorExtensionDeclared(plan.options.databaseExtensions)\n ? `${vectorExtensionStatement()}\\n\\n`\n : \"-- pgvector is not installed from here: no database declared it. To let Rebase\\n\" +\n `-- install it, add ${VECTOR_EXTENSION_OPT_IN} in config/resources.ts.\\n` +\n \"-- Otherwise install it once by hand; the column below needs the type either way.\\n\\n\";\n\n for (const table of tables) {\n const target = `\"${table.schema}\".\"${table.table}\"`;\n for (const spec of table.vectorColumns) {\n // Guard before the ADD, so a changed `dimensions` is reported\n // rather than skipped over — see `vectorDimensionGuard`.\n ddl += `${vectorDimensionGuard(spec)}\\n`;\n ddl += `ALTER TABLE ${target} ADD COLUMN IF NOT EXISTS ${vectorColumnDefinition(spec)};\\n`;\n }\n if (table.vector) {\n vectorIndexStatements(table.vector).forEach(s => { ddl += `${s}\\n`; });\n for (const skip of table.vector.skipped) {\n ddl += `-- No ANN index on \"${skip.schema}\".\"${skip.table}\".\"${skip.column}\": ${skip.reason}\\n`;\n }\n }\n ddl += \"\\n\";\n }\n\n return ddl;\n}\n\n/** @see searchExcludePatternsOf */\nexport const vectorExcludePatternsOf = (plan: SchemaPlan): string[] => {\n const patterns: string[] = [];\n for (const table of plan.tables) {\n const names = [\n ...table.vectorColumns.map(spec => spec.column),\n ...(table.vector ? vectorIndexNames(table.vector) : [])\n ];\n for (const name of names) patterns.push(atlasExcludePattern(table.schema, table.table, name));\n }\n return patterns;\n};\n\n// ── triggers.sql ─────────────────────────────────────────────────────────────\n\n/**\n * `autoValue: \"on_update\"`, as the file Rebase applies itself.\n *\n * Empty when nothing declares one — the caller writes no file then, and removes\n * a stale one.\n */\nexport function renderTriggersDdl(plan: SchemaPlan): string {\n const tables = plan.tables.filter(t => t.triggers.length > 0);\n if (tables.length === 0) return \"\";\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\";\n ddl += \"--\\n\";\n ddl += \"-- `updated_at` triggers, for the properties declaring `autoValue: \\\"on_update\\\"`,\\n\";\n ddl += \"-- and the triggers that keep a row in its tenant.\\n\";\n ddl += \"-- Applied by Rebase, not by Atlas — a trigger is a function plus a binding,\\n\";\n ddl += \"-- and Atlas's free tier refuses to parse a desired state containing one.\\n\\n\";\n\n for (const statement of plan.functions.filter(isTriggerFunction)) {\n ddl += `${statement}\\n\\n`;\n }\n for (const table of tables) {\n for (const trigger of table.triggers) {\n triggerStatements(trigger).forEach(s => { ddl += `${s}\\n`; });\n }\n ddl += \"\\n\";\n }\n return ddl;\n}\n\nconst isTriggerFunction = (statement: string): boolean => statement.includes(\"RETURNS trigger\");\n\n/** @see searchExcludePatternsOf */\nexport const triggerExcludePatternsOf = (plan: SchemaPlan): string[] =>\n plan.tables.flatMap(table => table.triggers.map(t => atlasExcludePattern(table.schema, table.table, t.name)));\n\nconst quoteIdentifier = (name: string): string => `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n\n/** The comment a view Rebase created carries: `rebase:view:<hash>`. */\nexport const viewComment = (view: ViewPlan): string => `rebase:view:${view.hash}`;\n\n/** A dollar-quote tag the text does not contain, so the text can be quoted whole. */\nfunction dollarTag(text: string): string {\n let tag = \"$rebase_view$\";\n for (let i = 1; text.includes(tag); i++) tag = `$rebase_view_${i}$`;\n return tag;\n}\n\n/**\n * The statements that create one view as planned, comment included, for\n * `EXECUTE`. A plain view runs as the caller (`security_invoker`), so the\n * policies of the tables it reads decide what each caller sees.\n *\n * A materialized view is two objects (see `view-names.ts`): its rows, stored\n * under {@link viewRowsName} with a unique index on the id columns (which\n * `REFRESH … CONCURRENTLY` needs), and the gate under the collection's name —\n * a `security_barrier` view that reads them with the owner's rights and serves\n * them to the collection's roles and to the server (no uid). It reads the\n * settings directly rather than through `rebase.roles()`, which a first boot\n * creates after the views. It carries each row's `xmin`, for `fingerprint()`;\n * the catalogue reader leaves that column out of the collection.\n */\nexport function viewCreateStatements(view: ViewPlan): string[] {\n const qualified = `${quoteIdentifier(view.schema)}.${quoteIdentifier(view.name)}`;\n if (!view.materialized) {\n return [\n `CREATE VIEW ${qualified} WITH (security_invoker = true) AS\\n${view.query}`,\n `COMMENT ON VIEW ${qualified} IS '${viewComment(view)}'`\n ];\n }\n const stored = `${quoteIdentifier(view.schema)}.${quoteIdentifier(viewRowsName(view.name))}`;\n const roles = view.roles.map(role => `'${role.replace(/'/g, \"''\")}'`).join(\", \");\n const statements = [`CREATE MATERIALIZED VIEW ${stored} AS\\n${view.query}\\nWITH DATA`];\n if (view.idColumns.length > 0) {\n statements.push(`CREATE UNIQUE INDEX ${quoteIdentifier(`${view.name}_rebase_id`)} ON ${stored} (${view.idColumns.map(quoteIdentifier).join(\", \")})`);\n }\n statements.push(...view.indexes);\n statements.push(\n `COMMENT ON MATERIALIZED VIEW ${stored} IS '${VIEW_ROWS_COMMENT_PREFIX}${view.hash}'`,\n `REVOKE ALL ON ${stored} FROM PUBLIC`,\n `CREATE VIEW ${qualified} WITH (security_barrier = true) AS\\n` +\n `SELECT rows.*, rows.xmin AS xmin FROM ${stored} rows\\n` +\n \"WHERE NULLIF(current_setting('app.uid', true), '') IS NULL\\n\" +\n ` OR string_to_array(COALESCE(current_setting('app.user_roles', true), ''), ',') && ARRAY[${roles || \"NULL\"}]::text[]`,\n `COMMENT ON VIEW ${qualified} IS '${viewComment(view)}'`\n );\n return statements;\n}\n\n/**\n * `views.sql`: the views of the collections that declare one, as the file\n * Rebase applies itself — Atlas manages no views on its free tier.\n *\n * Idempotent, in two passes. The first drops, last first, every view whose\n * comment no longer matches its plan and every view that reads one of those\n * (Postgres will not drop a view another still reads, and will not change a\n * view's columns in place); the second creates, in order, every view that is\n * not there. A view that is up to date is left alone, rows and all. A table or\n * a view Rebase did not create under the same name is refused, never dropped.\n *\n * Empty when no collection declares a view.\n */\nexport function renderViewsDdl(plan: SchemaPlan): string {\n if (plan.views.length === 0) return \"\";\n const literal = (text: string) => `'${text.replace(/'/g, \"''\")}'`;\n const regclass = (view: ViewPlan) => `to_regclass(${literal(`${quoteIdentifier(view.schema)}.${quoteIdentifier(view.name)}`)})`;\n const stale = (view: ViewPlan) =>\n `(${regclass(view)} IS NOT NULL AND obj_description(${regclass(view)}, 'pg_class') IS DISTINCT FROM ${literal(viewComment(view))})`;\n // Every planned view a view reads, directly or through another.\n const readsOf = (view: ViewPlan, seen = new Set<string>()): ViewPlan[] =>\n view.dependsOn.flatMap(name => {\n if (seen.has(name)) return [];\n seen.add(name);\n const target = plan.views.find(other => other.qualified === name);\n return target ? [target, ...readsOf(target, seen)] : [];\n });\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\";\n ddl += \"--\\n\";\n ddl += \"-- The views of the collections that declare `view`. Applied by Rebase, not by Atlas.\\n\\n\";\n ddl += \"DO $rebase_views$\\nDECLARE\\n kind \\\"char\\\";\\n note text;\\nBEGIN\\n\";\n for (const view of [...plan.views].reverse()) {\n const qualified = `${quoteIdentifier(view.schema)}.${quoteIdentifier(view.name)}`;\n const reasons = [view, ...readsOf(view)].map(stale).join(\"\\n OR \");\n ddl += ` SELECT c.relkind, obj_description(c.oid, 'pg_class') INTO kind, note FROM pg_class c WHERE c.oid = ${regclass(view)};\\n`;\n ddl += \" IF kind IS NOT NULL AND (kind NOT IN ('v', 'm') OR note IS NULL OR note NOT LIKE 'rebase:view:%') THEN\\n\";\n ddl += ` RAISE EXCEPTION 'Rebase will not replace %: it is a table or a view Rebase did not create. Rename or drop it, or give the collection another table.', ${literal(view.qualified)};\\n`;\n ddl += \" END IF;\\n\";\n ddl += ` IF ${reasons} THEN\\n`;\n ddl += ` IF kind = 'm' THEN EXECUTE ${literal(`DROP MATERIALIZED VIEW ${qualified}`)}; ELSE EXECUTE ${literal(`DROP VIEW ${qualified}`)}; END IF;\\n`;\n ddl += \" END IF;\\n\";\n }\n for (const view of plan.views) {\n const rows = `${quoteIdentifier(view.schema)}.${quoteIdentifier(viewRowsName(view.name))}`;\n ddl += ` IF ${regclass(view)} IS NULL THEN\\n`;\n // A gate that is gone leaves its rows: they are this view's, recomputed below.\n if (view.materialized) {\n ddl += ` IF to_regclass(${literal(rows)}) IS NOT NULL THEN EXECUTE ${literal(`DROP MATERIALIZED VIEW ${rows}`)}; END IF;\\n`;\n }\n for (const statement of viewCreateStatements(view)) {\n const tag = dollarTag(statement);\n ddl += ` EXECUTE ${tag}${statement}${tag};\\n`;\n }\n if (view.materialized) {\n ddl += ` IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${literal(REBASE_USER_ROLE)}) THEN EXECUTE ${literal(`REVOKE ALL ON ${rows} FROM ${REBASE_USER_ROLE}`)}; END IF;\\n`;\n }\n ddl += \" END IF;\\n\";\n }\n ddl += \"END\\n$rebase_views$;\\n\";\n return ddl;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,IAAa,gBAAgB,SAAyB;CAClD,QAAQ,KAAK,MAAb;EACI,KAAK,QAAQ,OAAO;EACpB,KAAK,WAAW,OAAO,WAAW,KAAK,OAAO;EAC9C,KAAK,QAAQ,OAAO,QAAQ,KAAK,OAAO;EACxC,KAAK,QAAQ,OAAO;EACpB,KAAK,QAAQ,OAAO,IAAI,KAAK,OAAO,KAAK,KAAK,KAAK;EACnD,KAAK,YAAY,O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AC1C,MAAM,YAAY,GAAG,gBAAgB,KAAK,MAAM,EAAE,GAAG,gBAAgB,KAAK,IAAI;EAC9E,MAAM,UAAU,CAAC,MAAM,GAAG,QAAQ,IAAI,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,KAAK,eAAe;EACxE,OAAO,0GAA0G,SAAS,IAAI,EAAE;EAChI,OAAO;EACP,OAAO,iKAAiK,QAAQ,KAAK,SAAS,EAAE;EAChM,OAAO;EACP,OAAO,UAAU,QAAQ;EACzB,OAAO,sCAAsC,QAAQ,0BAA0B,WAAW,EAAE,iBAAiB,QAAQ,aAAa,WAAW,EAAE;EAC/I,OAAO;CACX;CACA,KAAK,MAAM,QAAQ,KAAK,OAAO;EAC3B,MAAM,OAAO,GAAG,gBAAgB,KAAK,MAAM,EAAE,GAAG,gBAAgB,aAAa,KAAK,IAAI,CAAC;EACvF,OAAO,UAAU,SAAS,IAAI,EAAE;EAEhC,IAAI,KAAK,cACL,OAAO,0BAA0B,QAAQ,IAAI,EAAE,6BAA6B,QAAQ,0BAA0B,MAAM,EAAE;EAE1H,KAAK,MAAM,aAAa,qBAAqB,IAAI,GAAG;GAChD,MAAM,MAAM,UAAU,SAAS;GAC/B,OAAO,mBAAmB,MAAM,YAAY,IAAI;EACpD;EACA,IAAI,KAAK,cACL,OAAO,6DAA6D,QAAQ,gBAAgB,EAAE,iBAAiB,QAAQ,iBAAiB,KAAK,QAAQ,kBAAkB,EAAE;EAE7K,OAAO;CACX;CACA,OAAO;CACP,OAAO;AACX"}
@@ -1,10 +1,10 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { i as __exportAll, t as promptConfirm } from "./cli-prompt-DXG0yk-h.js";
4
- import { it as redactConnectionPasswords } from "./cli-errors-DYTxnLbW.js";
5
- import { n as resolveRlsSettings } from "./rls-settings-BCGMIig3.js";
6
- import { a as outWarn, i as outError, r as out, t as chalk } from "./source-fZb92pN8.js";
7
- import { _ as closestWord, y as parseCommandFlags } from "./migrate-baseline-CmWXL7qx.js";
4
+ import { ot as redactConnectionPasswords } from "./cli-schema-dir-CiN0ephV.js";
5
+ import { n as resolveRlsSettings } from "./rls-settings-CmGK2U0a.js";
6
+ import { a as outWarn, i as outError, r as out, t as chalk } from "./source-VxbrQojV.js";
7
+ import { _ as closestWord, v as parseCommandFlags } from "./migrate-baseline-DZmekgpD.js";
8
8
  import { REBASE_USER_ROLE } from "@rebasepro/common";
9
9
  //#region src/request-role-cli.ts
10
10
  var request_role_cli_exports = /* @__PURE__ */ __exportAll({
@@ -163,9 +163,9 @@ function databaseUrlOrExit() {
163
163
  async function provisionCommand(rawArgs) {
164
164
  parseProvisionLine(rawArgs);
165
165
  const databaseUrl = databaseUrlOrExit();
166
- const { withAppClient } = await import("./cli-errors-DYTxnLbW.js").then((n) => n.v);
167
- const { appRoleSetupInstructions, readRecordedRequestRoles } = await import("./rls-enforcement-Cc_UhOxb.js").then((n) => n.y);
168
- const { cliRlsSettings } = await import("./rls-settings-BCGMIig3.js").then((n) => n.a);
166
+ const { withAppClient } = await import("./cli-schema-dir-CiN0ephV.js").then((n) => n.x);
167
+ const { appRoleSetupInstructions, readRecordedRequestRoles } = await import("./rls-enforcement-DB5HHj96.js").then((n) => n.y);
168
+ const { cliRlsSettings } = await import("./rls-settings-CmGK2U0a.js").then((n) => n.a);
169
169
  out(await withAppClient(databaseUrl, async (client) => {
170
170
  const run = async (text) => (await client.query(text)).rows;
171
171
  const [who] = await run("SELECT current_user AS role");
@@ -195,9 +195,9 @@ async function confirmMigration(yes) {
195
195
  async function requestRoleCommand(rawArgs) {
196
196
  const line = parseRequestRoleLine(rawArgs);
197
197
  const databaseUrl = databaseUrlOrExit();
198
- const { withAppClient } = await import("./cli-errors-DYTxnLbW.js").then((n) => n.v);
199
- const { AppRoleSetupError, readRecordedRequestRoles } = await import("./rls-enforcement-Cc_UhOxb.js").then((n) => n.y);
200
- const { migrateRequestRoles, planRequestRoleMigration } = await import("./request-role-migration-GHTJnPMV.js");
198
+ const { withAppClient } = await import("./cli-schema-dir-CiN0ephV.js").then((n) => n.x);
199
+ const { AppRoleSetupError, readRecordedRequestRoles } = await import("./rls-enforcement-DB5HHj96.js").then((n) => n.y);
200
+ const { migrateRequestRoles, planRequestRoleMigration } = await import("./request-role-migration-C8aq_TO3.js");
201
201
  out("");
202
202
  out(chalk.bold(" rebase db request-role migrate"));
203
203
  out("");
@@ -257,4 +257,4 @@ function requestRoleReminder(to) {
257
257
  //#endregion
258
258
  export { parseRequestRoleLine as n, request_role_cli_exports as r, parseProvisionLine as t };
259
259
 
260
- //# sourceMappingURL=request-role-cli-Dy1EgJU9.js.map
260
+ //# sourceMappingURL=request-role-cli-BdRzdE87.js.map