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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (248) hide show
  1. package/README.md +11 -8
  2. package/dist/{BranchService-CrXvcES2.js → BranchService-USp1AvZB.js} +3 -3
  3. package/dist/{BranchService-CrXvcES2.js.map → BranchService-USp1AvZB.js.map} +1 -1
  4. package/dist/PostgresBackendDriver.d.ts +99 -54
  5. package/dist/PostgresBootstrapper.d.ts +12 -27
  6. package/dist/auth/ensure-tables.d.ts +16 -5
  7. package/dist/auth/schema-version.d.ts +2 -2
  8. package/dist/auth/services.d.ts +2 -3
  9. package/dist/{auth-users-columns-C72EMoDJ.js → auth-users-columns-BpfgbkxZ.js} +2 -16
  10. package/dist/auth-users-columns-BpfgbkxZ.js.map +1 -0
  11. package/dist/{backup-cli-CTKCOLpX.js → backup-cli-DbKyEj6c.js} +4 -4
  12. package/dist/{backup-cli-CTKCOLpX.js.map → backup-cli-DbKyEj6c.js.map} +1 -1
  13. package/dist/{boot-ddl-CqGIwSYx.js → boot-ddl-5H2bL_80.js} +2 -2
  14. package/dist/{boot-ddl-CqGIwSYx.js.map → boot-ddl-5H2bL_80.js.map} +1 -1
  15. package/dist/{cli-console-DBPw-oAz.js → cli-console-DsRgGSBR.js} +65 -39
  16. package/dist/cli-console-DsRgGSBR.js.map +1 -0
  17. package/dist/cli-console.d.ts +16 -13
  18. package/dist/cli-flags.d.ts +8 -9
  19. package/dist/cli-helpers.d.ts +15 -11
  20. package/dist/{cli-errors-DYTxnLbW.js → cli-schema-dir-CiN0ephV.js} +184 -70
  21. package/dist/cli-schema-dir-CiN0ephV.js.map +1 -0
  22. package/dist/cli-schema-dir.d.ts +64 -0
  23. package/dist/cli.js +192 -257
  24. package/dist/cli.js.map +1 -1
  25. package/dist/data-transformer.d.ts +50 -19
  26. package/dist/{database-preflight-iBpT7-vv.js → database-preflight-bfnIBnjM.js} +5 -5
  27. package/dist/database-preflight-bfnIBnjM.js.map +1 -0
  28. package/dist/{deferred-index-build-BCU9RoHK.js → deferred-index-build-CcSDA7wE.js} +69 -13
  29. package/dist/deferred-index-build-CcSDA7wE.js.map +1 -0
  30. package/dist/{ensure-collection-policies-Bo-_fDAy.js → ensure-policies-rRmXb5bt.js} +31 -31
  31. package/dist/ensure-policies-rRmXb5bt.js.map +1 -0
  32. package/dist/{ensure-collection-tables-DCJINkT_.js → ensure-tables-Bvm-F2wW.js} +44 -37
  33. package/dist/ensure-tables-Bvm-F2wW.js.map +1 -0
  34. package/dist/{ensure-tables-BPGaGh0y.js → ensure-tables-CC8p_AK3.js} +34 -29
  35. package/dist/ensure-tables-CC8p_AK3.js.map +1 -0
  36. package/dist/{enum-labels-kept-YAgOZS4I.js → enum-labels-kept-FlX9SHdf.js} +8 -8
  37. package/dist/enum-labels-kept-FlX9SHdf.js.map +1 -0
  38. package/dist/{generate-drizzle-schema-DcrFr7YX.js → generate-drizzle-schema-SJMXxzPI.js} +12 -12
  39. package/dist/generate-drizzle-schema-SJMXxzPI.js.map +1 -0
  40. package/dist/{generate-drizzle-schema-logic-LTLZvt6r.js → generate-drizzle-schema-logic-DL7R1rAF.js} +15 -8
  41. package/dist/generate-drizzle-schema-logic-DL7R1rAF.js.map +1 -0
  42. package/dist/{generate-files-CsaVzatS.js → generate-files-tlJ9_lGI.js} +23 -30
  43. package/dist/generate-files-tlJ9_lGI.js.map +1 -0
  44. package/dist/{generate-next-step-DgK5BlBn.js → generate-next-step-CO09dovd.js} +3 -3
  45. package/dist/generate-next-step-CO09dovd.js.map +1 -0
  46. package/dist/{generate-postgres-ddl-logic-Dg0bcENZ.js → generate-postgres-ddl-logic-B8huc03c.js} +51 -21
  47. package/dist/generate-postgres-ddl-logic-B8huc03c.js.map +1 -0
  48. package/dist/{generated-schema-diff-By4dxyTH.js → generated-schema-diff-DoT2dYDe.js} +297 -279
  49. package/dist/generated-schema-diff-DoT2dYDe.js.map +1 -0
  50. package/dist/{generated-schema-staleness-BvNF3i-s.js → generated-schema-staleness-YBVq2kTn.js} +21 -29
  51. package/dist/generated-schema-staleness-YBVq2kTn.js.map +1 -0
  52. package/dist/history/ensure-history-table.d.ts +22 -0
  53. package/dist/index.d.ts +8 -2
  54. package/dist/index.es.js +201 -25
  55. package/dist/index.es.js.map +1 -1
  56. package/dist/interfaces.d.ts +3 -4
  57. package/dist/{introspect-db-queries-DevUrzll.js → introspect-db-queries-BgiRQqtR.js} +7 -2
  58. package/dist/introspect-db-queries-BgiRQqtR.js.map +1 -0
  59. package/dist/introspect-tables-Cw_A-kk4.js +2086 -0
  60. package/dist/introspect-tables-Cw_A-kk4.js.map +1 -0
  61. package/dist/load-tables-B1Re74ng.js +92 -0
  62. package/dist/load-tables-B1Re74ng.js.map +1 -0
  63. package/dist/{migrate-baseline-CmWXL7qx.js → migrate-baseline-DZmekgpD.js} +19 -32
  64. package/dist/migrate-baseline-DZmekgpD.js.map +1 -0
  65. package/dist/{migrate-policy-stamps-BN_Qad6c.js → migrate-policy-stamps-B_acrUQB.js} +18 -19
  66. package/dist/migrate-policy-stamps-B_acrUQB.js.map +1 -0
  67. package/dist/model/PostgresTableRegistry.d.ts +159 -0
  68. package/dist/model/build-registry.d.ts +25 -0
  69. package/dist/model/refresh-relational-schema.d.ts +24 -0
  70. package/dist/model/runtime-table.d.ts +53 -0
  71. package/dist/{collections → model}/validate-relations.d.ts +15 -21
  72. package/dist/{open-rebase-40paQfVW.js → open-rebase-4kisUF_k.js} +3946 -3870
  73. package/dist/open-rebase-4kisUF_k.js.map +1 -0
  74. package/dist/open-rebase.d.ts +16 -15
  75. package/dist/{pg-error-utils-DJHjCF7-.js → pg-error-utils-BT5NzGFZ.js} +17 -20
  76. package/dist/pg-error-utils-BT5NzGFZ.js.map +1 -0
  77. package/dist/plan-schema-Hbtjhge3.js +1633 -0
  78. package/dist/plan-schema-Hbtjhge3.js.map +1 -0
  79. package/dist/{policy-drift-C-m0uWHH.js → policy-drift-BVMyqHSa.js} +29 -29
  80. package/dist/policy-drift-BVMyqHSa.js.map +1 -0
  81. package/dist/{push-index-adoption-Cp7oZxSl.js → push-index-adoption-hpHTyXMR.js} +7 -7
  82. package/dist/push-index-adoption-hpHTyXMR.js.map +1 -0
  83. package/dist/{push-index-prebuild-DbwKGtQT.js → push-index-prebuild-Bty9F7bD.js} +6 -6
  84. package/dist/push-index-prebuild-Bty9F7bD.js.map +1 -0
  85. package/dist/{push-kept-defaults-CLcgsEPt.js → push-kept-defaults-Bst4MDup.js} +13 -16
  86. package/dist/push-kept-defaults-Bst4MDup.js.map +1 -0
  87. package/dist/{push-legacy-renames-BthD0E9W.js → push-legacy-renames-bB4bM6br.js} +6 -6
  88. package/dist/push-legacy-renames-bB4bM6br.js.map +1 -0
  89. package/dist/{push-policy-plan-BgcrroxQ.js → push-policy-plan-BI8U4BOD.js} +11 -11
  90. package/dist/push-policy-plan-BI8U4BOD.js.map +1 -0
  91. package/dist/{render-ddl-Ci3S_SoI.js → render-ddl-D4n86NHz.js} +14 -7
  92. package/dist/render-ddl-D4n86NHz.js.map +1 -0
  93. package/dist/{request-role-cli-Dy1EgJU9.js → request-role-cli-BdRzdE87.js} +11 -11
  94. package/dist/{request-role-cli-Dy1EgJU9.js.map → request-role-cli-BdRzdE87.js.map} +1 -1
  95. package/dist/{request-role-migration-GHTJnPMV.js → request-role-migration-C8aq_TO3.js} +2 -2
  96. package/dist/{request-role-migration-GHTJnPMV.js.map → request-role-migration-C8aq_TO3.js.map} +1 -1
  97. package/dist/{rls-enforcement-Cc_UhOxb.js → rls-enforcement-DB5HHj96.js} +19 -19
  98. package/dist/rls-enforcement-DB5HHj96.js.map +1 -0
  99. package/dist/{rls-settings-BCGMIig3.js → rls-settings-CmGK2U0a.js} +2 -2
  100. package/dist/rls-settings-CmGK2U0a.js.map +1 -0
  101. package/dist/schema/auth-users-columns.d.ts +1 -11
  102. package/dist/schema/catalogue-schema.d.ts +33 -29
  103. package/dist/schema/classify-change.d.ts +23 -16
  104. package/dist/schema/column-type-drift.d.ts +16 -0
  105. package/dist/schema/config-relations.d.ts +10 -9
  106. package/dist/schema/deferred-index-build.d.ts +1 -1
  107. package/dist/schema/doctor-cli.js +1544 -66
  108. package/dist/schema/doctor-cli.js.map +1 -1
  109. package/dist/schema/doctor-database.d.ts +7 -7
  110. package/dist/schema/doctor-policy-checks.d.ts +4 -4
  111. package/dist/schema/doctor-search-scale.d.ts +14 -14
  112. package/dist/schema/doctor.d.ts +27 -27
  113. package/dist/schema/dynamic-tables.d.ts +6 -5
  114. package/dist/schema/{ensure-collection-policies.d.ts → ensure-policies.d.ts} +20 -20
  115. package/dist/schema/{ensure-collection-tables.d.ts → ensure-tables.d.ts} +11 -11
  116. package/dist/schema/enum-labels-kept.d.ts +6 -6
  117. package/dist/schema/generate-drizzle-schema-logic.d.ts +3 -3
  118. package/dist/schema/generate-drizzle-schema.js +1 -1
  119. package/dist/schema/generate-files.d.ts +6 -6
  120. package/dist/schema/generate-postgres-ddl-logic.d.ts +23 -20
  121. package/dist/schema/generate-postgres-ddl.js +11 -11
  122. package/dist/schema/generate-postgres-ddl.js.map +1 -1
  123. package/dist/schema/generate-schema-commit.d.ts +13 -8
  124. package/dist/schema/generated-schema-diff.d.ts +16 -16
  125. package/dist/schema/generated-schema-staleness.d.ts +11 -11
  126. package/dist/schema/index-adoption.d.ts +4 -4
  127. package/dist/schema/introspect-db-customization.d.ts +47 -0
  128. package/dist/schema/introspect-db-inference.d.ts +30 -9
  129. package/dist/schema/introspect-db-logic.d.ts +79 -110
  130. package/dist/schema/introspect-db-project.d.ts +15 -18
  131. package/dist/schema/introspect-db-queries.d.ts +1 -1
  132. package/dist/schema/introspect-db-search.d.ts +25 -4
  133. package/dist/schema/introspect-db-storage.d.ts +4 -74
  134. package/dist/schema/introspect-db.js +102 -90
  135. package/dist/schema/introspect-db.js.map +1 -1
  136. package/dist/schema/introspect-runtime.d.ts +47 -36
  137. package/dist/schema/introspect-tables.d.ts +182 -0
  138. package/dist/schema/load-tables.d.ts +55 -0
  139. package/dist/schema/migrate-policy-stamps.d.ts +4 -4
  140. package/dist/schema/migration-freshness.d.ts +13 -13
  141. package/dist/schema/plan/column-order.d.ts +82 -0
  142. package/dist/schema/plan/diff-plan.d.ts +9 -3
  143. package/dist/schema/plan/plan-schema.d.ts +55 -52
  144. package/dist/schema/plan/render-drizzle.d.ts +1 -1
  145. package/dist/schema/plan/types.d.ts +24 -15
  146. package/dist/schema/push-index-adoption.d.ts +3 -3
  147. package/dist/schema/push-index-prebuild.d.ts +3 -3
  148. package/dist/schema/push-kept-defaults.d.ts +7 -7
  149. package/dist/schema/push-legacy-renames.d.ts +3 -3
  150. package/dist/schema/push-policy-plan.d.ts +5 -5
  151. package/dist/schema/reconcile-schema.d.ts +5 -5
  152. package/dist/schema/relation-names.d.ts +15 -20
  153. package/dist/schema/render-outputs.d.ts +76 -0
  154. package/dist/schema/search-column.d.ts +11 -43
  155. package/dist/schema/{collection-index.d.ts → table-index.d.ts} +21 -42
  156. package/dist/schema/{collections-schema-version.d.ts → tables-schema-version.d.ts} +8 -2
  157. package/dist/schema/vector-index.d.ts +24 -28
  158. package/dist/{search-column-BM-GV6vH.js → search-column-BO-WND-B.js} +86 -149
  159. package/dist/search-column-BO-WND-B.js.map +1 -0
  160. package/dist/security/caller-sql-columns.d.ts +9 -6
  161. package/dist/security/policy-drift.d.ts +14 -14
  162. package/dist/security/rls-enforcement.d.ts +19 -25
  163. package/dist/security/rls-settings.d.ts +2 -2
  164. package/dist/security/served-table-protection.d.ts +125 -0
  165. package/dist/services/FetchService.d.ts +22 -133
  166. package/dist/services/PersistService.d.ts +6 -17
  167. package/dist/services/RelationService.d.ts +57 -106
  168. package/dist/services/RelationWriteService.d.ts +59 -66
  169. package/dist/services/cdc/identity-columns.d.ts +7 -5
  170. package/dist/services/cdc/junction-tables.d.ts +14 -14
  171. package/dist/services/collection-helpers.d.ts +52 -95
  172. package/dist/services/dataService.d.ts +15 -12
  173. package/dist/services/field-op-sql.d.ts +11 -9
  174. package/dist/services/field-viewer.d.ts +12 -11
  175. package/dist/services/hidden-columns.d.ts +30 -0
  176. package/dist/services/index.d.ts +1 -1
  177. package/dist/services/junction-writes.d.ts +37 -18
  178. package/dist/services/nested-path.d.ts +18 -18
  179. package/dist/services/read-field-access.d.ts +23 -7
  180. package/dist/services/read-scope.d.ts +10 -9
  181. package/dist/services/realtimeService.d.ts +25 -10
  182. package/dist/services/relation-tables.d.ts +97 -0
  183. package/dist/services/row-pipeline.d.ts +50 -69
  184. package/dist/services/soft-delete.d.ts +25 -24
  185. package/dist/services/table-hooks.d.ts +146 -0
  186. package/dist/services/view-access.d.ts +7 -7
  187. package/dist/services/write-transaction-scope.d.ts +1 -1
  188. package/dist/{source-fZb92pN8.js → source-VxbrQojV.js} +111 -79
  189. package/dist/source-VxbrQojV.js.map +1 -0
  190. package/dist/{collections-schema-version-D7bDI0PJ.js → tables-schema-version-YvZIBlOP.js} +12 -6
  191. package/dist/tables-schema-version-YvZIBlOP.js.map +1 -0
  192. package/dist/utils/drizzle-conditions.d.ts +70 -84
  193. package/dist/utils/pg-array-null-patch.d.ts +27 -10
  194. package/dist/utils/pg-error-utils.d.ts +4 -4
  195. package/dist/{vector-index-DsQ3V2d2.js → vector-index-VSh3ufTd.js} +62 -54
  196. package/dist/vector-index-VSh3ufTd.js.map +1 -0
  197. package/dist/{websocket-B7ex6AQM.js → websocket-BevXvwfo.js} +51 -40
  198. package/dist/websocket-BevXvwfo.js.map +1 -0
  199. package/dist/websocket.d.ts +2 -2
  200. package/package.json +7 -7
  201. package/dist/auth-users-columns-C72EMoDJ.js.map +0 -1
  202. package/dist/cli-collections-path.d.ts +0 -31
  203. package/dist/cli-console-DBPw-oAz.js.map +0 -1
  204. package/dist/cli-errors-DYTxnLbW.js.map +0 -1
  205. package/dist/collections/PostgresCollectionRegistry.d.ts +0 -47
  206. package/dist/collections/buildRegistry.d.ts +0 -27
  207. package/dist/collections-schema-version-D7bDI0PJ.js.map +0 -1
  208. package/dist/column-plan-helpers-BeSztMor.js +0 -161
  209. package/dist/column-plan-helpers-BeSztMor.js.map +0 -1
  210. package/dist/database-preflight-iBpT7-vv.js.map +0 -1
  211. package/dist/deferred-index-build-BCU9RoHK.js.map +0 -1
  212. package/dist/doctor-Kg1oUK0Q.js +0 -1458
  213. package/dist/doctor-Kg1oUK0Q.js.map +0 -1
  214. package/dist/ensure-collection-policies-Bo-_fDAy.js.map +0 -1
  215. package/dist/ensure-collection-tables-DCJINkT_.js.map +0 -1
  216. package/dist/ensure-tables-BPGaGh0y.js.map +0 -1
  217. package/dist/enum-labels-kept-YAgOZS4I.js.map +0 -1
  218. package/dist/generate-drizzle-schema-DcrFr7YX.js.map +0 -1
  219. package/dist/generate-drizzle-schema-logic-LTLZvt6r.js.map +0 -1
  220. package/dist/generate-files-CsaVzatS.js.map +0 -1
  221. package/dist/generate-next-step-DgK5BlBn.js.map +0 -1
  222. package/dist/generate-postgres-ddl-logic-Dg0bcENZ.js.map +0 -1
  223. package/dist/generated-schema-diff-By4dxyTH.js.map +0 -1
  224. package/dist/generated-schema-staleness-BvNF3i-s.js.map +0 -1
  225. package/dist/introspect-db-logic-DWqAEURB.js +0 -2047
  226. package/dist/introspect-db-logic-DWqAEURB.js.map +0 -1
  227. package/dist/introspect-db-queries-DevUrzll.js.map +0 -1
  228. package/dist/migrate-baseline-CmWXL7qx.js.map +0 -1
  229. package/dist/migrate-policy-stamps-BN_Qad6c.js.map +0 -1
  230. package/dist/open-rebase-40paQfVW.js.map +0 -1
  231. package/dist/pg-error-utils-DJHjCF7-.js.map +0 -1
  232. package/dist/plan-schema-vJd3UEmT.js +0 -1604
  233. package/dist/plan-schema-vJd3UEmT.js.map +0 -1
  234. package/dist/policy-drift-C-m0uWHH.js.map +0 -1
  235. package/dist/push-index-adoption-Cp7oZxSl.js.map +0 -1
  236. package/dist/push-index-prebuild-DbwKGtQT.js.map +0 -1
  237. package/dist/push-kept-defaults-CLcgsEPt.js.map +0 -1
  238. package/dist/push-legacy-renames-BthD0E9W.js.map +0 -1
  239. package/dist/push-policy-plan-BgcrroxQ.js.map +0 -1
  240. package/dist/render-ddl-Ci3S_SoI.js.map +0 -1
  241. package/dist/rls-enforcement-Cc_UhOxb.js.map +0 -1
  242. package/dist/rls-settings-BCGMIig3.js.map +0 -1
  243. package/dist/schema/column-plan-helpers.d.ts +0 -161
  244. package/dist/schema/introspect-db-naming.d.ts +0 -10
  245. package/dist/search-column-BM-GV6vH.js.map +0 -1
  246. package/dist/source-fZb92pN8.js.map +0 -1
  247. package/dist/vector-index-DsQ3V2d2.js.map +0 -1
  248. package/dist/websocket-B7ex6AQM.js.map +0 -1
@@ -1,37 +1,16 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
- import { l as searchColumnNames } from "./search-column-BM-GV6vH.js";
4
- import { i as isAuthCollection, t as AUTH_USERS_COLUMNS } from "./auth-users-columns-C72EMoDJ.js";
5
- import { c as sharedRelationName } from "./plan-schema-vJd3UEmT.js";
6
- import { _ as humanize, g as mapPgType, i as buildTablesMap, l as getIconForTable, p as singularize, r as buildEnumMap, u as identifyJoinTables } from "./introspect-db-logic-DWqAEURB.js";
3
+ import { h as tableSearchColumnNames } from "./search-column-BO-WND-B.js";
4
+ import { t as AUTH_USERS_COLUMNS } from "./auth-users-columns-BpfgbkxZ.js";
5
+ import { l as servedKeyOf, u as tableRelationName } from "./plan-schema-Hbtjhge3.js";
6
+ import { i as buildTablesMap, r as buildEnumMap, s as identifyJoinTables } from "./introspect-tables-Cw_A-kk4.js";
7
7
  import { logger } from "@rebasepro/server";
8
8
  import { getTableColumns, getTableName, isTable, relations, sql } from "drizzle-orm";
9
- import { bigint, boolean, char, cidr, customType, date, doublePrecision, geometry, inet, integer, interval, json, jsonb, line, macaddr, macaddr8, numeric, pgSchema, pgTable, point, primaryKey, real, smallint, text, time, timestamp, uuid, varchar, vector } from "drizzle-orm/pg-core";
10
- import { fieldKeyForColumn, getJunctionCollectionConfig, getTableName as getTableName$1, resolveCollectionRelations, resolveJunctionSpecs } from "@rebasepro/common";
11
- import { firstFreeKey, toWireKey } from "@rebasepro/utils";
9
+ import { PgArray, PgTable, bigint, boolean, char, cidr, customType, date, doublePrecision, geometry, inet, integer, interval, json, jsonb, line, macaddr, macaddr8, numeric, pgSchema, pgTable, point, primaryKey, real, smallint, text, time, timestamp, uuid, varchar, vector } from "drizzle-orm/pg-core";
10
+ import { compileDescribedTables, declaredSchemaOf, isSchemaDefinitionError, keyForColumn, resolveTableJunctions } from "@rebasepro/common";
11
+ import { toWireKey } from "@rebasepro/utils";
12
12
  //#region src/schema/introspect-runtime.ts
13
13
  /**
14
- * Read the RLS posture of each table in a schema.
15
- *
16
- * This is what decides whether baas mode may serve a table. A table with RLS
17
- * disabled has no authorization model: since every authenticated request runs
18
- * as `rebase_user`, and that role is granted DML on the schema, serving such a
19
- * table hands every row to every logged-in user.
20
- */
21
- async function readRlsStatus(client, pgSchema) {
22
- const { rows } = await client.query(`SELECT c.relname AS table,
23
- c.relrowsecurity AS rls_enabled,
24
- (SELECT count(*) FROM pg_policy p WHERE p.polrelid = c.oid) AS policy_count
25
- FROM pg_class c
26
- JOIN pg_namespace n ON n.oid = c.relnamespace
27
- WHERE n.nspname = $1 AND c.relkind = 'r'`, [pgSchema]);
28
- return new Map(rows.map((r) => [r.table, {
29
- table: r.table,
30
- rlsEnabled: r.rls_enabled === true,
31
- policyCount: Number(r.policy_count ?? 0)
32
- }]));
33
- }
34
- /**
35
14
  * Read tables, columns, enums, primary keys and foreign keys for a schema.
36
15
  * Mirrors the queries in introspect-db.ts.
37
16
  */
@@ -120,109 +99,153 @@ async function introspectSchema(client, pgSchema, options = {}) {
120
99
  joinTables: identifyJoinTables(tablesMap)
121
100
  };
122
101
  }
123
- /** Derive the `isId` flavour for a primary-key column. */
124
- function idKindFor(col, propType) {
125
- if (col.data_type.toLowerCase() === "uuid") return "uuid";
126
- if (propType === "number") return "increment";
127
- return true;
102
+ /** A descriptor without its relations into `removed`; a foreign-key column such a relation held becomes a plain column. */
103
+ function withoutRelationsInto(descriptor, removed) {
104
+ const gone = descriptor.relations.filter((relation) => removed.has(relation.target));
105
+ if (gone.length === 0) return descriptor;
106
+ const goneNames = new Set(gone.map((relation) => relation.name));
107
+ return {
108
+ ...descriptor,
109
+ relations: descriptor.relations.filter((relation) => !goneNames.has(relation.name)),
110
+ columns: descriptor.columns.map((column) => {
111
+ if (column.foreignKeyOf === void 0 || !goneNames.has(column.foreignKeyOf)) return column;
112
+ const { foreignKeyOf: _foreignKeyOf, derived: _derived, ...plain } = column;
113
+ return plain;
114
+ })
115
+ };
128
116
  }
129
- function buildProperties(meta, enumMap) {
130
- const properties = {};
131
- const takenKeys = /* @__PURE__ */ new Set();
132
- for (const col of meta.columns) {
133
- const isPk = meta.pks.includes(col.column_name);
134
- if (meta.fks.some((fk) => fk.column_name === col.column_name) && !isPk) continue;
135
- const enumValues = enumMap.get(col.udt_name);
136
- const isEnum = col.data_type === "USER-DEFINED" && enumValues !== void 0;
137
- const isVector = col.udt_name === "vector";
138
- const propType = isEnum ? "string" : isVector ? "vector" : mapPgType(col.data_type);
139
- const property = {
140
- name: humanize(col.column_name),
141
- columnName: col.column_name,
142
- type: propType
117
+ /**
118
+ * The tables an introspected database is served through, compiled.
119
+ *
120
+ * Each descriptor is kept as introspected, beside the definition that states
121
+ * it (`compileDescribedTables`). The definitions carry `rls: "admin-only"`:
122
+ * Rebase generates no policy for a table it did not declare, and the
123
+ * request-time code reads none — the database's own policies decide every
124
+ * row, as they always have. The descriptors keep stating those policies for
125
+ * `GET /api/schema/tables`.
126
+ *
127
+ * Never throws for one table: a descriptor no definition can be built from is
128
+ * dropped and named in {@link CompiledIntrospection.dropped}, and the rest are
129
+ * served.
130
+ *
131
+ * @group Schema
132
+ */
133
+ function compileIntrospectedTables(tables) {
134
+ const dropped = [];
135
+ let remaining = [...tables];
136
+ for (;;) try {
137
+ const compiled = compileDescribedTables(remaining, { rls: () => "admin-only" });
138
+ return {
139
+ tables: remaining,
140
+ compiled,
141
+ dropped
143
142
  };
144
- const key = firstFreeKey([toWireKey(col.column_name), col.column_name], takenKeys);
145
- takenKeys.add(key);
146
- if (isPk) property.isId = idKindFor(col, propType);
147
- else if (col.is_nullable === "NO" && col.column_default === null) property.validation = { required: true };
148
- if (isEnum && enumValues) property.enum = enumValues.map((value) => ({
149
- id: value,
150
- label: humanize(value)
151
- }));
152
- properties[key] = property;
143
+ } catch (error) {
144
+ if (!isSchemaDefinitionError(error)) throw error;
145
+ const reasons = /* @__PURE__ */ new Map();
146
+ for (const problem of error.problems) {
147
+ const table = remaining.find((candidate) => candidate.name === problem.table || candidate.slug === problem.table);
148
+ if (!table) continue;
149
+ reasons.set(table.slug, [...reasons.get(table.slug) ?? [], problem.key ? `${problem.key}: ${problem.message}` : problem.message]);
150
+ }
151
+ if (reasons.size === 0) throw error;
152
+ for (const [table, list] of reasons) dropped.push({
153
+ table,
154
+ reason: list.join("; ")
155
+ });
156
+ const removed = new Set(reasons.keys());
157
+ remaining = remaining.filter((table) => !removed.has(table.slug)).map((table) => withoutRelationsInto(table, removed));
153
158
  }
154
- return properties;
155
159
  }
160
+ //#endregion
161
+ //#region src/utils/pg-array-null-patch.ts
156
162
  /**
157
- * Owning relations, derived from this table's foreign keys — the same shape
158
- * `generateCollectionFile` writes into a collection file: a `relation` property
159
- * whose nested descriptor carries `kind`, a `target` thunk and the `localKey`.
163
+ * Read a Postgres array literal (`{a,"b c",NULL,"NULL"}`, nested
164
+ * `{{1,2},{3,4}}`) into its items, each as the text Postgres wrote — an
165
+ * unquoted `NULL` as `null`.
160
166
  *
161
- * The shape is load-bearing, not cosmetic. `resolveCollectionRelations` reads
162
- * relations from `property.relation` and `resolveRelation` requires `target` to
163
- * be a thunk; this used to emit `target`/`cardinality`/`localKey` flat on the
164
- * property with the slug as a bare string, which satisfies neither. Nothing
165
- * threw — the resolver simply skipped every such property and reported that the
166
- * collection had no relations. So an introspected BaaS collection had its FK
167
- * columns removed from `properties` (they "surface as relations") and then no
168
- * resolvable relation to surface as, which is why writing the FK column
169
- * directly came back as `has no field 'product_id'`: `assertKnownWriteFields`
170
- * learns that column from the resolved relation's `localKey`.
167
+ * Drizzle's own parser reads an unquoted `NULL` as the four-letter string, so
168
+ * a `date[]` / `timestamptz[]` / enum array holding a null item (the types the
169
+ * drivers leave to drizzle as text) served `"NULL"` in its place. A quoted
170
+ * `"NULL"` is the string.
171
171
  *
172
- * The thunk closes over the collections being built in this same pass rather
173
- * than importing a module, which is what a runtime introspection has instead of
174
- * generated files. It is called lazily, after the map is fully populated, so a
175
- * table may reference one introspected later.
172
+ * An explicit lower bound (`[0:1]={…}`) is skipped: the items are what is
173
+ * served, not their subscripts.
176
174
  */
177
- function buildRelations(meta, slugByTable, collectionBySlug) {
178
- const relations = {};
179
- for (const fk of meta.fks) {
180
- const targetSlug = slugByTable.get(fk.foreign_table_name);
181
- if (!targetSlug) continue;
182
- let key = toWireKey(fk.column_name.replace(/_id$/, ""));
183
- if (meta.pks.includes(fk.column_name) && key === fk.column_name) key = fk.foreign_table_name;
184
- relations[key] = {
185
- name: humanize(key),
186
- type: "relation",
187
- relation: {
188
- kind: "belongsTo",
189
- target: () => collectionBySlug.get(targetSlug),
190
- localKey: fk.column_name
175
+ function parsePgArrayLiteral(literal) {
176
+ let i = literal.startsWith("[") ? literal.indexOf("=") + 1 : 0;
177
+ const readArray = () => {
178
+ const items = [];
179
+ i++;
180
+ if (literal[i] === "}") {
181
+ i++;
182
+ return items;
183
+ }
184
+ for (;;) {
185
+ if (literal[i] === "{") items.push(readArray());
186
+ else if (literal[i] === "\"") {
187
+ let text = "";
188
+ i++;
189
+ while (i < literal.length && literal[i] !== "\"") {
190
+ if (literal[i] === "\\") i++;
191
+ text += literal[i];
192
+ i++;
193
+ }
194
+ i++;
195
+ items.push(text);
196
+ } else {
197
+ const start = i;
198
+ while (i < literal.length && literal[i] !== "," && literal[i] !== "}") i++;
199
+ const text = literal.slice(start, i).trim();
200
+ items.push(text.toUpperCase() === "NULL" ? null : text);
191
201
  }
192
- };
193
- }
194
- return relations;
202
+ if (literal[i] === ",") {
203
+ i++;
204
+ continue;
205
+ }
206
+ i++;
207
+ return items;
208
+ }
209
+ };
210
+ return literal[i] === "{" ? readArray() : [];
195
211
  }
196
212
  /**
197
- * Turn an introspected schema into collections.
213
+ * Patches every native array column (`PgArray`) of the given tables so a
214
+ * read hands back what the array holds, nulls included.
215
+ *
216
+ * Drizzle's `PgArray.mapFromDriverValue` has two faults this replaces:
198
217
  *
199
- * Join tables are skipped: they carry no identity of their own and exist to
200
- * express a many-to-many edge between two other tables.
218
+ * - it calls `value.map(...)` on a NULL column — `TypeError: value.map is
219
+ * not a function` — so a null array is served as `null` here;
220
+ * - it maps every item through the item column, a null item included, and
221
+ * parses a text literal's unquoted `NULL` as the string `"NULL"`: a null
222
+ * item of a `bigint[]` came back `0` (`Number(null)`), of a `date[]`,
223
+ * `timestamptz[]` or enum array `"NULL"`. A null item stays `null` here,
224
+ * and only the others go through the item column's own mapping.
225
+ *
226
+ * Applied where the runtime builds its tables (`buildDrizzleTablesFromSchema`),
227
+ * so every table a driver reads through carries it. Idempotent: a mark on the
228
+ * column, so a table patched twice is wrapped once.
201
229
  */
202
- function buildCollectionsFromSchema({ tablesMap, enumMap, joinTables }, pgSchema) {
203
- const slugByTable = /* @__PURE__ */ new Map();
204
- for (const tableName of tablesMap.keys()) if (!joinTables.has(tableName)) slugByTable.set(tableName, tableName);
205
- const collections = [];
206
- const collectionBySlug = /* @__PURE__ */ new Map();
207
- for (const [tableName, meta] of tablesMap) {
208
- if (joinTables.has(tableName)) continue;
209
- const collectionName = humanize(tableName);
210
- const collection = {
211
- name: collectionName,
212
- singularName: singularize(collectionName),
213
- slug: tableName,
214
- table: tableName,
215
- schema: pgSchema,
216
- icon: getIconForTable(tableName),
217
- properties: {
218
- ...buildProperties(meta, enumMap),
219
- ...buildRelations(meta, slugByTable, collectionBySlug)
220
- }
221
- };
222
- collections.push(collection);
223
- collectionBySlug.set(tableName, collection);
230
+ function patchPgArrayNullSafety(tables) {
231
+ for (const tableOrRelation of Object.values(tables)) {
232
+ if (!(tableOrRelation instanceof PgTable)) continue;
233
+ const columns = getTableColumns(tableOrRelation);
234
+ for (const column of Object.values(columns)) {
235
+ if (!(column instanceof PgArray) || Object.hasOwn(column, "__rebaseArrayPatched")) continue;
236
+ Object.defineProperty(column, "__rebaseArrayPatched", { value: true });
237
+ const item = column.baseColumn;
238
+ const mapItems = (items) => items.map((entry) => {
239
+ if (entry === null || entry === void 0) return null;
240
+ return Array.isArray(entry) ? mapItems(entry) : item.mapFromDriverValue(entry);
241
+ });
242
+ column.mapFromDriverValue = function(value) {
243
+ if (value === null || value === void 0) return null;
244
+ if (typeof value === "string") return mapItems(parsePgArrayLiteral(value));
245
+ return Array.isArray(value) ? mapItems(value) : value;
246
+ };
247
+ }
224
248
  }
225
- return collections;
226
249
  }
227
250
  //#endregion
228
251
  //#region src/schema/dynamic-tables.ts
@@ -244,9 +267,9 @@ function buildCollectionsFromSchema({ tablesMap, enumMap, joinTables }, pgSchema
244
267
  * Two things a caller has to supply for the tables to match what the generated
245
268
  * module used to produce, both about *names*: the Drizzle object is keyed by the
246
269
  * wire name of a column and not by the column (`authorId`, not `author_id`), and
247
- * a relation is keyed by the collection's own relation key rather than by a
248
- * guess made from the foreign key. Both come from the collections — see
249
- * `columnKeysFromCollections` and `buildDrizzleRelationsFromCollections`.
270
+ * a relation is keyed by the table's own relation name rather than by a
271
+ * guess made from the foreign key. Both come from the table descriptors — see
272
+ * `columnKeysFromTables` and `buildDrizzleRelationsFromTables`.
250
273
  */
251
274
  var columnNameAsKey = (_table, column) => column;
252
275
  /** drizzle ships no bytea builder; binary must round-trip as a Buffer. */
@@ -357,6 +380,7 @@ function buildDrizzleTablesFromSchema(tablesMap, pgSchemaName = "public", column
357
380
  return [primaryKey({ columns: [first, ...rest] })];
358
381
  } : void 0);
359
382
  }
383
+ patchPgArrayNullSafety(tables);
360
384
  return tables;
361
385
  }
362
386
  /**
@@ -367,8 +391,9 @@ function buildDrizzleTablesFromSchema(tablesMap, pgSchemaName = "public", column
367
391
  * property on the collection. Tables alone don't satisfy that — without these,
368
392
  * `?include=author` silently returns the raw `author_id` and no author.
369
393
  *
370
- * The keys here must match `buildRelations` in introspect-runtime.ts, which is
371
- * what names the collection's relation properties.
394
+ * The keys here must match the relation names `introspectTables` gives an
395
+ * introspected table (`introspect-tables.ts`), which name the collection's
396
+ * relation properties.
372
397
  */
373
398
  function buildDrizzleRelationsFromSchema(tablesMap, tables, columnKey = columnNameAsKey) {
374
399
  /** Owning side, per table: the `one()` relations from its foreign keys. */
@@ -425,47 +450,47 @@ function buildDrizzleRelationsFromSchema(tablesMap, tables, columnKey = columnNa
425
450
  //#endregion
426
451
  //#region src/schema/config-relations.ts
427
452
  /**
428
- * Build drizzle `relations()` for declared collections, from the collections.
453
+ * Build drizzle `relations()` for declared tables, from their descriptors.
429
454
  *
430
455
  * The heuristic builder in `dynamic-tables.ts` names a relation after the
431
456
  * foreign-key column (`author_id` → `author`), which is the only evidence a
432
457
  * database offers and is right for BaaS mode. It is wrong for a project that
433
- * declares its collections: there the relation's name is whatever the author
458
+ * declares its tables: there the relation's name is whatever the author
434
459
  * called it, `include=writer` addresses that name, and a relation whose key was
435
460
  * guessed from the column simply does not answer to it — the read returns the
436
461
  * bare foreign key and no target, silently, which is how a demo lost every
437
462
  * relation in its list view while the detail view (a different code path) kept
438
463
  * working.
439
464
  *
440
- * So when there are collections, they are the authority for *which* relations
465
+ * So when there are declared tables, they are the authority for *which* relations
441
466
  * exist and what they are called; the live catalogue is the authority for the
442
467
  * columns underneath. This is the same pairing `generate-drizzle-schema-logic`
443
468
  * emits into `schema.generated.ts` — kind for kind, key for key, and paired by
444
- * the same {@link sharedRelationName} — only built against tables read back from
469
+ * the same {@link tableRelationName} — only built against tables read back from
445
470
  * `information_schema` rather than against a file.
446
471
  */
447
- /** A collection's table, with any schema prefix stripped — as the DDL creates it. */
472
+ /** A table's name with any schema prefix stripped — as the DDL creates it. */
448
473
  function bareTableName(name) {
449
474
  return name.includes(".") ? name.split(".").pop() : name;
450
475
  }
451
476
  /**
452
- * The field key a collection's rows are addressed by, as the generated module
453
- * spells it: the property marked `isId`, else `id`.
477
+ * The key a table's rows are addressed by, as the generated module spells it:
478
+ * the first primary-key column's key, else `id`.
454
479
  *
455
- * Deliberately the config's answer rather than the catalogue's primary key —
456
- * `references: [users.id]` in the generated file is keyed the same way, and the
457
- * two have to name the same Drizzle key for a relation to compile at all.
480
+ * Deliberately the declaration's answer rather than the catalogue's primary
481
+ * key — `references: [users.id]` in the generated file is keyed the same way,
482
+ * and the two have to name the same Drizzle key for a relation to compile at
483
+ * all.
458
484
  */
459
- function primaryKeyFieldKey(collection) {
460
- for (const [key, prop] of Object.entries(collection.properties ?? {})) if (prop && typeof prop === "object" && "isId" in prop && Boolean(prop.isId)) return key;
461
- return "id";
485
+ function primaryKeyFieldKey(table) {
486
+ return table.primaryKey[0] ?? "id";
462
487
  }
463
488
  /**
464
- * The field key on the source table that a `hasOne`/`hasMany` foreign key
465
- * holds: its `sourceKey` when the link names one, else the primary key.
489
+ * The key on the source table that a `hasOne`/`hasMany` foreign key holds:
490
+ * its `sourceKey` when the link names one, else the primary key.
466
491
  */
467
- function sourceKeyFieldKey(relation, collection) {
468
- return relation.sourceKey ? fieldKeyForColumn(collection, relation.sourceKey) : primaryKeyFieldKey(collection);
492
+ function sourceKeyFieldKey(relation, source) {
493
+ return relation.sourceKey ? servedKeyOf(source, relation.sourceKey) : primaryKeyFieldKey(source);
469
494
  }
470
495
  /**
471
496
  * A column of a built table, by its Drizzle key or by its column name.
@@ -473,8 +498,8 @@ function sourceKeyFieldKey(relation, collection) {
473
498
  * The key is the answer in the ordinary case, and the name is the fallback for
474
499
  * the one place a caller holds a column and not a field: a junction table's two
475
500
  * foreign keys, which are keyed by column *unless* the project also declares a
476
- * collection over that table, in which case they are keyed by its property
477
- * names. Looking both up costs a scan of one table and removes the difference.
501
+ * table over that junction, in which case they are keyed by its column keys.
502
+ * Looking both up costs a scan of one table and removes the difference.
478
503
  */
479
504
  function columnOf(table, key) {
480
505
  if (!table) return void 0;
@@ -483,12 +508,13 @@ function columnOf(table, key) {
483
508
  for (const column of Object.values(getTableColumns(table))) if (column.name === key) return column;
484
509
  }
485
510
  /**
486
- * Drizzle relations for every declared collection, keyed `<table>Relations`.
511
+ * Drizzle relations for every declared table, keyed `<table>Relations`.
487
512
  *
488
- * @param collections every collection backed by a table in `tables`
513
+ * @param descriptors every declared table backed by a table in `tables`, and
514
+ * the targets of their relations
489
515
  * @param tables catalogue-built tables, keyed by bare table name
490
516
  */
491
- function buildDrizzleRelationsFromCollections(collections, tables) {
517
+ function buildDrizzleRelationsFromTables(descriptors, tables) {
492
518
  const ones = /* @__PURE__ */ new Map();
493
519
  const manys = /* @__PURE__ */ new Map();
494
520
  /** `<relationName>::<kind>` already emitted on a table — the generator dedupes the same way. */
@@ -503,34 +529,33 @@ function buildDrizzleRelationsFromCollections(collections, tables) {
503
529
  };
504
530
  const addOne = (table, spec) => ones.set(table, [...ones.get(table) ?? [], spec]);
505
531
  const addMany = (table, spec) => manys.set(table, [...manys.get(table) ?? [], spec]);
532
+ const bySlug = new Map(descriptors.map((descriptor) => [descriptor.slug, descriptor]));
533
+ const targetOf = (slug) => {
534
+ const target = bySlug.get(slug);
535
+ if (!target) throw new Error(`Relation target "${slug}" is not a declared table`);
536
+ return target;
537
+ };
506
538
  const byTable = /* @__PURE__ */ new Map();
507
- for (const collection of collections) {
508
- const table = bareTableName(getTableName$1(collection));
509
- if (table && tables[table]) byTable.set(table, collection);
539
+ for (const descriptor of descriptors) {
540
+ const table = bareTableName(descriptor.table);
541
+ if (tables[table]) byTable.set(table, descriptor);
510
542
  }
511
- for (const [tableName, collection] of byTable) {
543
+ for (const [tableName, source] of byTable) {
512
544
  const table = tables[tableName];
513
- for (const [relationKey, relation] of Object.entries(resolveCollectionRelations(collection))) {
514
- let target;
515
- try {
516
- target = relation.target();
517
- } catch (err) {
518
- logger.debug(`[schema] Relation ${collection.slug}.${relationKey} has no resolvable target`, { error: err });
519
- continue;
520
- }
521
- const targetTable = tables[bareTableName(getTableName$1(target))];
522
- const name = sharedRelationName(relation, collection);
545
+ for (const relation of source.relations) {
546
+ const target = bySlug.get(relation.target);
547
+ if (!target) continue;
548
+ const targetTable = tables[bareTableName(target.table)];
549
+ const name = tableRelationName(relation, source, targetOf);
523
550
  switch (relation.kind) {
524
551
  case "belongsTo": {
525
552
  if (!targetTable) continue;
526
553
  if (!claim(tableName, name, relation.kind)) continue;
527
- const localKey = fieldKeyForColumn(collection, relation.localKey);
528
- const referenced = primaryKeyFieldKey(target);
529
- const field = columnOf(table, localKey);
530
- const reference = columnOf(targetTable, referenced);
554
+ const field = columnOf(table, servedKeyOf(source, relation.localKey));
555
+ const reference = columnOf(targetTable, primaryKeyFieldKey(target));
531
556
  if (!field || !reference) continue;
532
557
  addOne(tableName, {
533
- key: relationKey,
558
+ key: relation.name,
534
559
  target: targetTable,
535
560
  fields: [field],
536
561
  references: [reference],
@@ -541,11 +566,11 @@ function buildDrizzleRelationsFromCollections(collections, tables) {
541
566
  case "hasOne": {
542
567
  if (!targetTable) continue;
543
568
  if (!claim(tableName, name, relation.kind)) continue;
544
- const field = columnOf(table, sourceKeyFieldKey(relation, collection));
545
- const reference = columnOf(targetTable, fieldKeyForColumn(target, relation.foreignKeyOnTarget));
569
+ const field = columnOf(table, sourceKeyFieldKey(relation, source));
570
+ const reference = columnOf(targetTable, servedKeyOf(target, relation.foreignKey));
546
571
  if (!field || !reference) continue;
547
572
  addOne(tableName, {
548
- key: relationKey,
573
+ key: relation.name,
549
574
  target: targetTable,
550
575
  fields: [field],
551
576
  references: [reference],
@@ -557,7 +582,7 @@ function buildDrizzleRelationsFromCollections(collections, tables) {
557
582
  if (!targetTable) continue;
558
583
  if (!claim(tableName, name, relation.kind)) continue;
559
584
  addMany(tableName, {
560
- key: relationKey,
585
+ key: relation.name,
561
586
  target: targetTable,
562
587
  relationName: name
563
588
  });
@@ -568,35 +593,31 @@ function buildDrizzleRelationsFromCollections(collections, tables) {
568
593
  if (!junction) continue;
569
594
  if (!claim(tableName, name, relation.kind)) continue;
570
595
  addMany(tableName, {
571
- key: relationKey,
596
+ key: relation.name,
572
597
  target: junction,
573
598
  relationName: name
574
599
  });
575
- addJunctionSides(relation, collection, target, junctionName, tables, addOne, claim);
600
+ addJunctionSides(relation, source, target, junctionName, tables, targetOf, addOne, claim);
576
601
  break;
577
602
  }
578
603
  case "via": break;
579
604
  }
580
605
  }
581
606
  }
582
- for (const [tableName, collection] of byTable) {
607
+ for (const [tableName, source] of byTable) {
583
608
  const table = tables[tableName];
584
- for (const [, relation] of Object.entries(resolveCollectionRelations(collection))) {
609
+ for (const relation of source.relations) {
585
610
  if (relation.kind !== "hasMany" && relation.kind !== "hasOne") continue;
586
- let target;
587
- try {
588
- target = relation.target();
589
- } catch {
590
- continue;
591
- }
592
- const targetTableName = bareTableName(getTableName$1(target));
611
+ const target = bySlug.get(relation.target);
612
+ if (!target) continue;
613
+ const targetTableName = bareTableName(target.table);
593
614
  const targetTable = tables[targetTableName];
594
615
  if (!targetTable) continue;
595
- const name = sharedRelationName(relation, collection);
616
+ const name = tableRelationName(relation, source, targetOf);
596
617
  if (!claim(targetTableName, name, "belongsTo")) continue;
597
- const fkKey = fieldKeyForColumn(target, relation.foreignKeyOnTarget);
618
+ const fkKey = servedKeyOf(target, relation.foreignKey);
598
619
  const field = columnOf(targetTable, fkKey);
599
- const reference = columnOf(table, sourceKeyFieldKey(relation, collection));
620
+ const reference = columnOf(table, sourceKeyFieldKey(relation, source));
600
621
  if (!field || !reference) continue;
601
622
  addOne(targetTableName, {
602
623
  key: `_synth_${targetTableName}_${fkKey}`,
@@ -638,31 +659,29 @@ function buildDrizzleRelationsFromCollections(collections, tables) {
638
659
  * junction rows. Keyed by the junction's own columns, which is how the
639
660
  * generated file keys them too.
640
661
  */
641
- function addJunctionSides(relation, sourceCollection, targetCollection, junctionName, tables, addOne, claim) {
662
+ function addJunctionSides(relation, source, target, junctionName, tables, targetOf, addOne, claim) {
642
663
  const junction = tables[junctionName];
643
- const sourceTable = tables[bareTableName(getTableName$1(sourceCollection))];
644
- const targetTable = tables[bareTableName(getTableName$1(targetCollection))];
664
+ const sourceTable = tables[bareTableName(source.table)];
665
+ const targetTable = tables[bareTableName(target.table)];
645
666
  if (!junction || !sourceTable || !targetTable) return;
646
- const sourceName = sharedRelationName(relation, sourceCollection);
647
- const inverse = Object.values(resolveCollectionRelations(targetCollection)).find((r) => r.kind === "manyToMany" && bareTableName(r.through.table) === junctionName);
648
- const targetName = inverse ? sharedRelationName(inverse, targetCollection) : `${junctionName}_${relation.through.targetColumn}`;
667
+ const sourceName = tableRelationName(relation, source, targetOf);
668
+ const inverse = target.relations.find((r) => r.kind === "manyToMany" && bareTableName(r.through.table) === junctionName);
669
+ const targetName = inverse ? tableRelationName(inverse, target, targetOf) : `${junctionName}_${relation.through.targetKey}`;
649
670
  const pairs = [[
650
- relation.through.sourceColumn,
671
+ relation.through.sourceKey,
651
672
  sourceTable,
652
673
  sourceName,
653
- sourceCollection,
654
- "source"
674
+ source
655
675
  ], [
656
- relation.through.targetColumn,
676
+ relation.through.targetKey,
657
677
  targetTable,
658
678
  targetName,
659
- targetCollection,
660
- "target"
679
+ target
661
680
  ]];
662
- for (const [column, endpointTable, relationName, endpointCollection] of pairs) {
681
+ for (const [column, endpointTable, relationName, endpoint] of pairs) {
663
682
  if (!claim(junctionName, relationName, "junction")) continue;
664
683
  const field = columnOf(junction, column);
665
- const reference = columnOf(endpointTable, primaryKeyFieldKey(endpointCollection));
684
+ const reference = columnOf(endpointTable, primaryKeyFieldKey(endpoint));
666
685
  if (!field || !reference) continue;
667
686
  addOne(junctionName, {
668
687
  key: column,
@@ -675,72 +694,77 @@ function addJunctionSides(relation, sourceCollection, targetCollection, junction
675
694
  }
676
695
  //#endregion
677
696
  //#region src/schema/catalogue-schema.ts
678
- /** The Postgres schema a collection's table lives in. */
679
- function schemaOfCollection(collection, fallback) {
680
- const declared = collection.schema;
681
- return typeof declared === "string" && declared.length > 0 ? declared : fallback;
697
+ /** The Postgres schema a table lives in: the one it declares, else `fallback`. */
698
+ function schemaOfTable(table, fallback) {
699
+ return declaredSchemaOf(table) ?? fallback;
682
700
  }
683
701
  /**
684
702
  * How a column of each table is keyed in the Drizzle object.
685
703
  *
686
- * The wire name, which is the property key — `authorId`, never `author_id` —
704
+ * The wire name, which is the column's key — `authorId`, never `author_id` —
687
705
  * because that is what every read and write path in this driver indexes tables
688
706
  * and rows by, and what the generated module has always emitted. Getting this
689
707
  * wrong does not throw: drizzle leaves an unknown key out of the statement and
690
- * the write reports success having stored nothing.
708
+ * the write reports success having stored nothing. A column the table does not
709
+ * describe is keyed by the camelCase of its name, which is the key a foreign
710
+ * key derived from it would get.
691
711
  *
692
- * Two exceptions, both columns no property declares:
712
+ * Two exceptions, both columns no table declares:
693
713
  *
694
714
  * - the generated search columns keep their raw names, because `search_vector`
695
- * is how `searchColumnNames` excludes them from responses and how the
715
+ * is how `searchColumnNamesOf` excludes them from responses and how the
696
716
  * condition builder finds the one to match against;
697
- * - a table no collection claims (a junction) is keyed by its **key** columns'
717
+ * - a table no descriptor claims (a junction) is keyed by its **key** columns'
698
718
  * names, which is also what the generated file does for them — but a
699
- * junction that declares `through.properties` keys those payload columns by
700
- * their property key, for the same reason a collection does. `joinedAt` with
701
- * `columnName: "joined_at"` has to be one name on both sides or a `_pivot`
702
- * write is silently dropped by drizzle and the read serves a key the caller
703
- * never declared.
719
+ * junction that declares `pivot` columns keys those payload columns by
720
+ * their column key, for the same reason a table does. `joinedAt` with
721
+ * column `joined_at` has to be one name on both sides or a `_pivot` write
722
+ * is silently dropped by drizzle and the read serves a key the caller never
723
+ * declared.
704
724
  */
705
- function columnKeysFromCollections(collections) {
725
+ function columnKeysFromTables(descriptors) {
706
726
  const byTable = /* @__PURE__ */ new Map();
707
727
  const rawColumns = /* @__PURE__ */ new Map();
708
- for (const collection of collections) {
709
- const table = bareTableName(getTableName$1(collection));
710
- if (!table) continue;
711
- byTable.set(table, collection);
712
- rawColumns.set(table, new Set(searchColumnNames(collection)));
728
+ for (const descriptor of descriptors) {
729
+ const table = bareTableName(descriptor.table);
730
+ byTable.set(table, descriptor);
731
+ rawColumns.set(table, new Set(tableSearchColumnNames(descriptor)));
713
732
  }
714
733
  const junctionByTable = /* @__PURE__ */ new Map();
715
- for (const spec of resolveJunctionSpecs(collections).values()) {
716
- if (Object.keys(spec.properties).length === 0) continue;
717
- junctionByTable.set(bareTableName(spec.table), getJunctionCollectionConfig(spec));
734
+ for (const junction of resolveTableJunctions(descriptors).values()) {
735
+ if (junction.pivot.length === 0) continue;
736
+ junctionByTable.set(junction.table, {
737
+ keyColumns: new Set(junction.endpoints.map((endpoint) => endpoint.junctionColumn)),
738
+ pivot: new Map(junction.pivot.map((column) => [column.column, column.key]))
739
+ });
718
740
  }
719
741
  return (tableName, columnName) => {
720
- const collection = byTable.get(tableName);
721
- if (!collection) {
742
+ const descriptor = byTable.get(tableName);
743
+ if (!descriptor) {
722
744
  const junction = junctionByTable.get(tableName);
723
- return junction ? fieldKeyForColumn(junction, columnName) : columnName;
745
+ if (!junction || junction.keyColumns.has(columnName)) return columnName;
746
+ return junction.pivot.get(columnName) ?? toWireKey(columnName);
724
747
  }
725
748
  if (rawColumns.get(tableName)?.has(columnName)) return columnName;
726
- return fieldKeyForColumn(collection, columnName);
749
+ return keyForColumn(descriptor, columnName) ?? toWireKey(columnName);
727
750
  };
728
751
  }
729
752
  /**
730
753
  * Read the tables this data source serves out of `information_schema`.
731
754
  *
732
- * Restricted to the collections handed in, because the driver is given every
733
- * collection the project declares while each database holds only its own: an
734
- * unfiltered read had a second source (`database("analytics")`) reporting the
735
- * default's tables as its own. Junction tables come too — they back no
736
- * collection and a many-to-many is unreadable without them.
755
+ * Restricted to the tables handed in, because the driver is given every table
756
+ * the project declares while each database holds only its own: an unfiltered
757
+ * read had a second source (`database("analytics")`) reporting the default's
758
+ * tables as its own. Junction tables come too — they back no declared table
759
+ * and a many-to-many is unreadable without them.
737
760
  *
738
- * Every schema the collections name is read, not just `public`. The users
739
- * collection lives in `rebase`, and a run restricted to `public` would leave the
740
- * registry with no table for it at all.
761
+ * Every schema the tables name is read, not just `public`. The users table
762
+ * lives in `rebase`, and a run restricted to `public` would leave the registry
763
+ * with no table for it at all. A table that declares no schema is read from
764
+ * `defaultSchema`.
741
765
  */
742
766
  async function readCatalogueSchema(options) {
743
- const { client, collections, defaultSchema } = options;
767
+ const { client, tables: descriptors, defaultSchema } = options;
744
768
  /** schema → the tables wanted from it. */
745
769
  const wanted = /* @__PURE__ */ new Map();
746
770
  const want = (schema, table) => {
@@ -748,12 +772,9 @@ async function readCatalogueSchema(options) {
748
772
  wanted.set(schema, set);
749
773
  set.add(table);
750
774
  };
751
- for (const collection of collections) {
752
- const table = bareTableName(getTableName$1(collection));
753
- if (table) want(schemaOfCollection(collection, defaultSchema), table);
754
- }
755
- for (const spec of resolveJunctionSpecs(collections).values()) want(spec.schema, bareTableName(spec.table));
756
- const columnKey = columnKeysFromCollections(collections);
775
+ for (const descriptor of descriptors) want(schemaOfTable(descriptor, defaultSchema), bareTableName(descriptor.table));
776
+ for (const junction of resolveTableJunctions(descriptors).values()) want(junction.schema, junction.table);
777
+ const columnKey = columnKeysFromTables(descriptors);
757
778
  const tables = {};
758
779
  const meta = /* @__PURE__ */ new Map();
759
780
  const missing = [];
@@ -774,22 +795,22 @@ async function readCatalogueSchema(options) {
774
795
  }
775
796
  return {
776
797
  tables,
777
- relations: buildDrizzleRelationsFromCollections(collections, tables),
798
+ relations: buildDrizzleRelationsFromTables(descriptors, tables),
778
799
  meta,
779
800
  missing
780
801
  };
781
802
  }
782
803
  /**
783
- * The BaaS variant: no collections are declared, so every table in one schema is
784
- * served and both the collections and the relations are derived from the
785
- * foreign keys.
804
+ * The BaaS variant: no tables are declared, so every table in one schema is
805
+ * served, described from the catalogue (`descriptors`), and the relations are
806
+ * derived from the foreign keys.
786
807
  *
787
808
  * Kept apart from {@link readCatalogueSchema} because the two answer different
788
809
  * questions. Here the database is the entire specification; there it supplies
789
810
  * the columns for a specification the project already wrote down.
790
811
  */
791
- function buildBaasSchema(tablesMap, pgSchemaName, collections) {
792
- const columnKey = columnKeysFromCollections(collections);
812
+ function buildBaasSchema(tablesMap, pgSchemaName, descriptors) {
813
+ const columnKey = columnKeysFromTables(descriptors);
793
814
  const tables = buildDrizzleTablesFromSchema(tablesMap, pgSchemaName, columnKey);
794
815
  return {
795
816
  tables,
@@ -815,7 +836,7 @@ function buildBaasSchema(tablesMap, pgSchemaName, collections) {
815
836
  * is exactly what was removed.
816
837
  *
817
838
  * `generated-schema-staleness.ts` answers a narrower question (does the file
818
- * name every table the collections do) from the file's *source text*. This one
839
+ * name every declared table) from the file's *source text*. This one
819
840
  * compares the loaded module against the database, column by column.
820
841
  */
821
842
  /**
@@ -899,28 +920,25 @@ function catalogueColumns(meta) {
899
920
  * One-directional in one respect only: a table the module has and the database
900
921
  * does not is reported (that is the stale-file case), while a table the database
901
922
  * has and the module does not is left alone — a database may hold anything, and
902
- * the collections-vs-file question is `generated-schema-staleness`'s.
923
+ * the declared-tables-vs-file question is `generated-schema-staleness`'s.
903
924
  */
904
925
  function diffGeneratedSchemaAgainstCatalogue(options) {
905
- const { generated, catalogue, collections } = options;
926
+ const { generated, catalogue, tables } = options;
906
927
  if (!generated) return [];
907
- const collectionByTable = /* @__PURE__ */ new Map();
908
- for (const collection of collections) {
909
- const table = getTableName$1(collection);
910
- if (table) collectionByTable.set(bareTableName(table), collection);
911
- }
928
+ const declaredByTable = /* @__PURE__ */ new Map();
929
+ for (const descriptor of tables) declaredByTable.set(bareTableName(descriptor.table), descriptor);
912
930
  const differences = [];
913
931
  for (const value of Object.values(generated)) {
914
932
  if (!isTable(value)) continue;
915
933
  const table = getTableName(value);
916
- const collection = collectionByTable.get(table);
934
+ const declared = declaredByTable.get(table);
917
935
  const at = {
918
936
  table,
919
- collection: collection?.slug
937
+ slug: declared?.slug
920
938
  };
921
939
  const meta = catalogue.get(table);
922
940
  if (!meta) {
923
- if (collection) differences.push({
941
+ if (declared) differences.push({
924
942
  ...at,
925
943
  kind: "missing-table"
926
944
  });
@@ -928,11 +946,11 @@ function diffGeneratedSchemaAgainstCatalogue(options) {
928
946
  }
929
947
  const live = catalogueColumns(meta);
930
948
  const seen = /* @__PURE__ */ new Set();
931
- const authOwned = isAuthCollection(collection) ? new Set(AUTH_USERS_COLUMNS.map((c) => c.column)) : void 0;
949
+ const authOwned = declared?.auth ? new Set(AUTH_USERS_COLUMNS.map((c) => c.column)) : void 0;
932
950
  for (const [key, column] of Object.entries(getTableColumns(value))) {
933
951
  const name = column.name ?? key;
934
952
  seen.add(name);
935
- const property = collection ? fieldKeyForColumn(collection, name) : key;
953
+ const columnKey = declared ? servedKeyOf(declared, name) : key;
936
954
  const generatedFamily = typeFamily(column.getSQLType?.());
937
955
  const generatedNotNull = Boolean(column.notNull);
938
956
  const found = live.get(name);
@@ -941,7 +959,7 @@ function diffGeneratedSchemaAgainstCatalogue(options) {
941
959
  ...at,
942
960
  kind: "missing-column",
943
961
  column: name,
944
- property,
962
+ key: columnKey,
945
963
  generated: generatedFamily
946
964
  });
947
965
  continue;
@@ -950,7 +968,7 @@ function diffGeneratedSchemaAgainstCatalogue(options) {
950
968
  ...at,
951
969
  kind: "type",
952
970
  column: name,
953
- property,
971
+ key: columnKey,
954
972
  generated: generatedFamily,
955
973
  live: found.family
956
974
  });
@@ -958,7 +976,7 @@ function diffGeneratedSchemaAgainstCatalogue(options) {
958
976
  ...at,
959
977
  kind: "nullability",
960
978
  column: name,
961
- property,
979
+ key: columnKey,
962
980
  generated: generatedNotNull ? "NOT NULL" : "nullable",
963
981
  live: found.notNull ? "NOT NULL" : "nullable"
964
982
  });
@@ -970,7 +988,7 @@ function diffGeneratedSchemaAgainstCatalogue(options) {
970
988
  ...at,
971
989
  kind: "extra-column",
972
990
  column: name,
973
- property: collection ? fieldKeyForColumn(collection, name) : name,
991
+ key: declared ? servedKeyOf(declared, name) : name,
974
992
  live: column.family
975
993
  });
976
994
  }
@@ -988,25 +1006,25 @@ function diffGeneratedSchemaAgainstCatalogue(options) {
988
1006
  * doctor compared on its own terms, it answered "In sync" over a NOT NULL and a
989
1007
  * left-behind column that boot had just warned about.
990
1008
  *
991
- * `collections` are the data source's own, as boot filters them.
1009
+ * `tables` are the data source's own, as boot filters them.
992
1010
  */
993
1011
  async function readGeneratedSchemaDrift(options) {
994
- const { client, generated, collections, defaultSchema } = options;
995
- if (!generated || collections.length === 0) return [];
1012
+ const { client, generated, tables, defaultSchema } = options;
1013
+ if (!generated || tables.length === 0) return [];
996
1014
  return diffGeneratedSchemaAgainstCatalogue({
997
1015
  generated,
998
1016
  catalogue: (await readCatalogueSchema({
999
1017
  client,
1000
- collections,
1018
+ tables,
1001
1019
  defaultSchema
1002
1020
  })).meta,
1003
- collections
1021
+ tables
1004
1022
  });
1005
1023
  }
1006
- /** One line, in the terms the reader has: collection, property, column. */
1024
+ /** One line, in the terms the reader has: table slug, column key, column. */
1007
1025
  function describeSchemaDifference(difference) {
1008
- const where = difference.collection ? `${difference.collection} (table "${difference.table}")` : `table "${difference.table}"`;
1009
- const field = difference.column ? `${difference.property && difference.property !== difference.column ? `${difference.property} → "${difference.column}"` : `"${difference.column}"`}` : void 0;
1026
+ const where = difference.slug ? `${difference.slug} (table "${difference.table}")` : `table "${difference.table}"`;
1027
+ const field = difference.column ? `${difference.key && difference.key !== difference.column ? `${difference.key} → "${difference.column}"` : `"${difference.column}"`}` : void 0;
1010
1028
  switch (difference.kind) {
1011
1029
  case "missing-table": return `${where} is in schema.generated.ts but not in the database`;
1012
1030
  case "missing-column": return `${where}: ${field} is in schema.generated.ts but not in the database`;
@@ -1017,37 +1035,37 @@ function describeSchemaDifference(difference) {
1017
1035
  }
1018
1036
  /**
1019
1037
  * The `rebase schema reconcile` line for a difference it can apply: a column
1020
- * the database requires and the collection made optional, or one the
1021
- * collection no longer declares. Undefined for the rest.
1038
+ * the database requires and the table made nullable, or one the table no
1039
+ * longer declares. Undefined for the rest.
1022
1040
  */
1023
1041
  function reconcileFix(difference) {
1024
1042
  if (difference.kind === "nullability" && difference.live === "NOT NULL") return "rebase schema reconcile";
1025
- if (difference.kind === "extra-column" && difference.collection) return `rebase schema reconcile --drop ${difference.collection}.${difference.column}`;
1043
+ if (difference.kind === "extra-column" && difference.slug) return `rebase schema reconcile --drop ${difference.slug}.${difference.column}`;
1026
1044
  }
1027
1045
  /**
1028
1046
  * Report the differences, one warning each, and never throw.
1029
1047
  *
1030
1048
  * Per difference rather than one summary block on purpose: these are read out of
1031
1049
  * a log aggregator as often as a terminal, and a single multi-line message
1032
- * cannot be filtered down to the one collection somebody is looking at.
1050
+ * cannot be filtered down to the one table somebody is looking at.
1033
1051
  *
1034
1052
  * The fix it names is `rebase db push`. `rebase dev` rewrites
1035
- * schema.generated.ts from the collections on every change, and boot applies
1053
+ * schema.generated.ts from the tables on every change, and boot applies
1036
1054
  * only additive changes, so what is still different at boot is the database
1037
1055
  * behind the file: a rename, a dropped column, a narrowed type, a NOT NULL.
1038
1056
  * `rebase schema generate` rewrites the file and leaves the database as it is,
1039
- * so it is named only for collections that changed since the file was written.
1057
+ * so it is named only for tables that changed since the file was written.
1040
1058
  */
1041
1059
  function warnOnGeneratedSchemaDrift(differences) {
1042
1060
  if (differences.length === 0) return;
1043
- logger.warn(`📄 [schema] schema.generated.ts and the database disagree (${differences.length} difference${differences.length === 1 ? "" : "s"}). Boot applies only additive changes; these are the ones it left for you. Run \`rebase db push\` to apply them (it shows the plan and asks before anything destructive), or \`rebase db generate\` for a migration. A NOT NULL to relax or a column to drop can also be applied through the running backend, Rebase Cloud included: \`rebase schema reconcile\`. If the collections changed since schema.generated.ts was written, run \`rebase schema generate\` first.`);
1061
+ logger.warn(`📄 [schema] schema.generated.ts and the database disagree (${differences.length} difference${differences.length === 1 ? "" : "s"}). Boot applies only additive changes; these are the ones it left for you. Run \`rebase db push\` to apply them (it shows the plan and asks before anything destructive), or \`rebase db generate\` for a migration. A NOT NULL to relax or a column to drop can also be applied through the running backend, Rebase Cloud included: \`rebase schema reconcile\`. If backend/schema changed since schema.generated.ts was written, run \`rebase schema generate\` first.`);
1044
1062
  for (const difference of differences) logger.warn(` • ${describeSchemaDifference(difference)}`, {
1045
1063
  schemaDrift: {
1046
1064
  kind: difference.kind,
1047
1065
  table: difference.table,
1048
- collection: difference.collection,
1066
+ slug: difference.slug,
1049
1067
  column: difference.column,
1050
- property: difference.property,
1068
+ key: difference.key,
1051
1069
  generated: difference.generated,
1052
1070
  live: difference.live
1053
1071
  },
@@ -1055,6 +1073,6 @@ function warnOnGeneratedSchemaDrift(differences) {
1055
1073
  });
1056
1074
  }
1057
1075
  //#endregion
1058
- export { buildBaasSchema as a, introspectSchema as c, warnOnGeneratedSchemaDrift as i, readRlsStatus as l, diffGeneratedSchemaAgainstCatalogue as n, readCatalogueSchema as o, readGeneratedSchemaDrift as r, buildCollectionsFromSchema as s, describeSchemaDifference as t };
1076
+ export { buildBaasSchema as a, introspectSchema as c, warnOnGeneratedSchemaDrift as i, diffGeneratedSchemaAgainstCatalogue as n, readCatalogueSchema as o, readGeneratedSchemaDrift as r, compileIntrospectedTables as s, describeSchemaDifference as t };
1059
1077
 
1060
- //# sourceMappingURL=generated-schema-diff-By4dxyTH.js.map
1078
+ //# sourceMappingURL=generated-schema-diff-DoT2dYDe.js.map