@rebasepro/server-postgres 0.33.2 → 0.34.1

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
@@ -114,11 +114,19 @@ export declare function fromAlterTable(statement: string): string;
114
114
  * `timestamptz(3)` → `timestamptz`);
115
115
  * - `smallint` → `integer` → `bigint`, and any of them to a `numeric` with
116
116
  * room for all their digits;
117
- * - `varchar(n)` → `text`, and `text` → an unbounded `varchar`.
117
+ * - `varchar(n)` → `text`, and `text` → an unbounded `varchar`;
118
+ * - `uuid` → `text` (or a `varchar` of 36 or more), its one exact spelling.
118
119
  *
119
120
  * Arrays follow their element type, and never gain or lose a dimension.
120
121
  */
121
122
  export declare function isLosslessTypeChange(from: string, to: string): boolean;
123
+ /**
124
+ * What a set of findings does, for the line above them: how many destroy data
125
+ * and how many only drop a constraint the database enforces. A dropped CHECK
126
+ * or foreign key loses no row, and a header saying "DESTROY data" above a line
127
+ * saying "no row is lost" read as a contradiction.
128
+ */
129
+ export declare function describeDestructiveFindings(found: readonly DestructiveStatement[]): string;
122
130
  export type PushDecision = "apply" | "confirm" | "refuse";
123
131
  /**
124
132
  * The flag that opted a push into destructive changes, as it was given —
@@ -2,15 +2,15 @@
2
2
  import { createRequire as __createRequire } from "module";
3
3
  __createRequire(import.meta.url);
4
4
  import { i as buildTableSearchColumnSpec } from "../search-column-BO-WND-B.js";
5
- import { c as diagnoseDbError, m as parseHostInfo, o as deepestErrorMessage } from "../cli-schema-dir-CjDH_31U.js";
6
- import { C as warnOnAnonymousGrants, S as validatePolicyPgRoles } from "../rls-enforcement-Ck-d8zdJ.js";
5
+ import { c as diagnoseDbError, m as parseHostInfo, o as deepestErrorMessage } from "../cli-schema-dir-CdEqBcph.js";
6
+ import { C as warnOnAnonymousGrants, S as validatePolicyPgRoles } from "../rls-enforcement-NZKe3Jr-.js";
7
7
  import { i as outError, n as describeFailure, r as out, t as chalk } from "../source-VxbrQojV.js";
8
8
  import { n as planSchema, t as pgTypeOf } from "../plan-schema-Hbtjhge3.js";
9
9
  import { t as generateSchema } from "../generate-drizzle-schema-logic-DL7R1rAF.js";
10
10
  import { i as renderPgType } from "../render-ddl-D4n86NHz.js";
11
11
  import { n as loadTableSchema, r as loadTables, t as defaultDatabaseSchemaVersion } from "../load-tables-B1Re74ng.js";
12
- import { r as readGeneratedSchemaDrift, t as describeSchemaDifference } from "../generated-schema-diff-DoT2dYDe.js";
13
- import { i as hasDrift, r as formatPolicyDrift, t as checkPolicyDrift } from "../policy-drift-rVLKS2AG.js";
12
+ import { r as readGeneratedSchemaDrift, t as describeSchemaDifference } from "../generated-schema-diff-DDktAATD.js";
13
+ import { i as hasDrift, r as formatPolicyDrift, t as checkPolicyDrift } from "../policy-drift-B2Czzs2Z.js";
14
14
  import { n as describeDeclarationDifferences, t as compareGeneratedDeclarations } from "../generated-schema-staleness-YBVq2kTn.js";
15
15
  import { describeMismatch } from "@rebasepro/server";
16
16
  import { DEFAULT_DATA_SOURCE_KEY, LEGACY_SCHEMA_VERSION_PREFIX, isNumericColumnType, isTemporalColumnType } from "@rebasepro/types";
@@ -1763,8 +1763,8 @@ async function runDatabasePreflight(schemaDir, databaseUrl) {
1763
1763
  return "unchecked";
1764
1764
  }
1765
1765
  const { loadTables } = await import("../load-tables-B1Re74ng.js").then((n) => n.i);
1766
- const { preflightDatabase } = await import("../database-preflight-DKzsGnc4.js");
1767
- const { readRecordedRequestRoles } = await import("../rls-enforcement-Ck-d8zdJ.js").then((n) => n.y);
1766
+ const { preflightDatabase } = await import("../database-preflight-NmFI_rFN.js");
1767
+ const { readRecordedRequestRoles } = await import("../rls-enforcement-NZKe3Jr-.js").then((n) => n.y);
1768
1768
  const { cliRlsSettings } = await import("../rls-settings-CmGK2U0a.js").then((n) => n.a);
1769
1769
  const { Pool } = await import("pg");
1770
1770
  const pool = new Pool({ connectionString: databaseUrl });
@@ -1,3 +1,13 @@
1
+ /**
2
+ * Introspection logic — pure functions and the pipeline that transforms
3
+ * raw PostgreSQL metadata into `backend/schema` source (and, for a project
4
+ * with a frontend, `frontend/src/cms` customizations).
5
+ *
6
+ * This module contains NO side-effects: no fs writes, no pg.Client creation,
7
+ * no process.exit. It is imported by introspect-db.ts (the CLI entry-point)
8
+ * and consumed directly by tests.
9
+ */
10
+ import type { LeftBehind } from "./introspect-foreign.js";
1
11
  import { mapPgType } from "./introspect-db-types.js";
2
12
  import type { CheckFactsByTable } from "./introspect-db-constraints.js";
3
13
  import type { TableClassification } from "./introspect-db-structure.js";
@@ -57,6 +67,33 @@ export interface ForeignKeyRow {
57
67
  ordinal?: number;
58
68
  /** `"CASCADE"`, `"RESTRICT"`, `"SET NULL"`, `"SET DEFAULT"`, `"NO ACTION"`. */
59
69
  delete_rule?: string;
70
+ /** The schema the referenced table is in. Absent from rows read before this was asked. */
71
+ foreign_schema?: string;
72
+ }
73
+ /** A plain index: columns only, no expression, as `defineTable`'s `indexes` can declare it. */
74
+ export interface IndexDefinitionRow {
75
+ table_name: string;
76
+ index_name: string;
77
+ /** The index method: `btree`, `gin`, `brin`, …. */
78
+ method: string;
79
+ unique: boolean;
80
+ /** `null` when a key is an expression. */
81
+ column_names: string[] | null;
82
+ /** Per key, whether it sorts descending. */
83
+ descending: boolean[] | null;
84
+ /** The WHERE of a partial index, or null. */
85
+ predicate: string | null;
86
+ /** `pg_get_indexdef`, for the report when it cannot be declared. */
87
+ definition: string;
88
+ }
89
+ /** A database object a table definition does not carry: a function, a trigger, an extension. */
90
+ export interface DatabaseObjectRow {
91
+ kind: "function" | "trigger" | "extension";
92
+ name: string;
93
+ /** The table a trigger is on. */
94
+ table_name?: string | null;
95
+ /** The SQL that recreates it, when Postgres can print it. */
96
+ definition?: string | null;
60
97
  }
61
98
  /** A unique constraint or unique index, as an ordered column list. */
62
99
  export interface UniqueConstraintRow {
@@ -129,6 +166,16 @@ export interface SchemaMetadata {
129
166
  * the caller did not read them, and then no collection is given rules.
130
167
  */
131
168
  policies?: PolicyRow[];
169
+ /**
170
+ * Foreign keys from the introspected tables to tables in another schema
171
+ * (Supabase's `auth.users`). No relation can hold one; read so they are
172
+ * reported rather than dropped without a word.
173
+ */
174
+ externalFks?: ForeignKeyRow[];
175
+ /** Every index, with its columns, so the plain ones become `indexes`. */
176
+ indexDefinitions?: IndexDefinitionRow[];
177
+ /** Functions, triggers and extensions: what a table definition does not carry, for the report. */
178
+ objects?: DatabaseObjectRow[];
132
179
  /**
133
180
  * Row counts for the tables that needed one, capped — see `countRowsUpTo`.
134
181
  * Absent for every table introspection never had a reason to count.
@@ -234,6 +281,8 @@ export interface SchemaGenerationInput {
234
281
  cms?: {
235
282
  tableImport: (table: string) => string;
236
283
  };
284
+ /** `schema introspect --from supabase`: see `DescribeTablesOptions.from`. */
285
+ from?: "supabase";
237
286
  /** Where the builders are imported from. `@rebasepro/server/schema` when omitted. */
238
287
  specifier?: string;
239
288
  }
@@ -265,6 +314,8 @@ export interface SchemaGeneration {
265
314
  }[];
266
315
  /** The generated tables whose row-level security is off: the first push switches it on. */
267
316
  rlsOff: string[];
317
+ /** What the files do not carry, each with why and the SQL that recreates it (`describeTables`). */
318
+ leftBehind: LeftBehind[];
268
319
  }
269
320
  /**
270
321
  * The source `rebase schema introspect` writes for a database: one
@@ -16,3 +16,9 @@ export declare function findProjectRoot(from: string): string | undefined;
16
16
  * import the file opens with, and a headless project could not resolve it.
17
17
  */
18
18
  export declare function detectCmsDir(schemaDir: string): string | undefined;
19
+ /**
20
+ * Whether the project's `.env` names the database this run read, which is when
21
+ * the next `db push` would write into it. A read from `--database-url`, with
22
+ * `.env` naming another database or none (the managed one), is not that case.
23
+ */
24
+ export declare function projectEnvNames(envFile: string | undefined, databaseUrl: string): boolean;
@@ -105,7 +105,7 @@ export declare const PRIMARY_KEYS_QUERY = "\n SELECT t.relname AS table_name,
105
105
  * declares the key on the parent *and* inherits it onto 26 partitions does not
106
106
  * yield 27 copies of the same relation.
107
107
  */
108
- export declare 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";
108
+ export declare 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";
109
109
  /**
110
110
  * Unique constraints and unique indexes, as ordered column lists.
111
111
  *
@@ -126,6 +126,17 @@ export declare const UNIQUE_CONSTRAINTS_QUERY = "\n SELECT t.relname AS table
126
126
  * `leading_column` is null when the first key is an expression.
127
127
  */
128
128
  export declare 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";
129
+ /**
130
+ * Every non-primary index with its keys: the plain ones (columns, no
131
+ * expression) become a table's `indexes`; the rest are reported.
132
+ */
133
+ export declare 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";
134
+ /**
135
+ * The functions and triggers of the schema, and the extensions of the
136
+ * database: objects a table definition does not carry, read only so the run
137
+ * can say they were left behind. Functions an extension owns are left out.
138
+ */
139
+ export declare 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";
129
140
  /**
130
141
  * CHECK constraints, as the source text Postgres reproduces them from.
131
142
  *
@@ -173,4 +184,12 @@ export declare function countRowsUpTo(client: QueryableClient, schema: string, t
173
184
  * a handful of tables can possibly need it. The caller fills it in for the
174
185
  * candidates `lookupCandidates()` names.
175
186
  */
176
- export declare function readSchemaMetadata(client: QueryableClient, schema: string): Promise<SchemaMetadata>;
187
+ export declare function readSchemaMetadata(client: QueryableClient, schema: string,
188
+ /**
189
+ * `true` for `schema introspect`: also read each index's columns and the
190
+ * functions, triggers and extensions, which only the generator and its
191
+ * "not carried over" report use. The runtime's read at boot leaves them out.
192
+ */
193
+ options?: {
194
+ forGeneration?: boolean;
195
+ }): Promise<SchemaMetadata>;
@@ -2,10 +2,10 @@ import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { n as require_arg, o as __toESM, t as promptConfirm } from "../cli-prompt-DXG0yk-h.js";
4
4
  import { u as pinSearchPath } from "../connection-C1zXTPJq.js";
5
- import { c as diagnoseDbError } from "../cli-schema-dir-CjDH_31U.js";
5
+ import { c as diagnoseDbError } from "../cli-schema-dir-CdEqBcph.js";
6
6
  import { a as outWarn, i as outError, r as out, t as chalk } from "../source-VxbrQojV.js";
7
- import { i as readSchemaMetadata, n as isUsableFileName, r as quoteRelation, t as countRowsUpTo } from "../introspect-db-queries-BgiRQqtR.js";
8
- import { a as describeRlsOffTables, c as mergeIndexModule, d as lookupCandidates, i as buildTablesMap, l as safeHostFromUrl, o as generateSchemaModules, u as classifyTables } from "../introspect-tables-Cw_A-kk4.js";
7
+ import { i as readSchemaMetadata, n as isUsableFileName, r as quoteRelation, t as countRowsUpTo } from "../introspect-db-queries-D7u9EOfV.js";
8
+ import { a as describeRlsOffTables, c as mergeIndexModule, d as lookupCandidates, i as buildTablesMap, l as safeHostFromUrl, m as renderLeftBehindSql, o as generateSchemaModules, p as looksLikeSupabase, u as classifyTables } from "../introspect-tables-2yJ3p98l.js";
9
9
  import pg from "pg";
10
10
  import { printIndexModule, tableIdentifier } from "@rebasepro/common";
11
11
  import path from "path";
@@ -74,6 +74,20 @@ function detectCmsDir(schemaDir) {
74
74
  if (!fs.existsSync(frontend)) return void 0;
75
75
  for (const manifest of [path.join(frontend, "package.json"), path.join(root, "package.json")]) if (fs.existsSync(manifest) && declaredDependencies(manifest).has("@rebasepro/cms")) return path.join(frontend, "src", "cms");
76
76
  }
77
+ /**
78
+ * Whether the project's `.env` names the database this run read, which is when
79
+ * the next `db push` would write into it. A read from `--database-url`, with
80
+ * `.env` naming another database or none (the managed one), is not that case.
81
+ */
82
+ function projectEnvNames(envFile, databaseUrl) {
83
+ if (!envFile) return false;
84
+ try {
85
+ const named = dotenv.parse(fs.readFileSync(envFile, "utf-8")).DATABASE_URL;
86
+ return named !== void 0 && named.trim() === databaseUrl.trim();
87
+ } catch {
88
+ return false;
89
+ }
90
+ }
77
91
  //#endregion
78
92
  //#region src/schema/introspect-db-constraints.ts
79
93
  /** The length functions whose argument is the column being constrained. */
@@ -412,23 +426,31 @@ async function main() {
412
426
  "--schema": String,
413
427
  "--data-inference": Boolean,
414
428
  "--no-data-inference": Boolean,
429
+ "--from": String,
415
430
  "-f": "--force"
416
431
  }, { permissive: true });
417
432
  const outDir = path.resolve(process.cwd(), args["--schema-dir"] || "schema");
418
433
  const cmsDir = detectCmsDir(outDir);
419
434
  const force = args["--force"] || false;
420
435
  const pgSchema = args["--schema"] || "public";
436
+ const from = args["--from"];
437
+ if (from !== void 0 && from !== "supabase") {
438
+ outError(chalk.red(`✗ --from takes "supabase", not "${from}".`));
439
+ process.exit(1);
440
+ }
421
441
  const envPaths = [
422
442
  process.env.DOTENV_CONFIG_PATH,
423
443
  path.resolve(process.cwd(), ".env"),
424
444
  path.resolve(process.cwd(), "../.env"),
425
445
  path.resolve(process.cwd(), "../../.env")
426
446
  ].filter(Boolean);
447
+ let envFileUsed;
427
448
  for (const p of envPaths) if (fs.existsSync(p)) {
428
449
  dotenv.config({
429
450
  path: p,
430
451
  quiet: true
431
452
  });
453
+ envFileUsed = p;
432
454
  break;
433
455
  }
434
456
  const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;
@@ -453,7 +475,7 @@ async function main() {
453
475
  out(chalk.gray(`Connected to database: ${hostPart}`));
454
476
  out(chalk.gray(`Introspecting schema '${pgSchema}'...`));
455
477
  try {
456
- const metadata = await readSchemaMetadata(client, pgSchema);
478
+ const metadata = await readSchemaMetadata(client, pgSchema, { forGeneration: true });
457
479
  const tablesMap = buildTablesMap(metadata.tables, metadata.columns, metadata.pks, metadata.fks);
458
480
  for (const table of lookupCandidates(metadata, tablesMap)) try {
459
481
  metadata.rowCounts[table] = await countRowsUpTo(client, pgSchema, table, 50);
@@ -492,6 +514,7 @@ async function main() {
492
514
  checkFacts,
493
515
  samples,
494
516
  leaveOut: unusable,
517
+ ...from === "supabase" ? { from: "supabase" } : {},
495
518
  ...cmsDir ? { cms: { tableImport: (table) => relativeImport(cmsDir, path.join(outDir, `${table}.ts`)) } } : {}
496
519
  });
497
520
  for (const { table, reason } of generation.failed) outWarn(chalk.yellow(`⚠ Skipping table ${JSON.stringify(table)}: ${reason}`));
@@ -553,6 +576,27 @@ async function main() {
553
576
  }
554
577
  out(chalk.green(` ✓ ${indexPath}`));
555
578
  }
579
+ if (from !== "supabase" && looksLikeSupabase(metadata)) {
580
+ outWarn("");
581
+ outWarn(chalk.yellow("⚠ This schema uses Supabase's conventions (auth.uid() defaults, auth.users foreign keys, TO anon / TO authenticated)."));
582
+ outWarn(chalk.gray(" Leaving Supabase? Run again with --from supabase to translate them for a Rebase database."));
583
+ outWarn(chalk.gray(" Keep them as they are only if Rebase will run on this same database, beside Supabase."));
584
+ }
585
+ if (generation.leftBehind.length > 0) {
586
+ outWarn("");
587
+ outWarn(chalk.yellow(`⚠ Not carried over (${generation.leftBehind.length}): these are not part of a table definition.`));
588
+ for (const item of generation.leftBehind) outWarn(chalk.gray(` - ${item.kind} ${item.table ? `${item.table}.` : ""}${item.name}: ${item.why}`));
589
+ const withSql = generation.leftBehind.filter((item) => item.sql);
590
+ if (withSql.length > 0) {
591
+ const sqlPath = path.join(path.dirname(outDir), "sql", "introspected-left-behind.sql");
592
+ fs.mkdirSync(path.dirname(sqlPath), { recursive: true });
593
+ if (!fs.existsSync(sqlPath) || force) {
594
+ fs.writeFileSync(sqlPath, renderLeftBehindSql(pgSchema, withSql), "utf-8");
595
+ outWarn(chalk.gray(` The SQL for ${withSql.length} of them is in ${sqlPath}: review it, then apply it after \`rebase db push\``));
596
+ outWarn(chalk.gray(" (`psql \"$DATABASE_URL\" -f …`, or `rebase cloud db query --file …` on Rebase Cloud)."));
597
+ } else outWarn(chalk.gray(` ${sqlPath} exists; pass --force to rewrite it.`));
598
+ }
599
+ }
556
600
  out("");
557
601
  if (skippedFiles.length > 0) {
558
602
  out(chalk.yellow(`⚠ Skipped ${skippedFiles.length} existing file(s): ${skippedFiles.join(", ")}`));
@@ -562,6 +606,11 @@ async function main() {
562
606
  out(chalk.bold.green(`✓ Introspected ${tablesMap.size} tables — generated ${generatedFiles.length} table(s).`));
563
607
  if (generatedFiles.length > 0) out(chalk.gray(` Review the generated files in ${outDir}.`));
564
608
  if (customizations.length > 0 && cmsDir) out(chalk.gray(` ${customizations.length} panel customization(s) in ${cmsDir}: pass them to <RebaseCMS tableCustomizations={[…]} />.`));
609
+ if (generatedFiles.length > 0 && projectEnvNames(envFileUsed, databaseUrl)) {
610
+ out(chalk.yellow(`⚠ DATABASE_URL still points at the database this read (${hostPart}).`));
611
+ out(chalk.gray(" If it is the source of a migration, point DATABASE_URL at the new database before `rebase db push`;"));
612
+ out(chalk.gray(" pushing now writes the generated tables back into the one just introspected."));
613
+ }
565
614
  out("");
566
615
  } catch (e) {
567
616
  outError(chalk.red(`✗ Error introspecting database: ${e instanceof Error ? e.message : String(e)}`));
@@ -1 +1 @@
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 * Where the project being introspected into keeps what introspection writes.\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: does the project have a\n * frontend that a `customizeTable` file can be written into.\n */\nimport fs from \"fs\";\nimport path from \"path\";\n\nimport { CMS_PACKAGE } from \"./introspect-db-customization\";\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 for (const field of [\"dependencies\", \"devDependencies\", \"peerDependencies\"]) {\n const block: unknown = Reflect.get(parsed, 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 * The project root above a directory: the first ancestor holding a\n * `rebase.json`, or `undefined` when none does within reach.\n */\nexport function findProjectRoot(from: string): string | undefined {\n let dir = path.resolve(from);\n for (let level = 0; level < MAX_LEVELS; level++) {\n if (fs.existsSync(path.join(dir, \"rebase.json\"))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n return undefined;\n}\n\n/**\n * The `frontend/src/cms` directory introspection writes `customizeTable`\n * files into, or `undefined` when the project has no frontend that can import\n * `@rebasepro/cms`.\n *\n * The project root is the one above the schema directory (`rebase.json`), or —\n * in a layout without one — the parent of `backend/`. The frontend is\n * `<root>/frontend`, and it counts only when a manifest on the path a\n * `frontend/src/cms/<table>.tsx` resolves bare specifiers along (the frontend's\n * own `package.json`, then the root's) declares `@rebasepro/cms`: that is the\n * import the file opens with, and a headless project could not resolve it.\n */\nexport function detectCmsDir(schemaDir: string): string | undefined {\n const resolved = path.resolve(schemaDir);\n const root = findProjectRoot(resolved) ?? path.dirname(path.dirname(resolved));\n const frontend = path.join(root, \"frontend\");\n if (!fs.existsSync(frontend)) return undefined;\n for (const manifest of [path.join(frontend, \"package.json\"), path.join(root, \"package.json\")]) {\n if (fs.existsSync(manifest) && declaredDependencies(manifest).has(CMS_PACKAGE)) {\n return path.join(frontend, \"src\", \"cms\");\n }\n }\n return undefined;\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\";\n\nimport { printIndexModule, tableIdentifier } from \"@rebasepro/common\";\n\nimport {\n buildTablesMap,\n describeRlsOffTables,\n generateSchemaModules,\n mergeIndexModule,\n safeHostFromUrl\n} from \"./introspect-db-logic\";\nimport { detectCmsDir } 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\";\nimport { promptConfirm } from \"../cli-prompt\";\nimport { diagnoseDbError } from \"../cli-errors\";\nimport { pinSearchPath } from \"../connection\";\nimport { DEFAULT_SCHEMA_DIR } from \"../cli-schema-dir\";\n\n/** A relative import between two files, POSIX-separated, without the extension. */\nfunction relativeImport(fromDir: string, toFile: string): string {\n const relative = path.relative(fromDir, toFile).split(path.sep).join(\"/\").replace(/\\.tsx?$/, \"\");\n return relative.startsWith(\".\") ? relative : `./${relative}`;\n}\n\nasync function main() {\n const args = arg(\n {\n \"--schema-dir\": String,\n \"--force\": Boolean,\n \"--schema\": String,\n \"--data-inference\": Boolean,\n \"--no-data-inference\": Boolean,\n \"-f\": \"--force\"\n },\n { permissive: true }\n );\n\n // Absolute, because it is printed. Relative to where the driver runs —\n // `backend/` — so the default is `backend/schema`, as every other driver\n // command reads it. The project's `frontend/src/cms`, when it has one, is\n // found from there (`detectCmsDir`).\n const outDir = path.resolve(process.cwd(), args[\"--schema-dir\"] || DEFAULT_SCHEMA_DIR);\n const cmsDir = detectCmsDir(outDir);\n const force = args[\"--force\"] || false;\n const pgSchema = args[\"--schema\"] || \"public\";\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 // Pinned to `public`, as the server's connections are. Postgres spells an\n // expression it read back — a policy's USING, a CHECK, a column default —\n // with every name on the search path unqualified, and under the default\n // `\"$user\", public` a role named `rebase` puts the `rebase` schema on it:\n // `rebase.roles()` came back as `roles()`, which the push, pinned to\n // `public`, could not find.\n const client = new pg.Client({ connectionString: pinSearchPath(databaseUrl) });\n\n try {\n await client.connect();\n } catch (err) {\n // The banner `db push` prints for the same failure, when it is one of\n // the ones it knows.\n const banner = diagnoseDbError(err, databaseUrl);\n if (banner) {\n outError(banner);\n } else {\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 }\n process.exit(1);\n }\n\n // Only once there is something to write into: created before connecting,\n // a run against a database that was down left an empty directory behind.\n if (!fs.existsSync(outDir)) {\n fs.mkdirSync(outDir, { recursive: true });\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 tablesMap = buildTablesMap(metadata.tables, metadata.columns, metadata.pks, 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 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 runDataInference = await promptConfirm(chalk.yellow(\"? Do you want to sample rows to suggest validation and how the panel edits each column? (y/N) \"));\n }\n\n // ── The name has to be usable as a filename ────────────────\n //\n // A table name came out of `pg_class` in a database this tool did\n // not create — adopting somebody else's database is the whole point\n // of introspection — and it is about to be joined onto a path.\n // Postgres will happily hold a table called `../../../etc/cron.d/x`,\n // and `path.join` resolves it. Skipped rather than sanitised: a file\n // named something other than its table does not round-trip.\n const unusable = new Set(Array.from(tablesMap.keys()).filter((t) => !joinTables.has(t) && !isUsableFileName(t)));\n for (const tableName of unusable) {\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 table by hand.\"\n ));\n }\n\n // One table at a time: there is one connection, and sampling ten at\n // once over it is what node-postgres warns about.\n const samples = new Map<string, Record<string, unknown>[]>();\n if (runDataInference) {\n out(chalk.gray(\"Sampling database rows for data inference...\"));\n for (const tableName of tablesMap.keys()) {\n if (joinTables.has(tableName) || unusable.has(tableName)) continue;\n try {\n // Quoted by `quoteRelation`, which doubles an embedded quote.\n const { rows } = await client.query(`SELECT * FROM ${quoteRelation(pgSchema, tableName)} LIMIT 100`);\n samples.set(tableName, 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\n const generation = generateSchemaModules({\n metadata,\n classifications,\n checkFacts,\n samples,\n leaveOut: unusable,\n ...(cmsDir ? { cms: { tableImport: (table: string) => relativeImport(cmsDir, path.join(outDir, `${table}.ts`)) } } : {})\n });\n for (const { table, reason } of generation.failed) {\n outWarn(chalk.yellow(`⚠ Skipping table ${JSON.stringify(table)}: ${reason}`));\n }\n\n const generatedFiles: { identifier: string; table: string }[] = [];\n const skippedFiles: string[] = [];\n const notes: string[] = [];\n const customizations: string[] = [];\n for (const generated of generation.tables) {\n // ── File overwrite protection ──────────────────────────────\n const filePath = path.join(outDir, `${generated.table}.ts`);\n if (fs.existsSync(filePath) && !force) {\n skippedFiles.push(generated.table);\n continue;\n }\n fs.writeFileSync(filePath, generated.schemaModule, \"utf-8\");\n generatedFiles.push({ identifier: generated.identifier, table: generated.table });\n for (const note of generated.notes) notes.push(`${generated.table}: ${note}`);\n out(chalk.green(` ✓ ${filePath}`));\n\n if (cmsDir && generated.customization) {\n const cmsPath = path.join(cmsDir, `${generated.table}.tsx`);\n if (fs.existsSync(cmsPath) && !force) continue;\n fs.mkdirSync(cmsDir, { recursive: true });\n fs.writeFileSync(cmsPath, generated.customization, \"utf-8\");\n customizations.push(generated.table);\n out(chalk.green(` ✓ ${cmsPath}`));\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} note(s) on what \\`rebase db push\\` would not reproduce exactly:`));\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 // And the tables whose access the push changes whatever their files\n // say: no table keeps row-level security off.\n const written = new Set(generatedFiles.map((file) => file.table));\n const rlsOff = describeRlsOffTables(generation.rlsOff.filter((table) => written.has(table)));\n if (rlsOff) {\n const [headline, ...rest] = rlsOff.split(\"\\n\");\n outWarn(\"\");\n outWarn(chalk.yellow(`⚠ ${headline}`));\n for (const line of rest) outWarn(chalk.gray(` ${line}`));\n outWarn(chalk.gray(\" `rebase db push --dry-run` lists every policy it would create.\"));\n }\n\n // backend/schema/index.ts: its exports are the tables the backend\n // serves, so every generated one is exported.\n if (generatedFiles.length > 0) {\n const indexPath = path.join(outDir, \"index.ts\");\n const entries = generatedFiles\n .map((file) => ({ identifier: file.identifier, importPath: `./${file.table}` }))\n .sort((a, b) => a.importPath.localeCompare(b.importPath));\n if (fs.existsSync(indexPath) && !force) {\n fs.writeFileSync(indexPath, mergeIndexModule(fs.readFileSync(indexPath, \"utf-8\"), entries), \"utf-8\");\n } else {\n // --force replaces the tables derived from the database, but the\n // directory can also hold hand-written ones with no table in the\n // introspected schema. An index listing only introspected tables\n // would silently stop serving them.\n const siblings = fs.readdirSync(outDir)\n .filter((f) => f.endsWith(\".ts\") && f !== \"index.ts\")\n .map((f) => f.replace(/\\.ts$/, \"\"))\n .filter((name) => !entries.some((entry) => entry.importPath === `./${name}`))\n .map((name) => ({ identifier: tableIdentifier(name), importPath: `./${name}` }));\n const all = [...entries, ...siblings].sort((a, b) => a.importPath.localeCompare(b.importPath));\n fs.writeFileSync(indexPath, printIndexModule(all), \"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} table(s).`));\n if (generatedFiles.length > 0) {\n out(chalk.gray(` Review the generated files in ${outDir}.`));\n }\n if (customizations.length > 0 && cmsDir) {\n out(chalk.gray(` ${customizations.length} panel customization(s) in ${cmsDir}: pass them to <RebaseCMS tableCustomizations={[…]} />.`));\n }\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));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["../../src/schema/introspect-db-project.ts","../../src/schema/introspect-db-constraints.ts","../../src/schema/introspect-db.ts"],"sourcesContent":["import * as dotenv from \"dotenv\";\n/**\n * Where the project being introspected into keeps what introspection writes.\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: does the project have a\n * frontend that a `customizeTable` file can be written into.\n */\nimport fs from \"fs\";\nimport path from \"path\";\n\nimport { CMS_PACKAGE } from \"./introspect-db-customization\";\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 for (const field of [\"dependencies\", \"devDependencies\", \"peerDependencies\"]) {\n const block: unknown = Reflect.get(parsed, 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 * The project root above a directory: the first ancestor holding a\n * `rebase.json`, or `undefined` when none does within reach.\n */\nexport function findProjectRoot(from: string): string | undefined {\n let dir = path.resolve(from);\n for (let level = 0; level < MAX_LEVELS; level++) {\n if (fs.existsSync(path.join(dir, \"rebase.json\"))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n return undefined;\n}\n\n/**\n * The `frontend/src/cms` directory introspection writes `customizeTable`\n * files into, or `undefined` when the project has no frontend that can import\n * `@rebasepro/cms`.\n *\n * The project root is the one above the schema directory (`rebase.json`), or —\n * in a layout without one — the parent of `backend/`. The frontend is\n * `<root>/frontend`, and it counts only when a manifest on the path a\n * `frontend/src/cms/<table>.tsx` resolves bare specifiers along (the frontend's\n * own `package.json`, then the root's) declares `@rebasepro/cms`: that is the\n * import the file opens with, and a headless project could not resolve it.\n */\nexport function detectCmsDir(schemaDir: string): string | undefined {\n const resolved = path.resolve(schemaDir);\n const root = findProjectRoot(resolved) ?? path.dirname(path.dirname(resolved));\n const frontend = path.join(root, \"frontend\");\n if (!fs.existsSync(frontend)) return undefined;\n for (const manifest of [path.join(frontend, \"package.json\"), path.join(root, \"package.json\")]) {\n if (fs.existsSync(manifest) && declaredDependencies(manifest).has(CMS_PACKAGE)) {\n return path.join(frontend, \"src\", \"cms\");\n }\n }\n return undefined;\n}\n\n/**\n * Whether the project's `.env` names the database this run read, which is when\n * the next `db push` would write into it. A read from `--database-url`, with\n * `.env` naming another database or none (the managed one), is not that case.\n */\nexport function projectEnvNames(envFile: string | undefined, databaseUrl: string): boolean {\n if (!envFile) return false;\n try {\n const named = dotenv.parse(fs.readFileSync(envFile, \"utf-8\")).DATABASE_URL;\n return named !== undefined && named.trim() === databaseUrl.trim();\n } catch {\n return false;\n }\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\";\n\nimport { printIndexModule, tableIdentifier } from \"@rebasepro/common\";\n\nimport {\n buildTablesMap,\n describeRlsOffTables,\n generateSchemaModules,\n mergeIndexModule,\n safeHostFromUrl\n} from \"./introspect-db-logic\";\nimport { detectCmsDir, projectEnvNames } 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 { looksLikeSupabase, renderLeftBehindSql } from \"./introspect-foreign\";\nimport { out, outWarn, outError } from \"../cli-output\";\nimport { promptConfirm } from \"../cli-prompt\";\nimport { diagnoseDbError } from \"../cli-errors\";\nimport { pinSearchPath } from \"../connection\";\nimport { DEFAULT_SCHEMA_DIR } from \"../cli-schema-dir\";\n\n/** A relative import between two files, POSIX-separated, without the extension. */\nfunction relativeImport(fromDir: string, toFile: string): string {\n const relative = path.relative(fromDir, toFile).split(path.sep).join(\"/\").replace(/\\.tsx?$/, \"\");\n return relative.startsWith(\".\") ? relative : `./${relative}`;\n}\n\nasync function main() {\n const args = arg(\n {\n \"--schema-dir\": String,\n \"--force\": Boolean,\n \"--schema\": String,\n \"--data-inference\": Boolean,\n \"--no-data-inference\": Boolean,\n \"--from\": String,\n \"-f\": \"--force\"\n },\n { permissive: true }\n );\n\n // Absolute, because it is printed. Relative to where the driver runs —\n // `backend/` — so the default is `backend/schema`, as every other driver\n // command reads it. The project's `frontend/src/cms`, when it has one, is\n // found from there (`detectCmsDir`).\n const outDir = path.resolve(process.cwd(), args[\"--schema-dir\"] || DEFAULT_SCHEMA_DIR);\n const cmsDir = detectCmsDir(outDir);\n const force = args[\"--force\"] || false;\n const pgSchema = args[\"--schema\"] || \"public\";\n const from = args[\"--from\"];\n if (from !== undefined && from !== \"supabase\") {\n outError(chalk.red(`✗ --from takes \"supabase\", not \"${from}\".`));\n process.exit(1);\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 let envFileUsed: string | undefined;\n for (const p of envPaths) {\n if (fs.existsSync(p)) {\n dotenv.config({ path: p, quiet: true });\n envFileUsed = p;\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 // Pinned to `public`, as the server's connections are. Postgres spells an\n // expression it read back — a policy's USING, a CHECK, a column default —\n // with every name on the search path unqualified, and under the default\n // `\"$user\", public` a role named `rebase` puts the `rebase` schema on it:\n // `rebase.roles()` came back as `roles()`, which the push, pinned to\n // `public`, could not find.\n const client = new pg.Client({ connectionString: pinSearchPath(databaseUrl) });\n\n try {\n await client.connect();\n } catch (err) {\n // The banner `db push` prints for the same failure, when it is one of\n // the ones it knows.\n const banner = diagnoseDbError(err, databaseUrl);\n if (banner) {\n outError(banner);\n } else {\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 }\n process.exit(1);\n }\n\n // Only once there is something to write into: created before connecting,\n // a run against a database that was down left an empty directory behind.\n if (!fs.existsSync(outDir)) {\n fs.mkdirSync(outDir, { recursive: true });\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, { forGeneration: true });\n const tablesMap = buildTablesMap(metadata.tables, metadata.columns, metadata.pks, 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 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 runDataInference = await promptConfirm(chalk.yellow(\"? Do you want to sample rows to suggest validation and how the panel edits each column? (y/N) \"));\n }\n\n // ── The name has to be usable as a filename ────────────────\n //\n // A table name came out of `pg_class` in a database this tool did\n // not create — adopting somebody else's database is the whole point\n // of introspection — and it is about to be joined onto a path.\n // Postgres will happily hold a table called `../../../etc/cron.d/x`,\n // and `path.join` resolves it. Skipped rather than sanitised: a file\n // named something other than its table does not round-trip.\n const unusable = new Set(Array.from(tablesMap.keys()).filter((t) => !joinTables.has(t) && !isUsableFileName(t)));\n for (const tableName of unusable) {\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 table by hand.\"\n ));\n }\n\n // One table at a time: there is one connection, and sampling ten at\n // once over it is what node-postgres warns about.\n const samples = new Map<string, Record<string, unknown>[]>();\n if (runDataInference) {\n out(chalk.gray(\"Sampling database rows for data inference...\"));\n for (const tableName of tablesMap.keys()) {\n if (joinTables.has(tableName) || unusable.has(tableName)) continue;\n try {\n // Quoted by `quoteRelation`, which doubles an embedded quote.\n const { rows } = await client.query(`SELECT * FROM ${quoteRelation(pgSchema, tableName)} LIMIT 100`);\n samples.set(tableName, 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\n const generation = generateSchemaModules({\n metadata,\n classifications,\n checkFacts,\n samples,\n leaveOut: unusable,\n ...(from === \"supabase\" ? { from: \"supabase\" as const } : {}),\n ...(cmsDir ? { cms: { tableImport: (table: string) => relativeImport(cmsDir, path.join(outDir, `${table}.ts`)) } } : {})\n });\n for (const { table, reason } of generation.failed) {\n outWarn(chalk.yellow(`⚠ Skipping table ${JSON.stringify(table)}: ${reason}`));\n }\n\n const generatedFiles: { identifier: string; table: string }[] = [];\n const skippedFiles: string[] = [];\n const notes: string[] = [];\n const customizations: string[] = [];\n for (const generated of generation.tables) {\n // ── File overwrite protection ──────────────────────────────\n const filePath = path.join(outDir, `${generated.table}.ts`);\n if (fs.existsSync(filePath) && !force) {\n skippedFiles.push(generated.table);\n continue;\n }\n fs.writeFileSync(filePath, generated.schemaModule, \"utf-8\");\n generatedFiles.push({ identifier: generated.identifier, table: generated.table });\n for (const note of generated.notes) notes.push(`${generated.table}: ${note}`);\n out(chalk.green(` ✓ ${filePath}`));\n\n if (cmsDir && generated.customization) {\n const cmsPath = path.join(cmsDir, `${generated.table}.tsx`);\n if (fs.existsSync(cmsPath) && !force) continue;\n fs.mkdirSync(cmsDir, { recursive: true });\n fs.writeFileSync(cmsPath, generated.customization, \"utf-8\");\n customizations.push(generated.table);\n out(chalk.green(` ✓ ${cmsPath}`));\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} note(s) on what \\`rebase db push\\` would not reproduce exactly:`));\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 // And the tables whose access the push changes whatever their files\n // say: no table keeps row-level security off.\n const written = new Set(generatedFiles.map((file) => file.table));\n const rlsOff = describeRlsOffTables(generation.rlsOff.filter((table) => written.has(table)));\n if (rlsOff) {\n const [headline, ...rest] = rlsOff.split(\"\\n\");\n outWarn(\"\");\n outWarn(chalk.yellow(`⚠ ${headline}`));\n for (const line of rest) outWarn(chalk.gray(` ${line}`));\n outWarn(chalk.gray(\" `rebase db push --dry-run` lists every policy it would create.\"));\n }\n\n // backend/schema/index.ts: its exports are the tables the backend\n // serves, so every generated one is exported.\n if (generatedFiles.length > 0) {\n const indexPath = path.join(outDir, \"index.ts\");\n const entries = generatedFiles\n .map((file) => ({ identifier: file.identifier, importPath: `./${file.table}` }))\n .sort((a, b) => a.importPath.localeCompare(b.importPath));\n if (fs.existsSync(indexPath) && !force) {\n fs.writeFileSync(indexPath, mergeIndexModule(fs.readFileSync(indexPath, \"utf-8\"), entries), \"utf-8\");\n } else {\n // --force replaces the tables derived from the database, but the\n // directory can also hold hand-written ones with no table in the\n // introspected schema. An index listing only introspected tables\n // would silently stop serving them.\n const siblings = fs.readdirSync(outDir)\n .filter((f) => f.endsWith(\".ts\") && f !== \"index.ts\")\n .map((f) => f.replace(/\\.ts$/, \"\"))\n .filter((name) => !entries.some((entry) => entry.importPath === `./${name}`))\n .map((name) => ({ identifier: tableIdentifier(name), importPath: `./${name}` }));\n const all = [...entries, ...siblings].sort((a, b) => a.importPath.localeCompare(b.importPath));\n fs.writeFileSync(indexPath, printIndexModule(all), \"utf-8\");\n }\n out(chalk.green(` ✓ ${indexPath}`));\n }\n\n // Supabase's conventions, seen in a run that was not asked to translate\n // them: said, because left as they are the first push into a new\n // database fails (`schema \"auth\" does not exist`) or keeps policies for\n // roles it does not have.\n if (from !== \"supabase\" && looksLikeSupabase(metadata)) {\n outWarn(\"\");\n outWarn(chalk.yellow(\"⚠ This schema uses Supabase's conventions (auth.uid() defaults, auth.users foreign keys, TO anon / TO authenticated).\"));\n outWarn(chalk.gray(\" Leaving Supabase? Run again with --from supabase to translate them for a Rebase database.\"));\n outWarn(chalk.gray(\" Keep them as they are only if Rebase will run on this same database, beside Supabase.\"));\n }\n\n // What the files do not carry, said rather than left to silence: a\n // run that listed nothing read as \"everything came across\" while seven\n // functions and two triggers stayed behind. The SQL that recreates each\n // one Postgres can print goes to one file, to review and apply after\n // the first push.\n if (generation.leftBehind.length > 0) {\n outWarn(\"\");\n outWarn(chalk.yellow(`⚠ Not carried over (${generation.leftBehind.length}): these are not part of a table definition.`));\n for (const item of generation.leftBehind) {\n outWarn(chalk.gray(` - ${item.kind} ${item.table ? `${item.table}.` : \"\"}${item.name}: ${item.why}`));\n }\n const withSql = generation.leftBehind.filter((item) => item.sql);\n if (withSql.length > 0) {\n const sqlPath = path.join(path.dirname(outDir), \"sql\", \"introspected-left-behind.sql\");\n fs.mkdirSync(path.dirname(sqlPath), { recursive: true });\n if (!fs.existsSync(sqlPath) || force) {\n fs.writeFileSync(sqlPath, renderLeftBehindSql(pgSchema, withSql), \"utf-8\");\n outWarn(chalk.gray(` The SQL for ${withSql.length} of them is in ${sqlPath}: review it, then apply it after \\`rebase db push\\``));\n outWarn(chalk.gray(\" (`psql \\\"$DATABASE_URL\\\" -f …`, or `rebase cloud db query --file …` on Rebase Cloud).\"));\n } else {\n outWarn(chalk.gray(` ${sqlPath} exists; pass --force to rewrite it.`));\n }\n }\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} table(s).`));\n if (generatedFiles.length > 0) {\n out(chalk.gray(` Review the generated files in ${outDir}.`));\n }\n if (customizations.length > 0 && cmsDir) {\n out(chalk.gray(` ${customizations.length} panel customization(s) in ${cmsDir}: pass them to <RebaseCMS tableCustomizations={[…]} />.`));\n }\n // The database just read is usually the one being left: a migration's\n // source. DATABASE_URL still names it, so the next `db push` would\n // write the generated tables back into it.\n if (generatedFiles.length > 0 && projectEnvNames(envFileUsed, databaseUrl)) {\n out(chalk.yellow(`⚠ DATABASE_URL still points at the database this read (${hostPart}).`));\n out(chalk.gray(\" If it is the source of a migration, point DATABASE_URL at the new database before `rebase db push`;\"));\n out(chalk.gray(\" pushing now writes the generated tables back into the one just introspected.\"));\n }\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":";;;;;;;;;;;;;;;;;;;;;;;AAcA,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,KAAK,MAAM,SAAS;EAAC;EAAgB;EAAmB;CAAkB,GAAG;EACzE,MAAM,QAAiB,QAAQ,IAAI,QAAQ,KAAK;EAChD,IAAI,OAAO,UAAU,YAAY,UAAU,MACvC,KAAK,MAAM,QAAQ,OAAO,KAAK,KAAK,GAAG,MAAM,IAAI,IAAI;CAE7D;CACA,OAAO;AACX;;;;;AAMA,SAAgB,gBAAgB,MAAkC;CAC9D,IAAI,MAAM,KAAK,QAAQ,IAAI;CAC3B,KAAK,IAAI,QAAQ,GAAG,QAAQ,YAAY,SAAS;EAC7C,IAAI,GAAG,WAAW,KAAK,KAAK,KAAK,aAAa,CAAC,GAAG,OAAO;EACzD,MAAM,SAAS,KAAK,QAAQ,GAAG;EAC/B,IAAI,WAAW,KAAK,OAAO,KAAA;EAC3B,MAAM;CACV;AAEJ;;;;;;;;;;;;;AAcA,SAAgB,aAAa,WAAuC;CAChE,MAAM,WAAW,KAAK,QAAQ,SAAS;CACvC,MAAM,OAAO,gBAAgB,QAAQ,KAAK,KAAK,QAAQ,KAAK,QAAQ,QAAQ,CAAC;CAC7E,MAAM,WAAW,KAAK,KAAK,MAAM,UAAU;CAC3C,IAAI,CAAC,GAAG,WAAW,QAAQ,GAAG,OAAO,KAAA;CACrC,KAAK,MAAM,YAAY,CAAC,KAAK,KAAK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MAAM,KAAK,KAAK,eAAe,OAAO,6BAA6B,OAAO,wDAAwD,CAAC;EAK3I,IAAI,eAAe,SAAS,KAAK,gBAAgB,aAAa,WAAW,GAAG;GACxE,IAAI,MAAM,OAAO,0DAA0D,SAAS,GAAG,CAAC;GACxF,IAAI,MAAM,KAAK,uGAAuG,CAAC;GACvH,IAAI,MAAM,KAAK,gFAAgF,CAAC;EACpG;EACA,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"}
@@ -0,0 +1,47 @@
1
+ import type { SecurityRule, TableIndex } from "@rebasepro/types";
2
+ import type { DatabaseObjectRow, ForeignKeyRow, IndexDefinitionRow, SchemaMetadata } from "./introspect-db-logic.js";
3
+ /** A column DEFAULT that is the caller's id: `auth.uid()`, `rebase.uid()`, either inside `(SELECT …)`. */
4
+ export declare function isCallerIdDefault(raw: string | null | undefined): boolean;
5
+ /** A foreign key to Supabase's users table. */
6
+ export declare function isAuthUsersReference(fk: Pick<ForeignKeyRow, "foreign_schema" | "foreign_table_name">): boolean;
7
+ /**
8
+ * A rule read back from a policy, with Supabase's `TO` roles translated into
9
+ * what Rebase means by them, or `null` when the policy only served a role
10
+ * Rebase has no use for (`service_role`, which the server's own context
11
+ * replaces).
12
+ *
13
+ * - `TO authenticated` → the role is dropped and the rule requires a signed-in
14
+ * caller (`policy.authenticated()`'s SQL, ANDed into USING and WITH CHECK).
15
+ * - `TO anon` → dropped, the rule requiring a caller who is *not* signed in.
16
+ * - `TO anon, authenticated` → dropped: every caller, which is no condition.
17
+ * - Any other role is kept as it was.
18
+ */
19
+ export declare function translateSupabaseRoles(rule: SecurityRule): {
20
+ rule: SecurityRule | null;
21
+ note?: string;
22
+ };
23
+ /**
24
+ * The plain indexes of a table as `indexes` entries: columns only, no
25
+ * expression, no predicate, btree / gin / brin, not unique (a unique index is
26
+ * the column's `unique`). An index on a link's column alone is left out: the
27
+ * relation indexes it. Everything else is returned in `unsupported`, with the
28
+ * SQL that recreates it.
29
+ */
30
+ export declare function plainIndexes(rows: readonly IndexDefinitionRow[], keyByColumn: ReadonlyMap<string, string>, linkColumns: ReadonlySet<string>): {
31
+ indexes: TableIndex[];
32
+ unsupported: IndexDefinitionRow[];
33
+ };
34
+ /** One line of the "not carried over" report, and the SQL to recreate it where there is one. */
35
+ export interface LeftBehind {
36
+ kind: "function" | "trigger" | "extension" | "check" | "index" | "foreign key";
37
+ name: string;
38
+ table?: string;
39
+ why: string;
40
+ sql?: string;
41
+ }
42
+ /** Functions, triggers and extensions, which no table definition carries. */
43
+ export declare function objectsLeftBehind(objects: readonly DatabaseObjectRow[]): LeftBehind[];
44
+ /** The left-behind objects' SQL as one reviewable file. */
45
+ export declare function renderLeftBehindSql(schema: string, items: readonly LeftBehind[]): string;
46
+ /** Whether a schema uses Supabase's conventions: an `auth.uid()` default, a foreign key to `auth.users`, a policy for its roles. */
47
+ export declare function looksLikeSupabase(metadata: Pick<SchemaMetadata, "columns" | "externalFks" | "policies">): boolean;