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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mysql-adapter-BFWYPoM0.mjs","names":[],"sources":["../src/adapters/databases/mysql/mysql-adapter.ts"],"sourcesContent":["import { unsupportedVector } from \"@errors\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { type Sql, sql } from \"@sql\";\nimport { encodeMySqlDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { GEO_POINT_EARTH_RADIUS_METERS } from \"@validation/primitives/geo-area-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport type { ArithmeticTarget } from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport { installAdapterNamespace } from \"../../adapter-namespace\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport {\n type AdapterResultParser,\n passThroughParseRelation,\n passThroughParseResult,\n} from \"../../adapter-result-parser\";\nimport { createNamedConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n type TextMatch,\n} from \"../../database-adapter\";\nimport { createMySqlBatchRefs } from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n halfEvenQuotient,\n scaleFactorSql,\n scaleUnitSql,\n signedNumerator,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoBoundsIndexPolygons,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport { parseIntegerBoolean } from \"../../shared/result-parsing\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n buildJsonPath,\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDecimalSumOperandPrecision,\n createDirectionOrderBy,\n createEmulatedNullsOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLateralJoins,\n createLogicalOperators,\n createMembershipOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n identitySql,\n stringifyJson,\n} from \"../../shared/standard-sql\";\n\nconst quoteIdent = createIdentifierQuoter(\"`\");\nconst MYSQL_CONSTRAINTS = createNamedConstraintIdentities(() => \"PRIMARY\");\n\n/**\n * MySQL has `MOD()` but no exact integer-quotient function for decimals: `DIV`\n * converts both sides to BIGINT (so it overflows and truncates a wide\n * `DECIMAL`), and `TRUNCATE(n / d, 0)` computes `n / d` to\n * `div_precision_increment` extra digits and ROUNDS there first, which can turn\n * a value just below a half into an exact-looking tie.\n *\n * `(n - MOD(n, d)) / d` avoids both: the numerator is exactly divisible by `d`,\n * so the division's true result has no fractional digits and the extra digits\n * MySQL computes are all zero.\n */\nconst MYSQL_INTEGERS: ExactIntegerArithmetic = {\n // The CAST is not decoration. MySQL's `/` ALWAYS returns\n // `div_precision_increment` (four, by default) fractional digits, so an exact\n // integer quotient arrives typed `DECIMAL(w, 4)` — four digits of the 65-digit\n // exact domain spent on zeros, and any product taking that value as an operand\n // would carry them into ITS width. Casting back to the widest exact integer\n // domain is exact here (the value has no fraction to lose) and is what keeps\n // every downstream term integer-typed.\n quotient: (n: Sql, d: Sql): Sql =>\n sql`CAST((${n} - MOD(${n}, ${d})) / ${d} AS DECIMAL(65,0))`,\n remainder: (n: Sql, d: Sql): Sql => sql`MOD(${n}, ${d})`,\n};\n\n/**\n * MySQL's exact decimal domain, in digits — the ceiling every expression below\n * is written to stay under (plan 5.3: \"MySQL expressions avoid an intermediate\n * wider than its 65-digit exact domain\").\n */\nconst MYSQL_EXACT_DIGITS = 65;\n\nconst mysqlMaximumCoefficient = (digits: number): Sql =>\n sql.raw(\"9\".repeat(digits));\n\nconst mysqlStrictMode = sql`(FIND_IN_SET('STRICT_TRANS_TABLES', @@SESSION.sql_mode) > 0 OR FIND_IN_SET('STRICT_ALL_TABLES', @@SESSION.sql_mode) > 0)`;\n\nconst mysqlArithmeticFailure = sql`JSON_EXTRACT('x', '$')`;\n\n/** `CAST(<expr> AS DECIMAL(precision,scale))`, the width-declaring device. */\nconst decimalCast = (expr: Sql, precision: number, scale: number): Sql =>\n sql`CAST(${expr} AS ${sql.raw(`DECIMAL(${precision},${scale})`)})`;\n\n/**\n * The signed unscaled COEFFICIENT of a logical `DECIMAL(p,s)` expression, as an\n * exact integer — WITHOUT ever multiplying the whole value by `10^s`.\n *\n * `column * 10^s` is the obvious spelling and it is the unsafe one. MySQL types\n * a product as `DECIMAL(p1+p2, s1+s2)` capped at `(65, 30)`, so multiplying a\n * `DECIMAL(65,30)` column by a `DECIMAL(31,0)` factor asks for a 96-digit type,\n * gets a 65-digit one whose 30 fractional digits leave 35 for an integer that\n * needs 65 — and MySQL answers ZERO, with no warning and no error (measured on\n * 8.4: `SELECT CAST(REPEAT('9',50) AS DECIMAL(65,0)) * 0.<29 zeros>1` is\n * `0.000…0`). Splitting the value first is what keeps every factor small:\n *\n * whole = TRUNCATE(v, 0) |whole| < 10^(p-s), scale 0\n * fraction = v - whole |fraction| < 1, scale s\n * coefficient = whole * 10^s + fraction * 10^s\n *\n * Widths, by construction, for every descriptor MySQL admits (`p <= 65`,\n * `s <= 30`, `p + s <= 65`): `whole * 10^s` is typed\n * `DECIMAL(min(p+2,65), 0)` and valued\n * below `10^p`; `fraction * 10^s` is typed `DECIMAL(2s+2, s)` — at most 62\n * digits — and valued below `10^s`, so its cast to `DECIMAL(s,0)` is exact.\n * Neither product's operands sum past the exact domain, so neither can take the\n * silent arm above.\n */\nconst mysqlCoefficient = (value: Sql, descriptor: DecimalDescriptor): Sql => {\n const { scale } = descriptor;\n if (scale === 0) return value;\n const factor = scaleFactorSql(scale);\n const whole = sql`TRUNCATE(${value}, 0)`;\n const fraction = decimalCast(sql`(${value} - ${whole})`, scale + 1, scale);\n return sql`(${whole} * ${factor} + ${decimalCast(sql`(${fraction} * ${factor})`, scale, 0)})`;\n};\n\n/**\n * The logical `DECIMAL(p,s)` value of an exact integer COEFFICIENT — the\n * inverse of {@link mysqlCoefficient}, and unsafe for the same reason in the\n * same place.\n *\n * `coefficient * 10^-s` would multiply a `p`-digit integer by a\n * `DECIMAL(s+1,s)` literal: `p + s + 1` digits of type for a value that needs\n * `p`, which is the silent-zero arm again for a wide descriptor. So the\n * coefficient is split by `10^s` FIRST — an integer part that is already the\n * answer's integer part, and a remainder below `10^s` that is the only thing\n * the tiny `10^-s` literal ever multiplies:\n *\n * integer part = (coefficient - MOD(coefficient, 10^s)) / 10^s\n * fraction = MOD(coefficient, 10^s) * 10^-s\n *\n * Widths: the division is typed `DECIMAL(w, 4)` over a value below `10^(p-s)`,\n * and the fractional product's operands sum to `2s + 1` — at most 61 digits.\n */\nconst mysqlLogical = (coefficient: Sql, descriptor: DecimalDescriptor): Sql => {\n const { scale } = descriptor;\n if (scale === 0) return coefficient;\n const factor = scaleFactorSql(scale);\n const remainder = sql`MOD(${coefficient}, ${factor})`;\n return sql`((${coefficient} - ${remainder}) / ${factor} + ${decimalCast(remainder, scale, 0)} * ${scaleUnitSql(scale)})`;\n};\n\n/**\n * Assign one coefficient-space answer without letting a non-strict MySQL\n * session turn overflow into a clipped value. Strict sessions retain their\n * native error. A non-strict session reaches the answer only after the caller's\n * operation-specific precondition proves its intermediate is exact and the\n * target-domain check proves the final coefficient fits.\n *\n * The session-mode arm is deliberately first. `CASE` is the same lazy error\n * primitive used by this adapter's assertion queries, so a safe or NULL arm\n * never evaluates the invalid JSON expression that raises the provider error.\n */\nconst mysqlGuardedDecimalAssignment = (\n column: Sql,\n coefficient: Sql,\n descriptor: DecimalDescriptor,\n intermediateFits: Sql\n): Sql => {\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const logical = mysqlLogical(coefficient, descriptor);\n return sql`${column} = CASE WHEN ${mysqlStrictMode} THEN ${logical} WHEN ${column} IS NULL THEN NULL WHEN ${intermediateFits} THEN CASE WHEN ${coefficient} BETWEEN -${maximum} AND ${maximum} THEN ${logical} ELSE ${mysqlArithmeticFailure} END ELSE ${mysqlArithmeticFailure} END`;\n};\n\nconst mysqlDecimalDelta = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor,\n add: boolean\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = add\n ? sql`CASE WHEN ${operand} > 0 THEN ${current} <= ${maximum} - ${operand} WHEN ${operand} < 0 THEN ${current} >= -${maximum} - ${operand} ELSE TRUE END`\n : sql`CASE WHEN ${operand} > 0 THEN ${current} >= -${maximum} + ${operand} WHEN ${operand} < 0 THEN ${current} <= ${maximum} + ${operand} ELSE TRUE END`;\n return mysqlGuardedDecimalAssignment(\n column,\n add ? sql`(${current} + ${operand})` : sql`(${current} - ${operand})`,\n descriptor,\n fits\n );\n};\n\n/**\n * `column = halfEven(column x by)`, computed on COEFFICIENTS.\n *\n * This is plan 5.3's rule verbatim — `multiply = halfEven((x * y) / F)` — and\n * it is stated on integers because MySQL cannot state it on logical values: the\n * exact product of two `DECIMAL(p,s)` values carries `2s` fractional digits,\n * and MySQL caps an expression's scale at 30, ROUNDING anything finer away\n * before the tie this rule exists to decide is ever visible (measured: `1e-30 *\n * 1e-30` is `0.000…0` at `DECIMAL(65,30)`, no warning). Coefficients have no\n * fractional digits at all, so nothing can be rounded away underneath the rule.\n *\n * WIDTH, BY CONSTRUCTION. `|x|, |y| < 10^p`, and the answer is in the field's\n * domain exactly when `|x * y| < 10^(p+s)`, so the product needs at most\n * `p + s` digits: within the 65-digit exact domain for every descriptor with\n * `precision + scale <= 65`. The quotient is `< 10^p`, the remainder `< 10^s`,\n * and the tie test compares `|r|` against `10^s - |r|` — the non-doubling form,\n * so nothing widens there either.\n *\n * Outside that bound the operation is loud on every session. A strict session\n * reaches MySQL's native overflow error. A non-strict session first proves the\n * product can be formed inside 65 digits and that the rounded coefficient fits\n * the field; a failed proof evaluates the adapter's lazy error expression\n * instead of letting MySQL clip the assignment. Both leave the row unchanged.\n */\nconst mysqlDecimalMultiply = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const left = mysqlCoefficient(column, descriptor);\n const right = mysqlCoefficient(by, descriptor);\n const maximumIntermediate = mysqlMaximumCoefficient(MYSQL_EXACT_DIGITS);\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n sql`(${left} * ${right})`,\n scaleFactorSql(descriptor.scale)\n );\n const intermediateFits = sql`CASE WHEN ${right} = 0 THEN TRUE ELSE ABS(${left}) <= ${MYSQL_INTEGERS.quotient(maximumIntermediate, sql`ABS(${right})`)} END`;\n return mysqlGuardedDecimalAssignment(\n column,\n coefficient,\n descriptor,\n intermediateFits\n );\n};\n\n/**\n * `column = halfEven(column / by)`, computed on COEFFICIENTS — plan 5.3's\n * `divide = halfEven((x * F) / y)`.\n *\n * The divisor is the operand's COEFFICIENT rather than its logical value: an\n * exact quotient is spelled `(n - MOD(n, d)) / d`, and with a fractional `d`\n * the numerator `n - MOD(n, d)` is `q * d` — a `p`-digit magnitude carrying `s`\n * fractional digits, `p + s` digits for a value the integer form states in `p`.\n * Integers on both sides keep every term at its own width.\n *\n * WIDTH, BY CONSTRUCTION: `|x * F| < 10^(p+s)` — inside the exact domain for\n * every descriptor with `precision + scale <= 65`, and unconditionally, not\n * only when the answer fits. The quotient is the answer's coefficient\n * (`< 10^p` when it fits the field), the remainder is below `|y| < 10^p`, and\n * the tie compares `|r|` against `|y| - |r|`, which is why the doubled form was\n * dropped: `2|r|` at `p = 65` needs 66.\n *\n * `by` is never zero — division by canonical zero is refused before I/O.\n */\nconst mysqlDecimalDivide = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const divisor = mysqlCoefficient(by, descriptor);\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n signedNumerator(\n sql`(${mysqlCoefficient(column, descriptor)} * ${scaleFactorSql(descriptor.scale)})`,\n divisor\n ),\n sql`ABS(${divisor})`\n );\n return mysqlGuardedDecimalAssignment(\n column,\n coefficient,\n descriptor,\n sql.raw`TRUE`\n );\n};\n\n/**\n * The exact decimal average, on coefficients: `SUM` of the column's\n * coefficients over `COUNT(column)`, quantized half to even.\n *\n * Summing the COEFFICIENTS rather than scaling the sum is what removes the last\n * `x 10^s` from this expression: `SUM(column) * 10^s` multiplies a value MySQL\n * already types up to 65 digits by a 31-digit factor, which is the silent-zero\n * arm {@link mysqlCoefficient} exists to avoid. Every row's coefficient is\n * below `10^p`, so the only way the sum leaves the exact domain is by genuinely\n * exceeding it, and MySQL raises there.\n *\n * `COUNT(column)` counts non-nulls, so an empty or all-null group answers NULL\n * through the null-strict operators instead of dividing by zero.\n */\nconst mysqlDecimalAverage = (\n column: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n sql`SUM(${mysqlCoefficient(column, descriptor)})`,\n sql`COUNT(${column})`\n );\n return mysqlLogical(coefficient, descriptor);\n};\n// MySQL's own case folding: `LOWER` maps every letter by the string's\n// character set (Unicode for utf8mb4). It must see the raw text — on a\n// `BINARY` string it does nothing — and its result is compared as bytes, so a\n// case- AND accent-insensitive collation (`utf8mb4_0900_ai_ci`) never decides.\nconst caseFold = (expr: Sql): Sql => sql`LOWER(${expr})`;\n\n// MySQL DATETIME rejects ISO-8601's 'Z' suffix (\"Incorrect datetime value\"),\n// so datetimes are stored as naive UTC wall-clock 'YYYY-MM-DD HH:MM:SS.mmm'.\n\n// Naive datetime string as it comes back from MySQL (top-level on string\n// drivers, or inside JSON_ARRAYAGG/JSON_OBJECT includes): no 'Z'/offset.\nconst NAIVE_DATETIME_REGEX =\n /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2})(\\.\\d+)?$/;\n\n/** Reattach UTC to a naive MySQL datetime string so it parses as the stored instant. */\nconst naiveDateTimeToIso = (value: string): string | undefined => {\n const match = NAIVE_DATETIME_REGEX.exec(value);\n if (!match) return undefined;\n const fraction = match[3] ? match[3].padEnd(4, \"0\").slice(0, 4) : \".000\";\n return `${match[1]}T${match[2]}${fraction}Z`;\n};\n\n/** Replace a single-integer-parameter fragment with an inline literal. */\nconst inlineIntegerLiteral = (fragment: Sql): Sql => {\n const value = fragment.values.length === 1 ? fragment.values[0] : undefined;\n return typeof value === \"number\" && Number.isInteger(value)\n ? sql.raw(String(value))\n : fragment;\n};\n\nconst mysqlJsonArray = (items: Sql[]): Sql =>\n items.length === 0\n ? sql.raw`JSON_ARRAY()`\n : sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n\nconst mysqlJsonExtract = (column: Sql, path: string[]): Sql =>\n sql`JSON_EXTRACT(${column}, ${buildJsonPath(path)})`;\n\nconst mysqlJsonObject = (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\n/** The one JSON list container every MySQL list value crosses as. */\nconst mysqlJsonListValue = (values: unknown[]): Sql =>\n sql`CAST(${stringifyJson(values)} AS JSON)`;\n\nconst mysqlAssert =\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\nexport class MySQLAdapter implements DatabaseAdapter {\n /**\n * The bound database, or `undefined` for the unqualified mode a\n * provider-configured MySQL2 client and every PlanetScale client keep. Under\n * Vitess the value is the keyspace qualifier submitted before routing rules\n * apply, not a proof of the routed backend.\n */\n declare readonly namespace: string | undefined;\n\n constructor(namespace?: string) {\n installAdapterNamespace(this, namespace, \"mysql\");\n // Reads the installed value, so it cannot be a field initializer: those run\n // before the constructor body.\n this.identifiers = createIdentifiers(\n quoteIdent,\n this.namespace,\n this.capabilities.namesQualifiedColumns\n );\n installGeoPointSql(this, this.geoPoint);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: MYSQL_CONSTRAINTS,\n // Qualified by the bound database; an unbound adapter cannot pin.\n ...(this.namespace !== undefined && {\n pinnedTable: this.identifiers.table,\n }),\n select: this.#assemble.select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // MySQL requires JSON values to be stringified\n json: (v: unknown): Sql => sql`${JSON.stringify(v)}`,\n\n dateTime: (\n iso: string,\n _nativeType?: NativeTypeDeclaration,\n member?: boolean\n ): Sql =>\n sql`${member || iso.length === 10 ? iso : encodeMySqlDateTime(iso)}`,\n\n // The cast is load-bearing, not decoration. MySQL's comparison rules say\n // that when one side is a number and the other a string, BOTH are converted\n // to double and compared as floating point — so `amount = '0.1'` against a\n // `DECIMAL` column would silently answer at float precision on an otherwise\n // exact column. Casting the operand into the SAME `DECIMAL(p,s)` the DDL\n // emits keeps the whole comparison in MySQL's exact decimal domain, and\n // names one domain for the operand and the column instead of two.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${encodePhysicalDecimal(canonical, descriptor, \"text\")} AS ${sql.raw(decimalColumnType(\"mysql\", descriptor))})`,\n\n // MySQL has no `uuid` type: every compact domain is a `BINARY(n)` column\n // and takes the payload's bytes as an ordinary binary parameter, which is\n // the same parameter a blob scalar already binds. A text-stored domain\n // takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n _representation: IdRepresentation\n ): Sql => sql`${physical}`,\n };\n\n operators = {\n ...createComparisonOperators(),\n\n containsText: (column: Sql, value: Sql): Sql =>\n sql`LOCATE(BINARY ${value}, BINARY ${column}) > 0`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value}`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`RIGHT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value}`,\n insensitiveText: (kind: TextMatch, column: Sql, value: Sql): Sql =>\n this.operators[`${kind}Text`](caseFold(column), caseFold(value)),\n // Two conjuncts, because on MySQL no single predicate is both exact and\n // index-usable. The index stores the column's own collation's sort keys —\n // `utf8mb4_0900_ai_ci` on a default install, which is case- AND\n // accent-insensitive — so any comparison forced to BINARY cannot range on\n // it. Measured on MySQL 8 (Docker, 20k rows): `col LIKE 'x%'` is a `range`\n // over 111 rows, while both `col LIKE BINARY 'x%'` and the\n // `LEFT(BINARY col, …)` spelling above degrade to a full `index` scan of\n // all 19731 entries.\n //\n // So the collation-native LIKE goes first as an index accelerator, and the\n // BINARY predicate — byte-identical to `startsWithText` above — follows as\n // the semantics. The accelerator can never drop a row the BINARY conjunct\n // would keep: byte-equal strings compare equal under every collation, so a\n // binary prefix match implies the collation-native one. It is not a second\n // guard on the same invariant — it decides no row's membership, only which\n // rows the server has to look at.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n startsWithPrefix: (column: Sql, value: string): Sql =>\n sql`(${column} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\\\\\' AND LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value})`,\n\n // `startsWithPrefix`'s twin, for the same reason and in the same shape\n // (plan §10.2). `BINARY col` is a FUNCTION of the column, so MySQL cannot\n // range on it: measured on MySQL 8.4 over 20,000 rows in the collation\n // viborm's own DDL declares, `BINARY name = ?` planned `index` over 20,455\n // rows where `name = ?` planned `ref` over 1, and `BINARY name IN (…)`\n // planned `index` over 20,455 where `name IN (…)` planned `range` over 3.\n //\n // The collation-native conjunct is the accelerator and decides no row's\n // membership: byte-identical strings compare equal under every collation\n // of the charset, so the BINARY comparison IMPLIES it. On the tables\n // viborm creates (`utf8mb4_0900_bin`) the two conjuncts say the same\n // thing; on a table viborm did not create the BINARY one is what keeps the\n // case-sensitivity contract, and the same measurement shows the pair still\n // plans `ref` over 1 row there.\n //\n // `notIn` and `not` deliberately have no such pair. Their implication runs\n // the other way — `BINARY col NOT IN ('X')` KEEPS a row spelled `x` that\n // `col NOT IN ('X')` drops on a case-insensitive column, measured at\n // 20,000 rows against 19,999 — so a conjunct would remove rows. There is\n // also nothing to win: both spellings of `NOT IN` scan all 20,442 rows.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n exactTextEq: (column: Sql, value: Sql): Sql =>\n sql`(${column} = ${value} AND BINARY ${column} = ${value})`,\n exactTextIn: (column: Sql, values: Sql): Sql =>\n sql`(${column} IN ${values} AND BINARY ${column} IN ${values})`,\n\n ...createMembershipOperators(),\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n caseFold,\n caseSensitiveText: (expr: Sql): Sql => sql`BINARY ${expr}`,\n\n // String operations - MySQL uses CONCAT() function\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw`''`;\n if (parts.length === 1) return parts[0]!;\n return sql`CONCAT(${sql.join(parts, \", \")})`;\n },\n\n greatest: (...exprs: Sql[]): Sql => sql`GREATEST(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`LEAST(${sql.join(exprs, \", \")})`,\n\n // The expression form of `set.divide`'s integer arm: MySQL `/` yields a\n // DECIMAL quotient even for two integers, so the truncation is explicit.\n integerDivide: (left: Sql, right: Sql): Sql =>\n sql`TRUNCATE(${left} / ${right}, 0)`,\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n decimalCast(expr, descriptor.precision, descriptor.scale),\n\n // `CHAR` rather than `TEXT`: MySQL's CAST target list has no `TEXT`, which\n // is why `cast` below maps the generic text cast to `CHAR` too.\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`UNHEX(${expr})`\n : sql`CAST(${expr} AS CHAR)`,\n\n cast: createCastExpression({\n text: \"CHAR\",\n integer: \"SIGNED\",\n bigint: \"SIGNED\",\n boolean: \"UNSIGNED\",\n numeric: \"DECIMAL\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`LOWER(HEX(${expr}))`,\n };\n\n aggregates = {\n ...createAggregateFunctions(),\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n mysqlDecimalAverage(column, descriptor),\n\n // MySQL's widest exact DECIMAL cast operand. SUM itself can return more\n // than 65 digits; this bound belongs to exact HAVING operand lowering.\n decimalSumOperandPrecision:\n createDecimalSumOperandPrecision(MYSQL_EXACT_DIGITS),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql => sql`${left} = ${right}`,\n number: identitySql,\n boolean: (condition: Sql): Sql =>\n sql`JSON_EXTRACT(CASE WHEN ${condition} THEN 'true' ELSE 'false' END, '$')`,\n document: identitySql,\n\n object: mysqlJsonObject,\n\n array: mysqlJsonArray,\n\n emptyArray: (): Sql => sql.raw`JSON_ARRAY()`,\n\n agg: (expr: Sql): Sql =>\n sql`COALESCE(JSON_ARRAYAGG(${expr}), JSON_ARRAY())`,\n\n objectFromColumns: mysqlJsonObject,\n\n // buildJsonPath quotes/escapes key segments and maps integer segments\n // to array indices; '$' alone extracts the document root\n extract: mysqlJsonExtract,\n\n extractText: (column: Sql, path: string[]): Sql =>\n sql`JSON_UNQUOTE(${mysqlJsonExtract(column, path)})`,\n\n // JSON_TYPE spells numbers three ways depending on how the literal was\n // stored; anything else (including an absent path, where JSON_TYPE is\n // NULL) falls through the CASE to NULL\n numberAtPath: (column: Sql, path: string[]): Sql => {\n const ex = mysqlJsonExtract(column, path);\n return sql`(CASE WHEN JSON_TYPE(${ex}) IN ('INTEGER', 'DOUBLE', 'DECIMAL') THEN CAST(JSON_UNQUOTE(${ex}) AS DOUBLE) END)`;\n },\n\n // CAST(... AS BINARY) yields VARBINARY, so < / > compare bytes instead of\n // the column's (case- and accent-insensitive by default) collation\n stringAtPath: (column: Sql, path: string[]): Sql => {\n const ex = mysqlJsonExtract(column, path);\n return sql`(CASE WHEN JSON_TYPE(${ex}) = 'STRING' THEN CAST(JSON_UNQUOTE(${ex}) AS BINARY) END)`;\n },\n foldableStringAtPath: (column: Sql, path: string[]): Sql => {\n const ex = mysqlJsonExtract(column, path);\n return sql`(CASE WHEN JSON_TYPE(${ex}) = 'STRING' THEN JSON_UNQUOTE(${ex}) END)`;\n },\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`JSON_CONTAINS(${target}, ${value})`,\n\n lastElement: (target: Sql): Sql => sql`JSON_EXTRACT(${target}, '$[last]')`,\n\n // Comparing a JSON column to a plain string coerces the string to a JSON\n // string scalar (always-false for documents); CAST parses it as JSON\n value: (v: unknown): Sql => sql`CAST(${stringifyJson(v)} AS JSON)`,\n };\n\n arrays = {\n // MySQL uses JSON arrays\n literal: mysqlJsonArray,\n\n value: mysqlJsonListValue,\n\n // Deliberately the same container, by identity: MySQL 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 inline `ENUM(...)` describes\n // one member.\n enumValue: mysqlJsonListValue,\n\n // JSON_CONTAINS requires a JSON document as candidate; a bare string\n // parameter throws ER_INVALID_JSON_TEXT. JSON_ARRAY keeps the parameter's\n // type (strings quoted, numbers not): [x] ⊆ column ⟺ x ∈ column\n has: (column: Sql, value: Sql): Sql =>\n sql`JSON_CONTAINS(${column}, JSON_ARRAY(${value}))`,\n\n hasEvery: (column: Sql, values: Sql): Sql =>\n sql`JSON_CONTAINS(${column}, ${values})`,\n\n hasSome: (column: Sql, values: Sql): Sql =>\n sql`JSON_OVERLAPS(${column}, ${values})`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(JSON_LENGTH(${column}) = 0 OR ${column} IS NULL)`,\n\n // The container as TEXT, so it reaches the decode as the exact bytes the\n // codec wrote: uncast, mysql2 parses a JSON column into a JavaScript\n // document and JSON_OBJECT nests it as a live array, and the coefficient\n // grammar would then be read off values a JSON parser already interpreted.\n exactNumericProjection: (column: Sql): Sql => sql`CAST(${column} AS CHAR)`,\n\n length: (column: Sql): Sql => sql`JSON_LENGTH(${column})`,\n\n get: (column: Sql, index: Sql): Sql =>\n sql`JSON_EXTRACT(${column}, CONCAT('$[', ${index}, ']'))`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`JSON_ARRAY_APPEND(${column}, '$', ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`JSON_SET(${column}, CONCAT('$[', ${index}, ']'), ${value})`,\n };\n\n orderBy = {\n ...createDirectionOrderBy(),\n // MySQL doesn't support NULLS FIRST/LAST natively - emulated\n ...createEmulatedNullsOrderBy(),\n };\n\n // mysql2's binary protocol binds JS numbers as DOUBLE, which MySQL rejects\n // in integer-only positions (\"Incorrect arguments to mysqld_stmt_execute\").\n // Inline integer LIMIT/OFFSET values instead of parameterizing them.\n clauses = {\n ...createStandardClauses(),\n limit: (count: Sql): Sql => sql`LIMIT ${inlineIntegerLiteral(count)}`,\n offset: (count: Sql): Sql => sql`OFFSET ${inlineIntegerLiteral(count)}`,\n };\n\n // JSON_MERGE_PRESERVE concatenates arrays element-wise; JSON_ARRAY_APPEND\n // would append the whole param as a single (stringified) element.\n set = {\n ...createNumericSetOperations(),\n\n increment: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalDelta(column, by, target.decimal, true)\n : sql`${column} = ${column} + ${by}`,\n\n decrement: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalDelta(column, by, target.decimal, false)\n : sql`${column} = ${column} - ${by}`,\n\n // A decimal target rounds the product back to the field's scale; every\n // other numeric column keeps MySQL's native multiplication.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalMultiply(column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n\n // MySQL `/` yields DECIMAL and rounds when assigned to an integer column.\n // Truncate explicitly so integer division matches PostgreSQL and SQLite.\n // A decimal target takes neither: `/` would round at\n // `div_precision_increment` digits, so the exact half-even quotient rule\n // decides the last digit instead.\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n if (target?.decimal) {\n return mysqlDecimalDivide(column, by, target.decimal);\n }\n return target?.integer\n ? sql`${column} = TRUNCATE(${column} / ${by}, 0)`\n : sql`${column} = ${column} / ${by}`;\n },\n\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = JSON_MERGE_PRESERVE(COALESCE(${column}, JSON_ARRAY()), ${values})`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = JSON_MERGE_PRESERVE(${values}, COALESCE(${column}, JSON_ARRAY()))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n // MySQL has no bare OFFSET; per the manual, use an all-ones LIMIT sentinel\n noLimitValue = sql.raw`18446744073709551615`;\n\n readonly #assemble = {\n select: (rawParts: QueryParts): Sql => {\n // Inline integer LIMIT/OFFSET (see clauses above for why)\n const parts: QueryParts = {\n ...rawParts,\n limit: rawParts.limit && inlineIntegerLiteral(rawParts.limit),\n offset: rawParts.offset && inlineIntegerLiteral(rawParts.offset),\n };\n\n // MySQL 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 return assembleSelectQuery(parts, {\n forUpdate: \"append\",\n noLimitValue: this.noLimitValue,\n });\n },\n };\n\n // MySQL 8.0+ common table expressions\n cte = createCteBuilders(quoteIdent);\n\n mutations = {\n skipDuplicatesStrategy: \"recoverableUniqueError\" as const,\n insert: createInsertStatement(quoteIdent),\n // `ON DUPLICATE KEY UPDATE` names no key: each row is selected where no\n // row holds its key, and what a row that is there takes is written after.\n insertAbsent: (\n table: Sql,\n columns: string[],\n rows: Sql[][],\n key: readonly string[],\n sets?: Sql,\n unless?: Sql\n ): Sql[] => {\n const name = (column: string) => sql.raw(quoteIdent(column));\n return rows.flatMap((row) => [\n sql`INSERT INTO ${table} (${sql.join(columns.map(name), \", \")}) SELECT * FROM (SELECT ${sql.join(\n row.map((value, at) => sql`${value} AS ${name(columns[at]!)}`),\n \", \"\n )}) AS \\`new\\` WHERE NOT EXISTS (SELECT 1 FROM ${table} AS \\`old\\` WHERE ${sql.join(\n key.map(\n (column) => sql`\\`old\\`.${name(column)} = \\`new\\`.${name(column)}`\n ),\n \" AND \"\n )})`,\n ...(sets\n ? [\n sql`UPDATE ${table} SET ${sets} WHERE ${sql.join(\n key.map(\n (column) =>\n sql`${name(column)} = ${row[columns.indexOf(column)]!}`\n ),\n \" AND \"\n )}${unless ? sql` AND NOT (${unless})` : sql.empty}`,\n ]\n : []),\n ]);\n },\n insertDefault: (table: Sql): Sql => sql`INSERT INTO ${table} () VALUES ()`,\n\n ...createMutationCommands(),\n updateFrom: (table, sets, source, on, where) =>\n sql`UPDATE ${table} JOIN ${source} ON ${on} SET ${sets}${\n where ? sql` WHERE ${where}` : sql.empty\n }`,\n\n // MySQL doesn't support RETURNING - returns empty\n // Use LAST_INSERT_ID() or SELECT after mutation\n returning: (_columns: Sql): Sql => sql.empty,\n\n // This low-level MySQL primitive ignores `_target`: ON DUPLICATE KEY UPDATE\n // fires on any unique collision. Public non-returning upserts therefore do\n // not execute this primitive; the query engine uses a locked, target-aware\n // branch so an unrelated unique collision still throws on every database.\n onConflict: (_target: Sql | null, action: Sql, _targetWhere?: Sql): Sql => {\n return sql`ON DUPLICATE KEY UPDATE ${action}`;\n },\n\n // MySQL doesn't need UPDATE SET prefix - onConflict already includes UPDATE\n onConflictUpdate: (sets: Sql, _setWhere?: Sql): Sql => sets,\n\n // A self-assignment reacts only to duplicate-key conflicts. Unlike\n // INSERT IGNORE, unrelated constraint and conversion failures still abort.\n //\n // It stays the JUNCTION insert's clause on MySQL as well, because\n // `ON DUPLICATE KEY UPDATE` cannot name a target (`onConflict` above says\n // so) — correct for every junction whose PK is its sole unique constraint,\n // which is every ordinary pair table. A polymorphic member table with a\n // SINGULAR inverse also carries a target-side UNIQUE that this clause would\n // swallow; the seam for that case is documented at `junctionDuplicateSkip`\n // in `query-engine/builders/many-to-many-utils.ts`.\n skipDuplicates: (duplicateNoopColumn: string) => {\n const column = sql.raw(quoteIdent(duplicateNoopColumn));\n return {\n prefix: sql.empty,\n suffix: sql`ON DUPLICATE KEY UPDATE ${column} = ${column}`,\n };\n },\n };\n\n assertions = {\n exists: mysqlAssert(\"\"),\n notExists: mysqlAssert(\"NOT \"),\n };\n\n joins = {\n ...createCoreJoins(),\n\n // MySQL doesn't support FULL OUTER JOIN (would need a UNION of LEFT and\n // RIGHT joins). Never silently downgrade to LEFT JOIN: that drops rows.\n // The query engine never calls this today.\n full: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\"MySQL does not support FULL OUTER JOIN.\");\n },\n\n // MySQL 8.0.14+ supports LATERAL\n ...createLateralJoins(quoteIdent),\n };\n\n setOperations = createSetOperations();\n\n capabilities = {\n namesQualifiedColumns: true,\n carriesDocumentsAsArrays: true,\n supportsReturning: false,\n supportsCteWithMutations: false, // MySQL CTEs are read-only\n supportsFullOuterJoin: false,\n supportsLateralJoins: true, // MySQL 8.0.14+\n supportsVector: false,\n supportsUpsertWhere: false, // ON DUPLICATE KEY UPDATE doesn't support WHERE clauses\n // ON DUPLICATE KEY UPDATE carries no conflict target and fires on ANY unique\n // collision — see the `onConflict` note above. A targeted upsert cannot be\n // spelled here, so the ON CONFLICT fold never opens on MySQL.\n supportsTargetedUpsert: false,\n // ERROR 1093: UPDATE/DELETE can't select from the mutated table in a\n // subquery. The engine wraps relation-filter subqueries in a derived\n // table when this is false (requires MySQL 8.0.14+ for outer references\n // in derived tables).\n supportsMutationTargetInSubquery: false,\n // MySQL's single-table UPDATE/DELETE take a native LIMIT, which is also the\n // only portable spelling here: the PK-subquery form would re-read the\n // mutated table and trip the same ERROR 1093 as above.\n supportsMutationRowLimit: true,\n supportsRowLocks: true,\n // InnoDB answers a locking miss on a unique index with a gap lock that\n // concurrent misses share and their INSERTs wait on (`ER_LOCK_DEADLOCK`).\n locksMissingKeys: true,\n boundsRecursionIterations: true,\n };\n\n lastInsertId = (): Sql => sql.raw`LAST_INSERT_ID()`;\n\n readonly #batchRefs = createMySqlBatchRefs({\n table: sql.raw`\\`__viborm_batch_refs\\``,\n batchIdColumn: sql.raw`\\`batch_id\\``,\n keyColumn: sql.raw`\\`ref_key\\``,\n valueColumn: sql.raw`\\`ref_value\\``,\n duplicateValue: sql.raw`VALUES(\\`ref_value\\`)`,\n createTable: sql.raw`CREATE TEMPORARY TABLE IF NOT EXISTS \\`__viborm_batch_refs\\` (\\`batch_id\\` VARCHAR(191) NOT NULL, \\`ref_key\\` VARCHAR(191) NOT NULL, \\`ref_value\\` TEXT, PRIMARY KEY (\\`batch_id\\`, \\`ref_key\\`))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS CHAR)`,\n lastInsertId: () => this.lastInsertId(),\n });\n\n vector = unsupportedVector;\n\n readonly geoPoint: GeoPointSql = (() => {\n const longitude = (point: Sql): Sql => sql`ST_Longitude(${point})`;\n const latitude = (point: Sql): Sql => sql`ST_Latitude(${point})`;\n const geojson = (json: string): Sql =>\n sql`ST_GeomFromGeoJSON(${json}, 1, 4326)`;\n return {\n value: (pointLongitude, pointLatitude) =>\n sql`ST_GeomFromText(CONCAT('POINT(', ${pointLongitude}, ' ', ${pointLatitude}, ')'), 4326, 'axis-order=long-lat')`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators,\n (point, bounds) => {\n const polygons = geoBoundsIndexPolygons(bounds);\n if (polygons.length === 0) return;\n return this.operators.or(\n ...polygons.map(\n (polygon) => sql`MBRIntersects(${point}, ${geojson(polygon)})`\n )\n );\n }\n ),\n withinPolygon: (point, polygon) =>\n sql`ST_Intersects(${geojson(geoPolygonJson(polygon))}, ${point})`,\n distance: (left, right) =>\n sql`ST_Distance_Sphere(${left}, ${right}, ${GEO_POINT_EARTH_RADIUS_METERS})`,\n };\n })();\n\n // RESULT PARSING\n // MySQL: booleans and naive UTC datetimes - both ROW VALUES.\n // This adapter says nothing about a RESULT: the engine's decoder asks for\n // the alias `_count` and reads it back, and mysql2 preserves that alias\n // (Arnaud's D-40, measured live).\n // Relation carriers decode at the query-engine boundary that knows their\n // value is JSON, so the adapter never sniffs ordinary strings.\n refreshAuto(\n table: string,\n body: string,\n _source: string,\n keyColumn: string\n ): Sql[] {\n const stored = this.identifiers.table(table);\n const pk = this.identifiers.escape(keyColumn);\n return [\n sql`DELETE FROM ${stored}`,\n sql`INSERT INTO ${stored} SELECT * FROM ${this.identifiers.table(body)} ON DUPLICATE KEY UPDATE ${stored}.${pk} = ${stored}.${pk}`,\n ];\n }\n\n result: AdapterResultParser = {\n // A MySQL SCALAR decimal is `DECIMAL(p,s)` and answers with exact text, so\n // `decimalRepresentation` stays at its default. A decimal LIST is JSON,\n // which has no exact decimal at all, so its members are stored and returned\n // as unscaled coefficient strings (plan 6.1). This adapter is the reason\n // the two are separate declarations.\n decimalListRepresentation: \"coefficient\",\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, \"mysql\")?.representation ?? \"text\",\n\n // The contract's shape, deciding nothing on all 20 asks D-40 measured over\n // seven operations and both routes on live MySQL - the `count`/`exist` arm\n // was entered on 10 of them and answered `undefined` every time\n // (`g4/rulings/o2/receipts/leg-probe-mysql.log`). A RESULT is the\n // decoder's, and D-28's chain ends there.\n parseResult: passThroughParseResult,\n parseRelation: passThroughParseRelation,\n\n parseField: (\n value: unknown,\n scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n // MySQL stores booleans as TINYINT(1) - 0/1\n if (scalarType === \"boolean\") {\n const parsed = parseIntegerBoolean(\n value === \"0\" ? 0 : value === \"1\" ? 1 : value\n );\n if (parsed !== undefined) {\n return next(parsed);\n }\n }\n // Datetime strings are naive UTC wall-clock; without this, the default\n // parser's new Date(str) would shift them by the process timezone\n if (scalarType === \"datetime\" && typeof value === \"string\") {\n const iso = naiveDateTimeToIso(value);\n if (iso !== undefined) {\n return next(iso);\n }\n }\n return next();\n },\n };\n}\n"],"mappings":"63BA+EA,MAAM,EAAa,EAAuB,IAAI,CACxC,GAAoB,MAAsC,UAAU,CAapE,EAAyC,CAQ7C,UAAW,EAAQ,IACjB,CAAG,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,oBAC1C,WAAY,EAAQ,IAAgB,CAAG,OAAO,EAAE,IAAI,EAAE,GACvD,CASK,EAA2B,GAC/B,EAAI,IAAI,IAAI,OAAO,EAAO,CAAC,CAEvB,GAAkB,CAAG,2HAErB,EAAyB,CAAG,yBAG5B,GAAe,EAAW,EAAmB,IACjD,CAAG,QAAQ,EAAK,MAAM,EAAI,IAAI,WAAW,EAAU,GAAG,EAAM,GAAG,CAAC,GA0B5D,GAAoB,EAAY,IAAuC,CAC3E,GAAM,CAAE,SAAU,EAClB,GAAI,IAAU,EAAG,OAAO,EACxB,IAAM,EAAS,EAAe,EAAM,CAC9B,EAAQ,CAAG,YAAY,EAAM,MAEnC,MAAO,EAAG,IAAI,EAAM,KAAK,EAAO,KAAK,EAAY,CAAG,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E,YACA,WACA,GAAG,EACD,EACA,EACA,KAAK,WACJ,EAAO,IAAW,CACjB,IAAM,EAAW,EAAuB,EAAO,CAC3C,KAAS,SAAW,EACxB,OAAO,KAAK,UAAU,GACpB,GAAG,EAAS,IACT,GAAY,CAAG,iBAAiB,EAAM,IAAI,EAAQ,EAAQ,CAAC,GAC9D,CACD,EAEJ,CACD,eAAgB,EAAO,IACrB,CAAG,iBAAiB,EAAQ,EAAe,EAAQ,CAAC,CAAC,IAAI,EAAM,GACjE,UAAW,EAAM,IACf,CAAG,sBAAsB,EAAK,IAAI,EAAM,IAAI,GAA8B,GAC7E,IACC,CASJ,YACE,EACA,EACA,EACA,EACO,CACP,IAAM,EAAS,KAAK,YAAY,MAAM,EAAM,CACtC,EAAK,KAAK,YAAY,OAAO,EAAU,CAC7C,MAAO,CACL,CAAG,eAAe,IAClB,CAAG,eAAe,EAAO,iBAAiB,KAAK,YAAY,MAAM,EAAK,CAAC,2BAA2B,EAAO,GAAG,EAAG,KAAK,EAAO,GAAG,IAC/H,CAGH,OAA8B,CAM5B,0BAA2B,cAI3B,kBAAmB,EAAQ,IACzB,EAAY,EAAQ,EAAY,QAAQ,EAAE,gBAAkB,OAO9D,YAAa,EACb,cAAe,EAEf,YACE,EACA,EACA,IACY,CAEZ,GAAI,IAAe,UAAW,CAC5B,IAAM,EAAS,GACb,IAAU,IAAM,EAAI,IAAU,IAAM,EAAI,EACzC,CACD,GAAI,IAAW,IAAA,GACb,OAAO,EAAK,EAAO,CAKvB,GAAI,IAAe,YAAc,OAAO,GAAU,SAAU,CAC1D,IAAM,EAAM,EAAmB,EAAM,CACrC,GAAI,IAAQ,IAAA,GACV,OAAO,EAAK,EAAI,CAGpB,OAAO,GAAM,EAEhB"}
|
package/dist/mysql2.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { $a as QueryExecutionContext, Di as LinkedClientConfig, Gr as Schema, Ja as TransactionOptionSupport, S as PinnedSessionReservation, eo as QueryResult, h as Driver, pt as VibORMClient, qa as DriverTransactionOptions, st as DriverConfig, t as DatabaseAdapter, ut as NoExtraDriverConfigKeys, w as MigrationNamespaceAttestation } from "./database-adapter-BMjJiBFm.mjs";
|
|
2
2
|
import { Pool, PoolConnection, PoolOptions } from "mysql2/promise";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/mysql2/index.d.ts
|
|
@@ -26,34 +26,9 @@ type MySQL2ClientConfig<C extends DriverConfig> = MySQL2DriverOptions & C;
|
|
|
26
26
|
declare class MySQL2Driver extends Driver<Pool, PoolConnection> {
|
|
27
27
|
readonly adapter: DatabaseAdapter;
|
|
28
28
|
readonly maxBindParametersPerStatement: number | undefined;
|
|
29
|
-
|
|
30
|
-
private readonly suppliedPool;
|
|
31
|
-
private readonly connectionOptions;
|
|
29
|
+
private readonly _p;
|
|
32
30
|
constructor(options?: MySQL2DriverOptions);
|
|
33
|
-
/**
|
|
34
|
-
* The pool this driver connects through.
|
|
35
|
-
*
|
|
36
|
-
* A caller's pool is RETURNED rather than replaced: reconnecting after a
|
|
37
|
-
* `$disconnect()` used to build a second pool behind their back — a transport
|
|
38
|
-
* they never asked for, pointed at whatever their options record said by
|
|
39
|
-
* then, and then never closed, because the ownership question was still
|
|
40
|
-
* answered "supplied".
|
|
41
|
-
*/
|
|
42
31
|
protected initClient(): Promise<Pool>;
|
|
43
|
-
/**
|
|
44
|
-
* Ends only a pool this driver created.
|
|
45
|
-
*
|
|
46
|
-
* A supplied pool belongs to the caller, who may be sharing it with other
|
|
47
|
-
* clients or with their own code, and §5.3's rule is that VibORM never
|
|
48
|
-
* changes a caller's connection state. `$disconnect()` used to end it
|
|
49
|
-
* regardless, so disconnecting one client tore down every other consumer of
|
|
50
|
-
* that pool.
|
|
51
|
-
*
|
|
52
|
-
* The test is on the pool's IDENTITY against what construction captured, so
|
|
53
|
-
* it answers for the pool actually being closed rather than for whatever the
|
|
54
|
-
* caller's record says now: every pool this driver made is ended, and the one
|
|
55
|
-
* it was handed never is.
|
|
56
|
-
*/
|
|
57
32
|
protected closeClient(pool: Pool): Promise<void>;
|
|
58
33
|
protected execute<T>(client: Pool | PoolConnection, sql: string, params: unknown[], context?: QueryExecutionContext): Promise<QueryResult<T>>;
|
|
59
34
|
protected executeRaw<T>(client: Pool | PoolConnection, sql: string, params: unknown[] | undefined, context?: QueryExecutionContext): Promise<QueryResult<T>>;
|
package/dist/mysql2.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{B as e,m as t,u as n}from"./error-mapping-B9rSvgG9.mjs";import{a as r}from"./base-17NSFtrA.mjs";import{p as i,r as a}from"./validation-ATmgN5RE.mjs";import{n as o}from"./transaction-Bv5nyp-U.mjs";import{a as s,i as c,o as l}from"./normalized-result-D7nVkF36.mjs";import{n as u}from"./client-D7sWgUt2.mjs";import{t as d}from"./mysql-adapter-BFWYPoM0.mjs";import{c as f,g as p,h as m,p as h,r as g,s as _,v}from"./driver-lShUkDmf.mjs";import{Buffer as y}from"node:buffer";const b=/^(?:ssl|tls)/i;function x(e){return new a(e,{meta:{driver:`mysql2`,operation:`configuration`}})}function S(e){let t=new URL(e),n=decodeURIComponent(t.pathname.slice(1)),r={};for(let[e,n]of t.searchParams){if(b.test(e)&&e!==`ssl`&&e!==`sslmode`)throw x(`Unsupported MySQL TLS URL option; configure options.ssl explicitly.`);try{r[e]=JSON.parse(n)}catch{r[e]=n}}let i=t.searchParams.get(`sslmode`);if(i&&i!==`disable`){if(![`require`,`verify-ca`,`verify-full`].includes(i))throw x(`Unsupported MySQL sslmode; configure options.ssl explicitly.`);if(r.ssl!==void 0&&(r.ssl===null||typeof r.ssl!=`object`&&typeof r.ssl!=`string`))throw x(`MySQL sslmode requires a TLS configuration`);r.ssl??={}}Reflect.deleteProperty(r,`sslmode`);let a=decodeURIComponent(t.username),o=decodeURIComponent(t.password);return{host:t.hostname,...t.port?{port:Number.parseInt(t.port,10)}:{},...n===``?{}:{database:n},...a===``?{}:{user:a},...o===``?{}:{password:o},...r}}const C={pool:!0,options:!0,databaseUrl:!0,namespace:!0,migrationNamespaceAttestation:!0};function w(e){return e.map(e=>e instanceof Uint8Array&&!y.isBuffer(e)?y.from(e.buffer,e.byteOffset,e.byteLength):e)}function T(e){return Array.isArray(e)&&e.every(e=>e===void 0||Array.isArray(e))}function E(e,t){return new i(`Driver "mysql2" returned a malformed result for operation "${e}": ${t}.`,{meta:{driver:`mysql2`,operation:e}})}const D=/^-[1-9]\d*$/;function O(e,t){if(!(typeof e==`number`&&Number.isSafeInteger(e)&&e<0||typeof e==`string`&&D.test(e)))return s(e,t,{n5:!0})}function k(e,t,n){if(T(t))throw new i(`Driver "mysql2" returned multiple statement results for "${n}".`,{meta:{driver:`mysql2`,operation:n}});if(Array.isArray(e)){if(!Array.isArray(t)||t.some(e=>!c(e)))throw E(n,`row arrays require one flat field metadata array`);return{rows:e,rowCount:e.length}}if(t!==void 0)throw E(n,`mutation results require undefined field metadata`);if(!c(e))throw E(n,`expected a mutation result object`);let r={provider:`mysql2`,operation:n},a=O(e.insertId,r);return{rows:[],rowCount:l(e.affectedRows,r,{wj:!0}),...a===void 0?{}:{insertId:a}}}function A(e){if(e.hk)return;let t=e.gb.database;return t===``?void 0:t}function j(e){let t=v(e),n=e.databaseUrl,r={...n?M(n):void 0};for(let[t,n]of Object.entries(e.options??{}))n!==void 0&&Reflect.set(r,t,n);let i={hk:e.pool,gb:r};return{namespace:t??A(i),...i}}function M(e){try{return S(e)}catch(e){throw r(e)?e:new a(`Driver "mysql2" could not parse its databaseUrl.`,{cause:e instanceof Error?e:void 0})}}function N(e){throw new a(`Driver "mysql2" does not support options.${e}.`,{meta:{driver:`mysql2`,operation:`configuration`}})}var P=class extends g{static get name(){return`MySQL2Driver`}maxBindParametersPerStatement=65535;_p;constructor(e={}){let t=p(e),n=j(e);super(`mysql`,`mysql2`,{},t);let r=n.gb;r.multipleStatements===!0&&N(`multipleStatements=true`),r.rowsAsArray===!0&&N(`rowsAsArray=true`),(r.nestTables===!0||typeof r.nestTables==`string`)&&N(`nestTables`),this._p={p:n.hk,c:r},h(this,`adapter`,new d(n.namespace)),n.hk&&(this.client=n.hk)}async initClient(){if(this._p.p!==void 0)return this._p.p;let e=await import(`mysql2/promise`),t={timezone:`Z`,supportBigNumbers:!0,dateStrings:[`DATE`],...this._p.c};return this.adapter.namespace!==void 0&&(t={...t,database:this.adapter.namespace}),e.createPool(t)}async closeClient(e){e!==this._p.p&&await e.end()}async execute(e,t,n,r){let i=r?.operation??`execute`,[a,o]=await e.query({sql:t,values:w(n),typeCast:(e,t)=>[`DATE`,`DATETIME`,`TIMESTAMP`,`LONGLONG`,`NEWDECIMAL`].includes(e.type)?e.string():t()});return k(a,o,i)}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`,[a,o]=await e.query(t,n&&w(n));return k(a,o,i)}transactionOptionSupport(){return{isolationLevel:`pre-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(r,i,a,s){if(!(`getConnection`in r))throw n(this.driverName);let c=r,l=await _(()=>c.getConnection(),e=>e.release(),s?.maxWaitMs,{driverName:this.driverName,form:`callback`}),u=!1,d=async e=>{try{await e()}catch(e){throw u=!0,e}},p=s?.isolationLevel;return t({begin:()=>d(async()=>{p&&await l.query(f(p)),await l.beginTransaction()}),callback:()=>i(l),commit:()=>d(()=>l.commit()),rollback:()=>d(()=>l.rollback()),he:e(a),close:()=>{try{if(u){l.destroy();return}l.release()}catch(e){throw super.transactionCleanupFailed(new o(`Driver "mysql2" could not release an unsafe transaction connection.`,{meta:{driver:`mysql2`,method:`$transaction`}})),e}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!(`getConnection`in e))throw n(this.driverName);let t=await e.getConnection();return{session:t,release:()=>(t.destroy(),Promise.resolve())}}};function F(e){m(e,`mysql2`,C);let{pool:t,options:n,databaseUrl:r}=e;return u(e,new P({migrationNamespaceAttestation:p(e),namespace:v(e),pool:t,options:n,databaseUrl:r}))}export{P as MySQL2Driver,F as createClient};
|
|
2
2
|
//# sourceMappingURL=mysql2.mjs.map
|
package/dist/mysql2.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mysql2.mjs","names":[],"sources":["../src/drivers/shared/mysql-utils.ts","../src/drivers/mysql2/index.ts"],"sourcesContent":["/**\n * Shared MySQL Utilities\n *\n * Shared connection utilities for MySQL-based drivers.\n */\n\nimport { ClientInitializationError } from \"@errors\";\n\n/**\n * The connection options a MySQL database URL carries: only the keys it\n * spells, so merged under a caller's options it fills what they left out\n * instead of replacing it with `undefined` or a default port.\n */\nexport interface MySQLConnectionOptions {\n [option: string]: unknown;\n ssl?: object | string;\n host: string;\n port?: number;\n /** Absent when the URL carries no database path. */\n database?: string;\n user?: string;\n password?: string;\n}\n\nconst TLS_URL_OPTION_PATTERN = /^(?:ssl|tls)/i;\n\n/**\n * A TLS request VibORM cannot honour. Its own text, which carries no part of\n * the URL, so the driver surfaces it rather than redacting it.\n */\nfunction tlsRefusal(message: string): ClientInitializationError {\n return new ClientInitializationError(message, {\n meta: { driver: \"mysql2\", operation: \"configuration\" },\n });\n}\n\nexport function parseMySQLUrl(url: string): MySQLConnectionOptions {\n const parsed = new URL(url);\n const database = decodeURIComponent(parsed.pathname.slice(1));\n const queryOptions: Record<string, unknown> = {};\n for (const [key, value] of parsed.searchParams) {\n if (\n TLS_URL_OPTION_PATTERN.test(key) &&\n key !== \"ssl\" &&\n key !== \"sslmode\"\n ) {\n throw tlsRefusal(\n \"Unsupported MySQL TLS URL option; configure options.ssl explicitly.\"\n );\n }\n try {\n queryOptions[key] = JSON.parse(value);\n } catch {\n queryOptions[key] = value;\n }\n }\n // mysql2 understands ssl, but not libpq's sslmode. Refuse a TLS request\n // whose policy cannot be represented instead of silently opening plaintext.\n const sslmode = parsed.searchParams.get(\"sslmode\");\n if (sslmode && sslmode !== \"disable\") {\n if (![\"require\", \"verify-ca\", \"verify-full\"].includes(sslmode)) {\n throw tlsRefusal(\n \"Unsupported MySQL sslmode; configure options.ssl explicitly.\"\n );\n }\n if (\n queryOptions.ssl !== undefined &&\n (queryOptions.ssl === null ||\n (typeof queryOptions.ssl !== \"object\" &&\n typeof queryOptions.ssl !== \"string\"))\n )\n throw tlsRefusal(\"MySQL sslmode requires a TLS configuration\");\n queryOptions.ssl ??= {};\n }\n Reflect.deleteProperty(queryOptions, \"sslmode\");\n const user = decodeURIComponent(parsed.username);\n const password = decodeURIComponent(parsed.password);\n return {\n host: parsed.hostname,\n ...(parsed.port ? { port: Number.parseInt(parsed.port, 10) } : {}),\n ...(database === \"\" ? {} : { database }),\n ...(user === \"\" ? {} : { user }),\n ...(password === \"\" ? {} : { password }),\n ...queryOptions,\n };\n}\n","/**\n * MySQL2 Driver\n *\n * Driver implementation for mysql2/promise with connection pooling.\n */\n\nimport { Buffer } from \"node:buffer\";\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { MySQLAdapter } from \"@adapters/databases/mysql/mysql-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n ClientInitializationError,\n isVibORMError,\n QueryError,\n TransactionError,\n} from \"@errors\";\nimport type { Pool, PoolConnection, PoolOptions } from \"mysql2/promise\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n isNormalizedResultRow,\n type NormalizedResultContext,\n normalizeProviderInsertId,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n isolationLevelStatement,\n type MigrationNamespaceAttestation,\n type MySQLConnectionOptions,\n nestedTransactionDispatchError,\n type PinnedSessionReservation,\n parseMySQLUrl,\n resolveMigrationNamespaceAttestationOption,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type MySQL2Options = PoolOptions;\n\nexport interface MySQL2DriverOptions {\n pool?: Pool;\n options?: PoolOptions;\n databaseUrl?: string;\n /**\n * The MySQL database this driver's persistent objects live in. Omitted, the\n * target is derived from a driver-created pool's own configuration, and a\n * driver that resolves none keeps the existing unqualified mode.\n */\n namespace?: string;\n /**\n * Caller-owned assertion that qualified `database.table` references and the\n * pinned migration session's `USE` cannot be redirected by VTGate\n * schema-routing rules or an equivalent proxy. It selects nothing, is never\n * inferred, and only effectful live migration work requires it.\n */\n migrationNamespaceAttestation?: MigrationNamespaceAttestation;\n}\n\nexport type MySQL2ClientConfig<C extends DriverConfig> = MySQL2DriverOptions &\n C;\n\nconst MYSQL2_CONFIG_KEYS: Record<keyof MySQL2DriverOptions, true> = {\n pool: true,\n options: true,\n databaseUrl: true,\n namespace: true,\n migrationNamespaceAttestation: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\n/** mysql2 escapes plain Uint8Array as an object — convert to Buffer for blobs. */\nfunction convertValuesForMySQL(values: unknown[]): unknown[] {\n return values.map((v) =>\n v instanceof Uint8Array && !Buffer.isBuffer(v)\n ? Buffer.from(v.buffer, v.byteOffset, v.byteLength)\n : v\n );\n}\n\nfunction isMultiStatementFields(fields: unknown): boolean {\n return (\n Array.isArray(fields) &&\n fields.every(\n (fieldSet) => fieldSet === undefined || Array.isArray(fieldSet)\n )\n );\n}\n\nfunction malformedMySQL2Result(operation: string, reason: string): QueryError {\n return new QueryError(\n `Driver \"mysql2\" returned a malformed result for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"mysql2\", operation } }\n );\n}\n\nconst CANONICAL_NEGATIVE_DECIMAL = /^-[1-9]\\d*$/;\n\n/** mysql2 echoes an explicit negative AUTO_INCREMENT key in ResultSetHeader.insertId. */\nfunction normalizeMySQL2InsertId(\n value: unknown,\n context: NormalizedResultContext\n): number | bigint | undefined {\n if (\n (typeof value === \"number\" && Number.isSafeInteger(value) && value < 0) ||\n (typeof value === \"string\" && CANONICAL_NEGATIVE_DECIMAL.test(value))\n ) {\n return undefined;\n }\n return normalizeProviderInsertId(value, context, { allowNumber: true });\n}\n\n/** SELECT returns a row array; mutations return a ResultSetHeader. */\nfunction toQueryResult<T>(\n result: unknown,\n fields: unknown,\n operation: string\n): QueryResult<T> {\n if (isMultiStatementFields(fields)) {\n throw new QueryError(\n `Driver \"mysql2\" returned multiple statement results for operation \"${operation}\"; VibORM requires exactly one statement result.`,\n { meta: { driver: \"mysql2\", operation } }\n );\n }\n\n if (Array.isArray(result)) {\n if (\n !Array.isArray(fields) ||\n fields.some((field) => !isNormalizedResultRow(field))\n ) {\n throw malformedMySQL2Result(\n operation,\n \"row arrays require one flat field metadata array\"\n );\n }\n return {\n rows: result as T[],\n rowCount: result.length,\n };\n }\n\n if (fields !== undefined) {\n throw malformedMySQL2Result(\n operation,\n \"mutation results require undefined field metadata\"\n );\n }\n if (!isNormalizedResultRow(result)) {\n throw malformedMySQL2Result(operation, \"expected a mutation result object\");\n }\n const context = { provider: \"mysql2\", operation };\n const insertId = normalizeMySQL2InsertId(result.insertId, context);\n return {\n rows: [] as T[],\n rowCount: normalizeProviderRowCount(result.affectedRows, context, {\n allowDecimalString: true,\n }),\n ...(insertId === undefined ? {} : { insertId }),\n };\n}\n\n/**\n * The target derived from a pool this driver will create: the `database` it\n * connects with, which is the caller's option when given and otherwise the\n * URL's path (see `resolveMySQL2Configuration`). A supplied `Pool` is opaque —\n * VibORM does not inspect mysql2 internals, so only an explicit `namespace` can\n * bind one. A pathless URL contributes nothing, and neither does an empty\n * `options.database`: §1.3's empty candidate is an absent one rather than a\n * name handed to identifier validation. A non-empty derived name is validated\n * exactly like an explicit one, by the adapter that installs it.\n */\nfunction deriveMySQL2Namespace(\n configuration: Omit<MySQL2Configuration, \"namespace\">\n): string | undefined {\n if (configuration.suppliedPool) return undefined;\n const configured = configuration.connectionOptions.database;\n return configured === \"\" ? undefined : configured;\n}\n\n/** What this driver settles from its caller's object, each source read once. */\ninterface MySQL2Configuration {\n readonly namespace: string | undefined;\n /**\n * The EXACT pool the caller supplied, or absent when this driver makes its\n * own. Identity, settled once, is the whole ownership answer: the caller's\n * options object is theirs to change, and a `pool` key deleted after\n * construction used to make `$disconnect()` end a transport VibORM was handed.\n */\n readonly suppliedPool: Pool | undefined;\n /**\n * The caller's connection record, copied once, over the keys its\n * `databaseUrl` carries: the URL fills only what the record leaves out, and\n * a key the record sets to `undefined` (an unset environment variable) is\n * left out. A per-tenant URL plus a password from a secret is this shape.\n *\n * A copy of THIS record, not of what it points at: a nested `ssl` object or\n * stream is the caller's to own, and the keys that decide where a pool\n * connects — host, port, user, database — all live here. It is also what the\n * constructor's refusals read, so the options this driver validated are the\n * exact options it later connects with.\n */\n readonly connectionOptions: PoolOptions;\n}\n\n/**\n * The one immutable ORM target for this driver, in the plan's exact order: an\n * explicit `namespace`, then the driver-created pool's own derivation.\n *\n * `databaseUrl` is read once and parsed once, here, and the parse is kept: a\n * second read at connect time would let a caller-owned accessor hand the\n * provider a different URL than the one that decided the target. A present URL\n * is parsed even when an explicit `namespace` outranks it, because an unusable\n * connection string is a construction failure either way; `\"\"`, `null`, and an\n * absent property are the same absent request. Both rules are the convenience\n * wrapper's too, so the two entry points cannot disagree.\n *\n * None of these sources is transport evidence: the attestation is read\n * separately and never derived from a resolved target.\n */\nfunction resolveMySQL2Configuration(\n options: MySQL2DriverOptions\n): MySQL2Configuration {\n const explicit = resolveNamespaceOption(options);\n const databaseUrl = options.databaseUrl;\n const urlOptions = databaseUrl\n ? parseMySQL2ConfiguredUrl(databaseUrl)\n : undefined;\n const connectionOptions: PoolOptions = { ...urlOptions };\n for (const [key, value] of Object.entries(options.options ?? {})) {\n if (value !== undefined) Reflect.set(connectionOptions, key, value);\n }\n const captured = { suppliedPool: options.pool, connectionOptions };\n return {\n namespace: explicit ?? deriveMySQL2Namespace(captured),\n ...captured,\n };\n}\n\n/**\n * The URL now decides a target, so a malformed one fails at construction. A\n * TLS refusal is VibORM's own secret-free text and passes through; the URL\n * parser's failure can carry the URL, so it is replaced and redacted.\n */\nfunction parseMySQL2ConfiguredUrl(databaseUrl: string): MySQLConnectionOptions {\n try {\n return parseMySQLUrl(databaseUrl);\n } catch (cause) {\n if (isVibORMError(cause)) throw cause;\n throw new ClientInitializationError(\n 'Driver \"mysql2\" could not parse its databaseUrl.',\n { cause: cause instanceof Error ? cause : undefined }\n );\n }\n}\n\nexport class MySQL2Driver extends Driver<Pool, PoolConnection> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n /** The caller's pool and connection record, as construction captured them. */\n private readonly suppliedPool: Pool | undefined;\n private readonly connectionOptions: PoolOptions;\n\n constructor(options: MySQL2DriverOptions = {}) {\n // Both facts are read before `super(...)` so the transport assertion is\n // installed by the base constructor and no option can be read twice.\n const attestation = resolveMigrationNamespaceAttestationOption(options);\n const configuration = resolveMySQL2Configuration(options);\n super(\"mysql\", \"mysql2\", {}, attestation);\n if (configuration.connectionOptions.multipleStatements === true) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support options.multipleStatements=true because VibORM operations require one result per statement.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n if (configuration.connectionOptions.rowsAsArray === true) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support options.rowsAsArray=true because VibORM requires row objects keyed by column name.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n if (\n configuration.connectionOptions.nestTables === true ||\n typeof configuration.connectionOptions.nestTables === \"string\"\n ) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support enabled options.nestTables because VibORM requires flat row objects keyed by result aliases.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n this.suppliedPool = configuration.suppliedPool;\n this.connectionOptions = configuration.connectionOptions;\n defineImmutableDriverFact(\n this,\n \"adapter\",\n new MySQLAdapter(configuration.namespace)\n );\n if (this.suppliedPool) {\n this.client = this.suppliedPool;\n }\n }\n\n /**\n * The pool this driver connects through.\n *\n * A caller's pool is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second pool behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<Pool> {\n if (this.suppliedPool !== undefined) {\n return this.suppliedPool;\n }\n const mysql = await import(\"mysql2/promise\");\n\n let options: PoolOptions = {\n // DATETIME is stored as naive UTC wall-clock; read it back as UTC\n // instead of shifting by the process timezone\n timezone: \"Z\",\n // BIGINT/DECIMAL values outside Number's safe range arrive as strings\n // (the result parser converts them losslessly) instead of lossy numbers\n supportBigNumbers: true,\n // DATE as plain \"YYYY-MM-DD\" — the result parser builds a UTC-midnight\n // Date, matching every other driver (mysql2 would build local midnight)\n dateStrings: [\"DATE\"],\n // Already merged with the URL, from the one parse construction made:\n // this driver never re-reads the caller's `databaseUrl`.\n ...this.connectionOptions,\n };\n\n // The pool this driver creates defaults to the same database the adapter\n // qualifies with, whichever source resolved it. A supplied pool never\n // reaches here, so VibORM never changes a caller's connection state.\n if (this.adapter.namespace !== undefined) {\n options = { ...options, database: this.adapter.namespace };\n }\n\n return mysql.createPool(options);\n }\n\n /**\n * Ends only a pool this driver created.\n *\n * A supplied pool belongs to the caller, who may be sharing it with other\n * clients or with their own code, and §5.3's rule is that VibORM never\n * changes a caller's connection state. `$disconnect()` used to end it\n * regardless, so disconnecting one client tore down every other consumer of\n * that pool.\n *\n * The test is on the pool's IDENTITY against what construction captured, so\n * it answers for the pool actually being closed rather than for whatever the\n * caller's record says now: every pool this driver made is ended, and the one\n * it was handed never is.\n */\n protected async closeClient(pool: Pool): Promise<void> {\n if (pool === this.suppliedPool) {\n return;\n }\n await pool.end();\n }\n\n protected async execute<T>(\n client: Pool | PoolConnection,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n const [result, fields] = await client.query({\n sql,\n values: convertValuesForMySQL(params),\n // Per-statement decoding also covers borrowed pools without mutating\n // their connection options. Text protocol avoids a statement per IN size.\n typeCast: (field, next) =>\n [\"DATE\", \"DATETIME\", \"TIMESTAMP\", \"LONGLONG\", \"NEWDECIMAL\"].includes(\n field.type\n )\n ? field.string()\n : next(),\n });\n return toQueryResult<T>(result, fields, operation);\n }\n\n protected async executeRaw<T>(\n client: Pool | PoolConnection,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const [result, fields] = await client.query(\n sql,\n params && convertValuesForMySQL(params)\n );\n return toQueryResult<T>(result, fields, operation);\n }\n\n /**\n * MySQL rejects `SET TRANSACTION ISOLATION LEVEL` once a transaction is open\n * (ER_CANT_CHANGE_TX_CHARACTERISTICS), so the level must be set on the\n * transaction's own connection *before* BEGIN, where it applies to exactly\n * the next transaction on that session. mysql2 pools hand out a connection we\n * can wait for with a bound and release if we stop waiting.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"pre-begin\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: Pool | PoolConnection,\n fn: (tx: PoolConnection) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (!(\"getConnection\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n // Start a new transaction from pool\n const pool = client as Pool;\n const connection = await acquireWithMaxWait(\n () => pool.getConnection(),\n (acquired) => acquired.release(),\n options?.maxWaitMs,\n { driverName: this.driverName, form: \"callback\" }\n );\n let shouldDestroy = false;\n const runOrDestroy = async (operation: () => Promise<void>) => {\n try {\n await operation();\n } catch (error) {\n shouldDestroy = true;\n throw error;\n }\n };\n const isolationLevel = options?.isolationLevel;\n return runTransactionLifecycle({\n begin: () =>\n runOrDestroy(async () => {\n // Session-scoped-next-transaction: this statement must land before\n // beginTransaction() to bind to the transaction it opens.\n if (isolationLevel) {\n await connection.query(isolationLevelStatement(isolationLevel));\n }\n await connection.beginTransaction();\n }),\n callback: () => fn(connection),\n commit: () => runOrDestroy(() => connection.commit()),\n rollback: () => runOrDestroy(() => connection.rollback()),\n phases: getExecutionTransactionPhases(context),\n close: () => {\n try {\n if (shouldDestroy) {\n connection.destroy();\n return;\n }\n connection.release();\n } catch (error) {\n super.transactionCleanupFailed(\n new TransactionError(\n 'Driver \"mysql2\" could not release an unsafe transaction connection.',\n { meta: { driver: \"mysql2\", method: \"$transaction\" } }\n )\n );\n throw error;\n }\n },\n });\n }\n\n protected override transactionCleanupFailed(_error: Error): void {\n // A connection with failed cleanup is destroyed; the pool remains usable.\n }\n\n /**\n * One `PoolConnection` from `pool.getConnection()` — plan §3.5's pinned\n * producer for MySQL2.\n *\n * It is ALWAYS destroyed, never released, and the `discard` flag is therefore\n * ignored: this session has executed `USE` to select the migration target and\n * may have executed author-owned statements from a manual artifact, and\n * mysql2's release resets neither. Returning it to an owned or a supplied\n * pool would leak that state into unrelated queries. This is correctness, not\n * an optimization.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<Pool | PoolConnection>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (!(\"getConnection\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const connection = await client.getConnection();\n return {\n session: connection,\n release: () => {\n connection.destroy();\n return Promise.resolve();\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: MySQL2ClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, MySQL2DriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: MySQL2Driver }\n >]: LinkedClientConfig<C & { driver: MySQL2Driver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"mysql2\", MYSQL2_CONFIG_KEYS);\n const { pool, options, databaseUrl } = config;\n const driver = new MySQL2Driver({\n // Attestation first, then namespace: the order a refusal reports in.\n migrationNamespaceAttestation:\n resolveMigrationNamespaceAttestationOption(config),\n namespace: resolveNamespaceOption(config),\n pool,\n options,\n databaseUrl,\n });\n\n return createClientFromDriverConfig<S, C, MySQL2Driver>(config, driver);\n}\n"],"mappings":"2gBAwBA,MAAM,EAAyB,gBAM/B,SAAS,WAAW,EAA4C,CAC9D,OAAO,IAAI,EAA0B,EAAS,CAC5C,KAAM,CAAE,OAAQ,SAAU,UAAW,gBAAiB,CACvD,CAAC,CAGJ,SAAgB,cAAc,EAAqC,CACjE,IAAM,EAAS,IAAI,IAAI,EAAI,CACrB,EAAW,mBAAmB,EAAO,SAAS,MAAM,EAAE,CAAC,CACvD,EAAwC,EAAE,CAChD,IAAK,GAAM,CAAC,EAAK,KAAU,EAAO,aAAc,CAC9C,GACE,EAAuB,KAAK,EAAI,EAChC,IAAQ,OACR,IAAQ,UAER,MAAM,WACJ,sEACD,CAEH,GAAI,CACF,EAAa,GAAO,KAAK,MAAM,EAAM,MAC/B,CACN,EAAa,GAAO,GAKxB,IAAM,EAAU,EAAO,aAAa,IAAI,UAAU,CAClD,GAAI,GAAW,IAAY,UAAW,CACpC,GAAI,CAAC,CAAC,UAAW,YAAa,cAAc,CAAC,SAAS,EAAQ,CAC5D,MAAM,WACJ,+DACD,CAEH,GACE,EAAa,MAAQ,IAAA,KACpB,EAAa,MAAQ,MACnB,OAAO,EAAa,KAAQ,UAC3B,OAAO,EAAa,KAAQ,UAEhC,MAAM,WAAW,6CAA6C,CAChE,EAAa,MAAQ,EAAE,CAEzB,QAAQ,eAAe,EAAc,UAAU,CAC/C,IAAM,EAAO,mBAAmB,EAAO,SAAS,CAC1C,EAAW,mBAAmB,EAAO,S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AejE,MAAyB,eAEvB,CACA,IAAM,EAAS,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CACnE,GAAI,EAAE,kBAAmB,GACvB,MAAM,EAA+B,KAAK,WAAW,CAEvD,IAAM,EAAa,MAAM,EAAO,eAAe,CAC/C,MAAO,CACL,QAAS,EACT,aACE,EAAW,SAAS,CACb,QAAQ,SAAS,EAE3B,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,SAAU,EAAmB,CACnE,GAAM,CAAE,OAAM,UAAS,eAAgB,EAWvC,OAAO,EAAiD,EAVzC,IAAI,aAAa,CAE9B,8BACE,EAA2C,EAAO,CACpD,UAAW,EAAuB,EAAO,CACzC,OACA,UACA,cACD,CAAC,CAEqE"}
|
|
1
|
+
{"version":3,"file":"mysql2.mjs","names":[],"sources":["../src/drivers/shared/mysql-utils.ts","../src/drivers/mysql2/index.ts"],"sourcesContent":["/**\n * Shared MySQL Utilities\n *\n * Shared connection utilities for MySQL-based drivers.\n */\n\nimport { ClientInitializationError } from \"@errors\";\n\n/**\n * The connection options a MySQL database URL carries: only the keys it\n * spells, so merged under a caller's options it fills what they left out\n * instead of replacing it with `undefined` or a default port.\n */\nexport interface MySQLConnectionOptions {\n [option: string]: unknown;\n ssl?: object | string;\n host: string;\n port?: number;\n /** Absent when the URL carries no database path. */\n database?: string;\n user?: string;\n password?: string;\n}\n\nconst TLS_URL_OPTION_PATTERN = /^(?:ssl|tls)/i;\n\n/**\n * A TLS request VibORM cannot honour. Its own text, which carries no part of\n * the URL, so the driver surfaces it rather than redacting it.\n */\nfunction tlsRefusal(message: string): ClientInitializationError {\n return new ClientInitializationError(message, {\n meta: { driver: \"mysql2\", operation: \"configuration\" },\n });\n}\n\nexport function parseMySQLUrl(url: string): MySQLConnectionOptions {\n const parsed = new URL(url);\n const database = decodeURIComponent(parsed.pathname.slice(1));\n const queryOptions: Record<string, unknown> = {};\n for (const [key, value] of parsed.searchParams) {\n if (\n TLS_URL_OPTION_PATTERN.test(key) &&\n key !== \"ssl\" &&\n key !== \"sslmode\"\n ) {\n throw tlsRefusal(\n \"Unsupported MySQL TLS URL option; configure options.ssl explicitly.\"\n );\n }\n try {\n queryOptions[key] = JSON.parse(value);\n } catch {\n queryOptions[key] = value;\n }\n }\n // mysql2 understands ssl, but not libpq's sslmode. Refuse a TLS request\n // whose policy cannot be represented instead of silently opening plaintext.\n const sslmode = parsed.searchParams.get(\"sslmode\");\n if (sslmode && sslmode !== \"disable\") {\n if (![\"require\", \"verify-ca\", \"verify-full\"].includes(sslmode)) {\n throw tlsRefusal(\n \"Unsupported MySQL sslmode; configure options.ssl explicitly.\"\n );\n }\n if (\n queryOptions.ssl !== undefined &&\n (queryOptions.ssl === null ||\n (typeof queryOptions.ssl !== \"object\" &&\n typeof queryOptions.ssl !== \"string\"))\n )\n throw tlsRefusal(\"MySQL sslmode requires a TLS configuration\");\n queryOptions.ssl ??= {};\n }\n Reflect.deleteProperty(queryOptions, \"sslmode\");\n const user = decodeURIComponent(parsed.username);\n const password = decodeURIComponent(parsed.password);\n return {\n host: parsed.hostname,\n ...(parsed.port ? { port: Number.parseInt(parsed.port, 10) } : {}),\n ...(database === \"\" ? {} : { database }),\n ...(user === \"\" ? {} : { user }),\n ...(password === \"\" ? {} : { password }),\n ...queryOptions,\n };\n}\n","/**\n * MySQL2 Driver\n *\n * Driver implementation for mysql2/promise with connection pooling.\n */\n\nimport { Buffer } from \"node:buffer\";\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { MySQLAdapter } from \"@adapters/databases/mysql/mysql-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n ClientInitializationError,\n isVibORMError,\n QueryError,\n TransactionError,\n} from \"@errors\";\nimport type { Pool, PoolConnection, PoolOptions } from \"mysql2/promise\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n isNormalizedResultRow,\n type NormalizedResultContext,\n normalizeProviderInsertId,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n isolationLevelStatement,\n type MigrationNamespaceAttestation,\n type MySQLConnectionOptions,\n nestedTransactionDispatchError,\n type PinnedSessionReservation,\n parseMySQLUrl,\n resolveMigrationNamespaceAttestationOption,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type MySQL2Options = PoolOptions;\n\nexport interface MySQL2DriverOptions {\n pool?: Pool;\n options?: PoolOptions;\n databaseUrl?: string;\n /**\n * The MySQL database this driver's persistent objects live in. Omitted, the\n * target is derived from a driver-created pool's own configuration, and a\n * driver that resolves none keeps the existing unqualified mode.\n */\n namespace?: string;\n /**\n * Caller-owned assertion that qualified `database.table` references and the\n * pinned migration session's `USE` cannot be redirected by VTGate\n * schema-routing rules or an equivalent proxy. It selects nothing, is never\n * inferred, and only effectful live migration work requires it.\n */\n migrationNamespaceAttestation?: MigrationNamespaceAttestation;\n}\n\nexport type MySQL2ClientConfig<C extends DriverConfig> = MySQL2DriverOptions &\n C;\n\nconst MYSQL2_CONFIG_KEYS: Record<keyof MySQL2DriverOptions, true> = {\n pool: true,\n options: true,\n databaseUrl: true,\n namespace: true,\n migrationNamespaceAttestation: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\n/** mysql2 escapes plain Uint8Array as an object — convert to Buffer for blobs. */\nfunction convertValuesForMySQL(values: unknown[]): unknown[] {\n return values.map((v) =>\n v instanceof Uint8Array && !Buffer.isBuffer(v)\n ? Buffer.from(v.buffer, v.byteOffset, v.byteLength)\n : v\n );\n}\n\nfunction isMultiStatementFields(fields: unknown): boolean {\n return (\n Array.isArray(fields) &&\n fields.every(\n (fieldSet) => fieldSet === undefined || Array.isArray(fieldSet)\n )\n );\n}\n\nfunction malformedMySQL2Result(operation: string, reason: string): QueryError {\n return new QueryError(\n `Driver \"mysql2\" returned a malformed result for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"mysql2\", operation } }\n );\n}\n\nconst CANONICAL_NEGATIVE_DECIMAL = /^-[1-9]\\d*$/;\n\n/** mysql2 echoes an explicit negative AUTO_INCREMENT key in ResultSetHeader.insertId. */\nfunction normalizeMySQL2InsertId(\n value: unknown,\n context: NormalizedResultContext\n): number | bigint | undefined {\n if (\n (typeof value === \"number\" && Number.isSafeInteger(value) && value < 0) ||\n (typeof value === \"string\" && CANONICAL_NEGATIVE_DECIMAL.test(value))\n ) {\n return undefined;\n }\n return normalizeProviderInsertId(value, context, { allowNumber: true });\n}\n\n/** SELECT returns a row array; mutations return a ResultSetHeader. */\nfunction toQueryResult<T>(\n result: unknown,\n fields: unknown,\n operation: string\n): QueryResult<T> {\n if (isMultiStatementFields(fields)) {\n throw new QueryError(\n `Driver \"mysql2\" returned multiple statement results for \"${operation}\".`,\n { meta: { driver: \"mysql2\", operation } }\n );\n }\n\n if (Array.isArray(result)) {\n if (\n !Array.isArray(fields) ||\n fields.some((field) => !isNormalizedResultRow(field))\n ) {\n throw malformedMySQL2Result(\n operation,\n \"row arrays require one flat field metadata array\"\n );\n }\n return {\n rows: result as T[],\n rowCount: result.length,\n };\n }\n\n if (fields !== undefined) {\n throw malformedMySQL2Result(\n operation,\n \"mutation results require undefined field metadata\"\n );\n }\n if (!isNormalizedResultRow(result)) {\n throw malformedMySQL2Result(operation, \"expected a mutation result object\");\n }\n const context = { provider: \"mysql2\", operation };\n const insertId = normalizeMySQL2InsertId(result.insertId, context);\n return {\n rows: [] as T[],\n rowCount: normalizeProviderRowCount(result.affectedRows, context, {\n allowDecimalString: true,\n }),\n ...(insertId === undefined ? {} : { insertId }),\n };\n}\n\n/**\n * The target derived from a pool this driver will create: the `database` it\n * connects with, which is the caller's option when given and otherwise the\n * URL's path (see `resolveMySQL2Configuration`). A supplied `Pool` is opaque —\n * VibORM does not inspect mysql2 internals, so only an explicit `namespace` can\n * bind one. A pathless URL contributes nothing, and neither does an empty\n * `options.database`: §1.3's empty candidate is an absent one rather than a\n * name handed to identifier validation. A non-empty derived name is validated\n * exactly like an explicit one, by the adapter that installs it.\n */\nfunction deriveMySQL2Namespace(\n configuration: Omit<MySQL2Configuration, \"namespace\">\n): string | undefined {\n if (configuration.suppliedPool) return undefined;\n const configured = configuration.connectionOptions.database;\n return configured === \"\" ? undefined : configured;\n}\n\n/** What this driver settles from its caller's object, each source read once. */\ninterface MySQL2Configuration {\n readonly namespace: string | undefined;\n /**\n * The EXACT pool the caller supplied, or absent when this driver makes its\n * own. Identity, settled once, is the whole ownership answer: the caller's\n * options object is theirs to change, and a `pool` key deleted after\n * construction used to make `$disconnect()` end a transport VibORM was handed.\n */\n readonly suppliedPool: Pool | undefined;\n /**\n * The caller's connection record, copied once, over the keys its\n * `databaseUrl` carries: the URL fills only what the record leaves out, and\n * a key the record sets to `undefined` (an unset environment variable) is\n * left out. A per-tenant URL plus a password from a secret is this shape.\n *\n * A copy of THIS record, not of what it points at: a nested `ssl` object or\n * stream is the caller's to own, and the keys that decide where a pool\n * connects — host, port, user, database — all live here. It is also what the\n * constructor's refusals read, so the options this driver validated are the\n * exact options it later connects with.\n */\n readonly connectionOptions: PoolOptions;\n}\n\n/**\n * The one immutable ORM target for this driver, in the plan's exact order: an\n * explicit `namespace`, then the driver-created pool's own derivation.\n *\n * `databaseUrl` is read once and parsed once, here, and the parse is kept: a\n * second read at connect time would let a caller-owned accessor hand the\n * provider a different URL than the one that decided the target. A present URL\n * is parsed even when an explicit `namespace` outranks it, because an unusable\n * connection string is a construction failure either way; `\"\"`, `null`, and an\n * absent property are the same absent request. Both rules are the convenience\n * wrapper's too, so the two entry points cannot disagree.\n *\n * None of these sources is transport evidence: the attestation is read\n * separately and never derived from a resolved target.\n */\nfunction resolveMySQL2Configuration(\n options: MySQL2DriverOptions\n): MySQL2Configuration {\n const explicit = resolveNamespaceOption(options);\n const databaseUrl = options.databaseUrl;\n const urlOptions = databaseUrl\n ? parseMySQL2ConfiguredUrl(databaseUrl)\n : undefined;\n const connectionOptions: PoolOptions = { ...urlOptions };\n for (const [key, value] of Object.entries(options.options ?? {})) {\n if (value !== undefined) Reflect.set(connectionOptions, key, value);\n }\n const captured = { suppliedPool: options.pool, connectionOptions };\n return {\n namespace: explicit ?? deriveMySQL2Namespace(captured),\n ...captured,\n };\n}\n\n/**\n * The URL now decides a target, so a malformed one fails at construction. A\n * TLS refusal is VibORM's own secret-free text and passes through; the URL\n * parser's failure can carry the URL, so it is replaced and redacted.\n */\nfunction parseMySQL2ConfiguredUrl(databaseUrl: string): MySQLConnectionOptions {\n try {\n return parseMySQLUrl(databaseUrl);\n } catch (cause) {\n if (isVibORMError(cause)) throw cause;\n throw new ClientInitializationError(\n 'Driver \"mysql2\" could not parse its databaseUrl.',\n { cause: cause instanceof Error ? cause : undefined }\n );\n }\n}\n\nfunction unsupportedMySQL2Option(option: string): never {\n throw new ClientInitializationError(\n `Driver \"mysql2\" does not support options.${option}.`,\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n}\n\nexport class MySQL2Driver extends Driver<Pool, PoolConnection> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n private readonly _p: {\n readonly p: Pool | undefined;\n readonly c: PoolOptions;\n };\n\n constructor(options: MySQL2DriverOptions = {}) {\n const attestation = resolveMigrationNamespaceAttestationOption(options);\n const configuration = resolveMySQL2Configuration(options);\n super(\"mysql\", \"mysql2\", {}, attestation);\n const opts = configuration.connectionOptions;\n if (opts.multipleStatements === true)\n unsupportedMySQL2Option(\"multipleStatements=true\");\n if (opts.rowsAsArray === true) unsupportedMySQL2Option(\"rowsAsArray=true\");\n if (opts.nestTables === true || typeof opts.nestTables === \"string\")\n unsupportedMySQL2Option(\"nestTables\");\n this._p = { p: configuration.suppliedPool, c: opts };\n defineImmutableDriverFact(\n this,\n \"adapter\",\n new MySQLAdapter(configuration.namespace)\n );\n if (configuration.suppliedPool) {\n this.client = configuration.suppliedPool;\n }\n }\n\n protected async initClient(): Promise<Pool> {\n if (this._p.p !== undefined) {\n return this._p.p;\n }\n const mysql = await import(\"mysql2/promise\");\n\n let options: PoolOptions = {\n timezone: \"Z\",\n supportBigNumbers: true,\n dateStrings: [\"DATE\"],\n ...this._p.c,\n };\n\n if (this.adapter.namespace !== undefined) {\n options = { ...options, database: this.adapter.namespace };\n }\n\n return mysql.createPool(options);\n }\n\n protected async closeClient(pool: Pool): Promise<void> {\n if (pool === this._p.p) {\n return;\n }\n await pool.end();\n }\n\n protected async execute<T>(\n client: Pool | PoolConnection,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n const [result, fields] = await client.query({\n sql,\n values: convertValuesForMySQL(params),\n // Per-statement decoding also covers borrowed pools without mutating\n // their connection options. Text protocol avoids a statement per IN size.\n typeCast: (field, next) =>\n [\"DATE\", \"DATETIME\", \"TIMESTAMP\", \"LONGLONG\", \"NEWDECIMAL\"].includes(\n field.type\n )\n ? field.string()\n : next(),\n });\n return toQueryResult<T>(result, fields, operation);\n }\n\n protected async executeRaw<T>(\n client: Pool | PoolConnection,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const [result, fields] = await client.query(\n sql,\n params && convertValuesForMySQL(params)\n );\n return toQueryResult<T>(result, fields, operation);\n }\n\n /**\n * MySQL rejects `SET TRANSACTION ISOLATION LEVEL` once a transaction is open\n * (ER_CANT_CHANGE_TX_CHARACTERISTICS), so the level must be set on the\n * transaction's own connection *before* BEGIN, where it applies to exactly\n * the next transaction on that session. mysql2 pools hand out a connection we\n * can wait for with a bound and release if we stop waiting.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"pre-begin\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: Pool | PoolConnection,\n fn: (tx: PoolConnection) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (!(\"getConnection\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n // Start a new transaction from pool\n const pool = client as Pool;\n const connection = await acquireWithMaxWait(\n () => pool.getConnection(),\n (acquired) => acquired.release(),\n options?.maxWaitMs,\n { driverName: this.driverName, form: \"callback\" }\n );\n let shouldDestroy = false;\n const runOrDestroy = async (operation: () => Promise<void>) => {\n try {\n await operation();\n } catch (error) {\n shouldDestroy = true;\n throw error;\n }\n };\n const isolationLevel = options?.isolationLevel;\n return runTransactionLifecycle({\n begin: () =>\n runOrDestroy(async () => {\n // Session-scoped-next-transaction: this statement must land before\n // beginTransaction() to bind to the transaction it opens.\n if (isolationLevel) {\n await connection.query(isolationLevelStatement(isolationLevel));\n }\n await connection.beginTransaction();\n }),\n callback: () => fn(connection),\n commit: () => runOrDestroy(() => connection.commit()),\n rollback: () => runOrDestroy(() => connection.rollback()),\n phases: getExecutionTransactionPhases(context),\n close: () => {\n try {\n if (shouldDestroy) {\n connection.destroy();\n return;\n }\n connection.release();\n } catch (error) {\n super.transactionCleanupFailed(\n new TransactionError(\n 'Driver \"mysql2\" could not release an unsafe transaction connection.',\n { meta: { driver: \"mysql2\", method: \"$transaction\" } }\n )\n );\n throw error;\n }\n },\n });\n }\n\n protected override transactionCleanupFailed(_error: Error): void {\n // A connection with failed cleanup is destroyed; the pool remains usable.\n }\n\n /**\n * One `PoolConnection` from `pool.getConnection()` — plan §3.5's pinned\n * producer for MySQL2.\n *\n * It is ALWAYS destroyed, never released, and the `discard` flag is therefore\n * ignored: this session has executed `USE` to select the migration target and\n * may have executed author-owned statements from a manual artifact, and\n * mysql2's release resets neither. Returning it to an owned or a supplied\n * pool would leak that state into unrelated queries. This is correctness, not\n * an optimization.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<Pool | PoolConnection>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (!(\"getConnection\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const connection = await client.getConnection();\n return {\n session: connection,\n release: () => {\n connection.destroy();\n return Promise.resolve();\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: MySQL2ClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, MySQL2DriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: MySQL2Driver }\n >]: LinkedClientConfig<C & { driver: MySQL2Driver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"mysql2\", MYSQL2_CONFIG_KEYS);\n const { pool, options, databaseUrl } = config;\n const driver = new MySQL2Driver({\n // Attestation first, then namespace: the order a refusal reports in.\n migrationNamespaceAttestation:\n resolveMigrationNamespaceAttestationOption(config),\n namespace: resolveNamespaceOption(config),\n pool,\n options,\n databaseUrl,\n });\n\n return createClientFromDriverConfig<S, C, MySQL2Driver>(config, driver);\n}\n"],"mappings":"6dAwBA,MAAM,EAAyB,gBAM/B,SAAS,EAAW,EAA4C,CAC9D,OAAO,IAAI,EAA0B,EAAS,CAC5C,KAAM,CAAE,OAAQ,SAAU,UAAW,gBAAiB,CACvD,CAAC,CAGJ,SAAgB,EAAc,EAAqC,CACjE,IAAM,EAAS,IAAI,IAAI,EAAI,CACrB,EAAW,mBAAmB,EAAO,SAAS,MAAM,EAAE,CAAC,CACvD,EAAwC,EAAE,CAChD,IAAK,GAAM,CAAC,EAAK,KAAU,EAAO,aAAc,CAC9C,GACE,EAAuB,KAAK,EAAI,EAChC,IAAQ,O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ACF,MAAM,EAAW,MAAM,EAAwB,EAAe,CAAC,CAEjE,MAAM,EAAW,kBAAkB,EACnC,CACJ,aAAgB,EAAG,EAAW,CAC9B,WAAc,MAAmB,EAAW,QAAQ,CAAC,CACrD,aAAgB,MAAmB,EAAW,UAAU,CAAC,CACzD,OAAQ,EAA8B,EAAQ,CAC9C,UAAa,CACX,GAAI,CACF,GAAI,EAAe,CACjB,EAAW,SAAS,CACpB,OAEF,EAAW,SAAS,OACb,EAAO,CAOd,MANA,MAAM,yBACJ,IAAI,EACF,sEACA,CAAE,KAAM,CAAE,OAAQ,SAAU,OAAQ,eAAgB,CAAC,CACvD,CACD,CACK,IAGX,CAAC,CAGJ,yBAA4C,EAAqB,EAejE,MAAyB,eAEvB,CACA,IAAM,EAAS,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CACnE,GAAI,EAAE,kBAAmB,GACvB,MAAM,EAA+B,KAAK,WAAW,CAEvD,IAAM,EAAa,MAAM,EAAO,eAAe,CAC/C,MAAO,CACL,QAAS,EACT,aACE,EAAW,SAAS,CACb,QAAQ,SAAS,EAE3B,GAQL,SAAgB,EACd,EAOC,CACD,EAA8B,EAAQ,SAAU,EAAmB,CACnE,GAAM,CAAE,OAAM,UAAS,eAAgB,EAWvC,OAAO,EAAiD,EAVzC,IAAI,EAAa,CAE9B,8BACE,EAA2C,EAAO,CACpD,UAAW,EAAuB,EAAO,CACzC,OACA,UACA,cACD,CAAC,CAEqE"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{r as e}from"./validation-ATmgN5RE.mjs";const t=e=>{let t=3735928559,n=1103547991;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=Math.imul(t^i,2654435761),n=Math.imul(n^i,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(t^t>>>13,3266489909),(4294967296*(2097151&n)+(t>>>0)).toString(36)};var n=class{static get name(){return`NamedStatements`}#e;#t;#n;#r=new Map;#i=new Set;#a=new Set;#o=new Set;#s=0;constructor(e,t){this.#e=e,this.#t=typeof t==`object`?t.max:100,this.#n=t===!0||typeof t==`object`&&t.auto!==!1}name(e,t){if(t===!1||!(t||this.#n))return;let n=this.#r.get(e);if(n!==void 0)return n;if(this.#s>=this.#t){t&&this.#c(e);return}if(!this.#a.has(e)){if(this.#i.delete(e)||t)return this.#l(e,``);this.#i.size>=256&&(this.#i=new Set),this.#i.add(e)}}m6(e){this.#r.delete(e)&&this.#s<this.#t&&this.#l(e,`_${this.#s}`)}drop(e){this.#r.delete(e)&&this.#a.add(e)}#c(e){this.#o.size>=256||this.#o.has(e)||(this.#o.add(e),console.warn(`VibORM (${this.#e}): namedStatements.max (${this.#t}) reached; sent unnamed: ${e.slice(0,160)}`))}#l(e,n){let r=`v${t(e)}${n}`;return this.#s++,this.#r.set(e,r),r}};const r=`getTypeInputInfo`,i=new Set([`FetchPreparedStatement`,`RevalidateCachedQuery`,r]),a=e=>{let t=o(e);return typeof t==`string`&&i.has(t)},o=e=>typeof e==`object`&&e&&`routine`in e?e.routine:void 0,s=(t,r)=>{if(r){if(typeof r==`object`?!(Number.isInteger(r.max)&&r.max>0)||r.auto!==void 0&&typeof r.auto!=`boolean`:r!==!0&&r!==`explicit`)throw new e(`Driver "${t}": invalid namedStatements.`,{meta:{driver:t,operation:`configuration`}});return new n(t,r)}};export{o as i,a as n,s as r,r as t};
|
|
2
|
+
//# sourceMappingURL=named-statements-CkOOD__I.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"named-statements-CkOOD__I.mjs","names":[],"sources":["../src/drivers/shared/named-statements.ts"],"sourcesContent":["// biome-ignore-all lint/suspicious/noBitwiseOperators: the name hash (cyrb53) is defined on 32-bit integer operations.\n/**\n * Which statements a PostgreSQL driver sends as named, server-side prepared\n * statements, and under which name.\n *\n * A named statement is parsed and planned once per connection, then only\n * bound: the server skips the parse and the plan a short query mostly pays\n * for. Each connection keeps every statement it was asked to name until it\n * closes (node-postgres and postgres.js evict none), and VibORM writes one SQL\n * text per query shape, so the names are bounded here: at most `max` texts\n * ever take a name, and a connection holds at most `max` statements of this\n * driver.\n *\n * Which texts take a place: a call's `named` decides first (`true` names its\n * statements at their first sending, `false` never), and a call that says\n * nothing is named, in the automatic mode only, the second time its text is\n * sent. A text seen once (a one-off shape, a `createMany` of an unusual row\n * count) never takes a place on its own.\n *\n * The name is derived from the text, never chosen by the caller: one call\n * writes several texts as its arguments vary, and a name stands for one text.\n * Two clients sharing one pool, or two Workers isolates behind Hyperdrive,\n * give the same text the same name.\n */\n\nimport { ClientInitializationError } from \"@errors\";\n\n/**\n * Statements a driver names, by default. Measured on PostgreSQL 18, a named\n * statement holds 11 kB (a `findUnique`) to 42 kB (a `findMany` with a\n * relation as JSON) of server memory per connection: 100 is at most about\n * 4 MB a connection, and under PgBouncer's default `max_prepared_statements`\n * (200).\n */\nexport const NAMED_STATEMENTS_MAX = 100;\n/** Texts remembered as seen once; past it, counting starts over. */\nconst SEEN_MAX = 256;\n\n/**\n * The public option. `true` is `{ max: 100, auto: true }`; `\"explicit\"` is\n * `{ max: 100, auto: false }`. With `auto: false`, only the statements of a\n * call that passes `named: true` are named.\n */\nexport type NamedStatementsOption =\n | boolean\n | \"explicit\"\n | { readonly max: number; readonly auto?: boolean };\n\n/** A 53-bit hash of the text (cyrb53), in base 36: about eleven characters. */\nconst hash = (text: string): string => {\n let h1 = 0xde_ad_be_ef;\n let h2 = 0x41_c6_ce_57;\n for (let index = 0; index < text.length; index++) {\n const code = text.charCodeAt(index);\n h1 = Math.imul(h1 ^ code, 2_654_435_761);\n h2 = Math.imul(h2 ^ code, 1_597_334_677);\n }\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2_246_822_507);\n h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3_266_489_909);\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2_246_822_507);\n h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3_266_489_909);\n return (4_294_967_296 * (2_097_151 & h2) + (h1 >>> 0)).toString(36);\n};\n\nexport class NamedStatements {\n readonly #driver: string;\n readonly #max: number;\n /** Whether a call that does not pass `named` may be named. */\n readonly #auto: boolean;\n /** Each named text's name. */\n readonly #names = new Map<string, string>();\n #seen = new Set<string>();\n /** Texts never named again (`drop`): at most `max`, as each had a name. */\n readonly #dropped = new Set<string>();\n /** Texts a `named: true` call asked for after the bound: each told once. */\n readonly #refused = new Set<string>();\n /** Names given, retired ones included: what a connection may hold. */\n #given = 0;\n\n constructor(driver: string, option: Exclude<NamedStatementsOption, false>) {\n this.#driver = driver;\n this.#max = typeof option === \"object\" ? option.max : NAMED_STATEMENTS_MAX;\n this.#auto =\n option === true || (typeof option === \"object\" && option.auto !== false);\n }\n\n /**\n * The name to send this text under, or `undefined` to send it unnamed.\n * `named` is the call's own option: `true` names the text at once, `false`\n * never, absent the second time it is sent where the mode is automatic.\n */\n name(text: string, named: boolean | undefined): string | undefined {\n if (named === false || !(named || this.#auto)) return;\n const given = this.#names.get(text);\n if (given !== undefined) return given;\n if (this.#given >= this.#max) {\n if (named) this.#full(text);\n return;\n }\n if (this.#dropped.has(text)) return;\n if (this.#seen.delete(text) || named) return this.#give(text, \"\");\n if (this.#seen.size >= SEEN_MAX) this.#seen = new Set();\n this.#seen.add(text);\n return;\n }\n\n /**\n * The server no longer answers this text's name (a `DEALLOCATE`, a\n * `DISCARD ALL`, a pooler that moved the session) or its plan no longer\n * fits the table: the text takes a new name, which every connection parses\n * again, or none once `max` names were given. A retired name still counts:\n * the connections that did not lose it keep it, so at the bound the text is\n * sent unnamed for the client's life.\n */\n retire(text: string): void {\n if (this.#names.delete(text) && this.#given < this.#max)\n this.#give(text, `_${this.#given}`);\n }\n\n /**\n * A driver whose client keys prepared statements by text (postgres.js)\n * cannot name a stale text anew: the same text meets the same stale entry.\n * The text is sent unprepared for the driver's life.\n */\n drop(text: string): void {\n if (this.#names.delete(text)) this.#dropped.add(text);\n }\n\n /**\n * A call asked to name a text and every place is taken: the text is sent\n * unnamed, and the application told once per text (of the first\n * `SEEN_MAX`) that `max` is too low for what it names.\n */\n #full(text: string): void {\n if (this.#refused.size >= SEEN_MAX || this.#refused.has(text)) return;\n this.#refused.add(text);\n console.warn(\n `VibORM (${this.#driver}): namedStatements.max (${this.#max}) reached; sent unnamed: ${text.slice(0, 160)}`\n );\n }\n\n /** A 53-bit hash leaves two texts one name with a chance far below one in a billion. */\n #give(text: string, suffix: string): string {\n const name = `v${hash(text)}${suffix}`;\n this.#given++;\n this.#names.set(text, name);\n return name;\n }\n}\n\n/** The routine of a parameter whose type was replaced: postgres.js does not retry it. */\nexport const REPLACED_TYPE = \"getTypeInputInfo\";\n\n/**\n * The server routines that say a name is stale rather than the statement\n * wrong, each raised before the statement does anything: the server no longer\n * has the name (`DEALLOCATE`, `DISCARD ALL`, a pooler that moved the session),\n * the plan's result type changed under it, or a parameter's type was replaced\n * (a migration that replaces an enum: the name keeps the old type's oid).\n */\nconst STALE_ROUTINES = new Set([\n \"FetchPreparedStatement\",\n \"RevalidateCachedQuery\",\n REPLACED_TYPE,\n]);\n\n/** Whether a statement's failure says its name is stale, not that the statement is wrong. */\nexport const isStaleStatement = (error: unknown): boolean => {\n const routine = routineOf(error);\n return typeof routine === \"string\" && STALE_ROUTINES.has(routine);\n};\n\n/** The server routine a driver error reports, when it reports one. */\nexport const routineOf = (error: unknown): unknown =>\n typeof error === \"object\" && error !== null && \"routine\" in error\n ? error.routine\n : undefined;\n\n/** The driver's registry for the option, or none when it is absent or `false`. */\nexport const namedStatements = (\n driver: string,\n option: NamedStatementsOption | undefined\n): NamedStatements | undefined => {\n if (!option) return;\n if (\n typeof option === \"object\"\n ? !(Number.isInteger(option.max) && option.max > 0) ||\n (option.auto !== undefined && typeof option.auto !== \"boolean\")\n : option !== true && option !== \"explicit\"\n )\n throw new ClientInitializationError(\n `Driver \"${driver}\": invalid namedStatements.`,\n { meta: { driver, operation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+
* The public option. `true` is `{ max: 100, auto: true }`; `"explicit"` is
|
|
5
|
+
* `{ max: 100, auto: false }`. With `auto: false`, only the statements of a
|
|
6
|
+
* call that passes `named: true` are named.
|
|
7
|
+
*/
|
|
8
|
+
type NamedStatementsOption = boolean | "explicit" | {
|
|
9
|
+
readonly max: number;
|
|
10
|
+
readonly auto?: boolean;
|
|
11
|
+
};
|
|
12
|
+
//#endregion
|
|
13
|
+
export { NamedStatementsOption as t };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{S as e,b as t,h as n}from"./base-17NSFtrA.mjs";import{r,t as i}from"./validation-ATmgN5RE.mjs";import{a,i as o,o as s,s as c,t as l}from"./value-guards-CBVIJXlI.mjs";const u=z(`Expected bigint or an integer string`),d=`^[+-]?\\d+$`,f=new RegExp(d);function p(e){return l(e)?U(e):typeof e==`string`&&f.test(e)?U(BigInt(e)):u}function m(e){return G(`bigint`,p,e)}const h=[`longitude`,`latitude`],g=-180,_=180,v=-90,y=90,b=[`south`,`west`,`north`,`east`],x=3,ee=/^(?:[0-9a-fA-F]{2})*$/,S=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,C=/^base64:type\d+:(.*)$/;function w(e){if(!ee.test(e))return{unsupported:`hex string`};let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=Number.parseInt(e.slice(n*2,n*2+2),16);return{bytes:t}}function T(e){return S.test(e)?{bytes:Uint8Array.from(atob(e),e=>e.charCodeAt(0))}:{unsupported:`base64 string`}}function E(e){if(e instanceof ArrayBuffer)return{bytes:new Uint8Array(e.slice(0))};if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),{bytes:t}}if(ArrayBuffer.isView(e)){let t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),{bytes:t}}if(Array.isArray(e)){for(let t of e)if(!Number.isInteger(t)||t<0||t>255)return{unsupported:`byte array`};return{bytes:Uint8Array.from(e)}}if(typeof e==`string`){if(e.startsWith(`\\x`))return w(e.slice(2));if(e.startsWith(`base64:type`)){let t=C.exec(e);return t?T(t[1]):{unsupported:`base64 string`}}return w(e)}return{unsupported:typeof e}}const D=16,O=10,te=10,ne=16,re=14e8;re+4294967295;const ie=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`,ae=ie+`0123456789abcdefghjkmnpqrstvwxyz`,oe=`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`,se=21,ce=/^[a-z][0-9a-z]{23}$/,k=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,le=2n**160n,A=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,j=62n;function M(e,t,n){throw new i({kind:`schema-builder`,builder:e,path:t},[{path:t,message:n}])}const ue=65536;function de(e,t){let n=globalThis.crypto;return typeof n?.getRandomValues!=`function`&&M(`s.string().${t}`,`generate`,`Cannot generate ${t}: crypto.getRandomValues unavailable`),n.getRandomValues(new Uint8Array(e))}function fe(e){return e!==void 0&&e!==``}function N(e,t){return fe(e)?`${e}-${t}`:t}function pe(e,t,n){let r=n;for(let n=t-1;n>=0;n--)e[n]=r%256,r=Math.floor(r/256)}function me(e,t,n,r,i,a,o,s){(!Number.isInteger(n)||n<r||n>i)&&M(`s.string().${e}`,`generate`,`${t} timestamp must be integer in ${r}..${i}; got ${n}`);let c=new Uint8Array(o);return c.set(s,a),pe(c,a,n-r),c}function he(e,t,n){return me(e,e,t,0,0xffffffffffff,6,16,n)}function ge(e,t){return e[6]=e[6]&15|t,e[8]=e[8]&63|128,e}function _e(e){return ge(e,64)}function ve(e,t){return ge(he(`uuidv7`,e,t),112)}function ye(e,t,n,r){e.length!==t&&M(`s.string().${n}`,`generate`,`${r} must be ${t} bytes; got ${e.length}`)}function be(e){ye(e,16,`uuid`,`UUID`);let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function xe(e){if(!A.test(e))return;let t=e.replaceAll(`-`,``),n=new Uint8Array(16);for(let e=0;e<16;e++)n[e]=Number.parseInt(t.slice(e*2,e*2+2),16);return n}function Se(e,t){return he(`ulid`,e,t)}function Ce(e){ye(e,16,`ulid`,`ULID`);let t=``,n=0,r=2;for(let i of e){for(n=n<<8|i,r+=8;r>=5;)r-=5,t+=ie.charAt(n>>>r&31);n&=(1<<r)-1}return t}function we(e){if(e.length!==26)return;let t=ae.indexOf(e.charAt(0));if(t<0)return;let n=t%32;if(n>7)return;let r=new Uint8Array(16),i=n,a=3,o=0;for(let t of e.slice(1)){let e=ae.indexOf(t);if(e<0)return;i=i<<5|e%32,a+=5,a>=8&&(a-=8,r[o]=i>>>a&255,o++,i&=(1<<a)-1)}return r}function Te(e,t){return me(`ksuid`,`KSUID`,e,re,5694967295,4,20,t)}function Ee(e){ye(e,20,`ksuid`,`KSUID`);let t=0n;for(let n of e)t=t*256n+BigInt(n);return De(t)}function De(e){let t=[],n=e;for(let e=0;e<27;e++)t.push(k.charAt(Number(n%j))),n/=j;return t.reverse().join(``)}const Oe=`aWgEPTl1tmebfsQzFP4bxwgy80V`;function ke(e){if(e.length!==27)return;let t=0n;for(let n of e){let e=k.indexOf(n);if(e<0)return;t=t*j+BigInt(e)}if(t>=le)return;let n=new Uint8Array(20);for(let e=19;e>=0;e--)n[e]=Number(t&255n),t>>=8n;return n}const Ae=new Set(`uuid uuidv7 ulid ksuid nanoid cuid`.split(` `));function je(e){return e!==void 0&&Ae.has(e)}function Me(e){return Ge(e)!==void 0}function Ne(e,t){return e===void 0||t===void 0?e===t:e.format===t.format&&P(e)===P(t)&&F(e)===F(t)}function P(e){return e.prefix||void 0}function F(e){if(e.format===`nanoid`)return e.length??21}function Pe(e){let t=P(e),n=e.format===`nanoid`?` of length ${F(e)}`:``;return`a ${e.format} value${n}${t===void 0?``:` prefixed '${t}-'`}`}const Fe=/[$()*+./?[\\\]^{|}]/g;function Ie(e){let t=P(e);return`^${t===void 0?``:`${t.replace(Fe,`\\$&`)}-`}${Le(e)}$`}function Le(e){switch(e.format){case`uuid`:case`uuidv7`:return A.source.slice(1,-1);case`ulid`:return`[0-7][${ie}0123456789abcdefghjkmnpqrstvwxyz]{25}`;case`ksuid`:return Re(Oe);case`nanoid`:return`[${oe.replace(`-`,`\\-`)}]{${F(e)}}`;default:return ce.source.slice(1,-1)}}function Re(e){let t=[e];for(let n=0;n<e.length;n++){let r=Be(e[n]);r!==``&&t.push(`${e.slice(0,n)}[${r}][0-9A-Za-z]{${e.length-n-1}}`)}return`(?:${t.join(`|`)})`}const ze=/[0-9]{3,}|[A-Z]{3,}|[a-z]{3,}/g;function Be(e){return k.slice(0,k.indexOf(e)).replace(ze,e=>`${e[0]}-${e.at(-1)}`)}function Ve(e,t){let n=P(t);if(n===void 0)return e;let r=`${n}-`;return e.startsWith(r)?e.slice(r.length):void 0}function He(e,t){if(e.length!==t)return!1;for(let t of e)if(!oe.includes(t))return!1;return!0}function Ue(e,t){switch(t.format){case`uuid`:case`uuidv7`:return A.test(e)?e.toLowerCase():void 0;case`ulid`:return we(e)?e.toUpperCase():void 0;case`ksuid`:return ke(e)?e:void 0;case`nanoid`:return He(e,F(t))?e:void 0;default:return ce.test(e)?e:void 0}}function We(e,t){if(typeof e!=`string`)return;let n=Ve(e,t);if(n===void 0)return;let r=Ue(n,t);return r===void 0?void 0:N(P(t),r)}function Ge(e){return e===`ksuid`?20:e===`uuid`||e===`uuidv7`||e===`ulid`?16:void 0}function Ke(e,t,n){let r=We(e,t);if(r===void 0||n===`text`)return r;let i=Ve(r,t);if(n===`uuid`)return i;let{format:a}=t;return a===`ulid`?we(i):a===`ksuid`?ke(i):a===`uuid`||a===`uuidv7`?xe(i):void 0}function qe(e,t,n){if(n===`text`)return We(e,t);let r=P(t);if(n===`uuid`)return typeof e==`string`&&A.test(e)?N(r,e.toLowerCase()):void 0;let{bytes:i}=E(e);if(!(i===void 0||i.length!==Ge(t.format)))return N(r,t.format===`ulid`?Ce(i):t.format===`ksuid`?Ee(i):be(i))}const Je=[`draft-07`,`draft-2020-12`,`openapi-3.0`];function Ye(e,t,n=`input`){return{definitions:{},hw:new Map,pf:new Map,i3:t,c1:0,target:e,direction:n}}const Xe=new Set([`array`,`nullable`,`nonNullable`,`optional`,`lazyRef`]);function Ze({precision:e,scale:t}){let n=e-t;return`^[+-]?(?:${n===0?`0+`:`(?:0+|0*[1-9]\\d{0,${n-1}})`}(?:\\.${`\\d{0,${t}}0*`})?|\\.${t===0?`0+`:`\\d{1,${t}}0*`})$`}function I(e,t){return{type:`object`,properties:e,required:t,additionalProperties:!1}}function L(e,t){return{type:`number`,minimum:e,maximum:t}}function Qe(e,t){return t===`openapi-3.0`?{...e,nullable:!0}:{anyOf:[e,{type:`null`}]}}function $e(){return I({[h[0]]:L(g,180),[h[1]]:L(-90,90)},[...h])}function et(e){let t=e;for(;t&&Xe.has(t.type);)t=t.item??t.wrapped;return t}function tt(e,t){if(e.xc!==null)return e.xc;if(e.schema===t.i3)return e.xc=`#`;let n=e.schema.options?.name||void 0;for(;!n||n in t.definitions;)n=`Recursive${++t.c1}`;return e.name=n,t.definitions[n]={},e.xc=`#/$defs/${n}`}function nt(e,t,n=!1){if(!n){let n=t.hw.get(e);if(n)return{$ref:`#/$defs/${n}`};let r=t.pf.get(e);if(r)return{$ref:tt(r,t)}}let r=t.pf.get(e),i={schema:e,xc:null,name:null};t.pf.set(e,i);let a;try{a=ot(e,t),`options`in e&&s(e.options)&&(e.options.array===!0&&(a={type:`array`,items:a}),e.options.nullable===!0&&(a=Qe(a,t.target)))}finally{r?t.pf.set(e,r):t.pf.delete(e)}return i.name===null?a:(t.definitions[i.name]=a,t.hw.set(e,i.name),{$ref:i.xc})}const rt=Object.assign(Object.create(null),{boolean:{type:`boolean`},bigint:{type:`string`,pattern:d},date:{type:`string`,format:`date-time`},iso_timestamp:{type:`string`,format:`date-time`},iso_date:{type:`string`,format:`date`},iso_time:{type:`string`,format:`time`},json:{},refused:{not:{}},blob:{type:`string`,contentEncoding:`base64`}}),it=new Set(`optional,transform,field_ref_or,comparison_operand,value_node_or,lazyRef,no_field_ref,written_depth,json_null_or,json_write`.split(`,`)),at={"draft-2020-12":`https://json-schema.org/draft/2020-12/schema`,"draft-07":`http://json-schema.org/draft-07/schema#`};function ot(e,t){let n=(e,n)=>nt(e,t,n),r=e.type;if(r===`decimal`){let n=e.options?.decimal;return{...n&&{description:`Exact decimal (${n.precision},${n.scale})`},type:`string`,pattern:t.direction===`output`?`^(?:0|-?(?:[1-9]\\d*(?:\\.\\d*[1-9])?|0\\.\\d*[1-9]))$`:n?Ze(n):`^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)$`}}if(r===`exact_one`){let t=[];for(let[r,i]of Object.entries(e.entries)){let e=o(i)?i():i;e.type!==`refused`&&t.push(I({[r]:n(e)},[r]))}return{oneOf:t}}let a=rt[r];if(a)return{...a};if(it.has(r))return n(e.wrapped);switch(r){case`string`:{let t=e.options?.idDomain;return t?{type:`string`,pattern:Ie(t)}:{type:`string`}}case`number`:case`integer`:{let t={type:r};return`minimum`in e&&typeof e.minimum==`number`&&(t.minimum=e.minimum),`maximum`in e&&typeof e.maximum==`number`&&(t.maximum=e.maximum),t}case`literal`:{let n=e.value;return t.target===`openapi-3.0`?{enum:[n]}:{const:n}}case`enum`:return{enum:e.values};case`nullable`:return Qe(n(e.wrapped),t.target);case`nonNullable`:{let t=n(e.wrapped);if(Array.isArray(t.anyOf)){let e=t.anyOf.filter(e=>e.type!==`null`);return e.length===1?e[0]:{...t,anyOf:e}}if(t.nullable===!0){let{nullable:e,...n}=t;return n}return t}case`array`:return{type:`array`,items:n(e.item)};case`object`:{let r=e.entries,i=e.options,a=i?.partial??!0,l=i?.strict??!0,u={},d=[];for(let e in r){let l=r[e],f=o(l)?l():l,p=et(f),m=p?.options?.name;m&&c(m)&&!t.hw.has(p)&&(t.hw.set(p,m),t.definitions[m]=n(p,!0)),u[e]=n(f);let h=f.type===`optional`||f.acceptsUndefined===!0,g=f.options,_=t.direction===`output`&&s(g)&&g.default!==void 0;(!a||i?.atLeast?.includes(e))&&(_||!h)&&d.push(e)}return{type:`object`,properties:u,required:d.length?d:void 0,...l&&{additionalProperties:!1}}}case`record`:return{type:`object`,additionalProperties:n(e.value)};case`union`:return{anyOf:e.options.map(e=>n(e))};case`vector`:{let t=e.dimensions;return{type:`array`,items:{type:`number`},...t!==void 0&&{minItems:t,maxItems:t}}}case`point`:return $e();case`geo_area`:{let e=L(-90,90),t=L(g,180),n=I({[b[0]]:e,[b[1]]:t,[b[2]]:e,[b[3]]:t},[...b]),r={type:`array`,items:$e(),minItems:3};return{oneOf:[I({bounds:n},[`bounds`]),I({polygon:I({outer:r,holes:{type:`array`,items:r}},[`outer`])},[`polygon`])]}}case`polymorphic_only`:{let{wrapped:t}=e;return{...n(t),uniqueItems:!0}}case`pipe`:return n(e.schema);default:throw new i({kind:`json-schema`,schemaType:r},[{path:`type`,message:`Unsupported type "${r}"`}])}}function st(e,t=`draft-07`){return ct(e,t,`input`)}function ct(e,t,n){if(!Je.includes(t))throw new i({kind:`json-schema`,target:t},[{path:`target`,message:`Unsupported target: ${t}`}]);let r=Ye(t,e,n),a=nt(e,r),o=at[t];return o&&(a.$schema=o),Object.keys(r.definitions).length>0&&(a.$defs=r.definitions),a}function lt(e){return{input(t){return ct(e,t.target,`input`)},output(t){return ct(e,t.target,`output`)}}}const ut=Symbol(`viborm.validation.parseFailureCause`);function dt(e){Promise.resolve(e).catch(()=>void 0)}function ft(e){let r=t(e),i={issues:[{message:`Schema validation failed unexpectedly`}]};return Object.defineProperty(i,ut,{value:n(r)}),i}function pt(t){let n=Reflect.get(t,ut);return e(n)?n:void 0}function mt(e,t,n){return Object.assign(e,{wrapped:t,acceptsUndefined:t.acceptsUndefined===!0,...n})}function R(e,t){return{issues:[t&&t.length>0?{message:e,path:t}:{message:e}]}}function z(e){return Object.freeze({issues:Object.freeze([Object.freeze({message:e})])})}function ht(e,t){let n=e[`~standard`];return Object.defineProperty(n,`validate`,{value:t(n.validate)}),e}function gt(e,t){let n=e[`~standard`];return{...e,parse:t,"~standard":{version:n.version,vendor:n.vendor,validate:t,get types(){return n.types},get jsonSchema(){return n.jsonSchema}}}}let B=!1;const V=()=>B;function _t(e,t){let n=B;B=e;try{return t()}finally{B=n}}function H(e,t){return(B?t:t.slice(0,1)).map(t=>({message:t.message,path:t.path?[e,...t.path]:[e]}))}function U(e){return{value:e}}function vt(e){return{issues:e.map(e=>e.path===void 0?{message:e.message}:{message:e.message,path:e.path.map(e=>typeof e==`object`?e.key:e)})}}const yt=z(`Expected array`),bt=z(`Async schemas are not supported`);function xt(e){return dt(e),bt}const St=Object.freeze({value:null}),Ct=Object.freeze({value:void 0});function wt(e,t){try{if(!Array.isArray(e))return yt}catch{return R(`Could not inspect array`)}let n;try{n=e.length}catch{return R(`Could not read array length`)}if(!Number.isInteger(n)||n<0)return yt;if(n===0)return U([]);let r=Array(n),i;for(let a=0;a<n;a++){let n;try{n=e[a]}catch{return R(`Could not read array member`,[a])}let o=t(n);if(o.issues){let e=H(a,o.issues);if(!B)return{issues:e};(i??=[]).push(...e);continue}r[a]=o.value}return i?{issues:i}:U(r)}function Tt(e,t){return n=>{if(n!==void 0)return e(n);let r;try{r=t()}catch(e){return R(`Default failed: ${Et(e)}`)}return e(r)}}function Et(e){try{return String(e instanceof Error?e.message:e)}catch{return`unrenderable thrown value`}}function W(e,t){return n=>{let r=e(n);return r.issues?r:t(r.value)}}function Dt(e){let t=`Expected ${Pe(e)}`;return n=>{let r=We(n,e);return r===void 0?R(t):U(r)}}function Ot(e,t,n){if(!t)return e;let{nullable:r,optional:i,array:a,default:s,transform:c,schema:l,disallowZero:u,idDomain:d}=t,f=s!==void 0,p=c!==void 0,m=e;u&&(m=W(m,At));let h=d===void 0?void 0:Dt(d);if(h&&(m=W(m,h)),l!==void 0){let e=l[`~standard`].validate;m=W(m,t=>Nt(e,t)),h&&(m=W(m,h))}if(p&&(m=Mt(m,c)),n===`json`&&(p||l!==void 0)&&(m=W(m,e)),m=kt(m,a,r),f){let e=o(s)?s:()=>s;return Tt(m,e)}return kt(m,!1,!1,i)}function kt(e,t,n,r){let i=e;if(t){let e=i;i=t=>wt(t,e)}if(n){let e=i;i=t=>t===null?St:e(t)}if(r){let e=i;i=t=>t===void 0?Ct:e(t)}return i}const At=e=>e===0||e===0n?R(`0 disallowed on auto-increment`):U(e);function jt(e){return R(`Transform failed: ${e instanceof Error?e.message:String(e)}`)}function Mt(e,t){return W(e,e=>{try{return U(t(e))}catch(e){return jt(e)}})}function G(e,t,n,r){let i=n?.optional===!0||n?.default!==void 0;return Object.assign(K(e,Ot(t,n,e)),{options:n,acceptsUndefined:i,...r})}function K(e,t){let n={type:e,"~standard":{version:1,vendor:`viborm`,validate:t,get jsonSchema(){let e=lt(n);return Object.defineProperty(this,`jsonSchema`,{value:e,writable:!1,enumerable:!0}),e}}};return Object.defineProperty(n,` vibInferred`,{value:void 0,enumerable:!1}),n}function Nt(e,t){let n=e(t);return`then`in n?xt(n):n.issues?vt(n.issues):U(n.value)}function Pt(e,t){return Nt(e[`~standard`].validate,t)}const Ft=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/,It=/^0+/,Lt=/0+$/,Rt=/^[+-]/;function zt(e){let[t=``,n=``]=e.replace(Rt,``).split(`.`),r=t.replace(It,``)||`0`,i=n.replace(Lt,``);return r===`0`&&i===``?`0`:`${e.startsWith(`-`)?`-`:``}${r}${i===``?``:`.${i}`}`}function q(e){return typeof e==`string`?Ft.test(e)?zt(e):void 0:en(e)}const Bt=10n;function J(e){return Bt**BigInt(e)}function Vt(e,t,n){let r=e/t,i=e%t*2n;return i>t?r+1n:i<t?r:n===`half-up`||r%2n!=0n?r+1n:r}const Ht=`decimal string (no exponent/number)`,Ut=`Expected Decimal or ${Ht}`,Wt=`Expected Decimal, bigint, or ${Ht}`;function Gt(e,t){let n=e<0n;return Kt(n,(n?-e:e).toString(),t)}function Kt(e,t,n){let r=e?`-`:``;if(n===0)return`${r}${t}`;let i=t.padStart(n+1,`0`),a=i.length-n;return`${r}${i.slice(0,a)}.${i.slice(a)}`}function qt(e,t,n){let r=e<0n;return Kt(r,Vt((r?-e:e)*J(n),J(t),`half-up`).toString(),n)}function Jt(e){let t=e.indexOf(`.`);if(t===-1)return[BigInt(e),0];let n=e.length-t-1;return[BigInt(e.slice(0,t)+e.slice(t+1)),n]}let Yt,Xt;var Zt=class e{static get name(){return`ExactDecimal`}#e;#t;value;constructor(e,t){let n;if(typeof e==`bigint`){let r=e,i=t??0;for(;i>0&&r%Bt===0n;)r/=Bt,i--;this.#e=r,this.#t=r===0n?0:i,n=Gt(this.#e,this.#t)}else if(Yt(e))this.#e=e.#e,this.#t=e.#t,n=e.value;else{let t=q(e);if(t===void 0)throw TypeError(Wt);let[r,i]=Jt(t);this.#e=r,this.#t=i,n=t}this.value=n,Object.defineProperty(this,`value`,{writable:!1,configurable:!1})}static{Yt=e=>typeof e==`object`&&!!e&&#e in e,Xt=e=>e.value}#n(e){return this.#e*J(e-this.#t)}#r(t){let n=new e(t),r=Math.max(this.#t,n.#t);return[this.#n(r),n.#n(r),r]}plus(t){let[n,r,i]=this.#r(t);return new e(n+r,i)}minus(t){let[n,r,i]=this.#r(t);return new e(n-r,i)}times(t){let n=new e(t);return new e(this.#e*n.#e,this.#t+n.#t)}div(t,n=20,r=`half-up`){let i=new e(t);if(i.#e===0n)throw RangeError(`Division by zero`);let a=this.#e*J(i.#t+n),o=i.#e*J(this.#t),s=a<0n!=o<0n,c=Vt(a<0n?-a:a,o<0n?-o:o,r);return new e(s?-c:c,n)}cmp(e){let[t,n]=this.#r(e);return t<n?-1:t>n?1:0}eq(e){return this.cmp(e)===0}lt(e){return this.cmp(e)===-1}lte(e){return this.cmp(e)!==1}gt(e){return this.cmp(e)===1}gte(e){return this.cmp(e)!==-1}abs(){return new e(this.#e<0n?-this.#e:this.#e,this.#t)}neg(){return new e(-this.#e,this.#t)}toString(){return Gt(this.#e,this.#t)}toFixed(e){return e===void 0?this.toString():qt(this.#e,this.#t,e)}toNumber(){return Number(this.toString())}valueOf(){return this.toString()}toJSON(){return this.toString()}[Symbol.for(`nodejs.util.inspect.custom`)](){return`Decimal("${this.value}")`}};const Qt=Zt;function $t(e){let[t,n]=Jt(e);return new Zt(t,n)}function en(e){return Yt(e)?Xt(e):void 0}function tn(e,t){return new Zt(e,t)}function Y(e,t){let[n,r]=Jt(e);return(n*J(t-r)).toString()}function nn(e,t,n){let r=e.indexOf(`.`),i=r===-1?0:e.length-r-1;if(i>n)return`'${e}' exceeds scale ${n} (${i} fractional digits)`;let a=e.startsWith(`-`)?1:0,o;if(e[a]!==`0`)o=(r===-1?e.length:r)-a+n;else{let t=r+1;for(;e[t]===`0`;)t++;o=r===-1?0:n-(t-r-1)}if(o>t)return`'${e}' exceeds precision ${t} (${o} digits)`}function rn(e,t){return e===void 0||t===void 0?e===t:e.precision===t.precision&&e.scale===t.scale}const an=q,on=$t,sn=Y,cn=/^(?:0|-?[1-9]\d*)$/;function ln(e,t,n){if(!(c(e)&&cn.test(e)))return;let r=e.startsWith(`-`)?e.length-1:e.length;if(!(n!==void 0&&r>n))return tn(BigInt(e),t)}function un(e,t,n){let r=ln(e,t,n);return r===void 0?void 0:en(r)}const dn=/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/;function fn(e,t,n=1/0){if(!(c(e)&&dn.test(e)))return;let r=q(e);return nn(r,n,t)===void 0?r:void 0}function pn(e,t){return fn(e,t.scale,t.precision)}function mn(e,t,n){return n===`coefficient`?Y(e,t):e}function hn(e,t,n){return mn(e,t.scale,n)}function gn(e,t,n,r){return n===`text`?fn(e,t,r):un(e,t,r)}function _n(e,t,n,r){if(n===`coefficient`)return ln(e,t,r);let i=fn(e,t,r);return i===void 0?void 0:$t(i)}function vn(e,t,n){return gn(e,t.scale,n,t.precision)}function yn(e,t,n){return _n(e,t.scale,n,t.precision)}function bn(e,t,n){let r=Array(e.length);for(let[i,a]of e.entries()){let e=q(a);if(e===void 0)return;r[i]=mn(e,t.scale,n)}return r}function xn(e,t,n){if(n===`coefficient`)return An(e,t.scale,t.precision);try{if(!Array.isArray(e))return;let n=e.length;if(!Number.isSafeInteger(n)||n<0)return;let r=Array(n);for(let i=0;i<n;i++){if(!Object.hasOwn(e,i))return;let n=pn(e[i],t);if(n===void 0)return;r[i]=n}return r}catch{return}}function Sn(e,t,n){return gn(e,t.scale,n)}function Cn(e,t,n){return _n(e,t.scale,n)}const wn={pg:{precision:1e3,scale:1e3},mysql:{precision:65,scale:30,sum:65},sqlite:{precision:18,scale:18,sum:18}};function Tn(e,t){let n=wn[e],{precision:r,scale:i}=t,a=jn(t);return r>n.precision?`${a} exceeds max precision ${n.precision}`:i>n.scale?`${a} exceeds max scale ${n.scale}`:n.sum!==void 0&&r+i>n.sum?`${a} requires precision + scale <= ${n.sum}`:void 0}function En(e,{precision:t,scale:n}){return e===`sqlite`?`INTEGER`:`${e===`pg`?`NUMERIC`:`DECIMAL`}(${t},${n})`}function Dn(e,t,n){let{scale:r}=n;if(e===`sqlite`)return Y(t,r);let i=t.indexOf(`.`);return r===0?i===-1?t:t.slice(0,i):i===-1?`${t}.${`0`.repeat(r)}`:t.padEnd(i+1+r,`0`)}function On(e,t,n){return e===`pg`?`{${t.map(e=>Dn(`pg`,e,n)).join(`,`)}}`:kn(t,n.scale)}function kn(e,t){return JSON.stringify(e.map(e=>Y(e,t)))}function An(e,t,n){if(!c(e))return;let r;try{r=JSON.parse(e)}catch{return}if(!Array.isArray(r))return;let i=Array(r.length);for(let[e,a]of r.entries()){let r=un(a,t,n);if(r===void 0)return;i[e]=r}return i}function jn(e){return`precision ${e.precision}, scale ${e.scale}`}const Mn=/^-?\d+$/;function Nn(e,t,n){let r=Pn(e),i=Pn(t);if(r===void 0||i===void 0||r<=0||i<0||i>r)return;let a={precision:r,scale:i};return Tn(n,a)===void 0?a:void 0}function Pn(e){let t=typeof e==`number`?e:c(e)&&Mn.test(e)?Number(e):NaN;return Number.isSafeInteger(t)?t:void 0}const Fn=new WeakSet,In=e=>Fn.has(e);function Ln(e,t){let n=o(e)&&!(`~standard`in e)?null:e[`~standard`].validate,r=()=>n||(n=e()[`~standard`].validate,n),i=K(`optional`,e=>e===void 0?U(t===void 0?void 0:o(t)?t():t):r()(e));return t===void 0&&Fn.add(i[`~standard`].validate),i.wrapped=e,i.default=t,i.acceptsUndefined=!0,i}let X;const Rn=(e,t)=>e!==void 0&&X?.(e,t)===!0,zn=(e,t)=>{let n=e===void 0?void 0:X?.(e,t);return typeof n==`function`?n:void 0};function Bn(e,t){let n=X;X=n?(t,r)=>e(t,r)||n(t,r):e;try{return t()}finally{X=n}}const Vn=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected object`})])}),Z=Object.freeze([]),Hn=Object.freeze(new Map),Un=Symbol(`unread`);function Wn(e,t={}){let{partial:n=!0,strict:r=!0,atLeast:i,requiresOneOf:a,requiresOneOfKeySets:c,omit:l,nonEmpty:u,refuse:d,provides:f}=t,p=Z,m=Hn,h=Z,g,_,v=Z,y=Z,b=null,x,ee,S=()=>{S=void 0;let t=l?new Set(l):null,r=Object.keys(e).filter(e=>!t?.has(e)),s=i?new Set(i):null,u=new Map,d=Array(r.length),f=n&&!s,C=a?.filter(e=>!e.some(e=>t?.has(e))),w=c?.filter(e=>!e.some(e=>e.some(e=>t?.has(e)))),T=f?[]:void 0,E=f?void 0:Array(r.length);p=r,m=u,h=d,g=C,_=w,v=T??Z,y=E??Z,b=!f&&n&&s?r.map(e=>s.has(e)):null;for(let t=0;t<r.length;t++){let n=r[t];u.set(n,t);let i=e[n],a=o(i)?i():i;d[t]=a[`~standard`].validate;let s=a.acceptsUndefined===!0;T?s&&!Gn(a)&&T.push(t):E[t]=s}let D=new Map,O=e=>{D.has(e)||D.set(e,D.size)};for(let e of C??Z)for(let t of e)O(t);for(let e of w??Z)for(let t of e)for(let e of t)O(e);for(let e of v)O(r[e]);D.size>0&&(x=Array(D.size).fill(Un),ee=D)},C=(e,t,n)=>{let r=n?ee.get(t):void 0;if(r===void 0)return e[t];let i=n[r];return i===Un?n[r]=e[t]:i},w=u===!0||a||c?(e,t)=>{if(u===!0){let t=!1;for(let n in e){t=!0;break}if(!t)return[{message:`Object cannot be empty`}]}for(let n of g??Z)if(!n.some(n=>C(e,n,t)!==void 0))return[{message:`Missing required field: one of ${n.join(`, `)}`}];for(let n of _??Z)if(!n.some(n=>n.every(n=>C(e,n,t)!==void 0||Rn(f,n))))return[{message:`Missing required fields: one of ${n.map(e=>e.join(`, `)).join(` or `)}`}]}:void 0,T=(e,t)=>{let n=r?qn(e,m,f):void 0;if(n&&!V())return n;let i=w?.(e,t);return i?Q(n,i):n},E=(e,t)=>{if(e)return{issues:e};let n=d?.(t);return n?{issues:[typeof n==`string`?{message:n}:n]}:{value:t}},D=(e,t)=>({issues:(r?qn(e,m,f):void 0)??t});return n&&!i?e=>{if(!s(e))return Vn;let t=e;S?.();let n=x?.slice(),i=V(),a=i?T(t,n):w?.(t,n);if(a&&!i)return D(t,a);let o={};for(let e in t){let s=m.get(e),c=s===void 0?zn(f,e):h[s];if(c===void 0){if(r&&!i)return{issues:[Kn(e)]};continue}let l=C(t,e,n);if(l===void 0)continue;let u=c(l);if(u.issues){let n=H(e,u.issues);if(!i)return D(t,n);a=Q(a,n);continue}u.value!==void 0&&(o[e]=u.value)}for(let e of v){let r=p[e];if(C(t,r,n)!==void 0)continue;let s=h[e](void 0);if(s.issues){if(a=Q(a,H(r,s.issues)),!i)return{issues:a};continue}s.value!==void 0&&(o[r]=s.value)}return E(a,o)}:e=>{if(!s(e))return Vn;let t=e;S?.();let r=x?.slice(),i=V(),a=T(t,r);if(a&&!i)return{issues:a};let o={};for(let e=0;e<p.length;e++){let s=p[e],c=C(t,s,r);if(c===void 0){if(Rn(f,s)){o[s]=void 0;continue}if((!n||b?.[e]===!0)&&!y[e]){if(a=Q(a,[{message:`Missing required field: ${s}`,path:[s]}]),!i)return{issues:a};continue}if(!y[e]){o[s]=void 0;continue}}let l=h[e](c);if(l.issues){if(a=Q(a,H(s,l.issues)),!i)return{issues:a};continue}o[s]=l.value}return E(a,o)}}function Gn(e){return In(e[`~standard`].validate)}function Q(e,t){return e?(e.push(...t),e):t}const Kn=e=>({message:`Unknown key: ${e}`,path:[e]});function qn(e,t,n){let r;for(let i in e)if(!(t.has(i)||zn(n,i))&&((r??=[]).push(Kn(i)),!V()))break;return r}function Jn(e,t){let{default:n,optional:r,nullable:i,array:a,transform:s}=t??{},c=Wn(e,t),l=kt(s?Mt(c,s):c,a,i,r);if(r===!0&&n!==void 0){let e=l,t=o(n)?n:()=>n;l=n=>n===void 0?U(t()):e(n)}return Object.assign(K(`object`,l),{entries:e,options:t,acceptsUndefined:r===!0||n!==void 0,extend:n=>Jn({...e,...n},t)})}const Yn=-621672192e5,Xn=0xe677d21fdbff;function Zn(e){return Number.isInteger(e)&&e>=Yn&&e<=Xn}function Qn(e,t,n){if(!(Number.isInteger(e)&&Number.isInteger(t)&&Number.isInteger(n))||t<1||t>12||n<1)return!1;let r=31;return t===2?r=er(e)?29:28:(t===4||t===6||t===9||t===11)&&(r=30),n<=r}function $n(e,t,n){return Number.isInteger(e)&&Number.isInteger(t)&&Number.isInteger(n)&&e>=0&&e<=23&&t>=0&&t<=59&&n>=0&&n<=59}function er(e){return e%4==0&&(e%100!=0||e%400==0)}const tr=z(`Expected finite number`);function nr(e){return a(e)&&Number.isFinite(e)?U(e):tr}function rr(e){return G(`number`,nr,e)}const ir=z(`Expected integer`),ar=z(`Expected safe integer`);function or(e){return a(e)&&Number.isInteger(e)?Number.isSafeInteger(e)?U(e):ar:ir}function sr(e){return G(`integer`,or,e)}function cr(e,t,n){return K(`number`,r=>{let i=nr(r);return i.issues?i:i.value<t||i.value>n?R(`${e} must be between ${t} and ${n}`):U(Object.is(i.value,-0)?0:i.value)})}const lr=cr(`Longitude`,g,180),ur=cr(`Latitude`,-90,90),dr=Jn({[h[0]]:lr,[h[1]]:ur},{partial:!1});function fr(e){let t=Pt(dr,e);if(t.issues)return t;let{longitude:n,latitude:r}=t.value;return U({longitude:n===g?180:n,latitude:r})}const pr=/^[a-zA-Z_][a-zA-Z0-9_]*$/,mr=new Set(Object.getOwnPropertyNames(Object.prototype)),hr=63;function gr(e){return typeof e==`string`&&e.length<=63&&pr.test(e)&&!mr.has(e)}const _r={postgresql:63,mysql:64},vr={postgresql:`PostgreSQL`,mysql:`MySQL`},yr=new Set([`information_schema`,`mysql`,`performance_schema`,`sys`,`ndbinfo`]);function $(e,t){throw new r(`The "namespace" option ${t} (${vr[e]}).`)}function br(e,t){typeof e!=`string`&&$(t,`must be a string (got "${typeof e}")`);let n=_r[t];return e.length>n&&$(t,`exceeds ${n} chars (${e.length})`),pr.test(e)||$(t,`invalid identifier ${JSON.stringify(e)}`),mr.has(e)&&$(t,`cannot be Object.prototype key ${JSON.stringify(e)}`),t===`postgresql`?((e===`information_schema`||e.startsWith(`pg_`))&&$(t,`cannot be system schema ${JSON.stringify(e)}`),e):(yr.has(e.toLowerCase())&&$(t,`cannot be system database ${JSON.stringify(e)}`),e)}const xr=[`pg`,`mysql`,`sqlite`],Sr=e=>`db`in e;function Cr(e,t){if(e!==void 0)return Sr(e)?e.db===t?e:void 0:e[t]}const wr=e=>t=>({db:e,type:t}),Tr=(e,t)=>n=>({db:e,type:`${t}(${n})`}),Er=(e,t)=>n=>({db:e,type:n===void 0?t:`${t}(${n})`}),Dr=(()=>{let e=wr(`pg`),t=e=>Tr(`pg`,e),n=e=>Er(`pg`,e);return{STRING:{TEXT:e(`text`),VARCHAR:t(`varchar`),CHAR:t(`char`),CITEXT:e(`citext`),UUID:e(`uuid`),BIT:t(`bit`),VARBIT:e=>({db:`pg`,type:e?`varbit(${e})`:`varbit`}),XML:e(`xml`),INET:e(`inet`),CIDR:e(`cidr`),MACADDR:e(`macaddr`),MACADDR8:e(`macaddr8`),TSVECTOR:e(`tsvector`),TSQUERY:e(`tsquery`)},INT:{SMALLINT:e(`smallint`),INTEGER:e(`integer`),OID:e(`oid`)},BIGINT:{BIGINT:e(`bigint`)},FLOAT:{REAL:e(`real`),DOUBLE_PRECISION:e(`double precision`)},BOOLEAN:{BOOLEAN:e(`boolean`)},DATETIME:{TIMESTAMP:n(`timestamp`),TIMESTAMPTZ:n(`timestamptz`),DATE:e(`date`),TIME:n(`time`),TIMETZ:n(`timetz`)},JSON:{JSON:e(`json`),JSONB:e(`jsonb`)},BLOB:{BYTEA:e(`bytea`)}}})(),Or=(()=>{let e=wr(`mysql`),t=e=>Tr(`mysql`,e),n=e=>Er(`mysql`,e);return{STRING:{VARCHAR:t(`VARCHAR`),CHAR:t(`CHAR`),TEXT:e(`TEXT`),TINYTEXT:e(`TINYTEXT`),MEDIUMTEXT:e(`MEDIUMTEXT`),LONGTEXT:e(`LONGTEXT`),BIT:t(`BIT`)},INT:{TINYINT:e(`TINYINT`),TINYINT_UNSIGNED:e(`TINYINT UNSIGNED`),SMALLINT:e(`SMALLINT`),SMALLINT_UNSIGNED:e(`SMALLINT UNSIGNED`),MEDIUMINT:e(`MEDIUMINT`),MEDIUMINT_UNSIGNED:e(`MEDIUMINT UNSIGNED`),INT:e(`INT`),INT_UNSIGNED:e(`INT UNSIGNED`),YEAR:e(`YEAR`)},BIGINT:{BIGINT:e(`BIGINT`),BIGINT_UNSIGNED:e(`BIGINT UNSIGNED`)},FLOAT:{FLOAT:e(`FLOAT`),DOUBLE:e(`DOUBLE`)},BOOLEAN:{TINYINT:e(`TINYINT(1)`)},DATETIME:{DATETIME:n(`DATETIME`),TIMESTAMP:n(`TIMESTAMP`),DATE:e(`DATE`),TIME:n(`TIME`)},JSON:{JSON:e(`JSON`)},BLOB:{BLOB:e(`BLOB`),TINYBLOB:e(`TINYBLOB`),MEDIUMBLOB:e(`MEDIUMBLOB`),LONGBLOB:e(`LONGBLOB`),BINARY:t(`BINARY`),VARBINARY:t(`VARBINARY`)}}})(),kr=(()=>{let e=wr(`sqlite`);return{STRING:{TEXT:e(`TEXT`)},INT:{INTEGER:e(`INTEGER`)},BIGINT:{INTEGER:e(`INTEGER`)},FLOAT:{REAL:e(`REAL`)},BOOLEAN:{INTEGER:e(`INTEGER`)},DATETIME:{TEXT:e(`TEXT`),REAL:e(`REAL`),INTEGER:e(`INTEGER`)},JSON:{TEXT:e(`TEXT`)},BLOB:{BLOB:e(`BLOB`)}}})();export{ht as $,xn as A,be as At,rn as B,v as Bt,Bn as C,se as Ct,Dn as D,N as Dt,En as E,D as Et,bn as F,Se as Ft,en as G,Ut as H,g as Ht,sn as I,_e as It,K as J,nn as K,yn as L,ve as Lt,jn as M,Te as Mt,Tn as N,de as Nt,On as O,Ee as Ot,hn as P,M as Pt,U as Q,Cn as R,E as Rt,Jn as S,oe as St,an as T,te as Tt,Qt as U,x as Ut,on as V,_ as Vt,q as W,m as Wt,z as X,R as Y,H as Z,Xn as _,je as _t,Sr as a,mt as at,Zn as b,ne as bt,gr as c,pt as ct,lr as d,st as dt,_t as et,fr as f,qe as ft,nr as g,Me as gt,or as h,Ge as ht,kr as i,Pt as it,Sn as j,fe as jt,vn as k,Ce as kt,br as l,ft as lt,rr as m,Ke as mt,xr as n,jt as nt,Cr as o,gt as ot,sr as p,Pe as pt,G as q,Dr as r,wt as rt,hr as s,dt as st,Or as t,Nt as tt,ur as u,lt as ut,Yn as v,Ne as vt,Ln as w,O as wt,Qn as x,ue as xt,$n as y,Oe as yt,Nn as z,y as zt};
|
|
2
|
+
//# sourceMappingURL=native-types-1ewJXVks.mjs.map
|