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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (248) hide show
  1. package/README.md +11 -8
  2. package/dist/{BranchService-CrXvcES2.js → BranchService-USp1AvZB.js} +3 -3
  3. package/dist/{BranchService-CrXvcES2.js.map → BranchService-USp1AvZB.js.map} +1 -1
  4. package/dist/PostgresBackendDriver.d.ts +99 -54
  5. package/dist/PostgresBootstrapper.d.ts +12 -27
  6. package/dist/auth/ensure-tables.d.ts +16 -5
  7. package/dist/auth/schema-version.d.ts +2 -2
  8. package/dist/auth/services.d.ts +2 -3
  9. package/dist/{auth-users-columns-C72EMoDJ.js → auth-users-columns-BpfgbkxZ.js} +2 -16
  10. package/dist/auth-users-columns-BpfgbkxZ.js.map +1 -0
  11. package/dist/{backup-cli-CTKCOLpX.js → backup-cli-DbKyEj6c.js} +4 -4
  12. package/dist/{backup-cli-CTKCOLpX.js.map → backup-cli-DbKyEj6c.js.map} +1 -1
  13. package/dist/{boot-ddl-CqGIwSYx.js → boot-ddl-5H2bL_80.js} +2 -2
  14. package/dist/{boot-ddl-CqGIwSYx.js.map → boot-ddl-5H2bL_80.js.map} +1 -1
  15. package/dist/{cli-console-DBPw-oAz.js → cli-console-DsRgGSBR.js} +65 -39
  16. package/dist/cli-console-DsRgGSBR.js.map +1 -0
  17. package/dist/cli-console.d.ts +16 -13
  18. package/dist/cli-flags.d.ts +8 -9
  19. package/dist/cli-helpers.d.ts +15 -11
  20. package/dist/{cli-errors-DYTxnLbW.js → cli-schema-dir-CiN0ephV.js} +184 -70
  21. package/dist/cli-schema-dir-CiN0ephV.js.map +1 -0
  22. package/dist/cli-schema-dir.d.ts +64 -0
  23. package/dist/cli.js +192 -257
  24. package/dist/cli.js.map +1 -1
  25. package/dist/data-transformer.d.ts +50 -19
  26. package/dist/{database-preflight-iBpT7-vv.js → database-preflight-bfnIBnjM.js} +5 -5
  27. package/dist/database-preflight-bfnIBnjM.js.map +1 -0
  28. package/dist/{deferred-index-build-BCU9RoHK.js → deferred-index-build-CcSDA7wE.js} +69 -13
  29. package/dist/deferred-index-build-CcSDA7wE.js.map +1 -0
  30. package/dist/{ensure-collection-policies-Bo-_fDAy.js → ensure-policies-rRmXb5bt.js} +31 -31
  31. package/dist/ensure-policies-rRmXb5bt.js.map +1 -0
  32. package/dist/{ensure-collection-tables-DCJINkT_.js → ensure-tables-Bvm-F2wW.js} +44 -37
  33. package/dist/ensure-tables-Bvm-F2wW.js.map +1 -0
  34. package/dist/{ensure-tables-BPGaGh0y.js → ensure-tables-CC8p_AK3.js} +34 -29
  35. package/dist/ensure-tables-CC8p_AK3.js.map +1 -0
  36. package/dist/{enum-labels-kept-YAgOZS4I.js → enum-labels-kept-FlX9SHdf.js} +8 -8
  37. package/dist/enum-labels-kept-FlX9SHdf.js.map +1 -0
  38. package/dist/{generate-drizzle-schema-DcrFr7YX.js → generate-drizzle-schema-SJMXxzPI.js} +12 -12
  39. package/dist/generate-drizzle-schema-SJMXxzPI.js.map +1 -0
  40. package/dist/{generate-drizzle-schema-logic-LTLZvt6r.js → generate-drizzle-schema-logic-DL7R1rAF.js} +15 -8
  41. package/dist/generate-drizzle-schema-logic-DL7R1rAF.js.map +1 -0
  42. package/dist/{generate-files-CsaVzatS.js → generate-files-tlJ9_lGI.js} +23 -30
  43. package/dist/generate-files-tlJ9_lGI.js.map +1 -0
  44. package/dist/{generate-next-step-DgK5BlBn.js → generate-next-step-CO09dovd.js} +3 -3
  45. package/dist/generate-next-step-CO09dovd.js.map +1 -0
  46. package/dist/{generate-postgres-ddl-logic-Dg0bcENZ.js → generate-postgres-ddl-logic-B8huc03c.js} +51 -21
  47. package/dist/generate-postgres-ddl-logic-B8huc03c.js.map +1 -0
  48. package/dist/{generated-schema-diff-By4dxyTH.js → generated-schema-diff-DoT2dYDe.js} +297 -279
  49. package/dist/generated-schema-diff-DoT2dYDe.js.map +1 -0
  50. package/dist/{generated-schema-staleness-BvNF3i-s.js → generated-schema-staleness-YBVq2kTn.js} +21 -29
  51. package/dist/generated-schema-staleness-YBVq2kTn.js.map +1 -0
  52. package/dist/history/ensure-history-table.d.ts +22 -0
  53. package/dist/index.d.ts +8 -2
  54. package/dist/index.es.js +201 -25
  55. package/dist/index.es.js.map +1 -1
  56. package/dist/interfaces.d.ts +3 -4
  57. package/dist/{introspect-db-queries-DevUrzll.js → introspect-db-queries-BgiRQqtR.js} +7 -2
  58. package/dist/introspect-db-queries-BgiRQqtR.js.map +1 -0
  59. package/dist/introspect-tables-Cw_A-kk4.js +2086 -0
  60. package/dist/introspect-tables-Cw_A-kk4.js.map +1 -0
  61. package/dist/load-tables-B1Re74ng.js +92 -0
  62. package/dist/load-tables-B1Re74ng.js.map +1 -0
  63. package/dist/{migrate-baseline-CmWXL7qx.js → migrate-baseline-DZmekgpD.js} +19 -32
  64. package/dist/migrate-baseline-DZmekgpD.js.map +1 -0
  65. package/dist/{migrate-policy-stamps-BN_Qad6c.js → migrate-policy-stamps-B_acrUQB.js} +18 -19
  66. package/dist/migrate-policy-stamps-B_acrUQB.js.map +1 -0
  67. package/dist/model/PostgresTableRegistry.d.ts +159 -0
  68. package/dist/model/build-registry.d.ts +25 -0
  69. package/dist/model/refresh-relational-schema.d.ts +24 -0
  70. package/dist/model/runtime-table.d.ts +53 -0
  71. package/dist/{collections → model}/validate-relations.d.ts +15 -21
  72. package/dist/{open-rebase-40paQfVW.js → open-rebase-4kisUF_k.js} +3946 -3870
  73. package/dist/open-rebase-4kisUF_k.js.map +1 -0
  74. package/dist/open-rebase.d.ts +16 -15
  75. package/dist/{pg-error-utils-DJHjCF7-.js → pg-error-utils-BT5NzGFZ.js} +17 -20
  76. package/dist/pg-error-utils-BT5NzGFZ.js.map +1 -0
  77. package/dist/plan-schema-Hbtjhge3.js +1633 -0
  78. package/dist/plan-schema-Hbtjhge3.js.map +1 -0
  79. package/dist/{policy-drift-C-m0uWHH.js → policy-drift-BVMyqHSa.js} +29 -29
  80. package/dist/policy-drift-BVMyqHSa.js.map +1 -0
  81. package/dist/{push-index-adoption-Cp7oZxSl.js → push-index-adoption-hpHTyXMR.js} +7 -7
  82. package/dist/push-index-adoption-hpHTyXMR.js.map +1 -0
  83. package/dist/{push-index-prebuild-DbwKGtQT.js → push-index-prebuild-Bty9F7bD.js} +6 -6
  84. package/dist/push-index-prebuild-Bty9F7bD.js.map +1 -0
  85. package/dist/{push-kept-defaults-CLcgsEPt.js → push-kept-defaults-Bst4MDup.js} +13 -16
  86. package/dist/push-kept-defaults-Bst4MDup.js.map +1 -0
  87. package/dist/{push-legacy-renames-BthD0E9W.js → push-legacy-renames-bB4bM6br.js} +6 -6
  88. package/dist/push-legacy-renames-bB4bM6br.js.map +1 -0
  89. package/dist/{push-policy-plan-BgcrroxQ.js → push-policy-plan-BI8U4BOD.js} +11 -11
  90. package/dist/push-policy-plan-BI8U4BOD.js.map +1 -0
  91. package/dist/{render-ddl-Ci3S_SoI.js → render-ddl-D4n86NHz.js} +14 -7
  92. package/dist/render-ddl-D4n86NHz.js.map +1 -0
  93. package/dist/{request-role-cli-Dy1EgJU9.js → request-role-cli-BdRzdE87.js} +11 -11
  94. package/dist/{request-role-cli-Dy1EgJU9.js.map → request-role-cli-BdRzdE87.js.map} +1 -1
  95. package/dist/{request-role-migration-GHTJnPMV.js → request-role-migration-C8aq_TO3.js} +2 -2
  96. package/dist/{request-role-migration-GHTJnPMV.js.map → request-role-migration-C8aq_TO3.js.map} +1 -1
  97. package/dist/{rls-enforcement-Cc_UhOxb.js → rls-enforcement-DB5HHj96.js} +19 -19
  98. package/dist/rls-enforcement-DB5HHj96.js.map +1 -0
  99. package/dist/{rls-settings-BCGMIig3.js → rls-settings-CmGK2U0a.js} +2 -2
  100. package/dist/rls-settings-CmGK2U0a.js.map +1 -0
  101. package/dist/schema/auth-users-columns.d.ts +1 -11
  102. package/dist/schema/catalogue-schema.d.ts +33 -29
  103. package/dist/schema/classify-change.d.ts +23 -16
  104. package/dist/schema/column-type-drift.d.ts +16 -0
  105. package/dist/schema/config-relations.d.ts +10 -9
  106. package/dist/schema/deferred-index-build.d.ts +1 -1
  107. package/dist/schema/doctor-cli.js +1544 -66
  108. package/dist/schema/doctor-cli.js.map +1 -1
  109. package/dist/schema/doctor-database.d.ts +7 -7
  110. package/dist/schema/doctor-policy-checks.d.ts +4 -4
  111. package/dist/schema/doctor-search-scale.d.ts +14 -14
  112. package/dist/schema/doctor.d.ts +27 -27
  113. package/dist/schema/dynamic-tables.d.ts +6 -5
  114. package/dist/schema/{ensure-collection-policies.d.ts → ensure-policies.d.ts} +20 -20
  115. package/dist/schema/{ensure-collection-tables.d.ts → ensure-tables.d.ts} +11 -11
  116. package/dist/schema/enum-labels-kept.d.ts +6 -6
  117. package/dist/schema/generate-drizzle-schema-logic.d.ts +3 -3
  118. package/dist/schema/generate-drizzle-schema.js +1 -1
  119. package/dist/schema/generate-files.d.ts +6 -6
  120. package/dist/schema/generate-postgres-ddl-logic.d.ts +23 -20
  121. package/dist/schema/generate-postgres-ddl.js +11 -11
  122. package/dist/schema/generate-postgres-ddl.js.map +1 -1
  123. package/dist/schema/generate-schema-commit.d.ts +13 -8
  124. package/dist/schema/generated-schema-diff.d.ts +16 -16
  125. package/dist/schema/generated-schema-staleness.d.ts +11 -11
  126. package/dist/schema/index-adoption.d.ts +4 -4
  127. package/dist/schema/introspect-db-customization.d.ts +47 -0
  128. package/dist/schema/introspect-db-inference.d.ts +30 -9
  129. package/dist/schema/introspect-db-logic.d.ts +79 -110
  130. package/dist/schema/introspect-db-project.d.ts +15 -18
  131. package/dist/schema/introspect-db-queries.d.ts +1 -1
  132. package/dist/schema/introspect-db-search.d.ts +25 -4
  133. package/dist/schema/introspect-db-storage.d.ts +4 -74
  134. package/dist/schema/introspect-db.js +102 -90
  135. package/dist/schema/introspect-db.js.map +1 -1
  136. package/dist/schema/introspect-runtime.d.ts +47 -36
  137. package/dist/schema/introspect-tables.d.ts +182 -0
  138. package/dist/schema/load-tables.d.ts +55 -0
  139. package/dist/schema/migrate-policy-stamps.d.ts +4 -4
  140. package/dist/schema/migration-freshness.d.ts +13 -13
  141. package/dist/schema/plan/column-order.d.ts +82 -0
  142. package/dist/schema/plan/diff-plan.d.ts +9 -3
  143. package/dist/schema/plan/plan-schema.d.ts +55 -52
  144. package/dist/schema/plan/render-drizzle.d.ts +1 -1
  145. package/dist/schema/plan/types.d.ts +24 -15
  146. package/dist/schema/push-index-adoption.d.ts +3 -3
  147. package/dist/schema/push-index-prebuild.d.ts +3 -3
  148. package/dist/schema/push-kept-defaults.d.ts +7 -7
  149. package/dist/schema/push-legacy-renames.d.ts +3 -3
  150. package/dist/schema/push-policy-plan.d.ts +5 -5
  151. package/dist/schema/reconcile-schema.d.ts +5 -5
  152. package/dist/schema/relation-names.d.ts +15 -20
  153. package/dist/schema/render-outputs.d.ts +76 -0
  154. package/dist/schema/search-column.d.ts +11 -43
  155. package/dist/schema/{collection-index.d.ts → table-index.d.ts} +21 -42
  156. package/dist/schema/{collections-schema-version.d.ts → tables-schema-version.d.ts} +8 -2
  157. package/dist/schema/vector-index.d.ts +24 -28
  158. package/dist/{search-column-BM-GV6vH.js → search-column-BO-WND-B.js} +86 -149
  159. package/dist/search-column-BO-WND-B.js.map +1 -0
  160. package/dist/security/caller-sql-columns.d.ts +9 -6
  161. package/dist/security/policy-drift.d.ts +14 -14
  162. package/dist/security/rls-enforcement.d.ts +19 -25
  163. package/dist/security/rls-settings.d.ts +2 -2
  164. package/dist/security/served-table-protection.d.ts +125 -0
  165. package/dist/services/FetchService.d.ts +22 -133
  166. package/dist/services/PersistService.d.ts +6 -17
  167. package/dist/services/RelationService.d.ts +57 -106
  168. package/dist/services/RelationWriteService.d.ts +59 -66
  169. package/dist/services/cdc/identity-columns.d.ts +7 -5
  170. package/dist/services/cdc/junction-tables.d.ts +14 -14
  171. package/dist/services/collection-helpers.d.ts +52 -95
  172. package/dist/services/dataService.d.ts +15 -12
  173. package/dist/services/field-op-sql.d.ts +11 -9
  174. package/dist/services/field-viewer.d.ts +12 -11
  175. package/dist/services/hidden-columns.d.ts +30 -0
  176. package/dist/services/index.d.ts +1 -1
  177. package/dist/services/junction-writes.d.ts +37 -18
  178. package/dist/services/nested-path.d.ts +18 -18
  179. package/dist/services/read-field-access.d.ts +23 -7
  180. package/dist/services/read-scope.d.ts +10 -9
  181. package/dist/services/realtimeService.d.ts +25 -10
  182. package/dist/services/relation-tables.d.ts +97 -0
  183. package/dist/services/row-pipeline.d.ts +50 -69
  184. package/dist/services/soft-delete.d.ts +25 -24
  185. package/dist/services/table-hooks.d.ts +146 -0
  186. package/dist/services/view-access.d.ts +7 -7
  187. package/dist/services/write-transaction-scope.d.ts +1 -1
  188. package/dist/{source-fZb92pN8.js → source-VxbrQojV.js} +111 -79
  189. package/dist/source-VxbrQojV.js.map +1 -0
  190. package/dist/{collections-schema-version-D7bDI0PJ.js → tables-schema-version-YvZIBlOP.js} +12 -6
  191. package/dist/tables-schema-version-YvZIBlOP.js.map +1 -0
  192. package/dist/utils/drizzle-conditions.d.ts +70 -84
  193. package/dist/utils/pg-array-null-patch.d.ts +27 -10
  194. package/dist/utils/pg-error-utils.d.ts +4 -4
  195. package/dist/{vector-index-DsQ3V2d2.js → vector-index-VSh3ufTd.js} +62 -54
  196. package/dist/vector-index-VSh3ufTd.js.map +1 -0
  197. package/dist/{websocket-B7ex6AQM.js → websocket-BevXvwfo.js} +51 -40
  198. package/dist/websocket-BevXvwfo.js.map +1 -0
  199. package/dist/websocket.d.ts +2 -2
  200. package/package.json +7 -7
  201. package/dist/auth-users-columns-C72EMoDJ.js.map +0 -1
  202. package/dist/cli-collections-path.d.ts +0 -31
  203. package/dist/cli-console-DBPw-oAz.js.map +0 -1
  204. package/dist/cli-errors-DYTxnLbW.js.map +0 -1
  205. package/dist/collections/PostgresCollectionRegistry.d.ts +0 -47
  206. package/dist/collections/buildRegistry.d.ts +0 -27
  207. package/dist/collections-schema-version-D7bDI0PJ.js.map +0 -1
  208. package/dist/column-plan-helpers-BeSztMor.js +0 -161
  209. package/dist/column-plan-helpers-BeSztMor.js.map +0 -1
  210. package/dist/database-preflight-iBpT7-vv.js.map +0 -1
  211. package/dist/deferred-index-build-BCU9RoHK.js.map +0 -1
  212. package/dist/doctor-Kg1oUK0Q.js +0 -1458
  213. package/dist/doctor-Kg1oUK0Q.js.map +0 -1
  214. package/dist/ensure-collection-policies-Bo-_fDAy.js.map +0 -1
  215. package/dist/ensure-collection-tables-DCJINkT_.js.map +0 -1
  216. package/dist/ensure-tables-BPGaGh0y.js.map +0 -1
  217. package/dist/enum-labels-kept-YAgOZS4I.js.map +0 -1
  218. package/dist/generate-drizzle-schema-DcrFr7YX.js.map +0 -1
  219. package/dist/generate-drizzle-schema-logic-LTLZvt6r.js.map +0 -1
  220. package/dist/generate-files-CsaVzatS.js.map +0 -1
  221. package/dist/generate-next-step-DgK5BlBn.js.map +0 -1
  222. package/dist/generate-postgres-ddl-logic-Dg0bcENZ.js.map +0 -1
  223. package/dist/generated-schema-diff-By4dxyTH.js.map +0 -1
  224. package/dist/generated-schema-staleness-BvNF3i-s.js.map +0 -1
  225. package/dist/introspect-db-logic-DWqAEURB.js +0 -2047
  226. package/dist/introspect-db-logic-DWqAEURB.js.map +0 -1
  227. package/dist/introspect-db-queries-DevUrzll.js.map +0 -1
  228. package/dist/migrate-baseline-CmWXL7qx.js.map +0 -1
  229. package/dist/migrate-policy-stamps-BN_Qad6c.js.map +0 -1
  230. package/dist/open-rebase-40paQfVW.js.map +0 -1
  231. package/dist/pg-error-utils-DJHjCF7-.js.map +0 -1
  232. package/dist/plan-schema-vJd3UEmT.js +0 -1604
  233. package/dist/plan-schema-vJd3UEmT.js.map +0 -1
  234. package/dist/policy-drift-C-m0uWHH.js.map +0 -1
  235. package/dist/push-index-adoption-Cp7oZxSl.js.map +0 -1
  236. package/dist/push-index-prebuild-DbwKGtQT.js.map +0 -1
  237. package/dist/push-kept-defaults-CLcgsEPt.js.map +0 -1
  238. package/dist/push-legacy-renames-BthD0E9W.js.map +0 -1
  239. package/dist/push-policy-plan-BgcrroxQ.js.map +0 -1
  240. package/dist/render-ddl-Ci3S_SoI.js.map +0 -1
  241. package/dist/rls-enforcement-Cc_UhOxb.js.map +0 -1
  242. package/dist/rls-settings-BCGMIig3.js.map +0 -1
  243. package/dist/schema/column-plan-helpers.d.ts +0 -161
  244. package/dist/schema/introspect-db-naming.d.ts +0 -10
  245. package/dist/search-column-BM-GV6vH.js.map +0 -1
  246. package/dist/source-fZb92pN8.js.map +0 -1
  247. package/dist/vector-index-DsQ3V2d2.js.map +0 -1
  248. package/dist/websocket-B7ex6AQM.js.map +0 -1
@@ -0,0 +1,1633 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ __createRequire(import.meta.url);
3
+ import { d as searchHelperFunctions, i as buildTableSearchColumnSpec, l as searchColumnTypeSql, u as searchExtensionStatements } from "./search-column-BO-WND-B.js";
4
+ import { r as viewRowsName, t as DEFAULT_VIEW_ROLES } from "./view-names-Dscp6--B.js";
5
+ import { n as authUsersColumnDefinition, r as authUsersColumnSql, t as AUTH_USERS_COLUMNS } from "./auth-users-columns-BpfgbkxZ.js";
6
+ import { c as vectorExtensionStatement, n as buildTableVectorColumnSpecs, o as vectorExtensionDeclared, r as buildTableVectorIndexPlan } from "./vector-index-VSh3ufTd.js";
7
+ import { c as buildTableIndexSpecs, f as leadsWithColumn, h as tableIndexStatement, l as deriveIndexName, u as foreignKeyIndexSpec } from "./source-VxbrQojV.js";
8
+ import { REBASE_SCHEMA } from "@rebasepro/types";
9
+ import { TENANT_INDEX_REASON, columnByKey, columnNameOf, compileTableRulePolicies, customSqlTypeProblem, declaredSchemaOf, getEnumVarName, getTableVarName, junctionPolicyTable, keyForColumn, policyTableFromDescriptor, policyTableResolver, relationOf, resolveTableJunctions, tableEffectiveRules, tableInjectedRules, tableJunctionRules, tenantOf } from "@rebasepro/common";
10
+ import { generateForeignKeyName, getPolicySupersededNames, legacyForeignKeyName, toPostgresIdentifier, toSnakeCase, toWireKey } from "@rebasepro/utils";
11
+ import { createHash } from "node:crypto";
12
+ //#region src/schema/relation-names.ts
13
+ /**
14
+ * The key a SQL column is served under on a table: its column's key, or — for
15
+ * a column the table does not describe — the camelCase of its name, which is
16
+ * the key a foreign key derived from it would get.
17
+ */
18
+ var servedKeyOf = (descriptor, sqlColumn) => keyForColumn(descriptor, sqlColumn) ?? toWireKey(sqlColumn);
19
+ /**
20
+ * The `relationName` both sides of a link must agree on.
21
+ *
22
+ * Drizzle pairs an owning `one()` with its inverse `many()` by this string and
23
+ * by nothing else, and the two sides are computed by different callers holding
24
+ * different tables — so the rule has to be derivable from either end. It is:
25
+ * name the link after the table that carries the foreign key and the key that
26
+ * column is served under (the key, not the column: the Drizzle object is keyed
27
+ * by the wire name, {@link servedKeyOf}).
28
+ *
29
+ * owning (belongsTo) → `{thisTable}_{key(localKey)}`
30
+ * inverse (hasMany/hasOne) → `{targetTable}_{key(foreignKey)}`
31
+ *
32
+ * A many-to-many and a `via` chain keep the relation's own name.
33
+ */
34
+ function tableRelationName(relation, source, targetOf) {
35
+ if (relation.kind === "belongsTo") return `${source.table}_${servedKeyOf(source, relation.localKey)}`;
36
+ if (relation.kind === "hasMany" || relation.kind === "hasOne") {
37
+ const target = targetOf(relation.target);
38
+ return `${target.table}_${servedKeyOf(target, relation.foreignKey)}`;
39
+ }
40
+ return relation.name;
41
+ }
42
+ //#endregion
43
+ //#region src/schema/plan/tenant-keep-trigger.ts
44
+ /**
45
+ * `tenant`'s immutability, as a database trigger.
46
+ *
47
+ * The driver refuses an update that moves a row to another tenant
48
+ * (`TENANT_IMMUTABLE`, see `resolveTenantWrite` in `@rebasepro/common`), and
49
+ * the restrictive tenant policy cannot: a policy sees the new row or the old
50
+ * one, never both, so a caller who belongs to two tenants passes it while
51
+ * moving a row from one to the other. Every writer that is not the driver —
52
+ * SQL run as the caller (`DataDriver.sql`) above all — met only the policy.
53
+ *
54
+ * So a `BEFORE UPDATE` trigger compares the two. It applies to whoever the
55
+ * table's policies bind (`row_security_active`), which is every request role
56
+ * whatever `rls.requestRole` names it: the owner connection (migrations, the
57
+ * auth flows, a person in `psql`) keeps moving rows when it means to, as it
58
+ * always could, and so does a caller holding one of the collection's
59
+ * `bypassRoles` — the same exemption the driver makes.
60
+ *
61
+ * One function for every table, the column and the bypass roles arriving as
62
+ * trigger arguments, like `set_updated_at`. The arguments are compared with
63
+ * the catalogue's on boot (see `diffPlanAgainstCatalogue`), so a changed
64
+ * `bypassRoles` re-creates the binding rather than leaving the old list in
65
+ * force.
66
+ */
67
+ /** The one trigger function, qualified. A frozen derived name. */
68
+ var KEEP_TENANT_FN = `${REBASE_SCHEMA}.keep_tenant`;
69
+ /** The trigger's name on `table`. A frozen derived name. */
70
+ var keepTenantTriggerName = (table) => `${table}_keep_tenant`;
71
+ var keepTenantFunction = () => `CREATE OR REPLACE FUNCTION ${KEEP_TENANT_FN}() RETURNS trigger\nLANGUAGE plpgsql AS \$\$
72
+ BEGIN
73
+ IF row_security_active(TG_RELID) THEN
74
+ IF to_jsonb(OLD) -> TG_ARGV[0] IS DISTINCT FROM to_jsonb(NEW) -> TG_ARGV[0] THEN
75
+ IF NOT (string_to_array(COALESCE(current_setting('app.user_roles', true), ''), ',') && TG_ARGV[1:TG_NARGS - 1]) THEN
76
+ RAISE EXCEPTION 'TENANT_IMMUTABLE: an update cannot move a row of "%" to another tenant (column "%")', TG_TABLE_NAME, TG_ARGV[0]
77
+ USING ERRCODE = '42501',
78
+ HINT = 'Move it as a role listed in the collection''s tenant.bypassRoles.';
79
+ END IF;
80
+ END IF;
81
+ END IF;
82
+ RETURN NEW;
83
+ END;
84
+ \$\$;`;
85
+ /** The arguments the binding passes: the column, then each bypass role. */
86
+ var keepTenantArguments = (plan) => [plan.column, ...plan.bypassRoles ?? []];
87
+ var literal = (value) => `'${value.replace(/'/g, "''")}'`;
88
+ var createKeepTenantStatement = (plan) => `CREATE TRIGGER "${plan.name}" BEFORE UPDATE ON "${plan.schema}"."${plan.table}" FOR EACH ROW EXECUTE FUNCTION ${KEEP_TENANT_FN}(${keepTenantArguments(plan).map(literal).join(", ")});`;
89
+ //#endregion
90
+ //#region src/schema/plan/updated-at-trigger.ts
91
+ /**
92
+ * `autoValue: "on_update"`, as a database trigger.
93
+ *
94
+ * ## Why a trigger and not only the driver
95
+ *
96
+ * The driver stamps `updated_at` on every write it makes, and it has to keep
97
+ * doing so: a `beforeSave` hook reads the row it is about to persist, and a
98
+ * value that only appears once Postgres has written it is a value the hook
99
+ * cannot see.
100
+ *
101
+ * But the driver is not the only writer. A seed script, a migration backfill, a
102
+ * `psql` session, an admin fixing one row by hand — every one of those leaves
103
+ * `updated_at` at whatever it was, and the column then says the row has not
104
+ * changed since a date that is simply wrong. Anything reading it to decide what
105
+ * to re-index, re-sync or re-send skips the row. The declaration says "this
106
+ * column tracks the last write"; only the database can make that true.
107
+ *
108
+ * So both: the app stamps so hooks see the value, and a `BEFORE UPDATE` trigger
109
+ * stamps so every other writer does too. They agree because they both mean
110
+ * "now" — the trigger's `now()` is the transaction's start time, which is the
111
+ * same instant the driver's own timestamp is written under.
112
+ *
113
+ * ## Why it is carved out of Atlas
114
+ *
115
+ * Atlas's free tier refuses to *parse* a desired-state file containing a
116
+ * function ("functions and procedures are available to logged-in users only"),
117
+ * and a trigger is a function plus a binding. This is the same arrangement the
118
+ * search helpers already have: excluded from Atlas's view by pattern, written
119
+ * to a file Rebase applies itself, applied at boot by the schema ensure, and
120
+ * appended to migrations by the CLI so a replay is complete.
121
+ *
122
+ * ## Why one function for every column
123
+ *
124
+ * The column name arrives as a trigger argument (`TG_ARGV[0]`), so a project
125
+ * with forty `updated_at` columns installs one function and forty bindings
126
+ * rather than forty near-identical functions. `jsonb_populate_record(NEW, …)`
127
+ * is the documented way to set a field of a row whose type is not known until
128
+ * run time; it takes `NEW` as the row template, so the value is cast back to
129
+ * whatever the column actually is — a `timestamptz`, or a `date` if that is
130
+ * what the property declared.
131
+ */
132
+ /** The one trigger function, qualified. A frozen derived name. */
133
+ var SET_UPDATED_AT_FN = `${REBASE_SCHEMA}.set_updated_at`;
134
+ /**
135
+ * `CREATE OR REPLACE FUNCTION`, so replaying it against a database that already
136
+ * has it is a no-op — this is emitted into a file that runs on every push and
137
+ * is appended to migrations that run against databases at any stage of life.
138
+ */
139
+ var setUpdatedAtFunction = () => `CREATE OR REPLACE FUNCTION ${SET_UPDATED_AT_FN}() RETURNS trigger\nLANGUAGE plpgsql AS \$\$
140
+ BEGIN
141
+ NEW := jsonb_populate_record(NEW, jsonb_build_object(TG_ARGV[0], now()));
142
+ RETURN NEW;
143
+ END;
144
+ \$\$;`;
145
+ /**
146
+ * `DROP TRIGGER IF EXISTS` before the `CREATE`.
147
+ *
148
+ * `CREATE OR REPLACE TRIGGER` exists only on Postgres 14+, and this runs
149
+ * against whatever a self-hosted project points at. Two statements rather than
150
+ * one is also what the boot-time applier needs: it issues DDL one statement at
151
+ * a time over the extended query protocol, which forbids multiple commands in
152
+ * one execute.
153
+ */
154
+ var dropTriggerStatement = (plan) => `DROP TRIGGER IF EXISTS "${plan.name}" ON "${plan.schema}"."${plan.table}";`;
155
+ var createTriggerStatement = (plan) => `CREATE TRIGGER "${plan.name}" BEFORE UPDATE ON "${plan.schema}"."${plan.table}" FOR EACH ROW EXECUTE FUNCTION ${SET_UPDATED_AT_FN}('${plan.column.replace(/'/g, "''")}');`;
156
+ /** Both statements, in the order they must run — for either kind of trigger. */
157
+ var triggerStatements = (plan) => [dropTriggerStatement(plan), plan.kind === "keep-tenant" ? createKeepTenantStatement(plan) : createTriggerStatement(plan)];
158
+ //#endregion
159
+ //#region src/schema/plan/column-order.ts
160
+ /** The implicit key's DEFAULT: a uuid, as text. */
161
+ var IMPLICIT_ID_DEFAULT = "gen_random_uuid()::text";
162
+ /** The type a column pointing at this key must have: a serial read as its plain integer. */
163
+ var referencingColumnType = (type) => {
164
+ switch (type.kind) {
165
+ case "smallserial": return { kind: "smallint" };
166
+ case "serial": return { kind: "integer" };
167
+ case "bigserial": return { kind: "bigint" };
168
+ default: return type;
169
+ }
170
+ };
171
+ /**
172
+ * The type of the target's key a link points at, as a column pointing at it
173
+ * holds it; `text` for a target with no key, `undefined` for a composite key.
174
+ */
175
+ var targetKeyColumnType = (target) => {
176
+ const keys = target.columns.filter((column) => column.primaryKey === true);
177
+ if (keys.length === 0) return { kind: "text" };
178
+ if (keys.length > 1) return void 0;
179
+ return referencingColumnType(keys[0].type);
180
+ };
181
+ /**
182
+ * Whether the table's first column is exactly the key the planner gives a
183
+ * table that declares none, which it adds back itself.
184
+ */
185
+ function isImplicitIdColumn(descriptor) {
186
+ const first = descriptor.columns[0];
187
+ if (!first || descriptor.primaryKey.length !== 1 || descriptor.primaryKey[0] !== first.key || first.key !== "id") return false;
188
+ if (first.column !== "id" || first.type.kind !== "text" || first.derived) return false;
189
+ if (first.default?.kind !== "sql" || first.default.expression !== "gen_random_uuid()::text") return false;
190
+ return !first.unique && !first.readOnly && !first.private && first.access === void 0 && first.stamp === void 0 && first.validate === void 0 && first.oneOf === void 0 && first.description === void 0 && first.storage === void 0 && first.generated === void 0 && first.transforms === void 0;
191
+ }
192
+ /**
193
+ * Whether a `belongsTo` was written `constraint: false`. The descriptor also
194
+ * records `constraint: false` for a link into a view or out of one, where
195
+ * Postgres refuses a foreign key — that link was not written without one.
196
+ */
197
+ var writtenWithoutConstraint = (descriptor, relation, target) => !relation.constraint && descriptor.kind === "table" && target.kind === "table";
198
+ /**
199
+ * Whether the column a `belongsTo` binds is nothing but the foreign key the
200
+ * relation would have derived: served under the camelCase of its SQL name (and
201
+ * no relation is named after that column), typed as the target's key, with no
202
+ * rule of its own, and the relation keeps its constraint. Such a column is
203
+ * planned once, as the link.
204
+ */
205
+ function isPlainForeignKey(descriptor, column, relation, target) {
206
+ if (writtenWithoutConstraint(descriptor, relation, target)) return false;
207
+ const localKey = column.column;
208
+ for (const other of descriptor.relations) if (other.name === localKey || toSnakeCase(other.name) === localKey) return false;
209
+ if (toWireKey(localKey) !== column.key) return false;
210
+ if (column.primaryKey || column.default !== void 0 || column.generated !== void 0 || column.readOnly || column.private) return false;
211
+ if (column.access !== void 0 || column.stamp !== void 0 || column.validate !== void 0 || column.oneOf !== void 0) return false;
212
+ if (column.description !== void 0 || column.storage !== void 0 || column.semantic !== void 0) return false;
213
+ if (column.vectorIndex !== void 0 || column.json !== void 0 || column.element !== void 0 || column.transforms !== void 0) return false;
214
+ const targetType = targetKeyColumnType(target);
215
+ if (targetType === void 0 || targetType.kind === "enum" || column.type.kind === "enum") return false;
216
+ return JSON.stringify(column.type) === JSON.stringify(targetType);
217
+ }
218
+ /**
219
+ * A table's planned column entries, in the plan's order (see the module
220
+ * comment). `targetOf` answers a relation target's descriptor by slug.
221
+ */
222
+ function plannedColumnEntries(descriptor, targetOf) {
223
+ const relationIndex = new Map(descriptor.relations.map((relation, index) => [relation.name, index]));
224
+ const ordered = [];
225
+ const absorbed = /* @__PURE__ */ new Set();
226
+ const implicitId = isImplicitIdColumn(descriptor);
227
+ descriptor.columns.forEach((column, position) => {
228
+ if (column.derived) return;
229
+ if (position === 0 && implicitId) return;
230
+ const relation = column.foreignKeyOf === void 0 ? void 0 : belongsToNamed(descriptor, column.foreignKeyOf);
231
+ if (relation && isPlainForeignKey(descriptor, column, relation, targetOf(relation.target))) {
232
+ ordered.push({
233
+ entry: {
234
+ kind: "link",
235
+ form: "absorbed",
236
+ relation,
237
+ column
238
+ },
239
+ relation: relationIndex.get(relation.name)
240
+ });
241
+ absorbed.add(relation.name);
242
+ return;
243
+ }
244
+ ordered.push({ entry: {
245
+ kind: "column",
246
+ column
247
+ } });
248
+ });
249
+ descriptor.relations.forEach((relation, index) => {
250
+ if (relation.kind !== "belongsTo" || absorbed.has(relation.name)) return;
251
+ const column = descriptor.columns.find((candidate) => candidate.foreignKeyOf === relation.name);
252
+ if (!column) throw new Error(`Internal: the relation "${relation.name}" of table "${descriptor.slug}" has no foreign-key column in its descriptor.`);
253
+ const item = {
254
+ entry: {
255
+ kind: "link",
256
+ form: column.derived ? "derived" : "constraint",
257
+ relation,
258
+ column
259
+ },
260
+ relation: index
261
+ };
262
+ let after = -1;
263
+ for (let position = ordered.length - 1; position >= 0; position--) {
264
+ const other = ordered[position].relation;
265
+ if (other !== void 0 && other < index) {
266
+ after = position;
267
+ break;
268
+ }
269
+ }
270
+ const before = ordered.findIndex((other) => other.relation !== void 0 && other.relation > index);
271
+ if (after !== -1) ordered.splice(after + 1, 0, item);
272
+ else if (before !== -1) ordered.splice(before, 0, item);
273
+ else ordered.push(item);
274
+ });
275
+ return ordered.map((item) => item.entry);
276
+ }
277
+ var belongsToNamed = (descriptor, name) => {
278
+ const relation = descriptor.relations.find((candidate) => candidate.name === name);
279
+ return relation?.kind === "belongsTo" ? relation : void 0;
280
+ };
281
+ //#endregion
282
+ //#region src/schema/plan/plan-schema.ts
283
+ /**
284
+ * The only place a table is read for schema purposes.
285
+ *
286
+ * Everything that used to `switch (prop.type)` — the Drizzle generator, the DDL
287
+ * generator, the boot-time ensure — now renders the {@link SchemaPlan} this
288
+ * produces. See `./types.ts` for why.
289
+ *
290
+ * Pure and synchronous. It reads compiled tables — their descriptors — and
291
+ * nothing else: no database, no filesystem, no process-wide registry. The one
292
+ * fact about the world it needs (which extensions a project's databases gave
293
+ * Rebase leave to install) is passed in, because a plan that depended on
294
+ * whatever module happened to be imported would not be comparable with itself.
295
+ *
296
+ * It **throws** rather than guessing. A configuration no renderer can honour —
297
+ * an empty enum, a foreign key into a composite key, an array of documents, a
298
+ * custom type name that leaves its statement — used to fail differently in
299
+ * each of the three emitters, or not at all, and the failure landed at
300
+ * `CREATE TABLE` time on a managed tenant with nobody in the loop. Here it
301
+ * lands once, with the table and the column named.
302
+ */
303
+ /**
304
+ * Single-quote escaping for a SQL string literal (PostgreSQL doubles the
305
+ * quote). Enum labels and `defaultValue`s come straight from user-authored
306
+ * collection config, so a value like `it's` closes the literal early and the
307
+ * whole generated file stops parsing at that statement.
308
+ */
309
+ var quoteSqlLiteral = (value) => `'${value.replace(/'/g, "''")}'`;
310
+ var bareTableName = (name) => name.includes(".") ? name.split(".").pop() : name;
311
+ /**
312
+ * The `ON DELETE` a foreign key gets when the author did not say.
313
+ *
314
+ * One rule for every property that emits one — `belongsTo` relations and
315
+ * `reference` properties alike. `reference` kept its own `CASCADE` default for
316
+ * a release after this rule was written, which is exactly the split this
317
+ * function exists to prevent: two spellings of the same link, two
318
+ * data-retention behaviours, and only one of them documented.
319
+ *
320
+ * An optional link is `SET NULL`: the column can hold NULL, so dropping the
321
+ * parent leaves the child row with an empty pointer, which is what "optional"
322
+ * already means.
323
+ *
324
+ * A required link is **`RESTRICT`**, not `CASCADE`. `NOT NULL` says the child
325
+ * cannot exist without a parent; it does not say deleting the parent should
326
+ * take the child with it. That second claim is a data-retention decision, and
327
+ * defaulting to it meant `onDelete` — a field nobody has to write — silently
328
+ * turned every `DELETE FROM authors` into a cascade through posts, comments and
329
+ * anything else that hung off them.
330
+ */
331
+ var defaultBelongsToOnDelete = (required) => required ? "RESTRICT" : "SET NULL";
332
+ var foreignKeyPlan = (args) => {
333
+ const constraintName = toPostgresIdentifier(`${args.table}_${args.column}_fkey`);
334
+ const onUpdate = args.onUpdate ? ` ON UPDATE ${args.onUpdate.toUpperCase()}` : "";
335
+ return {
336
+ ...args,
337
+ constraintName,
338
+ sql: `ALTER TABLE "${args.schema}"."${args.table}" ADD CONSTRAINT "${constraintName}" FOREIGN KEY ("${args.column}") REFERENCES "${args.targetSchema}"."${args.targetTable}" ("${args.targetColumn}") ON DELETE ${args.onDelete.toUpperCase()}${onUpdate}`
339
+ };
340
+ };
341
+ /** A value already written as a day, or as a time of day. */
342
+ var BARE_DATE = /^\d{4}-\d{2}-\d{2}$/;
343
+ var BARE_TIME = /^\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/;
344
+ /**
345
+ * A date default in the shape its column's type accepts: a day for `date`, a
346
+ * time of day for `time`, an instant for a timestamp.
347
+ *
348
+ * Rendered as a full ISO timestamp whatever the column, a `time` column's
349
+ * DEFAULT was `'2024-03-01T15:30:00.000Z'`, which Postgres refuses — "invalid
350
+ * input syntax for type time" — so the schema would not apply. A value already
351
+ * written in the column's shape (`"2024-12-25"`, `"09:00"`) is kept as written;
352
+ * anything else is read as an instant and its UTC day or time of day taken, the
353
+ * same zone the timestamp rendering has always used. A string that is no date
354
+ * at all is no DEFAULT, rather than a schema that cannot be applied.
355
+ */
356
+ var dateDefaultLiteral = (value, type) => {
357
+ if (typeof value === "string") {
358
+ if (type.kind === "date" && BARE_DATE.test(value)) return value;
359
+ if (type.kind === "time" && BARE_TIME.test(value)) return value;
360
+ }
361
+ const instant = value instanceof Date ? value : typeof value === "string" ? new Date(value) : void 0;
362
+ if (!instant || Number.isNaN(instant.getTime())) return void 0;
363
+ const iso = instant.toISOString();
364
+ if (type.kind === "date") return iso.slice(0, 10);
365
+ if (type.kind === "time") return iso.slice(11, 23);
366
+ return typeof value === "string" ? value : iso;
367
+ };
368
+ /**
369
+ * The element types a Postgres array column takes here: a scalar Rebase can
370
+ * read and write item by item. A JSON document or a vector is already a list
371
+ * of its own (`col.jsonb()` holds a list of documents), and a `bytea` item
372
+ * would need a binary codec per element that nothing implements.
373
+ */
374
+ var NON_ELEMENT_KINDS = /* @__PURE__ */ new Set([
375
+ "json",
376
+ "jsonb",
377
+ "vector",
378
+ "bytea",
379
+ "array",
380
+ "other"
381
+ ]);
382
+ /**
383
+ * The Postgres type a column descriptor states.
384
+ *
385
+ * One arm per {@link ColumnType} member: the two type unions are kept 1:1, so
386
+ * this is a renaming, not a derivation. An enum is the one member that needs
387
+ * the site — its type is named after the table and column it is declared on,
388
+ * unless the definition names a shared type.
389
+ */
390
+ var describedPgType = (column, site) => pgTypeOf(column.type, site);
391
+ /** Where a table's described column lands. */
392
+ var describedSite = (descriptor, column) => ({
393
+ schema: descriptor.schema,
394
+ table: descriptor.table,
395
+ owner: descriptor.slug,
396
+ propName: column.key,
397
+ column: column.column
398
+ });
399
+ /**
400
+ * The single-column key of a table a link points at — a `belongsTo` foreign
401
+ * key, a junction endpoint — and the type the pointing column must have: the
402
+ * key's own type (a serial read as its plain integer, which would otherwise
403
+ * give every referencing column a sequence of its own). A table with no key
404
+ * is pointed at by the implicit `id TEXT`.
405
+ *
406
+ * @param via the link asking, named if the key is composite and so cannot be
407
+ * pointed at.
408
+ */
409
+ var tableKeyTarget = (target, via) => {
410
+ const keys = target.columns.filter((column) => column.primaryKey === true);
411
+ if (keys.length > 1) throw new Error(`${via} points at table "${target.slug}", whose primary key spans ${keys.length} columns (${keys.map((key) => `"${key.key}"`).join(", ")}). A foreign key is one column and cannot reference a composite key. Point the link at a table with a single-column key, or reach these rows with \`rel.via(...)\`, whose steps compare every key column.`);
412
+ const key = keys[0];
413
+ if (!key) return {
414
+ key: "id",
415
+ column: "id",
416
+ type: { kind: "text" }
417
+ };
418
+ return {
419
+ key: key.key,
420
+ column: key.column,
421
+ type: pgTypeOf(referencingColumnType(key.type), describedSite(target, key))
422
+ };
423
+ };
424
+ var pgTypeOf = (type, site) => {
425
+ switch (type.kind) {
426
+ case "text": return { kind: "text" };
427
+ case "varchar": return {
428
+ kind: "varchar",
429
+ length: type.length
430
+ };
431
+ case "char": return {
432
+ kind: "char",
433
+ length: type.length
434
+ };
435
+ case "uuid": return { kind: "uuid" };
436
+ case "enum": return definedEnumType(type, site);
437
+ case "smallint": return { kind: "smallint" };
438
+ case "integer": return { kind: "integer" };
439
+ case "bigint": return { kind: "bigint" };
440
+ case "smallserial": return { kind: "smallserial" };
441
+ case "serial": return { kind: "serial" };
442
+ case "bigserial": return { kind: "bigserial" };
443
+ case "real": return { kind: "real" };
444
+ case "doublePrecision": return { kind: "doublePrecision" };
445
+ case "numeric":
446
+ if (type.precision === void 0) return { kind: "numeric" };
447
+ return type.scale === void 0 ? {
448
+ kind: "numeric",
449
+ precision: type.precision
450
+ } : {
451
+ kind: "numeric",
452
+ precision: type.precision,
453
+ scale: type.scale
454
+ };
455
+ case "boolean": return { kind: "boolean" };
456
+ case "timestamptz": return { kind: "timestamptz" };
457
+ case "date": return { kind: "date" };
458
+ case "time": return { kind: "time" };
459
+ case "json": return { kind: "json" };
460
+ case "jsonb": return { kind: "jsonb" };
461
+ case "vector": return {
462
+ kind: "vector",
463
+ dimensions: type.dimensions
464
+ };
465
+ case "bytea": return { kind: "bytea" };
466
+ case "array":
467
+ if (NON_ELEMENT_KINDS.has(type.of.kind)) throw new Error(`Column "${site.column}" of "${site.owner}" is an array of \`${type.of.kind}\`, which is not an element type Rebase stores in a Postgres array. An array column holds scalars (text, uuid, numbers, booleans, dates, enums); a list of documents or vectors is a \`col.jsonb()\` column.`);
468
+ return {
469
+ kind: "array",
470
+ of: pgTypeOf(type.of, site)
471
+ };
472
+ case "other": {
473
+ const problem = customSqlTypeProblem(type.sqlType);
474
+ if (problem !== void 0) throw new Error(`Column "${site.column}" of "${site.owner}" is \`col.custom({ dataType: ${JSON.stringify(type.sqlType)} })\`, and that type name ${problem}. Write the Postgres type as \`format_type\` prints it.`);
475
+ return {
476
+ kind: "custom",
477
+ sqlType: type.sqlType.trim()
478
+ };
479
+ }
480
+ }
481
+ };
482
+ /**
483
+ * The type name an enum states when it names a shared type: its `name`, unless
484
+ * that is exactly the `<table>_<column>` an unnamed one gets — then it is that
485
+ * column's own type, named and declared as it always was.
486
+ */
487
+ var sharedEnumName = (type, table, column) => type.name !== void 0 && type.name !== `${table}_${column}` ? type.name : void 0;
488
+ /**
489
+ * The Drizzle variable of a shared enum type: one per type, whichever columns
490
+ * use it, so it is named after the type (and its schema, outside `public`)
491
+ * rather than after any one column. The `Enum` suffix keeps it apart from the
492
+ * table variables, which are named after tables in the same namespace.
493
+ */
494
+ var sharedEnumVarName = (schema, name) => `${getTableVarName(schema === "public" ? name : `${schema}_${name}`)}Enum`;
495
+ var definedEnumType = (type, site) => {
496
+ const { table, schema } = site;
497
+ const labels = type.values.filter((label) => label.length > 0);
498
+ if (labels.length === 0) throw new Error(`Column "${site.column}" of "${site.owner}" is an enum with no values. A Postgres enum type needs at least one label.`);
499
+ const shared = sharedEnumName(type, table, site.column);
500
+ return {
501
+ kind: "enum",
502
+ schema,
503
+ name: shared ?? `${table}_${site.column}`,
504
+ varName: shared ? sharedEnumVarName(schema, shared) : getEnumVarName(table, site.propName),
505
+ labels
506
+ };
507
+ };
508
+ /** The enum type a defined column's values are typed by — its own, or its items'. */
509
+ var definedEnumOf = (type) => {
510
+ if (type.kind === "enum") return type;
511
+ if (type.kind === "array" && type.of.kind === "enum") return type.of;
512
+ };
513
+ /**
514
+ * A column's DEFAULT, from its descriptor.
515
+ *
516
+ * The precedence the legacy reading has — the key's strategy, then the time
517
+ * stamp, then a SQL expression, then a literal — over the one `default` a
518
+ * column holds. `identity` is planned on any integer column, key or not, at
519
+ * the width the column declares. `database` plans none: the database owns
520
+ * that default. A generated column has none at all.
521
+ */
522
+ var describedColumnDefault = (column, type) => {
523
+ if (column.generated !== void 0) return void 0;
524
+ const declared = column.default;
525
+ if (declared?.kind === "identity") return { kind: "identity" };
526
+ if (column.primaryKey) {
527
+ if (declared?.kind === "random-uuid") return {
528
+ kind: "sql",
529
+ expression: "gen_random_uuid()"
530
+ };
531
+ if (declared?.kind === "sql") return {
532
+ kind: "sql",
533
+ expression: declared.expression
534
+ };
535
+ }
536
+ if (column.stamp?.value === "now" && (type.kind === "timestamptz" || type.kind === "date" || type.kind === "time")) return {
537
+ kind: "sql",
538
+ expression: "now()"
539
+ };
540
+ if (declared?.kind === "random-uuid") return {
541
+ kind: "sql",
542
+ expression: "gen_random_uuid()"
543
+ };
544
+ if (declared?.kind === "sql") {
545
+ const expression = declared.expression.trim();
546
+ return expression ? {
547
+ kind: "sql",
548
+ expression
549
+ } : void 0;
550
+ }
551
+ if (declared?.kind !== "literal") return void 0;
552
+ return definedLiteralDefault(declared.value, type);
553
+ };
554
+ /**
555
+ * A literal default, as the column's type quotes it. The same spellings as
556
+ * {@link literalDefault}, chosen by the Postgres type rather than by the
557
+ * property's: a native array, a vector and a `bytea` take none (the driver
558
+ * still applies the value on create), exactly as their legacy reading did.
559
+ */
560
+ var definedLiteralDefault = (value, type) => {
561
+ if (value === void 0 || value === null) return void 0;
562
+ switch (type.kind) {
563
+ case "text":
564
+ case "varchar":
565
+ case "char":
566
+ case "uuid":
567
+ case "enum": return typeof value === "string" ? {
568
+ kind: "literal",
569
+ value,
570
+ sql: quoteSqlLiteral(value)
571
+ } : void 0;
572
+ case "smallint":
573
+ case "integer":
574
+ case "bigint":
575
+ case "smallserial":
576
+ case "serial":
577
+ case "bigserial":
578
+ case "real":
579
+ case "doublePrecision":
580
+ case "numeric": return typeof value === "number" && Number.isFinite(value) ? {
581
+ kind: "literal",
582
+ value,
583
+ sql: String(value)
584
+ } : void 0;
585
+ case "boolean": return typeof value === "boolean" ? {
586
+ kind: "literal",
587
+ value,
588
+ sql: value ? "TRUE" : "FALSE"
589
+ } : void 0;
590
+ case "timestamptz":
591
+ case "date":
592
+ case "time": {
593
+ const literal = dateDefaultLiteral(value, type);
594
+ return literal === void 0 ? void 0 : {
595
+ kind: "literal",
596
+ value: literal,
597
+ sql: quoteSqlLiteral(literal)
598
+ };
599
+ }
600
+ case "custom": return typeof value === "string" && !/\]\s*$/.test(type.sqlType) ? {
601
+ kind: "literal",
602
+ value,
603
+ sql: quoteSqlLiteral(value)
604
+ } : void 0;
605
+ case "json":
606
+ case "jsonb": {
607
+ let json;
608
+ try {
609
+ json = JSON.stringify(value);
610
+ } catch {
611
+ return;
612
+ }
613
+ if (json === void 0) return void 0;
614
+ return {
615
+ kind: "literal",
616
+ value,
617
+ sql: `${quoteSqlLiteral(json)}::${type.kind}`
618
+ };
619
+ }
620
+ default: return;
621
+ }
622
+ };
623
+ /**
624
+ * One column planned from its descriptor — collection table and junction
625
+ * pivot alike. {@link planPropertyColumn} hands over to it whenever the table
626
+ * describes the column.
627
+ */
628
+ function planDescribedColumn(described, ctx) {
629
+ const { site, auth } = ctx;
630
+ const { schema, table } = site;
631
+ const { key, column } = described;
632
+ const isKey = described.primaryKey === true;
633
+ const type = describedPgType(described, site);
634
+ const authDefinition = auth && !isKey ? authUsersColumnDefinition(column) : void 0;
635
+ const plan = {
636
+ key,
637
+ column,
638
+ type,
639
+ nullable: !isKey && described.nullable,
640
+ primaryKey: isKey,
641
+ unique: !isKey && described.unique === true,
642
+ default: describedColumnDefault(described, type),
643
+ sqlDefinition: authDefinition,
644
+ source: {
645
+ kind: "property",
646
+ propName: key,
647
+ slug: ctx.slug
648
+ }
649
+ };
650
+ if (described.generated !== void 0) plan.generated = {
651
+ expression: described.generated.expression,
652
+ stored: true
653
+ };
654
+ if (described.stamp?.on === "update" && described.stamp.value === "now") {
655
+ plan.touchOnUpdate = true;
656
+ ctx.triggerFunctionNeeded.value = true;
657
+ ctx.triggers.push({
658
+ schema,
659
+ table,
660
+ column,
661
+ name: toPostgresIdentifier(`${table}_${column}_touch`)
662
+ });
663
+ }
664
+ return plan;
665
+ }
666
+ /**
667
+ * One security rule of a table, compiled to its policies — what
668
+ * the legacy `compileSecurityRule` does for a collection, read from the table's
669
+ * {@link PolicyTable} (`policyTableFromDescriptor`, `junctionPolicyTable`).
670
+ */
671
+ var compileTableSecurityRule = (table, rule, resolveTable, injected, ruleKey = rule.name ?? "(unnamed)") => policyPlans(compileTableRulePolicies(table, rule, {
672
+ resolveTable,
673
+ adminRole: true,
674
+ adminRequestRole: true
675
+ }), getPolicySupersededNames(rule, table.table), injected, ruleKey);
676
+ /** The planner's bookkeeping over one rule's compiled policies. */
677
+ var policyPlans = (compiled, supersedes, injected, ruleKey) => {
678
+ const plans = [];
679
+ for (const policy of compiled) {
680
+ if (policy.adminRequestTarget) {
681
+ const base = plans[plans.length - 1];
682
+ if (base) base.adminRequestCompanion = {
683
+ name: policy.name,
684
+ using: policy.using,
685
+ withCheck: policy.withCheck
686
+ };
687
+ continue;
688
+ }
689
+ plans.push({
690
+ ...policy,
691
+ ruleKey,
692
+ injected,
693
+ ...plans.length === 0 && supersedes.length > 0 ? { supersedes } : {}
694
+ });
695
+ }
696
+ return plans;
697
+ };
698
+ /**
699
+ * Refuse two of a table's policies that Postgres would store under one name.
700
+ *
701
+ * Each policy is rendered as `DROP POLICY IF EXISTS "<name>"` and then its
702
+ * `CREATE`, and Postgres keeps the first 63 bytes of the name, so the second
703
+ * of two policies whose names share those bytes drops the first and takes its
704
+ * place. On a table of 56 bytes or more every unnamed rule of one operation is
705
+ * `<table>_<op>` once stored, so a restrictive gate followed by a grant left
706
+ * the grant alone in force. One rule's own operations never collide here —
707
+ * `getPolicyNamesForRule` names them apart — so a collision is always two
708
+ * rules, and the author names one of them.
709
+ */
710
+ var sameStoredPolicy = (a, b) => a.name === b.name && a.operation === b.operation && a.mode === b.mode && a.roles.join(",") === b.roles.join(",") && a.using === b.using && a.withCheck === b.withCheck;
711
+ function assertDistinctStoredPolicyNames(policies) {
712
+ const owners = /* @__PURE__ */ new Map();
713
+ for (const policy of policies) {
714
+ const stored = toPostgresIdentifier(policy.name);
715
+ const first = owners.get(stored);
716
+ if (!first) {
717
+ owners.set(stored, policy);
718
+ continue;
719
+ }
720
+ if (sameStoredPolicy(first, policy)) continue;
721
+ throw new Error(`The security rules "${first.ruleKey}" and "${policy.ruleKey}" compile to the policies "${first.name}" and "${policy.name}", which Postgres stores under one name, "${stored}": it keeps only the first 63 bytes of an identifier, so the second would replace the first. Give one of the rules a shorter \`name\`, or the table a shorter name.`);
722
+ }
723
+ }
724
+ /**
725
+ * A table's policies, minus any superseded name Postgres would store one of
726
+ * them under.
727
+ *
728
+ * A superseded name is a 63-byte cut, and another rule's over-long name can
729
+ * cut to the very same bytes — `<table>_default_admin_read` and the old
730
+ * `<table>_default_admin_write_<op>` both do on a 50-byte table. Dropping it
731
+ * then would drop that policy right after its own `CREATE`. Its own `DROP
732
+ * POLICY IF EXISTS` already removes the old policy, so nothing is lost.
733
+ */
734
+ var withoutLiveSupersededNames = (policies) => {
735
+ assertDistinctStoredPolicyNames(policies);
736
+ const stored = new Set(policies.map((policy) => toPostgresIdentifier(policy.name)));
737
+ return policies.map((policy) => {
738
+ if (!policy.supersedes) return policy;
739
+ const supersedes = policy.supersedes.filter((name) => !stored.has(name));
740
+ if (supersedes.length === policy.supersedes.length) return policy;
741
+ const kept = { ...policy };
742
+ if (supersedes.length > 0) kept.supersedes = supersedes;
743
+ else delete kept.supersedes;
744
+ return kept;
745
+ });
746
+ };
747
+ /**
748
+ * Everything a set of tables asks the database for.
749
+ *
750
+ * The input is the compiled tables — what `compileSchema` returns and every
751
+ * door (`loadTables`, boot, the CLI) hands over. Planned in the order given:
752
+ * the callers sort by slug first, and the generated files keep that order.
753
+ *
754
+ * @param compiledTables the compiled tables, in slug order.
755
+ * @param options the planner's world: the extensions it may install.
756
+ */
757
+ function planSchema(compiledTables, options = {}) {
758
+ const descriptors = compiledTables.map((table) => table.descriptor);
759
+ const descriptorOf = new Map(descriptors.map((descriptor) => [descriptor.slug, descriptor]));
760
+ const targetOf = (slug) => {
761
+ const target = descriptorOf.get(slug);
762
+ if (!target) throw new Error(`Internal: a relation points at the table "${slug}", which is not among the planned tables.`);
763
+ return target;
764
+ };
765
+ const tableDescriptors = descriptors.filter((descriptor) => descriptor.kind !== "view");
766
+ const declaredSchemas = Array.from(new Set(tableDescriptors.flatMap((descriptor) => {
767
+ const declared = declaredSchemaOf(descriptor);
768
+ return declared === void 0 ? [] : [declared];
769
+ })));
770
+ const schemas = Array.from(/* @__PURE__ */ new Set([REBASE_SCHEMA, ...declaredSchemas]));
771
+ const enums = [];
772
+ const enumOwners = /* @__PURE__ */ new Map();
773
+ /**
774
+ * The enum type a column is typed by, appended once.
775
+ *
776
+ * A column's own type (`<table>_<column>`) is claimed by that column alone,
777
+ * as above. A type the definition names (`pgEnum(name, values)`) is
778
+ * shared: every column naming it is typed by the one `CREATE TYPE`, and
779
+ * they must agree on its values — `compileTables` refuses a disagreement
780
+ * first, and so does this, for a plan reached any other way.
781
+ *
782
+ * `declaredSchema` is passed rather than read off the site because a
783
+ * junction's `public` is a resolved fact and not a declaration — emitting
784
+ * it as one would make the generated file reach for a `pgSchema("public")`
785
+ * variable that exists for nobody.
786
+ */
787
+ const collectEnumType = (site, described, declaredSchema) => {
788
+ const owner = `column "${described.key}" of "${site.owner}"`;
789
+ if (described.oneOf !== void 0 && described.oneOf.every((value) => String(value).length === 0)) throw new Error(`The ${owner} is \`.oneOf()\` with no non-empty value, so no value can be written to it. List the values the column accepts.`);
790
+ const enumType = definedEnumOf(describedPgType(described, site));
791
+ if (!enumType) return;
792
+ const { schema, name, labels } = enumType;
793
+ const { table, column } = site;
794
+ const qualified = `${schema}.${toPostgresIdentifier(name)}`;
795
+ const shared = name === `${table}_${column}` ? void 0 : {
796
+ name,
797
+ labels
798
+ };
799
+ const claimed = enumOwners.get(qualified);
800
+ if (claimed) {
801
+ if (claimed.table === table && claimed.column === column) return;
802
+ if (shared && claimed.shared?.name === name) {
803
+ if (claimed.shared.labels.join("\0") === labels.join("\0")) return;
804
+ throw new Error(`The enum type "${schema}"."${name}" is given the values (${labels.join(", ")}) by the ${owner} and (${claimed.shared.labels.join(", ")}) by the ${claimed.owner}. Columns sharing a named enum type must list the same values, in the same order. Make them agree, or give one column its own type \`name\`.`);
805
+ }
806
+ throw new Error(`The enum ${owner} and the enum ${claimed.owner} both derive the Postgres type "${schema}"."${toPostgresIdentifier(name)}" (Postgres keeps the first 63 bytes of a name). One type cannot hold both columns' values, and a type's name cannot change once a database holds it. Give one of the two columns another name with \`.column()\`, its table another \`table\` or \`schema\`, or its enum another \`name\`.`);
807
+ }
808
+ enumOwners.set(qualified, {
809
+ table,
810
+ column,
811
+ owner,
812
+ shared
813
+ });
814
+ enums.push({
815
+ schema,
816
+ name,
817
+ qualified,
818
+ declaredSchema,
819
+ varName: enumType.varName,
820
+ labels
821
+ });
822
+ };
823
+ for (const descriptor of tableDescriptors) {
824
+ const declaredSchema = declaredSchemaOf(descriptor);
825
+ for (const entry of plannedColumnEntries(descriptor, targetOf)) {
826
+ if (entry.kind !== "column") continue;
827
+ collectEnumType(describedSite(descriptor, entry.column), entry.column, declaredSchema);
828
+ }
829
+ }
830
+ const tableJunctions = resolveTableJunctions(descriptors);
831
+ const resolvePolicyTable = policyTableResolver(descriptors);
832
+ const tableEntries = /* @__PURE__ */ new Map();
833
+ const junctionShapes = /* @__PURE__ */ new Map();
834
+ for (const descriptor of tableDescriptors) {
835
+ tableEntries.set(descriptor.table, {
836
+ kind: "table",
837
+ descriptor
838
+ });
839
+ for (const relation of descriptor.relations) {
840
+ if (relation.kind !== "manyToMany") continue;
841
+ const junctionTable = relation.through.table;
842
+ assertOneJunctionShape(junctionShapes, junctionTable, descriptor, relation, targetOf(relation.target));
843
+ if (tableEntries.has(junctionTable)) continue;
844
+ const junction = tableJunctions.get(bareTableName(junctionTable));
845
+ if (!junction) throw new Error(`Internal: the junction table "${junctionTable}" of "${descriptor.slug}" was not resolved.`);
846
+ tableEntries.set(junctionTable, {
847
+ kind: "junction",
848
+ junction
849
+ });
850
+ }
851
+ }
852
+ for (const junction of tableJunctions.values()) {
853
+ const keys = new Set(junction.endpoints.map((endpoint) => endpoint.junctionColumn));
854
+ for (const pivotColumn of junction.pivot) {
855
+ if (keys.has(pivotColumn.column)) continue;
856
+ collectEnumType(junctionSite(junction, pivotColumn), pivotColumn, void 0);
857
+ }
858
+ }
859
+ const triggerFunctionNeeded = { value: false };
860
+ const tables = [];
861
+ for (const entry of tableEntries.values()) tables.push(entry.kind === "junction" ? planJunctionTable(entry.junction, targetOf, resolvePolicyTable, triggerFunctionNeeded) : planCollectionTable(entry.descriptor, resolvePolicyTable, targetOf, triggerFunctionNeeded));
862
+ assertNoTruncationCollisions(tables, enums);
863
+ const extensions = [];
864
+ const functions = [];
865
+ const seenStatements = /* @__PURE__ */ new Set();
866
+ const add = (into, statement) => {
867
+ if (seenStatements.has(statement)) return;
868
+ seenStatements.add(statement);
869
+ into.push(statement);
870
+ };
871
+ for (const table of tables) {
872
+ if (!table.search) continue;
873
+ for (const statement of searchExtensionStatements(table.search)) add(extensions, statement);
874
+ }
875
+ if (vectorExtensionDeclared(options.databaseExtensions) && tables.some((t) => t.vectorColumns.length > 0)) add(extensions, vectorExtensionStatement());
876
+ for (const table of tables) {
877
+ if (!table.search) continue;
878
+ for (const statement of searchHelperFunctions(table.search)) add(functions, statement);
879
+ }
880
+ if (triggerFunctionNeeded.value) add(functions, setUpdatedAtFunction());
881
+ if (tables.some((t) => t.triggers.some((trigger) => trigger.kind === "keep-tenant"))) add(functions, keepTenantFunction());
882
+ return {
883
+ schemas,
884
+ declaredSchemas,
885
+ enums,
886
+ tables,
887
+ views: planViews(descriptors),
888
+ relations: planRelations(tableDescriptors, tableEntries, targetOf),
889
+ extensions,
890
+ functions,
891
+ options
892
+ };
893
+ }
894
+ /**
895
+ * The views the tables declare (`defineView`), each after the views its query
896
+ * names.
897
+ *
898
+ * Which views a query reads is read off its text — a planned view's name as a
899
+ * whole word — which is enough to order them: a name that appears in a string
900
+ * literal only orders two views that did not need it, never the other way.
901
+ */
902
+ function planViews(tables) {
903
+ const declared = tables.flatMap((descriptor) => {
904
+ const view = descriptor.view;
905
+ if (descriptor.kind !== "view" || !view || view.query === void 0) return [];
906
+ const { schema, table: name } = descriptor;
907
+ const idColumns = descriptor.primaryKey.map((key) => columnNameOf(descriptor, key) ?? key);
908
+ const materialized = view.materialized;
909
+ return [{
910
+ schema,
911
+ name,
912
+ qualified: `${schema}.${name}`,
913
+ query: view.query.trim().replace(/;\s*$/, ""),
914
+ materialized,
915
+ roles: materialized ? [...view.roles ?? DEFAULT_VIEW_ROLES] : [],
916
+ idColumns,
917
+ indexes: materialized ? buildTableIndexSpecs(descriptor).map((spec) => tableIndexStatement({
918
+ ...spec,
919
+ table: viewRowsName(name)
920
+ }).replace(/;$/, "")) : []
921
+ }];
922
+ });
923
+ const named = (query, view) => new RegExp(`(^|[^A-Za-z0-9_$"])"?${escapeRegExp(view.name)}"?([^A-Za-z0-9_$"]|$)`).test(query);
924
+ const withDependencies = declared.map((view) => ({
925
+ ...view,
926
+ dependsOn: declared.filter((other) => other !== view && named(view.query, other)).map((other) => other.qualified)
927
+ }));
928
+ const ordered = [];
929
+ const placed = /* @__PURE__ */ new Set();
930
+ const visiting = /* @__PURE__ */ new Set();
931
+ const place = (view) => {
932
+ if (placed.has(view.qualified)) return;
933
+ if (visiting.has(view.qualified)) throw new Error(`The views ${[...visiting].join(", ")} read each other; a view cannot be created before the view it reads.`);
934
+ visiting.add(view.qualified);
935
+ for (const dependency of view.dependsOn) {
936
+ const target = withDependencies.find((other) => other.qualified === dependency);
937
+ if (target) place(target);
938
+ }
939
+ visiting.delete(view.qualified);
940
+ placed.add(view.qualified);
941
+ ordered.push(view);
942
+ };
943
+ for (const view of withDependencies) place(view);
944
+ return ordered.map((view) => ({
945
+ ...view,
946
+ hash: createHash("sha256").update(JSON.stringify([
947
+ view.qualified,
948
+ view.query,
949
+ view.materialized,
950
+ view.idColumns,
951
+ ...view.materialized ? [
952
+ "gated",
953
+ view.roles,
954
+ view.indexes
955
+ ] : []
956
+ ])).digest("hex").slice(0, 16)
957
+ }));
958
+ }
959
+ function escapeRegExp(text) {
960
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
961
+ }
962
+ /**
963
+ * Refuse two relations — tables, junctions and enum types share one namespace
964
+ * per schema, because every table owns a row type of its own name — that are
965
+ * distinct in full but one name after Postgres keeps the first 63 bytes.
966
+ *
967
+ * `a_table_with_a_really_long_name_that_goes_on_and_on_and_on_forever` with an
968
+ * enum column and a many-to-many truncated its table, its enum type and its
969
+ * junction to the same identifier: the push failed with `type "…" already
970
+ * exists` and no validator mentioned the length. A name that already works is
971
+ * never touched — only a collision that cannot be created refuses.
972
+ */
973
+ function assertNoTruncationCollisions(tables, enums) {
974
+ const owners = /* @__PURE__ */ new Map();
975
+ const claim = (schema, name, what) => {
976
+ const key = `${schema}.${toPostgresIdentifier(name)}`;
977
+ const first = owners.get(key);
978
+ if (first === void 0) {
979
+ owners.set(key, what);
980
+ return;
981
+ }
982
+ throw new Error(`The ${what} and the ${first} both become "${schema}"."${toPostgresIdentifier(name)}" in Postgres, which keeps only the first 63 bytes of an identifier — and a table, a junction table and an enum type share one namespace (every table owns a row type of its name). The push would fail with "already exists". Give the table a shorter name, or the enum's property a shorter \`columnName\` (an enum type is named <table>_<column>).`);
983
+ };
984
+ for (const table of tables) claim(table.schema, table.table, table.kind === "junction" ? `junction table "${table.table}"` : `table "${table.table}"`);
985
+ for (const e of enums) claim(e.schema, e.name, `enum type "${e.name}"`);
986
+ }
987
+ /**
988
+ * Refuse two many-to-many relations that resolve to one junction table with
989
+ * different key columns.
990
+ *
991
+ * A default `through` is named after the two tables, so `posts.tags` and
992
+ * `posts.featuredTags` both resolve to `posts_tags` — one keyed by `tag_id`,
993
+ * the other by `featured_tag_id`. One table is created, from whichever came
994
+ * first, so the other relation read and wrote a column that was never there.
995
+ * The two sides of one link (`posts.tags` and `tags.posts`) share a junction
996
+ * legitimately, and they name the same two columns — so the comparison is of
997
+ * the (column, endpoint) pairs, in either order.
998
+ */
999
+ function assertOneJunctionShape(seen, junctionTable, descriptor, relation, target) {
1000
+ const sourceTable = descriptor.table;
1001
+ const targetTable = target.table;
1002
+ const { sourceKey, targetKey } = relation.through;
1003
+ const keys = JSON.stringify([[sourceKey, sourceTable], [targetKey, targetTable]].sort());
1004
+ const claim = `the relation "${relation.name}" of table "${descriptor.slug}" ("${sourceKey}" → ${sourceTable}, "${targetKey}" → ${targetTable})`;
1005
+ const first = seen.get(junctionTable);
1006
+ if (!first) {
1007
+ seen.set(junctionTable, {
1008
+ keys,
1009
+ claim
1010
+ });
1011
+ return;
1012
+ }
1013
+ if (first.keys === keys) return;
1014
+ throw new Error(`Two many-to-many relations resolve to the junction table "${junctionTable}" with different key columns: ${first.claim} and ${claim}. Only one table is created, so one of them would read and write columns that do not exist. Give the second its own junction — \`through: { table: "${sourceTable}_${toSnakeCase(relation.name)}" }\` — or, if both are meant to be one link, declare it once.`);
1015
+ }
1016
+ /** Where a junction's pivot column lands. */
1017
+ var junctionSite = (junction, column) => ({
1018
+ schema: junction.schema,
1019
+ table: junction.table,
1020
+ owner: junction.table,
1021
+ propName: column.key,
1022
+ column: column.column
1023
+ });
1024
+ function planCollectionTable(descriptor, resolvePolicyTable, targetOf, triggerFunctionNeeded) {
1025
+ const { schema, table, slug } = descriptor;
1026
+ const auth = descriptor.auth !== void 0;
1027
+ const columns = [];
1028
+ const triggers = [];
1029
+ for (const entry of plannedColumnEntries(descriptor, targetOf)) {
1030
+ if (entry.kind === "link") {
1031
+ columns.push(planLinkColumn(entry, descriptor, targetOf));
1032
+ continue;
1033
+ }
1034
+ columns.push(planDescribedColumn(entry.column, {
1035
+ site: describedSite(descriptor, entry.column),
1036
+ slug,
1037
+ auth,
1038
+ triggers,
1039
+ triggerFunctionNeeded
1040
+ }));
1041
+ }
1042
+ if (auth) {
1043
+ const declared = new Set(columns.map((c) => c.column));
1044
+ for (const spec of AUTH_USERS_COLUMNS) {
1045
+ if (declared.has(spec.column)) continue;
1046
+ columns.push({
1047
+ key: spec.column,
1048
+ column: spec.column,
1049
+ type: authColumnType(spec.type),
1050
+ nullable: spec.notNull !== true,
1051
+ primaryKey: false,
1052
+ unique: false,
1053
+ sqlDefinition: authUsersColumnSql(spec),
1054
+ source: {
1055
+ kind: "auth",
1056
+ slug
1057
+ }
1058
+ });
1059
+ }
1060
+ }
1061
+ const search = buildTableSearchColumnSpec(descriptor);
1062
+ if (search) {
1063
+ columns.push({
1064
+ key: search.column,
1065
+ column: search.column,
1066
+ type: { kind: "tsvector" },
1067
+ nullable: true,
1068
+ primaryKey: false,
1069
+ unique: false,
1070
+ generated: {
1071
+ expression: search.expression,
1072
+ stored: true
1073
+ },
1074
+ sqlDefinition: searchColumnTypeSql(search.expression, "tsvector"),
1075
+ source: {
1076
+ kind: "search",
1077
+ slug
1078
+ }
1079
+ });
1080
+ if (search.fuzzy) columns.push({
1081
+ key: search.fuzzy.column,
1082
+ column: search.fuzzy.column,
1083
+ type: { kind: "text" },
1084
+ nullable: true,
1085
+ primaryKey: false,
1086
+ unique: false,
1087
+ generated: {
1088
+ expression: search.fuzzy.expression,
1089
+ stored: true
1090
+ },
1091
+ sqlDefinition: searchColumnTypeSql(search.fuzzy.expression, "text"),
1092
+ source: {
1093
+ kind: "search",
1094
+ slug
1095
+ }
1096
+ });
1097
+ }
1098
+ const primaryKey = planPrimaryKey(descriptor, columns);
1099
+ const policyTable = resolvePolicyTable(descriptor.slug) ?? policyTableFromDescriptor(descriptor);
1100
+ const injected = new Set(tableInjectedRules(policyTable).map((rule) => rule.name));
1101
+ const policies = withoutLiveSupersededNames(tableEffectiveRules(policyTable).flatMap((rule, index) => compileTableSecurityRule(policyTable, rule, resolvePolicyTable, Boolean(rule.name && injected.has(rule.name)), rule.name ?? `#${index}`)));
1102
+ const tenantIndexes = applyTenantColumnEffects(descriptor, columns, primaryKey);
1103
+ const keepTenant = planKeepTenantTrigger(descriptor, columns);
1104
+ if (keepTenant) triggers.push(keepTenant);
1105
+ settleDefaultOnDelete(descriptor, columns);
1106
+ const indexes = [...buildTableIndexSpecs(descriptor), ...tenantIndexes];
1107
+ indexes.push(...planForeignKeyIndexes(schema, table, columns, primaryKey, indexes, (column) => {
1108
+ const relation = linkRelationOf(descriptor, column);
1109
+ if (!relation?.index) return void 0;
1110
+ return column.foreignKey?.column ?? (writtenWithoutConstraint(descriptor, relation, targetOf(relation.target)) ? column.column : void 0);
1111
+ }));
1112
+ return {
1113
+ schema,
1114
+ table,
1115
+ qualified: `${schema}.${table}`,
1116
+ declaredSchema: declaredSchemaOf(descriptor),
1117
+ varName: getTableVarName(table),
1118
+ kind: "collection",
1119
+ slug,
1120
+ columns,
1121
+ primaryKey,
1122
+ indexes,
1123
+ search,
1124
+ vector: buildTableVectorIndexPlan(descriptor),
1125
+ vectorColumns: buildTableVectorColumnSpecs(descriptor),
1126
+ policies,
1127
+ triggers,
1128
+ auth
1129
+ };
1130
+ }
1131
+ /**
1132
+ * The table's primary key, as the column names {@link TablePlan.primaryKey}
1133
+ * lists — and the columns adjusted to state it one way only.
1134
+ *
1135
+ * One `isId` property is a key column of its own, declared inline
1136
+ * (`"id" INTEGER PRIMARY KEY`, `.primaryKey()`), which is how
1137
+ * {@link planPropertyColumn} planned it. Several are one composite key, and a
1138
+ * composite key cannot be said column by column: two inline `PRIMARY KEY`
1139
+ * clauses are two primary keys, which Postgres refuses. So each member stops
1140
+ * being a key of its own, keeps NOT NULL (the constraint implies it, and every
1141
+ * emitter spells it on the column so the three read the same), and the table
1142
+ * gets one `PRIMARY KEY (a, b)` over the list returned here — the shape a
1143
+ * junction's key has always had.
1144
+ *
1145
+ * A table that declares no key gets an implicit `id TEXT PRIMARY KEY`,
1146
+ * which is what `getPrimaryKeys` reads back.
1147
+ */
1148
+ function planPrimaryKey(descriptor, columns) {
1149
+ const keyNames = descriptor.primaryKey;
1150
+ if (keyNames.length > 1) return keyNames.map((name) => {
1151
+ const column = columns.find((c) => c.source.propName === name && !c.columnOwnedByProperty);
1152
+ if (!column) throw new Error(`Column "${name}" of table "${descriptor.slug}" is part of the primary key, and it puts no column on this table, so it cannot be part of the table's primary key. Mark the column that holds it \`.primaryKey()\` instead.`);
1153
+ column.primaryKey = false;
1154
+ column.nullable = false;
1155
+ return column.column;
1156
+ });
1157
+ if (!columns.some((c) => c.primaryKey)) columns.unshift({
1158
+ key: "id",
1159
+ column: "id",
1160
+ type: { kind: "text" },
1161
+ nullable: false,
1162
+ primaryKey: true,
1163
+ unique: false,
1164
+ default: {
1165
+ kind: "sql",
1166
+ expression: IMPLICIT_ID_DEFAULT
1167
+ },
1168
+ source: {
1169
+ kind: "implicit-id",
1170
+ slug: descriptor.slug
1171
+ }
1172
+ });
1173
+ return columns.filter((c) => c.primaryKey).map((c) => c.column);
1174
+ }
1175
+ /**
1176
+ * The two schema effects a `tenant` declaration has that a policy cannot state.
1177
+ *
1178
+ * The policy itself is injected as an ordinary `SecurityRule`
1179
+ * (`buildTenantSecurityRule`) and compiled above with every other rule, so
1180
+ * nothing here touches `policies`. What is left is the column:
1181
+ *
1182
+ * - **`NOT NULL`.** A row whose tenant is NULL belongs to nobody, and the
1183
+ * restrictive policy compares the column to the caller's tenant — a
1184
+ * comparison against NULL is never true. Such a row is therefore invisible to
1185
+ * every caller, forever, including the one who wrote it. The write path
1186
+ * refuses to create one (`TENANT_REQUIRED`); this is the same statement made
1187
+ * where a raw `INSERT`, a seed and a migration can also hear it.
1188
+ * - **An index.** The tenancy predicate is ANDed into *every* statement against
1189
+ * the table, so an unindexed tenant column turns every read into a sequential
1190
+ * scan filtered by tenant. It is the one index a tenant-scoped table cannot
1191
+ * be without, and the one people most reliably forget — which is the whole
1192
+ * argument for deriving it rather than documenting it.
1193
+ *
1194
+ * The index goes through `deriveIndexName` like every other index, so it is a
1195
+ * Rebase-managed name (`_ix_<fingerprint>`), it is in the Atlas diff, and the
1196
+ * doctor recognises it. Because that name is a fingerprint of the index's
1197
+ * semantics, an author who has *already* declared a plain btree index on the
1198
+ * tenant column derives byte-for-byte the same name — so the two are the same
1199
+ * object and this adds nothing rather than colliding.
1200
+ *
1201
+ * Throws when the field names no column. `planSchema` throws rather than
1202
+ * guessing, and the alternative here is a table with a tenancy policy over a
1203
+ * column that does not exist: `CREATE POLICY` fails, RLS stays enabled, and the
1204
+ * collection denies every row.
1205
+ */
1206
+ function applyTenantColumnEffects(descriptor, columns, primaryKey) {
1207
+ const tenant = tenantOf(descriptor);
1208
+ if (!tenant) return [];
1209
+ const { schema, table } = descriptor;
1210
+ const column = findTenantColumn(descriptor, columns, tenant.field);
1211
+ if (!column) throw new Error(`Table "${descriptor.slug}" declares \`tenant: { field: "${tenant.field}" }\`, and no column of that key is created on it. \`tenant\` says what a column means; it does not create one. Declare the column, or name the one that holds the tenant id.`);
1212
+ if (primaryKey[0] === column.column) return [];
1213
+ column.nullable = false;
1214
+ const withoutName = {
1215
+ schema,
1216
+ table,
1217
+ method: "btree",
1218
+ unique: false,
1219
+ keys: [{
1220
+ column: column.column,
1221
+ direction: "asc",
1222
+ nulls: "last"
1223
+ }],
1224
+ include: [],
1225
+ predicate: null,
1226
+ reason: TENANT_INDEX_REASON
1227
+ };
1228
+ return [{
1229
+ ...withoutName,
1230
+ indexName: deriveIndexName(withoutName)
1231
+ }];
1232
+ }
1233
+ /**
1234
+ * The trigger that keeps a row in its tenant, or nothing when the collection
1235
+ * declares no `tenant`. See `tenant-keep-trigger.ts` for why a policy cannot.
1236
+ */
1237
+ function planKeepTenantTrigger(descriptor, columns) {
1238
+ const tenant = tenantOf(descriptor);
1239
+ if (!tenant) return void 0;
1240
+ const column = findTenantColumn(descriptor, columns, tenant.field);
1241
+ if (!column) return void 0;
1242
+ const { schema, table } = descriptor;
1243
+ return {
1244
+ schema,
1245
+ table,
1246
+ column: column.column,
1247
+ name: toPostgresIdentifier(keepTenantTriggerName(table)),
1248
+ kind: "keep-tenant",
1249
+ bypassRoles: [...tenant.bypassRoles]
1250
+ };
1251
+ }
1252
+ /**
1253
+ * A btree on each foreign-key column of one table, where nothing already
1254
+ * serves the lookup — see `foreignKeyIndexSpec` for why the column needs one.
1255
+ * `linkColumn` names the column a planned column links by, or nothing for a
1256
+ * column that wants no such index (an opted-out link, a plain column).
1257
+ *
1258
+ * Skipped, so that no table ever carries two indexes doing one job, when the
1259
+ * column already leads:
1260
+ *
1261
+ * - the primary key — `<table>_pkey` is a btree over the key in key order, so
1262
+ * its first column is indexed and the rest are not (a junction's
1263
+ * `(post_id, tag_id)` key serves `post_id`, and `tag_id` gets an index);
1264
+ * - a UNIQUE on the column (`validation.unique`, on the relation or on the
1265
+ * property that owns the column) — Postgres backs it with a btree;
1266
+ * - another planned index that leads with it ({@link leadsWithColumn}) — one
1267
+ * the collection declares in `indexes:`, or the tenant index.
1268
+ *
1269
+ * Only the plan is consulted, never the catalogue: `db push` renders this from
1270
+ * the collections alone, and boot has to reach the same set with the same
1271
+ * names, or Atlas would plan to drop what boot built.
1272
+ */
1273
+ function planForeignKeyIndexes(schema, table, columns, primaryKey, planned, linkColumn) {
1274
+ const created = columns.filter((c) => !c.columnOwnedByProperty);
1275
+ const derived = [];
1276
+ for (const column of columns) {
1277
+ const name = linkColumn(column);
1278
+ if (name === void 0) continue;
1279
+ if (primaryKey[0] === name) continue;
1280
+ if (created.some((c) => c.column === name && c.unique)) continue;
1281
+ if ([...planned, ...derived].some((spec) => leadsWithColumn(spec, name))) continue;
1282
+ derived.push(foreignKeyIndexSpec(schema, table, name));
1283
+ }
1284
+ return derived;
1285
+ }
1286
+ /**
1287
+ * The planned column a `tenant.field` names.
1288
+ *
1289
+ * The descriptor's `tenant.field` is a column key — a `belongsTo` named as
1290
+ * the tenant was resolved to its foreign-key column when the table compiled —
1291
+ * so the planned column is the one with that column's SQL name.
1292
+ *
1293
+ * Only columns that are created count. A relation whose column a declared
1294
+ * column owns keeps an entry for its constraint alone, under the same SQL
1295
+ * name; when the relation was declared first, NOT NULL landed on that entry,
1296
+ * nothing rendered it, and the tenant column stayed nullable.
1297
+ */
1298
+ function findTenantColumn(descriptor, columns, field) {
1299
+ const tenantColumn = columnByKey(descriptor, field);
1300
+ if (!tenantColumn) return void 0;
1301
+ return columns.find((c) => !c.columnOwnedByProperty && c.column === tenantColumn.column);
1302
+ }
1303
+ /**
1304
+ * The `ON DELETE` a link gets when the author did not say, decided from the
1305
+ * column as it will be created.
1306
+ *
1307
+ * {@link planLinkColumn} sees only its own link's nullability, and two later facts change the premise: `tenant` makes
1308
+ * its column NOT NULL, and a declared property that owns a relation's column
1309
+ * decides that column's nullability itself. Defaulting before either produced
1310
+ * `NOT NULL … ON DELETE SET NULL` — a parent's delete that can only fail, and
1311
+ * fails with 23502 naming the child's column rather than as the foreign-key
1312
+ * refusal it is. An `onDelete` the author wrote is theirs and is kept.
1313
+ */
1314
+ function settleDefaultOnDelete(descriptor, columns) {
1315
+ for (const column of columns) {
1316
+ const fk = column.foreignKey;
1317
+ if (!fk || linkRelationOf(descriptor, column)?.onDelete !== void 0) continue;
1318
+ const onDelete = defaultBelongsToOnDelete(!(columns.find((c) => c.column === column.column && !c.columnOwnedByProperty) ?? column).nullable);
1319
+ if (onDelete === fk.onDelete) continue;
1320
+ column.foreignKey = foreignKeyPlan({
1321
+ schema: fk.schema,
1322
+ table: fk.table,
1323
+ column: fk.column,
1324
+ targetSchema: fk.targetSchema,
1325
+ targetTable: fk.targetTable,
1326
+ targetColumn: fk.targetColumn,
1327
+ onDelete,
1328
+ onUpdate: fk.onUpdate
1329
+ });
1330
+ }
1331
+ }
1332
+ /**
1333
+ * The column a `belongsTo` link plans, from its descriptor — one of the three
1334
+ * forms {@link plannedColumnEntries} hands over:
1335
+ *
1336
+ * - `absorbed`: the bound column is nothing but the foreign key, so this entry
1337
+ * IS the column, typed as the target's key;
1338
+ * - `constraint`: the bound column is planned on its own; this entry carries
1339
+ * the constraint alone (`columnOwnedByProperty`, skipped as a column by the
1340
+ * renderers) and states the same type and nullability, so one column never
1341
+ * reads two ways in the plan;
1342
+ * - `derived`: the relation derives the column, typed as the target's key.
1343
+ *
1344
+ * `constraint: false` keeps the column and plans no `FOREIGN KEY`; neither
1345
+ * does a link into a view (Postgres refuses one), which the descriptor already
1346
+ * records as `constraint: false`.
1347
+ */
1348
+ function planLinkColumn(entry, descriptor, targetOf) {
1349
+ const { relation, column, form } = entry;
1350
+ const { schema, table, slug } = descriptor;
1351
+ const target = targetOf(relation.target);
1352
+ const targetKey = tableKeyTarget(target, `relation "${slug}.${relation.name}"`);
1353
+ const ownsColumn = form === "constraint";
1354
+ const required = !column.nullable && column.primaryKey !== true;
1355
+ const legacyKey = legacyForeignKeyName(relation.name);
1356
+ const derivedName = relation.localKey === generateForeignKeyName(relation.name);
1357
+ return {
1358
+ key: column.key,
1359
+ column: relation.localKey,
1360
+ type: ownsColumn ? describedPgType(column, describedSite(descriptor, column)) : targetKey.type,
1361
+ nullable: column.nullable,
1362
+ primaryKey: false,
1363
+ unique: !ownsColumn && column.unique === true,
1364
+ columnOwnedByProperty: ownsColumn || void 0,
1365
+ legacyColumn: derivedName && legacyKey !== relation.localKey ? legacyKey : void 0,
1366
+ foreignKey: relation.constraint ? foreignKeyPlan({
1367
+ schema,
1368
+ table,
1369
+ column: relation.localKey,
1370
+ targetSchema: target.schema,
1371
+ targetTable: target.table,
1372
+ targetColumn: targetKey.column,
1373
+ onDelete: relation.onDelete ?? defaultBelongsToOnDelete(required),
1374
+ onUpdate: relation.onUpdate
1375
+ }) : void 0,
1376
+ source: {
1377
+ kind: "relation",
1378
+ propName: relation.name,
1379
+ slug
1380
+ }
1381
+ };
1382
+ }
1383
+ /** The `belongsTo` a planned link column stands for, or `undefined` for any other column. */
1384
+ var linkRelationOf = (descriptor, column) => {
1385
+ if (column.source.kind !== "relation" || !column.source.propName) return void 0;
1386
+ const relation = relationOf(descriptor, column.source.propName);
1387
+ return relation?.kind === "belongsTo" ? relation : void 0;
1388
+ };
1389
+ /**
1390
+ * An auth-owned column's declared SQL type, as a tag.
1391
+ *
1392
+ * `auth-users-columns` states these as SQL because that is the grammar its three
1393
+ * creators write in; the plan needs the tag so nothing downstream has to parse a
1394
+ * type back apart. Deliberately exhaustive rather than a fallback: a column auth
1395
+ * adds with a type nobody mapped should say so here, not turn into `TEXT` in a
1396
+ * table the login flow reads.
1397
+ */
1398
+ var AUTH_COLUMN_TYPES = {
1399
+ "TEXT": { kind: "text" },
1400
+ "TEXT[]": {
1401
+ kind: "array",
1402
+ of: { kind: "text" }
1403
+ },
1404
+ "BOOLEAN": { kind: "boolean" },
1405
+ "JSONB": { kind: "jsonb" },
1406
+ "TIMESTAMP WITH TIME ZONE": { kind: "timestamptz" }
1407
+ };
1408
+ var authColumnType = (sqlType) => {
1409
+ const mapped = AUTH_COLUMN_TYPES[sqlType];
1410
+ if (!mapped) throw new Error(`\`auth-users-columns\` declares a column of type "${sqlType}", which the schema plan has no tag for. Add it to \`AUTH_COLUMN_TYPES\` in schema/plan/plan-schema.ts.`);
1411
+ return mapped;
1412
+ };
1413
+ /**
1414
+ * Which declaring side a junction is planned from.
1415
+ *
1416
+ * With one side, that side — as it always was, so a junction only one end
1417
+ * declares keeps the key every database already has. With both ends declaring
1418
+ * it, the planner used to take whichever it reached first, and the two doors
1419
+ * reach them in different orders: `db push` loads files by name, boot walks the
1420
+ * bundle's array. The same junction was keyed `(a_id, b_id)` by one and
1421
+ * `(b_id, a_id)` by the other, and a push against a boot-built database rebuilt
1422
+ * the key. Now the side whose table sorts first (then its junction column),
1423
+ * which is the order `db push` already used wherever a file is named after its
1424
+ * table. Compared by SQL table name, not slug: that is what every key in the
1425
+ * field was created by.
1426
+ */
1427
+ function canonicalJunctionSide(junction) {
1428
+ const [first, ...rest] = junction.declaringSides;
1429
+ if (rest.length === 0) return first ?? junction.endpoints[0];
1430
+ return [...junction.declaringSides].sort((a, b) => {
1431
+ const left = a.descriptor.table;
1432
+ const right = b.descriptor.table;
1433
+ if (left !== right) return left < right ? -1 : 1;
1434
+ return a.junctionColumn < b.junctionColumn ? -1 : a.junctionColumn > b.junctionColumn ? 1 : 0;
1435
+ })[0];
1436
+ }
1437
+ function planJunctionTable(junction, targetOf, resolvePolicyTable, triggerFunctionNeeded) {
1438
+ const { relation, descriptor: source } = canonicalJunctionSide(junction);
1439
+ const { table } = junction;
1440
+ const schema = junction.schema;
1441
+ const target = targetOf(relation.target);
1442
+ const { sourceKey: sourceColumn, targetKey: targetColumn } = relation.through;
1443
+ const onDelete = relation.onDelete ?? "CASCADE";
1444
+ const legacyFor = (endpoint, column) => {
1445
+ const slug = toSnakeCase(endpoint.slug);
1446
+ const legacy = legacyForeignKeyName(slug);
1447
+ return column === generateForeignKeyName(slug) && legacy !== column ? legacy : void 0;
1448
+ };
1449
+ const via = `relation "${source.slug}.${relation.name}"`;
1450
+ const endpoint = (endpointTable, column) => {
1451
+ const key = tableKeyTarget(endpointTable, via);
1452
+ return {
1453
+ key: column,
1454
+ column,
1455
+ type: key.type,
1456
+ nullable: false,
1457
+ primaryKey: false,
1458
+ unique: false,
1459
+ legacyColumn: legacyFor(endpointTable, column),
1460
+ foreignKey: endpointTable.kind === "view" ? void 0 : foreignKeyPlan({
1461
+ schema,
1462
+ table,
1463
+ column,
1464
+ targetSchema: endpointTable.schema,
1465
+ targetTable: endpointTable.table,
1466
+ targetColumn: key.column,
1467
+ onDelete
1468
+ }),
1469
+ source: { kind: "junction-key" }
1470
+ };
1471
+ };
1472
+ const columns = [endpoint(source, sourceColumn), endpoint(target, targetColumn)];
1473
+ const triggers = [];
1474
+ const keyColumns = /* @__PURE__ */ new Set([sourceColumn, targetColumn]);
1475
+ for (const pivotColumn of junction.pivot) {
1476
+ if (keyColumns.has(pivotColumn.column)) continue;
1477
+ columns.push(planDescribedColumn(pivotColumn, {
1478
+ site: junctionSite(junction, pivotColumn),
1479
+ slug: table,
1480
+ auth: false,
1481
+ triggers,
1482
+ triggerFunctionNeeded
1483
+ }));
1484
+ }
1485
+ const junctionTable = junctionPolicyTable(junction);
1486
+ const policies = withoutLiveSupersededNames(tableJunctionRules(junction).flatMap((rule, index) => compileTableSecurityRule(junctionTable, rule, resolvePolicyTable, false, rule.name ?? `#${index}`)));
1487
+ return {
1488
+ schema,
1489
+ table,
1490
+ qualified: `${schema}.${table}`,
1491
+ varName: getTableVarName(table),
1492
+ kind: "junction",
1493
+ declaringSlugs: junction.declaringSides.map((side) => side.descriptor.slug),
1494
+ columns,
1495
+ primaryKey: [sourceColumn, targetColumn],
1496
+ indexes: planForeignKeyIndexes(schema, table, columns, [sourceColumn, targetColumn], [], (column) => column.source.kind === "junction-key" ? column.foreignKey?.column : void 0),
1497
+ vectorColumns: [],
1498
+ policies,
1499
+ triggers,
1500
+ auth: false
1501
+ };
1502
+ }
1503
+ /**
1504
+ * The `relations(...)` entries the generated file carries.
1505
+ *
1506
+ * Both sides of a link must share a `relationName` or Drizzle cannot pair them;
1507
+ * `tableRelationName` is the rule, and each side derives it independently.
1508
+ */
1509
+ function planRelations(tables, tableEntries, targetOf) {
1510
+ const plans = [];
1511
+ const keyOf = (descriptor, via) => tableKeyTarget(descriptor, via).key;
1512
+ const fkOnTargetBySlug = /* @__PURE__ */ new Map();
1513
+ for (const other of tables) for (const otherRel of other.relations) {
1514
+ if (otherRel.kind !== "hasOne" && otherRel.kind !== "hasMany") continue;
1515
+ const list = fkOnTargetBySlug.get(otherRel.target) ?? [];
1516
+ list.push({
1517
+ other,
1518
+ otherRel
1519
+ });
1520
+ fkOnTargetBySlug.set(otherRel.target, list);
1521
+ }
1522
+ for (const [tableName, entry] of tableEntries) {
1523
+ const tableVar = getTableVarName(tableName);
1524
+ if (entry.kind === "junction") {
1525
+ const { relation, descriptor: source } = entry.junction.endpoints[0];
1526
+ const target = targetOf(relation.target);
1527
+ const via = `relation "${source.slug}.${relation.name}"`;
1528
+ const owningRelationName = tableRelationName(relation, source, targetOf);
1529
+ const inverse = target.relations.find((r) => r.kind === "manyToMany" && bareTableName(r.through.table) === bareTableName(tableName));
1530
+ const inverseRelationName = inverse ? tableRelationName(inverse, target, targetOf) : `${tableName}_${relation.through.targetKey}`;
1531
+ plans.push({
1532
+ tableVar,
1533
+ key: relation.through.sourceKey,
1534
+ kind: "one",
1535
+ targetVar: getTableVarName(source.table),
1536
+ relationName: owningRelationName,
1537
+ fields: [relation.through.sourceKey],
1538
+ references: [keyOf(source, via)]
1539
+ });
1540
+ if (inverseRelationName === owningRelationName) continue;
1541
+ if (target.kind === "view") continue;
1542
+ plans.push({
1543
+ tableVar,
1544
+ key: relation.through.targetKey,
1545
+ kind: "one",
1546
+ targetVar: getTableVarName(target.table),
1547
+ relationName: inverseRelationName,
1548
+ fields: [relation.through.targetKey],
1549
+ references: [keyOf(target, via)]
1550
+ });
1551
+ continue;
1552
+ }
1553
+ const descriptor = entry.descriptor;
1554
+ const emitted = /* @__PURE__ */ new Set();
1555
+ for (const relation of descriptor.relations) {
1556
+ const target = targetOf(relation.target);
1557
+ if (target.kind === "view") continue;
1558
+ const targetVar = getTableVarName(target.table);
1559
+ const relationName = tableRelationName(relation, descriptor, targetOf);
1560
+ const dedupe = `${relationName}::${relation.kind}`;
1561
+ if (emitted.has(dedupe)) continue;
1562
+ emitted.add(dedupe);
1563
+ const via = `relation "${descriptor.slug}.${relation.name}"`;
1564
+ switch (relation.kind) {
1565
+ case "belongsTo":
1566
+ plans.push({
1567
+ tableVar,
1568
+ key: relation.name,
1569
+ kind: "one",
1570
+ targetVar,
1571
+ relationName,
1572
+ fields: [servedKeyOf(descriptor, relation.localKey)],
1573
+ references: [keyOf(target, via)]
1574
+ });
1575
+ break;
1576
+ case "hasOne":
1577
+ plans.push({
1578
+ tableVar,
1579
+ key: relation.name,
1580
+ kind: "one",
1581
+ targetVar,
1582
+ relationName,
1583
+ fields: [relation.sourceKey ? servedKeyOf(descriptor, relation.sourceKey) : keyOf(descriptor, via)],
1584
+ references: [servedKeyOf(target, relation.foreignKey)],
1585
+ nullable: true
1586
+ });
1587
+ break;
1588
+ case "hasMany":
1589
+ plans.push({
1590
+ tableVar,
1591
+ key: relation.name,
1592
+ kind: "many",
1593
+ targetVar,
1594
+ relationName
1595
+ });
1596
+ break;
1597
+ case "manyToMany":
1598
+ plans.push({
1599
+ tableVar,
1600
+ key: relation.name,
1601
+ kind: "many",
1602
+ targetVar: getTableVarName(relation.through.table),
1603
+ relationName
1604
+ });
1605
+ break;
1606
+ case "via": break;
1607
+ }
1608
+ }
1609
+ for (const { other, otherRel } of fkOnTargetBySlug.get(descriptor.slug) ?? []) {
1610
+ if (other.slug === descriptor.slug) continue;
1611
+ const relationName = tableRelationName(otherRel, other, targetOf);
1612
+ const dedupe = `${relationName}::belongsTo`;
1613
+ if (emitted.has(dedupe)) continue;
1614
+ emitted.add(dedupe);
1615
+ const otherVar = getTableVarName(other.table);
1616
+ const fieldKey = servedKeyOf(descriptor, otherRel.foreignKey);
1617
+ plans.push({
1618
+ tableVar,
1619
+ key: `_synth_${otherVar}_${fieldKey}`,
1620
+ kind: "one",
1621
+ targetVar: otherVar,
1622
+ relationName,
1623
+ fields: [fieldKey],
1624
+ references: [otherRel.sourceKey ? servedKeyOf(other, otherRel.sourceKey) : keyOf(other, `relation "${other.slug}.${otherRel.name}"`)]
1625
+ });
1626
+ }
1627
+ }
1628
+ return plans;
1629
+ }
1630
+ //#endregion
1631
+ export { SET_UPDATED_AT_FN as a, keepTenantArguments as c, plannedColumnEntries as i, servedKeyOf as l, planSchema as n, triggerStatements as o, quoteSqlLiteral as r, KEEP_TENANT_FN as s, pgTypeOf as t, tableRelationName as u };
1632
+
1633
+ //# sourceMappingURL=plan-schema-Hbtjhge3.js.map