@rebasepro/server-postgres 0.22.0 → 0.24.0

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 (123) hide show
  1. package/dist/{BranchService-CucnFcSE.js → BranchService-BRt78gfa.js} +35 -18
  2. package/dist/BranchService-BRt78gfa.js.map +1 -0
  3. package/dist/PostgresBackendDriver.d.ts +116 -4
  4. package/dist/auth/services.d.ts +99 -22
  5. package/dist/{auth-users-columns-D2LBFrMH.js → auth-users-columns-C72EMoDJ.js} +17 -1
  6. package/dist/{auth-users-columns-D2LBFrMH.js.map → auth-users-columns-C72EMoDJ.js.map} +1 -1
  7. package/dist/backup/backup-cli.d.ts +22 -0
  8. package/dist/{backup-cli-DqBakiMO.js → backup-cli-DW5p9_zv.js} +17 -14
  9. package/dist/backup-cli-DW5p9_zv.js.map +1 -0
  10. package/dist/{backup-service-CaMOS76G.js → backup-service-EwcDVG-8.js} +7 -9
  11. package/dist/{backup-service-CaMOS76G.js.map → backup-service-EwcDVG-8.js.map} +1 -1
  12. package/dist/{cli-errors-Dka89exj.js → cli-errors-DsA-K9uP.js} +101 -1
  13. package/dist/cli-errors-DsA-K9uP.js.map +1 -0
  14. package/dist/cli-errors.d.ts +42 -0
  15. package/dist/cli-flags-BglvpjHv.js +138 -0
  16. package/dist/cli-flags-BglvpjHv.js.map +1 -0
  17. package/dist/cli-flags.d.ts +28 -0
  18. package/dist/cli-helpers.d.ts +18 -12
  19. package/dist/cli-scratch-database.d.ts +34 -0
  20. package/dist/cli.js +177 -287
  21. package/dist/cli.js.map +1 -1
  22. package/dist/{column-plan-helpers-CpILzHJS.js → column-plan-helpers-1-LQD0yI.js} +44 -38
  23. package/dist/column-plan-helpers-1-LQD0yI.js.map +1 -0
  24. package/dist/data-transformer.d.ts +0 -8
  25. package/dist/{doctor-CU9IogdL.js → doctor-C-sYWbmt.js} +228 -46
  26. package/dist/doctor-C-sYWbmt.js.map +1 -0
  27. package/dist/{ensure-collection-policies-Dzd-2S81.js → ensure-collection-policies-B1ureSIV.js} +73 -18
  28. package/dist/ensure-collection-policies-B1ureSIV.js.map +1 -0
  29. package/dist/{ensure-collection-tables-CpAgy51F.js → ensure-collection-tables-kkkHk8oo.js} +124 -37
  30. package/dist/ensure-collection-tables-kkkHk8oo.js.map +1 -0
  31. package/dist/{ensure-tables-Cr5B4UmH.js → ensure-tables-BmI_tRxc.js} +10 -3
  32. package/dist/ensure-tables-BmI_tRxc.js.map +1 -0
  33. package/dist/{generate-drizzle-schema-B537GIvz.js → generate-drizzle-schema-93M0lUxK.js} +2 -2
  34. package/dist/{generate-drizzle-schema-B537GIvz.js.map → generate-drizzle-schema-93M0lUxK.js.map} +1 -1
  35. package/dist/{generate-drizzle-schema-logic-BcMl7VSy.js → generate-drizzle-schema-logic-sSFDp6LR.js} +26 -8
  36. package/dist/generate-drizzle-schema-logic-sSFDp6LR.js.map +1 -0
  37. package/dist/generate-postgres-ddl-logic-BJsLaVNX.js +152 -0
  38. package/dist/generate-postgres-ddl-logic-BJsLaVNX.js.map +1 -0
  39. package/dist/generated-sql.d.ts +28 -0
  40. package/dist/index.es.js +4768 -1117
  41. package/dist/index.es.js.map +1 -1
  42. package/dist/{introspect-db-logic-C6LQdTxj.js → introspect-db-logic-kCETE8TY.js} +532 -39
  43. package/dist/introspect-db-logic-kCETE8TY.js.map +1 -0
  44. package/dist/introspect-db-queries-C_Q5VgQw.js +317 -0
  45. package/dist/introspect-db-queries-C_Q5VgQw.js.map +1 -0
  46. package/dist/{plan-schema-CboAIwLN.js → plan-schema-DU9exq6C.js} +291 -529
  47. package/dist/plan-schema-DU9exq6C.js.map +1 -0
  48. package/dist/{policy-drift-xJfy9xG7.js → policy-drift-B-J2hhm0.js} +3 -3
  49. package/dist/policy-drift-B-J2hhm0.js.map +1 -0
  50. package/dist/{generate-postgres-ddl-logic-D7imhYV8.js → render-ddl-Ds2t_d9V.js} +11 -149
  51. package/dist/render-ddl-Ds2t_d9V.js.map +1 -0
  52. package/dist/{rls-bootstrap-sql-H3rCFi3F.js → rls-bootstrap-sql-_KNnjanK.js} +562 -35
  53. package/dist/rls-bootstrap-sql-_KNnjanK.js.map +1 -0
  54. package/dist/{rls-enforcement-C6Xk0lA6.js → rls-enforcement-CfXOJJaW.js} +10 -2
  55. package/dist/rls-enforcement-CfXOJJaW.js.map +1 -0
  56. package/dist/schema/atlas-argv.d.ts +15 -0
  57. package/dist/schema/auth-schema.d.ts +170 -0
  58. package/dist/schema/classify-change.d.ts +29 -1
  59. package/dist/schema/column-plan-helpers.d.ts +51 -20
  60. package/dist/schema/destructive-sql.d.ts +71 -1
  61. package/dist/schema/doctor-cli.js +4 -4
  62. package/dist/schema/doctor.d.ts +34 -1
  63. package/dist/schema/ensure-collection-policies.d.ts +22 -0
  64. package/dist/schema/generate-drizzle-schema.js +1 -1
  65. package/dist/schema/generate-postgres-ddl-logic.d.ts +5 -5
  66. package/dist/schema/generate-postgres-ddl.js +1 -1
  67. package/dist/schema/generate-schema-commit.d.ts +12 -0
  68. package/dist/schema/introspect-db-logic.d.ts +31 -0
  69. package/dist/schema/introspect-db-queries.d.ts +1 -1
  70. package/dist/schema/introspect-db-search.d.ts +22 -0
  71. package/dist/schema/introspect-db-storage.d.ts +83 -0
  72. package/dist/schema/introspect-db.js +15 -314
  73. package/dist/schema/introspect-db.js.map +1 -1
  74. package/dist/schema/plan/diff-plan.d.ts +4 -3
  75. package/dist/schema/plan/plan-schema.d.ts +26 -11
  76. package/dist/schema/plan/render-ddl.d.ts +6 -0
  77. package/dist/schema/plan/types.d.ts +43 -12
  78. package/dist/search-column-BM-GV6vH.js +442 -0
  79. package/dist/search-column-BM-GV6vH.js.map +1 -0
  80. package/dist/security/policy-drift.d.ts +1 -1
  81. package/dist/security/rls-enforcement.d.ts +7 -0
  82. package/dist/services/BranchService.d.ts +22 -1
  83. package/dist/services/FetchService.d.ts +102 -32
  84. package/dist/services/PersistService.d.ts +41 -5
  85. package/dist/services/RelationService.d.ts +29 -0
  86. package/dist/services/RelationWriteService.d.ts +6 -0
  87. package/dist/services/cdc/CdcListener.d.ts +15 -5
  88. package/dist/services/cdc/identity-columns.d.ts +19 -0
  89. package/dist/services/cdc/trigger-cdc.d.ts +45 -7
  90. package/dist/services/channel-bus/PostgresChannelBus.d.ts +12 -7
  91. package/dist/services/channel-history.d.ts +17 -1
  92. package/dist/services/collection-helpers.d.ts +21 -0
  93. package/dist/services/dataService.d.ts +3 -20
  94. package/dist/services/field-op-sql.d.ts +71 -0
  95. package/dist/services/junction-writes.d.ts +19 -3
  96. package/dist/services/pg-notify-listener.d.ts +95 -6
  97. package/dist/services/read-field-access.d.ts +19 -0
  98. package/dist/services/realtimeService.d.ts +232 -44
  99. package/dist/services/row-pipeline.d.ts +5 -0
  100. package/dist/services/socket-liveness.d.ts +45 -0
  101. package/dist/services/soft-delete.d.ts +12 -2
  102. package/dist/services/sql-script.d.ts +71 -0
  103. package/dist/services/write-depth.d.ts +16 -0
  104. package/dist/services/write-transaction-scope.d.ts +42 -0
  105. package/dist/utils/drizzle-conditions.d.ts +49 -4
  106. package/dist/utils/sql-redaction.d.ts +21 -0
  107. package/dist/websocket.d.ts +57 -18
  108. package/package.json +9 -9
  109. package/dist/BranchService-CucnFcSE.js.map +0 -1
  110. package/dist/backup-cli-DqBakiMO.js.map +0 -1
  111. package/dist/cli-errors-Dka89exj.js.map +0 -1
  112. package/dist/column-plan-helpers-CpILzHJS.js.map +0 -1
  113. package/dist/doctor-CU9IogdL.js.map +0 -1
  114. package/dist/ensure-collection-policies-Dzd-2S81.js.map +0 -1
  115. package/dist/ensure-collection-tables-CpAgy51F.js.map +0 -1
  116. package/dist/ensure-tables-Cr5B4UmH.js.map +0 -1
  117. package/dist/generate-drizzle-schema-logic-BcMl7VSy.js.map +0 -1
  118. package/dist/generate-postgres-ddl-logic-D7imhYV8.js.map +0 -1
  119. package/dist/introspect-db-logic-C6LQdTxj.js.map +0 -1
  120. package/dist/plan-schema-CboAIwLN.js.map +0 -1
  121. package/dist/policy-drift-xJfy9xG7.js.map +0 -1
  122. package/dist/rls-bootstrap-sql-H3rCFi3F.js.map +0 -1
  123. package/dist/rls-enforcement-C6Xk0lA6.js.map +0 -1
@@ -1,9 +1,10 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { a as __toESM, t as require___vite_browser_external } from "../__vite-browser-external-BnuHet1e.js";
4
+ import { i as readSchemaMetadata, n as isUsableFileName, r as quoteRelation, t as countRowsUpTo } from "../introspect-db-queries-C_Q5VgQw.js";
4
5
  import { n as outError, r as outWarn, t as out } from "../cli-output-CNdMql-L.js";
5
6
  import { t as chalk } from "../source-Br7L7GOI.js";
6
- import { a as generateCollectionFile, f as classifyTables, i as buildTablesMap, l as mergeIndexContent, o as generateIndexContent, p as lookupCandidates, r as buildEnumMap, u as safeHostFromUrl } from "../introspect-db-logic-C6LQdTxj.js";
7
+ import { a as compositeKeySkipReason, d as safeHostFromUrl, i as buildTablesMap, m as lookupCandidates, o as generateCollectionFile, p as classifyTables, r as buildEnumMap, s as generateIndexContent, u as mergeIndexContent } from "../introspect-db-logic-kCETE8TY.js";
7
8
  import { t as require_arg } from "../arg-Dni7MzLB.js";
8
9
  import pg from "pg";
9
10
  import fs from "fs";
@@ -77,317 +78,6 @@ function detectCollectionBuilder(outDir) {
77
78
  return "annotation";
78
79
  }
79
80
  //#endregion
80
- //#region src/schema/introspect-db-queries.ts
81
- /**
82
- * A Postgres identifier, quoted so that whatever is inside it stays inside it.
83
- *
84
- * Introspection reads table and schema names out of `pg_class` and puts them
85
- * straight back into SQL, and wrapping a name in double quotes is not the same
86
- * as escaping it: a table named `x" ; DROP TABLE users; --` closes the quote
87
- * and then the statement. Postgres's own escape for a quote inside a quoted
88
- * identifier is to double it, which is what this does.
89
- *
90
- * "The catalogue is trusted" is true of your own database, and is exactly the
91
- * assumption this tool cannot make. Introspection exists to be pointed at
92
- * databases somebody else built, and it runs with the privileges of whoever
93
- * ran it — which is usually a superuser, because that is who has a connection
94
- * string to a database they are adopting.
95
- */
96
- function quoteIdentifier(name) {
97
- return `"${name.replace(/"/g, "\"\"")}"`;
98
- }
99
- /** `"schema"."table"`, both halves quoted. */
100
- function quoteRelation(schema, table) {
101
- return `${quoteIdentifier(schema)}.${quoteIdentifier(table)}`;
102
- }
103
- /**
104
- * Can this table's name be the name of the file describing it?
105
- *
106
- * Introspection writes `<collectionsDir>/<tableName>.ts`, and the table name
107
- * came from a database this tool did not create. Postgres will hold a table
108
- * called `../../../etc/cron.d/x`, and `path.join` resolves it — so without this
109
- * the generator writes a file wherever the name points, as whoever ran the
110
- * command.
111
- *
112
- * Deliberately narrow, and deliberately not a blocklist of `..` and `/`: the
113
- * question is "is this a plain file name?", and every answer that is not
114
- * obviously yes is a table better written by hand. NUL and the Windows
115
- * separator are in scope because a collections directory is checked out on
116
- * whatever machine the developer has.
117
- */
118
- function isUsableFileName(name) {
119
- if (name.length === 0 || name.length > 200) return false;
120
- if (name === "." || name === "..") return false;
121
- if (/[/\\:\u0000-\u001f]/.test(name)) return false;
122
- return !name.startsWith(".") && !name.endsWith(".");
123
- }
124
- /**
125
- * Base tables, excluding partitions.
126
- *
127
- * `relispartition` is the reason this reads `pg_class` rather than
128
- * `information_schema.tables`, which reports every partition as a base table of
129
- * its own. Pagila partitions `payment` by month; introspected through
130
- * information_schema it yields `payment` plus 26 near-identical
131
- * `payment_p2022_*` collections, each with its own nav entry.
132
- *
133
- * `relkind = 'p'` (the partitioned parent) is included and `'r'` partitions are
134
- * dropped, which is the right way round: the parent is the queryable table.
135
- */
136
- var TABLES_QUERY = `
137
- SELECT c.relname AS table_name,
138
- c.relkind = 'p' AS is_partitioned
139
- FROM pg_class c
140
- JOIN pg_namespace n ON n.oid = c.relnamespace
141
- WHERE n.nspname = $1
142
- AND c.relkind IN ('r', 'p')
143
- AND NOT c.relispartition
144
- AND c.relname NOT LIKE 'drizzle_%'
145
- AND c.relname NOT LIKE 'rebase_%'
146
- ORDER BY c.relname
147
- `;
148
- /**
149
- * Columns, with the catalog facts that say a column is not the user's to edit.
150
- *
151
- * `is_generated`/`is_identity` are read for that reason: a generated column
152
- * rejects any write, so a form that offers it is offering a field that always
153
- * errors. `character_maximum_length` is the declared `varchar(n)` bound —
154
- * already enforced by the database, and free to surface as validation.
155
- */
156
- var COLUMNS_QUERY = `
157
- SELECT
158
- c.table_name,
159
- c.column_name,
160
- c.data_type,
161
- c.udt_name,
162
- c.is_nullable,
163
- c.column_default,
164
- c.ordinal_position,
165
- c.is_generated,
166
- c.is_identity,
167
- c.identity_generation,
168
- c.character_maximum_length,
169
- c.numeric_precision,
170
- c.numeric_scale,
171
- (SELECT a.atttypmod FROM pg_attribute a
172
- JOIN pg_class pc ON a.attrelid = pc.oid
173
- WHERE pc.relname = c.table_name
174
- AND a.attname = c.column_name
175
- AND pc.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = c.table_schema)) as atttypmod
176
- FROM information_schema.columns c
177
- WHERE c.table_schema = $1
178
- ORDER BY c.table_name, c.ordinal_position
179
- `;
180
- var ENUMS_QUERY = `
181
- SELECT t.typname AS enum_name,
182
- e.enumlabel AS enum_value,
183
- e.enumsortorder AS sort_order
184
- FROM pg_type t
185
- JOIN pg_enum e ON t.oid = e.enumtypid
186
- JOIN pg_namespace n ON t.typnamespace = n.oid
187
- WHERE n.nspname = $1
188
- ORDER BY t.typname, e.enumsortorder
189
- `;
190
- /**
191
- * Primary key columns, in key order.
192
- *
193
- * `ORDER BY k.ord` matters for composite keys: the position of a column inside
194
- * the key is what tells a two-column PK made of two foreign keys apart from an
195
- * ordinary composite key, and `= ANY(i.indkey)` (the shape this replaced)
196
- * returns catalog order instead.
197
- */
198
- var PRIMARY_KEYS_QUERY = `
199
- SELECT t.relname AS table_name,
200
- a.attname AS column_name
201
- FROM pg_index i
202
- JOIN pg_class t ON t.oid = i.indrelid
203
- JOIN pg_namespace n ON n.oid = t.relnamespace
204
- CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord)
205
- JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum
206
- WHERE i.indisprimary AND n.nspname = $1
207
- ORDER BY t.relname, k.ord
208
- `;
209
- /**
210
- * Foreign keys, one row per referencing column, with the delete rule.
211
- *
212
- * Read from `pg_constraint` rather than through
213
- * `information_schema.constraint_column_usage`, which does not preserve the
214
- * pairing on a composite foreign key: it reports the cross product of the
215
- * constraint's columns, so a two-column FK comes back as four rows, two of them
216
- * pairing the wrong columns. `unnest(...) WITH ORDINALITY` on both sides joined
217
- * on the ordinal keeps each referencing column with the column it references.
218
- *
219
- * `confdeltype` is carried because `ON DELETE CASCADE` is the schema author
220
- * saying, in the database, that the child cannot outlive the parent — the one
221
- * unambiguous declaration of ownership a schema contains.
222
- *
223
- * Constraints declared on a *partition* are attributed to the partition root,
224
- * because that is the table this run generates a collection for. Pagila declares
225
- * `payment`'s three foreign keys on each monthly partition and none on the
226
- * parent, so reading `pg_constraint` at face value gives the `payment`
227
- * collection no relations at all. `pick = 1` then keeps one row per logical key,
228
- * preferring the root's own constraint when it has one, so a schema that
229
- * declares the key on the parent *and* inherits it onto 26 partitions does not
230
- * yield 27 copies of the same relation.
231
- */
232
- var FOREIGN_KEYS_QUERY = `
233
- WITH fk AS (
234
- SELECT con.oid,
235
- con.conname,
236
- con.conrelid,
237
- con.confrelid,
238
- con.conkey,
239
- con.confkey,
240
- con.confdeltype,
241
- COALESCE(pg_partition_root(con.conrelid), con.conrelid) AS root_oid,
242
- row_number() OVER (
243
- PARTITION BY COALESCE(pg_partition_root(con.conrelid), con.conrelid),
244
- con.confrelid, con.conkey, con.confkey
245
- ORDER BY (con.conrelid = COALESCE(pg_partition_root(con.conrelid), con.conrelid)) DESC,
246
- con.oid
247
- ) AS pick
248
- FROM pg_constraint con
249
- JOIN pg_namespace n ON n.oid = con.connamespace
250
- WHERE con.contype = 'f' AND n.nspname = $1
251
- )
252
- SELECT root.relname AS table_name,
253
- sa.attname AS column_name,
254
- tgt.relname AS foreign_table_name,
255
- ta.attname AS foreign_column_name,
256
- fk.conname AS constraint_name,
257
- s.ord::int AS ordinal,
258
- CASE fk.confdeltype
259
- WHEN 'a' THEN 'NO ACTION'
260
- WHEN 'r' THEN 'RESTRICT'
261
- WHEN 'c' THEN 'CASCADE'
262
- WHEN 'n' THEN 'SET NULL'
263
- WHEN 'd' THEN 'SET DEFAULT'
264
- END AS delete_rule
265
- FROM fk
266
- JOIN pg_class root ON root.oid = fk.root_oid
267
- JOIN pg_class tgt ON tgt.oid = fk.confrelid
268
- CROSS JOIN LATERAL unnest(fk.conkey) WITH ORDINALITY AS s(attnum, ord)
269
- JOIN pg_attribute sa ON sa.attrelid = fk.conrelid AND sa.attnum = s.attnum
270
- CROSS JOIN LATERAL unnest(fk.confkey) WITH ORDINALITY AS f(attnum, ord)
271
- JOIN pg_attribute ta ON ta.attrelid = fk.confrelid AND ta.attnum = f.attnum
272
- WHERE fk.pick = 1 AND s.ord = f.ord
273
- ORDER BY root.relname, fk.conname, s.ord
274
- `;
275
- /**
276
- * Unique constraints and unique indexes, as ordered column lists.
277
- *
278
- * Indexes rather than constraints alone, because `CREATE UNIQUE INDEX` and
279
- * `ADD CONSTRAINT ... UNIQUE` produce the same guarantee and schemas use both.
280
- * Partial indexes (`indpred IS NOT NULL`) are excluded: they promise uniqueness
281
- * only over the rows matching their predicate, which is not the promise a
282
- * `validation: { unique: true }` field makes.
283
- */
284
- var UNIQUE_CONSTRAINTS_QUERY = `
285
- SELECT t.relname AS table_name,
286
- ic.relname AS constraint_name,
287
- -- ::text, because the driver has no parser for an array of \`name\`
288
- -- and hands back the raw \`{a,b}\` literal as a string. Every consumer
289
- -- here indexes and compares it as an array, and a string of that
290
- -- shape fails those silently rather than loudly.
291
- array_agg(a.attname::text ORDER BY k.ord) AS column_names
292
- FROM pg_index i
293
- JOIN pg_class t ON t.oid = i.indrelid
294
- JOIN pg_class ic ON ic.oid = i.indexrelid
295
- JOIN pg_namespace n ON n.oid = t.relnamespace
296
- CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord)
297
- JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum
298
- WHERE i.indisunique
299
- AND NOT i.indisprimary
300
- AND i.indpred IS NULL
301
- AND n.nspname = $1
302
- AND NOT t.relispartition
303
- GROUP BY t.relname, ic.relname
304
- ORDER BY t.relname, ic.relname
305
- `;
306
- /**
307
- * CHECK constraints, as the source text Postgres reproduces them from.
308
- *
309
- * `pg_get_constraintdef` output is normalized by the server — the parser in
310
- * {@link ./introspect-db-constraints.ts} reads that normalized form, not
311
- * whatever the author typed.
312
- */
313
- var CHECK_CONSTRAINTS_QUERY = `
314
- SELECT DISTINCT
315
- root.relname AS table_name,
316
- con.conname AS constraint_name,
317
- pg_get_constraintdef(con.oid) AS definition
318
- FROM pg_constraint con
319
- JOIN pg_namespace n ON n.oid = con.connamespace
320
- JOIN pg_class root ON root.oid = COALESCE(pg_partition_root(con.conrelid), con.conrelid)
321
- WHERE con.contype = 'c'
322
- AND n.nspname = $1
323
- ORDER BY root.relname, con.conname
324
- `;
325
- /**
326
- * `COMMENT ON TABLE` / `COMMENT ON COLUMN`, which is documentation the author
327
- * already wrote and which nothing downstream has ever read.
328
- */
329
- var COMMENTS_QUERY = `
330
- SELECT t.relname AS table_name,
331
- a.attname AS column_name,
332
- d.description AS comment
333
- FROM pg_description d
334
- JOIN pg_class t ON t.oid = d.objoid
335
- JOIN pg_namespace n ON n.oid = t.relnamespace
336
- LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = d.objsubid
337
- WHERE n.nspname = $1
338
- AND t.relkind IN ('r', 'p')
339
- AND (d.objsubid = 0 OR a.attname IS NOT NULL)
340
- ORDER BY t.relname, d.objsubid
341
- `;
342
- /**
343
- * Counts a table's rows, stopping once the answer can only be "more than
344
- * `limit`".
345
- *
346
- * Introspection asks this to tell a small reference table from a table that
347
- * merely looks like one (see `classifyTables`). `reltuples` would answer for
348
- * free but lies on a table that has never been analyzed — which is every table
349
- * in a database restored from a dump, i.e. exactly the case introspection meets
350
- * — and reports -1 there rather than an error, so the lie is silent.
351
- *
352
- * The subquery's LIMIT caps the work at `limit + 1` rows however large the
353
- * table is, so this stays cheap on a table with a billion rows.
354
- */
355
- async function countRowsUpTo(client, schema, table, limit) {
356
- const { rows } = await client.query(`SELECT count(*)::text AS count FROM (SELECT 1 FROM ${quoteRelation(schema, table)} LIMIT ${limit + 1}) probe`);
357
- return Number(rows[0]?.count ?? 0);
358
- }
359
- /**
360
- * Reads everything the generator needs, in one pass.
361
- *
362
- * `rowCounts` is deliberately absent here: it costs a query per table and only
363
- * a handful of tables can possibly need it. The caller fills it in for the
364
- * candidates `lookupCandidates()` names.
365
- */
366
- async function readSchemaMetadata(client, schema) {
367
- const tables = await client.query(TABLES_QUERY, [schema]);
368
- const columns = await client.query(COLUMNS_QUERY, [schema]);
369
- const enumValues = await client.query(ENUMS_QUERY, [schema]);
370
- const pks = await client.query(PRIMARY_KEYS_QUERY, [schema]);
371
- const fks = await client.query(FOREIGN_KEYS_QUERY, [schema]);
372
- const uniques = await client.query(UNIQUE_CONSTRAINTS_QUERY, [schema]);
373
- const checks = await client.query(CHECK_CONSTRAINTS_QUERY, [schema]);
374
- const comments = await client.query(COMMENTS_QUERY, [schema]);
375
- const known = new Set(tables.rows.map((t) => t.table_name));
376
- const scoped = (rows) => rows.filter((r) => known.has(r.table_name));
377
- return {
378
- schema,
379
- tables: tables.rows,
380
- columns: scoped(columns.rows),
381
- enumValues: enumValues.rows,
382
- pks: scoped(pks.rows),
383
- fks: scoped(fks.rows).filter((fk) => known.has(fk.foreign_table_name)),
384
- uniques: scoped(uniques.rows),
385
- checks: scoped(checks.rows),
386
- comments: scoped(comments.rows),
387
- rowCounts: {}
388
- };
389
- }
390
- //#endregion
391
81
  //#region src/schema/introspect-db-constraints.ts
392
82
  /** The length functions whose argument is the column being constrained. */
393
83
  var LENGTH_FUNCTIONS = /* @__PURE__ */ new Set([
@@ -796,7 +486,10 @@ async function main() {
796
486
  if (runDataInference) out(chalk.gray("Sampling database rows for data inference..."));
797
487
  const generatedFiles = [];
798
488
  const skippedFiles = [];
799
- const tablesToProcess = Array.from(tablesMap.entries()).filter(([tableName]) => !joinTables.has(tableName));
489
+ 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));
490
+ 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.`));
491
+ const notes = [];
492
+ const tablesToProcess = Array.from(tablesMap.entries()).filter(([tableName]) => !joinTables.has(tableName) && !compositeKeyed.has(tableName));
800
493
  const BATCH_SIZE = 10;
801
494
  for (let i = 0; i < tablesToProcess.length; i += BATCH_SIZE) {
802
495
  const batch = tablesToProcess.slice(i, i + BATCH_SIZE);
@@ -822,13 +515,21 @@ async function main() {
822
515
  metadata,
823
516
  classifications,
824
517
  checkFacts,
825
- builder
518
+ builder,
519
+ notes,
520
+ skippedTables: new Set(compositeKeyed.keys())
826
521
  });
827
522
  fs.writeFileSync(filePath, fileContent, "utf-8");
828
523
  generatedFiles.push(tableName);
829
524
  out(chalk.green(` ✓ ${filePath}`));
830
525
  }));
831
526
  }
527
+ if (notes.length > 0) {
528
+ outWarn("");
529
+ outWarn(chalk.yellow(`⚠ ${notes.length} column(s) will not round-trip exactly — \`rebase db push\` would change them:`));
530
+ for (const note of [...notes].sort()) outWarn(chalk.gray(` - ${note}`));
531
+ outWarn(chalk.gray(" Read these before the first push. Run `rebase db push --dry-run` to see the plan."));
532
+ }
832
533
  if (generatedFiles.length > 0) {
833
534
  const indexPath = path.join(outDir, "index.ts");
834
535
  if (fs.existsSync(indexPath) && !force) {
@@ -1 +1 @@
1
- {"version":3,"file":"introspect-db.js","names":[],"sources":["../../src/schema/introspect-db-project.ts","../../src/schema/introspect-db-queries.ts","../../src/schema/introspect-db-constraints.ts","../../src/schema/introspect-db.ts"],"sourcesContent":["/**\n * What the project being introspected into can actually import.\n *\n * The generator is pure — `introspect-db-logic.ts` reads no files — so the one\n * question it cannot answer for itself lives here: which `defineCollection`, if\n * any, will resolve from the directory the collections are written to.\n */\nimport fs from \"fs\";\nimport path from \"path\";\n\nimport { ADMIN_TYPES_PACKAGE, COMMON_PACKAGE, type CollectionBuilder } from \"./introspect-db-logic\";\n\n/** How far up to look before giving up, if no project root announces itself. */\nconst MAX_LEVELS = 8;\n\n/** Every dependency name a manifest declares, in any of the three fields. */\nfunction declaredDependencies(manifestPath: string): Set<string> {\n const names = new Set<string>();\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(manifestPath, \"utf-8\"));\n } catch {\n // A malformed or unreadable package.json is not this function's problem\n // to report — it answers \"can this import resolve\", and the answer is no.\n return names;\n }\n if (typeof parsed !== \"object\" || parsed === null) return names;\n const manifest = parsed as Record<string, unknown>;\n for (const field of [\"dependencies\", \"devDependencies\", \"peerDependencies\"]) {\n const block = manifest[field];\n if (typeof block === \"object\" && block !== null) {\n for (const name of Object.keys(block)) names.add(name);\n }\n }\n return names;\n}\n\n/**\n * Which `defineCollection` to generate against, for collections written to `outDir`.\n *\n * **The detection is the package manifests above the output directory**, unioned from\n * `outDir` up to and including the project root — the first ancestor holding a\n * `rebase.json`, or `MAX_LEVELS` up if there is none.\n *\n * That is the rule Node itself applies: a file in `config/collections` resolves a bare\n * specifier through `config/node_modules`, then `<project>/node_modules`, and so on up.\n * Reading the manifests along that same path answers the only question that matters —\n * *will this import resolve in the project I am writing into* — from the state on disk\n * at the moment of generation. The alternatives are all proxies for it: `rebase.json`'s\n * `apps` block says a CMS scaffold declared an admin app, and a `frontend/` directory\n * says one was scaffolded, but neither is what the compiler consults, and either can be\n * true of a project whose `config` package does not depend on `@rebasepro/cms-types`.\n *\n * Ambiguity resolves towards the admin panel: a project that declares both packages has\n * a panel, and `@rebasepro/cms-types` is the flavour that keeps the `admin` block.\n */\nexport function detectCollectionBuilder(outDir: string): CollectionBuilder {\n let dir = path.resolve(outDir);\n const declared = new Set<string>();\n\n for (let level = 0; level < MAX_LEVELS; level++) {\n const manifest = path.join(dir, \"package.json\");\n if (fs.existsSync(manifest)) {\n for (const name of declaredDependencies(manifest)) declared.add(name);\n }\n // The project root, and the last level worth reading: anything above it\n // belongs to whatever the project happens to be checked out inside.\n if (fs.existsSync(path.join(dir, \"rebase.json\"))) break;\n\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n\n if (declared.has(ADMIN_TYPES_PACKAGE)) return \"admin-types\";\n if (declared.has(COMMON_PACKAGE)) return \"common\";\n return \"annotation\";\n}\n","/**\n * The catalog queries introspection runs, and the shape they produce.\n *\n * These live apart from {@link ./introspect-db.ts} (the CLI entry point) on\n * purpose: the fixture-capture script and the live e2e read a database through\n * this module too, so what the tests see is what the CLI sees. A query that\n * only exists inside the CLI's `main()` can only be tested by running the CLI.\n *\n * No side effects beyond `SELECT`. Introspection reads a database it does not\n * own — it must never `ANALYZE`, create a temp table, or otherwise write.\n */\nimport type {\n TableRow,\n TableColumn,\n EnumValue,\n PrimaryKeyRow,\n ForeignKeyRow,\n UniqueConstraintRow,\n CheckConstraintRow,\n CommentRow,\n SchemaMetadata\n} from \"./introspect-db-logic\";\n\n/** The subset of `pg.Client` this module needs, so tests can pass a fake. */\nexport interface QueryableClient {\n query<R = Record<string, unknown>>(text: string, values?: unknown[]): Promise<{ rows: R[] }>;\n}\n\n/**\n * A Postgres identifier, quoted so that whatever is inside it stays inside it.\n *\n * Introspection reads table and schema names out of `pg_class` and puts them\n * straight back into SQL, and wrapping a name in double quotes is not the same\n * as escaping it: a table named `x\" ; DROP TABLE users; --` closes the quote\n * and then the statement. Postgres's own escape for a quote inside a quoted\n * identifier is to double it, which is what this does.\n *\n * \"The catalogue is trusted\" is true of your own database, and is exactly the\n * assumption this tool cannot make. Introspection exists to be pointed at\n * databases somebody else built, and it runs with the privileges of whoever\n * ran it — which is usually a superuser, because that is who has a connection\n * string to a database they are adopting.\n */\nexport function quoteIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n}\n\n/** `\"schema\".\"table\"`, both halves quoted. */\nexport function quoteRelation(schema: string, table: string): string {\n return `${quoteIdentifier(schema)}.${quoteIdentifier(table)}`;\n}\n\n/**\n * Can this table's name be the name of the file describing it?\n *\n * Introspection writes `<collectionsDir>/<tableName>.ts`, and the table name\n * came from a database this tool did not create. Postgres will hold a table\n * called `../../../etc/cron.d/x`, and `path.join` resolves it — so without this\n * the generator writes a file wherever the name points, as whoever ran the\n * command.\n *\n * Deliberately narrow, and deliberately not a blocklist of `..` and `/`: the\n * question is \"is this a plain file name?\", and every answer that is not\n * obviously yes is a table better written by hand. NUL and the Windows\n * separator are in scope because a collections directory is checked out on\n * whatever machine the developer has.\n */\nexport function isUsableFileName(name: string): boolean {\n if (name.length === 0 || name.length > 200) return false;\n if (name === \".\" || name === \"..\") return false;\n // Path separators (both platforms'), the Windows drive separator, and any\n // control character — a NUL truncates the path at the OS boundary, so a\n // name that reads as harmless in a log can be something else on disk.\n // eslint-disable-next-line no-control-regex\n if (/[/\\\\:\\u0000-\\u001f]/.test(name)) return false;\n // A leading dot makes a hidden file, and a trailing one is invalid on\n // Windows; neither is a table anyone means to generate.\n return !name.startsWith(\".\") && !name.endsWith(\".\");\n}\n\n/**\n * Base tables, excluding partitions.\n *\n * `relispartition` is the reason this reads `pg_class` rather than\n * `information_schema.tables`, which reports every partition as a base table of\n * its own. Pagila partitions `payment` by month; introspected through\n * information_schema it yields `payment` plus 26 near-identical\n * `payment_p2022_*` collections, each with its own nav entry.\n *\n * `relkind = 'p'` (the partitioned parent) is included and `'r'` partitions are\n * dropped, which is the right way round: the parent is the queryable table.\n */\nexport const TABLES_QUERY = `\n SELECT c.relname AS table_name,\n c.relkind = 'p' AS is_partitioned\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = $1\n AND c.relkind IN ('r', 'p')\n AND NOT c.relispartition\n AND c.relname NOT LIKE 'drizzle_%'\n AND c.relname NOT LIKE 'rebase_%'\n ORDER BY c.relname\n`;\n\n/**\n * Columns, with the catalog facts that say a column is not the user's to edit.\n *\n * `is_generated`/`is_identity` are read for that reason: a generated column\n * rejects any write, so a form that offers it is offering a field that always\n * errors. `character_maximum_length` is the declared `varchar(n)` bound —\n * already enforced by the database, and free to surface as validation.\n */\nexport 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.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`;\n\nexport 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`;\n\n/**\n * Primary key columns, in key order.\n *\n * `ORDER BY k.ord` matters for composite keys: the position of a column inside\n * the key is what tells a two-column PK made of two foreign keys apart from an\n * ordinary composite key, and `= ANY(i.indkey)` (the shape this replaced)\n * returns catalog order instead.\n */\nexport const PRIMARY_KEYS_QUERY = `\n SELECT t.relname AS table_name,\n a.attname AS column_name\n FROM pg_index i\n JOIN pg_class t ON t.oid = i.indrelid\n JOIN pg_namespace n ON n.oid = t.relnamespace\n CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord)\n JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum\n WHERE i.indisprimary AND n.nspname = $1\n ORDER BY t.relname, k.ord\n`;\n\n/**\n * Foreign keys, one row per referencing column, with the delete rule.\n *\n * Read from `pg_constraint` rather than through\n * `information_schema.constraint_column_usage`, which does not preserve the\n * pairing on a composite foreign key: it reports the cross product of the\n * constraint's columns, so a two-column FK comes back as four rows, two of them\n * pairing the wrong columns. `unnest(...) WITH ORDINALITY` on both sides joined\n * on the ordinal keeps each referencing column with the column it references.\n *\n * `confdeltype` is carried because `ON DELETE CASCADE` is the schema author\n * saying, in the database, that the child cannot outlive the parent — the one\n * unambiguous declaration of ownership a schema contains.\n *\n * Constraints declared on a *partition* are attributed to the partition root,\n * because that is the table this run generates a collection for. Pagila declares\n * `payment`'s three foreign keys on each monthly partition and none on the\n * parent, so reading `pg_constraint` at face value gives the `payment`\n * collection no relations at all. `pick = 1` then keeps one row per logical key,\n * preferring the root's own constraint when it has one, so a schema that\n * declares the key on the parent *and* inherits it onto 26 partitions does not\n * yield 27 copies of the same relation.\n */\nexport const FOREIGN_KEYS_QUERY = `\n WITH fk AS (\n SELECT con.oid,\n con.conname,\n con.conrelid,\n con.confrelid,\n con.conkey,\n con.confkey,\n con.confdeltype,\n COALESCE(pg_partition_root(con.conrelid), con.conrelid) AS root_oid,\n row_number() OVER (\n PARTITION BY COALESCE(pg_partition_root(con.conrelid), con.conrelid),\n con.confrelid, con.conkey, con.confkey\n ORDER BY (con.conrelid = COALESCE(pg_partition_root(con.conrelid), con.conrelid)) DESC,\n con.oid\n ) AS pick\n FROM pg_constraint con\n JOIN pg_namespace n ON n.oid = con.connamespace\n WHERE con.contype = 'f' AND n.nspname = $1\n )\n SELECT root.relname AS table_name,\n sa.attname AS column_name,\n tgt.relname AS foreign_table_name,\n ta.attname AS foreign_column_name,\n fk.conname AS constraint_name,\n s.ord::int AS ordinal,\n CASE fk.confdeltype\n WHEN 'a' THEN 'NO ACTION'\n WHEN 'r' THEN 'RESTRICT'\n WHEN 'c' THEN 'CASCADE'\n WHEN 'n' THEN 'SET NULL'\n WHEN 'd' THEN 'SET DEFAULT'\n END AS delete_rule\n FROM fk\n JOIN pg_class root ON root.oid = fk.root_oid\n JOIN pg_class tgt ON tgt.oid = fk.confrelid\n CROSS JOIN LATERAL unnest(fk.conkey) WITH ORDINALITY AS s(attnum, ord)\n JOIN pg_attribute sa ON sa.attrelid = fk.conrelid AND sa.attnum = s.attnum\n CROSS JOIN LATERAL unnest(fk.confkey) WITH ORDINALITY AS f(attnum, ord)\n JOIN pg_attribute ta ON ta.attrelid = fk.confrelid AND ta.attnum = f.attnum\n WHERE fk.pick = 1 AND s.ord = f.ord\n ORDER BY root.relname, fk.conname, s.ord\n`;\n\n/**\n * Unique constraints and unique indexes, as ordered column lists.\n *\n * Indexes rather than constraints alone, because `CREATE UNIQUE INDEX` and\n * `ADD CONSTRAINT ... UNIQUE` produce the same guarantee and schemas use both.\n * Partial indexes (`indpred IS NOT NULL`) are excluded: they promise uniqueness\n * only over the rows matching their predicate, which is not the promise a\n * `validation: { unique: true }` field makes.\n */\nexport const UNIQUE_CONSTRAINTS_QUERY = `\n SELECT t.relname AS table_name,\n ic.relname AS constraint_name,\n -- ::text, because the driver has no parser for an array of \\`name\\`\n -- and hands back the raw \\`{a,b}\\` literal as a string. Every consumer\n -- here indexes and compares it as an array, and a string of that\n -- shape fails those silently rather than loudly.\n array_agg(a.attname::text ORDER BY k.ord) AS column_names\n FROM pg_index i\n JOIN pg_class t ON t.oid = i.indrelid\n JOIN pg_class ic ON ic.oid = i.indexrelid\n JOIN pg_namespace n ON n.oid = t.relnamespace\n CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord)\n JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum\n WHERE i.indisunique\n AND NOT i.indisprimary\n AND i.indpred IS NULL\n AND n.nspname = $1\n AND NOT t.relispartition\n GROUP BY t.relname, ic.relname\n ORDER BY t.relname, ic.relname\n`;\n\n/**\n * CHECK constraints, as the source text Postgres reproduces them from.\n *\n * `pg_get_constraintdef` output is normalized by the server — the parser in\n * {@link ./introspect-db-constraints.ts} reads that normalized form, not\n * whatever the author typed.\n */\nexport const CHECK_CONSTRAINTS_QUERY = `\n SELECT DISTINCT\n root.relname AS table_name,\n con.conname AS constraint_name,\n pg_get_constraintdef(con.oid) AS definition\n FROM pg_constraint con\n JOIN pg_namespace n ON n.oid = con.connamespace\n JOIN pg_class root ON root.oid = COALESCE(pg_partition_root(con.conrelid), con.conrelid)\n WHERE con.contype = 'c'\n AND n.nspname = $1\n ORDER BY root.relname, con.conname\n`;\n\n/**\n * `COMMENT ON TABLE` / `COMMENT ON COLUMN`, which is documentation the author\n * already wrote and which nothing downstream has ever read.\n */\nexport const COMMENTS_QUERY = `\n SELECT t.relname AS table_name,\n a.attname AS column_name,\n d.description AS comment\n FROM pg_description d\n JOIN pg_class t ON t.oid = d.objoid\n JOIN pg_namespace n ON n.oid = t.relnamespace\n LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = d.objsubid\n WHERE n.nspname = $1\n AND t.relkind IN ('r', 'p')\n AND (d.objsubid = 0 OR a.attname IS NOT NULL)\n ORDER BY t.relname, d.objsubid\n`;\n\n/**\n * Counts a table's rows, stopping once the answer can only be \"more than\n * `limit`\".\n *\n * Introspection asks this to tell a small reference table from a table that\n * merely looks like one (see `classifyTables`). `reltuples` would answer for\n * free but lies on a table that has never been analyzed — which is every table\n * in a database restored from a dump, i.e. exactly the case introspection meets\n * — and reports -1 there rather than an error, so the lie is silent.\n *\n * The subquery's LIMIT caps the work at `limit + 1` rows however large the\n * table is, so this stays cheap on a table with a billion rows.\n */\nexport async function countRowsUpTo(\n client: QueryableClient,\n schema: string,\n table: string,\n limit: number\n): Promise<number> {\n const { rows } = await client.query<{ count: string }>(\n `SELECT count(*)::text AS count FROM (SELECT 1 FROM ${quoteRelation(schema, table)} LIMIT ${limit + 1}) probe`\n );\n return Number(rows[0]?.count ?? 0);\n}\n\n/**\n * Reads everything the generator needs, in one pass.\n *\n * `rowCounts` is deliberately absent here: it costs a query per table and only\n * a handful of tables can possibly need it. The caller fills it in for the\n * candidates `lookupCandidates()` names.\n */\nexport async function readSchemaMetadata(\n client: QueryableClient,\n schema: string\n): Promise<SchemaMetadata> {\n // Sequential, not `Promise.all`. A `pg.Client` is a single connection with\n // one protocol stream: concurrent `query()` calls on one are queued and\n // deprecated (removed in pg@9), so the parallel version buys nothing and\n // warns while doing it.\n const tables = await client.query<TableRow>(TABLES_QUERY, [schema]);\n const columns = await client.query<TableColumn>(COLUMNS_QUERY, [schema]);\n const enumValues = await client.query<EnumValue>(ENUMS_QUERY, [schema]);\n const pks = await client.query<PrimaryKeyRow>(PRIMARY_KEYS_QUERY, [schema]);\n const fks = await client.query<ForeignKeyRow>(FOREIGN_KEYS_QUERY, [schema]);\n const uniques = await client.query<UniqueConstraintRow>(UNIQUE_CONSTRAINTS_QUERY, [schema]);\n const checks = await client.query<CheckConstraintRow>(CHECK_CONSTRAINTS_QUERY, [schema]);\n const comments = await client.query<CommentRow>(COMMENTS_QUERY, [schema]);\n\n // A column list scoped to the schema still names tables this run excludes —\n // views, partitions, the drizzle bookkeeping tables. Narrow every row set to\n // the tables actually being introspected so downstream code never has to\n // ask whether a table it found in `columns` really exists.\n const known = new Set(tables.rows.map((t) => t.table_name));\n const scoped = <T extends { table_name: string }>(rows: T[]) => rows.filter((r) => known.has(r.table_name));\n\n return {\n schema,\n tables: tables.rows,\n columns: scoped(columns.rows),\n enumValues: enumValues.rows,\n pks: scoped(pks.rows),\n // A foreign key pointing *out* of the introspected set (into another\n // schema, or at a view) cannot be turned into a relation: there is no\n // collection on the other end to link to.\n fks: scoped(fks.rows).filter((fk) => known.has(fk.foreign_table_name)),\n uniques: scoped(uniques.rows),\n checks: scoped(checks.rows),\n comments: scoped(comments.rows),\n rowCounts: {}\n };\n}\n","/**\n * Reading validation rules out of CHECK constraints.\n *\n * A CHECK constraint is the schema author stating a rule the database already\n * enforces. Introspection has never read them, so a generated form let the user\n * type a value the database was always going to reject — the rule was written\n * down, in the schema, and the UI asked anyway.\n *\n * Everything here parses the *normalized* text `pg_get_constraintdef` produces,\n * not what the author typed: Postgres re-renders the expression from its parse\n * tree, so `CHECK (price > 0)` on a `numeric` column always comes back as\n * `CHECK ((price > (0)::numeric))`. That normalization is what makes a\n * string-level parser tractable — the input is generated, and the shapes are\n * few.\n *\n * Constraints this cannot read are skipped in full. A partially-understood\n * constraint is worse than an unread one: it would produce validation that\n * *narrows* differently from the database, so a value the UI accepts still\n * fails on write, or — worse — a value the database allows is refused in the\n * form with no way to see why.\n *\n * Pure module: no I/O, no logging.\n */\nimport type { CheckConstraintRow } from \"./introspect-db-logic\";\n\n/** What a table's CHECK constraints say about one column. */\nexport interface ColumnCheckFacts {\n /** Allowed values, from `IN (…)` / `= ANY (ARRAY[…])` / `= 'literal'`. */\n enumValues?: string[];\n /** `x >= n` */\n min?: number;\n /** `x <= n` */\n max?: number;\n /** `x > n` */\n moreThan?: number;\n /** `x < n` */\n lessThan?: number;\n /** `length(x) >= n` */\n lengthMin?: number;\n /** `length(x) <= n` */\n lengthMax?: number;\n}\n\n/** Per-table, per-column facts. */\nexport type CheckFactsByTable = Map<string, Map<string, ColumnCheckFacts>>;\n\n/** The length functions whose argument is the column being constrained. */\nconst LENGTH_FUNCTIONS = new Set([\"length\", \"char_length\", \"character_length\", \"octet_length\"]);\n\n/**\n * Splits on a separator that appears at paren depth 0 and outside string\n * literals.\n *\n * Depth tracking is the whole job: `ARRAY['a', 'b']` contains a comma that must\n * not split the enclosing argument list, and `'it''s'` contains a quote that\n * must not end the literal.\n */\nfunction splitTopLevel(input: string, separator: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let inString = false;\n let current = \"\";\n\n for (let i = 0; i < input.length; i++) {\n const ch = input[i];\n\n if (inString) {\n current += ch;\n if (ch === \"'\") {\n // '' inside a literal is an escaped quote, not the end of it.\n if (input[i + 1] === \"'\") {\n current += input[++i];\n } else {\n inString = false;\n }\n }\n continue;\n }\n\n if (ch === \"'\") {\n inString = true;\n current += ch;\n continue;\n }\n if (ch === \"(\" || ch === \"[\") depth++;\n if (ch === \")\" || ch === \"]\") depth--;\n\n if (depth === 0 && input.startsWith(separator, i)) {\n // A word separator must not match inside an identifier: \"AND\" is a\n // separator in `a AND b` but not in `brand = 1`.\n const before = input[i - 1];\n const after = input[i + separator.length];\n const wordish = /[A-Za-z]/.test(separator[0]);\n const boundedOk = !wordish || ((before === undefined || !/[A-Za-z0-9_]/.test(before)) &&\n (after === undefined || !/[A-Za-z0-9_]/.test(after)));\n if (boundedOk) {\n parts.push(current);\n current = \"\";\n i += separator.length - 1;\n continue;\n }\n }\n\n current += ch;\n }\n\n parts.push(current);\n return parts.map((p) => p.trim()).filter((p) => p.length > 0);\n}\n\n/** Removes one layer of wrapping parentheses, repeatedly, when balanced. */\nexport function unwrapParens(input: string): string {\n let s = input.trim();\n while (s.startsWith(\"(\") && s.endsWith(\")\")) {\n let depth = 0;\n let balanced = true;\n let inString = false;\n for (let i = 0; i < s.length; i++) {\n const ch = s[i];\n if (inString) {\n if (ch === \"'\") {\n if (s[i + 1] === \"'\") i++;\n else inString = false;\n }\n continue;\n }\n if (ch === \"'\") { inString = true; continue; }\n if (ch === \"(\") depth++;\n else if (ch === \")\") {\n depth--;\n // The opening paren closed before the end, so the outer pair is\n // not a wrapper: `(a) AND (b)`.\n if (depth === 0 && i < s.length - 1) { balanced = false; break; }\n }\n }\n if (!balanced) break;\n s = s.slice(1, -1).trim();\n }\n return s;\n}\n\n/** Drops trailing `::type` casts, including array and quoted forms. */\nexport function stripCasts(input: string): string {\n let s = unwrapParens(input);\n let previous: string;\n do {\n previous = s;\n s = unwrapParens(\n s.replace(/::\\s*\"?[A-Za-z_][A-Za-z0-9_ ]*\"?(\\s*\\(\\s*\\d+\\s*(,\\s*\\d+\\s*)?\\))?(\\s*\\[\\s*\\])*\\s*$/, \"\").trim()\n );\n } while (s !== previous);\n return s;\n}\n\n/** A bare, unquoted column reference — anything else is an expression. */\nfunction asColumnName(input: string): string | null {\n const s = stripCasts(input);\n if (/^[a-z_][a-z0-9_$]*$/i.test(s)) return s;\n // A quoted identifier keeps its case: \"userId\".\n const quoted = s.match(/^\"([^\"]+)\"$/);\n return quoted ? quoted[1] : null;\n}\n\n/** `length(col)` and friends → the column they measure. */\nfunction asLengthOfColumn(input: string): string | null {\n const s = stripCasts(input);\n const match = s.match(/^([a-z_]+)\\s*\\((.*)\\)$/is);\n if (!match || !LENGTH_FUNCTIONS.has(match[1].toLowerCase())) return null;\n return asColumnName(match[2]);\n}\n\n/** A numeric literal, after casts are removed. Rejects anything else. */\nfunction asNumber(input: string): number | null {\n const s = stripCasts(input).replace(/^'(.*)'$/s, \"$1\");\n if (!/^[+-]?(\\d+\\.?\\d*|\\.\\d+)$/.test(s)) return null;\n const n = Number(s);\n return Number.isFinite(n) ? n : null;\n}\n\n/** A single-quoted string literal, with `''` unescaped. */\nfunction asStringLiteral(input: string): string | null {\n const s = stripCasts(input);\n if (!s.startsWith(\"'\") || !s.endsWith(\"'\") || s.length < 2) return null;\n const body = s.slice(1, -1);\n // Any unescaped quote inside means this was not one literal.\n if (/(^|[^'])'($|[^'])/.test(body)) return null;\n return body.replace(/''/g, \"'\");\n}\n\n/** The element list of `ARRAY[…]`, or of a parenthesised `IN (…)` list. */\nfunction asValueList(input: string): string[] | null {\n const s = stripCasts(input);\n const arrayMatch = s.match(/^ARRAY\\s*\\[(.*)\\]$/is);\n const body = arrayMatch ? arrayMatch[1] : (s.startsWith(\"(\") && s.endsWith(\")\") ? s.slice(1, -1) : null);\n if (body === null) return null;\n if (body.trim() === \"\") return null;\n\n const values: string[] = [];\n for (const element of splitTopLevel(body, \",\")) {\n const literal = asStringLiteral(element);\n if (literal !== null) {\n values.push(literal);\n continue;\n }\n const numeric = asNumber(element);\n if (numeric !== null) {\n values.push(String(numeric));\n continue;\n }\n return null; // A non-literal element means this is not an enumeration.\n }\n return values;\n}\n\n/** One understood comparison, already resolved to the column it constrains. */\ninterface CheckTerm {\n column: string;\n apply: (facts: ColumnCheckFacts) => void;\n}\n\n/**\n * Parses one conjunct. Returns null when the shape is not one of the few this\n * understands, which is the signal to abandon the whole constraint.\n */\nfunction parseTerm(rawTerm: string): CheckTerm | null {\n const term = unwrapParens(rawTerm);\n\n // ── Membership: `x = ANY (ARRAY[…])`, `x IN (…)` ──────────────────\n const anyMatch = term.match(/^(.*?)\\s*=\\s*ANY\\s*(\\(.*\\))$/is);\n const inMatch = anyMatch ? null : term.match(/^(.*?)\\s+IN\\s*(\\(.*\\))$/is);\n const membership = anyMatch ?? inMatch;\n if (membership) {\n const column = asColumnName(membership[1]);\n const values = asValueList(membership[2]);\n if (!column || !values || values.length === 0) return null;\n return {\n column,\n apply: (facts) => {\n // Two membership checks on one column mean both must hold.\n facts.enumValues = facts.enumValues\n ? facts.enumValues.filter((v) => values.includes(v))\n : values;\n }\n };\n }\n\n // ── Comparison: `x >= n`, `length(x) <= n`, `x = 'literal'` ───────\n // Longest operators first so `>=` is not read as `>`.\n for (const operator of [\">=\", \"<=\", \"<>\", \"!=\", \"=\", \">\", \"<\"] as const) {\n const parts = splitTopLevel(term, operator);\n if (parts.length !== 2) continue;\n const [rawLeft, rawRight] = parts;\n\n const lengthColumn = asLengthOfColumn(rawLeft);\n if (lengthColumn) {\n const bound = asNumber(rawRight);\n if (bound === null) return null;\n switch (operator) {\n case \">=\": return { column: lengthColumn, apply: (f) => { f.lengthMin = Math.max(f.lengthMin ?? bound, bound); } };\n case \">\": return { column: lengthColumn, apply: (f) => { f.lengthMin = Math.max(f.lengthMin ?? bound + 1, bound + 1); } };\n case \"<=\": return { column: lengthColumn, apply: (f) => { f.lengthMax = Math.min(f.lengthMax ?? bound, bound); } };\n case \"<\": return { column: lengthColumn, apply: (f) => { f.lengthMax = Math.min(f.lengthMax ?? bound - 1, bound - 1); } };\n case \"=\": return { column: lengthColumn, apply: (f) => { f.lengthMin = bound; f.lengthMax = bound; } };\n default: return null;\n }\n }\n\n const column = asColumnName(rawLeft);\n if (!column) continue;\n\n if (operator === \"=\") {\n const literal = asStringLiteral(rawRight);\n if (literal !== null) {\n return {\n column,\n apply: (facts) => {\n facts.enumValues = facts.enumValues\n ? facts.enumValues.filter((v) => v === literal)\n : [literal];\n }\n };\n }\n // `x = 5` pins a number. Expressed as both bounds rather than as a\n // one-value enum, which for a number would render as a dropdown.\n const pinned = asNumber(rawRight);\n if (pinned === null) return null;\n return { column, apply: (f) => { f.min = pinned; f.max = pinned; } };\n }\n\n const bound = asNumber(rawRight);\n if (bound === null) return null;\n switch (operator) {\n case \">=\": return { column, apply: (f) => { f.min = Math.max(f.min ?? bound, bound); } };\n case \">\": return { column, apply: (f) => { f.moreThan = Math.max(f.moreThan ?? bound, bound); } };\n case \"<=\": return { column, apply: (f) => { f.max = Math.min(f.max ?? bound, bound); } };\n case \"<\": return { column, apply: (f) => { f.lessThan = Math.min(f.lessThan ?? bound, bound); } };\n default: return null; // `<>` / `!=` exclude rather than bound.\n }\n }\n\n return null;\n}\n\n/**\n * Reads one constraint definition into per-column facts.\n *\n * Returns an empty map for anything not understood — including a constraint\n * that is understood but spans two columns (`start_date < end_date`), which no\n * per-property validation rule can express.\n */\nexport function parseCheckDefinition(definition: string): Map<string, ColumnCheckFacts> {\n const result = new Map<string, ColumnCheckFacts>();\n\n const body = definition\n .trim()\n .replace(/\\s+NOT\\s+VALID\\s*$/i, \"\")\n .replace(/^CHECK\\s*/i, \"\")\n .trim();\n if (body === definition.trim()) return result; // Not a CHECK definition.\n\n const expression = unwrapParens(body);\n if (!expression) return result;\n\n // Only conjunctions. A disjunction (`a OR b`) does not narrow a column: each\n // branch may allow what the other forbids, so no single bound follows.\n if (splitTopLevel(expression, \" OR \").length > 1) return result;\n\n const terms = splitTopLevel(expression, \" AND \");\n const parsed: CheckTerm[] = [];\n for (const term of terms) {\n const one = parseTerm(term);\n if (!one) return result; // One unreadable conjunct voids the constraint.\n parsed.push(one);\n }\n\n // A CHECK naming two columns constrains their *relationship*; keeping the\n // half that mentions one column would assert something the database does not.\n const columns = new Set(parsed.map((t) => t.column));\n if (columns.size !== 1) return result;\n\n const facts: ColumnCheckFacts = {};\n for (const term of parsed) term.apply(facts);\n if (Object.keys(facts).length === 0) return result;\n\n result.set(parsed[0].column, facts);\n return result;\n}\n\n/** Merges every readable CHECK in the schema into per-table, per-column facts. */\nexport function parseCheckConstraints(rows: CheckConstraintRow[]): CheckFactsByTable {\n const byTable: CheckFactsByTable = new Map();\n\n for (const row of rows) {\n const parsed = parseCheckDefinition(row.definition);\n if (parsed.size === 0) continue;\n\n let table = byTable.get(row.table_name);\n if (!table) {\n table = new Map();\n byTable.set(row.table_name, table);\n }\n\n for (const [column, facts] of parsed) {\n const existing = table.get(column);\n if (!existing) {\n table.set(column, facts);\n continue;\n }\n // Separate constraints on the same column all hold at once.\n if (facts.enumValues) {\n existing.enumValues = existing.enumValues\n ? existing.enumValues.filter((v) => facts.enumValues!.includes(v))\n : facts.enumValues;\n }\n if (facts.min !== undefined) existing.min = Math.max(existing.min ?? facts.min, facts.min);\n if (facts.max !== undefined) existing.max = Math.min(existing.max ?? facts.max, facts.max);\n if (facts.moreThan !== undefined) existing.moreThan = Math.max(existing.moreThan ?? facts.moreThan, facts.moreThan);\n if (facts.lessThan !== undefined) existing.lessThan = Math.min(existing.lessThan ?? facts.lessThan, facts.lessThan);\n if (facts.lengthMin !== undefined) existing.lengthMin = Math.max(existing.lengthMin ?? facts.lengthMin, facts.lengthMin);\n if (facts.lengthMax !== undefined) existing.lengthMax = Math.min(existing.lengthMax ?? facts.lengthMax, facts.lengthMax);\n }\n }\n\n return byTable;\n}\n","import chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport pg from \"pg\";\nimport arg from \"arg\";\nimport * as dotenv from \"dotenv\";\nimport readline from \"readline\";\n\nimport {\n buildTablesMap,\n buildEnumMap,\n generateCollectionFile,\n generateIndexContent,\n mergeIndexContent,\n safeHostFromUrl\n} from \"./introspect-db-logic\";\nimport { detectCollectionBuilder } from \"./introspect-db-project\";\nimport { countRowsUpTo, isUsableFileName, quoteRelation, readSchemaMetadata } from \"./introspect-db-queries\";\nimport { classifyTables, lookupCandidates, LOOKUP_MAX_ROWS } from \"./introspect-db-structure\";\nimport { parseCheckConstraints } from \"./introspect-db-constraints\";\nimport { out, outWarn, outError } from \"../cli-output\";\n\nasync function main() {\n const args = arg(\n {\n \"--output\": String,\n \"--collections\": String,\n \"--force\": Boolean,\n \"--schema\": String,\n \"--data-inference\": Boolean,\n \"--no-data-inference\": Boolean,\n \"-o\": \"--output\",\n \"-c\": \"--collections\",\n \"-f\": \"--force\"\n },\n { permissive: true }\n );\n\n const cwd = process.cwd();\n const isBackendDir = path.basename(cwd) === \"backend\";\n const defaultOutDir = isBackendDir\n ? path.resolve(cwd, \"..\", \"config\", \"collections\")\n : path.resolve(cwd, \"config\", \"collections\");\n\n const outDir = args[\"--output\"] || args[\"--collections\"] || defaultOutDir;\n const force = args[\"--force\"] || false;\n const pgSchema = args[\"--schema\"] || \"public\";\n\n if (!fs.existsSync(outDir)) {\n fs.mkdirSync(outDir, { recursive: true });\n }\n\n // Load env\n const envPaths = [\n process.env.DOTENV_CONFIG_PATH,\n path.resolve(process.cwd(), \".env\"),\n path.resolve(process.cwd(), \"../.env\"),\n path.resolve(process.cwd(), \"../../.env\")\n ].filter(Boolean) as string[];\n\n for (const p of envPaths) {\n if (fs.existsSync(p)) {\n dotenv.config({ path: p, quiet: true });\n break;\n }\n }\n\n const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;\n if (!databaseUrl) {\n outError(chalk.red(\"✗ DATABASE_URL is not set. Make sure your .env file is configured.\"));\n process.exit(1);\n }\n\n const client = new pg.Client({ connectionString: databaseUrl });\n\n try {\n await client.connect();\n } catch (err) {\n outError(chalk.red(`✗ Failed to connect to database: ${err instanceof Error ? err.message : String(err)}`));\n outError(chalk.gray(\" Check your DATABASE_URL and ensure the database is reachable.\"));\n process.exit(1);\n }\n\n // Log the host portion safely — handle URLs without \"@\"\n const hostPart = safeHostFromUrl(databaseUrl);\n out(chalk.gray(`Connected to database: ${hostPart}`));\n out(chalk.gray(`Introspecting schema '${pgSchema}'...`));\n\n try {\n const metadata = await readSchemaMetadata(client, pgSchema);\n const enumMap = buildEnumMap(metadata.enumValues);\n const tablesMap = buildTablesMap(metadata.tables, metadata.columns, metadata.pks, metadata.fks);\n const fks = metadata.fks;\n\n // Only tables that could structurally be a code list are counted, and\n // each count stops at the threshold — see `countRowsUpTo`. Introspection\n // runs against a database it does not own, so \"cheap on a table of any\n // size\" is a requirement, not an optimization.\n for (const table of lookupCandidates(metadata, tablesMap)) {\n try {\n metadata.rowCounts[table] = await countRowsUpTo(client, pgSchema, table, LOOKUP_MAX_ROWS);\n } catch (err) {\n // A table this run cannot read is simply not classified as a code\n // list; everything else about it still generates.\n out(chalk.gray(` (skipped row count for ${table}: ${err instanceof Error ? err.message : String(err)})`));\n }\n }\n\n const classifications = classifyTables(metadata, tablesMap);\n const checkFacts = parseCheckConstraints(metadata.checks);\n\n // Which builder the generated files may import — read from the manifests\n // above `outDir`, because a project without `@rebasepro/cms-types` cannot\n // resolve that import and has no `admin` block to write into either.\n const builder = detectCollectionBuilder(outDir);\n if (builder === \"annotation\") {\n outWarn(chalk.yellow(\n \"⚠ Neither @rebasepro/cms-types nor @rebasepro/common is declared above \" +\n `${outDir}.`\n ));\n outWarn(chalk.gray(\n \" Generating plain type annotations, which widen the property keys to `string`: \" +\n \"`propertiesOrder` and friends will not be checked. Add @rebasepro/common to the \" +\n \"config package to turn that checking on.\"\n ));\n }\n const joinTables = new Set(\n Array.from(classifications.values())\n .filter((c) => c.role === \"junction\")\n .map((c) => c.table)\n );\n\n const roleCount = (role: string) =>\n Array.from(classifications.values()).filter((c) => c.role === role).length;\n\n out(chalk.blue(`Found ${tablesMap.size} tables.`));\n out(chalk.gray(\n ` ${roleCount(\"entity\")} entities, ${joinTables.size} join tables (folded into relations), ` +\n `${roleCount(\"lookup\")} code lists, ${roleCount(\"owned-child\")} owned by another table (hidden from navigation).`\n ));\n\n let runDataInference = false;\n if (args[\"--no-data-inference\"]) {\n runDataInference = false;\n } else if (args[\"--data-inference\"] !== undefined) {\n runDataInference = args[\"--data-inference\"];\n } else if (!process.stdin.isTTY) {\n // No terminal to answer the question below (scaffolding scripts, CI,\n // `rebase init --introspect`) — asking would hang forever.\n out(chalk.gray(\"Skipping data inference (non-interactive run; pass --data-inference to enable).\"));\n } else {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n const answer = await new Promise<string>((resolve) => rl.question(chalk.yellow(\"? Do you want to run comprehensive data inference on sampled rows to auto-detect types, formats, constraints, and UI configurations? (y/N) \"), resolve));\n runDataInference = answer.trim().toLowerCase() === \"y\";\n rl.close();\n }\n\n if (runDataInference) {\n out(chalk.gray(\"Sampling database rows for data inference...\"));\n }\n\n // Generate Collections\n const generatedFiles: string[] = [];\n const skippedFiles: string[] = [];\n\n const tablesToProcess = Array.from(tablesMap.entries()).filter(([tableName]) => !joinTables.has(tableName));\n\n const BATCH_SIZE = 10;\n for (let i = 0; i < tablesToProcess.length; i += BATCH_SIZE) {\n const batch = tablesToProcess.slice(i, i + BATCH_SIZE);\n\n await Promise.all(batch.map(async ([tableName, meta]) => {\n // ── The name has to be usable as a filename ────────────────\n //\n // `tableName` came out of `pg_class` in a database this tool\n // did not create — adopting somebody else's database is the\n // whole point of introspection — and it is about to be joined\n // onto a path. Postgres will happily hold a table called\n // `../../../etc/cron.d/x`, and `path.join` resolves it: the\n // generator would write a TypeScript file wherever that\n // pointed, as whoever ran the command.\n //\n // Skipped rather than sanitised. A file named something other\n // than its table is a collection that does not round-trip, and\n // silently renaming it would be a worse surprise than one line\n // saying which table was left out.\n if (!isUsableFileName(tableName)) {\n outWarn(chalk.yellow(\n `⚠ Skipping table ${JSON.stringify(tableName)}: its name cannot be used as a ` +\n \"filename. Rename the table, or write this collection by hand.\"\n ));\n skippedFiles.push(tableName);\n return;\n }\n\n // ── File overwrite protection ──────────────────────────────\n const filePath = path.join(outDir, `${tableName}.ts`);\n if (fs.existsSync(filePath) && !force) {\n skippedFiles.push(tableName);\n return;\n }\n\n let sampleData: Record<string, unknown>[] | undefined = undefined;\n if (runDataInference) {\n try {\n // Quoted by `quoteRelation`, which doubles an embedded\n // quote. Wrapping a catalogue name in `\"` is not\n // escaping it — see that function.\n const { rows } = await client.query(`SELECT * FROM ${quoteRelation(pgSchema, tableName)} LIMIT 100`);\n sampleData = rows;\n } catch (err) {\n outError(chalk.yellow(`⚠ Failed to sample data for table ${tableName}: ${err instanceof Error ? err.message : String(err)}`));\n }\n }\n\n const fileContent = generateCollectionFile(\n tableName,\n meta,\n fks,\n joinTables,\n tablesMap,\n enumMap,\n sampleData,\n { metadata, classifications, checkFacts, builder }\n );\n\n fs.writeFileSync(filePath, fileContent, \"utf-8\");\n generatedFiles.push(tableName);\n out(chalk.green(` ✓ ${filePath}`));\n }));\n }\n\n // Generate index.ts (sorted alphabetically for deterministic output)\n if (generatedFiles.length > 0) {\n const indexPath = path.join(outDir, \"index.ts\");\n\n if (fs.existsSync(indexPath) && !force) {\n // Merge: read existing index, add new exports that don't already exist\n const existing = fs.readFileSync(indexPath, \"utf-8\");\n const merged = mergeIndexContent(existing, generatedFiles);\n fs.writeFileSync(indexPath, merged, \"utf-8\");\n } else {\n // --force replaces collections derived from the database, but the\n // directory can also hold hand-written ones with no table in the\n // introspected schema (the auth users collection lives in\n // \"rebase\"). The backend discovers the whole directory, so an\n // index listing only introspected tables would silently drop them\n // from the admin UI while the API still served them.\n const siblings = fs.readdirSync(outDir)\n .filter(f => f.endsWith(\".ts\") && f !== \"index.ts\")\n .map(f => f.replace(/\\.ts$/, \"\"));\n const allFiles = [...new Set([...generatedFiles, ...siblings])];\n const indexContent = generateIndexContent(allFiles);\n fs.writeFileSync(indexPath, indexContent, \"utf-8\");\n }\n out(chalk.green(` ✓ ${indexPath}`));\n }\n\n out(\"\");\n if (skippedFiles.length > 0) {\n out(chalk.yellow(`⚠ Skipped ${skippedFiles.length} existing file(s): ${skippedFiles.join(\", \")}`));\n out(chalk.gray(\" Use --force to overwrite existing files.\"));\n out(\"\");\n }\n out(chalk.bold.green(`✓ Introspected ${tablesMap.size} tables — generated ${generatedFiles.length} collection(s).`));\n out(chalk.gray(` Review the generated files in ${outDir} and customize properties as needed.`));\n out(\"\");\n\n } catch (e) {\n outError(chalk.red(`✗ Error introspecting database: ${e instanceof Error ? e.message : String(e)}`));\n process.exit(1);\n } finally {\n await client.end();\n }\n}\n\nmain().catch((err) => {\n outError(String(err));\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAaA,IAAM,aAAa;;AAGnB,SAAS,qBAAqB,cAAmC;CAC7D,MAAM,wBAAQ,IAAI,IAAY;CAC9B,IAAI;CACJ,IAAI;EACA,SAAS,KAAK,MAAM,GAAG,aAAa,cAAc,OAAO,CAAC;CAC9D,QAAQ;EAGJ,OAAO;CACX;CACA,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO;CAC1D,MAAM,WAAW;CACjB,KAAK,MAAM,SAAS;EAAC;EAAgB;EAAmB;CAAkB,GAAG;EACzE,MAAM,QAAQ,SAAS;EACvB,IAAI,OAAO,UAAU,YAAY,UAAU,MACvC,KAAK,MAAM,QAAQ,OAAO,KAAK,KAAK,GAAG,MAAM,IAAI,IAAI;CAE7D;CACA,OAAO;AACX;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,wBAAwB,QAAmC;CACvE,IAAI,MAAM,KAAK,QAAQ,MAAM;CAC7B,MAAM,2BAAW,IAAI,IAAY;CAEjC,KAAK,IAAI,QAAQ,GAAG,QAAQ,YAAY,SAAS;EAC7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UAAU,CAAC,CAClD,KAAI,MAAK,EAAE,QAAQ,SAAS,EAAE,CAAC;IAEpC,MAAM,eAAe,qBAAqB,CADxB,mBAAG,IAAI,IAAI,CAAC,GAAG,gBAAgB,GAAG,QAAQ,CAAC,CACnB,CAAQ;IAClD,GAAG,cAAc,WAAW,cAAc,OAAO;GACrD;GACA,IAAI,MAAM,MAAM,OAAO,WAAW,CAAC;EACvC;EAEA,IAAI,EAAE;EACN,IAAI,aAAa,SAAS,GAAG;GACzB,IAAI,MAAM,OAAO,aAAa,aAAa,OAAO,qBAAqB,aAAa,KAAK,IAAI,GAAG,CAAC;GACjG,IAAI,MAAM,KAAK,4CAA4C,CAAC;GAC5D,IAAI,EAAE;EACV;EACA,IAAI,MAAM,KAAK,MAAM,kBAAkB,UAAU,KAAK,sBAAsB,eAAe,OAAO,gBAAgB,CAAC;EACnH,IAAI,MAAM,KAAK,mCAAmC,OAAO,qCAAqC,CAAC;EAC/F,IAAI,EAAE;CAEV,SAAS,GAAG;EACR,SAAS,MAAM,IAAI,mCAAmC,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,GAAG,CAAC;EACnG,QAAQ,KAAK,CAAC;CAClB,UAAU;EACN,MAAM,OAAO,IAAI;CACrB;AACJ;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CAClB,SAAS,OAAO,GAAG,CAAC;CACpB,QAAQ,KAAK,CAAC;AAClB,CAAC"}
1
+ {"version":3,"file":"introspect-db.js","names":[],"sources":["../../src/schema/introspect-db-project.ts","../../src/schema/introspect-db-constraints.ts","../../src/schema/introspect-db.ts"],"sourcesContent":["/**\n * What the project being introspected into can actually import.\n *\n * The generator is pure — `introspect-db-logic.ts` reads no files — so the one\n * question it cannot answer for itself lives here: which `defineCollection`, if\n * any, will resolve from the directory the collections are written to.\n */\nimport fs from \"fs\";\nimport path from \"path\";\n\nimport { ADMIN_TYPES_PACKAGE, COMMON_PACKAGE, type CollectionBuilder } from \"./introspect-db-logic\";\n\n/** How far up to look before giving up, if no project root announces itself. */\nconst MAX_LEVELS = 8;\n\n/** Every dependency name a manifest declares, in any of the three fields. */\nfunction declaredDependencies(manifestPath: string): Set<string> {\n const names = new Set<string>();\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(manifestPath, \"utf-8\"));\n } catch {\n // A malformed or unreadable package.json is not this function's problem\n // to report — it answers \"can this import resolve\", and the answer is no.\n return names;\n }\n if (typeof parsed !== \"object\" || parsed === null) return names;\n const manifest = parsed as Record<string, unknown>;\n for (const field of [\"dependencies\", \"devDependencies\", \"peerDependencies\"]) {\n const block = manifest[field];\n if (typeof block === \"object\" && block !== null) {\n for (const name of Object.keys(block)) names.add(name);\n }\n }\n return names;\n}\n\n/**\n * Which `defineCollection` to generate against, for collections written to `outDir`.\n *\n * **The detection is the package manifests above the output directory**, unioned from\n * `outDir` up to and including the project root — the first ancestor holding a\n * `rebase.json`, or `MAX_LEVELS` up if there is none.\n *\n * That is the rule Node itself applies: a file in `config/collections` resolves a bare\n * specifier through `config/node_modules`, then `<project>/node_modules`, and so on up.\n * Reading the manifests along that same path answers the only question that matters —\n * *will this import resolve in the project I am writing into* — from the state on disk\n * at the moment of generation. The alternatives are all proxies for it: `rebase.json`'s\n * `apps` block says a CMS scaffold declared an admin app, and a `frontend/` directory\n * says one was scaffolded, but neither is what the compiler consults, and either can be\n * true of a project whose `config` package does not depend on `@rebasepro/cms-types`.\n *\n * Ambiguity resolves towards the admin panel: a project that declares both packages has\n * a panel, and `@rebasepro/cms-types` is the flavour that keeps the `admin` block.\n */\nexport function detectCollectionBuilder(outDir: string): CollectionBuilder {\n let dir = path.resolve(outDir);\n const declared = new Set<string>();\n\n for (let level = 0; level < MAX_LEVELS; level++) {\n const manifest = path.join(dir, \"package.json\");\n if (fs.existsSync(manifest)) {\n for (const name of declaredDependencies(manifest)) declared.add(name);\n }\n // The project root, and the last level worth reading: anything above it\n // belongs to whatever the project happens to be checked out inside.\n if (fs.existsSync(path.join(dir, \"rebase.json\"))) break;\n\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n\n if (declared.has(ADMIN_TYPES_PACKAGE)) return \"admin-types\";\n if (declared.has(COMMON_PACKAGE)) return \"common\";\n return \"annotation\";\n}\n","/**\n * Reading validation rules out of CHECK constraints.\n *\n * A CHECK constraint is the schema author stating a rule the database already\n * enforces. Introspection has never read them, so a generated form let the user\n * type a value the database was always going to reject — the rule was written\n * down, in the schema, and the UI asked anyway.\n *\n * Everything here parses the *normalized* text `pg_get_constraintdef` produces,\n * not what the author typed: Postgres re-renders the expression from its parse\n * tree, so `CHECK (price > 0)` on a `numeric` column always comes back as\n * `CHECK ((price > (0)::numeric))`. That normalization is what makes a\n * string-level parser tractable — the input is generated, and the shapes are\n * few.\n *\n * Constraints this cannot read are skipped in full. A partially-understood\n * constraint is worse than an unread one: it would produce validation that\n * *narrows* differently from the database, so a value the UI accepts still\n * fails on write, or — worse — a value the database allows is refused in the\n * form with no way to see why.\n *\n * Pure module: no I/O, no logging.\n */\nimport type { CheckConstraintRow } from \"./introspect-db-logic\";\n\n/** What a table's CHECK constraints say about one column. */\nexport interface ColumnCheckFacts {\n /** Allowed values, from `IN (…)` / `= ANY (ARRAY[…])` / `= 'literal'`. */\n enumValues?: string[];\n /** `x >= n` */\n min?: number;\n /** `x <= n` */\n max?: number;\n /** `x > n` */\n moreThan?: number;\n /** `x < n` */\n lessThan?: number;\n /** `length(x) >= n` */\n lengthMin?: number;\n /** `length(x) <= n` */\n lengthMax?: number;\n}\n\n/** Per-table, per-column facts. */\nexport type CheckFactsByTable = Map<string, Map<string, ColumnCheckFacts>>;\n\n/** The length functions whose argument is the column being constrained. */\nconst LENGTH_FUNCTIONS = new Set([\"length\", \"char_length\", \"character_length\", \"octet_length\"]);\n\n/**\n * Splits on a separator that appears at paren depth 0 and outside string\n * literals.\n *\n * Depth tracking is the whole job: `ARRAY['a', 'b']` contains a comma that must\n * not split the enclosing argument list, and `'it''s'` contains a quote that\n * must not end the literal.\n */\nfunction splitTopLevel(input: string, separator: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let inString = false;\n let current = \"\";\n\n for (let i = 0; i < input.length; i++) {\n const ch = input[i];\n\n if (inString) {\n current += ch;\n if (ch === \"'\") {\n // '' inside a literal is an escaped quote, not the end of it.\n if (input[i + 1] === \"'\") {\n current += input[++i];\n } else {\n inString = false;\n }\n }\n continue;\n }\n\n if (ch === \"'\") {\n inString = true;\n current += ch;\n continue;\n }\n if (ch === \"(\" || ch === \"[\") depth++;\n if (ch === \")\" || ch === \"]\") depth--;\n\n if (depth === 0 && input.startsWith(separator, i)) {\n // A word separator must not match inside an identifier: \"AND\" is a\n // separator in `a AND b` but not in `brand = 1`.\n const before = input[i - 1];\n const after = input[i + separator.length];\n const wordish = /[A-Za-z]/.test(separator[0]);\n const boundedOk = !wordish || ((before === undefined || !/[A-Za-z0-9_]/.test(before)) &&\n (after === undefined || !/[A-Za-z0-9_]/.test(after)));\n if (boundedOk) {\n parts.push(current);\n current = \"\";\n i += separator.length - 1;\n continue;\n }\n }\n\n current += ch;\n }\n\n parts.push(current);\n return parts.map((p) => p.trim()).filter((p) => p.length > 0);\n}\n\n/** Removes one layer of wrapping parentheses, repeatedly, when balanced. */\nexport function unwrapParens(input: string): string {\n let s = input.trim();\n while (s.startsWith(\"(\") && s.endsWith(\")\")) {\n let depth = 0;\n let balanced = true;\n let inString = false;\n for (let i = 0; i < s.length; i++) {\n const ch = s[i];\n if (inString) {\n if (ch === \"'\") {\n if (s[i + 1] === \"'\") i++;\n else inString = false;\n }\n continue;\n }\n if (ch === \"'\") { inString = true; continue; }\n if (ch === \"(\") depth++;\n else if (ch === \")\") {\n depth--;\n // The opening paren closed before the end, so the outer pair is\n // not a wrapper: `(a) AND (b)`.\n if (depth === 0 && i < s.length - 1) { balanced = false; break; }\n }\n }\n if (!balanced) break;\n s = s.slice(1, -1).trim();\n }\n return s;\n}\n\n/** Drops trailing `::type` casts, including array and quoted forms. */\nexport function stripCasts(input: string): string {\n let s = unwrapParens(input);\n let previous: string;\n do {\n previous = s;\n s = unwrapParens(\n s.replace(/::\\s*\"?[A-Za-z_][A-Za-z0-9_ ]*\"?(\\s*\\(\\s*\\d+\\s*(,\\s*\\d+\\s*)?\\))?(\\s*\\[\\s*\\])*\\s*$/, \"\").trim()\n );\n } while (s !== previous);\n return s;\n}\n\n/** A bare, unquoted column reference — anything else is an expression. */\nfunction asColumnName(input: string): string | null {\n const s = stripCasts(input);\n if (/^[a-z_][a-z0-9_$]*$/i.test(s)) return s;\n // A quoted identifier keeps its case: \"userId\".\n const quoted = s.match(/^\"([^\"]+)\"$/);\n return quoted ? quoted[1] : null;\n}\n\n/** `length(col)` and friends → the column they measure. */\nfunction asLengthOfColumn(input: string): string | null {\n const s = stripCasts(input);\n const match = s.match(/^([a-z_]+)\\s*\\((.*)\\)$/is);\n if (!match || !LENGTH_FUNCTIONS.has(match[1].toLowerCase())) return null;\n return asColumnName(match[2]);\n}\n\n/** A numeric literal, after casts are removed. Rejects anything else. */\nfunction asNumber(input: string): number | null {\n const s = stripCasts(input).replace(/^'(.*)'$/s, \"$1\");\n if (!/^[+-]?(\\d+\\.?\\d*|\\.\\d+)$/.test(s)) return null;\n const n = Number(s);\n return Number.isFinite(n) ? n : null;\n}\n\n/** A single-quoted string literal, with `''` unescaped. */\nfunction asStringLiteral(input: string): string | null {\n const s = stripCasts(input);\n if (!s.startsWith(\"'\") || !s.endsWith(\"'\") || s.length < 2) return null;\n const body = s.slice(1, -1);\n // Any unescaped quote inside means this was not one literal.\n if (/(^|[^'])'($|[^'])/.test(body)) return null;\n return body.replace(/''/g, \"'\");\n}\n\n/** The element list of `ARRAY[…]`, or of a parenthesised `IN (…)` list. */\nfunction asValueList(input: string): string[] | null {\n const s = stripCasts(input);\n const arrayMatch = s.match(/^ARRAY\\s*\\[(.*)\\]$/is);\n const body = arrayMatch ? arrayMatch[1] : (s.startsWith(\"(\") && s.endsWith(\")\") ? s.slice(1, -1) : null);\n if (body === null) return null;\n if (body.trim() === \"\") return null;\n\n const values: string[] = [];\n for (const element of splitTopLevel(body, \",\")) {\n const literal = asStringLiteral(element);\n if (literal !== null) {\n values.push(literal);\n continue;\n }\n const numeric = asNumber(element);\n if (numeric !== null) {\n values.push(String(numeric));\n continue;\n }\n return null; // A non-literal element means this is not an enumeration.\n }\n return values;\n}\n\n/** One understood comparison, already resolved to the column it constrains. */\ninterface CheckTerm {\n column: string;\n apply: (facts: ColumnCheckFacts) => void;\n}\n\n/**\n * Parses one conjunct. Returns null when the shape is not one of the few this\n * understands, which is the signal to abandon the whole constraint.\n */\nfunction parseTerm(rawTerm: string): CheckTerm | null {\n const term = unwrapParens(rawTerm);\n\n // ── Membership: `x = ANY (ARRAY[…])`, `x IN (…)` ──────────────────\n const anyMatch = term.match(/^(.*?)\\s*=\\s*ANY\\s*(\\(.*\\))$/is);\n const inMatch = anyMatch ? null : term.match(/^(.*?)\\s+IN\\s*(\\(.*\\))$/is);\n const membership = anyMatch ?? inMatch;\n if (membership) {\n const column = asColumnName(membership[1]);\n const values = asValueList(membership[2]);\n if (!column || !values || values.length === 0) return null;\n return {\n column,\n apply: (facts) => {\n // Two membership checks on one column mean both must hold.\n facts.enumValues = facts.enumValues\n ? facts.enumValues.filter((v) => values.includes(v))\n : values;\n }\n };\n }\n\n // ── Comparison: `x >= n`, `length(x) <= n`, `x = 'literal'` ───────\n // Longest operators first so `>=` is not read as `>`.\n for (const operator of [\">=\", \"<=\", \"<>\", \"!=\", \"=\", \">\", \"<\"] as const) {\n const parts = splitTopLevel(term, operator);\n if (parts.length !== 2) continue;\n const [rawLeft, rawRight] = parts;\n\n const lengthColumn = asLengthOfColumn(rawLeft);\n if (lengthColumn) {\n const bound = asNumber(rawRight);\n if (bound === null) return null;\n switch (operator) {\n case \">=\": return { column: lengthColumn, apply: (f) => { f.lengthMin = Math.max(f.lengthMin ?? bound, bound); } };\n case \">\": return { column: lengthColumn, apply: (f) => { f.lengthMin = Math.max(f.lengthMin ?? bound + 1, bound + 1); } };\n case \"<=\": return { column: lengthColumn, apply: (f) => { f.lengthMax = Math.min(f.lengthMax ?? bound, bound); } };\n case \"<\": return { column: lengthColumn, apply: (f) => { f.lengthMax = Math.min(f.lengthMax ?? bound - 1, bound - 1); } };\n case \"=\": return { column: lengthColumn, apply: (f) => { f.lengthMin = bound; f.lengthMax = bound; } };\n default: return null;\n }\n }\n\n const column = asColumnName(rawLeft);\n if (!column) continue;\n\n if (operator === \"=\") {\n const literal = asStringLiteral(rawRight);\n if (literal !== null) {\n return {\n column,\n apply: (facts) => {\n facts.enumValues = facts.enumValues\n ? facts.enumValues.filter((v) => v === literal)\n : [literal];\n }\n };\n }\n // `x = 5` pins a number. Expressed as both bounds rather than as a\n // one-value enum, which for a number would render as a dropdown.\n const pinned = asNumber(rawRight);\n if (pinned === null) return null;\n return { column, apply: (f) => { f.min = pinned; f.max = pinned; } };\n }\n\n const bound = asNumber(rawRight);\n if (bound === null) return null;\n switch (operator) {\n case \">=\": return { column, apply: (f) => { f.min = Math.max(f.min ?? bound, bound); } };\n case \">\": return { column, apply: (f) => { f.moreThan = Math.max(f.moreThan ?? bound, bound); } };\n case \"<=\": return { column, apply: (f) => { f.max = Math.min(f.max ?? bound, bound); } };\n case \"<\": return { column, apply: (f) => { f.lessThan = Math.min(f.lessThan ?? bound, bound); } };\n default: return null; // `<>` / `!=` exclude rather than bound.\n }\n }\n\n return null;\n}\n\n/**\n * Reads one constraint definition into per-column facts.\n *\n * Returns an empty map for anything not understood — including a constraint\n * that is understood but spans two columns (`start_date < end_date`), which no\n * per-property validation rule can express.\n */\nexport function parseCheckDefinition(definition: string): Map<string, ColumnCheckFacts> {\n const result = new Map<string, ColumnCheckFacts>();\n\n const body = definition\n .trim()\n .replace(/\\s+NOT\\s+VALID\\s*$/i, \"\")\n .replace(/^CHECK\\s*/i, \"\")\n .trim();\n if (body === definition.trim()) return result; // Not a CHECK definition.\n\n const expression = unwrapParens(body);\n if (!expression) return result;\n\n // Only conjunctions. A disjunction (`a OR b`) does not narrow a column: each\n // branch may allow what the other forbids, so no single bound follows.\n if (splitTopLevel(expression, \" OR \").length > 1) return result;\n\n const terms = splitTopLevel(expression, \" AND \");\n const parsed: CheckTerm[] = [];\n for (const term of terms) {\n const one = parseTerm(term);\n if (!one) return result; // One unreadable conjunct voids the constraint.\n parsed.push(one);\n }\n\n // A CHECK naming two columns constrains their *relationship*; keeping the\n // half that mentions one column would assert something the database does not.\n const columns = new Set(parsed.map((t) => t.column));\n if (columns.size !== 1) return result;\n\n const facts: ColumnCheckFacts = {};\n for (const term of parsed) term.apply(facts);\n if (Object.keys(facts).length === 0) return result;\n\n result.set(parsed[0].column, facts);\n return result;\n}\n\n/** Merges every readable CHECK in the schema into per-table, per-column facts. */\nexport function parseCheckConstraints(rows: CheckConstraintRow[]): CheckFactsByTable {\n const byTable: CheckFactsByTable = new Map();\n\n for (const row of rows) {\n const parsed = parseCheckDefinition(row.definition);\n if (parsed.size === 0) continue;\n\n let table = byTable.get(row.table_name);\n if (!table) {\n table = new Map();\n byTable.set(row.table_name, table);\n }\n\n for (const [column, facts] of parsed) {\n const existing = table.get(column);\n if (!existing) {\n table.set(column, facts);\n continue;\n }\n // Separate constraints on the same column all hold at once.\n if (facts.enumValues) {\n existing.enumValues = existing.enumValues\n ? existing.enumValues.filter((v) => facts.enumValues!.includes(v))\n : facts.enumValues;\n }\n if (facts.min !== undefined) existing.min = Math.max(existing.min ?? facts.min, facts.min);\n if (facts.max !== undefined) existing.max = Math.min(existing.max ?? facts.max, facts.max);\n if (facts.moreThan !== undefined) existing.moreThan = Math.max(existing.moreThan ?? facts.moreThan, facts.moreThan);\n if (facts.lessThan !== undefined) existing.lessThan = Math.min(existing.lessThan ?? facts.lessThan, facts.lessThan);\n if (facts.lengthMin !== undefined) existing.lengthMin = Math.max(existing.lengthMin ?? facts.lengthMin, facts.lengthMin);\n if (facts.lengthMax !== undefined) existing.lengthMax = Math.min(existing.lengthMax ?? facts.lengthMax, facts.lengthMax);\n }\n }\n\n return byTable;\n}\n","import chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport pg from \"pg\";\nimport arg from \"arg\";\nimport * as dotenv from \"dotenv\";\nimport readline from \"readline\";\n\nimport {\n buildTablesMap,\n buildEnumMap,\n compositeKeySkipReason,\n generateCollectionFile,\n generateIndexContent,\n mergeIndexContent,\n safeHostFromUrl\n} from \"./introspect-db-logic\";\nimport { detectCollectionBuilder } from \"./introspect-db-project\";\nimport { countRowsUpTo, isUsableFileName, quoteRelation, readSchemaMetadata } from \"./introspect-db-queries\";\nimport { classifyTables, lookupCandidates, LOOKUP_MAX_ROWS } from \"./introspect-db-structure\";\nimport { parseCheckConstraints } from \"./introspect-db-constraints\";\nimport { out, outWarn, outError } from \"../cli-output\";\n\nasync function main() {\n const args = arg(\n {\n \"--output\": String,\n \"--collections\": String,\n \"--force\": Boolean,\n \"--schema\": String,\n \"--data-inference\": Boolean,\n \"--no-data-inference\": Boolean,\n \"-o\": \"--output\",\n \"-c\": \"--collections\",\n \"-f\": \"--force\"\n },\n { permissive: true }\n );\n\n const cwd = process.cwd();\n const isBackendDir = path.basename(cwd) === \"backend\";\n const defaultOutDir = isBackendDir\n ? path.resolve(cwd, \"..\", \"config\", \"collections\")\n : path.resolve(cwd, \"config\", \"collections\");\n\n const outDir = args[\"--output\"] || args[\"--collections\"] || defaultOutDir;\n const force = args[\"--force\"] || false;\n const pgSchema = args[\"--schema\"] || \"public\";\n\n if (!fs.existsSync(outDir)) {\n fs.mkdirSync(outDir, { recursive: true });\n }\n\n // Load env\n const envPaths = [\n process.env.DOTENV_CONFIG_PATH,\n path.resolve(process.cwd(), \".env\"),\n path.resolve(process.cwd(), \"../.env\"),\n path.resolve(process.cwd(), \"../../.env\")\n ].filter(Boolean) as string[];\n\n for (const p of envPaths) {\n if (fs.existsSync(p)) {\n dotenv.config({ path: p, quiet: true });\n break;\n }\n }\n\n const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;\n if (!databaseUrl) {\n outError(chalk.red(\"✗ DATABASE_URL is not set. Make sure your .env file is configured.\"));\n process.exit(1);\n }\n\n const client = new pg.Client({ connectionString: databaseUrl });\n\n try {\n await client.connect();\n } catch (err) {\n outError(chalk.red(`✗ Failed to connect to database: ${err instanceof Error ? err.message : String(err)}`));\n outError(chalk.gray(\" Check your DATABASE_URL and ensure the database is reachable.\"));\n process.exit(1);\n }\n\n // Log the host portion safely — handle URLs without \"@\"\n const hostPart = safeHostFromUrl(databaseUrl);\n out(chalk.gray(`Connected to database: ${hostPart}`));\n out(chalk.gray(`Introspecting schema '${pgSchema}'...`));\n\n try {\n const metadata = await readSchemaMetadata(client, pgSchema);\n const enumMap = buildEnumMap(metadata.enumValues);\n const tablesMap = buildTablesMap(metadata.tables, metadata.columns, metadata.pks, metadata.fks);\n const fks = metadata.fks;\n\n // Only tables that could structurally be a code list are counted, and\n // each count stops at the threshold — see `countRowsUpTo`. Introspection\n // runs against a database it does not own, so \"cheap on a table of any\n // size\" is a requirement, not an optimization.\n for (const table of lookupCandidates(metadata, tablesMap)) {\n try {\n metadata.rowCounts[table] = await countRowsUpTo(client, pgSchema, table, LOOKUP_MAX_ROWS);\n } catch (err) {\n // A table this run cannot read is simply not classified as a code\n // list; everything else about it still generates.\n out(chalk.gray(` (skipped row count for ${table}: ${err instanceof Error ? err.message : String(err)})`));\n }\n }\n\n const classifications = classifyTables(metadata, tablesMap);\n const checkFacts = parseCheckConstraints(metadata.checks);\n\n // Which builder the generated files may import — read from the manifests\n // above `outDir`, because a project without `@rebasepro/cms-types` cannot\n // resolve that import and has no `admin` block to write into either.\n const builder = detectCollectionBuilder(outDir);\n if (builder === \"annotation\") {\n outWarn(chalk.yellow(\n \"⚠ Neither @rebasepro/cms-types nor @rebasepro/common is declared above \" +\n `${outDir}.`\n ));\n outWarn(chalk.gray(\n \" Generating plain type annotations, which widen the property keys to `string`: \" +\n \"`propertiesOrder` and friends will not be checked. Add @rebasepro/common to the \" +\n \"config package to turn that checking on.\"\n ));\n }\n const joinTables = new Set(\n Array.from(classifications.values())\n .filter((c) => c.role === \"junction\")\n .map((c) => c.table)\n );\n\n const roleCount = (role: string) =>\n Array.from(classifications.values()).filter((c) => c.role === role).length;\n\n out(chalk.blue(`Found ${tablesMap.size} tables.`));\n out(chalk.gray(\n ` ${roleCount(\"entity\")} entities, ${joinTables.size} join tables (folded into relations), ` +\n `${roleCount(\"lookup\")} code lists, ${roleCount(\"owned-child\")} owned by another table (hidden from navigation).`\n ));\n\n let runDataInference = false;\n if (args[\"--no-data-inference\"]) {\n runDataInference = false;\n } else if (args[\"--data-inference\"] !== undefined) {\n runDataInference = args[\"--data-inference\"];\n } else if (!process.stdin.isTTY) {\n // No terminal to answer the question below (scaffolding scripts, CI,\n // `rebase init --introspect`) — asking would hang forever.\n out(chalk.gray(\"Skipping data inference (non-interactive run; pass --data-inference to enable).\"));\n } else {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n const answer = await new Promise<string>((resolve) => rl.question(chalk.yellow(\"? Do you want to run comprehensive data inference on sampled rows to auto-detect types, formats, constraints, and UI configurations? (y/N) \"), resolve));\n runDataInference = answer.trim().toLowerCase() === \"y\";\n rl.close();\n }\n\n if (runDataInference) {\n out(chalk.gray(\"Sampling database rows for data inference...\"));\n }\n\n // Generate Collections\n const generatedFiles: string[] = [];\n const skippedFiles: string[] = [];\n\n // A table keyed on more than one column is generated with `isId` on\n // every key column — one composite key, which the planner builds the\n // same way — unless that cannot round-trip: a key column no `isId` can\n // mark, or a link pointing at the table (see `compositeKeySkipReason`).\n // Those are left out, with the reason. Generating one anyway produced a\n // file that read the table by an `id` column it does not have, and a\n // push that planned that column as its new primary key.\n const compositeKeyed = new Map(\n Array.from(tablesMap.entries())\n .filter(([tableName]) => !joinTables.has(tableName))\n .map(([tableName, meta]) => [tableName, compositeKeySkipReason(meta, fks)] as const)\n .filter((entry): entry is readonly [string, string] => entry[1] !== undefined)\n );\n for (const [tableName, reason] of compositeKeyed) {\n outWarn(chalk.yellow(\n `⚠ Skipping table ${JSON.stringify(tableName)}: it is keyed on ` +\n `(${tablesMap.get(tableName)?.pks.join(\", \")}), and ${reason}. ` +\n \"`rebase db push` leaves a table that is not a collection alone.\"\n ));\n }\n const notes: string[] = [];\n\n const tablesToProcess = Array.from(tablesMap.entries())\n .filter(([tableName]) => !joinTables.has(tableName) && !compositeKeyed.has(tableName));\n\n const BATCH_SIZE = 10;\n for (let i = 0; i < tablesToProcess.length; i += BATCH_SIZE) {\n const batch = tablesToProcess.slice(i, i + BATCH_SIZE);\n\n await Promise.all(batch.map(async ([tableName, meta]) => {\n // ── The name has to be usable as a filename ────────────────\n //\n // `tableName` came out of `pg_class` in a database this tool\n // did not create — adopting somebody else's database is the\n // whole point of introspection — and it is about to be joined\n // onto a path. Postgres will happily hold a table called\n // `../../../etc/cron.d/x`, and `path.join` resolves it: the\n // generator would write a TypeScript file wherever that\n // pointed, as whoever ran the command.\n //\n // Skipped rather than sanitised. A file named something other\n // than its table is a collection that does not round-trip, and\n // silently renaming it would be a worse surprise than one line\n // saying which table was left out.\n if (!isUsableFileName(tableName)) {\n outWarn(chalk.yellow(\n `⚠ Skipping table ${JSON.stringify(tableName)}: its name cannot be used as a ` +\n \"filename. Rename the table, or write this collection by hand.\"\n ));\n skippedFiles.push(tableName);\n return;\n }\n\n // ── File overwrite protection ──────────────────────────────\n const filePath = path.join(outDir, `${tableName}.ts`);\n if (fs.existsSync(filePath) && !force) {\n skippedFiles.push(tableName);\n return;\n }\n\n let sampleData: Record<string, unknown>[] | undefined = undefined;\n if (runDataInference) {\n try {\n // Quoted by `quoteRelation`, which doubles an embedded\n // quote. Wrapping a catalogue name in `\"` is not\n // escaping it — see that function.\n const { rows } = await client.query(`SELECT * FROM ${quoteRelation(pgSchema, tableName)} LIMIT 100`);\n sampleData = rows;\n } catch (err) {\n outError(chalk.yellow(`⚠ Failed to sample data for table ${tableName}: ${err instanceof Error ? err.message : String(err)}`));\n }\n }\n\n const fileContent = generateCollectionFile(\n tableName,\n meta,\n fks,\n joinTables,\n tablesMap,\n enumMap,\n sampleData,\n { metadata, classifications, checkFacts, builder, notes, skippedTables: new Set(compositeKeyed.keys()) }\n );\n\n fs.writeFileSync(filePath, fileContent, \"utf-8\");\n generatedFiles.push(tableName);\n out(chalk.green(` ✓ ${filePath}`));\n }));\n }\n\n // Every column the planner will not reproduce exactly, before anyone\n // pushes. Each line is also at the top of its file.\n if (notes.length > 0) {\n outWarn(\"\");\n outWarn(chalk.yellow(`⚠ ${notes.length} column(s) will not round-trip exactly — \\`rebase db push\\` would change them:`));\n for (const note of [...notes].sort()) outWarn(chalk.gray(` - ${note}`));\n outWarn(chalk.gray(\" Read these before the first push. Run `rebase db push --dry-run` to see the plan.\"));\n }\n\n // Generate index.ts (sorted alphabetically for deterministic output)\n if (generatedFiles.length > 0) {\n const indexPath = path.join(outDir, \"index.ts\");\n\n if (fs.existsSync(indexPath) && !force) {\n // Merge: read existing index, add new exports that don't already exist\n const existing = fs.readFileSync(indexPath, \"utf-8\");\n const merged = mergeIndexContent(existing, generatedFiles);\n fs.writeFileSync(indexPath, merged, \"utf-8\");\n } else {\n // --force replaces collections derived from the database, but the\n // directory can also hold hand-written ones with no table in the\n // introspected schema (the auth users collection lives in\n // \"rebase\"). The backend discovers the whole directory, so an\n // index listing only introspected tables would silently drop them\n // from the admin UI while the API still served them.\n const siblings = fs.readdirSync(outDir)\n .filter(f => f.endsWith(\".ts\") && f !== \"index.ts\")\n .map(f => f.replace(/\\.ts$/, \"\"));\n const allFiles = [...new Set([...generatedFiles, ...siblings])];\n const indexContent = generateIndexContent(allFiles);\n fs.writeFileSync(indexPath, indexContent, \"utf-8\");\n }\n out(chalk.green(` ✓ ${indexPath}`));\n }\n\n out(\"\");\n if (skippedFiles.length > 0) {\n out(chalk.yellow(`⚠ Skipped ${skippedFiles.length} existing file(s): ${skippedFiles.join(\", \")}`));\n out(chalk.gray(\" Use --force to overwrite existing files.\"));\n out(\"\");\n }\n out(chalk.bold.green(`✓ Introspected ${tablesMap.size} tables — generated ${generatedFiles.length} collection(s).`));\n out(chalk.gray(` Review the generated files in ${outDir} and customize properties as needed.`));\n out(\"\");\n\n } catch (e) {\n outError(chalk.red(`✗ Error introspecting database: ${e instanceof Error ? e.message : String(e)}`));\n process.exit(1);\n } finally {\n await client.end();\n }\n}\n\nmain().catch((err) => {\n outError(String(err));\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAaA,IAAM,aAAa;;AAGnB,SAAS,qBAAqB,cAAmC;CAC7D,MAAM,wBAAQ,IAAI,IAAY;CAC9B,IAAI;CACJ,IAAI;EACA,SAAS,KAAK,MAAM,GAAG,aAAa,cAAc,OAAO,CAAC;CAC9D,QAAQ;EAGJ,OAAO;CACX;CACA,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO;CAC1D,MAAM,WAAW;CACjB,KAAK,MAAM,SAAS;EAAC;EAAgB;EAAmB;CAAkB,GAAG;EACzE,MAAM,QAAQ,SAAS;EACvB,IAAI,OAAO,UAAU,YAAY,UAAU,MACvC,KAAK,MAAM,QAAQ,OAAO,KAAK,KAAK,GAAG,MAAM,IAAI,IAAI;CAE7D;CACA,OAAO;AACX;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,wBAAwB,QAAmC;CACvE,IAAI,MAAM,KAAK,QAAQ,MAAM;CAC7B,MAAM,2BAAW,IAAI,IAAY;CAEjC,KAAK,IAAI,QAAQ,GAAG,QAAQ,YAAY,SAAS;EAC7C,MAAM,WAAW,KAAK,KAAK,KAAK,cAAc;EAC9C,IAAI,GAAG,WAAW,QAAQ,GACtB,KAAK,MAAM,QAAQ,qBAAqB,QAAQ,GAAG,SAAS,IAAI,IAAI;EAIxE,IAAI,GAAG,WAAW,KAAK,KAAK,KAAK,aAAa,CAAC,GAAG;EAElD,MAAM,SAAS,KAAK,QAAQ,GAAG;EAC/B,IAAI,WAAW,KAAK;EACpB,MAAM;CACV;CAEA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