viborm 1.14.1 → 1.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/adapters.d.mts +1 -1
  2. package/dist/bun-sql.d.mts +1 -1
  3. package/dist/bun-sqlite.d.mts +1 -1
  4. package/dist/cache/cloudflare-kv.d.mts +1 -1
  5. package/dist/cache/memory.d.mts +1 -1
  6. package/dist/cache.d.mts +2 -2
  7. package/dist/cli.mjs +1 -1
  8. package/dist/{client-D1shn5AL.d.mts → client-CRxfhw2y.d.mts} +1 -1
  9. package/dist/{client-DzXpmSNi.mjs → client-y7TV0PRZ.mjs} +2 -2
  10. package/dist/client-y7TV0PRZ.mjs.map +1 -0
  11. package/dist/client.d.mts +2 -2
  12. package/dist/config.d.mts +1 -1
  13. package/dist/d1.d.mts +1 -1
  14. package/dist/{database-adapter-BD_htd5h.d.mts → database-adapter-BGqvjeEy.d.mts} +1 -1
  15. package/dist/{document-rMfLKZP5.d.mts → document-BVTQ-cF-.d.mts} +1 -1
  16. package/dist/{driver-CH9qAuft.d.mts → driver-BBEmaJZy.d.mts} +1 -1
  17. package/dist/driver.d.mts +1 -1
  18. package/dist/durable-object.d.mts +1 -1
  19. package/dist/{every-KV5yuSVT.mjs → every-tOgQmaIE.mjs} +2 -2
  20. package/dist/{every-KV5yuSVT.mjs.map → every-tOgQmaIE.mjs.map} +1 -1
  21. package/dist/{exports-nYDS0SZ7.d.mts → exports-COCJ8f2f.d.mts} +1 -1
  22. package/dist/index.d.mts +1 -1
  23. package/dist/index.mjs +1 -1
  24. package/dist/instrumentation.d.mts +1 -1
  25. package/dist/instrumentation.mjs +1 -1
  26. package/dist/{introspect-DD_5FEl0.mjs → introspect-Bm6xnXcG.mjs} +2 -2
  27. package/dist/{introspect-DD_5FEl0.mjs.map → introspect-Bm6xnXcG.mjs.map} +1 -1
  28. package/dist/libsql.d.mts +1 -1
  29. package/dist/migrations/mysql.d.mts +4 -4
  30. package/dist/migrations/mysql.mjs +1 -1
  31. package/dist/migrations/postgres.d.mts +4 -4
  32. package/dist/migrations/postgres.mjs +1 -1
  33. package/dist/migrations/snowflake.d.mts +4 -4
  34. package/dist/migrations/snowflake.mjs +1 -1
  35. package/dist/migrations/sqlite.d.mts +4 -4
  36. package/dist/migrations/sqlite.mjs +1 -1
  37. package/dist/migrations/surrealdb.d.mts +4 -4
  38. package/dist/migrations/surrealdb.mjs +1 -1
  39. package/dist/migrations/tenant.d.mts +2 -2
  40. package/dist/migrations/tenant.mjs +1 -1
  41. package/dist/migrations.d.mts +4 -4
  42. package/dist/migrations.mjs +1 -1
  43. package/dist/mysql2.d.mts +1 -1
  44. package/dist/neon-http.d.mts +1 -1
  45. package/dist/{object-store-0zc3XYcO.d.mts → object-store-B_YMoW8u.d.mts} +3 -3
  46. package/dist/on.d.mts +1 -1
  47. package/dist/ordering.d.mts +1 -1
  48. package/dist/permissions.d.mts +1 -1
  49. package/dist/pg.d.mts +1 -1
  50. package/dist/pglite.d.mts +1 -1
  51. package/dist/planetscale.d.mts +1 -1
  52. package/dist/{planner-uYQS0hif.d.mts → planner-DHjdvjwk.d.mts} +1 -1
  53. package/dist/postgres.d.mts +1 -1
  54. package/dist/schema/introspect.d.mts +2 -2
  55. package/dist/schema/introspect.mjs +1 -1
  56. package/dist/schema/json.d.mts +2 -2
  57. package/dist/schema.d.mts +1 -1
  58. package/dist/snowflake.d.mts +1 -1
  59. package/dist/soft-delete.d.mts +1 -1
  60. package/dist/sqlite3.d.mts +1 -1
  61. package/dist/surrealdb.d.mts +1 -1
  62. package/dist/surrealdb.mjs +1 -1
  63. package/dist/surrealdb.mjs.map +1 -1
  64. package/dist/{surrealql-DpipDgMB.mjs → surrealql-C1dp1sWw.mjs} +2 -2
  65. package/dist/surrealql-C1dp1sWw.mjs.map +1 -0
  66. package/dist/validation.d.mts +1 -1
  67. package/dist/version-CXGIA82S.mjs +2 -0
  68. package/dist/{version-DRfmNoR1.mjs.map → version-CXGIA82S.mjs.map} +1 -1
  69. package/package.json +1 -1
  70. package/dist/client-DzXpmSNi.mjs.map +0 -1
  71. package/dist/surrealql-DpipDgMB.mjs.map +0 -1
  72. package/dist/version-DRfmNoR1.mjs +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"introspect-DD_5FEl0.mjs","names":["values","members","value","#taken","#reserved","#free","models","driver"],"sources":["../src/migrations/introspect/connect.ts","../src/migrations/introspect/read.ts","../src/migrations/introspect/columns.ts","../src/migrations/introspect/names.ts","../src/migrations/introspect/translate.ts","../src/migrations/introspect/verify.ts","../src/migrations/introspect/index.ts"],"sourcesContent":["/**\n * A connection string → the stock VibORM driver for it.\n *\n * The scheme names the driver, and the driver is constructed exactly as its\n * own `createClient` constructs it (`databaseUrl` / `dataDir`). Each driver\n * module is imported on demand, so only the provider package the URL names is\n * loaded — introspecting PostgreSQL never requires `better-sqlite3`.\n */\n\nimport type { AnyDriver } from \"../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport type { IntrospectionDialect } from \"./types\";\n\nexport interface OpenedDriver {\n readonly driver: AnyDriver;\n readonly dialect: IntrospectionDialect;\n}\n\nconst SCHEME = /^([a-z][a-z0-9+.-]*):/i;\nconst SQLITE_FILE = /\\.(?:db|sqlite3?|db3)$/i;\n\n/** A SQLite path from `file:` / `sqlite:` URLs, or a bare database file. */\nfunction sqlitePath(url: string): string | undefined {\n for (const prefix of [\"sqlite://\", \"sqlite:\", \"file://\", \"file:\"]) {\n if (url.startsWith(prefix)) return url.slice(prefix.length);\n }\n return SCHEME.test(url) ? undefined : url;\n}\n\nexport async function openDriver(url: string): Promise<OpenedDriver> {\n const scheme = SCHEME.exec(url)?.[1]?.toLowerCase();\n if (scheme === \"postgres\" || scheme === \"postgresql\") {\n const { PgDriver } = await import(\"../../drivers/pg\");\n return {\n driver: new PgDriver({ databaseUrl: url, options: {} }),\n dialect: \"postgresql\",\n };\n }\n if (\n scheme === \"libsql\" ||\n scheme === \"http\" ||\n scheme === \"https\" ||\n scheme === \"ws\" ||\n scheme === \"wss\"\n ) {\n const { LibSQLDriver } = await import(\"../../drivers/libsql\");\n const parsed = new URL(url);\n const authToken = parsed.searchParams.get(\"authToken\") ?? undefined;\n parsed.searchParams.delete(\"authToken\");\n return {\n driver: new LibSQLDriver({\n databaseUrl: parsed.href,\n ...(authToken === undefined ? {} : { authToken }),\n }),\n dialect: \"sqlite\",\n };\n }\n if (scheme === \"mysql\") {\n const { MySQL2Driver } = await import(\"../../drivers/mysql2\");\n return { driver: new MySQL2Driver({ databaseUrl: url }), dialect: \"mysql\" };\n }\n if (scheme === \"snowflake\")\n throw new MigrationError(\n 'A snowflake:// URL carries no key or token. Pass the driver instead: introspectSchema({ driver: new SnowflakeDriver({ databaseUrl, privateKey }) }) with SnowflakeDriver from \"viborm/snowflake\".',\n VibORMErrorCode.INVALID_INPUT,\n { meta: { feature: \"introspect-url\" } }\n );\n if (scheme === \"surrealdb\" || scheme === \"surreal\")\n throw new MigrationError(\n \"introspectSchema does not translate SurrealDB yet; PostgreSQL, SQLite and MySQL are supported.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { feature: \"introspect-schema\" } }\n );\n const path = sqlitePath(url);\n if (\n path !== undefined &&\n (scheme !== undefined || SQLITE_FILE.test(path) || path === \":memory:\")\n ) {\n const { SQLite3Driver } = await import(\"../../drivers/sqlite3\");\n // Read-only, and only an existing file: introspection never creates a\n // database it was asked to read.\n return {\n driver: new SQLite3Driver({\n dataDir: path,\n options: { readonly: true, fileMustExist: true },\n }),\n dialect: \"sqlite\",\n };\n }\n throw new MigrationError(\n `introspectSchema cannot tell which database \"${scheme ?? url}\" names. Use postgres:// or postgresql:// for PostgreSQL, mysql:// for MySQL, file: or sqlite: (or a .db / .sqlite file) for SQLite, and libsql:// for libSQL; or pass a driver.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { feature: \"introspect-url\" } }\n );\n}\n","/**\n * The live catalog `introspectSchema` translates: the snapshot the dialect's\n * own migration introspection reads, plus the few facts a snapshot does not\n * model and a document needs (identity columns) or must report (views, CHECK\n * constraints).\n *\n * Migration introspection REFUSES a table it cannot represent — a generated\n * column, a partitioned table, an index it cannot spell — because `push` must\n * not plan around what it does not understand. Here such a table is a skipped\n * object, not a failure: the refused table leaves the scope and the read runs\n * again, so one exotic table never hides the rest of the database.\n */\n\nimport type { AnyDriver } from \"../../drivers/driver\";\nimport { isVibORMError } from \"../../errors\";\nimport { CONTROL_TABLES } from \"../control\";\nimport { type BoundMigrationDriver, getMigrationDriver } from \"../drivers\";\nimport type { AdoptionHazard, MigrationDriver } from \"../drivers/base\";\nimport type { SchemaSnapshot } from \"../types\";\nimport type { IntrospectionDialect, SkippedObject } from \"./types\";\n\nexport interface LiveCatalog {\n readonly snapshot: SchemaSnapshot;\n readonly skipped: SkippedObject[];\n /** PostgreSQL identity columns, keyed `table\\0column`. */\n readonly identityColumns: ReadonlySet<string>;\n /**\n * What each kept table carries that changes how it behaves and that no\n * snapshot describes — the dialect's own `adoptionHazards`: a collation,\n * SQLite's `STRICT` and `ON CONFLICT`, a trigger, row security... A\n * document cannot carry it either.\n */\n readonly hazards: readonly AdoptionHazard[];\n /** The migration driver bound to the whole estate. */\n readonly migrationDriver: BoundMigrationDriver;\n}\n\nconst CONTROL = new Set([CONTROL_TABLES.state, CONTROL_TABLES.log]);\n\n/** The table a migration introspection refusal names, when it names one. */\nfunction refusedTable(error: unknown): string | undefined {\n if (!isVibORMError(error)) return;\n const table: unknown = error.meta?.table;\n return typeof table === \"string\" ? table : undefined;\n}\n\n/** The dialect's own introspection, without the managed-table boundary check. */\nasync function introspectScope(\n driver: AnyDriver,\n scope: readonly string[] | undefined\n): Promise<SchemaSnapshot> {\n const bound = getMigrationDriver(driver, scope);\n // The bound view wraps the implementation's `introspect` in the managed-table\n // selection, which REFUSES a foreign key crossing the scope. A refused table\n // can be the target of a foreign key this document still reports (as a\n // skipped foreign key), so the implementation itself is read, under the same\n // bound `this`, and the tables are selected below.\n const implementation: MigrationDriver = Object.getPrototypeOf(bound);\n return await implementation.introspect.call(bound, (sql, params) =>\n driver._executeRaw(sql, params)\n );\n}\n\nasync function rows<T>(\n driver: AnyDriver,\n sql: string,\n params: unknown[]\n): Promise<T[]> {\n return (await driver._executeRaw<T>(sql, params)).rows;\n}\n\nexport async function readCatalog(\n driver: AnyDriver,\n dialect: IntrospectionDialect,\n tables: readonly string[] | undefined\n): Promise<LiveCatalog> {\n const migrationDriver = getMigrationDriver(driver);\n const skipped: SkippedObject[] = [];\n const refused = new Map<string, string>();\n let inventory: string[] | undefined;\n let snapshot: SchemaSnapshot;\n for (;;) {\n // A caller's `tables` is the first scope: a table outside it is read\n // without the refusals that would only protect a push of it.\n const scope =\n refused.size === 0\n ? tables\n : (tables ?? inventory ?? []).filter((name) => !refused.has(name));\n try {\n snapshot = await introspectScope(driver, scope);\n break;\n } catch (error) {\n const table = refusedTable(error);\n if (table === undefined || refused.has(table)) throw error;\n refused.set(\n table,\n error instanceof Error ? error.message : \"introspection refused it\"\n );\n if (tables === undefined && inventory === undefined) {\n const query = migrationDriver.generateInventoryTables();\n inventory = (\n await rows<{ name: string }>(driver, query.sql, query.params)\n ).map((row) => row.name);\n }\n }\n }\n for (const [table, reason] of refused)\n skipped.push({ kind: \"table\", name: table, reason });\n\n const selected = (name: string) =>\n !(refused.has(name) || CONTROL.has(name)) &&\n (tables === undefined || tables.includes(name));\n for (const table of snapshot.tables)\n if (CONTROL.has(table.name))\n skipped.push({\n kind: \"table\",\n name: table.name,\n reason: \"it is VibORM's migration control table\",\n });\n\n const identityColumns = new Set<string>();\n if (dialect === \"postgresql\") {\n // Binding proved the estate's namespace for PostgreSQL.\n const namespace = migrationDriver.namespace;\n for (const row of await rows<{ table_name: string; column_name: string }>(\n driver,\n \"SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = $1 AND is_identity = 'YES'\",\n [namespace]\n ))\n identityColumns.add(`${row.table_name}\\0${row.column_name}`);\n for (const row of await rows<{ name: string; kind: string }>(\n driver,\n \"SELECT table_name AS name, 'view' AS kind FROM information_schema.views WHERE table_schema = $1 UNION ALL SELECT matviewname AS name, 'materialized view' AS kind FROM pg_catalog.pg_matviews WHERE schemaname = $1 ORDER BY 1\",\n [namespace]\n ))\n skipped.push({\n kind: \"view\",\n name: row.name,\n reason: `it is a ${row.kind}, and a document declares tables only`,\n });\n for (const row of await rows<{\n table_name: string;\n name: string;\n definition: string;\n }>(\n driver,\n \"SELECT rel.relname AS table_name, con.conname AS name, pg_catalog.pg_get_constraintdef(con.oid) AS definition FROM pg_catalog.pg_constraint con JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid JOIN pg_catalog.pg_namespace ns ON ns.oid = rel.relnamespace WHERE ns.nspname = $1 AND con.contype = 'c' ORDER BY 1, 2\",\n [namespace]\n ))\n if (selected(row.table_name))\n skipped.push({\n kind: \"check\",\n table: row.table_name,\n name: row.name,\n reason: `a document has no CHECK constraint (${row.definition}); the database keeps enforcing it`,\n });\n } else if (dialect === \"mysql\") {\n // Binding proved the estate's database for MySQL.\n const database = migrationDriver.namespace;\n for (const row of await rows<{ name: string }>(\n driver,\n \"SELECT TABLE_NAME AS name FROM information_schema.VIEWS WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME\",\n [database]\n ))\n skipped.push({\n kind: \"view\",\n name: row.name,\n reason: \"it is a view, and a document declares tables only\",\n });\n for (const row of await rows<{\n table_name: string;\n name: string;\n definition: string;\n }>(\n driver,\n \"SELECT tc.TABLE_NAME AS table_name, tc.CONSTRAINT_NAME AS name, cc.CHECK_CLAUSE AS definition FROM information_schema.TABLE_CONSTRAINTS tc JOIN information_schema.CHECK_CONSTRAINTS cc ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME WHERE tc.CONSTRAINT_SCHEMA = ? AND tc.CONSTRAINT_TYPE = 'CHECK' ORDER BY 1, 2\",\n [database]\n ))\n if (selected(row.table_name))\n skipped.push({\n kind: \"check\",\n table: row.table_name,\n name: row.name,\n reason: `a document has no CHECK constraint (${row.definition}); the database keeps enforcing it`,\n });\n } else if (dialect === \"snowflake\") {\n const schema = migrationDriver.namespace;\n for (const row of await rows<{ name: string }>(\n driver,\n schema === undefined\n ? 'SELECT TABLE_NAME AS \"name\" FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = CURRENT_SCHEMA() ORDER BY TABLE_NAME'\n : 'SELECT TABLE_NAME AS \"name\" FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME',\n schema === undefined ? [] : [schema]\n ))\n skipped.push({\n kind: \"view\",\n name: row.name,\n reason: \"it is a view, and a document declares tables only\",\n });\n } else {\n for (const row of await rows<{ name: string }>(\n driver,\n \"SELECT name FROM sqlite_master WHERE type = 'view' ORDER BY name\",\n []\n ))\n skipped.push({\n kind: \"view\",\n name: row.name,\n reason: \"it is a view, and a document declares tables only\",\n });\n }\n\n const kept = snapshot.tables.filter((table) => selected(table.name));\n return {\n snapshot: { ...snapshot, tables: kept },\n skipped,\n identityColumns,\n hazards: await migrationDriver.adoptionHazards(\n kept.map((table) => table.name),\n async <T>(sql: string, params?: unknown[]) => ({\n rows: await rows<T>(driver, sql, params ?? []),\n })\n ),\n migrationDriver,\n };\n}\n","/**\n * One live column → one scalar field document.\n *\n * Each dialect reads the snapshot its own introspection wrote (`ColumnDef`) and\n * answers with the field whose forward serialization (`mapScalarType` and\n * `getDefaultExpression`) spells that column again — or with the reason it\n * cannot. Nothing here guesses past what the catalog proves: an exactness this\n * table cannot promise is caught afterwards by `verify.ts`, which runs the\n * forward direction for real.\n */\n\nimport { readArrayLiteralText } from \"../../adapters/databases/postgres/array-literal\";\nimport type {\n DecimalFieldDocument,\n EnumFieldDocument,\n PointFieldDocument,\n ScalarFieldDocument,\n ValueFieldDocument,\n} from \"../../schema/json/document\";\nimport type { JsonValue } from \"../../validation/primitives/json\";\nimport { MYSQL_PRINTED_CHARACTERS } from \"../drivers/type-mapping\";\nimport { normalizeDefault, normalizeType } from \"../push-fingerprint\";\nimport type { ColumnDef, EnumDef } from \"../types\";\nimport type { IntrospectionDialect } from \"./types\";\n\n/** What a column becomes, before keys, keys and relations are settled. */\nexport interface ColumnField {\n readonly field: ScalarFieldDocument;\n /** The database enum type an enum column uses (PostgreSQL), by name. */\n readonly enumType?: string | undefined;\n /** Why the column's default is not carried, when it is not. */\n readonly skippedDefault?: string | undefined;\n /** How the field's meaning is weaker than the column proves, when it is. */\n readonly approximated?: string | undefined;\n}\n\nexport type ColumnTranslation = ColumnField | { readonly skip: string };\n\nexport interface ColumnContext {\n readonly column: ColumnDef;\n /** The database enums by name (PostgreSQL). */\n readonly enums: ReadonlyMap<string, EnumDef>;\n /** A PostgreSQL identity column: the catalog default is not a default. */\n readonly identity: boolean;\n /** The dialect's spelling of a column-owned enum (SQLite's CHECK). */\n readonly enumColumnType: (values: string[]) => string;\n /**\n * A SQLite `BLOB` key column, or a foreign key to one: VibORM stores a uuid\n * key there as sixteen bytes, and a blob cannot be a key.\n */\n readonly binaryKey: boolean;\n /**\n * MySQL: the column is in a key, an index or a foreign key, where VibORM\n * writes a string as `VARCHAR(191)` (an indexed TEXT needs a length).\n */\n readonly keyed: boolean;\n}\n\n/** The scalar types that have `.array()`. */\nconst LIST_TYPES = new Set<string>([\n \"string\",\n \"int\",\n \"number\",\n \"decimal\",\n \"boolean\",\n \"datetime\",\n \"date\",\n \"time\",\n \"bigint\",\n \"blob\",\n \"enum\",\n]);\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\ntype ValueDraft = Mutable<ValueFieldDocument>;\ntype FieldDraft =\n | ValueDraft\n | Mutable<EnumFieldDocument>\n | Mutable<DecimalFieldDocument>\n | Mutable<PointFieldDocument>;\n\n// =============================================================================\n// DEFAULTS (shared literal reading)\n// =============================================================================\n\nconst QUOTED = /^'([\\s\\S]*)'$/;\nconst NUMBER = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i;\nconst INTEGER = /^[+-]?\\d+$/;\nconst NOW_DEFAULTS = new Set([\n \"now()\",\n \"now() at time zone 'utc'\",\n \"date_trunc('milliseconds',now())\",\n \"date_trunc('milliseconds',now() at time zone 'utc')\",\n \"current_date\",\n \"current_time\",\n \"localtimestamp\",\n \"localtime\",\n \"timezone('utc',current_time)\",\n \"timezone('utc',current_time(3))\",\n // SQLite: VibORM's own millisecond UTC clock.\n \"strftime('%Y-%m-%dT%H:%M:%fZ','now')\",\n // MySQL: a fractional-second clock.\n \"current_timestamp(3)\",\n \"current_timestamp(6)\",\n \"(current_timestamp(3))\",\n]);\nconst DATE_LITERAL = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst PG_TIMESTAMP_LITERAL =\n /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?)([+-]\\d{2}(?::?\\d{2})?|Z)?$/;\n\n/** A JSON value a document can carry untagged, or wrapped in `$raw`. */\nfunction jsonDefault(value: JsonValue): JsonValue {\n if (\n value !== null &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n Object.keys(value).length === 1 &&\n Object.keys(value)[0]?.startsWith(\"$\")\n )\n return { $raw: value };\n return value;\n}\n\nconst MYSQL_EXPRESSION_LITERAL = /^\\(('[\\s\\S]*')\\)$/;\nconst MYSQL_ESCAPE = /\\\\(.)/g;\n\n/**\n * A quoted literal's value. MySQL prints `\\\\`, `\\n`, `\\r`, `\\0`, `\\Z` and `\\'`\n * (`MYSQL_PRINTED_CHARACTERS`); an escape outside that table is not one it\n * printed for a value VibORM can name, so there is no value.\n */\nfunction unquote(\n body: string,\n dialect: IntrospectionDialect\n): string | undefined {\n const doubled = body.replaceAll(\"''\", \"'\");\n if (dialect !== \"mysql\") return doubled;\n let known = true;\n const value = doubled.replace(\n MYSQL_ESCAPE,\n (_sequence, character: string) => {\n const printed = MYSQL_PRINTED_CHARACTERS.get(character);\n if (printed === undefined) known = false;\n return printed ?? character;\n }\n );\n return known ? value : undefined;\n}\n\n/** A decimal's text from its unscaled integer coefficient. */\nfunction coefficientText(coefficient: string, scale: number): string {\n if (scale === 0) return BigInt(coefficient).toString();\n const negative = coefficient.startsWith(\"-\");\n const digits = BigInt(negative ? coefficient.slice(1) : coefficient)\n .toString()\n .padStart(scale + 1, \"0\");\n return `${negative ? \"-\" : \"\"}${digits.slice(0, -scale)}.${digits.slice(-scale)}`;\n}\n\n/** Whether a date and a clock name a real instant, with nothing rolled over. */\nfunction isCalendarDate(day: string, clock: string): boolean {\n const [year, month, date] = day.split(\"-\").map(Number);\n const [hours, minutes, seconds] = clock.split(\":\").map(Number);\n // `Date.UTC` reads years 0–99 as 1900–1999; `setUTCFullYear` does not.\n const instant = new Date(0);\n instant.setUTCFullYear(year!, month! - 1, date!);\n instant.setUTCHours(hours!, minutes!, Math.trunc(seconds!));\n return (\n instant.getUTCFullYear() === year &&\n instant.getUTCMonth() === month! - 1 &&\n instant.getUTCDate() === date &&\n instant.getUTCHours() === hours &&\n instant.getUTCMinutes() === minutes &&\n instant.getUTCSeconds() === Math.trunc(seconds!)\n );\n}\n\n/** One literal default member, read as the field's own domain. */\nfunction literalValue(\n field: FieldDraft,\n text: string,\n quoted: boolean\n): JsonValue | undefined {\n switch (field.type) {\n case \"string\":\n return quoted ? text : undefined;\n case \"enum\":\n return Array.isArray(field.enum) && field.enum.includes(text)\n ? text\n : undefined;\n case \"int\":\n case \"number\":\n return NUMBER.test(text) &&\n (field.type === \"number\" || INTEGER.test(text))\n ? Number(text)\n : undefined;\n case \"bigint\":\n return INTEGER.test(text)\n ? { $bigint: BigInt(text).toString() }\n : undefined;\n case \"decimal\":\n return NUMBER.test(text) ? text : undefined;\n case \"boolean\": {\n const lower = text.toLowerCase();\n if (lower === \"true\" || lower === \"t\" || lower === \"1\") return true;\n if (lower === \"false\" || lower === \"f\" || lower === \"0\") return false;\n return;\n }\n case \"json\":\n try {\n const parsed: JsonValue = JSON.parse(text);\n return jsonDefault(parsed);\n } catch {\n return;\n }\n case \"datetime\": {\n const match = PG_TIMESTAMP_LITERAL.exec(text);\n if (!match) return;\n // `Date` rolls an impossible date (`2020-02-30`) into another day; such\n // a literal is no instant, so it has no value here.\n if (!isCalendarDate(match[1]!, match[2]!)) return;\n // PostgreSQL prints an offset as `+00`; ISO 8601 wants `+00:00`.\n const zone = match[3] ?? \"Z\";\n const offset = zone.length === 3 ? `${zone}:00` : zone;\n const date = new Date(`${match[1]}T${match[2]}${offset}`);\n return Number.isNaN(date.getTime()) ? undefined : date.toISOString();\n }\n case \"date\":\n return DATE_LITERAL.test(text) && isCalendarDate(text, \"00:00:00\")\n ? text\n : undefined;\n default:\n return;\n }\n}\n\n/**\n * The default of one column, as `default`/`generate` keys on its field draft,\n * or the reason it has no document spelling.\n */\nfunction readDefault(\n field: FieldDraft,\n column: ColumnDef,\n sqlText: string,\n dialect: IntrospectionDialect\n): string | undefined {\n const normalized = normalizeDefault(sqlText, column.type);\n if (normalized === undefined) return; // NULL: no default\n const unsupported = `the default \\`${sqlText}\\` has no document spelling`;\n\n if (\n NOW_DEFAULTS.has(normalized) ||\n NOW_DEFAULTS.has(normalized.toLowerCase())\n ) {\n if (\n field.type === \"datetime\" ||\n field.type === \"date\" ||\n field.type === \"time\"\n ) {\n if (field.array) return unsupported;\n field.generate = { kind: \"now\" };\n return;\n }\n return unsupported;\n }\n if (normalized === \"gen_random_uuid()\" || normalized === \"uuidv7()\") {\n if (field.type !== \"string\" || field.array) return unsupported;\n field.generate = {\n kind: normalized === \"gen_random_uuid()\" ? \"uuid\" : \"uuidv7\",\n };\n return;\n }\n\n // MySQL spells the default of a TEXT, BLOB or JSON column as an expression:\n // the literal in one pair of parentheses.\n const spelled = sqlText.trim();\n const expression =\n dialect === \"mysql\"\n ? MYSQL_EXPRESSION_LITERAL.exec(spelled)?.[1]\n : undefined;\n const quoted = QUOTED.exec(expression ?? spelled);\n const literal = quoted ? unquote(quoted[1]!, dialect) : sqlText.trim();\n if (literal === undefined) return unsupported;\n if (field.array) {\n if (!(quoted && dialect === \"postgresql\")) {\n // SQLite and MySQL hold a list as one JSON text.\n if (!quoted) return unsupported;\n try {\n const values: unknown = JSON.parse(literal);\n if (!Array.isArray(values)) return unsupported;\n const members: JsonValue[] = [];\n for (const value of values) {\n const member =\n value === null\n ? null\n : literalValue(\n field,\n typeof value === \"string\" ? value : JSON.stringify(value),\n typeof value === \"string\"\n );\n if (member === undefined) return unsupported;\n members.push(member);\n }\n field.default = members;\n return;\n } catch {\n return unsupported;\n }\n }\n const members = readArrayLiteralText(literal);\n if (members === undefined) return unsupported;\n const values: JsonValue[] = [];\n for (const member of members) {\n const value = member === null ? null : literalValue(field, member, true);\n if (value === undefined) return unsupported;\n values.push(value);\n }\n field.default = values;\n return;\n }\n // SQLite stores a scalar decimal default as its coefficient.\n const text =\n field.type === \"decimal\" && dialect === \"sqlite\" && INTEGER.test(literal)\n ? coefficientText(literal, field.scale)\n : literal;\n const value = literalValue(field, text, quoted !== null);\n if (value === undefined) return unsupported;\n field.default = value;\n return;\n}\n\n// =============================================================================\n// POSTGRESQL\n// =============================================================================\n\nconst PG_VARCHAR = /^varchar\\((\\d+)\\)$/;\nconst PG_CHAR = /^char\\((\\d+)\\)$/;\nconst PG_BIT = /^(bit|varbit)(\\((\\d+)\\))?$/;\nconst PG_NUMERIC = /^numeric\\((\\d+),(\\d+)\\)$/;\nconst PG_TIMESTAMP = /^timestamp(?:\\((\\d)\\))?( with time zone)?$/;\nconst PG_TIME = /^time(?:\\((\\d)\\))?( with time zone)?$/;\nconst PG_STRING_NATIVES = new Set([\n \"citext\",\n \"xml\",\n \"inet\",\n \"cidr\",\n \"macaddr\",\n \"macaddr8\",\n \"tsvector\",\n \"tsquery\",\n]);\n\nfunction pgNative(type: string): { db: \"pg\"; type: string } {\n return { db: \"pg\", type };\n}\n\n/** PostgreSQL's base type (no `[]`), normalized, as a field draft. */\nfunction postgresBase(\n base: string,\n column: ColumnDef,\n array: boolean\n): FieldDraft | string {\n if (base === \"text\") return { type: \"string\" };\n if (PG_VARCHAR.test(base) || PG_CHAR.test(base))\n return { type: \"string\", native: pgNative(base) };\n if (PG_STRING_NATIVES.has(base))\n return { type: \"string\", native: pgNative(base) };\n const bit = PG_BIT.exec(base);\n if (bit) return { type: \"string\", native: pgNative(base) };\n if (base === \"uuid\")\n // A uuid list keeps the column type itself; a scalar uuid is the uuid\n // domain, whose PostgreSQL storage is this same `uuid` column.\n return array\n ? { type: \"string\", native: pgNative(\"uuid\") }\n : { type: \"string\", generate: { kind: \"uuid\", generate: false } };\n if (base === \"integer\") return { type: \"int\" };\n if (base === \"smallint\" || base === \"oid\")\n return { type: \"int\", native: pgNative(base) };\n if (base === \"bigint\") return { type: \"bigint\" };\n if (base === \"real\") return { type: \"number\", native: pgNative(\"real\") };\n if (base === \"double precision\") return { type: \"number\" };\n if (base === \"boolean\") return { type: \"boolean\" };\n if (base === \"date\") return { type: \"date\" };\n if (base === \"bytea\") return { type: \"blob\" };\n if (base === \"jsonb\") return { type: \"json\" };\n if (base === \"json\") return { type: \"json\", native: pgNative(\"json\") };\n const numeric = PG_NUMERIC.exec(base);\n if (numeric) {\n const descriptor = column.decimal;\n if (descriptor === undefined)\n return `numeric(${numeric[1]},${numeric[2]}) is outside VibORM's fixed-decimal domain`;\n return {\n type: \"decimal\",\n precision: descriptor.precision,\n scale: descriptor.scale,\n };\n }\n if (base === \"numeric\")\n return \"an unconstrained `numeric` has no precision and scale, and a VibORM decimal declares both\";\n if (base === \"varchar\")\n return \"`varchar` without a length has no document spelling (use `text`, or a length)\";\n const timestamp = PG_TIMESTAMP.exec(base);\n if (timestamp) {\n const precision = timestamp[1];\n const zoned = timestamp[2] !== undefined;\n const draft: ValueDraft = { type: \"datetime\" };\n if (!zoned) draft.withoutTimezone = true;\n if (precision !== \"3\") {\n const name = zoned ? \"timestamptz\" : \"timestamp\";\n draft.native = pgNative(\n precision === undefined ? name : `${name}(${precision})`\n );\n }\n return draft;\n }\n const time = PG_TIME.exec(base);\n if (time) {\n const precision = time[1];\n const zoned = time[2] !== undefined;\n const draft: ValueDraft = { type: \"time\" };\n if (zoned || precision !== \"3\") {\n const name = zoned ? \"timetz\" : \"time\";\n draft.native = pgNative(\n precision === undefined ? name : `${name}(${precision})`\n );\n }\n return draft;\n }\n return `the type \\`${column.type}\\` has no VibORM scalar`;\n}\n\nexport function translatePostgresColumn(\n context: ColumnContext\n): ColumnTranslation {\n const { column } = context;\n const array = column.type.endsWith(\"[]\");\n const rawBase = array ? column.type.slice(0, -2) : column.type;\n const enumDef = context.enums.get(rawBase);\n let draft: FieldDraft;\n if (enumDef) {\n draft = { type: \"enum\", enum: [...enumDef.values] };\n } else {\n const base = postgresBase(normalizeType(rawBase), column, array);\n if (typeof base === \"string\") return { skip: base };\n draft = base;\n }\n return finish(draft, context, array, \"postgresql\", enumDef?.name);\n}\n\n/** The modifiers every dialect reads the same way: list, null, default. */\nfunction finish(\n draft: FieldDraft,\n context: ColumnContext,\n array: boolean,\n dialect: IntrospectionDialect,\n enumType?: string,\n approximated?: string\n): ColumnTranslation {\n const { column } = context;\n if (array) {\n if (!LIST_TYPES.has(draft.type))\n return { skip: `a list of ${draft.type} has no VibORM scalar` };\n draft.array = true;\n }\n if (column.nullable) draft.nullable = true;\n let skippedDefault: string | undefined;\n if (context.identity || column.autoIncrement) {\n if (draft.type === \"int\" || draft.type === \"bigint\")\n draft.generate = { kind: \"increment\" };\n else\n skippedDefault = `an auto-increment ${draft.type} has no document spelling`;\n } else if (column.default !== undefined) {\n skippedDefault = readDefault(draft, column, column.default, dialect);\n }\n return {\n field: draft,\n enumType,\n skippedDefault,\n approximated,\n };\n}\n\n// =============================================================================\n// SQLITE\n// =============================================================================\n\nconst SQLITE_ENUM = /^TEXT CHECK\\(/;\nconst SQLITE_ENUM_MEMBER = /'((?:[^']|'')*)'/g;\nconst SQLITE_NOW = \"(strftime('%Y-%m-%dT%H:%M:%fZ','now'))\";\n\n/** The enum values a SQLite CHECK spells, when the driver spells them so. */\nfunction sqliteEnumValues(context: ColumnContext): string[] | undefined {\n const { type } = context.column;\n const open = type.indexOf(\" IN (\");\n if (open === -1) return;\n const values = [...type.slice(open).matchAll(SQLITE_ENUM_MEMBER)].map(\n (match) => match[1]!.replaceAll(\"''\", \"'\")\n );\n return context.enumColumnType(values) === type ? values : undefined;\n}\n\n/** A declared SQLite type outside VibORM's spellings, read by affinity. */\nfunction sqliteAffinity(type: string): FieldDraft {\n if (type.includes(\"INT\")) return { type: \"int\" };\n if (type.includes(\"CHAR\") || type.includes(\"CLOB\") || type.includes(\"TEXT\"))\n return { type: \"string\" };\n if (type === \"\" || type.includes(\"BLOB\")) return { type: \"blob\" };\n if (type.includes(\"REAL\") || type.includes(\"FLOA\") || type.includes(\"DOUB\"))\n return { type: \"number\" };\n if (type.includes(\"BOOL\")) return { type: \"boolean\" };\n if (type.includes(\"DATETIME\") || type.includes(\"TIMESTAMP\"))\n return { type: \"datetime\" };\n if (type === \"DATE\") return { type: \"date\" };\n return { type: \"number\" };\n}\n\nexport function translateSqliteColumn(\n context: ColumnContext\n): ColumnTranslation {\n const { column } = context;\n const type = column.type.trim().toUpperCase();\n if (column.decimal)\n return finish(\n {\n type: \"decimal\",\n precision: column.decimal.precision,\n scale: column.decimal.scale,\n },\n context,\n type === \"TEXT\",\n \"sqlite\"\n );\n if (SQLITE_ENUM.test(column.type)) {\n const values = sqliteEnumValues(context);\n if (values === undefined)\n return { skip: `the CHECK in \\`${column.type}\\` is not a VibORM enum` };\n return finish({ type: \"enum\", enum: values }, context, false, \"sqlite\");\n }\n let draft: FieldDraft;\n let approximated: string | undefined;\n switch (type) {\n case \"TEXT\":\n draft =\n column.default?.trim() === SQLITE_NOW\n ? { type: \"datetime\" }\n : { type: \"string\" };\n break;\n case \"INTEGER\":\n draft = { type: \"int\" };\n break;\n case \"REAL\":\n draft = { type: \"number\" };\n break;\n case \"BLOB\":\n if (context.binaryKey) {\n draft = { type: \"string\", generate: { kind: \"uuid\", generate: false } };\n approximated =\n \"a BLOB key is read as a UUID, the key VibORM stores as sixteen bytes on SQLite; a key holding other bytes does not decode\";\n } else draft = { type: \"blob\" };\n break;\n case \"JSON\":\n draft = { type: \"json\" };\n break;\n default:\n draft = sqliteAffinity(type);\n approximated = `the declared type \\`${column.type}\\` is read by SQLite's affinity rules as ${draft.type}, which VibORM spells \\`${draft.type === \"string\" ? \"TEXT\" : draft.type === \"number\" ? \"REAL\" : draft.type === \"blob\" ? \"BLOB\" : draft.type === \"datetime\" || draft.type === \"date\" ? \"TEXT\" : \"INTEGER\"}\\``;\n }\n return finish(draft, context, false, \"sqlite\", undefined, approximated);\n}\n\n// =============================================================================\n// MYSQL\n// =============================================================================\n\nconst MYSQL_SIZED = /^(varchar|char|binary|varbinary|bit)\\((\\d+)\\)$/;\nconst MYSQL_TEMPORAL = /^(datetime|timestamp|time)(?:\\((\\d)\\))?$/;\nconst MYSQL_INTEGERS = new Set([\n \"tinyint\",\n \"tinyint unsigned\",\n \"smallint\",\n \"smallint unsigned\",\n \"mediumint\",\n \"mediumint unsigned\",\n \"int unsigned\",\n \"year\",\n]);\nconst MYSQL_TEXTS = new Set([\"tinytext\", \"mediumtext\", \"longtext\"]);\nconst MYSQL_BLOBS = new Set([\"tinyblob\", \"mediumblob\", \"longblob\"]);\nconst MYSQL_DISPLAY_WIDTH = /^(tinyint|smallint|mediumint|int|bigint)\\(\\d+\\)/;\n\nfunction mysqlNative(type: string): { db: \"mysql\"; type: string } {\n return { db: \"mysql\", type };\n}\n\n/** MySQL's column type (lowercased, display width dropped) as a field draft. */\nfunction mysqlBase(type: string, context: ColumnContext): FieldDraft | string {\n const { column } = context;\n if (type === \"text\") return { type: \"string\" };\n if (type === \"tinyint(1)\") return { type: \"boolean\" };\n const base = type.replace(MYSQL_DISPLAY_WIDTH, \"$1\");\n if (base === \"int\") return { type: \"int\" };\n if (base === \"bigint\") return { type: \"bigint\" };\n if (base === \"bigint unsigned\")\n return { type: \"bigint\", native: mysqlNative(\"BIGINT UNSIGNED\") };\n if (MYSQL_INTEGERS.has(base))\n return { type: \"int\", native: mysqlNative(base.toUpperCase()) };\n if (base === \"double\") return { type: \"number\" };\n if (base === \"float\") return { type: \"number\", native: mysqlNative(\"FLOAT\") };\n if (base === \"json\") return { type: \"json\" };\n if (base === \"blob\") return { type: \"blob\" };\n if (MYSQL_BLOBS.has(base))\n return { type: \"blob\", native: mysqlNative(base.toUpperCase()) };\n if (MYSQL_TEXTS.has(base))\n return { type: \"string\", native: mysqlNative(base.toUpperCase()) };\n if (base === \"date\") return { type: \"date\" };\n if (base.startsWith(\"decimal(\")) {\n const descriptor = column.decimal;\n if (descriptor === undefined)\n return `${column.type} is outside VibORM's fixed-decimal domain`;\n return {\n type: \"decimal\",\n precision: descriptor.precision,\n scale: descriptor.scale,\n };\n }\n const sized = MYSQL_SIZED.exec(base);\n if (sized) {\n const [, name, size] = sized;\n if (name === \"binary\" && size === \"16\" && context.binaryKey)\n return { type: \"string\", generate: { kind: \"uuid\", generate: false } };\n if (name === \"varchar\" && size === \"191\" && context.keyed)\n return { type: \"string\" };\n const native = mysqlNative(`${name!.toUpperCase()}(${size})`);\n return name === \"binary\" || name === \"varbinary\"\n ? { type: \"blob\", native }\n : { type: \"string\", native };\n }\n const temporal = MYSQL_TEMPORAL.exec(base);\n if (temporal) {\n const [, name, precision] = temporal;\n const draft: ValueDraft = { type: name === \"time\" ? \"time\" : \"datetime\" };\n if (name === \"timestamp\" || precision !== \"3\")\n draft.native = mysqlNative(\n precision === undefined\n ? name!.toUpperCase()\n : `${name!.toUpperCase()}(${precision})`\n );\n return draft;\n }\n return `the type \\`${column.type}\\` has no VibORM scalar`;\n}\n\nexport function translateMysqlColumn(\n context: ColumnContext\n): ColumnTranslation {\n const { column } = context;\n if (column.type.toUpperCase().startsWith(\"ENUM(\")) {\n const enumDef = context.enums.get(column.type);\n if (\n enumDef === undefined ||\n context.enumColumnType(enumDef.values) !== column.type\n )\n return { skip: `the enum \\`${column.type}\\` is not one VibORM spells` };\n return finish(\n { type: \"enum\", enum: [...enumDef.values] },\n context,\n false,\n \"mysql\"\n );\n }\n const base = mysqlBase(column.type.trim().toLowerCase(), context);\n if (typeof base === \"string\") return { skip: base };\n const approximated =\n base.type === \"string\" && base.generate?.kind === \"uuid\"\n ? \"a BINARY(16) key is read as a UUID, the key VibORM stores as sixteen bytes on MySQL; a key holding other bytes does not decode\"\n : undefined;\n return finish(base, context, false, \"mysql\", undefined, approximated);\n}\n\n// =============================================================================\n// SNOWFLAKE\n// =============================================================================\n\nconst SNOWFLAKE_NUMBER = /^number\\((\\d+),(\\d+)\\)$/;\nconst TYPE_PARAMETERS = /\\(.*\\)$/;\nconst SNOWFLAKE_VECTOR = /^vector\\((float|int), (\\d+)\\)$/;\nconst SNOWFLAKE_NOW =\n /^(?:current_timestamp|sysdate|systimestamp|localtimestamp|current_date|current_time|getdate)(?:\\(\\d*\\))?$/i;\n\n/**\n * Snowflake's column type (as its introspection spells it, lower case) as a\n * field draft. A `NUMBER(p,0)` wider than nine digits is a `bigint`, so no\n * integer past 2^53 is read through a JavaScript number; Snowflake's own\n * `INTEGER` is `NUMBER(38,0)`.\n */\nfunction snowflakeBase(column: ColumnDef): FieldDraft | string {\n const type = column.type.toLowerCase();\n const number = SNOWFLAKE_NUMBER.exec(type);\n if (number) {\n const precision = Number(number[1]);\n const scale = Number(number[2]);\n if (scale === 0) return { type: precision <= 9 ? \"int\" : \"bigint\" };\n return { type: \"decimal\", precision, scale };\n }\n const base = type.replace(TYPE_PARAMETERS, \"\");\n switch (base) {\n case \"float\":\n return { type: \"number\" };\n case \"varchar\":\n return { type: \"string\" };\n case \"boolean\":\n return { type: \"boolean\" };\n case \"date\":\n return { type: \"date\" };\n case \"time\":\n return { type: \"time\" };\n case \"timestamp_ntz\":\n case \"timestamp_ltz\":\n case \"timestamp_tz\":\n return { type: \"datetime\" };\n case \"binary\":\n return { type: \"blob\" };\n case \"variant\":\n case \"object\":\n case \"array\":\n return { type: \"json\" };\n case \"geography\":\n return { type: \"point\" };\n case \"geometry\":\n return \"a GEOMETRY is planar, in any SRID: VibORM's point is a geographic EPSG:4326 point (a GEOGRAPHY)\";\n default:\n break;\n }\n const vector = SNOWFLAKE_VECTOR.exec(type);\n if (vector?.[1] === \"float\")\n return { type: \"vector\", dimension: Number(vector[2]) };\n if (vector)\n return \"a VECTOR(INT) has no VibORM scalar: `s.vector()` holds floats\";\n return `the type \\`${column.type.toUpperCase()}\\` has no VibORM scalar`;\n}\n\nexport function translateSnowflakeColumn(\n context: ColumnContext\n): ColumnTranslation {\n const { column } = context;\n const base = snowflakeBase(column);\n if (typeof base === \"string\") return { skip: base };\n const timestamp = column.type.toLowerCase().replace(TYPE_PARAMETERS, \"\");\n const approximated =\n timestamp === \"timestamp_ntz\"\n ? \"a TIMESTAMP_NTZ holds a wall clock with no zone; VibORM reads it as UTC\"\n : timestamp === \"geography\"\n ? \"a GEOGRAPHY may hold any shape; VibORM reads it as a point, and a row holding another shape does not decode\"\n : undefined;\n // Snowflake's clocks are functions VibORM's generator stands for.\n if (\n column.default !== undefined &&\n SNOWFLAKE_NOW.test(column.default.trim()) &&\n (base.type === \"datetime\" || base.type === \"date\" || base.type === \"time\")\n ) {\n base.generate = { kind: \"now\" };\n const { default: _clock, ...rest } = column;\n return finish(\n base,\n { ...context, column: rest },\n false,\n \"snowflake\",\n undefined,\n approximated\n );\n }\n return finish(base, context, false, \"snowflake\", undefined, approximated);\n}\n","/**\n * Document keys from database names.\n *\n * A database name is kept as the key whenever it is a schema identifier; only a\n * name that is not one gets a derived key, and the model or field then carries\n * the real name (`table` / `column`). Every derivation is deterministic: the\n * same database gives the same document.\n */\n\nimport { isValidSchemaIdentifier } from \"../../schema/identifier\";\n\n/** F010's reserved member names: a column may not take them as its key. */\nconst RESERVED_MEMBERS = new Set([\"_count\", \"_distance\"]);\n\nconst INVALID_CHARACTER = /[^a-zA-Z0-9_]/g;\nconst LEADING_DIGIT = /^[0-9]/;\n\n/** The key a database name would take if it were free. */\nfunction keyCandidate(name: string): string {\n let key = name.replace(INVALID_CHARACTER, \"_\");\n if (key === \"\" || LEADING_DIGIT.test(key)) key = `_${key}`;\n return key.slice(0, 60);\n}\n\n/** One namespace of keys: a document's models, or one model's members. */\nexport class KeyAllocator {\n readonly #taken = new Set<string>();\n readonly #reserved: ReadonlySet<string>;\n\n constructor(reserved: ReadonlySet<string> = new Set()) {\n this.#reserved = reserved;\n }\n\n #free(key: string): boolean {\n return (\n !(this.#taken.has(key) || this.#reserved.has(key)) &&\n isValidSchemaIdentifier(key)\n );\n }\n\n /**\n * The database name itself when it is a free identifier, else the first free\n * of its sanitized spelling and that spelling suffixed `_2`, `_3` …\n */\n claimName(name: string): string {\n if (this.#free(name)) {\n this.#taken.add(name);\n return name;\n }\n return this.claim(keyCandidate(name));\n }\n\n /** `base`, else `base_2`, `base_3` … — the first that is free. */\n claim(base: string): string {\n const root = keyCandidate(base);\n let key = root;\n for (let n = 2; !this.#free(key); n++) key = `${root}_${n}`;\n this.#taken.add(key);\n return key;\n }\n}\n\n/** A member allocator: model members may not take F010's reserved names. */\nexport function memberAllocator(): KeyAllocator {\n return new KeyAllocator(RESERVED_MEMBERS);\n}\n\nconst SNAKE_ID_SUFFIX = /^(.+)_id$/i;\nconst CAMEL_ID_SUFFIX = /^(.*[a-z0-9])I[dD]$/;\n\n/**\n * The relation name a single foreign-key column suggests: `author_id` and\n * `authorId` both suggest `author`. Anything else suggests nothing, and the\n * caller falls back on the target's key.\n */\nexport function relationNameFromColumn(column: string): string | undefined {\n const match = SNAKE_ID_SUFFIX.exec(column) ?? CAMEL_ID_SUFFIX.exec(column);\n return match?.[1];\n}\n","/**\n * A live snapshot → a schema document (the draft `index.ts` canonicalizes).\n *\n * Pure: it reads the snapshot the dialect's own introspection wrote and the\n * catalog facts beside it, and says what it could not carry. Database names are\n * kept as document keys; a relation, which has no database name, is named from\n * its foreign key by one deterministic rule (see `relationNames`).\n */\n\nimport { isValidSchemaIdentifier } from \"../../schema/identifier\";\nimport {\n type EnumDocument,\n type FieldDocument,\n type IndexDocument,\n isRelationField,\n type JunctionDocument,\n type JunctionSidesDocument,\n type ModelDocument,\n type ModelTargetDocument,\n type SchemaDocument,\n} from \"../../schema/json/document\";\nimport type { JunctionReferentialAction } from \"../../schema/relation/types\";\nimport type { MigrationDriver } from \"../drivers/base\";\nimport type {\n EnumDef,\n ForeignKeyDef,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n} from \"../types\";\nimport { derivedMigrationName } from \"../utils\";\nimport {\n type ColumnContext,\n type ColumnTranslation,\n translateMysqlColumn,\n translatePostgresColumn,\n translateSnowflakeColumn,\n translateSqliteColumn,\n} from \"./columns\";\nimport { KeyAllocator, memberAllocator, relationNameFromColumn } from \"./names\";\nimport type {\n IntrospectionDialect,\n IntrospectionWarning,\n SkippedObject,\n} from \"./types\";\n\nexport interface TranslateInput {\n readonly snapshot: SchemaSnapshot;\n readonly dialect: IntrospectionDialect;\n readonly migrationDriver: MigrationDriver;\n /** PostgreSQL identity columns, keyed `table\\0column`. */\n readonly identityColumns: ReadonlySet<string>;\n /** Pure join tables to keep as a junction MODEL rather than a generated junction. */\n readonly junctionModels: ReadonlySet<string>;\n}\n\nexport interface Translation {\n readonly document: SchemaDocument;\n readonly skipped: SkippedObject[];\n readonly warnings: IntrospectionWarning[];\n /** The tables the document declares, models and generated junctions alike. */\n readonly tables: ReadonlySet<string>;\n /** The pure join tables written as a generated junction. */\n readonly generatedJunctions: ReadonlySet<string>;\n}\n\n/** One model under construction. */\ninterface ModelBuild {\n readonly key: string;\n readonly table: TableDef;\n readonly members: KeyAllocator;\n readonly fields: Record<string, FieldDocument>;\n /** Column name → field key, for the translated columns. */\n readonly fieldOf: Map<string, string>;\n readonly document: ModelDocument;\n /** Column sets the document declares unique (id, unique, uniques), sorted. */\n readonly keys: string[][];\n}\n\nconst TRANSLATORS: Record<\n IntrospectionDialect,\n (context: ColumnContext) => ColumnTranslation\n> = {\n postgresql: translatePostgresColumn,\n sqlite: translateSqliteColumn,\n mysql: translateMysqlColumn,\n snowflake: translateSnowflakeColumn,\n};\n\nconst BINARY_KEY_TYPES: Record<IntrospectionDialect, string | undefined> = {\n postgresql: undefined,\n sqlite: \"BLOB\",\n mysql: \"BINARY(16)\",\n snowflake: undefined,\n};\n\n/** `.map()` takes identifiers only, so a name outside them has no spelling. */\nconst UNMAPPABLE =\n \"its name is not an identifier (ASCII letters, digits and _, at most 63 bytes), which is all `.map()` accepts\";\n\n/** The warning a key column the database lets hold NULL carries. */\nconst NULLABLE_KEY =\n \"the database lets this primary key column hold NULL (SQLite does unless it is NOT NULL, outside a rowid table's INTEGER key), and the document declares it NOT NULL, as every model key is: a push of the document rebuilds the table to make it NOT NULL, which fails while a row's key is NULL and cannot keep what the table carries beyond the document (its `unstated` warnings)\";\n\n/** A junction foreign key's action: cascade, restrict or no action only. */\nfunction junctionAction(\n value: ReferentialAction | undefined\n): JunctionReferentialAction | undefined {\n const spelled = value ?? \"noAction\";\n return spelled === \"cascade\" ||\n spelled === \"restrict\" ||\n spelled === \"noAction\"\n ? spelled\n : undefined;\n}\n\n/** One action for both junction keys, or one per side (`source` first). */\ntype DeleteSpelling =\n | { onDelete: JunctionReferentialAction; onDeleteSides?: never }\n | { onDelete?: never; onDeleteSides: JunctionSidesDocument };\ntype UpdateSpelling =\n | { onUpdate: JunctionReferentialAction; onUpdateSides?: never }\n | { onUpdate?: never; onUpdateSides: JunctionSidesDocument };\n\n/**\n * The generated junction a pure join table is, named by its two key columns,\n * or `undefined` when either key has an action a junction cannot declare.\n */\nfunction generatedJunction(\n table: string,\n first: ForeignKeyDef,\n second: ForeignKeyDef\n): JunctionDocument | undefined {\n const deleteSource = junctionAction(first.onDelete);\n const deleteTarget = junctionAction(second.onDelete);\n const updateSource = junctionAction(first.onUpdate);\n const updateTarget = junctionAction(second.onUpdate);\n if (\n deleteSource === undefined ||\n deleteTarget === undefined ||\n updateSource === undefined ||\n updateTarget === undefined\n )\n return;\n const deletes: DeleteSpelling =\n deleteSource === deleteTarget\n ? { onDelete: deleteSource }\n : { onDeleteSides: { source: deleteSource, target: deleteTarget } };\n const updates: UpdateSpelling =\n updateSource === updateTarget\n ? { onUpdate: updateSource }\n : { onUpdateSides: { source: updateSource, target: updateTarget } };\n return {\n table,\n source: first.columns[0]!,\n target: second.columns[0]!,\n ...deletes,\n ...updates,\n };\n}\n\nfunction sameSet(a: readonly string[], b: readonly string[]): boolean {\n return a.length === b.length && a.every((item) => b.includes(item));\n}\n\nfunction sorted(columns: readonly string[]): string[] {\n return [...columns].sort();\n}\n\n/** One relation pair between two models, before its label is decided. */\ninterface Pair {\n readonly models: readonly [string, string];\n readonly label: string;\n readonly slots: Array<{ model: ModelBuild; key: string }>;\n}\n\nexport function translateSnapshot(input: TranslateInput): Translation {\n const { snapshot, dialect, migrationDriver } = input;\n const skipped: SkippedObject[] = [];\n const warnings: IntrospectionWarning[] = [];\n const readsNames =\n migrationDriver.capabilities.introspectionReadsConstraintNames;\n const enums = new Map<string, EnumDef>(\n (snapshot.enums ?? []).map((item) => [item.name, item])\n );\n const translateColumn: (context: ColumnContext) => ColumnTranslation =\n TRANSLATORS[dialect];\n\n // SQLite and MySQL store a uuid key as bytes (`BLOB`, `BINARY(16)`), and a\n // blob is never a key: such a primary-key column, and every foreign-key\n // column reaching one, is read as the uuid key it is VibORM's spelling of.\n const binaryKeys = new Set<string>();\n const binaryKeyType = BINARY_KEY_TYPES[dialect];\n if (binaryKeyType !== undefined) {\n const isBlob = (table: TableDef, column: string) =>\n table.columns.find((item) => item.name === column)?.type.toUpperCase() ===\n binaryKeyType;\n for (const table of snapshot.tables)\n for (const column of table.primaryKey?.columns ?? [])\n if (isBlob(table, column)) binaryKeys.add(`${table.name}\\0${column}`);\n for (let grew = true; grew; ) {\n grew = false;\n for (const table of snapshot.tables)\n for (const fk of table.foreignKeys)\n fk.columns.forEach((column, position) => {\n const id = `${table.name}\\0${column}`;\n const referenced = `${fk.referencedTable}\\0${fk.referencedColumns[position]}`;\n if (\n !binaryKeys.has(id) &&\n binaryKeys.has(referenced) &&\n isBlob(table, column)\n ) {\n binaryKeys.add(id);\n grew = true;\n }\n });\n }\n }\n\n // MySQL writes an indexed string as VARCHAR(191): the columns of a key, an\n // index or a foreign key.\n const keyedColumns = (table: TableDef) =>\n new Set([\n ...(table.primaryKey?.columns ?? []),\n ...table.uniqueConstraints.flatMap((unique) => unique.columns),\n ...table.indexes.flatMap((index) => (index.raw ? [] : index.columns)),\n ...table.foreignKeys.flatMap((foreignKey) => foreignKey.columns),\n ]);\n\n const modelKeys = new KeyAllocator();\n const builds = new Map<string, ModelBuild>();\n /** Enum type name → the columns using it. */\n const enumUses = new Map<\n string,\n Array<{ build: ModelBuild; field: string; column: string }>\n >();\n\n // ---------------------------------------------------------------------------\n // Tables → models with their scalar fields\n // ---------------------------------------------------------------------------\n for (const table of snapshot.tables) {\n const primaryKey = table.primaryKey;\n if (!primaryKey || primaryKey.columns.length === 0) {\n skipped.push({\n kind: \"table\",\n name: table.name,\n reason: \"it has no primary key, and a VibORM model is addressed by one\",\n });\n continue;\n }\n if (!isValidSchemaIdentifier(table.name)) {\n skipped.push({\n kind: \"table\",\n name: table.name,\n reason: UNMAPPABLE,\n });\n continue;\n }\n const translated = new Map<string, ColumnTranslation>();\n const keyed = keyedColumns(table);\n for (const column of table.columns) {\n if (!isValidSchemaIdentifier(column.name)) {\n translated.set(column.name, { skip: UNMAPPABLE });\n continue;\n }\n translated.set(\n column.name,\n translateColumn({\n column,\n enums,\n identity: input.identityColumns.has(`${table.name}\\0${column.name}`),\n enumColumnType: (values) =>\n migrationDriver.getEnumColumnType(table.name, column.name, values),\n binaryKey: binaryKeys.has(`${table.name}\\0${column.name}`),\n keyed: keyed.has(column.name),\n })\n );\n }\n const lostKey = primaryKey.columns.find((column) => {\n const result = translated.get(column);\n return result === undefined || \"skip\" in result;\n });\n if (lostKey !== undefined) {\n const result = translated.get(lostKey);\n skipped.push({\n kind: \"table\",\n name: table.name,\n reason: `its primary key column \"${lostKey}\" cannot be translated: ${result && \"skip\" in result ? result.skip : \"it is not a column of the table\"}`,\n });\n continue;\n }\n\n const key = modelKeys.claimName(table.name);\n const fields: Record<string, FieldDocument> = {};\n const document: ModelDocument = { fields };\n if (key !== table.name) document.table = table.name;\n const build: ModelBuild = {\n key,\n table,\n members: memberAllocator(),\n fields,\n fieldOf: new Map(),\n document,\n keys: [],\n };\n for (const column of table.columns) {\n const result = translated.get(column.name)!;\n if (\"skip\" in result) {\n skipped.push({\n kind: \"column\",\n table: table.name,\n name: column.name,\n reason: result.skip,\n });\n continue;\n }\n const fieldKey = build.members.claimName(column.name);\n const field = { ...result.field };\n if (fieldKey !== column.name) field.column = column.name;\n fields[fieldKey] = field;\n build.fieldOf.set(column.name, fieldKey);\n if (result.enumType !== undefined) {\n const uses = enumUses.get(result.enumType) ?? [];\n uses.push({ build, field: fieldKey, column: column.name });\n enumUses.set(result.enumType, uses);\n }\n if (result.skippedDefault !== undefined)\n skipped.push({\n kind: \"default\",\n table: table.name,\n name: column.name,\n reason: result.skippedDefault,\n });\n if (result.approximated !== undefined)\n warnings.push({\n kind: \"approximated\",\n table: table.name,\n name: column.name,\n message: result.approximated,\n });\n }\n\n // The primary key\n const pkFields = primaryKey.columns.map(\n (column) => build.fieldOf.get(column)!\n );\n // SQLite admits NULL in a key column other than a rowid table's INTEGER\n // key unless it is declared NOT NULL; a model key never holds one.\n pkFields.forEach((fieldKey, position) => {\n const field = fields[fieldKey]!;\n if (isRelationField(field) || !field.nullable) return;\n field.nullable = false;\n warnings.push({\n kind: \"approximated\",\n table: table.name,\n name: primaryKey.columns[position],\n message: NULLABLE_KEY,\n });\n });\n if (pkFields.length === 1) {\n const field = fields[pkFields[0]!]!;\n if (field.type !== \"toOne\" && field.type !== \"toMany\") {\n Object.assign(field, { id: true });\n // `.id()` on a string installs a ULID generator; a database cannot\n // prove the application generated its keys, so none is claimed.\n if (field.type === \"string\" && field.generate === undefined)\n Object.assign(field, {\n generate: { kind: \"ulid\", generate: false, implicit: true },\n });\n }\n } else {\n document.ids = [{ fields: pkFields }];\n }\n // SQLite's `WITHOUT ROWID`: the rows are clustered by this key.\n if (primaryKey.withoutRowid) document.withoutRowid = true;\n build.keys.push(sorted(primaryKey.columns));\n builds.set(table.name, build);\n }\n\n // ---------------------------------------------------------------------------\n // Unique constraints and indexes\n // ---------------------------------------------------------------------------\n for (const build of builds.values()) {\n const { table, fields, document, fieldOf } = build;\n const indexes: IndexDocument[] = [];\n const uniques: Array<{ fields: string[]; name?: string }> = [];\n const missing = (columns: readonly string[]) =>\n columns.find((column) => !fieldOf.has(column));\n\n // A total unique btree index IS a unique constraint to the differ (and\n // the only spelling MySQL has): one named the way a declared key is named\n // is read as that key, so it stays a `findUnique` key.\n const derivedUnique = (name: string, columns: readonly string[]) =>\n name.startsWith(`${table.name}_`) &&\n name.endsWith(\"_key\") &&\n columns.every((column) => fieldOf.has(column));\n const keyIndexes = table.indexes.filter(\n (index) =>\n index.unique &&\n !index.raw &&\n index.where === undefined &&\n (index.type === undefined || index.type === \"btree\") &&\n derivedUnique(index.name, index.columns)\n );\n const uniqueConstraints = [\n ...table.uniqueConstraints,\n ...keyIndexes.map((index) => ({\n name: index.name,\n columns: index.columns,\n })),\n ];\n for (const constraint of uniqueConstraints) {\n const lost = missing(constraint.columns);\n if (lost !== undefined) {\n skipped.push({\n kind: \"uniqueConstraint\",\n table: table.name,\n name: constraint.name,\n reason: `its column \"${lost}\" is not translated`,\n });\n continue;\n }\n const keys = constraint.columns.map((column) => fieldOf.get(column)!);\n const derived = (name: string) =>\n derivedMigrationName(`${table.name}_${name}_key`);\n if (\n keys.length === 1 &&\n (!readsNames || constraint.name === derived(constraint.columns[0]!))\n ) {\n Object.assign(fields[keys[0]!]!, { unique: true });\n build.keys.push(sorted(constraint.columns));\n continue;\n }\n if (!readsNames || constraint.name === derived(keys.join(\"_\"))) {\n uniques.push({ fields: keys });\n build.keys.push(sorted(constraint.columns));\n continue;\n }\n const prefix = `${table.name}_`;\n const named =\n constraint.name.startsWith(prefix) && constraint.name.endsWith(\"_key\")\n ? constraint.name.slice(prefix.length, -\"_key\".length)\n : undefined;\n if (named !== undefined && isValidSchemaIdentifier(named)) {\n uniques.push({ fields: keys, name: named });\n build.keys.push(sorted(constraint.columns));\n continue;\n }\n // A total unique btree index and a unique constraint enforce the same\n // key and the differ treats them as one; only the index spelling\n // carries an arbitrary name.\n indexes.push({ fields: keys, name: constraint.name, unique: true });\n warnings.push({\n kind: \"approximated\",\n table: table.name,\n name: constraint.name,\n message: `the unique constraint \"${constraint.name}\" is declared as a unique index under the same name, because a document names compound keys \"<table>_<name>_key\"; it is not a key \\`findUnique\\` accepts`,\n });\n }\n\n for (const index of table.indexes) {\n if (keyIndexes.includes(index)) continue;\n const lost = missing(index.columns);\n const reason = index.raw\n ? \"it is a raw index (`.rawIndex()`), which a document cannot declare: keep it in a TypeScript schema\"\n : index.where !== undefined\n ? `it is a partial index (WHERE ${index.where}), and a document has no \\`where\\`: keep it in a TypeScript schema`\n : lost !== undefined\n ? `its column \"${lost}\" is not translated`\n : undefined;\n if (reason !== undefined) {\n skipped.push({\n kind: \"index\",\n table: table.name,\n name: index.name,\n reason,\n });\n continue;\n }\n const declared: IndexDocument = {\n fields: index.columns.map((column) => fieldOf.get(column)!),\n name: index.name,\n };\n if (index.unique) declared.unique = true;\n if (index.type !== undefined && index.type !== \"btree\")\n declared.type = index.type;\n indexes.push(declared);\n }\n if (uniques.length > 0) document.uniques = uniques;\n if (indexes.length > 0) document.indexes = indexes;\n }\n\n // ---------------------------------------------------------------------------\n // Foreign keys → relations\n // ---------------------------------------------------------------------------\n interface Edge {\n readonly owner: ModelBuild;\n readonly target: ModelBuild;\n readonly fk: ForeignKeyDef;\n }\n const edgesByOwner = new Map<ModelBuild, Edge[]>();\n for (const owner of builds.values()) {\n const edges: Edge[] = [];\n const foreignKeys = [...owner.table.foreignKeys].sort((a, b) =>\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0\n );\n for (const fk of foreignKeys) {\n const target = builds.get(fk.referencedTable);\n const skip = (reason: string) =>\n skipped.push({\n kind: \"foreignKey\",\n table: owner.table.name,\n name: fk.name,\n reason,\n });\n if (target === undefined) {\n skip(\n `it references \"${fk.referencedTable}\", which the document does not declare`\n );\n continue;\n }\n const lostOwn = fk.columns.find((column) => !owner.fieldOf.has(column));\n const lostRef = fk.referencedColumns.find(\n (column) => !target.fieldOf.has(column)\n );\n if (lostOwn !== undefined || lostRef !== undefined) {\n skip(\n `its column \"${lostOwn ?? `${fk.referencedTable}.${lostRef}`}\" is not translated`\n );\n continue;\n }\n if (fk.onDelete === \"setDefault\" || fk.onUpdate === \"setDefault\") {\n skip(\n \"its referential action is SET DEFAULT, which a VibORM relation does not declare\"\n );\n continue;\n }\n if (!target.keys.some((key) => sameSet(key, fk.referencedColumns))) {\n skip(\n `it references (${fk.referencedColumns.join(\", \")}) of \"${fk.referencedTable}\", which the document does not declare as a key`\n );\n continue;\n }\n edges.push({ owner, target, fk });\n }\n edgesByOwner.set(owner, edges);\n }\n\n /**\n * A pure join table: two foreign keys, together exactly its columns and its\n * primary key, each referencing its target's primary key.\n */\n const joinTables = new Map<ModelBuild, readonly [Edge, Edge]>();\n for (const [owner, edges] of edgesByOwner) {\n const [first, second] = edges;\n if (edges.length !== 2 || first === undefined || second === undefined)\n continue;\n const table = owner.table;\n // A table another foreign key references is a row of its own, never a\n // junction: the reference would have no model to reach.\n if (\n snapshot.tables.some(\n (other) =>\n other !== table &&\n other.foreignKeys.some((fk) => fk.referencedTable === table.name)\n )\n )\n continue;\n const columns = table.columns.map((column) => column.name);\n const union = [...first.fk.columns, ...second.fk.columns];\n if (\n table.foreignKeys.length !== 2 ||\n first.fk.columns.some((column) => second.fk.columns.includes(column)) ||\n !sameSet(union, columns) ||\n !sameSet(table.primaryKey?.columns ?? [], columns) ||\n !edges.every((edge) =>\n sameSet(\n edge.fk.referencedColumns,\n edge.target.table.primaryKey?.columns ?? []\n )\n )\n )\n continue;\n joinTables.set(owner, [first, second]);\n }\n\n const pairs = new Map<string, Pair[]>();\n const addPair = (\n a: ModelBuild,\n b: ModelBuild,\n label: string,\n slots: Array<{ model: ModelBuild; key: string }>\n ) => {\n const models: readonly [string, string] =\n a.key < b.key ? [a.key, b.key] : [b.key, a.key];\n const id = models.join(\"\\0\");\n const list = pairs.get(id) ?? [];\n list.push({ models, label, slots });\n pairs.set(id, list);\n };\n\n const generatedJunctions = new Set<string>();\n const action = (\n value: ReferentialAction | undefined\n ): Exclude<ReferentialAction, \"setDefault\"> =>\n value === undefined || value === \"setDefault\" ? \"noAction\" : value;\n\n /** The to-one a foreign key gives its owner, and the inverse on its target. */\n const relationNames = (edge: Edge, siblings: readonly Edge[]) => {\n const { owner, target, fk } = edge;\n const single =\n fk.columns.length === 1\n ? relationNameFromColumn(owner.fieldOf.get(fk.columns[0]!)!)\n : undefined;\n const toOne = owner.members.claim(single ?? target.key);\n const shared =\n owner === target ||\n siblings.filter((other) => other.target === target).length > 1;\n const inverse = target.members.claim(\n shared ? `${owner.key}_by_${toOne}` : owner.key\n );\n return { toOne, inverse };\n };\n\n for (const owner of builds.values()) {\n const edges = edgesByOwner.get(owner) ?? [];\n const join = joinTables.get(owner);\n if (join) {\n const [first, second] = join;\n const junction =\n first.fk.columns.length === 1 && second.fk.columns.length === 1\n ? generatedJunction(owner.table.name, first.fk, second.fk)\n : undefined;\n const asGenerated =\n !input.junctionModels.has(owner.table.name) && junction !== undefined;\n if (asGenerated) {\n // The table is the generated junction of one many-to-many pair; it is\n // not a model. `verify.ts` keeps this form only when the junction the\n // pair generates IS this table, and demotes it to a model otherwise.\n builds.delete(owner.table.name);\n generatedJunctions.add(owner.table.name);\n const a = first.target;\n const b = second.target;\n const aName = a.members.claim(\n relationNameFromColumn(second.fk.columns[0]!) ?? b.key\n );\n const bName = b.members.claim(\n relationNameFromColumn(first.fk.columns[0]!) ?? a.key\n );\n a.fields[aName] = { type: \"toMany\", target: b.key, junction };\n b.fields[bName] = { type: \"toMany\", target: a.key };\n addPair(a, b, owner.table.name, [\n { model: a, key: aName },\n { model: b, key: bName },\n ]);\n continue;\n }\n }\n\n const names = new Map<Edge, { toOne: string; inverse: string }>();\n for (const edge of edges) {\n const { target, fk } = edge;\n const { toOne, inverse } = relationNames(edge, edges);\n names.set(edge, { toOne, inverse });\n const relation: ModelTargetDocument = {\n type: \"toOne\",\n target: target.key,\n fields: fk.columns.map((column) => owner.fieldOf.get(column)!),\n references: fk.referencedColumns.map(\n (column) => target.fieldOf.get(column)!\n ),\n onDelete: action(fk.onDelete),\n onUpdate: action(fk.onUpdate),\n };\n owner.fields[toOne] = relation;\n const unique = owner.keys.some((key) => sameSet(key, fk.columns));\n target.fields[inverse] = unique\n ? { type: \"toOne\", target: owner.key }\n : { type: \"toMany\", target: owner.key };\n addPair(owner, target, fk.name, [\n { model: owner, key: toOne },\n { model: target, key: inverse },\n ]);\n }\n\n if (join) {\n // A junction model: the table keeps its own shape, and the many-to-many\n // walks through it.\n const [first, second] = join;\n const a = first.target;\n const b = second.target;\n const firstName = names.get(first)!.toOne;\n const secondName = names.get(second)!.toOne;\n const aName = a.members.claim(secondName);\n const bName = b.members.claim(firstName);\n a.fields[aName] = {\n type: \"toMany\",\n target: b.key,\n junction: { model: owner.key, source: firstName, target: secondName },\n };\n b.fields[bName] = { type: \"toMany\", target: a.key };\n addPair(a, b, owner.table.name, [\n { model: a, key: aName },\n { model: b, key: bName },\n ]);\n }\n }\n\n // A pairing label where two models share more than one relation, or a\n // model relates to itself: the label is the foreign key's (or the join\n // table's) name, unique per pair of models.\n for (const list of pairs.values()) {\n const ambiguous =\n list.length > 1 || list[0]!.models[0] === list[0]!.models[1];\n if (!ambiguous) continue;\n for (const pair of list)\n for (const slot of pair.slots)\n Object.assign(slot.model.fields[slot.key]!, { name: pair.label });\n }\n\n // ---------------------------------------------------------------------------\n // Enums\n // ---------------------------------------------------------------------------\n const enumDocuments: Record<string, EnumDocument> = {};\n const enumKeys = new KeyAllocator();\n // Only PostgreSQL has enums of its own; a MySQL enum IS its column's type,\n // already inline on the field.\n for (const [name, def] of dialect === \"postgresql\" ? enums : []) {\n const uses = (enumUses.get(name) ?? []).filter((use) =>\n builds.has(use.build.table.name)\n );\n if (uses.length === 0) {\n skipped.push({\n kind: \"enum\",\n name,\n reason:\n \"no translated column uses it, and a document declares an enum through its fields\",\n });\n continue;\n }\n const only = uses.length === 1 ? uses[0]! : undefined;\n if (\n only &&\n migrationDriver.getEnumColumnType(\n only.build.table.name,\n only.column,\n def.values\n ) === name\n )\n continue; // the column's own derived type: inline values say exactly this\n const key = enumKeys.claimName(name);\n enumDocuments[key] = { values: [...def.values], name };\n for (const use of uses)\n Object.assign(use.build.fields[use.field]!, { enum: key });\n }\n\n const models: Record<string, ModelDocument> = {};\n for (const build of builds.values()) models[build.key] = build.document;\n const document: SchemaDocument = {\n version: 1,\n ...(Object.keys(enumDocuments).length > 0 ? { enums: enumDocuments } : {}),\n models,\n };\n return {\n document,\n skipped,\n warnings,\n tables: new Set([\n ...[...builds.values()].map((build) => build.table.name),\n ...generatedJunctions,\n ]),\n generatedJunctions,\n };\n}\n","/**\n * The proof that a document says what the database is.\n *\n * The document is parsed, validated, and serialized exactly as `push`\n * serializes a schema, then diffed against the snapshot the database was read\n * into, with the differ `push` uses. Every operation that diff plans is a place\n * where the document and the database disagree, reported as a `drift` warning:\n * a document with none pushes as a no-op. The translation never has to be\n * trusted to be the exact inverse of the forward direction — this runs it.\n */\n\nimport { hydrateSchemaNames } from \"../../schema/hydration\";\nimport { parseSchema } from \"../../schema/json\";\nimport type { SchemaDocument } from \"../../schema/json/document\";\nimport { diff } from \"../differ\";\nimport type { MigrationDriver } from \"../drivers/base\";\nimport { serializeModels } from \"../serializer\";\nimport type { ColumnDef, DiffOperation, SchemaSnapshot } from \"../types\";\nimport type { IntrospectionWarning } from \"./types\";\n\nfunction describeColumn(column: ColumnDef): string {\n return `${column.type}${column.nullable ? \" NULL\" : \" NOT NULL\"}${column.default === undefined ? \"\" : ` DEFAULT ${column.default}`}`;\n}\n\n/** An operation's kind, for one this file has no sentence for. */\nfunction operationType(operation: { readonly type: string }): string {\n return operation.type;\n}\n\nfunction describe(operation: DiffOperation): IntrospectionWarning {\n const push = (\n table: string | undefined,\n name: string | undefined,\n message: string\n ) => ({\n kind: \"drift\" as const,\n table,\n name,\n message: `push would ${message}`,\n });\n switch (operation.type) {\n case \"createTable\":\n return push(\n operation.table.name,\n undefined,\n `create table \"${operation.table.name}\"`\n );\n case \"dropTable\":\n return push(\n operation.tableName,\n undefined,\n `drop table \"${operation.tableName}\"`\n );\n case \"addColumn\":\n return push(\n operation.tableName,\n operation.column.name,\n `add column \"${operation.column.name}\" (${describeColumn(operation.column)})`\n );\n case \"dropColumn\":\n return push(\n operation.tableName,\n operation.columnName,\n `drop column \"${operation.columnName}\"`\n );\n case \"alterColumn\":\n return push(\n operation.tableName,\n operation.columnName,\n `alter column \"${operation.columnName}\" from ${describeColumn(operation.from)} to ${describeColumn(operation.to)}`\n );\n case \"createIndex\":\n return push(\n operation.tableName,\n operation.index.name,\n `create index \"${operation.index.name}\" on (${operation.index.columns.join(\", \")})`\n );\n case \"dropIndex\":\n return push(\n operation.tableName,\n operation.indexName,\n `drop index \"${operation.indexName}\"`\n );\n case \"addForeignKey\":\n return push(\n operation.tableName,\n operation.fk.name,\n `add foreign key \"${operation.fk.name}\" on (${operation.fk.columns.join(\", \")})`\n );\n case \"dropForeignKey\":\n return push(\n operation.tableName,\n operation.fkName,\n `drop foreign key \"${operation.fkName}\"`\n );\n case \"addUniqueConstraint\":\n return push(\n operation.tableName,\n operation.constraint.name,\n `add unique constraint \"${operation.constraint.name}\" on (${operation.constraint.columns.join(\", \")})`\n );\n case \"dropUniqueConstraint\":\n return push(\n operation.tableName,\n operation.constraintName,\n `drop unique constraint \"${operation.constraintName}\"`\n );\n case \"addPrimaryKey\":\n return push(\n operation.tableName,\n operation.primaryKey.name,\n `add a primary key on (${operation.primaryKey.columns.join(\", \")})`\n );\n case \"dropPrimaryKey\":\n return push(\n operation.tableName,\n operation.constraintName,\n `drop primary key \"${operation.constraintName}\"`\n );\n case \"createEnum\":\n return push(\n undefined,\n operation.enumDef.name,\n `create enum \"${operation.enumDef.name}\"`\n );\n case \"dropEnum\":\n return push(\n undefined,\n operation.enumName,\n `drop enum \"${operation.enumName}\"`\n );\n case \"alterEnum\":\n return push(\n undefined,\n operation.enumName,\n `alter enum \"${operation.enumName}\"`\n );\n case \"renameTable\":\n return push(\n operation.from,\n undefined,\n `rename table \"${operation.from}\" to \"${operation.to}\"`\n );\n case \"renameColumn\":\n return push(\n operation.tableName,\n operation.from,\n `rename column \"${operation.from}\" to \"${operation.to}\"`\n );\n default:\n return push(undefined, undefined, operationType(operation));\n }\n}\n\n/** The tables an operation touches, for demoting a generated junction. */\nfunction tableOf(warning: IntrospectionWarning): string | undefined {\n return warning.table;\n}\n\nexport interface Verification {\n readonly warnings: IntrospectionWarning[];\n /** Tables with at least one drift. */\n readonly drifted: ReadonlySet<string>;\n}\n\n/**\n * Diff the document against the live snapshot of the tables it declares.\n *\n * `current` holds exactly those tables (and the enums their columns use), so\n * what the document deliberately leaves out — a skipped table, a view — is not\n * reported twice. Throws what `parseSchema(…, { validate: true })` throws: a\n * document that does not validate is a translation bug, never a drift.\n */\nexport async function verifyDocument(\n document: SchemaDocument,\n current: SchemaSnapshot,\n migrationDriver: MigrationDriver\n): Promise<Verification> {\n const schema = parseSchema(document, { validate: true });\n hydrateSchemaNames(schema);\n const desired = serializeModels(schema, { migrationDriver });\n const readsNames =\n migrationDriver.capabilities.introspectionReadsConstraintNames;\n const result = await diff(current, desired, {\n matchConstraintsByShape: !readsNames,\n refuseConstraintNameChurn: false,\n });\n // On a dialect that reads constraint names, a constraint the database holds\n // under another name is a drop and an add of one shape. `push` refuses that\n // rather than renaming it, so the pair is reported as the one fact it is.\n const renamed = new Set<DiffOperation>();\n const warnings: IntrospectionWarning[] = [];\n for (const added of result.operations) {\n if (added.type !== \"addForeignKey\" && added.type !== \"addUniqueConstraint\")\n continue;\n const columns = (\n added.type === \"addForeignKey\" ? added.fk : added.constraint\n ).columns.join(\"\\0\");\n const live = current.tables.find((table) => table.name === added.tableName);\n const dropped = result.operations.find((operation) => {\n if (renamed.has(operation)) return false;\n if (\n added.type === \"addForeignKey\" &&\n operation.type === \"dropForeignKey\" &&\n operation.tableName === added.tableName\n )\n return live?.foreignKeys.some(\n (fk) =>\n fk.name === operation.fkName &&\n fk.columns.join(\"\\0\") === columns &&\n fk.referencedTable === added.fk.referencedTable\n );\n if (\n added.type === \"addUniqueConstraint\" &&\n operation.type === \"dropUniqueConstraint\" &&\n operation.tableName === added.tableName\n )\n return live?.uniqueConstraints.some(\n (unique) =>\n unique.name === operation.constraintName &&\n unique.columns.join(\"\\0\") === columns\n );\n return false;\n });\n if (dropped === undefined) continue;\n renamed.add(added);\n renamed.add(dropped);\n const actual =\n dropped.type === \"dropForeignKey\"\n ? dropped.fkName\n : dropped.type === \"dropUniqueConstraint\"\n ? dropped.constraintName\n : \"\";\n const wanted =\n added.type === \"addForeignKey\" ? added.fk.name : added.constraint.name;\n warnings.push({\n kind: \"drift\",\n table: added.tableName,\n name: actual,\n message: `push refuses this table: the constraint \"${actual}\" is the one VibORM names \"${wanted}\", and a document cannot name it`,\n });\n }\n for (const operation of result.operations)\n if (!renamed.has(operation)) warnings.push(describe(operation));\n for (const change of result.ambiguousChanges)\n warnings.push(\n change.type === \"ambiguousColumn\"\n ? {\n kind: \"drift\",\n table: change.tableName,\n name: change.droppedColumn.name,\n message: `push would replace column \"${change.droppedColumn.name}\" by \"${change.addedColumn.name}\"`,\n }\n : {\n kind: \"drift\",\n table: change.droppedTable,\n message: `push would replace table \"${change.droppedTable}\" by \"${change.addedTable}\"`,\n }\n );\n // A primary key's name is matched by name, never by diff: push refuses one\n // it would have to rename rather than planning anything.\n if (readsNames) {\n const desiredTables = new Map(\n desired.tables.map((table) => [table.name, table])\n );\n for (const table of current.tables) {\n const actual = table.primaryKey?.name;\n const wanted = desiredTables.get(table.name)?.primaryKey?.name;\n if (actual !== undefined && wanted !== undefined && actual !== wanted)\n warnings.push({\n kind: \"drift\",\n table: table.name,\n name: actual,\n message: `push refuses this table: its primary key is named \"${actual}\" and VibORM names it \"${wanted}\"`,\n });\n }\n }\n const drifted = new Set<string>();\n for (const warning of warnings) {\n const table = tableOf(warning);\n if (table !== undefined) drifted.add(table);\n }\n return { warnings, drifted };\n}\n","/**\n * `viborm/schema/introspect` — a schema document from an existing database.\n *\n * ```ts\n * import { introspectSchema } from \"viborm/schema/introspect\";\n * import { parseSchema } from \"viborm/schema/json\";\n *\n * const { document, skipped, warnings } = await introspectSchema({ url });\n * const db = createClient({ schema: parseSchema(document), databaseUrl: url });\n * ```\n *\n * The document is the canonical form of `viborm/schema/json`: there is no\n * second format, and a TypeScript schema generator can be written from it\n * later without reading the database again. What the document does not carry\n * is listed in `skipped`, what it states with less certainty than the database\n * proves is an `approximated` warning, what a table carries that the document\n * has no spelling for (a collation, `STRICT`, a trigger: the dialect's\n * `adoptionHazards`) is an `unstated` warning, and every place where a `push`\n * of it would change the database is a `drift` warning, found by running\n * push's own serializer and differ against the snapshot the database was read\n * into. `light: true` writes only what a client reads (`lighten`).\n *\n * This entry is tooling: it registers every migration driver and imports the\n * driver a URL names on demand. An application never imports it, so the\n * application bundle carries none of it.\n */\n\nimport type { AnyDriver } from \"../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { parseSchema, serializeSchema } from \"../../schema/json\";\nimport type { SchemaDocument } from \"../../schema/json/document\";\nimport { registerEveryMigrationDriver } from \"../dialects/every\";\nimport type { SchemaSnapshot } from \"../types\";\nimport { openDriver } from \"./connect\";\nimport { readCatalog } from \"./read\";\nimport { translateSnapshot } from \"./translate\";\nimport type {\n IntrospectionDialect,\n IntrospectionWarning,\n IntrospectSchemaResult,\n SkippedObject,\n} from \"./types\";\nimport { verifyDocument } from \"./verify\";\n\nregisterEveryMigrationDriver();\n\nexport type {\n IntrospectionDialect,\n IntrospectionWarning,\n IntrospectSchemaResult,\n SkippedKind,\n SkippedObject,\n} from \"./types\";\n\ninterface IntrospectScope {\n /** Only these tables (exact physical names). */\n readonly tables?: readonly string[];\n /**\n * A light document: only what a client reads (models, fields with their\n * type, nullability, list-ness, keys, uniques, defaults and generators,\n * native types, relations, names), without the indexes only migrations\n * read. It is marked `\"light\": true`, and every migration path refuses it.\n * `skipped` and `warnings` then keep only what changes what a client sees:\n * no index or CHECK constraint, no `unstated` or `drift` warning.\n */\n readonly light?: boolean;\n}\n\nexport type IntrospectSchemaOptions =\n | (IntrospectScope & {\n /**\n * The database: `postgres://` / `postgresql://`, `mysql://`, `file:` / `sqlite:` or a\n * `.db` / `.sqlite` path (opened read-only), or `libsql://`. The\n * connection is opened for this call and always closed.\n */\n readonly url: string;\n readonly driver?: never;\n })\n | (IntrospectScope & {\n /**\n * A driver you constructed (a D1 binding, a custom pool, a PostgreSQL\n * `namespace`). It is yours: it is not closed.\n */\n readonly driver: AnyDriver;\n readonly url?: never;\n });\n\nconst DIALECTS: readonly IntrospectionDialect[] = [\n \"postgresql\",\n \"sqlite\",\n \"mysql\",\n \"snowflake\",\n];\n\n/**\n * Snowflake is read, never pushed to: a drift against it has no push to\n * describe, and what the document cannot promise is that its keys hold.\n */\nconst SNOWFLAKE_KEYS: IntrospectionWarning = {\n kind: \"approximated\",\n message:\n \"Snowflake enforces no primary, unique or foreign key: the document's keys, uniques and relations are the ones the catalog declares, and a row may break them\",\n};\n\nfunction isIntrospectionDialect(\n dialect: string\n): dialect is IntrospectionDialect {\n return DIALECTS.some((item) => item === dialect);\n}\n\n/** The live tables the document declares, and the enums their columns use. */\nfunction declaredSnapshot(\n snapshot: SchemaSnapshot,\n tables: ReadonlySet<string>\n): SchemaSnapshot {\n const kept = snapshot.tables.filter((table) => tables.has(table.name));\n const used = new Set(\n kept.flatMap((table) =>\n table.columns.map((column) =>\n column.type.endsWith(\"[]\") ? column.type.slice(0, -2) : column.type\n )\n )\n );\n const enums = snapshot.enums?.filter((item) => used.has(item.name));\n return {\n tables: kept,\n ...(enums && enums.length > 0 ? { enums } : {}),\n };\n}\n\n/**\n * The light form of a canonical document: every index left out, and the\n * report narrowed to what a client sees. An `approximated` warning naming an\n * index (a unique constraint written as a unique index) goes with it.\n */\nfunction lighten(result: IntrospectSchemaResult): IntrospectSchemaResult {\n const dropped = new Set<string>();\n const models: SchemaDocument[\"models\"] = {};\n for (const [key, { indexes, ...model }] of Object.entries(\n result.document.models\n )) {\n for (const index of indexes ?? [])\n dropped.add(`${model.table ?? key}\\0${index.name}`);\n models[key] = model;\n }\n return {\n ...result,\n document: serializeSchema(\n parseSchema({ ...result.document, light: true, models })\n ),\n skipped: result.skipped.filter(\n (item) => item.kind !== \"index\" && item.kind !== \"check\"\n ),\n warnings: result.warnings.filter(\n (warning) =>\n warning.kind === \"approximated\" &&\n !dropped.has(`${warning.table}\\0${warning.name}`)\n ),\n };\n}\n\nasync function introspectDriver(\n driver: AnyDriver,\n tables: readonly string[] | undefined\n): Promise<IntrospectSchemaResult> {\n const introspectionDialect = driver.dialect;\n if (!isIntrospectionDialect(introspectionDialect))\n throw new MigrationError(\n `introspectSchema does not translate ${introspectionDialect} yet; PostgreSQL, SQLite, MySQL and Snowflake are supported.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { dialect: introspectionDialect, feature: \"introspect-schema\" } }\n );\n const catalog = await readCatalog(driver, introspectionDialect, tables);\n\n // A pure join table is first written as the generated junction of its pair;\n // where that junction is not exactly this table, it becomes a junction model\n // and the document is translated again.\n const junctionModels = new Set<string>();\n for (let attempt = 0; ; attempt++) {\n const translation = translateSnapshot({\n snapshot: catalog.snapshot,\n dialect: introspectionDialect,\n migrationDriver: catalog.migrationDriver,\n identityColumns: catalog.identityColumns,\n junctionModels,\n });\n const verification =\n introspectionDialect === \"snowflake\"\n ? { warnings: [SNOWFLAKE_KEYS], drifted: new Set<string>() }\n : await verifyDocument(\n translation.document,\n declaredSnapshot(catalog.snapshot, translation.tables),\n catalog.migrationDriver\n );\n const demote = [...translation.generatedJunctions].filter((table) =>\n verification.drifted.has(table)\n );\n if (demote.length > 0 && attempt === 0) {\n for (const table of demote) junctionModels.add(table);\n continue;\n }\n const document: SchemaDocument = serializeSchema(\n parseSchema(translation.document)\n );\n const skipped: SkippedObject[] = [\n ...catalog.skipped,\n ...translation.skipped,\n ];\n const warnings: IntrospectionWarning[] = [\n ...translation.warnings,\n // Each CHECK constraint is already in `skipped`, with its definition.\n ...catalog.hazards\n .filter(\n ({ table, feature }) =>\n translation.tables.has(table) && !feature.startsWith(\"CHECK\")\n )\n .map(({ table, feature }) => ({\n kind: \"unstated\" as const,\n table,\n message: `the document cannot carry ${feature}: the database keeps it and a push of the document plans nothing for it, but a push that recreates the table or the column cannot keep it`,\n })),\n ...verification.warnings,\n ];\n return { document, skipped, warnings, dialect: introspectionDialect };\n }\n}\n\n/**\n * Read an existing database into a schema document.\n *\n * Never invents: a fact the catalog does not prove is not in the document, and\n * what is lost or approximated is said in `skipped` and `warnings`.\n */\nexport async function introspectSchema(\n options: IntrospectSchemaOptions\n): Promise<IntrospectSchemaResult> {\n const read = async (driver: AnyDriver) => {\n const result = await introspectDriver(driver, options.tables);\n return options.light ? lighten(result) : result;\n };\n if (options.driver !== undefined) return await read(options.driver);\n const { driver } = await openDriver(options.url);\n try {\n return await read(driver);\n } finally {\n await driver.disconnect();\n }\n}\n"],"mappings":"gdAkBA,MAAM,EAAS,yBACT,EAAc,0BAGpB,SAAS,WAAW,EAAiC,CACnD,IAAK,IAAM,IAAU,CAAC,YAAa,UAAW,UAAW,QAAQ,CAC/D,GAAI,EAAI,WAAW,EAAO,CAAE,OAAO,EAAI,MAAM,EAAO,OAAO,CAE7D,OAAO,EAAO,KAAK,EAAI,CAAG,IAAA,GAAY,EAGxC,eAAsB,WAAW,EAAoC,CACnE,IAAM,EAAS,EAAO,K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EAAM,EAAI,CAAC,EAAQ,WAAW,QAAQ,CAChE,CACA,KAAK,CAAE,QAAO,cAAe,CAC5B,KAAM,WACN,QACA,QAAS,6BAA6B,EAAQ,2IAC/C,EAAE,CACL,GAAG,EAAa,SACjB,CACqC,QAAS,EAAsB,EAUzE,eAAsB,iBACpB,EACiC,CACjC,IAAM,KAAO,KAAO,IAAsB,CACxC,IAAM,EAAS,MAAM,iBAAiBC,EAAQ,EAAQ,OAAO,CAC7D,OAAO,EAAQ,MAAQ,QAAQ,EAAO,CAAG,GAE3C,GAAI,EAAQ,SAAW,IAAA,GAAW,OAAO,MAAM,KAAK,EAAQ,OAAO,CACnE,GAAM,CAAE,UAAW,MAAM,WAAW,EAAQ,IAAI,CAChD,GAAI,CACF,OAAO,MAAM,KAAK,EAAO,QACjB,CACR,MAAM,EAAO,YAAY"}
1
+ {"version":3,"file":"introspect-Bm6xnXcG.mjs","names":["values","members","value","#taken","#reserved","#free","models","driver"],"sources":["../src/migrations/introspect/connect.ts","../src/migrations/introspect/read.ts","../src/migrations/introspect/columns.ts","../src/migrations/introspect/names.ts","../src/migrations/introspect/translate.ts","../src/migrations/introspect/verify.ts","../src/migrations/introspect/index.ts"],"sourcesContent":["/**\n * A connection string → the stock VibORM driver for it.\n *\n * The scheme names the driver, and the driver is constructed exactly as its\n * own `createClient` constructs it (`databaseUrl` / `dataDir`). Each driver\n * module is imported on demand, so only the provider package the URL names is\n * loaded — introspecting PostgreSQL never requires `better-sqlite3`.\n */\n\nimport type { AnyDriver } from \"../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport type { IntrospectionDialect } from \"./types\";\n\nexport interface OpenedDriver {\n readonly driver: AnyDriver;\n readonly dialect: IntrospectionDialect;\n}\n\nconst SCHEME = /^([a-z][a-z0-9+.-]*):/i;\nconst SQLITE_FILE = /\\.(?:db|sqlite3?|db3)$/i;\n\n/** A SQLite path from `file:` / `sqlite:` URLs, or a bare database file. */\nfunction sqlitePath(url: string): string | undefined {\n for (const prefix of [\"sqlite://\", \"sqlite:\", \"file://\", \"file:\"]) {\n if (url.startsWith(prefix)) return url.slice(prefix.length);\n }\n return SCHEME.test(url) ? undefined : url;\n}\n\nexport async function openDriver(url: string): Promise<OpenedDriver> {\n const scheme = SCHEME.exec(url)?.[1]?.toLowerCase();\n if (scheme === \"postgres\" || scheme === \"postgresql\") {\n const { PgDriver } = await import(\"../../drivers/pg\");\n return {\n driver: new PgDriver({ databaseUrl: url, options: {} }),\n dialect: \"postgresql\",\n };\n }\n if (\n scheme === \"libsql\" ||\n scheme === \"http\" ||\n scheme === \"https\" ||\n scheme === \"ws\" ||\n scheme === \"wss\"\n ) {\n const { LibSQLDriver } = await import(\"../../drivers/libsql\");\n const parsed = new URL(url);\n const authToken = parsed.searchParams.get(\"authToken\") ?? undefined;\n parsed.searchParams.delete(\"authToken\");\n return {\n driver: new LibSQLDriver({\n databaseUrl: parsed.href,\n ...(authToken === undefined ? {} : { authToken }),\n }),\n dialect: \"sqlite\",\n };\n }\n if (scheme === \"mysql\") {\n const { MySQL2Driver } = await import(\"../../drivers/mysql2\");\n return { driver: new MySQL2Driver({ databaseUrl: url }), dialect: \"mysql\" };\n }\n if (scheme === \"snowflake\")\n throw new MigrationError(\n 'A snowflake:// URL carries no key or token. Pass the driver instead: introspectSchema({ driver: new SnowflakeDriver({ databaseUrl, privateKey }) }) with SnowflakeDriver from \"viborm/snowflake\".',\n VibORMErrorCode.INVALID_INPUT,\n { meta: { feature: \"introspect-url\" } }\n );\n if (scheme === \"surrealdb\" || scheme === \"surreal\")\n throw new MigrationError(\n \"introspectSchema does not translate SurrealDB yet; PostgreSQL, SQLite and MySQL are supported.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { feature: \"introspect-schema\" } }\n );\n const path = sqlitePath(url);\n if (\n path !== undefined &&\n (scheme !== undefined || SQLITE_FILE.test(path) || path === \":memory:\")\n ) {\n const { SQLite3Driver } = await import(\"../../drivers/sqlite3\");\n // Read-only, and only an existing file: introspection never creates a\n // database it was asked to read.\n return {\n driver: new SQLite3Driver({\n dataDir: path,\n options: { readonly: true, fileMustExist: true },\n }),\n dialect: \"sqlite\",\n };\n }\n throw new MigrationError(\n `introspectSchema cannot tell which database \"${scheme ?? url}\" names. Use postgres:// or postgresql:// for PostgreSQL, mysql:// for MySQL, file: or sqlite: (or a .db / .sqlite file) for SQLite, and libsql:// for libSQL; or pass a driver.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { feature: \"introspect-url\" } }\n );\n}\n","/**\n * The live catalog `introspectSchema` translates: the snapshot the dialect's\n * own migration introspection reads, plus the few facts a snapshot does not\n * model and a document needs (identity columns) or must report (views, CHECK\n * constraints).\n *\n * Migration introspection REFUSES a table it cannot represent — a generated\n * column, a partitioned table, an index it cannot spell — because `push` must\n * not plan around what it does not understand. Here such a table is a skipped\n * object, not a failure: the refused table leaves the scope and the read runs\n * again, so one exotic table never hides the rest of the database.\n */\n\nimport type { AnyDriver } from \"../../drivers/driver\";\nimport { isVibORMError } from \"../../errors\";\nimport { CONTROL_TABLES } from \"../control\";\nimport { type BoundMigrationDriver, getMigrationDriver } from \"../drivers\";\nimport type { AdoptionHazard, MigrationDriver } from \"../drivers/base\";\nimport type { SchemaSnapshot } from \"../types\";\nimport type { IntrospectionDialect, SkippedObject } from \"./types\";\n\nexport interface LiveCatalog {\n readonly snapshot: SchemaSnapshot;\n readonly skipped: SkippedObject[];\n /** PostgreSQL identity columns, keyed `table\\0column`. */\n readonly identityColumns: ReadonlySet<string>;\n /**\n * What each kept table carries that changes how it behaves and that no\n * snapshot describes — the dialect's own `adoptionHazards`: a collation,\n * SQLite's `STRICT` and `ON CONFLICT`, a trigger, row security... A\n * document cannot carry it either.\n */\n readonly hazards: readonly AdoptionHazard[];\n /** The migration driver bound to the whole estate. */\n readonly migrationDriver: BoundMigrationDriver;\n}\n\nconst CONTROL = new Set([CONTROL_TABLES.state, CONTROL_TABLES.log]);\n\n/** The table a migration introspection refusal names, when it names one. */\nfunction refusedTable(error: unknown): string | undefined {\n if (!isVibORMError(error)) return;\n const table: unknown = error.meta?.table;\n return typeof table === \"string\" ? table : undefined;\n}\n\n/** The dialect's own introspection, without the managed-table boundary check. */\nasync function introspectScope(\n driver: AnyDriver,\n scope: readonly string[] | undefined\n): Promise<SchemaSnapshot> {\n const bound = getMigrationDriver(driver, scope);\n // The bound view wraps the implementation's `introspect` in the managed-table\n // selection, which REFUSES a foreign key crossing the scope. A refused table\n // can be the target of a foreign key this document still reports (as a\n // skipped foreign key), so the implementation itself is read, under the same\n // bound `this`, and the tables are selected below.\n const implementation: MigrationDriver = Object.getPrototypeOf(bound);\n return await implementation.introspect.call(bound, (sql, params) =>\n driver._executeRaw(sql, params)\n );\n}\n\nasync function rows<T>(\n driver: AnyDriver,\n sql: string,\n params: unknown[]\n): Promise<T[]> {\n return (await driver._executeRaw<T>(sql, params)).rows;\n}\n\nexport async function readCatalog(\n driver: AnyDriver,\n dialect: IntrospectionDialect,\n tables: readonly string[] | undefined\n): Promise<LiveCatalog> {\n const migrationDriver = getMigrationDriver(driver);\n const skipped: SkippedObject[] = [];\n const refused = new Map<string, string>();\n let inventory: string[] | undefined;\n let snapshot: SchemaSnapshot;\n for (;;) {\n // A caller's `tables` is the first scope: a table outside it is read\n // without the refusals that would only protect a push of it.\n const scope =\n refused.size === 0\n ? tables\n : (tables ?? inventory ?? []).filter((name) => !refused.has(name));\n try {\n snapshot = await introspectScope(driver, scope);\n break;\n } catch (error) {\n const table = refusedTable(error);\n if (table === undefined || refused.has(table)) throw error;\n refused.set(\n table,\n error instanceof Error ? error.message : \"introspection refused it\"\n );\n if (tables === undefined && inventory === undefined) {\n const query = migrationDriver.generateInventoryTables();\n inventory = (\n await rows<{ name: string }>(driver, query.sql, query.params)\n ).map((row) => row.name);\n }\n }\n }\n for (const [table, reason] of refused)\n skipped.push({ kind: \"table\", name: table, reason });\n\n const selected = (name: string) =>\n !(refused.has(name) || CONTROL.has(name)) &&\n (tables === undefined || tables.includes(name));\n for (const table of snapshot.tables)\n if (CONTROL.has(table.name))\n skipped.push({\n kind: \"table\",\n name: table.name,\n reason: \"it is VibORM's migration control table\",\n });\n\n const identityColumns = new Set<string>();\n if (dialect === \"postgresql\") {\n // Binding proved the estate's namespace for PostgreSQL.\n const namespace = migrationDriver.namespace;\n for (const row of await rows<{ table_name: string; column_name: string }>(\n driver,\n \"SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = $1 AND is_identity = 'YES'\",\n [namespace]\n ))\n identityColumns.add(`${row.table_name}\\0${row.column_name}`);\n for (const row of await rows<{ name: string; kind: string }>(\n driver,\n \"SELECT table_name AS name, 'view' AS kind FROM information_schema.views WHERE table_schema = $1 UNION ALL SELECT matviewname AS name, 'materialized view' AS kind FROM pg_catalog.pg_matviews WHERE schemaname = $1 ORDER BY 1\",\n [namespace]\n ))\n skipped.push({\n kind: \"view\",\n name: row.name,\n reason: `it is a ${row.kind}, and a document declares tables only`,\n });\n for (const row of await rows<{\n table_name: string;\n name: string;\n definition: string;\n }>(\n driver,\n \"SELECT rel.relname AS table_name, con.conname AS name, pg_catalog.pg_get_constraintdef(con.oid) AS definition FROM pg_catalog.pg_constraint con JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid JOIN pg_catalog.pg_namespace ns ON ns.oid = rel.relnamespace WHERE ns.nspname = $1 AND con.contype = 'c' ORDER BY 1, 2\",\n [namespace]\n ))\n if (selected(row.table_name))\n skipped.push({\n kind: \"check\",\n table: row.table_name,\n name: row.name,\n reason: `a document has no CHECK constraint (${row.definition}); the database keeps enforcing it`,\n });\n } else if (dialect === \"mysql\") {\n // Binding proved the estate's database for MySQL.\n const database = migrationDriver.namespace;\n for (const row of await rows<{ name: string }>(\n driver,\n \"SELECT TABLE_NAME AS name FROM information_schema.VIEWS WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME\",\n [database]\n ))\n skipped.push({\n kind: \"view\",\n name: row.name,\n reason: \"it is a view, and a document declares tables only\",\n });\n for (const row of await rows<{\n table_name: string;\n name: string;\n definition: string;\n }>(\n driver,\n \"SELECT tc.TABLE_NAME AS table_name, tc.CONSTRAINT_NAME AS name, cc.CHECK_CLAUSE AS definition FROM information_schema.TABLE_CONSTRAINTS tc JOIN information_schema.CHECK_CONSTRAINTS cc ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME WHERE tc.CONSTRAINT_SCHEMA = ? AND tc.CONSTRAINT_TYPE = 'CHECK' ORDER BY 1, 2\",\n [database]\n ))\n if (selected(row.table_name))\n skipped.push({\n kind: \"check\",\n table: row.table_name,\n name: row.name,\n reason: `a document has no CHECK constraint (${row.definition}); the database keeps enforcing it`,\n });\n } else if (dialect === \"snowflake\") {\n const schema = migrationDriver.namespace;\n for (const row of await rows<{ name: string }>(\n driver,\n schema === undefined\n ? 'SELECT TABLE_NAME AS \"name\" FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = CURRENT_SCHEMA() ORDER BY TABLE_NAME'\n : 'SELECT TABLE_NAME AS \"name\" FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME',\n schema === undefined ? [] : [schema]\n ))\n skipped.push({\n kind: \"view\",\n name: row.name,\n reason: \"it is a view, and a document declares tables only\",\n });\n } else {\n for (const row of await rows<{ name: string }>(\n driver,\n \"SELECT name FROM sqlite_master WHERE type = 'view' ORDER BY name\",\n []\n ))\n skipped.push({\n kind: \"view\",\n name: row.name,\n reason: \"it is a view, and a document declares tables only\",\n });\n }\n\n const kept = snapshot.tables.filter((table) => selected(table.name));\n return {\n snapshot: { ...snapshot, tables: kept },\n skipped,\n identityColumns,\n hazards: await migrationDriver.adoptionHazards(\n kept.map((table) => table.name),\n async <T>(sql: string, params?: unknown[]) => ({\n rows: await rows<T>(driver, sql, params ?? []),\n })\n ),\n migrationDriver,\n };\n}\n","/**\n * One live column → one scalar field document.\n *\n * Each dialect reads the snapshot its own introspection wrote (`ColumnDef`) and\n * answers with the field whose forward serialization (`mapScalarType` and\n * `getDefaultExpression`) spells that column again — or with the reason it\n * cannot. Nothing here guesses past what the catalog proves: an exactness this\n * table cannot promise is caught afterwards by `verify.ts`, which runs the\n * forward direction for real.\n */\n\nimport { readArrayLiteralText } from \"../../adapters/databases/postgres/array-literal\";\nimport type {\n DecimalFieldDocument,\n EnumFieldDocument,\n PointFieldDocument,\n ScalarFieldDocument,\n ValueFieldDocument,\n} from \"../../schema/json/document\";\nimport type { JsonValue } from \"../../validation/primitives/json\";\nimport { MYSQL_PRINTED_CHARACTERS } from \"../drivers/type-mapping\";\nimport { normalizeDefault, normalizeType } from \"../push-fingerprint\";\nimport type { ColumnDef, EnumDef } from \"../types\";\nimport type { IntrospectionDialect } from \"./types\";\n\n/** What a column becomes, before keys, keys and relations are settled. */\nexport interface ColumnField {\n readonly field: ScalarFieldDocument;\n /** The database enum type an enum column uses (PostgreSQL), by name. */\n readonly enumType?: string | undefined;\n /** Why the column's default is not carried, when it is not. */\n readonly skippedDefault?: string | undefined;\n /** How the field's meaning is weaker than the column proves, when it is. */\n readonly approximated?: string | undefined;\n}\n\nexport type ColumnTranslation = ColumnField | { readonly skip: string };\n\nexport interface ColumnContext {\n readonly column: ColumnDef;\n /** The database enums by name (PostgreSQL). */\n readonly enums: ReadonlyMap<string, EnumDef>;\n /** A PostgreSQL identity column: the catalog default is not a default. */\n readonly identity: boolean;\n /** The dialect's spelling of a column-owned enum (SQLite's CHECK). */\n readonly enumColumnType: (values: string[]) => string;\n /**\n * A SQLite `BLOB` key column, or a foreign key to one: VibORM stores a uuid\n * key there as sixteen bytes, and a blob cannot be a key.\n */\n readonly binaryKey: boolean;\n /**\n * MySQL: the column is in a key, an index or a foreign key, where VibORM\n * writes a string as `VARCHAR(191)` (an indexed TEXT needs a length).\n */\n readonly keyed: boolean;\n}\n\n/** The scalar types that have `.array()`. */\nconst LIST_TYPES = new Set<string>([\n \"string\",\n \"int\",\n \"number\",\n \"decimal\",\n \"boolean\",\n \"datetime\",\n \"date\",\n \"time\",\n \"bigint\",\n \"blob\",\n \"enum\",\n]);\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\ntype ValueDraft = Mutable<ValueFieldDocument>;\ntype FieldDraft =\n | ValueDraft\n | Mutable<EnumFieldDocument>\n | Mutable<DecimalFieldDocument>\n | Mutable<PointFieldDocument>;\n\n// =============================================================================\n// DEFAULTS (shared literal reading)\n// =============================================================================\n\nconst QUOTED = /^'([\\s\\S]*)'$/;\nconst NUMBER = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i;\nconst INTEGER = /^[+-]?\\d+$/;\nconst NOW_DEFAULTS = new Set([\n \"now()\",\n \"now() at time zone 'utc'\",\n \"date_trunc('milliseconds',now())\",\n \"date_trunc('milliseconds',now() at time zone 'utc')\",\n \"current_date\",\n \"current_time\",\n \"localtimestamp\",\n \"localtime\",\n \"timezone('utc',current_time)\",\n \"timezone('utc',current_time(3))\",\n // SQLite: VibORM's own millisecond UTC clock.\n \"strftime('%Y-%m-%dT%H:%M:%fZ','now')\",\n // MySQL: a fractional-second clock.\n \"current_timestamp(3)\",\n \"current_timestamp(6)\",\n \"(current_timestamp(3))\",\n]);\nconst DATE_LITERAL = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst PG_TIMESTAMP_LITERAL =\n /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?)([+-]\\d{2}(?::?\\d{2})?|Z)?$/;\n\n/** A JSON value a document can carry untagged, or wrapped in `$raw`. */\nfunction jsonDefault(value: JsonValue): JsonValue {\n if (\n value !== null &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n Object.keys(value).length === 1 &&\n Object.keys(value)[0]?.startsWith(\"$\")\n )\n return { $raw: value };\n return value;\n}\n\nconst MYSQL_EXPRESSION_LITERAL = /^\\(('[\\s\\S]*')\\)$/;\nconst MYSQL_ESCAPE = /\\\\(.)/g;\n\n/**\n * A quoted literal's value. MySQL prints `\\\\`, `\\n`, `\\r`, `\\0`, `\\Z` and `\\'`\n * (`MYSQL_PRINTED_CHARACTERS`); an escape outside that table is not one it\n * printed for a value VibORM can name, so there is no value.\n */\nfunction unquote(\n body: string,\n dialect: IntrospectionDialect\n): string | undefined {\n const doubled = body.replaceAll(\"''\", \"'\");\n if (dialect !== \"mysql\") return doubled;\n let known = true;\n const value = doubled.replace(\n MYSQL_ESCAPE,\n (_sequence, character: string) => {\n const printed = MYSQL_PRINTED_CHARACTERS.get(character);\n if (printed === undefined) known = false;\n return printed ?? character;\n }\n );\n return known ? value : undefined;\n}\n\n/** A decimal's text from its unscaled integer coefficient. */\nfunction coefficientText(coefficient: string, scale: number): string {\n if (scale === 0) return BigInt(coefficient).toString();\n const negative = coefficient.startsWith(\"-\");\n const digits = BigInt(negative ? coefficient.slice(1) : coefficient)\n .toString()\n .padStart(scale + 1, \"0\");\n return `${negative ? \"-\" : \"\"}${digits.slice(0, -scale)}.${digits.slice(-scale)}`;\n}\n\n/** Whether a date and a clock name a real instant, with nothing rolled over. */\nfunction isCalendarDate(day: string, clock: string): boolean {\n const [year, month, date] = day.split(\"-\").map(Number);\n const [hours, minutes, seconds] = clock.split(\":\").map(Number);\n // `Date.UTC` reads years 0–99 as 1900–1999; `setUTCFullYear` does not.\n const instant = new Date(0);\n instant.setUTCFullYear(year!, month! - 1, date!);\n instant.setUTCHours(hours!, minutes!, Math.trunc(seconds!));\n return (\n instant.getUTCFullYear() === year &&\n instant.getUTCMonth() === month! - 1 &&\n instant.getUTCDate() === date &&\n instant.getUTCHours() === hours &&\n instant.getUTCMinutes() === minutes &&\n instant.getUTCSeconds() === Math.trunc(seconds!)\n );\n}\n\n/** One literal default member, read as the field's own domain. */\nfunction literalValue(\n field: FieldDraft,\n text: string,\n quoted: boolean\n): JsonValue | undefined {\n switch (field.type) {\n case \"string\":\n return quoted ? text : undefined;\n case \"enum\":\n return Array.isArray(field.enum) && field.enum.includes(text)\n ? text\n : undefined;\n case \"int\":\n case \"number\":\n return NUMBER.test(text) &&\n (field.type === \"number\" || INTEGER.test(text))\n ? Number(text)\n : undefined;\n case \"bigint\":\n return INTEGER.test(text)\n ? { $bigint: BigInt(text).toString() }\n : undefined;\n case \"decimal\":\n return NUMBER.test(text) ? text : undefined;\n case \"boolean\": {\n const lower = text.toLowerCase();\n if (lower === \"true\" || lower === \"t\" || lower === \"1\") return true;\n if (lower === \"false\" || lower === \"f\" || lower === \"0\") return false;\n return;\n }\n case \"json\":\n try {\n const parsed: JsonValue = JSON.parse(text);\n return jsonDefault(parsed);\n } catch {\n return;\n }\n case \"datetime\": {\n const match = PG_TIMESTAMP_LITERAL.exec(text);\n if (!match) return;\n // `Date` rolls an impossible date (`2020-02-30`) into another day; such\n // a literal is no instant, so it has no value here.\n if (!isCalendarDate(match[1]!, match[2]!)) return;\n // PostgreSQL prints an offset as `+00`; ISO 8601 wants `+00:00`.\n const zone = match[3] ?? \"Z\";\n const offset = zone.length === 3 ? `${zone}:00` : zone;\n const date = new Date(`${match[1]}T${match[2]}${offset}`);\n return Number.isNaN(date.getTime()) ? undefined : date.toISOString();\n }\n case \"date\":\n return DATE_LITERAL.test(text) && isCalendarDate(text, \"00:00:00\")\n ? text\n : undefined;\n default:\n return;\n }\n}\n\n/**\n * The default of one column, as `default`/`generate` keys on its field draft,\n * or the reason it has no document spelling.\n */\nfunction readDefault(\n field: FieldDraft,\n column: ColumnDef,\n sqlText: string,\n dialect: IntrospectionDialect\n): string | undefined {\n const normalized = normalizeDefault(sqlText, column.type);\n if (normalized === undefined) return; // NULL: no default\n const unsupported = `the default \\`${sqlText}\\` has no document spelling`;\n\n if (\n NOW_DEFAULTS.has(normalized) ||\n NOW_DEFAULTS.has(normalized.toLowerCase())\n ) {\n if (\n field.type === \"datetime\" ||\n field.type === \"date\" ||\n field.type === \"time\"\n ) {\n if (field.array) return unsupported;\n field.generate = { kind: \"now\" };\n return;\n }\n return unsupported;\n }\n if (normalized === \"gen_random_uuid()\" || normalized === \"uuidv7()\") {\n if (field.type !== \"string\" || field.array) return unsupported;\n field.generate = {\n kind: normalized === \"gen_random_uuid()\" ? \"uuid\" : \"uuidv7\",\n };\n return;\n }\n\n // MySQL spells the default of a TEXT, BLOB or JSON column as an expression:\n // the literal in one pair of parentheses.\n const spelled = sqlText.trim();\n const expression =\n dialect === \"mysql\"\n ? MYSQL_EXPRESSION_LITERAL.exec(spelled)?.[1]\n : undefined;\n const quoted = QUOTED.exec(expression ?? spelled);\n const literal = quoted ? unquote(quoted[1]!, dialect) : sqlText.trim();\n if (literal === undefined) return unsupported;\n if (field.array) {\n if (!(quoted && dialect === \"postgresql\")) {\n // SQLite and MySQL hold a list as one JSON text.\n if (!quoted) return unsupported;\n try {\n const values: unknown = JSON.parse(literal);\n if (!Array.isArray(values)) return unsupported;\n const members: JsonValue[] = [];\n for (const value of values) {\n const member =\n value === null\n ? null\n : literalValue(\n field,\n typeof value === \"string\" ? value : JSON.stringify(value),\n typeof value === \"string\"\n );\n if (member === undefined) return unsupported;\n members.push(member);\n }\n field.default = members;\n return;\n } catch {\n return unsupported;\n }\n }\n const members = readArrayLiteralText(literal);\n if (members === undefined) return unsupported;\n const values: JsonValue[] = [];\n for (const member of members) {\n const value = member === null ? null : literalValue(field, member, true);\n if (value === undefined) return unsupported;\n values.push(value);\n }\n field.default = values;\n return;\n }\n // SQLite stores a scalar decimal default as its coefficient.\n const text =\n field.type === \"decimal\" && dialect === \"sqlite\" && INTEGER.test(literal)\n ? coefficientText(literal, field.scale)\n : literal;\n const value = literalValue(field, text, quoted !== null);\n if (value === undefined) return unsupported;\n field.default = value;\n return;\n}\n\n// =============================================================================\n// POSTGRESQL\n// =============================================================================\n\nconst PG_VARCHAR = /^varchar\\((\\d+)\\)$/;\nconst PG_CHAR = /^char\\((\\d+)\\)$/;\nconst PG_BIT = /^(bit|varbit)(\\((\\d+)\\))?$/;\nconst PG_NUMERIC = /^numeric\\((\\d+),(\\d+)\\)$/;\nconst PG_TIMESTAMP = /^timestamp(?:\\((\\d)\\))?( with time zone)?$/;\nconst PG_TIME = /^time(?:\\((\\d)\\))?( with time zone)?$/;\nconst PG_STRING_NATIVES = new Set([\n \"citext\",\n \"xml\",\n \"inet\",\n \"cidr\",\n \"macaddr\",\n \"macaddr8\",\n \"tsvector\",\n \"tsquery\",\n]);\n\nfunction pgNative(type: string): { db: \"pg\"; type: string } {\n return { db: \"pg\", type };\n}\n\n/** PostgreSQL's base type (no `[]`), normalized, as a field draft. */\nfunction postgresBase(\n base: string,\n column: ColumnDef,\n array: boolean\n): FieldDraft | string {\n if (base === \"text\") return { type: \"string\" };\n if (PG_VARCHAR.test(base) || PG_CHAR.test(base))\n return { type: \"string\", native: pgNative(base) };\n if (PG_STRING_NATIVES.has(base))\n return { type: \"string\", native: pgNative(base) };\n const bit = PG_BIT.exec(base);\n if (bit) return { type: \"string\", native: pgNative(base) };\n if (base === \"uuid\")\n // A uuid list keeps the column type itself; a scalar uuid is the uuid\n // domain, whose PostgreSQL storage is this same `uuid` column.\n return array\n ? { type: \"string\", native: pgNative(\"uuid\") }\n : { type: \"string\", generate: { kind: \"uuid\", generate: false } };\n if (base === \"integer\") return { type: \"int\" };\n if (base === \"smallint\" || base === \"oid\")\n return { type: \"int\", native: pgNative(base) };\n if (base === \"bigint\") return { type: \"bigint\" };\n if (base === \"real\") return { type: \"number\", native: pgNative(\"real\") };\n if (base === \"double precision\") return { type: \"number\" };\n if (base === \"boolean\") return { type: \"boolean\" };\n if (base === \"date\") return { type: \"date\" };\n if (base === \"bytea\") return { type: \"blob\" };\n if (base === \"jsonb\") return { type: \"json\" };\n if (base === \"json\") return { type: \"json\", native: pgNative(\"json\") };\n const numeric = PG_NUMERIC.exec(base);\n if (numeric) {\n const descriptor = column.decimal;\n if (descriptor === undefined)\n return `numeric(${numeric[1]},${numeric[2]}) is outside VibORM's fixed-decimal domain`;\n return {\n type: \"decimal\",\n precision: descriptor.precision,\n scale: descriptor.scale,\n };\n }\n if (base === \"numeric\")\n return \"an unconstrained `numeric` has no precision and scale, and a VibORM decimal declares both\";\n if (base === \"varchar\")\n return \"`varchar` without a length has no document spelling (use `text`, or a length)\";\n const timestamp = PG_TIMESTAMP.exec(base);\n if (timestamp) {\n const precision = timestamp[1];\n const zoned = timestamp[2] !== undefined;\n const draft: ValueDraft = { type: \"datetime\" };\n if (!zoned) draft.withoutTimezone = true;\n if (precision !== \"3\") {\n const name = zoned ? \"timestamptz\" : \"timestamp\";\n draft.native = pgNative(\n precision === undefined ? name : `${name}(${precision})`\n );\n }\n return draft;\n }\n const time = PG_TIME.exec(base);\n if (time) {\n const precision = time[1];\n const zoned = time[2] !== undefined;\n const draft: ValueDraft = { type: \"time\" };\n if (zoned || precision !== \"3\") {\n const name = zoned ? \"timetz\" : \"time\";\n draft.native = pgNative(\n precision === undefined ? name : `${name}(${precision})`\n );\n }\n return draft;\n }\n return `the type \\`${column.type}\\` has no VibORM scalar`;\n}\n\nexport function translatePostgresColumn(\n context: ColumnContext\n): ColumnTranslation {\n const { column } = context;\n const array = column.type.endsWith(\"[]\");\n const rawBase = array ? column.type.slice(0, -2) : column.type;\n const enumDef = context.enums.get(rawBase);\n let draft: FieldDraft;\n if (enumDef) {\n draft = { type: \"enum\", enum: [...enumDef.values] };\n } else {\n const base = postgresBase(normalizeType(rawBase), column, array);\n if (typeof base === \"string\") return { skip: base };\n draft = base;\n }\n return finish(draft, context, array, \"postgresql\", enumDef?.name);\n}\n\n/** The modifiers every dialect reads the same way: list, null, default. */\nfunction finish(\n draft: FieldDraft,\n context: ColumnContext,\n array: boolean,\n dialect: IntrospectionDialect,\n enumType?: string,\n approximated?: string\n): ColumnTranslation {\n const { column } = context;\n if (array) {\n if (!LIST_TYPES.has(draft.type))\n return { skip: `a list of ${draft.type} has no VibORM scalar` };\n draft.array = true;\n }\n if (column.nullable) draft.nullable = true;\n let skippedDefault: string | undefined;\n if (context.identity || column.autoIncrement) {\n if (draft.type === \"int\" || draft.type === \"bigint\")\n draft.generate = { kind: \"increment\" };\n else\n skippedDefault = `an auto-increment ${draft.type} has no document spelling`;\n } else if (column.default !== undefined) {\n skippedDefault = readDefault(draft, column, column.default, dialect);\n }\n return {\n field: draft,\n enumType,\n skippedDefault,\n approximated,\n };\n}\n\n// =============================================================================\n// SQLITE\n// =============================================================================\n\nconst SQLITE_ENUM = /^TEXT CHECK\\(/;\nconst SQLITE_ENUM_MEMBER = /'((?:[^']|'')*)'/g;\nconst SQLITE_NOW = \"(strftime('%Y-%m-%dT%H:%M:%fZ','now'))\";\n\n/** The enum values a SQLite CHECK spells, when the driver spells them so. */\nfunction sqliteEnumValues(context: ColumnContext): string[] | undefined {\n const { type } = context.column;\n const open = type.indexOf(\" IN (\");\n if (open === -1) return;\n const values = [...type.slice(open).matchAll(SQLITE_ENUM_MEMBER)].map(\n (match) => match[1]!.replaceAll(\"''\", \"'\")\n );\n return context.enumColumnType(values) === type ? values : undefined;\n}\n\n/** A declared SQLite type outside VibORM's spellings, read by affinity. */\nfunction sqliteAffinity(type: string): FieldDraft {\n if (type.includes(\"INT\")) return { type: \"int\" };\n if (type.includes(\"CHAR\") || type.includes(\"CLOB\") || type.includes(\"TEXT\"))\n return { type: \"string\" };\n if (type === \"\" || type.includes(\"BLOB\")) return { type: \"blob\" };\n if (type.includes(\"REAL\") || type.includes(\"FLOA\") || type.includes(\"DOUB\"))\n return { type: \"number\" };\n if (type.includes(\"BOOL\")) return { type: \"boolean\" };\n if (type.includes(\"DATETIME\") || type.includes(\"TIMESTAMP\"))\n return { type: \"datetime\" };\n if (type === \"DATE\") return { type: \"date\" };\n return { type: \"number\" };\n}\n\nexport function translateSqliteColumn(\n context: ColumnContext\n): ColumnTranslation {\n const { column } = context;\n const type = column.type.trim().toUpperCase();\n if (column.decimal)\n return finish(\n {\n type: \"decimal\",\n precision: column.decimal.precision,\n scale: column.decimal.scale,\n },\n context,\n type === \"TEXT\",\n \"sqlite\"\n );\n if (SQLITE_ENUM.test(column.type)) {\n const values = sqliteEnumValues(context);\n if (values === undefined)\n return { skip: `the CHECK in \\`${column.type}\\` is not a VibORM enum` };\n return finish({ type: \"enum\", enum: values }, context, false, \"sqlite\");\n }\n let draft: FieldDraft;\n let approximated: string | undefined;\n switch (type) {\n case \"TEXT\":\n draft =\n column.default?.trim() === SQLITE_NOW\n ? { type: \"datetime\" }\n : { type: \"string\" };\n break;\n case \"INTEGER\":\n draft = { type: \"int\" };\n break;\n case \"REAL\":\n draft = { type: \"number\" };\n break;\n case \"BLOB\":\n if (context.binaryKey) {\n draft = { type: \"string\", generate: { kind: \"uuid\", generate: false } };\n approximated =\n \"a BLOB key is read as a UUID, the key VibORM stores as sixteen bytes on SQLite; a key holding other bytes does not decode\";\n } else draft = { type: \"blob\" };\n break;\n case \"JSON\":\n draft = { type: \"json\" };\n break;\n default:\n draft = sqliteAffinity(type);\n approximated = `the declared type \\`${column.type}\\` is read by SQLite's affinity rules as ${draft.type}, which VibORM spells \\`${draft.type === \"string\" ? \"TEXT\" : draft.type === \"number\" ? \"REAL\" : draft.type === \"blob\" ? \"BLOB\" : draft.type === \"datetime\" || draft.type === \"date\" ? \"TEXT\" : \"INTEGER\"}\\``;\n }\n return finish(draft, context, false, \"sqlite\", undefined, approximated);\n}\n\n// =============================================================================\n// MYSQL\n// =============================================================================\n\nconst MYSQL_SIZED = /^(varchar|char|binary|varbinary|bit)\\((\\d+)\\)$/;\nconst MYSQL_TEMPORAL = /^(datetime|timestamp|time)(?:\\((\\d)\\))?$/;\nconst MYSQL_INTEGERS = new Set([\n \"tinyint\",\n \"tinyint unsigned\",\n \"smallint\",\n \"smallint unsigned\",\n \"mediumint\",\n \"mediumint unsigned\",\n \"int unsigned\",\n \"year\",\n]);\nconst MYSQL_TEXTS = new Set([\"tinytext\", \"mediumtext\", \"longtext\"]);\nconst MYSQL_BLOBS = new Set([\"tinyblob\", \"mediumblob\", \"longblob\"]);\nconst MYSQL_DISPLAY_WIDTH = /^(tinyint|smallint|mediumint|int|bigint)\\(\\d+\\)/;\n\nfunction mysqlNative(type: string): { db: \"mysql\"; type: string } {\n return { db: \"mysql\", type };\n}\n\n/** MySQL's column type (lowercased, display width dropped) as a field draft. */\nfunction mysqlBase(type: string, context: ColumnContext): FieldDraft | string {\n const { column } = context;\n if (type === \"text\") return { type: \"string\" };\n if (type === \"tinyint(1)\") return { type: \"boolean\" };\n const base = type.replace(MYSQL_DISPLAY_WIDTH, \"$1\");\n if (base === \"int\") return { type: \"int\" };\n if (base === \"bigint\") return { type: \"bigint\" };\n if (base === \"bigint unsigned\")\n return { type: \"bigint\", native: mysqlNative(\"BIGINT UNSIGNED\") };\n if (MYSQL_INTEGERS.has(base))\n return { type: \"int\", native: mysqlNative(base.toUpperCase()) };\n if (base === \"double\") return { type: \"number\" };\n if (base === \"float\") return { type: \"number\", native: mysqlNative(\"FLOAT\") };\n if (base === \"json\") return { type: \"json\" };\n if (base === \"blob\") return { type: \"blob\" };\n if (MYSQL_BLOBS.has(base))\n return { type: \"blob\", native: mysqlNative(base.toUpperCase()) };\n if (MYSQL_TEXTS.has(base))\n return { type: \"string\", native: mysqlNative(base.toUpperCase()) };\n if (base === \"date\") return { type: \"date\" };\n if (base.startsWith(\"decimal(\")) {\n const descriptor = column.decimal;\n if (descriptor === undefined)\n return `${column.type} is outside VibORM's fixed-decimal domain`;\n return {\n type: \"decimal\",\n precision: descriptor.precision,\n scale: descriptor.scale,\n };\n }\n const sized = MYSQL_SIZED.exec(base);\n if (sized) {\n const [, name, size] = sized;\n if (name === \"binary\" && size === \"16\" && context.binaryKey)\n return { type: \"string\", generate: { kind: \"uuid\", generate: false } };\n if (name === \"varchar\" && size === \"191\" && context.keyed)\n return { type: \"string\" };\n const native = mysqlNative(`${name!.toUpperCase()}(${size})`);\n return name === \"binary\" || name === \"varbinary\"\n ? { type: \"blob\", native }\n : { type: \"string\", native };\n }\n const temporal = MYSQL_TEMPORAL.exec(base);\n if (temporal) {\n const [, name, precision] = temporal;\n const draft: ValueDraft = { type: name === \"time\" ? \"time\" : \"datetime\" };\n if (name === \"timestamp\" || precision !== \"3\")\n draft.native = mysqlNative(\n precision === undefined\n ? name!.toUpperCase()\n : `${name!.toUpperCase()}(${precision})`\n );\n return draft;\n }\n return `the type \\`${column.type}\\` has no VibORM scalar`;\n}\n\nexport function translateMysqlColumn(\n context: ColumnContext\n): ColumnTranslation {\n const { column } = context;\n if (column.type.toUpperCase().startsWith(\"ENUM(\")) {\n const enumDef = context.enums.get(column.type);\n if (\n enumDef === undefined ||\n context.enumColumnType(enumDef.values) !== column.type\n )\n return { skip: `the enum \\`${column.type}\\` is not one VibORM spells` };\n return finish(\n { type: \"enum\", enum: [...enumDef.values] },\n context,\n false,\n \"mysql\"\n );\n }\n const base = mysqlBase(column.type.trim().toLowerCase(), context);\n if (typeof base === \"string\") return { skip: base };\n const approximated =\n base.type === \"string\" && base.generate?.kind === \"uuid\"\n ? \"a BINARY(16) key is read as a UUID, the key VibORM stores as sixteen bytes on MySQL; a key holding other bytes does not decode\"\n : undefined;\n return finish(base, context, false, \"mysql\", undefined, approximated);\n}\n\n// =============================================================================\n// SNOWFLAKE\n// =============================================================================\n\nconst SNOWFLAKE_NUMBER = /^number\\((\\d+),(\\d+)\\)$/;\nconst TYPE_PARAMETERS = /\\(.*\\)$/;\nconst SNOWFLAKE_VECTOR = /^vector\\((float|int), (\\d+)\\)$/;\nconst SNOWFLAKE_NOW =\n /^(?:current_timestamp|sysdate|systimestamp|localtimestamp|current_date|current_time|getdate)(?:\\(\\d*\\))?$/i;\n\n/**\n * Snowflake's column type (as its introspection spells it, lower case) as a\n * field draft. A `NUMBER(p,0)` wider than nine digits is a `bigint`, so no\n * integer past 2^53 is read through a JavaScript number; Snowflake's own\n * `INTEGER` is `NUMBER(38,0)`.\n */\nfunction snowflakeBase(column: ColumnDef): FieldDraft | string {\n const type = column.type.toLowerCase();\n const number = SNOWFLAKE_NUMBER.exec(type);\n if (number) {\n const precision = Number(number[1]);\n const scale = Number(number[2]);\n if (scale === 0) return { type: precision <= 9 ? \"int\" : \"bigint\" };\n return { type: \"decimal\", precision, scale };\n }\n const base = type.replace(TYPE_PARAMETERS, \"\");\n switch (base) {\n case \"float\":\n return { type: \"number\" };\n case \"varchar\":\n return { type: \"string\" };\n case \"boolean\":\n return { type: \"boolean\" };\n case \"date\":\n return { type: \"date\" };\n case \"time\":\n return { type: \"time\" };\n case \"timestamp_ntz\":\n case \"timestamp_ltz\":\n case \"timestamp_tz\":\n return { type: \"datetime\" };\n case \"binary\":\n return { type: \"blob\" };\n case \"variant\":\n case \"object\":\n case \"array\":\n return { type: \"json\" };\n case \"geography\":\n return { type: \"point\" };\n case \"geometry\":\n return \"a GEOMETRY is planar, in any SRID: VibORM's point is a geographic EPSG:4326 point (a GEOGRAPHY)\";\n default:\n break;\n }\n const vector = SNOWFLAKE_VECTOR.exec(type);\n if (vector?.[1] === \"float\")\n return { type: \"vector\", dimension: Number(vector[2]) };\n if (vector)\n return \"a VECTOR(INT) has no VibORM scalar: `s.vector()` holds floats\";\n return `the type \\`${column.type.toUpperCase()}\\` has no VibORM scalar`;\n}\n\nexport function translateSnowflakeColumn(\n context: ColumnContext\n): ColumnTranslation {\n const { column } = context;\n const base = snowflakeBase(column);\n if (typeof base === \"string\") return { skip: base };\n const timestamp = column.type.toLowerCase().replace(TYPE_PARAMETERS, \"\");\n const approximated =\n timestamp === \"timestamp_ntz\"\n ? \"a TIMESTAMP_NTZ holds a wall clock with no zone; VibORM reads it as UTC\"\n : timestamp === \"geography\"\n ? \"a GEOGRAPHY may hold any shape; VibORM reads it as a point, and a row holding another shape does not decode\"\n : undefined;\n // Snowflake's clocks are functions VibORM's generator stands for.\n if (\n column.default !== undefined &&\n SNOWFLAKE_NOW.test(column.default.trim()) &&\n (base.type === \"datetime\" || base.type === \"date\" || base.type === \"time\")\n ) {\n base.generate = { kind: \"now\" };\n const { default: _clock, ...rest } = column;\n return finish(\n base,\n { ...context, column: rest },\n false,\n \"snowflake\",\n undefined,\n approximated\n );\n }\n return finish(base, context, false, \"snowflake\", undefined, approximated);\n}\n","/**\n * Document keys from database names.\n *\n * A database name is kept as the key whenever it is a schema identifier; only a\n * name that is not one gets a derived key, and the model or field then carries\n * the real name (`table` / `column`). Every derivation is deterministic: the\n * same database gives the same document.\n */\n\nimport { isValidSchemaIdentifier } from \"../../schema/identifier\";\n\n/** F010's reserved member names: a column may not take them as its key. */\nconst RESERVED_MEMBERS = new Set([\"_count\", \"_distance\"]);\n\nconst INVALID_CHARACTER = /[^a-zA-Z0-9_]/g;\nconst LEADING_DIGIT = /^[0-9]/;\n\n/** The key a database name would take if it were free. */\nfunction keyCandidate(name: string): string {\n let key = name.replace(INVALID_CHARACTER, \"_\");\n if (key === \"\" || LEADING_DIGIT.test(key)) key = `_${key}`;\n return key.slice(0, 60);\n}\n\n/** One namespace of keys: a document's models, or one model's members. */\nexport class KeyAllocator {\n readonly #taken = new Set<string>();\n readonly #reserved: ReadonlySet<string>;\n\n constructor(reserved: ReadonlySet<string> = new Set()) {\n this.#reserved = reserved;\n }\n\n #free(key: string): boolean {\n return (\n !(this.#taken.has(key) || this.#reserved.has(key)) &&\n isValidSchemaIdentifier(key)\n );\n }\n\n /**\n * The database name itself when it is a free identifier, else the first free\n * of its sanitized spelling and that spelling suffixed `_2`, `_3` …\n */\n claimName(name: string): string {\n if (this.#free(name)) {\n this.#taken.add(name);\n return name;\n }\n return this.claim(keyCandidate(name));\n }\n\n /** `base`, else `base_2`, `base_3` … — the first that is free. */\n claim(base: string): string {\n const root = keyCandidate(base);\n let key = root;\n for (let n = 2; !this.#free(key); n++) key = `${root}_${n}`;\n this.#taken.add(key);\n return key;\n }\n}\n\n/** A member allocator: model members may not take F010's reserved names. */\nexport function memberAllocator(): KeyAllocator {\n return new KeyAllocator(RESERVED_MEMBERS);\n}\n\nconst SNAKE_ID_SUFFIX = /^(.+)_id$/i;\nconst CAMEL_ID_SUFFIX = /^(.*[a-z0-9])I[dD]$/;\n\n/**\n * The relation name a single foreign-key column suggests: `author_id` and\n * `authorId` both suggest `author`. Anything else suggests nothing, and the\n * caller falls back on the target's key.\n */\nexport function relationNameFromColumn(column: string): string | undefined {\n const match = SNAKE_ID_SUFFIX.exec(column) ?? CAMEL_ID_SUFFIX.exec(column);\n return match?.[1];\n}\n","/**\n * A live snapshot → a schema document (the draft `index.ts` canonicalizes).\n *\n * Pure: it reads the snapshot the dialect's own introspection wrote and the\n * catalog facts beside it, and says what it could not carry. Database names are\n * kept as document keys; a relation, which has no database name, is named from\n * its foreign key by one deterministic rule (see `relationNames`).\n */\n\nimport { isValidSchemaIdentifier } from \"../../schema/identifier\";\nimport {\n type EnumDocument,\n type FieldDocument,\n type IndexDocument,\n isRelationField,\n type JunctionDocument,\n type JunctionSidesDocument,\n type ModelDocument,\n type ModelTargetDocument,\n type SchemaDocument,\n} from \"../../schema/json/document\";\nimport type { JunctionReferentialAction } from \"../../schema/relation/types\";\nimport type { MigrationDriver } from \"../drivers/base\";\nimport type {\n EnumDef,\n ForeignKeyDef,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n} from \"../types\";\nimport { derivedMigrationName } from \"../utils\";\nimport {\n type ColumnContext,\n type ColumnTranslation,\n translateMysqlColumn,\n translatePostgresColumn,\n translateSnowflakeColumn,\n translateSqliteColumn,\n} from \"./columns\";\nimport { KeyAllocator, memberAllocator, relationNameFromColumn } from \"./names\";\nimport type {\n IntrospectionDialect,\n IntrospectionWarning,\n SkippedObject,\n} from \"./types\";\n\nexport interface TranslateInput {\n readonly snapshot: SchemaSnapshot;\n readonly dialect: IntrospectionDialect;\n readonly migrationDriver: MigrationDriver;\n /** PostgreSQL identity columns, keyed `table\\0column`. */\n readonly identityColumns: ReadonlySet<string>;\n /** Pure join tables to keep as a junction MODEL rather than a generated junction. */\n readonly junctionModels: ReadonlySet<string>;\n}\n\nexport interface Translation {\n readonly document: SchemaDocument;\n readonly skipped: SkippedObject[];\n readonly warnings: IntrospectionWarning[];\n /** The tables the document declares, models and generated junctions alike. */\n readonly tables: ReadonlySet<string>;\n /** The pure join tables written as a generated junction. */\n readonly generatedJunctions: ReadonlySet<string>;\n}\n\n/** One model under construction. */\ninterface ModelBuild {\n readonly key: string;\n readonly table: TableDef;\n readonly members: KeyAllocator;\n readonly fields: Record<string, FieldDocument>;\n /** Column name → field key, for the translated columns. */\n readonly fieldOf: Map<string, string>;\n readonly document: ModelDocument;\n /** Column sets the document declares unique (id, unique, uniques), sorted. */\n readonly keys: string[][];\n}\n\nconst TRANSLATORS: Record<\n IntrospectionDialect,\n (context: ColumnContext) => ColumnTranslation\n> = {\n postgresql: translatePostgresColumn,\n sqlite: translateSqliteColumn,\n mysql: translateMysqlColumn,\n snowflake: translateSnowflakeColumn,\n};\n\nconst BINARY_KEY_TYPES: Record<IntrospectionDialect, string | undefined> = {\n postgresql: undefined,\n sqlite: \"BLOB\",\n mysql: \"BINARY(16)\",\n snowflake: undefined,\n};\n\n/** `.map()` takes identifiers only, so a name outside them has no spelling. */\nconst UNMAPPABLE =\n \"its name is not an identifier (ASCII letters, digits and _, at most 63 bytes), which is all `.map()` accepts\";\n\n/** The warning a key column the database lets hold NULL carries. */\nconst NULLABLE_KEY =\n \"the database lets this primary key column hold NULL (SQLite does unless it is NOT NULL, outside a rowid table's INTEGER key), and the document declares it NOT NULL, as every model key is: a push of the document rebuilds the table to make it NOT NULL, which fails while a row's key is NULL and cannot keep what the table carries beyond the document (its `unstated` warnings)\";\n\n/** A junction foreign key's action: cascade, restrict or no action only. */\nfunction junctionAction(\n value: ReferentialAction | undefined\n): JunctionReferentialAction | undefined {\n const spelled = value ?? \"noAction\";\n return spelled === \"cascade\" ||\n spelled === \"restrict\" ||\n spelled === \"noAction\"\n ? spelled\n : undefined;\n}\n\n/** One action for both junction keys, or one per side (`source` first). */\ntype DeleteSpelling =\n | { onDelete: JunctionReferentialAction; onDeleteSides?: never }\n | { onDelete?: never; onDeleteSides: JunctionSidesDocument };\ntype UpdateSpelling =\n | { onUpdate: JunctionReferentialAction; onUpdateSides?: never }\n | { onUpdate?: never; onUpdateSides: JunctionSidesDocument };\n\n/**\n * The generated junction a pure join table is, named by its two key columns,\n * or `undefined` when either key has an action a junction cannot declare.\n */\nfunction generatedJunction(\n table: string,\n first: ForeignKeyDef,\n second: ForeignKeyDef\n): JunctionDocument | undefined {\n const deleteSource = junctionAction(first.onDelete);\n const deleteTarget = junctionAction(second.onDelete);\n const updateSource = junctionAction(first.onUpdate);\n const updateTarget = junctionAction(second.onUpdate);\n if (\n deleteSource === undefined ||\n deleteTarget === undefined ||\n updateSource === undefined ||\n updateTarget === undefined\n )\n return;\n const deletes: DeleteSpelling =\n deleteSource === deleteTarget\n ? { onDelete: deleteSource }\n : { onDeleteSides: { source: deleteSource, target: deleteTarget } };\n const updates: UpdateSpelling =\n updateSource === updateTarget\n ? { onUpdate: updateSource }\n : { onUpdateSides: { source: updateSource, target: updateTarget } };\n return {\n table,\n source: first.columns[0]!,\n target: second.columns[0]!,\n ...deletes,\n ...updates,\n };\n}\n\nfunction sameSet(a: readonly string[], b: readonly string[]): boolean {\n return a.length === b.length && a.every((item) => b.includes(item));\n}\n\nfunction sorted(columns: readonly string[]): string[] {\n return [...columns].sort();\n}\n\n/** One relation pair between two models, before its label is decided. */\ninterface Pair {\n readonly models: readonly [string, string];\n readonly label: string;\n readonly slots: Array<{ model: ModelBuild; key: string }>;\n}\n\nexport function translateSnapshot(input: TranslateInput): Translation {\n const { snapshot, dialect, migrationDriver } = input;\n const skipped: SkippedObject[] = [];\n const warnings: IntrospectionWarning[] = [];\n const readsNames =\n migrationDriver.capabilities.introspectionReadsConstraintNames;\n const enums = new Map<string, EnumDef>(\n (snapshot.enums ?? []).map((item) => [item.name, item])\n );\n const translateColumn: (context: ColumnContext) => ColumnTranslation =\n TRANSLATORS[dialect];\n\n // SQLite and MySQL store a uuid key as bytes (`BLOB`, `BINARY(16)`), and a\n // blob is never a key: such a primary-key column, and every foreign-key\n // column reaching one, is read as the uuid key it is VibORM's spelling of.\n const binaryKeys = new Set<string>();\n const binaryKeyType = BINARY_KEY_TYPES[dialect];\n if (binaryKeyType !== undefined) {\n const isBlob = (table: TableDef, column: string) =>\n table.columns.find((item) => item.name === column)?.type.toUpperCase() ===\n binaryKeyType;\n for (const table of snapshot.tables)\n for (const column of table.primaryKey?.columns ?? [])\n if (isBlob(table, column)) binaryKeys.add(`${table.name}\\0${column}`);\n for (let grew = true; grew; ) {\n grew = false;\n for (const table of snapshot.tables)\n for (const fk of table.foreignKeys)\n fk.columns.forEach((column, position) => {\n const id = `${table.name}\\0${column}`;\n const referenced = `${fk.referencedTable}\\0${fk.referencedColumns[position]}`;\n if (\n !binaryKeys.has(id) &&\n binaryKeys.has(referenced) &&\n isBlob(table, column)\n ) {\n binaryKeys.add(id);\n grew = true;\n }\n });\n }\n }\n\n // MySQL writes an indexed string as VARCHAR(191): the columns of a key, an\n // index or a foreign key.\n const keyedColumns = (table: TableDef) =>\n new Set([\n ...(table.primaryKey?.columns ?? []),\n ...table.uniqueConstraints.flatMap((unique) => unique.columns),\n ...table.indexes.flatMap((index) => (index.raw ? [] : index.columns)),\n ...table.foreignKeys.flatMap((foreignKey) => foreignKey.columns),\n ]);\n\n const modelKeys = new KeyAllocator();\n const builds = new Map<string, ModelBuild>();\n /** Enum type name → the columns using it. */\n const enumUses = new Map<\n string,\n Array<{ build: ModelBuild; field: string; column: string }>\n >();\n\n // ---------------------------------------------------------------------------\n // Tables → models with their scalar fields\n // ---------------------------------------------------------------------------\n for (const table of snapshot.tables) {\n const primaryKey = table.primaryKey;\n if (!primaryKey || primaryKey.columns.length === 0) {\n skipped.push({\n kind: \"table\",\n name: table.name,\n reason: \"it has no primary key, and a VibORM model is addressed by one\",\n });\n continue;\n }\n if (!isValidSchemaIdentifier(table.name)) {\n skipped.push({\n kind: \"table\",\n name: table.name,\n reason: UNMAPPABLE,\n });\n continue;\n }\n const translated = new Map<string, ColumnTranslation>();\n const keyed = keyedColumns(table);\n for (const column of table.columns) {\n if (!isValidSchemaIdentifier(column.name)) {\n translated.set(column.name, { skip: UNMAPPABLE });\n continue;\n }\n translated.set(\n column.name,\n translateColumn({\n column,\n enums,\n identity: input.identityColumns.has(`${table.name}\\0${column.name}`),\n enumColumnType: (values) =>\n migrationDriver.getEnumColumnType(table.name, column.name, values),\n binaryKey: binaryKeys.has(`${table.name}\\0${column.name}`),\n keyed: keyed.has(column.name),\n })\n );\n }\n const lostKey = primaryKey.columns.find((column) => {\n const result = translated.get(column);\n return result === undefined || \"skip\" in result;\n });\n if (lostKey !== undefined) {\n const result = translated.get(lostKey);\n skipped.push({\n kind: \"table\",\n name: table.name,\n reason: `its primary key column \"${lostKey}\" cannot be translated: ${result && \"skip\" in result ? result.skip : \"it is not a column of the table\"}`,\n });\n continue;\n }\n\n const key = modelKeys.claimName(table.name);\n const fields: Record<string, FieldDocument> = {};\n const document: ModelDocument = { fields };\n if (key !== table.name) document.table = table.name;\n const build: ModelBuild = {\n key,\n table,\n members: memberAllocator(),\n fields,\n fieldOf: new Map(),\n document,\n keys: [],\n };\n for (const column of table.columns) {\n const result = translated.get(column.name)!;\n if (\"skip\" in result) {\n skipped.push({\n kind: \"column\",\n table: table.name,\n name: column.name,\n reason: result.skip,\n });\n continue;\n }\n const fieldKey = build.members.claimName(column.name);\n const field = { ...result.field };\n if (fieldKey !== column.name) field.column = column.name;\n fields[fieldKey] = field;\n build.fieldOf.set(column.name, fieldKey);\n if (result.enumType !== undefined) {\n const uses = enumUses.get(result.enumType) ?? [];\n uses.push({ build, field: fieldKey, column: column.name });\n enumUses.set(result.enumType, uses);\n }\n if (result.skippedDefault !== undefined)\n skipped.push({\n kind: \"default\",\n table: table.name,\n name: column.name,\n reason: result.skippedDefault,\n });\n if (result.approximated !== undefined)\n warnings.push({\n kind: \"approximated\",\n table: table.name,\n name: column.name,\n message: result.approximated,\n });\n }\n\n // The primary key\n const pkFields = primaryKey.columns.map(\n (column) => build.fieldOf.get(column)!\n );\n // SQLite admits NULL in a key column other than a rowid table's INTEGER\n // key unless it is declared NOT NULL; a model key never holds one.\n pkFields.forEach((fieldKey, position) => {\n const field = fields[fieldKey]!;\n if (isRelationField(field) || !field.nullable) return;\n field.nullable = false;\n warnings.push({\n kind: \"approximated\",\n table: table.name,\n name: primaryKey.columns[position],\n message: NULLABLE_KEY,\n });\n });\n if (pkFields.length === 1) {\n const field = fields[pkFields[0]!]!;\n if (field.type !== \"toOne\" && field.type !== \"toMany\") {\n Object.assign(field, { id: true });\n // `.id()` on a string installs a ULID generator; a database cannot\n // prove the application generated its keys, so none is claimed.\n if (field.type === \"string\" && field.generate === undefined)\n Object.assign(field, {\n generate: { kind: \"ulid\", generate: false, implicit: true },\n });\n }\n } else {\n document.ids = [{ fields: pkFields }];\n }\n // SQLite's `WITHOUT ROWID`: the rows are clustered by this key.\n if (primaryKey.withoutRowid) document.withoutRowid = true;\n build.keys.push(sorted(primaryKey.columns));\n builds.set(table.name, build);\n }\n\n // ---------------------------------------------------------------------------\n // Unique constraints and indexes\n // ---------------------------------------------------------------------------\n for (const build of builds.values()) {\n const { table, fields, document, fieldOf } = build;\n const indexes: IndexDocument[] = [];\n const uniques: Array<{ fields: string[]; name?: string }> = [];\n const missing = (columns: readonly string[]) =>\n columns.find((column) => !fieldOf.has(column));\n\n // A total unique btree index IS a unique constraint to the differ (and\n // the only spelling MySQL has): one named the way a declared key is named\n // is read as that key, so it stays a `findUnique` key.\n const derivedUnique = (name: string, columns: readonly string[]) =>\n name.startsWith(`${table.name}_`) &&\n name.endsWith(\"_key\") &&\n columns.every((column) => fieldOf.has(column));\n const keyIndexes = table.indexes.filter(\n (index) =>\n index.unique &&\n !index.raw &&\n index.where === undefined &&\n (index.type === undefined || index.type === \"btree\") &&\n derivedUnique(index.name, index.columns)\n );\n const uniqueConstraints = [\n ...table.uniqueConstraints,\n ...keyIndexes.map((index) => ({\n name: index.name,\n columns: index.columns,\n })),\n ];\n for (const constraint of uniqueConstraints) {\n const lost = missing(constraint.columns);\n if (lost !== undefined) {\n skipped.push({\n kind: \"uniqueConstraint\",\n table: table.name,\n name: constraint.name,\n reason: `its column \"${lost}\" is not translated`,\n });\n continue;\n }\n const keys = constraint.columns.map((column) => fieldOf.get(column)!);\n const derived = (name: string) =>\n derivedMigrationName(`${table.name}_${name}_key`);\n if (\n keys.length === 1 &&\n (!readsNames || constraint.name === derived(constraint.columns[0]!))\n ) {\n Object.assign(fields[keys[0]!]!, { unique: true });\n build.keys.push(sorted(constraint.columns));\n continue;\n }\n if (!readsNames || constraint.name === derived(keys.join(\"_\"))) {\n uniques.push({ fields: keys });\n build.keys.push(sorted(constraint.columns));\n continue;\n }\n const prefix = `${table.name}_`;\n const named =\n constraint.name.startsWith(prefix) && constraint.name.endsWith(\"_key\")\n ? constraint.name.slice(prefix.length, -\"_key\".length)\n : undefined;\n if (named !== undefined && isValidSchemaIdentifier(named)) {\n uniques.push({ fields: keys, name: named });\n build.keys.push(sorted(constraint.columns));\n continue;\n }\n // A total unique btree index and a unique constraint enforce the same\n // key and the differ treats them as one; only the index spelling\n // carries an arbitrary name.\n indexes.push({ fields: keys, name: constraint.name, unique: true });\n warnings.push({\n kind: \"approximated\",\n table: table.name,\n name: constraint.name,\n message: `the unique constraint \"${constraint.name}\" is declared as a unique index under the same name, because a document names compound keys \"<table>_<name>_key\"; it is not a key \\`findUnique\\` accepts`,\n });\n }\n\n for (const index of table.indexes) {\n if (keyIndexes.includes(index)) continue;\n const lost = missing(index.columns);\n const reason = index.raw\n ? \"it is a raw index (`.rawIndex()`), which a document cannot declare: keep it in a TypeScript schema\"\n : index.where !== undefined\n ? `it is a partial index (WHERE ${index.where}), and a document has no \\`where\\`: keep it in a TypeScript schema`\n : lost !== undefined\n ? `its column \"${lost}\" is not translated`\n : undefined;\n if (reason !== undefined) {\n skipped.push({\n kind: \"index\",\n table: table.name,\n name: index.name,\n reason,\n });\n continue;\n }\n const declared: IndexDocument = {\n fields: index.columns.map((column) => fieldOf.get(column)!),\n name: index.name,\n };\n if (index.unique) declared.unique = true;\n if (index.type !== undefined && index.type !== \"btree\")\n declared.type = index.type;\n indexes.push(declared);\n }\n if (uniques.length > 0) document.uniques = uniques;\n if (indexes.length > 0) document.indexes = indexes;\n }\n\n // ---------------------------------------------------------------------------\n // Foreign keys → relations\n // ---------------------------------------------------------------------------\n interface Edge {\n readonly owner: ModelBuild;\n readonly target: ModelBuild;\n readonly fk: ForeignKeyDef;\n }\n const edgesByOwner = new Map<ModelBuild, Edge[]>();\n for (const owner of builds.values()) {\n const edges: Edge[] = [];\n const foreignKeys = [...owner.table.foreignKeys].sort((a, b) =>\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0\n );\n for (const fk of foreignKeys) {\n const target = builds.get(fk.referencedTable);\n const skip = (reason: string) =>\n skipped.push({\n kind: \"foreignKey\",\n table: owner.table.name,\n name: fk.name,\n reason,\n });\n if (target === undefined) {\n skip(\n `it references \"${fk.referencedTable}\", which the document does not declare`\n );\n continue;\n }\n const lostOwn = fk.columns.find((column) => !owner.fieldOf.has(column));\n const lostRef = fk.referencedColumns.find(\n (column) => !target.fieldOf.has(column)\n );\n if (lostOwn !== undefined || lostRef !== undefined) {\n skip(\n `its column \"${lostOwn ?? `${fk.referencedTable}.${lostRef}`}\" is not translated`\n );\n continue;\n }\n if (fk.onDelete === \"setDefault\" || fk.onUpdate === \"setDefault\") {\n skip(\n \"its referential action is SET DEFAULT, which a VibORM relation does not declare\"\n );\n continue;\n }\n if (!target.keys.some((key) => sameSet(key, fk.referencedColumns))) {\n skip(\n `it references (${fk.referencedColumns.join(\", \")}) of \"${fk.referencedTable}\", which the document does not declare as a key`\n );\n continue;\n }\n edges.push({ owner, target, fk });\n }\n edgesByOwner.set(owner, edges);\n }\n\n /**\n * A pure join table: two foreign keys, together exactly its columns and its\n * primary key, each referencing its target's primary key.\n */\n const joinTables = new Map<ModelBuild, readonly [Edge, Edge]>();\n for (const [owner, edges] of edgesByOwner) {\n const [first, second] = edges;\n if (edges.length !== 2 || first === undefined || second === undefined)\n continue;\n const table = owner.table;\n // A table another foreign key references is a row of its own, never a\n // junction: the reference would have no model to reach.\n if (\n snapshot.tables.some(\n (other) =>\n other !== table &&\n other.foreignKeys.some((fk) => fk.referencedTable === table.name)\n )\n )\n continue;\n const columns = table.columns.map((column) => column.name);\n const union = [...first.fk.columns, ...second.fk.columns];\n if (\n table.foreignKeys.length !== 2 ||\n first.fk.columns.some((column) => second.fk.columns.includes(column)) ||\n !sameSet(union, columns) ||\n !sameSet(table.primaryKey?.columns ?? [], columns) ||\n !edges.every((edge) =>\n sameSet(\n edge.fk.referencedColumns,\n edge.target.table.primaryKey?.columns ?? []\n )\n )\n )\n continue;\n joinTables.set(owner, [first, second]);\n }\n\n const pairs = new Map<string, Pair[]>();\n const addPair = (\n a: ModelBuild,\n b: ModelBuild,\n label: string,\n slots: Array<{ model: ModelBuild; key: string }>\n ) => {\n const models: readonly [string, string] =\n a.key < b.key ? [a.key, b.key] : [b.key, a.key];\n const id = models.join(\"\\0\");\n const list = pairs.get(id) ?? [];\n list.push({ models, label, slots });\n pairs.set(id, list);\n };\n\n const generatedJunctions = new Set<string>();\n const action = (\n value: ReferentialAction | undefined\n ): Exclude<ReferentialAction, \"setDefault\"> =>\n value === undefined || value === \"setDefault\" ? \"noAction\" : value;\n\n /** The to-one a foreign key gives its owner, and the inverse on its target. */\n const relationNames = (edge: Edge, siblings: readonly Edge[]) => {\n const { owner, target, fk } = edge;\n const single =\n fk.columns.length === 1\n ? relationNameFromColumn(owner.fieldOf.get(fk.columns[0]!)!)\n : undefined;\n const toOne = owner.members.claim(single ?? target.key);\n const shared =\n owner === target ||\n siblings.filter((other) => other.target === target).length > 1;\n const inverse = target.members.claim(\n shared ? `${owner.key}_by_${toOne}` : owner.key\n );\n return { toOne, inverse };\n };\n\n for (const owner of builds.values()) {\n const edges = edgesByOwner.get(owner) ?? [];\n const join = joinTables.get(owner);\n if (join) {\n const [first, second] = join;\n const junction =\n first.fk.columns.length === 1 && second.fk.columns.length === 1\n ? generatedJunction(owner.table.name, first.fk, second.fk)\n : undefined;\n const asGenerated =\n !input.junctionModels.has(owner.table.name) && junction !== undefined;\n if (asGenerated) {\n // The table is the generated junction of one many-to-many pair; it is\n // not a model. `verify.ts` keeps this form only when the junction the\n // pair generates IS this table, and demotes it to a model otherwise.\n builds.delete(owner.table.name);\n generatedJunctions.add(owner.table.name);\n const a = first.target;\n const b = second.target;\n const aName = a.members.claim(\n relationNameFromColumn(second.fk.columns[0]!) ?? b.key\n );\n const bName = b.members.claim(\n relationNameFromColumn(first.fk.columns[0]!) ?? a.key\n );\n a.fields[aName] = { type: \"toMany\", target: b.key, junction };\n b.fields[bName] = { type: \"toMany\", target: a.key };\n addPair(a, b, owner.table.name, [\n { model: a, key: aName },\n { model: b, key: bName },\n ]);\n continue;\n }\n }\n\n const names = new Map<Edge, { toOne: string; inverse: string }>();\n for (const edge of edges) {\n const { target, fk } = edge;\n const { toOne, inverse } = relationNames(edge, edges);\n names.set(edge, { toOne, inverse });\n const relation: ModelTargetDocument = {\n type: \"toOne\",\n target: target.key,\n fields: fk.columns.map((column) => owner.fieldOf.get(column)!),\n references: fk.referencedColumns.map(\n (column) => target.fieldOf.get(column)!\n ),\n onDelete: action(fk.onDelete),\n onUpdate: action(fk.onUpdate),\n };\n owner.fields[toOne] = relation;\n const unique = owner.keys.some((key) => sameSet(key, fk.columns));\n target.fields[inverse] = unique\n ? { type: \"toOne\", target: owner.key }\n : { type: \"toMany\", target: owner.key };\n addPair(owner, target, fk.name, [\n { model: owner, key: toOne },\n { model: target, key: inverse },\n ]);\n }\n\n if (join) {\n // A junction model: the table keeps its own shape, and the many-to-many\n // walks through it.\n const [first, second] = join;\n const a = first.target;\n const b = second.target;\n const firstName = names.get(first)!.toOne;\n const secondName = names.get(second)!.toOne;\n const aName = a.members.claim(secondName);\n const bName = b.members.claim(firstName);\n a.fields[aName] = {\n type: \"toMany\",\n target: b.key,\n junction: { model: owner.key, source: firstName, target: secondName },\n };\n b.fields[bName] = { type: \"toMany\", target: a.key };\n addPair(a, b, owner.table.name, [\n { model: a, key: aName },\n { model: b, key: bName },\n ]);\n }\n }\n\n // A pairing label where two models share more than one relation, or a\n // model relates to itself: the label is the foreign key's (or the join\n // table's) name, unique per pair of models.\n for (const list of pairs.values()) {\n const ambiguous =\n list.length > 1 || list[0]!.models[0] === list[0]!.models[1];\n if (!ambiguous) continue;\n for (const pair of list)\n for (const slot of pair.slots)\n Object.assign(slot.model.fields[slot.key]!, { name: pair.label });\n }\n\n // ---------------------------------------------------------------------------\n // Enums\n // ---------------------------------------------------------------------------\n const enumDocuments: Record<string, EnumDocument> = {};\n const enumKeys = new KeyAllocator();\n // Only PostgreSQL has enums of its own; a MySQL enum IS its column's type,\n // already inline on the field.\n for (const [name, def] of dialect === \"postgresql\" ? enums : []) {\n const uses = (enumUses.get(name) ?? []).filter((use) =>\n builds.has(use.build.table.name)\n );\n if (uses.length === 0) {\n skipped.push({\n kind: \"enum\",\n name,\n reason:\n \"no translated column uses it, and a document declares an enum through its fields\",\n });\n continue;\n }\n const only = uses.length === 1 ? uses[0]! : undefined;\n if (\n only &&\n migrationDriver.getEnumColumnType(\n only.build.table.name,\n only.column,\n def.values\n ) === name\n )\n continue; // the column's own derived type: inline values say exactly this\n const key = enumKeys.claimName(name);\n enumDocuments[key] = { values: [...def.values], name };\n for (const use of uses)\n Object.assign(use.build.fields[use.field]!, { enum: key });\n }\n\n const models: Record<string, ModelDocument> = {};\n for (const build of builds.values()) models[build.key] = build.document;\n const document: SchemaDocument = {\n version: 1,\n ...(Object.keys(enumDocuments).length > 0 ? { enums: enumDocuments } : {}),\n models,\n };\n return {\n document,\n skipped,\n warnings,\n tables: new Set([\n ...[...builds.values()].map((build) => build.table.name),\n ...generatedJunctions,\n ]),\n generatedJunctions,\n };\n}\n","/**\n * The proof that a document says what the database is.\n *\n * The document is parsed, validated, and serialized exactly as `push`\n * serializes a schema, then diffed against the snapshot the database was read\n * into, with the differ `push` uses. Every operation that diff plans is a place\n * where the document and the database disagree, reported as a `drift` warning:\n * a document with none pushes as a no-op. The translation never has to be\n * trusted to be the exact inverse of the forward direction — this runs it.\n */\n\nimport { hydrateSchemaNames } from \"../../schema/hydration\";\nimport { parseSchema } from \"../../schema/json\";\nimport type { SchemaDocument } from \"../../schema/json/document\";\nimport { diff } from \"../differ\";\nimport type { MigrationDriver } from \"../drivers/base\";\nimport { serializeModels } from \"../serializer\";\nimport type { ColumnDef, DiffOperation, SchemaSnapshot } from \"../types\";\nimport type { IntrospectionWarning } from \"./types\";\n\nfunction describeColumn(column: ColumnDef): string {\n return `${column.type}${column.nullable ? \" NULL\" : \" NOT NULL\"}${column.default === undefined ? \"\" : ` DEFAULT ${column.default}`}`;\n}\n\n/** An operation's kind, for one this file has no sentence for. */\nfunction operationType(operation: { readonly type: string }): string {\n return operation.type;\n}\n\nfunction describe(operation: DiffOperation): IntrospectionWarning {\n const push = (\n table: string | undefined,\n name: string | undefined,\n message: string\n ) => ({\n kind: \"drift\" as const,\n table,\n name,\n message: `push would ${message}`,\n });\n switch (operation.type) {\n case \"createTable\":\n return push(\n operation.table.name,\n undefined,\n `create table \"${operation.table.name}\"`\n );\n case \"dropTable\":\n return push(\n operation.tableName,\n undefined,\n `drop table \"${operation.tableName}\"`\n );\n case \"addColumn\":\n return push(\n operation.tableName,\n operation.column.name,\n `add column \"${operation.column.name}\" (${describeColumn(operation.column)})`\n );\n case \"dropColumn\":\n return push(\n operation.tableName,\n operation.columnName,\n `drop column \"${operation.columnName}\"`\n );\n case \"alterColumn\":\n return push(\n operation.tableName,\n operation.columnName,\n `alter column \"${operation.columnName}\" from ${describeColumn(operation.from)} to ${describeColumn(operation.to)}`\n );\n case \"createIndex\":\n return push(\n operation.tableName,\n operation.index.name,\n `create index \"${operation.index.name}\" on (${operation.index.columns.join(\", \")})`\n );\n case \"dropIndex\":\n return push(\n operation.tableName,\n operation.indexName,\n `drop index \"${operation.indexName}\"`\n );\n case \"addForeignKey\":\n return push(\n operation.tableName,\n operation.fk.name,\n `add foreign key \"${operation.fk.name}\" on (${operation.fk.columns.join(\", \")})`\n );\n case \"dropForeignKey\":\n return push(\n operation.tableName,\n operation.fkName,\n `drop foreign key \"${operation.fkName}\"`\n );\n case \"addUniqueConstraint\":\n return push(\n operation.tableName,\n operation.constraint.name,\n `add unique constraint \"${operation.constraint.name}\" on (${operation.constraint.columns.join(\", \")})`\n );\n case \"dropUniqueConstraint\":\n return push(\n operation.tableName,\n operation.constraintName,\n `drop unique constraint \"${operation.constraintName}\"`\n );\n case \"addPrimaryKey\":\n return push(\n operation.tableName,\n operation.primaryKey.name,\n `add a primary key on (${operation.primaryKey.columns.join(\", \")})`\n );\n case \"dropPrimaryKey\":\n return push(\n operation.tableName,\n operation.constraintName,\n `drop primary key \"${operation.constraintName}\"`\n );\n case \"createEnum\":\n return push(\n undefined,\n operation.enumDef.name,\n `create enum \"${operation.enumDef.name}\"`\n );\n case \"dropEnum\":\n return push(\n undefined,\n operation.enumName,\n `drop enum \"${operation.enumName}\"`\n );\n case \"alterEnum\":\n return push(\n undefined,\n operation.enumName,\n `alter enum \"${operation.enumName}\"`\n );\n case \"renameTable\":\n return push(\n operation.from,\n undefined,\n `rename table \"${operation.from}\" to \"${operation.to}\"`\n );\n case \"renameColumn\":\n return push(\n operation.tableName,\n operation.from,\n `rename column \"${operation.from}\" to \"${operation.to}\"`\n );\n default:\n return push(undefined, undefined, operationType(operation));\n }\n}\n\n/** The tables an operation touches, for demoting a generated junction. */\nfunction tableOf(warning: IntrospectionWarning): string | undefined {\n return warning.table;\n}\n\nexport interface Verification {\n readonly warnings: IntrospectionWarning[];\n /** Tables with at least one drift. */\n readonly drifted: ReadonlySet<string>;\n}\n\n/**\n * Diff the document against the live snapshot of the tables it declares.\n *\n * `current` holds exactly those tables (and the enums their columns use), so\n * what the document deliberately leaves out — a skipped table, a view — is not\n * reported twice. Throws what `parseSchema(…, { validate: true })` throws: a\n * document that does not validate is a translation bug, never a drift.\n */\nexport async function verifyDocument(\n document: SchemaDocument,\n current: SchemaSnapshot,\n migrationDriver: MigrationDriver\n): Promise<Verification> {\n const schema = parseSchema(document, { validate: true });\n hydrateSchemaNames(schema);\n const desired = serializeModels(schema, { migrationDriver });\n const readsNames =\n migrationDriver.capabilities.introspectionReadsConstraintNames;\n const result = await diff(current, desired, {\n matchConstraintsByShape: !readsNames,\n refuseConstraintNameChurn: false,\n });\n // On a dialect that reads constraint names, a constraint the database holds\n // under another name is a drop and an add of one shape. `push` refuses that\n // rather than renaming it, so the pair is reported as the one fact it is.\n const renamed = new Set<DiffOperation>();\n const warnings: IntrospectionWarning[] = [];\n for (const added of result.operations) {\n if (added.type !== \"addForeignKey\" && added.type !== \"addUniqueConstraint\")\n continue;\n const columns = (\n added.type === \"addForeignKey\" ? added.fk : added.constraint\n ).columns.join(\"\\0\");\n const live = current.tables.find((table) => table.name === added.tableName);\n const dropped = result.operations.find((operation) => {\n if (renamed.has(operation)) return false;\n if (\n added.type === \"addForeignKey\" &&\n operation.type === \"dropForeignKey\" &&\n operation.tableName === added.tableName\n )\n return live?.foreignKeys.some(\n (fk) =>\n fk.name === operation.fkName &&\n fk.columns.join(\"\\0\") === columns &&\n fk.referencedTable === added.fk.referencedTable\n );\n if (\n added.type === \"addUniqueConstraint\" &&\n operation.type === \"dropUniqueConstraint\" &&\n operation.tableName === added.tableName\n )\n return live?.uniqueConstraints.some(\n (unique) =>\n unique.name === operation.constraintName &&\n unique.columns.join(\"\\0\") === columns\n );\n return false;\n });\n if (dropped === undefined) continue;\n renamed.add(added);\n renamed.add(dropped);\n const actual =\n dropped.type === \"dropForeignKey\"\n ? dropped.fkName\n : dropped.type === \"dropUniqueConstraint\"\n ? dropped.constraintName\n : \"\";\n const wanted =\n added.type === \"addForeignKey\" ? added.fk.name : added.constraint.name;\n warnings.push({\n kind: \"drift\",\n table: added.tableName,\n name: actual,\n message: `push refuses this table: the constraint \"${actual}\" is the one VibORM names \"${wanted}\", and a document cannot name it`,\n });\n }\n for (const operation of result.operations)\n if (!renamed.has(operation)) warnings.push(describe(operation));\n for (const change of result.ambiguousChanges)\n warnings.push(\n change.type === \"ambiguousColumn\"\n ? {\n kind: \"drift\",\n table: change.tableName,\n name: change.droppedColumn.name,\n message: `push would replace column \"${change.droppedColumn.name}\" by \"${change.addedColumn.name}\"`,\n }\n : {\n kind: \"drift\",\n table: change.droppedTable,\n message: `push would replace table \"${change.droppedTable}\" by \"${change.addedTable}\"`,\n }\n );\n // A primary key's name is matched by name, never by diff: push refuses one\n // it would have to rename rather than planning anything.\n if (readsNames) {\n const desiredTables = new Map(\n desired.tables.map((table) => [table.name, table])\n );\n for (const table of current.tables) {\n const actual = table.primaryKey?.name;\n const wanted = desiredTables.get(table.name)?.primaryKey?.name;\n if (actual !== undefined && wanted !== undefined && actual !== wanted)\n warnings.push({\n kind: \"drift\",\n table: table.name,\n name: actual,\n message: `push refuses this table: its primary key is named \"${actual}\" and VibORM names it \"${wanted}\"`,\n });\n }\n }\n const drifted = new Set<string>();\n for (const warning of warnings) {\n const table = tableOf(warning);\n if (table !== undefined) drifted.add(table);\n }\n return { warnings, drifted };\n}\n","/**\n * `viborm/schema/introspect` — a schema document from an existing database.\n *\n * ```ts\n * import { introspectSchema } from \"viborm/schema/introspect\";\n * import { parseSchema } from \"viborm/schema/json\";\n *\n * const { document, skipped, warnings } = await introspectSchema({ url });\n * const db = createClient({ schema: parseSchema(document), databaseUrl: url });\n * ```\n *\n * The document is the canonical form of `viborm/schema/json`: there is no\n * second format, and a TypeScript schema generator can be written from it\n * later without reading the database again. What the document does not carry\n * is listed in `skipped`, what it states with less certainty than the database\n * proves is an `approximated` warning, what a table carries that the document\n * has no spelling for (a collation, `STRICT`, a trigger: the dialect's\n * `adoptionHazards`) is an `unstated` warning, and every place where a `push`\n * of it would change the database is a `drift` warning, found by running\n * push's own serializer and differ against the snapshot the database was read\n * into. `light: true` writes only what a client reads (`lighten`).\n *\n * This entry is tooling: it registers every migration driver and imports the\n * driver a URL names on demand. An application never imports it, so the\n * application bundle carries none of it.\n */\n\nimport type { AnyDriver } from \"../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { parseSchema, serializeSchema } from \"../../schema/json\";\nimport type { SchemaDocument } from \"../../schema/json/document\";\nimport { registerEveryMigrationDriver } from \"../dialects/every\";\nimport type { SchemaSnapshot } from \"../types\";\nimport { openDriver } from \"./connect\";\nimport { readCatalog } from \"./read\";\nimport { translateSnapshot } from \"./translate\";\nimport type {\n IntrospectionDialect,\n IntrospectionWarning,\n IntrospectSchemaResult,\n SkippedObject,\n} from \"./types\";\nimport { verifyDocument } from \"./verify\";\n\nregisterEveryMigrationDriver();\n\nexport type {\n IntrospectionDialect,\n IntrospectionWarning,\n IntrospectSchemaResult,\n SkippedKind,\n SkippedObject,\n} from \"./types\";\n\ninterface IntrospectScope {\n /** Only these tables (exact physical names). */\n readonly tables?: readonly string[];\n /**\n * A light document: only what a client reads (models, fields with their\n * type, nullability, list-ness, keys, uniques, defaults and generators,\n * native types, relations, names), without the indexes only migrations\n * read. It is marked `\"light\": true`, and every migration path refuses it.\n * `skipped` and `warnings` then keep only what changes what a client sees:\n * no index or CHECK constraint, no `unstated` or `drift` warning.\n */\n readonly light?: boolean;\n}\n\nexport type IntrospectSchemaOptions =\n | (IntrospectScope & {\n /**\n * The database: `postgres://` / `postgresql://`, `mysql://`, `file:` / `sqlite:` or a\n * `.db` / `.sqlite` path (opened read-only), or `libsql://`. The\n * connection is opened for this call and always closed.\n */\n readonly url: string;\n readonly driver?: never;\n })\n | (IntrospectScope & {\n /**\n * A driver you constructed (a D1 binding, a custom pool, a PostgreSQL\n * `namespace`). It is yours: it is not closed.\n */\n readonly driver: AnyDriver;\n readonly url?: never;\n });\n\nconst DIALECTS: readonly IntrospectionDialect[] = [\n \"postgresql\",\n \"sqlite\",\n \"mysql\",\n \"snowflake\",\n];\n\n/**\n * Snowflake is read, never pushed to: a drift against it has no push to\n * describe, and what the document cannot promise is that its keys hold.\n */\nconst SNOWFLAKE_KEYS: IntrospectionWarning = {\n kind: \"approximated\",\n message:\n \"Snowflake enforces no primary, unique or foreign key: the document's keys, uniques and relations are the ones the catalog declares, and a row may break them\",\n};\n\nfunction isIntrospectionDialect(\n dialect: string\n): dialect is IntrospectionDialect {\n return DIALECTS.some((item) => item === dialect);\n}\n\n/** The live tables the document declares, and the enums their columns use. */\nfunction declaredSnapshot(\n snapshot: SchemaSnapshot,\n tables: ReadonlySet<string>\n): SchemaSnapshot {\n const kept = snapshot.tables.filter((table) => tables.has(table.name));\n const used = new Set(\n kept.flatMap((table) =>\n table.columns.map((column) =>\n column.type.endsWith(\"[]\") ? column.type.slice(0, -2) : column.type\n )\n )\n );\n const enums = snapshot.enums?.filter((item) => used.has(item.name));\n return {\n tables: kept,\n ...(enums && enums.length > 0 ? { enums } : {}),\n };\n}\n\n/**\n * The light form of a canonical document: every index left out, and the\n * report narrowed to what a client sees. An `approximated` warning naming an\n * index (a unique constraint written as a unique index) goes with it.\n */\nfunction lighten(result: IntrospectSchemaResult): IntrospectSchemaResult {\n const dropped = new Set<string>();\n const models: SchemaDocument[\"models\"] = {};\n for (const [key, { indexes, ...model }] of Object.entries(\n result.document.models\n )) {\n for (const index of indexes ?? [])\n dropped.add(`${model.table ?? key}\\0${index.name}`);\n models[key] = model;\n }\n return {\n ...result,\n document: serializeSchema(\n parseSchema({ ...result.document, light: true, models })\n ),\n skipped: result.skipped.filter(\n (item) => item.kind !== \"index\" && item.kind !== \"check\"\n ),\n warnings: result.warnings.filter(\n (warning) =>\n warning.kind === \"approximated\" &&\n !dropped.has(`${warning.table}\\0${warning.name}`)\n ),\n };\n}\n\nasync function introspectDriver(\n driver: AnyDriver,\n tables: readonly string[] | undefined\n): Promise<IntrospectSchemaResult> {\n const introspectionDialect = driver.dialect;\n if (!isIntrospectionDialect(introspectionDialect))\n throw new MigrationError(\n `introspectSchema does not translate ${introspectionDialect} yet; PostgreSQL, SQLite, MySQL and Snowflake are supported.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { dialect: introspectionDialect, feature: \"introspect-schema\" } }\n );\n const catalog = await readCatalog(driver, introspectionDialect, tables);\n\n // A pure join table is first written as the generated junction of its pair;\n // where that junction is not exactly this table, it becomes a junction model\n // and the document is translated again.\n const junctionModels = new Set<string>();\n for (let attempt = 0; ; attempt++) {\n const translation = translateSnapshot({\n snapshot: catalog.snapshot,\n dialect: introspectionDialect,\n migrationDriver: catalog.migrationDriver,\n identityColumns: catalog.identityColumns,\n junctionModels,\n });\n const verification =\n introspectionDialect === \"snowflake\"\n ? { warnings: [SNOWFLAKE_KEYS], drifted: new Set<string>() }\n : await verifyDocument(\n translation.document,\n declaredSnapshot(catalog.snapshot, translation.tables),\n catalog.migrationDriver\n );\n const demote = [...translation.generatedJunctions].filter((table) =>\n verification.drifted.has(table)\n );\n if (demote.length > 0 && attempt === 0) {\n for (const table of demote) junctionModels.add(table);\n continue;\n }\n const document: SchemaDocument = serializeSchema(\n parseSchema(translation.document)\n );\n const skipped: SkippedObject[] = [\n ...catalog.skipped,\n ...translation.skipped,\n ];\n const warnings: IntrospectionWarning[] = [\n ...translation.warnings,\n // Each CHECK constraint is already in `skipped`, with its definition.\n ...catalog.hazards\n .filter(\n ({ table, feature }) =>\n translation.tables.has(table) && !feature.startsWith(\"CHECK\")\n )\n .map(({ table, feature }) => ({\n kind: \"unstated\" as const,\n table,\n message: `the document cannot carry ${feature}: the database keeps it and a push of the document plans nothing for it, but a push that recreates the table or the column cannot keep it`,\n })),\n ...verification.warnings,\n ];\n return { document, skipped, warnings, dialect: introspectionDialect };\n }\n}\n\n/**\n * Read an existing database into a schema document.\n *\n * Never invents: a fact the catalog does not prove is not in the document, and\n * what is lost or approximated is said in `skipped` and `warnings`.\n */\nexport async function introspectSchema(\n options: IntrospectSchemaOptions\n): Promise<IntrospectSchemaResult> {\n const read = async (driver: AnyDriver) => {\n const result = await introspectDriver(driver, options.tables);\n return options.light ? lighten(result) : result;\n };\n if (options.driver !== undefined) return await read(options.driver);\n const { driver } = await openDriver(options.url);\n try {\n return await read(driver);\n } finally {\n await driver.disconnect();\n }\n}\n"],"mappings":"gdAkBA,MAAM,EAAS,yBACT,EAAc,0BAGpB,SAAS,WAAW,EAAiC,CACnD,IAAK,IAAM,IAAU,CAAC,YAAa,UAAW,UAAW,QAAQ,CAC/D,GAAI,EAAI,WAAW,EAAO,CAAE,OAAO,EAAI,MAAM,EAAO,OAAO,CAE7D,OAAO,EAAO,KAAK,EAAI,CAAG,IAAA,GAAY,EAGxC,eAAsB,WAAW,EAAoC,CACnE,IAAM,EAAS,EAAO,KAAK,EAAI,GAAG,IAAI,aAAa,CACnD,GAAI,IAAW,YAAc,IAAW,aAAc,CACpD,GAAM,CAAE,YAAa,MAAM,OAAO,YAClC,MAAO,CACL,OAAQ,IAAI,EAAS,CAAE,YAAa,EAAK,QAAS,EAAE,CAAE,CAAC,CACvD,QAAS,aACV,CAEH,GACE,IAAW,UACX,IAAW,QACX,IAAW,SACX,IAAW,MACX,IAAW,MACX,CACA,GAAM,CAAE,gBAAiB,MAAM,OAAO,gBAChC,EAAS,IAAI,IAAI,EAAI,CACrB,EAAY,EAAO,aAAa,IAAI,YAAY,EAAI,IAAA,GAE1D,OADA,EAAO,aAAa,OAAO,YAAY,CAChC,CACL,OAAQ,IAAI,EAAa,CACvB,YAAa,EAAO,KACpB,GAAI,IAAc,IAAA,GAAY,EAAE,CAAG,CAAE,YAAW,CACjD,CAAC,CACF,QAAS,SACV,CAEH,GAAI,IAAW,QAAS,CACtB,GAAM,CAAE,gBAAiB,MAAM,OAAO,gBACtC,MAAO,CAAE,OAAQ,IAAI,EAAa,CAAE,YAAa,EAAK,CAAC,CAAE,QAAS,QAAS,CAE7E,GAAI,IAAW,YACb,MAAM,IAAI,EACR,oMACA,EAAgB,cAChB,CAAE,KAAM,CAAE,QAAS,iBAAkB,CAAE,CACxC,CACH,GAAI,IAAW,aAAe,IAAW,UACvC,MAAM,IAAI,EACR,iGACA,EAAgB,sBAChB,CAA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