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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (248) hide show
  1. package/README.md +11 -8
  2. package/dist/{BranchService-CrXvcES2.js → BranchService-USp1AvZB.js} +3 -3
  3. package/dist/{BranchService-CrXvcES2.js.map → BranchService-USp1AvZB.js.map} +1 -1
  4. package/dist/PostgresBackendDriver.d.ts +99 -54
  5. package/dist/PostgresBootstrapper.d.ts +12 -27
  6. package/dist/auth/ensure-tables.d.ts +16 -5
  7. package/dist/auth/schema-version.d.ts +2 -2
  8. package/dist/auth/services.d.ts +2 -3
  9. package/dist/{auth-users-columns-C72EMoDJ.js → auth-users-columns-BpfgbkxZ.js} +2 -16
  10. package/dist/auth-users-columns-BpfgbkxZ.js.map +1 -0
  11. package/dist/{backup-cli-CTKCOLpX.js → backup-cli-DbKyEj6c.js} +4 -4
  12. package/dist/{backup-cli-CTKCOLpX.js.map → backup-cli-DbKyEj6c.js.map} +1 -1
  13. package/dist/{boot-ddl-CqGIwSYx.js → boot-ddl-5H2bL_80.js} +2 -2
  14. package/dist/{boot-ddl-CqGIwSYx.js.map → boot-ddl-5H2bL_80.js.map} +1 -1
  15. package/dist/{cli-console-DBPw-oAz.js → cli-console-DsRgGSBR.js} +65 -39
  16. package/dist/cli-console-DsRgGSBR.js.map +1 -0
  17. package/dist/cli-console.d.ts +16 -13
  18. package/dist/cli-flags.d.ts +8 -9
  19. package/dist/cli-helpers.d.ts +15 -11
  20. package/dist/{cli-errors-DYTxnLbW.js → cli-schema-dir-CiN0ephV.js} +184 -70
  21. package/dist/cli-schema-dir-CiN0ephV.js.map +1 -0
  22. package/dist/cli-schema-dir.d.ts +64 -0
  23. package/dist/cli.js +192 -257
  24. package/dist/cli.js.map +1 -1
  25. package/dist/data-transformer.d.ts +50 -19
  26. package/dist/{database-preflight-iBpT7-vv.js → database-preflight-bfnIBnjM.js} +5 -5
  27. package/dist/database-preflight-bfnIBnjM.js.map +1 -0
  28. package/dist/{deferred-index-build-BCU9RoHK.js → deferred-index-build-CcSDA7wE.js} +69 -13
  29. package/dist/deferred-index-build-CcSDA7wE.js.map +1 -0
  30. package/dist/{ensure-collection-policies-Bo-_fDAy.js → ensure-policies-rRmXb5bt.js} +31 -31
  31. package/dist/ensure-policies-rRmXb5bt.js.map +1 -0
  32. package/dist/{ensure-collection-tables-DCJINkT_.js → ensure-tables-Bvm-F2wW.js} +44 -37
  33. package/dist/ensure-tables-Bvm-F2wW.js.map +1 -0
  34. package/dist/{ensure-tables-BPGaGh0y.js → ensure-tables-CC8p_AK3.js} +34 -29
  35. package/dist/ensure-tables-CC8p_AK3.js.map +1 -0
  36. package/dist/{enum-labels-kept-YAgOZS4I.js → enum-labels-kept-FlX9SHdf.js} +8 -8
  37. package/dist/enum-labels-kept-FlX9SHdf.js.map +1 -0
  38. package/dist/{generate-drizzle-schema-DcrFr7YX.js → generate-drizzle-schema-SJMXxzPI.js} +12 -12
  39. package/dist/generate-drizzle-schema-SJMXxzPI.js.map +1 -0
  40. package/dist/{generate-drizzle-schema-logic-LTLZvt6r.js → generate-drizzle-schema-logic-DL7R1rAF.js} +15 -8
  41. package/dist/generate-drizzle-schema-logic-DL7R1rAF.js.map +1 -0
  42. package/dist/{generate-files-CsaVzatS.js → generate-files-tlJ9_lGI.js} +23 -30
  43. package/dist/generate-files-tlJ9_lGI.js.map +1 -0
  44. package/dist/{generate-next-step-DgK5BlBn.js → generate-next-step-CO09dovd.js} +3 -3
  45. package/dist/generate-next-step-CO09dovd.js.map +1 -0
  46. package/dist/{generate-postgres-ddl-logic-Dg0bcENZ.js → generate-postgres-ddl-logic-B8huc03c.js} +51 -21
  47. package/dist/generate-postgres-ddl-logic-B8huc03c.js.map +1 -0
  48. package/dist/{generated-schema-diff-By4dxyTH.js → generated-schema-diff-DoT2dYDe.js} +297 -279
  49. package/dist/generated-schema-diff-DoT2dYDe.js.map +1 -0
  50. package/dist/{generated-schema-staleness-BvNF3i-s.js → generated-schema-staleness-YBVq2kTn.js} +21 -29
  51. package/dist/generated-schema-staleness-YBVq2kTn.js.map +1 -0
  52. package/dist/history/ensure-history-table.d.ts +22 -0
  53. package/dist/index.d.ts +8 -2
  54. package/dist/index.es.js +201 -25
  55. package/dist/index.es.js.map +1 -1
  56. package/dist/interfaces.d.ts +3 -4
  57. package/dist/{introspect-db-queries-DevUrzll.js → introspect-db-queries-BgiRQqtR.js} +7 -2
  58. package/dist/introspect-db-queries-BgiRQqtR.js.map +1 -0
  59. package/dist/introspect-tables-Cw_A-kk4.js +2086 -0
  60. package/dist/introspect-tables-Cw_A-kk4.js.map +1 -0
  61. package/dist/load-tables-B1Re74ng.js +92 -0
  62. package/dist/load-tables-B1Re74ng.js.map +1 -0
  63. package/dist/{migrate-baseline-CmWXL7qx.js → migrate-baseline-DZmekgpD.js} +19 -32
  64. package/dist/migrate-baseline-DZmekgpD.js.map +1 -0
  65. package/dist/{migrate-policy-stamps-BN_Qad6c.js → migrate-policy-stamps-B_acrUQB.js} +18 -19
  66. package/dist/migrate-policy-stamps-B_acrUQB.js.map +1 -0
  67. package/dist/model/PostgresTableRegistry.d.ts +159 -0
  68. package/dist/model/build-registry.d.ts +25 -0
  69. package/dist/model/refresh-relational-schema.d.ts +24 -0
  70. package/dist/model/runtime-table.d.ts +53 -0
  71. package/dist/{collections → model}/validate-relations.d.ts +15 -21
  72. package/dist/{open-rebase-40paQfVW.js → open-rebase-4kisUF_k.js} +3946 -3870
  73. package/dist/open-rebase-4kisUF_k.js.map +1 -0
  74. package/dist/open-rebase.d.ts +16 -15
  75. package/dist/{pg-error-utils-DJHjCF7-.js → pg-error-utils-BT5NzGFZ.js} +17 -20
  76. package/dist/pg-error-utils-BT5NzGFZ.js.map +1 -0
  77. package/dist/plan-schema-Hbtjhge3.js +1633 -0
  78. package/dist/plan-schema-Hbtjhge3.js.map +1 -0
  79. package/dist/{policy-drift-C-m0uWHH.js → policy-drift-BVMyqHSa.js} +29 -29
  80. package/dist/policy-drift-BVMyqHSa.js.map +1 -0
  81. package/dist/{push-index-adoption-Cp7oZxSl.js → push-index-adoption-hpHTyXMR.js} +7 -7
  82. package/dist/push-index-adoption-hpHTyXMR.js.map +1 -0
  83. package/dist/{push-index-prebuild-DbwKGtQT.js → push-index-prebuild-Bty9F7bD.js} +6 -6
  84. package/dist/push-index-prebuild-Bty9F7bD.js.map +1 -0
  85. package/dist/{push-kept-defaults-CLcgsEPt.js → push-kept-defaults-Bst4MDup.js} +13 -16
  86. package/dist/push-kept-defaults-Bst4MDup.js.map +1 -0
  87. package/dist/{push-legacy-renames-BthD0E9W.js → push-legacy-renames-bB4bM6br.js} +6 -6
  88. package/dist/push-legacy-renames-bB4bM6br.js.map +1 -0
  89. package/dist/{push-policy-plan-BgcrroxQ.js → push-policy-plan-BI8U4BOD.js} +11 -11
  90. package/dist/push-policy-plan-BI8U4BOD.js.map +1 -0
  91. package/dist/{render-ddl-Ci3S_SoI.js → render-ddl-D4n86NHz.js} +14 -7
  92. package/dist/render-ddl-D4n86NHz.js.map +1 -0
  93. package/dist/{request-role-cli-Dy1EgJU9.js → request-role-cli-BdRzdE87.js} +11 -11
  94. package/dist/{request-role-cli-Dy1EgJU9.js.map → request-role-cli-BdRzdE87.js.map} +1 -1
  95. package/dist/{request-role-migration-GHTJnPMV.js → request-role-migration-C8aq_TO3.js} +2 -2
  96. package/dist/{request-role-migration-GHTJnPMV.js.map → request-role-migration-C8aq_TO3.js.map} +1 -1
  97. package/dist/{rls-enforcement-Cc_UhOxb.js → rls-enforcement-DB5HHj96.js} +19 -19
  98. package/dist/rls-enforcement-DB5HHj96.js.map +1 -0
  99. package/dist/{rls-settings-BCGMIig3.js → rls-settings-CmGK2U0a.js} +2 -2
  100. package/dist/rls-settings-CmGK2U0a.js.map +1 -0
  101. package/dist/schema/auth-users-columns.d.ts +1 -11
  102. package/dist/schema/catalogue-schema.d.ts +33 -29
  103. package/dist/schema/classify-change.d.ts +23 -16
  104. package/dist/schema/column-type-drift.d.ts +16 -0
  105. package/dist/schema/config-relations.d.ts +10 -9
  106. package/dist/schema/deferred-index-build.d.ts +1 -1
  107. package/dist/schema/doctor-cli.js +1544 -66
  108. package/dist/schema/doctor-cli.js.map +1 -1
  109. package/dist/schema/doctor-database.d.ts +7 -7
  110. package/dist/schema/doctor-policy-checks.d.ts +4 -4
  111. package/dist/schema/doctor-search-scale.d.ts +14 -14
  112. package/dist/schema/doctor.d.ts +27 -27
  113. package/dist/schema/dynamic-tables.d.ts +6 -5
  114. package/dist/schema/{ensure-collection-policies.d.ts → ensure-policies.d.ts} +20 -20
  115. package/dist/schema/{ensure-collection-tables.d.ts → ensure-tables.d.ts} +11 -11
  116. package/dist/schema/enum-labels-kept.d.ts +6 -6
  117. package/dist/schema/generate-drizzle-schema-logic.d.ts +3 -3
  118. package/dist/schema/generate-drizzle-schema.js +1 -1
  119. package/dist/schema/generate-files.d.ts +6 -6
  120. package/dist/schema/generate-postgres-ddl-logic.d.ts +23 -20
  121. package/dist/schema/generate-postgres-ddl.js +11 -11
  122. package/dist/schema/generate-postgres-ddl.js.map +1 -1
  123. package/dist/schema/generate-schema-commit.d.ts +13 -8
  124. package/dist/schema/generated-schema-diff.d.ts +16 -16
  125. package/dist/schema/generated-schema-staleness.d.ts +11 -11
  126. package/dist/schema/index-adoption.d.ts +4 -4
  127. package/dist/schema/introspect-db-customization.d.ts +47 -0
  128. package/dist/schema/introspect-db-inference.d.ts +30 -9
  129. package/dist/schema/introspect-db-logic.d.ts +79 -110
  130. package/dist/schema/introspect-db-project.d.ts +15 -18
  131. package/dist/schema/introspect-db-queries.d.ts +1 -1
  132. package/dist/schema/introspect-db-search.d.ts +25 -4
  133. package/dist/schema/introspect-db-storage.d.ts +4 -74
  134. package/dist/schema/introspect-db.js +102 -90
  135. package/dist/schema/introspect-db.js.map +1 -1
  136. package/dist/schema/introspect-runtime.d.ts +47 -36
  137. package/dist/schema/introspect-tables.d.ts +182 -0
  138. package/dist/schema/load-tables.d.ts +55 -0
  139. package/dist/schema/migrate-policy-stamps.d.ts +4 -4
  140. package/dist/schema/migration-freshness.d.ts +13 -13
  141. package/dist/schema/plan/column-order.d.ts +82 -0
  142. package/dist/schema/plan/diff-plan.d.ts +9 -3
  143. package/dist/schema/plan/plan-schema.d.ts +55 -52
  144. package/dist/schema/plan/render-drizzle.d.ts +1 -1
  145. package/dist/schema/plan/types.d.ts +24 -15
  146. package/dist/schema/push-index-adoption.d.ts +3 -3
  147. package/dist/schema/push-index-prebuild.d.ts +3 -3
  148. package/dist/schema/push-kept-defaults.d.ts +7 -7
  149. package/dist/schema/push-legacy-renames.d.ts +3 -3
  150. package/dist/schema/push-policy-plan.d.ts +5 -5
  151. package/dist/schema/reconcile-schema.d.ts +5 -5
  152. package/dist/schema/relation-names.d.ts +15 -20
  153. package/dist/schema/render-outputs.d.ts +76 -0
  154. package/dist/schema/search-column.d.ts +11 -43
  155. package/dist/schema/{collection-index.d.ts → table-index.d.ts} +21 -42
  156. package/dist/schema/{collections-schema-version.d.ts → tables-schema-version.d.ts} +8 -2
  157. package/dist/schema/vector-index.d.ts +24 -28
  158. package/dist/{search-column-BM-GV6vH.js → search-column-BO-WND-B.js} +86 -149
  159. package/dist/search-column-BO-WND-B.js.map +1 -0
  160. package/dist/security/caller-sql-columns.d.ts +9 -6
  161. package/dist/security/policy-drift.d.ts +14 -14
  162. package/dist/security/rls-enforcement.d.ts +19 -25
  163. package/dist/security/rls-settings.d.ts +2 -2
  164. package/dist/security/served-table-protection.d.ts +125 -0
  165. package/dist/services/FetchService.d.ts +22 -133
  166. package/dist/services/PersistService.d.ts +6 -17
  167. package/dist/services/RelationService.d.ts +57 -106
  168. package/dist/services/RelationWriteService.d.ts +59 -66
  169. package/dist/services/cdc/identity-columns.d.ts +7 -5
  170. package/dist/services/cdc/junction-tables.d.ts +14 -14
  171. package/dist/services/collection-helpers.d.ts +52 -95
  172. package/dist/services/dataService.d.ts +15 -12
  173. package/dist/services/field-op-sql.d.ts +11 -9
  174. package/dist/services/field-viewer.d.ts +12 -11
  175. package/dist/services/hidden-columns.d.ts +30 -0
  176. package/dist/services/index.d.ts +1 -1
  177. package/dist/services/junction-writes.d.ts +37 -18
  178. package/dist/services/nested-path.d.ts +18 -18
  179. package/dist/services/read-field-access.d.ts +23 -7
  180. package/dist/services/read-scope.d.ts +10 -9
  181. package/dist/services/realtimeService.d.ts +25 -10
  182. package/dist/services/relation-tables.d.ts +97 -0
  183. package/dist/services/row-pipeline.d.ts +50 -69
  184. package/dist/services/soft-delete.d.ts +25 -24
  185. package/dist/services/table-hooks.d.ts +146 -0
  186. package/dist/services/view-access.d.ts +7 -7
  187. package/dist/services/write-transaction-scope.d.ts +1 -1
  188. package/dist/{source-fZb92pN8.js → source-VxbrQojV.js} +111 -79
  189. package/dist/source-VxbrQojV.js.map +1 -0
  190. package/dist/{collections-schema-version-D7bDI0PJ.js → tables-schema-version-YvZIBlOP.js} +12 -6
  191. package/dist/tables-schema-version-YvZIBlOP.js.map +1 -0
  192. package/dist/utils/drizzle-conditions.d.ts +70 -84
  193. package/dist/utils/pg-array-null-patch.d.ts +27 -10
  194. package/dist/utils/pg-error-utils.d.ts +4 -4
  195. package/dist/{vector-index-DsQ3V2d2.js → vector-index-VSh3ufTd.js} +62 -54
  196. package/dist/vector-index-VSh3ufTd.js.map +1 -0
  197. package/dist/{websocket-B7ex6AQM.js → websocket-BevXvwfo.js} +51 -40
  198. package/dist/websocket-BevXvwfo.js.map +1 -0
  199. package/dist/websocket.d.ts +2 -2
  200. package/package.json +7 -7
  201. package/dist/auth-users-columns-C72EMoDJ.js.map +0 -1
  202. package/dist/cli-collections-path.d.ts +0 -31
  203. package/dist/cli-console-DBPw-oAz.js.map +0 -1
  204. package/dist/cli-errors-DYTxnLbW.js.map +0 -1
  205. package/dist/collections/PostgresCollectionRegistry.d.ts +0 -47
  206. package/dist/collections/buildRegistry.d.ts +0 -27
  207. package/dist/collections-schema-version-D7bDI0PJ.js.map +0 -1
  208. package/dist/column-plan-helpers-BeSztMor.js +0 -161
  209. package/dist/column-plan-helpers-BeSztMor.js.map +0 -1
  210. package/dist/database-preflight-iBpT7-vv.js.map +0 -1
  211. package/dist/deferred-index-build-BCU9RoHK.js.map +0 -1
  212. package/dist/doctor-Kg1oUK0Q.js +0 -1458
  213. package/dist/doctor-Kg1oUK0Q.js.map +0 -1
  214. package/dist/ensure-collection-policies-Bo-_fDAy.js.map +0 -1
  215. package/dist/ensure-collection-tables-DCJINkT_.js.map +0 -1
  216. package/dist/ensure-tables-BPGaGh0y.js.map +0 -1
  217. package/dist/enum-labels-kept-YAgOZS4I.js.map +0 -1
  218. package/dist/generate-drizzle-schema-DcrFr7YX.js.map +0 -1
  219. package/dist/generate-drizzle-schema-logic-LTLZvt6r.js.map +0 -1
  220. package/dist/generate-files-CsaVzatS.js.map +0 -1
  221. package/dist/generate-next-step-DgK5BlBn.js.map +0 -1
  222. package/dist/generate-postgres-ddl-logic-Dg0bcENZ.js.map +0 -1
  223. package/dist/generated-schema-diff-By4dxyTH.js.map +0 -1
  224. package/dist/generated-schema-staleness-BvNF3i-s.js.map +0 -1
  225. package/dist/introspect-db-logic-DWqAEURB.js +0 -2047
  226. package/dist/introspect-db-logic-DWqAEURB.js.map +0 -1
  227. package/dist/introspect-db-queries-DevUrzll.js.map +0 -1
  228. package/dist/migrate-baseline-CmWXL7qx.js.map +0 -1
  229. package/dist/migrate-policy-stamps-BN_Qad6c.js.map +0 -1
  230. package/dist/open-rebase-40paQfVW.js.map +0 -1
  231. package/dist/pg-error-utils-DJHjCF7-.js.map +0 -1
  232. package/dist/plan-schema-vJd3UEmT.js +0 -1604
  233. package/dist/plan-schema-vJd3UEmT.js.map +0 -1
  234. package/dist/policy-drift-C-m0uWHH.js.map +0 -1
  235. package/dist/push-index-adoption-Cp7oZxSl.js.map +0 -1
  236. package/dist/push-index-prebuild-DbwKGtQT.js.map +0 -1
  237. package/dist/push-kept-defaults-CLcgsEPt.js.map +0 -1
  238. package/dist/push-legacy-renames-BthD0E9W.js.map +0 -1
  239. package/dist/push-policy-plan-BgcrroxQ.js.map +0 -1
  240. package/dist/render-ddl-Ci3S_SoI.js.map +0 -1
  241. package/dist/rls-enforcement-Cc_UhOxb.js.map +0 -1
  242. package/dist/rls-settings-BCGMIig3.js.map +0 -1
  243. package/dist/schema/column-plan-helpers.d.ts +0 -161
  244. package/dist/schema/introspect-db-naming.d.ts +0 -10
  245. package/dist/search-column-BM-GV6vH.js.map +0 -1
  246. package/dist/source-fZb92pN8.js.map +0 -1
  247. package/dist/vector-index-DsQ3V2d2.js.map +0 -1
  248. package/dist/websocket-B7ex6AQM.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plan-schema-Hbtjhge3.js","names":[],"sources":["../src/schema/relation-names.ts","../src/schema/plan/tenant-keep-trigger.ts","../src/schema/plan/updated-at-trigger.ts","../src/schema/plan/column-order.ts","../src/schema/plan/plan-schema.ts"],"sourcesContent":["import type { RelationDescriptor, TableDescriptor } from \"@rebasepro/types\";\nimport { keyForColumn } from \"@rebasepro/common\";\nimport { toWireKey } from \"@rebasepro/utils\";\n\n/**\n * The key a SQL column is served under on a table: its column's key, or — for\n * a column the table does not describe — the camelCase of its name, which is\n * the key a foreign key derived from it would get.\n */\nexport const servedKeyOf = (descriptor: TableDescriptor, sqlColumn: string): string =>\n keyForColumn(descriptor, sqlColumn) ?? toWireKey(sqlColumn);\n\n/**\n * The `relationName` both sides of a link must agree on.\n *\n * Drizzle pairs an owning `one()` with its inverse `many()` by this string and\n * by nothing else, and the two sides are computed by different callers holding\n * different tables — so the rule has to be derivable from either end. It is:\n * name the link after the table that carries the foreign key and the key that\n * column is served under (the key, not the column: the Drizzle object is keyed\n * by the wire name, {@link servedKeyOf}).\n *\n * owning (belongsTo) → `{thisTable}_{key(localKey)}`\n * inverse (hasMany/hasOne) → `{targetTable}_{key(foreignKey)}`\n *\n * A many-to-many and a `via` chain keep the relation's own name.\n */\nexport function tableRelationName(\n relation: RelationDescriptor,\n source: TableDescriptor,\n targetOf: (slug: string) => TableDescriptor\n): string {\n if (relation.kind === \"belongsTo\") return `${source.table}_${servedKeyOf(source, relation.localKey)}`;\n if (relation.kind === \"hasMany\" || relation.kind === \"hasOne\") {\n const target = targetOf(relation.target);\n return `${target.table}_${servedKeyOf(target, relation.foreignKey)}`;\n }\n return relation.name;\n}\n","/**\n * `tenant`'s immutability, as a database trigger.\n *\n * The driver refuses an update that moves a row to another tenant\n * (`TENANT_IMMUTABLE`, see `resolveTenantWrite` in `@rebasepro/common`), and\n * the restrictive tenant policy cannot: a policy sees the new row or the old\n * one, never both, so a caller who belongs to two tenants passes it while\n * moving a row from one to the other. Every writer that is not the driver —\n * SQL run as the caller (`DataDriver.sql`) above all — met only the policy.\n *\n * So a `BEFORE UPDATE` trigger compares the two. It applies to whoever the\n * table's policies bind (`row_security_active`), which is every request role\n * whatever `rls.requestRole` names it: the owner connection (migrations, the\n * auth flows, a person in `psql`) keeps moving rows when it means to, as it\n * always could, and so does a caller holding one of the collection's\n * `bypassRoles` — the same exemption the driver makes.\n *\n * One function for every table, the column and the bypass roles arriving as\n * trigger arguments, like `set_updated_at`. The arguments are compared with\n * the catalogue's on boot (see `diffPlanAgainstCatalogue`), so a changed\n * `bypassRoles` re-creates the binding rather than leaving the old list in\n * force.\n */\nimport { REBASE_SCHEMA } from \"@rebasepro/types\";\nimport type { TriggerPlan } from \"./types\";\n\n/** The one trigger function, qualified. A frozen derived name. */\nexport const KEEP_TENANT_FN = `${REBASE_SCHEMA}.keep_tenant`;\n\n/** The trigger's name on `table`. A frozen derived name. */\nexport const keepTenantTriggerName = (table: string): string => `${table}_keep_tenant`;\n\nexport const keepTenantFunction = (): string =>\n `CREATE OR REPLACE FUNCTION ${KEEP_TENANT_FN}() RETURNS trigger\\n` +\n \"LANGUAGE plpgsql AS $$\\n\" +\n \"BEGIN\\n\" +\n // Nested rather than one AND, which Postgres may evaluate in any order;\n // and the roles read from the setting itself, as `rebase.roles()` does,\n // so the owner's updates never depend on that function existing yet.\n \" IF row_security_active(TG_RELID) THEN\\n\" +\n \" IF to_jsonb(OLD) -> TG_ARGV[0] IS DISTINCT FROM to_jsonb(NEW) -> TG_ARGV[0] THEN\\n\" +\n \" IF NOT (string_to_array(COALESCE(current_setting('app.user_roles', true), ''), ',') && TG_ARGV[1:TG_NARGS - 1]) THEN\\n\" +\n \" RAISE EXCEPTION 'TENANT_IMMUTABLE: an update cannot move a row of \\\"%\\\" to another tenant (column \\\"%\\\")', TG_TABLE_NAME, TG_ARGV[0]\\n\" +\n \" USING ERRCODE = '42501',\\n\" +\n \" HINT = 'Move it as a role listed in the collection''s tenant.bypassRoles.';\\n\" +\n \" END IF;\\n\" +\n \" END IF;\\n\" +\n \" END IF;\\n\" +\n \" RETURN NEW;\\n\" +\n \"END;\\n\" +\n \"$$;\";\n\n/** The arguments the binding passes: the column, then each bypass role. */\nexport const keepTenantArguments = (plan: TriggerPlan): string[] => [plan.column, ...(plan.bypassRoles ?? [])];\n\nconst literal = (value: string): string => `'${value.replace(/'/g, \"''\")}'`;\n\nexport const createKeepTenantStatement = (plan: TriggerPlan): string =>\n `CREATE TRIGGER \"${plan.name}\" BEFORE UPDATE ON \"${plan.schema}\".\"${plan.table}\" ` +\n `FOR EACH ROW EXECUTE FUNCTION ${KEEP_TENANT_FN}(${keepTenantArguments(plan).map(literal).join(\", \")});`;\n","/**\n * `autoValue: \"on_update\"`, as a database trigger.\n *\n * ## Why a trigger and not only the driver\n *\n * The driver stamps `updated_at` on every write it makes, and it has to keep\n * doing so: a `beforeSave` hook reads the row it is about to persist, and a\n * value that only appears once Postgres has written it is a value the hook\n * cannot see.\n *\n * But the driver is not the only writer. A seed script, a migration backfill, a\n * `psql` session, an admin fixing one row by hand — every one of those leaves\n * `updated_at` at whatever it was, and the column then says the row has not\n * changed since a date that is simply wrong. Anything reading it to decide what\n * to re-index, re-sync or re-send skips the row. The declaration says \"this\n * column tracks the last write\"; only the database can make that true.\n *\n * So both: the app stamps so hooks see the value, and a `BEFORE UPDATE` trigger\n * stamps so every other writer does too. They agree because they both mean\n * \"now\" — the trigger's `now()` is the transaction's start time, which is the\n * same instant the driver's own timestamp is written under.\n *\n * ## Why it is carved out of Atlas\n *\n * Atlas's free tier refuses to *parse* a desired-state file containing a\n * function (\"functions and procedures are available to logged-in users only\"),\n * and a trigger is a function plus a binding. This is the same arrangement the\n * search helpers already have: excluded from Atlas's view by pattern, written\n * to a file Rebase applies itself, applied at boot by the schema ensure, and\n * appended to migrations by the CLI so a replay is complete.\n *\n * ## Why one function for every column\n *\n * The column name arrives as a trigger argument (`TG_ARGV[0]`), so a project\n * with forty `updated_at` columns installs one function and forty bindings\n * rather than forty near-identical functions. `jsonb_populate_record(NEW, …)`\n * is the documented way to set a field of a row whose type is not known until\n * run time; it takes `NEW` as the row template, so the value is cast back to\n * whatever the column actually is — a `timestamptz`, or a `date` if that is\n * what the property declared.\n */\nimport { REBASE_SCHEMA } from \"@rebasepro/types\";\nimport type { TriggerPlan } from \"./types\";\nimport { createKeepTenantStatement } from \"./tenant-keep-trigger\";\n\n/** The one trigger function, qualified. A frozen derived name. */\nexport const SET_UPDATED_AT_FN = `${REBASE_SCHEMA}.set_updated_at`;\n\n/**\n * `CREATE OR REPLACE FUNCTION`, so replaying it against a database that already\n * has it is a no-op — this is emitted into a file that runs on every push and\n * is appended to migrations that run against databases at any stage of life.\n */\nexport const setUpdatedAtFunction = (): string =>\n `CREATE OR REPLACE FUNCTION ${SET_UPDATED_AT_FN}() RETURNS trigger\\n` +\n \"LANGUAGE plpgsql AS $$\\n\" +\n \"BEGIN\\n\" +\n \" NEW := jsonb_populate_record(NEW, jsonb_build_object(TG_ARGV[0], now()));\\n\" +\n \" RETURN NEW;\\n\" +\n \"END;\\n\" +\n \"$$;\";\n\n/**\n * `DROP TRIGGER IF EXISTS` before the `CREATE`.\n *\n * `CREATE OR REPLACE TRIGGER` exists only on Postgres 14+, and this runs\n * against whatever a self-hosted project points at. Two statements rather than\n * one is also what the boot-time applier needs: it issues DDL one statement at\n * a time over the extended query protocol, which forbids multiple commands in\n * one execute.\n */\nexport const dropTriggerStatement = (plan: TriggerPlan): string =>\n `DROP TRIGGER IF EXISTS \"${plan.name}\" ON \"${plan.schema}\".\"${plan.table}\";`;\n\nexport const createTriggerStatement = (plan: TriggerPlan): string =>\n `CREATE TRIGGER \"${plan.name}\" BEFORE UPDATE ON \"${plan.schema}\".\"${plan.table}\" ` +\n `FOR EACH ROW EXECUTE FUNCTION ${SET_UPDATED_AT_FN}('${plan.column.replace(/'/g, \"''\")}');`;\n\n/** Both statements, in the order they must run — for either kind of trigger. */\nexport const triggerStatements = (plan: TriggerPlan): string[] =>\n [dropTriggerStatement(plan), plan.kind === \"keep-tenant\" ? createKeepTenantStatement(plan) : createTriggerStatement(plan)];\n","/**\n * The order a table's columns are planned in, read from its descriptor.\n *\n * `TableDescriptor.columns` lists the declared columns in physical order and\n * then the foreign keys the `belongsTo` relations derive. The plan's order —\n * which `schema.sql`, `schema.generated.ts` and every golden are written in —\n * predates the table model, and it places a link where the legacy collection\n * shape listed its relation property:\n *\n * - a declared column a `belongsTo` binds that is **nothing but the foreign\n * key** (its key is the camelCase of the column, its type the target key's,\n * no rule of its own, the constraint kept) is planned *as the link*, at the\n * column's position — {@link isPlainForeignKey};\n * - any other bound column is planned as a column of its own at its position,\n * and its link adds a constraint-only entry (`columnOwnedByProperty`);\n * - those constraint-only entries and the derived foreign keys are placed in\n * relation order among the links: right after the link planned before them in\n * that order, else just before the one after them, else after the declared\n * columns;\n * - an `id` that is exactly the planner's implicit key (`id TEXT PRIMARY KEY\n * DEFAULT gen_random_uuid()::text`, declared first) is left out: the planner\n * adds it back as the implicit key, first in SQL and last in the Drizzle file.\n *\n * Every fact this reads is the descriptor's, and the target's key type is the\n * target descriptor's.\n */\nimport type { ColumnDescriptor, ColumnType, TableDescriptor } from \"@rebasepro/types\";\nimport type { RelationOfKind } from \"@rebasepro/common\";\nimport { toSnakeCase, toWireKey } from \"@rebasepro/utils\";\n\n/** A `belongsTo` relation descriptor. */\nexport type BelongsToDescriptor = RelationOfKind<\"belongsTo\">;\n\n/**\n * One entry of a table's planned columns, in order.\n *\n * - `column`: a column planned from its descriptor;\n * - `link` / `absorbed`: a bound column that is nothing but the foreign key,\n * planned as the link at the column's position;\n * - `link` / `constraint`: the constraint of a link whose bound column is\n * planned on its own (the entry renderers skip as a column);\n * - `link` / `derived`: a foreign-key column the relation derives.\n */\nexport type PlannedColumnEntry =\n | { kind: \"column\"; column: ColumnDescriptor }\n | { kind: \"link\"; form: \"absorbed\" | \"constraint\" | \"derived\"; relation: BelongsToDescriptor; column: ColumnDescriptor };\n\n/** The implicit key's DEFAULT: a uuid, as text. */\nexport const IMPLICIT_ID_DEFAULT = \"gen_random_uuid()::text\";\n\n/** The type a column pointing at this key must have: a serial read as its plain integer. */\nexport const referencingColumnType = (type: ColumnType): ColumnType => {\n switch (type.kind) {\n case \"smallserial\": return { kind: \"smallint\" };\n case \"serial\": return { kind: \"integer\" };\n case \"bigserial\": return { kind: \"bigint\" };\n default: return type;\n }\n};\n\n/**\n * The type of the target's key a link points at, as a column pointing at it\n * holds it; `text` for a target with no key, `undefined` for a composite key.\n */\nexport const targetKeyColumnType = (target: TableDescriptor): ColumnType | undefined => {\n const keys = target.columns.filter(column => column.primaryKey === true);\n if (keys.length === 0) return { kind: \"text\" };\n if (keys.length > 1) return undefined;\n return referencingColumnType(keys[0].type);\n};\n\n/**\n * Whether the table's first column is exactly the key the planner gives a\n * table that declares none, which it adds back itself.\n */\nexport function isImplicitIdColumn(descriptor: TableDescriptor): boolean {\n const first = descriptor.columns[0];\n if (!first || descriptor.primaryKey.length !== 1 || descriptor.primaryKey[0] !== first.key || first.key !== \"id\") return false;\n if (first.column !== \"id\" || first.type.kind !== \"text\" || first.derived) return false;\n if (first.default?.kind !== \"sql\" || first.default.expression !== IMPLICIT_ID_DEFAULT) return false;\n return !first.unique && !first.readOnly && !first.private && first.access === undefined && first.stamp === undefined\n && first.validate === undefined && first.oneOf === undefined && first.description === undefined\n && first.storage === undefined && first.generated === undefined && first.transforms === undefined;\n}\n\n/**\n * Whether a `belongsTo` was written `constraint: false`. The descriptor also\n * records `constraint: false` for a link into a view or out of one, where\n * Postgres refuses a foreign key — that link was not written without one.\n */\nexport const writtenWithoutConstraint = (\n descriptor: TableDescriptor,\n relation: BelongsToDescriptor,\n target: TableDescriptor\n): boolean => !relation.constraint && descriptor.kind === \"table\" && target.kind === \"table\";\n\n/**\n * Whether the column a `belongsTo` binds is nothing but the foreign key the\n * relation would have derived: served under the camelCase of its SQL name (and\n * no relation is named after that column), typed as the target's key, with no\n * rule of its own, and the relation keeps its constraint. Such a column is\n * planned once, as the link.\n */\nexport function isPlainForeignKey(\n descriptor: TableDescriptor,\n column: ColumnDescriptor,\n relation: BelongsToDescriptor,\n target: TableDescriptor\n): boolean {\n if (writtenWithoutConstraint(descriptor, relation, target)) return false;\n const localKey = column.column;\n for (const other of descriptor.relations) {\n if (other.name === localKey || toSnakeCase(other.name) === localKey) return false;\n }\n if (toWireKey(localKey) !== column.key) return false;\n if (column.primaryKey || column.default !== undefined || column.generated !== undefined || column.readOnly || column.private) return false;\n if (column.access !== undefined || column.stamp !== undefined || column.validate !== undefined || column.oneOf !== undefined) return false;\n if (column.description !== undefined || column.storage !== undefined || column.semantic !== undefined) return false;\n if (column.vectorIndex !== undefined || column.json !== undefined || column.element !== undefined || column.transforms !== undefined) return false;\n const targetType = targetKeyColumnType(target);\n if (targetType === undefined || targetType.kind === \"enum\" || column.type.kind === \"enum\") return false;\n return JSON.stringify(column.type) === JSON.stringify(targetType);\n}\n\n/**\n * A table's planned column entries, in the plan's order (see the module\n * comment). `targetOf` answers a relation target's descriptor by slug.\n */\nexport function plannedColumnEntries(\n descriptor: TableDescriptor,\n targetOf: (slug: string) => TableDescriptor\n): PlannedColumnEntry[] {\n const relationIndex = new Map(descriptor.relations.map((relation, index) => [relation.name, index]));\n const ordered: { entry: PlannedColumnEntry; relation?: number }[] = [];\n const absorbed = new Set<string>();\n const implicitId = isImplicitIdColumn(descriptor);\n\n descriptor.columns.forEach((column, position) => {\n if (column.derived) return;\n if (position === 0 && implicitId) return;\n const relation = column.foreignKeyOf === undefined ? undefined : belongsToNamed(descriptor, column.foreignKeyOf);\n if (relation && isPlainForeignKey(descriptor, column, relation, targetOf(relation.target))) {\n ordered.push({ entry: { kind: \"link\", form: \"absorbed\", relation, column }, relation: relationIndex.get(relation.name) });\n absorbed.add(relation.name);\n return;\n }\n ordered.push({ entry: { kind: \"column\", column } });\n });\n\n descriptor.relations.forEach((relation, index) => {\n if (relation.kind !== \"belongsTo\" || absorbed.has(relation.name)) return;\n const column = descriptor.columns.find(candidate => candidate.foreignKeyOf === relation.name);\n if (!column) {\n throw new Error(`Internal: the relation \"${relation.name}\" of table \"${descriptor.slug}\" has no foreign-key column in its descriptor.`);\n }\n const item = { entry: { kind: \"link\" as const, form: column.derived ? \"derived\" as const : \"constraint\" as const, relation, column }, relation: index };\n let after = -1;\n for (let position = ordered.length - 1; position >= 0; position--) {\n const other = ordered[position].relation;\n if (other !== undefined && other < index) {\n after = position;\n break;\n }\n }\n const before = ordered.findIndex(other => other.relation !== undefined && other.relation > index);\n if (after !== -1) ordered.splice(after + 1, 0, item);\n else if (before !== -1) ordered.splice(before, 0, item);\n else ordered.push(item);\n });\n\n return ordered.map(item => item.entry);\n}\n\nconst belongsToNamed = (descriptor: TableDescriptor, name: string): BelongsToDescriptor | undefined => {\n const relation = descriptor.relations.find(candidate => candidate.name === name);\n return relation?.kind === \"belongsTo\" ? relation : undefined;\n};\n","/**\n * The only place a table is read for schema purposes.\n *\n * Everything that used to `switch (prop.type)` — the Drizzle generator, the DDL\n * generator, the boot-time ensure — now renders the {@link SchemaPlan} this\n * produces. See `./types.ts` for why.\n *\n * Pure and synchronous. It reads compiled tables — their descriptors — and\n * nothing else: no database, no filesystem, no process-wide registry. The one\n * fact about the world it needs (which extensions a project's databases gave\n * Rebase leave to install) is passed in, because a plan that depended on\n * whatever module happened to be imported would not be comparable with itself.\n *\n * It **throws** rather than guessing. A configuration no renderer can honour —\n * an empty enum, a foreign key into a composite key, an array of documents, a\n * custom type name that leaves its statement — used to fail differently in\n * each of the three emitters, or not at all, and the failure landed at\n * `CREATE TABLE` time on a managed tenant with nobody in the loop. Here it\n * lands once, with the table and the column named.\n */\nimport {\n REBASE_SCHEMA,\n type SecurityRule,\n type ColumnType,\n type CompiledTable,\n type TableDescriptor,\n type ColumnDescriptor\n} from \"@rebasepro/types\";\nimport {\n getEnumVarName,\n TENANT_INDEX_REASON,\n getTableVarName,\n customSqlTypeProblem,\n declaredSchemaOf,\n columnByKey,\n relationOf,\n columnNameOf,\n tenantOf,\n compileTableRulePolicies,\n junctionPolicyTable,\n policyTableFromDescriptor,\n policyTableResolver,\n resolveTableJunctions,\n tableEffectiveRules,\n tableInjectedRules,\n tableJunctionRules,\n type CompiledRulePolicy,\n type PolicyTable,\n type RelationOfKind,\n type ResolvePolicyTable,\n type TableJunction,\n type TableJunctionSide\n} from \"@rebasepro/common\";\nimport {\n generateForeignKeyName,\n getPolicySupersededNames,\n legacyForeignKeyName,\n toPostgresIdentifier,\n toSnakeCase\n} from \"@rebasepro/utils\";\nimport {\n AUTH_USERS_COLUMNS,\n authUsersColumnDefinition,\n authUsersColumnSql\n} from \"../auth-users-columns\";\nimport {\n buildTableSearchColumnSpec,\n searchColumnTypeSql,\n searchExtensionStatements,\n searchHelperFunctions\n} from \"../search-column\";\nimport {\n buildTableVectorColumnSpecs,\n buildTableVectorIndexPlan,\n vectorExtensionDeclared,\n vectorExtensionStatement\n} from \"../vector-index\";\nimport {\n buildTableIndexSpecs,\n tableIndexStatement,\n deriveIndexName,\n foreignKeyIndexSpec,\n leadsWithColumn,\n type TableIndexSpec\n} from \"../table-index\";\nimport { createHash } from \"node:crypto\";\nimport { servedKeyOf, tableRelationName } from \"../relation-names\";\nimport { SET_UPDATED_AT_FN, setUpdatedAtFunction } from \"./updated-at-trigger\";\nimport { keepTenantFunction, keepTenantTriggerName } from \"./tenant-keep-trigger\";\nimport { DEFAULT_VIEW_ROLES, viewRowsName } from \"./view-names\";\nimport {\n IMPLICIT_ID_DEFAULT,\n plannedColumnEntries,\n referencingColumnType,\n writtenWithoutConstraint,\n type BelongsToDescriptor,\n type PlannedColumnEntry\n} from \"./column-order\";\nimport type {\n ColumnDefault,\n ColumnPlan,\n EnumPlan,\n ForeignKeyPlan,\n PgType,\n PlanOptions,\n PolicyPlan,\n RelationPlan,\n SchemaPlan,\n TablePlan,\n TriggerPlan,\n ViewPlan\n} from \"./types\";\n\n/**\n * Single-quote escaping for a SQL string literal (PostgreSQL doubles the\n * quote). Enum labels and `defaultValue`s come straight from user-authored\n * collection config, so a value like `it's` closes the literal early and the\n * whole generated file stops parsing at that statement.\n */\nexport const quoteSqlLiteral = (value: string): string => `'${value.replace(/'/g, \"''\")}'`;\n\nconst bareTableName = (name: string): string => (name.includes(\".\") ? name.split(\".\").pop()! : name);\n\n/**\n * The `ON DELETE` a foreign key gets when the author did not say.\n *\n * One rule for every property that emits one — `belongsTo` relations and\n * `reference` properties alike. `reference` kept its own `CASCADE` default for\n * a release after this rule was written, which is exactly the split this\n * function exists to prevent: two spellings of the same link, two\n * data-retention behaviours, and only one of them documented.\n *\n * An optional link is `SET NULL`: the column can hold NULL, so dropping the\n * parent leaves the child row with an empty pointer, which is what \"optional\"\n * already means.\n *\n * A required link is **`RESTRICT`**, not `CASCADE`. `NOT NULL` says the child\n * cannot exist without a parent; it does not say deleting the parent should\n * take the child with it. That second claim is a data-retention decision, and\n * defaulting to it meant `onDelete` — a field nobody has to write — silently\n * turned every `DELETE FROM authors` into a cascade through posts, comments and\n * anything else that hung off them.\n */\nexport const defaultBelongsToOnDelete = (required: boolean | undefined): \"RESTRICT\" | \"SET NULL\" =>\n required ? \"RESTRICT\" : \"SET NULL\";\n\nconst foreignKeyPlan = (\n args: Omit<ForeignKeyPlan, \"constraintName\" | \"sql\">\n): ForeignKeyPlan => {\n const constraintName = toPostgresIdentifier(`${args.table}_${args.column}_fkey`);\n const onUpdate = args.onUpdate ? ` ON UPDATE ${args.onUpdate.toUpperCase()}` : \"\";\n return {\n ...args,\n constraintName,\n sql:\n `ALTER TABLE \"${args.schema}\".\"${args.table}\" ADD CONSTRAINT \"${constraintName}\" ` +\n `FOREIGN KEY (\"${args.column}\") REFERENCES \"${args.targetSchema}\".\"${args.targetTable}\" ` +\n `(\"${args.targetColumn}\") ON DELETE ${args.onDelete.toUpperCase()}${onUpdate}`\n };\n};\n\n// ── Defaults ─────────────────────────────────────────────────────────────────\n\n/** A value already written as a day, or as a time of day. */\nconst BARE_DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst BARE_TIME = /^\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?$/;\n\n/**\n * A date default in the shape its column's type accepts: a day for `date`, a\n * time of day for `time`, an instant for a timestamp.\n *\n * Rendered as a full ISO timestamp whatever the column, a `time` column's\n * DEFAULT was `'2024-03-01T15:30:00.000Z'`, which Postgres refuses — \"invalid\n * input syntax for type time\" — so the schema would not apply. A value already\n * written in the column's shape (`\"2024-12-25\"`, `\"09:00\"`) is kept as written;\n * anything else is read as an instant and its UTC day or time of day taken, the\n * same zone the timestamp rendering has always used. A string that is no date\n * at all is no DEFAULT, rather than a schema that cannot be applied.\n */\nconst dateDefaultLiteral = (value: unknown, type: PgType): string | undefined => {\n if (typeof value === \"string\") {\n if (type.kind === \"date\" && BARE_DATE.test(value)) return value;\n if (type.kind === \"time\" && BARE_TIME.test(value)) return value;\n }\n const instant = value instanceof Date ? value : typeof value === \"string\" ? new Date(value) : undefined;\n if (!instant || Number.isNaN(instant.getTime())) return undefined;\n const iso = instant.toISOString();\n if (type.kind === \"date\") return iso.slice(0, 10);\n if (type.kind === \"time\") return iso.slice(11, 23);\n // A timestamp keeps a string default as it was written — its own offset\n // included — and a Date as the instant it is.\n return typeof value === \"string\" ? value : iso;\n};\n\n// ── Columns planned from their definition ────────────────────────────────────\n//\n// Every column is planned from its `ColumnDescriptor`: the `ColumnType` is the\n// Postgres type, the descriptor says whether it is a key, NOT NULL, UNIQUE,\n// generated, stamped or defaulted. Nothing is re-derived from a\n// document-shaped field (\"a string whose columnType is uuid\"), which is what\n// kept a generated column, a non-key identity and a `uuid[]` out of the\n// planner while it read the legacy shape.\n\n/** Where a defined column lands: what its enum type, if any, is named after. */\nexport interface DefinedColumnSite {\n /** The Postgres schema of the table (a junction's is `public`). */\n schema: string;\n /** The table, unqualified — an unnamed enum's type is named after it. */\n table: string;\n /** The table as a refusal names it: its slug, or a junction's table. */\n owner: string;\n /** The column key — an unnamed enum's Drizzle variable is named after it. */\n propName: string;\n /** The SQL column — an unnamed enum's type is named after it. */\n column: string;\n}\n\n/**\n * The element types a Postgres array column takes here: a scalar Rebase can\n * read and write item by item. A JSON document or a vector is already a list\n * of its own (`col.jsonb()` holds a list of documents), and a `bytea` item\n * would need a binary codec per element that nothing implements.\n */\nconst NON_ELEMENT_KINDS: ReadonlySet<ColumnType[\"kind\"]> = new Set([\"json\", \"jsonb\", \"vector\", \"bytea\", \"array\", \"other\"]);\n\n/**\n * The Postgres type a column descriptor states.\n *\n * One arm per {@link ColumnType} member: the two type unions are kept 1:1, so\n * this is a renaming, not a derivation. An enum is the one member that needs\n * the site — its type is named after the table and column it is declared on,\n * unless the definition names a shared type.\n */\nconst describedPgType = (column: ColumnDescriptor, site: DefinedColumnSite): PgType =>\n pgTypeOf(column.type, site);\n\n/** Where a table's described column lands. */\nconst describedSite = (descriptor: TableDescriptor, column: ColumnDescriptor): DefinedColumnSite => ({\n schema: descriptor.schema,\n table: descriptor.table,\n owner: descriptor.slug,\n propName: column.key,\n column: column.column\n});\n\n/** The key a link points at: its column key, its SQL column, and the type a column pointing at it has. */\ninterface TableKeyTarget {\n key: string;\n column: string;\n type: PgType;\n}\n\n/**\n * The single-column key of a table a link points at — a `belongsTo` foreign\n * key, a junction endpoint — and the type the pointing column must have: the\n * key's own type (a serial read as its plain integer, which would otherwise\n * give every referencing column a sequence of its own). A table with no key\n * is pointed at by the implicit `id TEXT`.\n *\n * @param via the link asking, named if the key is composite and so cannot be\n * pointed at.\n */\nexport const tableKeyTarget = (target: TableDescriptor, via: string): TableKeyTarget => {\n const keys = target.columns.filter(column => column.primaryKey === true);\n if (keys.length > 1) {\n throw new Error(\n `${via} points at table \"${target.slug}\", whose primary key spans ${keys.length} columns ` +\n `(${keys.map(key => `\"${key.key}\"`).join(\", \")}). A foreign key is one column and cannot reference a ` +\n \"composite key. Point the link at a table with a single-column key, or reach these rows with \" +\n \"`rel.via(...)`, whose steps compare every key column.\"\n );\n }\n const key = keys[0];\n if (!key) return { key: \"id\", column: \"id\", type: { kind: \"text\" } };\n return {\n key: key.key,\n column: key.column,\n type: pgTypeOf(referencingColumnType(key.type), describedSite(target, key))\n };\n};\n\nexport const pgTypeOf = (type: ColumnType, site: DefinedColumnSite): PgType => {\n switch (type.kind) {\n case \"text\": return { kind: \"text\" };\n case \"varchar\": return { kind: \"varchar\", length: type.length };\n case \"char\": return { kind: \"char\", length: type.length };\n case \"uuid\": return { kind: \"uuid\" };\n case \"enum\": return definedEnumType(type, site);\n case \"smallint\": return { kind: \"smallint\" };\n case \"integer\": return { kind: \"integer\" };\n case \"bigint\": return { kind: \"bigint\" };\n case \"smallserial\": return { kind: \"smallserial\" };\n case \"serial\": return { kind: \"serial\" };\n case \"bigserial\": return { kind: \"bigserial\" };\n case \"real\": return { kind: \"real\" };\n case \"doublePrecision\": return { kind: \"doublePrecision\" };\n case \"numeric\":\n if (type.precision === undefined) return { kind: \"numeric\" };\n return type.scale === undefined\n ? { kind: \"numeric\", precision: type.precision }\n : { kind: \"numeric\", precision: type.precision, scale: type.scale };\n case \"boolean\": return { kind: \"boolean\" };\n case \"timestamptz\": return { kind: \"timestamptz\" };\n case \"date\": return { kind: \"date\" };\n case \"time\": return { kind: \"time\" };\n case \"json\": return { kind: \"json\" };\n case \"jsonb\": return { kind: \"jsonb\" };\n case \"vector\": return { kind: \"vector\", dimensions: type.dimensions };\n case \"bytea\": return { kind: \"bytea\" };\n case \"array\":\n if (NON_ELEMENT_KINDS.has(type.of.kind)) {\n throw new Error(\n `Column \"${site.column}\" of \"${site.owner}\" is an array of ` +\n `\\`${type.of.kind}\\`, which is not an element type Rebase stores in a Postgres array. ` +\n \"An array column holds scalars (text, uuid, numbers, booleans, dates, enums); a list of \" +\n \"documents or vectors is a `col.jsonb()` column.\"\n );\n }\n return { kind: \"array\", of: pgTypeOf(type.of, site) };\n case \"other\": {\n // `col.custom(sqlType)`, written into DDL verbatim — so refused\n // again here, whoever built the definition, unless it is a type\n // name that cannot leave the statement.\n const problem = customSqlTypeProblem(type.sqlType);\n if (problem !== undefined) {\n throw new Error(\n `Column \"${site.column}\" of \"${site.owner}\" is \\`col.custom({ dataType: ${JSON.stringify(type.sqlType)} })\\`, ` +\n `and that type name ${problem}. Write the Postgres type as \\`format_type\\` prints it.`\n );\n }\n return { kind: \"custom\", sqlType: type.sqlType.trim() };\n }\n }\n};\n\n/**\n * The type name an enum states when it names a shared type: its `name`, unless\n * that is exactly the `<table>_<column>` an unnamed one gets — then it is that\n * column's own type, named and declared as it always was.\n */\nconst sharedEnumName = (type: Extract<ColumnType, { kind: \"enum\" }>, table: string, column: string): string | undefined =>\n type.name !== undefined && type.name !== `${table}_${column}` ? type.name : undefined;\n\n/**\n * The Drizzle variable of a shared enum type: one per type, whichever columns\n * use it, so it is named after the type (and its schema, outside `public`)\n * rather than after any one column. The `Enum` suffix keeps it apart from the\n * table variables, which are named after tables in the same namespace.\n */\nconst sharedEnumVarName = (schema: string, name: string): string =>\n `${getTableVarName(schema === \"public\" ? name : `${schema}_${name}`)}Enum`;\n\nconst definedEnumType = (type: Extract<ColumnType, { kind: \"enum\" }>, site: DefinedColumnSite): PgType => {\n const { table, schema } = site;\n // As `enumLabelsOf` reads a legacy enum: an empty label is no label, and a\n // type with none is refused rather than created empty.\n const labels = type.values.filter(label => label.length > 0);\n if (labels.length === 0) {\n throw new Error(\n `Column \"${site.column}\" of \"${site.owner}\" is an enum with no values. A Postgres enum ` +\n \"type needs at least one label.\"\n );\n }\n const shared = sharedEnumName(type, table, site.column);\n return {\n kind: \"enum\",\n schema,\n name: shared ?? `${table}_${site.column}`,\n varName: shared ? sharedEnumVarName(schema, shared) : getEnumVarName(table, site.propName),\n labels\n };\n};\n\n/** The enum type a defined column's values are typed by — its own, or its items'. */\nconst definedEnumOf = (type: PgType): Extract<PgType, { kind: \"enum\" }> | undefined => {\n if (type.kind === \"enum\") return type;\n if (type.kind === \"array\" && type.of.kind === \"enum\") return type.of;\n return undefined;\n};\n\n/**\n * A column's DEFAULT, from its descriptor.\n *\n * The precedence the legacy reading has — the key's strategy, then the time\n * stamp, then a SQL expression, then a literal — over the one `default` a\n * column holds. `identity` is planned on any integer column, key or not, at\n * the width the column declares. `database` plans none: the database owns\n * that default. A generated column has none at all.\n */\nconst describedColumnDefault = (column: ColumnDescriptor, type: PgType): ColumnDefault | undefined => {\n if (column.generated !== undefined) return undefined;\n const declared = column.default;\n if (declared?.kind === \"identity\") return { kind: \"identity\" };\n if (column.primaryKey) {\n // A key's strategy, as written: the expression is not trimmed (the\n // legacy `isId` reading never trimmed it either).\n if (declared?.kind === \"random-uuid\") return { kind: \"sql\", expression: \"gen_random_uuid()\" };\n if (declared?.kind === \"sql\") return { kind: \"sql\", expression: declared.expression };\n }\n if (column.stamp?.value === \"now\" && (type.kind === \"timestamptz\" || type.kind === \"date\" || type.kind === \"time\")) {\n return { kind: \"sql\", expression: \"now()\" };\n }\n if (declared?.kind === \"random-uuid\") return { kind: \"sql\", expression: \"gen_random_uuid()\" };\n if (declared?.kind === \"sql\") {\n const expression = declared.expression.trim();\n return expression ? { kind: \"sql\", expression } : undefined;\n }\n if (declared?.kind !== \"literal\") return undefined;\n return definedLiteralDefault(declared.value, type);\n};\n\n/**\n * A literal default, as the column's type quotes it. The same spellings as\n * {@link literalDefault}, chosen by the Postgres type rather than by the\n * property's: a native array, a vector and a `bytea` take none (the driver\n * still applies the value on create), exactly as their legacy reading did.\n */\nconst definedLiteralDefault = (value: unknown, type: PgType): ColumnDefault | undefined => {\n if (value === undefined || value === null) return undefined;\n switch (type.kind) {\n case \"text\":\n case \"varchar\":\n case \"char\":\n case \"uuid\":\n case \"enum\":\n return typeof value === \"string\" ? { kind: \"literal\", value, sql: quoteSqlLiteral(value) } : undefined;\n case \"smallint\":\n case \"integer\":\n case \"bigint\":\n case \"smallserial\":\n case \"serial\":\n case \"bigserial\":\n case \"real\":\n case \"doublePrecision\":\n case \"numeric\":\n return typeof value === \"number\" && Number.isFinite(value) ? { kind: \"literal\", value, sql: String(value) } : undefined;\n case \"boolean\":\n return typeof value === \"boolean\" ? { kind: \"literal\", value, sql: value ? \"TRUE\" : \"FALSE\" } : undefined;\n case \"timestamptz\":\n case \"date\":\n case \"time\": {\n const literal = dateDefaultLiteral(value, type);\n return literal === undefined ? undefined : { kind: \"literal\", value: literal, sql: quoteSqlLiteral(literal) };\n }\n // A custom scalar takes a string literal, which Postgres reads as the\n // column's type (`'10.0.0.1'` for `inet`, `'1 day'` for `interval`).\n case \"custom\":\n return typeof value === \"string\" && !/\\]\\s*$/.test(type.sqlType)\n ? { kind: \"literal\", value, sql: quoteSqlLiteral(value) }\n : undefined;\n case \"json\":\n case \"jsonb\": {\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n return undefined;\n }\n if (json === undefined) return undefined;\n return { kind: \"literal\", value, sql: `${quoteSqlLiteral(json)}::${type.kind}` };\n }\n default:\n return undefined;\n }\n};\n\n/**\n * One column planned from its descriptor — collection table and junction\n * pivot alike. {@link planPropertyColumn} hands over to it whenever the table\n * describes the column.\n */\nfunction planDescribedColumn(described: ColumnDescriptor, ctx: DescribedColumnContext): ColumnPlan {\n const { site, auth } = ctx;\n const { schema, table } = site;\n const { key, column } = described;\n const isKey = described.primaryKey === true;\n const type = describedPgType(described, site);\n const authDefinition = auth && !isKey ? authUsersColumnDefinition(column) : undefined;\n\n const plan: ColumnPlan = {\n key,\n column,\n type,\n nullable: !isKey && described.nullable,\n primaryKey: isKey,\n unique: !isKey && described.unique === true,\n default: describedColumnDefault(described, type),\n sqlDefinition: authDefinition,\n source: { kind: \"property\", propName: key, slug: ctx.slug }\n };\n if (described.generated !== undefined) {\n plan.generated = { expression: described.generated.expression, stored: true };\n }\n if (described.stamp?.on === \"update\" && described.stamp.value === \"now\") {\n plan.touchOnUpdate = true;\n ctx.triggerFunctionNeeded.value = true;\n ctx.triggers.push({\n schema,\n table,\n column,\n name: toPostgresIdentifier(`${table}_${column}_touch`)\n });\n }\n return plan;\n}\n\n// ── Policies ─────────────────────────────────────────────────────────────────\n\n/**\n * One security rule of a table, compiled to its policies — what\n * the legacy `compileSecurityRule` does for a collection, read from the table's\n * {@link PolicyTable} (`policyTableFromDescriptor`, `junctionPolicyTable`).\n */\nexport const compileTableSecurityRule = (\n table: PolicyTable,\n rule: SecurityRule,\n resolveTable: ResolvePolicyTable | undefined,\n injected: boolean,\n ruleKey = rule.name ?? \"(unnamed)\"\n): PolicyPlan[] =>\n policyPlans(\n compileTableRulePolicies(table, rule, { resolveTable, adminRole: true, adminRequestRole: true }),\n getPolicySupersededNames(rule, table.table), injected, ruleKey);\n\n/** The planner's bookkeeping over one rule's compiled policies. */\nconst policyPlans = (\n compiled: readonly CompiledRulePolicy[],\n supersedes: string[],\n injected: boolean,\n ruleKey: string\n): PolicyPlan[] => {\n const plans: PolicyPlan[] = [];\n for (const policy of compiled) {\n // A companion follows its base: carried on it, not planned beside it.\n if (policy.adminRequestTarget) {\n const base = plans[plans.length - 1];\n if (base) base.adminRequestCompanion = { name: policy.name, using: policy.using, withCheck: policy.withCheck };\n continue;\n }\n plans.push({\n ...policy,\n ruleKey,\n injected,\n ...(plans.length === 0 && supersedes.length > 0 ? { supersedes } : {})\n });\n }\n return plans;\n};\n\n/**\n * Refuse two of a table's policies that Postgres would store under one name.\n *\n * Each policy is rendered as `DROP POLICY IF EXISTS \"<name>\"` and then its\n * `CREATE`, and Postgres keeps the first 63 bytes of the name, so the second\n * of two policies whose names share those bytes drops the first and takes its\n * place. On a table of 56 bytes or more every unnamed rule of one operation is\n * `<table>_<op>` once stored, so a restrictive gate followed by a grant left\n * the grant alone in force. One rule's own operations never collide here —\n * `getPolicyNamesForRule` names them apart — so a collision is always two\n * rules, and the author names one of them.\n */\nconst sameStoredPolicy = (a: PolicyPlan, b: PolicyPlan): boolean =>\n a.name === b.name && a.operation === b.operation && a.mode === b.mode\n && a.roles.join(\",\") === b.roles.join(\",\") && a.using === b.using && a.withCheck === b.withCheck;\n\nfunction assertDistinctStoredPolicyNames(policies: PolicyPlan[]): void {\n const owners = new Map<string, PolicyPlan>();\n for (const policy of policies) {\n const stored = toPostgresIdentifier(policy.name);\n const first = owners.get(stored);\n if (!first) {\n owners.set(stored, policy);\n continue;\n }\n // The same policy twice — a rule repeated verbatim — replaces itself.\n if (sameStoredPolicy(first, policy)) continue;\n throw new Error(\n `The security rules \"${first.ruleKey}\" and \"${policy.ruleKey}\" compile to the policies ` +\n `\"${first.name}\" and \"${policy.name}\", which Postgres stores under one name, \"${stored}\": it ` +\n \"keeps only the first 63 bytes of an identifier, so the second would replace the first. \" +\n \"Give one of the rules a shorter `name`, or the table a shorter name.\"\n );\n }\n}\n\n/**\n * A table's policies, minus any superseded name Postgres would store one of\n * them under.\n *\n * A superseded name is a 63-byte cut, and another rule's over-long name can\n * cut to the very same bytes — `<table>_default_admin_read` and the old\n * `<table>_default_admin_write_<op>` both do on a 50-byte table. Dropping it\n * then would drop that policy right after its own `CREATE`. Its own `DROP\n * POLICY IF EXISTS` already removes the old policy, so nothing is lost.\n */\nconst withoutLiveSupersededNames = (policies: PolicyPlan[]): PolicyPlan[] => {\n assertDistinctStoredPolicyNames(policies);\n const stored = new Set(policies.map(policy => toPostgresIdentifier(policy.name)));\n return policies.map(policy => {\n if (!policy.supersedes) return policy;\n const supersedes = policy.supersedes.filter(name => !stored.has(name));\n if (supersedes.length === policy.supersedes.length) return policy;\n const kept: PolicyPlan = { ...policy };\n if (supersedes.length > 0) kept.supersedes = supersedes;\n else delete kept.supersedes;\n return kept;\n });\n};\n\n// ── The planner ──────────────────────────────────────────────────────────────\n\n/**\n * Everything a set of tables asks the database for.\n *\n * The input is the compiled tables — what `compileSchema` returns and every\n * door (`loadTables`, boot, the CLI) hands over. Planned in the order given:\n * the callers sort by slug first, and the generated files keep that order.\n *\n * @param compiledTables the compiled tables, in slug order.\n * @param options the planner's world: the extensions it may install.\n */\nexport function planSchema(compiledTables: readonly CompiledTable[], options: PlanOptions = {}): SchemaPlan {\n const descriptors = compiledTables.map(table => table.descriptor);\n const descriptorOf = new Map(descriptors.map(descriptor => [descriptor.slug, descriptor]));\n const targetOf = (slug: string): TableDescriptor => {\n const target = descriptorOf.get(slug);\n if (!target) throw new Error(`Internal: a relation points at the table \"${slug}\", which is not among the planned tables.`);\n return target;\n };\n // A view has no table, policy or enum: it is planned on its own (`views`),\n // and resolvable as a relation target.\n const tableDescriptors = descriptors.filter(descriptor => descriptor.kind !== \"view\");\n\n const declaredSchemas = Array.from(new Set(tableDescriptors.flatMap(descriptor => {\n const declared = declaredSchemaOf(descriptor);\n return declared === undefined ? [] : [declared];\n })));\n const schemas = Array.from(new Set([REBASE_SCHEMA, ...declaredSchemas]));\n\n // ── Enum types ───────────────────────────────────────────────────────────\n // The name is derived from table + column, so two tables mapped onto the\n // same SQL table — or two columns of one SQL name — land on the same type.\n // `CREATE TYPE` has no IF NOT EXISTS, so emitting it twice aborts the whole\n // file; deduplicated by name here, once, for every renderer.\n //\n // Deduplicated by the name *Postgres* holds, which is the first 63 bytes,\n // and only for the same column. Two different columns deriving one name —\n // `orders.item_status` and `orders_item.status`, or two long names that\n // share their first 63 bytes — cannot share a type: the second column would\n // be typed with the first one's labels and reject its own. The name is\n // frozen once a database holds it, so this refuses rather than renaming.\n const enums: EnumPlan[] = [];\n const enumOwners = new Map<string, { table: string; column: string; owner: string; shared?: { name: string; labels: string[] } }>();\n /**\n * The enum type a column is typed by, appended once.\n *\n * A column's own type (`<table>_<column>`) is claimed by that column alone,\n * as above. A type the definition names (`pgEnum(name, values)`) is\n * shared: every column naming it is typed by the one `CREATE TYPE`, and\n * they must agree on its values — `compileTables` refuses a disagreement\n * first, and so does this, for a plan reached any other way.\n *\n * `declaredSchema` is passed rather than read off the site because a\n * junction's `public` is a resolved fact and not a declaration — emitting\n * it as one would make the generated file reach for a `pgSchema(\"public\")`\n * variable that exists for nobody.\n */\n const collectEnumType = (site: DefinedColumnSite, described: ColumnDescriptor, declaredSchema: string | undefined): void => {\n const owner = `column \"${described.key}\" of \"${site.owner}\"`;\n // A closed value set that is no enum type (`.oneOf()`) refuses an\n // empty list as an enum type refuses one.\n if (described.oneOf !== undefined && described.oneOf.every(value => String(value).length === 0)) {\n throw new Error(\n `The ${owner} is \\`.oneOf()\\` with no non-empty value, so no value can be written to it. ` +\n \"List the values the column accepts.\"\n );\n }\n const enumType = definedEnumOf(describedPgType(described, site));\n if (!enumType) return;\n const { schema, name, labels } = enumType;\n const { table, column } = site;\n const qualified = `${schema}.${toPostgresIdentifier(name)}`;\n const shared = name === `${table}_${column}` ? undefined : { name, labels };\n const claimed = enumOwners.get(qualified);\n if (claimed) {\n if (claimed.table === table && claimed.column === column) return;\n if (shared && claimed.shared?.name === name) {\n if (claimed.shared.labels.join(\"\\u0000\") === labels.join(\"\\u0000\")) return;\n throw new Error(\n `The enum type \"${schema}\".\"${name}\" is given the values (${labels.join(\", \")}) by the ${owner} and ` +\n `(${claimed.shared.labels.join(\", \")}) by the ${claimed.owner}. Columns sharing a named enum type must ` +\n \"list the same values, in the same order. Make them agree, or give one column its own type `name`.\"\n );\n }\n throw new Error(\n `The enum ${owner} and the enum ${claimed.owner} both derive the Postgres type ` +\n `\"${schema}\".\"${toPostgresIdentifier(name)}\" (Postgres keeps the first 63 bytes of a name). One type ` +\n \"cannot hold both columns' values, and a type's name cannot change once a database holds it. Give \" +\n \"one of the two columns another name with `.column()`, its table another `table` or `schema`, or \" +\n \"its enum another `name`.\"\n );\n }\n enumOwners.set(qualified, { table, column, owner, shared });\n enums.push({ schema, name, qualified, declaredSchema, varName: enumType.varName, labels });\n };\n for (const descriptor of tableDescriptors) {\n const declaredSchema = declaredSchemaOf(descriptor);\n for (const entry of plannedColumnEntries(descriptor, targetOf)) {\n // A link is typed by its target's key, whose type its table declares.\n if (entry.kind !== \"column\") continue;\n collectEnumType(describedSite(descriptor, entry.column), entry.column, declaredSchema);\n }\n }\n\n // ── The table set ────────────────────────────────────────────────────────\n // Each table, then any junction its relations imply, in the order the\n // tables arrive. `schema.sql` and `schema.generated.ts` are compared\n // against their committed copies, so this order is the file's.\n // Every descriptor: a view declares no junction, but one may be a target.\n const tableJunctions = resolveTableJunctions(descriptors);\n const resolvePolicyTable = policyTableResolver(descriptors);\n const tableEntries = new Map<string, TableEntry>();\n const junctionShapes = new Map<string, { keys: string; claim: string }>();\n for (const descriptor of tableDescriptors) {\n tableEntries.set(descriptor.table, { kind: \"table\", descriptor });\n for (const relation of descriptor.relations) {\n if (relation.kind !== \"manyToMany\") continue;\n const junctionTable = relation.through.table;\n assertOneJunctionShape(junctionShapes, junctionTable, descriptor, relation, targetOf(relation.target));\n if (tableEntries.has(junctionTable)) continue;\n const junction = tableJunctions.get(bareTableName(junctionTable));\n if (!junction) throw new Error(`Internal: the junction table \"${junctionTable}\" of \"${descriptor.slug}\" was not resolved.`);\n tableEntries.set(junctionTable, { kind: \"junction\", junction });\n }\n }\n\n // A junction's pivot may declare an enum too, and the type it names is\n // created by nobody else: no table owns the junction, so the loop above\n // never sees the column. Appended after the tables' — the enum block is\n // compared byte-for-byte against its committed copy, and a junction whose\n // type interleaved with the tables' would reorder that file whenever a\n // `pivot` moved.\n for (const junction of tableJunctions.values()) {\n const keys = new Set(junction.endpoints.map(endpoint => endpoint.junctionColumn));\n for (const pivotColumn of junction.pivot) {\n if (keys.has(pivotColumn.column)) continue;\n collectEnumType(junctionSite(junction, pivotColumn), pivotColumn, undefined);\n }\n }\n\n const triggerFunctionNeeded = { value: false };\n\n const tables: TablePlan[] = [];\n for (const entry of tableEntries.values()) {\n tables.push(entry.kind === \"junction\"\n ? planJunctionTable(entry.junction, targetOf, resolvePolicyTable, triggerFunctionNeeded)\n : planCollectionTable(entry.descriptor, resolvePolicyTable, targetOf, triggerFunctionNeeded));\n }\n\n assertNoTruncationCollisions(tables, enums);\n\n // ── Extensions and functions ─────────────────────────────────────────────\n const extensions: string[] = [];\n const functions: string[] = [];\n const seenStatements = new Set<string>();\n const add = (into: string[], statement: string): void => {\n if (seenStatements.has(statement)) return;\n seenStatements.add(statement);\n into.push(statement);\n };\n for (const table of tables) {\n if (!table.search) continue;\n for (const statement of searchExtensionStatements(table.search)) add(extensions, statement);\n }\n // pgvector is a separate build behind an image, a grant and a provider\n // allow-list, so whether Rebase may install it is not Rebase's to decide.\n // See `DatabaseOptions.extensions`.\n if (vectorExtensionDeclared(options.databaseExtensions)\n && tables.some(t => t.vectorColumns.length > 0)) {\n add(extensions, vectorExtensionStatement());\n }\n for (const table of tables) {\n if (!table.search) continue;\n for (const statement of searchHelperFunctions(table.search)) add(functions, statement);\n }\n if (triggerFunctionNeeded.value) add(functions, setUpdatedAtFunction());\n if (tables.some(t => t.triggers.some(trigger => trigger.kind === \"keep-tenant\"))) add(functions, keepTenantFunction());\n\n return {\n schemas,\n declaredSchemas,\n enums,\n tables,\n views: planViews(descriptors),\n relations: planRelations(tableDescriptors, tableEntries, targetOf),\n extensions,\n functions,\n options\n };\n}\n\n/**\n * The views the tables declare (`defineView`), each after the views its query\n * names.\n *\n * Which views a query reads is read off its text — a planned view's name as a\n * whole word — which is enough to order them: a name that appears in a string\n * literal only orders two views that did not need it, never the other way.\n */\nexport function planViews(tables: readonly TableDescriptor[]): ViewPlan[] {\n const declared = tables.flatMap(descriptor => {\n const view = descriptor.view;\n if (descriptor.kind !== \"view\" || !view || view.query === undefined) return [];\n const { schema, table: name } = descriptor;\n const idColumns = descriptor.primaryKey.map(key => columnNameOf(descriptor, key) ?? key);\n const materialized = view.materialized;\n return [{\n schema, name, qualified: `${schema}.${name}`,\n query: view.query.trim().replace(/;\\s*$/, \"\"),\n materialized,\n roles: materialized ? [...(view.roles ?? DEFAULT_VIEW_ROLES)] : [],\n idColumns,\n // A materialized view's own `indexes`, on its stored rows.\n indexes: materialized\n ? buildTableIndexSpecs(descriptor)\n .map(spec => tableIndexStatement({ ...spec, table: viewRowsName(name) }).replace(/;$/, \"\"))\n : []\n }];\n });\n const named = (query: string, view: { schema: string; name: string }) =>\n new RegExp(`(^|[^A-Za-z0-9_$\"])\"?${escapeRegExp(view.name)}\"?([^A-Za-z0-9_$\"]|$)`).test(query);\n const withDependencies = declared.map(view => ({\n ...view,\n dependsOn: declared.filter(other => other !== view && named(view.query, other)).map(other => other.qualified)\n }));\n\n // Depth-first, so every view lands after what it reads; a cycle is two\n // queries naming each other, which Postgres refuses to create anyway.\n const ordered: typeof withDependencies = [];\n const placed = new Set<string>();\n const visiting = new Set<string>();\n const place = (view: typeof withDependencies[number]): void => {\n if (placed.has(view.qualified)) return;\n if (visiting.has(view.qualified)) {\n throw new Error(`The views ${[...visiting].join(\", \")} read each other; a view cannot be created before the view it reads.`);\n }\n visiting.add(view.qualified);\n for (const dependency of view.dependsOn) {\n const target = withDependencies.find(other => other.qualified === dependency);\n if (target) place(target);\n }\n visiting.delete(view.qualified);\n placed.add(view.qualified);\n ordered.push(view);\n };\n for (const view of withDependencies) place(view);\n\n return ordered.map(view => ({\n ...view,\n hash: createHash(\"sha256\")\n // `gated`: a materialized view is its stored rows behind a view\n // that serves them to its roles (0.29.0 created the bare matview).\n .update(JSON.stringify([view.qualified, view.query, view.materialized, view.idColumns,\n ...(view.materialized ? [\"gated\", view.roles, view.indexes] : [])]))\n .digest(\"hex\")\n .slice(0, 16)\n }));\n}\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Refuse two relations — tables, junctions and enum types share one namespace\n * per schema, because every table owns a row type of its own name — that are\n * distinct in full but one name after Postgres keeps the first 63 bytes.\n *\n * `a_table_with_a_really_long_name_that_goes_on_and_on_and_on_forever` with an\n * enum column and a many-to-many truncated its table, its enum type and its\n * junction to the same identifier: the push failed with `type \"…\" already\n * exists` and no validator mentioned the length. A name that already works is\n * never touched — only a collision that cannot be created refuses.\n */\nfunction assertNoTruncationCollisions(tables: TablePlan[], enums: EnumPlan[]): void {\n const owners = new Map<string, string>();\n const claim = (schema: string, name: string, what: string): void => {\n const key = `${schema}.${toPostgresIdentifier(name)}`;\n const first = owners.get(key);\n if (first === undefined) {\n owners.set(key, what);\n return;\n }\n throw new Error(\n `The ${what} and the ${first} both become \"${schema}\".\"${toPostgresIdentifier(name)}\" in Postgres, ` +\n \"which keeps only the first 63 bytes of an identifier — and a table, a junction table and an enum \" +\n \"type share one namespace (every table owns a row type of its name). The push would fail with \" +\n \"\\\"already exists\\\". Give the table a shorter name, or the enum's property a shorter \" +\n \"`columnName` (an enum type is named <table>_<column>).\"\n );\n };\n for (const table of tables) {\n claim(table.schema, table.table, table.kind === \"junction\" ? `junction table \"${table.table}\"` : `table \"${table.table}\"`);\n }\n for (const e of enums) claim(e.schema, e.name, `enum type \"${e.name}\"`);\n}\n\n/**\n * Refuse two many-to-many relations that resolve to one junction table with\n * different key columns.\n *\n * A default `through` is named after the two tables, so `posts.tags` and\n * `posts.featuredTags` both resolve to `posts_tags` — one keyed by `tag_id`,\n * the other by `featured_tag_id`. One table is created, from whichever came\n * first, so the other relation read and wrote a column that was never there.\n * The two sides of one link (`posts.tags` and `tags.posts`) share a junction\n * legitimately, and they name the same two columns — so the comparison is of\n * the (column, endpoint) pairs, in either order.\n */\nfunction assertOneJunctionShape(\n seen: Map<string, { keys: string; claim: string }>,\n junctionTable: string,\n descriptor: TableDescriptor,\n relation: RelationOfKind<\"manyToMany\">,\n target: TableDescriptor\n): void {\n const sourceTable = descriptor.table;\n const targetTable = target.table;\n const { sourceKey, targetKey } = relation.through;\n const keys = JSON.stringify([[sourceKey, sourceTable], [targetKey, targetTable]].sort());\n const claim = `the relation \"${relation.name}\" of table \"${descriptor.slug}\" ` +\n `(\"${sourceKey}\" → ${sourceTable}, \"${targetKey}\" → ${targetTable})`;\n const first = seen.get(junctionTable);\n if (!first) {\n seen.set(junctionTable, { keys, claim });\n return;\n }\n if (first.keys === keys) return;\n throw new Error(\n `Two many-to-many relations resolve to the junction table \"${junctionTable}\" with different key ` +\n `columns: ${first.claim} and ${claim}. Only one table is created, so one of them would read ` +\n \"and write columns that do not exist. Give the second its own junction — \" +\n `\\`through: { table: \"${sourceTable}_${toSnakeCase(relation.name)}\" }\\` — or, if both are meant to ` +\n \"be one link, declare it once.\"\n );\n}\n\n/** One table the plan creates: a table's own, or a junction its relations imply. */\ntype TableEntry =\n | { kind: \"table\"; descriptor: TableDescriptor }\n | { kind: \"junction\"; junction: TableJunction };\n\n/** Where a junction's pivot column lands. */\nconst junctionSite = (junction: TableJunction, column: ColumnDescriptor): DefinedColumnSite => ({\n schema: junction.schema,\n table: junction.table,\n owner: junction.table,\n propName: column.key,\n column: column.column\n});\n\n// ── A collection's table ─────────────────────────────────────────────────────\n\nfunction planCollectionTable(\n descriptor: TableDescriptor,\n resolvePolicyTable: ResolvePolicyTable,\n targetOf: (slug: string) => TableDescriptor,\n triggerFunctionNeeded: { value: boolean }\n): TablePlan {\n const { schema, table, slug } = descriptor;\n const auth = descriptor.auth !== undefined;\n const columns: ColumnPlan[] = [];\n const triggers: TriggerPlan[] = [];\n\n // In the plan's order, read from the descriptor (`plannedColumnEntries`).\n for (const entry of plannedColumnEntries(descriptor, targetOf)) {\n if (entry.kind === \"link\") {\n columns.push(planLinkColumn(entry, descriptor, targetOf));\n continue;\n }\n columns.push(planDescribedColumn(entry.column, {\n site: describedSite(descriptor, entry.column),\n slug,\n auth,\n triggers,\n triggerFunctionNeeded\n }));\n }\n\n // ── Auth columns the collection file never mentions ──────────────────────\n // `db push` is declarative: Atlas diffs the database against exactly what\n // is emitted and drops anything else. The scaffold's users collection\n // describes 12 columns while auth needs 14, so `is_anonymous` and\n // `tokens_valid_after` read as unmanaged drift and a push run after the\n // server had started once planned to DROP them.\n if (auth) {\n const declared = new Set(columns.map(c => c.column));\n for (const spec of AUTH_USERS_COLUMNS) {\n if (declared.has(spec.column)) continue;\n columns.push({\n key: spec.column,\n column: spec.column,\n type: authColumnType(spec.type),\n nullable: spec.notNull !== true,\n primaryKey: false,\n unique: false,\n sqlDefinition: authUsersColumnSql(spec),\n source: { kind: \"auth\", slug: slug }\n });\n }\n }\n\n // ── The opt-in search column ─────────────────────────────────────────────\n // Last, so it reads as what it is: derived from the columns above it.\n // Postgres recomputes it on every write of a source column and rejects any\n // attempt to write it directly, which is what makes it impossible for the\n // index to drift from the row.\n const search = buildTableSearchColumnSpec(descriptor);\n if (search) {\n columns.push({\n key: search.column,\n column: search.column,\n type: { kind: \"tsvector\" },\n nullable: true,\n primaryKey: false,\n unique: false,\n generated: { expression: search.expression, stored: true },\n sqlDefinition: searchColumnTypeSql(search.expression, \"tsvector\"),\n source: { kind: \"search\", slug: slug }\n });\n if (search.fuzzy) {\n columns.push({\n key: search.fuzzy.column,\n column: search.fuzzy.column,\n type: { kind: \"text\" },\n nullable: true,\n primaryKey: false,\n unique: false,\n generated: { expression: search.fuzzy.expression, stored: true },\n sqlDefinition: searchColumnTypeSql(search.fuzzy.expression, \"text\"),\n source: { kind: \"search\", slug: slug }\n });\n }\n }\n\n const primaryKey = planPrimaryKey(descriptor, columns);\n\n const policyTable = resolvePolicyTable(descriptor.slug) ?? policyTableFromDescriptor(descriptor);\n const injected = new Set(tableInjectedRules(policyTable).map(rule => rule.name));\n const policies = withoutLiveSupersededNames(tableEffectiveRules(policyTable).flatMap((rule, index) =>\n compileTableSecurityRule(\n policyTable,\n rule,\n resolvePolicyTable,\n Boolean(rule.name && injected.has(rule.name)),\n rule.name ?? `#${index}`\n )));\n\n // ── Tenancy ──────────────────────────────────────────────────────────────\n // The policy is already above — `tableEffectiveRules` injects it, so\n // it compiles, names and renders like every other rule. What is left is the\n // half a rule cannot express: the column is NOT NULL, and it is indexed.\n const tenantIndexes = applyTenantColumnEffects(descriptor, columns, primaryKey);\n const keepTenant = planKeepTenantTrigger(descriptor, columns);\n if (keepTenant) triggers.push(keepTenant);\n\n // Last among the columns, because it reads a nullability the two passes\n // above can still change.\n settleDefaultOnDelete(descriptor, columns);\n\n // After every other index, because the foreign-key ones defer to them: a\n // declared index or the tenant index that already leads with the column\n // serves the same lookups, and a second one would only cost writes.\n const indexes = [...buildTableIndexSpecs(descriptor), ...tenantIndexes];\n indexes.push(...planForeignKeyIndexes(schema, table, columns, primaryKey, indexes, column => {\n // A `belongsTo` whose author opted out keeps its constraint and loses\n // only the index. Asked of the relation, not the column: the column a\n // declared property owns carries no relation of its own.\n const relation = linkRelationOf(descriptor, column);\n if (!relation?.index) return undefined;\n // A link declared without its constraint is joined on all the same:\n // its column is indexed as a foreign key's would be. A link into a\n // view is not: nothing can be joined there by key.\n return column.foreignKey?.column\n ?? (writtenWithoutConstraint(descriptor, relation, targetOf(relation.target)) ? column.column : undefined);\n }));\n\n return {\n schema,\n table,\n qualified: `${schema}.${table}`,\n declaredSchema: declaredSchemaOf(descriptor),\n varName: getTableVarName(table),\n kind: \"collection\",\n slug,\n columns,\n primaryKey,\n indexes,\n search,\n vector: buildTableVectorIndexPlan(descriptor),\n vectorColumns: buildTableVectorColumnSpecs(descriptor),\n policies,\n triggers,\n auth\n };\n}\n\n/**\n * The table's primary key, as the column names {@link TablePlan.primaryKey}\n * lists — and the columns adjusted to state it one way only.\n *\n * One `isId` property is a key column of its own, declared inline\n * (`\"id\" INTEGER PRIMARY KEY`, `.primaryKey()`), which is how\n * {@link planPropertyColumn} planned it. Several are one composite key, and a\n * composite key cannot be said column by column: two inline `PRIMARY KEY`\n * clauses are two primary keys, which Postgres refuses. So each member stops\n * being a key of its own, keeps NOT NULL (the constraint implies it, and every\n * emitter spells it on the column so the three read the same), and the table\n * gets one `PRIMARY KEY (a, b)` over the list returned here — the shape a\n * junction's key has always had.\n *\n * A table that declares no key gets an implicit `id TEXT PRIMARY KEY`,\n * which is what `getPrimaryKeys` reads back.\n */\nfunction planPrimaryKey(descriptor: TableDescriptor, columns: ColumnPlan[]): string[] {\n const keyNames = descriptor.primaryKey;\n\n if (keyNames.length > 1) {\n return keyNames.map(name => {\n const column = columns.find(c => c.source.propName === name && !c.columnOwnedByProperty);\n if (!column) {\n throw new Error(\n `Column \"${name}\" of table \"${descriptor.slug}\" is part of the primary key, and it puts ` +\n \"no column on this table, so it cannot be part of the table's primary key. Mark the \" +\n \"column that holds it `.primaryKey()` instead.\"\n );\n }\n column.primaryKey = false;\n column.nullable = false;\n return column.column;\n });\n }\n\n // With a default the database fills. Nothing else can: the key is not a\n // property, so the admin form has no field for it, and REST, the SDK and\n // the socket send none. Without one, every insert into a collection that\n // declares no key — the quickstart's first one among them — was refused\n // as a missing `id`. The column stays TEXT so a table created before this\n // keeps its type, and boot's ensure adds the default to it: a DEFAULT binds\n // only future writes, so it is the one change it makes to an existing\n // column. A key the caller does supply still wins over the default.\n if (!columns.some(c => c.primaryKey)) {\n columns.unshift({\n key: \"id\",\n column: \"id\",\n type: { kind: \"text\" },\n nullable: false,\n primaryKey: true,\n unique: false,\n default: { kind: \"sql\", expression: IMPLICIT_ID_DEFAULT },\n source: { kind: \"implicit-id\", slug: descriptor.slug }\n });\n }\n return columns.filter(c => c.primaryKey).map(c => c.column);\n}\n\n/** What {@link planDescribedColumn} needs about the table the column lands on. */\ninterface DescribedColumnContext {\n /** Where the column lands — the trigger and an unnamed enum are named after it. */\n site: DefinedColumnSite;\n /** The slug the plan records as the column's source: the table's, or a junction's table name. */\n slug: string;\n /** Whether `auth-users-columns` owns this table's columns. */\n auth: boolean;\n /** Collected `BEFORE UPDATE` triggers, appended to. */\n triggers: TriggerPlan[];\n triggerFunctionNeeded: { value: boolean };\n}\n\n/**\n * The two schema effects a `tenant` declaration has that a policy cannot state.\n *\n * The policy itself is injected as an ordinary `SecurityRule`\n * (`buildTenantSecurityRule`) and compiled above with every other rule, so\n * nothing here touches `policies`. What is left is the column:\n *\n * - **`NOT NULL`.** A row whose tenant is NULL belongs to nobody, and the\n * restrictive policy compares the column to the caller's tenant — a\n * comparison against NULL is never true. Such a row is therefore invisible to\n * every caller, forever, including the one who wrote it. The write path\n * refuses to create one (`TENANT_REQUIRED`); this is the same statement made\n * where a raw `INSERT`, a seed and a migration can also hear it.\n * - **An index.** The tenancy predicate is ANDed into *every* statement against\n * the table, so an unindexed tenant column turns every read into a sequential\n * scan filtered by tenant. It is the one index a tenant-scoped table cannot\n * be without, and the one people most reliably forget — which is the whole\n * argument for deriving it rather than documenting it.\n *\n * The index goes through `deriveIndexName` like every other index, so it is a\n * Rebase-managed name (`_ix_<fingerprint>`), it is in the Atlas diff, and the\n * doctor recognises it. Because that name is a fingerprint of the index's\n * semantics, an author who has *already* declared a plain btree index on the\n * tenant column derives byte-for-byte the same name — so the two are the same\n * object and this adds nothing rather than colliding.\n *\n * Throws when the field names no column. `planSchema` throws rather than\n * guessing, and the alternative here is a table with a tenancy policy over a\n * column that does not exist: `CREATE POLICY` fails, RLS stays enabled, and the\n * collection denies every row.\n */\nfunction applyTenantColumnEffects(\n descriptor: TableDescriptor,\n columns: ColumnPlan[],\n primaryKey: string[]\n): TableIndexSpec[] {\n const tenant = tenantOf(descriptor);\n if (!tenant) return [];\n const { schema, table } = descriptor;\n\n const column = findTenantColumn(descriptor, columns, tenant.field);\n if (!column) {\n throw new Error(\n `Table \"${descriptor.slug}\" declares \\`tenant: { field: \"${tenant.field}\" }\\`, and ` +\n \"no column of that key is created on it. `tenant` says what a column means; it does not \" +\n \"create one. Declare the column, or name the one that holds the tenant id.\"\n );\n }\n\n // The leading column of the primary key is already NOT NULL and already\n // indexed by `<table>_pkey`. Saying either again would make `db push` plan\n // a constraint and an index the database has no reason to hold. A later\n // column of a composite key is NOT NULL too, but `<table>_pkey` cannot\n // serve a lookup on it alone, so it still gets its index.\n if (primaryKey[0] === column.column) return [];\n\n column.nullable = false;\n\n const withoutName = {\n schema,\n table,\n method: \"btree\" as const,\n unique: false,\n keys: [{ column: column.column, direction: \"asc\" as const, nulls: \"last\" as const }],\n include: [],\n predicate: null,\n reason: TENANT_INDEX_REASON\n };\n return [{ ...withoutName, indexName: deriveIndexName(withoutName) }];\n}\n\n/**\n * The trigger that keeps a row in its tenant, or nothing when the collection\n * declares no `tenant`. See `tenant-keep-trigger.ts` for why a policy cannot.\n */\nfunction planKeepTenantTrigger(\n descriptor: TableDescriptor,\n columns: ColumnPlan[]\n): TriggerPlan | undefined {\n const tenant = tenantOf(descriptor);\n if (!tenant) return undefined;\n const column = findTenantColumn(descriptor, columns, tenant.field);\n if (!column) return undefined;\n const { schema, table } = descriptor;\n return {\n schema,\n table,\n column: column.column,\n name: toPostgresIdentifier(keepTenantTriggerName(table)),\n kind: \"keep-tenant\",\n bypassRoles: [...tenant.bypassRoles]\n };\n}\n\n/**\n * A btree on each foreign-key column of one table, where nothing already\n * serves the lookup — see `foreignKeyIndexSpec` for why the column needs one.\n * `linkColumn` names the column a planned column links by, or nothing for a\n * column that wants no such index (an opted-out link, a plain column).\n *\n * Skipped, so that no table ever carries two indexes doing one job, when the\n * column already leads:\n *\n * - the primary key — `<table>_pkey` is a btree over the key in key order, so\n * its first column is indexed and the rest are not (a junction's\n * `(post_id, tag_id)` key serves `post_id`, and `tag_id` gets an index);\n * - a UNIQUE on the column (`validation.unique`, on the relation or on the\n * property that owns the column) — Postgres backs it with a btree;\n * - another planned index that leads with it ({@link leadsWithColumn}) — one\n * the collection declares in `indexes:`, or the tenant index.\n *\n * Only the plan is consulted, never the catalogue: `db push` renders this from\n * the collections alone, and boot has to reach the same set with the same\n * names, or Atlas would plan to drop what boot built.\n */\nfunction planForeignKeyIndexes(\n schema: string,\n table: string,\n columns: ColumnPlan[],\n primaryKey: string[],\n planned: readonly TableIndexSpec[],\n linkColumn: (column: ColumnPlan) => string | undefined\n): TableIndexSpec[] {\n const created = columns.filter(c => !c.columnOwnedByProperty);\n const derived: TableIndexSpec[] = [];\n for (const column of columns) {\n const name = linkColumn(column);\n if (name === undefined) continue;\n if (primaryKey[0] === name) continue;\n if (created.some(c => c.column === name && c.unique)) continue;\n if ([...planned, ...derived].some(spec => leadsWithColumn(spec, name))) continue;\n derived.push(foreignKeyIndexSpec(schema, table, name));\n }\n return derived;\n}\n\n/**\n * The planned column a `tenant.field` names.\n *\n * The descriptor's `tenant.field` is a column key — a `belongsTo` named as\n * the tenant was resolved to its foreign-key column when the table compiled —\n * so the planned column is the one with that column's SQL name.\n *\n * Only columns that are created count. A relation whose column a declared\n * column owns keeps an entry for its constraint alone, under the same SQL\n * name; when the relation was declared first, NOT NULL landed on that entry,\n * nothing rendered it, and the tenant column stayed nullable.\n */\nfunction findTenantColumn(\n descriptor: TableDescriptor,\n columns: ColumnPlan[],\n field: string\n): ColumnPlan | undefined {\n const tenantColumn = columnByKey(descriptor, field);\n if (!tenantColumn) return undefined;\n return columns.find(c => !c.columnOwnedByProperty && c.column === tenantColumn.column);\n}\n\n/**\n * The `ON DELETE` a link gets when the author did not say, decided from the\n * column as it will be created.\n *\n * {@link planLinkColumn} sees only its own link's nullability, and two later facts change the premise: `tenant` makes\n * its column NOT NULL, and a declared property that owns a relation's column\n * decides that column's nullability itself. Defaulting before either produced\n * `NOT NULL … ON DELETE SET NULL` — a parent's delete that can only fail, and\n * fails with 23502 naming the child's column rather than as the foreign-key\n * refusal it is. An `onDelete` the author wrote is theirs and is kept.\n */\nfunction settleDefaultOnDelete(descriptor: TableDescriptor, columns: ColumnPlan[]): void {\n for (const column of columns) {\n const fk = column.foreignKey;\n // An `onDelete` the author wrote is theirs.\n if (!fk || linkRelationOf(descriptor, column)?.onDelete !== undefined) continue;\n const created = columns.find(c => c.column === column.column && !c.columnOwnedByProperty) ?? column;\n const onDelete = defaultBelongsToOnDelete(!created.nullable);\n if (onDelete === fk.onDelete) continue;\n column.foreignKey = foreignKeyPlan({\n schema: fk.schema,\n table: fk.table,\n column: fk.column,\n targetSchema: fk.targetSchema,\n targetTable: fk.targetTable,\n targetColumn: fk.targetColumn,\n onDelete,\n onUpdate: fk.onUpdate\n });\n }\n}\n\n/**\n * The column a `belongsTo` link plans, from its descriptor — one of the three\n * forms {@link plannedColumnEntries} hands over:\n *\n * - `absorbed`: the bound column is nothing but the foreign key, so this entry\n * IS the column, typed as the target's key;\n * - `constraint`: the bound column is planned on its own; this entry carries\n * the constraint alone (`columnOwnedByProperty`, skipped as a column by the\n * renderers) and states the same type and nullability, so one column never\n * reads two ways in the plan;\n * - `derived`: the relation derives the column, typed as the target's key.\n *\n * `constraint: false` keeps the column and plans no `FOREIGN KEY`; neither\n * does a link into a view (Postgres refuses one), which the descriptor already\n * records as `constraint: false`.\n */\nfunction planLinkColumn(\n entry: Extract<PlannedColumnEntry, { kind: \"link\" }>,\n descriptor: TableDescriptor,\n targetOf: (slug: string) => TableDescriptor\n): ColumnPlan {\n const { relation, column, form } = entry;\n const { schema, table, slug } = descriptor;\n const target = targetOf(relation.target);\n const via = `relation \"${slug}.${relation.name}\"`;\n const targetKey = tableKeyTarget(target, via);\n const ownsColumn = form === \"constraint\";\n const required = !column.nullable && column.primaryKey !== true;\n\n // Only a *derived* column name can be affected by the change to\n // `generateForeignKeyName`; one the author wrote is theirs.\n const legacyKey = legacyForeignKeyName(relation.name);\n const derivedName = relation.localKey === generateForeignKeyName(relation.name);\n\n return {\n key: column.key,\n column: relation.localKey,\n type: ownsColumn ? describedPgType(column, describedSite(descriptor, column)) : targetKey.type,\n nullable: column.nullable,\n primaryKey: false,\n // UNIQUE on a link is a one-to-one. The constraint-only entry leaves\n // it to the column planned beside it.\n unique: !ownsColumn && column.unique === true,\n columnOwnedByProperty: ownsColumn || undefined,\n legacyColumn: derivedName && legacyKey !== relation.localKey ? legacyKey : undefined,\n foreignKey: relation.constraint ? foreignKeyPlan({\n schema,\n table,\n column: relation.localKey,\n targetSchema: target.schema,\n targetTable: target.table,\n targetColumn: targetKey.column,\n onDelete: relation.onDelete ?? defaultBelongsToOnDelete(required),\n onUpdate: relation.onUpdate\n }) : undefined,\n source: { kind: \"relation\", propName: relation.name, slug }\n };\n}\n\n/** The `belongsTo` a planned link column stands for, or `undefined` for any other column. */\nconst linkRelationOf = (descriptor: TableDescriptor, column: ColumnPlan): BelongsToDescriptor | undefined => {\n if (column.source.kind !== \"relation\" || !column.source.propName) return undefined;\n const relation = relationOf(descriptor, column.source.propName);\n return relation?.kind === \"belongsTo\" ? relation : undefined;\n};\n\n/**\n * An auth-owned column's declared SQL type, as a tag.\n *\n * `auth-users-columns` states these as SQL because that is the grammar its three\n * creators write in; the plan needs the tag so nothing downstream has to parse a\n * type back apart. Deliberately exhaustive rather than a fallback: a column auth\n * adds with a type nobody mapped should say so here, not turn into `TEXT` in a\n * table the login flow reads.\n */\nconst AUTH_COLUMN_TYPES: Record<string, PgType> = {\n \"TEXT\": { kind: \"text\" },\n \"TEXT[]\": { kind: \"array\", of: { kind: \"text\" } },\n \"BOOLEAN\": { kind: \"boolean\" },\n \"JSONB\": { kind: \"jsonb\" },\n \"TIMESTAMP WITH TIME ZONE\": { kind: \"timestamptz\" }\n};\n\nconst authColumnType = (sqlType: string): PgType => {\n const mapped = AUTH_COLUMN_TYPES[sqlType];\n if (!mapped) {\n throw new Error(\n `\\`auth-users-columns\\` declares a column of type \"${sqlType}\", which the schema plan ` +\n \"has no tag for. Add it to `AUTH_COLUMN_TYPES` in schema/plan/plan-schema.ts.\"\n );\n }\n return mapped;\n};\n\n// ── A junction table ─────────────────────────────────────────────────────────\n\n/**\n * Which declaring side a junction is planned from.\n *\n * With one side, that side — as it always was, so a junction only one end\n * declares keeps the key every database already has. With both ends declaring\n * it, the planner used to take whichever it reached first, and the two doors\n * reach them in different orders: `db push` loads files by name, boot walks the\n * bundle's array. The same junction was keyed `(a_id, b_id)` by one and\n * `(b_id, a_id)` by the other, and a push against a boot-built database rebuilt\n * the key. Now the side whose table sorts first (then its junction column),\n * which is the order `db push` already used wherever a file is named after its\n * table. Compared by SQL table name, not slug: that is what every key in the\n * field was created by.\n */\nfunction canonicalJunctionSide(junction: TableJunction): TableJunctionSide {\n const [first, ...rest] = junction.declaringSides;\n if (rest.length === 0) return first ?? junction.endpoints[0];\n return [...junction.declaringSides].sort((a, b) => {\n const left = a.descriptor.table;\n const right = b.descriptor.table;\n if (left !== right) return left < right ? -1 : 1;\n return a.junctionColumn < b.junctionColumn ? -1 : a.junctionColumn > b.junctionColumn ? 1 : 0;\n })[0];\n}\n\nfunction planJunctionTable(\n junction: TableJunction,\n targetOf: (slug: string) => TableDescriptor,\n resolvePolicyTable: ResolvePolicyTable,\n triggerFunctionNeeded: { value: boolean }\n): TablePlan {\n const { relation, descriptor: source } = canonicalJunctionSide(junction);\n const { table } = junction;\n // Junctions live in `public`, full stop — `resolveTableJunctions` says so,\n // so it is where the tables are created and where the derived RLS\n // policies are applied. Inheriting the endpoint's schema put the junction\n // of any m2m onto `users` in `rebase` while its policies were still created\n // against `public.<junction>`: RLS enabled on one table, rows in another.\n const schema = junction.schema;\n const target = targetOf(relation.target);\n const { sourceKey: sourceColumn, targetKey: targetColumn } = relation.through;\n // Every declaring side agrees on the edge's lifetime; the first one wins.\n const onDelete = relation.onDelete ?? \"CASCADE\";\n\n const legacyFor = (endpoint: TableDescriptor, column: string): string | undefined => {\n // A junction column's default name is derived from the endpoint\n // table's slug — normally plural, so this is where the\n // singularization change lands: a `categories` endpoint used to give\n // `categorie_id` and now gives `category_id`. Recorded, not used.\n const slug = toSnakeCase(endpoint.slug);\n const legacy = legacyForeignKeyName(slug);\n return column === generateForeignKeyName(slug) && legacy !== column ? legacy : undefined;\n };\n\n const via = `relation \"${source.slug}.${relation.name}\"`;\n const endpoint = (endpointTable: TableDescriptor, column: string): ColumnPlan => {\n const key = tableKeyTarget(endpointTable, via);\n return {\n key: column,\n column,\n type: key.type,\n nullable: false,\n // Part of the composite key on {@link TablePlan.primaryKey}, not a\n // key of its own — an inline `PRIMARY KEY` here would be a second one.\n primaryKey: false,\n unique: false,\n legacyColumn: legacyFor(endpointTable, column),\n // Postgres refuses a foreign key into a view.\n foreignKey: endpointTable.kind === \"view\" ? undefined : foreignKeyPlan({\n schema,\n table,\n column,\n targetSchema: endpointTable.schema,\n targetTable: endpointTable.table,\n targetColumn: key.column,\n onDelete\n }),\n source: { kind: \"junction-key\" }\n };\n };\n\n const columns = [endpoint(source, sourceColumn), endpoint(target, targetColumn)];\n\n // ── The junction's own columns ───────────────────────────────────────────\n // `pivot`: the `role` on a membership, the `position` on a tag. Planned by\n // the same {@link planDescribedColumn} the tables use, so a pivot column\n // gets exactly the type, nullability, default, UNIQUE and enum type it\n // would get on a table.\n //\n // Not supported here, and deliberately: `indexes`, `search`, `vector` and\n // links — a pivot holds plain columns.\n const triggers: TriggerPlan[] = [];\n const keyColumns = new Set([sourceColumn, targetColumn]);\n for (const pivotColumn of junction.pivot) {\n // A pivot column on a key column would be a second definition of it;\n // the compiler leaves it out, and so does this.\n if (keyColumns.has(pivotColumn.column)) continue;\n columns.push(planDescribedColumn(pivotColumn, {\n site: junctionSite(junction, pivotColumn),\n slug: table,\n auth: false,\n triggers,\n triggerFunctionNeeded\n }));\n }\n\n // Junction tables are generated tables like any other: locked by default,\n // with derived policies — reads follow the endpoints' visibility, writes\n // follow the declaring side's update rules. Without them they were the one\n // kind of generated table with no RLS at all.\n const junctionTable = junctionPolicyTable(junction);\n const policies = withoutLiveSupersededNames(tableJunctionRules(junction).flatMap((rule, index) =>\n compileTableSecurityRule(junctionTable, rule, resolvePolicyTable, false, rule.name ?? `#${index}`)));\n\n return {\n schema,\n table,\n qualified: `${schema}.${table}`,\n varName: getTableVarName(table),\n kind: \"junction\",\n declaringSlugs: junction.declaringSides.map(side => side.descriptor.slug),\n columns,\n primaryKey: [sourceColumn, targetColumn],\n // Always, and with no opt-out: the junction is the platform's table,\n // not the author's. The key covers lookups by `sourceColumn`; the\n // reverse side of the link — `tags → posts` — filters on\n // `targetColumn`, which only this index serves.\n indexes: planForeignKeyIndexes(schema, table, columns, [sourceColumn, targetColumn], [],\n column => (column.source.kind === \"junction-key\" ? column.foreignKey?.column : undefined)),\n vectorColumns: [],\n policies,\n triggers,\n auth: false\n };\n}\n\n// ── Drizzle relations ────────────────────────────────────────────────────────\n\n/**\n * The `relations(...)` entries the generated file carries.\n *\n * Both sides of a link must share a `relationName` or Drizzle cannot pair them;\n * `tableRelationName` is the rule, and each side derives it independently.\n */\nfunction planRelations(\n tables: readonly TableDescriptor[],\n tableEntries: ReadonlyMap<string, TableEntry>,\n targetOf: (slug: string) => TableDescriptor\n): RelationPlan[] {\n const plans: RelationPlan[] = [];\n const keyOf = (descriptor: TableDescriptor, via: string): string => tableKeyTarget(descriptor, via).key;\n\n // Every relation whose foreign key lives on its target's table, grouped by\n // that target's slug, in table order and each table's relations in order.\n // Built once: a scan per table over every other table's relations is N²\n // in the table count.\n const fkOnTargetBySlug = new Map<string, Array<{ other: TableDescriptor; otherRel: RelationOfKind<\"hasOne\" | \"hasMany\"> }>>();\n for (const other of tables) {\n for (const otherRel of other.relations) {\n if (otherRel.kind !== \"hasOne\" && otherRel.kind !== \"hasMany\") continue;\n const list = fkOnTargetBySlug.get(otherRel.target) ?? [];\n list.push({ other, otherRel });\n fkOnTargetBySlug.set(otherRel.target, list);\n }\n }\n\n for (const [tableName, entry] of tableEntries) {\n const tableVar = getTableVarName(tableName);\n\n if (entry.kind === \"junction\") {\n // The side the junction was first reached from.\n const { relation, descriptor: source } = entry.junction.endpoints[0];\n const target = targetOf(relation.target);\n const via = `relation \"${source.slug}.${relation.name}\"`;\n // Each `one()` here pairs with a `many(junction, { relationName })`\n // on its endpoint, so each takes the name that endpoint's own\n // relation derives. The far side is the target's many-to-many\n // through this same junction; only a junction nothing points back\n // through needs the synthesized name.\n const owningRelationName = tableRelationName(relation, source, targetOf);\n const inverse = target.relations.find(r =>\n r.kind === \"manyToMany\" && bareTableName(r.through.table) === bareTableName(tableName));\n const inverseRelationName = inverse\n ? tableRelationName(inverse, target, targetOf)\n : `${tableName}_${relation.through.targetKey}`;\n plans.push({\n tableVar,\n key: relation.through.sourceKey,\n kind: \"one\",\n targetVar: getTableVarName(source.table),\n relationName: owningRelationName,\n fields: [relation.through.sourceKey],\n references: [keyOf(source, via)]\n });\n // A self-referencing link is its own inverse: one name, one\n // endpoint table, and drizzle refuses two relations named alike.\n if (inverseRelationName === owningRelationName) continue;\n // The file declares no variable for a view to pair with.\n if (target.kind === \"view\") continue;\n plans.push({\n tableVar,\n key: relation.through.targetKey,\n kind: \"one\",\n targetVar: getTableVarName(target.table),\n relationName: inverseRelationName,\n fields: [relation.through.targetKey],\n references: [keyOf(target, via)]\n });\n continue;\n }\n\n const descriptor = entry.descriptor;\n // An alias entry for the same foreign key would otherwise emit twice.\n const emitted = new Set<string>();\n for (const relation of descriptor.relations) {\n const target = targetOf(relation.target);\n // A link into a view is not a relation this file can describe: it\n // declares no table for one.\n if (target.kind === \"view\") continue;\n const targetVar = getTableVarName(target.table);\n const relationName = tableRelationName(relation, descriptor, targetOf);\n const dedupe = `${relationName}::${relation.kind}`;\n if (emitted.has(dedupe)) continue;\n emitted.add(dedupe);\n const via = `relation \"${descriptor.slug}.${relation.name}\"`;\n\n switch (relation.kind) {\n case \"belongsTo\":\n plans.push({\n tableVar,\n key: relation.name,\n kind: \"one\",\n targetVar,\n relationName,\n // The generated object is keyed by the column's KEY:\n // `user_id` is exposed as `userId`, and emitting the\n // column produces a file that does not compile.\n fields: [servedKeyOf(descriptor, relation.localKey)],\n references: [keyOf(target, via)]\n });\n break;\n case \"hasOne\":\n // The foreign key lives on the TARGET table, so this side\n // states the join from its own end: its source key against\n // the target's foreign key, under the owning side's name.\n // Drizzle has no `one()` paired by `relationName` alone,\n // and a bare `one(target)` is paired by table, which throws\n // once the target has two links back here or the link is to\n // its own table.\n plans.push({\n tableVar,\n key: relation.name,\n kind: \"one\",\n targetVar,\n relationName,\n fields: [relation.sourceKey ? servedKeyOf(descriptor, relation.sourceKey) : keyOf(descriptor, via)],\n references: [servedKeyOf(target, relation.foreignKey)],\n nullable: true\n });\n break;\n case \"hasMany\":\n plans.push({ tableVar, key: relation.name, kind: \"many\", targetVar, relationName });\n break;\n case \"manyToMany\":\n plans.push({\n tableVar,\n key: relation.name,\n kind: \"many\",\n targetVar: getTableVarName(relation.through.table),\n relationName\n });\n break;\n case \"via\":\n // A join chain is resolved at query time, not modelled as a\n // Drizzle relation.\n break;\n }\n }\n\n // Reciprocals the far side declares and this one does not. Drizzle\n // needs both halves of a pair to exist for a relational query to work.\n for (const { other, otherRel } of fkOnTargetBySlug.get(descriptor.slug) ?? []) {\n if (other.slug === descriptor.slug) continue;\n const relationName = tableRelationName(otherRel, other, targetOf);\n const dedupe = `${relationName}::belongsTo`;\n if (emitted.has(dedupe)) continue;\n emitted.add(dedupe);\n const otherVar = getTableVarName(other.table);\n const fieldKey = servedKeyOf(descriptor, otherRel.foreignKey);\n plans.push({\n tableVar,\n key: `_synth_${otherVar}_${fieldKey}`,\n kind: \"one\",\n targetVar: otherVar,\n relationName,\n fields: [fieldKey],\n // The column the far side points at: its primary key,\n // unless the link names another one with `sourceKey`.\n references: [otherRel.sourceKey\n ? servedKeyOf(other, otherRel.sourceKey)\n : keyOf(other, `relation \"${other.slug}.${otherRel.name}\"`)]\n });\n }\n }\n\n return plans;\n}\n\nexport { SET_UPDATED_AT_FN };\n"],"mappings":";;;;;;;;;;;;;;;;;AASA,IAAa,eAAe,YAA6B,cACrD,aAAa,YAAY,SAAS,KAAK,UAAU,SAAS;;;;;;;;;;;;;;;;AAiB9D,SAAgB,kBACZ,UACA,QACA,UACM;CACN,IAAI,SAAS,SAAS,aAAa,OAAO,GAAG,OAAO,MAAM,GAAG,YAAY,QAAQ,SAAS,QAAQ;CAClG,IAAI,SAAS,SAAS,aAAa,SAAS,SAAS,UAAU;EAC3D,MAAM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gBAAgB,MAAM,KAAK;GAC5C,MAAM,WAAW,YAAY,YAAY,SAAS,UAAU;GAC5D,MAAM,KAAK;IACP;IACA,KAAK,UAAU,SAAS,GAAG;IAC3B,MAAM;IACN,WAAW;IACX;IACA,QAAQ,CAAC,QAAQ;IAGjB,YAAY,CAAC,SAAS,YAChB,YAAY,OAAO,SAAS,SAAS,IACrC,MAAM,OAAO,aAAa,MAAM,KAAK,GAAG,SAAS,KAAK,EAAE,CAAC;GACnE,CAAC;EACL;CACJ;CAEA,OAAO;AACX"}
@@ -1,17 +1,17 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { i as __exportAll } from "./cli-prompt-DXG0yk-h.js";
4
- import { c as planCollectionPolicies, n as generatePostgresPoliciesDdl } from "./generate-postgres-ddl-logic-Dg0bcENZ.js";
4
+ import { n as generatePostgresPoliciesDdl, u as planTablePolicies } from "./generate-postgres-ddl-logic-B8huc03c.js";
5
5
  import { RLS_UID_SQL } from "@rebasepro/types";
6
6
  import { ADMIN_REQUEST_POLICY_SUFFIX, toPostgresIdentifier } from "@rebasepro/utils";
7
7
  //#region src/security/policy-drift.ts
8
8
  /**
9
9
  * Compare the RLS policies a database actually has against the ones the
10
- * collections describe.
10
+ * tables describe.
11
11
  *
12
- * Policies live in Postgres; the collection config is only their *source*.
12
+ * Policies live in Postgres; the table definitions are only their *source*.
13
13
  * Nothing reconciled the two, which is how the demo database served empty
14
- * collections indefinitely: its policies granted `TO authenticated` (a Supabase
14
+ * tables indefinitely: its policies granted `TO authenticated` (a Supabase
15
15
  * role name) while requests run as `rebase_user`, so RLS filtered every row.
16
16
  * The config was later corrected and the database never noticed — an empty
17
17
  * table is indistinguishable from a table with no data.
@@ -120,7 +120,7 @@ async function readLivePolicies(client, schemas) {
120
120
  }));
121
121
  }
122
122
  /**
123
- * Tables the collections describe whose RLS switch is off.
123
+ * Tables the tables describe whose RLS switch is off.
124
124
  *
125
125
  * Read from `pg_class` because `pg_policies` cannot answer it: disabling RLS
126
126
  * leaves the policy rows in place, so every other comparison in this file keeps
@@ -158,7 +158,7 @@ async function readTablesWithRlsOff(client, tables) {
158
158
  * Both schema spellings are matched. The helpers moved from `auth` to `rebase`
159
159
  * in 1.0, and this check reads policies *as the database stored them*: a
160
160
  * database pushed before the move still holds `auth.uid()` until it is
161
- * recompiled, while everything written since — including raw `securityRules`
161
+ * recompiled, while everything written since — including raw `rls` rule
162
162
  * SQL, which the compiler rewrites on the way in — stores `rebase.uid()`.
163
163
  * Matching only the pre-1.0 name made the check blind to every policy a current
164
164
  * release could write, which is precisely the set still worth scanning.
@@ -189,24 +189,24 @@ var keyOf = (p) => `${p.schema}.${p.table}.${p.name}`;
189
189
  /** {@link AdminPoliciesExpectation} as a yes or no. Left out, `TO rebase_admin`, as compiled. */
190
190
  /** See `adminRequestCompanionsSafeForCli`. */
191
191
  async function companionsSafe(client) {
192
- const { adminRequestCompanionsSafeForCli } = await import("./rls-enforcement-Cc_UhOxb.js").then((n) => n.y);
192
+ const { adminRequestCompanionsSafeForCli } = await import("./rls-enforcement-DB5HHj96.js").then((n) => n.y);
193
193
  return adminRequestCompanionsSafeForCli(async (text) => (await client.query(text)).rows);
194
194
  }
195
195
  async function resolveAdminPolicies(client, expectation) {
196
196
  if (expectation !== "detect") return expectation !== false;
197
- const { adminPoliciesLiveForCli } = await import("./rls-enforcement-Cc_UhOxb.js").then((n) => n.y);
197
+ const { adminPoliciesLiveForCli } = await import("./rls-enforcement-DB5HHj96.js").then((n) => n.y);
198
198
  return adminPoliciesLiveForCli(async (text) => (await client.query(text)).rows);
199
199
  }
200
200
  /**
201
- * The policies the collections declare, parsed from the DDL `db push` writes —
201
+ * The policies the tables declare, parsed from the DDL `db push` writes —
202
202
  * with the ones the compiler put `TO rebase_admin` read as `TO public` where
203
203
  * `adminRoleAvailable` is false, as the boot and the push then write them. A
204
204
  * rule that names `rebase_admin` itself keeps it.
205
205
  */
206
- function expectedPolicies(collections, adminRoleAvailable) {
207
- const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(collections));
206
+ function expectedPolicies(compiledTables, adminRoleAvailable) {
207
+ const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(compiledTables));
208
208
  if (adminRoleAvailable) return expected;
209
- const moved = new Set(planCollectionPolicies(collections).flatMap((plan) => plan.policies.filter((policy) => policy.adminTarget).map((policy) => `${plan.schema}.${plan.table}.${policy.name}`)));
209
+ const moved = new Set(planTablePolicies(compiledTables).flatMap((plan) => plan.policies.filter((policy) => policy.adminTarget).map((policy) => `${plan.schema}.${plan.table}.${policy.name}`)));
210
210
  return expected.map((p) => moved.has(keyOf(p)) ? {
211
211
  ...p,
212
212
  roles: ["public"]
@@ -218,8 +218,8 @@ function expectedPolicies(collections, adminRoleAvailable) {
218
218
  * `policies.sql`, so not among the expected policies, and not orphans either
219
219
  * when they are there in that shape. Keyed `schema.table.name`.
220
220
  */
221
- function adminRequestCompanions(collections) {
222
- const ddl = planCollectionPolicies(collections, { adminRequestRoleAvailable: true }).flatMap((plan) => plan.policies.filter((policy) => policy.adminRequestTarget).flatMap((policy) => policy.statements)).join("\n");
221
+ function adminRequestCompanions(compiledTables) {
222
+ const ddl = planTablePolicies(compiledTables, { adminRequestRoleAvailable: true }).flatMap((plan) => plan.policies.filter((policy) => policy.adminRequestTarget).flatMap((policy) => policy.statements)).join("\n");
223
223
  return new Map(parseExpectedPolicies(ddl).map((p) => [keyOf(p), p]));
224
224
  }
225
225
  var sameRoles = (a, b) => a.length === b.length && [...a].sort().join(",") === [...b].sort().join(",");
@@ -239,10 +239,10 @@ var sameRoles = (a, b) => a.length === b.length && [...a].sort().join(",") === [
239
239
  * whose `qual` was NULL, matching on every field this checked and denying 100%
240
240
  * of reads. The same blindness would hide a policy that fails open.
241
241
  */
242
- async function checkPolicyDrift(client, collections, options = {}) {
242
+ async function checkPolicyDrift(client, compiledTables, options = {}) {
243
243
  const adminLive = await resolveAdminPolicies(client, options.adminRoleAvailable);
244
- const expected = expectedPolicies(collections, adminLive);
245
- const companions = adminLive && await companionsSafe(client) ? adminRequestCompanions(collections) : /* @__PURE__ */ new Map();
244
+ const expected = expectedPolicies(compiledTables, adminLive);
245
+ const companions = adminLive && await companionsSafe(client) ? adminRequestCompanions(compiledTables) : /* @__PURE__ */ new Map();
246
246
  const schemas = [...new Set(expected.map((p) => p.schema))];
247
247
  if (schemas.length === 0) return {
248
248
  missing: [],
@@ -322,12 +322,12 @@ function isGeneratedPolicyName(name, table) {
322
322
  /**
323
323
  * Drop the policies an earlier push superseded but never removed.
324
324
  *
325
- * Only touches tables the collections describe — a table with no expected
325
+ * Only touches tables the tables describe — a table with no expected
326
326
  * policy is not ours to reconcile, and scanning by schema alone would sweep up
327
327
  * policies belonging to something else sharing the database.
328
328
  */
329
- async function dropOrphanedPolicies(client, drift, collections) {
330
- const { dropped, kept } = partitionOrphans(drift, collections);
329
+ async function dropOrphanedPolicies(client, drift, compiledTables) {
330
+ const { dropped, kept } = partitionOrphans(drift, compiledTables);
331
331
  for (const p of dropped) await client.query(`DROP POLICY IF EXISTS "${p.name}" ON "${p.schema}"."${p.table}"`);
332
332
  return {
333
333
  dropped,
@@ -338,8 +338,8 @@ async function dropOrphanedPolicies(client, drift, collections) {
338
338
  * Which orphans {@link dropOrphanedPolicies} drops and which it keeps, decided
339
339
  * without dropping anything: what `db push --dry-run` lists.
340
340
  */
341
- function partitionOrphans(drift, collections) {
342
- const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(collections));
341
+ function partitionOrphans(drift, compiledTables) {
342
+ const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(compiledTables));
343
343
  const managed = new Set(expected.map((p) => `${p.schema}.${p.table}`));
344
344
  const cleanup = {
345
345
  dropped: [],
@@ -362,12 +362,12 @@ function partitionOrphans(drift, collections) {
362
362
  * stay, admitting every admin to every row, on a deployment whose boot never
363
363
  * provisions. `rebase db migrate` runs this after it applies.
364
364
  */
365
- async function dropStaleAdminRequestCompanions(client, collections, options = {}) {
366
- const drift = await checkPolicyDrift(client, collections, options);
365
+ async function dropStaleAdminRequestCompanions(client, compiledTables, options = {}) {
366
+ const drift = await checkPolicyDrift(client, compiledTables, options);
367
367
  const stale = partitionOrphans({
368
368
  ...drift,
369
369
  orphaned: drift.orphaned.filter((p) => ADMIN_REQUEST_POLICY_SUFFIX.test(p.name))
370
- }, collections).dropped;
370
+ }, compiledTables).dropped;
371
371
  for (const p of stale) await client.query(`DROP POLICY IF EXISTS "${p.name.replace(/"/g, "\"\"")}" ON "${p.schema.replace(/"/g, "\"\"")}"."${p.table.replace(/"/g, "\"\"")}"`);
372
372
  return stale;
373
373
  }
@@ -383,19 +383,19 @@ function formatPolicyDrift(drift) {
383
383
  lines.push(` Fix: ALTER TABLE "<schema>"."<table>" ENABLE ROW LEVEL SECURITY; or re-run \`rebase db push\`.`);
384
384
  }
385
385
  if (drift.missing.length > 0) {
386
- lines.push(" Missing — described by your collections, absent from the database:");
386
+ lines.push(" Missing — described by your tables, absent from the database:");
387
387
  for (const p of drift.missing) lines.push(` • ${p.schema}.${p.table} → "${p.name}" (${p.command} TO ${p.roles.join(", ")})`);
388
388
  lines.push(" Run `rebase db push` to apply them.");
389
389
  }
390
390
  if (drift.orphaned.length > 0) {
391
391
  const superseded = drift.orphaned.filter((p) => isGeneratedPolicyName(p.name, p.table));
392
392
  const unowned = drift.orphaned.filter((p) => !isGeneratedPolicyName(p.name, p.table));
393
- lines.push(" Orphaned — in the database, described by no collection:");
393
+ lines.push(" Orphaned — in the database, described by no table:");
394
394
  for (const p of drift.orphaned) lines.push(` • ${p.schema}.${p.table} → "${p.name}" (${p.command} TO ${p.roles.join(", ")})`);
395
395
  if (superseded.length > 0) lines.push(` ${superseded.map((p) => `"${p.name}"`).join(", ")}: left behind by an earlier push, when its rule changed. The next \`rebase db push\` drops it.`);
396
396
  if (unowned.length > 0) {
397
397
  lines.push(` ${unowned.map((p) => `"${p.name}"`).join(", ")}: written by hand or by another tool, and still in force.`);
398
- lines.push(" To keep one, describe it in its collection's `securityRules` (Studio's RLS view imports it);");
398
+ lines.push(" To keep one, describe it in its table's `rls` in backend/schema (Studio's RLS view imports it);");
399
399
  lines.push(" if it is stale, drop it by hand.");
400
400
  }
401
401
  }
@@ -418,4 +418,4 @@ function formatPolicyDrift(drift) {
418
418
  //#endregion
419
419
  export { isGeneratedPolicyName as a, resolveAdminPolicies as c, hasDrift as i, expectedPolicies as n, partitionOrphans as o, formatPolicyDrift as r, policy_drift_exports as s, checkPolicyDrift as t };
420
420
 
421
- //# sourceMappingURL=policy-drift-C-m0uWHH.js.map
421
+ //# sourceMappingURL=policy-drift-BVMyqHSa.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy-drift-BVMyqHSa.js","names":[],"sources":["../src/security/policy-drift.ts"],"sourcesContent":["/**\n * Compare the RLS policies a database actually has against the ones the\n * tables describe.\n *\n * Policies live in Postgres; the table definitions are only their *source*.\n * Nothing reconciled the two, which is how the demo database served empty\n * tables indefinitely: its policies granted `TO authenticated` (a Supabase\n * role name) while requests run as `rebase_user`, so RLS filtered every row.\n * The config was later corrected and the database never noticed — an empty\n * table is indistinguishable from a table with no data.\n *\n * Expected policies are parsed from `generatePostgresPoliciesDdl`, the same\n * function `db push` uses to write `.rebase/sql/policies.sql`, so this compares\n * against exactly what would be applied rather than a reimplementation.\n */\nimport { RLS_UID_SQL, type CompiledTable } from \"@rebasepro/types\";\nimport { ADMIN_REQUEST_POLICY_SUFFIX, toPostgresIdentifier } from \"@rebasepro/utils\";\n\nimport { generatePostgresPoliciesDdl, planTablePolicies } from \"../schema/generate-postgres-ddl-logic\";\n\nexport interface PolicyRef {\n schema: string;\n table: string;\n name: string;\n /** Roles in the TO clause. */\n roles: string[];\n /** SELECT / INSERT / UPDATE / DELETE / ALL. */\n command: string;\n /** Whether a USING clause is present at all (not what it says). */\n hasUsing: boolean;\n /** Whether a WITH CHECK clause is present at all (not what it says). */\n hasWithCheck: boolean;\n /**\n * PERMISSIVE or RESTRICTIVE — the `AS` clause.\n *\n * An exact catalogue value on both sides, so it belongs with roles and\n * command rather than with the expression text. It matters more than either:\n * permissive policies are ORed together and restrictive ones ANDed, so a rule\n * declared `mode: \"restrictive\"` whose live policy is PERMISSIVE has had its\n * gate turned from a requirement into an alternative — the maximally\n * permissive way for this to be wrong.\n *\n * The DDL regex captured this from the start and the destructuring threw it\n * away; `pg_policies.permissive` was never selected.\n */\n mode?: \"PERMISSIVE\" | \"RESTRICTIVE\";\n /**\n * The live clause text, when read from `pg_policies`. Present only for live\n * policies (the expected side is parsed from DDL and does not carry it).\n * Used solely for the insecure-tautology scan, not for divergence — Postgres\n * rewrites this text, so it is not safe to diff against expected.\n */\n qual?: string | null;\n withCheck?: string | null;\n}\n\nexport interface PolicyDrift {\n /** Described by the tables, absent from the database. */\n missing: PolicyRef[];\n /** In the database, described by no table — stale pushes live here. */\n orphaned: PolicyRef[];\n /** Same policy name, different roles or command. */\n diverged: { expected: PolicyRef; actual: PolicyRef; differences: string[] }[];\n /**\n * A live policy whose expression is the known-permissive tautology\n * `rebase.uid() IS NOT NULL` — true for anonymous visitors too, because the\n * user path coerces a blank id to the `'anonymous'` sentinel. This is what\n * `policy.authenticated()` used to compile to, so a database pushed before\n * that fix carries it, and neither the name, roles, command nor clause\n * *presence* differs from the corrected policy — the only thing that changed\n * is the expression text, which this checker otherwise (correctly) ignores.\n * So it is the one drift that hides from every other check here.\n *\n * @see reason a sentence naming the clause and what to do.\n */\n insecure: { policy: PolicyRef; reason: string }[];\n /**\n * A table the tables describe whose RLS switch is off.\n *\n * `ALTER TABLE posts DISABLE ROW LEVEL SECURITY` leaves every row in\n * `pg_policies` untouched, so before this category every expected policy\n * still matched on name, roles, command and clause presence and the checker\n * reported clean — on a table Postgres was applying no filter to at all.\n * Requests run as `rebase_user`, which holds full DML, so the table is wide\n * open while `doctor` certifies it.\n *\n * `forced` reports `relforcerowsecurity`, which is what also subjects the\n * table's *owner* to its policies. Its absence is not drift on its own —\n * Rebase does not connect as the owner in the request path — so it is\n * reported for context rather than raised as a failure.\n */\n rlsDisabled: { schema: string; table: string; forced: boolean }[];\n}\n\nexport interface Queryable {\n query<R>(text: string, values?: unknown[]): Promise<{ rows: R[] }>;\n}\n\n// The trailing group captures whichever clause follows the TO list, which is\n// what tells us the clause is present.\nconst CREATE_POLICY = /CREATE POLICY \"([^\"]+)\" ON \"([^\"]+)\"\\.\"([^\"]+)\"\\s+AS (\\w+)\\s+FOR (\\w+)\\s+TO ([^\\n]+?)(\\s+USING\\s*\\(|\\s+WITH CHECK\\s*\\(|;)/gi;\n\nconst WITH_CHECK_NEXT = /^\\s+WITH CHECK\\s*\\(/i;\n\n/**\n * Index just past the `)` closing a clause whose `(` ends at `open`.\n *\n * Needed because a policy expression nests parens and can contain a quoted\n * literal holding either character, so \"find the next `)`\" would stop early and\n * miss the `WITH CHECK` that follows.\n */\nfunction clauseEnd(ddl: string, open: number): number {\n let depth = 1;\n let inQuote = false;\n for (let i = open; i < ddl.length; i++) {\n const c = ddl[i];\n if (inQuote) {\n // '' is an escaped quote inside a string, not a close.\n if (c === \"'\") {\n if (ddl[i + 1] === \"'\") i++;\n else inQuote = false;\n }\n continue;\n }\n if (c === \"'\") inQuote = true;\n else if (c === \"(\") depth++;\n else if (c === \")\" && --depth === 0) return i + 1;\n }\n return ddl.length;\n}\n\n/**\n * `AS PERMISSIVE` / `AS RESTRICTIVE` from either side, or undefined.\n *\n * The DDL spells it as a bare word; `pg_policies.permissive` is the string\n * `\"PERMISSIVE\"`/`\"RESTRICTIVE\"` on modern Postgres but a boolean on some\n * drivers and older servers, so both are accepted. Anything unrecognised\n * becomes `undefined` and the comparison below skips it rather than inventing\n * drift from a shape we did not anticipate.\n */\nfunction normalizeMode(raw: unknown): \"PERMISSIVE\" | \"RESTRICTIVE\" | undefined {\n if (typeof raw === \"boolean\") return raw ? \"PERMISSIVE\" : \"RESTRICTIVE\";\n if (typeof raw !== \"string\") return undefined;\n const upper = raw.trim().toUpperCase();\n if (upper === \"PERMISSIVE\" || upper === \"TRUE\" || upper === \"T\") return \"PERMISSIVE\";\n if (upper === \"RESTRICTIVE\" || upper === \"FALSE\" || upper === \"F\") return \"RESTRICTIVE\";\n return undefined;\n}\n\n/**\n * Parse the generated DDL rather than rebuilding the shape by hand.\n *\n * Each name is the one Postgres stores — its first 63 bytes — because that is\n * the name every live policy is compared under. A rule's name can be longer,\n * and read as written its policy was both \"missing\" and, once cut to a name of\n * the generated shape, an \"orphan\" the push's reconcile dropped right after\n * `policies.sql` created it.\n */\nexport function parseExpectedPolicies(ddl: string): PolicyRef[] {\n const found: PolicyRef[] = [];\n for (const m of ddl.matchAll(CREATE_POLICY)) {\n const [, name, schema, table, modeRaw, command, rolesRaw, clause] = m;\n const roles = rolesRaw\n .split(\",\")\n .map((r) => r.trim().replace(/^\"|\"$/g, \"\"))\n .filter(Boolean);\n\n // The generator emits USING before WITH CHECK, so what follows the TO\n // list settles USING; WITH CHECK is then whatever follows that clause.\n const hasUsing = /USING/i.test(clause);\n const hasWithCheck = hasUsing\n ? WITH_CHECK_NEXT.test(ddl.slice(clauseEnd(ddl, m.index + m[0].length)))\n : /WITH CHECK/i.test(clause);\n\n found.push({\n schema, table, name: toPostgresIdentifier(name), roles,\n command: command.toUpperCase(),\n hasUsing, hasWithCheck,\n mode: normalizeMode(modeRaw)\n });\n }\n return found;\n}\n\nasync function readLivePolicies(client: Queryable, schemas: string[]): Promise<PolicyRef[]> {\n const { rows } = await client.query<{\n schemaname: string; tablename: string; policyname: string; roles: string[] | string; cmd: string;\n qual: string | null; with_check: string | null; permissive: string | boolean | null;\n }>(\n `SELECT schemaname, tablename, policyname, roles, cmd, qual, with_check, permissive\n FROM pg_policies\n WHERE schemaname = ANY($1)`,\n [schemas]\n );\n\n return rows.map((r) => ({\n schema: r.schemaname,\n table: r.tablename,\n name: r.policyname,\n // node-postgres yields text[] as an array; some drivers hand back \"{a,b}\".\n roles: Array.isArray(r.roles)\n ? r.roles\n : String(r.roles ?? \"\").replace(/^\\{|\\}$/g, \"\").split(\",\").filter(Boolean),\n command: (r.cmd ?? \"ALL\").toUpperCase(),\n // Presence only. Postgres rewrites the text, but it does not invent or\n // drop a clause: NULL here means the policy genuinely has none.\n hasUsing: r.qual != null,\n hasWithCheck: r.with_check != null,\n mode: normalizeMode(r.permissive),\n qual: r.qual,\n withCheck: r.with_check\n }));\n}\n\n/**\n * Tables the tables describe whose RLS switch is off.\n *\n * Read from `pg_class` because `pg_policies` cannot answer it: disabling RLS\n * leaves the policy rows in place, so every other comparison in this file keeps\n * matching while Postgres applies none of them.\n *\n * Only tables that expect at least one policy are considered. A table with no\n * declared rules is not asserting anything about RLS, and reporting it would\n * make the check noisy on exactly the projects least able to judge the noise.\n */\nasync function readTablesWithRlsOff(\n client: Queryable,\n tables: { schema: string; table: string }[]\n): Promise<{ schema: string; table: string; forced: boolean }[]> {\n if (tables.length === 0) return [];\n const { rows } = await client.query<{\n schemaname: string; tablename: string; relrowsecurity: boolean; relforcerowsecurity: boolean;\n }>(\n `SELECT n.nspname AS schemaname,\n c.relname AS tablename,\n c.relrowsecurity,\n c.relforcerowsecurity\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relkind = 'r'\n AND (n.nspname || '.' || c.relname) = ANY($1)`,\n [tables.map((t) => `${t.schema}.${t.table}`)]\n );\n\n return rows\n .filter((r) => !r.relrowsecurity)\n .map((r) => ({\n schema: r.schemaname,\n table: r.tablename,\n forced: !!r.relforcerowsecurity\n }));\n}\n\n/**\n * The permissive tautology `rebase.uid() IS NOT NULL`, without the\n * `<> 'anonymous'` guard that makes it mean \"signed in\".\n *\n * Whitespace varies with Postgres's rewrite, so match on a collapsed form. The\n * guard clause ({@link EXCLUDES_ANONYMOUS}, in any spelling) is what\n * distinguishes the corrected policy from the stale one, so its presence\n * clears the text.\n *\n * Both schema spellings are matched. The helpers moved from `auth` to `rebase`\n * in 1.0, and this check reads policies *as the database stored them*: a\n * database pushed before the move still holds `auth.uid()` until it is\n * recompiled, while everything written since — including raw `rls` rule\n * SQL, which the compiler rewrites on the way in — stores `rebase.uid()`.\n * Matching only the pre-1.0 name made the check blind to every policy a current\n * release could write, which is precisely the set still worth scanning.\n */\nfunction isPermissiveAuthTautology(clause: string | null | undefined): boolean {\n if (!clause) return false;\n const flat = clause.toLowerCase().replace(/\\s+/g, \" \");\n // The call bare, or wrapped as an initPlan, which Postgres stores as\n // `( SELECT rebase.uid() AS uid)`.\n if (!/\\b(?:rebase|auth)\\.uid\\s*\\(\\s*\\)(?:\\s+as\\s+\\w+\\s*\\))?\\s*is not null/.test(flat)) return false;\n return !EXCLUDES_ANONYMOUS.some((guard) => guard.test(flat));\n}\n\n/**\n * The guard that makes the null test mean \"signed in\": the anonymous\n * sentinel excluded, in every spelling a policy reaches the catalogue in.\n *\n * `policy.authenticated()` compiles to `NOT IN ('anonymous', 'anon')`, which\n * Postgres stores as `<> ALL (ARRAY['anonymous'::text, 'anon'::text])`. Only\n * `<> 'anonymous'` was recognised, so `doctor` and every `db push` called each\n * `authenticated()` and `registered()` policy the insecure tautology. A list\n * that leaves out `'anonymous'` excludes nobody a signed-out request arrives\n * as, and does not clear it.\n */\nconst EXCLUDES_ANONYMOUS: RegExp[] = [\n /(?:<>|!=)\\s*'anonymous'/,\n /(?:<>|!=)\\s*all\\s*\\(\\s*array\\s*\\[[^\\]]*'anonymous'/,\n /\\bnot in\\s*\\([^)]*'anonymous'/\n];\n\nconst keyOf = (p: PolicyRef) => `${p.schema}.${p.table}.${p.name}`;\n\n/**\n * Where the server-or-admin policies are expected: `TO rebase_admin` (`true`),\n * `TO public` (`false`), or `\"detect\"` — read off the database as a boot on\n * this connection would decide it (`adminPoliciesLiveForCli`). A boot whose\n * admin switch is not live writes them `TO public`, and that is not drift.\n */\nexport type AdminPoliciesExpectation = boolean | \"detect\";\n\n/** {@link AdminPoliciesExpectation} as a yes or no. Left out, `TO rebase_admin`, as compiled. */\n/** See `adminRequestCompanionsSafeForCli`. */\nasync function companionsSafe(client: Queryable): Promise<boolean> {\n const { adminRequestCompanionsSafeForCli } = await import(\"./rls-enforcement\");\n return adminRequestCompanionsSafeForCli(async (text) => (await client.query<Record<string, unknown>>(text)).rows);\n}\n\nexport async function resolveAdminPolicies(client: Queryable, expectation: AdminPoliciesExpectation | undefined): Promise<boolean> {\n if (expectation !== \"detect\") return expectation !== false;\n const { adminPoliciesLiveForCli } = await import(\"./rls-enforcement\");\n return adminPoliciesLiveForCli(async (text) => (await client.query<Record<string, unknown>>(text)).rows);\n}\n\n/**\n * The policies the tables declare, parsed from the DDL `db push` writes —\n * with the ones the compiler put `TO rebase_admin` read as `TO public` where\n * `adminRoleAvailable` is false, as the boot and the push then write them. A\n * rule that names `rebase_admin` itself keeps it.\n */\nexport function expectedPolicies(compiledTables: readonly CompiledTable[], adminRoleAvailable: boolean): PolicyRef[] {\n const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(compiledTables));\n if (adminRoleAvailable) return expected;\n const moved = new Set(planTablePolicies(compiledTables).flatMap(plan =>\n plan.policies.filter(policy => policy.adminTarget).map(policy => `${plan.schema}.${plan.table}.${policy.name}`)));\n return expected.map(p => moved.has(keyOf(p)) ? { ...p, roles: [\"public\"] } : p);\n}\n/**\n * The `TO rebase_admin_request USING (true)` companions a boot writes beside\n * the admin-only policies when it has made that role safe — never in\n * `policies.sql`, so not among the expected policies, and not orphans either\n * when they are there in that shape. Keyed `schema.table.name`.\n */\nfunction adminRequestCompanions(compiledTables: readonly CompiledTable[]): Map<string, PolicyRef> {\n const ddl = planTablePolicies(compiledTables, { adminRequestRoleAvailable: true })\n .flatMap(plan => plan.policies.filter(policy => policy.adminRequestTarget).flatMap(policy => policy.statements))\n .join(\"\\n\");\n return new Map(parseExpectedPolicies(ddl).map(p => [keyOf(p), p]));\n}\n\nconst sameRoles = (a: string[], b: string[]) =>\n a.length === b.length && [...a].sort().join(\",\") === [...b].sort().join(\",\");\n\n/**\n * Diff expected against live.\n *\n * Compares names, roles, command, and whether each clause exists — all exact\n * values. Policy expression *text* is deliberately not compared: Postgres\n * rewrites `qual`/`with_check` when storing them (parenthesising, casting,\n * schema-qualifying), so text comparison reports drift that does not exist, and\n * a check that cries wolf gets ignored.\n *\n * Presence is not text, though. A NULL `qual` is not a rewrite of an\n * expression, it is the absence of one, and absence has no false-positive risk:\n * either the generator emitted a clause or it did not. That distinction is worth\n * the extra comparison — a production database was found with a SELECT policy\n * whose `qual` was NULL, matching on every field this checked and denying 100%\n * of reads. The same blindness would hide a policy that fails open.\n */\nexport async function checkPolicyDrift(\n client: Queryable,\n compiledTables: readonly CompiledTable[],\n options: { adminRoleAvailable?: AdminPoliciesExpectation } = {}\n): Promise<PolicyDrift> {\n const adminLive = await resolveAdminPolicies(client, options.adminRoleAvailable);\n const expected = expectedPolicies(compiledTables, adminLive);\n // A live companion is Rebase's only where a boot could have written it:\n // the admin switch live, and nothing but the admin request roles holding\n // its role. Otherwise it is an orphan — and push drops it.\n const companions = adminLive && await companionsSafe(client)\n ? adminRequestCompanions(compiledTables)\n : new Map<string, PolicyRef>();\n const schemas = [...new Set(expected.map((p) => p.schema))];\n // Nothing expected means nothing to reconcile against; scanning every\n // schema would report the whole database as orphaned.\n if (schemas.length === 0) return { missing: [], orphaned: [], diverged: [], insecure: [], rlsDisabled: [] };\n\n const live = await readLivePolicies(client, schemas);\n const liveByKey = new Map(live.map((p) => [keyOf(p), p]));\n const expectedByKey = new Map(expected.map((p) => [keyOf(p), p]));\n\n const drift: PolicyDrift = { missing: [], orphaned: [], diverged: [], insecure: [], rlsDisabled: [] };\n\n // Before comparing policy against policy: is the switch even on? A table\n // with RLS disabled matches every expected policy on every field compared\n // below, so this has to be asked separately or it cannot be asked at all.\n const expectedTables = [...new Map(\n expected.map((p) => [`${p.schema}.${p.table}`, { schema: p.schema, table: p.table }])\n ).values()];\n drift.rlsDisabled = await readTablesWithRlsOff(client, expectedTables);\n\n // Scan every live policy for the permissive tautology. This is deliberately\n // independent of the name-keyed diff below: a database pushed before the\n // `authenticated()` fix matches its expected policy on name, roles, command\n // and clause presence, so nothing else here would flag it.\n for (const p of live) {\n const clause = isPermissiveAuthTautology(p.qual)\n ? \"USING\"\n : isPermissiveAuthTautology(p.withCheck) ? \"WITH CHECK\" : null;\n if (clause) {\n drift.insecure.push({\n policy: p,\n reason: `${clause} is \\`${RLS_UID_SQL} IS NOT NULL\\`, which is true for anonymous ` +\n `visitors too — this grants access to signed-out requests. It predates the ` +\n `\\`policy.authenticated()\\` fix; re-run \\`rebase db push\\` to tighten it.`\n });\n }\n }\n\n for (const [key, want] of expectedByKey) {\n const got = liveByKey.get(key);\n if (!got) {\n drift.missing.push(want);\n continue;\n }\n const differences: string[] = [];\n if (!sameRoles(want.roles, got.roles)) {\n differences.push(`roles: expected [${want.roles.join(\", \")}], database has [${got.roles.join(\", \")}]`);\n }\n if (want.command !== got.command) {\n differences.push(`command: expected ${want.command}, database has ${got.command}`);\n }\n // Skipped when either side is unknown: an unrecognised catalogue shape\n // should not manufacture drift. See `normalizeMode`.\n if (want.mode && got.mode && want.mode !== got.mode) {\n differences.push(\n `mode: expected ${want.mode}, database has ${got.mode}` +\n (got.mode === \"PERMISSIVE\"\n ? \" — a RESTRICTIVE rule is ANDed with the others, a PERMISSIVE one is ORed, so this policy now widens access instead of narrowing it\"\n : \" — a PERMISSIVE rule is ORed with the others, a RESTRICTIVE one is ANDed, so this policy now narrows access instead of widening it\")\n );\n }\n for (const clause of [\"USING\", \"WITH CHECK\"] as const) {\n const key = clause === \"USING\" ? \"hasUsing\" : \"hasWithCheck\";\n if (want[key] === got[key]) continue;\n differences.push(want[key]\n ? `${clause}: expected an expression, database has none — this policy matches no rows`\n : `${clause}: expected none, database has an expression`);\n }\n if (differences.length > 0) drift.diverged.push({ expected: want, actual: got, differences });\n }\n\n for (const [key, got] of liveByKey) {\n if (expectedByKey.has(key)) continue;\n // A boot's admin-request companion, in exactly the shape it writes —\n // anything else under that name is reported like any other stranger.\n const companion = companions.get(key);\n if (companion && sameRoles(companion.roles, got.roles) && companion.command === got.command\n && got.mode === \"PERMISSIVE\" && companion.hasUsing === got.hasUsing && companion.hasWithCheck === got.hasWithCheck) continue;\n drift.orphaned.push(got);\n }\n\n return drift;\n}\n\n/**\n * Does this name look like one the generator produced for this table?\n *\n * Unnamed rules compile to `<table>_<op>_<sha1[0:7]>` (plus `_<idx>` when one\n * rule spans several operations), and the hash covers the rule's semantics — so\n * *editing* a rule renames its policy. The policy under the old name is left\n * behind by `db push`, which only DROPs the names it is about to CREATE, and\n * Postgres ORs PERMISSIVE policies together: a superseded `USING (true)` keeps\n * granting everything no matter how tight its replacement is.\n *\n * Matching the shape is what makes dropping them safe. A hand-written policy\n * would have to collide with a 7-hex digest to be mistaken for generated one;\n * a policy named anything else is left alone and merely reported, because a\n * custom name is indistinguishable from one someone wrote in SQL on purpose.\n */\nexport function isGeneratedPolicyName(name: string, table: string): boolean {\n return new RegExp(`^${table.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}_(select|insert|update|delete|all)_[0-9a-f]{7}(_\\\\d+)?$`)\n .test(name);\n}\n\nexport interface OrphanCleanup {\n /** Superseded generated policies that were dropped. */\n dropped: PolicyRef[];\n /** Orphans left in place because their names are not generator-shaped. */\n kept: PolicyRef[];\n}\n\n/**\n * Drop the policies an earlier push superseded but never removed.\n *\n * Only touches tables the tables describe — a table with no expected\n * policy is not ours to reconcile, and scanning by schema alone would sweep up\n * policies belonging to something else sharing the database.\n */\nexport async function dropOrphanedPolicies(\n client: Queryable,\n drift: PolicyDrift,\n compiledTables: readonly CompiledTable[]\n): Promise<OrphanCleanup> {\n const { dropped, kept } = partitionOrphans(drift, compiledTables);\n for (const p of dropped) {\n // Identifiers are quoted, and the name came from pg_policies rather than\n // from user input, so it is already a valid identifier.\n await client.query(`DROP POLICY IF EXISTS \"${p.name}\" ON \"${p.schema}\".\"${p.table}\"`);\n }\n return { dropped, kept };\n}\n\n/**\n * Which orphans {@link dropOrphanedPolicies} drops and which it keeps, decided\n * without dropping anything: what `db push --dry-run` lists.\n */\nexport function partitionOrphans(drift: PolicyDrift, compiledTables: readonly CompiledTable[]): OrphanCleanup {\n const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(compiledTables));\n const managed = new Set(expected.map((p) => `${p.schema}.${p.table}`));\n\n const cleanup: OrphanCleanup = { dropped: [], kept: [] };\n for (const p of drift.orphaned) {\n // An admin-request companion reported as an orphan is one no current\n // rule earns (`checkPolicyDrift` leaves out the ones that do): its rule\n // was removed, renamed or narrowed, and it would go on admitting every\n // admin to every row. Dropped like a superseded generated policy.\n const droppable = isGeneratedPolicyName(p.name, p.table) || ADMIN_REQUEST_POLICY_SUFFIX.test(p.name);\n if (managed.has(`${p.schema}.${p.table}`) && droppable) cleanup.dropped.push(p);\n else cleanup.kept.push(p);\n }\n return cleanup;\n}\n\n/**\n * Drop the admin-request companions no current rule earns, and nothing else:\n * the `_ar_` policies on managed tables `checkPolicyDrift` reports as orphans.\n *\n * `db push` gets this from its orphan cleanup. A migration replays\n * `policies.sql`, which drops the companion of every policy it rewrites, but\n * runs no cleanup — so the companion of a rule removed or renamed since would\n * stay, admitting every admin to every row, on a deployment whose boot never\n * provisions. `rebase db migrate` runs this after it applies.\n */\nexport async function dropStaleAdminRequestCompanions(\n client: Queryable,\n compiledTables: readonly CompiledTable[],\n options: { adminRoleAvailable?: AdminPoliciesExpectation } = {}\n): Promise<PolicyRef[]> {\n const drift = await checkPolicyDrift(client, compiledTables, options);\n const stale = partitionOrphans({ ...drift, orphaned: drift.orphaned.filter(p => ADMIN_REQUEST_POLICY_SUFFIX.test(p.name)) }, compiledTables).dropped;\n for (const p of stale) {\n await client.query(`DROP POLICY IF EXISTS \"${p.name.replace(/\"/g, '\"\"')}\" ON \"${p.schema.replace(/\"/g, '\"\"')}\".\"${p.table.replace(/\"/g, '\"\"')}\"`);\n }\n return stale;\n}\n\nexport const hasDrift = (d: PolicyDrift): boolean =>\n d.missing.length > 0 || d.orphaned.length > 0 || d.diverged.length > 0 || d.insecure.length > 0\n || d.rlsDisabled.length > 0;\n\n/** Human-readable report; empty string when the database matches the config. */\nexport function formatPolicyDrift(drift: PolicyDrift): string {\n if (!hasDrift(drift)) return \"\";\n const lines: string[] = [];\n\n // First, because it subsumes every other finding on the same table: if RLS\n // is off, the policies listed below are not being applied at all.\n if (drift.rlsDisabled.length > 0) {\n lines.push(\" RLS DISABLED — the table has policies, and Postgres is applying none of them:\");\n for (const t of drift.rlsDisabled) {\n lines.push(` • ${t.schema}.${t.table}${t.forced ? \"\" : \" (and FORCE is off)\"}`);\n }\n lines.push(\" Every row is readable and writable by any request that reaches the table.\");\n lines.push(` Fix: ALTER TABLE \"<schema>\".\"<table>\" ENABLE ROW LEVEL SECURITY; or re-run \\`rebase db push\\`.`);\n }\n if (drift.missing.length > 0) {\n lines.push(\" Missing — described by your tables, absent from the database:\");\n for (const p of drift.missing) lines.push(` • ${p.schema}.${p.table} → \"${p.name}\" (${p.command} TO ${p.roles.join(\", \")})`);\n lines.push(\" Run `rebase db push` to apply them.\");\n }\n if (drift.orphaned.length > 0) {\n // Two different things share this list, and they want opposite\n // advice. A name of the shape an unnamed rule compiles to is a rule\n // edited since: the next push drops it. Any other name was written by\n // hand or by another tool, and may be the table's whole access model —\n // \"left behind by an earlier push\" was false of it, and telling its\n // author to drop it would take that access away.\n const superseded = drift.orphaned.filter((p) => isGeneratedPolicyName(p.name, p.table));\n const unowned = drift.orphaned.filter((p) => !isGeneratedPolicyName(p.name, p.table));\n lines.push(\" Orphaned — in the database, described by no table:\");\n for (const p of drift.orphaned) lines.push(` • ${p.schema}.${p.table} → \"${p.name}\" (${p.command} TO ${p.roles.join(\", \")})`);\n if (superseded.length > 0) {\n lines.push(` ${superseded.map((p) => `\"${p.name}\"`).join(\", \")}: left behind by an earlier push, when its rule changed. The next \\`rebase db push\\` drops it.`);\n }\n if (unowned.length > 0) {\n lines.push(` ${unowned.map((p) => `\"${p.name}\"`).join(\", \")}: written by hand or by another tool, and still in force.`);\n lines.push(\" To keep one, describe it in its table's `rls` in backend/schema (Studio's RLS view imports it);\");\n lines.push(\" if it is stale, drop it by hand.\");\n }\n }\n if (drift.diverged.length > 0) {\n lines.push(\" Diverged — same policy, different definition:\");\n for (const d of drift.diverged) {\n lines.push(` • ${d.expected.schema}.${d.expected.table} → \"${d.expected.name}\"`);\n for (const diff of d.differences) lines.push(` ${diff}`);\n }\n }\n if (drift.insecure.length > 0) {\n lines.push(\" Insecure — a live policy grants access it should not:\");\n for (const i of drift.insecure) {\n lines.push(` • ${i.policy.schema}.${i.policy.table} → \"${i.policy.name}\"`);\n lines.push(` ${i.reason}`);\n }\n }\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoGA,IAAM,gBAAgB;AAEtB,IAAM,kBAAkB;;;;;;;;AASxB,SAAS,UAAU,KAAa,MAAsB;CAClD,IAAI,QAAQ;CACZ,IAAI,UAAU;CACd,KAAK,IAAI,IAAI,MAAM,IAAI,IAAI,QAAQ,KAAK;EACpC,MAAM,IAAI,IAAI;EACd,IAAI,SAAS;GAET,IAAI,MAAM,KACN,IAAI,IAAI,IAAI,OAAO,KAAK;QACnB,UAAU;GAEnB;EACJ;EACA,IAAI,MAAM,KAAK,UAAU;OACpB,IAAI,MAAM,KAAK;OACf,IAAI,MAAM,OAAO,EAAE,UAAU,GAAG,OAAO,IAAI;CACpD;CACA,OAAO,IAAI;AACf;;;;;;;;;;AAWA,SAAS,cAAc,KAAwD;CAC3E,IAAI,OAAO,QAAQ,WAAW,OAAO,MAAM,eAAe;CAC1D,IAAI,OAAO,QAAQ,UAAU,OAAO,KAAA;CACpC,MAAM,QAAQ,IAAI,KAAK,CAAC,CAAC,YAAY;CACrC,IAAI,UAAU,gBAAgB,UAAU,UAAU,UAAU,KAAK,OAAO;CACxE,IAAI,UAAU,iBAAiB,UAAU,WAAW,UAAU,KAAK,OAAO;AAE9E;;;;;;;;;;AAWA,SAAgB,sBAAsB,KAA0B;CAC5D,M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