@rebasepro/server-postgres 0.25.1 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +1 -1
  2. package/dist/{BranchService-ClklxyAQ.js → BranchService-B9Lu8e-P.js} +25 -9
  3. package/dist/BranchService-B9Lu8e-P.js.map +1 -0
  4. package/dist/PostgresBackendDriver.d.ts +20 -0
  5. package/dist/PostgresBootstrapper.d.ts +7 -0
  6. package/dist/auth/services.d.ts +23 -2
  7. package/dist/auth/verify-auth-tables.d.ts +21 -0
  8. package/dist/{backup-cli-gijeXe0u.js → backup-cli-BZM2Fj1I.js} +4 -4
  9. package/dist/backup-cli-BZM2Fj1I.js.map +1 -0
  10. package/dist/{boot-ddl-DYH95Qeg.js → boot-ddl-yukSebLA.js} +2 -2
  11. package/dist/{boot-ddl-DYH95Qeg.js.map → boot-ddl-yukSebLA.js.map} +1 -1
  12. package/dist/branch-diff-CxE4VlxT.js +1396 -0
  13. package/dist/branch-diff-CxE4VlxT.js.map +1 -0
  14. package/dist/branch-diff-report-DpvVf7hR.js +48 -0
  15. package/dist/branch-diff-report-DpvVf7hR.js.map +1 -0
  16. package/dist/branching/branch-diff-report.d.ts +7 -0
  17. package/dist/branching/branch-diff.d.ts +115 -0
  18. package/dist/{cli-console-CQrQ0lAY.js → cli-console-BtzxzzvU.js} +38 -5
  19. package/dist/cli-console-BtzxzzvU.js.map +1 -0
  20. package/dist/cli-console.d.ts +17 -1
  21. package/dist/{cli-errors-DiA0XFIS.js → cli-errors-BBSJqlYX.js} +58 -7
  22. package/dist/cli-errors-BBSJqlYX.js.map +1 -0
  23. package/dist/cli.js +107 -127
  24. package/dist/cli.js.map +1 -1
  25. package/dist/{collections-schema-version-T6cGvrDi.js → collections-schema-version-D7bDI0PJ.js} +13 -9
  26. package/dist/collections-schema-version-D7bDI0PJ.js.map +1 -0
  27. package/dist/{column-plan-helpers-IG6uFb1s.js → column-plan-helpers-BeSztMor.js} +5 -1
  28. package/dist/{column-plan-helpers-IG6uFb1s.js.map → column-plan-helpers-BeSztMor.js.map} +1 -1
  29. package/dist/{deferred-index-build-BE0I6sYU.js → deferred-index-build-DRnoMq-O.js} +5 -5
  30. package/dist/{deferred-index-build-BE0I6sYU.js.map → deferred-index-build-DRnoMq-O.js.map} +1 -1
  31. package/dist/{doctor-BT--1kq3.js → doctor-Cs6AtizY.js} +85 -37
  32. package/dist/doctor-Cs6AtizY.js.map +1 -0
  33. package/dist/{ensure-collection-policies-BnGOURpG.js → ensure-collection-policies-H8HN1Gbd.js} +8 -8
  34. package/dist/{ensure-collection-policies-BnGOURpG.js.map → ensure-collection-policies-H8HN1Gbd.js.map} +1 -1
  35. package/dist/{ensure-collection-tables-Cet4650m.js → ensure-collection-tables-BeF1lArf.js} +7 -7
  36. package/dist/{ensure-collection-tables-Cet4650m.js.map → ensure-collection-tables-BeF1lArf.js.map} +1 -1
  37. package/dist/{ensure-tables-l_OgFQjN.js → ensure-tables-DDkNaPN2.js} +4 -4
  38. package/dist/{ensure-tables-l_OgFQjN.js.map → ensure-tables-DDkNaPN2.js.map} +1 -1
  39. package/dist/{enum-labels-kept-nheku1pB.js → enum-labels-kept-B6loB2U_.js} +3 -3
  40. package/dist/{enum-labels-kept-nheku1pB.js.map → enum-labels-kept-B6loB2U_.js.map} +1 -1
  41. package/dist/{generate-drizzle-schema-DC0BOUpn.js → generate-drizzle-schema-D_O8_iyT.js} +2 -2
  42. package/dist/{generate-drizzle-schema-DC0BOUpn.js.map → generate-drizzle-schema-D_O8_iyT.js.map} +1 -1
  43. package/dist/{generate-drizzle-schema-logic-CPzCRD-8.js → generate-drizzle-schema-logic-D0E64iwx.js} +2 -2
  44. package/dist/{generate-drizzle-schema-logic-CPzCRD-8.js.map → generate-drizzle-schema-logic-D0E64iwx.js.map} +1 -1
  45. package/dist/{generate-files-BP-4W_gm.js → generate-files-BpgyRwhU.js} +3 -3
  46. package/dist/{generate-files-BP-4W_gm.js.map → generate-files-BpgyRwhU.js.map} +1 -1
  47. package/dist/{generate-postgres-ddl-logic-DPl1oH_z.js → generate-postgres-ddl-logic-CogQBrzs.js} +3 -3
  48. package/dist/{generate-postgres-ddl-logic-DPl1oH_z.js.map → generate-postgres-ddl-logic-CogQBrzs.js.map} +1 -1
  49. package/dist/{generated-schema-diff-eZCklRZQ.js → generated-schema-diff-X9NA2Vig.js} +2 -2
  50. package/dist/{generated-schema-diff-eZCklRZQ.js.map → generated-schema-diff-X9NA2Vig.js.map} +1 -1
  51. package/dist/history/HistoryService.d.ts +7 -0
  52. package/dist/index.d.ts +20 -0
  53. package/dist/index.es.js +228 -10
  54. package/dist/index.es.js.map +1 -1
  55. package/dist/{db-subcommands-BPoHCxJR.js → migrate-baseline-Bfk1LGC6.js} +266 -41
  56. package/dist/migrate-baseline-Bfk1LGC6.js.map +1 -0
  57. package/dist/{migrate-policy-stamps-3eqfhes6.js → migrate-policy-stamps-DHxwcawC.js} +6 -6
  58. package/dist/{migrate-policy-stamps-3eqfhes6.js.map → migrate-policy-stamps-DHxwcawC.js.map} +1 -1
  59. package/dist/{open-rebase-EmqVmS14.js → open-rebase-DZ5JbZpg.js} +546 -52
  60. package/dist/open-rebase-DZ5JbZpg.js.map +1 -0
  61. package/dist/open-rebase.d.ts +9 -1
  62. package/dist/{pg-error-utils-CFEnm2m9.js → pg-error-utils-BueZEJ0S.js} +2 -2
  63. package/dist/{pg-error-utils-CFEnm2m9.js.map → pg-error-utils-BueZEJ0S.js.map} +1 -1
  64. package/dist/{plan-schema-Czf3q4-Q.js → plan-schema-YagMlmNE.js} +2 -2
  65. package/dist/{plan-schema-Czf3q4-Q.js.map → plan-schema-YagMlmNE.js.map} +1 -1
  66. package/dist/{policy-drift-X4A-xAzv.js → policy-drift-Dqp_yFeE.js} +2 -2
  67. package/dist/{policy-drift-X4A-xAzv.js.map → policy-drift-Dqp_yFeE.js.map} +1 -1
  68. package/dist/{push-index-prebuild-COd7i6wm.js → push-index-prebuild-hVRrfTi-.js} +4 -4
  69. package/dist/{push-index-prebuild-COd7i6wm.js.map → push-index-prebuild-hVRrfTi-.js.map} +1 -1
  70. package/dist/push-kept-defaults-M_ZCcXuy.js +137 -0
  71. package/dist/push-kept-defaults-M_ZCcXuy.js.map +1 -0
  72. package/dist/{push-legacy-renames-CLgYYwPE.js → push-legacy-renames-DcoAWmGt.js} +4 -4
  73. package/dist/{push-legacy-renames-CLgYYwPE.js.map → push-legacy-renames-DcoAWmGt.js.map} +1 -1
  74. package/dist/{push-policy-plan-D2gpQsdv.js → push-policy-plan-Bq1bcb3Y.js} +4 -4
  75. package/dist/{push-policy-plan-D2gpQsdv.js.map → push-policy-plan-Bq1bcb3Y.js.map} +1 -1
  76. package/dist/{render-ddl-4v88y-Gv.js → render-ddl-D5jeXKR-.js} +2 -2
  77. package/dist/{render-ddl-4v88y-Gv.js.map → render-ddl-D5jeXKR-.js.map} +1 -1
  78. package/dist/{rls-enforcement-DDyNoOSy.js → rls-enforcement-BOHuHVlc.js} +42 -3
  79. package/dist/rls-enforcement-BOHuHVlc.js.map +1 -0
  80. package/dist/schema/destructive-sql.d.ts +16 -0
  81. package/dist/schema/doctor-cli.js +4 -4
  82. package/dist/schema/generate-drizzle-schema.js +1 -1
  83. package/dist/schema/generate-postgres-ddl.js +1 -1
  84. package/dist/schema/introspect-db.js +1 -1
  85. package/dist/schema/migration-freshness.d.ts +69 -0
  86. package/dist/schema/push-kept-defaults.d.ts +57 -0
  87. package/dist/schema/rls-bootstrap-sql.d.ts +47 -10
  88. package/dist/security/rls-enforcement.d.ts +18 -0
  89. package/dist/services/FetchService.d.ts +12 -0
  90. package/dist/services/channel-bus/PostgresChannelBus.d.ts +1 -0
  91. package/dist/services/channel-presence.d.ts +3 -1
  92. package/dist/services/nested-path.d.ts +16 -0
  93. package/dist/services/realtimeService.d.ts +48 -2
  94. package/dist/{websocket-BKZwsjmf.js → websocket-C9Fx7iSx.js} +70 -15
  95. package/dist/websocket-C9Fx7iSx.js.map +1 -0
  96. package/package.json +7 -7
  97. package/dist/BranchService-ClklxyAQ.js.map +0 -1
  98. package/dist/backup-cli-gijeXe0u.js.map +0 -1
  99. package/dist/cli-console-CQrQ0lAY.js.map +0 -1
  100. package/dist/cli-errors-DiA0XFIS.js.map +0 -1
  101. package/dist/collections-schema-version-T6cGvrDi.js.map +0 -1
  102. package/dist/db-subcommands-BPoHCxJR.js.map +0 -1
  103. package/dist/doctor-BT--1kq3.js.map +0 -1
  104. package/dist/open-rebase-EmqVmS14.js.map +0 -1
  105. package/dist/rls-enforcement-DDyNoOSy.js.map +0 -1
  106. package/dist/websocket-BKZwsjmf.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"generated-schema-diff-eZCklRZQ.js","names":[],"sources":["../src/schema/introspect-runtime.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 — builds collections in memory from the live database.\n *\n * This is what makes BaaS mode work with zero configuration: instead of loading\n * collection files from disk, the server reads `information_schema` at boot and\n * derives a collection per table, so any database is served over REST without a\n * single config file.\n *\n * Distinct from `introspect-db.ts`, which runs the same queries but emits\n * TypeScript *source* for a developer to edit and commit (declared collections). The two\n * share the mapping helpers in `introspect-db-logic.ts` so a table is described\n * the same way whether it was generated or introspected.\n */\nimport type { PostgresCollectionConfig } from \"@rebasepro/types\";\n\nimport {\n TableRow,\n TableColumn,\n EnumValue,\n PrimaryKeyRow,\n ForeignKeyRow,\n TableMeta,\n buildTablesMap,\n buildEnumMap,\n identifyJoinTables,\n singularize,\n mapPgType,\n getIconForTable\n} from \"./introspect-db-logic\";\nimport { humanize } from \"./introspect-db-naming\";\nimport { firstFreeKey, toWireKey } from \"@rebasepro/utils\";\n\nexport interface IntrospectedSchema {\n tablesMap: Map<string, TableMeta>;\n enumMap: Map<string, string[]>;\n joinTables: Set<string>;\n}\n\n/** Whether a table carries an authorization model of its own. */\nexport interface TableRlsStatus {\n table: string;\n /** ALTER TABLE … ENABLE ROW LEVEL SECURITY has been run. */\n rlsEnabled: boolean;\n /** Policies attached to it. RLS enabled with none = nothing is visible. */\n policyCount: number;\n}\n\n/**\n * Read the RLS posture of each table in a schema.\n *\n * This is what decides whether baas mode may serve a table. A table with RLS\n * disabled has no authorization model: since every authenticated request runs\n * as `rebase_user`, and that role is granted DML on the schema, serving such a\n * table hands every row to every logged-in user.\n */\nexport async function readRlsStatus(client: Queryable, pgSchema: string): Promise<Map<string, TableRlsStatus>> {\n const { rows } = await client.query<{ table: string; rls_enabled: boolean; policy_count: string | number }>(\n `SELECT c.relname AS table,\n c.relrowsecurity AS rls_enabled,\n (SELECT count(*) FROM pg_policy p WHERE p.polrelid = c.oid) AS policy_count\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = $1 AND c.relkind = 'r'`,\n [pgSchema]\n );\n\n return new Map(\n rows.map((r) => [\n r.table,\n { table: r.table, rlsEnabled: r.rls_enabled === true, policyCount: Number(r.policy_count ?? 0) }\n ])\n );\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(client: Queryable, pgSchema: string): 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 = 'BASE TABLE'\n AND table_name NOT LIKE 'drizzle_%'\n AND table_name NOT LIKE 'rebase_%'\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 [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/** Derive the `isId` flavour for a primary-key column. */\nfunction idKindFor(col: TableColumn, propType: string): \"uuid\" | \"increment\" | true {\n if (col.data_type.toLowerCase() === \"uuid\") return \"uuid\";\n if (propType === \"number\") return \"increment\";\n return true;\n}\n\nfunction buildProperties(\n meta: TableMeta,\n enumMap: Map<string, string[]>\n): Record<string, Record<string, unknown>> {\n const properties: Record<string, Record<string, unknown>> = {};\n const takenKeys = new Set<string>();\n\n for (const col of meta.columns) {\n const isPk = meta.pks.includes(col.column_name);\n // Foreign keys surface as relations below, unless they are also part of\n // the primary key, in which case the column itself must stay.\n const isFk = meta.fks.some((fk) => fk.column_name === col.column_name);\n if (isFk && !isPk) continue;\n\n const enumValues = enumMap.get(col.udt_name);\n const isEnum = col.data_type === \"USER-DEFINED\" && enumValues !== undefined;\n const isVector = col.udt_name === \"vector\";\n const propType = isEnum ? \"string\" : isVector ? \"vector\" : mapPgType(col.data_type);\n\n const property: Record<string, unknown> = {\n name: humanize(col.column_name),\n columnName: col.column_name,\n type: propType\n };\n\n // The wire name, with `columnName` above carrying the column. The two\n // are different names for different things — this used to serve the\n // column, so a runtime-introspected collection answered `user_id` while\n // every authored one beside it answered `displayName`.\n //\n // `user_id` and `userId` as two real columns camel-case to one key, so\n // the first free candidate wins and the second falls back to its own\n // column name, then to a numbered tail. Never dropped, and stable for a\n // given database: columns arrive in ordinal order.\n const key = firstFreeKey([toWireKey(col.column_name), col.column_name], takenKeys);\n takenKeys.add(key);\n\n if (isPk) {\n property.isId = idKindFor(col, propType);\n } else if (col.is_nullable === \"NO\" && col.column_default === null) {\n property.validation = { required: true };\n }\n\n if (isEnum && enumValues) {\n property.enum = enumValues.map((value) => ({ id: value, label: humanize(value) }));\n }\n\n properties[key] = property;\n }\n\n return properties;\n}\n\n/**\n * Owning relations, derived from this table's foreign keys — the same shape\n * `generateCollectionFile` writes into a collection file: a `relation` property\n * whose nested descriptor carries `kind`, a `target` thunk and the `localKey`.\n *\n * The shape is load-bearing, not cosmetic. `resolveCollectionRelations` reads\n * relations from `property.relation` and `resolveRelation` requires `target` to\n * be a thunk; this used to emit `target`/`cardinality`/`localKey` flat on the\n * property with the slug as a bare string, which satisfies neither. Nothing\n * threw — the resolver simply skipped every such property and reported that the\n * collection had no relations. So an introspected BaaS collection had its FK\n * columns removed from `properties` (they \"surface as relations\") and then no\n * resolvable relation to surface as, which is why writing the FK column\n * directly came back as `has no field 'product_id'`: `assertKnownWriteFields`\n * learns that column from the resolved relation's `localKey`.\n *\n * The thunk closes over the collections being built in this same pass rather\n * than importing a module, which is what a runtime introspection has instead of\n * generated files. It is called lazily, after the map is fully populated, so a\n * table may reference one introspected later.\n */\nfunction buildRelations(\n meta: TableMeta,\n slugByTable: Map<string, string>,\n collectionBySlug: Map<string, PostgresCollectionConfig>\n): Record<string, Record<string, unknown>> {\n const relations: Record<string, Record<string, unknown>> = {};\n\n for (const fk of meta.fks) {\n const targetSlug = slugByTable.get(fk.foreign_table_name);\n if (!targetSlug) continue;\n\n // Strip the conventional _id suffix: author_id -> author\n let key = toWireKey(fk.column_name.replace(/_id$/, \"\"));\n if (meta.pks.includes(fk.column_name) && key === fk.column_name) {\n // The FK is also the PK and its name doesn't imply a relation (e.g.\n // \"id\"), so naming the relation after the column would collide with\n // the primary-key property.\n key = fk.foreign_table_name;\n }\n\n relations[key] = {\n name: humanize(key),\n type: \"relation\",\n relation: {\n kind: \"belongsTo\",\n target: () => collectionBySlug.get(targetSlug),\n localKey: fk.column_name\n }\n };\n }\n\n return relations;\n}\n\n/**\n * Turn an introspected schema into collections.\n *\n * Join tables are skipped: they carry no identity of their own and exist to\n * express a many-to-many edge between two other tables.\n */\nexport function buildCollectionsFromSchema(\n { tablesMap, enumMap, joinTables }: IntrospectedSchema,\n pgSchema: string\n): PostgresCollectionConfig[] {\n const slugByTable = new Map<string, string>();\n for (const tableName of tablesMap.keys()) {\n if (!joinTables.has(tableName)) slugByTable.set(tableName, tableName);\n }\n\n const collections: PostgresCollectionConfig[] = [];\n // Filled as we go; the relation thunks read it lazily, so a table may point\n // at one that has not been built yet at the moment its relation is created.\n const collectionBySlug = new Map<string, PostgresCollectionConfig>();\n\n for (const [tableName, meta] of tablesMap) {\n if (joinTables.has(tableName)) continue;\n\n const collectionName = humanize(tableName);\n const collection = {\n name: collectionName,\n singularName: singularize(collectionName),\n slug: tableName,\n table: tableName,\n schema: pgSchema,\n icon: getIconForTable(tableName),\n properties: {\n ...buildProperties(meta, enumMap),\n ...buildRelations(meta, slugByTable, collectionBySlug)\n }\n // A collection synthesised from a catalogue read, not authored.\n // `PostgresCollectionConfig` is generic over the row type `M`, and\n // there is no `M` here — the columns were discovered a moment ago —\n // so the object is built from the fields introspection can supply\n // and asserted into the config the rest of the server consumes.\n } as unknown as PostgresCollectionConfig;\n\n collections.push(collection);\n collectionBySlug.set(tableName, collection);\n }\n\n return collections;\n}\n\n/** Introspect the database and return ready-to-serve collections. */\nexport async function introspectCollections(\n client: Queryable,\n pgSchema: string\n): Promise<PostgresCollectionConfig[]> {\n const schema = await introspectSchema(client, pgSchema);\n return buildCollectionsFromSchema(schema, pgSchema);\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 collection's own relation key rather than by a\n * guess made from the foreign key. Both come from the collections — see\n * `columnKeysFromCollections` and `buildDrizzleRelationsFromCollections`.\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 PgColumnBuilderBase,\n type PgTable\n} from \"drizzle-orm/pg-core\";\n\nimport { getTableColumns, relations, sql, type Relations } from \"drizzle-orm\";\nimport { toWireKey } from \"@rebasepro/utils\";\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 `as unknown as`: 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, unknown>) => 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) => [primaryKey({ columns: meta.pks.map((pk) => t[keyOf.get(pk) ?? pk]) as never })]\n : undefined\n );\n }\n\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 `buildRelations` in introspect-runtime.ts, which is\n * what names the collection's 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 buildRelations in introspect-runtime: 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, unknown> = {};\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 as never;\n });\n }\n\n return built;\n}\n","/**\n * Build drizzle `relations()` for declared collections, from the collections.\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 collections: 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 collections, 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 sharedRelationName} — only built against tables read back from\n * `information_schema` rather than against a file.\n */\nimport { getTableColumns, relations, type Relations } from \"drizzle-orm\";\nimport type { PgTable } from \"drizzle-orm/pg-core\";\nimport { CollectionConfig, ResolvedRelation, type ResolvedForeignKeyOnTarget } from \"@rebasepro/types\";\nimport { fieldKeyForColumn, getTableName, resolveCollectionRelations } from \"@rebasepro/common\";\nimport { logger } from \"@rebasepro/server\";\n\nimport { sharedRelationName } from \"./relation-names\";\n\n/** A collection's table, 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 field key a collection's rows are addressed by, as the generated module\n * spells it: the property marked `isId`, else `id`.\n *\n * Deliberately the config's answer rather than the catalogue's primary key —\n * `references: [users.id]` in the generated file is keyed the same way, and the\n * two have to name the same Drizzle key for a relation to compile at all.\n */\nfunction primaryKeyFieldKey(collection: CollectionConfig): string {\n for (const [key, prop] of Object.entries(collection.properties ?? {})) {\n if (prop && typeof prop === \"object\" && \"isId\" in prop && Boolean((prop as { isId?: unknown }).isId)) {\n return key;\n }\n }\n return \"id\";\n}\n\n/**\n * The field key on the source table that a `hasOne`/`hasMany` foreign key\n * holds: its `sourceKey` when the link names one, else the primary key.\n */\nfunction sourceKeyFieldKey(\n relation: ResolvedForeignKeyOnTarget,\n collection: CollectionConfig\n): string {\n return relation.sourceKey\n ? fieldKeyForColumn(collection, relation.sourceKey)\n : primaryKeyFieldKey(collection);\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 * collection over that table, in which case they are keyed by its property\n * names. Looking both up costs a scan of one table and removes the difference.\n */\nfunction columnOf(table: PgTable | undefined, key: string): unknown {\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 property names\" case this function's docblock\n // describes — so `getTableColumns` answers it, and indexing the table\n // object (which 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 as { name?: unknown })?.name === key) return column;\n }\n return undefined;\n}\n\ninterface OneSpec {\n key: string;\n target: PgTable;\n fields: unknown[];\n references: unknown[];\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 collection, keyed `<table>Relations`.\n *\n * @param collections every collection backed by a table in `tables`\n * @param tables catalogue-built tables, keyed by bare table name\n */\nexport function buildDrizzleRelationsFromCollections(\n collections: CollectionConfig[],\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 byTable = new Map<string, CollectionConfig>();\n for (const collection of collections) {\n const table = bareTableName(getTableName(collection));\n if (table && tables[table]) byTable.set(table, collection);\n }\n\n for (const [tableName, collection] of byTable) {\n const table = tables[tableName];\n\n for (const [relationKey, relation] of Object.entries(resolveCollectionRelations(collection))) {\n let target: CollectionConfig;\n try {\n target = relation.target();\n } catch (err) {\n // Nothing to build against, and nothing to fail over: the boot\n // relation check reports an unresolvable target by name.\n logger.debug(`[schema] Relation ${collection.slug}.${relationKey} has no resolvable target`, { error: err });\n continue;\n }\n const targetTableName = bareTableName(getTableName(target));\n const targetTable = tables[targetTableName];\n const name = sharedRelationName(relation, collection);\n\n switch (relation.kind) {\n case \"belongsTo\": {\n if (!targetTable) continue;\n if (!claim(tableName, name, relation.kind)) continue;\n const localKey = fieldKeyForColumn(collection, relation.localKey);\n const referenced = primaryKeyFieldKey(target);\n const field = columnOf(table, localKey);\n const reference = columnOf(targetTable, referenced);\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 collection; this only declines to build it.\n if (!field || !reference) continue;\n addOne(tableName, {\n key: relationKey,\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, collection));\n const reference = columnOf(targetTable, fieldKeyForColumn(target, relation.foreignKeyOnTarget));\n if (!field || !reference) continue;\n addOne(tableName, {\n key: relationKey,\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: relationKey, 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: relationKey, target: junction, relationName: name });\n addJunctionSides(relation, collection, target, junctionName, tables, 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 // collection 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, collection] of byTable) {\n const table = tables[tableName];\n for (const [, relation] of Object.entries(resolveCollectionRelations(collection))) {\n if (relation.kind !== \"hasMany\" && relation.kind !== \"hasOne\") continue;\n let target: CollectionConfig;\n try {\n target = relation.target();\n } catch {\n continue;\n }\n const targetTableName = bareTableName(getTableName(target));\n const targetTable = tables[targetTableName];\n if (!targetTable) continue;\n\n const name = sharedRelationName(relation, collection);\n if (!claim(targetTableName, name, \"belongsTo\")) continue;\n\n const fkKey = fieldKeyForColumn(target, relation.foreignKeyOnTarget);\n const field = columnOf(targetTable, fkKey);\n const reference = columnOf(table, sourceKeyFieldKey(relation, collection));\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, unknown> = {};\n for (const spec of tableOnes) {\n map[spec.key] = one(spec.target, {\n fields: spec.fields as never,\n references: spec.references as never,\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 as never;\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<ResolvedRelation, { kind: \"manyToMany\" }>,\n sourceCollection: CollectionConfig,\n targetCollection: CollectionConfig,\n junctionName: string,\n tables: Record<string, PgTable>,\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(getTableName(sourceCollection))];\n const targetTable = tables[bareTableName(getTableName(targetCollection))];\n if (!junction || !sourceTable || !targetTable) return;\n\n const sourceName = sharedRelationName(relation, sourceCollection);\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 = Object.values(resolveCollectionRelations(targetCollection))\n .find(r => r.kind === \"manyToMany\"\n && bareTableName(r.through.table) === junctionName);\n const targetName = inverse\n ? sharedRelationName(inverse, targetCollection)\n : `${junctionName}_${relation.through.targetColumn}`;\n\n const pairs: [string, PgTable, string, CollectionConfig, string][] = [\n [relation.through.sourceColumn, sourceTable, sourceName, sourceCollection, \"source\"],\n [relation.through.targetColumn, targetTable, targetName, targetCollection, \"target\"]\n ];\n\n for (const [column, endpointTable, relationName, endpointCollection] of pairs) {\n if (!claim(junctionName, relationName, \"junction\")) continue;\n const field = columnOf(junction, column);\n const reference = columnOf(endpointTable, primaryKeyFieldKey(endpointCollection));\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 collections 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 { CollectionConfig } from \"@rebasepro/types\";\nimport { fieldKeyForColumn, getJunctionCollectionConfig, getTableName, resolveJunctionSpecs } from \"@rebasepro/common\";\n\nimport { buildDrizzleRelationsFromSchema, buildDrizzleTablesFromSchema, type ColumnKeyResolver } from \"./dynamic-tables\";\nimport { bareTableName, buildDrizzleRelationsFromCollections } from \"./config-relations\";\nimport { introspectSchema, type Queryable } from \"./introspect-runtime\";\nimport type { TableMeta } from \"./introspect-db-logic\";\nimport { searchColumnNames } from \"./search-column\";\n\n/** The Postgres schema a collection's table lives in. */\nexport function schemaOfCollection(collection: CollectionConfig, fallback: string): string {\n const declared = (collection as { schema?: unknown }).schema;\n return typeof declared === \"string\" && declared.length > 0 ? declared : 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 property 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.\n *\n * Two exceptions, both columns no property declares:\n *\n * - the generated search columns keep their raw names, because `search_vector`\n * is how `searchColumnNames` excludes them from responses and how the\n * condition builder finds the one to match against;\n * - a table no collection 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 `through.properties` keys those payload columns by\n * their property key, for the same reason a collection does. `joinedAt` with\n * `columnName: \"joined_at\"` has to be one name on both sides or a `_pivot`\n * write is silently dropped by drizzle and the read serves a key the caller\n * never declared.\n */\nexport function columnKeysFromCollections(\n collections: CollectionConfig[]\n): ColumnKeyResolver {\n const byTable = new Map<string, CollectionConfig>();\n const rawColumns = new Map<string, Set<string>>();\n for (const collection of collections) {\n const table = bareTableName(getTableName(collection));\n if (!table) continue;\n byTable.set(table, collection);\n rawColumns.set(table, new Set(searchColumnNames(collection)));\n }\n // The junctions' payload columns, as the synthetic collection that owns\n // them — the same one the planner emitted the columns from, so the runtime\n // table and the generated one cannot key them differently.\n const junctionByTable = new Map<string, CollectionConfig>();\n for (const spec of resolveJunctionSpecs(collections).values()) {\n if (Object.keys(spec.properties).length === 0) continue;\n junctionByTable.set(bareTableName(spec.table), getJunctionCollectionConfig(spec));\n }\n return (tableName, columnName) => {\n const collection = byTable.get(tableName);\n if (!collection) {\n const junction = junctionByTable.get(tableName);\n return junction ? fieldKeyForColumn(junction, columnName) : columnName;\n }\n if (rawColumns.get(tableName)?.has(columnName)) return columnName;\n return fieldKeyForColumn(collection, 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 a collection declares 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 collections handed in, because the driver is given every\n * collection the project declares while each database holds only its own: an\n * unfiltered read had a second source (`database(\"analytics\")`) reporting the\n * default's tables as its own. Junction tables come too — they back no\n * collection and a many-to-many is unreadable without them.\n *\n * Every schema the collections name is read, not just `public`. The users\n * collection lives in `rebase`, and a run restricted to `public` would leave the\n * registry with no table for it at all.\n */\nexport async function readCatalogueSchema(options: {\n client: Queryable;\n collections: CollectionConfig[];\n defaultSchema: string;\n}): Promise<CatalogueSchema> {\n const { client, collections, 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 collection of collections) {\n const table = bareTableName(getTableName(collection));\n if (table) want(schemaOfCollection(collection, defaultSchema), table);\n }\n // Junctions are created in `public`, full stop — `resolveJunctionSpecs`\n // hardcodes it and the three generators agree with it.\n for (const spec of resolveJunctionSpecs(collections).values()) {\n want(spec.schema, bareTableName(spec.table));\n }\n\n const columnKey = columnKeysFromCollections(collections);\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 const live = await introspectSchema(client, schema);\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 collection 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: buildDrizzleRelationsFromCollections(collections, tables),\n meta,\n missing\n };\n}\n\n/**\n * The BaaS variant: no collections are declared, so every table in one schema is\n * served and both the collections and the relations are derived from the\n * 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 collections: CollectionConfig[]\n): { tables: Record<string, PgTable>; relations: Record<string, Relations> } {\n const columnKey = columnKeysFromCollections(collections);\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 table the collections do) 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 { CollectionConfig } from \"@rebasepro/types\";\nimport { fieldKeyForColumn, getTableName } from \"@rebasepro/common\";\nimport { logger } from \"@rebasepro/server\";\n\nimport { AUTH_USERS_COLUMNS, isAuthCollection } 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\";\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 collection backed by that table, when one is. */\n collection?: string;\n /** The column, in database terms. */\n column?: string;\n /** The field it is served under — the property key, where there is one. */\n property?: 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 collections-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 /** Collections of this source, so a column can be named as a property. */\n collections: CollectionConfig[];\n}): SchemaDifference[] {\n const { generated, catalogue, collections } = options;\n if (!generated) return [];\n\n const collectionByTable = new Map<string, CollectionConfig>();\n for (const collection of collections) {\n const table = getTableName(collection);\n if (table) collectionByTable.set(bareTableName(table), collection);\n }\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 collection = collectionByTable.get(table);\n const at = { table, collection: collection?.slug };\n\n const meta = catalogue.get(table);\n if (!meta) {\n // Only for a table a collection of this source claims: 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 (collection) 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 a users collection does not declare (`is_anonymous`,\n // `tokens_valid_after`) because drizzle-kit creates no auth table, and\n // the collection's own property 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 collection 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 = isAuthCollection(collection)\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 property = collection ? fieldKeyForColumn(collection, 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, property, generated: generatedFamily });\n continue;\n }\n if (found.family !== generatedFamily) {\n differences.push({\n ...at,\n kind: \"type\",\n column: name,\n property,\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 property,\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 property: collection ? fieldKeyForColumn(collection, 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 * `collections` 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 collections: CollectionConfig[];\n defaultSchema: string;\n}): Promise<SchemaDifference[]> {\n const { client, generated, collections, defaultSchema } = options;\n if (!generated || collections.length === 0) return [];\n const catalogue = await readCatalogueSchema({ client, collections, defaultSchema });\n return diffGeneratedSchemaAgainstCatalogue({ generated, catalogue: catalogue.meta, collections });\n}\n\n/** One line, in the terms the reader has: collection, property, column. */\nexport function describeSchemaDifference(difference: SchemaDifference): string {\n const where = difference.collection\n ? `${difference.collection} (table \"${difference.table}\")`\n : `table \"${difference.table}\"`;\n const field = difference.column\n ? `${difference.property && difference.property !== difference.column\n ? `${difference.property} → \"${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 * 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 collection somebody is looking at.\n *\n * The fix it names is `rebase db push`. `rebase dev` rewrites\n * schema.generated.ts from the collections 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 collections 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. If the collections changed since \" +\n \"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 collection: difference.collection,\n column: difference.column,\n property: difference.property,\n generated: difference.generated,\n live: difference.live\n },\n fix: \"rebase db push\"\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuDA,eAAsB,cAAc,QAAmB,UAAwD;CAC3G,MAAM,EAAE,SAAS,MAAM,OAAO,MAC1B;;;;;oDAMA,CAAC,QAAQ,CACb;CAEA,OAAO,IAAI,IACP,KAAK,KAAK,MAAM,CACZ,EAAE,OACF;EAAE,OAAO,EAAE;EAAO,YAAY,EAAE,gBAAgB;EAAM,aAAa,OAAO,EAAE,gBAAgB,CAAC;CAAE,CACnG,CAAC,CACL;AACJ;;;;;AAWA,eAAsB,iBAAiB,QAAmB,UAA+C;CACrG,MAAM,EAAE,MAAM,WAAW,MAAM,OAAO,MAClC;;;;;+BAMA,CAAC,QAAQ,CACb;CAEA,MAAM,EAAE,MAAM,YAAY,MAAM,OAAO,MACnC;;;;;;;;;;;;;;;;;;;qCAoBA,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;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,CACL;EAAM;CAAY,CAAC;AACpG;;AAGA,SAAgB,yBAAyB,YAAsC;CAC3E,MAAM,QAAQ,WAAW,aACnB,GAAG,WAAW,WAAW,WAAW,WAAW,MAAM,MACrD,UAAU,WAAW,MAAM;CACjC,MAAM,QAAQ,WAAW,SACnB,GAAG,WAAW,YAAY,WAAW,aAAa,WAAW,SACzD,GAAG,WAAW,SAAS,MAAM,WAAW,OAAO,KAC/C,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;;;;;;;;;;;;;;;AAgBA,SAAgB,2BAA2B,aAAuC;CAC9E,IAAI,YAAY,WAAW,GAAG;CAE9B,OAAO,KACH,8DAA8D,YAAY,OAAO,aAC9E,YAAY,WAAW,IAAI,KAAK,IAAI,6TAI3C;CAEA,KAAK,MAAM,cAAc,aACrB,OAAO,KAAK,QAAQ,yBAAyB,UAAU,KAAK;EACxD,aAAa;GACT,MAAM,WAAW;GACjB,OAAO,WAAW;GAClB,YAAY,WAAW;GACvB,QAAQ,WAAW;GACnB,UAAU,WAAW;GACrB,WAAW,WAAW;GACtB,MAAM,WAAW;EACrB;EACA,KAAK;CACT,CAAC;AAET"}
1
+ {"version":3,"file":"generated-schema-diff-X9NA2Vig.js","names":[],"sources":["../src/schema/introspect-runtime.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 — builds collections in memory from the live database.\n *\n * This is what makes BaaS mode work with zero configuration: instead of loading\n * collection files from disk, the server reads `information_schema` at boot and\n * derives a collection per table, so any database is served over REST without a\n * single config file.\n *\n * Distinct from `introspect-db.ts`, which runs the same queries but emits\n * TypeScript *source* for a developer to edit and commit (declared collections). The two\n * share the mapping helpers in `introspect-db-logic.ts` so a table is described\n * the same way whether it was generated or introspected.\n */\nimport type { PostgresCollectionConfig } from \"@rebasepro/types\";\n\nimport {\n TableRow,\n TableColumn,\n EnumValue,\n PrimaryKeyRow,\n ForeignKeyRow,\n TableMeta,\n buildTablesMap,\n buildEnumMap,\n identifyJoinTables,\n singularize,\n mapPgType,\n getIconForTable\n} from \"./introspect-db-logic\";\nimport { humanize } from \"./introspect-db-naming\";\nimport { firstFreeKey, toWireKey } from \"@rebasepro/utils\";\n\nexport interface IntrospectedSchema {\n tablesMap: Map<string, TableMeta>;\n enumMap: Map<string, string[]>;\n joinTables: Set<string>;\n}\n\n/** Whether a table carries an authorization model of its own. */\nexport interface TableRlsStatus {\n table: string;\n /** ALTER TABLE … ENABLE ROW LEVEL SECURITY has been run. */\n rlsEnabled: boolean;\n /** Policies attached to it. RLS enabled with none = nothing is visible. */\n policyCount: number;\n}\n\n/**\n * Read the RLS posture of each table in a schema.\n *\n * This is what decides whether baas mode may serve a table. A table with RLS\n * disabled has no authorization model: since every authenticated request runs\n * as `rebase_user`, and that role is granted DML on the schema, serving such a\n * table hands every row to every logged-in user.\n */\nexport async function readRlsStatus(client: Queryable, pgSchema: string): Promise<Map<string, TableRlsStatus>> {\n const { rows } = await client.query<{ table: string; rls_enabled: boolean; policy_count: string | number }>(\n `SELECT c.relname AS table,\n c.relrowsecurity AS rls_enabled,\n (SELECT count(*) FROM pg_policy p WHERE p.polrelid = c.oid) AS policy_count\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = $1 AND c.relkind = 'r'`,\n [pgSchema]\n );\n\n return new Map(\n rows.map((r) => [\n r.table,\n { table: r.table, rlsEnabled: r.rls_enabled === true, policyCount: Number(r.policy_count ?? 0) }\n ])\n );\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(client: Queryable, pgSchema: string): 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 = 'BASE TABLE'\n AND table_name NOT LIKE 'drizzle_%'\n AND table_name NOT LIKE 'rebase_%'\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 [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/** Derive the `isId` flavour for a primary-key column. */\nfunction idKindFor(col: TableColumn, propType: string): \"uuid\" | \"increment\" | true {\n if (col.data_type.toLowerCase() === \"uuid\") return \"uuid\";\n if (propType === \"number\") return \"increment\";\n return true;\n}\n\nfunction buildProperties(\n meta: TableMeta,\n enumMap: Map<string, string[]>\n): Record<string, Record<string, unknown>> {\n const properties: Record<string, Record<string, unknown>> = {};\n const takenKeys = new Set<string>();\n\n for (const col of meta.columns) {\n const isPk = meta.pks.includes(col.column_name);\n // Foreign keys surface as relations below, unless they are also part of\n // the primary key, in which case the column itself must stay.\n const isFk = meta.fks.some((fk) => fk.column_name === col.column_name);\n if (isFk && !isPk) continue;\n\n const enumValues = enumMap.get(col.udt_name);\n const isEnum = col.data_type === \"USER-DEFINED\" && enumValues !== undefined;\n const isVector = col.udt_name === \"vector\";\n const propType = isEnum ? \"string\" : isVector ? \"vector\" : mapPgType(col.data_type);\n\n const property: Record<string, unknown> = {\n name: humanize(col.column_name),\n columnName: col.column_name,\n type: propType\n };\n\n // The wire name, with `columnName` above carrying the column. The two\n // are different names for different things — this used to serve the\n // column, so a runtime-introspected collection answered `user_id` while\n // every authored one beside it answered `displayName`.\n //\n // `user_id` and `userId` as two real columns camel-case to one key, so\n // the first free candidate wins and the second falls back to its own\n // column name, then to a numbered tail. Never dropped, and stable for a\n // given database: columns arrive in ordinal order.\n const key = firstFreeKey([toWireKey(col.column_name), col.column_name], takenKeys);\n takenKeys.add(key);\n\n if (isPk) {\n property.isId = idKindFor(col, propType);\n } else if (col.is_nullable === \"NO\" && col.column_default === null) {\n property.validation = { required: true };\n }\n\n if (isEnum && enumValues) {\n property.enum = enumValues.map((value) => ({ id: value, label: humanize(value) }));\n }\n\n properties[key] = property;\n }\n\n return properties;\n}\n\n/**\n * Owning relations, derived from this table's foreign keys — the same shape\n * `generateCollectionFile` writes into a collection file: a `relation` property\n * whose nested descriptor carries `kind`, a `target` thunk and the `localKey`.\n *\n * The shape is load-bearing, not cosmetic. `resolveCollectionRelations` reads\n * relations from `property.relation` and `resolveRelation` requires `target` to\n * be a thunk; this used to emit `target`/`cardinality`/`localKey` flat on the\n * property with the slug as a bare string, which satisfies neither. Nothing\n * threw — the resolver simply skipped every such property and reported that the\n * collection had no relations. So an introspected BaaS collection had its FK\n * columns removed from `properties` (they \"surface as relations\") and then no\n * resolvable relation to surface as, which is why writing the FK column\n * directly came back as `has no field 'product_id'`: `assertKnownWriteFields`\n * learns that column from the resolved relation's `localKey`.\n *\n * The thunk closes over the collections being built in this same pass rather\n * than importing a module, which is what a runtime introspection has instead of\n * generated files. It is called lazily, after the map is fully populated, so a\n * table may reference one introspected later.\n */\nfunction buildRelations(\n meta: TableMeta,\n slugByTable: Map<string, string>,\n collectionBySlug: Map<string, PostgresCollectionConfig>\n): Record<string, Record<string, unknown>> {\n const relations: Record<string, Record<string, unknown>> = {};\n\n for (const fk of meta.fks) {\n const targetSlug = slugByTable.get(fk.foreign_table_name);\n if (!targetSlug) continue;\n\n // Strip the conventional _id suffix: author_id -> author\n let key = toWireKey(fk.column_name.replace(/_id$/, \"\"));\n if (meta.pks.includes(fk.column_name) && key === fk.column_name) {\n // The FK is also the PK and its name doesn't imply a relation (e.g.\n // \"id\"), so naming the relation after the column would collide with\n // the primary-key property.\n key = fk.foreign_table_name;\n }\n\n relations[key] = {\n name: humanize(key),\n type: \"relation\",\n relation: {\n kind: \"belongsTo\",\n target: () => collectionBySlug.get(targetSlug),\n localKey: fk.column_name\n }\n };\n }\n\n return relations;\n}\n\n/**\n * Turn an introspected schema into collections.\n *\n * Join tables are skipped: they carry no identity of their own and exist to\n * express a many-to-many edge between two other tables.\n */\nexport function buildCollectionsFromSchema(\n { tablesMap, enumMap, joinTables }: IntrospectedSchema,\n pgSchema: string\n): PostgresCollectionConfig[] {\n const slugByTable = new Map<string, string>();\n for (const tableName of tablesMap.keys()) {\n if (!joinTables.has(tableName)) slugByTable.set(tableName, tableName);\n }\n\n const collections: PostgresCollectionConfig[] = [];\n // Filled as we go; the relation thunks read it lazily, so a table may point\n // at one that has not been built yet at the moment its relation is created.\n const collectionBySlug = new Map<string, PostgresCollectionConfig>();\n\n for (const [tableName, meta] of tablesMap) {\n if (joinTables.has(tableName)) continue;\n\n const collectionName = humanize(tableName);\n const collection = {\n name: collectionName,\n singularName: singularize(collectionName),\n slug: tableName,\n table: tableName,\n schema: pgSchema,\n icon: getIconForTable(tableName),\n properties: {\n ...buildProperties(meta, enumMap),\n ...buildRelations(meta, slugByTable, collectionBySlug)\n }\n // A collection synthesised from a catalogue read, not authored.\n // `PostgresCollectionConfig` is generic over the row type `M`, and\n // there is no `M` here — the columns were discovered a moment ago —\n // so the object is built from the fields introspection can supply\n // and asserted into the config the rest of the server consumes.\n } as unknown as PostgresCollectionConfig;\n\n collections.push(collection);\n collectionBySlug.set(tableName, collection);\n }\n\n return collections;\n}\n\n/** Introspect the database and return ready-to-serve collections. */\nexport async function introspectCollections(\n client: Queryable,\n pgSchema: string\n): Promise<PostgresCollectionConfig[]> {\n const schema = await introspectSchema(client, pgSchema);\n return buildCollectionsFromSchema(schema, pgSchema);\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 collection's own relation key rather than by a\n * guess made from the foreign key. Both come from the collections — see\n * `columnKeysFromCollections` and `buildDrizzleRelationsFromCollections`.\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 PgColumnBuilderBase,\n type PgTable\n} from \"drizzle-orm/pg-core\";\n\nimport { getTableColumns, relations, sql, type Relations } from \"drizzle-orm\";\nimport { toWireKey } from \"@rebasepro/utils\";\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 `as unknown as`: 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, unknown>) => 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) => [primaryKey({ columns: meta.pks.map((pk) => t[keyOf.get(pk) ?? pk]) as never })]\n : undefined\n );\n }\n\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 `buildRelations` in introspect-runtime.ts, which is\n * what names the collection's 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 buildRelations in introspect-runtime: 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, unknown> = {};\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 as never;\n });\n }\n\n return built;\n}\n","/**\n * Build drizzle `relations()` for declared collections, from the collections.\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 collections: 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 collections, 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 sharedRelationName} — only built against tables read back from\n * `information_schema` rather than against a file.\n */\nimport { getTableColumns, relations, type Relations } from \"drizzle-orm\";\nimport type { PgTable } from \"drizzle-orm/pg-core\";\nimport { CollectionConfig, ResolvedRelation, type ResolvedForeignKeyOnTarget } from \"@rebasepro/types\";\nimport { fieldKeyForColumn, getTableName, resolveCollectionRelations } from \"@rebasepro/common\";\nimport { logger } from \"@rebasepro/server\";\n\nimport { sharedRelationName } from \"./relation-names\";\n\n/** A collection's table, 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 field key a collection's rows are addressed by, as the generated module\n * spells it: the property marked `isId`, else `id`.\n *\n * Deliberately the config's answer rather than the catalogue's primary key —\n * `references: [users.id]` in the generated file is keyed the same way, and the\n * two have to name the same Drizzle key for a relation to compile at all.\n */\nfunction primaryKeyFieldKey(collection: CollectionConfig): string {\n for (const [key, prop] of Object.entries(collection.properties ?? {})) {\n if (prop && typeof prop === \"object\" && \"isId\" in prop && Boolean((prop as { isId?: unknown }).isId)) {\n return key;\n }\n }\n return \"id\";\n}\n\n/**\n * The field key on the source table that a `hasOne`/`hasMany` foreign key\n * holds: its `sourceKey` when the link names one, else the primary key.\n */\nfunction sourceKeyFieldKey(\n relation: ResolvedForeignKeyOnTarget,\n collection: CollectionConfig\n): string {\n return relation.sourceKey\n ? fieldKeyForColumn(collection, relation.sourceKey)\n : primaryKeyFieldKey(collection);\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 * collection over that table, in which case they are keyed by its property\n * names. Looking both up costs a scan of one table and removes the difference.\n */\nfunction columnOf(table: PgTable | undefined, key: string): unknown {\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 property names\" case this function's docblock\n // describes — so `getTableColumns` answers it, and indexing the table\n // object (which 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 as { name?: unknown })?.name === key) return column;\n }\n return undefined;\n}\n\ninterface OneSpec {\n key: string;\n target: PgTable;\n fields: unknown[];\n references: unknown[];\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 collection, keyed `<table>Relations`.\n *\n * @param collections every collection backed by a table in `tables`\n * @param tables catalogue-built tables, keyed by bare table name\n */\nexport function buildDrizzleRelationsFromCollections(\n collections: CollectionConfig[],\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 byTable = new Map<string, CollectionConfig>();\n for (const collection of collections) {\n const table = bareTableName(getTableName(collection));\n if (table && tables[table]) byTable.set(table, collection);\n }\n\n for (const [tableName, collection] of byTable) {\n const table = tables[tableName];\n\n for (const [relationKey, relation] of Object.entries(resolveCollectionRelations(collection))) {\n let target: CollectionConfig;\n try {\n target = relation.target();\n } catch (err) {\n // Nothing to build against, and nothing to fail over: the boot\n // relation check reports an unresolvable target by name.\n logger.debug(`[schema] Relation ${collection.slug}.${relationKey} has no resolvable target`, { error: err });\n continue;\n }\n const targetTableName = bareTableName(getTableName(target));\n const targetTable = tables[targetTableName];\n const name = sharedRelationName(relation, collection);\n\n switch (relation.kind) {\n case \"belongsTo\": {\n if (!targetTable) continue;\n if (!claim(tableName, name, relation.kind)) continue;\n const localKey = fieldKeyForColumn(collection, relation.localKey);\n const referenced = primaryKeyFieldKey(target);\n const field = columnOf(table, localKey);\n const reference = columnOf(targetTable, referenced);\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 collection; this only declines to build it.\n if (!field || !reference) continue;\n addOne(tableName, {\n key: relationKey,\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, collection));\n const reference = columnOf(targetTable, fieldKeyForColumn(target, relation.foreignKeyOnTarget));\n if (!field || !reference) continue;\n addOne(tableName, {\n key: relationKey,\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: relationKey, 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: relationKey, target: junction, relationName: name });\n addJunctionSides(relation, collection, target, junctionName, tables, 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 // collection 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, collection] of byTable) {\n const table = tables[tableName];\n for (const [, relation] of Object.entries(resolveCollectionRelations(collection))) {\n if (relation.kind !== \"hasMany\" && relation.kind !== \"hasOne\") continue;\n let target: CollectionConfig;\n try {\n target = relation.target();\n } catch {\n continue;\n }\n const targetTableName = bareTableName(getTableName(target));\n const targetTable = tables[targetTableName];\n if (!targetTable) continue;\n\n const name = sharedRelationName(relation, collection);\n if (!claim(targetTableName, name, \"belongsTo\")) continue;\n\n const fkKey = fieldKeyForColumn(target, relation.foreignKeyOnTarget);\n const field = columnOf(targetTable, fkKey);\n const reference = columnOf(table, sourceKeyFieldKey(relation, collection));\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, unknown> = {};\n for (const spec of tableOnes) {\n map[spec.key] = one(spec.target, {\n fields: spec.fields as never,\n references: spec.references as never,\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 as never;\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<ResolvedRelation, { kind: \"manyToMany\" }>,\n sourceCollection: CollectionConfig,\n targetCollection: CollectionConfig,\n junctionName: string,\n tables: Record<string, PgTable>,\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(getTableName(sourceCollection))];\n const targetTable = tables[bareTableName(getTableName(targetCollection))];\n if (!junction || !sourceTable || !targetTable) return;\n\n const sourceName = sharedRelationName(relation, sourceCollection);\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 = Object.values(resolveCollectionRelations(targetCollection))\n .find(r => r.kind === \"manyToMany\"\n && bareTableName(r.through.table) === junctionName);\n const targetName = inverse\n ? sharedRelationName(inverse, targetCollection)\n : `${junctionName}_${relation.through.targetColumn}`;\n\n const pairs: [string, PgTable, string, CollectionConfig, string][] = [\n [relation.through.sourceColumn, sourceTable, sourceName, sourceCollection, \"source\"],\n [relation.through.targetColumn, targetTable, targetName, targetCollection, \"target\"]\n ];\n\n for (const [column, endpointTable, relationName, endpointCollection] of pairs) {\n if (!claim(junctionName, relationName, \"junction\")) continue;\n const field = columnOf(junction, column);\n const reference = columnOf(endpointTable, primaryKeyFieldKey(endpointCollection));\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 collections 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 { CollectionConfig } from \"@rebasepro/types\";\nimport { fieldKeyForColumn, getJunctionCollectionConfig, getTableName, resolveJunctionSpecs } from \"@rebasepro/common\";\n\nimport { buildDrizzleRelationsFromSchema, buildDrizzleTablesFromSchema, type ColumnKeyResolver } from \"./dynamic-tables\";\nimport { bareTableName, buildDrizzleRelationsFromCollections } from \"./config-relations\";\nimport { introspectSchema, type Queryable } from \"./introspect-runtime\";\nimport type { TableMeta } from \"./introspect-db-logic\";\nimport { searchColumnNames } from \"./search-column\";\n\n/** The Postgres schema a collection's table lives in. */\nexport function schemaOfCollection(collection: CollectionConfig, fallback: string): string {\n const declared = (collection as { schema?: unknown }).schema;\n return typeof declared === \"string\" && declared.length > 0 ? declared : 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 property 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.\n *\n * Two exceptions, both columns no property declares:\n *\n * - the generated search columns keep their raw names, because `search_vector`\n * is how `searchColumnNames` excludes them from responses and how the\n * condition builder finds the one to match against;\n * - a table no collection 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 `through.properties` keys those payload columns by\n * their property key, for the same reason a collection does. `joinedAt` with\n * `columnName: \"joined_at\"` has to be one name on both sides or a `_pivot`\n * write is silently dropped by drizzle and the read serves a key the caller\n * never declared.\n */\nexport function columnKeysFromCollections(\n collections: CollectionConfig[]\n): ColumnKeyResolver {\n const byTable = new Map<string, CollectionConfig>();\n const rawColumns = new Map<string, Set<string>>();\n for (const collection of collections) {\n const table = bareTableName(getTableName(collection));\n if (!table) continue;\n byTable.set(table, collection);\n rawColumns.set(table, new Set(searchColumnNames(collection)));\n }\n // The junctions' payload columns, as the synthetic collection that owns\n // them — the same one the planner emitted the columns from, so the runtime\n // table and the generated one cannot key them differently.\n const junctionByTable = new Map<string, CollectionConfig>();\n for (const spec of resolveJunctionSpecs(collections).values()) {\n if (Object.keys(spec.properties).length === 0) continue;\n junctionByTable.set(bareTableName(spec.table), getJunctionCollectionConfig(spec));\n }\n return (tableName, columnName) => {\n const collection = byTable.get(tableName);\n if (!collection) {\n const junction = junctionByTable.get(tableName);\n return junction ? fieldKeyForColumn(junction, columnName) : columnName;\n }\n if (rawColumns.get(tableName)?.has(columnName)) return columnName;\n return fieldKeyForColumn(collection, 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 a collection declares 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 collections handed in, because the driver is given every\n * collection the project declares while each database holds only its own: an\n * unfiltered read had a second source (`database(\"analytics\")`) reporting the\n * default's tables as its own. Junction tables come too — they back no\n * collection and a many-to-many is unreadable without them.\n *\n * Every schema the collections name is read, not just `public`. The users\n * collection lives in `rebase`, and a run restricted to `public` would leave the\n * registry with no table for it at all.\n */\nexport async function readCatalogueSchema(options: {\n client: Queryable;\n collections: CollectionConfig[];\n defaultSchema: string;\n}): Promise<CatalogueSchema> {\n const { client, collections, 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 collection of collections) {\n const table = bareTableName(getTableName(collection));\n if (table) want(schemaOfCollection(collection, defaultSchema), table);\n }\n // Junctions are created in `public`, full stop — `resolveJunctionSpecs`\n // hardcodes it and the three generators agree with it.\n for (const spec of resolveJunctionSpecs(collections).values()) {\n want(spec.schema, bareTableName(spec.table));\n }\n\n const columnKey = columnKeysFromCollections(collections);\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 const live = await introspectSchema(client, schema);\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 collection 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: buildDrizzleRelationsFromCollections(collections, tables),\n meta,\n missing\n };\n}\n\n/**\n * The BaaS variant: no collections are declared, so every table in one schema is\n * served and both the collections and the relations are derived from the\n * 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 collections: CollectionConfig[]\n): { tables: Record<string, PgTable>; relations: Record<string, Relations> } {\n const columnKey = columnKeysFromCollections(collections);\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 table the collections do) 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 { CollectionConfig } from \"@rebasepro/types\";\nimport { fieldKeyForColumn, getTableName } from \"@rebasepro/common\";\nimport { logger } from \"@rebasepro/server\";\n\nimport { AUTH_USERS_COLUMNS, isAuthCollection } 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\";\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 collection backed by that table, when one is. */\n collection?: string;\n /** The column, in database terms. */\n column?: string;\n /** The field it is served under — the property key, where there is one. */\n property?: 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 collections-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 /** Collections of this source, so a column can be named as a property. */\n collections: CollectionConfig[];\n}): SchemaDifference[] {\n const { generated, catalogue, collections } = options;\n if (!generated) return [];\n\n const collectionByTable = new Map<string, CollectionConfig>();\n for (const collection of collections) {\n const table = getTableName(collection);\n if (table) collectionByTable.set(bareTableName(table), collection);\n }\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 collection = collectionByTable.get(table);\n const at = { table, collection: collection?.slug };\n\n const meta = catalogue.get(table);\n if (!meta) {\n // Only for a table a collection of this source claims: 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 (collection) 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 a users collection does not declare (`is_anonymous`,\n // `tokens_valid_after`) because drizzle-kit creates no auth table, and\n // the collection's own property 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 collection 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 = isAuthCollection(collection)\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 property = collection ? fieldKeyForColumn(collection, 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, property, generated: generatedFamily });\n continue;\n }\n if (found.family !== generatedFamily) {\n differences.push({\n ...at,\n kind: \"type\",\n column: name,\n property,\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 property,\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 property: collection ? fieldKeyForColumn(collection, 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 * `collections` 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 collections: CollectionConfig[];\n defaultSchema: string;\n}): Promise<SchemaDifference[]> {\n const { client, generated, collections, defaultSchema } = options;\n if (!generated || collections.length === 0) return [];\n const catalogue = await readCatalogueSchema({ client, collections, defaultSchema });\n return diffGeneratedSchemaAgainstCatalogue({ generated, catalogue: catalogue.meta, collections });\n}\n\n/** One line, in the terms the reader has: collection, property, column. */\nexport function describeSchemaDifference(difference: SchemaDifference): string {\n const where = difference.collection\n ? `${difference.collection} (table \"${difference.table}\")`\n : `table \"${difference.table}\"`;\n const field = difference.column\n ? `${difference.property && difference.property !== difference.column\n ? `${difference.property} → \"${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 * 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 collection somebody is looking at.\n *\n * The fix it names is `rebase db push`. `rebase dev` rewrites\n * schema.generated.ts from the collections 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 collections 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. If the collections changed since \" +\n \"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 collection: difference.collection,\n column: difference.column,\n property: difference.property,\n generated: difference.generated,\n live: difference.live\n },\n fix: \"rebase db push\"\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuDA,eAAsB,cAAc,QAAmB,UAAwD;CAC3G,MAAM,EAAE,SAAS,MAAM,OAAO,MAC1B;;;;;oDAMA,CAAC,QAAQ,CACb;CAEA,OAAO,IAAI,IACP,KAAK,KAAK,MAAM,CACZ,EAAE,OACF;EAA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AAG,MAAM,IAAI,MAAM,MAAM,WAAW,UAAU,8BAA8B,WAAW,KAAK;CAC3G;AACJ;;;;;;;;;;;;;;;AAgBA,SAAgB,2BAA2B,aAAuC;CAC9E,IAAI,YAAY,WAAW,GAAG;CAE9B,OAAO,KACH,8DAA8D,YAAY,OAAO,aAC9E,YAAY,WAAW,IAAI,KAAK,IAAI,6TAI3C;CAEA,KAAK,MAAM,cAAc,aACrB,OAAO,KAAK,QAAQ,yBAAyB,UAAU,KAAK;EACxD,aAAa;GACT,MAAM,WAAW;GACjB,OAAO,WAAW;GAClB,YAAY,WAAW;GACvB,QAAQ,WAAW;GACnB,UAAU,WAAW;GACrB,WAAW,WAAW;GACtB,MAAM,WAAW;EACrB;EACA,KAAK;CACT,CAAC;AAET"}
@@ -103,6 +103,13 @@ export declare class HistoryService {
103
103
  * Fetch a single history entry by ID.
104
104
  */
105
105
  fetchHistoryEntry(historyId: string): Promise<HistoryEntry | null>;
106
+ /**
107
+ * Every entry's `values` and `previous_values`, of every row, a page at a
108
+ * time in id order — for a whole-store sweep. `rebase storage orphans`
109
+ * reads it because a history revert restores the values an entry holds,
110
+ * so a file only an entry names is still in use.
111
+ */
112
+ scanStoredValues(pageSize?: number): AsyncGenerator<unknown[]>;
106
113
  /**
107
114
  * Each entry's `format`. A table without the column holds only entries
108
115
  * that store the whole previous row, which is what `1` says.
package/dist/index.d.ts CHANGED
@@ -11,11 +11,31 @@ export * from "./services/channel-bus/index.js";
11
11
  export * from "./websocket.js";
12
12
  export * from "./collections/PostgresCollectionRegistry.js";
13
13
  export * from "./services/BranchService.js";
14
+ export { diffDatabaseBranch, mergeDatabaseBranch, DEFAULT_BRANCH_DIFF_SAMPLE_LIMIT, DEFAULT_BRANCH_DIFF_MAX_ROWS } from "./branching/branch-diff.js";
14
15
  export * from "./backup/index.js";
15
16
  export * from "./PostgresBootstrapper.js";
16
17
  export * from "./PostgresAdapter.js";
17
18
  export * from "./open-rebase.js";
18
19
  export { assertDbCommandLine } from "./db-command-line.js";
20
+ /**
21
+ * Whether the migration files still build what the collections declare —
22
+ * offline, without Atlas or a dev database. `rebase verify` runs it after every
23
+ * collection edit and in CI.
24
+ */
25
+ export { findUnmigratedSchema } from "./schema/migration-freshness.js";
26
+ export type { UnmigratedChange } from "./schema/migration-freshness.js";
27
+ /**
28
+ * Atlas's version order and the version a migration file records, for a
29
+ * caller that reads `rebase.atlas_schema_revisions` itself — `rebase verify
30
+ * --live` counts a baselined database's earlier migrations as applied.
31
+ */
32
+ export { compareMigrationVersions, migrationVersionOf } from "./schema/migrate-baseline.js";
33
+ /**
34
+ * Whether a policy name is one Rebase generates from a collection's
35
+ * `securityRules` — `rebase verify --live` reads such a public-read policy as
36
+ * what the rule says rather than as a hand-written hole.
37
+ */
38
+ export { isGeneratedPolicyName } from "./security/policy-drift.js";
19
39
  /**
20
40
  * The app-role provisioning boot performs, for callers that restore a database
21
41
  * outside a boot.