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

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