viborm 1.12.1 → 1.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/{adapter-internals-DNY4JWFC.mjs → adapter-internals-DZO1WI67.mjs} +2 -2
- package/dist/adapter-internals-DZO1WI67.mjs.map +1 -0
- package/dist/{adapter-namespace-VikEzb7o.mjs → adapter-namespace-C9RM19_J.mjs} +1 -1
- package/dist/{adapter-namespace-VikEzb7o.mjs.map → adapter-namespace-C9RM19_J.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{batch-refs-ZHBzfoBC.mjs → batch-refs-DShoaHb7.mjs} +1 -1
- package/dist/{batch-refs-ZHBzfoBC.mjs.map → batch-refs-DShoaHb7.mjs.map} +1 -1
- package/dist/builder-yLL4r6JS.mjs +2 -0
- package/dist/builder-yLL4r6JS.mjs.map +1 -0
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/bun-sqlite.mjs.map +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/{chain-CoOL8l4W.mjs → chain-3bgO2RX3.mjs} +2 -2
- package/dist/{chain-CoOL8l4W.mjs.map → chain-3bgO2RX3.mjs.map} +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/client-Bbke7iRo.mjs +50 -0
- package/dist/client-Bbke7iRo.mjs.map +1 -0
- package/dist/{client-DMbHPHC_.d.mts → client-Dx-6NncH.d.mts} +6 -3
- package/dist/client-nkU6M5bV.mjs +2 -0
- package/dist/client-nkU6M5bV.mjs.map +1 -0
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/{datetime-physical-codec-Cdgq6sGs.mjs → datetime-physical-codec-kE6fh5zZ.mjs} +1 -1
- package/dist/{datetime-physical-codec-Cdgq6sGs.mjs.map → datetime-physical-codec-kE6fh5zZ.mjs.map} +1 -1
- package/dist/driver-BRYL6K0W.mjs +2 -0
- package/dist/driver-BRYL6K0W.mjs.map +1 -0
- package/dist/{driver-DX8GWgGf.mjs → driver-CcEhJcsE.mjs} +1 -1
- package/dist/{driver-DX8GWgGf.mjs.map → driver-CcEhJcsE.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/{error-mapping-D--MVRCY.mjs → error-mapping-DW7TYOyA.mjs} +2 -2
- package/dist/{error-mapping-D--MVRCY.mjs.map → error-mapping-DW7TYOyA.mjs.map} +1 -1
- package/dist/every-hDecAr5k.mjs +2 -0
- package/dist/every-hDecAr5k.mjs.map +1 -0
- package/dist/{fs-estate-CfvH8Fxa.mjs → fs-estate-Bfy9RFvT.mjs} +2 -2
- package/dist/{fs-estate-CfvH8Fxa.mjs.map → fs-estate-Bfy9RFvT.mjs.map} +1 -1
- package/dist/identifier-conversion-771tvRzd.mjs +2 -0
- package/dist/identifier-conversion-771tvRzd.mjs.map +1 -0
- package/dist/identifiers-DLcLFNim.mjs +2 -0
- package/dist/identifiers-DLcLFNim.mjs.map +1 -0
- package/dist/identity-b2N94bh1.mjs +2 -0
- package/dist/identity-b2N94bh1.mjs.map +1 -0
- package/dist/{index-B4Bo2kEi.d.mts → index-B8MMx5Al.d.mts} +104 -16
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{invariant-Dw9UB49x.mjs → invariant-CKZrz_S2.mjs} +1 -1
- package/dist/{invariant-Dw9UB49x.mjs.map → invariant-CKZrz_S2.mjs.map} +1 -1
- package/dist/{keys-CyfjT6uC.mjs → keys-BcQgRjMB.mjs} +2 -2
- package/dist/{keys-CyfjT6uC.mjs.map → keys-BcQgRjMB.mjs.map} +1 -1
- package/dist/keys-M0pWraMM.mjs +2 -0
- package/dist/keys-M0pWraMM.mjs.map +1 -0
- package/dist/libsql-lOqKLyZA.mjs +11 -0
- package/dist/libsql-lOqKLyZA.mjs.map +1 -0
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/{memory-BXOh0pq2.mjs → memory-CsRVfZdT.mjs} +2 -2
- package/dist/{memory-BXOh0pq2.mjs.map → memory-CsRVfZdT.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +5 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +5 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +5 -5
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.d.mts +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.d.mts +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/surrealdb.d.mts +6 -0
- package/dist/migrations/surrealdb.mjs +2 -0
- package/dist/migrations/surrealdb.mjs.map +1 -0
- package/dist/migrations/tenant.d.mts +3 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/migrations.mjs.map +1 -1
- package/dist/{model-u8Ug971J.mjs → model-DK9BhhNF.mjs} +2 -2
- package/dist/{model-u8Ug971J.mjs.map → model-DK9BhhNF.mjs.map} +1 -1
- package/dist/mysql-CIdv4h7j.mjs +100 -0
- package/dist/mysql-CIdv4h7j.mjs.map +1 -0
- package/dist/mysql-adapter-C3d-TdaO.mjs +2 -0
- package/dist/{mysql-adapter-BZtZrWeX.mjs.map → mysql-adapter-C3d-TdaO.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/{object-store-DdgcT8d9.mjs → object-store-DdKoB-lN.mjs} +2 -2
- package/dist/{object-store-DdgcT8d9.mjs.map → object-store-DdKoB-lN.mjs.map} +1 -1
- package/dist/{object-store-BI1YgcZ9.d.mts → object-store-DlGfGCb4.d.mts} +4 -4
- package/dist/on.d.mts +1 -1
- package/dist/on.mjs +1 -1
- package/dist/ordering.d.mts +1 -1
- package/dist/ordering.mjs +3 -3
- package/dist/ordering.mjs.map +1 -1
- package/dist/permissions.d.mts +1 -1
- package/dist/pg.d.mts +1 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-rsXqQbJR.d.mts → planner-DUjM5jQk.d.mts} +26 -1
- package/dist/{postgres-CrjBX4Yj.mjs → postgres-V7noUFbG.mjs} +45 -40
- package/dist/postgres-V7noUFbG.mjs.map +1 -0
- package/dist/{postgres-adapter--PJvhRSM.mjs → postgres-adapter-CvLB764t.mjs} +2 -2
- package/dist/{postgres-adapter--PJvhRSM.mjs.map → postgres-adapter-CvLB764t.mjs.map} +1 -1
- package/dist/postgres-adapter-D53hxZM4.mjs +2 -0
- package/dist/postgres-adapter-D53hxZM4.mjs.map +1 -0
- package/dist/{postgres-result-ehQiy2H-.mjs → postgres-result-CJ8C5cck.mjs} +1 -1
- package/dist/{postgres-result-ehQiy2H-.mjs.map → postgres-result-CJ8C5cck.mjs.map} +1 -1
- package/dist/postgres.d.mts +1 -1
- package/dist/postgres.mjs +1 -1
- package/dist/{relation-bound-5hindjxU.mjs → relation-bound-C02WchLT.mjs} +1 -1
- package/dist/{relation-bound-5hindjxU.mjs.map → relation-bound-C02WchLT.mjs.map} +1 -1
- package/dist/{result-parsing-Dkgy-xcy.mjs → result-parsing-Bj0gVF-R.mjs} +1 -1
- package/dist/{result-parsing-Dkgy-xcy.mjs.map → result-parsing-Bj0gVF-R.mjs.map} +1 -1
- package/dist/{result-shape-BPdZ1rUk.mjs → result-shape-D5gZFVps.mjs} +2 -2
- package/dist/{result-shape-BPdZ1rUk.mjs.map → result-shape-D5gZFVps.mjs.map} +1 -1
- package/dist/{rows-C4hPsLfi.mjs → rows-B1SG8qg9.mjs} +2 -2
- package/dist/{rows-C4hPsLfi.mjs.map → rows-B1SG8qg9.mjs.map} +1 -1
- package/dist/rows-of-qH0_KyL6.mjs.map +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema/json.mjs.map +1 -1
- package/dist/{schema-C8_nS6Ub.mjs → schema-DKL7GSu7.mjs} +2 -2
- package/dist/{schema-C8_nS6Ub.mjs.map → schema-DKL7GSu7.mjs.map} +1 -1
- package/dist/{schema-introspection-BiG5153d.mjs → schema-introspection-BogU9kCO.mjs} +2 -2
- package/dist/{schema-introspection-BiG5153d.mjs.map → schema-introspection-BogU9kCO.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-Dcaqm09G.mjs → select-assembly-BL9BG6oR.mjs} +1 -1
- package/dist/select-assembly-BL9BG6oR.mjs.map +1 -0
- package/dist/soft-delete.d.mts +1 -1
- package/dist/{sql-statement-tokens-CV2qkIKN.mjs → sql-statement-tokens-ugBPr6SM.mjs} +1 -1
- package/dist/{sql-statement-tokens-CV2qkIKN.mjs.map → sql-statement-tokens-ugBPr6SM.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sqlite-adapter-CVKv1u4i.mjs +2 -0
- package/dist/{sqlite-adapter-CMRvEsOv.mjs.map → sqlite-adapter-CVKv1u4i.mjs.map} +1 -1
- package/dist/{sqlite-utils-DztTzv08.mjs → sqlite-utils-B-Y47_Uz.mjs} +2 -2
- package/dist/{sqlite-utils-DztTzv08.mjs.map → sqlite-utils-B-Y47_Uz.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/standard-sql-BHpLmLeM.mjs +6 -0
- package/dist/standard-sql-BHpLmLeM.mjs.map +1 -0
- package/dist/surrealdb.d.mts +86 -0
- package/dist/surrealdb.mjs +2 -0
- package/dist/surrealdb.mjs.map +1 -0
- package/dist/surrealql-Bnu3BzHE.mjs +2 -0
- package/dist/surrealql-Bnu3BzHE.mjs.map +1 -0
- package/dist/{to-many-CMK2Ys4N.mjs → to-many-Dd1m0XqX.mjs} +2 -2
- package/dist/{to-many-CMK2Ys4N.mjs.map → to-many-Dd1m0XqX.mjs.map} +1 -1
- package/dist/{utils-BLIPe1Cb.mjs → utils-CuQHO2NF.mjs} +2 -2
- package/dist/{utils-BLIPe1Cb.mjs.map → utils-CuQHO2NF.mjs.map} +1 -1
- package/dist/utils-QZGdBir8.mjs +2 -0
- package/dist/utils-QZGdBir8.mjs.map +1 -0
- package/dist/{validation-CMvAxrIo.mjs → validation-mTttU3Fk.mjs} +1 -1
- package/dist/{validation-CMvAxrIo.mjs.map → validation-mTttU3Fk.mjs.map} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-BjNxS3uX.mjs +2 -0
- package/dist/validator-BjNxS3uX.mjs.map +1 -0
- package/dist/version-Ce4zn8qc.mjs +2 -0
- package/dist/{version-BOmHASPL.mjs.map → version-Ce4zn8qc.mjs.map} +1 -1
- package/dist/write-sinks-Bean5xf5.mjs +2 -0
- package/dist/{write-sinks-3IKCDF-S.mjs.map → write-sinks-Bean5xf5.mjs.map} +1 -1
- package/package.json +33 -18
- package/dist/adapter-internals-DNY4JWFC.mjs.map +0 -1
- package/dist/builder-CUyS5pxN.mjs +0 -2
- package/dist/builder-CUyS5pxN.mjs.map +0 -1
- package/dist/client-CkdJJwAM.mjs +0 -2
- package/dist/client-CkdJJwAM.mjs.map +0 -1
- package/dist/client-Dpgesimv.mjs +0 -49
- package/dist/client-Dpgesimv.mjs.map +0 -1
- package/dist/driver-XlmOJFRH.mjs +0 -2
- package/dist/driver-XlmOJFRH.mjs.map +0 -1
- package/dist/every-B1gLSYOW.mjs +0 -2
- package/dist/every-B1gLSYOW.mjs.map +0 -1
- package/dist/identifier-conversion-D3oCaSia.mjs +0 -2
- package/dist/identifier-conversion-D3oCaSia.mjs.map +0 -1
- package/dist/identity-BtuwgqhS.mjs +0 -2
- package/dist/identity-BtuwgqhS.mjs.map +0 -1
- package/dist/libsql-C4sm2U20.mjs +0 -11
- package/dist/libsql-C4sm2U20.mjs.map +0 -1
- package/dist/mysql-BR0XTumr.mjs +0 -99
- package/dist/mysql-BR0XTumr.mjs.map +0 -1
- package/dist/mysql-adapter-BZtZrWeX.mjs +0 -2
- package/dist/postgres-CrjBX4Yj.mjs.map +0 -1
- package/dist/postgres-adapter-BJcelBCx.mjs +0 -2
- package/dist/postgres-adapter-BJcelBCx.mjs.map +0 -1
- package/dist/select-assembly-Dcaqm09G.mjs.map +0 -1
- package/dist/sqlite-adapter-CMRvEsOv.mjs +0 -2
- package/dist/standard-sql-BtzSzrof.mjs +0 -6
- package/dist/standard-sql-BtzSzrof.mjs.map +0 -1
- package/dist/validator-CtSM_qvW.mjs +0 -2
- package/dist/validator-CtSM_qvW.mjs.map +0 -1
- package/dist/version-BOmHASPL.mjs +0 -2
- package/dist/write-sinks-3IKCDF-S.mjs +0 -2
- /package/dist/{contract-CYl0OzhZ.d.mts → contract-BOwMGvl2.d.mts} +0 -0
- /package/dist/{sql-D7JnXgUh.d.mts → sql-BbLhTqDH.d.mts} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"identifier-conversion-D3oCaSia.mjs","names":["sql"],"sources":["../src/migrations/drivers/utils.ts","../src/migrations/identifier-conversion.ts"],"sourcesContent":["/**\n * Migration Driver Utilities\n *\n * Shared helper functions used across multiple migration drivers.\n */\n\nimport type { ReferentialAction } from \"../types\";\n\n/** A catalog's `ON DELETE` / `ON UPDATE` spelling, as a ReferentialAction. */\nexport function mapReferentialAction(rule: string): ReferentialAction {\n switch (rule.toUpperCase()) {\n case \"CASCADE\":\n return \"cascade\";\n case \"SET NULL\":\n return \"setNull\";\n case \"RESTRICT\":\n return \"restrict\";\n case \"SET DEFAULT\":\n return \"setDefault\";\n default:\n return \"noAction\";\n }\n}\n\n/**\n * Groups items by a key function.\n *\n * @param items - Array of items to group\n * @param keyFn - Function to extract the grouping key\n * @returns Map from key to array of items\n */\nexport function groupBy<T>(\n items: T[],\n keyFn: (item: T) => string\n): Map<string, T[]> {\n const map = new Map<string, T[]>();\n for (const item of items) {\n const key = keyFn(item);\n const existing = map.get(key);\n if (existing) {\n existing.push(item);\n } else {\n map.set(key, [item]);\n }\n }\n return map;\n}\n\n/**\n * Groups items by two levels of keys (nested grouping).\n *\n * @param items - Array of items to group\n * @param primaryKeyFn - Function to extract the primary grouping key\n * @param secondaryKeyFn - Function to extract the secondary grouping key\n * @returns Nested Map structure\n */\nexport function groupByNested<T>(\n items: T[],\n primaryKeyFn: (item: T) => string,\n secondaryKeyFn: (item: T) => string\n): Map<string, Map<string, T[]>> {\n const map = new Map<string, Map<string, T[]>>();\n for (const item of items) {\n const pk = primaryKeyFn(item);\n const sk = secondaryKeyFn(item);\n\n let secondary = map.get(pk);\n if (!secondary) {\n secondary = new Map();\n map.set(pk, secondary);\n }\n\n const existing = secondary.get(sk);\n if (existing) {\n existing.push(item);\n } else {\n secondary.set(sk, [item]);\n }\n }\n return map;\n}\n","/**\n * The three questions an EXISTING text column has to answer before it can\n * become an identifier column — asked as SQL, against the live database, by\n * the person doing the conversion.\n *\n * VibORM does not convert a populated text column on its own: the generated\n * `alterColumn` into a binary column is refused outright\n * ({@link file://./binary-conversion.ts}), and PostgreSQL's one automated leg,\n * `text` → `uuid`, is a per-value cast that either succeeds for the whole table\n * or aborts it. Both routes leave the same work to the author, and this module\n * is the part of that work a machine can state exactly:\n *\n * 1. **Every row is a value of the domain.** Prefix matched whole, payload in\n * the format's own grammar and width — and, for a KSUID, at most the text\n * of the largest value its 20 bytes hold. A row that is not is a row no\n * route can carry.\n * 2. **No two rows fold together.** `uuid` admits uppercase and `ulid`\n * lowercase as ALIASES, so a text column may hold two spellings of one\n * identifier. Compact storage holds the canonical one, so those two rows\n * become one value — violating a unique key, or silently merging two rows\n * where there is none. `ksuid` has no aliases and gets no such check. Asked\n * of the key AND of every referencing column that is a complete key of its\n * own model, because that column carries its own unique constraint through\n * the same fold; a non-unique foreign key holds repeats by design and is\n * never asked.\n * 3. **Every foreign key still finds its parent after the fold.** The FK\n * column converts with its own normalization, so agreement has to be proven\n * against the NORMALIZED sets rather than the stored text.\n *\n * Each check is one row and one boolean column, so each is exactly a\n * {@link MigrationCheckInput} — the `trusted-read` shape `generate()` already\n * accepts as `originChecks` on a manual transition. Run them by hand, or put\n * them in front of your own conversion migration; they are the same SQL either\n * way.\n *\n * Every IDENTITY comparison these checks make is asked of BYTES, because the\n * column they are about answers in bytes. MySQL 8's default collation is\n * `utf8mb4_0900_ai_ci`, where `=` folds case and accents: a bare\n * `p.id = c.userId` there answers TRUE for a KSUID pair that a `BINARY(20)`\n * column will hold as two different values, so an estate certified ready came\n * out of the conversion with a foreign key naming no parent. `CAST(… AS BINARY)`\n * pins it, and it pins across character sets where `COLLATE utf8mb4_bin` raises\n * on a `latin1` column. The grammar match is deliberately NOT cast: MySQL's\n * `REGEXP` refuses a binary operand outright, and every pattern here already\n * spells both cases, so nothing is lost.\n *\n * Pure and connection-free, like every other module in this layer: it renders\n * SQL, it never executes it.\n *\n * What it does NOT cover, deliberately: a junction table's own columns and a\n * polymorphic row carrier's id column. Those hold a key's values too and\n * convert by the same recipe, but they are private storage with no (model,\n * field) to name them by, so the migration guide lists them rather than this\n * module guessing at them.\n */\n\nimport { type Sql, sql } from \"@sql\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport {\n type AnyModel,\n getColumnName,\n getModelKeyCatalog,\n getTableName,\n} from \"../schema/model\";\nimport { idDomainOf } from \"../schema/validation/id-domains\";\nimport {\n type ResolvedRelationIndex,\n resolvedEdges,\n} from \"../schema/validation/relation-resolution\";\nimport { resolveSchemaOrThrow } from \"../schema/validation/validator\";\nimport { createIdentifierQuoter } from \"../sql/identifiers\";\nimport {\n type IdDomain,\n isCompactIdFormat,\n} from \"../validation/primitives/id-codec\";\nimport { KSUID_MAX_TEXT } from \"../validation/primitives/id-formats\";\nimport type { Dialect } from \"./drivers/types\";\nimport type { MigrationCheckInput } from \"./v1-types\";\n\n/** The key whose text column is being converted, and the schema it lives in. */\nexport interface IdentifierConversionRequest {\n /**\n * The WHOLE schema, not just the model: a foreign key's domain is derived\n * from the resolved topology, and so is the list of columns that reference\n * this key. Resolved here, exactly as `serializeModels` resolves it.\n */\n readonly schema: Record<string, AnyModel>;\n readonly model: AnyModel;\n readonly field: string;\n readonly dialect: Dialect;\n /** PostgreSQL's target namespace, when the estate is bound to one. */\n readonly namespace?: string | undefined;\n}\n\n/** One character class, spelled once for both pattern languages. */\nconst HEX = \"[0-9a-fA-F]\";\nconst CROCKFORD = \"[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]\";\nconst BASE62 = \"[0-9A-Za-z]\";\n\n/**\n * The payload grammar of each compact format, as a regex and as a GLOB, and\n * the largest payload text when the grammar alone admits more than the bytes\n * hold.\n *\n * A ULID's grammar carries its own bound — the leading `[0-7]` — but 27 base62\n * characters express more than 2^160 values, and no character class can say\n * where 2^160 falls. So a KSUID is bounded by comparison against the codec's\n * own maximum text, read from `id-formats.ts` rather than spelled here.\n */\nconst PATTERNS = {\n uuid: {\n length: 36,\n regex: `^${HEX}{8}-${HEX}{4}-${HEX}{4}-${HEX}{4}-${HEX}{12}$`,\n glob: `${HEX.repeat(8)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(12)}`,\n fold: \"lower\",\n max: undefined,\n },\n ulid: {\n length: 26,\n regex: `^[0-7]${CROCKFORD}{25}$`,\n glob: `[0-7]${CROCKFORD.repeat(25)}`,\n fold: \"upper\",\n max: undefined,\n },\n ksuid: {\n length: 27,\n regex: `^${BASE62}{27}$`,\n glob: BASE62.repeat(27),\n fold: undefined,\n max: KSUID_MAX_TEXT,\n },\n} as const;\n\n/** `uuidv7` shares a uuid's grammar: the version nibble is not a storage fact. */\nfunction patternOf(domain: IdDomain) {\n if (domain.format === \"ulid\") return PATTERNS.ulid;\n if (domain.format === \"ksuid\") return PATTERNS.ksuid;\n return PATTERNS.uuid;\n}\n\n/** A literal integer: a width, never caller text, so it is text and not a bind. */\nconst int = (value: number): Sql => sql.raw(String(value));\n\n/** One quoted, optionally qualified table name, bound to a one-letter alias. */\nfunction fromSql(\n model: AnyModel,\n dialect: Dialect,\n namespace: string | undefined,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n const qualifier =\n dialect === \"postgresql\" && namespace ? `${quote(namespace)}.` : \"\";\n return sql.raw(`${qualifier + quote(getTableName(model))} AS ${alias}`);\n}\n\n/**\n * One column, always written through its table's alias.\n *\n * The FK checks correlate two tables, and a one-to-one child whose primary key\n * IS its foreign key names both columns `id` — an unqualified reference there\n * binds to the inner table and compares a value with itself.\n */\nfunction columnSql(\n model: AnyModel,\n field: string,\n dialect: Dialect,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n return sql.raw(`${alias}.${quote(getColumnName(model, field))}`);\n}\n\n/** The payload of a stored value: the whole column, or what follows the prefix. */\nfunction payloadSql(column: Sql, domain: IdDomain): Sql {\n const prefix = domain.prefix;\n if (!prefix) return column;\n return sql`substr(${column}, ${int(prefix.length + 2)})`;\n}\n\n/**\n * One comparison operand, asked as the bytes the compact column will hold.\n *\n * Only MySQL needs it, and only because its default collation answers a\n * different question than the column will: see the module note above. Not\n * applied to `REGEXP`, which refuses a binary operand.\n */\nfunction bytesSql(expression: Sql, dialect: Dialect): Sql {\n return dialect === \"mysql\" ? sql`CAST(${expression} AS BINARY)` : expression;\n}\n\n/**\n * One ORDERING operand, compared byte by byte on every dialect.\n *\n * Fixed-width base62 text sorts as its number only under byte order: every\n * database default here that is not bytes folds case, and there `a` sorts\n * before `V`. MySQL takes the byte pin `bytesSql` already applies; PostgreSQL\n * takes `COLLATE \"C\"`, after a cast to `text` because `citext` — a text-family\n * type a KSUID column may hold — lowercases before any collation is consulted;\n * SQLite's default collation is already `BINARY`, as every identity\n * comparison in this module already relies on.\n */\nfunction orderedSql(expression: Sql, dialect: Dialect): Sql {\n if (dialect === \"postgresql\") {\n return sql`CAST(${expression} AS text) COLLATE \"C\"`;\n }\n return bytesSql(expression, dialect);\n}\n\n/** Whether one stored value is a value of the domain. */\nfunction admitsSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const pattern = patternOf(domain);\n const payload = payloadSql(column, domain);\n const matches =\n dialect === \"postgresql\"\n ? sql`${payload} ~ ${pattern.regex}`\n : dialect === \"mysql\"\n ? sql`${payload} REGEXP ${pattern.regex}`\n : sql`${payload} GLOB ${pattern.glob}`;\n const width = sql.raw(dialect === \"mysql\" ? \"CHAR_LENGTH\" : \"length\");\n const grammar = sql`${width}(${payload}) = ${int(pattern.length)} AND ${matches}`;\n const sized =\n pattern.max === undefined\n ? grammar\n : sql`${grammar} AND ${orderedSql(payload, dialect)} <= ${pattern.max}`;\n const prefix = domain.prefix;\n if (!prefix) return sized;\n const spelled = bytesSql(\n sql`substr(${column}, 1, ${int(prefix.length + 1)})`,\n dialect\n );\n return sql`${spelled} = ${`${prefix}-`} AND ${sized}`;\n}\n\n/**\n * The canonical spelling of one stored value, as the bytes it will become:\n * the alias fold for a format that has one, then the dialect's byte pin.\n */\nfunction foldSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const fold = patternOf(domain).fold;\n const payload = payloadSql(column, domain);\n return bytesSql(\n fold === undefined ? payload : sql`${sql.raw(fold)}(${payload})`,\n dialect\n );\n}\n\n/**\n * `COUNT(col) = COUNT(DISTINCT fold(col))`: the question a UNIQUE column has to\n * answer before its aliases collapse into one another.\n */\nfunction foldCollisionCheck(\n from: Sql,\n column: Sql,\n domain: IdDomain,\n dialect: Dialect\n): MigrationCheckInput {\n return {\n kind: \"trusted-read\",\n query: sql`SELECT COUNT(${column}) = COUNT(DISTINCT ${foldSql(column, domain, dialect)}) AS ok FROM ${from}`,\n equals: true,\n };\n}\n\n/**\n * Whether this column is, BY ITSELF, a complete key of its own model.\n *\n * The fold question belongs to every column that carries a uniqueness\n * constraint through it, and a referencing column often does: the one-to-one\n * child whose primary key IS its foreign key is the ordinary shape, and a\n * `.unique()` foreign key is the other. Asking it of a plain many-side foreign\n * key would refuse every healthy estate on earth — repeats there are the\n * relation — so the catalog decides, not the fact of being a reference.\n *\n * `referenceableKeys` is the right catalog rather than the addressable one: a\n * total unique INDEX no selector can name still refuses a duplicate.\n */\nfunction isSingleColumnKey(model: AnyModel, field: string): boolean {\n return getModelKeyCatalog(model).referenceableKeys.some(\n (key) => key.length === 1 && key[0] === field\n );\n}\n\n/** `SELECT NOT EXISTS (…)`, the shape every row check takes. */\nconst noRowWhere = (from: Sql, predicate: Sql): MigrationCheckInput => ({\n kind: \"trusted-read\",\n query: sql`SELECT NOT EXISTS (SELECT 1 FROM ${from} WHERE ${predicate}) AS ok`,\n equals: true,\n});\n\n/** Every foreign-key column that holds this key's values. */\nfunction referencingColumns(\n request: IdentifierConversionRequest,\n index: ResolvedRelationIndex\n): { model: AnyModel; field: string }[] {\n const columns: { model: AnyModel; field: string }[] = [];\n for (const edge of resolvedEdges(index)) {\n if (edge.kind !== \"foreignKey\") continue;\n const other =\n edge.endpoints[0] === edge.owner ? edge.endpoints[1] : edge.endpoints[0];\n if (other.source !== request.model) continue;\n for (const member of edge.reference.members) {\n if (member.referencedField !== request.field) continue;\n columns.push({ model: edge.owner.source, field: member.foreignField });\n }\n }\n return columns;\n}\n\n/**\n * The pre-checks for converting one key's text column into its identifier\n * column, in the order a conversion needs them.\n *\n * Refuses a field with no compactly stored identifier domain rather than\n * answering with an empty list: an empty list reads as \"this estate is ready\",\n * and that is the one answer a caller who named the wrong field must not get.\n */\nexport function identifierConversionChecks(\n request: IdentifierConversionRequest\n): readonly MigrationCheckInput[] {\n const { model, field, dialect, namespace } = request;\n hydrateSchemaNames(request.schema);\n const index = resolveSchemaOrThrow(request.schema);\n const domain = idDomainOf(model, field, index);\n if (domain === undefined || !isCompactIdFormat(domain.format)) {\n throw new MigrationError(\n `'${getTableName(model)}.${getColumnName(model, field)}' has no compactly stored identifier domain, so it has no text conversion to check: only uuid, uuidv7, ulid and ksuid change storage.`,\n VibORMErrorCode.INVALID_INPUT\n );\n }\n const parent = fromSql(model, dialect, namespace, \"p\");\n const key = columnSql(model, field, dialect, \"p\");\n const checks: MigrationCheckInput[] = [\n noRowWhere(\n parent,\n sql`${key} IS NOT NULL AND NOT (${admitsSql(key, domain, dialect)})`\n ),\n ];\n const folds = patternOf(domain).fold !== undefined;\n if (folds) {\n checks.push(foldCollisionCheck(parent, key, domain, dialect));\n }\n for (const reference of referencingColumns(request, index)) {\n const child = fromSql(reference.model, dialect, namespace, \"c\");\n const fk = columnSql(reference.model, reference.field, dialect, \"c\");\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT (${admitsSql(fk, domain, dialect)})`\n )\n );\n if (folds && isSingleColumnKey(reference.model, reference.field)) {\n checks.push(foldCollisionCheck(child, fk, domain, dialect));\n }\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${parent} WHERE ${foldSql(key, domain, dialect)} = ${foldSql(fk, domain, dialect)})`\n )\n );\n }\n return checks;\n}\n\n// =============================================================================\n// THE ONE AUTOMATED LEG\n// =============================================================================\n\n/** The text column spellings PostgreSQL can hold an identifier in. */\nconst PG_TEXT_COLUMN = /^(?:text|citext|varchar\\(\\d+\\)|character varying.*)$/i;\n\n/** A SQL string literal: the only escape a quoted name needs inside one. */\nconst literal = (text: string): string => `'${text.replaceAll(\"'\", \"''\")}'`;\n\n/**\n * The message PostgreSQL's own `col::uuid` does not give.\n *\n * `ALTER COLUMN … TYPE uuid USING col::uuid` converts value by value: it\n * succeeds for an estate of canonical uuids and raises\n * `invalid input syntax for type uuid: \"…\"` on the first row that is not one,\n * aborting the transaction and leaving the column as it was. The outcome is\n * right; the message names one offending row and nothing about the choice the\n * author actually has. This runs FIRST, inside the same transaction, and says\n * how many rows are in the way and what the two routes are.\n *\n * A PREFIXED domain fails here too, and deliberately: `usr-a0ee…` is not uuid\n * text, and no `USING substring(col from 5)::uuid` is emitted for it, because\n * the snapshot carries the column TYPE and not the domain — the prefix is a\n * fact of the declaration that no migration artifact has ever held. Converting\n * a prefixed column is a manual route, and this says so before anything runs.\n *\n * It is not a second refusal: without it the conversion fails anyway. Its whole\n * and only coverage is the message.\n */\nexport function postgresTextToUuidGuard(\n qualifiedTable: string,\n quotedColumn: string\n): string {\n const marker = `${qualifiedTable}.${quotedColumn}`;\n return (\n \"DO $viborm$ DECLARE invalid bigint; BEGIN \" +\n `SELECT count(*) INTO invalid FROM ${qualifiedTable} WHERE ${quotedColumn} IS NOT NULL AND ${quotedColumn} !~ ${literal(PATTERNS.uuid.regex)}; ` +\n \"IF invalid > 0 THEN RAISE EXCEPTION \" +\n `${literal(`VibORM: % row(s) of ${marker} are not canonical uuid text, so this conversion would abort on them. A prefixed identifier is one of the shapes that fails here: only the payload is stored, and no generated statement strips a prefix. Convert the rows yourself — add the uuid column, write the payloads into it, drop the old column and rename — or keep the column as it is with a text-family native type, which validates the domain without changing storage.`)}, invalid; ` +\n \"END IF; END $viborm$\"\n );\n}\n\n/** Whether this alteration is the one text→identifier conversion pg performs. */\nexport function isPostgresTextToUuid(\n fromType: string,\n toType: string\n): boolean {\n return (\n toType.toLowerCase() === \"uuid\" && PG_TEXT_COLUMN.test(fromType.trim())\n );\n}\n"],"mappings":"kdASA,SAAgB,qBAAqB,EAAiC,CACpE,OAAQ,EAAK,aAAa,CAA1B,CACE,IAAK,UACH,MAAO,UACT,IAAK,WACH,MAAO,UACT,IAAK,WACH,MAAO,WACT,IAAK,cACH,MAAO,aACT,QACE,MAAO,YAWb,SAAgB,QACd,EACA,EACkB,CAClB,IAAM,EAAM,IAAI,IAChB,IAAK,IAAM,KAAQ,EAAO,CACxB,IAAM,EAAM,EAAM,EAAK,CACjB,EAAW,EAAI,IAAI,EAAI,CACzB,EACF,EAAS,KAAK,EAAK,CAEnB,EAAI,IAAI,EAAK,CAAC,EAAK,CAAC,CAGxB,OAAO,EAWT,SAAgB,cACd,EACA,EACA,EAC+B,CAC/B,IAAM,EAAM,IAAI,IAChB,IAAK,IAAM,KAAQ,EAAO,CACxB,IAAM,EAAK,EAAa,EAAK,CACvB,EAAK,EAAe,EAAK,CAE3B,EAAY,EAAI,IAAI,EAAG,CACtB,IACH,EAAY,IAAI,IAChB,EAAI,IAAI,EAAI,EAAU,EAGxB,IAAM,EAAW,EAAU,IAAI,EAAG,CAC9B,EACF,EAAS,KAAK,EAAK,CAEnB,EAAU,IAAI,EAAI,CAAC,EAAK,CAAC,CAG7B,OAAO,ECiBT,MAAM,EAAM,cACN,EAAY,kCACZ,EAAS,cAYT,EAAW,CACf,KAAM,CACJ,OAAQ,GACR,MAAO,IAAI,EAAI,MAAM,EAAI,MAAM,EAAI,MAAM,EAAI,MAAM,EAAI,OACvD,KAAM,GAAG,EAAI,OAAO,EAAE,CAAC,GAAG,EAAI,OAAO,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EAAQ,CAAC,GACjE,CACF,CACG,GAAS,kBAAkB,EAAU,MAAO,EAAU,MAAM,EAC9D,EAAO,KAAK,mBAAmB,EAAO,EAAI,EAAQ,EAAQ,CAAC,CAE7D,EAAO,KACL,WACE,EACA,CAAG,GAAG,EAAG,6CAA6C,EAAO,SAAS,QAAQ,EAAK,EAAQ,EAAQ,CAAC,KAAK,QAAQ,EAAI,EAAQ,EAAQ,CAAC,GACvI,CACF,CAEH,OAAO,EAQT,MAAM,EAAiB,wDAGjB,QAAW,GAAyB,IAAI,EAAK,WAAW,IAAK,KAAK,CAAC,GAsBzE,SAAgB,wBACd,EACA,EACQ,CACR,IAAM,EAAS,GAAG,EAAe,GAAG,IACpC,MACE,iFACqC,EAAe,SAAS,EAAa,mBAAmB,EAAa,MAAM,QAAQ,EAAS,KAAK,MAAM,CAAC,wCAE1I,QAAQ,uBAAuB,EAAO,0aAA0a,CAAC,mCAMxd,SAAgB,qBACd,EACA,EACS,CACT,OACE,EAAO,aAAa,GAAK,QAAU,EAAe,KAAK,EAAS,MAAM,CAAC"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-wlv81COV.mjs";import{t as n}from"./migrations-OE5D32qo.mjs";import{t as r}from"./sha256-D_fCV62w.mjs";const i=`sha256`,a={estate:`viborm.migration.estate.v1`,snapshot:`viborm.migration.snapshot.v1`,snapshotDelta:`viborm.migration.snapshot-delta.v1`,sql:`viborm.migration.sql.v1`,dispatch:`viborm.migration.dispatch.v1`,transition:`viborm.migration.transition.v1`,state:`viborm.migration.state.v1`,path:`viborm.migration.path.v1`,plan:`viborm.migration.plan.v1`,resetPlan:`viborm.migration.reset-plan.v1`,event:`viborm.migration.event.v1`},o=/^[0-9a-f]{64}$/,s=new TextEncoder;function isSha256(e){return typeof e==`string`&&o.test(e)}function parseSha256(e,r){if(!isSha256(e))throw new n(`${r} is not a lowercase 64-hex SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return e}function sha256Hex(e){let t=``;for(let n of r(e))t+=n.toString(16).padStart(2,`0`);return t}function domainHash(e,t){let n=s.encode(e),r=new Uint8Array(n.length+1+t.length);return r.set(n,0),r[n.length]=0,r.set(t,n.length+1),sha256Hex(r)}function utf8Bytes(e){return s.encode(e)}function decodeUtf8(e){return new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(e)}export{isSha256 as a,utf8Bytes as c,domainHash as i,a as n,parseSha256 as o,decodeUtf8 as r,sha256Hex as s,i as t};
|
|
2
|
-
//# sourceMappingURL=identity-BtuwgqhS.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"identity-BtuwgqhS.mjs","names":[],"sources":["../src/migrations/identity.ts"],"sourcesContent":["/**\n * Content-addressed identity for Migration V1.\n *\n * One hash owner: SHA-256 over a frozen ASCII domain label, 0x00, then the\n * exact bytes being authenticated. Filenames and stored hex digests are the\n * lowercase 64-hex form of that digest. There is no self-referential checksum\n * header and no second hasher.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { sha256 } from \"../validation/primitives/sha256\";\n\nexport type Sha256 = string;\n\nexport const HASH_ALGORITHM = \"sha256\";\n\nexport const HASH_DOMAIN = {\n estate: \"viborm.migration.estate.v1\",\n snapshot: \"viborm.migration.snapshot.v1\",\n snapshotDelta: \"viborm.migration.snapshot-delta.v1\",\n sql: \"viborm.migration.sql.v1\",\n dispatch: \"viborm.migration.dispatch.v1\",\n transition: \"viborm.migration.transition.v1\",\n state: \"viborm.migration.state.v1\",\n path: \"viborm.migration.path.v1\",\n plan: \"viborm.migration.plan.v1\",\n resetPlan: \"viborm.migration.reset-plan.v1\",\n event: \"viborm.migration.event.v1\",\n} as const;\n\nexport type HashDomain = (typeof HASH_DOMAIN)[keyof typeof HASH_DOMAIN];\n\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst UTF8 = new TextEncoder();\n\nexport function isSha256(value: unknown): value is Sha256 {\n return typeof value === \"string\" && HEX64.test(value);\n}\n\nexport function parseSha256(value: unknown, label: string): Sha256 {\n if (!isSha256(value)) {\n throw new MigrationError(\n `${label} is not a lowercase 64-hex SHA-256 digest`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return value;\n}\n\nexport function sha256Hex(bytes: Uint8Array): Sha256 {\n let hex = \"\";\n for (const byte of sha256(bytes)) hex += byte.toString(16).padStart(2, \"0\");\n return hex;\n}\n\nexport function domainHash(domain: HashDomain, bytes: Uint8Array): Sha256 {\n const prefix = UTF8.encode(domain);\n const input = new Uint8Array(prefix.length + 1 + bytes.length);\n input.set(prefix, 0);\n input[prefix.length] = 0;\n input.set(bytes, prefix.length + 1);\n return sha256Hex(input);\n}\n\nexport function utf8Bytes(text: string): Uint8Array {\n return UTF8.encode(text);\n}\n\n/**\n * Exactly the characters the bytes encode — a leading U+FEFF among them.\n *\n * These bytes are a VALUE (a catalog default, a blob's text), not a document\n * with a byte-order mark: the decoder's default of swallowing a leading U+FEFF\n * would report a value its source does not hold. A caller that refuses a BOM\n * refuses it as a byte, before this (`validateSqlRanges`).\n */\nexport function decodeUtf8(bytes: Uint8Array): string {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(\n bytes\n );\n}\n"],"mappings":"yKAcA,MAAa,EAAiB,SAEjB,EAAc,CACzB,OAAQ,6BACR,SAAU,+BACV,cAAe,qCACf,IAAK,0BACL,SAAU,+BACV,WAAY,iCACZ,MAAO,4BACP,KAAM,2BACN,KAAM,2BACN,UAAW,iCACX,MAAO,4BACR,CAIK,EAAQ,iBACR,EAAO,IAAI,YAEjB,SAAgB,SAAS,EAAiC,CACxD,OAAO,OAAO,GAAU,UAAY,EAAM,KAAK,EAAM,CAGvD,SAAgB,YAAY,EAAgB,EAAuB,CACjE,GAAI,CAAC,SAAS,EAAM,CAClB,MAAM,IAAI,EACR,GAAG,EAAM,2CACT,EAAgB,yBACjB,CAEH,OAAO,EAGT,SAAgB,UAAU,EAA2B,CACnD,IAAI,EAAM,GACV,IAAK,IAAM,KAAQ,EAAO,EAAM,CAAE,GAAO,EAAK,SAAS,GAAG,CAAC,SAAS,EAAG,IAAI,CAC3E,OAAO,EAGT,SAAgB,WAAW,EAAoB,EAA2B,CACxE,IAAM,EAAS,EAAK,OAAO,EAAO,CAC5B,EAAQ,IAAI,WAAW,EAAO,OAAS,EAAI,EAAM,OAAO,CAI9D,OAHA,EAAM,IAAI,EAAQ,EAAE,CACpB,EAAM,EAAO,QAAU,EACvB,EAAM,IAAI,EAAO,EAAO,OAAS,EAAE,CAC5B,UAAU,EAAM,CAGzB,SAAgB,UAAU,EAA0B,CAClD,OAAO,EAAK,OAAO,EAAK,CAW1B,SAAgB,WAAW,EAA2B,CACpD,OAAO,IAAI,YAAY,QAAS,CAAE,MAAO,GAAM,UAAW,GAAM,CAAC,CAAC,OAChE,EACD"}
|
package/dist/libsql-C4sm2U20.mjs
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-wlv81COV.mjs";import{t as n}from"./migrations-OE5D32qo.mjs";import{d as r}from"./v-CWY9ntMb.mjs";import{E as i,P as a}from"./geo-point-codec-Ggv29hSH.mjs";import{o}from"./native-types-CQH05hcr.mjs";import{a as s,t as c}from"./physical-CjG29tya.mjs";import{i as l}from"./datetime-physical-codec-Cdgq6sGs.mjs";import{$ as u,B as d,F as f,Q as p,S as m,X as h,Z as g,_,at as v,c as y,ct as b,d as x,et as S,f as C,h as w,it as T,k as E,lt as D,m as O,nt as k,ot as A,rt as j,st as M,tt as N}from"./client-Dpgesimv.mjs";import{t as P}from"./batch-refs-ZHBzfoBC.mjs";import{o as F}from"./identifier-conversion-D3oCaSia.mjs";function escapeIdentifier(e){return`"${e.replace(/"/g,`""`)}"`}function int(e){return Number(e)}const I=/^WHERE\s+([\s\S]+)$/i,L=/^(?:[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|0x[\da-f]+|'(?:[^']|'')*'|x'[\da-f]*'|"(?:[^"]|"")*"|[a-z_][\w$]*)$/i;function columnDefault(e){if(e!==null)return L.test(e)?e:`(${e})`}const R=/\bAUTOINCREMENT\b/i;function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function sqliteEnumCheckSuffix(e,t){if(!e)return;let n=escapeIdentifier(t),r=e.match(RegExp(`CHECK\\(\\s*${escapeRegExp(n)}\\s+IN\\s*\\((\\s*(?:'(?:[^']|'')*'\\s*,\\s*)*'(?:[^']|'')*'\\s*)\\)\\s*\\)`,`i`))?.[1];if(!r)return;let i=[],a=/'((?:[^']|'')*)'/g,o=a.exec(r);for(;o;){let e=o[1];e!==void 0&&i.push(e.replace(/''/g,`'`)),o=a.exec(r)}if(i.length!==0)return` CHECK(${n} IN (${i.map(e=>`'${e.replace(/'/g,`''`)}'`).join(`, `)}))`}function partialIndexPredicate(e){if(!e)return;let t=0,n=0,r=-1;for(;n<e.length;){let i=D(e,n);if(i!==n){n=i;continue}let a=e[n];if(a===`(`)t++;else if(a===`)`&&(t--,t===0)){r=n;break}n++}if(r!==-1)return I.exec(e.slice(r+1).trimStart())?.[1]}async function introspect(e,r,i=!1){let a=await e(`
|
|
2
|
-
SELECT name, sql
|
|
3
|
-
FROM sqlite_master
|
|
4
|
-
WHERE type = 'table'
|
|
5
|
-
AND name NOT LIKE 'sqlite_%'
|
|
6
|
-
AND name <> ?
|
|
7
|
-
${i?`AND name NOT GLOB '_cf_*'`:``}
|
|
8
|
-
ORDER BY name
|
|
9
|
-
`,[P]),o=[];for(let i of a.rows){let a=i.name,s=r===void 0||r.includes(a),c=A(i.sql??``);if(s&&c.some(e=>v(e.text).includes(`AS`)))throw new n(`SQLite table "${a}" has generated columns that this schema cannot represent. Synchronization refuses before effects and preserves them.`,t.MIGRATION_INVALID_STATE,{meta:{table:a,feature:`generated columns`}});if(s&&v((i.sql??``).split(`(`)[0]).includes(`VIRTUAL`))throw new n(`SQLite virtual table "${a}" cannot be faithfully reconstructed. Synchronization refuses before effects.`,t.MIGRATION_INVALID_STATE,{meta:{table:a,feature:`virtual table`}});let l=await e(`PRAGMA table_info(${escapeIdentifier(a)})`),u=i.sql,d=R.test(u??``),f=await e(`PRAGMA index_list(${escapeIdentifier(a)})`),p=await e(`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?`,[a]),m=new Map(p.rows.map(e=>[e.name,e.sql])),g=await e(`PRAGMA foreign_key_list(${escapeIdentifier(a)})`),_=[],y=[];for(let e of l.rows){let t=int(e.pk),n=e.type||`TEXT`,r=int(e.notnull)===0&&t===0,i=N(u,{name:e.name,type:n,nullable:r},escapeIdentifier);_.push({name:e.name,geoPointEncoding:i,type:i?S:`${n}${sqliteEnumCheckSuffix(u,e.name)??``}`,nullable:r,default:columnDefault(e.dflt_value),autoIncrement:t===1&&d,decimal:h(u,{name:e.name,type:e.type,nullable:r},escapeIdentifier)}),t>0&&y.push({name:e.name,position:t})}if(s&&c.reduce((e,t)=>e+v(t.text).filter(e=>e===`CHECK`).length,0)!==_.reduce((e,t)=>e+Number(t.decimal!==void 0)+Number(t.geoPointEncoding!==void 0)+Number(sqliteEnumCheckSuffix(u,t.name)!==void 0),0)&&!w(a,u))throw new n(`SQLite table "${a}" has CHECK constraints that this schema cannot faithfully represent. Synchronization refuses before effects and preserves them.`,t.MIGRATION_INVALID_STATE,{meta:{table:a,feature:`CHECK constraints`}});let b;y.length>0&&(y.sort((e,t)=>e.position-t.position),b={name:`${a}_pkey`,columns:y.map(e=>e.name)});let x=[],C=[];for(let i of f.rows){let o=(await e(`PRAGMA index_xinfo(${escapeIdentifier(i.name)})`)).rows.filter(e=>int(e.key)===1);if(o.length===0||o.some(e=>int(e.cid)<0||e.name===null||int(e.desc)!==0||e.coll!==`BINARY`)){if(r===void 0||r.includes(a))throw new n(`SQLite index "${a}.${i.name}" has expression/order/collation semantics that this index declaration cannot represent. Synchronization refuses before effects and preserves it. Manage its table outside this synchronization scope until a faithful declaration is available.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:a,indexName:i.name}});continue}if(i.origin===`pk`)continue;let s=o.sort((e,t)=>int(e.seqno)-int(t.seqno)).flatMap(e=>e.name===null?[]:[e.name]),c=int(i.unique)===1;c&&i.origin===`u`?C.push({name:i.name,columns:s}):x.push({name:i.name,columns:s,unique:c,where:partialIndexPredicate(m.get(i.name)??null)})}let T=new Map;for(let e of g.rows){let t=int(e.id),n=T.get(t)||[];n.push(e),T.set(t,n)}let E=[];for(let[e,t]of T){let n=t.sort((e,t)=>int(e.seq)-int(t.seq)),r=n[0];r&&E.push({name:`${a}_fk_${e}`,columns:n.map(e=>e.from),referencedTable:r.table,referencedColumns:n.map(e=>e.to),onDelete:F(r.on_delete),onUpdate:F(r.on_update)})}o.push({name:a,columns:_,primaryKey:b,indexes:x,foreignKeys:E,uniqueConstraints:C})}return{tables:o,enums:[]}}const z=/^(?:CURRENT_(?:TIME|DATE|TIMESTAMP)|\()/i,B=`__new_`,V=/^CREATE\s+TABLE\s+/i,H=/^ALTER\s+TABLE\s+/i,U=/^\s+RENAME\s+TO\s+/i,W=/^CREATE\s+(?:TEMP(?:ORARY)?\s+)?(TRIGGER|VIEW)\s+(?:IF\s+NOT\s+EXISTS\s+)?/i,G=/^DROP\s+(?:TRIGGER|VIEW)\s+(?:IF\s+EXISTS\s+)?/i,K=/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?/i,q=/^\s*\./,J=/^(?:add|all|alter|and|as|autoincrement|between|case|check|collate|commit|constraint|create|default|deferrable|delete|distinct|drop|else|escape|except|exists|foreign|from|group|having|in|index|insert|intersect|into|is|isnull|join|limit|not|nothing|notnull|null|on|or|order|primary|references|returning|select|set|table|then|to|transaction|union|unique|update|using|values|when|where)$/,Y=/\s+CHECK\s*\(/,X=/CHAR|CLOB|TEXT/,Z=/REAL|FLOA|DOUB/;function lostDependents(e,t){let n=new Map(t.map(e=>[e.name.toLowerCase(),e])),r=new Map,i=[];for(let t of e){let e=t.trim(),a=D(e,0);for(;a>0;)e=e.slice(a).trimStart(),a=D(e,0);let o=V.exec(e),s=H.exec(e),c=W.exec(e),l=G.exec(e),u=K.exec(e),d=o??s??c??l??u,f=d&&readObjectName(e,d[0].length);if(!f)continue;let p=f.value.toLowerCase();if(c){let t=c[1].toLowerCase();n.set(p,{type:t,name:f.value,sql:e})}else if(l)n.delete(p);else if(u){let e=(r.get(p)??f.value).toLowerCase();for(let[t,r]of n)r.type===`trigger`&&r.table===e&&n.delete(t)}else if(o&&p.startsWith(B)){let e=f.value.slice(6),t=r.get(e.toLowerCase())??e,a=[e.toLowerCase(),t.toLowerCase()];for(let[e,r]of n){let o=r.sql??``;a.some(e=>sqlNamesTable(o,r.name,e))&&(i.push({table:t,dependent:r}),n.delete(e))}}else if(s&&!p.startsWith(B)){let t=U.exec(e.slice(f.end)),n=t&&b(e,f.end+t[0].length);n&&r.set(n.value.toLowerCase(),r.get(p)??f.value)}}return i}function readObjectName(e,t){let n=b(e,t),r=n?q.exec(e.slice(n.end)):null;return n&&r?b(e,n.end+r[0].length):n}function sqlNamesTable(e,t,n){let r=!0,i=0;for(;i<e.length;){let a=e.charAt(i),o='"`['.includes(a)||M(a)?b(e,i):void 0;if(o){let e=o.value.toLowerCase();if(r&&e===t.toLowerCase())r=!1;else if(e===n&&(o.quoted||!J.test(e)))return!0;i=o.end}else i=Math.max(D(e,i),i+1)}return!1}function sqliteAffinity(e){let t=e.toUpperCase().split(Y)[0].trim();return t.includes(`INT`)?`INTEGER`:X.test(t)?`TEXT`:t===``||t.includes(`BLOB`)?`BLOB`:Z.test(t)?`REAL`:`NUMERIC`}function sqliteConvertingAffinity(e,t){let n=sqliteAffinity(t.type);if(n!==sqliteAffinity(e.type))return n===`INTEGER`||n===`REAL`||n===`TEXT`?n:void 0}function applyToTable(e,t){if(!(`tableName`in t)||t.tableName!==e.name)return e;switch(t.type){case`addColumn`:return{...e,columns:[...e.columns,t.column]};case`dropColumn`:return{...e,columns:e.columns.filter(e=>e.name!==t.columnName)};case`alterColumn`:return{...e,columns:e.columns.map(e=>e.name===t.columnName?t.to:e)};case`createIndex`:return{...e,indexes:[...e.indexes,t.index]};case`dropIndex`:return{...e,indexes:e.indexes.filter(e=>e.name!==t.indexName)};case`addForeignKey`:return{...e,foreignKeys:[...e.foreignKeys,t.fk]};case`dropForeignKey`:return{...e,foreignKeys:e.foreignKeys.filter(e=>e.name!==t.fkName)};case`addUniqueConstraint`:return{...e,uniqueConstraints:[...e.uniqueConstraints,t.constraint]};case`dropUniqueConstraint`:return{...e,uniqueConstraints:e.uniqueConstraints.filter(e=>e.name!==t.constraintName)};case`addPrimaryKey`:return{...e,primaryKey:t.primaryKey};case`dropPrimaryKey`:return{...e,primaryKey:void 0};default:return e}}function replaySchemaTables(e,t){let n=[...e];for(let e of t){if(e.type===`createTable`){n=[...n,e.table];continue}if(e.type===`dropTable`){n=n.filter(t=>t.name!==e.tableName);continue}if(e.type===`renameTable`||e.type===`renameColumn`){n=E({tables:n},e).tables;continue}n=n.map(t=>applyToTable(t,e))}return n}function sqliteTableBearsRelations(e,t,n,r=[]){if(n&&n.foreignKeys.length>0)return!0;let i=replaySchemaTables(t,r);for(let t of i)if(t.name===e&&t.foreignKeys.length>0||t.foreignKeys.some(t=>t.referencedTable===e))return!0;return!1}var SQLite3MigrationDriver=class extends O{dialect=`sqlite`;driverName=`sqlite3`;finalizeTable(e){let r=e.columns.filter(e=>e.autoIncrement);if(r.length>0&&(r.length!==1||e.primaryKey?.columns.length!==1||e.primaryKey.columns[0]!==r[0].name||r[0].type.toUpperCase()!==`INTEGER`||r[0].nullable))throw new n(`SQLite table "${e.name}" requires its AUTOINCREMENT column to be the sole non-null INTEGER primary key. Declare .id().autoIncrement() on that column.`,t.INVALID_INPUT,{meta:{table:e.name}});return e}getIrreversibleRollbackReason(e){return e.type===`alterColumn`&&T(e.from)===`binary64`&&T(e.to)===`legacy`?`Rollback cannot downgrade GeoPoint column "${e.tableName}.${e.columnName}" to its legacy CHECK without rounding coordinates. Author an explicit manual data transition.`:super.getIrreversibleRollbackReason(e)}capabilities={supportsNativeEnums:!1,supportsAddEnumValueInTransaction:!0,supportsIndexTypes:[`btree`],supportsNativeArrays:!1,supportsAddForeignKeyViaAlter:!1,introspectionReadsConstraintNames:!1};async preflightSchemaRequirements(e,r,i){let a=[...new Set(e.flatMap(e=>e.tables.map(e=>e.name)))];if(a.length===0&&i.length===0)return!1;let o=await r(`SELECT type, name, sql, lower(tbl_name) AS "table" FROM sqlite_master WHERE type IN ('view', 'trigger')`),s=o.rows.find(e=>e.type===`view`&&a.includes(e.name));if(s)throw new n(`SQLite relation "${s.name}" is a view, but this schema declares a table. Synchronization refuses before effects and preserves the view.`,t.MIGRATION_INVALID_STATE,{meta:{table:s.name,feature:`view`}});let c=lostDependents(i,o.rows);if(c.length>0)throw new n(`This migration rebuilds SQLite ${c.map(({table:e,dependent:t})=>`table "${e}", which ${t.type} "${t.name}" depends on`).join(`; `)}. A rebuild drops the table, which silently drops its triggers and breaks every view or trigger that reads it. The migration is refused before any statement runs, so the schema and data are unchanged. Drop them before this change (a SQL step earlier in the same migration path counts) and recreate them after it.`,t.MIGRATION_INVALID_STATE,{meta:{table:c[0].table,dependents:c.map(({dependent:e})=>`${e.type}:${e.name}`),feature:`table recreation`}});return!1}introspect(e){let t=this.executionDriver?.driverName;return introspect(e,this.target?.tables,t===`d1`)}mapScalarType(e,t,n){let r=e[`~`].nativeType,i=n===void 0||t.array===!0?void 0:s(n,r,`sqlite`);if(i)return i.columnType;let a=o(r,`sqlite`);return a&&!t.array?a.type:f({type:t.type,array:t.array,decimal:t.decimal})}getDefaultExpression(e,i){if(i.type===`datetime`&&i.autoGenerate?.kind===`now`){let t=c(e[`~`].nativeType);return t===`julianDay`?`(julianday('now'))`:t===`epochMillis`?`(CAST(strftime('%s','now') AS INTEGER) * 1000 + CAST(substr(strftime('%f','now'),4,3) AS INTEGER))`:`(strftime('%Y-%m-%dT%H:%M:%fZ','now'))`}if(i.autoGenerate?.kind===`now`){if(i.type===`date`)return`(strftime('%Y-%m-%d','now'))`;if(i.type===`time`)return`(strftime('%H:%M:%f','now'))`}let a=i.hasDefault&&!i.autoGenerate&&!i.array&&(i.type===`datetime`||i.type===`time`)?this.literalDefaultValue(i):void 0;if(i.type===`datetime`&&i.array!==!0&&i.autoGenerate===void 0&&i.hasDefault&&typeof a==`string`){let t=l(a,c(e[`~`].nativeType));return typeof t==`string`?this.escapeValue(t):String(t)}if(i.type===`time`&&!i.array&&!i.autoGenerate&&i.hasDefault&&typeof a==`string`){let e=r(a);if(!(`value`in e))throw new n(`Invalid Time literal default`,t.MIGRATION_INVALID_STATE);return this.escapeValue(e.value)}return super.getDefaultExpression(e,i)}formatBooleanDefault(e){return e?`1`:`0`}getEnumColumnType(e,t,n){let r=n.map(e=>`'${e.replace(/'/g,`''`)}'`).join(`, `);return`TEXT CHECK(${this.escapeIdentifier(t)} IN (${r}))`}generateColumnDef(e,r){if(e.autoIncrement&&e.type.toUpperCase()!==`INTEGER`)throw new n(`SQLite auto-increment requires INTEGER type. Column "${e.name}" has type "${e.type}" which is not compatible with auto-increment. Note: SQLite auto-increment is implicit when using INTEGER PRIMARY KEY.`,t.INVALID_INPUT,{meta:{column:e.name,type:e.type,autoIncrement:!0}});if(e.autoIncrement)return`${this.escapeIdentifier(e.name)} INTEGER PRIMARY KEY AUTOINCREMENT`;let i=[this.escapeIdentifier(e.name),e.type];e.nullable||i.push(`NOT NULL`),e.default!==void 0&&i.push(`DEFAULT ${e.default}`),e.type.toUpperCase()===S&&i.push(j(e,e=>this.escapeIdentifier(e),T(e)));let a=u(e);return e.decimal&&a&&i.push(g(e,e.decimal,a,e=>this.escapeIdentifier(e))),i.join(` `)}compileTableRecreation(e,r,i,a,o,s){let c=[],l=`${B}${e}`,u=new Map(i.columns.map(e=>[e.name,e])),d=new Map;for(let[e,t]of o??[])d.set(t,e);let f=r.columns.some(e=>{let t=d.get(e.name)??e.name;return this.decimalConversionKind(u.get(t),e)===`list`}),p=`__viborm_source`;c.push(`PRAGMA foreign_keys=OFF`),c.push(this.generateCreateTableDef({...r,name:l},a));let m=[];for(let i of r.columns){let r=d.get(i.name)??i.name,a=u.get(r);if(a!==void 0){let t=f?`${this.escapeIdentifier(p)}.${this.escapeIdentifier(r)}`:this.escapeIdentifier(r);m.push({source:s?.get(i.name)??this.copySourceExpression(e,r,a,i,t),target:i.name})}else if(!i.nullable&&i.default===void 0)throw new n(`Cannot add NOT NULL column "${i.name}" without a default value during table recreation. SQLite requires a default value or nullable column for table recreation.`,t.FEATURE_NOT_SUPPORTED)}if(m.length>0){let t=m.map(e=>e.source).join(`, `),n=m.map(e=>this.escapeIdentifier(e.target)).join(`, `);c.push(`INSERT INTO ${this.escapeIdentifier(l)} (${n}) SELECT ${t} FROM ${this.escapeIdentifier(e)}`+(f?` AS ${this.escapeIdentifier(p)}`:``))}c.push(`DROP TABLE ${this.escapeIdentifier(e)}`),c.push(`ALTER TABLE ${this.escapeIdentifier(l)} RENAME TO ${this.escapeIdentifier(e)}`);for(let t of r.indexes)c.push(this.generateCreateIndex({type:`createIndex`,tableName:e,index:t},a));return c.push(`PRAGMA foreign_keys=ON`),this.filterStatements(c)}copySourceExpression(e,r,o,s,c){if(s.geoPointEncoding===`binary64`&&o!==void 0&&T(o)===`legacy`)return`CASE WHEN ${c} IS NULL THEN NULL ELSE ${k(c)} END`;let l=s.dateTime;if(l!==void 0){let a=this.sqliteDateTimeSourceForm(o);if(a===void 0)throw new n(`The declared change to "${e}"."${r}" would adopt ${o?.decimal===void 0?`${o?.type??`unknown`} storage`:`a fixed-decimal domain at ${i(o.decimal)}`} as a SQLite DateTime. Only a declared DateTime or unmarked TEXT, INTEGER epoch-millisecond, or REAL Julian-day candidate can be converted exactly. The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e,column:r,feature:`SQLite DateTime storage conversion`,dialect:`sqlite`}});return x(c,a,l,o?.dateTime!==void 0)}let d=s.decimal,f=u(s),m=o?.decimal;if(d===void 0&&o!==void 0&&m!==void 0)return this.descaledDecimalSource(e,r,{...o,decimal:m},s.type,c);if(d===void 0||f===void 0){let e=o&&sqliteConvertingAffinity(o,s);return e===void 0?c:`CASE WHEN ${c} IS NULL THEN NULL WHEN CAST(${c} AS ${e}) = ${c} THEN CAST(${c} AS ${e}) ELSE ${y} END`}if(m===void 0){if(!(f===`scalar`&&o?.type.toUpperCase()===`INTEGER`))throw new n(`The declared change to "${e}"."${r}" would adopt unmarked ${o?.type??`unknown`} storage as a fixed-decimal ${f}. Only a scalar INTEGER has one exact descriptor-free meaning that can be rescaled into the target domain. TEXT and every list container carry no proven member scale, while other SQLite affinities can already have changed the stored value. The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e,column:r,feature:`decimal storage adoption`,dialect:`sqlite`}});return p(c,void 0,d,`scalar`)}if(a(m,d))return c;let h=this.decimalConversionKind(o,s);return h===void 0?c:p(c,m,d,h)}descaledDecimalSource(e,r,a,o,s){let c=u(a);if(c===`scalar`&&sqliteAffinity(o)===`INTEGER`){let e=10n**BigInt(a.decimal.scale);return`CASE WHEN ${s} IS NULL THEN NULL WHEN typeof(${s}) = 'integer' AND ${s} % ${e} = 0 THEN ${s} / ${e} ELSE ${y} END`}throw new n(`The declared change to "${e}"."${r}" would copy a fixed-decimal ${c??`column`} at ${i(a.decimal)} into ${o} storage that declares no decimal domain. SQLite stores the decimal as its scaled integer coefficient, and only a scalar copied into INTEGER storage can be descaled exactly. The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e,column:r,feature:`decimal storage conversion`,dialect:`sqlite`}})}sqliteDateTimeSourceForm(e){if(e?.dateTime!==void 0)return e.dateTime;if(e?.decimal===void 0)switch(e?.type.toUpperCase()){case`TEXT`:return`text`;case`INTEGER`:return`epochMillis`;case`REAL`:return`julianDay`;default:return}}decimalConversionKind(e,t){let n=e?.decimal,r=t.decimal;if(e===void 0||n===void 0||r===void 0||a(n,r))return;let i=u(t);if(!(i===void 0||u(e)!==i))return i}assertDomainReconstructionAdmitted(e,r,a,o,s){let c,l;if(s===`decimal`){if(r.decimal===void 0)return;c=`a fixed-decimal column at ${i(r.decimal)}`,l=`decimal descriptor conversion`}else{if(r.dateTime===void 0)return;c=`a SQLite DateTime column in ${r.dateTime} storage`,l=`SQLite DateTime storage conversion`}let u=this.executionDriver;if(u&&_(u)&&sqliteTableBearsRelations(e,o.currentSchema?.tables??[],a,o.precedingOperations))throw new n(`Rebuilding "${e}"."${r.name}", ${c}, recreates the whole table, and the driver "${u.driverName}" runs migrations without a transaction (D1 runs them as one native batch). Without a transaction, \`PRAGMA foreign_keys=OFF\` cannot be proven before the rebuild drops a table that still has references, nor the drop rolled back — and a pragma that did not take raises on one referential action and silently deletes or nulls child rows on another. The change is refused before any statement runs, so the schema and its data are exactly as they were. Recreate the table without its references, or run the change on a driver with transactions.`,t.FEATURE_NOT_SUPPORTED,{meta:{driver:u.driverName,table:e,column:r.name,feature:l}})}generateCreateTableDef(e,t){let n=[];for(let r of e.columns)n.push(this.generateColumnDef(r,t));if(e.primaryKey&&!(e.primaryKey.columns.length===1&&e.columns.find(t=>t.name===e.primaryKey.columns[0]&&t.type.toUpperCase()===`INTEGER`&&t.autoIncrement))){let t=e.primaryKey.columns.map(e=>this.escapeIdentifier(e)).join(`, `);n.push(`PRIMARY KEY (${t})`)}for(let t of e.uniqueConstraints){let e=t.columns.map(e=>this.escapeIdentifier(e)).join(`, `);n.push(t.name.startsWith(`sqlite_autoindex_`)?`UNIQUE (${e})`:`CONSTRAINT ${this.escapeIdentifier(t.name)} UNIQUE (${e})`)}for(let t of e.foreignKeys){let e=t.columns.map(e=>this.escapeIdentifier(e)).join(`, `),r=t.referencedColumns.map(e=>this.escapeIdentifier(e)).join(`, `),i=`CONSTRAINT ${this.escapeIdentifier(t.name)} `;i+=`FOREIGN KEY (${e}) `,i+=`REFERENCES ${this.escapeIdentifier(t.referencedTable)} (${r})`,t.onDelete&&t.onDelete!==`noAction`&&(i+=` ON DELETE ${this.formatReferentialAction(t.onDelete)}`),t.onUpdate&&t.onUpdate!==`noAction`&&(i+=` ON UPDATE ${this.formatReferentialAction(t.onUpdate)}`),n.push(i)}return`CREATE TABLE ${this.escapeIdentifier(e.name)} (\n ${n.join(`,
|
|
10
|
-
`)}\n)`}getCurrentTable(e,t){return replaySchemaTables(t.currentSchema?.tables??[],t.precedingOperations??[]).find(t=>t.name===e)}generateCreateTable(e,t){let{table:n}=e,r=[this.generateCreateTableDef(n,t)];for(let e of n.indexes)r.push(this.generateCreateIndex({type:`createIndex`,tableName:n.name,index:e},t));return r}generateDropTable(e,t){return`DROP TABLE ${this.escapeIdentifier(e.tableName)}`}generateRenameTable(e,t){return`ALTER TABLE ${this.escapeIdentifier(e.from)} RENAME TO ${this.escapeIdentifier(e.to)}`}generateAddColumn(e,r){if(e.column.default!==void 0&&z.test(e.column.default)){let i=this.getCurrentTable(e.tableName,r);if(!i)throw new n(`Cannot add computed default: table "${e.tableName}" is absent`,t.MIGRATION_INVALID_STATE);return this.compileTableRecreation(e.tableName,{...i,columns:[...i.columns,e.column]},i,r)}let i=this.generateColumnDef(e.column,r);return`ALTER TABLE ${this.escapeIdentifier(e.tableName)} ADD COLUMN ${i}`}generateDropColumn(e,t){return`ALTER TABLE ${this.escapeIdentifier(e.tableName)} DROP COLUMN ${this.escapeIdentifier(e.columnName)}`}generateRenameColumn(e,r){let i=this.getCurrentTable(e.tableName,r),a=i?.columns.find(t=>t.name===e.from),o=`ALTER TABLE ${this.escapeIdentifier(e.tableName)} RENAME COLUMN ${this.escapeIdentifier(e.from)} TO ${this.escapeIdentifier(e.to)}`;if(i===void 0||a?.decimal===void 0)return o;let s=E({tables:[i]},e).tables[0];if(s===void 0)throw new n(`Cannot rename column: table "${e.tableName}" disappeared from the current schema.`,t.INTERNAL_ERROR,{meta:{table:e.tableName,column:e.from}});return this.assertDomainReconstructionAdmitted(e.tableName,a,s,r,`decimal`),[o,...this.compileTableRecreation(e.tableName,s,s,r)]}generateAlterColumn(e,t){return this.compileAlterColumnByRecreation(e,t,!0)}compileAlterColumnByRecreation(e,t,n){let r=[e];if(n&&t.followingOperations){let compatible=t=>t?.type===`alterColumn`&&t.tableName===e.tableName&&m(t)===m(e),n=[];for(let e of[...t.precedingOperations??[]].reverse()){if(!compatible(e))break;n.unshift(e)}let i=[];for(let e of t.followingOperations){if(!compatible(e))break;i.push(e)}let a=[...n,e,...i];if(new Set(a.map(e=>e.columnName)).size===a.length){if(n.length>0)return[];r.push(...i)}}let i=this.getCurrentTable(e.tableName,t);if(!i)throw Error(`Cannot alter column: table "${e.tableName}" not found in current schema. Supply the current schema when compiling this operation.`);let a=new Map(r.map(e=>[e.columnName,e.to])),o=i.columns.map(e=>a.get(e.name)??e),s={...i,columns:o};for(let n of r)d(n.from,n.to)?this.assertDomainReconstructionAdmitted(e.tableName,n.to,s,t,`decimal`):C(n.from.dateTime,n.to.dateTime)&&this.assertDomainReconstructionAdmitted(e.tableName,n.to,s,t,`dateTime`);return this.compileTableRecreation(e.tableName,s,i,t)}generateCreateIndex(e,t){let{tableName:n,index:r}=e;this.validateIndexType(r.type,r.name);let i=r.unique?`UNIQUE `:``,a=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `),o=r.where?` WHERE ${r.where}`:``;return`CREATE ${i}INDEX ${this.escapeIdentifier(r.name)} ON ${this.escapeIdentifier(n)} (${a})${o}`}generateDropIndex(e,t){return`DROP INDEX ${this.escapeIdentifier(e.indexName)}`}generateAddForeignKey(e,t){return this.recreateWith(e.tableName,t,`add foreign key`,t=>({...t,foreignKeys:[...t.foreignKeys,e.fk]}))}generateDropForeignKey(e,t){return this.recreateWith(e.tableName,t,`drop foreign key`,t=>({...t,foreignKeys:t.foreignKeys.filter(t=>t.name!==e.fkName)}))}recreateWith(e,t,n,r){let i=this.getCurrentTable(e,t);if(!i)throw Error(`Cannot ${n}: table "${e}" not found in current schema. Supply the current schema when compiling this operation.`);return this.compileTableRecreation(e,r(i),i,t)}generateAddUniqueConstraint(e,t){return this.recreateWith(e.tableName,t,`add unique constraint`,t=>({...t,uniqueConstraints:[...t.uniqueConstraints,e.constraint]}))}generateDropUniqueConstraint(e,t){return this.recreateWith(e.tableName,t,`drop unique constraint`,t=>({...t,uniqueConstraints:t.uniqueConstraints.filter(t=>t.name!==e.constraintName)}))}generateAddPrimaryKey(e,t){return this.recreateWith(e.tableName,t,`add primary key`,t=>({...t,primaryKey:e.primaryKey}))}generateDropPrimaryKey(e,t){return this.recreateWith(e.tableName,t,`drop primary key`,e=>({...e,primaryKey:void 0}))}generateCreateEnum(e,t){return`-- SQLite: enum CHECK constraint is part of column definition`}generateDropEnum(e,r){let{enumName:i,dependentColumns:a}=e;if(!a||a.length===0)return`-- SQLite: no dependent columns for enum "${i}"`;let o=[];for(let e of a){let a=this.getCurrentTable(e.tableName,r);if(!a)throw new n(`Table "${e.tableName}" not found for enum "${i}"`,t.INTERNAL_ERROR);let s=a.columns.map(t=>t.name===e.columnName&&t.type.includes(`CHECK`)?{...t,type:`TEXT`}:t),c={...a,columns:s};o.push(...this.compileTableRecreation(e.tableName,c,a,r))}return o}generateAlterEnum(e,t){let{enumName:n,newValues:r,dependentColumns:i}=e,a=[];if(!r||r.length===0)return`-- SQLite: no new values provided for enum "${n}"`;if(!i||i.length===0)return`-- SQLite: no dependent columns found for enum "${n}"`;let o=r.map(e=>`'${e.replace(/'/g,`''`)}'`).join(`, `);for(let n of i){let r=this.getCurrentTable(n.tableName,t);if(!r){a.push(`-- SQLite: table "${n.tableName}" not found`);continue}let i=`TEXT CHECK(${this.escapeIdentifier(n.columnName)} IN (${o}))`,s=r.columns.map(e=>e.name===n.columnName?{...e,type:i}:e),c={...r,columns:s},l=this.escapeIdentifier(n.columnName),u=this.enumReplacementCases(e,n.tableName,n.columnName),d=u.length===0?void 0:new Map([[n.columnName,`CASE ${l} ${u.join(` `)} ELSE ${l} END`]]);a.push(...this.compileTableRecreation(n.tableName,c,r,t,void 0,d))}return a}generateAcquireLock(e){return null}generateReleaseLock(e){return null}generateInventoryTables(){return{sql:`SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name`,params:[]}}generateInventoryEnums(){return null}};const Q=new SQLite3MigrationDriver;var LibSQLMigrationDriver=class extends SQLite3MigrationDriver{driverName=`libsql`;capabilities={supportsNativeEnums:!1,supportsAddEnumValueInTransaction:!0,supportsIndexTypes:[`btree`],supportsNativeArrays:!1,supportsAddForeignKeyViaAlter:!1,introspectionReadsConstraintNames:!1};generateAlterColumn(e,t){if(d(e.from,e.to)||C(e.from.dateTime,e.to.dateTime))return this.compileAlterColumnByRecreation(e,t,!1);let{tableName:n,columnName:r,to:i}=e;return`ALTER TABLE ${this.escapeIdentifier(n)} ALTER COLUMN ${this.escapeIdentifier(r)} TO ${this.generateColumnDef(i,t)}`}buildColumnDefWithReferences(e,t){let n=[this.escapeIdentifier(e.name),e.type];e.nullable||n.push(`NOT NULL`),e.default!==void 0&&n.push(`DEFAULT ${e.default}`),e.type.toUpperCase()===S&&n.push(j(e,e=>this.escapeIdentifier(e),T(e)));let r=u(e);return e.decimal&&r&&n.push(g(e,e.decimal,r,e=>this.escapeIdentifier(e))),t&&(n.push(`REFERENCES ${this.escapeIdentifier(t.refTable)}(${this.escapeIdentifier(t.refCol)})`),t.onDelete&&t.onDelete!==`noAction`&&n.push(`ON DELETE ${this.formatReferentialAction(t.onDelete)}`),t.onUpdate&&t.onUpdate!==`noAction`&&n.push(`ON UPDATE ${this.formatReferentialAction(t.onUpdate)}`)),n.join(` `)}generateAddForeignKey(e,t){let{tableName:n,fk:r}=e;if(r.columns.length>1)return super.generateAddForeignKey(e,t);let i=r.columns[0],a=r.referencedColumns[0];if(!(i&&a))throw Error(`Invalid foreign key: columns array is empty for table "${n}".`);let o=this.getCurrentTable(n,t);if(!o)throw Error(`Cannot add foreign key: table "${n}" not found in current schema. Pass currentSchema in DDLContext.`);let s=o.columns.find(e=>e.name===i);if(!s)throw Error(`Cannot add foreign key: column "${i}" not found in table "${n}".`);return`ALTER TABLE ${this.escapeIdentifier(n)} ALTER COLUMN ${this.escapeIdentifier(i)} TO ${this.buildColumnDefWithReferences(s,{refTable:r.referencedTable,refCol:a,onDelete:r.onDelete,onUpdate:r.onUpdate})}`}generateDropForeignKey(e,t){let n=this.getCurrentTable(e.tableName,t);if(!n)throw Error(`Cannot drop foreign key: table "${e.tableName}" not found in current schema. Supply the current schema when compiling this operation.`);let r=n.foreignKeys.find(t=>t.name===e.fkName);if(!r)throw Error(`Cannot drop foreign key: constraint "${e.fkName}" not found in table "${e.tableName}".`);if(r.columns.length>1)return super.generateDropForeignKey(e,t);let i=r.columns[0];if(!i)throw Error(`Invalid foreign key: columns array is empty for constraint "${e.fkName}".`);let a=n.columns.find(e=>e.name===i);if(!a)throw Error(`Cannot drop foreign key: column "${i}" not found in table "${e.tableName}".`);return`ALTER TABLE ${this.escapeIdentifier(e.tableName)} ALTER COLUMN ${this.escapeIdentifier(i)} TO ${this.buildColumnDefWithReferences(a)}`}};const $=new LibSQLMigrationDriver;export{Q as n,$ as t};
|
|
11
|
-
//# sourceMappingURL=libsql-C4sm2U20.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"libsql-C4sm2U20.mjs","names":[],"sources":["../src/migrations/drivers/sqlite/introspect.ts","../src/migrations/drivers/sqlite/index.ts","../src/migrations/drivers/libsql/index.ts"],"sourcesContent":["import { isSqliteStateControlDefinition } from \"../../control\";\n/**\n * SQLite Schema Introspection\n *\n * Reads the current database schema from SQLite's PRAGMA statements\n * and sqlite_master, returning a normalized SchemaSnapshot.\n */\n\nimport { BATCH_REFS_TABLE } from \"@adapters/shared/batch-refs\";\nimport {\n sqliteDefinitionKeywords,\n sqliteTableDefinitions,\n} from \"../../../adapters/databases/sqlite/storage/column-constraints\";\nimport { readSqliteDecimalConstraint } from \"../../../adapters/databases/sqlite/storage/decimal\";\nimport {\n readSqliteGeoPointColumn,\n SQLITE_GEO_POINT_TYPE,\n} from \"../../../adapters/databases/sqlite/storage/geo-point\";\nimport { skipSqlNonStructuralRegion } from \"../../../adapters/databases/sqlite/storage/sql-lexing\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport type {\n ColumnDef,\n ForeignKeyDef,\n IndexDef,\n PrimaryKeyDef,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"../../types\";\nimport { mapReferentialAction } from \"../utils\";\nimport type {\n SqliteColumn,\n SqliteForeignKey,\n SqliteIndex,\n SqliteIndexColumn,\n SqliteInt,\n SqliteTable,\n} from \"./types\";\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\nfunction escapeIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/**\n * A pragma's integer column, as a number.\n *\n * SQLite reports integers, but the driver decides how they arrive: the LibSQL\n * driver runs with `intMode: \"bigint\"` (`src/drivers/libsql/index.ts`), so every\n * pragma integer reaches this file as BigInt. Read raw, each one is wrong in a\n * different way — `1n === 1` is false, so a unique index reads as non-unique\n * and a NOT NULL column reads as nullable; and `a.seqno - b.seqno` yields a\n * BigInt that `Array#sort` refuses outright, which crashes the introspection of\n * any index over two or more columns. Normalizing here, once, is what lets the\n * rest of this file compare plain numbers.\n */\nfunction int(value: SqliteInt): number {\n return Number(value);\n}\n\n/** The predicate half of a stored `CREATE INDEX … WHERE …`, if there is one. */\nconst TRAILING_WHERE = /^WHERE\\s+([\\s\\S]+)$/i;\n/** The defaults SQLite's column grammar takes without parentheses. */\n// Identifiers include NULL, TRUE, FALSE and CURRENT_*, and SQLite reads a\n// bare or double-quoted one in a default as a string literal.\nconst LITERAL_DEFAULT =\n /^(?:[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?|0x[\\da-f]+|'(?:[^']|'')*'|x'[\\da-f]*'|\"(?:[^\"]|\"\")*\"|[a-z_][\\w$]*)$/i;\n\n/**\n * A column's default as DDL. `PRAGMA table_info` reports `DEFAULT (expr)`\n * without its parentheses, and an expression is a legal default only inside\n * them: a table recreation that wrote `strftime(...)` back verbatim (an\n * `s.dateTime().now()` column) was a `CREATE TABLE` SQLite refused.\n */\nfunction columnDefault(value: string | null): string | undefined {\n if (value === null) return;\n return LITERAL_DEFAULT.test(value) ? value : `(${value})`;\n}\nconst AUTOINCREMENT = /\\bAUTOINCREMENT\\b/i;\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * The CHECK the SQLite driver embeds in an enum column type.\n *\n * `PRAGMA table_info` reports only `TEXT`. The values live in\n * `sqlite_master.sql` as `CHECK(\"col\" IN ('a', 'b'))`, which is the same\n * spelling `getEnumColumnType` writes into the desired snapshot. Reconstruct\n * that suffix so fingerprint and differ see one type.\n */\nfunction sqliteEnumCheckSuffix(\n tableSql: string | null,\n columnName: string\n): string | undefined {\n if (!tableSql) return;\n const quoted = escapeIdentifier(columnName);\n const match = tableSql.match(\n new RegExp(\n `CHECK\\\\(\\\\s*${escapeRegExp(quoted)}\\\\s+IN\\\\s*\\\\((\\\\s*(?:'(?:[^']|'')*'\\\\s*,\\\\s*)*'(?:[^']|'')*'\\\\s*)\\\\)\\\\s*\\\\)`,\n \"i\"\n )\n );\n const list = match?.[1];\n if (!list) return;\n const values: string[] = [];\n const literals = /'((?:[^']|'')*)'/g;\n let literal = literals.exec(list);\n while (literal) {\n const value = literal[1];\n if (value !== undefined) values.push(value.replace(/''/g, \"'\"));\n literal = literals.exec(list);\n }\n if (values.length === 0) return;\n const escaped = values\n .map((value) => `'${value.replace(/'/g, \"''\")}'`)\n .join(\", \");\n return ` CHECK(${quoted} IN (${escaped}))`;\n}\n\n/**\n * Reads the predicate of a partial index back out of the text SQLite stored.\n *\n * SQLite keeps `sqlite_master.sql` as the statement was written and re-spells\n * nothing (measured on 3.51: the predicate, its inner spacing and its padding\n * all come back byte-identical; only the statement terminator is dropped), so\n * the predicate the differ compares is the one the serializer emitted. This\n * reads it out and does not normalize it — `indexesEqual` is the one place the\n * two snapshot producers' spellings are reconciled.\n *\n * The predicate is whatever follows the column list, not whatever follows the\n * first `WHERE` in the text: a column may be named `a WHERE b`. So walk the\n * statement to the parenthesis that closes the column list, skipping quoted\n * identifiers and string literals, and read the tail from there.\n */\nfunction partialIndexPredicate(sql: string | null): string | undefined {\n if (!sql) return undefined;\n\n let depth = 0;\n let cursor = 0;\n let columnListEnd = -1;\n\n while (cursor < sql.length) {\n // Quoted tokens and comments are skipped through the ONE owner of where a\n // non-structural SQLite region ends, shared with the reserved decimal-\n // constraint reader: both read text SQLite stored verbatim, and both are\n // wrong the same way if its contents are read as syntax.\n const skipped = skipSqlNonStructuralRegion(sql, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n\n const char = sql[cursor];\n\n if (char === \"(\") {\n depth++;\n } else if (char === \")\") {\n depth--;\n if (depth === 0) {\n columnListEnd = cursor;\n break;\n }\n }\n cursor++;\n }\n\n if (columnListEnd === -1) return undefined;\n\n const match = TRAILING_WHERE.exec(sql.slice(columnListEnd + 1).trimStart());\n return match?.[1];\n}\n\n// =============================================================================\n// INTROSPECTION\n// =============================================================================\n\nexport async function introspect(\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>,\n managedTables?: readonly string[],\n excludeD1SystemTables = false\n): Promise<SchemaSnapshot> {\n // Get all tables. `sql` rides along on the query that was already being made\n // — the reserved decimal constraints are read out of it, and a second live\n // read for them would be a raw-execution call site the architecture census\n // pins per file. The engine's batch reference scratch is not part of the\n // user's schema: it is TEMP where the transport admits temporary objects and\n // never appears here, but on D1 it is an ordinary table in `main`, and a\n // snapshot that carried it would have push and diff plan its drop.\n // D1 also exposes provider-owned `_cf_` tables but forbids their PRAGMAs.\n // Filter that exact reserved prefix only for D1; GLOB treats `_` literally,\n // and an ordinary SQLite application's similarly named tables stay visible.\n const tablesResult = await executeRaw<SqliteTable>(\n `\n SELECT name, sql\n FROM sqlite_master\n WHERE type = 'table'\n AND name NOT LIKE 'sqlite_%'\n AND name <> ?\n ${excludeD1SystemTables ? \"AND name NOT GLOB '_cf_*'\" : \"\"}\n ORDER BY name\n `,\n [BATCH_REFS_TABLE]\n );\n\n const tables: TableDef[] = [];\n\n for (const tableRow of tablesResult.rows) {\n const tableName = tableRow.name;\n\n const selected =\n managedTables === undefined || managedTables.includes(tableName);\n const definitions = sqliteTableDefinitions(tableRow.sql ?? \"\");\n if (\n selected &&\n definitions.some((definition) =>\n sqliteDefinitionKeywords(definition.text).includes(\"AS\")\n )\n )\n throw new MigrationError(\n `SQLite table \"${tableName}\" has generated columns that this schema cannot represent. Synchronization refuses before effects and preserves them.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: tableName, feature: \"generated columns\" } }\n );\n if (\n selected &&\n sqliteDefinitionKeywords((tableRow.sql ?? \"\").split(\"(\")[0]!).includes(\n \"VIRTUAL\"\n )\n )\n throw new MigrationError(\n `SQLite virtual table \"${tableName}\" cannot be faithfully reconstructed. Synchronization refuses before effects.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: tableName, feature: \"virtual table\" } }\n );\n\n // Get columns using PRAGMA\n const columnsResult = await executeRaw<SqliteColumn>(\n `PRAGMA table_info(${escapeIdentifier(tableName)})`\n );\n const tableSql = tableRow.sql;\n const hasAutoincrement = AUTOINCREMENT.test(tableSql ?? \"\");\n\n // Get indexes\n const indexesResult = await executeRaw<SqliteIndex>(\n `PRAGMA index_list(${escapeIdentifier(tableName)})`\n );\n\n // The pragma reports that an index is partial but not what its predicate\n // is; only the stored statement carries that.\n const indexSqlResult = await executeRaw<{\n name: string;\n sql: string | null;\n }>(\n \"SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?\",\n [tableName]\n );\n const indexSql = new Map(\n indexSqlResult.rows.map((row) => [row.name, row.sql])\n );\n\n // Get foreign keys\n const fksResult = await executeRaw<SqliteForeignKey>(\n `PRAGMA foreign_key_list(${escapeIdentifier(tableName)})`\n );\n\n // Build columns\n const columns: ColumnDef[] = [];\n const pkColumns: { name: string; position: number }[] = [];\n\n for (const col of columnsResult.rows) {\n const pk = int(col.pk);\n const type = col.type || \"TEXT\";\n const nullable = int(col.notnull) === 0 && pk === 0;\n const geoPointEncoding = readSqliteGeoPointColumn(\n tableSql,\n { name: col.name, type, nullable },\n escapeIdentifier\n );\n columns.push({\n name: col.name,\n geoPointEncoding,\n type: geoPointEncoding\n ? SQLITE_GEO_POINT_TYPE\n : `${type}${sqliteEnumCheckSuffix(tableSql, col.name) ?? \"\"}`,\n nullable,\n default: columnDefault(col.dflt_value),\n autoIncrement: pk === 1 && hasAutoincrement,\n // The declared domain, recovered from the reserved CHECK constraint\n // the driver wrote. Nothing else on this dialect carries it: the type\n // is `INTEGER` (or `TEXT`) at every precision and scale, and the\n // pragma reports no constraints at all — so a side that could not\n // recover it would read as a change on every push, forever.\n decimal: readSqliteDecimalConstraint(\n tableSql,\n // The descriptor proof consumes the exact declared type PRAGMA\n // reported. The generic snapshot fallback above may call an untyped\n // column TEXT, but that normalization cannot turn BLOB affinity into\n // the writer-owned TEXT decimal-list carrier.\n { name: col.name, type: col.type, nullable },\n escapeIdentifier\n ),\n });\n\n if (pk > 0) {\n pkColumns.push({ name: col.name, position: pk });\n }\n }\n\n if (selected) {\n const checks = definitions.reduce(\n (count, definition) =>\n count +\n sqliteDefinitionKeywords(definition.text).filter(\n (word) => word === \"CHECK\"\n ).length,\n 0\n );\n const represented = columns.reduce(\n (count, column) =>\n count +\n Number(column.decimal !== undefined) +\n Number(column.geoPointEncoding !== undefined) +\n Number(sqliteEnumCheckSuffix(tableSql, column.name) !== undefined),\n 0\n );\n if (\n checks !== represented &&\n !isSqliteStateControlDefinition(tableName, tableSql)\n )\n throw new MigrationError(\n `SQLite table \"${tableName}\" has CHECK constraints that this schema cannot faithfully represent. Synchronization refuses before effects and preserves them.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: tableName, feature: \"CHECK constraints\" } }\n );\n }\n\n // Build primary key (sort by pk position)\n let primaryKey: PrimaryKeyDef | undefined;\n if (pkColumns.length > 0) {\n pkColumns.sort((a, b) => a.position - b.position);\n primaryKey = {\n name: `${tableName}_pkey`,\n columns: pkColumns.map((p) => p.name),\n };\n }\n\n // Build indexes and unique constraints\n const indexes: IndexDef[] = [];\n const uniqueConstraints: UniqueConstraintDef[] = [];\n\n for (const idx of indexesResult.rows) {\n // xinfo exposes the physical key semantics that index_info erases.\n // Auxiliary rowid columns are not key members; user expressions, DESC\n // and collations cannot be faithfully recreated by this declaration DSL.\n const indexColsResult = await executeRaw<SqliteIndexColumn>(\n `PRAGMA index_xinfo(${escapeIdentifier(idx.name)})`\n );\n const keys = indexColsResult.rows.filter(\n (column) => int(column.key) === 1\n );\n const unsupported =\n keys.length === 0 ||\n keys.some(\n (column) =>\n int(column.cid) < 0 ||\n column.name === null ||\n int(column.desc) !== 0 ||\n column.coll !== \"BINARY\"\n );\n if (unsupported) {\n if (managedTables === undefined || managedTables.includes(tableName)) {\n throw new MigrationError(\n `SQLite index \"${tableName}.${idx.name}\" has expression/order/collation semantics that this index declaration cannot represent. Synchronization refuses before effects and preserves it. Manage its table outside this synchronization scope until a faithful declaration is available.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { table: tableName, indexName: idx.name } }\n );\n }\n continue;\n }\n // PK membership is already represented by the table's primary key.\n if (idx.origin === \"pk\") continue;\n const indexColumns = keys\n .sort((a, b) => int(a.seqno) - int(b.seqno))\n .flatMap((column) => (column.name === null ? [] : [column.name]));\n\n const unique = int(idx.unique) === 1;\n if (unique && idx.origin === \"u\") {\n // This is a unique constraint\n uniqueConstraints.push({\n name: idx.name,\n columns: indexColumns,\n });\n } else {\n indexes.push({\n name: idx.name,\n columns: indexColumns,\n unique,\n where: partialIndexPredicate(indexSql.get(idx.name) ?? null),\n });\n }\n }\n\n // Build foreign keys - group by id (constraint)\n const fkMap = new Map<number, SqliteForeignKey[]>();\n for (const fk of fksResult.rows) {\n const id = int(fk.id);\n const existing = fkMap.get(id) || [];\n existing.push(fk);\n fkMap.set(id, existing);\n }\n\n const foreignKeys: ForeignKeyDef[] = [];\n for (const [id, fkCols] of fkMap) {\n const sorted = fkCols.sort((a, b) => int(a.seq) - int(b.seq));\n const first = sorted[0];\n if (first) {\n foreignKeys.push({\n name: `${tableName}_fk_${id}`,\n columns: sorted.map((f) => f.from),\n referencedTable: first.table,\n referencedColumns: sorted.map((f) => f.to),\n onDelete: mapReferentialAction(first.on_delete),\n onUpdate: mapReferentialAction(first.on_update),\n });\n }\n }\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n });\n }\n\n // SQLite doesn't have native enum types\n return { tables, enums: [] };\n}\n","import { nativeTypeFor } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport type { IdDomain } from \"@validation/primitives/id-codec\";\nimport { isDestructiveOperation } from \"../../differ\";\n/**\n * SQLite Migration Driver\n *\n * Implements the MigrationDriver interface for SQLite databases.\n * Uses table recreation for operations SQLite doesn't support natively.\n */\n\nimport type { Scalar, ScalarState } from \"@schema/scalars\";\nimport { sqliteDateTimePhysicalForm } from \"@schema/scalars/datetime/physical\";\nimport { encodePhysicalDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport { sameDecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { validateIsoTime } from \"@validation/primitives/iso\";\nimport {\n SQLITE_ABORT,\n sqliteDateTimeCopyExpression,\n sqliteDateTimeTargetRequiresRecreation,\n} from \"../../../adapters/databases/sqlite/storage/datetime\";\nimport {\n sqliteDecimalCheck,\n sqliteDecimalCopyExpression,\n} from \"../../../adapters/databases/sqlite/storage/decimal\";\nimport {\n SQLITE_GEO_POINT_TYPE,\n sqliteGeoPointCarrier,\n sqliteGeoPointCheck,\n sqliteGeoPointEncoding,\n} from \"../../../adapters/databases/sqlite/storage/geo-point\";\nimport {\n isSqliteBareIdentifierCharacter,\n readSqliteIdentifier,\n skipSqlNonStructuralRegion,\n} from \"../../../adapters/databases/sqlite/storage/sql-lexing\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport {\n decimalConversionRequired,\n describeDecimalDomain,\n sqliteDecimalStorageKind,\n} from \"../../decimal\";\nimport { foreignKeyPragmasCannotBeLifted } from \"../../foreign-keys\";\nimport { applyNativeRename } from \"../../native-rename\";\nimport type {\n ColumnDef,\n DiffOperation,\n SchemaSnapshot,\n TableDef,\n} from \"../../types\";\nimport {\n type AddColumnOperation,\n type AddForeignKeyOperation,\n type AddPrimaryKeyOperation,\n type AddUniqueConstraintOperation,\n type AlterColumnOperation,\n type AlterEnumOperation,\n type CreateEnumOperation,\n type CreateIndexOperation,\n type CreateTableOperation,\n type DDLContext,\n type DropColumnOperation,\n type DropEnumOperation,\n type DropForeignKeyOperation,\n type DropIndexOperation,\n type DropPrimaryKeyOperation,\n type DropTableOperation,\n type DropUniqueConstraintOperation,\n MigrationDriver,\n type RenameColumnOperation,\n type RenameTableOperation,\n} from \"../base\";\nimport { getSQLiteType } from \"../type-mapping\";\nimport type { MigrationCapabilities } from \"../types\";\nimport { introspect } from \"./introspect\";\n\nconst COMPUTED_DEFAULT_PREFIX = /^(?:CURRENT_(?:TIME|DATE|TIMESTAMP)|\\()/i;\n\nconst SQLITE_AUTOINDEX_PREFIX = \"sqlite_autoindex_\";\n\n/** The name a recreation builds its replacement under before the swap. */\nconst RECREATION_PREFIX = \"__new_\";\nconst CREATE_TABLE = /^CREATE\\s+TABLE\\s+/i;\nconst ALTER_TABLE = /^ALTER\\s+TABLE\\s+/i;\nconst RENAME_TO = /^\\s+RENAME\\s+TO\\s+/i;\nconst CREATE_DEPENDENT =\n /^CREATE\\s+(?:TEMP(?:ORARY)?\\s+)?(TRIGGER|VIEW)\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?/i;\nconst DROP_DEPENDENT = /^DROP\\s+(?:TRIGGER|VIEW)\\s+(?:IF\\s+EXISTS\\s+)?/i;\nconst DROP_TABLE = /^DROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?/i;\nconst IDENTIFIER_OPENERS = '\"`[';\nconst QUALIFIER_DOT = /^\\s*\\./;\n/**\n * The words SQLite never reads as a bare table name (checked on 3.53 against\n * every keyword, in FROM, INSERT, UPDATE, DELETE, JOIN and trigger `ON`). A\n * table spelled like one is quoted wherever SQL names it, so its bare spelling\n * is a keyword (`ORDER BY`), never a reference. Keywords SQLite also accepts\n * as names (`END`, `BY`, `VIEW`) stay references, the safe reading.\n */\nconst SQLITE_RESERVED_WORD =\n /^(?:add|all|alter|and|as|autoincrement|between|case|check|collate|commit|constraint|create|default|deferrable|delete|distinct|drop|else|escape|except|exists|foreign|from|group|having|in|index|insert|intersect|into|is|isnull|join|limit|not|nothing|notnull|null|on|or|order|primary|references|returning|select|set|table|then|to|transaction|union|unique|update|using|values|when|where)$/;\nconst COLUMN_CHECK = /\\s+CHECK\\s*\\(/;\nconst TEXT_AFFINITY = /CHAR|CLOB|TEXT/;\nconst REAL_AFFINITY = /REAL|FLOA|DOUB/;\n\n/**\n * A trigger or view as `sqlite_master` stores it; `table` is the lower-cased\n * `tbl_name`, a trigger's own table, unknown for one the program creates.\n */\ninterface SqliteDependent {\n readonly type: string;\n readonly name: string;\n readonly sql: string | null;\n readonly table?: string;\n}\n\n/**\n * The triggers and views a program's recreations would lose, each with the\n * live table it depends on.\n *\n * The program is walked in order from the catalog as it stands before it\n * runs, past leading comments and a `schema.` qualifier: a\n * `CREATE TRIGGER|VIEW` adds a dependent, a `DROP TRIGGER|VIEW` releases one,\n * a `DROP TABLE` releases the catalog's triggers on that table, which SQLite\n * drops with it, and each recreation — read from the one spelling\n * `compileTableRecreation` writes, `CREATE TABLE \"__new_<t>\"`, as the\n * foreign-key bracket is read from its pragmas — loses the dependents that\n * name the table at that point. A native `ALTER TABLE … RENAME TO` earlier in\n * the program maps the rebuilt name back to the live table, and both spellings\n * count, because the catalog was read before the rename rewrote it.\n */\nfunction lostDependents(\n program: readonly string[],\n catalog: readonly SqliteDependent[]\n): { readonly table: string; readonly dependent: SqliteDependent }[] {\n const dependents = new Map(\n catalog.map((row) => [row.name.toLowerCase(), row])\n );\n const formerNames = new Map<string, string>();\n const lost: { table: string; dependent: SqliteDependent }[] = [];\n for (const statement of program) {\n let text = statement.trim();\n // A leading comment does not hide the statement's head.\n let skipped = skipSqlNonStructuralRegion(text, 0);\n while (skipped > 0) {\n text = text.slice(skipped).trimStart();\n skipped = skipSqlNonStructuralRegion(text, 0);\n }\n const create = CREATE_TABLE.exec(text);\n const alter = ALTER_TABLE.exec(text);\n const created = CREATE_DEPENDENT.exec(text);\n const drop = DROP_DEPENDENT.exec(text);\n const dropTable = DROP_TABLE.exec(text);\n const head = create ?? alter ?? created ?? drop ?? dropTable;\n const name = head && readObjectName(text, head[0].length);\n if (!name) continue;\n const key = name.value.toLowerCase();\n if (created) {\n const type = created[1]!.toLowerCase();\n dependents.set(key, { type, name: name.value, sql: text });\n } else if (drop) {\n dependents.delete(key);\n } else if (dropTable) {\n const live = (formerNames.get(key) ?? name.value).toLowerCase();\n for (const [dependentKey, dependent] of dependents) {\n if (dependent.type === \"trigger\" && dependent.table === live) {\n dependents.delete(dependentKey);\n }\n }\n } else if (create && key.startsWith(RECREATION_PREFIX)) {\n const rebuilt = name.value.slice(RECREATION_PREFIX.length);\n const table = formerNames.get(rebuilt.toLowerCase()) ?? rebuilt;\n const spellings = [rebuilt.toLowerCase(), table.toLowerCase()];\n for (const [dependentKey, dependent] of dependents) {\n const sql = dependent.sql ?? \"\";\n if (!spellings.some((s) => sqlNamesTable(sql, dependent.name, s)))\n continue;\n lost.push({ table, dependent });\n dependents.delete(dependentKey);\n }\n } else if (alter && !key.startsWith(RECREATION_PREFIX)) {\n const rename = RENAME_TO.exec(text.slice(name.end));\n const to =\n rename && readSqliteIdentifier(text, name.end + rename[0].length);\n if (to)\n formerNames.set(\n to.value.toLowerCase(),\n formerNames.get(key) ?? name.value\n );\n }\n }\n return lost;\n}\n\n/** The object a statement head names, past an optional `schema.` qualifier. */\nfunction readObjectName(text: string, index: number) {\n const first = readSqliteIdentifier(text, index);\n const dot = first ? QUALIFIER_DOT.exec(text.slice(first.end)) : null;\n return first && dot\n ? readSqliteIdentifier(text, first.end + dot[0].length)\n : first;\n}\n\n/**\n * Whether a stored view or trigger names the lower-cased `table` as an\n * identifier, past its own name. String literals and comments are skipped, so\n * a trigger that writes the text 'item' does not name the table `item`, and\n * neither does a bare reserved word (`SQLITE_RESERVED_WORD`); a column spelled\n * like the table does, and refusing is the safe reading.\n */\nfunction sqlNamesTable(sql: string, ownName: string, table: string): boolean {\n let ownNamePending = true;\n let index = 0;\n while (index < sql.length) {\n const character = sql.charAt(index);\n const token =\n IDENTIFIER_OPENERS.includes(character) ||\n isSqliteBareIdentifierCharacter(character)\n ? readSqliteIdentifier(sql, index)\n : undefined;\n if (token) {\n const name = token.value.toLowerCase();\n if (ownNamePending && name === ownName.toLowerCase()) {\n ownNamePending = false;\n } else if (\n name === table &&\n (token.quoted || !SQLITE_RESERVED_WORD.test(name))\n ) {\n return true;\n }\n index = token.end;\n } else {\n index = Math.max(skipSqlNonStructuralRegion(sql, index), index + 1);\n }\n }\n return false;\n}\n\n/** SQLite's declared-type affinity rules; a column CHECK is not part of the type name. */\nfunction sqliteAffinity(type: string): string {\n const name = type.toUpperCase().split(COLUMN_CHECK)[0]!.trim();\n if (name.includes(\"INT\")) return \"INTEGER\";\n if (TEXT_AFFINITY.test(name)) return \"TEXT\";\n if (name === \"\" || name.includes(\"BLOB\")) return \"BLOB\";\n if (REAL_AFFINITY.test(name)) return \"REAL\";\n return \"NUMERIC\";\n}\n\n/**\n * The storage class a column type change converts copied values into, or\n * `undefined` when the copy keeps them as they are.\n *\n * Only a change of affinity into INTEGER, REAL or TEXT is guarded, because\n * SQLite converts into them silently and partially: an INTEGER column keeps\n * 'twelve' as TEXT and 1.5 as REAL, and a REAL one rounds an integer past\n * 2^53. A BLOB target stores values verbatim, and NUMERIC is the JSON\n * container's, whose CAST would read every JSON object as 0.\n */\nfunction sqliteConvertingAffinity(\n from: ColumnDef,\n to: ColumnDef\n): \"INTEGER\" | \"REAL\" | \"TEXT\" | undefined {\n const target = sqliteAffinity(to.type);\n if (target === sqliteAffinity(from.type)) return undefined;\n return target === \"INTEGER\" || target === \"REAL\" || target === \"TEXT\"\n ? target\n : undefined;\n}\n\n/**\n * One preceding operation of the batch, applied to the table definition a later\n * recreation will rebuild. `SQLite3MigrationDriver.getCurrentTable` explains\n * why the introspected definition alone is not enough, and what each list costs\n * when it is left behind.\n */\nfunction applyToTable(table: TableDef, op: DiffOperation): TableDef {\n if (!(\"tableName\" in op) || op.tableName !== table.name) {\n return table;\n }\n switch (op.type) {\n case \"addColumn\":\n return { ...table, columns: [...table.columns, op.column] };\n case \"dropColumn\":\n return {\n ...table,\n columns: table.columns.filter(\n (column) => column.name !== op.columnName\n ),\n };\n case \"alterColumn\":\n return {\n ...table,\n columns: table.columns.map((column) =>\n column.name === op.columnName ? op.to : column\n ),\n };\n case \"createIndex\":\n return { ...table, indexes: [...table.indexes, op.index] };\n case \"dropIndex\":\n return {\n ...table,\n indexes: table.indexes.filter((index) => index.name !== op.indexName),\n };\n case \"addForeignKey\":\n return { ...table, foreignKeys: [...table.foreignKeys, op.fk] };\n case \"dropForeignKey\":\n return {\n ...table,\n foreignKeys: table.foreignKeys.filter((fk) => fk.name !== op.fkName),\n };\n case \"addUniqueConstraint\":\n return {\n ...table,\n uniqueConstraints: [...table.uniqueConstraints, op.constraint],\n };\n case \"dropUniqueConstraint\":\n return {\n ...table,\n uniqueConstraints: table.uniqueConstraints.filter(\n (constraint) => constraint.name !== op.constraintName\n ),\n };\n case \"addPrimaryKey\":\n return { ...table, primaryKey: op.primaryKey };\n case \"dropPrimaryKey\":\n return { ...table, primaryKey: undefined };\n default:\n // `dropTable` is the only remaining operation that names this table, and\n // nothing rebuilds a table the same batch dropped.\n return table;\n }\n}\n\n/**\n * The schema-level table set after every preceding operation in the batch.\n *\n * Per-table replay cannot see a table created earlier in the same batch, and\n * retaining a dropped table invents relations the database no longer has.\n * This owner first evolves membership, then applies each operation's local and\n * inbound effects to every table that exists at that point.\n */\nfunction replaySchemaTables(\n tables: readonly TableDef[],\n operations: readonly DiffOperation[]\n): TableDef[] {\n let replayed = [...tables];\n for (const operation of operations) {\n if (operation.type === \"createTable\") {\n replayed = [...replayed, operation.table];\n continue;\n }\n if (operation.type === \"dropTable\") {\n replayed = replayed.filter((table) => table.name !== operation.tableName);\n continue;\n }\n if (operation.type === \"renameTable\" || operation.type === \"renameColumn\") {\n replayed = applyNativeRename({ tables: replayed }, operation).tables;\n continue;\n }\n replayed = replayed.map((table) => applyToTable(table, operation));\n }\n return replayed;\n}\n\n/** Whether a table carries an outbound FK or is the target of an inbound FK. */\nexport function sqliteTableBearsRelations(\n tableName: string,\n tables: readonly TableDef[],\n rebuiltTable?: TableDef,\n precedingOperations: readonly DiffOperation[] = []\n): boolean {\n if (rebuiltTable && rebuiltTable.foreignKeys.length > 0) return true;\n const replayed = replaySchemaTables(tables, precedingOperations);\n for (const table of replayed) {\n if (table.name === tableName && table.foreignKeys.length > 0) return true;\n if (\n table.foreignKeys.some(\n (foreignKey) => foreignKey.referencedTable === tableName\n )\n ) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * SQLite3 Migration Driver\n *\n * Handles migrations for better-sqlite3 and similar synchronous SQLite drivers.\n * Uses table recreation for operations SQLite doesn't support natively:\n * - ALTER COLUMN (type, default, NOT NULL changes)\n * - ADD/DROP FOREIGN KEY\n * - ADD/DROP PRIMARY KEY\n *\n * LibSQL extends this class and overrides methods for operations it supports.\n */\nexport class SQLite3MigrationDriver extends MigrationDriver {\n readonly dialect = \"sqlite\" as const;\n readonly driverName: string = \"sqlite3\";\n\n override finalizeTable(table: TableDef): TableDef {\n const increments = table.columns.filter((column) => column.autoIncrement);\n if (\n increments.length > 0 &&\n (increments.length !== 1 ||\n table.primaryKey?.columns.length !== 1 ||\n table.primaryKey.columns[0] !== increments[0]!.name ||\n increments[0]!.type.toUpperCase() !== \"INTEGER\" ||\n increments[0]!.nullable)\n ) {\n throw new MigrationError(\n `SQLite table \"${table.name}\" requires its AUTOINCREMENT column to be the sole non-null INTEGER primary key. Declare .id().autoIncrement() on that column.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { table: table.name } }\n );\n }\n return table;\n }\n\n override getIrreversibleRollbackReason(\n operation: DiffOperation\n ): string | undefined {\n if (\n operation.type === \"alterColumn\" &&\n sqliteGeoPointEncoding(operation.from) === \"binary64\" &&\n sqliteGeoPointEncoding(operation.to) === \"legacy\"\n ) {\n return `Rollback cannot downgrade GeoPoint column \"${operation.tableName}.${operation.columnName}\" to its legacy CHECK without rounding coordinates. Author an explicit manual data transition.`;\n }\n return super.getIrreversibleRollbackReason(operation);\n }\n\n readonly capabilities: MigrationCapabilities = {\n supportsNativeEnums: false,\n supportsAddEnumValueInTransaction: true, // N/A but doesn't matter\n supportsIndexTypes: [\"btree\"],\n supportsNativeArrays: false,\n // No `ALTER TABLE ADD FOREIGN KEY`: FKs stay inline in CREATE TABLE and\n // rely on SQLite's lazy reference resolution (forward refs are fine).\n supportsAddForeignKeyViaAlter: false,\n // `PRAGMA foreign_key_list` has no name column, and an inline\n // `CONSTRAINT x UNIQUE (...)` is only ever reported as\n // `sqlite_autoindex_<table>_<n>`. Neither name survives a round trip.\n introspectionReadsConstraintNames: false,\n };\n\n // ===========================================================================\n // INTROSPECTION\n // ===========================================================================\n\n /**\n * Also refuses, by name, every trigger and view a table recreation in\n * `program` would lose. A recreation drops the table, and SQLite drops its\n * triggers with it silently; a view or another table's trigger that reads it\n * fails the swap with an error that names neither. A trigger always names\n * its own table (`ON \"t\"`), so one read of the stored SQL finds both kinds\n * (`lostDependents`). A trigger or view the program drops before the\n * recreation is its own business; one it creates earlier is checked too.\n */\n override async preflightSchemaRequirements(\n snapshots: readonly SchemaSnapshot[],\n executeRaw: Parameters<typeof introspect>[0],\n program: readonly string[]\n ): Promise<boolean> {\n const names = [\n ...new Set(\n snapshots.flatMap((snapshot) =>\n snapshot.tables.map((table) => table.name)\n )\n ),\n ];\n if (names.length === 0 && program.length === 0) return false;\n const objects = await executeRaw<SqliteDependent>(\n \"SELECT type, name, sql, lower(tbl_name) AS \\\"table\\\" FROM sqlite_master WHERE type IN ('view', 'trigger')\"\n );\n const collision = objects.rows.find(\n (row) => row.type === \"view\" && names.includes(row.name)\n );\n if (collision)\n throw new MigrationError(\n `SQLite relation \"${collision.name}\" is a view, but this schema declares a table. Synchronization refuses before effects and preserves the view.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: collision.name, feature: \"view\" } }\n );\n const lost = lostDependents(program, objects.rows);\n if (lost.length > 0)\n throw new MigrationError(\n `This migration rebuilds SQLite ${lost.map(({ table, dependent }) => `table \"${table}\", which ${dependent.type} \"${dependent.name}\" depends on`).join(\"; \")}. ` +\n \"A rebuild drops the table, which silently drops its triggers and breaks every view or trigger that reads it. \" +\n \"The migration is refused before any statement runs, so the schema and data are unchanged. Drop them before this change (a SQL step earlier in the same migration path counts) and recreate them after it.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n table: lost[0]!.table,\n dependents: lost.map(\n ({ dependent }) => `${dependent.type}:${dependent.name}`\n ),\n feature: \"table recreation\",\n },\n }\n );\n return false;\n }\n\n introspect(\n executeRaw: Parameters<typeof introspect>[0]\n ): Promise<SchemaSnapshot> {\n const provider = this.executionDriver?.driverName;\n return introspect(executeRaw, this.target?.tables, provider === \"d1\");\n }\n\n // ===========================================================================\n // TYPE MAPPING\n // ===========================================================================\n\n mapScalarType(\n scalar: Scalar,\n scalarState: ScalarState,\n idDomain?: IdDomain\n ): string {\n const declaration = scalar[\"~\"].nativeType;\n\n // See the PostgreSQL driver: one storage owner, override included.\n const idStorage =\n idDomain === undefined || scalarState.array === true\n ? undefined\n : idStorageOf(idDomain, declaration, \"sqlite\");\n if (idStorage) return idStorage.columnType;\n\n // SQLite has no native list type. A native declaration can describe one\n // scalar member only; every list keeps its container below.\n const nativeType = nativeTypeFor(declaration, \"sqlite\");\n if (nativeType && !scalarState.array) {\n return nativeType.type;\n }\n\n // Use centralized type mapping\n return getSQLiteType({\n type: scalarState.type,\n array: scalarState.array,\n decimal: scalarState.decimal,\n });\n }\n\n override getDefaultExpression(\n scalar: Scalar,\n scalarState: ScalarState\n ): string | undefined {\n if (\n scalarState.type === \"datetime\" &&\n scalarState.autoGenerate?.kind === \"now\"\n ) {\n const form = sqliteDateTimePhysicalForm(scalar[\"~\"].nativeType);\n if (form === \"julianDay\") return \"(julianday('now'))\";\n if (form === \"epochMillis\")\n return \"(CAST(strftime('%s','now') AS INTEGER) * 1000 + CAST(substr(strftime('%f','now'),4,3) AS INTEGER))\";\n return \"(strftime('%Y-%m-%dT%H:%M:%fZ','now'))\";\n }\n if (scalarState.autoGenerate?.kind === \"now\") {\n if (scalarState.type === \"date\") return \"(strftime('%Y-%m-%d','now'))\";\n if (scalarState.type === \"time\") return \"(strftime('%H:%M:%f','now'))\";\n }\n const defaultValue =\n scalarState.hasDefault &&\n !scalarState.autoGenerate &&\n !scalarState.array &&\n (scalarState.type === \"datetime\" || scalarState.type === \"time\")\n ? this.literalDefaultValue(scalarState)\n : undefined;\n if (\n scalarState.type === \"datetime\" &&\n scalarState.array !== true &&\n scalarState.autoGenerate === undefined &&\n scalarState.hasDefault &&\n typeof defaultValue === \"string\"\n ) {\n const form = sqliteDateTimePhysicalForm(scalar[\"~\"].nativeType);\n const physical = encodePhysicalDateTime(defaultValue, form);\n return typeof physical === \"string\"\n ? this.escapeValue(physical)\n : String(physical);\n }\n if (\n scalarState.type === \"time\" &&\n !scalarState.array &&\n !scalarState.autoGenerate &&\n scalarState.hasDefault &&\n typeof defaultValue === \"string\"\n ) {\n const canonical = validateIsoTime(defaultValue);\n if (!(\"value\" in canonical))\n throw new MigrationError(\n \"Invalid Time literal default\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n return this.escapeValue(canonical.value);\n }\n return super.getDefaultExpression(scalar, scalarState);\n }\n\n // Override formatBooleanDefault for SQLite's 1/0 representation\n\n /**\n * SQLite uses 1/0 for boolean values instead of true/false.\n */\n protected override formatBooleanDefault(value: boolean): string {\n return value ? \"1\" : \"0\";\n }\n\n getEnumColumnType(\n _tableName: string,\n columnName: string,\n values: string[]\n ): string {\n // SQLite uses TEXT with CHECK constraint for enum validation\n const escapedValues = values\n .map((v) => `'${v.replace(/'/g, \"''\")}'`)\n .join(\", \");\n return `TEXT CHECK(${this.escapeIdentifier(columnName)} IN (${escapedValues}))`;\n }\n\n // ===========================================================================\n // HELPER: Column Definition\n // ===========================================================================\n\n protected generateColumnDef(column: ColumnDef, _context: DDLContext): string {\n // SQLite auto-increment only works with INTEGER PRIMARY KEY\n // Validate that autoIncrement columns use INTEGER type\n if (column.autoIncrement && column.type.toUpperCase() !== \"INTEGER\") {\n throw new MigrationError(\n \"SQLite auto-increment requires INTEGER type. \" +\n `Column \"${column.name}\" has type \"${column.type}\" which is not compatible with auto-increment. ` +\n \"Note: SQLite auto-increment is implicit when using INTEGER PRIMARY KEY.\",\n VibORMErrorCode.INVALID_INPUT,\n {\n meta: { column: column.name, type: column.type, autoIncrement: true },\n }\n );\n }\n\n if (column.autoIncrement) {\n return `${this.escapeIdentifier(column.name)} INTEGER PRIMARY KEY AUTOINCREMENT`;\n }\n\n const parts: string[] = [this.escapeIdentifier(column.name), column.type];\n\n if (!column.nullable) {\n parts.push(\"NOT NULL\");\n }\n\n if (column.default !== undefined) {\n parts.push(`DEFAULT ${column.default}`);\n }\n\n if (column.type.toUpperCase() === SQLITE_GEO_POINT_TYPE) {\n parts.push(\n sqliteGeoPointCheck(\n column,\n (name) => this.escapeIdentifier(name),\n sqliteGeoPointEncoding(column)\n )\n );\n }\n\n // The reserved decimal CHECK is a DERIVED render of the column's own\n // descriptor, emitted as a column CONSTRAINT beside the type — never\n // folded INTO `column.type`. `getEnumColumnType` above does fold its CHECK\n // into the type, and the measured cost is a full table recreation on every\n // push forever: `PRAGMA table_info.type` reports only the `type-name`\n // production, so the desired `TEXT CHECK(...)` never equals the\n // introspected `TEXT`. A named constraint reads back out of\n // `sqlite_master.sql` instead, which is where introspection recovers the\n // descriptor from.\n const kind = sqliteDecimalStorageKind(column);\n if (column.decimal && kind) {\n parts.push(\n sqliteDecimalCheck(column, column.decimal, kind, (name) =>\n this.escapeIdentifier(name)\n )\n );\n }\n\n return parts.join(\" \");\n }\n\n // ===========================================================================\n // TABLE RECREATION\n // ===========================================================================\n\n /**\n * Generates SQL for table recreation.\n * This is the Drizzle-style pattern for operations SQLite doesn't support.\n *\n * Steps:\n * 1. PRAGMA foreign_keys=OFF\n * 2. Create new table with desired schema\n * 3. Copy data from old table (using explicit column mapping by name)\n * 4. Drop old table\n * 5. Rename new table\n * 6. Recreate indexes\n * 7. PRAGMA foreign_keys=ON\n *\n * @param tableName - The table to recreate\n * @param newTable - The new table definition\n * @param currentTable - The current table definition (required for safe column mapping)\n * @param columnRenames - Optional map of old column name to new column name\n */\n protected compileTableRecreation(\n tableName: string,\n newTable: TableDef,\n currentTable: TableDef,\n context: DDLContext,\n columnRenames?: Map<string, string>,\n valueExpressions?: ReadonlyMap<string, string>\n ): string[] {\n const statements: string[] = [];\n const tempName = `${RECREATION_PREFIX}${tableName}`;\n const currentColumns = new Map(\n currentTable.columns.map((column) => [column.name, column])\n );\n const sourceNames = new Map<string, string>();\n for (const [oldName, newName] of columnRenames ?? []) {\n sourceNames.set(newName, oldName);\n }\n const usesCorrelatedListCopy = newTable.columns.some((column) => {\n const sourceName = sourceNames.get(column.name) ?? column.name;\n return (\n this.decimalConversionKind(currentColumns.get(sourceName), column) ===\n \"list\"\n );\n });\n // A list conversion opens correlated `json_each` tables whose ten virtual\n // column names are ordinary legal user column names. Every outer read is\n // qualified through this one statement-local alias so `\"value\"`, `\"key\"`,\n // and their siblings cannot be captured by the inner table. Ordinary and\n // scalar-only recreations retain their original unaliased SQL.\n const sourceAlias = \"__viborm_source\";\n\n // 1. Disable foreign keys\n statements.push(\"PRAGMA foreign_keys=OFF\");\n\n // 2. Create new table\n statements.push(\n this.generateCreateTableDef({ ...newTable, name: tempName }, context)\n );\n\n // 3. Copy data - EXPLICIT column mapping by NAME, not position\n // Build a set of current column names for quick lookup\n // For each column in the new table, find the corresponding source column.\n // `source` is an EXPRESSION, not an identifier: a decimal column whose\n // declared domain moved is converted here, inside the database, on the way\n // across.\n const copyColumns: Array<{ source: string; target: string }> = [];\n\n for (const col of newTable.columns) {\n const sourceName = sourceNames.get(col.name) ?? col.name;\n\n // Only copy if source column exists in current table\n const currentColumn = currentColumns.get(sourceName);\n if (currentColumn !== undefined) {\n const source = usesCorrelatedListCopy\n ? `${this.escapeIdentifier(sourceAlias)}.${this.escapeIdentifier(sourceName)}`\n : this.escapeIdentifier(sourceName);\n copyColumns.push({\n source:\n valueExpressions?.get(col.name) ??\n this.copySourceExpression(\n tableName,\n sourceName,\n currentColumn,\n col,\n source\n ),\n target: col.name,\n });\n } else if (!col.nullable && col.default === undefined) {\n // New NOT NULL column without default - INSERT will fail\n throw new MigrationError(\n `Cannot add NOT NULL column \"${col.name}\" without a default value during table recreation. ` +\n \"SQLite requires a default value or nullable column for table recreation.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED\n );\n }\n // New columns with defaults or nullable will get their default/NULL values\n }\n\n if (copyColumns.length > 0) {\n const selectCols = copyColumns.map((c) => c.source).join(\", \");\n const insertCols = copyColumns\n .map((c) => this.escapeIdentifier(c.target))\n .join(\", \");\n\n statements.push(\n `INSERT INTO ${this.escapeIdentifier(tempName)} (${insertCols}) ` +\n `SELECT ${selectCols} FROM ${this.escapeIdentifier(tableName)}` +\n (usesCorrelatedListCopy\n ? ` AS ${this.escapeIdentifier(sourceAlias)}`\n : \"\")\n );\n }\n\n // 4. Drop old table\n statements.push(`DROP TABLE ${this.escapeIdentifier(tableName)}`);\n\n // 5. Rename new table\n statements.push(\n `ALTER TABLE ${this.escapeIdentifier(tempName)} RENAME TO ${this.escapeIdentifier(tableName)}`\n );\n\n // 6. Recreate indexes (they were dropped with the old table)\n for (const idx of newTable.indexes) {\n statements.push(\n this.generateCreateIndex(\n { type: \"createIndex\", tableName, index: idx },\n context\n )\n );\n }\n\n // 7. Re-enable foreign keys\n statements.push(\"PRAGMA foreign_keys=ON\");\n\n return this.filterStatements(statements);\n }\n\n /**\n * What the recreation SELECTs for one column of the rebuilt table.\n *\n * Ordinarily the column itself. When the column's declared decimal domain\n * moved, it is the conversion expression instead: SQLite stores the unscaled\n * coefficient, so a scale change makes every stored integer mean a different\n * number until it is rescaled, and the whole conversion runs inside the\n * database because the rebuild is one `INSERT ... SELECT` this process never\n * reads a row of.\n *\n * A change that moves the STORAGE SHAPE — a scalar becoming a list, or the\n * other way — gets no conversion and no second guard: the value is copied as\n * it stands and the target column's own reserved CHECK refuses it, which\n * aborts the rebuild inside its transaction and leaves the old table exactly\n * as it was.\n *\n * A source column that declares NO domain is the third case, and it is a\n * conversion too. An `INTEGER` holding logical integers, adopted as\n * `decimal(p,s)`, has to become a coefficient: copied as it stands, `123`\n * would silently start reading as 1.23. Only that one adoption is converted.\n * A TEXT source or a list target has no proven logical scale, and SQLite can\n * coerce numeric text after the copy, so every other unmarked source refuses\n * here before the recreation exists.\n *\n * A decimal column leaving its domain is descaled the same way, by\n * `descaledDecimalSource`.\n *\n * A column with no decimal or DateTime target whose type changes affinity\n * (`sqliteConvertingAffinity`) is converted with a `CAST` that must compare\n * equal to the source under SQLite's own rules. A value that does not —\n * 'twelve' or 1.5 into INTEGER, a BLOB into TEXT — aborts the rebuild like\n * an inexact DateTime instead of being stored unconverted.\n */\n private copySourceExpression(\n tableName: string,\n sourceName: string,\n currentColumn: ColumnDef | undefined,\n targetColumn: ColumnDef,\n source: string\n ): string {\n if (\n targetColumn.geoPointEncoding === \"binary64\" &&\n currentColumn !== undefined &&\n sqliteGeoPointEncoding(currentColumn) === \"legacy\"\n ) {\n return `CASE WHEN ${source} IS NULL THEN NULL ELSE ${sqliteGeoPointCarrier(source)} END`;\n }\n const dateTime = targetColumn.dateTime;\n if (dateTime !== undefined) {\n const sourceForm = this.sqliteDateTimeSourceForm(currentColumn);\n if (sourceForm === undefined) {\n const sourceDomain =\n currentColumn?.decimal === undefined\n ? `${currentColumn?.type ?? \"unknown\"} storage`\n : `a fixed-decimal domain at ${describeDecimalDomain(currentColumn.decimal)}`;\n throw new MigrationError(\n `The declared change to \"${tableName}\".\"${sourceName}\" would adopt ${sourceDomain} as a SQLite DateTime. ` +\n \"Only a declared DateTime or unmarked TEXT, INTEGER epoch-millisecond, or REAL Julian-day candidate can be converted exactly. \" +\n \"The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n table: tableName,\n column: sourceName,\n feature: \"SQLite DateTime storage conversion\",\n dialect: \"sqlite\",\n },\n }\n );\n }\n return sqliteDateTimeCopyExpression(\n source,\n sourceForm,\n dateTime,\n currentColumn?.dateTime !== undefined\n );\n }\n\n const to = targetColumn.decimal;\n const targetKind = sqliteDecimalStorageKind(targetColumn);\n const from = currentColumn?.decimal;\n if (to === undefined && currentColumn !== undefined && from !== undefined) {\n return this.descaledDecimalSource(\n tableName,\n sourceName,\n { ...currentColumn, decimal: from },\n targetColumn.type,\n source\n );\n }\n if (to === undefined || targetKind === undefined) {\n const affinity =\n currentColumn && sqliteConvertingAffinity(currentColumn, targetColumn);\n return affinity === undefined\n ? source\n : `CASE WHEN ${source} IS NULL THEN NULL WHEN CAST(${source} AS ${affinity}) = ${source} THEN CAST(${source} AS ${affinity}) ELSE ${SQLITE_ABORT} END`;\n }\n\n if (from === undefined) {\n const adopting =\n targetKind === \"scalar\" &&\n currentColumn?.type.toUpperCase() === \"INTEGER\";\n if (!adopting) {\n throw new MigrationError(\n `The declared change to \"${tableName}\".\"${sourceName}\" would adopt unmarked ${currentColumn?.type ?? \"unknown\"} storage as a fixed-decimal ${targetKind}. ` +\n \"Only a scalar INTEGER has one exact descriptor-free meaning that can be rescaled into the target domain. TEXT and every list container carry no proven member scale, while other SQLite affinities can already have changed the stored value. \" +\n \"The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n table: tableName,\n column: sourceName,\n feature: \"decimal storage adoption\",\n dialect: \"sqlite\",\n },\n }\n );\n }\n return sqliteDecimalCopyExpression(source, undefined, to, \"scalar\");\n }\n if (sameDecimalDescriptor(from, to)) return source;\n const conversionKind = this.decimalConversionKind(\n currentColumn,\n targetColumn\n );\n if (conversionKind === undefined) return source;\n return sqliteDecimalCopyExpression(source, from, to, conversionKind);\n }\n\n /**\n * A fixed-decimal source copied into a column that declares no domain.\n *\n * SQLite stores the scaled coefficient, so the value is descaled on the way\n * across: 1.23 at scale 2 is stored as 123 and must not read back as 123.\n * Only an INTEGER target holds the result exactly, and a value with a\n * fraction — or a stored value that is no coefficient at all — aborts the\n * rebuild through `SQLITE_ABORT`. The decimal copy helper guards the same\n * way, but its sentinel relies on a reserved CHECK this target does not\n * carry.\n * Every other target (TEXT, REAL, a list) has no one exact spelling of the\n * value and is refused here, before the recreation exists.\n */\n private descaledDecimalSource(\n tableName: string,\n sourceName: string,\n currentColumn: ColumnDef & { decimal: NonNullable<ColumnDef[\"decimal\"]> },\n targetType: string,\n source: string\n ): string {\n const kind = sqliteDecimalStorageKind(currentColumn);\n if (kind === \"scalar\" && sqliteAffinity(targetType) === \"INTEGER\") {\n const factor = 10n ** BigInt(currentColumn.decimal.scale);\n return `CASE WHEN ${source} IS NULL THEN NULL WHEN typeof(${source}) = 'integer' AND ${source} % ${factor} = 0 THEN ${source} / ${factor} ELSE ${SQLITE_ABORT} END`;\n }\n throw new MigrationError(\n `The declared change to \"${tableName}\".\"${sourceName}\" would copy a fixed-decimal ${kind ?? \"column\"} at ${describeDecimalDomain(currentColumn.decimal)} into ${targetType} storage that declares no decimal domain. ` +\n \"SQLite stores the decimal as its scaled integer coefficient, and only a scalar copied into INTEGER storage can be descaled exactly. \" +\n \"The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n table: tableName,\n column: sourceName,\n feature: \"decimal storage conversion\",\n dialect: \"sqlite\",\n },\n }\n );\n }\n\n /** Physical source vocabulary for a target known to be a DateTime. */\n private sqliteDateTimeSourceForm(\n column: ColumnDef | undefined\n ): \"text\" | \"epochMillis\" | \"julianDay\" | undefined {\n if (column?.dateTime !== undefined) return column.dateTime;\n if (column?.decimal !== undefined) return undefined;\n switch (column?.type.toUpperCase()) {\n case \"TEXT\":\n return \"text\";\n case \"INTEGER\":\n return \"epochMillis\";\n case \"REAL\":\n return \"julianDay\";\n default:\n return undefined;\n }\n }\n\n /** The shared-storage decimal conversion one copied column requires. */\n private decimalConversionKind(\n currentColumn: ColumnDef | undefined,\n targetColumn: ColumnDef\n ): \"scalar\" | \"list\" | undefined {\n const from = currentColumn?.decimal;\n const to = targetColumn.decimal;\n if (\n currentColumn === undefined ||\n from === undefined ||\n to === undefined ||\n sameDecimalDescriptor(from, to)\n ) {\n return undefined;\n }\n const targetKind = sqliteDecimalStorageKind(targetColumn);\n if (\n targetKind === undefined ||\n sqliteDecimalStorageKind(currentColumn) !== targetKind\n ) {\n return undefined;\n }\n return targetKind;\n }\n\n /**\n * Refuses a domain conversion the substrate cannot rebuild safely, BEFORE\n * any statement runs.\n *\n * Every SQLite descriptor change is a table recreation, and a recreation\n * drops and rebuilds the table with foreign-key enforcement disabled. That\n * disable is only real when `PRAGMA foreign_keys=OFF` runs OUTSIDE the\n * transaction — SQLite documents it as a no-op inside one — and the lift is\n * proven only inside a transaction that can roll it back\n * (`foreignKeyPragmasCannotBeLifted`). A driver without one cannot prove it:\n * on D1 the pragma travels inside one native batch and does nothing, so\n * `DROP TABLE` either raises the constraint or silently fires the\n * referential action on every child row.\n *\n * D1 is the shipped case, and plan §7.4 states the prerequisite exactly: a\n * relation-bearing rebuild is admitted only after the foreign-key-safe\n * rebuild is proven across the ten relation shapes. Until then this refuses\n * with the substrate reason rather than shipping an unsafe drop/recreate or\n * a manual shadow-column instruction.\n *\n * Only relation-bearing tables are refused: a table with no reference in\n * either direction has nothing the disabled enforcement could damage, so\n * fresh decimal schemas and ordinary descriptor changes stay available.\n *\n * The question remains conversion-owned: decimal descriptor changes and\n * adoption, decimal carrier renames, and DateTime form/adoption transitions\n * ask this owner. A recreation requested by another column, constraint, key,\n * or enum does not become a domain conversion merely because the same table\n * also contains one of these scalars. General D1 reconstruction safety is an\n * existing migration concern outside this boundary.\n */\n private assertDomainReconstructionAdmitted(\n tableName: string,\n column: ColumnDef,\n table: TableDef,\n context: DDLContext,\n domain: \"decimal\" | \"dateTime\"\n ): void {\n let description: string;\n let feature: string;\n if (domain === \"decimal\") {\n if (column.decimal === undefined) return;\n description = `a fixed-decimal column at ${describeDecimalDomain(column.decimal)}`;\n feature = \"decimal descriptor conversion\";\n } else {\n if (column.dateTime === undefined) return;\n description = `a SQLite DateTime column in ${column.dateTime} storage`;\n feature = \"SQLite DateTime storage conversion\";\n }\n const driver = this.executionDriver;\n if (!(driver && foreignKeyPragmasCannotBeLifted(driver))) return;\n if (\n !sqliteTableBearsRelations(\n tableName,\n context.currentSchema?.tables ?? [],\n table,\n context.precedingOperations\n )\n ) {\n return;\n }\n throw new MigrationError(\n `Rebuilding \"${tableName}\".\"${column.name}\", ${description}, recreates the whole table, and the driver \"${driver.driverName}\" runs migrations without a transaction (D1 runs them as one native batch). ` +\n \"Without a transaction, `PRAGMA foreign_keys=OFF` cannot be proven before the rebuild drops a table that still has references, nor the drop rolled back — and a pragma that did not take raises on one referential action and silently deletes or nulls child rows on another. \" +\n \"The change is refused before any statement runs, so the schema and its data are exactly as they were. Recreate the table without its references, or run the change on a driver with transactions.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n driver: driver.driverName,\n table: tableName,\n column: column.name,\n feature,\n },\n }\n );\n }\n\n /**\n * Helper to generate CREATE TABLE DDL without indexes\n */\n protected generateCreateTableDef(\n table: TableDef,\n context: DDLContext\n ): string {\n const parts: string[] = [];\n\n // Columns\n for (const col of table.columns) {\n parts.push(this.generateColumnDef(col, context));\n }\n\n // Primary key (if composite or not INTEGER autoincrement)\n if (table.primaryKey) {\n const isSingleIntegerPK =\n table.primaryKey.columns.length === 1 &&\n table.columns.find(\n (c) =>\n c.name === table.primaryKey!.columns[0] &&\n c.type.toUpperCase() === \"INTEGER\" &&\n c.autoIncrement\n );\n\n if (!isSingleIntegerPK) {\n const pkCols = table.primaryKey.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n parts.push(`PRIMARY KEY (${pkCols})`);\n }\n }\n\n // Unique constraints. One read back from the live table has SQLite's own\n // `sqlite_autoindex_<table>_<n>` for a name, which a recreation must not\n // carry into the new table: it is written unnamed, as SQLite reports it.\n for (const uq of table.uniqueConstraints) {\n const uqCols = uq.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n parts.push(\n uq.name.startsWith(SQLITE_AUTOINDEX_PREFIX)\n ? `UNIQUE (${uqCols})`\n : `CONSTRAINT ${this.escapeIdentifier(uq.name)} UNIQUE (${uqCols})`\n );\n }\n\n // Foreign keys\n for (const fk of table.foreignKeys) {\n const fkCols = fk.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n const refCols = fk.referencedColumns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n\n let fkDef = `CONSTRAINT ${this.escapeIdentifier(fk.name)} `;\n fkDef += `FOREIGN KEY (${fkCols}) `;\n fkDef += `REFERENCES ${this.escapeIdentifier(fk.referencedTable)} (${refCols})`;\n\n if (fk.onDelete && fk.onDelete !== \"noAction\") {\n fkDef += ` ON DELETE ${this.formatReferentialAction(fk.onDelete)}`;\n }\n if (fk.onUpdate && fk.onUpdate !== \"noAction\") {\n fkDef += ` ON UPDATE ${this.formatReferentialAction(fk.onUpdate)}`;\n }\n\n parts.push(fkDef);\n }\n\n return `CREATE TABLE ${this.escapeIdentifier(table.name)} (\\n ${parts.join(\",\\n \")}\\n)`;\n }\n\n /**\n * The table definition a recreation has to rebuild — the introspected one,\n * moved on by every preceding operation of the same batch.\n *\n * `currentSchema` is read once, before the first statement runs, so on its own\n * it describes the table as it was. A recreation drops the table and rebuilds\n * whatever this definition names, so read raw it destroys everything the same\n * batch created earlier and resurrects everything the same batch dropped. Each\n * list is a measured hazard, not a hypothetical:\n *\n * - INDEXES. `createIndex` runs at priority 15 and `addForeignKey` at 16, and\n * SQLite recreates the table for every foreign-key change — so on a database\n * that predates the FK index each foreign-key push created the index and\n * then threw it away, forever.\n *\n * - FOREIGN KEYS. `dropForeignKey` runs at 2 and `addForeignKey` at 16, and\n * the differ plans that pair for every changed key. With the pre-batch list\n * the add rebuilt the table around the constraint the drop had just removed\n * AND its replacement: measured on better-sqlite3, `zz_posts` held 1, then\n * 2, then 3 identical foreign keys after three idempotent pushes.\n *\n * - COLUMNS. `addColumn` runs at 10 and `alterColumn` at 12, and `alterColumn`\n * is a recreation on SQLite. Measured: pushing a model that both widens one\n * column's type and adds another emitted the `ALTER TABLE ... ADD COLUMN`,\n * then rebuilt the table from the pre-batch column list — and the new column\n * was gone. The push reported success, and the next one added and lost it\n * again. Two `alterColumn`s in one batch reverted each other the same way.\n *\n * - UNIQUE CONSTRAINTS. `dropUniqueConstraint` runs at 4 and\n * `addUniqueConstraint` at 14, and both ARE recreations here — the\n * constraint is inline in `CREATE TABLE` (see\n * `generateAddUniqueConstraint`). So the pair a changed constraint plans\n * reads its own predecessor, and a later recreation at 16 has to rebuild\n * around the constraint the add put there rather than the one the drop\n * removed.\n *\n * - PRIMARY KEY. `dropPrimaryKey` runs at 5 and `addPrimaryKey` at 13, both\n * ahead of `addForeignKey`, so a later recreation would rebuild around the\n * key that was just replaced.\n *\n * - INBOUND FOREIGN KEYS. Native SQLite table and column renames rewrite\n * references stored in OTHER tables. If one of those tables is recreated\n * later in the batch, its pre-batch definition would restore the old table\n * or column name unless the same replay carries the rename's remote effect.\n *\n * These are all the operations that move any of those five out of `TableDef`,\n * plus the two native renames whose effects cross table boundaries. Replaying\n * them gives what the database actually holds when the recreation runs.\n */\n protected getCurrentTable(\n tableName: string,\n context: DDLContext\n ): TableDef | undefined {\n return replaySchemaTables(\n context.currentSchema?.tables ?? [],\n context.precedingOperations ?? []\n ).find((table) => table.name === tableName);\n }\n\n // ===========================================================================\n // DDL GENERATION - Table Operations\n // ===========================================================================\n\n generateCreateTable(\n op: CreateTableOperation,\n context: DDLContext\n ): readonly string[] {\n const { table } = op;\n const statements: string[] = [this.generateCreateTableDef(table, context)];\n\n // Create indexes separately\n for (const idx of table.indexes) {\n statements.push(\n this.generateCreateIndex(\n {\n type: \"createIndex\",\n tableName: table.name,\n index: idx,\n },\n context\n )\n );\n }\n\n return statements;\n }\n\n generateDropTable(op: DropTableOperation, _context: DDLContext): string {\n return `DROP TABLE ${this.escapeIdentifier(op.tableName)}`;\n }\n\n generateRenameTable(op: RenameTableOperation, _context: DDLContext): string {\n return `ALTER TABLE ${this.escapeIdentifier(op.from)} RENAME TO ${this.escapeIdentifier(op.to)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Column Operations\n // ===========================================================================\n\n generateAddColumn(\n op: AddColumnOperation,\n context: DDLContext\n ): string | readonly string[] {\n if (\n op.column.default !== undefined &&\n COMPUTED_DEFAULT_PREFIX.test(op.column.default)\n ) {\n const current = this.getCurrentTable(op.tableName, context);\n if (!current)\n throw new MigrationError(\n `Cannot add computed default: table \"${op.tableName}\" is absent`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n return this.compileTableRecreation(\n op.tableName,\n { ...current, columns: [...current.columns, op.column] },\n current,\n context\n );\n }\n const colDef = this.generateColumnDef(op.column, context);\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} ADD COLUMN ${colDef}`;\n }\n\n generateDropColumn(op: DropColumnOperation, _context: DDLContext): string {\n // SQLite 3.35.0+ supports DROP COLUMN\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} DROP COLUMN ${this.escapeIdentifier(op.columnName)}`;\n }\n\n /**\n * Renames a column — natively first, then through a table recreation when\n * that column is a decimal.\n *\n * The descriptor rides in a CHECK constraint whose NAME contains the column\n * name, and `ALTER TABLE … RENAME COLUMN` rewrites column REFERENCES inside a\n * CHECK body but never a constraint NAME. So the native rename leaves the\n * carrier behind, pointing at a column that no longer exists: introspection\n * reads the renamed column as carrying no domain, the next push plans an\n * alteration between a domain and nothing, and the stored coefficient is\n * copied unchanged under whatever scale the schema now declares — 12345\n * meaning 123.45 silently becomes 1.2345. It is not even destructive by the\n * differ's reading, because no domain narrowed, so no prompt fires.\n *\n * The native statement has a second job a recreation cannot perform: SQLite\n * rewrites inbound foreign keys stored in OTHER tables. Only after that\n * schema-wide propagation does the ordinary recreation replace the stale\n * carrier name on the already-renamed table. The reconstruction therefore\n * copies the new column name from a current definition that already contains\n * the rename; it is not a second rename mechanism.\n */\n generateRenameColumn(\n op: RenameColumnOperation,\n context: DDLContext\n ): string | readonly string[] {\n const currentTable = this.getCurrentTable(op.tableName, context);\n const renamed = currentTable?.columns.find(\n (column) => column.name === op.from\n );\n // SQLite 3.25.0+ supports RENAME COLUMN\n const nativeRename = `ALTER TABLE ${this.escapeIdentifier(op.tableName)} RENAME COLUMN ${this.escapeIdentifier(op.from)} TO ${this.escapeIdentifier(op.to)}`;\n if (currentTable === undefined || renamed?.decimal === undefined) {\n return nativeRename;\n }\n\n const renamedTable = applyNativeRename({ tables: [currentTable] }, op)\n .tables[0];\n if (renamedTable === undefined) {\n throw new MigrationError(\n `Cannot rename column: table \"${op.tableName}\" disappeared from the current schema.`,\n VibORMErrorCode.INTERNAL_ERROR,\n { meta: { table: op.tableName, column: op.from } }\n );\n }\n this.assertDomainReconstructionAdmitted(\n op.tableName,\n renamed,\n renamedTable,\n context,\n \"decimal\"\n );\n return [\n nativeRename,\n ...this.compileTableRecreation(\n op.tableName,\n renamedTable,\n renamedTable,\n context\n ),\n ];\n }\n\n generateAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): string | readonly string[] {\n return this.compileAlterColumnByRecreation(op, context, true);\n }\n\n /**\n * SQLite's value-preserving ALTER COLUMN implementation. `grouped` folds a\n * run of compatible changes to one table into one recreation; a dialect\n * that recreates only some changes (LibSQL) recreates each on its own.\n */\n protected compileAlterColumnByRecreation(\n op: AlterColumnOperation,\n context: DDLContext,\n grouped: boolean\n ): readonly string[] {\n const group = [op];\n if (grouped && context.followingOperations) {\n const compatible = (\n candidate: DiffOperation | undefined\n ): candidate is AlterColumnOperation =>\n candidate?.type === \"alterColumn\" &&\n candidate.tableName === op.tableName &&\n isDestructiveOperation(candidate) === isDestructiveOperation(op);\n const previous: AlterColumnOperation[] = [];\n for (const candidate of [\n ...(context.precedingOperations ?? []),\n ].reverse()) {\n if (!compatible(candidate)) break;\n previous.unshift(candidate);\n }\n const following: AlterColumnOperation[] = [];\n for (const candidate of context.followingOperations) {\n if (!compatible(candidate)) break;\n following.push(candidate);\n }\n const run = [...previous, op, ...following];\n // Repeated changes to the same column are sequential semantics, not one projection.\n if (new Set(run.map((change) => change.columnName)).size === run.length) {\n if (previous.length > 0) return [];\n group.push(...following);\n }\n }\n // SQLite doesn't support ALTER COLUMN - need table recreation\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot alter column: table \"${op.tableName}\" not found in current schema. ` +\n \"Supply the current schema when compiling this operation.\"\n );\n }\n\n const targets = new Map(\n group.map((change) => [change.columnName, change.to])\n );\n const newColumns = currentTable.columns.map(\n (column) => targets.get(column.name) ?? column\n );\n\n const newTable: TableDef = {\n ...currentTable,\n columns: newColumns,\n };\n\n for (const change of group) {\n if (decimalConversionRequired(change.from, change.to)) {\n this.assertDomainReconstructionAdmitted(\n op.tableName,\n change.to,\n newTable,\n context,\n \"decimal\"\n );\n } else if (\n sqliteDateTimeTargetRequiresRecreation(\n change.from.dateTime,\n change.to.dateTime\n )\n ) {\n this.assertDomainReconstructionAdmitted(\n op.tableName,\n change.to,\n newTable,\n context,\n \"dateTime\"\n );\n }\n }\n\n return this.compileTableRecreation(\n op.tableName,\n newTable,\n currentTable,\n context\n );\n }\n\n // ===========================================================================\n // DDL GENERATION - Index Operations\n // ===========================================================================\n\n generateCreateIndex(op: CreateIndexOperation, _context: DDLContext): string {\n const { tableName, index } = op;\n\n // Validate index type against capabilities (SQLite only supports btree)\n this.validateIndexType(index.type, index.name);\n\n const unique = index.unique ? \"UNIQUE \" : \"\";\n const cols = index.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n // SQLite has supported partial indexes since 3.8.0. Dropping the predicate\n // silently would build a different index from the declared one, and the\n // differ would re-create it on every push forever, because introspection\n // reads the predicate back.\n const where = index.where ? ` WHERE ${index.where}` : \"\";\n // SQLite doesn't support USING clause - it only has btree indexes\n return `CREATE ${unique}INDEX ${this.escapeIdentifier(index.name)} ON ${this.escapeIdentifier(tableName)} (${cols})${where}`;\n }\n\n generateDropIndex(op: DropIndexOperation, _context: DDLContext): string {\n return `DROP INDEX ${this.escapeIdentifier(op.indexName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Foreign Key Operations (require table recreation)\n // ===========================================================================\n\n generateAddForeignKey(\n op: AddForeignKeyOperation,\n context: DDLContext\n ): string | readonly string[] {\n return this.recreateWith(\n op.tableName,\n context,\n \"add foreign key\",\n (table) => ({\n ...table,\n foreignKeys: [...table.foreignKeys, op.fk],\n })\n );\n }\n\n generateDropForeignKey(\n op: DropForeignKeyOperation,\n context: DDLContext\n ): string | readonly string[] {\n return this.recreateWith(\n op.tableName,\n context,\n \"drop foreign key\",\n (table) => ({\n ...table,\n foreignKeys: table.foreignKeys.filter((fk) => fk.name !== op.fkName),\n })\n );\n }\n\n /**\n * Recreates `tableName` as `change` derives it from the table the batch has\n * left, which is how SQLite changes an inline foreign key, unique or primary\n * key.\n */\n protected recreateWith(\n tableName: string,\n context: DDLContext,\n action: string,\n change: (table: TableDef) => TableDef\n ): string[] {\n const currentTable = this.getCurrentTable(tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot ${action}: table \"${tableName}\" not found in current schema. ` +\n \"Supply the current schema when compiling this operation.\"\n );\n }\n return this.compileTableRecreation(\n tableName,\n change(currentTable),\n currentTable,\n context\n );\n }\n\n // ===========================================================================\n // DDL GENERATION - Unique Constraint Operations\n // ===========================================================================\n\n /**\n * A unique constraint is INLINE in `CREATE TABLE` on SQLite, so both halves\n * of the diff go through a table recreation. There is no other spelling that\n * round-trips.\n *\n * SQLite has two ways to spell \"these columns are unique\" and only one of\n * them survives introspection as a constraint. An inline\n * `CONSTRAINT x UNIQUE (...)` is reported by `PRAGMA index_list` with\n * `origin = \"u\"`, which `introspect` files under `uniqueConstraints` —\n * matched by shape against the declared one (see\n * `introspectionReadsConstraintNames`), so an unchanged schema plans nothing.\n * A standalone `CREATE UNIQUE INDEX` is reported with `origin = \"c\"` and\n * filed under `indexes` instead, where no declared unique constraint will\n * ever match it.\n *\n * Measured on better-sqlite3 at `f78fa83`, with the add as a standalone\n * index: push #2 of a model that gained `.unique([\"slug\", \"tenant\"])`\n * planned `addUniqueConstraint` and created the index; push #3 read that\n * index back under the wrong bucket and planned `addUniqueConstraint` again\n * beside `dropIndex` on the same name — and since `addUniqueConstraint` (14)\n * runs ahead of a superseded index drop (15.5), the push died on\n * `index \"…_slug_tenant_key\" already exists`. Every later push died the same\n * way. Before the shape matching landed the FK churn rebuilt the table on\n * every push and destroyed the index before push #3 could collide with it,\n * so the same schema pushed green forever and the unique was never enforced.\n *\n * The drop had no working spelling at all: every `dropUniqueConstraint` the\n * differ plans here names a constraint read out of `PRAGMA index_list` with\n * `origin = \"u\"`, i.e. `sqlite_autoindex_<table>_<n>`, and SQLite refuses\n * `DROP INDEX` on an index it created itself.\n *\n * A database written by the old add still holds the standalone index. It\n * heals on the next push: the recreation rebuilds the table with the\n * constraint inline, and the stale index — dropped with the old table and\n * re-created by step 6 of the recreation, because it is still in the\n * introspected definition — is removed by the `dropIndex` the same batch\n * plans for it.\n */\n generateAddUniqueConstraint(\n op: AddUniqueConstraintOperation,\n context: DDLContext\n ): readonly string[] {\n return this.recreateWith(\n op.tableName,\n context,\n \"add unique constraint\",\n (table) => ({\n ...table,\n uniqueConstraints: [...table.uniqueConstraints, op.constraint],\n })\n );\n }\n\n generateDropUniqueConstraint(\n op: DropUniqueConstraintOperation,\n context: DDLContext\n ): readonly string[] {\n return this.recreateWith(\n op.tableName,\n context,\n \"drop unique constraint\",\n (table) => ({\n ...table,\n uniqueConstraints: table.uniqueConstraints.filter(\n (constraint) => constraint.name !== op.constraintName\n ),\n })\n );\n }\n\n // ===========================================================================\n // DDL GENERATION - Primary Key Operations (require table recreation)\n // ===========================================================================\n\n generateAddPrimaryKey(\n op: AddPrimaryKeyOperation,\n context: DDLContext\n ): readonly string[] {\n return this.recreateWith(\n op.tableName,\n context,\n \"add primary key\",\n (table) => ({\n ...table,\n primaryKey: op.primaryKey,\n })\n );\n }\n\n generateDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n context: DDLContext\n ): readonly string[] {\n return this.recreateWith(\n op.tableName,\n context,\n \"drop primary key\",\n (table) => ({\n ...table,\n primaryKey: undefined,\n })\n );\n }\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // ===========================================================================\n\n generateCreateEnum(_op: CreateEnumOperation, _context: DDLContext): string {\n // SQLite enums use CHECK constraints embedded in column definitions\n // No separate enum type creation needed\n return \"-- SQLite: enum CHECK constraint is part of column definition\";\n }\n\n generateDropEnum(\n op: DropEnumOperation,\n context: DDLContext\n ): string | readonly string[] {\n // Dropping an enum means removing CHECK constraints from dependent columns\n // This requires table recreation for each dependent table\n const { enumName, dependentColumns } = op;\n\n if (!dependentColumns || dependentColumns.length === 0) {\n return `-- SQLite: no dependent columns for enum \"${enumName}\"`;\n }\n\n const statements: string[] = [];\n\n for (const dep of dependentColumns) {\n const currentTable = this.getCurrentTable(dep.tableName, context);\n if (!currentTable) {\n throw new MigrationError(\n `Table \"${dep.tableName}\" not found for enum \"${enumName}\"`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n\n // Change the column type to plain TEXT (remove CHECK constraint)\n const newColumns = currentTable.columns.map((col) => {\n if (col.name === dep.columnName && col.type.includes(\"CHECK\")) {\n return { ...col, type: \"TEXT\" };\n }\n return col;\n });\n\n const newTable: TableDef = { ...currentTable, columns: newColumns };\n statements.push(\n ...this.compileTableRecreation(\n dep.tableName,\n newTable,\n currentTable,\n context\n )\n );\n }\n\n return statements;\n }\n\n generateAlterEnum(\n op: AlterEnumOperation,\n context: DDLContext\n ): string | readonly string[] {\n // Altering an enum means updating CHECK constraints on dependent columns\n // This requires table recreation for each dependent column\n const { enumName, newValues, dependentColumns } = op;\n const statements: string[] = [];\n\n if (!newValues || newValues.length === 0) {\n return `-- SQLite: no new values provided for enum \"${enumName}\"`;\n }\n\n if (!dependentColumns || dependentColumns.length === 0) {\n return `-- SQLite: no dependent columns found for enum \"${enumName}\"`;\n }\n\n // Apply mappings in the reconstruction SELECT. A replacement belongs to\n // the destination CHECK, including a value introduced in this change.\n\n // Generate new CHECK constraint\n const escapedValues = newValues\n .map((v) => `'${v.replace(/'/g, \"''\")}'`)\n .join(\", \");\n\n for (const dep of dependentColumns) {\n const currentTable = this.getCurrentTable(dep.tableName, context);\n if (!currentTable) {\n statements.push(`-- SQLite: table \"${dep.tableName}\" not found`);\n continue;\n }\n\n // Build new CHECK constraint for this column\n const newCheckType = `TEXT CHECK(${this.escapeIdentifier(dep.columnName)} IN (${escapedValues}))`;\n\n // Update the column type with new CHECK\n const newColumns = currentTable.columns.map((col) => {\n if (col.name === dep.columnName) {\n return { ...col, type: newCheckType };\n }\n return col;\n });\n\n const newTable: TableDef = { ...currentTable, columns: newColumns };\n const source = this.escapeIdentifier(dep.columnName);\n const cases = this.enumReplacementCases(\n op,\n dep.tableName,\n dep.columnName\n );\n const expressions =\n cases.length === 0\n ? undefined\n : new Map([\n [\n dep.columnName,\n `CASE ${source} ${cases.join(\" \")} ELSE ${source} END`,\n ],\n ]);\n statements.push(\n ...this.compileTableRecreation(\n dep.tableName,\n newTable,\n currentTable,\n context,\n undefined,\n expressions\n )\n );\n }\n\n return statements;\n }\n\n // ===========================================================================\n // MIGRATION LOCKING\n // ===========================================================================\n\n generateAcquireLock(_lockId: number): string | null {\n // SQLite uses file-based locking via transactions\n // Return null to signal that locking is handled differently\n return null;\n }\n\n generateReleaseLock(_lockId: number): string | null {\n // SQLite uses file-based locking via transactions\n return null;\n }\n\n // ===========================================================================\n // SCHEMA INTROSPECTION HELPERS\n // ===========================================================================\n\n generateInventoryTables(): { sql: string; params: unknown[] } {\n return {\n sql: \"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name\",\n params: [],\n };\n }\n\n generateInventoryEnums(): { sql: string; params: unknown[] } | null {\n // SQLite doesn't support enums\n return null;\n }\n}\n\n// Export singleton instance\nexport const sqlite3MigrationDriver = new SQLite3MigrationDriver();\n","/**\n * LibSQL Migration Driver\n *\n * Extends SQLite3 driver with native ALTER COLUMN support.\n * LibSQL supports ALTER TABLE ALTER COLUMN syntax that SQLite doesn't,\n * avoiding expensive table recreation for column modifications.\n *\n * CAVEAT: LibSQL's ALTER COLUMN only validates newly inserted/updated rows,\n * NOT existing data. This differs from PostgreSQL's behavior where constraints\n * are validated against all existing rows.\n */\n\nimport { sqliteDateTimeTargetRequiresRecreation } from \"../../../adapters/databases/sqlite/storage/datetime\";\nimport { sqliteDecimalCheck } from \"../../../adapters/databases/sqlite/storage/decimal\";\nimport {\n SQLITE_GEO_POINT_TYPE,\n sqliteGeoPointCheck,\n sqliteGeoPointEncoding,\n} from \"../../../adapters/databases/sqlite/storage/geo-point\";\nimport {\n decimalConversionRequired,\n sqliteDecimalStorageKind,\n} from \"../../decimal\";\nimport type { ColumnDef, ReferentialAction } from \"../../types\";\nimport type {\n AddForeignKeyOperation,\n AlterColumnOperation,\n DDLContext,\n DropForeignKeyOperation,\n} from \"../base\";\nimport { SQLite3MigrationDriver } from \"../sqlite\";\nimport type { MigrationCapabilities } from \"../types\";\n\nexport class LibSQLMigrationDriver extends SQLite3MigrationDriver {\n override readonly driverName: string = \"libsql\";\n\n // Same capabilities as SQLite3 (no native enums, no arrays, btree only)\n override readonly capabilities: MigrationCapabilities = {\n supportsNativeEnums: false,\n supportsAddEnumValueInTransaction: true,\n supportsIndexTypes: [\"btree\"],\n supportsNativeArrays: false,\n // Adds FKs by rewriting the column (`ALTER COLUMN ... TO`), which needs the\n // existing column def — not a standalone add. Keep FKs inline in CREATE\n // TABLE and rely on lazy reference resolution (forward refs are fine).\n supportsAddForeignKeyViaAlter: false,\n // Inherits SQLite's introspection verbatim, so the same two names are\n // unreadable here.\n introspectionReadsConstraintNames: false,\n };\n\n // ===========================================================================\n // LIBSQL-SPECIFIC: ALTER COLUMN (native support)\n // ===========================================================================\n\n /**\n * LibSQL supports ALTER TABLE ... ALTER COLUMN ... TO syntax.\n * This avoids table recreation for column type/default/nullable changes.\n *\n * Syntax: ALTER TABLE t ALTER COLUMN c TO c <new_column_def>\n *\n * CAVEAT: LibSQL's ALTER COLUMN only validates newly inserted/updated rows,\n * NOT existing data. This is different from PostgreSQL's behavior.\n */\n override generateAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): string | readonly string[] {\n // A decimal descriptor change CONVERTS stored values — SQLite holds the\n // unscaled coefficient, so the same integer means a different number at a\n // different scale. The native ALTER rewrites the column DECLARATION and\n // copies nothing, and by LibSQL's own contract (above) it validates only\n // rows written afterwards, so every existing row would keep its old\n // coefficient under the new domain and read back wrong. Table recreation\n // is the only route that carries the values across; §9.6 states it as a\n // falsifier (\"LibSQL cannot take a native ALTER route that skips\n // conversion\").\n if (\n decimalConversionRequired(op.from, op.to) ||\n sqliteDateTimeTargetRequiresRecreation(op.from.dateTime, op.to.dateTime)\n ) {\n return this.compileAlterColumnByRecreation(op, context, false);\n }\n\n const { tableName, columnName, to } = op;\n const table = this.escapeIdentifier(tableName);\n const col = this.escapeIdentifier(columnName);\n\n // Build new column definition\n const colDef = this.generateColumnDef(to, context);\n\n // LibSQL syntax: ALTER TABLE t ALTER COLUMN old_name TO new_def\n return `ALTER TABLE ${table} ALTER COLUMN ${col} TO ${colDef}`;\n }\n\n // ===========================================================================\n // LIBSQL-SPECIFIC: FOREIGN KEYS (native support via ALTER COLUMN)\n // ===========================================================================\n\n // ===========================================================================\n // HELPER: Build column definition with optional REFERENCES\n // ===========================================================================\n\n /**\n * Builds a column definition string with optional foreign key REFERENCES clause.\n * Used for LibSQL's ALTER COLUMN TO syntax.\n */\n private buildColumnDefWithReferences(\n column: ColumnDef,\n fkRef?: {\n refTable: string;\n refCol: string;\n onDelete?: ReferentialAction;\n onUpdate?: ReferentialAction;\n }\n ): string {\n const parts: string[] = [this.escapeIdentifier(column.name), column.type];\n\n if (!column.nullable) {\n parts.push(\"NOT NULL\");\n }\n\n if (column.default !== undefined) {\n parts.push(`DEFAULT ${column.default}`);\n }\n\n if (column.type.toUpperCase() === SQLITE_GEO_POINT_TYPE) {\n parts.push(\n sqliteGeoPointCheck(\n column,\n (name) => this.escapeIdentifier(name),\n sqliteGeoPointEncoding(column)\n )\n );\n }\n\n // The reserved decimal CHECK travels with the rewritten declaration.\n // `ALTER COLUMN ... TO` replaces the WHOLE column definition, so a\n // constraint this rebuild left out would be gone from the stored\n // `CREATE TABLE` — and with it the only carrier of the column's declared\n // domain, which introspection would then read as a descriptor change on\n // every push afterwards.\n const kind = sqliteDecimalStorageKind(column);\n if (column.decimal && kind) {\n parts.push(\n sqliteDecimalCheck(column, column.decimal, kind, (name) =>\n this.escapeIdentifier(name)\n )\n );\n }\n\n if (fkRef) {\n parts.push(\n `REFERENCES ${this.escapeIdentifier(fkRef.refTable)}(${this.escapeIdentifier(fkRef.refCol)})`\n );\n if (fkRef.onDelete && fkRef.onDelete !== \"noAction\") {\n parts.push(`ON DELETE ${this.formatReferentialAction(fkRef.onDelete)}`);\n }\n if (fkRef.onUpdate && fkRef.onUpdate !== \"noAction\") {\n parts.push(`ON UPDATE ${this.formatReferentialAction(fkRef.onUpdate)}`);\n }\n }\n\n return parts.join(\" \");\n }\n\n // ===========================================================================\n // LIBSQL-SPECIFIC: FOREIGN KEYS (native support via ALTER COLUMN)\n // ===========================================================================\n\n /**\n * LibSQL can add foreign keys by redefining the column with REFERENCES.\n * This avoids table recreation for single-column foreign keys.\n *\n * Note: Multi-column FKs still require table recreation.\n */\n override generateAddForeignKey(\n op: AddForeignKeyOperation,\n context: DDLContext\n ): string | readonly string[] {\n const { tableName, fk } = op;\n\n // For multi-column FKs, fall back to table recreation\n if (fk.columns.length > 1) {\n return super.generateAddForeignKey(op, context);\n }\n\n // Validate columns exist FIRST (before any array access)\n const fkColumn = fk.columns[0];\n const refColumn = fk.referencedColumns[0];\n if (!(fkColumn && refColumn)) {\n throw new Error(\n `Invalid foreign key: columns array is empty for table \"${tableName}\".`\n );\n }\n\n const currentTable = this.getCurrentTable(tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot add foreign key: table \"${tableName}\" not found in current schema. ` +\n \"Pass currentSchema in DDLContext.\"\n );\n }\n\n // Find the column to alter\n const column = currentTable.columns.find((c) => c.name === fkColumn);\n if (!column) {\n throw new Error(\n `Cannot add foreign key: column \"${fkColumn}\" not found in table \"${tableName}\".`\n );\n }\n\n const table = this.escapeIdentifier(tableName);\n const col = this.escapeIdentifier(fkColumn);\n\n // Build column definition with REFERENCES using helper\n const colDef = this.buildColumnDefWithReferences(column, {\n refTable: fk.referencedTable,\n refCol: refColumn,\n onDelete: fk.onDelete,\n onUpdate: fk.onUpdate,\n });\n\n return `ALTER TABLE ${table} ALTER COLUMN ${col} TO ${colDef}`;\n }\n\n /**\n * LibSQL can drop foreign keys by redefining the column without REFERENCES.\n * This avoids table recreation for single-column foreign keys.\n */\n override generateDropForeignKey(\n op: DropForeignKeyOperation,\n context: DDLContext\n ): string | readonly string[] {\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot drop foreign key: table \"${op.tableName}\" not found in current schema. ` +\n \"Supply the current schema when compiling this operation.\"\n );\n }\n\n // Find the FK to drop\n const fk = currentTable.foreignKeys.find((f) => f.name === op.fkName);\n if (!fk) {\n throw new Error(\n `Cannot drop foreign key: constraint \"${op.fkName}\" not found in table \"${op.tableName}\".`\n );\n }\n\n // For multi-column FKs, fall back to table recreation\n if (fk.columns.length > 1) {\n return super.generateDropForeignKey(op, context);\n }\n\n const fkColumn = fk.columns[0];\n if (!fkColumn) {\n throw new Error(\n `Invalid foreign key: columns array is empty for constraint \"${op.fkName}\".`\n );\n }\n\n // Find the column\n const column = currentTable.columns.find((c) => c.name === fkColumn);\n if (!column) {\n throw new Error(\n `Cannot drop foreign key: column \"${fkColumn}\" not found in table \"${op.tableName}\".`\n );\n }\n\n const table = this.escapeIdentifier(op.tableName);\n const col = this.escapeIdentifier(fkColumn);\n\n // Rebuild column definition WITHOUT REFERENCES using helper\n const colDef = this.buildColumnDefWithReferences(column);\n\n return `ALTER TABLE ${table} ALTER COLUMN ${col} TO ${colDef}`;\n }\n\n // ===========================================================================\n // PRIMARY KEY OPERATIONS\n // LibSQL still requires table recreation for PK changes\n // ===========================================================================\n\n // generateAddPrimaryKey and generateDropPrimaryKey inherit from SQLite3\n // which uses table recreation. LibSQL does not support native PK modifications.\n}\n\n// Export singleton instance\nexport const libsqlMigrationDriver = new LibSQLMigrationDriver();\n"],"mappings":"8qBA2CA,SAAS,iBA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