@rebasepro/server-postgres 0.21.0 → 0.21.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -13
- package/dist/{BranchService-W3DMfcZZ.js → BranchService-CucnFcSE.js} +2 -2
- package/dist/{BranchService-W3DMfcZZ.js.map → BranchService-CucnFcSE.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +26 -10
- package/dist/backup/backup-cron.d.ts +28 -1
- package/dist/{backup-cli-Bp-ou6o2.js → backup-cli-CkjsJEcu.js} +3 -2
- package/dist/backup-cli-CkjsJEcu.js.map +1 -0
- package/dist/{cli-errors-C3g_kHBw.js → cli-errors-Dka89exj.js} +19 -2
- package/dist/cli-errors-Dka89exj.js.map +1 -0
- package/dist/cli.js +15 -8
- package/dist/cli.js.map +1 -1
- package/dist/{doctor-ByFWL_ET.js → doctor-Gzzd8wTq.js} +4 -4
- package/dist/{doctor-ByFWL_ET.js.map → doctor-Gzzd8wTq.js.map} +1 -1
- package/dist/{ensure-collection-policies-CQGHln-y.js → ensure-collection-policies-B4IDFtQ-.js} +2 -2
- package/dist/{ensure-collection-policies-CQGHln-y.js.map → ensure-collection-policies-B4IDFtQ-.js.map} +1 -1
- package/dist/{ensure-collection-tables-Bkvehxdm.js → ensure-collection-tables-Cr2ye5JC.js} +2 -2
- package/dist/{ensure-collection-tables-Bkvehxdm.js.map → ensure-collection-tables-Cr2ye5JC.js.map} +1 -1
- package/dist/{generate-drizzle-schema-vSK-VdYT.js → generate-drizzle-schema-D2MDdJt-.js} +2 -2
- package/dist/{generate-drizzle-schema-vSK-VdYT.js.map → generate-drizzle-schema-D2MDdJt-.js.map} +1 -1
- package/dist/{generate-drizzle-schema-logic-Dfyf_MRu.js → generate-drizzle-schema-logic-DFa9qy9u.js} +4 -2
- package/dist/{generate-drizzle-schema-logic-Dfyf_MRu.js.map → generate-drizzle-schema-logic-DFa9qy9u.js.map} +1 -1
- package/dist/{generated-schema-staleness-DRQe2BpC.js → generated-schema-staleness-Di9c4ZxN.js} +9 -5
- package/dist/{generated-schema-staleness-DRQe2BpC.js.map → generated-schema-staleness-Di9c4ZxN.js.map} +1 -1
- package/dist/index.es.js +264 -180
- package/dist/index.es.js.map +1 -1
- package/dist/schema/doctor-cli.js +2 -2
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generated-schema-staleness.d.ts +22 -0
- package/dist/services/realtimeService.d.ts +75 -12
- package/package.json +7 -7
- package/dist/backup-cli-Bp-ou6o2.js.map +0 -1
- package/dist/cli-errors-C3g_kHBw.js.map +0 -1
package/dist/{ensure-collection-tables-Bkvehxdm.js.map → ensure-collection-tables-Cr2ye5JC.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ensure-collection-tables-Bkvehxdm.js","names":[],"sources":["../src/schema/column-type-drift.ts","../src/schema/plan/diff-plan.ts","../src/schema/ensure-collection-tables.ts"],"sourcesContent":["/**\n * A column whose type in the database is not the type the collection declares.\n *\n * The boot ensure is additive: it creates tables, columns, enum values and\n * indexes, and it never changes an existing column's type. That is the right\n * default — an automatic `ALTER COLUMN … TYPE` against customer data, decided\n * by a process nobody is watching, is not a thing to do quietly.\n *\n * What was wrong is that it happened *silently*. A property's `columnType`\n * changed after the first deploy, the deploy reported success, the column stayed\n * as it was, and the divergence surfaced later as writes failing:\n *\n * Invalid data format in \"listing_observations\":\n * malformed array literal: \"[0,0,0.0755,…]\"\n *\n * ...after a 10,690-row import, from a deployment that had said \"success\". The\n * two ends disagreed about the schema, so no value satisfied both: the declared\n * shape was rejected by Postgres and the Postgres shape was rejected by the\n * API's own validator, first. There is no encoding out of that, only a report.\n *\n * ## Why the comparison is deliberately blunt\n *\n * A drift report that cries wolf is worse than none, because the boot that says\n * it every time is the boot nobody reads. So types are compared by *family*, and\n * a family is only split from another when the difference changes what the\n * column can hold:\n *\n * - every numeric type is one family. `int4`, `numeric` and `float8` all arrive\n * as JavaScript numbers and accept each other's values; a database adopted\n * from an existing schema legitimately has `int4` where `type: \"number\"`\n * generates `NUMERIC`, and that is not news.\n * - every character type is one family, for the same reason: `text`,\n * `varchar(255)` and `char(3)` differ in what they *reject*, not in shape.\n * - `jsonb` and an array are different families, and that is the case this\n * exists for.\n *\n * Anything this module does not recognise — an enum type, a domain, a PostGIS\n * geometry, an extension type it has never met — returns `null` and is compared\n * with nothing. Silence on an unknown type is the deliberate choice: the cost of\n * a missed report is a question somebody asks once, and the cost of a false one\n * is a warning everybody learns to skip.\n */\n\n/** A column whose live type and declared type are in different families. */\nexport interface ColumnTypeDrift {\n /** `schema.table`. */\n table: string;\n /** The column name as it exists in the database. */\n column: string;\n /** What the collection says the column should be, e.g. `JSONB`. */\n declared: string;\n /** What the database actually has, as `udt_name` reports it, e.g. `_numeric`. */\n actual: string;\n}\n\n/**\n * Types that mean the same thing to everything above the driver.\n *\n * Keyed by every spelling either side can produce: `information_schema` reports\n * `udt_name` (`int4`, `_numeric`, `bpchar`), while the generators emit SQL\n * (`INTEGER`, `NUMERIC[]`, `CHAR(3)`). Both are normalised through here.\n */\nconst FAMILIES: Record<string, string> = {\n // Numbers. One family on purpose — see the note above.\n int2: \"number\", smallint: \"number\",\n int4: \"number\", int: \"number\", integer: \"number\",\n int8: \"number\", bigint: \"number\",\n numeric: \"number\", decimal: \"number\",\n float4: \"number\", real: \"number\",\n float8: \"number\", \"double precision\": \"number\",\n money: \"number\",\n\n // Characters. Also one family: the differences are limits, not shapes.\n text: \"text\", varchar: \"text\", \"character varying\": \"text\",\n bpchar: \"text\", char: \"text\", character: \"text\", citext: \"text\",\n\n bool: \"boolean\", boolean: \"boolean\",\n\n json: \"json\",\n jsonb: \"jsonb\",\n\n uuid: \"uuid\",\n bytea: \"bytea\",\n\n date: \"date\",\n time: \"time\", \"time without time zone\": \"time\",\n timetz: \"time\", \"time with time zone\": \"time\",\n timestamp: \"timestamp\", \"timestamp without time zone\": \"timestamp\",\n timestamptz: \"timestamptz\", \"timestamp with time zone\": \"timestamptz\",\n interval: \"interval\",\n\n tsvector: \"tsvector\",\n vector: \"vector\",\n halfvec: \"halfvec\",\n sparsevec: \"sparsevec\"\n};\n\n/**\n * One SQL or `udt_name` spelling reduced to its family, or `null` when this\n * module has no opinion about it.\n *\n * `null` is not a failure. It is the answer for an enum type, a domain, a\n * PostGIS column, a quoted qualified name — everything whose identity is a\n * *name* rather than a shape, where two spellings being different says nothing\n * about whether the values are compatible.\n */\nexport function typeFamily(raw: string | undefined | null): string | null {\n if (!raw) return null;\n let type = raw.trim().toLowerCase();\n if (!type) return null;\n\n // `\"public\".\"posts_status\"` — an enum, identified by name. Not comparable.\n if (type.startsWith(\"\\\"\")) return null;\n\n // `INTEGER GENERATED BY DEFAULT AS IDENTITY` is an `int4` with a default\n // attached; the identity clause is not part of the type.\n const generated = type.indexOf(\" generated \");\n if (generated > 0) type = type.slice(0, generated).trim();\n\n // Arrays, in both spellings: `NUMERIC[]` from the generators, `_numeric`\n // from `udt_name`. Compared element-wise, so `text[]` and `numeric[]` are\n // different and `int4[]` and `numeric[]` are not.\n if (type.endsWith(\"[]\")) {\n const element = typeFamily(type.slice(0, -2));\n return element && `array:${element}`;\n }\n if (type.startsWith(\"_\")) {\n const element = typeFamily(type.slice(1));\n return element && `array:${element}`;\n }\n\n // `VARCHAR(255)`, `VECTOR(384)`, `NUMERIC(10, 2)` — the width is a limit on\n // a family, not a family. A vector whose *dimensions* changed is a separate\n // concern with its own handling in the ensure.\n const paren = type.indexOf(\"(\");\n if (paren > 0) type = type.slice(0, paren).trim();\n\n return FAMILIES[type] ?? null;\n}\n\n/**\n * Do these two spellings describe columns that hold the same kind of value?\n *\n * `true` whenever the answer is not confidently \"no\" — an unrecognised type on\n * either side agrees with everything, because a report needs evidence and an\n * unknown type is the absence of it.\n */\nexport function typesAgree(declared: string, actual: string): boolean {\n const a = typeFamily(declared);\n const b = typeFamily(actual);\n if (a === null || b === null) return true;\n if (a !== b) return false;\n // Same family, and for `numeric` that is not the end of it: the modifier is\n // what makes `NUMERIC(10, 2)` a price and a bare `NUMERIC` a number that\n // keeps whatever the caller sent. A property that declares\n // `precision`/`scale` is asking the database to round, and a column without\n // them silently does not — so the two disagree, and the drift report says\n // so. A declaration with no modifier accepts whatever is there, which is\n // what it always did.\n if (a !== \"numeric\") return true;\n const declaredModifier = numericModifier(declared);\n if (declaredModifier === null) return true;\n return declaredModifier === numericModifier(actual);\n}\n\n/** `numeric(10,2)` / `NUMERIC(10, 2)` → `10,2`; a bare `numeric` → `null`. */\nfunction numericModifier(raw: string): string | null {\n const match = raw.match(/\\(([^)]*)\\)/);\n return match ? match[1].replace(/\\s+/g, \"\") : null;\n}\n\n/**\n * The sentence a boot log says about one drifted column.\n *\n * Written to be actionable in the place it is read, which is a runtime log with\n * no way to run a migration from it: it names both types, says which surface\n * will break first, and gives the statement that resolves it.\n */\nexport function columnTypeDriftMessage(drift: ColumnTypeDrift): string {\n const [schema, table] = drift.table.split(\".\");\n return (\n `Column \"${drift.table}\".\"${drift.column}\" is ${drift.actual} in the database, but this ` +\n `collection declares ${drift.declared}. Boot does not change an existing column's type, so ` +\n \"the database keeps what it has and writes that match the declaration will be rejected by \" +\n \"Postgres. Change it deliberately, when you can watch it:\\n\" +\n ` ALTER TABLE \"${schema}\".\"${table}\" ALTER COLUMN \"${drift.column}\" ` +\n `TYPE ${drift.declared} USING \"${drift.column}\"::${drift.declared};`\n );\n}\n","/**\n * The additive statements that bring a database up to a {@link SchemaPlan}.\n *\n * ## Why additive-only, forever\n *\n * This runs unattended, at boot, against a database with customers' data in it,\n * with no human reading a diff. So it may only ever do things that cannot lose\n * data: create a missing table, add a missing column, create a missing enum\n * type, add an enum value, create an index.\n *\n * It will **never** drop a table or a column, narrow a type, or alter a\n * constraint at boot. A removed field leaves its column behind; a renamed field\n * looks like an addition and the old column stays. That is the correct trade\n * for an automated path — the alternative is an unattended process that can\n * silently destroy a column. Destructive changes stay a deliberate,\n * human-reviewed migration. Because of that, this is safe to run on every boot,\n * and re-running it is a no-op.\n *\n * ## What changed when the planner arrived\n *\n * This used to read `Property` itself — its own reading of the type, of\n * `validation`, of relations, of enums — and disagreed with `db push` about all\n * of them. The audit found a required `author_id` that was NOT NULL after a\n * push and nullable after a boot, on the one path with no developer in the\n * loop. Now it reads the same {@link ColumnPlan} the DDL renderer does, so a\n * column's type, default, uniqueness and foreign key are decided once. What is\n * left here is the half that is genuinely this path's own: *what the database\n * already has*, and which of the planned constraints are safe to apply to it.\n */\nimport type { ColumnPlan, SchemaPlan, TablePlan } from \"./types\";\nimport { renderColumnDefinition, renderPgType } from \"./render-ddl\";\nimport { quoteSqlLiteral } from \"./plan-schema\";\nimport { SET_UPDATED_AT_FN, triggerStatements } from \"./updated-at-trigger\";\nimport {\n SEARCH_STAMP_PREFIX,\n SEARCH_TEXT_FN,\n SEARCH_UNACCENT_FN,\n searchColumnStamps,\n searchIndexStatements\n} from \"../search-column\";\nimport { collectionIndexStatement, sortIndexSpecs } from \"../collection-index\";\nimport { vectorIndexStatement, type SkippedVectorIndex } from \"../vector-index\";\nimport { typesAgree, type ColumnTypeDrift } from \"../column-type-drift\";\n\n/** Postgres identifiers this module is willing to interpolate. */\nconst SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;\n\n/**\n * Validation used to run only on the names read back OUT of the catalogue,\n * which is the direction that cannot hurt anyone: those came from Postgres. The\n * names going IN — the schema and table a collection declares — were quoted and\n * concatenated on trust, and quoting is not escaping. A table named\n * `x\" (id int); DROP TABLE users; --` closes the quote and the statement, and\n * the whole thing runs on the owner connection, which is the one connection in\n * the system that is exempt from every RLS policy.\n *\n * That is only a config file on a self-hosted project, where the person writing\n * it could run the SQL directly anyway. It is not only a config file where a\n * collection can be defined over the wire — the live-schema and source editors\n * both do that — and there the caller is an admin on the app, not an operator\n * of the database.\n */\nexport function assertSafeIdentifier(value: string, what: string): string {\n if (!SAFE_IDENTIFIER.test(value)) {\n throw new Error(`Refusing to build SQL with an unsafe ${what}: ${JSON.stringify(value)}`);\n }\n return value;\n}\n\n/** What the database currently has, as the planner needs it. */\nexport interface ExistingSchema {\n /** `schema.table` → set of column names. */\n tables: Map<string, Set<string>>;\n /** `schema.typename` of every enum type that already exists. */\n enums: Set<string>;\n /**\n * `schema.table.constraint` of every constraint that already exists.\n *\n * Optional so a caller that only cares about tables can still build one by\n * hand; absent is read as \"none known\", which at worst re-attempts a\n * constraint that then fails harmlessly as a duplicate.\n */\n constraints?: Set<string>;\n /**\n * `schema.table.column` → that column's comment, for the columns that have\n * one. This is where a generated search column's fingerprint lives.\n */\n columnComments?: Map<string, string>;\n /** `schema.typename` → its labels, in `enumsortorder`. */\n enumValues?: Map<string, string[]>;\n /** `schema.table.column` of every NOT NULL column. */\n notNullColumns?: Set<string>;\n /** `schema.table.column` of every column that has a DEFAULT. */\n columnDefaults?: Set<string>;\n /** `schema.table` of every table that holds at least one row. */\n populatedTables?: Set<string>;\n /**\n * `schema.table.column` → the type Postgres reports, as `udt_name` (plus a\n * modifier where one distinguishes two columns of the same family, e.g.\n * `numeric(10,2)`).\n */\n columnTypes?: Map<string, string>;\n /** `schema.table.trigger` of every trigger that already exists. */\n triggers?: Set<string>;\n}\n\n/**\n * How far the planner may go in making the database's constraints match the\n * configuration.\n *\n * - `additive` — the boot default. Columns, tables, indexes and enum values are\n * created; no existing column's constraints are touched. Unattended boots run\n * against customer data with nobody reading a diff, and a database adopted by\n * introspection legitimately carries NOT NULL on columns the generated\n * collection leaves optional (`introspect-db-logic` withholds `required` from\n * a column with a default or a trigger behind it). Converging there would\n * strip real constraints on first boot.\n * - `converge` — the live schema editor. Every statement is planned, shown to\n * the person making the change, and applied only once they confirm it.\n */\nexport type ConstraintPolicy = \"additive\" | \"converge\";\n\nexport interface DiffOptions {\n /** Defaults to `additive`. See {@link ConstraintPolicy}. */\n constraints?: ConstraintPolicy;\n}\n\nexport interface EnsureAction {\n kind: \"create-enum\" | \"create-table\" | \"add-column\" | \"add-constraint\" | \"rename-column\"\n | \"create-extension\" | \"create-function\" | \"create-index\" | \"comment-column\"\n | \"add-enum-value\" | \"set-not-null\" | \"drop-not-null\" | \"set-default\" | \"create-trigger\";\n /** Qualified target, for logging: `public.posts` or `public.posts.title`. */\n target: string;\n sql: string;\n}\n\n/** A NOT NULL column with no default that no property declares. */\nexport interface OrphanedRequiredColumn {\n /** `schema.table`. */\n table: string;\n /** The column left behind. */\n column: string;\n /** The collection that no longer declares it. */\n slug: string;\n}\n\n/** A constraint the configuration asks for that the planner is not applying. */\nexport interface WithheldConstraint {\n /** `schema.table.column`. */\n target: string;\n kind: \"not-null\";\n /**\n * Why, in a sentence that names the obstacle rather than the rule. The\n * reader is looking at a column that is nullable when they asked for\n * required, and needs to know what to do about it.\n */\n reason: string;\n /** What would make it applicable. */\n remedy: string;\n}\n\n/**\n * A generated search column built from a `search` block that has since changed.\n *\n * Reported instead of applied because the two ways to apply it are both worse\n * than stopping. `ALTER COLUMN … SET EXPRESSION` exists only on PG17+ and\n * rewrites the table either way; `DROP COLUMN` + `ADD COLUMN` rewrites it under\n * an ACCESS EXCLUSIVE lock and rebuilds the GIN index. This module runs\n * unattended against live customer data with nobody reading a diff, so a\n * multi-minute outage is not a decision it may take on its own.\n *\n * Not applying it silently is not an option either: a collection that added a\n * field, flipped `unaccent` or raised a weight kept indexing the *old* set\n * forever, and the only symptom was searches returning nothing for content\n * plainly in the row.\n */\nexport interface SearchColumnDrift {\n /** `schema.table`. */\n table: string;\n column: string;\n /** The fingerprint recorded on the column. */\n found: string;\n /** The fingerprint the current `search` block computes. */\n expected: string;\n /** The statements that would rebuild the column, for the operator to run. */\n rebuild: string[];\n}\n\n/** A relation column whose old and new spellings both plausibly apply. */\nexport interface LegacyForeignKey {\n /** `schema.table`. */\n table: string;\n /** The name the current rule derives, and what this plan would create. */\n expected: string;\n /** The name the old rule derived, which the table already has. */\n legacy: string;\n}\n\nexport interface EnsurePlan {\n actions: EnsureAction[];\n /** Every statement, in dependency order. Empty when the schema is current. */\n statements: string[];\n /**\n * Relation columns this plan is about to create where the table already\n * carries the same column under its pre-singularization name.\n *\n * Reported rather than silently handled: the ensure is additive, so it\n * would add `category_id` beside a populated `categorie_id` and the\n * relation would then read the new, empty one. No statement fails, no table\n * is missing, and the only symptom is relations resolving to nothing.\n */\n legacyForeignKeys: LegacyForeignKey[];\n /** @see SearchColumnDrift */\n searchDrift: SearchColumnDrift[];\n /**\n * Generated search columns that exist but carry no fingerprint — created\n * before this check existed, or by `search.sql` on an older CLI. The plan\n * stamps them so the *next* change is detectable.\n */\n searchAdopted: { table: string; column: string }[];\n /**\n * Vector columns this plan is deliberately leaving unindexed, because\n * pgvector cannot build an ANN index that wide. Reported rather than\n * thrown: the column is valid, storable and searchable.\n */\n vectorIndexSkipped: SkippedVectorIndex[];\n /**\n * Constraints the configuration asks for that this plan is not applying,\n * and why. Every one of these was previously withheld in silence.\n */\n withheldConstraints: WithheldConstraint[];\n /**\n * Columns whose type in the database is in a different family from the one\n * the collection declares. Reported and never acted on — this is the one\n * divergence that presents as a *working* deploy.\n */\n columnTypeDrift: ColumnTypeDrift[];\n /**\n * Columns that are NOT NULL, have no default, and that no property declares\n * any more — so every insert through the API is rejected for a field the\n * author cannot name, because they already deleted it. This is what a\n * **rename** looks like to an additive provisioner. Reported, never acted\n * on: dropping the column is the right fix roughly always and destructive\n * exactly once, which is not a decision to take unattended.\n */\n orphanedRequiredColumns: OrphanedRequiredColumn[];\n}\n\n/** Which pass a column belongs to. The order below is the order they run in. */\nconst isScalarProperty = (column: ColumnPlan): boolean =>\n (column.source.kind === \"property\" || column.source.kind === \"implicit-id\") && !column.primaryKey;\n\nexport function diffPlanAgainstCatalogue(\n plan: SchemaPlan,\n existing: ExistingSchema,\n options: DiffOptions = {}\n): EnsurePlan {\n const constraintPolicy: ConstraintPolicy = options.constraints ?? \"additive\";\n const actions: EnsureAction[] = [];\n const withheldConstraints: WithheldConstraint[] = [];\n const columnTypeDrift: ColumnTypeDrift[] = [];\n const legacyForeignKeys: LegacyForeignKey[] = [];\n const searchDrift: SearchColumnDrift[] = [];\n const searchAdopted: { table: string; column: string }[] = [];\n\n const collectionTables = plan.tables.filter(t => t.kind === \"collection\");\n const junctionTables = plan.tables.filter(t => t.kind === \"junction\");\n\n // 1. Enum types. `CREATE TYPE` has no IF NOT EXISTS, so an existing type is\n // skipped by name rather than guarded in SQL.\n for (const enumPlan of plan.enums) {\n assertSafeIdentifier(enumPlan.schema, \"schema name\");\n if (existing.enums.has(enumPlan.qualified)) {\n // The type is there, but that says nothing about its *values*.\n // Skipping the whole type by name is what made an added enum value\n // vanish: nothing was planned, the boot reported success, and the\n // first row using the value was rejected by a type that had never\n // heard of it. `ADD VALUE` is the one alteration Postgres offers\n // here, it is purely additive, and it is idempotent.\n //\n // `enumValues` absent means the caller built the schema by hand and\n // does not know the values; skip by name as before.\n const current = existing.enumValues?.get(enumPlan.qualified);\n if (!current) continue;\n for (const value of enumPlan.labels) {\n if (current.includes(value)) continue;\n actions.push({\n kind: \"add-enum-value\",\n target: `${enumPlan.qualified}.${value}`,\n // Not inside a transaction with any use of the value:\n // Postgres refuses to read a value added by the transaction\n // still adding it. The applier runs these one statement at a\n // time, which is what makes it legal.\n sql: `ALTER TYPE \"${enumPlan.schema}\".\"${enumPlan.name}\" ADD VALUE IF NOT EXISTS ${quoteSqlLiteral(value)};`\n });\n }\n continue;\n }\n actions.push({\n kind: \"create-enum\",\n target: enumPlan.qualified,\n sql: `CREATE TYPE \"${enumPlan.schema}\".\"${enumPlan.name}\" AS ENUM (${enumPlan.labels.map(quoteSqlLiteral).join(\", \")});`\n });\n }\n\n // 1b. Extensions and helper functions, before the tables and columns that\n // reference them: a generated column's expression is resolved when the\n // column is created, so a table whose search column calls\n // `rebase_search_text` cannot be added before that function exists.\n // Both forms are idempotent, so a boot against a database that already\n // has them plans nothing.\n for (const statement of plan.extensions) {\n actions.push({\n kind: \"create-extension\",\n target: statement.replace(/^CREATE EXTENSION IF NOT EXISTS |;$/g, \"\"),\n sql: statement\n });\n }\n for (const statement of plan.functions) {\n actions.push({ kind: \"create-function\", target: functionTarget(statement), sql: statement });\n }\n\n // 2. Missing tables. Only the identity column is created here; every other\n // column is added by step 3, so a new table and an existing table that\n // gained a field travel the exact same code path. One way to build a\n // column means one way for it to be wrong.\n const created = new Set<string>();\n for (const table of collectionTables) {\n if (existing.tables.has(table.qualified) || created.has(table.qualified)) continue;\n created.add(table.qualified);\n const schema = assertSafeIdentifier(table.schema, \"schema name\");\n const name = assertSafeIdentifier(table.table, \"table name\");\n const id = table.columns.find(c => c.primaryKey);\n const definition = id\n ? `\"${assertSafeIdentifier(id.column, \"column name\")}\" ${renderColumnDefinition(id)}`\n : '\"id\" TEXT PRIMARY KEY';\n actions.push({\n kind: \"create-table\",\n target: table.qualified,\n sql: `CREATE TABLE IF NOT EXISTS \"${schema}\".\"${name}\" (${definition});`\n });\n }\n\n // 2b. Junction tables behind many-to-many relations. No collection declares\n // them, so until they existed an m2m write had nowhere to land and the\n // junction's derived RLS had nothing to attach to. Both columns are\n // created here — unlike a collection table, whose CREATE declares only\n // the identity column — because there is nothing else to them.\n for (const table of junctionTables) {\n if (existing.tables.has(table.qualified) || created.has(table.qualified)) continue;\n created.add(table.qualified);\n const columns = table.columns\n .map(c => `\"${c.column}\" ${renderColumnDefinition(c)}`)\n .join(\", \");\n actions.push({\n kind: \"create-table\",\n target: table.qualified,\n sql: `CREATE TABLE IF NOT EXISTS \"${table.schema}\".\"${table.table}\" (${columns}` +\n `, PRIMARY KEY (${table.primaryKey.map(c => `\"${c}\"`).join(\", \")}));`\n });\n }\n\n const addColumn = (table: TablePlan, column: string, definition: string): void => {\n if (existing.tables.get(table.qualified)?.has(column)) return;\n // Same reason as `assertSafeIdentifier` above: a column name reaching\n // here came from a property declaration, which on the editor paths came\n // over the wire. `definition` is built by the renderer from a closed set\n // of type mappings and is not caller text.\n assertSafeIdentifier(column, \"column name\");\n actions.push({\n kind: \"add-column\",\n target: `${table.qualified}.${column}`,\n sql: `ALTER TABLE \"${table.schema}\".\"${table.table}\" ADD COLUMN IF NOT EXISTS \"${column}\" ${definition};`\n });\n };\n\n /**\n * Move a column that is only missing because it was renamed.\n *\n * Returns true when it handled the column, so the caller skips the ordinary\n * ADD. Adding would be the wrong move and a quiet one: the data is in the\n * old column, `ADD COLUMN` creates the new one empty beside it, every\n * statement succeeds, and the relation reads the empty one. A rename is\n * metadata-only in Postgres, keeps the values, and carries the column's\n * indexes and constraints with it.\n */\n const renameLegacyColumn = (table: TablePlan, column: ColumnPlan): boolean => {\n const present = existing.tables.get(table.qualified);\n if (!column.legacyColumn || !present) return false;\n if (present.has(column.column) || !present.has(column.legacyColumn)) return false;\n legacyForeignKeys.push({ table: table.qualified, expected: column.column, legacy: column.legacyColumn });\n actions.push({\n kind: \"rename-column\",\n target: `${table.qualified}.${column.column}`,\n sql: `ALTER TABLE \"${table.schema}\".\"${table.table}\" RENAME COLUMN \"${column.legacyColumn}\" TO \"${column.column}\";`\n });\n return true;\n };\n\n /**\n * A `NOT NULL` is safe exactly when it cannot fail against rows that are\n * already there, and there are three ways to know that:\n *\n * - the table is being created by this plan (no rows yet);\n * - the table exists and is empty;\n * - the column arrives with a DEFAULT, which Postgres backfills into every\n * existing row as part of ADD COLUMN.\n *\n * `populatedTables` absent means the caller does not know, and not knowing\n * has to read as \"assume rows\" — the other direction emits a NOT NULL that\n * is checked against live data and aborts the boot. Written as an explicit\n * `!== undefined` because the optional-chain form quietly says *empty* when\n * the fact is missing, which is the wrong way to be wrong.\n */\n const tableIsEmpty = (table: TablePlan): boolean =>\n existing.populatedTables !== undefined\n && existing.tables.has(table.qualified)\n && !existing.populatedTables.has(table.qualified);\n\n /**\n * Plan one column, with the constraints this database can safely take.\n *\n * The definition comes from the same renderer `schema.sql` uses, minus the\n * constraints that are checked against live rows. That subtraction is the\n * whole of what this path is allowed to decide for itself.\n */\n const planColumn = (table: TablePlan, column: ColumnPlan): void => {\n const key = `${table.qualified}.${column.column}`;\n const columnExists = existing.tables.get(table.qualified)?.has(column.column) === true;\n const fresh = created.has(table.qualified);\n const empty = tableIsEmpty(table);\n const required = !column.nullable;\n const hasDefault = column.default !== undefined;\n\n // The column is there and holds a different kind of value than the\n // collection says it does. Reported, never altered: an unattended\n // `ALTER COLUMN … TYPE` over customer data is not a thing to do\n // quietly, and the *quiet* is what this fixes. A deploy that changed a\n // `columnType` used to report success while the column stayed as it\n // was, and the divergence surfaced later as every write failing.\n // A column whose definition is owned elsewhere (auth, or a generated\n // search column) is not compared: the declaration there is a rendered\n // string rather than a type, and auth's own reconcile owns it.\n const declaredType = renderPgType(column.type);\n const actualType = existing.columnTypes?.get(key);\n if (columnExists && !column.sqlDefinition && actualType && !typesAgree(declaredType, actualType)) {\n columnTypeDrift.push({ table: table.qualified, column: column.column, declared: declaredType, actual: actualType });\n }\n\n // A table this run is creating has no rows yet, so the constraints\n // `db push` writes are free to apply. On a table that already exists\n // they are not: `SET NOT NULL` is checked against live rows and a UNIQUE\n // would fail on existing duplicates. So the constraints are emitted for\n // the fresh case — which is the whole managed-runtime path, and the one\n // that diverged from `db push` — and withheld for the adopted one.\n const notNullIsSafe = fresh || empty || hasDefault;\n const applicable: ColumnPlan = {\n ...column,\n unique: column.unique && fresh,\n nullable: column.nullable || !(notNullIsSafe || columnExists)\n };\n if (required && !columnExists && !notNullIsSafe) {\n withheldConstraints.push({\n target: key,\n kind: \"not-null\",\n reason: column.source.kind === \"relation\" || column.source.kind === \"reference\"\n ? `\"${column.column}\" is a required link, but \"${table.qualified}\" already holds rows and ` +\n \"the column has no default to backfill them with, so NOT NULL would be checked \" +\n \"against data that does not have a value yet.\"\n : `\"${column.column}\" is required, but \"${table.qualified}\" already holds rows and the column ` +\n \"has no default to backfill them with, so NOT NULL would be checked \" +\n \"against data that does not have a value yet.\",\n remedy: column.source.kind === \"relation\" || column.source.kind === \"reference\"\n ? \"Backfill the column, then add the constraint — or make the relation optional.\"\n : \"Backfill the column, then add the constraint — or give the property a \" +\n \"default so every existing row gets one.\"\n });\n }\n addColumn(table, column.column, renderColumnDefinition(applicable));\n\n if (!columnExists) return;\n\n // ── The column is already there and only a modifier differs ──────────\n // A DEFAULT binds future writes only, so `SET DEFAULT` cannot fail and\n // cannot touch a row that already exists. That makes it the one\n // convergence this path may do unattended — and it has to, because\n // `ADD COLUMN IF NOT EXISTS` is a no-op against an existing column, so\n // a `defaultValue` added to a live collection would otherwise never\n // reach the database at all.\n if (column.default && column.default.kind !== \"identity\" && !column.generated) {\n const expression = column.default.kind === \"sql\" ? column.default.expression : column.default.sql;\n if (!existing.columnDefaults?.has(key)) {\n actions.push({\n kind: \"set-default\",\n target: key,\n sql: `ALTER TABLE \"${table.schema}\".\"${table.table}\" ALTER COLUMN \"${column.column}\" SET DEFAULT ${expression};`\n });\n }\n }\n\n // Two directions on NOT NULL, and they are not equally safe — see\n // `ConstraintPolicy` for why neither runs at an unattended boot.\n if (constraintPolicy !== \"converge\") return;\n const isNotNull = existing.notNullColumns?.has(key) === true;\n if (required && !isNotNull) {\n if (empty) {\n actions.push({\n kind: \"set-not-null\",\n target: key,\n sql: `ALTER TABLE \"${table.schema}\".\"${table.table}\" ALTER COLUMN \"${column.column}\" SET NOT NULL;`\n });\n } else {\n withheldConstraints.push({\n target: key,\n kind: \"not-null\",\n reason:\n `\"${column.column}\" became required, but \"${table.qualified}\" holds rows and any of them ` +\n \"with no value would make SET NOT NULL fail.\",\n remedy:\n \"Backfill the column first — `UPDATE … SET \\\"\" + column.column +\n \"\\\" = … WHERE \\\"\" + column.column + \"\\\" IS NULL` — then apply this again.\"\n });\n }\n }\n if (!required && isNotNull) {\n // Loosening never fails and never loses data. It is here rather\n // than at boot because a database adopted by introspection carries\n // NOT NULL on columns the generated collection deliberately leaves\n // optional, and converging those unasked would drop constraints\n // nobody edited.\n actions.push({\n kind: \"drop-not-null\",\n target: key,\n sql: `ALTER TABLE \"${table.schema}\".\"${table.table}\" ALTER COLUMN \"${column.column}\" DROP NOT NULL;`\n });\n }\n };\n\n // 3. Scalar columns, then the auth columns the collection never mentions.\n // The scaffold's users collection describes 12 of the 14 columns auth\n // reads and writes, so planning only from properties left `is_anonymous`\n // and `tokens_valid_after` to `ensureAuthTablesExist` — which does create\n // them, but only because that function happens to run later in the same\n // boot. Planning them here makes this path self-contained.\n for (const table of collectionTables) {\n assertSafeIdentifier(table.schema, \"schema name\");\n assertSafeIdentifier(table.table, \"table name\");\n for (const column of table.columns) {\n if (!isScalarProperty(column)) continue;\n planColumn(table, column);\n }\n for (const column of table.columns) {\n if (column.source.kind !== \"auth\") continue;\n addColumn(table, column.column, renderColumnDefinition(column));\n }\n }\n\n // 3a. The generated search columns.\n //\n // Adding a STORED generated column rewrites the table, which on a large\n // one is not free — but it is the same additive shape as every other\n // column here, and the alternative (leaving it out until someone runs a\n // migration) is a declared `search` block that silently does nothing.\n //\n // Changing one is not additive, and `ADD COLUMN IF NOT EXISTS` is a\n // no-op against a column that is already there — which is why a `search`\n // block that gained a field, flipped `unaccent` or moved a weight used\n // to be inert forever, on every path, with nothing logged. Each column\n // carries a fingerprint of the expression it was built from, and a\n // mismatch is reported rather than applied.\n for (const table of collectionTables) {\n if (!table.search) continue;\n const definitions = new Map(\n table.columns\n .filter(c => c.source.kind === \"search\")\n .map(c => [c.column, renderColumnDefinition(c)] as const)\n );\n for (const stamp of searchColumnStamps(table.search)) {\n const definition = definitions.get(stamp.column)!;\n const exists = existing.tables.get(table.qualified)?.has(stamp.column) === true;\n const recorded = existing.columnComments?.get(`${table.qualified}.${stamp.column}`);\n\n if (exists && recorded?.startsWith(SEARCH_STAMP_PREFIX) && recorded !== stamp.fingerprint) {\n searchDrift.push({\n table: table.qualified,\n column: stamp.column,\n found: recorded,\n expected: stamp.fingerprint,\n rebuild: [\n `ALTER TABLE \"${table.schema}\".\"${table.table}\" DROP COLUMN \"${stamp.column}\";`,\n `ALTER TABLE \"${table.schema}\".\"${table.table}\" ADD COLUMN \"${stamp.column}\" ${definition};`,\n stamp.sql\n ]\n });\n // The old stamp is the only evidence of what the column holds;\n // overwriting it here would erase the drift instead of fixing it.\n continue;\n }\n\n addColumn(table, stamp.column, definition);\n if (exists && recorded === undefined) {\n searchAdopted.push({ table: table.qualified, column: stamp.column });\n }\n if (recorded !== stamp.fingerprint) {\n actions.push({ kind: \"comment-column\", target: `${table.qualified}.${stamp.column}`, sql: stamp.sql });\n }\n }\n }\n\n // 3b. A junction that already existed, but is short a column. One created\n // above already carries both, so re-listing them would log two no-op\n // statements and inflate the count of changes applied.\n for (const table of junctionTables) {\n if (created.has(table.qualified)) continue;\n for (const column of table.columns) {\n if (renameLegacyColumn(table, column)) continue;\n // A payload column (`through.properties`) goes through `planColumn`,\n // the same pass a collection's scalar columns take. The bare\n // `ADD COLUMN <type>` below is right for the two key columns — they\n // are NOT NULL by the composite primary key and have no default —\n // and wrong for everything else: it would drop a `defaultValue`, and\n // it would either omit a NOT NULL the collection declared or apply\n // one to a junction that already holds rows without a value to\n // backfill them. `planColumn` is the one place that decides which of\n // those is safe, and it reports the constraint it withheld.\n if (column.source.kind === \"property\") {\n planColumn(table, column);\n continue;\n }\n addColumn(table, column.column, renderPgType(column.type));\n }\n }\n\n // 3c. The columns relation and reference properties own.\n for (const table of collectionTables) {\n for (const column of table.columns) {\n if (column.source.kind !== \"relation\" && column.source.kind !== \"reference\") continue;\n // A declared property already emits this column (an explicit\n // `postId` beside the `belongsTo` that uses it); the relation\n // contributes only the constraint, below.\n if (column.columnOwnedByProperty) continue;\n if (renameLegacyColumn(table, column)) continue;\n planColumn(table, column);\n }\n }\n\n // 4. Foreign keys, last: the tables and columns on both ends have to exist\n // first, and a constraint is the one thing here that can fail on data\n // rather than on schema, so nothing else depends on it.\n const knownConstraints = existing.constraints ?? new Set<string>();\n const plannedConstraints = new Set<string>();\n for (const table of [...collectionTables, ...junctionTables]) {\n for (const column of table.columns) {\n const fk = column.foreignKey;\n if (!fk) continue;\n const name = `${fk.schema}.${fk.table}.${fk.constraintName}`;\n if (knownConstraints.has(name) || plannedConstraints.has(name)) continue;\n plannedConstraints.add(name);\n actions.push({ kind: \"add-constraint\", target: name, sql: `${fk.sql};` });\n }\n }\n\n // 5. Indexes, after everything — the column has to exist, and this is the\n // one step that runs against a populated table for real work.\n //\n // CONCURRENTLY: a plain CREATE INDEX takes a lock that blocks writes for\n // the duration of the build, which on a live table is an outage. Each\n // statement here is issued on its own, outside any transaction, which is\n // the condition CONCURRENTLY requires.\n //\n // ...and only on a live table. It is withheld for a table this same plan\n // is creating: there are no rows to build from and no writer to block, so\n // the lock CONCURRENTLY avoids is a lock nobody would have taken. Worth\n // withholding rather than merely harmless, because CONCURRENTLY is the\n // one index form Postgres refuses inside a transaction block.\n const concurrent = (schema: string, table: string): boolean => !created.has(`${schema}.${table}`);\n for (const table of collectionTables) {\n if (!table.search) continue;\n for (const statement of searchIndexStatements(table.search)) {\n actions.push({\n kind: \"create-index\",\n target: table.qualified,\n sql: concurrent(table.schema, table.table)\n ? statement.replace(\"CREATE INDEX IF NOT EXISTS\", \"CREATE INDEX CONCURRENTLY IF NOT EXISTS\")\n : statement\n });\n }\n }\n\n // ANN indexes for vector columns, on the same terms. A column too wide\n // for pgvector to index is reported, not planned — silence there would\n // read as \"indexed\" to anyone watching the boot.\n const vectorIndexSkipped: SkippedVectorIndex[] = [];\n for (const table of collectionTables) {\n if (!table.vector) continue;\n for (const spec of table.vector.specs) {\n actions.push({\n kind: \"create-index\",\n target: `${spec.schema}.${spec.table}`,\n sql: concurrent(spec.schema, spec.table)\n ? vectorIndexStatement(spec).replace(\"CREATE INDEX IF NOT EXISTS\", \"CREATE INDEX CONCURRENTLY IF NOT EXISTS\")\n : vectorIndexStatement(spec)\n });\n }\n vectorIndexSkipped.push(...table.vector.skipped);\n }\n\n // Declared indexes, on exactly the same terms. Boot has to emit these,\n // not just `db push`: the managed runtime provisions at boot and never\n // runs a push, so a push-only index would simply not exist there — and\n // nothing would say so. `contracts/derived-names.txt` states the rule\n // (\"Both, or it is a bug\") and the gate enforces it.\n //\n // `concurrently` is a parameter rather than a string replacement on the\n // rendered SQL: the `.replace(…)` above silently does nothing for a\n // UNIQUE index, whose text is `CREATE UNIQUE INDEX …`.\n for (const spec of sortIndexSpecs(collectionTables.flatMap(t => t.indexes))) {\n actions.push({\n kind: \"create-index\",\n target: `${spec.schema}.${spec.table}`,\n sql: collectionIndexStatement(spec, {\n concurrently: concurrent(spec.schema, spec.table),\n ifNotExists: true\n })\n });\n }\n\n // 6. `autoValue: \"on_update\"` triggers. After the column, and idempotent by\n // DROP-then-CREATE rather than `CREATE OR REPLACE TRIGGER`, which exists\n // only on Postgres 14+.\n for (const table of collectionTables) {\n for (const trigger of table.triggers) {\n // Named after its table and column, so a trigger already in the\n // catalogue is this one — re-issuing it every boot would work and\n // would report a change on a database that has none.\n if (existing.triggers?.has(`${table.qualified}.${trigger.name}`)) continue;\n for (const statement of triggerStatements(trigger)) {\n actions.push({\n kind: \"create-trigger\",\n target: `${table.qualified}.${trigger.name}`,\n sql: statement\n });\n }\n }\n }\n\n // A column the database still requires that no property declares any more.\n //\n // Computed last, over the same live snapshot the rest of the plan read, and\n // only for tables this run did not create — a table created here has exactly\n // the columns the collection asked for, so there is nothing to orphan.\n //\n // Every element of the test matters. NOT NULL, because a nullable leftover\n // accepts a write and is merely untidy. No DEFAULT, because a leftover with\n // one is filled in for you. Not declared, because that is what makes it\n // unreachable — the author has no field to send.\n const orphanedRequiredColumns: OrphanedRequiredColumn[] = [];\n if (existing.notNullColumns && existing.columnDefaults) {\n for (const table of collectionTables) {\n const live = existing.tables.get(table.qualified);\n if (!live || created.has(table.qualified)) continue;\n const declared = new Set<string>();\n for (const column of table.columns) {\n declared.add(column.column);\n if (column.legacyColumn) declared.add(column.legacyColumn);\n }\n for (const column of live) {\n const key = `${table.qualified}.${column}`;\n if (declared.has(column)) continue;\n if (!existing.notNullColumns.has(key)) continue;\n if (existing.columnDefaults.has(key)) continue;\n orphanedRequiredColumns.push({ table: table.qualified, column, slug: table.slug! });\n }\n }\n }\n\n return {\n actions,\n statements: actions.map(a => a.sql),\n legacyForeignKeys,\n searchDrift,\n searchAdopted,\n vectorIndexSkipped,\n withheldConstraints,\n columnTypeDrift,\n orphanedRequiredColumns\n };\n}\n\n/** What a `CREATE FUNCTION` statement is called, for the action log. */\nconst functionTarget = (statement: string): string => {\n if (statement.includes(\"set_updated_at\")) return SET_UPDATED_AT_FN;\n return statement.includes(\"unaccent\") ? SEARCH_UNACCENT_FN : SEARCH_TEXT_FN;\n};\n","/**\n * Applying a schema plan to a database that is already running.\n *\n * ## What this module is\n *\n * A managed runtime boots someone else's compiled project against a database it\n * has never seen. Auth tables are ensured at boot already, but collection tables\n * were not created by anything: the platform ran the app and every `/api/data/*`\n * request answered 500 on a missing relation. `rebase db push` cannot help — it\n * is an Atlas-driven CLI command, and the runtime image ships no CLI.\n *\n * Two halves, and only one of them is here. *What the collections ask for* is\n * `schema/plan/plan-schema.ts`, shared with `db push` and the generated Drizzle\n * file; *what the database already has, and which of those statements are safe\n * to run against it* is `schema/plan/diff-plan.ts`. This module reads the\n * catalogue, runs the statements, and reports what happened.\n *\n * ## Why additive-only, forever\n *\n * This runs unattended, against a database with customers' data in it, with no\n * human reading a diff. So it may only ever do things that cannot lose data.\n * See `diff-plan.ts` for the whole of that argument.\n */\nimport {\n declaredDatabaseExtensions,\n REBASE_SCHEMA,\n type CollectionConfig\n} from \"@rebasepro/types\";\nimport { relationalCollections } from \"@rebasepro/common\";\nimport { logger, isConcurrentDdlRace, isDuplicateObjectRace } from \"@rebasepro/server\";\nimport { SEARCH_STAMP_PREFIX } from \"./search-column\";\nimport { vectorExtensionHint } from \"./vector-index\";\nimport { planJunctionTables, quoteSqlLiteral } from \"./generate-postgres-ddl-logic\";\nimport { planSchema } from \"./plan/plan-schema\";\nimport {\n assertSafeIdentifier,\n diffPlanAgainstCatalogue,\n type ConstraintPolicy,\n type DiffOptions,\n type EnsureAction,\n type EnsurePlan,\n type ExistingSchema,\n type LegacyForeignKey,\n type OrphanedRequiredColumn,\n type SearchColumnDrift,\n type WithheldConstraint\n} from \"./plan/diff-plan\";\nimport { extractCauseMessage, extractPgError } from \"../utils/pg-error-utils\";\nimport { columnTypeDriftMessage, type ColumnTypeDrift } from \"./column-type-drift\";\n\nexport type {\n ConstraintPolicy,\n EnsureAction,\n EnsurePlan,\n ExistingSchema,\n LegacyForeignKey,\n OrphanedRequiredColumn,\n SearchColumnDrift,\n WithheldConstraint\n};\n\n/**\n * The subset of a database handle this needs: run a statement, get rows back.\n *\n * Deliberately parameterless. Everything here is DDL or catalogue reads keyed by\n * schema name, and schema names are identifiers — they cannot be bound as\n * parameters anyway. They are validated by `assertSafeIdentifier` before they\n * reach a statement, so a config that somehow carried a quote is refused rather\n * than concatenated.\n */\nexport interface Queryable {\n query<T = unknown>(sql: string): Promise<{ rows: T[] }>;\n}\n\nexport interface EnsureOptions extends DiffOptions {\n /**\n * Server extensions the project's databases gave Rebase leave to install —\n * `declaredDatabaseExtensions()`. Absent means none, which is a refusal and\n * is the right default for a planner given no configuration at all.\n *\n * Explicit rather than read from the resource registry in here, because the\n * planner is pure and several callers plan against fixtures: reaching for a\n * process-wide registry would make the plan depend on whatever some other\n * module happened to import. `ensureCollectionTables` is the boundary that\n * reads the world.\n */\n databaseExtensions?: readonly string[];\n}\n\nexport interface EnsureOutcome extends EnsurePlan {\n /**\n * Actions that could not be applied and are non-fatal by nature.\n *\n * Two kinds qualify. A foreign key can only fail on data that already\n * violates it, and the column it would police exists either way, so the\n * collection still serves; refusing to boot over one would turn a\n * pre-existing data problem into an outage. A column comment is the search\n * fingerprint, which needs table ownership — losing it costs drift\n * detection on the next boot, not the deployment. Both are reported loudly.\n */\n failures: { kind: EnsureAction[\"kind\"]; target: string; error: string }[];\n}\n\n/** The schema a collection lives in, validated before it reaches any DDL. */\nfunction schemaOf(collection: CollectionConfig): string {\n const schema = (collection as { schema?: string }).schema || \"public\";\n return assertSafeIdentifier(schema, \"schema name\");\n}\n\n/**\n * Decide what to add. Pure — the caller supplies what exists and runs the\n * result.\n *\n * A plan and a diff: the collections are read once, by `planSchema`, into the\n * same {@link SchemaPlan} `db push` renders `schema.sql` from, and the diff\n * subtracts what the database already has. Before that split this function had\n * its own reading of every `Property`, and the audit found twelve places where\n * it disagreed with the two generators — a required `author_id` that was\n * NOT NULL after a push and nullable after a boot among them, on the one path\n * with no developer in the loop.\n */\nexport function planCollectionSchemaEnsure(\n allCollections: CollectionConfig[],\n existing: ExistingSchema,\n options: EnsureOptions = {}\n): EnsurePlan {\n const plan = planSchema(allCollections, { databaseExtensions: options.databaseExtensions });\n return diffPlanAgainstCatalogue(plan, existing, { constraints: options.constraints });\n}\n\n/** Read what the database has, for the schemas the collections live in. */\nexport async function readExistingSchema(\n client: Queryable,\n schemas: string[]\n): Promise<ExistingSchema> {\n const tables = new Map<string, Set<string>>();\n const enums = new Set<string>();\n if (schemas.length === 0) return { tables, enums };\n\n const inList = schemas\n .map(schema => `'${assertSafeIdentifier(schema, \"schema name\")}'`)\n .join(\", \");\n\n const notNullColumns = new Set<string>();\n // `udt_name` rather than `data_type`: `data_type` collapses every array to\n // the literal string `ARRAY` and every extension type to `USER-DEFINED`,\n // which cannot be compared with anything. `udt_name` names the actual type\n // — `int4`, `jsonb`, `_numeric`, `vector` — which is what the drift check\n // needs.\n const columnTypes = new Map<string, string>();\n // A NOT NULL column that has a DEFAULT is not a problem for a write that\n // omits it, so orphan detection needs the default as well as the nullability\n // — otherwise every `created_at DEFAULT now()` on a table whose collection\n // does not declare it would be reported as a blocker.\n const columnDefaults = new Set<string>();\n const { rows: columns } = await client.query<{\n table_schema: string;\n table_name: string;\n column_name: string;\n is_nullable: string;\n udt_name: string | null;\n column_default: string | null;\n numeric_precision: number | null;\n numeric_scale: number | null;\n }>(\n // `numeric_precision`/`numeric_scale` because `udt_name` is `numeric`\n // for both `NUMERIC` and `NUMERIC(10, 2)`, and a property that declares\n // a precision means it: money stored in an unbounded column keeps the\n // third decimal the rounding was supposed to remove. Only carried for\n // `numeric`, where the modifier changes what a value *is*; a `varchar`\n // width is a limit on the same family and `typesAgree` ignores it.\n `SELECT table_schema, table_name, column_name, is_nullable, udt_name, column_default,\n numeric_precision, numeric_scale\n FROM information_schema.columns\n WHERE table_schema IN (${inList})`\n );\n for (const row of columns) {\n const key = `${row.table_schema}.${row.table_name}`;\n if (!tables.has(key)) tables.set(key, new Set());\n tables.get(key)!.add(row.column_name);\n if (row.is_nullable === \"NO\") notNullColumns.add(`${key}.${row.column_name}`);\n if (row.udt_name) {\n const modifier = row.udt_name === \"numeric\" && row.numeric_precision !== null\n ? `(${row.numeric_precision},${row.numeric_scale ?? 0})`\n : \"\";\n columnTypes.set(`${key}.${row.column_name}`, `${row.udt_name}${modifier}`);\n }\n if (row.column_default !== null) columnDefaults.add(`${key}.${row.column_name}`);\n }\n\n // Trigger names, so `autoValue: \"on_update\"` is installed once rather than\n // re-issued on every boot. `tgisinternal` excludes the ones Postgres itself\n // creates to enforce foreign keys.\n const triggers = new Set<string>();\n const { rows: triggerRows } = await client.query<{ schema: string; table: string; name: string }>(\n `SELECT n.nspname AS schema, c.relname AS table, t.tgname AS name\n FROM pg_trigger t\n JOIN pg_class c ON t.tgrelid = c.oid\n JOIN pg_namespace n ON c.relnamespace = n.oid\n WHERE NOT t.tgisinternal AND n.nspname IN (${inList})`\n );\n for (const row of triggerRows) triggers.add(`${row.schema}.${row.table}.${row.name}`);\n\n // Which tables hold rows. This is the only fact that decides whether a\n // NOT NULL can be added without reading the data, so it is worth a query.\n //\n // `reltuples` would be cheaper and is wrong for this: it is a planner\n // estimate, it is -1 on a table that has never been analyzed, and a table\n // that was full an hour ago still reads as full after a DELETE. A wrong\n // \"empty\" here means a boot that aborts on a constraint violation, so the\n // estimate is not good enough. `EXISTS … LIMIT 1` stops at the first row,\n // which makes the true cost one page read per table.\n //\n // Restricted to ordinary and partitioned tables: `information_schema.columns`\n // also lists views and materialized views, and probing those runs whatever\n // query defines them.\n const populatedTables = new Set<string>();\n const { rows: realTables } = await client.query<{ schema: string; name: string }>(\n `SELECT n.nspname AS schema, c.relname AS name\n FROM pg_class c\n JOIN pg_namespace n ON c.relnamespace = n.oid\n WHERE c.relkind IN ('r', 'p') AND n.nspname IN (${inList})`\n );\n if (realTables.length > 0) {\n const probes = realTables.map(row => {\n const schema = assertSafeIdentifier(row.schema, \"schema name\");\n const table = assertSafeIdentifier(row.name, \"table name\");\n return `SELECT ${quoteSqlLiteral(`${schema}.${table}`)} AS key, ` +\n `EXISTS(SELECT 1 FROM \"${schema}\".\"${table}\" LIMIT 1) AS populated`;\n });\n const { rows: populationRows } = await client.query<{ key: string; populated: boolean }>(\n probes.join(\" UNION ALL \")\n );\n for (const row of populationRows) {\n if (row.populated) populatedTables.add(row.key);\n }\n }\n\n const enumValues = new Map<string, string[]>();\n const { rows: enumValueRows } = await client.query<{\n schema: string;\n name: string;\n value: string;\n }>(\n // Ordered by `enumsortorder`, not by label: an enum's order is part of\n // its meaning (it is what `<` compares), and reading it back sorted\n // alphabetically would make a correct type look drifted.\n `SELECT n.nspname AS schema, t.typname AS name, e.enumlabel AS value\n FROM pg_enum e\n JOIN pg_type t ON e.enumtypid = t.oid\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE n.nspname IN (${inList})\n ORDER BY t.typname, e.enumsortorder`\n );\n for (const row of enumValueRows) {\n const key = `${row.schema}.${row.name}`;\n if (!enumValues.has(key)) enumValues.set(key, []);\n enumValues.get(key)!.push(row.value);\n }\n\n const { rows: enumRows } = await client.query<{ schema: string; name: string }>(\n `SELECT n.nspname AS schema, t.typname AS name\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE t.typtype = 'e' AND n.nspname IN (${inList})`\n );\n for (const row of enumRows) enums.add(`${row.schema}.${row.name}`);\n\n // `ADD CONSTRAINT` has no IF NOT EXISTS, so an existing foreign key is\n // skipped by name rather than guarded in SQL.\n const constraints = new Set<string>();\n const { rows: constraintRows } = await client.query<{\n schema: string;\n table: string;\n name: string;\n }>(\n `SELECT n.nspname AS schema, c.relname AS table, con.conname AS name\n FROM pg_constraint con\n JOIN pg_class c ON con.conrelid = c.oid\n JOIN pg_namespace n ON c.relnamespace = n.oid\n WHERE n.nspname IN (${inList})`\n );\n for (const row of constraintRows) constraints.add(`${row.schema}.${row.table}.${row.name}`);\n\n // Column comments, which is where a generated search column records the\n // expression it was built from. `objsubid > 0` is what makes a row a\n // *column* comment rather than the table's own.\n const columnComments = new Map<string, string>();\n const { rows: commentRows } = await client.query<{\n schema: string;\n table: string;\n column: string;\n comment: string | null;\n }>(\n `SELECT n.nspname AS schema, c.relname AS table, a.attname AS column, d.description AS comment\n FROM pg_description d\n JOIN pg_class c ON d.objoid = c.oid\n JOIN pg_namespace n ON c.relnamespace = n.oid\n JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = d.objsubid\n WHERE d.objsubid > 0 AND n.nspname IN (${inList})`\n );\n for (const row of commentRows) {\n if (row.comment == null) continue;\n columnComments.set(`${row.schema}.${row.table}.${row.column}`, row.comment);\n }\n\n return {\n tables, enums, constraints, columnComments, enumValues, notNullColumns, populatedTables, columnTypes,\n columnDefaults, triggers\n };\n}\n\n/**\n * What to tell an operator whose `search` block no longer matches its column.\n *\n * Every line here is doing work: naming the collection is not enough, because\n * the symptom (a search that finds nothing) points at the data, not the schema;\n * and the remediation has to be exact, because it is a table rewrite the\n * operator is being asked to schedule rather than discover.\n */\nfunction searchDriftMessage(drift: SearchColumnDrift[]): string {\n const blocks = drift.map(d =>\n ` \"${d.table}\".\"${d.column}\" was generated from a different \\`search\\` block ` +\n `(recorded ${d.found}, current ${d.expected}).\\n` +\n d.rebuild.map(s => ` ${s}`).join(\"\\n\")\n );\n return (\n \"The `search` block changed after its generated column was created, and Postgres cannot alter a \" +\n \"generated expression in place.\\n\" +\n \"Rebase will not rebuild it for you: dropping and re-adding a STORED generated column rewrites the whole \" +\n \"table under an ACCESS EXCLUSIVE lock and rebuilds its GIN index, which is an outage this unattended path \" +\n \"may not schedule on your behalf.\\n\" +\n \"Until it is rebuilt the column keeps indexing the previous fields, weights and language — searches for \" +\n \"anything added since return nothing, which reads from outside as \\\"no such row\\\".\\n\" +\n \"Run these (or revert the block to what the column was built from), then boot again:\\n\" +\n blocks.join(\"\\n\") +\n \"\\n The GIN index is dropped with the column and recreated concurrently on the next boot.\"\n );\n}\n\n\n/**\n * Read what the database looks like, for the schemas a set of collections\n * lives in.\n *\n * The same read `ensureCollectionTables` does at boot, exposed on its own for\n * the callers that want to *plan* against a real database without changing it —\n * the live schema editor, which has to tell somebody what a change would do\n * before they agree to it.\n */\nexport async function readSchemaFactsFor(\n client: Queryable,\n collections: CollectionConfig[]\n): Promise<ExistingSchema> {\n const relational = relationalCollections(collections);\n const schemas = Array.from(new Set([\n ...relational.map(schemaOf),\n ...planJunctionTables(relational).map(junction => junction.schema)\n ]));\n return readExistingSchema(client, schemas);\n}\n\n/**\n * Bring the database up to date. Returns what it did.\n *\n * Each statement runs on its own rather than in one transaction: they are all\n * independently safe and idempotent, and a single failure (an enum label that\n * cannot be added, say) should not roll back the tables that were created fine.\n * The error is surfaced with the statement that caused it.\n */\nexport async function ensureCollectionTables(\n client: Queryable,\n collections: CollectionConfig[],\n log?: (message: string) => void,\n options: EnsureOptions = {}\n): Promise<EnsureOutcome> {\n // This is the boundary, so this is where the world is read: the planner\n // itself takes the permission as an argument and never reaches for the\n // registry. By the time boot gets here `loadBundleResourceGraph` has\n // evaluated the project's `resources.ts`, so the declarations are there —\n // and a caller that already knows them can still say so.\n const schema = planSchema(collections, {\n databaseExtensions: options.databaseExtensions ?? declaredDatabaseExtensions()\n });\n\n // Junctions live alongside the collections that declare them, so their\n // schema has to be read too — otherwise an existing junction reads as\n // missing and its constraints as unplanned. Taken off the plan, which lists\n // both kinds of table.\n const schemas = Array.from(new Set(schema.tables.map(table => table.schema)));\n for (const name of schemas) {\n assertSafeIdentifier(name, \"schema name\");\n if (name !== \"public\") {\n await client.query(`CREATE SCHEMA IF NOT EXISTS \"${name}\";`);\n }\n }\n // `rebase` is where the `updated_at` trigger's function lives. Every real\n // boot has the schema by the time this runs (auth ensures it first) and\n // `db push` creates it in `schema.sql`, but this path is also driven by the\n // live schema editor and by tests, where \"the function's schema happens to\n // exist already\" is not a thing to rely on. Only when something needs it,\n // so a project with no trigger issues no statement — and not added to the\n // read set: what is *in* `rebase` is auth's business, not this planner's.\n if (schema.tables.some(table => table.triggers.length > 0)) {\n await client.query(`CREATE SCHEMA IF NOT EXISTS \"${REBASE_SCHEMA}\";`);\n }\n\n const existing = await readExistingSchema(client, schemas);\n const plan = diffPlanAgainstCatalogue(schema, existing, { constraints: options.constraints });\n const failures: EnsureOutcome[\"failures\"] = [];\n\n // Reported, not warned: this is a rename the ensure is about to perform, and\n // the operator should be able to see in the log why a column changed name.\n // The interesting case is the one that no longer happens — before this,\n // ensure added the new column empty beside the populated old one, every\n // statement succeeded, and the relation read the empty one.\n for (const legacy of plan.legacyForeignKeys) {\n const message =\n `Renaming \"${legacy.table}\".\"${legacy.legacy}\" to \"${legacy.expected}\". The old name is ` +\n \"the one Rebase derived for this relation before it singularized properly; the column \" +\n \"keeps its data, indexes and constraints. To keep the old name instead, set \" +\n `\\`localKey: \"${legacy.legacy}\"\\` on the relation and this will stop.`;\n logger.info(`[schema] ${message}`);\n log?.(message);\n }\n\n // Before anything is applied: a `search` block that changed after its column\n // was generated cannot be honoured by an additive plan, and serving the old\n // index while the config describes a new one is the silent failure this\n // check exists to end. Refusing is the loud half — boot is fatal on purpose\n // (see `ensureCollectionSchema` in the server's boot) and the message\n // carries the exact statements that resolve it.\n if (plan.searchDrift.length > 0) {\n throw new Error(searchDriftMessage(plan.searchDrift));\n }\n\n // Said once per column, at the moment the stamp is applied: from here on a\n // change is detected, but whether *this* column matches the block it is\n // being stamped with is not knowable — it predates the stamp.\n for (const adopted of plan.searchAdopted) {\n const message =\n `Adopting the existing generated column \"${adopted.table}\".\"${adopted.column}\" and recording what the ` +\n \"current `search` block would generate. Any later change to that block will be detected and refused; a \" +\n \"change made *before* this version was deployed cannot be, so if search has been missing content, \" +\n `rebuild the column once: ALTER TABLE \"${adopted.table.split(\".\").join('\".\"')}\" DROP COLUMN \"${adopted.column}\"; and boot again.`;\n logger.info(`[schema] ${message}`);\n log?.(message);\n }\n\n // Said once per column, every boot: an unindexed vector column and an\n // indexed one behave identically apart from latency, so the only way anyone\n // learns which one they have is if the boot says so.\n for (const skip of plan.vectorIndexSkipped) {\n const message = `No ANN index on \"${skip.table}\".\"${skip.column}\": ${skip.reason}`;\n logger.warn(`[schema] ${message}`);\n log?.(message);\n }\n\n // Said once per column, every boot, because the alternative is what this\n // whole feature exists to end: a column the configuration calls required,\n // sitting there nullable, with every surface reporting success. The boot\n // does not fail over it — the column is usable and the data is intact — but\n // it stops being invisible.\n for (const withheld of plan.withheldConstraints) {\n const message =\n `No NOT NULL on \"${withheld.target}\": ${withheld.reason} ${withheld.remedy}`;\n logger.warn(`[schema] ${message}`);\n log?.(message);\n }\n\n // Said once per drifted column, every boot, and this is the one report here\n // that describes a system which currently *looks* healthy. Everything else\n // in this function explains a statement that did not run; this explains a\n // statement that was never planned, on a deploy that reported success, and\n // whose first symptom is a write rejected long afterwards.\n for (const drift of plan.columnTypeDrift) {\n const message = columnTypeDriftMessage(drift);\n logger.warn(`[schema] ${message}`);\n log?.(message);\n }\n\n // Said once per column, every boot, and it matters more than the rest here\n // because the table is not merely imperfect — it is unwritable, and the\n // error the API returns names a field the author has already deleted.\n // This is what a renamed property looks like to an additive provisioner.\n for (const orphan of plan.orphanedRequiredColumns) {\n const [schema, table] = orphan.table.split(\".\");\n const message =\n `\"${orphan.table}\".\"${orphan.column}\" is NOT NULL with no default, and the \"${orphan.slug}\" ` +\n \"collection no longer declares it. Every insert will be rejected for a field you cannot set \" +\n `(PG_23502, naming \"${orphan.column}\"). This is what a renamed property looks like: the new ` +\n \"column was added, and the old one cannot be dropped unattended. Fix it with ONE of:\\n\" +\n ` ALTER TABLE \"${schema}\".\"${table}\" DROP COLUMN \"${orphan.column}\"; -- the rename is complete\\n` +\n ` ALTER TABLE \"${schema}\".\"${table}\" ALTER COLUMN \"${orphan.column}\" DROP NOT NULL; -- keep the data, stop requiring it\\n` +\n \" ...or declare the property again, if the column is still wanted.\";\n logger.warn(`[schema] ${message}`);\n log?.(message);\n }\n\n if (plan.actions.length === 0) {\n log?.(\"Schema is up to date; nothing to create.\");\n return { ...plan, failures };\n }\n\n for (const action of plan.actions) {\n try {\n if (await applyAction(client, action)) {\n log?.(`${action.kind}: ${action.target}`);\n } else {\n log?.(`${action.kind}: ${action.target} (already created by a peer)`);\n }\n } catch (err) {\n const message = describeDriverError(err);\n // A foreign key is the only action that can fail on the customer's\n // data rather than on the schema. The column it polices is already\n // there, so the collection serves either way — record it and carry\n // on rather than crash-looping the deployment.\n //\n // A comment is metadata about a column that was just created\n // successfully, and it can only fail on ownership (COMMENT requires\n // owning the table, which an adopted table may not grant). Losing\n // the stamp costs drift detection on the next boot; it must not cost\n // the deployment.\n //\n // An index that is not UNIQUE is an optimization, and losing an\n // optimization must not cost the deployment. This was the difference\n // between a slow collection and a tenant that would not boot: on a\n // managed runtime the throw killed the process, the pod never went\n // ready, and the deploy reported a 300-second readiness timeout — for\n // an ANN index whose absence changes latency and nothing else.\n //\n // UNIQUE is excluded because it is not an optimization. It is the\n // collection declaring that two rows cannot share a value, and\n // serving without it is serving a promise the database is not\n // keeping.\n const survivable =\n action.kind === \"add-constraint\" ||\n action.kind === \"comment-column\" ||\n (action.kind === \"create-index\" && !/CREATE\\s+UNIQUE\\s+INDEX/i.test(action.sql));\n if (survivable) {\n failures.push({ kind: action.kind, target: action.target, error: message });\n continue;\n }\n throw new Error(\n `Failed to ${action.kind} ${action.target}: ${message}${vectorExtensionHint(message)}\\n ${action.sql}`\n );\n }\n }\n return { ...plan, failures };\n}\n\n/**\n * What actually went wrong, rather than what the ORM said about it.\n *\n * Drizzle wraps every driver error, and its `message` is literally\n * ``Failed query: ${sql}\\nparams: ${params}`` — the statement we already know,\n * and not one word of Postgres's answer. Reporting `err.message` therefore\n * produced a failure that named the statement twice and the *reason* zero\n * times, so four unrelated boot failures — a missing extension, a wrong\n * privilege, a bad index method, a constraint the rows violate — all read\n * identically to whoever had to fix them.\n *\n * Two consequences, both observed in the field before this existed:\n *\n * 1. On a managed deployment the reason never reaches anybody. Boot dies, the\n * pod never goes ready, and the deploy reports a readiness timeout — so the\n * one line that says why is the one line that was thrown away here.\n * 2. {@link vectorExtensionHint} matches on the error text. Against the\n * wrapper it matched nothing, so the hint written specifically to explain a\n * missing pgvector never fired on the path that raises it.\n *\n * `detail` and `hint` come along because they are the fields Postgres uses to\n * say which object it meant and what to do about it — `CREATE EXTENSION` names\n * the missing library there, and a rejected constraint names the row. This\n * writes into the tenant's own boot log, about the tenant's own database.\n */\nexport function describeDriverError(err: unknown): string {\n const pg = extractPgError(err);\n if (pg) {\n const parts = [pg.code ? `${pg.message} [${pg.code}]` : pg.message];\n if (pg.detail) parts.push(` detail: ${pg.detail}`);\n if (pg.hint) parts.push(` hint: ${pg.hint}`);\n return parts.join(\"\\n\");\n }\n // No SQLSTATE anywhere in the chain: not a database answer at all — a\n // socket that closed, a bug in this file. The deepest cause still beats the\n // wrapper, and the wrapper still beats nothing.\n const cause = extractCauseMessage(err);\n if (cause) return cause;\n return err instanceof Error ? err.message : String(err);\n}\n\n/** ` CONCURRENTLY ` as it appears in a rendered `CREATE [UNIQUE] INDEX`. */\nconst CONCURRENTLY_RE = /\\sCONCURRENTLY\\s/i;\n\n/**\n * `25001 active_sql_transaction` — \"cannot run inside a transaction block\".\n *\n * Only ever raised here by `CREATE INDEX CONCURRENTLY`, and only when the\n * connection we were handed is inside a transaction. Deliberately narrow: it\n * decides to retry a *different* statement, so it must not fire on anything it\n * has not been reasoned about.\n */\nfunction isTransactionBlockRefusal(err: unknown): boolean {\n return extractPgError(err)?.code === \"25001\";\n}\n\n/** Attempts per action, including the first. Matches the server's bootstraps. */\nconst DDL_ATTEMPTS = 4;\n\n/**\n * Run one planned statement, surviving a simultaneous boot.\n *\n * Every statement in a plan is written to be idempotent, and that is not the\n * same as being safe to run concurrently: `CREATE … IF NOT EXISTS` reads the\n * catalog and then writes to it as two steps, so peers starting together both\n * see \"absent\" and the loser gets a duplicate key on a *catalog* index. Measured\n * against Postgres 18: five instances, 8 of 10 calls lost. `CREATE TYPE` is\n * worse, because Postgres has no `IF NOT EXISTS` for it at all.\n *\n * What made that fatal here rather than merely noisy is the loop this sits in.\n * A losing statement threw, and the throw abandoned **every remaining action in\n * the plan** — so a replica that lost one race came up missing tables it never\n * attempted, and the boot log blamed the one statement that failed.\n *\n * @returns `true` if this process applied the statement, `false` if a peer had\n * already created the object. The distinction is only for the log; both mean\n * the object is now there.\n * @throws the original error for anything that is not a race — a syntax error, a\n * permission failure, a unique constraint the customer's own rows violate.\n */\nasync function applyAction(\n client: Queryable,\n action: EnsureAction\n): Promise<boolean> {\n let sqlText = action.sql;\n for (let attempt = 1; ; attempt++) {\n try {\n await client.query(sqlText);\n return true;\n } catch (err) {\n // `CREATE INDEX CONCURRENTLY` is the one statement here Postgres\n // refuses inside a transaction block (25001), and whether we are in\n // one is not ours to know: the client is whatever handle the caller\n // bootstrapped with, and an application that builds its own adapter\n // can hand us a connection already inside a transaction. The plain\n // form is always correct and never refused — it takes a write lock\n // for the build, which is the cost of getting the index at all.\n if (isTransactionBlockRefusal(err) && CONCURRENTLY_RE.test(sqlText)) {\n sqlText = sqlText.replace(CONCURRENTLY_RE, \" \");\n logger.warn(\n `[schema] ${action.kind} ${action.target}: this connection is inside a transaction, ` +\n \"so the index is being built with a write lock rather than concurrently. Writes to \" +\n \"this table block until it finishes.\"\n );\n continue;\n }\n // Already there. Not \"retry\" — the end state this statement wanted\n // is the end state the database is in, so carry on to the next\n // action rather than spending three more attempts proving it.\n if (isDuplicateObjectRace(err)) {\n logger.debug(\n `[schema] ${action.kind} ${action.target}: already created by another instance`\n );\n return false;\n }\n // Retryable but not yet satisfied — a deadlock between two boots\n // taking catalog locks in step. The statement did nothing; run it\n // again after a jittered pause so peers that collided once do not\n // collide again in lockstep.\n if (isConcurrentDdlRace(err) && attempt < DDL_ATTEMPTS) {\n logger.debug(\n `[schema] ${action.kind} ${action.target}: lost a race with another instance ` +\n `(attempt ${attempt}/${DDL_ATTEMPTS}) — retrying`\n );\n await new Promise(resolve => setTimeout(resolve, 40 * attempt * (1 + Math.random())));\n continue;\n }\n throw err;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA8DA,IAAM,WAAmC;CAErC,MAAM;CAAU,UAAU;CAC1B,MAAM;CAAU,KAAK;CAAU,SAAS;CACxC,MAAM;CAAU,QAAQ;CACxB,SAAS;CAAU,SAAS;CAC5B,QAAQ;CAAU,MAAM;CACxB,QAAQ;CAAU,oBAAoB;CACtC,OAAO;CAGP,MAAM;CAAQ,SAAS;CAAQ,qBAAqB;CACpD,QAAQ;CAAQ,MAAM;CAAQ,WAAW;CAAQ,QAAQ;CAEzD,MAAM;CAAW,SAAS;CAE1B,MAAM;CACN,OAAO;CAEP,MAAM;CACN,OAAO;CAEP,MAAM;CACN,MAAM;CAAQ,0BAA0B;CACxC,QAAQ;CAAQ,uBAAuB;CACvC,WAAW;CAAa,+BAA+B;CACvD,aAAa;CAAe,4BAA4B;CACxD,UAAU;CAEV,UAAU;CACV,QAAQ;CACR,SAAS;CACT,WAAW;AACf;;;;;;;;;;AAWA,SAAgB,WAAW,KAA+C;CACtE,IAAI,CAAC,KAAK,OAAO;CACjB,IAAI,OAAO,IAAI,KAAK,CAAC,CAAC,YAAY;CAClC,IAAI,CAAC,MAAM,OAAO;CAGlB,IAAI,KAAK,WAAW,IAAI,GAAG,OAAO;CAIlC,MAAM,YAAY,KAAK,QAAQ,aAAa;CAC5C,IAAI,YAAY,GAAG,OAAO,KAAK,MAAM,GAAG,SAAS,CAAC,CAAC,KAAK;CAKxD,IAAI,KAAK,SAAS,IAAI,GAAG;EACrB,MAAM,UAAU,WAAW,KAAK,MAAM,GAAG,EAAE,CAAC;EAC5C,OAAO,WAA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-collection-tables-Cr2ye5JC.js","names":[],"sources":["../src/schema/column-type-drift.ts","../src/schema/plan/diff-plan.ts","../src/schema/ensure-collection-tables.ts"],"sourcesContent":["/**\n * A column whose type in the database is not the type the collection declares.\n *\n * The boot ensure is additive: it creates tables, columns, enum values and\n * indexes, and it never changes an existing column's type. That is the right\n * default — an automatic `ALTER COLUMN … TYPE` against customer data, decided\n * by a process nobody is watching, is not a thing to do quietly.\n *\n * What was wrong is that it happened *silently*. A property's `columnType`\n * changed after the first deploy, the deploy reported success, the column stayed\n * as it was, and the divergence surfaced later as writes failing:\n *\n * Invalid data format in \"listing_observations\":\n * malformed array literal: \"[0,0,0.0755,…]\"\n *\n * ...after a 10,690-row import, from a deployment that had said \"success\". The\n * two ends disagreed about the schema, so no value satisfied both: the declared\n * shape was rejected by Postgres and the Postgres shape was rejected by the\n * API's own validator, first. There is no encoding out of that, only a report.\n *\n * ## Why the comparison is deliberately blunt\n *\n * A drift report that cries wolf is worse than none, because the boot that says\n * it every time is the boot nobody reads. So types are compared by *family*, and\n * a family is only split from another when the difference changes what the\n * column can hold:\n *\n * - every numeric type is one family. `int4`, `numeric` and `float8` all arrive\n * as JavaScript numbers and accept each other's values; a database adopted\n * from an existing schema legitimately has `int4` where `type: \"number\"`\n * generates `NUMERIC`, and that is not news.\n * - every character type is one family, for the same reason: `text`,\n * `varchar(255)` and `char(3)` differ in what they *reject*, not in shape.\n * - `jsonb` and an array are different families, and that is the case this\n * exists for.\n *\n * Anything this module does not recognise — an enum type, a domain, a PostGIS\n * geometry, an extension type it has never met — returns `null` and is compared\n * with nothing. Silence on an unknown type is the deliberate choice: the cost of\n * a missed report is a question somebody asks once, and the cost of a false one\n * is a warning everybody learns to skip.\n */\n\n/** A column whose live type and declared type are in different families. */\nexport interface ColumnTypeDrift {\n /** `schema.table`. */\n table: string;\n /** The column name as it exists in the database. */\n column: string;\n /** What the collection says the column should be, e.g. `JSONB`. */\n declared: string;\n /** What the database actually has, as `udt_name` reports it, e.g. `_numeric`. */\n actual: string;\n}\n\n/**\n * Types that mean the same thing to everything above the driver.\n *\n * Keyed by every spelling either side can produce: `information_schema` reports\n * `udt_name` (`int4`, `_numeric`, `bpchar`), while the generators emit SQL\n * (`INTEGER`, `NUMERIC[]`, `CHAR(3)`). Both are normalised through here.\n */\nconst FAMILIES: Record<string, string> = {\n // Numbers. One family on purpose — see the note above.\n int2: \"number\", smallint: \"number\",\n int4: \"number\", int: \"number\", integer: \"number\",\n int8: \"number\", bigint: \"number\",\n numeric: \"number\", decimal: \"number\",\n float4: \"number\", real: \"number\",\n float8: \"number\", \"double precision\": \"number\",\n money: \"number\",\n\n // Characters. Also one family: the differences are limits, not shapes.\n text: \"text\", varchar: \"text\", \"character varying\": \"text\",\n bpchar: \"text\", char: \"text\", character: \"text\", citext: \"text\",\n\n bool: \"boolean\", boolean: \"boolean\",\n\n json: \"json\",\n jsonb: \"jsonb\",\n\n uuid: \"uuid\",\n bytea: \"bytea\",\n\n date: \"date\",\n time: \"time\", \"time without time zone\": \"time\",\n timetz: \"time\", \"time with time zone\": \"time\",\n timestamp: \"timestamp\", \"timestamp without time zone\": \"timestamp\",\n timestamptz: \"timestamptz\", \"timestamp with time zone\": \"timestamptz\",\n interval: \"interval\",\n\n tsvector: \"tsvector\",\n vector: \"vector\",\n halfvec: \"halfvec\",\n sparsevec: \"sparsevec\"\n};\n\n/**\n * One SQL or `udt_name` spelling reduced to its family, or `null` when this\n * module has no opinion about it.\n *\n * `null` is not a failure. It is the answer for an enum type, a domain, a\n * PostGIS column, a quoted qualified name — everything whose identity is a\n * *name* rather than a shape, where two spellings being different says nothing\n * about whether the values are compatible.\n */\nexport function typeFamily(raw: string | undefined | null): string | null {\n if (!raw) return null;\n let type = raw.trim().toLowerCase();\n if (!type) return null;\n\n // `\"public\".\"posts_status\"` — an enum, identified by name. Not comparable.\n if (type.startsWith(\"\\\"\")) return null;\n\n // `INTEGER GENERATED BY DEFAULT AS IDENTITY` is an `int4` with a default\n // attached; the identity clause is not part of the type.\n const generated = type.indexOf(\" generated \");\n if (generated > 0) type = type.slice(0, generated).trim();\n\n // Arrays, in both spellings: `NUMERIC[]` from the generators, `_numeric`\n // from `udt_name`. Compared element-wise, so `text[]` and `numeric[]` are\n // different and `int4[]` and `numeric[]` are not.\n if (type.endsWith(\"[]\")) {\n const element = typeFamily(type.slice(0, -2));\n return element && `array:${element}`;\n }\n if (type.startsWith(\"_\")) {\n const element = typeFamily(type.slice(1));\n return element && `array:${element}`;\n }\n\n // `VARCHAR(255)`, `VECTOR(384)`, `NUMERIC(10, 2)` — the width is a limit on\n // a family, not a family. A vector whose *dimensions* changed is a separate\n // concern with its own handling in the ensure.\n const paren = type.indexOf(\"(\");\n if (paren > 0) type = type.slice(0, paren).trim();\n\n return FAMILIES[type] ?? null;\n}\n\n/**\n * Do these two spellings describe columns that hold the same kind of value?\n *\n * `true` whenever the answer is not confidently \"no\" — an unrecognised type on\n * either side agrees with everything, because a report needs evidence and an\n * unknown type is the absence of it.\n */\nexport function typesAgree(declared: string, actual: string): boolean {\n const a = typeFamily(declared);\n const b = typeFamily(actual);\n if (a === null || b === null) return true;\n if (a !== b) return false;\n // Same family, and for `numeric` that is not the end of it: the modifier is\n // what makes `NUMERIC(10, 2)` a price and a bare `NUMERIC` a number that\n // keeps whatever the caller sent. A property that declares\n // `precision`/`scale` is asking the database to round, and a column without\n // them silently does not — so the two disagree, and the drift report says\n // so. A declaration with no modifier accepts whatever is there, which is\n // what it always did.\n if (a !== \"numeric\") return true;\n const declaredModifier = numericModifier(declared);\n if (declaredModifier === null) return true;\n return declaredModifier === numericModifier(actual);\n}\n\n/** `numeric(10,2)` / `NUMERIC(10, 2)` → `10,2`; a bare `numeric` → `null`. */\nfunction numericModifier(raw: string): string | null {\n const match = raw.match(/\\(([^)]*)\\)/);\n return match ? match[1].replace(/\\s+/g, \"\") : null;\n}\n\n/**\n * The sentence a boot log says about one drifted column.\n *\n * Written to be actionable in the place it is read, which is a runtime log with\n * no way to run a migration from it: it names both types, says which surface\n * will break first, and gives the statement that resolves it.\n */\nexport function columnTypeDriftMessage(drift: ColumnTypeDrift): string {\n const [schema, table] = drift.table.split(\".\");\n return (\n `Column \"${drift.table}\".\"${drift.column}\" is ${drift.actual} in the database, but this ` +\n `collection declares ${drift.declared}. Boot does not change an existing column's type, so ` +\n \"the database keeps what it has and writes that match the declaration will be rejected by \" +\n \"Postgres. Change it deliberately, when you can watch it:\\n\" +\n ` ALTER TABLE \"${schema}\".\"${table}\" ALTER COLUMN \"${drift.column}\" ` +\n `TYPE ${drift.declared} USING \"${drift.column}\"::${drift.declared};`\n );\n}\n","/**\n * The additive statements that bring a database up to a {@link SchemaPlan}.\n *\n * ## Why additive-only, forever\n *\n * This runs unattended, at boot, against a database with customers' data in it,\n * with no human reading a diff. So it may only ever do things that cannot lose\n * data: create a missing table, add a missing column, create a missing enum\n * type, add an enum value, create an index.\n *\n * It will **never** drop a table or a column, narrow a type, or alter a\n * constraint at boot. A removed field leaves its column behind; a renamed field\n * looks like an addition and the old column stays. That is the correct trade\n * for an automated path — the alternative is an unattended process that can\n * silently destroy a column. Destructive changes stay a deliberate,\n * human-reviewed migration. Because of that, this is safe to run on every boot,\n * and re-running it is a no-op.\n *\n * ## What changed when the planner arrived\n *\n * This used to read `Property` itself — its own reading of the type, of\n * `validation`, of relations, of enums — and disagreed with `db push` about all\n * of them. The audit found a required `author_id` that was NOT NULL after a\n * push and nullable after a boot, on the one path with no developer in the\n * loop. Now it reads the same {@link ColumnPlan} the DDL renderer does, so a\n * column's type, default, uniqueness and foreign key are decided once. What is\n * left here is the half that is genuinely this path's own: *what the database\n * already has*, and which of the planned constraints are safe to apply to it.\n */\nimport type { ColumnPlan, SchemaPlan, TablePlan } from \"./types\";\nimport { renderColumnDefinition, renderPgType } from \"./render-ddl\";\nimport { quoteSqlLiteral } from \"./plan-schema\";\nimport { SET_UPDATED_AT_FN, triggerStatements } from \"./updated-at-trigger\";\nimport {\n SEARCH_STAMP_PREFIX,\n SEARCH_TEXT_FN,\n SEARCH_UNACCENT_FN,\n searchColumnStamps,\n searchIndexStatements\n} from \"../search-column\";\nimport { collectionIndexStatement, sortIndexSpecs } from \"../collection-index\";\nimport { vectorIndexStatement, type SkippedVectorIndex } from \"../vector-index\";\nimport { typesAgree, type ColumnTypeDrift } from \"../column-type-drift\";\n\n/** Postgres identifiers this module is willing to interpolate. */\nconst SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;\n\n/**\n * Validation used to run only on the names read back OUT of the catalogue,\n * which is the direction that cannot hurt anyone: those came from Postgres. The\n * names going IN — the schema and table a collection declares — were quoted and\n * concatenated on trust, and quoting is not escaping. A table named\n * `x\" (id int); DROP TABLE users; --` closes the quote and the statement, and\n * the whole thing runs on the owner connection, which is the one connection in\n * the system that is exempt from every RLS policy.\n *\n * That is only a config file on a self-hosted project, where the person writing\n * it could run the SQL directly anyway. It is not only a config file where a\n * collection can be defined over the wire — the live-schema and source editors\n * both do that — and there the caller is an admin on the app, not an operator\n * of the database.\n */\nexport function assertSafeIdentifier(value: string, what: string): string {\n if (!SAFE_IDENTIFIER.test(value)) {\n throw new Error(`Refusing to build SQL with an unsafe ${what}: ${JSON.stringify(value)}`);\n }\n return value;\n}\n\n/** What the database currently has, as the planner needs it. */\nexport interface ExistingSchema {\n /** `schema.table` → set of column names. */\n tables: Map<string, Set<string>>;\n /** `schema.typename` of every enum type that already exists. */\n enums: Set<string>;\n /**\n * `schema.table.constraint` of every constraint that already exists.\n *\n * Optional so a caller that only cares about tables can still build one by\n * hand; absent is read as \"none known\", which at worst re-attempts a\n * constraint that then fails harmlessly as a duplicate.\n */\n constraints?: Set<string>;\n /**\n * `schema.table.column` → that column's comment, for the columns that have\n * one. This is where a generated search column's fingerprint lives.\n */\n columnComments?: Map<string, string>;\n /** `schema.typename` → its labels, in `enumsortorder`. */\n enumValues?: Map<string, string[]>;\n /** `schema.table.column` of every NOT NULL column. */\n notNullColumns?: Set<string>;\n /** `schema.table.column` of every column that has a DEFAULT. */\n columnDefaults?: Set<string>;\n /** `schema.table` of every table that holds at least one row. */\n populatedTables?: Set<string>;\n /**\n * `schema.table.column` → the type Postgres reports, as `udt_name` (plus a\n * modifier where one distinguishes two columns of the same family, e.g.\n * `numeric(10,2)`).\n */\n columnTypes?: Map<string, string>;\n /** `schema.table.trigger` of every trigger that already exists. */\n triggers?: Set<string>;\n}\n\n/**\n * How far the planner may go in making the database's constraints match the\n * configuration.\n *\n * - `additive` — the boot default. Columns, tables, indexes and enum values are\n * created; no existing column's constraints are touched. Unattended boots run\n * against customer data with nobody reading a diff, and a database adopted by\n * introspection legitimately carries NOT NULL on columns the generated\n * collection leaves optional (`introspect-db-logic` withholds `required` from\n * a column with a default or a trigger behind it). Converging there would\n * strip real constraints on first boot.\n * - `converge` — the live schema editor. Every statement is planned, shown to\n * the person making the change, and applied only once they confirm it.\n */\nexport type ConstraintPolicy = \"additive\" | \"converge\";\n\nexport interface DiffOptions {\n /** Defaults to `additive`. See {@link ConstraintPolicy}. */\n constraints?: ConstraintPolicy;\n}\n\nexport interface EnsureAction {\n kind: \"create-enum\" | \"create-table\" | \"add-column\" | \"add-constraint\" | \"rename-column\"\n | \"create-extension\" | \"create-function\" | \"create-index\" | \"comment-column\"\n | \"add-enum-value\" | \"set-not-null\" | \"drop-not-null\" | \"set-default\" | \"create-trigger\";\n /** Qualified target, for logging: `public.posts` or `public.posts.title`. */\n target: string;\n sql: string;\n}\n\n/** A NOT NULL column with no default that no property declares. */\nexport interface OrphanedRequiredColumn {\n /** `schema.table`. */\n table: string;\n /** The column left behind. */\n column: string;\n /** The collection that no longer declares it. */\n slug: string;\n}\n\n/** A constraint the configuration asks for that the planner is not applying. */\nexport interface WithheldConstraint {\n /** `schema.table.column`. */\n target: string;\n kind: \"not-null\";\n /**\n * Why, in a sentence that names the obstacle rather than the rule. The\n * reader is looking at a column that is nullable when they asked for\n * required, and needs to know what to do about it.\n */\n reason: string;\n /** What would make it applicable. */\n remedy: string;\n}\n\n/**\n * A generated search column built from a `search` block that has since changed.\n *\n * Reported instead of applied because the two ways to apply it are both worse\n * than stopping. `ALTER COLUMN … SET EXPRESSION` exists only on PG17+ and\n * rewrites the table either way; `DROP COLUMN` + `ADD COLUMN` rewrites it under\n * an ACCESS EXCLUSIVE lock and rebuilds the GIN index. This module runs\n * unattended against live customer data with nobody reading a diff, so a\n * multi-minute outage is not a decision it may take on its own.\n *\n * Not applying it silently is not an option either: a collection that added a\n * field, flipped `unaccent` or raised a weight kept indexing the *old* set\n * forever, and the only symptom was searches returning nothing for content\n * plainly in the row.\n */\nexport interface SearchColumnDrift {\n /** `schema.table`. */\n table: string;\n column: string;\n /** The fingerprint recorded on the column. */\n found: string;\n /** The fingerprint the current `search` block computes. */\n expected: string;\n /** The statements that would rebuild the column, for the operator to run. */\n rebuild: string[];\n}\n\n/** A relation column whose old and new spellings both plausibly apply. */\nexport interface LegacyForeignKey {\n /** `schema.table`. */\n table: string;\n /** The name the current rule derives, and what this plan would create. */\n expected: string;\n /** The name the old rule derived, which the table already has. */\n legacy: string;\n}\n\nexport interface EnsurePlan {\n actions: EnsureAction[];\n /** Every statement, in dependency order. Empty when the schema is current. */\n statements: string[];\n /**\n * Relation columns this plan is about to create where the table already\n * carries the same column under its pre-singularization name.\n *\n * Reported rather than silently handled: the ensure is additive, so it\n * would add `category_id` beside a populated `categorie_id` and the\n * relation would then read the new, empty one. No statement fails, no table\n * is missing, and the only symptom is relations resolving to nothing.\n */\n legacyForeignKeys: LegacyForeignKey[];\n /** @see SearchColumnDrift */\n searchDrift: SearchColumnDrift[];\n /**\n * Generated search columns that exist but carry no fingerprint — created\n * before this check existed, or by `search.sql` on an older CLI. The plan\n * stamps them so the *next* change is detectable.\n */\n searchAdopted: { table: string; column: string }[];\n /**\n * Vector columns this plan is deliberately leaving unindexed, because\n * pgvector cannot build an ANN index that wide. Reported rather than\n * thrown: the column is valid, storable and searchable.\n */\n vectorIndexSkipped: SkippedVectorIndex[];\n /**\n * Constraints the configuration asks for that this plan is not applying,\n * and why. Every one of these was previously withheld in silence.\n */\n withheldConstraints: WithheldConstraint[];\n /**\n * Columns whose type in the database is in a different family from the one\n * the collection declares. Reported and never acted on — this is the one\n * divergence that presents as a *working* deploy.\n */\n columnTypeDrift: ColumnTypeDrift[];\n /**\n * Columns that are NOT NULL, have no default, and that no property declares\n * any more — so every insert through the API is rejected for a field the\n * author cannot name, because they already deleted it. This is what a\n * **rename** looks like to an additive provisioner. Reported, never acted\n * on: dropping the column is the right fix roughly always and destructive\n * exactly once, which is not a decision to take unattended.\n */\n orphanedRequiredColumns: OrphanedRequiredColumn[];\n}\n\n/** Which pass a column belongs to. The order below is the order they run in. */\nconst isScalarProperty = (column: ColumnPlan): boolean =>\n (column.source.kind === \"property\" || column.source.kind === \"implicit-id\") && !column.primaryKey;\n\nexport function diffPlanAgainstCatalogue(\n plan: SchemaPlan,\n existing: ExistingSchema,\n options: DiffOptions = {}\n): EnsurePlan {\n const constraintPolicy: ConstraintPolicy = options.constraints ?? \"additive\";\n const actions: EnsureAction[] = [];\n const withheldConstraints: WithheldConstraint[] = [];\n const columnTypeDrift: ColumnTypeDrift[] = [];\n const legacyForeignKeys: LegacyForeignKey[] = [];\n const searchDrift: SearchColumnDrift[] = [];\n const searchAdopted: { table: string; column: string }[] = [];\n\n const collectionTables = plan.tables.filter(t => t.kind === \"collection\");\n const junctionTables = plan.tables.filter(t => t.kind === \"junction\");\n\n // 1. Enum types. `CREATE TYPE` has no IF NOT EXISTS, so an existing type is\n // skipped by name rather than guarded in SQL.\n for (const enumPlan of plan.enums) {\n assertSafeIdentifier(enumPlan.schema, \"schema name\");\n if (existing.enums.has(enumPlan.qualified)) {\n // The type is there, but that says nothing about its *values*.\n // Skipping the whole type by name is what made an added enum value\n // vanish: nothing was planned, the boot reported success, and the\n // first row using the value was rejected by a type that had never\n // heard of it. `ADD VALUE` is the one alteration Postgres offers\n // here, it is purely additive, and it is idempotent.\n //\n // `enumValues` absent means the caller built the schema by hand and\n // does not know the values; skip by name as before.\n const current = existing.enumValues?.get(enumPlan.qualified);\n if (!current) continue;\n for (const value of enumPlan.labels) {\n if (current.includes(value)) continue;\n actions.push({\n kind: \"add-enum-value\",\n target: `${enumPlan.qualified}.${value}`,\n // Not inside a transaction with any use of the value:\n // Postgres refuses to read a value added by the transaction\n // still adding it. The applier runs these one statement at a\n // time, which is what makes it legal.\n sql: `ALTER TYPE \"${enumPlan.schema}\".\"${enumPlan.name}\" ADD VALUE IF NOT EXISTS ${quoteSqlLiteral(value)};`\n });\n }\n continue;\n }\n actions.push({\n kind: \"create-enum\",\n target: enumPlan.qualified,\n sql: `CREATE TYPE \"${enumPlan.schema}\".\"${enumPlan.name}\" AS ENUM (${enumPlan.labels.map(quoteSqlLiteral).join(\", \")});`\n });\n }\n\n // 1b. Extensions and helper functions, before the tables and columns that\n // reference them: a generated column's expression is resolved when the\n // column is created, so a table whose search column calls\n // `rebase_search_text` cannot be added before that function exists.\n // Both forms are idempotent, so a boot against a database that already\n // has them plans nothing.\n for (const statement of plan.extensions) {\n actions.push({\n kind: \"create-extension\",\n target: statement.replace(/^CREATE EXTENSION IF NOT EXISTS |;$/g, \"\"),\n sql: statement\n });\n }\n for (const statement of plan.functions) {\n actions.push({ kind: \"create-function\", target: functionTarget(statement), sql: statement });\n }\n\n // 2. Missing tables. Only the identity column is created here; every other\n // column is added by step 3, so a new table and an existing table that\n // gained a field travel the exact same code path. One way to build a\n // column means one way for it to be wrong.\n const created = new Set<string>();\n for (const table of collectionTables) {\n if (existing.tables.has(table.qualified) || created.has(table.qualified)) continue;\n created.add(table.qualified);\n const schema = assertSafeIdentifier(table.schema, \"schema name\");\n const name = assertSafeIdentifier(table.table, \"table name\");\n const id = table.columns.find(c => c.primaryKey);\n const definition = id\n ? `\"${assertSafeIdentifier(id.column, \"column name\")}\" ${renderColumnDefinition(id)}`\n : '\"id\" TEXT PRIMARY KEY';\n actions.push({\n kind: \"create-table\",\n target: table.qualified,\n sql: `CREATE TABLE IF NOT EXISTS \"${schema}\".\"${name}\" (${definition});`\n });\n }\n\n // 2b. Junction tables behind many-to-many relations. No collection declares\n // them, so until they existed an m2m write had nowhere to land and the\n // junction's derived RLS had nothing to attach to. Both columns are\n // created here — unlike a collection table, whose CREATE declares only\n // the identity column — because there is nothing else to them.\n for (const table of junctionTables) {\n if (existing.tables.has(table.qualified) || created.has(table.qualified)) continue;\n created.add(table.qualified);\n const columns = table.columns\n .map(c => `\"${c.column}\" ${renderColumnDefinition(c)}`)\n .join(\", \");\n actions.push({\n kind: \"create-table\",\n target: table.qualified,\n sql: `CREATE TABLE IF NOT EXISTS \"${table.schema}\".\"${table.table}\" (${columns}` +\n `, PRIMARY KEY (${table.primaryKey.map(c => `\"${c}\"`).join(\", \")}));`\n });\n }\n\n const addColumn = (table: TablePlan, column: string, definition: string): void => {\n if (existing.tables.get(table.qualified)?.has(column)) return;\n // Same reason as `assertSafeIdentifier` above: a column name reaching\n // here came from a property declaration, which on the editor paths came\n // over the wire. `definition` is built by the renderer from a closed set\n // of type mappings and is not caller text.\n assertSafeIdentifier(column, \"column name\");\n actions.push({\n kind: \"add-column\",\n target: `${table.qualified}.${column}`,\n sql: `ALTER TABLE \"${table.schema}\".\"${table.table}\" ADD COLUMN IF NOT EXISTS \"${column}\" ${definition};`\n });\n };\n\n /**\n * Move a column that is only missing because it was renamed.\n *\n * Returns true when it handled the column, so the caller skips the ordinary\n * ADD. Adding would be the wrong move and a quiet one: the data is in the\n * old column, `ADD COLUMN` creates the new one empty beside it, every\n * statement succeeds, and the relation reads the empty one. A rename is\n * metadata-only in Postgres, keeps the values, and carries the column's\n * indexes and constraints with it.\n */\n const renameLegacyColumn = (table: TablePlan, column: ColumnPlan): boolean => {\n const present = existing.tables.get(table.qualified);\n if (!column.legacyColumn || !present) return false;\n if (present.has(column.column) || !present.has(column.legacyColumn)) return false;\n legacyForeignKeys.push({ table: table.qualified, expected: column.column, legacy: column.legacyColumn });\n actions.push({\n kind: \"rename-column\",\n target: `${table.qualified}.${column.column}`,\n sql: `ALTER TABLE \"${table.schema}\".\"${table.table}\" RENAME COLUMN \"${column.legacyColumn}\" TO \"${column.column}\";`\n });\n return true;\n };\n\n /**\n * A `NOT NULL` is safe exactly when it cannot fail against rows that are\n * already there, and there are three ways to know that:\n *\n * - the table is being created by this plan (no rows yet);\n * - the table exists and is empty;\n * - the column arrives with a DEFAULT, which Postgres backfills into every\n * existing row as part of ADD COLUMN.\n *\n * `populatedTables` absent means the caller does not know, and not knowing\n * has to read as \"assume rows\" — the other direction emits a NOT NULL that\n * is checked against live data and aborts the boot. Written as an explicit\n * `!== undefined` because the optional-chain form quietly says *empty* when\n * the fact is missing, which is the wrong way to be wrong.\n */\n const tableIsEmpty = (table: TablePlan): boolean =>\n existing.populatedTables !== undefined\n && existing.tables.has(table.qualified)\n && !existing.populatedTables.has(table.qualified);\n\n /**\n * Plan one column, with the constraints this database can safely take.\n *\n * The definition comes from the same renderer `schema.sql` uses, minus the\n * constraints that are checked against live rows. That subtraction is the\n * whole of what this path is allowed to decide for itself.\n */\n const planColumn = (table: TablePlan, column: ColumnPlan): void => {\n const key = `${table.qualified}.${column.column}`;\n const columnExists = existing.tables.get(table.qualified)?.has(column.column) === true;\n const fresh = created.has(table.qualified);\n const empty = tableIsEmpty(table);\n const required = !column.nullable;\n const hasDefault = column.default !== undefined;\n\n // The column is there and holds a different kind of value than the\n // collection says it does. Reported, never altered: an unattended\n // `ALTER COLUMN … TYPE` over customer data is not a thing to do\n // quietly, and the *quiet* is what this fixes. A deploy that changed a\n // `columnType` used to report success while the column stayed as it\n // was, and the divergence surfaced later as every write failing.\n // A column whose definition is owned elsewhere (auth, or a generated\n // search column) is not compared: the declaration there is a rendered\n // string rather than a type, and auth's own reconcile owns it.\n const declaredType = renderPgType(column.type);\n const actualType = existing.columnTypes?.get(key);\n if (columnExists && !column.sqlDefinition && actualType && !typesAgree(declaredType, actualType)) {\n columnTypeDrift.push({ table: table.qualified, column: column.column, declared: declaredType, actual: actualType });\n }\n\n // A table this run is creating has no rows yet, so the constraints\n // `db push` writes are free to apply. On a table that already exists\n // they are not: `SET NOT NULL` is checked against live rows and a UNIQUE\n // would fail on existing duplicates. So the constraints are emitted for\n // the fresh case — which is the whole managed-runtime path, and the one\n // that diverged from `db push` — and withheld for the adopted one.\n const notNullIsSafe = fresh || empty || hasDefault;\n const applicable: ColumnPlan = {\n ...column,\n unique: column.unique && fresh,\n nullable: column.nullable || !(notNullIsSafe || columnExists)\n };\n if (required && !columnExists && !notNullIsSafe) {\n withheldConstraints.push({\n target: key,\n kind: \"not-null\",\n reason: column.source.kind === \"relation\" || column.source.kind === \"reference\"\n ? `\"${column.column}\" is a required link, but \"${table.qualified}\" already holds rows and ` +\n \"the column has no default to backfill them with, so NOT NULL would be checked \" +\n \"against data that does not have a value yet.\"\n : `\"${column.column}\" is required, but \"${table.qualified}\" already holds rows and the column ` +\n \"has no default to backfill them with, so NOT NULL would be checked \" +\n \"against data that does not have a value yet.\",\n remedy: column.source.kind === \"relation\" || column.source.kind === \"reference\"\n ? \"Backfill the column, then add the constraint — or make the relation optional.\"\n : \"Backfill the column, then add the constraint — or give the property a \" +\n \"default so every existing row gets one.\"\n });\n }\n addColumn(table, column.column, renderColumnDefinition(applicable));\n\n if (!columnExists) return;\n\n // ── The column is already there and only a modifier differs ──────────\n // A DEFAULT binds future writes only, so `SET DEFAULT` cannot fail and\n // cannot touch a row that already exists. That makes it the one\n // convergence this path may do unattended — and it has to, because\n // `ADD COLUMN IF NOT EXISTS` is a no-op against an existing column, so\n // a `defaultValue` added to a live collection would otherwise never\n // reach the database at all.\n if (column.default && column.default.kind !== \"identity\" && !column.generated) {\n const expression = column.default.kind === \"sql\" ? column.default.expression : column.default.sql;\n if (!existing.columnDefaults?.has(key)) {\n actions.push({\n kind: \"set-default\",\n target: key,\n sql: `ALTER TABLE \"${table.schema}\".\"${table.table}\" ALTER COLUMN \"${column.column}\" SET DEFAULT ${expression};`\n });\n }\n }\n\n // Two directions on NOT NULL, and they are not equally safe — see\n // `ConstraintPolicy` for why neither runs at an unattended boot.\n if (constraintPolicy !== \"converge\") return;\n const isNotNull = existing.notNullColumns?.has(key) === true;\n if (required && !isNotNull) {\n if (empty) {\n actions.push({\n kind: \"set-not-null\",\n target: key,\n sql: `ALTER TABLE \"${table.schema}\".\"${table.table}\" ALTER COLUMN \"${column.column}\" SET NOT NULL;`\n });\n } else {\n withheldConstraints.push({\n target: key,\n kind: \"not-null\",\n reason:\n `\"${column.column}\" became required, but \"${table.qualified}\" holds rows and any of them ` +\n \"with no value would make SET NOT NULL fail.\",\n remedy:\n \"Backfill the column first — `UPDATE … SET \\\"\" + column.column +\n \"\\\" = … WHERE \\\"\" + column.column + \"\\\" IS NULL` — then apply this again.\"\n });\n }\n }\n if (!required && isNotNull) {\n // Loosening never fails and never loses data. It is here rather\n // than at boot because a database adopted by introspection carries\n // NOT NULL on columns the generated collection deliberately leaves\n // optional, and converging those unasked would drop constraints\n // nobody edited.\n actions.push({\n kind: \"drop-not-null\",\n target: key,\n sql: `ALTER TABLE \"${table.schema}\".\"${table.table}\" ALTER COLUMN \"${column.column}\" DROP NOT NULL;`\n });\n }\n };\n\n // 3. Scalar columns, then the auth columns the collection never mentions.\n // The scaffold's users collection describes 12 of the 14 columns auth\n // reads and writes, so planning only from properties left `is_anonymous`\n // and `tokens_valid_after` to `ensureAuthTablesExist` — which does create\n // them, but only because that function happens to run later in the same\n // boot. Planning them here makes this path self-contained.\n for (const table of collectionTables) {\n assertSafeIdentifier(table.schema, \"schema name\");\n assertSafeIdentifier(table.table, \"table name\");\n for (const column of table.columns) {\n if (!isScalarProperty(column)) continue;\n planColumn(table, column);\n }\n for (const column of table.columns) {\n if (column.source.kind !== \"auth\") continue;\n addColumn(table, column.column, renderColumnDefinition(column));\n }\n }\n\n // 3a. The generated search columns.\n //\n // Adding a STORED generated column rewrites the table, which on a large\n // one is not free — but it is the same additive shape as every other\n // column here, and the alternative (leaving it out until someone runs a\n // migration) is a declared `search` block that silently does nothing.\n //\n // Changing one is not additive, and `ADD COLUMN IF NOT EXISTS` is a\n // no-op against a column that is already there — which is why a `search`\n // block that gained a field, flipped `unaccent` or moved a weight used\n // to be inert forever, on every path, with nothing logged. Each column\n // carries a fingerprint of the expression it was built from, and a\n // mismatch is reported rather than applied.\n for (const table of collectionTables) {\n if (!table.search) continue;\n const definitions = new Map(\n table.columns\n .filter(c => c.source.kind === \"search\")\n .map(c => [c.column, renderColumnDefinition(c)] as const)\n );\n for (const stamp of searchColumnStamps(table.search)) {\n const definition = definitions.get(stamp.column)!;\n const exists = existing.tables.get(table.qualified)?.has(stamp.column) === true;\n const recorded = existing.columnComments?.get(`${table.qualified}.${stamp.column}`);\n\n if (exists && recorded?.startsWith(SEARCH_STAMP_PREFIX) && recorded !== stamp.fingerprint) {\n searchDrift.push({\n table: table.qualified,\n column: stamp.column,\n found: recorded,\n expected: stamp.fingerprint,\n rebuild: [\n `ALTER TABLE \"${table.schema}\".\"${table.table}\" DROP COLUMN \"${stamp.column}\";`,\n `ALTER TABLE \"${table.schema}\".\"${table.table}\" ADD COLUMN \"${stamp.column}\" ${definition};`,\n stamp.sql\n ]\n });\n // The old stamp is the only evidence of what the column holds;\n // overwriting it here would erase the drift instead of fixing it.\n continue;\n }\n\n addColumn(table, stamp.column, definition);\n if (exists && recorded === undefined) {\n searchAdopted.push({ table: table.qualified, column: stamp.column });\n }\n if (recorded !== stamp.fingerprint) {\n actions.push({ kind: \"comment-column\", target: `${table.qualified}.${stamp.column}`, sql: stamp.sql });\n }\n }\n }\n\n // 3b. A junction that already existed, but is short a column. One created\n // above already carries both, so re-listing them would log two no-op\n // statements and inflate the count of changes applied.\n for (const table of junctionTables) {\n if (created.has(table.qualified)) continue;\n for (const column of table.columns) {\n if (renameLegacyColumn(table, column)) continue;\n // A payload column (`through.properties`) goes through `planColumn`,\n // the same pass a collection's scalar columns take. The bare\n // `ADD COLUMN <type>` below is right for the two key columns — they\n // are NOT NULL by the composite primary key and have no default —\n // and wrong for everything else: it would drop a `defaultValue`, and\n // it would either omit a NOT NULL the collection declared or apply\n // one to a junction that already holds rows without a value to\n // backfill them. `planColumn` is the one place that decides which of\n // those is safe, and it reports the constraint it withheld.\n if (column.source.kind === \"property\") {\n planColumn(table, column);\n continue;\n }\n addColumn(table, column.column, renderPgType(column.type));\n }\n }\n\n // 3c. The columns relation and reference properties own.\n for (const table of collectionTables) {\n for (const column of table.columns) {\n if (column.source.kind !== \"relation\" && column.source.kind !== \"reference\") continue;\n // A declared property already emits this column (an explicit\n // `postId` beside the `belongsTo` that uses it); the relation\n // contributes only the constraint, below.\n if (column.columnOwnedByProperty) continue;\n if (renameLegacyColumn(table, column)) continue;\n planColumn(table, column);\n }\n }\n\n // 4. Foreign keys, last: the tables and columns on both ends have to exist\n // first, and a constraint is the one thing here that can fail on data\n // rather than on schema, so nothing else depends on it.\n const knownConstraints = existing.constraints ?? new Set<string>();\n const plannedConstraints = new Set<string>();\n for (const table of [...collectionTables, ...junctionTables]) {\n for (const column of table.columns) {\n const fk = column.foreignKey;\n if (!fk) continue;\n const name = `${fk.schema}.${fk.table}.${fk.constraintName}`;\n if (knownConstraints.has(name) || plannedConstraints.has(name)) continue;\n plannedConstraints.add(name);\n actions.push({ kind: \"add-constraint\", target: name, sql: `${fk.sql};` });\n }\n }\n\n // 5. Indexes, after everything — the column has to exist, and this is the\n // one step that runs against a populated table for real work.\n //\n // CONCURRENTLY: a plain CREATE INDEX takes a lock that blocks writes for\n // the duration of the build, which on a live table is an outage. Each\n // statement here is issued on its own, outside any transaction, which is\n // the condition CONCURRENTLY requires.\n //\n // ...and only on a live table. It is withheld for a table this same plan\n // is creating: there are no rows to build from and no writer to block, so\n // the lock CONCURRENTLY avoids is a lock nobody would have taken. Worth\n // withholding rather than merely harmless, because CONCURRENTLY is the\n // one index form Postgres refuses inside a transaction block.\n const concurrent = (schema: string, table: string): boolean => !created.has(`${schema}.${table}`);\n for (const table of collectionTables) {\n if (!table.search) continue;\n for (const statement of searchIndexStatements(table.search)) {\n actions.push({\n kind: \"create-index\",\n target: table.qualified,\n sql: concurrent(table.schema, table.table)\n ? statement.replace(\"CREATE INDEX IF NOT EXISTS\", \"CREATE INDEX CONCURRENTLY IF NOT EXISTS\")\n : statement\n });\n }\n }\n\n // ANN indexes for vector columns, on the same terms. A column too wide\n // for pgvector to index is reported, not planned — silence there would\n // read as \"indexed\" to anyone watching the boot.\n const vectorIndexSkipped: SkippedVectorIndex[] = [];\n for (const table of collectionTables) {\n if (!table.vector) continue;\n for (const spec of table.vector.specs) {\n actions.push({\n kind: \"create-index\",\n target: `${spec.schema}.${spec.table}`,\n sql: concurrent(spec.schema, spec.table)\n ? vectorIndexStatement(spec).replace(\"CREATE INDEX IF NOT EXISTS\", \"CREATE INDEX CONCURRENTLY IF NOT EXISTS\")\n : vectorIndexStatement(spec)\n });\n }\n vectorIndexSkipped.push(...table.vector.skipped);\n }\n\n // Declared indexes, on exactly the same terms. Boot has to emit these,\n // not just `db push`: the managed runtime provisions at boot and never\n // runs a push, so a push-only index would simply not exist there — and\n // nothing would say so. `contracts/derived-names.txt` states the rule\n // (\"Both, or it is a bug\") and the gate enforces it.\n //\n // `concurrently` is a parameter rather than a string replacement on the\n // rendered SQL: the `.replace(…)` above silently does nothing for a\n // UNIQUE index, whose text is `CREATE UNIQUE INDEX …`.\n for (const spec of sortIndexSpecs(collectionTables.flatMap(t => t.indexes))) {\n actions.push({\n kind: \"create-index\",\n target: `${spec.schema}.${spec.table}`,\n sql: collectionIndexStatement(spec, {\n concurrently: concurrent(spec.schema, spec.table),\n ifNotExists: true\n })\n });\n }\n\n // 6. `autoValue: \"on_update\"` triggers. After the column, and idempotent by\n // DROP-then-CREATE rather than `CREATE OR REPLACE TRIGGER`, which exists\n // only on Postgres 14+.\n for (const table of collectionTables) {\n for (const trigger of table.triggers) {\n // Named after its table and column, so a trigger already in the\n // catalogue is this one — re-issuing it every boot would work and\n // would report a change on a database that has none.\n if (existing.triggers?.has(`${table.qualified}.${trigger.name}`)) continue;\n for (const statement of triggerStatements(trigger)) {\n actions.push({\n kind: \"create-trigger\",\n target: `${table.qualified}.${trigger.name}`,\n sql: statement\n });\n }\n }\n }\n\n // A column the database still requires that no property declares any more.\n //\n // Computed last, over the same live snapshot the rest of the plan read, and\n // only for tables this run did not create — a table created here has exactly\n // the columns the collection asked for, so there is nothing to orphan.\n //\n // Every element of the test matters. NOT NULL, because a nullable leftover\n // accepts a write and is merely untidy. No DEFAULT, because a leftover with\n // one is filled in for you. Not declared, because that is what makes it\n // unreachable — the author has no field to send.\n const orphanedRequiredColumns: OrphanedRequiredColumn[] = [];\n if (existing.notNullColumns && existing.columnDefaults) {\n for (const table of collectionTables) {\n const live = existing.tables.get(table.qualified);\n if (!live || created.has(table.qualified)) continue;\n const declared = new Set<string>();\n for (const column of table.columns) {\n declared.add(column.column);\n if (column.legacyColumn) declared.add(column.legacyColumn);\n }\n for (const column of live) {\n const key = `${table.qualified}.${column}`;\n if (declared.has(column)) continue;\n if (!existing.notNullColumns.has(key)) continue;\n if (existing.columnDefaults.has(key)) continue;\n orphanedRequiredColumns.push({ table: table.qualified, column, slug: table.slug! });\n }\n }\n }\n\n return {\n actions,\n statements: actions.map(a => a.sql),\n legacyForeignKeys,\n searchDrift,\n searchAdopted,\n vectorIndexSkipped,\n withheldConstraints,\n columnTypeDrift,\n orphanedRequiredColumns\n };\n}\n\n/** What a `CREATE FUNCTION` statement is called, for the action log. */\nconst functionTarget = (statement: string): string => {\n if (statement.includes(\"set_updated_at\")) return SET_UPDATED_AT_FN;\n return statement.includes(\"unaccent\") ? SEARCH_UNACCENT_FN : SEARCH_TEXT_FN;\n};\n","/**\n * Applying a schema plan to a database that is already running.\n *\n * ## What this module is\n *\n * A managed runtime boots someone else's compiled project against a database it\n * has never seen. Auth tables are ensured at boot already, but collection tables\n * were not created by anything: the platform ran the app and every `/api/data/*`\n * request answered 500 on a missing relation. `rebase db push` cannot help — it\n * is an Atlas-driven CLI command, and the runtime image ships no CLI.\n *\n * Two halves, and only one of them is here. *What the collections ask for* is\n * `schema/plan/plan-schema.ts`, shared with `db push` and the generated Drizzle\n * file; *what the database already has, and which of those statements are safe\n * to run against it* is `schema/plan/diff-plan.ts`. This module reads the\n * catalogue, runs the statements, and reports what happened.\n *\n * ## Why additive-only, forever\n *\n * This runs unattended, against a database with customers' data in it, with no\n * human reading a diff. So it may only ever do things that cannot lose data.\n * See `diff-plan.ts` for the whole of that argument.\n */\nimport {\n declaredDatabaseExtensions,\n REBASE_SCHEMA,\n type CollectionConfig\n} from \"@rebasepro/types\";\nimport { relationalCollections } from \"@rebasepro/common\";\nimport { logger, isConcurrentDdlRace, isDuplicateObjectRace } from \"@rebasepro/server\";\nimport { SEARCH_STAMP_PREFIX } from \"./search-column\";\nimport { vectorExtensionHint } from \"./vector-index\";\nimport { planJunctionTables, quoteSqlLiteral } from \"./generate-postgres-ddl-logic\";\nimport { planSchema } from \"./plan/plan-schema\";\nimport {\n assertSafeIdentifier,\n diffPlanAgainstCatalogue,\n type ConstraintPolicy,\n type DiffOptions,\n type EnsureAction,\n type EnsurePlan,\n type ExistingSchema,\n type LegacyForeignKey,\n type OrphanedRequiredColumn,\n type SearchColumnDrift,\n type WithheldConstraint\n} from \"./plan/diff-plan\";\nimport { extractCauseMessage, extractPgError } from \"../utils/pg-error-utils\";\nimport { columnTypeDriftMessage, type ColumnTypeDrift } from \"./column-type-drift\";\n\nexport type {\n ConstraintPolicy,\n EnsureAction,\n EnsurePlan,\n ExistingSchema,\n LegacyForeignKey,\n OrphanedRequiredColumn,\n SearchColumnDrift,\n WithheldConstraint\n};\n\n/**\n * The subset of a database handle this needs: run a statement, get rows back.\n *\n * Deliberately parameterless. Everything here is DDL or catalogue reads keyed by\n * schema name, and schema names are identifiers — they cannot be bound as\n * parameters anyway. They are validated by `assertSafeIdentifier` before they\n * reach a statement, so a config that somehow carried a quote is refused rather\n * than concatenated.\n */\nexport interface Queryable {\n query<T = unknown>(sql: string): Promise<{ rows: T[] }>;\n}\n\nexport interface EnsureOptions extends DiffOptions {\n /**\n * Server extensions the project's databases gave Rebase leave to install —\n * `declaredDatabaseExtensions()`. Absent means none, which is a refusal and\n * is the right default for a planner given no configuration at all.\n *\n * Explicit rather than read from the resource registry in here, because the\n * planner is pure and several callers plan against fixtures: reaching for a\n * process-wide registry would make the plan depend on whatever some other\n * module happened to import. `ensureCollectionTables` is the boundary that\n * reads the world.\n */\n databaseExtensions?: readonly string[];\n}\n\nexport interface EnsureOutcome extends EnsurePlan {\n /**\n * Actions that could not be applied and are non-fatal by nature.\n *\n * Two kinds qualify. A foreign key can only fail on data that already\n * violates it, and the column it would police exists either way, so the\n * collection still serves; refusing to boot over one would turn a\n * pre-existing data problem into an outage. A column comment is the search\n * fingerprint, which needs table ownership — losing it costs drift\n * detection on the next boot, not the deployment. Both are reported loudly.\n */\n failures: { kind: EnsureAction[\"kind\"]; target: string; error: string }[];\n}\n\n/** The schema a collection lives in, validated before it reaches any DDL. */\nfunction schemaOf(collection: CollectionConfig): string {\n const schema = (collection as { schema?: string }).schema || \"public\";\n return assertSafeIdentifier(schema, \"schema name\");\n}\n\n/**\n * Decide what to add. Pure — the caller supplies what exists and runs the\n * result.\n *\n * A plan and a diff: the collections are read once, by `planSchema`, into the\n * same {@link SchemaPlan} `db push` renders `schema.sql` from, and the diff\n * subtracts what the database already has. Before that split this function had\n * its own reading of every `Property`, and the audit found twelve places where\n * it disagreed with the two generators — a required `author_id` that was\n * NOT NULL after a push and nullable after a boot among them, on the one path\n * with no developer in the loop.\n */\nexport function planCollectionSchemaEnsure(\n allCollections: CollectionConfig[],\n existing: ExistingSchema,\n options: EnsureOptions = {}\n): EnsurePlan {\n const plan = planSchema(allCollections, { databaseExtensions: options.databaseExtensions });\n return diffPlanAgainstCatalogue(plan, existing, { constraints: options.constraints });\n}\n\n/** Read what the database has, for the schemas the collections live in. */\nexport async function readExistingSchema(\n client: Queryable,\n schemas: string[]\n): Promise<ExistingSchema> {\n const tables = new Map<string, Set<string>>();\n const enums = new Set<string>();\n if (schemas.length === 0) return { tables, enums };\n\n const inList = schemas\n .map(schema => `'${assertSafeIdentifier(schema, \"schema name\")}'`)\n .join(\", \");\n\n const notNullColumns = new Set<string>();\n // `udt_name` rather than `data_type`: `data_type` collapses every array to\n // the literal string `ARRAY` and every extension type to `USER-DEFINED`,\n // which cannot be compared with anything. `udt_name` names the actual type\n // — `int4`, `jsonb`, `_numeric`, `vector` — which is what the drift check\n // needs.\n const columnTypes = new Map<string, string>();\n // A NOT NULL column that has a DEFAULT is not a problem for a write that\n // omits it, so orphan detection needs the default as well as the nullability\n // — otherwise every `created_at DEFAULT now()` on a table whose collection\n // does not declare it would be reported as a blocker.\n const columnDefaults = new Set<string>();\n const { rows: columns } = await client.query<{\n table_schema: string;\n table_name: string;\n column_name: string;\n is_nullable: string;\n udt_name: string | null;\n column_default: string | null;\n numeric_precision: number | null;\n numeric_scale: number | null;\n }>(\n // `numeric_precision`/`numeric_scale` because `udt_name` is `numeric`\n // for both `NUMERIC` and `NUMERIC(10, 2)`, and a property that declares\n // a precision means it: money stored in an unbounded column keeps the\n // third decimal the rounding was supposed to remove. Only carried for\n // `numeric`, where the modifier changes what a value *is*; a `varchar`\n // width is a limit on the same family and `typesAgree` ignores it.\n `SELECT table_schema, table_name, column_name, is_nullable, udt_name, column_default,\n numeric_precision, numeric_scale\n FROM information_schema.columns\n WHERE table_schema IN (${inList})`\n );\n for (const row of columns) {\n const key = `${row.table_schema}.${row.table_name}`;\n if (!tables.has(key)) tables.set(key, new Set());\n tables.get(key)!.add(row.column_name);\n if (row.is_nullable === \"NO\") notNullColumns.add(`${key}.${row.column_name}`);\n if (row.udt_name) {\n const modifier = row.udt_name === \"numeric\" && row.numeric_precision !== null\n ? `(${row.numeric_precision},${row.numeric_scale ?? 0})`\n : \"\";\n columnTypes.set(`${key}.${row.column_name}`, `${row.udt_name}${modifier}`);\n }\n if (row.column_default !== null) columnDefaults.add(`${key}.${row.column_name}`);\n }\n\n // Trigger names, so `autoValue: \"on_update\"` is installed once rather than\n // re-issued on every boot. `tgisinternal` excludes the ones Postgres itself\n // creates to enforce foreign keys.\n const triggers = new Set<string>();\n const { rows: triggerRows } = await client.query<{ schema: string; table: string; name: string }>(\n `SELECT n.nspname AS schema, c.relname AS table, t.tgname AS name\n FROM pg_trigger t\n JOIN pg_class c ON t.tgrelid = c.oid\n JOIN pg_namespace n ON c.relnamespace = n.oid\n WHERE NOT t.tgisinternal AND n.nspname IN (${inList})`\n );\n for (const row of triggerRows) triggers.add(`${row.schema}.${row.table}.${row.name}`);\n\n // Which tables hold rows. This is the only fact that decides whether a\n // NOT NULL can be added without reading the data, so it is worth a query.\n //\n // `reltuples` would be cheaper and is wrong for this: it is a planner\n // estimate, it is -1 on a table that has never been analyzed, and a table\n // that was full an hour ago still reads as full after a DELETE. A wrong\n // \"empty\" here means a boot that aborts on a constraint violation, so the\n // estimate is not good enough. `EXISTS … LIMIT 1` stops at the first row,\n // which makes the true cost one page read per table.\n //\n // Restricted to ordinary and partitioned tables: `information_schema.columns`\n // also lists views and materialized views, and probing those runs whatever\n // query defines them.\n const populatedTables = new Set<string>();\n const { rows: realTables } = await client.query<{ schema: string; name: string }>(\n `SELECT n.nspname AS schema, c.relname AS name\n FROM pg_class c\n JOIN pg_namespace n ON c.relnamespace = n.oid\n WHERE c.relkind IN ('r', 'p') AND n.nspname IN (${inList})`\n );\n if (realTables.length > 0) {\n const probes = realTables.map(row => {\n const schema = assertSafeIdentifier(row.schema, \"schema name\");\n const table = assertSafeIdentifier(row.name, \"table name\");\n return `SELECT ${quoteSqlLiteral(`${schema}.${table}`)} AS key, ` +\n `EXISTS(SELECT 1 FROM \"${schema}\".\"${table}\" LIMIT 1) AS populated`;\n });\n const { rows: populationRows } = await client.query<{ key: string; populated: boolean }>(\n probes.join(\" UNION ALL \")\n );\n for (const row of populationRows) {\n if (row.populated) populatedTables.add(row.key);\n }\n }\n\n const enumValues = new Map<string, string[]>();\n const { rows: enumValueRows } = await client.query<{\n schema: string;\n name: string;\n value: string;\n }>(\n // Ordered by `enumsortorder`, not by label: an enum's order is part of\n // its meaning (it is what `<` compares), and reading it back sorted\n // alphabetically would make a correct type look drifted.\n `SELECT n.nspname AS schema, t.typname AS name, e.enumlabel AS value\n FROM pg_enum e\n JOIN pg_type t ON e.enumtypid = t.oid\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE n.nspname IN (${inList})\n ORDER BY t.typname, e.enumsortorder`\n );\n for (const row of enumValueRows) {\n const key = `${row.schema}.${row.name}`;\n if (!enumValues.has(key)) enumValues.set(key, []);\n enumValues.get(key)!.push(row.value);\n }\n\n const { rows: enumRows } = await client.query<{ schema: string; name: string }>(\n `SELECT n.nspname AS schema, t.typname AS name\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE t.typtype = 'e' AND n.nspname IN (${inList})`\n );\n for (const row of enumRows) enums.add(`${row.schema}.${row.name}`);\n\n // `ADD CONSTRAINT` has no IF NOT EXISTS, so an existing foreign key is\n // skipped by name rather than guarded in SQL.\n const constraints = new Set<string>();\n const { rows: constraintRows } = await client.query<{\n schema: string;\n table: string;\n name: string;\n }>(\n `SELECT n.nspname AS schema, c.relname AS table, con.conname AS name\n FROM pg_constraint con\n JOIN pg_class c ON con.conrelid = c.oid\n JOIN pg_namespace n ON c.relnamespace = n.oid\n WHERE n.nspname IN (${inList})`\n );\n for (const row of constraintRows) constraints.add(`${row.schema}.${row.table}.${row.name}`);\n\n // Column comments, which is where a generated search column records the\n // expression it was built from. `objsubid > 0` is what makes a row a\n // *column* comment rather than the table's own.\n const columnComments = new Map<string, string>();\n const { rows: commentRows } = await client.query<{\n schema: string;\n table: string;\n column: string;\n comment: string | null;\n }>(\n `SELECT n.nspname AS schema, c.relname AS table, a.attname AS column, d.description AS comment\n FROM pg_description d\n JOIN pg_class c ON d.objoid = c.oid\n JOIN pg_namespace n ON c.relnamespace = n.oid\n JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = d.objsubid\n WHERE d.objsubid > 0 AND n.nspname IN (${inList})`\n );\n for (const row of commentRows) {\n if (row.comment == null) continue;\n columnComments.set(`${row.schema}.${row.table}.${row.column}`, row.comment);\n }\n\n return {\n tables, enums, constraints, columnComments, enumValues, notNullColumns, populatedTables, columnTypes,\n columnDefaults, triggers\n };\n}\n\n/**\n * What to tell an operator whose `search` block no longer matches its column.\n *\n * Every line here is doing work: naming the collection is not enough, because\n * the symptom (a search that finds nothing) points at the data, not the schema;\n * and the remediation has to be exact, because it is a table rewrite the\n * operator is being asked to schedule rather than discover.\n */\nfunction searchDriftMessage(drift: SearchColumnDrift[]): string {\n const blocks = drift.map(d =>\n ` \"${d.table}\".\"${d.column}\" was generated from a different \\`search\\` block ` +\n `(recorded ${d.found}, current ${d.expected}).\\n` +\n d.rebuild.map(s => ` ${s}`).join(\"\\n\")\n );\n return (\n \"The `search` block changed after its generated column was created, and Postgres cannot alter a \" +\n \"generated expression in place.\\n\" +\n \"Rebase will not rebuild it for you: dropping and re-adding a STORED generated column rewrites the whole \" +\n \"table under an ACCESS EXCLUSIVE lock and rebuilds its GIN index, which is an outage this unattended path \" +\n \"may not schedule on your behalf.\\n\" +\n \"Until it is rebuilt the column keeps indexing the previous fields, weights and language — searches for \" +\n \"anything added since return nothing, which reads from outside as \\\"no such row\\\".\\n\" +\n \"Run these (or revert the block to what the column was built from), then boot again:\\n\" +\n blocks.join(\"\\n\") +\n \"\\n The GIN index is dropped with the column and recreated concurrently on the next boot.\"\n );\n}\n\n\n/**\n * Read what the database looks like, for the schemas a set of collections\n * lives in.\n *\n * The same read `ensureCollectionTables` does at boot, exposed on its own for\n * the callers that want to *plan* against a real database without changing it —\n * the live schema editor, which has to tell somebody what a change would do\n * before they agree to it.\n */\nexport async function readSchemaFactsFor(\n client: Queryable,\n collections: CollectionConfig[]\n): Promise<ExistingSchema> {\n const relational = relationalCollections(collections);\n const schemas = Array.from(new Set([\n ...relational.map(schemaOf),\n ...planJunctionTables(relational).map(junction => junction.schema)\n ]));\n return readExistingSchema(client, schemas);\n}\n\n/**\n * Bring the database up to date. Returns what it did.\n *\n * Each statement runs on its own rather than in one transaction: they are all\n * independently safe and idempotent, and a single failure (an enum label that\n * cannot be added, say) should not roll back the tables that were created fine.\n * The error is surfaced with the statement that caused it.\n */\nexport async function ensureCollectionTables(\n client: Queryable,\n collections: CollectionConfig[],\n log?: (message: string) => void,\n options: EnsureOptions = {}\n): Promise<EnsureOutcome> {\n // This is the boundary, so this is where the world is read: the planner\n // itself takes the permission as an argument and never reaches for the\n // registry. By the time boot gets here `loadBundleResourceGraph` has\n // evaluated the project's `resources.ts`, so the declarations are there —\n // and a caller that already knows them can still say so.\n const schema = planSchema(collections, {\n databaseExtensions: options.databaseExtensions ?? declaredDatabaseExtensions()\n });\n\n // Junctions live alongside the collections that declare them, so their\n // schema has to be read too — otherwise an existing junction reads as\n // missing and its constraints as unplanned. Taken off the plan, which lists\n // both kinds of table.\n const schemas = Array.from(new Set(schema.tables.map(table => table.schema)));\n for (const name of schemas) {\n assertSafeIdentifier(name, \"schema name\");\n if (name !== \"public\") {\n await client.query(`CREATE SCHEMA IF NOT EXISTS \"${name}\";`);\n }\n }\n // `rebase` is where the `updated_at` trigger's function lives. Every real\n // boot has the schema by the time this runs (auth ensures it first) and\n // `db push` creates it in `schema.sql`, but this path is also driven by the\n // live schema editor and by tests, where \"the function's schema happens to\n // exist already\" is not a thing to rely on. Only when something needs it,\n // so a project with no trigger issues no statement — and not added to the\n // read set: what is *in* `rebase` is auth's business, not this planner's.\n if (schema.tables.some(table => table.triggers.length > 0)) {\n await client.query(`CREATE SCHEMA IF NOT EXISTS \"${REBASE_SCHEMA}\";`);\n }\n\n const existing = await readExistingSchema(client, schemas);\n const plan = diffPlanAgainstCatalogue(schema, existing, { constraints: options.constraints });\n const failures: EnsureOutcome[\"failures\"] = [];\n\n // Reported, not warned: this is a rename the ensure is about to perform, and\n // the operator should be able to see in the log why a column changed name.\n // The interesting case is the one that no longer happens — before this,\n // ensure added the new column empty beside the populated old one, every\n // statement succeeded, and the relation read the empty one.\n for (const legacy of plan.legacyForeignKeys) {\n const message =\n `Renaming \"${legacy.table}\".\"${legacy.legacy}\" to \"${legacy.expected}\". The old name is ` +\n \"the one Rebase derived for this relation before it singularized properly; the column \" +\n \"keeps its data, indexes and constraints. To keep the old name instead, set \" +\n `\\`localKey: \"${legacy.legacy}\"\\` on the relation and this will stop.`;\n logger.info(`[schema] ${message}`);\n log?.(message);\n }\n\n // Before anything is applied: a `search` block that changed after its column\n // was generated cannot be honoured by an additive plan, and serving the old\n // index while the config describes a new one is the silent failure this\n // check exists to end. Refusing is the loud half — boot is fatal on purpose\n // (see `ensureCollectionSchema` in the server's boot) and the message\n // carries the exact statements that resolve it.\n if (plan.searchDrift.length > 0) {\n throw new Error(searchDriftMessage(plan.searchDrift));\n }\n\n // Said once per column, at the moment the stamp is applied: from here on a\n // change is detected, but whether *this* column matches the block it is\n // being stamped with is not knowable — it predates the stamp.\n for (const adopted of plan.searchAdopted) {\n const message =\n `Adopting the existing generated column \"${adopted.table}\".\"${adopted.column}\" and recording what the ` +\n \"current `search` block would generate. Any later change to that block will be detected and refused; a \" +\n \"change made *before* this version was deployed cannot be, so if search has been missing content, \" +\n `rebuild the column once: ALTER TABLE \"${adopted.table.split(\".\").join('\".\"')}\" DROP COLUMN \"${adopted.column}\"; and boot again.`;\n logger.info(`[schema] ${message}`);\n log?.(message);\n }\n\n // Said once per column, every boot: an unindexed vector column and an\n // indexed one behave identically apart from latency, so the only way anyone\n // learns which one they have is if the boot says so.\n for (const skip of plan.vectorIndexSkipped) {\n const message = `No ANN index on \"${skip.table}\".\"${skip.column}\": ${skip.reason}`;\n logger.warn(`[schema] ${message}`);\n log?.(message);\n }\n\n // Said once per column, every boot, because the alternative is what this\n // whole feature exists to end: a column the configuration calls required,\n // sitting there nullable, with every surface reporting success. The boot\n // does not fail over it — the column is usable and the data is intact — but\n // it stops being invisible.\n for (const withheld of plan.withheldConstraints) {\n const message =\n `No NOT NULL on \"${withheld.target}\": ${withheld.reason} ${withheld.remedy}`;\n logger.warn(`[schema] ${message}`);\n log?.(message);\n }\n\n // Said once per drifted column, every boot, and this is the one report here\n // that describes a system which currently *looks* healthy. Everything else\n // in this function explains a statement that did not run; this explains a\n // statement that was never planned, on a deploy that reported success, and\n // whose first symptom is a write rejected long afterwards.\n for (const drift of plan.columnTypeDrift) {\n const message = columnTypeDriftMessage(drift);\n logger.warn(`[schema] ${message}`);\n log?.(message);\n }\n\n // Said once per column, every boot, and it matters more than the rest here\n // because the table is not merely imperfect — it is unwritable, and the\n // error the API returns names a field the author has already deleted.\n // This is what a renamed property looks like to an additive provisioner.\n for (const orphan of plan.orphanedRequiredColumns) {\n const [schema, table] = orphan.table.split(\".\");\n const message =\n `\"${orphan.table}\".\"${orphan.column}\" is NOT NULL with no default, and the \"${orphan.slug}\" ` +\n \"collection no longer declares it. Every insert will be rejected for a field you cannot set \" +\n `(PG_23502, naming \"${orphan.column}\"). This is what a renamed property looks like: the new ` +\n \"column was added, and the old one cannot be dropped unattended. Fix it with ONE of:\\n\" +\n ` ALTER TABLE \"${schema}\".\"${table}\" DROP COLUMN \"${orphan.column}\"; -- the rename is complete\\n` +\n ` ALTER TABLE \"${schema}\".\"${table}\" ALTER COLUMN \"${orphan.column}\" DROP NOT NULL; -- keep the data, stop requiring it\\n` +\n \" ...or declare the property again, if the column is still wanted.\";\n logger.warn(`[schema] ${message}`);\n log?.(message);\n }\n\n if (plan.actions.length === 0) {\n log?.(\"Schema is up to date; nothing to create.\");\n return { ...plan, failures };\n }\n\n for (const action of plan.actions) {\n try {\n if (await applyAction(client, action)) {\n log?.(`${action.kind}: ${action.target}`);\n } else {\n log?.(`${action.kind}: ${action.target} (already created by a peer)`);\n }\n } catch (err) {\n const message = describeDriverError(err);\n // A foreign key is the only action that can fail on the customer's\n // data rather than on the schema. The column it polices is already\n // there, so the collection serves either way — record it and carry\n // on rather than crash-looping the deployment.\n //\n // A comment is metadata about a column that was just created\n // successfully, and it can only fail on ownership (COMMENT requires\n // owning the table, which an adopted table may not grant). Losing\n // the stamp costs drift detection on the next boot; it must not cost\n // the deployment.\n //\n // An index that is not UNIQUE is an optimization, and losing an\n // optimization must not cost the deployment. This was the difference\n // between a slow collection and a tenant that would not boot: on a\n // managed runtime the throw killed the process, the pod never went\n // ready, and the deploy reported a 300-second readiness timeout — for\n // an ANN index whose absence changes latency and nothing else.\n //\n // UNIQUE is excluded because it is not an optimization. It is the\n // collection declaring that two rows cannot share a value, and\n // serving without it is serving a promise the database is not\n // keeping.\n const survivable =\n action.kind === \"add-constraint\" ||\n action.kind === \"comment-column\" ||\n (action.kind === \"create-index\" && !/CREATE\\s+UNIQUE\\s+INDEX/i.test(action.sql));\n if (survivable) {\n failures.push({ kind: action.kind, target: action.target, error: message });\n continue;\n }\n throw new Error(\n `Failed to ${action.kind} ${action.target}: ${message}${vectorExtensionHint(message)}\\n ${action.sql}`\n );\n }\n }\n return { ...plan, failures };\n}\n\n/**\n * What actually went wrong, rather than what the ORM said about it.\n *\n * Drizzle wraps every driver error, and its `message` is literally\n * ``Failed query: ${sql}\\nparams: ${params}`` — the statement we already know,\n * and not one word of Postgres's answer. Reporting `err.message` therefore\n * produced a failure that named the statement twice and the *reason* zero\n * times, so four unrelated boot failures — a missing extension, a wrong\n * privilege, a bad index method, a constraint the rows violate — all read\n * identically to whoever had to fix them.\n *\n * Two consequences, both observed in the field before this existed:\n *\n * 1. On a managed deployment the reason never reaches anybody. Boot dies, the\n * pod never goes ready, and the deploy reports a readiness timeout — so the\n * one line that says why is the one line that was thrown away here.\n * 2. {@link vectorExtensionHint} matches on the error text. Against the\n * wrapper it matched nothing, so the hint written specifically to explain a\n * missing pgvector never fired on the path that raises it.\n *\n * `detail` and `hint` come along because they are the fields Postgres uses to\n * say which object it meant and what to do about it — `CREATE EXTENSION` names\n * the missing library there, and a rejected constraint names the row. This\n * writes into the tenant's own boot log, about the tenant's own database.\n */\nexport function describeDriverError(err: unknown): string {\n const pg = extractPgError(err);\n if (pg) {\n const parts = [pg.code ? `${pg.message} [${pg.code}]` : pg.message];\n if (pg.detail) parts.push(` detail: ${pg.detail}`);\n if (pg.hint) parts.push(` hint: ${pg.hint}`);\n return parts.join(\"\\n\");\n }\n // No SQLSTATE anywhere in the chain: not a database answer at all — a\n // socket that closed, a bug in this file. The deepest cause still beats the\n // wrapper, and the wrapper still beats nothing.\n const cause = extractCauseMessage(err);\n if (cause) return cause;\n return err instanceof Error ? err.message : String(err);\n}\n\n/** ` CONCURRENTLY ` as it appears in a rendered `CREATE [UNIQUE] INDEX`. */\nconst CONCURRENTLY_RE = /\\sCONCURRENTLY\\s/i;\n\n/**\n * `25001 active_sql_transaction` — \"cannot run inside a transaction block\".\n *\n * Only ever raised here by `CREATE INDEX CONCURRENTLY`, and only when the\n * connection we were handed is inside a transaction. Deliberately narrow: it\n * decides to retry a *different* statement, so it must not fire on anything it\n * has not been reasoned about.\n */\nfunction isTransactionBlockRefusal(err: unknown): boolean {\n return extractPgError(err)?.code === \"25001\";\n}\n\n/** Attempts per action, including the first. Matches the server's bootstraps. */\nconst DDL_ATTEMPTS = 4;\n\n/**\n * Run one planned statement, surviving a simultaneous boot.\n *\n * Every statement in a plan is written to be idempotent, and that is not the\n * same as being safe to run concurrently: `CREATE … IF NOT EXISTS` reads the\n * catalog and then writes to it as two steps, so peers starting together both\n * see \"absent\" and the loser gets a duplicate key on a *catalog* index. Measured\n * against Postgres 18: five instances, 8 of 10 calls lost. `CREATE TYPE` is\n * worse, because Postgres has no `IF NOT EXISTS` for it at all.\n *\n * What made that fatal here rather than merely noisy is the loop this sits in.\n * A losing statement threw, and the throw abandoned **every remaining action in\n * the plan** — so a replica that lost one race came up missing tables it never\n * attempted, and the boot log blamed the one statement that failed.\n *\n * @returns `true` if this process applied the statement, `false` if a peer had\n * already created the object. The distinction is only for the log; both mean\n * the object is now there.\n * @throws the original error for anything that is not a race — a syntax error, a\n * permission failure, a unique constraint the customer's own rows violate.\n */\nasync function applyAction(\n client: Queryable,\n action: EnsureAction\n): Promise<boolean> {\n let sqlText = action.sql;\n for (let attempt = 1; ; attempt++) {\n try {\n await client.query(sqlText);\n return true;\n } catch (err) {\n // `CREATE INDEX CONCURRENTLY` is the one statement here Postgres\n // refuses inside a transaction block (25001), and whether we are in\n // one is not ours to know: the client is whatever handle the caller\n // bootstrapped with, and an application that builds its own adapter\n // can hand us a connection already inside a transaction. The plain\n // form is always correct and never refused — it takes a write lock\n // for the build, which is the cost of getting the index at all.\n if (isTransactionBlockRefusal(err) && CONCURRENTLY_RE.test(sqlText)) {\n sqlText = sqlText.replace(CONCURRENTLY_RE, \" \");\n logger.warn(\n `[schema] ${action.kind} ${action.target}: this connection is inside a transaction, ` +\n \"so the index is being built with a write lock rather than concurrently. Writes to \" +\n \"this table block until it finishes.\"\n );\n continue;\n }\n // Already there. Not \"retry\" — the end state this statement wanted\n // is the end state the database is in, so carry on to the next\n // action rather than spending three more attempts proving it.\n if (isDuplicateObjectRace(err)) {\n logger.debug(\n `[schema] ${action.kind} ${action.target}: already created by another instance`\n );\n return false;\n }\n // Retryable but not yet satisfied — a deadlock between two boots\n // taking catalog locks in step. The statement did nothing; run it\n // again after a jittered pause so peers that collided once do not\n // collide again in lockstep.\n if (isConcurrentDdlRace(err) && attempt < DDL_ATTEMPTS) {\n logger.debug(\n `[schema] ${action.kind} ${action.target}: lost a race with another instance ` +\n `(attempt ${attempt}/${DDL_ATTEMPTS}) — retrying`\n );\n await new Promise(resolve => setTimeout(resolve, 40 * attempt * (1 + Math.random())));\n continue;\n }\n throw err;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA8DA,IAAM,WAAmC;CAErC,MAAM;CAAU,UAAU;CAC1B,MAAM;CAAU,KAAK;CAAU,SAAS;CACxC,MAAM;CAAU,QAAQ;CACxB,SAAS;CAAU,SAAS;CAC5B,QAAQ;CAAU,MAAM;CACxB,QAAQ;CAAU,oBAAoB;CACtC,OAAO;CAGP,MAAM;CAAQ,SAAS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;;;;;;;;;;;;;;;AAuBrB,eAAe,YACX,QACA,QACgB;CAChB,IAAI,UAAU,OAAO;CACrB,KAAK,IAAI,UAAU,IAAK,WACpB,IAAI;EACA,MAAM,OAAO,MAAM,OAAO;EAC1B,OAAO;CACX,SAAS,KAAK;EAQV,IAAI,0BAA0B,GAAG,KAAK,gBAAgB,KAAK,OAAO,GAAG;GACjE,UAAU,QAAQ,QAAQ,iBAAiB,GAAG;GAC9C,OAAO,KACH,YAAY,OAAO,KAAK,GAAG,OAAO,OAAO,iKAG7C;GACA;EACJ;EAIA,IAAI,sBAAsB,GAAG,GAAG;GAC5B,OAAO,MACH,YAAY,OAAO,KAAK,GAAG,OAAO,OAAO,sCAC7C;GACA,OAAO;EACX;EAKA,IAAI,oBAAoB,GAAG,KAAK,UAAU,cAAc;GACpD,OAAO,MACH,YAAY,OAAO,KAAK,GAAG,OAAO,OAAO,+CAC7B,QAAQ,GAAG,aAAa,aACxC;GACA,MAAM,IAAI,SAAQ,YAAW,WAAW,SAAS,KAAK,WAAW,IAAI,KAAK,OAAO,EAAE,CAAC;GACpF;EACJ;EACA,MAAM;CACV;AAER"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
|
-
import { t as generateSchema } from "./generate-drizzle-schema-logic-
|
|
3
|
+
import { t as generateSchema } from "./generate-drizzle-schema-logic-DFa9qy9u.js";
|
|
4
4
|
import { n as outError, t as out } from "./cli-output-CNdMql-L.js";
|
|
5
5
|
import { loadCollectionsFromDirectory } from "@rebasepro/server";
|
|
6
6
|
import { promises } from "fs";
|
|
@@ -120,4 +120,4 @@ if (import.meta.url.endsWith(process.argv[1])) main().catch(() => {
|
|
|
120
120
|
//#endregion
|
|
121
121
|
export { main as t };
|
|
122
122
|
|
|
123
|
-
//# sourceMappingURL=generate-drizzle-schema-
|
|
123
|
+
//# sourceMappingURL=generate-drizzle-schema-D2MDdJt-.js.map
|
package/dist/{generate-drizzle-schema-vSK-VdYT.js.map → generate-drizzle-schema-D2MDdJt-.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-drizzle-schema-vSK-VdYT.js","names":[],"sources":["../src/schema/generate-next-step.ts","../src/schema/generate-drizzle-schema.ts"],"sourcesContent":["/**\n * The line `rebase schema generate` ends on.\n *\n * Its own module because `generate-drizzle-schema.ts` uses `import.meta` to\n * decide whether it was executed directly, which the driver's jest suite cannot\n * load at all — so the one sentence in that file with a decision in it had no\n * test and could not have one where it stood.\n */\n\nexport const formatTerminalText = (text: string, options: {\n bold?: boolean;\n backgroundColor?: \"blue\" | \"green\" | \"red\" | \"yellow\" | \"cyan\" | \"magenta\";\n textColor?: \"white\" | \"black\" | \"red\" | \"green\" | \"yellow\" | \"blue\" | \"magenta\" | \"cyan\";\n} = {}): string => {\n let codes = \"\";\n if (options.bold) codes += \"\\x1b[1m\";\n if (options.backgroundColor) {\n const bgColors = {\n blue: \"\\x1b[44m\",\n green: \"\\x1b[42m\",\n red: \"\\x1b[41m\",\n yellow: \"\\x1b[43m\",\n cyan: \"\\x1b[46m\",\n magenta: \"\\x1b[45m\"\n } as const;\n codes += bgColors[options.backgroundColor];\n }\n if (options.textColor) {\n const textColors = {\n white: \"\\x1b[37m\",\n black: \"\\x1b[30m\",\n red: \"\\x1b[31m\",\n green: \"\\x1b[32m\",\n yellow: \"\\x1b[33m\",\n blue: \"\\x1b[34m\",\n magenta: \"\\x1b[35m\",\n cyan: \"\\x1b[36m\"\n } as const;\n codes += textColors[options.textColor];\n }\n return `${codes}${text}\\x1b[0m`;\n};\n\n/**\n * What to do with the file that was just generated.\n *\n * Not the same answer on the managed development database: `rebase db generate`\n * plans with Atlas, Atlas needs a second empty database to diff against, and\n * PGlite serves exactly one — so the CLI refuses that command outright there.\n * This line recommended it unconditionally, which meant every stock scaffold\n * was told, by the tool itself, to run something the same tool would refuse.\n *\n * The kind arrives as `REBASE_DEV_DATABASE_KIND`, set by the CLI from the\n * ordered resolution in `dev-db/resolve.ts`. It is a pure decision — nothing is\n * started to make it — and the driver cannot make it for itself: on the managed\n * path `DATABASE_URL` is a perfectly ordinary connection string to a Postgres\n * on loopback. Absent (the driver run directly, outside the CLI) keeps the\n * original wording.\n */\nexport const nextStepAfterGenerate = (): string => {\n if (process.env.REBASE_DEV_DATABASE_KIND === \"managed\") {\n return `Start or restart ${formatTerminalText(\"rebase dev\", {\n bold: true,\n backgroundColor: \"blue\",\n textColor: \"black\"\n })} — boot applies your collections to the managed development database.`;\n }\n\n return `You can now run ${formatTerminalText(\"rebase db generate\", {\n bold: true,\n backgroundColor: \"blue\",\n textColor: \"black\"\n })} to generate the SQL migration files.`;\n};\n","import { promises as fsPromises } from \"fs\";\nimport * as fs from \"fs\";\nimport path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport { generateSchema } from \"./generate-drizzle-schema-logic\";\nimport { CollectionConfig } from \"@rebasepro/types\";\nimport { loadCollectionsFromDirectory } from \"@rebasepro/server\";\nimport { out, outError } from \"../cli-output\";\nimport { nextStepAfterGenerate } from \"./generate-next-step\";\n\n\n// --- Execution and Watch Logic ---\n\nconst runGeneration = async (collectionsFilePath?: string, outputPath?: string) => {\n try {\n if (!collectionsFilePath) {\n throw new Error(\"No collections file path provided.\");\n }\n\n const resolvedPath = path.resolve(collectionsFilePath);\n\n // Shared with the runtime and the doctor: what gets generated here must\n // be exactly what the server serves, including directory-level defaults.\n let collections: CollectionConfig[] = await loadCollectionsFromDirectory(resolvedPath);\n\n\n // If collections directory is empty but exists, or failed to find any, we still want to inject defaults\n if (!collections || !Array.isArray(collections)) {\n collections = [];\n }\n\n\n // Sort collections by slug alphabetically to ensure deterministic schema generation\n collections.sort((a, b) => a.slug.localeCompare(b.slug));\n\n const schemaContent = generateSchema(collections);\n\n if (outputPath) {\n const outputDir = path.dirname(outputPath);\n await fsPromises.mkdir(outputDir, { recursive: true });\n await fsPromises.writeFile(outputPath, schemaContent);\n out(`✅ Drizzle schema generated successfully at ${outputPath}`);\n } else {\n out(\"✅ Drizzle schema generated successfully.\");\n out(String(schemaContent));\n }\n\n out(nextStepAfterGenerate());\n\n } catch (error) {\n outError(`Error generating schema: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`);\n // The same contract its sibling `generate-postgres-ddl.ts` keeps, and\n // for the same reason: `rebase db push` runs both as step 1 and reads\n // nothing but their exit codes. Exiting 0 after printing an error made\n // the push apply whatever `src/schema.generated.ts` was already there.\n process.exitCode = 1;\n throw error;\n }\n};\n\nexport const main = async () => {\n const collectionsFilePathArg = process.argv.find(arg => arg.startsWith(\"--collections=\"));\n const collectionsFilePath = collectionsFilePathArg ? collectionsFilePathArg.split(\"=\")[1] : process.argv[2];\n\n const outputPathArg = process.argv.find(arg => arg.startsWith(\"--output=\"));\n const outputPath = outputPathArg ? outputPathArg.split(\"=\")[1] : undefined;\n\n const watch = process.argv.includes(\"--watch\");\n\n if (!collectionsFilePath) {\n out(\"Usage: ts-node generate-drizzle-schema.ts <path-to-collections-file> [--output <path-to-output-file>] [--watch]\");\n return;\n }\n\n const resolvedPath = path.resolve(process.cwd(), collectionsFilePath);\n const resolvedOutputPath = outputPath ? path.resolve(process.cwd(), outputPath) : undefined;\n\n if (watch) {\n out(`Watching for changes in ${resolvedPath}...`);\n // Imported here rather than at module scope, and this is not a style\n // choice: chokidar is needed only by `--watch`, which is a\n // schema-authoring path that never runs inside the runtime image. A\n // top-level import puts it on the boot path of the published driver\n // bundle, and the image installs a hand-listed set of runtime\n // dependencies that does not include it — so the whole driver failed to\n // load with \"Cannot find package 'chokidar'\", and every self-hosted\n // container answered 500 with a stack trace about a file watcher.\n //\n // Same reasoning the image already applies to @ariga/atlas: an\n // authoring-only dependency does not belong on a boot path.\n const { default: chokidar } = await import(\"chokidar\");\n const watcher = chokidar.watch(resolvedPath, {\n persistent: true,\n ignoreInitial: false\n });\n\n watcher.on(\"all\", (event, filePath) => {\n out(`[${event}] ${filePath}. Regenerating schema...`);\n // A watch session outlives a bad edit; the next save is the retry.\n void runGeneration(resolvedPath, resolvedOutputPath).catch(() => undefined);\n });\n } else {\n await runGeneration(resolvedPath, resolvedOutputPath);\n }\n};\n\n// This check ensures the script only runs when executed directly\nif (import.meta.url.endsWith(process.argv[1])) {\n // The cause is already on stderr with the exit code set; this keeps Node\n // from printing the same stack again as an unhandled rejection.\n main().catch(() => {\n process.exitCode = 1;\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AASA,IAAa,sBAAsB,MAAc,UAI7C,CAAC,MAAc;CACf,IAAI,QAAQ;CACZ,IAAI,QAAQ,MAAM,SAAS;CAC3B,IAAI,QAAQ,iBASR,SAAS;EAPL,MAAM;EACN,OAAO;EACP,KAAK;EACL,QAAQ;EACR,MAAM;EACN,SAAS;CAEJ,EAAS,QAAQ;CAE9B,IAAI,QAAQ,WAWR,SAAS;EATL,OAAO;EACP,OAAO;EACP,KAAK;EACL,OAAO;EACP,QAAQ;EACR,MAAM;EACN,SAAS;EACT,MAAM;CAED,EAAW,QAAQ;CAEhC,OAAO,GAAG,QAAQ,KAAK;AAC3B;;;;;;;;;;;;;;;;;AAkBA,IAAa,8BAAsC;CAC/C,IAAI,QAAQ,IAAI,6BAA6B,WACzC,OAAO,oBAAoB,mBAAmB,cAAc;EACxD,MAAM;EACN,iBAAiB;EACjB,WAAW;CACf,CAAC,EAAE;CAGP,OAAO,mBAAmB,mBAAmB,sBAAsB;EAC/D,MAAM;EACN,iBAAiB;EACjB,WAAW;CACf,CAAC,EAAE;AACP;;;AC5DA,IAAM,gBAAgB,OAAO,qBAA8B,eAAwB;CAC/E,IAAI;EACA,IAAI,CAAC,qBACD,MAAM,IAAI,MAAM,oCAAoC;EAOxD,IAAI,cAAkC,MAAM,6BAJvB,KAAK,QAAQ,mBAIuC,CAAY;EAIrF,IAAI,CAAC,eAAe,CAAC,MAAM,QAAQ,WAAW,GAC1C,cAAc,CAAC;EAKnB,YAAY,MAAM,GAAG,MAAM,EAAE,KAAK,c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AAI,MAAM,IAAI,SAAS,yBAAyB;GAEpD,cAAmB,cAAc,kBAAkB,CAAC,CAAC,YAAY,KAAA,CAAS;EAC9E,CAAC;CACL,OACI,MAAM,cAAc,cAAc,kBAAkB;AAE5D;AAGA,IAAI,OAAO,KAAK,IAAI,SAAS,QAAQ,KAAK,EAAE,GAGxC,KAAK,CAAC,CAAC,YAAY;CACf,QAAQ,WAAW;AACvB,CAAC"}
|
|
1
|
+
{"version":3,"file":"generate-drizzle-schema-D2MDdJt-.js","names":[],"sources":["../src/schema/generate-next-step.ts","../src/schema/generate-drizzle-schema.ts"],"sourcesContent":["/**\n * The line `rebase schema generate` ends on.\n *\n * Its own module because `generate-drizzle-schema.ts` uses `import.meta` to\n * decide whether it was executed directly, which the driver's jest suite cannot\n * load at all — so the one sentence in that file with a decision in it had no\n * test and could not have one where it stood.\n */\n\nexport const formatTerminalText = (text: string, options: {\n bold?: boolean;\n backgroundColor?: \"blue\" | \"green\" | \"red\" | \"yellow\" | \"cyan\" | \"magenta\";\n textColor?: \"white\" | \"black\" | \"red\" | \"green\" | \"yellow\" | \"blue\" | \"magenta\" | \"cyan\";\n} = {}): string => {\n let codes = \"\";\n if (options.bold) codes += \"\\x1b[1m\";\n if (options.backgroundColor) {\n const bgColors = {\n blue: \"\\x1b[44m\",\n green: \"\\x1b[42m\",\n red: \"\\x1b[41m\",\n yellow: \"\\x1b[43m\",\n cyan: \"\\x1b[46m\",\n magenta: \"\\x1b[45m\"\n } as const;\n codes += bgColors[options.backgroundColor];\n }\n if (options.textColor) {\n const textColors = {\n white: \"\\x1b[37m\",\n black: \"\\x1b[30m\",\n red: \"\\x1b[31m\",\n green: \"\\x1b[32m\",\n yellow: \"\\x1b[33m\",\n blue: \"\\x1b[34m\",\n magenta: \"\\x1b[35m\",\n cyan: \"\\x1b[36m\"\n } as const;\n codes += textColors[options.textColor];\n }\n return `${codes}${text}\\x1b[0m`;\n};\n\n/**\n * What to do with the file that was just generated.\n *\n * Not the same answer on the managed development database: `rebase db generate`\n * plans with Atlas, Atlas needs a second empty database to diff against, and\n * PGlite serves exactly one — so the CLI refuses that command outright there.\n * This line recommended it unconditionally, which meant every stock scaffold\n * was told, by the tool itself, to run something the same tool would refuse.\n *\n * The kind arrives as `REBASE_DEV_DATABASE_KIND`, set by the CLI from the\n * ordered resolution in `dev-db/resolve.ts`. It is a pure decision — nothing is\n * started to make it — and the driver cannot make it for itself: on the managed\n * path `DATABASE_URL` is a perfectly ordinary connection string to a Postgres\n * on loopback. Absent (the driver run directly, outside the CLI) keeps the\n * original wording.\n */\nexport const nextStepAfterGenerate = (): string => {\n if (process.env.REBASE_DEV_DATABASE_KIND === \"managed\") {\n return `Start or restart ${formatTerminalText(\"rebase dev\", {\n bold: true,\n backgroundColor: \"blue\",\n textColor: \"black\"\n })} — boot applies your collections to the managed development database.`;\n }\n\n return `You can now run ${formatTerminalText(\"rebase db generate\", {\n bold: true,\n backgroundColor: \"blue\",\n textColor: \"black\"\n })} to generate the SQL migration files.`;\n};\n","import { promises as fsPromises } from \"fs\";\nimport * as fs from \"fs\";\nimport path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport { generateSchema } from \"./generate-drizzle-schema-logic\";\nimport { CollectionConfig } from \"@rebasepro/types\";\nimport { loadCollectionsFromDirectory } from \"@rebasepro/server\";\nimport { out, outError } from \"../cli-output\";\nimport { nextStepAfterGenerate } from \"./generate-next-step\";\n\n\n// --- Execution and Watch Logic ---\n\nconst runGeneration = async (collectionsFilePath?: string, outputPath?: string) => {\n try {\n if (!collectionsFilePath) {\n throw new Error(\"No collections file path provided.\");\n }\n\n const resolvedPath = path.resolve(collectionsFilePath);\n\n // Shared with the runtime and the doctor: what gets generated here must\n // be exactly what the server serves, including directory-level defaults.\n let collections: CollectionConfig[] = await loadCollectionsFromDirectory(resolvedPath);\n\n\n // If collections directory is empty but exists, or failed to find any, we still want to inject defaults\n if (!collections || !Array.isArray(collections)) {\n collections = [];\n }\n\n\n // Sort collections by slug alphabetically to ensure deterministic schema generation\n collections.sort((a, b) => a.slug.localeCompare(b.slug));\n\n const schemaContent = generateSchema(collections);\n\n if (outputPath) {\n const outputDir = path.dirname(outputPath);\n await fsPromises.mkdir(outputDir, { recursive: true });\n await fsPromises.writeFile(outputPath, schemaContent);\n out(`✅ Drizzle schema generated successfully at ${outputPath}`);\n } else {\n out(\"✅ Drizzle schema generated successfully.\");\n out(String(schemaContent));\n }\n\n out(nextStepAfterGenerate());\n\n } catch (error) {\n outError(`Error generating schema: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`);\n // The same contract its sibling `generate-postgres-ddl.ts` keeps, and\n // for the same reason: `rebase db push` runs both as step 1 and reads\n // nothing but their exit codes. Exiting 0 after printing an error made\n // the push apply whatever `src/schema.generated.ts` was already there.\n process.exitCode = 1;\n throw error;\n }\n};\n\nexport const main = async () => {\n const collectionsFilePathArg = process.argv.find(arg => arg.startsWith(\"--collections=\"));\n const collectionsFilePath = collectionsFilePathArg ? collectionsFilePathArg.split(\"=\")[1] : process.argv[2];\n\n const outputPathArg = process.argv.find(arg => arg.startsWith(\"--output=\"));\n const outputPath = outputPathArg ? outputPathArg.split(\"=\")[1] : undefined;\n\n const watch = process.argv.includes(\"--watch\");\n\n if (!collectionsFilePath) {\n out(\"Usage: ts-node generate-drizzle-schema.ts <path-to-collections-file> [--output <path-to-output-file>] [--watch]\");\n return;\n }\n\n const resolvedPath = path.resolve(process.cwd(), collectionsFilePath);\n const resolvedOutputPath = outputPath ? path.resolve(process.cwd(), outputPath) : undefined;\n\n if (watch) {\n out(`Watching for changes in ${resolvedPath}...`);\n // Imported here rather than at module scope, and this is not a style\n // choice: chokidar is needed only by `--watch`, which is a\n // schema-authoring path that never runs inside the runtime image. A\n // top-level import puts it on the boot path of the published driver\n // bundle, and the image installs a hand-listed set of runtime\n // dependencies that does not include it — so the whole driver failed to\n // load with \"Cannot find package 'chokidar'\", and every self-hosted\n // container answered 500 with a stack trace about a file watcher.\n //\n // Same reasoning the image already applies to @ariga/atlas: an\n // authoring-only dependency does not belong on a boot path.\n const { default: chokidar } = await import(\"chokidar\");\n const watcher = chokidar.watch(resolvedPath, {\n persistent: true,\n ignoreInitial: false\n });\n\n watcher.on(\"all\", (event, filePath) => {\n out(`[${event}] ${filePath}. Regenerating schema...`);\n // A watch session outlives a bad edit; the next save is the retry.\n void runGeneration(resolvedPath, resolvedOutputPath).catch(() => undefined);\n });\n } else {\n await runGeneration(resolvedPath, resolvedOutputPath);\n }\n};\n\n// This check ensures the script only runs when executed directly\nif (import.meta.url.endsWith(process.argv[1])) {\n // The cause is already on stderr with the exit code set; this keeps Node\n // from printing the same stack again as an unhandled rejection.\n main().catch(() => {\n process.exitCode = 1;\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AASA,IAAa,sBAAsB,MAAc,UAI7C,CAAC,MAAc;CACf,IAAI,QAAQ;CACZ,IAAI,QAAQ,MAAM,SAAS;CAC3B,IAAI,QAAQ,iBASR,SAAS;EAPL,MAAM;EACN,OAAO;EACP,KAAK;EACL,QAAQ;EACR,MAAM;EACN,SAAS;CAEJ,EAAS,QAAQ;CAE9B,IAAI,QAAQ,WAWR,SAAS;EATL,OAAO;EACP,OAAO;EACP,KAAK;EACL,OAAO;EACP,QAAQ;EACR,MAAM;EACN,SAAS;EACT,MAAM;CAED,EAAW,QAAQ;CAEhC,OAAO,GAAG,QAAQ,KAAK;AAC3B;;;;;;;;;;;;;;;;;AAkBA,IAAa,8BAAsC;CAC/C,IAAI,QAAQ,IAAI,6BAA6B,WACzC,OAAO,oBAAoB,mBAAmB,cAAc;EACxD,MAAM;EACN,iBAAiB;EACjB,WAAW;CACf,CAAC,EAAE;CAGP,OAAO,mBAAmB,mBAAmB,sBAAsB;EAC/D,MAAM;EACN,iBAAiB;EACjB,WAAW;CACf,CAAC,EAAE;AACP;;;AC5DA,IAAM,gBAAgB,OAAO,qBAA8B,eAAwB;CAC/E,IAAI;EACA,IAAI,CAAC,qBACD,MAAM,IAAI,MAAM,oCAAoC;EAO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A2B,aAAa,IAAI;EAYhD,MAAM,EAAE,SAAS,aAAa,MAAM,OAAO;EAM3C,SALyB,MAAM,cAAc;GACzC,YAAY;GACZ,eAAe;EACnB,CAEA,CAAA,CAAQ,GAAG,QAAQ,OAAO,aAAa;GACnC,IAAI,IAAI,MAAM,IAAI,SAAS,yBAAyB;GAEpD,cAAmB,cAAc,kBAAkB,CAAC,CAAC,YAAY,KAAA,CAAS;EAC9E,CAAC;CACL,OACI,MAAM,cAAc,cAAc,kBAAkB;AAE5D;AAGA,IAAI,OAAO,KAAK,IAAI,SAAS,QAAQ,KAAK,EAAE,GAGxC,KAAK,CAAC,CAAC,YAAY;CACf,QAAQ,WAAW;AACvB,CAAC"}
|
package/dist/{generate-drizzle-schema-logic-Dfyf_MRu.js → generate-drizzle-schema-logic-DFa9qy9u.js}
RENAMED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
|
+
import { r as __exportAll } from "./__vite-browser-external-BnuHet1e.js";
|
|
3
4
|
import { n as planSchema } from "./plan-schema-Hgl62S-w.js";
|
|
4
5
|
import { s as renderPredicate } from "./collection-index-DdnsxiJ_.js";
|
|
5
6
|
import { relationalCollections, sortCollectionsBySlug } from "@rebasepro/common";
|
|
@@ -207,6 +208,7 @@ var renderRelation = (table, relation) => {
|
|
|
207
208
|
};
|
|
208
209
|
//#endregion
|
|
209
210
|
//#region src/schema/generate-drizzle-schema-logic.ts
|
|
211
|
+
var generate_drizzle_schema_logic_exports = /* @__PURE__ */ __exportAll({ generateSchema: () => generateSchema });
|
|
210
212
|
/**
|
|
211
213
|
* The generated Drizzle schema for a set of collections.
|
|
212
214
|
*
|
|
@@ -223,6 +225,6 @@ var generateSchema = (allCollections, options = {}) => {
|
|
|
223
225
|
return renderDrizzleSchema(planSchema(sortCollectionsBySlug(relationalCollections(allCollections))), options);
|
|
224
226
|
};
|
|
225
227
|
//#endregion
|
|
226
|
-
export { generateSchema as t };
|
|
228
|
+
export { generate_drizzle_schema_logic_exports as n, generateSchema as t };
|
|
227
229
|
|
|
228
|
-
//# sourceMappingURL=generate-drizzle-schema-logic-
|
|
230
|
+
//# sourceMappingURL=generate-drizzle-schema-logic-DFa9qy9u.js.map
|