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
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{C as e,n as t,y as n}from"./registration-preflight-DEjv050M.mjs";import{_ as r,a as i,d as a,f as o,g as s,h as c,i as l,l as u,m as d,n as f,o as p,p as m,r as h,t as g}from"./scalar-U0wD5bKy.mjs";const _={model:n,string:t,boolean:d,int:i,number:h,decimal:u,bigInt:s,dateTime:o,date:m,time:a,json:l,blob:c,enum:p,point:f,vector:g,toOne:e,toMany:r};export{_ as t};
|
|
2
|
+
//# sourceMappingURL=schema-Cjem1-0f.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema-
|
|
1
|
+
{"version":3,"file":"schema-Cjem1-0f.mjs","names":[],"sources":["../src/schema/index.ts"],"sourcesContent":["// Schema Builder Entry Point\n// Main API for defining models, scalars, and relations\n\nimport { model } from \"./model\";\nimport { toMany, toOne } from \"./relation\";\nimport {\n bigInt,\n blob,\n boolean,\n date,\n dateTime,\n decimal,\n enumScalar,\n int,\n json,\n number,\n point,\n string,\n time,\n vector,\n} from \"./scalars\";\n\n// =============================================================================\n// SCHEMA BUILDER API\n// =============================================================================\n\n/**\n * Main schema builder object\n * Use this to define models, scalars, and relations\n *\n * A relation states two independent facts: `s.toOne` / `s.toMany` states the\n * SLOT CARDINALITY, and the argument states the TARGET DOMAIN — one model\n * (`() => model`) or named variants (`{ post: () => post, video: () => video }`).\n * Everything else about an edge is derived from the full schema graph.\n *\n * @example\n * ```ts\n * import { s } from \"viborm\";\n *\n * const user = s.model({\n * id: s.string().id().ulid(),\n * name: s.string(),\n * email: s.string().unique(),\n * posts: s.toMany(() => post),\n * profile: s.toOne(() => profile),\n * }).map(\"users\");\n *\n * const post = s.model({\n * id: s.string().id().ulid(),\n * authorId: s.string(),\n * author: s.toOne(() => user).fields(\"authorId\").references(\"id\"),\n * }).map(\"posts\");\n * ```\n */\nexport const s = {\n // Model factory\n model,\n\n // Scalar factories\n string,\n boolean,\n /**\n * @description Creates a new int scalar.\n * @param nativeType - The native type to use for the scalar.\n * @returns A new int scalar.\n */\n int,\n number,\n decimal,\n bigInt,\n dateTime,\n date,\n time,\n json,\n blob,\n enum: enumScalar,\n point,\n vector,\n\n // Relation factories: slot cardinality here, target domain in the argument\n toOne,\n toMany,\n};\n\n// =============================================================================\n// RE-EXPORTS\n// =============================================================================\n\n// Hydration exports (excluding Schema type which conflicts with validation)\nexport {\n getFieldSqlName,\n getModelSqlName,\n hydrateSchemaNames,\n isSchemaHydrated,\n} from \"./hydration\";\n// JSON null sentinels — the two nulls of a nullable JSON column, told apart\nexport {\n type AnyJsonNullSentinel,\n AnyNull,\n DbNull,\n isJsonNullSentinel,\n JsonNull,\n type JsonNullKind,\n JsonNullSentinel,\n} from \"./json-null\";\nexport * from \"./model\";\nexport { Model } from \"./model\";\nexport * from \"./relation\";\n// Types\nexport type { NumericScalar, Scalar } from \"./scalars\";\n// Export all from submodules\nexport * from \"./scalars\";\n// Classes for advanced usage\nexport {\n BigIntScalar,\n BlobScalar,\n BooleanScalar,\n DateScalar,\n DateTimeScalar,\n EnumScalar,\n IntScalar,\n JsonScalar,\n NumberScalar,\n PointScalar,\n StringScalar,\n TimeScalar,\n VectorScalar,\n} from \"./scalars\";\nexport * as TYPES from \"./scalars/native-types\";\nexport * from \"./validation\";\n\n// =============================================================================\n// TYPE INFERENCE EXPORTS\n// =============================================================================\n\n// Re-export core types from common\nexport type {\n AutoGenerate,\n AutoGenerateType,\n InferBaseType,\n InferCreateType,\n ScalarState as ScalarStateType,\n} from \"./scalars/common\";\n"],"mappings":"6MAsDA,MAAa,EAAI,CAEf,QAGA,SACA,UAMA,MACA,SACA,UACA,SACA,WACA,OACA,OACA,OACA,OACA,KAAM,EACN,QACA,SAGA,QACA,SACD"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t,s as n}from"./controls-DXgIn4zh.mjs";import{d as r,t as i}from"./validation-Dk9Q_-C7.mjs";import{a,c as o,l as s,n as c,o as l}from"./result-shape-CTNdNSW3.mjs";import{t as u}from"./result-parsing-DRXC89ek.mjs";import{n as d,s as f,t as p}from"./builder-Ycvq3ETg.mjs";import{n as m}from"./validator-X9-bwtRo.mjs";import{h}from"./registration-preflight-DEjv050M.mjs";import{t as g}from"./types-C4v6iAmY.mjs";import{t as _}from"./hydration-CAxOL4aI.mjs";function classifyAggregateLeaf(e,t,n){let r=Object.hasOwn(n,t)?n[t]:void 0;return e===`_count`?t===`_all`||r?{kind:`count`,nullable:!1}:{kind:`unknown`}:r?e===`_avg`&&r[`~`].state.type!==`decimal`?{kind:`number`,nullable:!0}:e===`_sum`?{kind:`widenedSum`,nullable:!0,scalar:r}:{kind:`scalar`,nullable:!0,scalar:r}:{kind:`unknown`}}function classifyResultColumn(e,t,n){if(t===l)return{kind:`empty`};if(t===a)return{kind:`distance`,scalar:n.distanceScalar};let r=e[`~`].state.scalars,i=Object.hasOwn(r,t)?r[t]:void 0;if(i)return{kind:`scalar`,key:t,scalar:i};if(t===o)return{kind:`relationCounts`,relations:n.relationCounts};let c=e[`~`].state.relations,u=Object.hasOwn(c,t)?c[t]:void 0;if(u){if(g(u[`~`].state)){let e=n.polymorphic.get(t);return e?{kind:`polymorphic`,key:t,relation:u,expected:e}:{kind:`unknown`,key:t}}let e=n.relations.get(t);return e?{kind:`relation`,key:t,relation:u,expected:e}:{kind:`unknown`,key:t}}let d=s(t);if(d){let e=n.aggregates.get(t);return e?{kind:`aggregate`,name:d,expected:e}:{kind:`unknown`,key:t}}return{kind:`unknown`,key:t}}const v=/^[A-Za-z_$][A-Za-z0-9_$]*$/,y={kind:`atom`,value:`null`};function atom(e){return{kind:`atom`,value:e}}function arrayOf(e,t=!1){return{kind:`array`,element:e,immutable:t}}function objectOf(e){return{kind:`object`,fields:e}}function unionOf(...e){let t=[],n=new Set;for(let r of e){let e=r.kind===`union`?r.members:[r];for(let r of e){let e=renderType(r,0);n.has(e)||(n.add(e),t.push(r))}}let[r]=t;return r?t.length===1?r:{kind:`union`,members:t}:atom(`never`)}function renderPropertyName(e){return v.test(e)?e:JSON.stringify(e)}function indentation(e){return` `.repeat(e)}function renderType(e,t){switch(e.kind){case`atom`:return e.value;case`array`:return`${e.immutable?`ReadonlyArray`:`Array`}<${renderType(e.element,t)}>`;case`union`:return e.members.map(e=>renderType(e,t)).join(` | `);case`object`:{if(e.fields.length===0)return`{}`;let n=indentation(t+1);return`{
|
|
2
|
+
${e.fields.map(e=>{let r=e.immutable?`readonly `:``,i=e.optional?`?`:``;return`${n}${r}${renderPropertyName(e.name)}${i}: ${renderType(e.type,t+1)};`}).join(`
|
|
3
|
+
`)}
|
|
4
|
+
${indentation(t)}}`}default:throw new r(`The TypeScript renderer received an unknown node.`)}}function enumType(e){let t=Reflect.get(e[`~`].state.base,`values`);if(!(Array.isArray(t)&&t.every(e=>typeof e==`string`)))throw new r(`An enum scalar has no readable string values.`);return unionOf(...t.map(e=>atom(JSON.stringify(e))))}const b=Object.freeze({string:`string`,time:`string`,int:`number`,number:`number`,decimal:`import("viborm").Decimal`,boolean:`boolean`,datetime:`Date`,date:`Date`,bigint:`bigint`,json:`unknown`,blob:`Uint8Array`});function scalarType(e){let t=e[`~`].state,n;if(Object.hasOwn(b,t.type))n=atom(b[t.type]);else if(t.type===`vector`)n=arrayOf(atom(`number`));else if(t.type===`point`)n=objectOf([{name:`longitude`,type:atom(`number`)},{name:`latitude`,type:atom(`number`)}]);else if(t.type===`enum`)n=enumType(e);else throw new r(`The TypeScript renderer does not support this scalar type.`);return t.array&&(n=arrayOf(n)),t.nullable?unionOf(n,y):n}function requiredRelationShape(e,t){if(t)return t;throw new r(`The result shape for relation '${e}' is absent.`)}function requiredPolymorphicShape(e,t){if(t)return t;throw new r(`The result shape for polymorphic relation '${e}' is absent.`)}function aggregateLeafType(e){switch(e.kind){case`count`:case`number`:return e.nullable?unionOf(atom(`number`),y):atom(`number`);case`scalar`:case`widenedSum`:return unionOf(scalarType(e.scalar),y);case`unknown`:throw new r(`The aggregate result contains an unknown field.`);default:throw new r(`The TypeScript renderer received an unknown aggregate leaf.`)}}function aggregateType(e,t,n){if(t===`_count`&&n?.fields===void 0)return atom(`number`);if(!n?.fields)throw new r(`The result shape for aggregate '${t}' is absent.`);return objectOf([...n.fields].map(n=>({name:n,type:aggregateLeafType(classifyAggregateLeaf(t,n,e[`~`].state.scalars))})))}function polymorphicType(e,t){let n=[];for(let[r,i]of e.variants)n.push(objectOf([{name:`type`,type:atom(JSON.stringify(r)),immutable:!0},{name:`data`,type:rowType(i.model,i.shape,t),immutable:!0}]));let r=n.length===0?atom(`never`):unionOf(...n);return e.cardinality===`many`?arrayOf(r,!0):e.optional?unionOf(r,y):r}function relationValue(e,t){return e.cardinality===`many`?arrayOf(t):e.optional?unionOf(t,y):t}function recursiveRowType(e,t,n,r){let i={name:`VibORMRecursiveNode${r.length+1}`,type:atom(`never`)};r.push(i);let a=atom(i.name);return i.type=objectOf([...rowFields(t.model,t.shape,r),{name:e,type:relationValue(t,a),...n===!1?{}:{optional:!0}}]),a}function rowType(e,t,n){return objectOf(rowFields(e,t,n))}function rowFields(e,t,n){let i=[];for(let a of t.rawKeys){let o=classifyResultColumn(e,a,t);switch(o.kind){case`empty`:break;case`distance`:i.push({name:`_distance`,type:o.scalar?.[`~`].state.type===`point`&&o.scalar[`~`].state.nullable?unionOf(atom(`number`),y):atom(`number`)});break;case`scalar`:i.push({name:o.key,type:scalarType(o.scalar)});break;case`relation`:{let e=requiredRelationShape(o.key,o.expected),t=e.recurrence?recursiveRowType(o.key,e,e.recurrence.depth,n):rowType(e.model,e.shape,n);i.push({name:o.key,type:relationValue(e,t)});break}case`polymorphic`:i.push({name:o.key,type:polymorphicType(requiredPolymorphicShape(o.key,o.expected),n)});break;case`relationCounts`:if(!o.relations)throw new r(`The relation-count result shape is absent.`);i.push({name:`_count`,type:objectOf([...o.relations].map(e=>({name:e,type:atom(`number`)})))});break;case`aggregate`:i.push({name:o.name,type:aggregateType(e,o.name,o.expected)});break;case`unknown`:throw new r(`The result shape contains unknown column '${o.key}'.`);default:throw new r(`The TypeScript renderer received an unknown result column.`)}}return i}function countType(e){return e.rawKeys.length===1&&e.rawKeys[0]===u?atom(`number`):objectOf(e.rawKeys.map(e=>({name:e,type:atom(`number`)})))}function operationResultType(e,t,n,i,a){if((t===`createMany`||t===`updateMany`||t===`deleteMany`)&&n===t)return renderType(objectOf([{name:`count`,type:atom(`number`)}]),0);let o=c(e,n,i,a);if(!o)throw new r(`Operation '${t}' has no renderable result shape.`);let s=[],l=o.carrier===`existence`?atom(`boolean`):o.carrier===`count`?countType(o):rowType(e,o,s);return t===`findMany`||t===`groupBy`||n===`createManyAndReturn`||n===`updateManyAndReturn`||n===`deleteManyAndReturn`?l=arrayOf(l):(t===`findFirst`||t===`findUnique`)&&(l=unionOf(l,y)),s.length===0?renderType(l,0):[{name:`VibORMOperationResult`,type:l},...s].map(({name:e,type:t})=>`type ${e} = ${renderType(t,0)};`).join(`
|
|
5
|
+
`)}function settledModel(e,t){let n=e[`~`].settleTarget(t);if(n instanceof h)return n;throw new r(`A relation target is not a model.`)}function schemaModelReference(e){let t=e[`~`].names.ts;if(!t)throw new r(`A schema model has no hydrated TypeScript name.`);return atom(`VibORMSchema[${JSON.stringify(t)}]`)}function schemaRelationType(e,t,n,i){let a=i.get(e)?.get(t);if(!a)throw new r(`The resolved schema has no relation slot for '${t}'.`);let o=n[`~`].state;if(g(o)){let e=Object.keys(o.target.entries).map(e=>objectOf([{name:`type`,type:atom(JSON.stringify(e)),immutable:!0},{name:`data`,type:schemaModelReference(settledModel(n,e)),immutable:!0}])),t=e.length===0?atom(`never`):unionOf(...e);return o.cardinality===`many`?arrayOf(t,!0):f(a)?unionOf(t,y):t}let s=schemaModelReference(settledModel(n));return o.cardinality===`many`?arrayOf(s):f(a)?unionOf(s,y):s}function schemaModelType(e,t){let n=e[`~`].state,i=[];for(let a of Object.keys(n.shape)){let o=Object.hasOwn(n.scalars,a)?n.scalars[a]:void 0;if(o){i.push({name:a,type:scalarType(o)});continue}let s=Object.hasOwn(n.relations,a)?n.relations[a]:void 0;if(s){i.push({name:a,type:schemaRelationType(e,a,s,t)});continue}throw new r(`Model '${e[`~`].names.ts??`model`}' has unknown field '${a}'.`)}return objectOf(i)}function schemaType(e,t){return`type VibORMSchema = ${renderType(objectOf(Object.entries(e).map(([e,n])=>({name:e,type:schemaModelType(n,t)}))),0)};`}function publicOperationOrThrow(e,n){if(t.has(n))return n;throw new i({kind:`registry`,model:e,property:n},[{path:`operation`,message:`${n} does not exist`}])}function requireIdentifier(e,t){if(typeof e==`string`)return e;throw new i({kind:`registry`,property:t},[{path:t,message:`${t} must be a string`}])}function resultOperation(e,t){switch(e){case`createMany`:case`updateMany`:case`deleteMany`:return t.select===void 0?e:`${e}AndReturn`;default:return n(e)}}function getOperationPayloadSchema(e,t,r){requireIdentifier(t,`model`);let i=publicOperationOrThrow(t,requireIdentifier(r,`operation`));return d(e).proxy[t].args[n(i)]}function validateOperationPayload(e,t,r,i){let a=requireIdentifier(t,`model`),o=publicOperationOrThrow(a,requireIdentifier(r,`operation`));return d(e).validate(a,n(o),i??{})}function renderOperationResultType(e,t,r,a){let o=requireIdentifier(t,`model`),s=publicOperationOrThrow(o,requireIdentifier(r,`operation`)),c=n(s);_(e);let l=m(e),u=p(e,l).validate(o,c,a??{}),d=e[o];if(!d)throw new i({kind:`registry`,model:o},[{path:o,message:`${o} does not exist`}]);return operationResultType(d,s,resultOperation(s,u),u,l)}function renderSchemaType(e){return _(e),schemaType(e,m(e))}export{validateOperationPayload as i,renderOperationResultType as n,renderSchemaType as r,getOperationPayloadSchema as t};
|
|
6
|
+
//# sourceMappingURL=schema-introspection-DEYGC2qg.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-introspection-DEYGC2qg.mjs","names":["expected"],"sources":["../src/query-engine/result/result-aggregate-leaf.ts","../src/query-engine/result/result-column.ts","../src/client/typescript-type-renderer.ts","../src/client/schema-introspection.ts"],"sourcesContent":["import type { Scalar } from \"@schema/scalars\";\nimport type { AggregateResultName } from \"../result-aliases\";\n\nexport type AggregateLeaf =\n | { readonly kind: \"count\"; readonly nullable: false }\n | { readonly kind: \"number\"; readonly nullable: true }\n | {\n readonly kind: \"scalar\";\n readonly nullable: true;\n readonly scalar: Scalar;\n }\n | {\n readonly kind: \"widenedSum\";\n readonly nullable: true;\n readonly scalar: Scalar;\n }\n | { readonly kind: \"unknown\" };\n\n/**\n * The one semantic classification of an aggregate result leaf. Provider\n * parsing and detached cache encoding must agree on widening and nullability.\n *\n * A `_sum` — admitted only on a decimal, bigint, number or int — is its OWN\n * leaf kind because it answers outside the column's declared domain: a number\n * sum may be `±Infinity`, an int sum may pass 2^53 (read as the nearest\n * double), a bigint sum may leave the int64 range, and summing\n * a million `precision: 10` rows is exact arithmetic whose result no single\n * column could store, so it keeps the field's scale and drops the field's\n * precision. Every other decimal aggregate stays in the field domain — `_min`\n * and `_max` are stored values, and `_avg` is quantized to the field's scale\n * by the shared half-even rounder before it leaves the database. Reading a sum\n * through the field decoder would refuse a correct answer; reading an average\n * through the widened one would accept a wrong one.\n */\nexport function classifyAggregateLeaf(\n name: AggregateResultName,\n field: string,\n scalars: Readonly<Record<string, Scalar>>\n): AggregateLeaf {\n const scalar: Scalar | undefined = Object.hasOwn(scalars, field)\n ? scalars[field]\n : undefined;\n if (name === \"_count\") {\n return field === \"_all\" || scalar\n ? { kind: \"count\", nullable: false }\n : { kind: \"unknown\" };\n }\n if (!scalar) return { kind: \"unknown\" };\n if (name === \"_avg\" && scalar[\"~\"].state.type !== \"decimal\") {\n return { kind: \"number\", nullable: true };\n }\n if (name === \"_sum\") return { kind: \"widenedSum\", nullable: true, scalar };\n return { kind: \"scalar\", nullable: true, scalar };\n}\n","import type { Model } from \"@schema/model\";\nimport { type AnyRelation, isVariantRelationState } from \"@schema/relation\";\nimport type { Scalar } from \"@schema/scalars\";\nimport {\n type AggregateResultName,\n DISTANCE_RESULT_KEY,\n EMPTY_ROW_RESULT_KEY,\n getAggregateResultName,\n RELATION_COUNTS_RESULT_KEY,\n} from \"../result-aliases\";\nimport type {\n ExpectedAggregateResultShape,\n ExpectedPolymorphicResultShape,\n ExpectedRelationResultShape,\n ExpectedResultShape,\n} from \"../types\";\n\nexport type ResultColumn =\n | { readonly kind: \"empty\" }\n | { readonly kind: \"distance\"; readonly scalar: Scalar | undefined }\n | {\n readonly kind: \"scalar\";\n readonly key: string;\n readonly scalar: Scalar;\n }\n | {\n readonly kind: \"relationCounts\";\n readonly relations: ReadonlySet<string>;\n }\n | {\n readonly kind: \"relation\";\n readonly key: string;\n readonly relation: AnyRelation;\n readonly expected: ExpectedRelationResultShape;\n }\n | {\n readonly kind: \"polymorphic\";\n readonly key: string;\n readonly relation: AnyRelation;\n readonly expected: ExpectedPolymorphicResultShape;\n }\n | {\n readonly kind: \"aggregate\";\n readonly name: AggregateResultName;\n readonly expected: ExpectedAggregateResultShape;\n }\n | { readonly kind: \"unknown\"; readonly key: string };\n\n/**\n * The one semantic classification of a compiled raw result column. SQL aliases\n * are translated to their public result owners here; parsing and detached cache\n * encoding consume the same decision.\n */\nexport function classifyResultColumn(\n model: Model<any>,\n key: string,\n shape: ExpectedResultShape\n): ResultColumn {\n if (key === EMPTY_ROW_RESULT_KEY) return { kind: \"empty\" };\n if (key === DISTANCE_RESULT_KEY) {\n return { kind: \"distance\", scalar: shape.distanceScalar };\n }\n\n const scalars = model[\"~\"].state.scalars;\n const scalar: Scalar | undefined = Object.hasOwn(scalars, key)\n ? scalars[key]\n : undefined;\n if (scalar) return { kind: \"scalar\", key, scalar };\n\n if (key === RELATION_COUNTS_RESULT_KEY) {\n return { kind: \"relationCounts\", relations: shape.relationCounts };\n }\n\n const relations = model[\"~\"].state.relations;\n const relation: AnyRelation | undefined = Object.hasOwn(relations, key)\n ? relations[key]\n : undefined;\n if (relation) {\n if (isVariantRelationState(relation[\"~\"].state)) {\n const expected = shape.polymorphic.get(key);\n if (!expected) return { kind: \"unknown\", key };\n return {\n kind: \"polymorphic\",\n key,\n relation,\n expected,\n };\n }\n const expected = shape.relations.get(key);\n if (!expected) return { kind: \"unknown\", key };\n return {\n kind: \"relation\",\n key,\n relation,\n expected,\n };\n }\n\n const name = getAggregateResultName(key);\n if (name) {\n const expected = shape.aggregates.get(key);\n if (!expected) return { kind: \"unknown\", key };\n return {\n kind: \"aggregate\",\n name,\n expected,\n };\n }\n\n return { kind: \"unknown\", key };\n}\n","import { COUNT_RESULT_KEY } from \"@adapters/shared/result-parsing\";\nimport { QueryEngineError } from \"@errors\";\nimport {\n type AggregateLeaf,\n classifyAggregateLeaf,\n} from \"@query-engine/result/result-aggregate-leaf\";\nimport { classifyResultColumn } from \"@query-engine/result/result-column\";\nimport { buildExpectedResultShape } from \"@query-engine/result/result-shape\";\nimport type {\n ExpectedAggregateResultShape,\n ExpectedPolymorphicResultShape,\n ExpectedRelationResultShape,\n ExpectedResultShape,\n Operation,\n} from \"@query-engine/types\";\nimport { type AnyModel, Model } from \"@schema/model\";\nimport {\n type AnyRelation,\n isVariantRelationState,\n slotMayBeEmpty,\n} from \"@schema/relation\";\nimport type { Scalar, ScalarType } from \"@schema/scalars\";\nimport type { ResolvedRelationIndex } from \"@schema/validation/relation-resolution\";\nimport type { Operations, Schema } from \"./types\";\n\ntype TypeNode =\n | { readonly kind: \"atom\"; readonly value: string }\n | {\n readonly kind: \"array\";\n readonly element: TypeNode;\n readonly immutable: boolean;\n }\n | { readonly kind: \"object\"; readonly fields: readonly TypeField[] }\n | { readonly kind: \"union\"; readonly members: readonly TypeNode[] };\n\ninterface TypeField {\n readonly name: string;\n readonly type: TypeNode;\n readonly immutable?: true;\n readonly optional?: true;\n}\n\n/**\n * One named alias a rendered result declares. A recursive relation is the\n * only type TypeScript cannot spell as one anonymous expression, so each\n * recursive slot is rendered once as a named alias whose repeated key refers\n * to the alias itself.\n */\ntype AliasDeclaration = { readonly name: string; type: TypeNode };\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\nconst NULL_TYPE: TypeNode = { kind: \"atom\", value: \"null\" };\n\nfunction atom(value: string): TypeNode {\n return { kind: \"atom\", value };\n}\n\nfunction arrayOf(element: TypeNode, immutable = false): TypeNode {\n return { kind: \"array\", element, immutable };\n}\n\nfunction objectOf(fields: readonly TypeField[]): TypeNode {\n return { kind: \"object\", fields };\n}\n\nfunction unionOf(...nodes: readonly TypeNode[]): TypeNode {\n const members: TypeNode[] = [];\n const seen = new Set<string>();\n for (const node of nodes) {\n const candidates = node.kind === \"union\" ? node.members : [node];\n for (const candidate of candidates) {\n const identity = renderType(candidate, 0);\n if (seen.has(identity)) continue;\n seen.add(identity);\n members.push(candidate);\n }\n }\n const [onlyMember] = members;\n if (!onlyMember) return atom(\"never\");\n return members.length === 1 ? onlyMember : { kind: \"union\", members };\n}\n\nfunction renderPropertyName(name: string): string {\n return IDENTIFIER.test(name) ? name : JSON.stringify(name);\n}\n\nfunction indentation(depth: number): string {\n return \" \".repeat(depth);\n}\n\nfunction renderType(node: TypeNode, depth: number): string {\n switch (node.kind) {\n case \"atom\":\n return node.value;\n case \"array\": {\n const typeConstructor = node.immutable ? \"ReadonlyArray\" : \"Array\";\n return `${typeConstructor}<${renderType(node.element, depth)}>`;\n }\n case \"union\":\n return node.members\n .map((member) => renderType(member, depth))\n .join(\" | \");\n case \"object\": {\n if (node.fields.length === 0) return \"{}\";\n const fieldIndentation = indentation(depth + 1);\n const fields = node.fields.map((field) => {\n const modifier = field.immutable ? \"readonly \" : \"\";\n const optional = field.optional ? \"?\" : \"\";\n return `${fieldIndentation}${modifier}${renderPropertyName(field.name)}${optional}: ${renderType(field.type, depth + 1)};`;\n });\n return `{\n${fields.join(\"\\n\")}\n${indentation(depth)}}`;\n }\n default:\n throw new QueryEngineError(\n \"The TypeScript renderer received an unknown node.\"\n );\n }\n}\n\nfunction enumType(scalar: Scalar): TypeNode {\n const values = Reflect.get(scalar[\"~\"].state.base, \"values\");\n if (\n !(\n Array.isArray(values) &&\n values.every((value) => typeof value === \"string\")\n )\n ) {\n throw new QueryEngineError(\"An enum scalar has no readable string values.\");\n }\n return unionOf(...values.map((value) => atom(JSON.stringify(value))));\n}\n\n/** Scalar kinds whose TypeScript type is one fixed atom. */\nconst SCALAR_ATOMS: Readonly<\n Record<Exclude<ScalarType, \"vector\" | \"point\" | \"enum\">, string>\n> = Object.freeze({\n string: \"string\",\n time: \"string\",\n int: \"number\",\n number: \"number\",\n decimal: 'import(\"viborm\").Decimal',\n boolean: \"boolean\",\n datetime: \"Date\",\n date: \"Date\",\n bigint: \"bigint\",\n // A custom Standard Schema carries its output only in an erased generic.\n json: \"unknown\",\n blob: \"Uint8Array\",\n});\n\nfunction scalarType(scalar: Scalar): TypeNode {\n const state = scalar[\"~\"].state;\n let value: TypeNode;\n if (Object.hasOwn(SCALAR_ATOMS, state.type)) {\n value = atom(SCALAR_ATOMS[state.type as keyof typeof SCALAR_ATOMS]);\n } else if (state.type === \"vector\") {\n value = arrayOf(atom(\"number\"));\n } else if (state.type === \"point\") {\n value = objectOf([\n { name: \"longitude\", type: atom(\"number\") },\n { name: \"latitude\", type: atom(\"number\") },\n ]);\n } else if (state.type === \"enum\") {\n value = enumType(scalar);\n } else {\n throw new QueryEngineError(\n \"The TypeScript renderer does not support this scalar type.\"\n );\n }\n if (state.array) value = arrayOf(value);\n return state.nullable ? unionOf(value, NULL_TYPE) : value;\n}\n\nfunction requiredRelationShape(\n relationName: string,\n expected: ExpectedRelationResultShape | undefined\n): ExpectedRelationResultShape {\n if (expected) return expected;\n throw new QueryEngineError(\n `The result shape for relation '${relationName}' is absent.`\n );\n}\n\nfunction requiredPolymorphicShape(\n relationName: string,\n expected: ExpectedPolymorphicResultShape | undefined\n): ExpectedPolymorphicResultShape {\n if (expected) return expected;\n throw new QueryEngineError(\n `The result shape for polymorphic relation '${relationName}' is absent.`\n );\n}\n\nfunction aggregateLeafType(leaf: AggregateLeaf): TypeNode {\n switch (leaf.kind) {\n case \"count\":\n case \"number\":\n return leaf.nullable\n ? unionOf(atom(\"number\"), NULL_TYPE)\n : atom(\"number\");\n case \"scalar\":\n case \"widenedSum\":\n return unionOf(scalarType(leaf.scalar), NULL_TYPE);\n case \"unknown\":\n throw new QueryEngineError(\n \"The aggregate result contains an unknown field.\"\n );\n default:\n throw new QueryEngineError(\n \"The TypeScript renderer received an unknown aggregate leaf.\"\n );\n }\n}\n\nfunction aggregateType(\n model: AnyModel,\n name: \"_count\" | \"_avg\" | \"_sum\" | \"_min\" | \"_max\",\n expected: ExpectedAggregateResultShape | undefined\n): TypeNode {\n if (name === \"_count\" && expected?.fields === undefined) {\n return atom(\"number\");\n }\n if (!expected?.fields) {\n throw new QueryEngineError(\n `The result shape for aggregate '${name}' is absent.`\n );\n }\n const fields = [...expected.fields].map((fieldName) => ({\n name: fieldName,\n type: aggregateLeafType(\n classifyAggregateLeaf(name, fieldName, model[\"~\"].state.scalars)\n ),\n }));\n return objectOf(fields);\n}\n\nfunction polymorphicType(\n expected: ExpectedPolymorphicResultShape,\n declarations: AliasDeclaration[]\n): TypeNode {\n const variants: TypeNode[] = [];\n for (const [publicType, variant] of expected.variants) {\n variants.push(\n objectOf([\n {\n name: \"type\",\n type: atom(JSON.stringify(publicType)),\n immutable: true,\n },\n {\n name: \"data\",\n type: rowType(variant.model, variant.shape, declarations),\n immutable: true,\n },\n ])\n );\n }\n const member = variants.length === 0 ? atom(\"never\") : unionOf(...variants);\n if (expected.cardinality === \"many\") return arrayOf(member, true);\n return expected.optional ? unionOf(member, NULL_TYPE) : member;\n}\n\n/** A relation slot's cardinality and emptiness around one row type. */\nfunction relationValue(\n expected: ExpectedRelationResultShape,\n row: TypeNode\n): TypeNode {\n if (expected.cardinality === \"many\") return arrayOf(row);\n return expected.optional ? unionOf(row, NULL_TYPE) : row;\n}\n\n/**\n * One recursive slot: the ordinary node row once, as a named alias whose own\n * key repeats the slot. A numeric cutoff may leave that key absent, so it is\n * optional; an exhaustive traversal publishes it on every occurrence.\n */\nfunction recursiveRowType(\n key: string,\n expected: ExpectedRelationResultShape,\n depth: number | false,\n declarations: AliasDeclaration[]\n): TypeNode {\n const declaration: AliasDeclaration = {\n name: `VibORMRecursiveNode${declarations.length + 1}`,\n type: atom(\"never\"),\n };\n declarations.push(declaration);\n const self = atom(declaration.name);\n declaration.type = objectOf([\n ...rowFields(expected.model, expected.shape, declarations),\n {\n name: key,\n type: relationValue(expected, self),\n ...(depth === false ? {} : { optional: true as const }),\n },\n ]);\n return self;\n}\n\nfunction rowType(\n model: AnyModel,\n shape: ExpectedResultShape,\n declarations: AliasDeclaration[]\n): TypeNode {\n return objectOf(rowFields(model, shape, declarations));\n}\n\nfunction rowFields(\n model: AnyModel,\n shape: ExpectedResultShape,\n declarations: AliasDeclaration[]\n): TypeField[] {\n const fields: TypeField[] = [];\n for (const rawKey of shape.rawKeys) {\n const column = classifyResultColumn(model, rawKey, shape);\n switch (column.kind) {\n case \"empty\":\n break;\n case \"distance\":\n fields.push({\n name: \"_distance\",\n type:\n column.scalar?.[\"~\"].state.type === \"point\" &&\n column.scalar[\"~\"].state.nullable\n ? unionOf(atom(\"number\"), NULL_TYPE)\n : atom(\"number\"),\n });\n break;\n case \"scalar\":\n fields.push({ name: column.key, type: scalarType(column.scalar) });\n break;\n case \"relation\": {\n const expected = requiredRelationShape(column.key, column.expected);\n const relatedRow = expected.recurrence\n ? recursiveRowType(\n column.key,\n expected,\n expected.recurrence.depth,\n declarations\n )\n : rowType(expected.model, expected.shape, declarations);\n fields.push({\n name: column.key,\n type: relationValue(expected, relatedRow),\n });\n break;\n }\n case \"polymorphic\":\n fields.push({\n name: column.key,\n type: polymorphicType(\n requiredPolymorphicShape(column.key, column.expected),\n declarations\n ),\n });\n break;\n case \"relationCounts\": {\n if (!column.relations) {\n throw new QueryEngineError(\n \"The relation-count result shape is absent.\"\n );\n }\n fields.push({\n name: \"_count\",\n type: objectOf(\n [...column.relations].map((relationName) => ({\n name: relationName,\n type: atom(\"number\"),\n }))\n ),\n });\n break;\n }\n case \"aggregate\":\n fields.push({\n name: column.name,\n type: aggregateType(model, column.name, column.expected),\n });\n break;\n case \"unknown\":\n throw new QueryEngineError(\n `The result shape contains unknown column '${column.key}'.`\n );\n default:\n throw new QueryEngineError(\n \"The TypeScript renderer received an unknown result column.\"\n );\n }\n }\n return fields;\n}\n\nfunction countType(shape: ExpectedResultShape): TypeNode {\n if (shape.rawKeys.length === 1 && shape.rawKeys[0] === COUNT_RESULT_KEY) {\n return atom(\"number\");\n }\n return objectOf(\n shape.rawKeys.map((fieldName) => ({\n name: fieldName,\n type: atom(\"number\"),\n }))\n );\n}\n\n/**\n * The schema-only result type of one admitted payload, from its expected\n * shape alone: no driver, no SQL, no client default-omit or extension.\n *\n * Almost every result renders as ONE type expression. A recursive relation\n * slot cannot: its node refers to itself, and TypeScript names recursion only\n * through a declaration (format: `renderOperationResultType`). The text names\n * no exported helper.\n */\nexport function operationResultType(\n model: AnyModel,\n publicOperation: Operations,\n engineOperation: Operation,\n args: Record<string, unknown>,\n index: ResolvedRelationIndex\n): string {\n if (\n (publicOperation === \"createMany\" ||\n publicOperation === \"updateMany\" ||\n publicOperation === \"deleteMany\") &&\n engineOperation === publicOperation\n ) {\n return renderType(objectOf([{ name: \"count\", type: atom(\"number\") }]), 0);\n }\n\n const shape = buildExpectedResultShape(model, engineOperation, args, index);\n if (!shape) {\n throw new QueryEngineError(\n `Operation '${publicOperation}' has no renderable result shape.`\n );\n }\n\n const declarations: AliasDeclaration[] = [];\n let value =\n shape.carrier === \"existence\"\n ? atom(\"boolean\")\n : shape.carrier === \"count\"\n ? countType(shape)\n : rowType(model, shape, declarations);\n\n if (\n publicOperation === \"findMany\" ||\n publicOperation === \"groupBy\" ||\n engineOperation === \"createManyAndReturn\" ||\n engineOperation === \"updateManyAndReturn\" ||\n engineOperation === \"deleteManyAndReturn\"\n ) {\n value = arrayOf(value);\n } else if (\n publicOperation === \"findFirst\" ||\n publicOperation === \"findUnique\"\n ) {\n value = unionOf(value, NULL_TYPE);\n }\n if (declarations.length === 0) return renderType(value, 0);\n return [{ name: \"VibORMOperationResult\", type: value }, ...declarations]\n .map(({ name, type }) => `type ${name} = ${renderType(type, 0)};`)\n .join(\"\\n\");\n}\n\nfunction settledModel(relation: AnyRelation, variant?: string): AnyModel {\n const target = relation[\"~\"].settleTarget(variant);\n if (target instanceof Model) return target;\n throw new QueryEngineError(\"A relation target is not a model.\");\n}\n\nfunction schemaModelReference(model: AnyModel): TypeNode {\n const modelName = model[\"~\"].names.ts;\n if (!modelName) {\n throw new QueryEngineError(\n \"A schema model has no hydrated TypeScript name.\"\n );\n }\n return atom(`VibORMSchema[${JSON.stringify(modelName)}]`);\n}\n\nfunction schemaRelationType(\n model: AnyModel,\n fieldName: string,\n relation: AnyRelation,\n index: ResolvedRelationIndex\n): TypeNode {\n const resolved = index.get(model)?.get(fieldName);\n if (!resolved) {\n throw new QueryEngineError(\n `The resolved schema has no relation slot for '${fieldName}'.`\n );\n }\n const state = relation[\"~\"].state;\n if (isVariantRelationState(state)) {\n const variants = Object.keys(state.target.entries).map((publicType) =>\n objectOf([\n {\n name: \"type\",\n type: atom(JSON.stringify(publicType)),\n immutable: true,\n },\n {\n name: \"data\",\n type: schemaModelReference(settledModel(relation, publicType)),\n immutable: true,\n },\n ])\n );\n const member = variants.length === 0 ? atom(\"never\") : unionOf(...variants);\n if (state.cardinality === \"many\") return arrayOf(member, true);\n return slotMayBeEmpty(resolved) ? unionOf(member, NULL_TYPE) : member;\n }\n\n const target = schemaModelReference(settledModel(relation));\n if (state.cardinality === \"many\") return arrayOf(target);\n return slotMayBeEmpty(resolved) ? unionOf(target, NULL_TYPE) : target;\n}\n\nfunction schemaModelType(\n model: AnyModel,\n index: ResolvedRelationIndex\n): TypeNode {\n const state = model[\"~\"].state;\n const fields: TypeField[] = [];\n for (const fieldName of Object.keys(state.shape)) {\n const scalar = Object.hasOwn(state.scalars, fieldName)\n ? state.scalars[fieldName]\n : undefined;\n if (scalar) {\n fields.push({ name: fieldName, type: scalarType(scalar) });\n continue;\n }\n const relation = Object.hasOwn(state.relations, fieldName)\n ? state.relations[fieldName]\n : undefined;\n if (relation) {\n fields.push({\n name: fieldName,\n type: schemaRelationType(model, fieldName, relation, index),\n });\n continue;\n }\n const modelName = model[\"~\"].names.ts ?? \"model\";\n throw new QueryEngineError(\n `Model '${modelName}' has unknown field '${fieldName}'.`\n );\n }\n return objectOf(fields);\n}\n\nexport function schemaType(\n schema: Schema,\n index: ResolvedRelationIndex\n): string {\n const models = Object.entries(schema).map(([modelName, model]) => ({\n name: modelName,\n type: schemaModelType(model, index),\n }));\n return `type VibORMSchema = ${renderType(objectOf(models), 0)};`;\n}\n","import { ValidationError } from \"@errors\";\nimport {\n baseOperation,\n ROUTED_OPERATIONS,\n} from \"@query-engine/routed-operations\";\nimport type { Operation } from \"@query-engine/types\";\nimport { hydrateSchemaNames } from \"@schema/hydration\";\nimport { resolveSchemaOrThrow } from \"@schema/validation\";\nimport {\n createResolvedSchemaRegistry,\n createSchemaRegistry,\n} from \"@validation/builder\";\nimport type {\n OperationPayloadSchema,\n Operations,\n Schema,\n ValidatedOperationPayload,\n} from \"./types\";\nimport { operationResultType, schemaType } from \"./typescript-type-renderer\";\n\nfunction publicOperationOrThrow(\n modelName: string,\n operation: string\n): Operations {\n if (ROUTED_OPERATIONS.has(operation)) return operation as Operations;\n throw new ValidationError(\n { kind: \"registry\", model: modelName, property: operation },\n [{ path: \"operation\", message: `${operation} does not exist` }]\n );\n}\n\nfunction requireIdentifier(\n value: unknown,\n path: \"model\" | \"operation\"\n): string {\n if (typeof value === \"string\") return value;\n throw new ValidationError({ kind: \"registry\", property: path }, [\n { path, message: `${path} must be a string` },\n ]);\n}\n\nfunction resultOperation(\n operation: Operations,\n args: Record<string, unknown>\n): Operation {\n switch (operation) {\n case \"createMany\":\n case \"updateMany\":\n case \"deleteMany\":\n return args.select === undefined ? operation : `${operation}AndReturn`;\n default:\n return baseOperation(operation);\n }\n}\n\n/** Return the canonical Standard Schema for one public operation payload. */\nexport function getOperationPayloadSchema<\n const S extends Schema,\n ModelName extends Extract<keyof S, string>,\n OperationName extends Operations,\n>(\n schema: S,\n modelName: ModelName,\n operation: OperationName\n): OperationPayloadSchema<OperationName, S[ModelName]>;\nexport function getOperationPayloadSchema<\n const S extends Schema,\n ModelName extends Extract<keyof S, string>,\n>(schema: S, modelName: ModelName, operation: unknown): unknown {\n requireIdentifier(modelName, \"model\");\n const validatedOperation = publicOperationOrThrow(\n modelName,\n requireIdentifier(operation, \"operation\")\n );\n return createSchemaRegistry(schema).proxy[modelName].args[\n baseOperation(validatedOperation)\n ];\n}\n\n/**\n * Validate one public model-operation payload and return its normalized value.\n * This is schema validation, not a driver-specific executability check.\n */\nexport function validateOperationPayload<\n const S extends Schema,\n ModelName extends Extract<keyof S, string>,\n OperationName extends Operations,\n>(\n schema: S,\n modelName: ModelName,\n operation: OperationName,\n payload: unknown\n): ValidatedOperationPayload<OperationName, S[ModelName]>;\nexport function validateOperationPayload(\n schema: Schema,\n modelName: unknown,\n operation: unknown,\n payload: unknown\n): unknown {\n const validatedModelName = requireIdentifier(modelName, \"model\");\n const validatedOperation = publicOperationOrThrow(\n validatedModelName,\n requireIdentifier(operation, \"operation\")\n );\n const registry = createSchemaRegistry(schema);\n return registry.validate(\n validatedModelName,\n baseOperation(validatedOperation),\n payload ?? {}\n );\n}\n\n/**\n * Render the concrete return type for one validated public operation payload.\n * Client extensions and `defaultOmit()` are not part of this schema-only view:\n * on a client whose extensions declare `rows`, a to-one relation can read\n * `null` where the rendered type says it cannot.\n *\n * A payload with a recursive relation slot renders as declarations — a\n * `VibORMOperationResult` alias followed by one `VibORMRecursiveNodeN` alias per\n * recursive slot, numbered outer-first — because a finite recursive type needs\n * a name; every other result renders as one type expression.\n */\nexport function renderOperationResultType<\n const S extends Schema,\n ModelName extends Extract<keyof S, string>,\n>(\n schema: S,\n modelName: ModelName,\n operation: Operations,\n payload: unknown\n): string;\nexport function renderOperationResultType(\n schema: Schema,\n modelName: unknown,\n operation: unknown,\n payload: unknown\n): string {\n const validatedModelName = requireIdentifier(modelName, \"model\");\n const validatedOperation = publicOperationOrThrow(\n validatedModelName,\n requireIdentifier(operation, \"operation\")\n );\n const schemaOperation = baseOperation(validatedOperation);\n hydrateSchemaNames(schema);\n const index = resolveSchemaOrThrow(schema);\n const registry = createResolvedSchemaRegistry(schema, index);\n const validated = registry.validate(\n validatedModelName,\n schemaOperation,\n payload ?? {}\n );\n const model = schema[validatedModelName];\n if (!model) {\n throw new ValidationError({ kind: \"registry\", model: validatedModelName }, [\n {\n path: validatedModelName,\n message: `${validatedModelName} does not exist`,\n },\n ]);\n }\n return operationResultType(\n model,\n validatedOperation,\n resultOperation(validatedOperation, validated),\n validated,\n index\n );\n}\n\n/**\n * Render the complete schema graph as a recursive `VibORMSchema` declaration.\n * Custom JSON schema output is `unknown` because Standard Schema erases it at runtime.\n */\nexport function renderSchemaType<const S extends Schema>(schema: S): string {\n hydrateSchemaNames(schema);\n return schemaType(schema, resolveSchemaOrThrow(schema));\n}\n"],"mappings":"2fAkCA,SAAgB,sBACd,EACA,EACA,EACe,CACf,IAAM,EAA6B,OAAO,OAAO,EAAS,EAAM,CAC5D,EAAQ,GACR,IAAA,GAWJ,OAVI,IAAS,SACJ,IAAU,QAAU,EACvB,CAAE,KAAM,QAAS,SAAU,GAAO,CAClC,CAAE,KAAM,UAAW,CAEpB,EACD,IAAS,QAAU,EAAO,KAAK,MAAM,OAAS,UACzC,CAAE,KAAM,SAAU,SAAU,GAAM,CAEvC,IAAS,OAAe,CAAE,KAAM,aAAc,SAAU,GAAM,SAAQ,CACnE,CAAE,KAAM,SAAU,SAAU,GAAM,SAAQ,CAL7B,CAAE,KAAM,UAAW,CCMzC,SAAgB,qBACd,EACA,EACA,EACc,CACd,GAAI,IAAQ,EAAsB,MAAO,CAAE,KAAM,QAAS,CAC1D,GAAI,IAAQ,EACV,MAAO,CAAE,KAAM,WAAY,OAAQ,EAAM,eAAgB,CAG3D,IAAM,EAAU,EAAM,KAAK,MAAM,QAC3B,EAA6B,OAAO,OAAO,EAAS,EAAI,CAC1D,EAAQ,GACR,IAAA,GACJ,GAAI,EAAQ,MAAO,CAAE,KAAM,SAAU,MAAK,SAAQ,CAElD,GAAI,IAAQ,EACV,MAAO,CAAE,KAAM,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AAmB,EAkBrC,SAAgB,yBACd,EACA,EACA,EACA,EACS,CACT,IAAM,EAAqB,kBAAkB,EAAW,QAAQ,CAC1D,EAAqB,uBACzB,EACA,kBAAkB,EAAW,YAAY,CAC1C,CAED,OADiB,EAAqB,EAAO,CAC7B,SACd,EACA,EAAc,EAAmB,CACjC,GAAW,EAAE,CACd,CAuBH,SAAgB,0BACd,EACA,EACA,EACA,EACQ,CACR,IAAM,EAAqB,kBAAkB,EAAW,QAAQ,CAC1D,EAAqB,uBACzB,EACA,kBAAkB,EAAW,YAAY,CAC1C,CACK,EAAkB,EAAc,EAAmB,CACzD,EAAmB,EAAO,CAC1B,IAAM,EAAQ,EAAqB,EAAO,CAEpC,EADW,EAA6B,EAAQ,EAAM,CACjC,SACzB,EACA,EACA,GAAW,EAAE,CACd,CACK,EAAQ,EAAO,GACrB,GAAI,CAAC,EACH,MAAM,IAAI,EAAgB,CAAE,KAAM,WAAY,MAAO,EAAoB,CAAE,CACzE,CACE,KAAM,EACN,QAAS,GAAG,EAAmB,iBAChC,CACF,CAAC,CAEJ,OAAO,oBACL,EACA,EACA,gBAAgB,EAAoB,EAAU,CAC9C,EACA,EACD,CAOH,SAAgB,iBAAyC,EAAmB,CAE1E,OADA,EAAmB,EAAO,CACnB,WAAW,EAAQ,EAAqB,EAAO,CAAC"}
|
package/dist/schema.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { $n as GeneratorDefaultBrand, Cr as IsoTimestampSchema, Ct as BooleanScalar, Dr as BooleanSchema, Dt as ModelToManyRelation, Et as ReferencesStage, Fn as StringSchema, G as VariantToOneRelation, Gi as MYSQL, Gn as InitialModelState, Gr as Getter, Ji as PG, Jn as ModelState, Jr as RelationCardinality, K as Scalar, Ki as NativeType, Kn as Model, Ot as s, Sr as IsoTimeSchema, St as DateScalar, Tr as EnumSchema, Tt as ModelToOneRelation, U as ModelShape, Ui as DecimalDescriptor, Vi as GeoPoint, Vn as AnyModel, W as VariantToManyRelation, Wr as AnyRelation, Xn as DecimalSchema, Yi as SQLITE, Yn as UpdateState, Yr as RelationSlot, Zn as AutoGenerate, _t as IntScalar, bt as TimeScalar, cr as PointSchema, dt as NumericScalar, er as InitialScalarState, fr as IntegerSchema, ft as VectorScalar, gr as JsonSchema, gt as JsonScalar, ht as NumberScalar, jr as BigIntSchema, kr as BlobSchema, mt as PointScalar, or as VectorSchema, pr as NumberSchema, pt as StringScalar, q as BigIntScalar, qi as NativeTypeMap, qn as ModelInternal, qr as ReferentialAction, rr as UpdateState$1, tr as ScalarState, vt as EnumScalar, wt as BlobScalar, xr as IsoDateSchema, xt as DateTimeScalar, yt as DecimalScalar } from "./index-C_XLSTy2.mjs";
|
|
2
2
|
export { type AnyModel, type AnyRelation, type AutoGenerate, type BigIntScalar, type BigIntSchema, type BlobScalar, type BlobSchema, type BooleanScalar, type BooleanSchema, type DateScalar, type DateTimeScalar, type DecimalDescriptor, type DecimalScalar, type DecimalSchema, type EnumScalar, type EnumSchema, type GeneratorDefaultBrand, type GeoPoint, type Getter, type InitialModelState, type InitialScalarState, type IntScalar, type IntegerSchema, type IsoDateSchema, type IsoTimeSchema, type IsoTimestampSchema, type JsonScalar, type JsonSchema as JsonValueSchema, MYSQL, type Model, type ModelInternal, type ModelShape, type ModelState, type ModelToManyRelation, type ModelToOneRelation, type UpdateState as ModelUpdateState, type NativeType, type NativeTypeMap, type NumberScalar, type NumberSchema, type NumericScalar, PG, type PointScalar, type PointSchema, type ReferencesStage, type ReferentialAction, type RelationCardinality, type RelationSlot, SQLITE, type Scalar, type ScalarState, type UpdateState$1 as ScalarUpdateState, type StringScalar, type StringSchema, type TimeScalar, type VariantToManyRelation, type VariantToOneRelation, type VectorScalar, type VectorSchema, s };
|
package/dist/schema.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e,r as t,t as n}from"./native-types-veeTk36s.mjs";import{t as r}from"./schema-
|
|
1
|
+
import{i as e,r as t,t as n}from"./native-types-veeTk36s.mjs";import{t as r}from"./schema-Cjem1-0f.mjs";export{n as MYSQL,t as PG,e as SQLITE,r as s};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./sql
|
|
2
|
-
//# sourceMappingURL=select-assembly-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./sql-Bp7jicEX.mjs";const passThroughParseResult=(e,t,n)=>n();function createNamedConstraintIdentities(e){let identity=(e,t)=>({name:t,normalizedError:{table:e,constraint:t}});return{primaryKey:t=>identity(t,e(t)),unique:(e,t)=>identity(e,`${e}_${t}_key`)}}const n={primaryKey:(e,t)=>({name:`${e}_pkey`,normalizedError:{table:e,columns:[...t]}}),unique:(e,t,n)=>({name:`${e}_${t}_key`,normalizedError:{table:e,columns:[...n]}})};function installGeoPointSql(e,t){let n;if(t){let e=t.withinPolygon,r=t.distance;n=Object.freeze({value:t.value,longitude:t.longitude,latitude:t.latitude,equals:t.equals,withinBounds:t.withinBounds,...e?{withinPolygon:e}:{},...r?{distance:r}:{}})}Object.defineProperty(e,`geoPoint`,{value:n,writable:!1,enumerable:!0,configurable:!1})}const scaleFactorSql=e=>t.raw(`1${`0`.repeat(e)}`),scaleUnitSql=e=>t.raw(e===0?`1`:`0.${`0`.repeat(e-1)}1`),halfEvenQuotient=(e,n,r)=>{let i=e.quotient(n,r),a=e.remainder(n,r);return t`(${i} + (CASE WHEN ABS(${a}) > ${r} - ABS(${a}) OR (ABS(${a}) = ${r} - ABS(${a}) AND ${e.remainder(i,t.raw`2`)} <> 0) THEN (CASE WHEN ${a} < 0 THEN -1 ELSE 1 END) ELSE 0 END))`},signedNumerator=(e,n)=>t`(CASE WHEN ${n} < 0 THEN -${e} ELSE ${e} END)`,logicalDecimalMultiply=(e,n,r,i)=>t`${n} = ${halfEvenQuotient(e,t`(${n} * ${r} * ${scaleFactorSql(i.scale)})`,t.raw`1`)} * ${scaleUnitSql(i.scale)}`,logicalDecimalDivide=(e,n,r,i)=>t`${n} = ${halfEvenQuotient(e,signedNumerator(t`(${n} * ${scaleFactorSql(i.scale)})`,r),t`ABS(${r})`)} * ${scaleUnitSql(i.scale)}`,logicalDecimalAverage=(e,n,r)=>t`(${halfEvenQuotient(e,t`(SUM(${n}) * ${scaleFactorSql(r.scale)})`,t`COUNT(${n})`)} * ${scaleUnitSql(r.scale)})`;function createGeoPointCoordinatePredicates(e,n,r,i){return{equals(i,a){let o=e(i),s=r.eq(o,t`${a.longitude}`);return a.longitude===180&&(s=r.or(s,r.eq(o,t`${-180}`))),r.and(s,r.eq(n(i),t`${a.latitude}`))},withinBounds(a,o){let s=e(a),c=r.and(r.gte(n(a),t`${o.south}`),r.lte(n(a),t`${o.north}`)),l;if(o.west===-180&&o.east===180)l=c;else{let e=r.gte(s,t`${o.west}`),n=r.lte(s,t`${o.east}`),i=o.west>o.east?r.or(e,n):r.and(e,n);o.west===-180&&o.east<180&&(i=r.or(i,r.eq(s,t`${180}`))),o.east===180&&o.west>-180&&(i=r.or(i,r.eq(s,t`${-180}`))),l=r.and(c,i)}let u=i?.(a,o);return u?r.and(u,l):l}}}function geoBoundsIndexPolygons(e){return e.south===-90||e.north===90||e.south===e.north||e.west===e.east||e.west>e.east||e.west===-180||e.east===180?[]:[boundsPolygonJson(e.west,e.east,e.south,e.north)]}function boundsPolygonJson(e,t,n,r){let i=[e,...[-90,0,90].filter(n=>e<n&&n<t),t],a=i.map(e=>[e,n]),o=[...i].reverse().map(e=>[e,r]);return JSON.stringify({type:`Polygon`,coordinates:[[...a,...o,a[0]]]})}function geoPolygonJson(e){let t=[closedRing(e.outer)];if(e.holes)for(let n of e.holes)t.push(closedRing(n));return JSON.stringify({type:`Polygon`,coordinates:t})}function closedRing(e){let t=Array(e.length+1);for(let n=0;n<e.length;n+=1){let r=e[n];t[n]=[r.longitude,r.latitude]}let n=e[0];return t[e.length]=[n.longitude,n.latitude],t}const assembleSelectQuery=(e,n,r)=>{let i=[e,t`FROM ${n.from}`];return appendSelectParts(i,n,r),r.forUpdate===`append`&&n.forUpdate&&i.push(t.raw`FOR UPDATE`),t.join(i,` `)},appendSelectParts=(e,n,r)=>{appendFilterParts(e,n),n.orderBy&&e.push(t`ORDER BY ${n.orderBy}`),appendLimitOffset(e,n.limit,n.offset,r.noLimitValue)},appendFilterParts=(e,n)=>{n.joins&&n.joins.length>0&&e.push(...n.joins),n.where&&e.push(t`WHERE ${n.where}`),n.groupBy&&e.push(t`GROUP BY ${n.groupBy}`),n.having&&e.push(t`HAVING ${n.having}`)},appendLimitOffset=(e,n,r,i)=>{n?e.push(t`LIMIT ${n}`):r&&i&&e.push(t`LIMIT ${i}`),r&&e.push(t`OFFSET ${r}`)},assembleDistinctOnEmulation=(e,n,r,i)=>{let a=e.distinctOrderBy??e.orderBy??n,o=[e.columns,t`ROW_NUMBER() OVER (PARTITION BY ${n} ORDER BY ${a}) AS ${r(`_rn`)}`];e.orderBy&&o.push(t`ROW_NUMBER() OVER (ORDER BY ${e.orderBy}) AS ${r(`_ord`)}`);let s=[t`SELECT ${t.join(o,`, `)}`,t`FROM ${e.from}`];appendFilterParts(s,e);let c=t.join(s,` `),l=e.distinctColumnAliases.map(r),u=[t`SELECT ${t.join(l,`, `)} FROM (${c}) AS ${r(`_distinct_subquery`)}`,t`WHERE ${r(`_rn`)} = 1`];return e.orderBy&&u.push(t`ORDER BY ${r(`_ord`)}`),appendLimitOffset(u,e.limit,e.offset,i),t.join(u,` `)};export{geoPolygonJson as a,logicalDecimalDivide as c,scaleUnitSql as d,signedNumerator as f,passThroughParseResult as g,n as h,geoBoundsIndexPolygons as i,logicalDecimalMultiply as l,createNamedConstraintIdentities as m,assembleSelectQuery as n,halfEvenQuotient as o,installGeoPointSql as p,createGeoPointCoordinatePredicates as r,logicalDecimalAverage as s,assembleDistinctOnEmulation as t,scaleFactorSql as u};
|
|
2
|
+
//# sourceMappingURL=select-assembly-f1UGoblh.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"select-assembly-f1UGoblh.mjs","names":["sql","sql"],"sources":["../src/adapters/adapter-result-parser.ts","../src/adapters/constraint-identity.ts","../src/adapters/database-adapter.ts","../src/adapters/shared/decimal-arithmetic.ts","../src/adapters/shared/geo-point.ts","../src/adapters/shared/select-assembly.ts"],"sourcesContent":["import type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport type { DecimalPhysicalRepresentation } from \"@validation/primitives/decimal-codec\";\nimport type {\n IdDomain,\n IdRepresentation,\n} from \"@validation/primitives/id-codec\";\n\nexport interface AdapterResultParser {\n /**\n * How this dialect physically spells a decimal on the way back.\n *\n * `\"coefficient\"` means the column stores (and therefore returns) the signed\n * unscaled integer, cast to text before a driver can round an int64 into a\n * double — the SQLite family, which has no exact decimal type. Every other\n * provider returns native exact decimal text, which is the default when this\n * is unset.\n *\n * It is DECLARED and never inferred: at scale 2 the text `\"120\"` is logical\n * 120 in one vocabulary and logical 1.2 in the other, so a value cannot be\n * read without knowing which promise produced it. Declaring it on the adapter\n * is also what keeps the result parser from asking a dialect question, which\n * the layering rule forbids.\n */\n decimalRepresentation?: DecimalPhysicalRepresentation;\n\n /**\n * How this dialect physically spells a decimal LIST on the way back.\n *\n * `\"coefficient\"` means the column holds a JSON array of unscaled coefficient\n * STRINGS, read back as the container text — JSON has no exact decimal, and a\n * numeric token would already have been rounded past 2^53 by JavaScript or D1\n * (plan 6.1). Unset means the column is a native decimal array whose members\n * arrive as exact decimal text, one JavaScript array member each.\n *\n * A SEPARATE declaration from {@link AdapterResultParser.decimalRepresentation}\n * because the two genuinely differ: MySQL's scalar column is `DECIMAL(p,s)`\n * and answers with text while its list column is JSON and answers with\n * coefficients. Deriving one from the other would decode every MySQL list\n * member at the wrong scale, and the two spellings are indistinguishable by\n * inspection — at scale 2 the member `\"120\"` is 120 in one and 1.2 in the\n * other.\n */\n decimalListRepresentation?: DecimalPhysicalRepresentation;\n\n /**\n * How this dialect physically spells a datetime column that DECLARES the given\n * native type. Unset means timestamp text for every field, which is what every\n * dialect with a temporal column type stores.\n *\n * A function rather than a value because this promise is per FIELD, not per\n * dialect: SQLite has no temporal type at all, so `s.dateTime()` accepts a\n * declaration choosing between TEXT, an INTEGER count of epoch milliseconds\n * and a REAL Julian day, and the DDL already builds the column that way. The\n * adapter is asked because the declaration is dialect vocabulary — a\n * PostgreSQL native type reaching a SQLite adapter describes no column here\n * and answers `\"text\"` like an undeclared field.\n *\n * It is DECLARED and never inferred for the same reason\n * {@link AdapterResultParser.decimalRepresentation} is: the number\n * `2460324.9375` is one instant as a Julian day and a completely different one\n * as milliseconds, so a value cannot be read without knowing which promise\n * produced it.\n */\n dateTimeRepresentation?: (\n nativeType: NativeTypeDeclaration | undefined\n ) => DateTimePhysicalForm;\n\n /**\n * How this dialect physically spells an enum LIST on the way back.\n *\n * `\"arrayText\"` means the column is a native enum array whose element type no\n * driver's result-type table knows, so the provider answers the array's own\n * text (`{ADMIN,USER}`) — PostgreSQL. Unset means the column is the dialect's\n * JSON list container and the members arrive through the JSON reading like\n * every other list.\n *\n * It is DECLARED and never inferred for the same reason\n * {@link AdapterResultParser.decimalRepresentation} is: the two spellings\n * collide on the empty container — `{}` is an empty PostgreSQL array AND a\n * valid JSON object — so a value cannot be read without knowing which promise\n * produced it, and reading array text on a JSON dialect would accept\n * malformed rows every other list type refuses.\n */\n enumListRepresentation?: \"arrayText\";\n\n /**\n * How this dialect physically spells one identifier DOMAIN on a column that\n * declares the given native type.\n *\n * `\"text\"` is the whole public string; `\"uuid\"` the payload as canonical UUID\n * text, which is what a PostgreSQL `uuid` column returns; `\"bytes\"` the\n * payload's own bytes, in whatever binary shape the driver spells them.\n *\n * A function of the DOMAIN and the field's own native type override, not a\n * constant, because both move the answer: a ULID is `bytea` on PostgreSQL and\n * `BINARY(16)` on MySQL, and a `varchar(26)` override keeps either one text\n * while the domain stays admitted. It is DECLARED and never inferred for the\n * same reason {@link AdapterResultParser.decimalRepresentation} is — sixteen\n * bytes and a 36-character string are the same identifier, and a value cannot\n * be read without knowing which promise produced it.\n *\n * Unset means the dialect stores every domain as text. Every shipped adapter\n * declares it; the option exists so a custom adapter that keeps text columns\n * is a complete adapter.\n */\n idRepresentation?: (\n domain: IdDomain,\n nativeType: NativeTypeDeclaration | undefined\n ) => IdRepresentation;\n\n /**\n * When `true`, {@link AdapterResultParser.parseField} performs NO\n * transformation for any scalar type (it is a pure `next()` passthrough) and\n * the provider returns native JS values (text→string, int→number,\n * bool→boolean, float→number). This lets the result parser take an identity\n * fast path for plain string/int/number/boolean columns, skipping the typed\n * decode switch. The path stays byte-identical: a per-value guard defers any\n * non-native value back to the full parser. Adapters that coerce field values\n * (MySQL/SQLite: 0/1→boolean, JSON-as-text, …) leave this unset.\n */\n nativeScalarPassthrough?: boolean;\n\n /**\n * One OPERATION's raw result, once, before it is decoded.\n *\n * This dialect's chance to reshape what the provider answered for a verb,\n * asked exactly once per operation by `Queries.decodeResult` (Arnaud's D-28)\n * with the operation's own rows — never per statement and never per member.\n * It is a REQUIRED member, and every adapter the estate ships installs the\n * one {@link passThroughParseResult} below for it: a result's MEANING belongs\n * to the engine's decoder, which asks for its own aliases and reads them\n * back, and a VALUE's meaning to {@link AdapterResultParser.parseField} and\n * the scalar codecs one level down. Arnaud's D-40 deleted the two legs that\n * decided otherwise (MySQL's count-column normalisation, PostgreSQL's bigint\n * conversion) after measuring both answering `undefined` on every live\n * operation.\n *\n * @param raw - Raw database result\n * @param operation - Query operation type\n * @param next - Call to continue with default parsing\n * - `next()` uses original raw value\n * - `next(transformed)` uses the transformed value\n *\n * @returns Parsed result or result of `next()`\n *\n * @example\n * // Every shipped adapter: the result is the decoder's.\n * parseResult: passThroughParseResult\n */\n parseResult: (\n raw: unknown,\n operation: import(\"../query-engine/types\").Operation,\n next: (value?: unknown) => unknown\n ) => unknown;\n\n /**\n * Parse relation value (nested JSON from includes)\n *\n * @param value - Raw relation value from database\n * @param next - Call to continue with default parsing\n * - `next()` uses original value\n * - `next(parsed)` uses the parsed value\n *\n * @returns Parsed relation or result of `next()`\n *\n * @example\n * // Parse JSON strings (MySQL/SQLite)\n * parseRelation: (value, next) => {\n * const parsed = tryParseJsonString(value);\n * return parsed !== undefined ? next(parsed) : next();\n * }\n */\n parseRelation: (\n value: unknown,\n next: (value?: unknown) => unknown\n ) => unknown;\n\n /**\n * Parse field value by type\n *\n * @param value - Raw field value from database\n * @param scalarType - Scalar type (boolean, datetime, bigint, etc.)\n * @param next - Pass a value to the query engine's strict scalar parser\n * - `next()` uses original value\n * - `next(converted)` uses the converted value\n *\n * @returns Decoded field value. The query engine strictly parses it once.\n *\n * @example\n * // Convert 0/1 to boolean (SQLite/MySQL)\n * parseField: (value, scalarType, next) => {\n * if (scalarType !== 'boolean') return next();\n * const bool = parseIntegerBoolean(value);\n * return bool === undefined ? next() : next(bool);\n * }\n */\n parseField: (\n value: unknown,\n scalarType: string,\n next: (value?: unknown) => unknown\n ) => unknown;\n}\n\n/**\n * The `parseResult` every adapter this estate ships installs: the contract's\n * shape, deciding nothing.\n *\n * ONE object, referenced by the SQLite, MySQL and PostgreSQL adapters, so the\n * answer \"this dialect decides nothing about a RESULT\" has a single owner\n * rather than three byte-identical members in three files (Arnaud's D-43). It\n * lives beside the member it implements because this is the file where the\n * contract's shape is declared: the required signature and the do-nothing\n * answer to it are then one fact in one place, and the doc above cannot drift\n * from the value below it.\n *\n * It does NOT close the seam. `Queries.decodeResult` still asks the adapter's\n * own `parseResult` once per operation, so an adapter from outside this estate\n * that installs its own — to recover a result whose transport reshaped it —\n * is still asked and still honoured (Arnaud's D-42: the member stays a public\n * extension point). Both facts are pinned together by \"the three shipped\n * adapters share one pass-through, and a custom adapter's own is still asked\"\n * in `tests/contracts/engine/query/parity-decoding.core.test.ts`.\n */\nexport const passThroughParseResult: AdapterResultParser[\"parseResult\"] = (\n _raw,\n _operation,\n next\n) => next();\n","/** The exact normalized provider evidence that identifies one constraint. */\nexport interface NormalizedConstraintDescriptor {\n readonly table?: string;\n readonly constraint?: string;\n readonly columns?: readonly string[];\n}\n\nexport interface ConstraintIdentity {\n readonly name: string;\n readonly normalizedError: NormalizedConstraintDescriptor;\n}\n\n/** Private adapter projection from a schema key to its physical identity. */\nexport interface ConstraintIdentities {\n readonly primaryKey: (\n tableName: string,\n columns: readonly string[]\n ) => ConstraintIdentity;\n readonly unique: (\n tableName: string,\n keyName: string,\n columns: readonly string[]\n ) => ConstraintIdentity;\n}\n\n/** PostgreSQL/MySQL errors identify named constraints and their table. */\nexport function createNamedConstraintIdentities(\n primaryKeyName: (tableName: string) => string\n): ConstraintIdentities {\n const identity = (tableName: string, name: string): ConstraintIdentity => ({\n name,\n normalizedError: { table: tableName, constraint: name },\n });\n return {\n primaryKey: (tableName) => identity(tableName, primaryKeyName(tableName)),\n unique: (tableName, keyName) =>\n identity(tableName, `${tableName}_${keyName}_key`),\n };\n}\n\n/** Driver normalization separates SQLite's physical table and columns. */\nexport const sqliteConstraintIdentities: ConstraintIdentities = {\n primaryKey: (tableName, columns) => ({\n name: `${tableName}_pkey`,\n normalizedError: {\n table: tableName,\n columns: [...columns],\n },\n }),\n unique: (tableName, keyName, columns) => ({\n name: `${tableName}_${keyName}_key`,\n normalizedError: {\n table: tableName,\n columns: [...columns],\n },\n }),\n};\n","import type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport type { Sql } from \"@sql\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport type {\n GeoBounds,\n GeoPoint,\n GeoPolygon,\n} from \"@validation/primitives/geo-values\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport type { DatabaseAdapterCapabilities } from \"./adapter-capabilities\";\nimport type { ArithmeticTarget, CastType } from \"./adapter-core-types\";\nimport type { AdapterResultParser } from \"./adapter-result-parser\";\n\nexport type { DatabaseAdapterCapabilities } from \"./adapter-capabilities\";\nexport type {\n ArithmeticTarget,\n CastType,\n} from \"./adapter-core-types\";\nexport type { AdapterResultParser } from \"./adapter-result-parser\";\n\n/** The one physical SQL vocabulary for a logical EPSG:4326 GeoPoint. */\nexport interface GeoPointSql {\n /** Construct a stored point from already-bound longitude and latitude. */\n readonly value: (longitude: Sql, latitude: Sql) => Sql;\n /** Project the logical longitude from a stored point. */\n readonly longitude: (point: Sql) => Sql;\n /** Project the logical latitude from a stored point. */\n readonly latitude: (point: Sql) => Sql;\n /** Exact canonical coordinate equality. */\n readonly equals: (point: Sql, expected: GeoPoint) => Sql;\n /** Inclusive coordinate bounds, including antimeridian-crossing bounds. */\n readonly withinBounds: (point: Sql, bounds: GeoBounds) => Sql;\n /** Inclusive geographic polygon membership on full-tier providers. */\n readonly withinPolygon?: (point: Sql, polygon: GeoPolygon) => Sql;\n /** Fixed-radius spherical distance in meters on full-tier providers. */\n readonly distance?: (left: Sql, right: Sql) => Sql;\n}\n\n/** Install the adapter's settled GeoPoint protocol as one immutable fact. */\nexport function installGeoPointSql(\n adapter: object,\n geoPoint: GeoPointSql | undefined\n): void {\n let installed: GeoPointSql | undefined;\n if (geoPoint) {\n const withinPolygon = geoPoint.withinPolygon;\n const distance = geoPoint.distance;\n installed = Object.freeze<GeoPointSql>({\n value: geoPoint.value,\n longitude: geoPoint.longitude,\n latitude: geoPoint.latitude,\n equals: geoPoint.equals,\n withinBounds: geoPoint.withinBounds,\n ...(withinPolygon ? { withinPolygon } : {}),\n ...(distance ? { distance } : {}),\n });\n }\n Object.defineProperty(adapter, \"geoPoint\", {\n value: installed,\n writable: false,\n enumerable: true,\n configurable: false,\n });\n}\n\n/**\n * DatabaseAdapter Interface\n *\n * A monadic, composable interface for database-specific SQL generation.\n * Each method is a pure function that transforms Sql fragments or primitives\n * into new Sql fragments, enabling clean composition without side effects.\n *\n * DESIGN PRINCIPLES:\n * - Pure functions: Same inputs always produce same outputs\n * - Composable: Outputs can be inputs to other methods\n * - Database-agnostic inputs: Query engine speaks neutral language\n * - Database-specific outputs: Adapter handles syntax differences\n *\n * USAGE:\n * The query engine calls adapter methods to build SQL fragments,\n * then composes them into complete queries. The adapter never\n * needs to understand query semantics - just SQL syntax.\n */\nexport interface DatabaseAdapter {\n /**\n * NAMESPACE\n * The one normalized SQL qualification value for this adapter's persistent\n * objects — a PostgreSQL schema, a MySQL database, or a requested Vitess\n * keyspace qualifier. `undefined` means deliberately unqualified: unbound\n * MySQL and every SQLite adapter. It is selected once at construction and\n * installed non-writable, and THAT INSTALL is where its immutability lives —\n * not a ban on copies: the two readers that capture it once, the bound\n * migration driver at bind time and the `readDriverIdentity` snapshot a cached\n * read takes, cannot go stale because the property they read can never be\n * reassigned.\n */\n readonly namespace?: string;\n\n /**\n * RAW\n * Escape hatch for raw SQL strings (use sparingly)\n */\n raw: (sqlString: string) => Sql;\n\n /**\n * IDENTIFIERS\n * Database-specific identifier escaping (table names, column names, aliases)\n */\n identifiers: {\n /** Escape a single identifier: \"name\" or `name` */\n escape: (name: string) => Sql;\n /** Create qualified column reference: \"alias\".\"field\" */\n column: (alias: string, field: string) => Sql;\n /**\n * The one renderer for a persistent model or junction table: applies the\n * adapter's namespace and, when an alias is given, the `AS` clause.\n * Statement-local names — CTEs, aliases, columns, constraints — use\n * `escape` instead, and an omitted alias is for a site that splices its own.\n */\n table: (tableName: string, alias?: string) => Sql;\n /** Create aliased expression: expr AS \"alias\" */\n aliased: (expression: Sql, alias: string) => Sql;\n };\n\n /**\n * LITERALS\n * Value wrapping with proper parameterization\n */\n literals: {\n /** Wrap a value as parameterized SQL */\n value: (v: unknown) => Sql;\n /** NULL keyword */\n null: () => Sql;\n /** TRUE literal (database-specific: TRUE vs 1) */\n true: () => Sql;\n /** FALSE literal (database-specific: FALSE vs 0) */\n false: () => Sql;\n /**\n * Returns the dialect's membership operand, valid only as `operators.in` /\n * `notIn` input: a parenthesized list, a PostgreSQL array parameter, or,\n * past 25 members, a SQLite `json_each` subquery.\n */\n list: (values: Sql[]) => Sql;\n /** JSON value (PG: native, MySQL/SQLite: JSON.stringify) */\n json: (v: unknown) => Sql;\n /**\n * Datetime operand from a validated ISO-8601 string, in the PHYSICAL form\n * the destination column holds (PG: as-is, MySQL: naive UTC\n * 'YYYY-MM-DD HH:MM:SS.mmm').\n *\n * `nativeType` is the field's own declaration, threaded because SQLite has\n * no temporal type: a `s.dateTime(SQLITE.DATETIME.INTEGER)` column holds\n * epoch milliseconds and a `REAL` one holds a Julian day, so an ISO string\n * bound into either compares against nothing and stores text the typed read\n * then refuses. The dialects that DO have a temporal type ignore it — their\n * own native types all name a column that accepts this same spelling.\n */\n dateTime: (\n iso: string,\n nativeType?: NativeTypeDeclaration,\n member?: boolean\n ) => Sql;\n /**\n * Decimal operand from a canonical decimal string, in the DOMAIN it is\n * being compared or assigned against.\n *\n * The value binds as text and the DIALECT decides how to read it, because\n * the reading is where precision is won or lost. PostgreSQL and MySQL cast\n * it into their exact decimal type — MySQL in particular compares a\n * `DECIMAL` column against an uncast string operand as a *double*, which\n * would make an exact column compare inexactly with nothing to show for it.\n * SQLite has no exact decimal type and stores the unscaled integer\n * coefficient, so there the operand becomes that same coefficient.\n *\n * The descriptor is the operand's domain, which is USUALLY the field's and\n * deliberately not always: a `having: { _sum: ... }` operand is compared\n * against a sum that may legitimately be wider than any single row's\n * column, so the aggregate's caller widens the precision it passes. The\n * scale is the field's on every path — it is what makes the operand and the\n * column the same physical kind of number.\n */\n decimal: (canonical: string, descriptor: DecimalDescriptor) => Sql;\n /**\n * Identifier operand, in the PHYSICAL representation its column holds.\n *\n * The value arrives already encoded by the codec — canonical public text,\n * canonical UUID text, or the payload's own bytes — so nothing here reads a\n * format, a prefix or an alphabet. What the dialect owns is the BINDING: a\n * PostgreSQL `uuid` column takes text and wants the operand typed as\n * `uuid`, because an untyped text operand against a `uuid` column is\n * `operator does not exist: uuid = text`; a `bytea`, `BINARY(n)` or `BLOB`\n * column takes the bytes as an ordinary binary parameter, which every\n * driver already serializes for blob scalars.\n *\n * Separate from {@link DatabaseAdapter.literals.value} for the reason\n * `decimal` is: the operand and the column have to be ONE physical kind, and\n * a generic parameter leaves that to inference at every site.\n */\n id: (\n physical: string | Uint8Array,\n representation: IdRepresentation\n ) => Sql;\n };\n\n /**\n * OPERATORS\n * Comparison and logical operators (pure Sql -> Sql)\n */\n operators: {\n // Comparison\n eq: (left: Sql, right: Sql) => Sql;\n neq: (left: Sql, right: Sql) => Sql;\n lt: (left: Sql, right: Sql) => Sql;\n lte: (left: Sql, right: Sql) => Sql;\n gt: (left: Sql, right: Sql) => Sql;\n gte: (left: Sql, right: Sql) => Sql;\n\n // Pattern matching\n like: (column: Sql, pattern: Sql) => Sql;\n notLike: (column: Sql, pattern: Sql) => Sql;\n /** Case-insensitive LIKE. */\n ilike: (column: Sql, pattern: Sql) => Sql;\n notIlike: (column: Sql, pattern: Sql) => Sql;\n /** Case-sensitive substring predicates, independent of database collation. */\n containsText: (column: Sql, value: Sql) => Sql;\n startsWithText: (column: Sql, value: Sql) => Sql;\n endsWithText: (column: Sql, value: Sql) => Sql;\n /**\n * `startsWithText` for a plain string operand, spelled so the dialect's\n * planner can turn it into an index range.\n *\n * Same answer as `startsWithText` on every input — it exists only because\n * `startsWithText` wraps the COLUMN in a function (`LEFT`/`substr`), which\n * no planner can range on. This one takes the raw JS string instead of a\n * bound `Sql` so the adapter can escape it into its own pattern language\n * and bind the finished pattern; a pattern assembled in SQL from the\n * operand would be non-constant and lose the range again.\n *\n * Only the where-builder's default-mode, plain-string, `string`-scalar path\n * reaches it. A field-reference operand, a JSON path, an enum column and\n * `mode: \"insensitive\"` all keep `startsWithText`: each of those either has\n * no client-side string to escape, or already wraps the column in a fold\n * that forecloses the range anyway.\n *\n * Each dialect's implementation must hold the case-sensitivity contract\n * `startsWithText` documents. See the per-adapter comments — the three\n * answers are not the same shape, and the measurements that forced that\n * are recorded in `docs/architecture/query-performance-plan.md`, §7.3.\n */\n startsWithPrefix: (\n column: Sql,\n value: string,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n\n /**\n * `column = value` and `column IN (values)` on a TEXT column, under the\n * case-sensitive semantics `caseSensitiveText` spells, written so the\n * dialect's planner can still use an index.\n *\n * `column` arrives unwrapped: each adapter applies its own\n * `caseSensitiveText` where its own semantics need it, and is free to put\n * an index-usable conjunct in front of it. On PostgreSQL and SQLite that\n * is exactly `caseSensitiveText(column) <op> …` and nothing more — their\n * case-sensitive spellings are already index-usable. MySQL's is not: the\n * `BINARY` cast is a function of the column, so the planner drops to a full\n * scan, and MySQL adds a collation-native conjunct in front. See\n * `docs/architecture/query-performance-plan.md`, §10.2 for the plans.\n *\n * The operands are BOUND values, never referenced columns — the caller\n * routes a reference to the plain comparison, which has no index lookup to\n * preserve.\n */\n exactTextEq: (\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n exactTextIn: (\n column: Sql,\n values: Sql,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n\n // Set membership\n in: (column: Sql, values: Sql) => Sql;\n notIn: (column: Sql, values: Sql) => Sql;\n\n // Null checks\n isNull: (expr: Sql) => Sql;\n isNotNull: (expr: Sql) => Sql;\n\n // Range\n between: (column: Sql, min: Sql, max: Sql) => Sql;\n notBetween: (column: Sql, min: Sql, max: Sql) => Sql;\n\n // Logical\n and: (...conditions: Sql[]) => Sql;\n or: (...conditions: Sql[]) => Sql;\n not: (condition: Sql) => Sql;\n\n // Subquery existence\n exists: (subquery: Sql) => Sql;\n notExists: (subquery: Sql) => Sql;\n };\n\n /**\n * EXPRESSIONS\n * Computed values and functions\n */\n expressions: {\n /** Portable searched CASE expression. */\n caseWhen: (\n branches: readonly { readonly when: Sql; readonly then: Sql }[],\n otherwise: Sql\n ) => Sql;\n\n // Arithmetic\n add: (left: Sql, right: Sql) => Sql;\n subtract: (left: Sql, right: Sql) => Sql;\n multiply: (left: Sql, right: Sql) => Sql;\n divide: (left: Sql, right: Sql) => Sql;\n /**\n * The integer quotient of two integer operands, truncated toward zero.\n *\n * The same fact {@link DatabaseAdapter.set.divide}'s `target.integer` flag\n * already carries, as an EXPRESSION rather than an assignment: naming the\n * value an integer column will hold after `{ divide }` needs the dialect's\n * own truncation, and `/` does not agree across dialects. SQLite and\n * PostgreSQL truncate natively once both operands are integers, while MySQL\n * `/` yields a DECIMAL quotient and needs `TRUNCATE(…, 0)`. Casting the\n * quotient afterwards is not a substitute: MySQL and PostgreSQL ROUND on\n * cast, only SQLite truncates.\n */\n integerDivide: (left: Sql, right: Sql) => Sql;\n\n // String operations\n concat: (...parts: Sql[]) => Sql;\n upper: (expr: Sql) => Sql;\n lower: (expr: Sql) => Sql;\n /** Fold ASCII A-Z to a-z without provider-native Unicode case folding. */\n asciiCaseFold: (expr: Sql) => Sql;\n /** Force exact text comparison semantics independent of column/database collation. */\n caseSensitiveText: (\n expr: Sql,\n nativeType?: NativeTypeDeclaration,\n textOperation?: boolean\n ) => Sql;\n\n /** Cast a deferred value into one fixed-decimal field's exact domain. */\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor) => Sql;\n\n /**\n * Bind a DEFERRED identifier back into its column's physical type — the\n * INVERSE of the transport spelling a byte column travels in (lowercase\n * hex, `query-engine/raptor3/shared/identifier.ts`\n * `transportedIdentifier`).\n *\n * NO ENGINE CALLER since the Raptor 3 port: that engine has no deferred\n * identifier — a located key is a raw column sub-select, already physical,\n * and the batch scratch carries integers only. The member stays declared\n * and pinned (`tests/contracts/adapters/identifier-storage.core.test.ts`)\n * until its owner retires or re-adopts it; the provenance below is the\n * retired engine's.\n *\n * The sibling of {@link DatabaseAdapter.expressions.decimalCast}, and\n * needed for the same reason: a relation key whose value does not exist at\n * build time — a `Ref` into a located parent's captured column — cannot go\n * through `literals.id`, and the generic `text` cast names a type the\n * column does not have. `CAST($1 AS TEXT)` against a PostgreSQL `uuid`\n * column is the 42804 this exists to avoid.\n *\n * A deferred value has exactly ONE provenance — a step output, which is a\n * row the driver returned — so it arrives in the spelling that projection\n * published: LOWERCASE HEX for a `bytes` column, canonical text for a\n * `uuid` or text-stored one. A plain cast of that hex into the binary type\n * would bind the hex text's own bytes, so the binary arm decodes it\n * (`decode(…, 'hex')`, `UNHEX`, `unhex`). SQLite's `unhex()` arrived in\n * 3.41, above this adapter's 3.35 floor: a compact identifier on SQLite\n * needs 3.41, and so does a bytes list longer than `literals.list` keeps\n * parenthesized; nothing else here does.\n */\n idCast: (expr: Sql, representation: IdRepresentation) => Sql;\n\n // Utility\n coalesce: (...exprs: Sql[]) => Sql;\n /** Reserved — not called by the query engine yet. */\n greatest: (...exprs: Sql[]) => Sql;\n /** Reserved — not called by the query engine yet. */\n least: (...exprs: Sql[]) => Sql;\n cast: (expr: Sql, type: CastType) => Sql;\n /**\n * Hex-encode a binary column for JSON embedding — JSON can't hold binary\n * (PG: encode(x, 'hex'), MySQL/SQLite: lower(hex(x))).\n * The result parser decodes hex back to Uint8Array.\n */\n blobToHex: (expr: Sql) => Sql;\n };\n\n /**\n * AGGREGATES\n * Aggregate functions\n */\n aggregates: {\n count: (expr?: Sql) => Sql;\n countDistinct: (expr: Sql) => Sql;\n sum: (expr: Sql) => Sql;\n /**\n * A double column's sum as two `SUM`s no row count can overflow: its\n * members of magnitude at least 1e-288 divided by 2^64, and the smaller\n * ones as they are. Dividing such a double by 2^64 is exact, so the first\n * part is the plain sum scaled exactly, and the reader's\n * `high * 2^64 + low` is that sum — `±Infinity` past the double range,\n * where PostgreSQL's own `SUM` raises and MySQL's answers 0 (engine-10).\n *\n * `having` compares `value` and a grouped `orderBy` sorts by `order`, so\n * a group is kept and placed by the sum the projection publishes.\n */\n numberSum: (expr: Sql) => {\n readonly parts: readonly [high: Sql, low: Sql];\n /** The joined sum as one comparable expression. */\n readonly value: Sql;\n /** Sort keys, most significant first, ordering by the joined sum. */\n readonly order: readonly Sql[];\n };\n /**\n * Stated only where an integer `SUM` is int64 and raises past it\n * (SQLite): an int64 column's sum as two `SUM`s no realistic row count\n * can overflow — each member's high 32 bits and the rest — read back\n * exactly as `high * 2^32 + low` (engine-10), compared and sorted as\n * `numberSum` states. PostgreSQL and MySQL already sum integers as exact\n * numerics.\n */\n integerSum?: DatabaseAdapter[\"aggregates\"][\"numberSum\"];\n avg: (expr: Sql) => Sql;\n min: (expr: Sql, boolean?: boolean) => Sql;\n max: (expr: Sql, boolean?: boolean) => Sql;\n /**\n * The average of an EXACT decimal column, in the column's own physical\n * domain and quantized to the field's scale with round-half-to-even.\n *\n * Separate from {@link DatabaseAdapter.aggregates.avg} because `AVG()` is a\n * different function on a decimal: SQLite computes it in a double, and\n * PostgreSQL/MySQL choose the result's scale themselves. This one is\n * derived from the exact `SUM` and `COUNT(column)` — so it is NULL for an\n * empty or all-null group — and rounds by the one shared rule rather than\n * by a provider default.\n */\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor) => Sql;\n\n /**\n * The widened precision needed to cast this exact coefficient as a\n * `having _sum` operand, or `undefined` when the dialect cannot represent\n * that value exactly.\n *\n * `_sum` may exceed one row's precision, but its comparison domain is not\n * unbounded. PostgreSQL and MySQL admit by their exact decimal precision;\n * SQLite admits by signed-int64 VALUE, whose valid range contains some but\n * not all 19-digit coefficients. The adapter owns that provider fact so the\n * query engine never branches on a dialect or silently binds a saturated\n * value.\n */\n decimalSumOperandPrecision: (coefficient: string) => number | undefined;\n };\n\n /**\n * JSON\n * Database-specific JSON building and extraction\n */\n json: {\n /** Structural JSON equality: object key order is insignificant. */\n equals: (left: Sql, right: Sql) => Sql;\n /** Convert a SQL predicate into a JSON boolean value. */\n boolean: (condition: Sql) => Sql;\n /** Preserve a SQL expression as a JSON document when embedding it in JSON. */\n document: (expression: Sql) => Sql;\n /** Carry a finite number through JSON without losing binary precision. */\n number: (expression: Sql) => Sql;\n /** Build JSON object from key-value pairs */\n object: (pairs: [string, Sql][]) => Sql;\n /** Build JSON array from items */\n array: (items: Sql[]) => Sql;\n /** Empty JSON array literal: '[]'::json (PG), JSON_ARRAY() (MySQL), '[]' (SQLite) */\n emptyArray: () => Sql;\n /**\n * Aggregate rows into a JSON array. An empty aggregate is the empty array,\n * never SQL NULL, so no caller wraps it in its own COALESCE.\n */\n agg: (expr: Sql) => Sql;\n /** Build JSON object from explicit column list (works on all databases) */\n objectFromColumns: (columns: [string, Sql][]) => Sql;\n /**\n * Extract the JSON value at a path (empty path = document root) in a\n * form comparable against `json.value` params. Integer segments address\n * array elements. Used by JSON path filters in the where-builder.\n */\n extract: (column: Sql, path: string[]) => Sql;\n /**\n * Extract the value at a path as text (strings unquoted; empty path =\n * document root). Used by JSON string_contains/starts_with/ends_with.\n */\n extractText: (column: Sql, path: string[]) => Sql;\n /**\n * The value at `path` as a double-precision number, or SQL NULL when the\n * path is absent or the JSON value there is NOT a JSON number. Every\n * dialect gates the cast behind its own JSON type test (PG jsonb_typeof,\n * MySQL JSON_TYPE, SQLite json_type) so a non-numeric value yields NULL\n * instead of a cast error. Used by JSON lt/lte/gt/gte with number\n * operands: NULL never satisfies a comparison, so mismatched types and\n * absent paths never match and never error.\n */\n numberAtPath: (column: Sql, path: string[]) => Sql;\n /**\n * The value at `path` as unquoted text under a byte-ordered collation\n * (PG COLLATE \"C\", MySQL VARBINARY, SQLite COLLATE BINARY), or SQL NULL\n * when the path is absent or the JSON value there is NOT a JSON string.\n * The forced collation makes `<`/`>` code-point ordering on every\n * dialect instead of the database's default (locale) collation. Used by\n * JSON lt/lte/gt/gte with string operands.\n */\n stringAtPath: (column: Sql, path: string[]) => Sql;\n /**\n * JSON array containment: target is an array containing every element\n * of the candidate JSON array value (PG @>, MySQL JSON_CONTAINS,\n * SQLite json_each). Used by the array_contains filter.\n */\n contains: (target: Sql, value: Sql) => Sql;\n /**\n * Last element of a JSON array (PG -> -1, MySQL $[last],\n * SQLite $[#-1]). Used by the array_ends_with filter.\n */\n lastElement: (target: Sql) => Sql;\n /**\n * Parameterized JSON value usable in comparisons against a JSON column.\n * PG: plain param (jsonb), MySQL: CAST(? AS JSON) so equality compares\n * JSON documents instead of coercing to a JSON string scalar,\n * SQLite: canonical JSON text param.\n */\n value: (v: unknown) => Sql;\n };\n\n /**\n * ARRAYS\n * Array operations (PG: native arrays, MySQL/SQLite: JSON-based)\n */\n arrays: {\n /**\n * Create array literal. Reserved — not called by the query engine yet.\n */\n literal: (items: Sql[]) => Sql;\n /**\n * Parameterized value for a complete list in the dialect's storage\n * format: native array param (PG), CAST(? AS JSON) (MySQL), canonical\n * JSON text param (SQLite). Used for list writes and equals/not filters.\n */\n value: (values: unknown[], temporal?: \"date\" | \"datetime\") => Sql;\n /**\n * Parameterized value for a complete ENUM list.\n *\n * The one list whose element type no driver can serialize: a PostgreSQL\n * managed enum is created by the estate, so its array OID is in no driver's\n * serializer table and the native array parameter above reaches the server\n * as `ADMIN,USER` (22P02). PostgreSQL binds the array literal as ONE\n * untyped parameter and lets the column or operand it meets resolve the\n * type, so the enum's NAME stays with the migration driver that generated\n * it and never appears in runtime SQL. The JSON-backed dialects answer with\n * the same container every other list uses — there, an enum list has no\n * element type to spell at all.\n */\n enumValue: (values: unknown[]) => Sql;\n /** Check if array contains value */\n has: (column: Sql, value: Sql) => Sql;\n /** Check if array contains all values */\n hasEvery: (column: Sql, values: Sql) => Sql;\n /** Check if array contains any value */\n hasSome: (column: Sql, values: Sql) => Sql;\n /** Check if array is empty */\n isEmpty: (column: Sql) => Sql;\n /**\n * Project a numeric list without a provider/JSON carrier rounding members.\n *\n * Decimal, bigint and floating-point lists share this transport boundary.\n * On a native-array dialect the members are exact text, and\n * the whole-column TEXT cast every other decimal projection uses yields the\n * dialect's own array literal (`{1.20,-0.03}`) rather than an array of\n * members — while embedding the column in a JSON carrier uncast yields JSON\n * NUMBERS, which round past 2^53. Casting ELEMENT-WISE answers both: the\n * flat read gets an array of exact text and the carrier gets a JSON array of\n * strings. On a JSON-backed dialect the container is already an array of\n * coefficient strings and what this owns is that it arrives as TEXT rather\n * than as a driver-parsed document.\n *\n * One name, one meaning, three dialect spellings — the query engine asks for\n * a readable numeric list and never for a dialect cast.\n */\n exactNumericProjection: (column: Sql) => Sql;\n /** Get array length. Reserved — not called by the query engine yet. */\n length: (column: Sql) => Sql;\n /** Get element at index. Reserved — not called by the query engine yet. */\n get: (column: Sql, index: Sql) => Sql;\n /**\n * Append value to array. Reserved — not called by the query engine yet.\n */\n push: (column: Sql, value: Sql) => Sql;\n /** Set value at index. Reserved — not called by the query engine yet. */\n set: (column: Sql, index: Sql, value: Sql) => Sql;\n };\n\n /**\n * ORDER BY\n * Ordering helpers\n */\n orderBy: {\n asc: (column: Sql) => Sql;\n desc: (column: Sql) => Sql;\n /** Directed order placing NULLs first (native on PG, IS NULL sort-key emulation on MySQL/SQLite) */\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\") => Sql;\n /** Directed order placing NULLs last (native on PG, IS NULL sort-key emulation on MySQL/SQLite) */\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\") => Sql;\n };\n\n /**\n * CLAUSES\n * SQL clause keywords\n */\n /**\n * LIMIT value meaning \"no limit\", for dialects that reject OFFSET without\n * LIMIT (MySQL: 18446744073709551615, SQLite: -1).\n * Omit when the dialect supports bare OFFSET (PostgreSQL).\n *\n * It is also the bound an ORDERED derived table states when its caller asked\n * for no window: MySQL merges an unlimited derived table into the query that\n * reads it and the merge takes the ORDER BY with it, so a page whose order a\n * reader consumes (the to-many include's aggregate) spells this value rather\n * than losing it. A dialect that keeps a derived order unbounded declares\n * none and emits nothing.\n */\n noLimitValue?: Sql;\n\n clauses: {\n select: (columns: Sql) => Sql;\n selectDistinct: (columns: Sql) => Sql;\n from: (table: Sql) => Sql;\n where: (condition: Sql) => Sql;\n orderBy: (orders: Sql) => Sql;\n limit: (count: Sql) => Sql;\n offset: (count: Sql) => Sql;\n groupBy: (columns: Sql) => Sql;\n having: (condition: Sql) => Sql;\n };\n\n /**\n * SET\n * UPDATE SET operations\n */\n set: {\n /** Simple assignment: \"col\" = value */\n assign: (column: Sql, value: Sql) => Sql;\n /** Increment: \"col\" = \"col\" + value */\n increment: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /** Decrement: \"col\" = \"col\" - value */\n decrement: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /**\n * Multiply: \"col\" = \"col\" * value.\n * A decimal target rounds the product back to its scale (see\n * {@link ArithmeticTarget}); every other target multiplies natively.\n */\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /**\n * Divide: \"col\" = \"col\" / value.\n * `target.integer` tells the adapter the target column is integer-typed\n * so it can force integer division where the dialect would otherwise do\n * real division. SQLite binds the operand as REAL, while MySQL `/` returns\n * a decimal quotient even for integer columns; both adapters use the flag\n * to preserve truncation toward zero. PostgreSQL integer division already\n * has that behavior and ignores the flag. A decimal target instead rounds\n * the quotient to its scale.\n */\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /**\n * Array push: append the complete provider-encoded `values` container.\n * The query engine selects the scalar's list vocabulary once; the adapter\n * owns only how its dialect concatenates two containers.\n */\n push: (column: Sql, values: Sql) => Sql;\n /** Array unshift: prepend the complete provider-encoded container. */\n unshift: (column: Sql, values: Sql) => Sql;\n };\n\n /**\n * FILTERS\n * Relation filter wrappers for subqueries\n */\n filters: {\n /** EXISTS wrapper for \"some\" relation filter (to-many) */\n some: (subquery: Sql) => Sql;\n /** NOT EXISTS wrapper for \"every\" - negated condition (to-many) */\n every: (subquery: Sql) => Sql;\n /** NOT EXISTS wrapper for \"none\" (to-many) */\n none: (subquery: Sql) => Sql;\n /** EXISTS wrapper for \"is\" relation filter (to-one) */\n is: (subquery: Sql) => Sql;\n /** NOT EXISTS wrapper for \"isNot\" relation filter (to-one) */\n isNot: (subquery: Sql) => Sql;\n };\n\n /**\n * SUBQUERIES\n * Subquery wrappers\n */\n subqueries: {\n /** Scalar subquery: (SELECT ...) */\n scalar: (query: Sql) => Sql;\n /** Correlated subquery with alias */\n correlate: (query: Sql, alias: string) => Sql;\n /** Build EXISTS-style subquery: SELECT 1 FROM table WHERE condition */\n existsCheck: (from: Sql, where: Sql) => Sql;\n };\n\n /**\n * CTE\n * Common Table Expressions\n */\n cte: {\n /** Build WITH clause: WITH name AS (query), ... */\n with: (definitions: { name: string; query: Sql }[]) => Sql;\n /**\n * Build recursive CTE: WITH RECURSIVE name AS (anchor UNION ALL recursive).\n * The query engine calls only the `\"distinct\"` mode (`UNION`); the default\n * `\"all\"` mode is reserved — not called by the query engine yet.\n */\n recursive: (\n name: string,\n anchor: Sql,\n recursive: Sql,\n union?: \"all\" | \"distinct\"\n ) => Sql;\n };\n\n /**\n * MUTATIONS\n * Insert, Update, Delete operations\n */\n mutations: {\n /** How top-level bulk create realizes duplicate-only skipping. */\n skipDuplicatesStrategy: \"sql\" | \"recoverableUniqueError\";\n /** INSERT INTO table (cols) from literal rows or a SELECT source. */\n insert: (\n table: Sql,\n columns: string[],\n source: Sql[][] | { readonly select: Sql },\n prefix?: Sql\n ) => Sql;\n /** Insert one row using only database defaults. */\n insertDefault: (table: Sql) => Sql;\n /** UPDATE table SET ... WHERE ... */\n update: (table: Sql, sets: Sql, where?: Sql) => Sql;\n /** DELETE FROM table WHERE ... */\n delete: (table: Sql, where?: Sql) => Sql;\n /** RETURNING clause (PG/SQLite) or empty (MySQL) */\n returning: (columns: Sql) => Sql;\n /**\n * ON CONFLICT / ON DUPLICATE KEY\n * @param target - Conflict target columns (e.g., \"id\")\n * @param action - Action to take (e.g., UPDATE SET ...)\n * @param targetWhere - Optional WHERE for partial unique index matching\n * PostgreSQL: ON CONFLICT (id) WHERE <targetWhere> DO UPDATE ...\n */\n onConflict: (target: Sql | null, action: Sql, targetWhere?: Sql) => Sql;\n /**\n * Build update action for ON CONFLICT (PG/SQLite: UPDATE SET ..., MySQL: just the SET part)\n * @param sets - SET clause assignments\n * @param setWhere - Optional WHERE for conditional updates\n * PostgreSQL: ... DO UPDATE SET x = y WHERE <setWhere>\n */\n onConflictUpdate: (sets: Sql, setWhere?: Sql) => Sql;\n /**\n * Skip duplicate key errors (for createMany with skipDuplicates: true)\n * PostgreSQL/SQLite: ON CONFLICT DO NOTHING (suffix)\n * MySQL: duplicate-key-only no-op update (suffix)\n *\n * UNTARGETED ON PURPOSE, and that is the whole distinction from\n * {@link DatabaseAdapter.mutations.onConflict}: `createMany({\n * skipDuplicates: true })` promises to skip a row that collides with ANY\n * unique constraint, so naming one would be the wrong answer. A JUNCTION\n * membership insert asks the opposite question — skip only an exact repeat\n * of this complete `(owner, target)` key, and let a target-side UNIQUE\n * (a singular polymorphic member's occupied slot) raise — so it goes\n * through the targeted door instead. See `junctionDuplicateSkip` in\n * `query-engine/builders/many-to-many-utils.ts`; do not route it back here.\n */\n skipDuplicates: (duplicateNoopColumn: string) => {\n prefix: Sql;\n suffix: Sql;\n };\n };\n\n /**\n * ASSERTIONS\n * Dialect-specific statements that abort a batch when a precondition fails.\n */\n assertions: {\n /** Abort unless the provided SELECT returns at least one row. */\n exists: (query: Sql) => Sql;\n /** Abort unless the provided SELECT returns no rows. */\n notExists: (query: Sql) => Sql;\n };\n\n capabilities: DatabaseAdapterCapabilities;\n\n /**\n * LAST INSERT ID\n * Returns SQL for getting the last auto-generated ID.\n * Used only where the provider exposes an exact statement-local identity.\n *\n * PostgreSQL: lastval() exists for legacy/direct SQL uses, but batchRefs does not\n * expose it because another generated column or trigger can change the session value\n * SQLite: last_insert_rowid() - returns last ROWID inserted\n * MySQL: LAST_INSERT_ID() - returns last AUTO_INCREMENT value\n */\n lastInsertId: () => Sql;\n\n /**\n * JOINS\n * Join operations\n */\n joins: {\n inner: (table: Sql, condition: Sql) => Sql;\n left: (table: Sql, condition: Sql) => Sql;\n right: (table: Sql, condition: Sql) => Sql;\n full: (table: Sql, condition: Sql) => Sql;\n cross: (table: Sql) => Sql;\n /**\n * LATERAL subquery join (PostgreSQL 9.3+, MySQL 8.0.14+)\n * Allows referencing columns from preceding tables in the subquery.\n * Used for efficient nested includes.\n *\n * @param subquery - The lateral subquery (must be a complete SELECT)\n * @param alias - Alias for the lateral result\n * @returns JOIN LATERAL (subquery) AS alias ON true\n */\n lateral: (subquery: Sql, alias: string) => Sql;\n /**\n * LEFT JOIN LATERAL - same as lateral but with LEFT JOIN semantics\n * Returns NULL for the joined columns when subquery returns no rows.\n *\n * @param subquery - The lateral subquery (must be a complete SELECT)\n * @param alias - Alias for the lateral result\n * @returns LEFT JOIN LATERAL (subquery) AS alias ON true\n */\n lateralLeft: (subquery: Sql, alias: string) => Sql;\n };\n\n /**\n * SET OPERATIONS\n * UNION, INTERSECT, EXCEPT operations\n */\n setOperations: {\n /** UNION (removes duplicates) */\n union: (...queries: Sql[]) => Sql;\n /**\n * UNION ALL (keeps duplicates). Reserved — not called by the query engine\n * yet.\n */\n unionAll: (...queries: Sql[]) => Sql;\n /** INTERSECT */\n intersect: (...queries: Sql[]) => Sql;\n /** EXCEPT / MINUS */\n except: (left: Sql, right: Sql) => Sql;\n };\n\n /**\n * VECTOR\n * Vector operations for similarity search (pgvector)\n *\n * Matches filter schema: { l2, cosine }\n * Drivers that don't support vector operations can override\n * this property with an object that throws FeatureNotSupportedError.\n *\n * Reserved — the query engine does not call these yet; vector filters are\n * rejected in the where-builder today.\n */\n vector: {\n /** Create a vector literal from number array: '[1,2,3]'::vector */\n literal: (values: number[]) => Sql;\n /** L2 (Euclidean) distance operator for ORDER BY: column <-> vector */\n l2: (column: Sql, vector: Sql) => Sql;\n /** Cosine distance operator for ORDER BY: column <=> vector */\n cosine: (column: Sql, vector: Sql) => Sql;\n };\n\n /**\n * Exact EPSG:4326 point SQL. Absence means this adapter has no physical\n * GeoPoint tier; optional members distinguish the full polygon/distance tier.\n */\n readonly geoPoint?: GeoPointSql;\n\n result: AdapterResultParser;\n}\n","/**\n * The ONE round-half-to-even rule, spelled in each dialect's exact integer\n * vocabulary.\n *\n * Multiply, divide and average are the only operations that can create digits\n * beyond a decimal field's scale, so they are the only ones that round — and\n * they round the same way everywhere, because a rounding mode that came from\n * the provider would make the same query answer differently per database.\n * Nothing here consults a provider default: quotient, remainder and parity are\n * exact integer facts, and the arms are composed from them.\n *\n * WHY A QUOTIENT RULE AND NOT A ROUNDING FUNCTION. `ROUND()` is half-up on\n * MySQL, half-even-ish on PostgreSQL numerics, and absent on SQLite; every one\n * of them would have to be trusted at the exact tie this rule exists to decide.\n * Quotient/remainder/parity are the same three integers on all three.\n *\n * NO PATH CASTS THROUGH REAL. Every operand below is an integer or an exact\n * decimal, and every operator applied to them is exact in its dialect.\n */\n\nimport { type Sql, sql } from \"@sql\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\n\n/**\n * How one dialect spells EXACT truncated division and its remainder.\n *\n * `quotient(n, d)` truncates toward zero and `remainder(n, d)` carries the sign\n * of `n`, which is C semantics and what all three dialects already do — but\n * they spell it three ways, and one of the three (`n / d`) is only integer\n * division when both operands are integers. Each adapter declares its own pair\n * so this file never asks which database it is running against.\n */\nexport interface ExactIntegerArithmetic {\n /** `n / d` truncated toward zero. `d` is never zero unless `n` is NULL. */\n readonly quotient: (n: Sql, d: Sql) => Sql;\n /** `n - quotient(n, d) * d`; sign follows `n`. */\n readonly remainder: (n: Sql, d: Sql) => Sql;\n}\n\n/** `10^scale`, the factor between a logical value and its coefficient. */\nexport const scaleFactorSql = (scale: number): Sql =>\n sql.raw(`1${\"0\".repeat(scale)}`);\n\n/**\n * `10^-scale`: one unit in the last place of the field's domain, as an exact\n * decimal literal. Multiplying a coefficient by it is exact on PostgreSQL and\n * MySQL (scales add); DIVIDING by `10^scale` is not — MySQL computes a quotient\n * to `div_precision_increment` extra digits and rounds there, which would put a\n * provider default back in charge of the last digit.\n */\nexport const scaleUnitSql = (scale: number): Sql =>\n sql.raw(scale === 0 ? \"1\" : `0.${\"0\".repeat(scale - 1)}1`);\n\n/**\n * `n / d` rounded half to even, for `d > 0` and any sign of `n`.\n *\n * The three facts: `q` is the truncated quotient, `r` the remainder, and the\n * decision compares `|r|` against `d - |r|` — below is down, above is away from\n * zero, and EQUAL is the tie, resolved by `q`'s parity so the even neighbour\n * wins.\n *\n * WHY `|r| vs d - |r|` AND NOT `2|r| vs d`. They decide identically (`|r| >\n * d - |r|` is `2|r| > d` rearranged), but the doubled form is the only one that\n * can leave the dialect's exact domain: `|r| < d`, so `d - |r|` is bounded by\n * the divisor while `2|r|` needs one digit MORE than it. That extra digit is\n * the whole domain on the two dialects with a finite one — a 65-digit MySQL\n * divisor doubles to 66, and an int64 count doubles past int64 — so the\n * comparison is written in the form that never widens.\n *\n * The sign of the step reads `r`, not `n`: the step is taken only when `r <> 0`\n * (`|r| > d - |r| >= 0`, or `|r| = d - |r|` which needs `r <> 0` for a non-zero\n * `d`), and a non-zero remainder has exactly the sign of the dividend. Reading\n * `r` keeps one fewer copy of `n` in the emitted statement.\n *\n * `d` MUST be positive. A negative divisor would flip which neighbour is\n * \"away\", so the callers below normalize the sign onto the numerator instead.\n */\nexport const halfEvenQuotient = (\n integers: ExactIntegerArithmetic,\n n: Sql,\n d: Sql\n): Sql => {\n const q = integers.quotient(n, d);\n const r = integers.remainder(n, d);\n const parity = integers.remainder(q, sql.raw`2`);\n return sql`(${q} + (CASE WHEN ABS(${r}) > ${d} - ABS(${r}) OR (ABS(${r}) = ${d} - ABS(${r}) AND ${parity} <> 0) THEN (CASE WHEN ${r} < 0 THEN -1 ELSE 1 END) ELSE 0 END))`;\n};\n\n/**\n * `n` with the divisor's sign folded in, so the half-even rule always sees a\n * positive divisor. `n x sign(d)` and `|d|` name the same quotient as `n / d`.\n */\nexport const signedNumerator = (n: Sql, d: Sql): Sql =>\n sql`(CASE WHEN ${d} < 0 THEN -${n} ELSE ${n} END)`;\n\n/**\n * `column = halfEven(column x by)` where the column holds the LOGICAL decimal\n * in a dialect whose exact decimal domain is UNBOUNDED — PostgreSQL's\n * `NUMERIC`, which computes an expression at whatever width the value needs.\n *\n * The rule is stated on the COEFFICIENT, so the product is scaled up by `10^s`\n * — leaving a value whose integer part is the answer's coefficient and whose\n * fraction is what has to be rounded away — rounded to an integer against a\n * divisor of one, and scaled back by one exact multiplication.\n *\n * The widest intermediate is `column x by x 10^s`, which needs `2p + s` digits.\n * That is why MySQL does NOT use this form: its exact domain stops at 65\n * digits, and past it MySQL rounds an over-scaled product to 30 fractional\n * digits or answers ZERO without a warning. MySQL spells the same rule in its\n * own bounded, coefficient-space form (`mysql-adapter.ts`); this one is\n * PostgreSQL's, where no such ceiling exists.\n */\nexport const logicalDecimalMultiply = (\n integers: ExactIntegerArithmetic,\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const scaled = sql`(${column} * ${by} * ${scaleFactorSql(descriptor.scale)})`;\n const coefficient = halfEvenQuotient(integers, scaled, sql.raw`1`);\n return sql`${column} = ${coefficient} * ${scaleUnitSql(descriptor.scale)}`;\n};\n\n/**\n * `column = halfEven(column / by)` where the column holds the LOGICAL decimal\n * in an unbounded exact domain ({@link logicalDecimalMultiply}'s PostgreSQL).\n *\n * The quotient is never computed by the dialect's `/`: the answer's coefficient\n * is `halfEven((column x 10^s) / by)`, which is a quotient of an exact integer\n * by an exact decimal, so remainder and parity decide the last digit instead of\n * `div_precision_increment` or a numeric division's chosen scale.\n *\n * `by` is non-zero: division by canonical zero is refused before I/O, where the\n * operand's canonical text is still in hand (`set-builder.ts`).\n */\nexport const logicalDecimalDivide = (\n integers: ExactIntegerArithmetic,\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n integers,\n signedNumerator(sql`(${column} * ${scaleFactorSql(descriptor.scale)})`, by),\n sql`ABS(${by})`\n );\n return sql`${column} = ${coefficient} * ${scaleUnitSql(descriptor.scale)}`;\n};\n\n/**\n * The exact decimal average of a LOGICAL decimal column in an unbounded exact\n * domain ({@link logicalDecimalMultiply}'s PostgreSQL): the exact `SUM` over\n * `COUNT(column)`, quantized to the field's scale half to even.\n *\n * `COUNT(column)` counts NON-NULL values, which is what makes the empty and\n * all-null cases answer NULL rather than divide by zero: `SUM` of no non-null\n * rows is NULL, every operator below is null-strict, and the zero divisor is\n * therefore never reached with a non-null numerator.\n *\n * `AVG()` is deliberately unused. It is a double on SQLite, and on the other\n * two its result scale is the provider's choice rather than the field's.\n */\nexport const logicalDecimalAverage = (\n integers: ExactIntegerArithmetic,\n column: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n integers,\n sql`(SUM(${column}) * ${scaleFactorSql(descriptor.scale)})`,\n sql`COUNT(${column})`\n );\n return sql`(${coefficient} * ${scaleUnitSql(descriptor.scale)})`;\n};\n","import type { GeoPointSql } from \"@adapters/database-adapter\";\nimport { type Sql, sql } from \"@sql\";\nimport type {\n GeoBounds,\n GeoPolygon,\n} from \"@validation/primitives/geo-area-codec\";\n\ntype CoordinateOperations = {\n readonly and: (...conditions: Sql[]) => Sql;\n readonly or: (...conditions: Sql[]) => Sql;\n readonly eq: (left: Sql, right: Sql) => Sql;\n readonly gte: (left: Sql, right: Sql) => Sql;\n readonly lte: (left: Sql, right: Sql) => Sql;\n};\n\ntype IndexableBounds = (point: Sql, bounds: GeoBounds) => Sql | undefined;\n\n/**\n * Coordinate equality and inclusive bounds are one logical contract on every\n * provider. Only coordinate extraction differs, so this is their single owner.\n */\nexport function createGeoPointCoordinatePredicates(\n longitude: GeoPointSql[\"longitude\"],\n latitude: GeoPointSql[\"latitude\"],\n operators: CoordinateOperations,\n indexableBounds?: IndexableBounds\n): Pick<GeoPointSql, \"equals\" | \"withinBounds\"> {\n return {\n equals(point, expected) {\n const pointLongitude = longitude(point);\n let longitudeCondition = operators.eq(\n pointLongitude,\n sql`${expected.longitude}`\n );\n // -180 and +180 are one canonical meridian. Storage written outside the\n // ORM may still contain the physical -180 spelling that the value codec\n // presents as +180.\n if (expected.longitude === 180) {\n longitudeCondition = operators.or(\n longitudeCondition,\n operators.eq(pointLongitude, sql`${-180}`)\n );\n }\n return operators.and(\n longitudeCondition,\n operators.eq(latitude(point), sql`${expected.latitude}`)\n );\n },\n withinBounds(point, bounds) {\n const pointLongitude = longitude(point);\n const latitudeCondition = operators.and(\n operators.gte(latitude(point), sql`${bounds.south}`),\n operators.lte(latitude(point), sql`${bounds.north}`)\n );\n\n let exactCondition: Sql;\n if (bounds.west === -180 && bounds.east === 180) {\n exactCondition = latitudeCondition;\n } else {\n const westArm = operators.gte(pointLongitude, sql`${bounds.west}`);\n const eastArm = operators.lte(pointLongitude, sql`${bounds.east}`);\n let longitudeCondition =\n bounds.west > bounds.east\n ? operators.or(westArm, eastArm)\n : operators.and(westArm, eastArm);\n\n // GeoPoint canonicalizes -180 to +180. A normal interval whose western\n // boundary is -180 still contains that one physical meridian.\n if (bounds.west === -180 && bounds.east < 180) {\n longitudeCondition = operators.or(\n longitudeCondition,\n operators.eq(pointLongitude, sql`${180}`)\n );\n }\n // The inverse endpoint is the same canonical meridian: an external\n // writer may have stored -180 while the logical interval ends at +180.\n if (bounds.east === 180 && bounds.west > -180) {\n longitudeCondition = operators.or(\n longitudeCondition,\n operators.eq(pointLongitude, sql`${-180}`)\n );\n }\n exactCondition = operators.and(latitudeCondition, longitudeCondition);\n }\n const indexCondition = indexableBounds?.(point, bounds);\n return indexCondition\n ? operators.and(indexCondition, exactCondition)\n : exactCondition;\n },\n };\n}\n\n/**\n * GeoJSON rectangles safe to use only as conservative spatial-index probes.\n * Empty means the exact coordinate predicate is the only portable shape for\n * this boundary (world, pole, zero-area, or the canonical -180 meridian case).\n */\nexport function geoBoundsIndexPolygons(bounds: GeoBounds): readonly string[] {\n if (\n bounds.south === -90 ||\n bounds.north === 90 ||\n bounds.south === bounds.north ||\n bounds.west === bounds.east ||\n bounds.west > bounds.east ||\n bounds.west === -180 ||\n bounds.east === 180\n ) {\n return [];\n }\n return [\n boundsPolygonJson(bounds.west, bounds.east, bounds.south, bounds.north),\n ];\n}\n\nfunction boundsPolygonJson(\n west: number,\n east: number,\n south: number,\n north: number\n): string {\n // Geography edges are great-circle arcs. Include every axis meridian so\n // their geocentric bounding box encloses the full coordinate rectangle.\n const meridians = [\n west,\n ...[-90, 0, 90].filter((x) => west < x && x < east),\n east,\n ];\n const southEdge = meridians.map((longitude) => [longitude, south]);\n const northEdge = [...meridians]\n .reverse()\n .map((longitude) => [longitude, north]);\n return JSON.stringify({\n type: \"Polygon\",\n coordinates: [[...southEdge, ...northEdge, southEdge[0]]],\n });\n}\n\n/** One bound GeoJSON document; callers never contribute SQL or WKT text. */\nexport function geoPolygonJson(polygon: GeoPolygon): string {\n const rings: number[][][] = [closedRing(polygon.outer)];\n if (polygon.holes) {\n for (const hole of polygon.holes) rings.push(closedRing(hole));\n }\n return JSON.stringify({ type: \"Polygon\", coordinates: rings });\n}\n\nfunction closedRing(ring: GeoPolygon[\"outer\"]): number[][] {\n const result = new Array<number[]>(ring.length + 1);\n for (let index = 0; index < ring.length; index += 1) {\n const point = ring[index]!;\n result[index] = [point.longitude, point.latitude];\n }\n const first = ring[0]!;\n result[ring.length] = [first.longitude, first.latitude];\n return result;\n}\n","import { type Sql, sql } from \"@sql\";\nimport type { QueryParts } from \"../adapter-query-parts\";\n\ninterface SelectAssemblyOptions {\n forUpdate: \"append\" | \"omit\";\n /** LIMIT value meaning \"no limit\", for dialects that reject OFFSET without LIMIT */\n noLimitValue?: Sql;\n}\n\nexport const assembleSelectQuery = (\n selectClause: Sql,\n parts: QueryParts,\n options: SelectAssemblyOptions\n): Sql => {\n const fragments: Sql[] = [selectClause, sql`FROM ${parts.from}`];\n\n appendSelectParts(fragments, parts, options);\n\n if (options.forUpdate === \"append\" && parts.forUpdate) {\n fragments.push(sql.raw`FOR UPDATE`);\n }\n\n return sql.join(fragments, \" \");\n};\n\nconst appendSelectParts = (\n fragments: Sql[],\n parts: QueryParts,\n options: SelectAssemblyOptions\n): void => {\n appendFilterParts(fragments, parts);\n\n if (parts.orderBy) {\n fragments.push(sql`ORDER BY ${parts.orderBy}`);\n }\n\n appendLimitOffset(fragments, parts.limit, parts.offset, options.noLimitValue);\n};\n\n/** Joins, WHERE, GROUP BY and HAVING: shared by the plain and the emulated-DISTINCT select. */\nconst appendFilterParts = (fragments: Sql[], parts: QueryParts): void => {\n if (parts.joins && parts.joins.length > 0) {\n fragments.push(...parts.joins);\n }\n\n if (parts.where) {\n fragments.push(sql`WHERE ${parts.where}`);\n }\n\n if (parts.groupBy) {\n fragments.push(sql`GROUP BY ${parts.groupBy}`);\n }\n\n if (parts.having) {\n fragments.push(sql`HAVING ${parts.having}`);\n }\n};\n\nconst appendLimitOffset = (\n fragments: Sql[],\n limit: Sql | undefined,\n offset: Sql | undefined,\n noLimitValue: Sql | undefined\n): void => {\n if (limit) {\n fragments.push(sql`LIMIT ${limit}`);\n } else if (offset && noLimitValue) {\n // Dialects like MySQL/SQLite have no bare OFFSET; emit their \"no limit\" sentinel\n fragments.push(sql`LIMIT ${noLimitValue}`);\n }\n\n if (offset) {\n fragments.push(sql`OFFSET ${offset}`);\n }\n};\n\n/**\n * Simulate `SELECT DISTINCT ON` using ROW_NUMBER() window functions.\n *\n * Used by MySQL/SQLite (no DISTINCT ON support) and by PostgreSQL when an\n * ORDER BY is present: DISTINCT ON would require the ORDER BY to lead with\n * the distinct columns, which changes result ordering. This emulation keeps\n * Prisma semantics — rows are ordered by the user's ORDER BY, then the first\n * row of each distinct group is kept, preserving that order.\n *\n * Generates:\n * SELECT col1, col2, ... FROM (\n * SELECT columns,\n * ROW_NUMBER() OVER (PARTITION BY distinct_cols ORDER BY order_cols) AS _rn,\n * ROW_NUMBER() OVER (ORDER BY order_cols) AS _ord -- only when ORDER BY present\n * FROM table\n * WHERE ...\n * ) AS _distinct_subquery\n * WHERE _rn = 1\n * ORDER BY _ord\n * LIMIT ... OFFSET ...\n *\n * The outer ORDER BY uses the precomputed _ord rank because the user's\n * ORDER BY references inner table aliases (and relation-order joins) that\n * are out of scope outside the subquery.\n */\nexport const assembleDistinctOnEmulation = (\n parts: QueryParts,\n distinct: Sql,\n escapeIdentifier: (name: string) => Sql,\n noLimitValue?: Sql\n): Sql => {\n // ORDER BY for ROW_NUMBER() - use provided orderBy or default to distinct columns\n const rowNumberOrder = parts.distinctOrderBy ?? parts.orderBy ?? distinct;\n\n const selectColumns: Sql[] = [\n parts.columns,\n sql`ROW_NUMBER() OVER (PARTITION BY ${distinct} ORDER BY ${rowNumberOrder}) AS ${escapeIdentifier(\"_rn\")}`,\n ];\n\n if (parts.orderBy) {\n selectColumns.push(\n sql`ROW_NUMBER() OVER (ORDER BY ${parts.orderBy}) AS ${escapeIdentifier(\"_ord\")}`\n );\n }\n\n // Inner query with ROW_NUMBER()\n const innerFragments: Sql[] = [\n sql`SELECT ${sql.join(selectColumns, \", \")}`,\n sql`FROM ${parts.from}`,\n ];\n\n appendFilterParts(innerFragments, parts);\n\n const innerQuery = sql.join(innerFragments, \" \");\n\n // Outer query that filters for first row of each partition. It names the\n // output columns so _rn/_ord stay inside: every engine DISTINCT carrier\n // states its aliases.\n const aliasColumns = parts.distinctColumnAliases!.map(escapeIdentifier);\n const outerFragments: Sql[] = [\n sql`SELECT ${sql.join(aliasColumns, \", \")} FROM (${innerQuery}) AS ${escapeIdentifier(\"_distinct_subquery\")}`,\n sql`WHERE ${escapeIdentifier(\"_rn\")} = 1`,\n ];\n\n if (parts.orderBy) {\n outerFragments.push(sql`ORDER BY ${escapeIdentifier(\"_ord\")}`);\n }\n\n appendLimitOffset(outerFragments, parts.limit, parts.offset, noLimitValue);\n\n return sql.join(outerFragments, \" \");\n};\n"],"mappings":"gFAgOA,MAAa,wBACX,EACA,EACA,IACG,GAAM,CC1MX,SAAgB,gCACd,EACsB,CACtB,IAAM,UAAY,EAAmB,KAAsC,CACzE,OACA,gBAAiB,CAAE,MAAO,EAAW,WAAY,EAAM,CACxD,EACD,MAAO,CACL,WAAa,GAAc,SAAS,EAAW,EAAe,EAAU,CAAC,CACzE,QAAS,EAAW,IAClB,SAAS,EAAW,GAAG,EAAU,GAAG,EAAQ,MAAM,CACrD,CAIH,MAAa,EAAmD,CAC9D,YAAa,EAAW,KAAa,CACnC,KAAM,GAAG,EAAU,OACnB,gBAAiB,CACf,MAAO,EACP,QAAS,CAAC,GAAG,EAAQ,CACtB,CACF,EACD,QAAS,EAAW,EAAS,KAAa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,mCAAmC,EAAS,YAAY,EAAe,OAAO,EAAiB,MAAM,GACzG,CAEG,EAAM,SACR,EAAc,KACZ,CAAG,+BAA+B,EAAM,QAAQ,OAAO,EAAiB,OAAO,GAChF,CAIH,IAAM,EAAwB,CAC5B,CAAG,UAAUA,EAAI,KAAK,EAAe,KAAK,GAC1C,CAAG,QAAQ,EAAM,OAClB,CAED,kBAAkB,EAAgB,EAAM,CAExC,IAAM,EAAaA,EAAI,KAAK,EAAgB,IAAI,CAK1C,EAAe,EAAM,sBAAuB,IAAI,EAAiB,CACjE,EAAwB,CAC5B,CAAG,UAAUA,EAAI,KAAK,EAAc,KAAK,CAAC,SAAS,EAAW,OAAO,EAAiB,qBAAqB,GAC3G,CAAG,SAAS,EAAiB,MAAM,CAAC,MACrC,CAQD,OANI,EAAM,SACR,EAAe,KAAK,CAAG,YAAY,EAAiB,OAAO,GAAG,CAGhE,kBAAkB,EAAgB,EAAM,MAAO,EAAM,OAAQ,EAAa,CAEnEA,EAAI,KAAK,EAAgB,IAAI"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{t}from"./clock-CK41KO7t.mjs";async function settleWithin(e,n,r,i,a=t){let o,s=!1;e.then(e=>{s&&i?.(e)},()=>void 0);let c=new Promise((e,t)=>{o=a.setTimeout(()=>{s=!0,t(r())},n)});try{return await Promise.race([e,c])}finally{o?.cancel()}}export{settleWithin as t};
|
|
2
|
+
//# sourceMappingURL=settle-B9Vg1FnP.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"settle-B9Vg1FnP.mjs","names":[],"sources":["../src/drivers/shared/settle.ts"],"sourcesContent":["import { type Clock, type ClockTimer, systemClock } from \"../../clock\";\n\n/**\n * `running`, or a rejection built by `expired` once `ms` passed without an\n * answer.\n *\n * The abandoned operation keeps running on the provider. Its rejection is\n * observed here so it never surfaces as unhandled, and a late success is\n * handed to `abandon` — a reservation nobody will use goes back.\n *\n * `clock` is the same internal seam the transaction bounds take.\n */\nexport async function settleWithin<T>(\n running: Promise<T>,\n ms: number,\n expired: () => Error,\n abandon?: (late: T) => void,\n clock: Clock = systemClock\n): Promise<T> {\n let timer: ClockTimer | undefined;\n let late = false;\n running.then(\n (value) => {\n if (late) abandon?.(value);\n },\n () => undefined\n );\n const expiry = new Promise<never>((_resolve, reject) => {\n timer = clock.setTimeout(() => {\n late = true;\n reject(expired());\n }, ms);\n });\n try {\n return await Promise.race([running, expiry]);\n } finally {\n timer?.cancel();\n }\n}\n"],"mappings":"6EAYA,eAAsB,aACpB,EACA,EACA,EACA,EACA,EAAe,EACH,CACZ,IAAI,EACA,EAAO,GACX,EAAQ,KACL,GAAU,CACL,GAAM,IAAU,EAAM,MAEtB,IAAA,GACP,CACD,IAAM,EAAS,IAAI,SAAgB,EAAU,IAAW,CACtD,EAAQ,EAAM,eAAiB,CAC7B,EAAO,GACP,EAAO,GAAS,CAAC,EAChB,EAAG,EACN,CACF,GAAI,CACF,OAAO,MAAM,QAAQ,KAAK,CAAC,EAAS,EAAO,CAAC,QACpC,CACR,GAAO,QAAQ"}
|
package/dist/soft-delete.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Bt as VibORMConfig, E as OperationPayload, Gt as NoControls, It as ExtendedOperationResult, L as ClientSchema, Lt as ExtensionState, Wt as DefinitionControls, Zt as AccumulatedExtensionState, mn as PendingOperation, tn as ExtensionContributionState, zt as VibORMClient } from "./index-C_XLSTy2.mjs";
|
|
2
2
|
import "./client.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/soft-delete/index.d.ts
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{n as e}from"./chunk-BuuaeEvq.mjs";var t=class Sql{rawStrings;rawValues;projection;statements;constructor(e,t){if(e.length-1!==t.length)throw e.length===0?TypeError(`Expected at least 1 string`):TypeError(`Expected ${e.length} strings to have ${e.length-1} values`);this.rawStrings=e,this.rawValues=t}get values(){return this.flatten().values}get strings(){return this.flatten().strings}flatten(){if(this.projection!==void 0)return this.projection;let e=[],t=[],n=``,walk=(r,i)=>{n+=r[0];for(let a=0;a<i.length;a++){let o=i[a];o instanceof Sql?walk(o.rawStrings,o.rawValues):(t.push(o),e.push(n),n=``),n+=r[a+1]}};walk(this.rawStrings,this.rawValues),e.push(n);let r={strings:e,values:t};return this.rawStrings=e,this.rawValues=t,this.projection=r,r}toStatement(e=`?`){let t=this.statements?.[e];if(t!==void 0)return t;let n=this.strings,r=n.length;if(r===1){let e=n[0];return this.statements={$n:e,":n":e,"?":e},e}let i;if(e===`?`)i=n.join(`?`);else{let t=e===`$n`?`$`:`:`,a=Array(r*2-1);a[0]=n[0];for(let e=1;e<r;e++)a[e*2-1]=t+e,a[e*2]=n[e];i=a.join(``)}let a=this.statements??{};return a[e]=i,this.statements=a,i}};function raw(e,...n){if(n.length!==0||typeof e!=`string`&&e.length!==1)throw TypeError(`raw templates cannot interpolate values; use sql for parameters or raw(trustedText) for explicit SQL text.`);return typeof e==`string`?new t([e],[]):new t(e,[])}function join(e,n=`,`,r=``,i=``){let a=e.length;if(a===0)return new t([r+i],[]);let o=Array(a+1);o[0]=r;for(let e=1;e<a;e++)o[e]=n;return o[a]=i,new t(o,e)}const n=raw``;function sql(e,...n){return new t(e,n)}const r=Object.assign(sql,{raw,empty:n,join});function isSql(e){if(e instanceof t)return!0;if(typeof e!=`object`||!e)return!1;let n=Reflect.get(e,`strings`);if(!Array.isArray(n))return!1;let r=Reflect.get(e,`values`);return Array.isArray(r)&&n.length===r.length+1&&n.every(e=>typeof e==`string`)&&typeof Reflect.get(e,`toStatement`)==`function`}export{raw as a,join as i,n,r as o,isSql as r,t};
|
|
2
|
-
//# sourceMappingURL=sql
|
|
2
|
+
//# sourceMappingURL=sql-Bp7jicEX.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sql
|
|
1
|
+
{"version":3,"file":"sql-Bp7jicEX.mjs","names":["result"],"sources":["../src/sql/sql.ts"],"sourcesContent":["/**\n * Values supported by SQL engine.\n */\nexport type Value = unknown;\n\n/**\n * Supported value or SQL instance.\n */\nexport type RawValue = Value | Sql;\n\ntype Placeholder = \"$n\" | \":n\" | \"?\";\n\ninterface SqlProjection {\n strings: string[];\n values: Value[];\n}\n\ntype StatementCache = Partial<Record<Placeholder, string>>;\n\n/**\n * A SQL instance can be nested within each other to build SQL strings.\n *\n * Composition is lazy: constructing a Sql just stores the raw fragments.\n * The nested tree is flattened in a single pass over raw fragments when\n * `strings`/`values` is first read (typically only on the root query), so\n * intermediate fragments never pay flattening or allocation.\n */\nexport class Sql {\n private rawStrings: readonly string[];\n private rawValues: readonly RawValue[];\n\n private projection: SqlProjection | undefined;\n private statements: StatementCache | undefined;\n\n constructor(rawStrings: readonly string[], rawValues: readonly RawValue[]) {\n if (rawStrings.length - 1 !== rawValues.length) {\n if (rawStrings.length === 0) {\n throw new TypeError(\"Expected at least 1 string\");\n }\n throw new TypeError(\n `Expected ${rawStrings.length} strings to have ${\n rawStrings.length - 1\n } values`\n );\n }\n\n this.rawStrings = rawStrings;\n this.rawValues = rawValues;\n }\n\n get values(): Value[] {\n return this.flatten().values;\n }\n\n get strings(): string[] {\n return this.flatten().strings;\n }\n\n /**\n * Flatten the raw fragment tree in one pass, walking children's raw\n * fragments directly so nested Sql instances are never flattened themselves.\n * The flat arrays then replace the raw tree as the canonical representation,\n * releasing child fragments that are not referenced elsewhere.\n */\n private flatten(): SqlProjection {\n if (this.projection !== undefined) {\n return this.projection;\n }\n\n const strings: string[] = [];\n const values: Value[] = [];\n let current = \"\";\n\n const walk = (\n rawStrings: readonly string[],\n rawValues: readonly RawValue[]\n ): void => {\n current += rawStrings[0]!;\n for (let i = 0; i < rawValues.length; i++) {\n const child = rawValues[i]!;\n if (child instanceof Sql) {\n walk(child.rawStrings, child.rawValues);\n } else {\n values.push(child);\n strings.push(current);\n current = \"\";\n }\n current += rawStrings[i + 1]!;\n }\n };\n\n walk(this.rawStrings, this.rawValues);\n strings.push(current);\n\n const projection: SqlProjection = { strings, values };\n\n this.rawStrings = strings;\n this.rawValues = values;\n this.projection = projection;\n\n return projection;\n }\n\n /**\n * Build the final SQL statement string with placeholders.\n * Results are cached per placeholder type for reuse.\n */\n toStatement(placeholder: Placeholder = \"?\"): string {\n const cached = this.statements?.[placeholder];\n if (cached !== undefined) return cached;\n\n const strings = this.strings;\n const len = strings.length;\n\n if (len === 1) {\n const result = strings[0]!;\n this.statements = { $n: result, \":n\": result, \"?\": result };\n return result;\n }\n\n let result: string;\n\n if (placeholder === \"?\") {\n result = strings.join(\"?\");\n } else {\n const prefix = placeholder === \"$n\" ? \"$\" : \":\";\n const parts = new Array<string>(len * 2 - 1);\n parts[0] = strings[0]!;\n for (let i = 1; i < len; i++) {\n parts[i * 2 - 1] = prefix + i;\n parts[i * 2] = strings[i]!;\n }\n result = parts.join(\"\");\n }\n\n const statements = this.statements ?? {};\n statements[placeholder] = result;\n this.statements = statements;\n\n return result;\n }\n}\n\n/**\n * Splice text into a statement verbatim — nothing here is bound as a\n * parameter. Two shapes live under this one name:\n *\n * - `raw(\"ORDER BY name DESC\")` — Prisma's unsafe string splice. The caller\n * owns the escaping; never hand it user input.\n * - ``raw`TRUE` `` — the tagged-template form the adapters use for dialect\n * keywords. Interpolations are refused; use `sql` for bound values.\n */\nfunction raw(value: string | readonly string[]): Sql;\nfunction raw(\n strings: string | readonly string[],\n ...values: readonly RawValue[]\n): Sql {\n if (\n values.length !== 0 ||\n (typeof strings !== \"string\" && strings.length !== 1)\n )\n throw new TypeError(\n \"raw templates cannot interpolate values; use sql for parameters or raw(trustedText) for explicit SQL text.\"\n );\n if (typeof strings === \"string\") {\n return new Sql([strings], []);\n }\n return new Sql(strings, []);\n}\n\n/**\n * Create a SQL query for a list of values.\n *\n * Values are `RawValue`s, matching Prisma: a nested `Sql` is spliced as a\n * fragment, anything else becomes a bound parameter.\n */\nfunction join(\n values: readonly RawValue[],\n separator = \",\",\n prefix = \"\",\n suffix = \"\"\n) {\n const len = values.length;\n if (len === 0) {\n return new Sql([prefix + suffix], []);\n }\n\n // Pre-allocate array with exact size instead of spread + fill\n const strings = new Array<string>(len + 1);\n strings[0] = prefix;\n for (let i = 1; i < len; i++) {\n strings[i] = separator;\n }\n strings[len] = suffix;\n\n return new Sql(strings, values);\n}\n\n/**\n * Placeholder value for \"no text\".\n */\nconst empty = raw``;\n\n/**\n * Create a SQL object from a template string.\n */\nfunction sql(strings: readonly string[], ...values: readonly RawValue[]) {\n return new Sql(strings, values);\n}\n\nconst sqlTag = Object.assign(sql, { raw, empty, join });\n\nexport { empty, join, raw, sqlTag as sql };\n\n/**\n * Type guard for Sql fragments. Structural check rather than instanceof so it\n * also matches fragments from a duplicated module instance. A document with\n * strings/values arrays is data; executable SQL also has the renderer method.\n */\nexport function isSql(value: unknown): value is Sql {\n if (value instanceof Sql) return true;\n if (value === null || typeof value !== \"object\") return false;\n\n const strings = Reflect.get(value, \"strings\");\n if (!Array.isArray(strings)) return false;\n\n const values = Reflect.get(value, \"values\");\n return (\n Array.isArray(values) &&\n strings.length === values.length + 1 &&\n strings.every((part) => typeof part === \"string\") &&\n typeof Reflect.get(value, \"toStatement\") === \"function\"\n );\n}\n"],"mappings":"yCA2BA,IAAa,EAAb,MAAa,GAAI,CACf,WACA,UAEA,WACA,WAEA,YAAY,EAA+B,EAAgC,CACzE,GAAI,EAAW,OAAS,IAAM,EAAU,OAItC,MAHI,EAAW,SAAW,EACd,UAAU,6BAA6B,CAEzC,UACR,YAAY,EAAW,OAAO,mBAC5B,EAAW,OAAS,EACrB,SACF,CAGH,KAAK,WAAa,EAClB,KAAK,UAAY,EAGnB,IAAI,QAAkB,CACpB,OAAO,KAAK,SAAS,CAAC,OAGxB,IAAI,SAAoB,CACtB,OAAO,KAAK,SAAS,CAAC,QASxB,SAAiC,CAC/B,GAAI,KAAK,aAAe,IAAA,GACtB,OAAO,KAAK,WAGd,IAAM,EAAoB,EAAE,C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l===`-`&&u===`-`){s=skipLineComment(e,s+2);continue}if(l===`/`&&u===`*`){let t=e.indexOf(`*/`,s+2);if(t<0)return;s=t+2;continue}if(l===`'`){let t=skipQuoted(e,s,l,i.backslashEscapes===!0);if(t<0||c)return;s=t;continue}if(l===`"`||l==="`"||l===`[`){let t=readQuotedIdentifier(e,s,l===`[`?`]`:l);if(!t||c)return;a.push({depth:o,kind:`identifier`,value:t.value.toUpperCase()}),s=t.end;continue}if(l===`;`&&o===0){c=!0,s+=1;continue}if(c)return;if((l===`:`||l===`@`||l===`$`)&&n.test(u??``)){for(s+=2;s<e.length&&r.test(e[s]??``);)s+=1;continue}if(l===`(`){a.push({depth:o,kind:`symbol`,value:l}),o+=1,s+=1;continue}if(l===`)`){if(--o,o<0)return;a.push({depth:o,kind:`symbol`,value:l}),s+=1;continue}if(l===`=`){a.push({depth:o,kind:`symbol`,value:l}),s+=1;continue}if(n.test(l)){let t=s;for(s+=1;s<e.length&&r.test(e[s]??``);)s+=1;a.push({depth:o,kind:`word`,value:e.slice(t,s).toUpperCase()});continue}s+=1}if(o===0)return a.filter(e=>e.depth===0)}function skipLineComment(e,t){let n=e.indexOf(`
|
|
2
2
|
`,t);return n<0?e.length:n+1}function skipQuoted(e,t,n,r){let i=t+1;for(;i<e.length;){if(r&&e[i]===`\\`){if(i+1>=e.length)return-1;i+=2;continue}if(e[i]!==n){i+=1;continue}if(e[i+1]===n){i+=2;continue}return i+1}return-1}function readQuotedIdentifier(e,t,n){let r=t+1,i=``;for(;r<e.length;){let t=e[r];if(t!==n){i+=t,r+=1;continue}if(e[r+1]===n){i+=n,r+=2;continue}return{end:r+1,value:i}}}export{getTopLevelStatementTokens as t};
|
|
3
|
-
//# sourceMappingURL=sql-statement-tokens-
|
|
3
|
+
//# sourceMappingURL=sql-statement-tokens-BBcoGmJb.mjs.map
|
package/dist/{sql-statement-tokens-CykxFmOJ.mjs.map → sql-statement-tokens-BBcoGmJb.mjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sql-statement-tokens-
|
|
1
|
+
{"version":3,"file":"sql-statement-tokens-BBcoGmJb.mjs","names":[],"sources":["../src/drivers/shared/sql-statement-tokens.ts"],"sourcesContent":["export interface SQLStatementToken {\n depth: number;\n kind: \"identifier\" | \"word\" | \"symbol\";\n value: string;\n}\n\nexport interface SQLStatementTokenOptions {\n /** MySQL string literals may escape the next character with a backslash. */\n backslashEscapes?: boolean;\n}\n\nconst WHITESPACE_REGEX = /\\s/;\nconst WORD_START_REGEX = /[A-Za-z_]/;\nconst WORD_PART_REGEX = /[A-Za-z0-9_$]/;\n\n/** Tokenize one SQL statement while ignoring comments, strings, and parameters. */\nexport function getTopLevelStatementTokens(\n sql: string,\n options: SQLStatementTokenOptions = {}\n): SQLStatementToken[] | undefined {\n const tokens: SQLStatementToken[] = [];\n let depth = 0;\n let index = 0;\n let statementEnded = false;\n\n while (index < sql.length) {\n const char = sql[index];\n const next = sql[index + 1];\n if (!char) break;\n if (WHITESPACE_REGEX.test(char)) {\n index += 1;\n continue;\n }\n if (char === \"-\" && next === \"-\") {\n index = skipLineComment(sql, index + 2);\n continue;\n }\n if (char === \"/\" && next === \"*\") {\n const commentEnd = sql.indexOf(\"*/\", index + 2);\n if (commentEnd < 0) return undefined;\n index = commentEnd + 2;\n continue;\n }\n if (char === \"'\") {\n const quotedEnd = skipQuoted(\n sql,\n index,\n char,\n options.backslashEscapes === true\n );\n if (quotedEnd < 0 || statementEnded) return undefined;\n index = quotedEnd;\n continue;\n }\n if (char === '\"' || char === \"`\" || char === \"[\") {\n const quote = char === \"[\" ? \"]\" : char;\n const identifier = readQuotedIdentifier(sql, index, quote);\n if (!identifier || statementEnded) return undefined;\n tokens.push({\n depth,\n kind: \"identifier\",\n value: identifier.value.toUpperCase(),\n });\n index = identifier.end;\n continue;\n }\n if (char === \";\" && depth === 0) {\n statementEnded = true;\n index += 1;\n continue;\n }\n if (statementEnded) return undefined;\n if (\n (char === \":\" || char === \"@\" || char === \"$\") &&\n WORD_START_REGEX.test(next ?? \"\")\n ) {\n index += 2;\n while (index < sql.length && WORD_PART_REGEX.test(sql[index] ?? \"\")) {\n index += 1;\n }\n continue;\n }\n if (char === \"(\") {\n tokens.push({ depth, kind: \"symbol\", value: char });\n depth += 1;\n index += 1;\n continue;\n }\n if (char === \")\") {\n depth -= 1;\n if (depth < 0) return undefined;\n tokens.push({ depth, kind: \"symbol\", value: char });\n index += 1;\n continue;\n }\n if (char === \"=\") {\n tokens.push({ depth, kind: \"symbol\", value: char });\n index += 1;\n continue;\n }\n if (WORD_START_REGEX.test(char)) {\n const start = index;\n index += 1;\n while (index < sql.length && WORD_PART_REGEX.test(sql[index] ?? \"\")) {\n index += 1;\n }\n tokens.push({\n depth,\n kind: \"word\",\n value: sql.slice(start, index).toUpperCase(),\n });\n continue;\n }\n index += 1;\n }\n\n if (depth !== 0) return undefined;\n return tokens.filter((token) => token.depth === 0);\n}\n\nfunction skipLineComment(sql: string, index: number): number {\n const lineEnd = sql.indexOf(\"\\n\", index);\n return lineEnd < 0 ? sql.length : lineEnd + 1;\n}\n\nfunction skipQuoted(\n sql: string,\n index: number,\n quote: string,\n backslashEscapes: boolean\n): number {\n let cursor = index + 1;\n while (cursor < sql.length) {\n if (backslashEscapes && sql[cursor] === \"\\\\\") {\n if (cursor + 1 >= sql.length) return -1;\n cursor += 2;\n continue;\n }\n if (sql[cursor] !== quote) {\n cursor += 1;\n continue;\n }\n if (sql[cursor + 1] === quote) {\n cursor += 2;\n continue;\n }\n return cursor + 1;\n }\n return -1;\n}\n\nfunction readQuotedIdentifier(\n sql: string,\n index: number,\n quote: string\n): { end: number; value: string } | undefined {\n let cursor = index + 1;\n let value = \"\";\n while (cursor < sql.length) {\n const char = sql[cursor];\n if (char !== quote) {\n value += char;\n cursor += 1;\n continue;\n }\n if (sql[cursor + 1] === quote) {\n value += quote;\n cursor += 2;\n continue;\n }\n return { end: cursor + 1, value };\n }\n return undefined;\n}\n"],"mappings":"yCAW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I,EAAS,KAAO,EAAO,CAC7B,GAAS,EACT,GAAU,EACV,SAEF,MAAO,CAAE,IAAK,EAAS,EAAG,QAAO"}
|
package/dist/sql.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as isSql, c as sqlTag, i as empty, n as Sql, o as join, r as Value, s as raw, t as RawValue } from "./sql
|
|
1
|
+
import { a as isSql, c as sqlTag, i as empty, n as Sql, o as join, r as Value, s as raw, t as RawValue } from "./sql-BvfwUKIh.mjs";
|
|
2
2
|
export { RawValue, Sql, Value, empty, isSql, join, raw, sqlTag as sql };
|
package/dist/sql.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,i as t,n,o as r,r as i,t as a}from"./sql
|
|
1
|
+
import{a as e,i as t,n,o as r,r as i,t as a}from"./sql-Bp7jicEX.mjs";export{a as Sql,n as empty,i as isSql,t as join,e as raw,r as sql};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{p as t,y as n}from"./validation-Dk9Q_-C7.mjs";import{o as r,t as i}from"./sql-Bp7jicEX.mjs";import{r as a}from"./adapter-internals-n3Mf3css.mjs";import{O as o}from"./geo-point-codec-lhxH42SK.mjs";import{i as s}from"./datetime-physical-codec-oIhiYZEP.mjs";import{a as c,t as l}from"./physical-6V_LNU3L.mjs";import{t as u}from"./json-number-CGXpPu4D.mjs";import{C as d,D as f,E as p,M as ee,O as m,S as h,T as te,_ as ne,a as re,b as ie,d as g,f as _,g as v,h as y,i as b,j as x,k as S,l as C,n as w,o as T,p as E,r as D,s as O,v as k,w as A,x as j,y as M}from"./standard-sql-Bk4RZPqJ.mjs";import{r as N,t as P}from"./batch-refs-4L8ECdPU.mjs";import{f as F,g as I,h as L,n as R,o as z,p as B,r as V,t as H,u as U}from"./select-assembly-f1UGoblh.mjs";const W=ee(`"`),G={quotient:(e,t)=>r`(${e} / ${t})`,remainder:(e,t)=>r`(${e} % ${t})`};function sqliteIntegerPrecision(e){let t=m(e);if(t<19)return t;if(!(t>19))return(e.startsWith(`-`)?e.slice(1)<=`9223372036854775808`:e<=`9223372036854775807`)?t:void 0}const K=r.raw(`1000000000000000000`),overflowCoefficient=e=>r.raw(`1${`0`.repeat(Math.min(e.precision,18))}`),guardedCoefficientAssignment=(e,t,n,i)=>r`${e} = CASE WHEN ${e} IS NULL OR ${t} THEN ${n} ELSE ${overflowCoefficient(i)} END`,q=/^\d+$/,J=/["\\]/,jsonPathLeg=e=>{if(q.test(e))return`$[${e}]`;if(J.test(e))throw Error(`SQLite JSON path segments containing " or \\ must be rejected by the portable query contract.`);return`$."${e}"`},jsonExtract=(e,t)=>{let n=r`${e} -> '$'`;for(let e of t)n=r`${n} -> ${jsonPathLeg(e)}`;return n},jsonExtractText=(e,t)=>{if(t.length===0)return r`${e} ->> '$'`;let n=t.map(jsonPathLeg),i=n.pop(),a=e;for(let e of n)a=r`${a} -> ${e}`;return r`${a} ->> ${i}`},jsonArrayConcat=(e,t)=>r`(CASE WHEN ${e} = '[]' THEN ${t} WHEN ${t} = '[]' THEN ${e} ELSE substr(${e}, 1, length(${e}) - 1) || ',' || substr(${t}, 2) END)`,sqliteJsonListValue=e=>r`${x(e)}`,Y=[``,``],X=[`CAST(`,` AS INTEGER)`],ae=/\p{Cs}/u,Z=p().list;function jsonMember(e){return typeof e==`string`?ae.test(e)?void 0:JSON.stringify(e):e instanceof Uint8Array?`"${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}"`:typeof e==`bigint`||typeof e==`boolean`||Number.isSafeInteger(e)?String(e):void 0}function sqliteList(e){if(e.length<=25)return Z(e);let[t]=e,n=t?.strings[0]===X[0]?X:Y,a=[],o=0;for(let t of e){let[r,i,s]=t.strings,c=t.values[0],l=jsonMember(c);if(l===void 0||r!==n[0]||i!==n[1]||s!==void 0)return Z(e);c instanceof Uint8Array&&o++,a.push(l)}return o!==0&&o!==e.length?Z(e):r`(SELECT ${new i(n,[r.raw(o===0?`value`:`unhex(value)`)])} FROM json_each(${`[${a.join(`,`)}]`}))`}const Q={...p(),value:e=>{if(typeof e==`bigint`&&sqliteIntegerPrecision(String(e))===void 0)throw new t(`SQLite bigint values must fit signed 64-bit integers.`);return r`${e}`},true:()=>r.raw(`1`),false:()=>r.raw(`0`),json:e=>r`${JSON.stringify(e)}`,dateTime:(e,t)=>r`${s(e,l(t))}`,decimal:(e,t)=>new i(X,[o(e,t,`coefficient`)]),id:(e,t)=>r`${e}`,list:sqliteList},oe={...re(),like:(e,t)=>r`${e} LIKE ${t} ESCAPE '\\'`,notLike:(e,t)=>r`${e} NOT LIKE ${t} ESCAPE '\\'`,ilike:(e,t)=>r`lower(${e}) LIKE lower(${t}) ESCAPE '\\'`,notIlike:(e,t)=>r`lower(${e}) NOT LIKE lower(${t}) ESCAPE '\\'`,containsText:(e,t)=>r`instr(${e}, ${t}) > 0`,startsWithText:(e,t)=>r`substr(${e}, 1, length(${t})) COLLATE BINARY = ${t}`,endsWithText:(e,t)=>r`substr(${e}, length(${e}) - length(${t}) + 1) COLLATE BINARY = ${t}`,startsWithPrefix:(e,t)=>r`${e} GLOB ${`${S(t)}*`}`,exactTextEq:(e,t)=>r`${e} COLLATE BINARY = ${t}`,exactTextIn:(e,t)=>r`${e} COLLATE BINARY IN ${t}`,...v(),...k(),...j(),...y(Q.true,Q.false),...g()},se={...b(),asciiCaseFold:e=>r`lower(${e})`,caseSensitiveText:e=>r`${e} COLLATE BINARY`,concat:(...e)=>e.length===0?r.raw(`''`):e.length===1?e[0]:r`(${r.join(e,` || `)})`,greatest:(...e)=>r`MAX(${r.join(e,`, `)})`,least:(...e)=>r`MIN(${r.join(e,`, `)})`,integerDivide:(e,t)=>r`(${e} / CAST(${t} AS INTEGER))`,decimalCast:(e,t)=>r`CAST(${e} AS INTEGER)`,idCast:(e,t)=>t===`bytes`?r`unhex(${e})`:r`CAST(${e} AS TEXT)`,cast:D({text:`TEXT`,integer:`INTEGER`,bigint:`INTEGER`,boolean:`INTEGER`,numeric:`NUMERIC`}),blobToHex:e=>r`lower(hex(${e}))`},ce={...w(`9e999`),decimalAvg:(e,t)=>z(G,r`SUM(${e})`,r`COUNT(${e})`),decimalSumOperandPrecision:sqliteIntegerPrecision,integerSum:e=>{let t=r`SUM(${e} >> 32)`,n=r`SUM(${e} - ((${e} >> 32) << 32))`,i=r`(${t} + (${n} >> 32))`,a=r`(${n} & 4294967295)`,o=r`${i} * 4294967296.0 + ${a}`;return{parts:[t,n],value:r`CASE WHEN ${i} > 2147483647 THEN ${o} WHEN ${i} >= -2147483648 THEN ${i} * 4294967296 + ${a} ELSE MIN(${o}, -9223372036854777856.0) END`,order:[i,a]}}};function sqliteJsonEquals(e,t){let nodes=e=>r`SELECT fullkey, CASE WHEN type IN ('integer', 'real') THEN 'number' ELSE type END, atom FROM json_tree(${e})`;return r`(CASE WHEN ${e} IS NULL OR ${t} IS NULL THEN NULL ELSE NOT EXISTS (${nodes(e)} EXCEPT ${nodes(t)}) AND NOT EXISTS (${nodes(t)} EXCEPT ${nodes(e)}) END)`}const sqliteJsonObject=e=>{if(e.length===0)return r.raw(`json_object()`);let t=e.flatMap(([e,t])=>[r`${e}`,t]);return r`json_object(${r.join(t,`, `)})`},le={equals:sqliteJsonEquals,number:e=>r`CASE WHEN ${e} IS NULL THEN NULL ELSE printf(${r.raw(`'${u}'`)}, ${e}) END`,boolean:e=>r`json(CASE WHEN ${e} THEN 'true' ELSE 'false' END)`,document:e=>r`json(${e})`,object:sqliteJsonObject,array:e=>e.length===0?r.raw(`json_array()`):r`json_array(${r.join(e,`, `)})`,emptyArray:()=>r.raw(`json_array()`),agg:e=>r`COALESCE(json_group_array(json(${e})), json_array())`,objectFromColumns:sqliteJsonObject,extract:jsonExtract,extractText:jsonExtractText,numberAtPath:(e,t)=>r`(CASE WHEN json_type(${jsonExtract(e,t)}) IN ('integer', 'real') THEN CAST(${jsonExtractText(e,t)} AS REAL) END)`,stringAtPath:(e,t)=>r`((CASE WHEN json_type(${jsonExtract(e,t)}) = 'text' THEN ${jsonExtractText(e,t)} END) COLLATE BINARY)`,contains:(e,t)=>r`(json_type(${e}) = 'array' AND NOT EXISTS (SELECT 1 FROM json_each(${t}) AS required WHERE NOT EXISTS (SELECT 1 FROM json_each(${e}) AS candidate WHERE ${sqliteJsonEquals(r`${e} -> candidate.fullkey`,r`${t} -> required.fullkey`)})))`,lastElement:e=>r`${e} -> '$[#-1]'`,value:e=>r`${x(e)}`},ue={literal:e=>e.length===0?r.raw(`json_array()`):r`json_array(${r.join(e,`, `)})`,value:sqliteJsonListValue,enumValue:sqliteJsonListValue,has:(e,t)=>r`EXISTS (SELECT 1 FROM json_each(${e}) WHERE value = ${t})`,hasEvery:(e,t)=>r`(SELECT COUNT(*) FROM json_each(${t}) WHERE value IN (SELECT value FROM json_each(${e}))) = json_array_length(${t})`,hasSome:(e,t)=>r`EXISTS (SELECT 1 FROM json_each(${e}) AS a, json_each(${t}) AS b WHERE a.value = b.value)`,isEmpty:e=>r`(json_array_length(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>r`CAST(${e} AS TEXT)`,length:e=>r`json_array_length(${e})`,get:(e,t)=>r`json_extract(${e}, '$[' || ${t} || ']')`,push:(e,t)=>r`json_insert(${e}, '$[#]', ${t})`,set:(e,t,n)=>r`json_set(${e}, '$[' || ${t} || ']', ${n})`},de={...C(),nullsFirst:(e,t)=>t===`desc`?r`${e} DESC NULLS FIRST`:r`${e} ASC NULLS FIRST`,nullsLast:(e,t)=>t===`desc`?r`${e} DESC NULLS LAST`:r`${e} ASC NULLS LAST`},fe={...M(),multiply:(e,t,n)=>{let i=n?.decimal;return i?guardedCoefficientAssignment(e,r`${t} = 0 OR ABS(${e}) <= ${K} / ABS(${t})`,z(G,r`(${e} * ${t})`,U(i.scale)),i):r`${e} = ${e} * ${t}`},divide:(e,t,n)=>{let i=n?.decimal;if(i){let n=U(i.scale);return guardedCoefficientAssignment(e,r`ABS(${e}) <= ${K} / ${n}`,z(G,F(r`(${e} * ${n})`,t),r`ABS(${t})`),i)}return n?.integer?r`${e} = ${e} / CAST(${t} AS INTEGER)`:r`${e} = ${e} / ${t}`},push:(e,t)=>r`${e} = ${jsonArrayConcat(r`json(COALESCE(${e}, '[]'))`,t)}`,unshift:(e,t)=>r`${e} = ${jsonArrayConcat(t,r`json(COALESCE(${e}, '[]'))`)}`},pe={skipDuplicatesStrategy:`sql`,insert:E(W),insertDefault:e=>r`INSERT INTO ${e} DEFAULT VALUES`,...ne(),returning:e=>r`RETURNING ${e}`,...ie()},$={exists:e=>r`SELECT CASE WHEN EXISTS (${e}) THEN 1 ELSE json_extract('x', '$') END AS "__viborm_assert__"`,notExists:e=>r`SELECT CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE json_extract('x', '$') END AS "__viborm_assert__"`},me={...T(),right:(e,t)=>{throw Error(`SQLite does not support RIGHT JOIN. Restructure the query with joins.left and swapped operands.`)},full:(e,t)=>{throw Error(`SQLite does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.`)},lateral:(e,t)=>{throw Error(`SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.`)},lateralLeft:(e,t)=>{throw Error(`SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.`)}},he={supportsReturning:!0,supportsCteWithMutations:!1,supportsFullOuterJoin:!1,supportsLateralJoins:!1,supportsVector:!1,supportsUpsertWhere:!0,supportsTargetedUpsert:!0,supportsMutationTargetInSubquery:!0,supportsMutationRowLimit:!1,supportsRowLocks:!1},ge={decimalRepresentation:`coefficient`,decimalListRepresentation:`coefficient`,dateTimeRepresentation:l,idRepresentation:(e,t)=>c(e,t,`sqlite`)?.representation??`text`,parseResult:I,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>n()},_e=_(W),ve=te(),ye=d(),be=f(W),xe=O(W),Se=A(),Ce=h();var SQLiteAdapter=class{constructor({temporaryObjects:e=!0}={}){B(this,this.geoPoint);let t,createBatchRefs=()=>this.#t(e);a(this,{get batchRefs(){return t??=createBatchRefs(),t},constraints:L,select:this.#e.select})}raw=Ce;identifiers={..._e};literals={...Q};operators={...oe};expressions={...se};aggregates={...ce};json={...le};arrays={...ue};orderBy={...de};clauses={...ve};set={...fe};filters={...ye};subqueries={...be};noLimitValue=r.raw(`-1`);#e={select:e=>e.distinct?H(e,e.distinct,this.identifiers.escape,this.noLimitValue):R(r`SELECT ${e.columns}`,e,{forUpdate:`omit`,noLimitValue:this.noLimitValue})};cte={...xe};mutations={...pe};assertions={...$};joins={...me};setOperations={...Se};capabilities={...he};lastInsertId=()=>r.raw(`last_insert_rowid()`);#t(e){let t=r.raw(W(P)),n=r.raw(e?`CREATE TEMP TABLE IF NOT EXISTS`:`CREATE TABLE IF NOT EXISTS`);return N({table:t,batchIdColumn:r.raw(`"batch_id"`),keyColumn:r.raw(`"ref_key"`),valueColumn:r.raw(`"ref_value"`),createTable:r`${n} ${t} ("batch_id" TEXT NOT NULL, "ref_key" TEXT NOT NULL, "ref_value" TEXT, PRIMARY KEY ("batch_id", "ref_key"))`,castValue:e=>r`CAST((${e}) AS TEXT)`,lastInsertId:()=>this.lastInsertId()})}vector=n;geoPoint=(()=>{let longitude=e=>this.json.numberAtPath(e,[`longitude`]),latitude=e=>this.json.numberAtPath(e,[`latitude`]);return{value:(e,t)=>r`json_object('longitude', ${this.json.document(this.json.number(e))}, 'latitude', ${this.json.document(this.json.number(t))})`,longitude,latitude,...V(longitude,latitude,this.operators)}})();result={...ge}};export{SQLiteAdapter as t};
|
|
2
|
+
//# sourceMappingURL=sqlite-adapter-CW_3l6ea.mjs.map
|