@rebasepro/server-postgres 0.33.1 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/{BranchService-Bdin0Wxh.js → BranchService-BLcVK_Rd.js} +3 -3
  2. package/dist/{BranchService-Bdin0Wxh.js.map → BranchService-BLcVK_Rd.js.map} +1 -1
  3. package/dist/{backup-cli-BEAMPWMs.js → backup-cli-CVLOCTo_.js} +3 -3
  4. package/dist/{backup-cli-BEAMPWMs.js.map → backup-cli-CVLOCTo_.js.map} +1 -1
  5. package/dist/{boot-ddl-Bu6gAY-2.js → boot-ddl-C7hAFEvY.js} +2 -2
  6. package/dist/{boot-ddl-Bu6gAY-2.js.map → boot-ddl-C7hAFEvY.js.map} +1 -1
  7. package/dist/{cli-console-BU_Rf22O.js → cli-console-E5TM3GaL.js} +4 -4
  8. package/dist/{cli-console-BU_Rf22O.js.map → cli-console-E5TM3GaL.js.map} +1 -1
  9. package/dist/{cli-schema-dir-CjDH_31U.js → cli-schema-dir-CdEqBcph.js} +29 -10
  10. package/dist/cli-schema-dir-CdEqBcph.js.map +1 -0
  11. package/dist/cli.js +29 -27
  12. package/dist/cli.js.map +1 -1
  13. package/dist/{database-preflight-DKzsGnc4.js → database-preflight-NmFI_rFN.js} +2 -2
  14. package/dist/{database-preflight-DKzsGnc4.js.map → database-preflight-NmFI_rFN.js.map} +1 -1
  15. package/dist/{deferred-index-build-88bWtYgx.js → deferred-index-build-Bz37bvxW.js} +4 -4
  16. package/dist/{deferred-index-build-88bWtYgx.js.map → deferred-index-build-Bz37bvxW.js.map} +1 -1
  17. package/dist/{ensure-policies-nIITKxud.js → ensure-policies-C1UCom37.js} +6 -6
  18. package/dist/{ensure-policies-nIITKxud.js.map → ensure-policies-C1UCom37.js.map} +1 -1
  19. package/dist/{ensure-tables-hQ5oAK_j.js → ensure-tables-BVUNi6uG.js} +3 -3
  20. package/dist/{ensure-tables-hQ5oAK_j.js.map → ensure-tables-BVUNi6uG.js.map} +1 -1
  21. package/dist/{ensure-tables-Lm-77eM5.js → ensure-tables-DjuNRClr.js} +7 -7
  22. package/dist/{ensure-tables-Lm-77eM5.js.map → ensure-tables-DjuNRClr.js.map} +1 -1
  23. package/dist/{enum-labels-kept-mesgEJWH.js → enum-labels-kept-DrCueSHr.js} +2 -2
  24. package/dist/{enum-labels-kept-mesgEJWH.js.map → enum-labels-kept-DrCueSHr.js.map} +1 -1
  25. package/dist/{generated-schema-diff-DoT2dYDe.js → generated-schema-diff-DDktAATD.js} +2 -2
  26. package/dist/{generated-schema-diff-DoT2dYDe.js.map → generated-schema-diff-DDktAATD.js.map} +1 -1
  27. package/dist/index.es.js +11 -11
  28. package/dist/{introspect-db-queries-BgiRQqtR.js → introspect-db-queries-D7u9EOfV.js} +66 -4
  29. package/dist/introspect-db-queries-D7u9EOfV.js.map +1 -0
  30. package/dist/{introspect-tables-Cw_A-kk4.js → introspect-tables-2yJ3p98l.js} +267 -30
  31. package/dist/introspect-tables-2yJ3p98l.js.map +1 -0
  32. package/dist/{migrate-baseline-Bzj5gSCM.js → migrate-baseline-CnIbBRgh.js} +4 -3
  33. package/dist/{migrate-baseline-Bzj5gSCM.js.map → migrate-baseline-CnIbBRgh.js.map} +1 -1
  34. package/dist/{migrate-policy-stamps-C2WaOEsB.js → migrate-policy-stamps-D7BaYeKO.js} +4 -4
  35. package/dist/{migrate-policy-stamps-C2WaOEsB.js.map → migrate-policy-stamps-D7BaYeKO.js.map} +1 -1
  36. package/dist/{open-rebase-x3yAPy5g.js → open-rebase-DykxNl1j.js} +72 -20
  37. package/dist/open-rebase-DykxNl1j.js.map +1 -0
  38. package/dist/{pg-error-utils-CWopxboq.js → pg-error-utils-DXyqf9yP.js} +2 -2
  39. package/dist/{pg-error-utils-CWopxboq.js.map → pg-error-utils-DXyqf9yP.js.map} +1 -1
  40. package/dist/{policy-drift-rVLKS2AG.js → policy-drift-B2Czzs2Z.js} +3 -3
  41. package/dist/{policy-drift-rVLKS2AG.js.map → policy-drift-B2Czzs2Z.js.map} +1 -1
  42. package/dist/{push-index-adoption-EcamXfW2.js → push-index-adoption-DTLPk_5i.js} +2 -2
  43. package/dist/{push-index-adoption-EcamXfW2.js.map → push-index-adoption-DTLPk_5i.js.map} +1 -1
  44. package/dist/{push-index-prebuild-BPIns6wA.js → push-index-prebuild-WP5272gZ.js} +3 -3
  45. package/dist/{push-index-prebuild-BPIns6wA.js.map → push-index-prebuild-WP5272gZ.js.map} +1 -1
  46. package/dist/{push-legacy-renames-lmYkb41I.js → push-legacy-renames-CvWSBxRu.js} +3 -3
  47. package/dist/{push-legacy-renames-lmYkb41I.js.map → push-legacy-renames-CvWSBxRu.js.map} +1 -1
  48. package/dist/{push-policy-plan-Dqu4FKWh.js → push-policy-plan-D8HvHgPs.js} +3 -3
  49. package/dist/{push-policy-plan-Dqu4FKWh.js.map → push-policy-plan-D8HvHgPs.js.map} +1 -1
  50. package/dist/{request-role-cli-Ay0v9oYZ.js → request-role-cli-Y5Uqalop.js} +8 -8
  51. package/dist/{request-role-cli-Ay0v9oYZ.js.map → request-role-cli-Y5Uqalop.js.map} +1 -1
  52. package/dist/{request-role-migration-DTE3Owsh.js → request-role-migration-Cc0gJSso.js} +2 -2
  53. package/dist/{request-role-migration-DTE3Owsh.js.map → request-role-migration-Cc0gJSso.js.map} +1 -1
  54. package/dist/{rls-enforcement-Ck-d8zdJ.js → rls-enforcement-NZKe3Jr-.js} +2 -2
  55. package/dist/{rls-enforcement-Ck-d8zdJ.js.map → rls-enforcement-NZKe3Jr-.js.map} +1 -1
  56. package/dist/schema/destructive-sql.d.ts +9 -1
  57. package/dist/schema/doctor-cli.js +6 -6
  58. package/dist/schema/introspect-db-logic.d.ts +51 -0
  59. package/dist/schema/introspect-db-project.d.ts +6 -0
  60. package/dist/schema/introspect-db-queries.d.ts +21 -2
  61. package/dist/schema/introspect-db.js +53 -4
  62. package/dist/schema/introspect-db.js.map +1 -1
  63. package/dist/schema/introspect-foreign.d.ts +47 -0
  64. package/dist/schema/introspect-tables.d.ts +17 -0
  65. package/dist/schema/undeclarable-constraints.d.ts +16 -3
  66. package/dist/utils/result-rows.d.ts +20 -0
  67. package/dist/{websocket-DAVDn7Ki.js → websocket-CvmbzBeS.js} +3 -3
  68. package/dist/{websocket-DAVDn7Ki.js.map → websocket-CvmbzBeS.js.map} +1 -1
  69. package/package.json +7 -7
  70. package/dist/cli-schema-dir-CjDH_31U.js.map +0 -1
  71. package/dist/introspect-db-queries-BgiRQqtR.js.map +0 -1
  72. package/dist/introspect-tables-Cw_A-kk4.js.map +0 -1
  73. package/dist/open-rebase-x3yAPy5g.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"introspect-db-queries-BgiRQqtR.js","names":[],"sources":["../src/schema/introspect-db-queries.ts"],"sourcesContent":["/**\n * The catalog queries introspection runs, and the shape they produce.\n *\n * These live apart from {@link ./introspect-db.ts} (the CLI entry point) on\n * purpose: the fixture-capture script and the live e2e read a database through\n * this module too, so what the tests see is what the CLI sees. A query that\n * only exists inside the CLI's `main()` can only be tested by running the CLI.\n *\n * No side effects beyond `SELECT`. Introspection reads a database it does not\n * own — it must never `ANALYZE`, create a temp table, or otherwise write.\n */\nimport type {\n TableRow,\n TableColumn,\n EnumValue,\n PrimaryKeyRow,\n ForeignKeyRow,\n UniqueConstraintRow,\n IndexRow,\n CheckConstraintRow,\n CommentRow,\n PolicyRow,\n SchemaMetadata\n} from \"./introspect-db-logic\";\n\n/** The subset of `pg.Client` this module needs, so tests can pass a fake. */\nexport interface QueryableClient {\n query<R = Record<string, unknown>>(text: string, values?: unknown[]): Promise<{ rows: R[] }>;\n}\n\n/**\n * A Postgres identifier, quoted so that whatever is inside it stays inside it.\n *\n * Introspection reads table and schema names out of `pg_class` and puts them\n * straight back into SQL, and wrapping a name in double quotes is not the same\n * as escaping it: a table named `x\" ; DROP TABLE users; --` closes the quote\n * and then the statement. Postgres's own escape for a quote inside a quoted\n * identifier is to double it, which is what this does.\n *\n * \"The catalogue is trusted\" is true of your own database, and is exactly the\n * assumption this tool cannot make. Introspection exists to be pointed at\n * databases somebody else built, and it runs with the privileges of whoever\n * ran it — which is usually a superuser, because that is who has a connection\n * string to a database they are adopting.\n */\nexport function quoteIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n}\n\n/** `\"schema\".\"table\"`, both halves quoted. */\nexport function quoteRelation(schema: string, table: string): string {\n return `${quoteIdentifier(schema)}.${quoteIdentifier(table)}`;\n}\n\n/**\n * Can this table's name be the name of the file describing it?\n *\n * Introspection writes `<collectionsDir>/<tableName>.ts`, and the table name\n * came from a database this tool did not create. Postgres will hold a table\n * called `../../../etc/cron.d/x`, and `path.join` resolves it — so without this\n * the generator writes a file wherever the name points, as whoever ran the\n * command.\n *\n * Deliberately narrow, and deliberately not a blocklist of `..` and `/`: the\n * question is \"is this a plain file name?\", and every answer that is not\n * obviously yes is a table better written by hand. NUL and the Windows\n * separator are in scope because a collections directory is checked out on\n * whatever machine the developer has.\n */\nexport function isUsableFileName(name: string): boolean {\n if (name.length === 0 || name.length > 200) return false;\n if (name === \".\" || name === \"..\") return false;\n // Path separators (both platforms'), the Windows drive separator, and any\n // control character — a NUL truncates the path at the OS boundary, so a\n // name that reads as harmless in a log can be something else on disk.\n // eslint-disable-next-line no-control-regex\n if (/[/\\\\:\\u0000-\\u001f]/.test(name)) return false;\n // A leading dot makes a hidden file, and a trailing one is invalid on\n // Windows; neither is a table anyone means to generate.\n return !name.startsWith(\".\") && !name.endsWith(\".\");\n}\n\n/**\n * Base tables, excluding partitions.\n *\n * `relispartition` is the reason this reads `pg_class` rather than\n * `information_schema.tables`, which reports every partition as a base table of\n * its own. Pagila partitions `payment` by month; introspected through\n * information_schema it yields `payment` plus 26 near-identical\n * `payment_p2022_*` collections, each with its own nav entry.\n *\n * `relkind = 'p'` (the partitioned parent) is included and `'r'` partitions are\n * dropped, which is the right way round: the parent is the queryable table.\n */\nexport const TABLES_QUERY = `\n SELECT c.relname AS table_name,\n c.relkind = 'p' AS is_partitioned,\n c.relrowsecurity AS rls_enabled\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = $1\n AND c.relkind IN ('r', 'p')\n AND NOT c.relispartition\n AND c.relname NOT LIKE 'drizzle_%'\n AND c.relname NOT LIKE 'rebase_%'\n ORDER BY c.relname\n`;\n\n/**\n * Columns, with the catalog facts that say a column is not the user's to edit.\n *\n * `is_generated`/`is_identity` are read for that reason: a generated column\n * rejects any write, so a form that offers it is offering a field that always\n * errors. `character_maximum_length` is the declared `varchar(n)` bound —\n * already enforced by the database, and free to surface as validation.\n */\nexport const COLUMNS_QUERY = `\n SELECT\n c.table_name,\n c.column_name,\n c.data_type,\n c.udt_name,\n c.is_nullable,\n c.column_default,\n c.ordinal_position,\n c.is_generated,\n c.generation_expression,\n c.is_identity,\n c.identity_generation,\n c.character_maximum_length,\n c.numeric_precision,\n c.numeric_scale,\n (SELECT a.atttypmod FROM pg_attribute a\n JOIN pg_class pc ON a.attrelid = pc.oid\n WHERE pc.relname = c.table_name\n AND a.attname = c.column_name\n AND pc.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = c.table_schema)) as atttypmod,\n (SELECT format_type(a.atttypid, a.atttypmod) FROM pg_attribute a\n JOIN pg_class pc ON a.attrelid = pc.oid\n WHERE pc.relname = c.table_name\n AND a.attname = c.column_name\n AND pc.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = c.table_schema)) as formatted_type\n FROM information_schema.columns c\n WHERE c.table_schema = $1\n ORDER BY c.table_name, c.ordinal_position\n`;\n\nexport const ENUMS_QUERY = `\n SELECT t.typname AS enum_name,\n e.enumlabel AS enum_value,\n e.enumsortorder AS sort_order\n FROM pg_type t\n JOIN pg_enum e ON t.oid = e.enumtypid\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE n.nspname = $1\n ORDER BY t.typname, e.enumsortorder\n`;\n\n/**\n * Primary key columns, in key order.\n *\n * `ORDER BY k.ord` matters for composite keys: the position of a column inside\n * the key is what tells a two-column PK made of two foreign keys apart from an\n * ordinary composite key, and `= ANY(i.indkey)` (the shape this replaced)\n * returns catalog order instead.\n */\nexport const PRIMARY_KEYS_QUERY = `\n SELECT t.relname AS table_name,\n a.attname AS column_name\n FROM pg_index i\n JOIN pg_class t ON t.oid = i.indrelid\n JOIN pg_namespace n ON n.oid = t.relnamespace\n CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord)\n JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum\n WHERE i.indisprimary AND n.nspname = $1\n ORDER BY t.relname, k.ord\n`;\n\n/**\n * Foreign keys, one row per referencing column, with the delete rule.\n *\n * Read from `pg_constraint` rather than through\n * `information_schema.constraint_column_usage`, which does not preserve the\n * pairing on a composite foreign key: it reports the cross product of the\n * constraint's columns, so a two-column FK comes back as four rows, two of them\n * pairing the wrong columns. `unnest(...) WITH ORDINALITY` on both sides joined\n * on the ordinal keeps each referencing column with the column it references.\n *\n * `confdeltype` is carried because `ON DELETE CASCADE` is the schema author\n * saying, in the database, that the child cannot outlive the parent — the one\n * unambiguous declaration of ownership a schema contains.\n *\n * Constraints declared on a *partition* are attributed to the partition root,\n * because that is the table this run generates a collection for. Pagila declares\n * `payment`'s three foreign keys on each monthly partition and none on the\n * parent, so reading `pg_constraint` at face value gives the `payment`\n * collection no relations at all. `pick = 1` then keeps one row per logical key,\n * preferring the root's own constraint when it has one, so a schema that\n * declares the key on the parent *and* inherits it onto 26 partitions does not\n * yield 27 copies of the same relation.\n */\nexport const FOREIGN_KEYS_QUERY = `\n WITH fk AS (\n SELECT con.oid,\n con.conname,\n con.conrelid,\n con.confrelid,\n con.conkey,\n con.confkey,\n con.confdeltype,\n COALESCE(pg_partition_root(con.conrelid), con.conrelid) AS root_oid,\n row_number() OVER (\n PARTITION BY COALESCE(pg_partition_root(con.conrelid), con.conrelid),\n con.confrelid, con.conkey, con.confkey\n ORDER BY (con.conrelid = COALESCE(pg_partition_root(con.conrelid), con.conrelid)) DESC,\n con.oid\n ) AS pick\n FROM pg_constraint con\n JOIN pg_namespace n ON n.oid = con.connamespace\n WHERE con.contype = 'f' AND n.nspname = $1\n )\n SELECT root.relname AS table_name,\n sa.attname AS column_name,\n tgt.relname AS foreign_table_name,\n ta.attname AS foreign_column_name,\n fk.conname AS constraint_name,\n s.ord::int AS ordinal,\n CASE fk.confdeltype\n WHEN 'a' THEN 'NO ACTION'\n WHEN 'r' THEN 'RESTRICT'\n WHEN 'c' THEN 'CASCADE'\n WHEN 'n' THEN 'SET NULL'\n WHEN 'd' THEN 'SET DEFAULT'\n END AS delete_rule\n FROM fk\n JOIN pg_class root ON root.oid = fk.root_oid\n JOIN pg_class tgt ON tgt.oid = fk.confrelid\n CROSS JOIN LATERAL unnest(fk.conkey) WITH ORDINALITY AS s(attnum, ord)\n JOIN pg_attribute sa ON sa.attrelid = fk.conrelid AND sa.attnum = s.attnum\n CROSS JOIN LATERAL unnest(fk.confkey) WITH ORDINALITY AS f(attnum, ord)\n JOIN pg_attribute ta ON ta.attrelid = fk.confrelid AND ta.attnum = f.attnum\n WHERE fk.pick = 1 AND s.ord = f.ord\n ORDER BY root.relname, fk.conname, s.ord\n`;\n\n/**\n * Unique constraints and unique indexes, as ordered column lists.\n *\n * Indexes rather than constraints alone, because `CREATE UNIQUE INDEX` and\n * `ADD CONSTRAINT ... UNIQUE` produce the same guarantee and schemas use both.\n * Partial indexes (`indpred IS NOT NULL`) are excluded: they promise uniqueness\n * only over the rows matching their predicate, which is not the promise a\n * `validation: { unique: true }` field makes.\n */\nexport const UNIQUE_CONSTRAINTS_QUERY = `\n SELECT t.relname AS table_name,\n ic.relname AS constraint_name,\n -- ::text, because the driver has no parser for an array of \\`name\\`\n -- and hands back the raw \\`{a,b}\\` literal as a string. Every consumer\n -- here indexes and compares it as an array, and a string of that\n -- shape fails those silently rather than loudly.\n array_agg(a.attname::text ORDER BY k.ord) AS column_names\n FROM pg_index i\n JOIN pg_class t ON t.oid = i.indrelid\n JOIN pg_class ic ON ic.oid = i.indexrelid\n JOIN pg_namespace n ON n.oid = t.relnamespace\n CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord)\n JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum\n WHERE i.indisunique\n AND NOT i.indisprimary\n AND i.indpred IS NULL\n AND n.nspname = $1\n AND NOT t.relispartition\n GROUP BY t.relname, ic.relname\n ORDER BY t.relname, ic.relname\n`;\n\n/**\n * Every index on the schema's tables: its name, which tells a foreign key\n * Rebase already indexed apart from one it would index on the first push\n * (see `foreignKeyIndexSpec`), and whether it serves an equality lookup on its\n * leading column — a btree with no predicate — which tells one the database\n * already indexes some other way apart from one with no index at all.\n *\n * `leading_column` is null when the first key is an expression.\n */\nexport const INDEXES_QUERY = `\n SELECT t.relname AS table_name,\n ic.relname AS index_name,\n a.attname AS leading_column,\n am.amname = 'btree' AND i.indpred IS NULL AS serves_leading_column\n FROM pg_index i\n JOIN pg_class t ON t.oid = i.indrelid\n JOIN pg_class ic ON ic.oid = i.indexrelid\n JOIN pg_am am ON am.oid = ic.relam\n JOIN pg_namespace n ON n.oid = t.relnamespace\n LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = i.indkey[0] AND i.indkey[0] <> 0\n WHERE n.nspname = $1\n AND NOT t.relispartition\n ORDER BY t.relname, ic.relname\n`;\n\n/**\n * CHECK constraints, as the source text Postgres reproduces them from.\n *\n * `pg_get_constraintdef` output is normalized by the server — the parser in\n * {@link ./introspect-db-constraints.ts} reads that normalized form, not\n * whatever the author typed.\n */\nexport const CHECK_CONSTRAINTS_QUERY = `\n SELECT DISTINCT\n root.relname AS table_name,\n con.conname AS constraint_name,\n pg_get_constraintdef(con.oid) AS definition\n FROM pg_constraint con\n JOIN pg_namespace n ON n.oid = con.connamespace\n JOIN pg_class root ON root.oid = COALESCE(pg_partition_root(con.conrelid), con.conrelid)\n WHERE con.contype = 'c'\n AND n.nspname = $1\n ORDER BY root.relname, con.conname\n`;\n\n/**\n * `COMMENT ON TABLE` / `COMMENT ON COLUMN`, which is documentation the author\n * already wrote and which nothing downstream has ever read.\n *\n * Only comments on relations: `pg_description` also holds the stamps boot\n * writes on each policy (`rebase:<hash>`), and an OID is unique only within\n * its own catalogue, so a policy's could name a table.\n */\nexport const COMMENTS_QUERY = `\n SELECT t.relname AS table_name,\n a.attname AS column_name,\n d.description AS comment\n FROM pg_description d\n JOIN pg_class t ON t.oid = d.objoid\n JOIN pg_namespace n ON n.oid = t.relnamespace\n LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = d.objsubid\n WHERE n.nspname = $1\n AND d.classoid = 'pg_catalog.pg_class'::regclass\n AND t.relkind IN ('r', 'p')\n AND (d.objsubid = 0 OR a.attname IS NOT NULL)\n ORDER BY t.relname, d.objsubid\n`;\n\n/**\n * Every row-level security policy in the schema, as `pg_policies` reports it.\n *\n * A table's policies are its access model. Introspection that leaves them out\n * generates collections describing no rules, and the database's own policies\n * then read as orphans: `doctor` fails on them, and a `db push` drops any\n * whose name has the shape an unnamed rule compiles to.\n */\nexport const POLICIES_QUERY = `\n SELECT tablename AS table_name,\n policyname AS policy_name,\n permissive,\n roles,\n cmd,\n qual,\n with_check\n FROM pg_policies\n WHERE schemaname = $1\n ORDER BY tablename, policyname\n`;\n\n/**\n * Counts a table's rows, stopping once the answer can only be \"more than\n * `limit`\".\n *\n * Introspection asks this to tell a small reference table from a table that\n * merely looks like one (see `classifyTables`). `reltuples` would answer for\n * free but lies on a table that has never been analyzed — which is every table\n * in a database restored from a dump, i.e. exactly the case introspection meets\n * — and reports -1 there rather than an error, so the lie is silent.\n *\n * The subquery's LIMIT caps the work at `limit + 1` rows however large the\n * table is, so this stays cheap on a table with a billion rows.\n */\nexport async function countRowsUpTo(\n client: QueryableClient,\n schema: string,\n table: string,\n limit: number\n): Promise<number> {\n const { rows } = await client.query<{ count: string }>(\n `SELECT count(*)::text AS count FROM (SELECT 1 FROM ${quoteRelation(schema, table)} LIMIT ${limit + 1}) probe`\n );\n return Number(rows[0]?.count ?? 0);\n}\n\n/**\n * Reads everything the generator needs, in one pass.\n *\n * `rowCounts` is deliberately absent here: it costs a query per table and only\n * a handful of tables can possibly need it. The caller fills it in for the\n * candidates `lookupCandidates()` names.\n */\nexport async function readSchemaMetadata(\n client: QueryableClient,\n schema: string\n): Promise<SchemaMetadata> {\n // Sequential, not `Promise.all`. A `pg.Client` is a single connection with\n // one protocol stream: concurrent `query()` calls on one are queued and\n // deprecated (removed in pg@9), so the parallel version buys nothing and\n // warns while doing it.\n const tables = await client.query<TableRow>(TABLES_QUERY, [schema]);\n const columns = await client.query<TableColumn>(COLUMNS_QUERY, [schema]);\n const enumValues = await client.query<EnumValue>(ENUMS_QUERY, [schema]);\n const pks = await client.query<PrimaryKeyRow>(PRIMARY_KEYS_QUERY, [schema]);\n const fks = await client.query<ForeignKeyRow>(FOREIGN_KEYS_QUERY, [schema]);\n const uniques = await client.query<UniqueConstraintRow>(UNIQUE_CONSTRAINTS_QUERY, [schema]);\n const indexes = await client.query<IndexRow>(INDEXES_QUERY, [schema]);\n const checks = await client.query<CheckConstraintRow>(CHECK_CONSTRAINTS_QUERY, [schema]);\n const comments = await client.query<CommentRow>(COMMENTS_QUERY, [schema]);\n const policies = await client.query<PolicyRow>(POLICIES_QUERY, [schema]);\n\n // A column list scoped to the schema still names tables this run excludes —\n // views, partitions, the drizzle bookkeeping tables. Narrow every row set to\n // the tables actually being introspected so downstream code never has to\n // ask whether a table it found in `columns` really exists.\n const known = new Set(tables.rows.map((t) => t.table_name));\n const scoped = <T extends { table_name: string }>(rows: T[]) => rows.filter((r) => known.has(r.table_name));\n\n return {\n schema,\n tables: tables.rows,\n columns: scoped(columns.rows),\n enumValues: enumValues.rows,\n pks: scoped(pks.rows),\n // A foreign key pointing *out* of the introspected set (into another\n // schema, or at a view) cannot be turned into a relation: there is no\n // collection on the other end to link to.\n fks: scoped(fks.rows).filter((fk) => known.has(fk.foreign_table_name)),\n uniques: scoped(uniques.rows),\n indexes: scoped(indexes.rows),\n checks: scoped(checks.rows),\n comments: scoped(comments.rows),\n policies: scoped(policies.rows).map((policy) => ({\n ...policy,\n // node-postgres yields `name[]` as an array; some drivers hand back \"{a,b}\".\n roles: Array.isArray(policy.roles)\n ? policy.roles\n : String(policy.roles ?? \"\").replace(/^\\{|\\}$/g, \"\").split(\",\").filter(Boolean)\n })),\n rowCounts: {}\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA6CA,SAAgB,gBAAgB,MAAsB;CAClD,OAAO,IAAI,KAAK,QAAQ,MAAM,MAAM,EAAE;AAC1C;;AAGA,SAAgB,cAAc,QAAgB,OAAuB;CACjE,OAAO,GAAG,gBAAgB,MAAM,EAAE,GAAG,gBAAgB,KAAK;AAC9D;;;;;;;;;;;;;;;;AAiBA,SAAgB,iBAAiB,MAAuB;CACpD,IAAI,KAAK,WAAW,KAAK,KAAK,SAAS,KAAK,OAAO;CACnD,IAAI,SAAS,OAAO,SAAS,MAAM,OAAO;CAK1C,IAAI,sBAAsB,KAAK,IAAI,GAAG,OAAO;CAG7C,OAAO,CAAC,KAAK,WAAW,GAAG,KAAK,CAAC,KAAK,SAAS,GAAG;AACtD;;;;;;;;;;;;;AAcA,IAAa,eAAe;;;;;;;;;;;;;;;;;;;;;AAsB5B,IAAa,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+B7B,IAAa,cAAc;;;;;;;;;;;;;;;;;;AAmB3B,IAAa,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmClC,IAAa,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDlC,IAAa,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCxC,IAAa,gBAAgB;;;;;;;;;;;;;;;;;;;;;;AAuB7B,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Y,WAAW;EACvB,KAAK,OAAO,IAAI,IAAI;EAIpB,KAAK,OAAO,IAAI,IAAI,CAAC,CAAC,QAAQ,OAAO,MAAM,IAAI,GAAG,kBAAkB,CAAC;EACrE,SAAS,OAAO,QAAQ,IAAI;EAC5B,SAAS,OAAO,QAAQ,IAAI;EAC5B,QAAQ,OAAO,OAAO,IAAI;EAC1B,UAAU,OAAO,SAAS,IAAI;EAC9B,UAAU,OAAO,SAAS,IAAI,CAAC,CAAC,KAAK,YAAY;GAC7C,GAAG;GAEH,OAAO,MAAM,QAAQ,OAAO,KAAK,IAC3B,OAAO,QACP,OAAO,OAAO,SAAS,EAAE,CAAC,CAAC,QAAQ,YAAY,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO;EACtF,EAAE;EACF,WAAW,CAAC;CAChB;AACJ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"introspect-tables-Cw_A-kk4.js","names":[],"sources":["../src/schema/introspect-db-inference.ts","../src/schema/introspect-db-types.ts","../src/schema/introspect-db-customization.ts","../src/schema/introspect-db-structure.ts","../src/schema/introspect-db-logic.ts","../src/schema/introspect-db-storage.ts","../src/schema/introspect-db-search.ts","../src/schema/introspect-tables.ts"],"sourcesContent":["import type { ColumnType, ColumnValidation } from \"@rebasepro/types\";\n\n/**\n * What sampled rows suggest about a column (`schema introspect\n * --data-inference`).\n *\n * The column's type is the catalogue's and is never second-guessed from data:\n * a `smallint` holding only 0s and 1s is still a `smallint`, a `text` of ISO\n * dates is still `text`, and declaring otherwise would plan a type change on\n * the first push. What the rows can add is what the type does not say — a\n * bound the API may check, and how the panel should edit the value.\n */\nexport interface ColumnHints {\n /** Rules the API checks before a write, merged into the column's `.validate()`. */\n validate?: ColumnValidation;\n /** Field options for the panel, written into the table's `customizeTable`. */\n field?: { multiline?: true; markdown?: true; urlPreview?: \"image\" };\n}\n\nconst MARKDOWN = [/^#{1,6}\\s+.+/m, /\\*\\*.+\\*\\*/, /\\[.+\\]\\(.+\\)/, /^\\s*[-*]\\s+.+/m];\nconst IMAGE_FILE = /\\.(jpeg|jpg|gif|png|webp|svg)(\\?|$)/i;\nconst MEDIA_NAME = /image|avatar|photo|logo|cover/;\n\nconst isNumericType = (type: ColumnType): boolean =>\n [\"smallint\", \"integer\", \"bigint\", \"real\", \"doublePrecision\", \"numeric\"].includes(type.kind);\nconst isTextType = (type: ColumnType): boolean => type.kind === \"text\" || type.kind === \"varchar\" || type.kind === \"char\";\n\n/**\n * Read a column's sampled values for what they add to its declared type.\n *\n * - a number column named like a percentage (`*percent*`, `*rate*`, `*score*`)\n * whose values lie in 0–100 is validated to that range; one named like a\n * quantity (`*count*`, `*total*`, `*amount*`) with no negative value, to `min: 0`;\n * - a text column whose every value is an absolute URL is validated as one,\n * and previewed as an image when the values (or the name) say so;\n * - a text column holding markdown is edited as markdown, one holding line\n * breaks or long values in a multi-line box.\n */\nexport function inferColumnHints(columnName: string, type: ColumnType, sampleValues: readonly unknown[]): ColumnHints {\n const values = sampleValues.filter(value => value !== null && value !== undefined && value !== \"\");\n if (values.length === 0) return {};\n const name = columnName.toLowerCase();\n\n if (isNumericType(type)) {\n const numbers = values.map(Number).filter(value => !Number.isNaN(value));\n if (numbers.length !== values.length) return {};\n const min = Math.min(...numbers);\n const max = Math.max(...numbers);\n if (min >= 0 && max <= 100 && /percent|rate|score/.test(name)) return { validate: { min: 0, max: 100 } };\n if (min >= 0 && /count|total|amount/.test(name)) return { validate: { min: 0 } };\n return {};\n }\n\n if (!isTextType(type) || !values.every(value => typeof value === \"string\")) return {};\n const strings = values.filter((value): value is string => typeof value === \"string\");\n const hints: ColumnHints = {};\n if (strings.every(value => value.startsWith(\"http://\") || value.startsWith(\"https://\"))) {\n hints.validate = { url: true };\n if (strings.some(value => IMAGE_FILE.test(value)) || MEDIA_NAME.test(name)) hints.field = { urlPreview: \"image\" };\n return hints;\n }\n const longest = Math.max(...strings.map(value => value.length));\n if (strings.some(value => MARKDOWN.some(pattern => pattern.test(value)))) hints.field = { multiline: true, markdown: true };\n else if (strings.some(value => value.includes(\"\\n\")) || longest > 100) hints.field = { multiline: true };\n return hints;\n}\n","/**\n * The PostgreSQL type → Rebase property type mapping.\n *\n * Split out of `introspect-db-logic` so that the structural analysis can use it\n * without importing the generator, which imports the analysis. Re-exported from\n * `introspect-db-logic` so existing callers keep their import path.\n */\n\n/**\n * Map a PostgreSQL data type to a Rebase property type.\n */\nexport function mapPgType(dataType: string): string {\n const dt = dataType.toLowerCase();\n\n // Interval MUST be checked before numeric (\"interval\" contains \"int\")\n if (dt === \"interval\") return \"string\";\n\n // Array types MUST be checked before numeric (\"_int4\" contains \"int\")\n if (dt === \"array\" || dt.startsWith(\"_\")) return \"array\";\n\n // Numeric types\n if (\n dt.includes(\"int\") || // integer, smallint, bigint\n dt.includes(\"numeric\") ||\n dt.includes(\"decimal\") ||\n dt.includes(\"serial\") || // serial, bigserial\n dt === \"real\" ||\n dt === \"float4\" ||\n dt === \"float8\" ||\n dt === \"double precision\" ||\n dt === \"money\"\n ) {\n return \"number\";\n }\n\n // Boolean\n if (dt.includes(\"bool\")) return \"boolean\";\n\n // Date / Time\n if (dt.includes(\"time\") || dt.includes(\"date\")) return \"date\";\n\n // JSON\n if (dt === \"json\" || dt === \"jsonb\") return \"map\";\n\n // Binary\n if (dt === \"bytea\") return \"binary\";\n\n // Network types\n if (dt === \"inet\" || dt === \"cidr\" || dt === \"macaddr\" || dt === \"macaddr8\") return \"string\";\n\n // UUID\n if (dt === \"uuid\") return \"string\";\n\n // Text/varchar/char — default to string\n return \"string\";\n}\n","/**\n * The `frontend/src/cms/<table>.tsx` introspection writes beside a table whose\n * structure suggested how the panel should show it: a `customizeTable(…)` of\n * plain data (an icon, a group, a title field, a board, a sort, the list and\n * form order, field options).\n *\n * A minimal emitter on purpose. Its values are strings, booleans, arrays and\n * nested objects — never code — so it needs none of the CLI codemod's\n * customization printer (which handles functions and JSX, and which this\n * package must not depend on).\n *\n * @module\n */\n\n/** A value this emitter prints: data only. */\nexport type CustomizationValue = string | number | boolean | readonly CustomizationValue[] | { readonly [key: string]: CustomizationValue | undefined };\n\n/** The package `customizeTable` is imported from. */\nexport const CMS_PACKAGE = \"@rebasepro/cms\";\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\nconst key = (name: string): string => IDENTIFIER.test(name) ? name : JSON.stringify(name);\n\n/** One value as source, four-space indented, `depth` levels in. Short scalar arrays stay on one line. */\nexport function printCustomizationValue(value: CustomizationValue, depth = 0): string {\n const pad = \" \".repeat(depth + 1);\n const close = \" \".repeat(depth);\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n if (Array.isArray(value)) {\n const items: readonly CustomizationValue[] = value;\n if (items.length === 0) return \"[]\";\n const scalars = items.every(item => typeof item !== \"object\");\n const inline = `[${items.map(item => printCustomizationValue(item, depth)).join(\", \")}]`;\n if (scalars && inline.length <= 80) return inline;\n return `[\\n${items.map(item => `${pad}${printCustomizationValue(item, depth + 1)}`).join(\",\\n\")}\\n${close}]`;\n }\n const entries = Object.entries(value).filter((entry): entry is [string, CustomizationValue] => entry[1] !== undefined);\n if (entries.length === 0) return \"{}\";\n return `{\\n${entries.map(([name, item]) => `${pad}${key(name)}: ${printCustomizationValue(item, depth + 1)}`).join(\",\\n\")}\\n${close}}`;\n}\n\n/** What {@link printCustomizationModule} prints. */\nexport interface CustomizationModule {\n /** The table's slug, `customizeTable`'s first argument. */\n slug: string;\n /** The identifier the table is exported as from its schema module. */\n tableIdentifier: string;\n /** The schema module, relative to the customization file, without extension: `../../../backend/schema/film`. */\n tableImport: string;\n /** The options: plain data. */\n options: { readonly [key: string]: CustomizationValue | undefined };\n /** Comment lines written above the export. */\n comments?: readonly string[];\n}\n\n/**\n * The whole module:\n *\n * ```ts\n * import { customizeTable } from \"@rebasepro/cms\";\n * import type { film } from \"../../../backend/schema/film\";\n *\n * export const filmCms = customizeTable<typeof film>(\"film\", { … });\n * ```\n */\nexport function printCustomizationModule(module: CustomizationModule): string {\n const comments = (module.comments ?? []).map(line => `// ${line.replace(/\\s*[\\r\\n]+\\s*/g, \" \")}`);\n return [\n `import { customizeTable } from ${JSON.stringify(CMS_PACKAGE)};`,\n `import type { ${module.tableIdentifier} } from ${JSON.stringify(module.tableImport)};`,\n \"\",\n ...comments,\n `export const ${module.tableIdentifier}Cms = customizeTable<typeof ${module.tableIdentifier}>(${JSON.stringify(module.slug)}, ${printCustomizationValue(module.options)});`,\n \"\"\n ].join(\"\\n\");\n}\n","/**\n * What a schema's *structure* says about the app on top of it.\n *\n * Introspection has always been a table mirror: one table in, one collection\n * out, one nav entry each, every column a form field. A schema of thirty tables\n * produces thirty sidebar entries, and a panel whose navigation is a list of\n * table names reads as a database browser however good the fields are — which\n * is the actual complaint about generated admin panels, and is structural, not\n * cosmetic.\n *\n * Most of what separates the eight nouns a user navigates by from the thirty\n * tables underneath them is written down in the schema already: which tables\n * only exist to join two others, which are small referenced code lists, which\n * rows cannot outlive a parent row. This module reads that.\n *\n * ## Structure only\n *\n * Nothing here looks at a column or table *name*. Name heuristics — `status`,\n * `*_url`, `image`, `created_at` — are wrong exactly when a schema is not in\n * English, or is domain-specific, or spells things differently, and they are\n * wrong silently. Every rule below is a fact the database enforces: key\n * composition, foreign-key direction and delete rule, uniqueness, nullability,\n * declared type and length, generated-ness, row count.\n *\n * That constraint has a cost, and it is worth stating: a schema that declares\n * nothing beyond `NOT NULL` gives this module very little to work with, and it\n * returns `entity` for everything rather than guessing. Under-classifying is\n * the intended failure mode. A table wrongly hidden from the navigation is a\n * table the user cannot find; a table wrongly left in it is merely the status\n * quo.\n *\n * Pure module: no I/O. Row counts come in on {@link SchemaMetadata.rowCounts},\n * which the caller fills from {@link ./introspect-db-queries.countRowsUpTo} for\n * the tables {@link lookupCandidates} names.\n */\nimport type {\n ForeignKeyRow,\n SchemaMetadata,\n TableColumn,\n TableMeta,\n UniqueConstraintRow\n} from \"./introspect-db-logic\";\nimport { mapPgType } from \"./introspect-db-types\";\nimport type { CheckFactsByTable } from \"./introspect-db-constraints\";\n\n// ── Thresholds ────────────────────────────────────────────────────────\n\n/**\n * The row count above which a referenced table is a real entity rather than a\n * code list. Deliberately low: `pagila.category` has 16 rows and `language` 6,\n * while `actor` has 200 and `country` 109 — the gap between \"a fixed set\n * somebody typed once\" and \"data the app accumulates\" is wide, and picking a\n * number in the middle of it costs nothing.\n */\nexport const LOOKUP_MAX_ROWS = 50;\n\n/**\n * The most payload columns a code list may carry. A code list is an id, a\n * label, and perhaps a sort key or a flag; past that it is a table with\n * attributes, which is an entity.\n */\nexport const LOOKUP_MAX_PAYLOAD_COLUMNS = 3;\n\n/**\n * The most enum values a board can usefully have as columns. A kanban with\n * thirty columns is a horizontally scrolling table.\n */\nexport const KANBAN_MAX_VALUES = 12;\n\n/** Below this, a \"board\" is one or two columns — a filter, not a board. */\nexport const KANBAN_MIN_VALUES = 2;\n\n/**\n * How many columns a generated list view shows before it stops being readable.\n * Only applied when a table has more properties than this; a six-column table\n * gets no `listProperties` at all rather than a restatement of its own columns.\n */\nexport const LIST_PROPERTIES_CAP = 6;\n\n// ── Roles ─────────────────────────────────────────────────────────────\n\n/**\n * What a table *is*, structurally.\n *\n * - `entity` — a thing the app is about. Gets a collection and a nav entry.\n * - `junction` — exists only to relate two other tables. Gets no collection at\n * all; it becomes a many-to-many relation on both sides.\n * - `lookup` — a small, referenced, self-contained code list. Gets a collection,\n * grouped away from the entities rather than listed beside them.\n * - `owned-child` — rows that belong to exactly one parent row and are reached\n * through it. Gets a collection (it is a real table with real rows, and the\n * API still serves it) but no nav entry: it already renders as a tab on its\n * parent.\n */\nexport type TableRole = \"entity\" | \"junction\" | \"lookup\" | \"owned-child\";\n\n/**\n * Why a table was called someone's child, weakest last.\n *\n * Carried into the generated file as a comment. A reader who disagrees with the\n * classification needs to see what it was based on to know which line to change.\n */\nexport type OwnershipEvidence =\n /** The only foreign key declared `ON DELETE CASCADE`. */\n | \"cascade-delete\"\n /** The only foreign key that is part of the table's primary key. */\n | \"identifying-key\"\n /** The only foreign key that is `NOT NULL`. */\n | \"sole-required-key\"\n /** First column of a composite primary key made entirely of foreign keys. */\n | \"leading-key-column\";\n\nexport interface JunctionShape {\n sourceTable: string;\n sourceColumn: string;\n targetTable: string;\n targetColumn: string;\n}\n\nexport interface TableClassification {\n table: string;\n role: TableRole;\n /** One line, in prose, for the generated file. */\n reason: string;\n /** Set when `role === \"owned-child\"`. */\n owner?: { table: string; column: string; evidence: OwnershipEvidence };\n /** Set when `role === \"junction\"`. */\n junction?: JunctionShape;\n}\n\n// ── Column-level structural predicates ────────────────────────────────\n\n/**\n * A timestamp the database maintains: a temporal column defaulting to the\n * transaction clock.\n *\n * This is the structural stand-in for the `created_at`/`updated_at` name check.\n * It is strictly better than the name: it catches `fecha_creacion` and\n * `last_update` (pagila's spelling, which the name list misses), and it does not\n * fire on a user-editable `created_at date` column that has no default and which\n * the name check would wrongly make read-only.\n */\nexport function isAutoTimestamp(column: TableColumn): boolean {\n if (mapPgType(column.data_type) !== \"date\") return false;\n const columnDefault = (column.column_default ?? \"\").toLowerCase();\n if (!columnDefault) return false;\n return /\\b(now\\(\\)|current_timestamp|current_date|current_time|localtimestamp|localtime|transaction_timestamp\\(\\)|statement_timestamp\\(\\)|clock_timestamp\\(\\))/.test(columnDefault);\n}\n\n/** A key the database fills in: identity, serial, or a uuid-generating default. */\nexport function isGeneratedKey(column: TableColumn): boolean {\n if (column.is_identity === \"YES\") return true;\n const columnDefault = (column.column_default ?? \"\").toLowerCase();\n if (!columnDefault) return false;\n return columnDefault.includes(\"nextval(\") ||\n columnDefault.includes(\"gen_random_uuid\") ||\n columnDefault.includes(\"uuid_generate\");\n}\n\n/** A column Postgres computes; writing to it is an error. */\nexport function isGeneratedColumn(column: TableColumn): boolean {\n return column.is_generated === \"ALWAYS\";\n}\n\n/**\n * Types that exist to be searched or indexed, never to be typed into.\n *\n * A `tsvector` column is a derived search index — maintained by a trigger, a\n * generated expression, or an application job — and its contents are lexeme\n * positions, not text. Pagila's `film.fulltext` is one, and introspection used\n * to emit it as an ordinary required string: a mandatory form field whose\n * correct value no user can produce, on the sixth column of the list view.\n */\nexport function isDerivedIndexColumn(column: TableColumn): boolean {\n return column.udt_name === \"tsvector\" || column.udt_name === \"tsquery\";\n}\n\n/** Anything the user cannot meaningfully edit, whatever the reason. */\nexport function isReadOnlyColumn(column: TableColumn): boolean {\n return isGeneratedColumn(column) || isDerivedIndexColumn(column);\n}\n\n/**\n * A string column with a declared maximum length.\n *\n * `varchar(50)` and `text` are the same type to an application but not to the\n * author: choosing a bound is a statement that the value is short and\n * label-like, which is what makes this usable for picking a display column.\n */\nexport function isBoundedString(column: TableColumn): boolean {\n return mapPgType(column.data_type) === \"string\" &&\n typeof column.character_maximum_length === \"number\" &&\n column.character_maximum_length > 0;\n}\n\n/**\n * A column carrying data rather than structure: not a key, not a foreign key,\n * not a database-maintained timestamp, not computed.\n *\n * The count of these is what tells a pure join table from an association that\n * carries its own attributes — `northwind.order_details` has the key shape of a\n * junction and three payload columns, so it is not one.\n */\nexport function isPayloadColumn(column: TableColumn, pks: string[], fkColumns: Set<string>): boolean {\n if (pks.includes(column.column_name)) return false;\n if (fkColumns.has(column.column_name)) return false;\n if (isAutoTimestamp(column)) return false;\n if (isGeneratedColumn(column)) return false;\n return true;\n}\n\n// ── Foreign-key topology ──────────────────────────────────────────────\n\n/** One foreign key, with its columns grouped back together. */\nexport interface ForeignKeyConstraint {\n name: string;\n table: string;\n columns: string[];\n foreignTable: string;\n foreignColumns: string[];\n deleteRule?: string;\n}\n\n/**\n * Groups per-column foreign key rows back into constraints.\n *\n * Rows arrive one per referencing column. A composite key looks exactly like two\n * separate keys until they are grouped by constraint name, and the difference\n * matters: two single-column keys to two tables can be a junction, one\n * two-column key never is.\n */\nexport function groupForeignKeys(fks: ForeignKeyRow[]): ForeignKeyConstraint[] {\n const byName = new Map<string, ForeignKeyConstraint>();\n for (const fk of fks) {\n // Rows from older callers carry no constraint name. Falling back to a\n // per-column key treats each as its own single-column constraint, which\n // is what the generator assumed before names were available.\n const key = `${fk.table_name}::${fk.constraint_name ?? `${fk.column_name}->${fk.foreign_table_name}`}`;\n const existing = byName.get(key);\n if (existing) {\n existing.columns.push(fk.column_name);\n existing.foreignColumns.push(fk.foreign_column_name);\n continue;\n }\n byName.set(key, {\n name: fk.constraint_name ?? `${fk.table_name}_${fk.column_name}_fkey`,\n table: fk.table_name,\n columns: [fk.column_name],\n foreignTable: fk.foreign_table_name,\n foreignColumns: [fk.foreign_column_name],\n deleteRule: fk.delete_rule\n });\n }\n return Array.from(byName.values());\n}\n\n/** Column sets that are unique in a table: its primary key and every unique index. */\nfunction uniqueColumnSets(table: string, pks: string[], uniques: UniqueConstraintRow[]): string[][] {\n const sets: string[][] = [];\n if (pks.length > 0) sets.push(pks);\n for (const unique of uniques) {\n if (unique.table_name === table) sets.push(unique.column_names);\n }\n return sets;\n}\n\nfunction sameColumnSet(a: string[], b: string[]): boolean {\n if (a.length !== b.length) return false;\n const left = [...a].sort();\n const right = [...b].sort();\n return left.every((value, index) => value === right[index]);\n}\n\n// ── Classification ────────────────────────────────────────────────────\n\n/** Everything classification needs, assembled once per run. */\ninterface AnalysisContext {\n /** The schema the tables were read from. */\n schema: string;\n tables: Map<string, TableMeta>;\n constraintsByTable: Map<string, ForeignKeyConstraint[]>;\n inboundByTable: Map<string, ForeignKeyConstraint[]>;\n uniques: UniqueConstraintRow[];\n rowCounts: Record<string, number>;\n}\n\nfunction buildContext(metadata: SchemaMetadata, tables: Map<string, TableMeta>): AnalysisContext {\n const allConstraints = groupForeignKeys(metadata.fks);\n const constraintsByTable = new Map<string, ForeignKeyConstraint[]>();\n const inboundByTable = new Map<string, ForeignKeyConstraint[]>();\n\n for (const constraint of allConstraints) {\n const outbound = constraintsByTable.get(constraint.table) ?? [];\n outbound.push(constraint);\n constraintsByTable.set(constraint.table, outbound);\n\n const inbound = inboundByTable.get(constraint.foreignTable) ?? [];\n inbound.push(constraint);\n inboundByTable.set(constraint.foreignTable, inbound);\n }\n\n return {\n schema: metadata.schema,\n tables,\n constraintsByTable,\n inboundByTable,\n uniques: metadata.uniques,\n rowCounts: metadata.rowCounts\n };\n}\n\n/**\n * A table that exists only to relate two others.\n *\n * Requires all of:\n * - exactly two single-column foreign keys, to two distinct columns;\n * - that pair is unique — it is the primary key, or a unique index covers it.\n * Without this the table can hold the same pair twice, which is a list of\n * events between two things, not a set membership;\n * - no payload columns. A join row that carries a quantity is an association\n * with attributes, and collapsing it into a many-to-many silently drops those\n * attributes from the UI entirely;\n * - nothing references it. A junction with its own dependents is something rows\n * point *at*, so it needs an identity of its own;\n * - it is in `public`. That is the only schema Rebase reads and creates\n * junction tables in (`resolveTableJunctions`), so a `manyToMany` folded from\n * `crm.contacts_tags` would read and write an empty `public.contacts_tags`\n * instead. Kept as a table, its rows stay where they are and are served.\n */\nfunction classifyJunction(table: string, context: AnalysisContext): TableClassification | null {\n if (context.schema !== \"public\") return null;\n const meta = context.tables.get(table);\n if (!meta) return null;\n\n const constraints = context.constraintsByTable.get(table) ?? [];\n if (constraints.length !== 2) return null;\n if (constraints.some((c) => c.columns.length !== 1)) return null;\n\n const [first, second] = constraints;\n if (first.columns[0] === second.columns[0]) return null;\n\n if ((context.inboundByTable.get(table) ?? []).length > 0) return null;\n\n const pair = [first.columns[0], second.columns[0]];\n const uniqueSets = uniqueColumnSets(table, meta.pks, context.uniques);\n if (!uniqueSets.some((set) => sameColumnSet(set, pair))) return null;\n\n const fkColumns = new Set(pair);\n const payload = meta.columns.filter((column) => isPayloadColumn(column, meta.pks, fkColumns));\n if (payload.length > 0) return null;\n\n return {\n table,\n role: \"junction\",\n reason: `only relates ${first.foreignTable} to ${second.foreignTable}: two foreign keys, unique together, no other data`,\n junction: {\n sourceTable: first.foreignTable,\n sourceColumn: first.columns[0],\n targetTable: second.foreignTable,\n targetColumn: second.columns[0]\n }\n };\n}\n\n/**\n * A policy expression that reads who is asking: the `app.uid` setting every\n * request runs with, `rebase.uid()` (or the retired `auth.uid()`), the JWT,\n * or the session's own role.\n */\nconst CALLER_IDENTITY = /current_setting\\(\\s*'app\\.(uid|user_id|jwt)'|\\b(rebase|auth)\\.(uid|jwt)\\s*\\(|\\bcurrent_user\\b|\\bsession_user\\b/i;\n\n/**\n * The tables whose row-level security hands each caller rows of their own,\n * with the policies that do it.\n *\n * Structure in the sense this module means: a policy is a rule the database\n * enforces, and one that compares a row to the caller's identity says the rows\n * belong to users. That is the app's data. A young database holds three\n * customers and one order; by row count the customers are \"a 3-row code list\"\n * and the orders a child reached only through them, and both go missing from\n * the navigation of the app that owns them.\n */\nfunction callerScopedTables(metadata: SchemaMetadata): Map<string, string[]> {\n const scoped = new Map<string, string[]>();\n for (const policy of metadata.policies ?? []) {\n if (!CALLER_IDENTITY.test(policy.qual ?? \"\") && !CALLER_IDENTITY.test(policy.with_check ?? \"\")) continue;\n scoped.set(policy.table_name, [...(scoped.get(policy.table_name) ?? []), policy.policy_name]);\n }\n return scoped;\n}\n\n/** An entity because its policies give each user their own rows — see {@link callerScopedTables}. */\nfunction classifyCallerScoped(table: string, perCaller: Map<string, string[]>): TableClassification | null {\n const policies = perCaller.get(table);\n if (!policies) return null;\n return {\n table,\n role: \"entity\",\n reason: `its row-level security gives each user their own rows (${policies.join(\", \")}), so they are the app's data`\n };\n}\n\n/**\n * A small, referenced, self-contained code list.\n *\n * Requires: something references it, it references nothing, it carries few and\n * simple payload columns, and it is small — where \"small\" is a real count, not\n * an estimate. `reltuples` is -1 on any table that has never been analyzed,\n * which is every table in a freshly restored dump, so a count that is merely\n * absent must not read as \"small\".\n */\nfunction classifyLookup(table: string, context: AnalysisContext): TableClassification | null {\n if (!isLookupCandidate(table, context)) return null;\n\n const rowCount = context.rowCounts[table];\n if (typeof rowCount !== \"number\") return null;\n // An empty table is not a code list — there is nothing to look up, and a\n // schema-only restore would otherwise classify half the database this way.\n if (rowCount < 1 || rowCount > LOOKUP_MAX_ROWS) return null;\n\n const referencedBy = (context.inboundByTable.get(table) ?? []).length;\n return {\n table,\n role: \"lookup\",\n reason: `a ${rowCount}-row code list: referenced by ${referencedBy} table(s), references none, ${LOOKUP_MAX_PAYLOAD_COLUMNS} or fewer simple columns`\n };\n}\n\n/**\n * The structural half of the lookup test — everything except the row count.\n *\n * Separate because the count costs a query per table, and the caller only wants\n * to pay it for tables that could possibly qualify.\n */\nfunction isLookupCandidate(table: string, context: AnalysisContext): boolean {\n const meta = context.tables.get(table);\n if (!meta) return false;\n\n if ((context.constraintsByTable.get(table) ?? []).length > 0) return false;\n if ((context.inboundByTable.get(table) ?? []).length === 0) return false;\n\n const payload = meta.columns.filter((column) => isPayloadColumn(column, meta.pks, new Set()));\n if (payload.length > LOOKUP_MAX_PAYLOAD_COLUMNS) return false;\n\n // A code list holds labels and flags. Documents, arrays, files and dates are\n // content, and content means the rows are worth browsing in their own right.\n //\n // Strings are allowed whether or not they declare a length. Requiring\n // `varchar(n)` looked like a way to say \"label, not prose\", and it is —\n // except that a schema written any time recently uses `text` for everything,\n // which is the advice Postgres itself gives. Modern pagila is all `text`, so\n // that rule classified nothing at all on it.\n return payload.every((column) => {\n const type = mapPgType(column.data_type);\n return type === \"boolean\" || type === \"number\" || type === \"string\";\n });\n}\n\n/**\n * Names the tables whose classification depends on a row count.\n *\n * The caller counts these — and only these — before calling\n * {@link classifyTables}. On a schema of any size this is a handful of tables,\n * and the count itself is capped (see `countRowsUpTo`), so the whole extra cost\n * is bounded regardless of how much data the database holds.\n */\nexport function lookupCandidates(metadata: SchemaMetadata, tables: Map<string, TableMeta>): string[] {\n const context = buildContext(metadata, tables);\n return Array.from(tables.keys()).filter((table) => isLookupCandidate(table, context));\n}\n\n/**\n * Rows that belong to one parent row and are reached through it.\n *\n * Requires nothing to reference the table — a table others point at has an\n * identity of its own and belongs in the navigation — and an *unambiguous*\n * owner among its foreign keys. The evidence ladder runs strongest first; each\n * rung is only taken when exactly one key satisfies it, so a table with two\n * equally plausible parents stays an entity rather than being filed under a\n * coin-flip.\n */\nfunction classifyOwnedChild(table: string, context: AnalysisContext): TableClassification | null {\n const meta = context.tables.get(table);\n if (!meta) return null;\n\n const constraints = context.constraintsByTable.get(table) ?? [];\n if (constraints.length === 0) return null;\n if ((context.inboundByTable.get(table) ?? []).length > 0) return null;\n\n const owner = pickOwner(meta, constraints);\n if (!owner) return null;\n\n return {\n table,\n role: \"owned-child\",\n reason: `belongs to ${owner.constraint.foreignTable} (${describeEvidence(owner.evidence)}) and nothing else references it`,\n owner: {\n table: owner.constraint.foreignTable,\n column: owner.constraint.columns[0],\n evidence: owner.evidence\n }\n };\n}\n\nfunction describeEvidence(evidence: OwnershipEvidence): string {\n switch (evidence) {\n case \"cascade-delete\": return \"its only ON DELETE CASCADE foreign key\";\n case \"identifying-key\": return \"its only foreign key inside the primary key\";\n case \"sole-required-key\": return \"its only NOT NULL foreign key\";\n case \"leading-key-column\": return \"the leading column of a primary key made only of foreign keys\";\n }\n}\n\nfunction pickOwner(\n meta: TableMeta,\n constraints: ForeignKeyConstraint[]\n): { constraint: ForeignKeyConstraint; evidence: OwnershipEvidence } | null {\n const singleColumn = constraints.filter((c) => c.columns.length === 1);\n if (singleColumn.length === 0) return null;\n\n const nullability = new Map(meta.columns.map((c) => [c.column_name, c.is_nullable === \"NO\"]));\n\n const cascading = singleColumn.filter((c) => c.deleteRule === \"CASCADE\");\n if (cascading.length === 1) return { constraint: cascading[0], evidence: \"cascade-delete\" };\n\n const identifying = singleColumn.filter((c) => meta.pks.includes(c.columns[0]));\n if (identifying.length === 1) return { constraint: identifying[0], evidence: \"identifying-key\" };\n\n const required = singleColumn.filter((c) => nullability.get(c.columns[0]) === true);\n if (required.length === 1) return { constraint: required[0], evidence: \"sole-required-key\" };\n\n // Last resort, and the only rung that leans on an ordering convention rather\n // than a guarantee: in a table whose whole primary key is foreign keys, the\n // first key column is the parent the rows are filed under.\n // `northwind.order_details` is keyed `(order_id, product_id)` — the rows are\n // lines of an order, which is exactly what that ordering says.\n if (identifying.length === meta.pks.length && meta.pks.length > 1) {\n const leading = identifying.find((c) => c.columns[0] === meta.pks[0]);\n if (leading) return { constraint: leading, evidence: \"leading-key-column\" };\n }\n\n return null;\n}\n\n/**\n * Classifies every table in the schema.\n *\n * Order matters: junction is the most specific and most consequential (the\n * table disappears), so it is tested first; then lookup, which needs no\n * ownership reasoning; then ownership. Anything unmatched is an entity, which\n * is also what every rule falls back to when its evidence is ambiguous.\n */\nexport function classifyTables(\n metadata: SchemaMetadata,\n tables: Map<string, TableMeta>\n): Map<string, TableClassification> {\n const context = buildContext(metadata, tables);\n const result = new Map<string, TableClassification>();\n const perCaller = callerScopedTables(metadata);\n\n for (const table of tables.keys()) {\n const classification =\n classifyJunction(table, context) ??\n classifyCallerScoped(table, perCaller) ??\n classifyLookup(table, context) ??\n classifyOwnedChild(table, context) ?? {\n table,\n role: \"entity\" as const,\n reason: \"no structural evidence that it is a join table, a code list, or owned by another table\"\n };\n result.set(table, classification);\n }\n\n return result;\n}\n\n// ── Presentation derived from structure ───────────────────────────────\n\n/**\n * The columns a property-level derivation needs, resolved once.\n */\nexport interface ColumnFacts {\n column: TableColumn;\n isPk: boolean;\n isFk: boolean;\n /** Covered by a single-column unique constraint or unique index. */\n isUniqueAlone: boolean;\n isAutoTimestamp: boolean;\n isGenerated: boolean;\n /** Allowed values, from a Postgres enum type or a readable CHECK. */\n enumValues?: string[];\n propType: string;\n}\n\nexport function buildColumnFacts(\n meta: TableMeta,\n metadata: SchemaMetadata,\n enumMap: Map<string, string[]>,\n checkFacts: CheckFactsByTable\n): Map<string, ColumnFacts> {\n const fkColumns = new Set(meta.fks.map((fk) => fk.column_name));\n const singleColumnUniques = new Set(\n metadata.uniques\n .filter((u) => u.table_name === meta.name && u.column_names.length === 1)\n .map((u) => u.column_names[0])\n );\n const tableChecks = checkFacts.get(meta.name);\n\n const facts = new Map<string, ColumnFacts>();\n for (const column of meta.columns) {\n const pgEnum = column.data_type === \"USER-DEFINED\" ? enumMap.get(column.udt_name) : undefined;\n const checkEnum = tableChecks?.get(column.column_name)?.enumValues;\n facts.set(column.column_name, {\n column,\n isPk: meta.pks.includes(column.column_name),\n isFk: fkColumns.has(column.column_name),\n isUniqueAlone: singleColumnUniques.has(column.column_name),\n isAutoTimestamp: isAutoTimestamp(column),\n isGenerated: isGeneratedColumn(column),\n enumValues: pgEnum ?? checkEnum,\n propType: pgEnum ? \"string\" : mapPgType(column.data_type)\n });\n }\n return facts;\n}\n\n/**\n * The column that identifies a row to a human.\n *\n * Structural, in three rungs, strongest first:\n *\n * 1. A single-column unique constraint on a required string. This is as close\n * as a schema comes to declaring \"this is what a row is called\": it is the\n * column a person looks a row up by, and the database guarantees it picks\n * out one row.\n * 2. The first required string that declares a length, when the table also has\n * strings that do not. Choosing `varchar(n)` for one column and `text` for\n * another is the author distinguishing a label from prose.\n * 3. The first required string in declaration order. Weak, but it is the same\n * rung the panel's own fallback stands on, and column order carries real\n * information — the identifying column of a table is written near the top of\n * it, in every schema, in every language.\n *\n * Deliberately not: a column called `name`, or `title`. That works on English\n * schemas written by someone who read the same tutorial. This picks\n * `film.title`, `actor.first_name` and `category.name` out of pagila without\n * knowing what any of those words mean.\n */\nexport function deriveTitleProperty(facts: Map<string, ColumnFacts>): string | undefined {\n const candidates = Array.from(facts.values()).filter((f) =>\n !f.isPk && !f.isFk && !f.isGenerated &&\n f.propType === \"string\" &&\n !f.enumValues &&\n f.column.is_nullable === \"NO\"\n );\n if (candidates.length === 0) return undefined;\n\n const unique = candidates.find((f) => f.isUniqueAlone);\n if (unique) return unique.column.column_name;\n\n const bounded = candidates.filter((f) => isBoundedString(f.column));\n if (bounded.length > 0 && bounded.length < candidates.length) {\n return bounded[0].column.column_name;\n }\n\n return candidates[0].column.column_name;\n}\n\n/**\n * The enum column a board should have as its columns.\n *\n * A board needs a small, closed, always-present set of states. `NOT NULL` is\n * required because a null has no column to sit in; the bounds keep out\n * two-state flags (a filter, not a board) and long code lists (a scrolling\n * table). The first qualifying column in declaration order wins, so the output\n * is stable across runs.\n */\nexport function deriveKanbanProperty(facts: Map<string, ColumnFacts>): string | undefined {\n for (const fact of facts.values()) {\n if (fact.isPk || fact.isFk || fact.isGenerated) continue;\n if (!fact.enumValues) continue;\n if (fact.column.is_nullable !== \"NO\") continue;\n if (fact.enumValues.length < KANBAN_MIN_VALUES || fact.enumValues.length > KANBAN_MAX_VALUES) continue;\n return fact.column.column_name;\n }\n return undefined;\n}\n\n/** Names a string column goes by when it holds a board's card order (a fractional-indexing key). */\nconst ORDER_KEY_NAMES = new Set([\"__order\", \"order_key\", \"sort_key\", \"rank\", \"lexorank\", \"position_key\"]);\n\n/**\n * The string column that can hold a board's card order, or nothing.\n *\n * A board without `orderProperty` cannot keep a card's position within a\n * column, and the config validator says so on every generate — so a board is\n * emitted only when the table already has somewhere to store the order. A\n * legacy table almost never does; asking its owner to add a hidden column\n * just to satisfy generated output was the wrong way round.\n */\nexport function deriveKanbanOrderProperty(facts: Map<string, ColumnFacts>): string | undefined {\n for (const fact of facts.values()) {\n if (fact.isPk || fact.isFk || fact.isGenerated || fact.enumValues) continue;\n if (fact.propType !== \"string\") continue;\n if (!/^(text|character varying)$/.test(fact.column.data_type)) continue;\n if (ORDER_KEY_NAMES.has(fact.column.column_name.toLowerCase())) return fact.column.column_name;\n }\n return undefined;\n}\n\n/**\n * The column a list should be sorted by, newest first.\n *\n * Only when the table has exactly one database-maintained timestamp. With two —\n * a created and an updated stamp — the two orderings differ and the schema does\n * not say which the user means, so neither is chosen.\n */\nexport function deriveSort(facts: Map<string, ColumnFacts>): [string, \"desc\"] | undefined {\n const stamps = Array.from(facts.values()).filter((f) => f.isAutoTimestamp);\n if (stamps.length !== 1) return undefined;\n return [stamps[0].column.column_name, \"desc\"];\n}\n\n/**\n * The first `LIST_PROPERTIES_CAP` visible properties, or nothing.\n *\n * Returning nothing when the table is already narrow matters: `listProperties`\n * that restates every column is config the reader has to check against the\n * property list to discover it does nothing, and it silently stops new columns\n * from appearing in the list view when someone adds one later.\n *\n * `hidden` names the properties already marked `hideFromCollection` — spending\n * one of six columns on a value the list does not render is worse than not\n * capping at all.\n */\nexport function deriveListProperties(propertiesOrder: string[], hidden: ReadonlySet<string> = new Set()): string[] | undefined {\n const visible = propertiesOrder.filter((key) => !hidden.has(key));\n if (visible.length <= LIST_PROPERTIES_CAP) return undefined;\n return visible.slice(0, LIST_PROPERTIES_CAP);\n}\n","/**\n * Introspection logic — pure functions and the pipeline that transforms\n * raw PostgreSQL metadata into `backend/schema` source (and, for a project\n * with a frontend, `frontend/src/cms` customizations).\n *\n * This module contains NO side-effects: no fs writes, no pg.Client creation,\n * no process.exit. It is imported by introspect-db.ts (the CLI entry-point)\n * and consumed directly by tests.\n */\nimport { columnTypeLabel, type ColumnType, type TableDescriptor } from \"@rebasepro/types\";\nimport { printIndexModule, printTableModule, tableIdentifier } from \"@rebasepro/common\";\nimport { toWireKey } from \"@rebasepro/utils\";\nimport { inferColumnHints } from \"./introspect-db-inference\";\nimport { mapPgType } from \"./introspect-db-types\";\nimport { printCustomizationModule, type CustomizationValue } from \"./introspect-db-customization\";\nimport { describeTables } from \"./introspect-tables\";\nimport type { CheckFactsByTable } from \"./introspect-db-constraints\";\nimport type { TableClassification } from \"./introspect-db-structure\";\nimport {\n buildColumnFacts,\n deriveKanbanOrderProperty,\n deriveKanbanProperty,\n deriveListProperties,\n deriveSort,\n deriveTitleProperty,\n isDerivedIndexColumn\n} from \"./introspect-db-structure\";\n\n// ── Typed interfaces for SQL query results ────────────────────────────\n\nexport interface TableRow {\n table_name: string;\n /** True for the parent of a partitioned table (`relkind = 'p'`). */\n is_partitioned?: boolean;\n /** Whether row-level security is on (`relrowsecurity`). Absent when the caller did not read it. */\n rls_enabled?: boolean;\n}\n\nexport interface TableColumn {\n table_name: string;\n column_name: string;\n data_type: string;\n udt_name: string;\n is_nullable: string;\n column_default: string | null;\n atttypmod: number | null;\n /** 1-based position in the table, as declared. */\n ordinal_position?: number;\n /** `\"ALWAYS\"` for a generated column, `\"NEVER\"` otherwise. */\n is_generated?: string;\n /** The `GENERATED ALWAYS AS (…)` expression, when `is_generated` says so. */\n generation_expression?: string | null;\n /** `\"YES\"` for an identity column. */\n is_identity?: string;\n /** `\"ALWAYS\"` or `\"BY DEFAULT\"` on an identity column. */\n identity_generation?: string | null;\n /** The declared `varchar(n)` / `char(n)` bound, if any. */\n character_maximum_length?: number | null;\n numeric_precision?: number | null;\n numeric_scale?: number | null;\n /**\n * `format_type(atttypid, atttypmod)`: the type as Postgres spells it in\n * full, modifiers included (`timestamp(3) without time zone`,\n * `geometry(Point,4326)`) — what a `col.custom()` column is declared as.\n */\n formatted_type?: string | null;\n}\n\nexport interface EnumValue {\n enum_name: string;\n enum_value: string;\n sort_order: number;\n}\n\nexport interface PrimaryKeyRow {\n table_name: string;\n column_name: string;\n}\n\nexport interface ForeignKeyRow {\n table_name: string;\n column_name: string;\n foreign_table_name: string;\n foreign_column_name: string;\n /** Name of the FK constraint — the only way to tell composite keys apart. */\n constraint_name?: string;\n /** 1-based position of this column within its constraint. */\n ordinal?: number;\n /** `\"CASCADE\"`, `\"RESTRICT\"`, `\"SET NULL\"`, `\"SET DEFAULT\"`, `\"NO ACTION\"`. */\n delete_rule?: string;\n}\n\n/** A unique constraint or unique index, as an ordered column list. */\nexport interface UniqueConstraintRow {\n table_name: string;\n constraint_name: string;\n column_names: string[];\n}\n\n/** One index: its name, and what it leads with. */\nexport interface IndexRow {\n table_name: string;\n index_name: string;\n /** The column its first key is, or null for an expression. */\n leading_column: string | null;\n /** Whether it serves every equality lookup on that column: a btree with no predicate. */\n serves_leading_column: boolean;\n}\n\n/** A CHECK constraint, as `pg_get_constraintdef` renders it. */\nexport interface CheckConstraintRow {\n table_name: string;\n constraint_name: string;\n definition: string;\n}\n\n/** A `COMMENT ON TABLE` (null `column_name`) or `COMMENT ON COLUMN`. */\nexport interface CommentRow {\n table_name: string;\n column_name: string | null;\n comment: string;\n}\n\n/** A row-level security policy, as `pg_policies` reports it. */\nexport interface PolicyRow {\n table_name: string;\n policy_name: string;\n /** `PERMISSIVE` or `RESTRICTIVE`. */\n permissive: string;\n /** The `TO` list: database roles, `public` for every role. */\n roles: string[];\n /** `SELECT`, `INSERT`, `UPDATE`, `DELETE` or `ALL`. */\n cmd: string;\n /** The `USING` expression, as Postgres renders it back. */\n qual: string | null;\n /** The `WITH CHECK` expression, as Postgres renders it back. */\n with_check: string | null;\n}\n\n/**\n * Everything one introspection run reads from the database.\n *\n * Passed around as one value so a new signal means a new field here rather than\n * a new parameter on every function between the query and the generator — the\n * shape `generateCollectionFile` had grown to seven positional arguments by.\n */\nexport interface SchemaMetadata {\n schema: string;\n tables: TableRow[];\n columns: TableColumn[];\n enumValues: EnumValue[];\n pks: PrimaryKeyRow[];\n fks: ForeignKeyRow[];\n uniques: UniqueConstraintRow[];\n /**\n * Every index on the introspected tables, by name — how a foreign key\n * whose column Rebase would index is told apart from one it already has.\n * Absent when the caller did not read them, and then nothing is said\n * about foreign-key indexes either way.\n */\n indexes?: IndexRow[];\n checks: CheckConstraintRow[];\n comments: CommentRow[];\n /**\n * The row-level security policies on the introspected tables. Absent when\n * the caller did not read them, and then no collection is given rules.\n */\n policies?: PolicyRow[];\n /**\n * Row counts for the tables that needed one, capped — see `countRowsUpTo`.\n * Absent for every table introspection never had a reason to count.\n */\n rowCounts: Record<string, number>;\n}\n\nexport interface TableMeta {\n name: string;\n columns: TableColumn[];\n pks: string[];\n fks: ForeignKeyRow[];\n}\n\n/**\n * The icon a table's name suggests, for its panel customization: `Database`\n * when the name suggests none (and then no icon is written).\n */\nexport function getIconForTable(tableName: string): string {\n const table = tableName.toLowerCase();\n if (table.includes(\"user\") || table.includes(\"account\") || table.includes(\"member\") || table.includes(\"customer\") || table.includes(\"client\") || table.includes(\"patient\")) return \"Users\";\n if (table.includes(\"post\") || table.includes(\"article\") || table.includes(\"blog\") || table.includes(\"page\")) return \"FileText\";\n if (table.includes(\"product\") || table.includes(\"item\")) return \"Package\";\n if (table.includes(\"order\") || table.includes(\"cart\") || table.includes(\"purchase\") || table.includes(\"invoice\")) return \"ShoppingCart\";\n if (table.includes(\"setting\") || table.includes(\"config\")) return \"Settings\";\n if (table.includes(\"tag\") || table.includes(\"categor\")) return \"Tag\";\n if (table.includes(\"image\") || table.includes(\"photo\") || table.includes(\"media\") || table.includes(\"asset\")) return \"Image\";\n if (table.includes(\"notification\") || table.includes(\"message\") || table.includes(\"email\")) return \"Mail\";\n if (table.includes(\"log\") || table.includes(\"audit\") || table.includes(\"event\")) return \"Activity\";\n if (table.includes(\"subscription\") || table.includes(\"plan\") || table.includes(\"billing\")) return \"CreditCard\";\n if (table.includes(\"comment\") || table.includes(\"review\") || table.includes(\"feedback\")) return \"MessageCircle\";\n return \"Database\";\n}\n\nexport { mapPgType };\n\n// ── Build the enum map from query results ─────────────────────────────\n\nexport function buildEnumMap(enumValues: EnumValue[]): Map<string, string[]> {\n const enumMap = new Map<string, string[]>();\n for (const ev of enumValues) {\n const existing = enumMap.get(ev.enum_name);\n if (existing) {\n existing.push(ev.enum_value);\n } else {\n enumMap.set(ev.enum_name, [ev.enum_value]);\n }\n }\n return enumMap;\n}\n\n// ── Build the tables map from raw query results ───────────────────────\n\nexport function buildTablesMap(\n tables: TableRow[],\n columns: TableColumn[],\n pks: PrimaryKeyRow[],\n fks: ForeignKeyRow[]\n): Map<string, TableMeta> {\n const tablesMap = new Map<string, TableMeta>();\n for (const t of tables) {\n tablesMap.set(t.table_name, {\n name: t.table_name,\n columns: columns.filter((c) => c.table_name === t.table_name),\n pks: pks.filter((pk) => pk.table_name === t.table_name).map((pk) => pk.column_name),\n fks: fks.filter((fk) => fk.table_name === t.table_name)\n });\n }\n return tablesMap;\n}\n\n// ── Identify join tables ──────────────────────────────────────────────\n\n/**\n * Join tables, identified by column name.\n *\n * Superseded for the CLI by `classifyTables` in `./introspect-db-structure`,\n * which asks the database instead: two single-column keys, unique together, no\n * payload column, nothing referencing the table. This rule folds away\n * `northwind.order_details` — which has the key shape and carries unit price,\n * quantity and discount — because it recognises `id`, `created_at` and\n * `updated_at` by name and calls everything else a foreign key.\n *\n * Still the runtime's rule (`describeTables(…, { purpose: \"serve\" })`): what a\n * backend with no `backend/schema` has always folded away, kept so the set of\n * tables it serves does not move. Row counts, which `classifyTables` needs,\n * are not read at boot.\n */\nexport function identifyJoinTables(tablesMap: Map<string, TableMeta>): Set<string> {\n const joinTables = new Set<string>();\n for (const [tableName, meta] of tablesMap.entries()) {\n if (meta.fks.length === 2) {\n const isLikelyJoinTable = meta.columns.every((c) =>\n meta.fks.some((fk) => fk.column_name === c.column_name) ||\n c.column_name === \"id\" ||\n c.column_name === \"created_at\" ||\n c.column_name === \"updated_at\"\n );\n\n if (isLikelyJoinTable) {\n joinTables.add(tableName);\n }\n }\n }\n return joinTables;\n}\n\n// ── Property ordering heuristics ──────────────────────────────────────\n\n/**\n * Property metadata used to compute display priority.\n * Keeps computePropertyPriority free of any TableMeta coupling.\n */\nexport interface PropertyOrderingContext {\n /** The resolved Rebase property type (e.g. \"string\", \"number\", \"date\", \"relation\"). */\n propType: string;\n /** Whether this column is a primary key. */\n isPk: boolean;\n /** Whether this column is an enum (USER-DEFINED with matching values). */\n isEnum: boolean;\n /** Whether this is a storage/file-upload field (detected from column name). */\n isStorage: boolean;\n /** The PostgreSQL data_type (e.g. \"text\", \"character varying\", \"jsonb\"). */\n pgDataType: string;\n /** The original column index in PostgreSQL (for stable tiebreaking). */\n originalIndex: number;\n}\n\n// — Tier 0: Identity (0–9) ————————————————————————————————————————————\nconst IDENTITY_EXACT: Record<string, number> = {\n id: 0,\n uuid: 1,\n _id: 2\n};\n\n// — Tier 1: Title / Name — the \"display column\" (10–19) ———————————————\nconst TITLE_EXACT: Record<string, number> = {\n name: 10,\n title: 11,\n label: 12,\n display_name: 13,\n displayname: 13,\n headline: 14,\n subject: 15,\n heading: 16\n};\n\n// — Tier 2: Human identity fields (20–29) —————————————————————————————\nconst HUMAN_IDENTITY_EXACT: Record<string, number> = {\n first_name: 20,\n firstname: 20,\n last_name: 21,\n lastname: 21,\n full_name: 22,\n fullname: 22,\n given_name: 22,\n family_name: 23,\n middle_name: 24,\n username: 25,\n user_name: 25,\n email: 26,\n email_address: 26,\n phone: 27,\n phone_number: 27,\n mobile: 27\n};\n\n// — Tier 3: Core descriptors (30–39) ——————————————————————————————————\nconst DESCRIPTOR_EXACT: Record<string, number> = {\n slug: 30,\n code: 31,\n sku: 32,\n reference: 33,\n ref: 33,\n type: 34,\n kind: 34,\n status: 35,\n state: 35,\n role: 36,\n category: 37,\n group: 38,\n priority: 39,\n order: 39,\n sort_order: 39,\n position: 39\n};\n\n// — Tier 12: System timestamps (120–129) ——————————————————————————————\nconst SYSTEM_TIMESTAMP_EXACT: Record<string, number> = {\n created_at: 120,\n createdat: 120,\n creation_date: 120,\n inserted_at: 121,\n updated_at: 122,\n updatedat: 122,\n modified_at: 122,\n last_modified: 122,\n deleted_at: 123,\n deletedat: 123,\n archived_at: 124\n};\n\n// — Pattern-based rules for partial matches ———————————————————————————\nconst TITLE_PATTERNS = [\"name\", \"title\", \"label\"];\nconst LONG_TEXT_NAMES = new Set([\"description\", \"summary\", \"excerpt\", \"abstract\", \"overview\", \"bio\", \"biography\", \"about\"]);\nconst RICH_CONTENT_NAMES = new Set([\"content\", \"body\", \"html\", \"markup\", \"text\", \"article_body\", \"post_body\"]);\nconst MEDIA_PATTERNS = [\"image\", \"avatar\", \"photo\", \"logo\", \"cover\", \"thumbnail\", \"banner\", \"icon\", \"picture\", \"poster\"];\nconst JSON_MAP_NAMES = new Set([\"metadata\", \"meta\", \"config\", \"configuration\", \"settings\", \"options\", \"preferences\", \"data\", \"payload\", \"attributes\", \"extra\", \"additional_info\"]);\n\n/**\n * Compute a numeric priority score for a property.\n * Lower scores appear first in the generated `propertiesOrder` array.\n *\n * The system uses 14 tiers (0–139), with the original column index\n * added as a fractional tiebreaker (originalIndex / 10000) to\n * guarantee stable ordering within the same tier.\n *\n * Pure function — no side effects.\n */\nexport function computePropertyPriority(\n columnName: string,\n ctx: PropertyOrderingContext\n): number {\n // Normalize camelCase/PascalCase to snake_case, then lowercase\n const col = columnName.replace(/([a-z0-9])([A-Z])/g, \"$1_$2\").toLowerCase();\n const tiebreaker = ctx.originalIndex / 10000;\n\n // ── Tier 0: Primary key identity fields\n if (ctx.isPk) {\n const exactScore = IDENTITY_EXACT[col];\n return (exactScore ?? 5) + tiebreaker;\n }\n\n // ── Tier 12: System timestamps (check early to prevent false matches)\n const systemTs = SYSTEM_TIMESTAMP_EXACT[col];\n if (systemTs !== undefined) {\n return systemTs + tiebreaker;\n }\n\n // ── Tier 1: Title / Name exact matches\n const titleExact = TITLE_EXACT[col];\n if (titleExact !== undefined) {\n return titleExact + tiebreaker;\n }\n\n // ── Tier 2: Human identity exact matches\n const humanExact = HUMAN_IDENTITY_EXACT[col];\n if (humanExact !== undefined) {\n return humanExact + tiebreaker;\n }\n\n // ── Tier 3: Core descriptor exact matches\n const descriptorExact = DESCRIPTOR_EXACT[col];\n if (descriptorExact !== undefined) {\n return descriptorExact + tiebreaker;\n }\n\n // ── Tier 1b: Title-like partial matches (e.g. \"product_name\", \"page_title\")\n // Score 17–19 so they rank after exact matches but still in tier 1.\n for (const pattern of TITLE_PATTERNS) {\n if (col.includes(pattern) && col !== pattern) {\n return 17 + tiebreaker;\n }\n }\n\n // ── Tier 9: Media / file upload fields (check before general strings)\n if (ctx.isStorage) {\n return 90 + tiebreaker;\n }\n for (const pattern of MEDIA_PATTERNS) {\n if (col.includes(pattern)) {\n return 91 + tiebreaker;\n }\n }\n if (col.endsWith(\"_url\") || col.endsWith(\"_uri\") || col.endsWith(\"_link\")) {\n return 92 + tiebreaker;\n }\n\n // ── Tier 7: Long text fields\n if (LONG_TEXT_NAMES.has(col)) {\n return 70 + tiebreaker;\n }\n\n // ── Tier 8: Rich content fields\n if (RICH_CONTENT_NAMES.has(col)) {\n return 80 + tiebreaker;\n }\n\n // ── Tier 10: JSON / Map types\n if (ctx.propType === \"map\") {\n return JSON_MAP_NAMES.has(col) ? 100 + tiebreaker : 105 + tiebreaker;\n }\n\n // ── Tier 11: Array types\n if (ctx.propType === \"array\") {\n return 110 + tiebreaker;\n }\n\n // ── Tier 6: Owning relations\n if (ctx.propType === \"relation\") {\n return 60 + tiebreaker;\n }\n\n // ── Tier 4: Short text, enums, booleans — \"quick glance\" fields\n if (ctx.isEnum) {\n return 40 + tiebreaker;\n }\n if (ctx.propType === \"boolean\") {\n return 45 + tiebreaker;\n }\n if (ctx.propType === \"string\" && ctx.pgDataType !== \"text\") {\n // Short string (varchar, char, uuid that's not a PK)\n return 42 + tiebreaker;\n }\n\n // ── Tier 5: Numbers & user-facing dates\n if (ctx.propType === \"number\") {\n return 50 + tiebreaker;\n }\n if (ctx.propType === \"date\") {\n // A date that isn't a system timestamp (already handled above)\n return 55 + tiebreaker;\n }\n\n // ── Tier 7b: text data_type that didn't match long-text names\n if (ctx.propType === \"string\" && ctx.pgDataType === \"text\") {\n return 75 + tiebreaker;\n }\n\n // ── Tier 13: Fallback / unknown\n return 130 + tiebreaker;\n}\n\n/**\n * Sort a `propertiesOrder` array using the priority heuristic.\n * Returns a new sorted array; does not mutate the input.\n *\n * @param entries - Array of { key, columnName, propType, ... } objects\n * carrying the information needed to compute priority.\n */\nexport interface PropertyOrderEntry {\n /** The property key in the generated collection (may differ from columnName for relations). */\n key: string;\n /** The ordering context for this property. */\n ctx: PropertyOrderingContext;\n}\n\nexport function sortPropertiesOrder(entries: PropertyOrderEntry[]): string[] {\n return [...entries]\n .sort((a, b) => computePropertyPriority(a.key, a.ctx) - computePropertyPriority(b.key, b.ctx))\n .map((e) => e.key);\n}\n\n// ── Generate backend/schema (and frontend/src/cms) source ─────────────\n\n/**\n * What one `schema introspect` run hands the generator.\n *\n * Everything but `metadata` is optional, and the generator degrades without\n * it: no classification is no table roles and no presentation heuristics, no\n * CHECK facts is no bounds, no samples is no data hints, no `cms` is no\n * `customizeTable` files.\n */\nexport interface SchemaGenerationInput {\n metadata: SchemaMetadata;\n /** Each table's role (`classifyTables`): junctions fold into `manyToMany`, the rest steer the panel. */\n classifications?: Map<string, TableClassification>;\n /** The CHECK constraints, parsed (`parseCheckConstraints`). */\n checkFacts?: CheckFactsByTable;\n /** Sampled rows by table (`--data-inference`). */\n samples?: ReadonlyMap<string, readonly Record<string, unknown>[]>;\n /** Tables not to generate, which nothing may then point at (a name that is no file name). */\n leaveOut?: ReadonlySet<string>;\n /**\n * Present when the project has a frontend that imports `@rebasepro/cms`:\n * the import path from a `frontend/src/cms/<table>.tsx` to the table's\n * schema module. Absent, no customization is written.\n */\n cms?: { tableImport: (table: string) => string };\n /** Where the builders are imported from. `@rebasepro/server/schema` when omitted. */\n specifier?: string;\n}\n\n/**\n * The source written for one table.\n */\nexport interface GeneratedTable {\n table: string;\n /** What `backend/schema/<table>.ts` exports, and `index.ts` re-exports. */\n identifier: string;\n /** `backend/schema/<table>.ts`. */\n schemaModule: string;\n /** `frontend/src/cms/<table>.tsx`, when a presentation heuristic fired and the project has a frontend. */\n customization?: string;\n /** What `rebase db push` would not reproduce exactly, each also at the top of the module. */\n notes: string[];\n /** Decisions the module states that the reader may want to undo (`index: false`, …), each also at its top. */\n remarks: string[];\n}\n\n/**\n * What {@link generateSchemaModules} returns.\n */\nexport interface SchemaGeneration {\n tables: GeneratedTable[];\n /** Tables whose descriptor could not be printed, each with why. */\n failed: { table: string; reason: string }[];\n /** The generated tables whose row-level security is off: the first push switches it on. */\n rlsOff: string[];\n}\n\n/** The column types a declared key may not have (`defineTable` refuses them). */\nconst UNKEYABLE_KINDS: ReadonlySet<ColumnType[\"kind\"]> = new Set([\"timestamptz\", \"time\", \"json\", \"jsonb\", \"vector\", \"bytea\", \"array\", \"other\"]);\n\n/** The `PropertyOrderingContext` property type of a column type. */\nfunction orderingType(type: ColumnType): string {\n switch (type.kind) {\n case \"smallint\": case \"integer\": case \"bigint\": case \"smallserial\": case \"serial\": case \"bigserial\":\n case \"real\": case \"doublePrecision\": case \"numeric\":\n return \"number\";\n case \"timestamptz\": case \"date\": case \"time\": return \"date\";\n case \"json\": case \"jsonb\": return \"map\";\n case \"array\": return \"array\";\n case \"boolean\": return \"boolean\";\n case \"vector\": return \"vector\";\n case \"bytea\": return \"binary\";\n default: return \"string\";\n }\n}\n\n/** A `CustomizationValue` object, built up key by key. */\ntype FieldOptions = Record<string, CustomizationValue>;\n\n/**\n * The panel options a table's structure and names suggest — what the\n * generator used to write into the collection's `admin` block — or\n * `undefined` when none fired (an icon of its own, a role, a title, a board, a\n * sort, a capped list, an option on a field).\n */\nfunction customizationOf(\n descriptor: TableDescriptor,\n meta: TableMeta,\n input: SchemaGenerationInput,\n enumMap: Map<string, string[]>,\n fieldHints: ReadonlyMap<string, FieldOptions>\n): { options: Record<string, CustomizationValue>; comments: string[] } | undefined {\n const table = descriptor.table;\n const classification = input.classifications?.get(table);\n const options: Record<string, CustomizationValue> = {};\n const comments: string[] = [];\n const keyOf = new Map(descriptor.columns.map(column => [column.column, column.key]));\n const relationOf = new Map(descriptor.relations\n .filter(relation => relation.kind === \"belongsTo\")\n .map(relation => [relation.kind === \"belongsTo\" ? relation.localKey : \"\", relation.name]));\n\n const icon = getIconForTable(table);\n if (icon !== \"Database\") options.icon = icon;\n if (classification?.role === \"owned-child\") options.hideFromNavigation = true;\n if (classification?.role === \"lookup\") options.group = \"Reference\";\n\n // Field options, by column key, from the column's name and kind.\n const fields: Record<string, FieldOptions> = {};\n const hidden = new Set<string>();\n for (const column of descriptor.columns) {\n const col = meta.columns.find(candidate => candidate.column_name === column.column);\n if (!col || column.foreignKeyOf !== undefined) continue;\n const name = column.column.toLowerCase();\n const field: FieldOptions = {};\n if (column.stamp?.value === \"now\") {\n field.readOnly = true;\n if (name === \"created_at\" || name === \"createdat\" || name === \"updated_at\" || name === \"updatedat\") {\n field.hidden = true;\n hidden.add(column.key);\n }\n } else if (isDerivedIndexColumn(col)) {\n field.hidden = true;\n hidden.add(column.key);\n } else if ((column.type.kind === \"text\" || column.type.kind === \"varchar\") && column.validate?.url !== true && !column.primaryKey) {\n if (name === \"content\" || name === \"body\") {\n field.multiline = true;\n field.markdown = true;\n } else if (column.type.kind === \"text\" || name === \"description\" || name === \"summary\" || name === \"excerpt\") {\n field.multiline = true;\n }\n }\n Object.assign(field, fieldHints.get(column.key) ?? {});\n if (Object.keys(field).length > 0) fields[column.key] = field;\n }\n\n // The order fields are listed in, by the same priority the generator has\n // always used; a link is placed where its relation is.\n const entries: PropertyOrderEntry[] = [];\n descriptor.columns.forEach((column, index) => {\n const col = meta.columns.find(candidate => candidate.column_name === column.column);\n const relation = relationOf.get(column.column);\n const isPk = column.primaryKey === true;\n entries.push({\n key: relation !== undefined && !isPk ? relation : column.key,\n ctx: {\n propType: relation !== undefined && !isPk ? \"relation\" : orderingType(column.type),\n isPk,\n isEnum: column.type.kind === \"enum\",\n isStorage: false,\n pgDataType: col?.data_type ?? \"\",\n originalIndex: index\n }\n });\n });\n const defaultOrder = entries.map(entry => entry.key);\n const order = sortPropertiesOrder(entries);\n\n if (classification && input.metadata) {\n const facts = buildColumnFacts(meta, input.metadata, enumMap, input.checkFacts ?? new Map());\n const asKey = (column: string): string => keyOf.get(column) ?? toWireKey(column);\n const title = deriveTitleProperty(facts);\n if (title) options.display = { title: asKey(title) };\n const kanban = deriveKanbanProperty(facts);\n const orderField = kanban ? deriveKanbanOrderProperty(facts) : undefined;\n if (kanban && orderField) options.kanban = { columnField: asKey(kanban), orderField: asKey(orderField) };\n else if (kanban) {\n comments.push(\n `A board over \"${asKey(kanban)}\" fits this table, but a board needs a text column to keep each card's order in. ` +\n `Add one, then declare kanban: { columnField: \"${asKey(kanban)}\", orderField: \"<that column>\" }.`\n );\n }\n const sort = deriveSort(facts);\n if (sort) options.sort = [asKey(sort[0]), \"desc\"];\n const listFields = deriveListProperties(order, hidden);\n if (listFields) options.listFields = listFields;\n }\n if (Object.keys(fields).length > 0) options.fields = fields;\n if (Object.keys(options).length === 0 && comments.length === 0) return undefined;\n if (order.join(\"\\n\") !== defaultOrder.join(\"\\n\")) options.fieldOrder = order;\n return { options, comments };\n}\n\n/** The comment a table whose row-level security is off opens with. */\nfunction rlsOffComment(table: TableRow | undefined): string[] {\n if (table?.rls_enabled !== false) return [];\n return [\n \"⚠ Row-level security is off on this table, so every request reaches every row. `rebase db push`\",\n \"switches it on: from then on the server and admins reach its rows, and anyone else what `rls` grants.\"\n ];\n}\n\n/** Comment lines, safe after `//`. */\nconst commentLines = (lines: readonly string[]): string =>\n lines.map(line => `// ${line.replace(/\\s*[\\r\\n]+\\s*/g, \" \")}`.trimEnd()).join(\"\\n\");\n\n/**\n * The source `rebase schema introspect` writes for a database: one\n * `backend/schema/<table>.ts` per table through the one table printer\n * (`printTableModule`), and a `frontend/src/cms/<table>.tsx` beside a table\n * whose structure suggested how the panel should show it.\n *\n * The tables are described with `describeTables(…, { purpose: \"generate\" })`:\n * columns as their Postgres types, foreign keys as `belongsTo` with the column\n * declared, the reverse `hasMany`, a junction as `manyToMany`, the policies as\n * `rls` (or `\"admin-only\"` when the table holds only the admin baseline). Pure.\n */\nexport function generateSchemaModules(input: SchemaGenerationInput): SchemaGeneration {\n const { metadata } = input;\n const tablesMap = buildTablesMap(metadata.tables, metadata.columns, metadata.pks, metadata.fks);\n const enumMap = buildEnumMap(metadata.enumValues);\n const joinTables = input.classifications\n ? new Set([...input.classifications.values()].filter(c => c.role === \"junction\").map(c => c.table))\n : identifyJoinTables(tablesMap);\n // A table with no primary key cannot be declared: a row is addressed by\n // its key in every URL, filter and foreign key.\n const keyless = [...tablesMap.values()].filter(meta => meta.pks.length === 0 && !joinTables.has(meta.name) && !(input.leaveOut?.has(meta.name) ?? false));\n const describe = (leaveOut: ReadonlySet<string>) => describeTables(metadata, {\n purpose: \"generate\",\n joinTables,\n leaveOut: new Set([...(input.leaveOut ?? []), ...keyless.map(meta => meta.name), ...leaveOut]),\n checkFacts: input.checkFacts\n });\n // A key column a row cannot be addressed by — an instant, a document, a\n // list, a type Rebase does not create — cannot be declared either; the\n // table is left out, and described again without it so nothing points at it.\n const unkeyable = new Map<string, string>();\n for (const table of describe(new Set()).tables) {\n const bad = table.columns.filter(column => column.primaryKey && UNKEYABLE_KINDS.has(column.type.kind));\n if (bad.length > 0) {\n unkeyable.set(table.table, `its key includes ${bad.map(column => `\"${column.column}\" (${columnTypeLabel(column.type)})`).join(\", \")}, and a key ` +\n \"column is a value a row is addressed by — text, a number, a uuid, a date, a boolean or an enum. Key the table on such a column and introspect again.\");\n }\n }\n const described = describe(new Set(unkeyable.keys()));\n const bySlug = new Map(described.tables.map(table => [table.slug, table]));\n const resolveTarget = (target: { name?: string; slug: string }) => {\n const found = bySlug.get(target.slug);\n return { identifier: tableIdentifier(target.slug), importPath: `./${target.slug}`, ...(found ? { table: found.table, kind: found.kind } : {}) };\n };\n\n const out: SchemaGeneration = {\n tables: [],\n failed: [\n ...keyless.map(meta => ({\n table: meta.name,\n reason: \"it has no primary key, and a table is declared with the column (or columns) that identify a row. Add one (`ALTER TABLE … ADD PRIMARY KEY (…)`) and introspect again.\"\n })),\n ...[...unkeyable].map(([table, reason]) => ({ table, reason }))\n ],\n rlsOff: []\n };\n for (const descriptor of described.tables) {\n const meta = tablesMap.get(descriptor.table);\n if (!meta) continue;\n const notes = [...(described.notes.drift.get(descriptor.table) ?? [])];\n const remarks = [...(described.notes.remark.get(descriptor.table) ?? [])];\n\n // What the rows and the names add to each column.\n const rows = input.samples?.get(descriptor.table);\n const fieldHints = new Map<string, FieldOptions>();\n const columns = descriptor.columns.map(column => {\n const hints = rows ? inferColumnHints(column.column, column.type, rows.map(row => row[column.column])) : {};\n if (hints.field) fieldHints.set(column.key, { ...hints.field });\n let validate = hints.validate;\n const name = column.column.toLowerCase();\n const text = column.type.kind === \"text\" || column.type.kind === \"varchar\" || column.type.kind === \"char\";\n if (!validate && !rows && text && column.foreignKeyOf === undefined && /_(url|uri|link)$/.test(name)) validate = { url: true };\n return validate ? { ...column, validate: { ...column.validate, ...validate } } : column;\n });\n const table: TableDescriptor = { ...descriptor, columns };\n\n let schemaModule: string;\n try {\n schemaModule = printTableModule(table, { resolveTarget, ...(input.specifier ? { specifier: input.specifier } : {}) });\n } catch (error) {\n out.failed.push({ table: descriptor.table, reason: error instanceof Error ? error.message : String(error) });\n continue;\n }\n const row = metadata.tables.find(candidate => candidate.table_name === descriptor.table);\n if (row?.rls_enabled === false) out.rlsOff.push(descriptor.table);\n const classification = input.classifications?.get(descriptor.table);\n const header = [\n ...(classification && classification.role !== \"entity\"\n ? [`Introspected as ${/^[aeiou]/.test(classification.role) ? \"an\" : \"a\"} ${classification.role}: ${classification.reason}.`]\n : []),\n ...(notes.length > 0 ? [\"⚠ Not reproduced exactly by `rebase db push` — read before pushing:\", ...notes.map(note => ` - ${note}`)] : []),\n ...(remarks.length > 0 ? [\"Introspection notes:\", ...remarks.map(remark => ` - ${remark}`)] : []),\n ...rlsOffComment(row)\n ];\n if (header.length > 0) {\n const split = schemaModule.indexOf(\"\\n\\nexport const \");\n schemaModule = `${schemaModule.slice(0, split)}\\n\\n${commentLines(header)}${schemaModule.slice(split + 1)}`;\n }\n\n const identifier = tableIdentifier(descriptor.slug);\n let customization: string | undefined;\n if (input.cms) {\n const options = customizationOf(table, meta, input, enumMap, fieldHints);\n if (options) {\n customization = printCustomizationModule({\n slug: descriptor.slug,\n tableIdentifier: identifier,\n tableImport: input.cms.tableImport(descriptor.table),\n options: options.options,\n comments: options.comments\n });\n }\n }\n out.tables.push({ table: descriptor.table, identifier, schemaModule, notes, remarks, ...(customization ? { customization } : {}) });\n }\n return out;\n}\n\n/**\n * `backend/schema/index.ts` with an export line added for each table it does\n * not export yet — what a run without `--force` does to an index that exists.\n */\nexport function mergeIndexModule(existing: string, tables: readonly { identifier: string; importPath: string }[]): string {\n const exported = new Set([...existing.matchAll(/from\\s+[\"']\\.\\/([^\"']+)[\"']/g)].map(match => match[1]));\n const missing = tables.filter(table => !exported.has(table.importPath.replace(/^\\.\\//, \"\")));\n if (missing.length === 0) return existing;\n const lines = printIndexModule(missing).trimEnd().split(\"\\n\");\n const lastExport = [...existing.matchAll(/^export \\{[^}]*\\} from [^\\n]*$/gm)].pop();\n if (!lastExport || lastExport.index === undefined) return `${lines.join(\"\\n\")}\\n${existing.startsWith(\"\\n\") ? \"\" : \"\\n\"}${existing}`;\n const at = lastExport.index + lastExport[0].length;\n return `${existing.slice(0, at)}\\n${lines.join(\"\\n\")}${existing.slice(at)}`;\n}\n\n/**\n * What `rebase db push` does to tables whose row-level security is off, for\n * the introspection to say once — or `undefined` when there are none.\n */\nexport function describeRlsOffTables(tableNames: readonly string[]): string | undefined {\n if (tableNames.length === 0) return undefined;\n return `${tableNames.length} table(s) have row-level security off, so every request reaches every row: ` +\n `${[...tableNames].sort().join(\", \")}.\\n` +\n \"`rebase db push` switches it on: from then on the server and admins reach their rows, and anyone else \" +\n \"what each table's `rls` grants.\";\n}\n\n/**\n * Safely extract the host portion of a database URL for logging.\n */\nexport function safeHostFromUrl(url: string): string {\n return url.includes(\"@\") ? url.split(\"@\")[1] : \"(local connection)\";\n}\n","/**\n * The sequence a `SERIAL` column owns, named the way Postgres names it — how\n * introspection tells a key whose default is its own serial sequence (declared\n * `col.serial()`) from one fed by a sequence Rebase did not create (a\n * `{ kind: \"database\" }` default).\n */\n\n/**\n * The name Postgres gives a `SERIAL` column's sequence — `ChooseRelationName`\n * with the `seq` label: `<table>_<column>_seq`, and when that is over 63 bytes\n * the longer of the two names is shortened, one character at a time, until it\n * fits.\n */\nexport function serialSequenceName(table: string, column: string): string {\n const available = 63 - \"_seq\".length - 1;\n let tableChars = table.length;\n let columnChars = column.length;\n while (tableChars + columnChars > available) {\n if (tableChars > columnChars) tableChars--;\n else columnChars--;\n }\n return `${table.slice(0, tableChars)}_${column.slice(0, columnChars)}_seq`;\n}\n","/**\n * A table's `search` block, read back out of the column it built.\n *\n * A Rebase search column is `tsvector GENERATED ALWAYS AS (…) STORED`, stamped\n * with a fingerprint of the expression in its `COMMENT`. Introspection used to\n * emit it as an ordinary read-only text column, which the planner makes a\n * `text` column — so the first push after adopting a Rebase database planned\n * `ALTER COLUMN \"search_vector\" TYPE text … DROP EXPRESSION`, and search was\n * gone for whoever approved it.\n *\n * Reading the block back is a guess checked by the stamp: the deparsed\n * expression names each field's column, weight and language, which is enough\n * to write a candidate block; the candidate is then compiled by the very code\n * that built the column, and kept only if its fingerprint is the one the column\n * carries. A block that does not reproduce the stamp is not emitted at all —\n * the note says so — because a wrong one would rebuild the column differently.\n *\n * `mode` and `fuzzyThreshold` act at query time and are stored nowhere, so they\n * come back as their defaults.\n */\nimport {\n DEFAULT_SEARCH_COLUMN,\n DEFAULT_SEARCH_LANGUAGE,\n type ColumnDescriptor,\n type ColumnType,\n type SearchConfig,\n type TableDescriptor\n} from \"@rebasepro/types\";\nimport { buildTableSearchColumnSpec, searchColumnStamps, SEARCH_STAMP_PREFIX } from \"./search-column\";\nimport type { TableColumn } from \"./introspect-db-logic\";\n\n/** What introspection makes of a table's search columns. */\nexport interface ReconstructedSearch {\n /** The generated columns that belong to the search block — never emitted as columns. */\n columns: Set<string>;\n /** The table's `search` block, when the stamp confirmed it. */\n search?: SearchConfig;\n note?: string;\n}\n\n/** One `setweight(to_tsvector('<lang>'::regconfig, <text>), '<W>'::\"char\")`, deparsed. */\nconst SEGMENT = /setweight\\(to_tsvector\\('((?:[^']|'')+)'::regconfig, ([\\s\\S]+?)\\), '([A-D])'::\"char\"\\)/g;\n\n/**\n * The column's type as the search builder classifies it, for the candidate\n * block to resolve against: every string type reads as text, as the builder\n * indexes them alike.\n */\nfunction searchableTypeOf(col: TableColumn): ColumnType | undefined {\n if (col.data_type === \"text\" || col.data_type === \"character varying\" || col.data_type === \"character\") {\n return { kind: \"text\" };\n }\n if (col.udt_name === \"_text\") return { kind: \"array\", of: { kind: \"text\" } };\n if (col.data_type === \"jsonb\") return { kind: \"jsonb\" };\n return undefined;\n}\n\n/**\n * The search block a table's stamped generated columns were built from, or a\n * note saying why it could not be read back.\n */\nexport function reconstructSearchBlock(input: {\n schema: string;\n table: string;\n columns: TableColumn[];\n /** column → `COMMENT ON COLUMN`. */\n comments: Map<string, string>;\n /** column → the column key it is generated under. */\n keyByColumn: Map<string, string>;\n}): ReconstructedSearch {\n const stamped = input.columns.filter(col =>\n col.is_generated === \"ALWAYS\" && (input.comments.get(col.column_name) ?? \"\").startsWith(SEARCH_STAMP_PREFIX));\n const main = stamped.find(col => col.udt_name === \"tsvector\");\n if (!main) return { columns: new Set() };\n const fuzzy = stamped.find(col => col.column_name === `${main.column_name}_text`);\n const columns = new Set(stamped.map(col => col.column_name));\n\n const unreadable = (why: string): ReconstructedSearch => ({\n columns,\n note: `\"${main.column_name}\" is a Rebase search column whose \\`search\\` block could not be read back (${why}). ` +\n \"Declare the block again before pushing — without it a push plans dropping the column.\"\n });\n\n const expression = main.generation_expression ?? \"\";\n const byColumn = new Map(input.columns.map(col => [col.column_name, col]));\n const fields: { path: string; weight: string }[] = [];\n let language: string | undefined;\n let unaccent = false;\n for (const [, lang, inner, weight] of expression.matchAll(SEGMENT)) {\n language ??= lang.replace(/''/g, \"'\");\n if (lang.replace(/''/g, \"'\") !== language) return unreadable(\"its fields use different languages\");\n if (inner.includes(\"rebase_search_unaccent\")) unaccent = true;\n // The field's column is the first identifier in it that this table has.\n const column = [...inner.matchAll(/\"?([A-Za-z_][A-Za-z0-9_$]*)\"?/g)]\n .map(m => m[1])\n .find(name => byColumn.has(name) && !columns.has(name));\n if (!column) return unreadable(\"a field reads no column of this table\");\n const key = input.keyByColumn.get(column);\n if (!key) return unreadable(`the column \"${column}\" is not a declared column`);\n const jsonPath = [...inner.matchAll(/(?:->|#>)\\s*'([^']+)'/g)]\n .flatMap(m => m[1].replace(/^\\{|\\}$/g, \"\").split(\",\"));\n fields.push({ path: [key, ...jsonPath].join(\".\"), weight });\n }\n if (fields.length === 0 || !language) return unreadable(\"its expression is not one Rebase writes\");\n\n const search: SearchConfig = {\n ...(main.column_name !== DEFAULT_SEARCH_COLUMN ? { column: main.column_name } : {}),\n ...(language !== DEFAULT_SEARCH_LANGUAGE ? { language } : {}),\n ...(unaccent ? { unaccent: true } : {}),\n ...(fuzzy ? { fuzzy: true } : {}),\n fields: fields.map(f => ({ path: f.path, weight: f.weight as \"A\" | \"B\" | \"C\" | \"D\" }))\n };\n\n // Compiled by the code that built the column, and kept only if it is the\n // same column: the fingerprint is a hash of the exact expression.\n const candidateColumns: ColumnDescriptor[] = [];\n for (const [column, key] of input.keyByColumn) {\n const col = byColumn.get(column);\n const type = col ? searchableTypeOf(col) : undefined;\n if (type) candidateColumns.push({ key, column, type, nullable: true });\n }\n const candidate: TableDescriptor = {\n name: input.table,\n slug: input.table,\n table: input.table,\n schema: input.schema,\n kind: \"table\",\n columns: candidateColumns,\n primaryKey: [],\n relations: [],\n rls: { posture: \"rules\", rules: [], defaultPolicies: false },\n search\n };\n let fingerprints: Map<string, string>;\n try {\n const spec = buildTableSearchColumnSpec(candidate);\n if (!spec) return unreadable(\"no block compiles from it\");\n fingerprints = new Map(searchColumnStamps(spec).map(stamp => [stamp.column, stamp.fingerprint]));\n } catch (err) {\n return unreadable(err instanceof Error ? err.message : String(err));\n }\n for (const col of stamped) {\n if (fingerprints.get(col.column_name) !== input.comments.get(col.column_name)) {\n return unreadable(\"the block read from its expression does not reproduce the column's stamp\");\n }\n }\n\n return { columns, search };\n}\n","/**\n * Introspection that speaks tables: a database's catalogue, read into\n * {@link TableDescriptor}s.\n *\n * Two callers, one description:\n *\n * - **the runtime** (`introspectTables`, purpose `\"serve\"`): a backend with no\n * `backend/schema` serves every protected table of its database. The\n * descriptors are what `GET /api/schema/tables` serves, and what the\n * request-time collections are lowered from.\n * - **the source generator** (`rebase schema introspect`, purpose\n * `\"generate\"`): the descriptors are printed as `backend/schema/<table>.ts`.\n *\n * Columns are their Postgres types (`ColumnType`): a uuid stays a uuid, a\n * `varchar(n)` keeps its `n`, an enum its labels and its real type name; a type\n * Rebase serves but does not create is `{ kind: \"other\", sqlType }`. Defaults\n * are classified (`ColumnDefault`), identity and serial keys recognised,\n * generated columns kept. Wire keys are `toWireKey` of the column with the\n * first-free-key dedupe the runtime has always used, so the REST surface of an\n * introspected database does not move by one key.\n *\n * Row-level security is read from the catalogue (`relrowsecurity`,\n * `pg_policies`) and the refusal lives here, so every caller gets it: a table\n * whose row-level security is off is not described — it is in `skipped`, with\n * the SQL that protects it — unless the caller passes the one explicit opt-out,\n * `unprotectedTables: \"serve\"`.\n *\n * @module\n */\nimport type {\n ColumnDefault,\n ColumnDescriptor,\n ColumnType,\n OnAction,\n RelationDescriptor,\n RlsDescriptor,\n SearchConfig,\n SecurityRule,\n TableDescriptor,\n UnmappedTable\n} from \"@rebasepro/types\";\nimport { classifyTable, policyToSecurityRule, tableGeneratedPolicyNames } from \"@rebasepro/common\";\nimport { firstFreeKey, toWireKey } from \"@rebasepro/utils\";\n\nimport {\n buildEnumMap,\n buildTablesMap,\n identifyJoinTables,\n type ForeignKeyRow,\n type PolicyRow,\n type SchemaMetadata,\n type TableColumn,\n type TableMeta,\n type TableRow\n} from \"./introspect-db-logic\";\nimport { readSchemaMetadata, type QueryableClient } from \"./introspect-db-queries\";\nimport type { CheckFactsByTable } from \"./introspect-db-constraints\";\nimport { serialSequenceName } from \"./introspect-db-storage\";\nimport { reconstructSearchBlock } from \"./introspect-db-search\";\nimport { SEARCH_STAMP_PREFIX } from \"./search-column\";\nimport { foreignKeyIndexSpec } from \"./table-index\";\n\n// ── Result ───────────────────────────────────────────────────────────────────\n\n/**\n * A table introspection did not describe, and the SQL that would have it\n * described.\n *\n * @group Schema\n */\nexport interface SkippedTable {\n /** The table, unqualified. */\n table: string;\n /** Why, as a sentence. */\n reason: string;\n /** What to run so the table is served: `ALTER TABLE … ENABLE ROW LEVEL SECURITY;` and an example policy. */\n remediationSql: string;\n}\n\n/**\n * A junction table: folded away rather than described (the runtime serves no\n * junction; the generator makes it a `manyToMany`).\n *\n * @group Schema\n */\nexport interface IntrospectedJunction {\n table: string;\n /** `ALTER TABLE … ENABLE ROW LEVEL SECURITY` has been run on it. */\n rlsEnabled: boolean;\n}\n\n/**\n * What {@link introspectTables} returns.\n *\n * @group Schema\n */\nexport interface IntrospectedTables {\n /** One descriptor per table served, in table-name order. */\n tables: TableDescriptor[];\n /** The tables left out because row-level security is off on them, each with the SQL that protects it. */\n skipped: SkippedTable[];\n /** The junction tables, never described as tables. */\n junctions: IntrospectedJunction[];\n /** Tables described although row-level security is off on them — only with `unprotectedTables: \"serve\"`. */\n unprotected: string[];\n}\n\n/**\n * Options of {@link introspectTables}.\n *\n * @group Schema\n */\nexport interface IntrospectTablesOptions {\n /**\n * `\"serve\"` describes a table whose row-level security is off as well —\n * with a rule that says every caller reaches every row. The one explicit,\n * loud opt-out (`baas.unprotectedTables`); `\"exclude\"` (the default) leaves\n * such a table in `skipped`.\n */\n unprotectedTables?: \"exclude\" | \"serve\";\n}\n\n/**\n * What one table's description says about itself, by table, for the generator\n * to print: `drift` — what `rebase db push` would not reproduce exactly (a\n * column no builder states as it is, a foreign key no relation can hold) — and\n * `remark` — a decision the file states and the reader may want to undo\n * (`index: false`, a many-to-many declared on one end only).\n *\n * @group Schema\n */\nexport interface IntrospectionNotes {\n drift: Map<string, string[]>;\n remark: Map<string, string[]>;\n}\n\n/**\n * Options of {@link describeTables}.\n *\n * @group Schema\n */\nexport interface DescribeTablesOptions extends IntrospectTablesOptions {\n /**\n * - `\"serve\"` (default) — what the runtime serves, exactly as it always\n * has: owning links only (`belongsTo`, its foreign-key column marked\n * `derived` — the relation's, left out of the definition it is lowered\n * from, exactly the collection the runtime has always built), the\n * catalogue's policies as the rules, no heuristics.\n * - `\"generate\"` — what `schema introspect` writes: foreign-key columns\n * declared in `columns`, the reverse `hasMany` and the `manyToMany` of\n * each junction, the admin baseline folded into `\"admin-only\"` /\n * `defaultPolicies`, CHECK bounds as validation, `created_at` /\n * `updated_at` stamps, the `search` block read back, and a table whose\n * row-level security is off described as `\"admin-only\"` (the push then\n * switches it on).\n */\n purpose?: \"serve\" | \"generate\";\n /** The junction tables. Default: the runtime's name-based rule (`identifyJoinTables`). */\n joinTables?: ReadonlySet<string>;\n /** Tables the caller does not want described (and that nothing may point at). */\n leaveOut?: ReadonlySet<string>;\n /** The CHECK constraints, parsed (`parseCheckConstraints`): validation in `\"generate\"`. */\n checkFacts?: CheckFactsByTable;\n}\n\n/**\n * What {@link describeTables} returns: {@link IntrospectedTables} and the notes.\n *\n * @group Schema\n */\nexport interface DescribedTables extends IntrospectedTables {\n notes: IntrospectionNotes;\n}\n\n// ── Entry points ─────────────────────────────────────────────────────────────\n\n/**\n * Describe every table of a Postgres schema, as the runtime serves them.\n *\n * Reads the catalogue (`readSchemaMetadata`: tables with `relrowsecurity`,\n * columns, enums, keys, foreign keys, unique constraints, indexes, CHECKs,\n * comments, `pg_policies`) and describes each table that is neither a junction\n * nor unprotected. Only `SELECT`s.\n *\n * @group Schema\n */\nexport async function introspectTables(\n client: QueryableClient,\n schema: string,\n options: IntrospectTablesOptions = {}\n): Promise<IntrospectedTables> {\n const metadata = await readSchemaMetadata(client, schema);\n const { tables, skipped, junctions, unprotected } = describeTables(metadata, { purpose: \"serve\", ...options });\n return { tables, skipped, junctions, unprotected };\n}\n\n/**\n * The tables of one Postgres schema that no declared table maps, each\n * described for \"Import an existing table\" to adopt.\n *\n * Each table is described as `rebase schema introspect` writes it\n * (`describeTables(…, { purpose: \"generate\" })`), alone: a foreign key to a\n * declared table is a `belongsTo`, one to another undeclared table stays a\n * plain column (its constraint is left as it is), and the generator's reverse\n * links — relations of other tables — are not this table's to declare.\n *\n * Its `rls` is never weaker than what the database enforces: with row-level\n * security off, or no policy at all, it is `\"admin-only\"`, and `rlsRaised`\n * says so. A table with no primary key is listed with why it cannot be\n * imported. Junction tables and Rebase's own tables are left out. Only\n * `SELECT`s.\n *\n * @param mapped The SQL names of the tables already declared in `schema`.\n * @group Schema\n */\nexport async function describeUnmappedTables(\n client: QueryableClient,\n schema: string,\n options: { mapped: ReadonlySet<string> }\n): Promise<UnmappedTable[]> {\n const metadata = await readSchemaMetadata(client, schema);\n const tablesMap = buildTablesMap(metadata.tables, metadata.columns, metadata.pks, metadata.fks);\n const joinTables = identifyJoinTables(tablesMap);\n const candidates = metadata.tables\n .map(row => row.table_name)\n .filter(name => !options.mapped.has(name) && !joinTables.has(name) && classifyTable(name, schema) !== \"rebase-internal\");\n const out: UnmappedTable[] = [];\n for (const name of candidates) {\n const row = metadata.tables.find(candidate => candidate.table_name === name);\n const policies = metadata.policies?.filter(policy => policy.table_name === name) ?? [];\n const base = { schema, table: name, rlsEnabled: row?.rls_enabled === true, policies: policies.length };\n if ((tablesMap.get(name)?.pks.length ?? 0) === 0) {\n out.push({\n ...base,\n notes: [],\n unimportable: \"it has no primary key, and a table is declared with the column (or columns) that identify a row. \" +\n \"Add one (`ALTER TABLE … ADD PRIMARY KEY (…)`) and import it again.\"\n });\n continue;\n }\n const described = describeTables(metadata, {\n purpose: \"generate\",\n joinTables,\n leaveOut: new Set(candidates.filter(other => other !== name))\n });\n const found = described.tables.find(table => table.table === name);\n if (!found) {\n out.push({ ...base, notes: [], unimportable: \"introspection could not describe it.\" });\n continue;\n }\n const rlsRaised = !base.rlsEnabled\n ? `Row-level security is off on \"${name}\", so today every request reaches every row. It is imported as \"admin-only\": ` +\n \"applying it switches row-level security on, and from then on only the server and admins reach its rows, until you add rules.\"\n : policies.length === 0\n ? `\"${name}\" has row-level security on and no policy. It is imported as \"admin-only\": ` +\n \"applying it gives the server and admins its rows, and nobody else, until you add rules.\"\n : undefined;\n const descriptor: TableDescriptor = {\n ...found,\n relations: found.relations.filter(relation => relation.kind === \"belongsTo\"),\n ...(rlsRaised ? { rls: { posture: \"admin-only\", rules: [], defaultPolicies: true } } : {})\n };\n out.push({\n ...base,\n descriptor,\n ...(rlsRaised ? { rlsRaised } : {}),\n notes: [...(described.notes.drift.get(name) ?? []), ...(described.notes.remark.get(name) ?? [])]\n });\n }\n return out;\n}\n\n/**\n * The SQL that protects a table introspection skipped: row-level security on,\n * and an example policy to adapt — what boot prints for it.\n *\n * @group Schema\n */\nexport function rlsRemediationSql(schema: string, table: string): string {\n const relation = `${quoteIdent(schema)}.${quoteIdent(table)}`;\n return `ALTER TABLE ${relation} ENABLE ROW LEVEL SECURITY;\\n` +\n `CREATE POLICY ${quoteIdent(`${table}_owner`)} ON ${relation} FOR ALL TO public USING (owner_id = rebase.uid()); -- an example: write the condition that fits`;\n}\n\n/**\n * Describe a schema from catalogue rows already read. Pure.\n *\n * @group Schema\n */\nexport function describeTables(metadata: SchemaMetadata, options: DescribeTablesOptions = {}): DescribedTables {\n const generate = options.purpose === \"generate\";\n const schema = metadata.schema;\n const tablesMap = buildTablesMap(metadata.tables, metadata.columns, metadata.pks, metadata.fks);\n const enumMap = buildEnumMap(metadata.enumValues);\n const joinTables = options.joinTables ?? identifyJoinTables(tablesMap);\n const leaveOut = options.leaveOut ?? new Set<string>();\n const notes: IntrospectionNotes = { drift: new Map(), remark: new Map() };\n const note = (table: string, text: string, kind: keyof IntrospectionNotes = \"drift\"): void => {\n const list = notes[kind].get(table) ?? [];\n list.push(text);\n notes[kind].set(table, list);\n };\n\n const skipped: SkippedTable[] = [];\n const junctions: IntrospectedJunction[] = [];\n const unprotected: string[] = [];\n const described: TableRow[] = [];\n for (const row of metadata.tables) {\n const name = row.table_name;\n if (joinTables.has(name)) {\n junctions.push({ table: name, rlsEnabled: row.rls_enabled === true });\n continue;\n }\n if (leaveOut.has(name)) continue;\n if (!generate && row.rls_enabled !== true && options.unprotectedTables !== \"serve\") {\n skipped.push({\n table: name,\n reason: \"row-level security is disabled, so the table has no authorization model: every request would reach every row\",\n remediationSql: rlsRemediationSql(schema, name)\n });\n continue;\n }\n if (!generate && row.rls_enabled !== true) unprotected.push(name);\n described.push(row);\n }\n const servedNames = new Set(described.map(row => row.table_name));\n\n const context: TableContext = {\n metadata,\n schema,\n generate,\n tablesMap,\n enumMap,\n joinTables,\n servedNames,\n checkFacts: options.checkFacts ?? new Map(),\n note\n };\n // Keys first, for every table: a relation names its target's key column.\n const shapes = new Map<string, TableShape>();\n for (const row of described) {\n const meta = tablesMap.get(row.table_name);\n if (meta) shapes.set(row.table_name, shapeTable(meta, context));\n }\n const tables: TableDescriptor[] = [];\n for (const row of described) {\n const shape = shapes.get(row.table_name);\n if (shape) tables.push(describeTable(row, shape, shapes, context));\n }\n return { tables, skipped, junctions, unprotected, notes };\n}\n\n// ── Internals ────────────────────────────────────────────────────────────────\n\ninterface TableContext {\n metadata: SchemaMetadata;\n schema: string;\n generate: boolean;\n tablesMap: Map<string, TableMeta>;\n enumMap: Map<string, string[]>;\n joinTables: ReadonlySet<string>;\n servedNames: ReadonlySet<string>;\n checkFacts: CheckFactsByTable;\n note: (table: string, text: string, kind?: keyof IntrospectionNotes) => void;\n}\n\n/** A foreign key that becomes a `belongsTo`. */\ninterface OwningLink {\n fk: ForeignKeyRow;\n name: string;\n}\n\n/** One table's columns and owning links, before the relations that need other tables are resolved. */\ninterface TableShape {\n meta: TableMeta;\n columns: ColumnDescriptor[];\n /** column name → wire key. */\n keyByColumn: Map<string, string>;\n links: OwningLink[];\n /** Every key and relation name taken, so later relations stay unique. */\n taken: Set<string>;\n search?: SearchConfig;\n}\n\nconst quoteIdent = (name: string): string => `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n\n/** `NOT NULL` facts, as the catalogue says them. */\nconst isNotNull = (col: TableColumn): boolean => col.is_nullable === \"NO\";\n\n/** The foreign keys of a table that a `belongsTo` can hold: one column, pointing at the target's single-column key. */\nfunction linkableForeignKeys(meta: TableMeta, context: TableContext): ForeignKeyRow[] {\n const byConstraint = new Map<string, ForeignKeyRow[]>();\n for (const fk of meta.fks) {\n const key = fk.constraint_name ?? `${fk.column_name}->${fk.foreign_table_name}`;\n byConstraint.set(key, [...(byConstraint.get(key) ?? []), fk]);\n }\n const out: ForeignKeyRow[] = [];\n for (const [constraint, rows] of byConstraint) {\n const fk = rows[0];\n if (rows.length > 1) {\n context.note(meta.name, `the foreign key ${constraint} spans (${rows.map(r => r.column_name).join(\", \")}); a relation holds one column, so its columns are plain columns.`);\n continue;\n }\n if (!context.servedNames.has(fk.foreign_table_name)) continue;\n const target = context.tablesMap.get(fk.foreign_table_name);\n if (!target || target.pks.length !== 1 || target.pks[0] !== fk.foreign_column_name) {\n context.note(meta.name, `\"${fk.column_name}\" references ${fk.foreign_table_name}(${fk.foreign_column_name}), which is not that table's one-column primary key; a relation points at the key, so it stays a plain column.`);\n continue;\n }\n // One link per column: a second constraint on the same column says nothing new.\n if (out.some(other => other.column_name === fk.column_name)) continue;\n out.push(fk);\n }\n return out;\n}\n\nfunction shapeTable(meta: TableMeta, context: TableContext): TableShape {\n const { generate } = context;\n const comments = new Map<string, string>();\n for (const comment of context.metadata.comments) {\n if (comment.table_name === meta.name && comment.column_name !== null) comments.set(comment.column_name, comment.comment);\n }\n const links = linkableForeignKeys(meta, context);\n const linkColumns = new Set(links.map(fk => fk.column_name));\n // The search block's generated columns belong to `search`, not to `columns`.\n const searchColumns = new Set(meta.columns\n .filter(col => generate && col.is_generated === \"ALWAYS\" && (comments.get(col.column_name) ?? \"\").startsWith(SEARCH_STAMP_PREFIX))\n .map(col => col.column_name));\n\n // Wire keys, in the order the runtime has always taken them: the columns\n // that are not a link's first, in physical order, then the relation names,\n // then the link columns.\n const taken = new Set<string>();\n const keyByColumn = new Map<string, string>();\n const isFolded = (col: TableColumn): boolean => linkColumns.has(col.column_name) && !meta.pks.includes(col.column_name);\n for (const col of meta.columns) {\n if (searchColumns.has(col.column_name) || isFolded(col)) continue;\n const key = firstFreeKey([toWireKey(col.column_name), col.column_name], taken);\n taken.add(key);\n keyByColumn.set(col.column_name, key);\n }\n const named: OwningLink[] = [];\n if (generate) {\n // Declared columns: the link column keeps its own key, and the relation\n // is named beside it (a table keeps a column and a relation apart).\n for (const col of meta.columns) {\n if (!isFolded(col)) continue;\n const key = firstFreeKey([toWireKey(col.column_name), col.column_name], taken);\n taken.add(key);\n keyByColumn.set(col.column_name, key);\n }\n for (const fk of links) {\n const stripped = toWireKey(fk.column_name.replace(/_id$/, \"\"));\n const name = firstFreeKey([stripped, `${stripped}Relation`], taken);\n taken.add(name);\n named.push({ fk, name });\n }\n } else {\n // The runtime's names: `author_id` → `author`, and the target table when\n // the stripped name is a key column's own.\n for (const fk of links) {\n const stripped = toWireKey(fk.column_name.replace(/_id$/, \"\"));\n const pkCollision = meta.pks.includes(fk.column_name) && stripped === fk.column_name;\n const name = firstFreeKey([\n ...(pkCollision ? [] : [stripped]),\n fk.foreign_table_name,\n toWireKey(fk.foreign_table_name),\n `${stripped}Relation`\n ], taken);\n taken.add(name);\n named.push({ fk, name });\n }\n for (const col of meta.columns) {\n if (!isFolded(col)) continue;\n const key = firstFreeKey([toWireKey(col.column_name), col.column_name], taken);\n taken.add(key);\n keyByColumn.set(col.column_name, key);\n }\n }\n\n const uniques = new Set(context.metadata.uniques\n .filter(unique => unique.table_name === meta.name && unique.column_names.length === 1)\n .map(unique => unique.column_names[0]));\n const columns: ColumnDescriptor[] = [];\n for (const col of meta.columns) {\n const key = keyByColumn.get(col.column_name);\n if (key === undefined) continue;\n const link = named.find(entry => entry.fk.column_name === col.column_name);\n columns.push(describeColumn(col, key, meta, context, {\n unique: uniques.has(col.column_name),\n description: comments.get(col.column_name),\n foreignKeyOf: link?.name,\n derived: !generate && link !== undefined && isFolded(col)\n }));\n }\n\n let search: SearchConfig | undefined;\n if (generate && searchColumns.size > 0) {\n const read = reconstructSearchBlock({ schema: context.schema, table: meta.name, columns: meta.columns, comments, keyByColumn });\n if (read.note) context.note(meta.name, read.note);\n search = read.search;\n }\n return { meta, columns, keyByColumn, links: named, taken, search };\n}\n\n/** What a column's description needs besides the catalogue row. */\ninterface ColumnFacts {\n unique: boolean;\n description?: string;\n foreignKeyOf?: string;\n derived: boolean;\n}\n\nfunction describeColumn(col: TableColumn, key: string, meta: TableMeta, context: TableContext, facts: ColumnFacts): ColumnDescriptor {\n const isPk = meta.pks.includes(col.column_name);\n const sequenceKey = isPk && meta.pks.length === 1 ? serialKind(col) : undefined;\n const type = sequenceKey ?? columnTypeOf(col, context, meta.name);\n const out: ColumnDescriptor = {\n key,\n column: col.column_name,\n type,\n nullable: !isPk && !isNotNull(col)\n };\n if (isPk) out.primaryKey = true;\n if (facts.unique && !isPk) out.unique = true;\n if (col.is_generated === \"ALWAYS\" && col.generation_expression) {\n out.generated = { expression: col.generation_expression };\n out.readOnly = true;\n } else if (col.is_generated === \"ALWAYS\") {\n // Generated, by an expression this read did not return: never written.\n out.readOnly = true;\n context.note(meta.name, `\"${col.column_name}\" is a generated column whose expression was not read; it is declared read-only, and a push would plan it as a plain column.`);\n } else if (!sequenceKey) {\n const fallback = defaultOf(col, type);\n if (fallback) out.default = fallback;\n }\n if (facts.description !== undefined) out.description = facts.description;\n if (facts.foreignKeyOf !== undefined) out.foreignKeyOf = facts.foreignKeyOf;\n if (facts.derived) out.derived = true;\n if (context.generate) {\n applyGeneratedFacts(out, col, meta, context);\n }\n return out;\n}\n\n/**\n * The stamps and CHECK bounds the generator writes — what `schema introspect`\n * has always declared. Not in `\"serve\"`: the runtime stamps nothing the\n * database does not, and leaves CHECKs to the database.\n */\nfunction applyGeneratedFacts(out: ColumnDescriptor, col: TableColumn, meta: TableMeta, context: TableContext): void {\n const name = col.column_name.toLowerCase();\n const temporal = out.type.kind === \"timestamptz\" || out.type.kind === \"date\" || out.type.kind === \"time\";\n const nowDefault = out.default?.kind === \"sql\" && /^(now\\(\\)|CURRENT_TIMESTAMP)$/i.test(out.default.expression);\n if (temporal && !out.primaryKey && out.generated === undefined) {\n if (name === \"updated_at\" || name === \"updatedat\") {\n out.stamp = { on: \"update\", value: \"now\" };\n delete out.default;\n } else if (name === \"created_at\" || name === \"createdat\" || nowDefault) {\n out.stamp = { on: \"create\", value: \"now\" };\n delete out.default;\n }\n }\n const checks = context.checkFacts.get(meta.name)?.get(col.column_name);\n if (!checks) return;\n const numeric = [\"smallint\", \"integer\", \"bigint\", \"real\", \"doublePrecision\", \"numeric\"].includes(out.type.kind);\n const text = out.type.kind === \"text\" || out.type.kind === \"varchar\" || out.type.kind === \"char\";\n const validate: NonNullable<ColumnDescriptor[\"validate\"]> = {};\n if (numeric) {\n if (checks.min !== undefined) validate.min = checks.min;\n if (checks.max !== undefined) validate.max = checks.max;\n if (checks.moreThan !== undefined) validate.moreThan = checks.moreThan;\n if (checks.lessThan !== undefined) validate.lessThan = checks.lessThan;\n }\n if (text) {\n if (checks.lengthMin !== undefined) validate.min = checks.lengthMin;\n if (checks.lengthMax !== undefined) validate.max = checks.lengthMax;\n }\n if (Object.keys(validate).length > 0) out.validate = validate;\n if (checks.enumValues && text) {\n context.note(meta.name, `\"${col.column_name}\" accepts only ${checks.enumValues.map(v => `'${v}'`).join(\", \")} (a CHECK the database enforces); ` +\n \"a closed set on a text column is not declared yet (`.oneOf()` there waits on `text-one-of`), so the API leaves it to the database.\");\n }\n}\n\n/** `NEXTVAL('<table>_<column>_seq')`, the default `SERIAL` gives a column. */\nconst SEQUENCE_DEFAULT = /^nextval\\('([^']+)'::regclass\\)$/i;\n\n/** The serial kind of a single-column key whose default is its own conventional sequence. */\nfunction serialKind(col: TableColumn): ColumnType | undefined {\n const match = col.column_default ? SEQUENCE_DEFAULT.exec(col.column_default.trim()) : null;\n if (!match) return undefined;\n const bare = match[1].replace(/^.*\\./, \"\").replace(/^\"|\"$/g, \"\");\n if (bare !== serialSequenceName(col.table_name, col.column_name)) return undefined;\n switch (col.data_type.toLowerCase()) {\n case \"smallint\": return { kind: \"smallserial\" };\n case \"integer\": return { kind: \"serial\" };\n case \"bigint\": return { kind: \"bigserial\" };\n default: return undefined;\n }\n}\n\n/** A catalogue element type name (`udt_name` without the `_`) as the type an array holds, when it is one Rebase stores in an array. */\nfunction elementTypeOf(udt: string, typmod: number | null, enumMap: Map<string, string[]>): ColumnType | undefined {\n switch (udt) {\n case \"text\": return { kind: \"text\" };\n case \"varchar\": return typmod !== null && typmod > 4 ? { kind: \"varchar\", length: typmod - 4 } : { kind: \"text\" };\n case \"bpchar\": return { kind: \"char\", length: typmod !== null && typmod > 4 ? typmod - 4 : 1 };\n case \"uuid\": return { kind: \"uuid\" };\n case \"int2\": return { kind: \"smallint\" };\n case \"int4\": return { kind: \"integer\" };\n case \"int8\": return { kind: \"bigint\" };\n case \"float4\": return { kind: \"real\" };\n case \"float8\": return { kind: \"doublePrecision\" };\n case \"numeric\": return { kind: \"numeric\" };\n case \"bool\": return { kind: \"boolean\" };\n case \"timestamptz\": return { kind: \"timestamptz\" };\n case \"date\": return { kind: \"date\" };\n case \"time\": return { kind: \"time\" };\n default: {\n const labels = enumMap.get(udt);\n return labels ? { kind: \"enum\", values: labels, name: udt } : undefined;\n }\n }\n}\n\n/**\n * A column's Postgres type, as the catalogue states it. A type with no\n * `ColumnType` member is `{ kind: \"other\", sqlType }`, spelled as Postgres\n * names it — served as the driver returns it, and declared with `col.custom()`.\n */\nfunction columnTypeOf(col: TableColumn, context: TableContext, table: string): ColumnType {\n const dataType = col.data_type.toLowerCase();\n switch (dataType) {\n case \"text\": return { kind: \"text\" };\n case \"character varying\":\n if (typeof col.character_maximum_length === \"number\" && col.character_maximum_length > 0) {\n return { kind: \"varchar\", length: col.character_maximum_length };\n }\n context.note(table, `\"${col.column_name}\" is a varchar with no length, declared as text: a push would convert it to text, which keeps every value.`);\n return { kind: \"text\" };\n case \"character\": return { kind: \"char\", length: typeof col.character_maximum_length === \"number\" && col.character_maximum_length > 0 ? col.character_maximum_length : 1 };\n case \"uuid\": return { kind: \"uuid\" };\n case \"smallint\": return { kind: \"smallint\" };\n case \"integer\": return { kind: \"integer\" };\n case \"bigint\": return { kind: \"bigint\" };\n case \"real\": return { kind: \"real\" };\n case \"double precision\": return { kind: \"doublePrecision\" };\n case \"numeric\":\n if (typeof col.numeric_precision !== \"number\") return { kind: \"numeric\" };\n return typeof col.numeric_scale === \"number\"\n ? { kind: \"numeric\", precision: col.numeric_precision, scale: col.numeric_scale }\n : { kind: \"numeric\", precision: col.numeric_precision };\n case \"boolean\": return { kind: \"boolean\" };\n // A declared fractional precision (`timestamptz(3)`, `time(0)`) is no\n // builder's: kept as the type the database holds, so a push does not\n // widen the column back to the default of 6.\n case \"timestamp with time zone\":\n return withPrecision(col) ?? { kind: \"timestamptz\" };\n case \"date\": return { kind: \"date\" };\n case \"time without time zone\":\n return withPrecision(col) ?? { kind: \"time\" };\n case \"json\": return { kind: \"json\" };\n case \"jsonb\": return { kind: \"jsonb\" };\n case \"bytea\": return { kind: \"bytea\" };\n case \"user-defined\": {\n const labels = context.enumMap.get(col.udt_name);\n if (labels) return { kind: \"enum\", values: labels, name: col.udt_name };\n if (col.udt_name === \"vector\" && typeof col.atttypmod === \"number\" && col.atttypmod > 0) {\n return { kind: \"vector\", dimensions: col.atttypmod };\n }\n return { kind: \"other\", sqlType: col.formatted_type ?? col.udt_name };\n }\n case \"array\": {\n const element = col.udt_name.replace(/^_/, \"\");\n const of = elementTypeOf(element, col.atttypmod, context.enumMap);\n return of ? { kind: \"array\", of } : { kind: \"other\", sqlType: col.formatted_type ?? `${element}[]` };\n }\n // A `col.custom()` type, as `format_type` prints it where the read has\n // it — modifiers kept (`timestamp(3)`, a PostGIS SRID) — which is the\n // type a push then writes back.\n default:\n return { kind: \"other\", sqlType: col.formatted_type ?? col.data_type };\n }\n}\n\n/** A temporal column with a declared precision, as `col.custom()` of the type the catalogue prints; `undefined` without one. */\nfunction withPrecision(col: TableColumn): ColumnType | undefined {\n return col.formatted_type && /\\(\\d+\\)/.test(col.formatted_type) ? { kind: \"other\", sqlType: col.formatted_type } : undefined;\n}\n\n/** `'text'::type` → `text`, unescaped. */\nconst QUOTED_LITERAL = /^'((?:[^']|'')*)'(?:::[\\w\\s.\"[\\]]+)?$/;\n\n/**\n * A column's DEFAULT, classified.\n *\n * - identity → `{ kind: \"identity\" }`; `gen_random_uuid()` → `random-uuid`;\n * - a literal of the column's own type → `literal`;\n * - an expression Rebase can state again verbatim (`now()`, a function call,\n * an operator) → `sql`;\n * - a `nextval` of a sequence that is not the column's own `SERIAL` one —\n * an object Rebase does not create, so stating it would fail on a fresh\n * database — → `database`: the database owns it, and a push leaves it alone.\n */\nfunction defaultOf(col: TableColumn, type: ColumnType): ColumnDefault | undefined {\n if (col.is_identity === \"YES\") return { kind: \"identity\" };\n const raw = col.column_default?.trim();\n if (!raw) return undefined;\n if (/^gen_random_uuid\\(\\)$/i.test(raw) && type.kind === \"uuid\") return { kind: \"random-uuid\" };\n if (/^nextval\\(/i.test(raw)) return { kind: \"database\" };\n // `DEFAULT NULL` is no default.\n if (/^NULL(::[\\w\\s.\"[\\]]+)?$/i.test(raw)) return undefined;\n const literal = literalOf(raw, type);\n if (literal !== undefined) return { kind: \"literal\", value: literal };\n return { kind: \"sql\", expression: raw };\n}\n\n/** A DEFAULT that is a literal of the column's type, as the value; `undefined` when it is an expression. */\nfunction literalOf(raw: string, type: ColumnType): unknown {\n const quoted = QUOTED_LITERAL.exec(raw);\n const text = quoted ? quoted[1].replace(/''/g, \"'\") : undefined;\n switch (type.kind) {\n case \"text\":\n case \"varchar\":\n case \"char\":\n case \"enum\":\n return text;\n case \"smallint\":\n case \"integer\":\n case \"bigint\":\n case \"real\":\n case \"doublePrecision\":\n case \"numeric\": {\n const value = text ?? raw.replace(/^\\((.*)\\)$/, \"$1\").replace(/::[\\w\\s]+$/, \"\");\n return /^-?\\d+(\\.\\d+)?$/.test(value) && Number.isFinite(Number(value)) ? Number(value) : undefined;\n }\n case \"boolean\":\n if (/^true$/i.test(raw)) return true;\n if (/^false$/i.test(raw)) return false;\n return undefined;\n case \"json\":\n case \"jsonb\": {\n if (text === undefined) return undefined;\n try {\n const parsed: unknown = JSON.parse(text);\n return parsed !== null && typeof parsed === \"object\" ? parsed : undefined;\n } catch {\n return undefined;\n }\n }\n case \"date\":\n case \"time\":\n case \"timestamptz\":\n return text !== undefined && /^\\d/.test(text) ? text : undefined;\n default:\n return undefined;\n }\n}\n\n/** `ON DELETE`, when it is not the default a relation gets (`RESTRICT` for a required link, `SET NULL` otherwise). */\nfunction onDeleteOf(fk: ForeignKeyRow, required: boolean): OnAction | undefined {\n const rule = fk.delete_rule?.toLowerCase();\n if (!rule) return undefined;\n if (rule === (required ? \"restrict\" : \"set null\")) return undefined;\n switch (rule) {\n case \"cascade\":\n case \"restrict\":\n case \"no action\":\n case \"set null\":\n case \"set default\":\n return rule;\n default:\n return undefined;\n }\n}\n\nfunction describeTable(row: TableRow, shape: TableShape, shapes: ReadonlyMap<string, TableShape>, context: TableContext): TableDescriptor {\n const { meta } = shape;\n const name = meta.name;\n const relations: RelationDescriptor[] = [];\n for (const link of shape.links) {\n const col = meta.columns.find(column => column.column_name === link.fk.column_name);\n const required = col ? isNotNull(col) : false;\n const onDelete = onDeleteOf(link.fk, required);\n relations.push({\n name: link.name,\n kind: \"belongsTo\",\n target: link.fk.foreign_table_name,\n cardinality: \"one\",\n localKey: link.fk.column_name,\n localField: shape.keyByColumn.get(link.fk.column_name) ?? toWireKey(link.fk.column_name),\n ...(onDelete !== undefined ? { onDelete } : {}),\n index: foreignKeyIndexed(name, link.fk.column_name, meta, context),\n constraint: true\n });\n }\n if (context.generate) {\n relations.push(...inverseRelations(name, shape, shapes, context));\n }\n\n let description: string | undefined;\n for (const comment of context.metadata.comments) {\n if (comment.table_name === name && comment.column_name === null) description = comment.comment;\n }\n const descriptor: TableDescriptor = {\n name,\n slug: name,\n table: name,\n schema: context.schema,\n kind: \"table\",\n ...(description !== undefined ? { description } : {}),\n columns: shape.columns,\n primaryKey: meta.pks.map(pk => shape.keyByColumn.get(pk) ?? toWireKey(pk)),\n relations,\n rls: rlsOf(row, name, context)\n };\n if (shape.search) descriptor.search = shape.search;\n return descriptor;\n}\n\n/**\n * Whether the database indexes a foreign-key column the way Rebase would —\n * so that a `belongsTo` saying `index: true` (the default) plans no new\n * index. `true` when the indexes were not read: nothing is claimed then.\n */\nfunction foreignKeyIndexed(table: string, column: string, meta: TableMeta, context: TableContext): boolean {\n const indexes = context.metadata.indexes?.filter(index => index.table_name === table);\n if (indexes === undefined || meta.pks[0] === column) return true;\n const derived = foreignKeyIndexSpec(context.schema, table, column).indexName;\n if (indexes.some(index => index.index_name === derived)) return true;\n const servedBy = indexes.find(index => index.leading_column === column && index.serves_leading_column);\n context.note(table, servedBy\n ? `${servedBy.index_name} already indexes \"${column}\", so its relation says \\`index: false\\`: without it \\`rebase db push\\` would build a second index.`\n : `the database has no index on \"${column}\", so its relation says \\`index: false\\`; drop that to have one built.`, \"remark\");\n return false;\n}\n\n/** The generator's reverse links: a `hasMany` for each foreign key into the table, a `manyToMany` through each junction. */\nfunction inverseRelations(table: string, shape: TableShape, shapes: ReadonlyMap<string, TableShape>, context: TableContext): RelationDescriptor[] {\n const out: RelationDescriptor[] = [];\n const nameFor = (preferred: string, fallback: string): string => {\n const name = firstFreeKey([preferred, fallback], shape.taken);\n shape.taken.add(name);\n return name;\n };\n for (const [source, other] of shapes) {\n for (const link of other.links) {\n if (link.fk.foreign_table_name !== table) continue;\n out.push({\n name: nameFor(source, `${source}_by_${link.fk.column_name}`),\n kind: \"hasMany\",\n target: source,\n cardinality: \"many\",\n foreignKey: link.fk.column_name\n });\n }\n }\n for (const junction of context.joinTables) {\n const jt = context.tablesMap.get(junction);\n if (!jt || jt.fks.length < 2) continue;\n const keyPosition = (fk: ForeignKeyRow): number => {\n const position = jt.pks.indexOf(fk.column_name);\n return position === -1 ? Number.MAX_SAFE_INTEGER : position;\n };\n const linkColumns = new Set(jt.fks.map(fk => fk.column_name));\n const pivot = (): ColumnDescriptor[] => jt.columns\n .filter(col => !linkColumns.has(col.column_name))\n .map(col => {\n const column = describeColumn(col, toWireKey(col.column_name), { ...jt, pks: [] }, context, { unique: false, derived: false });\n delete column.primaryKey;\n return column;\n });\n const selfLinks = jt.fks.filter(fk => fk.foreign_table_name === table).sort((a, b) => keyPosition(a) - keyPosition(b));\n if (selfLinks.length === 2) {\n const [own, otherEnd] = selfLinks;\n const preferred = `${table}_via_${otherEnd.column_name.replace(/_id$/, \"\")}`;\n out.push({\n name: nameFor(preferred, `${preferred}_${junction}`),\n kind: \"manyToMany\",\n target: table,\n cardinality: \"many\",\n through: { table: junction, sourceKey: own.column_name, targetKey: otherEnd.column_name, pivot: pivot() }\n });\n continue;\n }\n const own = jt.fks.find(fk => fk.foreign_table_name === table);\n const otherEnd = jt.fks.find(fk => fk.foreign_table_name !== table);\n if (!own || !otherEnd || !context.servedNames.has(otherEnd.foreign_table_name)) continue;\n // Which ends declare the link decides how the planner keys the junction:\n // from the one declaring side, or — when both declare it — from the side\n // whose table sorts first. Declared here only when that keys it the way\n // the database already has it.\n const leading = jt.fks.find(fk => fk.column_name === jt.pks[0])?.foreign_table_name;\n const sortsFirst = [table, otherEnd.foreign_table_name].sort()[0];\n if (leading && leading !== sortsFirst && leading !== table) {\n context.note(table, `the many-to-many with ${otherEnd.foreign_table_name} through ${junction} is declared on ${otherEnd.foreign_table_name} only: declaring it here too would re-key ${junction} from (${jt.pks.join(\", \")}).`, \"remark\");\n continue;\n }\n out.push({\n name: nameFor(otherEnd.foreign_table_name, `${otherEnd.foreign_table_name}_via_${junction}`),\n kind: \"manyToMany\",\n target: otherEnd.foreign_table_name,\n cardinality: \"many\",\n through: { table: junction, sourceKey: own.column_name, targetKey: otherEnd.column_name, pivot: pivot() }\n });\n }\n return out;\n}\n\n/** The admin baseline's policy names (`<table>_default_admin_*`). */\nconst adminBaselineNames = (table: string): Set<string> =>\n tableGeneratedPolicyNames({ slug: table, table, columns: {}, links: {}, idKey: \"id\", rules: [], auth: false });\n\n/** A `pg_policies` row as the rule `db push` compiles back into it. */\nfunction ruleOf(policy: PolicyRow): SecurityRule {\n const cmd = policy.cmd.toUpperCase();\n return policyToSecurityRule({\n policyname: policy.policy_name,\n cmd: cmd === \"SELECT\" || cmd === \"INSERT\" || cmd === \"UPDATE\" || cmd === \"DELETE\" || cmd === \"ALL\" ? cmd : undefined,\n permissive: policy.permissive.toUpperCase() === \"RESTRICTIVE\" ? \"RESTRICTIVE\" : \"PERMISSIVE\",\n roles: policy.roles,\n qual: policy.qual,\n with_check: policy.with_check\n });\n}\n\n/**\n * A table's row-level security, from the catalogue.\n *\n * `\"serve\"`: every policy as a rule, `defaultPolicies: false` (Rebase injected\n * nothing). RLS on with no policy is `rules: []` — closed. RLS off (only with\n * `unprotectedTables: \"serve\"`) is one rule granting everyone everything,\n * which is what such a table does.\n *\n * `\"generate\"`: the admin baseline is folded — a table holding every baseline\n * policy keeps `defaultPolicies` and lists only its own; holding nothing else,\n * it is `\"admin-only\"`. RLS on with no policy at all is one closed rule (a\n * push then creates a policy that grants nothing, which is what the table\n * does today). RLS off keeps the baseline and its own policies (`\"admin-only\"`\n * when it has none): the push switches it on.\n */\nfunction rlsOf(row: TableRow, table: string, context: TableContext): RlsDescriptor {\n const policies = context.metadata.policies?.filter(policy => policy.table_name === table);\n if (!context.generate) {\n if (row.rls_enabled !== true) {\n return { posture: \"rules\", rules: [{ name: `${table}_rls_disabled`, operations: [\"all\"], access: \"public\" }], defaultPolicies: false };\n }\n return { posture: \"rules\", rules: (policies ?? []).map(ruleOf), defaultPolicies: false };\n }\n if (policies === undefined) return { posture: \"admin-only\", rules: [], defaultPolicies: true };\n const baseline = adminBaselineNames(table);\n if (row.rls_enabled === false) {\n // The push switches RLS on whatever the file says; the table keeps the\n // baseline (nothing narrowed anyone before) and its own policies.\n const own = policies.filter(policy => !baseline.has(policy.policy_name)).map(ruleOf);\n return own.length > 0 ? { posture: \"rules\", rules: own, defaultPolicies: true } : { posture: \"admin-only\", rules: [], defaultPolicies: true };\n }\n const present = new Set(policies.map(policy => policy.policy_name));\n if (row.rls_enabled !== true && present.size === 0) return { posture: \"admin-only\", rules: [], defaultPolicies: true };\n const keepsBaseline = [...baseline].every(name => present.has(name));\n const own = policies.filter(policy => !(keepsBaseline && baseline.has(policy.policy_name))).map(ruleOf);\n if (keepsBaseline) return own.length > 0 ? { posture: \"rules\", rules: own, defaultPolicies: true } : { posture: \"admin-only\", rules: [], defaultPolicies: true };\n if (own.length > 0) return { posture: \"rules\", rules: own, defaultPolicies: false };\n return { posture: \"rules\", rules: [{ name: `${table}_closed`, operation: \"all\", using: \"false\" }], defaultPolicies: false };\n}\n"],"mappings":";;;;;;;;;AAmBA,IAAM,WAAW;CAAC;CAAiB;CAAc;CAAgB;AAAgB;AACjF,IAAM,aAAa;AACnB,IAAM,aAAa;AAEnB,IAAM,iBAAiB,SACnB;CAAC;CAAY;CAAW;CAAU;CAAQ;CAAmB;AAAS,CAAC,CAAC,SAAS,KAAK,IAAI;AAC9F,IAAM,cAAc,SAA8B,KAAK,SAAS,UAAU,KAAK,SAAS,aAAa,KAAK,SAAS;;;;;;;;;;;;AAanH,SAAgB,iBAAiB,YAAoB,MAAkB,cAA+C;CAClH,MAAM,SAAS,aAAa,QAAO,UAAS,UAAU,QAAQ,UAAU,KAAA,KAAa,UAAU,EAAE;CACjG,IAAI,OAAO,WAAW,GAAG,OAAO,CAAC;CACjC,MAAM,OAAO,WAAW,YAAY;CAEpC,IAAI,cAAc,IAAI,GAAG;EACrB,MAAM,UAAU,OAAO,IAAI,MAAM,CAAC,CAAC,QAAO,UAAS,CAAC,OAAO,MAAM,KAAK,CAAC;EACvE,IAAI,QAAQ,WAAW,OAAO,QAAQ,OAAO,CAAC;EAC9C,MAAM,MAAM,KAAK,IAAI,GAAG,OAAO;EAC/B,MAAM,MAAM,KAAK,IAAI,GAAG,OAAO;EAC/B,IAAI,OAAO,KAAK,OAAO,OAAO,qBAAqB,KAAK,IAAI,GAAG,OAAO,EAAE,UAAU;GAAE,KAAK;GAAG,KAAK;EAAI,EAAE;EACvG,IAAI,OAAO,KAAK,qBAAqB,KAAK,IAAI,GAAG,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE;EAC/E,OAAO,CAAC;CACZ;CAEA,IAAI,CAAC,WAAW,IAAI,KAAK,CAAC,OAAO,OAAM,UAAS,OAAO,UAAU,QAAQ,GAAG,OAAO,CAAC;CACpF,MAAM,UAAU,OAAO,QA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