viborm 1.3.3 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-internals-AGgQRu5t.mjs → adapter-internals-Cy2QEBnH.mjs} +1 -1
- package/dist/{adapter-internals-AGgQRu5t.mjs.map → adapter-internals-Cy2QEBnH.mjs.map} +1 -1
- package/dist/{adapter-namespace-CWLEmon2.mjs → adapter-namespace-NnXlXR8c.mjs} +2 -2
- package/dist/{adapter-namespace-CWLEmon2.mjs.map → adapter-namespace-NnXlXR8c.mjs.map} +1 -1
- package/dist/adapter-result-parser-D6lluSMi.mjs +2 -0
- package/dist/adapter-result-parser-D6lluSMi.mjs.map +1 -0
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-BKdLfNzM.mjs → array-literal-BsbbSLw3.mjs} +1 -1
- package/dist/{array-literal-BKdLfNzM.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
- package/dist/{batch-refs-DGJPz8-G.mjs → batch-refs-BYCu1JnQ.mjs} +1 -1
- package/dist/{batch-refs-DGJPz8-G.mjs.map → batch-refs-BYCu1JnQ.mjs.map} +1 -1
- package/dist/bind-parameter-capacity-D6p9HrbB.mjs +2 -0
- package/dist/bind-parameter-capacity-D6p9HrbB.mjs.map +1 -0
- package/dist/builder-BxCr9ANq.mjs +2 -0
- package/dist/builder-BxCr9ANq.mjs.map +1 -0
- package/dist/bun-sql.d.mts +3 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/{canonical-json-BReb5nFO.mjs → canonical-json-acY4dQNQ.mjs} +2 -2
- package/dist/canonical-json-acY4dQNQ.mjs.map +1 -0
- package/dist/chain-C4EUyLzF.mjs +2 -0
- package/dist/chain-C4EUyLzF.mjs.map +1 -0
- package/dist/cli.mjs +1 -1
- package/dist/{client-DR0vYetv.d.mts → client-3FqgR4eS.d.mts} +3 -1
- package/dist/client-DUulrWw5.mjs +2 -0
- package/dist/client-DUulrWw5.mjs.map +1 -0
- package/dist/{client-DjtWangN.mjs → client-sAey5P-I.mjs} +16 -16
- package/dist/client-sAey5P-I.mjs.map +1 -0
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{clock-YTLtjLFS.mjs → clock-CJotKAxc.mjs} +1 -1
- package/dist/{clock-YTLtjLFS.mjs.map → clock-CJotKAxc.mjs.map} +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +1 -1
- package/dist/current-C2fZL9Ln.mjs +2 -0
- package/dist/current-C2fZL9Ln.mjs.map +1 -0
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/{datetime-physical-codec-qKxFtI3B.mjs → datetime-physical-codec-CFoeuitT.mjs} +2 -2
- package/dist/{datetime-physical-codec-qKxFtI3B.mjs.map → datetime-physical-codec-CFoeuitT.mjs.map} +1 -1
- package/dist/{driver-BvP7eW0A.mjs → driver-BqD-3_jO.mjs} +2 -2
- package/dist/{driver-BvP7eW0A.mjs.map → driver-BqD-3_jO.mjs.map} +1 -1
- package/dist/driver-DseQwbsu.mjs +2 -0
- package/dist/driver-DseQwbsu.mjs.map +1 -0
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-6op318w6.mjs.map +1 -1
- package/dist/every-CEQMQEdt.mjs +2 -0
- package/dist/{every-WUr3mlvg.mjs.map → every-CEQMQEdt.mjs.map} +1 -1
- package/dist/execution-context-asSCmyas.mjs +2 -0
- package/dist/execution-context-asSCmyas.mjs.map +1 -0
- package/dist/{fs-estate-azK36i9V.mjs → fs-estate-N_F2YqYa.mjs} +2 -2
- package/dist/{fs-estate-azK36i9V.mjs.map → fs-estate-N_F2YqYa.mjs.map} +1 -1
- package/dist/{geo-area-codec-BmMmWgU_.mjs → geo-area-codec-4W5b7whM.mjs} +2 -2
- package/dist/{geo-area-codec-BmMmWgU_.mjs.map → geo-area-codec-4W5b7whM.mjs.map} +1 -1
- package/dist/geo-point-codec-pAWYj5ZZ.mjs +2 -0
- package/dist/geo-point-codec-pAWYj5ZZ.mjs.map +1 -0
- package/dist/{hydration-BflrXEIQ.mjs → hydration-Az2rjp5a.mjs} +2 -2
- package/dist/{hydration-BflrXEIQ.mjs.map → hydration-Az2rjp5a.mjs.map} +1 -1
- package/dist/{identifier-conversion-Bs7A2GGU.mjs → identifier-conversion-ufaCNi9E.mjs} +2 -2
- package/dist/{identifier-conversion-Bs7A2GGU.mjs.map → identifier-conversion-ufaCNi9E.mjs.map} +1 -1
- package/dist/identity-CmRos0Yf.mjs +2 -0
- package/dist/identity-CmRos0Yf.mjs.map +1 -0
- package/dist/{index-B_jh2oaQ.d.mts → index-oVv9RLt5.d.mts} +1315 -1057
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/instrumentation.mjs.map +1 -1
- package/dist/{invariant-D57gi_yW.mjs → invariant-D_fIjY_z.mjs} +1 -1
- package/dist/{invariant-D57gi_yW.mjs.map → invariant-D_fIjY_z.mjs.map} +1 -1
- package/dist/{json-number-DvmiNx0n.mjs → json-number-CGXpPu4D.mjs} +1 -1
- package/dist/{json-number-DvmiNx0n.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
- package/dist/{key-B89Z4vxn.mjs → key-CyLRw0ne.mjs} +2 -2
- package/dist/{key-B89Z4vxn.mjs.map → key-CyLRw0ne.mjs.map} +1 -1
- package/dist/{libsql-C8dn4id0.mjs → libsql-DPrXWc_J.mjs} +2 -2
- package/dist/{libsql-C8dn4id0.mjs.map → libsql-DPrXWc_J.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-B7CcHS6I.mjs → memory-DiTWROVS.mjs} +2 -2
- package/dist/{memory-B7CcHS6I.mjs.map → memory-DiTWROVS.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +4 -4
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +4 -4
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +4 -4
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +4 -4
- package/dist/migrations.mjs +1 -1
- package/dist/mysql-adapter-B1U35CJn.mjs +2 -0
- package/dist/{mysql-adapter-ABpgFB2N.mjs.map → mysql-adapter-B1U35CJn.mjs.map} +1 -1
- package/dist/{mysql-mUmhH9Cf.mjs → mysql-fJlFIW7m.mjs} +2 -2
- package/dist/{mysql-mUmhH9Cf.mjs.map → mysql-fJlFIW7m.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/neon-http.d.mts +3 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/normalized-result-BF7gr4_b.mjs +2 -0
- package/dist/normalized-result-BF7gr4_b.mjs.map +1 -0
- package/dist/{object-store-Ds9NKRU6.d.mts → object-store-C56-FLkl.d.mts} +3 -3
- package/dist/{object-store-CZADAv4c.mjs → object-store-WjVilDvN.mjs} +2 -2
- package/dist/{object-store-CZADAv4c.mjs.map → object-store-WjVilDvN.mjs.map} +1 -1
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/pg.d.mts +26 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +3 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/{physical-uJfmo4-Z.mjs → physical-C4D-979R.mjs} +2 -2
- package/dist/{physical-uJfmo4-Z.mjs.map → physical-C4D-979R.mjs.map} +1 -1
- package/dist/{pinned-session-C79aDzOg.mjs → pinned-session-FYOFV_gB.mjs} +2 -2
- package/dist/{pinned-session-C79aDzOg.mjs.map → pinned-session-FYOFV_gB.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-DHZG9Vy7.d.mts → planner-C3KX6S85.d.mts} +1 -1
- package/dist/{postgres-BACQ_wqF.mjs → postgres-DD92WdFu.mjs} +2 -2
- package/dist/{postgres-BACQ_wqF.mjs.map → postgres-DD92WdFu.mjs.map} +1 -1
- package/dist/postgres-adapter-B7hzWhky.mjs +2 -0
- package/dist/postgres-adapter-B7hzWhky.mjs.map +1 -0
- package/dist/postgres-adapter-CJmoxTW7.mjs +2 -0
- package/dist/{postgres-adapter-DaMvNOkx.mjs.map → postgres-adapter-CJmoxTW7.mjs.map} +1 -1
- package/dist/postgres-result-BCUQf8b_.mjs +2 -0
- package/dist/{postgres-result-D403cLyA.mjs.map → postgres-result-BCUQf8b_.mjs.map} +1 -1
- package/dist/postgres.d.mts +3 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-DSv2tYFr.mjs → provider-limits-D0ECF7_Q.mjs} +2 -2
- package/dist/{provider-limits-DSv2tYFr.mjs.map → provider-limits-D0ECF7_Q.mjs.map} +1 -1
- package/dist/relation-bound-BrZLsSke.mjs +2 -0
- package/dist/relation-bound-BrZLsSke.mjs.map +1 -0
- package/dist/{result-parsing-8wEK3GY1.mjs → result-parsing-CQf_eCl8.mjs} +1 -1
- package/dist/{result-parsing-8wEK3GY1.mjs.map → result-parsing-CQf_eCl8.mjs.map} +1 -1
- package/dist/result-shape-ic2j3Tze.mjs +2 -0
- package/dist/result-shape-ic2j3Tze.mjs.map +1 -0
- package/dist/{rows-v1VuwOTa.mjs → rows-YyvK9MDz.mjs} +2 -2
- package/dist/{rows-v1VuwOTa.mjs.map → rows-YyvK9MDz.mjs.map} +1 -1
- package/dist/{scalar-Cm7nMFmO.mjs → scalar-Dyns7kc7.mjs} +2 -2
- package/dist/{scalar-Cm7nMFmO.mjs.map → scalar-Dyns7kc7.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/{schema-D3-ScVH6.mjs → schema-CUm_yh6L.mjs} +2 -2
- package/dist/{schema-D3-ScVH6.mjs.map → schema-CUm_yh6L.mjs.map} +1 -1
- package/dist/{schema-introspection-TdJrSaKd.mjs → schema-introspection-LpRNeSG2.mjs} +2 -2
- package/dist/{schema-introspection-TdJrSaKd.mjs.map → schema-introspection-LpRNeSG2.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/select-assembly-BjT_fDbu.mjs +2 -0
- package/dist/select-assembly-BjT_fDbu.mjs.map +1 -0
- package/dist/{settle-etgtP1WM.mjs → settle-C4w1GfTU.mjs} +2 -2
- package/dist/{settle-etgtP1WM.mjs.map → settle-C4w1GfTU.mjs.map} +1 -1
- package/dist/{sha256-CEYo7k7R.mjs → sha256-_Nu4s32f.mjs} +1 -1
- package/dist/{sha256-CEYo7k7R.mjs.map → sha256-_Nu4s32f.mjs.map} +1 -1
- package/dist/soft-delete.d.mts +3 -3
- package/dist/{sql-statement-tokens-BW7Q-rF-.mjs → sql-statement-tokens-4J5l5Lyt.mjs} +1 -1
- package/dist/{sql-statement-tokens-BW7Q-rF-.mjs.map → sql-statement-tokens-4J5l5Lyt.mjs.map} +1 -1
- package/dist/sqlite-adapter-B3dRr5fl.mjs +2 -0
- package/dist/sqlite-adapter-B3dRr5fl.mjs.map +1 -0
- package/dist/{sqlite-utils-BvSlEs5W.mjs → sqlite-utils-C5_KQPZn.mjs} +2 -2
- package/dist/{sqlite-utils-BvSlEs5W.mjs.map → sqlite-utils-C5_KQPZn.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-CYdZ_KXH.mjs → standard-sql-DmKF8msN.mjs} +2 -2
- package/dist/{standard-sql-CYdZ_KXH.mjs.map → standard-sql-DmKF8msN.mjs.map} +1 -1
- package/dist/{to-many-Btc9X5Ga.mjs → to-many-DxQuOBuq.mjs} +2 -2
- package/dist/{to-many-Btc9X5Ga.mjs.map → to-many-DxQuOBuq.mjs.map} +1 -1
- package/dist/transaction-operation-CU1zlxiG.mjs.map +1 -1
- package/dist/{utils-Qr8ug94X.mjs → utils-CQ2nQwwO.mjs} +2 -2
- package/dist/{utils-Qr8ug94X.mjs.map → utils-CQ2nQwwO.mjs.map} +1 -1
- package/dist/{v-514RME2X.mjs → v-BcroBusN.mjs} +2 -2
- package/dist/{v-514RME2X.mjs.map → v-BcroBusN.mjs.map} +1 -1
- package/dist/{validation-CPnrLcjW.mjs → validation-CjWRiLWU.mjs} +2 -2
- package/dist/{validation-CPnrLcjW.mjs.map → validation-CjWRiLWU.mjs.map} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/{validator-CQOw7G3q.mjs → validator-yrGnrsAo.mjs} +2 -2
- package/dist/{validator-CQOw7G3q.mjs.map → validator-yrGnrsAo.mjs.map} +1 -1
- package/dist/version-B9azgPiR.mjs +2 -0
- package/dist/{version-0RVYpih5.mjs.map → version-B9azgPiR.mjs.map} +1 -1
- package/package.json +16 -16
- package/dist/bind-parameter-capacity-DiwRmZ1h.mjs +0 -2
- package/dist/bind-parameter-capacity-DiwRmZ1h.mjs.map +0 -1
- package/dist/builder-D6Ug-zjM.mjs +0 -2
- package/dist/builder-D6Ug-zjM.mjs.map +0 -1
- package/dist/canonical-json-BReb5nFO.mjs.map +0 -1
- package/dist/chain-B5IbqLGi.mjs +0 -2
- package/dist/chain-B5IbqLGi.mjs.map +0 -1
- package/dist/client-BmcHzDBa.mjs +0 -2
- package/dist/client-BmcHzDBa.mjs.map +0 -1
- package/dist/client-DjtWangN.mjs.map +0 -1
- package/dist/current-oXcxSCBQ.mjs +0 -2
- package/dist/current-oXcxSCBQ.mjs.map +0 -1
- package/dist/driver-Bzc0GCQ4.mjs +0 -2
- package/dist/driver-Bzc0GCQ4.mjs.map +0 -1
- package/dist/every-WUr3mlvg.mjs +0 -2
- package/dist/execution-context-rJXTRVrJ.mjs +0 -2
- package/dist/execution-context-rJXTRVrJ.mjs.map +0 -1
- package/dist/geo-point-codec-D95uXgDF.mjs +0 -2
- package/dist/geo-point-codec-D95uXgDF.mjs.map +0 -1
- package/dist/identity-Bj2EN6Ss.mjs +0 -2
- package/dist/identity-Bj2EN6Ss.mjs.map +0 -1
- package/dist/mysql-adapter-ABpgFB2N.mjs +0 -2
- package/dist/postgres-adapter-Ci07rgh_.mjs +0 -2
- package/dist/postgres-adapter-Ci07rgh_.mjs.map +0 -1
- package/dist/postgres-adapter-DaMvNOkx.mjs +0 -2
- package/dist/postgres-result-D403cLyA.mjs +0 -2
- package/dist/result-shape-BKydBCsR.mjs +0 -2
- package/dist/result-shape-BKydBCsR.mjs.map +0 -1
- package/dist/select-assembly-uZfvbYjz.mjs +0 -2
- package/dist/select-assembly-uZfvbYjz.mjs.map +0 -1
- package/dist/sqlite-adapter-DPc9T6Lh.mjs +0 -2
- package/dist/sqlite-adapter-DPc9T6Lh.mjs.map +0 -1
- package/dist/version-0RVYpih5.mjs +0 -2
package/dist/mysql2.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, On as DriverTransactionOptions, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, g as MigrationNamespaceAttestation, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-
|
|
1
|
+
import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, On as DriverTransactionOptions, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, g as MigrationNamespaceAttestation, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-oVv9RLt5.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{
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,i as n,o as r}from"./normalized-result-BF7gr4_b.mjs";import{i}from"./base-D3m1S7Uc.mjs";import{l as a,p as o}from"./error-mapping-6op318w6.mjs";import{p as s,r as c}from"./validation-gwZYm3Yn.mjs";import{n as l}from"./transaction-4dfqals6.mjs";import{c as u}from"./execution-context-asSCmyas.mjs";import{n as d}from"./client-DUulrWw5.mjs";import{a as f,c as p,d as m,i as h,l as g,o as _,t as v}from"./driver-DseQwbsu.mjs";import{t as y}from"./mysql-adapter-B1U35CJn.mjs";import{Buffer as b}from"node:buffer";const x=/^(?:ssl|tls)/i;function tlsRefusal(e){return new c(e,{meta:{driver:`mysql2`,operation:`configuration`}})}function parseMySQLUrl(e){let t=new URL(e),n=decodeURIComponent(t.pathname.slice(1)),r={};for(let[e,n]of t.searchParams){if(x.test(e)&&e!==`ssl`&&e!==`sslmode`)throw tlsRefusal(`Unsupported MySQL TLS URL option; configure options.ssl explicitly.`);try{r[e]=JSON.parse(n)}catch{r[e]=n}}let i=t.searchParams.get(`sslmode`);if(i&&i!==`disable`){if(![`require`,`verify-ca`,`verify-full`].includes(i))throw tlsRefusal(`Unsupported MySQL sslmode; configure options.ssl explicitly.`);if(r.ssl!==void 0&&(r.ssl===null||typeof r.ssl!=`object`&&typeof r.ssl!=`string`))throw tlsRefusal(`MySQL sslmode requires a TLS configuration`);r.ssl??={}}Reflect.deleteProperty(r,`sslmode`);let a=decodeURIComponent(t.username),o=decodeURIComponent(t.password);return{host:t.hostname,...t.port?{port:Number.parseInt(t.port,10)}:{},...n===``?{}:{database:n},...a===``?{}:{user:a},...o===``?{}:{password:o},...r}}const S={pool:!0,options:!0,databaseUrl:!0,namespace:!0,migrationNamespaceAttestation:!0};function convertValuesForMySQL(e){return e.map(e=>e instanceof Uint8Array&&!b.isBuffer(e)?b.from(e.buffer,e.byteOffset,e.byteLength):e)}function isMultiStatementFields(e){return Array.isArray(e)&&e.every(e=>e===void 0||Array.isArray(e))}function malformedMySQL2Result(e,t){return new s(`Driver "mysql2" returned a malformed result for operation "${e}": ${t}.`,{meta:{driver:`mysql2`,operation:e}})}const C=/^-[1-9]\d*$/;function normalizeMySQL2InsertId(e,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 s(`Driver "mysql2" returned multiple statement results for operation "${i}"; VibORM requires exactly one statement result.`,{meta:{driver:`mysql2`,operation:i}});if(Array.isArray(e)){if(!Array.isArray(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 i(e)?e:new c(`Driver "mysql2" could not parse its databaseUrl.`,{cause:e instanceof Error?e:void 0})}}var MySQL2Driver=class extends v{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;constructor(e={}){let t=g(e),n=resolveMySQL2Configuration(e);if(super(`mysql`,`mysql2`,{},t),n.connectionOptions.multipleStatements===!0)throw new c(`Driver "mysql2" does not support options.multipleStatements=true because VibORM operations require one result per statement.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(n.connectionOptions.rowsAsArray===!0)throw new c(`Driver "mysql2" does not support options.rowsAsArray=true because VibORM requires row objects keyed by column name.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(n.connectionOptions.nestTables===!0||typeof n.connectionOptions.nestTables==`string`)throw new c(`Driver "mysql2" does not support enabled options.nestTables because VibORM requires flat row objects keyed by result aliases.`,{meta:{driver:`mysql2`,operation:`configuration`}});this.suppliedPool=n.suppliedPool,this.connectionOptions=n.connectionOptions,_(this,`adapter`,new y(n.namespace)),this.suppliedPool&&(this.client=this.suppliedPool)}async initClient(){if(this.suppliedPool!==void 0)return this.suppliedPool;let e=await import(`mysql2/promise`),t={timezone:`Z`,supportBigNumbers:!0,dateStrings:[`DATE`],...this.connectionOptions};return this.adapter.namespace!==void 0&&(t={...t,database:this.adapter.namespace}),e.createPool(t)}async closeClient(e){e!==this.suppliedPool&&await e.end()}async execute(e,t,n,r){let i=r?.operation??`execute`,[a,o]=await e.query({sql:t,values:convertValuesForMySQL(n),typeCast:(e,t)=>[`DATE`,`DATETIME`,`TIMESTAMP`,`LONGLONG`,`NEWDECIMAL`].includes(e.type)?e.string():t()});return toQueryResult(a,o,i)}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`,[a,o]=await e.query(t,n&&convertValuesForMySQL(n));return toQueryResult(a,o,i)}transactionOptionSupport(){return{isolationLevel:`pre-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(e,t,n,r){if(!(`getConnection`in e))throw a(this.driverName);let i=e,s=await h(()=>i.getConnection(),e=>e.release(),r?.maxWaitMs,{driverName:this.driverName,form:`callback`}),c=!1,runOrDestroy=async e=>{try{await e()}catch(e){throw c=!0,e}},d=r?.isolationLevel;return o({begin:()=>runOrDestroy(async()=>{d&&await s.query(f(d)),await s.beginTransaction()}),callback:()=>t(s),commit:()=>runOrDestroy(()=>s.commit()),rollback:()=>runOrDestroy(()=>s.rollback()),phases:u(n),close:()=>{try{if(c){s.destroy();return}s.release()}catch(e){throw super.transactionCleanupFailed(new l(`Driver "mysql2" could not release an unsafe transaction connection.`,{meta:{driver:`mysql2`,method:`$transaction`}})),e}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!(`getConnection`in e))throw a(this.driverName);let t=await e.getConnection();return{session:t,release:()=>(t.destroy(),Promise.resolve())}}};function createClient(e){p(e,`mysql2`,S);let{pool:t,options:n,databaseUrl:r}=e;return d(e,new MySQL2Driver({migrationNamespaceAttestation:g(e),namespace:m(e),pool:t,options:n,databaseUrl:r}))}export{MySQL2Driver,createClient};
|
|
2
2
|
//# sourceMappingURL=mysql2.mjs.map
|
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,\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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,MAAM,WACJ,sEACD,CAEH,GAAI,CACF,EAAa,GAAO,KAAK,MAAM,EAAM,MAC/B,CACN,EAAa,GAAO,GAKxB,IAAM,EAAU,EAAO,aAAa,IAAI,UAAU,CAClD,GAAI,GAAW,IAAY,UAAW,CACpC,GAAI,CAAC,CAAC,UAAW,YAAa,cAAc,CAAC,SAAS,EAAQ,CAC5D,MAAM,WACJ,+DACD,CAEH,GACE,EAAa,MAAQ,IAAA,KACpB,EAAa,MAAQ,MACnB,OAAO,EAAa,KAAQ,UAC3B,OAAO,EAAa,KAAQ,UAEhC,MAAM,WAAW,6CAA6C,CAChE,EAAa,MAAQ,EAAE,CAEzB,QAAQ,eAAe,EAAc,UA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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"}
|
package/dist/neon-http.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as Schema, An as BatchQuery, At as DriverConfig, Dn as BatchTransactionOptions, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, jn as CommittedBatchNotification, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-
|
|
1
|
+
import { A as Schema, An as BatchQuery, At as DriverConfig, Dn as BatchTransactionOptions, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, jn as CommittedBatchNotification, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-oVv9RLt5.mjs";
|
|
2
2
|
import { NeonQueryFunction } from "@neondatabase/serverless";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/neon-http/index.d.ts
|
|
@@ -13,6 +13,8 @@ interface NeonHTTPDriverOptions {
|
|
|
13
13
|
postgis?: boolean;
|
|
14
14
|
/** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */
|
|
15
15
|
sharedRelationBodies?: boolean;
|
|
16
|
+
/** 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. */
|
|
17
|
+
relationsPerStatement?: number;
|
|
16
18
|
/** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */
|
|
17
19
|
namespace?: string;
|
|
18
20
|
}
|
package/dist/neon-http.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./normalized-result-BF7gr4_b.mjs";import{m as n}from"./error-mapping-6op318w6.mjs";import{p as r,r as i}from"./validation-gwZYm3Yn.mjs";import{n as a}from"./client-DUulrWw5.mjs";import{c as o,d as s,t as c}from"./driver-DseQwbsu.mjs";import{t as l}from"./postgres-result-BCUQf8b_.mjs";import{t as u}from"./postgres-adapter-B7hzWhky.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 PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type NeonHTTPClientConfig<C extends DriverConfig> =\n NeonHTTPDriverOptions & C;\n\nconst NEON_HTTP_CONFIG_KEYS: Record<keyof NeonHTTPDriverOptions, true> = {\n databaseUrl: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n namespace: true,\n};\n\n// ============================================================\n// TYPE DECLARATIONS\n// ============================================================\n\n/**\n * NeonQuery is the main query function returned by neon().\n * Configured with arrayMode=false (object rows) and fullResults=true (includes rowCount).\n */\ntype NeonQuery = NeonQueryFunction<false, true>;\n\ninterface NeonFullResult<T> {\n fields: unknown[];\n command: string;\n rowCount: number | null;\n rows: T[];\n rowAsArray: false;\n}\n\nfunction malformedNeonResult(\n context: QueryExecutionContext,\n reason: string\n): QueryError {\n const operation = context.operation ?? \"execute\";\n return new QueryError(\n `Driver \"neon-http\" returned a malformed result payload for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"neon-http\", ...context, operation } }\n );\n}\n\nfunction assertNeonFullResult<T>(\n result: unknown,\n context: QueryExecutionContext\n): asserts result is NeonFullResult<T> {\n if (\n !(isNormalizedResultRow(result) && Array.isArray(result.fields)) ||\n typeof result.command !== \"string\" ||\n !Object.hasOwn(result, \"rowCount\") ||\n (result.rowCount !== null &&\n (typeof result.rowCount !== \"number\" ||\n !Number.isFinite(result.rowCount) ||\n !Number.isSafeInteger(result.rowCount) ||\n result.rowCount < 0)) ||\n !Array.isArray(result.rows) ||\n !result.rows.every(isNormalizedResultRow) ||\n result.rowAsArray !== false\n ) {\n throw malformedNeonResult(\n context,\n \"expected fullResults object with object rows and explicit rowCount\"\n );\n }\n}\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class NeonHTTPDriver extends Driver<NeonQuery, NeonQuery> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n // Neon HTTP only supports non-interactive (batch) transactions\n // Callback-style transactions are not supported\n readonly supportsTransactions = false;\n readonly supportsBatch = true;\n\n // Hosted rollback, durable visibility and malformed post-commit metadata\n // witnesses qualify this notification before driver result validation.\n readonly supportsOrderedCommittedSegments = true;\n\n private readonly driverOptions: NeonHTTPDriverOptions;\n private queryTypes: CustomTypesConfig | undefined;\n\n constructor(options: NeonHTTPDriverOptions = {}) {\n super(\"postgresql\", \"neon-http\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n\n installPostgresAdapter(this, namespace, options);\n }\n\n protected async initClient(): Promise<NeonQuery> {\n const { neon, types } = await import(\"@neondatabase/serverless\");\n\n if (!this.driverOptions.databaseUrl) {\n throw new ClientInitializationError(\n \"Neon HTTP driver requires a databaseUrl\",\n { meta: { driver: this.driverName } }\n );\n }\n\n // DATE (1082) / TIMESTAMP WITHOUT TIME ZONE (1114): the default parsers\n // build process-local Dates, shifting the stored value by the process\n // timezone. Return raw strings — the shared result parser builds UTC\n // Dates from them, matching every other driver.\n const identityParser = (value: string) => value;\n // pg-types declares getTypeParser with per-format overloads that a single\n // wrapper function can't express — the cast is unavoidable here\n const getTypeParser = ((oid: number, format?: string) => {\n if (\n [1082, 1114, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return types.getTypeParser(oid as never, format as never);\n }) as typeof types.getTypeParser;\n this.queryTypes = { getTypeParser };\n\n // Always use arrayMode=false (object rows) and fullResults=true (includes rowCount)\n const client = neon(this.driverOptions.databaseUrl, {\n fetchOptions: this.driverOptions.options?.fetchOptions,\n authToken: this.driverOptions.options?.authToken,\n fullResults: true,\n arrayMode: false,\n });\n\n return client;\n }\n\n protected async closeClient(_client: NeonQuery): Promise<void> {\n // HTTP client doesn't need to be closed\n }\n\n protected async execute<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery<T>(client, sql, params, context, \"execute\");\n }\n\n private async executeQuery<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[],\n context: QueryExecutionContext | undefined,\n fallbackOperation: string\n ): Promise<QueryResult<T>> {\n const executionContext = context ?? { operation: fallbackOperation };\n const result = await client.query(sql, params, {\n arrayMode: false,\n fullResults: true,\n types: this.queryTypes,\n });\n\n return this.parseResult<T>(result, executionContext);\n }\n\n protected async executeRaw<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery<T>(\n client,\n sql,\n params ?? [],\n context,\n \"executeRaw\"\n );\n }\n\n /**\n * Neon HTTP sends the whole batch as one request through `client.transaction`\n * and offers no callback transaction. The provider opens and closes that\n * transaction server-side in a single round trip. The SDK receives the\n * requested isolation level; timeout/maxWait need an interactive body or\n * acquired connection, which this HTTP transport does not have.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"provider\",\n timeout: false,\n timeoutReason:\n \"Neon HTTP runs a batch as one provider call with no interactive body to interrupt\",\n maxWait: \"unsupported\",\n maxWaitReason:\n \"Neon HTTP submits the batch immediately with no connection to acquire\",\n };\n }\n\n protected transaction<T>(\n _client: NeonQuery,\n _fn: (tx: NeonQuery) => Promise<T>\n ): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n\n /**\n * Execute multiple queries atomically using Neon's transaction() function.\n * This provides atomic batch execution with full PostgreSQL transaction semantics.\n */\n protected async executeBatch<T>(\n client: NeonQuery,\n queries: BatchQuery[],\n context?: QueryExecutionContext,\n committed?: CommittedBatchNotification,\n options?: BatchTransactionOptions\n ): Promise<QueryResult<T>[]> {\n const batchContext = context ?? { operation: \"executeBatch\" };\n // Query promises retain their own parser options in the public SDK API.\n const results: unknown = await client.transaction(\n queries.map((query) => {\n const statementContext = query.context ?? batchContext;\n try {\n return client.query(query.sql, query.params ?? [], {\n types: this.queryTypes,\n });\n } catch (error) {\n throw this.normalizeStatementFailure(\n error,\n query.sql,\n this.getBatchDiagnosticParameters(query),\n statementContext,\n true\n );\n }\n }),\n {\n isolationLevel: options?.isolationLevel,\n arrayMode: false,\n fullResults: true,\n }\n );\n await committed?.();\n\n if (!Array.isArray(results) || results.length !== queries.length) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw malformedNeonResult(\n batchContext,\n `expected ${queries.length} statement results but received ${actualResultCount}`\n );\n }\n\n return results.map((result, index) =>\n this.parseResult<T>(result, queries[index]?.context ?? batchContext)\n );\n }\n\n /**\n * Parse Neon result into QueryResult format.\n */\n private parseResult<T>(\n result: unknown,\n context: QueryExecutionContext\n ): QueryResult<T> {\n const operation = context.operation ?? \"execute\";\n assertNeonFullResult<T>(result, context);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n {\n provider: \"neon-http\",\n operation,\n model: context.model,\n correlationId: context.correlationId,\n }\n ),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: NeonHTTPClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, NeonHTTPDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: NeonHTTPDriver }\n >]: LinkedClientConfig<C & { driver: NeonHTTPDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"neon-http\", NEON_HTTP_CONFIG_KEYS);\n const { databaseUrl, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new NeonHTTPDriver({\n databaseUrl,\n options,\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, NeonHTTPDriver>(config, driver);\n}\n"],"mappings":"mZA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CAGD,GAFA,MAAM,KAAa,CAEf,CAAC,MAAM,QAAQ,EAAQ,EAAI,EAAQ,SAAW,EAAQ,OAAQ,CAChE,IAAM,EAAoB,MAAM,QAAQ,EAAQ,CAAG,EAAQ,OAAS,EACpE,MAAM,oBACJ,EACA,YAAY,EAAQ,OAAO,kCAAkC,IAC9D,CAGH,OAAO,EAAQ,KAAK,EAAQ,IAC1B,KAAK,YAAe,EAAQ,EAAQ,IAAQ,SAAW,EAAa,CACrE,CAMH,YACE,EACA,EACgB,CAChB,IAAM,EAAY,EAAQ,WAAa,UAEvC,OADA,qBAAwB,EAAQ,EAAQ,CACjC,CACL,KAAM,EAAO,KACb,SAAU,EACR,EAAO,SACP,EAAO,QACP,EAAO,KACP,CACE,SAAU,YACV,YACA,MAAO,EAAQ,MACf,cAAe,EAAQ,cACxB,CACF,CACF,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,YAAa,EAAsB,CACzE,GAAM,CAAE,cAAa,UAAS,WAAU,WAAY,EAC9C,EAAY,EAAuB,EAAO,CAWhD,OAAO,EAAmD,EAT3C,IAAI,eAAe,CAChC,cACA,UACA,WACA,UACA,qBAAsB,EAAO,qBAC7B,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":"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,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,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d,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"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{r as t}from"./value-guards-CK9guf2Z.mjs";import{n}from"./base-D3m1S7Uc.mjs";import{p as r}from"./validation-gwZYm3Yn.mjs";import{t as i}from"./sql-BvHwL73I.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-BF7gr4_b.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"normalized-result-BF7gr4_b.mjs","names":[],"sources":["../src/drivers/async-dispose.ts","../src/drivers/driver-batch-query-kind.ts","../src/drivers/prepared-statement-provenance.ts","../src/drivers/provider-parameter-snapshot.ts","../src/drivers/normalized-result.ts"],"sourcesContent":["/**\n * The platform's async-disposal protocol — as much of it as the runtime and the\n * consumer's type declarations actually provide.\n *\n * `Symbol.asyncDispose` (explicit resource management, TypeScript 5.2+) can be\n * missing in two independent ways, and each one is handled here so that no\n * caller has to think about it:\n *\n * 1. **The runtime symbol** is absent on engines that predate the proposal.\n * {@link ASYNC_DISPOSE} resolves it once; every definition site guards on it\n * rather than writing a bare `[Symbol.asyncDispose]` computed key, which\n * would otherwise install a method under the string key `\"undefined\"`.\n *\n * 2. **The type declaration** is absent from a consumer's `lib` / `@types`.\n * That is why the disposal member is carried by {@link AsyncDisposeMember}\n * instead of being written literally: a consumer who never writes\n * `await using` must not be forced to widen `lib` just to compile the\n * published `.d.mts`. See `docs/architecture/typed-kernel-without-effect-plan.md`\n * (Phase T6) and the consumer-floor probe in\n * `scripts/consumer-type-floor.mjs` for the measured floor.\n */\n\n/**\n * The runtime's async-disposal key, or `undefined` on engines that predate\n * explicit resource management.\n */\nexport const ASYNC_DISPOSE: typeof Symbol.asyncDispose | undefined =\n typeof Symbol.asyncDispose === \"symbol\" ? Symbol.asyncDispose : undefined;\n\n/**\n * `Symbol.asyncDispose`'s type where the ambient declarations define it, and\n * `never` where they do not.\n *\n * `never` is the load-bearing half: it turns {@link AsyncDisposeMember} into the\n * empty object, so the member simply is not there for a consumer whose `lib`\n * and `@types` never declared the symbol in the first place.\n */\nexport type AsyncDisposeKey = SymbolConstructor extends {\n readonly asyncDispose: infer Key extends symbol;\n}\n ? Key\n : never;\n\n/**\n * `{ [Symbol.asyncDispose](): Promise<void> }` where the symbol is typed, and\n * `{}` where it is not — the graceful-degradation carrier for every viborm type\n * that participates in `await using`.\n */\nexport type AsyncDisposeMember = {\n [Key in AsyncDisposeKey]: () => Promise<void>;\n};\n","/** Internal execution-kind metadata for prepared batch queries. */\n\nconst VERBATIM_BATCH_QUERY = Symbol(\"viborm.verbatimBatchQuery\");\n\n/** Mark a prepared raw statement that must retain verbatim driver semantics. */\nexport function markVerbatimBatchQuery<T extends object>(query: T): T {\n Object.defineProperty(query, VERBATIM_BATCH_QUERY, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n });\n return query;\n}\n\n/** Whether a prepared statement came from an unsafe or legacy raw call. */\nexport function isVerbatimBatchQuery(query: object): boolean {\n return Reflect.get(query, VERBATIM_BATCH_QUERY) === true;\n}\n","import { Sql } from \"@sql\";\n\nconst preparedStatements = new WeakMap<object, Sql>();\n\n/** Retain the typed Sql behind a rendered batch query without publishing it. */\nexport function registerPreparedStatement(query: object, statement: Sql): void {\n preparedStatements.set(query, statement);\n}\n\n/** Preserve private provenance when an internal owner snapshots a batch query. */\nexport function transferPreparedStatement<Output extends object>(\n source: object,\n output: Output\n): Output {\n const statement = preparedStatements.get(source);\n if (statement !== undefined) preparedStatements.set(output, statement);\n return output;\n}\n\n/** Preserve provenance with the exact detached values a batch will execute. */\nexport function snapshotPreparedStatement<Output extends object>(\n source: object,\n output: Output,\n values: readonly unknown[]\n): Output {\n const statement = preparedStatements.get(source);\n if (statement !== undefined) {\n preparedStatements.set(\n output,\n new Sql([...statement.strings], [...values])\n );\n }\n return output;\n}\n\n/** Read provenance only at the trusted typed-statement execution boundary. */\nexport function readPreparedStatement(query: object): Sql | undefined {\n return preparedStatements.get(query);\n}\n","import { QueryError, VibORMErrorCode } from \"@errors\";\nimport { isDate } from \"@validation/value-guards\";\nimport type { QueryExecutionContext } from \"./types\";\n\ntype InvalidRawDateError = (parameterIndex: number) => Error;\ntype UnsupportedRawArrayError = (parameterIndex: number) => Error;\n\ninterface RawParameterErrors {\n readonly invalidDate: InvalidRawDateError;\n readonly unsupportedArray: UnsupportedRawArrayError;\n}\n\ninterface RawParameterEdge {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n readonly value: unknown;\n}\n\ninterface RawParameterNode {\n readonly edges: readonly RawParameterEdge[];\n readonly isArray: boolean;\n readonly properties: readonly RawParameterProperty[];\n readonly prototype: object | null;\n readonly source: object;\n}\n\ninterface RawParameterProperty {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n}\n\ninterface RawParameterGraph {\n readonly dateTimes: WeakMap<object, number>;\n readonly nodes: readonly RawParameterNode[];\n readonly roots: readonly unknown[];\n}\n\ntype RawParameterNodeAnalysis =\n | { readonly kind: \"node\"; readonly shape: Omit<RawParameterNode, \"source\"> }\n | { readonly kind: \"opaque\" }\n | { readonly kind: \"unsupported-array\" };\n\nconst arrayIndex = /^(?:0|[1-9]\\d*)$/;\nconst maximumArrayIndex = 4_294_967_294;\n\ninterface BuiltinPrototypeProperty {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n}\n\nfunction captureBuiltinPrototype(\n prototype: object\n): readonly BuiltinPrototypeProperty[] {\n const properties: BuiltinPrototypeProperty[] = [];\n for (const key of Reflect.ownKeys(prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, key);\n if (descriptor) properties.push({ descriptor, key });\n }\n return Object.freeze(properties);\n}\n\nconst objectPrototypeShape = captureBuiltinPrototype(Object.prototype);\nconst arrayPrototypeShape = captureBuiltinPrototype(Array.prototype);\n\nfunction isArrayIndex(key: PropertyKey): boolean {\n if (typeof key !== \"string\" || !arrayIndex.test(key)) return false;\n const index = Number(key);\n return index <= maximumArrayIndex && String(index) === key;\n}\n\nfunction functionSource(value: unknown): string | undefined {\n if (typeof value !== \"function\") return;\n try {\n return Function.prototype.toString.call(value);\n } catch {\n return;\n }\n}\n\nfunction sameInertRecord(left: unknown, right: unknown): boolean {\n if (\n left === null ||\n right === null ||\n typeof left !== \"object\" ||\n typeof right !== \"object\"\n ) {\n return Object.is(left, right);\n }\n try {\n if (\n Object.getPrototypeOf(left) !== null ||\n Object.getPrototypeOf(right) !== null\n ) {\n return false;\n }\n const leftKeys = Reflect.ownKeys(left);\n const rightKeys = Reflect.ownKeys(right);\n if (leftKeys.length !== rightKeys.length) return false;\n for (let index = 0; index < rightKeys.length; index += 1) {\n const leftKey = leftKeys[index];\n const rightKey = rightKeys[index];\n if (leftKey !== rightKey || rightKey === undefined) return false;\n const leftDescriptor = Object.getOwnPropertyDescriptor(left, rightKey);\n const rightDescriptor = Object.getOwnPropertyDescriptor(right, rightKey);\n if (\n leftDescriptor === undefined ||\n rightDescriptor === undefined ||\n !(\"value\" in leftDescriptor) ||\n !(\"value\" in rightDescriptor) ||\n leftDescriptor.configurable !== rightDescriptor.configurable ||\n leftDescriptor.enumerable !== rightDescriptor.enumerable ||\n leftDescriptor.writable !== rightDescriptor.writable ||\n !Object.is(leftDescriptor.value, rightDescriptor.value)\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction sameBuiltinDescriptor(\n actual: PropertyDescriptor,\n expected: PropertyDescriptor\n): boolean {\n if (\n actual.configurable !== expected.configurable ||\n actual.enumerable !== expected.enumerable ||\n \"value\" in actual !== \"value\" in expected\n ) {\n return false;\n }\n if (\"value\" in actual && \"value\" in expected) {\n if (actual.writable !== expected.writable) return false;\n const expectedSource = functionSource(expected.value);\n if (expectedSource !== undefined) {\n return functionSource(actual.value) === expectedSource;\n }\n return sameInertRecord(actual.value, expected.value);\n }\n return (\n functionSource(actual.get) === functionSource(expected.get) &&\n functionSource(actual.set) === functionSource(expected.set)\n );\n}\n\nfunction hasBuiltinPrototypeShape(\n prototype: object,\n shape: readonly BuiltinPrototypeProperty[]\n): boolean {\n try {\n const keys = Reflect.ownKeys(prototype);\n if (keys.length !== shape.length) return false;\n for (let index = 0; index < shape.length; index += 1) {\n const expected = shape[index];\n if (expected === undefined || keys[index] !== expected.key) return false;\n const actual = Object.getOwnPropertyDescriptor(prototype, expected.key);\n if (\n actual === undefined ||\n !sameBuiltinDescriptor(actual, expected.descriptor)\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isObjectPrototype(prototype: object): boolean {\n try {\n return (\n Object.getPrototypeOf(prototype) === null &&\n hasBuiltinPrototypeShape(prototype, objectPrototypeShape)\n );\n } catch {\n return false;\n }\n}\n\nfunction isArrayPrototype(prototype: object): boolean {\n try {\n const parent = Object.getPrototypeOf(prototype);\n return (\n parent !== null &&\n isObjectPrototype(parent) &&\n hasBuiltinPrototypeShape(prototype, arrayPrototypeShape)\n );\n } catch {\n return false;\n }\n}\n\n/** Only arrays and records with inert inherited behavior are interpreted. */\nfunction rawParameterNodeShape(value: object): RawParameterNodeAnalysis {\n let isArray = false;\n try {\n isArray = Array.isArray(value);\n const prototype = Object.getPrototypeOf(value);\n if (\n (isArray && prototype !== null && !isArrayPrototype(prototype)) ||\n (!isArray && prototype !== null && !isObjectPrototype(prototype))\n ) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n\n const edges: RawParameterEdge[] = [];\n const properties: RawParameterProperty[] = [];\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined) continue;\n properties.push({ descriptor, key });\n const isProviderVisible = isArray\n ? isArrayIndex(key)\n : descriptor.enumerable && typeof key === \"string\";\n if (!isProviderVisible) continue;\n if (!(\"value\" in descriptor)) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n edges.push({ descriptor, key, value: descriptor.value });\n }\n const toJSON = properties.find((property) => property.key === \"toJSON\");\n if (\n toJSON &&\n (!(\"value\" in toJSON.descriptor) ||\n typeof toJSON.descriptor.value === \"function\")\n ) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n return {\n kind: \"node\",\n shape: { edges, isArray, properties, prototype },\n };\n } catch {\n // An exotic record owns its traversal semantics. If reflection refuses an\n // array shape, it cannot safely reach provider array semantics.\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n}\n\nfunction rawDateTime(\n value: unknown,\n parameterIndex: number,\n invalidDateError: InvalidRawDateError\n): number | undefined {\n if (!isDate(value)) return;\n const time = Date.prototype.getTime.call(value);\n if (Number.isNaN(time)) throw invalidDateError(parameterIndex);\n return time;\n}\n\nfunction analyzeRawParameterGraph(\n params: readonly unknown[],\n errors: RawParameterErrors\n): RawParameterGraph {\n const nodesBySource = new WeakMap<object, RawParameterNode>();\n const dateTimes = new WeakMap<object, number>();\n const nodes: RawParameterNode[] = [];\n const roots = new Array<unknown>(params.length);\n\n const discover = (\n value: unknown,\n parameterIndex: number\n ): RawParameterNode | undefined => {\n const time = rawDateTime(value, parameterIndex, errors.invalidDate);\n if (time !== undefined && typeof value === \"object\" && value !== null) {\n dateTimes.set(value, time);\n return;\n }\n if (typeof value !== \"object\" || value === null) return;\n\n const known = nodesBySource.get(value);\n if (known) return known;\n const analysis = rawParameterNodeShape(value);\n if (analysis.kind === \"unsupported-array\") {\n throw errors.unsupportedArray(parameterIndex);\n }\n if (analysis.kind === \"opaque\") return;\n const node: RawParameterNode = {\n ...analysis.shape,\n source: value,\n };\n nodesBySource.set(value, node);\n nodes.push(node);\n return node;\n };\n\n for (\n let parameterIndex = 0;\n parameterIndex < params.length;\n parameterIndex++\n ) {\n if (!Object.hasOwn(params, parameterIndex)) continue;\n const root = params[parameterIndex];\n roots[parameterIndex] = root;\n const rootTime = rawDateTime(root, parameterIndex, errors.invalidDate);\n if (rootTime !== undefined && typeof root === \"object\" && root !== null) {\n dateTimes.set(root, rootTime);\n continue;\n }\n const rootNode = discover(root, parameterIndex);\n if (!rootNode) continue;\n\n const pending = [rootNode];\n let cursor = 0;\n while (cursor < pending.length) {\n const node = pending[cursor];\n cursor += 1;\n if (!node) continue;\n for (const edge of node.edges) {\n const before = nodes.length;\n const child = discover(edge.value, parameterIndex);\n if (child && nodes.length > before) pending.push(child);\n }\n }\n }\n\n return { dateTimes, nodes, roots };\n}\n\n/** Validate every interpreted raw parameter before query interception. */\nexport function validateRawParameters(\n params: readonly unknown[],\n errors: RawParameterErrors\n): void {\n analyzeRawParameterGraph(params, errors);\n}\n\n/**\n * Snapshot every admitted data-descriptor JSON container, preserving aliases,\n * cycles, and property descriptors. Foreign built-in containers normalize to\n * local prototypes. Custom record carriers and provider-native objects remain\n * opaque; arrays with custom provider-visible behavior are refused. A Proxy\n * can run reflection traps while presenting an admitted container shape; the\n * captured descriptor view, never the later mutable Proxy, reaches dispatch.\n */\nfunction snapshotRawParameterGraph(\n params: readonly unknown[],\n errors: RawParameterErrors\n): unknown[] {\n const graph = analyzeRawParameterGraph(params, errors);\n const copies = new WeakMap<object, object>();\n const copiedDates = new WeakMap<object, Date>();\n\n for (const node of graph.nodes) {\n const copy: object = node.isArray ? [] : {};\n if (node.prototype === null) Object.setPrototypeOf(copy, null);\n copies.set(node.source, copy);\n }\n\n const copiedValue = (value: unknown): unknown => {\n if (typeof value !== \"object\" || value === null) return value;\n const time = graph.dateTimes.get(value);\n if (time !== undefined) {\n const known = copiedDates.get(value);\n if (known) return known;\n const copy = new Date(time);\n copiedDates.set(value, copy);\n return copy;\n }\n return copies.get(value) ?? value;\n };\n\n for (const node of graph.nodes) {\n const copy = copies.get(node.source);\n if (!copy) continue;\n for (const property of node.properties) {\n if (node.isArray && property.key === \"length\") continue;\n const descriptor = property.descriptor;\n Object.defineProperty(\n copy,\n property.key,\n \"value\" in descriptor &&\n (node.isArray\n ? isArrayIndex(property.key)\n : descriptor.enumerable && typeof property.key === \"string\")\n ? { ...descriptor, value: copiedValue(descriptor.value) }\n : descriptor\n );\n }\n if (node.isArray) {\n const length = node.properties.find(\n (property) => property.key === \"length\"\n );\n if (length) Object.defineProperty(copy, \"length\", length.descriptor);\n }\n }\n\n const snapshot = new Array<unknown>(graph.roots.length);\n for (let index = 0; index < graph.roots.length; index++) {\n if (!Object.hasOwn(graph.roots, index)) continue;\n snapshot[index] = copiedValue(graph.roots[index]);\n }\n return snapshot;\n}\n\nfunction invalidProviderDateError(\n context: QueryExecutionContext,\n parameterIndex: number\n): QueryError {\n return new QueryError(\n `Operation \"${context.operation ?? \"statement\"}\" received an invalid Date as bound parameter ${parameterIndex}. An invalid Date names no instant, so a provider either refuses the statement after dispatch or binds it as null.`,\n {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: {\n parameterIndex,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n },\n }\n );\n}\n\nfunction unsupportedProviderArrayError(\n context: QueryExecutionContext,\n parameterIndex: number\n): QueryError {\n return new QueryError(\n `Operation \"${context.operation ?? \"statement\"}\" received raw array parameter ${parameterIndex} with custom inherited or accessor behavior. VibORM cannot validate that behavior without invoking caller code before dispatch.`,\n {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: {\n parameterIndex,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n },\n }\n );\n}\n\n/**\n * Preserve the raw Date admission invariant after the last trusted statement\n * transform. Non-raw statements keep the old shallow-copy path: their typed\n * inputs were validated upstream, and statement transforms are trusted. Raw\n * Date leaves are revalidated and every admitted data-descriptor array or\n * ordinary JSON record is detached. Reflection does not invoke accessors,\n * iterators, or `toJSON`; a Proxy may run its reflection traps, so its captured\n * descriptor view is the stable provider value. Arrays with custom inherited\n * or accessor behavior are refused. Custom record and provider-native carriers\n * remain opaque and are not traversed.\n */\nexport function snapshotProviderParameters(\n params: readonly unknown[],\n context: QueryExecutionContext\n): unknown[] {\n if (context.model !== \"$raw\") return [...params];\n return snapshotRawParameterGraph(params, {\n invalidDate: (parameterIndex) =>\n invalidProviderDateError(context, parameterIndex),\n unsupportedArray: (parameterIndex) =>\n unsupportedProviderArrayError(context, parameterIndex),\n });\n}\n","import { QueryError } from \"@errors\";\nimport type { QueryResult } from \"./types\";\n\nexport interface NormalizedResultContext {\n provider: string;\n operation: string;\n model?: string;\n correlationId?: string;\n}\n\nexport function createNormalizedResultMeta(\n context: NormalizedResultContext\n): Record<string, unknown> {\n return {\n driver: context.provider,\n operation: context.operation,\n ...(context.model ? { model: context.model } : {}),\n ...(context.correlationId ? { correlationId: context.correlationId } : {}),\n };\n}\n\nconst NON_NEGATIVE_DECIMAL_REGEX = /^(?:0|[1-9]\\d*)$/;\n\nexport function normalizeProviderRowCount(\n value: unknown,\n context: NormalizedResultContext,\n options?: { allowDecimalString?: boolean; nullValue?: number }\n): number {\n let normalized = value === null ? options?.nullValue : value;\n if (\n options?.allowDecimalString === true &&\n typeof normalized === \"string\" &&\n NON_NEGATIVE_DECIMAL_REGEX.test(normalized)\n ) {\n normalized = Number(normalized);\n }\n if (\n typeof normalized !== \"number\" ||\n !Number.isSafeInteger(normalized) ||\n normalized < 0\n ) {\n throw new QueryError(\n `Driver \"${context.provider}\" returned a malformed row count for operation \"${context.operation}\".`,\n {\n meta: createNormalizedResultMeta(context),\n }\n );\n }\n return normalized;\n}\n\nexport function normalizeProviderInsertId(\n value: unknown,\n context: NormalizedResultContext,\n options?: { allowNumber?: boolean }\n): number | bigint | undefined {\n if (typeof value === \"string\") {\n if (!NON_NEGATIVE_DECIMAL_REGEX.test(value)) {\n throw malformedInsertId(context);\n }\n return value === \"0\" ? undefined : BigInt(value);\n }\n if (options?.allowNumber === true && typeof value === \"number\") {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw malformedInsertId(context);\n }\n return value === 0 ? undefined : value;\n }\n throw malformedInsertId(context);\n}\n\nfunction malformedInsertId(context: NormalizedResultContext): QueryError {\n return new QueryError(\n `Driver \"${context.provider}\" returned a malformed insert id for operation \"${context.operation}\".`,\n {\n meta: createNormalizedResultMeta(context),\n }\n );\n}\n\nfunction malformedNormalizedResult(\n context: NormalizedResultContext,\n resultIndex?: number\n): QueryError {\n const position =\n resultIndex === undefined ? \"\" : ` at batch result index ${resultIndex}`;\n return new QueryError(\n `Driver \"${context.provider}\" returned a malformed normalized result for operation \"${context.operation}\"${position}; expected { rows: object[], rowCount: safe non-negative integer }.`,\n {\n meta: {\n ...createNormalizedResultMeta(context),\n ...(resultIndex === undefined ? {} : { resultIndex }),\n },\n }\n );\n}\n\nexport function isNormalizedResultRow(\n value: unknown\n): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.prototype.toString.call(value) === \"[object Object]\"\n );\n}\n\nfunction hasNormalizedRows(value: unknown): value is Record<string, unknown>[] {\n if (!Array.isArray(value)) return false;\n for (let index = 0; index < value.length; index += 1) {\n if (!(Object.hasOwn(value, index) && isNormalizedResultRow(value[index]))) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Assert the single cross-driver success contract. Empty row arrays and a\n * rowCount of zero are valid; missing fields, non-record rows, and invented\n * counts are not.\n */\nexport function assertNormalizedQueryResult(\n result: QueryResult<unknown> | undefined,\n context: NormalizedResultContext,\n resultIndex?: number\n): void {\n const hasValidInsertId =\n result?.insertId === undefined ||\n (typeof result.insertId === \"bigint\" && result.insertId >= 0n) ||\n (typeof result.insertId === \"number\" &&\n Number.isFinite(result.insertId) &&\n Number.isSafeInteger(result.insertId) &&\n result.insertId >= 0);\n if (\n !(isNormalizedResultRow(result) && hasNormalizedRows(result.rows)) ||\n typeof result.rowCount !== \"number\" ||\n !Number.isFinite(result.rowCount) ||\n !Number.isSafeInteger(result.rowCount) ||\n result.rowCount < 0 ||\n !hasValidInsertId\n ) {\n throw malformedNormalizedResult(context, resultIndex);\n }\n}\n\n/**\n * Native and planned batches must return one normalized result for each\n * submitted statement, in the same order.\n */\nexport function assertNormalizedBatchResults(\n results: readonly QueryResult<unknown>[],\n expectedStatementCount: number,\n context: NormalizedResultContext\n): void {\n if (!Array.isArray(results) || results.length !== expectedStatementCount) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw new QueryError(\n `Driver \"${context.provider}\" returned ${actualResultCount} results for operation \"${context.operation}\"; expected ${expectedStatementCount}, one per statement.`,\n {\n meta: {\n ...createNormalizedResultMeta(context),\n expectedStatementCount,\n actualResultCount,\n },\n }\n );\n }\n\n for (let resultIndex = 0; resultIndex < results.length; resultIndex += 1) {\n assertNormalizedQueryResult(results[resultIndex], context, resultIndex);\n }\n}\n"],"mappings":"iNA0BA,M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,EACM,CACN,GAAI,CAAC,MAAM,QAAQ,EAAQ,EAAI,EAAQ,SAAW,EAAwB,CACxE,IAAM,EAAoB,MAAM,QAAQ,EAAQ,CAAG,EAAQ,OAAS,EACpE,MAAM,IAAI,EACR,WAAW,EAAQ,SAAS,aAAa,EAAkB,0BAA0B,EAAQ,UAAU,cAAc,EAAuB,sBAC5I,CACE,KAAM,CACJ,GAAG,2BAA2B,EAAQ,CACtC,yBACA,oBACD,CACF,CACF,CAGH,IAAK,IAAI,EAAc,EAAG,EAAc,EAAQ,OAAQ,GAAe,EACrE,4BAA4B,EAAQ,GAAc,EAAS,EAAY"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { Mn as Dialect, Un as AnyModel } from "./index-
|
|
2
|
-
import { i as ResolveCallback, t as MigrationClient } from "./planner-
|
|
1
|
+
import { Mn as Dialect, Un as AnyModel } from "./index-oVv9RLt5.mjs";
|
|
2
|
+
import { i as ResolveCallback, t as MigrationClient } from "./planner-C3KX6S85.mjs";
|
|
3
3
|
import { i as Sha256, n as MigrationStorageWriter, r as PublishResult } from "./contract-Dw0FR78e.mjs";
|
|
4
|
-
import { B as MigrationCheckInput, V as MigrationDecisionV1 } from "./client-
|
|
4
|
+
import { B as MigrationCheckInput, V as MigrationDecisionV1 } from "./client-3FqgR4eS.mjs";
|
|
5
5
|
|
|
6
6
|
//#region src/adapters/databases/sqlite/storage/datetime.d.ts
|
|
7
7
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-D3m1S7Uc.mjs";import{t as n}from"./migrations-Bn1SatyB.mjs";import{n as r}from"./canonical-json-
|
|
2
|
-
//# sourceMappingURL=object-store-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-D3m1S7Uc.mjs";import{t as n}from"./migrations-Bn1SatyB.mjs";import{n as r}from"./canonical-json-acY4dQNQ.mjs";import{a as i}from"./identity-CmRos0Yf.mjs";function refuseWorkersKvWritable(){throw new n(`Workers KV cannot be a V1 estate writer: listing is eventually consistent and puts are not conditional`,t.MIGRATION_UNSUPPORTED_PROVIDER)}var ObjectStoreEstateStorage=class{store;constructor(e){this.store=e}async readEstate(){return this.store.get(`estate.json`)}async listStates(){return this.listHex(`states/`,`.json`)}async listSnapshots(){return this.listHex(`snapshots/`,`.json`)}async listSql(){return this.listHex(`sql/`,`.sql`)}async readState(e){return this.store.get(`states/${e}.json`)}async readSnapshot(e){return this.store.get(`snapshots/${e}.json`)}async readSql(e){return this.store.get(`sql/${e}.sql`)}async publishEstate(e){return this.publish(`estate.json`,e)}async publishSnapshot(e,t){return this.publish(`snapshots/${e}.json`,t)}async publishSql(e,t){return this.publish(`sql/${e}.sql`,t)}async publishState(e,r){if(!i(e))throw new n(`State id is not a SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return this.publish(`states/${e}.json`,r)}async publish(e,i){if(await this.store.putIfAbsent(e,i)===`created`)return{outcome:`created`};let a=await this.store.get(e);if(!(a&&r(a,i)))throw new n(`Object-store key ${e} already holds different bytes`,t.MIGRATION_CORRUPTION);return{outcome:`identical`}}async listHex(e,t){let n=await this.store.list(e),r=[];for(let a of n){let n=a.slice(e.length);if(!n.endsWith(t))continue;let o=n.slice(0,-t.length);i(o)&&r.push(o)}return r.sort()}},MemoryConditionalObjectStore=class{objects=new Map;async putIfAbsent(e,t){return this.objects.has(e)?`exists`:(this.objects.set(e,t.slice()),`created`)}async get(e){let t=this.objects.get(e);return t?t.slice():null}async list(e){return[...this.objects.keys()].filter(t=>t.startsWith(e)).sort()}};export{ObjectStoreEstateStorage as n,refuseWorkersKvWritable as r,MemoryConditionalObjectStore as t};
|
|
2
|
+
//# sourceMappingURL=object-store-WjVilDvN.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"object-store-
|
|
1
|
+
{"version":3,"file":"object-store-WjVilDvN.mjs","names":[],"sources":["../src/migrations/storage/object-store.ts"],"sourcesContent":["/**\n * Strong object-store publication contract.\n * A writable driver that cannot do conditional create is not a V1 estate owner.\n * Workers KV is refused here: it has no compare-and-swap publication.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { bytesEqual } from \"../canonical-json\";\nimport { isSha256, type Sha256 } from \"../identity\";\nimport type { MigrationStorageWriter, PublishResult } from \"./contract\";\n\nexport function refuseWorkersKvWritable(): never {\n throw new MigrationError(\n \"Workers KV cannot be a V1 estate writer: listing is eventually consistent and puts are not conditional\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n}\n\nexport interface ObjectStoreConditionalPut {\n putIfAbsent(key: string, bytes: Uint8Array): Promise<\"created\" | \"exists\">;\n get(key: string): Promise<Uint8Array | null>;\n list(prefix: string): Promise<readonly string[]>;\n}\n\n/**\n * Estate writer over a strongly consistent object store with if-none-match\n * publication. Manifests become visible only after referenced bytes exist.\n */\nexport class ObjectStoreEstateStorage implements MigrationStorageWriter {\n private readonly store: ObjectStoreConditionalPut;\n\n constructor(store: ObjectStoreConditionalPut) {\n this.store = store;\n }\n\n async readEstate(): Promise<Uint8Array | null> {\n return this.store.get(\"estate.json\");\n }\n\n async listStates(): Promise<readonly Sha256[]> {\n return this.listHex(\"states/\", \".json\");\n }\n\n async listSnapshots(): Promise<readonly Sha256[]> {\n return this.listHex(\"snapshots/\", \".json\");\n }\n\n async listSql(): Promise<readonly Sha256[]> {\n return this.listHex(\"sql/\", \".sql\");\n }\n\n async readState(id: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`states/${id}.json`);\n }\n\n async readSnapshot(hash: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`snapshots/${hash}.json`);\n }\n\n async readSql(hash: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`sql/${hash}.sql`);\n }\n\n async publishEstate(bytes: Uint8Array): Promise<PublishResult> {\n return this.publish(\"estate.json\", bytes);\n }\n\n async publishSnapshot(\n hash: Sha256,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n return this.publish(`snapshots/${hash}.json`, bytes);\n }\n\n async publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return this.publish(`sql/${hash}.sql`, bytes);\n }\n\n async publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n if (!isSha256(id)) {\n throw new MigrationError(\n \"State id is not a SHA-256 digest\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return this.publish(`states/${id}.json`, bytes);\n }\n\n private async publish(\n key: string,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n const result = await this.store.putIfAbsent(key, bytes);\n if (result === \"created\") return { outcome: \"created\" };\n const existing = await this.store.get(key);\n if (!(existing && bytesEqual(existing, bytes))) {\n throw new MigrationError(\n `Object-store key ${key} already holds different bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { outcome: \"identical\" };\n }\n\n private async listHex(prefix: string, suffix: string): Promise<Sha256[]> {\n const keys = await this.store.list(prefix);\n const hashes: Sha256[] = [];\n for (const key of keys) {\n const name = key.slice(prefix.length);\n if (!name.endsWith(suffix)) continue;\n const hex = name.slice(0, -suffix.length);\n if (isSha256(hex)) hashes.push(hex);\n }\n return hashes.sort();\n }\n}\n\n/** In-memory strong object store for the conformance fixture. */\nexport class MemoryConditionalObjectStore implements ObjectStoreConditionalPut {\n private readonly objects = new Map<string, Uint8Array>();\n\n async putIfAbsent(\n key: string,\n bytes: Uint8Array\n ): Promise<\"created\" | \"exists\"> {\n if (this.objects.has(key)) return \"exists\";\n this.objects.set(key, bytes.slice());\n return \"created\";\n }\n\n async get(key: string): Promise<Uint8Array | null> {\n const bytes = this.objects.get(key);\n return bytes ? bytes.slice() : null;\n }\n\n async list(prefix: string): Promise<readonly string[]> {\n return [...this.objects.keys()]\n .filter((key) => key.startsWith(prefix))\n .sort();\n }\n}\n"],"mappings":"6NAWA,SAAgB,yBAAiC,CAC/C,MAAM,IAAI,EACR,yGACA,EAAgB,+BACjB,CAaH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gB,EAAmC,CACvE,IAAM,EAAO,MAAM,KAAK,MAAM,KAAK,EAAO,CACpC,EAAmB,EAAE,CAC3B,IAAK,IAAM,KAAO,EAAM,CACtB,IAAM,EAAO,EAAI,MAAM,EAAO,OAAO,CACrC,GAAI,CAAC,EAAK,SAAS,EAAO,CAAE,SAC5B,IAAM,EAAM,EAAK,MAAM,EAAG,CAAC,EAAO,OAAO,CACrC,EAAS,EAAI,EAAE,EAAO,KAAK,EAAI,CAErC,OAAO,EAAO,MAAM,GAKX,6BAAb,KAA+E,CAC7E,QAA2B,IAAI,IAE/B,MAAM,YACJ,EACA,EAC+B,CAG/B,OAFI,KAAK,QAAQ,IAAI,EAAI,CAAS,UAClC,KAAK,QAAQ,IAAI,EAAK,EAAM,OAAO,CAAC,CAC7B,WAGT,MAAM,IAAI,EAAyC,CACjD,IAAM,EAAQ,KAAK,QAAQ,IAAI,EAAI,CACnC,OAAO,EAAQ,EAAM,OAAO,CAAG,KAGjC,MAAM,KAAK,EAA4C,CACrD,MAAO,CAAC,GAAG,KAAK,QAAQ,MAAM,CAAC,CAC5B,OAAQ,GAAQ,EAAI,WAAW,EAAO,CAAC,CACvC,MAAM"}
|
package/dist/permissions.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { E as OperationPayload, Ft as VibORMClient, It as VibORMConfig,
|
|
1
|
+
import { E as OperationPayload, Ft as VibORMClient, It as VibORMConfig, M as ClientSchema, Nt as ExtensionState, Ut as RowsVerbs, W as InferOutput, en as MergeExtensionState, jt as ExtendedClient, kt as ClientTypeState } from "./index-oVv9RLt5.mjs";
|
|
2
2
|
import "./client.mjs";
|
|
3
3
|
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
4
4
|
|