viborm 1.14.2 → 1.15.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/dist/{adapter-namespace-DaRiTIIf.mjs → adapter-namespace-DD-BQ2Wk.mjs} +2 -2
- package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DD-BQ2Wk.mjs.map} +1 -1
- package/dist/adapters.d.mts +15 -3
- package/dist/adapters.mjs +1 -1
- package/dist/{args-764KdWMr.mjs → args-BvA37zBZ.mjs} +2 -2
- package/dist/{args-764KdWMr.mjs.map → args-BvA37zBZ.mjs.map} +1 -1
- package/dist/{batch-refs-C-gx7A4-.mjs → batch-refs-BmEpMmjI.mjs} +2 -2
- package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-BmEpMmjI.mjs.map} +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +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 +2 -2
- package/dist/cache.mjs +1 -1
- package/dist/{call-Cz8XUmrl.mjs → call-BWFI7-vU.mjs} +2 -2
- package/dist/{call-Cz8XUmrl.mjs.map → call-BWFI7-vU.mjs.map} +1 -1
- package/dist/cli.mjs +2 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/client-CVCC-D1j.mjs +2 -0
- package/dist/client-CVCC-D1j.mjs.map +1 -0
- package/dist/{client-CRxfhw2y.d.mts → client-DZ39sYy2.d.mts} +2 -2
- package/dist/{client-y7TV0PRZ.mjs → client-DtPTegtA.mjs} +2 -2
- package/dist/{client-y7TV0PRZ.mjs.map → client-DtPTegtA.mjs.map} +1 -1
- package/dist/client.d.mts +3 -3
- package/dist/client.mjs +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +1 -1
- package/dist/{confine-DqFBTUw6.mjs → confine-BGGv2du0.mjs} +2 -2
- package/dist/{confine-DqFBTUw6.mjs.map → confine-BGGv2du0.mjs.map} +1 -1
- package/dist/{coordination-6qZHx_kl.mjs → coordination-BY6Np3xV.mjs} +2 -2
- package/dist/{coordination-6qZHx_kl.mjs.map → coordination-BY6Np3xV.mjs.map} +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-D62c-uC6.d.mts} +604 -473
- package/dist/{datetime-physical-codec-Dj-APo9f.mjs → datetime-physical-codec-BS2T81sD.mjs} +2 -2
- package/dist/{datetime-physical-codec-Dj-APo9f.mjs.map → datetime-physical-codec-BS2T81sD.mjs.map} +1 -1
- package/dist/{defaults-DwOHWI_M.mjs → defaults-CrtGVdEC.mjs} +2 -2
- package/dist/{defaults-DwOHWI_M.mjs.map → defaults-CrtGVdEC.mjs.map} +1 -1
- package/dist/{document-BVTQ-cF-.d.mts → document-o5Bd5ZoJ.d.mts} +1 -1
- package/dist/{driver-BBEmaJZy.d.mts → driver-0cdCF_KD.d.mts} +1 -1
- package/dist/{driver-BGVcgnIX.mjs → driver-D1grnHEr.mjs} +2 -2
- package/dist/{driver-BGVcgnIX.mjs.map → driver-D1grnHEr.mjs.map} +1 -1
- package/dist/{driver-BIXhOH2_.mjs → driver-Df88hu4U.mjs} +2 -2
- package/dist/{driver-BIXhOH2_.mjs.map → driver-Df88hu4U.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/durable-object.d.mts +1 -1
- package/dist/durable-object.mjs +1 -1
- package/dist/error-mapping-DIRlrmDK.mjs +2 -0
- package/dist/error-mapping-DIRlrmDK.mjs.map +1 -0
- package/dist/every-BHEmfLOW.mjs +2 -0
- package/dist/{every-tOgQmaIE.mjs.map → every-BHEmfLOW.mjs.map} +1 -1
- package/dist/execution-context-VMQm-9CH.mjs +2 -0
- package/dist/execution-context-VMQm-9CH.mjs.map +1 -0
- package/dist/{exports-COCJ8f2f.d.mts → exports-Bzvtum3F.d.mts} +1 -1
- package/dist/geo-area-codec-BDvW7IH-.mjs +2 -0
- package/dist/{geo-area-codec-mHrM3b9A.mjs.map → geo-area-codec-BDvW7IH-.mjs.map} +1 -1
- package/dist/{hydration-A3zffFWP.mjs → hydration-D7U8HACL.mjs} +2 -2
- package/dist/{hydration-A3zffFWP.mjs.map → hydration-D7U8HACL.mjs.map} +1 -1
- package/dist/{identifier-conversion-DHYPTgzr.mjs → identifier-conversion-Ci_iaJ0b.mjs} +2 -2
- package/dist/{identifier-conversion-DHYPTgzr.mjs.map → identifier-conversion-Ci_iaJ0b.mjs.map} +1 -1
- package/dist/identifiers-BTCfD5ic.mjs +2 -0
- package/dist/identifiers-BTCfD5ic.mjs.map +1 -0
- 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/{introspect-Bm6xnXcG.mjs → introspect-C4T5gt9O.mjs} +2 -2
- package/dist/{introspect-Bm6xnXcG.mjs.map → introspect-C4T5gt9O.mjs.map} +1 -1
- package/dist/{json-DgMc8-GU.mjs → json-CHdgejCt.mjs} +2 -2
- package/dist/{json-DgMc8-GU.mjs.map → json-CHdgejCt.mjs.map} +1 -1
- package/dist/judge-words-DpwxOfre.mjs +2 -0
- package/dist/judge-words-DpwxOfre.mjs.map +1 -0
- package/dist/{key-hxFFCKed.mjs → key-B3xgpu0M.mjs} +2 -2
- package/dist/{key-hxFFCKed.mjs.map → key-B3xgpu0M.mjs.map} +1 -1
- package/dist/{keys-BQxM4c_a.mjs → keys-1Z6WKrnE.mjs} +1 -1
- package/dist/{keys-BQxM4c_a.mjs.map → keys-1Z6WKrnE.mjs.map} +1 -1
- package/dist/{libsql-DuGR904j.mjs → libsql-DJRsCDT_.mjs} +2 -2
- package/dist/{libsql-DuGR904j.mjs.map → libsql-DJRsCDT_.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-G4cSuc6A.mjs → memory-gjKMy3Ql.mjs} +2 -2
- package/dist/{memory-G4cSuc6A.mjs.map → memory-gjKMy3Ql.mjs.map} +1 -1
- package/dist/methods-part-DoTrY6b9.mjs +2 -0
- package/dist/methods-part-DoTrY6b9.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +4 -4
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +4 -4
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/snowflake.d.mts +4 -4
- package/dist/migrations/snowflake.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +4 -4
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/surrealdb.d.mts +4 -4
- package/dist/migrations/surrealdb.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +4 -4
- package/dist/migrations.mjs +1 -1
- package/dist/{mysql-BNXWfTOo.mjs → mysql-BH0Z3PlH.mjs} +2 -2
- package/dist/{mysql-BNXWfTOo.mjs.map → mysql-BH0Z3PlH.mjs.map} +1 -1
- package/dist/mysql-adapter-B06Ve3ds.mjs +2 -0
- package/dist/mysql-adapter-B06Ve3ds.mjs.map +1 -0
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/named-statements-Bdz2GD5R.d.mts +13 -0
- package/dist/named-statements-CMj1QEyw.mjs +2 -0
- package/dist/named-statements-CMj1QEyw.mjs.map +1 -0
- package/dist/{native-types-DgjMUikz.mjs → native-types-DspZ0Z5E.mjs} +2 -2
- package/dist/{native-types-DgjMUikz.mjs.map → native-types-DspZ0Z5E.mjs.map} +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/{object-store-B_YMoW8u.d.mts → object-store-D5x-Yf7w.d.mts} +3 -3
- package/dist/{object-store-DS0F0yZX.mjs → object-store-WIE0DGGG.mjs} +1 -1
- package/dist/{object-store-DS0F0yZX.mjs.map → object-store-WIE0DGGG.mjs.map} +1 -1
- package/dist/{on-ylYaKuRu.mjs → on-DvrfHGje.mjs} +2 -2
- package/dist/{on-ylYaKuRu.mjs.map → on-DvrfHGje.mjs.map} +1 -1
- package/dist/on.d.mts +1 -1
- package/dist/on.mjs +1 -1
- package/dist/ordering/keys.mjs +1 -1
- package/dist/ordering.d.mts +1 -1
- package/dist/ordering.mjs +1 -1
- package/dist/pending-operation-Dq4rv-Ml.mjs +2 -0
- package/dist/pending-operation-Dq4rv-Ml.mjs.map +1 -0
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/pg.d.mts +27 -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/{physical-CeE2nYmI.mjs → physical-wboFLAg9.mjs} +2 -2
- package/dist/{physical-CeE2nYmI.mjs.map → physical-wboFLAg9.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-DHjdvjwk.d.mts → planner-Ckoxeruk.d.mts} +1 -1
- package/dist/{postgres-CDdh5dSP.mjs → postgres-DQ_pO0hi.mjs} +2 -2
- package/dist/{postgres-CDdh5dSP.mjs.map → postgres-DQ_pO0hi.mjs.map} +1 -1
- package/dist/{postgres-adapter-axapXX8d.mjs → postgres-adapter-Byp7Zpop.mjs} +2 -2
- package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-Byp7Zpop.mjs.map} +1 -1
- package/dist/postgres-adapter-Ia4u0-Ht.mjs +2 -0
- package/dist/postgres-adapter-Ia4u0-Ht.mjs.map +1 -0
- package/dist/postgres-result-CiS5OWp1.mjs +2 -0
- package/dist/postgres-result-CiS5OWp1.mjs.map +1 -0
- package/dist/postgres.d.mts +17 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-Ccsb8PTb.mjs → provider-limits-CCOa4d1E.mjs} +2 -2
- package/dist/{provider-limits-Ccsb8PTb.mjs.map → provider-limits-CCOa4d1E.mjs.map} +1 -1
- package/dist/{provider-parameter-snapshot-BikrgKqI.mjs → provider-parameter-snapshot-C0ehKSAA.mjs} +2 -2
- package/dist/{provider-parameter-snapshot-BikrgKqI.mjs.map → provider-parameter-snapshot-C0ehKSAA.mjs.map} +1 -1
- package/dist/query-Cdy8E2jM.mjs +2 -0
- package/dist/query-Cdy8E2jM.mjs.map +1 -0
- package/dist/{query-inspection-BoG-yAln.mjs → query-inspection-C-T2ttRx.mjs} +2 -2
- package/dist/{query-inspection-BoG-yAln.mjs.map → query-inspection-C-T2ttRx.mjs.map} +1 -1
- package/dist/{raw-Dyq6Y6UX.mjs → raw-uaVIxHcE.mjs} +2 -2
- package/dist/{raw-Dyq6Y6UX.mjs.map → raw-uaVIxHcE.mjs.map} +1 -1
- package/dist/{relation-bound-ku_cMdye.mjs → relation-bound-BaU-LuuI.mjs} +1 -1
- package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-BaU-LuuI.mjs.map} +1 -1
- package/dist/{rule-words-ZIGm7cDm.mjs → rule-words-C4lXzgW2.mjs} +2 -2
- package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-C4lXzgW2.mjs.map} +1 -1
- package/dist/scalar-B9WizsvR.mjs +4 -0
- package/dist/scalar-B9WizsvR.mjs.map +1 -0
- package/dist/schema/introspect.d.mts +2 -2
- package/dist/schema/introspect.mjs +1 -1
- package/dist/schema/json.d.mts +2 -2
- package/dist/schema/json.mjs +1 -1
- package/dist/{schema-BYA-_bpk.mjs → schema-MB-pPNTO.mjs} +2 -2
- package/dist/schema-MB-pPNTO.mjs.map +1 -0
- package/dist/{schema-CFIaebgi.mjs → schema-TthAXPVP.mjs} +2 -2
- package/dist/{schema-CFIaebgi.mjs.map → schema-TthAXPVP.mjs.map} +1 -1
- package/dist/schema-introspection-wMVZowIF.mjs +6 -0
- package/dist/schema-introspection-wMVZowIF.mjs.map +1 -0
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/select-assembly-SuVxJjps.mjs +2 -0
- package/dist/select-assembly-SuVxJjps.mjs.map +1 -0
- package/dist/{serializer-rBq3v1xr.mjs → serializer-B2kk7NAR.mjs} +5 -5
- package/dist/{serializer-rBq3v1xr.mjs.map → serializer-B2kk7NAR.mjs.map} +1 -1
- package/dist/{settled-BjyuA76m.mjs → settled-Dkk5w1vE.mjs} +2 -2
- package/dist/{settled-BjyuA76m.mjs.map → settled-Dkk5w1vE.mjs.map} +1 -1
- package/dist/{snowflake-UOCC820W.mjs → snowflake-6sBLJi34.mjs} +2 -2
- package/dist/{snowflake-UOCC820W.mjs.map → snowflake-6sBLJi34.mjs.map} +1 -1
- package/dist/snowflake.d.mts +2 -2
- package/dist/snowflake.mjs +1 -1
- package/dist/snowflake.mjs.map +1 -1
- package/dist/soft-delete.d.mts +1 -1
- package/dist/soft-delete.mjs +1 -1
- package/dist/{spans-XDUFeTzC.mjs → spans-BE-EjlZK.mjs} +1 -1
- package/dist/{spans-XDUFeTzC.mjs.map → spans-BE-EjlZK.mjs.map} +1 -1
- package/dist/sql-BGjAsoBE.mjs +2 -0
- package/dist/sql-BGjAsoBE.mjs.map +1 -0
- package/dist/{sql-Dl6nykFV.mjs → sql-CFxGrk3K.mjs} +2 -2
- package/dist/{sql-Dl6nykFV.mjs.map → sql-CFxGrk3K.mjs.map} +1 -1
- package/dist/{sql-BVZ8QefY.d.mts → sql-CXtSIPzy.d.mts} +11 -5
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/{sqlite-adapter-Ad0d-m2t.mjs → sqlite-adapter-fIbNDvwO.mjs} +2 -2
- package/dist/{sqlite-adapter-Ad0d-m2t.mjs.map → sqlite-adapter-fIbNDvwO.mjs.map} +1 -1
- package/dist/{sqlite-utils-BRvbmlQ1.mjs → sqlite-utils-DcQct689.mjs} +2 -2
- package/dist/{sqlite-utils-BRvbmlQ1.mjs.map → sqlite-utils-DcQct689.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/{standard-sql-qLcQyCtK.mjs → standard-sql-Bsf5nrla.mjs} +3 -3
- package/dist/standard-sql-Bsf5nrla.mjs.map +1 -0
- package/dist/surrealdb.d.mts +2 -2
- package/dist/surrealdb.mjs +1 -1
- package/dist/surrealdb.mjs.map +1 -1
- package/dist/{surrealql-C1dp1sWw.mjs → surrealql-DY7sgVnJ.mjs} +2 -2
- package/dist/{surrealql-C1dp1sWw.mjs.map → surrealql-DY7sgVnJ.mjs.map} +1 -1
- package/dist/{to-many-BybuKQM1.mjs → to-many-DiP6cOSQ.mjs} +2 -2
- package/dist/{to-many-BybuKQM1.mjs.map → to-many-DiP6cOSQ.mjs.map} +1 -1
- package/dist/{unit-BhHbZyuJ.mjs → unit-CSaAB0su.mjs} +2 -2
- package/dist/{unit-BhHbZyuJ.mjs.map → unit-CSaAB0su.mjs.map} +1 -1
- package/dist/{unit-words-CT0yeqfZ.mjs → unit-words-BGMVZ1MX.mjs} +2 -2
- package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BGMVZ1MX.mjs.map} +1 -1
- package/dist/{utils-CpAojrCj.mjs → utils-BLlgSQIo.mjs} +2 -2
- package/dist/{utils-CpAojrCj.mjs.map → utils-BLlgSQIo.mjs.map} +1 -1
- package/dist/validation-D0LG854o.mjs +2 -0
- package/dist/validation-D0LG854o.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/{validator-CZLW7aR3.mjs → validator-CDYlO9HV.mjs} +2 -2
- package/dist/{validator-CZLW7aR3.mjs.map → validator-CDYlO9HV.mjs.map} +1 -1
- package/dist/{values-B4aj1i1f.mjs → values-Byqn5wAh.mjs} +2 -2
- package/dist/{values-B4aj1i1f.mjs.map → values-Byqn5wAh.mjs.map} +1 -1
- package/dist/version-B_ZLWzLW.mjs +2 -0
- package/dist/{version-CXGIA82S.mjs.map → version-B_ZLWzLW.mjs.map} +1 -1
- package/package.json +35 -35
- package/dist/client-DRpX3-vw.mjs +0 -2
- package/dist/client-DRpX3-vw.mjs.map +0 -1
- package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
- package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
- package/dist/every-tOgQmaIE.mjs +0 -2
- package/dist/execution-context-BXpcbyPe.mjs +0 -2
- package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
- package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
- package/dist/identifiers-s00pGES8.mjs +0 -2
- package/dist/identifiers-s00pGES8.mjs.map +0 -1
- package/dist/judge-words-CzUyXtJ6.mjs +0 -2
- package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
- package/dist/methods-part-ZY0f2AV_.mjs +0 -2
- package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
- package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
- package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
- package/dist/pending-operation-C_eOFOBE.mjs +0 -2
- package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
- package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
- package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
- package/dist/postgres-result-DF6DmW3r.mjs +0 -2
- package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
- package/dist/query-BZVHfA0s.mjs +0 -2
- package/dist/query-BZVHfA0s.mjs.map +0 -1
- package/dist/scalar-BHCh7aUz.mjs +0 -4
- package/dist/scalar-BHCh7aUz.mjs.map +0 -1
- package/dist/schema-BYA-_bpk.mjs.map +0 -1
- package/dist/schema-introspection-D0f8cti4.mjs +0 -6
- package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
- package/dist/select-assembly-DVI7d3tf.mjs +0 -2
- package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
- package/dist/sql-3o4DOKm9.mjs +0 -2
- package/dist/sql-3o4DOKm9.mjs.map +0 -1
- package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
- package/dist/validation-CYaJ8ndO.mjs +0 -2
- package/dist/validation-CYaJ8ndO.mjs.map +0 -1
- package/dist/version-CXGIA82S.mjs +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"libsql-DuGR904j.mjs","names":[],"sources":["../src/migrations/drivers/sqlite/index.ts","../src/migrations/drivers/libsql/index.ts"],"sourcesContent":["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 AdoptionHazard,\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, sqliteTableHazards } 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 /** A trigger on the table, and what its stored definition declares beyond the snapshot. */\n override async adoptionHazards(\n tables: readonly string[],\n executeRaw: Parameters<typeof introspect>[0]\n ): Promise<readonly AdoptionHazard[]> {\n const hazards: AdoptionHazard[] = [];\n for (const table of tables) {\n const { rows } = await executeRaw<{\n type: string;\n name: string;\n sql: string | null;\n }>(\n \"SELECT type, name, sql FROM sqlite_master WHERE type IN ('table', 'trigger') AND lower(tbl_name) = lower(?) ORDER BY type, name\",\n [table]\n );\n for (const row of rows) {\n const features =\n row.type === \"trigger\"\n ? [`trigger \"${row.name}\"`]\n : sqliteTableHazards(row.sql ?? \"\");\n hazards.push(...features.map((feature) => ({ table, feature })));\n }\n }\n return hazards;\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 return introspect(\n executeRaw,\n this.target?.tables,\n this.sqliteMigrationCapability?.reservedTablePrefixes\n );\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 // A recreation builds from this definition too, so it keeps the option.\n const options = table.primaryKey?.withoutRowid ? \" WITHOUT ROWID\" : \"\";\n return `CREATE TABLE ${this.escapeIdentifier(table.name)} (\\n ${parts.join(\",\\n \")}\\n)${options}`;\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":"umBAoFA,MAAM,EAA0B,2CAK1B,EAAoB,SACpB,EAAe,sBACf,EAAc,qBACd,EAAY,sBACZ,EACJ,8EACI,EAAiB,kDACjB,EAAa,uCAEb,EAAgB,SAQhB,EACJ,kYACI,EAAe,gBACf,EAAgB,iBAChB,EAAgB,iBA4BtB,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sCDT_.mjs","names":[],"sources":["../src/migrations/drivers/sqlite/index.ts","../src/migrations/drivers/libsql/index.ts"],"sourcesContent":["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 AdoptionHazard,\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, sqliteTableHazards } 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 /** A trigger on the table, and what its stored definition declares beyond the snapshot. */\n override async adoptionHazards(\n tables: readonly string[],\n executeRaw: Parameters<typeof introspect>[0]\n ): Promise<readonly AdoptionHazard[]> {\n const hazards: AdoptionHazard[] = [];\n for (const table of tables) {\n const { rows } = await executeRaw<{\n type: string;\n name: string;\n sql: string | null;\n }>(\n \"SELECT type, name, sql FROM sqlite_master WHERE type IN ('table', 'trigger') AND lower(tbl_name) = lower(?) ORDER BY type, name\",\n [table]\n );\n for (const row of rows) {\n const features =\n row.type === \"trigger\"\n ? [`trigger \"${row.name}\"`]\n : sqliteTableHazards(row.sql ?? \"\");\n hazards.push(...features.map((feature) => ({ table, feature })));\n }\n }\n return hazards;\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 return introspect(\n executeRaw,\n this.target?.tables,\n this.sqliteMigrationCapability?.reservedTablePrefixes\n );\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 // A recreation builds from this definition too, so it keeps the option.\n const options = table.primaryKey?.withoutRowid ? \" WITHOUT ROWID\" : \"\";\n return `CREATE TABLE ${this.escapeIdentifier(table.name)} (\\n ${parts.join(\",\\n \")}\\n)${options}`;\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":"umBAoFA,MAAM,EAA0B,2CAK1B,EAAoB,SACpB,EAAe,sBACf,EAAc,qBACd,EAAY,sBACZ,EACJ,8EACI,EAAiB,kDACjB,EAAa,uCAEb,EAAgB,SAQhB,EACJ,kYACI,EAAe,gBACf,EAAgB,iBAChB,EAAgB,iBA4BtB,SAAS,eACP,EACA,EACmE,CACnE,IAAM,EAAa,IAAI,IACrB,EAAQ,IAAK,GAAQ,CAAC,EAAI,KAAK,aAAa,CAAE,EAAI,CAAC,CACpD,CACK,EAAc,IAAI,IAClB,EAAwD,EAAE,CAChE,IAAK,IAAM,KAAa,EAAS,CAC/B,IAAI,EAAO,EAAU,MAAM,CAEvB,EAAU,EAA2B,EAAM,EAAE,CACjD,KAAO,EAAU,GACf,EAAO,EAAK,MAAM,EAAQ,CAAC,WAAW,CACtC,EAAU,EAA2B,EAAM,EAAE,CAE/C,IAAM,EAAS,EAAa,KAAK,EAAK,CAChC,EAAQ,EAAY,KAAK,EAA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EAAG,gBACb,OAAQ,EACR,SAAU,EAAG,SACb,SAAU,EAAG,SACd,CAAC,GASJ,uBACE,EACA,EAC4B,CAC5B,IAAM,EAAe,KAAK,gBAAgB,EAAG,UAAW,EAAQ,CAChE,GAAI,CAAC,EACH,MAAU,MACR,mCAAmC,EAAG,UAAU,yFAEjD,CAIH,IAAM,EAAK,EAAa,YAAY,KAAM,GAAM,EAAE,OAAS,EAAG,OAAO,CACrE,GAAI,CAAC,EACH,MAAU,MACR,wCAAwC,EAAG,OAAO,wBAAwB,EAAG,UAAU,IACxF,CAIH,GAAI,EAAG,QAAQ,OAAS,EACtB,OAAO,MAAM,uBAAuB,EAAI,EAAQ,CAGlD,IAAM,EAAW,EAAG,QAAQ,GAC5B,GAAI,CAAC,EACH,MAAU,MACR,+DAA+D,EAAG,OAAO,IAC1E,CAIH,IAAM,EAAS,EAAa,QAAQ,KAAM,GAAM,EAAE,OAAS,EAAS,CACpE,GAAI,CAAC,EACH,MAAU,MACR,oCAAoC,EAAS,wBAAwB,EAAG,UAAU,IACnF,CASH,MAAO,eANO,KAAK,iBAAiB,EAAG,UAAU,CAMrB,gBALhB,KAAK,iBAAiB,EAAS,CAKK,MAFjC,KAAK,6BAA6B,EAAO,KAe5D,MAAa,EAAwB,IAAI"}
|
package/dist/libsql.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { $a as QueryResult, C as DriverResultParser, Ka as DriverTransactionOptions, Qa as QueryExecutionContext, h as Driver, li as Schema, pt as VibORMClient, qa as TransactionOptionSupport, st as DriverConfig, t as DatabaseAdapter, ut as NoExtraDriverConfigKeys, xi as LinkedClientConfig } from "./database-adapter-D62c-uC6.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{B as t,m as n,u as r}from"./error-mapping-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{B as t,m as n,u as r}from"./error-mapping-DIRlrmDK.mjs";import{n as i}from"./base-z-cH5ZBI.mjs";import{i as a}from"./validation--qS7OPmg.mjs";import{o}from"./normalized-result-B8pifWS0.mjs";import{n as s}from"./client-CVCC-D1j.mjs";import{c,m as l,p as u,r as d}from"./driver-Df88hu4U.mjs";import{c as f,i as p,l as m,n as h}from"./sqlite-utils-DcQct689.mjs";import{t as g}from"./sqlite-adapter-fIbNDvwO.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,t)=>{let n=o(e.rowsAffected,{provider:`libsql`,operation:t});return e.rows.length>0?e.rows.length:n};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:u(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,i,a,o){if(`commit`in e)throw r(this.driverName);let s=await l(()=>this.quarantineOnBusy(e,()=>e.transaction(`write`)),e=>e.close(),o?.maxWaitMs,{driverName:this.driverName,form:`callback`});return n({begin:()=>void 0,callback:()=>i(s),commit:()=>s.commit(),rollback:()=>s.rollback(),phases:t(a),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 a(`Local libSQL execution encountered SQLITE_BUSY; disconnect an owned driver, or close and replace the supplied native client, before reuse.`,{code:i.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){c(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
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-z-cH5ZBI.mjs";import{t as n}from"./migrations-BMiRjR-N.mjs";import{Sn as r}from"./serializer-
|
|
2
|
-
//# sourceMappingURL=memory-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-z-cH5ZBI.mjs";import{t as n}from"./migrations-BMiRjR-N.mjs";import{Sn as r}from"./serializer-B2kk7NAR.mjs";import{n as i}from"./canonical-json-Bl-fKFF_.mjs";import{a,c as o}from"./identity-CtW15WlB.mjs";const isCorruption=e=>e instanceof n&&e.code===t.MIGRATION_CORRUPTION;function createStorageConformanceSuite(e){return[{name:`identical content-addressed publish is idempotent`,run:async()=>{let t=e(),n=o(`hello`),i=r(n),a=await t.publishSql(i,n),s=await t.publishSql(i,n);if(a.outcome!==`created`||s.outcome!==`identical`)throw Error(`idempotent publish failed`)}},{name:`same hash with different bytes is corruption`,run:async()=>{let t=e(),n=o(`hello`),i=r(n);await t.publishSql(i,n);try{await t.publishSql(i,o(`other`))}catch(e){if(isCorruption(e))return}throw Error(`corrupt publish was accepted`)}},{name:`listStates returns only committed manifests`,run:async()=>{if((await e().listStates()).length!==0)throw Error(`fresh writer is not empty`)}},{name:`estate publish is idempotent for identical bytes`,run:async()=>{let t=e(),n=o(`{"format":"1"}`),r=await t.publishEstate(n),i=await t.publishEstate(n);if(r.outcome!==`created`||i.outcome!==`identical`)throw Error(`estate idempotent publish failed`)}},{name:`concurrent identical creates report created exactly once`,run:async()=>{let t=e(),n=o(`race-identical`),i=r(n),a=(await Promise.all(Array.from({length:8},()=>t.publishState(i,n)))).filter(e=>e.outcome===`created`).length;if(a!==1)throw Error(`${a} of 8 concurrent creates won`)}},{name:`concurrent conflicting creates keep one winner and refuse the rest`,run:async()=>{let t=e(),n=r(o(`race-conflicting`)),a=Array.from({length:8},(e,t)=>o(`{"racer":${t}}`)),s=await Promise.allSettled(a.map(e=>t.publishState(n,e))),c=a.filter((e,t)=>s[t]?.status===`fulfilled`),l=s.filter(e=>e.status===`rejected`&&isCorruption(e.reason)).length,u=await t.readState(n);if(c.length!==1||l!==7||!(u&&i(u,c[0])))throw Error(`${c.length} winners and ${l} refusals of 8 conflicting creates`)}},{name:`absent artifacts read as null`,run:async()=>{let t=e(),n=r(o(`absent`));if((await Promise.all([t.readState(n),t.readSnapshot(n),t.readSql(n)])).some(e=>e!==null))throw Error(`an absent artifact read as bytes`)}},{name:`published artifacts are listed as soon as publish returns`,run:async()=>{let t=e(),n=Array.from({length:5},(e,t)=>o(`listed-${t}`)),i=n.map(r);for(let[e,r]of i.entries())await t.publishState(r,n[e]),await t.publishSnapshot(r,n[e]),await t.publishSql(r,n[e]);if((await Promise.all([t.listStates(),t.listSnapshots(),t.listSql()])).some(e=>i.some(t=>!e.includes(t))))throw Error(`a published artifact is missing from its listing`)}},{name:`a listed state's snapshot and SQL are already readable (manifest last)`,run:async()=>{let t=e(),n=o(`manifest-last`),i=r(n),a=!1,s=(async()=>{await t.publishSnapshot(i,n),await t.publishSql(i,n),await t.publishState(i,n)})().finally(()=>{a=!0});try{for(;;){let e=a;if((await t.listStates()).includes(i))break;if(e)throw Error(`a published state is not listed`)}let[e,n]=await Promise.all([t.readSnapshot(i),t.readSql(i)]);if(!(e&&n))throw Error(`a listed state's artifacts are not readable yet`)}finally{await s}}}]}var MemoryEstateStorage=class{estate=null;states=new Map;snapshots=new Map;sql=new Map;async readEstate(){return this.estate?this.estate.slice():null}async listStates(){return[...this.states.keys()].sort()}async listSnapshots(){return[...this.snapshots.keys()].sort()}async listSql(){return[...this.sql.keys()].sort()}async readState(e){let t=this.states.get(e);return t?t.slice():null}async readSnapshot(e){let t=this.snapshots.get(e);return t?t.slice():null}async readSql(e){let t=this.sql.get(e);return t?t.slice():null}async publishEstate(e){if(this.estate&&!i(this.estate,e))throw new n(`estate.json already exists with different bytes`,t.MIGRATION_CORRUPTION);return this.estate?{outcome:`identical`}:(this.estate=e.slice(),{outcome:`created`})}async publishSnapshot(e,t){return publishMap(this.snapshots,e,t,`snapshot`)}async publishSql(e,t){return publishMap(this.sql,e,t,`sql`)}async publishState(e,r){if(!a(e))throw new n(`State id is not a SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return publishMap(this.states,e,r,`state`)}};function publishMap(e,r,a,o){let s=e.get(r);if(s){if(!i(s,a))throw new n(`${o} ${r} already holds different bytes`,t.MIGRATION_CORRUPTION);return{outcome:`identical`}}return e.set(r,a.slice()),{outcome:`created`}}export{createStorageConformanceSuite as n,MemoryEstateStorage as t};
|
|
2
|
+
//# sourceMappingURL=memory-gjKMy3Ql.mjs.map
|