viborm 1.14.2 → 1.16.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-DwFnfpED.mjs +2 -0
- package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DwFnfpED.mjs.map} +1 -1
- package/dist/adapters.d.mts +26 -10
- package/dist/adapters.mjs +1 -1
- package/dist/args-7WgBFd_f.mjs +2 -0
- package/dist/{args-764KdWMr.mjs.map → args-7WgBFd_f.mjs.map} +1 -1
- package/dist/array-literal-BOzj0E2u.mjs +2 -0
- package/dist/{array-literal-DHinAnVs.mjs.map → array-literal-BOzj0E2u.mjs.map} +1 -1
- package/dist/base-17NSFtrA.mjs +2 -0
- package/dist/base-17NSFtrA.mjs.map +1 -0
- package/dist/batch-refs-Bd8HvwUc.mjs +2 -0
- package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-Bd8HvwUc.mjs.map} +1 -1
- package/dist/better-auth.d.mts +116 -0
- package/dist/better-auth.mjs +6 -0
- package/dist/better-auth.mjs.map +1 -0
- package/dist/bind-parameter-capacity-BAFQM9Jt.mjs +2 -0
- package/dist/{bind-parameter-capacity-BMD-bxMO.mjs.map → bind-parameter-capacity-BAFQM9Jt.mjs.map} +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/bun-sqlite.mjs.map +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/cloudflare-kv.mjs.map +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache/memory.mjs.map +1 -1
- package/dist/cache.d.mts +2 -2
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/call-0bd_B9Vp.mjs +2 -0
- package/dist/{call-Cz8XUmrl.mjs.map → call-0bd_B9Vp.mjs.map} +1 -1
- package/dist/cli.mjs +6 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-D7sWgUt2.mjs +2 -0
- package/dist/client-D7sWgUt2.mjs.map +1 -0
- package/dist/client-DEfFqv4S.mjs +9 -0
- package/dist/client-DEfFqv4S.mjs.map +1 -0
- package/dist/{client-CRxfhw2y.d.mts → client-Dlz3-2JC.d.mts} +3 -3
- package/dist/client.d.mts +3 -3
- package/dist/client.mjs +1 -1
- package/dist/client.mjs.map +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/confine-CyI9IwjC.mjs +2 -0
- package/dist/{confine-DqFBTUw6.mjs.map → confine-CyI9IwjC.mjs.map} +1 -1
- package/dist/coordination-BxMskOgi.mjs +2 -0
- package/dist/coordination-BxMskOgi.mjs.map +1 -0
- package/dist/d1.d.mts +2 -30
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-BMjJiBFm.d.mts} +8476 -8386
- package/dist/datetime-physical-codec-DAF7WJpy.mjs +2 -0
- package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +1 -0
- package/dist/defaults-DAPb-tJ4.mjs +2 -0
- package/dist/{defaults-DwOHWI_M.mjs.map → defaults-DAPb-tJ4.mjs.map} +1 -1
- package/dist/{document-BVTQ-cF-.d.mts → document-CHaVF7Vn.d.mts} +36 -2
- package/dist/{driver-BBEmaJZy.d.mts → driver-BvTixv-m.d.mts} +1 -1
- package/dist/driver-diagnostics-aQ54bArn.mjs +2 -0
- package/dist/{driver-diagnostics-DW9NdckJ.mjs.map → driver-diagnostics-aQ54bArn.mjs.map} +1 -1
- package/dist/driver-kiIQS_Fd.mjs +2 -0
- package/dist/driver-kiIQS_Fd.mjs.map +1 -0
- package/dist/driver-lShUkDmf.mjs +2 -0
- package/dist/driver-lShUkDmf.mjs.map +1 -0
- 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 +2 -2
- package/dist/durable-object.mjs.map +1 -1
- package/dist/error-mapping-B9rSvgG9.mjs +2 -0
- package/dist/error-mapping-B9rSvgG9.mjs.map +1 -0
- package/dist/every-JpbiHdMb.mjs +2 -0
- package/dist/{every-tOgQmaIE.mjs.map → every-JpbiHdMb.mjs.map} +1 -1
- package/dist/execution-context-couU2tgh.mjs +2 -0
- package/dist/execution-context-couU2tgh.mjs.map +1 -0
- package/dist/{exports-COCJ8f2f.d.mts → exports-DYnTfvQo.d.mts} +1 -1
- package/dist/extension-Dh1ddrlA.mjs +2 -0
- package/dist/{extension-CGepsF-p.mjs.map → extension-Dh1ddrlA.mjs.map} +1 -1
- package/dist/fs-estate-n-QpsFqb.mjs +2 -0
- package/dist/{fs-estate-D1Nsg9G1.mjs.map → fs-estate-n-QpsFqb.mjs.map} +1 -1
- package/dist/geo-area-codec-Bti2PA2i.mjs +2 -0
- package/dist/geo-area-codec-Bti2PA2i.mjs.map +1 -0
- package/dist/id-domain-Cg65TLZ-.mjs +2 -0
- package/dist/id-domain-Cg65TLZ-.mjs.map +1 -0
- package/dist/identifier-conversion-BTDxDwDB.mjs +2 -0
- package/dist/identifier-conversion-BTDxDwDB.mjs.map +1 -0
- package/dist/identifiers-BxOf57qy.mjs +2 -0
- package/dist/identifiers-BxOf57qy.mjs.map +1 -0
- package/dist/identity-CJlRQA-m.mjs +2 -0
- package/dist/identity-CJlRQA-m.mjs.map +1 -0
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/instrumentation.mjs.map +1 -1
- package/dist/introspect-q3Rf_Xv8.mjs +2 -0
- package/dist/introspect-q3Rf_Xv8.mjs.map +1 -0
- package/dist/json-CsAdz9pg.mjs +2 -0
- package/dist/json-CsAdz9pg.mjs.map +1 -0
- package/dist/json-number-C09rsm1g.mjs +2 -0
- package/dist/{json-number-AI-SdUUn.mjs.map → json-number-C09rsm1g.mjs.map} +1 -1
- package/dist/json-parameter-D7hDrVKw.mjs +2 -0
- package/dist/{json-parameter-oQ8nGaKr.mjs.map → json-parameter-D7hDrVKw.mjs.map} +1 -1
- package/dist/judge-words-k5GCc4cV.mjs +2 -0
- package/dist/judge-words-k5GCc4cV.mjs.map +1 -0
- package/dist/key-BDH6oTyC.mjs +2 -0
- package/dist/key-BDH6oTyC.mjs.map +1 -0
- package/dist/keys-CIal55WQ.mjs +2 -0
- package/dist/{keys-BQxM4c_a.mjs.map → keys-CIal55WQ.mjs.map} +1 -1
- package/dist/keys-DZdKAd4n.mjs +2 -0
- package/dist/keys-DZdKAd4n.mjs.map +1 -0
- package/dist/libsql-DEZ0uhK2.mjs +3 -0
- package/dist/libsql-DEZ0uhK2.mjs.map +1 -0
- package/dist/libsql.d.mts +2 -20
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/light-D2wNSbzY.mjs +2 -0
- package/dist/{light-BkJe3-yW.mjs.map → light-D2wNSbzY.mjs.map} +1 -1
- package/dist/memory-BaGWNdvk.mjs +2 -0
- package/dist/{memory-G4cSuc6A.mjs.map → memory-BaGWNdvk.mjs.map} +1 -1
- package/dist/methods-part-BaNx3o7b.mjs +2 -0
- package/dist/methods-part-BaNx3o7b.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +5 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +5 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/snowflake.d.mts +5 -5
- package/dist/migrations/snowflake.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +5 -5
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.d.mts +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/durable-object.mjs.map +1 -1
- package/dist/migrations/storage/fs.d.mts +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/storage/r2.mjs.map +1 -1
- package/dist/migrations/surrealdb.d.mts +5 -5
- package/dist/migrations/surrealdb.mjs +1 -1
- package/dist/migrations/tenant.d.mts +3 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations/tenant.mjs.map +1 -1
- package/dist/migrations-DIUltjr3.mjs +2 -0
- package/dist/{migrations-BMiRjR-N.mjs.map → migrations-DIUltjr3.mjs.map} +1 -1
- package/dist/migrations.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/model-Dtd37Sky.mjs +2 -0
- package/dist/model-Dtd37Sky.mjs.map +1 -0
- package/dist/mysql-BFPF8xyv.mjs +9 -0
- package/dist/mysql-BFPF8xyv.mjs.map +1 -0
- package/dist/mysql-adapter-BFWYPoM0.mjs +2 -0
- package/dist/mysql-adapter-BFWYPoM0.mjs.map +1 -0
- package/dist/mysql2.d.mts +2 -27
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/named-statements-CkOOD__I.mjs +2 -0
- package/dist/named-statements-CkOOD__I.mjs.map +1 -0
- package/dist/named-statements-NF7Iycjk.d.mts +13 -0
- package/dist/native-types-1ewJXVks.mjs +2 -0
- package/dist/native-types-1ewJXVks.mjs.map +1 -0
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/normalized-result-D7nVkF36.mjs +2 -0
- package/dist/normalized-result-D7nVkF36.mjs.map +1 -0
- package/dist/{object-store-B_YMoW8u.d.mts → object-store-C4qmW7xf.d.mts} +4 -4
- package/dist/object-store-Chq1PMYz.mjs +2 -0
- package/dist/object-store-Chq1PMYz.mjs.map +1 -0
- package/dist/on-ZkOVmE4-.mjs +2 -0
- package/dist/{on-ylYaKuRu.mjs.map → on-ZkOVmE4-.mjs.map} +1 -1
- package/dist/on.d.mts +1 -1
- package/dist/on.mjs +1 -1
- package/dist/on.mjs.map +1 -1
- package/dist/ordering/keys.mjs +1 -1
- package/dist/ordering.d.mts +9 -3
- package/dist/ordering.mjs +10 -10
- package/dist/ordering.mjs.map +1 -1
- package/dist/pending-operation-D4gUKMxD.mjs +2 -0
- package/dist/pending-operation-D4gUKMxD.mjs.map +1 -0
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/permissions.mjs.map +1 -1
- package/dist/pg.d.mts +16 -99
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +3 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/physical-DO4PEYcc.mjs +2 -0
- package/dist/physical-DO4PEYcc.mjs.map +1 -0
- package/dist/pinned-session-Y7-2pRBJ.mjs +2 -0
- package/dist/pinned-session-Y7-2pRBJ.mjs.map +1 -0
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-DHjdvjwk.d.mts → planner-C-zjj19U.d.mts} +123 -1
- package/dist/postgres-DQQE2ys_.mjs +34 -0
- package/dist/postgres-DQQE2ys_.mjs.map +1 -0
- package/dist/postgres-adapter-BpLizOaK.mjs +2 -0
- package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-BpLizOaK.mjs.map} +1 -1
- package/dist/postgres-adapter-psTVfuw7.mjs +2 -0
- package/dist/postgres-adapter-psTVfuw7.mjs.map +1 -0
- package/dist/postgres-result-133boRW-.mjs +2 -0
- package/dist/postgres-result-133boRW-.mjs.map +1 -0
- package/dist/postgres.d.mts +27 -59
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/provider-limits-Bcsz0EJv.mjs +2 -0
- package/dist/provider-limits-Bcsz0EJv.mjs.map +1 -0
- package/dist/provider-parameter-snapshot-cyTUDutH.mjs +2 -0
- package/dist/provider-parameter-snapshot-cyTUDutH.mjs.map +1 -0
- package/dist/quantized-BKBs0joq.mjs +2 -0
- package/dist/quantized-BKBs0joq.mjs.map +1 -0
- package/dist/query-BTb6iakn.mjs +2 -0
- package/dist/query-BTb6iakn.mjs.map +1 -0
- package/dist/query-backend-TisPjCPF.mjs +2 -0
- package/dist/query-backend-TisPjCPF.mjs.map +1 -0
- package/dist/query-inspection-DwYBKSDG.mjs +2 -0
- package/dist/query-inspection-DwYBKSDG.mjs.map +1 -0
- package/dist/raw-DqEb71JZ.mjs +2 -0
- package/dist/raw-DqEb71JZ.mjs.map +1 -0
- package/dist/relation-bound-CSNKLyDy.mjs +2 -0
- package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-CSNKLyDy.mjs.map} +1 -1
- package/dist/result-parsing-BbffueEX.mjs +2 -0
- package/dist/{result-parsing-B0Y4KGDT.mjs.map → result-parsing-BbffueEX.mjs.map} +1 -1
- package/dist/routed-operations-CcKOdn51.mjs +2 -0
- package/dist/{routed-operations-wytpbYKv.mjs.map → routed-operations-CcKOdn51.mjs.map} +1 -1
- package/dist/rows-of-Bgl9GVtK.mjs +2 -0
- package/dist/rows-of-Bgl9GVtK.mjs.map +1 -0
- package/dist/rule-words-DMbQuvD2.mjs +2 -0
- package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-DMbQuvD2.mjs.map} +1 -1
- package/dist/scalar-Dm9brvAU.mjs +4 -0
- package/dist/scalar-Dm9brvAU.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 +6 -4
- package/dist/schema/json.mjs +1 -1
- package/dist/schema-DDkAUfOb.mjs +2 -0
- package/dist/schema-DDkAUfOb.mjs.map +1 -0
- package/dist/schema-DqR_Kcje.mjs +2 -0
- package/dist/schema-DqR_Kcje.mjs.map +1 -0
- package/dist/schema-introspection-Bbo4DN_d.mjs +4 -0
- package/dist/schema-introspection-Bbo4DN_d.mjs.map +1 -0
- package/dist/schema.d.mts +2 -2
- package/dist/schema.mjs +1 -1
- package/dist/select-assembly-CEpNu-Gw.mjs +2 -0
- package/dist/select-assembly-CEpNu-Gw.mjs.map +1 -0
- package/dist/serializer-ettLu5xG.mjs +33 -0
- package/dist/serializer-ettLu5xG.mjs.map +1 -0
- package/dist/settle-Pui-1tfJ.mjs +2 -0
- package/dist/{settle-1cy5x_52.mjs.map → settle-Pui-1tfJ.mjs.map} +1 -1
- package/dist/settled-DYYPcaBX.mjs +2 -0
- package/dist/{settled-BjyuA76m.mjs.map → settled-DYYPcaBX.mjs.map} +1 -1
- package/dist/snowflake-BfF8xwfP.mjs +2 -0
- package/dist/{snowflake-UOCC820W.mjs.map → snowflake-BfF8xwfP.mjs.map} +1 -1
- package/dist/snowflake.d.mts +3 -3
- package/dist/snowflake.mjs +2 -2
- package/dist/snowflake.mjs.map +1 -1
- package/dist/soft-delete.d.mts +9 -3
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/{spans-XDUFeTzC.mjs → spans-DwDXMvyd.mjs} +1 -1
- package/dist/{spans-XDUFeTzC.mjs.map → spans-DwDXMvyd.mjs.map} +1 -1
- package/dist/sql-Bu63iAfT.mjs +2 -0
- package/dist/sql-Bu63iAfT.mjs.map +1 -0
- package/dist/{sql-BVZ8QefY.d.mts → sql-C4_sFNDm.d.mts} +18 -5
- package/dist/sql-statement-tokens-Z5Ta4iDB.mjs +3 -0
- package/dist/{sql-statement-tokens-DbeMwHra.mjs.map → sql-statement-tokens-Z5Ta4iDB.mjs.map} +1 -1
- package/dist/sql-tegqTqGq.mjs +2 -0
- package/dist/sql-tegqTqGq.mjs.map +1 -0
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-Cb-SJw2f.mjs +2 -0
- package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +1 -0
- package/dist/sqlite-statement-classifier-JBHiQO6Q.mjs +2 -0
- package/dist/{sqlite-statement-classifier-BAHl-WXS.mjs.map → sqlite-statement-classifier-JBHiQO6Q.mjs.map} +1 -1
- package/dist/sqlite-utils-Bfmtkt1b.mjs +2 -0
- package/dist/sqlite-utils-Bfmtkt1b.mjs.map +1 -0
- package/dist/sqlite3.d.mts +2 -46
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/standard-sql-Bl2OHGfi.mjs +6 -0
- package/dist/standard-sql-Bl2OHGfi.mjs.map +1 -0
- package/dist/suppressed-failure-CFUDJrUw.mjs +2 -0
- package/dist/{suppressed-failure-CQkQsMVS.mjs.map → suppressed-failure-CFUDJrUw.mjs.map} +1 -1
- package/dist/surrealdb.d.mts +2 -2
- package/dist/surrealdb.mjs +1 -1
- package/dist/surrealdb.mjs.map +1 -1
- package/dist/surrealql-DY74AUeD.mjs +2 -0
- package/dist/surrealql-DY74AUeD.mjs.map +1 -0
- package/dist/time-step-DJaIhpAz.mjs +2 -0
- package/dist/time-step-DJaIhpAz.mjs.map +1 -0
- package/dist/transaction-Bv5nyp-U.mjs +2 -0
- package/dist/{transaction-BNomMtme.mjs.map → transaction-Bv5nyp-U.mjs.map} +1 -1
- package/dist/transaction-operation-CaWzo7gE.mjs +2 -0
- package/dist/{transaction-operation-CVVJxQ19.mjs.map → transaction-operation-CaWzo7gE.mjs.map} +1 -1
- package/dist/types-Dy33vBdd.mjs +2 -0
- package/dist/{types-DtDnXhwa.mjs.map → types-Dy33vBdd.mjs.map} +1 -1
- package/dist/unit-DUPX5Sdd.mjs +2 -0
- package/dist/{unit-BhHbZyuJ.mjs.map → unit-DUPX5Sdd.mjs.map} +1 -1
- package/dist/unit-words-BXpLpyr2.mjs +2 -0
- package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BXpLpyr2.mjs.map} +1 -1
- package/dist/utils-BHkJsduV.mjs +26 -0
- package/dist/{utils-CpAojrCj.mjs.map → utils-BHkJsduV.mjs.map} +1 -1
- package/dist/v1-parse-shared-cJ-uD14P.mjs +2 -0
- package/dist/v1-parse-shared-cJ-uD14P.mjs.map +1 -0
- package/dist/validation-ATmgN5RE.mjs +2 -0
- package/dist/validation-ATmgN5RE.mjs.map +1 -0
- package/dist/validation-BHjx13zG.mjs +2 -0
- package/dist/validation-BHjx13zG.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-DMzH5Tz0.mjs +2 -0
- package/dist/validator-DMzH5Tz0.mjs.map +1 -0
- package/dist/value-guards-CBVIJXlI.mjs +2 -0
- package/dist/{value-guards-CBuxSC66.mjs.map → value-guards-CBVIJXlI.mjs.map} +1 -1
- package/dist/values-Ch2cTlss.mjs +2 -0
- package/dist/{values-B4aj1i1f.mjs.map → values-Ch2cTlss.mjs.map} +1 -1
- package/dist/version-0BDwfy7C.mjs +2 -0
- package/dist/{version-CXGIA82S.mjs.map → version-0BDwfy7C.mjs.map} +1 -1
- package/dist/view-CHgjF2BO.mjs +2 -0
- package/dist/view-CHgjF2BO.mjs.map +1 -0
- package/dist/write-sinks-Bei5vFHP.mjs +2 -0
- package/dist/{write-sinks-3IKCDF-S.mjs.map → write-sinks-Bei5vFHP.mjs.map} +1 -1
- package/package.json +50 -37
- package/dist/adapter-internals-DOqI8IlQ.mjs +0 -2
- package/dist/adapter-internals-DOqI8IlQ.mjs.map +0 -1
- package/dist/adapter-namespace-DaRiTIIf.mjs +0 -2
- package/dist/adapter-result-parser-3WP82Cm-.mjs +0 -2
- package/dist/adapter-result-parser-3WP82Cm-.mjs.map +0 -1
- package/dist/args-764KdWMr.mjs +0 -2
- package/dist/array-literal-DHinAnVs.mjs +0 -2
- package/dist/base-z-cH5ZBI.mjs +0 -2
- package/dist/base-z-cH5ZBI.mjs.map +0 -1
- package/dist/batch-refs-C-gx7A4-.mjs +0 -2
- package/dist/bind-parameter-capacity-BMD-bxMO.mjs +0 -2
- package/dist/call-Cz8XUmrl.mjs +0 -2
- package/dist/canonical-json-Bl-fKFF_.mjs +0 -2
- package/dist/canonical-json-Bl-fKFF_.mjs.map +0 -1
- package/dist/chunk-BuuaeEvq.mjs +0 -1
- package/dist/client-DRpX3-vw.mjs +0 -2
- package/dist/client-DRpX3-vw.mjs.map +0 -1
- package/dist/client-y7TV0PRZ.mjs +0 -9
- package/dist/client-y7TV0PRZ.mjs.map +0 -1
- package/dist/confine-DqFBTUw6.mjs +0 -2
- package/dist/coordination-6qZHx_kl.mjs +0 -2
- package/dist/coordination-6qZHx_kl.mjs.map +0 -1
- package/dist/current-DBTlPsQg.mjs +0 -2
- package/dist/current-DBTlPsQg.mjs.map +0 -1
- package/dist/datetime-physical-codec-Dj-APo9f.mjs +0 -2
- package/dist/datetime-physical-codec-Dj-APo9f.mjs.map +0 -1
- package/dist/defaults-DwOHWI_M.mjs +0 -2
- package/dist/driver-BGVcgnIX.mjs +0 -2
- package/dist/driver-BGVcgnIX.mjs.map +0 -1
- package/dist/driver-BIXhOH2_.mjs +0 -2
- package/dist/driver-BIXhOH2_.mjs.map +0 -1
- package/dist/driver-diagnostics-DW9NdckJ.mjs +0 -2
- 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/extension-CGepsF-p.mjs +0 -2
- package/dist/fs-estate-D1Nsg9G1.mjs +0 -2
- package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
- package/dist/geo-area-codec-mHrM3b9A.mjs.map +0 -1
- package/dist/hydration-A3zffFWP.mjs +0 -2
- package/dist/hydration-A3zffFWP.mjs.map +0 -1
- package/dist/identifier-conversion-DHYPTgzr.mjs +0 -2
- package/dist/identifier-conversion-DHYPTgzr.mjs.map +0 -1
- package/dist/identifiers-s00pGES8.mjs +0 -2
- package/dist/identifiers-s00pGES8.mjs.map +0 -1
- package/dist/identity-CtW15WlB.mjs +0 -2
- package/dist/identity-CtW15WlB.mjs.map +0 -1
- package/dist/introspect-Bm6xnXcG.mjs +0 -2
- package/dist/introspect-Bm6xnXcG.mjs.map +0 -1
- package/dist/json-DgMc8-GU.mjs +0 -2
- package/dist/json-DgMc8-GU.mjs.map +0 -1
- package/dist/json-number-AI-SdUUn.mjs +0 -2
- package/dist/json-parameter-oQ8nGaKr.mjs +0 -2
- package/dist/judge-words-CzUyXtJ6.mjs +0 -2
- package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
- package/dist/key-hxFFCKed.mjs +0 -2
- package/dist/key-hxFFCKed.mjs.map +0 -1
- package/dist/keys-BQxM4c_a.mjs +0 -2
- package/dist/libsql-DuGR904j.mjs +0 -3
- package/dist/libsql-DuGR904j.mjs.map +0 -1
- package/dist/light-BkJe3-yW.mjs +0 -2
- package/dist/memory-G4cSuc6A.mjs +0 -2
- package/dist/methods-part-ZY0f2AV_.mjs +0 -2
- package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
- package/dist/migrations-BMiRjR-N.mjs +0 -2
- package/dist/mysql-BNXWfTOo.mjs +0 -100
- package/dist/mysql-BNXWfTOo.mjs.map +0 -1
- package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
- package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
- package/dist/native-types-DgjMUikz.mjs +0 -2
- package/dist/native-types-DgjMUikz.mjs.map +0 -1
- package/dist/normalized-result-B8pifWS0.mjs +0 -2
- package/dist/normalized-result-B8pifWS0.mjs.map +0 -1
- package/dist/object-store-DS0F0yZX.mjs +0 -2
- package/dist/object-store-DS0F0yZX.mjs.map +0 -1
- package/dist/on-ylYaKuRu.mjs +0 -2
- package/dist/pending-operation-C_eOFOBE.mjs +0 -2
- package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
- package/dist/physical-CeE2nYmI.mjs +0 -2
- package/dist/physical-CeE2nYmI.mjs.map +0 -1
- package/dist/pinned-session-DCoAZDOz.mjs +0 -2
- package/dist/pinned-session-DCoAZDOz.mjs.map +0 -1
- package/dist/postgres-CDdh5dSP.mjs +0 -437
- package/dist/postgres-CDdh5dSP.mjs.map +0 -1
- package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
- package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
- package/dist/postgres-adapter-axapXX8d.mjs +0 -2
- package/dist/postgres-result-DF6DmW3r.mjs +0 -2
- package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
- package/dist/provider-limits-Ccsb8PTb.mjs +0 -2
- package/dist/provider-limits-Ccsb8PTb.mjs.map +0 -1
- package/dist/provider-parameter-snapshot-BikrgKqI.mjs +0 -2
- package/dist/provider-parameter-snapshot-BikrgKqI.mjs.map +0 -1
- package/dist/query-BZVHfA0s.mjs +0 -2
- package/dist/query-BZVHfA0s.mjs.map +0 -1
- package/dist/query-inspection-BoG-yAln.mjs +0 -2
- package/dist/query-inspection-BoG-yAln.mjs.map +0 -1
- package/dist/raw-Dyq6Y6UX.mjs +0 -2
- package/dist/raw-Dyq6Y6UX.mjs.map +0 -1
- package/dist/relation-bound-ku_cMdye.mjs +0 -2
- package/dist/result-parsing-B0Y4KGDT.mjs +0 -2
- package/dist/routed-operations-wytpbYKv.mjs +0 -2
- package/dist/rule-words-ZIGm7cDm.mjs +0 -2
- package/dist/scalar-BHCh7aUz.mjs +0 -4
- package/dist/scalar-BHCh7aUz.mjs.map +0 -1
- package/dist/schema-BYA-_bpk.mjs +0 -2
- package/dist/schema-BYA-_bpk.mjs.map +0 -1
- package/dist/schema-CFIaebgi.mjs +0 -2
- package/dist/schema-CFIaebgi.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/serializer-rBq3v1xr.mjs +0 -51
- package/dist/serializer-rBq3v1xr.mjs.map +0 -1
- package/dist/settle-1cy5x_52.mjs +0 -2
- package/dist/settled-BjyuA76m.mjs +0 -2
- package/dist/snowflake-UOCC820W.mjs +0 -2
- package/dist/sql-3o4DOKm9.mjs +0 -2
- package/dist/sql-3o4DOKm9.mjs.map +0 -1
- package/dist/sql-Dl6nykFV.mjs +0 -2
- package/dist/sql-Dl6nykFV.mjs.map +0 -1
- package/dist/sql-statement-tokens-DbeMwHra.mjs +0 -3
- package/dist/sqlite-adapter-Ad0d-m2t.mjs +0 -2
- package/dist/sqlite-adapter-Ad0d-m2t.mjs.map +0 -1
- package/dist/sqlite-statement-classifier-BAHl-WXS.mjs +0 -2
- package/dist/sqlite-utils-BRvbmlQ1.mjs +0 -2
- package/dist/sqlite-utils-BRvbmlQ1.mjs.map +0 -1
- package/dist/standard-sql-qLcQyCtK.mjs +0 -6
- package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
- package/dist/suppressed-failure-CQkQsMVS.mjs +0 -2
- package/dist/surrealql-C1dp1sWw.mjs +0 -2
- package/dist/surrealql-C1dp1sWw.mjs.map +0 -1
- package/dist/to-many-BybuKQM1.mjs +0 -2
- package/dist/to-many-BybuKQM1.mjs.map +0 -1
- package/dist/transaction-BNomMtme.mjs +0 -2
- package/dist/transaction-operation-CVVJxQ19.mjs +0 -2
- package/dist/types-DtDnXhwa.mjs +0 -2
- package/dist/unit-BhHbZyuJ.mjs +0 -2
- package/dist/unit-words-CT0yeqfZ.mjs +0 -2
- package/dist/utils-CpAojrCj.mjs +0 -26
- package/dist/validation--qS7OPmg.mjs +0 -2
- package/dist/validation--qS7OPmg.mjs.map +0 -1
- package/dist/validation-CYaJ8ndO.mjs +0 -2
- package/dist/validation-CYaJ8ndO.mjs.map +0 -1
- package/dist/validator-CZLW7aR3.mjs +0 -2
- package/dist/validator-CZLW7aR3.mjs.map +0 -1
- package/dist/value-guards-CBuxSC66.mjs +0 -2
- package/dist/values-B4aj1i1f.mjs +0 -2
- package/dist/version-CXGIA82S.mjs +0 -2
- package/dist/write-sinks-3IKCDF-S.mjs +0 -2
- /package/dist/{contract-CrIB-3ZJ.d.mts → contract-CxJn0_cV.d.mts} +0 -0
package/dist/soft-delete.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { F as Exact, I as Extension, L as Facts, O as AnyTarget, Sr as PendingOperation, U as PlacedArgument, Vr as OperationPayload, at as DelegateOperationPayload, it as DelegateOperationArgs, mt as VibORMConfig, ot as DelegateOperationResult, wi as ClientSchema } from "./database-adapter-BMjJiBFm.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/soft-delete/index.d.ts
|
|
4
4
|
interface SoftDeleteModel {
|
|
@@ -28,8 +28,14 @@ type SoftDeleteModels<T extends AnyTarget> = { readonly [M in keyof ClientSchema
|
|
|
28
28
|
readonly deletedBy?: ScalarsOf<T, M>;
|
|
29
29
|
} };
|
|
30
30
|
type ScalarsOf<T extends AnyTarget, M$1> = M$1 extends keyof ClientSchema<T["config"]> ? Extract<keyof ClientSchema<T["config"]>[M$1]["~"]["state"]["scalars"], string> : never;
|
|
31
|
-
/**
|
|
32
|
-
|
|
31
|
+
/**
|
|
32
|
+
* What `softDelete(config)` adds: its two arguments, the models it hides rows
|
|
33
|
+
* of, the methods. A view it lists is filtered as it is read, and gains no
|
|
34
|
+
* method: each one writes.
|
|
35
|
+
*/
|
|
36
|
+
type SoftDeleteFacts<T extends AnyTarget, Models> = Facts<Record<never, never>, { readonly [K in keyof Models & keyof ClientSchema<T["config"]> as ClientSchema<T["config"]>[K]["~"]["state"] extends {
|
|
37
|
+
readonly view: object;
|
|
38
|
+
} ? never : K]: SoftDeleteMethods<T["config"], K> }, {
|
|
33
39
|
readonly deleted: PlacedArgument<"without" | "with" | "only", PropertyKey, "findMany" | "findFirst" | "findUnique" | "findFirstOrThrow" | "findUniqueOrThrow" | "count" | "aggregate" | "groupBy" | "exist" | "update" | "updateMany" | "upsert" | "delete" | "deleteMany">;
|
|
34
40
|
readonly mode: PlacedArgument<"soft" | "hard", keyof Models, "delete" | "deleteMany">;
|
|
35
41
|
}, Extract<keyof Models, string>>;
|
package/dist/soft-delete.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{r as e}from"./validation-ATmgN5RE.mjs";import{t}from"./extension-Dh1ddrlA.mjs";import{n}from"./methods-part-BaNx3o7b.mjs";import{o as r}from"./on-ZkOVmE4-.mjs";import{i,n as a}from"./args-7WgBFd_f.mjs";import{d as o,o as s,r as c,u as l}from"./rule-words-DMbQuvD2.mjs";import{a as u,c as d}from"./judge-words-k5GCc4cV.mjs";const f=`viborm.softDelete`;function p(t,n){for(let[r,{deletedAt:i}]of n){let n=Object.hasOwn(t,r)?t[r][`~`].state.scalars:void 0;if(!(n&&Object.hasOwn(n,i)))continue;let a=n[i][`~`].state;if(a.type!==`datetime`||a.array||!a.nullable)throw new e(`softDelete: ${r}.${i} must be a nullable DateTime field (s.dateTime().nullable()): a live row holds null there.`,{meta:{extension:f}})}}const m=(e,t)=>function(n={}){return this[e]({...n,...t})};function h(h){if(h.actorId!==void 0&&h.actor!==void 0)throw new e(`softDelete: give actorId, not both actorId and actor (its former name).`,{meta:{extension:f}});let g=h.actorId??h.actor??null,_=Object.entries(h.models),v=_.map(([e])=>e);return t(f,a({deleted:i(`without`,`with`,`only`).default(`without`).on(r),mode:i(`soft`,`hard`).on([`delete`,`deleteMany`]).models(v)}),d(e=>(p(e,_),Object.fromEntries(_.map(([e,{deletedAt:t,deletedBy:n}])=>[e,{root:[o(c(`deleted`),`without`,{[t]:null}),o(c(`deleted`),`only`,{[t]:{not:null}})],related:l(c(`deleted`),`with`,{[t]:null}),delete:{instead:u(l(c(`mode`),`hard`,{[t]:s,...n?{[n]:g}:{}}))}}])))),n(()=>Object.fromEntries(_.map(([e,{deletedAt:t,deletedBy:n}])=>{let r={data:{[t]:null,...n?{[n]:null}:{}},deleted:`only`},i={deleted:`only`,mode:`hard`};return[e,{restore:m(`update`,r),restoreMany:m(`updateMany`,r),purge:m(`delete`,i),purgeMany:m(`deleteMany`,i)}]}))))}export{h as softDelete};
|
|
2
2
|
//# sourceMappingURL=soft-delete.mjs.map
|
package/dist/soft-delete.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"soft-delete.mjs","names":[],"sources":["../src/soft-delete/index.ts"],"sourcesContent":["// viborm/soft-delete: the entire extension.\n\nimport type { OperationPayload } from \"../client/exports\"; // public today\nimport { ClientInitializationError } from \"../errors\"; // viborm's own class\nimport { args, oneOf } from \"../extensions/args\";\nimport { extension } from \"../extensions/extension\";\nimport { keep } from \"../extensions/judge-words\";\nimport { modelMethods } from \"../extensions/methods-part\";\nimport { selecting } from \"../extensions/on\";\nimport { rule } from \"../extensions/rule\";\nimport { arg, now, unless, when } from \"../extensions/rule-words\";\nimport type {\n AnyTarget,\n ClientSchema,\n DelegateOperationArgs,\n DelegateOperationPayload,\n DelegateOperationResult,\n EmptyFacts,\n Exact,\n Extension,\n Facts,\n PendingOperation,\n PlacedArgument,\n Target,\n VibORMConfig,\n} from \"../index\";\n\nexport interface SoftDeleteModel {\n readonly deletedAt: string; // a nullable DateTime field of this model\n readonly deletedBy?: string; // optional scalar field for the actor\n}\nexport interface SoftDeleteConfig {\n readonly models: Readonly<Record<string, SoftDeleteModel>>;\n /** What a delete writes into `deletedBy`, fixed per derived client. */\n readonly actorId?: string | number | bigint;\n /** `actorId`'s name before 1.9.1, still accepted (`actor` names the request's actor in `permissions`). */\n readonly actor?: string | number | bigint;\n}\n\nconst NAME = \"viborm.softDelete\";\n\n// restore and purge take the model's own update and delete arguments\n// (restore minus `data`); other keys are flagged.\n// They are read from the delegate's own client (`Self`): written apart from\n// any client, the extension's own target knows no model.\ntype ArgsOf<\n C extends VibORMConfig,\n K,\n O extends \"update\" | \"updateMany\" | \"delete\" | \"deleteMany\",\n Self,\n> = DelegateOperationPayload<\n Self,\n O,\n OperationPayload<O, ClientSchema<C>[K & keyof ClientSchema<C>]>\n>;\ntype RestoreArgs<\n C extends VibORMConfig,\n K,\n O extends \"update\" | \"updateMany\",\n Self,\n> = Omit<ArgsOf<C, K, O, Self>, \"data\">;\ntype PurgeManyArgs<C extends VibORMConfig, K, Self> = NonNullable<\n ArgsOf<C, K, \"deleteMany\", Self>\n>;\ntype NoExtra<A, R> = A & Record<Exclude<keyof A, keyof R>, never>; // flags data and typos\n\n// Each result is typed from the delegate the method is called on (`Self`),\n// so it follows every extension applied after this one: a later rule\n// that hides rows types a to-one relation `| null`, a later `defaultOmit` drops a\n// field. Called off its delegate (destructured), its result is `unknown`:\n// using it is a type error, not a silent `never`. A type alias, not an interface: a method record.\n// Exported so an exported client's declaration names it instead of spelling\n// its arguments out.\nexport type SoftDeleteMethods<C extends VibORMConfig, K> = {\n restore<\n Self,\n const A extends DelegateOperationArgs<\n Self,\n RestoreArgs<C, K, \"update\", Self>\n >,\n >(\n this: Self,\n args: NoExtra<A, RestoreArgs<C, K, \"update\", Self>>\n ): PendingOperation<DelegateOperationResult<Self, \"update\", A>>;\n restoreMany<Self, A extends RestoreArgs<C, K, \"updateMany\", Self>>(\n this: Self,\n args: NoExtra<A, RestoreArgs<C, K, \"updateMany\", Self>>\n ): PendingOperation<DelegateOperationResult<Self, \"updateMany\", A>>;\n purge<\n Self,\n const A extends DelegateOperationArgs<Self, ArgsOf<C, K, \"delete\", Self>>,\n >(\n this: Self,\n args: NoExtra<A, ArgsOf<C, K, \"delete\", Self>>\n ): PendingOperation<DelegateOperationResult<Self, \"delete\", A>>;\n purgeMany<\n Self,\n A extends PurgeManyArgs<C, K, Self> = PurgeManyArgs<C, K, Self>,\n >(\n this: Self,\n args?: NoExtra<A, PurgeManyArgs<C, K, Self>>\n ): PendingOperation<DelegateOperationResult<Self, \"deleteMany\", A>>;\n};\n\n/** Each model's markers, as the client `$extends` is called on has them. */\ntype SoftDeleteModels<T extends AnyTarget> = {\n readonly [M in keyof ClientSchema<T[\"config\"]> & string]?: {\n readonly deletedAt: ScalarsOf<T, M>;\n readonly deletedBy?: ScalarsOf<T, M>;\n };\n};\ntype ScalarsOf<T extends AnyTarget, M> = M extends keyof ClientSchema<\n T[\"config\"]\n>\n ? Extract<keyof ClientSchema<T[\"config\"]>[M][\"~\"][\"state\"][\"scalars\"], string>\n : never;\n\n/** What `softDelete(config)` adds: its two arguments, the models it hides rows of, the methods. */\ntype SoftDeleteFacts<T extends AnyTarget, Models> = Facts<\n Record<never, never>,\n {\n readonly [K in keyof Models &\n keyof ClientSchema<T[\"config\"]>]: SoftDeleteMethods<T[\"config\"], K>;\n },\n {\n // A mode chooses rows a call selects: a create selects none. Spelled\n // out, so an exported client's declaration needs no other name.\n readonly deleted: PlacedArgument<\n \"without\" | \"with\" | \"only\",\n PropertyKey,\n | \"findMany\"\n | \"findFirst\"\n | \"findUnique\"\n | \"findFirstOrThrow\"\n | \"findUniqueOrThrow\"\n | \"count\"\n | \"aggregate\"\n | \"groupBy\"\n | \"exist\"\n | \"update\"\n | \"updateMany\"\n | \"upsert\"\n | \"delete\"\n | \"deleteMany\"\n >;\n readonly mode: PlacedArgument<\n \"soft\" | \"hard\",\n keyof Models,\n \"delete\" | \"deleteMany\"\n >;\n },\n Extract<keyof Models, string>\n>;\n\n/** Refuse a marker that is not a nullable, single DateTime field. */\nfunction admitMarkers(\n schema: VibORMConfig[\"schema\"],\n entries: readonly (readonly [string, SoftDeleteModel])[]\n): void {\n for (const [name, { deletedAt }] of entries) {\n const scalars = Object.hasOwn(schema, name)\n ? schema[name]![\"~\"].state.scalars\n : undefined;\n if (!(scalars && Object.hasOwn(scalars, deletedAt))) continue;\n const state = scalars[deletedAt]![\"~\"].state;\n if (state.type !== \"datetime\" || state.array || !state.nullable)\n throw new ClientInitializationError(\n `softDelete: ${name}.${deletedAt} must be a nullable DateTime field (s.dateTime().nullable()): a live row holds null there.`,\n { meta: { extension: NAME } }\n );\n }\n}\n\n/** No client: what an extension written apart from one is built against. */\ntype Untyped = Target<\n VibORMConfig<Record<never, never>>,\n AnyTarget[\"state\"],\n EmptyFacts\n>;\ntype Schema = VibORMConfig[\"schema\"];\n\n/** A delegate as the methods call it: its own operations. */\ntype Self = Readonly<Record<string, (args: object) => unknown>>;\n\n/** A method that calls the delegate's `operation` with `added` over what it is given. */\nconst method = (operation: string, added: object) =>\n function (this: Self, given: object = {}) {\n return this[operation]!({ ...given, ...added });\n };\n\n/**\n * Keep deleted rows as tombstones: `client.$extends(softDelete({ models: {\n * post: { deletedAt: \"deletedAt\" } } }))`. One step, applied in any order\n * with the other extensions.\n */\nexport function softDelete<T extends AnyTarget, const Models>(config: {\n readonly models: Models &\n SoftDeleteModels<T> &\n NoInfer<Exact<Models, SoftDeleteModels<T>>>;\n /** What a delete writes into `deletedBy`, fixed per extension. */\n readonly actorId?: string | number | bigint;\n /** `actorId`'s name before 1.9.1, still accepted. */\n readonly actor?: string | number | bigint;\n}): Extension<T, SoftDeleteFacts<T, Models>>;\nexport function softDelete(config: SoftDeleteConfig): unknown {\n if (config.actorId !== undefined && config.actor !== undefined)\n throw new ClientInitializationError(\n \"softDelete: give actorId, not both actorId and actor (its former name).\",\n { meta: { extension: NAME } }\n );\n const actor = config.actorId ?? config.actor ?? null;\n const entries = Object.entries(config.models);\n const managed = entries.map(([model]) => model);\n // Built against no client: the entries are read from the schema the\n // extension is applied to, and checked there; `softDelete`'s own\n // signature types what it adds.\n return extension<Untyped>(\n NAME,\n args({\n deleted: oneOf(\"without\", \"with\", \"only\")\n .default(\"without\")\n .on(selecting),\n // Named, not `deletes`: that set brings what watches writes.\n mode: oneOf(\"soft\", \"hard\").on([\"delete\", \"deleteMany\"]).models(managed),\n }),\n // Read where the extension is applied: a marker that is not a nullable\n // DateTime is refused there, before its filters would refuse it less\n // clearly (a string field would fail at the first delete).\n rule<Untyped, (schema: Schema) => object>((schema: Schema) => {\n admitMarkers(schema, entries);\n return Object.fromEntries(\n entries.map(([model, { deletedAt, deletedBy }]) => [\n model,\n {\n root: [\n when(arg(\"deleted\"), \"without\", { [deletedAt]: null }),\n when(arg(\"deleted\"), \"only\", { [deletedAt]: { not: null } }),\n ],\n related: unless(arg(\"deleted\"), \"with\", { [deletedAt]: null }),\n delete: {\n instead: keep(\n unless(arg(\"mode\"), \"hard\", {\n [deletedAt]: now,\n ...(deletedBy ? { [deletedBy]: actor } : {}),\n })\n ),\n },\n },\n ])\n );\n }),\n // The methods read nothing typed at this step (each result is typed from\n // the delegate it is called on), so later extensions may hide rows or\n // omit fields freely.\n modelMethods((): object =>\n Object.fromEntries(\n entries.map(([model, { deletedAt, deletedBy }]) => {\n // Tombstones only: `deleted: \"only\"` overrides a caller's value.\n const restore = {\n data: {\n [deletedAt]: null,\n ...(deletedBy ? { [deletedBy]: null } : {}),\n },\n deleted: \"only\",\n };\n const purge = { deleted: \"only\", mode: \"hard\" };\n return [\n model,\n {\n restore: method(\"update\", restore),\n restoreMany: method(\"updateMany\", restore),\n purge: method(\"delete\", purge),\n purgeMany: method(\"deleteMany\", purge),\n },\n ];\n })\n )\n )\n );\n}\n"],"mappings":"6XAuCA,MAAM,EAAO,oBAoHb,SAAS,aACP,EACA,EACM,CACN,IAAK,GAAM,CAAC,EAAM,CAAE,gBAAgB,EAAS,CAC3C,IAAM,EAAU,OAAO,OAAO,EAAQ,EAAK,CACvC,EAAO,GAAO,KAAK,MAAM,QACzB,IAAA,GACJ,GAAI,EAAE,GAAW,OAAO,OAAO,EAAS,EAAU,EAAG,SACrD,IAAM,EAAQ,EAAQ,GAAY,KAAK,MACvC,GAAI,EAAM,OAAS,YAAc,EAAM,OAAS,CAAC,EAAM,SACrD,MAAM,IAAI,EACR,eAAe,EAAK,GAAG,EAAU,4FACjC,CAAE,KAAM,CAAE,UAAW,EAAM,CAAE,CAC9B,EAgBP,MAAM,QAAU,EAAmB,IACjC,SAAsB,EAAgB,EAAE,CAAE,CACx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Q,CAAE,QAAS,OAAQ,KAAM,OAAQ,CAC/C,MAAO,CACL,EACA,CACE,QAAS,OAAO,SAAU,EAAQ,CAClC,YAAa,OAAO,aAAc,EAAQ,CAC1C,MAAO,OAAO,SAAU,EAAM,CAC9B,UAAW,OAAO,aAAc,EAAM,CACvC,CACF,EACD,CACH,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"soft-delete.mjs","names":[],"sources":["../src/soft-delete/index.ts"],"sourcesContent":["// viborm/soft-delete: the entire extension.\n\nimport type { OperationPayload } from \"../client/exports\"; // public today\nimport { ClientInitializationError } from \"../errors\"; // viborm's own class\nimport { args, oneOf } from \"../extensions/args\";\nimport { extension } from \"../extensions/extension\";\nimport { keep } from \"../extensions/judge-words\";\nimport { modelMethods } from \"../extensions/methods-part\";\nimport { selecting } from \"../extensions/on\";\nimport { rule } from \"../extensions/rule\";\nimport { arg, now, unless, when } from \"../extensions/rule-words\";\nimport type {\n AnyTarget,\n ClientSchema,\n DelegateOperationArgs,\n DelegateOperationPayload,\n DelegateOperationResult,\n EmptyFacts,\n Exact,\n Extension,\n Facts,\n PendingOperation,\n PlacedArgument,\n Target,\n VibORMConfig,\n} from \"../index\";\n\nexport interface SoftDeleteModel {\n readonly deletedAt: string; // a nullable DateTime field of this model\n readonly deletedBy?: string; // optional scalar field for the actor\n}\nexport interface SoftDeleteConfig {\n readonly models: Readonly<Record<string, SoftDeleteModel>>;\n /** What a delete writes into `deletedBy`, fixed per derived client. */\n readonly actorId?: string | number | bigint;\n /** `actorId`'s name before 1.9.1, still accepted (`actor` names the request's actor in `permissions`). */\n readonly actor?: string | number | bigint;\n}\n\nconst NAME = \"viborm.softDelete\";\n\n// restore and purge take the model's own update and delete arguments\n// (restore minus `data`); other keys are flagged.\n// They are read from the delegate's own client (`Self`): written apart from\n// any client, the extension's own target knows no model.\ntype ArgsOf<\n C extends VibORMConfig,\n K,\n O extends \"update\" | \"updateMany\" | \"delete\" | \"deleteMany\",\n Self,\n> = DelegateOperationPayload<\n Self,\n O,\n OperationPayload<O, ClientSchema<C>[K & keyof ClientSchema<C>]>\n>;\ntype RestoreArgs<\n C extends VibORMConfig,\n K,\n O extends \"update\" | \"updateMany\",\n Self,\n> = Omit<ArgsOf<C, K, O, Self>, \"data\">;\ntype PurgeManyArgs<C extends VibORMConfig, K, Self> = NonNullable<\n ArgsOf<C, K, \"deleteMany\", Self>\n>;\ntype NoExtra<A, R> = A & Record<Exclude<keyof A, keyof R>, never>; // flags data and typos\n\n// Each result is typed from the delegate the method is called on (`Self`),\n// so it follows every extension applied after this one: a later rule\n// that hides rows types a to-one relation `| null`, a later `defaultOmit` drops a\n// field. Called off its delegate (destructured), its result is `unknown`:\n// using it is a type error, not a silent `never`. A type alias, not an interface: a method record.\n// Exported so an exported client's declaration names it instead of spelling\n// its arguments out.\nexport type SoftDeleteMethods<C extends VibORMConfig, K> = {\n restore<\n Self,\n const A extends DelegateOperationArgs<\n Self,\n RestoreArgs<C, K, \"update\", Self>\n >,\n >(\n this: Self,\n args: NoExtra<A, RestoreArgs<C, K, \"update\", Self>>\n ): PendingOperation<DelegateOperationResult<Self, \"update\", A>>;\n restoreMany<Self, A extends RestoreArgs<C, K, \"updateMany\", Self>>(\n this: Self,\n args: NoExtra<A, RestoreArgs<C, K, \"updateMany\", Self>>\n ): PendingOperation<DelegateOperationResult<Self, \"updateMany\", A>>;\n purge<\n Self,\n const A extends DelegateOperationArgs<Self, ArgsOf<C, K, \"delete\", Self>>,\n >(\n this: Self,\n args: NoExtra<A, ArgsOf<C, K, \"delete\", Self>>\n ): PendingOperation<DelegateOperationResult<Self, \"delete\", A>>;\n purgeMany<\n Self,\n A extends PurgeManyArgs<C, K, Self> = PurgeManyArgs<C, K, Self>,\n >(\n this: Self,\n args?: NoExtra<A, PurgeManyArgs<C, K, Self>>\n ): PendingOperation<DelegateOperationResult<Self, \"deleteMany\", A>>;\n};\n\n/** Each model's markers, as the client `$extends` is called on has them. */\ntype SoftDeleteModels<T extends AnyTarget> = {\n readonly [M in keyof ClientSchema<T[\"config\"]> & string]?: {\n readonly deletedAt: ScalarsOf<T, M>;\n readonly deletedBy?: ScalarsOf<T, M>;\n };\n};\ntype ScalarsOf<T extends AnyTarget, M> = M extends keyof ClientSchema<\n T[\"config\"]\n>\n ? Extract<keyof ClientSchema<T[\"config\"]>[M][\"~\"][\"state\"][\"scalars\"], string>\n : never;\n\n/**\n * What `softDelete(config)` adds: its two arguments, the models it hides rows\n * of, the methods. A view it lists is filtered as it is read, and gains no\n * method: each one writes.\n */\ntype SoftDeleteFacts<T extends AnyTarget, Models> = Facts<\n Record<never, never>,\n {\n readonly [K in keyof Models &\n keyof ClientSchema<T[\"config\"]> as ClientSchema<\n T[\"config\"]\n >[K][\"~\"][\"state\"] extends { readonly view: object }\n ? never\n : K]: SoftDeleteMethods<T[\"config\"], K>;\n },\n {\n // A mode chooses rows a call selects: a create selects none. Spelled\n // out, so an exported client's declaration needs no other name.\n readonly deleted: PlacedArgument<\n \"without\" | \"with\" | \"only\",\n PropertyKey,\n | \"findMany\"\n | \"findFirst\"\n | \"findUnique\"\n | \"findFirstOrThrow\"\n | \"findUniqueOrThrow\"\n | \"count\"\n | \"aggregate\"\n | \"groupBy\"\n | \"exist\"\n | \"update\"\n | \"updateMany\"\n | \"upsert\"\n | \"delete\"\n | \"deleteMany\"\n >;\n readonly mode: PlacedArgument<\n \"soft\" | \"hard\",\n keyof Models,\n \"delete\" | \"deleteMany\"\n >;\n },\n Extract<keyof Models, string>\n>;\n\n/** Refuse a marker that is not a nullable, single DateTime field. */\nfunction admitMarkers(\n schema: VibORMConfig[\"schema\"],\n entries: readonly (readonly [string, SoftDeleteModel])[]\n): void {\n for (const [name, { deletedAt }] of entries) {\n const scalars = Object.hasOwn(schema, name)\n ? schema[name]![\"~\"].state.scalars\n : undefined;\n if (!(scalars && Object.hasOwn(scalars, deletedAt))) continue;\n const state = scalars[deletedAt]![\"~\"].state;\n if (state.type !== \"datetime\" || state.array || !state.nullable)\n throw new ClientInitializationError(\n `softDelete: ${name}.${deletedAt} must be a nullable DateTime field (s.dateTime().nullable()): a live row holds null there.`,\n { meta: { extension: NAME } }\n );\n }\n}\n\n/** No client: what an extension written apart from one is built against. */\ntype Untyped = Target<\n VibORMConfig<Record<never, never>>,\n AnyTarget[\"state\"],\n EmptyFacts\n>;\ntype Schema = VibORMConfig[\"schema\"];\n\n/** A delegate as the methods call it: its own operations. */\ntype Self = Readonly<Record<string, (args: object) => unknown>>;\n\n/** A method that calls the delegate's `operation` with `added` over what it is given. */\nconst method = (operation: string, added: object) =>\n function (this: Self, given: object = {}) {\n return this[operation]!({ ...given, ...added });\n };\n\n/**\n * Keep deleted rows as tombstones: `client.$extends(softDelete({ models: {\n * post: { deletedAt: \"deletedAt\" } } }))`. One step, applied in any order\n * with the other extensions.\n */\nexport function softDelete<T extends AnyTarget, const Models>(config: {\n readonly models: Models &\n SoftDeleteModels<T> &\n NoInfer<Exact<Models, SoftDeleteModels<T>>>;\n /** What a delete writes into `deletedBy`, fixed per extension. */\n readonly actorId?: string | number | bigint;\n /** `actorId`'s name before 1.9.1, still accepted. */\n readonly actor?: string | number | bigint;\n}): Extension<T, SoftDeleteFacts<T, Models>>;\nexport function softDelete(config: SoftDeleteConfig): unknown {\n if (config.actorId !== undefined && config.actor !== undefined)\n throw new ClientInitializationError(\n \"softDelete: give actorId, not both actorId and actor (its former name).\",\n { meta: { extension: NAME } }\n );\n const actor = config.actorId ?? config.actor ?? null;\n const entries = Object.entries(config.models);\n const managed = entries.map(([model]) => model);\n // Built against no client: the entries are read from the schema the\n // extension is applied to, and checked there; `softDelete`'s own\n // signature types what it adds.\n return extension<Untyped>(\n NAME,\n args({\n deleted: oneOf(\"without\", \"with\", \"only\")\n .default(\"without\")\n .on(selecting),\n // Named, not `deletes`: that set brings what watches writes.\n mode: oneOf(\"soft\", \"hard\").on([\"delete\", \"deleteMany\"]).models(managed),\n }),\n // Read where the extension is applied: a marker that is not a nullable\n // DateTime is refused there, before its filters would refuse it less\n // clearly (a string field would fail at the first delete).\n rule<Untyped, (schema: Schema) => object>((schema: Schema) => {\n admitMarkers(schema, entries);\n return Object.fromEntries(\n entries.map(([model, { deletedAt, deletedBy }]) => [\n model,\n {\n root: [\n when(arg(\"deleted\"), \"without\", { [deletedAt]: null }),\n when(arg(\"deleted\"), \"only\", { [deletedAt]: { not: null } }),\n ],\n related: unless(arg(\"deleted\"), \"with\", { [deletedAt]: null }),\n delete: {\n instead: keep(\n unless(arg(\"mode\"), \"hard\", {\n [deletedAt]: now,\n ...(deletedBy ? { [deletedBy]: actor } : {}),\n })\n ),\n },\n },\n ])\n );\n }),\n // The methods read nothing typed at this step (each result is typed from\n // the delegate it is called on), so later extensions may hide rows or\n // omit fields freely.\n modelMethods((): object =>\n Object.fromEntries(\n entries.map(([model, { deletedAt, deletedBy }]) => {\n // Tombstones only: `deleted: \"only\"` overrides a caller's value.\n const restore = {\n data: {\n [deletedAt]: null,\n ...(deletedBy ? { [deletedBy]: null } : {}),\n },\n deleted: \"only\",\n };\n const purge = { deleted: \"only\", mode: \"hard\" };\n return [\n model,\n {\n restore: method(\"update\", restore),\n restoreMany: method(\"updateMany\", restore),\n purge: method(\"delete\", purge),\n purgeMany: method(\"deleteMany\", purge),\n },\n ];\n })\n )\n )\n );\n}\n"],"mappings":"0UAuCA,MAAM,EAAO,oBA4Hb,SAAS,EACP,EACA,EACM,CACN,IAAK,GAAM,CAAC,EAAM,CAAE,gBAAgB,EAAS,CAC3C,IAAM,EAAU,OAAO,OAAO,EAAQ,EAAK,CACvC,EAAO,GAAO,KAAK,MAAM,QACzB,IAAA,GACJ,GAAI,EAAE,GAAW,OAAO,OAAO,EAAS,EAAU,EAAG,SACrD,IAAM,EAAQ,EAAQ,GAAY,KAAK,MACvC,GAAI,EAAM,OAAS,YAAc,EAAM,OAAS,CAAC,EAAM,SACrD,MAAM,IAAI,EACR,eAAe,EAAK,GAAG,EAAU,4FACjC,CAAE,KAAM,CAAE,UAAW,EAAM,CAAE,CAC9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AY,EAAG,GAAY,KAAM,CAAG,EAAE,CAC3C,CACD,QAAS,OACV,CACK,EAAQ,CAAE,QAAS,OAAQ,KAAM,OAAQ,CAC/C,MAAO,CACL,EACA,CACE,QAAS,EAAO,SAAU,EAAQ,CAClC,YAAa,EAAO,aAAc,EAAQ,CAC1C,MAAO,EAAO,SAAU,EAAM,CAC9B,UAAW,EAAO,aAAc,EAAM,CACvC,CACF,EACD,CACH,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
const e=`viborm.operation`,t=`viborm.execute`,n=`viborm.transaction`,r=`viborm.connect`,i=`viborm.disconnect`,a=`db.system.name`,o=`db.namespace`,s=`db.collection.name`,c=`db.operation.name`,l=`db.query.text`,u=`db.query.summary`,d=`db.operation.batch.size`,f=`server.address`,p=`server.port`,m=`db.response.returned_rows`,h=`error.type`,g=`db.system.driver`,_=`viborm.correlation.id`,v=`db.query.parameter`,y=`viborm.cache.get`,b=`viborm.cache.set`,x=`viborm.cache.delete`,S=`viborm.cache.clear`,C=`viborm.cache.invalidate`,w=`cache.driver`,T=`cache.result`,E=`cache.ttl`;export{r as C,n as D,e as E,b as S,t as T,_,s as a,y as b,c,l as d,m as f,p as g,f as h,d as i,v as l,h as m,T as n,g as o,a as p,E as r,o as s,w as t,u,S as v,i as w,C as x,x as y};
|
|
2
|
-
//# sourceMappingURL=spans-
|
|
2
|
+
//# sourceMappingURL=spans-DwDXMvyd.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spans-
|
|
1
|
+
{"version":3,"file":"spans-DwDXMvyd.mjs","names":[],"sources":["../src/instrumentation/spans.ts"],"sourcesContent":["/**\n * Span Names\n *\n * Constants for OpenTelemetry span names following VibORM conventions.\n * Using a prefix pattern similar to Prisma (prisma:*) and Drizzle (drizzle.*).\n */\n\n/**\n * Span name for high-level client operations\n * Created for each client method call (findMany, create, etc.)\n */\nexport const SPAN_OPERATION = \"viborm.operation\";\n\n/**\n * Span name for query execution\n * Created for the actual database round-trip\n */\nexport const SPAN_EXECUTE = \"viborm.execute\";\n\n/**\n * Span name for transactions\n * Created around transaction boundaries\n */\nexport const SPAN_TRANSACTION = \"viborm.transaction\";\n\n/**\n * Span name for connection establishment\n * Created during lazy connection initialization\n */\nexport const SPAN_CONNECT = \"viborm.connect\";\n\n/**\n * Span name for connection teardown\n * Created during disconnect\n */\nexport const SPAN_DISCONNECT = \"viborm.disconnect\";\n\n/**\n * Type for all valid span names\n */\nexport type VibORMSpanName =\n | typeof SPAN_OPERATION\n | typeof SPAN_EXECUTE\n | typeof SPAN_TRANSACTION\n | typeof SPAN_CONNECT\n | typeof SPAN_DISCONNECT\n | typeof SPAN_CACHE_GET\n | typeof SPAN_CACHE_SET\n | typeof SPAN_CACHE_DELETE\n | typeof SPAN_CACHE_CLEAR\n | typeof SPAN_CACHE_INVALIDATE;\n\n/**\n * Semantic attribute keys for span attributes\n * Following OTel database semantic conventions where possible\n * @see https://opentelemetry.io/docs/specs/semconv/database/database-spans/\n */\n\n// =============================================================================\n// OTel Standard Attributes\n// =============================================================================\n\n/** Database system (postgresql, mysql, sqlite) - REQUIRED */\nexport const ATTR_DB_SYSTEM = \"db.system.name\";\n\n/** Database name/schema - Conditionally required */\nexport const ATTR_DB_NAMESPACE = \"db.namespace\";\n\n/** Table/collection name - Conditionally required */\nexport const ATTR_DB_COLLECTION = \"db.collection.name\";\n\n/** Operation name (SELECT, INSERT, findMany, create) - Conditionally required */\nexport const ATTR_DB_OPERATION_NAME = \"db.operation.name\";\n\n/** SQL query text - Recommended */\nexport const ATTR_DB_QUERY_TEXT = \"db.query.text\";\n\n/** Low cardinality query summary - Recommended */\nexport const ATTR_DB_QUERY_SUMMARY = \"db.query.summary\";\n\n/** Batch operation size - Recommended */\nexport const ATTR_DB_BATCH_SIZE = \"db.operation.batch.size\";\n\n/** Database server host - Recommended */\nexport const ATTR_SERVER_ADDRESS = \"server.address\";\n\n/** Database server port - Conditionally required */\nexport const ATTR_SERVER_PORT = \"server.port\";\n\n/** Number of rows returned - Optional */\nexport const ATTR_DB_ROWS_RETURNED = \"db.response.returned_rows\";\n\n/** Error type on failure - Conditionally required */\nexport const ATTR_ERROR_TYPE = \"error.type\";\n\n// =============================================================================\n// VibORM Custom Attributes\n// =============================================================================\n\n/** Driver name (postgres, pg, pglite, mysql2, better-sqlite3) */\nexport const ATTR_DB_DRIVER = \"db.system.driver\";\n\n/** Caller-supplied identifier that correlates one execution across outputs. */\nexport const ATTR_VIBORM_CORRELATION_ID = \"viborm.correlation.id\";\n\n/**\n * Query parameter by key or index\n * Usage: `db.query.parameter.0`, `db.query.parameter.userId`\n */\nexport const ATTR_DB_QUERY_PARAMETER_PREFIX = \"db.query.parameter\";\n\n// =============================================================================\n// Cache Spans and Attributes\n// =============================================================================\n\n/** Span name for cache get operations */\nexport const SPAN_CACHE_GET = \"viborm.cache.get\";\n\n/** Span name for cache set operations */\nexport const SPAN_CACHE_SET = \"viborm.cache.set\";\n\n/** Span name for cache delete operations */\nexport const SPAN_CACHE_DELETE = \"viborm.cache.delete\";\n\n/** Span name for cache clear operations */\nexport const SPAN_CACHE_CLEAR = \"viborm.cache.clear\";\n\n/** Span name for cache invalidation */\nexport const SPAN_CACHE_INVALIDATE = \"viborm.cache.invalidate\";\n\n/** Cache driver name (memory, cloudflare-kv, redis, etc.) */\nexport const ATTR_CACHE_DRIVER = \"cache.driver\";\n\n/** Cache operation result (hit, miss, stale) */\nexport const ATTR_CACHE_RESULT = \"cache.result\";\n\n/** Cache TTL in milliseconds */\nexport const ATTR_CACHE_TTL = \"cache.ttl\";\n"],"mappings":"AAWA,MAAa,EAAiB,mBAMjB,EAAe,iBAMf,EAAmB,qBAMnB,EAAe,iBAMf,EAAkB,oBA4BlB,EAAiB,iBAGjB,EAAoB,eAGpB,EAAqB,qBAGrB,EAAyB,oBAGzB,EAAqB,gBAGrB,EAAwB,mBAGxB,EAAqB,0BAGrB,EAAsB,iBAGtB,EAAmB,cAGnB,EAAwB,4BAGxB,EAAkB,aAOlB,EAAiB,mBAGjB,EAA6B,wBAM7B,EAAiC,qBAOjC,EAAiB,mBAGjB,EAAiB,mBAGjB,EAAoB,sBAGpB,EAAmB,qBAGnB,EAAwB,0BAGxB,EAAoB,eAGpB,EAAoB,eAGpB,EAAiB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./migrations-DIUltjr3.mjs";import{o as t}from"./sql-tegqTqGq.mjs";import{gt as n}from"./model-Dtd37Sky.mjs";import{D as r,O as i}from"./native-types-1ewJXVks.mjs";import{u as a}from"./validator-DMzH5Tz0.mjs";import{L as o}from"./standard-sql-Bl2OHGfi.mjs";import{Gn as s,Kn as c,S as l,ir as u,nr as d}from"./serializer-ettLu5xG.mjs";const f={cascade:`CASCADE`,setNull:`SET NULL`,restrict:`RESTRICT`,setDefault:`SET DEFAULT`,noAction:`NO ACTION`},p={trigger:0,function:1,view:2};var m=class extends l{zm(e,n){let r=this.re(n,n[`~`].state);return t`CAST(${e} AS ${t.raw(r)})`}async gp(e,t){let{identifiers:n}=e.adapter,r=n.table(t);return(await e._executeRaw(`SELECT 1 AS present FROM ${r.toStatement()} LIMIT 1`)).rows.length>0}async hc(e,n,r,i){let{identifiers:a,literals:o,operators:s}=e.adapter,c=a.escape(r),l=o.list(i.map(e=>o.value(e))),u=e._prepare(t`SELECT ${a.aliased(c,`stored`)} FROM ${a.table(n)} WHERE ${s.notIn(c,l)} LIMIT 1`),[d]=(await e._executeRaw(u.sql,u.params)).rows;return d}pe(e,t,n,r){let i=e.columnValueReplacements?.[`${t}.${n}`];return i&&r in i?i[r]:e.valueReplacements&&r in e.valueReplacements?e.valueReplacements[r]:e.defaultReplacement}cg(e,t){return(e.dependentColumns??[]).flatMap(({tableName:n,columnName:r})=>this.iz(e,n,r,t))}iz(e,t,n,r){let i=this.tl(t,r.destination),a=this.escapeIdentifier(n);return(e.removeValues??[]).flatMap(r=>{let o=this.pe(e,t,n,r);return o===void 0?[]:[`UPDATE ${i} SET ${a} = ${this.ek(o)} WHERE ${a} = ${this.ek(r)}`]})}fm(e,t,n){return(e.removeValues??[]).flatMap(r=>{let i=this.pe(e,t,n,r);return i===void 0?[]:[`WHEN ${this.ek(r)} THEN ${this.ek(i)}`]})}escapeIdentifier(t){if(t==null)throw new e(`Cannot escape null or undefined identifier`,`V4002`);return`"${String(t).replace(/"/g,`""`)}"`}tl(e,t){return this.escapeIdentifier(e)}ek(e){return e==null?`NULL`:`'${String(e).replace(/'/g,`''`)}'`}tv(e){return f[e]??`NO ACTION`}tg(t,a){if(a.autoGenerate)return this.ud(a.autoGenerate);if(!a.hasDefault||a.default===void 0)return;let s=this.au(a);if(typeof s!=`function`){if(a.type===`json`&&!a.array){let e=n(s);if(e===`DbNull`)return this.dialect===`sqlite`?`NULL`:void 0;if(e===`JsonNull`||s===null&&a.default!==null)return this.ek(`null`);if(s!==null&&[`string`,`number`,`boolean`].includes(typeof s))return this.ek(o(s))}if(s===null)return`NULL`;if(a.decimal&&a.array&&Array.isArray(s))return this.ek(i(this.yf(),s,a.decimal));if(a.array&&Array.isArray(s)||a.type===`json`&&typeof s==`object`)return this.ek(o(s));if(typeof s==`bigint`)return s.toString();if(typeof s==`string`)return a.decimal?r(this.yf(),s,a.decimal):this.ek(s);if(typeof s==`number`){if(!Number.isFinite(s))throw new e(`Invalid default value: ${s} is not a finite number`,`V4002`);return String(s)}if(typeof s==`boolean`)return this.ck(s)}}ck(e){return e?`true`:`false`}yf(){return this.dialect===`postgresql`?`pg`:this.dialect===`mysql`?`mysql`:`sqlite`}ud(e){}mu(t,n){if(!t)return;let r=this.capabilities.supportsIndexTypes;if(!r.includes(t))throw new e(`Index "${n}" uses unsupported index type "${t}". Supported types for ${this.dialect}: ${r.join(`, `)}`,`V8001`)}nf(e,t){let n=[this.escapeIdentifier(e.name)],r=this.mj(e,t);return n.push(r),e.nullable||n.push(`NOT NULL`),e.default!==void 0&&!e.autoIncrement&&n.push(`DEFAULT ${e.default}`),n.join(` `)}mj(e,t){return e.type}uw(e,t){let{view:n}=e;if(n.auto)return this.vf(n,t);let r=this.tl(n.name,t.destination),i=u(n,e=>this.escapeIdentifier(e));return n.materialized?[`CREATE MATERIALIZED VIEW ${r} AS ${i} WITH DATA`,...(n.indexes??[]).flatMap(e=>this.tu({type:`createIndex`,tableName:n.name,index:e},t))]:`CREATE VIEW ${r} AS ${i}`}mq(e,t){return e.auto?this.yv(e,e.auto,t):`DROP ${e.materialized?`MATERIALIZED `:``}VIEW ${this.tl(e.viewName,t.destination)}`}fv(){return!0}ub(e,t){return s(e,t)}vf(e,t){let n=c(e),r=a(e.name);return[...this.bd({name:e.name,columns:n.columns,primaryKey:{columns:n.key},indexes:e.indexes??[],foreignKeys:[],uniqueConstraints:[]},d(e.hash),t),`CREATE VIEW ${this.tl(r,t.destination)} AS ${u(e,e=>this.escapeIdentifier(e),this.og(n))}`,...this.fj(e,n,t),...[this.kg(e,n,t)].flat()]}bd(e,t,n){let[r,...i]=this.nw({type:`createTable`,table:e},n),a=r.indexOf(`(`);return[`${r.slice(0,a+1)}/* ${t} */${r.slice(a+1)}`,...i]}kg(e,t,n){let r=this.og(t);return`INSERT INTO ${this.tl(e.name,n.destination)} (${r}) SELECT ${r} FROM ${this.tl(a(e.name),n.destination)}`}og(e){return e.columns.map(e=>this.escapeIdentifier(e.name)).join(`, `)}cu(e,t,n,r,i=``){let o=this.tl(e.name,r.destination),s=this.tl(a(e.name),r.destination),c=this.og(t),l=t.key.map((e,r)=>`${this.escapeIdentifier(e)} = ${n}.${this.escapeIdentifier(t.sourceKey[r])}`).join(` AND `);return[`DELETE FROM ${o} WHERE ${l}${i}`,`INSERT INTO ${o} (${c}) SELECT ${c} FROM ${s} WHERE ${l}${i}`]}yv(e,t,n){return[...[...t.objects].sort((e,t)=>p[e.kind]-p[t.kind]).map(e=>this.oe(e,n)),...t.tableless?[]:[`DROP TABLE ${this.tl(e.viewName,n.destination)}`]]}oe(e,t){return e.kind===`view`?`DROP VIEW IF EXISTS ${this.tl(e.name,t.destination)}`:`DROP TRIGGER IF EXISTS ${this.escapeIdentifier(e.name)}`}cj(e){return`DROP TABLE IF EXISTS ${this.tl(e,`live`)}`}ls(e){return null}};export{m as t};
|
|
2
|
+
//# sourceMappingURL=sql-Bu63iAfT.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sql-Bu63iAfT.mjs","names":[],"sources":["../src/migrations/drivers/sql.ts"],"sourcesContent":["/**\n * What every SQL migration driver shares: how an identifier, a value and a default\n * are spelled, and the two probes `push` reads. {@link MigrationDriver} is what any\n * language answers. See `docs/architecture/query-backend-frontier.md`.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport type { AnyDriver } from \"@drivers/driver\";\nimport { jsonNullKindOf } from \"@schema/json-null\";\nimport type { Scalar, ScalarState } from \"@schema/scalars\";\nimport { type Sql, sql } from \"@sql\";\nimport {\n type DecimalDialect,\n decimalDefaultText,\n decimalListDefaultText,\n} from \"@validation/primitives/decimal-codec\";\nimport { stringifyJson } from \"../../adapters/shared/standard-sql\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport type { ViewColumnSql } from \"../../query-engine/raptor3/view-body\";\nimport { autoViewBodyName } from \"../../schema/view/auto-names\";\nimport type {\n AutoViewDef,\n AutoViewObject,\n AutoViewStorage,\n ColumnDef,\n ReferentialAction,\n TableDef,\n ViewDef,\n} from \"../types\";\nimport {\n autoViewObjects,\n declaredAutoViewStorage,\n viewMarker,\n wrappedViewBody,\n} from \"../view\";\nimport {\n type AlterEnumOperation,\n type CreateViewOperation,\n type DDLContext,\n type DropViewOperation,\n MigrationDriver,\n} from \"./base\";\n\nconst REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string> = {\n cascade: \"CASCADE\",\n setNull: \"SET NULL\",\n restrict: \"RESTRICT\",\n setDefault: \"SET DEFAULT\",\n noAction: \"NO ACTION\",\n};\n\nconst DROP_OBJECT_ORDER = { trigger: 0, function: 1, view: 2 } as const;\n\nexport abstract class SqlMigrationDriver\n extends MigrationDriver\n implements ViewColumnSql\n{\n /**\n * An aggregate as a view's column (`count`, `sumAmount`): cast to the type\n * a column of its scalar is created with, so a filter, an order or an\n * aggregate on the view reads it as it reads that scalar's column.\n */\n viewCast(expression: Sql, scalar: Scalar): Sql {\n const type = this.mapScalarType(scalar, scalar[\"~\"].state);\n return sql`CAST(${expression} AS ${sql.raw(type)})`;\n }\n\n override async tableHoldsRows(\n producer: AnyDriver,\n table: string\n ): Promise<boolean> {\n const { identifiers } = producer.adapter as DatabaseAdapter;\n const reference = identifiers.table(table);\n const populated = await producer._executeRaw(\n `SELECT 1 AS present FROM ${reference.toStatement()} LIMIT 1`\n );\n return populated.rows.length > 0;\n }\n\n override async undeclaredValue(\n producer: AnyDriver,\n table: string,\n columnName: string,\n declared: readonly string[]\n ): Promise<{ readonly stored: unknown } | undefined> {\n const { identifiers, literals, operators } =\n producer.adapter as DatabaseAdapter;\n const column = identifiers.escape(columnName);\n const values = literals.list(\n declared.map((value) => literals.value(value))\n );\n const probe = producer._prepare(\n sql`SELECT ${identifiers.aliased(column, \"stored\")} FROM ${identifiers.table(table)} WHERE ${operators.notIn(column, values)} LIMIT 1`\n );\n const [found] = (\n await producer._executeRaw<{ stored: unknown }>(probe.sql, probe.params)\n ).rows;\n return found;\n }\n\n /**\n * Resolves the replacement for a removed enum value on a specific column.\n * Precedence: per-column mapping (columnValueReplacements, keyed\n * \"tableName.columnName\") → flat valueReplacements → defaultReplacement.\n * Returns undefined when no replacement is configured.\n */\n protected getEnumValueReplacement(\n op: AlterEnumOperation,\n tableName: string,\n columnName: string,\n removedValue: string\n ): string | null | undefined {\n const perColumn =\n op.columnValueReplacements?.[`${tableName}.${columnName}`];\n if (perColumn && removedValue in perColumn) {\n return perColumn[removedValue];\n }\n if (op.valueReplacements && removedValue in op.valueReplacements) {\n return op.valueReplacements[removedValue];\n }\n return op.defaultReplacement;\n }\n\n /**\n * Builds the UPDATE statements that migrate rows off removed enum values,\n * honoring per-column mappings. Dialects run these before the type change\n * (Postgres: while columns are text; MySQL: before MODIFY COLUMN).\n */\n protected buildEnumReplacementUpdates(\n op: AlterEnumOperation,\n context: DDLContext\n ): string[] {\n return (op.dependentColumns ?? []).flatMap(({ tableName, columnName }) =>\n this.enumColumnReplacementUpdates(op, tableName, columnName, context)\n );\n }\n\n /** One dependent column's UPDATEs, one per removed value it replaces. */\n protected enumColumnReplacementUpdates(\n op: AlterEnumOperation,\n tableName: string,\n columnName: string,\n context: DDLContext\n ): string[] {\n const table = this.tableRef(tableName, context.destination);\n const column = this.escapeIdentifier(columnName);\n return (op.removeValues ?? []).flatMap((removedValue) => {\n const replacement = this.getEnumValueReplacement(\n op,\n tableName,\n columnName,\n removedValue\n );\n return replacement === undefined\n ? []\n : [\n `UPDATE ${table} SET ${column} = ${this.escapeValue(replacement)} WHERE ${column} = ${this.escapeValue(removedValue)}`,\n ];\n });\n }\n\n /** The `WHEN removed THEN replacement` arms of a column's value mapping. */\n protected enumReplacementCases(\n op: AlterEnumOperation,\n tableName: string,\n columnName: string\n ): string[] {\n return (op.removeValues ?? []).flatMap((value) => {\n const replacement = this.getEnumValueReplacement(\n op,\n tableName,\n columnName,\n value\n );\n return replacement === undefined\n ? []\n : [\n `WHEN ${this.escapeValue(value)} THEN ${this.escapeValue(replacement)}`,\n ];\n });\n }\n\n // ===========================================================================\n // HELPER METHODS (can be overridden)\n // ===========================================================================\n\n /**\n * Escapes an identifier (table name, column name, etc.).\n * Default uses double quotes with proper escaping.\n */\n override escapeIdentifier(name: string): string {\n if (name == null) {\n throw new MigrationError(\n \"Cannot escape null or undefined identifier\",\n VibORMErrorCode.INVALID_INPUT\n );\n }\n return `\"${String(name).replace(/\"/g, '\"\"')}\"`;\n }\n\n /**\n * A table position. Default: one identifier. PostgreSQL qualifies it with\n * the estate schema; MySQL names the database in a live statement.\n */\n protected tableRef(\n tableName: string,\n _destination: DDLContext[\"destination\"]\n ): string {\n return this.escapeIdentifier(tableName);\n }\n\n /**\n * Escapes a string value for SQL.\n * Default uses single quotes with proper escaping.\n * Returns \"NULL\" for null/undefined values.\n */\n escapeValue(value: string | null | undefined): string {\n if (value == null) {\n return \"NULL\";\n }\n return `'${String(value).replace(/'/g, \"''\")}'`;\n }\n\n /**\n * Formats a referential action for foreign keys.\n */\n formatReferentialAction(action: ReferentialAction): string {\n return REFERENTIAL_ACTION_SQL[action] ?? \"NO ACTION\";\n }\n\n // ===========================================================================\n // COMMON IMPLEMENTATIONS (can be overridden for database-specific behavior)\n // ===========================================================================\n\n /**\n * Gets the SQL default expression for a field.\n * Common implementation that handles most cases.\n * Override for database-specific behavior (e.g., UUID generation, boolean representation).\n *\n * @param scalar - The scalar declaration, including its native type\n * @param scalarState - The scalar state\n * @returns SQL default expression or undefined if no default\n */\n override getDefaultExpression(\n _scalar: Scalar,\n scalarState: ScalarState\n ): string | undefined {\n // Auto-generated values - check for database-level support first\n if (scalarState.autoGenerate) {\n return this.getAutoGenerateExpression(scalarState.autoGenerate);\n }\n\n // Check for explicit default value\n if (!scalarState.hasDefault || scalarState.default === undefined) {\n return undefined;\n }\n\n const defaultVal = this.literalDefaultValue(scalarState);\n\n // Function defaults are generated at runtime\n if (typeof defaultVal === \"function\") {\n return undefined;\n }\n\n // A JSON null document and absent SQL value are distinct physical defaults.\n // Scalar admission already resolves bare-null ambiguity and authenticates\n // sentinels; JSON primitives must also be quoted as documents, not SQL data.\n if (scalarState.type === \"json\" && !scalarState.array) {\n const kind = jsonNullKindOf(defaultVal);\n if (kind === \"DbNull\")\n return this.dialect === \"sqlite\" ? \"NULL\" : undefined;\n if (kind === \"JsonNull\") return this.escapeValue(\"null\");\n // A schema's null output is a document; only the original nullable\n // bare-null default declares an absent SQL value.\n if (defaultVal === null && scalarState.default !== null)\n return this.escapeValue(\"null\");\n if (\n defaultVal !== null &&\n [\"string\", \"number\", \"boolean\"].includes(typeof defaultVal)\n )\n return this.escapeValue(stringifyJson(defaultVal));\n }\n\n // Null default\n if (defaultVal === null) {\n return \"NULL\";\n }\n\n // A literal decimal-list default is already a trusted list of canonical\n // logical strings: the field codec normalized it at `.default()`. Render\n // its provider value through that same codec, then let the migration driver\n // own quoting and MySQL's required expression parentheses. No generic\n // array/object default enters this arm.\n if (scalarState.decimal && scalarState.array && Array.isArray(defaultVal)) {\n return this.escapeValue(\n decimalListDefaultText(\n this.decimalDialect(),\n defaultVal,\n scalarState.decimal\n )\n );\n }\n\n if (scalarState.array && Array.isArray(defaultVal))\n return this.escapeValue(stringifyJson(defaultVal));\n if (scalarState.type === \"json\" && typeof defaultVal === \"object\")\n return this.escapeValue(stringifyJson(defaultVal));\n if (typeof defaultVal === \"bigint\") return defaultVal.toString();\n\n // Primitive defaults\n if (typeof defaultVal === \"string\") {\n // A decimal default is canonical text by the time it reaches here\n // (`.default()` normalizes at definition time), and canonical text is the\n // WRONG DDL spelling: it strips trailing zeros, while MySQL reads a\n // `DECIMAL(p,s)` default back from `information_schema` padded to the\n // scale. Two renderings, one owner — this is the DDL one, and emitting\n // the identity one instead would make the differ see a changed default\n // on every push. It is also unquoted, because a decimal default is a\n // numeric literal and not a string on any of the three dialects.\n if (scalarState.decimal) {\n return decimalDefaultText(\n this.decimalDialect(),\n defaultVal,\n scalarState.decimal\n );\n }\n return this.escapeValue(defaultVal);\n }\n if (typeof defaultVal === \"number\") {\n if (!Number.isFinite(defaultVal)) {\n throw new MigrationError(\n `Invalid default value: ${defaultVal} is not a finite number`,\n VibORMErrorCode.INVALID_INPUT\n );\n }\n return String(defaultVal);\n }\n if (typeof defaultVal === \"boolean\") {\n return this.formatBooleanDefault(defaultVal);\n }\n\n // Arrays and objects are handled at application level, not as SQL defaults\n if (typeof defaultVal === \"object\") {\n return undefined;\n }\n\n return undefined;\n }\n\n /**\n * Formats a boolean default value.\n * Override for databases that use different representations (e.g., SQLite uses 1/0).\n */\n protected formatBooleanDefault(value: boolean): string {\n return value ? \"true\" : \"false\";\n }\n\n /**\n * This driver's dialect in the codec's vocabulary.\n *\n * Two vocabularies exist because they name different things: `Dialect` is the\n * migration ESTATE's dialect, and `DecimalDialect` is the set of dialects\n * that spell a fixed decimal differently. They are not extended together, so\n * the translation is stated once here rather than at each of the codec's\n * call sites.\n */\n protected decimalDialect(): DecimalDialect {\n if (this.dialect === \"postgresql\") return \"pg\";\n if (this.dialect === \"mysql\") return \"mysql\";\n return \"sqlite\";\n }\n\n /**\n * Gets the SQL expression for an auto-generated value.\n * Override for databases that support specific generation functions.\n *\n * By default, returns undefined for all types (handled at application level).\n * PostgreSQL overrides this to use gen_random_uuid() for UUID.\n *\n * @param autoGenerate - The auto-generate type\n * @returns SQL expression or undefined if handled at application level\n */\n protected getAutoGenerateExpression(\n _autoGenerate: ScalarState[\"autoGenerate\"]\n ): string | undefined {\n // By default, all auto-generate types are handled at application level\n // Databases can override to provide native support (e.g., gen_random_uuid())\n return undefined;\n }\n\n /**\n * Validates an index type against supported capabilities.\n * Throws MigrationError if the index type is not supported.\n *\n * @param indexType - The index type to validate (e.g., \"btree\", \"hash\", \"gin\")\n * @param indexName - The index name (for error messages)\n */\n protected validateIndexType(\n indexType: string | undefined,\n indexName: string\n ): void {\n if (!indexType) return; // Default index type is always supported\n\n const supported = this.capabilities.supportsIndexTypes;\n if (!supported.includes(indexType)) {\n throw new MigrationError(\n `Index \"${indexName}\" uses unsupported index type \"${indexType}\". ` +\n `Supported types for ${this.dialect}: ${supported.join(\", \")}`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED\n );\n }\n }\n\n /**\n * Generates a column definition string.\n * Common implementation that can be overridden for database-specific syntax.\n *\n * @param column - The column definition\n * @returns SQL column definition string\n */\n protected generateColumnDef(column: ColumnDef, context: DDLContext): string {\n const parts: string[] = [this.escapeIdentifier(column.name)];\n\n // Handle type (may be overridden for auto-increment handling)\n const columnType = this.formatColumnType(column, context);\n parts.push(columnType);\n\n // NOT NULL constraint\n if (!column.nullable) {\n parts.push(\"NOT NULL\");\n }\n\n // DEFAULT clause (skip for auto-increment columns)\n if (column.default !== undefined && !column.autoIncrement) {\n parts.push(`DEFAULT ${column.default}`);\n }\n\n return parts.join(\" \");\n }\n\n /**\n * Formats the column type, handling auto-increment and other special cases.\n * Override for database-specific type handling (e.g., PostgreSQL SERIAL).\n *\n * Takes the DDL context because a column type can name a managed enum type,\n * and a managed enum type is qualified exactly like any other persistent\n * object — which is a destination-dependent decision.\n */\n protected formatColumnType(column: ColumnDef, _context: DDLContext): string {\n return column.type;\n }\n\n /**\n * Generates SQL for dropping a table.\n *\n * There is no `CASCADE` arm. §6.1: a namespace is a containment boundary, and\n * `DROP TABLE ... CASCADE` drops dependants in OTHER namespaces even when the\n * enumeration that produced this name only ever selected one. The dependency\n * graph is materialized as explicit foreign-key drops before the table drops\n * instead, and an unknown external dependency then aborts the operation\n * through PostgreSQL's default `RESTRICT` rather than deleting collaterally.\n *\n * @param tableName - The table name\n * @returns SQL DROP TABLE statement\n */\n /**\n * A view is created at its table position, the marker alias spelled as the\n * dialect quotes an identifier. A materialized view is computed by its\n * creation (`WITH DATA`), then indexed as a table is, so the one operation\n * that creates it leaves it whole. Its drop keeps the database's default\n * RESTRICT: what still reads it is dropped first by the program.\n */\n generateCreateView(\n op: CreateViewOperation,\n context: DDLContext\n ): string | string[] {\n const { view } = op;\n if (view.auto) return this.generateCreateAutoView(view, context);\n const name = this.tableRef(view.name, context.destination);\n const body = wrappedViewBody(view, (marker) =>\n this.escapeIdentifier(marker)\n );\n if (!view.materialized) return `CREATE VIEW ${name} AS ${body}`;\n return [\n `CREATE MATERIALIZED VIEW ${name} AS ${body} WITH DATA`,\n ...(view.indexes ?? []).flatMap((index) =>\n this.generateCreateIndex(\n { type: \"createIndex\", tableName: view.name, index },\n context\n )\n ),\n ];\n }\n\n generateDropView(\n op: DropViewOperation,\n context: DDLContext\n ): string | string[] {\n if (op.auto) return this.generateDropAutoView(op, op.auto, context);\n return `DROP ${op.materialized ? \"MATERIALIZED \" : \"\"}VIEW ${this.tableRef(op.viewName, context.destination)}`;\n }\n\n // ===========================================================================\n // VIEWS KEPT BY TRIGGERS (`.materialized({ refresh: \"auto\" })`)\n // ===========================================================================\n\n override keepsViewsByTriggers(): boolean {\n return true;\n }\n\n override autoViewObjects(\n view: string,\n storage: AutoViewStorage\n ): AutoViewObject[] {\n return autoViewObjects(view, storage);\n }\n\n /**\n * A view kept by triggers, in one operation: the table that holds its rows\n * (its marker beside it, its key its primary key, then its indexes), the\n * ordinary view that holds its body, the triggers that keep it, and its\n * rows. Where DDL is transactional the rows are computed in the\n * transaction that created the triggers, which blocks the source's writers\n * until it ends; where it is not (MySQL), after the triggers, so that no\n * write is missed between the two.\n */\n protected generateCreateAutoView(\n view: ViewDef,\n context: DDLContext\n ): string[] {\n const storage = declaredAutoViewStorage(view);\n const body = autoViewBodyName(view.name);\n return [\n ...this.autoViewTable(\n {\n name: view.name,\n columns: storage.columns,\n primaryKey: { columns: storage.key },\n indexes: view.indexes ?? [],\n foreignKeys: [],\n uniqueConstraints: [],\n },\n viewMarker(view.hash),\n context\n ),\n // Its columns listed in the table's order: `$refresh` reads it whole.\n `CREATE VIEW ${this.tableRef(body, context.destination)} AS ${wrappedViewBody(\n view,\n (marker) => this.escapeIdentifier(marker),\n this.autoViewColumns(storage)\n )}`,\n ...this.autoViewKeepers(view, storage, context),\n ...[this.autoViewFill(view, storage, context)].flat(),\n ];\n }\n\n /**\n * The table of a view kept by triggers, with its marker. Here (SQLite) the\n * marker is a comment inside the parentheses of its `CREATE TABLE`, which\n * the catalog keeps as written (`sqlite_master.sql`; measured on SQLite\n * 3.51, which drops one written after them).\n */\n protected autoViewTable(\n table: TableDef,\n marker: string,\n context: DDLContext\n ): string[] {\n const [create, ...rest] = this.generateCreateTable(\n { type: \"createTable\", table },\n context\n );\n const at = create!.indexOf(\"(\");\n return [\n `${create!.slice(0, at + 1)}/* ${marker} */${create!.slice(at + 1)}`,\n ...rest,\n ];\n }\n\n /** The triggers, and what else, that keep a view current from its source's writes. */\n protected abstract autoViewKeepers(\n view: ViewDef,\n storage: AutoViewStorage,\n context: DDLContext\n ): string[];\n\n /** The rows of a view kept by triggers, computed whole. */\n protected autoViewFill(\n view: ViewDef,\n storage: AutoViewStorage,\n context: DDLContext\n ): string | string[] {\n const columns = this.autoViewColumns(storage);\n return `INSERT INTO ${this.tableRef(view.name, context.destination)} (${columns}) SELECT ${columns} FROM ${this.tableRef(autoViewBodyName(view.name), context.destination)}`;\n }\n\n /** A view kept by triggers' columns, as an `INSERT` lists them. */\n protected autoViewColumns(storage: AutoViewStorage): string {\n return storage.columns\n .map((column) => this.escapeIdentifier(column.name))\n .join(\", \");\n }\n\n /**\n * The statements that compute again the row or the group of the source row\n * `ref` (`OLD` or `NEW`) in a view kept by triggers: its row is deleted,\n * then its body's row of that key inserted, so a row its filter no longer\n * keeps, or a group that emptied, is not there again. `guard` ends each\n * statement's filter (SQLite's test that the key changed). Each body reads\n * its key's rows alone: every database measured (PostgreSQL 18, MySQL 8.4,\n * SQLite 3.51) moves the key's test into the body's own filter, through its\n * grouping, so the source is read by the index of its key.\n */\n protected autoViewRecompute(\n view: ViewDef,\n storage: AutoViewStorage,\n ref: \"OLD\" | \"NEW\",\n context: DDLContext,\n guard = \"\"\n ): string[] {\n const table = this.tableRef(view.name, context.destination);\n const body = this.tableRef(\n autoViewBodyName(view.name),\n context.destination\n );\n const columns = this.autoViewColumns(storage);\n // The view's column, named as the view names it, against the trigger\n // row's, named as its source does (a `.map()`ped field differs).\n const match = storage.key\n .map(\n (column, at) =>\n `${this.escapeIdentifier(column)} = ${ref}.${this.escapeIdentifier(storage.sourceKey[at]!)}`\n )\n .join(\" AND \");\n return [\n `DELETE FROM ${table} WHERE ${match}${guard}`,\n `INSERT INTO ${table} (${columns}) SELECT ${columns} FROM ${body} WHERE ${match}${guard}`,\n ];\n }\n\n /**\n * A view kept by triggers, dropped whole: the objects its snapshot records\n * (its triggers first, which call the rest), then its table. An object a\n * hand already dropped is skipped.\n */\n protected generateDropAutoView(\n op: DropViewOperation,\n auto: AutoViewDef,\n context: DDLContext\n ): string[] {\n return [\n ...[...auto.objects]\n .sort((a, b) => DROP_OBJECT_ORDER[a.kind] - DROP_OBJECT_ORDER[b.kind])\n .map((object) => this.dropAutoViewObject(object, context)),\n ...(auto.tableless\n ? []\n : [`DROP TABLE ${this.tableRef(op.viewName, context.destination)}`]),\n ];\n }\n\n /** One object a view kept by triggers needs, dropped if it is there. */\n protected dropAutoViewObject(\n object: AutoViewObject,\n context: DDLContext\n ): string {\n return object.kind === \"view\"\n ? `DROP VIEW IF EXISTS ${this.tableRef(object.name, context.destination)}`\n : `DROP TRIGGER IF EXISTS ${this.escapeIdentifier(object.name)}`;\n }\n\n override generateDropTableSQL(tableName: string): string {\n return `DROP TABLE IF EXISTS ${this.tableRef(tableName, \"live\")}`;\n }\n\n /**\n * Generates SQL for dropping an enum type.\n * Returns null for databases that don't support enums.\n *\n * @param enumName - The enum name\n * @returns SQL DROP TYPE statement or null\n */\n override generateDropEnumSQL(_enumName: string): string | null {\n return null; // Override in PostgreSQL driver\n }\n}\n"],"mappings":"iWA2CA,MAAM,EAA4D,CAChE,QAAS,UACT,QAAS,WACT,SAAU,WACV,WAAY,cACZ,SAAU,YACX,CAEK,EAAoB,CAAE,QAAS,EAAG,SAAU,EAAG,KAAM,EAAG,CAE9D,IAAsB,EAAtB,cACU,CAEV,CAME,SAAS,EAAiB,EAAqB,CAC7C,IAAM,EAAO,KAAK,cAAc,EAAQ,EAAO,KAAK,MAAM,CAC1D,MAAO,EAAG,QAAQ,EAAW,MAAM,EAAI,IAAI,EAAK,CAAC,GAGnD,MAAe,eACb,EACA,EACkB,CAClB,GAAM,CAAE,eAAgB,EAAS,QAC3B,EAAY,EAAY,MAAM,EAAM,CAI1C,OAHkB,MAAM,EAAS,YAC/B,4BAA4B,EAAU,aAAa,CAAC,UACrD,EACgB,KAAK,OAAS,EAGjC,MAAe,gBACb,EACA,EACA,EACA,EACmD,CACnD,GAAM,CAAE,cAAa,WAAU,aAC7B,EAAS,QACL,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O,KAAK,GAGlE,qBAA8B,EAA2B,CACvD,MAAO,wBAAwB,KAAK,SAAS,EAAW,OAAO,GAUjE,oBAA6B,EAAkC,CAC7D,OAAO"}
|
|
@@ -19,9 +19,11 @@ type Placeholder = "$n" | ":n" | "?";
|
|
|
19
19
|
declare class Sql {
|
|
20
20
|
private rawStrings;
|
|
21
21
|
private rawValues;
|
|
22
|
+
/** Whether `rawStrings` is a tagged template's strings ({@link stringAt}). */
|
|
23
|
+
private template;
|
|
22
24
|
private projection;
|
|
23
25
|
private statements;
|
|
24
|
-
constructor(rawStrings: readonly string[], rawValues: readonly RawValue[]);
|
|
26
|
+
constructor(rawStrings: readonly string[], rawValues: readonly RawValue[], template?: boolean);
|
|
25
27
|
get values(): Value[];
|
|
26
28
|
get strings(): string[];
|
|
27
29
|
/**
|
|
@@ -33,11 +35,23 @@ declare class Sql {
|
|
|
33
35
|
strings: string[];
|
|
34
36
|
values: Value[];
|
|
35
37
|
};
|
|
38
|
+
/**
|
|
39
|
+
* The flat strings and values of `fragment`'s raw tree, read in one pass
|
|
40
|
+
* over the raw fragments, so a nested Sql is never flattened itself.
|
|
41
|
+
*/
|
|
42
|
+
private static project;
|
|
36
43
|
/**
|
|
37
44
|
* The text of a fragment that holds no value and no fragment (a
|
|
38
45
|
* `sql.raw`), read without composing anything; `undefined` for any other.
|
|
39
46
|
*/
|
|
40
47
|
static leafText(fragment: Sql): string | undefined;
|
|
48
|
+
/**
|
|
49
|
+
* Whether `fragment` is a plain single bound parameter (`sql.value(v)`)
|
|
50
|
+
* with no surrounding text, no nested fragment, and no open slot.
|
|
51
|
+
*/
|
|
52
|
+
static isSingleBound(fragment: Sql): boolean;
|
|
53
|
+
/** The bound parameter of a fragment {@link isSingleBound} accepted. */
|
|
54
|
+
static singleBoundValue(fragment: Sql): Value;
|
|
41
55
|
/**
|
|
42
56
|
* {@link peek}'s text, also cut where a fragment `opaque` accepts begins
|
|
43
57
|
* and ends, each run saying whether it lies inside one: a reader rewriting
|
|
@@ -59,10 +73,9 @@ declare class Sql {
|
|
|
59
73
|
/** `slot`'s text replaced by `content`'s (see {@link SqlSlot.settle}). */
|
|
60
74
|
protected static fill(slot: Sql, content: Sql): void;
|
|
61
75
|
/**
|
|
62
|
-
* Flatten the raw fragment tree
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
* releasing child fragments that are not referenced elsewhere.
|
|
76
|
+
* Flatten the raw fragment tree ({@link project}). The flat arrays then
|
|
77
|
+
* replace the raw tree as the canonical representation, releasing child
|
|
78
|
+
* fragments that are not referenced elsewhere.
|
|
66
79
|
*/
|
|
67
80
|
private flatten;
|
|
68
81
|
/**
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const e=/\s/,t=/[A-Za-z_]/,n=/[A-Za-z0-9_$]/;function r(r,s={}){let c=[],l=0,u=0,d=!1;for(;u<r.length;){let f=r[u],p=r[u+1];if(!f)break;if(e.test(f)){u+=1;continue}if(f===`-`&&p===`-`){u=i(r,u+2);continue}if(f===`/`&&p===`*`){let e=r.indexOf(`*/`,u+2);if(e<0)return;u=e+2;continue}if(f===`'`){let e=a(r,u,f,s.xv===!0);if(e<0||d)return;u=e;continue}if(f===`"`||f==="`"||f===`[`){let e=o(r,u,f===`[`?`]`:f);if(!e||d)return;c.push({depth:l,kind:`identifier`,value:e.value.toUpperCase()}),u=e.end;continue}if(f===`;`&&l===0){d=!0,u+=1;continue}if(d)return;if((f===`:`||f===`@`||f===`$`)&&t.test(p??``)){for(u+=2;u<r.length&&n.test(r[u]??``);)u+=1;continue}if(f===`(`){c.push({depth:l,kind:`symbol`,value:f}),l+=1,u+=1;continue}if(f===`)`){if(--l,l<0)return;c.push({depth:l,kind:`symbol`,value:f}),u+=1;continue}if(f===`=`){c.push({depth:l,kind:`symbol`,value:f}),u+=1;continue}if(t.test(f)){let e=u;for(u+=1;u<r.length&&n.test(r[u]??``);)u+=1;c.push({depth:l,kind:`word`,value:r.slice(e,u).toUpperCase()});continue}u+=1}if(l===0)return c.filter(e=>e.depth===0)}function i(e,t){let n=e.indexOf(`
|
|
2
|
+
`,t);return n<0?e.length:n+1}function a(e,t,n,r){let i=t+1;for(;i<e.length;){if(r&&e[i]===`\\`){if(i+1>=e.length)return-1;i+=2;continue}if(e[i]!==n){i+=1;continue}if(e[i+1]===n){i+=2;continue}return i+1}return-1}function o(e,t,n){let r=t+1,i=``;for(;r<e.length;){let t=e[r];if(t!==n){i+=t,r+=1;continue}if(e[r+1]===n){i+=n,r+=2;continue}return{end:r+1,value:i}}}export{r as t};
|
|
3
|
+
//# sourceMappingURL=sql-statement-tokens-Z5Ta4iDB.mjs.map
|
package/dist/{sql-statement-tokens-DbeMwHra.mjs.map → sql-statement-tokens-Z5Ta4iDB.mjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sql-statement-tokens-
|
|
1
|
+
{"version":3,"file":"sql-statement-tokens-Z5Ta4iDB.mjs","names":[],"sources":["../src/drivers/shared/sql-statement-tokens.ts"],"sourcesContent":["export interface SQLStatementToken {\n depth: number;\n kind: \"identifier\" | \"word\" | \"symbol\";\n value: string;\n}\n\nexport interface SQLStatementTokenOptions {\n /** MySQL string literals may escape the next character with a backslash. */\n backslashEscapes?: boolean;\n}\n\nconst WHITESPACE_REGEX = /\\s/;\nconst WORD_START_REGEX = /[A-Za-z_]/;\nconst WORD_PART_REGEX = /[A-Za-z0-9_$]/;\n\n/** Tokenize one SQL statement while ignoring comments, strings, and parameters. */\nexport function getTopLevelStatementTokens(\n sql: string,\n options: SQLStatementTokenOptions = {}\n): SQLStatementToken[] | undefined {\n const tokens: SQLStatementToken[] = [];\n let depth = 0;\n let index = 0;\n let statementEnded = false;\n\n while (index < sql.length) {\n const char = sql[index];\n const next = sql[index + 1];\n if (!char) break;\n if (WHITESPACE_REGEX.test(char)) {\n index += 1;\n continue;\n }\n if (char === \"-\" && next === \"-\") {\n index = skipLineComment(sql, index + 2);\n continue;\n }\n if (char === \"/\" && next === \"*\") {\n const commentEnd = sql.indexOf(\"*/\", index + 2);\n if (commentEnd < 0) return undefined;\n index = commentEnd + 2;\n continue;\n }\n if (char === \"'\") {\n const quotedEnd = skipQuoted(\n sql,\n index,\n char,\n options.backslashEscapes === true\n );\n if (quotedEnd < 0 || statementEnded) return undefined;\n index = quotedEnd;\n continue;\n }\n if (char === '\"' || char === \"`\" || char === \"[\") {\n const quote = char === \"[\" ? \"]\" : char;\n const identifier = readQuotedIdentifier(sql, index, quote);\n if (!identifier || statementEnded) return undefined;\n tokens.push({\n depth,\n kind: \"identifier\",\n value: identifier.value.toUpperCase(),\n });\n index = identifier.end;\n continue;\n }\n if (char === \";\" && depth === 0) {\n statementEnded = true;\n index += 1;\n continue;\n }\n if (statementEnded) return undefined;\n if (\n (char === \":\" || char === \"@\" || char === \"$\") &&\n WORD_START_REGEX.test(next ?? \"\")\n ) {\n index += 2;\n while (index < sql.length && WORD_PART_REGEX.test(sql[index] ?? \"\")) {\n index += 1;\n }\n continue;\n }\n if (char === \"(\") {\n tokens.push({ depth, kind: \"symbol\", value: char });\n depth += 1;\n index += 1;\n continue;\n }\n if (char === \")\") {\n depth -= 1;\n if (depth < 0) return undefined;\n tokens.push({ depth, kind: \"symbol\", value: char });\n index += 1;\n continue;\n }\n if (char === \"=\") {\n tokens.push({ depth, kind: \"symbol\", value: char });\n index += 1;\n continue;\n }\n if (WORD_START_REGEX.test(char)) {\n const start = index;\n index += 1;\n while (index < sql.length && WORD_PART_REGEX.test(sql[index] ?? \"\")) {\n index += 1;\n }\n tokens.push({\n depth,\n kind: \"word\",\n value: sql.slice(start, index).toUpperCase(),\n });\n continue;\n }\n index += 1;\n }\n\n if (depth !== 0) return undefined;\n return tokens.filter((token) => token.depth === 0);\n}\n\nfunction skipLineComment(sql: string, index: number): number {\n const lineEnd = sql.indexOf(\"\\n\", index);\n return lineEnd < 0 ? sql.length : lineEnd + 1;\n}\n\nfunction skipQuoted(\n sql: string,\n index: number,\n quote: string,\n backslashEscapes: boolean\n): number {\n let cursor = index + 1;\n while (cursor < sql.length) {\n if (backslashEscapes && sql[cursor] === \"\\\\\") {\n if (cursor + 1 >= sql.length) return -1;\n cursor += 2;\n continue;\n }\n if (sql[cursor] !== quote) {\n cursor += 1;\n continue;\n }\n if (sql[cursor + 1] === quote) {\n cursor += 2;\n continue;\n }\n return cursor + 1;\n }\n return -1;\n}\n\nfunction readQuotedIdentifier(\n sql: string,\n index: number,\n quote: string\n): { end: number; value: string } | undefined {\n let cursor = index + 1;\n let value = \"\";\n while (cursor < sql.length) {\n const char = sql[cursor];\n if (char !== quote) {\n value += char;\n cursor += 1;\n continue;\n }\n if (sql[cursor + 1] === quote) {\n value += quote;\n cursor += 2;\n continue;\n }\n return { end: cursor + 1, value };\n }\n return undefined;\n}\n"],"mappings":"AAWA,MAAM,EAAmB,KACnB,EAAmB,YACnB,EAAkB,gBAGxB,SAAgB,EACd,EACA,EAAoC,EAAE,CACL,CACjC,IAAM,EAA8B,EAAE,CAClC,EAAQ,EACR,EAAQ,EACR,EAAiB,GAErB,KAAO,EAAQ,EAAI,QAAQ,CACzB,IAAM,EAAO,EAAI,GACX,EAAO,EAAI,EAAQ,GACzB,GAAI,CAAC,EAAM,MACX,GAAI,EAAiB,KAAK,EAAK,CAAE,CAC/B,GAAS,EACT,SAEF,GAAI,IAAS,KAAO,IAAS,IAAK,CAChC,EAAQ,EAAgB,EAAK,EAAQ,EAAE,CACvC,SAEF,GAAI,IAAS,KAAO,IAAS,IAAK,CAChC,IAAM,EAAa,EAAI,QAAQ,KAAM,EAAQ,EAAE,CAC/C,GAAI,EAAa,EAAG,OACpB,EAAQ,EAAa,EACrB,SAEF,GAAI,IAAS,IAAK,CAChB,IAAM,EAAY,EAChB,EACA,EACA,EACA,EAAQ,mBAAqB,GAC9B,CACD,GAAI,EAAY,GAAK,EAAgB,OACrC,EAAQ,EACR,SAEF,GAAI,IAAS,KAAO,IAAS,KAAO,IAAS,IAAK,CAEhD,IAAM,EAAa,EAAqB,EAAK,EAD/B,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IAAI,EAAS,EAAQ,EACrB,KAAO,EAAS,EAAI,QAAQ,CAC1B,GAAI,GAAoB,EAAI,KAAY,KAAM,CAC5C,GAAI,EAAS,GAAK,EAAI,OAAQ,MAAO,GACrC,GAAU,EACV,SAEF,GAAI,EAAI,KAAY,EAAO,CACzB,GAAU,EACV,SAEF,GAAI,EAAI,EAAS,KAAO,EAAO,CAC7B,GAAU,EACV,SAEF,OAAO,EAAS,EAElB,MAAO,GAGT,SAAS,EACP,EACA,EACA,EAC4C,CAC5C,IAAI,EAAS,EAAQ,EACjB,EAAQ,GACZ,KAAO,EAAS,EAAI,QAAQ,CAC1B,IAAM,EAAO,EAAI,GACjB,GAAI,IAAS,EAAO,CAClB,GAAS,EACT,GAAU,EACV,SAEF,GAAI,EAAI,EAAS,KAAO,EAAO,CAC7B,GAAS,EACT,GAAU,EACV,SAEF,MAAO,CAAE,IAAK,EAAS,EAAG,QAAO"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=(e,t)=>e[t],t=(e,t)=>e[t],n=(n,r,i)=>i?e(n,r):t(n,r);var r=class e{static get name(){return`Sql`}om;lb;template;projection;statements;constructor(e,t,n=!1){if(e.length-1!==t.length)throw e.length===0?TypeError(`Expected at least 1 string`):TypeError(`Expected ${e.length} strings to have ${e.length-1} values`);this.om=e,this.lb=t,this.template=n}get values(){return this.flatten().values}get strings(){return this.flatten().strings}static peek(t){return t.projection??e.se(t)}static se(t){let r=[],i=[],a=``,o=(t,s,c)=>{a+=n(t,0,c);for(let l=0;l<s.length;l++){let u=s[l];u instanceof e?o(u.om,u.lb,u.template):(i.push(u),r.push(a),a=``),a+=n(t,l+1,c)}};return o(t.om,t.lb,t.template),r.push(a),{strings:r,values:i}}static leafText(t){return t.constructor===e&&t.lb.length===0?t.om[0]:void 0}static isSingleBound(t){return t.constructor===e&&t.om.length===2&&t.om[0]===``&&t.om[1]===``&&!(t.lb[0]instanceof e)}static singleBoundValue(e){return e.lb[0]}static peekRuns(t,r){let i=[],a=[],o=``,s=!1,c=e=>{e!==s&&(i.push({text:o,opaque:s}),o=``,s=e)},l=(t,u)=>{let d=u||r(t);c(d),o+=n(t.om,0,t.template);for(let r=0;r<t.lb.length;r++){let u=t.lb[r];u instanceof e?(l(u,d),c(d)):(a.push(u),i.push({text:o,opaque:s}),o=``),o+=n(t.om,r+1,t.template)}};return l(t,!1),i.push({text:o,opaque:s}),{runs:i,values:a}}static each(t,n){n(t);for(let r of t.lb)r instanceof e&&e.each(r,n)}static fill(e,t){e.om=[``,``],e.lb=[t]}flatten(){if(this.projection!==void 0)return this.projection;let t=e.se(this);return this.om=t.strings,this.lb=t.values,this.template=!1,this.projection=t,t}toStatement(e=`?`){let t=this.statements?.[e];if(t!==void 0)return t;let n=this.strings,r=n.length;if(r===1){let e=n[0];return this.statements={$n:e,":n":e,"?":e},e}let i;if(e===`?`)i=n.join(`?`);else{let t=e===`$n`?`$`:`:`,a=Array(r*2-1);a[0]=n[0];for(let e=1;e<r;e++)a[e*2-1]=t+e,a[e*2]=n[e];i=a.join(``)}let a=this.statements??{};return a[e]=i,this.statements=a,i}};function i(e,...t){if(t.length!==0||typeof e!=`string`&&e.length!==1)throw TypeError(`raw template cannot interpolate; use sql or raw(text).`);return typeof e==`string`?new r([e],[]):new r(e,[],!0)}function a(e,t=`,`,n=``,i=``){let a=e.length;if(a===0)return new r([n+i],[]);let o=Array(a+1);o[0]=n;for(let e=1;e<a;e++)o[e]=t;return o[a]=i,new r(o,e)}const o=i``;function s(e,...t){return new r(e,t,!0)}const c=Object.assign(s,{raw:i,empty:o,join:a});function l(e){if(e instanceof r)return!0;if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`strings`);if(!Array.isArray(t))return!1;let n=Reflect.get(e,`values`);return Array.isArray(n)&&t.length===n.length+1&&t.every(e=>typeof e==`string`)&&typeof Reflect.get(e,`toStatement`)==`function`}export{i as a,a as i,o as n,c as o,l as r,r as t};
|
|
2
|
+
//# sourceMappingURL=sql-tegqTqGq.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sql-tegqTqGq.mjs","names":[],"sources":["../src/sql/sql.ts"],"sourcesContent":["/**\n * Values supported by SQL engine.\n */\nexport type Value = unknown;\n\n/**\n * Supported value or SQL instance.\n */\nexport type RawValue = Value | Sql;\n\ntype Placeholder = \"$n\" | \":n\" | \"?\";\n\ninterface SqlProjection {\n strings: string[];\n values: Value[];\n}\n\ntype StatementCache = Partial<Record<Placeholder, string>>;\n\nconst templateString = (strings: readonly string[], index: number): string =>\n strings[index]!;\nconst listString = (strings: readonly string[], index: number): string =>\n strings[index]!;\n\n/**\n * The string of a fragment's `strings` at `index`, a tagged template's\n * (`template`: a frozen array) read at one place and any other array at\n * another. Read at the same place, the two kinds of array cost every read a\n * lookup: flattening the statement of a two-level read (109 fragments, 228\n * strings) took 2.2 µs, 1.8 µs read apart, and 1.5 µs over plain arrays alone.\n */\nconst stringAt = (\n strings: readonly string[],\n index: number,\n template: boolean\n): string =>\n template ? templateString(strings, index) : listString(strings, index);\n\n/**\n * A SQL instance can be nested within each other to build SQL strings.\n *\n * Composition is lazy: constructing a Sql just stores the raw fragments.\n * The nested tree is flattened in a single pass over raw fragments when\n * `strings`/`values` is first read (typically only on the root query), so\n * intermediate fragments never pay flattening or allocation.\n */\nexport class Sql {\n private rawStrings: readonly string[];\n private rawValues: readonly RawValue[];\n /** Whether `rawStrings` is a tagged template's strings ({@link stringAt}). */\n private template: boolean;\n\n private projection: SqlProjection | undefined;\n private statements: StatementCache | undefined;\n\n constructor(\n rawStrings: readonly string[],\n rawValues: readonly RawValue[],\n template = false\n ) {\n if (rawStrings.length - 1 !== rawValues.length) {\n if (rawStrings.length === 0) {\n throw new TypeError(\"Expected at least 1 string\");\n }\n throw new TypeError(\n `Expected ${rawStrings.length} strings to have ${\n rawStrings.length - 1\n } values`\n );\n }\n\n this.rawStrings = rawStrings;\n this.rawValues = rawValues;\n this.template = template;\n }\n\n get values(): Value[] {\n return this.flatten().values;\n }\n\n get strings(): string[] {\n return this.flatten().strings;\n }\n\n /**\n * The projection {@link flatten} makes of `fragment`, made without keeping\n * it: a fragment holding an open {@link SqlSlot} reads its provisional text\n * and stays open.\n */\n static peek(fragment: Sql): { strings: string[]; values: Value[] } {\n return fragment.projection ?? Sql.project(fragment);\n }\n\n /**\n * The flat strings and values of `fragment`'s raw tree, read in one pass\n * over the raw fragments, so a nested Sql is never flattened itself.\n */\n private static project(fragment: Sql): SqlProjection {\n const strings: string[] = [];\n const values: Value[] = [];\n let current = \"\";\n const walk = (\n rawStrings: readonly string[],\n rawValues: readonly RawValue[],\n template: boolean\n ): void => {\n current += stringAt(rawStrings, 0, template);\n for (let i = 0; i < rawValues.length; i++) {\n const child = rawValues[i]!;\n if (child instanceof Sql) {\n walk(child.rawStrings, child.rawValues, child.template);\n } else {\n values.push(child);\n strings.push(current);\n current = \"\";\n }\n current += stringAt(rawStrings, i + 1, template);\n }\n };\n walk(fragment.rawStrings, fragment.rawValues, fragment.template);\n strings.push(current);\n return { strings, values };\n }\n\n /**\n * The text of a fragment that holds no value and no fragment (a\n * `sql.raw`), read without composing anything; `undefined` for any other.\n */\n static leafText(fragment: Sql): string | undefined {\n return fragment.constructor === Sql && fragment.rawValues.length === 0\n ? fragment.rawStrings[0]\n : undefined;\n }\n\n /**\n * Whether `fragment` is a plain single bound parameter (`sql.value(v)`)\n * with no surrounding text, no nested fragment, and no open slot.\n */\n static isSingleBound(fragment: Sql): boolean {\n return (\n fragment.constructor === Sql &&\n fragment.rawStrings.length === 2 &&\n fragment.rawStrings[0] === \"\" &&\n fragment.rawStrings[1] === \"\" &&\n !(fragment.rawValues[0] instanceof Sql)\n );\n }\n\n /** The bound parameter of a fragment {@link isSingleBound} accepted. */\n static singleBoundValue(fragment: Sql): Value {\n return fragment.rawValues[0];\n }\n\n /**\n * {@link peek}'s text, also cut where a fragment `opaque` accepts begins\n * and ends, each run saying whether it lies inside one: a reader rewriting\n * the text its owner wrote can leave the text another party wrote alone.\n * Without an opaque fragment the runs are {@link peek}'s strings.\n */\n static peekRuns(\n fragment: Sql,\n opaque: (fragment: Sql) => boolean\n ): { runs: { text: string; opaque: boolean }[]; values: Value[] } {\n const runs: { text: string; opaque: boolean }[] = [];\n const values: Value[] = [];\n let current = \"\";\n let inside = false;\n const cut = (next: boolean): void => {\n if (next === inside) return;\n runs.push({ text: current, opaque: inside });\n current = \"\";\n inside = next;\n };\n const walk = (node: Sql, within: boolean): void => {\n const here = within || opaque(node);\n cut(here);\n current += stringAt(node.rawStrings, 0, node.template);\n for (let i = 0; i < node.rawValues.length; i++) {\n const child = node.rawValues[i]!;\n if (child instanceof Sql) {\n walk(child, here);\n cut(here);\n } else {\n values.push(child);\n runs.push({ text: current, opaque: inside });\n current = \"\";\n }\n current += stringAt(node.rawStrings, i + 1, node.template);\n }\n };\n walk(fragment, false);\n runs.push({ text: current, opaque: inside });\n return { runs, values };\n }\n\n /**\n * Visit `fragment` and every fragment composed into it, outermost first.\n * A flattened fragment holds no fragment any more: only its own visit.\n */\n static each(fragment: Sql, visit: (node: Sql) => void): void {\n visit(fragment);\n for (const child of fragment.rawValues)\n if (child instanceof Sql) Sql.each(child, visit);\n }\n\n /** `slot`'s text replaced by `content`'s (see {@link SqlSlot.settle}). */\n protected static fill(slot: Sql, content: Sql): void {\n slot.rawStrings = [\"\", \"\"];\n slot.rawValues = [content];\n }\n\n /**\n * Flatten the raw fragment tree ({@link project}). The flat arrays then\n * replace the raw tree as the canonical representation, releasing child\n * fragments that are not referenced elsewhere.\n */\n private flatten(): SqlProjection {\n if (this.projection !== undefined) {\n return this.projection;\n }\n\n const projection = Sql.project(this);\n\n this.rawStrings = projection.strings;\n this.rawValues = projection.values;\n this.template = false;\n this.projection = projection;\n\n return projection;\n }\n\n /**\n * Build the final SQL statement string with placeholders.\n * Results are cached per placeholder type for reuse.\n */\n toStatement(placeholder: Placeholder = \"?\"): string {\n const cached = this.statements?.[placeholder];\n if (cached !== undefined) return cached;\n\n const strings = this.strings;\n const len = strings.length;\n\n if (len === 1) {\n const result = strings[0]!;\n this.statements = { $n: result, \":n\": result, \"?\": result };\n return result;\n }\n\n let result: string;\n\n if (placeholder === \"?\") {\n result = strings.join(\"?\");\n } else {\n const prefix = placeholder === \"$n\" ? \"$\" : \":\";\n const parts = new Array<string>(len * 2 - 1);\n parts[0] = strings[0]!;\n for (let i = 1; i < len; i++) {\n parts[i * 2 - 1] = prefix + i;\n parts[i * 2] = strings[i]!;\n }\n result = parts.join(\"\");\n }\n\n const statements = this.statements ?? {};\n statements[placeholder] = result;\n this.statements = statements;\n\n return result;\n }\n}\n\n/**\n * Splice text into a statement verbatim — nothing here is bound as a\n * parameter. Two shapes live under this one name:\n *\n * - `raw(\"ORDER BY name DESC\")` — Prisma's unsafe string splice. The caller\n * owns the escaping; never hand it user input.\n * - ``raw`TRUE` `` — the tagged-template form the adapters use for dialect\n * keywords. Interpolations are refused; use `sql` for bound values.\n */\nfunction raw(value: string | readonly string[]): Sql;\nfunction raw(\n strings: string | readonly string[],\n ...values: readonly RawValue[]\n): Sql {\n if (\n values.length !== 0 ||\n (typeof strings !== \"string\" && strings.length !== 1)\n )\n throw new TypeError(\n \"raw template cannot interpolate; use sql or raw(text).\"\n );\n if (typeof strings === \"string\") {\n return new Sql([strings], []);\n }\n return new Sql(strings, [], true);\n}\n\n/**\n * Create a SQL query for a list of values.\n *\n * Values are `RawValue`s, matching Prisma: a nested `Sql` is spliced as a\n * fragment, anything else becomes a bound parameter.\n */\nfunction join(\n values: readonly RawValue[],\n separator = \",\",\n prefix = \"\",\n suffix = \"\"\n) {\n const len = values.length;\n if (len === 0) {\n return new Sql([prefix + suffix], []);\n }\n\n // Pre-allocate array with exact size instead of spread + fill\n const strings = new Array<string>(len + 1);\n strings[0] = prefix;\n for (let i = 1; i < len; i++) {\n strings[i] = separator;\n }\n strings[len] = suffix;\n\n return new Sql(strings, values);\n}\n\n/**\n * Placeholder value for \"no text\".\n */\nconst empty = raw``;\n\n/**\n * Create a SQL object from a template string.\n */\nfunction sql(strings: readonly string[], ...values: readonly RawValue[]) {\n return new Sql(strings, values, true);\n}\n\nconst sqlTag = Object.assign(sql, { raw, empty, join });\n\nexport { empty, join, raw, sqlTag as sql };\n\n/**\n * Type guard for Sql fragments. Structural check rather than instanceof so it\n * also matches fragments from a duplicated module instance. A document with\n * strings/values arrays is data; executable SQL also has the renderer method.\n */\nexport function isSql(value: unknown): value is Sql {\n if (value instanceof Sql) return true;\n if (value === null || typeof value !== \"object\") return false;\n\n const strings = Reflect.get(value, \"strings\");\n if (!Array.isArray(strings)) return false;\n\n const values = Reflect.get(value, \"values\");\n return (\n Array.isArray(values) &&\n strings.length === values.length + 1 &&\n strings.every((part) => typeof part === \"string\") &&\n typeof Reflect.get(value, \"toStatement\") === \"function\"\n );\n}\n"],"mappings":"AAmBA,MAAM,GAAkB,EAA4B,IAClD,EAAQ,GACJ,GAAc,EAA4B,IAC9C,EAAQ,GASJ,GACJ,EACA,EACA,IAEA,EAAW,EAAe,EAAS,EAAM,CAAG,EAAW,EAAS,EAAM,CAUxE,IAAa,EAAb,MAAa,CAAI,CAAA,WAAA,MAAA,CAAA,MAAA,MACf,WACA,UAEA,SAEA,WACA,WAEA,YACE,EACA,EACA,EAAW,GACX,CACA,GAAI,EAAW,OAAS,IAAM,EAAU,OAItC,MAHI,EAAW,SAAW,EACd,UAAU,6BAA6B,CAEzC,UACR,YAAY,EAAW,OAAO,mBAC5B,EAAW,OAAS,EACrB,SACF,CAGH,KAAK,WAAa,EAClB,KAAK,UAAY,EACjB,KAAK,SAAW,EAGlB,IAAI,QAAkB,CACpB,OAAO,KAAK,SAAS,CAAC,OAGxB,IAAI,SAAoB,CACtB,OAAO,KAAK,SAAS,CAAC,QAQxB,OAAO,KAAK,EAAuD,CACjE,OAAO,EAAS,YAAc,EAAI,QAAQ,EAAS,CAOrD,OAAe,QAAQ,EAA8B,CACnD,IAAM,EAAoB,EAAE,CACtB,EAAkB,EAAE,CACtB,EAAU,GACR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ist/sql.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as isSql, c as sqlTag, i as empty, n as Sql, o as join, r as Value, s as raw, t as RawValue } from "./sql-
|
|
1
|
+
import { a as isSql, c as sqlTag, i as empty, n as Sql, o as join, r as Value, s as raw, t as RawValue } from "./sql-C4_sFNDm.mjs";
|
|
2
2
|
export { RawValue, Sql, Value, empty, isSql, join, raw, sqlTag as sql };
|
package/dist/sql.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,i as t,n,o as r,r as i,t as a}from"./sql-
|
|
1
|
+
import{a as e,i as t,n,o as r,r as i,t as a}from"./sql-tegqTqGq.mjs";export{a as Sql,n as empty,i as isSql,t as join,e as raw,r as sql};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as e,m as t}from"./validation-ATmgN5RE.mjs";import{o as n,t as r}from"./sql-tegqTqGq.mjs";import{d as i,f as a,i as o,p as s,u as c}from"./datetime-physical-codec-DAF7WJpy.mjs";import{P as l}from"./native-types-1ewJXVks.mjs";import{i as ee}from"./id-domain-Cg65TLZ-.mjs";import{t as u}from"./physical-DO4PEYcc.mjs";import{t as te}from"./identifiers-BxOf57qy.mjs";import{A as ne,C as d,D as f,E as p,F as re,L as m,M as ie,O as ae,S as oe,T as se,_ as ce,a as le,b as ue,c as de,f as fe,h as pe,i as me,j as he,k as h,m as ge,n as _e,o as ve,p as g,r as ye,s as be,u as _,v,w as y,x as b,y as x}from"./standard-sql-Bl2OHGfi.mjs";import{t as S}from"./json-number-C09rsm1g.mjs";import{f as C,h as w,n as T,o as E,p as D,r as O,t as k,u as A}from"./select-assembly-CEpNu-Gw.mjs";import{r as j,t as M}from"./batch-refs-Bd8HvwUc.mjs";const N=te(`"`),P={gu:(e,t)=>n`(${e} / ${t})`,remainder:(e,t)=>n`(${e} % ${t})`};function F(e){let t=he(e);if(t<19)return t;if(!(t>19))return(e.startsWith(`-`)?e.slice(1)<=`9223372036854775808`:e<=`9223372036854775807`)?t:void 0}const I=n.raw(`1000000000000000000`),xe=e=>n.raw(`1${`0`.repeat(Math.min(e.precision,18))}`),L=(e,t,r,i)=>n`${e} = CASE WHEN ${e} IS NULL OR ${t} THEN ${r} ELSE ${xe(i)} END`,Se=/^\d+$/,Ce=/["\\]/,R=e=>{if(Se.test(e))return`$[${e}]`;if(Ce.test(e))throw Error(`SQLite JSON path cannot contain " or \\.`);return`$."${e}"`},z=(e,t)=>{let r=n`${e} -> '$'`;for(let e of t)r=n`${r} -> ${R(e)}`;return r},B=(e,t)=>{if(t.length===0)return n`${e} ->> '$'`;let r=e;for(let e=0;e<t.length-1;e++)r=n`${r} -> ${R(t[e])}`;return n`${r} ->> ${R(t.at(-1))}`},V=(e,t)=>n`(CASE WHEN ${e} = '[]' THEN ${t} WHEN ${t} = '[]' THEN ${e} ELSE substr(${e}, 1, length(${e}) - 1) || ',' || substr(${t}, 2) END)`,H=e=>n`${m(e)}`,we=[``,``],U=[`CAST(`,` AS INTEGER)`],Te=/\p{Cs}/u,W=h().list;function Ee(e){return typeof e==`string`?Te.test(e)?void 0:JSON.stringify(e):e instanceof Uint8Array?`"${_e(e)}"`:typeof e==`bigint`||typeof e==`boolean`||Number.isSafeInteger(e)?String(e):void 0}function De(e){if(e.length<=25)return W(e);let[t]=e,i=t?.strings[0]===U[0]?U:we,a=[],o=0;for(let t of e){let[n,r,s]=t.strings,c=t.values[0],l=Ee(c);if(l===void 0||n!==i[0]||r!==i[1]||s!==void 0)return W(e);c instanceof Uint8Array&&o++,a.push(l)}return o!==0&&o!==e.length?W(e):n`(SELECT ${new r(i,[n.raw(o===0?`value`:`unhex(value)`)])} FROM json_each(${`[${a.join(`,`)}]`}))`}const G={...h(),value:e=>{if(typeof e==`bigint`&&F(String(e))===void 0)throw new t(`SQLite bigint values must fit signed 64-bit integers.`);return n`${e}`},true:()=>n.raw(`1`),false:()=>n.raw(`0`),json:e=>n`${JSON.stringify(e)}`,dateTime:(e,t)=>n`${o(e,u(t))}`,decimal:(e,t)=>new r(U,[l(e,t,`coefficient`)]),id:(e,t)=>n`${e}`,list:De},K={...ve(),containsText:(e,t)=>n`instr(${e}, ${t}) > 0`,startsWithText:(e,t)=>n`substr(${e}, 1, length(${t})) COLLATE BINARY = ${t}`,endsWithText:(e,t)=>n`substr(${e}, length(${e}) - length(${t}) + 1) COLLATE BINARY = ${t}`,insensitiveText(e,t,r){return this[`${e}Text`](n`lower(${t})`,n`lower(${r})`)},startsWithPrefix:(e,t)=>n`${e} GLOB ${`${ie(t)}*`}`,exactTextEq:(e,t)=>n`${e} COLLATE BINARY = ${t}`,exactTextIn:(e,t)=>n`${e} COLLATE BINARY IN ${t}`,...v(),...b(),...y(),...ce(G.true,G.false),...fe()},Oe={...le(),caseFold:e=>n`lower(${e})`,caseSensitiveText:e=>n`${e} COLLATE BINARY`,concat:re,greatest:(...e)=>n`MAX(${n.join(e,`, `)})`,least:(...e)=>n`MIN(${n.join(e,`, `)})`,integerDivide:(e,t)=>n`(${e} / CAST(${t} AS INTEGER))`,decimalCast:(e,t)=>n`CAST(${e} AS INTEGER)`,idCast:(e,t)=>t===`bytes`?n`unhex(${e})`:n`CAST(${e} AS TEXT)`,cast:me({text:`TEXT`,integer:`INTEGER`,bigint:`INTEGER`,boolean:`INTEGER`,numeric:`NUMERIC`}),blobToHex:e=>n`lower(hex(${e}))`},ke={...ye(`9e999`),decimalAvg:(e,t)=>E(P,n`SUM(${e})`,n`COUNT(${e})`),decimalSumOperandPrecision:F,integerSum:e=>{let t=n`SUM(${e} >> 32)`,r=n`SUM(${e} - ((${e} >> 32) << 32))`,i=n`(${t} + (${r} >> 32))`,a=n`(${r} & 4294967295)`,o=n`${i} * 4294967296.0 + ${a}`;return{parts:[t,r],value:n`CASE WHEN ${i} > 2147483647 THEN ${o} WHEN ${i} >= -2147483648 THEN ${i} * 4294967296 + ${a} ELSE MIN(${o}, -9223372036854777856.0) END`,order:[i,a]}}};function q(e,t){let r=e=>n`SELECT fullkey, CASE WHEN type IN ('integer', 'real') THEN 'number' ELSE type END, atom FROM json_tree(${e})`;return n`(CASE WHEN ${e} IS NULL OR ${t} IS NULL THEN NULL ELSE NOT EXISTS (${r(e)} EXCEPT ${r(t)}) AND NOT EXISTS (${r(t)} EXCEPT ${r(e)}) END)`}const J=e=>{if(e.length===0)return n.raw(`json_object()`);let t=e.flatMap(([e,t])=>[n`${e}`,t]);return n`json_object(${n.join(t,`, `)})`},Y=e=>e.length===0?n.raw(`json_array()`):n`json_array(${n.join(e,`, `)})`,Ae={equals:q,number:e=>n`CASE WHEN ${e} IS NULL THEN NULL ELSE printf(${n.raw(`'${S}'`)}, ${e}) END`,boolean:e=>n`json(CASE WHEN ${e} THEN 'true' ELSE 'false' END)`,document:e=>n`json(${e})`,object:J,array:Y,emptyArray:()=>n.raw(`json_array()`),agg:e=>n`json_group_array(${e})`,objectFromColumns:J,extract:z,extractText:B,numberAtPath:(e,t)=>n`(CASE WHEN json_type(${z(e,t)}) IN ('integer', 'real') THEN CAST(${B(e,t)} AS REAL) END)`,stringAtPath:(e,t)=>n`((CASE WHEN json_type(${z(e,t)}) = 'text' THEN ${B(e,t)} END) COLLATE BINARY)`,foldableStringAtPath(e,t){return this.stringAtPath(e,t)},contains:(e,t)=>n`(json_type(${e}) = 'array' AND NOT EXISTS (SELECT 1 FROM json_each(${t}) AS required WHERE NOT EXISTS (SELECT 1 FROM json_each(${e}) AS candidate WHERE ${q(n`${e} -> candidate.fullkey`,n`${t} -> required.fullkey`)})))`,lastElement:e=>n`${e} -> '$[#-1]'`,value:e=>n`${m(e)}`},je={literal:Y,value:H,enumValue:H,has:(e,t)=>n`EXISTS (SELECT 1 FROM json_each(${e}) WHERE value = ${t})`,hasEvery:(e,t)=>n`(SELECT COUNT(*) FROM json_each(${t}) WHERE value IN (SELECT value FROM json_each(${e}))) = json_array_length(${t})`,hasSome:(e,t)=>n`EXISTS (SELECT 1 FROM json_each(${e}) AS a, json_each(${t}) AS b WHERE a.value = b.value)`,isEmpty:e=>n`(json_array_length(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>n`CAST(${e} AS TEXT)`,length:e=>n`json_array_length(${e})`,get:(e,t)=>n`json_extract(${e}, '$[' || ${t} || ']')`,push:(e,t)=>n`json_insert(${e}, '$[#]', ${t})`,set:(e,t,r)=>n`json_set(${e}, '$[' || ${t} || ']', ${r})`},Me={..._(),...ue()},Ne={...oe(),multiply:(e,t,r)=>{let i=r?.decimal;return i?L(e,n`${t} = 0 OR ABS(${e}) <= ${I} / ABS(${t})`,E(P,n`(${e} * ${t})`,A(i.scale)),i):n`${e} = ${e} * ${t}`},divide:(e,t,r)=>{let i=r?.decimal;if(i){let r=A(i.scale);return L(e,n`ABS(${e}) <= ${I} / ${r}`,E(P,C(n`(${e} * ${r})`,t),n`ABS(${t})`),i)}return r?.integer?n`${e} = ${e} / CAST(${t} AS INTEGER)`:n`${e} = ${e} / ${t}`},push:(e,t)=>n`${e} = ${V(n`json(COALESCE(${e}, '[]'))`,t)}`,unshift:(e,t)=>n`${e} = ${V(t,n`json(COALESCE(${e}, '[]'))`)}`},Pe={skipDuplicatesStrategy:`sql`,insert:pe(N),insertAbsent:ge(N),insertDefault:e=>n`INSERT INTO ${e} DEFAULT VALUES`,...x(),returning:e=>n`RETURNING ${e}`,...d()},X=e=>t=>n`SELECT CASE WHEN ${n.raw(e)}EXISTS (${t}) THEN 1 ELSE json_extract('x', '$') END AS "__viborm_assert__"`,Fe={exists:X(``),notExists:X(`NOT `)},Z=e=>(...t)=>{throw Error(`SQLite does not support ${e}.`)},Q={...be(),right:Z(`RIGHT JOIN`),full:Z(`FULL OUTER JOIN`),lateral:Z(`LATERAL joins`),lateralLeft:Z(`LATERAL joins`)},Ie={carriesDocumentsAsArrays:!0,supportsReturning:!0,supportsCteWithMutations:!1,supportsFullOuterJoin:!1,supportsLateralJoins:!1,supportsVector:!1,supportsUpsertWhere:!0,supportsTargetedUpsert:!0,supportsMutationTargetInSubquery:!0,supportsMutationRowLimit:!1,supportsRowLocks:!1,joinsJunctionFilters:!0},Le={decimalRepresentation:`coefficient`,decimalListRepresentation:`coefficient`,dateTimeRepresentation:u,idRepresentation:(e,t)=>ee(e,t,`sqlite`)?.representation??`text`,parseResult:s,parseRelation:a,parseField:i},Re=g(N),ze=g(N,`main`).table,Be=ae(),Ve=p(),$=ne(N,!0),He=de(N,{zv:n.raw(`MATERIALIZED`)}),Ue=f(),We=se();function Ge(e){let t=(...n)=>{if(n.length<=2)return e(...n);let r=Math.floor(n.length/2);return e(t(...n.slice(0,r)),t(...n.slice(r)))};return t}var Ke=class{static get name(){return`SQLiteAdapter`}constructor({temporaryObjects:e=!0,deepExpressions:t=!0,sharedRelationBodies:r=!1,compoundSelectTerms:i,relationsPerStatement:a,countsCascadedChanges:o}={}){D(this,this.geoPoint),t||(this.subqueries.existsCheck=(e,t)=>n`SELECT 1 FROM (${$.existsCheck(e,t)})`,this.subqueries.isolated=e=>n`EXISTS (SELECT 1 FROM (SELECT 1 WHERE ${e}))`,this.operators.and=Ge(K.and),this.capabilities.boundsExpressionDepth=!0),r&&(this.capabilities.sharesRelationBodies=!0),i!==void 0&&(this.capabilities.compoundSelectTerms=i),a!==void 0&&(this.capabilities.relationsPerStatement=a),o&&(this.capabilities.countsCascadedChanges=!0);let s,l=()=>this.#t(e);c(this,{get bb(){return s??=l(),s},constraints:w,yq:ze,select:this.#e.select})}raw=We;identifiers={...Re};literals={...G};operators={...K};expressions={...Oe};aggregates={...ke};json={...Ae};arrays={...je};orderBy={...Me};clauses={...Be};set={...Ne};filters={...Ve};subqueries={...$};noLimitValue=n.raw(`-1`);#e={select:e=>e.distinct?k(e,e.distinct,this.identifiers.escape,this.noLimitValue):T(e,{sb:`omit`,noLimitValue:this.noLimitValue})};cte={...He};mutations={...Pe};assertions={...Fe};joins={...Q};setOperations={...Ue};capabilities={...Ie};lastInsertId=()=>n.raw(`last_insert_rowid()`);#t(e){let t=n.raw(N(M)),r=n.raw(e?`CREATE TEMP TABLE IF NOT EXISTS`:`CREATE TABLE IF NOT EXISTS`);return j({table:t,oj:n.raw(`"batch_id"`),hx:n.raw(`"ref_key"`),ly:n.raw(`"ref_value"`),createTable:n`${r} ${t} ("batch_id" TEXT NOT NULL, "ref_key" TEXT NOT NULL, "ref_value" TEXT, PRIMARY KEY ("batch_id", "ref_key"))`,wd:e=>n`CAST((${e}) AS TEXT)`,lastInsertId:()=>this.lastInsertId()})}vector=e;geoPoint=(()=>{let e=e=>this.json.numberAtPath(e,[`longitude`]),t=e=>this.json.numberAtPath(e,[`latitude`]);return{value:(e,t)=>n`json_object('longitude', ${this.json.document(this.json.number(e))}, 'latitude', ${this.json.document(this.json.number(t))})`,longitude:e,latitude:t,...O(e,t,this.operators)}})();refreshAuto(e,t){let r=this.identifiers.table(e);return[n`DELETE FROM ${r}`,n`INSERT INTO ${r} SELECT * FROM ${this.identifiers.table(t)}`]}result={...Le}};export{Ke as t};
|
|
2
|
+
//# sourceMappingURL=sqlite-adapter-Cb-SJw2f.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sqlite-adapter-Cb-SJw2f.mjs","names":[],"sources":["../src/adapters/databases/sqlite/sqlite-adapter.ts"],"sourcesContent":["import { UnsupportedOperationError, unsupportedVector } from \"@errors\";\nimport { sqliteDateTimePhysicalForm } from \"@schema/scalars/datetime/physical\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { Sql, sql } from \"@sql\";\nimport { encodePhysicalDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport type {\n ArithmeticTarget,\n BatchReferenceSqlAdapter,\n} from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport {\n type AdapterResultParser,\n passThroughParseField,\n passThroughParseRelation,\n passThroughParseResult,\n} from \"../../adapter-result-parser\";\nimport { sqliteConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n type TextMatch,\n} from \"../../database-adapter\";\nimport {\n BATCH_REFS_TABLE,\n createOnConflictBatchRefs,\n} from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n halfEvenQuotient,\n scaleFactorSql,\n signedNumerator,\n} from \"../../shared/decimal-arithmetic\";\nimport { createGeoPointCoordinatePredicates } from \"../../shared/geo-point\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n bytesToHex,\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDirectionOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertAbsent,\n createInsertStatement,\n createLogicalOperators,\n createMembershipOperators,\n createMutationCommands,\n createNativeNullsOrderBy,\n createNullOperators,\n createNumericSetOperations,\n createOnConflictBuilders,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n decimalCoefficientPrecision,\n escapeGlobLiteral,\n pipeConcat,\n stringifyJson,\n} from \"../../shared/standard-sql\";\nimport { SQLITE_BINARY64_FORMAT } from \"./storage/json-number\";\n\nconst quoteIdent = createIdentifierQuoter('\"');\n\n/**\n * Every SQLite decimal expression is signed-int64 integer arithmetic on the\n * stored unscaled coefficient, so `/` IS truncating integer division and `%`\n * carries the dividend's sign. Neither is true once an operand becomes REAL or\n * TEXT, which is why every operand below arrives as an INTEGER column, an\n * integer literal, or a `CAST(... AS INTEGER)` bind.\n */\nconst SQLITE_INTEGERS: ExactIntegerArithmetic = {\n quotient: (n: Sql, d: Sql): Sql => sql`(${n} / ${d})`,\n remainder: (n: Sql, d: Sql): Sql => sql`(${n} % ${d})`,\n};\n\nconst SQLITE_INT64_NEGATIVE_MAGNITUDE = \"9223372036854775808\";\nconst SQLITE_INT64_MAX = \"9223372036854775807\";\n\n/** Admit the exact TEXT-to-INTEGER cast domain, including its 19-digit edges. */\nfunction sqliteIntegerPrecision(coefficient: string): number | undefined {\n const precision = decimalCoefficientPrecision(coefficient);\n if (precision < 19) return precision;\n if (precision > 19) return undefined;\n const isAdmitted = coefficient.startsWith(\"-\")\n ? coefficient.slice(1) <= SQLITE_INT64_NEGATIVE_MAGNITUDE\n : coefficient <= SQLITE_INT64_MAX;\n return isAdmitted ? precision : undefined;\n}\n\n/**\n * The widest intermediate the guarded arms will evaluate: 10^18.\n *\n * SQLite does not raise on an integer multiply that overflows — it converts the\n * expression to REAL, which is the one representation an exact decimal must\n * never touch. So the arms are GUARDED: the guard compares magnitudes by\n * DIVISION (`|x| <= LIMIT / |y|`, exact for integers) instead of computing the\n * product it is protecting, and a `CASE` evaluates only the branch it selects.\n *\n * 10^18 is not arbitrary, and it is not independent. `precision + scale <= 18`\n * is SQLite's declared field limit (plan 3.1), ENFORCED once when the schema is\n * bound (`schema/scalars/decimal/provider-limits.ts`), so every mathematically\n * in-range result has `|x * y| <= 10^(p+s) <= 10^18`: the guard never rejects\n * an answer that fits the field, and int64 keeps a factor of nine in reserve\n * for the `+/- 1` step and the `d - |r|` tie test.\n *\n * THE COUPLING IS LOAD-BEARING, in both directions. This constant is flat where\n * the per-descriptor bound would be `B = scale === 0 ? M : M*F + F/2 - 1`, and\n * that is only equivalent because no descriptor past `p + s = 18` can reach it:\n * a product in `(B, 10^18]` is admitted here and then refused by the range\n * CHECK instead of by the sentinel — the same loud, atomic failure by the other\n * mechanism. Remove the bind limit and the flat guard stops being a bound on\n * the FIELD at all, which is exactly what {@link overflowCoefficient} depends\n * on below.\n */\nconst SQLITE_INTERMEDIATE_LIMIT = sql.raw(\"1000000000000000000\");\n\n/**\n * The coefficient an unsafe or out-of-domain arithmetic result becomes: 10^p,\n * the smallest integer OUTSIDE a `precision: p` field's declared range.\n *\n * The DDL's range check refuses it, so the statement fails atomically and\n * nothing is written — which is the contract for an overflow that is only\n * knowable mid-statement.\n *\n * THE CLAMP DEPENDS ON THE BIND LIMIT, and is only correct because of it. At 19\n * digits and beyond, `10^p` is a REAL to SQLite's own parser, so the sentinel\n * would stop being an integer the CHECK can refuse — and `min(p, 18)` would put\n * it INSIDE the range of a `precision >= 19` column, which is a silently\n * written wrong value rather than a failure. No such column exists: plan 3.1's\n * `precision <= 18 && precision + scale <= 18` is proven once at schema bind\n * (`schema/scalars/decimal/provider-limits.ts`), before any I/O, so\n * `min(p, 18)` is `p` for every descriptor that ever reaches here. The clamp is\n * what an unreachable arm does when it is reached anyway, not a policy — and it\n * is why the bind limit is load-bearing rather than ergonomic.\n */\nconst overflowCoefficient = (descriptor: DecimalDescriptor): Sql =>\n sql.raw(`1${\"0\".repeat(Math.min(descriptor.precision, 18))}`);\n\n/**\n * `column = <exact coefficient arithmetic>`, or the constraint-breaking\n * coefficient when the intermediate would leave int64.\n *\n * A NULL column is safe by definition and takes the guarded arm, where every\n * operator is null-strict and the assignment stays NULL.\n */\nconst guardedCoefficientAssignment = (\n column: Sql,\n safe: Sql,\n value: Sql,\n descriptor: DecimalDescriptor\n): Sql =>\n sql`${column} = CASE WHEN ${column} IS NULL OR ${safe} THEN ${value} ELSE ${overflowCoefficient(descriptor)} END`;\n\nconst JSON_ARRAY_INDEX_SEGMENT = /^\\d+$/;\nconst JSON_UNADDRESSABLE_LABEL = /[\"\\\\]/;\n\n// Each path segment binds as its own single-leg JSONPath ('$[N]' for\n// array indices, '$.\"seg\"' otherwise) chained with -> , so segments can\n// never splice extra legs into the path. SQLite's path grammar has no\n// escape syntax inside quoted labels, so the portable query contract rejects\n// keys containing \" or \\ before adapter execution. This throw is defensive.\nconst jsonPathLeg = (segment: string): string => {\n if (JSON_ARRAY_INDEX_SEGMENT.test(segment)) {\n return `$[${segment}]`;\n }\n if (JSON_UNADDRESSABLE_LABEL.test(segment)) {\n throw new Error('SQLite JSON path cannot contain \" or \\\\.');\n }\n return `$.\"${segment}\"`;\n};\n\n/** Chain one bound `-> '$leg'` per path segment ('$' alone = document root). */\nconst jsonExtract = (column: Sql, path: string[]): Sql => {\n let expr = sql`${column} -> '$'`;\n for (const segment of path) expr = sql`${expr} -> ${jsonPathLeg(segment)}`;\n return expr;\n};\n\n/** Same chain, but the final leg uses `->>` so strings come back unquoted. */\nconst jsonExtractText = (column: Sql, path: string[]): Sql => {\n if (path.length === 0) return sql`${column} ->> '$'`;\n let expr = column;\n for (let i = 0; i < path.length - 1; i++)\n expr = sql`${expr} -> ${jsonPathLeg(path[i]!)}`;\n return sql`${expr} ->> ${jsonPathLeg(path.at(-1)!)}`;\n};\n\n/**\n * Concatenate two JSON array texts by string surgery: strip `left`'s closing\n * bracket and `right`'s opening bracket. SQLite has no JSON array-concat\n * function, and json_insert('$[#]') can only append one element per pair.\n * Both sides must be canonical JSON (json() output or JSON.stringify).\n */\nconst jsonArrayConcat = (left: Sql, right: Sql): Sql =>\n sql`(CASE WHEN ${left} = '[]' THEN ${right} WHEN ${right} = '[]' THEN ${left} ELSE substr(${left}, 1, length(${left}) - 1) || ',' || substr(${right}, 2) END)`;\n\n/** The one JSON list container every SQLite list value crosses as. */\nconst sqliteJsonListValue = (values: unknown[]): Sql =>\n sql`${stringifyJson(values)}`;\n\n/** A bare operand, and a decimal operand: its coefficient read as INTEGER. */\nconst PARAMETER = [\"\", \"\"];\nconst COEFFICIENT = [\"CAST(\", \" AS INTEGER)\"];\nconst LONE_SURROGATE = /\\p{Cs}/u;\nconst PARENTHESIZED_LIST = createStandardLiterals().list;\n/**\n * The longest list kept parenthesized. Without `sqlite_stat1` SQLite sizes an\n * `IN (SELECT …)` at 25 rows and a list at its length, so up to 25 members the\n * list is planned no worse: a key list beside another indexed equality still\n * seeks the key. It is also a quarter of D1's 100-value bind budget.\n */\nconst PLANNED_LIST = 25;\n\n/**\n * One member as JSON text that `json_each` reads back as the value its own\n * parameter binds, or `undefined`. A non-integer number is not one: SQLite\n * reparses JSON text with an error in the last place for some doubles; nor is\n * a string with a lone surrogate, which a driver binds as U+FFFD.\n */\nfunction jsonMember(value: unknown): string | undefined {\n if (typeof value === \"string\")\n return LONE_SURROGATE.test(value) ? undefined : JSON.stringify(value);\n if (value instanceof Uint8Array) return `\"${bytesToHex(value)}\"`;\n return typeof value === \"bigint\" ||\n typeof value === \"boolean\" ||\n Number.isSafeInteger(value)\n ? String(value)\n : undefined;\n}\n\n/**\n * engine-09: a list longer than {@link PLANNED_LIST} whose members are each one\n * parameter under one spelling — bare, or a decimal's coefficient cast — as\n * ONE parameter, a JSON array `json_each` reads back and spells per element as\n * each member was, so `IN` and `NOT IN` keep their answers, NULLs included.\n * Blobs travel as hex, read through `unhex` (SQLite 3.41). Any other list\n * keeps a parameter per member.\n */\nfunction sqliteList(members: Sql[]): Sql {\n if (members.length <= PLANNED_LIST) return PARENTHESIZED_LIST(members);\n const [first] = members;\n const spelling =\n first?.strings[0] === COEFFICIENT[0] ? COEFFICIENT : PARAMETER;\n const elements: string[] = [];\n let blobs = 0;\n for (const member of members) {\n const [head, tail, extra] = member.strings;\n const value = member.values[0];\n const element = jsonMember(value);\n if (\n element === undefined ||\n head !== spelling[0] ||\n tail !== spelling[1] ||\n extra !== undefined\n )\n return PARENTHESIZED_LIST(members);\n if (value instanceof Uint8Array) blobs++;\n elements.push(element);\n }\n // Blobs beside other values: nothing one spelling reads.\n if (blobs !== 0 && blobs !== members.length)\n return PARENTHESIZED_LIST(members);\n const read = new Sql(spelling, [\n sql.raw(blobs === 0 ? \"value\" : \"unhex(value)\"),\n ]);\n return sql`(SELECT ${read} FROM json_each(${`[${elements.join(\",\")}]`}))`;\n}\n\n/** Facts a SQLite driver states about its transport. */\nexport interface SQLiteAdapterOptions {\n /**\n * Whether the transport admits temporary objects (`CREATE TEMP TABLE`).\n * better-sqlite3, libSQL and bun:sqlite do; Cloudflare D1's authorizer\n * rejects them with `SQLITE_AUTH`, and rejects the whole batch with them.\n * Defaults to `true`.\n */\n readonly temporaryObjects?: boolean;\n /**\n * Whether the transport compiles deep expression trees. SQLite counts a\n * subquery's `WHERE` in the height of the expression that holds it, and sums\n * those heights again while it resolves names, so k nested relation filters\n * cost about k² of `SQLITE_MAX_EXPR_DEPTH`: SQLite's default (1000) admits\n * that; Cloudflare D1 compiles with 100 and refuses \"Expression tree is too\n * large\". Where it does not, each relation filter reads its rows from a\n * derived table, whose `WHERE` neither count reaches through the expression:\n * about four per level, the same plan (SQLite flattens it), one statement.\n * A conjunction of many members nests as a balanced tree where it does not,\n * as the engine already nests a disjunction: SQLite parses `a AND b AND …`\n * one level per member. A level's row domain, where the filter goes on\n * below it, is isolated the same way (`subqueries.isolated`), so a policy\n * costs its height once and not at every level (measured on D1: a\n * three-arm read policy 10 per level, failing at 9 levels; isolated, 5 per\n * level, 94 at the 15 levels admission takes).\n * Defaults to `true`.\n */\n readonly deepExpressions?: boolean;\n /**\n * Whether a statement states each relation filter body it repeats once\n * (`capabilities.sharesRelationBodies`), for a\n * transport that bounds statement text (Cloudflare D1: 100 KB). Defaults\n * to `false`.\n */\n readonly sharedRelationBodies?: boolean;\n /**\n * The most terms one compound `SELECT` may chain\n * (`capabilities.compoundSelectTerms`): Cloudflare D1 compiles SQLite with\n * 5 and refuses a sixth (\"too many terms in compound SELECT\"). Defaults to\n * SQLite's own bound, which the engine never reaches.\n */\n readonly compoundSelectTerms?: number;\n /**\n * Where bodies are shared, the relations a statement may reference before\n * its repeated walks become reaching sets and its rows join the key sets\n * they test (`capabilities.relationsPerStatement`). Absent: unbounded.\n */\n readonly relationsPerStatement?: number;\n /**\n * Whether the transport's affected-row count also counts the rows a foreign\n * key's cascade changed (`capabilities.countsCascadedChanges`): Cloudflare\n * D1's `meta.changes` does. Defaults to `false`, SQLite's own count.\n */\n readonly countsCascadedChanges?: boolean;\n}\n\n/**\n * The dialect's stateless SQL builders, built once per module. Each adapter\n * takes its own shallow copy of every group, so a driver that overrides one\n * hook (`driver.adapter.result.parseField = …`) changes only its own adapter,\n * as before, while a driver per request no longer rebuilds every closure.\n */\nconst SQLITE_LITERALS = {\n ...createStandardLiterals(),\n\n value: (value: unknown): Sql => {\n if (\n typeof value === \"bigint\" &&\n sqliteIntegerPrecision(String(value)) === undefined\n )\n throw new UnsupportedOperationError(\n \"SQLite bigint values must fit signed 64-bit integers.\"\n );\n return sql`${value}`;\n },\n\n // SQLite uses 1/0 for booleans\n true: (): Sql => sql.raw(\"1\"),\n\n false: (): Sql => sql.raw(\"0\"),\n\n // SQLite requires JSON values to be stringified\n json: (v: unknown): Sql => sql`${JSON.stringify(v)}`,\n\n // SQLite has no temporal type, so the field's declaration is what the column\n // physically holds and the operand has to be the same kind of value: an ISO\n // string bound against an epoch-millisecond INTEGER matches no row and,\n // written, stores text the typed read then refuses. A TEXT-declared or\n // undeclared field keeps the ISO spelling byte for byte. The string is a\n // validated ISO timestamp — the ISO boundary owns that — and every\n // four-digit public instant round-trips through the Julian-day double.\n dateTime: (iso: string, nativeType?: NativeTypeDeclaration): Sql =>\n sql`${encodePhysicalDateTime(iso, sqliteDateTimePhysicalForm(nativeType))}`,\n\n // SQLite has no exact decimal type, so a decimal column stores the UNSCALED\n // INTEGER COEFFICIENT and an operand becomes that same coefficient. Integer\n // comparison is then exact numeric comparison, and ordering, aggregation\n // and arithmetic are exact for the same reason.\n //\n // The digits bind as TEXT and `CAST(... AS INTEGER)` reads them, rather than\n // riding a JavaScript number (which rounds above 2^53) or a bigint (which\n // D1 will not bind). SQLite's TEXT-to-INTEGER cast is a decimal integer\n // parse, not a float one.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n new Sql(COEFFICIENT, [\n encodePhysicalDecimal(canonical, descriptor, \"coefficient\"),\n ]),\n\n // Every compact domain is a `BLOB` here and takes the payload's bytes as\n // the ordinary binary parameter a blob scalar already binds; a text-stored\n // domain takes the public string unchanged.\n id: (physical: string | Uint8Array, _representation: IdRepresentation): Sql =>\n sql`${physical}`,\n\n list: sqliteList,\n};\n\nconst SQLITE_OPERATORS = {\n ...createComparisonOperators(),\n\n containsText: (column: Sql, value: Sql): Sql =>\n sql`instr(${column}, ${value}) > 0`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`substr(${column}, 1, length(${value})) COLLATE BINARY = ${value}`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`substr(${column}, length(${column}) - length(${value}) + 1) COLLATE BINARY = ${value}`,\n // SQLite's own `lower` folds ASCII only, unless the ICU extension replaced it.\n insensitiveText(kind: TextMatch, column: Sql, value: Sql): Sql {\n return this[`${kind}Text`](sql`lower(${column})`, sql`lower(${value})`);\n },\n // GLOB, not LIKE — and this is the one place the \"portable escaped LIKE\"\n // premise of Decision 7.3 does not survive contact with SQLite. Both of\n // SQLite's LIKE-optimization preconditions fail here: an ESCAPE clause\n // disqualifies the optimization outright, and with `case_sensitive_like`\n // off (the default, and connection-global, so not ours to flip) the\n // optimization additionally wants a NOCASE-collated index, while `push()`\n // only ever creates BINARY ones. Measured on better-sqlite3, 20k rows,\n // plain index: `col LIKE ? ESCAPE '\\'` is a SCAN — exactly what the\n // `substr` spelling above already costs — AND it answers case-insensitively,\n // which would break the case-sensitivity contract this operator holds.\n //\n // GLOB has neither problem. It compares bytes, so it is case- and\n // accent-sensitive by construction (that is what `COLLATE BINARY` buys\n // above, so nothing is lost by dropping it), and it ranges on the ordinary\n // BINARY index: the same probe plans this as a covering index SEARCH over\n // 111 rows against a 20000-row SCAN. Its wildcards are `*`/`?`/`[`, and it\n // has no ESCAPE clause, so `escapeGlobLiteral` quotes them as classes.\n startsWithPrefix: (column: Sql, value: string): Sql =>\n sql`${column} GLOB ${`${escapeGlobLiteral(value)}*`}`,\n\n // `COLLATE BINARY` names a COLLATION, not a function of the column, and\n // SQLite's ordinary index is a BINARY index — so the case-sensitive\n // spelling is already the index-usable one and there is nothing to add.\n // Byte-identical to what shipped before §10.2.\n exactTextEq: (column: Sql, value: Sql): Sql =>\n sql`${column} COLLATE BINARY = ${value}`,\n exactTextIn: (column: Sql, values: Sql): Sql =>\n sql`${column} COLLATE BINARY IN ${values}`,\n\n ...createMembershipOperators(),\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n // Logical (vacuous cases use SQLite's 1/0 booleans)\n ...createLogicalOperators(SQLITE_LITERALS.true, SQLITE_LITERALS.false),\n\n ...createExistenceOperators(),\n};\n\nconst SQLITE_EXPRESSIONS = {\n ...createCommonExpressions(),\n\n // SQLite lower() intentionally provides the portable ASCII-only contract.\n caseFold: (expr: Sql): Sql => sql`lower(${expr})`,\n caseSensitiveText: (expr: Sql): Sql => sql`${expr} COLLATE BINARY`,\n\n concat: pipeConcat,\n\n // SQLite has no GREATEST/LEAST; multi-arg MAX/MIN are the scalar forms\n greatest: (...exprs: Sql[]): Sql => sql`MAX(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`MIN(${sql.join(exprs, \", \")})`,\n\n // The expression form of `set.divide`'s integer arm, and for the same\n // reason: SQLite drivers bind JS numbers as REAL, so `x / ?` would run real\n // division. Casting the divisor to INTEGER makes it native INT/INT\n // division, truncating toward zero.\n integerDivide: (left: Sql, right: Sql): Sql =>\n sql`(${left} / CAST(${right} AS INTEGER))`,\n\n // A deferred SQLite decimal is already a captured coefficient. The\n // descriptor still travels through the common contract so no caller can\n // select this physical cast without naming the destination domain.\n decimalCast: (expr: Sql, _descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${expr} AS INTEGER)`,\n\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`unhex(${expr})`\n : sql`CAST(${expr} AS TEXT)`,\n\n // SQLite type mappings\n cast: createCastExpression({\n text: \"TEXT\",\n integer: \"INTEGER\",\n bigint: \"INTEGER\",\n boolean: \"INTEGER\",\n numeric: \"NUMERIC\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`lower(hex(${expr}))`,\n};\n\nconst SQLITE_AGGREGATES = {\n ...createAggregateFunctions(\"9e999\"),\n\n // The average of a coefficient column IS the half-even integer quotient of\n // its exact sum by its non-null count: dividing both the sum and the count\n // of `logical x 10^s` values leaves `average x 10^s`, so no scale factor\n // appears at all. `COUNT(column)` is zero exactly when `SUM` is NULL, so\n // the null-strict operators answer NULL for an empty or all-null group and\n // the zero divisor is never reached with a value.\n decimalAvg: (column: Sql, _descriptor: DecimalDescriptor): Sql =>\n halfEvenQuotient(\n SQLITE_INTEGERS,\n sql`SUM(${column})`,\n sql`COUNT(${column})`\n ),\n\n // A SQLite decimal aggregate is an int64 `SUM` over coefficients. Exact\n // operand admission follows the signed range rather than digit count: some\n // 19-digit values fit, while the next value past either endpoint would make\n // `CAST(... AS INTEGER)` saturate. The sum itself is `integerSum`'s, exact\n // past that range.\n decimalSumOperandPrecision: sqliteIntegerPrecision,\n\n // `>>` is arithmetic, so an int64 member is exactly `(x >> 32) * 2^32` plus\n // its second part. That part stays REAL for a non-integer member, which the\n // reader refuses as it refused the plain `SUM`.\n // `low` sums non-negative 32-bit remainders: carrying its high bits into\n // `high` leaves a pair that sorts exactly as the total. `value` is that\n // total inside int64 and its nearest double outside, below -2^63 at most\n // `-2^63 - 2048`: SQLite compares an integer with a double exactly, so it\n // is exact against every int64 operand (a decimal coefficient's whole\n // domain), and a number operand past int64 is told apart from every total\n // but those that round to it.\n integerSum: (column: Sql) => {\n const high = sql`SUM(${column} >> 32)`;\n const low = sql`SUM(${column} - ((${column} >> 32) << 32))`;\n const carried = sql`(${high} + (${low} >> 32))`;\n const rest = sql`(${low} & 4294967295)`;\n const double = sql`${carried} * 4294967296.0 + ${rest}`;\n return {\n parts: [high, low] as const,\n value: sql`CASE WHEN ${carried} > 2147483647 THEN ${double} WHEN ${carried} >= -2147483648 THEN ${carried} * 4294967296 + ${rest} ELSE MIN(${double}, -9223372036854777856.0) END`,\n order: [carried, rest],\n };\n },\n};\n\n// Compare every node, including empty containers. Array indices remain part\n// of the path; object property insertion order does not. JSON numbers share\n// one domain, while booleans, strings and JSON null retain their distinct type.\nfunction sqliteJsonEquals(left: Sql, right: Sql): Sql {\n const nodes = (value: Sql) =>\n sql`SELECT fullkey, CASE WHEN type IN ('integer', 'real') THEN 'number' ELSE type END, atom FROM json_tree(${value})`;\n return sql`(CASE WHEN ${left} IS NULL OR ${right} IS NULL THEN NULL ELSE NOT EXISTS (${nodes(left)} EXCEPT ${nodes(right)}) AND NOT EXISTS (${nodes(right)} EXCEPT ${nodes(left)}) END)`;\n}\n\nconst sqliteJsonObject = (pairs: [string, Sql][]): Sql => {\n if (pairs.length === 0) return sql.raw(\"json_object()\");\n const args = pairs.flatMap(([key, value]) => [sql`${key}`, value]);\n return sql`json_object(${sql.join(args, \", \")})`;\n};\n\nconst sqliteJsonArray = (items: Sql[]): Sql =>\n items.length === 0\n ? sql.raw(\"json_array()\")\n : sql`json_array(${sql.join(items, \", \")})`;\n\nconst SQLITE_JSON = {\n equals: sqliteJsonEquals,\n number: (expression: Sql): Sql =>\n sql`CASE WHEN ${expression} IS NULL THEN NULL ELSE printf(${sql.raw(`'${SQLITE_BINARY64_FORMAT}'`)}, ${expression}) END`,\n boolean: (condition: Sql): Sql =>\n sql`json(CASE WHEN ${condition} THEN 'true' ELSE 'false' END)`,\n // SQLite drops the JSON subtype across scalar-subquery boundaries. Restore it\n // before embedding the value in json_object/json_array, or an object becomes a\n // quoted JSON string inside the outer document.\n document: (expression: Sql): Sql => sql`json(${expression})`,\n\n object: sqliteJsonObject,\n\n array: sqliteJsonArray,\n\n emptyArray: (): Sql => sql.raw(\"json_array()\"),\n\n // `expr` carries the JSON subtype (a json_object call, or a subquery\n // column restored through `document`), so it is aggregated as JSON, not\n // quoted as a string. Over no rows json_group_array is `[]`, never NULL.\n agg: (expr: Sql): Sql => sql`json_group_array(${expr})`,\n\n objectFromColumns: sqliteJsonObject,\n\n // `->` returns the value as canonical JSON text ('\"str\"', '2', 'null'),\n // the same format json.value binds, so extracted values compare with\n // plain equality (json_extract would return native SQL values instead)\n extract: jsonExtract,\n\n // `->>` returns text with strings unquoted, for LIKE matching\n extractText: jsonExtractText,\n\n // json_type reads the chained `->` result (canonical JSON text), so it\n // sees 'integer'/'real' only for real JSON numbers; every other shape —\n // and an absent path, where `->` is NULL — falls through to NULL\n numberAtPath: (column: Sql, path: string[]): Sql =>\n sql`(CASE WHEN json_type(${jsonExtract(column, path)}) IN ('integer', 'real') THEN CAST(${jsonExtractText(column, path)} AS REAL) END)`,\n\n // COLLATE BINARY is SQLite's default for these columns; naming it keeps\n // the code-point ordering contract explicit alongside PG's COLLATE \"C\"\n stringAtPath: (column: Sql, path: string[]): Sql =>\n sql`((CASE WHEN json_type(${jsonExtract(column, path)}) = 'text' THEN ${jsonExtractText(column, path)} END) COLLATE BINARY)`,\n // `lower` folds the same way under any collation, so the pin can stay.\n foldableStringAtPath(column: Sql, path: string[]): Sql {\n return this.stringAtPath(column, path);\n },\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`(json_type(${target}) = 'array' AND NOT EXISTS (SELECT 1 FROM json_each(${value}) AS required WHERE NOT EXISTS (SELECT 1 FROM json_each(${target}) AS candidate WHERE ${sqliteJsonEquals(sql`${target} -> candidate.fullkey`, sql`${value} -> required.fullkey`)})))`,\n\n lastElement: (target: Sql): Sql => sql`${target} -> '$[#-1]'`,\n\n value: (v: unknown): Sql => sql`${stringifyJson(v)}`,\n};\n\nconst SQLITE_ARRAYS = {\n // SQLite uses JSON arrays\n literal: sqliteJsonArray,\n\n value: sqliteJsonListValue,\n\n // Deliberately the same container, by identity: SQLite stores an enum LIST\n // as JSON like every other list, so its members are ordinary JSON strings\n // and there is no element type to spell. The `TEXT CHECK(col IN ...)`\n // describes one member.\n enumValue: sqliteJsonListValue,\n\n // Check if value exists in JSON array using json_each\n has: (column: Sql, value: Sql): Sql =>\n sql`EXISTS (SELECT 1 FROM json_each(${column}) WHERE value = ${value})`,\n\n hasEvery: (column: Sql, values: Sql): Sql =>\n sql`(SELECT COUNT(*) FROM json_each(${values}) WHERE value IN (SELECT value FROM json_each(${column}))) = json_array_length(${values})`,\n\n hasSome: (column: Sql, values: Sql): Sql =>\n sql`EXISTS (SELECT 1 FROM json_each(${column}) AS a, json_each(${values}) AS b WHERE a.value = b.value)`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(json_array_length(${column}) = 0 OR ${column} IS NULL)`,\n\n // The column already stores the container as TEXT (its declared type is\n // TEXT, not JSON, precisely so the descriptor's CHECK can hold it). The\n // cast is what stops a JSON carrier from embedding it as a document and a\n // driver from handing back anything but the stored bytes.\n exactNumericProjection: (column: Sql): Sql => sql`CAST(${column} AS TEXT)`,\n\n length: (column: Sql): Sql => sql`json_array_length(${column})`,\n\n get: (column: Sql, index: Sql): Sql =>\n sql`json_extract(${column}, '$[' || ${index} || ']')`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`json_insert(${column}, '$[#]', ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`json_set(${column}, '$[' || ${index} || ']', ${value})`,\n};\n\nconst SQLITE_ORDER_BY = {\n ...createDirectionOrderBy(),\n ...createNativeNullsOrderBy(),\n};\n\nconst SQLITE_SET = {\n ...createNumericSetOperations(),\n\n // `x * y / 10^s` in coefficient space, rounded half to even. The guard is\n // the multiply's own: `x * y` is the only intermediate here that can leave\n // int64, and it does so exactly when the result cannot fit the field.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n const descriptor = target?.decimal;\n if (!descriptor) return sql`${column} = ${column} * ${by}`;\n return guardedCoefficientAssignment(\n column,\n sql`${by} = 0 OR ABS(${column}) <= ${SQLITE_INTERMEDIATE_LIMIT} / ABS(${by})`,\n halfEvenQuotient(\n SQLITE_INTEGERS,\n sql`(${column} * ${by})`,\n scaleFactorSql(descriptor.scale)\n ),\n descriptor\n );\n },\n\n // `x * 10^s / y` in coefficient space, rounded half to even; the divisor's\n // sign moves onto the numerator so the rule always sees a positive divisor.\n // `y` is never zero — division by canonical zero is refused before I/O.\n //\n // SQLite drivers bind JS numbers as REAL, so `col / ?` runs real division\n // and would persist a fractional value into an INTEGER column. Casting the\n // divisor to INTEGER makes it native INT/INT division (truncating toward\n // zero, matching Postgres) for integer columns; real columns keep real\n // division since the column itself carries REAL affinity.\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n const descriptor = target?.decimal;\n if (descriptor) {\n const factor = scaleFactorSql(descriptor.scale);\n return guardedCoefficientAssignment(\n column,\n sql`ABS(${column}) <= ${SQLITE_INTERMEDIATE_LIMIT} / ${factor}`,\n halfEvenQuotient(\n SQLITE_INTEGERS,\n signedNumerator(sql`(${column} * ${factor})`, by),\n sql`ABS(${by})`\n ),\n descriptor\n );\n }\n return target?.integer\n ? sql`${column} = ${column} / CAST(${by} AS INTEGER)`\n : sql`${column} = ${column} / ${by}`;\n },\n\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = ${jsonArrayConcat(\n sql`json(COALESCE(${column}, '[]'))`,\n values\n )}`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = ${jsonArrayConcat(\n values,\n sql`json(COALESCE(${column}, '[]'))`\n )}`,\n};\n\nconst SQLITE_MUTATIONS = {\n skipDuplicatesStrategy: \"sql\" as const,\n insert: createInsertStatement(quoteIdent),\n insertAbsent: createInsertAbsent(quoteIdent),\n insertDefault: (table: Sql): Sql => sql`INSERT INTO ${table} DEFAULT VALUES`,\n\n ...createMutationCommands(),\n\n // SQLite 3.35+ supports RETURNING\n returning: (columns: Sql): Sql => sql`RETURNING ${columns}`,\n\n // SQLite uses same ON CONFLICT syntax as PostgreSQL (3.24+/3.35+)\n ...createOnConflictBuilders(),\n};\n\nconst sqliteAssert =\n (not: string) =>\n (query: Sql): Sql =>\n sql`SELECT CASE WHEN ${sql.raw(not)}EXISTS (${query}) THEN 1 ELSE json_extract('x', '$') END AS \"__viborm_assert__\"`;\n\nconst SQLITE_ASSERTIONS = {\n exists: sqliteAssert(\"\"),\n notExists: sqliteAssert(\"NOT \"),\n};\n\nconst noSqliteJoin =\n (feature: string) =>\n (..._args: unknown[]): never => {\n throw new Error(`SQLite does not support ${feature}.`);\n };\n\nconst SQLITE_JOINS = {\n ...createCoreJoins(),\n right: noSqliteJoin(\"RIGHT JOIN\"),\n full: noSqliteJoin(\"FULL OUTER JOIN\"),\n lateral: noSqliteJoin(\"LATERAL joins\"),\n lateralLeft: noSqliteJoin(\"LATERAL joins\"),\n};\n\nconst SQLITE_CAPABILITIES = {\n carriesDocumentsAsArrays: true,\n supportsReturning: true, // SQLite 3.35+\n // FALSE IN FACT, and it read `true` until the Phase 8 fold gave the flag its\n // first reader (query-performance-plan Phase 10.1). SQLite's `WITH` grammar\n // admits a SELECT and nothing else: measured on SQLite 3.51.2, each of\n // `WITH x AS (UPDATE …/INSERT …/DELETE … RETURNING …) SELECT * FROM x` is a\n // parse error (`near \"UPDATE\": syntax error`). Kept as a capability rather\n // than deleted because Phase 8's `WITH u AS (UPDATE … RETURNING *) SELECT …`\n // fold reads it to decide whether it may emit at all.\n supportsCteWithMutations: false,\n supportsFullOuterJoin: false,\n supportsLateralJoins: false, // SQLite does not support LATERAL joins\n supportsVector: false,\n supportsUpsertWhere: true, // SQLite supports WHERE in ON CONFLICT (3.24+)\n supportsTargetedUpsert: true, // ON CONFLICT (cols) arbitrates on those cols\n supportsMutationTargetInSubquery: true,\n // UPDATE/DELETE ... LIMIT needs SQLITE_ENABLE_UPDATE_DELETE_LIMIT, which is\n // off in the builds this project targets (better-sqlite3, libSQL, D1).\n supportsMutationRowLimit: false,\n supportsRowLocks: false,\n joinsJunctionFilters: true,\n};\n\nconst SQLITE_RESULT: AdapterResultParser = {\n // SQLite has no exact decimal type: a decimal column IS its unscaled\n // integer coefficient, and every projection casts it to text before a\n // driver turns an int64 into a double. The result boundary cannot tell the\n // two vocabularies apart by inspection, so the promise is declared here.\n decimalRepresentation: \"coefficient\",\n\n // A decimal LIST is TEXT holding a JSON array of those same coefficients,\n // stated separately because the two facts are separate: a dialect can spell\n // its scalar decimals exactly and still have no exact decimal inside JSON.\n decimalListRepresentation: \"coefficient\",\n\n // The same reading the `dateTime` literal above lowers through, so a column\n // is read back in the vocabulary it was written in.\n dateTimeRepresentation: sqliteDateTimePhysicalForm,\n\n // Derived from the ONE storage owner, so the column the migration creates\n // and the value this reads back cannot be two decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"sqlite\")?.representation ?? \"text\",\n\n parseResult: passThroughParseResult,\n parseRelation: passThroughParseRelation,\n parseField: passThroughParseField,\n};\n\nconst SQLITE_IDENTIFIERS = createIdentifiers(quoteIdent);\n// The main database's tables: a caller's CTE cannot stand for one of them.\nconst SQLITE_PINNED_TABLE = createIdentifiers(quoteIdent, \"main\").table;\n\nconst SQLITE_CLAUSES = createStandardClauses();\n\nconst SQLITE_FILTERS = createRelationFilters();\n\n// Every table but a WITHOUT ROWID one keeps an implicit rowid.\nconst SQLITE_SUBQUERIES = createSubqueries(quoteIdent, true);\n\n// A member is written once and inlined at every use: one a nested body reads\n// is compiled again inside each use of that body, so it is materialized.\nconst SQLITE_CTE = createCteBuilders(quoteIdent, {\n materializing: sql.raw(\"MATERIALIZED\"),\n});\n\nconst SQLITE_SET_OPERATIONS = createSetOperations();\n\nconst SQLITE_RAW = createRawSql();\n\n/**\n * `and` nesting its members as a balanced tree, about log2(n) levels for n\n * members, where `and` itself nests one level per member.\n */\nfunction balancedConjunction(\n and: (...conditions: Sql[]) => Sql\n): (...conditions: Sql[]) => Sql {\n const balanced = (...conditions: Sql[]): Sql => {\n if (conditions.length <= 2) return and(...conditions);\n const middle = Math.floor(conditions.length / 2);\n return and(\n balanced(...conditions.slice(0, middle)),\n balanced(...conditions.slice(middle))\n );\n };\n return balanced;\n}\n\nexport class SQLiteAdapter implements DatabaseAdapter {\n constructor({\n temporaryObjects = true,\n deepExpressions = true,\n sharedRelationBodies = false,\n compoundSelectTerms,\n relationsPerStatement,\n countsCascadedChanges,\n }: SQLiteAdapterOptions = {}) {\n installGeoPointSql(this, this.geoPoint);\n if (!deepExpressions) {\n this.subqueries.existsCheck = (from, where) =>\n sql`SELECT 1 FROM (${SQLITE_SUBQUERIES.existsCheck(from, where)})`;\n // A derived table's `WHERE` is resolved on its own branch: a level's\n // row domain costs its height there, once, not at every level below.\n this.subqueries.isolated = (condition) =>\n sql`EXISTS (SELECT 1 FROM (SELECT 1 WHERE ${condition}))`;\n this.operators.and = balancedConjunction(SQLITE_OPERATORS.and);\n this.capabilities.boundsExpressionDepth = true;\n }\n if (sharedRelationBodies) this.capabilities.sharesRelationBodies = true;\n if (compoundSelectTerms !== undefined)\n this.capabilities.compoundSelectTerms = compoundSelectTerms;\n if (relationsPerStatement !== undefined)\n this.capabilities.relationsPerStatement = relationsPerStatement;\n if (countsCascadedChanges) this.capabilities.countsCascadedChanges = true;\n // Only batches read the reference-table SQL, so it is built on first use.\n let batchRefs: BatchReferenceSqlAdapter | undefined;\n const createBatchRefs = () => this.#createBatchRefs(temporaryObjects);\n installAdapterInternals(this, {\n get batchRefs() {\n batchRefs ??= createBatchRefs();\n return batchRefs;\n },\n constraints: sqliteConstraintIdentities,\n pinnedTable: SQLITE_PINNED_TABLE,\n select: this.#assemble.select,\n });\n }\n\n raw = SQLITE_RAW;\n\n identifiers = { ...SQLITE_IDENTIFIERS };\n\n literals = { ...SQLITE_LITERALS };\n\n operators = { ...SQLITE_OPERATORS };\n\n expressions = { ...SQLITE_EXPRESSIONS };\n\n aggregates = { ...SQLITE_AGGREGATES };\n\n // SQLite 3.38+ JSON functions\n json = { ...SQLITE_JSON };\n\n arrays = { ...SQLITE_ARRAYS };\n\n // SQLite parses NULLS FIRST/LAST natively since 3.30 (2019-10-04), which is\n // below this adapter's documented 3.35+ floor. The `(col IS NULL)` emulation\n // this replaces was an extra leading sort key, and an index can never supply\n // a sort key that is an expression: on a 100,000-row table with an index over\n // the sort columns, the emulated spelling planned `SCAN t | USE TEMP B-TREE\n // FOR ORDER BY` at 3.356 ms per page and the native one plans `SCAN t USING\n // INDEX` at 0.005 ms. MySQL keeps the emulation — it has no native syntax at\n // any version.\n orderBy = { ...SQLITE_ORDER_BY };\n\n clauses = { ...SQLITE_CLAUSES };\n\n set = { ...SQLITE_SET };\n\n filters = { ...SQLITE_FILTERS };\n\n subqueries = { ...SQLITE_SUBQUERIES };\n\n // SQLite has no bare OFFSET; LIMIT -1 means \"no limit\"\n noLimitValue = sql.raw(\"-1\");\n\n readonly #assemble = {\n select: (parts: QueryParts): Sql => {\n // SQLite doesn't support DISTINCT ON natively\n // Simulate using ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)\n if (parts.distinct) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape,\n this.noLimitValue\n );\n }\n\n // SQLite uses database-level locking, so FOR UPDATE is a no-op\n // (ignoring parts.forUpdate intentionally)\n return assembleSelectQuery(parts, {\n forUpdate: \"omit\",\n noLimitValue: this.noLimitValue,\n });\n },\n };\n\n cte = { ...SQLITE_CTE };\n\n mutations = { ...SQLITE_MUTATIONS };\n\n assertions = { ...SQLITE_ASSERTIONS };\n\n joins = { ...SQLITE_JOINS };\n\n setOperations = { ...SQLITE_SET_OPERATIONS };\n\n capabilities: DatabaseAdapter[\"capabilities\"] = { ...SQLITE_CAPABILITIES };\n\n lastInsertId = (): Sql => sql.raw(\"last_insert_rowid()\");\n\n // The scratch is a TEMP table wherever the transport admits one, so it never\n // enters the user's database file. Where it does not (D1), it is an ordinary\n // table in `main`: created once, kept, and EMPTY between batches — every\n // batch deletes the rows it stored, keyed by its own batch id, inside that\n // same batch, and a batch that fails rolls its rows back with it. The table\n // itself persists; SQLite migration introspection leaves it out of the\n // snapshot (`src/migrations/drivers/sqlite/introspect.ts`).\n #createBatchRefs(temporaryObjects: boolean): BatchReferenceSqlAdapter {\n const table = sql.raw(quoteIdent(BATCH_REFS_TABLE));\n const create = sql.raw(\n temporaryObjects\n ? \"CREATE TEMP TABLE IF NOT EXISTS\"\n : \"CREATE TABLE IF NOT EXISTS\"\n );\n return createOnConflictBatchRefs({\n table,\n batchIdColumn: sql.raw('\"batch_id\"'),\n keyColumn: sql.raw('\"ref_key\"'),\n valueColumn: sql.raw('\"ref_value\"'),\n createTable: sql`${create} ${table} (\"batch_id\" TEXT NOT NULL, \"ref_key\" TEXT NOT NULL, \"ref_value\" TEXT, PRIMARY KEY (\"batch_id\", \"ref_key\"))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS TEXT)`,\n lastInsertId: () => this.lastInsertId(),\n });\n }\n\n vector = unsupportedVector;\n\n readonly geoPoint: GeoPointSql = (() => {\n const longitude = (point: Sql): Sql =>\n this.json.numberAtPath(point, [\"longitude\"]);\n const latitude = (point: Sql): Sql =>\n this.json.numberAtPath(point, [\"latitude\"]);\n return {\n value: (pointLongitude, pointLatitude) =>\n sql`json_object('longitude', ${this.json.document(this.json.number(pointLongitude))}, 'latitude', ${this.json.document(this.json.number(pointLatitude))})`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators\n ),\n };\n })();\n\n refreshAuto(table: string, body: string): Sql[] {\n const stored = this.identifiers.table(table);\n return [\n sql`DELETE FROM ${stored}`,\n sql`INSERT INTO ${stored} SELECT * FROM ${this.identifiers.table(body)}`,\n ];\n }\n\n result: AdapterResultParser = { ...SQLITE_RESULT };\n}\n"],"mappings":"q0BAgFA,MAAM,EAAa,GAAuB,IAAI,CASxC,EAA0C,CAC9C,UAAW,EAAQ,IAAgB,CAAG,IAAI,EAAE,KAAK,EAAE,GACnD,WAAY,EAAQ,IAAgB,CAAG,IAAI,EAAE,KAAK,EAAE,GACrD,CAMD,SAAS,EAAuB,EAAyC,CACvE,IAAM,EAAY,GAA4B,EAAY,CAC1D,GAAI,EAAY,GAAI,OAAO,EACvB,OAAY,IAIhB,OAHmB,EAAY,WAAW,IAAG,CACzC,EAAY,MAAM,EAAE,EAAI,sBACxB,GAAe,uBACC,EAAY,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M,EAAK,GACvE,CAGH,OAA8B,CAAE,GAAG,GAAe"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./sql-statement-tokens-Z5Ta4iDB.mjs";const t=new Set([`EXPLAIN`,`SELECT`,`VALUES`]),n=new Set([`DELETE`,`INSERT`,`REPLACE`,`UPDATE`]),r=new Set([`ALTER`,`ANALYZE`,`ATTACH`,`BEGIN`,`COMMIT`,`CREATE`,`DETACH`,`DROP`,`END`,`REINDEX`,`RELEASE`,`ROLLBACK`,`SAVEPOINT`,`VACUUM`]),i=new Set([`CASE_SENSITIVE_LIKE`,`DEFER_FOREIGN_KEYS`,`FOREIGN_KEYS`,`IGNORE_CHECK_CONSTRAINTS`,`LEGACY_ALTER_TABLE`,`RECURSIVE_TRIGGERS`,`REVERSE_UNORDERED_SELECTS`]),a=new Set([`OPTIMIZE`]),o=new Set([...t,...n]);function s(i){let a=e(i);if(!a)return`unknown`;let o=u(a),s=o?.value;return s?t.has(s)?`rows`:n.has(s)?a.slice(o.index+1).some(e=>e.kind===`word`&&e.value===`RETURNING`)?`rows`:`no-rows`:s===`PRAGMA`?d(a):r.has(s)?`no-rows`:`unknown`:`unknown`}function c(t){let r=u(e(t))?.value;return r!==void 0&&n.has(r)}function l(t){let n=u(e(t))?.value;return n===`INSERT`||n===`REPLACE`}function u(e){let t=e?.[0];if(!t||t.kind!==`word`)return;if(t.value!==`WITH`)return{index:0,value:t.value};let n=e.findIndex((e,t)=>t>0&&e.kind===`word`&&o.has(e.value)),r=e[n];return r?.kind===`word`?{index:n,value:r.value}:void 0}function d(e){let t=e.findIndex(e=>e.kind===`symbol`&&e.value===`=`),n=e.findIndex(e=>e.kind===`symbol`&&e.value===`(`),r=t>=0?t:n,o=r<0?e.length:r,s;for(let t=o-1;t>0;--t){let n=e[t];if(n&&(n.kind===`word`||n.kind===`identifier`)){s=n.value;break}}return r<0?s&&a.has(s)?`no-rows`:`rows`:s&&i.has(s)?`no-rows`:`rows`}export{l as n,c as r,s as t};
|
|
2
|
+
//# sourceMappingURL=sqlite-statement-classifier-JBHiQO6Q.mjs.map
|