viborm 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/dist/{adapter-namespace-DMhEF6my.mjs → adapter-namespace-DqkJQdrD.mjs} +2 -2
- package/dist/{adapter-namespace-DMhEF6my.mjs.map → adapter-namespace-DqkJQdrD.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-D9FexFqy.mjs → array-literal-BsbbSLw3.mjs} +1 -1
- package/dist/{array-literal-D9FexFqy.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
- package/dist/base-AdXAoy6l.mjs +2 -0
- package/dist/base-AdXAoy6l.mjs.map +1 -0
- package/dist/batch-refs-4L8ECdPU.mjs +2 -0
- package/dist/batch-refs-4L8ECdPU.mjs.map +1 -0
- package/dist/bind-parameter-capacity-CjPgqnmx.mjs +2 -0
- package/dist/{bind-parameter-capacity-DzMcIB95.mjs.map → bind-parameter-capacity-CjPgqnmx.mjs.map} +1 -1
- package/dist/builder-Ycvq3ETg.mjs +2 -0
- package/dist/builder-Ycvq3ETg.mjs.map +1 -0
- package/dist/bun-sql.d.mts +19 -2
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +9 -8
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/bun-sqlite.mjs.map +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache/memory.mjs.map +1 -1
- package/dist/cache-BO57X0TT.mjs +2 -0
- package/dist/cache-BO57X0TT.mjs.map +1 -0
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/canonical-json-rfC2Dg0X.mjs +2 -0
- package/dist/canonical-json-rfC2Dg0X.mjs.map +1 -0
- package/dist/chain-Dh0FV72b.mjs +2 -0
- package/dist/chain-Dh0FV72b.mjs.map +1 -0
- package/dist/cli.mjs +5 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-BLiBmykn.mjs +2 -0
- package/dist/client-BLiBmykn.mjs.map +1 -0
- package/dist/client-CCgfcp5A.mjs +52 -0
- package/dist/client-CCgfcp5A.mjs.map +1 -0
- package/dist/client-CRBo95D0.d.mts +610 -0
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{clock-W8H2Khng.mjs → clock-CK41KO7t.mjs} +1 -1
- package/dist/{clock-W8H2Khng.mjs.map → clock-CK41KO7t.mjs.map} +1 -1
- package/dist/config.d.mts +3 -3
- package/dist/config.mjs +1 -1
- package/dist/controls-DXgIn4zh.mjs +2 -0
- package/dist/controls-DXgIn4zh.mjs.map +1 -0
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/datetime-physical-codec-oIhiYZEP.mjs +2 -0
- package/dist/datetime-physical-codec-oIhiYZEP.mjs.map +1 -0
- package/dist/driver-B19QlFqn.mjs +2 -0
- package/dist/{driver-CRaDT4B7.mjs.map → driver-B19QlFqn.mjs.map} +1 -1
- package/dist/driver-BlnKXPFF.mjs +2 -0
- package/dist/driver-BlnKXPFF.mjs.map +1 -0
- package/dist/driver.d.mts +2 -2
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-CnPCv1dm.mjs +2 -0
- package/dist/error-mapping-CnPCv1dm.mjs.map +1 -0
- package/dist/every-4KE0p2Gw.mjs +2 -0
- package/dist/every-4KE0p2Gw.mjs.map +1 -0
- package/dist/execution-context-BKR3bgES.mjs +2 -0
- package/dist/execution-context-BKR3bgES.mjs.map +1 -0
- package/dist/fs-estate-CAhDg7nY.mjs +2 -0
- package/dist/fs-estate-CAhDg7nY.mjs.map +1 -0
- package/dist/{geo-area-codec-B4DRInvA.mjs → geo-area-codec-1SY9im7O.mjs} +2 -2
- package/dist/{geo-area-codec-B4DRInvA.mjs.map → geo-area-codec-1SY9im7O.mjs.map} +1 -1
- package/dist/geo-point-codec-lhxH42SK.mjs +2 -0
- package/dist/geo-point-codec-lhxH42SK.mjs.map +1 -0
- package/dist/{hydration-D6JICBQG.mjs → hydration-CAxOL4aI.mjs} +2 -2
- package/dist/{hydration-D6JICBQG.mjs.map → hydration-CAxOL4aI.mjs.map} +1 -1
- package/dist/identifier-conversion-GgbwHc2G.mjs +2 -0
- package/dist/identifier-conversion-GgbwHc2G.mjs.map +1 -0
- package/dist/{identifier-EsWKVHXi.mjs → identifier-hQCs8M1n.mjs} +2 -2
- package/dist/{identifier-EsWKVHXi.mjs.map → identifier-hQCs8M1n.mjs.map} +1 -1
- package/dist/identity-CLFhCTZx.mjs +2 -0
- package/dist/identity-CLFhCTZx.mjs.map +1 -0
- package/dist/{index-T0YKKw66.d.mts → index-C_XLSTy2.d.mts} +723 -400
- package/dist/index.d.mts +2 -2
- 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/{invariant-DCsftyml.mjs → invariant-BnLYqsHO.mjs} +1 -1
- package/dist/{invariant-DCsftyml.mjs.map → invariant-BnLYqsHO.mjs.map} +1 -1
- package/dist/{json-number-C10HFiy6.mjs → json-number-CGXpPu4D.mjs} +1 -1
- package/dist/{json-number-C10HFiy6.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
- package/dist/key-BeoOwGr3.mjs +2 -0
- package/dist/key-BeoOwGr3.mjs.map +1 -0
- package/dist/libsql-Bu_IdFU1.mjs +11 -0
- package/dist/libsql-Bu_IdFU1.mjs.map +1 -0
- package/dist/libsql.d.mts +8 -3
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/memory-D4yxtCPK.mjs +2 -0
- package/dist/memory-D4yxtCPK.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +6 -0
- package/dist/migrations/mysql.mjs +2 -0
- package/dist/migrations/mysql.mjs.map +1 -0
- package/dist/migrations/postgres.d.mts +6 -0
- package/dist/migrations/postgres.mjs +2 -0
- package/dist/migrations/postgres.mjs.map +1 -0
- package/dist/migrations/sqlite.d.mts +6 -0
- package/dist/migrations/sqlite.mjs +2 -0
- package/dist/migrations/sqlite.mjs.map +1 -0
- package/dist/migrations/storage/durable-object.d.mts +17 -0
- package/dist/migrations/storage/durable-object.mjs +2 -0
- package/dist/migrations/storage/durable-object.mjs.map +1 -0
- package/dist/migrations/storage/fs.d.mts +6 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +14 -0
- package/dist/migrations/storage/r2.mjs +2 -0
- package/dist/migrations/storage/r2.mjs.map +1 -0
- package/dist/migrations/tenant.d.mts +92 -0
- package/dist/migrations/tenant.mjs +2 -0
- package/dist/migrations/tenant.mjs.map +1 -0
- package/dist/{migrations-BWZSBMZh.mjs → migrations-DTObIjAm.mjs} +2 -2
- package/dist/migrations-DTObIjAm.mjs.map +1 -0
- package/dist/migrations.d.mts +6 -559
- package/dist/migrations.mjs +1 -1
- package/dist/migrations.mjs.map +1 -1
- package/dist/mysql-CibPaHSp.mjs +99 -0
- package/dist/mysql-CibPaHSp.mjs.map +1 -0
- package/dist/mysql-adapter-DkJPfoGf.mjs +2 -0
- package/dist/mysql-adapter-DkJPfoGf.mjs.map +1 -0
- package/dist/mysql2.d.mts +1 -3
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- 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/object-store-DQR6bTBY.mjs +2 -0
- package/dist/object-store-DQR6bTBY.mjs.map +1 -0
- package/dist/object-store-DyYOCtmX.d.mts +156 -0
- package/dist/observation-DUSm7oXK.mjs +2 -0
- package/dist/observation-DUSm7oXK.mjs.map +1 -0
- package/dist/pg.d.mts +37 -12
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +2 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/physical-6V_LNU3L.mjs +2 -0
- package/dist/{physical-BkelResN.mjs.map → physical-6V_LNU3L.mjs.map} +1 -1
- package/dist/pinned-session-CLxj5M5e.mjs +2 -0
- package/dist/pinned-session-CLxj5M5e.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-B11VjIin.d.mts → planner-C6Lfsasx.d.mts} +57 -3
- package/dist/postgres-adapter-B3SQvcV1.mjs +2 -0
- package/dist/postgres-adapter-B3SQvcV1.mjs.map +1 -0
- package/dist/postgres-adapter-CQD2oGuD.mjs +2 -0
- package/dist/postgres-adapter-CQD2oGuD.mjs.map +1 -0
- package/dist/postgres-oqNW9xqo.mjs +415 -0
- package/dist/postgres-oqNW9xqo.mjs.map +1 -0
- package/dist/{postgres-result-Dc_iW3Hb.mjs → postgres-result-7F0DllQe.mjs} +2 -2
- package/dist/{postgres-result-Dc_iW3Hb.mjs.map → postgres-result-7F0DllQe.mjs.map} +1 -1
- package/dist/postgres.d.mts +11 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/provider-limits-BHATED_m.mjs +2 -0
- package/dist/provider-limits-BHATED_m.mjs.map +1 -0
- package/dist/registration-preflight-DEjv050M.mjs +4 -0
- package/dist/registration-preflight-DEjv050M.mjs.map +1 -0
- package/dist/result-shape-CTNdNSW3.mjs +2 -0
- package/dist/result-shape-CTNdNSW3.mjs.map +1 -0
- package/dist/scalar-U0wD5bKy.mjs +2 -0
- package/dist/{scalar-BTktMqvO.mjs.map → scalar-U0wD5bKy.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema/json.mjs.map +1 -1
- package/dist/schema-Cjem1-0f.mjs +2 -0
- package/dist/{schema-BFNcMdO6.mjs.map → schema-Cjem1-0f.mjs.map} +1 -1
- package/dist/schema-introspection-DEYGC2qg.mjs +6 -0
- package/dist/schema-introspection-DEYGC2qg.mjs.map +1 -0
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-BgqlrePH.mjs → select-assembly-f1UGoblh.mjs} +2 -2
- package/dist/select-assembly-f1UGoblh.mjs.map +1 -0
- package/dist/settle-B9Vg1FnP.mjs +2 -0
- package/dist/settle-B9Vg1FnP.mjs.map +1 -0
- package/dist/soft-delete.d.mts +1 -1
- package/dist/{sql--69HUgel.mjs → sql-Bp7jicEX.mjs} +1 -1
- package/dist/{sql--69HUgel.mjs.map → sql-Bp7jicEX.mjs.map} +1 -1
- package/dist/{sql-statement-tokens-CykxFmOJ.mjs → sql-statement-tokens-BBcoGmJb.mjs} +1 -1
- package/dist/{sql-statement-tokens-CykxFmOJ.mjs.map → sql-statement-tokens-BBcoGmJb.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-CW_3l6ea.mjs +2 -0
- package/dist/sqlite-adapter-CW_3l6ea.mjs.map +1 -0
- package/dist/sqlite-utils-DlgokMJN.mjs +2 -0
- package/dist/sqlite-utils-DlgokMJN.mjs.map +1 -0
- package/dist/sqlite3.d.mts +2 -8
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/standard-sql-Bk4RZPqJ.mjs +6 -0
- package/dist/standard-sql-Bk4RZPqJ.mjs.map +1 -0
- package/dist/{suppressed-failure-BPxfHTMc.mjs → suppressed-failure-BwULh-8h.mjs} +1 -1
- package/dist/{suppressed-failure-BPxfHTMc.mjs.map → suppressed-failure-BwULh-8h.mjs.map} +1 -1
- package/dist/{terminal-BbRi0CNZ.mjs → terminal-C8cq1WWX.mjs} +2 -2
- package/dist/{terminal-BbRi0CNZ.mjs.map → terminal-C8cq1WWX.mjs.map} +1 -1
- package/dist/{transaction-oskVwmsf.mjs → transaction-Bnl6ULTw.mjs} +2 -2
- package/dist/transaction-Bnl6ULTw.mjs.map +1 -0
- package/dist/{transaction-operation-BC7aua5V.mjs → transaction-operation-CKK3l_9x.mjs} +2 -2
- package/dist/transaction-operation-CKK3l_9x.mjs.map +1 -0
- package/dist/{utils-DfztpPvR.mjs → utils-CZNaOZR7.mjs} +4 -3
- package/dist/utils-CZNaOZR7.mjs.map +1 -0
- package/dist/v-D5Z06FKN.mjs +2 -0
- package/dist/v-D5Z06FKN.mjs.map +1 -0
- package/dist/validation-Dk9Q_-C7.mjs +2 -0
- package/dist/validation-Dk9Q_-C7.mjs.map +1 -0
- package/dist/validation-PF9-_nKd.mjs +2 -0
- package/dist/{validation-tgjL_9n8.mjs.map → validation-PF9-_nKd.mjs.map} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-X9-bwtRo.mjs +2 -0
- package/dist/{validator-DMlEScV3.mjs.map → validator-X9-bwtRo.mjs.map} +1 -1
- package/dist/value-guards-CK9guf2Z.mjs +2 -0
- package/dist/value-guards-CK9guf2Z.mjs.map +1 -0
- package/dist/version-JDaZht4U.mjs +2 -0
- package/dist/{version-Cr80LFvx.mjs.map → version-JDaZht4U.mjs.map} +1 -1
- package/package.json +75 -34
- package/dist/base-vfur-DaU.mjs +0 -2
- package/dist/base-vfur-DaU.mjs.map +0 -1
- package/dist/batch-refs-BY51FIXm.mjs +0 -6
- package/dist/batch-refs-BY51FIXm.mjs.map +0 -1
- package/dist/bind-parameter-capacity-DzMcIB95.mjs +0 -2
- package/dist/builder-bPfagDQV.mjs +0 -2
- package/dist/builder-bPfagDQV.mjs.map +0 -1
- package/dist/chain-uIFlkkXS.mjs +0 -2
- package/dist/chain-uIFlkkXS.mjs.map +0 -1
- package/dist/client-NleI4Nm-.mjs +0 -434
- package/dist/client-NleI4Nm-.mjs.map +0 -1
- package/dist/client-tjSMPjeZ.mjs +0 -2
- package/dist/client-tjSMPjeZ.mjs.map +0 -1
- package/dist/controls-BhxRnPYS.mjs +0 -2
- package/dist/controls-BhxRnPYS.mjs.map +0 -1
- package/dist/decimal-12NERGYZ.mjs +0 -3
- package/dist/decimal-12NERGYZ.mjs.map +0 -1
- package/dist/driver-CRaDT4B7.mjs +0 -2
- package/dist/driver-options-DxlB1tms.mjs +0 -2
- package/dist/driver-options-DxlB1tms.mjs.map +0 -1
- package/dist/driver-yCYqzIQg.mjs +0 -2
- package/dist/driver-yCYqzIQg.mjs.map +0 -1
- package/dist/error-mapping-BWzb-l02.mjs +0 -2
- package/dist/error-mapping-BWzb-l02.mjs.map +0 -1
- package/dist/execution-context-BPk0YLhd.mjs +0 -2
- package/dist/execution-context-BPk0YLhd.mjs.map +0 -1
- package/dist/fs-estate-3Bu_K9mk.d.mts +0 -7
- package/dist/fs-estate-BcjgY4iY.mjs +0 -2
- package/dist/fs-estate-BcjgY4iY.mjs.map +0 -1
- package/dist/geo-point-codec-DUTTtlav.mjs +0 -2
- package/dist/geo-point-codec-DUTTtlav.mjs.map +0 -1
- package/dist/identifiers-By-JRCb5.mjs +0 -2
- package/dist/identifiers-By-JRCb5.mjs.map +0 -1
- package/dist/key-DKaqPb8w.mjs +0 -2
- package/dist/key-DKaqPb8w.mjs.map +0 -1
- package/dist/migrations-BWZSBMZh.mjs.map +0 -1
- package/dist/mysql-adapter-D9FoHlWE.mjs +0 -2
- package/dist/mysql-adapter-D9FoHlWE.mjs.map +0 -1
- package/dist/observation-CLp8ylmL.mjs +0 -2
- package/dist/observation-CLp8ylmL.mjs.map +0 -1
- package/dist/physical-BkelResN.mjs +0 -2
- package/dist/pinned-session-Ca7C9yxY.mjs +0 -2
- package/dist/pinned-session-Ca7C9yxY.mjs.map +0 -1
- package/dist/postgres-adapter-T2Iko-vt.mjs +0 -2
- package/dist/postgres-adapter-T2Iko-vt.mjs.map +0 -1
- package/dist/registration-preflight-BrA3EWvq.mjs +0 -4
- package/dist/registration-preflight-BrA3EWvq.mjs.map +0 -1
- package/dist/result-shape-DKTu8yre.mjs +0 -2
- package/dist/result-shape-DKTu8yre.mjs.map +0 -1
- package/dist/scalar-BTktMqvO.mjs +0 -2
- package/dist/schema-BFNcMdO6.mjs +0 -2
- package/dist/schema-introspection-DsXPfCst.mjs +0 -6
- package/dist/schema-introspection-DsXPfCst.mjs.map +0 -1
- package/dist/select-assembly-BgqlrePH.mjs.map +0 -1
- package/dist/sqlite-adapter-HqO3GpAK.mjs +0 -2
- package/dist/sqlite-adapter-HqO3GpAK.mjs.map +0 -1
- package/dist/sqlite-utils-D26BFuJJ.mjs +0 -2
- package/dist/sqlite-utils-D26BFuJJ.mjs.map +0 -1
- package/dist/transaction-operation-BC7aua5V.mjs.map +0 -1
- package/dist/transaction-oskVwmsf.mjs.map +0 -1
- package/dist/transactions-gjmrWN5W.mjs +0 -2
- package/dist/transactions-gjmrWN5W.mjs.map +0 -1
- package/dist/utils-DfztpPvR.mjs.map +0 -1
- package/dist/v-B2WwtcRz.mjs +0 -2
- package/dist/v-B2WwtcRz.mjs.map +0 -1
- package/dist/validation-Du6j0Q38.mjs +0 -2
- package/dist/validation-Du6j0Q38.mjs.map +0 -1
- package/dist/validation-tgjL_9n8.mjs +0 -2
- package/dist/validator-DMlEScV3.mjs +0 -2
- package/dist/version-Cr80LFvx.mjs +0 -2
- /package/dist/{contract-BHUOUAZ-.d.mts → contract-CIIqgFyb.d.mts} +0 -0
- /package/dist/{sql--yhoVvRM.d.mts → sql-BvfwUKIh.d.mts} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"key-DKaqPb8w.mjs","names":[],"sources":["../src/cache/key.ts"],"sourcesContent":["/**\n * Cache Key Generation\n *\n * Generates deterministic cache keys from operation parameters.\n */\n\nimport { CacheInvalidKeyError } from \"@errors\";\nimport { fieldRefPayload, isFieldRef } from \"@schema/field-ref\";\nimport { isJsonNullSentinel } from \"@schema/json-null\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\nimport { isSql } from \"@sql\";\n\n/**\n * Prefix for all VibORM cache keys\n */\nexport const CACHE_PREFIX = \"viborm\";\n\n/** Namespace root reserved for authenticated official cache extensions. */\nexport const OFFICIAL_CACHE_NAMESPACE_ROOT = `${CACHE_PREFIX}:cache`;\n\n/**\n * Private storage-format revision. It moved r1 → r2 when the SQL namespace and\n * dialect entered the derivation below: every r1 entry keyed a scope that made\n * no claim about which schema or database produced the rows, so no r1 entry may\n * ever be served to an r2 reader. The bump is the invalidation.\n *\n * It moved r2 → r3 when a decimal became a value object. An r2 entry stored a\n * decimal's canonical text and MATERIALIZED it as that same string, which is\n * what an r2 reader's caller was handed; an r3 reader rebuilds a `Decimal` from\n * the identical bytes. The stored bytes did not change — their MEANING did, and\n * a reader that served the old bytes under the new contract would hand one\n * client a string where every other read gives it a value object. Same rule as\n * before: the bump is the invalidation.\n */\n// r4 entries carry their full canonical identity, checked before materialization.\nconst OFFICIAL_CACHE_SNAPSHOT_REVISION = \"r4\";\n\n/**\n * The facts one official cache scope partitions on.\n *\n * `dialect` is load-bearing on its own: a PostgreSQL schema `billing` and a\n * MySQL database `billing` are different stores that spell their qualifier the\n * same way. `namespace` is `undefined` for exactly the families the feature\n * leaves unqualified — SQLite and unbound MySQL/PlanetScale — and that absence\n * is encoded as its own token, never as text that a real namespace could spell.\n */\nexport interface OfficialCacheScopeFacts {\n readonly version: string | number | undefined;\n readonly dialect: string;\n readonly namespace: string | undefined;\n}\n\n/**\n * Encode text as fixed-width hex per UTF-16 code unit.\n *\n * Fixed width is what makes the joined namespace INJECTIVE: every component\n * below is either a bare discriminator letter or `<letter>:<hex>`, hex never\n * contains the `:` separator, and no variable-length body can absorb the\n * component after it. Two different fact tuples therefore cannot produce one\n * namespace, which is the whole isolation guarantee.\n */\nfunction encodeText(value: string): string {\n let encoded = \"\";\n for (let index = 0; index < value.length; index += 1) {\n encoded += value.charCodeAt(index).toString(16).padStart(4, \"0\");\n }\n return encoded;\n}\n\n/** `u` unversioned, `n:<f64 hex>` numeric, `s:<hex>` string. */\nfunction encodeVersion(version: string | number | undefined): string {\n if (version === undefined) return \"u\";\n if (typeof version === \"number\") {\n const bytes = new Uint8Array(8);\n new DataView(bytes.buffer).setFloat64(0, version, false);\n let encoded = \"\";\n for (const byte of bytes) encoded += byte.toString(16).padStart(2, \"0\");\n return `n:${encoded}`;\n }\n return `s:${encodeText(version)}`;\n}\n\n/**\n * `x` unknown, `k:<hex>` known.\n *\n * An unknown namespace is a bare `x` with no body, so it cannot be reached by\n * encoding any string whatsoever — a database literally named `undefined`\n * encodes as `k:0075...`. Absence is a distinct value here, not a spelling.\n */\nfunction encodeNamespace(namespace: string | undefined): string {\n return namespace === undefined ? \"x\" : `k:${encodeText(namespace)}`;\n}\n\n/**\n * Build the private namespace for one client-bound official cache extension.\n *\n * Pure: the same facts always give the same string, which is why re-binding the\n * chain after another extension is appended retains the scope by value instead\n * of needing a registry to hand the old one back.\n */\nexport function createOfficialCacheNamespace(\n facts: OfficialCacheScopeFacts\n): string {\n return [\n OFFICIAL_CACHE_NAMESPACE_ROOT,\n OFFICIAL_CACHE_SNAPSHOT_REVISION,\n `d:${encodeText(facts.dialect)}`,\n encodeNamespace(facts.namespace),\n encodeVersion(facts.version),\n ].join(\":\");\n}\n\n/**\n * Build the versioned prefix\n */\nfunction buildPrefix(version?: string | number): string {\n return version !== undefined ? `${CACHE_PREFIX}:v${version}` : CACHE_PREFIX;\n}\n\n/**\n * Generate an unprefixed cache key (internal use)\n * Key structure: <model>:<operation>:<hash>\n */\nexport function generateUnprefixedCacheKey(\n modelName: string,\n operation: string,\n args: unknown\n): string {\n const argsHash = hashArgs(args);\n return `${modelName}:${operation}:${argsHash}`;\n}\n\n/** Hash for storage lookup, exact identity for collision verification. */\nexport function cacheLookupOf(\n model: string,\n operation: string,\n args: unknown\n): {\n readonly key: string;\n readonly identity: string;\n} {\n const serialized = stableStringify(args);\n return {\n key: `${model}:${operation}:${fastHash(serialized)}`,\n identity: JSON.stringify([model, operation, serialized]),\n };\n}\n\n/**\n * Generate a deterministic cache key from operation parameters\n *\n * Returns a FULLY PREFIXED key for external use (manual invalidation, etc.)\n *\n * Key structure: viborm[:v<version>]:<model>:<operation>:<hash>\n *\n * @example\n * generateCacheKey(\"user\", \"findMany\", { where: { active: true } })\n * // \"viborm:user:findMany:abc123...\"\n *\n * generateCacheKey(\"user\", \"findMany\", { where: { active: true } }, 2)\n * // \"viborm:v2:user:findMany:abc123...\"\n */\nexport function generateCacheKey(\n modelName: string,\n operation: string,\n args: unknown,\n version?: string | number\n): string {\n const prefix = buildPrefix(version);\n const argsHash = hashArgs(args);\n return `${prefix}:${modelName}:${operation}:${argsHash}`;\n}\n\n/**\n * Generate prefix for cache invalidation\n * Used to clear all cached queries for a model\n *\n * Returns a FULLY PREFIXED prefix for external use.\n */\nexport function generateCachePrefix(\n modelName?: string,\n version?: string | number\n): string {\n const prefix = buildPrefix(version);\n return modelName ? `${prefix}:${modelName}` : prefix;\n}\n\n/**\n * Generate a deterministic hash from query arguments\n */\nfunction hashArgs(args: unknown): string {\n const serialized = stableStringify(args);\n return fastHash(serialized);\n}\n\n/**\n * The two bytes that open and close a NON-JSON value's serialization: U+001F\n * (unit separator) and U+001E (record separator).\n *\n * They are what makes the token below UNFORGEABLE, and the reason is\n * mechanical: every string this serializer emits — operand values AND object\n * keys — goes through `JSON.stringify`, and JSON escapes every code point below\n * U+0020 into a printable six-character escape. A raw separator byte can\n * therefore never appear in the output by any route except the one deliberately\n * taken here, so a user document may spell the LETTERS of a token but never the\n * token. (Verified across the whole C0/C1 range, and for lone surrogates, by\n * the \"no JSON value can forge a brand token\" test.)\n */\nconst BRAND_OPEN = \"\\u001F\";\nconst BRAND_CLOSE = \"\\u001E\";\n\n/**\n * Serialize a value that is not a JSON value — one of the branded operand\n * tokens, or a scalar JSON cannot carry — into the reserved namespace.\n *\n * `namespace` names the KIND and `body` distinguishes two values of that kind;\n * the delimiters are balanced, so a token nested inside another token's body\n * (an `Sql` whose bound values hold a `Date`) stays unambiguous.\n */\nfunction brandToken(namespace: string, body: string): string {\n return `${BRAND_OPEN}viborm.${namespace}:${body}${BRAND_CLOSE}`;\n}\n\n/**\n * Stable JSON stringify that handles:\n * - Sorted object keys (deterministic)\n * - Date objects (ISO string)\n * - BigInt\n * - Uint8Array (base64)\n * - SQL fragments (statement text + bound values)\n * - Field references (the model and field they name)\n * - JSON null sentinels (`DbNull` / `JsonNull` / `AnyNull`)\n * - undefined values (omitted)\n * - Circular references (throws)\n *\n * It is only ever handed a VALIDATED payload (see\n * `PendingOperation.cacheKeyArgs`), so the non-JSON values it can meet are the\n * ones validation deliberately admits: a field reference, an SQL fragment, and\n * a JSON null sentinel. Admitted control values reach it only once\n * {@link isCanonicalKeyData} accepts them: in a read's key, and as the key of\n * the facts `rows` binds to a call's values (`extensions/rows.ts`).\n *\n * EVERY ONE OF THEM KEYS IN THE RESERVED NAMESPACE, because a user document is\n * allowed to look exactly like any of them. A JSON column takes an arbitrary\n * object, so `{ kind: \"DbNull\" }` is ordinary user data — and while the sentinel\n * carries `kind` as an own enumerable key precisely so a structural serializer\n * could tell the three apart, that only moved the collision one shape over:\n * walking `Object.keys` made `equals: DbNull` and `equals: { kind: \"DbNull\" }`\n * the same cache entry, and a cached client served one query's rows for the\n * other, in both directions, for the whole TTL.\n *\n * The sentinel is the one that collided in production spelling — a JSON filter\n * operand admits both a sentinel and an arbitrary document. The other two\n * cannot meet their look-alike at one position TODAY, and only because\n * validation holds those doors shut (`v.noFieldRef` refuses a reference\n * wherever arbitrary data is legal; `v.json` refuses a real `Sql` as\n * non-JSON-compatible) — while the fragment's look-alike still reached the\n * fragment branch and crashed there, see the note on it below. A key builder\n * that is correct only because a schema elsewhere is holding a door is one\n * refactor from being wrong again, so the rule here is structural instead:\n * what is not a JSON value does not serialize like one.\n */\nexport function stableStringify(\n value: unknown,\n seen = new WeakSet<object>()\n): string {\n if (value === null) return \"null\";\n if (value === undefined) return \"\";\n\n const type = typeof value;\n\n if (type === \"boolean\" || type === \"number\") {\n return String(value);\n }\n\n if (type === \"string\") {\n return JSON.stringify(value);\n }\n\n if (type === \"bigint\") {\n return brandToken(\"bigint\", String(value));\n }\n\n if (type !== \"object\") {\n // Functions and symbols are not cacheable\n throw new CacheInvalidKeyError(`Uncacheable value type: ${type}`);\n }\n\n // A fragment is identified by what it will EMIT, not by its instance fields:\n // an `Sql` memoizes its flattened text on first read, so enumerating its own\n // properties would key the same fragment differently depending on whether\n // anything had compiled it yet.\n //\n // THE METHOD IS PART OF THE TEST because `isSql` is a duck-type probe\n // (`strings` and `values`, both arrays), and a JSON column may legally hold\n // `{ strings: [], values: [] }` — validation says so in as many words\n // (`v.noFieldRef`: such a document \"is honest user data and must stay\n // accepted\"). That document reached here as a fragment and threw a bare\n // `TypeError: value.toStatement is not a function` out of cache key\n // generation. A real fragment carries the method that flattens it and a\n // document cannot, because `v.json` refuses a function; so the look-alike\n // falls through to the object branch below and keys as the data it is.\n if (isSql(value) && typeof value.toStatement === \"function\") {\n return brandToken(\n \"sql\",\n `${JSON.stringify(value.toStatement(\"?\"))}:${stableStringify(value.values, seen)}`\n );\n }\n\n // A reference names a COLUMN: the model and field are its identity, and its\n // `type`/`list` are derived from them by `createModelFieldRefs`.\n if (isFieldRef(value)) {\n const payload = fieldRefPayload(value);\n return brandToken(\n \"field-ref\",\n `${JSON.stringify(payload.model)}:${JSON.stringify(payload.field)}`\n );\n }\n\n if (isJsonNullSentinel(value)) {\n return brandToken(\"json-null\", value.kind);\n }\n\n if (value instanceof Date) {\n return brandToken(\"date\", value.toISOString());\n }\n\n if (value instanceof Uint8Array) {\n // Use Buffer in Node.js, btoa in browser/edge\n let base64: string;\n if (typeof Buffer !== \"undefined\") {\n base64 = Buffer.from(value).toString(\"base64\");\n } else {\n let binary = \"\";\n for (const byte of value) {\n binary += String.fromCharCode(byte);\n }\n base64 = btoa(binary);\n }\n return brandToken(\"bytes\", base64);\n }\n\n // `seen` holds the objects on the current PATH only, as in\n // {@link isCanonicalKeyData}: one object reached twice through different\n // keys (`{ a: ids, b: ids }`) is data, not a cycle.\n if (seen.has(value as object))\n throw new CacheInvalidKeyError(\"Circular reference in cache key args\");\n seen.add(value as object);\n let serialized: string;\n if (Array.isArray(value)) {\n serialized = `[${value.map((v) => stableStringify(v, seen)).join(\",\")}]`;\n } else {\n const obj = value as Record<string, unknown>;\n const pairs = Object.keys(obj)\n .sort()\n .filter((k) => obj[k] !== undefined)\n .map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k], seen)}`);\n serialized = `{${pairs.join(\",\")}}`;\n }\n seen.delete(value as object);\n return serialized;\n}\n\n/**\n * Whether {@link stableStringify} keys this value by its content: plain\n * records and arrays of JSON scalars, bigints, valid `Date`s and\n * `Uint8Array`s. A class instance would key as its own enumerable fields (a\n * `Map` as `{}`), a function or symbol throws, and a cycle throws; the caller\n * bypasses the cache for any of those rather than alias or fail. A value it\n * cannot inspect is not canonical either.\n */\nexport function isCanonicalKeyData(value: unknown): boolean {\n try {\n return hasCanonicalForm(value, new Set());\n } catch {\n return false;\n }\n}\n\nfunction hasCanonicalForm(value: unknown, seen: Set<object>): boolean {\n if (value === null) return true;\n switch (typeof value) {\n case \"string\":\n case \"boolean\":\n case \"bigint\":\n return true;\n case \"number\":\n return Number.isFinite(value);\n case \"object\":\n break;\n default:\n return false;\n }\n // The two instance kinds `stableStringify` brands, tested as it tests them.\n if (value instanceof Date) return !Number.isNaN(value.getTime());\n if (value instanceof Uint8Array) return true;\n if (seen.has(value)) return false;\n if (!(Array.isArray(value) || isPlainRecord(value))) return false;\n seen.add(value);\n const canonical = Object.values(value).every((entry) =>\n hasCanonicalForm(entry, seen)\n );\n seen.delete(value);\n return canonical;\n}\n\n/**\n * Fast non-cryptographic hash (djb2 variant)\n * Produces a 16-character hex string\n */\nfunction fastHash(str: string): string {\n let h1 = 0xde_ad_be_ef;\n let h2 = 0x41_c6_ce_57;\n\n for (let i = 0; i < str.length; i++) {\n const ch = str.charCodeAt(i);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash mixing requires 32-bit XOR.\n h1 = Math.imul(h1 ^ ch, 2_654_435_761);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash mixing requires 32-bit XOR.\n h2 = Math.imul(h2 ^ ch, 1_597_334_677);\n }\n\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2_246_822_507);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3_266_489_909);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2_246_822_507);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3_266_489_909);\n\n return (\n // biome-ignore lint/suspicious/noBitwiseOperators: Hex output requires unsigned 32-bit values.\n (h2 >>> 0).toString(16).padStart(8, \"0\") +\n // biome-ignore lint/suspicious/noBitwiseOperators: Hex output requires unsigned 32-bit values.\n (h1 >>> 0)\n .toString(16)\n .padStart(8, \"0\")\n );\n}\n"],"mappings":"gMAeA,MAAa,EAAe,SAGf,EAAgC,GAAG,EAAa,QA2C7D,SAAS,WAAW,EAAuB,CACzC,IAAI,EAAU,GACd,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAM,OAAQ,GAAS,EACjD,GAAW,EAAM,WAAW,EAAM,CAAC,SAAS,GAAG,CAAC,SAAS,EAAG,IAAI,CAElE,OAAO,EAIT,SAAS,cAAc,EAA8C,CACnE,GAAI,IAAY,IAAA,GAAW,MAAO,IAClC,GAAI,OAAO,GAAY,SAAU,CAC/B,IAAM,EAAQ,IAAI,WAA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AK,SACH,MAAO,GACT,IAAK,SACH,OAAO,OAAO,SAAS,EAAM,CAC/B,IAAK,SACH,MACF,QACE,MAAO,GAGX,GAAI,aAAiB,KAAM,MAAO,CAAC,OAAO,MAAM,EAAM,SAAS,CAAC,CAChE,GAAI,aAAiB,WAAY,MAAO,GAExC,GADI,EAAK,IAAI,EAAM,EACf,EAAE,MAAM,QAAQ,EAAM,EAAI,EAAc,EAAM,EAAG,MAAO,GAC5D,EAAK,IAAI,EAAM,CACf,IAAM,EAAY,OAAO,OAAO,EAAM,CAAC,MAAO,GAC5C,iBAAiB,EAAO,EAAK,CAC9B,CAED,OADA,EAAK,OAAO,EAAM,CACX,EAOT,SAAS,SAAS,EAAqB,CACrC,IAAI,EAAK,WACL,EAAK,WAET,IAAK,IAAI,EAAI,EAAG,EAAI,EAAI,OAAQ,IAAK,CACnC,IAAM,EAAK,EAAI,WAAW,EAAE,CAE5B,EAAK,KAAK,KAAK,EAAK,EAAI,WAAc,CAEtC,EAAK,KAAK,KAAK,EAAK,EAAI,WAAc,CAYxC,MARA,GAAK,KAAK,KAAK,EAAM,IAAO,GAAK,WAAc,CAE/C,GAAM,KAAK,KAAK,EAAM,IAAO,GAAK,WAAc,CAEhD,EAAK,KAAK,KAAK,EAAM,IAAO,GAAK,WAAc,CAE/C,GAAM,KAAK,KAAK,EAAM,IAAO,GAAK,WAAc,EAI7C,IAAO,GAAG,SAAS,GAAG,CAAC,SAAS,EAAG,IAAI,EAEvC,IAAO,GACL,SAAS,GAAG,CACZ,SAAS,EAAG,IAAI"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"migrations-BWZSBMZh.mjs","names":[],"sources":["../src/errors/migrations.ts"],"sourcesContent":["import { VibORMError, VibORMErrorCode, type VibORMErrorMeta } from \"./base\";\n\n/**\n * Migration error metadata\n */\nexport interface MigrationErrorMeta extends VibORMErrorMeta {\n /** Name of the migration */\n migrationName?: string;\n /** Expected checksum (from database) */\n expectedChecksum?: string;\n /** Actual checksum (from file) */\n actualChecksum?: string;\n /** Migration index */\n migrationIndex?: number;\n /** Directory path */\n migrationsDir?: string;\n /** Last confirmed dispatch or step identity */\n lastConfirmedStep?: string;\n /** Estate digest involved in the refusal */\n estateHash?: string;\n /** State digest involved in the refusal */\n stateId?: string;\n /** Push plan digest involved in the refusal */\n planHash?: string;\n /** Honest effect classification after a non-transactional failure */\n effectState?: \"none\" | \"committed\" | \"partial\" | \"may-have-committed\";\n /** True when some provider work may already have committed */\n partial?: boolean;\n}\n\n/**\n * Every code {@link MigrationError} can carry.\n *\n * The `MIGRATION_*` family plus four codes the migration layer genuinely raises through this\n * class — measured, not assumed: `INVALID_INPUT` (`migrations/utils.ts`, `drivers/base.ts`),\n * `FEATURE_NOT_SUPPORTED` (unsupported index type, SQLite table recreation),\n * `DRIVER_NOT_SUPPORTED` (`drivers/index.ts`) and `INTERNAL_ERROR` (unreachable operation\n * kinds). A code outside this union is a compile error at the construction site.\n */\nexport type MigrationErrorCode =\n | typeof VibORMErrorCode.MIGRATION_FAILED\n | typeof VibORMErrorCode.MIGRATION_NOT_FOUND\n | typeof VibORMErrorCode.MIGRATION_CHECKSUM_MISMATCH\n | typeof VibORMErrorCode.MIGRATION_DIALECT_MISMATCH\n | typeof VibORMErrorCode.MIGRATION_LOCK_FAILED\n | typeof VibORMErrorCode.MIGRATION_ALREADY_APPLIED\n | typeof VibORMErrorCode.MIGRATION_OUT_OF_ORDER\n | typeof VibORMErrorCode.MIGRATION_FILE_NOT_FOUND\n | typeof VibORMErrorCode.MIGRATION_INVALID_STATE\n | typeof VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n | typeof VibORMErrorCode.MIGRATION_STORAGE_REQUIRED\n | typeof VibORMErrorCode.MIGRATION_INVALID_ESTATE\n | typeof VibORMErrorCode.MIGRATION_PATH_REQUIRED\n | typeof VibORMErrorCode.MIGRATION_DRIFT\n | typeof VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n | typeof VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n | typeof VibORMErrorCode.MIGRATION_CONSENT_REQUIRED\n | typeof VibORMErrorCode.MIGRATION_CONSENT_MISMATCH\n | typeof VibORMErrorCode.MIGRATION_PARTIAL_EFFECT\n | typeof VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT\n | typeof VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n | typeof VibORMErrorCode.MIGRATION_CORRUPTION\n | typeof VibORMErrorCode.INVALID_INPUT\n | typeof VibORMErrorCode.FEATURE_NOT_SUPPORTED\n | typeof VibORMErrorCode.DRIVER_NOT_SUPPORTED\n | typeof VibORMErrorCode.INTERNAL_ERROR;\n\n/**\n * Migration-related errors\n */\nexport class MigrationError extends VibORMError {\n static override readonly diagnosticName = \"MigrationError\";\n\n /** Discriminant: one of {@link MigrationErrorCode}, never a code outside the family. */\n declare readonly code: MigrationErrorCode;\n\n constructor(\n message: string,\n code: MigrationErrorCode = VibORMErrorCode.MIGRATION_FAILED,\n options?: {\n cause?: Error | undefined;\n meta?: MigrationErrorMeta | undefined;\n }\n ) {\n super(message, code, options);\n }\n}\n\n/**\n * Type guard for migration errors\n */\nexport function isMigrationError(error: unknown): error is MigrationError {\n return error instanceof MigrationError;\n}\n"],"mappings":"wFAsEA,IAAa,eAAb,cAAoC,CAAY,CAC9C,OAAyB,eAAiB,iBAK1C,YACE,EACA,EAA2B,EAAgB,iBAC3C,EAIA,CACA,MAAM,EAAS,EAAM,EAAQ,GAOjC,SAAgB,iBAAiB,EAAyC,CACxE,OAAO,aAAiB"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{y as t}from"./validation-Du6j0Q38.mjs";import{o as n}from"./sql--69HUgel.mjs";import{r}from"./adapter-internals-n3Mf3css.mjs";import{n as i}from"./result-parsing-DRXC89ek.mjs";import{O as a,v as o}from"./geo-point-codec-DUTTtlav.mjs";import{o as s,t as c}from"./identifiers-By-JRCb5.mjs";import{t as l}from"./geo-area-codec-B4DRInvA.mjs";import{a as u}from"./physical-BkelResN.mjs";import{A as d,D as f,E as p,N as ee,O as te,P as m,S as h,T as g,_,a as v,b as y,c as b,d as x,f as S,g as C,h as w,i as T,k as E,l as D,m as O,n as k,o as A,p as j,s as M,u as N,v as ne,w as P,x as F,y as I}from"./batch-refs-BY51FIXm.mjs";import{t as L}from"./adapter-namespace-DMhEF6my.mjs";import{a as R,d as z,f as B,g as V,i as H,m as U,n as W,o as G,p as K,r as q,t as J,u as Y}from"./select-assembly-BgqlrePH.mjs";const X=c("`"),Z=U(()=>`PRIMARY`),Q={quotient:(e,t)=>n`CAST((${e} - MOD(${e}, ${t})) / ${t} AS DECIMAL(65,0))`,remainder:(e,t)=>n`MOD(${e}, ${t})`},mysqlMaximumCoefficient=e=>n.raw(`9`.repeat(e)),re=n`(FIND_IN_SET('STRICT_TRANS_TABLES', @@SESSION.sql_mode) > 0 OR FIND_IN_SET('STRICT_ALL_TABLES', @@SESSION.sql_mode) > 0)`,$=n`JSON_EXTRACT('x', '$')`,decimalCast=(e,t,r)=>n`CAST(${e} AS ${n.raw(`DECIMAL(${t},${r})`)})`,mysqlCoefficient=(e,t)=>{let{scale:r}=t;if(r===0)return e;let i=Y(r),a=n`TRUNCATE(${e}, 0)`;return n`(${a} * ${i} + ${decimalCast(n`(${decimalCast(n`(${e} - ${a})`,r+1,r)} * ${i})`,r,0)})`},mysqlLogical=(e,t)=>{let{scale:r}=t;if(r===0)return e;let i=Y(r),a=n`MOD(${e}, ${i})`;return n`((${e} - ${a}) / ${i} + ${decimalCast(a,r,0)} * ${z(r)})`},mysqlGuardedDecimalAssignment=(e,t,r,i)=>{let a=mysqlMaximumCoefficient(r.precision),o=mysqlLogical(t,r);return n`${e} = CASE WHEN ${re} THEN ${o} WHEN ${e} IS NULL THEN NULL WHEN ${i} THEN CASE WHEN ${t} BETWEEN -${a} AND ${a} THEN ${o} ELSE ${$} END ELSE ${$} END`},mysqlDecimalIncrement=(e,t,r)=>{let i=mysqlCoefficient(e,r),a=mysqlCoefficient(t,r),o=mysqlMaximumCoefficient(r.precision),s=n`CASE WHEN ${a} > 0 THEN ${i} <= ${o} - ${a} WHEN ${a} < 0 THEN ${i} >= -${o} - ${a} ELSE TRUE END`;return mysqlGuardedDecimalAssignment(e,n`(${i} + ${a})`,r,s)},mysqlDecimalDecrement=(e,t,r)=>{let i=mysqlCoefficient(e,r),a=mysqlCoefficient(t,r),o=mysqlMaximumCoefficient(r.precision),s=n`CASE WHEN ${a} > 0 THEN ${i} >= -${o} + ${a} WHEN ${a} < 0 THEN ${i} <= ${o} + ${a} ELSE TRUE END`;return mysqlGuardedDecimalAssignment(e,n`(${i} - ${a})`,r,s)},mysqlDecimalMultiply=(e,t,r)=>{let i=mysqlCoefficient(e,r),a=mysqlCoefficient(t,r),o=mysqlMaximumCoefficient(65);return mysqlGuardedDecimalAssignment(e,G(Q,n`(${i} * ${a})`,Y(r.scale)),r,n`CASE WHEN ${a} = 0 THEN TRUE ELSE ABS(${i}) <= ${Q.quotient(o,n`ABS(${a})`)} END`)},mysqlDecimalDivide=(e,t,r)=>{let i=mysqlCoefficient(t,r);return mysqlGuardedDecimalAssignment(e,G(Q,B(n`(${mysqlCoefficient(e,r)} * ${Y(r.scale)})`,i),n`ABS(${i})`),r,n.raw`TRUE`)},mysqlDecimalAverage=(e,t)=>mysqlLogical(G(Q,n`SUM(${mysqlCoefficient(e,t)})`,n`COUNT(${e})`),t),asciiCaseFold=e=>{let t=e;for(let e=0;e<26;e++){let r=n.raw(`'${`ABCDEFGHIJKLMNOPQRSTUVWXYZ`[e]}'`),i=n.raw(`'${`abcdefghijklmnopqrstuvwxyz`[e]}'`);t=n`REPLACE(${t}, ${r}, ${i})`}return t},ie=/^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(\.\d+)?$/,naiveDateTimeToIso=e=>{let t=ie.exec(e);if(!t)return;let n=t[3]?t[3].padEnd(4,`0`).slice(0,4):`.000`;return`${t[1]}T${t[2]}${n}Z`},inlineIntegerLiteral=e=>{let t=e.values.length===1?e.values[0]:void 0;return typeof t==`number`&&Number.isInteger(t)?n.raw(String(t)):e},mysqlJsonListValue=e=>n`CAST(${m(e)} AS JSON)`;var MySQLAdapter=class{constructor(e){L(this,e,`mysql`),this.identifiers=w(X,this.namespace),K(this,this.geoPoint),r(this,{batchRefs:this.#t,constraints:Z,select:this.#e.select})}raw=g();identifiers;literals={...E(),true:()=>n.raw`TRUE`,false:()=>n.raw`FALSE`,json:e=>n`${JSON.stringify(e)}`,dateTime:(e,t,r)=>n`${r||e.length===10?e:s(e)}`,decimal:(e,t)=>n`CAST(${a(e,t,`text`)} AS ${n.raw(o(`mysql`,t))})`,id:(e,t)=>n`${e}`};operators={...b(),like:(e,t)=>n`${e} LIKE ${t} ESCAPE '\\\\'`,notLike:(e,t)=>n`${e} NOT LIKE ${t} ESCAPE '\\\\'`,ilike:(e,t)=>n`${asciiCaseFold(e)} LIKE ${asciiCaseFold(t)} ESCAPE '\\\\'`,notIlike:(e,t)=>n`${asciiCaseFold(e)} NOT LIKE ${asciiCaseFold(t)} ESCAPE '\\\\'`,containsText:(e,t)=>n`LOCATE(BINARY ${t}, BINARY ${e}) > 0`,startsWithText:(e,t)=>n`LEFT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t}`,endsWithText:(e,t)=>n`RIGHT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t}`,startsWithPrefix:(e,t)=>n`(${e} LIKE ${`${ee(t)}%`} ESCAPE '\\\\' AND LEFT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t})`,exactTextEq:(e,t)=>n`(${e} = ${t} AND BINARY ${e} = ${t})`,exactTextIn:(e,t)=>n`(${e} IN ${t} AND BINARY ${e} IN ${t})`,...I(),...F(),...P(),...ne(this.literals.true,this.literals.false),...O()};expressions={...M(),asciiCaseFold,caseSensitiveText:e=>n`BINARY ${e}`,concat:(...e)=>e.length===0?n.raw`''`:e.length===1?e[0]:n`CONCAT(${n.join(e,`, `)})`,greatest:(...e)=>n`GREATEST(${n.join(e,`, `)})`,least:(...e)=>n`LEAST(${n.join(e,`, `)})`,integerDivide:(e,t)=>n`TRUNCATE(${e} / ${t}, 0)`,decimalCast:(e,t)=>decimalCast(e,t.precision,t.scale),idCast:(e,t)=>t===`bytes`?n`UNHEX(${e})`:n`CAST(${e} AS CHAR)`,cast:A({text:`CHAR`,integer:`SIGNED`,bigint:`SIGNED`,boolean:`UNSIGNED`,numeric:`DECIMAL`}),blobToHex:e=>n`LOWER(HEX(${e}))`};aggregates={...v(),decimalAvg:(e,t)=>mysqlDecimalAverage(e,t),decimalSumOperandPrecision:x(65)};json={equals:(e,t)=>n`${e} = ${t}`,number:e=>e,boolean:e=>n`JSON_EXTRACT(CASE WHEN ${e} THEN 'true' ELSE 'false' END, '$')`,document:e=>e,object:e=>{if(e.length===0)return n.raw`JSON_OBJECT()`;let t=e.flatMap(([e,t])=>[n`${e}`,t]);return n`JSON_OBJECT(${n.join(t,`, `)})`},array:e=>e.length===0?n.raw`JSON_ARRAY()`:n`JSON_ARRAY(${n.join(e,`, `)})`,emptyArray:()=>n.raw`JSON_ARRAY()`,agg:e=>n`COALESCE(JSON_ARRAYAGG(${e}), JSON_ARRAY())`,objectFromColumns:e=>{if(e.length===0)return n.raw`JSON_OBJECT()`;let t=e.flatMap(([e,t])=>[n`${e}`,t]);return n`JSON_OBJECT(${n.join(t,`, `)})`},extract:(e,t)=>n`JSON_EXTRACT(${e}, ${T(t)})`,extractText:(e,t)=>n`JSON_UNQUOTE(JSON_EXTRACT(${e}, ${T(t)}))`,numberAtPath:(e,t)=>{let r=T(t);return n`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${r})) IN ('INTEGER', 'DOUBLE', 'DECIMAL') THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${e}, ${r})) AS DOUBLE) END)`},stringAtPath:(e,t)=>{let r=T(t);return n`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${r})) = 'STRING' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${e}, ${r})) AS BINARY) END)`},contains:(e,t)=>n`JSON_CONTAINS(${e}, ${t})`,lastElement:e=>n`JSON_EXTRACT(${e}, '$[last]')`,value:e=>n`CAST(${m(e)} AS JSON)`};arrays={literal:e=>e.length===0?n.raw`JSON_ARRAY()`:n`JSON_ARRAY(${n.join(e,`, `)})`,value:mysqlJsonListValue,enumValue:mysqlJsonListValue,has:(e,t)=>n`JSON_CONTAINS(${e}, JSON_ARRAY(${t}))`,hasEvery:(e,t)=>n`JSON_CONTAINS(${e}, ${t})`,hasSome:(e,t)=>n`JSON_OVERLAPS(${e}, ${t})`,isEmpty:e=>n`(JSON_LENGTH(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>n`CAST(${e} AS CHAR)`,length:e=>n`JSON_LENGTH(${e})`,get:(e,t)=>n`JSON_EXTRACT(${e}, CONCAT('$[', ${t}, ']'))`,push:(e,t)=>n`JSON_ARRAY_APPEND(${e}, '$', ${t})`,set:(e,t,r)=>n`JSON_SET(${e}, CONCAT('$[', ${t}, ']'), ${r})`};orderBy={...S(),...j()};clauses={...te(),limit:e=>n`LIMIT ${inlineIntegerLiteral(e)}`,offset:e=>n`OFFSET ${inlineIntegerLiteral(e)}`};set={...h(),increment:(e,t,r)=>r?.decimal?mysqlDecimalIncrement(e,t,r.decimal):n`${e} = ${e} + ${t}`,decrement:(e,t,r)=>r?.decimal?mysqlDecimalDecrement(e,t,r.decimal):n`${e} = ${e} - ${t}`,multiply:(e,t,r)=>r?.decimal?mysqlDecimalMultiply(e,t,r.decimal):n`${e} = ${e} * ${t}`,divide:(e,t,r)=>r?.decimal?mysqlDecimalDivide(e,t,r.decimal):r?.integer?n`${e} = TRUNCATE(${e} / ${t}, 0)`:n`${e} = ${e} / ${t}`,push:(e,t)=>n`${e} = JSON_MERGE_PRESERVE(COALESCE(${e}, JSON_ARRAY()), ${t})`,unshift:(e,t)=>n`${e} = JSON_MERGE_PRESERVE(${t}, COALESCE(${e}, JSON_ARRAY()))`};filters=p();subqueries=d(X);noLimitValue=n.raw`18446744073709551615`;#e={select:e=>{let t={...e,limit:e.limit&&inlineIntegerLiteral(e.limit),offset:e.offset&&inlineIntegerLiteral(e.offset)};return t.distinct?J(t,t.distinct,this.identifiers.escape,this.noLimitValue):W(n`SELECT ${t.columns}`,t,{forUpdate:`append`,noLimitValue:this.noLimitValue})}};cte=N(X);mutations={skipDuplicatesStrategy:`recoverableUniqueError`,insert:C(X),insertDefault:e=>n`INSERT INTO ${e} () VALUES ()`,...y(),returning:e=>n.empty,onConflict:(e,t,r)=>n`ON DUPLICATE KEY UPDATE ${t}`,onConflictUpdate:(e,t)=>e,skipDuplicates:e=>{let t=n.raw(X(e));return{prefix:n.empty,suffix:n`ON DUPLICATE KEY UPDATE ${t} = ${t}`}}};assertions={exists:e=>n`SELECT CASE WHEN EXISTS (${e}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \`__viborm_assert__\``,notExists:e=>n`SELECT CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \`__viborm_assert__\``};joins={...D(),full:(e,t)=>{throw Error(`MySQL does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.`)},..._(X)};setOperations=f();capabilities={supportsReturning:!1,supportsCteWithMutations:!1,supportsFullOuterJoin:!1,supportsLateralJoins:!0,supportsVector:!1,supportsUpsertWhere:!1,supportsTargetedUpsert:!1,supportsMutationTargetInSubquery:!1,supportsMutationRowLimit:!0,supportsRowLocks:!0};lastInsertId=()=>n.raw`LAST_INSERT_ID()`;#t=k({table:n.raw`\`__viborm_batch_refs\``,batchIdColumn:n.raw`\`batch_id\``,keyColumn:n.raw`\`ref_key\``,valueColumn:n.raw`\`ref_value\``,duplicateValue:n.raw`VALUES(\`ref_value\`)`,createTable:n.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\`))`,castValue:e=>n`CAST((${e}) AS CHAR)`,lastInsertId:()=>this.lastInsertId()});vector=t;geoPoint=(()=>{let longitude=e=>n`ST_Longitude(${e})`,latitude=e=>n`ST_Latitude(${e})`;return{value:(e,t)=>n`ST_GeomFromText(CONCAT('POINT(', ${e}, ' ', ${t}, ')'), 4326, 'axis-order=long-lat')`,longitude,latitude,...q(longitude,latitude,this.operators,(e,t)=>{let r=H(t);if(r.length!==0)return this.operators.or(...r.map(t=>n`MBRIntersects(${e}, ST_GeomFromGeoJSON(${t}, 1, 4326))`))}),withinPolygon:(e,t)=>n`ST_Intersects(${n`ST_GeomFromGeoJSON(${R(t)}, 1, 4326)`}, ${e})`,distance:(e,t)=>n`ST_Distance_Sphere(${e}, ${t}, ${l})`}})();result={decimalListRepresentation:`coefficient`,idRepresentation:(e,t)=>u(e,t,`mysql`)?.representation??`text`,parseResult:V,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>{if(t===`boolean`){let t=i(e===`0`?0:e===`1`?1:e);if(t!==void 0)return n(t)}if(t===`datetime`&&typeof e==`string`){let t=naiveDateTimeToIso(e);if(t!==void 0)return n(t)}return n()}}};export{MySQLAdapter as t};
|
|
2
|
-
//# sourceMappingURL=mysql-adapter-D9FoHlWE.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"mysql-adapter-D9FoHlWE.mjs","names":["sql","#batchRefs","#assemble"],"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 passThroughParseResult,\n} from \"../../adapter-result-parser\";\nimport { createNamedConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\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 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 mysqlDecimalIncrement = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = 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 sql`(${current} + ${operand})`,\n descriptor,\n fits\n );\n};\n\nconst mysqlDecimalDecrement = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = 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 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};\nconst ASCII_UPPERCASE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst ASCII_LOWERCASE = \"abcdefghijklmnopqrstuvwxyz\";\n\nconst asciiCaseFold = (expr: Sql): Sql => {\n let folded = expr;\n for (let index = 0; index < ASCII_UPPERCASE.length; index++) {\n const upper = sql.raw(`'${ASCII_UPPERCASE[index]}'`);\n const lower = sql.raw(`'${ASCII_LOWERCASE[index]}'`);\n folded = sql`REPLACE(${folded}, ${upper}, ${lower})`;\n }\n return folded;\n};\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\n/**\n * MySQL Database Adapter\n *\n * Implements the DatabaseAdapter interface for MySQL-specific SQL generation.\n *\n * Key MySQL features:\n * - Backtick identifier escaping: `table`.`column`\n * - No native ARRAY type - uses JSON for arrays\n * - Portable string filters override the database collation explicitly\n * - JSON_OBJECT(), JSON_ARRAYAGG() for JSON operations\n * - No RETURNING clause (use LAST_INSERT_ID())\n * - No NULLS FIRST/LAST ordering\n * - ON DUPLICATE KEY UPDATE for upserts\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\nexport class MySQLAdapter implements DatabaseAdapter {\n // ============================================================\n // NAMESPACE\n // ============================================================\n\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(quoteIdent, this.namespace);\n installGeoPointSql(this, this.geoPoint);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: MYSQL_CONSTRAINTS,\n select: this.#assemble.select,\n });\n }\n\n // ============================================================\n // RAW\n // ============================================================\n\n raw = createRawSql();\n\n // ============================================================\n // IDENTIFIERS\n // ============================================================\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n // ============================================================\n // LITERALS\n // ============================================================\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 // ============================================================\n // OPERATORS\n // ============================================================\n\n operators = {\n // Comparison\n ...createComparisonOperators(),\n\n // Pattern matching\n // Explicit ESCAPE '\\' pairs with wildcard escaping in the where-builder.\n // The literal is doubled ('\\\\') because MySQL's default mode treats\n // backslash as a string-literal escape; under NO_BACKSLASH_ESCAPES it\n // fails loudly rather than silently matching wildcards.\n like: (column: Sql, pattern: Sql): Sql =>\n sql`${column} LIKE ${pattern} ESCAPE '\\\\\\\\'`,\n notLike: (column: Sql, pattern: Sql): Sql =>\n sql`${column} NOT LIKE ${pattern} ESCAPE '\\\\\\\\'`,\n ilike: (column: Sql, pattern: Sql): Sql =>\n sql`${asciiCaseFold(column)} LIKE ${asciiCaseFold(pattern)} ESCAPE '\\\\\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`${asciiCaseFold(column)} NOT LIKE ${asciiCaseFold(pattern)} ESCAPE '\\\\\\\\'`,\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 // 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 // Set membership\n ...createMembershipOperators(),\n\n // Null checks\n ...createNullOperators(),\n\n // Range\n ...createRangeOperators(),\n\n // Logical\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n // Subquery existence\n ...createExistenceOperators(),\n };\n\n // ============================================================\n // EXPRESSIONS\n // ============================================================\n\n expressions = {\n ...createCommonExpressions(),\n\n asciiCaseFold,\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 // MySQL type mappings - MySQL doesn't support TEXT in CAST\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 // ============================================================\n // AGGREGATES\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 // ============================================================\n // JSON\n // ============================================================\n\n json = {\n equals: (left: Sql, right: Sql): Sql => sql`${left} = ${right}`,\n number: (expression: Sql): Sql => expression,\n boolean: (condition: Sql): Sql =>\n sql`JSON_EXTRACT(CASE WHEN ${condition} THEN 'true' ELSE 'false' END, '$')`,\n document: (expression: Sql): Sql => expression,\n\n object: (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 array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`JSON_ARRAY()`;\n return sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n },\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: (columns: [string, Sql][]): Sql => {\n if (columns.length === 0) return sql.raw`JSON_OBJECT()`;\n const args = columns.flatMap(([key, value]) => [sql`${key}`, value]);\n return sql`JSON_OBJECT(${sql.join(args, \", \")})`;\n },\n\n // buildJsonPath quotes/escapes key segments and maps integer segments\n // to array indices; '$' alone extracts the document root\n extract: (column: Sql, path: string[]): Sql =>\n sql`JSON_EXTRACT(${column}, ${buildJsonPath(path)})`,\n\n extractText: (column: Sql, path: string[]): Sql =>\n sql`JSON_UNQUOTE(JSON_EXTRACT(${column}, ${buildJsonPath(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 jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) IN ('INTEGER', 'DOUBLE', 'DECIMAL') THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) 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 jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) = 'STRING' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) AS BINARY) 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 // ============================================================\n // ARRAYS (JSON-based for MySQL)\n // ============================================================\n\n arrays = {\n // MySQL uses JSON arrays\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`JSON_ARRAY()`;\n return sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n },\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 // ============================================================\n // ORDER BY\n // ============================================================\n\n orderBy = {\n ...createDirectionOrderBy(),\n // MySQL doesn't support NULLS FIRST/LAST natively - emulated\n ...createEmulatedNullsOrderBy(),\n };\n\n // ============================================================\n // CLAUSES\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 // ============================================================\n // SET (UPDATE operations)\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 ? mysqlDecimalIncrement(column, by, target.decimal)\n : sql`${column} = ${column} + ${by}`,\n\n decrement: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalDecrement(column, by, target.decimal)\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 // ============================================================\n // FILTERS (Relation subquery wrappers)\n // ============================================================\n\n filters = createRelationFilters();\n\n // ============================================================\n // SUBQUERIES\n // ============================================================\n\n subqueries = createSubqueries(quoteIdent);\n\n // ============================================================\n // ASSEMBLE (Build complete SQL statements)\n // ============================================================\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(sql`SELECT ${parts.columns}`, parts, {\n forUpdate: \"append\",\n noLimitValue: this.noLimitValue,\n });\n },\n };\n\n // ============================================================\n // CTE (Common Table Expressions - MySQL 8.0+)\n // ============================================================\n\n cte = createCteBuilders(quoteIdent);\n\n // ============================================================\n // MUTATIONS\n // ============================================================\n\n mutations = {\n skipDuplicatesStrategy: \"recoverableUniqueError\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql => sql`INSERT INTO ${table} () VALUES ()`,\n\n ...createMutationCommands(),\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: (query: Sql): Sql =>\n sql`SELECT CASE WHEN EXISTS (${query}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \\`__viborm_assert__\\``,\n notExists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \\`__viborm_assert__\\``,\n };\n\n // ============================================================\n // JOINS\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(\n \"MySQL does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.\"\n );\n },\n\n // MySQL 8.0.14+ supports LATERAL\n ...createLateralJoins(quoteIdent),\n };\n\n // ============================================================\n // SET OPERATIONS\n // ============================================================\n\n setOperations = createSetOperations();\n\n // ============================================================\n // CAPABILITIES\n // ============================================================\n\n capabilities = {\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 };\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 // ============================================================\n // VECTOR (not natively supported in MySQL)\n // ============================================================\n\n vector = unsupportedVector;\n\n // ============================================================\n // GEOPOINT (MySQL geographic POINT SRID 4326)\n // ============================================================\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 return {\n // EPSG:4326 is latitude-longitude in MySQL's SRS catalog. The explicit\n // WKT option makes the two bound coordinates longitude-latitude instead.\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) =>\n sql`MBRIntersects(${point}, ST_GeomFromGeoJSON(${polygon}, 1, 4326))`\n )\n );\n }\n ),\n withinPolygon: (point, polygon) => {\n const geography = sql`ST_GeomFromGeoJSON(${geoPolygonJson(\n polygon\n )}, 1, 4326)`;\n return sql`ST_Intersects(${geography}, ${point})`;\n },\n distance: (left, right) =>\n sql`ST_Distance_Sphere(${left}, ${right}, ${GEO_POINT_EARTH_RADIUS_METERS})`,\n };\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 // ============================================================\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\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => next(),\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":"m1BA4EA,MAAM,EAAa,EAAuB,IAAI,CACxC,EAAoB,MAAsC,UAAU,CAapE,EAAyC,CAQ7C,UAAW,EAAQ,IACjB,CAAG,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,OAA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DaU.mjs";var CacheInvalidTTLError=class extends a{static diagnosticName=`CacheInvalidTTLError`;constructor(e,t){super(e,i.CACHE_INVALID_TTL,t)}},CacheInvalidKeyError=class extends a{static diagnosticName=`CacheInvalidKeyError`;constructor(e,t){super(e,i.CACHE_INVALID_KEY,t)}},CacheOperationNotCacheableError=class extends a{static diagnosticName=`CacheOperationNotCacheableError`;constructor(e,t,n){super(`Operation "${e}" is not cacheable. Only read operations can be cached: ${t.join(`, `)}`,i.CACHE_OPERATION_NOT_CACHEABLE,{meta:{...n?.meta,operation:e}})}},CacheConfigurationError=class extends a{static diagnosticName=`CacheConfigurationError`;constructor(e,t){super(e,i.CACHE_CONFIGURATION,t)}};const o=new WeakMap,s=new WeakMap,c=new WeakMap,settleObserverReturn=()=>void 0;function getOfficialInstrumentationChainCapability(e){return e===void 0?void 0:c.get(e)}function registerOfficialInstrumentationChain(e,t){c.set(e,t)}function registerTrustedProtectedObserver(e,t,n){o.set(e,{capability:t,observer:n})}function getTrustedProtectedObserverCapability(e){return t(e)?o.get(e)?.capability:void 0}function selectTrustedObservers(e){let t=e?.find(({handler:e})=>o.has(e));return t===void 0?void 0:[t]}function prewarmProtectedObservers(e){if(!(e===void 0||e.length===0))for(let t of e){let e=o.get(t.handler);if(e===void 0)continue;let n=prewarmTrustedObserver(e.capability);if(n!==void 0)return n}}function readProtectedLifecycleFacts(e){return s.get(e)?.facts}function readProtectedLifecycleCompletionFacts(e){return s.get(e)?.completion}function runProtectedObservers(e,t,n,r,i){if(t===void 0||t.length===0)return n();let a=Date.now(),c=freezeLifecycleUnit(e),l=-1,u;for(let[e,n]of t.entries()){let t=o.get(n.handler);if(t!==void 0){l=e,u=t;break}}let d,f,p,m=u===void 0?void 0:new Promise(e=>{p=e}),h,g=u===void 0,_,v=!1,resolveOuterWhenReady=()=>{g&&h!==void 0&&p?.(h)},settleCompletion=(e,t)=>{let n=Math.max(0,Date.now()-a),i;try{i=r?.()?.commitCertainty}catch{i=void 0}let o=createCompletion(e,n,i,t);h=o;let l=s.get(c);if(l!==void 0)try{l.completion=l.facts.complete({status:e,durationMs:n,...e===`failure`?{failure:t}:{}})}catch{l.completion=void 0}d?.(o),resolveOuterWhenReady()},observeApplicationCompletion=()=>{v||f===void 0||_===void 0||(v=!0,_.then(()=>settleCompletion(`success`),e=>settleCompletion(`failure`,e)))},readCompletionPromise=()=>(f===void 0&&(f=new Promise(e=>{d=e})),observeApplicationCompletion(),f),startChild=()=>{let e;try{e=n()}catch(t){e=Promise.reject(t)}return _=e,observeApplicationCompletion(),e},startObserver=e=>{let n=t[e];if(n===void 0)return startChild();let r=o.get(n.handler);if(r!==void 0){if(i!==void 0)try{let e=i();e!==void 0&&s.set(c,{facts:e})}catch{}let t,n,a=new Promise((e,r)=>{t=e,n=r}),o=!1,startNext=()=>(o||(o=!0,startObserver(e+1).then(e=>t(e),e=>n(e))),readCompletionPromise()),l;try{l=r.observer(c,startNext)}catch{return startNext(),g=!0,resolveOuterWhenReady(),a}return Promise.resolve(l).then(()=>{o||startNext(),g=!0,resolveOuterWhenReady()},()=>{o||startNext(),g=!0,resolveOuterWhenReady()}),a}let a,startNextApplication=()=>(a===void 0&&(a=startObserver(e+1)),a),proceed=()=>(startNextApplication(),m!==void 0&&e<l?m:readCompletionPromise()),u;try{u=Reflect.apply(n.handler,void 0,[c,proceed])}catch{u=void 0}let d=startNextApplication();return consumeObserverReturn(u),d},y=i===void 0||u===void 0?void 0:prewarmTrustedObserver(u.capability);if(y===void 0)return startObserver(0);let b,x,S=new Promise((e,t)=>{b=e,x=t}),startAfterPrewarm=()=>{startObserver(0).then(e=>b(e),e=>x(e))};return y.then(startAfterPrewarm),S}function observeOperation(e,t,n,r,i,a){return runProtectedObservers({kind:`operation`,operation:t,...n===void 0?{}:{model:n}},e,r,i,a)}function observeStatement(e,t,n,r,i,a){return runProtectedObservers({kind:`statement`,...t===void 0?{}:{operation:t},...n===void 0||n===`$raw`?{}:{model:n}},e,r,i,a)}function observeDriverLifecycle(e,t,n,r,i,a){return runProtectedObservers({kind:e,...n===void 0?{}:{operation:n}},t,r,i,a)}function prewarmTrustedObserver(e){let t=e.prewarm;if(t===void 0)return;let n;try{n=t()}catch{return}if(n!==void 0)return Promise.resolve(n).then(()=>void 0,()=>void 0)}function freezeLifecycleUnit(e){return Object.freeze(e)}function consumeObserverReturn(e){if(!(e===null||typeof e!=`object`&&typeof e!=`function`))try{let n=Reflect.get(e,`then`);if(!t(n))return;Reflect.apply(n,e,[settleObserverReturn,settleObserverReturn])}catch{}}function createCompletion(e,t,n,r){let i=e===`failure`?summarizeFailure(r):void 0;return Object.freeze({status:e,durationMs:t,...i===void 0?{}:{error:i},...n===void 0?{}:{commitCertainty:n}})}function summarizeFailure(e){let t=r(n(e)?e:Error(`Application rejected with a non-Error value`)),i=Object.getOwnPropertyDescriptor(t,`code`)?.value;return Object.freeze({name:t.name,message:t.message,...typeof i==`string`?{code:i}:{}})}export{observeStatement as a,readProtectedLifecycleFacts as c,runProtectedObservers as d,selectTrustedObservers as f,CacheOperationNotCacheableError as g,CacheInvalidTTLError as h,observeOperation as i,registerOfficialInstrumentationChain as l,CacheInvalidKeyError as m,getTrustedProtectedObserverCapability as n,prewarmProtectedObservers as o,CacheConfigurationError as p,observeDriverLifecycle as r,readProtectedLifecycleCompletionFacts as s,getOfficialInstrumentationChainCapability as t,registerTrustedProtectedObserver as u};
|
|
2
|
-
//# sourceMappingURL=observation-CLp8ylmL.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"observation-CLp8ylmL.mjs","names":["resolveApplication","rejectApplication","applicationBridge"],"sources":["../src/errors/cache.ts","../src/extensions/observation.ts"],"sourcesContent":["import { VibORMError, VibORMErrorCode, type VibORMErrorMeta } from \"./base\";\n\n/**\n * Invalid TTL format or value\n */\nexport class CacheInvalidTTLError extends VibORMError {\n static override readonly diagnosticName = \"CacheInvalidTTLError\";\n\n /** Literal discriminant: this class always carries `CACHE_INVALID_TTL`. */\n declare readonly code: typeof VibORMErrorCode.CACHE_INVALID_TTL;\n\n constructor(message: string, options?: { meta?: VibORMErrorMeta }) {\n super(message, VibORMErrorCode.CACHE_INVALID_TTL, options);\n }\n}\n\n/**\n * Invalid cache key (circular reference, uncacheable type)\n */\nexport class CacheInvalidKeyError extends VibORMError {\n static override readonly diagnosticName = \"CacheInvalidKeyError\";\n\n /** Literal discriminant: this class always carries `CACHE_INVALID_KEY`. */\n declare readonly code: typeof VibORMErrorCode.CACHE_INVALID_KEY;\n\n constructor(message: string, options?: { meta?: VibORMErrorMeta }) {\n super(message, VibORMErrorCode.CACHE_INVALID_KEY, options);\n }\n}\n\n/**\n * Operation cannot be cached (e.g., mutation operations)\n */\nexport class CacheOperationNotCacheableError extends VibORMError {\n static override readonly diagnosticName = \"CacheOperationNotCacheableError\";\n\n /** Literal discriminant: this class always carries `CACHE_OPERATION_NOT_CACHEABLE`. */\n declare readonly code: typeof VibORMErrorCode.CACHE_OPERATION_NOT_CACHEABLE;\n\n constructor(\n operation: string,\n cacheableOperations: string[],\n options?: { meta?: VibORMErrorMeta }\n ) {\n super(\n `Operation \"${operation}\" is not cacheable. Only read operations can be cached: ${cacheableOperations.join(\", \")}`,\n VibORMErrorCode.CACHE_OPERATION_NOT_CACHEABLE,\n {\n meta: { ...options?.meta, operation },\n }\n );\n }\n}\n\n/**\n * Invalid or missing cache configuration (options or driver)\n */\nexport class CacheConfigurationError extends VibORMError {\n static override readonly diagnosticName = \"CacheConfigurationError\";\n\n /** Literal discriminant: this class always carries `CACHE_CONFIGURATION`. */\n declare readonly code: typeof VibORMErrorCode.CACHE_CONFIGURATION;\n\n constructor(\n message: string,\n options?: { cause?: Error | undefined; meta?: VibORMErrorMeta }\n ) {\n super(message, VibORMErrorCode.CACHE_CONFIGURATION, options);\n }\n}\n","import { sanitizeErrorForLogging } from \"@errors\";\nimport { isFunction } from \"@validation/value-guards\";\nimport { isError } from \"../errors/diagnostic-safety\";\nimport type { ResolvedExtensionChain, ResolvedExtensionHandler } from \"./chain\";\nimport type {\n OfficialLifecycleCompletionFacts,\n OfficialLifecycleFacts,\n OfficialLifecycleFactsReader,\n OfficialObservationCapability,\n} from \"./official-facts\";\n\n/** The exact public facts carried by each protected lifecycle boundary. */\nexport type LifecycleUnit =\n | Readonly<{\n kind: \"operation\";\n operation: string;\n model?: string;\n }>\n | Readonly<{\n kind: \"statement\";\n operation?: string;\n model?: string;\n }>\n | Readonly<{\n kind: \"batch\";\n operation: string;\n }>\n | Readonly<{\n kind: \"transaction\";\n operation?: string;\n }>\n | Readonly<{\n kind: \"savepoint\";\n operation?: string;\n }>\n | Readonly<{\n kind: \"connection\";\n operation?: string;\n }>\n | Readonly<{\n kind: \"cache\";\n operation: \"get\" | \"set\" | \"revalidate\" | \"invalidate\";\n }>;\n\nexport type LifecycleUnitKind = LifecycleUnit[\"kind\"];\n\nexport type CommitCertainty = \"committed\" | \"may-have-committed\";\n\nexport interface ObservationErrorSummary {\n readonly name: string;\n readonly message: string;\n readonly code?: string;\n}\n\nexport interface ObservationCompletion {\n readonly status: \"success\" | \"failure\";\n readonly durationMs: number;\n readonly error?: ObservationErrorSummary;\n readonly commitCertainty?: CommitCertainty;\n}\n\nexport interface ObservationCompletionFacts {\n readonly commitCertainty?: CommitCertainty;\n}\n\nexport type ObservationCompletionFactsReader = () =>\n | ObservationCompletionFacts\n | undefined;\n\nexport type ObservationUnit = LifecycleUnit;\n\nexport type ObserveHandler = (\n unit: ObservationUnit,\n proceed: () => Promise<ObservationCompletion>\n) => unknown;\n\ntype TrustedProtectedObserver = (\n unit: LifecycleUnit,\n proceed: () => Promise<ObservationCompletion>\n) => unknown;\n\ninterface TrustedProtectedObserverRegistration {\n readonly capability: OfficialObservationCapability;\n readonly observer: TrustedProtectedObserver;\n}\n\ninterface ProtectedLifecycleFactsState {\n readonly facts: OfficialLifecycleFacts;\n completion?: OfficialLifecycleCompletionFacts;\n}\n\nconst trustedObservers = new WeakMap<\n CallableFunction,\n TrustedProtectedObserverRegistration\n>();\nconst lifecycleFacts = new WeakMap<\n LifecycleUnit,\n ProtectedLifecycleFactsState\n>();\nconst officialCapabilitiesByChain = new WeakMap<\n ResolvedExtensionChain,\n OfficialObservationCapability\n>();\nconst settleObserverReturn = (): undefined => undefined;\n\n/** The one official capability registered for this exact chain, if any. */\nexport function getOfficialInstrumentationChainCapability(\n chain: ResolvedExtensionChain | undefined\n): OfficialObservationCapability | undefined {\n return chain === undefined\n ? undefined\n : officialCapabilitiesByChain.get(chain);\n}\n\n/** Bind the admitted official capability to one exact resolved chain. */\nexport function registerOfficialInstrumentationChain(\n chain: ResolvedExtensionChain,\n capability: OfficialObservationCapability\n): void {\n officialCapabilitiesByChain.set(chain, capability);\n}\n\n/** Register one package-owned observer identity without publishing a marker. */\nexport function registerTrustedProtectedObserver(\n handler: CallableFunction,\n capability: OfficialObservationCapability,\n observer: TrustedProtectedObserver\n): void {\n trustedObservers.set(handler, { capability, observer });\n}\n\n/** Recognize the exact package-owned handler identity and nothing else. */\nexport function getTrustedProtectedObserverCapability(\n handler: unknown\n): OfficialObservationCapability | undefined {\n return isFunction(handler)\n ? trustedObservers.get(handler)?.capability\n : undefined;\n}\n\n/**\n * The exact chain's one trusted observer, alone, or `undefined`. Dispatch\n * through it reaches no ordinary observer: cache backend delete/clear, which\n * have no public unit, run through the one runner this way.\n */\nexport function selectTrustedObservers(\n observers: readonly ResolvedExtensionHandler[] | undefined\n): readonly ResolvedExtensionHandler[] | undefined {\n const trusted = observers?.find(({ handler }) =>\n trustedObservers.has(handler)\n );\n return trusted === undefined ? undefined : [trusted];\n}\n\n/** Resolve the one trusted readiness once before a coordinated array starts. */\nexport function prewarmProtectedObservers(\n observers: readonly ResolvedExtensionHandler[] | undefined\n): void | Promise<void> {\n if (observers === undefined || observers.length === 0) return;\n for (const observer of observers) {\n const registration = trustedObservers.get(observer.handler);\n if (registration === undefined) continue;\n const readiness = prewarmTrustedObserver(registration.capability);\n if (readiness !== undefined) return readiness;\n }\n}\n\n/** Read facts only for the exact frozen unit created by this runner. */\nexport function readProtectedLifecycleFacts(\n unit: LifecycleUnit\n): OfficialLifecycleFacts | undefined {\n return lifecycleFacts.get(unit)?.facts;\n}\n\n/** Read completion facts projected by core after the child settled. */\nexport function readProtectedLifecycleCompletionFacts(\n unit: LifecycleUnit\n): OfficialLifecycleCompletionFacts | undefined {\n return lifecycleFacts.get(unit)?.completion;\n}\n\n/**\n * Runs completion-only observers without giving their onion authority over the\n * application promise.\n */\nexport function runProtectedObservers<Result>(\n unit: LifecycleUnit,\n observers: readonly ResolvedExtensionHandler[] | undefined,\n child: () => Promise<Result>,\n readCompletionFacts?: ObservationCompletionFactsReader,\n readInstrumentationFacts?: OfficialLifecycleFactsReader\n): Promise<Result> {\n if (observers === undefined || observers.length === 0) return child();\n\n const startedAt = Date.now();\n const immutableUnit = freezeLifecycleUnit(unit);\n let trustedIndex = -1;\n let trustedRegistration: TrustedProtectedObserverRegistration | undefined;\n for (const [index, observer] of observers.entries()) {\n const registration = trustedObservers.get(observer.handler);\n if (registration !== undefined) {\n trustedIndex = index;\n trustedRegistration = registration;\n break;\n }\n }\n let resolveCompletion:\n | ((completion: ObservationCompletion) => void)\n | undefined;\n let completionPromise: Promise<ObservationCompletion> | undefined;\n let resolveOuterCompletion:\n | ((completion: ObservationCompletion) => void)\n | undefined;\n const outerCompletionPromise =\n trustedRegistration === undefined\n ? undefined\n : new Promise<ObservationCompletion>((resolve) => {\n resolveOuterCompletion = resolve;\n });\n let settledCompletion: ObservationCompletion | undefined;\n let trustedSetupSettled = trustedRegistration === undefined;\n let applicationPromise: Promise<Result> | undefined;\n let observesApplicationCompletion = false;\n\n const resolveOuterWhenReady = (): void => {\n if (trustedSetupSettled && settledCompletion !== undefined) {\n resolveOuterCompletion?.(settledCompletion);\n }\n };\n\n const settleCompletion = (\n status: ObservationCompletion[\"status\"],\n failure?: unknown\n ): void => {\n const durationMs = Math.max(0, Date.now() - startedAt);\n let commitCertainty: CommitCertainty | undefined;\n try {\n commitCertainty = readCompletionFacts?.()?.commitCertainty;\n } catch {\n commitCertainty = undefined;\n }\n const completion = createCompletion(\n status,\n durationMs,\n commitCertainty,\n failure\n );\n settledCompletion = completion;\n const factsState = lifecycleFacts.get(immutableUnit);\n if (factsState !== undefined) {\n try {\n factsState.completion = factsState.facts.complete({\n status,\n durationMs,\n ...(status === \"failure\" ? { failure } : {}),\n });\n } catch {\n factsState.completion = undefined;\n }\n }\n resolveCompletion?.(completion);\n resolveOuterWhenReady();\n };\n\n const observeApplicationCompletion = (): void => {\n if (\n observesApplicationCompletion ||\n completionPromise === undefined ||\n applicationPromise === undefined\n ) {\n return;\n }\n observesApplicationCompletion = true;\n applicationPromise.then(\n () => settleCompletion(\"success\"),\n (failure: unknown) => settleCompletion(\"failure\", failure)\n );\n };\n\n const readCompletionPromise = (): Promise<ObservationCompletion> => {\n if (completionPromise === undefined) {\n completionPromise = new Promise<ObservationCompletion>((resolve) => {\n resolveCompletion = resolve;\n });\n }\n observeApplicationCompletion();\n return completionPromise;\n };\n\n const startChild = (): Promise<Result> => {\n let started: Promise<Result>;\n try {\n started = child();\n } catch (failure) {\n started = Promise.reject(failure);\n }\n applicationPromise = started;\n observeApplicationCompletion();\n return started;\n };\n\n const startObserver = (index: number): Promise<Result> => {\n const observer = observers[index];\n if (observer === undefined) return startChild();\n\n const trustedObserver = trustedObservers.get(observer.handler);\n if (trustedObserver !== undefined) {\n if (readInstrumentationFacts !== undefined) {\n try {\n const facts = readInstrumentationFacts();\n if (facts !== undefined) lifecycleFacts.set(immutableUnit, { facts });\n } catch {\n // Instrumentation fact production cannot stop the application.\n }\n }\n // Promise executors run synchronously; TypeScript does not model that guarantee.\n let resolveApplication!: (value: Result | PromiseLike<Result>) => void;\n let rejectApplication!: (reason?: unknown) => void;\n const applicationBridge = new Promise<Result>((resolve, reject) => {\n resolveApplication = resolve;\n rejectApplication = reject;\n });\n let proceeded = false;\n const startNext = (): Promise<ObservationCompletion> => {\n if (!proceeded) {\n proceeded = true;\n startObserver(index + 1).then(\n (value) => resolveApplication(value),\n (failure: unknown) => rejectApplication(failure)\n );\n }\n return readCompletionPromise();\n };\n let setup: unknown;\n try {\n setup = trustedObserver.observer(immutableUnit, startNext);\n } catch {\n startNext();\n trustedSetupSettled = true;\n resolveOuterWhenReady();\n return applicationBridge;\n }\n Promise.resolve(setup).then(\n () => {\n if (!proceeded) startNext();\n trustedSetupSettled = true;\n resolveOuterWhenReady();\n },\n () => {\n if (!proceeded) startNext();\n trustedSetupSettled = true;\n resolveOuterWhenReady();\n }\n );\n return applicationBridge;\n }\n\n let nextApplicationPromise: Promise<Result> | undefined;\n const startNextApplication = (): Promise<Result> => {\n if (nextApplicationPromise === undefined) {\n nextApplicationPromise = startObserver(index + 1);\n }\n return nextApplicationPromise;\n };\n const proceed = (): Promise<ObservationCompletion> => {\n startNextApplication();\n return outerCompletionPromise !== undefined && index < trustedIndex\n ? outerCompletionPromise\n : readCompletionPromise();\n };\n\n let returned: unknown;\n try {\n returned = Reflect.apply(observer.handler, undefined, [\n immutableUnit,\n proceed,\n ]);\n } catch {\n returned = undefined;\n }\n const nextApplication = startNextApplication();\n consumeObserverReturn(returned);\n return nextApplication;\n };\n\n const readiness =\n readInstrumentationFacts === undefined || trustedRegistration === undefined\n ? undefined\n : prewarmTrustedObserver(trustedRegistration.capability);\n if (readiness === undefined) return startObserver(0);\n\n // Promise executors run synchronously; TypeScript does not model that guarantee.\n let resolveApplication!: (value: Result | PromiseLike<Result>) => void;\n let rejectApplication!: (reason?: unknown) => void;\n const applicationBridge = new Promise<Result>((resolve, reject) => {\n resolveApplication = resolve;\n rejectApplication = reject;\n });\n const startAfterPrewarm = (): void => {\n startObserver(0).then(\n (value) => resolveApplication(value),\n (failure: unknown) => rejectApplication(failure)\n );\n };\n readiness.then(startAfterPrewarm);\n return applicationBridge;\n}\n\n/** Observe one logical operation without duplicating its completion protocol. */\nexport function observeOperation<Result>(\n observers: readonly ResolvedExtensionHandler[],\n operation: string,\n model: string | undefined,\n child: () => Promise<Result>,\n readCompletionFacts?: ObservationCompletionFactsReader,\n readInstrumentationFacts?: OfficialLifecycleFactsReader\n): Promise<Result> {\n return runProtectedObservers(\n {\n kind: \"operation\",\n operation,\n ...(model === undefined ? {} : { model }),\n },\n observers,\n child,\n readCompletionFacts,\n readInstrumentationFacts\n );\n}\n\n/** Observe one driver-owned physical statement boundary. */\nexport function observeStatement<Result>(\n observers: readonly ResolvedExtensionHandler[],\n operation: string | undefined,\n model: string | undefined,\n child: () => Promise<Result>,\n readCompletionFacts?: ObservationCompletionFactsReader,\n readInstrumentationFacts?: OfficialLifecycleFactsReader\n): Promise<Result> {\n return runProtectedObservers(\n {\n kind: \"statement\",\n ...(operation === undefined ? {} : { operation }),\n ...(model === undefined || model === \"$raw\" ? {} : { model }),\n },\n observers,\n child,\n readCompletionFacts,\n readInstrumentationFacts\n );\n}\n\n/** Observe one driver-owned connection, transaction, or savepoint boundary. */\nexport function observeDriverLifecycle<Result>(\n kind: Extract<LifecycleUnitKind, \"connection\" | \"savepoint\" | \"transaction\">,\n observers: readonly ResolvedExtensionHandler[],\n operation: string | undefined,\n child: () => Promise<Result>,\n readCompletionFacts?: ObservationCompletionFactsReader,\n readInstrumentationFacts?: OfficialLifecycleFactsReader\n): Promise<Result> {\n return runProtectedObservers(\n {\n kind,\n ...(operation === undefined ? {} : { operation }),\n },\n observers,\n child,\n readCompletionFacts,\n readInstrumentationFacts\n );\n}\n\nfunction prewarmTrustedObserver(\n capability: OfficialObservationCapability\n): void | Promise<void> {\n const prewarm = capability.prewarm;\n if (prewarm === undefined) return;\n let readiness: void | Promise<void>;\n try {\n readiness = prewarm();\n } catch {\n return;\n }\n if (readiness === undefined) return;\n return Promise.resolve(readiness).then(\n () => undefined,\n () => undefined\n );\n}\n\nfunction freezeLifecycleUnit(unit: LifecycleUnit): LifecycleUnit {\n return Object.freeze(unit);\n}\n\nfunction consumeObserverReturn(returned: unknown): void {\n if (\n returned === null ||\n (typeof returned !== \"object\" && typeof returned !== \"function\")\n ) {\n return;\n }\n try {\n const then = Reflect.get(returned, \"then\");\n if (!isFunction(then)) return;\n Reflect.apply(then, returned, [settleObserverReturn, settleObserverReturn]);\n } catch {\n // Observer returns cannot affect the application.\n }\n}\n\nfunction createCompletion(\n status: ObservationCompletion[\"status\"],\n durationMs: number,\n commitCertainty: CommitCertainty | undefined,\n failure: unknown\n): ObservationCompletion {\n const error = status === \"failure\" ? summarizeFailure(failure) : undefined;\n return Object.freeze({\n status,\n durationMs,\n ...(error === undefined ? {} : { error }),\n ...(commitCertainty === undefined ? {} : { commitCertainty }),\n });\n}\n\nfunction summarizeFailure(failure: unknown): ObservationErrorSummary {\n const normalized = isError(failure)\n ? failure\n : new Error(\"Application rejected with a non-Error value\");\n const sanitized = sanitizeErrorForLogging(normalized);\n const code = Object.getOwnPropertyDescriptor(sanitized, \"code\")?.value;\n return Object.freeze({\n name: sanitized.name,\n message: sanitized.message,\n ...(typeof code === \"string\" ? { code } : {}),\n });\n}\n"],"mappings":"oJAKA,IAAa,qBAAb,cAA0C,CAAY,CACpD,OAAyB,eAAiB,uBAK1C,YAAY,EAAiB,EAAsC,CACjE,MAAM,EAAS,EAAgB,kBAAmB,EAAQ,GAOjD,qBAAb,cAA0C,CAAY,CACpD,OAAyB,eAAiB,uBAK1C,YAAY,EAAiB,EAAsC,CACjE,MAAM,EAAS,EAAgB,kBAAmB,EAAQ,GAOjD,gCAAb,cAAqD,CAAY,CAC/D,OAAyB,eAAiB,kCAK1C,YACE,EACA,EACA,EACA,CACA,MACE,cAAc,EAAU,0DAA0D,EAAoB,KAAK,KAAK,GAChH,EAAgB,8BAChB,CACE,KAAM,CAAE,GAAG,GAAS,KAAM,YAAW,CACtC,CACF,GAOQ,wBAAb,cAA6C,CAAY,CACvD,OAAyB,eAAiB,0BAK1C,YACE,EACA,EACA,CACA,MAAM,EAAS,EAAgB,oBAAqB,EAAQ,GCwBhE,MAAM,EAAmB,IAAI,QAIvB,EAAiB,IAAI,QAIrB,EAA8B,IAAI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ACnB,SACA,aACA,GAAI,IAAU,IAAA,GAAY,EAAE,CAAG,CAAE,QAAO,CACxC,GAAI,IAAoB,IAAA,GAAY,EAAE,CAAG,CAAE,kBAAiB,CAC7D,CAAC,CAGJ,SAAS,iBAAiB,EAA2C,CAInE,IAAM,EAAY,EAHC,EAAQ,EAAQ,CAC/B,EACI,MAAM,8CAA8C,CACP,CAC/C,EAAO,OAAO,yBAAyB,EAAW,OAAO,EAAE,MACjE,OAAO,OAAO,OAAO,CACnB,KAAM,EAAU,KAChB,QAAS,EAAU,QACnB,GAAI,OAAO,GAAS,SAAW,CAAE,OAAM,CAAG,EAAE,CAC7C,CAAC"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{$ as t,Z as n}from"./geo-point-codec-DUTTtlav.mjs";import{i as r,o as i,r as a,t as o}from"./native-types-veeTk36s.mjs";const s=new WeakMap;function idDomainOfState(e){return e?.array===!0?void 0:idMemberDomainOfState(e)}function idMemberDomainOfState(e){if(e===void 0||e.type!==`string`)return;let n=s.get(e);if(n)return n;let r=e.autoGenerate;if(r===void 0||!t(r.kind)||r.implicit===!0)return;let i={format:r.kind,prefix:r.prefix,length:r.length};return s.set(e,i),i}const c=/^(?:text|citext|varchar\(\d+\))$/,l=/^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\(\d+\)|CHAR\(\d+\))$/,u=/^TEXT$/,d=/^(?:BINARY|VARBINARY)\((\d+)\)$/;function defaultIdStorage(e,t){let i=n(e);if(i===void 0)switch(t){case`pg`:return{representation:`text`,columnType:a.STRING.TEXT.type};case`mysql`:return{representation:`text`,columnType:`TEXT`};default:return{representation:`text`,columnType:r.STRING.TEXT.type}}switch(t){case`pg`:return e===`uuid`||e===`uuidv7`?{representation:`uuid`,columnType:a.STRING.UUID.type}:{representation:`bytes`,columnType:a.BLOB.BYTEA.type};case`mysql`:return{representation:`bytes`,columnType:o.BLOB.BINARY(i).type};default:return{representation:`bytes`,columnType:r.BLOB.BLOB.type}}}function isTextColumnType(e,t){switch(t){case`pg`:return c.test(e);case`mysql`:return l.test(e);default:return u.test(e)}}function binaryRepresentation(e,t,i){let s=n(t);if(s===void 0)return;if(i===`pg`)return e===a.BLOB.BYTEA.type?`bytes`:e===a.STRING.UUID.type&&(t===`uuid`||t===`uuidv7`)?`uuid`:void 0;if(i===`sqlite`)return e===r.BLOB.BLOB.type?`bytes`:void 0;if(e===o.BLOB.BLOB.type)return`bytes`;let c=d.exec(e);return c&&Number(c[1])===s?`bytes`:void 0}function idStorageOf(e,t,n){let r=i(t,n);if(r===void 0)return defaultIdStorage(e.format,n);let a=r.type;if(isTextColumnType(a,n))return{representation:`text`,columnType:a};let o=binaryRepresentation(a,e.format,n);return o===void 0?void 0:{representation:o,columnType:a}}function describeIdNativeTypes(e,t){let r=n(e),i=t===`pg`?`text, citext, varchar(n)`:t===`mysql`?`TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)`:`TEXT`;return r===void 0?i:`${t===`pg`?e===`uuid`||e===`uuidv7`?`uuid, bytea`:`bytea`:t===`mysql`?`BINARY(${r}), VARBINARY(${r}), BLOB`:`BLOB`}, ${i}`}function sqliteDateTimePhysicalForm(e){let t=i(e,`sqlite`);return t===void 0?`text`:t.type===`INTEGER`?`epochMillis`:t.type===`REAL`?`julianDay`:`text`}export{idStorageOf as a,idMemberDomainOfState as i,describeIdNativeTypes as n,idDomainOfState as r,sqliteDateTimePhysicalForm as t};
|
|
2
|
-
//# sourceMappingURL=physical-BkelResN.mjs.map
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./validation-Du6j0Q38.mjs";import{n}from"./base-vfur-DaU.mjs";import{n as r}from"./suppressed-failure-BPxfHTMc.mjs";import{n as i}from"./driver-options-DxlB1tms.mjs";const a=`SELECT pg_advisory_unlock_all()`;function unprovenLockStateError(e,r,o){return new t(`Driver "${e}" could not prove the advisory-lock state of a discarded migration session: its "${a}" reset failed. ${r}`,{code:n.CONNECTION_CLOSED,cause:i(o),meta:{driver:e,operation:`pinnedSession`}})}function condemnedSessionError(e){return new t(`Driver "${e}" will pin no further migration session: an earlier session's "${a}" reset failed, so the advisory-lock state of its one client is unknown. That client was not closed — it is the caller's database, not a pooled connection VibORM may discard — and ordinary queries on it are unaffected.`,{code:n.CONNECTION_CLOSED,meta:{driver:e,operation:`pinnedSession`}})}async function releaseReservedPostgresSession(e){if(!e.discard){e.release();return}try{await e.reset()}catch(t){let{closeOwnedTransport:n}=e;if(n===void 0)throw unprovenLockStateError(e.driverName,`The reserved connection was abandoned rather than returned to the pool. VibORM did not close the transport, which belongs to the caller, so the lock is freed when that connection is.`,t);try{await n()}catch(n){throw r(unprovenLockStateError(e.driverName,`The reserved connection was abandoned rather than returned to the pool, and ending the transport VibORM created for it FAILED: that backend may still be running, and any advisory lock it holds is freed only when it goes away. VibORM withdrew that transport and will not use it again.`,t),n)}throw unprovenLockStateError(e.driverName,`The reserved connection was abandoned rather than returned to the pool, and the transport VibORM created for it was closed — which ends that backend, and with it every advisory lock it held.`,t)}e.release()}const o=new WeakMap;function refuseCondemnedSession(e,t){if(t.condemned)throw condemnedSessionError(e)}function leasePinnedCommand(e,t,n){let r=physicalSessionState(t);refuseCondemnedSession(e,r);let i=r.queued.then(()=>(refuseCondemnedSession(e,r),n()));return r.queued=i.then(()=>void 0,()=>void 0),i}function condemnPhysicalSession(e){physicalSessionState(e).condemned=!0}function physicalSessionState(e){let t=o.get(e);if(t)return t;let n={queued:Promise.resolve(),condemned:!1};return o.set(e,n),n}export{unprovenLockStateError as i,leasePinnedCommand as n,releaseReservedPostgresSession as r,condemnPhysicalSession as t};
|
|
2
|
-
//# sourceMappingURL=pinned-session-Ca7C9yxY.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"pinned-session-Ca7C9yxY.mjs","names":[],"sources":["../src/drivers/shared/pinned-session.ts"],"sourcesContent":["import { ConnectionError, VibORMErrorCode } from \"@errors\";\nimport { errorCause } from \"./driver-options\";\nimport { withSuppressedFailure } from \"./suppressed-failure\";\n\n/** The PostgreSQL statement that resets a session's advisory-lock state. */\nconst ADVISORY_RESET = \"SELECT pg_advisory_unlock_all()\";\n\n/**\n * One reserved physical session, as a provider hands it back.\n *\n * The plan's requirement (§3.5) is \"one physical producer across decisions and\n * commit boundaries\": a session lock is session-scoped, so acquiring it through\n * one pooled connection and running the protected work through another protects\n * nothing and can strand the lock. A reservation is therefore a connection the\n * provider has taken OUT of its pool, plus the exact way to give it back.\n */\nexport interface PinnedSessionReservation<TSession> {\n /** The reserved producer. Every statement of the session runs on it. */\n readonly session: TSession;\n /**\n * Returns the producer to the provider.\n *\n * `discard` is true when the session's state is unknown — a failed unlock, a\n * failed cleanup, or a thrown body — and the provider must then destroy the\n * connection rather than hand a session carrying unknown state back to a\n * pool. A provider whose session can never be made clean again (MySQL2, which\n * has executed `USE` and possibly author-owned statements) destroys\n * unconditionally and ignores the flag.\n */\n release(discard: boolean): Promise<void>;\n}\n\n/**\n * The handle the pinned body uses to condemn its own producer.\n *\n * A thrown body already condemns the session. This exists for the case that\n * does not throw: an unlock statement that RETURNS a result proving the lock\n * was not released. That session is still usable in the provider's eyes and\n * would be returned to the pool holding a lock nobody owns.\n */\nexport interface PinnedSessionControl {\n /** Condemn this producer; it will be destroyed instead of released. */\n discard(): void;\n}\n\n/**\n * The refusal a discarded session whose reset FAILED raises.\n *\n * A session is discarded because its state is unknown, and the reset is what\n * makes it known again. When the reset fails too, the session may still hold\n * the migration lock every other command is excluded by — so it must not go\n * back to the provider, and saying nothing about that is not an option either:\n * a swallowed cleanup failure is how a pool ends up serving a connection that\n * blocks the next migration forever.\n *\n * The reset's own failure is the evidence, and it is the PROVIDER's value: it\n * goes through the one total normalizer rather than a bare `instanceof`, which\n * a rejection whose `getPrototypeOf` trap throws turns into a throw inside this\n * constructor — replacing the whole typed refusal with the trap's error.\n */\nexport function unprovenLockStateError(\n driverName: string,\n containment: string,\n cause: unknown\n): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" could not prove the advisory-lock state of a discarded migration session: its \"${ADVISORY_RESET}\" reset failed. ${containment}`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n cause: errorCause(cause),\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * The refusal raised afterwards by EVERY driver whose one client was condemned.\n *\n * A transport that pools connections recovers by reserving a different one, so\n * this is only for the driver whose single client IS the session: there is no\n * other connection to reach for, and running the next migration command on a\n * session that may still hold the lock is precisely what the condemnation\n * exists to prevent. Two drivers over that one client are two callers of this\n * same refusal, because the session they would both pin is the same session.\n */\nexport function condemnedSessionError(driverName: string): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" will pin no further migration session: an earlier session's \"${ADVISORY_RESET}\" reset failed, so the advisory-lock state of its one client is unknown. That client was not closed — it is the caller's database, not a pooled connection VibORM may discard — and ordinary queries on it are unaffected.`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * What was actually DONE about the abandoned connection, in the refusal's own\n * words.\n *\n * Three outcomes, three sentences, each chosen once the outcome is known\n * rather than once the ownership is known. A single sentence written before the\n * close was attempted claimed the backend had been ended even when ending it\n * threw — and the one thing a caller does with that claim is stop looking for a\n * connection that is still running, still holding the lock this refusal exists\n * to report.\n */\nconst CALLER_OWNED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool. VibORM did not close the transport, which belongs to the caller, so the lock is freed when that connection is.\";\nconst CLOSED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool, and the transport VibORM created for it was closed — which ends that backend, and with it every advisory lock it held.\";\nconst CLOSE_FAILED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool, and ending the transport VibORM created for it FAILED: that backend may still be running, and any advisory lock it holds is freed only when it goes away. VibORM withdrew that transport and will not use it again.\";\n\n/**\n * Returns a reserved PostgreSQL session to its pool, or condemns it — the ONE\n * rule for every provider that reserves a connection it cannot destroy.\n *\n * postgres.js and Bun SQL both expose `release()` and nothing else: there is no\n * destructive return to reach for, so a session whose reset failed is ABANDONED\n * — never released — which is the only way it stops being a connection the pool\n * will hand to the next caller.\n *\n * Abandoning it leaves the lock held until that backend goes away, so a\n * transport VibORM created is closed too: ending it terminates the backend, and\n * PostgreSQL frees every advisory lock the session held. A transport the CALLER\n * supplied is never closed for this — it is theirs, may be serving their own\n * code, and closing it to tidy up VibORM's cleanup failure would be a far\n * larger effect than the one being contained.\n */\nexport async function releaseReservedPostgresSession(reservation: {\n readonly driverName: string;\n readonly discard: boolean;\n /** Runs `SELECT pg_advisory_unlock_all()` on the reserved session. */\n readonly reset: () => Promise<unknown>;\n /** Hands the reserved session back to the provider's pool. */\n readonly release: () => void;\n /** Closes the transport, or absent when the CALLER owns it. */\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n}): Promise<void> {\n if (!reservation.discard) {\n reservation.release();\n return;\n }\n\n try {\n await reservation.reset();\n } catch (resetFailure) {\n const { closeOwnedTransport } = reservation;\n if (closeOwnedTransport === undefined) {\n throw unprovenLockStateError(\n reservation.driverName,\n CALLER_OWNED_CONTAINMENT,\n resetFailure\n );\n }\n try {\n await closeOwnedTransport();\n } catch (closeFailure) {\n // The reset stays primary — it is what the caller acts on — and the\n // close's own failure is cleanup evidence beside it.\n throw withSuppressedFailure(\n unprovenLockStateError(\n reservation.driverName,\n CLOSE_FAILED_CONTAINMENT,\n resetFailure\n ),\n closeFailure\n );\n }\n throw unprovenLockStateError(\n reservation.driverName,\n CLOSED_CONTAINMENT,\n resetFailure\n );\n }\n reservation.release();\n}\n\n/** What VibORM knows about one PHYSICAL session it pins commands on. */\ninterface PhysicalSessionState {\n /**\n * The pinned commands already queued on this session. It never rejects, so\n * one command's failure cannot poison the queue — the next command runs\n * either way, exactly as it would after a success.\n */\n queued: Promise<void>;\n /**\n * Set when a discarded session's advisory-lock reset failed, and never\n * cleared: nothing that happens later can prove a lock was released.\n */\n condemned: boolean;\n}\n\n/**\n * What is known about each PHYSICAL session, keyed on the session itself.\n *\n * A driver's connection queue serializes the commands of THAT driver. Two\n * drivers built over one supplied client — the documented shape for two\n * schema-scoped estates over one PGlite — own two queues and one session, so\n * the queue arbitrates nothing between them, and a PostgreSQL session advisory\n * lock is REENTRANT: the second command re-acquires the lock the first is\n * holding instead of waiting for it, then reads and writes inside the first\n * command's session. The client is the only thing both drivers agree on, so it\n * is what this is keyed on.\n *\n * The condemnation shares that key because it answers for the same subject: a\n * failed reset leaves the CLIENT's lock state unknown, not the wrapper's. Kept\n * on the driver instead, it was a fact the other wrappers over that client\n * never consulted, and their next command ran inside the session it condemned.\n *\n * Weak by construction: the entry dies with the client, and a client nobody\n * holds keeps nothing alive here.\n */\nconst PHYSICAL_SESSIONS = new WeakMap<object, PhysicalSessionState>();\n\n/**\n * Refuses a command on a session whose advisory-lock state was condemned.\n *\n * One refusal, read at two moments, and each covers what the other cannot. At\n * ADMISSION, so a session condemned before this command arrived refuses now\n * rather than behind a queue whose head may itself be waiting on the very lock\n * nobody can account for. At the FRONT of the queue, because condemnation lands\n * BETWEEN the two: the command ahead of this one is the one whose reset fails,\n * and this one was admitted while that session still looked accountable.\n */\nfunction refuseCondemnedSession(\n driverName: string,\n state: PhysicalSessionState\n): void {\n if (state.condemned) {\n throw condemnedSessionError(driverName);\n }\n}\n\n/**\n * Runs `command` exclusively on this physical session, when it may still be\n * pinned at all.\n *\n * The refusal is here rather than beside it because this is the one path every\n * pinned command over a shared session takes, and it lands before `command` —\n * so no body and no statement of the refused command reaches the client.\n */\nexport function leasePinnedCommand<T>(\n driverName: string,\n session: object,\n command: () => Promise<T>\n): Promise<T> {\n const state = physicalSessionState(session);\n refuseCondemnedSession(driverName, state);\n const next = state.queued.then(() => {\n refuseCondemnedSession(driverName, state);\n return command();\n });\n state.queued = next.then(\n () => undefined,\n () => undefined\n );\n return next;\n}\n\n/**\n * Records that this physical session's advisory-lock state can no longer be\n * accounted for — for every driver that reaches it, not only the one whose\n * reset failed.\n */\nexport function condemnPhysicalSession(session: object): void {\n physicalSessionState(session).condemned = true;\n}\n\n/** This session's state, created on first use and mutated in place after. */\nfunction physicalSessionState(session: object): PhysicalSessionState {\n const existing = PHYSICAL_SESSIONS.get(session);\n if (existing) {\n return existing;\n }\n const created: PhysicalSessionState = {\n queued: Promise.resolve(),\n condemned: false,\n };\n PHYSICAL_SESSIONS.set(session, created);\n return created;\n}\n"],"mappings":"kOAKA,MAAM,EAAiB,kCAuDvB,SAAgB,uBACd,EACA,EACA,EACiB,CACjB,OAAO,IAAI,EACT,WAAW,EAAW,mFAAmF,EAAe,kBAAkB,IAC1I,CACE,KAAM,EAAgB,kBACtB,MAAO,EAAW,EAAM,CACxB,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CACzD,CACF,CAaH,SAAgB,sBAAsB,EAAqC,CACzE,OAAO,IAAI,EACT,WAAW,EAAW,iEAAiE,EAAe,4NACtG,CACE,KAAM,EAAgB,kBACtB,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CACzD,CACF,CAqCH,eAAsB,+BAA+B,EASnC,CAChB,GAAI,CAAC,EAAY,QAAS,CACxB,EAAY,SAAS,CACrB,OAGF,GAAI,CACF,MAAM,EAAY,OAAO,OAClB,EAAc,CACrB,GAAM,CAAE,uBAAwB,EAChC,GAAI,IAAwB,IAAA,GAC1B,MAAM,uBACJ,EAAY,WACZ,yLACA,EACD,CAEH,GAAI,CACF,MAAM,GAAqB,OACpB,EAAc,CAGrB,MAAM,EACJ,uBACE,EAAY,WACZ,8RACA,EACD,CACD,EACD,CAEH,MAAM,uBACJ,EAAY,WACZ,iMACA,EACD,CAEH,EAAY,SAAS,CAsCvB,MAAM,EAAoB,IAAI,QAY9B,SAAS,uBACP,EACA,EACM,CACN,GAAI,EAAM,UACR,MAAM,sBAAsB,EAAW,CAY3C,SAAgB,mBACd,EACA,EACA,EACY,CACZ,IAAM,EAAQ,qBAAqB,EAAQ,CAC3C,uBAAuB,EAAY,EAAM,CACzC,IAAM,EAAO,EAAM,OAAO,UACxB,uBAAuB,EAAY,EAAM,CAClC,GAAS,EAChB,CAKF,MAJA,GAAM,OAAS,EAAK,SACZ,IAAA,OACA,IAAA,GACP,CACM,EAQT,SAAgB,uBAAuB,EAAuB,CAC5D,qBAAqB,EAAQ,CAAC,UAAY,GAI5C,SAAS,qBAAqB,EAAuC,CACnE,IAAM,EAAW,EAAkB,IAAI,EAAQ,CAC/C,GAAI,EACF,OAAO,EAET,IAAM,EAAgC,CACpC,OAAQ,QAAQ,SAAS,CACzB,UAAW,GACZ,CAED,OADA,EAAkB,IAAI,EAAS,EAAQ,CAChC"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{f as t,p as n}from"./validation-Du6j0Q38.mjs";import{n as r}from"./base-vfur-DaU.mjs";import{o as i}from"./sql--69HUgel.mjs";import{r as a}from"./adapter-internals-n3Mf3css.mjs";import{O as o,v as s}from"./geo-point-codec-DUTTtlav.mjs";import{c,t as l}from"./identifiers-By-JRCb5.mjs";import{t as u}from"./geo-area-codec-B4DRInvA.mjs";import{o as d}from"./native-types-veeTk36s.mjs";import{a as ee}from"./physical-BkelResN.mjs";import{t as f}from"./array-literal-D9FexFqy.mjs";import{A as p,C as m,D as h,E as g,N as _,O as v,S as y,T as b,_ as x,a as S,b as C,c as w,d as T,f as E,g as D,h as O,k,l as A,m as j,o as te,r as M,s as N,u as P,v as F,w as I,x as L,y as R}from"./batch-refs-BY51FIXm.mjs";import{t as z}from"./adapter-namespace-DMhEF6my.mjs";import{a as B,c as V,g as H,i as U,l as W,m as G,n as K,p as q,r as J,s as Y,t as X}from"./select-assembly-BgqlrePH.mjs";var Z=class JsonParameter{json;constructor(e){this.json=e,Object.freeze(this)}static from(e){let t=JSON.stringify(e);return t===void 0?void 0:new JsonParameter(t)}toString(){return this.json}toJSON(){return JSON.parse(this.json)}};const Q=l(`"`);function postgresLikeLiteral(e){return i`REPLACE(REPLACE(REPLACE(${e}, CHR(92), CHR(92) || CHR(92)), '%', CHR(92) || '%'), '_', CHR(92) || '_')`}function postgresJsonObject(e){if(e.length===0)return i.raw`'{}'::json`;let t=[],n=i.raw(e.length>50?`jsonb_build_object`:`json_build_object`);for(let r=0;r<e.length;r+=50){let a=e.slice(r,r+50).flatMap(([e,t])=>[i`${e}::text`,t]);t.push(i`${n}(${i.join(a,`, `)})`)}return t.length===1?t[0]:i`(${i.join(t,` || `)})::json`}const ne=G(e=>`${e}_pkey`),$={quotient:(e,t)=>i`div(${e}, ${t})`,remainder:(e,t)=>i`mod(${e}, ${t})`},re=/^(?:inet|cidr|macaddr8?|uuid|xml|tsvector|tsquery|bit|varbit)(?:\(|$)/i;var PostgresAdapter=class{geoPoint;constructor(e=`public`,t=!1){z(this,e,`postgresql`),this.identifiers=O(Q,this.namespace),q(this,t?this.#r():void 0),a(this,{batchRefs:this.#n,constraints:ne,select:this.#e.select})}raw=b();identifiers;literals={...k(),dateTime:e=>i`${c(e)}`,true:()=>i.raw`TRUE`,false:()=>i.raw`FALSE`,json:e=>i`${Z.from(e)}`,decimal:(e,t)=>i`CAST(${o(e,t,`text`)} AS ${i.raw(s(`pg`,t))})`,id:(e,t)=>t===`uuid`?i`CAST(${e} AS UUID)`:i`${e}`};operators={...w(),like:(e,t)=>i`${e} LIKE ${t} ESCAPE '\\'`,notLike:(e,t)=>i`${e} NOT LIKE ${t} ESCAPE '\\'`,ilike:(e,t)=>i`TRANSLATE(${e}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') LIKE TRANSLATE(${t}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') ESCAPE '\\'`,notIlike:(e,t)=>i`TRANSLATE(${e}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') NOT LIKE TRANSLATE(${t}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') ESCAPE '\\'`,containsText:(e,t)=>i`${e} LIKE ('%' || ${postgresLikeLiteral(t)} || '%') ESCAPE '\\'`,startsWithText:(e,t)=>i`${e} LIKE (${postgresLikeLiteral(t)} || '%') ESCAPE '\\'`,endsWithText:(e,t)=>i`${e} LIKE ('%' || ${postgresLikeLiteral(t)}) ESCAPE '\\'`,startsWithPrefix:(e,t,n)=>i`${this.expressions.caseSensitiveText(e,n,!0)} LIKE ${`${_(t)}%`} ESCAPE '\\'`,exactTextEq:(e,t,n)=>i`${this.expressions.caseSensitiveText(e,n,!1)} = ${t}`,exactTextIn:(e,t,n)=>i`${this.expressions.caseSensitiveText(e,n,!1)} IN ${t}`,...R(),...L(),...I(),...F(this.literals.true,this.literals.false),...j()};expressions={...N(),caseSensitiveText:(e,t,r=!1)=>{let a=d(t,`pg`)?.type;if(!r&&a?.toLowerCase()===`xml`)throw new n(`PostgreSQL XML has no equality or ordering operator; use a text pattern filter or raw SQL.`,{meta:{dialect:`pg`,scalarType:`string`}});return r&&a&&re.test(a)?i`CAST(${e} AS TEXT)`:e},asciiCaseFold:e=>i`TRANSLATE(${e}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')`,concat:(...e)=>e.length===0?i.raw`''`:e.length===1?e[0]:i`(${i.join(e,` || `)})`,greatest:(...e)=>i`GREATEST(${i.join(e,`, `)})`,least:(...e)=>i`LEAST(${i.join(e,`, `)})`,integerDivide:(e,t)=>i`(${e} / ${t})`,decimalCast:(e,t)=>i`CAST(${e} AS ${i.raw(s(`pg`,t))})`,idCast:(e,t)=>t===`bytes`?i`decode(${e}, 'hex')`:i`CAST(${e} AS ${i.raw(t===`uuid`?`UUID`:`TEXT`)})`,cast:te({text:`TEXT`,integer:`INTEGER`,bigint:`BIGINT`,boolean:`BOOLEAN`,numeric:`NUMERIC`}),blobToHex:e=>i`encode(${e}, 'hex')`};aggregates={...S(),min:(e,t=!1)=>t?i`BOOL_AND(${e})`:i`MIN(${e})`,max:(e,t=!1)=>t?i`BOOL_OR(${e})`:i`MAX(${e})`,decimalAvg:(e,t)=>Y($,e,t),decimalSumOperandPrecision:T(1e3)};json={equals:(e,t)=>i`(${e})::jsonb = (${t})::jsonb`,boolean:e=>e,document:e=>e,number:e=>e,object:postgresJsonObject,array:e=>e.length===0?i.raw`'[]'::json`:i`json_build_array(${i.join(e,`, `)})`,emptyArray:()=>i.raw`'[]'::json`,agg:e=>i`COALESCE(json_agg(${e}), '[]'::json)`,objectFromColumns:postgresJsonObject,extract:(e,t)=>i`(${e})::jsonb#>${t}::text[]`,extractText:(e,t)=>i`(${e})::jsonb#>>${t}::text[]`,numberAtPath:(e,t)=>i`(CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'number' THEN ((${e})::jsonb#>>${t}::text[])::double precision END)`,stringAtPath:(e,t)=>i`((CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'string' THEN (${e})::jsonb#>>${t}::text[] END) COLLATE "C")`,contains:(e,t)=>i`(${e})::jsonb @> ${t}`,lastElement:e=>i`(${e})::jsonb -> -1`,value:e=>i`${Z.from(e)}`};arrays={literal:e=>e.length===0?i.raw`'{}'`:i`ARRAY[${i.join(e,`, `)}]`,value:(e,t)=>i`${t?e.map(e=>typeof e==`string`?c(e):e):e}`,enumValue:e=>i`${f(e)}`,has:(e,t)=>i`${t} = ANY(${e})`,hasEvery:(e,t)=>i`${e} @> ${t}`,hasSome:(e,t)=>i`${e} && ${t}`,isEmpty:e=>i`(cardinality(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>i`CAST(${e} AS TEXT[])`,length:e=>i`cardinality(${e})`,get:(e,t)=>i`${e}[${t}]`,push:(e,t)=>i`array_append(${e}, ${t})`,set:(e,t,n)=>i`${e}[:${t}-1] || ARRAY[${n}] || ${e}[${t}+1:]`};orderBy={...E(),nullsFirst:(e,t)=>t===`desc`?i`${e} DESC NULLS FIRST`:i`${e} ASC NULLS FIRST`,nullsLast:(e,t)=>t===`desc`?i`${e} DESC NULLS LAST`:i`${e} ASC NULLS LAST`};clauses=v();set={...y(),multiply:(e,t,n)=>n?.decimal?W($,e,t,n.decimal):i`${e} = ${e} * ${t}`,divide:(e,t,n)=>n?.decimal?V($,e,t,n.decimal):i`${e} = ${e} / ${t}`,push:(e,t)=>i`${e} = array_cat(COALESCE(${e}, '{}'), ${t})`,unshift:(e,t)=>i`${e} = array_cat(${t}, COALESCE(${e}, '{}'))`};filters=g();subqueries=p(Q);#e={select:e=>e.distinct&&e.orderBy?X(e,e.distinct,this.identifiers.escape):K(e.distinct?i`SELECT DISTINCT ON (${e.distinct}) ${e.columns}`:i`SELECT ${e.columns}`,e,{forUpdate:`append`})};cte=P(Q);mutations={skipDuplicatesStrategy:`sql`,insert:D(Q),insertDefault:e=>i`INSERT INTO ${e} DEFAULT VALUES`,...C(),returning:e=>i`RETURNING ${e}`,...m()};assertions={exists:e=>i`SELECT 1 / CASE WHEN EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`,notExists:e=>i`SELECT 1 / CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`};joins={...A(),full:(e,t)=>i`FULL OUTER JOIN ${e} ON ${t}`,...x(Q)};setOperations=h();capabilities={supportsReturning:!0,supportsCteWithMutations:!0,supportsFullOuterJoin:!0,supportsLateralJoins:!0,supportsVector:!1,supportsUpsertWhere:!0,supportsTargetedUpsert:!0,supportsMutationTargetInSubquery:!0,supportsMutationRowLimit:!1,supportsRowLocks:!0};lastInsertId=()=>i.raw`lastval()`;#t=M({table:i.raw`"__viborm_batch_refs"`,batchIdColumn:i.raw`"batch_id"`,keyColumn:i.raw`"ref_key"`,valueColumn:i.raw`"ref_value"`,createTable:i.raw`CREATE TEMP TABLE IF NOT EXISTS "__viborm_batch_refs" ("batch_id" TEXT NOT NULL, "ref_key" TEXT NOT NULL, "ref_value" TEXT, PRIMARY KEY ("batch_id", "ref_key"))`,castValue:e=>i`CAST((${e}) AS TEXT)`,storeReturning:(e,t,n,r)=>i`WITH "__viborm_inserted" AS (${n} RETURNING ${r}) INSERT INTO "__viborm_batch_refs" ("batch_id", "ref_key", "ref_value") SELECT ${e}, ${t}, CAST(${r} AS TEXT) FROM "__viborm_inserted"`});#n=(()=>{let e=this.#t,t=this.capabilities;return{setup:e.setup,clear:e.clear,cleanup:e.cleanup,store:e.store,read:e.read,get storeReturning(){return t.supportsCteWithMutations?e.storeReturning:void 0},get storeInsertedKey(){return t.supportsCteWithMutations?e.storeInsertedKey:void 0}}})();vector={literal:e=>{if(e.some(e=>!Number.isFinite(Math.fround(e))))throw new t(`PostgreSQL vector components must fit a finite float32 value.`,{code:r.INVALID_INPUT});return i`${`[${e.join(`,`)}]`}::vector`},l2:(e,t)=>i`${e} <-> ${t}`,cosine:(e,t)=>i`NULLIF(${e} <=> ${t}, 'NaN'::double precision)`};#r(){let longitude=e=>i`ST_X(${e}::geometry)`,latitude=e=>i`ST_Y(${e}::geometry)`;return{value:(e,t)=>i`ST_SetSRID(ST_MakePoint(${e}, ${t}), 4326)::geography`,longitude,latitude,...J(longitude,latitude,this.operators,(e,t)=>{let n=U(t);if(n.length!==0)return this.operators.or(...n.map(t=>i`${e} && ST_SetSRID(ST_GeomFromGeoJSON(${t}), 4326)::geography`))}),withinPolygon:(e,t)=>i`ST_Intersects(${i`ST_SetSRID(ST_GeomFromGeoJSON(${B(t)}), 4326)::geography`}, ${e})`,distance:(e,t)=>{let n=i`RADIANS(ST_X(${e}::geometry))`,r=i`RADIANS(ST_Y(${e}::geometry))`,a=i`RADIANS(ST_X(${t}::geometry))`,o=i`RADIANS(ST_Y(${t}::geometry))`;return i`CASE WHEN ${e} IS NULL OR ${t} IS NULL THEN NULL ELSE CAST(${u} AS double precision) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${i`POWER(SIN((${o} - ${r}) / 2), 2) + COS(${r}) * COS(${o}) * POWER(SIN((${a} - ${n}) / 2), 2)`})))) END`}}}result={nativeScalarPassthrough:!0,enumListRepresentation:`arrayText`,idRepresentation:(e,t)=>ee(e,t,`pg`)?.representation??`text`,parseResult:H,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>n()}};export{PostgresAdapter as t};
|
|
2
|
-
//# sourceMappingURL=postgres-adapter-T2Iko-vt.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-adapter-T2Iko-vt.mjs","names":["sql","#createGeoPointSql","#batchRefs","#assemble","#cteBatchRefs"],"sources":["../src/sql/json-parameter.ts","../src/adapters/databases/postgres/postgres-adapter.ts"],"sourcesContent":["/**\n * One JSON document, bound as one statement parameter.\n *\n * PostgreSQL's JSON literals bind CANONICAL JSON TEXT and let the server cast\n * that text from the parameter's column context. Nothing at the driver can\n * tell that text apart from an ordinary string, so every transport that\n * re-serializes a `json`/`jsonb` parameter has to be told not to, and only some\n * of them offer a place to say it: postgres.js takes a `json` type override\n * (`src/drivers/postgres/index.ts`), PGlite's own JSON serializer already\n * passes strings through, and node-postgres/Neon never touch a string. Bun SQL\n * offers no such hook and JSON-ENCODES a string bound to a `json`/`jsonb`\n * parameter, storing the physical document `\"[1,2,3]\"` — a JSON string — where\n * `[1,2,3]` was meant (upstream Drizzle #5287).\n *\n * This carrier is the missing distinction, and it needs no per-transport hook:\n * a PostgreSQL transport can only reach a bound value through string coercion\n * or through JSON serialization, and this renders as its canonical text under\n * BOTH. The text captured at construction is the ONE stored fact: `toJSON`\n * answers it parsed back, and `JSON.stringify` of its own output re-serializes\n * to those exact bytes, so both protocols agree even if the caller mutates the\n * original value after binding.\n * Bun, which serializes an object parameter for a `json`/`jsonb` column with\n * `JSON.stringify`, therefore stores the exact document for every JSON type,\n * including the number, boolean and null primitives that no bare JavaScript\n * value can express to it (a JS number is bound as `integer`, `null` as SQL\n * NULL).\n *\n * `json` is an own property rather than a private field because it is what a\n * parameter snapshot shows: diagnostics read own properties, so an opted-in\n * `includeParams` disclosure keeps the document instead of reporting `{}`.\n */\nexport class JsonParameter {\n /** The canonical JSON text — `JSON.stringify(value)`. */\n readonly json: string;\n\n private constructor(json: string) {\n this.json = json;\n Object.freeze(this);\n }\n\n /**\n * The carrier for `value`, or `undefined` when `JSON.stringify` has no text\n * for it (`undefined`, a function, a symbol). Those bound `undefined`\n * directly before this carrier existed, which providers send as SQL NULL;\n * carrying them would bind the text `\"undefined\"` instead.\n */\n static from(value: unknown): JsonParameter | undefined {\n // The lib signature says `string`, which is only true for the values it can\n // represent.\n const json: string | undefined = JSON.stringify(value);\n return json === undefined ? undefined : new JsonParameter(json);\n }\n\n toString(): string {\n return this.json;\n }\n\n toJSON(): unknown {\n return JSON.parse(this.json);\n }\n}\n","import {\n QueryError,\n UnsupportedOperationError,\n VibORMErrorCode,\n} from \"@errors\";\nimport {\n type NativeTypeDeclaration,\n nativeTypeFor,\n} from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { type Sql, sql } from \"@sql\";\nimport { encodePostgresTemporal } 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 { JsonParameter } from \"../../../sql/json-parameter\";\nimport type {\n ArithmeticTarget,\n BatchReferenceSqlAdapter,\n} from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport { installAdapterNamespace } from \"../../adapter-namespace\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport { passThroughParseResult } from \"../../adapter-result-parser\";\nimport { createNamedConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n} from \"../../database-adapter\";\nimport { createOnConflictBatchRefs } from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n logicalDecimalAverage,\n logicalDecimalDivide,\n logicalDecimalMultiply,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoBoundsIndexPolygons,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDecimalSumOperandPrecision,\n createDirectionOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLateralJoins,\n createLogicalOperators,\n createMembershipOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createOnConflictBuilders,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n} from \"../../shared/standard-sql\";\nimport { arrayLiteralText } from \"./array-literal\";\n\nconst quoteIdent = createIdentifierQuoter('\"');\nfunction postgresLikeLiteral(value: Sql): Sql {\n return sql`REPLACE(REPLACE(REPLACE(${value}, CHR(92), CHR(92) || CHR(92)), '%', CHR(92) || '%'), '_', CHR(92) || '_')`;\n}\nfunction postgresJsonObject(pairs: [string, Sql][]): Sql {\n if (pairs.length === 0) return sql.raw`'{}'::json`;\n const chunks: Sql[] = [];\n const buildObject = sql.raw(\n pairs.length > 50 ? \"jsonb_build_object\" : \"json_build_object\"\n );\n // PostgreSQL limits a function call to 100 arguments. Chunking preserves\n // the surrounding aggregate scope, unlike moving values into a subquery.\n for (let start = 0; start < pairs.length; start += 50) {\n const args = pairs\n .slice(start, start + 50)\n .flatMap(([key, value]) => [sql`${key}::text`, value]);\n chunks.push(sql`${buildObject}(${sql.join(args, \", \")})`);\n }\n return chunks.length === 1\n ? chunks[0]!\n : sql`(${sql.join(chunks, \" || \")})::json`;\n}\nconst POSTGRES_CONSTRAINTS = createNamedConstraintIdentities(\n (tableName) => `${tableName}_pkey`\n);\n\n/**\n * `div`/`mod` rather than `/` and a hand-rolled remainder: both are exact on\n * `numeric` for any operand, including a fractional divisor, and `div`\n * truncates toward zero — which is what the half-even rule's quotient means.\n * `/` on numerics picks its own result scale and would round the last digit.\n */\nconst POSTGRES_INTEGERS: ExactIntegerArithmetic = {\n quotient: (n: Sql, d: Sql): Sql => sql`div(${n}, ${d})`,\n remainder: (n: Sql, d: Sql): Sql => sql`mod(${n}, ${d})`,\n};\n\n/** The two characters PostgreSQL reads structurally inside a quoted member. */\n\n/**\n * PostgreSQL's own text spelling of one list, for a column whose element type\n * the driver cannot serialize.\n *\n * Every member is quoted, so a member that is empty, spells `NULL`, or holds a\n * brace, comma, quote or backslash is still exactly one member: those are the\n * only characters the server reads structurally, and quoting makes the reading\n * unambiguous without a per-member decision.\n */\n\n/**\n * PostgreSQL Database Adapter\n *\n * Implements the DatabaseAdapter interface for PostgreSQL-specific SQL generation.\n *\n * Key PostgreSQL features:\n * - Double-quote identifier escaping: \"table\".\"column\"\n * - Native ARRAY type with operators: @>, &&, ANY()\n * - ILIKE for case-insensitive matching\n * - json_build_object(), json_agg() for JSON operations\n * - RETURNING clause for mutations\n * - NULLS FIRST/LAST ordering\n * - ON CONFLICT DO UPDATE/NOTHING\n */\nconst NON_TEXT_STRING_TYPE =\n /^(?:inet|cidr|macaddr8?|uuid|xml|tsvector|tsquery|bit|varbit)(?:\\(|$)/i;\n\nexport class PostgresAdapter implements DatabaseAdapter {\n // ============================================================\n // NAMESPACE\n // ============================================================\n\n /**\n * The bound schema. PostgreSQL always qualifies, so this adapter has no\n * unbound mode: an omitted or explicitly `undefined` argument means the\n * `public` schema, whatever a connection's `search_path` says.\n */\n declare readonly namespace: string;\n readonly geoPoint: GeoPointSql | undefined;\n\n constructor(namespace = \"public\", postgis = false) {\n installAdapterNamespace(this, namespace, \"postgresql\");\n // Reads the installed value, so it cannot be a field initializer: those run\n // before the constructor body.\n this.identifiers = createIdentifiers(quoteIdent, this.namespace);\n installGeoPointSql(this, postgis ? this.#createGeoPointSql() : undefined);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: POSTGRES_CONSTRAINTS,\n select: this.#assemble.select,\n });\n }\n\n // ============================================================\n // RAW\n // ============================================================\n\n raw = createRawSql();\n\n // ============================================================\n // IDENTIFIERS\n // ============================================================\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n // ============================================================\n // LITERALS\n // ============================================================\n\n literals = {\n ...createStandardLiterals(),\n\n dateTime: (iso: string): Sql => sql`${encodePostgresTemporal(iso)}`,\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // Serialized JSON text — PG casts the param to json/jsonb from the column\n // context. Stringifying (not raw binding) keeps primitives valid: a bare\n // 'hello' is not valid JSON input, '\"hello\"' is. The carrier is what tells\n // a transport that this text is already a document; see json-parameter.ts.\n json: (v: unknown): Sql => sql`${JsonParameter.from(v)}`,\n\n // Cast into the operand's own `NUMERIC(p,s)` domain, the same type the DDL\n // emits for the field. PostgreSQL would usually infer `numeric` from the\n // column context anyway; saying it makes the comparison independent of what\n // the surrounding expression does to the operand's inferred type, and\n // naming the precision keeps the operand and the column one domain rather\n // than two that happen to agree.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${encodePhysicalDecimal(canonical, descriptor, \"text\")} AS ${sql.raw(decimalColumnType(\"pg\", descriptor))})`,\n\n // A `uuid` column takes canonical text and is TYPED: PostgreSQL has no\n // `uuid = text` operator, so an untyped operand raises 42883 rather than\n // comparing. `bytea` takes the payload's bytes as an ordinary binary\n // parameter — the same parameter every blob scalar already binds — and a\n // text-stored domain takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n representation: IdRepresentation\n ): Sql =>\n representation === \"uuid\"\n ? sql`CAST(${physical} AS UUID)`\n : sql`${physical}`,\n };\n\n // ============================================================\n // OPERATORS\n // ============================================================\n\n operators = {\n // Comparison\n ...createComparisonOperators(),\n\n // Pattern matching\n // Explicit ESCAPE '\\' pairs with wildcard escaping in the where-builder\n like: (column: Sql, pattern: Sql): Sql =>\n sql`${column} LIKE ${pattern} ESCAPE '\\\\'`,\n notLike: (column: Sql, pattern: Sql): Sql =>\n sql`${column} NOT LIKE ${pattern} ESCAPE '\\\\'`,\n ilike: (column: Sql, pattern: Sql): Sql =>\n sql`TRANSLATE(${column}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') LIKE TRANSLATE(${pattern}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') ESCAPE '\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`TRANSLATE(${column}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') NOT LIKE TRANSLATE(${pattern}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') ESCAPE '\\\\'`,\n containsText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ('%' || ${postgresLikeLiteral(value)} || '%') ESCAPE '\\\\'`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE (${postgresLikeLiteral(value)} || '%') ESCAPE '\\\\'`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ('%' || ${postgresLikeLiteral(value)}) ESCAPE '\\\\'`,\n // PostgreSQL is the one dialect where the escaped LIKE spelling is both\n // exact and index-usable, so it stands alone here: `LIKE` is case- and\n // accent-sensitive natively, which is the contract `startsWithText` holds,\n // and `match_pattern_prefix` extracts `name >= 'x' AND name < 'y'` from the\n // constant-folded pattern even though it arrives as a bound parameter.\n //\n // THE INDEX RANGE HAS A COLLATION PRECONDITION, and the common case does\n // not meet it. Measured, 20k rows, plain btree index:\n // - C-collated database (PGlite, `datcollate = 'C'`): Bitmap Index Scan\n // over 111 rows, where `LEFT(col, LENGTH($1)) = $1` is a Seq Scan over\n // all 20000.\n // - `en_US.utf8` (postgres:16 — the project's own test container, and\n // what a default `initdb` produces): BOTH spellings Seq Scan. Only a\n // `(col text_pattern_ops)` index ranges, and `generateCreateIndex`\n // (src/migrations/drivers/postgres/index.ts) emits no opclass, so\n // viborm cannot create one.\n // What survives on a default-locale cluster — and the reason this spelling\n // still stands there — is the row estimate: `LIKE` tracks the data\n // (202/1010/11111/19998 against truths 111/1111/11111/20000) while\n // `LEFT(...)` is an opaque function estimated at a flat 100 for every\n // prefix width, a 111x error at `name1%` that propagates into the row\n // estimate of any join above it. It is never worse than the spelling it\n // replaced on any measured leg. Full record: Decision 7.3 in\n // docs/architecture/query-performance-plan.md.\n startsWithPrefix: (\n column: Sql,\n value: string,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, true)} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\'`,\n\n // Preserve native equality and indexes; the shared text boundary refuses\n // native types such as XML that cannot express an exact comparison.\n exactTextEq: (\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, false)} = ${value}`,\n exactTextIn: (\n column: Sql,\n values: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, false)} IN ${values}`,\n\n // Set membership — values is a parenthesized list from literals.list(),\n // so ANY/ALL (which need an array) would produce invalid SQL here\n ...createMembershipOperators(),\n\n // Null checks\n ...createNullOperators(),\n\n // Range\n ...createRangeOperators(),\n\n // Logical\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n // Subquery existence\n ...createExistenceOperators(),\n };\n\n // ============================================================\n // EXPRESSIONS\n // ============================================================\n\n expressions = {\n ...createCommonExpressions(),\n\n caseSensitiveText: (\n expr: Sql,\n nativeType?: NativeTypeDeclaration,\n textOperation = false\n ): Sql => {\n const type = nativeTypeFor(nativeType, \"pg\")?.type;\n if (!textOperation && type?.toLowerCase() === \"xml\")\n throw new UnsupportedOperationError(\n \"PostgreSQL XML has no equality or ordering operator; use a text pattern filter or raw SQL.\",\n { meta: { dialect: \"pg\", scalarType: \"string\" } }\n );\n return textOperation && type && NON_TEXT_STRING_TYPE.test(type)\n ? sql`CAST(${expr} AS TEXT)`\n : expr;\n },\n asciiCaseFold: (expr: Sql): Sql =>\n sql`TRANSLATE(${expr}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')`,\n\n // String concatenation via ||\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw`''`;\n if (parts.length === 1) return parts[0]!;\n return sql`(${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 // PostgreSQL integer division already truncates toward zero, which is why\n // `set.divide` ignores `target.integer` here as well. Casting either side\n // would narrow a `bigint` operand to `int4`.\n integerDivide: (left: Sql, right: Sql): Sql => sql`(${left} / ${right})`,\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${expr} AS ${sql.raw(decimalColumnType(\"pg\", descriptor))})`,\n\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`decode(${expr}, 'hex')`\n : sql`CAST(${expr} AS ${sql.raw(\n representation === \"uuid\" ? \"UUID\" : \"TEXT\"\n )})`,\n\n // PostgreSQL type mappings\n cast: createCastExpression({\n text: \"TEXT\",\n integer: \"INTEGER\",\n bigint: \"BIGINT\",\n boolean: \"BOOLEAN\",\n numeric: \"NUMERIC\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`encode(${expr}, 'hex')`,\n };\n\n // ============================================================\n // AGGREGATES\n // ============================================================\n\n aggregates = {\n ...createAggregateFunctions(),\n\n min: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOL_AND(${column})` : sql`MIN(${column})`,\n max: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOL_OR(${column})` : sql`MAX(${column})`,\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n logicalDecimalAverage(POSTGRES_INTEGERS, column, descriptor),\n\n // `sum(numeric)` is itself unbounded on PostgreSQL; 1000 is the widest\n // `NUMERIC(p,s)` an operand can be CAST into to meet it, which is the\n // domain a comparison against that sum is actually limited by.\n decimalSumOperandPrecision: createDecimalSumOperandPrecision(1000),\n };\n\n // ============================================================\n // JSON\n // ============================================================\n\n json = {\n equals: (left: Sql, right: Sql): Sql =>\n sql`(${left})::jsonb = (${right})::jsonb`,\n boolean: (condition: Sql): Sql => condition,\n document: (expression: Sql): Sql => expression,\n number: (expression: Sql): Sql => expression,\n\n object: postgresJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`'[]'::json`;\n return sql`json_build_array(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw`'[]'::json`,\n\n agg: (expr: Sql): Sql => sql`COALESCE(json_agg(${expr}), '[]'::json)`,\n\n objectFromColumns: postgresJsonObject,\n\n // #>/#>> with a text[] param handles every path shape uniformly:\n // '{}' returns the document root, and integer segments address array\n // elements (a single-segment `-> '0'` would only match an object key)\n extract: (column: Sql, path: string[]): Sql =>\n sql`(${column})::jsonb#>${path}::text[]`,\n\n extractText: (column: Sql, path: string[]): Sql =>\n sql`(${column})::jsonb#>>${path}::text[]`,\n\n // jsonb_typeof gates the cast: a non-number (or an absent path, where\n // jsonb_typeof is NULL) short-circuits to NULL instead of raising\n // \"invalid input syntax for type double precision\"\n numberAtPath: (column: Sql, path: string[]): Sql =>\n sql`(CASE WHEN jsonb_typeof((${column})::jsonb#>${path}::text[]) = 'number' THEN ((${column})::jsonb#>>${path}::text[])::double precision END)`,\n\n // COLLATE \"C\" pins byte (= code point) ordering; the database's default\n // collation (en_US.UTF-8 and friends) orders 'a' before 'B', which would\n // make < / > disagree with MySQL and SQLite\n stringAtPath: (column: Sql, path: string[]): Sql =>\n sql`((CASE WHEN jsonb_typeof((${column})::jsonb#>${path}::text[]) = 'string' THEN (${column})::jsonb#>>${path}::text[] END) COLLATE \"C\")`,\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`(${target})::jsonb @> ${value}`,\n\n lastElement: (target: Sql): Sql => sql`(${target})::jsonb -> -1`,\n\n // Serialized JSON text, same format literals.json writes — PG casts the\n // param to jsonb from the comparison context\n value: (v: unknown): Sql => sql`${JsonParameter.from(v)}`,\n };\n\n // ============================================================\n // ARRAYS (Native PostgreSQL arrays)\n // ============================================================\n\n arrays = {\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`'{}'`;\n return sql`ARRAY[${sql.join(items, \", \")}]`;\n },\n\n // Native array parameter; drivers serialize JS arrays to PG array format\n value: (values: unknown[], temporal?: \"date\" | \"datetime\"): Sql =>\n sql`${temporal ? values.map((value) => (typeof value === \"string\" ? encodePostgresTemporal(value) : value)) : values}`,\n\n // One untyped parameter holding PostgreSQL's own array literal. A managed\n // enum's array OID is created by the estate, so no driver has a serializer\n // for it and the native parameter above arrives malformed; an unknown\n // parameter instead takes its type from the column or operand it meets,\n // which is how the enum type is reached without naming it here.\n enumValue: (values: unknown[]): Sql => sql`${arrayLiteralText(values)}`,\n\n has: (column: Sql, value: Sql): Sql => sql`${value} = ANY(${column})`,\n\n hasEvery: (column: Sql, values: Sql): Sql => sql`${column} @> ${values}`,\n\n hasSome: (column: Sql, values: Sql): Sql => sql`${column} && ${values}`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(cardinality(${column}) = 0 OR ${column} IS NULL)`,\n\n // `numeric[]::text[]` casts every ELEMENT. `numeric[]::text` would produce\n // one string holding PostgreSQL's array literal, and `to_json(numeric[])`\n // JSON numbers — the two spellings a decimal list cannot survive.\n exactNumericProjection: (column: Sql): Sql =>\n sql`CAST(${column} AS TEXT[])`,\n\n length: (column: Sql): Sql => sql`cardinality(${column})`,\n\n get: (column: Sql, index: Sql): Sql => sql`${column}[${index}]`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`array_append(${column}, ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`${column}[:${index}-1] || ARRAY[${value}] || ${column}[${index}+1:]`,\n };\n\n // ============================================================\n // ORDER BY\n // ============================================================\n\n orderBy = {\n ...createDirectionOrderBy(),\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS FIRST`\n : sql`${column} ASC NULLS FIRST`,\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS LAST`\n : sql`${column} ASC NULLS LAST`,\n };\n\n // ============================================================\n // CLAUSES\n // ============================================================\n\n clauses = createStandardClauses();\n\n // ============================================================\n // SET (UPDATE operations)\n // ============================================================\n\n set = {\n ...createNumericSetOperations(),\n\n // A decimal target rounds the product/quotient back to the field's scale\n // half-to-even; every other numeric column keeps PostgreSQL's own\n // arithmetic, whose integer division already truncates toward zero.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalMultiply(POSTGRES_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalDivide(POSTGRES_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} / ${by}`,\n\n // `values` is already the destination field's one complete list crossing:\n // a native array parameter for ordinary lists or an untyped PostgreSQL\n // array literal for managed enums. `array_cat` lets the column resolve that\n // one parameter's exact array type and keeps bind/SQL size constant.\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = array_cat(COALESCE(${column}, '{}'), ${values})`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = array_cat(${values}, COALESCE(${column}, '{}'))`,\n };\n\n // ============================================================\n // FILTERS (Relation subquery wrappers)\n // ============================================================\n\n filters = createRelationFilters();\n\n // ============================================================\n // SUBQUERIES\n // ============================================================\n\n subqueries = createSubqueries(quoteIdent);\n\n // ============================================================\n // ASSEMBLE (Build complete SQL statements)\n // ============================================================\n\n readonly #assemble = {\n select: (parts: QueryParts): Sql => {\n // DISTINCT ON requires ORDER BY to lead with the distinct columns, which\n // would override the user's ordering — emulate via ROW_NUMBER() instead\n if (parts.distinct && parts.orderBy) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape\n );\n }\n\n // PostgreSQL supports DISTINCT ON (columns)\n const selectClause = parts.distinct\n ? sql`SELECT DISTINCT ON (${parts.distinct}) ${parts.columns}`\n : sql`SELECT ${parts.columns}`;\n\n return assembleSelectQuery(selectClause, parts, { forUpdate: \"append\" });\n },\n };\n\n // ============================================================\n // CTE (Common Table Expressions)\n // ============================================================\n\n cte = createCteBuilders(quoteIdent);\n\n // ============================================================\n // MUTATIONS\n // ============================================================\n\n mutations = {\n skipDuplicatesStrategy: \"sql\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql =>\n sql`INSERT INTO ${table} DEFAULT VALUES`,\n\n ...createMutationCommands(),\n\n returning: (columns: Sql): Sql => sql`RETURNING ${columns}`,\n\n ...createOnConflictBuilders(),\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT 1 / CASE WHEN EXISTS (${query}) THEN 1 ELSE 0 END AS \"__viborm_assert__\"`,\n notExists: (query: Sql): Sql =>\n sql`SELECT 1 / CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE 0 END AS \"__viborm_assert__\"`,\n };\n\n // ============================================================\n // JOINS\n // ============================================================\n\n joins = {\n ...createCoreJoins(),\n\n full: (table: Sql, condition: Sql): Sql =>\n sql`FULL OUTER JOIN ${table} ON ${condition}`,\n\n ...createLateralJoins(quoteIdent),\n };\n\n // ============================================================\n // SET OPERATIONS\n // ============================================================\n\n setOperations = createSetOperations();\n\n // ============================================================\n // CAPABILITIES\n // ============================================================\n\n capabilities = {\n supportsReturning: true,\n supportsCteWithMutations: true,\n supportsFullOuterJoin: true,\n supportsLateralJoins: true,\n supportsVector: false,\n supportsUpsertWhere: true, // PostgreSQL supports WHERE in ON CONFLICT\n supportsTargetedUpsert: true, // ON CONFLICT (cols) arbitrates on those cols\n supportsMutationTargetInSubquery: true,\n supportsMutationRowLimit: false, // PostgreSQL has no UPDATE/DELETE ... LIMIT\n supportsRowLocks: true,\n };\n\n lastInsertId = (): Sql => sql.raw`lastval()`;\n\n readonly #cteBatchRefs = createOnConflictBatchRefs({\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 // The table is not ON COMMIT DROP, so it survives the native batch that\n // created it (D-50); the scratch itself belongs to the dispatched batch —\n // each batch stores its own reference rows, reads back what it stored at\n // its own end and deletes them there (D-58), so a later batch never names\n // a reference an earlier one stored. The table lingers on the session like\n // the SQLite and MySQL scratch tables do.\n createTable: sql.raw`CREATE TEMP TABLE IF NOT EXISTS \"__viborm_batch_refs\" (\"batch_id\" TEXT NOT NULL, \"ref_key\" TEXT NOT NULL, \"ref_value\" TEXT, PRIMARY KEY (\"batch_id\", \"ref_key\"))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS TEXT)`,\n // The exact identity of an INSERT, carried by the statement that runs it:\n // the INSERT is the data-modifying CTE, its RETURNING feeds the reference\n // row, and nothing session-global (lastval) is read.\n storeReturning: (batchId, key, insert, column) =>\n sql`WITH \"__viborm_inserted\" AS (${insert} RETURNING ${column}) INSERT INTO \"__viborm_batch_refs\" (\"batch_id\", \"ref_key\", \"ref_value\") SELECT ${batchId}, ${key}, CAST(${column} AS TEXT) FROM \"__viborm_inserted\"`,\n });\n\n // Whether this provider can mutate inside a CTE is the capability's fact,\n // read live: the CTE store and the key store it derives are offered only\n // while `capabilities.supportsCteWithMutations` holds, and a PostgreSQL\n // without it offers no exact key store at all (lastval() is not exact).\n readonly #batchRefs: BatchReferenceSqlAdapter = (() => {\n const withCte = this.#cteBatchRefs;\n const capabilities = this.capabilities;\n return {\n setup: withCte.setup,\n clear: withCte.clear,\n cleanup: withCte.cleanup,\n store: withCte.store,\n read: withCte.read,\n get storeReturning() {\n return capabilities.supportsCteWithMutations\n ? withCte.storeReturning\n : undefined;\n },\n get storeInsertedKey() {\n return capabilities.supportsCteWithMutations\n ? withCte.storeInsertedKey\n : undefined;\n },\n };\n })();\n\n // ============================================================\n // VECTOR (pgvector)\n // ============================================================\n\n vector = {\n literal: (values: number[]): Sql => {\n if (values.some((value) => !Number.isFinite(Math.fround(value))))\n throw new QueryError(\n \"PostgreSQL vector components must fit a finite float32 value.\",\n { code: VibORMErrorCode.INVALID_INPUT }\n );\n return sql`${`[${values.join(\",\")}]`}::vector`;\n },\n\n l2: (column: Sql, vector: Sql): Sql => sql`${column} <-> ${vector}`,\n\n cosine: (column: Sql, vector: Sql): Sql =>\n sql`NULLIF(${column} <=> ${vector}, 'NaN'::double precision)`,\n };\n\n // ============================================================\n // GEOPOINT (PostGIS)\n // ============================================================\n\n #createGeoPointSql(): GeoPointSql {\n const longitude = (point: Sql): Sql => sql`ST_X(${point}::geometry)`;\n const latitude = (point: Sql): Sql => sql`ST_Y(${point}::geometry)`;\n return {\n value: (pointLongitude, pointLatitude) =>\n sql`ST_SetSRID(ST_MakePoint(${pointLongitude}, ${pointLatitude}), 4326)::geography`,\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) =>\n sql`${point} && ST_SetSRID(ST_GeomFromGeoJSON(${polygon}), 4326)::geography`\n )\n );\n }\n ),\n withinPolygon: (point, polygon) => {\n const geography = sql`ST_SetSRID(ST_GeomFromGeoJSON(${geoPolygonJson(\n polygon\n )}), 4326)::geography`;\n return sql`ST_Intersects(${geography}, ${point})`;\n },\n distance: (left, right) => {\n const leftLongitude = sql`RADIANS(ST_X(${left}::geometry))`;\n const leftLatitude = sql`RADIANS(ST_Y(${left}::geometry))`;\n const rightLongitude = sql`RADIANS(ST_X(${right}::geometry))`;\n const rightLatitude = sql`RADIANS(ST_Y(${right}::geometry))`;\n const haversine = sql`POWER(SIN((${rightLatitude} - ${leftLatitude}) / 2), 2) + COS(${leftLatitude}) * COS(${rightLatitude}) * POWER(SIN((${rightLongitude} - ${leftLongitude}) / 2), 2)`;\n // PostgreSQL's LEAST/GREATEST ignore NULL operands. The explicit arm is\n // what keeps a nullable source point's distance NULL rather than zero.\n return sql`CASE WHEN ${left} IS NULL OR ${right} IS NULL THEN NULL ELSE CAST(${GEO_POINT_EARTH_RADIUS_METERS} AS double precision) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${haversine})))) END`;\n },\n };\n }\n\n // ============================================================\n // RESULT PARSING\n // PostgreSQL: passthrough - native JSON and boolean types\n // ============================================================\n\n result: DatabaseAdapter[\"result\"] = {\n // PostgreSQL returns native JS scalars and parseField below is a pure\n // passthrough, so the result parser may take the identity fast path for\n // plain string/int/number/boolean columns (byte-identical, guarded).\n nativeScalarPassthrough: true,\n\n // A managed enum's array OID is in no driver's result-type table, so an\n // enum LIST comes back as the array's own text rather than a JS array.\n enumListRepresentation: \"arrayText\",\n\n // The one physical promise an identifier column makes, derived from the\n // ONE storage owner so the column the migration creates, the parameter the\n // write binds and the value this reads back cannot be three decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"pg\")?.representation ?? \"text\",\n\n // The contract's shape, deciding nothing. This leg used to offer\n // `convertBigIntToNumber(raw)`, but `Queries.decodeResult` hands it the\n // operation's ROW ARRAY, which is never a bigint, and an integer's width\n // is a VALUE's fact that the engine's `int` codec owns - it turns a bigint\n // or an integer text into a number and refuses one outside the safe range\n // (`raptor3/shared/query.ts`). Measured on live PostgreSQL over seven\n // operations and both routes, on `pg` and on `postgres.js`: 40 asks, 40\n // `undefined` (Arnaud's D-40, `g4/rulings/o2/receipts/leg-probe-pg.log`\n // and `leg-probe-postgresjs-2.log`), with `COUNT(*)` arriving as the text\n // `\"2\"` on both transports.\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => {\n // PostgreSQL returns native JSON objects - passthrough\n return next();\n },\n\n parseField: (\n _value: unknown,\n _scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n // PostgreSQL has native types - passthrough\n return next();\n },\n };\n}\n"],"mappings":"25BA+BA,IAAa,EAAb,MAAa,aAAc,CAEzB,KAEA,YAAoB,EAAc,CAChC,KAAK,KAAO,EACZ,OAAO,OAAO,KAAK,CASrB,OAAO,KAAK,EAA2C,CAGrD,IAAM,EAA2B,KAAK,UAAU,EAAM,CACtD,OAAO,IAAS,IAAA,GAAY,IAAA,GAAY,IAAI,cAAc,EAAK,CAGjE,UAAmB,CACjB,OAAO,KAAK,KAGd,QAAkB,CAChB,OAAO,KAAK,MAAM,KAAK,KAAK,GCuBhC,MAAM,EAAa,EAAuB,IAAI,CAC9C,SAAS,oBAAoB,EAAiB,CAC5C,MAAO,EAAG,2BAA2B,EAAM,4EAE7C,SAAS,mBAAmB,EAA6B,CACvD,GAAI,EAAM,SAAW,EAAG,MAAO,GAAI,GAAG,aACtC,IAAM,EAAgB,EAAE,CAClB,EAAcA,EAAI,IACtB,EAAM,OAAS,GAAK,qBAAuB,oBAC5C,CAGD,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAM,OAAQ,GAAS,GAAI,CAC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ACpB,CAAG,UAAU,EAAO,OAAO,EAAO,4BACrC,CAMD,IAAkC,CAChC,IAAM,UAAa,GAAoB,CAAG,QAAQ,EAAM,aAClD,SAAY,GAAoB,CAAG,QAAQ,EAAM,aACvD,MAAO,CACL,OAAQ,EAAgB,IACtB,CAAG,2BAA2B,EAAe,IAAI,EAAc,qBACjE,UACA,SACA,GAAG,EACD,UACA,SACA,KAAK,WACJ,EAAO,IAAW,CACjB,IAAM,EAAW,EAAuB,EAAO,CAC3C,KAAS,SAAW,EACxB,OAAO,KAAK,UAAU,GACpB,GAAG,EAAS,IACT,GACC,CAAG,GAAG,EAAM,oCAAoC,EAAQ,qBAC3D,CACF,EAEJ,CACD,eAAgB,EAAO,IAId,CAAG,iBAHQ,CAAG,iCAAiC,EACpD,EACD,CAAC,qBACmC,IAAI,EAAM,GAEjD,UAAW,EAAM,IAAU,CACzB,IAAM,EAAgB,CAAG,gBAAgB,EAAK,cACxC,EAAe,CAAG,gBAAgB,EAAK,cACvC,EAAiB,CAAG,gBAAgB,EAAM,cAC1C,EAAgB,CAAG,gBAAgB,EAAM,cAI/C,MAAO,EAAG,aAAa,EAAK,cAAc,EAAM,+BAA+B,EAA8B,6DAH3F,CAAG,cAAc,EAAc,KAAK,EAAa,mBAAmB,EAAa,UAAU,EAAc,iBAAiB,EAAe,KAAK,EAAc,YAGM,WAEvL,CAQH,OAAoC,CAIlC,wBAAyB,GAIzB,uBAAwB,YAKxB,kBAAmB,EAAQ,IACzB,GAAY,EAAQ,EAAY,KAAK,EAAE,gBAAkB,OAY3D,YAAa,EAEb,eACE,EACA,IAGO,GAAM,CAGf,YACE,EACA,EACA,IAGO,GAAM,CAEhB"}
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{T as t,t as n}from"./validation-Du6j0Q38.mjs";import{n as r,t as i}from"./base-vfur-DaU.mjs";import{a,c as o,d as s,i as c,l,n as u,r as d,t as f,u as p}from"./terminal-BbRi0CNZ.mjs";import{t as m}from"./identifier-EsWKVHXi.mjs";import{_t as h,at as g,ct as _,dt as ee,ft as v,gt as y,ht as b,it as x,lt as S,mt as C,nt as w,ot as T,pt as E,rt as D,st as te,ut as ne,vt as re,yt as ie}from"./geo-point-codec-DUTTtlav.mjs";import{n as O}from"./v-B2WwtcRz.mjs";import{a as k,i as A,n as j,r as M,t as N}from"./native-types-veeTk36s.mjs";const P=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,190}$/,F=[`table`,`source`,`target`];function normalizeVariantEntries(e,t,n){c(t)||s(e,`target`,"A relation target is either `() => model` or a plain map of named `() => model` getters");let r=u(t);r.length===0&&s(e,`target`,`A variant map needs at least one variant`);let i=readStoredValues(e,r,n),a={};for(let n of r){m(n)||s(e,`target.${n}`,`Variant key '${n}' is not a valid schema identifier`);let r=p(e,t,n,`target.${n}`);typeof r!=`function`&&s(e,`target.${n}`,`Variant '${n}' must be a lazy getter; write \`() => model\` rather than the model itself`),a[n]=Object.freeze({getter:r,storedValue:i[n]??n})}return Object.freeze(a)}function readStoredValues(e,t,n){if(n===void 0)return{};c(n)||s(e,`options`,"Relation options must be a plain `{ values }` record; omit the argument to use each variant key as its stored value"),d(u(n),[`values`])||s(e,`options`,"Relation options carry exactly one key, `values`; omit the argument to use each variant key as its stored value");let r=p(e,n,`values`,`options.values`);c(r)||s(e,`options.values`,"`values` must be a plain record keyed by every variant");let i=u(r);d(i,t)||s(e,`options.values`,`\`values\` must be exact over the variant keys ${renderKeys(t)}; it declares ${renderKeys(i)}`);let a={},o=new Set;for(let n of t){let t=p(e,r,n,`options.values.${n}`);(typeof t!=`string`||!P.test(t))&&s(e,`options.values.${n}`,`Stored value for variant '${n}' must match the stored-discriminator grammar`),o.has(t)&&s(e,`options.values.${n}`,`Stored value '${t}' is declared for more than one variant`),o.add(t),a[n]=t}return a}function renderKeys(e){return`[${e.map(e=>`'${e}'`).join(`, `)}]`}function foldMemberJunctions(e,t){let n=Object.keys(e);c(t)||s(`s.toMany`,`through`,"`.through()` takes a plain map keyed by every variant"),d(u(t),n)||s(`s.toMany`,`through`,`\`.through()\` must be exact over the variant keys ${renderKeys(n)}`);let r={};for(let[n,i]of Object.entries(e)){let e=p(`s.toMany`,t,n,`through.${n}`);r[n]=Object.freeze({...i,junction:readJunctionOverride(n,e)})}return Object.freeze(r)}function readJunctionOverride(e,t){let n=`through.${e}`;c(t)||s(`s.toMany`,n,`Member junction '${e}' must be a plain \`{ table, source, target }\` record`);let r=p(`s.toMany`,t,`table`,`${n}.table`),i=p(`s.toMany`,t,`source`,`${n}.source`),a=p(`s.toMany`,t,`target`,`${n}.target`);return(!d(u(t),F)||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)&&s(`s.toMany`,n,`Member junction '${e}' declares exactly \`table\`, \`source\` and \`target\`, all strings`),Object.freeze({table:r,source:i,target:a})}var I=class VariantToOne{#e;#t;constructor(e){this.#e=Object.freeze(e),this.#t=Object.freeze({state:this.#e,settleTarget:f(e=>readVariantGetter(this.#e,e))})}name(e){return new VariantToOne({...this.#e,name:l(`s.toOne`,e)})}optional(){return new VariantToOne({...this.#e,optional:!0})}get"~"(){return this.#t}},L=class VariantToMany{#e;#t;constructor(e){this.#e=Object.freeze(e),this.#t=Object.freeze({state:this.#e,settleTarget:f(e=>readVariantGetter(this.#e,e))})}name(e){return new VariantToMany({...this.#e,name:l(`s.toMany`,e)})}through(e){return new VariantToMany({...this.#e,target:{kind:`variants`,entries:foldMemberJunctions(this.#e.target.entries,e)}})}get"~"(){return this.#t}};function variantToOneTerminal(e){return new I(e)}function variantToManyTerminal(e){return new L(e)}function readVariantGetter(e,t){if(t===void 0)return;let n=e.target.entries[t];return n===void 0?void 0:n.getter}var R=class ModelToOne{#e;#t;constructor(e){this.#e=Object.freeze(e),this.#t=Object.freeze({state:this.#e,settleTarget:f(()=>this.#e.target.getter)})}name(e){return new ModelToOne({...this.#e,name:l(`s.toOne`,e)})}fields(...e){return new z(this.#e,a(`s.toOne`,`fields`,e))}onDelete(e){return this.#n(`onDelete`,e)}onUpdate(e){return this.#n(`onUpdate`,e)}#n(e,t){let n=this.#e.foreignKey;return n===void 0&&s(`s.toOne`,e,`'${e}' is available only after \`.fields(...).references(...)\` declares a foreign key`),new ModelToOne({...this.#e,foreignKey:Object.freeze({...n,[e]:o(e,t)})})}get"~"(){return this.#t}},z=class PendingReferences{#e;#t;constructor(e,t){this.#e=e,this.#t=t}name(e){return new PendingReferences({...this.#e,name:l(`s.toOne`,e)},this.#t)}references(...e){let t=a(`s.toOne`,`references`,e);t.length!==this.#t.length&&refuseReferenceArity(t.length,this.#t.length);let n=this.#e.foreignKey,r={fields:this.#t,references:t,...n?.onDelete===void 0?{}:{onDelete:n.onDelete},...n?.onUpdate===void 0?{}:{onUpdate:n.onUpdate}};return new R({...this.#e,foreignKey:Object.freeze(r)})}};function isReferencesStage(e){return e instanceof z}function toOne(e,t){return typeof e==`function`?(arguments.length>1&&s(`s.toOne`,`options`,`A model-target relation takes exactly one argument`),new R({kind:`relation`,cardinality:`one`,target:{kind:`model`,getter:e}})):variantToOneTerminal({kind:`relation`,cardinality:`one`,target:{kind:`variants`,entries:normalizeVariantEntries(`s.toOne`,e,t)}})}function refuseReferenceArity(e,t){return s(`s.toOne`,`references`,`\`.references(...)\` declares ${e} field(s) against ${t} local field(s); a foreign key pairs them positionally`)}function emptyRecord(){return Object.create(null)}function put(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function own(e,t){if(!(e===void 0||!Object.hasOwn(e,t)))return e[t]}function isRelation(e){if((typeof e!=`object`||!e)&&typeof e!=`function`)return!1;let t=Reflect.get(e,`~`);if(typeof t!=`object`||!t)return!1;let n=Reflect.get(t,`state`);return typeof n==`object`&&!!n&&Reflect.get(n,`kind`)===`relation`}const B=new Set([`string`,`int`,`number`,`decimal`,`boolean`,`datetime`,`date`,`time`,`bigint`,`json`,`blob`,`vector`,`point`,`enum`]);function isScalar(e){if((typeof e!=`object`||!e)&&typeof e!=`function`)return!1;let t=Reflect.get(e,`~`);if(typeof t!=`object`||!t)return!1;let n=Reflect.get(t,`state`);if(typeof n!=`object`||!n)return!1;let r=Reflect.get(n,`type`);return typeof r==`string`&&B.has(r)}const extractScalarMap=e=>{let t=emptyRecord();for(let[n,r]of Object.entries(e))isScalar(r)&&(t[n]=r);return t},extractRelationMap=e=>{let t=emptyRecord();for(let[n,r]of Object.entries(e))isRelation(r)?t[n]=r:isReferencesStage(r)&&s(`s.model`,n,`Relation '${n}' started \`.fields(...)\` without \`.references(...)\`; complete the foreign key before using it as a model field`);return t},extractUniqueScalarMap=e=>{let t=emptyRecord();for(let[n,r]of Object.entries(e))isScalar(r)&&(r[`~`].state.isUnique||r[`~`].state.isId)&&(t[n]=r);return t},getNameFromKeys=(e,t)=>e??t.join(`_`);function isTotalIndex(e){return!e.where}const mergeIndexDefinitions=(e,t)=>[...e.indexes,t];function compoundMembers(e,t,n){refuseDuplicateModelKeyMembers(t,n);let r=emptyRecord();for(let i of t){let t=i in e.scalars?e.scalars[i]:void 0;if(!t)throw Error(i in e.relations?`${n} field '${i}' is a relation and cannot be a key member`:`${n} field '${i}' does not exist`);put(r,i,t[`~`].state.base)}return r}function snapshotModelKeyMembers(e,t){if(!Array.isArray(e))throw Error(`${t} fields must be a dense array of strings`);let n=e.length,r=Array(n);for(let i=0;i<n;i++){if(!Object.hasOwn(e,i))throw Error(`${t} fields must be a dense array of strings`);let n=e[i];if(typeof n!=`string`)throw Error(`${t} fields must be a dense array of strings`);r[i]=n}return r}function snapshotIndexOptions(e){let t=e.name,n=e.unique,r=e.type,i=e.where;return{...t===void 0?{}:{name:t},...n===void 0?{}:{unique:n},...r===void 0?{}:{type:r},...i===void 0?{}:{where:i}}}function refuseDuplicateModelKeyMembers(e,t){if(new Set(e).size!==e.length)throw Error(`${t} cannot repeat a field in one tuple`)}function refuseCompoundKeyStateOverwrite(e,t,n){if(Object.hasOwn(e??{},t))throw Error(`${n} name '${t}' is already used by another compound key; give this tuple a distinct name`)}var V=class Model{#e={};#t={fields:new Map};#n;#r;#i;#a;constructor(e){this.#n=e}map(e){return new Model({...this.#n,tableName:e})}omit(e){return new Model({...this.#n,omit:e})}index(e,t={}){let n=snapshotModelKeyMembers(e,`Index`);refuseDuplicateModelKeyMembers(n,`Index`);let r=snapshotIndexOptions(t);return new Model({...this.#n,indexes:mergeIndexDefinitions(this.#n,{fields:n,options:r})})}id(e,t){let n=snapshotModelKeyMembers(e,`Compound ID`),r=getNameFromKeys(t?.name,n);refuseCompoundKeyStateOverwrite(this.#n.compoundId,r,`Compound ID`);let i=compoundMembers(this.#n,n,`Compound ID`),a={...this.#n.compoundId,[r]:O.object(i,{partial:!1})};return new Model({...this.#n,compoundId:a})}unique(e,t){let n=snapshotModelKeyMembers(e,`Compound unique`),r=getNameFromKeys(t?.name,n);refuseCompoundKeyStateOverwrite(this.#n.compoundUniques,r,`Compound unique`);let i=compoundMembers(this.#n,n,`Compound unique`),a={...this.#n.compoundUniques,[r]:O.object(i,{partial:!1})};return new Model({...this.#n,compoundUniques:a})}extends(e){let t={...this.#n.shape,...e};return new Model({...this.#n,shape:t,scalars:extractScalarMap(t),relations:extractRelationMap(t),uniques:extractUniqueScalarMap(t)})}get"~"(){if(this.#a)return this.#a;let e=this;return this.#a={state:this.#n,get names(){return e.#e},get nameRegistry(){return e.#t},getFieldName:t=>{let n=e.#t.fields.get(t);if(n)return n;throw Error(`Scalar "${t}" not found in nameRegistry`)},get scalarFieldNames(){return e.#r??=Object.keys(e.#n.scalars)},get relationNames(){return e.#i??=Object.keys(e.#n.relations)}},this.#a}};const model=e=>new V({compoundId:void 0,compoundUniques:void 0,tableName:void 0,indexes:[],omit:void 0,shape:e,scalars:extractScalarMap(e),relations:extractRelationMap(e),uniques:extractUniqueScalarMap(e)});function getTableName(e,t=`unknown`){return e[`~`].names.sql??e[`~`].state.tableName??t}function getColumnName(e,t){return e[`~`].getFieldName(t).sql}var SchemaValidationError=class extends i{static diagnosticName=`SchemaValidationError`;issues;constructor(e,t){let n=Object.freeze(e.map(e=>Object.freeze(e.candidates?{...e,candidates:Object.freeze([...e.candidates])}:{...e}))),i=n.map(e=>[`[${e.code}] ${e.message}`,e.candidates?.length?`Candidates: ${e.candidates.join(`, `)}`:``,e.repair??``].filter(Boolean).join(`
|
|
2
|
-
`));super(`Schema validation failed:\n${i.join(`
|
|
3
|
-
`)}`,r.INVALID_INPUT,t?.cause?{cause:t.cause}:void 0),this.issues=n}toJSON(){return{...super.toJSON(),issues:this.issues}}};function isSchemaValidationError(e){return e instanceof SchemaValidationError}function thrownAsError(e){return e instanceof Error?e:Error(String(e))}const H=new WeakSet;function generatorDefault(e){return H.add(e),e}function refuseListGenerator(e){throw new n({kind:`schema-builder`,builder:e,path:`array`},[{path:`array`,message:`Scalar generation is not supported on lists; declare an explicit array default`}])}function nullableDefault(e){return e.hasDefault?e.default:null}function isGeneratorDefault(e){return typeof e==`function`&&H.has(e)}const updateState=(e,t)=>({...e[`~`].state,...t}),createDefaultState=(e,t)=>({type:e,nullable:!1,array:!1,hasDefault:!1,isId:!1,isUnique:!1,default:void 0,autoGenerate:void 0,disallowZero:!1,schema:void 0,columnName:void 0,optional:!1,withTimezone:!1,base:t}),U=[[],[1],[1,2]],W=/^\d+$/,G=/^[A-Za-z_][A-Za-z0-9_]*(\(\d+(,\d+)*\))?$/,K={pg:`PG`,mysql:`MYSQL`,sqlite:`SQLITE`};let q;function isNativeTypeInCatalog(e,t){q??=buildCatalogs();let n=q[e];if(n.exact.has(t))return!0;if(!G.test(t))return!1;let r=t.indexOf(`(`);if(r===-1)return n.templates.get(t)?.has(0)===!0;let i=t.slice(0,r),a=t.slice(r+1,-1).split(`,`).length;return n.templates.get(i)?.has(a)===!0}function nativeTypeRefusal(e){return`A \`native.type\` is written into DDL verbatim, so a document may carry only a native type from the '${e}' dialect's closed catalog — the values the ${K[e]} native-type constants produce. See the native types documentation (docs/schema/native-types).`}function refuse(e,t,r){throw new n({kind:`schema-builder`,builder:e,path:t},[{path:t,message:r}])}function admitNativeType(e,t){return t===void 0?void 0:admitDeclaredNativeType(e,t)}function admitDeclaredNativeType(e,n){if(t(n)||refuse(e,`nativeType`,"A native type is a `{ db, type }` constant or a map of them by dialect (`{ pg, mysql, sqlite }`)"),k(n)){let{db:t,type:r}=n;(!j.includes(t)||typeof r!=`string`)&&refuse(e,`nativeType`,`A tagged native type is \`{ db, type }\`: \`db\` one of ${j.join(`, `)} and \`type\` a string`);let i=j.find(e=>Object.hasOwn(n,e));return i!==void 0&&refuse(e,`nativeType.${i}`,`A tagged native type ('db: ${t}') cannot also carry a '${i}' entry: declare one tagged type, or a map by dialect (\`{ pg, mysql, sqlite }\`)`),n}return admitNativeTypeMap(e,n)}function admitNativeTypeMap(e,t){for(let n of Object.keys(t))j.some(e=>e===n)||refuse(e,`nativeType.${n}`,`'${n}' is not a dialect: a native-type map names only ${j.join(`, `)}`);let n={};return Object.hasOwn(t,`pg`)&&(n.pg=admitEntry(e,`pg`,t.pg)),Object.hasOwn(t,`mysql`)&&(n.mysql=admitEntry(e,`mysql`,t.mysql)),Object.hasOwn(t,`sqlite`)&&(n.sqlite=admitEntry(e,`sqlite`,t.sqlite)),Object.keys(n).length===0&&refuse(e,`nativeType`,`A native-type map names at least one dialect; omit the argument to keep every automatic column`),Object.freeze(n)}function admitEntry(e,n,r){let i=t(r)?r.db:void 0,a=t(r)?r.type:void 0;return(i!==n||typeof a!=`string`)&&refuse(e,`nativeType.${n}`,`The '${n}' entry must be a ${K[n]} native type (\`{ db: "${n}", type }\`)`),Object.freeze({db:n,type:a})}function buildCatalogs(){let e={pg:emptyCatalog(),mysql:emptyCatalog(),sqlite:emptyCatalog()};return walk(M,e.pg),walk(N,e.mysql),walk(A,e.sqlite),e}function emptyCatalog(){return{exact:new Set,templates:new Map}}function walk(e,t){if(typeof e==`function`){deriveFunction(e,t);return}let n=e.type;if(typeof n==`string`){t.exact.add(n);return}for(let n of Object.values(e))walk(n,t)}function deriveFunction(e,t){for(let n of U){let r=e(...n).type,i=r.indexOf(`(`);if(i===-1){admit(t,r,0);continue}let a=r.slice(i+1,-1).split(`,`);a.every(e=>W.test(e))&&admit(t,r.slice(0,i),a.length)}}function admit(e,t,n){let r=e.templates.get(t);if(r===void 0){e.templates.set(t,new Set([n]));return}r.add(n)}const J=new DataView(new ArrayBuffer(192));for(let[e,t]of[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648].entries())J.setInt32(e*4,t,!0);const ae=new DataView(new Uint8Array([0,1,62,28,27,36,44,6,55,20,3,10,43,25,39,41,45,15,21,8,18,2,61,56,14]).buffer),oe=new DataView(new Uint8Array([0,10,20,5,15,16,1,11,21,6,7,17,2,12,22,23,8,18,3,13,14,24,9,19,4]).buffer),Y=new Uint8Array(200),X=new DataView(Y.buffer),Z=new DataView(new ArrayBuffer(200)),Q=new DataView(new ArrayBuffer(40));function permute(){for(let e=0;e<24;e++){for(let e=0;e<5;e++){let t=0,n=0;for(let r=0;r<25;r+=5)t^=X.getInt32((e+r)*8,!0),n^=X.getInt32((e+r)*8+4,!0);Q.setInt32(e*8,t,!0),Q.setInt32(e*8+4,n,!0)}for(let e=0;e<5;e++){let t=Q.getInt32((e+1)%5*8,!0),n=Q.getInt32((e+1)%5*8+4,!0),r=Q.getInt32((e+4)%5*8,!0)^(t<<1|n>>>31),i=Q.getInt32((e+4)%5*8+4,!0)^(n<<1|t>>>31);for(let t=0;t<25;t+=5){let n=(e+t)*8;X.setInt32(n,X.getInt32(n,!0)^r,!0),X.setInt32(n+4,X.getInt32(n+4,!0)^i,!0)}}Z.setInt32(0,X.getInt32(0,!0),!0),Z.setInt32(4,X.getInt32(4,!0),!0);for(let e=1;e<25;e++){let t=ae.getUint8(e),n=X.getInt32(e*8,!0),r=X.getInt32(e*8+4,!0),i=oe.getUint8(e)*8;if(t<32)Z.setInt32(i,n<<t|r>>>32-t,!0),Z.setInt32(i+4,r<<t|n>>>32-t,!0);else{let e=t-32;Z.setInt32(i,r<<e|n>>>32-e,!0),Z.setInt32(i+4,n<<e|r>>>32-e,!0)}}for(let e=0;e<25;e+=5)for(let t=0;t<5;t++){let n=(e+t)*8,r=(e+(t+1)%5)*8,i=(e+(t+2)%5)*8;X.setInt32(n,Z.getInt32(n,!0)^~Z.getInt32(r,!0)&Z.getInt32(i,!0),!0),X.setInt32(n+4,Z.getInt32(n+4,!0)^~Z.getInt32(r+4,!0)&Z.getInt32(i+4,!0),!0)}X.setInt32(0,X.getInt32(0,!0)^J.getInt32(e*8,!0),!0),X.setInt32(4,X.getInt32(4,!0)^J.getInt32(e*8+4,!0),!0)}}function absorb(e,t){for(let n=0;n<72;n+=4)X.setInt32(n,X.getInt32(n,!0)^e.getInt32(t+n,!0),!0);permute()}function sha3_512(e){Y.fill(0);let t=e.length,n=new DataView(e.buffer,e.byteOffset,t),r=Math.floor(t/72);for(let e=0;e<r;e++)absorb(n,e*72);let i=new Uint8Array(72),a=t-r*72;return i.set(e.subarray(r*72)),i[a]=6,i[71]=a===71?134:128,absorb(new DataView(i.buffer),0),Uint8Array.from(Y.subarray(0,64))}function uuidV4(){let e=globalThis.crypto;return typeof e?.randomUUID==`function`?e.randomUUID():v(re(b(_,`uuid`)))}const defaultUuid=e=>()=>S(e,uuidV4()),defaultUuidV7=e=>()=>S(e,v(ie(Date.now(),b(te,`uuidv7`))));function incrementUlidRandom(e){let t=Uint8Array.from(e),n=new DataView(t.buffer);for(let e=t.length-1;e>=0;e--){let r=n.getUint8(e)+1;if(n.setUint8(e,r&255),r<=255)return t}return y(`s.string().ulid`,`generate`,`This process issued every ULID one millisecond can hold (2^80). Monotonicity cannot be preserved without emitting a smaller identifier`)}function createUlidGenerator(e={}){let t=e.now??Date.now,n=e.random??(e=>b(e,`ulid`)),r;return()=>{let e=t();return r=r!==void 0&&e<=r.time?{time:r.time,random:incrementUlidRandom(r.random)}:{time:e,random:n(T)},ee(h(r.time,r.random))}}const se=createUlidGenerator(),defaultUlid=e=>()=>S(e,se()),defaultKsuid=e=>()=>S(e,ne(C(Math.floor(Date.now()/1e3),b(w,`ksuid`)))),defaultNanoid=(e,t)=>{let n=e??g;return(!Number.isInteger(n)||n<1||n>D)&&y(`s.string().nanoid`,`length`,`A nanoid length must be a whole number of characters between 1 and ${D}; received ${n}`),()=>{let e=``;for(let t of b(n,`nanoid`))e+=x.charAt(t&63);return S(t,e)}},ce=new TextEncoder;function secureFloat(){let e=b(4,`cuid`);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0,!0)/4294967296}function createEntropy(e,t){let n=``;for(;n.length<e;)n+=Math.floor(t()*36).toString(36);return n}function hashBase36(e){let t=0n;for(let n of sha3_512(ce.encode(e)))t=t<<8n|BigInt(n);return t.toString(36).slice(1)}function createFingerprint(e){return hashBase36(Object.keys(globalThis).toString()+createEntropy(32,e)).substring(0,32)}function createCuid2(e={}){let t=e.random??secureFloat,n=e.counter??createCounter(Math.floor(t()*476782367)),r=e.length??24,i=e.fingerprint??createFingerprint(t);return()=>{let e=`abcdefghijklmnopqrstuvwxyz`.charAt(Math.floor(t()*26)),a=Date.now().toString(36),o=n().toString(36);return e+hashBase36(a+createEntropy(r,t)+o+i).substring(1,r)}}function createCounter(e){let t=e;return()=>{let e=t;return t++,e}}let le;const defaultCuid=e=>()=>S(e,(le??=createCuid2())());function identifierGenerator(e){let{kind:t,prefix:n,length:r}=e;switch(t){case`uuid`:return defaultUuid(n);case`uuidv7`:return defaultUuidV7(n);case`ulid`:return defaultUlid(n);case`ksuid`:return defaultKsuid(n);case`nanoid`:return defaultNanoid(r,n);case`cuid`:return defaultCuid(n);default:return y(`s.string`,`generate`,`This generator is not a string identifier format`)}}const $=O.string();var ue=class StringScalar{state;_nativeType;constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new StringScalar(updateState(this,{nullable:!0,hasDefault:!0,default:nullableDefault(this.state),optional:!0,base:O.string({nullable:!0,array:this.state.array,schema:this.state.schema})}),this._nativeType)}array(){return isGeneratorDefault(this.state.default)&&refuseListGenerator(`s.string`),new StringScalar(updateState(this,{array:!0,base:O.string({nullable:this.state.nullable,array:!0,schema:this.state.schema})}),this._nativeType)}id(e){let t=typeof e==`object`?e.generate:void 0,n=typeof e==`string`?e:e?.prefix,r=this.state.autoGenerate;r&&E(n)&&refuseSecondIdPrefix(r);let i=r?{...r,generate:t??r.generate}:{kind:`ulid`,prefix:n,implicit:!0,generate:t};return this.withIdentifier(i,!0)}unique(){return new StringScalar(updateState(this,{isUnique:!0}),this._nativeType)}default(e){return new StringScalar(updateState(this,{hasDefault:!0,default:e,optional:!0}),this._nativeType)}schema(e){return new StringScalar(updateState(this,{schema:e,base:O.string({nullable:this.state.nullable,array:this.state.array,schema:e})}),this._nativeType)}map(e){return new StringScalar(updateState(this,{columnName:e}),this._nativeType)}uuid(e){return this.withFormat(`uuid`,e)}uuidv7(e){return this.withFormat(`uuidv7`,e)}ksuid(e){return this.withFormat(`ksuid`,e)}ulid(e){return this.withFormat(`ulid`,e)}cuid(e){return this.withFormat(`cuid`,e)}nanoid(e,t){return this.withFormat(`nanoid`,typeof e==`number`?{length:e,prefix:t}:e??{prefix:t})}withFormat(e,t){let n=typeof t==`string`?{prefix:t}:t;return this.withIdentifier({kind:e,prefix:n?.prefix,length:e===`nanoid`?n?.length:void 0,generate:n?.generate??this.state.autoGenerate?.generate},this.state.isId)}withIdentifier(e,t){let n=identifierGenerator(e),r=this.state.hasDefault&&!isGeneratorDefault(this.state.default),i=(e.generate===!0||t&&e.generate!==!1)&&!r;return this.state.array&&i&&refuseListGenerator(`s.string`),new StringScalar(updateState(this,{isId:t,isUnique:t||this.state.isUnique,autoGenerate:e,hasDefault:r||i,optional:r||i,default:i?generatorDefault(n):r?this.state.default:void 0}),this._nativeType)}_internal;get"~"(){return this._internal??={state:this.state,nativeType:this._nativeType}}};const string=e=>new ue(createDefaultState(`string`,$),admitNativeType(`s.string`,e));function refuseSecondIdPrefix(e){return y(`s.string().id`,`prefix`,`This field already declares a '${e.kind}' generator${e.prefix?` with the prefix '${e.prefix}'`:``}. A prefix is spelled once, on the call that declares the format`)}function preflightModelRegistrationIdentity(e){let t=new Map;for(let[n,r]of e){if(typeof r!=`object`||!r||!r[`~`]?.names||!r[`~`]?.state?.scalars)return{code:`M008`,message:`Schema entry '${n}' is not a model; pass an explicit object containing only s.model() definitions`,severity:`error`,model:n};let e=r[`~`].names.ts??t.get(r);if(e!==void 0&&e!==n)return doubleRegistrationIssue(e,n);t.set(r,n)}}function doubleRegistrationIssue(e,t){return{code:`M003`,message:`Model registered as '${e}' cannot also be registered as '${t}'; one model object binds one schema key`,severity:`error`,model:t}}export{toOne as C,put as S,variantToManyTerminal as T,getTableName as _,nativeTypeRefusal as a,emptyRecord as b,isGeneratorDefault as c,updateState as d,SchemaValidationError as f,getColumnName as g,V as h,isNativeTypeInCatalog as i,nullableDefault as l,thrownAsError as m,string as n,createDefaultState as o,isSchemaValidationError as p,admitNativeType as r,generatorDefault as s,preflightModelRegistrationIdentity as t,refuseListGenerator as u,isTotalIndex as v,normalizeVariantEntries as w,own as x,model as y};
|
|
4
|
-
//# sourceMappingURL=registration-preflight-BrA3EWvq.mjs.map
|