@rebasepro/server-postgres 0.29.1 → 0.29.3

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 (148) hide show
  1. package/dist/{BranchService-BIIBF5ZL.js → BranchService-CrXvcES2.js} +3 -3
  2. package/dist/{BranchService-BIIBF5ZL.js.map → BranchService-CrXvcES2.js.map} +1 -1
  3. package/dist/PostgresBackendDriver.d.ts +64 -4
  4. package/dist/PostgresBootstrapper.d.ts +27 -0
  5. package/dist/auth/ensure-tables.d.ts +2 -2
  6. package/dist/auth/schema-version.d.ts +5 -5
  7. package/dist/auth/services.d.ts +9 -9
  8. package/dist/{backup-cli-QcOpmRpQ.js → backup-cli-CTKCOLpX.js} +3 -3
  9. package/dist/{backup-cli-QcOpmRpQ.js.map → backup-cli-CTKCOLpX.js.map} +1 -1
  10. package/dist/{boot-ddl-BSNpEUOS.js → boot-ddl-CqGIwSYx.js} +2 -2
  11. package/dist/{boot-ddl-BSNpEUOS.js.map → boot-ddl-CqGIwSYx.js.map} +1 -1
  12. package/dist/{cli-console-DTsm96lW.js → cli-console-DBPw-oAz.js} +6 -6
  13. package/dist/{cli-console-DTsm96lW.js.map → cli-console-DBPw-oAz.js.map} +1 -1
  14. package/dist/{cli-errors-DwqFRIWz.js → cli-errors-DYTxnLbW.js} +5 -5
  15. package/dist/{cli-errors-DwqFRIWz.js.map → cli-errors-DYTxnLbW.js.map} +1 -1
  16. package/dist/cli.js +185 -49
  17. package/dist/cli.js.map +1 -1
  18. package/dist/{connection-COuS5Fm-.js → connection-C1zXTPJq.js} +7 -3
  19. package/dist/{connection-COuS5Fm-.js.map → connection-C1zXTPJq.js.map} +1 -1
  20. package/dist/data-transformer.d.ts +2 -2
  21. package/dist/database-health.d.ts +2 -1
  22. package/dist/{database-preflight-D5JtPt8i.js → database-preflight-iBpT7-vv.js} +36 -3
  23. package/dist/database-preflight-iBpT7-vv.js.map +1 -0
  24. package/dist/{databasePoolManager-7hXVurmG.js → databasePoolManager-DIjzlTK4.js} +2 -2
  25. package/dist/{databasePoolManager-7hXVurmG.js.map → databasePoolManager-DIjzlTK4.js.map} +1 -1
  26. package/dist/{deferred-index-build-B8feKnUj.js → deferred-index-build-BCU9RoHK.js} +18 -6
  27. package/dist/deferred-index-build-BCU9RoHK.js.map +1 -0
  28. package/dist/{doctor-BaR11xUe.js → doctor-Kg1oUK0Q.js} +11 -11
  29. package/dist/doctor-Kg1oUK0Q.js.map +1 -0
  30. package/dist/{ensure-collection-policies-85HiG-k1.js → ensure-collection-policies-Bo-_fDAy.js} +25 -15
  31. package/dist/ensure-collection-policies-Bo-_fDAy.js.map +1 -0
  32. package/dist/{ensure-collection-tables-DR_WcxLA.js → ensure-collection-tables-DCJINkT_.js} +11 -8
  33. package/dist/ensure-collection-tables-DCJINkT_.js.map +1 -0
  34. package/dist/{ensure-tables-Dh5UP_Zs.js → ensure-tables-BPGaGh0y.js} +4 -4
  35. package/dist/ensure-tables-BPGaGh0y.js.map +1 -0
  36. package/dist/{enum-labels-kept-DSU8lAnd.js → enum-labels-kept-YAgOZS4I.js} +3 -3
  37. package/dist/{enum-labels-kept-DSU8lAnd.js.map → enum-labels-kept-YAgOZS4I.js.map} +1 -1
  38. package/dist/{generate-drizzle-schema-5spbTyQ6.js → generate-drizzle-schema-DcrFr7YX.js} +2 -2
  39. package/dist/{generate-drizzle-schema-5spbTyQ6.js.map → generate-drizzle-schema-DcrFr7YX.js.map} +1 -1
  40. package/dist/{generate-drizzle-schema-logic-C5FB7Fpo.js → generate-drizzle-schema-logic-LTLZvt6r.js} +3 -3
  41. package/dist/{generate-drizzle-schema-logic-C5FB7Fpo.js.map → generate-drizzle-schema-logic-LTLZvt6r.js.map} +1 -1
  42. package/dist/{generate-files-Bl3_D_oP.js → generate-files-CsaVzatS.js} +3 -3
  43. package/dist/{generate-files-Bl3_D_oP.js.map → generate-files-CsaVzatS.js.map} +1 -1
  44. package/dist/{generate-postgres-ddl-logic-BC3JA93M.js → generate-postgres-ddl-logic-Dg0bcENZ.js} +45 -7
  45. package/dist/generate-postgres-ddl-logic-Dg0bcENZ.js.map +1 -0
  46. package/dist/{generated-schema-diff-Jm93vyJB.js → generated-schema-diff-By4dxyTH.js} +8 -5
  47. package/dist/generated-schema-diff-By4dxyTH.js.map +1 -0
  48. package/dist/history/HistoryService.d.ts +2 -3
  49. package/dist/history/ensure-history-table.d.ts +8 -3
  50. package/dist/index.es.js +15 -15
  51. package/dist/interfaces.d.ts +24 -2
  52. package/dist/{introspect-db-logic-DgQVzccW.js → introspect-db-logic-DWqAEURB.js} +7 -5
  53. package/dist/introspect-db-logic-DWqAEURB.js.map +1 -0
  54. package/dist/{migrate-baseline-BfHmq3vN.js → migrate-baseline-CmWXL7qx.js} +163 -502
  55. package/dist/migrate-baseline-CmWXL7qx.js.map +1 -0
  56. package/dist/{migrate-policy-stamps-B4k1ggma.js → migrate-policy-stamps-BN_Qad6c.js} +42 -13
  57. package/dist/migrate-policy-stamps-BN_Qad6c.js.map +1 -0
  58. package/dist/{open-rebase-CiO_sjMT.js → open-rebase-40paQfVW.js} +1401 -655
  59. package/dist/open-rebase-40paQfVW.js.map +1 -0
  60. package/dist/open-rebase.d.ts +1 -1
  61. package/dist/{pg-error-utils-D1Nc0UML.js → pg-error-utils-DJHjCF7-.js} +2 -2
  62. package/dist/{pg-error-utils-D1Nc0UML.js.map → pg-error-utils-DJHjCF7-.js.map} +1 -1
  63. package/dist/pipelined-transaction.d.ts +24 -37
  64. package/dist/{plan-schema-BYxOzflz.js → plan-schema-vJd3UEmT.js} +41 -11
  65. package/dist/plan-schema-vJd3UEmT.js.map +1 -0
  66. package/dist/{policy-drift-DKuTJHfc.js → policy-drift-C-m0uWHH.js} +78 -10
  67. package/dist/policy-drift-C-m0uWHH.js.map +1 -0
  68. package/dist/push-index-adoption-Cp7oZxSl.js +22 -0
  69. package/dist/push-index-adoption-Cp7oZxSl.js.map +1 -0
  70. package/dist/{push-index-prebuild-bqXimSZz.js → push-index-prebuild-DbwKGtQT.js} +4 -4
  71. package/dist/{push-index-prebuild-bqXimSZz.js.map → push-index-prebuild-DbwKGtQT.js.map} +1 -1
  72. package/dist/{push-kept-defaults-CN9R8cHf.js → push-kept-defaults-CLcgsEPt.js} +2 -2
  73. package/dist/{push-kept-defaults-CN9R8cHf.js.map → push-kept-defaults-CLcgsEPt.js.map} +1 -1
  74. package/dist/{push-legacy-renames-CU_UYPbz.js → push-legacy-renames-BthD0E9W.js} +4 -4
  75. package/dist/{push-legacy-renames-CU_UYPbz.js.map → push-legacy-renames-BthD0E9W.js.map} +1 -1
  76. package/dist/{push-policy-plan-JcyK94bc.js → push-policy-plan-BgcrroxQ.js} +14 -8
  77. package/dist/push-policy-plan-BgcrroxQ.js.map +1 -0
  78. package/dist/read-routing.d.ts +10 -30
  79. package/dist/{render-ddl-DCdVP-pQ.js → render-ddl-Ci3S_SoI.js} +34 -3
  80. package/dist/render-ddl-Ci3S_SoI.js.map +1 -0
  81. package/dist/{request-role-cli-DSdRtvgH.js → request-role-cli-Dy1EgJU9.js} +10 -10
  82. package/dist/{request-role-cli-DSdRtvgH.js.map → request-role-cli-Dy1EgJU9.js.map} +1 -1
  83. package/dist/{request-role-migration-D9BZ5Uba.js → request-role-migration-GHTJnPMV.js} +2 -2
  84. package/dist/{request-role-migration-D9BZ5Uba.js.map → request-role-migration-GHTJnPMV.js.map} +1 -1
  85. package/dist/rls-bootstrap-sql-kPX4-MB1.js +549 -0
  86. package/dist/rls-bootstrap-sql-kPX4-MB1.js.map +1 -0
  87. package/dist/{rls-enforcement-BO618rnr.js → rls-enforcement-Cc_UhOxb.js} +316 -10
  88. package/dist/rls-enforcement-Cc_UhOxb.js.map +1 -0
  89. package/dist/{rls-settings-De5NoHHy.js → rls-settings-BCGMIig3.js} +23 -3
  90. package/dist/rls-settings-BCGMIig3.js.map +1 -0
  91. package/dist/schema/doctor-cli.js +9 -9
  92. package/dist/schema/doctor-cli.js.map +1 -1
  93. package/dist/schema/drizzle-ddl.d.ts +2 -2
  94. package/dist/schema/ensure-collection-policies.d.ts +23 -3
  95. package/dist/schema/generate-drizzle-schema.js +1 -1
  96. package/dist/schema/generate-postgres-ddl-logic.d.ts +14 -1
  97. package/dist/schema/generate-postgres-ddl.js +1 -1
  98. package/dist/schema/index-adoption.d.ts +99 -0
  99. package/dist/schema/introspect-db-logic.d.ts +2 -1
  100. package/dist/schema/introspect-db.js +3 -3
  101. package/dist/schema/migrate-policy-stamps.d.ts +19 -1
  102. package/dist/schema/plan/diff-plan.d.ts +8 -1
  103. package/dist/schema/plan/render-ddl.d.ts +7 -0
  104. package/dist/schema/plan/types.d.ts +15 -0
  105. package/dist/schema/push-index-adoption.d.ts +10 -0
  106. package/dist/schema/push-policy-plan.d.ts +5 -1
  107. package/dist/schema/rls-bootstrap-sql.d.ts +19 -2
  108. package/dist/schema/search-column.d.ts +2 -2
  109. package/dist/search-column-BM-GV6vH.js.map +1 -1
  110. package/dist/security/policy-drift.d.ts +31 -1
  111. package/dist/security/rls-enforcement.d.ts +118 -1
  112. package/dist/security/rls-settings.d.ts +33 -0
  113. package/dist/services/FetchService.d.ts +33 -8
  114. package/dist/services/PersistService.d.ts +75 -4
  115. package/dist/services/RelationService.d.ts +1 -1
  116. package/dist/services/channel-bus/PostgresChannelBus.d.ts +2 -2
  117. package/dist/services/channel-bus/index.d.ts +2 -2
  118. package/dist/services/channel-history.d.ts +2 -2
  119. package/dist/services/channel-presence.d.ts +3 -3
  120. package/dist/services/dataService.d.ts +6 -2
  121. package/dist/services/realtimeService.d.ts +18 -5
  122. package/dist/services/socket-liveness.d.ts +6 -1
  123. package/dist/types.d.ts +1 -1
  124. package/dist/utils/drizzle-conditions.d.ts +12 -0
  125. package/dist/utils/positional-params.d.ts +40 -0
  126. package/dist/{websocket-B33YjKhs.js → websocket-B7ex6AQM.js} +3 -3
  127. package/dist/websocket-B7ex6AQM.js.map +1 -0
  128. package/dist/websocket.d.ts +14 -3
  129. package/package.json +7 -7
  130. package/dist/database-preflight-D5JtPt8i.js.map +0 -1
  131. package/dist/deferred-index-build-B8feKnUj.js.map +0 -1
  132. package/dist/doctor-BaR11xUe.js.map +0 -1
  133. package/dist/ensure-collection-policies-85HiG-k1.js.map +0 -1
  134. package/dist/ensure-collection-tables-DR_WcxLA.js.map +0 -1
  135. package/dist/ensure-tables-Dh5UP_Zs.js.map +0 -1
  136. package/dist/generate-postgres-ddl-logic-BC3JA93M.js.map +0 -1
  137. package/dist/generated-schema-diff-Jm93vyJB.js.map +0 -1
  138. package/dist/introspect-db-logic-DgQVzccW.js.map +0 -1
  139. package/dist/migrate-baseline-BfHmq3vN.js.map +0 -1
  140. package/dist/migrate-policy-stamps-B4k1ggma.js.map +0 -1
  141. package/dist/open-rebase-CiO_sjMT.js.map +0 -1
  142. package/dist/plan-schema-BYxOzflz.js.map +0 -1
  143. package/dist/policy-drift-DKuTJHfc.js.map +0 -1
  144. package/dist/push-policy-plan-JcyK94bc.js.map +0 -1
  145. package/dist/render-ddl-DCdVP-pQ.js.map +0 -1
  146. package/dist/rls-enforcement-BO618rnr.js.map +0 -1
  147. package/dist/rls-settings-De5NoHHy.js.map +0 -1
  148. package/dist/websocket-B33YjKhs.js.map +0 -1
@@ -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-BYxOzflz.js";
4
- import { s as diffPlanAgainstCatalogue } from "./deferred-index-build-B8feKnUj.js";
5
- import { i as readExistingSchema } from "./ensure-collection-tables-DR_WcxLA.js";
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";
6
6
  import { declaredDatabaseExtensions } from "@rebasepro/types";
7
7
  //#region src/schema/push-index-prebuild.ts
8
8
  /**
@@ -42,4 +42,4 @@ async function missingForeignKeyIndexes(client, collections) {
42
42
  //#endregion
43
43
  export { missingForeignKeyIndexes };
44
44
 
45
- //# sourceMappingURL=push-index-prebuild-bqXimSZz.js.map
45
+ //# sourceMappingURL=push-index-prebuild-DbwKGtQT.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"push-index-prebuild-bqXimSZz.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 CollectionConfig } from \"@rebasepro/types\";\nimport { planSchema } from \"./plan/plan-schema\";\nimport { diffPlanAgainstCatalogue, type DeferredIndexBuild } from \"./plan/diff-plan\";\nimport { readExistingSchema, type Queryable } from \"./ensure-collection-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 collections: CollectionConfig[]\n): Promise<DeferredIndexBuild[]> {\n const schema = planSchema(collections, { 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,aAC6B;CAC7B,MAAM,SAAS,WAAW,aAAa,EAAE,oBAAoB,2BAA2B,EAAE,CAAC;CAI3F,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
+ {"version":3,"file":"push-index-prebuild-DbwKGtQT.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 CollectionConfig } from \"@rebasepro/types\";\nimport { planSchema } from \"./plan/plan-schema\";\nimport { diffPlanAgainstCatalogue, type DeferredIndexBuild } from \"./plan/diff-plan\";\nimport { readExistingSchema, type Queryable } from \"./ensure-collection-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 collections: CollectionConfig[]\n): Promise<DeferredIndexBuild[]> {\n const schema = planSchema(collections, { 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,aAC6B;CAC7B,MAAM,SAAS,WAAW,aAAa,EAAE,oBAAoB,2BAA2B,EAAE,CAAC;CAI3F,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,7 +1,7 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { u as resolveColumnName } from "./column-plan-helpers-BeSztMor.js";
4
- import { n as planSchema } from "./plan-schema-BYxOzflz.js";
4
+ import { n as planSchema } from "./plan-schema-vJd3UEmT.js";
5
5
  import { declaredDatabaseExtensions } from "@rebasepro/types";
6
6
  //#region src/schema/push-kept-defaults.ts
7
7
  /**
@@ -134,4 +134,4 @@ ${keptDefaultStatements(kept).join("\n")}\n`;
134
134
  //#endregion
135
135
  export { databaseOwnedDefaultColumns, readKeptDefaults, withKeptDefaults };
136
136
 
137
- //# sourceMappingURL=push-kept-defaults-CN9R8cHf.js.map
137
+ //# sourceMappingURL=push-kept-defaults-CLcgsEPt.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"push-kept-defaults-CN9R8cHf.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 CollectionConfig, type Property } from \"@rebasepro/types\";\nimport { planSchema } from \"./plan/plan-schema\";\nimport { resolveColumnName } from \"./column-plan-helpers\";\nimport type { Queryable } from \"./ensure-collection-tables\";\n\n/** A column whose DEFAULT the collections 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 `databaseDefault: true` that the planner writes no\n * DEFAULT for. An id strategy or `autoValue` writes one of its own, and that\n * one is the planner's to keep.\n */\nexport function databaseOwnedDefaultColumns(collections: CollectionConfig[]): DatabaseOwnedDefaultColumn[] {\n const declared = collections.filter(collection =>\n Object.values(collection.properties ?? {}).some(prop => isDatabaseOwned(prop)));\n if (declared.length === 0) return [];\n\n const plan = planSchema(collections, { databaseExtensions: declaredDatabaseExtensions() });\n const found: DatabaseOwnedDefaultColumn[] = [];\n for (const table of plan.tables) {\n const collection = declared.find(each => each.slug === table.slug);\n if (!collection) continue;\n for (const [key, prop] of Object.entries(collection.properties ?? {})) {\n if (!isDatabaseOwned(prop)) continue;\n const name = resolveColumnName(key, prop);\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\nconst isDatabaseOwned = (prop: unknown): prop is Property =>\n typeof prop === \"object\" && prop !== null &&\n (prop as { databaseDefault?: unknown }).databaseDefault === true;\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 \"-- read before planning so the push leaves them as they are.\\n\" +\n `${keptDefaultStatements(kept).join(\"\\n\")}\\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,4BAA4B,aAA+D;CACvG,MAAM,WAAW,YAAY,QAAO,eAChC,OAAO,OAAO,WAAW,cAAc,CAAC,CAAC,CAAC,CAAC,MAAK,SAAQ,gBAAgB,IAAI,CAAC,CAAC;CAClF,IAAI,SAAS,WAAW,GAAG,OAAO,CAAC;CAEnC,MAAM,OAAO,WAAW,aAAa,EAAE,oBAAoB,2BAA2B,EAAE,CAAC;CACzF,MAAM,QAAsC,CAAC;CAC7C,KAAK,MAAM,SAAS,KAAK,QAAQ;EAC7B,MAAM,aAAa,SAAS,MAAK,SAAQ,KAAK,SAAS,MAAM,IAAI;EACjE,IAAI,CAAC,YAAY;EACjB,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,WAAW,cAAc,CAAC,CAAC,GAAG;GACnE,IAAI,CAAC,gBAAgB,IAAI,GAAG;GAC5B,MAAM,OAAO,kBAAkB,KAAK,IAAI;GACxC,MAAM,SAAS,MAAM,QAAQ,MAAK,SAAQ,KAAK,WAAW,IAAI;GAC9D,IAAI,CAAC,UAAU,OAAO,WAAW,OAAO,WAAW;GACnD,MAAM,KAAK;IAAE,QAAQ,MAAM;IAAQ,OAAO,MAAM;IAAO,QAAQ;GAAK,CAAC;EACzE;CACJ;CACA,OAAO;AACX;AAEA,IAAM,mBAAmB,SACrB,OAAO,SAAS,YAAY,SAAS,QACpC,KAAuC,oBAAoB;;;;;;;;;AAUhE,IAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuC1B,eAAsB,iBAAiB,QAAmB,SAA+D;CACrH,IAAI,QAAQ,WAAW,GAAG,OAAO,CAAC;CAClC,MAAM,SAAS,IAAI,IAAI,QAAQ,IAAI,KAAK,CAAC;CACzC,IAAI;CACJ,MAAM,OAAO,MAAM,iBAAiB;CACpC,IAAI;EACA,MAAM,OAAO,MAAM,qCAAqC;EACxD,QAAQ,MAAM,OAAO,MAAsB,iBAAiB,EAAA,CAAG;CACnE,UAAU;EACN,MAAM,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
+ {"version":3,"file":"push-kept-defaults-CLcgsEPt.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 CollectionConfig, type Property } from \"@rebasepro/types\";\nimport { planSchema } from \"./plan/plan-schema\";\nimport { resolveColumnName } from \"./column-plan-helpers\";\nimport type { Queryable } from \"./ensure-collection-tables\";\n\n/** A column whose DEFAULT the collections 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 `databaseDefault: true` that the planner writes no\n * DEFAULT for. An id strategy or `autoValue` writes one of its own, and that\n * one is the planner's to keep.\n */\nexport function databaseOwnedDefaultColumns(collections: CollectionConfig[]): DatabaseOwnedDefaultColumn[] {\n const declared = collections.filter(collection =>\n Object.values(collection.properties ?? {}).some(prop => isDatabaseOwned(prop)));\n if (declared.length === 0) return [];\n\n const plan = planSchema(collections, { databaseExtensions: declaredDatabaseExtensions() });\n const found: DatabaseOwnedDefaultColumn[] = [];\n for (const table of plan.tables) {\n const collection = declared.find(each => each.slug === table.slug);\n if (!collection) continue;\n for (const [key, prop] of Object.entries(collection.properties ?? {})) {\n if (!isDatabaseOwned(prop)) continue;\n const name = resolveColumnName(key, prop);\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\nconst isDatabaseOwned = (prop: unknown): prop is Property =>\n typeof prop === \"object\" && prop !== null &&\n (prop as { databaseDefault?: unknown }).databaseDefault === true;\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 \"-- read before planning so the push leaves them as they are.\\n\" +\n `${keptDefaultStatements(kept).join(\"\\n\")}\\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,4BAA4B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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-BYxOzflz.js";
4
- import { s as diffPlanAgainstCatalogue } from "./deferred-index-build-B8feKnUj.js";
5
- import { i as readExistingSchema } from "./ensure-collection-tables-DR_WcxLA.js";
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";
6
6
  import { declaredDatabaseExtensions } from "@rebasepro/types";
7
7
  //#region src/schema/push-legacy-renames.ts
8
8
  /**
@@ -31,4 +31,4 @@ async function legacyForeignKeyRenames(client, collections) {
31
31
  //#endregion
32
32
  export { legacyForeignKeyRenames };
33
33
 
34
- //# sourceMappingURL=push-legacy-renames-CU_UYPbz.js.map
34
+ //# sourceMappingURL=push-legacy-renames-BthD0E9W.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"push-legacy-renames-CU_UYPbz.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 CollectionConfig } from \"@rebasepro/types\";\nimport { planSchema } from \"./plan/plan-schema\";\nimport { diffPlanAgainstCatalogue, type LegacyForeignKey } from \"./plan/diff-plan\";\nimport { readExistingSchema, type Queryable } from \"./ensure-collection-tables\";\n\nexport interface LegacyRename extends LegacyForeignKey {\n /** `ALTER TABLE … RENAME COLUMN …;` */\n sql: string;\n}\n\nexport async function legacyForeignKeyRenames(client: Queryable, collections: CollectionConfig[]): Promise<LegacyRename[]> {\n const schema = planSchema(collections, { 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,aAA0D;CACvH,MAAM,SAAS,WAAW,aAAa,EAAE,oBAAoB,2BAA2B,EAAE,CAAC;CAG3F,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
+ {"version":3,"file":"push-legacy-renames-BthD0E9W.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 CollectionConfig } from \"@rebasepro/types\";\nimport { planSchema } from \"./plan/plan-schema\";\nimport { diffPlanAgainstCatalogue, type LegacyForeignKey } from \"./plan/diff-plan\";\nimport { readExistingSchema, type Queryable } from \"./ensure-collection-tables\";\n\nexport interface LegacyRename extends LegacyForeignKey {\n /** `ALTER TABLE … RENAME COLUMN …;` */\n sql: string;\n}\n\nexport async function legacyForeignKeyRenames(client: Queryable, collections: CollectionConfig[]): Promise<LegacyRename[]> {\n const schema = planSchema(collections, { 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,aAA0D;CACvH,MAAM,SAAS,WAAW,aAAa,EAAE,oBAAoB,2BAA2B,EAAE,CAAC;CAG3F,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,8 +1,7 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
- import { n as generatePostgresPoliciesDdl } from "./generate-postgres-ddl-logic-BC3JA93M.js";
4
- import { a as parseExpectedPolicies, o as partitionOrphans, t as checkPolicyDrift } from "./policy-drift-DKuTJHfc.js";
5
- import { probeRenderedPolicies, readPolicyStamps, tablesRlsWouldEnable } from "./ensure-collection-policies-85HiG-k1.js";
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";
6
5
  //#region src/schema/push-policy-plan.ts
7
6
  var keyOf = (p) => `${p.schema}.${p.table}.${p.name}`;
8
7
  /** What a stamp that no longer matches says. */
@@ -15,19 +14,23 @@ var UNSTAMPED_DIFFERS = "it carries no stamp of Rebase's, and its rule defines i
15
14
  * @param options.searchPath the `search_path` the stamps were written under
16
15
  * when the connection's own differs — the one `db push` stamps under.
17
16
  * See {@link readPolicyStamps}.
17
+ * @param options.adminRoleAvailable where the push writes the server-or-admin
18
+ * policies (`TO rebase_admin`, or `TO public` where the admin switch is
19
+ * not live); `"detect"` reads it off the database. Left out, as compiled.
18
20
  */
19
21
  async function planPolicyPush(client, collections, options = {}) {
20
- const drift = await checkPolicyDrift(client, collections);
22
+ const adminRoleAvailable = await resolveAdminPolicies(client, options.adminRoleAvailable);
23
+ const drift = await checkPolicyDrift(client, collections, { adminRoleAvailable });
21
24
  const { dropped, kept } = partitionOrphans(drift, collections);
22
25
  const enableRls = await tablesRlsWouldEnable(client, collections);
23
- const stamps = await underSearchPath(client, options.searchPath, () => readPolicyStamps(client, collections));
26
+ const stamps = await underSearchPath(client, options.searchPath, () => readPolicyStamps(client, collections, { adminRoleAvailable }));
24
27
  const replace = drift.diverged.map((d) => ({
25
28
  policy: d.expected,
26
29
  why: d.differences
27
30
  }));
28
31
  const settled = new Set([...drift.missing, ...drift.diverged.map((d) => d.expected)].map(keyOf));
29
32
  const unsure = [];
30
- for (const policy of parseExpectedPolicies(generatePostgresPoliciesDdl(collections))) {
33
+ for (const policy of expectedPolicies(collections, adminRoleAvailable)) {
31
34
  if (settled.has(keyOf(policy))) continue;
32
35
  const state = stamps.get(`${policy.schema}.${policy.table}`)?.get(policy.name);
33
36
  if (state === "stale" || state === "unstamped") unsure.push({
@@ -35,7 +38,10 @@ async function planPolicyPush(client, collections, options = {}) {
35
38
  state
36
39
  });
37
40
  }
38
- const rendersAsStored = unsure.length === 0 ? /* @__PURE__ */ new Map() : await probeRenderedPolicies(client, collections, unsure.map((entry) => entry.policy), { searchPath: options.searchPath });
41
+ const rendersAsStored = unsure.length === 0 ? /* @__PURE__ */ new Map() : await probeRenderedPolicies(client, collections, unsure.map((entry) => entry.policy), {
42
+ searchPath: options.searchPath,
43
+ adminRoleAvailable
44
+ });
39
45
  const unstamped = [];
40
46
  for (const { policy, state } of unsure) {
41
47
  const same = rendersAsStored.get(keyOf(policy));
@@ -124,4 +130,4 @@ async function underSearchPath(client, searchPath, read) {
124
130
  //#endregion
125
131
  export { formatPolicyPushPlan, planPolicyPush, summarizePolicyPushPlan, underSearchPath };
126
132
 
127
- //# sourceMappingURL=push-policy-plan-JcyK94bc.js.map
133
+ //# sourceMappingURL=push-policy-plan-BgcrroxQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"push-policy-plan-BgcrroxQ.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 collections\", 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 `lockCollectionTables` 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 { CollectionConfig } 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-collection-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 collection 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 collections: CollectionConfig[],\n options: { searchPath?: string; adminRoleAvailable?: AdminPoliciesExpectation } = {}\n): Promise<PolicyPushPlan> {\n const adminRoleAvailable = await resolveAdminPolicies(client, options.adminRoleAvailable);\n const drift = await checkPolicyDrift(client, collections, { adminRoleAvailable });\n const { dropped, kept } = partitionOrphans(drift, collections);\n const enableRls = await tablesRlsWouldEnable(client, collections);\n const stamps = await underSearchPath(client, options.searchPath, () => readPolicyStamps(client, collections, { 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(collections, 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, collections, 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 collection 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,aACA,UAAkF,CAAC,GAC5D;CACvB,MAAM,qBAAqB,MAAM,qBAAqB,QAAQ,QAAQ,kBAAkB;CACxF,MAAM,QAAQ,MAAM,iBAAiB,QAAQ,aAAa,EAAE,mBAAmB,CAAC;CAChF,MAAM,EAAE,SAAS,SAAS,iBAAiB,OAAO,WAAW;CAC7D,MAAM,YAAY,MAAM,qBAAqB,QAAQ,WAAW;CAChE,MAAM,SAAS,MAAM,gBAAgB,QAAQ,QAAQ,kBAAkB,iBAAiB,QAAQ,aAAa,EAAE,mBAAmB,CAAC,CAAC;CAEpI,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,aAAa,kBAAkB,GAAG;EACpE,IAAI,QAAQ,IAAI,MAAM,MAAM,CAAC,GAAG;EAChC,MAAM,QAAQ,OAAO,IAAI,GAAG,OAAO,OAAO,GAAG,OAAO,OAAO,CAAC,EAAE,IAAI,OAAO,IAAI;EAC7E,IAAI,UAAU,WAAW,UAAU,aAAa,OAAO,KAAK;GAAE;GAAQ;EAAM,CAAC;CACjF;CAGA,MAAM,kBAAkB,OAAO,WAAW,oBACpC,IAAI,IAAqB,IACzB,MAAM,sBAAsB,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AK;EACV,MAAM,OAAO,MAAM,UAAU,CAAC,CAAC,YAAY,KAAA,CAAS;EACpD,MAAM;CACV;AACJ"}
@@ -1,32 +1,3 @@
1
- /**
2
- * Which connection an authenticated read runs on: the primary, or a standby
3
- * (`DATABASE_READ_URL`).
4
- *
5
- * A standby serves a read as well as the primary does — the RLS context is
6
- * transaction-local (`applyAuthContext`), and `SET LOCAL ROLE` and
7
- * `set_config(…, true)` both work on a hot standby — but it serves what it
8
- * has replayed, which is a little behind. Two rules keep that from being
9
- * visible:
10
- *
11
- * - **Read-your-writes.** A principal that just wrote reads from the primary
12
- * for {@link ReadRoutingOptions.stickyMs} afterwards, so a save followed by
13
- * a list shows the save. In-process: another instance does not know about
14
- * the write, and the lag guard is what bounds what it can serve.
15
- * - **Lag guard.** The standby's replay lag is sampled every
16
- * {@link ReadRoutingOptions.sampleIntervalMs}; above
17
- * {@link ReadRoutingOptions.maxLagMs}, or with no recent sample, every read
18
- * goes to the primary. So does every read for a while after the standby
19
- * failed one (see {@link isReplicaFallbackError}), and the failed read is
20
- * retried on the primary.
21
- *
22
- * What never comes here is decided by the caller: writes, reads inside a
23
- * write's transaction, the service identity (crons, jobs, `dataAsAdmin`), and
24
- * everything on the base driver — auth, realtime, idempotency, the SQL
25
- * console, `rebase.sql`.
26
- *
27
- * @module
28
- */
29
- import type { Pool } from "pg";
30
1
  /** How reads are routed, from `REBASE_READ_STICKY_MS` / `REBASE_READ_MAX_LAG_MS`. */
31
2
  export interface ReadRoutingOptions {
32
3
  /** How long a principal reads from the primary after a write. Default 5000. */
@@ -87,7 +58,16 @@ export declare function isReplicaFallbackError(error: unknown, depth?: number):
87
58
  */
88
59
  export declare const REPLICA_LAG_SQL = "SELECT CASE\n WHEN NOT pg_is_in_recovery() THEN 0\n WHEN pg_last_wal_receive_lsn() IS NOT NULL AND pg_last_wal_receive_lsn() = pg_last_wal_replay_lsn() THEN 0\n ELSE EXTRACT(EPOCH FROM (now() - pg_last_xact_replay_timestamp())) * 1000\nEND AS lag_ms";
89
60
  /** Run {@link REPLICA_LAG_SQL} on `pool`, in milliseconds. */
90
- export declare function readReplicaLagMs(pool: Pick<Pool, "query">): Promise<number | null>;
61
+ /**
62
+ * What a probe asks of a pool: one statement, answered with its rows. A
63
+ * `pg.Pool` is one. The rows are read as they arrive, not as a declared shape.
64
+ */
65
+ export interface RowsQueryable {
66
+ query(text: string): Promise<{
67
+ rows: Record<string, unknown>[];
68
+ }>;
69
+ }
70
+ export declare function readReplicaLagMs(pool: RowsQueryable): Promise<number | null>;
91
71
  /**
92
72
  * The standby's routing state for one data source: recent writers, the last
93
73
  * lag sample, and whether the standby failed a read recently. One per source,
@@ -2,10 +2,13 @@ import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
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";
4
4
  import { n as VIEW_ROWS_COMMENT_PREFIX, r as viewRowsName } from "./view-names-Dscp6--B.js";
5
+ import { t as ADMIN_POLICY_ROLE_SQL } from "./rls-bootstrap-sql-kPX4-MB1.js";
5
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";
6
7
  import { o as atlasExcludePattern, u as collectionIndexStatements } from "./source-fZb92pN8.js";
7
- import { a as triggerStatements, r as quoteSqlLiteral } from "./plan-schema-BYxOzflz.js";
8
+ import { a as triggerStatements, r as quoteSqlLiteral } from "./plan-schema-vJd3UEmT.js";
9
+ import { REBASE_ADMIN_REQUEST_ROLE, REBASE_ADMIN_ROLE } from "@rebasepro/types";
8
10
  import { REBASE_USER_ROLE } from "@rebasepro/common";
11
+ import { adminRequestPolicyName } from "@rebasepro/utils";
9
12
  //#region src/schema/plan/render-ddl.ts
10
13
  /**
11
14
  * The SQL files, rendered from a {@link SchemaPlan}.
@@ -106,13 +109,30 @@ var renderPolicyStatements = (table, policy) => {
106
109
  let create = `CREATE POLICY "${policy.name}" ON ${target} AS ${policy.mode.toUpperCase()} FOR ${policy.operation.toUpperCase()} TO ${policy.roles.map((r) => `"${r}"`).join(", ")}`;
107
110
  if (policy.using) create += ` USING (${policy.using})`;
108
111
  if (policy.withCheck) create += ` WITH CHECK (${policy.withCheck})`;
112
+ const superseded = (policy.supersedes ?? []).map((name) => `DROP POLICY IF EXISTS "${name}" ON ${target};`);
113
+ const keepsCompanion = policy.adminRequestCompanion !== void 0 && policy.roles.includes(REBASE_ADMIN_ROLE);
114
+ const isCompanion = policy.roles.includes(REBASE_ADMIN_REQUEST_ROLE);
115
+ const companionName = adminRequestPolicyName(policy.name);
116
+ const companion = isCompanion ? [] : keepsCompanion ? [mismatchedCompanionDropSql(table, companionName, policy.operation)] : [`DROP POLICY IF EXISTS "${companionName}" ON ${target};`];
109
117
  return [
110
- ...(policy.supersedes ?? []).map((name) => `DROP POLICY IF EXISTS "${name}" ON ${target};`),
118
+ ...superseded,
119
+ ...companion,
111
120
  `DROP POLICY IF EXISTS "${policy.name}" ON ${target};`,
112
121
  `${create};`
113
122
  ];
114
123
  };
115
124
  /**
125
+ * Drop the companion `name` on the table unless it is exactly what a boot
126
+ * writes for a policy of this operation: permissive, `TO rebase_admin_request`
127
+ * alone, `FOR <operation>`, its clauses `true` or absent. One `DO` statement,
128
+ * so it runs on a handle that refuses several commands in one string.
129
+ */
130
+ function mismatchedCompanionDropSql(table, name, operation) {
131
+ const literal = (value) => `'${value.replace(/'/g, "''")}'`;
132
+ const ident = (value) => `"${value.replace(/"/g, "\"\"")}"`;
133
+ return `DO $rebase_companion$ BEGIN IF EXISTS (SELECT 1 FROM pg_policies p WHERE p.schemaname = ${literal(table.schema)} AND p.tablename = ${literal(table.table)} AND p.policyname = ${literal(name)} AND NOT (p.cmd = ${literal(operation.toUpperCase())} AND p.permissive = 'PERMISSIVE' AND p.roles = ARRAY[${literal(REBASE_ADMIN_REQUEST_ROLE)}]::name[] AND COALESCE(p.qual, 'true') = 'true' AND COALESCE(p.with_check, 'true') = 'true')) THEN EXECUTE ${literal(`DROP POLICY ${ident(name)} ON ${ident(table.schema)}.${ident(table.table)}`)}; END IF; END $rebase_companion$;`;
134
+ }
135
+ /**
116
136
  * A restrictive policy, under its own name, command and roles, that passes no
117
137
  * row: `USING (false)` / `WITH CHECK (false)` for the clauses its command takes.
118
138
  *
@@ -199,13 +219,24 @@ function renderPostgresDdl(plan, options = {}) {
199
219
  }
200
220
  if (policyStatements.length > 0) {
201
221
  ddl += "-- Row Level Security Policies\n";
222
+ ddl += adminRolePreamble(plan);
202
223
  ddl += policyStatements.join("");
203
224
  ddl += "\n";
204
225
  }
205
226
  return ddl;
206
227
  }
228
+ /**
229
+ * The statement that creates `rebase_admin`, when a policy in the plan is
230
+ * written `TO` it — so a file of policies is self-contained, as it is for the
231
+ * RLS helpers: CREATE POLICY refuses a role that does not exist. Empty when no
232
+ * policy names it (`rls.adminPolicies: "public"`).
233
+ */
234
+ function adminRolePreamble(plan) {
235
+ return plan.tables.some((table) => table.policies.some((policy) => policy.roles.includes(REBASE_ADMIN_ROLE))) ? `${ADMIN_POLICY_ROLE_SQL};\n\n` : "";
236
+ }
207
237
  function renderPoliciesDdl(plan) {
208
238
  let ddl = "-- This file contains RLS policies generated by Rebase. Applied separately from migrations.\n\n";
239
+ ddl += adminRolePreamble(plan);
209
240
  for (const table of plan.tables.filter((t) => t.kind === "collection")) {
210
241
  ddl += `${renderEnableRls(table)}\n`;
211
242
  ddl += "\n";
@@ -447,4 +478,4 @@ function renderViewsDdl(plan) {
447
478
  //#endregion
448
479
  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 };
449
480
 
450
- //# sourceMappingURL=render-ddl-DCdVP-pQ.js.map
481
+ //# sourceMappingURL=render-ddl-Ci3S_SoI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-ddl-Ci3S_SoI.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 { collectionIndexStatements } from \"../collection-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 }\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 if (column.generated) {\n return `${renderPgType(column.type)} GENERATED ALWAYS AS (${column.generated.expression}) STORED`;\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(...collectionIndexStatements(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 `securityRules` reads 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,OAAO;EACxB,KAAK,WAAW,OAAO;EACvB,KAAK,UAAU,OAAO;EACtB,KAAK,eAAe,OAAO;EAC3B,KAAK,UAAU,OAAO;EACtB,KAAK,aAAa,OAAO;EACzB,KAAK,QAAQ,OAAO;EACpB,KAAK,mBAAmB,OAAO;EAC/B,KAAK;GACD,IAAI,KAAK,cAAc,KAAA,GAAW,OAAO;GACzC,OAAO,KAAK,UAAU,KAAA,IAChB,WAAW,KAAK,UAAU,KAC1B,WAAW,KAAK,UAAU,IAAI,KAAK,MAAM;EACnD,KAAK,WAAW,OAAO;EACvB,KAAK,eAAe,OAAO;EAC3B,KAAK,QAAQ,OAAO;EACpB,KAAK,QAAQ,OAAO;EACpB,KAAK,QAAQ,OAAO;EACpB,KAAK,SA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,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-DwqFRIWz.js";
4
+ import { it as redactConnectionPasswords } from "./cli-errors-DYTxnLbW.js";
5
+ import { n as resolveRlsSettings } from "./rls-settings-BCGMIig3.js";
5
6
  import { a as outWarn, i as outError, r as out, t as chalk } from "./source-fZb92pN8.js";
6
- import { _ as closestWord, y as parseCommandFlags } from "./migrate-baseline-BfHmq3vN.js";
7
- import { n as resolveRlsSettings } from "./rls-settings-De5NoHHy.js";
7
+ import { _ as closestWord, y as parseCommandFlags } from "./migrate-baseline-CmWXL7qx.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-DwqFRIWz.js").then((n) => n.v);
167
- const { appRoleSetupInstructions, readRecordedRequestRoles } = await import("./rls-enforcement-BO618rnr.js").then((n) => n.v);
168
- const { cliRlsSettings } = await import("./rls-settings-De5NoHHy.js").then((n) => n.a);
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);
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-DwqFRIWz.js").then((n) => n.v);
199
- const { AppRoleSetupError, readRecordedRequestRoles } = await import("./rls-enforcement-BO618rnr.js").then((n) => n.v);
200
- const { migrateRequestRoles, planRequestRoleMigration } = await import("./request-role-migration-D9BZ5Uba.js");
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");
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-DSdRtvgH.js.map
260
+ //# sourceMappingURL=request-role-cli-Dy1EgJU9.js.map