viborm 1.2.4 → 1.3.1
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 +6 -1
- package/dist/{adapter-internals-n3Mf3css.mjs → adapter-internals-AGgQRu5t.mjs} +1 -1
- package/dist/{adapter-internals-n3Mf3css.mjs.map → adapter-internals-AGgQRu5t.mjs.map} +1 -1
- package/dist/adapter-namespace-BpMbLKpL.mjs +2 -0
- package/dist/{adapter-namespace-DqkJQdrD.mjs.map → adapter-namespace-BpMbLKpL.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-BsbbSLw3.mjs → array-literal-BKdLfNzM.mjs} +1 -1
- package/dist/{array-literal-BsbbSLw3.mjs.map → array-literal-BKdLfNzM.mjs.map} +1 -1
- package/dist/{base-AdXAoy6l.mjs → base-D3m1S7Uc.mjs} +2 -2
- package/dist/{base-AdXAoy6l.mjs.map → base-D3m1S7Uc.mjs.map} +1 -1
- package/dist/{batch-refs-4L8ECdPU.mjs → batch-refs-B4zn-FAu.mjs} +2 -2
- package/dist/{batch-refs-4L8ECdPU.mjs.map → batch-refs-B4zn-FAu.mjs.map} +1 -1
- package/dist/{bind-parameter-capacity-CjPgqnmx.mjs → bind-parameter-capacity-qfEejeOX.mjs} +2 -2
- package/dist/{bind-parameter-capacity-CjPgqnmx.mjs.map → bind-parameter-capacity-qfEejeOX.mjs.map} +1 -1
- package/dist/builder-s1ySUuMb.mjs +2 -0
- package/dist/builder-s1ySUuMb.mjs.map +1 -0
- package/dist/bun-sql.d.mts +3 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/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-BO57X0TT.mjs → cache-CIPRF-pz.mjs} +2 -2
- package/dist/{cache-BO57X0TT.mjs.map → cache-CIPRF-pz.mjs.map} +1 -1
- 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 → canonical-json-BReb5nFO.mjs} +2 -2
- package/dist/{canonical-json-rfC2Dg0X.mjs.map → canonical-json-BReb5nFO.mjs.map} +1 -1
- package/dist/chain-7qiFSE8J.mjs +2 -0
- package/dist/chain-7qiFSE8J.mjs.map +1 -0
- package/dist/cli.mjs +2 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/client-6YgGlXzN.mjs +2 -0
- package/dist/client-6YgGlXzN.mjs.map +1 -0
- package/dist/{client-CUnPXifK.d.mts → client-70MrTq1E.d.mts} +3 -3
- package/dist/client-BgJ7Faln.mjs +49 -0
- package/dist/{client-B3VWFhv_.mjs.map → client-BgJ7Faln.mjs.map} +1 -1
- package/dist/client.d.mts +2 -2
- package/dist/client.mjs +1 -1
- package/dist/{clock-CK41KO7t.mjs → clock-C24RcpwO.mjs} +1 -1
- package/dist/{clock-CK41KO7t.mjs.map → clock-C24RcpwO.mjs.map} +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/controls-KQ85SWfT.mjs +2 -0
- package/dist/controls-KQ85SWfT.mjs.map +1 -0
- package/dist/{current-DyzK6OCh.mjs → current-oXcxSCBQ.mjs} +1 -1
- package/dist/{current-DyzK6OCh.mjs.map → current-oXcxSCBQ.mjs.map} +1 -1
- 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 → datetime-physical-codec-BEqQbIP_.mjs} +2 -2
- package/dist/{datetime-physical-codec-oIhiYZEP.mjs.map → datetime-physical-codec-BEqQbIP_.mjs.map} +1 -1
- package/dist/driver-B9fIori_.mjs +2 -0
- package/dist/driver-B9fIori_.mjs.map +1 -0
- package/dist/{driver-B19QlFqn.mjs → driver-vn-9CN0y.mjs} +2 -2
- package/dist/{driver-B19QlFqn.mjs.map → driver-vn-9CN0y.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-C9WgitPi.mjs +2 -0
- package/dist/error-mapping-C9WgitPi.mjs.map +1 -0
- package/dist/every-CcpKWCVo.mjs +2 -0
- package/dist/{every-o-Nu9Em8.mjs.map → every-CcpKWCVo.mjs.map} +1 -1
- package/dist/{execution-context-BKR3bgES.mjs → execution-context-rJXTRVrJ.mjs} +1 -1
- package/dist/{execution-context-BKR3bgES.mjs.map → execution-context-rJXTRVrJ.mjs.map} +1 -1
- package/dist/{fs-estate-CAhDg7nY.mjs → fs-estate-i8Zlr1OQ.mjs} +2 -2
- package/dist/{fs-estate-CAhDg7nY.mjs.map → fs-estate-i8Zlr1OQ.mjs.map} +1 -1
- package/dist/{geo-area-codec-1SY9im7O.mjs → geo-area-codec-CbkmFArQ.mjs} +2 -2
- package/dist/{geo-area-codec-1SY9im7O.mjs.map → geo-area-codec-CbkmFArQ.mjs.map} +1 -1
- package/dist/geo-point-codec-DyEHMdJg.mjs +2 -0
- package/dist/geo-point-codec-DyEHMdJg.mjs.map +1 -0
- package/dist/hydration-BsPZI4jE.mjs +2 -0
- package/dist/{hydration-CAxOL4aI.mjs.map → hydration-BsPZI4jE.mjs.map} +1 -1
- package/dist/identifier-conversion-BneQiLxQ.mjs +2 -0
- package/dist/{identifier-conversion-GgbwHc2G.mjs.map → identifier-conversion-BneQiLxQ.mjs.map} +1 -1
- package/dist/{identity-CLFhCTZx.mjs → identity-oQvIe7u8.mjs} +2 -2
- package/dist/{identity-CLFhCTZx.mjs.map → identity-oQvIe7u8.mjs.map} +1 -1
- package/dist/{index-B0b7asA4.d.mts → index-VsM29vYN.d.mts} +5257 -4915
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{invariant-BnLYqsHO.mjs → invariant-D57gi_yW.mjs} +1 -1
- package/dist/{invariant-BnLYqsHO.mjs.map → invariant-D57gi_yW.mjs.map} +1 -1
- package/dist/{json-number-CGXpPu4D.mjs → json-number-DvmiNx0n.mjs} +1 -1
- package/dist/{json-number-CGXpPu4D.mjs.map → json-number-DvmiNx0n.mjs.map} +1 -1
- package/dist/key-D9LtHxVK.mjs +2 -0
- package/dist/{key-BeoOwGr3.mjs.map → key-D9LtHxVK.mjs.map} +1 -1
- package/dist/{libsql-Drp-zaxq.mjs → libsql-BlSBYwd_.mjs} +3 -3
- package/dist/{libsql-Drp-zaxq.mjs.map → libsql-BlSBYwd_.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-CDTUZQWL.mjs → memory-C0k-_S_n.mjs} +2 -2
- package/dist/{memory-CDTUZQWL.mjs.map → memory-C0k-_S_n.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +5 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +5 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +5 -5
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.d.mts +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.d.mts +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/tenant.d.mts +3 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/{migrations-DTObIjAm.mjs → migrations-Bn1SatyB.mjs} +2 -2
- package/dist/{migrations-DTObIjAm.mjs.map → migrations-Bn1SatyB.mjs.map} +1 -1
- package/dist/migrations.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/{mysql-D7zC03yD.mjs → mysql-DOLHwIM_.mjs} +6 -6
- package/dist/{mysql-D7zC03yD.mjs.map → mysql-DOLHwIM_.mjs.map} +1 -1
- package/dist/mysql-adapter-C6c5govr.mjs +2 -0
- package/dist/{mysql-adapter-DkJPfoGf.mjs.map → mysql-adapter-C6c5govr.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/{native-types-veeTk36s.mjs → native-types-asNCr26n.mjs} +1 -1
- package/dist/{native-types-veeTk36s.mjs.map → native-types-asNCr26n.mjs.map} +1 -1
- package/dist/neon-http.d.mts +3 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/{object-store-DQR6bTBY.mjs → object-store-ChYHlOMD.mjs} +2 -2
- package/dist/{object-store-DQR6bTBY.mjs.map → object-store-ChYHlOMD.mjs.map} +1 -1
- package/dist/{object-store-DMFXXQEC.d.mts → object-store-D9mvOHP4.d.mts} +4 -4
- package/dist/{observation-DUSm7oXK.mjs → observation-Co72iCd1.mjs} +2 -2
- package/dist/{observation-DUSm7oXK.mjs.map → observation-Co72iCd1.mjs.map} +1 -1
- package/dist/permissions.d.mts +424 -0
- package/dist/permissions.mjs +2 -0
- package/dist/permissions.mjs.map +1 -0
- package/dist/pg.d.mts +9 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +3 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/{physical-6V_LNU3L.mjs → physical-CAOaNM4R.mjs} +2 -2
- package/dist/{physical-6V_LNU3L.mjs.map → physical-CAOaNM4R.mjs.map} +1 -1
- package/dist/{pinned-session-CLxj5M5e.mjs → pinned-session-BTplL3iZ.mjs} +2 -2
- package/dist/{pinned-session-CLxj5M5e.mjs.map → pinned-session-BTplL3iZ.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-C0Q7ks-V.d.mts → planner-C1NzLBge.d.mts} +1 -1
- package/dist/{postgres-Dv-QnnbD.mjs → postgres-DQVSTqVm.mjs} +4 -4
- package/dist/{postgres-Dv-QnnbD.mjs.map → postgres-DQVSTqVm.mjs.map} +1 -1
- package/dist/postgres-adapter-CGthb5yh.mjs +2 -0
- package/dist/postgres-adapter-CGthb5yh.mjs.map +1 -0
- package/dist/postgres-adapter-CxEit2-v.mjs +2 -0
- package/dist/postgres-adapter-CxEit2-v.mjs.map +1 -0
- package/dist/{postgres-result-7F0DllQe.mjs → postgres-result-KyBKBNJr.mjs} +2 -2
- package/dist/{postgres-result-7F0DllQe.mjs.map → postgres-result-KyBKBNJr.mjs.map} +1 -1
- package/dist/postgres.d.mts +3 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-BHATED_m.mjs → provider-limits-Da00ilvv.mjs} +2 -2
- package/dist/{provider-limits-BHATED_m.mjs.map → provider-limits-Da00ilvv.mjs.map} +1 -1
- package/dist/{result-parsing-DRXC89ek.mjs → result-parsing-8wEK3GY1.mjs} +1 -1
- package/dist/{result-parsing-DRXC89ek.mjs.map → result-parsing-8wEK3GY1.mjs.map} +1 -1
- package/dist/result-shape-B6yWtnx_.mjs +2 -0
- package/dist/result-shape-B6yWtnx_.mjs.map +1 -0
- package/dist/scalar-CpEwuJvn.mjs +4 -0
- package/dist/scalar-CpEwuJvn.mjs.map +1 -0
- 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-BnzGHn7k.mjs +2 -0
- package/dist/{schema-Cjem1-0f.mjs.map → schema-BnzGHn7k.mjs.map} +1 -1
- package/dist/{schema-introspection-DEYGC2qg.mjs → schema-introspection-DZsdP6bi.mjs} +4 -4
- package/dist/{schema-introspection-DEYGC2qg.mjs.map → schema-introspection-DZsdP6bi.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-f1UGoblh.mjs → select-assembly-CkGe2ABs.mjs} +2 -2
- package/dist/{select-assembly-f1UGoblh.mjs.map → select-assembly-CkGe2ABs.mjs.map} +1 -1
- package/dist/{settle-B9Vg1FnP.mjs → settle-CS_k6Ztm.mjs} +2 -2
- package/dist/{settle-B9Vg1FnP.mjs.map → settle-CS_k6Ztm.mjs.map} +1 -1
- package/dist/soft-delete.d.mts +27 -96
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/sql-Bhxq9arK.mjs +2 -0
- package/dist/sql-Bhxq9arK.mjs.map +1 -0
- package/dist/{sql-BvfwUKIh.d.mts → sql-EsoN_7Et.d.mts} +24 -0
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-CFi1y3bK.mjs} +1 -1
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-CFi1y3bK.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-BXAJy3mI.mjs +2 -0
- package/dist/sqlite-adapter-BXAJy3mI.mjs.map +1 -0
- package/dist/{sqlite-utils-DlgokMJN.mjs → sqlite-utils-D_cypcyW.mjs} +2 -2
- package/dist/{sqlite-utils-DlgokMJN.mjs.map → sqlite-utils-D_cypcyW.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +3 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/{standard-sql-Bk4RZPqJ.mjs → standard-sql-CoGqv-iX.mjs} +3 -3
- package/dist/standard-sql-CoGqv-iX.mjs.map +1 -0
- package/dist/{suppressed-failure-BwULh-8h.mjs → suppressed-failure-Bdo2aK81.mjs} +1 -1
- package/dist/{suppressed-failure-BwULh-8h.mjs.map → suppressed-failure-Bdo2aK81.mjs.map} +1 -1
- package/dist/to-many-C5RMZl05.mjs +2 -0
- package/dist/to-many-C5RMZl05.mjs.map +1 -0
- package/dist/{transaction-Bnl6ULTw.mjs → transaction-4dfqals6.mjs} +2 -2
- package/dist/{transaction-Bnl6ULTw.mjs.map → transaction-4dfqals6.mjs.map} +1 -1
- package/dist/{transaction-operation-CKK3l_9x.mjs → transaction-operation-CU1zlxiG.mjs} +2 -2
- package/dist/{transaction-operation-CKK3l_9x.mjs.map → transaction-operation-CU1zlxiG.mjs.map} +1 -1
- package/dist/{types-C4v6iAmY.mjs → types-C5Oxz9yp.mjs} +1 -1
- package/dist/{types-C4v6iAmY.mjs.map → types-C5Oxz9yp.mjs.map} +1 -1
- package/dist/{utils-CZNaOZR7.mjs → utils-C3r4gO3Y.mjs} +4 -4
- package/dist/{utils-CZNaOZR7.mjs.map → utils-C3r4gO3Y.mjs.map} +1 -1
- package/dist/v-DtLdBQYg.mjs +2 -0
- package/dist/v-DtLdBQYg.mjs.map +1 -0
- package/dist/validation-BQtO6srU.mjs +2 -0
- package/dist/{validation-PF9-_nKd.mjs.map → validation-BQtO6srU.mjs.map} +1 -1
- package/dist/validation-BamBwne9.mjs +2 -0
- package/dist/validation-BamBwne9.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-CVSrhn0u.mjs +2 -0
- package/dist/validator-CVSrhn0u.mjs.map +1 -0
- package/dist/version-C8QLCt1n.mjs +2 -0
- package/dist/{version-nt0parEY.mjs.map → version-C8QLCt1n.mjs.map} +1 -1
- package/package.json +36 -9
- package/dist/adapter-namespace-DqkJQdrD.mjs +0 -2
- package/dist/builder-Ycvq3ETg.mjs +0 -2
- package/dist/builder-Ycvq3ETg.mjs.map +0 -1
- package/dist/chain-Dh0FV72b.mjs +0 -2
- package/dist/chain-Dh0FV72b.mjs.map +0 -1
- package/dist/client-B3VWFhv_.mjs +0 -49
- package/dist/client-BLiBmykn.mjs +0 -2
- package/dist/client-BLiBmykn.mjs.map +0 -1
- package/dist/controls-DXgIn4zh.mjs +0 -2
- package/dist/controls-DXgIn4zh.mjs.map +0 -1
- package/dist/driver-BlnKXPFF.mjs +0 -2
- package/dist/driver-BlnKXPFF.mjs.map +0 -1
- package/dist/error-mapping-CnPCv1dm.mjs +0 -2
- package/dist/error-mapping-CnPCv1dm.mjs.map +0 -1
- package/dist/every-o-Nu9Em8.mjs +0 -2
- package/dist/geo-point-codec-lhxH42SK.mjs +0 -2
- package/dist/geo-point-codec-lhxH42SK.mjs.map +0 -1
- package/dist/hydration-CAxOL4aI.mjs +0 -2
- package/dist/identifier-conversion-GgbwHc2G.mjs +0 -2
- package/dist/identifier-hQCs8M1n.mjs +0 -2
- package/dist/identifier-hQCs8M1n.mjs.map +0 -1
- package/dist/key-BeoOwGr3.mjs +0 -2
- package/dist/mysql-adapter-DkJPfoGf.mjs +0 -2
- package/dist/postgres-adapter-B3SQvcV1.mjs +0 -2
- package/dist/postgres-adapter-B3SQvcV1.mjs.map +0 -1
- package/dist/postgres-adapter-CQD2oGuD.mjs +0 -2
- package/dist/postgres-adapter-CQD2oGuD.mjs.map +0 -1
- package/dist/registration-preflight-DEjv050M.mjs +0 -4
- package/dist/registration-preflight-DEjv050M.mjs.map +0 -1
- package/dist/result-shape-CTNdNSW3.mjs +0 -2
- package/dist/result-shape-CTNdNSW3.mjs.map +0 -1
- package/dist/scalar-U0wD5bKy.mjs +0 -2
- package/dist/scalar-U0wD5bKy.mjs.map +0 -1
- package/dist/schema-Cjem1-0f.mjs +0 -2
- package/dist/sql-Bp7jicEX.mjs +0 -2
- package/dist/sql-Bp7jicEX.mjs.map +0 -1
- package/dist/sqlite-adapter-CW_3l6ea.mjs +0 -2
- package/dist/sqlite-adapter-CW_3l6ea.mjs.map +0 -1
- package/dist/standard-sql-Bk4RZPqJ.mjs.map +0 -1
- package/dist/terminal-C8cq1WWX.mjs +0 -2
- package/dist/terminal-C8cq1WWX.mjs.map +0 -1
- package/dist/v-D5Z06FKN.mjs +0 -2
- package/dist/v-D5Z06FKN.mjs.map +0 -1
- package/dist/validation-Dk9Q_-C7.mjs +0 -2
- package/dist/validation-Dk9Q_-C7.mjs.map +0 -1
- package/dist/validation-PF9-_nKd.mjs +0 -2
- package/dist/validator-X9-bwtRo.mjs +0 -2
- package/dist/validator-X9-bwtRo.mjs.map +0 -1
- package/dist/version-nt0parEY.mjs +0 -2
- /package/dist/{contract-CIIqgFyb.d.mts → contract-Dw0FR78e.d.mts} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t}from"./validation-BamBwne9.mjs";import{E as n,g as r}from"./geo-point-codec-DyEHMdJg.mjs";import{o as i}from"./sql-Bhxq9arK.mjs";import{a}from"./physical-CAOaNM4R.mjs";import{t as o}from"./geo-area-codec-CbkmFArQ.mjs";import{r as s}from"./adapter-internals-AGgQRu5t.mjs";import{n as ee}from"./result-parsing-8wEK3GY1.mjs";import{r as c}from"./datetime-physical-codec-BEqQbIP_.mjs";import{A as l,C as u,D as d,E as f,M as p,N as te,S as m,T as h,_ as g,a as _,c as v,d as y,f as b,g as x,h as S,i as C,l as w,m as T,n as E,o as D,p as O,r as k,s as A,t as j,u as M,v as N,w as ne,x as P,y as F}from"./standard-sql-CoGqv-iX.mjs";import{n as I}from"./batch-refs-B4zn-FAu.mjs";import{t as L}from"./adapter-namespace-BpMbLKpL.mjs";import{a as R,d as z,f as B,g as V,i as H,m as U,n as W,o as G,p as K,r as q,t as J,u as Y}from"./select-assembly-CkGe2ABs.mjs";const X=te("`"),Z=U(()=>`PRIMARY`),Q={quotient:(e,t)=>i`CAST((${e} - MOD(${e}, ${t})) / ${t} AS DECIMAL(65,0))`,remainder:(e,t)=>i`MOD(${e}, ${t})`},mysqlMaximumCoefficient=e=>i.raw(`9`.repeat(e)),re=i`(FIND_IN_SET('STRICT_TRANS_TABLES', @@SESSION.sql_mode) > 0 OR FIND_IN_SET('STRICT_ALL_TABLES', @@SESSION.sql_mode) > 0)`,$=i`JSON_EXTRACT('x', '$')`,decimalCast=(e,t,n)=>i`CAST(${e} AS ${i.raw(`DECIMAL(${t},${n})`)})`,mysqlCoefficient=(e,t)=>{let{scale:n}=t;if(n===0)return e;let r=Y(n),a=i`TRUNCATE(${e}, 0)`;return i`(${a} * ${r} + ${decimalCast(i`(${decimalCast(i`(${e} - ${a})`,n+1,n)} * ${r})`,n,0)})`},mysqlLogical=(e,t)=>{let{scale:n}=t;if(n===0)return e;let r=Y(n),a=i`MOD(${e}, ${r})`;return i`((${e} - ${a}) / ${r} + ${decimalCast(a,n,0)} * ${z(n)})`},mysqlGuardedDecimalAssignment=(e,t,n,r)=>{let a=mysqlMaximumCoefficient(n.precision),o=mysqlLogical(t,n);return i`${e} = CASE WHEN ${re} THEN ${o} WHEN ${e} IS NULL THEN NULL WHEN ${r} THEN CASE WHEN ${t} BETWEEN -${a} AND ${a} THEN ${o} ELSE ${$} END ELSE ${$} END`},mysqlDecimalIncrement=(e,t,n)=>{let r=mysqlCoefficient(e,n),a=mysqlCoefficient(t,n),o=mysqlMaximumCoefficient(n.precision),s=i`CASE WHEN ${a} > 0 THEN ${r} <= ${o} - ${a} WHEN ${a} < 0 THEN ${r} >= -${o} - ${a} ELSE TRUE END`;return mysqlGuardedDecimalAssignment(e,i`(${r} + ${a})`,n,s)},mysqlDecimalDecrement=(e,t,n)=>{let r=mysqlCoefficient(e,n),a=mysqlCoefficient(t,n),o=mysqlMaximumCoefficient(n.precision),s=i`CASE WHEN ${a} > 0 THEN ${r} >= -${o} + ${a} WHEN ${a} < 0 THEN ${r} <= ${o} + ${a} ELSE TRUE END`;return mysqlGuardedDecimalAssignment(e,i`(${r} - ${a})`,n,s)},mysqlDecimalMultiply=(e,t,n)=>{let r=mysqlCoefficient(e,n),a=mysqlCoefficient(t,n),o=mysqlMaximumCoefficient(65);return mysqlGuardedDecimalAssignment(e,G(Q,i`(${r} * ${a})`,Y(n.scale)),n,i`CASE WHEN ${a} = 0 THEN TRUE ELSE ABS(${r}) <= ${Q.quotient(o,i`ABS(${a})`)} END`)},mysqlDecimalDivide=(e,t,n)=>{let r=mysqlCoefficient(t,n);return mysqlGuardedDecimalAssignment(e,G(Q,B(i`(${mysqlCoefficient(e,n)} * ${Y(n.scale)})`,r),i`ABS(${r})`),n,i.raw`TRUE`)},mysqlDecimalAverage=(e,t)=>mysqlLogical(G(Q,i`SUM(${mysqlCoefficient(e,t)})`,i`COUNT(${e})`),t),asciiCaseFold=e=>{let t=e;for(let e=0;e<26;e++){let n=i.raw(`'${`ABCDEFGHIJKLMNOPQRSTUVWXYZ`[e]}'`),r=i.raw(`'${`abcdefghijklmnopqrstuvwxyz`[e]}'`);t=i`REPLACE(${t}, ${n}, ${r})`}return t},ie=/^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(\.\d+)?$/,naiveDateTimeToIso=e=>{let t=ie.exec(e);if(!t)return;let n=t[3]?t[3].padEnd(4,`0`).slice(0,4):`.000`;return`${t[1]}T${t[2]}${n}Z`},inlineIntegerLiteral=e=>{let t=e.values.length===1?e.values[0]:void 0;return typeof t==`number`&&Number.isInteger(t)?i.raw(String(t)):e},mysqlJsonObject=e=>{if(e.length===0)return i.raw`JSON_OBJECT()`;let t=e.flatMap(([e,t])=>[i`${e}`,t]);return i`JSON_OBJECT(${i.join(t,`, `)})`},mysqlJsonListValue=e=>i`CAST(${p(e)} AS JSON)`;var MySQLAdapter=class{constructor(e){L(this,e,`mysql`),this.identifiers=b(X,this.namespace),K(this,this.geoPoint),s(this,{batchRefs:this.#t,constraints:Z,select:this.#e.select})}raw=m();identifiers;literals={...f(),true:()=>i.raw`TRUE`,false:()=>i.raw`FALSE`,json:e=>i`${JSON.stringify(e)}`,dateTime:(e,t,n)=>i`${n||e.length===10?e:c(e)}`,decimal:(e,t)=>i`CAST(${n(e,t,`text`)} AS ${i.raw(r(`mysql`,t))})`,id:(e,t)=>i`${e}`};operators={..._(),like:(e,t)=>i`${e} LIKE ${t} ESCAPE '\\\\'`,notLike:(e,t)=>i`${e} NOT LIKE ${t} ESCAPE '\\\\'`,ilike:(e,t)=>i`${asciiCaseFold(e)} LIKE ${asciiCaseFold(t)} ESCAPE '\\\\'`,notIlike:(e,t)=>i`${asciiCaseFold(e)} NOT LIKE ${asciiCaseFold(t)} ESCAPE '\\\\'`,containsText:(e,t)=>i`LOCATE(BINARY ${t}, BINARY ${e}) > 0`,startsWithText:(e,t)=>i`LEFT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t}`,endsWithText:(e,t)=>i`RIGHT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t}`,startsWithPrefix:(e,t)=>i`(${e} LIKE ${`${l(t)}%`} ESCAPE '\\\\' AND LEFT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t})`,exactTextEq:(e,t)=>i`(${e} = ${t} AND BINARY ${e} = ${t})`,exactTextIn:(e,t)=>i`(${e} IN ${t} AND BINARY ${e} IN ${t})`,...x(),...N(),...P(),...S(this.literals.true,this.literals.false),...y()};expressions={...C(),asciiCaseFold,caseSensitiveText:e=>i`BINARY ${e}`,concat:(...e)=>e.length===0?i.raw`''`:e.length===1?e[0]:i`CONCAT(${i.join(e,`, `)})`,greatest:(...e)=>i`GREATEST(${i.join(e,`, `)})`,least:(...e)=>i`LEAST(${i.join(e,`, `)})`,integerDivide:(e,t)=>i`TRUNCATE(${e} / ${t}, 0)`,decimalCast:(e,t)=>decimalCast(e,t.precision,t.scale),idCast:(e,t)=>t===`bytes`?i`UNHEX(${e})`:i`CAST(${e} AS CHAR)`,cast:k({text:`CHAR`,integer:`SIGNED`,bigint:`SIGNED`,boolean:`UNSIGNED`,numeric:`DECIMAL`}),blobToHex:e=>i`LOWER(HEX(${e}))`};aggregates={...E(),decimalAvg:(e,t)=>mysqlDecimalAverage(e,t),decimalSumOperandPrecision:v(65)};json={equals:(e,t)=>i`${e} = ${t}`,number:e=>e,boolean:e=>i`JSON_EXTRACT(CASE WHEN ${e} THEN 'true' ELSE 'false' END, '$')`,document:e=>e,object:mysqlJsonObject,array:e=>e.length===0?i.raw`JSON_ARRAY()`:i`JSON_ARRAY(${i.join(e,`, `)})`,emptyArray:()=>i.raw`JSON_ARRAY()`,agg:e=>i`COALESCE(JSON_ARRAYAGG(${e}), JSON_ARRAY())`,objectFromColumns:mysqlJsonObject,extract:(e,t)=>i`JSON_EXTRACT(${e}, ${j(t)})`,extractText:(e,t)=>i`JSON_UNQUOTE(JSON_EXTRACT(${e}, ${j(t)}))`,numberAtPath:(e,t)=>{let n=j(t);return i`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${n})) IN ('INTEGER', 'DOUBLE', 'DECIMAL') THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${e}, ${n})) AS DOUBLE) END)`},stringAtPath:(e,t)=>{let n=j(t);return i`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${n})) = 'STRING' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${e}, ${n})) AS BINARY) END)`},contains:(e,t)=>i`JSON_CONTAINS(${e}, ${t})`,lastElement:e=>i`JSON_EXTRACT(${e}, '$[last]')`,value:e=>i`CAST(${p(e)} AS JSON)`};arrays={literal:e=>e.length===0?i.raw`JSON_ARRAY()`:i`JSON_ARRAY(${i.join(e,`, `)})`,value:mysqlJsonListValue,enumValue:mysqlJsonListValue,has:(e,t)=>i`JSON_CONTAINS(${e}, JSON_ARRAY(${t}))`,hasEvery:(e,t)=>i`JSON_CONTAINS(${e}, ${t})`,hasSome:(e,t)=>i`JSON_OVERLAPS(${e}, ${t})`,isEmpty:e=>i`(JSON_LENGTH(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>i`CAST(${e} AS CHAR)`,length:e=>i`JSON_LENGTH(${e})`,get:(e,t)=>i`JSON_EXTRACT(${e}, CONCAT('$[', ${t}, ']'))`,push:(e,t)=>i`JSON_ARRAY_APPEND(${e}, '$', ${t})`,set:(e,t,n)=>i`JSON_SET(${e}, CONCAT('$[', ${t}, ']'), ${n})`};orderBy={...w(),...M()};clauses={...h(),limit:e=>i`LIMIT ${inlineIntegerLiteral(e)}`,offset:e=>i`OFFSET ${inlineIntegerLiteral(e)}`};set={...F(),increment:(e,t,n)=>n?.decimal?mysqlDecimalIncrement(e,t,n.decimal):i`${e} = ${e} + ${t}`,decrement:(e,t,n)=>n?.decimal?mysqlDecimalDecrement(e,t,n.decimal):i`${e} = ${e} - ${t}`,multiply:(e,t,n)=>n?.decimal?mysqlDecimalMultiply(e,t,n.decimal):i`${e} = ${e} * ${t}`,divide:(e,t,n)=>n?.decimal?mysqlDecimalDivide(e,t,n.decimal):n?.integer?i`${e} = TRUNCATE(${e} / ${t}, 0)`:i`${e} = ${e} / ${t}`,push:(e,t)=>i`${e} = JSON_MERGE_PRESERVE(COALESCE(${e}, JSON_ARRAY()), ${t})`,unshift:(e,t)=>i`${e} = JSON_MERGE_PRESERVE(${t}, COALESCE(${e}, JSON_ARRAY()))`};filters=u();subqueries=d(X);noLimitValue=i.raw`18446744073709551615`;#e={select:e=>{let t={...e,limit:e.limit&&inlineIntegerLiteral(e.limit),offset:e.offset&&inlineIntegerLiteral(e.offset)};return t.distinct?J(t,t.distinct,this.identifiers.escape,this.noLimitValue):W(i`SELECT ${t.columns}`,t,{forUpdate:`append`,noLimitValue:this.noLimitValue})}};cte=A(X);mutations={skipDuplicatesStrategy:`recoverableUniqueError`,insert:O(X),insertDefault:e=>i`INSERT INTO ${e} () VALUES ()`,...g(),returning:e=>i.empty,onConflict:(e,t,n)=>i`ON DUPLICATE KEY UPDATE ${t}`,onConflictUpdate:(e,t)=>e,skipDuplicates:e=>{let t=i.raw(X(e));return{prefix:i.empty,suffix:i`ON DUPLICATE KEY UPDATE ${t} = ${t}`}}};assertions={exists:e=>i`SELECT CASE WHEN EXISTS (${e}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \`__viborm_assert__\``,notExists:e=>i`SELECT CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \`__viborm_assert__\``,holds:(e,t)=>i`SELECT CASE WHEN ${e} THEN 1 ELSE JSON_EXTRACT('{}', '__viborm_refused__') END AS \`__viborm_judged__\`${t?i` FROM ${t}`:i``}`};joins={...D(),full:(e,t)=>{throw Error(`MySQL does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.`)},...T(X)};setOperations=ne(X);capabilities={supportsReturning:!1,supportsCteWithMutations:!1,supportsFullOuterJoin:!1,supportsLateralJoins:!0,supportsVector:!1,supportsUpsertWhere:!1,supportsTargetedUpsert:!1,supportsMutationTargetInSubquery:!1,supportsMutationRowLimit:!0,supportsRowLocks:!0};lastInsertId=()=>i.raw`LAST_INSERT_ID()`;#t=I({table:i.raw`\`__viborm_batch_refs\``,batchIdColumn:i.raw`\`batch_id\``,keyColumn:i.raw`\`ref_key\``,valueColumn:i.raw`\`ref_value\``,duplicateValue:i.raw`VALUES(\`ref_value\`)`,createTable:i.raw`CREATE TEMPORARY TABLE IF NOT EXISTS \`__viborm_batch_refs\` (\`batch_id\` VARCHAR(191) NOT NULL, \`ref_key\` VARCHAR(191) NOT NULL, \`ref_value\` TEXT, PRIMARY KEY (\`batch_id\`, \`ref_key\`))`,castValue:e=>i`CAST((${e}) AS CHAR)`,lastInsertId:()=>this.lastInsertId()});vector=t;geoPoint=(()=>{let longitude=e=>i`ST_Longitude(${e})`,latitude=e=>i`ST_Latitude(${e})`;return{value:(e,t)=>i`ST_GeomFromText(CONCAT('POINT(', ${e}, ' ', ${t}, ')'), 4326, 'axis-order=long-lat')`,longitude,latitude,...q(longitude,latitude,this.operators,(e,t)=>{let n=H(t);if(n.length!==0)return this.operators.or(...n.map(t=>i`MBRIntersects(${e}, ST_GeomFromGeoJSON(${t}, 1, 4326))`))}),withinPolygon:(e,t)=>i`ST_Intersects(${i`ST_GeomFromGeoJSON(${R(t)}, 1, 4326)`}, ${e})`,distance:(e,t)=>i`ST_Distance_Sphere(${e}, ${t}, ${o})`}})();result={decimalListRepresentation:`coefficient`,idRepresentation:(e,t)=>a(e,t,`mysql`)?.representation??`text`,parseResult:V,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>{if(t===`boolean`){let t=ee(e===`0`?0:e===`1`?1:e);if(t!==void 0)return n(t)}if(t===`datetime`&&typeof e==`string`){let t=naiveDateTimeToIso(e);if(t!==void 0)return n(t)}return n()}}};export{MySQLAdapter as t};
|
|
2
|
+
//# sourceMappingURL=mysql-adapter-C6c5govr.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mysql-adapter-DkJPfoGf.mjs","names":["sql","#batchRefs","#assemble"],"sources":["../src/adapters/databases/mysql/mysql-adapter.ts"],"sourcesContent":["import { unsupportedVector } from \"@errors\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { type Sql, sql } from \"@sql\";\nimport { encodeMySqlDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { GEO_POINT_EARTH_RADIUS_METERS } from \"@validation/primitives/geo-area-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport type { ArithmeticTarget } from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport { installAdapterNamespace } from \"../../adapter-namespace\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport {\n type AdapterResultParser,\n passThroughParseResult,\n} from \"../../adapter-result-parser\";\nimport { createNamedConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n} from \"../../database-adapter\";\nimport { createMySqlBatchRefs } from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n halfEvenQuotient,\n scaleFactorSql,\n scaleUnitSql,\n signedNumerator,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoBoundsIndexPolygons,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport { parseIntegerBoolean } from \"../../shared/result-parsing\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n buildJsonPath,\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDecimalSumOperandPrecision,\n createDirectionOrderBy,\n createEmulatedNullsOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLateralJoins,\n createLogicalOperators,\n createMembershipOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n stringifyJson,\n} from \"../../shared/standard-sql\";\n\nconst quoteIdent = createIdentifierQuoter(\"`\");\nconst MYSQL_CONSTRAINTS = createNamedConstraintIdentities(() => \"PRIMARY\");\n\n/**\n * MySQL has `MOD()` but no exact integer-quotient function for decimals: `DIV`\n * converts both sides to BIGINT (so it overflows and truncates a wide\n * `DECIMAL`), and `TRUNCATE(n / d, 0)` computes `n / d` to\n * `div_precision_increment` extra digits and ROUNDS there first, which can turn\n * a value just below a half into an exact-looking tie.\n *\n * `(n - MOD(n, d)) / d` avoids both: the numerator is exactly divisible by `d`,\n * so the division's true result has no fractional digits and the extra digits\n * MySQL computes are all zero.\n */\nconst MYSQL_INTEGERS: ExactIntegerArithmetic = {\n // The CAST is not decoration. MySQL's `/` ALWAYS returns\n // `div_precision_increment` (four, by default) fractional digits, so an exact\n // integer quotient arrives typed `DECIMAL(w, 4)` — four digits of the 65-digit\n // exact domain spent on zeros, and any product taking that value as an operand\n // would carry them into ITS width. Casting back to the widest exact integer\n // domain is exact here (the value has no fraction to lose) and is what keeps\n // every downstream term integer-typed.\n quotient: (n: Sql, d: Sql): Sql =>\n sql`CAST((${n} - MOD(${n}, ${d})) / ${d} AS DECIMAL(65,0))`,\n remainder: (n: Sql, d: Sql): Sql => sql`MOD(${n}, ${d})`,\n};\n\n/**\n * MySQL's exact decimal domain, in digits — the ceiling every expression below\n * is written to stay under (plan 5.3: \"MySQL expressions avoid an intermediate\n * wider than its 65-digit exact domain\").\n */\nconst MYSQL_EXACT_DIGITS = 65;\n\nconst mysqlMaximumCoefficient = (digits: number): Sql =>\n sql.raw(\"9\".repeat(digits));\n\nconst mysqlStrictMode = sql`(FIND_IN_SET('STRICT_TRANS_TABLES', @@SESSION.sql_mode) > 0 OR FIND_IN_SET('STRICT_ALL_TABLES', @@SESSION.sql_mode) > 0)`;\n\nconst mysqlArithmeticFailure = sql`JSON_EXTRACT('x', '$')`;\n\n/** `CAST(<expr> AS DECIMAL(precision,scale))`, the width-declaring device. */\nconst decimalCast = (expr: Sql, precision: number, scale: number): Sql =>\n sql`CAST(${expr} AS ${sql.raw(`DECIMAL(${precision},${scale})`)})`;\n\n/**\n * The signed unscaled COEFFICIENT of a logical `DECIMAL(p,s)` expression, as an\n * exact integer — WITHOUT ever multiplying the whole value by `10^s`.\n *\n * `column * 10^s` is the obvious spelling and it is the unsafe one. MySQL types\n * a product as `DECIMAL(p1+p2, s1+s2)` capped at `(65, 30)`, so multiplying a\n * `DECIMAL(65,30)` column by a `DECIMAL(31,0)` factor asks for a 96-digit type,\n * gets a 65-digit one whose 30 fractional digits leave 35 for an integer that\n * needs 65 — and MySQL answers ZERO, with no warning and no error (measured on\n * 8.4: `SELECT CAST(REPEAT('9',50) AS DECIMAL(65,0)) * 0.<29 zeros>1` is\n * `0.000…0`). Splitting the value first is what keeps every factor small:\n *\n * whole = TRUNCATE(v, 0) |whole| < 10^(p-s), scale 0\n * fraction = v - whole |fraction| < 1, scale s\n * coefficient = whole * 10^s + fraction * 10^s\n *\n * Widths, by construction, for every descriptor MySQL admits (`p <= 65`,\n * `s <= 30`, `p + s <= 65`): `whole * 10^s` is typed\n * `DECIMAL(min(p+2,65), 0)` and valued\n * below `10^p`; `fraction * 10^s` is typed `DECIMAL(2s+2, s)` — at most 62\n * digits — and valued below `10^s`, so its cast to `DECIMAL(s,0)` is exact.\n * Neither product's operands sum past the exact domain, so neither can take the\n * silent arm above.\n */\nconst mysqlCoefficient = (value: Sql, descriptor: DecimalDescriptor): Sql => {\n const { scale } = descriptor;\n if (scale === 0) return value;\n const factor = scaleFactorSql(scale);\n const whole = sql`TRUNCATE(${value}, 0)`;\n const fraction = decimalCast(sql`(${value} - ${whole})`, scale + 1, scale);\n return sql`(${whole} * ${factor} + ${decimalCast(sql`(${fraction} * ${factor})`, scale, 0)})`;\n};\n\n/**\n * The logical `DECIMAL(p,s)` value of an exact integer COEFFICIENT — the\n * inverse of {@link mysqlCoefficient}, and unsafe for the same reason in the\n * same place.\n *\n * `coefficient * 10^-s` would multiply a `p`-digit integer by a\n * `DECIMAL(s+1,s)` literal: `p + s + 1` digits of type for a value that needs\n * `p`, which is the silent-zero arm again for a wide descriptor. So the\n * coefficient is split by `10^s` FIRST — an integer part that is already the\n * answer's integer part, and a remainder below `10^s` that is the only thing\n * the tiny `10^-s` literal ever multiplies:\n *\n * integer part = (coefficient - MOD(coefficient, 10^s)) / 10^s\n * fraction = MOD(coefficient, 10^s) * 10^-s\n *\n * Widths: the division is typed `DECIMAL(w, 4)` over a value below `10^(p-s)`,\n * and the fractional product's operands sum to `2s + 1` — at most 61 digits.\n */\nconst mysqlLogical = (coefficient: Sql, descriptor: DecimalDescriptor): Sql => {\n const { scale } = descriptor;\n if (scale === 0) return coefficient;\n const factor = scaleFactorSql(scale);\n const remainder = sql`MOD(${coefficient}, ${factor})`;\n return sql`((${coefficient} - ${remainder}) / ${factor} + ${decimalCast(remainder, scale, 0)} * ${scaleUnitSql(scale)})`;\n};\n\n/**\n * Assign one coefficient-space answer without letting a non-strict MySQL\n * session turn overflow into a clipped value. Strict sessions retain their\n * native error. A non-strict session reaches the answer only after the caller's\n * operation-specific precondition proves its intermediate is exact and the\n * target-domain check proves the final coefficient fits.\n *\n * The session-mode arm is deliberately first. `CASE` is the same lazy error\n * primitive used by this adapter's assertion queries, so a safe or NULL arm\n * never evaluates the invalid JSON expression that raises the provider error.\n */\nconst mysqlGuardedDecimalAssignment = (\n column: Sql,\n coefficient: Sql,\n descriptor: DecimalDescriptor,\n intermediateFits: Sql\n): Sql => {\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const logical = mysqlLogical(coefficient, descriptor);\n return sql`${column} = CASE WHEN ${mysqlStrictMode} THEN ${logical} WHEN ${column} IS NULL THEN NULL WHEN ${intermediateFits} THEN CASE WHEN ${coefficient} BETWEEN -${maximum} AND ${maximum} THEN ${logical} ELSE ${mysqlArithmeticFailure} END ELSE ${mysqlArithmeticFailure} END`;\n};\n\nconst mysqlDecimalIncrement = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = sql`CASE WHEN ${operand} > 0 THEN ${current} <= ${maximum} - ${operand} WHEN ${operand} < 0 THEN ${current} >= -${maximum} - ${operand} ELSE TRUE END`;\n return mysqlGuardedDecimalAssignment(\n column,\n sql`(${current} + ${operand})`,\n descriptor,\n fits\n );\n};\n\nconst mysqlDecimalDecrement = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = sql`CASE WHEN ${operand} > 0 THEN ${current} >= -${maximum} + ${operand} WHEN ${operand} < 0 THEN ${current} <= ${maximum} + ${operand} ELSE TRUE END`;\n return mysqlGuardedDecimalAssignment(\n column,\n sql`(${current} - ${operand})`,\n descriptor,\n fits\n );\n};\n\n/**\n * `column = halfEven(column x by)`, computed on COEFFICIENTS.\n *\n * This is plan 5.3's rule verbatim — `multiply = halfEven((x * y) / F)` — and\n * it is stated on integers because MySQL cannot state it on logical values: the\n * exact product of two `DECIMAL(p,s)` values carries `2s` fractional digits,\n * and MySQL caps an expression's scale at 30, ROUNDING anything finer away\n * before the tie this rule exists to decide is ever visible (measured: `1e-30 *\n * 1e-30` is `0.000…0` at `DECIMAL(65,30)`, no warning). Coefficients have no\n * fractional digits at all, so nothing can be rounded away underneath the rule.\n *\n * WIDTH, BY CONSTRUCTION. `|x|, |y| < 10^p`, and the answer is in the field's\n * domain exactly when `|x * y| < 10^(p+s)`, so the product needs at most\n * `p + s` digits: within the 65-digit exact domain for every descriptor with\n * `precision + scale <= 65`. The quotient is `< 10^p`, the remainder `< 10^s`,\n * and the tie test compares `|r|` against `10^s - |r|` — the non-doubling form,\n * so nothing widens there either.\n *\n * Outside that bound the operation is loud on every session. A strict session\n * reaches MySQL's native overflow error. A non-strict session first proves the\n * product can be formed inside 65 digits and that the rounded coefficient fits\n * the field; a failed proof evaluates the adapter's lazy error expression\n * instead of letting MySQL clip the assignment. Both leave the row unchanged.\n */\nconst mysqlDecimalMultiply = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const left = mysqlCoefficient(column, descriptor);\n const right = mysqlCoefficient(by, descriptor);\n const maximumIntermediate = mysqlMaximumCoefficient(MYSQL_EXACT_DIGITS);\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n sql`(${left} * ${right})`,\n scaleFactorSql(descriptor.scale)\n );\n const intermediateFits = sql`CASE WHEN ${right} = 0 THEN TRUE ELSE ABS(${left}) <= ${MYSQL_INTEGERS.quotient(maximumIntermediate, sql`ABS(${right})`)} END`;\n return mysqlGuardedDecimalAssignment(\n column,\n coefficient,\n descriptor,\n intermediateFits\n );\n};\n\n/**\n * `column = halfEven(column / by)`, computed on COEFFICIENTS — plan 5.3's\n * `divide = halfEven((x * F) / y)`.\n *\n * The divisor is the operand's COEFFICIENT rather than its logical value: an\n * exact quotient is spelled `(n - MOD(n, d)) / d`, and with a fractional `d`\n * the numerator `n - MOD(n, d)` is `q * d` — a `p`-digit magnitude carrying `s`\n * fractional digits, `p + s` digits for a value the integer form states in `p`.\n * Integers on both sides keep every term at its own width.\n *\n * WIDTH, BY CONSTRUCTION: `|x * F| < 10^(p+s)` — inside the exact domain for\n * every descriptor with `precision + scale <= 65`, and unconditionally, not\n * only when the answer fits. The quotient is the answer's coefficient\n * (`< 10^p` when it fits the field), the remainder is below `|y| < 10^p`, and\n * the tie compares `|r|` against `|y| - |r|`, which is why the doubled form was\n * dropped: `2|r|` at `p = 65` needs 66.\n *\n * `by` is never zero — division by canonical zero is refused before I/O.\n */\nconst mysqlDecimalDivide = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const divisor = mysqlCoefficient(by, descriptor);\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n signedNumerator(\n sql`(${mysqlCoefficient(column, descriptor)} * ${scaleFactorSql(descriptor.scale)})`,\n divisor\n ),\n sql`ABS(${divisor})`\n );\n return mysqlGuardedDecimalAssignment(\n column,\n coefficient,\n descriptor,\n sql.raw`TRUE`\n );\n};\n\n/**\n * The exact decimal average, on coefficients: `SUM` of the column's\n * coefficients over `COUNT(column)`, quantized half to even.\n *\n * Summing the COEFFICIENTS rather than scaling the sum is what removes the last\n * `x 10^s` from this expression: `SUM(column) * 10^s` multiplies a value MySQL\n * already types up to 65 digits by a 31-digit factor, which is the silent-zero\n * arm {@link mysqlCoefficient} exists to avoid. Every row's coefficient is\n * below `10^p`, so the only way the sum leaves the exact domain is by genuinely\n * exceeding it, and MySQL raises there.\n *\n * `COUNT(column)` counts non-nulls, so an empty or all-null group answers NULL\n * through the null-strict operators instead of dividing by zero.\n */\nconst mysqlDecimalAverage = (\n column: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n sql`SUM(${mysqlCoefficient(column, descriptor)})`,\n sql`COUNT(${column})`\n );\n return mysqlLogical(coefficient, descriptor);\n};\nconst ASCII_UPPERCASE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst ASCII_LOWERCASE = \"abcdefghijklmnopqrstuvwxyz\";\n\nconst asciiCaseFold = (expr: Sql): Sql => {\n let folded = expr;\n for (let index = 0; index < ASCII_UPPERCASE.length; index++) {\n const upper = sql.raw(`'${ASCII_UPPERCASE[index]}'`);\n const lower = sql.raw(`'${ASCII_LOWERCASE[index]}'`);\n folded = sql`REPLACE(${folded}, ${upper}, ${lower})`;\n }\n return folded;\n};\n\n// MySQL DATETIME rejects ISO-8601's 'Z' suffix (\"Incorrect datetime value\"),\n// so datetimes are stored as naive UTC wall-clock 'YYYY-MM-DD HH:MM:SS.mmm'.\n\n// Naive datetime string as it comes back from MySQL (top-level on string\n// drivers, or inside JSON_ARRAYAGG/JSON_OBJECT includes): no 'Z'/offset.\nconst NAIVE_DATETIME_REGEX =\n /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2})(\\.\\d+)?$/;\n\n/** Reattach UTC to a naive MySQL datetime string so it parses as the stored instant. */\nconst naiveDateTimeToIso = (value: string): string | undefined => {\n const match = NAIVE_DATETIME_REGEX.exec(value);\n if (!match) return undefined;\n const fraction = match[3] ? match[3].padEnd(4, \"0\").slice(0, 4) : \".000\";\n return `${match[1]}T${match[2]}${fraction}Z`;\n};\n\n/** Replace a single-integer-parameter fragment with an inline literal. */\nconst inlineIntegerLiteral = (fragment: Sql): Sql => {\n const value = fragment.values.length === 1 ? fragment.values[0] : undefined;\n return typeof value === \"number\" && Number.isInteger(value)\n ? sql.raw(String(value))\n : fragment;\n};\n\nconst mysqlJsonObject = (pairs: [string, Sql][]): Sql => {\n if (pairs.length === 0) return sql.raw`JSON_OBJECT()`;\n const args = pairs.flatMap(([key, value]) => [sql`${key}`, value]);\n return sql`JSON_OBJECT(${sql.join(args, \", \")})`;\n};\n\n/** The one JSON list container every MySQL list value crosses as. */\nconst mysqlJsonListValue = (values: unknown[]): Sql =>\n sql`CAST(${stringifyJson(values)} AS JSON)`;\n\nexport class MySQLAdapter implements DatabaseAdapter {\n /**\n * The bound database, or `undefined` for the unqualified mode a\n * provider-configured MySQL2 client and every PlanetScale client keep. Under\n * Vitess the value is the keyspace qualifier submitted before routing rules\n * apply, not a proof of the routed backend.\n */\n declare readonly namespace: string | undefined;\n\n constructor(namespace?: string) {\n installAdapterNamespace(this, namespace, \"mysql\");\n // Reads the installed value, so it cannot be a field initializer: those run\n // before the constructor body.\n this.identifiers = createIdentifiers(quoteIdent, this.namespace);\n installGeoPointSql(this, this.geoPoint);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: MYSQL_CONSTRAINTS,\n select: this.#assemble.select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // MySQL requires JSON values to be stringified\n json: (v: unknown): Sql => sql`${JSON.stringify(v)}`,\n\n dateTime: (\n iso: string,\n _nativeType?: NativeTypeDeclaration,\n member?: boolean\n ): Sql =>\n sql`${member || iso.length === 10 ? iso : encodeMySqlDateTime(iso)}`,\n\n // The cast is load-bearing, not decoration. MySQL's comparison rules say\n // that when one side is a number and the other a string, BOTH are converted\n // to double and compared as floating point — so `amount = '0.1'` against a\n // `DECIMAL` column would silently answer at float precision on an otherwise\n // exact column. Casting the operand into the SAME `DECIMAL(p,s)` the DDL\n // emits keeps the whole comparison in MySQL's exact decimal domain, and\n // names one domain for the operand and the column instead of two.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${encodePhysicalDecimal(canonical, descriptor, \"text\")} AS ${sql.raw(decimalColumnType(\"mysql\", descriptor))})`,\n\n // MySQL has no `uuid` type: every compact domain is a `BINARY(n)` column\n // and takes the payload's bytes as an ordinary binary parameter, which is\n // the same parameter a blob scalar already binds. A text-stored domain\n // takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n _representation: IdRepresentation\n ): Sql => sql`${physical}`,\n };\n\n operators = {\n ...createComparisonOperators(),\n\n // Explicit ESCAPE '\\' pairs with wildcard escaping in the where-builder.\n // The literal is doubled ('\\\\') because MySQL's default mode treats\n // backslash as a string-literal escape; under NO_BACKSLASH_ESCAPES it\n // fails loudly rather than silently matching wildcards.\n like: (column: Sql, pattern: Sql): Sql =>\n sql`${column} LIKE ${pattern} ESCAPE '\\\\\\\\'`,\n notLike: (column: Sql, pattern: Sql): Sql =>\n sql`${column} NOT LIKE ${pattern} ESCAPE '\\\\\\\\'`,\n ilike: (column: Sql, pattern: Sql): Sql =>\n sql`${asciiCaseFold(column)} LIKE ${asciiCaseFold(pattern)} ESCAPE '\\\\\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`${asciiCaseFold(column)} NOT LIKE ${asciiCaseFold(pattern)} ESCAPE '\\\\\\\\'`,\n containsText: (column: Sql, value: Sql): Sql =>\n sql`LOCATE(BINARY ${value}, BINARY ${column}) > 0`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value}`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`RIGHT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value}`,\n // Two conjuncts, because on MySQL no single predicate is both exact and\n // index-usable. The index stores the column's own collation's sort keys —\n // `utf8mb4_0900_ai_ci` on a default install, which is case- AND\n // accent-insensitive — so any comparison forced to BINARY cannot range on\n // it. Measured on MySQL 8 (Docker, 20k rows): `col LIKE 'x%'` is a `range`\n // over 111 rows, while both `col LIKE BINARY 'x%'` and the\n // `LEFT(BINARY col, …)` spelling above degrade to a full `index` scan of\n // all 19731 entries.\n //\n // So the collation-native LIKE goes first as an index accelerator, and the\n // BINARY predicate — byte-identical to `startsWithText` above — follows as\n // the semantics. The accelerator can never drop a row the BINARY conjunct\n // would keep: byte-equal strings compare equal under every collation, so a\n // binary prefix match implies the collation-native one. It is not a second\n // guard on the same invariant — it decides no row's membership, only which\n // rows the server has to look at.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n startsWithPrefix: (column: Sql, value: string): Sql =>\n sql`(${column} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\\\\\' AND LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value})`,\n\n // `startsWithPrefix`'s twin, for the same reason and in the same shape\n // (plan §10.2). `BINARY col` is a FUNCTION of the column, so MySQL cannot\n // range on it: measured on MySQL 8.4 over 20,000 rows in the collation\n // viborm's own DDL declares, `BINARY name = ?` planned `index` over 20,455\n // rows where `name = ?` planned `ref` over 1, and `BINARY name IN (…)`\n // planned `index` over 20,455 where `name IN (…)` planned `range` over 3.\n //\n // The collation-native conjunct is the accelerator and decides no row's\n // membership: byte-identical strings compare equal under every collation\n // of the charset, so the BINARY comparison IMPLIES it. On the tables\n // viborm creates (`utf8mb4_0900_bin`) the two conjuncts say the same\n // thing; on a table viborm did not create the BINARY one is what keeps the\n // case-sensitivity contract, and the same measurement shows the pair still\n // plans `ref` over 1 row there.\n //\n // `notIn` and `not` deliberately have no such pair. Their implication runs\n // the other way — `BINARY col NOT IN ('X')` KEEPS a row spelled `x` that\n // `col NOT IN ('X')` drops on a case-insensitive column, measured at\n // 20,000 rows against 19,999 — so a conjunct would remove rows. There is\n // also nothing to win: both spellings of `NOT IN` scan all 20,442 rows.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n exactTextEq: (column: Sql, value: Sql): Sql =>\n sql`(${column} = ${value} AND BINARY ${column} = ${value})`,\n exactTextIn: (column: Sql, values: Sql): Sql =>\n sql`(${column} IN ${values} AND BINARY ${column} IN ${values})`,\n\n ...createMembershipOperators(),\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n asciiCaseFold,\n caseSensitiveText: (expr: Sql): Sql => sql`BINARY ${expr}`,\n\n // String operations - MySQL uses CONCAT() function\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw`''`;\n if (parts.length === 1) return parts[0]!;\n return sql`CONCAT(${sql.join(parts, \", \")})`;\n },\n\n greatest: (...exprs: Sql[]): Sql => sql`GREATEST(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`LEAST(${sql.join(exprs, \", \")})`,\n\n // The expression form of `set.divide`'s integer arm: MySQL `/` yields a\n // DECIMAL quotient even for two integers, so the truncation is explicit.\n integerDivide: (left: Sql, right: Sql): Sql =>\n sql`TRUNCATE(${left} / ${right}, 0)`,\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n decimalCast(expr, descriptor.precision, descriptor.scale),\n\n // `CHAR` rather than `TEXT`: MySQL's CAST target list has no `TEXT`, which\n // is why `cast` below maps the generic text cast to `CHAR` too.\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`UNHEX(${expr})`\n : sql`CAST(${expr} AS CHAR)`,\n\n cast: createCastExpression({\n text: \"CHAR\",\n integer: \"SIGNED\",\n bigint: \"SIGNED\",\n boolean: \"UNSIGNED\",\n numeric: \"DECIMAL\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`LOWER(HEX(${expr}))`,\n };\n\n aggregates = {\n ...createAggregateFunctions(),\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n mysqlDecimalAverage(column, descriptor),\n\n // MySQL's widest exact DECIMAL cast operand. SUM itself can return more\n // than 65 digits; this bound belongs to exact HAVING operand lowering.\n decimalSumOperandPrecision:\n createDecimalSumOperandPrecision(MYSQL_EXACT_DIGITS),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql => sql`${left} = ${right}`,\n number: (expression: Sql): Sql => expression,\n boolean: (condition: Sql): Sql =>\n sql`JSON_EXTRACT(CASE WHEN ${condition} THEN 'true' ELSE 'false' END, '$')`,\n document: (expression: Sql): Sql => expression,\n\n object: mysqlJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`JSON_ARRAY()`;\n return sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw`JSON_ARRAY()`,\n\n agg: (expr: Sql): Sql =>\n sql`COALESCE(JSON_ARRAYAGG(${expr}), JSON_ARRAY())`,\n\n objectFromColumns: mysqlJsonObject,\n\n // buildJsonPath quotes/escapes key segments and maps integer segments\n // to array indices; '$' alone extracts the document root\n extract: (column: Sql, path: string[]): Sql =>\n sql`JSON_EXTRACT(${column}, ${buildJsonPath(path)})`,\n\n extractText: (column: Sql, path: string[]): Sql =>\n sql`JSON_UNQUOTE(JSON_EXTRACT(${column}, ${buildJsonPath(path)}))`,\n\n // JSON_TYPE spells numbers three ways depending on how the literal was\n // stored; anything else (including an absent path, where JSON_TYPE is\n // NULL) falls through the CASE to NULL\n numberAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) IN ('INTEGER', 'DOUBLE', 'DECIMAL') THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) AS DOUBLE) END)`;\n },\n\n // CAST(... AS BINARY) yields VARBINARY, so < / > compare bytes instead of\n // the column's (case- and accent-insensitive by default) collation\n stringAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) = 'STRING' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) AS BINARY) END)`;\n },\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`JSON_CONTAINS(${target}, ${value})`,\n\n lastElement: (target: Sql): Sql => sql`JSON_EXTRACT(${target}, '$[last]')`,\n\n // Comparing a JSON column to a plain string coerces the string to a JSON\n // string scalar (always-false for documents); CAST parses it as JSON\n value: (v: unknown): Sql => sql`CAST(${stringifyJson(v)} AS JSON)`,\n };\n\n arrays = {\n // MySQL uses JSON arrays\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`JSON_ARRAY()`;\n return sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n },\n\n value: mysqlJsonListValue,\n\n // Deliberately the same container, by identity: MySQL stores an enum LIST\n // as JSON like every other list, so its members are ordinary JSON strings\n // and there is no element type to spell. The inline `ENUM(...)` describes\n // one member.\n enumValue: mysqlJsonListValue,\n\n // JSON_CONTAINS requires a JSON document as candidate; a bare string\n // parameter throws ER_INVALID_JSON_TEXT. JSON_ARRAY keeps the parameter's\n // type (strings quoted, numbers not): [x] ⊆ column ⟺ x ∈ column\n has: (column: Sql, value: Sql): Sql =>\n sql`JSON_CONTAINS(${column}, JSON_ARRAY(${value}))`,\n\n hasEvery: (column: Sql, values: Sql): Sql =>\n sql`JSON_CONTAINS(${column}, ${values})`,\n\n hasSome: (column: Sql, values: Sql): Sql =>\n sql`JSON_OVERLAPS(${column}, ${values})`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(JSON_LENGTH(${column}) = 0 OR ${column} IS NULL)`,\n\n // The container as TEXT, so it reaches the decode as the exact bytes the\n // codec wrote: uncast, mysql2 parses a JSON column into a JavaScript\n // document and JSON_OBJECT nests it as a live array, and the coefficient\n // grammar would then be read off values a JSON parser already interpreted.\n exactNumericProjection: (column: Sql): Sql => sql`CAST(${column} AS CHAR)`,\n\n length: (column: Sql): Sql => sql`JSON_LENGTH(${column})`,\n\n get: (column: Sql, index: Sql): Sql =>\n sql`JSON_EXTRACT(${column}, CONCAT('$[', ${index}, ']'))`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`JSON_ARRAY_APPEND(${column}, '$', ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`JSON_SET(${column}, CONCAT('$[', ${index}, ']'), ${value})`,\n };\n\n orderBy = {\n ...createDirectionOrderBy(),\n // MySQL doesn't support NULLS FIRST/LAST natively - emulated\n ...createEmulatedNullsOrderBy(),\n };\n\n // mysql2's binary protocol binds JS numbers as DOUBLE, which MySQL rejects\n // in integer-only positions (\"Incorrect arguments to mysqld_stmt_execute\").\n // Inline integer LIMIT/OFFSET values instead of parameterizing them.\n clauses = {\n ...createStandardClauses(),\n limit: (count: Sql): Sql => sql`LIMIT ${inlineIntegerLiteral(count)}`,\n offset: (count: Sql): Sql => sql`OFFSET ${inlineIntegerLiteral(count)}`,\n };\n\n // JSON_MERGE_PRESERVE concatenates arrays element-wise; JSON_ARRAY_APPEND\n // would append the whole param as a single (stringified) element.\n set = {\n ...createNumericSetOperations(),\n\n increment: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalIncrement(column, by, target.decimal)\n : sql`${column} = ${column} + ${by}`,\n\n decrement: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalDecrement(column, by, target.decimal)\n : sql`${column} = ${column} - ${by}`,\n\n // A decimal target rounds the product back to the field's scale; every\n // other numeric column keeps MySQL's native multiplication.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalMultiply(column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n\n // MySQL `/` yields DECIMAL and rounds when assigned to an integer column.\n // Truncate explicitly so integer division matches PostgreSQL and SQLite.\n // A decimal target takes neither: `/` would round at\n // `div_precision_increment` digits, so the exact half-even quotient rule\n // decides the last digit instead.\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n if (target?.decimal) {\n return mysqlDecimalDivide(column, by, target.decimal);\n }\n return target?.integer\n ? sql`${column} = TRUNCATE(${column} / ${by}, 0)`\n : sql`${column} = ${column} / ${by}`;\n },\n\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = JSON_MERGE_PRESERVE(COALESCE(${column}, JSON_ARRAY()), ${values})`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = JSON_MERGE_PRESERVE(${values}, COALESCE(${column}, JSON_ARRAY()))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n // MySQL has no bare OFFSET; per the manual, use an all-ones LIMIT sentinel\n noLimitValue = sql.raw`18446744073709551615`;\n\n readonly #assemble = {\n select: (rawParts: QueryParts): Sql => {\n // Inline integer LIMIT/OFFSET (see clauses above for why)\n const parts: QueryParts = {\n ...rawParts,\n limit: rawParts.limit && inlineIntegerLiteral(rawParts.limit),\n offset: rawParts.offset && inlineIntegerLiteral(rawParts.offset),\n };\n\n // MySQL doesn't support DISTINCT ON natively\n // Simulate using ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)\n if (parts.distinct) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape,\n this.noLimitValue\n );\n }\n\n return assembleSelectQuery(sql`SELECT ${parts.columns}`, parts, {\n forUpdate: \"append\",\n noLimitValue: this.noLimitValue,\n });\n },\n };\n\n // MySQL 8.0+ common table expressions\n cte = createCteBuilders(quoteIdent);\n\n mutations = {\n skipDuplicatesStrategy: \"recoverableUniqueError\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql => sql`INSERT INTO ${table} () VALUES ()`,\n\n ...createMutationCommands(),\n\n // MySQL doesn't support RETURNING - returns empty\n // Use LAST_INSERT_ID() or SELECT after mutation\n returning: (_columns: Sql): Sql => sql.empty,\n\n // This low-level MySQL primitive ignores `_target`: ON DUPLICATE KEY UPDATE\n // fires on any unique collision. Public non-returning upserts therefore do\n // not execute this primitive; the query engine uses a locked, target-aware\n // branch so an unrelated unique collision still throws on every database.\n onConflict: (_target: Sql | null, action: Sql, _targetWhere?: Sql): Sql => {\n return sql`ON DUPLICATE KEY UPDATE ${action}`;\n },\n\n // MySQL doesn't need UPDATE SET prefix - onConflict already includes UPDATE\n onConflictUpdate: (sets: Sql, _setWhere?: Sql): Sql => sets,\n\n // A self-assignment reacts only to duplicate-key conflicts. Unlike\n // INSERT IGNORE, unrelated constraint and conversion failures still abort.\n //\n // It stays the JUNCTION insert's clause on MySQL as well, because\n // `ON DUPLICATE KEY UPDATE` cannot name a target (`onConflict` above says\n // so) — correct for every junction whose PK is its sole unique constraint,\n // which is every ordinary pair table. A polymorphic member table with a\n // SINGULAR inverse also carries a target-side UNIQUE that this clause would\n // swallow; the seam for that case is documented at `junctionDuplicateSkip`\n // in `query-engine/builders/many-to-many-utils.ts`.\n skipDuplicates: (duplicateNoopColumn: string) => {\n const column = sql.raw(quoteIdent(duplicateNoopColumn));\n return {\n prefix: sql.empty,\n suffix: sql`ON DUPLICATE KEY UPDATE ${column} = ${column}`,\n };\n },\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN EXISTS (${query}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \\`__viborm_assert__\\``,\n notExists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \\`__viborm_assert__\\``,\n };\n\n joins = {\n ...createCoreJoins(),\n\n // MySQL doesn't support FULL OUTER JOIN (would need a UNION of LEFT and\n // RIGHT joins). Never silently downgrade to LEFT JOIN: that drops rows.\n // The query engine never calls this today.\n full: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\n \"MySQL does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.\"\n );\n },\n\n // MySQL 8.0.14+ supports LATERAL\n ...createLateralJoins(quoteIdent),\n };\n\n setOperations = createSetOperations();\n\n capabilities = {\n supportsReturning: false,\n supportsCteWithMutations: false, // MySQL CTEs are read-only\n supportsFullOuterJoin: false,\n supportsLateralJoins: true, // MySQL 8.0.14+\n supportsVector: false,\n supportsUpsertWhere: false, // ON DUPLICATE KEY UPDATE doesn't support WHERE clauses\n // ON DUPLICATE KEY UPDATE carries no conflict target and fires on ANY unique\n // collision — see the `onConflict` note above. A targeted upsert cannot be\n // spelled here, so the ON CONFLICT fold never opens on MySQL.\n supportsTargetedUpsert: false,\n // ERROR 1093: UPDATE/DELETE can't select from the mutated table in a\n // subquery. The engine wraps relation-filter subqueries in a derived\n // table when this is false (requires MySQL 8.0.14+ for outer references\n // in derived tables).\n supportsMutationTargetInSubquery: false,\n // MySQL's single-table UPDATE/DELETE take a native LIMIT, which is also the\n // only portable spelling here: the PK-subquery form would re-read the\n // mutated table and trip the same ERROR 1093 as above.\n supportsMutationRowLimit: true,\n supportsRowLocks: true,\n };\n\n lastInsertId = (): Sql => sql.raw`LAST_INSERT_ID()`;\n\n readonly #batchRefs = createMySqlBatchRefs({\n table: sql.raw`\\`__viborm_batch_refs\\``,\n batchIdColumn: sql.raw`\\`batch_id\\``,\n keyColumn: sql.raw`\\`ref_key\\``,\n valueColumn: sql.raw`\\`ref_value\\``,\n duplicateValue: sql.raw`VALUES(\\`ref_value\\`)`,\n createTable: sql.raw`CREATE TEMPORARY TABLE IF NOT EXISTS \\`__viborm_batch_refs\\` (\\`batch_id\\` VARCHAR(191) NOT NULL, \\`ref_key\\` VARCHAR(191) NOT NULL, \\`ref_value\\` TEXT, PRIMARY KEY (\\`batch_id\\`, \\`ref_key\\`))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS CHAR)`,\n lastInsertId: () => this.lastInsertId(),\n });\n\n vector = unsupportedVector;\n\n readonly geoPoint: GeoPointSql = (() => {\n const longitude = (point: Sql): Sql => sql`ST_Longitude(${point})`;\n const latitude = (point: Sql): Sql => sql`ST_Latitude(${point})`;\n return {\n // EPSG:4326 is latitude-longitude in MySQL's SRS catalog. The explicit\n // WKT option makes the two bound coordinates longitude-latitude instead.\n value: (pointLongitude, pointLatitude) =>\n sql`ST_GeomFromText(CONCAT('POINT(', ${pointLongitude}, ' ', ${pointLatitude}, ')'), 4326, 'axis-order=long-lat')`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators,\n (point, bounds) => {\n const polygons = geoBoundsIndexPolygons(bounds);\n if (polygons.length === 0) return;\n return this.operators.or(\n ...polygons.map(\n (polygon) =>\n sql`MBRIntersects(${point}, ST_GeomFromGeoJSON(${polygon}, 1, 4326))`\n )\n );\n }\n ),\n withinPolygon: (point, polygon) => {\n const geography = sql`ST_GeomFromGeoJSON(${geoPolygonJson(\n polygon\n )}, 1, 4326)`;\n return sql`ST_Intersects(${geography}, ${point})`;\n },\n distance: (left, right) =>\n sql`ST_Distance_Sphere(${left}, ${right}, ${GEO_POINT_EARTH_RADIUS_METERS})`,\n };\n })();\n\n // RESULT PARSING\n // MySQL: booleans and naive UTC datetimes - both ROW VALUES.\n // This adapter says nothing about a RESULT: the engine's decoder asks for\n // the alias `_count` and reads it back, and mysql2 preserves that alias\n // (Arnaud's D-40, measured live).\n // Relation carriers decode at the query-engine boundary that knows their\n // value is JSON, so the adapter never sniffs ordinary strings.\n result: AdapterResultParser = {\n // A MySQL SCALAR decimal is `DECIMAL(p,s)` and answers with exact text, so\n // `decimalRepresentation` stays at its default. A decimal LIST is JSON,\n // which has no exact decimal at all, so its members are stored and returned\n // as unscaled coefficient strings (plan 6.1). This adapter is the reason\n // the two are separate declarations.\n decimalListRepresentation: \"coefficient\",\n\n // Derived from the ONE storage owner, so the column the migration creates\n // and the value this reads back cannot be two decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"mysql\")?.representation ?? \"text\",\n\n // The contract's shape, deciding nothing on all 20 asks D-40 measured over\n // seven operations and both routes on live MySQL - the `count`/`exist` arm\n // was entered on 10 of them and answered `undefined` every time\n // (`g4/rulings/o2/receipts/leg-probe-mysql.log`). A RESULT is the\n // decoder's, and D-28's chain ends there.\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n\n parseField: (\n value: unknown,\n scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n // MySQL stores booleans as TINYINT(1) - 0/1\n if (scalarType === \"boolean\") {\n const parsed = parseIntegerBoolean(\n value === \"0\" ? 0 : value === \"1\" ? 1 : value\n );\n if (parsed !== undefined) {\n return next(parsed);\n }\n }\n // Datetime strings are naive UTC wall-clock; without this, the default\n // parser's new Date(str) would shift them by the process timezone\n if (scalarType === \"datetime\" && typeof value === \"string\") {\n const iso = naiveDateTimeToIso(value);\n if (iso !== undefined) {\n return next(iso);\n }\n }\n return next();\n },\n };\n}\n"],"mappings":"64BA4EA,MAAM,EAAa,GAAuB,IAAI,CACxC,EAAoB,MAAsC,UAAU,CAapE,EAAyC,CAQ7C,UAAW,EAAQ,IACjB,CAAG,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,oBAC1C,WAAY,EAAQ,IAAgB,CAAG,OAAO,EAAE,IAAI,EAAE,GACvD,CASK,wBAA2B,GAC/BA,EAAI,IAAI,IAAI,OAAO,EAAO,CAAC,CAEvB,GAAkB,CAAG,2HAErB,EAAyB,CAAG,yBAG5B,aAAe,EAAW,EAAmB,IACjD,CAAG,QAAQ,EAAK,MAAMA,EAAI,IAAI,WAAW,EAAU,GAAG,EAAM,GAAG,CAAC,GA0B5D,kBAAoB,EAAY,IAAuC,CAC3E,GAAM,CAAE,SAAU,EAClB,GAAI,IAAU,EAAG,OAAO,EACxB,IAAM,EAAS,EAAe,EAAM,CAC9B,EAAQ,CAAG,YAAY,EAAM,MAEnC,MAAO,EAAG,IAAI,EAAM,KAAK,EAAO,KAAK,YAAY,CAAG,IADnC,YAAY,CAAG,IAAI,EAAM,KAAK,EAAM,GAAI,EAAQ,EAAG,EAAM,CACT,KAAK,EAAO,GAAI,EAAO,EAAE,CAAC,IAqBvF,cAAgB,EAAkB,IAAuC,CAC7E,GAAM,CAAE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AAS,EACb,IAAU,IAAM,EAAI,IAAU,IAAM,EAAI,EACzC,CACD,GAAI,IAAW,IAAA,GACb,OAAO,EAAK,EAAO,CAKvB,GAAI,IAAe,YAAc,OAAO,GAAU,SAAU,CAC1D,IAAM,EAAM,mBAAmB,EAAM,CACrC,GAAI,IAAQ,IAAA,GACV,OAAO,EAAK,EAAI,CAGpB,OAAO,GAAM,EAEhB"}
|
|
1
|
+
{"version":3,"file":"mysql-adapter-C6c5govr.mjs","names":["sql","#batchRefs","#assemble"],"sources":["../src/adapters/databases/mysql/mysql-adapter.ts"],"sourcesContent":["import { unsupportedVector } from \"@errors\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { type Sql, sql } from \"@sql\";\nimport { encodeMySqlDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { GEO_POINT_EARTH_RADIUS_METERS } from \"@validation/primitives/geo-area-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport type { ArithmeticTarget } from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport { installAdapterNamespace } from \"../../adapter-namespace\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport {\n type AdapterResultParser,\n passThroughParseResult,\n} from \"../../adapter-result-parser\";\nimport { createNamedConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n} from \"../../database-adapter\";\nimport { createMySqlBatchRefs } from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n halfEvenQuotient,\n scaleFactorSql,\n scaleUnitSql,\n signedNumerator,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoBoundsIndexPolygons,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport { parseIntegerBoolean } from \"../../shared/result-parsing\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n buildJsonPath,\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDecimalSumOperandPrecision,\n createDirectionOrderBy,\n createEmulatedNullsOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLateralJoins,\n createLogicalOperators,\n createMembershipOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n stringifyJson,\n} from \"../../shared/standard-sql\";\n\nconst quoteIdent = createIdentifierQuoter(\"`\");\nconst MYSQL_CONSTRAINTS = createNamedConstraintIdentities(() => \"PRIMARY\");\n\n/**\n * MySQL has `MOD()` but no exact integer-quotient function for decimals: `DIV`\n * converts both sides to BIGINT (so it overflows and truncates a wide\n * `DECIMAL`), and `TRUNCATE(n / d, 0)` computes `n / d` to\n * `div_precision_increment` extra digits and ROUNDS there first, which can turn\n * a value just below a half into an exact-looking tie.\n *\n * `(n - MOD(n, d)) / d` avoids both: the numerator is exactly divisible by `d`,\n * so the division's true result has no fractional digits and the extra digits\n * MySQL computes are all zero.\n */\nconst MYSQL_INTEGERS: ExactIntegerArithmetic = {\n // The CAST is not decoration. MySQL's `/` ALWAYS returns\n // `div_precision_increment` (four, by default) fractional digits, so an exact\n // integer quotient arrives typed `DECIMAL(w, 4)` — four digits of the 65-digit\n // exact domain spent on zeros, and any product taking that value as an operand\n // would carry them into ITS width. Casting back to the widest exact integer\n // domain is exact here (the value has no fraction to lose) and is what keeps\n // every downstream term integer-typed.\n quotient: (n: Sql, d: Sql): Sql =>\n sql`CAST((${n} - MOD(${n}, ${d})) / ${d} AS DECIMAL(65,0))`,\n remainder: (n: Sql, d: Sql): Sql => sql`MOD(${n}, ${d})`,\n};\n\n/**\n * MySQL's exact decimal domain, in digits — the ceiling every expression below\n * is written to stay under (plan 5.3: \"MySQL expressions avoid an intermediate\n * wider than its 65-digit exact domain\").\n */\nconst MYSQL_EXACT_DIGITS = 65;\n\nconst mysqlMaximumCoefficient = (digits: number): Sql =>\n sql.raw(\"9\".repeat(digits));\n\nconst mysqlStrictMode = sql`(FIND_IN_SET('STRICT_TRANS_TABLES', @@SESSION.sql_mode) > 0 OR FIND_IN_SET('STRICT_ALL_TABLES', @@SESSION.sql_mode) > 0)`;\n\nconst mysqlArithmeticFailure = sql`JSON_EXTRACT('x', '$')`;\n\n/** `CAST(<expr> AS DECIMAL(precision,scale))`, the width-declaring device. */\nconst decimalCast = (expr: Sql, precision: number, scale: number): Sql =>\n sql`CAST(${expr} AS ${sql.raw(`DECIMAL(${precision},${scale})`)})`;\n\n/**\n * The signed unscaled COEFFICIENT of a logical `DECIMAL(p,s)` expression, as an\n * exact integer — WITHOUT ever multiplying the whole value by `10^s`.\n *\n * `column * 10^s` is the obvious spelling and it is the unsafe one. MySQL types\n * a product as `DECIMAL(p1+p2, s1+s2)` capped at `(65, 30)`, so multiplying a\n * `DECIMAL(65,30)` column by a `DECIMAL(31,0)` factor asks for a 96-digit type,\n * gets a 65-digit one whose 30 fractional digits leave 35 for an integer that\n * needs 65 — and MySQL answers ZERO, with no warning and no error (measured on\n * 8.4: `SELECT CAST(REPEAT('9',50) AS DECIMAL(65,0)) * 0.<29 zeros>1` is\n * `0.000…0`). Splitting the value first is what keeps every factor small:\n *\n * whole = TRUNCATE(v, 0) |whole| < 10^(p-s), scale 0\n * fraction = v - whole |fraction| < 1, scale s\n * coefficient = whole * 10^s + fraction * 10^s\n *\n * Widths, by construction, for every descriptor MySQL admits (`p <= 65`,\n * `s <= 30`, `p + s <= 65`): `whole * 10^s` is typed\n * `DECIMAL(min(p+2,65), 0)` and valued\n * below `10^p`; `fraction * 10^s` is typed `DECIMAL(2s+2, s)` — at most 62\n * digits — and valued below `10^s`, so its cast to `DECIMAL(s,0)` is exact.\n * Neither product's operands sum past the exact domain, so neither can take the\n * silent arm above.\n */\nconst mysqlCoefficient = (value: Sql, descriptor: DecimalDescriptor): Sql => {\n const { scale } = descriptor;\n if (scale === 0) return value;\n const factor = scaleFactorSql(scale);\n const whole = sql`TRUNCATE(${value}, 0)`;\n const fraction = decimalCast(sql`(${value} - ${whole})`, scale + 1, scale);\n return sql`(${whole} * ${factor} + ${decimalCast(sql`(${fraction} * ${factor})`, scale, 0)})`;\n};\n\n/**\n * The logical `DECIMAL(p,s)` value of an exact integer COEFFICIENT — the\n * inverse of {@link mysqlCoefficient}, and unsafe for the same reason in the\n * same place.\n *\n * `coefficient * 10^-s` would multiply a `p`-digit integer by a\n * `DECIMAL(s+1,s)` literal: `p + s + 1` digits of type for a value that needs\n * `p`, which is the silent-zero arm again for a wide descriptor. So the\n * coefficient is split by `10^s` FIRST — an integer part that is already the\n * answer's integer part, and a remainder below `10^s` that is the only thing\n * the tiny `10^-s` literal ever multiplies:\n *\n * integer part = (coefficient - MOD(coefficient, 10^s)) / 10^s\n * fraction = MOD(coefficient, 10^s) * 10^-s\n *\n * Widths: the division is typed `DECIMAL(w, 4)` over a value below `10^(p-s)`,\n * and the fractional product's operands sum to `2s + 1` — at most 61 digits.\n */\nconst mysqlLogical = (coefficient: Sql, descriptor: DecimalDescriptor): Sql => {\n const { scale } = descriptor;\n if (scale === 0) return coefficient;\n const factor = scaleFactorSql(scale);\n const remainder = sql`MOD(${coefficient}, ${factor})`;\n return sql`((${coefficient} - ${remainder}) / ${factor} + ${decimalCast(remainder, scale, 0)} * ${scaleUnitSql(scale)})`;\n};\n\n/**\n * Assign one coefficient-space answer without letting a non-strict MySQL\n * session turn overflow into a clipped value. Strict sessions retain their\n * native error. A non-strict session reaches the answer only after the caller's\n * operation-specific precondition proves its intermediate is exact and the\n * target-domain check proves the final coefficient fits.\n *\n * The session-mode arm is deliberately first. `CASE` is the same lazy error\n * primitive used by this adapter's assertion queries, so a safe or NULL arm\n * never evaluates the invalid JSON expression that raises the provider error.\n */\nconst mysqlGuardedDecimalAssignment = (\n column: Sql,\n coefficient: Sql,\n descriptor: DecimalDescriptor,\n intermediateFits: Sql\n): Sql => {\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const logical = mysqlLogical(coefficient, descriptor);\n return sql`${column} = CASE WHEN ${mysqlStrictMode} THEN ${logical} WHEN ${column} IS NULL THEN NULL WHEN ${intermediateFits} THEN CASE WHEN ${coefficient} BETWEEN -${maximum} AND ${maximum} THEN ${logical} ELSE ${mysqlArithmeticFailure} END ELSE ${mysqlArithmeticFailure} END`;\n};\n\nconst mysqlDecimalIncrement = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = sql`CASE WHEN ${operand} > 0 THEN ${current} <= ${maximum} - ${operand} WHEN ${operand} < 0 THEN ${current} >= -${maximum} - ${operand} ELSE TRUE END`;\n return mysqlGuardedDecimalAssignment(\n column,\n sql`(${current} + ${operand})`,\n descriptor,\n fits\n );\n};\n\nconst mysqlDecimalDecrement = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = sql`CASE WHEN ${operand} > 0 THEN ${current} >= -${maximum} + ${operand} WHEN ${operand} < 0 THEN ${current} <= ${maximum} + ${operand} ELSE TRUE END`;\n return mysqlGuardedDecimalAssignment(\n column,\n sql`(${current} - ${operand})`,\n descriptor,\n fits\n );\n};\n\n/**\n * `column = halfEven(column x by)`, computed on COEFFICIENTS.\n *\n * This is plan 5.3's rule verbatim — `multiply = halfEven((x * y) / F)` — and\n * it is stated on integers because MySQL cannot state it on logical values: the\n * exact product of two `DECIMAL(p,s)` values carries `2s` fractional digits,\n * and MySQL caps an expression's scale at 30, ROUNDING anything finer away\n * before the tie this rule exists to decide is ever visible (measured: `1e-30 *\n * 1e-30` is `0.000…0` at `DECIMAL(65,30)`, no warning). Coefficients have no\n * fractional digits at all, so nothing can be rounded away underneath the rule.\n *\n * WIDTH, BY CONSTRUCTION. `|x|, |y| < 10^p`, and the answer is in the field's\n * domain exactly when `|x * y| < 10^(p+s)`, so the product needs at most\n * `p + s` digits: within the 65-digit exact domain for every descriptor with\n * `precision + scale <= 65`. The quotient is `< 10^p`, the remainder `< 10^s`,\n * and the tie test compares `|r|` against `10^s - |r|` — the non-doubling form,\n * so nothing widens there either.\n *\n * Outside that bound the operation is loud on every session. A strict session\n * reaches MySQL's native overflow error. A non-strict session first proves the\n * product can be formed inside 65 digits and that the rounded coefficient fits\n * the field; a failed proof evaluates the adapter's lazy error expression\n * instead of letting MySQL clip the assignment. Both leave the row unchanged.\n */\nconst mysqlDecimalMultiply = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const left = mysqlCoefficient(column, descriptor);\n const right = mysqlCoefficient(by, descriptor);\n const maximumIntermediate = mysqlMaximumCoefficient(MYSQL_EXACT_DIGITS);\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n sql`(${left} * ${right})`,\n scaleFactorSql(descriptor.scale)\n );\n const intermediateFits = sql`CASE WHEN ${right} = 0 THEN TRUE ELSE ABS(${left}) <= ${MYSQL_INTEGERS.quotient(maximumIntermediate, sql`ABS(${right})`)} END`;\n return mysqlGuardedDecimalAssignment(\n column,\n coefficient,\n descriptor,\n intermediateFits\n );\n};\n\n/**\n * `column = halfEven(column / by)`, computed on COEFFICIENTS — plan 5.3's\n * `divide = halfEven((x * F) / y)`.\n *\n * The divisor is the operand's COEFFICIENT rather than its logical value: an\n * exact quotient is spelled `(n - MOD(n, d)) / d`, and with a fractional `d`\n * the numerator `n - MOD(n, d)` is `q * d` — a `p`-digit magnitude carrying `s`\n * fractional digits, `p + s` digits for a value the integer form states in `p`.\n * Integers on both sides keep every term at its own width.\n *\n * WIDTH, BY CONSTRUCTION: `|x * F| < 10^(p+s)` — inside the exact domain for\n * every descriptor with `precision + scale <= 65`, and unconditionally, not\n * only when the answer fits. The quotient is the answer's coefficient\n * (`< 10^p` when it fits the field), the remainder is below `|y| < 10^p`, and\n * the tie compares `|r|` against `|y| - |r|`, which is why the doubled form was\n * dropped: `2|r|` at `p = 65` needs 66.\n *\n * `by` is never zero — division by canonical zero is refused before I/O.\n */\nconst mysqlDecimalDivide = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const divisor = mysqlCoefficient(by, descriptor);\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n signedNumerator(\n sql`(${mysqlCoefficient(column, descriptor)} * ${scaleFactorSql(descriptor.scale)})`,\n divisor\n ),\n sql`ABS(${divisor})`\n );\n return mysqlGuardedDecimalAssignment(\n column,\n coefficient,\n descriptor,\n sql.raw`TRUE`\n );\n};\n\n/**\n * The exact decimal average, on coefficients: `SUM` of the column's\n * coefficients over `COUNT(column)`, quantized half to even.\n *\n * Summing the COEFFICIENTS rather than scaling the sum is what removes the last\n * `x 10^s` from this expression: `SUM(column) * 10^s` multiplies a value MySQL\n * already types up to 65 digits by a 31-digit factor, which is the silent-zero\n * arm {@link mysqlCoefficient} exists to avoid. Every row's coefficient is\n * below `10^p`, so the only way the sum leaves the exact domain is by genuinely\n * exceeding it, and MySQL raises there.\n *\n * `COUNT(column)` counts non-nulls, so an empty or all-null group answers NULL\n * through the null-strict operators instead of dividing by zero.\n */\nconst mysqlDecimalAverage = (\n column: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n sql`SUM(${mysqlCoefficient(column, descriptor)})`,\n sql`COUNT(${column})`\n );\n return mysqlLogical(coefficient, descriptor);\n};\nconst ASCII_UPPERCASE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst ASCII_LOWERCASE = \"abcdefghijklmnopqrstuvwxyz\";\n\nconst asciiCaseFold = (expr: Sql): Sql => {\n let folded = expr;\n for (let index = 0; index < ASCII_UPPERCASE.length; index++) {\n const upper = sql.raw(`'${ASCII_UPPERCASE[index]}'`);\n const lower = sql.raw(`'${ASCII_LOWERCASE[index]}'`);\n folded = sql`REPLACE(${folded}, ${upper}, ${lower})`;\n }\n return folded;\n};\n\n// MySQL DATETIME rejects ISO-8601's 'Z' suffix (\"Incorrect datetime value\"),\n// so datetimes are stored as naive UTC wall-clock 'YYYY-MM-DD HH:MM:SS.mmm'.\n\n// Naive datetime string as it comes back from MySQL (top-level on string\n// drivers, or inside JSON_ARRAYAGG/JSON_OBJECT includes): no 'Z'/offset.\nconst NAIVE_DATETIME_REGEX =\n /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2})(\\.\\d+)?$/;\n\n/** Reattach UTC to a naive MySQL datetime string so it parses as the stored instant. */\nconst naiveDateTimeToIso = (value: string): string | undefined => {\n const match = NAIVE_DATETIME_REGEX.exec(value);\n if (!match) return undefined;\n const fraction = match[3] ? match[3].padEnd(4, \"0\").slice(0, 4) : \".000\";\n return `${match[1]}T${match[2]}${fraction}Z`;\n};\n\n/** Replace a single-integer-parameter fragment with an inline literal. */\nconst inlineIntegerLiteral = (fragment: Sql): Sql => {\n const value = fragment.values.length === 1 ? fragment.values[0] : undefined;\n return typeof value === \"number\" && Number.isInteger(value)\n ? sql.raw(String(value))\n : fragment;\n};\n\nconst mysqlJsonObject = (pairs: [string, Sql][]): Sql => {\n if (pairs.length === 0) return sql.raw`JSON_OBJECT()`;\n const args = pairs.flatMap(([key, value]) => [sql`${key}`, value]);\n return sql`JSON_OBJECT(${sql.join(args, \", \")})`;\n};\n\n/** The one JSON list container every MySQL list value crosses as. */\nconst mysqlJsonListValue = (values: unknown[]): Sql =>\n sql`CAST(${stringifyJson(values)} AS JSON)`;\n\nexport class MySQLAdapter implements DatabaseAdapter {\n /**\n * The bound database, or `undefined` for the unqualified mode a\n * provider-configured MySQL2 client and every PlanetScale client keep. Under\n * Vitess the value is the keyspace qualifier submitted before routing rules\n * apply, not a proof of the routed backend.\n */\n declare readonly namespace: string | undefined;\n\n constructor(namespace?: string) {\n installAdapterNamespace(this, namespace, \"mysql\");\n // Reads the installed value, so it cannot be a field initializer: those run\n // before the constructor body.\n this.identifiers = createIdentifiers(quoteIdent, this.namespace);\n installGeoPointSql(this, this.geoPoint);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: MYSQL_CONSTRAINTS,\n select: this.#assemble.select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // MySQL requires JSON values to be stringified\n json: (v: unknown): Sql => sql`${JSON.stringify(v)}`,\n\n dateTime: (\n iso: string,\n _nativeType?: NativeTypeDeclaration,\n member?: boolean\n ): Sql =>\n sql`${member || iso.length === 10 ? iso : encodeMySqlDateTime(iso)}`,\n\n // The cast is load-bearing, not decoration. MySQL's comparison rules say\n // that when one side is a number and the other a string, BOTH are converted\n // to double and compared as floating point — so `amount = '0.1'` against a\n // `DECIMAL` column would silently answer at float precision on an otherwise\n // exact column. Casting the operand into the SAME `DECIMAL(p,s)` the DDL\n // emits keeps the whole comparison in MySQL's exact decimal domain, and\n // names one domain for the operand and the column instead of two.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${encodePhysicalDecimal(canonical, descriptor, \"text\")} AS ${sql.raw(decimalColumnType(\"mysql\", descriptor))})`,\n\n // MySQL has no `uuid` type: every compact domain is a `BINARY(n)` column\n // and takes the payload's bytes as an ordinary binary parameter, which is\n // the same parameter a blob scalar already binds. A text-stored domain\n // takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n _representation: IdRepresentation\n ): Sql => sql`${physical}`,\n };\n\n operators = {\n ...createComparisonOperators(),\n\n // Explicit ESCAPE '\\' pairs with wildcard escaping in the where-builder.\n // The literal is doubled ('\\\\') because MySQL's default mode treats\n // backslash as a string-literal escape; under NO_BACKSLASH_ESCAPES it\n // fails loudly rather than silently matching wildcards.\n like: (column: Sql, pattern: Sql): Sql =>\n sql`${column} LIKE ${pattern} ESCAPE '\\\\\\\\'`,\n notLike: (column: Sql, pattern: Sql): Sql =>\n sql`${column} NOT LIKE ${pattern} ESCAPE '\\\\\\\\'`,\n ilike: (column: Sql, pattern: Sql): Sql =>\n sql`${asciiCaseFold(column)} LIKE ${asciiCaseFold(pattern)} ESCAPE '\\\\\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`${asciiCaseFold(column)} NOT LIKE ${asciiCaseFold(pattern)} ESCAPE '\\\\\\\\'`,\n containsText: (column: Sql, value: Sql): Sql =>\n sql`LOCATE(BINARY ${value}, BINARY ${column}) > 0`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value}`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`RIGHT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value}`,\n // Two conjuncts, because on MySQL no single predicate is both exact and\n // index-usable. The index stores the column's own collation's sort keys —\n // `utf8mb4_0900_ai_ci` on a default install, which is case- AND\n // accent-insensitive — so any comparison forced to BINARY cannot range on\n // it. Measured on MySQL 8 (Docker, 20k rows): `col LIKE 'x%'` is a `range`\n // over 111 rows, while both `col LIKE BINARY 'x%'` and the\n // `LEFT(BINARY col, …)` spelling above degrade to a full `index` scan of\n // all 19731 entries.\n //\n // So the collation-native LIKE goes first as an index accelerator, and the\n // BINARY predicate — byte-identical to `startsWithText` above — follows as\n // the semantics. The accelerator can never drop a row the BINARY conjunct\n // would keep: byte-equal strings compare equal under every collation, so a\n // binary prefix match implies the collation-native one. It is not a second\n // guard on the same invariant — it decides no row's membership, only which\n // rows the server has to look at.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n startsWithPrefix: (column: Sql, value: string): Sql =>\n sql`(${column} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\\\\\' AND LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value})`,\n\n // `startsWithPrefix`'s twin, for the same reason and in the same shape\n // (plan §10.2). `BINARY col` is a FUNCTION of the column, so MySQL cannot\n // range on it: measured on MySQL 8.4 over 20,000 rows in the collation\n // viborm's own DDL declares, `BINARY name = ?` planned `index` over 20,455\n // rows where `name = ?` planned `ref` over 1, and `BINARY name IN (…)`\n // planned `index` over 20,455 where `name IN (…)` planned `range` over 3.\n //\n // The collation-native conjunct is the accelerator and decides no row's\n // membership: byte-identical strings compare equal under every collation\n // of the charset, so the BINARY comparison IMPLIES it. On the tables\n // viborm creates (`utf8mb4_0900_bin`) the two conjuncts say the same\n // thing; on a table viborm did not create the BINARY one is what keeps the\n // case-sensitivity contract, and the same measurement shows the pair still\n // plans `ref` over 1 row there.\n //\n // `notIn` and `not` deliberately have no such pair. Their implication runs\n // the other way — `BINARY col NOT IN ('X')` KEEPS a row spelled `x` that\n // `col NOT IN ('X')` drops on a case-insensitive column, measured at\n // 20,000 rows against 19,999 — so a conjunct would remove rows. There is\n // also nothing to win: both spellings of `NOT IN` scan all 20,442 rows.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n exactTextEq: (column: Sql, value: Sql): Sql =>\n sql`(${column} = ${value} AND BINARY ${column} = ${value})`,\n exactTextIn: (column: Sql, values: Sql): Sql =>\n sql`(${column} IN ${values} AND BINARY ${column} IN ${values})`,\n\n ...createMembershipOperators(),\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n asciiCaseFold,\n caseSensitiveText: (expr: Sql): Sql => sql`BINARY ${expr}`,\n\n // String operations - MySQL uses CONCAT() function\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw`''`;\n if (parts.length === 1) return parts[0]!;\n return sql`CONCAT(${sql.join(parts, \", \")})`;\n },\n\n greatest: (...exprs: Sql[]): Sql => sql`GREATEST(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`LEAST(${sql.join(exprs, \", \")})`,\n\n // The expression form of `set.divide`'s integer arm: MySQL `/` yields a\n // DECIMAL quotient even for two integers, so the truncation is explicit.\n integerDivide: (left: Sql, right: Sql): Sql =>\n sql`TRUNCATE(${left} / ${right}, 0)`,\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n decimalCast(expr, descriptor.precision, descriptor.scale),\n\n // `CHAR` rather than `TEXT`: MySQL's CAST target list has no `TEXT`, which\n // is why `cast` below maps the generic text cast to `CHAR` too.\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`UNHEX(${expr})`\n : sql`CAST(${expr} AS CHAR)`,\n\n cast: createCastExpression({\n text: \"CHAR\",\n integer: \"SIGNED\",\n bigint: \"SIGNED\",\n boolean: \"UNSIGNED\",\n numeric: \"DECIMAL\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`LOWER(HEX(${expr}))`,\n };\n\n aggregates = {\n ...createAggregateFunctions(),\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n mysqlDecimalAverage(column, descriptor),\n\n // MySQL's widest exact DECIMAL cast operand. SUM itself can return more\n // than 65 digits; this bound belongs to exact HAVING operand lowering.\n decimalSumOperandPrecision:\n createDecimalSumOperandPrecision(MYSQL_EXACT_DIGITS),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql => sql`${left} = ${right}`,\n number: (expression: Sql): Sql => expression,\n boolean: (condition: Sql): Sql =>\n sql`JSON_EXTRACT(CASE WHEN ${condition} THEN 'true' ELSE 'false' END, '$')`,\n document: (expression: Sql): Sql => expression,\n\n object: mysqlJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`JSON_ARRAY()`;\n return sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw`JSON_ARRAY()`,\n\n agg: (expr: Sql): Sql =>\n sql`COALESCE(JSON_ARRAYAGG(${expr}), JSON_ARRAY())`,\n\n objectFromColumns: mysqlJsonObject,\n\n // buildJsonPath quotes/escapes key segments and maps integer segments\n // to array indices; '$' alone extracts the document root\n extract: (column: Sql, path: string[]): Sql =>\n sql`JSON_EXTRACT(${column}, ${buildJsonPath(path)})`,\n\n extractText: (column: Sql, path: string[]): Sql =>\n sql`JSON_UNQUOTE(JSON_EXTRACT(${column}, ${buildJsonPath(path)}))`,\n\n // JSON_TYPE spells numbers three ways depending on how the literal was\n // stored; anything else (including an absent path, where JSON_TYPE is\n // NULL) falls through the CASE to NULL\n numberAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) IN ('INTEGER', 'DOUBLE', 'DECIMAL') THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) AS DOUBLE) END)`;\n },\n\n // CAST(... AS BINARY) yields VARBINARY, so < / > compare bytes instead of\n // the column's (case- and accent-insensitive by default) collation\n stringAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) = 'STRING' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) AS BINARY) END)`;\n },\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`JSON_CONTAINS(${target}, ${value})`,\n\n lastElement: (target: Sql): Sql => sql`JSON_EXTRACT(${target}, '$[last]')`,\n\n // Comparing a JSON column to a plain string coerces the string to a JSON\n // string scalar (always-false for documents); CAST parses it as JSON\n value: (v: unknown): Sql => sql`CAST(${stringifyJson(v)} AS JSON)`,\n };\n\n arrays = {\n // MySQL uses JSON arrays\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`JSON_ARRAY()`;\n return sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n },\n\n value: mysqlJsonListValue,\n\n // Deliberately the same container, by identity: MySQL stores an enum LIST\n // as JSON like every other list, so its members are ordinary JSON strings\n // and there is no element type to spell. The inline `ENUM(...)` describes\n // one member.\n enumValue: mysqlJsonListValue,\n\n // JSON_CONTAINS requires a JSON document as candidate; a bare string\n // parameter throws ER_INVALID_JSON_TEXT. JSON_ARRAY keeps the parameter's\n // type (strings quoted, numbers not): [x] ⊆ column ⟺ x ∈ column\n has: (column: Sql, value: Sql): Sql =>\n sql`JSON_CONTAINS(${column}, JSON_ARRAY(${value}))`,\n\n hasEvery: (column: Sql, values: Sql): Sql =>\n sql`JSON_CONTAINS(${column}, ${values})`,\n\n hasSome: (column: Sql, values: Sql): Sql =>\n sql`JSON_OVERLAPS(${column}, ${values})`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(JSON_LENGTH(${column}) = 0 OR ${column} IS NULL)`,\n\n // The container as TEXT, so it reaches the decode as the exact bytes the\n // codec wrote: uncast, mysql2 parses a JSON column into a JavaScript\n // document and JSON_OBJECT nests it as a live array, and the coefficient\n // grammar would then be read off values a JSON parser already interpreted.\n exactNumericProjection: (column: Sql): Sql => sql`CAST(${column} AS CHAR)`,\n\n length: (column: Sql): Sql => sql`JSON_LENGTH(${column})`,\n\n get: (column: Sql, index: Sql): Sql =>\n sql`JSON_EXTRACT(${column}, CONCAT('$[', ${index}, ']'))`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`JSON_ARRAY_APPEND(${column}, '$', ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`JSON_SET(${column}, CONCAT('$[', ${index}, ']'), ${value})`,\n };\n\n orderBy = {\n ...createDirectionOrderBy(),\n // MySQL doesn't support NULLS FIRST/LAST natively - emulated\n ...createEmulatedNullsOrderBy(),\n };\n\n // mysql2's binary protocol binds JS numbers as DOUBLE, which MySQL rejects\n // in integer-only positions (\"Incorrect arguments to mysqld_stmt_execute\").\n // Inline integer LIMIT/OFFSET values instead of parameterizing them.\n clauses = {\n ...createStandardClauses(),\n limit: (count: Sql): Sql => sql`LIMIT ${inlineIntegerLiteral(count)}`,\n offset: (count: Sql): Sql => sql`OFFSET ${inlineIntegerLiteral(count)}`,\n };\n\n // JSON_MERGE_PRESERVE concatenates arrays element-wise; JSON_ARRAY_APPEND\n // would append the whole param as a single (stringified) element.\n set = {\n ...createNumericSetOperations(),\n\n increment: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalIncrement(column, by, target.decimal)\n : sql`${column} = ${column} + ${by}`,\n\n decrement: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalDecrement(column, by, target.decimal)\n : sql`${column} = ${column} - ${by}`,\n\n // A decimal target rounds the product back to the field's scale; every\n // other numeric column keeps MySQL's native multiplication.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalMultiply(column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n\n // MySQL `/` yields DECIMAL and rounds when assigned to an integer column.\n // Truncate explicitly so integer division matches PostgreSQL and SQLite.\n // A decimal target takes neither: `/` would round at\n // `div_precision_increment` digits, so the exact half-even quotient rule\n // decides the last digit instead.\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n if (target?.decimal) {\n return mysqlDecimalDivide(column, by, target.decimal);\n }\n return target?.integer\n ? sql`${column} = TRUNCATE(${column} / ${by}, 0)`\n : sql`${column} = ${column} / ${by}`;\n },\n\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = JSON_MERGE_PRESERVE(COALESCE(${column}, JSON_ARRAY()), ${values})`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = JSON_MERGE_PRESERVE(${values}, COALESCE(${column}, JSON_ARRAY()))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n // MySQL has no bare OFFSET; per the manual, use an all-ones LIMIT sentinel\n noLimitValue = sql.raw`18446744073709551615`;\n\n readonly #assemble = {\n select: (rawParts: QueryParts): Sql => {\n // Inline integer LIMIT/OFFSET (see clauses above for why)\n const parts: QueryParts = {\n ...rawParts,\n limit: rawParts.limit && inlineIntegerLiteral(rawParts.limit),\n offset: rawParts.offset && inlineIntegerLiteral(rawParts.offset),\n };\n\n // MySQL doesn't support DISTINCT ON natively\n // Simulate using ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)\n if (parts.distinct) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape,\n this.noLimitValue\n );\n }\n\n return assembleSelectQuery(sql`SELECT ${parts.columns}`, parts, {\n forUpdate: \"append\",\n noLimitValue: this.noLimitValue,\n });\n },\n };\n\n // MySQL 8.0+ common table expressions\n cte = createCteBuilders(quoteIdent);\n\n mutations = {\n skipDuplicatesStrategy: \"recoverableUniqueError\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql => sql`INSERT INTO ${table} () VALUES ()`,\n\n ...createMutationCommands(),\n\n // MySQL doesn't support RETURNING - returns empty\n // Use LAST_INSERT_ID() or SELECT after mutation\n returning: (_columns: Sql): Sql => sql.empty,\n\n // This low-level MySQL primitive ignores `_target`: ON DUPLICATE KEY UPDATE\n // fires on any unique collision. Public non-returning upserts therefore do\n // not execute this primitive; the query engine uses a locked, target-aware\n // branch so an unrelated unique collision still throws on every database.\n onConflict: (_target: Sql | null, action: Sql, _targetWhere?: Sql): Sql => {\n return sql`ON DUPLICATE KEY UPDATE ${action}`;\n },\n\n // MySQL doesn't need UPDATE SET prefix - onConflict already includes UPDATE\n onConflictUpdate: (sets: Sql, _setWhere?: Sql): Sql => sets,\n\n // A self-assignment reacts only to duplicate-key conflicts. Unlike\n // INSERT IGNORE, unrelated constraint and conversion failures still abort.\n //\n // It stays the JUNCTION insert's clause on MySQL as well, because\n // `ON DUPLICATE KEY UPDATE` cannot name a target (`onConflict` above says\n // so) — correct for every junction whose PK is its sole unique constraint,\n // which is every ordinary pair table. A polymorphic member table with a\n // SINGULAR inverse also carries a target-side UNIQUE that this clause would\n // swallow; the seam for that case is documented at `junctionDuplicateSkip`\n // in `query-engine/builders/many-to-many-utils.ts`.\n skipDuplicates: (duplicateNoopColumn: string) => {\n const column = sql.raw(quoteIdent(duplicateNoopColumn));\n return {\n prefix: sql.empty,\n suffix: sql`ON DUPLICATE KEY UPDATE ${column} = ${column}`,\n };\n },\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN EXISTS (${query}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \\`__viborm_assert__\\``,\n notExists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \\`__viborm_assert__\\``,\n // The refusal is an invalid path (3143), never the invalid text (3141)\n // a premise fails with.\n holds: (condition: Sql, from?: Sql): Sql =>\n sql`SELECT CASE WHEN ${condition} THEN 1 ELSE JSON_EXTRACT('{}', '__viborm_refused__') END AS \\`__viborm_judged__\\`${from ? sql` FROM ${from}` : sql``}`,\n };\n\n joins = {\n ...createCoreJoins(),\n\n // MySQL doesn't support FULL OUTER JOIN (would need a UNION of LEFT and\n // RIGHT joins). Never silently downgrade to LEFT JOIN: that drops rows.\n // The query engine never calls this today.\n full: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\n \"MySQL does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.\"\n );\n },\n\n // MySQL 8.0.14+ supports LATERAL\n ...createLateralJoins(quoteIdent),\n };\n\n setOperations = createSetOperations(quoteIdent);\n\n capabilities = {\n supportsReturning: false,\n supportsCteWithMutations: false, // MySQL CTEs are read-only\n supportsFullOuterJoin: false,\n supportsLateralJoins: true, // MySQL 8.0.14+\n supportsVector: false,\n supportsUpsertWhere: false, // ON DUPLICATE KEY UPDATE doesn't support WHERE clauses\n // ON DUPLICATE KEY UPDATE carries no conflict target and fires on ANY unique\n // collision — see the `onConflict` note above. A targeted upsert cannot be\n // spelled here, so the ON CONFLICT fold never opens on MySQL.\n supportsTargetedUpsert: false,\n // ERROR 1093: UPDATE/DELETE can't select from the mutated table in a\n // subquery. The engine wraps relation-filter subqueries in a derived\n // table when this is false (requires MySQL 8.0.14+ for outer references\n // in derived tables).\n supportsMutationTargetInSubquery: false,\n // MySQL's single-table UPDATE/DELETE take a native LIMIT, which is also the\n // only portable spelling here: the PK-subquery form would re-read the\n // mutated table and trip the same ERROR 1093 as above.\n supportsMutationRowLimit: true,\n supportsRowLocks: true,\n };\n\n lastInsertId = (): Sql => sql.raw`LAST_INSERT_ID()`;\n\n readonly #batchRefs = createMySqlBatchRefs({\n table: sql.raw`\\`__viborm_batch_refs\\``,\n batchIdColumn: sql.raw`\\`batch_id\\``,\n keyColumn: sql.raw`\\`ref_key\\``,\n valueColumn: sql.raw`\\`ref_value\\``,\n duplicateValue: sql.raw`VALUES(\\`ref_value\\`)`,\n createTable: sql.raw`CREATE TEMPORARY TABLE IF NOT EXISTS \\`__viborm_batch_refs\\` (\\`batch_id\\` VARCHAR(191) NOT NULL, \\`ref_key\\` VARCHAR(191) NOT NULL, \\`ref_value\\` TEXT, PRIMARY KEY (\\`batch_id\\`, \\`ref_key\\`))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS CHAR)`,\n lastInsertId: () => this.lastInsertId(),\n });\n\n vector = unsupportedVector;\n\n readonly geoPoint: GeoPointSql = (() => {\n const longitude = (point: Sql): Sql => sql`ST_Longitude(${point})`;\n const latitude = (point: Sql): Sql => sql`ST_Latitude(${point})`;\n return {\n // EPSG:4326 is latitude-longitude in MySQL's SRS catalog. The explicit\n // WKT option makes the two bound coordinates longitude-latitude instead.\n value: (pointLongitude, pointLatitude) =>\n sql`ST_GeomFromText(CONCAT('POINT(', ${pointLongitude}, ' ', ${pointLatitude}, ')'), 4326, 'axis-order=long-lat')`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators,\n (point, bounds) => {\n const polygons = geoBoundsIndexPolygons(bounds);\n if (polygons.length === 0) return;\n return this.operators.or(\n ...polygons.map(\n (polygon) =>\n sql`MBRIntersects(${point}, ST_GeomFromGeoJSON(${polygon}, 1, 4326))`\n )\n );\n }\n ),\n withinPolygon: (point, polygon) => {\n const geography = sql`ST_GeomFromGeoJSON(${geoPolygonJson(\n polygon\n )}, 1, 4326)`;\n return sql`ST_Intersects(${geography}, ${point})`;\n },\n distance: (left, right) =>\n sql`ST_Distance_Sphere(${left}, ${right}, ${GEO_POINT_EARTH_RADIUS_METERS})`,\n };\n })();\n\n // RESULT PARSING\n // MySQL: booleans and naive UTC datetimes - both ROW VALUES.\n // This adapter says nothing about a RESULT: the engine's decoder asks for\n // the alias `_count` and reads it back, and mysql2 preserves that alias\n // (Arnaud's D-40, measured live).\n // Relation carriers decode at the query-engine boundary that knows their\n // value is JSON, so the adapter never sniffs ordinary strings.\n result: AdapterResultParser = {\n // A MySQL SCALAR decimal is `DECIMAL(p,s)` and answers with exact text, so\n // `decimalRepresentation` stays at its default. A decimal LIST is JSON,\n // which has no exact decimal at all, so its members are stored and returned\n // as unscaled coefficient strings (plan 6.1). This adapter is the reason\n // the two are separate declarations.\n decimalListRepresentation: \"coefficient\",\n\n // Derived from the ONE storage owner, so the column the migration creates\n // and the value this reads back cannot be two decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"mysql\")?.representation ?? \"text\",\n\n // The contract's shape, deciding nothing on all 20 asks D-40 measured over\n // seven operations and both routes on live MySQL - the `count`/`exist` arm\n // was entered on 10 of them and answered `undefined` every time\n // (`g4/rulings/o2/receipts/leg-probe-mysql.log`). A RESULT is the\n // decoder's, and D-28's chain ends there.\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n\n parseField: (\n value: unknown,\n scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n // MySQL stores booleans as TINYINT(1) - 0/1\n if (scalarType === \"boolean\") {\n const parsed = parseIntegerBoolean(\n value === \"0\" ? 0 : value === \"1\" ? 1 : value\n );\n if (parsed !== undefined) {\n return next(parsed);\n }\n }\n // Datetime strings are naive UTC wall-clock; without this, the default\n // parser's new Date(str) would shift them by the process timezone\n if (scalarType === \"datetime\" && typeof value === \"string\") {\n const iso = naiveDateTimeToIso(value);\n if (iso !== undefined) {\n return next(iso);\n }\n }\n return next();\n },\n };\n}\n"],"mappings":"64BA4EA,MAAM,EAAa,GAAuB,IAAI,CACxC,EAAoB,MAAsC,UAAU,CAapE,EAAyC,CAQ7C,UAAW,EAAQ,IACjB,CAAG,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,oBAC1C,WAAY,EAAQ,IAAgB,CAAG,OAAO,EAAE,IAAI,EAAE,GACvD,CASK,wBAA2B,GAC/BA,EAAI,IAAI,IAAI,OAAO,EAAO,CAAC,CAEvB,GAAkB,CAAG,2HAErB,EAAyB,CAAG,yBAG5B,aAAe,EAAW,EAAmB,IACjD,CAAG,QAAQ,EAAK,MAAMA,EAAI,IAAI,WAAW,EAAU,GAAG,EAAM,GAAG,CAAC,GA0B5D,kBAAoB,EAAY,IAAuC,CAC3E,GAAM,CAAE,SAAU,EAClB,GAAI,IAAU,EAAG,OAAO,EACxB,IAAM,EAAS,EAAe,EAAM,CAC9B,EAAQ,CAAG,YAAY,EAAM,MAEnC,MAAO,EAAG,IAAI,EAAM,KAAK,EAAO,KAAK,YAAY,CAAG,IADnC,YAAY,CAAG,IAAI,EAAM,KAAK,EAAM,GAAI,EAAQ,EAAG,EA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B,0BAA2B,cAI3B,kBAAmB,EAAQ,IACzB,EAAY,EAAQ,EAAY,QAAQ,EAAE,gBAAkB,OAO9D,YAAa,EAEb,eACE,EACA,IACY,GAAM,CAEpB,YACE,EACA,EACA,IACY,CAEZ,GAAI,IAAe,UAAW,CAC5B,IAAM,EAAS,GACb,IAAU,IAAM,EAAI,IAAU,IAAM,EAAI,EACzC,CACD,GAAI,IAAW,IAAA,GACb,OAAO,EAAK,EAAO,CAKvB,GAAI,IAAe,YAAc,OAAO,GAAU,SAAU,CAC1D,IAAM,EAAM,mBAAmB,EAAM,CACrC,GAAI,IAAQ,IAAA,GACV,OAAO,EAAK,EAAI,CAGpB,OAAO,GAAM,EAEhB"}
|
package/dist/mysql2.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as Schema,
|
|
1
|
+
import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, On as DriverTransactionOptions, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, g as MigrationNamespaceAttestation, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-VsM29vYN.mjs";
|
|
2
2
|
import { Pool, PoolConnection, PoolOptions } from "mysql2/promise";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/mysql2/index.d.ts
|
package/dist/mysql2.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{c as t,o as n,s as r}from"./bind-parameter-capacity-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{c as t,o as n,s as r}from"./bind-parameter-capacity-qfEejeOX.mjs";import{i}from"./base-D3m1S7Uc.mjs";import{l as a,p as o}from"./error-mapping-C9WgitPi.mjs";import{p as s,r as c}from"./validation-BamBwne9.mjs";import{n as l}from"./transaction-4dfqals6.mjs";import{s as u}from"./execution-context-rJXTRVrJ.mjs";import{n as d}from"./client-6YgGlXzN.mjs";import{a as f,c as p,d as m,i as h,l as g,o as _,t as v}from"./driver-B9fIori_.mjs";import{t as y}from"./mysql-adapter-C6c5govr.mjs";import{Buffer as b}from"node:buffer";const x=/^(?:ssl|tls)/i;function tlsRefusal(e){return new c(e,{meta:{driver:`mysql2`,operation:`configuration`}})}function parseMySQLUrl(e){let t=new URL(e),n=decodeURIComponent(t.pathname.slice(1)),r={};for(let[e,n]of t.searchParams){if(x.test(e)&&e!==`ssl`&&e!==`sslmode`)throw tlsRefusal(`Unsupported MySQL TLS URL option; configure options.ssl explicitly.`);try{r[e]=JSON.parse(n)}catch{r[e]=n}}let i=t.searchParams.get(`sslmode`);if(i&&i!==`disable`){if(![`require`,`verify-ca`,`verify-full`].includes(i))throw tlsRefusal(`Unsupported MySQL sslmode; configure options.ssl explicitly.`);if(r.ssl!==void 0&&(r.ssl===null||typeof r.ssl!=`object`&&typeof r.ssl!=`string`))throw tlsRefusal(`MySQL sslmode requires a TLS configuration`);r.ssl??={}}Reflect.deleteProperty(r,`sslmode`);let a=decodeURIComponent(t.username),o=decodeURIComponent(t.password);return{host:t.hostname,...t.port?{port:Number.parseInt(t.port,10)}:{},...n===``?{}:{database:n},...a===``?{}:{user:a},...o===``?{}:{password:o},...r}}const S={pool:!0,options:!0,databaseUrl:!0,namespace:!0,migrationNamespaceAttestation:!0};function convertValuesForMySQL(e){return e.map(e=>e instanceof Uint8Array&&!b.isBuffer(e)?b.from(e.buffer,e.byteOffset,e.byteLength):e)}function isMultiStatementFields(e){return Array.isArray(e)&&e.every(e=>e===void 0||Array.isArray(e))}function malformedMySQL2Result(e,t){return new s(`Driver "mysql2" returned a malformed result for operation "${e}": ${t}.`,{meta:{driver:`mysql2`,operation:e}})}const C=/^-[1-9]\d*$/;function normalizeMySQL2InsertId(e,t){if(!(typeof e==`number`&&Number.isSafeInteger(e)&&e<0||typeof e==`string`&&C.test(e)))return r(e,t,{allowNumber:!0})}function toQueryResult(e,r,i){if(isMultiStatementFields(r))throw new s(`Driver "mysql2" returned multiple statement results for operation "${i}"; VibORM requires exactly one statement result.`,{meta:{driver:`mysql2`,operation:i}});if(Array.isArray(e)){if(!Array.isArray(r)||r.some(e=>!n(e)))throw malformedMySQL2Result(i,`row arrays require one flat field metadata array`);return{rows:e,rowCount:e.length}}if(r!==void 0)throw malformedMySQL2Result(i,`mutation results require undefined field metadata`);if(!n(e))throw malformedMySQL2Result(i,`expected a mutation result object`);let a={provider:`mysql2`,operation:i},o=normalizeMySQL2InsertId(e.insertId,a);return{rows:[],rowCount:t(e.affectedRows,a,{allowDecimalString:!0}),...o===void 0?{}:{insertId:o}}}function deriveMySQL2Namespace(e){if(e.suppliedPool)return;let t=e.connectionOptions.database;return t===``?void 0:t}function resolveMySQL2Configuration(e){let t=m(e),n=e.databaseUrl,r={...n?parseMySQL2ConfiguredUrl(n):void 0};for(let[t,n]of Object.entries(e.options??{}))n!==void 0&&Reflect.set(r,t,n);let i={suppliedPool:e.pool,connectionOptions:r};return{namespace:t??deriveMySQL2Namespace(i),...i}}function parseMySQL2ConfiguredUrl(e){try{return parseMySQLUrl(e)}catch(e){throw i(e)?e:new c(`Driver "mysql2" could not parse its databaseUrl.`,{cause:e instanceof Error?e:void 0})}}var MySQL2Driver=class extends v{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;constructor(e={}){let t=g(e),n=resolveMySQL2Configuration(e);if(super(`mysql`,`mysql2`,{},t),n.connectionOptions.multipleStatements===!0)throw new c(`Driver "mysql2" does not support options.multipleStatements=true because VibORM operations require one result per statement.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(n.connectionOptions.rowsAsArray===!0)throw new c(`Driver "mysql2" does not support options.rowsAsArray=true because VibORM requires row objects keyed by column name.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(n.connectionOptions.nestTables===!0||typeof n.connectionOptions.nestTables==`string`)throw new c(`Driver "mysql2" does not support enabled options.nestTables because VibORM requires flat row objects keyed by result aliases.`,{meta:{driver:`mysql2`,operation:`configuration`}});this.suppliedPool=n.suppliedPool,this.connectionOptions=n.connectionOptions,_(this,`adapter`,new y(n.namespace)),this.suppliedPool&&(this.client=this.suppliedPool)}async initClient(){if(this.suppliedPool!==void 0)return this.suppliedPool;let e=await import(`mysql2/promise`),t={timezone:`Z`,supportBigNumbers:!0,dateStrings:[`DATE`],...this.connectionOptions};return this.adapter.namespace!==void 0&&(t={...t,database:this.adapter.namespace}),e.createPool(t)}async closeClient(e){e!==this.suppliedPool&&await e.end()}async execute(e,t,n,r){let i=r?.operation??`execute`,[a,o]=await e.query({sql:t,values:convertValuesForMySQL(n),typeCast:(e,t)=>[`DATE`,`DATETIME`,`TIMESTAMP`,`LONGLONG`,`NEWDECIMAL`].includes(e.type)?e.string():t()});return toQueryResult(a,o,i)}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`,[a,o]=await e.query(t,n&&convertValuesForMySQL(n));return toQueryResult(a,o,i)}transactionOptionSupport(){return{isolationLevel:`pre-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(e,t,n,r){if(!(`getConnection`in e))throw a(this.driverName);let i=e,s=await h(()=>i.getConnection(),e=>e.release(),r?.maxWaitMs,{driverName:this.driverName,form:`callback`}),c=!1,runOrDestroy=async e=>{try{await e()}catch(e){throw c=!0,e}},d=r?.isolationLevel;return o({begin:()=>runOrDestroy(async()=>{d&&await s.query(f(d)),await s.beginTransaction()}),callback:()=>t(s),commit:()=>runOrDestroy(()=>s.commit()),rollback:()=>runOrDestroy(()=>s.rollback()),phases:u(n),close:()=>{try{if(c){s.destroy();return}s.release()}catch(e){throw super.transactionCleanupFailed(new l(`Driver "mysql2" could not release an unsafe transaction connection.`,{meta:{driver:`mysql2`,method:`$transaction`}})),e}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!(`getConnection`in e))throw a(this.driverName);let t=await e.getConnection();return{session:t,release:()=>(t.destroy(),Promise.resolve())}}};function createClient(e){p(e,`mysql2`,S);let{pool:t,options:n,databaseUrl:r}=e;return d(e,new MySQL2Driver({migrationNamespaceAttestation:g(e),namespace:m(e),pool:t,options:n,databaseUrl:r}))}export{MySQL2Driver,createClient};
|
|
2
2
|
//# sourceMappingURL=mysql2.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{n as e}from"./chunk-BuuaeEvq.mjs";const t=[`pg`,`mysql`,`sqlite`],isTaggedNativeType=e=>`db`in e;function nativeTypeFor(e,t){if(e!==void 0)return isTaggedNativeType(e)?e.db===t?e:void 0:e[t]}const fixed=e=>t=>({db:e,type:t}),n=fixed(`pg`),r=fixed(`mysql`),i=fixed(`sqlite`),sized=(e,t)=>n=>({db:e,type:`${t}(${n})`}),opt=(e,t)=>n=>({db:e,type:n===void 0?t:`${t}(${n})`}),a={STRING:{TEXT:n(`text`),VARCHAR:sized(`pg`,`varchar`),CHAR:sized(`pg`,`char`),CITEXT:n(`citext`),UUID:n(`uuid`),BIT:sized(`pg`,`bit`),VARBIT:e=>({db:`pg`,type:e?`varbit(${e})`:`varbit`}),XML:n(`xml`),INET:n(`inet`),CIDR:n(`cidr`),MACADDR:n(`macaddr`),MACADDR8:n(`macaddr8`),TSVECTOR:n(`tsvector`),TSQUERY:n(`tsquery`)},INT:{SMALLINT:n(`smallint`),INTEGER:n(`integer`),OID:n(`oid`)},BIGINT:{BIGINT:n(`bigint`)},FLOAT:{REAL:n(`real`),DOUBLE_PRECISION:n(`double precision`)},BOOLEAN:{BOOLEAN:n(`boolean`)},DATETIME:{TIMESTAMP:opt(`pg`,`timestamp`),TIMESTAMPTZ:opt(`pg`,`timestamptz`),DATE:n(`date`),TIME:opt(`pg`,`time`),TIMETZ:opt(`pg`,`timetz`)},JSON:{JSON:n(`json`),JSONB:n(`jsonb`)},BLOB:{BYTEA:n(`bytea`)}},o={STRING:{VARCHAR:sized(`mysql`,`VARCHAR`),CHAR:sized(`mysql`,`CHAR`),TEXT:r(`TEXT`),TINYTEXT:r(`TINYTEXT`),MEDIUMTEXT:r(`MEDIUMTEXT`),LONGTEXT:r(`LONGTEXT`),BIT:sized(`mysql`,`BIT`)},INT:{TINYINT:r(`TINYINT`),TINYINT_UNSIGNED:r(`TINYINT UNSIGNED`),SMALLINT:r(`SMALLINT`),SMALLINT_UNSIGNED:r(`SMALLINT UNSIGNED`),MEDIUMINT:r(`MEDIUMINT`),MEDIUMINT_UNSIGNED:r(`MEDIUMINT UNSIGNED`),INT:r(`INT`),INT_UNSIGNED:r(`INT UNSIGNED`),YEAR:r(`YEAR`)},BIGINT:{BIGINT:r(`BIGINT`),BIGINT_UNSIGNED:r(`BIGINT UNSIGNED`)},FLOAT:{FLOAT:r(`FLOAT`),DOUBLE:r(`DOUBLE`)},BOOLEAN:{TINYINT:r(`TINYINT(1)`)},DATETIME:{DATETIME:opt(`mysql`,`DATETIME`),TIMESTAMP:opt(`mysql`,`TIMESTAMP`),DATE:r(`DATE`),TIME:opt(`mysql`,`TIME`)},JSON:{JSON:r(`JSON`)},BLOB:{BLOB:r(`BLOB`),TINYBLOB:r(`TINYBLOB`),MEDIUMBLOB:r(`MEDIUMBLOB`),LONGBLOB:r(`LONGBLOB`),BINARY:sized(`mysql`,`BINARY`),VARBINARY:sized(`mysql`,`VARBINARY`)}},s={STRING:{TEXT:i(`TEXT`)},INT:{INTEGER:i(`INTEGER`)},BIGINT:{INTEGER:i(`INTEGER`)},FLOAT:{REAL:i(`REAL`)},BOOLEAN:{INTEGER:i(`INTEGER`)},DATETIME:{TEXT:i(`TEXT`),REAL:i(`REAL`),INTEGER:i(`INTEGER`)},JSON:{TEXT:i(`TEXT`)},BLOB:{BLOB:i(`BLOB`)}};export{isTaggedNativeType as a,s as i,t as n,nativeTypeFor as o,a as r,o as t};
|
|
2
|
-
//# sourceMappingURL=native-types-
|
|
2
|
+
//# sourceMappingURL=native-types-asNCr26n.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"native-types-veeTk36s.mjs","names":[],"sources":["../src/schema/scalars/native-types.ts"],"sourcesContent":["// Native Database Type Overrides\n// Provides typed constants for database-specific column types\n\n// =============================================================================\n// NATIVE TYPE INTERFACE\n// =============================================================================\n\nexport interface NativeType {\n readonly db: \"pg\" | \"mysql\" | \"sqlite\";\n readonly type: string;\n}\n\n/** The three dialects a native type can name. */\nexport type NativeDialect = NativeType[\"db\"];\n\n/**\n * A native type of ONE dialect — what every `PG` / `MYSQL` / `SQLITE` constant\n * is, parameterized ones included, so `PG.STRING.VARCHAR(80)` can fill a `pg`\n * entry of a {@link NativeTypeMap} and cannot fill a `mysql` one.\n */\nexport interface DialectNativeType<Dialect extends NativeDialect>\n extends NativeType {\n readonly db: Dialect;\n}\n\n/**\n * One scalar's native type on each dialect it names:\n * `s.string({ pg: PG.STRING.CITEXT, mysql: MYSQL.STRING.LONGTEXT })`.\n *\n * A dialect the map leaves out keeps that scalar's automatic column, exactly\n * as a tagged {@link NativeType} leaves every OTHER dialect's column alone.\n */\nexport interface NativeTypeMap {\n readonly pg?: DialectNativeType<\"pg\">;\n readonly mysql?: DialectNativeType<\"mysql\">;\n readonly sqlite?: DialectNativeType<\"sqlite\">;\n}\n\n/**\n * What a scalar factory's native-type argument declares: the tagged shorthand\n * (one dialect) or a {@link NativeTypeMap} (several). Scalars store the\n * declaration in the form it was written, so a schema document restates it\n * faithfully; every PHYSICAL reader asks {@link nativeTypeFor} instead of\n * inspecting the form.\n */\nexport type NativeTypeDeclaration = NativeType | NativeTypeMap;\n\n/** Every dialect, in the order a per-dialect question visits them. */\nexport const NATIVE_DIALECTS: readonly NativeDialect[] = [\n \"pg\",\n \"mysql\",\n \"sqlite\",\n];\n\n/** Whether a declaration is the tagged shorthand rather than a map. */\nexport const isTaggedNativeType = (\n declaration: NativeTypeDeclaration\n): declaration is NativeType => \"db\" in declaration;\n\n/**\n * The native type a declaration selects on one dialect, or `undefined` for the\n * dialect's automatic column.\n *\n * The ONE bound-dialect resolver. A migration driver, an adapter and the\n * identifier storage owner each know which dialect they speak and ask this;\n * none of them reads the declaration's form. A tagged shorthand for another\n * dialect is that dialect's automatic column, as it always was.\n */\nexport function nativeTypeFor(\n declaration: NativeTypeDeclaration | undefined,\n dialect: NativeDialect\n): NativeType | undefined {\n if (declaration === undefined) return undefined;\n if (isTaggedNativeType(declaration)) {\n return declaration.db === dialect ? declaration : undefined;\n }\n return declaration[dialect];\n}\n\n/**\n * A scalar factory's native-type argument: the tagged shorthand of dialect\n * `Db`, or the map `Given`, which the factory bounds by\n * {@link ExactNativeTypeMap}.\n *\n * The tagged shorthand keeps its historical shape: a `NativeType`, a union of\n * them, a generic `T extends NativeType`, a custom `type`, or one with unrelated\n * extra keys held in a variable all still compile, a fresh literal with an extra\n * key is still an excess-property error, and a value missing `db` or `type` is\n * still refused — except that a dialect key BESIDE its `db` is refused, since\n * that object would be two declarations at once.\n *\n * `Db` is inferred from a tagged value's `db` only so that TypeScript counts the\n * value as matched by this first member and keeps it out of `Given`: an\n * argument reaches `Given` only when it is not tagged, and `Given` is naked so\n * a union-typed argument (`NativeType | NativeTypeMap`) reaches it whole.\n */\nexport type NativeTypeArgument<Db extends NativeDialect, Given> =\n | (DialectNativeType<Db> & Partial<Record<NativeDialect, never>>)\n | Given;\n\n/**\n * The bound of a factory's `Given`: every key a dialect, each entry a native\n * type of its own key's dialect, and at least one dialect key. `{ type: \"text\" }`,\n * `{ postgres: … }`, `{}` and a `Date` are refused; an unknown key is refused\n * beside a real one, fresh and held in a variable. An argument that fails the\n * bound is refused against the bound itself, which is TypeScript's fallback.\n *\n * The exactness is a homomorphic mapped type, so it judges each member of a\n * union-typed map on its own. Measured traps (TS 7.0.2) that shaped it: a\n * generic CONSTRAINED to the weak `NativeTypeMap` falls back to that weak type\n * and admitted `{ foo: 1 }` and a `Date`; a parameter spelled `Given & NoInfer<…>`\n * makes TypeScript infer one member of a union argument; and a bound that is a\n * conditional type distributing over `Given` is a circular constraint (TS2313).\n * The at-least-one test is therefore not distributive: a union of maps with no\n * dialect key in COMMON is refused — annotate such a variable `NativeTypeMap`.\n */\nexport type ExactNativeTypeMap<Given> = {\n [Key in keyof Given]: Key extends NativeDialect\n ? DialectNativeType<Key>\n : never;\n} & ([keyof Given & NativeDialect] extends [never] ? never : unknown);\n\n// =============================================================================\n// CONSTANT BUILDERS\n// =============================================================================\n\n/** A fixed native type: its `db` and `type` keep their literal types. */\nconst fixed =\n <const Db extends NativeDialect>(db: Db) =>\n <const Type extends string>(type: Type) =>\n ({ db, type }) as const;\n\nconst pg = fixed(\"pg\");\nconst mysql = fixed(\"mysql\");\nconst sqlite = fixed(\"sqlite\");\n\n/** A type that takes one required size: `varchar(80)`. */\nconst sized =\n <Db extends NativeDialect>(db: Db, name: string) =>\n (n: number): DialectNativeType<Db> => ({ db, type: `${name}(${n})` });\n\n/** A type whose precision is optional: `timestamp` or `timestamp(3)`. */\nconst opt =\n <Db extends NativeDialect>(db: Db, name: string) =>\n (precision?: number): DialectNativeType<Db> => ({\n db,\n type: precision !== undefined ? `${name}(${precision})` : name,\n });\n\n// =============================================================================\n// POSTGRESQL NATIVE TYPES\n// https://www.prisma.io/docs/orm/reference/prisma-schema-reference#postgresql\n// =============================================================================\n\nexport const PG = {\n // String types\n STRING: {\n TEXT: pg(\"text\"),\n VARCHAR: sized(\"pg\", \"varchar\"),\n CHAR: sized(\"pg\", \"char\"),\n CITEXT: pg(\"citext\"),\n UUID: pg(\"uuid\"),\n BIT: sized(\"pg\", \"bit\"),\n // By hand: a zero size is the bare type here, not `varbit(0)`.\n VARBIT: (n?: number): DialectNativeType<\"pg\"> => ({\n db: \"pg\",\n type: n ? `varbit(${n})` : \"varbit\",\n }),\n XML: pg(\"xml\"),\n INET: pg(\"inet\"),\n CIDR: pg(\"cidr\"),\n MACADDR: pg(\"macaddr\"),\n MACADDR8: pg(\"macaddr8\"),\n TSVECTOR: pg(\"tsvector\"),\n TSQUERY: pg(\"tsquery\"),\n },\n\n // Integer types\n INT: {\n SMALLINT: pg(\"smallint\"),\n INTEGER: pg(\"integer\"),\n OID: pg(\"oid\"),\n },\n\n // BigInt types\n BIGINT: {\n BIGINT: pg(\"bigint\"),\n },\n\n // Float types\n FLOAT: {\n REAL: pg(\"real\"),\n DOUBLE_PRECISION: pg(\"double precision\"),\n },\n\n // Boolean types\n BOOLEAN: {\n BOOLEAN: pg(\"boolean\"),\n },\n\n // DateTime types\n DATETIME: {\n TIMESTAMP: opt(\"pg\", \"timestamp\"),\n TIMESTAMPTZ: opt(\"pg\", \"timestamptz\"),\n DATE: pg(\"date\"),\n TIME: opt(\"pg\", \"time\"),\n TIMETZ: opt(\"pg\", \"timetz\"),\n },\n\n // JSON types\n JSON: {\n JSON: pg(\"json\"),\n JSONB: pg(\"jsonb\"),\n },\n\n // Binary types\n BLOB: {\n BYTEA: pg(\"bytea\"),\n },\n} as const;\n\n// =============================================================================\n// MYSQL NATIVE TYPES\n// https://www.prisma.io/docs/orm/reference/prisma-schema-reference#mysql\n// =============================================================================\n\nexport const MYSQL = {\n // String types\n STRING: {\n VARCHAR: sized(\"mysql\", \"VARCHAR\"),\n CHAR: sized(\"mysql\", \"CHAR\"),\n TEXT: mysql(\"TEXT\"),\n TINYTEXT: mysql(\"TINYTEXT\"),\n MEDIUMTEXT: mysql(\"MEDIUMTEXT\"),\n LONGTEXT: mysql(\"LONGTEXT\"),\n BIT: sized(\"mysql\", \"BIT\"),\n },\n\n // Integer types\n INT: {\n TINYINT: mysql(\"TINYINT\"),\n TINYINT_UNSIGNED: mysql(\"TINYINT UNSIGNED\"),\n SMALLINT: mysql(\"SMALLINT\"),\n SMALLINT_UNSIGNED: mysql(\"SMALLINT UNSIGNED\"),\n MEDIUMINT: mysql(\"MEDIUMINT\"),\n MEDIUMINT_UNSIGNED: mysql(\"MEDIUMINT UNSIGNED\"),\n INT: mysql(\"INT\"),\n INT_UNSIGNED: mysql(\"INT UNSIGNED\"),\n YEAR: mysql(\"YEAR\"),\n },\n\n // BigInt types\n BIGINT: {\n BIGINT: mysql(\"BIGINT\"),\n BIGINT_UNSIGNED: mysql(\"BIGINT UNSIGNED\"),\n },\n\n // Float types\n FLOAT: {\n FLOAT: mysql(\"FLOAT\"),\n DOUBLE: mysql(\"DOUBLE\"),\n },\n\n // Boolean types (MySQL uses TINYINT(1))\n BOOLEAN: {\n TINYINT: mysql(\"TINYINT(1)\"),\n },\n\n // DateTime types\n DATETIME: {\n DATETIME: opt(\"mysql\", \"DATETIME\"),\n TIMESTAMP: opt(\"mysql\", \"TIMESTAMP\"),\n DATE: mysql(\"DATE\"),\n TIME: opt(\"mysql\", \"TIME\"),\n },\n\n // JSON types\n JSON: {\n JSON: mysql(\"JSON\"),\n },\n\n // Binary types\n BLOB: {\n BLOB: mysql(\"BLOB\"),\n TINYBLOB: mysql(\"TINYBLOB\"),\n MEDIUMBLOB: mysql(\"MEDIUMBLOB\"),\n LONGBLOB: mysql(\"LONGBLOB\"),\n BINARY: sized(\"mysql\", \"BINARY\"),\n VARBINARY: sized(\"mysql\", \"VARBINARY\"),\n },\n} as const;\n\n// =============================================================================\n// SQLITE NATIVE TYPES\n// https://www.prisma.io/docs/orm/reference/prisma-schema-reference#sqlite\n// SQLite has limited type affinity, but we expose common mappings\n// =============================================================================\n\nexport const SQLITE = {\n // String types (all map to TEXT)\n STRING: {\n TEXT: sqlite(\"TEXT\"),\n },\n\n // Integer types\n INT: {\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // BigInt types (same as INTEGER in SQLite)\n BIGINT: {\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // Float types\n FLOAT: {\n REAL: sqlite(\"REAL\"),\n },\n\n // Boolean types (stored as INTEGER 0/1)\n BOOLEAN: {\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // DateTime types (stored as TEXT, REAL, or INTEGER)\n DATETIME: {\n TEXT: sqlite(\"TEXT\"),\n REAL: sqlite(\"REAL\"),\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // JSON types (stored as TEXT)\n JSON: {\n TEXT: sqlite(\"TEXT\"),\n },\n\n // Binary types\n BLOB: {\n BL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3B,OAAQ,MAAM,QAAS,SAAS,CAChC,UAAW,MAAM,QAAS,YAAY,CACvC,CACF,CAQY,EAAS,CAEpB,OAAQ,CACN,KAAM,EAAO,OAAO,CACrB,CAGD,IAAK,CACH,QAAS,EAAO,UAAU,CAC3B,CAGD,OAAQ,CACN,QAAS,EAAO,UAAU,CAC3B,CAGD,MAAO,CACL,KAAM,EAAO,OAAO,CACrB,CAGD,QAAS,CACP,QAAS,EAAO,UAAU,CAC3B,CAGD,SAAU,CACR,KAAM,EAAO,OAAO,CACpB,KAAM,EAAO,OAAO,CACpB,QAAS,EAAO,UAAU,CAC3B,CAGD,KAAM,CACJ,KAAM,EAAO,OAAO,CACrB,CAGD,KAAM,CACJ,KAAM,EAAO,OAAO,CACrB,CACF"}
|
|
1
|
+
{"version":3,"file":"native-types-asNCr26n.mjs","names":[],"sources":["../src/schema/scalars/native-types.ts"],"sourcesContent":["// Native Database Type Overrides\n// Provides typed constants for database-specific column types\n\n// =============================================================================\n// NATIVE TYPE INTERFACE\n// =============================================================================\n\nexport interface NativeType {\n readonly db: \"pg\" | \"mysql\" | \"sqlite\";\n readonly type: string;\n}\n\n/** The three dialects a native type can name. */\nexport type NativeDialect = NativeType[\"db\"];\n\n/**\n * A native type of ONE dialect — what every `PG` / `MYSQL` / `SQLITE` constant\n * is, parameterized ones included, so `PG.STRING.VARCHAR(80)` can fill a `pg`\n * entry of a {@link NativeTypeMap} and cannot fill a `mysql` one.\n */\nexport interface DialectNativeType<Dialect extends NativeDialect>\n extends NativeType {\n readonly db: Dialect;\n}\n\n/**\n * One scalar's native type on each dialect it names:\n * `s.string({ pg: PG.STRING.CITEXT, mysql: MYSQL.STRING.LONGTEXT })`.\n *\n * A dialect the map leaves out keeps that scalar's automatic column, exactly\n * as a tagged {@link NativeType} leaves every OTHER dialect's column alone.\n */\nexport interface NativeTypeMap {\n readonly pg?: DialectNativeType<\"pg\">;\n readonly mysql?: DialectNativeType<\"mysql\">;\n readonly sqlite?: DialectNativeType<\"sqlite\">;\n}\n\n/**\n * What a scalar factory's native-type argument declares: the tagged shorthand\n * (one dialect) or a {@link NativeTypeMap} (several). Scalars store the\n * declaration in the form it was written, so a schema document restates it\n * faithfully; every PHYSICAL reader asks {@link nativeTypeFor} instead of\n * inspecting the form.\n */\nexport type NativeTypeDeclaration = NativeType | NativeTypeMap;\n\n/** Every dialect, in the order a per-dialect question visits them. */\nexport const NATIVE_DIALECTS: readonly NativeDialect[] = [\n \"pg\",\n \"mysql\",\n \"sqlite\",\n];\n\n/** Whether a declaration is the tagged shorthand rather than a map. */\nexport const isTaggedNativeType = (\n declaration: NativeTypeDeclaration\n): declaration is NativeType => \"db\" in declaration;\n\n/**\n * The native type a declaration selects on one dialect, or `undefined` for the\n * dialect's automatic column.\n *\n * The ONE bound-dialect resolver. A migration driver, an adapter and the\n * identifier storage owner each know which dialect they speak and ask this;\n * none of them reads the declaration's form. A tagged shorthand for another\n * dialect is that dialect's automatic column, as it always was.\n */\nexport function nativeTypeFor(\n declaration: NativeTypeDeclaration | undefined,\n dialect: NativeDialect\n): NativeType | undefined {\n if (declaration === undefined) return undefined;\n if (isTaggedNativeType(declaration)) {\n return declaration.db === dialect ? declaration : undefined;\n }\n return declaration[dialect];\n}\n\n/**\n * A scalar factory's native-type argument: the tagged shorthand of dialect\n * `Db`, or the map `Given`, which the factory bounds by\n * {@link ExactNativeTypeMap}.\n *\n * The tagged shorthand keeps its historical shape: a `NativeType`, a union of\n * them, a generic `T extends NativeType`, a custom `type`, or one with unrelated\n * extra keys held in a variable all still compile, a fresh literal with an extra\n * key is still an excess-property error, and a value missing `db` or `type` is\n * still refused — except that a dialect key BESIDE its `db` is refused, since\n * that object would be two declarations at once.\n *\n * `Db` is inferred from a tagged value's `db` only so that TypeScript counts the\n * value as matched by this first member and keeps it out of `Given`: an\n * argument reaches `Given` only when it is not tagged, and `Given` is naked so\n * a union-typed argument (`NativeType | NativeTypeMap`) reaches it whole.\n */\nexport type NativeTypeArgument<Db extends NativeDialect, Given> =\n | (DialectNativeType<Db> & Partial<Record<NativeDialect, never>>)\n | Given;\n\n/**\n * The bound of a factory's `Given`: every key a dialect, each entry a native\n * type of its own key's dialect, and at least one dialect key. `{ type: \"text\" }`,\n * `{ postgres: … }`, `{}` and a `Date` are refused; an unknown key is refused\n * beside a real one, fresh and held in a variable. An argument that fails the\n * bound is refused against the bound itself, which is TypeScript's fallback.\n *\n * The exactness is a homomorphic mapped type, so it judges each member of a\n * union-typed map on its own. Measured traps (TS 7.0.2) that shaped it: a\n * generic CONSTRAINED to the weak `NativeTypeMap` falls back to that weak type\n * and admitted `{ foo: 1 }` and a `Date`; a parameter spelled `Given & NoInfer<…>`\n * makes TypeScript infer one member of a union argument; and a bound that is a\n * conditional type distributing over `Given` is a circular constraint (TS2313).\n * The at-least-one test is therefore not distributive: a union of maps with no\n * dialect key in COMMON is refused — annotate such a variable `NativeTypeMap`.\n */\nexport type ExactNativeTypeMap<Given> = {\n [Key in keyof Given]: Key extends NativeDialect\n ? DialectNativeType<Key>\n : never;\n} & ([keyof Given & NativeDialect] extends [never] ? never : unknown);\n\n// =============================================================================\n// CONSTANT BUILDERS\n// =============================================================================\n\n/** A fixed native type: its `db` and `type` keep their literal types. */\nconst fixed =\n <const Db extends NativeDialect>(db: Db) =>\n <const Type extends string>(type: Type) =>\n ({ db, type }) as const;\n\nconst pg = fixed(\"pg\");\nconst mysql = fixed(\"mysql\");\nconst sqlite = fixed(\"sqlite\");\n\n/** A type that takes one required size: `varchar(80)`. */\nconst sized =\n <Db extends NativeDialect>(db: Db, name: string) =>\n (n: number): DialectNativeType<Db> => ({ db, type: `${name}(${n})` });\n\n/** A type whose precision is optional: `timestamp` or `timestamp(3)`. */\nconst opt =\n <Db extends NativeDialect>(db: Db, name: string) =>\n (precision?: number): DialectNativeType<Db> => ({\n db,\n type: precision !== undefined ? `${name}(${precision})` : name,\n });\n\n// =============================================================================\n// POSTGRESQL NATIVE TYPES\n// https://www.prisma.io/docs/orm/reference/prisma-schema-reference#postgresql\n// =============================================================================\n\nexport const PG = {\n // String types\n STRING: {\n TEXT: pg(\"text\"),\n VARCHAR: sized(\"pg\", \"varchar\"),\n CHAR: sized(\"pg\", \"char\"),\n CITEXT: pg(\"citext\"),\n UUID: pg(\"uuid\"),\n BIT: sized(\"pg\", \"bit\"),\n // By hand: a zero size is the bare type here, not `varbit(0)`.\n VARBIT: (n?: number): DialectNativeType<\"pg\"> => ({\n db: \"pg\",\n type: n ? `varbit(${n})` : \"varbit\",\n }),\n XML: pg(\"xml\"),\n INET: pg(\"inet\"),\n CIDR: pg(\"cidr\"),\n MACADDR: pg(\"macaddr\"),\n MACADDR8: pg(\"macaddr8\"),\n TSVECTOR: pg(\"tsvector\"),\n TSQUERY: pg(\"tsquery\"),\n },\n\n // Integer types\n INT: {\n SMALLINT: pg(\"smallint\"),\n INTEGER: pg(\"integer\"),\n OID: pg(\"oid\"),\n },\n\n // BigInt types\n BIGINT: {\n BIGINT: pg(\"bigint\"),\n },\n\n // Float types\n FLOAT: {\n REAL: pg(\"real\"),\n DOUBLE_PRECISION: pg(\"double precision\"),\n },\n\n // Boolean types\n BOOLEAN: {\n BOOLEAN: pg(\"boolean\"),\n },\n\n // DateTime types\n DATETIME: {\n TIMESTAMP: opt(\"pg\", \"timestamp\"),\n TIMESTAMPTZ: opt(\"pg\", \"timestamptz\"),\n DATE: pg(\"date\"),\n TIME: opt(\"pg\", \"time\"),\n TIMETZ: opt(\"pg\", \"timetz\"),\n },\n\n // JSON types\n JSON: {\n JSON: pg(\"json\"),\n JSONB: pg(\"jsonb\"),\n },\n\n // Binary types\n BLOB: {\n BYTEA: pg(\"bytea\"),\n },\n} as const;\n\n// =============================================================================\n// MYSQL NATIVE TYPES\n// https://www.prisma.io/docs/orm/reference/prisma-schema-reference#mysql\n// =============================================================================\n\nexport const MYSQL = {\n // String types\n STRING: {\n VARCHAR: sized(\"mysql\", \"VARCHAR\"),\n CHAR: sized(\"mysql\", \"CHAR\"),\n TEXT: mysql(\"TEXT\"),\n TINYTEXT: mysql(\"TINYTEXT\"),\n MEDIUMTEXT: mysql(\"MEDIUMTEXT\"),\n LONGTEXT: mysql(\"LONGTEXT\"),\n BIT: sized(\"mysql\", \"BIT\"),\n },\n\n // Integer types\n INT: {\n TINYINT: mysql(\"TINYINT\"),\n TINYINT_UNSIGNED: mysql(\"TINYINT UNSIGNED\"),\n SMALLINT: mysql(\"SMALLINT\"),\n SMALLINT_UNSIGNED: mysql(\"SMALLINT UNSIGNED\"),\n MEDIUMINT: mysql(\"MEDIUMINT\"),\n MEDIUMINT_UNSIGNED: mysql(\"MEDIUMINT UNSIGNED\"),\n INT: mysql(\"INT\"),\n INT_UNSIGNED: mysql(\"INT UNSIGNED\"),\n YEAR: mysql(\"YEAR\"),\n },\n\n // BigInt types\n BIGINT: {\n BIGINT: mysql(\"BIGINT\"),\n BIGINT_UNSIGNED: mysql(\"BIGINT UNSIGNED\"),\n },\n\n // Float types\n FLOAT: {\n FLOAT: mysql(\"FLOAT\"),\n DOUBLE: mysql(\"DOUBLE\"),\n },\n\n // Boolean types (MySQL uses TINYINT(1))\n BOOLEAN: {\n TINYINT: mysql(\"TINYINT(1)\"),\n },\n\n // DateTime types\n DATETIME: {\n DATETIME: opt(\"mysql\", \"DATETIME\"),\n TIMESTAMP: opt(\"mysql\", \"TIMESTAMP\"),\n DATE: mysql(\"DATE\"),\n TIME: opt(\"mysql\", \"TIME\"),\n },\n\n // JSON types\n JSON: {\n JSON: mysql(\"JSON\"),\n },\n\n // Binary types\n BLOB: {\n BLOB: mysql(\"BLOB\"),\n TINYBLOB: mysql(\"TINYBLOB\"),\n MEDIUMBLOB: mysql(\"MEDIUMBLOB\"),\n LONGBLOB: mysql(\"LONGBLOB\"),\n BINARY: sized(\"mysql\", \"BINARY\"),\n VARBINARY: sized(\"mysql\", \"VARBINARY\"),\n },\n} as const;\n\n// =============================================================================\n// SQLITE NATIVE TYPES\n// https://www.prisma.io/docs/orm/reference/prisma-schema-reference#sqlite\n// SQLite has limited type affinity, but we expose common mappings\n// =============================================================================\n\nexport const SQLITE = {\n // String types (all map to TEXT)\n STRING: {\n TEXT: sqlite(\"TEXT\"),\n },\n\n // Integer types\n INT: {\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // BigInt types (same as INTEGER in SQLite)\n BIGINT: {\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // Float types\n FLOAT: {\n REAL: sqlite(\"REAL\"),\n },\n\n // Boolean types (stored as INTEGER 0/1)\n BOOLEAN: {\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // DateTime types (stored as TEXT, REAL, or INTEGER)\n DATETIME: {\n TEXT: sqlite(\"TEXT\"),\n REAL: sqlite(\"REAL\"),\n INTEGER: sqlite(\"INTEGER\"),\n },\n\n // JSON types (stored as TEXT)\n JSON: {\n TEXT: sqlite(\"TEXT\"),\n },\n\n // Binary types\n BLOB: {\n BLOB: sqlite(\"BLOB\"),\n },\n} as const;\n"],"mappings":"yCAgDA,MAAa,EAA4C,CACvD,KACA,QACA,SACD,CAGY,mBACX,GAC8B,OAAQ,EAWxC,SAAgB,cACd,EACA,EACwB,CACpB,OAAgB,IAAA,GAIpB,OAHI,mBAAmB,EAAY,CAC1B,EAAY,KAAO,EAAU,EAAc,IAAA,GAE7C,EAAY,GAmDrB,MAAM,MAC6B,GACL,IACzB,CAAE,KAAI,OAAM,EAEX,EAAK,MAAM,KAAK,CAChB,EAAQ,MAAM,QAAQ,CACtB,EAAS,MAAM,SAAS,CAGxB,OACuB,EAAQ,IAClC,IAAsC,CAAE,KAAI,KAAM,GAAG,EAAK,GAAG,EAAE,GAAI,EAGhE,KACuB,EAAQ,IAClC,IAA+C,CAC9C,KACA,KAAM,IAAc,IAAA,GAAsC,EAA1B,GAAG,EAAK,GAAG,EAAU,GACtD,EAOU,EAAK,CAEhB,OAAQ,CACN,KAAM,EAAG,OAAO,CAChB,QAAS,MAAM,KAAM,UAAU,CAC/B,KAAM,MAAM,KAAM,OAAO,CACzB,OAAQ,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B,CAC/C,IAAK,EAAM,MAAM,CACjB,aAAc,EAAM,eAAe,CACnC,KAAM,EAAM,OAAO,CACpB,CAGD,OAAQ,CACN,OAAQ,EAAM,SAAS,CACvB,gBAAiB,EAAM,kBAAkB,CAC1C,CAGD,MAAO,CACL,MAAO,EAAM,QAAQ,CACrB,OAAQ,EAAM,SAAS,CACxB,CAGD,QAAS,CACP,QAAS,EAAM,aAAa,CAC7B,CAGD,SAAU,CACR,SAAU,IAAI,QAAS,WAAW,CAClC,UAAW,IAAI,QAAS,YAAY,CACpC,KAAM,EAAM,OAAO,CACnB,KAAM,IAAI,QAAS,OAAO,CAC3B,CAGD,KAAM,CACJ,KAAM,EAAM,OAAO,CACpB,CAGD,KAAM,CACJ,KAAM,EAAM,OAAO,CACnB,SAAU,EAAM,WAAW,CAC3B,WAAY,EAAM,aAAa,CAC/B,SAAU,EAAM,WAAW,CAC3B,OAAQ,MAAM,QAAS,SAAS,CAChC,UAAW,MAAM,QAAS,YAAY,CACvC,CACF,CAQY,EAAS,CAEpB,OAAQ,CACN,KAAM,EAAO,OAAO,CACrB,CAGD,IAAK,CACH,QAAS,EAAO,UAAU,CAC3B,CAGD,OAAQ,CACN,QAAS,EAAO,UAAU,CAC3B,CAGD,MAAO,CACL,KAAM,EAAO,OAAO,CACrB,CAGD,QAAS,CACP,QAAS,EAAO,UAAU,CAC3B,CAGD,SAAU,CACR,KAAM,EAAO,OAAO,CACpB,KAAM,EAAO,OAAO,CACpB,QAAS,EAAO,UAAU,CAC3B,CAGD,KAAM,CACJ,KAAM,EAAO,OAAO,CACrB,CAGD,KAAM,CACJ,KAAM,EAAO,OAAO,CACrB,CACF"}
|
package/dist/neon-http.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as Schema,
|
|
1
|
+
import { A as Schema, An as BatchQuery, At as DriverConfig, Dn as BatchTransactionOptions, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, jn as CommittedBatchNotification, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-VsM29vYN.mjs";
|
|
2
2
|
import { NeonQueryFunction } from "@neondatabase/serverless";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/neon-http/index.d.ts
|
|
@@ -11,6 +11,8 @@ interface NeonHTTPDriverOptions {
|
|
|
11
11
|
};
|
|
12
12
|
pgvector?: boolean;
|
|
13
13
|
postgis?: boolean;
|
|
14
|
+
/** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */
|
|
15
|
+
sharedRelationBodies?: boolean;
|
|
14
16
|
/** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */
|
|
15
17
|
namespace?: string;
|
|
16
18
|
}
|
package/dist/neon-http.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./bind-parameter-capacity-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./bind-parameter-capacity-qfEejeOX.mjs";import{m as n}from"./error-mapping-C9WgitPi.mjs";import{p as r,r as i}from"./validation-BamBwne9.mjs";import{n as a}from"./client-6YgGlXzN.mjs";import{c as o,d as s,t as c}from"./driver-B9fIori_.mjs";import{t as l}from"./postgres-result-KyBKBNJr.mjs";import{t as u}from"./postgres-adapter-CGthb5yh.mjs";const d={databaseUrl:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,namespace:!0};function malformedNeonResult(e,t){let n=e.operation??`execute`;return new r(`Driver "neon-http" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`neon-http`,...e,operation:n}})}function assertNeonFullResult(e,n){if(!(t(e)&&Array.isArray(e.fields))||typeof e.command!=`string`||!Object.hasOwn(e,`rowCount`)||e.rowCount!==null&&(typeof e.rowCount!=`number`||!Number.isFinite(e.rowCount)||!Number.isSafeInteger(e.rowCount)||e.rowCount<0)||!Array.isArray(e.rows)||!e.rows.every(t)||e.rowAsArray!==!1)throw malformedNeonResult(n,`expected fullResults object with object rows and explicit rowCount`)}var NeonHTTPDriver=class extends c{maxBindParametersPerStatement=65535;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;queryTypes;constructor(e={}){super(`postgresql`,`neon-http`);let t=s(e);this.driverOptions=e,u(this,t,e)}async initClient(){let{neon:e,types:t}=await import(`@neondatabase/serverless`);if(!this.driverOptions.databaseUrl)throw new i(`Neon HTTP driver requires a databaseUrl`,{meta:{driver:this.driverName}});let identityParser=e=>e,getTypeParser=((e,n)=>[1082,1114,1184,1115,1182,1185].includes(e)&&n!==`binary`?identityParser:t.getTypeParser(e,n));return this.queryTypes={getTypeParser},e(this.driverOptions.databaseUrl,{fetchOptions:this.driverOptions.options?.fetchOptions,authToken:this.driverOptions.options?.authToken,fullResults:!0,arrayMode:!1})}async closeClient(e){}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeQuery(e,t,n,r,i){let a=r??{operation:i},o=await e.query(t,n,{arrayMode:!1,fullResults:!0,types:this.queryTypes});return this.parseResult(o,a)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n??[],r,`executeRaw`)}transactionOptionSupport(){return{isolationLevel:`provider`,timeout:!1,timeoutReason:`Neon HTTP runs a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`Neon HTTP submits the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(n(this.driverName))}async executeBatch(e,t,n,r,i){let a=n??{operation:`executeBatch`},o=await e.transaction(t.map(t=>{let n=t.context??a;try{return e.query(t.sql,t.params??[],{types:this.queryTypes})}catch(e){throw this.normalizeStatementFailure(e,t.sql,this.getBatchDiagnosticParameters(t),n,!0)}}),{isolationLevel:i?.isolationLevel,arrayMode:!1,fullResults:!0});if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedNeonResult(a,`expected ${t.length} statement results but received ${e}`)}return o.map((e,n)=>this.parseResult(e,t[n]?.context??a))}parseResult(e,t){let n=t.operation??`execute`;return assertNeonFullResult(e,t),{rows:e.rows,rowCount:l(e.rowCount,e.command,e.rows,{provider:`neon-http`,operation:n,model:t.model,correlationId:t.correlationId})}}};function createClient(e){o(e,`neon-http`,d);let{databaseUrl:t,options:n,pgvector:r,postgis:i}=e,c=s(e);return a(e,new NeonHTTPDriver({databaseUrl:t,options:n,pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,namespace:c}))}export{NeonHTTPDriver,createClient};
|
|
2
2
|
//# sourceMappingURL=neon-http.mjs.map
|
package/dist/neon-http.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"neon-http.mjs","names":[],"sources":["../src/drivers/neon-http/index.ts"],"sourcesContent":["/**\n * Neon HTTP Driver\n *\n * Driver implementation for @neondatabase/serverless - Neon's HTTP-based PostgreSQL driver.\n *\n * Note: Neon's HTTP API uses non-interactive transactions. This means:\n * - Batch transactions ($transaction([...])) work via executeBatch\n * - Callback transactions ($transaction(async (tx) => {...})) are NOT supported\n * because Neon HTTP requires all queries to be submitted at once\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, QueryError } from \"@errors\";\nimport type {\n CustomTypesConfig,\n NeonQueryFunction,\n} from \"@neondatabase/serverless\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { isNormalizedResultRow } from \"../normalized-result\";\nimport {\n type BatchTransactionOptions,\n normalizePostgresRowCount,\n resolveNamespaceOption,\n type TransactionOptionSupport,\n unsupportedCallbackTransactionError,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type {\n BatchQuery,\n CommittedBatchNotification,\n QueryResult,\n} from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface NeonHTTPDriverOptions {\n databaseUrl?: string;\n options?: {\n fetchOptions?: RequestInit;\n authToken?: string | (() => Promise<string> | string);\n };\n pgvector?: boolean;\n postgis?: boolean;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type NeonHTTPClientConfig<C extends DriverConfig> =\n NeonHTTPDriverOptions & C;\n\nconst NEON_HTTP_CONFIG_KEYS: Record<keyof NeonHTTPDriverOptions, true> = {\n databaseUrl: true,\n options: true,\n pgvector: true,\n postgis: true,\n namespace: true,\n};\n\n// ============================================================\n// TYPE DECLARATIONS\n// ============================================================\n\n/**\n * NeonQuery is the main query function returned by neon().\n * Configured with arrayMode=false (object rows) and fullResults=true (includes rowCount).\n */\ntype NeonQuery = NeonQueryFunction<false, true>;\n\ninterface NeonFullResult<T> {\n fields: unknown[];\n command: string;\n rowCount: number | null;\n rows: T[];\n rowAsArray: false;\n}\n\nfunction malformedNeonResult(\n context: QueryExecutionContext,\n reason: string\n): QueryError {\n const operation = context.operation ?? \"execute\";\n return new QueryError(\n `Driver \"neon-http\" returned a malformed result payload for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"neon-http\", ...context, operation } }\n );\n}\n\nfunction assertNeonFullResult<T>(\n result: unknown,\n context: QueryExecutionContext\n): asserts result is NeonFullResult<T> {\n if (\n !(isNormalizedResultRow(result) && Array.isArray(result.fields)) ||\n typeof result.command !== \"string\" ||\n !Object.hasOwn(result, \"rowCount\") ||\n (result.rowCount !== null &&\n (typeof result.rowCount !== \"number\" ||\n !Number.isFinite(result.rowCount) ||\n !Number.isSafeInteger(result.rowCount) ||\n result.rowCount < 0)) ||\n !Array.isArray(result.rows) ||\n !result.rows.every(isNormalizedResultRow) ||\n result.rowAsArray !== false\n ) {\n throw malformedNeonResult(\n context,\n \"expected fullResults object with object rows and explicit rowCount\"\n );\n }\n}\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class NeonHTTPDriver extends Driver<NeonQuery, NeonQuery> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n // Neon HTTP only supports non-interactive (batch) transactions\n // Callback-style transactions are not supported\n readonly supportsTransactions = false;\n readonly supportsBatch = true;\n\n // Hosted rollback, durable visibility and malformed post-commit metadata\n // witnesses qualify this notification before driver result validation.\n readonly supportsOrderedCommittedSegments = true;\n\n private readonly driverOptions: NeonHTTPDriverOptions;\n private queryTypes: CustomTypesConfig | undefined;\n\n constructor(options: NeonHTTPDriverOptions = {}) {\n super(\"postgresql\", \"neon-http\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n\n installPostgresAdapter(this, namespace, options);\n }\n\n protected async initClient(): Promise<NeonQuery> {\n const { neon, types } = await import(\"@neondatabase/serverless\");\n\n if (!this.driverOptions.databaseUrl) {\n throw new ClientInitializationError(\n \"Neon HTTP driver requires a databaseUrl\",\n { meta: { driver: this.driverName } }\n );\n }\n\n // DATE (1082) / TIMESTAMP WITHOUT TIME ZONE (1114): the default parsers\n // build process-local Dates, shifting the stored value by the process\n // timezone. Return raw strings — the shared result parser builds UTC\n // Dates from them, matching every other driver.\n const identityParser = (value: string) => value;\n // pg-types declares getTypeParser with per-format overloads that a single\n // wrapper function can't express — the cast is unavoidable here\n const getTypeParser = ((oid: number, format?: string) => {\n if (\n [1082, 1114, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return types.getTypeParser(oid as never, format as never);\n }) as typeof types.getTypeParser;\n this.queryTypes = { getTypeParser };\n\n // Always use arrayMode=false (object rows) and fullResults=true (includes rowCount)\n const client = neon(this.driverOptions.databaseUrl, {\n fetchOptions: this.driverOptions.options?.fetchOptions,\n authToken: this.driverOptions.options?.authToken,\n fullResults: true,\n arrayMode: false,\n });\n\n return client;\n }\n\n protected async closeClient(_client: NeonQuery): Promise<void> {\n // HTTP client doesn't need to be closed\n }\n\n protected async execute<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery<T>(client, sql, params, context, \"execute\");\n }\n\n private async executeQuery<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[],\n context: QueryExecutionContext | undefined,\n fallbackOperation: string\n ): Promise<QueryResult<T>> {\n const executionContext = context ?? { operation: fallbackOperation };\n const result = await client.query(sql, params, {\n arrayMode: false,\n fullResults: true,\n types: this.queryTypes,\n });\n\n return this.parseResult<T>(result, executionContext);\n }\n\n protected async executeRaw<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery<T>(\n client,\n sql,\n params ?? [],\n context,\n \"executeRaw\"\n );\n }\n\n /**\n * Neon HTTP sends the whole batch as one request through `client.transaction`\n * and offers no callback transaction. The provider opens and closes that\n * transaction server-side in a single round trip. The SDK receives the\n * requested isolation level; timeout/maxWait need an interactive body or\n * acquired connection, which this HTTP transport does not have.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"provider\",\n timeout: false,\n timeoutReason:\n \"Neon HTTP runs a batch as one provider call with no interactive body to interrupt\",\n maxWait: \"unsupported\",\n maxWaitReason:\n \"Neon HTTP submits the batch immediately with no connection to acquire\",\n };\n }\n\n protected transaction<T>(\n _client: NeonQuery,\n _fn: (tx: NeonQuery) => Promise<T>\n ): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n\n /**\n * Execute multiple queries atomically using Neon's transaction() function.\n * This provides atomic batch execution with full PostgreSQL transaction semantics.\n */\n protected async executeBatch<T>(\n client: NeonQuery,\n queries: BatchQuery[],\n context?: QueryExecutionContext,\n committed?: CommittedBatchNotification,\n options?: BatchTransactionOptions\n ): Promise<QueryResult<T>[]> {\n const batchContext = context ?? { operation: \"executeBatch\" };\n // Query promises retain their own parser options in the public SDK API.\n const results: unknown = await client.transaction(\n queries.map((query) => {\n const statementContext = query.context ?? batchContext;\n try {\n return client.query(query.sql, query.params ?? [], {\n types: this.queryTypes,\n });\n } catch (error) {\n throw this.normalizeStatementFailure(\n error,\n query.sql,\n this.getBatchDiagnosticParameters(query),\n statementContext,\n true\n );\n }\n }),\n {\n isolationLevel: options?.isolationLevel,\n arrayMode: false,\n fullResults: true,\n }\n );\n await committed?.();\n\n if (!Array.isArray(results) || results.length !== queries.length) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw malformedNeonResult(\n batchContext,\n `expected ${queries.length} statement results but received ${actualResultCount}`\n );\n }\n\n return results.map((result, index) =>\n this.parseResult<T>(result, queries[index]?.context ?? batchContext)\n );\n }\n\n /**\n * Parse Neon result into QueryResult format.\n */\n private parseResult<T>(\n result: unknown,\n context: QueryExecutionContext\n ): QueryResult<T> {\n const operation = context.operation ?? \"execute\";\n assertNeonFullResult<T>(result, context);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n {\n provider: \"neon-http\",\n operation,\n model: context.model,\n correlationId: context.correlationId,\n }\n ),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: NeonHTTPClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, NeonHTTPDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: NeonHTTPDriver }\n >]: LinkedClientConfig<C & { driver: NeonHTTPDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"neon-http\", NEON_HTTP_CONFIG_KEYS);\n const { databaseUrl, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new NeonHTTPDriver({\n databaseUrl,\n options,\n pgvector,\n postgis,\n namespace,\n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,CACE,eAAgB,GAAS,eACzB,UAAW,GACX,YAAa,GACd,CACF,CAGD,GAFA,MAAM,KAAa,CAEf,CAAC,MAAM,QAAQ,EAAQ,EAAI,EAAQ,SAAW,EAAQ,OAAQ,CAChE,IAAM,EAAoB,MAAM,QAAQ,EAAQ,CAAG,EAAQ,OAAS,EACpE,MAAM,oBACJ,EACA,YAAY,EAAQ,OAAO,kCAAkC,IAC9D,CAGH,OAAO,EAAQ,KAAK,EAAQ,IAC1B,KAAK,YAAe,EAAQ,EAAQ,IAAQ,SAAW,EAAa,CACrE,CAMH,YACE,EACA,EACgB,CAChB,IAAM,EAAY,EAAQ,WAAa,UAEvC,OADA,qBAAwB,EAAQ,EAAQ,CACjC,CACL,KAAM,EAAO,KACb,SAAU,EACR,EAAO,SACP,EAAO,QACP,EAAO,KACP,CACE,SAAU,YACV,YACA,MAAO,EAAQ,MACf,cAAe,EAAQ,cACxB,CACF,CACF,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,YAAa,EAAsB,CACzE,GAAM,CAAE,cAAa,UAAS,WAAU,WAAY,EAWpD,OAAO,EAAmD,EAR3C,IAAI,eAAe,CAChC,cACA,UACA,WACA,UACA,UAPgB,EAAuB,EAAO,CAQ/C,CAAC,CAEuE"}
|
|
1
|
+
{"version":3,"file":"neon-http.mjs","names":[],"sources":["../src/drivers/neon-http/index.ts"],"sourcesContent":["/**\n * Neon HTTP Driver\n *\n * Driver implementation for @neondatabase/serverless - Neon's HTTP-based PostgreSQL driver.\n *\n * Note: Neon's HTTP API uses non-interactive transactions. This means:\n * - Batch transactions ($transaction([...])) work via executeBatch\n * - Callback transactions ($transaction(async (tx) => {...})) are NOT supported\n * because Neon HTTP requires all queries to be submitted at once\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, QueryError } from \"@errors\";\nimport type {\n CustomTypesConfig,\n NeonQueryFunction,\n} from \"@neondatabase/serverless\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { isNormalizedResultRow } from \"../normalized-result\";\nimport {\n type BatchTransactionOptions,\n normalizePostgresRowCount,\n resolveNamespaceOption,\n type TransactionOptionSupport,\n unsupportedCallbackTransactionError,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type {\n BatchQuery,\n CommittedBatchNotification,\n QueryResult,\n} from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface NeonHTTPDriverOptions {\n databaseUrl?: string;\n options?: {\n fetchOptions?: RequestInit;\n authToken?: string | (() => Promise<string> | string);\n };\n pgvector?: boolean;\n postgis?: boolean;\n /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type NeonHTTPClientConfig<C extends DriverConfig> =\n NeonHTTPDriverOptions & C;\n\nconst NEON_HTTP_CONFIG_KEYS: Record<keyof NeonHTTPDriverOptions, true> = {\n databaseUrl: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n namespace: true,\n};\n\n// ============================================================\n// TYPE DECLARATIONS\n// ============================================================\n\n/**\n * NeonQuery is the main query function returned by neon().\n * Configured with arrayMode=false (object rows) and fullResults=true (includes rowCount).\n */\ntype NeonQuery = NeonQueryFunction<false, true>;\n\ninterface NeonFullResult<T> {\n fields: unknown[];\n command: string;\n rowCount: number | null;\n rows: T[];\n rowAsArray: false;\n}\n\nfunction malformedNeonResult(\n context: QueryExecutionContext,\n reason: string\n): QueryError {\n const operation = context.operation ?? \"execute\";\n return new QueryError(\n `Driver \"neon-http\" returned a malformed result payload for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"neon-http\", ...context, operation } }\n );\n}\n\nfunction assertNeonFullResult<T>(\n result: unknown,\n context: QueryExecutionContext\n): asserts result is NeonFullResult<T> {\n if (\n !(isNormalizedResultRow(result) && Array.isArray(result.fields)) ||\n typeof result.command !== \"string\" ||\n !Object.hasOwn(result, \"rowCount\") ||\n (result.rowCount !== null &&\n (typeof result.rowCount !== \"number\" ||\n !Number.isFinite(result.rowCount) ||\n !Number.isSafeInteger(result.rowCount) ||\n result.rowCount < 0)) ||\n !Array.isArray(result.rows) ||\n !result.rows.every(isNormalizedResultRow) ||\n result.rowAsArray !== false\n ) {\n throw malformedNeonResult(\n context,\n \"expected fullResults object with object rows and explicit rowCount\"\n );\n }\n}\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class NeonHTTPDriver extends Driver<NeonQuery, NeonQuery> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n // Neon HTTP only supports non-interactive (batch) transactions\n // Callback-style transactions are not supported\n readonly supportsTransactions = false;\n readonly supportsBatch = true;\n\n // Hosted rollback, durable visibility and malformed post-commit metadata\n // witnesses qualify this notification before driver result validation.\n readonly supportsOrderedCommittedSegments = true;\n\n private readonly driverOptions: NeonHTTPDriverOptions;\n private queryTypes: CustomTypesConfig | undefined;\n\n constructor(options: NeonHTTPDriverOptions = {}) {\n super(\"postgresql\", \"neon-http\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n\n installPostgresAdapter(this, namespace, options);\n }\n\n protected async initClient(): Promise<NeonQuery> {\n const { neon, types } = await import(\"@neondatabase/serverless\");\n\n if (!this.driverOptions.databaseUrl) {\n throw new ClientInitializationError(\n \"Neon HTTP driver requires a databaseUrl\",\n { meta: { driver: this.driverName } }\n );\n }\n\n // DATE (1082) / TIMESTAMP WITHOUT TIME ZONE (1114): the default parsers\n // build process-local Dates, shifting the stored value by the process\n // timezone. Return raw strings — the shared result parser builds UTC\n // Dates from them, matching every other driver.\n const identityParser = (value: string) => value;\n // pg-types declares getTypeParser with per-format overloads that a single\n // wrapper function can't express — the cast is unavoidable here\n const getTypeParser = ((oid: number, format?: string) => {\n if (\n [1082, 1114, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return types.getTypeParser(oid as never, format as never);\n }) as typeof types.getTypeParser;\n this.queryTypes = { getTypeParser };\n\n // Always use arrayMode=false (object rows) and fullResults=true (includes rowCount)\n const client = neon(this.driverOptions.databaseUrl, {\n fetchOptions: this.driverOptions.options?.fetchOptions,\n authToken: this.driverOptions.options?.authToken,\n fullResults: true,\n arrayMode: false,\n });\n\n return client;\n }\n\n protected async closeClient(_client: NeonQuery): Promise<void> {\n // HTTP client doesn't need to be closed\n }\n\n protected async execute<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery<T>(client, sql, params, context, \"execute\");\n }\n\n private async executeQuery<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[],\n context: QueryExecutionContext | undefined,\n fallbackOperation: string\n ): Promise<QueryResult<T>> {\n const executionContext = context ?? { operation: fallbackOperation };\n const result = await client.query(sql, params, {\n arrayMode: false,\n fullResults: true,\n types: this.queryTypes,\n });\n\n return this.parseResult<T>(result, executionContext);\n }\n\n protected async executeRaw<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery<T>(\n client,\n sql,\n params ?? [],\n context,\n \"executeRaw\"\n );\n }\n\n /**\n * Neon HTTP sends the whole batch as one request through `client.transaction`\n * and offers no callback transaction. The provider opens and closes that\n * transaction server-side in a single round trip. The SDK receives the\n * requested isolation level; timeout/maxWait need an interactive body or\n * acquired connection, which this HTTP transport does not have.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"provider\",\n timeout: false,\n timeoutReason:\n \"Neon HTTP runs a batch as one provider call with no interactive body to interrupt\",\n maxWait: \"unsupported\",\n maxWaitReason:\n \"Neon HTTP submits the batch immediately with no connection to acquire\",\n };\n }\n\n protected transaction<T>(\n _client: NeonQuery,\n _fn: (tx: NeonQuery) => Promise<T>\n ): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n\n /**\n * Execute multiple queries atomically using Neon's transaction() function.\n * This provides atomic batch execution with full PostgreSQL transaction semantics.\n */\n protected async executeBatch<T>(\n client: NeonQuery,\n queries: BatchQuery[],\n context?: QueryExecutionContext,\n committed?: CommittedBatchNotification,\n options?: BatchTransactionOptions\n ): Promise<QueryResult<T>[]> {\n const batchContext = context ?? { operation: \"executeBatch\" };\n // Query promises retain their own parser options in the public SDK API.\n const results: unknown = await client.transaction(\n queries.map((query) => {\n const statementContext = query.context ?? batchContext;\n try {\n return client.query(query.sql, query.params ?? [], {\n types: this.queryTypes,\n });\n } catch (error) {\n throw this.normalizeStatementFailure(\n error,\n query.sql,\n this.getBatchDiagnosticParameters(query),\n statementContext,\n true\n );\n }\n }),\n {\n isolationLevel: options?.isolationLevel,\n arrayMode: false,\n fullResults: true,\n }\n );\n await committed?.();\n\n if (!Array.isArray(results) || results.length !== queries.length) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw malformedNeonResult(\n batchContext,\n `expected ${queries.length} statement results but received ${actualResultCount}`\n );\n }\n\n return results.map((result, index) =>\n this.parseResult<T>(result, queries[index]?.context ?? batchContext)\n );\n }\n\n /**\n * Parse Neon result into QueryResult format.\n */\n private parseResult<T>(\n result: unknown,\n context: QueryExecutionContext\n ): QueryResult<T> {\n const operation = context.operation ?? \"execute\";\n assertNeonFullResult<T>(result, context);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n {\n provider: \"neon-http\",\n operation,\n model: context.model,\n correlationId: context.correlationId,\n }\n ),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: NeonHTTPClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, NeonHTTPDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: NeonHTTPDriver }\n >]: LinkedClientConfig<C & { driver: NeonHTTPDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"neon-http\", NEON_HTTP_CONFIG_KEYS);\n const { databaseUrl, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new NeonHTTPDriver({\n databaseUrl,\n options,\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, NeonHTTPDriver>(config, driver);\n}\n"],"mappings":"mZA+DA,MAAM,EAAmE,CACvE,YAAa,GACb,QAAS,GACT,SAAU,GACV,QAAS,GACT,qBAAsB,GACtB,UAAW,GACZ,CAoBD,SAAS,oBACP,EACA,EACY,CACZ,IAAM,EAAY,EAAQ,WAAa,UACvC,OAAO,IAAI,EACT,yEAAyE,EAAU,KAAK,EAAO,GAC/F,CAAE,KAAM,CAAE,OAAQ,YAAa,GAAG,EAAS,YAAW,CAAE,CACzD,CAGH,SAAS,qBACP,EACA,EACqC,CACrC,GACE,EAAE,EAAsB,EAAO,EAAI,MAAM,QAAQ,EAAO,OAAO,GAC/D,OAAO,EAAO,SAAY,UAC1B,CAAC,OAAO,OAAO,EAAQ,WAAW,EACjC,EAAO,WAAa,OAClB,OAAO,EAAO,UAAa,UAC1B,CAAC,OAAO,SAAS,EAAO,SAAS,EACjC,CAAC,OAAO,cAAc,EAAO,SAAS,EACtC,EAAO,SAAW,IACtB,CAAC,MAAM,QAAQ,EAAO,KAAK,EAC3B,CAAC,EAAO,KAAK,MAAM,EAAsB,EACzC,EAAO,aAAe,GAEtB,MAAM,oBACJ,EACA,qEACD,CAQL,IAAa,eAAb,c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A,WACA,UACA,qBAAsB,EAAO,qBAC7B,YACD,CAAC,CAEuE"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-
|
|
2
|
-
//# sourceMappingURL=object-store-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-D3m1S7Uc.mjs";import{t as n}from"./migrations-Bn1SatyB.mjs";import{n as r}from"./canonical-json-BReb5nFO.mjs";import{a as i}from"./identity-oQvIe7u8.mjs";function refuseWorkersKvWritable(){throw new n(`Workers KV cannot be a V1 estate writer: listing is eventually consistent and puts are not conditional`,t.MIGRATION_UNSUPPORTED_PROVIDER)}var ObjectStoreEstateStorage=class{store;constructor(e){this.store=e}async readEstate(){return this.store.get(`estate.json`)}async listStates(){return this.listHex(`states/`,`.json`)}async listSnapshots(){return this.listHex(`snapshots/`,`.json`)}async listSql(){return this.listHex(`sql/`,`.sql`)}async readState(e){return this.store.get(`states/${e}.json`)}async readSnapshot(e){return this.store.get(`snapshots/${e}.json`)}async readSql(e){return this.store.get(`sql/${e}.sql`)}async publishEstate(e){return this.publish(`estate.json`,e)}async publishSnapshot(e,t){return this.publish(`snapshots/${e}.json`,t)}async publishSql(e,t){return this.publish(`sql/${e}.sql`,t)}async publishState(e,r){if(!i(e))throw new n(`State id is not a SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return this.publish(`states/${e}.json`,r)}async publish(e,i){if(await this.store.putIfAbsent(e,i)===`created`)return{outcome:`created`};let a=await this.store.get(e);if(!(a&&r(a,i)))throw new n(`Object-store key ${e} already holds different bytes`,t.MIGRATION_CORRUPTION);return{outcome:`identical`}}async listHex(e,t){let n=await this.store.list(e),r=[];for(let a of n){let n=a.slice(e.length);if(!n.endsWith(t))continue;let o=n.slice(0,-t.length);i(o)&&r.push(o)}return r.sort()}},MemoryConditionalObjectStore=class{objects=new Map;async putIfAbsent(e,t){return this.objects.has(e)?`exists`:(this.objects.set(e,t.slice()),`created`)}async get(e){let t=this.objects.get(e);return t?t.slice():null}async list(e){return[...this.objects.keys()].filter(t=>t.startsWith(e)).sort()}};export{ObjectStoreEstateStorage as n,refuseWorkersKvWritable as r,MemoryConditionalObjectStore as t};
|
|
2
|
+
//# sourceMappingURL=object-store-ChYHlOMD.mjs.map
|