viborm 1.5.1 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/{adapter-internals-Dagucesf.mjs → adapter-internals-DULbfdmQ.mjs} +1 -1
- package/dist/{adapter-internals-Dagucesf.mjs.map → adapter-internals-DULbfdmQ.mjs.map} +1 -1
- package/dist/{adapter-namespace-DuugUuQa.mjs → adapter-namespace-CFtC8LbT.mjs} +2 -2
- package/dist/{adapter-namespace-DuugUuQa.mjs.map → adapter-namespace-CFtC8LbT.mjs.map} +1 -1
- package/dist/{adapter-result-parser-B63ouFIz.mjs → adapter-result-parser-C0vW9am8.mjs} +1 -1
- package/dist/{adapter-result-parser-B63ouFIz.mjs.map → adapter-result-parser-C0vW9am8.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-BU1R9byi.mjs → array-literal-Dohoq5rT.mjs} +1 -1
- package/dist/{array-literal-BU1R9byi.mjs.map → array-literal-Dohoq5rT.mjs.map} +1 -1
- package/dist/{batch-refs-C3MTcVre.mjs → batch-refs-cBYAKzaE.mjs} +2 -2
- package/dist/{batch-refs-C3MTcVre.mjs.map → batch-refs-cBYAKzaE.mjs.map} +1 -1
- package/dist/bind-parameter-capacity-4OU6feZG.mjs +2 -0
- package/dist/{bind-parameter-capacity-faPOSaLz.mjs.map → bind-parameter-capacity-4OU6feZG.mjs.map} +1 -1
- package/dist/{builder-ClblW6Lj.mjs → builder-D0GQK-fA.mjs} +2 -2
- package/dist/{builder-ClblW6Lj.mjs.map → builder-D0GQK-fA.mjs.map} +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/bun-sqlite.mjs.map +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/{canonical-json-JLUMrnoq.mjs → canonical-json-D_FgOt4S.mjs} +1 -1
- package/dist/{canonical-json-JLUMrnoq.mjs.map → canonical-json-D_FgOt4S.mjs.map} +1 -1
- package/dist/chain-BQoDfo80.mjs +2 -0
- package/dist/{chain-C1VPkUpC.mjs.map → chain-BQoDfo80.mjs.map} +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/{client-C1MxqFtt.mjs → client-BCcIdDl8.mjs} +4 -4
- package/dist/client-BCcIdDl8.mjs.map +1 -0
- package/dist/client-BqgVSbk0.mjs +2 -0
- package/dist/client-BqgVSbk0.mjs.map +1 -0
- package/dist/{client-DyIsSin0.d.mts → client-C5BGyg5n.d.mts} +3 -3
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{clock-CK41KO7t.mjs → clock-QtW83Dcm.mjs} +1 -1
- package/dist/{clock-CK41KO7t.mjs.map → clock-QtW83Dcm.mjs.map} +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/{current-CKQ4EgeM.mjs → current-CEWlNJcP.mjs} +1 -1
- package/dist/{current-CKQ4EgeM.mjs.map → current-CEWlNJcP.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-DfVmz14E.mjs → datetime-physical-codec-Bl6M6vF5.mjs} +2 -2
- package/dist/{datetime-physical-codec-DfVmz14E.mjs.map → datetime-physical-codec-Bl6M6vF5.mjs.map} +1 -1
- package/dist/{driver-DpQbSOUD.mjs → driver-Dv2GJyGs.mjs} +2 -2
- package/dist/{driver-DpQbSOUD.mjs.map → driver-Dv2GJyGs.mjs.map} +1 -1
- package/dist/driver-szWYBmjD.mjs +2 -0
- package/dist/{driver-aqfbJdZC.mjs.map → driver-szWYBmjD.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-DRY49A3C.mjs +2 -0
- package/dist/error-mapping-DRY49A3C.mjs.map +1 -0
- package/dist/every-DIG9CPly.mjs +2 -0
- package/dist/{every-BUf842ai.mjs.map → every-DIG9CPly.mjs.map} +1 -1
- package/dist/{fs-estate-BXNX7l62.mjs → fs-estate-DNCM7hYC.mjs} +2 -2
- package/dist/{fs-estate-BXNX7l62.mjs.map → fs-estate-DNCM7hYC.mjs.map} +1 -1
- package/dist/{geo-area-codec-DQpSEgSD.mjs → geo-area-codec-H50rrGiF.mjs} +2 -2
- package/dist/{geo-area-codec-DQpSEgSD.mjs.map → geo-area-codec-H50rrGiF.mjs.map} +1 -1
- package/dist/geo-point-codec-mjROsQX-.mjs +2 -0
- package/dist/{geo-point-codec-DcUTvoEg.mjs.map → geo-point-codec-mjROsQX-.mjs.map} +1 -1
- package/dist/{hydration-BK6vRndL.mjs → hydration-BQ7tYLtA.mjs} +2 -2
- package/dist/{hydration-BK6vRndL.mjs.map → hydration-BQ7tYLtA.mjs.map} +1 -1
- package/dist/{identifier-conversion-8ldidfgu.mjs → identifier-conversion-DV63mwKG.mjs} +2 -2
- package/dist/{identifier-conversion-8ldidfgu.mjs.map → identifier-conversion-DV63mwKG.mjs.map} +1 -1
- package/dist/{identity-Bu6jbgym.mjs → identity-B75EaVTM.mjs} +2 -2
- package/dist/{identity-Bu6jbgym.mjs.map → identity-B75EaVTM.mjs.map} +1 -1
- package/dist/{index-Ci8b13Lm.d.mts → index-DRX_LLQM.d.mts} +47 -8
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{invariant-BnLYqsHO.mjs → invariant-B5znICP_.mjs} +1 -1
- package/dist/{invariant-BnLYqsHO.mjs.map → invariant-B5znICP_.mjs.map} +1 -1
- package/dist/{json-number-CAfNAqDB.mjs → json-number-DoseUwuo.mjs} +1 -1
- package/dist/{json-number-CAfNAqDB.mjs.map → json-number-DoseUwuo.mjs.map} +1 -1
- package/dist/{key-DJXcPZR_.mjs → key-rszcmZdB.mjs} +2 -2
- package/dist/{key-DJXcPZR_.mjs.map → key-rszcmZdB.mjs.map} +1 -1
- package/dist/{libsql-Dmtj0O4E.mjs → libsql-CAZVcr9G.mjs} +2 -2
- package/dist/{libsql-Dmtj0O4E.mjs.map → libsql-CAZVcr9G.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/{memory-b-dafk9S.mjs → memory-CqWRO6-3.mjs} +2 -2
- package/dist/{memory-b-dafk9S.mjs.map → memory-CqWRO6-3.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.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/{mysql-DAaUSeBw.mjs → mysql-BPPBSJzl.mjs} +2 -2
- package/dist/{mysql-DAaUSeBw.mjs.map → mysql-BPPBSJzl.mjs.map} +1 -1
- package/dist/mysql-adapter-Dbo7l0lI.mjs +2 -0
- package/dist/mysql-adapter-Dbo7l0lI.mjs.map +1 -0
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/{native-types-BbKWN3JV.mjs → native-types-6wCGP1a1.mjs} +1 -1
- package/dist/{native-types-BbKWN3JV.mjs.map → native-types-6wCGP1a1.mjs.map} +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/normalized-result-23DWxZVY.mjs +2 -0
- package/dist/{normalized-result-VunNi4ID.mjs.map → normalized-result-23DWxZVY.mjs.map} +1 -1
- package/dist/{object-store-BHyP-LEI.d.mts → object-store-Cs3AueG5.d.mts} +4 -4
- package/dist/{object-store-I1MyfM72.mjs → object-store-DmnlQy7V.mjs} +2 -2
- package/dist/{object-store-I1MyfM72.mjs.map → object-store-DmnlQy7V.mjs.map} +1 -1
- package/dist/on.d.mts +80 -0
- package/dist/on.mjs +2 -0
- package/dist/on.mjs.map +1 -0
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/pg.d.mts +1 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/{physical-CAZ_LauY.mjs → physical-DT6C54w7.mjs} +2 -2
- package/dist/{physical-CAZ_LauY.mjs.map → physical-DT6C54w7.mjs.map} +1 -1
- package/dist/pinned-session-BdON2d0V.mjs +2 -0
- package/dist/{pinned-session-D8bM5obl.mjs.map → pinned-session-BdON2d0V.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-BDLdDieE.d.mts → planner-BxCcoO8s.d.mts} +22 -1
- package/dist/{postgres-HaFcFACt.mjs → postgres-BK_aOx_C.mjs} +44 -37
- package/dist/postgres-BK_aOx_C.mjs.map +1 -0
- package/dist/postgres-adapter-CVazEDVI.mjs +2 -0
- package/dist/postgres-adapter-CVazEDVI.mjs.map +1 -0
- package/dist/postgres-adapter-DxhZu7Qw.mjs +2 -0
- package/dist/{postgres-adapter-CnZjhvG1.mjs.map → postgres-adapter-DxhZu7Qw.mjs.map} +1 -1
- package/dist/postgres-result-DYeVeHuT.mjs +2 -0
- package/dist/{postgres-result-D4_yZqO8.mjs.map → postgres-result-DYeVeHuT.mjs.map} +1 -1
- package/dist/postgres.d.mts +1 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-CpitUqW6.mjs → provider-limits-zLe7S_0W.mjs} +2 -2
- package/dist/{provider-limits-CpitUqW6.mjs.map → provider-limits-zLe7S_0W.mjs.map} +1 -1
- package/dist/{validation-DN1N2OdK.mjs → query-CTna5P9o.mjs} +2 -2
- package/dist/query-CTna5P9o.mjs.map +1 -0
- package/dist/{relation-bound-5ChGF3n5.mjs → relation-bound-Bj7X-EUE.mjs} +1 -1
- package/dist/{relation-bound-5ChGF3n5.mjs.map → relation-bound-Bj7X-EUE.mjs.map} +1 -1
- package/dist/{result-parsing-BX3_3Q15.mjs → result-parsing-C2044903.mjs} +1 -1
- package/dist/{result-parsing-BX3_3Q15.mjs.map → result-parsing-C2044903.mjs.map} +1 -1
- package/dist/result-shape-C8QFUuIt.mjs +2 -0
- package/dist/{result-shape-BuGfArOr.mjs.map → result-shape-C8QFUuIt.mjs.map} +1 -1
- package/dist/rows-D7ns2l0U.mjs +2 -0
- package/dist/{rows-BlONp14o.mjs.map → rows-D7ns2l0U.mjs.map} +1 -1
- package/dist/{scalar-B3WLZzJj.mjs → scalar-D6QmJ22_.mjs} +2 -2
- package/dist/{scalar-B3WLZzJj.mjs.map → scalar-D6QmJ22_.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/{schema-B_Bc7TQ2.mjs → schema-CY9kOwJ-.mjs} +2 -2
- package/dist/{schema-B_Bc7TQ2.mjs.map → schema-CY9kOwJ-.mjs.map} +1 -1
- package/dist/{schema-introspection-BqN7d_sA.mjs → schema-introspection-CfqmM3Cz.mjs} +2 -2
- package/dist/{schema-introspection-BqN7d_sA.mjs.map → schema-introspection-CfqmM3Cz.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-BP8c4O-0.mjs → select-assembly-D7FEenz2.mjs} +2 -2
- package/dist/select-assembly-D7FEenz2.mjs.map +1 -0
- package/dist/{settle-B9Vg1FnP.mjs → settle-CObilv26.mjs} +2 -2
- package/dist/{settle-B9Vg1FnP.mjs.map → settle-CObilv26.mjs.map} +1 -1
- package/dist/{sha256-DDEbgnTU.mjs → sha256-Da07rzvR.mjs} +1 -1
- package/dist/{sha256-DDEbgnTU.mjs.map → sha256-Da07rzvR.mjs.map} +1 -1
- package/dist/soft-delete.d.mts +1 -1
- package/dist/{sql-BR8ZzKn8.mjs → sql-DGtEeP8z.mjs} +1 -1
- package/dist/{sql-BR8ZzKn8.mjs.map → sql-DGtEeP8z.mjs.map} +1 -1
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-DL3ooNs7.mjs} +1 -1
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-DL3ooNs7.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-DqT6HeDs.mjs +2 -0
- package/dist/sqlite-adapter-DqT6HeDs.mjs.map +1 -0
- package/dist/{sqlite-utils-CFInz2yY.mjs → sqlite-utils-DeDlMJKj.mjs} +2 -2
- package/dist/{sqlite-utils-CFInz2yY.mjs.map → sqlite-utils-DeDlMJKj.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/{standard-sql-wRMNi-Yg.mjs → standard-sql-BErrm6AV.mjs} +2 -2
- package/dist/{standard-sql-wRMNi-Yg.mjs.map → standard-sql-BErrm6AV.mjs.map} +1 -1
- package/dist/{suppressed-failure-Bdo2aK81.mjs → suppressed-failure-3C4sFXvH.mjs} +1 -1
- package/dist/{suppressed-failure-Bdo2aK81.mjs.map → suppressed-failure-3C4sFXvH.mjs.map} +1 -1
- package/dist/{to-many-CUBK3CTd.mjs → to-many-DqYv9-vp.mjs} +2 -2
- package/dist/{to-many-CUBK3CTd.mjs.map → to-many-DqYv9-vp.mjs.map} +1 -1
- package/dist/{transaction-operation-C3Jbblbl.mjs → transaction-operation-Co3hw8yz.mjs} +1 -1
- package/dist/{transaction-operation-C3Jbblbl.mjs.map → transaction-operation-Co3hw8yz.mjs.map} +1 -1
- package/dist/{types-BNR3u6hH.mjs → types-CJgtjXtu.mjs} +1 -1
- package/dist/{types-BNR3u6hH.mjs.map → types-CJgtjXtu.mjs.map} +1 -1
- package/dist/{utils-Be91XL14.mjs → utils-DooFtO1V.mjs} +3 -3
- package/dist/utils-DooFtO1V.mjs.map +1 -0
- package/dist/{v-lthABIXD.mjs → v-yKivkoka.mjs} +2 -2
- package/dist/{v-lthABIXD.mjs.map → v-yKivkoka.mjs.map} +1 -1
- package/dist/validation-pfpKPPZ_.mjs +2 -0
- package/dist/validation-pfpKPPZ_.mjs.map +1 -0
- package/dist/{validation-BfJaNYMf.mjs → validation-u-sZDdfD.mjs} +2 -2
- package/dist/{validation-BfJaNYMf.mjs.map → validation-u-sZDdfD.mjs.map} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/{validator-BJhI364k.mjs → validator-XVm02V0K.mjs} +2 -2
- package/dist/{validator-BJhI364k.mjs.map → validator-XVm02V0K.mjs.map} +1 -1
- package/dist/version-WvqPqZJ4.mjs +2 -0
- package/dist/{version-DAFcmokN.mjs.map → version-WvqPqZJ4.mjs.map} +1 -1
- package/dist/write-sinks-CoB5PPw9.mjs +2 -0
- package/dist/write-sinks-CoB5PPw9.mjs.map +1 -0
- package/dist/writes-CD0mNS5-.mjs +2 -0
- package/dist/writes-CD0mNS5-.mjs.map +1 -0
- package/package.json +36 -15
- package/dist/bind-parameter-capacity-faPOSaLz.mjs +0 -2
- package/dist/chain-C1VPkUpC.mjs +0 -2
- package/dist/client-C1MxqFtt.mjs.map +0 -1
- package/dist/client-DHf2ZfRe.mjs +0 -2
- package/dist/client-DHf2ZfRe.mjs.map +0 -1
- package/dist/driver-aqfbJdZC.mjs +0 -2
- package/dist/error-mapping-Zett_Pnt.mjs +0 -2
- package/dist/error-mapping-Zett_Pnt.mjs.map +0 -1
- package/dist/every-BUf842ai.mjs +0 -2
- package/dist/geo-point-codec-DcUTvoEg.mjs +0 -2
- package/dist/mysql-adapter-BrkDrfin.mjs +0 -2
- package/dist/mysql-adapter-BrkDrfin.mjs.map +0 -1
- package/dist/normalized-result-VunNi4ID.mjs +0 -2
- package/dist/pinned-session-D8bM5obl.mjs +0 -2
- package/dist/postgres-HaFcFACt.mjs.map +0 -1
- package/dist/postgres-adapter-BhNE_3b-.mjs +0 -2
- package/dist/postgres-adapter-BhNE_3b-.mjs.map +0 -1
- package/dist/postgres-adapter-CnZjhvG1.mjs +0 -2
- package/dist/postgres-result-D4_yZqO8.mjs +0 -2
- package/dist/result-shape-BuGfArOr.mjs +0 -2
- package/dist/rows-BlONp14o.mjs +0 -2
- package/dist/select-assembly-BP8c4O-0.mjs.map +0 -1
- package/dist/sqlite-adapter-CF-m7LIP.mjs +0 -2
- package/dist/sqlite-adapter-CF-m7LIP.mjs.map +0 -1
- package/dist/utils-Be91XL14.mjs.map +0 -1
- package/dist/validation-DN1N2OdK.mjs.map +0 -1
- package/dist/version-DAFcmokN.mjs +0 -2
- /package/dist/{contract-Dw0FR78e.d.mts → contract-H_WiAUaR.d.mts} +0 -0
- /package/dist/{sql-Q_twK-wW.d.mts → sql-CF5Xi6z-.d.mts} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{v as t}from"./query-CTna5P9o.mjs";import{E as n,g as r}from"./geo-point-codec-mjROsQX-.mjs";import{o as i}from"./sql-DGtEeP8z.mjs";import{a}from"./physical-DT6C54w7.mjs";import{t as o}from"./geo-area-codec-H50rrGiF.mjs";import{t as s}from"./adapter-result-parser-C0vW9am8.mjs";import{r as ee}from"./adapter-internals-DULbfdmQ.mjs";import{n as c}from"./result-parsing-C2044903.mjs";import{r as l}from"./datetime-physical-codec-Bl6M6vF5.mjs";import{A as u,C as d,D as f,E as te,M as p,N as m,S as h,T as g,_,a as v,c as y,d as b,f as x,g as S,h as C,i as w,l as T,m as E,n as D,o as O,p as k,r as A,s as j,t as M,u as N,v as ne,w as P,x as F,y as I}from"./standard-sql-BErrm6AV.mjs";import{n as L}from"./batch-refs-cBYAKzaE.mjs";import{t as R}from"./adapter-namespace-CFtC8LbT.mjs";import{a as z,d as B,f 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-D7FEenz2.mjs";const X=m("`"),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)} * ${B(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,V(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),caseFold=e=>i`LOWER(${e})`,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){R(this,e,`mysql`),this.identifiers=x(X,this.namespace,!0),K(this,this.geoPoint),ee(this,{batchRefs:this.#t,constraints:Z,select:this.#e.select})}raw=h();identifiers;literals={...te(),true:()=>i.raw`TRUE`,false:()=>i.raw`FALSE`,json:e=>i`${JSON.stringify(e)}`,dateTime:(e,t,n)=>i`${n||e.length===10?e:l(e)}`,decimal:(e,t)=>i`CAST(${n(e,t,`text`)} AS ${i.raw(r(`mysql`,t))})`,id:(e,t)=>i`${e}`};operators={...v(),like:(e,t)=>i`${e} LIKE ${t} ESCAPE '\\\\'`,notLike:(e,t)=>i`${e} NOT LIKE ${t} ESCAPE '\\\\'`,ilike:(e,t)=>i`BINARY ${caseFold(e)} LIKE BINARY ${caseFold(t)} ESCAPE '\\\\'`,notIlike:(e,t)=>i`BINARY ${caseFold(e)} NOT LIKE BINARY ${caseFold(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}`,insensitiveText:(e,t,n)=>this.operators[`${e}Text`](caseFold(t),caseFold(n)),startsWithPrefix:(e,t)=>i`(${e} LIKE ${`${u(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})`,...S(),...ne(),...F(),...C(this.literals.true,this.literals.false),...b()};expressions={...w(),caseFold,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:A({text:`CHAR`,integer:`SIGNED`,bigint:`SIGNED`,boolean:`UNSIGNED`,numeric:`DECIMAL`}),blobToHex:e=>i`LOWER(HEX(${e}))`};aggregates={...D(),decimalAvg:(e,t)=>mysqlDecimalAverage(e,t),decimalSumOperandPrecision:y(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}, ${M(t)})`,extractText:(e,t)=>i`JSON_UNQUOTE(JSON_EXTRACT(${e}, ${M(t)}))`,numberAtPath:(e,t)=>{let n=M(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=M(t);return i`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${n})) = 'STRING' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${e}, ${n})) AS BINARY) END)`},foldableStringAtPath:(e,t)=>{let n=M(t);return i`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${n})) = 'STRING' THEN JSON_UNQUOTE(JSON_EXTRACT(${e}, ${n})) 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={...T(),...N()};clauses={...g(),limit:e=>i`LIMIT ${inlineIntegerLiteral(e)}`,offset:e=>i`OFFSET ${inlineIntegerLiteral(e)}`};set={...I(),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=d();subqueries=f(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=j(X);mutations={skipDuplicatesStrategy:`recoverableUniqueError`,insert:k(X),insertDefault:e=>i`INSERT INTO ${e} () VALUES ()`,..._(),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={...O(),full:(e,t)=>{throw Error(`MySQL does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.`)},...E(X)};setOperations=P(X);capabilities={supportsReturning:!1,supportsCteWithMutations:!1,supportsFullOuterJoin:!1,supportsLateralJoins:!0,supportsVector:!1,supportsUpsertWhere:!1,supportsTargetedUpsert:!1,supportsMutationTargetInSubquery:!1,supportsMutationRowLimit:!0,supportsRowLocks:!0,locksMissingKeys:!0,boundsRecursionIterations:!0};lastInsertId=()=>i.raw`LAST_INSERT_ID()`;#t=L({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(${z(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:s,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>{if(t===`boolean`){let t=c(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-Dbo7l0lI.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mysql-adapter-Dbo7l0lI.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 type TextMatch,\n} from \"../../database-adapter\";\nimport { createMySqlBatchRefs } from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n halfEvenQuotient,\n scaleFactorSql,\n scaleUnitSql,\n signedNumerator,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoBoundsIndexPolygons,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport { parseIntegerBoolean } from \"../../shared/result-parsing\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n buildJsonPath,\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDecimalSumOperandPrecision,\n createDirectionOrderBy,\n createEmulatedNullsOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLateralJoins,\n createLogicalOperators,\n createMembershipOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n 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};\n// MySQL's own case folding: `LOWER` maps every letter by the string's\n// character set (Unicode for utf8mb4). It must see the raw text — on a\n// `BINARY` string it does nothing — and its result is compared as bytes, so a\n// case- AND accent-insensitive collation (`utf8mb4_0900_ai_ci`) never decides.\nconst caseFold = (expr: Sql): Sql => sql`LOWER(${expr})`;\n\n// MySQL DATETIME rejects ISO-8601's 'Z' suffix (\"Incorrect datetime value\"),\n// so datetimes are stored as naive UTC wall-clock 'YYYY-MM-DD HH:MM:SS.mmm'.\n\n// Naive datetime string as it comes back from MySQL (top-level on string\n// drivers, or inside JSON_ARRAYAGG/JSON_OBJECT includes): no 'Z'/offset.\nconst NAIVE_DATETIME_REGEX =\n /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2})(\\.\\d+)?$/;\n\n/** Reattach UTC to a naive MySQL datetime string so it parses as the stored instant. */\nconst naiveDateTimeToIso = (value: string): string | undefined => {\n const match = NAIVE_DATETIME_REGEX.exec(value);\n if (!match) return undefined;\n const fraction = match[3] ? match[3].padEnd(4, \"0\").slice(0, 4) : \".000\";\n return `${match[1]}T${match[2]}${fraction}Z`;\n};\n\n/** Replace a single-integer-parameter fragment with an inline literal. */\nconst inlineIntegerLiteral = (fragment: Sql): Sql => {\n const value = fragment.values.length === 1 ? fragment.values[0] : undefined;\n return typeof value === \"number\" && Number.isInteger(value)\n ? sql.raw(String(value))\n : fragment;\n};\n\nconst 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, true);\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`BINARY ${caseFold(column)} LIKE BINARY ${caseFold(pattern)} ESCAPE '\\\\\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`BINARY ${caseFold(column)} NOT LIKE BINARY ${caseFold(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 insensitiveText: (kind: TextMatch, column: Sql, value: Sql): Sql =>\n this.operators[`${kind}Text`](caseFold(column), caseFold(value)),\n // Two conjuncts, because on MySQL no single predicate is both exact and\n // index-usable. The index stores the column's own collation's sort keys —\n // `utf8mb4_0900_ai_ci` on a default install, which is case- AND\n // accent-insensitive — so any comparison forced to BINARY cannot range on\n // it. Measured on MySQL 8 (Docker, 20k rows): `col LIKE 'x%'` is a `range`\n // over 111 rows, while both `col LIKE BINARY 'x%'` and the\n // `LEFT(BINARY col, …)` spelling above degrade to a full `index` scan of\n // all 19731 entries.\n //\n // So the collation-native LIKE goes first as an index accelerator, and the\n // BINARY predicate — byte-identical to `startsWithText` above — follows as\n // the semantics. The accelerator can never drop a row the BINARY conjunct\n // would keep: byte-equal strings compare equal under every collation, so a\n // binary prefix match implies the collation-native one. It is not a second\n // guard on the same invariant — it decides no row's membership, only which\n // rows the server has to look at.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n startsWithPrefix: (column: Sql, value: string): Sql =>\n sql`(${column} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\\\\\' AND LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value})`,\n\n // `startsWithPrefix`'s twin, for the same reason and in the same shape\n // (plan §10.2). `BINARY col` is a FUNCTION of the column, so MySQL cannot\n // range on it: measured on MySQL 8.4 over 20,000 rows in the collation\n // viborm's own DDL declares, `BINARY name = ?` planned `index` over 20,455\n // rows where `name = ?` planned `ref` over 1, and `BINARY name IN (…)`\n // planned `index` over 20,455 where `name IN (…)` planned `range` over 3.\n //\n // The collation-native conjunct is the accelerator and decides no row's\n // membership: byte-identical strings compare equal under every collation\n // of the charset, so the BINARY comparison IMPLIES it. On the tables\n // viborm creates (`utf8mb4_0900_bin`) the two conjuncts say the same\n // thing; on a table viborm did not create the BINARY one is what keeps the\n // case-sensitivity contract, and the same measurement shows the pair still\n // plans `ref` over 1 row there.\n //\n // `notIn` and `not` deliberately have no such pair. Their implication runs\n // the other way — `BINARY col NOT IN ('X')` KEEPS a row spelled `x` that\n // `col NOT IN ('X')` drops on a case-insensitive column, measured at\n // 20,000 rows against 19,999 — so a conjunct would remove rows. There is\n // also nothing to win: both spellings of `NOT IN` scan all 20,442 rows.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n exactTextEq: (column: Sql, value: Sql): Sql =>\n sql`(${column} = ${value} AND BINARY ${column} = ${value})`,\n exactTextIn: (column: Sql, values: Sql): Sql =>\n sql`(${column} IN ${values} AND BINARY ${column} IN ${values})`,\n\n ...createMembershipOperators(),\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n caseFold,\n caseSensitiveText: (expr: Sql): Sql => sql`BINARY ${expr}`,\n\n // String operations - MySQL uses CONCAT() function\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw`''`;\n if (parts.length === 1) return parts[0]!;\n return sql`CONCAT(${sql.join(parts, \", \")})`;\n },\n\n greatest: (...exprs: Sql[]): Sql => sql`GREATEST(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`LEAST(${sql.join(exprs, \", \")})`,\n\n // The expression form of `set.divide`'s integer arm: MySQL `/` yields a\n // DECIMAL quotient even for two integers, so the truncation is explicit.\n integerDivide: (left: Sql, right: Sql): Sql =>\n sql`TRUNCATE(${left} / ${right}, 0)`,\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n decimalCast(expr, descriptor.precision, descriptor.scale),\n\n // `CHAR` rather than `TEXT`: MySQL's CAST target list has no `TEXT`, which\n // is why `cast` below maps the generic text cast to `CHAR` too.\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`UNHEX(${expr})`\n : sql`CAST(${expr} AS CHAR)`,\n\n cast: createCastExpression({\n text: \"CHAR\",\n integer: \"SIGNED\",\n bigint: \"SIGNED\",\n boolean: \"UNSIGNED\",\n numeric: \"DECIMAL\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`LOWER(HEX(${expr}))`,\n };\n\n aggregates = {\n ...createAggregateFunctions(),\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n mysqlDecimalAverage(column, descriptor),\n\n // MySQL's widest exact DECIMAL cast operand. SUM itself can return more\n // than 65 digits; this bound belongs to exact HAVING operand lowering.\n decimalSumOperandPrecision:\n createDecimalSumOperandPrecision(MYSQL_EXACT_DIGITS),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql => sql`${left} = ${right}`,\n number: (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 foldableStringAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) = 'STRING' THEN JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) 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 // InnoDB answers a locking miss on a unique index with a gap lock that\n // concurrent misses share and their INSERTs wait on (`ER_LOCK_DEADLOCK`).\n locksMissingKeys: true,\n boundsRecursionIterations: true,\n };\n\n lastInsertId = (): Sql => sql.raw`LAST_INSERT_ID()`;\n\n readonly #batchRefs = createMySqlBatchRefs({\n table: sql.raw`\\`__viborm_batch_refs\\``,\n batchIdColumn: sql.raw`\\`batch_id\\``,\n keyColumn: sql.raw`\\`ref_key\\``,\n valueColumn: sql.raw`\\`ref_value\\``,\n duplicateValue: sql.raw`VALUES(\\`ref_value\\`)`,\n createTable: sql.raw`CREATE TEMPORARY TABLE IF NOT EXISTS \\`__viborm_batch_refs\\` (\\`batch_id\\` VARCHAR(191) NOT NULL, \\`ref_key\\` VARCHAR(191) NOT NULL, \\`ref_value\\` TEXT, PRIMARY KEY (\\`batch_id\\`, \\`ref_key\\`))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS CHAR)`,\n lastInsertId: () => this.lastInsertId(),\n });\n\n vector = unsupportedVector;\n\n readonly geoPoint: GeoPointSql = (() => {\n const longitude = (point: Sql): Sql => sql`ST_Longitude(${point})`;\n const latitude = (point: Sql): Sql => sql`ST_Latitude(${point})`;\n 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":"q7BA6EA,MAAM,EAAa,EAAuB,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,IAD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,GAEjD,UAAW,EAAM,IACf,CAAG,sBAAsB,EAAK,IAAI,EAAM,IAAI,EAA8B,GAC7E,IACC,CASJ,OAA8B,CAM5B,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,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"}
|
package/dist/mysql2.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as Schema,
|
|
1
|
+
import { A as Schema, An as TransactionOptionSupport, At as DriverConfig, F as LinkedClientConfig, Fn as QueryResult, Ft as VibORMClient, Pn as QueryExecutionContext, Pt as NoExtraDriverConfigKeys, g as MigrationNamespaceAttestation, kn as DriverTransactionOptions, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-DRX_LLQM.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{a as t,i as n,o as r}from"./normalized-result-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,i as n,o as r}from"./normalized-result-23DWxZVY.mjs";import{l as i}from"./execution-context-_oajgBi4.mjs";import{i as a}from"./base-wlv81COV.mjs";import{m as o,u as s}from"./error-mapping-DRY49A3C.mjs";import{d as c,t as l}from"./query-CTna5P9o.mjs";import{n as u}from"./transaction-D5LHYn-r.mjs";import{n as d}from"./client-BqgVSbk0.mjs";import{a as f,c as p,d as m,i as h,l as g,o as _,t as v}from"./driver-szWYBmjD.mjs";import{t as y}from"./mysql-adapter-Dbo7l0lI.mjs";import{Buffer as b}from"node:buffer";const x=/^(?:ssl|tls)/i;function tlsRefusal(e){return new l(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 c(`Driver "mysql2" returned a malformed result for operation "${e}": ${t}.`,{meta:{driver:`mysql2`,operation:e}})}const C=/^-[1-9]\d*$/;function normalizeMySQL2InsertId(e,n){if(!(typeof e==`number`&&Number.isSafeInteger(e)&&e<0||typeof e==`string`&&C.test(e)))return t(e,n,{allowNumber:!0})}function toQueryResult(e,t,i){if(isMultiStatementFields(t))throw new c(`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(t)||t.some(e=>!n(e)))throw malformedMySQL2Result(i,`row arrays require one flat field metadata array`);return{rows:e,rowCount:e.length}}if(t!==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:r(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 a(e)?e:new l(`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 l(`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 l(`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 l(`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 s(this.driverName);let a=e,c=await h(()=>a.getConnection(),e=>e.release(),r?.maxWaitMs,{driverName:this.driverName,form:`callback`}),l=!1,runOrDestroy=async e=>{try{await e()}catch(e){throw l=!0,e}},d=r?.isolationLevel;return o({begin:()=>runOrDestroy(async()=>{d&&await c.query(f(d)),await c.beginTransaction()}),callback:()=>t(c),commit:()=>runOrDestroy(()=>c.commit()),rollback:()=>runOrDestroy(()=>c.rollback()),phases:i(n),close:()=>{try{if(l){c.destroy();return}c.release()}catch(e){throw super.transactionCleanupFailed(new u(`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 s(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
|
package/dist/mysql2.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mysql2.mjs","names":[],"sources":["../src/drivers/shared/mysql-utils.ts","../src/drivers/mysql2/index.ts"],"sourcesContent":["/**\n * Shared MySQL Utilities\n *\n * Shared connection utilities for MySQL-based drivers.\n */\n\nimport { ClientInitializationError } from \"@errors\";\n\n/**\n * The connection options a MySQL database URL carries: only the keys it\n * spells, so merged under a caller's options it fills what they left out\n * instead of replacing it with `undefined` or a default port.\n */\nexport interface MySQLConnectionOptions {\n [option: string]: unknown;\n ssl?: object | string;\n host: string;\n port?: number;\n /** Absent when the URL carries no database path. */\n database?: string;\n user?: string;\n password?: string;\n}\n\nconst TLS_URL_OPTION_PATTERN = /^(?:ssl|tls)/i;\n\n/**\n * A TLS request VibORM cannot honour. Its own text, which carries no part of\n * the URL, so the driver surfaces it rather than redacting it.\n */\nfunction tlsRefusal(message: string): ClientInitializationError {\n return new ClientInitializationError(message, {\n meta: { driver: \"mysql2\", operation: \"configuration\" },\n });\n}\n\nexport function parseMySQLUrl(url: string): MySQLConnectionOptions {\n const parsed = new URL(url);\n const database = decodeURIComponent(parsed.pathname.slice(1));\n const queryOptions: Record<string, unknown> = {};\n for (const [key, value] of parsed.searchParams) {\n if (\n TLS_URL_OPTION_PATTERN.test(key) &&\n key !== \"ssl\" &&\n key !== \"sslmode\"\n ) {\n throw tlsRefusal(\n \"Unsupported MySQL TLS URL option; configure options.ssl explicitly.\"\n );\n }\n try {\n queryOptions[key] = JSON.parse(value);\n } catch {\n queryOptions[key] = value;\n }\n }\n // mysql2 understands ssl, but not libpq's sslmode. Refuse a TLS request\n // whose policy cannot be represented instead of silently opening plaintext.\n const sslmode = parsed.searchParams.get(\"sslmode\");\n if (sslmode && sslmode !== \"disable\") {\n if (![\"require\", \"verify-ca\", \"verify-full\"].includes(sslmode)) {\n throw tlsRefusal(\n \"Unsupported MySQL sslmode; configure options.ssl explicitly.\"\n );\n }\n if (\n queryOptions.ssl !== undefined &&\n (queryOptions.ssl === null ||\n (typeof queryOptions.ssl !== \"object\" &&\n typeof queryOptions.ssl !== \"string\"))\n )\n throw tlsRefusal(\"MySQL sslmode requires a TLS configuration\");\n queryOptions.ssl ??= {};\n }\n Reflect.deleteProperty(queryOptions, \"sslmode\");\n const user = decodeURIComponent(parsed.username);\n const password = decodeURIComponent(parsed.password);\n return {\n host: parsed.hostname,\n ...(parsed.port ? { port: Number.parseInt(parsed.port, 10) } : {}),\n ...(database === \"\" ? {} : { database }),\n ...(user === \"\" ? {} : { user }),\n ...(password === \"\" ? {} : { password }),\n ...queryOptions,\n };\n}\n","/**\n * MySQL2 Driver\n *\n * Driver implementation for mysql2/promise with connection pooling.\n */\n\nimport { Buffer } from \"node:buffer\";\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { MySQLAdapter } from \"@adapters/databases/mysql/mysql-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n ClientInitializationError,\n isVibORMError,\n QueryError,\n TransactionError,\n} from \"@errors\";\nimport type { Pool, PoolConnection, PoolOptions } from \"mysql2/promise\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n isNormalizedResultRow,\n type NormalizedResultContext,\n normalizeProviderInsertId,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n isolationLevelStatement,\n type MigrationNamespaceAttestation,\n type MySQLConnectionOptions,\n nestedTransactionDispatchError,\n type PinnedSessionReservation,\n parseMySQLUrl,\n resolveMigrationNamespaceAttestationOption,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type MySQL2Options = PoolOptions;\n\nexport interface MySQL2DriverOptions {\n pool?: Pool;\n options?: PoolOptions;\n databaseUrl?: string;\n /**\n * The MySQL database this driver's persistent objects live in. Omitted, the\n * target is derived from a driver-created pool's own configuration, and a\n * driver that resolves none keeps the existing unqualified mode.\n */\n namespace?: string;\n /**\n * Caller-owned assertion that qualified `database.table` references and the\n * pinned migration session's `USE` cannot be redirected by VTGate\n * schema-routing rules or an equivalent proxy. It selects nothing, is never\n * inferred, and only effectful live migration work requires it.\n */\n migrationNamespaceAttestation?: MigrationNamespaceAttestation;\n}\n\nexport type MySQL2ClientConfig<C extends DriverConfig> = MySQL2DriverOptions &\n C;\n\nconst MYSQL2_CONFIG_KEYS: Record<keyof MySQL2DriverOptions, true> = {\n pool: true,\n options: true,\n databaseUrl: true,\n namespace: true,\n migrationNamespaceAttestation: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\n/** mysql2 escapes plain Uint8Array as an object — convert to Buffer for blobs. */\nfunction convertValuesForMySQL(values: unknown[]): unknown[] {\n return values.map((v) =>\n v instanceof Uint8Array && !Buffer.isBuffer(v)\n ? Buffer.from(v.buffer, v.byteOffset, v.byteLength)\n : v\n );\n}\n\nfunction isMultiStatementFields(fields: unknown): boolean {\n return (\n Array.isArray(fields) &&\n fields.every(\n (fieldSet) => fieldSet === undefined || Array.isArray(fieldSet)\n )\n );\n}\n\nfunction malformedMySQL2Result(operation: string, reason: string): QueryError {\n return new QueryError(\n `Driver \"mysql2\" returned a malformed result for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"mysql2\", operation } }\n );\n}\n\nconst CANONICAL_NEGATIVE_DECIMAL = /^-[1-9]\\d*$/;\n\n/** mysql2 echoes an explicit negative AUTO_INCREMENT key in ResultSetHeader.insertId. */\nfunction normalizeMySQL2InsertId(\n value: unknown,\n context: NormalizedResultContext\n): number | bigint | undefined {\n if (\n (typeof value === \"number\" && Number.isSafeInteger(value) && value < 0) ||\n (typeof value === \"string\" && CANONICAL_NEGATIVE_DECIMAL.test(value))\n ) {\n return undefined;\n }\n return normalizeProviderInsertId(value, context, { allowNumber: true });\n}\n\n/** SELECT returns a row array; mutations return a ResultSetHeader. */\nfunction toQueryResult<T>(\n result: unknown,\n fields: unknown,\n operation: string\n): QueryResult<T> {\n if (isMultiStatementFields(fields)) {\n throw new QueryError(\n `Driver \"mysql2\" returned multiple statement results for operation \"${operation}\"; VibORM requires exactly one statement result.`,\n { meta: { driver: \"mysql2\", operation } }\n );\n }\n\n if (Array.isArray(result)) {\n if (\n !Array.isArray(fields) ||\n fields.some((field) => !isNormalizedResultRow(field))\n ) {\n throw malformedMySQL2Result(\n operation,\n \"row arrays require one flat field metadata array\"\n );\n }\n return {\n rows: result as T[],\n rowCount: result.length,\n };\n }\n\n if (fields !== undefined) {\n throw malformedMySQL2Result(\n operation,\n \"mutation results require undefined field metadata\"\n );\n }\n if (!isNormalizedResultRow(result)) {\n throw malformedMySQL2Result(operation, \"expected a mutation result object\");\n }\n const context = { provider: \"mysql2\", operation };\n const insertId = normalizeMySQL2InsertId(result.insertId, context);\n return {\n rows: [] as T[],\n rowCount: normalizeProviderRowCount(result.affectedRows, context, {\n allowDecimalString: true,\n }),\n ...(insertId === undefined ? {} : { insertId }),\n };\n}\n\n/**\n * The target derived from a pool this driver will create: the `database` it\n * connects with, which is the caller's option when given and otherwise the\n * URL's path (see `resolveMySQL2Configuration`). A supplied `Pool` is opaque —\n * VibORM does not inspect mysql2 internals, so only an explicit `namespace` can\n * bind one. A pathless URL contributes nothing, and neither does an empty\n * `options.database`: §1.3's empty candidate is an absent one rather than a\n * name handed to identifier validation. A non-empty derived name is validated\n * exactly like an explicit one, by the adapter that installs it.\n */\nfunction deriveMySQL2Namespace(\n configuration: Omit<MySQL2Configuration, \"namespace\">\n): string | undefined {\n if (configuration.suppliedPool) return undefined;\n const configured = configuration.connectionOptions.database;\n return configured === \"\" ? undefined : configured;\n}\n\n/** What this driver settles from its caller's object, each source read once. */\ninterface MySQL2Configuration {\n readonly namespace: string | undefined;\n /**\n * The EXACT pool the caller supplied, or absent when this driver makes its\n * own. Identity, settled once, is the whole ownership answer: the caller's\n * options object is theirs to change, and a `pool` key deleted after\n * construction used to make `$disconnect()` end a transport VibORM was handed.\n */\n readonly suppliedPool: Pool | undefined;\n /**\n * The caller's connection record, copied once, over the keys its\n * `databaseUrl` carries: the URL fills only what the record leaves out, and\n * a key the record sets to `undefined` (an unset environment variable) is\n * left out. A per-tenant URL plus a password from a secret is this shape.\n *\n * A copy of THIS record, not of what it points at: a nested `ssl` object or\n * stream is the caller's to own, and the keys that decide where a pool\n * connects — host, port, user, database — all live here. It is also what the\n * constructor's refusals read, so the options this driver validated are the\n * exact options it later connects with.\n */\n readonly connectionOptions: PoolOptions;\n}\n\n/**\n * The one immutable ORM target for this driver, in the plan's exact order: an\n * explicit `namespace`, then the driver-created pool's own derivation.\n *\n * `databaseUrl` is read once and parsed once, here, and the parse is kept: a\n * second read at connect time would let a caller-owned accessor hand the\n * provider a different URL than the one that decided the target. A present URL\n * is parsed even when an explicit `namespace` outranks it, because an unusable\n * connection string is a construction failure either way; `\"\"`, `null`, and an\n * absent property are the same absent request. Both rules are the convenience\n * wrapper's too, so the two entry points cannot disagree.\n *\n * None of these sources is transport evidence: the attestation is read\n * separately and never derived from a resolved target.\n */\nfunction resolveMySQL2Configuration(\n options: MySQL2DriverOptions\n): MySQL2Configuration {\n const explicit = resolveNamespaceOption(options);\n const databaseUrl = options.databaseUrl;\n const urlOptions = databaseUrl\n ? parseMySQL2ConfiguredUrl(databaseUrl)\n : undefined;\n const connectionOptions: PoolOptions = { ...urlOptions };\n for (const [key, value] of Object.entries(options.options ?? {})) {\n if (value !== undefined) Reflect.set(connectionOptions, key, value);\n }\n const captured = { suppliedPool: options.pool, connectionOptions };\n return {\n namespace: explicit ?? deriveMySQL2Namespace(captured),\n ...captured,\n };\n}\n\n/**\n * The URL now decides a target, so a malformed one fails at construction. A\n * TLS refusal is VibORM's own secret-free text and passes through; the URL\n * parser's failure can carry the URL, so it is replaced and redacted.\n */\nfunction parseMySQL2ConfiguredUrl(databaseUrl: string): MySQLConnectionOptions {\n try {\n return parseMySQLUrl(databaseUrl);\n } catch (cause) {\n if (isVibORMError(cause)) throw cause;\n throw new ClientInitializationError(\n 'Driver \"mysql2\" could not parse its databaseUrl.',\n { cause: cause instanceof Error ? cause : undefined }\n );\n }\n}\n\nexport class MySQL2Driver extends Driver<Pool, PoolConnection> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n /** The caller's pool and connection record, as construction captured them. */\n private readonly suppliedPool: Pool | undefined;\n private readonly connectionOptions: PoolOptions;\n\n constructor(options: MySQL2DriverOptions = {}) {\n // Both facts are read before `super(...)` so the transport assertion is\n // installed by the base constructor and no option can be read twice.\n const attestation = resolveMigrationNamespaceAttestationOption(options);\n const configuration = resolveMySQL2Configuration(options);\n super(\"mysql\", \"mysql2\", {}, attestation);\n if (configuration.connectionOptions.multipleStatements === true) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support options.multipleStatements=true because VibORM operations require one result per statement.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n if (configuration.connectionOptions.rowsAsArray === true) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support options.rowsAsArray=true because VibORM requires row objects keyed by column name.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n if (\n configuration.connectionOptions.nestTables === true ||\n typeof configuration.connectionOptions.nestTables === \"string\"\n ) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support enabled options.nestTables because VibORM requires flat row objects keyed by result aliases.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n this.suppliedPool = configuration.suppliedPool;\n this.connectionOptions = configuration.connectionOptions;\n defineImmutableDriverFact(\n this,\n \"adapter\",\n new MySQLAdapter(configuration.namespace)\n );\n if (this.suppliedPool) {\n this.client = this.suppliedPool;\n }\n }\n\n /**\n * The pool this driver connects through.\n *\n * A caller's pool is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second pool behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<Pool> {\n if (this.suppliedPool !== undefined) {\n return this.suppliedPool;\n }\n const mysql = await import(\"mysql2/promise\");\n\n let options: PoolOptions = {\n // DATETIME is stored as naive UTC wall-clock; read it back as UTC\n // instead of shifting by the process timezone\n timezone: \"Z\",\n // BIGINT/DECIMAL values outside Number's safe range arrive as strings\n // (the result parser converts them losslessly) instead of lossy numbers\n supportBigNumbers: true,\n // DATE as plain \"YYYY-MM-DD\" — the result parser builds a UTC-midnight\n // Date, matching every other driver (mysql2 would build local midnight)\n dateStrings: [\"DATE\"],\n // Already merged with the URL, from the one parse construction made:\n // this driver never re-reads the caller's `databaseUrl`.\n ...this.connectionOptions,\n };\n\n // The pool this driver creates defaults to the same database the adapter\n // qualifies with, whichever source resolved it. A supplied pool never\n // reaches here, so VibORM never changes a caller's connection state.\n if (this.adapter.namespace !== undefined) {\n options = { ...options, database: this.adapter.namespace };\n }\n\n return mysql.createPool(options);\n }\n\n /**\n * Ends only a pool this driver created.\n *\n * A supplied pool belongs to the caller, who may be sharing it with other\n * clients or with their own code, and §5.3's rule is that VibORM never\n * changes a caller's connection state. `$disconnect()` used to end it\n * regardless, so disconnecting one client tore down every other consumer of\n * that pool.\n *\n * The test is on the pool's IDENTITY against what construction captured, so\n * it answers for the pool actually being closed rather than for whatever the\n * caller's record says now: every pool this driver made is ended, and the one\n * it was handed never is.\n */\n protected async closeClient(pool: Pool): Promise<void> {\n if (pool === this.suppliedPool) {\n return;\n }\n await pool.end();\n }\n\n protected async execute<T>(\n client: Pool | PoolConnection,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n const [result, fields] = await client.query({\n sql,\n values: convertValuesForMySQL(params),\n // Per-statement decoding also covers borrowed pools without mutating\n // their connection options. Text protocol avoids a statement per IN size.\n typeCast: (field, next) =>\n [\"DATE\", \"DATETIME\", \"TIMESTAMP\", \"LONGLONG\", \"NEWDECIMAL\"].includes(\n field.type\n )\n ? field.string()\n : next(),\n });\n return toQueryResult<T>(result, fields, operation);\n }\n\n protected async executeRaw<T>(\n client: Pool | PoolConnection,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const [result, fields] = await client.query(\n sql,\n params && convertValuesForMySQL(params)\n );\n return toQueryResult<T>(result, fields, operation);\n }\n\n /**\n * MySQL rejects `SET TRANSACTION ISOLATION LEVEL` once a transaction is open\n * (ER_CANT_CHANGE_TX_CHARACTERISTICS), so the level must be set on the\n * transaction's own connection *before* BEGIN, where it applies to exactly\n * the next transaction on that session. mysql2 pools hand out a connection we\n * can wait for with a bound and release if we stop waiting.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"pre-begin\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: Pool | PoolConnection,\n fn: (tx: PoolConnection) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (!(\"getConnection\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n // Start a new transaction from pool\n const pool = client as Pool;\n const connection = await acquireWithMaxWait(\n () => pool.getConnection(),\n (acquired) => acquired.release(),\n options?.maxWaitMs,\n { driverName: this.driverName, form: \"callback\" }\n );\n let shouldDestroy = false;\n const runOrDestroy = async (operation: () => Promise<void>) => {\n try {\n await operation();\n } catch (error) {\n shouldDestroy = true;\n throw error;\n }\n };\n const isolationLevel = options?.isolationLevel;\n return runTransactionLifecycle({\n begin: () =>\n runOrDestroy(async () => {\n // Session-scoped-next-transaction: this statement must land before\n // beginTransaction() to bind to the transaction it opens.\n if (isolationLevel) {\n await connection.query(isolationLevelStatement(isolationLevel));\n }\n await connection.beginTransaction();\n }),\n callback: () => fn(connection),\n commit: () => runOrDestroy(() => connection.commit()),\n rollback: () => runOrDestroy(() => connection.rollback()),\n phases: getExecutionTransactionPhases(context),\n close: () => {\n try {\n if (shouldDestroy) {\n connection.destroy();\n return;\n }\n connection.release();\n } catch (error) {\n super.transactionCleanupFailed(\n new TransactionError(\n 'Driver \"mysql2\" could not release an unsafe transaction connection.',\n { meta: { driver: \"mysql2\", method: \"$transaction\" } }\n )\n );\n throw error;\n }\n },\n });\n }\n\n protected override transactionCleanupFailed(_error: Error): void {\n // A connection with failed cleanup is destroyed; the pool remains usable.\n }\n\n /**\n * One `PoolConnection` from `pool.getConnection()` — plan §3.5's pinned\n * producer for MySQL2.\n *\n * It is ALWAYS destroyed, never released, and the `discard` flag is therefore\n * ignored: this session has executed `USE` to select the migration target and\n * may have executed author-owned statements from a manual artifact, and\n * mysql2's release resets neither. Returning it to an owned or a supplied\n * pool would leak that state into unrelated queries. This is correctness, not\n * an optimization.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<Pool | PoolConnection>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (!(\"getConnection\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const connection = await client.getConnection();\n return {\n session: connection,\n release: () => {\n connection.destroy();\n return Promise.resolve();\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: MySQL2ClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, MySQL2DriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: MySQL2Driver }\n >]: LinkedClientConfig<C & { driver: MySQL2Driver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"mysql2\", MYSQL2_CONFIG_KEYS);\n const { pool, options, databaseUrl } = config;\n const driver = new MySQL2Driver({\n // Attestation first, then namespace: the order a refusal reports in.\n migrationNamespaceAttestation:\n resolveMigrationNamespaceAttestationOption(config),\n namespace: resolveNamespaceOption(config),\n pool,\n options,\n databaseUrl,\n });\n\n return createClientFromDriverConfig<S, C, MySQL2Driver>(config, driver);\n}\n"],"mappings":"yjBAwBA,MAAM,EAAyB,gBAM/B,SAAS,WAAW,EAA4C,CAC9D,OAAO,IAAI,EAA0B,EAAS,CAC5C,KAAM,CAAE,OAAQ,SAAU,UAAW,gBAAiB,CACvD,CAAC,CAGJ,SAAgB,cAAc,EAAqC,CACjE,IAAM,EAAS,IAAI,IAAI,EAAI,CACrB,EAAW,mBAAmB,EAAO,SAAS,MAAM,EAAE,CAAC,CACvD,EAAwC,EAAE,CAChD,IAAK,GAAM,CAAC,EAAK,KAAU,EAAO,aAAc,CAC9C,GACE,EAAuB,KAAK,EAAI,EAChC,IAAQ,OACR,IAAQ,UAER,MAAM,WACJ,sEACD,CAEH,GAAI,CACF,EAAa,GAAO,KAAK,MAAM,EAAM,MAC/B,CACN,EAAa,GAAO,GAKxB,IAAM,EAAU,EAAO,aAAa,IAAI,UAAU,CAClD,GAAI,GAAW,IAAY,UAAW,CACpC,GAAI,CAAC,CAAC,UAAW,YAAa,cAAc,CAAC,SAAS,EAAQ,CAC5D,MAAM,WACJ,+DACD,CAEH,GACE,EAAa,MAAQ,IAAA,KACpB,EAAa,MAAQ,MACnB,OAAO,EAAa,KAAQ,UAC3B,OAAO,EAAa,KAA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S,OACb,EAAO,CAOd,MANA,MAAM,yBACJ,IAAI,EACF,sEACA,CAAE,KAAM,CAAE,OAAQ,SAAU,OAAQ,eAAgB,CAAE,CACvD,CACF,CACK,IAGX,CAAC,CAGJ,yBAA4C,EAAqB,EAejE,MAAyB,eAEvB,CACA,IAAM,EAAS,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CACnE,GAAI,EAAE,kBAAmB,GACvB,MAAM,EAA+B,KAAK,WAAW,CAEvD,IAAM,EAAa,MAAM,EAAO,eAAe,CAC/C,MAAO,CACL,QAAS,EACT,aACE,EAAW,SAAS,CACb,QAAQ,SAAS,EAE3B,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,SAAU,EAAmB,CACnE,GAAM,CAAE,OAAM,UAAS,eAAgB,EAWvC,OAAO,EAAiD,EAVzC,IAAI,aAAa,CAE9B,8BACE,EAA2C,EAAO,CACpD,UAAW,EAAuB,EAAO,CACzC,OACA,UACA,cACD,CAAC,CAEqE"}
|
|
1
|
+
{"version":3,"file":"mysql2.mjs","names":[],"sources":["../src/drivers/shared/mysql-utils.ts","../src/drivers/mysql2/index.ts"],"sourcesContent":["/**\n * Shared MySQL Utilities\n *\n * Shared connection utilities for MySQL-based drivers.\n */\n\nimport { ClientInitializationError } from \"@errors\";\n\n/**\n * The connection options a MySQL database URL carries: only the keys it\n * spells, so merged under a caller's options it fills what they left out\n * instead of replacing it with `undefined` or a default port.\n */\nexport interface MySQLConnectionOptions {\n [option: string]: unknown;\n ssl?: object | string;\n host: string;\n port?: number;\n /** Absent when the URL carries no database path. */\n database?: string;\n user?: string;\n password?: string;\n}\n\nconst TLS_URL_OPTION_PATTERN = /^(?:ssl|tls)/i;\n\n/**\n * A TLS request VibORM cannot honour. Its own text, which carries no part of\n * the URL, so the driver surfaces it rather than redacting it.\n */\nfunction tlsRefusal(message: string): ClientInitializationError {\n return new ClientInitializationError(message, {\n meta: { driver: \"mysql2\", operation: \"configuration\" },\n });\n}\n\nexport function parseMySQLUrl(url: string): MySQLConnectionOptions {\n const parsed = new URL(url);\n const database = decodeURIComponent(parsed.pathname.slice(1));\n const queryOptions: Record<string, unknown> = {};\n for (const [key, value] of parsed.searchParams) {\n if (\n TLS_URL_OPTION_PATTERN.test(key) &&\n key !== \"ssl\" &&\n key !== \"sslmode\"\n ) {\n throw tlsRefusal(\n \"Unsupported MySQL TLS URL option; configure options.ssl explicitly.\"\n );\n }\n try {\n queryOptions[key] = JSON.parse(value);\n } catch {\n queryOptions[key] = value;\n }\n }\n // mysql2 understands ssl, but not libpq's sslmode. Refuse a TLS request\n // whose policy cannot be represented instead of silently opening plaintext.\n const sslmode = parsed.searchParams.get(\"sslmode\");\n if (sslmode && sslmode !== \"disable\") {\n if (![\"require\", \"verify-ca\", \"verify-full\"].includes(sslmode)) {\n throw tlsRefusal(\n \"Unsupported MySQL sslmode; configure options.ssl explicitly.\"\n );\n }\n if (\n queryOptions.ssl !== undefined &&\n (queryOptions.ssl === null ||\n (typeof queryOptions.ssl !== \"object\" &&\n typeof queryOptions.ssl !== \"string\"))\n )\n throw tlsRefusal(\"MySQL sslmode requires a TLS configuration\");\n queryOptions.ssl ??= {};\n }\n Reflect.deleteProperty(queryOptions, \"sslmode\");\n const user = decodeURIComponent(parsed.username);\n const password = decodeURIComponent(parsed.password);\n return {\n host: parsed.hostname,\n ...(parsed.port ? { port: Number.parseInt(parsed.port, 10) } : {}),\n ...(database === \"\" ? {} : { database }),\n ...(user === \"\" ? {} : { user }),\n ...(password === \"\" ? {} : { password }),\n ...queryOptions,\n };\n}\n","/**\n * MySQL2 Driver\n *\n * Driver implementation for mysql2/promise with connection pooling.\n */\n\nimport { Buffer } from \"node:buffer\";\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { MySQLAdapter } from \"@adapters/databases/mysql/mysql-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n ClientInitializationError,\n isVibORMError,\n QueryError,\n TransactionError,\n} from \"@errors\";\nimport type { Pool, PoolConnection, PoolOptions } from \"mysql2/promise\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n isNormalizedResultRow,\n type NormalizedResultContext,\n normalizeProviderInsertId,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n isolationLevelStatement,\n type MigrationNamespaceAttestation,\n type MySQLConnectionOptions,\n nestedTransactionDispatchError,\n type PinnedSessionReservation,\n parseMySQLUrl,\n resolveMigrationNamespaceAttestationOption,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type MySQL2Options = PoolOptions;\n\nexport interface MySQL2DriverOptions {\n pool?: Pool;\n options?: PoolOptions;\n databaseUrl?: string;\n /**\n * The MySQL database this driver's persistent objects live in. Omitted, the\n * target is derived from a driver-created pool's own configuration, and a\n * driver that resolves none keeps the existing unqualified mode.\n */\n namespace?: string;\n /**\n * Caller-owned assertion that qualified `database.table` references and the\n * pinned migration session's `USE` cannot be redirected by VTGate\n * schema-routing rules or an equivalent proxy. It selects nothing, is never\n * inferred, and only effectful live migration work requires it.\n */\n migrationNamespaceAttestation?: MigrationNamespaceAttestation;\n}\n\nexport type MySQL2ClientConfig<C extends DriverConfig> = MySQL2DriverOptions &\n C;\n\nconst MYSQL2_CONFIG_KEYS: Record<keyof MySQL2DriverOptions, true> = {\n pool: true,\n options: true,\n databaseUrl: true,\n namespace: true,\n migrationNamespaceAttestation: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\n/** mysql2 escapes plain Uint8Array as an object — convert to Buffer for blobs. */\nfunction convertValuesForMySQL(values: unknown[]): unknown[] {\n return values.map((v) =>\n v instanceof Uint8Array && !Buffer.isBuffer(v)\n ? Buffer.from(v.buffer, v.byteOffset, v.byteLength)\n : v\n );\n}\n\nfunction isMultiStatementFields(fields: unknown): boolean {\n return (\n Array.isArray(fields) &&\n fields.every(\n (fieldSet) => fieldSet === undefined || Array.isArray(fieldSet)\n )\n );\n}\n\nfunction malformedMySQL2Result(operation: string, reason: string): QueryError {\n return new QueryError(\n `Driver \"mysql2\" returned a malformed result for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"mysql2\", operation } }\n );\n}\n\nconst CANONICAL_NEGATIVE_DECIMAL = /^-[1-9]\\d*$/;\n\n/** mysql2 echoes an explicit negative AUTO_INCREMENT key in ResultSetHeader.insertId. */\nfunction normalizeMySQL2InsertId(\n value: unknown,\n context: NormalizedResultContext\n): number | bigint | undefined {\n if (\n (typeof value === \"number\" && Number.isSafeInteger(value) && value < 0) ||\n (typeof value === \"string\" && CANONICAL_NEGATIVE_DECIMAL.test(value))\n ) {\n return undefined;\n }\n return normalizeProviderInsertId(value, context, { allowNumber: true });\n}\n\n/** SELECT returns a row array; mutations return a ResultSetHeader. */\nfunction toQueryResult<T>(\n result: unknown,\n fields: unknown,\n operation: string\n): QueryResult<T> {\n if (isMultiStatementFields(fields)) {\n throw new QueryError(\n `Driver \"mysql2\" returned multiple statement results for operation \"${operation}\"; VibORM requires exactly one statement result.`,\n { meta: { driver: \"mysql2\", operation } }\n );\n }\n\n if (Array.isArray(result)) {\n if (\n !Array.isArray(fields) ||\n fields.some((field) => !isNormalizedResultRow(field))\n ) {\n throw malformedMySQL2Result(\n operation,\n \"row arrays require one flat field metadata array\"\n );\n }\n return {\n rows: result as T[],\n rowCount: result.length,\n };\n }\n\n if (fields !== undefined) {\n throw malformedMySQL2Result(\n operation,\n \"mutation results require undefined field metadata\"\n );\n }\n if (!isNormalizedResultRow(result)) {\n throw malformedMySQL2Result(operation, \"expected a mutation result object\");\n }\n const context = { provider: \"mysql2\", operation };\n const insertId = normalizeMySQL2InsertId(result.insertId, context);\n return {\n rows: [] as T[],\n rowCount: normalizeProviderRowCount(result.affectedRows, context, {\n allowDecimalString: true,\n }),\n ...(insertId === undefined ? {} : { insertId }),\n };\n}\n\n/**\n * The target derived from a pool this driver will create: the `database` it\n * connects with, which is the caller's option when given and otherwise the\n * URL's path (see `resolveMySQL2Configuration`). A supplied `Pool` is opaque —\n * VibORM does not inspect mysql2 internals, so only an explicit `namespace` can\n * bind one. A pathless URL contributes nothing, and neither does an empty\n * `options.database`: §1.3's empty candidate is an absent one rather than a\n * name handed to identifier validation. A non-empty derived name is validated\n * exactly like an explicit one, by the adapter that installs it.\n */\nfunction deriveMySQL2Namespace(\n configuration: Omit<MySQL2Configuration, \"namespace\">\n): string | undefined {\n if (configuration.suppliedPool) return undefined;\n const configured = configuration.connectionOptions.database;\n return configured === \"\" ? undefined : configured;\n}\n\n/** What this driver settles from its caller's object, each source read once. */\ninterface MySQL2Configuration {\n readonly namespace: string | undefined;\n /**\n * The EXACT pool the caller supplied, or absent when this driver makes its\n * own. Identity, settled once, is the whole ownership answer: the caller's\n * options object is theirs to change, and a `pool` key deleted after\n * construction used to make `$disconnect()` end a transport VibORM was handed.\n */\n readonly suppliedPool: Pool | undefined;\n /**\n * The caller's connection record, copied once, over the keys its\n * `databaseUrl` carries: the URL fills only what the record leaves out, and\n * a key the record sets to `undefined` (an unset environment variable) is\n * left out. A per-tenant URL plus a password from a secret is this shape.\n *\n * A copy of THIS record, not of what it points at: a nested `ssl` object or\n * stream is the caller's to own, and the keys that decide where a pool\n * connects — host, port, user, database — all live here. It is also what the\n * constructor's refusals read, so the options this driver validated are the\n * exact options it later connects with.\n */\n readonly connectionOptions: PoolOptions;\n}\n\n/**\n * The one immutable ORM target for this driver, in the plan's exact order: an\n * explicit `namespace`, then the driver-created pool's own derivation.\n *\n * `databaseUrl` is read once and parsed once, here, and the parse is kept: a\n * second read at connect time would let a caller-owned accessor hand the\n * provider a different URL than the one that decided the target. A present URL\n * is parsed even when an explicit `namespace` outranks it, because an unusable\n * connection string is a construction failure either way; `\"\"`, `null`, and an\n * absent property are the same absent request. Both rules are the convenience\n * wrapper's too, so the two entry points cannot disagree.\n *\n * None of these sources is transport evidence: the attestation is read\n * separately and never derived from a resolved target.\n */\nfunction resolveMySQL2Configuration(\n options: MySQL2DriverOptions\n): MySQL2Configuration {\n const explicit = resolveNamespaceOption(options);\n const databaseUrl = options.databaseUrl;\n const urlOptions = databaseUrl\n ? parseMySQL2ConfiguredUrl(databaseUrl)\n : undefined;\n const connectionOptions: PoolOptions = { ...urlOptions };\n for (const [key, value] of Object.entries(options.options ?? {})) {\n if (value !== undefined) Reflect.set(connectionOptions, key, value);\n }\n const captured = { suppliedPool: options.pool, connectionOptions };\n return {\n namespace: explicit ?? deriveMySQL2Namespace(captured),\n ...captured,\n };\n}\n\n/**\n * The URL now decides a target, so a malformed one fails at construction. A\n * TLS refusal is VibORM's own secret-free text and passes through; the URL\n * parser's failure can carry the URL, so it is replaced and redacted.\n */\nfunction parseMySQL2ConfiguredUrl(databaseUrl: string): MySQLConnectionOptions {\n try {\n return parseMySQLUrl(databaseUrl);\n } catch (cause) {\n if (isVibORMError(cause)) throw cause;\n throw new ClientInitializationError(\n 'Driver \"mysql2\" could not parse its databaseUrl.',\n { cause: cause instanceof Error ? cause : undefined }\n );\n }\n}\n\nexport class MySQL2Driver extends Driver<Pool, PoolConnection> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n /** The caller's pool and connection record, as construction captured them. */\n private readonly suppliedPool: Pool | undefined;\n private readonly connectionOptions: PoolOptions;\n\n constructor(options: MySQL2DriverOptions = {}) {\n // Both facts are read before `super(...)` so the transport assertion is\n // installed by the base constructor and no option can be read twice.\n const attestation = resolveMigrationNamespaceAttestationOption(options);\n const configuration = resolveMySQL2Configuration(options);\n super(\"mysql\", \"mysql2\", {}, attestation);\n if (configuration.connectionOptions.multipleStatements === true) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support options.multipleStatements=true because VibORM operations require one result per statement.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n if (configuration.connectionOptions.rowsAsArray === true) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support options.rowsAsArray=true because VibORM requires row objects keyed by column name.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n if (\n configuration.connectionOptions.nestTables === true ||\n typeof configuration.connectionOptions.nestTables === \"string\"\n ) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support enabled options.nestTables because VibORM requires flat row objects keyed by result aliases.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n this.suppliedPool = configuration.suppliedPool;\n this.connectionOptions = configuration.connectionOptions;\n defineImmutableDriverFact(\n this,\n \"adapter\",\n new MySQLAdapter(configuration.namespace)\n );\n if (this.suppliedPool) {\n this.client = this.suppliedPool;\n }\n }\n\n /**\n * The pool this driver connects through.\n *\n * A caller's pool is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second pool behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<Pool> {\n if (this.suppliedPool !== undefined) {\n return this.suppliedPool;\n }\n const mysql = await import(\"mysql2/promise\");\n\n let options: PoolOptions = {\n // DATETIME is stored as naive UTC wall-clock; read it back as UTC\n // instead of shifting by the process timezone\n timezone: \"Z\",\n // BIGINT/DECIMAL values outside Number's safe range arrive as strings\n // (the result parser converts them losslessly) instead of lossy numbers\n supportBigNumbers: true,\n // DATE as plain \"YYYY-MM-DD\" — the result parser builds a UTC-midnight\n // Date, matching every other driver (mysql2 would build local midnight)\n dateStrings: [\"DATE\"],\n // Already merged with the URL, from the one parse construction made:\n // this driver never re-reads the caller's `databaseUrl`.\n ...this.connectionOptions,\n };\n\n // The pool this driver creates defaults to the same database the adapter\n // qualifies with, whichever source resolved it. A supplied pool never\n // reaches here, so VibORM never changes a caller's connection state.\n if (this.adapter.namespace !== undefined) {\n options = { ...options, database: this.adapter.namespace };\n }\n\n return mysql.createPool(options);\n }\n\n /**\n * Ends only a pool this driver created.\n *\n * A supplied pool belongs to the caller, who may be sharing it with other\n * clients or with their own code, and §5.3's rule is that VibORM never\n * changes a caller's connection state. `$disconnect()` used to end it\n * regardless, so disconnecting one client tore down every other consumer of\n * that pool.\n *\n * The test is on the pool's IDENTITY against what construction captured, so\n * it answers for the pool actually being closed rather than for whatever the\n * caller's record says now: every pool this driver made is ended, and the one\n * it was handed never is.\n */\n protected async closeClient(pool: Pool): Promise<void> {\n if (pool === this.suppliedPool) {\n return;\n }\n await pool.end();\n }\n\n protected async execute<T>(\n client: Pool | PoolConnection,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n const [result, fields] = await client.query({\n sql,\n values: convertValuesForMySQL(params),\n // Per-statement decoding also covers borrowed pools without mutating\n // their connection options. Text protocol avoids a statement per IN size.\n typeCast: (field, next) =>\n [\"DATE\", \"DATETIME\", \"TIMESTAMP\", \"LONGLONG\", \"NEWDECIMAL\"].includes(\n field.type\n )\n ? field.string()\n : next(),\n });\n return toQueryResult<T>(result, fields, operation);\n }\n\n protected async executeRaw<T>(\n client: Pool | PoolConnection,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const [result, fields] = await client.query(\n sql,\n params && convertValuesForMySQL(params)\n );\n return toQueryResult<T>(result, fields, operation);\n }\n\n /**\n * MySQL rejects `SET TRANSACTION ISOLATION LEVEL` once a transaction is open\n * (ER_CANT_CHANGE_TX_CHARACTERISTICS), so the level must be set on the\n * transaction's own connection *before* BEGIN, where it applies to exactly\n * the next transaction on that session. mysql2 pools hand out a connection we\n * can wait for with a bound and release if we stop waiting.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"pre-begin\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: Pool | PoolConnection,\n fn: (tx: PoolConnection) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (!(\"getConnection\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n // Start a new transaction from pool\n const pool = client as Pool;\n const connection = await acquireWithMaxWait(\n () => pool.getConnection(),\n (acquired) => acquired.release(),\n options?.maxWaitMs,\n { driverName: this.driverName, form: \"callback\" }\n );\n let shouldDestroy = false;\n const runOrDestroy = async (operation: () => Promise<void>) => {\n try {\n await operation();\n } catch (error) {\n shouldDestroy = true;\n throw error;\n }\n };\n const isolationLevel = options?.isolationLevel;\n return runTransactionLifecycle({\n begin: () =>\n runOrDestroy(async () => {\n // Session-scoped-next-transaction: this statement must land before\n // beginTransaction() to bind to the transaction it opens.\n if (isolationLevel) {\n await connection.query(isolationLevelStatement(isolationLevel));\n }\n await connection.beginTransaction();\n }),\n callback: () => fn(connection),\n commit: () => runOrDestroy(() => connection.commit()),\n rollback: () => runOrDestroy(() => connection.rollback()),\n phases: getExecutionTransactionPhases(context),\n close: () => {\n try {\n if (shouldDestroy) {\n connection.destroy();\n return;\n }\n connection.release();\n } catch (error) {\n super.transactionCleanupFailed(\n new TransactionError(\n 'Driver \"mysql2\" could not release an unsafe transaction connection.',\n { meta: { driver: \"mysql2\", method: \"$transaction\" } }\n )\n );\n throw error;\n }\n },\n });\n }\n\n protected override transactionCleanupFailed(_error: Error): void {\n // A connection with failed cleanup is destroyed; the pool remains usable.\n }\n\n /**\n * One `PoolConnection` from `pool.getConnection()` — plan §3.5's pinned\n * producer for MySQL2.\n *\n * It is ALWAYS destroyed, never released, and the `discard` flag is therefore\n * ignored: this session has executed `USE` to select the migration target and\n * may have executed author-owned statements from a manual artifact, and\n * mysql2's release resets neither. Returning it to an owned or a supplied\n * pool would leak that state into unrelated queries. This is correctness, not\n * an optimization.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<Pool | PoolConnection>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (!(\"getConnection\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const connection = await client.getConnection();\n return {\n session: connection,\n release: () => {\n connection.destroy();\n return Promise.resolve();\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: MySQL2ClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, MySQL2DriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: MySQL2Driver }\n >]: LinkedClientConfig<C & { driver: MySQL2Driver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"mysql2\", MYSQL2_CONFIG_KEYS);\n const { pool, options, databaseUrl } = config;\n const driver = new MySQL2Driver({\n // Attestation first, then namespace: the order a refusal reports in.\n migrationNamespaceAttestation:\n resolveMigrationNamespaceAttestationOption(config),\n namespace: resolveNamespaceOption(config),\n pool,\n options,\n databaseUrl,\n });\n\n return createClientFromDriverConfig<S, C, MySQL2Driver>(config, driver);\n}\n"],"mappings":"ojBAwBA,MAAM,EAAyB,gBAM/B,SAAS,WAAW,EAA4C,CAC9D,OAAO,IAAI,EAA0B,EAAS,CAC5C,KAAM,CAAE,OAAQ,SAAU,UAAW,gBAAiB,CACvD,CAAC,CAGJ,SAAgB,cAAc,EAAqC,CACjE,IAAM,EAAS,IAAI,IAAI,EAAI,CACrB,EAAW,mBAAmB,EAAO,SAAS,MAAM,EAAE,CAAC,CACvD,EAAwC,EAAE,CAChD,IAAK,GAAM,CAAC,EAAK,KAAU,EAAO,aAAc,CAC9C,GACE,EAAuB,KAAK,EAAI,EAChC,IAAQ,OACR,IAAQ,UAER,MAA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S,eAChC,OAAO,EAAwB,CAC7B,UACE,aAAa,SAAY,CAGnB,GACF,MAAM,EAAW,MAAM,EAAwB,EAAe,CAAC,CAEjE,MAAM,EAAW,kBAAkB,EACnC,CACJ,aAAgB,EAAG,EAAW,CAC9B,WAAc,iBAAmB,EAAW,QAAQ,CAAC,CACrD,aAAgB,iBAAmB,EAAW,UAAU,CAAC,CACzD,OAAQ,EAA8B,EAAQ,CAC9C,UAAa,CACX,GAAI,CACF,GAAI,EAAe,CACjB,EAAW,SAAS,CACpB,OAEF,EAAW,SAAS,OACb,EAAO,CAOd,MANA,MAAM,yBACJ,IAAI,EACF,sEACA,CAAE,KAAM,CAAE,OAAQ,SAAU,OAAQ,eAAgB,CAAE,CACvD,CACF,CACK,IAGX,CAAC,CAGJ,yBAA4C,EAAqB,EAejE,MAAyB,eAEvB,CACA,IAAM,EAAS,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CACnE,GAAI,EAAE,kBAAmB,GACvB,MAAM,EAA+B,KAAK,WAAW,CAEvD,IAAM,EAAa,MAAM,EAAO,eAAe,CAC/C,MAAO,CACL,QAAS,EACT,aACE,EAAW,SAAS,CACb,QAAQ,SAAS,EAE3B,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,SAAU,EAAmB,CACnE,GAAM,CAAE,OAAM,UAAS,eAAgB,EAWvC,OAAO,EAAiD,EAVzC,IAAI,aAAa,CAE9B,8BACE,EAA2C,EAAO,CACpD,UAAW,EAAuB,EAAO,CACzC,OACA,UACA,cACD,CAAC,CAEqE"}
|
|
@@ -1,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-6wCGP1a1.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"native-types-BbKWN3JV.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,C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,KAAM,EAAO,OAAO,CACrB,CAGD,KAAM,CACJ,KAAM,EAAO,OAAO,CACrB,CACF"}
|
|
1
|
+
{"version":3,"file":"native-types-6wCGP1a1.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,EAAG,SAAS,CACpB,KAAM,EAAG,OAAO,CAChB,IAAK,MAAM,KAAM,MAAM,CAEvB,OAAS,IAAyC,CAChD,GAAI,KACJ,KAAM,EAAI,UAAU,EAAE,GAAK,SAC5B,EACD,IAAK,EAAG,MAAM,CACd,KAAM,EAAG,OAAO,CAChB,KAAM,EAAG,OAAO,CAChB,QAAS,EAAG,UAAU,CACtB,SAAU,EAAG,WAAW,CACxB,SAAU,EAAG,WAAW,CACxB,QAAS,EAAG,UAAU,CACvB,CAGD,IAAK,CACH,SAAU,EAAG,WAAW,CACxB,QAAS,EAAG,UAAU,CACtB,IAAK,EAAG,MAAM,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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, An as
|
|
1
|
+
import { A as Schema, An as TransactionOptionSupport, At as DriverConfig, F as LinkedClientConfig, Fn as QueryResult, Ft as VibORMClient, Mn as CommittedBatchNotification, On as BatchTransactionOptions, Pn as QueryExecutionContext, Pt as NoExtraDriverConfigKeys, jn as BatchQuery, s as DatabaseAdapter, u as Driver } from "./index-DRX_LLQM.mjs";
|
|
2
2
|
import { NeonQueryFunction } from "@neondatabase/serverless";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/neon-http/index.d.ts
|
package/dist/neon-http.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./normalized-result-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./normalized-result-23DWxZVY.mjs";import{h as n}from"./error-mapping-DRY49A3C.mjs";import{d as r,t as i}from"./query-CTna5P9o.mjs";import{n as a}from"./client-BqgVSbk0.mjs";import{c as o,d as s,t as c}from"./driver-szWYBmjD.mjs";import{t as l}from"./postgres-result-DYeVeHuT.mjs";import{t as u}from"./postgres-adapter-DxhZu7Qw.mjs";const d={databaseUrl:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!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,relationsPerStatement:e.relationsPerStatement,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 /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n /** The most relations (`FROM` items) one statement may reference: past it, a statement repeating recursive filters states them as key sets, which some plans pay for. Set 256 for PlanetScale Neki, which refuses more. Absent: unbounded. Only where relation bodies are shared. */\n relationsPerStatement?: number;\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 relationsPerStatement: 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 relationsPerStatement: config.relationsPerStatement,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, NeonHTTPDriver>(config, driver);\n}\n"],"mappings":"6YAiEA,MAAM,EAAmE,CACvE,YAAa,GACb,QAAS,GACT,SAAU,GACV,QAAS,GACT,qBAAsB,GACtB,sBAAuB,GACvB,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,qB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,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,EAC9C,EAAY,EAAuB,EAAO,CAYhD,OAAO,EAAmD,EAV3C,IAAI,eAAe,CAChC,cACA,UACA,WACA,UACA,qBAAsB,EAAO,qBAC7B,sBAAuB,EAAO,sBAC9B,YACD,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 most relations (`FROM` items) one statement may reference: past it, a statement repeating recursive filters states them as key sets, which some plans pay for. Set 256 for PlanetScale Neki, which refuses more. Absent: unbounded. Only where relation bodies are shared. */\n relationsPerStatement?: number;\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 relationsPerStatement: 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 relationsPerStatement: config.relationsPerStatement,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, NeonHTTPDriver>(config, driver);\n}\n"],"mappings":"wYAiEA,MAAM,EAAmE,CACvE,YAAa,GACb,QAAS,GACT,SAAU,GACV,QAAS,GACT,qBAAsB,GACtB,sBAAuB,GACvB,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,cAAoC,CAA6B,CAE/D,8BAA6D,MAI7D,qBAAgC,GAChC,cAAyB,GAIzB,iCAA4C,GAE5C,cACA,WAEA,YAAY,EAA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
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{r as t}from"./value-guards-CK9guf2Z.mjs";import{n}from"./base-wlv81COV.mjs";import{d as r}from"./query-CTna5P9o.mjs";import{t as i}from"./sql-DGtEeP8z.mjs";const a=typeof Symbol.asyncDispose==`symbol`?Symbol.asyncDispose:void 0,o=Symbol(`viborm.verbatimBatchQuery`);function markVerbatimBatchQuery(e){return Object.defineProperty(e,o,{configurable:!1,enumerable:!1,value:!0,writable:!1}),e}function isVerbatimBatchQuery(e){return Reflect.get(e,o)===!0}const s=new WeakMap;function registerPreparedStatement(e,t){s.set(e,t)}function transferPreparedStatement(e,t){let n=s.get(e);return n!==void 0&&s.set(t,n),t}function snapshotPreparedStatement(e,t,n){let r=s.get(e);return r!==void 0&&s.set(t,new i([...r.strings],[...n])),t}function readPreparedStatement(e){return s.get(e)}const c=/^(?:0|[1-9]\d*)$/;function captureBuiltinPrototype(e){let t=[];for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);r&&t.push({descriptor:r,key:n})}return Object.freeze(t)}const l=captureBuiltinPrototype(Object.prototype),u=captureBuiltinPrototype(Array.prototype);function isArrayIndex(e){if(typeof e!=`string`||!c.test(e))return!1;let t=Number(e);return t<=4294967294&&String(t)===e}function functionSource(e){if(typeof e==`function`)try{return Function.prototype.toString.call(e)}catch{return}}function sameInertRecord(e,t){if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return Object.is(e,t);try{if(Object.getPrototypeOf(e)!==null||Object.getPrototypeOf(t)!==null)return!1;let n=Reflect.ownKeys(e),r=Reflect.ownKeys(t);if(n.length!==r.length)return!1;for(let i=0;i<r.length;i+=1){let a=n[i],o=r[i];if(a!==o||o===void 0)return!1;let s=Object.getOwnPropertyDescriptor(e,o),c=Object.getOwnPropertyDescriptor(t,o);if(s===void 0||c===void 0||!(`value`in s)||!(`value`in c)||s.configurable!==c.configurable||s.enumerable!==c.enumerable||s.writable!==c.writable||!Object.is(s.value,c.value))return!1}return!0}catch{return!1}}function sameBuiltinDescriptor(e,t){if(e.configurable!==t.configurable||e.enumerable!==t.enumerable||`value`in e!=`value`in t)return!1;if(`value`in e&&`value`in t){if(e.writable!==t.writable)return!1;let n=functionSource(t.value);return n===void 0?sameInertRecord(e.value,t.value):functionSource(e.value)===n}return functionSource(e.get)===functionSource(t.get)&&functionSource(e.set)===functionSource(t.set)}function hasBuiltinPrototypeShape(e,t){try{let n=Reflect.ownKeys(e);if(n.length!==t.length)return!1;for(let r=0;r<t.length;r+=1){let i=t[r];if(i===void 0||n[r]!==i.key)return!1;let a=Object.getOwnPropertyDescriptor(e,i.key);if(a===void 0||!sameBuiltinDescriptor(a,i.descriptor))return!1}return!0}catch{return!1}}function isObjectPrototype(e){try{return Object.getPrototypeOf(e)===null&&hasBuiltinPrototypeShape(e,l)}catch{return!1}}function isArrayPrototype(e){try{let t=Object.getPrototypeOf(e);return t!==null&&isObjectPrototype(t)&&hasBuiltinPrototypeShape(e,u)}catch{return!1}}function rawParameterNodeShape(e){let t=!1;try{t=Array.isArray(e);let n=Object.getPrototypeOf(e);if(t&&n!==null&&!isArrayPrototype(n)||!t&&n!==null&&!isObjectPrototype(n))return{kind:t?`unsupported-array`:`opaque`};let r=[],i=[];for(let n of Reflect.ownKeys(e)){let a=Object.getOwnPropertyDescriptor(e,n);if(a!==void 0&&(i.push({descriptor:a,key:n}),t?isArrayIndex(n):a.enumerable&&typeof n==`string`)){if(!(`value`in a))return{kind:t?`unsupported-array`:`opaque`};r.push({descriptor:a,key:n,value:a.value})}}let a=i.find(e=>e.key===`toJSON`);return a&&(!(`value`in a.descriptor)||typeof a.descriptor.value==`function`)?{kind:t?`unsupported-array`:`opaque`}:{kind:`node`,shape:{edges:r,isArray:t,properties:i,prototype:n}}}catch{return{kind:t?`unsupported-array`:`opaque`}}}function rawDateTime(e,n,r){if(!t(e))return;let i=Date.prototype.getTime.call(e);if(Number.isNaN(i))throw r(n);return i}function analyzeRawParameterGraph(e,t){let n=new WeakMap,r=new WeakMap,i=[],a=Array(e.length),discover=(e,a)=>{let o=rawDateTime(e,a,t.invalidDate);if(o!==void 0&&typeof e==`object`&&e){r.set(e,o);return}if(typeof e!=`object`||!e)return;let s=n.get(e);if(s)return s;let c=rawParameterNodeShape(e);if(c.kind===`unsupported-array`)throw t.unsupportedArray(a);if(c.kind===`opaque`)return;let l={...c.shape,source:e};return n.set(e,l),i.push(l),l};for(let n=0;n<e.length;n++){if(!Object.hasOwn(e,n))continue;let o=e[n];a[n]=o;let s=rawDateTime(o,n,t.invalidDate);if(s!==void 0&&typeof o==`object`&&o){r.set(o,s);continue}let c=discover(o,n);if(!c)continue;let l=[c],u=0;for(;u<l.length;){let e=l[u];if(u+=1,e)for(let t of e.edges){let e=i.length,r=discover(t.value,n);r&&i.length>e&&l.push(r)}}}return{dateTimes:r,nodes:i,roots:a}}function validateRawParameters(e,t){analyzeRawParameterGraph(e,t)}function snapshotRawParameterGraph(e,t){let n=analyzeRawParameterGraph(e,t),r=new WeakMap,i=new WeakMap;for(let e of n.nodes){let t=e.isArray?[]:{};e.prototype===null&&Object.setPrototypeOf(t,null),r.set(e.source,t)}let copiedValue=e=>{if(typeof e!=`object`||!e)return e;let t=n.dateTimes.get(e);if(t!==void 0){let n=i.get(e);if(n)return n;let r=new Date(t);return i.set(e,r),r}return r.get(e)??e};for(let e of n.nodes){let t=r.get(e.source);if(t){for(let n of e.properties){if(e.isArray&&n.key===`length`)continue;let r=n.descriptor;Object.defineProperty(t,n.key,`value`in r&&(e.isArray?isArrayIndex(n.key):r.enumerable&&typeof n.key==`string`)?{...r,value:copiedValue(r.value)}:r)}if(e.isArray){let n=e.properties.find(e=>e.key===`length`);n&&Object.defineProperty(t,`length`,n.descriptor)}}}let a=Array(n.roots.length);for(let e=0;e<n.roots.length;e++)Object.hasOwn(n.roots,e)&&(a[e]=copiedValue(n.roots[e]));return a}function invalidProviderDateError(e,t){return new r(`Operation "${e.operation??`statement`}" received an invalid Date as bound parameter ${t}. An invalid Date names no instant, so a provider either refuses the statement after dispatch or binds it as null.`,{code:n.INVALID_INPUT,meta:{parameterIndex:t,model:e.model,operation:e.operation,correlationId:e.correlationId}})}function unsupportedProviderArrayError(e,t){return new r(`Operation "${e.operation??`statement`}" received raw array parameter ${t} with custom inherited or accessor behavior. VibORM cannot validate that behavior without invoking caller code before dispatch.`,{code:n.INVALID_INPUT,meta:{parameterIndex:t,model:e.model,operation:e.operation,correlationId:e.correlationId}})}function snapshotProviderParameters(e,t){return t.model===`$raw`?snapshotRawParameterGraph(e,{invalidDate:e=>invalidProviderDateError(t,e),unsupportedArray:e=>unsupportedProviderArrayError(t,e)}):[...e]}function createNormalizedResultMeta(e){return{driver:e.provider,operation:e.operation,...e.model?{model:e.model}:{},...e.correlationId?{correlationId:e.correlationId}:{}}}const d=/^(?:0|[1-9]\d*)$/;function normalizeProviderRowCount(e,t,n){let i=e===null?n?.nullValue:e;if(n?.allowDecimalString===!0&&typeof i==`string`&&d.test(i)&&(i=Number(i)),typeof i!=`number`||!Number.isSafeInteger(i)||i<0)throw new r(`Driver "${t.provider}" returned a malformed row count for operation "${t.operation}".`,{meta:createNormalizedResultMeta(t)});return i}function normalizeProviderInsertId(e,t,n){if(typeof e==`string`){if(!d.test(e))throw malformedInsertId(t);return e===`0`?void 0:BigInt(e)}if(n?.allowNumber===!0&&typeof e==`number`){if(!Number.isSafeInteger(e)||e<0)throw malformedInsertId(t);return e===0?void 0:e}throw malformedInsertId(t)}function malformedInsertId(e){return new r(`Driver "${e.provider}" returned a malformed insert id for operation "${e.operation}".`,{meta:createNormalizedResultMeta(e)})}function malformedNormalizedResult(e,t){let n=t===void 0?``:` at batch result index ${t}`;return new r(`Driver "${e.provider}" returned a malformed normalized result for operation "${e.operation}"${n}; expected { rows: object[], rowCount: safe non-negative integer }.`,{meta:{...createNormalizedResultMeta(e),...t===void 0?{}:{resultIndex:t}}})}function isNormalizedResultRow(e){return typeof e==`object`&&!!e&&Object.prototype.toString.call(e)===`[object Object]`}function hasNormalizedRows(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t+=1)if(!(Object.hasOwn(e,t)&&isNormalizedResultRow(e[t])))return!1;return!0}function assertNormalizedQueryResult(e,t,n){let r=e?.insertId===void 0||typeof e.insertId==`bigint`&&e.insertId>=0n||typeof e.insertId==`number`&&Number.isFinite(e.insertId)&&Number.isSafeInteger(e.insertId)&&e.insertId>=0;if(!(isNormalizedResultRow(e)&&hasNormalizedRows(e.rows))||typeof e.rowCount!=`number`||!Number.isFinite(e.rowCount)||!Number.isSafeInteger(e.rowCount)||e.rowCount<0||!r)throw malformedNormalizedResult(t,n)}function assertNormalizedBatchResults(e,t,n){if(!Array.isArray(e)||e.length!==t){let i=Array.isArray(e)?e.length:0;throw new r(`Driver "${n.provider}" returned ${i} results for operation "${n.operation}"; expected ${t}, one per statement.`,{meta:{...createNormalizedResultMeta(n),expectedStatementCount:t,actualResultCount:i}})}for(let t=0;t<e.length;t+=1)assertNormalizedQueryResult(e[t],n,t)}export{normalizeProviderInsertId as a,validateRawParameters as c,snapshotPreparedStatement as d,transferPreparedStatement as f,a as h,isNormalizedResultRow as i,readPreparedStatement as l,markVerbatimBatchQuery as m,assertNormalizedQueryResult as n,normalizeProviderRowCount as o,isVerbatimBatchQuery as p,createNormalizedResultMeta as r,snapshotProviderParameters as s,assertNormalizedBatchResults as t,registerPreparedStatement as u};
|
|
2
|
+
//# sourceMappingURL=normalized-result-23DWxZVY.mjs.map
|