viborm 1.3.0 → 1.3.2

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.
Files changed (167) hide show
  1. package/dist/{adapter-namespace-BpMbLKpL.mjs → adapter-namespace-B8XWzCev.mjs} +1 -1
  2. package/dist/{adapter-namespace-BpMbLKpL.mjs.map → adapter-namespace-B8XWzCev.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +1 -1
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/{batch-refs-B4zn-FAu.mjs → batch-refs-DoWlPD2h.mjs} +1 -1
  6. package/dist/{batch-refs-B4zn-FAu.mjs.map → batch-refs-DoWlPD2h.mjs.map} +1 -1
  7. package/dist/{builder-Df24l2Bd.mjs → builder-DhxaVYP2.mjs} +2 -2
  8. package/dist/{builder-Df24l2Bd.mjs.map → builder-DhxaVYP2.mjs.map} +1 -1
  9. package/dist/bun-sql.d.mts +1 -1
  10. package/dist/bun-sql.mjs +1 -1
  11. package/dist/bun-sqlite.d.mts +1 -1
  12. package/dist/bun-sqlite.mjs +1 -1
  13. package/dist/cache/cloudflare-kv.d.mts +1 -1
  14. package/dist/cache/cloudflare-kv.mjs +1 -1
  15. package/dist/cache/memory.d.mts +1 -1
  16. package/dist/cache/memory.mjs +1 -1
  17. package/dist/cache.d.mts +1 -1
  18. package/dist/cache.mjs +1 -1
  19. package/dist/cache.mjs.map +1 -1
  20. package/dist/chain-BjJ_M7EE.mjs +2 -0
  21. package/dist/chain-BjJ_M7EE.mjs.map +1 -0
  22. package/dist/cli.mjs +1 -1
  23. package/dist/client-BCgMXn6N.mjs +2 -0
  24. package/dist/client-BCgMXn6N.mjs.map +1 -0
  25. package/dist/{client-70MrTq1E.d.mts → client-Df81J4oB.d.mts} +1 -1
  26. package/dist/{client-DM1UHfYG.mjs → client-q6ccRgdO.mjs} +2 -2
  27. package/dist/{client-DM1UHfYG.mjs.map → client-q6ccRgdO.mjs.map} +1 -1
  28. package/dist/client.d.mts +1 -1
  29. package/dist/client.mjs +1 -1
  30. package/dist/{clock-C24RcpwO.mjs → clock-YTLtjLFS.mjs} +1 -1
  31. package/dist/{clock-C24RcpwO.mjs.map → clock-YTLtjLFS.mjs.map} +1 -1
  32. package/dist/config.d.mts +1 -1
  33. package/dist/config.mjs +1 -1
  34. package/dist/d1.d.mts +1 -1
  35. package/dist/d1.mjs +1 -1
  36. package/dist/{driver-CPD0Xxw2.mjs → driver-D6_Ik58x.mjs} +2 -2
  37. package/dist/{driver-CPD0Xxw2.mjs.map → driver-D6_Ik58x.mjs.map} +1 -1
  38. package/dist/{driver-B9fIori_.mjs → driver-Ddt147dK.mjs} +2 -2
  39. package/dist/{driver-B9fIori_.mjs.map → driver-Ddt147dK.mjs.map} +1 -1
  40. package/dist/driver.d.mts +1 -1
  41. package/dist/driver.mjs +1 -1
  42. package/dist/every-dpzVDwzu.mjs +2 -0
  43. package/dist/{every-1pKZteeB.mjs.map → every-dpzVDwzu.mjs.map} +1 -1
  44. package/dist/{fs-estate-i8Zlr1OQ.mjs → fs-estate-azK36i9V.mjs} +2 -2
  45. package/dist/{fs-estate-i8Zlr1OQ.mjs.map → fs-estate-azK36i9V.mjs.map} +1 -1
  46. package/dist/{hydration-DsyHNSDS.mjs → hydration-C2uXmJy6.mjs} +2 -2
  47. package/dist/{hydration-DsyHNSDS.mjs.map → hydration-C2uXmJy6.mjs.map} +1 -1
  48. package/dist/{identifier-conversion-DaZ9yNpv.mjs → identifier-conversion-C2pwwFOS.mjs} +2 -2
  49. package/dist/{identifier-conversion-DaZ9yNpv.mjs.map → identifier-conversion-C2pwwFOS.mjs.map} +1 -1
  50. package/dist/identity-Bj2EN6Ss.mjs +2 -0
  51. package/dist/identity-Bj2EN6Ss.mjs.map +1 -0
  52. package/dist/{index-VsM29vYN.d.mts → index-D4O0Twvs.d.mts} +16 -8
  53. package/dist/index.d.mts +1 -1
  54. package/dist/index.mjs +1 -1
  55. package/dist/instrumentation.d.mts +1 -1
  56. package/dist/instrumentation.mjs +1 -1
  57. package/dist/{key-D_kagnFv.mjs → key-B7vuAYPG.mjs} +2 -2
  58. package/dist/{key-D_kagnFv.mjs.map → key-B7vuAYPG.mjs.map} +1 -1
  59. package/dist/{libsql-DFAoHXrI.mjs → libsql-DUO6vHad.mjs} +2 -2
  60. package/dist/{libsql-DFAoHXrI.mjs.map → libsql-DUO6vHad.mjs.map} +1 -1
  61. package/dist/libsql.d.mts +1 -1
  62. package/dist/libsql.mjs +1 -1
  63. package/dist/{memory-GTWgeDNY.mjs → memory-BApsTkt1.mjs} +2 -2
  64. package/dist/{memory-GTWgeDNY.mjs.map → memory-BApsTkt1.mjs.map} +1 -1
  65. package/dist/migrations/mysql.d.mts +4 -4
  66. package/dist/migrations/mysql.mjs +1 -1
  67. package/dist/migrations/postgres.d.mts +4 -4
  68. package/dist/migrations/postgres.mjs +1 -1
  69. package/dist/migrations/sqlite.d.mts +4 -4
  70. package/dist/migrations/sqlite.mjs +1 -1
  71. package/dist/migrations/storage/durable-object.mjs +1 -1
  72. package/dist/migrations/storage/fs.mjs +1 -1
  73. package/dist/migrations/storage/r2.mjs +1 -1
  74. package/dist/migrations/tenant.d.mts +2 -2
  75. package/dist/migrations/tenant.mjs +1 -1
  76. package/dist/migrations.d.mts +4 -4
  77. package/dist/migrations.mjs +1 -1
  78. package/dist/{mysql-xChEivOe.mjs → mysql-D1GlcktG.mjs} +2 -2
  79. package/dist/{mysql-xChEivOe.mjs.map → mysql-D1GlcktG.mjs.map} +1 -1
  80. package/dist/{mysql-adapter-C6c5govr.mjs → mysql-adapter-ClOoHKpn.mjs} +2 -2
  81. package/dist/{mysql-adapter-C6c5govr.mjs.map → mysql-adapter-ClOoHKpn.mjs.map} +1 -1
  82. package/dist/mysql2.d.mts +1 -1
  83. package/dist/mysql2.mjs +1 -1
  84. package/dist/neon-http.d.mts +1 -1
  85. package/dist/neon-http.mjs +1 -1
  86. package/dist/{object-store-D9mvOHP4.d.mts → object-store-BN64q8Zn.d.mts} +3 -3
  87. package/dist/{object-store-ChYHlOMD.mjs → object-store-CZADAv4c.mjs} +2 -2
  88. package/dist/{object-store-ChYHlOMD.mjs.map → object-store-CZADAv4c.mjs.map} +1 -1
  89. package/dist/permissions.d.mts +2 -2
  90. package/dist/permissions.mjs +1 -1
  91. package/dist/permissions.mjs.map +1 -1
  92. package/dist/pg.d.mts +1 -1
  93. package/dist/pg.mjs +1 -1
  94. package/dist/pglite.d.mts +1 -1
  95. package/dist/pglite.mjs +1 -1
  96. package/dist/{pinned-session-BTplL3iZ.mjs → pinned-session-CjvR0Ge2.mjs} +2 -2
  97. package/dist/{pinned-session-BTplL3iZ.mjs.map → pinned-session-CjvR0Ge2.mjs.map} +1 -1
  98. package/dist/planetscale.d.mts +1 -1
  99. package/dist/planetscale.mjs +1 -1
  100. package/dist/{planner-C1NzLBge.d.mts → planner-8smxUOt9.d.mts} +1 -1
  101. package/dist/{postgres-BqAxDWTQ.mjs → postgres-Be0jMJWI.mjs} +2 -2
  102. package/dist/{postgres-BqAxDWTQ.mjs.map → postgres-Be0jMJWI.mjs.map} +1 -1
  103. package/dist/{postgres-adapter-CxEit2-v.mjs → postgres-adapter-BoQ4RRwr.mjs} +2 -2
  104. package/dist/{postgres-adapter-CxEit2-v.mjs.map → postgres-adapter-BoQ4RRwr.mjs.map} +1 -1
  105. package/dist/{postgres-adapter-CGthb5yh.mjs → postgres-adapter-C_Mt8lVC.mjs} +2 -2
  106. package/dist/{postgres-adapter-CGthb5yh.mjs.map → postgres-adapter-C_Mt8lVC.mjs.map} +1 -1
  107. package/dist/{postgres-result-KyBKBNJr.mjs → postgres-result-CYu1dyI_.mjs} +1 -1
  108. package/dist/{postgres-result-KyBKBNJr.mjs.map → postgres-result-CYu1dyI_.mjs.map} +1 -1
  109. package/dist/postgres.d.mts +1 -1
  110. package/dist/postgres.mjs +1 -1
  111. package/dist/result-shape-DQc-tDJ5.mjs +2 -0
  112. package/dist/{result-shape-CDgX_vzn.mjs.map → result-shape-DQc-tDJ5.mjs.map} +1 -1
  113. package/dist/rows-JXjhWwyb.mjs +2 -0
  114. package/dist/rows-JXjhWwyb.mjs.map +1 -0
  115. package/dist/{scalar-S8yMvdmx.mjs → scalar-CqqZ6jWd.mjs} +2 -2
  116. package/dist/{scalar-S8yMvdmx.mjs.map → scalar-CqqZ6jWd.mjs.map} +1 -1
  117. package/dist/schema/json.d.mts +1 -1
  118. package/dist/schema/json.mjs +1 -1
  119. package/dist/{schema-9N9jQlVL.mjs → schema-Cv-hhpl5.mjs} +2 -2
  120. package/dist/{schema-9N9jQlVL.mjs.map → schema-Cv-hhpl5.mjs.map} +1 -1
  121. package/dist/{schema-introspection-CyXKReK1.mjs → schema-introspection-B2Rvqgut.mjs} +3 -3
  122. package/dist/{schema-introspection-CyXKReK1.mjs.map → schema-introspection-B2Rvqgut.mjs.map} +1 -1
  123. package/dist/schema.d.mts +1 -1
  124. package/dist/schema.mjs +1 -1
  125. package/dist/{select-assembly-CkGe2ABs.mjs → select-assembly-BxtETbG9.mjs} +1 -1
  126. package/dist/{select-assembly-CkGe2ABs.mjs.map → select-assembly-BxtETbG9.mjs.map} +1 -1
  127. package/dist/{settle-CS_k6Ztm.mjs → settle-etgtP1WM.mjs} +2 -2
  128. package/dist/{settle-CS_k6Ztm.mjs.map → settle-etgtP1WM.mjs.map} +1 -1
  129. package/dist/sha256-CEYo7k7R.mjs +2 -0
  130. package/dist/sha256-CEYo7k7R.mjs.map +1 -0
  131. package/dist/soft-delete.d.mts +1 -1
  132. package/dist/{sql-statement-tokens-CFi1y3bK.mjs → sql-statement-tokens-BW7Q-rF-.mjs} +1 -1
  133. package/dist/{sql-statement-tokens-CFi1y3bK.mjs.map → sql-statement-tokens-BW7Q-rF-.mjs.map} +1 -1
  134. package/dist/{sqlite-adapter-BXAJy3mI.mjs → sqlite-adapter-B_LNxPA0.mjs} +2 -2
  135. package/dist/{sqlite-adapter-BXAJy3mI.mjs.map → sqlite-adapter-B_LNxPA0.mjs.map} +1 -1
  136. package/dist/{sqlite-utils-D_cypcyW.mjs → sqlite-utils-DIOll4P7.mjs} +1 -1
  137. package/dist/{sqlite-utils-D_cypcyW.mjs.map → sqlite-utils-DIOll4P7.mjs.map} +1 -1
  138. package/dist/sqlite3.d.mts +1 -1
  139. package/dist/sqlite3.mjs +1 -1
  140. package/dist/{standard-sql-CoGqv-iX.mjs → standard-sql-mJt0RHHE.mjs} +1 -1
  141. package/dist/{standard-sql-CoGqv-iX.mjs.map → standard-sql-mJt0RHHE.mjs.map} +1 -1
  142. package/dist/{to-many-C1PuFIpf.mjs → to-many-BSipkSbK.mjs} +2 -2
  143. package/dist/{to-many-C1PuFIpf.mjs.map → to-many-BSipkSbK.mjs.map} +1 -1
  144. package/dist/{utils-CtFUE8UN.mjs → utils-DjXObbUK.mjs} +2 -2
  145. package/dist/{utils-CtFUE8UN.mjs.map → utils-DjXObbUK.mjs.map} +1 -1
  146. package/dist/v-CrJYqdzu.mjs +2 -0
  147. package/dist/v-CrJYqdzu.mjs.map +1 -0
  148. package/dist/validation.d.mts +1 -1
  149. package/dist/validation.mjs +1 -1
  150. package/dist/{validator-DgffZq9C.mjs → validator-BqzpyNmt.mjs} +2 -2
  151. package/dist/{validator-DgffZq9C.mjs.map → validator-BqzpyNmt.mjs.map} +1 -1
  152. package/dist/version-Dus3if78.mjs +2 -0
  153. package/dist/{version-CXuJzC-q.mjs.map → version-Dus3if78.mjs.map} +1 -1
  154. package/package.json +16 -15
  155. package/dist/chain-C7c1YTXD.mjs +0 -2
  156. package/dist/chain-C7c1YTXD.mjs.map +0 -1
  157. package/dist/client-_WKrPNmm.mjs +0 -2
  158. package/dist/client-_WKrPNmm.mjs.map +0 -1
  159. package/dist/controls-Da-efekX.mjs +0 -2
  160. package/dist/controls-Da-efekX.mjs.map +0 -1
  161. package/dist/every-1pKZteeB.mjs +0 -2
  162. package/dist/identity-oQvIe7u8.mjs +0 -2
  163. package/dist/identity-oQvIe7u8.mjs.map +0 -1
  164. package/dist/result-shape-CDgX_vzn.mjs +0 -2
  165. package/dist/v-CYTUI0H5.mjs +0 -2
  166. package/dist/v-CYTUI0H5.mjs.map +0 -1
  167. package/dist/version-CXuJzC-q.mjs +0 -2
package/dist/pg.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, d as MigrationSessionAttestation, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-VsM29vYN.mjs";
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, d as MigrationSessionAttestation, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-D4O0Twvs.mjs";
2
2
  import { Pool, PoolClient, PoolConfig, PoolConfig as PgOptions } from "pg";
3
3
 
4
4
  //#region src/drivers/pg/index.d.ts
package/dist/pg.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{l as t,n,p as r,r as i}from"./error-mapping-C9WgitPi.mjs";import{r as a}from"./validation-BamBwne9.mjs";import{n as o}from"./transaction-4dfqals6.mjs";import{n as s}from"./suppressed-failure-Bdo2aK81.mjs";import{s as c}from"./execution-context-rJXTRVrJ.mjs";import{n as l}from"./client-_WKrPNmm.mjs";import{c as u,d,f,i as p,o as m,s as h,t as g,u as _}from"./driver-B9fIori_.mjs";import{t as v}from"./postgres-result-KyBKBNJr.mjs";import{t as y}from"./postgres-adapter-CGthb5yh.mjs";import{Pool as b,types as x}from"pg";const identityParser=e=>e,S={getTypeParser:(e,t)=>[1082,1114,1184,1115,1182,1185].includes(e)&&t!==`binary`?identityParser:x.getTypeParser(e,t)};function createOwnedPoolErrorState(){let e=0,t={retain(n){e+=1,t.backgroundFailure={error:n,generation:e,isAvailable:!0}}};return t}function holdClientErrors(e){let t,retain=e=>{t??=e};return e.on(`error`,retain),{failure:()=>t,stop:()=>{e.off(`error`,retain)}}}const C=new Set([`user`,`password`,`host`,`port`]),w=[`sslmode`,`sslcert`,`sslkey`,`sslrootcert`];function connectionRecord(e,t){let n=e.connectionString??t;if(!n)return e;if(typeof e.password==`function`)throw new a('Driver "pg" cannot keep a password callback beside a connection URL: node-postgres reads the password from the URL. Pass `host`, `user` and `database` in `options` instead.',{meta:{driver:`pg`,operation:`configuration`}});let r=f(n),i;try{i=new URL(r)}catch{i=void 0}let o=Object.entries(e).filter(([e,t])=>t!==void 0&&(C.has(e)||e===`database`||e===`ssl`||e!==`connectionString`&&i?.searchParams.has(e)));if(o.length===0)return{...e,connectionString:r};if(i===void 0)throw new a(`Driver "pg" could not read its connection URL to apply the connection options beside it.`,{meta:{driver:`pg`,operation:`configuration`}});for(let[e,t]of o)if(i.searchParams.delete(e),e===`ssl`)for(let e of w)i.searchParams.delete(e);else e===`database`?i.pathname=`/${String(t)}`:C.has(e)&&(typeof t==`string`||typeof t==`number`)&&i.searchParams.set(e,String(t));return{...e,connectionString:i.href}}const T={pool:!0,options:!0,pgvector:!0,postgis:!0,databaseUrl:!0,namespace:!0,sharedRelationBodies:!0,migrationSessionAttestation:!0};var PgDriver=class extends g{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;ownedPoolErrors=new WeakMap;constructor(e={}){super(`postgresql`,`pg`);let t=d(e);this.suppliedPool=e.pool;let n={...e.options};h(`pg`,e,!!(this.suppliedPool||n.host||n.connectionString)),this.connectionOptions=connectionRecord(n,e.databaseUrl),this.suppliedPool&&(this.client=this.suppliedPool),y(this,t,e),m(this,`migrationSessionAttestation`,_(e))}migrationSessionEndpoints(){let e=this.suppliedPool?Reflect.get(this.suppliedPool,`options`):void 0,t=typeof e==`object`&&e?e:{};return[this.connectionOptions.host,this.connectionOptions.connectionString,Reflect.get(t,`host`),Reflect.get(t,`connectionString`)]}initClient(){if(this.suppliedPool!==void 0)return Promise.resolve(this.suppliedPool);let e=new b({types:S,...this.connectionOptions}),t=createOwnedPoolErrorState();return this.ownedPoolErrors.set(e,t),e.on(`error`,t.retain),Promise.resolve(e)}readBackgroundPoolFailure(e){return this.ownedPoolErrors.get(e)?.backgroundFailure}clearBackgroundPoolFailure(e,t){if(t===void 0||!t.isAvailable)return!1;t.isAvailable=!1;let n=this.ownedPoolErrors.get(e);return n?.backgroundFailure?.generation===t.generation&&(n.backgroundFailure=void 0),!0}consumeBackgroundPoolFailure(e,t){if(this.clearBackgroundPoolFailure(e,t))return t?.error}throwPoolQueryFailure(e,t,n,r,a,o){let c=this.consumeBackgroundPoolFailure(e,t);throw c===void 0?n:s(i(n,{driverName:this.driverName,dialect:this.dialect,model:o?.model,operation:o?.operation,correlationId:o?.correlationId,query:r,params:this.getDiagnosticParameters(a??[],o),diagnostics:this.getErrorDisclosure(o),forceContext:!0}),c)}async acquirePooledClient(e,t={},r){let i=this.readBackgroundPoolFailure(e),a=!1;try{return await p(async()=>{try{let t=await e.connect();return this.clearBackgroundPoolFailure(e,i),t}finally{a=!0}},e=>e.release(),r,{driverName:this.driverName,form:`callback`})}catch(r){if(!a)throw r;let o=this.consumeBackgroundPoolFailure(e,i);throw o===void 0?r:s(n(r,{driverName:this.driverName,model:t.model,operation:t.operation,correlationId:t.correlationId,diagnostics:this.getErrorDisclosure(t)},`Database connection failed after the pool reported a background failure`),o)}}async closeClient(e){if(e===this.suppliedPool)return;let t=this.ownedPoolErrors.get(e);try{await e.end()}catch(r){let i=this.consumeBackgroundPoolFailure(e,t?.backgroundFailure);throw i===void 0?r:s(n(r,{driverName:this.driverName},`Database disconnection failed`),i)}t!==void 0&&(e.off(`error`,t.retain),t.backgroundFailure=void 0,this.ownedPoolErrors.delete(e))}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,t,n,r,i){let a=r?.operation??i,o=this.readBackgroundPoolFailure(e),s=await e.query({text:t,values:n,types:S}).catch(i=>this.throwPoolQueryFailure(e,o,i,t,n,r));return this.clearBackgroundPoolFailure(e,o),{rows:s.rows,rowCount:v(s.rowCount,s.command,s.rows,{provider:`pg`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(e,n,i,a){if(`release`in e)throw t(this.driverName);let l=await this.acquirePooledClient(e,i,a?.maxWaitMs),u=holdClientErrors(l),withClientFailure=e=>{let t=u.failure();return t===void 0||t===e?e:s(e,t)},d,queryOrDiscard=async e=>{try{await l.query(e)}catch(e){throw d??=e instanceof Error?e:!0,withClientFailure(e)}};return r({begin:()=>queryOrDiscard(`BEGIN`),callback:async()=>{try{return await n(l)}catch(e){throw withClientFailure(e)}},commit:()=>{let e=u.failure();if(e!==void 0)throw e;return queryOrDiscard(`COMMIT`)},rollback:()=>u.failure()===void 0?queryOrDiscard(`ROLLBACK`):void 0,phases:c(i),close:()=>{try{let e=d??u.failure();if(e){l.release(e);return}l.release()}catch(e){throw super.transactionCleanupFailed(new o(`Driver "pg" could not release an unsafe transaction connection.`,{meta:{driver:`pg`,method:`$transaction`}})),e}finally{u.stop()}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(`release`in e)throw t(this.driverName);let n=await this.acquirePooledClient(e,{operation:`pinnedSession`}),r=holdClientErrors(n);return{session:n,lost:r.failure,release:e=>{try{n.release(r.failure()??(e?!0:void 0))}finally{r.stop()}return Promise.resolve()}}}};function createClient(e){u(e,`pg`,T);let{pool:t,options:n={},pgvector:r,postgis:i,databaseUrl:a}=e;return l(e,new PgDriver({namespace:d(e),migrationSessionAttestation:_(e),pool:t||void 0,options:n,...Object.hasOwn(e,`databaseUrl`)?{databaseUrl:a}:{},pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies}))}export{PgDriver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{l as t,n,p as r,r as i}from"./error-mapping-C9WgitPi.mjs";import{r as a}from"./validation-BamBwne9.mjs";import{n as o}from"./transaction-4dfqals6.mjs";import{n as s}from"./suppressed-failure-Bdo2aK81.mjs";import{s as c}from"./execution-context-rJXTRVrJ.mjs";import{n as l}from"./client-BCgMXn6N.mjs";import{c as u,d,f,i as p,o as m,s as h,t as g,u as _}from"./driver-Ddt147dK.mjs";import{t as v}from"./postgres-result-CYu1dyI_.mjs";import{t as y}from"./postgres-adapter-C_Mt8lVC.mjs";import{Pool as b,types as x}from"pg";const identityParser=e=>e,S={getTypeParser:(e,t)=>[1082,1114,1184,1115,1182,1185].includes(e)&&t!==`binary`?identityParser:x.getTypeParser(e,t)};function createOwnedPoolErrorState(){let e=0,t={retain(n){e+=1,t.backgroundFailure={error:n,generation:e,isAvailable:!0}}};return t}function holdClientErrors(e){let t,retain=e=>{t??=e};return e.on(`error`,retain),{failure:()=>t,stop:()=>{e.off(`error`,retain)}}}const C=new Set([`user`,`password`,`host`,`port`]),w=[`sslmode`,`sslcert`,`sslkey`,`sslrootcert`];function connectionRecord(e,t){let n=e.connectionString??t;if(!n)return e;if(typeof e.password==`function`)throw new a('Driver "pg" cannot keep a password callback beside a connection URL: node-postgres reads the password from the URL. Pass `host`, `user` and `database` in `options` instead.',{meta:{driver:`pg`,operation:`configuration`}});let r=f(n),i;try{i=new URL(r)}catch{i=void 0}let o=Object.entries(e).filter(([e,t])=>t!==void 0&&(C.has(e)||e===`database`||e===`ssl`||e!==`connectionString`&&i?.searchParams.has(e)));if(o.length===0)return{...e,connectionString:r};if(i===void 0)throw new a(`Driver "pg" could not read its connection URL to apply the connection options beside it.`,{meta:{driver:`pg`,operation:`configuration`}});for(let[e,t]of o)if(i.searchParams.delete(e),e===`ssl`)for(let e of w)i.searchParams.delete(e);else e===`database`?i.pathname=`/${String(t)}`:C.has(e)&&(typeof t==`string`||typeof t==`number`)&&i.searchParams.set(e,String(t));return{...e,connectionString:i.href}}const T={pool:!0,options:!0,pgvector:!0,postgis:!0,databaseUrl:!0,namespace:!0,sharedRelationBodies:!0,migrationSessionAttestation:!0};var PgDriver=class extends g{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;ownedPoolErrors=new WeakMap;constructor(e={}){super(`postgresql`,`pg`);let t=d(e);this.suppliedPool=e.pool;let n={...e.options};h(`pg`,e,!!(this.suppliedPool||n.host||n.connectionString)),this.connectionOptions=connectionRecord(n,e.databaseUrl),this.suppliedPool&&(this.client=this.suppliedPool),y(this,t,e),m(this,`migrationSessionAttestation`,_(e))}migrationSessionEndpoints(){let e=this.suppliedPool?Reflect.get(this.suppliedPool,`options`):void 0,t=typeof e==`object`&&e?e:{};return[this.connectionOptions.host,this.connectionOptions.connectionString,Reflect.get(t,`host`),Reflect.get(t,`connectionString`)]}initClient(){if(this.suppliedPool!==void 0)return Promise.resolve(this.suppliedPool);let e=new b({types:S,...this.connectionOptions}),t=createOwnedPoolErrorState();return this.ownedPoolErrors.set(e,t),e.on(`error`,t.retain),Promise.resolve(e)}readBackgroundPoolFailure(e){return this.ownedPoolErrors.get(e)?.backgroundFailure}clearBackgroundPoolFailure(e,t){if(t===void 0||!t.isAvailable)return!1;t.isAvailable=!1;let n=this.ownedPoolErrors.get(e);return n?.backgroundFailure?.generation===t.generation&&(n.backgroundFailure=void 0),!0}consumeBackgroundPoolFailure(e,t){if(this.clearBackgroundPoolFailure(e,t))return t?.error}throwPoolQueryFailure(e,t,n,r,a,o){let c=this.consumeBackgroundPoolFailure(e,t);throw c===void 0?n:s(i(n,{driverName:this.driverName,dialect:this.dialect,model:o?.model,operation:o?.operation,correlationId:o?.correlationId,query:r,params:this.getDiagnosticParameters(a??[],o),diagnostics:this.getErrorDisclosure(o),forceContext:!0}),c)}async acquirePooledClient(e,t={},r){let i=this.readBackgroundPoolFailure(e),a=!1;try{return await p(async()=>{try{let t=await e.connect();return this.clearBackgroundPoolFailure(e,i),t}finally{a=!0}},e=>e.release(),r,{driverName:this.driverName,form:`callback`})}catch(r){if(!a)throw r;let o=this.consumeBackgroundPoolFailure(e,i);throw o===void 0?r:s(n(r,{driverName:this.driverName,model:t.model,operation:t.operation,correlationId:t.correlationId,diagnostics:this.getErrorDisclosure(t)},`Database connection failed after the pool reported a background failure`),o)}}async closeClient(e){if(e===this.suppliedPool)return;let t=this.ownedPoolErrors.get(e);try{await e.end()}catch(r){let i=this.consumeBackgroundPoolFailure(e,t?.backgroundFailure);throw i===void 0?r:s(n(r,{driverName:this.driverName},`Database disconnection failed`),i)}t!==void 0&&(e.off(`error`,t.retain),t.backgroundFailure=void 0,this.ownedPoolErrors.delete(e))}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,t,n,r,i){let a=r?.operation??i,o=this.readBackgroundPoolFailure(e),s=await e.query({text:t,values:n,types:S}).catch(i=>this.throwPoolQueryFailure(e,o,i,t,n,r));return this.clearBackgroundPoolFailure(e,o),{rows:s.rows,rowCount:v(s.rowCount,s.command,s.rows,{provider:`pg`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(e,n,i,a){if(`release`in e)throw t(this.driverName);let l=await this.acquirePooledClient(e,i,a?.maxWaitMs),u=holdClientErrors(l),withClientFailure=e=>{let t=u.failure();return t===void 0||t===e?e:s(e,t)},d,queryOrDiscard=async e=>{try{await l.query(e)}catch(e){throw d??=e instanceof Error?e:!0,withClientFailure(e)}};return r({begin:()=>queryOrDiscard(`BEGIN`),callback:async()=>{try{return await n(l)}catch(e){throw withClientFailure(e)}},commit:()=>{let e=u.failure();if(e!==void 0)throw e;return queryOrDiscard(`COMMIT`)},rollback:()=>u.failure()===void 0?queryOrDiscard(`ROLLBACK`):void 0,phases:c(i),close:()=>{try{let e=d??u.failure();if(e){l.release(e);return}l.release()}catch(e){throw super.transactionCleanupFailed(new o(`Driver "pg" could not release an unsafe transaction connection.`,{meta:{driver:`pg`,method:`$transaction`}})),e}finally{u.stop()}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(`release`in e)throw t(this.driverName);let n=await this.acquirePooledClient(e,{operation:`pinnedSession`}),r=holdClientErrors(n);return{session:n,lost:r.failure,release:e=>{try{n.release(r.failure()??(e?!0:void 0))}finally{r.stop()}return Promise.resolve()}}}};function createClient(e){u(e,`pg`,T);let{pool:t,options:n={},pgvector:r,postgis:i,databaseUrl:a}=e;return l(e,new PgDriver({namespace:d(e),migrationSessionAttestation:_(e),pool:t||void 0,options:n,...Object.hasOwn(e,`databaseUrl`)?{databaseUrl:a}:{},pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies}))}export{PgDriver,createClient};
2
2
  //# sourceMappingURL=pg.mjs.map
package/dist/pglite.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-VsM29vYN.mjs";
1
+ import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, kn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-D4O0Twvs.mjs";
2
2
  import { PGlite, PGliteOptions, PGliteOptions as PGliteOptions$1, Transaction } from "@electric-sql/pglite";
3
3
 
4
4
  //#region src/drivers/pglite/index.d.ts
package/dist/pglite.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{c as t}from"./bind-parameter-capacity-qfEejeOX.mjs";import{d as n,l as r}from"./error-mapping-C9WgitPi.mjs";import{s as i}from"./execution-context-rJXTRVrJ.mjs";import{n as a}from"./client-_WKrPNmm.mjs";import{a as o,n as s}from"./pinned-session-BTplL3iZ.mjs";import{c,d as l,r as u,t as d}from"./driver-B9fIori_.mjs";import{t as f}from"./postgres-adapter-CGthb5yh.mjs";import{PGlite as p}from"@electric-sql/pglite";const m=Object.fromEntries([1082,1114,1184,1115,1182,1185].map(e=>[e,e=>e])),h={client:!0,dataDir:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,namespace:!0};function isPGliteDatabase(e){return`transaction`in e}var PGliteDriver=class extends d{maxBindParametersPerStatement=32767;serializeTransactions=!0;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`pglite`);let t=l(e);this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient&&(this.client=this.suppliedClient,Object.defineProperty(this,`connectionQueue`,{value:u(this.suppliedClient)})),f(this,t,e)}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let e=this.driverOptions.dataDir,t=this.driverOptions.options??{},n={...t,parsers:{1114:e=>e,...t.parsers}};return e?await p.create(e,n):await p.create(n)}async closeClient(e){e!==this.suppliedClient&&await e.close()}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,n,r,i,a){let o=i?.operation??a,s=await e.query(n,r,{parsers:m}),c=t(s.affectedRows,{provider:`pglite`,operation:o});return{rows:s.rows,rowCount:s.rows.length>0?s.rows.length:c}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`queue`}}transaction(e,t,a){if(!isPGliteDatabase(e))throw r(this.driverName);return n({run:t=>e.transaction(t),callback:t,phases:i(a),close:async()=>void 0})}async physicalPinnedSession(){return await this.getClient({operation:`pinnedSession`})}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!isPGliteDatabase(e))throw r(this.driverName);return{session:e,release:async t=>{if(t)try{await e.query(`SELECT pg_advisory_unlock_all()`)}catch(t){throw s(e),o(this.driverName,`No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.`,t)}}}}};function createClient(e){c(e,`pglite`,h);let{client:t,dataDir:n,options:r,pgvector:i,postgis:o}=e,s=l(e);return a(e,new PGliteDriver({client:t,dataDir:n,options:r,pgvector:i,postgis:o,sharedRelationBodies:e.sharedRelationBodies,namespace:s}))}export{PGliteDriver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{c as t}from"./bind-parameter-capacity-qfEejeOX.mjs";import{d as n,l as r}from"./error-mapping-C9WgitPi.mjs";import{s as i}from"./execution-context-rJXTRVrJ.mjs";import{n as a}from"./client-BCgMXn6N.mjs";import{a as o,n as s}from"./pinned-session-CjvR0Ge2.mjs";import{c,d as l,r as u,t as d}from"./driver-Ddt147dK.mjs";import{t as f}from"./postgres-adapter-C_Mt8lVC.mjs";import{PGlite as p}from"@electric-sql/pglite";const m=Object.fromEntries([1082,1114,1184,1115,1182,1185].map(e=>[e,e=>e])),h={client:!0,dataDir:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,namespace:!0};function isPGliteDatabase(e){return`transaction`in e}var PGliteDriver=class extends d{maxBindParametersPerStatement=32767;serializeTransactions=!0;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`pglite`);let t=l(e);this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient&&(this.client=this.suppliedClient,Object.defineProperty(this,`connectionQueue`,{value:u(this.suppliedClient)})),f(this,t,e)}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let e=this.driverOptions.dataDir,t=this.driverOptions.options??{},n={...t,parsers:{1114:e=>e,...t.parsers}};return e?await p.create(e,n):await p.create(n)}async closeClient(e){e!==this.suppliedClient&&await e.close()}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,n,r,i,a){let o=i?.operation??a,s=await e.query(n,r,{parsers:m}),c=t(s.affectedRows,{provider:`pglite`,operation:o});return{rows:s.rows,rowCount:s.rows.length>0?s.rows.length:c}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`queue`}}transaction(e,t,a){if(!isPGliteDatabase(e))throw r(this.driverName);return n({run:t=>e.transaction(t),callback:t,phases:i(a),close:async()=>void 0})}async physicalPinnedSession(){return await this.getClient({operation:`pinnedSession`})}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!isPGliteDatabase(e))throw r(this.driverName);return{session:e,release:async t=>{if(t)try{await e.query(`SELECT pg_advisory_unlock_all()`)}catch(t){throw s(e),o(this.driverName,`No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.`,t)}}}}};function createClient(e){c(e,`pglite`,h);let{client:t,dataDir:n,options:r,pgvector:i,postgis:o}=e,s=l(e);return a(e,new PGliteDriver({client:t,dataDir:n,options:r,pgvector:i,postgis:o,sharedRelationBodies:e.sharedRelationBodies,namespace:s}))}export{PGliteDriver,createClient};
2
2
  //# sourceMappingURL=pglite.mjs.map
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,n}from"./base-D3m1S7Uc.mjs";import{i as r}from"./validation-BamBwne9.mjs";import{n as i}from"./suppressed-failure-Bdo2aK81.mjs";import{t as a}from"./settle-CS_k6Ztm.mjs";const o=`SELECT pg_advisory_unlock_all()`,s=`could not prove the advisory-lock state of a discarded migration session: its "${o}" reset failed.`,c=5e3;function unprovenLockStateError(e,n,r){return abandonedSessionError(e,s,n,t(r))}function abandonedSessionError(e,t,i,a){return new r(`Driver "${e}" ${t} ${i}`,{code:n.CONNECTION_CLOSED,cause:a,meta:{driver:e,operation:`pinnedSession`}})}function condemnedSessionError(e){return new r(`Driver "${e}" will pin no further migration session: an earlier session's "${o}" reset failed, so the advisory-lock state of its one client is unknown. That client was not closed — it is the caller's database, not a pooled connection VibORM may discard — and ordinary queries on it are unaffected.`,{code:n.CONNECTION_CLOSED,meta:{driver:e,operation:`pinnedSession`}})}const l=`The reserved connection was abandoned rather than returned to the pool. VibORM did not close the transport, which belongs to the caller, so the lock is freed when that connection is.`;async function releaseReservedPostgresSession(e){if(e.lost===!0){let{closeOwnedTransport:t,driverName:n}=e;if(t===void 0)throw abandonedSessionError(n,`lost the connection of a reserved migration session and sent nothing more on it.`,l,void 0);t().catch(()=>void 0);return}if(!e.discard){e.release();return}try{await a(e.reset(),c,()=>Error(`The advisory-lock reset went unanswered for ${c} ms.`))}catch(t){await abandon(e,s,t)}e.release()}async function abandon(e,n,r){let{closeOwnedTransport:a,driverName:o}=e;if(a===void 0)throw abandonedSessionError(o,n,l,t(r));try{await a()}catch(e){throw i(abandonedSessionError(o,n,`The reserved connection was abandoned rather than returned to the pool, and ending the transport VibORM created for it FAILED: that backend may still be running, and any advisory lock it holds is freed only when it goes away. VibORM withdrew that transport and will not use it again.`,t(r)),e)}throw abandonedSessionError(o,n,`The reserved connection was abandoned rather than returned to the pool, and the transport VibORM created for it was closed — which ends that backend, and with it every advisory lock it held.`,t(r))}const u=new WeakMap;function refuseCondemnedSession(e,t){if(t.condemned)throw condemnedSessionError(e)}function leasePinnedCommand(e,t,n){let r=physicalSessionState(t);refuseCondemnedSession(e,r);let i=r.queued.then(()=>(refuseCondemnedSession(e,r),n()));return r.queued=i.then(()=>void 0,()=>void 0),i}function condemnPhysicalSession(e){physicalSessionState(e).condemned=!0}function physicalSessionState(e){let t=u.get(e);if(t)return t;let n={queued:Promise.resolve(),condemned:!1};return u.set(e,n),n}export{unprovenLockStateError as a,releaseReservedPostgresSession as i,condemnPhysicalSession as n,leasePinnedCommand as r,c as t};
2
- //# sourceMappingURL=pinned-session-BTplL3iZ.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,n}from"./base-D3m1S7Uc.mjs";import{i as r}from"./validation-BamBwne9.mjs";import{n as i}from"./suppressed-failure-Bdo2aK81.mjs";import{t as a}from"./settle-etgtP1WM.mjs";const o=`SELECT pg_advisory_unlock_all()`,s=`could not prove the advisory-lock state of a discarded migration session: its "${o}" reset failed.`,c=5e3;function unprovenLockStateError(e,n,r){return abandonedSessionError(e,s,n,t(r))}function abandonedSessionError(e,t,i,a){return new r(`Driver "${e}" ${t} ${i}`,{code:n.CONNECTION_CLOSED,cause:a,meta:{driver:e,operation:`pinnedSession`}})}function condemnedSessionError(e){return new r(`Driver "${e}" will pin no further migration session: an earlier session's "${o}" reset failed, so the advisory-lock state of its one client is unknown. That client was not closed — it is the caller's database, not a pooled connection VibORM may discard — and ordinary queries on it are unaffected.`,{code:n.CONNECTION_CLOSED,meta:{driver:e,operation:`pinnedSession`}})}const l=`The reserved connection was abandoned rather than returned to the pool. VibORM did not close the transport, which belongs to the caller, so the lock is freed when that connection is.`;async function releaseReservedPostgresSession(e){if(e.lost===!0){let{closeOwnedTransport:t,driverName:n}=e;if(t===void 0)throw abandonedSessionError(n,`lost the connection of a reserved migration session and sent nothing more on it.`,l,void 0);t().catch(()=>void 0);return}if(!e.discard){e.release();return}try{await a(e.reset(),c,()=>Error(`The advisory-lock reset went unanswered for ${c} ms.`))}catch(t){await abandon(e,s,t)}e.release()}async function abandon(e,n,r){let{closeOwnedTransport:a,driverName:o}=e;if(a===void 0)throw abandonedSessionError(o,n,l,t(r));try{await a()}catch(e){throw i(abandonedSessionError(o,n,`The reserved connection was abandoned rather than returned to the pool, and ending the transport VibORM created for it FAILED: that backend may still be running, and any advisory lock it holds is freed only when it goes away. VibORM withdrew that transport and will not use it again.`,t(r)),e)}throw abandonedSessionError(o,n,`The reserved connection was abandoned rather than returned to the pool, and the transport VibORM created for it was closed — which ends that backend, and with it every advisory lock it held.`,t(r))}const u=new WeakMap;function refuseCondemnedSession(e,t){if(t.condemned)throw condemnedSessionError(e)}function leasePinnedCommand(e,t,n){let r=physicalSessionState(t);refuseCondemnedSession(e,r);let i=r.queued.then(()=>(refuseCondemnedSession(e,r),n()));return r.queued=i.then(()=>void 0,()=>void 0),i}function condemnPhysicalSession(e){physicalSessionState(e).condemned=!0}function physicalSessionState(e){let t=u.get(e);if(t)return t;let n={queued:Promise.resolve(),condemned:!1};return u.set(e,n),n}export{unprovenLockStateError as a,releaseReservedPostgresSession as i,condemnPhysicalSession as n,leasePinnedCommand as r,c as t};
2
+ //# sourceMappingURL=pinned-session-CjvR0Ge2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"pinned-session-BTplL3iZ.mjs","names":[],"sources":["../src/drivers/shared/pinned-session.ts"],"sourcesContent":["import { ConnectionError, VibORMErrorCode } from \"@errors\";\nimport { errorCause } from \"../../errors/diagnostic-safety\";\nimport { settleWithin } from \"./settle\";\nimport { withSuppressedFailure } from \"./suppressed-failure\";\n\n/** The PostgreSQL statement that resets a session's advisory-lock state. */\nconst ADVISORY_RESET = \"SELECT pg_advisory_unlock_all()\";\n\n/** Why a reserved session is abandoned, in the refusal's own words. */\nconst LOST_SESSION =\n \"lost the connection of a reserved migration session and sent nothing more on it.\";\nconst ADVISORY_RESET_FAILED = `could not prove the advisory-lock state of a discarded migration session: its \"${ADVISORY_RESET}\" reset failed.`;\n\n/**\n * How long one cleanup statement — `ROLLBACK`, the unlock, the limits reset,\n * the advisory reset — may take before its session is treated as lost.\n *\n * A healthy server answers each of them in milliseconds. A session that does\n * not answer one within this bound is a half-open socket or a dying backend,\n * and waiting on it longer only keeps the caller from the failure it already\n * has (plan S2: \"bound every cleanup statement\").\n */\nexport const CLEANUP_BOUND_MS = 5000;\n\n/**\n * One reserved physical session, as a provider hands it back.\n *\n * The plan's requirement (§3.5) is \"one physical producer across decisions and\n * commit boundaries\": a session lock is session-scoped, so acquiring it through\n * one pooled connection and running the protected work through another protects\n * nothing and can strand the lock. A reservation is therefore a connection the\n * provider has taken OUT of its pool, plus the exact way to give it back.\n */\nexport interface PinnedSessionReservation<TSession> {\n /** The reserved producer. Every statement of the session runs on it. */\n readonly session: TSession;\n /**\n * The failure the provider itself saw end this session's connection, or\n * `undefined` while it has seen none.\n *\n * Only a provider that observes its connection has one (`pg`, through the\n * client's `error` event). Elsewhere a lost connection is recognized by the\n * failure that reported it.\n */\n readonly lost?: () => unknown;\n /**\n * Returns the producer to the provider.\n *\n * `discard` is true when the session's state is unknown — a failed unlock, a\n * failed cleanup, or a thrown body — and the provider must then destroy the\n * connection rather than hand a session carrying unknown state back to a\n * pool. A provider whose session can never be made clean again (MySQL2, which\n * has executed `USE` and possibly author-owned statements) destroys\n * unconditionally and ignores the flag.\n *\n * `lost` is true when the connection itself is gone or stopped answering:\n * the provider must send nothing more on it — not even the reset a discard\n * otherwise runs — and abandon or destroy it.\n */\n release(discard: boolean, lost?: boolean): Promise<void>;\n}\n\n/**\n * The handle the pinned body uses to condemn its own producer.\n *\n * A thrown body already condemns the session. This exists for the case that\n * does not throw: an unlock statement that RETURNS a result proving the lock\n * was not released. That session is still usable in the provider's eyes and\n * would be returned to the pool holding a lock nobody owns.\n */\nexport interface PinnedSessionControl {\n /** Condemn this producer; it will be destroyed instead of released. */\n discard(): void;\n /**\n * Whether this session's connection is gone: the provider saw it end,\n * `failure` reports it, or a cleanup statement went unanswered. Once true it\n * stays true, and nothing more is sent on the session (plan S2).\n */\n lost(failure?: unknown): boolean;\n /** Runs one cleanup statement within `CLEANUP_BOUND_MS`; past it, the session is lost. */\n cleanup<T>(run: () => Promise<T>): Promise<T>;\n}\n\n/**\n * The refusal a discarded session whose reset FAILED raises.\n *\n * A session is discarded because its state is unknown, and the reset is what\n * makes it known again. When the reset fails too, the session may still hold\n * the migration lock every other command is excluded by — so it must not go\n * back to the provider, and saying nothing about that is not an option either:\n * a swallowed cleanup failure is how a pool ends up serving a connection that\n * blocks the next migration forever.\n *\n * The reset's own failure is the evidence, and it is the PROVIDER's value: it\n * goes through the one total normalizer rather than a bare `instanceof`, which\n * a rejection whose `getPrototypeOf` trap throws turns into a throw inside this\n * constructor — replacing the whole typed refusal with the trap's error.\n */\nexport function unprovenLockStateError(\n driverName: string,\n containment: string,\n cause: unknown\n): ConnectionError {\n return abandonedSessionError(\n driverName,\n ADVISORY_RESET_FAILED,\n containment,\n errorCause(cause)\n );\n}\n\nfunction abandonedSessionError(\n driverName: string,\n reason: string,\n containment: string,\n cause: Error | undefined\n): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" ${reason} ${containment}`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n cause,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * The refusal raised afterwards by EVERY driver whose one client was condemned.\n *\n * A transport that pools connections recovers by reserving a different one, so\n * this is only for the driver whose single client IS the session: there is no\n * other connection to reach for, and running the next migration command on a\n * session that may still hold the lock is precisely what the condemnation\n * exists to prevent. Two drivers over that one client are two callers of this\n * same refusal, because the session they would both pin is the same session.\n */\nexport function condemnedSessionError(driverName: string): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" will pin no further migration session: an earlier session's \"${ADVISORY_RESET}\" reset failed, so the advisory-lock state of its one client is unknown. That client was not closed — it is the caller's database, not a pooled connection VibORM may discard — and ordinary queries on it are unaffected.`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * What was actually DONE about the abandoned connection, in the refusal's own\n * words.\n *\n * Three outcomes, three sentences, each chosen once the outcome is known\n * rather than once the ownership is known. A single sentence written before the\n * close was attempted claimed the backend had been ended even when ending it\n * threw — and the one thing a caller does with that claim is stop looking for a\n * connection that is still running, still holding the lock this refusal exists\n * to report.\n */\nconst CALLER_OWNED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool. VibORM did not close the transport, which belongs to the caller, so the lock is freed when that connection is.\";\nconst CLOSED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool, and the transport VibORM created for it was closed — which ends that backend, and with it every advisory lock it held.\";\nconst CLOSE_FAILED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool, and ending the transport VibORM created for it FAILED: that backend may still be running, and any advisory lock it holds is freed only when it goes away. VibORM withdrew that transport and will not use it again.\";\n\n/**\n * Returns a reserved PostgreSQL session to its pool, or condemns it — the ONE\n * rule for every provider that reserves a connection it cannot destroy.\n *\n * postgres.js and Bun SQL both expose `release()` and nothing else: there is no\n * destructive return to reach for, so a session whose reset failed is ABANDONED\n * — never released — which is the only way it stops being a connection the pool\n * will hand to the next caller.\n *\n * Abandoning it leaves the lock held until that backend goes away, so a\n * transport VibORM created is closed too: ending it terminates the backend, and\n * PostgreSQL frees every advisory lock the session held. A transport the CALLER\n * supplied is never closed for this — it is theirs, may be serving their own\n * code, and closing it to tidy up VibORM's cleanup failure would be a far\n * larger effect than the one being contained.\n *\n * A LOST session (plan S2) is abandoned the same way without the reset: its\n * connection is gone or stopped answering, and a statement written to it is,\n * on postgres.js, an uncaught crash from inside the provider's write loop. Its\n * owned transport is closed; a supplied one is reported, since abandoning is\n * all VibORM may do with it.\n */\nexport async function releaseReservedPostgresSession(reservation: {\n readonly driverName: string;\n readonly discard: boolean;\n readonly lost?: boolean | undefined;\n /** Runs `SELECT pg_advisory_unlock_all()` on the reserved session. */\n readonly reset: () => Promise<unknown>;\n /** Hands the reserved session back to the provider's pool. */\n readonly release: () => void;\n /** Closes the transport, or absent when the CALLER owns it. */\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n}): Promise<void> {\n if (reservation.lost === true) {\n const { closeOwnedTransport, driverName } = reservation;\n if (closeOwnedTransport === undefined) {\n throw abandonedSessionError(\n driverName,\n LOST_SESSION,\n CALLER_OWNED_CONTAINMENT,\n undefined\n );\n }\n // Not awaited: the connection failure the caller holds is already the\n // answer, and the close lets the transport's other queries finish first\n // (postgres.js waits on the dead connection's unsettled query until its\n // bound). The transport is withdrawn before it closes, and a session the\n // close cannot end is ended by the server's idle limit.\n closeOwnedTransport().catch(() => undefined);\n return;\n }\n if (!reservation.discard) {\n reservation.release();\n return;\n }\n\n try {\n await settleWithin(\n reservation.reset(),\n CLEANUP_BOUND_MS,\n () =>\n new Error(\n `The advisory-lock reset went unanswered for ${CLEANUP_BOUND_MS} ms.`\n )\n );\n } catch (resetFailure) {\n await abandon(reservation, ADVISORY_RESET_FAILED, resetFailure);\n }\n reservation.release();\n}\n\n/**\n * Abandons a reserved session: never released, its owned transport closed,\n * and the refusal that says so thrown. A transport the caller supplied is only\n * abandoned.\n */\nasync function abandon(\n reservation: {\n readonly driverName: string;\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n },\n reason: string,\n cause: unknown\n): Promise<void> {\n const { closeOwnedTransport, driverName } = reservation;\n if (closeOwnedTransport === undefined) {\n throw abandonedSessionError(\n driverName,\n reason,\n CALLER_OWNED_CONTAINMENT,\n errorCause(cause)\n );\n }\n try {\n await closeOwnedTransport();\n } catch (closeFailure) {\n // The reason stays primary — it is what the caller acts on — and the\n // close's own failure is cleanup evidence beside it.\n throw withSuppressedFailure(\n abandonedSessionError(\n driverName,\n reason,\n CLOSE_FAILED_CONTAINMENT,\n errorCause(cause)\n ),\n closeFailure\n );\n }\n throw abandonedSessionError(\n driverName,\n reason,\n CLOSED_CONTAINMENT,\n errorCause(cause)\n );\n}\n\n/** What VibORM knows about one PHYSICAL session it pins commands on. */\ninterface PhysicalSessionState {\n /**\n * The pinned commands already queued on this session. It never rejects, so\n * one command's failure cannot poison the queue — the next command runs\n * either way, exactly as it would after a success.\n */\n queued: Promise<void>;\n /**\n * Set when a discarded session's advisory-lock reset failed, and never\n * cleared: nothing that happens later can prove a lock was released.\n */\n condemned: boolean;\n}\n\n/**\n * What is known about each PHYSICAL session, keyed on the session itself.\n *\n * A driver's connection queue serializes the commands of THAT driver. Two\n * drivers built over one supplied client — the documented shape for two\n * schema-scoped estates over one PGlite — own two queues and one session, so\n * the queue arbitrates nothing between them, and a PostgreSQL session advisory\n * lock is REENTRANT: the second command re-acquires the lock the first is\n * holding instead of waiting for it, then reads and writes inside the first\n * command's session. The client is the only thing both drivers agree on, so it\n * is what this is keyed on.\n *\n * The condemnation shares that key because it answers for the same subject: a\n * failed reset leaves the CLIENT's lock state unknown, not the wrapper's. Kept\n * on the driver instead, it was a fact the other wrappers over that client\n * never consulted, and their next command ran inside the session it condemned.\n *\n * Weak by construction: the entry dies with the client, and a client nobody\n * holds keeps nothing alive here.\n */\nconst PHYSICAL_SESSIONS = new WeakMap<object, PhysicalSessionState>();\n\n/**\n * Refuses a command on a session whose advisory-lock state was condemned.\n *\n * One refusal, read at two moments, and each covers what the other cannot. At\n * ADMISSION, so a session condemned before this command arrived refuses now\n * rather than behind a queue whose head may itself be waiting on the very lock\n * nobody can account for. At the FRONT of the queue, because condemnation lands\n * BETWEEN the two: the command ahead of this one is the one whose reset fails,\n * and this one was admitted while that session still looked accountable.\n */\nfunction refuseCondemnedSession(\n driverName: string,\n state: PhysicalSessionState\n): void {\n if (state.condemned) {\n throw condemnedSessionError(driverName);\n }\n}\n\n/**\n * Runs `command` exclusively on this physical session, when it may still be\n * pinned at all.\n *\n * The refusal is here rather than beside it because this is the one path every\n * pinned command over a shared session takes, and it lands before `command` —\n * so no body and no statement of the refused command reaches the client.\n */\nexport function leasePinnedCommand<T>(\n driverName: string,\n session: object,\n command: () => Promise<T>\n): Promise<T> {\n const state = physicalSessionState(session);\n refuseCondemnedSession(driverName, state);\n const next = state.queued.then(() => {\n refuseCondemnedSession(driverName, state);\n return command();\n });\n state.queued = next.then(\n () => undefined,\n () => undefined\n );\n return next;\n}\n\n/**\n * Records that this physical session's advisory-lock state can no longer be\n * accounted for — for every driver that reaches it, not only the one whose\n * reset failed.\n */\nexport function condemnPhysicalSession(session: object): void {\n physicalSessionState(session).condemned = true;\n}\n\n/** This session's state, created on first use and mutated in place after. */\nfunction physicalSessionState(session: object): PhysicalSessionState {\n const existing = PHYSICAL_SESSIONS.get(session);\n if (existing) {\n return existing;\n }\n const created: PhysicalSessionState = {\n queued: Promise.resolve(),\n condemned: false,\n };\n PHYSICAL_SESSIONS.set(session, created);\n return created;\n}\n"],"mappings":"iOAMA,MAAM,EAAiB,kCAKjB,EAAwB,kFAAkF,EAAe,iBAWlH,EAAmB,IA4EhC,SAAgB,uBACd,EACA,EACA,EACiB,CACjB,OAAO,sBACL,EACA,EACA,EACA,EAAW,EAAM,CAClB,CAGH,SAAS,sBACP,EACA,EACA,EACA,EACiB,CACjB,OAAO,IAAI,EACT,WAAW,EAAW,IAAI,EAAO,GAAG,IACpC,CACE,KAAM,EAAgB,kBACtB,QACA,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CACzD,CACF,CAaH,SAAgB,sBAAsB,EAAqC,CACzE,OAAO,IAAI,EACT,WAAW,EAAW,iEAAiE,EAAe,4NACtG,CACE,KAAM,EAAgB,kBACtB,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CACzD,CACF,CAcH,MAAM,EACJ,yLA4BF,eAAsB,+BAA+B,EAUnC,CAChB,GAAI,EAAY,OAAS,GAAM,CAC7B,GAAM,CAAE,sBAAqB,cAAe,EAC5C,GAAI,IAAwB,IAAA,GAC1B,MAAM,sBACJ,EACA,mFACA,EACA,IAAA,GACD,CAOH,GAAqB,CAAC,UAAY,IAAA,GAAU,CAC5C,OAEF,GAAI,CAAC,EAAY,QAAS,CACxB,EAAY,SAAS,CACrB,OAGF,GAAI,CACF,MAAM,EACJ,EAAY,OAAO,CACnB,MAEM,MACF,+CAA+C,EAAiB,MACjE,CACJ,OACM,EAAc,CACrB,MAAM,QAAQ,EAAa,EAAuB,EAAa,CAEjE,EAAY,SAAS,CAQvB,eAAe,QACb,EAIA,EACA,EACe,CACf,GAAM,CAAE,sBAAqB,cAAe,EAC5C,GAAI,IAAwB,IAAA,GAC1B,MAAM,sBACJ,EACA,EACA,EACA,EAAW,EAAM,CAClB,CAEH,GAAI,CACF,MAAM,GAAqB,OACpB,EAAc,CAGrB,MAAM,EACJ,sBACE,EACA,EACA,8RACA,EAAW,EAAM,CAClB,CACD,EACD,CAEH,MAAM,sBACJ,EACA,EACA,iMACA,EAAW,EAAM,CAClB,CAsCH,MAAM,EAAoB,IAAI,QAY9B,SAAS,uBACP,EACA,EACM,CACN,GAAI,EAAM,UACR,MAAM,sBAAsB,EAAW,CAY3C,SAAgB,mBACd,EACA,EACA,EACY,CACZ,IAAM,EAAQ,qBAAqB,EAAQ,CAC3C,uBAAuB,EAAY,EAAM,CACzC,IAAM,EAAO,EAAM,OAAO,UACxB,uBAAuB,EAAY,EAAM,CAClC,GAAS,EAChB,CAKF,MAJA,GAAM,OAAS,EAAK,SACZ,IAAA,OACA,IAAA,GACP,CACM,EAQT,SAAgB,uBAAuB,EAAuB,CAC5D,qBAAqB,EAAQ,CAAC,UAAY,GAI5C,SAAS,qBAAqB,EAAuC,CACnE,IAAM,EAAW,EAAkB,IAAI,EAAQ,CAC/C,GAAI,EACF,OAAO,EAET,IAAM,EAAgC,CACpC,OAAQ,QAAQ,SAAS,CACzB,UAAW,GACZ,CAED,OADA,EAAkB,IAAI,EAAS,EAAQ,CAChC"}
1
+ {"version":3,"file":"pinned-session-CjvR0Ge2.mjs","names":[],"sources":["../src/drivers/shared/pinned-session.ts"],"sourcesContent":["import { ConnectionError, VibORMErrorCode } from \"@errors\";\nimport { errorCause } from \"../../errors/diagnostic-safety\";\nimport { settleWithin } from \"./settle\";\nimport { withSuppressedFailure } from \"./suppressed-failure\";\n\n/** The PostgreSQL statement that resets a session's advisory-lock state. */\nconst ADVISORY_RESET = \"SELECT pg_advisory_unlock_all()\";\n\n/** Why a reserved session is abandoned, in the refusal's own words. */\nconst LOST_SESSION =\n \"lost the connection of a reserved migration session and sent nothing more on it.\";\nconst ADVISORY_RESET_FAILED = `could not prove the advisory-lock state of a discarded migration session: its \"${ADVISORY_RESET}\" reset failed.`;\n\n/**\n * How long one cleanup statement — `ROLLBACK`, the unlock, the limits reset,\n * the advisory reset — may take before its session is treated as lost.\n *\n * A healthy server answers each of them in milliseconds. A session that does\n * not answer one within this bound is a half-open socket or a dying backend,\n * and waiting on it longer only keeps the caller from the failure it already\n * has (plan S2: \"bound every cleanup statement\").\n */\nexport const CLEANUP_BOUND_MS = 5000;\n\n/**\n * One reserved physical session, as a provider hands it back.\n *\n * The plan's requirement (§3.5) is \"one physical producer across decisions and\n * commit boundaries\": a session lock is session-scoped, so acquiring it through\n * one pooled connection and running the protected work through another protects\n * nothing and can strand the lock. A reservation is therefore a connection the\n * provider has taken OUT of its pool, plus the exact way to give it back.\n */\nexport interface PinnedSessionReservation<TSession> {\n /** The reserved producer. Every statement of the session runs on it. */\n readonly session: TSession;\n /**\n * The failure the provider itself saw end this session's connection, or\n * `undefined` while it has seen none.\n *\n * Only a provider that observes its connection has one (`pg`, through the\n * client's `error` event). Elsewhere a lost connection is recognized by the\n * failure that reported it.\n */\n readonly lost?: () => unknown;\n /**\n * Returns the producer to the provider.\n *\n * `discard` is true when the session's state is unknown — a failed unlock, a\n * failed cleanup, or a thrown body — and the provider must then destroy the\n * connection rather than hand a session carrying unknown state back to a\n * pool. A provider whose session can never be made clean again (MySQL2, which\n * has executed `USE` and possibly author-owned statements) destroys\n * unconditionally and ignores the flag.\n *\n * `lost` is true when the connection itself is gone or stopped answering:\n * the provider must send nothing more on it — not even the reset a discard\n * otherwise runs — and abandon or destroy it.\n */\n release(discard: boolean, lost?: boolean): Promise<void>;\n}\n\n/**\n * The handle the pinned body uses to condemn its own producer.\n *\n * A thrown body already condemns the session. This exists for the case that\n * does not throw: an unlock statement that RETURNS a result proving the lock\n * was not released. That session is still usable in the provider's eyes and\n * would be returned to the pool holding a lock nobody owns.\n */\nexport interface PinnedSessionControl {\n /** Condemn this producer; it will be destroyed instead of released. */\n discard(): void;\n /**\n * Whether this session's connection is gone: the provider saw it end,\n * `failure` reports it, or a cleanup statement went unanswered. Once true it\n * stays true, and nothing more is sent on the session (plan S2).\n */\n lost(failure?: unknown): boolean;\n /** Runs one cleanup statement within `CLEANUP_BOUND_MS`; past it, the session is lost. */\n cleanup<T>(run: () => Promise<T>): Promise<T>;\n}\n\n/**\n * The refusal a discarded session whose reset FAILED raises.\n *\n * A session is discarded because its state is unknown, and the reset is what\n * makes it known again. When the reset fails too, the session may still hold\n * the migration lock every other command is excluded by — so it must not go\n * back to the provider, and saying nothing about that is not an option either:\n * a swallowed cleanup failure is how a pool ends up serving a connection that\n * blocks the next migration forever.\n *\n * The reset's own failure is the evidence, and it is the PROVIDER's value: it\n * goes through the one total normalizer rather than a bare `instanceof`, which\n * a rejection whose `getPrototypeOf` trap throws turns into a throw inside this\n * constructor — replacing the whole typed refusal with the trap's error.\n */\nexport function unprovenLockStateError(\n driverName: string,\n containment: string,\n cause: unknown\n): ConnectionError {\n return abandonedSessionError(\n driverName,\n ADVISORY_RESET_FAILED,\n containment,\n errorCause(cause)\n );\n}\n\nfunction abandonedSessionError(\n driverName: string,\n reason: string,\n containment: string,\n cause: Error | undefined\n): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" ${reason} ${containment}`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n cause,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * The refusal raised afterwards by EVERY driver whose one client was condemned.\n *\n * A transport that pools connections recovers by reserving a different one, so\n * this is only for the driver whose single client IS the session: there is no\n * other connection to reach for, and running the next migration command on a\n * session that may still hold the lock is precisely what the condemnation\n * exists to prevent. Two drivers over that one client are two callers of this\n * same refusal, because the session they would both pin is the same session.\n */\nexport function condemnedSessionError(driverName: string): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" will pin no further migration session: an earlier session's \"${ADVISORY_RESET}\" reset failed, so the advisory-lock state of its one client is unknown. That client was not closed — it is the caller's database, not a pooled connection VibORM may discard — and ordinary queries on it are unaffected.`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * What was actually DONE about the abandoned connection, in the refusal's own\n * words.\n *\n * Three outcomes, three sentences, each chosen once the outcome is known\n * rather than once the ownership is known. A single sentence written before the\n * close was attempted claimed the backend had been ended even when ending it\n * threw — and the one thing a caller does with that claim is stop looking for a\n * connection that is still running, still holding the lock this refusal exists\n * to report.\n */\nconst CALLER_OWNED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool. VibORM did not close the transport, which belongs to the caller, so the lock is freed when that connection is.\";\nconst CLOSED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool, and the transport VibORM created for it was closed — which ends that backend, and with it every advisory lock it held.\";\nconst CLOSE_FAILED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool, and ending the transport VibORM created for it FAILED: that backend may still be running, and any advisory lock it holds is freed only when it goes away. VibORM withdrew that transport and will not use it again.\";\n\n/**\n * Returns a reserved PostgreSQL session to its pool, or condemns it — the ONE\n * rule for every provider that reserves a connection it cannot destroy.\n *\n * postgres.js and Bun SQL both expose `release()` and nothing else: there is no\n * destructive return to reach for, so a session whose reset failed is ABANDONED\n * — never released — which is the only way it stops being a connection the pool\n * will hand to the next caller.\n *\n * Abandoning it leaves the lock held until that backend goes away, so a\n * transport VibORM created is closed too: ending it terminates the backend, and\n * PostgreSQL frees every advisory lock the session held. A transport the CALLER\n * supplied is never closed for this — it is theirs, may be serving their own\n * code, and closing it to tidy up VibORM's cleanup failure would be a far\n * larger effect than the one being contained.\n *\n * A LOST session (plan S2) is abandoned the same way without the reset: its\n * connection is gone or stopped answering, and a statement written to it is,\n * on postgres.js, an uncaught crash from inside the provider's write loop. Its\n * owned transport is closed; a supplied one is reported, since abandoning is\n * all VibORM may do with it.\n */\nexport async function releaseReservedPostgresSession(reservation: {\n readonly driverName: string;\n readonly discard: boolean;\n readonly lost?: boolean | undefined;\n /** Runs `SELECT pg_advisory_unlock_all()` on the reserved session. */\n readonly reset: () => Promise<unknown>;\n /** Hands the reserved session back to the provider's pool. */\n readonly release: () => void;\n /** Closes the transport, or absent when the CALLER owns it. */\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n}): Promise<void> {\n if (reservation.lost === true) {\n const { closeOwnedTransport, driverName } = reservation;\n if (closeOwnedTransport === undefined) {\n throw abandonedSessionError(\n driverName,\n LOST_SESSION,\n CALLER_OWNED_CONTAINMENT,\n undefined\n );\n }\n // Not awaited: the connection failure the caller holds is already the\n // answer, and the close lets the transport's other queries finish first\n // (postgres.js waits on the dead connection's unsettled query until its\n // bound). The transport is withdrawn before it closes, and a session the\n // close cannot end is ended by the server's idle limit.\n closeOwnedTransport().catch(() => undefined);\n return;\n }\n if (!reservation.discard) {\n reservation.release();\n return;\n }\n\n try {\n await settleWithin(\n reservation.reset(),\n CLEANUP_BOUND_MS,\n () =>\n new Error(\n `The advisory-lock reset went unanswered for ${CLEANUP_BOUND_MS} ms.`\n )\n );\n } catch (resetFailure) {\n await abandon(reservation, ADVISORY_RESET_FAILED, resetFailure);\n }\n reservation.release();\n}\n\n/**\n * Abandons a reserved session: never released, its owned transport closed,\n * and the refusal that says so thrown. A transport the caller supplied is only\n * abandoned.\n */\nasync function abandon(\n reservation: {\n readonly driverName: string;\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n },\n reason: string,\n cause: unknown\n): Promise<void> {\n const { closeOwnedTransport, driverName } = reservation;\n if (closeOwnedTransport === undefined) {\n throw abandonedSessionError(\n driverName,\n reason,\n CALLER_OWNED_CONTAINMENT,\n errorCause(cause)\n );\n }\n try {\n await closeOwnedTransport();\n } catch (closeFailure) {\n // The reason stays primary — it is what the caller acts on — and the\n // close's own failure is cleanup evidence beside it.\n throw withSuppressedFailure(\n abandonedSessionError(\n driverName,\n reason,\n CLOSE_FAILED_CONTAINMENT,\n errorCause(cause)\n ),\n closeFailure\n );\n }\n throw abandonedSessionError(\n driverName,\n reason,\n CLOSED_CONTAINMENT,\n errorCause(cause)\n );\n}\n\n/** What VibORM knows about one PHYSICAL session it pins commands on. */\ninterface PhysicalSessionState {\n /**\n * The pinned commands already queued on this session. It never rejects, so\n * one command's failure cannot poison the queue — the next command runs\n * either way, exactly as it would after a success.\n */\n queued: Promise<void>;\n /**\n * Set when a discarded session's advisory-lock reset failed, and never\n * cleared: nothing that happens later can prove a lock was released.\n */\n condemned: boolean;\n}\n\n/**\n * What is known about each PHYSICAL session, keyed on the session itself.\n *\n * A driver's connection queue serializes the commands of THAT driver. Two\n * drivers built over one supplied client — the documented shape for two\n * schema-scoped estates over one PGlite — own two queues and one session, so\n * the queue arbitrates nothing between them, and a PostgreSQL session advisory\n * lock is REENTRANT: the second command re-acquires the lock the first is\n * holding instead of waiting for it, then reads and writes inside the first\n * command's session. The client is the only thing both drivers agree on, so it\n * is what this is keyed on.\n *\n * The condemnation shares that key because it answers for the same subject: a\n * failed reset leaves the CLIENT's lock state unknown, not the wrapper's. Kept\n * on the driver instead, it was a fact the other wrappers over that client\n * never consulted, and their next command ran inside the session it condemned.\n *\n * Weak by construction: the entry dies with the client, and a client nobody\n * holds keeps nothing alive here.\n */\nconst PHYSICAL_SESSIONS = new WeakMap<object, PhysicalSessionState>();\n\n/**\n * Refuses a command on a session whose advisory-lock state was condemned.\n *\n * One refusal, read at two moments, and each covers what the other cannot. At\n * ADMISSION, so a session condemned before this command arrived refuses now\n * rather than behind a queue whose head may itself be waiting on the very lock\n * nobody can account for. At the FRONT of the queue, because condemnation lands\n * BETWEEN the two: the command ahead of this one is the one whose reset fails,\n * and this one was admitted while that session still looked accountable.\n */\nfunction refuseCondemnedSession(\n driverName: string,\n state: PhysicalSessionState\n): void {\n if (state.condemned) {\n throw condemnedSessionError(driverName);\n }\n}\n\n/**\n * Runs `command` exclusively on this physical session, when it may still be\n * pinned at all.\n *\n * The refusal is here rather than beside it because this is the one path every\n * pinned command over a shared session takes, and it lands before `command` —\n * so no body and no statement of the refused command reaches the client.\n */\nexport function leasePinnedCommand<T>(\n driverName: string,\n session: object,\n command: () => Promise<T>\n): Promise<T> {\n const state = physicalSessionState(session);\n refuseCondemnedSession(driverName, state);\n const next = state.queued.then(() => {\n refuseCondemnedSession(driverName, state);\n return command();\n });\n state.queued = next.then(\n () => undefined,\n () => undefined\n );\n return next;\n}\n\n/**\n * Records that this physical session's advisory-lock state can no longer be\n * accounted for — for every driver that reaches it, not only the one whose\n * reset failed.\n */\nexport function condemnPhysicalSession(session: object): void {\n physicalSessionState(session).condemned = true;\n}\n\n/** This session's state, created on first use and mutated in place after. */\nfunction physicalSessionState(session: object): PhysicalSessionState {\n const existing = PHYSICAL_SESSIONS.get(session);\n if (existing) {\n return existing;\n }\n const created: PhysicalSessionState = {\n queued: Promise.resolve(),\n condemned: false,\n };\n PHYSICAL_SESSIONS.set(session, created);\n return created;\n}\n"],"mappings":"iOAMA,MAAM,EAAiB,kCAKjB,EAAwB,kFAAkF,EAAe,iBAWlH,EAAmB,IA4EhC,SAAgB,uBACd,EACA,EACA,EACiB,CACjB,OAAO,sBACL,EACA,EACA,EACA,EAAW,EAAM,CAClB,CAGH,SAAS,sBACP,EACA,EACA,EACA,EACiB,CACjB,OAAO,IAAI,EACT,WAAW,EAAW,IAAI,EAAO,GAAG,IACpC,CACE,KAAM,EAAgB,kBACtB,QACA,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CACzD,CACF,CAaH,SAAgB,sBAAsB,EAAqC,CACzE,OAAO,IAAI,EACT,WAAW,EAAW,iEAAiE,EAAe,4NACtG,CACE,KAAM,EAAgB,kBACtB,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CACzD,CACF,CAcH,MAAM,EACJ,yLA4BF,eAAsB,+BAA+B,EAUnC,CAChB,GAAI,EAAY,OAAS,GAAM,CAC7B,GAAM,CAAE,sBAAqB,cAAe,EAC5C,GAAI,IAAwB,IAAA,GAC1B,MAAM,sBACJ,EACA,mFACA,EACA,IAAA,GACD,CAOH,GAAqB,CAAC,UAAY,IAAA,GAAU,CAC5C,OAEF,GAAI,CAAC,EAAY,QAAS,CACxB,EAAY,SAAS,CACrB,OAGF,GAAI,CACF,MAAM,EACJ,EAAY,OAAO,CACnB,MAEM,MACF,+CAA+C,EAAiB,MACjE,CACJ,OACM,EAAc,CACrB,MAAM,QAAQ,EAAa,EAAuB,EAAa,CAEjE,EAAY,SAAS,CAQvB,eAAe,QACb,EAIA,EACA,EACe,CACf,GAAM,CAAE,sBAAqB,cAAe,EAC5C,GAAI,IAAwB,IAAA,GAC1B,MAAM,sBACJ,EACA,EACA,EACA,EAAW,EAAM,CAClB,CAEH,GAAI,CACF,MAAM,GAAqB,OACpB,EAAc,CAGrB,MAAM,EACJ,sBACE,EACA,EACA,8RACA,EAAW,EAAM,CAClB,CACD,EACD,CAEH,MAAM,sBACJ,EACA,EACA,iMACA,EAAW,EAAM,CAClB,CAsCH,MAAM,EAAoB,IAAI,QAY9B,SAAS,uBACP,EACA,EACM,CACN,GAAI,EAAM,UACR,MAAM,sBAAsB,EAAW,CAY3C,SAAgB,mBACd,EACA,EACA,EACY,CACZ,IAAM,EAAQ,qBAAqB,EAAQ,CAC3C,uBAAuB,EAAY,EAAM,CACzC,IAAM,EAAO,EAAM,OAAO,UACxB,uBAAuB,EAAY,EAAM,CAClC,GAAS,EAChB,CAKF,MAJA,GAAM,OAAS,EAAK,SACZ,IAAA,OACA,IAAA,GACP,CACM,EAQT,SAAgB,uBAAuB,EAAuB,CAC5D,qBAAqB,EAAQ,CAAC,UAAY,GAI5C,SAAS,qBAAqB,EAAuC,CACnE,IAAM,EAAW,EAAkB,IAAI,EAAQ,CAC/C,GAAI,EACF,OAAO,EAET,IAAM,EAAgC,CACpC,OAAQ,QAAQ,SAAS,CACzB,UAAW,GACZ,CAED,OADA,EAAkB,IAAI,EAAS,EAAQ,CAChC"}
@@ -1,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, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-VsM29vYN.mjs";
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, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-D4O0Twvs.mjs";
2
2
  import { Client, Config, Connection } from "@planetscale/database";
3
3
 
4
4
  //#region src/drivers/planetscale/index.d.ts
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./value-guards-CK9guf2Z.mjs";import{c as n,s as r}from"./bind-parameter-capacity-qfEejeOX.mjs";import{l as i,p as a}from"./error-mapping-C9WgitPi.mjs";import{p as o}from"./validation-BamBwne9.mjs";import{s}from"./execution-context-rJXTRVrJ.mjs";import{n as c}from"./client-_WKrPNmm.mjs";import{a as l,c as u,d,o as f,t as p}from"./driver-B9fIori_.mjs";import{t as m}from"./sql-statement-tokens-CFi1y3bK.mjs";import{t as h}from"./mysql-adapter-C6c5govr.mjs";const g=/^(?:0|[1-9]\d*)$/,_=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,v=new Set([`ANALYZE`,`CALL`,`DESC`,`DESCRIBE`,`EXPLAIN`,`SELECT`,`SHOW`,`VALUES`]),y=new Set([`DELETE`,`INSERT`,`REPLACE`,`UPDATE`]),b=new Set([`ALTER`,`BEGIN`,`COMMIT`,`CREATE`,`DROP`,`LOCK`,`RELEASE`,`RENAME`,`ROLLBACK`,`SAVEPOINT`,`SET`,`TRUNCATE`,`UNLOCK`,`USE`]),x=new Set([...v,...y]),defaultFetch=async(e,t)=>globalThis.fetch(e,t);function isRecord(e){return typeof e==`object`&&!!e&&Object.prototype.toString.call(e)===`[object Object]`}function isExecuteEndpoint(e){try{return new URL(e).pathname===`/psdb.v1alpha1.Database/Execute`}catch{return!1}}function getRequestQuery(e){if(typeof e==`string`)try{let t=JSON.parse(e);return isRecord(t)&&typeof t.query==`string`?t.query:void 0}catch{return}}function classifyStatement(e){if(!e)return`unknown`;let t=m(e,{backslashEscapes:!0}),n=t?.[0];if(!(t&&n)||n.kind!==`word`)return`unknown`;let r=0;if(n.value===`WITH`&&(r=t.findIndex((e,t)=>t>0&&e.kind===`word`&&x.has(e.value)),r<0))return`unknown`;let i=t[r]?.value;return i?v.has(i)?`rows`:y.has(i)?t.slice(r+1).some(e=>e.kind===`word`&&e.value===`RETURNING`)?`rows`:`no-rows`:b.has(i)?`no-rows`:`unknown`:`unknown`}function malformedPlanetScaleResponse(e){return new o(`Driver "planetscale" returned a malformed successful response: ${e}.`,{meta:{driver:`planetscale`}})}function assertDenseArray(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t+=1)if(!Object.hasOwn(e,t))return!1;return!0}function validateFields(e){if(!assertDenseArray(e))throw malformedPlanetScaleResponse(`result.fields is not a dense array`);let t=[],n=new Set;for(let r of e){if(!isRecord(r)||typeof r.name!=`string`||r.name.length===0||r.type!==void 0&&typeof r.type!=`string`)throw malformedPlanetScaleResponse(`result.fields contains an invalid field descriptor`);if(r.name===`__proto__`||n.has(r.name))throw malformedPlanetScaleResponse(`result.fields contains an unsafe or duplicate field name`);n.add(r.name),t.push(r)}return t}function validateRows(e,t){if(!assertDenseArray(e))throw malformedPlanetScaleResponse(`result.rows is not a dense array`);if(e.length>0&&t.length===0)throw malformedPlanetScaleResponse(`non-empty result.rows has no matching field metadata`);for(let n of e){if(!(isRecord(n)&&assertDenseArray(n.lengths)))throw malformedPlanetScaleResponse(`result.rows contains a row that does not match result.fields`);let e=getExpectedRowByteLength(n.lengths,t.length),r=getBase64ByteLength(n.values);if(e===void 0||r!==e)throw malformedPlanetScaleResponse(`result.rows contains a row that does not match result.fields`)}}function getExpectedRowByteLength(e,t){if(e.length!==t)return;let n=0;for(let t of e){if(t===`-1`)continue;if(typeof t!=`string`||!g.test(t))return;let e=Number(t);if(!Number.isSafeInteger(e)||n>2**53-1-e)return;n+=e}return n}function getBase64ByteLength(e){if(e===void 0)return 0;if(!(typeof e!=`string`||!_.test(e)))try{let t=atob(e);return btoa(t)===e?t.length:void 0}catch{return}}function validateExecuteEnvelope(e,t){if(!isRecord(e))throw malformedPlanetScaleResponse(`the response body is not an object`);if(Object.hasOwn(e,`error`)&&e.error!=null)return;if(!Object.hasOwn(e,`result`))throw malformedPlanetScaleResponse(`the result member is absent`);let n=e.result;if(n===null){if(t===`no-rows`)return;throw malformedPlanetScaleResponse(`a row-producing or unknown statement has a null result member`)}if(!isRecord(n))throw malformedPlanetScaleResponse(`the result member is not an object or null`);let r=[];if(Object.hasOwn(n,`fields`)&&n.fields!==null&&(r=validateFields(n.fields)),t!==`no-rows`&&r.length===0)throw malformedPlanetScaleResponse(`a row-producing or unknown statement has no field metadata`);if(Object.hasOwn(n,`rows`)&&validateRows(n.rows,r),Object.hasOwn(n,`rowsAffected`)&&n.rowsAffected!==null&&(typeof n.rowsAffected!=`string`||!g.test(n.rowsAffected)))throw malformedPlanetScaleResponse(`result.rowsAffected is malformed`);if(Object.hasOwn(n,`insertId`)&&n.insertId!==null&&(typeof n.insertId!=`string`||!g.test(n.insertId)))throw malformedPlanetScaleResponse(`result.insertId is malformed`)}function wrapExecuteResponse(e,t){return new Proxy(e,{get(e,n){if(n===`json`)return async()=>{let n;try{n=await e.json()}catch{throw malformedPlanetScaleResponse(`the response body is not valid JSON`)}return validateExecuteEnvelope(n,t),n};if(n===`text`)return async()=>{let n=await e.text(),r;try{r=JSON.parse(n)}catch{throw malformedPlanetScaleResponse(`the response body is not valid JSON`)}return validateExecuteEnvelope(r,t),n};let r=Reflect.get(e,n,e);return typeof r==`function`?r.bind(e):r}})}function createValidatedPlanetScaleFetch(e){let t=e??defaultFetch;return async(e,n)=>{let r=classifyStatement(getRequestQuery(n?.body)),i=await t(e,n);return isExecuteEndpoint(e)&&i.ok?wrapExecuteResponse(i,r):i}}const S={client:!0,databaseUrl:!0,options:!0,namespace:!0};function toQueryResult(e,t){let i={provider:`planetscale`,operation:t},a=r(e.insertId,i);return{rows:e.rows,rowCount:n(e.rowsAffected,i),...a===void 0?{}:{insertId:a}}}var PlanetScaleDriver=class extends p{maxBindParametersPerStatement=65535;supportsTransactions=!0;driverOptions;constructor(e={}){let t=d(e);super(`mysql`,`planetscale`),this.driverOptions=e,f(this,`adapter`,new h(t))}async initClient(){let{Client:e}=await import(`@planetscale/database`),n=this.driverOptions.client;if(n){if(!t(n.config))return n;let r={...n.config};return r.fetch=createValidatedPlanetScaleFetch(r.fetch),new e(r)}let r={...this.driverOptions.options};return this.driverOptions.databaseUrl&&(r.url=this.driverOptions.databaseUrl),r.fetch=createValidatedPlanetScaleFetch(r.fetch),new e(r)}async closeClient(e){}async execute(e,t,n,r){let i=r?.operation??`execute`;return toQueryResult(await e.execute(t,n),i)}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`;return toQueryResult(await e.execute(t,n),i)}transactionOptionSupport(){return{isolationLevel:`pre-begin`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`each PlanetScale transaction gets its own HTTP connection created without waiting, so there is no acquisition maxWait could bound`}}async transaction(e,t,n,r){if(!(`transaction`in e))throw i(this.driverName);let o=`connection`in e?e.connection():e,c=r?.isolationLevel;return a({begin:async()=>{await o.execute(`SET transaction_mode = 'single'`),c&&await o.execute(l(c)),await o.execute(`BEGIN`)},callback:()=>t(o),commit:()=>o.execute(`COMMIT`),rollback:()=>o.execute(`ROLLBACK`),phases:s(n)})}transactionCleanupFailed(e){this.client&&`connection`in this.client||super.transactionCleanupFailed(e)}};function createClient(e){u(e,`planetscale`,S);let{client:t,databaseUrl:n,options:r}=e;return c(e,new PlanetScaleDriver({client:t,databaseUrl:n,options:r,namespace:d(e)}))}export{PlanetScaleDriver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./value-guards-CK9guf2Z.mjs";import{c as n,s as r}from"./bind-parameter-capacity-qfEejeOX.mjs";import{l as i,p as a}from"./error-mapping-C9WgitPi.mjs";import{p as o}from"./validation-BamBwne9.mjs";import{s}from"./execution-context-rJXTRVrJ.mjs";import{n as c}from"./client-BCgMXn6N.mjs";import{a as l,c as u,d,o as f,t as p}from"./driver-Ddt147dK.mjs";import{t as m}from"./sql-statement-tokens-BW7Q-rF-.mjs";import{t as h}from"./mysql-adapter-ClOoHKpn.mjs";const g=/^(?:0|[1-9]\d*)$/,_=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,v=new Set([`ANALYZE`,`CALL`,`DESC`,`DESCRIBE`,`EXPLAIN`,`SELECT`,`SHOW`,`VALUES`]),y=new Set([`DELETE`,`INSERT`,`REPLACE`,`UPDATE`]),b=new Set([`ALTER`,`BEGIN`,`COMMIT`,`CREATE`,`DROP`,`LOCK`,`RELEASE`,`RENAME`,`ROLLBACK`,`SAVEPOINT`,`SET`,`TRUNCATE`,`UNLOCK`,`USE`]),x=new Set([...v,...y]),defaultFetch=async(e,t)=>globalThis.fetch(e,t);function isRecord(e){return typeof e==`object`&&!!e&&Object.prototype.toString.call(e)===`[object Object]`}function isExecuteEndpoint(e){try{return new URL(e).pathname===`/psdb.v1alpha1.Database/Execute`}catch{return!1}}function getRequestQuery(e){if(typeof e==`string`)try{let t=JSON.parse(e);return isRecord(t)&&typeof t.query==`string`?t.query:void 0}catch{return}}function classifyStatement(e){if(!e)return`unknown`;let t=m(e,{backslashEscapes:!0}),n=t?.[0];if(!(t&&n)||n.kind!==`word`)return`unknown`;let r=0;if(n.value===`WITH`&&(r=t.findIndex((e,t)=>t>0&&e.kind===`word`&&x.has(e.value)),r<0))return`unknown`;let i=t[r]?.value;return i?v.has(i)?`rows`:y.has(i)?t.slice(r+1).some(e=>e.kind===`word`&&e.value===`RETURNING`)?`rows`:`no-rows`:b.has(i)?`no-rows`:`unknown`:`unknown`}function malformedPlanetScaleResponse(e){return new o(`Driver "planetscale" returned a malformed successful response: ${e}.`,{meta:{driver:`planetscale`}})}function assertDenseArray(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t+=1)if(!Object.hasOwn(e,t))return!1;return!0}function validateFields(e){if(!assertDenseArray(e))throw malformedPlanetScaleResponse(`result.fields is not a dense array`);let t=[],n=new Set;for(let r of e){if(!isRecord(r)||typeof r.name!=`string`||r.name.length===0||r.type!==void 0&&typeof r.type!=`string`)throw malformedPlanetScaleResponse(`result.fields contains an invalid field descriptor`);if(r.name===`__proto__`||n.has(r.name))throw malformedPlanetScaleResponse(`result.fields contains an unsafe or duplicate field name`);n.add(r.name),t.push(r)}return t}function validateRows(e,t){if(!assertDenseArray(e))throw malformedPlanetScaleResponse(`result.rows is not a dense array`);if(e.length>0&&t.length===0)throw malformedPlanetScaleResponse(`non-empty result.rows has no matching field metadata`);for(let n of e){if(!(isRecord(n)&&assertDenseArray(n.lengths)))throw malformedPlanetScaleResponse(`result.rows contains a row that does not match result.fields`);let e=getExpectedRowByteLength(n.lengths,t.length),r=getBase64ByteLength(n.values);if(e===void 0||r!==e)throw malformedPlanetScaleResponse(`result.rows contains a row that does not match result.fields`)}}function getExpectedRowByteLength(e,t){if(e.length!==t)return;let n=0;for(let t of e){if(t===`-1`)continue;if(typeof t!=`string`||!g.test(t))return;let e=Number(t);if(!Number.isSafeInteger(e)||n>2**53-1-e)return;n+=e}return n}function getBase64ByteLength(e){if(e===void 0)return 0;if(!(typeof e!=`string`||!_.test(e)))try{let t=atob(e);return btoa(t)===e?t.length:void 0}catch{return}}function validateExecuteEnvelope(e,t){if(!isRecord(e))throw malformedPlanetScaleResponse(`the response body is not an object`);if(Object.hasOwn(e,`error`)&&e.error!=null)return;if(!Object.hasOwn(e,`result`))throw malformedPlanetScaleResponse(`the result member is absent`);let n=e.result;if(n===null){if(t===`no-rows`)return;throw malformedPlanetScaleResponse(`a row-producing or unknown statement has a null result member`)}if(!isRecord(n))throw malformedPlanetScaleResponse(`the result member is not an object or null`);let r=[];if(Object.hasOwn(n,`fields`)&&n.fields!==null&&(r=validateFields(n.fields)),t!==`no-rows`&&r.length===0)throw malformedPlanetScaleResponse(`a row-producing or unknown statement has no field metadata`);if(Object.hasOwn(n,`rows`)&&validateRows(n.rows,r),Object.hasOwn(n,`rowsAffected`)&&n.rowsAffected!==null&&(typeof n.rowsAffected!=`string`||!g.test(n.rowsAffected)))throw malformedPlanetScaleResponse(`result.rowsAffected is malformed`);if(Object.hasOwn(n,`insertId`)&&n.insertId!==null&&(typeof n.insertId!=`string`||!g.test(n.insertId)))throw malformedPlanetScaleResponse(`result.insertId is malformed`)}function wrapExecuteResponse(e,t){return new Proxy(e,{get(e,n){if(n===`json`)return async()=>{let n;try{n=await e.json()}catch{throw malformedPlanetScaleResponse(`the response body is not valid JSON`)}return validateExecuteEnvelope(n,t),n};if(n===`text`)return async()=>{let n=await e.text(),r;try{r=JSON.parse(n)}catch{throw malformedPlanetScaleResponse(`the response body is not valid JSON`)}return validateExecuteEnvelope(r,t),n};let r=Reflect.get(e,n,e);return typeof r==`function`?r.bind(e):r}})}function createValidatedPlanetScaleFetch(e){let t=e??defaultFetch;return async(e,n)=>{let r=classifyStatement(getRequestQuery(n?.body)),i=await t(e,n);return isExecuteEndpoint(e)&&i.ok?wrapExecuteResponse(i,r):i}}const S={client:!0,databaseUrl:!0,options:!0,namespace:!0};function toQueryResult(e,t){let i={provider:`planetscale`,operation:t},a=r(e.insertId,i);return{rows:e.rows,rowCount:n(e.rowsAffected,i),...a===void 0?{}:{insertId:a}}}var PlanetScaleDriver=class extends p{maxBindParametersPerStatement=65535;supportsTransactions=!0;driverOptions;constructor(e={}){let t=d(e);super(`mysql`,`planetscale`),this.driverOptions=e,f(this,`adapter`,new h(t))}async initClient(){let{Client:e}=await import(`@planetscale/database`),n=this.driverOptions.client;if(n){if(!t(n.config))return n;let r={...n.config};return r.fetch=createValidatedPlanetScaleFetch(r.fetch),new e(r)}let r={...this.driverOptions.options};return this.driverOptions.databaseUrl&&(r.url=this.driverOptions.databaseUrl),r.fetch=createValidatedPlanetScaleFetch(r.fetch),new e(r)}async closeClient(e){}async execute(e,t,n,r){let i=r?.operation??`execute`;return toQueryResult(await e.execute(t,n),i)}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`;return toQueryResult(await e.execute(t,n),i)}transactionOptionSupport(){return{isolationLevel:`pre-begin`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`each PlanetScale transaction gets its own HTTP connection created without waiting, so there is no acquisition maxWait could bound`}}async transaction(e,t,n,r){if(!(`transaction`in e))throw i(this.driverName);let o=`connection`in e?e.connection():e,c=r?.isolationLevel;return a({begin:async()=>{await o.execute(`SET transaction_mode = 'single'`),c&&await o.execute(l(c)),await o.execute(`BEGIN`)},callback:()=>t(o),commit:()=>o.execute(`COMMIT`),rollback:()=>o.execute(`ROLLBACK`),phases:s(n)})}transactionCleanupFailed(e){this.client&&`connection`in this.client||super.transactionCleanupFailed(e)}};function createClient(e){u(e,`planetscale`,S);let{client:t,databaseUrl:n,options:r}=e;return c(e,new PlanetScaleDriver({client:t,databaseUrl:n,options:r,namespace:d(e)}))}export{PlanetScaleDriver,createClient};
2
2
  //# sourceMappingURL=planetscale.mjs.map
@@ -1,4 +1,4 @@
1
- import { Ki as DecimalDescriptor, Un as AnyModel, l as AnyDriver, mn as DateTimePhysicalForm } from "./index-VsM29vYN.mjs";
1
+ import { Ki as DecimalDescriptor, Un as AnyModel, l as AnyDriver, mn as DateTimePhysicalForm } from "./index-D4O0Twvs.mjs";
2
2
 
3
3
  //#region src/migrations/limits.d.ts
4
4
 
@@ -1,4 +1,4 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,n}from"./base-D3m1S7Uc.mjs";import{t as r}from"./migrations-Bn1SatyB.mjs";import{Ct as i,_ as a,j as o,m as s}from"./geo-point-codec-DyEHMdJg.mjs";import{s as c}from"./scalar-S8yMvdmx.mjs";import{o as l}from"./native-types-asNCr26n.mjs";import{a as u,r as d}from"./physical-CAOaNM4R.mjs";import{a as f}from"./datetime-physical-codec-BEqQbIP_.mjs";import{B as p,J as m,M as h,O as g,P as _,b as v,g as y,m as b,ut as x,v as S,x as C,y as w,z as T}from"./client-DM1UHfYG.mjs";import{n as ee,t as E}from"./array-literal-BKdLfNzM.mjs";import{a as D,n as O}from"./identity-oQvIe7u8.mjs";import{P as te}from"./standard-sql-CoGqv-iX.mjs";import{a as k,i as A,n as ne,o as j,r as ie}from"./identifier-conversion-DaZ9yNpv.mjs";const M=/;\s*$/,N=/-/g;function quoteIdentifier(e){return`"${e.replace(/"/g,`""`)}"`}function quoteLiteral(e){return`'${e.replace(/'/g,`''`)}'`}async function canonicalizeIndexPredicates(e,t,n,r,i){if(n.length===0)return[];let a=i??(async e=>{let t=[];for(let n of e)t.push(await r(n));return t}),deparse=async t=>{let n=[...t.keys()].filter(e=>t[e]!==void 0);if(n.length===0)return t.map(()=>void 0);let r=`viborm_index_predicate_${crypto.randomUUID().replace(N,``)}_`,i=n.map(e=>`${r}${e}`),o=i.map(t=>`${quoteIdentifier(e)}.${quoteIdentifier(t)}`),s=await a([...n.map((e,n)=>`CREATE VIEW ${o[n]} AS ${t[e]}`),`SELECT c.relname AS name, pg_catalog.pg_get_viewdef(c.oid) AS definition FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ${quoteLiteral(e)} AND c.relname IN (${i.map(quoteLiteral).join(`, `)})`,`DROP VIEW ${o.join(`, `)}`]),c=new Map(s[n.length]?.rows.map(e=>[e.name,e.definition]));return t.map((e,t)=>e===void 0?void 0:c.get(`${r}${t}`)??void 0)};return deparse((await deparse(n.map(e=>`SELECT 1 AS c FROM ${t} WHERE ${e}`))).map(e=>e?.replace(M,``)))}const P=/::(?:"(?:[^"]|"")+"|[a-zA-Z_][\w$]*)(?:\.(?:"(?:[^"]|"")+"|[a-zA-Z_][\w$]*))?(?:\s+(?:varying|precision|with time zone|without time zone))?(?:\(\d+(?:,\s*\d+)?\))?(?:\[\])?$/,F=new Set([`pg_catalog`,`information_schema`]),I={supportsVector:[`vector`,`halfvec`,`sparsevec`],geoPoint:[`geometry`,`geography`]};function admittedExtensionTypes(e){let t=e?.adapter;return new Set([...t?.capabilities.supportsVector?I.supportsVector:[],...t?.geoPoint?I.geoPoint:[]])}const L=`
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,n}from"./base-D3m1S7Uc.mjs";import{t as r}from"./migrations-Bn1SatyB.mjs";import{Ct as i,_ as a,j as o,m as s}from"./geo-point-codec-DyEHMdJg.mjs";import{s as c}from"./scalar-CqqZ6jWd.mjs";import{o as l}from"./native-types-asNCr26n.mjs";import{a as u,r as d}from"./physical-CAOaNM4R.mjs";import{a as f}from"./datetime-physical-codec-BEqQbIP_.mjs";import{B as p,J as m,M as h,O as g,P as _,b as v,g as y,m as b,ut as x,v as S,x as C,y as w,z as T}from"./client-q6ccRgdO.mjs";import{n as ee,t as E}from"./array-literal-BKdLfNzM.mjs";import{a as D,n as O}from"./identity-Bj2EN6Ss.mjs";import{P as te}from"./standard-sql-mJt0RHHE.mjs";import{a as k,i as A,n as ne,o as j,r as ie}from"./identifier-conversion-C2pwwFOS.mjs";const M=/;\s*$/,N=/-/g;function quoteIdentifier(e){return`"${e.replace(/"/g,`""`)}"`}function quoteLiteral(e){return`'${e.replace(/'/g,`''`)}'`}async function canonicalizeIndexPredicates(e,t,n,r,i){if(n.length===0)return[];let a=i??(async e=>{let t=[];for(let n of e)t.push(await r(n));return t}),deparse=async t=>{let n=[...t.keys()].filter(e=>t[e]!==void 0);if(n.length===0)return t.map(()=>void 0);let r=`viborm_index_predicate_${crypto.randomUUID().replace(N,``)}_`,i=n.map(e=>`${r}${e}`),o=i.map(t=>`${quoteIdentifier(e)}.${quoteIdentifier(t)}`),s=await a([...n.map((e,n)=>`CREATE VIEW ${o[n]} AS ${t[e]}`),`SELECT c.relname AS name, pg_catalog.pg_get_viewdef(c.oid) AS definition FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ${quoteLiteral(e)} AND c.relname IN (${i.map(quoteLiteral).join(`, `)})`,`DROP VIEW ${o.join(`, `)}`]),c=new Map(s[n.length]?.rows.map(e=>[e.name,e.definition]));return t.map((e,t)=>e===void 0?void 0:c.get(`${r}${t}`)??void 0)};return deparse((await deparse(n.map(e=>`SELECT 1 AS c FROM ${t} WHERE ${e}`))).map(e=>e?.replace(M,``)))}const P=/::(?:"(?:[^"]|"")+"|[a-zA-Z_][\w$]*)(?:\.(?:"(?:[^"]|"")+"|[a-zA-Z_][\w$]*))?(?:\s+(?:varying|precision|with time zone|without time zone))?(?:\(\d+(?:,\s*\d+)?\))?(?:\[\])?$/,F=new Set([`pg_catalog`,`information_schema`]),I={supportsVector:[`vector`,`halfvec`,`sparsevec`],geoPoint:[`geometry`,`geography`]};function admittedExtensionTypes(e){let t=e?.adapter;return new Set([...t?.capabilities.supportsVector?I.supportsVector:[],...t?.geoPoint?I.geoPoint:[]])}const L=`
2
2
  SELECT tables.table_name, tables.table_name AS name, relation.relkind AS relation_kind, relation.relispartition AS is_partition
3
3
  FROM information_schema.tables tables
4
4
  JOIN pg_catalog.pg_class relation
@@ -412,4 +412,4 @@ SELECT (
412
412
  JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
413
413
  WHERE t.typtype = 'e' AND n.nspname = $1
414
414
  ORDER BY t.typname`,params:[this.requireEstateNamespace()]}}generateDropEnumSQL(e){return`DROP TYPE IF EXISTS ${this.qualify(e)}`}generateAlterEnum(e,t){let i={...t,currentSchema:this.schemaAtOperation(t)},{enumName:a,addValues:o=[],removeValues:s,newValues:c,dependentColumns:l}=e,u=[],d=this.qualify(a),f=i.currentSchema?.enums?.find(e=>e.name===a)?.values??[],p=c!==void 0&&f.filter(e=>c.includes(e)).join(`\0`)!==c.filter(e=>f.includes(e)).join(`\0`),m=readsAddedValue(a,o,i.currentSchema?.tables??[],t.followingOperations??[]);if(!(s?.length||p||m)){let e=new Set(f);for(let t of o){let n=c?.slice(c.indexOf(t)+1).find(t=>e.has(t));u.push(`ALTER TYPE ${d} ADD VALUE ${this.escapeValue(t)}${n===void 0?``:` BEFORE ${this.escapeValue(n)}`}`),e.add(t)}return u}if(!c?.length)throw new r(`Cannot alter enum "${a}" without its full destination values`,n.MIGRATION_INVALID_STATE);for(let{tableName:e,columnName:t}of l??[]){let n=i.currentSchema?.tables.find(t=>t.name===e)?.columns.find(e=>e.name===t),r=`${this.qualify(e)} ALTER COLUMN ${this.escapeIdentifier(t)}`;n?.default!==void 0&&u.push(`ALTER TABLE ${r} DROP DEFAULT`);let a=n?.type.endsWith(`[]`)?`text[]`:`text`;u.push(`ALTER TABLE ${r} TYPE ${a} USING ${this.escapeIdentifier(t)}::${a}`)}u.push(...this.buildEnumReplacementUpdates(e,i)),u.push(`DROP TYPE ${d}`),u.push(`CREATE TYPE ${d} AS ENUM (${c.map(e=>this.escapeValue(e)).join(`, `)})`);for(let{tableName:e,columnName:t}of l??[]){let n=i.currentSchema?.tables.find(t=>t.name===e)?.columns.find(e=>e.name===t),r=`${this.qualify(e)} ALTER COLUMN ${this.escapeIdentifier(t)}`,o=n?.type.endsWith(`[]`)?`${d}[]`:d;u.push(`ALTER TABLE ${r} TYPE ${o} USING ${this.escapeIdentifier(t)}::${o}`),n?.default!==void 0&&!enumDefaultLabels(n,a).some(e=>e!==null&&s?.includes(e))&&u.push(`ALTER TABLE ${r} SET DEFAULT ${n.default}`)}return u}enumColumnReplacementUpdates(e,t,n,r){if(!(r.currentSchema?.tables.find(e=>e.name===t)?.columns.find(e=>e.name===n)?.type)?.endsWith(`[]`))return super.enumColumnReplacementUpdates(e,t,n,r);let i=this.enumReplacementCases(e,t,n);if(i.length===0)return[];let a=this.escapeIdentifier(n);return[`UPDATE ${this.qualify(t)} SET ${a} = ARRAY(SELECT CASE value ${i.join(` `)} ELSE value END FROM unnest(${a}) WITH ORDINALITY AS member(value, position) ORDER BY position) WHERE ${a} IS NOT NULL`]}};export{ye as t};
415
- //# sourceMappingURL=postgres-BqAxDWTQ.mjs.map
415
+ //# sourceMappingURL=postgres-Be0jMJWI.mjs.map