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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (248) hide show
  1. package/README.md +11 -8
  2. package/dist/{BranchService-CrXvcES2.js → BranchService-USp1AvZB.js} +3 -3
  3. package/dist/{BranchService-CrXvcES2.js.map → BranchService-USp1AvZB.js.map} +1 -1
  4. package/dist/PostgresBackendDriver.d.ts +99 -54
  5. package/dist/PostgresBootstrapper.d.ts +12 -27
  6. package/dist/auth/ensure-tables.d.ts +16 -5
  7. package/dist/auth/schema-version.d.ts +2 -2
  8. package/dist/auth/services.d.ts +2 -3
  9. package/dist/{auth-users-columns-C72EMoDJ.js → auth-users-columns-BpfgbkxZ.js} +2 -16
  10. package/dist/auth-users-columns-BpfgbkxZ.js.map +1 -0
  11. package/dist/{backup-cli-CTKCOLpX.js → backup-cli-DbKyEj6c.js} +4 -4
  12. package/dist/{backup-cli-CTKCOLpX.js.map → backup-cli-DbKyEj6c.js.map} +1 -1
  13. package/dist/{boot-ddl-CqGIwSYx.js → boot-ddl-5H2bL_80.js} +2 -2
  14. package/dist/{boot-ddl-CqGIwSYx.js.map → boot-ddl-5H2bL_80.js.map} +1 -1
  15. package/dist/{cli-console-DBPw-oAz.js → cli-console-DsRgGSBR.js} +65 -39
  16. package/dist/cli-console-DsRgGSBR.js.map +1 -0
  17. package/dist/cli-console.d.ts +16 -13
  18. package/dist/cli-flags.d.ts +8 -9
  19. package/dist/cli-helpers.d.ts +15 -11
  20. package/dist/{cli-errors-DYTxnLbW.js → cli-schema-dir-CiN0ephV.js} +184 -70
  21. package/dist/cli-schema-dir-CiN0ephV.js.map +1 -0
  22. package/dist/cli-schema-dir.d.ts +64 -0
  23. package/dist/cli.js +192 -257
  24. package/dist/cli.js.map +1 -1
  25. package/dist/data-transformer.d.ts +50 -19
  26. package/dist/{database-preflight-iBpT7-vv.js → database-preflight-bfnIBnjM.js} +5 -5
  27. package/dist/database-preflight-bfnIBnjM.js.map +1 -0
  28. package/dist/{deferred-index-build-BCU9RoHK.js → deferred-index-build-CcSDA7wE.js} +69 -13
  29. package/dist/deferred-index-build-CcSDA7wE.js.map +1 -0
  30. package/dist/{ensure-collection-policies-Bo-_fDAy.js → ensure-policies-rRmXb5bt.js} +31 -31
  31. package/dist/ensure-policies-rRmXb5bt.js.map +1 -0
  32. package/dist/{ensure-collection-tables-DCJINkT_.js → ensure-tables-Bvm-F2wW.js} +44 -37
  33. package/dist/ensure-tables-Bvm-F2wW.js.map +1 -0
  34. package/dist/{ensure-tables-BPGaGh0y.js → ensure-tables-CC8p_AK3.js} +34 -29
  35. package/dist/ensure-tables-CC8p_AK3.js.map +1 -0
  36. package/dist/{enum-labels-kept-YAgOZS4I.js → enum-labels-kept-FlX9SHdf.js} +8 -8
  37. package/dist/enum-labels-kept-FlX9SHdf.js.map +1 -0
  38. package/dist/{generate-drizzle-schema-DcrFr7YX.js → generate-drizzle-schema-SJMXxzPI.js} +12 -12
  39. package/dist/generate-drizzle-schema-SJMXxzPI.js.map +1 -0
  40. package/dist/{generate-drizzle-schema-logic-LTLZvt6r.js → generate-drizzle-schema-logic-DL7R1rAF.js} +15 -8
  41. package/dist/generate-drizzle-schema-logic-DL7R1rAF.js.map +1 -0
  42. package/dist/{generate-files-CsaVzatS.js → generate-files-tlJ9_lGI.js} +23 -30
  43. package/dist/generate-files-tlJ9_lGI.js.map +1 -0
  44. package/dist/{generate-next-step-DgK5BlBn.js → generate-next-step-CO09dovd.js} +3 -3
  45. package/dist/generate-next-step-CO09dovd.js.map +1 -0
  46. package/dist/{generate-postgres-ddl-logic-Dg0bcENZ.js → generate-postgres-ddl-logic-B8huc03c.js} +51 -21
  47. package/dist/generate-postgres-ddl-logic-B8huc03c.js.map +1 -0
  48. package/dist/{generated-schema-diff-By4dxyTH.js → generated-schema-diff-DoT2dYDe.js} +297 -279
  49. package/dist/generated-schema-diff-DoT2dYDe.js.map +1 -0
  50. package/dist/{generated-schema-staleness-BvNF3i-s.js → generated-schema-staleness-YBVq2kTn.js} +21 -29
  51. package/dist/generated-schema-staleness-YBVq2kTn.js.map +1 -0
  52. package/dist/history/ensure-history-table.d.ts +22 -0
  53. package/dist/index.d.ts +8 -2
  54. package/dist/index.es.js +201 -25
  55. package/dist/index.es.js.map +1 -1
  56. package/dist/interfaces.d.ts +3 -4
  57. package/dist/{introspect-db-queries-DevUrzll.js → introspect-db-queries-BgiRQqtR.js} +7 -2
  58. package/dist/introspect-db-queries-BgiRQqtR.js.map +1 -0
  59. package/dist/introspect-tables-Cw_A-kk4.js +2086 -0
  60. package/dist/introspect-tables-Cw_A-kk4.js.map +1 -0
  61. package/dist/load-tables-B1Re74ng.js +92 -0
  62. package/dist/load-tables-B1Re74ng.js.map +1 -0
  63. package/dist/{migrate-baseline-CmWXL7qx.js → migrate-baseline-DZmekgpD.js} +19 -32
  64. package/dist/migrate-baseline-DZmekgpD.js.map +1 -0
  65. package/dist/{migrate-policy-stamps-BN_Qad6c.js → migrate-policy-stamps-B_acrUQB.js} +18 -19
  66. package/dist/migrate-policy-stamps-B_acrUQB.js.map +1 -0
  67. package/dist/model/PostgresTableRegistry.d.ts +159 -0
  68. package/dist/model/build-registry.d.ts +25 -0
  69. package/dist/model/refresh-relational-schema.d.ts +24 -0
  70. package/dist/model/runtime-table.d.ts +53 -0
  71. package/dist/{collections → model}/validate-relations.d.ts +15 -21
  72. package/dist/{open-rebase-40paQfVW.js → open-rebase-4kisUF_k.js} +3946 -3870
  73. package/dist/open-rebase-4kisUF_k.js.map +1 -0
  74. package/dist/open-rebase.d.ts +16 -15
  75. package/dist/{pg-error-utils-DJHjCF7-.js → pg-error-utils-BT5NzGFZ.js} +17 -20
  76. package/dist/pg-error-utils-BT5NzGFZ.js.map +1 -0
  77. package/dist/plan-schema-Hbtjhge3.js +1633 -0
  78. package/dist/plan-schema-Hbtjhge3.js.map +1 -0
  79. package/dist/{policy-drift-C-m0uWHH.js → policy-drift-BVMyqHSa.js} +29 -29
  80. package/dist/policy-drift-BVMyqHSa.js.map +1 -0
  81. package/dist/{push-index-adoption-Cp7oZxSl.js → push-index-adoption-hpHTyXMR.js} +7 -7
  82. package/dist/push-index-adoption-hpHTyXMR.js.map +1 -0
  83. package/dist/{push-index-prebuild-DbwKGtQT.js → push-index-prebuild-Bty9F7bD.js} +6 -6
  84. package/dist/push-index-prebuild-Bty9F7bD.js.map +1 -0
  85. package/dist/{push-kept-defaults-CLcgsEPt.js → push-kept-defaults-Bst4MDup.js} +13 -16
  86. package/dist/push-kept-defaults-Bst4MDup.js.map +1 -0
  87. package/dist/{push-legacy-renames-BthD0E9W.js → push-legacy-renames-bB4bM6br.js} +6 -6
  88. package/dist/push-legacy-renames-bB4bM6br.js.map +1 -0
  89. package/dist/{push-policy-plan-BgcrroxQ.js → push-policy-plan-BI8U4BOD.js} +11 -11
  90. package/dist/push-policy-plan-BI8U4BOD.js.map +1 -0
  91. package/dist/{render-ddl-Ci3S_SoI.js → render-ddl-D4n86NHz.js} +14 -7
  92. package/dist/render-ddl-D4n86NHz.js.map +1 -0
  93. package/dist/{request-role-cli-Dy1EgJU9.js → request-role-cli-BdRzdE87.js} +11 -11
  94. package/dist/{request-role-cli-Dy1EgJU9.js.map → request-role-cli-BdRzdE87.js.map} +1 -1
  95. package/dist/{request-role-migration-GHTJnPMV.js → request-role-migration-C8aq_TO3.js} +2 -2
  96. package/dist/{request-role-migration-GHTJnPMV.js.map → request-role-migration-C8aq_TO3.js.map} +1 -1
  97. package/dist/{rls-enforcement-Cc_UhOxb.js → rls-enforcement-DB5HHj96.js} +19 -19
  98. package/dist/rls-enforcement-DB5HHj96.js.map +1 -0
  99. package/dist/{rls-settings-BCGMIig3.js → rls-settings-CmGK2U0a.js} +2 -2
  100. package/dist/rls-settings-CmGK2U0a.js.map +1 -0
  101. package/dist/schema/auth-users-columns.d.ts +1 -11
  102. package/dist/schema/catalogue-schema.d.ts +33 -29
  103. package/dist/schema/classify-change.d.ts +23 -16
  104. package/dist/schema/column-type-drift.d.ts +16 -0
  105. package/dist/schema/config-relations.d.ts +10 -9
  106. package/dist/schema/deferred-index-build.d.ts +1 -1
  107. package/dist/schema/doctor-cli.js +1544 -66
  108. package/dist/schema/doctor-cli.js.map +1 -1
  109. package/dist/schema/doctor-database.d.ts +7 -7
  110. package/dist/schema/doctor-policy-checks.d.ts +4 -4
  111. package/dist/schema/doctor-search-scale.d.ts +14 -14
  112. package/dist/schema/doctor.d.ts +27 -27
  113. package/dist/schema/dynamic-tables.d.ts +6 -5
  114. package/dist/schema/{ensure-collection-policies.d.ts → ensure-policies.d.ts} +20 -20
  115. package/dist/schema/{ensure-collection-tables.d.ts → ensure-tables.d.ts} +11 -11
  116. package/dist/schema/enum-labels-kept.d.ts +6 -6
  117. package/dist/schema/generate-drizzle-schema-logic.d.ts +3 -3
  118. package/dist/schema/generate-drizzle-schema.js +1 -1
  119. package/dist/schema/generate-files.d.ts +6 -6
  120. package/dist/schema/generate-postgres-ddl-logic.d.ts +23 -20
  121. package/dist/schema/generate-postgres-ddl.js +11 -11
  122. package/dist/schema/generate-postgres-ddl.js.map +1 -1
  123. package/dist/schema/generate-schema-commit.d.ts +13 -8
  124. package/dist/schema/generated-schema-diff.d.ts +16 -16
  125. package/dist/schema/generated-schema-staleness.d.ts +11 -11
  126. package/dist/schema/index-adoption.d.ts +4 -4
  127. package/dist/schema/introspect-db-customization.d.ts +47 -0
  128. package/dist/schema/introspect-db-inference.d.ts +30 -9
  129. package/dist/schema/introspect-db-logic.d.ts +79 -110
  130. package/dist/schema/introspect-db-project.d.ts +15 -18
  131. package/dist/schema/introspect-db-queries.d.ts +1 -1
  132. package/dist/schema/introspect-db-search.d.ts +25 -4
  133. package/dist/schema/introspect-db-storage.d.ts +4 -74
  134. package/dist/schema/introspect-db.js +102 -90
  135. package/dist/schema/introspect-db.js.map +1 -1
  136. package/dist/schema/introspect-runtime.d.ts +47 -36
  137. package/dist/schema/introspect-tables.d.ts +182 -0
  138. package/dist/schema/load-tables.d.ts +55 -0
  139. package/dist/schema/migrate-policy-stamps.d.ts +4 -4
  140. package/dist/schema/migration-freshness.d.ts +13 -13
  141. package/dist/schema/plan/column-order.d.ts +82 -0
  142. package/dist/schema/plan/diff-plan.d.ts +9 -3
  143. package/dist/schema/plan/plan-schema.d.ts +55 -52
  144. package/dist/schema/plan/render-drizzle.d.ts +1 -1
  145. package/dist/schema/plan/types.d.ts +24 -15
  146. package/dist/schema/push-index-adoption.d.ts +3 -3
  147. package/dist/schema/push-index-prebuild.d.ts +3 -3
  148. package/dist/schema/push-kept-defaults.d.ts +7 -7
  149. package/dist/schema/push-legacy-renames.d.ts +3 -3
  150. package/dist/schema/push-policy-plan.d.ts +5 -5
  151. package/dist/schema/reconcile-schema.d.ts +5 -5
  152. package/dist/schema/relation-names.d.ts +15 -20
  153. package/dist/schema/render-outputs.d.ts +76 -0
  154. package/dist/schema/search-column.d.ts +11 -43
  155. package/dist/schema/{collection-index.d.ts → table-index.d.ts} +21 -42
  156. package/dist/schema/{collections-schema-version.d.ts → tables-schema-version.d.ts} +8 -2
  157. package/dist/schema/vector-index.d.ts +24 -28
  158. package/dist/{search-column-BM-GV6vH.js → search-column-BO-WND-B.js} +86 -149
  159. package/dist/search-column-BO-WND-B.js.map +1 -0
  160. package/dist/security/caller-sql-columns.d.ts +9 -6
  161. package/dist/security/policy-drift.d.ts +14 -14
  162. package/dist/security/rls-enforcement.d.ts +19 -25
  163. package/dist/security/rls-settings.d.ts +2 -2
  164. package/dist/security/served-table-protection.d.ts +125 -0
  165. package/dist/services/FetchService.d.ts +22 -133
  166. package/dist/services/PersistService.d.ts +6 -17
  167. package/dist/services/RelationService.d.ts +57 -106
  168. package/dist/services/RelationWriteService.d.ts +59 -66
  169. package/dist/services/cdc/identity-columns.d.ts +7 -5
  170. package/dist/services/cdc/junction-tables.d.ts +14 -14
  171. package/dist/services/collection-helpers.d.ts +52 -95
  172. package/dist/services/dataService.d.ts +15 -12
  173. package/dist/services/field-op-sql.d.ts +11 -9
  174. package/dist/services/field-viewer.d.ts +12 -11
  175. package/dist/services/hidden-columns.d.ts +30 -0
  176. package/dist/services/index.d.ts +1 -1
  177. package/dist/services/junction-writes.d.ts +37 -18
  178. package/dist/services/nested-path.d.ts +18 -18
  179. package/dist/services/read-field-access.d.ts +23 -7
  180. package/dist/services/read-scope.d.ts +10 -9
  181. package/dist/services/realtimeService.d.ts +25 -10
  182. package/dist/services/relation-tables.d.ts +97 -0
  183. package/dist/services/row-pipeline.d.ts +50 -69
  184. package/dist/services/soft-delete.d.ts +25 -24
  185. package/dist/services/table-hooks.d.ts +146 -0
  186. package/dist/services/view-access.d.ts +7 -7
  187. package/dist/services/write-transaction-scope.d.ts +1 -1
  188. package/dist/{source-fZb92pN8.js → source-VxbrQojV.js} +111 -79
  189. package/dist/source-VxbrQojV.js.map +1 -0
  190. package/dist/{collections-schema-version-D7bDI0PJ.js → tables-schema-version-YvZIBlOP.js} +12 -6
  191. package/dist/tables-schema-version-YvZIBlOP.js.map +1 -0
  192. package/dist/utils/drizzle-conditions.d.ts +70 -84
  193. package/dist/utils/pg-array-null-patch.d.ts +27 -10
  194. package/dist/utils/pg-error-utils.d.ts +4 -4
  195. package/dist/{vector-index-DsQ3V2d2.js → vector-index-VSh3ufTd.js} +62 -54
  196. package/dist/vector-index-VSh3ufTd.js.map +1 -0
  197. package/dist/{websocket-B7ex6AQM.js → websocket-BevXvwfo.js} +51 -40
  198. package/dist/websocket-BevXvwfo.js.map +1 -0
  199. package/dist/websocket.d.ts +2 -2
  200. package/package.json +7 -7
  201. package/dist/auth-users-columns-C72EMoDJ.js.map +0 -1
  202. package/dist/cli-collections-path.d.ts +0 -31
  203. package/dist/cli-console-DBPw-oAz.js.map +0 -1
  204. package/dist/cli-errors-DYTxnLbW.js.map +0 -1
  205. package/dist/collections/PostgresCollectionRegistry.d.ts +0 -47
  206. package/dist/collections/buildRegistry.d.ts +0 -27
  207. package/dist/collections-schema-version-D7bDI0PJ.js.map +0 -1
  208. package/dist/column-plan-helpers-BeSztMor.js +0 -161
  209. package/dist/column-plan-helpers-BeSztMor.js.map +0 -1
  210. package/dist/database-preflight-iBpT7-vv.js.map +0 -1
  211. package/dist/deferred-index-build-BCU9RoHK.js.map +0 -1
  212. package/dist/doctor-Kg1oUK0Q.js +0 -1458
  213. package/dist/doctor-Kg1oUK0Q.js.map +0 -1
  214. package/dist/ensure-collection-policies-Bo-_fDAy.js.map +0 -1
  215. package/dist/ensure-collection-tables-DCJINkT_.js.map +0 -1
  216. package/dist/ensure-tables-BPGaGh0y.js.map +0 -1
  217. package/dist/enum-labels-kept-YAgOZS4I.js.map +0 -1
  218. package/dist/generate-drizzle-schema-DcrFr7YX.js.map +0 -1
  219. package/dist/generate-drizzle-schema-logic-LTLZvt6r.js.map +0 -1
  220. package/dist/generate-files-CsaVzatS.js.map +0 -1
  221. package/dist/generate-next-step-DgK5BlBn.js.map +0 -1
  222. package/dist/generate-postgres-ddl-logic-Dg0bcENZ.js.map +0 -1
  223. package/dist/generated-schema-diff-By4dxyTH.js.map +0 -1
  224. package/dist/generated-schema-staleness-BvNF3i-s.js.map +0 -1
  225. package/dist/introspect-db-logic-DWqAEURB.js +0 -2047
  226. package/dist/introspect-db-logic-DWqAEURB.js.map +0 -1
  227. package/dist/introspect-db-queries-DevUrzll.js.map +0 -1
  228. package/dist/migrate-baseline-CmWXL7qx.js.map +0 -1
  229. package/dist/migrate-policy-stamps-BN_Qad6c.js.map +0 -1
  230. package/dist/open-rebase-40paQfVW.js.map +0 -1
  231. package/dist/pg-error-utils-DJHjCF7-.js.map +0 -1
  232. package/dist/plan-schema-vJd3UEmT.js +0 -1604
  233. package/dist/plan-schema-vJd3UEmT.js.map +0 -1
  234. package/dist/policy-drift-C-m0uWHH.js.map +0 -1
  235. package/dist/push-index-adoption-Cp7oZxSl.js.map +0 -1
  236. package/dist/push-index-prebuild-DbwKGtQT.js.map +0 -1
  237. package/dist/push-kept-defaults-CLcgsEPt.js.map +0 -1
  238. package/dist/push-legacy-renames-BthD0E9W.js.map +0 -1
  239. package/dist/push-policy-plan-BgcrroxQ.js.map +0 -1
  240. package/dist/render-ddl-Ci3S_SoI.js.map +0 -1
  241. package/dist/rls-enforcement-Cc_UhOxb.js.map +0 -1
  242. package/dist/rls-settings-BCGMIig3.js.map +0 -1
  243. package/dist/schema/column-plan-helpers.d.ts +0 -161
  244. package/dist/schema/introspect-db-naming.d.ts +0 -10
  245. package/dist/search-column-BM-GV6vH.js.map +0 -1
  246. package/dist/source-fZb92pN8.js.map +0 -1
  247. package/dist/vector-index-DsQ3V2d2.js.map +0 -1
  248. package/dist/websocket-B7ex6AQM.js.map +0 -1
@@ -71,7 +71,7 @@ export declare const TABLES_QUERY = "\n SELECT c.relname AS table_name,\n
71
71
  * errors. `character_maximum_length` is the declared `varchar(n)` bound —
72
72
  * already enforced by the database, and free to surface as validation.
73
73
  */
74
- export declare const COLUMNS_QUERY = "\n SELECT\n c.table_name,\n c.column_name,\n c.data_type,\n c.udt_name,\n c.is_nullable,\n c.column_default,\n c.ordinal_position,\n c.is_generated,\n c.generation_expression,\n c.is_identity,\n c.identity_generation,\n c.character_maximum_length,\n c.numeric_precision,\n c.numeric_scale,\n (SELECT a.atttypmod FROM pg_attribute a\n JOIN pg_class pc ON a.attrelid = pc.oid\n WHERE pc.relname = c.table_name\n AND a.attname = c.column_name\n AND pc.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = c.table_schema)) as atttypmod\n FROM information_schema.columns c\n WHERE c.table_schema = $1\n ORDER BY c.table_name, c.ordinal_position\n";
74
+ export declare const COLUMNS_QUERY = "\n SELECT\n c.table_name,\n c.column_name,\n c.data_type,\n c.udt_name,\n c.is_nullable,\n c.column_default,\n c.ordinal_position,\n c.is_generated,\n c.generation_expression,\n c.is_identity,\n c.identity_generation,\n c.character_maximum_length,\n c.numeric_precision,\n c.numeric_scale,\n (SELECT a.atttypmod FROM pg_attribute a\n JOIN pg_class pc ON a.attrelid = pc.oid\n WHERE pc.relname = c.table_name\n AND a.attname = c.column_name\n AND pc.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = c.table_schema)) as atttypmod,\n (SELECT format_type(a.atttypid, a.atttypmod) FROM pg_attribute a\n JOIN pg_class pc ON a.attrelid = pc.oid\n WHERE pc.relname = c.table_name\n AND a.attname = c.column_name\n AND pc.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = c.table_schema)) as formatted_type\n FROM information_schema.columns c\n WHERE c.table_schema = $1\n ORDER BY c.table_name, c.ordinal_position\n";
75
75
  export declare const ENUMS_QUERY = "\n SELECT t.typname AS enum_name,\n e.enumlabel AS enum_value,\n e.enumsortorder AS sort_order\n FROM pg_type t\n JOIN pg_enum e ON t.oid = e.enumtypid\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE n.nspname = $1\n ORDER BY t.typname, e.enumsortorder\n";
76
76
  /**
77
77
  * Primary key columns, in key order.
@@ -1,10 +1,31 @@
1
+ /**
2
+ * A table's `search` block, read back out of the column it built.
3
+ *
4
+ * A Rebase search column is `tsvector GENERATED ALWAYS AS (…) STORED`, stamped
5
+ * with a fingerprint of the expression in its `COMMENT`. Introspection used to
6
+ * emit it as an ordinary read-only text column, which the planner makes a
7
+ * `text` column — so the first push after adopting a Rebase database planned
8
+ * `ALTER COLUMN "search_vector" TYPE text … DROP EXPRESSION`, and search was
9
+ * gone for whoever approved it.
10
+ *
11
+ * Reading the block back is a guess checked by the stamp: the deparsed
12
+ * expression names each field's column, weight and language, which is enough
13
+ * to write a candidate block; the candidate is then compiled by the very code
14
+ * that built the column, and kept only if its fingerprint is the one the column
15
+ * carries. A block that does not reproduce the stamp is not emitted at all —
16
+ * the note says so — because a wrong one would rebuild the column differently.
17
+ *
18
+ * `mode` and `fuzzyThreshold` act at query time and are stored nowhere, so they
19
+ * come back as their defaults.
20
+ */
21
+ import { type SearchConfig } from "@rebasepro/types";
1
22
  import type { TableColumn } from "./introspect-db-logic.js";
2
23
  /** What introspection makes of a table's search columns. */
3
24
  export interface ReconstructedSearch {
4
- /** The generated columns that belong to the search block — never emitted as properties. */
25
+ /** The generated columns that belong to the search block — never emitted as columns. */
5
26
  columns: Set<string>;
6
- /** The `search: { … }` source, when the stamp confirmed it. */
7
- block?: string;
27
+ /** The table's `search` block, when the stamp confirmed it. */
28
+ search?: SearchConfig;
8
29
  note?: string;
9
30
  }
10
31
  /**
@@ -17,6 +38,6 @@ export declare function reconstructSearchBlock(input: {
17
38
  columns: TableColumn[];
18
39
  /** column → `COMMENT ON COLUMN`. */
19
40
  comments: Map<string, string>;
20
- /** column → the property key it is generated under. */
41
+ /** column → the column key it is generated under. */
21
42
  keyByColumn: Map<string, string>;
22
43
  }): ReconstructedSearch;
@@ -1,30 +1,9 @@
1
1
  /**
2
- * The property keys a column needs for the planner to build that same column.
3
- *
4
- * Introspection writes collections, and `rebase db push` plans them back into
5
- * DDL. The two used to read a column differently: introspection wrote
6
- * `type: "number"` for an `integer`, and the planner reads an unqualified
7
- * number as `NUMERIC`; `validation.max: 40` for a `varchar(40)`, and the
8
- * planner reads an unqualified string as `TEXT`; a `time` as a plain `date`,
9
- * which the planner makes a `timestamptz` — a change Postgres refuses to cast.
10
- * So adopting a database — introspect, then push, the documented path — planned
11
- * a type change on nearly every column, and some it could not even dry-run.
12
- *
13
- * Each function here answers one question about one column: what to write so
14
- * that `planSchema` produces exactly what the catalogue holds. Where no
15
- * property can say it, the answer is a note naming the column and what a push
16
- * would do to it, so the reader decides before anything runs.
17
- *
18
- * Pure: catalogue rows in, keys and notes out.
2
+ * The sequence a `SERIAL` column owns, named the way Postgres names it — how
3
+ * introspection tells a key whose default is its own serial sequence (declared
4
+ * `col.serial()`) from one fed by a sequence Rebase did not create (a
5
+ * `{ kind: "database" }` default).
19
6
  */
20
- import type { ForeignKeyRow, TableColumn } from "./introspect-db-logic.js";
21
- /** Keys to write on a property, as `key: value` source fragments, plus what could not be said. */
22
- export interface ColumnStorage {
23
- /** e.g. `columnType: "varchar"`, `precision: 10`. */
24
- keys: string[];
25
- /** Why the planner will not reproduce this column exactly, when it will not. */
26
- note?: string;
27
- }
28
7
  /**
29
8
  * The name Postgres gives a `SERIAL` column's sequence — `ChooseRelationName`
30
9
  * with the `seq` label: `<table>_<column>_seq`, and when that is over 63 bytes
@@ -32,52 +11,3 @@ export interface ColumnStorage {
32
11
  * fits.
33
12
  */
34
13
  export declare function serialSequenceName(table: string, column: string): string;
35
- /**
36
- * The `isId` (and `columnType`) a single-column primary key needs.
37
- *
38
- * `isId: "increment"` is an identity column, and only an INTEGER one. A serial
39
- * key — an integer with a `nextval` default — is `SERIAL`/`BIGSERIAL`, declared
40
- * through `columnType` beside `isId: "manual"`. A uuid key is `"uuid"` only when
41
- * the database generates it; a key with no default is `"manual"`, which keeps
42
- * the planner from inventing one.
43
- */
44
- export declare function primaryKeyStorage(col: TableColumn, propType: string): ColumnStorage;
45
- /**
46
- * The keys a non-key column needs, for the property type introspection chose.
47
- *
48
- * `enumTypeName` is the type the planner would name for this column
49
- * (`<table>_<column>`, cut to 63 bytes); an enum column whose type is called
50
- * anything else cannot be declared, and the note says how to rename it.
51
- */
52
- export declare function columnStorage(col: TableColumn, propType: string, context: {
53
- isEnumColumn: boolean;
54
- enumTypeName: string;
55
- enumTypeShared: boolean;
56
- }): ColumnStorage;
57
- /**
58
- * The `columnType` an array column needs, or a note when its element type is
59
- * not one the planner stores natively.
60
- *
61
- * Only `text[]`, `integer[]`, `boolean[]` and `numeric[]` are. Reading
62
- * `bigint[]` as `integer[]` — what this used to do — planned a narrowing.
63
- */
64
- export declare function arrayStorage(col: TableColumn): {
65
- columnType?: string;
66
- innerType: string;
67
- note?: string;
68
- };
69
- /**
70
- * A column default as a `defaultValue`, when it is a literal a property can carry.
71
- *
72
- * `undefined` when there is no default to carry, or when the default is one the
73
- * generator expresses another way (`now()` is `autoValue`, a key's default is
74
- * its `isId`). `{ note }` when there is a default and no property can say it —
75
- * a push would plan dropping it.
76
- */
77
- export declare function literalDefaultOf(col: TableColumn, propType: string): {
78
- source: string;
79
- } | {
80
- note: string;
81
- } | undefined;
82
- /** `ON DELETE` as the relation's `onDelete`, when it is not the default the planner would choose. */
83
- export declare function onDeleteOf(fk: ForeignKeyRow, required: boolean): string | undefined;
@@ -2,22 +2,23 @@ import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { n as require_arg, o as __toESM, t as promptConfirm } from "../cli-prompt-DXG0yk-h.js";
4
4
  import { u as pinSearchPath } from "../connection-C1zXTPJq.js";
5
- import { a as diagnoseDbError } from "../cli-errors-DYTxnLbW.js";
6
- import { a as outWarn, i as outError, r as out, t as chalk } from "../source-fZb92pN8.js";
7
- import { i as readSchemaMetadata, n as isUsableFileName, r as quoteRelation, t as countRowsUpTo } from "../introspect-db-queries-DevUrzll.js";
8
- import { a as compositeKeySkipReason, c as generateIndexContent, d as mergeIndexContent, f as safeHostFromUrl, h as lookupCandidates, i as buildTablesMap, m as classifyTables, o as describeRlsOffTables, r as buildEnumMap, s as generateCollectionFile } from "../introspect-db-logic-DWqAEURB.js";
5
+ import { c as diagnoseDbError } from "../cli-schema-dir-CiN0ephV.js";
6
+ import { a as outWarn, i as outError, r as out, t as chalk } from "../source-VxbrQojV.js";
7
+ import { i as readSchemaMetadata, n as isUsableFileName, r as quoteRelation, t as countRowsUpTo } from "../introspect-db-queries-BgiRQqtR.js";
8
+ import { a as describeRlsOffTables, c as mergeIndexModule, d as lookupCandidates, i as buildTablesMap, l as safeHostFromUrl, o as generateSchemaModules, u as classifyTables } from "../introspect-tables-Cw_A-kk4.js";
9
9
  import pg from "pg";
10
+ import { printIndexModule, tableIdentifier } from "@rebasepro/common";
10
11
  import path from "path";
11
12
  import fs from "fs";
12
13
  import * as dotenv from "dotenv";
13
14
  //#region src/schema/introspect-db-project.ts
14
15
  var import_arg = /* @__PURE__ */ __toESM(require_arg(), 1);
15
16
  /**
16
- * What the project being introspected into can actually import.
17
+ * Where the project being introspected into keeps what introspection writes.
17
18
  *
18
19
  * The generator is pure — `introspect-db-logic.ts` reads no files — so the one
19
- * question it cannot answer for itself lives here: which `defineCollection`, if
20
- * any, will resolve from the directory the collections are written to.
20
+ * question it cannot answer for itself lives here: does the project have a
21
+ * frontend that a `customizeTable` file can be written into.
21
22
  */
22
23
  /** How far up to look before giving up, if no project root announces itself. */
23
24
  var MAX_LEVELS = 8;
@@ -31,50 +32,47 @@ function declaredDependencies(manifestPath) {
31
32
  return names;
32
33
  }
33
34
  if (typeof parsed !== "object" || parsed === null) return names;
34
- const manifest = parsed;
35
35
  for (const field of [
36
36
  "dependencies",
37
37
  "devDependencies",
38
38
  "peerDependencies"
39
39
  ]) {
40
- const block = manifest[field];
40
+ const block = Reflect.get(parsed, field);
41
41
  if (typeof block === "object" && block !== null) for (const name of Object.keys(block)) names.add(name);
42
42
  }
43
43
  return names;
44
44
  }
45
45
  /**
46
- * Which `defineCollection` to generate against, for collections written to `outDir`.
47
- *
48
- * **The detection is the package manifests above the output directory**, unioned from
49
- * `outDir` up to and including the project root — the first ancestor holding a
50
- * `rebase.json`, or `MAX_LEVELS` up if there is none.
51
- *
52
- * That is the rule Node itself applies: a file in `config/collections` resolves a bare
53
- * specifier through `config/node_modules`, then `<project>/node_modules`, and so on up.
54
- * Reading the manifests along that same path answers the only question that matters —
55
- * *will this import resolve in the project I am writing into* — from the state on disk
56
- * at the moment of generation. The alternatives are all proxies for it: `rebase.json`'s
57
- * `apps` block says a CMS scaffold declared an admin app, and a `frontend/` directory
58
- * says one was scaffolded, but neither is what the compiler consults, and either can be
59
- * true of a project whose `config` package does not depend on `@rebasepro/cms-types`.
60
- *
61
- * Ambiguity resolves towards the admin panel: a project that declares both packages has
62
- * a panel, and `@rebasepro/cms-types` is the flavour that keeps the `admin` block.
46
+ * The project root above a directory: the first ancestor holding a
47
+ * `rebase.json`, or `undefined` when none does within reach.
63
48
  */
64
- function detectCollectionBuilder(outDir) {
65
- let dir = path.resolve(outDir);
66
- const declared = /* @__PURE__ */ new Set();
49
+ function findProjectRoot(from) {
50
+ let dir = path.resolve(from);
67
51
  for (let level = 0; level < MAX_LEVELS; level++) {
68
- const manifest = path.join(dir, "package.json");
69
- if (fs.existsSync(manifest)) for (const name of declaredDependencies(manifest)) declared.add(name);
70
- if (fs.existsSync(path.join(dir, "rebase.json"))) break;
52
+ if (fs.existsSync(path.join(dir, "rebase.json"))) return dir;
71
53
  const parent = path.dirname(dir);
72
- if (parent === dir) break;
54
+ if (parent === dir) return void 0;
73
55
  dir = parent;
74
56
  }
75
- if (declared.has("@rebasepro/cms-types")) return "admin-types";
76
- if (declared.has("@rebasepro/common")) return "common";
77
- return "annotation";
57
+ }
58
+ /**
59
+ * The `frontend/src/cms` directory introspection writes `customizeTable`
60
+ * files into, or `undefined` when the project has no frontend that can import
61
+ * `@rebasepro/cms`.
62
+ *
63
+ * The project root is the one above the schema directory (`rebase.json`), or —
64
+ * in a layout without one — the parent of `backend/`. The frontend is
65
+ * `<root>/frontend`, and it counts only when a manifest on the path a
66
+ * `frontend/src/cms/<table>.tsx` resolves bare specifiers along (the frontend's
67
+ * own `package.json`, then the root's) declares `@rebasepro/cms`: that is the
68
+ * import the file opens with, and a headless project could not resolve it.
69
+ */
70
+ function detectCmsDir(schemaDir) {
71
+ const resolved = path.resolve(schemaDir);
72
+ const root = findProjectRoot(resolved) ?? path.dirname(path.dirname(resolved));
73
+ const frontend = path.join(root, "frontend");
74
+ if (!fs.existsSync(frontend)) return void 0;
75
+ for (const manifest of [path.join(frontend, "package.json"), path.join(root, "package.json")]) if (fs.existsSync(manifest) && declaredDependencies(manifest).has("@rebasepro/cms")) return path.join(frontend, "src", "cms");
78
76
  }
79
77
  //#endregion
80
78
  //#region src/schema/introspect-db-constraints.ts
@@ -402,21 +400,22 @@ function parseCheckConstraints(rows) {
402
400
  }
403
401
  //#endregion
404
402
  //#region src/schema/introspect-db.ts
403
+ /** A relative import between two files, POSIX-separated, without the extension. */
404
+ function relativeImport(fromDir, toFile) {
405
+ const relative = path.relative(fromDir, toFile).split(path.sep).join("/").replace(/\.tsx?$/, "");
406
+ return relative.startsWith(".") ? relative : `./${relative}`;
407
+ }
405
408
  async function main() {
406
409
  const args = (0, import_arg.default)({
407
- "--output": String,
408
- "--collections": String,
410
+ "--schema-dir": String,
409
411
  "--force": Boolean,
410
412
  "--schema": String,
411
413
  "--data-inference": Boolean,
412
414
  "--no-data-inference": Boolean,
413
- "-o": "--output",
414
- "-c": "--collections",
415
415
  "-f": "--force"
416
416
  }, { permissive: true });
417
- const cwd = process.cwd();
418
- const defaultOutDir = path.basename(cwd) === "backend" ? path.resolve(cwd, "..", "config", "collections") : path.resolve(cwd, "config", "collections");
419
- const outDir = path.resolve(args["--output"] || args["--collections"] || defaultOutDir);
417
+ const outDir = path.resolve(process.cwd(), args["--schema-dir"] || "schema");
418
+ const cmsDir = detectCmsDir(outDir);
420
419
  const force = args["--force"] || false;
421
420
  const pgSchema = args["--schema"] || "public";
422
421
  const envPaths = [
@@ -455,9 +454,7 @@ async function main() {
455
454
  out(chalk.gray(`Introspecting schema '${pgSchema}'...`));
456
455
  try {
457
456
  const metadata = await readSchemaMetadata(client, pgSchema);
458
- const enumMap = buildEnumMap(metadata.enumValues);
459
457
  const tablesMap = buildTablesMap(metadata.tables, metadata.columns, metadata.pks, metadata.fks);
460
- const fks = metadata.fks;
461
458
  for (const table of lookupCandidates(metadata, tablesMap)) try {
462
459
  metadata.rowCounts[table] = await countRowsUpTo(client, pgSchema, table, 50);
463
460
  } catch (err) {
@@ -465,11 +462,6 @@ async function main() {
465
462
  }
466
463
  const classifications = classifyTables(metadata, tablesMap);
467
464
  const checkFacts = parseCheckConstraints(metadata.checks);
468
- const builder = detectCollectionBuilder(outDir);
469
- if (builder === "annotation") {
470
- outWarn(chalk.yellow(`⚠ Neither @rebasepro/cms-types nor @rebasepro/common is declared above ${outDir}.`));
471
- outWarn(chalk.gray(" Generating plain type annotations, which widen the property keys to `string`: `propertiesOrder` and friends will not be checked. Add @rebasepro/common to the config package to turn that checking on."));
472
- }
473
465
  const joinTables = new Set(Array.from(classifications.values()).filter((c) => c.role === "junction").map((c) => c.table));
474
466
  const roleCount = (role) => Array.from(classifications.values()).filter((c) => c.role === role).length;
475
467
  out(chalk.blue(`Found ${tablesMap.size} tables.`));
@@ -478,51 +470,65 @@ async function main() {
478
470
  if (args["--no-data-inference"]) runDataInference = false;
479
471
  else if (args["--data-inference"] !== void 0) runDataInference = args["--data-inference"];
480
472
  else if (!process.stdin.isTTY) out(chalk.gray("Skipping data inference (non-interactive run; pass --data-inference to enable)."));
481
- else runDataInference = await promptConfirm(chalk.yellow("? Do you want to run comprehensive data inference on sampled rows to auto-detect types, formats, constraints, and UI configurations? (y/N) "));
482
- if (runDataInference) out(chalk.gray("Sampling database rows for data inference..."));
473
+ else runDataInference = await promptConfirm(chalk.yellow("? Do you want to sample rows to suggest validation and how the panel edits each column? (y/N) "));
474
+ const unusable = new Set(Array.from(tablesMap.keys()).filter((t) => !joinTables.has(t) && !isUsableFileName(t)));
475
+ for (const tableName of unusable) outWarn(chalk.yellow(`⚠ Skipping table ${JSON.stringify(tableName)}: its name cannot be used as a filename. Rename the table, or write this table by hand.`));
476
+ const samples = /* @__PURE__ */ new Map();
477
+ if (runDataInference) {
478
+ out(chalk.gray("Sampling database rows for data inference..."));
479
+ for (const tableName of tablesMap.keys()) {
480
+ if (joinTables.has(tableName) || unusable.has(tableName)) continue;
481
+ try {
482
+ const { rows } = await client.query(`SELECT * FROM ${quoteRelation(pgSchema, tableName)} LIMIT 100`);
483
+ samples.set(tableName, rows);
484
+ } catch (err) {
485
+ outError(chalk.yellow(`⚠ Failed to sample data for table ${tableName}: ${err instanceof Error ? err.message : String(err)}`));
486
+ }
487
+ }
488
+ }
489
+ const generation = generateSchemaModules({
490
+ metadata,
491
+ classifications,
492
+ checkFacts,
493
+ samples,
494
+ leaveOut: unusable,
495
+ ...cmsDir ? { cms: { tableImport: (table) => relativeImport(cmsDir, path.join(outDir, `${table}.ts`)) } } : {}
496
+ });
497
+ for (const { table, reason } of generation.failed) outWarn(chalk.yellow(`⚠ Skipping table ${JSON.stringify(table)}: ${reason}`));
483
498
  const generatedFiles = [];
484
499
  const skippedFiles = [];
485
- const compositeKeyed = new Map(Array.from(tablesMap.entries()).filter(([tableName]) => !joinTables.has(tableName)).map(([tableName, meta]) => [tableName, compositeKeySkipReason(meta, fks)]).filter((entry) => entry[1] !== void 0));
486
- for (const [tableName, reason] of compositeKeyed) outWarn(chalk.yellow(`⚠ Skipping table ${JSON.stringify(tableName)}: it is keyed on (${tablesMap.get(tableName)?.pks.join(", ")}), and ${reason}. \`rebase db push\` leaves a table that is not a collection alone.`));
487
500
  const notes = [];
488
- const tablesToProcess = Array.from(tablesMap.entries()).filter(([tableName]) => !joinTables.has(tableName) && !compositeKeyed.has(tableName));
489
- for (const [tableName, meta] of tablesToProcess) {
490
- if (!isUsableFileName(tableName)) {
491
- outWarn(chalk.yellow(`⚠ Skipping table ${JSON.stringify(tableName)}: its name cannot be used as a filename. Rename the table, or write this collection by hand.`));
492
- skippedFiles.push(tableName);
493
- continue;
494
- }
495
- const filePath = path.join(outDir, `${tableName}.ts`);
501
+ const customizations = [];
502
+ for (const generated of generation.tables) {
503
+ const filePath = path.join(outDir, `${generated.table}.ts`);
496
504
  if (fs.existsSync(filePath) && !force) {
497
- skippedFiles.push(tableName);
505
+ skippedFiles.push(generated.table);
498
506
  continue;
499
507
  }
500
- let sampleData = void 0;
501
- if (runDataInference) try {
502
- const { rows } = await client.query(`SELECT * FROM ${quoteRelation(pgSchema, tableName)} LIMIT 100`);
503
- sampleData = rows;
504
- } catch (err) {
505
- outError(chalk.yellow(`⚠ Failed to sample data for table ${tableName}: ${err instanceof Error ? err.message : String(err)}`));
506
- }
507
- const fileContent = generateCollectionFile(tableName, meta, fks, joinTables, tablesMap, enumMap, sampleData, {
508
- metadata,
509
- classifications,
510
- checkFacts,
511
- builder,
512
- notes,
513
- skippedTables: new Set(compositeKeyed.keys())
508
+ fs.writeFileSync(filePath, generated.schemaModule, "utf-8");
509
+ generatedFiles.push({
510
+ identifier: generated.identifier,
511
+ table: generated.table
514
512
  });
515
- fs.writeFileSync(filePath, fileContent, "utf-8");
516
- generatedFiles.push(tableName);
513
+ for (const note of generated.notes) notes.push(`${generated.table}: ${note}`);
517
514
  out(chalk.green(` ✓ ${filePath}`));
515
+ if (cmsDir && generated.customization) {
516
+ const cmsPath = path.join(cmsDir, `${generated.table}.tsx`);
517
+ if (fs.existsSync(cmsPath) && !force) continue;
518
+ fs.mkdirSync(cmsDir, { recursive: true });
519
+ fs.writeFileSync(cmsPath, generated.customization, "utf-8");
520
+ customizations.push(generated.table);
521
+ out(chalk.green(` ✓ ${cmsPath}`));
522
+ }
518
523
  }
519
524
  if (notes.length > 0) {
520
525
  outWarn("");
521
- outWarn(chalk.yellow(`⚠ ${notes.length} column(s) will not round-trip exactly — \`rebase db push\` would change them:`));
526
+ outWarn(chalk.yellow(`⚠ ${notes.length} note(s) on what \`rebase db push\` would not reproduce exactly:`));
522
527
  for (const note of [...notes].sort()) outWarn(chalk.gray(` - ${note}`));
523
528
  outWarn(chalk.gray(" Read these before the first push. Run `rebase db push --dry-run` to see the plan."));
524
529
  }
525
- const rlsOff = describeRlsOffTables(metadata.tables.filter((table) => table.rls_enabled === false && generatedFiles.includes(table.table_name)).map((table) => table.table_name));
530
+ const written = new Set(generatedFiles.map((file) => file.table));
531
+ const rlsOff = describeRlsOffTables(generation.rlsOff.filter((table) => written.has(table)));
526
532
  if (rlsOff) {
527
533
  const [headline, ...rest] = rlsOff.split("\n");
528
534
  outWarn("");
@@ -532,13 +538,18 @@ async function main() {
532
538
  }
533
539
  if (generatedFiles.length > 0) {
534
540
  const indexPath = path.join(outDir, "index.ts");
535
- if (fs.existsSync(indexPath) && !force) {
536
- const merged = mergeIndexContent(fs.readFileSync(indexPath, "utf-8"), generatedFiles);
537
- fs.writeFileSync(indexPath, merged, "utf-8");
538
- } else {
539
- const siblings = fs.readdirSync(outDir).filter((f) => f.endsWith(".ts") && f !== "index.ts").map((f) => f.replace(/\.ts$/, ""));
540
- const indexContent = generateIndexContent([.../* @__PURE__ */ new Set([...generatedFiles, ...siblings])]);
541
- fs.writeFileSync(indexPath, indexContent, "utf-8");
541
+ const entries = generatedFiles.map((file) => ({
542
+ identifier: file.identifier,
543
+ importPath: `./${file.table}`
544
+ })).sort((a, b) => a.importPath.localeCompare(b.importPath));
545
+ if (fs.existsSync(indexPath) && !force) fs.writeFileSync(indexPath, mergeIndexModule(fs.readFileSync(indexPath, "utf-8"), entries), "utf-8");
546
+ else {
547
+ const siblings = fs.readdirSync(outDir).filter((f) => f.endsWith(".ts") && f !== "index.ts").map((f) => f.replace(/\.ts$/, "")).filter((name) => !entries.some((entry) => entry.importPath === `./${name}`)).map((name) => ({
548
+ identifier: tableIdentifier(name),
549
+ importPath: `./${name}`
550
+ }));
551
+ const all = [...entries, ...siblings].sort((a, b) => a.importPath.localeCompare(b.importPath));
552
+ fs.writeFileSync(indexPath, printIndexModule(all), "utf-8");
542
553
  }
543
554
  out(chalk.green(` ✓ ${indexPath}`));
544
555
  }
@@ -548,8 +559,9 @@ async function main() {
548
559
  out(chalk.gray(" Use --force to overwrite existing files."));
549
560
  out("");
550
561
  }
551
- out(chalk.bold.green(`✓ Introspected ${tablesMap.size} tables — generated ${generatedFiles.length} collection(s).`));
552
- if (generatedFiles.length > 0) out(chalk.gray(` Review the generated files in ${outDir} and customize properties as needed.`));
562
+ out(chalk.bold.green(`✓ Introspected ${tablesMap.size} tables — generated ${generatedFiles.length} table(s).`));
563
+ if (generatedFiles.length > 0) out(chalk.gray(` Review the generated files in ${outDir}.`));
564
+ if (customizations.length > 0 && cmsDir) out(chalk.gray(` ${customizations.length} panel customization(s) in ${cmsDir}: pass them to <RebaseCMS tableCustomizations={[…]} />.`));
553
565
  out("");
554
566
  } catch (e) {
555
567
  outError(chalk.red(`✗ Error introspecting database: ${e instanceof Error ? e.message : String(e)}`));