@rebasepro/server-postgres 0.33.2 → 0.34.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 (73) hide show
  1. package/dist/{BranchService-Bdin0Wxh.js → BranchService-BLcVK_Rd.js} +3 -3
  2. package/dist/{BranchService-Bdin0Wxh.js.map → BranchService-BLcVK_Rd.js.map} +1 -1
  3. package/dist/{backup-cli-BEAMPWMs.js → backup-cli-CVLOCTo_.js} +3 -3
  4. package/dist/{backup-cli-BEAMPWMs.js.map → backup-cli-CVLOCTo_.js.map} +1 -1
  5. package/dist/{boot-ddl-Bu6gAY-2.js → boot-ddl-C7hAFEvY.js} +2 -2
  6. package/dist/{boot-ddl-Bu6gAY-2.js.map → boot-ddl-C7hAFEvY.js.map} +1 -1
  7. package/dist/{cli-console-BU_Rf22O.js → cli-console-E5TM3GaL.js} +4 -4
  8. package/dist/{cli-console-BU_Rf22O.js.map → cli-console-E5TM3GaL.js.map} +1 -1
  9. package/dist/{cli-schema-dir-CjDH_31U.js → cli-schema-dir-CdEqBcph.js} +29 -10
  10. package/dist/cli-schema-dir-CdEqBcph.js.map +1 -0
  11. package/dist/cli.js +29 -27
  12. package/dist/cli.js.map +1 -1
  13. package/dist/{database-preflight-DKzsGnc4.js → database-preflight-NmFI_rFN.js} +2 -2
  14. package/dist/{database-preflight-DKzsGnc4.js.map → database-preflight-NmFI_rFN.js.map} +1 -1
  15. package/dist/{deferred-index-build-88bWtYgx.js → deferred-index-build-Bz37bvxW.js} +4 -4
  16. package/dist/{deferred-index-build-88bWtYgx.js.map → deferred-index-build-Bz37bvxW.js.map} +1 -1
  17. package/dist/{ensure-policies-nIITKxud.js → ensure-policies-C1UCom37.js} +6 -6
  18. package/dist/{ensure-policies-nIITKxud.js.map → ensure-policies-C1UCom37.js.map} +1 -1
  19. package/dist/{ensure-tables-hQ5oAK_j.js → ensure-tables-BVUNi6uG.js} +3 -3
  20. package/dist/{ensure-tables-hQ5oAK_j.js.map → ensure-tables-BVUNi6uG.js.map} +1 -1
  21. package/dist/{ensure-tables-Lm-77eM5.js → ensure-tables-DjuNRClr.js} +7 -7
  22. package/dist/{ensure-tables-Lm-77eM5.js.map → ensure-tables-DjuNRClr.js.map} +1 -1
  23. package/dist/{enum-labels-kept-mesgEJWH.js → enum-labels-kept-DrCueSHr.js} +2 -2
  24. package/dist/{enum-labels-kept-mesgEJWH.js.map → enum-labels-kept-DrCueSHr.js.map} +1 -1
  25. package/dist/{generated-schema-diff-DoT2dYDe.js → generated-schema-diff-DDktAATD.js} +2 -2
  26. package/dist/{generated-schema-diff-DoT2dYDe.js.map → generated-schema-diff-DDktAATD.js.map} +1 -1
  27. package/dist/index.es.js +11 -11
  28. package/dist/{introspect-db-queries-BgiRQqtR.js → introspect-db-queries-D7u9EOfV.js} +66 -4
  29. package/dist/introspect-db-queries-D7u9EOfV.js.map +1 -0
  30. package/dist/{introspect-tables-Cw_A-kk4.js → introspect-tables-2yJ3p98l.js} +267 -30
  31. package/dist/introspect-tables-2yJ3p98l.js.map +1 -0
  32. package/dist/{migrate-baseline-Bzj5gSCM.js → migrate-baseline-CnIbBRgh.js} +4 -3
  33. package/dist/{migrate-baseline-Bzj5gSCM.js.map → migrate-baseline-CnIbBRgh.js.map} +1 -1
  34. package/dist/{migrate-policy-stamps-C2WaOEsB.js → migrate-policy-stamps-D7BaYeKO.js} +4 -4
  35. package/dist/{migrate-policy-stamps-C2WaOEsB.js.map → migrate-policy-stamps-D7BaYeKO.js.map} +1 -1
  36. package/dist/{open-rebase-x3yAPy5g.js → open-rebase-DykxNl1j.js} +72 -20
  37. package/dist/open-rebase-DykxNl1j.js.map +1 -0
  38. package/dist/{pg-error-utils-CWopxboq.js → pg-error-utils-DXyqf9yP.js} +2 -2
  39. package/dist/{pg-error-utils-CWopxboq.js.map → pg-error-utils-DXyqf9yP.js.map} +1 -1
  40. package/dist/{policy-drift-rVLKS2AG.js → policy-drift-B2Czzs2Z.js} +3 -3
  41. package/dist/{policy-drift-rVLKS2AG.js.map → policy-drift-B2Czzs2Z.js.map} +1 -1
  42. package/dist/{push-index-adoption-EcamXfW2.js → push-index-adoption-DTLPk_5i.js} +2 -2
  43. package/dist/{push-index-adoption-EcamXfW2.js.map → push-index-adoption-DTLPk_5i.js.map} +1 -1
  44. package/dist/{push-index-prebuild-BPIns6wA.js → push-index-prebuild-WP5272gZ.js} +3 -3
  45. package/dist/{push-index-prebuild-BPIns6wA.js.map → push-index-prebuild-WP5272gZ.js.map} +1 -1
  46. package/dist/{push-legacy-renames-lmYkb41I.js → push-legacy-renames-CvWSBxRu.js} +3 -3
  47. package/dist/{push-legacy-renames-lmYkb41I.js.map → push-legacy-renames-CvWSBxRu.js.map} +1 -1
  48. package/dist/{push-policy-plan-Dqu4FKWh.js → push-policy-plan-D8HvHgPs.js} +3 -3
  49. package/dist/{push-policy-plan-Dqu4FKWh.js.map → push-policy-plan-D8HvHgPs.js.map} +1 -1
  50. package/dist/{request-role-cli-Ay0v9oYZ.js → request-role-cli-Y5Uqalop.js} +8 -8
  51. package/dist/{request-role-cli-Ay0v9oYZ.js.map → request-role-cli-Y5Uqalop.js.map} +1 -1
  52. package/dist/{request-role-migration-DTE3Owsh.js → request-role-migration-Cc0gJSso.js} +2 -2
  53. package/dist/{request-role-migration-DTE3Owsh.js.map → request-role-migration-Cc0gJSso.js.map} +1 -1
  54. package/dist/{rls-enforcement-Ck-d8zdJ.js → rls-enforcement-NZKe3Jr-.js} +2 -2
  55. package/dist/{rls-enforcement-Ck-d8zdJ.js.map → rls-enforcement-NZKe3Jr-.js.map} +1 -1
  56. package/dist/schema/destructive-sql.d.ts +9 -1
  57. package/dist/schema/doctor-cli.js +6 -6
  58. package/dist/schema/introspect-db-logic.d.ts +51 -0
  59. package/dist/schema/introspect-db-project.d.ts +6 -0
  60. package/dist/schema/introspect-db-queries.d.ts +21 -2
  61. package/dist/schema/introspect-db.js +53 -4
  62. package/dist/schema/introspect-db.js.map +1 -1
  63. package/dist/schema/introspect-foreign.d.ts +47 -0
  64. package/dist/schema/introspect-tables.d.ts +17 -0
  65. package/dist/schema/undeclarable-constraints.d.ts +16 -3
  66. package/dist/utils/result-rows.d.ts +20 -0
  67. package/dist/{websocket-DAVDn7Ki.js → websocket-CvmbzBeS.js} +3 -3
  68. package/dist/{websocket-DAVDn7Ki.js.map → websocket-CvmbzBeS.js.map} +1 -1
  69. package/package.json +7 -7
  70. package/dist/cli-schema-dir-CjDH_31U.js.map +0 -1
  71. package/dist/introspect-db-queries-BgiRQqtR.js.map +0 -1
  72. package/dist/introspect-tables-Cw_A-kk4.js.map +0 -1
  73. package/dist/open-rebase-x3yAPy5g.js.map +0 -1
@@ -191,10 +191,12 @@ var FOREIGN_KEYS_QUERY = `
191
191
  WHEN 'c' THEN 'CASCADE'
192
192
  WHEN 'n' THEN 'SET NULL'
193
193
  WHEN 'd' THEN 'SET DEFAULT'
194
- END AS delete_rule
194
+ END AS delete_rule,
195
+ tn.nspname AS foreign_schema
195
196
  FROM fk
196
197
  JOIN pg_class root ON root.oid = fk.root_oid
197
198
  JOIN pg_class tgt ON tgt.oid = fk.confrelid
199
+ JOIN pg_namespace tn ON tn.oid = tgt.relnamespace
198
200
  CROSS JOIN LATERAL unnest(fk.conkey) WITH ORDINALITY AS s(attnum, ord)
199
201
  JOIN pg_attribute sa ON sa.attrelid = fk.conrelid AND sa.attnum = s.attnum
200
202
  CROSS JOIN LATERAL unnest(fk.confkey) WITH ORDINALITY AS f(attnum, ord)
@@ -258,6 +260,61 @@ var INDEXES_QUERY = `
258
260
  ORDER BY t.relname, ic.relname
259
261
  `;
260
262
  /**
263
+ * Every non-primary index with its keys: the plain ones (columns, no
264
+ * expression) become a table's `indexes`; the rest are reported.
265
+ */
266
+ var INDEX_DEFINITIONS_QUERY = `
267
+ SELECT t.relname AS table_name,
268
+ ic.relname AS index_name,
269
+ am.amname AS method,
270
+ i.indisunique AS unique,
271
+ CASE WHEN 0 = ANY (i.indkey::int2[]) THEN NULL ELSE
272
+ (SELECT array_agg(a.attname::text ORDER BY k.ord)
273
+ FROM unnest(i.indkey::int2[]) WITH ORDINALITY AS k(attnum, ord)
274
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum)
275
+ END AS column_names,
276
+ (SELECT array_agg((o.opt & 1) = 1 ORDER BY o.ord)
277
+ FROM unnest(i.indoption::int2[]) WITH ORDINALITY AS o(opt, ord)) AS descending,
278
+ pg_get_expr(i.indpred, i.indrelid) AS predicate,
279
+ pg_get_indexdef(i.indexrelid) AS definition
280
+ FROM pg_index i
281
+ JOIN pg_class t ON t.oid = i.indrelid
282
+ JOIN pg_class ic ON ic.oid = i.indexrelid
283
+ JOIN pg_am am ON am.oid = ic.relam
284
+ JOIN pg_namespace n ON n.oid = t.relnamespace
285
+ WHERE n.nspname = $1
286
+ AND NOT i.indisprimary
287
+ AND NOT t.relispartition
288
+ ORDER BY t.relname, ic.relname
289
+ `;
290
+ /**
291
+ * The functions and triggers of the schema, and the extensions of the
292
+ * database: objects a table definition does not carry, read only so the run
293
+ * can say they were left behind. Functions an extension owns are left out.
294
+ */
295
+ var DATABASE_OBJECTS_QUERY = `
296
+ SELECT 'function' AS kind,
297
+ p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')' AS name,
298
+ NULL::text AS table_name,
299
+ pg_get_functiondef(p.oid) AS definition
300
+ FROM pg_proc p
301
+ JOIN pg_namespace n ON n.oid = p.pronamespace
302
+ WHERE n.nspname = $1
303
+ AND p.prokind IN ('f', 'p')
304
+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = p.oid AND d.deptype = 'e')
305
+ UNION ALL
306
+ SELECT 'trigger', tg.tgname, c.relname, pg_get_triggerdef(tg.oid)
307
+ FROM pg_trigger tg
308
+ JOIN pg_class c ON c.oid = tg.tgrelid
309
+ JOIN pg_namespace n ON n.oid = c.relnamespace
310
+ WHERE n.nspname = $1 AND NOT tg.tgisinternal
311
+ UNION ALL
312
+ SELECT 'extension', e.extname, NULL, NULL
313
+ FROM pg_extension e
314
+ WHERE e.extname <> 'plpgsql'
315
+ ORDER BY 1, 2
316
+ `;
317
+ /**
261
318
  * CHECK constraints, as the source text Postgres reproduces them from.
262
319
  *
263
320
  * `pg_get_constraintdef` output is normalized by the server — the parser in
@@ -342,7 +399,7 @@ async function countRowsUpTo(client, schema, table, limit) {
342
399
  * a handful of tables can possibly need it. The caller fills it in for the
343
400
  * candidates `lookupCandidates()` names.
344
401
  */
345
- async function readSchemaMetadata(client, schema) {
402
+ async function readSchemaMetadata(client, schema, options = {}) {
346
403
  const tables = await client.query(TABLES_QUERY, [schema]);
347
404
  const columns = await client.query(COLUMNS_QUERY, [schema]);
348
405
  const enumValues = await client.query(ENUMS_QUERY, [schema]);
@@ -353,6 +410,8 @@ async function readSchemaMetadata(client, schema) {
353
410
  const checks = await client.query(CHECK_CONSTRAINTS_QUERY, [schema]);
354
411
  const comments = await client.query(COMMENTS_QUERY, [schema]);
355
412
  const policies = await client.query(POLICIES_QUERY, [schema]);
413
+ const indexDefinitions = options.forGeneration ? await client.query(INDEX_DEFINITIONS_QUERY, [schema]) : void 0;
414
+ const objects = options.forGeneration ? await client.query(DATABASE_OBJECTS_QUERY, [schema]).catch(() => ({ rows: [] })) : void 0;
356
415
  const known = new Set(tables.rows.map((t) => t.table_name));
357
416
  const scoped = (rows) => rows.filter((r) => known.has(r.table_name));
358
417
  return {
@@ -361,7 +420,10 @@ async function readSchemaMetadata(client, schema) {
361
420
  columns: scoped(columns.rows),
362
421
  enumValues: enumValues.rows,
363
422
  pks: scoped(pks.rows),
364
- fks: scoped(fks.rows).filter((fk) => known.has(fk.foreign_table_name)),
423
+ fks: scoped(fks.rows).filter((fk) => (fk.foreign_schema ?? schema) === schema && known.has(fk.foreign_table_name)),
424
+ externalFks: scoped(fks.rows).filter((fk) => fk.foreign_schema !== void 0 && fk.foreign_schema !== schema),
425
+ ...indexDefinitions ? { indexDefinitions: scoped(indexDefinitions.rows) } : {},
426
+ ...objects ? { objects: objects.rows.filter((o) => o.kind !== "trigger" || o.table_name !== null && o.table_name !== void 0 && known.has(o.table_name)) } : {},
365
427
  uniques: scoped(uniques.rows),
366
428
  indexes: scoped(indexes.rows),
367
429
  checks: scoped(checks.rows),
@@ -376,4 +438,4 @@ async function readSchemaMetadata(client, schema) {
376
438
  //#endregion
377
439
  export { readSchemaMetadata as i, isUsableFileName as n, quoteRelation as r, countRowsUpTo as t };
378
440
 
379
- //# sourceMappingURL=introspect-db-queries-BgiRQqtR.js.map
441
+ //# sourceMappingURL=introspect-db-queries-D7u9EOfV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"introspect-db-queries-D7u9EOfV.js","names":[],"sources":["../src/schema/introspect-db-queries.ts"],"sourcesContent":["/**\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 IndexRow,\n CheckConstraintRow,\n CommentRow,\n PolicyRow,\n IndexDefinitionRow,\n DatabaseObjectRow,\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 c.relrowsecurity AS rls_enabled\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.generation_expression,\n c.is_identity,\n c.identity_generation,\n c.character_maximum_length,\n c.numeric_precision,\n c.numeric_scale,\n (SELECT a.atttypmod FROM pg_attribute a\n JOIN pg_class pc ON a.attrelid = pc.oid\n WHERE pc.relname = c.table_name\n AND a.attname = c.column_name\n AND pc.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = c.table_schema)) as atttypmod,\n (SELECT format_type(a.atttypid, a.atttypmod) FROM pg_attribute a\n JOIN pg_class pc ON a.attrelid = pc.oid\n WHERE pc.relname = c.table_name\n AND a.attname = c.column_name\n AND pc.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = c.table_schema)) as formatted_type\n FROM information_schema.columns c\n WHERE c.table_schema = $1\n ORDER BY c.table_name, c.ordinal_position\n`;\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 tn.nspname AS foreign_schema\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 JOIN pg_namespace tn ON tn.oid = tgt.relnamespace\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 * Every index on the schema's tables: its name, which tells a foreign key\n * Rebase already indexed apart from one it would index on the first push\n * (see `foreignKeyIndexSpec`), and whether it serves an equality lookup on its\n * leading column — a btree with no predicate — which tells one the database\n * already indexes some other way apart from one with no index at all.\n *\n * `leading_column` is null when the first key is an expression.\n */\nexport const INDEXES_QUERY = `\n SELECT t.relname AS table_name,\n ic.relname AS index_name,\n a.attname AS leading_column,\n am.amname = 'btree' AND i.indpred IS NULL AS serves_leading_column\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_am am ON am.oid = ic.relam\n JOIN pg_namespace n ON n.oid = t.relnamespace\n LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = i.indkey[0] AND i.indkey[0] <> 0\n WHERE n.nspname = $1\n AND NOT t.relispartition\n ORDER BY t.relname, ic.relname\n`;\n\n/**\n * Every non-primary index with its keys: the plain ones (columns, no\n * expression) become a table's `indexes`; the rest are reported.\n */\nexport const INDEX_DEFINITIONS_QUERY = `\n SELECT t.relname AS table_name,\n ic.relname AS index_name,\n am.amname AS method,\n i.indisunique AS unique,\n CASE WHEN 0 = ANY (i.indkey::int2[]) THEN NULL ELSE\n (SELECT array_agg(a.attname::text ORDER BY k.ord)\n FROM unnest(i.indkey::int2[]) WITH ORDINALITY AS k(attnum, ord)\n JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum)\n END AS column_names,\n (SELECT array_agg((o.opt & 1) = 1 ORDER BY o.ord)\n FROM unnest(i.indoption::int2[]) WITH ORDINALITY AS o(opt, ord)) AS descending,\n pg_get_expr(i.indpred, i.indrelid) AS predicate,\n pg_get_indexdef(i.indexrelid) AS definition\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_am am ON am.oid = ic.relam\n JOIN pg_namespace n ON n.oid = t.relnamespace\n WHERE n.nspname = $1\n AND NOT i.indisprimary\n AND NOT t.relispartition\n ORDER BY t.relname, ic.relname\n`;\n\n/**\n * The functions and triggers of the schema, and the extensions of the\n * database: objects a table definition does not carry, read only so the run\n * can say they were left behind. Functions an extension owns are left out.\n */\nexport const DATABASE_OBJECTS_QUERY = `\n SELECT 'function' AS kind,\n p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')' AS name,\n NULL::text AS table_name,\n pg_get_functiondef(p.oid) AS definition\n FROM pg_proc p\n JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname = $1\n AND p.prokind IN ('f', 'p')\n AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = p.oid AND d.deptype = 'e')\n UNION ALL\n SELECT 'trigger', tg.tgname, c.relname, pg_get_triggerdef(tg.oid)\n FROM pg_trigger tg\n JOIN pg_class c ON c.oid = tg.tgrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = $1 AND NOT tg.tgisinternal\n UNION ALL\n SELECT 'extension', e.extname, NULL, NULL\n FROM pg_extension e\n WHERE e.extname <> 'plpgsql'\n ORDER BY 1, 2\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 *\n * Only comments on relations: `pg_description` also holds the stamps boot\n * writes on each policy (`rebase:<hash>`), and an OID is unique only within\n * its own catalogue, so a policy's could name a table.\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 d.classoid = 'pg_catalog.pg_class'::regclass\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 * Every row-level security policy in the schema, as `pg_policies` reports it.\n *\n * A table's policies are its access model. Introspection that leaves them out\n * generates collections describing no rules, and the database's own policies\n * then read as orphans: `doctor` fails on them, and a `db push` drops any\n * whose name has the shape an unnamed rule compiles to.\n */\nexport const POLICIES_QUERY = `\n SELECT tablename AS table_name,\n policyname AS policy_name,\n permissive,\n roles,\n cmd,\n qual,\n with_check\n FROM pg_policies\n WHERE schemaname = $1\n ORDER BY tablename, policyname\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 /**\n * `true` for `schema introspect`: also read each index's columns and the\n * functions, triggers and extensions, which only the generator and its\n * \"not carried over\" report use. The runtime's read at boot leaves them out.\n */\n options: { forGeneration?: boolean } = {}\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 indexes = await client.query<IndexRow>(INDEXES_QUERY, [schema]);\n const checks = await client.query<CheckConstraintRow>(CHECK_CONSTRAINTS_QUERY, [schema]);\n const comments = await client.query<CommentRow>(COMMENTS_QUERY, [schema]);\n const policies = await client.query<PolicyRow>(POLICIES_QUERY, [schema]);\n const indexDefinitions = options.forGeneration\n ? await client.query<IndexDefinitionRow>(INDEX_DEFINITIONS_QUERY, [schema])\n : undefined;\n // A role that may not call `pg_get_functiondef` on some function still\n // gets its tables; the report is the part that goes missing.\n const objects = options.forGeneration\n ? await client.query<DatabaseObjectRow>(DATABASE_OBJECTS_QUERY, [schema]).catch(() => ({ rows: [] as DatabaseObjectRow[] }))\n : undefined;\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) => (fk.foreign_schema ?? schema) === schema && known.has(fk.foreign_table_name)),\n externalFks: scoped(fks.rows).filter((fk) => fk.foreign_schema !== undefined && fk.foreign_schema !== schema),\n ...(indexDefinitions ? { indexDefinitions: scoped(indexDefinitions.rows) } : {}),\n ...(objects\n ? { objects: objects.rows.filter((o) => o.kind !== \"trigger\" || (o.table_name !== null && o.table_name !== undefined && known.has(o.table_name))) }\n : {}),\n uniques: scoped(uniques.rows),\n indexes: scoped(indexes.rows),\n checks: scoped(checks.rows),\n comments: scoped(comments.rows),\n policies: scoped(policies.rows).map((policy) => ({\n ...policy,\n // node-postgres yields `name[]` as an array; some drivers hand back \"{a,b}\".\n roles: Array.isArray(policy.roles)\n ? policy.roles\n : String(policy.roles ?? \"\").replace(/^\\{|\\}$/g, \"\").split(\",\").filter(Boolean)\n })),\n rowCounts: {}\n };\n}\n"],"mappings":"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"}
@@ -2,10 +2,188 @@ import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { c as searchColumnStamps, i as buildTableSearchColumnSpec } from "./search-column-BO-WND-B.js";
4
4
  import { u as foreignKeyIndexSpec } from "./source-VxbrQojV.js";
5
- import { i as readSchemaMetadata } from "./introspect-db-queries-BgiRQqtR.js";
6
- import { DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE, columnTypeLabel } from "@rebasepro/types";
7
- import { classifyTable, policyToSecurityRule, printIndexModule, printTableModule, tableGeneratedPolicyNames, tableIdentifier } from "@rebasepro/common";
5
+ import { i as readSchemaMetadata } from "./introspect-db-queries-D7u9EOfV.js";
6
+ import { DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE, columnTypeLabel, policy } from "@rebasepro/types";
7
+ import { classifyTable, compilePolicyExpression, policyToSecurityRule, printIndexModule, printTableModule, tableGeneratedPolicyNames, tableIdentifier } from "@rebasepro/common";
8
8
  import { firstFreeKey, toWireKey } from "@rebasepro/utils";
9
+ //#region src/schema/introspect-foreign.ts
10
+ /**
11
+ * What `schema introspect` does with the parts of a database that a table
12
+ * definition does not hold as they are: Supabase's conventions, plain indexes,
13
+ * CHECKs the API validates and the database no longer would, and the objects
14
+ * (functions, triggers, extensions) no definition carries at all.
15
+ *
16
+ * Introspecting a Supabase schema used to rewrite the policies to
17
+ * `rebase.uid()` and leave the rest as it was: a column default of
18
+ * `auth.uid()` that fails the first push (`schema "auth" does not exist`),
19
+ * policies `TO authenticated` / `TO anon` for roles a Rebase database does not
20
+ * have, a foreign key to `auth.users` dropped without a word, indexes dropped,
21
+ * and seven functions and two triggers never mentioned. Silence read as
22
+ * "everything came across".
23
+ *
24
+ * Every function here is pure: `describeTables` calls them in its "generate"
25
+ * pass, and `schema introspect` prints the report.
26
+ */
27
+ /** A column DEFAULT that is the caller's id: `auth.uid()`, `rebase.uid()`, either inside `(SELECT …)`. */
28
+ function isCallerIdDefault(raw) {
29
+ if (!raw) return false;
30
+ return /^\(*\s*(?:select\s+)?(?:auth|rebase)\.uid\(\)\s*\)*(?:::\s*(?:text|uuid))?$/i.test(raw.trim());
31
+ }
32
+ /** A foreign key to Supabase's users table. */
33
+ function isAuthUsersReference(fk) {
34
+ return fk.foreign_schema === "auth" && fk.foreign_table_name === "users";
35
+ }
36
+ /** Supabase's database roles, which a Rebase database does not have. */
37
+ var SUPABASE_ROLES = /* @__PURE__ */ new Set([
38
+ "anon",
39
+ "authenticated",
40
+ "service_role"
41
+ ]);
42
+ /** The SQL `policy.authenticated()` compiles to: a signed-in caller, guests included, as Supabase's `authenticated`. */
43
+ function signedInSql() {
44
+ return compilePolicyExpression(policy.authenticated());
45
+ }
46
+ function and(a, clause) {
47
+ if (a === void 0 || /^\(?\s*true\s*\)?$/i.test(a.trim())) return clause;
48
+ if (clause === signedInSql() && OWNER_EQUALITY.test(a)) return a;
49
+ return `(${a}) AND (${clause})`;
50
+ }
51
+ /** `<column> = rebase.uid()`, bare or inside `(SELECT … AS uid)`, as Postgres prints it back. */
52
+ var OWNER_EQUALITY = /^\(*\s*"?\w+"?\s*=\s*\(*\s*(?:SELECT\s+)?rebase\.uid\(\)(?:\s+AS\s+uid)?\s*\)*\s*$/i;
53
+ /**
54
+ * A rule read back from a policy, with Supabase's `TO` roles translated into
55
+ * what Rebase means by them, or `null` when the policy only served a role
56
+ * Rebase has no use for (`service_role`, which the server's own context
57
+ * replaces).
58
+ *
59
+ * - `TO authenticated` → the role is dropped and the rule requires a signed-in
60
+ * caller (`policy.authenticated()`'s SQL, ANDed into USING and WITH CHECK).
61
+ * - `TO anon` → dropped, the rule requiring a caller who is *not* signed in.
62
+ * - `TO anon, authenticated` → dropped: every caller, which is no condition.
63
+ * - Any other role is kept as it was.
64
+ */
65
+ function translateSupabaseRoles(rule) {
66
+ const pgRoles = "pgRoles" in rule ? rule.pgRoles : void 0;
67
+ if (!pgRoles || !pgRoles.some((role) => SUPABASE_ROLES.has(role))) return { rule };
68
+ const kept = pgRoles.filter((role) => !SUPABASE_ROLES.has(role));
69
+ const anon = pgRoles.includes("anon");
70
+ const authenticated = pgRoles.includes("authenticated");
71
+ const name = rule.name ?? "a policy";
72
+ if (!anon && !authenticated && kept.length === 0) return {
73
+ rule: null,
74
+ note: `policy "${name}" was only for Supabase's service_role, which a Rebase server replaces with its own context; it is not carried over.`
75
+ };
76
+ const base = {
77
+ ...rule.name !== void 0 ? { name: rule.name } : {},
78
+ ...rule.operation !== void 0 ? { operation: rule.operation } : {},
79
+ ...rule.operations !== void 0 ? { operations: rule.operations } : {},
80
+ ...rule.mode !== void 0 ? { mode: rule.mode } : {},
81
+ ...kept.length > 0 ? { pgRoles: kept } : {}
82
+ };
83
+ const using = "using" in rule && typeof rule.using === "string" ? rule.using : void 0;
84
+ const withCheck = "withCheck" in rule && typeof rule.withCheck === "string" ? rule.withCheck : void 0;
85
+ const rebuilt = (u, w) => u !== void 0 ? w !== void 0 ? {
86
+ ...base,
87
+ using: u,
88
+ withCheck: w
89
+ } : {
90
+ ...base,
91
+ using: u
92
+ } : w !== void 0 ? {
93
+ ...base,
94
+ withCheck: w
95
+ } : {
96
+ ...base,
97
+ using: "true"
98
+ };
99
+ if (anon && authenticated) return {
100
+ rule: rebuilt(using, withCheck),
101
+ note: `policy "${name}" was TO anon, authenticated (every caller); the roles are dropped.`
102
+ };
103
+ const clause = authenticated ? signedInSql() : `NOT (${signedInSql()})`;
104
+ return {
105
+ rule: using === void 0 && withCheck === void 0 ? rebuilt(clause, void 0) : rebuilt(using !== void 0 ? and(using, clause) : void 0, withCheck !== void 0 ? and(withCheck, clause) : void 0),
106
+ note: `policy "${name}" was TO ${authenticated ? "authenticated" : "anon"}; Rebase has no such database role, so the rule now requires a ${authenticated ? "signed-in" : "signed-out"} caller instead.`
107
+ };
108
+ }
109
+ /**
110
+ * The plain indexes of a table as `indexes` entries: columns only, no
111
+ * expression, no predicate, btree / gin / brin, not unique (a unique index is
112
+ * the column's `unique`). An index on a link's column alone is left out: the
113
+ * relation indexes it. Everything else is returned in `unsupported`, with the
114
+ * SQL that recreates it.
115
+ */
116
+ function plainIndexes(rows, keyByColumn, linkColumns) {
117
+ const indexes = [];
118
+ const unsupported = [];
119
+ for (const row of rows) {
120
+ const columns = Array.isArray(row.column_names) ? row.column_names : null;
121
+ if (row.unique && columns && columns.length === 1) continue;
122
+ if (columns && columns.length === 1 && linkColumns.has(columns[0]) && row.method === "btree" && !row.predicate) continue;
123
+ const method = row.method === "btree" || row.method === "gin" || row.method === "brin" ? row.method : null;
124
+ const keys = columns?.map((column) => keyByColumn.get(column));
125
+ if (!columns || !method || row.unique || row.predicate || !keys || keys.some((key) => key === void 0)) {
126
+ unsupported.push(row);
127
+ continue;
128
+ }
129
+ const desc = Array.isArray(row.descending) ? row.descending : [];
130
+ const entries = [];
131
+ keys.forEach((key, i) => {
132
+ if (key === void 0) return;
133
+ entries.push(desc[i] && method === "btree" ? {
134
+ column: key,
135
+ direction: "desc"
136
+ } : key);
137
+ });
138
+ const [first, ...more] = entries;
139
+ if (first === void 0) {
140
+ unsupported.push(row);
141
+ continue;
142
+ }
143
+ indexes.push({
144
+ columns: [first, ...more],
145
+ ...method !== "btree" ? { using: method } : {},
146
+ reason: `carried over from ${row.index_name}`
147
+ });
148
+ }
149
+ return {
150
+ indexes,
151
+ unsupported
152
+ };
153
+ }
154
+ /** Functions, triggers and extensions, which no table definition carries. */
155
+ function objectsLeftBehind(objects) {
156
+ return objects.map((object) => ({
157
+ kind: object.kind,
158
+ name: object.name,
159
+ ...object.table_name ? { table: object.table_name } : {},
160
+ why: object.kind === "extension" ? "an extension of the database; enable it on the new one (`CREATE EXTENSION`) if the app uses it" : `a ${object.kind} is not part of a table definition; apply its SQL after \`db push\` (\`rebase cloud db query --file\` on Rebase Cloud)`,
161
+ ...object.definition ? { sql: object.definition } : {}
162
+ }));
163
+ }
164
+ /** The left-behind objects' SQL as one reviewable file. */
165
+ function renderLeftBehindSql(schema, items) {
166
+ const lines = [
167
+ `-- Objects \`rebase schema introspect\` did not carry over from schema "${schema}".`,
168
+ "-- Review each one, then apply after `rebase db push`:",
169
+ "-- psql \"$DATABASE_URL\" -f this-file.sql (or `rebase cloud db query --file this-file.sql`)",
170
+ "-- Functions that referenced Supabase (auth.uid(), auth.users, roles anon/authenticated)",
171
+ "-- need the same edits the tables got: rebase.uid(), the users table, no such roles.",
172
+ ""
173
+ ];
174
+ for (const item of items) {
175
+ lines.push(`-- ${item.kind}: ${item.table ? `${item.table}.` : ""}${item.name}`);
176
+ if (!item.sql) continue;
177
+ lines.push(item.sql.trim().replace(/;?$/, ";"));
178
+ lines.push("");
179
+ }
180
+ return lines.join("\n");
181
+ }
182
+ /** Whether a schema uses Supabase's conventions: an `auth.uid()` default, a foreign key to `auth.users`, a policy for its roles. */
183
+ function looksLikeSupabase(metadata) {
184
+ return metadata.columns.some((col) => /\bauth\.uid\(\)/i.test(col.column_default ?? "")) || (metadata.externalFks ?? []).some(isAuthUsersReference) || (metadata.policies ?? []).some((policy) => policy.roles.some((role) => SUPABASE_ROLES.has(role)));
185
+ }
186
+ //#endregion
9
187
  //#region src/schema/introspect-db-inference.ts
10
188
  var MARKDOWN = [
11
189
  /^#{1,6}\s+.+/m,
@@ -601,15 +779,6 @@ function deriveListProperties(propertiesOrder, hidden = /* @__PURE__ */ new Set(
601
779
  //#endregion
602
780
  //#region src/schema/introspect-db-logic.ts
603
781
  /**
604
- * Introspection logic — pure functions and the pipeline that transforms
605
- * raw PostgreSQL metadata into `backend/schema` source (and, for a project
606
- * with a frontend, `frontend/src/cms` customizations).
607
- *
608
- * This module contains NO side-effects: no fs writes, no pg.Client creation,
609
- * no process.exit. It is imported by introspect-db.ts (the CLI entry-point)
610
- * and consumed directly by tests.
611
- */
612
- /**
613
782
  * The icon a table's name suggests, for its panel customization: `Database`
614
783
  * when the name suggests none (and then no icon is written).
615
784
  */
@@ -978,7 +1147,8 @@ function generateSchemaModules(input) {
978
1147
  ...keyless.map((meta) => meta.name),
979
1148
  ...leaveOut
980
1149
  ]),
981
- checkFacts: input.checkFacts
1150
+ checkFacts: input.checkFacts,
1151
+ ...input.from ? { from: input.from } : {}
982
1152
  });
983
1153
  const unkeyable = /* @__PURE__ */ new Map();
984
1154
  for (const table of describe(/* @__PURE__ */ new Set()).tables) {
@@ -1007,7 +1177,8 @@ function generateSchemaModules(input) {
1007
1177
  table,
1008
1178
  reason
1009
1179
  }))],
1010
- rlsOff: []
1180
+ rlsOff: [],
1181
+ leftBehind: described.leftBehind
1011
1182
  };
1012
1183
  for (const descriptor of described.tables) {
1013
1184
  const meta = tablesMap.get(descriptor.table);
@@ -1381,6 +1552,7 @@ function describeTables(metadata, options = {}) {
1381
1552
  drift: /* @__PURE__ */ new Map(),
1382
1553
  remark: /* @__PURE__ */ new Map()
1383
1554
  };
1555
+ const leftBehind = generate ? objectsLeftBehind(metadata.objects ?? []) : [];
1384
1556
  const note = (table, text, kind = "drift") => {
1385
1557
  const list = notes[kind].get(table) ?? [];
1386
1558
  list.push(text);
@@ -1411,6 +1583,7 @@ function describeTables(metadata, options = {}) {
1411
1583
  if (!generate && row.rls_enabled !== true) unprotected.push(name);
1412
1584
  described.push(row);
1413
1585
  }
1586
+ const servedNames = new Set(described.map((row) => row.table_name));
1414
1587
  const context = {
1415
1588
  metadata,
1416
1589
  schema,
@@ -1418,10 +1591,22 @@ function describeTables(metadata, options = {}) {
1418
1591
  tablesMap,
1419
1592
  enumMap,
1420
1593
  joinTables,
1421
- servedNames: new Set(described.map((row) => row.table_name)),
1594
+ servedNames,
1422
1595
  checkFacts: options.checkFacts ?? /* @__PURE__ */ new Map(),
1423
- note
1596
+ note,
1597
+ leftBehind,
1598
+ supabase: options.from === "supabase"
1424
1599
  };
1600
+ if (generate) for (const check of metadata.checks) {
1601
+ if (!servedNames.has(check.table_name)) continue;
1602
+ leftBehind.push({
1603
+ kind: "check",
1604
+ name: check.constraint_name,
1605
+ table: check.table_name,
1606
+ why: "a CHECK is not part of a table definition: the API validates the bounds it could read, and the database stops enforcing it",
1607
+ sql: `ALTER TABLE ${quoteIdent(schema)}.${quoteIdent(check.table_name)} ADD CONSTRAINT ${quoteIdent(check.constraint_name)} ${check.definition};`
1608
+ });
1609
+ }
1425
1610
  const shapes = /* @__PURE__ */ new Map();
1426
1611
  for (const row of described) {
1427
1612
  const meta = tablesMap.get(row.table_name);
@@ -1437,7 +1622,8 @@ function describeTables(metadata, options = {}) {
1437
1622
  skipped,
1438
1623
  junctions,
1439
1624
  unprotected,
1440
- notes
1625
+ notes,
1626
+ leftBehind
1441
1627
  };
1442
1628
  }
1443
1629
  var quoteIdent = (name) => `"${name.replace(/"/g, "\"\"")}"`;
@@ -1455,6 +1641,16 @@ function linkableForeignKeys(meta, context) {
1455
1641
  const fk = rows[0];
1456
1642
  if (rows.length > 1) {
1457
1643
  context.note(meta.name, `the foreign key ${constraint} spans (${rows.map((r) => r.column_name).join(", ")}); a relation holds one column, so its columns are plain columns.`);
1644
+ if (context.generate) {
1645
+ const ordered = [...rows].sort((a, b) => (a.ordinal ?? 0) - (b.ordinal ?? 0));
1646
+ context.leftBehind.push({
1647
+ kind: "foreign key",
1648
+ name: constraint,
1649
+ table: meta.name,
1650
+ why: "a foreign key over several columns has no relation to hold it; `db push` leaves it where it is, and a new database needs its SQL",
1651
+ sql: `ALTER TABLE ${quoteIdent(context.schema)}.${quoteIdent(meta.name)} ADD CONSTRAINT ${quoteIdent(constraint)} FOREIGN KEY (${ordered.map((r) => quoteIdent(r.column_name)).join(", ")}) REFERENCES ${quoteIdent(context.schema)}.${quoteIdent(fk.foreign_table_name)} (${ordered.map((r) => quoteIdent(r.foreign_column_name)).join(", ")})${fk.delete_rule && fk.delete_rule !== "NO ACTION" ? ` ON DELETE ${fk.delete_rule}` : ""};`
1652
+ });
1653
+ }
1458
1654
  continue;
1459
1655
  }
1460
1656
  if (!context.servedNames.has(fk.foreign_table_name)) continue;
@@ -1592,6 +1788,29 @@ function describeColumn(col, key, meta, context, facts) {
1592
1788
  */
1593
1789
  function applyGeneratedFacts(out, col, meta, context) {
1594
1790
  const name = col.column_name.toLowerCase();
1791
+ const authRef = (context.metadata.externalFks ?? []).find((fk) => fk.table_name === meta.name && fk.column_name === col.column_name && isAuthUsersReference(fk));
1792
+ const callerDefault = isCallerIdDefault(col.column_default);
1793
+ if (context.supabase && (authRef || callerDefault) && !out.primaryKey && out.generated === void 0) {
1794
+ out.semantic = "user";
1795
+ if (out.type.kind === "uuid") {
1796
+ out.type = { kind: "text" };
1797
+ context.note(meta.name, `"${col.column_name}" held a Supabase user id as uuid; it is text, as \`rebase.users.id\` and \`rebase.uid()\` are, so policies compare like with like.`, "remark");
1798
+ }
1799
+ if (callerDefault) {
1800
+ out.stamp = {
1801
+ on: "create",
1802
+ value: "user"
1803
+ };
1804
+ delete out.default;
1805
+ context.note(meta.name, `"${col.column_name}" defaulted to auth.uid(); it is \`.onCreateUser()\`: the server writes the caller's id on create.`, "remark");
1806
+ }
1807
+ if (authRef) context.leftBehind.push({
1808
+ kind: "foreign key",
1809
+ name: authRef.constraint_name ?? `${col.column_name} → auth.users`,
1810
+ table: meta.name,
1811
+ why: `"${col.column_name}" referenced auth.users(id). It is declared \`.userId()\`; for the database to enforce it, add \`rel.belongsTo(() => users)\` against the project's users table` + (authRef.delete_rule ? ` (it was ON DELETE ${authRef.delete_rule})` : "")
1812
+ });
1813
+ }
1595
1814
  const temporal = out.type.kind === "timestamptz" || out.type.kind === "date" || out.type.kind === "time";
1596
1815
  const nowDefault = out.default?.kind === "sql" && /^(now\(\)|CURRENT_TIMESTAMP)$/i.test(out.default.expression);
1597
1816
  if (temporal && !out.primaryKey && out.generated === void 0) {
@@ -1880,6 +2099,20 @@ function describeTable(row, shape, shapes, context) {
1880
2099
  rls: rlsOf(row, name, context)
1881
2100
  };
1882
2101
  if (shape.search) descriptor.search = shape.search;
2102
+ if (context.generate && context.metadata.indexDefinitions) {
2103
+ const { indexes, unsupported } = plainIndexes(context.metadata.indexDefinitions.filter((index) => index.table_name === name), shape.keyByColumn, new Set(shape.links.map((link) => link.fk.column_name)));
2104
+ if (indexes.length > 0) descriptor.indexes = indexes;
2105
+ for (const index of unsupported) {
2106
+ if (index.unique && !index.predicate && Array.isArray(index.column_names)) continue;
2107
+ context.leftBehind.push({
2108
+ kind: "index",
2109
+ name: index.index_name,
2110
+ table: name,
2111
+ why: "an index on an expression, with a predicate, unique, or of a method `indexes` does not declare",
2112
+ sql: `${index.definition};`
2113
+ });
2114
+ }
2115
+ }
1883
2116
  return descriptor;
1884
2117
  }
1885
2118
  /**
@@ -1986,7 +2219,7 @@ var adminBaselineNames = (table) => tableGeneratedPolicyNames({
1986
2219
  auth: false
1987
2220
  });
1988
2221
  /** A `pg_policies` row as the rule `db push` compiles back into it. */
1989
- function ruleOf(policy) {
2222
+ function readRule(policy) {
1990
2223
  const cmd = policy.cmd.toUpperCase();
1991
2224
  return policyToSecurityRule({
1992
2225
  policyname: policy.policy_name,
@@ -2026,7 +2259,7 @@ function rlsOf(row, table, context) {
2026
2259
  };
2027
2260
  return {
2028
2261
  posture: "rules",
2029
- rules: (policies ?? []).map(ruleOf),
2262
+ rules: (policies ?? []).map(readRule),
2030
2263
  defaultPolicies: false
2031
2264
  };
2032
2265
  }
@@ -2036,8 +2269,15 @@ function rlsOf(row, table, context) {
2036
2269
  defaultPolicies: true
2037
2270
  };
2038
2271
  const baseline = adminBaselineNames(table);
2272
+ const ruleOf = (policy) => {
2273
+ if (!context.supabase) return readRule(policy);
2274
+ const translated = translateSupabaseRoles(readRule(policy));
2275
+ if (translated.note) context.note(table, translated.note, "remark");
2276
+ return translated.rule;
2277
+ };
2278
+ const rules = (list) => list.map(ruleOf).filter((rule) => rule !== null);
2039
2279
  if (row.rls_enabled === false) {
2040
- const own = policies.filter((policy) => !baseline.has(policy.policy_name)).map(ruleOf);
2280
+ const own = rules(policies.filter((policy) => !baseline.has(policy.policy_name)));
2041
2281
  return own.length > 0 ? {
2042
2282
  posture: "rules",
2043
2283
  rules: own,
@@ -2055,7 +2295,7 @@ function rlsOf(row, table, context) {
2055
2295
  defaultPolicies: true
2056
2296
  };
2057
2297
  const keepsBaseline = [...baseline].every((name) => present.has(name));
2058
- const own = policies.filter((policy) => !(keepsBaseline && baseline.has(policy.policy_name))).map(ruleOf);
2298
+ const own = rules(policies.filter((policy) => !(keepsBaseline && baseline.has(policy.policy_name))));
2059
2299
  if (keepsBaseline) return own.length > 0 ? {
2060
2300
  posture: "rules",
2061
2301
  rules: own,
@@ -2070,17 +2310,14 @@ function rlsOf(row, table, context) {
2070
2310
  rules: own,
2071
2311
  defaultPolicies: false
2072
2312
  };
2313
+ context.note(table, `"${table}" has row-level security on and no policy: it is "admin-only", so server code (\`rebase.dataAsAdmin\`) and admins reach it. Write \`rls: [{ operation: "all", using: "false" }]\` to keep it closed to admins too.`, "remark");
2073
2314
  return {
2074
- posture: "rules",
2075
- rules: [{
2076
- name: `${table}_closed`,
2077
- operation: "all",
2078
- using: "false"
2079
- }],
2080
- defaultPolicies: false
2315
+ posture: "admin-only",
2316
+ rules: [],
2317
+ defaultPolicies: true
2081
2318
  };
2082
2319
  }
2083
2320
  //#endregion
2084
- export { describeRlsOffTables as a, mergeIndexModule as c, lookupCandidates as d, CMS_PACKAGE as f, buildTablesMap as i, safeHostFromUrl as l, introspectTables as n, generateSchemaModules as o, buildEnumMap as r, identifyJoinTables as s, describeUnmappedTables as t, classifyTables as u };
2321
+ export { describeRlsOffTables as a, mergeIndexModule as c, lookupCandidates as d, CMS_PACKAGE as f, buildTablesMap as i, safeHostFromUrl as l, renderLeftBehindSql as m, introspectTables as n, generateSchemaModules as o, looksLikeSupabase as p, buildEnumMap as r, identifyJoinTables as s, describeUnmappedTables as t, classifyTables as u };
2085
2322
 
2086
- //# sourceMappingURL=introspect-tables-Cw_A-kk4.js.map
2323
+ //# sourceMappingURL=introspect-tables-2yJ3p98l.js.map