@rebasepro/server-postgres 0.33.2 → 0.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{BranchService-Bdin0Wxh.js → BranchService-BLcVK_Rd.js} +3 -3
- package/dist/{BranchService-Bdin0Wxh.js.map → BranchService-BLcVK_Rd.js.map} +1 -1
- package/dist/{backup-cli-BEAMPWMs.js → backup-cli-CVLOCTo_.js} +3 -3
- package/dist/{backup-cli-BEAMPWMs.js.map → backup-cli-CVLOCTo_.js.map} +1 -1
- package/dist/{boot-ddl-Bu6gAY-2.js → boot-ddl-C7hAFEvY.js} +2 -2
- package/dist/{boot-ddl-Bu6gAY-2.js.map → boot-ddl-C7hAFEvY.js.map} +1 -1
- package/dist/{cli-console-BU_Rf22O.js → cli-console-E5TM3GaL.js} +4 -4
- package/dist/{cli-console-BU_Rf22O.js.map → cli-console-E5TM3GaL.js.map} +1 -1
- package/dist/{cli-schema-dir-CjDH_31U.js → cli-schema-dir-CdEqBcph.js} +29 -10
- package/dist/cli-schema-dir-CdEqBcph.js.map +1 -0
- package/dist/cli.js +29 -27
- package/dist/cli.js.map +1 -1
- package/dist/{database-preflight-DKzsGnc4.js → database-preflight-NmFI_rFN.js} +2 -2
- package/dist/{database-preflight-DKzsGnc4.js.map → database-preflight-NmFI_rFN.js.map} +1 -1
- package/dist/{deferred-index-build-88bWtYgx.js → deferred-index-build-Bz37bvxW.js} +4 -4
- package/dist/{deferred-index-build-88bWtYgx.js.map → deferred-index-build-Bz37bvxW.js.map} +1 -1
- package/dist/{ensure-policies-nIITKxud.js → ensure-policies-C1UCom37.js} +6 -6
- package/dist/{ensure-policies-nIITKxud.js.map → ensure-policies-C1UCom37.js.map} +1 -1
- package/dist/{ensure-tables-hQ5oAK_j.js → ensure-tables-BVUNi6uG.js} +3 -3
- package/dist/{ensure-tables-hQ5oAK_j.js.map → ensure-tables-BVUNi6uG.js.map} +1 -1
- package/dist/{ensure-tables-Lm-77eM5.js → ensure-tables-DjuNRClr.js} +7 -7
- package/dist/{ensure-tables-Lm-77eM5.js.map → ensure-tables-DjuNRClr.js.map} +1 -1
- package/dist/{enum-labels-kept-mesgEJWH.js → enum-labels-kept-DrCueSHr.js} +2 -2
- package/dist/{enum-labels-kept-mesgEJWH.js.map → enum-labels-kept-DrCueSHr.js.map} +1 -1
- package/dist/{generated-schema-diff-DoT2dYDe.js → generated-schema-diff-DDktAATD.js} +2 -2
- package/dist/{generated-schema-diff-DoT2dYDe.js.map → generated-schema-diff-DDktAATD.js.map} +1 -1
- package/dist/index.es.js +11 -11
- package/dist/{introspect-db-queries-BgiRQqtR.js → introspect-db-queries-D7u9EOfV.js} +66 -4
- package/dist/introspect-db-queries-D7u9EOfV.js.map +1 -0
- package/dist/{introspect-tables-Cw_A-kk4.js → introspect-tables-2yJ3p98l.js} +267 -30
- package/dist/introspect-tables-2yJ3p98l.js.map +1 -0
- package/dist/{migrate-baseline-Bzj5gSCM.js → migrate-baseline-CnIbBRgh.js} +4 -3
- package/dist/{migrate-baseline-Bzj5gSCM.js.map → migrate-baseline-CnIbBRgh.js.map} +1 -1
- package/dist/{migrate-policy-stamps-C2WaOEsB.js → migrate-policy-stamps-D7BaYeKO.js} +4 -4
- package/dist/{migrate-policy-stamps-C2WaOEsB.js.map → migrate-policy-stamps-D7BaYeKO.js.map} +1 -1
- package/dist/{open-rebase-x3yAPy5g.js → open-rebase-DykxNl1j.js} +72 -20
- package/dist/open-rebase-DykxNl1j.js.map +1 -0
- package/dist/{pg-error-utils-CWopxboq.js → pg-error-utils-DXyqf9yP.js} +2 -2
- package/dist/{pg-error-utils-CWopxboq.js.map → pg-error-utils-DXyqf9yP.js.map} +1 -1
- package/dist/{policy-drift-rVLKS2AG.js → policy-drift-B2Czzs2Z.js} +3 -3
- package/dist/{policy-drift-rVLKS2AG.js.map → policy-drift-B2Czzs2Z.js.map} +1 -1
- package/dist/{push-index-adoption-EcamXfW2.js → push-index-adoption-DTLPk_5i.js} +2 -2
- package/dist/{push-index-adoption-EcamXfW2.js.map → push-index-adoption-DTLPk_5i.js.map} +1 -1
- package/dist/{push-index-prebuild-BPIns6wA.js → push-index-prebuild-WP5272gZ.js} +3 -3
- package/dist/{push-index-prebuild-BPIns6wA.js.map → push-index-prebuild-WP5272gZ.js.map} +1 -1
- package/dist/{push-legacy-renames-lmYkb41I.js → push-legacy-renames-CvWSBxRu.js} +3 -3
- package/dist/{push-legacy-renames-lmYkb41I.js.map → push-legacy-renames-CvWSBxRu.js.map} +1 -1
- package/dist/{push-policy-plan-Dqu4FKWh.js → push-policy-plan-D8HvHgPs.js} +3 -3
- package/dist/{push-policy-plan-Dqu4FKWh.js.map → push-policy-plan-D8HvHgPs.js.map} +1 -1
- package/dist/{request-role-cli-Ay0v9oYZ.js → request-role-cli-Y5Uqalop.js} +8 -8
- package/dist/{request-role-cli-Ay0v9oYZ.js.map → request-role-cli-Y5Uqalop.js.map} +1 -1
- package/dist/{request-role-migration-DTE3Owsh.js → request-role-migration-Cc0gJSso.js} +2 -2
- package/dist/{request-role-migration-DTE3Owsh.js.map → request-role-migration-Cc0gJSso.js.map} +1 -1
- package/dist/{rls-enforcement-Ck-d8zdJ.js → rls-enforcement-NZKe3Jr-.js} +2 -2
- package/dist/{rls-enforcement-Ck-d8zdJ.js.map → rls-enforcement-NZKe3Jr-.js.map} +1 -1
- package/dist/schema/destructive-sql.d.ts +9 -1
- package/dist/schema/doctor-cli.js +6 -6
- package/dist/schema/introspect-db-logic.d.ts +51 -0
- package/dist/schema/introspect-db-project.d.ts +6 -0
- package/dist/schema/introspect-db-queries.d.ts +21 -2
- package/dist/schema/introspect-db.js +53 -4
- package/dist/schema/introspect-db.js.map +1 -1
- package/dist/schema/introspect-foreign.d.ts +47 -0
- package/dist/schema/introspect-tables.d.ts +17 -0
- package/dist/schema/undeclarable-constraints.d.ts +16 -3
- package/dist/utils/result-rows.d.ts +20 -0
- package/dist/{websocket-DAVDn7Ki.js → websocket-CvmbzBeS.js} +3 -3
- package/dist/{websocket-DAVDn7Ki.js.map → websocket-CvmbzBeS.js.map} +1 -1
- package/package.json +7 -7
- package/dist/cli-schema-dir-CjDH_31U.js.map +0 -1
- package/dist/introspect-db-queries-BgiRQqtR.js.map +0 -1
- package/dist/introspect-tables-Cw_A-kk4.js.map +0 -1
- package/dist/open-rebase-x3yAPy5g.js.map +0 -1
package/dist/{generated-schema-diff-DoT2dYDe.js.map → generated-schema-diff-DDktAATD.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generated-schema-diff-DoT2dYDe.js","names":[],"sources":["../src/schema/introspect-runtime.ts","../src/utils/pg-array-null-patch.ts","../src/schema/dynamic-tables.ts","../src/schema/config-relations.ts","../src/schema/catalogue-schema.ts","../src/schema/generated-schema-diff.ts"],"sourcesContent":["/**\n * Runtime introspection — what a backend with no `backend/schema` serves.\n *\n * `introspectTables` (`./introspect-tables`) describes every protected table\n * of the database as a `TableDescriptor`; this module compiles those into the\n * tables the runtime runs on (`compileIntrospectedTables`) and reads the catalogue the\n * runtime builds its Drizzle tables from (`introspectSchema`, shared with the\n * declared path in `catalogue-schema.ts`).\n *\n * Distinct from `introspect-db.ts`, which describes the same database with\n * `describeTables(…, { purpose: \"generate\" })` and prints the descriptors as\n * `backend/schema` source for a developer to edit and commit.\n */\nimport type { CompiledTable, TableDescriptor } from \"@rebasepro/types\";\nimport { compileDescribedTables, isSchemaDefinitionError } from \"@rebasepro/common\";\n\nimport {\n TableRow,\n TableColumn,\n EnumValue,\n PrimaryKeyRow,\n ForeignKeyRow,\n TableMeta,\n buildTablesMap,\n buildEnumMap,\n identifyJoinTables\n} from \"./introspect-db-logic\";\n\nexport interface IntrospectedSchema {\n tablesMap: Map<string, TableMeta>;\n enumMap: Map<string, string[]>;\n joinTables: Set<string>;\n}\n\n/** Minimal query surface — satisfied by pg.Client and pg.Pool alike. */\nexport interface Queryable {\n query<R>(text: string, values?: unknown[]): Promise<{ rows: R[] }>;\n}\n\n/**\n * Read tables, columns, enums, primary keys and foreign keys for a schema.\n * Mirrors the queries in introspect-db.ts.\n */\nexport async function introspectSchema(\n client: Queryable,\n pgSchema: string,\n /**\n * Read views and materialized views too, as tables to read from — what\n * the runtime catalogue needs for tables declared with `defineView`. Off\n * for introspection that turns relations into tables to serve, where a\n * view is not one.\n */\n options: { views?: boolean } = {}\n): Promise<IntrospectedSchema> {\n const { rows: tables } = await client.query<TableRow>(\n `SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = $1 AND table_type ${options.views ? \"IN ('BASE TABLE', 'VIEW')\" : \"= 'BASE TABLE'\"}\n AND table_name NOT LIKE 'drizzle_%'\n AND table_name NOT LIKE 'rebase_%'\n ${options.views ? `UNION\n SELECT c.relname AS table_name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = $1 AND c.relkind = 'm'\n AND COALESCE(obj_description(c.oid, 'pg_class'), '') NOT LIKE 'rebase:view-rows:%'` : \"\"}\n ORDER BY table_name`,\n [pgSchema]\n );\n\n const { rows: columns } = await client.query<TableColumn>(\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 -- A stored generated column must be declared as one, or drizzle\n -- writes DEFAULT into it on every INSERT. Postgres tolerates that\n -- today; the generated module has always declared them properly,\n -- and the runtime tables are built to match it.\n c.is_generated,\n c.generation_expression,\n (SELECT a.atttypmod FROM pg_attribute a\n JOIN pg_class pc ON a.attrelid = pc.oid\n WHERE pc.relname = c.table_name\n AND a.attname = c.column_name\n AND pc.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = c.table_schema)) as atttypmod\n FROM information_schema.columns c\n WHERE c.table_schema = $1\n -- A table has no column of that name (it is a system column); the\n -- gate of a materialized view carries one for fingerprint(), and it\n -- is not the collection's.\n AND NOT (c.column_name = 'xmin' AND EXISTS (\n SELECT 1 FROM information_schema.views v\n WHERE v.table_schema = c.table_schema AND v.table_name = c.table_name))\n ${options.views ? `UNION ALL\n -- A materialized view is in neither information_schema.tables nor\n -- .columns: its columns, in the same shape, from the catalogue.\n SELECT c.relname, a.attname,\n CASE WHEN t.typcategory = 'A' THEN 'ARRAY' WHEN t.typtype = 'e' THEN 'USER-DEFINED'\n ELSE format_type(a.atttypid, NULL) END,\n t.typname, CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END, NULL, 'NEVER', NULL, a.atttypmod\n FROM pg_attribute a\n JOIN pg_class c ON c.oid = a.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n JOIN pg_type t ON t.oid = a.atttypid\n WHERE n.nspname = $1 AND c.relkind = 'm' AND a.attnum > 0 AND NOT a.attisdropped\n AND COALESCE(obj_description(c.oid, 'pg_class'), '') NOT LIKE 'rebase:view-rows:%'` : \"\"}`,\n [pgSchema]\n );\n\n const { rows: enumValues } = await client.query<EnumValue>(\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 [pgSchema]\n );\n\n const { rows: pks } = await client.query<PrimaryKeyRow>(\n `SELECT t.relname as table_name, a.attname as column_name\n FROM pg_index i\n JOIN pg_attribute a ON a.attrelid = i.indrelid\n AND a.attnum = ANY(i.indkey)\n JOIN pg_class t ON t.oid = i.indrelid\n JOIN pg_namespace n ON n.oid = t.relnamespace\n WHERE i.indisprimary AND n.nspname = $1`,\n [pgSchema]\n );\n\n const { rows: fks } = await client.query<ForeignKeyRow>(\n `SELECT\n tc.table_name,\n kcu.column_name,\n ccu.table_name AS foreign_table_name,\n ccu.column_name AS foreign_column_name\n FROM information_schema.table_constraints AS tc\n JOIN information_schema.key_column_usage AS kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n JOIN information_schema.constraint_column_usage AS ccu\n ON ccu.constraint_name = tc.constraint_name\n AND ccu.table_schema = tc.table_schema\n WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = $1`,\n [pgSchema]\n );\n\n const tablesMap = buildTablesMap(tables, columns, pks, fks);\n return {\n tablesMap,\n enumMap: buildEnumMap(enumValues),\n joinTables: identifyJoinTables(tablesMap)\n };\n}\n\n/**\n * What {@link compileIntrospectedTables} returns.\n *\n * @group Schema\n */\nexport interface CompiledIntrospection {\n /** The descriptors served — every one given, unless it is in {@link dropped}. */\n tables: TableDescriptor[];\n /** The same tables compiled for the runtime, one per descriptor of {@link tables}, in the same order. */\n compiled: CompiledTable[];\n /**\n * Descriptors no definition could be built from, each with why: a table\n * `defineTable` itself refuses (no columns, a schema name that is not a plain\n * identifier). They are not served; the relations into them are dropped.\n */\n dropped: { table: string; reason: string }[];\n}\n\n/** A descriptor without its relations into `removed`; a foreign-key column such a relation held becomes a plain column. */\nfunction withoutRelationsInto(descriptor: TableDescriptor, removed: ReadonlySet<string>): TableDescriptor {\n const gone = descriptor.relations.filter(relation => removed.has(relation.target));\n if (gone.length === 0) return descriptor;\n const goneNames = new Set(gone.map(relation => relation.name));\n return {\n ...descriptor,\n relations: descriptor.relations.filter(relation => !goneNames.has(relation.name)),\n columns: descriptor.columns.map(column => {\n if (column.foreignKeyOf === undefined || !goneNames.has(column.foreignKeyOf)) return column;\n const { foreignKeyOf: _foreignKeyOf, derived: _derived, ...plain } = column;\n return plain;\n })\n };\n}\n\n/**\n * The tables an introspected database is served through, compiled.\n *\n * Each descriptor is kept as introspected, beside the definition that states\n * it (`compileDescribedTables`). The definitions carry `rls: \"admin-only\"`:\n * Rebase generates no policy for a table it did not declare, and the\n * request-time code reads none — the database's own policies decide every\n * row, as they always have. The descriptors keep stating those policies for\n * `GET /api/schema/tables`.\n *\n * Never throws for one table: a descriptor no definition can be built from is\n * dropped and named in {@link CompiledIntrospection.dropped}, and the rest are\n * served.\n *\n * @group Schema\n */\nexport function compileIntrospectedTables(tables: readonly TableDescriptor[]): CompiledIntrospection {\n const dropped: CompiledIntrospection[\"dropped\"] = [];\n let remaining = [...tables];\n for (;;) {\n try {\n const compiled = compileDescribedTables(remaining, { rls: () => \"admin-only\" });\n return { tables: remaining, compiled, dropped };\n } catch (error) {\n if (!isSchemaDefinitionError(error)) throw error;\n const reasons = new Map<string, string[]>();\n for (const problem of error.problems) {\n const table = remaining.find(candidate => candidate.name === problem.table || candidate.slug === problem.table);\n if (!table) continue;\n reasons.set(table.slug, [...(reasons.get(table.slug) ?? []), problem.key ? `${problem.key}: ${problem.message}` : problem.message]);\n }\n if (reasons.size === 0) throw error;\n for (const [table, list] of reasons) dropped.push({ table, reason: list.join(\"; \") });\n const removed = new Set(reasons.keys());\n remaining = remaining.filter(table => !removed.has(table.slug)).map(table => withoutRelationsInto(table, removed));\n }\n }\n}\n","import { getTableColumns } from \"drizzle-orm\";\nimport { PgArray, PgTable } from \"drizzle-orm/pg-core\";\n\n/**\n * Read a Postgres array literal (`{a,\"b c\",NULL,\"NULL\"}`, nested\n * `{{1,2},{3,4}}`) into its items, each as the text Postgres wrote — an\n * unquoted `NULL` as `null`.\n *\n * Drizzle's own parser reads an unquoted `NULL` as the four-letter string, so\n * a `date[]` / `timestamptz[]` / enum array holding a null item (the types the\n * drivers leave to drizzle as text) served `\"NULL\"` in its place. A quoted\n * `\"NULL\"` is the string.\n *\n * An explicit lower bound (`[0:1]={…}`) is skipped: the items are what is\n * served, not their subscripts.\n */\nexport function parsePgArrayLiteral(literal: string): unknown[] {\n let i = literal.startsWith(\"[\") ? literal.indexOf(\"=\") + 1 : 0;\n\n const readArray = (): unknown[] => {\n const items: unknown[] = [];\n i++; // `{`\n if (literal[i] === \"}\") {\n i++;\n return items;\n }\n for (;;) {\n if (literal[i] === \"{\") {\n items.push(readArray());\n } else if (literal[i] === \"\\\"\") {\n let text = \"\";\n i++;\n while (i < literal.length && literal[i] !== \"\\\"\") {\n if (literal[i] === \"\\\\\") i++;\n text += literal[i];\n i++;\n }\n i++; // closing quote\n items.push(text);\n } else {\n const start = i;\n while (i < literal.length && literal[i] !== \",\" && literal[i] !== \"}\") i++;\n const text = literal.slice(start, i).trim();\n items.push(text.toUpperCase() === \"NULL\" ? null : text);\n }\n if (literal[i] === \",\") {\n i++;\n continue;\n }\n i++; // `}`\n return items;\n }\n };\n\n return literal[i] === \"{\" ? readArray() : [];\n}\n\n/**\n * Patches every native array column (`PgArray`) of the given tables so a\n * read hands back what the array holds, nulls included.\n *\n * Drizzle's `PgArray.mapFromDriverValue` has two faults this replaces:\n *\n * - it calls `value.map(...)` on a NULL column — `TypeError: value.map is\n * not a function` — so a null array is served as `null` here;\n * - it maps every item through the item column, a null item included, and\n * parses a text literal's unquoted `NULL` as the string `\"NULL\"`: a null\n * item of a `bigint[]` came back `0` (`Number(null)`), of a `date[]`,\n * `timestamptz[]` or enum array `\"NULL\"`. A null item stays `null` here,\n * and only the others go through the item column's own mapping.\n *\n * Applied where the runtime builds its tables (`buildDrizzleTablesFromSchema`),\n * so every table a driver reads through carries it. Idempotent: a mark on the\n * column, so a table patched twice is wrapped once.\n */\nexport function patchPgArrayNullSafety(tables: Record<string, unknown>): void {\n for (const tableOrRelation of Object.values(tables)) {\n if (!(tableOrRelation instanceof PgTable)) continue;\n\n const columns = getTableColumns(tableOrRelation);\n for (const column of Object.values(columns)) {\n if (!(column instanceof PgArray) || Object.hasOwn(column, \"__rebaseArrayPatched\")) continue;\n Object.defineProperty(column, \"__rebaseArrayPatched\", { value: true });\n const item = column.baseColumn;\n const mapItems = (items: unknown[]): unknown[] => items.map(entry => {\n if (entry === null || entry === undefined) return null;\n return Array.isArray(entry) ? mapItems(entry) : item.mapFromDriverValue(entry);\n });\n column.mapFromDriverValue = function (value: unknown) {\n if (value === null || value === undefined) return null;\n if (typeof value === \"string\") return mapItems(parsePgArrayLiteral(value));\n return Array.isArray(value) ? mapItems(value) : value;\n };\n }\n }\n}\n","/**\n * Build drizzle tables at runtime from an introspected schema.\n *\n * **Every** data source's tables are built here, from `information_schema`,\n * after boot-ensure has run — a project with declared collections included. The\n * committed `schema.generated.ts` is a build artefact for Atlas, `db push`,\n * `eject` and user code; the runtime does not read it for its tables, because a\n * file that is one commit behind the database used to change what the server\n * served (a renamed foreign-key column 500'd every request, a lost relation\n * silently emptied a list). See `catalogue-schema.ts` for the caller.\n *\n * These are handed to drizzle as its schema, which keeps the relational query\n * path (`db.query.*`) working; without them FetchService would fall back to\n * plain selects and lose relation loading.\n *\n * Two things a caller has to supply for the tables to match what the generated\n * module used to produce, both about *names*: the Drizzle object is keyed by the\n * wire name of a column and not by the column (`authorId`, not `author_id`), and\n * a relation is keyed by the table's own relation name rather than by a\n * guess made from the foreign key. Both come from the table descriptors — see\n * `columnKeysFromTables` and `buildDrizzleRelationsFromTables`.\n */\nimport {\n bigint,\n boolean,\n char,\n cidr,\n customType,\n date,\n doublePrecision,\n geometry,\n inet,\n integer,\n interval,\n json,\n jsonb,\n line,\n macaddr,\n macaddr8,\n numeric,\n pgSchema,\n pgTable,\n point,\n primaryKey,\n real,\n smallint,\n text,\n time,\n timestamp,\n uuid,\n varchar,\n vector,\n type AnyPgColumn,\n type PgColumnBuilderBase,\n type PgTable\n} from \"drizzle-orm/pg-core\";\n\nimport { getTableColumns, relations, sql, type Relation, type Relations } from \"drizzle-orm\";\nimport { toWireKey } from \"@rebasepro/utils\";\nimport { patchPgArrayNullSafety } from \"../utils/pg-array-null-patch\";\n\nimport type { TableColumn, TableMeta } from \"./introspect-db-logic\";\n\n/**\n * The Drizzle object key a column is served under, given its table.\n *\n * Defaults to the column name — right for a junction table and for a database\n * nothing declares — and is supplied from the collections wherever there is\n * one, because there the wire name is the property key. Every read and write\n * path in this driver indexes tables and rows by that key.\n */\nexport type ColumnKeyResolver = (tableName: string, columnName: string) => string;\n\nconst columnNameAsKey: ColumnKeyResolver = (_table, column) => column;\n\n/** drizzle ships no bytea builder; binary must round-trip as a Buffer. */\nconst bytea = customType<{ data: Buffer; driverData: Buffer }>({\n dataType: () => \"bytea\"\n});\n\n/**\n * A full-text search column, declared with its real SQL type.\n *\n * Not cosmetic: `isSearchIndexColumn` asks the column for its type and drops\n * every `tsvector` from the projection, so a search column that fell through to\n * `text` (the old default for an unrecognised type) would be selected, returned\n * to callers, and rendered in the admin as a wall of lexemes. drizzle ships no\n * builder for these two.\n */\nconst tsvector = customType<{ data: string; driverData: string }>({\n dataType: () => \"tsvector\"\n});\n\nconst tsquery = customType<{ data: string; driverData: string }>({\n dataType: () => \"tsquery\"\n});\n\n/**\n * Postgres stores a column's type modifier (varchar length, vector dimensions)\n * in `atttypmod`. For length-carrying string types it is length + VARHDRSZ(4);\n * for pgvector it is the dimension count as-is. -1 means unspecified.\n */\nfunction varlenLength(col: TableColumn): number | undefined {\n return col.atttypmod && col.atttypmod > 4 ? col.atttypmod - 4 : undefined;\n}\n\n/**\n * Map a Postgres type to a drizzle column builder, keyed on `udt_name` — the\n * concrete underlying type, which is exact where `data_type` reports umbrella\n * values like \"ARRAY\" or \"USER-DEFINED\".\n *\n * Unknown types fall back to `text`: the driver still reads and writes them,\n * with the value passing through as a string, which beats dropping the column.\n */\nfunction scalarBuilder(udtName: string, name: string, col: TableColumn): PgColumnBuilderBase {\n switch (udtName) {\n case \"uuid\":\n return uuid(name);\n case \"bool\":\n return boolean(name);\n case \"int2\":\n return smallint(name);\n case \"int4\":\n return integer(name);\n case \"int8\":\n return bigint(name, { mode: \"number\" });\n case \"float4\":\n return real(name);\n case \"float8\":\n return doublePrecision(name);\n case \"numeric\":\n case \"money\":\n return numeric(name);\n case \"json\":\n return json(name);\n case \"jsonb\":\n return jsonb(name);\n case \"date\":\n return date(name);\n case \"time\":\n return time(name);\n case \"timetz\":\n return time(name, { withTimezone: true });\n // `mode: \"string\"`, both of them, because that is what the generated\n // module declared for every `date` property: the value Postgres sent,\n // untouched. Drizzle's default mode is `date`, which parses it into a\n // `Date` — the same instant in a different shape, and a difference that\n // would have appeared only on the read path of a project that changed\n // nothing. (`parsePropertyFromServer` normalises either shape to an ISO\n // string for a declared `date` property, so what a REST caller sees is\n // the same; a raw `db.select()` is where the two differ.)\n case \"timestamp\":\n return timestamp(name, { mode: \"string\" });\n case \"timestamptz\":\n return timestamp(name, { withTimezone: true, mode: \"string\" });\n case \"interval\":\n return interval(name);\n case \"bytea\":\n return bytea(name);\n case \"inet\":\n return inet(name);\n case \"cidr\":\n return cidr(name);\n case \"macaddr\":\n return macaddr(name);\n case \"macaddr8\":\n return macaddr8(name);\n case \"point\":\n return point(name);\n case \"line\":\n return line(name);\n case \"geometry\":\n return geometry(name);\n case \"vector\": {\n // drizzle requires the dimension count; without it fall back to text\n // rather than declaring a vector of unknown width.\n const dimensions = col.atttypmod && col.atttypmod > 0 ? col.atttypmod : undefined;\n return dimensions ? vector(name, { dimensions }) : text(name);\n }\n case \"bpchar\": {\n const length = varlenLength(col);\n return length ? char(name, { length }) : char(name);\n }\n case \"varchar\": {\n const length = varlenLength(col);\n return length ? varchar(name, { length }) : text(name);\n }\n case \"tsvector\":\n return tsvector(name);\n case \"tsquery\":\n return tsquery(name);\n default:\n // Includes text, enums (pg enums are strings on the wire), citext,\n // geography, and anything else this driver hasn't met yet.\n //\n // An enum deliberately stays `text`, which is what the generated\n // module's `pgEnum` column also serves: drizzle does no runtime\n // validation of enum members either way, and Postgres rejects a\n // label it does not have. The difference is only in the type the\n // generated *types* carry, and those come from the collection.\n return text(name);\n }\n}\n\n/**\n * The fluent methods this file calls on a column builder.\n *\n * Drizzle's `PgColumnBuilderBase` exposes none of them by design: they live on\n * the concrete `PgColumnBuilder` subclasses, each generic over the column's\n * TypeScript type, its name and whether it is notNull / hasDefault — a chain\n * resolved when you *write* a schema, and not resolvable when you build one\n * from a catalogue read at runtime, which is all this file does.\n *\n * So a conversion here is irreducible; what was avoidable was doing it four\n * separate times, each declaring its own one-method slice of the builder and\n * each free to disagree with the others about a name or a signature. Declaring\n * the methods as an *extension* of the base also drops the double cast: the\n * two types overlap, so tsc will still refuse this if drizzle ever gives\n * `PgColumnBuilderBase` a conflicting member.\n */\ninterface FluentColumnBuilder extends PgColumnBuilderBase {\n array(): PgColumnBuilderBase;\n notNull(): PgColumnBuilderBase;\n primaryKey(): PgColumnBuilderBase;\n generatedAlwaysAs(expr: unknown): PgColumnBuilderBase;\n}\n\n/** See {@link FluentColumnBuilder}. */\nconst fluent = (builder: PgColumnBuilderBase): FluentColumnBuilder => builder as FluentColumnBuilder;\n\nfunction columnBuilderFor(col: TableColumn): PgColumnBuilderBase {\n // Array types are named after their element with a leading underscore\n // (_int4 = int4[]), so the element mapping is reused verbatim.\n if (col.udt_name.startsWith(\"_\")) {\n const element = scalarBuilder(col.udt_name.slice(1), col.column_name, col);\n return fluent(element).array();\n }\n return scalarBuilder(col.udt_name, col.column_name, col);\n}\n\n/**\n * Build one drizzle table per introspected table, keyed by table name.\n *\n * @param columnKey how a column is named on the wire — see {@link ColumnKeyResolver}.\n */\nexport function buildDrizzleTablesFromSchema(\n tablesMap: Map<string, TableMeta>,\n pgSchemaName = \"public\",\n columnKey: ColumnKeyResolver = columnNameAsKey\n): Record<string, PgTable> {\n const schema = pgSchemaName === \"public\" ? null : pgSchema(pgSchemaName);\n // The column set is only known at runtime, so drizzle's generic table\n // signature can't be satisfied statically; call it through a loose type.\n const createTable = (schema ? schema.table.bind(schema) : pgTable) as (\n name: string,\n columns: Record<string, PgColumnBuilderBase>,\n extras?: (self: Record<string, AnyPgColumn>) => unknown[]\n ) => PgTable;\n\n const tables: Record<string, PgTable> = {};\n\n for (const [tableName, meta] of tablesMap) {\n const columns: Record<string, PgColumnBuilderBase> = {};\n const keyOf = new Map<string, string>();\n\n for (const col of meta.columns) {\n let builder = columnBuilderFor(col);\n\n if (col.is_nullable === \"NO\") {\n builder = fluent(builder).notNull();\n }\n // Single-column primary keys are marked inline; composite keys are\n // declared in the table extras below.\n if (meta.pks.length === 1 && meta.pks[0] === col.column_name) {\n builder = fluent(builder).primaryKey();\n }\n // A stored generated column must be left out of every INSERT, which\n // is what `.generatedAlwaysAs` tells drizzle. The expression is\n // carried through so a drizzle-kit run over these tables describes\n // the column it actually found; nothing at runtime evaluates it.\n if (col.is_generated === \"ALWAYS\") {\n builder = fluent(builder).generatedAlwaysAs(sql.raw(col.generation_expression ?? \"\"));\n }\n\n const key = columnKey(tableName, col.column_name);\n keyOf.set(col.column_name, key);\n columns[key] = builder;\n }\n\n const isComposite = meta.pks.length > 1;\n tables[tableName] = createTable(\n tableName,\n columns,\n isComposite\n ? (t) => {\n const [first, ...rest] = meta.pks.map((pk) => t[keyOf.get(pk) ?? pk]);\n return [primaryKey({ columns: [first, ...rest] })];\n }\n : undefined\n );\n }\n\n // Drizzle's array mapping turns a null item into `0` / `\"NULL\"` and fails\n // on a null array; every table the runtime reads through is built here.\n patchPgArrayNullSafety(tables);\n return tables;\n}\n\n/**\n * Build drizzle `relations()` for the foreign keys, so the relational query\n * path can actually load them.\n *\n * FetchService asks drizzle for `with: { <key>: true }`, keyed by the relation\n * property on the collection. Tables alone don't satisfy that — without these,\n * `?include=author` silently returns the raw `author_id` and no author.\n *\n * The keys here must match the relation names `introspectTables` gives an\n * introspected table (`introspect-tables.ts`), which name the collection's\n * relation properties.\n */\nexport function buildDrizzleRelationsFromSchema(\n tablesMap: Map<string, TableMeta>,\n tables: Record<string, PgTable>,\n columnKey: ColumnKeyResolver = columnNameAsKey\n): Record<string, Relations> {\n /** Owning side, per table: the `one()` relations from its foreign keys. */\n const owning = new Map<string, { key: string; targetTable: string; fkColumn: string; targetColumn: string; relationName: string }[]>();\n /** Inverse side, per referenced table: the matching `many()` back-references. */\n const inverse = new Map<string, { key: string; sourceTable: string; relationName: string }[]>();\n\n for (const [tableName, meta] of tablesMap) {\n if (!tables[tableName]) continue;\n // The keys the table actually carries — what a relation key must not\n // collide with, since both live in one Drizzle object.\n const columnNames = new Set(meta.columns.map((c) => columnKey(tableName, c.column_name)));\n\n for (const fk of meta.fks) {\n if (!tables[fk.foreign_table_name]) continue;\n\n // Mirrors introspectTables' relation names: author_id -> author,\n // falling back to the target table when the column name carries no\n // hint. `toWireKey` for the same reason it is there — the two keys\n // must be the same string or the collection advertises a relation key\n // drizzle has never heard of (`author_ref` here, `authorRef` there).\n let key = toWireKey(fk.column_name.replace(/_id$/, \"\"));\n if (meta.pks.includes(fk.column_name) && key === fk.column_name) {\n key = fk.foreign_table_name;\n }\n // A relation key must not shadow a real column.\n if (columnNames.has(key)) continue;\n\n // Pairs the two sides. Drizzle matches a named one() to the many()\n // carrying the same name, and disambiguates multiple foreign keys\n // into the same table.\n const relationName = `${tableName}_${fk.column_name}`;\n\n owning.set(tableName, [\n ...(owning.get(tableName) ?? []),\n {\n key,\n targetTable: fk.foreign_table_name,\n // The Drizzle keys, not the columns: `fields`/`references`\n // index the built table objects, which are keyed by the\n // wire name wherever a collection supplies one.\n fkColumn: columnKey(tableName, fk.column_name),\n targetColumn: columnKey(fk.foreign_table_name, fk.foreign_column_name),\n relationName\n }\n ]);\n\n const backKey = tableName;\n const targetColumns = new Set(\n (tablesMap.get(fk.foreign_table_name)?.columns ?? [])\n .map((c) => columnKey(fk.foreign_table_name, c.column_name))\n );\n if (targetColumns.has(backKey)) continue;\n\n inverse.set(fk.foreign_table_name, [\n ...(inverse.get(fk.foreign_table_name) ?? []),\n { key: backKey, sourceTable: tableName, relationName }\n ]);\n }\n }\n\n const built: Record<string, Relations> = {};\n\n for (const tableName of tablesMap.keys()) {\n const table = tables[tableName];\n const ones = owning.get(tableName) ?? [];\n const manys = inverse.get(tableName) ?? [];\n if (!table || (ones.length === 0 && manys.length === 0)) continue;\n\n built[`${tableName}Relations`] = relations(table, ({ one, many }) => {\n const map: Record<string, Relation> = {};\n\n for (const rel of ones) {\n map[rel.key] = one(tables[rel.targetTable], {\n // `getTableColumns` is drizzle's own accessor for this.\n // Indexing the table object — which is what the casts here\n // were for — also reaches its methods and symbols, so a\n // foreign key named after one of them yields something that\n // is not a column; and the target type they used,\n // `Record<string, never>`, makes every lookup `never`,\n // which is assignable to anything and therefore checks\n // nothing at all.\n fields: [getTableColumns(table)[rel.fkColumn]],\n references: [getTableColumns(tables[rel.targetTable])[rel.targetColumn]],\n relationName: rel.relationName\n });\n }\n\n // Drizzle needs the inverse of every named one(); without it,\n // normalizeRelation throws and the relational path is dead.\n for (const rel of manys) {\n // An inverse must not collide with an owning key on this table.\n if (map[rel.key]) continue;\n map[rel.key] = many(tables[rel.sourceTable], { relationName: rel.relationName });\n }\n\n return map;\n });\n }\n\n return built;\n}\n","/**\n * Build drizzle `relations()` for declared tables, from their descriptors.\n *\n * The heuristic builder in `dynamic-tables.ts` names a relation after the\n * foreign-key column (`author_id` → `author`), which is the only evidence a\n * database offers and is right for BaaS mode. It is wrong for a project that\n * declares its tables: there the relation's name is whatever the author\n * called it, `include=writer` addresses that name, and a relation whose key was\n * guessed from the column simply does not answer to it — the read returns the\n * bare foreign key and no target, silently, which is how a demo lost every\n * relation in its list view while the detail view (a different code path) kept\n * working.\n *\n * So when there are declared tables, they are the authority for *which* relations\n * exist and what they are called; the live catalogue is the authority for the\n * columns underneath. This is the same pairing `generate-drizzle-schema-logic`\n * emits into `schema.generated.ts` — kind for kind, key for key, and paired by\n * the same {@link tableRelationName} — only built against tables read back from\n * `information_schema` rather than against a file.\n */\nimport { getTableColumns, relations, type AnyColumn, type Relation, type Relations } from \"drizzle-orm\";\nimport type { PgTable } from \"drizzle-orm/pg-core\";\nimport type { RelationDescriptor, TableDescriptor } from \"@rebasepro/types\";\n\nimport { servedKeyOf, tableRelationName } from \"./relation-names\";\n\n/** A table's name with any schema prefix stripped — as the DDL creates it. */\nexport function bareTableName(name: string): string {\n return name.includes(\".\") ? name.split(\".\").pop()! : name;\n}\n\n/**\n * The key a table's rows are addressed by, as the generated module spells it:\n * the first primary-key column's key, else `id`.\n *\n * Deliberately the declaration's answer rather than the catalogue's primary\n * key — `references: [users.id]` in the generated file is keyed the same way,\n * and the two have to name the same Drizzle key for a relation to compile at\n * all.\n */\nfunction primaryKeyFieldKey(table: TableDescriptor): string {\n return table.primaryKey[0] ?? \"id\";\n}\n\n/**\n * The key on the source table that a `hasOne`/`hasMany` foreign key holds:\n * its `sourceKey` when the link names one, else the primary key.\n */\nfunction sourceKeyFieldKey(\n relation: Extract<RelationDescriptor, { kind: \"hasOne\" | \"hasMany\" }>,\n source: TableDescriptor\n): string {\n return relation.sourceKey\n ? servedKeyOf(source, relation.sourceKey)\n : primaryKeyFieldKey(source);\n}\n\n/**\n * A column of a built table, by its Drizzle key or by its column name.\n *\n * The key is the answer in the ordinary case, and the name is the fallback for\n * the one place a caller holds a column and not a field: a junction table's two\n * foreign keys, which are keyed by column *unless* the project also declares a\n * table over that junction, in which case they are keyed by its column keys.\n * Looking both up costs a scan of one table and removes the difference.\n */\nfunction columnOf(table: PgTable | undefined, key: string): AnyColumn | undefined {\n if (!table) return undefined;\n // Drizzle's column map is keyed by the JS property name, which is exactly\n // the \"keyed by its column keys\" case this function's docblock describes\n // — so `getTableColumns` answers it, and indexing the table object (which\n // also reaches its methods and symbols) was never needed.\n const direct = getTableColumns(table)[key];\n if (direct) return direct;\n for (const column of Object.values(getTableColumns(table))) {\n if (column.name === key) return column;\n }\n return undefined;\n}\n\ninterface OneSpec {\n key: string;\n target: PgTable;\n fields: [AnyColumn, ...AnyColumn[]];\n references: [AnyColumn, ...AnyColumn[]];\n relationName: string;\n}\n\ninterface ManySpec {\n key: string;\n target: PgTable;\n relationName: string;\n}\n\n/**\n * Drizzle relations for every declared table, keyed `<table>Relations`.\n *\n * @param descriptors every declared table backed by a table in `tables`, and\n * the targets of their relations\n * @param tables catalogue-built tables, keyed by bare table name\n */\nexport function buildDrizzleRelationsFromTables(\n descriptors: readonly TableDescriptor[],\n tables: Record<string, PgTable>\n): Record<string, Relations> {\n const ones = new Map<string, OneSpec[]>();\n const manys = new Map<string, ManySpec[]>();\n /** `<relationName>::<kind>` already emitted on a table — the generator dedupes the same way. */\n const emitted = new Map<string, Set<string>>();\n\n const claim = (table: string, name: string, kind: string): boolean => {\n const seen = emitted.get(table) ?? new Set<string>();\n emitted.set(table, seen);\n const key = `${name}::${kind}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n };\n\n const addOne = (table: string, spec: OneSpec) => ones.set(table, [...(ones.get(table) ?? []), spec]);\n const addMany = (table: string, spec: ManySpec) => manys.set(table, [...(manys.get(table) ?? []), spec]);\n\n const bySlug = new Map(descriptors.map(descriptor => [descriptor.slug, descriptor]));\n // Only reached for a target that is among `descriptors`: every caller\n // looks the target up in `bySlug` first.\n const targetOf = (slug: string): TableDescriptor => {\n const target = bySlug.get(slug);\n if (!target) throw new Error(`Relation target \"${slug}\" is not a declared table`);\n return target;\n };\n\n const byTable = new Map<string, TableDescriptor>();\n for (const descriptor of descriptors) {\n const table = bareTableName(descriptor.table);\n if (tables[table]) byTable.set(table, descriptor);\n }\n\n for (const [tableName, source] of byTable) {\n const table = tables[tableName];\n\n for (const relation of source.relations) {\n // A target outside this set has nothing to build against, and\n // nothing to fail over: the boot relation check reports an\n // unresolvable target by name.\n const target = bySlug.get(relation.target);\n if (!target) continue;\n const targetTableName = bareTableName(target.table);\n const targetTable = tables[targetTableName];\n const name = tableRelationName(relation, source, targetOf);\n\n switch (relation.kind) {\n case \"belongsTo\": {\n if (!targetTable) continue;\n if (!claim(tableName, name, relation.kind)) continue;\n const field = columnOf(table, servedKeyOf(source, relation.localKey));\n const reference = columnOf(targetTable, primaryKeyFieldKey(target));\n // A column the catalogue does not have would make drizzle\n // throw `Cannot read properties of undefined` from inside\n // `normalizeRelation`, three frames from anything nameable.\n // The boot relation check reports the same defect in terms\n // of the table; this only declines to build it.\n if (!field || !reference) continue;\n addOne(tableName, {\n key: relation.name,\n target: targetTable,\n fields: [field],\n references: [reference],\n relationName: name\n });\n break;\n }\n\n case \"hasOne\": {\n if (!targetTable) continue;\n if (!claim(tableName, name, relation.kind)) continue;\n // The foreign key lives on the target, so this side states\n // the join from its own end: its source key against the\n // target's foreign key. Drizzle has no `one()` that is paired\n // by `relationName` alone — `createOne` reads\n // `config.fields.reduce(...)` as the relations are evaluated,\n // which is at `drizzle({ schema })` — and a bare `one(target)`\n // is paired by table, which is ambiguous as soon as the target\n // has two links back here or the link is to its own table.\n // These are the columns drizzle would infer from the owning\n // side, given outright.\n const field = columnOf(table, sourceKeyFieldKey(relation, source));\n const reference = columnOf(targetTable, servedKeyOf(target, relation.foreignKey));\n if (!field || !reference) continue;\n addOne(tableName, {\n key: relation.name,\n target: targetTable,\n fields: [field],\n references: [reference],\n relationName: name\n });\n break;\n }\n\n case \"hasMany\": {\n if (!targetTable) continue;\n if (!claim(tableName, name, relation.kind)) continue;\n addMany(tableName, { key: relation.name, target: targetTable, relationName: name });\n break;\n }\n\n case \"manyToMany\": {\n const junctionName = bareTableName(relation.through.table);\n const junction = tables[junctionName];\n if (!junction) continue;\n if (!claim(tableName, name, relation.kind)) continue;\n addMany(tableName, { key: relation.name, target: junction, relationName: name });\n addJunctionSides(relation, source, target, junctionName, tables, targetOf, addOne, claim);\n break;\n }\n\n case \"via\":\n // A join chain is resolved at query time, not modelled as a\n // drizzle relation — same as the generator.\n break;\n }\n }\n }\n\n // The reciprocal a `many()` needs. A `hasMany` gives drizzle no columns to\n // join on; it finds them on the owning side, which exists only if the other\n // table happens to declare a `belongsTo` back. Where it does not, the\n // generated file synthesizes one under a `_synth_` key, and so does this.\n // A `hasOne` names its own columns, and gets the same owning side so the\n // target's table carries the link back under the same `relationName`.\n for (const [tableName, source] of byTable) {\n const table = tables[tableName];\n for (const relation of source.relations) {\n if (relation.kind !== \"hasMany\" && relation.kind !== \"hasOne\") continue;\n const target = bySlug.get(relation.target);\n if (!target) continue;\n const targetTableName = bareTableName(target.table);\n const targetTable = tables[targetTableName];\n if (!targetTable) continue;\n\n const name = tableRelationName(relation, source, targetOf);\n if (!claim(targetTableName, name, \"belongsTo\")) continue;\n\n const fkKey = servedKeyOf(target, relation.foreignKey);\n const field = columnOf(targetTable, fkKey);\n const reference = columnOf(table, sourceKeyFieldKey(relation, source));\n if (!field || !reference) continue;\n\n addOne(targetTableName, {\n key: `_synth_${targetTableName}_${fkKey}`,\n target: tables[tableName],\n fields: [field],\n references: [reference],\n relationName: name\n });\n }\n }\n\n const built: Record<string, Relations> = {};\n for (const tableName of new Set([...ones.keys(), ...manys.keys()])) {\n const table = tables[tableName];\n if (!table) continue;\n const tableOnes = ones.get(tableName) ?? [];\n const tableManys = manys.get(tableName) ?? [];\n\n built[`${tableName}Relations`] = relations(table, ({ one, many }) => {\n const map: Record<string, Relation> = {};\n for (const spec of tableOnes) {\n map[spec.key] = one(spec.target, {\n fields: spec.fields,\n references: spec.references,\n relationName: spec.relationName\n });\n }\n for (const spec of tableManys) {\n if (map[spec.key]) continue;\n map[spec.key] = many(spec.target, { relationName: spec.relationName });\n }\n return map;\n });\n }\n\n return built;\n}\n\n/**\n * The junction table's own two `one()` sides.\n *\n * A many-to-many is a `many(junction)` on each endpoint, so the junction has to\n * carry the matching `one()` back to each — without them drizzle can join a\n * post to its `posts_tags` rows and no further, and the tags come back as\n * junction rows. Keyed by the junction's own columns, which is how the\n * generated file keys them too.\n */\nfunction addJunctionSides(\n relation: Extract<RelationDescriptor, { kind: \"manyToMany\" }>,\n source: TableDescriptor,\n target: TableDescriptor,\n junctionName: string,\n tables: Record<string, PgTable>,\n targetOf: (slug: string) => TableDescriptor,\n addOne: (table: string, spec: OneSpec) => void,\n claim: (table: string, name: string, kind: string) => boolean\n): void {\n const junction = tables[junctionName];\n const sourceTable = tables[bareTableName(source.table)];\n const targetTable = tables[bareTableName(target.table)];\n if (!junction || !sourceTable || !targetTable) return;\n\n const sourceName = tableRelationName(relation, source, targetOf);\n // The far endpoint pairs with whatever *it* calls this junction, so the two\n // sides are looked up rather than assumed: an inverse declared on the target\n // owns the name, and only a junction nothing points back through needs a\n // synthesized one.\n const inverse = target.relations\n .find(r => r.kind === \"manyToMany\" && bareTableName(r.through.table) === junctionName);\n const targetName = inverse\n ? tableRelationName(inverse, target, targetOf)\n : `${junctionName}_${relation.through.targetKey}`;\n\n const pairs: [string, PgTable, string, TableDescriptor][] = [\n [relation.through.sourceKey, sourceTable, sourceName, source],\n [relation.through.targetKey, targetTable, targetName, target]\n ];\n\n for (const [column, endpointTable, relationName, endpoint] of pairs) {\n if (!claim(junctionName, relationName, \"junction\")) continue;\n const field = columnOf(junction, column);\n const reference = columnOf(endpointTable, primaryKeyFieldKey(endpoint));\n if (!field || !reference) continue;\n addOne(junctionName, {\n key: column,\n target: endpointTable,\n fields: [field],\n references: [reference],\n relationName\n });\n }\n}\n","/**\n * The runtime's Drizzle schema, read back from the database it is about to\n * serve.\n *\n * This is the whole point of the module: **the live catalogue is the schema**.\n * Boot-ensure has already created and altered whatever the tables describe\n * by the time this runs, so `information_schema` is both current and complete,\n * and the committed `schema.generated.ts` — which is a build artefact for Atlas,\n * `db push`, `eject` and user code — never decides what the server serves.\n *\n * It used to. The default data source was handed the bundle's generated module\n * and nothing reconciled it, so a file one commit behind the database changed\n * behaviour in ways that looked nothing like \"your schema file is old\":\n *\n * - a foreign-key column renamed by boot-ensure (`categorie_id` → `category_id`)\n * left every request 500ing, because the module still declared the old name;\n * - a property added to a collection answered `400 VALIDATION_UNKNOWN_FIELDS`\n * on first save, because the write check reads the table and the table came\n * from the file, while the column itself existed;\n * - relations missing from the module were silently missing from list reads.\n *\n * The catalogue cannot drift from itself. What the generated module is still\n * good for is telling the developer their file is stale — see\n * `generated-schema-diff.ts`, which is now its only reader at boot.\n */\nimport type { PgTable } from \"drizzle-orm/pg-core\";\nimport type { Relations } from \"drizzle-orm\";\nimport type { TableDescriptor } from \"@rebasepro/types\";\nimport { declaredSchemaOf, keyForColumn, resolveTableJunctions } from \"@rebasepro/common\";\nimport { toWireKey } from \"@rebasepro/utils\";\n\nimport { buildDrizzleRelationsFromSchema, buildDrizzleTablesFromSchema, type ColumnKeyResolver } from \"./dynamic-tables\";\nimport { bareTableName, buildDrizzleRelationsFromTables } from \"./config-relations\";\nimport { introspectSchema, type Queryable } from \"./introspect-runtime\";\nimport type { TableMeta } from \"./introspect-db-logic\";\nimport { tableSearchColumnNames } from \"./search-column\";\n\n/** The Postgres schema a table lives in: the one it declares, else `fallback`. */\nexport function schemaOfTable(table: Pick<TableDescriptor, \"schema\">, fallback: string): string {\n return declaredSchemaOf(table) ?? fallback;\n}\n\n/**\n * How a column of each table is keyed in the Drizzle object.\n *\n * The wire name, which is the column's key — `authorId`, never `author_id` —\n * because that is what every read and write path in this driver indexes tables\n * and rows by, and what the generated module has always emitted. Getting this\n * wrong does not throw: drizzle leaves an unknown key out of the statement and\n * the write reports success having stored nothing. A column the table does not\n * describe is keyed by the camelCase of its name, which is the key a foreign\n * key derived from it would get.\n *\n * Two exceptions, both columns no table declares:\n *\n * - the generated search columns keep their raw names, because `search_vector`\n * is how `searchColumnNamesOf` excludes them from responses and how the\n * condition builder finds the one to match against;\n * - a table no descriptor claims (a junction) is keyed by its **key** columns'\n * names, which is also what the generated file does for them — but a\n * junction that declares `pivot` columns keys those payload columns by\n * their column key, for the same reason a table does. `joinedAt` with\n * column `joined_at` has to be one name on both sides or a `_pivot` write\n * is silently dropped by drizzle and the read serves a key the caller never\n * declared.\n */\nexport function columnKeysFromTables(\n descriptors: readonly TableDescriptor[]\n): ColumnKeyResolver {\n const byTable = new Map<string, TableDescriptor>();\n const rawColumns = new Map<string, Set<string>>();\n for (const descriptor of descriptors) {\n const table = bareTableName(descriptor.table);\n byTable.set(table, descriptor);\n rawColumns.set(table, new Set(tableSearchColumnNames(descriptor)));\n }\n // The junctions' payload columns, as the pivot the planner emitted them\n // from, so the runtime table and the generated one cannot key them\n // differently.\n const junctionByTable = new Map<string, { keyColumns: Set<string>; pivot: Map<string, string> }>();\n for (const junction of resolveTableJunctions(descriptors).values()) {\n if (junction.pivot.length === 0) continue;\n junctionByTable.set(junction.table, {\n keyColumns: new Set(junction.endpoints.map(endpoint => endpoint.junctionColumn)),\n pivot: new Map(junction.pivot.map(column => [column.column, column.key]))\n });\n }\n return (tableName, columnName) => {\n const descriptor = byTable.get(tableName);\n if (!descriptor) {\n const junction = junctionByTable.get(tableName);\n if (!junction || junction.keyColumns.has(columnName)) return columnName;\n return junction.pivot.get(columnName) ?? toWireKey(columnName);\n }\n if (rawColumns.get(tableName)?.has(columnName)) return columnName;\n return keyForColumn(descriptor, columnName) ?? toWireKey(columnName);\n };\n}\n\nexport interface CatalogueSchema {\n /** Drizzle tables, keyed by bare table name. */\n tables: Record<string, PgTable>;\n /** Drizzle relations, keyed `<table>Relations`. */\n relations: Record<string, Relations>;\n /** Introspected metadata per table — what the boot diff compares against. */\n meta: Map<string, TableMeta>;\n /** Tables declared for this source that the database does not have. */\n missing: string[];\n}\n\n/**\n * Read the tables this data source serves out of `information_schema`.\n *\n * Restricted to the tables handed in, because the driver is given every table\n * the project declares while each database holds only its own: an unfiltered\n * read had a second source (`database(\"analytics\")`) reporting the default's\n * tables as its own. Junction tables come too — they back no declared table\n * and a many-to-many is unreadable without them.\n *\n * Every schema the tables name is read, not just `public`. The users table\n * lives in `rebase`, and a run restricted to `public` would leave the registry\n * with no table for it at all. A table that declares no schema is read from\n * `defaultSchema`.\n */\nexport async function readCatalogueSchema(options: {\n client: Queryable;\n /** This data source's tables, and the targets of their relations. */\n tables: readonly TableDescriptor[];\n defaultSchema: string;\n}): Promise<CatalogueSchema> {\n const { client, tables: descriptors, defaultSchema } = options;\n\n /** schema → the tables wanted from it. */\n const wanted = new Map<string, Set<string>>();\n const want = (schema: string, table: string) => {\n const set = wanted.get(schema) ?? new Set<string>();\n wanted.set(schema, set);\n set.add(table);\n };\n\n for (const descriptor of descriptors) {\n want(schemaOfTable(descriptor, defaultSchema), bareTableName(descriptor.table));\n }\n // Junctions are created in `public`, full stop — `resolveTableJunctions`\n // hardcodes it and the three generators agree with it.\n for (const junction of resolveTableJunctions(descriptors).values()) {\n want(junction.schema, junction.table);\n }\n\n const columnKey = columnKeysFromTables(descriptors);\n const tables: Record<string, PgTable> = {};\n const meta = new Map<string, TableMeta>();\n const missing: string[] = [];\n\n for (const [schema, names] of wanted) {\n // Views too: a `defineView` reads one.\n const live = await introspectSchema(client, schema, { views: true });\n const present = new Map<string, TableMeta>();\n for (const name of names) {\n const found = live.tablesMap.get(name);\n if (!found) {\n missing.push(schema === defaultSchema ? name : `${schema}.${name}`);\n continue;\n }\n // First schema to carry a name wins. Two schemas holding a table of\n // the same name is the `search_path` hazard the drift report\n // explains; the registry is keyed by bare name either way, so this\n // only picks which one is served — the one whose table asked.\n if (tables[name]) continue;\n present.set(name, found);\n meta.set(name, found);\n }\n Object.assign(tables, buildDrizzleTablesFromSchema(present, schema, columnKey));\n }\n\n return {\n tables,\n relations: buildDrizzleRelationsFromTables(descriptors, tables),\n meta,\n missing\n };\n}\n\n/**\n * The BaaS variant: no tables are declared, so every table in one schema is\n * served, described from the catalogue (`descriptors`), and the relations are\n * derived from the foreign keys.\n *\n * Kept apart from {@link readCatalogueSchema} because the two answer different\n * questions. Here the database is the entire specification; there it supplies\n * the columns for a specification the project already wrote down.\n */\nexport function buildBaasSchema(\n tablesMap: Map<string, TableMeta>,\n pgSchemaName: string,\n descriptors: readonly TableDescriptor[]\n): { tables: Record<string, PgTable>; relations: Record<string, Relations> } {\n const columnKey = columnKeysFromTables(descriptors);\n const tables = buildDrizzleTablesFromSchema(tablesMap, pgSchemaName, columnKey);\n return {\n tables,\n relations: buildDrizzleRelationsFromSchema(tablesMap, tables, columnKey)\n };\n}\n","/**\n * Compare the committed `schema.generated.ts` against the live catalogue, and\n * say so — once per difference, at boot, as a warning and nothing more.\n *\n * The runtime stopped reading that file for its tables (see\n * `catalogue-schema.ts`), which removes an entire class of production failure\n * and creates a smaller one: a stale file is now *invisible*. It is still real —\n * it is what Atlas plans migrations from, what `db push` diffs, what `eject`\n * writes out and what user code imports — so a project whose file no longer\n * describes its database will hit it later, in a tool, with no clue that boot\n * already knew.\n *\n * Hence this: a guard rather than a doc. It never fails boot and never changes\n * what is served — the previous arrangement, where the file could do both,\n * is exactly what was removed.\n *\n * `generated-schema-staleness.ts` answers a narrower question (does the file\n * name every declared table) from the file's *source text*. This one\n * compares the loaded module against the database, column by column.\n */\nimport { getTableColumns, getTableName as drizzleTableName, isTable } from \"drizzle-orm\";\nimport type { PgTable } from \"drizzle-orm/pg-core\";\nimport type { TableDescriptor } from \"@rebasepro/types\";\nimport { logger } from \"@rebasepro/server\";\n\nimport { AUTH_USERS_COLUMNS } from \"./auth-users-columns\";\nimport type { TableMeta } from \"./introspect-db-logic\";\nimport { bareTableName } from \"./config-relations\";\nimport { readCatalogueSchema } from \"./catalogue-schema\";\nimport type { Queryable } from \"./introspect-runtime\";\nimport { servedKeyOf } from \"./relation-names\";\n\nexport type SchemaDifferenceKind =\n | \"missing-table\"\n | \"missing-column\"\n | \"extra-column\"\n | \"type\"\n | \"nullability\";\n\nexport interface SchemaDifference {\n kind: SchemaDifferenceKind;\n /** Bare table name, as both sides spell it. */\n table: string;\n /** The slug of the declared table backed by that table, when one is. */\n slug?: string;\n /** The column, in database terms. */\n column?: string;\n /** The key it is served under, where the table declares it. */\n key?: string;\n /** What `schema.generated.ts` says. */\n generated?: string;\n /** What the database says. */\n live?: string;\n}\n\n/**\n * The families a boot warning is worth raising over.\n *\n * Deliberately coarse. `varchar(120)` and `text` are the same family because the\n * runtime treats them identically and a warning about the difference would fire\n * on every boot of a correct project — the widths still reach Postgres, which\n * enforces them. What this is looking for is the kind of drift that changes what\n * a value *is*: a number that became text, a timestamp that became a date, a\n * column that stopped existing.\n */\nexport function typeFamily(sqlType: string | undefined): string {\n if (!sqlType) return \"unknown\";\n let type = sqlType.trim().toLowerCase();\n const isArray = type.endsWith(\"[]\") || type.startsWith(\"_\");\n type = type.replace(/\\[\\]$/, \"\").replace(/^_/, \"\");\n // Strip the modifier: varchar(255), numeric(10,2), vector(1536), char(2).\n type = type.replace(/\\s*\\([^)]*\\)\\s*$/, \"\").trim();\n\n const family = FAMILIES[type] ?? type;\n return isArray ? `${family}[]` : family;\n}\n\nconst FAMILIES: Record<string, string> = {\n // strings\n text: \"text\",\n varchar: \"text\",\n \"character varying\": \"text\",\n bpchar: \"text\",\n char: \"text\",\n character: \"text\",\n citext: \"text\",\n name: \"text\",\n // integers\n int2: \"integer\",\n smallint: \"integer\",\n smallserial: \"integer\",\n int4: \"integer\",\n int: \"integer\",\n integer: \"integer\",\n serial: \"integer\",\n int8: \"bigint\",\n bigint: \"bigint\",\n bigserial: \"bigint\",\n // approximate and exact numerics: kept apart, because one rounds\n float4: \"float\",\n real: \"float\",\n float8: \"float\",\n \"double precision\": \"float\",\n numeric: \"numeric\",\n decimal: \"numeric\",\n money: \"numeric\",\n // the rest\n bool: \"boolean\",\n boolean: \"boolean\",\n uuid: \"uuid\",\n json: \"json\",\n jsonb: \"jsonb\",\n date: \"date\",\n time: \"time\",\n \"time without time zone\": \"time\",\n timetz: \"time\",\n \"time with time zone\": \"time\",\n timestamp: \"timestamp\",\n \"timestamp without time zone\": \"timestamp\",\n timestamptz: \"timestamptz\",\n \"timestamp with time zone\": \"timestamptz\",\n interval: \"interval\",\n bytea: \"bytea\",\n tsvector: \"tsvector\",\n tsquery: \"tsquery\",\n vector: \"vector\"\n};\n\n/** One catalogue column, reduced to the three facts this compares. */\ninterface CatalogueColumn {\n name: string;\n family: string;\n notNull: boolean;\n}\n\nfunction catalogueColumns(meta: TableMeta): Map<string, CatalogueColumn> {\n const columns = new Map<string, CatalogueColumn>();\n for (const col of meta.columns) {\n columns.set(col.column_name, {\n name: col.column_name,\n // `udt_name` over `data_type`: the latter reports \"ARRAY\" and\n // \"USER-DEFINED\" where the former is the concrete type, and an enum\n // has to compare by its own type name against the module's pgEnum.\n family: typeFamily(col.udt_name || col.data_type),\n notNull: col.is_nullable === \"NO\"\n });\n }\n return columns;\n}\n\n/**\n * Every way the generated module and the database disagree, for the tables both\n * describe.\n *\n * One-directional in one respect only: a table the module has and the database\n * does not is reported (that is the stale-file case), while a table the database\n * has and the module does not is left alone — a database may hold anything, and\n * the declared-tables-vs-file question is `generated-schema-staleness`'s.\n */\nexport function diffGeneratedSchemaAgainstCatalogue(options: {\n /** The `tables` export of the bundle's schema module. */\n generated: Record<string, unknown> | undefined;\n /** What was introspected for this data source, keyed by bare table name. */\n catalogue: Map<string, TableMeta>;\n /** The declared tables of this source, so a column can be named by its key. */\n tables: readonly TableDescriptor[];\n}): SchemaDifference[] {\n const { generated, catalogue, tables } = options;\n if (!generated) return [];\n\n const declaredByTable = new Map<string, TableDescriptor>();\n for (const descriptor of tables) declaredByTable.set(bareTableName(descriptor.table), descriptor);\n\n const differences: SchemaDifference[] = [];\n\n for (const value of Object.values(generated)) {\n if (!isTable(value)) continue;\n const table = drizzleTableName(value as PgTable);\n const declared = declaredByTable.get(table);\n const at = { table, slug: declared?.slug };\n\n const meta = catalogue.get(table);\n if (!meta) {\n // Only for a table this source declares: the module\n // carries every table of the project, including the ones another\n // data source holds, and those are legitimately absent here.\n if (declared) differences.push({ ...at, kind: \"missing-table\" });\n continue;\n }\n\n const live = catalogueColumns(meta);\n const seen = new Set<string>();\n\n // On the auth table, auth owns its own columns' contract and the\n // generated file deliberately does not carry it: `render-drizzle` drops\n // the columns an auth table does not declare (`is_anonymous`,\n // `tokens_valid_after`) because drizzle-kit creates no auth table, and\n // the table's own column definitions say nothing about the\n // `NOT NULL DEFAULT` that `ensureAuthTablesExist` applies.\n //\n // Comparing them anyway reported seven differences on a project nobody\n // had touched yet, and prescribed `rebase schema generate` — which\n // regenerates the file from the same table and cannot change any\n // of them. A warning that survives its own remedy teaches the reader to\n // ignore the next one, so these are not differences. A *type* mismatch\n // still is: that is the file and the database disagreeing about\n // something neither side intends.\n const authOwned = declared?.auth\n ? new Set(AUTH_USERS_COLUMNS.map(c => c.column))\n : undefined;\n\n for (const [key, column] of Object.entries(getTableColumns(value as PgTable))) {\n const name = (column as { name?: string }).name ?? key;\n seen.add(name);\n const columnKey = declared ? servedKeyOf(declared, name) : key;\n const generatedFamily = typeFamily((column as { getSQLType?: () => string }).getSQLType?.());\n const generatedNotNull = Boolean((column as { notNull?: boolean }).notNull);\n\n const found = live.get(name);\n if (!found) {\n differences.push({ ...at, kind: \"missing-column\", column: name, key: columnKey, generated: generatedFamily });\n continue;\n }\n if (found.family !== generatedFamily) {\n differences.push({\n ...at,\n kind: \"type\",\n column: name,\n key: columnKey,\n generated: generatedFamily,\n live: found.family\n });\n }\n if (found.notNull !== generatedNotNull && !authOwned?.has(name)) {\n differences.push({\n ...at,\n kind: \"nullability\",\n column: name,\n key: columnKey,\n generated: generatedNotNull ? \"NOT NULL\" : \"nullable\",\n live: found.notNull ? \"NOT NULL\" : \"nullable\"\n });\n }\n }\n\n for (const [name, column] of live) {\n if (seen.has(name)) continue;\n if (authOwned?.has(name)) continue;\n differences.push({\n ...at,\n kind: \"extra-column\",\n column: name,\n key: declared ? servedKeyOf(declared, name) : name,\n live: column.family\n });\n }\n }\n\n return differences;\n}\n\n/**\n * Boot's drift question, asked of a database from outside a boot.\n *\n * The same two calls boot makes before it warns, with the arguments it makes\n * them with: the catalogue read the way the registry reads it\n * ({@link readCatalogueSchema}), then {@link diffGeneratedSchemaAgainstCatalogue}\n * over its metadata. `rebase doctor` asks through here, because the boot\n * warning sends the reader to the doctor for \"the full report\" — and while the\n * doctor compared on its own terms, it answered \"In sync\" over a NOT NULL and a\n * left-behind column that boot had just warned about.\n *\n * `tables` are the data source's own, as boot filters them.\n */\nexport async function readGeneratedSchemaDrift(options: {\n client: Queryable;\n /** The `tables` export of `schema.generated.ts`. */\n generated: Record<string, unknown> | undefined;\n tables: readonly TableDescriptor[];\n defaultSchema: string;\n}): Promise<SchemaDifference[]> {\n const { client, generated, tables, defaultSchema } = options;\n if (!generated || tables.length === 0) return [];\n const catalogue = await readCatalogueSchema({ client, tables, defaultSchema });\n return diffGeneratedSchemaAgainstCatalogue({ generated, catalogue: catalogue.meta, tables });\n}\n\n/** One line, in the terms the reader has: table slug, column key, column. */\nexport function describeSchemaDifference(difference: SchemaDifference): string {\n const where = difference.slug\n ? `${difference.slug} (table \"${difference.table}\")`\n : `table \"${difference.table}\"`;\n const field = difference.column\n ? `${difference.key && difference.key !== difference.column\n ? `${difference.key} → \"${difference.column}\"`\n : `\"${difference.column}\"`}`\n : undefined;\n\n switch (difference.kind) {\n case \"missing-table\":\n return `${where} is in schema.generated.ts but not in the database`;\n case \"missing-column\":\n return `${where}: ${field} is in schema.generated.ts but not in the database`;\n case \"extra-column\":\n return `${where}: ${field} is in the database but not in schema.generated.ts (${difference.live})`;\n case \"type\":\n return `${where}: ${field} is ${difference.generated} in schema.generated.ts and ${difference.live} in the database`;\n case \"nullability\":\n return `${where}: ${field} is ${difference.generated} in schema.generated.ts and ${difference.live} in the database`;\n }\n}\n\n/**\n * The `rebase schema reconcile` line for a difference it can apply: a column\n * the database requires and the table made nullable, or one the table no\n * longer declares. Undefined for the rest.\n */\nexport function reconcileFix(difference: SchemaDifference): string | undefined {\n if (difference.kind === \"nullability\" && difference.live === \"NOT NULL\") return \"rebase schema reconcile\";\n if (difference.kind === \"extra-column\" && difference.slug) {\n return `rebase schema reconcile --drop ${difference.slug}.${difference.column}`;\n }\n return undefined;\n}\n\n/**\n * Report the differences, one warning each, and never throw.\n *\n * Per difference rather than one summary block on purpose: these are read out of\n * a log aggregator as often as a terminal, and a single multi-line message\n * cannot be filtered down to the one table somebody is looking at.\n *\n * The fix it names is `rebase db push`. `rebase dev` rewrites\n * schema.generated.ts from the tables on every change, and boot applies\n * only additive changes, so what is still different at boot is the database\n * behind the file: a rename, a dropped column, a narrowed type, a NOT NULL.\n * `rebase schema generate` rewrites the file and leaves the database as it is,\n * so it is named only for tables that changed since the file was written.\n */\nexport function warnOnGeneratedSchemaDrift(differences: SchemaDifference[]): void {\n if (differences.length === 0) return;\n\n logger.warn(\n `📄 [schema] schema.generated.ts and the database disagree (${differences.length} difference` +\n `${differences.length === 1 ? \"\" : \"s\"}). Boot applies only additive changes; these are the ones it ` +\n \"left for you. Run `rebase db push` to apply them (it shows the plan and asks before anything \" +\n \"destructive), or `rebase db generate` for a migration. A NOT NULL to relax or a column to drop \" +\n \"can also be applied through the running backend, Rebase Cloud included: `rebase schema reconcile`. \" +\n \"If backend/schema changed since schema.generated.ts was written, run `rebase schema generate` first.\"\n );\n\n for (const difference of differences) {\n logger.warn(` • ${describeSchemaDifference(difference)}`, {\n schemaDrift: {\n kind: difference.kind,\n table: difference.table,\n slug: difference.slug,\n column: difference.column,\n key: difference.key,\n generated: difference.generated,\n live: difference.live\n },\n fix: reconcileFix(difference) ?? \"rebase db push\"\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2CA,eAAsB,iBAClB,QACA,UAOA,UAA+B,CAAC,GACL;CAC3B,MAAM,EAAE,MAAM,WAAW,MAAM,OAAO,MAClC;;kDAE0C,QAAQ,QAAQ,8BAA8B,iBAAiB;;;WAGtG,QAAQ,QAAQ;;;iGAGsE,GAAG;+BAE5F,CAAC,QAAQ,CACb;CAEA,MAAM,EAAE,MAAM,YAAY,MAAM,OAAO,MACnC;;;;;;;;;;;;;;;;;;;;;;;;;;WA0BG,QAAQ,QAAQ;;;;;;;;;;;;iGAYsE,MACzF,CAAC,QAAQ,CACb;CAEA,MAAM,EAAE,MAAM,eAAe,MAAM,OAAO,MACtC;;;;;;;+CAQA,CAAC,QAAQ,CACb;CAEA,MAAM,EAAE,MAAM,QAAQ,MAAM,OAAO,MAC/B;;;;;;oDAOA,CAAC,QAAQ,CACb;CAEA,MAAM,EAAE,MAAM,QAAQ,MAAM,OAAO,MAC/B;;;;;;;;;;;;6EAaA,CAAC,QAAQ,CACb;CAEA,MAAM,YAAY,eAAe,QAAQ,SAAS,KAAK,GAAG;CAC1D,OAAO;EACH;EACA,SAAS,aAAa,UAAU;EAChC,YAAY,mBAAmB,SAAS;CAC5C;AACJ;;AAqBA,SAAS,qBAAqB,YAA6B,SAA+C;CACtG,MAAM,OAAO,WAAW,UAAU,QAAO,aAAY,QAAQ,IAAI,SAAS,MAAM,CAAC;CACjF,IAAI,KAAK,WAAW,GAAG,OAAO;CAC9B,MAAM,YAAY,IAAI,IA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AAO,GAAG,MAAM,IAAI,MAAM,MAAM,WAAW,UAAU,8BAA8B,WAAW,KAAK;CAC3G;AACJ;;;;;;AAOA,SAAgB,aAAa,YAAkD;CAC3E,IAAI,WAAW,SAAS,iBAAiB,WAAW,SAAS,YAAY,OAAO;CAChF,IAAI,WAAW,SAAS,kBAAkB,WAAW,MACjD,OAAO,kCAAkC,WAAW,KAAK,GAAG,WAAW;AAG/E;;;;;;;;;;;;;;;AAgBA,SAAgB,2BAA2B,aAAuC;CAC9E,IAAI,YAAY,WAAW,GAAG;CAE9B,OAAO,KACH,8DAA8D,YAAY,OAAO,aAC9E,YAAY,WAAW,IAAI,KAAK,IAAI,ycAK3C;CAEA,KAAK,MAAM,cAAc,aACrB,OAAO,KAAK,QAAQ,yBAAyB,UAAU,KAAK;EACxD,aAAa;GACT,MAAM,WAAW;GACjB,OAAO,WAAW;GAClB,MAAM,WAAW;GACjB,QAAQ,WAAW;GACnB,KAAK,WAAW;GAChB,WAAW,WAAW;GACtB,MAAM,WAAW;EACrB;EACA,KAAK,aAAa,UAAU,KAAK;CACrC,CAAC;AAET"}
|
|
1
|
+
{"version":3,"file":"generated-schema-diff-DDktAATD.js","names":[],"sources":["../src/schema/introspect-runtime.ts","../src/utils/pg-array-null-patch.ts","../src/schema/dynamic-tables.ts","../src/schema/config-relations.ts","../src/schema/catalogue-schema.ts","../src/schema/generated-schema-diff.ts"],"sourcesContent":["/**\n * Runtime introspection — what a backend with no `backend/schema` serves.\n *\n * `introspectTables` (`./introspect-tables`) describes every protected table\n * of the database as a `TableDescriptor`; this module compiles those into the\n * tables the runtime runs on (`compileIntrospectedTables`) and reads the catalogue the\n * runtime builds its Drizzle tables from (`introspectSchema`, shared with the\n * declared path in `catalogue-schema.ts`).\n *\n * Distinct from `introspect-db.ts`, which describes the same database with\n * `describeTables(…, { purpose: \"generate\" })` and prints the descriptors as\n * `backend/schema` source for a developer to edit and commit.\n */\nimport type { CompiledTable, TableDescriptor } from \"@rebasepro/types\";\nimport { compileDescribedTables, isSchemaDefinitionError } from \"@rebasepro/common\";\n\nimport {\n TableRow,\n TableColumn,\n EnumValue,\n PrimaryKeyRow,\n ForeignKeyRow,\n TableMeta,\n buildTablesMap,\n buildEnumMap,\n identifyJoinTables\n} from \"./introspect-db-logic\";\n\nexport interface IntrospectedSchema {\n tablesMap: Map<string, TableMeta>;\n enumMap: Map<string, string[]>;\n joinTables: Set<string>;\n}\n\n/** Minimal query surface — satisfied by pg.Client and pg.Pool alike. */\nexport interface Queryable {\n query<R>(text: string, values?: unknown[]): Promise<{ rows: R[] }>;\n}\n\n/**\n * Read tables, columns, enums, primary keys and foreign keys for a schema.\n * Mirrors the queries in introspect-db.ts.\n */\nexport async function introspectSchema(\n client: Queryable,\n pgSchema: string,\n /**\n * Read views and materialized views too, as tables to read from — what\n * the runtime catalogue needs for tables declared with `defineView`. Off\n * for introspection that turns relations into tables to serve, where a\n * view is not one.\n */\n options: { views?: boolean } = {}\n): Promise<IntrospectedSchema> {\n const { rows: tables } = await client.query<TableRow>(\n `SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = $1 AND table_type ${options.views ? \"IN ('BASE TABLE', 'VIEW')\" : \"= 'BASE TABLE'\"}\n AND table_name NOT LIKE 'drizzle_%'\n AND table_name NOT LIKE 'rebase_%'\n ${options.views ? `UNION\n SELECT c.relname AS table_name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = $1 AND c.relkind = 'm'\n AND COALESCE(obj_description(c.oid, 'pg_class'), '') NOT LIKE 'rebase:view-rows:%'` : \"\"}\n ORDER BY table_name`,\n [pgSchema]\n );\n\n const { rows: columns } = await client.query<TableColumn>(\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 -- A stored generated column must be declared as one, or drizzle\n -- writes DEFAULT into it on every INSERT. Postgres tolerates that\n -- today; the generated module has always declared them properly,\n -- and the runtime tables are built to match it.\n c.is_generated,\n c.generation_expression,\n (SELECT a.atttypmod FROM pg_attribute a\n JOIN pg_class pc ON a.attrelid = pc.oid\n WHERE pc.relname = c.table_name\n AND a.attname = c.column_name\n AND pc.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = c.table_schema)) as atttypmod\n FROM information_schema.columns c\n WHERE c.table_schema = $1\n -- A table has no column of that name (it is a system column); the\n -- gate of a materialized view carries one for fingerprint(), and it\n -- is not the collection's.\n AND NOT (c.column_name = 'xmin' AND EXISTS (\n SELECT 1 FROM information_schema.views v\n WHERE v.table_schema = c.table_schema AND v.table_name = c.table_name))\n ${options.views ? `UNION ALL\n -- A materialized view is in neither information_schema.tables nor\n -- .columns: its columns, in the same shape, from the catalogue.\n SELECT c.relname, a.attname,\n CASE WHEN t.typcategory = 'A' THEN 'ARRAY' WHEN t.typtype = 'e' THEN 'USER-DEFINED'\n ELSE format_type(a.atttypid, NULL) END,\n t.typname, CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END, NULL, 'NEVER', NULL, a.atttypmod\n FROM pg_attribute a\n JOIN pg_class c ON c.oid = a.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n JOIN pg_type t ON t.oid = a.atttypid\n WHERE n.nspname = $1 AND c.relkind = 'm' AND a.attnum > 0 AND NOT a.attisdropped\n AND COALESCE(obj_description(c.oid, 'pg_class'), '') NOT LIKE 'rebase:view-rows:%'` : \"\"}`,\n [pgSchema]\n );\n\n const { rows: enumValues } = await client.query<EnumValue>(\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 [pgSchema]\n );\n\n const { rows: pks } = await client.query<PrimaryKeyRow>(\n `SELECT t.relname as table_name, a.attname as column_name\n FROM pg_index i\n JOIN pg_attribute a ON a.attrelid = i.indrelid\n AND a.attnum = ANY(i.indkey)\n JOIN pg_class t ON t.oid = i.indrelid\n JOIN pg_namespace n ON n.oid = t.relnamespace\n WHERE i.indisprimary AND n.nspname = $1`,\n [pgSchema]\n );\n\n const { rows: fks } = await client.query<ForeignKeyRow>(\n `SELECT\n tc.table_name,\n kcu.column_name,\n ccu.table_name AS foreign_table_name,\n ccu.column_name AS foreign_column_name\n FROM information_schema.table_constraints AS tc\n JOIN information_schema.key_column_usage AS kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n JOIN information_schema.constraint_column_usage AS ccu\n ON ccu.constraint_name = tc.constraint_name\n AND ccu.table_schema = tc.table_schema\n WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = $1`,\n [pgSchema]\n );\n\n const tablesMap = buildTablesMap(tables, columns, pks, fks);\n return {\n tablesMap,\n enumMap: buildEnumMap(enumValues),\n joinTables: identifyJoinTables(tablesMap)\n };\n}\n\n/**\n * What {@link compileIntrospectedTables} returns.\n *\n * @group Schema\n */\nexport interface CompiledIntrospection {\n /** The descriptors served — every one given, unless it is in {@link dropped}. */\n tables: TableDescriptor[];\n /** The same tables compiled for the runtime, one per descriptor of {@link tables}, in the same order. */\n compiled: CompiledTable[];\n /**\n * Descriptors no definition could be built from, each with why: a table\n * `defineTable` itself refuses (no columns, a schema name that is not a plain\n * identifier). They are not served; the relations into them are dropped.\n */\n dropped: { table: string; reason: string }[];\n}\n\n/** A descriptor without its relations into `removed`; a foreign-key column such a relation held becomes a plain column. */\nfunction withoutRelationsInto(descriptor: TableDescriptor, removed: ReadonlySet<string>): TableDescriptor {\n const gone = descriptor.relations.filter(relation => removed.has(relation.target));\n if (gone.length === 0) return descriptor;\n const goneNames = new Set(gone.map(relation => relation.name));\n return {\n ...descriptor,\n relations: descriptor.relations.filter(relation => !goneNames.has(relation.name)),\n columns: descriptor.columns.map(column => {\n if (column.foreignKeyOf === undefined || !goneNames.has(column.foreignKeyOf)) return column;\n const { foreignKeyOf: _foreignKeyOf, derived: _derived, ...plain } = column;\n return plain;\n })\n };\n}\n\n/**\n * The tables an introspected database is served through, compiled.\n *\n * Each descriptor is kept as introspected, beside the definition that states\n * it (`compileDescribedTables`). The definitions carry `rls: \"admin-only\"`:\n * Rebase generates no policy for a table it did not declare, and the\n * request-time code reads none — the database's own policies decide every\n * row, as they always have. The descriptors keep stating those policies for\n * `GET /api/schema/tables`.\n *\n * Never throws for one table: a descriptor no definition can be built from is\n * dropped and named in {@link CompiledIntrospection.dropped}, and the rest are\n * served.\n *\n * @group Schema\n */\nexport function compileIntrospectedTables(tables: readonly TableDescriptor[]): CompiledIntrospection {\n const dropped: CompiledIntrospection[\"dropped\"] = [];\n let remaining = [...tables];\n for (;;) {\n try {\n const compiled = compileDescribedTables(remaining, { rls: () => \"admin-only\" });\n return { tables: remaining, compiled, dropped };\n } catch (error) {\n if (!isSchemaDefinitionError(error)) throw error;\n const reasons = new Map<string, string[]>();\n for (const problem of error.problems) {\n const table = remaining.find(candidate => candidate.name === problem.table || candidate.slug === problem.table);\n if (!table) continue;\n reasons.set(table.slug, [...(reasons.get(table.slug) ?? []), problem.key ? `${problem.key}: ${problem.message}` : problem.message]);\n }\n if (reasons.size === 0) throw error;\n for (const [table, list] of reasons) dropped.push({ table, reason: list.join(\"; \") });\n const removed = new Set(reasons.keys());\n remaining = remaining.filter(table => !removed.has(table.slug)).map(table => withoutRelationsInto(table, removed));\n }\n }\n}\n","import { getTableColumns } from \"drizzle-orm\";\nimport { PgArray, PgTable } from \"drizzle-orm/pg-core\";\n\n/**\n * Read a Postgres array literal (`{a,\"b c\",NULL,\"NULL\"}`, nested\n * `{{1,2},{3,4}}`) into its items, each as the text Postgres wrote — an\n * unquoted `NULL` as `null`.\n *\n * Drizzle's own parser reads an unquoted `NULL` as the four-letter string, so\n * a `date[]` / `timestamptz[]` / enum array holding a null item (the types the\n * drivers leave to drizzle as text) served `\"NULL\"` in its place. A quoted\n * `\"NULL\"` is the string.\n *\n * An explicit lower bound (`[0:1]={…}`) is skipped: the items are what is\n * served, not their subscripts.\n */\nexport function parsePgArrayLiteral(literal: string): unknown[] {\n let i = literal.startsWith(\"[\") ? literal.indexOf(\"=\") + 1 : 0;\n\n const readArray = (): unknown[] => {\n const items: unknown[] = [];\n i++; // `{`\n if (literal[i] === \"}\") {\n i++;\n return items;\n }\n for (;;) {\n if (literal[i] === \"{\") {\n items.push(readArray());\n } else if (literal[i] === \"\\\"\") {\n let text = \"\";\n i++;\n while (i < literal.length && literal[i] !== \"\\\"\") {\n if (literal[i] === \"\\\\\") i++;\n text += literal[i];\n i++;\n }\n i++; // closing quote\n items.push(text);\n } else {\n const start = i;\n while (i < literal.length && literal[i] !== \",\" && literal[i] !== \"}\") i++;\n const text = literal.slice(start, i).trim();\n items.push(text.toUpperCase() === \"NULL\" ? null : text);\n }\n if (literal[i] === \",\") {\n i++;\n continue;\n }\n i++; // `}`\n return items;\n }\n };\n\n return literal[i] === \"{\" ? readArray() : [];\n}\n\n/**\n * Patches every native array column (`PgArray`) of the given tables so a\n * read hands back what the array holds, nulls included.\n *\n * Drizzle's `PgArray.mapFromDriverValue` has two faults this replaces:\n *\n * - it calls `value.map(...)` on a NULL column — `TypeError: value.map is\n * not a function` — so a null array is served as `null` here;\n * - it maps every item through the item column, a null item included, and\n * parses a text literal's unquoted `NULL` as the string `\"NULL\"`: a null\n * item of a `bigint[]` came back `0` (`Number(null)`), of a `date[]`,\n * `timestamptz[]` or enum array `\"NULL\"`. A null item stays `null` here,\n * and only the others go through the item column's own mapping.\n *\n * Applied where the runtime builds its tables (`buildDrizzleTablesFromSchema`),\n * so every table a driver reads through carries it. Idempotent: a mark on the\n * column, so a table patched twice is wrapped once.\n */\nexport function patchPgArrayNullSafety(tables: Record<string, unknown>): void {\n for (const tableOrRelation of Object.values(tables)) {\n if (!(tableOrRelation instanceof PgTable)) continue;\n\n const columns = getTableColumns(tableOrRelation);\n for (const column of Object.values(columns)) {\n if (!(column instanceof PgArray) || Object.hasOwn(column, \"__rebaseArrayPatched\")) continue;\n Object.defineProperty(column, \"__rebaseArrayPatched\", { value: true });\n const item = column.baseColumn;\n const mapItems = (items: unknown[]): unknown[] => items.map(entry => {\n if (entry === null || entry === undefined) return null;\n return Array.isArray(entry) ? mapItems(entry) : item.mapFromDriverValue(entry);\n });\n column.mapFromDriverValue = function (value: unknown) {\n if (value === null || value === undefined) return null;\n if (typeof value === \"string\") return mapItems(parsePgArrayLiteral(value));\n return Array.isArray(value) ? mapItems(value) : value;\n };\n }\n }\n}\n","/**\n * Build drizzle tables at runtime from an introspected schema.\n *\n * **Every** data source's tables are built here, from `information_schema`,\n * after boot-ensure has run — a project with declared collections included. The\n * committed `schema.generated.ts` is a build artefact for Atlas, `db push`,\n * `eject` and user code; the runtime does not read it for its tables, because a\n * file that is one commit behind the database used to change what the server\n * served (a renamed foreign-key column 500'd every request, a lost relation\n * silently emptied a list). See `catalogue-schema.ts` for the caller.\n *\n * These are handed to drizzle as its schema, which keeps the relational query\n * path (`db.query.*`) working; without them FetchService would fall back to\n * plain selects and lose relation loading.\n *\n * Two things a caller has to supply for the tables to match what the generated\n * module used to produce, both about *names*: the Drizzle object is keyed by the\n * wire name of a column and not by the column (`authorId`, not `author_id`), and\n * a relation is keyed by the table's own relation name rather than by a\n * guess made from the foreign key. Both come from the table descriptors — see\n * `columnKeysFromTables` and `buildDrizzleRelationsFromTables`.\n */\nimport {\n bigint,\n boolean,\n char,\n cidr,\n customType,\n date,\n doublePrecision,\n geometry,\n inet,\n integer,\n interval,\n json,\n jsonb,\n line,\n macaddr,\n macaddr8,\n numeric,\n pgSchema,\n pgTable,\n point,\n primaryKey,\n real,\n smallint,\n text,\n time,\n timestamp,\n uuid,\n varchar,\n vector,\n type AnyPgColumn,\n type PgColumnBuilderBase,\n type PgTable\n} from \"drizzle-orm/pg-core\";\n\nimport { getTableColumns, relations, sql, type Relation, type Relations } from \"drizzle-orm\";\nimport { toWireKey } from \"@rebasepro/utils\";\nimport { patchPgArrayNullSafety } from \"../utils/pg-array-null-patch\";\n\nimport type { TableColumn, TableMeta } from \"./introspect-db-logic\";\n\n/**\n * The Drizzle object key a column is served under, given its table.\n *\n * Defaults to the column name — right for a junction table and for a database\n * nothing declares — and is supplied from the collections wherever there is\n * one, because there the wire name is the property key. Every read and write\n * path in this driver indexes tables and rows by that key.\n */\nexport type ColumnKeyResolver = (tableName: string, columnName: string) => string;\n\nconst columnNameAsKey: ColumnKeyResolver = (_table, column) => column;\n\n/** drizzle ships no bytea builder; binary must round-trip as a Buffer. */\nconst bytea = customType<{ data: Buffer; driverData: Buffer }>({\n dataType: () => \"bytea\"\n});\n\n/**\n * A full-text search column, declared with its real SQL type.\n *\n * Not cosmetic: `isSearchIndexColumn` asks the column for its type and drops\n * every `tsvector` from the projection, so a search column that fell through to\n * `text` (the old default for an unrecognised type) would be selected, returned\n * to callers, and rendered in the admin as a wall of lexemes. drizzle ships no\n * builder for these two.\n */\nconst tsvector = customType<{ data: string; driverData: string }>({\n dataType: () => \"tsvector\"\n});\n\nconst tsquery = customType<{ data: string; driverData: string }>({\n dataType: () => \"tsquery\"\n});\n\n/**\n * Postgres stores a column's type modifier (varchar length, vector dimensions)\n * in `atttypmod`. For length-carrying string types it is length + VARHDRSZ(4);\n * for pgvector it is the dimension count as-is. -1 means unspecified.\n */\nfunction varlenLength(col: TableColumn): number | undefined {\n return col.atttypmod && col.atttypmod > 4 ? col.atttypmod - 4 : undefined;\n}\n\n/**\n * Map a Postgres type to a drizzle column builder, keyed on `udt_name` — the\n * concrete underlying type, which is exact where `data_type` reports umbrella\n * values like \"ARRAY\" or \"USER-DEFINED\".\n *\n * Unknown types fall back to `text`: the driver still reads and writes them,\n * with the value passing through as a string, which beats dropping the column.\n */\nfunction scalarBuilder(udtName: string, name: string, col: TableColumn): PgColumnBuilderBase {\n switch (udtName) {\n case \"uuid\":\n return uuid(name);\n case \"bool\":\n return boolean(name);\n case \"int2\":\n return smallint(name);\n case \"int4\":\n return integer(name);\n case \"int8\":\n return bigint(name, { mode: \"number\" });\n case \"float4\":\n return real(name);\n case \"float8\":\n return doublePrecision(name);\n case \"numeric\":\n case \"money\":\n return numeric(name);\n case \"json\":\n return json(name);\n case \"jsonb\":\n return jsonb(name);\n case \"date\":\n return date(name);\n case \"time\":\n return time(name);\n case \"timetz\":\n return time(name, { withTimezone: true });\n // `mode: \"string\"`, both of them, because that is what the generated\n // module declared for every `date` property: the value Postgres sent,\n // untouched. Drizzle's default mode is `date`, which parses it into a\n // `Date` — the same instant in a different shape, and a difference that\n // would have appeared only on the read path of a project that changed\n // nothing. (`parsePropertyFromServer` normalises either shape to an ISO\n // string for a declared `date` property, so what a REST caller sees is\n // the same; a raw `db.select()` is where the two differ.)\n case \"timestamp\":\n return timestamp(name, { mode: \"string\" });\n case \"timestamptz\":\n return timestamp(name, { withTimezone: true, mode: \"string\" });\n case \"interval\":\n return interval(name);\n case \"bytea\":\n return bytea(name);\n case \"inet\":\n return inet(name);\n case \"cidr\":\n return cidr(name);\n case \"macaddr\":\n return macaddr(name);\n case \"macaddr8\":\n return macaddr8(name);\n case \"point\":\n return point(name);\n case \"line\":\n return line(name);\n case \"geometry\":\n return geometry(name);\n case \"vector\": {\n // drizzle requires the dimension count; without it fall back to text\n // rather than declaring a vector of unknown width.\n const dimensions = col.atttypmod && col.atttypmod > 0 ? col.atttypmod : undefined;\n return dimensions ? vector(name, { dimensions }) : text(name);\n }\n case \"bpchar\": {\n const length = varlenLength(col);\n return length ? char(name, { length }) : char(name);\n }\n case \"varchar\": {\n const length = varlenLength(col);\n return length ? varchar(name, { length }) : text(name);\n }\n case \"tsvector\":\n return tsvector(name);\n case \"tsquery\":\n return tsquery(name);\n default:\n // Includes text, enums (pg enums are strings on the wire), citext,\n // geography, and anything else this driver hasn't met yet.\n //\n // An enum deliberately stays `text`, which is what the generated\n // module's `pgEnum` column also serves: drizzle does no runtime\n // validation of enum members either way, and Postgres rejects a\n // label it does not have. The difference is only in the type the\n // generated *types* carry, and those come from the collection.\n return text(name);\n }\n}\n\n/**\n * The fluent methods this file calls on a column builder.\n *\n * Drizzle's `PgColumnBuilderBase` exposes none of them by design: they live on\n * the concrete `PgColumnBuilder` subclasses, each generic over the column's\n * TypeScript type, its name and whether it is notNull / hasDefault — a chain\n * resolved when you *write* a schema, and not resolvable when you build one\n * from a catalogue read at runtime, which is all this file does.\n *\n * So a conversion here is irreducible; what was avoidable was doing it four\n * separate times, each declaring its own one-method slice of the builder and\n * each free to disagree with the others about a name or a signature. Declaring\n * the methods as an *extension* of the base also drops the double cast: the\n * two types overlap, so tsc will still refuse this if drizzle ever gives\n * `PgColumnBuilderBase` a conflicting member.\n */\ninterface FluentColumnBuilder extends PgColumnBuilderBase {\n array(): PgColumnBuilderBase;\n notNull(): PgColumnBuilderBase;\n primaryKey(): PgColumnBuilderBase;\n generatedAlwaysAs(expr: unknown): PgColumnBuilderBase;\n}\n\n/** See {@link FluentColumnBuilder}. */\nconst fluent = (builder: PgColumnBuilderBase): FluentColumnBuilder => builder as FluentColumnBuilder;\n\nfunction columnBuilderFor(col: TableColumn): PgColumnBuilderBase {\n // Array types are named after their element with a leading underscore\n // (_int4 = int4[]), so the element mapping is reused verbatim.\n if (col.udt_name.startsWith(\"_\")) {\n const element = scalarBuilder(col.udt_name.slice(1), col.column_name, col);\n return fluent(element).array();\n }\n return scalarBuilder(col.udt_name, col.column_name, col);\n}\n\n/**\n * Build one drizzle table per introspected table, keyed by table name.\n *\n * @param columnKey how a column is named on the wire — see {@link ColumnKeyResolver}.\n */\nexport function buildDrizzleTablesFromSchema(\n tablesMap: Map<string, TableMeta>,\n pgSchemaName = \"public\",\n columnKey: ColumnKeyResolver = columnNameAsKey\n): Record<string, PgTable> {\n const schema = pgSchemaName === \"public\" ? null : pgSchema(pgSchemaName);\n // The column set is only known at runtime, so drizzle's generic table\n // signature can't be satisfied statically; call it through a loose type.\n const createTable = (schema ? schema.table.bind(schema) : pgTable) as (\n name: string,\n columns: Record<string, PgColumnBuilderBase>,\n extras?: (self: Record<string, AnyPgColumn>) => unknown[]\n ) => PgTable;\n\n const tables: Record<string, PgTable> = {};\n\n for (const [tableName, meta] of tablesMap) {\n const columns: Record<string, PgColumnBuilderBase> = {};\n const keyOf = new Map<string, string>();\n\n for (const col of meta.columns) {\n let builder = columnBuilderFor(col);\n\n if (col.is_nullable === \"NO\") {\n builder = fluent(builder).notNull();\n }\n // Single-column primary keys are marked inline; composite keys are\n // declared in the table extras below.\n if (meta.pks.length === 1 && meta.pks[0] === col.column_name) {\n builder = fluent(builder).primaryKey();\n }\n // A stored generated column must be left out of every INSERT, which\n // is what `.generatedAlwaysAs` tells drizzle. The expression is\n // carried through so a drizzle-kit run over these tables describes\n // the column it actually found; nothing at runtime evaluates it.\n if (col.is_generated === \"ALWAYS\") {\n builder = fluent(builder).generatedAlwaysAs(sql.raw(col.generation_expression ?? \"\"));\n }\n\n const key = columnKey(tableName, col.column_name);\n keyOf.set(col.column_name, key);\n columns[key] = builder;\n }\n\n const isComposite = meta.pks.length > 1;\n tables[tableName] = createTable(\n tableName,\n columns,\n isComposite\n ? (t) => {\n const [first, ...rest] = meta.pks.map((pk) => t[keyOf.get(pk) ?? pk]);\n return [primaryKey({ columns: [first, ...rest] })];\n }\n : undefined\n );\n }\n\n // Drizzle's array mapping turns a null item into `0` / `\"NULL\"` and fails\n // on a null array; every table the runtime reads through is built here.\n patchPgArrayNullSafety(tables);\n return tables;\n}\n\n/**\n * Build drizzle `relations()` for the foreign keys, so the relational query\n * path can actually load them.\n *\n * FetchService asks drizzle for `with: { <key>: true }`, keyed by the relation\n * property on the collection. Tables alone don't satisfy that — without these,\n * `?include=author` silently returns the raw `author_id` and no author.\n *\n * The keys here must match the relation names `introspectTables` gives an\n * introspected table (`introspect-tables.ts`), which name the collection's\n * relation properties.\n */\nexport function buildDrizzleRelationsFromSchema(\n tablesMap: Map<string, TableMeta>,\n tables: Record<string, PgTable>,\n columnKey: ColumnKeyResolver = columnNameAsKey\n): Record<string, Relations> {\n /** Owning side, per table: the `one()` relations from its foreign keys. */\n const owning = new Map<string, { key: string; targetTable: string; fkColumn: string; targetColumn: string; relationName: string }[]>();\n /** Inverse side, per referenced table: the matching `many()` back-references. */\n const inverse = new Map<string, { key: string; sourceTable: string; relationName: string }[]>();\n\n for (const [tableName, meta] of tablesMap) {\n if (!tables[tableName]) continue;\n // The keys the table actually carries — what a relation key must not\n // collide with, since both live in one Drizzle object.\n const columnNames = new Set(meta.columns.map((c) => columnKey(tableName, c.column_name)));\n\n for (const fk of meta.fks) {\n if (!tables[fk.foreign_table_name]) continue;\n\n // Mirrors introspectTables' relation names: author_id -> author,\n // falling back to the target table when the column name carries no\n // hint. `toWireKey` for the same reason it is there — the two keys\n // must be the same string or the collection advertises a relation key\n // drizzle has never heard of (`author_ref` here, `authorRef` there).\n let key = toWireKey(fk.column_name.replace(/_id$/, \"\"));\n if (meta.pks.includes(fk.column_name) && key === fk.column_name) {\n key = fk.foreign_table_name;\n }\n // A relation key must not shadow a real column.\n if (columnNames.has(key)) continue;\n\n // Pairs the two sides. Drizzle matches a named one() to the many()\n // carrying the same name, and disambiguates multiple foreign keys\n // into the same table.\n const relationName = `${tableName}_${fk.column_name}`;\n\n owning.set(tableName, [\n ...(owning.get(tableName) ?? []),\n {\n key,\n targetTable: fk.foreign_table_name,\n // The Drizzle keys, not the columns: `fields`/`references`\n // index the built table objects, which are keyed by the\n // wire name wherever a collection supplies one.\n fkColumn: columnKey(tableName, fk.column_name),\n targetColumn: columnKey(fk.foreign_table_name, fk.foreign_column_name),\n relationName\n }\n ]);\n\n const backKey = tableName;\n const targetColumns = new Set(\n (tablesMap.get(fk.foreign_table_name)?.columns ?? [])\n .map((c) => columnKey(fk.foreign_table_name, c.column_name))\n );\n if (targetColumns.has(backKey)) continue;\n\n inverse.set(fk.foreign_table_name, [\n ...(inverse.get(fk.foreign_table_name) ?? []),\n { key: backKey, sourceTable: tableName, relationName }\n ]);\n }\n }\n\n const built: Record<string, Relations> = {};\n\n for (const tableName of tablesMap.keys()) {\n const table = tables[tableName];\n const ones = owning.get(tableName) ?? [];\n const manys = inverse.get(tableName) ?? [];\n if (!table || (ones.length === 0 && manys.length === 0)) continue;\n\n built[`${tableName}Relations`] = relations(table, ({ one, many }) => {\n const map: Record<string, Relation> = {};\n\n for (const rel of ones) {\n map[rel.key] = one(tables[rel.targetTable], {\n // `getTableColumns` is drizzle's own accessor for this.\n // Indexing the table object — which is what the casts here\n // were for — also reaches its methods and symbols, so a\n // foreign key named after one of them yields something that\n // is not a column; and the target type they used,\n // `Record<string, never>`, makes every lookup `never`,\n // which is assignable to anything and therefore checks\n // nothing at all.\n fields: [getTableColumns(table)[rel.fkColumn]],\n references: [getTableColumns(tables[rel.targetTable])[rel.targetColumn]],\n relationName: rel.relationName\n });\n }\n\n // Drizzle needs the inverse of every named one(); without it,\n // normalizeRelation throws and the relational path is dead.\n for (const rel of manys) {\n // An inverse must not collide with an owning key on this table.\n if (map[rel.key]) continue;\n map[rel.key] = many(tables[rel.sourceTable], { relationName: rel.relationName });\n }\n\n return map;\n });\n }\n\n return built;\n}\n","/**\n * Build drizzle `relations()` for declared tables, from their descriptors.\n *\n * The heuristic builder in `dynamic-tables.ts` names a relation after the\n * foreign-key column (`author_id` → `author`), which is the only evidence a\n * database offers and is right for BaaS mode. It is wrong for a project that\n * declares its tables: there the relation's name is whatever the author\n * called it, `include=writer` addresses that name, and a relation whose key was\n * guessed from the column simply does not answer to it — the read returns the\n * bare foreign key and no target, silently, which is how a demo lost every\n * relation in its list view while the detail view (a different code path) kept\n * working.\n *\n * So when there are declared tables, they are the authority for *which* relations\n * exist and what they are called; the live catalogue is the authority for the\n * columns underneath. This is the same pairing `generate-drizzle-schema-logic`\n * emits into `schema.generated.ts` — kind for kind, key for key, and paired by\n * the same {@link tableRelationName} — only built against tables read back from\n * `information_schema` rather than against a file.\n */\nimport { getTableColumns, relations, type AnyColumn, type Relation, type Relations } from \"drizzle-orm\";\nimport type { PgTable } from \"drizzle-orm/pg-core\";\nimport type { RelationDescriptor, TableDescriptor } from \"@rebasepro/types\";\n\nimport { servedKeyOf, tableRelationName } from \"./relation-names\";\n\n/** A table's name with any schema prefix stripped — as the DDL creates it. */\nexport function bareTableName(name: string): string {\n return name.includes(\".\") ? name.split(\".\").pop()! : name;\n}\n\n/**\n * The key a table's rows are addressed by, as the generated module spells it:\n * the first primary-key column's key, else `id`.\n *\n * Deliberately the declaration's answer rather than the catalogue's primary\n * key — `references: [users.id]` in the generated file is keyed the same way,\n * and the two have to name the same Drizzle key for a relation to compile at\n * all.\n */\nfunction primaryKeyFieldKey(table: TableDescriptor): string {\n return table.primaryKey[0] ?? \"id\";\n}\n\n/**\n * The key on the source table that a `hasOne`/`hasMany` foreign key holds:\n * its `sourceKey` when the link names one, else the primary key.\n */\nfunction sourceKeyFieldKey(\n relation: Extract<RelationDescriptor, { kind: \"hasOne\" | \"hasMany\" }>,\n source: TableDescriptor\n): string {\n return relation.sourceKey\n ? servedKeyOf(source, relation.sourceKey)\n : primaryKeyFieldKey(source);\n}\n\n/**\n * A column of a built table, by its Drizzle key or by its column name.\n *\n * The key is the answer in the ordinary case, and the name is the fallback for\n * the one place a caller holds a column and not a field: a junction table's two\n * foreign keys, which are keyed by column *unless* the project also declares a\n * table over that junction, in which case they are keyed by its column keys.\n * Looking both up costs a scan of one table and removes the difference.\n */\nfunction columnOf(table: PgTable | undefined, key: string): AnyColumn | undefined {\n if (!table) return undefined;\n // Drizzle's column map is keyed by the JS property name, which is exactly\n // the \"keyed by its column keys\" case this function's docblock describes\n // — so `getTableColumns` answers it, and indexing the table object (which\n // also reaches its methods and symbols) was never needed.\n const direct = getTableColumns(table)[key];\n if (direct) return direct;\n for (const column of Object.values(getTableColumns(table))) {\n if (column.name === key) return column;\n }\n return undefined;\n}\n\ninterface OneSpec {\n key: string;\n target: PgTable;\n fields: [AnyColumn, ...AnyColumn[]];\n references: [AnyColumn, ...AnyColumn[]];\n relationName: string;\n}\n\ninterface ManySpec {\n key: string;\n target: PgTable;\n relationName: string;\n}\n\n/**\n * Drizzle relations for every declared table, keyed `<table>Relations`.\n *\n * @param descriptors every declared table backed by a table in `tables`, and\n * the targets of their relations\n * @param tables catalogue-built tables, keyed by bare table name\n */\nexport function buildDrizzleRelationsFromTables(\n descriptors: readonly TableDescriptor[],\n tables: Record<string, PgTable>\n): Record<string, Relations> {\n const ones = new Map<string, OneSpec[]>();\n const manys = new Map<string, ManySpec[]>();\n /** `<relationName>::<kind>` already emitted on a table — the generator dedupes the same way. */\n const emitted = new Map<string, Set<string>>();\n\n const claim = (table: string, name: string, kind: string): boolean => {\n const seen = emitted.get(table) ?? new Set<string>();\n emitted.set(table, seen);\n const key = `${name}::${kind}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n };\n\n const addOne = (table: string, spec: OneSpec) => ones.set(table, [...(ones.get(table) ?? []), spec]);\n const addMany = (table: string, spec: ManySpec) => manys.set(table, [...(manys.get(table) ?? []), spec]);\n\n const bySlug = new Map(descriptors.map(descriptor => [descriptor.slug, descriptor]));\n // Only reached for a target that is among `descriptors`: every caller\n // looks the target up in `bySlug` first.\n const targetOf = (slug: string): TableDescriptor => {\n const target = bySlug.get(slug);\n if (!target) throw new Error(`Relation target \"${slug}\" is not a declared table`);\n return target;\n };\n\n const byTable = new Map<string, TableDescriptor>();\n for (const descriptor of descriptors) {\n const table = bareTableName(descriptor.table);\n if (tables[table]) byTable.set(table, descriptor);\n }\n\n for (const [tableName, source] of byTable) {\n const table = tables[tableName];\n\n for (const relation of source.relations) {\n // A target outside this set has nothing to build against, and\n // nothing to fail over: the boot relation check reports an\n // unresolvable target by name.\n const target = bySlug.get(relation.target);\n if (!target) continue;\n const targetTableName = bareTableName(target.table);\n const targetTable = tables[targetTableName];\n const name = tableRelationName(relation, source, targetOf);\n\n switch (relation.kind) {\n case \"belongsTo\": {\n if (!targetTable) continue;\n if (!claim(tableName, name, relation.kind)) continue;\n const field = columnOf(table, servedKeyOf(source, relation.localKey));\n const reference = columnOf(targetTable, primaryKeyFieldKey(target));\n // A column the catalogue does not have would make drizzle\n // throw `Cannot read properties of undefined` from inside\n // `normalizeRelation`, three frames from anything nameable.\n // The boot relation check reports the same defect in terms\n // of the table; this only declines to build it.\n if (!field || !reference) continue;\n addOne(tableName, {\n key: relation.name,\n target: targetTable,\n fields: [field],\n references: [reference],\n relationName: name\n });\n break;\n }\n\n case \"hasOne\": {\n if (!targetTable) continue;\n if (!claim(tableName, name, relation.kind)) continue;\n // The foreign key lives on the target, so this side states\n // the join from its own end: its source key against the\n // target's foreign key. Drizzle has no `one()` that is paired\n // by `relationName` alone — `createOne` reads\n // `config.fields.reduce(...)` as the relations are evaluated,\n // which is at `drizzle({ schema })` — and a bare `one(target)`\n // is paired by table, which is ambiguous as soon as the target\n // has two links back here or the link is to its own table.\n // These are the columns drizzle would infer from the owning\n // side, given outright.\n const field = columnOf(table, sourceKeyFieldKey(relation, source));\n const reference = columnOf(targetTable, servedKeyOf(target, relation.foreignKey));\n if (!field || !reference) continue;\n addOne(tableName, {\n key: relation.name,\n target: targetTable,\n fields: [field],\n references: [reference],\n relationName: name\n });\n break;\n }\n\n case \"hasMany\": {\n if (!targetTable) continue;\n if (!claim(tableName, name, relation.kind)) continue;\n addMany(tableName, { key: relation.name, target: targetTable, relationName: name });\n break;\n }\n\n case \"manyToMany\": {\n const junctionName = bareTableName(relation.through.table);\n const junction = tables[junctionName];\n if (!junction) continue;\n if (!claim(tableName, name, relation.kind)) continue;\n addMany(tableName, { key: relation.name, target: junction, relationName: name });\n addJunctionSides(relation, source, target, junctionName, tables, targetOf, addOne, claim);\n break;\n }\n\n case \"via\":\n // A join chain is resolved at query time, not modelled as a\n // drizzle relation — same as the generator.\n break;\n }\n }\n }\n\n // The reciprocal a `many()` needs. A `hasMany` gives drizzle no columns to\n // join on; it finds them on the owning side, which exists only if the other\n // table happens to declare a `belongsTo` back. Where it does not, the\n // generated file synthesizes one under a `_synth_` key, and so does this.\n // A `hasOne` names its own columns, and gets the same owning side so the\n // target's table carries the link back under the same `relationName`.\n for (const [tableName, source] of byTable) {\n const table = tables[tableName];\n for (const relation of source.relations) {\n if (relation.kind !== \"hasMany\" && relation.kind !== \"hasOne\") continue;\n const target = bySlug.get(relation.target);\n if (!target) continue;\n const targetTableName = bareTableName(target.table);\n const targetTable = tables[targetTableName];\n if (!targetTable) continue;\n\n const name = tableRelationName(relation, source, targetOf);\n if (!claim(targetTableName, name, \"belongsTo\")) continue;\n\n const fkKey = servedKeyOf(target, relation.foreignKey);\n const field = columnOf(targetTable, fkKey);\n const reference = columnOf(table, sourceKeyFieldKey(relation, source));\n if (!field || !reference) continue;\n\n addOne(targetTableName, {\n key: `_synth_${targetTableName}_${fkKey}`,\n target: tables[tableName],\n fields: [field],\n references: [reference],\n relationName: name\n });\n }\n }\n\n const built: Record<string, Relations> = {};\n for (const tableName of new Set([...ones.keys(), ...manys.keys()])) {\n const table = tables[tableName];\n if (!table) continue;\n const tableOnes = ones.get(tableName) ?? [];\n const tableManys = manys.get(tableName) ?? [];\n\n built[`${tableName}Relations`] = relations(table, ({ one, many }) => {\n const map: Record<string, Relation> = {};\n for (const spec of tableOnes) {\n map[spec.key] = one(spec.target, {\n fields: spec.fields,\n references: spec.references,\n relationName: spec.relationName\n });\n }\n for (const spec of tableManys) {\n if (map[spec.key]) continue;\n map[spec.key] = many(spec.target, { relationName: spec.relationName });\n }\n return map;\n });\n }\n\n return built;\n}\n\n/**\n * The junction table's own two `one()` sides.\n *\n * A many-to-many is a `many(junction)` on each endpoint, so the junction has to\n * carry the matching `one()` back to each — without them drizzle can join a\n * post to its `posts_tags` rows and no further, and the tags come back as\n * junction rows. Keyed by the junction's own columns, which is how the\n * generated file keys them too.\n */\nfunction addJunctionSides(\n relation: Extract<RelationDescriptor, { kind: \"manyToMany\" }>,\n source: TableDescriptor,\n target: TableDescriptor,\n junctionName: string,\n tables: Record<string, PgTable>,\n targetOf: (slug: string) => TableDescriptor,\n addOne: (table: string, spec: OneSpec) => void,\n claim: (table: string, name: string, kind: string) => boolean\n): void {\n const junction = tables[junctionName];\n const sourceTable = tables[bareTableName(source.table)];\n const targetTable = tables[bareTableName(target.table)];\n if (!junction || !sourceTable || !targetTable) return;\n\n const sourceName = tableRelationName(relation, source, targetOf);\n // The far endpoint pairs with whatever *it* calls this junction, so the two\n // sides are looked up rather than assumed: an inverse declared on the target\n // owns the name, and only a junction nothing points back through needs a\n // synthesized one.\n const inverse = target.relations\n .find(r => r.kind === \"manyToMany\" && bareTableName(r.through.table) === junctionName);\n const targetName = inverse\n ? tableRelationName(inverse, target, targetOf)\n : `${junctionName}_${relation.through.targetKey}`;\n\n const pairs: [string, PgTable, string, TableDescriptor][] = [\n [relation.through.sourceKey, sourceTable, sourceName, source],\n [relation.through.targetKey, targetTable, targetName, target]\n ];\n\n for (const [column, endpointTable, relationName, endpoint] of pairs) {\n if (!claim(junctionName, relationName, \"junction\")) continue;\n const field = columnOf(junction, column);\n const reference = columnOf(endpointTable, primaryKeyFieldKey(endpoint));\n if (!field || !reference) continue;\n addOne(junctionName, {\n key: column,\n target: endpointTable,\n fields: [field],\n references: [reference],\n relationName\n });\n }\n}\n","/**\n * The runtime's Drizzle schema, read back from the database it is about to\n * serve.\n *\n * This is the whole point of the module: **the live catalogue is the schema**.\n * Boot-ensure has already created and altered whatever the tables describe\n * by the time this runs, so `information_schema` is both current and complete,\n * and the committed `schema.generated.ts` — which is a build artefact for Atlas,\n * `db push`, `eject` and user code — never decides what the server serves.\n *\n * It used to. The default data source was handed the bundle's generated module\n * and nothing reconciled it, so a file one commit behind the database changed\n * behaviour in ways that looked nothing like \"your schema file is old\":\n *\n * - a foreign-key column renamed by boot-ensure (`categorie_id` → `category_id`)\n * left every request 500ing, because the module still declared the old name;\n * - a property added to a collection answered `400 VALIDATION_UNKNOWN_FIELDS`\n * on first save, because the write check reads the table and the table came\n * from the file, while the column itself existed;\n * - relations missing from the module were silently missing from list reads.\n *\n * The catalogue cannot drift from itself. What the generated module is still\n * good for is telling the developer their file is stale — see\n * `generated-schema-diff.ts`, which is now its only reader at boot.\n */\nimport type { PgTable } from \"drizzle-orm/pg-core\";\nimport type { Relations } from \"drizzle-orm\";\nimport type { TableDescriptor } from \"@rebasepro/types\";\nimport { declaredSchemaOf, keyForColumn, resolveTableJunctions } from \"@rebasepro/common\";\nimport { toWireKey } from \"@rebasepro/utils\";\n\nimport { buildDrizzleRelationsFromSchema, buildDrizzleTablesFromSchema, type ColumnKeyResolver } from \"./dynamic-tables\";\nimport { bareTableName, buildDrizzleRelationsFromTables } from \"./config-relations\";\nimport { introspectSchema, type Queryable } from \"./introspect-runtime\";\nimport type { TableMeta } from \"./introspect-db-logic\";\nimport { tableSearchColumnNames } from \"./search-column\";\n\n/** The Postgres schema a table lives in: the one it declares, else `fallback`. */\nexport function schemaOfTable(table: Pick<TableDescriptor, \"schema\">, fallback: string): string {\n return declaredSchemaOf(table) ?? fallback;\n}\n\n/**\n * How a column of each table is keyed in the Drizzle object.\n *\n * The wire name, which is the column's key — `authorId`, never `author_id` —\n * because that is what every read and write path in this driver indexes tables\n * and rows by, and what the generated module has always emitted. Getting this\n * wrong does not throw: drizzle leaves an unknown key out of the statement and\n * the write reports success having stored nothing. A column the table does not\n * describe is keyed by the camelCase of its name, which is the key a foreign\n * key derived from it would get.\n *\n * Two exceptions, both columns no table declares:\n *\n * - the generated search columns keep their raw names, because `search_vector`\n * is how `searchColumnNamesOf` excludes them from responses and how the\n * condition builder finds the one to match against;\n * - a table no descriptor claims (a junction) is keyed by its **key** columns'\n * names, which is also what the generated file does for them — but a\n * junction that declares `pivot` columns keys those payload columns by\n * their column key, for the same reason a table does. `joinedAt` with\n * column `joined_at` has to be one name on both sides or a `_pivot` write\n * is silently dropped by drizzle and the read serves a key the caller never\n * declared.\n */\nexport function columnKeysFromTables(\n descriptors: readonly TableDescriptor[]\n): ColumnKeyResolver {\n const byTable = new Map<string, TableDescriptor>();\n const rawColumns = new Map<string, Set<string>>();\n for (const descriptor of descriptors) {\n const table = bareTableName(descriptor.table);\n byTable.set(table, descriptor);\n rawColumns.set(table, new Set(tableSearchColumnNames(descriptor)));\n }\n // The junctions' payload columns, as the pivot the planner emitted them\n // from, so the runtime table and the generated one cannot key them\n // differently.\n const junctionByTable = new Map<string, { keyColumns: Set<string>; pivot: Map<string, string> }>();\n for (const junction of resolveTableJunctions(descriptors).values()) {\n if (junction.pivot.length === 0) continue;\n junctionByTable.set(junction.table, {\n keyColumns: new Set(junction.endpoints.map(endpoint => endpoint.junctionColumn)),\n pivot: new Map(junction.pivot.map(column => [column.column, column.key]))\n });\n }\n return (tableName, columnName) => {\n const descriptor = byTable.get(tableName);\n if (!descriptor) {\n const junction = junctionByTable.get(tableName);\n if (!junction || junction.keyColumns.has(columnName)) return columnName;\n return junction.pivot.get(columnName) ?? toWireKey(columnName);\n }\n if (rawColumns.get(tableName)?.has(columnName)) return columnName;\n return keyForColumn(descriptor, columnName) ?? toWireKey(columnName);\n };\n}\n\nexport interface CatalogueSchema {\n /** Drizzle tables, keyed by bare table name. */\n tables: Record<string, PgTable>;\n /** Drizzle relations, keyed `<table>Relations`. */\n relations: Record<string, Relations>;\n /** Introspected metadata per table — what the boot diff compares against. */\n meta: Map<string, TableMeta>;\n /** Tables declared for this source that the database does not have. */\n missing: string[];\n}\n\n/**\n * Read the tables this data source serves out of `information_schema`.\n *\n * Restricted to the tables handed in, because the driver is given every table\n * the project declares while each database holds only its own: an unfiltered\n * read had a second source (`database(\"analytics\")`) reporting the default's\n * tables as its own. Junction tables come too — they back no declared table\n * and a many-to-many is unreadable without them.\n *\n * Every schema the tables name is read, not just `public`. The users table\n * lives in `rebase`, and a run restricted to `public` would leave the registry\n * with no table for it at all. A table that declares no schema is read from\n * `defaultSchema`.\n */\nexport async function readCatalogueSchema(options: {\n client: Queryable;\n /** This data source's tables, and the targets of their relations. */\n tables: readonly TableDescriptor[];\n defaultSchema: string;\n}): Promise<CatalogueSchema> {\n const { client, tables: descriptors, defaultSchema } = options;\n\n /** schema → the tables wanted from it. */\n const wanted = new Map<string, Set<string>>();\n const want = (schema: string, table: string) => {\n const set = wanted.get(schema) ?? new Set<string>();\n wanted.set(schema, set);\n set.add(table);\n };\n\n for (const descriptor of descriptors) {\n want(schemaOfTable(descriptor, defaultSchema), bareTableName(descriptor.table));\n }\n // Junctions are created in `public`, full stop — `resolveTableJunctions`\n // hardcodes it and the three generators agree with it.\n for (const junction of resolveTableJunctions(descriptors).values()) {\n want(junction.schema, junction.table);\n }\n\n const columnKey = columnKeysFromTables(descriptors);\n const tables: Record<string, PgTable> = {};\n const meta = new Map<string, TableMeta>();\n const missing: string[] = [];\n\n for (const [schema, names] of wanted) {\n // Views too: a `defineView` reads one.\n const live = await introspectSchema(client, schema, { views: true });\n const present = new Map<string, TableMeta>();\n for (const name of names) {\n const found = live.tablesMap.get(name);\n if (!found) {\n missing.push(schema === defaultSchema ? name : `${schema}.${name}`);\n continue;\n }\n // First schema to carry a name wins. Two schemas holding a table of\n // the same name is the `search_path` hazard the drift report\n // explains; the registry is keyed by bare name either way, so this\n // only picks which one is served — the one whose table asked.\n if (tables[name]) continue;\n present.set(name, found);\n meta.set(name, found);\n }\n Object.assign(tables, buildDrizzleTablesFromSchema(present, schema, columnKey));\n }\n\n return {\n tables,\n relations: buildDrizzleRelationsFromTables(descriptors, tables),\n meta,\n missing\n };\n}\n\n/**\n * The BaaS variant: no tables are declared, so every table in one schema is\n * served, described from the catalogue (`descriptors`), and the relations are\n * derived from the foreign keys.\n *\n * Kept apart from {@link readCatalogueSchema} because the two answer different\n * questions. Here the database is the entire specification; there it supplies\n * the columns for a specification the project already wrote down.\n */\nexport function buildBaasSchema(\n tablesMap: Map<string, TableMeta>,\n pgSchemaName: string,\n descriptors: readonly TableDescriptor[]\n): { tables: Record<string, PgTable>; relations: Record<string, Relations> } {\n const columnKey = columnKeysFromTables(descriptors);\n const tables = buildDrizzleTablesFromSchema(tablesMap, pgSchemaName, columnKey);\n return {\n tables,\n relations: buildDrizzleRelationsFromSchema(tablesMap, tables, columnKey)\n };\n}\n","/**\n * Compare the committed `schema.generated.ts` against the live catalogue, and\n * say so — once per difference, at boot, as a warning and nothing more.\n *\n * The runtime stopped reading that file for its tables (see\n * `catalogue-schema.ts`), which removes an entire class of production failure\n * and creates a smaller one: a stale file is now *invisible*. It is still real —\n * it is what Atlas plans migrations from, what `db push` diffs, what `eject`\n * writes out and what user code imports — so a project whose file no longer\n * describes its database will hit it later, in a tool, with no clue that boot\n * already knew.\n *\n * Hence this: a guard rather than a doc. It never fails boot and never changes\n * what is served — the previous arrangement, where the file could do both,\n * is exactly what was removed.\n *\n * `generated-schema-staleness.ts` answers a narrower question (does the file\n * name every declared table) from the file's *source text*. This one\n * compares the loaded module against the database, column by column.\n */\nimport { getTableColumns, getTableName as drizzleTableName, isTable } from \"drizzle-orm\";\nimport type { PgTable } from \"drizzle-orm/pg-core\";\nimport type { TableDescriptor } from \"@rebasepro/types\";\nimport { logger } from \"@rebasepro/server\";\n\nimport { AUTH_USERS_COLUMNS } from \"./auth-users-columns\";\nimport type { TableMeta } from \"./introspect-db-logic\";\nimport { bareTableName } from \"./config-relations\";\nimport { readCatalogueSchema } from \"./catalogue-schema\";\nimport type { Queryable } from \"./introspect-runtime\";\nimport { servedKeyOf } from \"./relation-names\";\n\nexport type SchemaDifferenceKind =\n | \"missing-table\"\n | \"missing-column\"\n | \"extra-column\"\n | \"type\"\n | \"nullability\";\n\nexport interface SchemaDifference {\n kind: SchemaDifferenceKind;\n /** Bare table name, as both sides spell it. */\n table: string;\n /** The slug of the declared table backed by that table, when one is. */\n slug?: string;\n /** The column, in database terms. */\n column?: string;\n /** The key it is served under, where the table declares it. */\n key?: string;\n /** What `schema.generated.ts` says. */\n generated?: string;\n /** What the database says. */\n live?: string;\n}\n\n/**\n * The families a boot warning is worth raising over.\n *\n * Deliberately coarse. `varchar(120)` and `text` are the same family because the\n * runtime treats them identically and a warning about the difference would fire\n * on every boot of a correct project — the widths still reach Postgres, which\n * enforces them. What this is looking for is the kind of drift that changes what\n * a value *is*: a number that became text, a timestamp that became a date, a\n * column that stopped existing.\n */\nexport function typeFamily(sqlType: string | undefined): string {\n if (!sqlType) return \"unknown\";\n let type = sqlType.trim().toLowerCase();\n const isArray = type.endsWith(\"[]\") || type.startsWith(\"_\");\n type = type.replace(/\\[\\]$/, \"\").replace(/^_/, \"\");\n // Strip the modifier: varchar(255), numeric(10,2), vector(1536), char(2).\n type = type.replace(/\\s*\\([^)]*\\)\\s*$/, \"\").trim();\n\n const family = FAMILIES[type] ?? type;\n return isArray ? `${family}[]` : family;\n}\n\nconst FAMILIES: Record<string, string> = {\n // strings\n text: \"text\",\n varchar: \"text\",\n \"character varying\": \"text\",\n bpchar: \"text\",\n char: \"text\",\n character: \"text\",\n citext: \"text\",\n name: \"text\",\n // integers\n int2: \"integer\",\n smallint: \"integer\",\n smallserial: \"integer\",\n int4: \"integer\",\n int: \"integer\",\n integer: \"integer\",\n serial: \"integer\",\n int8: \"bigint\",\n bigint: \"bigint\",\n bigserial: \"bigint\",\n // approximate and exact numerics: kept apart, because one rounds\n float4: \"float\",\n real: \"float\",\n float8: \"float\",\n \"double precision\": \"float\",\n numeric: \"numeric\",\n decimal: \"numeric\",\n money: \"numeric\",\n // the rest\n bool: \"boolean\",\n boolean: \"boolean\",\n uuid: \"uuid\",\n json: \"json\",\n jsonb: \"jsonb\",\n date: \"date\",\n time: \"time\",\n \"time without time zone\": \"time\",\n timetz: \"time\",\n \"time with time zone\": \"time\",\n timestamp: \"timestamp\",\n \"timestamp without time zone\": \"timestamp\",\n timestamptz: \"timestamptz\",\n \"timestamp with time zone\": \"timestamptz\",\n interval: \"interval\",\n bytea: \"bytea\",\n tsvector: \"tsvector\",\n tsquery: \"tsquery\",\n vector: \"vector\"\n};\n\n/** One catalogue column, reduced to the three facts this compares. */\ninterface CatalogueColumn {\n name: string;\n family: string;\n notNull: boolean;\n}\n\nfunction catalogueColumns(meta: TableMeta): Map<string, CatalogueColumn> {\n const columns = new Map<string, CatalogueColumn>();\n for (const col of meta.columns) {\n columns.set(col.column_name, {\n name: col.column_name,\n // `udt_name` over `data_type`: the latter reports \"ARRAY\" and\n // \"USER-DEFINED\" where the former is the concrete type, and an enum\n // has to compare by its own type name against the module's pgEnum.\n family: typeFamily(col.udt_name || col.data_type),\n notNull: col.is_nullable === \"NO\"\n });\n }\n return columns;\n}\n\n/**\n * Every way the generated module and the database disagree, for the tables both\n * describe.\n *\n * One-directional in one respect only: a table the module has and the database\n * does not is reported (that is the stale-file case), while a table the database\n * has and the module does not is left alone — a database may hold anything, and\n * the declared-tables-vs-file question is `generated-schema-staleness`'s.\n */\nexport function diffGeneratedSchemaAgainstCatalogue(options: {\n /** The `tables` export of the bundle's schema module. */\n generated: Record<string, unknown> | undefined;\n /** What was introspected for this data source, keyed by bare table name. */\n catalogue: Map<string, TableMeta>;\n /** The declared tables of this source, so a column can be named by its key. */\n tables: readonly TableDescriptor[];\n}): SchemaDifference[] {\n const { generated, catalogue, tables } = options;\n if (!generated) return [];\n\n const declaredByTable = new Map<string, TableDescriptor>();\n for (const descriptor of tables) declaredByTable.set(bareTableName(descriptor.table), descriptor);\n\n const differences: SchemaDifference[] = [];\n\n for (const value of Object.values(generated)) {\n if (!isTable(value)) continue;\n const table = drizzleTableName(value as PgTable);\n const declared = declaredByTable.get(table);\n const at = { table, slug: declared?.slug };\n\n const meta = catalogue.get(table);\n if (!meta) {\n // Only for a table this source declares: the module\n // carries every table of the project, including the ones another\n // data source holds, and those are legitimately absent here.\n if (declared) differences.push({ ...at, kind: \"missing-table\" });\n continue;\n }\n\n const live = catalogueColumns(meta);\n const seen = new Set<string>();\n\n // On the auth table, auth owns its own columns' contract and the\n // generated file deliberately does not carry it: `render-drizzle` drops\n // the columns an auth table does not declare (`is_anonymous`,\n // `tokens_valid_after`) because drizzle-kit creates no auth table, and\n // the table's own column definitions say nothing about the\n // `NOT NULL DEFAULT` that `ensureAuthTablesExist` applies.\n //\n // Comparing them anyway reported seven differences on a project nobody\n // had touched yet, and prescribed `rebase schema generate` — which\n // regenerates the file from the same table and cannot change any\n // of them. A warning that survives its own remedy teaches the reader to\n // ignore the next one, so these are not differences. A *type* mismatch\n // still is: that is the file and the database disagreeing about\n // something neither side intends.\n const authOwned = declared?.auth\n ? new Set(AUTH_USERS_COLUMNS.map(c => c.column))\n : undefined;\n\n for (const [key, column] of Object.entries(getTableColumns(value as PgTable))) {\n const name = (column as { name?: string }).name ?? key;\n seen.add(name);\n const columnKey = declared ? servedKeyOf(declared, name) : key;\n const generatedFamily = typeFamily((column as { getSQLType?: () => string }).getSQLType?.());\n const generatedNotNull = Boolean((column as { notNull?: boolean }).notNull);\n\n const found = live.get(name);\n if (!found) {\n differences.push({ ...at, kind: \"missing-column\", column: name, key: columnKey, generated: generatedFamily });\n continue;\n }\n if (found.family !== generatedFamily) {\n differences.push({\n ...at,\n kind: \"type\",\n column: name,\n key: columnKey,\n generated: generatedFamily,\n live: found.family\n });\n }\n if (found.notNull !== generatedNotNull && !authOwned?.has(name)) {\n differences.push({\n ...at,\n kind: \"nullability\",\n column: name,\n key: columnKey,\n generated: generatedNotNull ? \"NOT NULL\" : \"nullable\",\n live: found.notNull ? \"NOT NULL\" : \"nullable\"\n });\n }\n }\n\n for (const [name, column] of live) {\n if (seen.has(name)) continue;\n if (authOwned?.has(name)) continue;\n differences.push({\n ...at,\n kind: \"extra-column\",\n column: name,\n key: declared ? servedKeyOf(declared, name) : name,\n live: column.family\n });\n }\n }\n\n return differences;\n}\n\n/**\n * Boot's drift question, asked of a database from outside a boot.\n *\n * The same two calls boot makes before it warns, with the arguments it makes\n * them with: the catalogue read the way the registry reads it\n * ({@link readCatalogueSchema}), then {@link diffGeneratedSchemaAgainstCatalogue}\n * over its metadata. `rebase doctor` asks through here, because the boot\n * warning sends the reader to the doctor for \"the full report\" — and while the\n * doctor compared on its own terms, it answered \"In sync\" over a NOT NULL and a\n * left-behind column that boot had just warned about.\n *\n * `tables` are the data source's own, as boot filters them.\n */\nexport async function readGeneratedSchemaDrift(options: {\n client: Queryable;\n /** The `tables` export of `schema.generated.ts`. */\n generated: Record<string, unknown> | undefined;\n tables: readonly TableDescriptor[];\n defaultSchema: string;\n}): Promise<SchemaDifference[]> {\n const { client, generated, tables, defaultSchema } = options;\n if (!generated || tables.length === 0) return [];\n const catalogue = await readCatalogueSchema({ client, tables, defaultSchema });\n return diffGeneratedSchemaAgainstCatalogue({ generated, catalogue: catalogue.meta, tables });\n}\n\n/** One line, in the terms the reader has: table slug, column key, column. */\nexport function describeSchemaDifference(difference: SchemaDifference): string {\n const where = difference.slug\n ? `${difference.slug} (table \"${difference.table}\")`\n : `table \"${difference.table}\"`;\n const field = difference.column\n ? `${difference.key && difference.key !== difference.column\n ? `${difference.key} → \"${difference.column}\"`\n : `\"${difference.column}\"`}`\n : undefined;\n\n switch (difference.kind) {\n case \"missing-table\":\n return `${where} is in schema.generated.ts but not in the database`;\n case \"missing-column\":\n return `${where}: ${field} is in schema.generated.ts but not in the database`;\n case \"extra-column\":\n return `${where}: ${field} is in the database but not in schema.generated.ts (${difference.live})`;\n case \"type\":\n return `${where}: ${field} is ${difference.generated} in schema.generated.ts and ${difference.live} in the database`;\n case \"nullability\":\n return `${where}: ${field} is ${difference.generated} in schema.generated.ts and ${difference.live} in the database`;\n }\n}\n\n/**\n * The `rebase schema reconcile` line for a difference it can apply: a column\n * the database requires and the table made nullable, or one the table no\n * longer declares. Undefined for the rest.\n */\nexport function reconcileFix(difference: SchemaDifference): string | undefined {\n if (difference.kind === \"nullability\" && difference.live === \"NOT NULL\") return \"rebase schema reconcile\";\n if (difference.kind === \"extra-column\" && difference.slug) {\n return `rebase schema reconcile --drop ${difference.slug}.${difference.column}`;\n }\n return undefined;\n}\n\n/**\n * Report the differences, one warning each, and never throw.\n *\n * Per difference rather than one summary block on purpose: these are read out of\n * a log aggregator as often as a terminal, and a single multi-line message\n * cannot be filtered down to the one table somebody is looking at.\n *\n * The fix it names is `rebase db push`. `rebase dev` rewrites\n * schema.generated.ts from the tables on every change, and boot applies\n * only additive changes, so what is still different at boot is the database\n * behind the file: a rename, a dropped column, a narrowed type, a NOT NULL.\n * `rebase schema generate` rewrites the file and leaves the database as it is,\n * so it is named only for tables that changed since the file was written.\n */\nexport function warnOnGeneratedSchemaDrift(differences: SchemaDifference[]): void {\n if (differences.length === 0) return;\n\n logger.warn(\n `📄 [schema] schema.generated.ts and the database disagree (${differences.length} difference` +\n `${differences.length === 1 ? \"\" : \"s\"}). Boot applies only additive changes; these are the ones it ` +\n \"left for you. Run `rebase db push` to apply them (it shows the plan and asks before anything \" +\n \"destructive), or `rebase db generate` for a migration. A NOT NULL to relax or a column to drop \" +\n \"can also be applied through the running backend, Rebase Cloud included: `rebase schema reconcile`. \" +\n \"If backend/schema changed since schema.generated.ts was written, run `rebase schema generate` first.\"\n );\n\n for (const difference of differences) {\n logger.warn(` • ${describeSchemaDifference(difference)}`, {\n schemaDrift: {\n kind: difference.kind,\n table: difference.table,\n slug: difference.slug,\n column: difference.column,\n key: difference.key,\n generated: difference.generated,\n live: difference.live\n },\n fix: reconcileFix(difference) ?? \"rebase db push\"\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2CA,eAAsB,iBAClB,QACA,UAOA,UAA+B,CAAC,GACL;CAC3B,MAAM,EAAE,MAAM,WAAW,MAAM,OAAO,MAClC;;kDAE0C,QAAQ,QAAQ,8BAA8B,iBAAiB;;;WAGtG,QAAQ,QAAQ;;;iGAGsE,GAAG;+BAE5F,CAAC,QAAQ,CACb;CAEA,MAAM,EAAE,MAAM,YAAY,MAAM,OAAO,MACnC;;;;;;;;;;;;;;;;;;;;;;;;;;WA0BG,QAAQ,QAAQ;;;;;;;;;;;;iGAYsE,MACzF,CAAC,QAAQ,CACb;CAEA,MAAM,EAAE,MAAM,eAAe,MAAM,OAAO,MACtC;;;;;;;+CAQA,CAAC,QAAQ,CACb;CAEA,MAAM,EAAE,MAAM,QAAQ,MAAM,OAAO,MAC/B;;;;;;oDAOA,CAAC,QAAQ,CACb;CAEA,MAAM,EAAE,MAAM,QAAQ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AC/C,GAAG,WAAW,IAAI,MAAM,WAAW,OAAO,KAC1C,IAAI,WAAW,OAAO,OAC1B,KAAA;CAEN,QAAQ,WAAW,MAAnB;EACI,KAAK,iBACD,OAAO,GAAG,MAAM;EACpB,KAAK,kBACD,OAAO,GAAG,MAAM,IAAI,MAAM;EAC9B,KAAK,gBACD,OAAO,GAAG,MAAM,IAAI,MAAM,sDAAsD,WAAW,KAAK;EACpG,KAAK,QACD,OAAO,GAAG,MAAM,IAAI,MAAM,MAAM,WAAW,UAAU,8BAA8B,WAAW,KAAK;EACvG,KAAK,eACD,OAAO,GAAG,MAAM,IAAI,MAAM,MAAM,WAAW,UAAU,8BAA8B,WAAW,KAAK;CAC3G;AACJ;;;;;;AAOA,SAAgB,aAAa,YAAkD;CAC3E,IAAI,WAAW,SAAS,iBAAiB,WAAW,SAAS,YAAY,OAAO;CAChF,IAAI,WAAW,SAAS,kBAAkB,WAAW,MACjD,OAAO,kCAAkC,WAAW,KAAK,GAAG,WAAW;AAG/E;;;;;;;;;;;;;;;AAgBA,SAAgB,2BAA2B,aAAuC;CAC9E,IAAI,YAAY,WAAW,GAAG;CAE9B,OAAO,KACH,8DAA8D,YAAY,OAAO,aAC9E,YAAY,WAAW,IAAI,KAAK,IAAI,ycAK3C;CAEA,KAAK,MAAM,cAAc,aACrB,OAAO,KAAK,QAAQ,yBAAyB,UAAU,KAAK;EACxD,aAAa;GACT,MAAM,WAAW;GACjB,OAAO,WAAW;GAClB,MAAM,WAAW;GACjB,QAAQ,WAAW;GACnB,KAAK,WAAW;GAChB,WAAW,WAAW;GACtB,MAAM,WAAW;EACrB;EACA,KAAK,aAAa,UAAU,KAAK;CACrC,CAAC;AAET"}
|
package/dist/index.es.js
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
3
|
import { a as createPostgresDatabaseConnection, c as guardPoolAgainstDirtyRelease, d as poolMaxCeiling, i as createDirectDatabaseConnection, o as createReadReplicaConnection, s as defaultPoolTimeouts, t as cappedPoolMax, u as pinSearchPath } from "./connection-C1zXTPJq.js";
|
|
4
|
-
import { $ as PostgresBackendDriver, B as passwordResetTokens, C as PostgresChannelBus, D as frameByteLength, E as MemoryChannelBus, F as magicLinkTokensRelations, G as refreshTokensRelations, H as recoveryCodes, I as mfaChallenges, J as users, K as userIdentities, L as mfaChallengesRelations, M as appConfig, N as createAuthSchema, O as isChannelBusInstance, P as magicLinkTokens, Q as CONNECTION_OWNER, R as mfaFactors, S as PG_NOTIFY_MAX_PAYLOAD_BYTES, T as parseChannelBusPayload, U as recoveryCodesRelations, V as passwordResetTokensRelations, W as refreshTokens, X as usersSchema, Y as usersRelations, Z as AuthenticatedPostgresBackendDriver, _ as refetchConcurrencyFor, a as openPostgresDriver, b as CHANNEL_BUS_NOTIFY_CHANNEL, c as PostgresTableRegistry, d as PostgresRealtimeProvider, dt as PostgresConditionBuilder, et as RoleSwitchUnavailableError, f as RealtimeService, ft as configureUnknownFilterFields, g as parseRealtimeTuning, gt as listedColumnKeys, h as parseMaxSubscriptionsPerSocket, ht as joinColumn, i as isScaffoldedLocalDatabase, it as sqlRoleRanAs, l as DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET, m as parseMaxSocketsPerUser, mt as getUnknownFilterFieldsMode, n as createPostgresBootstrapper, nt as effectiveSqlRole, o as postgresDriverConfigFromEnv, p as packEntityChanges, pt as escapeLikePattern, q as userIdentitiesRelations, r as describeSchemaDriftCause, rt as isRoleSwitchingOptedOut, s as resolveSourceUrls, t as openRebase, tt as branchParentDatabase, u as DEFAULT_RECOUNT_MIN_ROWS, ut as DrizzleConditionBuilder, v as createChannelBus, w as parseChannelBusFrame, x as DEFAULT_BATCH_WINDOW_MS, y as resolveChannelBusSetting, z as mfaFactorsRelations } from "./open-rebase-
|
|
5
|
-
import { n as assertNoCollectionsFlag } from "./cli-schema-dir-
|
|
6
|
-
import { a as reopenedDatabasesNotice, i as reopenClosedDatabases, r as BranchingUnsupportedError, t as BranchService } from "./BranchService-
|
|
4
|
+
import { $ as PostgresBackendDriver, B as passwordResetTokens, C as PostgresChannelBus, D as frameByteLength, E as MemoryChannelBus, F as magicLinkTokensRelations, G as refreshTokensRelations, H as recoveryCodes, I as mfaChallenges, J as users, K as userIdentities, L as mfaChallengesRelations, M as appConfig, N as createAuthSchema, O as isChannelBusInstance, P as magicLinkTokens, Q as CONNECTION_OWNER, R as mfaFactors, S as PG_NOTIFY_MAX_PAYLOAD_BYTES, T as parseChannelBusPayload, U as recoveryCodesRelations, V as passwordResetTokensRelations, W as refreshTokens, X as usersSchema, Y as usersRelations, Z as AuthenticatedPostgresBackendDriver, _ as refetchConcurrencyFor, a as openPostgresDriver, b as CHANNEL_BUS_NOTIFY_CHANNEL, c as PostgresTableRegistry, d as PostgresRealtimeProvider, dt as PostgresConditionBuilder, et as RoleSwitchUnavailableError, f as RealtimeService, ft as configureUnknownFilterFields, g as parseRealtimeTuning, gt as listedColumnKeys, h as parseMaxSubscriptionsPerSocket, ht as joinColumn, i as isScaffoldedLocalDatabase, it as sqlRoleRanAs, l as DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET, m as parseMaxSocketsPerUser, mt as getUnknownFilterFieldsMode, n as createPostgresBootstrapper, nt as effectiveSqlRole, o as postgresDriverConfigFromEnv, p as packEntityChanges, pt as escapeLikePattern, q as userIdentitiesRelations, r as describeSchemaDriftCause, rt as isRoleSwitchingOptedOut, s as resolveSourceUrls, t as openRebase, tt as branchParentDatabase, u as DEFAULT_RECOUNT_MIN_ROWS, ut as DrizzleConditionBuilder, v as createChannelBus, w as parseChannelBusFrame, x as DEFAULT_BATCH_WINDOW_MS, y as resolveChannelBusSetting, z as mfaFactorsRelations } from "./open-rebase-DykxNl1j.js";
|
|
5
|
+
import { n as assertNoCollectionsFlag } from "./cli-schema-dir-CdEqBcph.js";
|
|
6
|
+
import { a as reopenedDatabasesNotice, i as reopenClosedDatabases, r as BranchingUnsupportedError, t as BranchService } from "./BranchService-BLcVK_Rd.js";
|
|
7
7
|
import { n as resolveRlsSettings, r as rlsConfigFromEnv, t as cliRlsSettings } from "./rls-settings-CmGK2U0a.js";
|
|
8
|
-
import { _ as recordRequestRoles, c as ensureAppRole, f as findOtherRoleMembers, g as readRecordedRequestRoles, l as ensureAppRoleGrants, s as detectConnectionPosture, t as REBASE_USER_ROLE } from "./rls-enforcement-
|
|
8
|
+
import { _ as recordRequestRoles, c as ensureAppRole, f as findOtherRoleMembers, g as readRecordedRequestRoles, l as ensureAppRoleGrants, s as detectConnectionPosture, t as REBASE_USER_ROLE } from "./rls-enforcement-NZKe3Jr-.js";
|
|
9
9
|
import { n as planSchema } from "./plan-schema-Hbtjhge3.js";
|
|
10
10
|
import { t as generateSchema } from "./generate-drizzle-schema-logic-DL7R1rAF.js";
|
|
11
11
|
import { a as generatePostgresVectorDdl, c as planJunctionTables, d as planTablePolicies, f as searchExcludePatterns, i as generatePostgresTriggersDdl, l as planPolicyDefinitions, m as vectorExcludePatterns, n as generatePostgresPoliciesDdl, o as generatePostgresViewsDdl, p as triggerExcludePatterns, r as generatePostgresSearchDdl, t as generatePostgresDdl, u as planRelationalColumns } from "./generate-postgres-ddl-logic-CQof4iFH.js";
|
|
12
|
-
import { a as migrationVersionOf, c as isDriverDbSubcommand, g as assertKnownFlags, l as backupActionOf, n as compareMigrationVersions, u as assertKnownBranchFlags } from "./migrate-baseline-
|
|
13
|
-
import { r as planTableSchemaEnsure } from "./ensure-tables-
|
|
12
|
+
import { a as migrationVersionOf, c as isDriverDbSubcommand, g as assertKnownFlags, l as backupActionOf, n as compareMigrationVersions, u as assertKnownBranchFlags } from "./migrate-baseline-CnIbBRgh.js";
|
|
13
|
+
import { r as planTableSchemaEnsure } from "./ensure-tables-DjuNRClr.js";
|
|
14
14
|
import { a as mergeDatabaseBranch, i as diffDatabaseBranch, n as DEFAULT_BRANCH_DIFF_SAMPLE_LIMIT, t as DEFAULT_BRANCH_DIFF_MAX_ROWS } from "./branch-diff-CxE4VlxT.js";
|
|
15
15
|
import { t as DatabasePoolManager } from "./databasePoolManager-DIjzlTK4.js";
|
|
16
16
|
import { t as main } from "./generate-drizzle-schema-B-Mkf8UI.js";
|
|
17
|
-
import { a as createPostgresWebSocket, i as TOO_MANY_SOCKETS_CLOSE_CODE, n as PUBLIC_TYPES, o as isSocketRealtimeService, r as SESSION_ENDED_CLOSE_CODE, s as socketRealtimeMissing, t as ADMIN_PLANE_TYPES } from "./websocket-
|
|
18
|
-
import { A as buildBackupFilename, B as diagnoseRowSecurityDumpFailure, C as restoreDumpReplacing, D as resolvePgBinary, E as pgToolVariable, F as buildPgRestoreScriptArgs, G as parseBackupTimestamp, H as isBackupOfDatabase, I as buildPsqlScriptArgs, J as parsePgToolMajor, K as parseDbNameFromUrl, L as buildRowSecurityPgOptions, M as buildPgDumpallGlobalsArgs, N as buildPgRestoreArgs, O as selectBackupsToPrune, P as buildPgRestoreListArgs, Q as withDatabaseName, R as checkToolServerCompatibility, S as restoreDump, T as validateDump, U as joinStorageKey, V as globalsFileForDump, W as parseBackupDestination, X as serverVersionNumToMajor, Y as resolveConnectionString, Z as splitGlobalsStatements, _ as listBackups, a as BackupToolError, b as readDumpObjects, d as detectToolMajor, f as discardPartialDump, g as getServerVersionMajor, h as findRestoreConflicts, i as parseRestoreLine, j as buildPgDumpArgs, k as CLEAN_LOCK_TIMEOUT, l as createDump, m as findCleanExtras, n as parseBackupLine, o as CleanRestoreFailed, p as ensureDatabaseExists, q as parseDumpObjects, r as parseBackupsListLine, s as applyGlobals, u as describeUnreadableDump, v as preflight, w as uploadBackup, x as resetSharedSession, y as pruneBackups, z as cleanRestorePrelude } from "./backup-cli-
|
|
19
|
-
import { n as parseRequestRoleLine, t as parseProvisionLine } from "./request-role-cli-
|
|
20
|
-
import { a as isGeneratedPolicyName } from "./policy-drift-
|
|
17
|
+
import { a as createPostgresWebSocket, i as TOO_MANY_SOCKETS_CLOSE_CODE, n as PUBLIC_TYPES, o as isSocketRealtimeService, r as SESSION_ENDED_CLOSE_CODE, s as socketRealtimeMissing, t as ADMIN_PLANE_TYPES } from "./websocket-CvmbzBeS.js";
|
|
18
|
+
import { A as buildBackupFilename, B as diagnoseRowSecurityDumpFailure, C as restoreDumpReplacing, D as resolvePgBinary, E as pgToolVariable, F as buildPgRestoreScriptArgs, G as parseBackupTimestamp, H as isBackupOfDatabase, I as buildPsqlScriptArgs, J as parsePgToolMajor, K as parseDbNameFromUrl, L as buildRowSecurityPgOptions, M as buildPgDumpallGlobalsArgs, N as buildPgRestoreArgs, O as selectBackupsToPrune, P as buildPgRestoreListArgs, Q as withDatabaseName, R as checkToolServerCompatibility, S as restoreDump, T as validateDump, U as joinStorageKey, V as globalsFileForDump, W as parseBackupDestination, X as serverVersionNumToMajor, Y as resolveConnectionString, Z as splitGlobalsStatements, _ as listBackups, a as BackupToolError, b as readDumpObjects, d as detectToolMajor, f as discardPartialDump, g as getServerVersionMajor, h as findRestoreConflicts, i as parseRestoreLine, j as buildPgDumpArgs, k as CLEAN_LOCK_TIMEOUT, l as createDump, m as findCleanExtras, n as parseBackupLine, o as CleanRestoreFailed, p as ensureDatabaseExists, q as parseDumpObjects, r as parseBackupsListLine, s as applyGlobals, u as describeUnreadableDump, v as preflight, w as uploadBackup, x as resetSharedSession, y as pruneBackups, z as cleanRestorePrelude } from "./backup-cli-CVLOCTo_.js";
|
|
19
|
+
import { n as parseRequestRoleLine, t as parseProvisionLine } from "./request-role-cli-Y5Uqalop.js";
|
|
20
|
+
import { a as isGeneratedPolicyName } from "./policy-drift-B2Czzs2Z.js";
|
|
21
21
|
import { logger } from "@rebasepro/server";
|
|
22
22
|
import { resetDeclaredResources } from "@rebasepro/types";
|
|
23
23
|
import { sortTablesBySlug } from "@rebasepro/common";
|
|
@@ -106,7 +106,7 @@ function createBackupCron(config) {
|
|
|
106
106
|
enabled: config.enabled ?? true,
|
|
107
107
|
timeoutSeconds: 3600,
|
|
108
108
|
async handler({ log }) {
|
|
109
|
-
const { createDump, discardPartialDump, pruneBackups, uploadBackup, validateDump } = await import("./backup-cli-
|
|
109
|
+
const { createDump, discardPartialDump, pruneBackups, uploadBackup, validateDump } = await import("./backup-cli-CVLOCTo_.js").then((n) => n.c);
|
|
110
110
|
const { destination } = config;
|
|
111
111
|
if (destination.kind !== "local" && !config.storage) throw new Error(`Backup destination is ${destination.kind} but no storage controller was provided. Pass the backend's configured StorageController to createBackupCron({ storage }).`);
|
|
112
112
|
log(`Starting backup of "${dbName}"…`);
|