viborm 1.12.0 → 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-BPr1CKHw.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-Db-sVg93.mjs +0 -2
- package/dist/client-Db-sVg93.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-BPr1CKHw.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,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./model-
|
|
2
|
-
//# sourceMappingURL=keys-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./model-DK9BhhNF.mjs";const n=new WeakMap;function getModelKeyCatalog(e){let t=n.get(e);if(t)return t;let r=buildModelKeyCatalog(e);return n.set(e,r),r}function findAddressableKey(e,t){for(let n of getModelKeyCatalog(e).addressableKeys)if((n.name??n.fields[0])===t)return n}const r=[`AND`,`OR`,`NOT`];function getAmbiguousPublicSelectorNames(e){let t=e[`~`].state,n=new Set([...Object.keys(t.shape),...r]),i=new Set,a=[...Object.keys(t.compoundId??{}),...Object.keys(t.compoundUniques??{})];for(let e of a)n.has(e)&&i.add(e),n.add(e);return[...i]}function findReferenceableKey(e,t){let n;for(let r of getModelKeyCatalog(e).referenceableKeys)if(!(r.length!==t.length||!r.every(e=>t.includes(e)))){if(r.every((e,n)=>e===t[n]))return r;n??=r}return n}function buildModelKeyCatalog(e){let n=e[`~`].state,r=[],i;for(let e of Object.keys(n.uniques)){let t=n.scalars[e]?.[`~`].state.isId===!0,a=t?{kind:`primary`,fields:[e]}:{kind:`unique`,fields:[e]};t&&!i&&(i=a),r.push(a)}let a=n.compoundId??{},o,s=!0;for(let[e,t]of Object.entries(a)){let n={kind:`primary`,name:e,fields:Object.keys(t.entries)};s&&(s=!1,e&&n.fields.length>0&&(o=n)),r.push(n)}let c=n.compoundUniques??{};for(let[e,t]of Object.entries(c))r.push({kind:`compoundUnique`,name:e,fields:Object.keys(t.entries)});let l=new Set(Object.keys(n.uniques));for(let e of Object.values(a))for(let t of Object.keys(e.entries))l.add(t);for(let e of Object.values(c))for(let t of Object.keys(e.entries))l.add(t);let u=[...r.map(e=>e.fields),...n.indexes.filter(e=>e.options.unique&&t(e.options)).map(e=>e.fields)];return{rowKey:o??i,addressableKeys:r,referenceableKeys:u,uniqueOverlapFields:[...l]}}export{getModelKeyCatalog as i,findReferenceableKey as n,getAmbiguousPublicSelectorNames as r,findAddressableKey as t};
|
|
2
|
+
//# sourceMappingURL=keys-BcQgRjMB.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keys-CyfjT6uC.mjs","names":[],"sources":["../src/schema/model/keys.ts"],"sourcesContent":["/**\n * The ordered model-key catalog — the one owner of how a row can be addressed.\n *\n * A model's key facts have exactly three shapes, and this module stores each\n * once, grouped and ordered, in TS-field-name space:\n *\n * - `rowKey` — the complete primary key in constraint order (the array given to\n * `.id([...])`, or the one `.id()` scalar). Optional: a model may declare no\n * primary key.\n * - `addressableKeys` — the exact keys a public unique selector can name. A key\n * with a `name` is a grouped constraint whose selector is that name and whose\n * value is an object of members (`where: { region_slug: { region, slug } }`);\n * a key without one is a bare scalar selector (`where: { email }`). That\n * spelling difference is a real addressing fact — `.id([\"a\"])` and a scalar\n * `.id()` on `a` accept different selectors — so it is stored, not inferred.\n * - `referenceableKeys` — every complete ordered key a foreign key may target:\n * the addressable keys above plus total unique indexes. This is deliberately\n * wider than the public selector grammar and is the one physical-key catalog\n * consumed by schema validation and relation topology.\n * - `uniqueOverlapFields` — the conservative flattened view, used only to ask\n * whether two selectors MAY overlap. Never a substitute for a grouped key.\n *\n * Public addressability and physical referenceability remain distinct views:\n * a foreign key may target a total unique INDEX no selector can address.\n *\n * A second deliberate survivor: the validation whereUnique factories\n * (`validation/model/core/filter.ts` / `where.ts`) keep reading the constraint\n * slots directly, because they need the member `VibSchema` VALUES to build the\n * parser and its inferred type — something a field-name catalog structurally\n * cannot supply. That is the preserved type/runtime-projection distinction,\n * not a missed migration.\n *\n * The catalog's arrays are cached for the model's lifetime and handed out\n * uncopied; every consumer treats them as the `readonly` types say. A consumer\n * that needs to mutate must copy first, as `getPrimaryKeyFields` does.\n *\n * Field-name space only: hydration binds column names after model construction,\n * so caching resolved columns here would freeze pre-hydration names. Every\n * column resolution is a downstream projection through `getColumnName`.\n */\n\nimport { isTotalIndex, type Model } from \"./model\";\n\nexport interface OrderedModelKey {\n // No \"uniqueIndex\" kind, deliberately departing from the plan's §4.1 sketch:\n // an index is never addressable, and an inhabited kind for it would invite\n // someone to push index-derived keys into `addressableKeys`, silently making\n // `where: { <indexed column> }` a unique discriminator.\n readonly kind: \"primary\" | \"unique\" | \"compoundUnique\";\n /**\n * The grouped-constraint selector name. Present exactly when the public\n * selector is the constraint name wrapping an object of members; absent for\n * a bare single-scalar selector.\n */\n readonly name?: string;\n /** Ordered members. Compound keys stay grouped; never flatten them. */\n readonly fields: readonly string[];\n}\n\nexport interface ModelKeyCatalog {\n readonly rowKey?: OrderedModelKey;\n readonly addressableKeys: readonly OrderedModelKey[];\n readonly referenceableKeys: readonly (readonly string[])[];\n readonly uniqueOverlapFields: readonly string[];\n}\n\n/**\n * One catalog per model instance. Models are immutable after construction\n * except name hydration, which binds COLUMN names only — key membership and\n * order never change, and the catalog stores no columns.\n */\nconst catalogCache = new WeakMap<object, ModelKeyCatalog>();\n\nexport function getModelKeyCatalog(model: Model<any>): ModelKeyCatalog {\n const cached = catalogCache.get(model);\n if (cached) {\n return cached;\n }\n const catalog = buildModelKeyCatalog(model);\n catalogCache.set(model, catalog);\n return catalog;\n}\n\n/**\n * Resolve one public unique-selector key to its addressable key.\n *\n * Definition validation guarantees that one model-local public selector name\n * identifies at most one key. The catalog therefore resolves one exact match;\n * it does not own a scalar/compound or primary/unique precedence policy.\n */\nexport function findAddressableKey(\n model: Model<any>,\n selectorKey: string\n): OrderedModelKey | undefined {\n for (const key of getModelKeyCatalog(model).addressableKeys) {\n const selector = key.name ?? key.fields[0];\n if (selector === selectorKey) {\n return key;\n }\n }\n return undefined;\n}\n\nconst LOGICAL_FILTER_NAMES = [\"AND\", \"OR\", \"NOT\"] as const;\n\n/**\n * Find compound selectors that collide in the actual public unique-where\n * namespace. Extended unique selectors merge every model field and the three\n * logical filters with compound discriminators, so those names are occupied\n * before compound IDs and uniques are added. The namespace is model-local and\n * stays in TypeScript/query spelling; mapped columns and physical constraint\n * names are separate adapter/driver facts.\n */\nexport function getAmbiguousPublicSelectorNames(\n model: Model<any>\n): readonly string[] {\n const state = model[\"~\"].state;\n const occupied = new Set<string>([\n ...Object.keys(state.shape),\n ...LOGICAL_FILTER_NAMES,\n ]);\n const ambiguous = new Set<string>();\n const compoundNames = [\n ...Object.keys(state.compoundId ?? {}),\n ...Object.keys(state.compoundUniques ?? {}),\n ];\n for (const name of compoundNames) {\n if (occupied.has(name)) ambiguous.add(name);\n occupied.add(name);\n }\n return [...ambiguous];\n}\n\n/**\n * Resolve one complete referenced tuple to the target key's own order.\n *\n * Membership is order-insensitive, but the answer is ordered because MySQL\n * requires composite referenced columns to follow an index left-prefix. An\n * exactly-spelled key wins; otherwise catalog order supplies the stable answer.\n */\nexport function findReferenceableKey(\n model: Model<any>,\n fields: readonly string[]\n): readonly string[] | undefined {\n let setMatch: readonly string[] | undefined;\n for (const candidate of getModelKeyCatalog(model).referenceableKeys) {\n if (\n candidate.length !== fields.length ||\n !candidate.every((field) => fields.includes(field))\n ) {\n continue;\n }\n if (candidate.every((field, position) => field === fields[position])) {\n return candidate;\n }\n setMatch ??= candidate;\n }\n return setMatch;\n}\n\nfunction buildModelKeyCatalog(model: Model<any>): ModelKeyCatalog {\n const state = model[\"~\"].state;\n const addressableKeys: OrderedModelKey[] = [];\n\n // Bare scalar selectors, in shape-declaration order. `state.uniques` carries\n // `.id()` scalars beside `.unique()` ones (`extractUniqueScalarMap` keys on\n // `isUnique || isId`), so the scalar primary key is addressable here too.\n let scalarRowKey: OrderedModelKey | undefined;\n for (const field of Object.keys(state.uniques)) {\n const isId = state.scalars[field]?.[\"~\"].state.isId === true;\n const key: OrderedModelKey = isId\n ? { kind: \"primary\", fields: [field] }\n : { kind: \"unique\", fields: [field] };\n if (isId && !scalarRowKey) {\n scalarRowKey = key;\n }\n addressableKeys.push(key);\n }\n\n // EVERY declared compound-id constraint is addressable by its name — the\n // selector grammar has always resolved any of them (a second `.id([...])` is\n // representable; F002 refuses it at PUSH time only, never at `createClient`),\n // and empty ones stay addressable so their established \"must include at least\n // one field\" refusal keeps firing. The ROW key below is narrower: first\n // non-empty constraint only.\n const compoundIds: Record<string, { entries: Record<string, unknown> }> =\n state.compoundId ?? {};\n let compoundRowKey: OrderedModelKey | undefined;\n let firstCompoundId = true;\n for (const [name, constraint] of Object.entries(compoundIds)) {\n const key: OrderedModelKey = {\n kind: \"primary\",\n name,\n fields: Object.keys(constraint.entries),\n };\n // The row key is the FIRST declared constraint only, and only when it has a\n // name and members — a later non-empty constraint does not promote, exactly\n // as `getCompoundIdConstraint` has always read the record.\n if (firstCompoundId) {\n firstCompoundId = false;\n if (name && key.fields.length > 0) {\n compoundRowKey = key;\n }\n }\n addressableKeys.push(key);\n }\n\n // Named compound uniques, in declaration order.\n const compoundUniques: Record<string, { entries: Record<string, unknown> }> =\n state.compoundUniques ?? {};\n for (const [name, constraint] of Object.entries(compoundUniques)) {\n addressableKeys.push({\n kind: \"compoundUnique\",\n name,\n fields: Object.keys(constraint.entries),\n });\n }\n\n // The conservative flattened overlap view, in its established construction\n // order: scalar unique/id fields, then every compound-id member, then every\n // compound-unique member.\n const overlap = new Set<string>(Object.keys(state.uniques));\n for (const constraint of Object.values(compoundIds)) {\n for (const field of Object.keys(constraint.entries)) {\n overlap.add(field);\n }\n }\n for (const constraint of Object.values(compoundUniques)) {\n for (const field of Object.keys(constraint.entries)) {\n overlap.add(field);\n }\n }\n\n const referenceableKeys: readonly (readonly string[])[] = [\n ...addressableKeys.map((key) => key.fields),\n ...state.indexes\n .filter((index) => index.options.unique && isTotalIndex(index.options))\n .map((index) => index.fields),\n ];\n\n return {\n // The row key prefers the compound constraint: `getPrimaryKeyFields` has\n // always answered compound-first, and the projection contract pins that\n // reading (`target-projection.core.test.ts`, \"schema order is the KEY's\n // order\"). A model spelling both is refused by F002 at PUSH time only —\n // `createClient` never runs that rule — so the cursor deliberately keeps\n // its own scalar-first projection (`getCursorIdentityFields`).\n rowKey: compoundRowKey ?? scalarRowKey,\n addressableKeys,\n referenceableKeys,\n uniqueOverlapFields: [...overlap],\n };\n}\n"],"mappings":"kFAuEA,MAAM,EAAe,IAAI,QAEzB,SAAgB,mBAAmB,EAAoC,CACrE,IAAM,EAAS,EAAa,IAAI,EAAM,CACtC,GAAI,EACF,OAAO,EAET,IAAM,EAAU,qBAAqB,EAAM,CAE3C,OADA,EAAa,IAAI,EAAO,EAAQ,CACzB,EAUT,SAAgB,mBACd,EACA,EAC6B,CAC7B,IAAK,IAAM,KAAO,mBAAmB,EAAM,CAAC,gBAE1C,IADiB,EAAI,MAAQ,EAAI,OAAO,MACvB,EACf,OAAO,EAMb,MAAM,EAAuB,CAAC,MAAO,KAAM,MAAM,CAUjD,SAAgB,gCACd,EACmB,CACnB,IAAM,EAAQ,EAAM,KAAK,MACnB,EAAW,IAAI,IAAY,CAC/B,GAAG,OAAO,KAAK,EAAM,MAAM,CAC3B,GAAG,EACJ,CAAC,CACI,EAAY,IAAI,IAChB,EAAgB,CACpB,GAAG,OAAO,KAAK,EAAM,YAAc,EAAE,CAAC,CACtC,GAAG,OAAO,KAAK,EAAM,iBAAmB,EAAE,CAAC,CAC5C,CACD,IAAK,IAAM,KAAQ,EACb,EAAS,IAAI,EAAK,EAAE,EAAU,IAAI,EAAK,CAC3C,EAAS,IAAI,EAAK,CAEpB,MAAO,CAAC,GAAG,EAAU,CAUvB,SAAgB,qBACd,EACA,EAC+B,CAC/B,IAAI,EACJ,IAAK,IAAM,KAAa,mBAAmB,EAAM,CAAC,kBAE9C,OAAU,SAAW,EAAO,QAC5B,CAAC,EAAU,MAAO,GAAU,EAAO,SAAS,EAAM,CAAC,EAIrD,IAAI,EAAU,OAAO,EAAO,IAAa,IAAU,EAAO,GAAU,CAClE,OAAO,EAET,IAAa,EAEf,OAAO,EAGT,SAAS,qBAAqB,EAAoC,CAChE,IAAM,EAAQ,EA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C,CACtE,IAAK,GAAU,EAAM,OAAO,CAChC,CAED,MAAO,CAOL,OAAQ,GAAkB,EAC1B,kBACA,oBACA,oBAAqB,CAAC,GAAG,EAAQ,CAClC"}
|
|
1
|
+
{"version":3,"file":"keys-BcQgRjMB.mjs","names":[],"sources":["../src/schema/model/keys.ts"],"sourcesContent":["/**\n * The ordered model-key catalog — the one owner of how a row can be addressed.\n *\n * A model's key facts have exactly three shapes, and this module stores each\n * once, grouped and ordered, in TS-field-name space:\n *\n * - `rowKey` — the complete primary key in constraint order (the array given to\n * `.id([...])`, or the one `.id()` scalar). Optional: a model may declare no\n * primary key.\n * - `addressableKeys` — the exact keys a public unique selector can name. A key\n * with a `name` is a grouped constraint whose selector is that name and whose\n * value is an object of members (`where: { region_slug: { region, slug } }`);\n * a key without one is a bare scalar selector (`where: { email }`). That\n * spelling difference is a real addressing fact — `.id([\"a\"])` and a scalar\n * `.id()` on `a` accept different selectors — so it is stored, not inferred.\n * - `referenceableKeys` — every complete ordered key a foreign key may target:\n * the addressable keys above plus total unique indexes. This is deliberately\n * wider than the public selector grammar and is the one physical-key catalog\n * consumed by schema validation and relation topology.\n * - `uniqueOverlapFields` — the conservative flattened view, used only to ask\n * whether two selectors MAY overlap. Never a substitute for a grouped key.\n *\n * Public addressability and physical referenceability remain distinct views:\n * a foreign key may target a total unique INDEX no selector can address.\n *\n * A second deliberate survivor: the validation whereUnique factories\n * (`validation/model/core/filter.ts` / `where.ts`) keep reading the constraint\n * slots directly, because they need the member `VibSchema` VALUES to build the\n * parser and its inferred type — something a field-name catalog structurally\n * cannot supply. That is the preserved type/runtime-projection distinction,\n * not a missed migration.\n *\n * The catalog's arrays are cached for the model's lifetime and handed out\n * uncopied; every consumer treats them as the `readonly` types say. A consumer\n * that needs to mutate must copy first, as `getPrimaryKeyFields` does.\n *\n * Field-name space only: hydration binds column names after model construction,\n * so caching resolved columns here would freeze pre-hydration names. Every\n * column resolution is a downstream projection through `getColumnName`.\n */\n\nimport { isTotalIndex, type Model } from \"./model\";\n\nexport interface OrderedModelKey {\n // No \"uniqueIndex\" kind, deliberately departing from the plan's §4.1 sketch:\n // an index is never addressable, and an inhabited kind for it would invite\n // someone to push index-derived keys into `addressableKeys`, silently making\n // `where: { <indexed column> }` a unique discriminator.\n readonly kind: \"primary\" | \"unique\" | \"compoundUnique\";\n /**\n * The grouped-constraint selector name. Present exactly when the public\n * selector is the constraint name wrapping an object of members; absent for\n * a bare single-scalar selector.\n */\n readonly name?: string;\n /** Ordered members. Compound keys stay grouped; never flatten them. */\n readonly fields: readonly string[];\n}\n\nexport interface ModelKeyCatalog {\n readonly rowKey?: OrderedModelKey;\n readonly addressableKeys: readonly OrderedModelKey[];\n readonly referenceableKeys: readonly (readonly string[])[];\n readonly uniqueOverlapFields: readonly string[];\n}\n\n/**\n * One catalog per model instance. Models are immutable after construction\n * except name hydration, which binds COLUMN names only — key membership and\n * order never change, and the catalog stores no columns.\n */\nconst catalogCache = new WeakMap<object, ModelKeyCatalog>();\n\nexport function getModelKeyCatalog(model: Model<any>): ModelKeyCatalog {\n const cached = catalogCache.get(model);\n if (cached) {\n return cached;\n }\n const catalog = buildModelKeyCatalog(model);\n catalogCache.set(model, catalog);\n return catalog;\n}\n\n/**\n * Resolve one public unique-selector key to its addressable key.\n *\n * Definition validation guarantees that one model-local public selector name\n * identifies at most one key. The catalog therefore resolves one exact match;\n * it does not own a scalar/compound or primary/unique precedence policy.\n */\nexport function findAddressableKey(\n model: Model<any>,\n selectorKey: string\n): OrderedModelKey | undefined {\n for (const key of getModelKeyCatalog(model).addressableKeys) {\n const selector = key.name ?? key.fields[0];\n if (selector === selectorKey) {\n return key;\n }\n }\n return undefined;\n}\n\nconst LOGICAL_FILTER_NAMES = [\"AND\", \"OR\", \"NOT\"] as const;\n\n/**\n * Find compound selectors that collide in the actual public unique-where\n * namespace. Extended unique selectors merge every model field and the three\n * logical filters with compound discriminators, so those names are occupied\n * before compound IDs and uniques are added. The namespace is model-local and\n * stays in TypeScript/query spelling; mapped columns and physical constraint\n * names are separate adapter/driver facts.\n */\nexport function getAmbiguousPublicSelectorNames(\n model: Model<any>\n): readonly string[] {\n const state = model[\"~\"].state;\n const occupied = new Set<string>([\n ...Object.keys(state.shape),\n ...LOGICAL_FILTER_NAMES,\n ]);\n const ambiguous = new Set<string>();\n const compoundNames = [\n ...Object.keys(state.compoundId ?? {}),\n ...Object.keys(state.compoundUniques ?? {}),\n ];\n for (const name of compoundNames) {\n if (occupied.has(name)) ambiguous.add(name);\n occupied.add(name);\n }\n return [...ambiguous];\n}\n\n/**\n * Resolve one complete referenced tuple to the target key's own order.\n *\n * Membership is order-insensitive, but the answer is ordered because MySQL\n * requires composite referenced columns to follow an index left-prefix. An\n * exactly-spelled key wins; otherwise catalog order supplies the stable answer.\n */\nexport function findReferenceableKey(\n model: Model<any>,\n fields: readonly string[]\n): readonly string[] | undefined {\n let setMatch: readonly string[] | undefined;\n for (const candidate of getModelKeyCatalog(model).referenceableKeys) {\n if (\n candidate.length !== fields.length ||\n !candidate.every((field) => fields.includes(field))\n ) {\n continue;\n }\n if (candidate.every((field, position) => field === fields[position])) {\n return candidate;\n }\n setMatch ??= candidate;\n }\n return setMatch;\n}\n\nfunction buildModelKeyCatalog(model: Model<any>): ModelKeyCatalog {\n const state = model[\"~\"].state;\n const addressableKeys: OrderedModelKey[] = [];\n\n // Bare scalar selectors, in shape-declaration order. `state.uniques` carries\n // `.id()` scalars beside `.unique()` ones (`extractUniqueScalarMap` keys on\n // `isUnique || isId`), so the scalar primary key is addressable here too.\n let scalarRowKey: OrderedModelKey | undefined;\n for (const field of Object.keys(state.uniques)) {\n const isId = state.scalars[field]?.[\"~\"].state.isId === true;\n const key: OrderedModelKey = isId\n ? { kind: \"primary\", fields: [field] }\n : { kind: \"unique\", fields: [field] };\n if (isId && !scalarRowKey) {\n scalarRowKey = key;\n }\n addressableKeys.push(key);\n }\n\n // EVERY declared compound-id constraint is addressable by its name — the\n // selector grammar has always resolved any of them (a second `.id([...])` is\n // representable; F002 refuses it at PUSH time only, never at `createClient`),\n // and empty ones stay addressable so their established \"must include at least\n // one field\" refusal keeps firing. The ROW key below is narrower: first\n // non-empty constraint only.\n const compoundIds: Record<string, { entries: Record<string, unknown> }> =\n state.compoundId ?? {};\n let compoundRowKey: OrderedModelKey | undefined;\n let firstCompoundId = true;\n for (const [name, constraint] of Object.entries(compoundIds)) {\n const key: OrderedModelKey = {\n kind: \"primary\",\n name,\n fields: Object.keys(constraint.entries),\n };\n // The row key is the FIRST declared constraint only, and only when it has a\n // name and members — a later non-empty constraint does not promote, exactly\n // as `getCompoundIdConstraint` has always read the record.\n if (firstCompoundId) {\n firstCompoundId = false;\n if (name && key.fields.length > 0) {\n compoundRowKey = key;\n }\n }\n addressableKeys.push(key);\n }\n\n // Named compound uniques, in declaration order.\n const compoundUniques: Record<string, { entries: Record<string, unknown> }> =\n state.compoundUniques ?? {};\n for (const [name, constraint] of Object.entries(compoundUniques)) {\n addressableKeys.push({\n kind: \"compoundUnique\",\n name,\n fields: Object.keys(constraint.entries),\n });\n }\n\n // The conservative flattened overlap view, in its established construction\n // order: scalar unique/id fields, then every compound-id member, then every\n // compound-unique member.\n const overlap = new Set<string>(Object.keys(state.uniques));\n for (const constraint of Object.values(compoundIds)) {\n for (const field of Object.keys(constraint.entries)) {\n overlap.add(field);\n }\n }\n for (const constraint of Object.values(compoundUniques)) {\n for (const field of Object.keys(constraint.entries)) {\n overlap.add(field);\n }\n }\n\n const referenceableKeys: readonly (readonly string[])[] = [\n ...addressableKeys.map((key) => key.fields),\n ...state.indexes\n .filter((index) => index.options.unique && isTotalIndex(index.options))\n .map((index) => index.fields),\n ];\n\n return {\n // The row key prefers the compound constraint: `getPrimaryKeyFields` has\n // always answered compound-first, and the projection contract pins that\n // reading (`target-projection.core.test.ts`, \"schema order is the KEY's\n // order\"). A model spelling both is refused by F002 at PUSH time only —\n // `createClient` never runs that rule — so the cursor deliberately keeps\n // its own scalar-first projection (`getCursorIdentityFields`).\n rowKey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AQ,GAAkB,EAC1B,kBACA,oBACA,oBAAqB,CAAC,GAAG,EAAQ,CAClC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";const t=64,n=1000000n,r=/^\d+$/,i=/0+$/,a=10n;function split(e){if(e.length<2||!r.test(e))return;let t;if(e[0]===`0`){let n=9-Number(e[1]);if(n<1||(t=e.slice(0,2+n),t.length!==2+n))return;let r=BigInt(t.slice(2));if(r<1n||r>9n*a**BigInt(n-1))return}else{let n=Number(e[0]);if(t=e.slice(0,1+n),t.length!==1+n||n>1&&t[1]===`0`)return}let n=e.slice(t.length);if(!n.endsWith(`0`))return{integer:t,fraction:n}}function isKeyFormat(e){return typeof e==`string`&&e.length<=64&&split(e)!==void 0}const o=isKeyFormat;function parse(e){let t=split(e);if(t===void 0)throw RangeError(`"${e}" is not a key`);let{integer:n,fraction:r}=t;return{value:n[0]===`0`?BigInt(n.slice(2))-a**BigInt(n.length-2):BigInt(n.slice(1)),fraction:r}}function encode(e){if(e>=0n){let t=e.toString();if(t.length>9)throw RangeError(`a list holds at most 10^9 appends`);return`${t.length}${t}`}let t=(-e).toString();if(t.length>9)throw RangeError(`a list holds at most 10^9 prepends`);let n=(a**BigInt(t.length)+e).toString();return`0${9-t.length}${n.padStart(t.length,`0`)}`}function random(e){let t=e.toString().length+6,n=0n,r=0;for(;r<t;){let e=new Uint8Array(t-r+4);crypto.getRandomValues(e);for(let i of e)i<250&&r<t&&(n=n*a+BigInt(i%10),r+=1)}return n%e}function randomFraction(){return random(n).toString().padStart(6,`0`).replace(i,``)}function fractionsBetween(e,t,r){let o=Math.max(e.length,t?.length??0),scaled=e=>BigInt(e.padEnd(o,`0`)||`0`),s=BigInt(r+1),c=scaled(e),l=t===void 0?a**BigInt(o):scaled(t);for(;(l-c)/s<3n*n;)o+=1,c*=a,l*=a;let u=(l-c)/s,d=[];for(let e=1n;e<=BigInt(r);e+=1n){let t=c+u*e-u/6n+random(u/3n);d.push(t.toString().padStart(o,`0`).replace(i,``))}return d}function keysBetween(e,t,n){if(!Number.isInteger(n)||n<1)throw RangeError(`count must be a positive integer`);if(e!==null&&t!==null&&!(e<t))throw RangeError(`"${e}" is not below "${t}"`);let r=[];if(t===null){let t=e===null?-1n:parse(e).value,i=t<0n?-1n:t;for(let e=1n;e<=BigInt(n);e+=1n)r.push(encode(i+e)+randomFraction());return r}let i=parse(t);if(e===null){for(let e=BigInt(n);e>=1n;e-=1n)r.push(encode(i.value-e)+randomFraction());return r}let a=parse(e);if(i.value-a.value>BigInt(n)){for(let e=1n;e<=BigInt(n);e+=1n)r.push(encode(a.value+e)+randomFraction());return r}let o=encode(a.value),s=i.value===a.value?i.fraction:void 0;for(let e of fractionsBetween(a.fraction,s,n))r.push(o+e);return r}function keysAfter(e,t){if(e===null||isKeyFormat(e))return keysBetween(e,null,t);let n=Number(e[0]),i=e.slice(1,1+n);return keysBetween(e[0]===`0`||!r.test(i)?null:encode(BigInt(i)),null,t)}function keyBetween(e,t){return keysBetween(e,t,1)[0]}export{keysAfter as a,keyBetween as i,o as n,keysBetween as o,isKeyFormat as r,t};
|
|
2
|
+
//# sourceMappingURL=keys-M0pWraMM.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"keys-M0pWraMM.mjs","names":["digits"],"sources":["../src/ordering/keys.ts"],"sourcesContent":["// viborm/ordering keys: decimal fractional keys.\n//\n// A key is a string of the digits 0-9: an integer part that carries its own\n// length, then an optional fraction with no trailing zero. Comparing two keys\n// as strings compares their values, under any collation that orders digits\n// as digits: digits are the one alphabet no locale tailors (base 36 breaks\n// under Czech `ch` or Danish `aa`; measured on 89 ICU locales). The only\n// exception is a collation with numeric ordering (ICU `kn-true`).\n//\n// Integer part, for a value v:\n// - v >= 0: one digit L (1-9) giving the number of digits of v, then v\n// (\"10\" is 0, \"15\" is 5, \"210\" is 10). Appends increment it, so n appends\n// cost O(log n) digits.\n// - v < 0, with j = -v of L digits: \"0\", then 9 - L, then 10^L - j on L\n// digits (\"089\" is -1, \"081\" is -9, \"0790\" is -10). Prepends decrement it.\n// The head fixes the length of the integer part, so two integer parts never\n// share a prefix, and a longer negative sorts first.\n//\n// The append computed by SQL inside an INSERT (`append.ts`) builds exactly\n// `appendKey`'s integer: max(v, -1) + 1. A key never decides anything by\n// randomness: the random fraction only spreads concurrent writers apart.\n\n/** The longest key accepted, generated or given. */\nexport const MAX_KEY_LENGTH = 64;\n\n/** Random positions a generated key is drawn from: two writers placing into\n * one gap at once collide (tie) with probability 1 / RANDOM_SPAN. */\nconst RANDOM_SPAN = 1_000_000n;\nconst RANDOM_DIGITS = 6;\nconst MAX_INTEGER_DIGITS = 9;\n\nconst DIGITS = /^\\d+$/;\nconst TRAILING_ZEROS = /0+$/;\nconst TEN = 10n;\n\n/** The integer part of a key, and its fraction; undefined if not a key. */\nfunction split(key: string): { integer: string; fraction: string } | undefined {\n if (key.length < 2 || !DIGITS.test(key)) return undefined;\n let integer: string;\n if (key[0] === \"0\") {\n const length = 9 - Number(key[1]);\n if (length < 1) return undefined;\n integer = key.slice(0, 2 + length);\n if (integer.length !== 2 + length) return undefined;\n const body = BigInt(integer.slice(2));\n if (body < 1n || body > 9n * TEN ** BigInt(length - 1)) return undefined;\n } else {\n const length = Number(key[0]);\n integer = key.slice(0, 1 + length);\n if (integer.length !== 1 + length) return undefined;\n if (length > 1 && integer[1] === \"0\") return undefined;\n }\n const fraction = key.slice(integer.length);\n if (fraction.endsWith(\"0\")) return undefined;\n return { integer, fraction };\n}\n\n/**\n * Whether `value` is written as a key: the grammar above, at most\n * MAX_KEY_LENGTH. Every key a list may hold; `orderingKey` also refuses a\n * write setting an integer part of 10^8 or more.\n */\nexport function isKeyFormat(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length <= MAX_KEY_LENGTH &&\n split(value) !== undefined\n );\n}\n\n/** {@link isKeyFormat}'s name before 1.9.1, still accepted (a write may still refuse a key it accepts: `orderingKey`). */\nexport const isKey = isKeyFormat;\n\nfunction parse(key: string): { value: bigint; fraction: string } {\n const parts = split(key);\n if (parts === undefined) throw new RangeError(`\"${key}\" is not a key`);\n const { integer, fraction } = parts;\n const value =\n integer[0] === \"0\"\n ? BigInt(integer.slice(2)) - TEN ** BigInt(integer.length - 2)\n : BigInt(integer.slice(1));\n return { value, fraction };\n}\n\n/** The integer part encoding `value`. */\nfunction encode(value: bigint): string {\n if (value >= 0n) {\n const digits = value.toString();\n if (digits.length > MAX_INTEGER_DIGITS) {\n throw new RangeError(\"a list holds at most 10^9 appends\");\n }\n return `${digits.length}${digits}`;\n }\n const digits = (-value).toString();\n if (digits.length > MAX_INTEGER_DIGITS) {\n throw new RangeError(\"a list holds at most 10^9 prepends\");\n }\n const body = (TEN ** BigInt(digits.length) + value).toString();\n return `0${9 - digits.length}${body.padStart(digits.length, \"0\")}`;\n}\n\n/** A uniform random bigint in [0, span): one digit per byte below 250. */\nfunction random(span: bigint): bigint {\n const wanted = span.toString().length + 6;\n let drawn = 0n;\n let digits = 0;\n while (digits < wanted) {\n const bytes = new Uint8Array(wanted - digits + 4);\n crypto.getRandomValues(bytes);\n for (const byte of bytes)\n if (byte < 250 && digits < wanted) {\n drawn = drawn * TEN + BigInt(byte % 10);\n digits += 1;\n }\n }\n return drawn % span;\n}\n\n/** A random fraction of RANDOM_DIGITS digits, trailing zeros removed: what\n * the SQL append adds after its integer. */\nfunction randomFraction(): string {\n return random(RANDOM_SPAN)\n .toString()\n .padStart(RANDOM_DIGITS, \"0\")\n .replace(TRAILING_ZEROS, \"\");\n}\n\n/**\n * `count` fractions strictly between `lower` and `upper` (digit strings read\n * as 0.lower and 0.upper; `upper` undefined is 1), in order. The gap is cut\n * into count + 1 equal slots; key i is drawn from the middle third of the\n * boundary between slots i and i + 1, at a precision where that third holds\n * RANDOM_SPAN positions. Keys are increasing, inside the gap, and a gap\n * shrinks by at most 2.4x per key placed in it.\n */\nfunction fractionsBetween(\n lower: string,\n upper: string | undefined,\n count: number\n): string[] {\n let precision = Math.max(lower.length, upper?.length ?? 0);\n const scaled = (digits: string) =>\n BigInt(digits.padEnd(precision, \"0\") || \"0\");\n const slots = BigInt(count + 1);\n let low = scaled(lower);\n let high = upper === undefined ? TEN ** BigInt(precision) : scaled(upper);\n while ((high - low) / slots < 3n * RANDOM_SPAN) {\n precision += 1;\n low *= TEN;\n high *= TEN;\n }\n const slot = (high - low) / slots;\n const keys: string[] = [];\n for (let index = 1n; index <= BigInt(count); index += 1n) {\n const at = low + slot * index - slot / 6n + random(slot / 3n);\n keys.push(\n at.toString().padStart(precision, \"0\").replace(TRAILING_ZEROS, \"\")\n );\n }\n return keys;\n}\n\n/**\n * `count` keys strictly between `lower` and `upper` (`null`: an open end),\n * in increasing order.\n *\n * - After the last key (`upper` null): the next integers, as the SQL append\n * computes them, each with a random fraction.\n * - Before the first key (`lower` null): the integers just below `upper`'s.\n * - Between two keys: free integers between theirs when there are enough,\n * else fractions under `lower`'s integer.\n *\n * A result may exceed MAX_KEY_LENGTH once a gap has been split many times;\n * the caller checks `isKeyFormat` and respaces the neighbourhood when it does not.\n * Throws a RangeError when `lower` is not strictly below `upper`.\n */\nexport function keysBetween(\n lower: string | null,\n upper: string | null,\n count: number\n): string[] {\n if (!Number.isInteger(count) || count < 1) {\n throw new RangeError(\"count must be a positive integer\");\n }\n if (lower !== null && upper !== null && !(lower < upper)) {\n throw new RangeError(`\"${lower}\" is not below \"${upper}\"`);\n }\n const keys: string[] = [];\n if (upper === null) {\n const base = lower === null ? -1n : parse(lower).value;\n const from = base < 0n ? -1n : base;\n for (let step = 1n; step <= BigInt(count); step += 1n) {\n keys.push(encode(from + step) + randomFraction());\n }\n return keys;\n }\n const high = parse(upper);\n if (lower === null) {\n for (let step = BigInt(count); step >= 1n; step -= 1n) {\n keys.push(encode(high.value - step) + randomFraction());\n }\n return keys;\n }\n const low = parse(lower);\n if (high.value - low.value > BigInt(count)) {\n for (let step = 1n; step <= BigInt(count); step += 1n) {\n keys.push(encode(low.value + step) + randomFraction());\n }\n return keys;\n }\n const integer = encode(low.value);\n const ceiling = high.value === low.value ? high.fraction : undefined;\n for (const fraction of fractionsBetween(low.fraction, ceiling, count)) {\n keys.push(integer + fraction);\n }\n return keys;\n}\n\n/**\n * `count` keys after `last`, as `keysBetween(last, null, count)`, where\n * `last` may be any digit string the list's largest value is (a backfilled\n * constant, a key a write left malformed): only its integer is read, as the\n * SQL append reads it.\n */\nexport function keysAfter(last: string | null, count: number): string[] {\n if (last === null || isKeyFormat(last as unknown))\n return keysBetween(last, null, count);\n const length = Number(last[0]);\n const integer = last.slice(1, 1 + length);\n return keysBetween(\n last[0] === \"0\" || !DIGITS.test(integer) ? null : encode(BigInt(integer)),\n null,\n count\n );\n}\n\n/** One key strictly between `lower` and `upper` (`null`: an open end). */\nexport function keyBetween(lower: string | null, upper: string | null): string {\n return keysBetween(lower, upper, 1)[0] as string;\n}\n"],"mappings":"yCAuBA,MAAa,EAAiB,GAIxB,EAAc,SAId,EAAS,QACT,EAAiB,MACjB,EAAM,IAGZ,SAAS,MAAM,EAAgE,CAC7E,GAAI,EAAI,OAAS,GAAK,CAAC,EAAO,KAAK,EAAI,CAAE,OACzC,IAAI,EACJ,GAAI,EAAI,KAAO,IAAK,CAClB,IAAM,EAAS,EAAI,OAAO,EAAI,GAAG,CAGjC,GAFI,EAAS,IACb,EAAU,EAAI,MAAM,EAAG,EAAI,EAAO,CAC9B,EAAQ,SAAW,EAAI,GAAQ,OACnC,IAAM,EAAO,OAAO,EAAQ,MAAM,EAAE,CAAC,CACrC,GAAI,EAAO,IAAM,EAAO,GAAK,GAAO,OAAO,EAAS,EAAE,CAAE,WACnD,CACL,IAAM,EAAS,OAAO,EAAI,GAAG,CAG7B,GAFA,EAAU,EAAI,MAAM,EAAG,EAAI,EAAO,CAC9B,EAAQ,SAAW,EAAI,GACvB,EAAS,GAAK,EAAQ,KAAO,IAAK,OAExC,IAAM,EAAW,EAAI,MAAM,EAAQ,OAAO,CACtC,MAAS,SAAS,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AClB,IAAK,IAAI,EAAO,OAAO,EAAM,CAAE,GAAQ,GAAI,GAAQ,GACjD,EAAK,KAAK,OAAO,EAAK,MAAQ,EAAK,CAAG,gBAAgB,CAAC,CAEzD,OAAO,EAET,IAAM,EAAM,MAAM,EAAM,CACxB,GAAI,EAAK,MAAQ,EAAI,MAAQ,OAAO,EAAM,CAAE,CAC1C,IAAK,IAAI,EAAO,GAAI,GAAQ,OAAO,EAAM,CAAE,GAAQ,GACjD,EAAK,KAAK,OAAO,EAAI,MAAQ,EAAK,CAAG,gBAAgB,CAAC,CAExD,OAAO,EAET,IAAM,EAAU,OAAO,EAAI,MAAM,CAC3B,EAAU,EAAK,QAAU,EAAI,MAAQ,EAAK,SAAW,IAAA,GAC3D,IAAK,IAAM,KAAY,iBAAiB,EAAI,SAAU,EAAS,EAAM,CACnE,EAAK,KAAK,EAAU,EAAS,CAE/B,OAAO,EAST,SAAgB,UAAU,EAAqB,EAAyB,CACtE,GAAI,IAAS,MAAQ,YAAY,EAAgB,CAC/C,OAAO,YAAY,EAAM,KAAM,EAAM,CACvC,IAAM,EAAS,OAAO,EAAK,GAAG,CACxB,EAAU,EAAK,MAAM,EAAG,EAAI,EAAO,CACzC,OAAO,YACL,EAAK,KAAO,KAAO,CAAC,EAAO,KAAK,EAAQ,CAAG,KAAO,OAAO,OAAO,EAAQ,CAAC,CACzE,KACA,EACD,CAIH,SAAgB,WAAW,EAAsB,EAA8B,CAC7E,OAAO,YAAY,EAAO,EAAO,EAAE,CAAC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
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-kE6fh5zZ.mjs";import{F as u,J as d,L as f,M as p,N as m,P as h,S as g,T as _,U as v,_t as y,at as b,c as x,ct as S,d as C,dt as w,f as T,ft as E,g as D,gt as O,ht as ee,it as k,j as A,lt as j,mt as M,ot as N,pt as P,st as F,ut as I,v as L}from"./client-Bbke7iRo.mjs";import{i as R,r as z}from"./utils-QZGdBir8.mjs";import{t as B}from"./batch-refs-DShoaHb7.mjs";function escapeIdentifier(e){return`"${e.replace(/"/g,`""`)}"`}function int(e){return Number(e)}const V=/^WHERE\s+([\s\S]+)$/i,H=/^(?:[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|0x[\da-f]+|'(?:[^']|'')*'|x'[\da-f]*'|"(?:[^"]|"")*"|[a-z_][\w$]*)$/i;function columnDefault(e){if(e!==null)return H.test(e)?e:`(${e})`}const U=/\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(`, `)}))`}const W=new RegExp(String.raw`/\* ${A}(\{[^\n]*\}) \*/\s*$`);function sqliteRawIndex(e,t){let n=e===null?void 0:W.exec(e)?.[1];return n===void 0?void 0:m(n,t)}function partialIndexPredicate(e){if(!e)return;let t=0,n=0,r=-1;for(;n<e.length;){let i=y(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 V.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
|
+
`,[B]),o=[];for(let i of a.rows){let a=i.name,s=r===void 0||r.includes(a),c=M(i.sql??``);if(s&&c.some(e=>P(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&&P((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=U.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])),h=await e(`PRAGMA foreign_key_list(${escapeIdentifier(a)})`),g=[],_=[];for(let e of l.rows){let t=int(e.pk),n=e.type||`TEXT`,r=int(e.notnull)===0&&t===0,i=j(u,{name:e.name,type:n,nullable:r},escapeIdentifier);g.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:k(u,{name:e.name,type:e.type,nullable:r},escapeIdentifier)}),t>0&&_.push({name:e.name,position:t})}if(s&&c.reduce((e,t)=>e+P(t.text).filter(e=>e===`CHECK`).length,0)!==g.reduce((e,t)=>e+Number(t.decimal!==void 0)+Number(t.geoPointEncoding!==void 0)+Number(sqliteEnumCheckSuffix(u,t.name)!==void 0),0)&&!D(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 v;_.length>0&&(_.sort((e,t)=>e.position-t.position),v={name:`${a}_pkey`,columns:_.map(e=>e.name)});let y=[],b=[];for(let i of f.rows){let o=sqliteRawIndex(m.get(i.name)??null,i.name);if(o){y.push(o);continue}let s=(await e(`PRAGMA index_xinfo(${escapeIdentifier(i.name)})`)).rows.filter(e=>int(e.key)===1);if(s.length===0||s.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. Declare it with .rawIndex() (drop this hand-made copy first: only an index VibORM created carries the marker it recognizes), or manage its table outside this synchronization scope.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:a,indexName:i.name}});continue}if(i.origin===`pk`)continue;let c=s.sort((e,t)=>int(e.seqno)-int(t.seqno)).flatMap(e=>e.name===null?[]:[e.name]),l=int(i.unique)===1;l&&i.origin===`u`?b.push({name:i.name,columns:c}):y.push({name:i.name,columns:c,unique:l,where:partialIndexPredicate(m.get(i.name)??null)})}let x=new Map;for(let e of h.rows){let t=int(e.id),n=x.get(t)||[];n.push(e),x.set(t,n)}let C=[];for(let[e,t]of x){let n=t.sort((e,t)=>int(e.seq)-int(t.seq)),r=n[0];r&&C.push({name:`${a}_fk_${e}`,columns:n.map(e=>e.from),referencedTable:r.table,referencedColumns:n.map(e=>e.to),onDelete:z(r.on_delete),onUpdate:z(r.on_update)})}o.push({name:a,columns:g,primaryKey:v,indexes:y,foreignKeys:C,uniqueConstraints:b})}return{tables:o,enums:[]}}const G=/^(?:CURRENT_(?:TIME|DATE|TIMESTAMP)|\()/i,K=`__new_`,q=/^CREATE\s+TABLE\s+/i,J=/^ALTER\s+TABLE\s+/i,Y=/^\s+RENAME\s+TO\s+/i,X=/^CREATE\s+(?:TEMP(?:ORARY)?\s+)?(TRIGGER|VIEW)\s+(?:IF\s+NOT\s+EXISTS\s+)?/i,Z=/^DROP\s+(?:TRIGGER|VIEW)\s+(?:IF\s+EXISTS\s+)?/i,Q=/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?/i,te=/^\s*\./,ne=/^(?: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)$/,$=/\s+CHECK\s*\(/,re=/CHAR|CLOB|TEXT/,ie=/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=y(e,0);for(;a>0;)e=e.slice(a).trimStart(),a=y(e,0);let o=q.exec(e),s=J.exec(e),c=X.exec(e),l=Z.exec(e),u=Q.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(K)){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(K)){let t=Y.exec(e.slice(f.end)),n=t&&O(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=O(e,t),r=n?te.exec(e.slice(n.end)):null;return n&&r?O(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)||ee(a)?O(e,i):void 0;if(o){let e=o.value.toLowerCase();if(r&&e===t.toLowerCase())r=!1;else if(e===n&&(o.quoted||!ne.test(e)))return!0;i=o.end}else i=Math.max(y(e,i),i+1)}return!1}function sqliteAffinity(e){let t=e.toUpperCase().split($)[0].trim();return t.includes(`INT`)?`INTEGER`:re.test(t)?`TEXT`:t===``||t.includes(`BLOB`)?`BLOB`:ie.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=f({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 R{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`&&E(e.from)===`binary64`&&E(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:v({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(w(e,e=>this.escapeIdentifier(e),E(e)));let a=F(e);return e.decimal&&a&&i.push(b(e,e.decimal,a,e=>this.escapeIdentifier(e))),i.join(` `)}compileTableRecreation(e,r,i,a,o,s){let c=[],l=`${K}${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&&E(o)===`legacy`)return`CASE WHEN ${c} IS NULL THEN NULL ELSE ${I(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 C(c,a,l,o?.dateTime!==void 0)}let u=s.decimal,d=F(s),f=o?.decimal;if(u===void 0&&o!==void 0&&f!==void 0)return this.descaledDecimalSource(e,r,{...o,decimal:f},s.type,c);if(u===void 0||d===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 ${x} END`}if(f===void 0){if(!(d===`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 ${d}. 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 N(c,void 0,u,`scalar`)}if(a(f,u))return c;let p=this.decimalConversionKind(o,s);return p===void 0?c:N(c,f,u,p)}descaledDecimalSource(e,r,a,o,s){let c=F(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 ${x} 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=F(t);if(!(i===void 0||F(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&&L(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&&G.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,...this.rawIndexesRenamedBy(e,r).flatMap(t=>[this.generateDropIndex({type:`dropIndex`,tableName:e.tableName,indexName:t.name},r),this.generateCreateIndex({type:`createIndex`,tableName:e.tableName,index:t},r)])];let s=f({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&&_(t)===_(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`):T(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;if(r.raw){let e=u(r,{name:this.escapeIdentifier(r.name),table:this.escapeIdentifier(n),column:e=>this.escapeIdentifier(e)});return h(r,e,e=>g(e,`sqlite`),[]),`${e} /* ${A}${p(r).replaceAll(`/`,`\\/`)} */`}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 ae=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)||T(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(w(e,e=>this.escapeIdentifier(e),E(e)));let r=F(e);return e.decimal&&r&&n.push(b(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 oe=new LibSQLMigrationDriver;export{ae as n,oe as t};
|
|
11
|
+
//# sourceMappingURL=libsql-lOqKLyZA.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"libsql-lOqKLyZA.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 { RAW_INDEX_MARKER_PREFIX, readRawIndexMarker } from \"../../raw-index\";\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 */\n/** The marker `generateCreateIndex` ends a raw index's text with. */\nconst RAW_INDEX_TRAILER = new RegExp(\n String.raw`/\\* ${RAW_INDEX_MARKER_PREFIX}(\\{[^\\n]*\\}) \\*/\\s*$`\n);\n\n/** The raw index an index's stored text marks, when VibORM wrote it for this index. */\nfunction sqliteRawIndex(\n sql: string | null,\n name: string\n): IndexDef | undefined {\n const marker = sql === null ? undefined : RAW_INDEX_TRAILER.exec(sql)?.[1];\n return marker === undefined ? undefined : readRawIndexMarker(marker, name);\n}\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 // A raw index is its marker, whatever its key semantics are.\n const raw = sqliteRawIndex(indexSql.get(idx.name) ?? null, idx.name);\n if (raw) {\n indexes.push(raw);\n continue;\n }\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. Declare it with .rawIndex() (drop this hand-made copy first: only an index VibORM created carries the marker it recognizes), or manage its table outside this synchronization scope.`,\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 {\n RAW_INDEX_MARKER_PREFIX,\n rawIndexMarker,\n refuseRawIndexStatement,\n renderRawIndex,\n} from \"../../raw-index\";\nimport { readExecutableStatements } from \"../../statement-safety\";\nimport type {\n ColumnDef,\n DiffOperation,\n SchemaSnapshot,\n TableDef,\n} from \"../../types\";\nimport type {\n AddColumnOperation,\n AddForeignKeyOperation,\n AddPrimaryKeyOperation,\n AddUniqueConstraintOperation,\n AlterColumnOperation,\n AlterEnumOperation,\n CreateEnumOperation,\n CreateIndexOperation,\n CreateTableOperation,\n DDLContext,\n DropColumnOperation,\n DropEnumOperation,\n DropForeignKeyOperation,\n DropIndexOperation,\n DropPrimaryKeyOperation,\n DropTableOperation,\n DropUniqueConstraintOperation,\n RenameColumnOperation,\n RenameTableOperation,\n} from \"../base\";\nimport { SqlMigrationDriver } from \"../sql\";\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 SqlMigrationDriver {\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 // SQLite rewrites the index's text, but not the marker in its comment.\n return [\n nativeRename,\n ...this.rawIndexesRenamedBy(op, context).flatMap((index) => [\n this.generateDropIndex(\n {\n type: \"dropIndex\",\n tableName: op.tableName,\n indexName: index.name,\n },\n context\n ),\n this.generateCreateIndex(\n { type: \"createIndex\", tableName: op.tableName, index },\n context\n ),\n ]),\n ];\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 if (index.raw) {\n const rendered = renderRawIndex(index, {\n name: this.escapeIdentifier(index.name),\n table: this.escapeIdentifier(tableName),\n column: (column) => this.escapeIdentifier(column),\n });\n refuseRawIndexStatement(\n index,\n rendered,\n (text) => readExecutableStatements(text, \"sqlite\"),\n []\n );\n // SQLite keeps an index's text as written, a trailing comment included,\n // and rewrites only identifiers on a rename: the comment is its marker.\n // Every `/` is escaped so that no name can close the comment early.\n return `${rendered} /* ${RAW_INDEX_MARKER_PREFIX}${rawIndexMarker(index).replaceAll(\"/\", \"\\\\/\")} */`;\n }\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":"ktBA4CA,SAAS,iBAAiB,EAAsB,CAC9C,MAAO,IAAI,EAAK,QAAQ,KAAM,KAAK,CAAC,GAetC,SAAS,IAAI,EAA0B,CACrC,OAAO,OAAO,EAAM,CAItB,MAAM,EAAiB,uBAIjB,EACJ,sHAQF,SAAS,cAAc,EAA0C,CAC3D,OAAU,KACd,OAAO,EAAgB,KAAK,EAAM,CAAG,EAAQ,IAAI,EAAM,GAEzD,MAAM,EAAgB,qBAEtB,SAAS,aAAa,EAAuB,CAC3C,OAAO,EAAM,QAAQ,sBAAuB,OAAO,CAWrD,SAAS,sBACP,EACA,EACoB,CACpB,GAAI,CAAC,EAAU,O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C,KAAK,6BAA6B,EAAO,KAe5D,MAAa,GAAwB,IAAI"}
|
package/dist/libsql.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Hn as DriverTransactionOptions, Jn as QueryExecutionContext, Lt as DriverConfig, P as Schema, Un as TransactionOptionSupport, Ut as VibORMClient, Vt as NoExtraDriverConfigKeys, Yn as QueryResult, _ as DriverResultParser, d as Driver, s as DatabaseAdapter, z as LinkedClientConfig } from "./index-B8MMx5Al.mjs";
|
|
2
2
|
import { Client, Config, Transaction } from "@libsql/client";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/libsql/index.d.ts
|
package/dist/libsql.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./normalized-result-ByvlIQqa.mjs";import{l as n}from"./execution-context-_oajgBi4.mjs";import{n as r}from"./base-wlv81COV.mjs";import{m as i,u as a}from"./error-mapping-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./normalized-result-ByvlIQqa.mjs";import{l as n}from"./execution-context-_oajgBi4.mjs";import{n as r}from"./base-wlv81COV.mjs";import{m as i,u as a}from"./error-mapping-DW7TYOyA.mjs";import{n as o}from"./query-CTna5P9o.mjs";import{n as s}from"./client-nkU6M5bV.mjs";import{a as c,i as l,l as u,t as d}from"./driver-BRYL6K0W.mjs";import{c as f,i as p,l as m,n as h}from"./sqlite-utils-B-Y47_Uz.mjs";import{t as g}from"./sqlite-adapter-CVKv1u4i.mjs";const _=new WeakSet,v={client:!0,databaseUrl:!0,dataDir:!0,authToken:!0,options:!0};function convertValuesForLibSQL(e){return e.map(e=>{let t=h(e);if(typeof t==`string`&&t.includes(`\0`))throw TypeError(`libSQL cannot preserve strings containing NUL bytes`);if(p(t))return t instanceof ArrayBuffer?t:f(t);if(t===null||typeof t==`string`||typeof t==`number`||typeof t==`bigint`||typeof t==`boolean`||t instanceof Date)return t;throw TypeError(`Driver "libsql" received an unsupported SQLite parameter value.`)})}const libsqlRowCount=(e,n)=>{let r=t(e.rowsAffected,{provider:`libsql`,operation:n});return e.rows.length>0?e.rows.length:r};var LibSQLDriver=class extends d{adapter=new g;maxBindParametersPerStatement=32766;result=m;serializeTransactions;driverOptions;suppliedClient;constructor(e={}){if(super(`sqlite`,`libsql`),this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient)this.serializeTransactions=this.suppliedClient.protocol===`file`;else{let e=this.getDatabaseUrl();this.serializeTransactions=e===`:memory:`||e.startsWith(`file:`)}this.suppliedClient&&(this.client=this.suppliedClient,this.serializeTransactions&&Object.defineProperty(this,`connectionQueue`,{value:l(this.suppliedClient)}))}async initClient(){if(this.suppliedClient)return this.suppliedClient;let{createClient:e}=await import(`@libsql/client`),t=this.getDatabaseUrl(),n=this.driverOptions.authToken;return e({url:t,authToken:n,timeout:5e3,...this.driverOptions.options??{},intMode:`bigint`})}async closeClient(e){e!==this.suppliedClient&&`close`in e&&(e.close(),`commit`in e||_.delete(e))}async execute(e,t,n,r){let i=r?.operation??`execute`,a=convertValuesForLibSQL(n),o=await this.executeStatement(e,{sql:t,args:a});return{rows:o.rows,rowCount:libsqlRowCount(o,i)}}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`,a=n?convertValuesForLibSQL(n):[],o=await this.executeStatement(e,{sql:t,args:a});return{rows:o.rows,rowCount:libsqlRowCount(o,i)}}transactionOptionSupport(){return{isolationLevel:`serializable-only`,isolationLevelReason:`libSQL serializes writers the way SQLite does and has no statement to weaken isolation, so only Serializable can be honored truthfully`,timeout:!0,maxWait:this.serializeTransactions?`queue`:`acquisition`}}async transaction(e,t,r,o){if(`commit`in e)throw a(this.driverName);let s=await c(()=>this.quarantineOnBusy(e,()=>e.transaction(`write`)),e=>e.close(),o?.maxWaitMs,{driverName:this.driverName,form:`callback`});return i({begin:()=>void 0,callback:()=>t(s),commit:()=>s.commit(),rollback:()=>s.rollback(),phases:n(r),close:()=>s.close()})}transactionCleanupFailed(e){}executeStatement(e,t){return this.quarantineOnBusy(e,()=>e.execute(t))}async quarantineOnBusy(e,t){try{return await t()}catch(t){throw this.serializeTransactions&&!(`commit`in e)&&typeof t==`object`&&t&&`code`in t&&typeof t.code==`string`&&(t.code===`SQLITE_BUSY`||t.code.startsWith(`SQLITE_BUSY_`))&&(_.add(e),this.closeRetryClient=e,this.client=null,this.initPromise=null),t}}async getClient(e){let t=await super.getClient(e);return this.assertLocalClientUsable(t),t}assertLocalClientUsable(e){if(!(`commit`in e)&&_.has(e))throw new o(`Local libSQL execution encountered SQLITE_BUSY; disconnect an owned driver, or close and replace the supplied native client, before reuse.`,{code:r.CONNECTION_CLOSED,meta:{driver:`libsql`}})}getDatabaseUrl(){return this.driverOptions.databaseUrl?this.driverOptions.databaseUrl:this.driverOptions.dataDir?`file:${this.driverOptions.dataDir}`:`file::memory:`}};function createClient(e){u(e,`libsql`,v);let{client:t,databaseUrl:n,dataDir:r,authToken:i,options:a}=e;return s(e,new LibSQLDriver({client:t,databaseUrl:n,dataDir:r,authToken:i,options:a}))}export{LibSQLDriver,createClient};
|
|
2
2
|
//# sourceMappingURL=libsql.mjs.map
|