@rebasepro/server-postgres 0.18.0 → 0.18.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/dist/BranchService-ByLfM_Tt.js +360 -0
- package/dist/BranchService-ByLfM_Tt.js.map +1 -0
- package/dist/__vite-browser-external-BnuHet1e.js +46 -0
- package/dist/__vite-browser-external-BnuHet1e.js.map +1 -0
- package/dist/arg-Dni7MzLB.js +87 -0
- package/dist/arg-Dni7MzLB.js.map +1 -0
- package/dist/auth-users-columns-D2LBFrMH.js +116 -0
- package/dist/auth-users-columns-D2LBFrMH.js.map +1 -0
- package/dist/backup-cli-oM9WQVlV.js +408 -0
- package/dist/backup-cli-oM9WQVlV.js.map +1 -0
- package/dist/backup-service-Br3tqwsy.js +715 -0
- package/dist/backup-service-Br3tqwsy.js.map +1 -0
- package/dist/cli-errors-DxN4yzdH.js +657 -0
- package/dist/cli-errors-DxN4yzdH.js.map +1 -0
- package/dist/cli-output-CNdMql-L.js +47 -0
- package/dist/cli-output-CNdMql-L.js.map +1 -0
- package/dist/cli.js +2020 -0
- package/dist/cli.js.map +1 -0
- package/dist/{collection-index-C7LopMyX.js → collection-index-BHgT_TKd.js} +32 -3
- package/dist/{collection-index-C7LopMyX.js.map → collection-index-BHgT_TKd.js.map} +1 -1
- package/dist/{collections-schema-version-BMeu3cgv.js → collections-schema-version-T6cGvrDi.js} +1 -2
- package/dist/{collections-schema-version-BMeu3cgv.js.map → collections-schema-version-T6cGvrDi.js.map} +1 -1
- package/dist/databasePoolManager-Bj5FbeAs.js +349 -0
- package/dist/databasePoolManager-Bj5FbeAs.js.map +1 -0
- package/dist/doctor-D7HWmGzs.js +974 -0
- package/dist/doctor-D7HWmGzs.js.map +1 -0
- package/dist/{ensure-collection-policies-CagOzEPS.js → ensure-collection-policies-2c2NV8zX.js} +5 -25
- package/dist/ensure-collection-policies-2c2NV8zX.js.map +1 -0
- package/dist/ensure-collection-tables-D4wJzM4y.js +820 -0
- package/dist/ensure-collection-tables-D4wJzM4y.js.map +1 -0
- package/dist/ensure-tables-CIojK-Rx.js +650 -0
- package/dist/ensure-tables-CIojK-Rx.js.map +1 -0
- package/dist/generate-drizzle-schema-CwEgVyjO.js +123 -0
- package/dist/generate-drizzle-schema-CwEgVyjO.js.map +1 -0
- package/dist/generate-drizzle-schema-logic-so2Z_lyC.js +528 -0
- package/dist/generate-drizzle-schema-logic-so2Z_lyC.js.map +1 -0
- package/dist/generate-postgres-ddl-logic-CtnpIBVv.js +1312 -0
- package/dist/generate-postgres-ddl-logic-CtnpIBVv.js.map +1 -0
- package/dist/generated-schema-staleness-DQdfJl2A.js +157 -0
- package/dist/generated-schema-staleness-DQdfJl2A.js.map +1 -0
- package/dist/index.es.js +849 -10807
- package/dist/index.es.js.map +1 -1
- package/dist/introspect-db-logic-C6LQdTxj.js +1378 -0
- package/dist/introspect-db-logic-C6LQdTxj.js.map +1 -0
- package/dist/policy-drift-kNJ6X2Uj.js +313 -0
- package/dist/policy-drift-kNJ6X2Uj.js.map +1 -0
- package/dist/rls-bootstrap-sql-DLDnUjtx.js +7092 -0
- package/dist/rls-bootstrap-sql-DLDnUjtx.js.map +1 -0
- package/dist/{rls-enforcement-ClJoTboT.js → rls-enforcement-DeYEjYLt.js} +14 -3
- package/dist/{rls-enforcement-ClJoTboT.js.map → rls-enforcement-DeYEjYLt.js.map} +1 -1
- package/dist/schema/bin/generate-drizzle-schema.d.ts +1 -0
- package/dist/schema/bin/generate-postgres-ddl.d.ts +1 -0
- package/dist/schema/doctor-cli.js +129 -0
- package/dist/schema/doctor-cli.js.map +1 -0
- package/dist/schema/generate-drizzle-schema.d.ts +1 -1
- package/dist/schema/generate-drizzle-schema.js +24 -0
- package/dist/schema/generate-drizzle-schema.js.map +1 -0
- package/dist/schema/generate-postgres-ddl.d.ts +1 -1
- package/dist/schema/generate-postgres-ddl.js +138 -0
- package/dist/schema/generate-postgres-ddl.js.map +1 -0
- package/dist/schema/introspect-db.js +866 -0
- package/dist/schema/introspect-db.js.map +1 -0
- package/dist/source-Br7L7GOI.js +410 -0
- package/dist/source-Br7L7GOI.js.map +1 -0
- package/dist/vector-index-DkWxm2de.js +309 -0
- package/dist/vector-index-DkWxm2de.js.map +1 -0
- package/package.json +7 -7
- package/dist/ensure-collection-policies-CagOzEPS.js.map +0 -1
- package/dist/ensure-collection-tables-DbAhrjnG.js +0 -2732
- package/dist/ensure-collection-tables-DbAhrjnG.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ensure-collection-tables-DbAhrjnG.js","names":[],"sources":["../src/schema/search-column.ts","../src/utils/pg-error-utils.ts","../src/schema/auth-users-columns.ts","../src/schema/vector-index.ts","../src/schema/generate-postgres-ddl-logic.ts","../src/schema/column-type-drift.ts","../src/schema/ensure-collection-tables.ts"],"sourcesContent":["/**\n * The one place a collection's `search` block becomes SQL.\n *\n * Four things describe a Postgres table in this codebase — the DDL generator,\n * the Drizzle schema generator, the runtime table builder for BaaS mode, and\n * the boot-time schema ensure — and each of them has, at some point, described\n * a column differently from the others. The `varchar(255)` note in\n * `generate-postgres-ddl-logic` is one such scar: the same property produced a\n * capped column down one path and an uncapped one down the other, and nothing\n * failed until a user hit the cap.\n *\n * So the search column is not implemented four times. It is computed once,\n * here, and every generator renders the same {@link SearchColumnSpec}. There is\n * a test asserting exactly that (`search-column-contract.test.ts`); the point of\n * this module is that the test has something to assert *about*.\n *\n * ## Why the expressions look the way they do\n *\n * A `GENERATED ALWAYS AS … STORED` expression must be strictly IMMUTABLE, and\n * Postgres is stricter here than intuition. Verified against PostgreSQL 18:\n *\n * | expression | immutable |\n * |-----------------------------------------|-----------|\n * | `to_tsvector('spanish', col)` | yes |\n * | `to_tsvector(col)` (1-arg) | **no** — depends on `default_text_search_config` |\n * | `array_to_string(col, ' ')` | **no** |\n * | `col::text` on `text[]` | **no** |\n * | `to_jsonb(col)` | **no** |\n * | `unaccent(col)` | **no** — dictionary lookup is STABLE |\n * | `jsonb_to_tsvector('spanish', j, '[\"string\"]')` | yes |\n * | `setweight(...) || setweight(...)` | yes |\n *\n * Three of the four things a real search column needs are therefore unavailable\n * directly, which is why {@link searchHelperFunctions} exists: each wraps a\n * stable built-in in an SQL function declared IMMUTABLE. That declaration is a\n * promise, and it is a true one for these three — array joining, JSON string\n * extraction and accent folding are all deterministic for a given input; the\n * built-ins are marked stable only because they must account for element types\n * and dictionaries in general.\n *\n * The alternative was to skip `unaccent` and text arrays entirely. That is not\n * a real option in an accented language: Postgres stems `auditoría` to\n * `auditor` and `auditoria` to `auditori` — *different lexemes* — so a query\n * typed without accents misses every row that carries them.\n */\nimport {\n CollectionConfig,\n Property,\n StringProperty,\n ArrayProperty,\n MapProperty,\n SearchConfig,\n SearchField,\n SearchWeight,\n isPostgresCollectionConfig,\n DEFAULT_SEARCH_COLUMN,\n DEFAULT_SEARCH_LANGUAGE,\n DEFAULT_SEARCH_WEIGHT,\n DEFAULT_FUZZY_THRESHOLD\n} from \"@rebasepro/types\";\nimport { createHash } from \"node:crypto\";\nimport { getTableName } from \"@rebasepro/common\";\nimport { toSnakeCase, toPostgresIdentifier } from \"@rebasepro/utils\";\n\n/** Schema-qualified so a collection outside `public` still resolves them. */\nconst HELPER_SCHEMA = \"public\";\n\n/**\n * Names of the helper functions. Frozen: they are recorded in the stored\n * generation expression of every search column ever created, so renaming one\n * orphans every table that already has a search column.\n */\nexport const SEARCH_TEXT_FN = `${HELPER_SCHEMA}.rebase_search_text`;\nexport const SEARCH_UNACCENT_FN = `${HELPER_SCHEMA}.rebase_search_unaccent`;\n\n/** How a declared path reaches text, which decides the SQL that extracts it. */\ntype FieldKind = \"text\" | \"text_array\" | \"jsonb\";\n\n/** One resolved field: where it lives, how to read it, what it is worth. */\nexport interface ResolvedSearchField {\n /** The path exactly as the author wrote it, for error messages. */\n path: string;\n /** The physical column the path starts at. */\n column: string;\n /** Dotted remainder addressed inside a JSONB column, if any. */\n jsonPath: string[];\n kind: FieldKind;\n weight: SearchWeight;\n /** The `setweight(to_tsvector(…), 'X')` term this field contributes. */\n sql: string;\n /** The plain-text term this field contributes, for the fuzzy column. */\n textSql: string;\n}\n\n/** Everything the generators need to render one collection's search column. */\nexport interface SearchColumnSpec {\n schema: string;\n table: string;\n /** The generated `tsvector` column. */\n column: string;\n language: string;\n unaccent: boolean;\n fields: ResolvedSearchField[];\n /** Body of `GENERATED ALWAYS AS ( … ) STORED` for the tsvector column. */\n expression: string;\n indexName: string;\n /** Extensions that must exist before the column can be created. */\n extensions: string[];\n fuzzy?: {\n column: string;\n expression: string;\n indexName: string;\n threshold: number;\n };\n}\n\n/** Raised when a `search` block names something that cannot be searched. */\nexport class SearchConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SearchConfigError\";\n }\n}\n\n/** The `search` block of a collection, or undefined when it has none. */\nexport const getSearchConfig = (collection: CollectionConfig): SearchConfig | undefined =>\n isPostgresCollectionConfig(collection) ? collection.search : undefined;\n\n/**\n * Refuse a `search` block on a collection this engine does not store.\n *\n * The type only permits one on a `PostgresCollectionConfig`, so TypeScript\n * already stops the ordinary case. This catches the rest — a JS config, a cast,\n * a collection whose `engine` was changed after the block was written — because\n * the alternative is the exact failure the block exists to prevent: a developer\n * who declared what to index, saw no error, and got the substring fallback.\n *\n * Called with *every* collection, before the Postgres ones are filtered out.\n */\nexport const assertSearchIsPostgresOnly = (collections: CollectionConfig[]): void => {\n for (const collection of collections) {\n if (isPostgresCollectionConfig(collection)) continue;\n if (!(collection as { search?: unknown }).search) continue;\n const engine = (collection as { engine?: string }).engine ?? \"non-postgres\";\n throw new SearchConfigError(\n `${collection.slug}.search: full-text search is a Postgres feature, and this collection is served by \\`${engine}\\`. ` +\n \"Remove the block — it would otherwise look configured while `.search()` kept using the default substring match.\"\n );\n }\n};\n\nconst columnNameOf = (propName: string, prop?: Property | null): string =>\n prop && \"columnName\" in prop && typeof prop.columnName === \"string\" ? prop.columnName : toSnakeCase(propName);\n\n/**\n * Classify a property for search purposes.\n *\n * Deliberately narrower than `getSqlColumnType`: search only cares whether a\n * value reaches text, and the mapping from property to *physical* type is\n * asserted against `getSqlColumnType` in the contract test rather than\n * duplicated here.\n *\n * Returns null for anything that is not text-bearing, which the caller turns\n * into a boot error naming the property.\n */\nconst classify = (prop: Property): { kind: FieldKind; reason?: string } | null => {\n switch (prop.type) {\n case \"string\": {\n const sp = prop as StringProperty;\n if (sp.enum) {\n return { kind: \"text\", reason: \"enum\" };\n }\n if (sp.isId === \"uuid\" || sp.columnType === \"uuid\") {\n return { kind: \"text\", reason: \"uuid\" };\n }\n return { kind: \"text\" };\n }\n case \"map\": {\n const mp = prop as MapProperty;\n // A `json` column is not `jsonb`, and the cast between them is not\n // immutable. Declaring `columnType: \"json\"` puts the value out of\n // reach of a generated column.\n if (mp.columnType === \"json\") return { kind: \"jsonb\", reason: \"json\" };\n return { kind: \"jsonb\" };\n }\n case \"array\": {\n const ap = prop as ArrayProperty;\n let colType = ap.columnType;\n if (!colType && ap.of && !Array.isArray(ap.of)) {\n const of = ap.of as Property;\n if (of.type === \"string\") colType = \"text[]\";\n else if (of.type === \"number\") colType = of.validation?.integer ? \"integer[]\" : \"numeric[]\";\n else if (of.type === \"boolean\") colType = \"boolean[]\";\n }\n if (colType === \"text[]\") return { kind: \"text_array\" };\n if (colType === \"json\") return { kind: \"jsonb\", reason: \"json\" };\n if (colType === \"integer[]\" || colType === \"boolean[]\" || colType === \"numeric[]\") {\n return { kind: \"text_array\", reason: \"non_text_array\" };\n }\n // Everything else lands in JSONB, which the JSON extractor handles.\n return { kind: \"jsonb\" };\n }\n default:\n return null;\n }\n};\n\nconst normalize = (inner: string, unaccent: boolean): string =>\n unaccent ? `${SEARCH_UNACCENT_FN}(${inner})` : inner;\n\n/** SQL reading one field as plain text, before normalization. */\nconst rawTextSql = (field: { column: string; jsonPath: string[]; kind: FieldKind }): string => {\n const col = `\"${field.column}\"`;\n if (field.kind === \"text\") return `coalesce(${col}, '')`;\n if (field.kind === \"text_array\") return `${SEARCH_TEXT_FN}(coalesce(${col}, '{}'::text[]))`;\n // JSONB, optionally addressed at a path inside the document.\n const target = field.jsonPath.length === 0\n ? col\n : field.jsonPath.length === 1\n ? `${col} -> ${quote(field.jsonPath[0])}`\n : `${col} #> ${quote(`{${field.jsonPath.join(\",\")}}`)}`;\n return `${SEARCH_TEXT_FN}(coalesce(${target}, '{}'::jsonb))`;\n};\n\nconst quote = (v: string): string => `'${v.replace(/'/g, \"''\")}'`;\n\n/**\n * Resolve and validate one declared field path.\n *\n * A path that does not resolve throws. The whole point of an explicit block is\n * that the author knows what is indexed; a silently dropped field would make it\n * a guess again, and the failure — a search that returns nothing for content\n * that is plainly in the row — is invisible from the outside.\n */\nconst resolveField = (\n entry: string | SearchField,\n collection: CollectionConfig,\n cfg: SearchConfig\n): ResolvedSearchField => {\n const path = typeof entry === \"string\" ? entry : entry.path;\n const weight = (typeof entry === \"string\" ? undefined : entry.weight) ?? DEFAULT_SEARCH_WEIGHT;\n const where = `${collection.slug}.search`;\n\n if (!path || typeof path !== \"string\") {\n throw new SearchConfigError(`${where}: every entry in \\`fields\\` needs a property path.`);\n }\n\n const [head, ...rest] = path.split(\".\");\n const prop = collection.properties?.[head] as Property | undefined;\n if (!prop) {\n const known = Object.keys(collection.properties ?? {}).join(\", \");\n throw new SearchConfigError(\n `${where}: \"${path}\" starts at property \"${head}\", which this collection does not declare. Known properties: ${known}.`\n );\n }\n\n const classified = classify(prop);\n if (!classified) {\n throw new SearchConfigError(\n `${where}: \"${path}\" is a \\`${prop.type}\\` property, which holds no text to search. ` +\n `Searchable kinds are \\`string\\`, \\`string[]\\` and \\`map\\` (or a path inside one).`\n );\n }\n if (classified.reason === \"enum\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" is an enum. Enums are a fixed vocabulary — filter on them with \\`where\\` instead, which is exact and uses an index.`\n );\n }\n if (classified.reason === \"uuid\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" is a UUID column. Look it up by id rather than searching it.`\n );\n }\n if (classified.reason === \"json\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" is a \\`json\\` column, and the cast from \\`json\\` to \\`jsonb\\` is not immutable, so it cannot feed a generated column. Declare the property as \\`jsonb\\` (the default) to search it.`\n );\n }\n if (classified.reason === \"non_text_array\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" is an array of numbers or booleans. Only \\`string[]\\` carries text to search.`\n );\n }\n\n if (rest.length > 0 && classified.kind !== \"jsonb\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" addresses a path inside \"${head}\", but \"${head}\" is a \\`${prop.type}\\` property, not a \\`map\\`. Only map properties have paths inside them.`\n );\n }\n\n const column = columnNameOf(head, prop);\n const field = { column, jsonPath: rest, kind: classified.kind };\n const textSql = normalize(rawTextSql(field), cfg.unaccent === true);\n const language = cfg.language ?? DEFAULT_SEARCH_LANGUAGE;\n\n return {\n path,\n column,\n jsonPath: rest,\n kind: classified.kind,\n weight,\n sql: `setweight(to_tsvector(${quote(language)}, ${textSql}), ${quote(weight)})`,\n textSql\n };\n};\n\n/**\n * Build the full spec for a collection, or undefined when it has not opted in.\n *\n * Throws {@link SearchConfigError} on a config that cannot be honoured. Callers\n * at boot surface that as a startup failure — a search block that half-works is\n * worse than one that refuses.\n */\nexport const buildSearchColumnSpec = (collection: CollectionConfig): SearchColumnSpec | undefined => {\n const cfg = getSearchConfig(collection);\n if (!cfg) return undefined;\n\n if (!Array.isArray(cfg.fields) || cfg.fields.length === 0) {\n throw new SearchConfigError(\n `${collection.slug}.search: \\`fields\\` is empty. Name the properties to index, or remove the \\`search\\` block to keep the default ILIKE behaviour.`\n );\n }\n\n const table = getTableName(collection);\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n const column = cfg.column ?? DEFAULT_SEARCH_COLUMN;\n\n if (collection.properties?.[column]) {\n throw new SearchConfigError(\n `${collection.slug}.search: the generated column \"${column}\" collides with a declared property of the same name. Set \\`search.column\\` to something else.`\n );\n }\n\n const fields = cfg.fields.map(entry => resolveField(entry, collection, cfg));\n\n const seen = new Set<string>();\n for (const f of fields) {\n if (seen.has(f.path)) {\n throw new SearchConfigError(`${collection.slug}.search: \"${f.path}\" is listed twice.`);\n }\n seen.add(f.path);\n }\n\n const extensions: string[] = [];\n if (cfg.unaccent) extensions.push(\"unaccent\");\n if (cfg.fuzzy) extensions.push(\"pg_trgm\");\n\n const spec: SearchColumnSpec = {\n schema,\n table,\n column,\n language: cfg.language ?? DEFAULT_SEARCH_LANGUAGE,\n unaccent: cfg.unaccent === true,\n fields,\n expression: fields.map(f => f.sql).join(\" || \"),\n indexName: toPostgresIdentifier(`${table}_${column}_gin`),\n extensions\n };\n\n if (cfg.fuzzy) {\n const fuzzyColumn = `${column}_text`;\n if (collection.properties?.[fuzzyColumn]) {\n throw new SearchConfigError(\n `${collection.slug}.search: \\`fuzzy\\` needs the column \"${fuzzyColumn}\", which collides with a declared property. Set \\`search.column\\` to something else.`\n );\n }\n spec.fuzzy = {\n column: fuzzyColumn,\n // Concatenated with spaces so a trigram never spans two fields.\n expression: fields.map(f => f.textSql).join(\" || ' ' || \"),\n indexName: toPostgresIdentifier(`${table}_${fuzzyColumn}_trgm`),\n threshold: cfg.fuzzyThreshold ?? DEFAULT_FUZZY_THRESHOLD\n };\n }\n\n return spec;\n};\n\n/**\n * The IMMUTABLE wrappers the generated expressions call.\n *\n * `CREATE OR REPLACE` so a boot against an existing database is a no-op rather\n * than an error, and idempotent for the same reason every other boot-time DDL\n * statement here is.\n *\n * The bodies are stable built-ins wrapped in an immutable promise — see the\n * module comment for why that promise is sound. `STRICT` matters: it makes NULL\n * in mean NULL out without executing the body, which is what the `coalesce` at\n * each call site then absorbs.\n */\nexport const searchHelperFunctions = (spec: SearchColumnSpec): string[] => {\n const statements: string[] = [\n // text[] → \" \"-joined text.\n `CREATE OR REPLACE FUNCTION ${SEARCH_TEXT_FN}(text[]) RETURNS text\\n` +\n ` LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\\n` +\n ` $$ SELECT array_to_string($1, ' ') $$;`,\n // jsonb → every string value at or below the node, space-joined. Keys\n // are not values: indexing them would make `certifications` itself a\n // search term on every row that has the field at all.\n `CREATE OR REPLACE FUNCTION ${SEARCH_TEXT_FN}(jsonb) RETURNS text\\n` +\n ` LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\\n` +\n ` $$ SELECT coalesce(string_agg(v, ' '), '')\\n` +\n ` FROM jsonb_array_elements_text(jsonb_path_query_array($1, 'strict $.**?(@.type() == \"string\")')) AS v $$;`\n ];\n if (spec.unaccent) {\n // The two-argument form with an explicit dictionary is the one that can\n // honestly be called immutable: the single-argument form resolves the\n // dictionary through the current search_path at call time.\n statements.push(\n `CREATE OR REPLACE FUNCTION ${SEARCH_UNACCENT_FN}(text) RETURNS text\\n` +\n ` LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\\n` +\n ` $$ SELECT ${HELPER_SCHEMA}.unaccent('${HELPER_SCHEMA}.unaccent'::regdictionary, $1) $$;`\n );\n }\n return statements;\n};\n\n/**\n * `CREATE EXTENSION` statements the spec's expressions depend on.\n *\n * `WITH SCHEMA public` is load-bearing, not tidiness. An unqualified\n * `CREATE EXTENSION` installs into the first schema on `search_path`, which\n * defaults to `\"$user\", public` — and the scaffold's database role is named\n * `rebase`, the same as the schema the generator creates one statement earlier.\n * So the moment that schema exists, `CREATE EXTENSION unaccent` puts the\n * dictionary in `rebase`, and every reference to `public.unaccent` below fails\n * with \"text search dictionary does not exist\". Observed, not theorised.\n */\nexport const searchExtensionStatements = (spec: SearchColumnSpec): string[] =>\n spec.extensions.map(e => `CREATE EXTENSION IF NOT EXISTS ${e} WITH SCHEMA ${HELPER_SCHEMA};`);\n\n/** The column definition as it appears inside `CREATE TABLE`. */\nexport const searchColumnDefinition = (spec: SearchColumnSpec): string =>\n `\"${spec.column}\" tsvector GENERATED ALWAYS AS (${spec.expression}) STORED`;\n\n/** The fuzzy column definition, when the spec asks for one. */\nexport const fuzzyColumnDefinition = (spec: SearchColumnSpec): string | undefined =>\n spec.fuzzy ? `\"${spec.fuzzy.column}\" text GENERATED ALWAYS AS (${spec.fuzzy.expression}) STORED` : undefined;\n\n/**\n * Index statements for the spec.\n *\n * `CONCURRENTLY` is deliberately *not* used here. This form is emitted into a\n * SQL file replayed as one unit — a migration, or `search.sql` — where a\n * concurrent build is not allowed. The boot-time ensure path runs statement by\n * statement against tables that are live and populated, and uses the\n * concurrent form instead; see `ensureSearchColumns`.\n */\nexport const searchIndexStatements = (spec: SearchColumnSpec): string[] => {\n const statements = [\n `CREATE INDEX IF NOT EXISTS \"${spec.indexName}\" ON \"${spec.schema}\".\"${spec.table}\" USING GIN (\"${spec.column}\");`\n ];\n if (spec.fuzzy) {\n statements.push(\n // The operator class is resolved through `search_path` like any\n // other object, so it is qualified for the same reason the\n // extension is installed explicitly.\n `CREATE INDEX IF NOT EXISTS \"${spec.fuzzy.indexName}\" ON \"${spec.schema}\".\"${spec.table}\" USING GIN (\"${spec.fuzzy.column}\" ${HELPER_SCHEMA}.gin_trgm_ops);`\n );\n }\n return statements;\n};\n\n// ── Telling a changed `search` block from an unchanged one ──────────────────\n\n/**\n * Marker on the comment of every generated search column this module creates.\n *\n * Versioned because the fingerprint below is only comparable against itself: a\n * future change to how it is computed has to read as \"not stamped by this\n * version\" rather than as drift on every existing column.\n */\nexport const SEARCH_STAMP_PREFIX = \"rebase:search:v1:\";\n\n/**\n * A stable fingerprint of one generated column's expression.\n *\n * Why a stamp rather than reading the expression back: Postgres stores a\n * generated column's expression *parsed*, and hands it back deparsed — casts\n * made explicit, identifiers requoted, schema qualifications added or dropped\n * according to `search_path`. Comparing that text to the text we generated\n * would report drift on wording, and this comparison decides whether a boot\n * refuses, so a false positive is an outage. The stamp is written by the same\n * code that writes the column, so equality means what it says.\n */\nexport const searchExpressionFingerprint = (expression: string): string =>\n `${SEARCH_STAMP_PREFIX}${createHash(\"sha256\").update(expression).digest(\"hex\").slice(0, 16)}`;\n\n/** One generated column, with the fingerprint that identifies its expression. */\nexport interface SearchColumnStamp {\n column: string;\n /** The expression the column is generated from. */\n expression: string;\n fingerprint: string;\n /** `COMMENT ON COLUMN …`, which is where the fingerprint is recorded. */\n sql: string;\n}\n\n/**\n * The stamps for a spec's generated columns — one per column, never shared.\n *\n * Per column on purpose: turning `fuzzy` on adds a second column and changes\n * nothing about the first, and a spec-wide fingerprint would report the\n * untouched `tsvector` column as drifted and refuse a boot over a change that\n * is purely additive.\n */\nexport const searchColumnStamps = (spec: SearchColumnSpec): SearchColumnStamp[] => {\n const stamp = (column: string, expression: string): SearchColumnStamp => {\n const fingerprint = searchExpressionFingerprint(expression);\n return {\n column,\n expression,\n fingerprint,\n sql: `COMMENT ON COLUMN \"${spec.schema}\".\"${spec.table}\".\"${column}\" IS ${quote(fingerprint)};`\n };\n };\n const stamps = [stamp(spec.column, spec.expression)];\n if (spec.fuzzy) stamps.push(stamp(spec.fuzzy.column, spec.fuzzy.expression));\n return stamps;\n};\n\n/**\n * The same drift check as the boot ensure, for the SQL file.\n *\n * Needed because {@link searchColumnStamps} would otherwise *launder* drift on\n * the migration path: `ADD COLUMN IF NOT EXISTS` does nothing to a column that\n * exists, so a re-generated `search.sql` would stamp a stale column with the\n * new block's fingerprint and the next boot would find them in agreement.\n * Guarding first means the file refuses instead — `rebase db push` is attended,\n * and the operator reading the failure is the person who changed the block.\n */\nexport const searchStampGuards = (spec: SearchColumnSpec): string[] =>\n searchColumnStamps(spec).map(stamp => {\n const relation = quote(`\"${spec.schema}\".\"${spec.table}\"`);\n return `DO $rebase_search$\nDECLARE recorded text;\nBEGIN\n SELECT col_description(a.attrelid, a.attnum) INTO recorded\n FROM pg_attribute a\n WHERE a.attrelid = ${relation}::regclass AND a.attname = ${quote(stamp.column)} AND NOT a.attisdropped;\n IF recorded LIKE ${quote(`${SEARCH_STAMP_PREFIX}%`)} AND recorded <> ${quote(stamp.fingerprint)} THEN\n RAISE EXCEPTION 'Rebase: the search block for ${spec.schema}.${spec.table} changed after the generated column \"${stamp.column}\" was built (recorded %, expected ${stamp.fingerprint}). Postgres cannot alter a generated expression in place. Drop the column and re-apply this file — it rewrites the table and rebuilds the index: ALTER TABLE ${relation.slice(1, -1)} DROP COLUMN \"${stamp.column}\";', recorded;\n END IF;\nEND\n$rebase_search$;`;\n });\n\n/**\n * The index names the spec creates.\n *\n * Needed by name, not just by statement, so Atlas can be told to exclude them\n * from its diff — see `searchExcludePatterns`.\n */\nexport const searchIndexNames = (spec: SearchColumnSpec): string[] =>\n spec.fuzzy ? [spec.indexName, spec.fuzzy.indexName] : [spec.indexName];\n\n// ── Keeping the generated columns out of responses ──────────────────────────\n\n/**\n * The generated column names a collection's search block adds, if any.\n *\n * These are physical columns on the table, so `SELECT *` returns them. They are\n * an index in column form — a list of lexeme positions, or a concatenation of\n * every searchable field on the row — and nothing outside the query planner has\n * any use for them. Left in, every list response carries a second, larger copy\n * of the row's text.\n */\nexport const searchColumnNames = (collection: CollectionConfig): string[] => {\n let spec: SearchColumnSpec | undefined;\n try {\n spec = buildSearchColumnSpec(collection);\n } catch {\n // A malformed block is reported at boot, loudly. A read is the wrong\n // place to raise it a second time, and returning the row without the\n // exclusion would be worse than returning it with.\n return [];\n }\n if (!spec) return [];\n return spec.fuzzy ? [spec.column, spec.fuzzy.column] : [spec.column];\n};\n\n/**\n * True for a column whose type only ever holds a search index.\n *\n * Independent of any collection config on purpose: an introspected database\n * (BaaS mode) can carry a `tsvector` column this framework never created —\n * Pagila's `film.fulltext` is the canonical one — and it should not be returned\n * to callers either. `isDerivedIndexColumn` already keeps such a column out of\n * the *properties*; this keeps it out of the *rows*.\n */\nexport const isSearchIndexColumn = (column: { getSQLType?: () => string }): boolean => {\n const sqlType = typeof column?.getSQLType === \"function\" ? column.getSQLType().toLowerCase() : \"\";\n return sqlType === \"tsvector\" || sqlType === \"tsquery\";\n};\n\n/**\n * A drizzle select projection over `table` with the search columns dropped.\n *\n * Returns undefined when nothing needs dropping, so the common case keeps using\n * a plain `select()` and this stays invisible in the generated SQL.\n */\nexport const visibleColumnProjection = (\n tableColumns: Record<string, { getSQLType?: () => string }> | undefined,\n collection?: CollectionConfig\n): Record<string, unknown> | undefined => {\n const excluded = excludedColumnNames(tableColumns, collection);\n if (!tableColumns || excluded.length === 0) return undefined;\n const projection: Record<string, unknown> = {};\n for (const [name, column] of Object.entries(tableColumns)) {\n if (!excluded.includes(name)) projection[name] = column;\n }\n return projection;\n};\n\n/** The same exclusion as a drizzle `db.query` `columns` denylist. */\nexport const hiddenColumnsOption = (\n tableColumns: Record<string, { getSQLType?: () => string }> | undefined,\n collection?: CollectionConfig\n): Record<string, false> | undefined => {\n const excluded = excludedColumnNames(tableColumns, collection);\n if (excluded.length === 0) return undefined;\n return Object.fromEntries(excluded.map(name => [name, false as const]));\n};\n\n/**\n * The columns to keep out of a response, by name.\n *\n * `tableColumns` is whatever `getTableColumns` returned, which is `undefined`\n * for anything that is not a real drizzle table — a stub in a test, a derived\n * or nested path with no table behind it. Nothing to exclude is the right\n * answer there, and it has to be an answer rather than a throw: this runs on\n * the read path of every collection, opted in or not.\n */\nconst excludedColumnNames = (\n tableColumns: Record<string, { getSQLType?: () => string }> | undefined,\n collection?: CollectionConfig\n): string[] => {\n if (!tableColumns || typeof tableColumns !== \"object\") return [];\n const byName = new Set(collection ? searchColumnNames(collection) : []);\n return Object.keys(tableColumns).filter(\n name => byName.has(name) || isSearchIndexColumn(tableColumns[name])\n );\n};\n","/**\n * Shared PostgreSQL error extraction and user-friendly message formatting.\n *\n * Drizzle wraps native PG errors in a `.cause` chain. These utilities\n * unwrap that chain to get the real PostgreSQL error (identified by a\n * 5-character alphanumeric `code` such as `42P01`) and translate it into\n * a message that is safe and helpful to show to end-users.\n */\n\nimport { logger } from \"@rebasepro/server\";\n\n/**\n * Shape of a deliberate client-facing error — `ApiError` from\n * `@rebasepro/server`, or anything else carrying a 4xx `statusCode`.\n *\n * Matched structurally rather than with `instanceof`: `@rebasepro/server` can\n * be loaded twice (published dist vs. workspace source), which breaks class\n * identity — `PersistService` hedges against the same thing by also accepting\n * `name === \"ApiError\"`.\n */\ninterface ClientFacingError extends Error {\n statusCode?: number;\n code?: string;\n /** See `ApiError.expected` — routine outcomes log at debug, not warn. */\n expected?: boolean;\n}\n\n/**\n * Return the error when it is a deliberate 4xx, otherwise null.\n *\n * A thrown `ApiError` is a decision the server made about the request, not a\n * database failure: its message and code are already written for the client.\n */\nfunction asClientFacingError(error: unknown): ClientFacingError | null {\n if (!(error instanceof Error)) return null;\n const e = error as ClientFacingError;\n if (typeof e.statusCode !== \"number\" || e.statusCode < 400 || e.statusCode >= 500) return null;\n return e;\n}\n\n/** Shape of PostgreSQL errors with diagnostic metadata. */\nexport interface PostgresError extends Error {\n code?: string;\n detail?: string;\n hint?: string;\n constraint?: string;\n column?: string;\n table?: string;\n dataType?: string;\n cause?: unknown;\n}\n\n/**\n * Extract the underlying PostgreSQL error from a Drizzle wrapper.\n * Drizzle wraps PG errors in a `cause` property — this function\n * recursively walks the chain until it finds an object with a PG\n * error code (5-char alphanumeric, e.g. `42P01`).\n */\nexport function extractPgError(error: unknown): PostgresError | null {\n if (!error || typeof error !== \"object\") return null;\n if (!(error instanceof Error)) {\n // Check non-Error objects for a cause chain (Drizzle sometimes wraps oddly)\n if (\"cause\" in error && (error as Record<string, unknown>).cause && typeof (error as Record<string, unknown>).cause === \"object\") {\n return extractPgError((error as Record<string, unknown>).cause);\n }\n return null;\n }\n\n // Check if the error itself has a PG error code\n if (\"code\" in error && typeof (error as PostgresError).code === \"string\" && /^[0-9A-Z]{5}$/.test((error as PostgresError).code!)) {\n return error as PostgresError;\n }\n\n // Check the cause chain (Drizzle wraps PG errors)\n if (error.cause && typeof error.cause === \"object\") {\n return extractPgError(error.cause);\n }\n\n return null;\n}\n\n/**\n * Whether the failure came back from Postgres rather than from building the\n * query — which decides whether a fallback query is worth issuing.\n *\n * Reads here run inside a transaction (that is where `SET LOCAL ROLE` binds\n * RLS). Once a statement raises, that transaction is aborted, and every later\n * statement on it returns `25P02` — \"current transaction is aborted, commands\n * ignored until end of transaction block\". So a retry after a database error\n * cannot succeed, and it replaces a precise diagnosis (\"invalid input syntax\n * for type uuid\") with a generic one. Rethrow instead.\n *\n * A query the driver could not even build — a missing reciprocal relation, say\n * — never reached Postgres, leaves the transaction usable, and is exactly what\n * the fallback paths exist for.\n */\nexport function reachedDatabase(error: unknown): boolean {\n return extractPgError(error) !== null;\n}\n\n/**\n * Walk the error cause chain and return the deepest meaningful message.\n */\nexport function extractCauseMessage(error: unknown): string | null {\n if (!error || typeof error !== \"object\") return null;\n if (!(error instanceof Error)) return null;\n\n if (error.cause && typeof error.cause === \"object\") {\n const deeper = extractCauseMessage(error.cause);\n if (deeper) return deeper;\n // The cause itself has a message\n if (error.cause instanceof Error && error.cause.message) {\n return error.cause.message;\n }\n }\n return null;\n}\n\n/**\n * Codes that mean \"this connection will never work as configured\".\n *\n * A wrong password or a database that does not exist is a settled fact about\n * the connection string, not a transient fault — retrying produces the same\n * answer forever.\n */\nconst UNRECOVERABLE_CONNECT_CODES = new Set([\n \"28P01\", // invalid_password\n \"28000\", // invalid_authorization_specification\n \"3D000\", // invalid_catalog_name — the database does not exist\n \"42501\" // insufficient_privilege\n]);\n\nexport interface ConnectFailure {\n /** True when retrying cannot help: the connection string itself is wrong. */\n fatal: boolean;\n /** The deepest message available — the Postgres one where there is one. */\n reason: string;\n /** The `SQLSTATE`, when the failure came from Postgres rather than the socket. */\n code?: string;\n}\n\n/**\n * Describe a failed connection attempt in terms a developer can act on.\n *\n * The error a caller catches is Drizzle's wrapper: its message is\n * `Failed query: SELECT 1` and its stack runs through drizzle internals, while\n * the sentence that says what is actually wrong — \"password authentication\n * failed for user …\", \"database … does not exist\" — sits in `.cause`. Logging\n * the wrapper, as the bootstrapper used to, tells a developer with a typo in\n * their `DATABASE_URL` nothing at all.\n */\nexport function classifyConnectFailure(error: unknown): ConnectFailure {\n const pgError = extractPgError(error);\n const reason =\n pgError?.message ??\n extractCauseMessage(error) ??\n (error instanceof Error ? error.message : String(error));\n return {\n fatal: Boolean(pgError?.code && UNRECOVERABLE_CONNECT_CODES.has(pgError.code)),\n reason,\n code: pgError?.code\n };\n}\n\n/**\n * Detect whether an error is specifically a role-switching permission failure\n * (e.g. \"permission denied to set role\" or \"must be member of role\"),\n * as opposed to a table-level permission denial.\n *\n * This is used by the backend driver to auto-disable role switching when the\n * connection user lacks SET ROLE privileges, rather than surfacing a confusing\n * error to the Studio SQL Editor user.\n */\nexport function isRoleSwitchingPermissionError(error: unknown): boolean {\n const pgError = extractPgError(error);\n if (!pgError || pgError.code !== \"42501\") return false;\n const msg = pgError.message.toLowerCase();\n return msg.includes(\"set role\") || msg.includes(\"member of role\");\n}\n\n/**\n * Was this `42501` the *caller* being refused by a policy, rather than the\n * server lacking a privilege?\n *\n * Both arrive as `insufficient_privilege`, and they are opposite kinds of\n * problem. A row-level-security refusal is a working access-control system\n * doing its job: the caller asked for something their policies do not permit,\n * which is a 403 and nobody's bug. A missing `GRANT` is the deployment being\n * wrong — the connection role cannot touch the table at all, no policy is\n * involved, and nothing the caller changes about the request will help.\n *\n * Postgres distinguishes them in the message, so this does too:\n *\n * new row violates row-level security policy for table \"notes\" → the caller\n * permission denied for table notes → the server\n *\n * Only writes reach this. A read that RLS excludes is not an error — the rows\n * are filtered and the caller gets an empty page — so the erroring case is\n * specifically an `INSERT`/`UPDATE` whose row fails a policy's `WITH CHECK`.\n *\n * Matched on the message because that is the only thing carrying the\n * distinction; the SQLSTATE is identical either way. Narrow by design: anything\n * not naming row-level security stays the server's problem, since reporting a\n * genuine privilege misconfiguration as \"forbidden\" would send an operator\n * hunting for a policy bug that does not exist.\n */\nexport function isRowLevelSecurityDenial(error: unknown): boolean {\n const pgError = extractPgError(error);\n if (!pgError || pgError.code !== \"42501\") return false;\n return pgError.message.toLowerCase().includes(\"row-level security policy\");\n}\n\n/**\n * Translate a raw PostgreSQL error into a user-friendly message.\n *\n * @param pgError - The extracted PostgreSQL error (from {@link extractPgError})\n * @param context - A human-readable context string (e.g. collection slug or path)\n * @returns An object with a `message` safe for the client and the PG `code`.\n */\nexport function pgErrorToFriendlyMessage(\n pgError: PostgresError,\n context: string,\n options: { verbose?: boolean } = {}\n): { message: string; code: string } {\n // Postgres's own `DETAIL` and `HINT`, and the raw driver message, are what\n // make these errors useful while you are building — and what makes them an\n // oracle once the server is answering strangers.\n //\n // The sharp one is `23505`: its detail reads `Key (email)=(a@b.c) already\n // exists.`, which answers \"is this person registered?\" for any address, on\n // a table whose rows RLS is otherwise hiding completely. The rest leak\n // physical column and constraint names, which are the map for the next\n // question. So in production the shape of the failure is served — what\n // rule was broken, and where — and the values are not.\n //\n // The full text is not lost: the caller logs the original error. This\n // decides what crosses the wire, not what is recorded.\n const verbose = options.verbose ?? process.env.NODE_ENV !== \"production\";\n\n const detail = verbose ? (pgError.detail as string | undefined) : undefined;\n const hint = verbose ? (pgError.hint as string | undefined) : undefined;\n const constraint = pgError.constraint as string | undefined;\n const column = pgError.column as string | undefined;\n const table = pgError.table as string | undefined;\n const dataType = verbose ? (pgError.dataType as string | undefined) : undefined;\n const rawMessage = pgError.message || \"Unknown database error\";\n const pgMessage = verbose ? rawMessage : \"\";\n const code = pgError.code || \"UNKNOWN\";\n\n const suffix = hint ? ` Hint: ${hint}` : \"\";\n const tableRef = table ?? context;\n\n /** `\": <postgres said>\"`, or nothing when the details are withheld. */\n const said = pgMessage ? `: ${pgMessage}` : \"\";\n\n switch (pgError.code) {\n case \"23503\": // foreign_key_violation\n return {\n message: detail\n ? `Foreign key constraint violated: ${detail}${suffix}`\n : `Cannot complete operation: a foreign key constraint${constraint ? ` (${constraint})` : \"\"} was violated in \"${context}\".${suffix}`,\n code\n };\n case \"23505\": // unique_violation\n return {\n message: detail\n ? `Duplicate value: ${detail}${suffix}`\n : `Cannot complete operation: a unique constraint${constraint ? ` (${constraint})` : \"\"} was violated in \"${context}\".${suffix}`,\n code\n };\n case \"23502\": // not_null_violation\n return {\n message: `Missing required field: \"${column ?? \"unknown\"}\" in \"${tableRef}\" cannot be empty.${suffix}`,\n code\n };\n case \"23514\": // check_violation\n return {\n message: `Validation failed: a check constraint${constraint ? ` (${constraint})` : \"\"} was violated in \"${context}\".${suffix}`,\n code\n };\n case \"22P02\": // invalid_text_representation (e.g. invalid UUID, wrong enum value)\n return {\n message: `Invalid data format in \"${context}\"${said}.${suffix}`,\n code\n };\n case \"22001\": // string_data_right_truncation (value too long)\n return {\n message: `Value too long for column \"${column ?? \"unknown\"}\" in \"${tableRef}\"${said}.${suffix}`,\n code\n };\n case \"22003\": // numeric_value_out_of_range\n return {\n message: `Numeric value out of range for column \"${column ?? \"unknown\"}\" in \"${tableRef}\"${said}.${suffix}`,\n code\n };\n case \"42703\": // undefined_column\n return {\n message: `Unknown column in \"${tableRef}\"${said}. Check if your schema is up to date (run migrations).${suffix}`,\n code\n };\n case \"42P01\": // undefined_table\n return {\n message: `Table not found for \"${context}\"${said}. Check if your schema is up to date (run migrations).${suffix}`,\n code\n };\n case \"42501\": // insufficient_privilege\n // Two unrelated failures share this SQLSTATE, and the old message\n // named both causes because it could not tell them apart — which\n // meant it was half wrong whichever one had happened, and sent the\n // reader to check the other. Postgres says which in its own message.\n return rawMessage.toLowerCase().includes(\"row-level security policy\")\n ? {\n // The caller. Their policies do not permit this row; the\n // deployment is working exactly as configured.\n message: `Not permitted to write this row in \"${tableRef}\": it does not satisfy the row-level security policy.${suffix}`,\n code\n }\n : {\n // The deployment. No policy is involved — the connecting\n // role cannot touch the table at all.\n message: `Permission denied on \"${tableRef}\": the database role this server connects as lacks privileges on it.${suffix}`,\n code\n };\n case \"28000\": // invalid_authorization_specification\n return {\n message: `Authorization failed for \"${context}\". Check your database credentials.${suffix}`,\n code\n };\n default: {\n // Unhandled PG code — still surface the actual database message\n const parts = [`Database error in \"${context}\" [${code}]${said}`];\n if (detail) parts.push(`Detail: ${detail}`);\n if (column) parts.push(`Column: ${column}`);\n if (dataType) parts.push(`Data type: ${dataType}`);\n if (constraint) parts.push(`Constraint: ${constraint}`);\n if (hint) parts.push(`Hint: ${hint}`);\n return { message: parts.join(\". \"), code };\n }\n }\n}\n\n/**\n * Sanitize any error into a message safe and helpful for the client.\n *\n * A deliberate 4xx (`ApiError`) passes through untouched — the server already\n * decided what the client should read. Otherwise the PG error is extracted\n * from the Drizzle cause chain, falling back to a generic message that\n * doesn't leak SQL.\n *\n * @param error - The raw caught error\n * @param context - A human-readable context string (e.g. collection path)\n * @returns An object with `message` (user-friendly) and optional `code`\n * (the `ApiError` code, or the PG SQLSTATE).\n */\nexport function sanitizeErrorForClient(error: unknown, context: string): { message: string; code?: string } {\n // ── A deliberate 4xx is not a database failure ──────────────────\n // Its message and code are written for the client; replacing them with\n // \"Check server logs\" would discard the only diagnosis the caller gets\n // (e.g. the offending filter field and the collection's valid ones).\n // Log level follows the same convention as the HTTP error handler in\n // @rebasepro/server: routine outcomes at debug, everything else at warn.\n const clientError = asClientFacingError(error);\n if (clientError) {\n const line = `[API ${clientError.statusCode} ${clientError.code ?? \"BAD_REQUEST\"}] in \"${context}\": ${clientError.message}`;\n if (clientError.expected) {\n logger.debug(line);\n } else {\n logger.warn(`⚠️ ${line}`);\n }\n return { message: clientError.message, ...(clientError.code && { code: clientError.code }) };\n }\n\n // ── Always log the full, unsanitized error server-side ──────────\n const pgError = extractPgError(error);\n\n if (pgError) {\n logger.error(`[PG ${pgError.code}] Error in \"${context}\"`, {\n code: pgError.code,\n message: pgError.message,\n detail: pgError.detail,\n hint: pgError.hint,\n column: pgError.column,\n table: pgError.table,\n constraint: pgError.constraint,\n dataType: pgError.dataType\n // The outer Drizzle wrapper message used to be logged here \"for\n // full context\": it is `Failed query: <sql>\\nparams: <values>`, so\n // it published the statement and every bound value (an email, a\n // password hash) on every realtime data failure. The SQLSTATE,\n // detail, table, column and constraint above are the diagnostic\n // value; the wrapper added only the leak. `logger` strips the\n // wrapper as well, but the field itself carried nothing else.\n });\n return pgErrorToFriendlyMessage(pgError, context);\n }\n\n // No PG error found — log the raw error as-is\n logger.error(`Database error in \"${context}\" (no PG error extracted)`, {\n error: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n cause: error instanceof Error && error.cause\n ? (error.cause instanceof Error ? error.cause.message : String(error.cause))\n : undefined\n });\n\n // Try to get the deepest cause message\n const causeMessage = extractCauseMessage(error);\n if (causeMessage) {\n return { message: `Database error in \"${context}\": ${causeMessage}` };\n }\n\n // Last resort — generic message, never leak raw SQL\n return { message: `Could not load data for \"${context}\". Check server logs for details.` };\n}\n","/**\n * The one description of what an auth user table's columns must be.\n *\n * ## Why this exists\n *\n * Three different code paths create `rebase.users`, and before this module they\n * disagreed about it:\n *\n * | column | `db push` (generator) | `ensureAuthTablesExist` | `ensureCollectionTables` |\n * |------------------|-----------------------|-------------------------|--------------------------|\n * | `email` | `TEXT UNIQUE NOT NULL`| `TEXT NOT NULL` + CHECK | `TEXT` (nullable) |\n * | `roles` | `TEXT[]` | `NOT NULL DEFAULT '{}'` | nullable, no default |\n * | `email_verified` | `BOOLEAN` | `NOT NULL DEFAULT FALSE`| nullable |\n * | `created_at` | `DEFAULT now()` | `NOT NULL DEFAULT NOW()`| no default |\n *\n * They are all `CREATE TABLE IF NOT EXISTS` / `ADD COLUMN IF NOT EXISTS`, so\n * whichever ran first decided the table and the other two silently no-op'd.\n * Boot order therefore chose the constraints: a managed deploy (collection\n * tables first) got a users table whose `email` was nullable and whose\n * `email_verified` had no default, while the same project pushed from a\n * checkout got the strict one. In the same table, `is_anonymous` came out\n * `NOT NULL DEFAULT false` — because *that* column existed in only one of the\n * three lists, so its owner's definition won by default.\n *\n * A second consequence was drift in the other direction. The scaffold's\n * `users.ts` describes 12 columns; auth needs 14. `db push` is declarative and\n * builds its desired state from the collection alone, so the two columns only\n * auth knows about (`is_anonymous`, `tokens_valid_after`) read as unmanaged\n * drift, and a push run after the server had booted once planned to DROP them.\n *\n * Both problems are the same problem: no single place said what this table is.\n * This is that place. Every creator asks here first and only then falls back to\n * the collection's own property definitions, so a column auth owns has one\n * definition regardless of who gets there first, and a column the developer\n * added to their users collection still behaves like any other field.\n *\n * ## What belongs here\n *\n * Only columns the auth services read or write. A developer's own additions to\n * their users collection (`bio`, `stripe_customer_id`) are ordinary columns and\n * must NOT be listed — they are generated from the collection like every other\n * field, and listing them here would freeze a user's schema.\n *\n * `id` is deliberately absent: its type comes from the collection's id property\n * (uuid / increment / text) and each creator already derives it.\n *\n * Keep in step with {@link AUTH_SCHEMA_VERSION} when a change here makes an\n * older runtime unable to work against a migrated table.\n */\n\n/**\n * A column auth owns.\n *\n * Structured rather than one SQL string because the same facts are needed in\n * three grammars — a `CREATE TABLE` column list, an `ADD COLUMN IF NOT EXISTS`,\n * and a pair of `ALTER COLUMN … SET DEFAULT` / `SET NOT NULL` reconciles for a\n * table that already exists with the wrong shape. Parsing a string back apart\n * for the third of those is how the copies drifted in the first place.\n */\nexport interface AuthUsersColumn {\n /** Physical column name. */\n column: string;\n /** Postgres type. */\n type: string;\n /** Default expression, verbatim, or absent for no default. */\n default?: string;\n /** Whether the column is NOT NULL. */\n notNull?: boolean;\n}\n\n/**\n * `email` is NOT NULL on purpose, and the anonymous sign-in route depends on it\n * — it synthesizes `anon_<32 hex>@anonymous.local` rather than inserting NULL.\n * The 320-char bound (RFC 5321) is a CHECK rather than a `VARCHAR(n)`, added\n * separately by `ensureAuthTablesExist` so it can be `NOT VALID` on an adopted\n * table that already holds a longer row.\n */\nexport const AUTH_USERS_COLUMNS: readonly AuthUsersColumn[] = [\n { column: \"email\", type: \"TEXT\", notNull: true },\n { column: \"display_name\", type: \"TEXT\" },\n { column: \"photo_url\", type: \"TEXT\" },\n { column: \"roles\", type: \"TEXT[]\", default: \"'{}'\", notNull: true },\n { column: \"password_hash\", type: \"TEXT\" },\n { column: \"email_verified\", type: \"BOOLEAN\", default: \"FALSE\", notNull: true },\n { column: \"email_verification_token\", type: \"TEXT\" },\n { column: \"email_verification_sent_at\", type: \"TIMESTAMP WITH TIME ZONE\" },\n { column: \"is_anonymous\", type: \"BOOLEAN\", default: \"FALSE\", notNull: true },\n { column: \"metadata\", type: \"JSONB\", default: \"'{}'\", notNull: true },\n { column: \"tokens_valid_after\", type: \"TIMESTAMP WITH TIME ZONE\" },\n { column: \"created_at\", type: \"TIMESTAMP WITH TIME ZONE\", default: \"NOW()\", notNull: true },\n { column: \"updated_at\", type: \"TIMESTAMP WITH TIME ZONE\", default: \"NOW()\", notNull: true }\n];\n\nconst BY_COLUMN = new Map(AUTH_USERS_COLUMNS.map(c => [c.column, c]));\n\n/** Type + inline constraints, as they appear after the column name. */\nexport function authUsersColumnSql(spec: AuthUsersColumn): string {\n return [\n spec.type,\n spec.default !== undefined ? `DEFAULT ${spec.default}` : \"\",\n spec.notNull ? \"NOT NULL\" : \"\"\n ].filter(Boolean).join(\" \");\n}\n\n/**\n * The auth-owned definition for a physical column name, or `undefined` when\n * auth does not own it.\n *\n * Callers pass the RESOLVED column name (after `columnName` mapping), because\n * that is the only name the three creators agree on: the scaffold's users\n * collection spells the property `displayName` and the column `display_name`.\n */\nexport function authUsersColumnDefinition(column: string): string | undefined {\n const spec = BY_COLUMN.get(column);\n return spec ? authUsersColumnSql(spec) : undefined;\n}\n\n/**\n * Whether a collection is an auth collection, i.e. whether the definitions in\n * this module apply to its table at all.\n *\n * Duplicated in shape from `@rebasepro/common`'s policy defaults on purpose:\n * that one takes a `CollectionConfig`, this one is called from DDL code paths\n * that hold looser objects, and both spellings must accept `auth: true` as well\n * as `auth: { enabled: true }`.\n */\nexport function isAuthCollection(collection: unknown): boolean {\n const auth = (collection as { auth?: unknown } | undefined)?.auth;\n if (auth === true) return true;\n return typeof auth === \"object\" && auth !== null && (auth as { enabled?: unknown }).enabled === true;\n}\n","/**\n * The one place a `{ type: \"vector\" }` property becomes an ANN index.\n *\n * Without an index, pgvector answers `ORDER BY embedding <=> $1` by computing\n * the distance to every row and sorting — exact, and linear. That is the right\n * answer at ten thousand rows and the wrong one at a million, which is why the\n * default here is to build an index rather than to leave the column bare.\n *\n * ## The operator class is not a detail\n *\n * An index is built for exactly one operator class, and the planner uses it\n * only for the operator that class implements. `vector_cosine_ops` answers\n * `<=>` and nothing else; a query asking for `<->` against a cosine index gets\n * a sequential scan and no error. So the default indexed distance here is\n * `cosine`, because `cosine` is what `vectorSearch` measures with when the\n * caller does not say — see `DrizzleConditionBuilder.buildVectorSearch`. The\n * two defaults have to agree, and this comment is the reason they do.\n *\n * ## Why 2000 dimensions is a ceiling and not an error\n *\n * pgvector cannot index a `vector` wider than 2000 dimensions with either\n * method. A 3072-dimension embedding (`text-embedding-3-large`) is therefore\n * storable and searchable but not indexable. Refusing the boot over that would\n * make a working configuration unbootable; silently indexing it is impossible.\n * So the column is created, the index is skipped, and the reason is reported.\n *\n * Like `search-column.ts`, this module exists so that the DDL generator and the\n * boot-time ensure render the *same* specification rather than describing the\n * same index twice, differently. `contracts/derived-names.txt` records the\n * names both produce, and CI fails if they diverge.\n *\n * ## And why the column itself is described here too\n *\n * `VECTOR(n)` is a type Atlas cannot be shown. It has to materialise the\n * desired state in a dev database to diff against, that database is created\n * empty and *emptied again* by Atlas at the start of every run, and nothing in\n * the free tier can put `CREATE EXTENSION vector` back — so a `schema.sql`\n * mentioning the type fails with `type \"vector\" does not exist` on every push,\n * for good. Search hit the same wall for its own reasons and took the same way\n * out: the objects leave `schema.sql`, Atlas is told to exclude them, and\n * Rebase applies them itself. See `generatePostgresVectorDdl`.\n */\nimport type { CollectionConfig, Property, VectorDistance, VectorIndexConfig } from \"@rebasepro/types\";\nimport { isPostgresCollectionConfig } from \"@rebasepro/types\";\nimport { getTableName } from \"@rebasepro/common\";\nimport { toPostgresIdentifier } from \"@rebasepro/utils\";\n\n/**\n * The widest `vector` pgvector will build an HNSW or IVFFlat index over.\n * Storage and exact search are unaffected by this limit.\n */\nexport const MAX_INDEXABLE_VECTOR_DIMENSIONS = 2000;\n\n/** The distance indexed when a property does not name one. */\nexport const DEFAULT_VECTOR_DISTANCE: VectorDistance = \"cosine\";\n\n/** The index method used when a property does not name one. */\nexport const DEFAULT_VECTOR_INDEX_METHOD = \"hnsw\" as const;\n\n/**\n * Operator class per distance. These strings are part of the database contract:\n * they appear in `CREATE INDEX`, so renaming one renames an index.\n */\nconst OPERATOR_CLASS: Record<VectorDistance, string> = {\n cosine: \"vector_cosine_ops\",\n l2: \"vector_l2_ops\",\n inner_product: \"vector_ip_ops\"\n};\n\n/** Short, stable tag per distance, used to name the index. */\nconst DISTANCE_TAG: Record<VectorDistance, string> = {\n cosine: \"cosine\",\n l2: \"l2\",\n inner_product: \"ip\"\n};\n\nexport interface VectorIndexSpec {\n schema: string;\n table: string;\n column: string;\n indexName: string;\n method: \"hnsw\" | \"ivfflat\";\n distance: VectorDistance;\n operatorClass: string;\n /** Rendered into `WITH (...)`; empty when every parameter is defaulted. */\n parameters: Array<[string, number]>;\n}\n\n/** A vector column that will not be indexed, and why. */\nexport interface SkippedVectorIndex {\n schema: string;\n table: string;\n column: string;\n dimensions: number;\n reason: string;\n}\n\nexport interface VectorIndexPlan {\n specs: VectorIndexSpec[];\n skipped: SkippedVectorIndex[];\n}\n\nexport class VectorIndexConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"VectorIndexConfigError\";\n }\n}\n\nconst isVectorProperty = (prop: unknown): prop is Property & {\n type: \"vector\";\n dimensions: number;\n index?: VectorIndexConfig | false;\n} => !!prop && typeof prop === \"object\" && (prop as { type?: string }).type === \"vector\";\n\nconst asDistances = (config: VectorIndexConfig, label: string): VectorDistance[] => {\n const raw = config.distance ?? DEFAULT_VECTOR_DISTANCE;\n const list = Array.isArray(raw) ? raw : [raw];\n if (list.length === 0) {\n throw new VectorIndexConfigError(\n `${label}: \\`index.distance\\` is an empty array. Name at least one distance, or set \\`index: false\\` to create no index.`\n );\n }\n const seen = new Set<VectorDistance>();\n for (const distance of list) {\n if (!(distance in OPERATOR_CLASS)) {\n throw new VectorIndexConfigError(\n `${label}: \\`index.distance\\` is \"${distance}\", which is not a pgvector distance. Use ${Object.keys(OPERATOR_CLASS).map(d => `\"${d}\"`).join(\", \")}.`\n );\n }\n if (seen.has(distance)) {\n throw new VectorIndexConfigError(`${label}: \\`index.distance\\` lists \"${distance}\" twice.`);\n }\n seen.add(distance);\n }\n return list;\n};\n\nconst assertPositiveInteger = (value: number | undefined, key: string, label: string): void => {\n if (value === undefined) return;\n if (!Number.isInteger(value) || value <= 0) {\n throw new VectorIndexConfigError(\n `${label}: \\`index.${key}\\` is ${JSON.stringify(value)}. It must be a positive integer.`\n );\n }\n};\n\n/**\n * Index parameters for one method. Parameters belonging to the *other* method\n * are rejected rather than ignored, because a silently dropped `lists` on an\n * HNSW index reads, from the config, exactly like a tuned index.\n */\nconst parametersFor = (\n method: \"hnsw\" | \"ivfflat\",\n config: VectorIndexConfig,\n label: string\n): Array<[string, number]> => {\n assertPositiveInteger(config.m, \"m\", label);\n assertPositiveInteger(config.efConstruction, \"efConstruction\", label);\n assertPositiveInteger(config.lists, \"lists\", label);\n\n if (method === \"hnsw\") {\n if (config.lists !== undefined) {\n throw new VectorIndexConfigError(\n `${label}: \\`index.lists\\` only applies to \\`method: \"ivfflat\"\\`. Remove it, or switch the method.`\n );\n }\n const params: Array<[string, number]> = [];\n if (config.m !== undefined) params.push([\"m\", config.m]);\n if (config.efConstruction !== undefined) params.push([\"ef_construction\", config.efConstruction]);\n return params;\n }\n\n for (const key of [\"m\", \"efConstruction\"] as const) {\n if (config[key] !== undefined) {\n throw new VectorIndexConfigError(\n `${label}: \\`index.${key}\\` only applies to \\`method: \"hnsw\"\\`. Remove it, or switch the method.`\n );\n }\n }\n return config.lists !== undefined ? [[\"lists\", config.lists]] : [];\n};\n\n/**\n * Every ANN index a collection's vector properties call for.\n *\n * `resolveColumn` is passed in rather than imported so that this module stays\n * free of the DDL generator, which imports *it*. Both callers hand it the same\n * `resolveColumnName`, and a contract test asserts the names agree.\n */\nexport const buildVectorIndexPlan = (\n collection: CollectionConfig,\n resolveColumn: (propName: string, prop?: Property | null) => string\n): VectorIndexPlan => {\n const specs: VectorIndexSpec[] = [];\n const skipped: SkippedVectorIndex[] = [];\n const properties = collection.properties ?? {};\n\n const table = getTableName(collection);\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n\n for (const [propName, prop] of Object.entries(properties)) {\n if (!isVectorProperty(prop)) continue;\n if (prop.index === false) continue;\n\n const label = `${collection.slug}.${propName}`;\n const column = resolveColumn(propName, prop as Property);\n const config: VectorIndexConfig = prop.index ?? {};\n const method = config.method ?? DEFAULT_VECTOR_INDEX_METHOD;\n\n if (method !== \"hnsw\" && method !== \"ivfflat\") {\n throw new VectorIndexConfigError(\n `${label}: \\`index.method\\` is \"${method}\". Use \"hnsw\" or \"ivfflat\".`\n );\n }\n\n // Read before the dimension gate so a malformed block is reported even\n // on a column too wide to index — the config is wrong either way.\n const distances = asDistances(config, label);\n const parameters = parametersFor(method, config, label);\n\n if (!Number.isInteger(prop.dimensions) || prop.dimensions <= 0) {\n throw new VectorIndexConfigError(\n `${label}: \\`dimensions\\` is ${JSON.stringify(prop.dimensions)}. It must be a positive integer.`\n );\n }\n\n if (prop.dimensions > MAX_INDEXABLE_VECTOR_DIMENSIONS) {\n skipped.push({\n schema,\n table,\n column,\n dimensions: prop.dimensions,\n reason:\n `pgvector cannot index a vector wider than ${MAX_INDEXABLE_VECTOR_DIMENSIONS} dimensions, and ` +\n `${label} declares ${prop.dimensions}. The column works and \\`vectorSearch\\` still answers, as an ` +\n `exact scan. To index it, reduce the dimensions (many embedding models support a shorter output) ` +\n `or set \\`index: false\\` to state that the scan is intended.`\n });\n continue;\n }\n\n for (const distance of distances) {\n specs.push({\n schema,\n table,\n column,\n // Distance is in the name because one column may carry an index\n // per distance, and two indexes cannot share a name. The method\n // is in it because switching methods is a different index, not\n // a redefinition of the same one — `CREATE INDEX IF NOT EXISTS`\n // would otherwise keep the old one and report success.\n indexName: toPostgresIdentifier(`${table}_${column}_${method}_${DISTANCE_TAG[distance]}`),\n method,\n distance,\n operatorClass: OPERATOR_CLASS[distance],\n parameters\n });\n }\n }\n\n return { specs, skipped };\n};\n\n/**\n * The `CREATE INDEX` for one spec.\n *\n * `CONCURRENTLY` is deliberately absent, for the same reason it is absent from\n * `searchIndexStatements`: this form is replayed as part of a migration, where\n * a concurrent build is not allowed. The boot-time ensure rewrites it — see\n * `ensureCollectionTables`.\n */\nexport const vectorIndexStatement = (spec: VectorIndexSpec): string => {\n const params = spec.parameters.length\n ? ` WITH (${spec.parameters.map(([key, value]) => `${key} = ${value}`).join(\", \")})`\n : \"\";\n return (\n `CREATE INDEX IF NOT EXISTS \"${spec.indexName}\" ON \"${spec.schema}\".\"${spec.table}\" ` +\n `USING ${spec.method} (\"${spec.column}\" ${spec.operatorClass})${params};`\n );\n};\n\n/** Every statement for a plan, in a stable order. */\nexport const vectorIndexStatements = (plan: VectorIndexPlan): string[] =>\n plan.specs.map(vectorIndexStatement);\n\n/** The index names a plan creates — what the derived-names contract records. */\nexport const vectorIndexNames = (plan: VectorIndexPlan): string[] =>\n plan.specs.map(spec => spec.indexName);\n\n// ── The column, for the file Rebase applies itself ──────────────────────────\n\nconst quote = (v: string): string => `'${v.replace(/'/g, \"''\")}'`;\n\n/**\n * The schema pgvector's types are installed into.\n *\n * `WITH SCHEMA public` for the same load-bearing reason `searchExtensionStatements`\n * gives: an unqualified `CREATE EXTENSION` lands in the first schema on\n * `search_path`, which is `\"$user\", public` — and the scaffold's role is named\n * `rebase`, the same as a schema the generator creates. Left to itself the\n * extension would install into `rebase`, and every unqualified `VECTOR(n)`\n * below would fail to resolve.\n */\nexport const VECTOR_EXTENSION_SCHEMA = \"public\";\n\n/** The extension name a database has to name to let Rebase install pgvector. */\nexport const VECTOR_EXTENSION = \"vector\";\n\n/**\n * How a project says Rebase may install pgvector, quoted into the messages that\n * have to name it. Spelled once so the option and the advice cannot drift.\n */\nexport const VECTOR_EXTENSION_OPT_IN = `database({ extensions: [\"${VECTOR_EXTENSION}\"] })`;\n\n/** Did the project give Rebase leave to install pgvector? */\nexport const vectorExtensionDeclared = (extensions: readonly string[] | undefined): boolean =>\n (extensions ?? []).includes(VECTOR_EXTENSION);\n\n/**\n * Install pgvector — emitted only when the database asked for it.\n *\n * Opt-in because installing an extension is a decision with a deployment behind\n * it: the image has to ship the library, the role has to be allowed to install\n * it, and a managed provider has to have it on an allow-list. None of that is\n * visible from inside the connection, so Rebase does not decide it. See\n * `DatabaseOptions.extensions`.\n *\n * Withholding the statement is not withholding the *column*: the column is\n * still created, and Postgres refuses it with `type \"vector\" does not exist`\n * on a database where pgvector was never installed by hand. That error is the\n * one this design accepts, and `vectorExtensionHint` is what makes it name\n * {@link VECTOR_EXTENSION_OPT_IN} rather than nothing.\n */\nexport const vectorExtensionStatement = (): string =>\n `CREATE EXTENSION IF NOT EXISTS ${VECTOR_EXTENSION} WITH SCHEMA ${VECTOR_EXTENSION_SCHEMA};`;\n\n/**\n * The missing-pgvector explanation, appended to whichever error revealed it.\n *\n * Two readers, needing opposite things, which is why the branch is on the error\n * text rather than on the configuration:\n *\n * - **`type \"vector\" does not exist`** — nobody opted in and the database has\n * no pgvector. The fix is one line of config they cannot guess, so naming\n * the option *is* the hint.\n * - **the install itself failed** — the config is already right, and repeating\n * the option would send them to edit a correct line. What is missing is the\n * library on the server, or the grant.\n *\n * Lives here rather than beside either caller because both need it: the boot\n * ensure raises the first through its action applier, and `rebase db push`\n * raises it out of `applyVectorDdl`. A hint on only one path is how a bare\n * `type \"vector\" does not exist` reaches somebody — which is the thing this\n * exists to prevent.\n */\nexport const vectorExtensionHint = (message: string): string => {\n const installRefused = /extension \"vector\" is not available/i.test(message)\n || /(permission denied to create extension|must be (superuser|owner).{0,40}extension)/i.test(message);\n if (installRefused) {\n return (\n \"\\n pgvector was declared and could not be installed. It is a server extension, so it needs an image \" +\n \"that ships the library (the scaffold's `pgvector/pgvector:pg18` does; a stock `postgres:18` does not) \" +\n \"and a role allowed to run `CREATE EXTENSION vector;`. Managed Postgres usually allows it once the \" +\n \"extension is on the provider's allow-list.\"\n );\n }\n if (!/type \"(vector|halfvec|sparsevec)\" does not exist/i.test(message)) return \"\";\n return (\n \"\\n pgvector is not installed on this database, and Rebase installs it only where a database says it may: \" +\n `add \\`${VECTOR_EXTENSION_OPT_IN}\\` in config/resources.ts, or install it once by hand with ` +\n \"`CREATE EXTENSION vector;`. Either way the server needs an image that ships the library — the scaffold's \" +\n \"`pgvector/pgvector:pg18` does, a stock `postgres:18` does not. Rebase then creates the column and its ANN \" +\n \"index automatically — see the `index` option on the property.\"\n );\n};\n\n/** One `{ type: \"vector\" }` property, as a column. */\nexport interface VectorColumnSpec {\n schema: string;\n table: string;\n column: string;\n dimensions: number;\n /** Rendered after the type, in the generator's order: UNIQUE then NOT NULL. */\n modifiers: string;\n}\n\n/**\n * Every vector column a collection declares.\n *\n * Wider than {@link buildVectorIndexPlan} on purpose: that one answers \"what\n * gets an ANN index\", and skips both a property with `index: false` and one too\n * wide to index. Either still needs its column.\n */\nexport const buildVectorColumnSpecs = (\n collection: CollectionConfig,\n resolveColumn: (propName: string, prop?: Property | null) => string\n): VectorColumnSpec[] => {\n const table = getTableName(collection);\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n const specs: VectorColumnSpec[] = [];\n\n for (const [propName, prop] of Object.entries(collection.properties ?? {})) {\n if (!isVectorProperty(prop)) continue;\n // Assembled in the CREATE TABLE generator's order, so the column this\n // file adds and the column `schema.sql` used to declare are the same\n // column. A vector property is never a primary key and carries no\n // SQL-level default, which is what leaves only these two.\n const validation = (prop as { validation?: { required?: boolean; unique?: boolean } }).validation;\n let modifiers = \"\";\n if (validation?.unique) modifiers += \" UNIQUE\";\n if (validation?.required) modifiers += \" NOT NULL\";\n specs.push({\n schema,\n table,\n column: resolveColumn(propName, prop as Property),\n dimensions: prop.dimensions,\n modifiers\n });\n }\n\n return specs;\n};\n\n/** The column type — the one place `VECTOR(n)` is spelled. */\nexport const vectorColumnType = (spec: Pick<VectorColumnSpec, \"dimensions\">): string =>\n `VECTOR(${spec.dimensions})`;\n\n/** The column definition as it appears inside `CREATE TABLE`. */\nexport const vectorColumnDefinition = (spec: VectorColumnSpec): string =>\n `\"${spec.column}\" ${vectorColumnType(spec)}${spec.modifiers}`;\n\n/**\n * Refuse — or perform — a `dimensions` change that `ADD COLUMN IF NOT EXISTS`\n * would otherwise swallow.\n *\n * Without this the file *launders* the change: the ADD is a no-op against a\n * column that exists, so a project that went from 384 to 768 dimensions would\n * push clean, keep a 384-wide column, and fail on the next insert with a\n * message about the row rather than about the config. Atlas used to catch this\n * — it owned the column and planned the `ALTER … TYPE` — and taking the column\n * out of its sight is exactly what makes the guard necessary.\n *\n * The widening is performed when the column holds no values, because that is\n * the case Atlas handled and it is the common one: a developer changing\n * embedding models before there are any embeddings. With values present the\n * conversion is pgvector's to reject — every stored vector is the old width —\n * so this refuses first and names the statement to run afterwards.\n *\n * `atttypmod` on a `vector` column *is* the dimension count: pgvector stores it\n * directly rather than offsetting it the way `varchar` does. `-1` means the\n * column was declared as a bare `vector`, which is drift in the same sense.\n */\nexport const vectorDimensionGuard = (spec: VectorColumnSpec): string => {\n const relation = `\"${spec.schema}\".\"${spec.table}\"`;\n return `DO $rebase_vector$\nDECLARE actual int;\nBEGIN\n SELECT a.atttypmod INTO actual\n FROM pg_attribute a\n JOIN pg_type t ON t.oid = a.atttypid\n WHERE a.attrelid = ${quote(relation)}::regclass\n AND a.attname = ${quote(spec.column)}\n AND NOT a.attisdropped\n AND t.typname = 'vector';\n IF actual IS NOT NULL AND actual <> ${spec.dimensions} THEN\n IF EXISTS (SELECT 1 FROM ${relation} WHERE \"${spec.column}\" IS NOT NULL) THEN\n RAISE EXCEPTION 'Rebase: ${spec.schema}.${spec.table}.\"${spec.column}\" declares ${spec.dimensions} dimensions but the column is vector(%), and it already holds values of the old width. pgvector cannot convert them. Re-embed the rows at ${spec.dimensions} dimensions (or clear the column), then re-apply: ALTER TABLE ${relation} ALTER COLUMN \"${spec.column}\" TYPE ${vectorColumnType(spec)};', actual;\n END IF;\n ALTER TABLE ${relation} ALTER COLUMN \"${spec.column}\" TYPE ${vectorColumnType(spec)};\n END IF;\nEND\n$rebase_vector$;`;\n};\n\n/**\n * The object names a collection's vector properties own, unqualified.\n *\n * What Atlas has to be told to exclude. Only the column and the ANN indexes: a\n * `UNIQUE` or `NOT NULL` on the column is a property *of* the column, and\n * excluding the column takes them with it — measured against Atlas 1.2.3 and\n * 1.3.2, where a target carrying `vector(3) NOT NULL UNIQUE` and a `schema.sql`\n * carrying neither reported \"Schema is synced, no changes to be made\".\n */\nexport const vectorObjectNames = (\n collection: CollectionConfig,\n resolveColumn: (propName: string, prop?: Property | null) => string\n): string[] => [\n ...buildVectorColumnSpecs(collection, resolveColumn).map(spec => spec.column),\n ...vectorIndexNames(buildVectorIndexPlan(collection, resolveColumn))\n];\n","import { CollectionConfig, NumberProperty, Property, ResolvedRelation, RelationProperty, SecurityOperation, SecurityRule, StringProperty, isPostgresCollectionConfig, DateProperty, ArrayProperty, MapProperty, ReferenceProperty, VectorProperty, BinaryProperty, isManyToMany, type ResolvedManyToMany, type ResolvedBelongsTo } from \"@rebasepro/types\";\nimport { getEnumVarName, getTableName, resolveCollectionRelations, findRelation, securityRuleToConditions, policyToPostgres, getEffectiveSecurityRules, getInjectedSecurityRules, resolveJunctionSpecs, getJunctionSecurityRules, getJunctionCollectionConfig, resolveStringColumnLength, relationalCollections } from \"@rebasepro/common\";\nimport { toSnakeCase, getPolicyNamesForRule, generateForeignKeyName, legacyForeignKeyName, toPostgresIdentifier } from \"@rebasepro/utils\";\nimport { AUTH_USERS_COLUMNS, authUsersColumnDefinition, authUsersColumnSql, isAuthCollection } from \"./auth-users-columns\";\nimport {\n buildSearchColumnSpec,\n searchColumnDefinition,\n fuzzyColumnDefinition,\n searchIndexStatements,\n searchHelperFunctions,\n searchExtensionStatements,\n searchColumnNames,\n searchColumnStamps,\n searchStampGuards,\n searchIndexNames,\n type SearchColumnSpec\n} from \"./search-column\";\nimport {\n buildVectorColumnSpecs,\n buildVectorIndexPlan,\n vectorColumnDefinition,\n vectorDimensionGuard,\n vectorExtensionDeclared,\n vectorExtensionStatement,\n vectorIndexStatements,\n vectorObjectNames,\n VECTOR_EXTENSION_OPT_IN,\n type VectorIndexPlan\n} from \"./vector-index\";\nimport { buildCollectionIndexSpecs, collectionIndexStatements } from \"./collection-index\";\nimport { REBASE_SCHEMA } from \"@rebasepro/types\";\n\n// --- Helper Functions ---\n\nexport const resolveColumnName = (propName: string, prop?: Property | null): string => {\n if (prop && \"columnName\" in prop && typeof prop.columnName === \"string\") {\n return prop.columnName;\n }\n return toSnakeCase(propName);\n};\n\nexport const getPrimaryKeyProp = (collection: CollectionConfig): { name: string, type: \"string\" | \"number\", isUuid: boolean } => {\n if (collection.properties) {\n const idPropEntry = Object.entries(collection.properties).find(([_, prop]) => \"isId\" in (prop as unknown as object) && Boolean((prop as unknown as Record<string, unknown>).isId));\n if (idPropEntry) {\n const prop = idPropEntry[1] as unknown as Property;\n const isUuid = prop.type === \"string\" && \"isId\" in prop && (prop as unknown as StringProperty).isId === \"uuid\";\n return { name: idPropEntry[0], type: prop.type === \"number\" ? \"number\" : \"string\", isUuid };\n }\n }\n const idProp = collection.properties?.[\"id\"] as unknown as Property | undefined;\n if (idProp?.type === \"number\") {\n return { name: \"id\", type: \"number\", isUuid: false };\n }\n const isUuid = idProp?.type === \"string\" && \"isId\" in idProp && (idProp as unknown as StringProperty).isId === \"uuid\";\n return { name: \"id\", type: \"string\", isUuid: isUuid ?? false };\n};\n\nexport const isNumericId = (collection: CollectionConfig): boolean => {\n return getPrimaryKeyProp(collection).type === \"number\";\n};\n\nexport const getPrimaryKeyName = (collection: CollectionConfig): string => {\n return getPrimaryKeyProp(collection).name;\n};\n\n/** The column type a junction holds for one endpoint's primary key. */\nconst junctionKeyType = (collection: CollectionConfig): string =>\n isNumericId(collection) ? \"INTEGER\" : (getPrimaryKeyProp(collection).isUuid ? \"UUID\" : \"TEXT\");\n\nexport const isIdProperty = (propName: string, prop: Property, collection: CollectionConfig): boolean => {\n if (\"isId\" in prop && Boolean(prop.isId)) return true;\n const hasExplicitId = Object.values(collection.properties ?? {}).some(p => \"isId\" in (p as unknown as object) && Boolean((p as unknown as Record<string, unknown>).isId));\n return !hasExplicitId && propName === \"id\";\n};\n\n\ntype ResolveCollection = (slug: string) => CollectionConfig | undefined;\n\n/**\n * Render statements produced by {@link generatePolicyStatements} back into the\n * exact string the DDL/policies files have always carried: each statement on\n * its own line, terminated by a newline. Keeping the string form derived from\n * the statement array means the two can never drift — the boot-time applier and\n * the generated `policies.sql` emit the same SQL, from the same source.\n */\nconst statementsToDdl = (statements: string[]): string => statements.map(s => `${s}\\n`).join(\"\");\n\n/**\n * The `ON DELETE` a foreign key gets when the author did not say.\n *\n * One rule for every property that emits one — `belongsTo` relations and\n * `reference` properties alike. `reference` kept its own `CASCADE` default for\n * a release after this rule was written, which is exactly the split this\n * function exists to prevent: two spellings of the same link, two data-retention\n * behaviours, and only one of them documented.\n *\n * An optional link is `SET NULL`: the column can hold NULL, so dropping the\n * parent leaves the child row with an empty pointer, which is what \"optional\"\n * already means.\n *\n * A required link is **`RESTRICT`**, not `CASCADE`. `NOT NULL` says the child\n * cannot exist without a parent; it does not say deleting the parent should\n * take the child with it. That second claim is a data-retention decision, and\n * defaulting to it meant `onDelete` — a field nobody has to write — silently\n * turned every `DELETE FROM authors` into a cascade through posts, comments and\n * anything else that hung off them. `RESTRICT` fails the delete instead and\n * names the constraint, so the author chooses `cascade` on purpose or clears\n * the children first.\n *\n * Both DDL paths — the `CREATE TABLE` generator and {@link planRelationalColumns},\n * which boot-ensure compares the live database against — call this, so a\n * default that appears in one and not the other cannot make `db push` plan a\n * constraint rewrite on every run.\n */\nexport const defaultBelongsToOnDelete = (required: boolean | undefined): \"RESTRICT\" | \"SET NULL\" =>\n required ? \"RESTRICT\" : \"SET NULL\";\n\nconst generatePolicyDdl = (collection: CollectionConfig, rule: SecurityRule, resolveCollection: ResolveCollection): string =>\n statementsToDdl(generatePolicyStatements(collection, rule, resolveCollection));\n\n/**\n * The individual SQL statements a single security rule compiles to: a\n * `DROP POLICY IF EXISTS` / `CREATE POLICY` pair per operation, each a complete\n * statement (terminated by `;`, no trailing newline).\n *\n * This is the primitive the boot-time RLS applier runs one statement at a time\n * (the runtime's DB handle speaks the extended query protocol, which forbids\n * multiple commands in one execute), while `db push` writes the joined string.\n */\nexport const generatePolicyStatements = (collection: CollectionConfig, rule: SecurityRule, resolveCollection: ResolveCollection): string[] => {\n const tableName = getTableName(collection);\n const ops: readonly SecurityOperation[] = rule.operations && rule.operations.length > 0\n ? rule.operations\n : [rule.operation ?? \"all\"];\n\n const policyNames = getPolicyNamesForRule(rule, tableName);\n\n return ops.flatMap((op, opIdx) => {\n return generateSinglePolicyStatements(collection, rule, op, policyNames[opIdx], resolveCollection);\n });\n};\n\nconst generateSinglePolicyStatements = (collection: CollectionConfig, rule: SecurityRule, operation: SecurityOperation, policyName: string, resolveCollection: ResolveCollection): string[] => {\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n const tableName = getTableName(collection);\n const mode = (rule.mode ?? \"permissive\").toUpperCase();\n const operationUpper = operation.toUpperCase();\n const pgRoles = rule.pgRoles ? [...rule.pgRoles].sort() : [\"public\"];\n\n const needsUsing = operation !== \"insert\";\n const needsWithCheck = operation !== \"select\" && operation !== \"delete\";\n\n // Desugar the rule (access / ownerField / roles / structured condition / raw\n // SQL) into the shared PolicyExpression model, then compile to SQL. This is\n // the same normalization the client-side evaluator uses, so DDL and UI agree.\n const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);\n\n let usingClause = needsUsing && usingExpr ? policyToPostgres(usingExpr, collection, { resolveCollection }) : null;\n let withCheckClause = needsWithCheck && withCheckExpr ? policyToPostgres(withCheckExpr, collection, { resolveCollection }) : null;\n\n if (!usingClause && needsUsing) {\n usingClause = \"false\";\n }\n if (!withCheckClause && needsWithCheck) {\n withCheckClause = \"false\";\n }\n\n const drop = `DROP POLICY IF EXISTS \"${policyName}\" ON \"${schema}\".\"${tableName}\";`;\n let create = `CREATE POLICY \"${policyName}\" ON \"${schema}\".\"${tableName}\" AS ${mode} FOR ${operationUpper} TO ${pgRoles.map(r => `\"${r}\"`).join(\", \")}`;\n if (usingClause) create += ` USING (${usingClause})`;\n if (withCheckClause) create += ` WITH CHECK (${withCheckClause})`;\n create += \";\";\n return [drop, create];\n};\n\n/**\n * Single-quote escaping for a SQL string literal (PostgreSQL doubles the\n * quote). Enum labels come straight from user-authored collection config, so a\n * label like `it's` closes the literal early and the whole generated file stops\n * parsing at the `CREATE TYPE`. Lives here rather than next to its other caller\n * because ensure-collection-tables already imports from this module — the\n * reverse would be a cycle.\n */\nexport const quoteSqlLiteral = (value: string): string => `'${value.replace(/'/g, \"''\")}'`;\n\nexport const getSqlColumnType = (propName: string, prop: Property, collection: CollectionConfig, collections: CollectionConfig[]): string => {\n switch (prop.type) {\n case \"string\": {\n const stringProp = prop as StringProperty;\n if (stringProp.enum) {\n const tableName = getTableName(collection);\n const colName = resolveColumnName(propName, prop);\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n return `\"${schema}\".\"${tableName}_${colName}\"`;\n }\n if (stringProp.isId === \"uuid\" || stringProp.columnType === \"uuid\") {\n return \"UUID\";\n }\n // Width comes from `validation.max` when the property states one.\n // It used to be a hardcoded 255 here and *absent* on the Drizzle\n // path, so the same property produced a bounded column down one\n // generator and an unbounded one down the other.\n if (stringProp.columnType === \"char\") {\n return `CHAR(${resolveStringColumnLength(stringProp)})`;\n }\n if (stringProp.columnType === \"varchar\") {\n return `VARCHAR(${resolveStringColumnLength(stringProp)})`;\n }\n // `text` is the default. The two generators disagreed here before:\n // this one emitted VARCHAR(255) while the drizzle path emitted a bare\n // `varchar()`, which Postgres treats as unbounded — so the same\n // property produced a capped column down one path and an uncapped one\n // down the other.\n return \"TEXT\";\n }\n case \"number\": {\n const numProp = prop as NumberProperty;\n const isId = isIdProperty(propName, prop, collection);\n if (\"isId\" in numProp && numProp.isId === \"increment\") {\n return \"INTEGER GENERATED BY DEFAULT AS IDENTITY\";\n }\n if (numProp.columnType) {\n if (numProp.columnType === \"double precision\") return \"DOUBLE PRECISION\";\n return numProp.columnType.toUpperCase();\n }\n return (numProp.validation?.integer || isId) ? \"INTEGER\" : \"NUMERIC\";\n }\n case \"boolean\":\n return \"BOOLEAN\";\n case \"date\": {\n const dateProp = prop as DateProperty;\n if (dateProp.columnType === \"date\") return \"DATE\";\n if (dateProp.columnType === \"time\") return \"TIME\";\n return \"TIMESTAMP WITH TIME ZONE\";\n }\n case \"map\": {\n const mapProp = prop as MapProperty;\n return mapProp.columnType === \"json\" ? \"JSON\" : \"JSONB\";\n }\n // `{ latitude, longitude }` — a document, like `map`. It used to fall to\n // the `TEXT` default below while the Drizzle generator emitted no column\n // at all, which is the divergence that made the type unpersistable.\n case \"geopoint\":\n return \"JSONB\";\n case \"array\": {\n const arrayProp = prop as ArrayProperty;\n let colType = arrayProp.columnType;\n if (!colType && arrayProp.of && !Array.isArray(arrayProp.of)) {\n const ofProp = arrayProp.of as Property;\n if (ofProp.type === \"string\") {\n colType = \"text[]\";\n } else if (ofProp.type === \"number\") {\n colType = ofProp.validation?.integer ? \"integer[]\" : \"numeric[]\";\n } else if (ofProp.type === \"boolean\") {\n colType = \"boolean[]\";\n }\n }\n if (colType === \"json\") return \"JSON\";\n if (colType === \"text[]\") return \"TEXT[]\";\n if (colType === \"integer[]\") return \"INTEGER[]\";\n if (colType === \"boolean[]\") return \"BOOLEAN[]\";\n if (colType === \"numeric[]\") return \"NUMERIC[]\";\n return \"JSONB\";\n }\n case \"vector\": {\n const vp = prop as VectorProperty;\n return `VECTOR(${vp.dimensions})`;\n }\n case \"binary\": {\n return \"BYTEA\";\n }\n case \"relation\": {\n const refProp = prop as RelationProperty;\n const resolvedRelations = resolveCollectionRelations(collection);\n const relation = findRelation(resolvedRelations, refProp.relation?.relationName ?? propName);\n if (relation?.kind !== \"belongsTo\") {\n throw new Error(`Relation ${propName} does not put a column on this table (only \\`belongsTo\\` does)`);\n }\n let targetCollection: CollectionConfig;\n try {\n targetCollection = relation.target();\n } catch {\n return \"TEXT\";\n }\n const pkProp = getPrimaryKeyProp(targetCollection);\n return pkProp.type === \"number\" ? \"INTEGER\" : (pkProp.isUuid ? \"UUID\" : \"TEXT\");\n }\n case \"reference\": {\n const refProp = prop as ReferenceProperty;\n const targetCollection = collections.find(c => c.slug === refProp.path || getTableName(c) === refProp.path);\n if (!targetCollection) return \"TEXT\";\n const pkProp = getPrimaryKeyProp(targetCollection);\n return pkProp.type === \"number\" ? \"INTEGER\" : (pkProp.isUuid ? \"UUID\" : \"TEXT\");\n }\n default:\n // A silent `TEXT` here is how the two generators drifted apart: the\n // database got a column for `geopoint` and the Drizzle table did\n // not, so the type looked supported and persisted nothing. Every\n // member of `DataType` is handled above; anything else is a\n // generator that has not been taught the type yet, and it should\n // say so rather than invent a column.\n throw new Error(\n `No Postgres column type for property '${propName}' of type ` +\n `'${(prop as Property).type}' in collection '${collection.slug}'. ` +\n \"Add a case to `getSqlColumnType` (and to `getDrizzleColumn`, which must agree).\"\n );\n }\n};\n\n/**\n * Everything a `search` block needs, as a file Rebase applies itself.\n *\n * Search is the one part of the schema Atlas does not own. Two independent\n * reasons, and either alone would be enough:\n *\n * 1. Its free tier refuses to *parse* a desired-state file that so much as\n * contains a function — \"functions and procedures are available to\n * logged-in users only\". A generated `tsvector` column cannot avoid one:\n * `unaccent` is STABLE and jsonb flattening needs a set-returning function,\n * so both have to be wrapped in an IMMUTABLE helper to be legal in a\n * generated column at all.\n * 2. Even with the file accepted, Atlas *wipes* the dev database it diffs\n * against, so a helper seeded there beforehand is gone by the time the plan\n * is analysed. There is no hook to reinstate it.\n *\n * So the column, its index and its helpers are excluded from Atlas's view\n * (`searchExcludePatterns`) and applied from here — the same arrangement the\n * RLS policies already use, and for the same underlying reason.\n *\n * Ordered as it must run: extensions, then helpers, then the column whose\n * expression calls them, then the index over that column. Every statement is\n * `IF NOT EXISTS` / `OR REPLACE`, because this is replayed on every push and\n * appended to migrations that run against databases at any stage of their\n * life. Empty when nothing opted in — the caller writes no file then.\n *\n * The dev database Atlas plans against needs none of this. `searchExcludePatterns`\n * removes the search column from the *inspected* state, so the state Atlas\n * replays there never mentions the column and never calls a helper. Seeding the\n * helpers into that database was tried and removed: measured on Atlas 1.2.3, a\n * `schema apply --dry-run` produces byte-identical output seeded or not, and\n * Atlas wipes the dev database before it plans anyway — so a seed could not have\n * helped even where the excludes are missing, which is the case that really does\n * fail with `function public.rebase_search_unaccent(text) does not exist`.\n */\nexport const generatePostgresSearchDdl = (allCollections: CollectionConfig[]): string => {\n const collections = relationalCollections(allCollections);\n const specs = collections\n .map(c => buildSearchColumnSpec(c))\n .filter((s): s is SearchColumnSpec => s !== undefined);\n if (specs.length === 0) return \"\";\n\n const extensions = Array.from(new Set(specs.flatMap(searchExtensionStatements)));\n const helpers = Array.from(new Set(specs.flatMap(searchHelperFunctions)));\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\";\n ddl += \"--\\n\";\n ddl += \"-- Full-text search for the collections declaring a `search` block.\\n\";\n ddl += \"-- Applied by Rebase, not by Atlas — see generatePostgresSearchDdl.\\n\\n\";\n\n extensions.forEach(s => { ddl += `${s}\\n`; });\n if (extensions.length > 0) ddl += \"\\n\";\n helpers.forEach(s => { ddl += `${s}\\n\\n`; });\n\n for (const collection of collections) {\n const spec = buildSearchColumnSpec(collection);\n if (!spec) continue;\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n const table = `\"${schema}\".\"${getTableName(collection)}\"`;\n\n // ADD COLUMN IF NOT EXISTS rather than the inline definition the\n // CREATE TABLE would use: by the time this runs the table exists,\n // whether Atlas just created it or it has been live for a year.\n // Refuse before altering anything if the column in the database was\n // generated from a different `search` block: `ADD COLUMN IF NOT EXISTS`\n // is a no-op against an existing column, so without this the file would\n // report success and leave the old expression in place — and then stamp\n // it as current.\n searchStampGuards(spec).forEach(s => { ddl += `${s}\\n`; });\n ddl += `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${searchColumnDefinition(spec)};\\n`;\n const fuzzyDef = fuzzyColumnDefinition(spec);\n if (fuzzyDef) ddl += `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${fuzzyDef};\\n`;\n // The fingerprint of the expression each column was built from — the\n // only record of *which* block a generated column came from, and what\n // the guard above and the boot-time ensure both compare against.\n searchColumnStamps(spec).forEach(s => { ddl += `${s.sql}\\n`; });\n searchIndexStatements(spec).forEach(s => { ddl += `${s}\\n`; });\n ddl += \"\\n\";\n }\n\n return ddl;\n};\n\n/**\n * Glob patterns telling Atlas to leave the search column and its index alone.\n *\n * Without these, a desired state that omits search reads to Atlas as an\n * instruction to drop the column — taking the index and the whole search\n * feature with it on the next push.\n *\n * Fully qualified, `schema.table.object`, matching the include list. The\n * two-part form is what Atlas wants when the connection URL scopes it to one\n * schema and is *silently ignored* otherwise: it reads `posts.search_vector`\n * as a table named `search_vector` in a schema named `posts`, matches nothing,\n * and reports no error for the pattern that never fired.\n */\nexport const searchExcludePatterns = (allCollections: CollectionConfig[]): string[] => {\n const patterns: string[] = [];\n for (const collection of relationalCollections(allCollections)) {\n const spec = buildSearchColumnSpec(collection);\n if (!spec) continue;\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n const table = getTableName(collection);\n for (const name of searchColumnNames(collection)) {\n patterns.push(`${schema}.${table}.${name}`);\n }\n for (const index of searchIndexNames(spec)) {\n patterns.push(`${schema}.${table}.${index}`);\n }\n }\n return patterns;\n};\n\n/**\n * Everything a `{ type: \"vector\" }` property needs, as a file Rebase applies\n * itself.\n *\n * Vector is the second part of the schema Atlas does not own, and it is out for\n * a narrower reason than search: not that Atlas refuses to parse the file, but\n * that it cannot *execute* it. To compute a desired state Atlas materialises\n * `schema.sql` in a dev database, that database is created empty, and Atlas\n * empties it again at the start of every run — so `VECTOR(384)` resolves\n * against a database that structurally cannot have pgvector, and every push\n * dies with `type \"vector\" does not exist`. Seeding the extension beforehand\n * does not survive the clean (measured: present before the run, gone after),\n * putting `CREATE EXTENSION` in `schema.sql` is refused as an Atlas Pro\n * feature, and `--exclude` alone cannot help because Atlas still parses and\n * applies the whole file.\n *\n * So the column, its ANN indexes and the extension are excluded from Atlas's\n * view ({@link vectorExcludePatterns}) and applied from here — the same\n * arrangement search and the RLS policies already use.\n *\n * `CREATE EXTENSION` appears only when the project's database named `vector` in\n * its `extensions` — see `DatabaseOptions.extensions`. Everything else is\n * emitted either way: a database that already has pgvector installed by hand\n * needs no permission from anyone, and one that does not gets the column\n * refused by Postgres with a message this repo makes name the opt-in.\n *\n * Ordered as it must run: the extension, then the drift guard, then the column\n * whose type needs the extension, then the indexes over that column. Every\n * statement is `IF NOT EXISTS`, because this is replayed on every push and\n * appended to migrations that run against databases at any stage of their life.\n * Empty when no collection declares a vector — the caller writes no file then.\n */\nexport const generatePostgresVectorDdl = (\n allCollections: CollectionConfig[],\n options: { extensions?: readonly string[] } = {}\n): string => {\n const collections = relationalCollections(allCollections);\n const withVectors = collections.filter(c => buildVectorColumnSpecs(c, resolveColumnName).length > 0);\n if (withVectors.length === 0) return \"\";\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\";\n ddl += \"--\\n\";\n ddl += \"-- Vector columns and their ANN indexes, for the collections declaring a\\n\";\n ddl += \"-- `vector` property. Applied by Rebase, not by Atlas — see\\n\";\n ddl += \"-- generatePostgresVectorDdl.\\n\\n\";\n // The note is not decoration. Someone reading this file after a failed push\n // is looking for the reason the type does not exist, and \"no CREATE\n // EXTENSION here\" is invisible unless it is written down.\n ddl += vectorExtensionDeclared(options.extensions)\n ? `${vectorExtensionStatement()}\\n\\n`\n : `-- pgvector is not installed from here: no database declared it. To let Rebase\\n` +\n `-- install it, add ${VECTOR_EXTENSION_OPT_IN} in config/resources.ts.\\n` +\n `-- Otherwise install it once by hand; the column below needs the type either way.\\n\\n`;\n\n for (const collection of withVectors) {\n const table = `\"${isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\"}\".\"${getTableName(collection)}\"`;\n for (const spec of buildVectorColumnSpecs(collection, resolveColumnName)) {\n // Guard before the ADD, so a changed `dimensions` is reported rather\n // than skipped over — see `vectorDimensionGuard`.\n ddl += `${vectorDimensionGuard(spec)}\\n`;\n // ADD COLUMN IF NOT EXISTS rather than the inline definition the\n // CREATE TABLE would use: by the time this runs the table exists,\n // whether Atlas just created it or it has been live for a year.\n ddl += `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${vectorColumnDefinition(spec)};\\n`;\n }\n const plan = buildVectorIndexPlan(collection, resolveColumnName);\n vectorIndexStatements(plan).forEach(s => { ddl += `${s}\\n`; });\n for (const skip of plan.skipped) {\n ddl += `-- No ANN index on \"${skip.schema}\".\"${skip.table}\".\"${skip.column}\": ${skip.reason}\\n`;\n }\n ddl += \"\\n\";\n }\n\n return ddl;\n};\n\n/**\n * Glob patterns telling Atlas to leave the vector column and its ANN indexes\n * alone.\n *\n * Without these, a desired state that omits the column reads to Atlas as an\n * instruction to drop it, taking the embeddings and the indexes with it on the\n * next push.\n *\n * Fully qualified, `schema.table.object`, for the reason spelled out on\n * {@link searchExcludePatterns}: the two-part form matches nothing and reports\n * no error, which turns a protection into a `DROP COLUMN`.\n */\nexport const vectorExcludePatterns = (allCollections: CollectionConfig[]): string[] => {\n const patterns: string[] = [];\n for (const collection of relationalCollections(allCollections)) {\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n const table = getTableName(collection);\n for (const name of vectorObjectNames(collection, resolveColumnName)) {\n patterns.push(`${schema}.${table}.${name}`);\n }\n }\n return patterns;\n};\n\nexport const generatePostgresDdl = async (\n allCollections: CollectionConfig[],\n options: { includePolicies?: boolean; includeSearch?: boolean; includeVector?: boolean } = {\n includePolicies: true,\n includeSearch: true,\n includeVector: true\n }\n): Promise<string> => {\n // Only the collections this engine stores. See `relationalCollections`.\n const collections = relationalCollections(allCollections);\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\\n\";\n\n // 1. Create custom schemas.\n //\n // `rebase` is unconditional and load-bearing. The RLS helper functions live\n // in it, so the migration preamble creates it — which puts it in Atlas's\n // replayed state, and anything in that state but absent from this desired\n // schema gets a `DROP SCHEMA … CASCADE` planned against it. That would take\n // the auth tables. It used to appear here only when some collection\n // happened to declare `schema: \"rebase\"`; the scaffold's users collection\n // does, which is why nobody hit it, but nothing guaranteed it.\n const uniqueSchemas = Array.from(new Set([\n REBASE_SCHEMA,\n ...collections.map(c => isPostgresCollectionConfig(c) ? c.schema : undefined).filter(Boolean)\n ]));\n uniqueSchemas.forEach(schema => {\n if (schema) ddl += `CREATE SCHEMA IF NOT EXISTS \"${schema}\";\\n`;\n });\n if (uniqueSchemas.length > 0) ddl += \"\\n\";\n\n // 1b. Search support, for collections that opted in.\n //\n // Extensions and helper functions come before every CREATE TABLE because a\n // generated column's expression is resolved at creation time: a table whose\n // search column calls `rebase_search_text` cannot be created before that\n // function exists. Both are `IF NOT EXISTS` / `OR REPLACE`, so a file\n // replayed against a live database is a no-op here.\n const searchSpecs = collections\n .map(c => buildSearchColumnSpec(c))\n .filter((s): s is SearchColumnSpec => s !== undefined);\n\n if (searchSpecs.length > 0) {\n if (options.includeSearch === false) {\n // Everything search-related lives in `search.sql` — see\n // `generatePostgresSearchDdl` for why Atlas is not shown any of it.\n ddl += \"-- Full-text search support lives in `search.sql`, applied separately.\\n\\n\";\n } else {\n const extensions = Array.from(new Set(searchSpecs.flatMap(searchExtensionStatements)));\n const helpers = Array.from(new Set(searchSpecs.flatMap(searchHelperFunctions)));\n ddl += \"-- Full-text search support (collections declaring a `search` block)\\n\";\n extensions.forEach(s => { ddl += `${s}\\n`; });\n if (extensions.length > 0) ddl += \"\\n\";\n helpers.forEach(s => { ddl += `${s}\\n\\n`; });\n }\n }\n\n // 1c. Vector support, for collections that declared a `vector` property.\n //\n // Only a note, never a statement — unlike 1b, which emits search's\n // extensions when they are included. `CREATE EXTENSION vector` is the one\n // thing this file must never carry whichever way the flag goes: Atlas\n // rejects an extension in a desired state as a paid feature. The note is\n // for whoever opens the generated file looking for the column.\n if (options.includeVector === false\n && collections.some(c => buildVectorColumnSpecs(c, resolveColumnName).length > 0)) {\n ddl += \"-- Vector columns and their ANN indexes live in `vector.sql`, applied separately.\\n\\n\";\n }\n\n // 2. Generate Enums\n //\n // The enum type name is derived from table + column, so two collections\n // mapped onto the same table — or two properties whose `columnName`\n // resolves to the same column — land on the same name. `CREATE TYPE` has no\n // IF NOT EXISTS, so emitting it twice aborts the whole file on the second\n // statement. Dedupe by name, matching planCollectionSchemaEnsure.\n const emittedEnums = new Set<string>();\n collections.forEach(collection => {\n const collectionTable = getTableName(collection);\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n Object.entries(collection.properties ?? {}).forEach(([propName, prop]) => {\n if ((\"enum\" in prop) && (prop.type === \"string\" || prop.type === \"number\") && prop.enum) {\n const enumDbName = `${collectionTable}_${resolveColumnName(propName, prop)}`;\n const values = Array.isArray(prop.enum)\n ? (prop.enum as (string | number | { id: string | number })[]).map((v: string | number | { id: string | number }) =>\n String(typeof v === \"object\" && v !== null && \"id\" in v ? v.id : v)\n )\n : Object.keys(prop.enum);\n if (values.length > 0 && !emittedEnums.has(`${schema}.${enumDbName}`)) {\n emittedEnums.add(`${schema}.${enumDbName}`);\n ddl += `CREATE TYPE \"${schema}\".\"${enumDbName}\" AS ENUM (${values.map(quoteSqlLiteral).join(\", \")});\\n`;\n }\n }\n });\n });\n if (ddl.endsWith(\";\\n\")) ddl += \"\\n\";\n\n // Junction policy derivation needs every declaring side of each junction,\n // not just the first relation that reached it in the walk below.\n const junctionSpecs = resolveJunctionSpecs(collections);\n\n const allTablesToGenerate = new Map<string, {\n collection: CollectionConfig,\n isJunction?: boolean,\n relation?: ResolvedRelation,\n sourceCollection?: CollectionConfig\n }>();\n\n // Identify all tables\n for (const collection of collections) {\n const tableName = getTableName(collection);\n if (tableName) {\n allTablesToGenerate.set(tableName, { collection });\n }\n\n const resolvedRelations = resolveCollectionRelations(collection);\n for (const relation of Object.values(resolvedRelations)) {\n if (isManyToMany(relation)) {\n const junctionTableName = relation.through.table;\n if (!allTablesToGenerate.has(junctionTableName)) {\n allTablesToGenerate.set(junctionTableName, {\n collection: {\n table: junctionTableName,\n properties: {}\n } as CollectionConfig,\n isJunction: true,\n relation: relation,\n sourceCollection: collection\n });\n }\n }\n }\n }\n\n // 3. Generate tables\n const fkStatements: string[] = [];\n // Indexes follow the tables for the same reason the FK constraints do: the\n // table has to exist first.\n const indexStatements: string[] = [];\n // Policies are emitted after every CREATE TABLE, like the FK constraints:\n // a policy may reference other tables (a junction's derived policies always\n // reference both endpoints; `policy.existsIn` references a join table), and\n // CREATE POLICY validates those relations at creation time.\n const policyStatements: string[] = [];\n for (const [tableName, {\n collection,\n isJunction,\n relation,\n sourceCollection\n }] of allTablesToGenerate.entries()) {\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n const baseTableName = tableName.includes(\".\") ? tableName.split(\".\").pop()! : tableName;\n\n if (isJunction && relation && sourceCollection && isManyToMany(relation)) {\n const targetCollection = relation.target();\n const sourceTable = getTableName(sourceCollection);\n const targetTable = getTableName(targetCollection);\n const sourceSchema = isPostgresCollectionConfig(sourceCollection) && sourceCollection.schema ? sourceCollection.schema : \"public\";\n const targetSchema = isPostgresCollectionConfig(targetCollection) && targetCollection.schema ? targetCollection.schema : \"public\";\n const { sourceColumn, targetColumn } = relation.through;\n\n // TEXT, matching the string default: a junction column has to have the\n // same type as the primary key it references.\n const sourceColType = isNumericId(sourceCollection) ? \"INTEGER\" : (getPrimaryKeyProp(sourceCollection).isUuid ? \"UUID\" : \"TEXT\");\n const targetColType = isNumericId(targetCollection) ? \"INTEGER\" : (getPrimaryKeyProp(targetCollection).isUuid ? \"UUID\" : \"TEXT\");\n const sourceId = getPrimaryKeyName(sourceCollection);\n const targetId = getPrimaryKeyName(targetCollection);\n\n const onDelete = relation.onDelete ?? \"CASCADE\";\n\n ddl += `CREATE TABLE \"${schema}\".\"${baseTableName}\" (\\n`;\n ddl += ` \"${sourceColumn}\" ${sourceColType} NOT NULL,\\n`;\n ddl += ` \"${targetColumn}\" ${targetColType} NOT NULL,\\n`;\n ddl += ` PRIMARY KEY (\"${sourceColumn}\", \"${targetColumn}\")\\n`;\n ddl += `);\\n\\n`;\n\n fkStatements.push(`ALTER TABLE \"${schema}\".\"${baseTableName}\" ADD CONSTRAINT \"${toPostgresIdentifier(`${baseTableName}_${sourceColumn}_fkey`)}\" FOREIGN KEY (\"${sourceColumn}\") REFERENCES \"${sourceSchema}\".\"${sourceTable}\" (\"${sourceId}\") ON DELETE ${onDelete.toUpperCase()};`);\n fkStatements.push(`ALTER TABLE \"${schema}\".\"${baseTableName}\" ADD CONSTRAINT \"${toPostgresIdentifier(`${baseTableName}_${targetColumn}_fkey`)}\" FOREIGN KEY (\"${targetColumn}\") REFERENCES \"${targetSchema}\".\"${targetTable}\" (\"${targetId}\") ON DELETE ${onDelete.toUpperCase()};`);\n\n if (options.includePolicies) {\n // Junction tables are generated tables like any other: locked by\n // default, with derived policies — reads follow the endpoints'\n // visibility, writes follow the declaring side's update rules.\n // Without this they were the one kind of generated table with no\n // RLS at all, readable and writable by every signed-in user.\n ddl += `ALTER TABLE \"${schema}\".\"${baseTableName}\" ENABLE ROW LEVEL SECURITY;\\n`;\n ddl += `\\n`;\n\n const spec = junctionSpecs.get(baseTableName);\n if (spec) {\n const junctionCollection = getJunctionCollectionConfig(spec);\n const resolveCollection: ResolveCollection = (slug) => collections.find(c => c.slug === slug || getTableName(c) === slug);\n getJunctionSecurityRules(spec).forEach((rule: SecurityRule) => {\n policyStatements.push(generatePolicyDdl(junctionCollection, rule, resolveCollection));\n });\n }\n }\n } else if (!isJunction) {\n ddl += `CREATE TABLE \"${schema}\".\"${baseTableName}\" (\\n`;\n const columns: string[] = [];\n\n Object.entries(collection.properties ?? {}).forEach(([propName, prop]) => {\n // A vector column is not Atlas's — `vector.sql` adds it. Skipped\n // here rather than filtered upstream so the column keeps its\n // place in the generator's order when it *is* included, which is\n // what the derived-names contract renders.\n if (prop.type === \"vector\" && options.includeVector === false) {\n return;\n }\n if (prop.type === \"relation\") {\n const refProp = prop as RelationProperty;\n const resolvedRelations = resolveCollectionRelations(collection);\n const relInfo = findRelation(resolvedRelations, refProp.relation?.relationName ?? propName);\n\n if (relInfo?.kind !== \"belongsTo\") {\n return;\n }\n\n if (collection.properties[relInfo.localKey] && propName !== relInfo.localKey) {\n return;\n }\n\n let targetCollection: CollectionConfig;\n try {\n targetCollection = relInfo.target();\n } catch {\n return;\n }\n\n const targetTable = getTableName(targetCollection);\n const targetSchema = isPostgresCollectionConfig(targetCollection) && targetCollection.schema ? targetCollection.schema : \"public\";\n const targetId = getPrimaryKeyName(targetCollection);\n const fkColType = getSqlColumnType(propName, prop, collection, collections);\n \n const onUpdate = relInfo.onUpdate ? ` ON UPDATE ${relInfo.onUpdate.toUpperCase()}` : \"\";\n const required = prop.validation?.required;\n const onDeleteVal = relInfo.onDelete ?? defaultBelongsToOnDelete(required);\n \n let colDef = ` \"${relInfo.localKey}\" ${fkColType}`;\n if (required) colDef += \" NOT NULL\";\n columns.push(colDef);\n\n fkStatements.push(`ALTER TABLE \"${schema}\".\"${baseTableName}\" ADD CONSTRAINT \"${toPostgresIdentifier(`${baseTableName}_${relInfo.localKey}_fkey`)}\" FOREIGN KEY (\"${relInfo.localKey}\") REFERENCES \"${targetSchema}\".\"${targetTable}\" (\"${targetId}\") ON DELETE ${onDeleteVal.toUpperCase()}${onUpdate};`);\n } else if (prop.type === \"reference\") {\n const refProp = prop as ReferenceProperty;\n const targetCollection = collections.find(c => c.slug === refProp.path || getTableName(c) === refProp.path);\n const colName = resolveColumnName(propName, prop);\n const colType = getSqlColumnType(propName, prop, collection, collections);\n const required = prop.validation?.required;\n\n if (!targetCollection) {\n let colDef = ` \"${colName}\" ${colType}`;\n if (required) colDef += \" NOT NULL\";\n columns.push(colDef);\n } else {\n const targetTable = getTableName(targetCollection);\n const targetSchema = isPostgresCollectionConfig(targetCollection) && targetCollection.schema ? targetCollection.schema : \"public\";\n const targetId = getPrimaryKeyName(targetCollection);\n // The same rule as `belongsTo`, from the same function.\n // A `reference` is a foreign key like any other, and it\n // carries no `onDelete` of its own to override it with.\n const onDelete = defaultBelongsToOnDelete(required);\n\n let colDef = ` \"${colName}\" ${colType}`;\n if (required) colDef += \" NOT NULL\";\n columns.push(colDef);\n\n fkStatements.push(`ALTER TABLE \"${schema}\".\"${baseTableName}\" ADD CONSTRAINT \"${toPostgresIdentifier(`${baseTableName}_${colName}_fkey`)}\" FOREIGN KEY (\"${colName}\") REFERENCES \"${targetSchema}\".\"${targetTable}\" (\"${targetId}\") ON DELETE ${onDelete.toUpperCase()};`);\n }\n } else {\n const colName = resolveColumnName(propName, prop);\n\n // On an auth collection, the columns auth reads and writes\n // are defined once, in `auth-users-columns`, and every\n // creator of this table emits that definition. Before this,\n // the desired state here was built from the collection file\n // alone — which knows nothing of `is_anonymous` or\n // `tokens_valid_after` — so `db push` and the runtime\n // disagreed about `email`'s nullability and about which\n // columns exist at all.\n const authDefinition = isAuthCollection(collection)\n ? authUsersColumnDefinition(colName)\n : undefined;\n if (authDefinition && !isIdProperty(propName, prop, collection)) {\n columns.push(` \"${colName}\" ${authDefinition}`);\n return;\n }\n\n const colType = getSqlColumnType(propName, prop, collection, collections);\n let colDef = ` \"${colName}\" ${colType}`;\n\n if (isIdProperty(propName, prop, collection)) {\n colDef += \" PRIMARY KEY\";\n }\n\n if (\"isId\" in prop && prop.isId !== \"manual\" && prop.isId !== true && prop.isId !== \"increment\") {\n if (prop.isId === \"uuid\") {\n colDef += \" DEFAULT gen_random_uuid()\";\n } else if (prop.isId === \"cuid\") {\n colDef += \" DEFAULT cuid()\";\n } else if (typeof prop.isId === \"string\") {\n colDef += ` DEFAULT ${prop.isId}`;\n }\n }\n\n if (!isIdProperty(propName, prop, collection) && prop.validation?.unique) {\n colDef += \" UNIQUE\";\n }\n\n if (prop.type === \"date\") {\n const dateProp = prop as DateProperty;\n if (dateProp.autoValue === \"on_create\" || dateProp.autoValue === \"on_update\") {\n colDef += \" DEFAULT now()\";\n }\n }\n\n if (prop.validation?.required && !colDef.includes(\"PRIMARY KEY\")) {\n colDef += \" NOT NULL\";\n }\n\n columns.push(colDef);\n }\n });\n\n // ── Auth columns the collection file never mentions ──────────────\n // `db push` is declarative: Atlas diffs the database against exactly\n // what is emitted here and drops anything else. The scaffold's users\n // collection describes 12 columns while auth needs 14, so\n // `is_anonymous` and `tokens_valid_after` — created at boot by\n // `ensureAuthTablesExist` — read as unmanaged drift, and a push run\n // after the server had started once planned to DROP them. The\n // destructive gate catches it, which makes it a data-loss prompt on\n // the auth table rather than silent damage; either way the desired\n // state was wrong. Emit the full contract so the two agree.\n if (isAuthCollection(collection)) {\n const declared = new Set(\n Object.entries(collection.properties ?? {})\n .map(([name, prop]) => resolveColumnName(name, prop))\n );\n for (const spec of AUTH_USERS_COLUMNS) {\n if (declared.has(spec.column)) continue;\n columns.push(` \"${spec.column}\" ${authUsersColumnSql(spec)}`);\n }\n }\n\n // ── The opt-in search column ─────────────────────────────────────\n // Last, so it reads as what it is: derived from the columns above\n // it. Postgres recomputes it on every write of a source column and\n // rejects any attempt to write it directly, which is the property\n // that makes it impossible for the index to drift from the row.\n const searchSpec = options.includeSearch === false ? undefined : buildSearchColumnSpec(collection);\n if (searchSpec) {\n columns.push(` ${searchColumnDefinition(searchSpec)}`);\n const fuzzyDef = fuzzyColumnDefinition(searchSpec);\n if (fuzzyDef) columns.push(` ${fuzzyDef}`);\n indexStatements.push(...searchIndexStatements(searchSpec));\n }\n\n // ANN indexes for vector columns. Emitted with the other indexes\n // rather than inline, because `CREATE INDEX` is a statement and a\n // column definition is not — and because a column too wide for\n // pgvector to index still needs its column.\n //\n // Absent alongside their column when vector is carved out: an index\n // over a column this file no longer declares would not resolve, and\n // `USING hnsw` needs the extension the dev database cannot have.\n if (options.includeVector !== false) {\n const vectorPlan: VectorIndexPlan = buildVectorIndexPlan(collection, resolveColumnName);\n indexStatements.push(...vectorIndexStatements(vectorPlan));\n for (const skip of vectorPlan.skipped) {\n indexStatements.push(`-- No ANN index on \"${skip.schema}\".\"${skip.table}\".\"${skip.column}\": ${skip.reason}`);\n }\n }\n\n // The collection's own `indexes:` block. Last of the three index\n // producers, and the only one the developer wrote deliberately\n // rather than getting as a side effect of another feature.\n indexStatements.push(...collectionIndexStatements(\n buildCollectionIndexSpecs(collection, resolveColumnName)\n ));\n\n // The implicit primary key, for a collection that declares none.\n const hasPk = columns.some(c => c.includes(\"PRIMARY KEY\"));\n if (!hasPk) {\n columns.unshift(' \"id\" TEXT PRIMARY KEY');\n }\n\n ddl += columns.join(\",\\n\");\n ddl += `\\n);\\n\\n`;\n\n if (options.includePolicies) {\n // Enable RLS and add Policies. No FORCE: authenticated requests\n // run as the non-owner `rebase_user` role, which plain ENABLE\n // already binds. The owner (server context) must bypass — it is\n // the trusted plane (auth flows, dataAsAdmin).\n ddl += `ALTER TABLE \"${schema}\".\"${baseTableName}\" ENABLE ROW LEVEL SECURITY;\\n`;\n ddl += `\\n`;\n\n const securityRules = getEffectiveSecurityRules(collection);\n if (securityRules.length > 0) {\n const resolveCollection: ResolveCollection = (slug) => collections.find(c => c.slug === slug || getTableName(c) === slug);\n securityRules.forEach((rule: SecurityRule) => {\n policyStatements.push(generatePolicyDdl(collection, rule, resolveCollection));\n });\n }\n }\n }\n }\n\n // Indexes before foreign keys. Today every FK targets a primary key created\n // inline, so the order is safe by accident; the moment a declared\n // `unique: true` index can back an FK target, a constraint emitted first\n // would reference an index that does not exist yet.\n if (indexStatements.length > 0) {\n ddl += \"-- Indexes\\n\";\n ddl += indexStatements.join(\"\\n\") + \"\\n\\n\";\n }\n\n if (fkStatements.length > 0) {\n ddl += \"-- Foreign Key Constraints\\n\";\n ddl += fkStatements.join(\"\\n\") + \"\\n\\n\";\n }\n\n if (policyStatements.length > 0) {\n ddl += \"-- Row Level Security Policies\\n\";\n ddl += policyStatements.join(\"\");\n ddl += \"\\n\";\n }\n\n return ddl;\n};\n\n/** The RLS statements one declared collection's table needs, ready to run. */\n/**\n * A foreign key, as both its parts and the statement that creates it.\n *\n * `ALTER TABLE … ADD CONSTRAINT` has no `IF NOT EXISTS`, so a caller applying\n * these has to skip by name — hence the name is a field and not only a substring\n * of the SQL.\n */\nexport interface ForeignKeyPlan {\n constraintName: string;\n schema: string;\n /** Bare table name, no schema prefix. */\n table: string;\n column: string;\n targetSchema: string;\n targetTable: string;\n targetColumn: string;\n sql: string;\n}\n\n/** A column a `relation` or `reference` property owns on its own table. */\nexport interface RelationalColumnPlan {\n schema: string;\n /** Bare table name, no schema prefix. */\n table: string;\n column: string;\n /** Postgres type, exactly as the DDL generator declares it. */\n type: string;\n /** Absent when the target collection is not part of this bundle. */\n foreignKey?: ForeignKeyPlan;\n /**\n * What this column would have been called before `generateForeignKeyName`\n * learned to singularize — set only when the two differ and the column name\n * is the derived default rather than one the author wrote.\n *\n * Carried so the boot-time ensure can notice a database provisioned under\n * the old rule. It is never used to name anything.\n */\n legacyColumn?: string;\n}\n\n/** The table behind a many-to-many `through` relation. */\nexport interface JunctionTablePlan {\n schema: string;\n /** Bare table name, no schema prefix. */\n table: string;\n columns: { name: string; type: string; legacyName?: string }[];\n /** Both endpoint columns plus the composite primary key. */\n createTable: string;\n foreignKeys: ForeignKeyPlan[];\n}\n\nconst schemaOfCollection = (collection: CollectionConfig): string =>\n isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n\nconst bareTableName = (name: string): string => (name.includes(\".\") ? name.split(\".\").pop()! : name);\n\n/**\n * Truncate a derived identifier the way Postgres does: to 63 bytes, silently.\n *\n * This is not cosmetic, and not really a naming choice at all — it is agreeing\n * with the name the database ALREADY stored. `ADD CONSTRAINT` on a longer name\n * succeeds and records the truncated form, so the untruncated name this used to\n * derive matched nothing in the catalogue. Boot-ensure compares its planned\n * constraints against `readExistingSchema`, which reads catalogue names, so the\n * comparison could never hit: every boot re-issued `ADD CONSTRAINT` for the same\n * constraint, forever, and got \"already exists\" every time. Non-fatal (foreign\n * keys are the one action allowed to fail) and therefore permanent — an error in\n * the log on every restart of a project whose table and column names happened to\n * be long.\n *\n * Byte length, not string length: NAMEDATALEN is 64 bytes, and a multi-byte\n * character straddling the boundary would be cut mid-sequence by `slice(0, 63)`.\n */\n// Moved to `@rebasepro/utils` so the search-column builder derives index names\n// under the same 63-byte rule this file derives constraint names under. Two\n// copies of a truncation rule is two rules the moment one of them is edited.\n\nconst foreignKeyPlan = (\n args: Omit<ForeignKeyPlan, \"constraintName\" | \"sql\"> & { onDelete: string; onUpdate?: string }\n): ForeignKeyPlan => {\n const constraintName = toPostgresIdentifier(`${args.table}_${args.column}_fkey`);\n const onUpdate = args.onUpdate ? ` ON UPDATE ${args.onUpdate.toUpperCase()}` : \"\";\n return {\n constraintName,\n schema: args.schema,\n table: args.table,\n column: args.column,\n targetSchema: args.targetSchema,\n targetTable: args.targetTable,\n targetColumn: args.targetColumn,\n sql:\n `ALTER TABLE \"${args.schema}\".\"${args.table}\" ADD CONSTRAINT \"${constraintName}\" ` +\n `FOREIGN KEY (\"${args.column}\") REFERENCES \"${args.targetSchema}\".\"${args.targetTable}\" ` +\n `(\"${args.targetColumn}\") ON DELETE ${args.onDelete.toUpperCase()}${onUpdate};`\n };\n};\n\n/**\n * The FK columns the declared collections own — one entry per `relation`\n * (`belongsTo` side) or `reference` property.\n *\n * Split out of {@link generatePostgresDdl} so the boot-time schema ensure can\n * create the same columns with the same names, types and constraints. Before\n * this it skipped them outright, which was survivable only because `db push`\n * always followed; on a managed tenant nothing follows, so a table arrived\n * without the column its own collection reads and wrote 400 on every insert.\n *\n * A relation whose target is not in the bundle yields no column at all (the\n * generator returns early on an unresolvable target); a `reference` whose target\n * is unknown yields the column without a constraint. Both mirror the generator\n * exactly — a divergence here is a schema fork between boot and `db push`.\n */\nexport const planRelationalColumns = (allCollections: CollectionConfig[]): RelationalColumnPlan[] => {\n const collections = relationalCollections(allCollections);\n const plans: RelationalColumnPlan[] = [];\n\n for (const collection of collections) {\n const tableName = getTableName(collection);\n if (!tableName) continue;\n const schema = schemaOfCollection(collection);\n const table = bareTableName(tableName);\n\n for (const [propName, rawProp] of Object.entries(collection.properties ?? {})) {\n const prop = rawProp as Property;\n\n if (prop.type === \"relation\") {\n const refProp = prop as RelationProperty;\n const resolvedRelations = resolveCollectionRelations(collection);\n const relInfo = findRelation(resolvedRelations, refProp.relation?.relationName ?? propName);\n if (relInfo?.kind !== \"belongsTo\") continue;\n // The relation and an explicit FK property can both be declared;\n // the explicit one owns the column.\n if (collection.properties[relInfo.localKey] && propName !== relInfo.localKey) continue;\n\n let targetCollection: CollectionConfig;\n try {\n targetCollection = relInfo.target();\n } catch {\n continue;\n }\n if (!targetCollection) continue;\n\n const required = prop.validation?.required;\n // Only a *derived* column name can be affected by the change to\n // `generateForeignKeyName`; one the author wrote is theirs.\n const relationName = refProp.relation?.relationName ?? propName;\n const legacyKey = legacyForeignKeyName(relationName);\n const derived = relInfo.localKey === generateForeignKeyName(relationName);\n plans.push({\n schema,\n table,\n column: relInfo.localKey,\n legacyColumn: derived && legacyKey !== relInfo.localKey ? legacyKey : undefined,\n type: getSqlColumnType(propName, prop, collection, collections),\n foreignKey: foreignKeyPlan({\n schema,\n table,\n column: relInfo.localKey,\n targetSchema: schemaOfCollection(targetCollection),\n targetTable: bareTableName(getTableName(targetCollection)),\n targetColumn: getPrimaryKeyName(targetCollection),\n onDelete: relInfo.onDelete ?? defaultBelongsToOnDelete(required),\n onUpdate: relInfo.onUpdate\n })\n });\n } else if (prop.type === \"reference\") {\n const refProp = prop as ReferenceProperty;\n const targetCollection = collections.find(\n c => c.slug === refProp.path || getTableName(c) === refProp.path\n );\n const column = resolveColumnName(propName, prop);\n const type = getSqlColumnType(propName, prop, collection, collections);\n const required = prop.validation?.required;\n\n plans.push({\n schema,\n table,\n column,\n type,\n foreignKey: targetCollection\n ? foreignKeyPlan({\n schema,\n table,\n column,\n targetSchema: schemaOfCollection(targetCollection),\n targetTable: bareTableName(getTableName(targetCollection)),\n targetColumn: getPrimaryKeyName(targetCollection),\n // Same rule, same function as the `CREATE TABLE`\n // path above — a default that appears in one and not\n // the other makes `db push` plan a constraint\n // rewrite on every run.\n onDelete: defaultBelongsToOnDelete(required)\n })\n : undefined\n });\n }\n }\n }\n\n return plans;\n};\n\n/**\n * The junction tables a bundle's many-to-many relations imply.\n *\n * Derived from {@link resolveJunctionSpecs}, the same source the junction RLS\n * comes from, so a table created here always has policies planned for it — a\n * junction with row-level security left off is readable and writable by every\n * signed-in user, which is why the two must ship together.\n */\nexport const planJunctionTables = (allCollections: CollectionConfig[]): JunctionTablePlan[] => {\n const collections = relationalCollections(allCollections);\n const plans: JunctionTablePlan[] = [];\n\n for (const spec of resolveJunctionSpecs(collections).values()) {\n const [source, target] = spec.endpoints;\n // A junction column's default name is derived from the endpoint\n // collection's slug — which is normally plural, so this is where the\n // singularization change actually lands: a `categories` endpoint used\n // to give `categorie_id` and now gives `category_id`. Recorded, not\n // used, so boot-ensure can recognise a table built under the old rule.\n const legacyFor = (endpoint: typeof source): string | undefined => {\n const slug = toSnakeCase(endpoint.collection.slug ?? endpoint.collection.name ?? \"\");\n const legacy = legacyForeignKeyName(slug);\n const derived = endpoint.junctionColumn === generateForeignKeyName(slug);\n return derived && legacy !== endpoint.junctionColumn ? legacy : undefined;\n };\n const columns = [\n { name: source.junctionColumn, type: junctionKeyType(source.collection), legacyName: legacyFor(source) },\n { name: target.junctionColumn, type: junctionKeyType(target.collection), legacyName: legacyFor(target) }\n ];\n // Every declaring side agrees on the edge's lifetime; the first one wins,\n // as it does in the generator's walk.\n const onDelete = spec.declaringSides[0]?.relation.onDelete ?? \"CASCADE\";\n\n plans.push({\n schema: spec.schema,\n table: spec.table,\n columns,\n createTable:\n `CREATE TABLE IF NOT EXISTS \"${spec.schema}\".\"${spec.table}\" (` +\n columns.map(c => `\"${c.name}\" ${c.type} NOT NULL`).join(\", \") +\n `, PRIMARY KEY (${columns.map(c => `\"${c.name}\"`).join(\", \")}));`,\n foreignKeys: [source, target].map((endpoint, i) =>\n foreignKeyPlan({\n schema: spec.schema,\n table: spec.table,\n column: columns[i].name,\n targetSchema: schemaOfCollection(endpoint.collection),\n targetTable: bareTableName(getTableName(endpoint.collection)),\n targetColumn: getPrimaryKeyName(endpoint.collection),\n onDelete\n })\n )\n });\n }\n\n return plans;\n};\n\nexport interface CollectionPolicyPlan {\n /** The table's schema (e.g. `public`, `rebase`). */\n schema: string;\n /** The bare table name, no schema prefix. */\n table: string;\n /** `schema.table` — matches the keys `readExistingSchema` returns. */\n qualified: string;\n /** `ALTER TABLE … ENABLE ROW LEVEL SECURITY;` — locked by default. */\n enableRls: string;\n /** `DROP POLICY IF EXISTS` / `CREATE POLICY` statements, in order. */\n policyStatements: string[];\n}\n\n/**\n * The per-table RLS plan for the *declared* collections, as executable\n * statements — what the managed runtime applies at boot so a freshly\n * provisioned tenant database serves data instead of 401ing every read.\n *\n * Mirrors {@link generatePostgresPoliciesDdl} exactly (same\n * `generatePolicyStatements`, same enable-RLS, same effective rules, same\n * derived junction rules), so boot and `db push` produce identical policies from\n * identical collections.\n *\n * Junction tables are included, and have to be: boot creates them now\n * ({@link planJunctionTables}), and a junction with RLS left off is readable and\n * writable by every signed-in user. A junction whose table is still absent is\n * skipped by the applier, not planned away here.\n */\nexport const planCollectionPolicies = (allCollections: CollectionConfig[]): CollectionPolicyPlan[] => {\n // A store with no RLS gets no policies planned for it — `supportsRLS` is\n // false for exactly the engines `relationalCollections` filters out.\n const collections = relationalCollections(allCollections);\n const resolveCollection: ResolveCollection = (slug) => collections.find(c => c.slug === slug || getTableName(c) === slug);\n const plans: CollectionPolicyPlan[] = [];\n const seen = new Set<string>();\n\n for (const collection of collections) {\n const tableName = getTableName(collection);\n if (!tableName) continue;\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n const baseTableName = tableName.includes(\".\") ? tableName.split(\".\").pop()! : tableName;\n const qualified = `${schema}.${baseTableName}`;\n if (seen.has(qualified)) continue;\n seen.add(qualified);\n\n const policyStatements: string[] = [];\n for (const rule of getEffectiveSecurityRules(collection)) {\n policyStatements.push(...generatePolicyStatements(collection, rule, resolveCollection));\n }\n\n plans.push({\n schema,\n table: baseTableName,\n qualified,\n enableRls: `ALTER TABLE \"${schema}\".\"${baseTableName}\" ENABLE ROW LEVEL SECURITY;`,\n policyStatements\n });\n }\n\n // Junctions are derived from `through` relations rather than declared, so\n // the walk above never sees them.\n for (const spec of resolveJunctionSpecs(collections).values()) {\n const qualified = `${spec.schema}.${spec.table}`;\n if (seen.has(qualified)) continue;\n seen.add(qualified);\n\n const junctionCollection = getJunctionCollectionConfig(spec);\n const policyStatements: string[] = [];\n for (const rule of getJunctionSecurityRules(spec)) {\n policyStatements.push(...generatePolicyStatements(junctionCollection, rule, resolveCollection));\n }\n\n plans.push({\n schema: spec.schema,\n table: spec.table,\n qualified,\n enableRls: `ALTER TABLE \"${spec.schema}\".\"${spec.table}\" ENABLE ROW LEVEL SECURITY;`,\n policyStatements\n });\n }\n\n return plans;\n};\n\nexport const generatePostgresPoliciesDdl = (allCollections: CollectionConfig[]): string => {\n // Also the expectation `checkPolicyDrift` reconciles the database against,\n // so a non-SQL collection filtered out here is one the drift report cannot\n // invent a missing policy for.\n const collections = relationalCollections(allCollections);\n let ddl = \"-- This file contains RLS policies generated by Rebase. Applied separately from migrations.\\n\\n\";\n\n const allTablesToGenerate = new Map<string, {\n collection: CollectionConfig\n }>();\n\n for (const collection of collections) {\n const tableName = getTableName(collection);\n if (tableName) {\n allTablesToGenerate.set(tableName, { collection });\n }\n }\n\n for (const [tableName, { collection }] of allTablesToGenerate.entries()) {\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n const baseTableName = tableName.includes(\".\") ? tableName.split(\".\").pop()! : tableName;\n\n // No FORCE: user requests run as the non-owner `rebase_user` role\n // (plain ENABLE binds them); the owner is the trusted server context.\n ddl += `ALTER TABLE \"${schema}\".\"${baseTableName}\" ENABLE ROW LEVEL SECURITY;\\n`;\n ddl += `\\n`;\n\n const securityRules = getEffectiveSecurityRules(collection);\n if (securityRules.length > 0) {\n const resolveCollection: ResolveCollection = (slug) => collections.find(c => c.slug === slug || getTableName(c) === slug);\n const injectedNames = new Set(getInjectedSecurityRules(collection).map((rule) => rule.name));\n\n securityRules.forEach((rule: SecurityRule) => {\n // Say which policies the author did not write. They are permissive,\n // so they OR with the declared rules and widen the final ACL beyond\n // what `securityRules` reads like — and re-appear after any manual\n // DROP, because a push asserts the declared state.\n if (rule.name && injectedNames.has(rule.name)) {\n ddl += `-- Injected by Rebase (not from this collection's securityRules).\\n`;\n ddl += `-- Set \\`disableDefaultPolicies: true\\` on \"${collection.slug}\" to drop these and own its RLS outright.\\n`;\n }\n ddl += generatePolicyDdl(collection, rule, resolveCollection);\n });\n ddl += \"\\n\";\n }\n }\n\n // Junction tables are generated from `through` relations, not declared as\n // collections, so the walk above never sees them. They get the same\n // treatment as any generated table: locked by default, with derived\n // policies — reads follow the endpoints, writes follow the declaring\n // side's update rules.\n const junctionSpecs = resolveJunctionSpecs(collections);\n for (const spec of junctionSpecs.values()) {\n ddl += `ALTER TABLE \"${spec.schema}\".\"${spec.table}\" ENABLE ROW LEVEL SECURITY;\\n`;\n ddl += `\\n`;\n\n const junctionRules = getJunctionSecurityRules(spec);\n if (junctionRules.length === 0) continue;\n\n const junctionCollection = getJunctionCollectionConfig(spec);\n const resolveCollection: ResolveCollection = (slug) => collections.find(c => c.slug === slug || getTableName(c) === slug);\n const declaringSlugs = spec.declaringSides.map(s => s.collection.slug).join('\", \"');\n\n ddl += `-- Derived by Rebase for the junction \"${spec.table}\" (no collection declares it).\\n`;\n ddl += `-- Reads require both endpoint rows to be visible; writes follow the update\\n`;\n ddl += `-- rules of \"${declaringSlugs}\". Set \\`disableDefaultPolicies: true\\` on the\\n`;\n ddl += `-- declaring collection(s) to drop these and police the junction yourself.\\n`;\n junctionRules.forEach((rule: SecurityRule) => {\n ddl += generatePolicyDdl(junctionCollection, rule, resolveCollection);\n });\n ddl += \"\\n\";\n }\n\n return ddl;\n};\n\n","/**\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 return a === b;\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 * Bringing a database up to date with a bundle's collections, additively.\n *\n * ## Why this exists\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 * ## 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 * create a missing table, add a missing column, create a missing enum type.\n *\n * It will **never** drop a table or a column, narrow a type, or alter a\n * constraint. A removed field leaves its column behind; a renamed field looks\n * like an addition and the old column stays. That is the correct trade for an\n * automated path — the alternative is an unattended process that can silently\n * destroy a column, which is precisely the failure `db push` was hardened\n * against. Destructive changes stay a deliberate, human-reviewed migration.\n *\n * Because of that, this is safe to run on every boot, and re-running it is a\n * no-op.\n */\nimport {\n declaredDatabaseExtensions,\n isPostgresCollectionConfig,\n type CollectionConfig,\n type Property\n} from \"@rebasepro/types\";\nimport { getTableName, relationalCollections } from \"@rebasepro/common\";\nimport { logger, isConcurrentDdlRace, isDuplicateObjectRace } from \"@rebasepro/server\";\nimport {\n assertSearchIsPostgresOnly,\n buildSearchColumnSpec,\n searchExtensionStatements,\n searchHelperFunctions,\n searchIndexStatements,\n searchColumnStamps,\n SEARCH_STAMP_PREFIX,\n SEARCH_TEXT_FN,\n SEARCH_UNACCENT_FN,\n type SearchColumnSpec\n} from \"./search-column\";\nimport {\n getSqlColumnType,\n resolveColumnName,\n isIdProperty,\n planRelationalColumns,\n planJunctionTables,\n quoteSqlLiteral\n} from \"./generate-postgres-ddl-logic\";\nimport {\n buildVectorColumnSpecs,\n buildVectorIndexPlan,\n vectorExtensionDeclared,\n vectorExtensionHint,\n vectorExtensionStatement,\n vectorIndexStatement,\n type SkippedVectorIndex\n} from \"./vector-index\";\nimport { buildCollectionIndexPlan, collectionIndexStatement } from \"./collection-index\";\nimport { extractCauseMessage, extractPgError } from \"../utils/pg-error-utils\";\nimport { columnTypeDriftMessage, typesAgree, type ColumnTypeDrift } from \"./column-type-drift\";\nimport {\n AUTH_USERS_COLUMNS,\n authUsersColumnDefinition,\n authUsersColumnSql,\n isAuthCollection\n} from \"./auth-users-columns\";\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 against {@link SAFE_IDENTIFIER} before\n * they reach a statement, so a config that somehow carried a quote is refused\n * rather than concatenated.\n */\nexport interface Queryable {\n query<T = unknown>(sql: string): Promise<{ rows: T[] }>;\n}\n\n/** Postgres identifiers this module is willing to interpolate. */\nconst SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;\n\nfunction 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, so it\n * is the only evidence that a `search` block has changed since the column\n * was built. Absent is read as \"no column is stamped\", which plans a stamp\n * and reports nothing as drifted.\n */\n columnComments?: Map<string, string>;\n /**\n * `schema.typename` → the values that type currently holds, in order.\n *\n * Without this, an enum type that already exists is skipped whole and a\n * value added to it never reaches the database — the type is there, so\n * nothing plans anything, and the first row using the new value is rejected\n * by a constraint nobody changed. Absent is read as \"the values are\n * unknown\", which keeps the old skip-by-name behaviour rather than guessing.\n */\n enumValues?: Map<string, string[]>;\n /** `schema.table.column` for every column the database marks NOT NULL. */\n notNullColumns?: Set<string>;\n /**\n * `schema.table.column` → the column's `udt_name` as the database reports\n * it (`int4`, `jsonb`, `_numeric` for an array of numeric).\n *\n * The only evidence that a column's declared type and its real type have\n * parted company. Absent is read as \"unknown\", which reports no drift —\n * see `column-type-drift.ts` for why silence is the right unknown here.\n */\n columnTypes?: Map<string, string>;\n /**\n * Tables known to hold at least one row.\n *\n * The only thing that decides whether a NOT NULL can be added without\n * reading the data: on an empty table the constraint cannot fail, on a\n * populated one it is checked against every existing row. Absent is read as\n * \"assume populated\", which is the conservative direction — it withholds a\n * constraint rather than attempting one that aborts the boot.\n */\n populatedTables?: Set<string>;\n /**\n * `schema.table.column` for every column the database gives a DEFAULT.\n *\n * Paired with {@link notNullColumns} to decide whether a column no property\n * declares can still accept a write: NOT NULL with a default can, NOT NULL\n * without one cannot. Absent is read as \"unknown\", which reports nothing.\n */\n columnDefaults?: 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. That\n * is the context in which changing an existing column's constraints is a\n * reviewed act rather than a surprise.\n */\nexport type ConstraintPolicy = \"additive\" | \"converge\";\n\nexport interface EnsureOptions {\n /** Defaults to `additive`. See {@link ConstraintPolicy}. */\n constraints?: ConstraintPolicy;\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\n * this function is pure and several callers plan against fixtures: reaching\n * for a process-wide registry would make the plan depend on whatever some\n * other module happened to import. `ensureCollectionTables` is the boundary\n * that reads the world.\n */\n databaseExtensions?: readonly string[];\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\";\n /** Qualified target, for logging: `public.posts` or `public.posts.title`. */\n target: string;\n sql: 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 * The reason this is reported rather than silently handled: the ensure is\n * additive, so it would add `category_id` beside a populated\n * `categorie_id` and the relation would then read the new, empty one. No\n * statement fails, no table is missing, and the only symptom is relations\n * resolving to nothing — which is indistinguishable from having no data.\n */\n legacyForeignKeys: LegacyForeignKey[];\n /**\n * Generated search columns whose `search` block has changed since they were\n * built. Reported, never planned into `actions` — see\n * {@link SearchColumnDrift} for why applying it is not this path's call.\n */\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; whether they match the\n * current block cannot be known, which is what the caller reports.\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.\n *\n * Reported rather than thrown: the column is valid, storable and\n * searchable, and refusing the boot over it would make a working\n * configuration unbootable. Reported rather than dropped: an unindexed\n * vector column and an indexed one differ only in latency, so nothing\n * about the running system says which one you got.\n */\n vectorIndexSkipped: SkippedVectorIndex[];\n /**\n * Constraints the configuration asks for that this plan is not applying,\n * and why.\n *\n * This is the half of the feature that matters most. Every one of these was\n * previously withheld in silence: a required property arrived nullable, and\n * the only evidence was a database that disagreed with its own\n * configuration. Reporting them is what lets boot warn, the live editor\n * refuse, and the doctor explain — three surfaces that until now had nothing\n * to read.\n */\n withheldConstraints: WithheldConstraint[];\n /**\n * Columns whose type in the database is in a different family from the one\n * the collection declares.\n *\n * Reported and never acted on — see `column-type-drift.ts`. This is the one\n * divergence that presents as a *working* deploy: the statement was never\n * planned, so nothing failed, and the first evidence is a write rejected\n * hours later by whichever end validates first.\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.\n *\n * This is what a **rename** looks like to an additive provisioner. Rename\n * `title` to `headline` and boot does exactly what it promises: it adds\n * `headline` (nullable, correctly, and says why) and leaves `title` alone,\n * because dropping a column is destructive and this runs unattended. The\n * table is then unwritable:\n *\n * POST /api/data/posts -> 400 PG_23502\n * Missing required field: \"title\" in \"posts\" cannot be empty.\n *\n * naming a field that is no longer in the collection at all. On the default\n * first-run path there is no way out inside the product either: the managed\n * database is PGlite, and `db push` — the documented repair — refuses there\n * because Atlas needs a second database to diff against.\n *\n * Reported, never acted on. Dropping the column is the right fix roughly\n * always and destructive exactly once, which is not a decision to take\n * unattended.\n */\n orphanedRequiredColumns: OrphanedRequiredColumn[];\n}\n\n/**\n * A NOT NULL column with no default that no property declares.\n * @see EnsurePlan.orphanedRequiredColumns\n */\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 — the same\n * reason it withholds `SET NOT NULL` from an adopted table — so a multi-minute\n * outage is not a decision it may take on its own.\n *\n * Not applying it silently is not an option either: that is the bug this\n * detection exists for. A collection that added a field, flipped `unaccent` or\n * raised a weight kept indexing the *old* set forever, and the only symptom was\n * searches returning nothing for content 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 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/**\n * The schema a collection lives in — validated, because it is about to be\n * interpolated into DDL.\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 */\nfunction schemaOf(collection: CollectionConfig): string {\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n return assertSafeIdentifier(schema, \"schema name\");\n}\n\n/** A collection's table name, validated for the same reason as {@link schemaOf}. */\nfunction tableOf(collection: CollectionConfig): string {\n return assertSafeIdentifier(getTableName(collection), \"table name\");\n}\n\nfunction qualified(collection: CollectionConfig): string {\n return `${schemaOf(collection)}.${tableOf(collection)}`;\n}\n\n/**\n * Enum types a collection's properties require, as `schema.typename`.\n *\n * Named exactly as the DDL generator names them (`<table>_<column>`), because\n * a column added here has to reference the same type the generator would have\n * created — a second, differently-named type for the same field would be a\n * silent schema fork.\n */\nfunction requiredEnums(collection: CollectionConfig): { name: string; values: string[] }[] {\n const table = tableOf(collection);\n const schema = schemaOf(collection);\n const out: { name: string; values: string[] }[] = [];\n for (const [propName, prop] of Object.entries(collection.properties ?? {})) {\n const p = prop as Property;\n if (!(\"enum\" in p) || !p.enum) continue;\n if (p.type !== \"string\" && p.type !== \"number\") continue;\n const values = (p.enum as unknown[])\n .map(entry =>\n entry && typeof entry === \"object\" && \"id\" in (entry as Record<string, unknown>)\n ? String((entry as Record<string, unknown>).id)\n : String(entry)\n )\n .filter(v => v.length > 0);\n if (values.length === 0) continue;\n out.push({ name: `${schema}.${table}_${resolveColumnName(propName, p)}`, values });\n }\n return out;\n}\n\n/**\n * Decide what to add. Pure — the caller supplies what exists and runs the result.\n *\n * Ordering matters and is deliberate: enum types before the tables and columns\n * that reference them, tables before the columns added to other tables (a new\n * table may be the target of a relation), and nothing is emitted twice.\n */\nexport function planCollectionSchemaEnsure(\n allCollections: CollectionConfig[],\n existing: ExistingSchema,\n options: EnsureOptions = {}\n): EnsurePlan {\n const constraintPolicy: ConstraintPolicy = options.constraints ?? \"additive\";\n const withheldConstraints: WithheldConstraint[] = [];\n const columnTypeDrift: ColumnTypeDrift[] = [];\n // Boot receives every collection the bundle declares, including the ones\n // served by another engine entirely. Creating a Postgres table for a\n // Firestore collection is not a harmless extra: the app keeps reading\n // documents from Firestore while an empty table with the same name accretes\n // policies and shows up in every drift report.\n // Before the filter, deliberately: a `search` block on a collection this\n // engine does not store would otherwise be dropped here without a word.\n assertSearchIsPostgresOnly(allCollections);\n\n const collections = relationalCollections(allCollections);\n const actions: EnsureAction[] = [];\n const plannedEnums = new Set<string>();\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 collection of collections) {\n for (const { name, values } of requiredEnums(collection)) {\n if (existing.enums.has(name) || plannedEnums.has(name)) {\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\n // value vanish: nothing was planned, the boot reported success,\n // and the first row using the value was rejected by a type that\n // had never heard of it. `ADD VALUE` is the one alteration\n // Postgres offers here, it is purely additive, and it is\n // idempotent with `IF NOT EXISTS`.\n //\n // `enumValues` absent means the caller built the schema by hand\n // and does not know the values; skip by name as before rather\n // than plan against a guess.\n const current = existing.enumValues?.get(name);\n if (!current || plannedEnums.has(name)) continue;\n const [schema, typeName] = name.split(\".\");\n for (const value of values) {\n if (current.includes(value)) continue;\n actions.push({\n kind: \"add-enum-value\",\n target: `${name}.${value}`,\n // Not inside a transaction with any use of the value:\n // Postgres refuses to read a value added by the\n // transaction still adding it. The applier runs these\n // one statement at a time, which is what makes it legal.\n sql: `ALTER TYPE \"${schema}\".\"${typeName}\" ADD VALUE IF NOT EXISTS ${quoteSqlLiteral(value)};`\n });\n }\n continue;\n }\n plannedEnums.add(name);\n const [schema, typeName] = name.split(\".\");\n actions.push({\n kind: \"create-enum\",\n target: name,\n sql: `CREATE TYPE \"${schema}\".\"${typeName}\" AS ENUM (${values.map(quoteSqlLiteral).join(\", \")});`\n });\n }\n }\n\n // 1b. Search support, for collections that declared a `search` block.\n //\n // Before the tables, because a generated column's expression is\n // resolved when the column is created: a table whose search column\n // calls `rebase_search_text` cannot be added before that function\n // exists. Both forms are idempotent, so a boot against a database that\n // already has them plans nothing.\n const searchSpecs = collections\n .map(c => buildSearchColumnSpec(c))\n .filter((spec): spec is SearchColumnSpec => spec !== undefined);\n\n const plannedExtensions = new Set<string>();\n const planExtension = (statement: string): void => {\n if (plannedExtensions.has(statement)) return;\n plannedExtensions.add(statement);\n actions.push({ kind: \"create-extension\", target: statement.replace(/^CREATE EXTENSION IF NOT EXISTS |;$/g, \"\"), sql: statement });\n };\n for (const spec of searchSpecs) {\n for (const statement of searchExtensionStatements(spec)) planExtension(statement);\n }\n\n // pgvector, for collections that declared a `vector` property — and only\n // when a database gave leave to install it. Unlike the search extensions\n // above, which are contrib modules every Postgres carries, pgvector is a\n // separate build behind an image, a grant and a provider allow-list, so\n // whether Rebase may install it is not Rebase's to decide. See\n // `DatabaseOptions.extensions`.\n //\n // Boot has to make the same call `rebase db push` makes, or the two produce\n // different databases from one commit — which is the rule\n // `contracts/derived-names.txt` enforces.\n if (vectorExtensionDeclared(options.databaseExtensions)\n && collections.some(c => buildVectorColumnSpecs(c, resolveColumnName).length > 0)) {\n planExtension(vectorExtensionStatement());\n }\n const plannedFunctions = new Set<string>();\n for (const spec of searchSpecs) {\n for (const statement of searchHelperFunctions(spec)) {\n if (plannedFunctions.has(statement)) continue;\n plannedFunctions.add(statement);\n actions.push({ kind: \"create-function\", target: statement.includes(\"unaccent\") ? SEARCH_UNACCENT_FN : SEARCH_TEXT_FN, sql: statement });\n }\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 collection of collections) {\n const key = qualified(collection);\n if (existing.tables.has(key) || created.has(key)) continue;\n created.add(key);\n const schema = schemaOf(collection);\n const table = tableOf(collection);\n const idEntry = Object.entries(collection.properties ?? {}).find(([n, p]) =>\n isIdProperty(n, p as Property, collection)\n );\n const idName = idEntry ? resolveColumnName(idEntry[0], idEntry[1] as Property) : \"id\";\n const idProp = idEntry?.[1] as Property | undefined;\n // Derived through the generator's own type mapping, not re-decided here.\n // This branch used to emit BIGSERIAL for a numeric id while `db push`\n // emitted INTEGER GENERATED BY DEFAULT AS IDENTITY, so the same project\n // got an int8 key when the runtime brought the schema up and an int4 key\n // when a human pushed it. Two consequences, both real: node-postgres\n // hands back int8 as a *string*, so a collection declaring\n // `type: \"number\"` served `\"1\"` instead of `1` on the managed path only;\n // and every foreign key and junction column pointing at it stayed\n // INTEGER on both paths, which is a truncation waiting for the sequence\n // to pass 2^31. The agreement test now pins this.\n const idType = idProp\n ? getSqlColumnType(idEntry![0], idProp, collection, collections)\n : \"TEXT\";\n let idDef = `\"${assertSafeIdentifier(idName, \"column name\")}\" ${idType} PRIMARY KEY`;\n if (idProp?.type === \"string\" && (idProp as { isId?: unknown }).isId === \"uuid\") {\n idDef += \" DEFAULT gen_random_uuid()\";\n }\n actions.push({\n kind: \"create-table\",\n target: key,\n sql: `CREATE TABLE IF NOT EXISTS \"${schema}\".\"${table}\" (${idDef});`\n });\n }\n\n // 2b. Junction tables behind many-to-many relations. No collection declares\n // them, so the walk above never sees them — and until they existed, an\n // m2m write had nowhere to land and the junction's derived RLS had\n // nothing to attach to.\n const junctions = planJunctionTables(collections);\n for (const junction of junctions) {\n const key = `${junction.schema}.${junction.table}`;\n if (existing.tables.has(key) || created.has(key)) continue;\n created.add(key);\n actions.push({ kind: \"create-table\", target: key, sql: junction.createTable });\n }\n\n // 3. Missing columns, on both brand-new and pre-existing tables.\n const legacyForeignKeys: LegacyForeignKey[] = [];\n\n /**\n * Move a relation 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 here would be the wrong move and a quiet one: the data is in\n * the 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 * Only ever reached when the new name is absent and the old name is\n * present, so there is nothing to overwrite and nothing to choose between.\n */\n const renameLegacyColumn = (\n key: string,\n schema: string,\n table: string,\n column: string,\n legacyName: string | undefined\n ): boolean => {\n const present = existing.tables.get(key);\n if (!legacyName || !present) return false;\n if (present.has(column) || !present.has(legacyName)) return false;\n\n legacyForeignKeys.push({ table: key, expected: column, legacy: legacyName });\n actions.push({\n kind: \"rename-column\",\n target: `${key}.${column}`,\n sql: `ALTER TABLE \"${schema}\".\"${table}\" RENAME COLUMN \"${legacyName}\" TO \"${column}\";`\n });\n return true;\n };\n\n const addColumn = (\n key: string,\n schema: string,\n table: string,\n column: string,\n definition: string\n ): void => {\n const present = existing.tables.get(key);\n if (present?.has(column)) return;\n // Same reason as {@link schemaOf}: a column name reaching here came\n // from a property declaration, which on the editor paths came over the\n // wire. `definition` is built by the generator from a closed set of\n // type mappings and is not caller text.\n assertSafeIdentifier(column, \"column name\");\n actions.push({\n kind: \"add-column\",\n target: `${key}.${column}`,\n sql: `ALTER TABLE \"${schema}\".\"${table}\" ADD COLUMN IF NOT EXISTS \"${column}\" ${definition};`\n });\n };\n\n for (const collection of collections) {\n const key = qualified(collection);\n const schema = schemaOf(collection);\n const table = tableOf(collection);\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, and this module runs unattended\n // against customer data with nobody reading a diff. So the constraints\n // are emitted for the fresh case — which is the whole managed-runtime\n // path, and the one that diverged from `db push` — and withheld for the\n // adopted one. `rebase db push` remains how an existing table gets them.\n const fresh = created.has(key);\n const auth = isAuthCollection(collection);\n for (const [propName, prop] of Object.entries(collection.properties ?? {})) {\n const p = prop as Property;\n if (isIdProperty(propName, p, collection)) continue;\n // Relation and reference columns are planned from the shared\n // relational planner below, which derives the column name, type and\n // foreign key the same way `db push` does. Deriving them here as\n // plain columns is what once produced a column with no constraint.\n if (p.type === \"reference\" || p.type === \"relation\") continue;\n\n const column = resolveColumnName(propName, p);\n // On an auth collection, the columns auth itself reads and writes\n // have exactly one definition, wherever the table is created from —\n // see `auth-users-columns`. Anything else on that collection is an\n // ordinary user-declared field and is generated like any other.\n const authDefinition = auth ? authUsersColumnDefinition(column) : undefined;\n if (authDefinition) {\n addColumn(key, schema, table, column, authDefinition);\n continue;\n }\n\n // Assembled in the generator's order — type, UNIQUE, DEFAULT,\n // NOT NULL — so the two produce byte-identical column definitions\n // and the agreement test can compare them directly instead of\n // checking that a column merely exists, which is how BIGSERIAL-vs-\n // INTEGER and every missing constraint went unnoticed.\n const declaredType = getSqlColumnType(propName, p, collection, collections);\n let definition = declaredType;\n if (fresh && p.validation?.unique) definition += \" UNIQUE\";\n // Not gated on `fresh`: a default binds future writes only, so it is\n // safe on a live table, and a column added without it would take the\n // value the application forgot to send rather than `now()`.\n const autoValue = (p as { autoValue?: string }).autoValue;\n const hasDefault = p.type === \"date\" && (autoValue === \"on_create\" || autoValue === \"on_update\");\n if (hasDefault) definition += \" DEFAULT now()\";\n\n const required = p.validation?.required === true;\n const columnKey = `${key}.${column}`;\n const columnExists = existing.tables.get(key)?.has(column) === true;\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\n // a `columnType` used to report success while the column stayed as\n // it was, and the divergence surfaced later as every write failing.\n const actualType = existing.columnTypes?.get(columnKey);\n if (columnExists && actualType && !typesAgree(declaredType, actualType)) {\n columnTypeDrift.push({\n table: key,\n column,\n declared: declaredType,\n actual: actualType\n });\n }\n\n // A NOT NULL is safe exactly when it cannot fail against rows that\n // are 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\n // into every existing row as part of ADD COLUMN.\n //\n // Anything else is checked against live data and can abort the boot,\n // which is why it used to be withheld — correctly. What was wrong was\n // withholding it in *silence*: the config said required, the column\n // came out nullable, and nothing anywhere said so.\n // `populatedTables` absent means the caller does not know, and not\n // knowing has to read as \"assume rows\" — the other direction emits a\n // NOT NULL that is checked against live data and aborts the boot.\n // Written as an explicit `!== undefined` because the optional-chain\n // form (`!existing.populatedTables?.has(key)`) quietly says *empty*\n // when the fact is missing, which is the wrong way to be wrong.\n const tableIsEmpty = existing.populatedTables !== undefined\n && existing.tables.has(key)\n && !existing.populatedTables.has(key);\n const notNullIsSafe = fresh || tableIsEmpty || hasDefault;\n\n if (required && !columnExists) {\n if (notNullIsSafe) {\n definition += \" NOT NULL\";\n } else {\n withheldConstraints.push({\n target: columnKey,\n kind: \"not-null\",\n reason:\n `\"${column}\" is required, but \"${key}\" 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:\n \"Backfill the column, then add the constraint — or give the property a \" +\n \"default so every existing row gets one.\"\n });\n }\n }\n addColumn(key, schema, table, column, definition);\n\n // The column is already there and only its constraint differs. Two\n // directions, and they are not equally safe — see `ConstraintPolicy`\n // for why neither runs at an unattended boot.\n if (columnExists && constraintPolicy === \"converge\") {\n const isNotNull = existing.notNullColumns?.has(columnKey) === true;\n if (required && !isNotNull) {\n if (tableIsEmpty) {\n actions.push({\n kind: \"set-not-null\",\n target: columnKey,\n sql: `ALTER TABLE \"${schema}\".\"${table}\" ALTER COLUMN \"${column}\" SET NOT NULL;`\n });\n } else {\n withheldConstraints.push({\n target: columnKey,\n kind: \"not-null\",\n reason:\n `\"${column}\" became required, but \"${key}\" 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 +\n \"\\\" = … WHERE \\\"\" + 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\n // rather than at boot because a database adopted by\n // introspection carries NOT NULL on columns the generated\n // collection deliberately leaves optional, and converging\n // those unasked would drop constraints nobody edited.\n actions.push({\n kind: \"drop-not-null\",\n target: columnKey,\n sql: `ALTER TABLE \"${schema}\".\"${table}\" ALTER COLUMN \"${column}\" DROP NOT NULL;`\n });\n }\n }\n }\n\n // The auth columns the collection never mentions. The scaffold's users\n // collection describes 12 of the 14 auth reads and writes, so planning\n // only from properties left `is_anonymous` and `tokens_valid_after` to\n // `ensureAuthTablesExist` — which does create them, but only because\n // that function happens to run later in the same boot. Planning them\n // here makes this path self-contained and identical to `db push`, so\n // neither depends on the other having run.\n if (auth) {\n const declared = new Set(\n Object.entries(collection.properties ?? {})\n .map(([name, prop]) => resolveColumnName(name, prop as Property))\n );\n for (const spec of AUTH_USERS_COLUMNS) {\n if (declared.has(spec.column)) continue;\n addColumn(key, schema, table, spec.column, authUsersColumnSql(spec));\n }\n }\n }\n\n // 3aa. 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 // therefore carries a fingerprint of the expression it was built from\n // (in its comment), and a mismatch is reported rather than applied.\n const searchDrift: SearchColumnDrift[] = [];\n const searchAdopted: { table: string; column: string }[] = [];\n for (const spec of searchSpecs) {\n const key = `${spec.schema}.${spec.table}`;\n const definitions: Record<string, string> = {\n [spec.column]: `tsvector GENERATED ALWAYS AS (${spec.expression}) STORED`\n };\n if (spec.fuzzy) {\n definitions[spec.fuzzy.column] = `text GENERATED ALWAYS AS (${spec.fuzzy.expression}) STORED`;\n }\n\n for (const stamp of searchColumnStamps(spec)) {\n const definition = definitions[stamp.column];\n const exists = existing.tables.get(key)?.has(stamp.column) === true;\n const recorded = existing.columnComments?.get(`${key}.${stamp.column}`);\n\n if (exists && recorded?.startsWith(SEARCH_STAMP_PREFIX) && recorded !== stamp.fingerprint) {\n searchDrift.push({\n table: key,\n column: stamp.column,\n found: recorded,\n expected: stamp.fingerprint,\n rebuild: [\n `ALTER TABLE \"${spec.schema}\".\"${spec.table}\" DROP COLUMN \"${stamp.column}\";`,\n `ALTER TABLE \"${spec.schema}\".\"${spec.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(key, spec.schema, spec.table, stamp.column, definition);\n if (exists && recorded === undefined) {\n searchAdopted.push({ table: key, column: stamp.column });\n }\n if (recorded !== stamp.fingerprint) {\n actions.push({\n kind: \"comment-column\",\n target: `${key}.${stamp.column}`,\n sql: stamp.sql\n });\n }\n }\n }\n\n // 3b. A junction that already existed, but is short a column. One created\n // above already carries both — unlike a collection table, whose CREATE\n // declares only the identity column — so re-listing them would log two\n // no-op statements and inflate the count of changes applied.\n for (const junction of junctions) {\n const key = `${junction.schema}.${junction.table}`;\n if (created.has(key)) continue;\n for (const column of junction.columns) {\n if (renameLegacyColumn(key, junction.schema, junction.table, column.name, column.legacyName)) continue;\n addColumn(key, junction.schema, junction.table, column.name, column.type);\n }\n }\n\n // 3c. The columns relation and reference properties own.\n //\n // Recorded per table as well as planned: these columns are derived here\n // rather than declared in `properties`, so the orphan check below would\n // otherwise read every foreign key as a column nobody declared.\n const plannedRelationColumns = new Map<string, Set<string>>();\n for (const relational of planRelationalColumns(collections)) {\n const relKey = `${relational.schema}.${relational.table}`;\n if (!plannedRelationColumns.has(relKey)) plannedRelationColumns.set(relKey, new Set());\n plannedRelationColumns.get(relKey)!.add(relational.column);\n if (relational.legacyColumn) plannedRelationColumns.get(relKey)!.add(relational.legacyColumn);\n if (renameLegacyColumn(relKey, relational.schema, relational.table, relational.column, relational.legacyColumn)) continue;\n addColumn(\n relKey,\n relational.schema,\n relational.table,\n relational.column,\n relational.type\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 const foreignKeys = [\n ...planRelationalColumns(collections).map(r => r.foreignKey),\n ...junctions.flatMap(j => j.foreignKeys)\n ];\n for (const fk of foreignKeys) {\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({\n kind: \"add-constraint\",\n target: `${fk.schema}.${fk.table}.${fk.constraintName}`,\n sql: fk.sql\n });\n }\n\n // 5. Search indexes, after everything — the column has to exist, and this is\n // the 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. `concurrentIndexing` withholds it for a\n // table this same plan is creating: there are no rows to build from and\n // no writer to block, so the lock CONCURRENTLY avoids is a lock nobody\n // would have taken. Worth withholding rather than merely harmless,\n // because CONCURRENTLY is the one index form Postgres refuses inside a\n // transaction block — so on a first boot it buys nothing and adds the\n // single failure mode this whole statement family has.\n const concurrentIndexing = (schema: string, table: string): boolean =>\n !created.has(`${schema}.${table}`);\n for (const spec of searchSpecs) {\n for (const statement of searchIndexStatements(spec)) {\n actions.push({\n kind: \"create-index\",\n target: `${spec.schema}.${spec.table}`,\n sql: concurrentIndexing(spec.schema, spec.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: the column has to\n // exist, the build is real work against real rows, and CONCURRENTLY is\n // what keeps that from locking writes for its duration.\n //\n // A column too wide for pgvector to index is reported, not planned —\n // silence there would read as \"indexed\" to anyone watching the boot.\n const vectorIndexSkipped: SkippedVectorIndex[] = [];\n for (const collection of collections) {\n const plan = buildVectorIndexPlan(collection, resolveColumnName);\n for (const spec of plan.specs) {\n actions.push({\n kind: \"create-index\",\n target: `${spec.schema}.${spec.table}`,\n sql: concurrentIndexing(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(...plan.skipped);\n }\n\n // Declared indexes, on exactly the same terms as the ANN ones above.\n //\n // Boot has to emit these, not just `db push`: the managed runtime\n // provisions at boot and never runs a push, so a push-only index would\n // simply not exist there — and nothing would say so.\n // `contracts/derived-names.txt` states the rule (\"Both, or it is a\n // bug\") and the gate enforces it, which is what caught this.\n //\n // `concurrently` is a parameter here rather than a string replacement\n // on the rendered SQL. The `.replace(\"CREATE INDEX IF NOT EXISTS\", …)`\n // just above silently does nothing for a UNIQUE index, whose text is\n // `CREATE UNIQUE INDEX …` and never matches the pattern.\n for (const spec of buildCollectionIndexPlan(collections, resolveColumnName)) {\n actions.push({\n kind: \"create-index\",\n target: `${spec.schema}.${spec.table}`,\n sql: collectionIndexStatement(spec, {\n concurrently: concurrentIndexing(spec.schema, spec.table),\n ifNotExists: true\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. The id column is excluded\n // for the same reason it is skipped everywhere else here: it is generated.\n const orphanedRequiredColumns: OrphanedRequiredColumn[] = [];\n if (existing.notNullColumns && existing.columnDefaults) {\n for (const collection of collections) {\n const key = qualified(collection);\n const live = existing.tables.get(key);\n if (!live || created.has(key)) continue;\n\n const declared = new Set<string>();\n for (const [propName, prop] of Object.entries(collection.properties ?? {})) {\n declared.add(resolveColumnName(propName, prop as Property));\n }\n // Relation and reference columns are planned by the relational\n // planner, not from `properties`, so a foreign key would otherwise\n // read as undeclared. Anything that planner named for this table is\n // declared by definition.\n for (const column of plannedRelationColumns.get(key) ?? []) declared.add(column);\n\n for (const column of live) {\n const columnKey = `${key}.${column}`;\n if (declared.has(column)) continue;\n if (!existing.notNullColumns.has(columnKey)) continue;\n if (existing.columnDefaults.has(columnKey)) continue;\n orphanedRequiredColumns.push({ table: key, column, slug: collection.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/** 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 }>(\n `SELECT table_schema, table_name, column_name, is_nullable, udt_name, column_default\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) columnTypes.set(`${key}.${row.column_name}`, row.udt_name);\n if (row.column_default !== null) columnDefaults.add(`${key}.${row.column_name}`);\n }\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\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 // 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.\n const schemas = Array.from(new Set([\n ...collections.map(schemaOf),\n ...planJunctionTables(collections).map(j => j.schema)\n ]));\n for (const schema of schemas) {\n assertSafeIdentifier(schema, \"schema name\");\n if (schema !== \"public\") {\n await client.query(`CREATE SCHEMA IF NOT EXISTS \"${schema}\";`);\n }\n }\n\n const existing = await readExistingSchema(client, schemas);\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 plan = planCollectionSchemaEnsure(collections, existing, {\n ...options,\n databaseExtensions: options.databaseExtensions ?? declaredDatabaseExtensions()\n });\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,IAAM,gBAAgB;;;;;;AAOtB,IAAa,iBAAiB,GAAG,cAAc;AAC/C,IAAa,qBAAqB,GAAG,cAAc;;AA4CnD,IAAa,oBAAb,cAAuC,MAAM;CACzC,YAAY,SAAiB;EACzB,MAAM,OAAO;EACb,KAAK,OAAO;CAChB;AACJ;;AAGA,IAAa,mBAAmB,eAC5B,2BAA2B,UAAU,IAAI,WAAW,SAAS,KAAA;;;;;;;;;;;;AAajE,IAAa,8BAA8B,gBAA0C;CACjF,KAAK,MAAM,cAAc,aAAa;EAClC,IAAI,2BAA2B,UAAU,GAAG;EAC5C,IAAI,CAAE,WAAoC,QAAQ;EAClD,MAAM,SAAU,WAAmC,UAAU;EAC7D,MAAM,IAAI,kBACN,GAAG,WAAW,KAAK,sFAAsF,OAAO,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