viborm 1.4.1 → 1.4.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 (60) hide show
  1. package/dist/adapters.d.mts +1 -1
  2. package/dist/adapters.mjs +1 -1
  3. package/dist/bun-sql.d.mts +1 -1
  4. package/dist/bun-sql.mjs +1 -1
  5. package/dist/bun-sqlite.d.mts +1 -1
  6. package/dist/bun-sqlite.mjs +1 -1
  7. package/dist/cache/cloudflare-kv.d.mts +1 -1
  8. package/dist/cache/memory.d.mts +1 -1
  9. package/dist/cache.d.mts +1 -1
  10. package/dist/cli.mjs +1 -1
  11. package/dist/{client-3FqgR4eS.d.mts → client-D-XiaClb.d.mts} +1 -1
  12. package/dist/{client-DUulrWw5.mjs → client-DACEO6tS.mjs} +2 -2
  13. package/dist/client-DACEO6tS.mjs.map +1 -0
  14. package/dist/client.d.mts +1 -1
  15. package/dist/config.d.mts +1 -1
  16. package/dist/d1.d.mts +1 -1
  17. package/dist/d1.mjs +1 -1
  18. package/dist/d1.mjs.map +1 -1
  19. package/dist/driver.d.mts +1 -1
  20. package/dist/{index-oVv9RLt5.d.mts → index-Ci8b13Lm.d.mts} +18 -1
  21. package/dist/index.d.mts +1 -1
  22. package/dist/index.mjs +1 -1
  23. package/dist/instrumentation.d.mts +1 -1
  24. package/dist/instrumentation.mjs +1 -1
  25. package/dist/libsql.d.mts +1 -1
  26. package/dist/libsql.mjs +1 -1
  27. package/dist/migrations/mysql.d.mts +4 -4
  28. package/dist/migrations/postgres.d.mts +4 -4
  29. package/dist/migrations/sqlite.d.mts +4 -4
  30. package/dist/migrations/tenant.d.mts +2 -2
  31. package/dist/migrations.d.mts +4 -4
  32. package/dist/mysql2.d.mts +1 -1
  33. package/dist/mysql2.mjs +1 -1
  34. package/dist/neon-http.d.mts +1 -1
  35. package/dist/neon-http.mjs +1 -1
  36. package/dist/{object-store-C56-FLkl.d.mts → object-store-H7fJwgPR.d.mts} +3 -3
  37. package/dist/permissions.d.mts +1 -1
  38. package/dist/pg.d.mts +1 -1
  39. package/dist/pg.mjs +1 -1
  40. package/dist/pglite.d.mts +1 -1
  41. package/dist/pglite.mjs +1 -1
  42. package/dist/planetscale.d.mts +1 -1
  43. package/dist/planetscale.mjs +1 -1
  44. package/dist/{planner-C3KX6S85.d.mts → planner-CUcPdJwD.d.mts} +1 -1
  45. package/dist/postgres.d.mts +1 -1
  46. package/dist/postgres.mjs +1 -1
  47. package/dist/schema/json.d.mts +1 -1
  48. package/dist/schema.d.mts +1 -1
  49. package/dist/soft-delete.d.mts +1 -1
  50. package/dist/{sqlite-adapter-B3dRr5fl.mjs → sqlite-adapter-CLWY4B8w.mjs} +2 -2
  51. package/dist/sqlite-adapter-CLWY4B8w.mjs.map +1 -0
  52. package/dist/sqlite3.d.mts +1 -1
  53. package/dist/sqlite3.mjs +1 -1
  54. package/dist/validation.d.mts +1 -1
  55. package/dist/version-DLtcW9kn.mjs +2 -0
  56. package/dist/{version-B9azgPiR.mjs.map → version-DLtcW9kn.mjs.map} +1 -1
  57. package/package.json +1 -1
  58. package/dist/client-DUulrWw5.mjs.map +0 -1
  59. package/dist/sqlite-adapter-B3dRr5fl.mjs.map +0 -1
  60. package/dist/version-B9azgPiR.mjs +0 -2
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./normalized-result-BF7gr4_b.mjs";import{m as n}from"./error-mapping-6op318w6.mjs";import{p as r,r as i}from"./validation-gwZYm3Yn.mjs";import{n as a}from"./client-DUulrWw5.mjs";import{c as o,d as s,t as c}from"./driver-DseQwbsu.mjs";import{t as l}from"./postgres-result-BCUQf8b_.mjs";import{t as u}from"./postgres-adapter-B7hzWhky.mjs";const d={databaseUrl:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,namespace:!0};function malformedNeonResult(e,t){let n=e.operation??`execute`;return new r(`Driver "neon-http" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`neon-http`,...e,operation:n}})}function assertNeonFullResult(e,n){if(!(t(e)&&Array.isArray(e.fields))||typeof e.command!=`string`||!Object.hasOwn(e,`rowCount`)||e.rowCount!==null&&(typeof e.rowCount!=`number`||!Number.isFinite(e.rowCount)||!Number.isSafeInteger(e.rowCount)||e.rowCount<0)||!Array.isArray(e.rows)||!e.rows.every(t)||e.rowAsArray!==!1)throw malformedNeonResult(n,`expected fullResults object with object rows and explicit rowCount`)}var NeonHTTPDriver=class extends c{maxBindParametersPerStatement=65535;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;queryTypes;constructor(e={}){super(`postgresql`,`neon-http`);let t=s(e);this.driverOptions=e,u(this,t,e)}async initClient(){let{neon:e,types:t}=await import(`@neondatabase/serverless`);if(!this.driverOptions.databaseUrl)throw new i(`Neon HTTP driver requires a databaseUrl`,{meta:{driver:this.driverName}});let identityParser=e=>e,getTypeParser=((e,n)=>[1082,1114,1184,1115,1182,1185].includes(e)&&n!==`binary`?identityParser:t.getTypeParser(e,n));return this.queryTypes={getTypeParser},e(this.driverOptions.databaseUrl,{fetchOptions:this.driverOptions.options?.fetchOptions,authToken:this.driverOptions.options?.authToken,fullResults:!0,arrayMode:!1})}async closeClient(e){}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeQuery(e,t,n,r,i){let a=r??{operation:i},o=await e.query(t,n,{arrayMode:!1,fullResults:!0,types:this.queryTypes});return this.parseResult(o,a)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n??[],r,`executeRaw`)}transactionOptionSupport(){return{isolationLevel:`provider`,timeout:!1,timeoutReason:`Neon HTTP runs a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`Neon HTTP submits the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(n(this.driverName))}async executeBatch(e,t,n,r,i){let a=n??{operation:`executeBatch`},o=await e.transaction(t.map(t=>{let n=t.context??a;try{return e.query(t.sql,t.params??[],{types:this.queryTypes})}catch(e){throw this.normalizeStatementFailure(e,t.sql,this.getBatchDiagnosticParameters(t),n,!0)}}),{isolationLevel:i?.isolationLevel,arrayMode:!1,fullResults:!0});if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedNeonResult(a,`expected ${t.length} statement results but received ${e}`)}return o.map((e,n)=>this.parseResult(e,t[n]?.context??a))}parseResult(e,t){let n=t.operation??`execute`;return assertNeonFullResult(e,t),{rows:e.rows,rowCount:l(e.rowCount,e.command,e.rows,{provider:`neon-http`,operation:n,model:t.model,correlationId:t.correlationId})}}};function createClient(e){o(e,`neon-http`,d);let{databaseUrl:t,options:n,pgvector:r,postgis:i}=e,c=s(e);return a(e,new NeonHTTPDriver({databaseUrl:t,options:n,pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:c}))}export{NeonHTTPDriver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./normalized-result-BF7gr4_b.mjs";import{m as n}from"./error-mapping-6op318w6.mjs";import{p as r,r as i}from"./validation-gwZYm3Yn.mjs";import{n as a}from"./client-DACEO6tS.mjs";import{c as o,d as s,t as c}from"./driver-DseQwbsu.mjs";import{t as l}from"./postgres-result-BCUQf8b_.mjs";import{t as u}from"./postgres-adapter-B7hzWhky.mjs";const d={databaseUrl:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,namespace:!0};function malformedNeonResult(e,t){let n=e.operation??`execute`;return new r(`Driver "neon-http" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`neon-http`,...e,operation:n}})}function assertNeonFullResult(e,n){if(!(t(e)&&Array.isArray(e.fields))||typeof e.command!=`string`||!Object.hasOwn(e,`rowCount`)||e.rowCount!==null&&(typeof e.rowCount!=`number`||!Number.isFinite(e.rowCount)||!Number.isSafeInteger(e.rowCount)||e.rowCount<0)||!Array.isArray(e.rows)||!e.rows.every(t)||e.rowAsArray!==!1)throw malformedNeonResult(n,`expected fullResults object with object rows and explicit rowCount`)}var NeonHTTPDriver=class extends c{maxBindParametersPerStatement=65535;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;queryTypes;constructor(e={}){super(`postgresql`,`neon-http`);let t=s(e);this.driverOptions=e,u(this,t,e)}async initClient(){let{neon:e,types:t}=await import(`@neondatabase/serverless`);if(!this.driverOptions.databaseUrl)throw new i(`Neon HTTP driver requires a databaseUrl`,{meta:{driver:this.driverName}});let identityParser=e=>e,getTypeParser=((e,n)=>[1082,1114,1184,1115,1182,1185].includes(e)&&n!==`binary`?identityParser:t.getTypeParser(e,n));return this.queryTypes={getTypeParser},e(this.driverOptions.databaseUrl,{fetchOptions:this.driverOptions.options?.fetchOptions,authToken:this.driverOptions.options?.authToken,fullResults:!0,arrayMode:!1})}async closeClient(e){}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeQuery(e,t,n,r,i){let a=r??{operation:i},o=await e.query(t,n,{arrayMode:!1,fullResults:!0,types:this.queryTypes});return this.parseResult(o,a)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n??[],r,`executeRaw`)}transactionOptionSupport(){return{isolationLevel:`provider`,timeout:!1,timeoutReason:`Neon HTTP runs a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`Neon HTTP submits the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(n(this.driverName))}async executeBatch(e,t,n,r,i){let a=n??{operation:`executeBatch`},o=await e.transaction(t.map(t=>{let n=t.context??a;try{return e.query(t.sql,t.params??[],{types:this.queryTypes})}catch(e){throw this.normalizeStatementFailure(e,t.sql,this.getBatchDiagnosticParameters(t),n,!0)}}),{isolationLevel:i?.isolationLevel,arrayMode:!1,fullResults:!0});if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedNeonResult(a,`expected ${t.length} statement results but received ${e}`)}return o.map((e,n)=>this.parseResult(e,t[n]?.context??a))}parseResult(e,t){let n=t.operation??`execute`;return assertNeonFullResult(e,t),{rows:e.rows,rowCount:l(e.rowCount,e.command,e.rows,{provider:`neon-http`,operation:n,model:t.model,correlationId:t.correlationId})}}};function createClient(e){o(e,`neon-http`,d);let{databaseUrl:t,options:n,pgvector:r,postgis:i}=e,c=s(e);return a(e,new NeonHTTPDriver({databaseUrl:t,options:n,pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:c}))}export{NeonHTTPDriver,createClient};
2
2
  //# sourceMappingURL=neon-http.mjs.map
@@ -1,7 +1,7 @@
1
- import { Mn as Dialect, Un as AnyModel } from "./index-oVv9RLt5.mjs";
2
- import { i as ResolveCallback, t as MigrationClient } from "./planner-C3KX6S85.mjs";
1
+ import { Mn as Dialect, Un as AnyModel } from "./index-Ci8b13Lm.mjs";
2
+ import { i as ResolveCallback, t as MigrationClient } from "./planner-CUcPdJwD.mjs";
3
3
  import { i as Sha256, n as MigrationStorageWriter, r as PublishResult } from "./contract-Dw0FR78e.mjs";
4
- import { B as MigrationCheckInput, V as MigrationDecisionV1 } from "./client-3FqgR4eS.mjs";
4
+ import { B as MigrationCheckInput, V as MigrationDecisionV1 } from "./client-D-XiaClb.mjs";
5
5
 
6
6
  //#region src/adapters/databases/sqlite/storage/datetime.d.ts
7
7
 
@@ -1,4 +1,4 @@
1
- import { E as OperationPayload, Ft as VibORMClient, It as VibORMConfig, M as ClientSchema, Nt as ExtensionState, Ut as RowsVerbs, W as InferOutput, en as MergeExtensionState, jt as ExtendedClient, kt as ClientTypeState } from "./index-oVv9RLt5.mjs";
1
+ import { E as OperationPayload, Ft as VibORMClient, It as VibORMConfig, M as ClientSchema, Nt as ExtensionState, Ut as RowsVerbs, W as InferOutput, en as MergeExtensionState, jt as ExtendedClient, kt as ClientTypeState } from "./index-Ci8b13Lm.mjs";
2
2
  import "./client.mjs";
3
3
  import { StandardSchemaV1 } from "@standard-schema/spec";
4
4
 
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-oVv9RLt5.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-Ci8b13Lm.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-6op318w6.mjs";import{r as a}from"./validation-gwZYm3Yn.mjs";import{n as o}from"./transaction-4dfqals6.mjs";import{n as s}from"./suppressed-failure-Bdo2aK81.mjs";import{c}from"./execution-context-asSCmyas.mjs";import{n as l}from"./client-DUulrWw5.mjs";import{c as u,d,f,i as p,o as m,s as h,t as g,u as _}from"./driver-DseQwbsu.mjs";import{t as v}from"./postgres-result-BCUQf8b_.mjs";import{t as y}from"./postgres-adapter-B7hzWhky.mjs";import{n as b,t as x}from"./relation-bound-BrZLsSke.mjs";import{Client as S,Pool as C,types as w}from"pg";const identityParser=e=>e,T={getTypeParser:(e,t)=>[1082,1114,1184,1115,1182,1185].includes(e)&&t!==`binary`?identityParser:w.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 E=new Set([`user`,`password`,`host`,`port`]),D=[`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&&(E.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 D)i.searchParams.delete(e);else e===`database`?i.pathname=`/${String(t)}`:E.has(e)&&(typeof t==`string`||typeof t==`number`)&&i.searchParams.set(e,String(t));return{...e,connectionString:i.href}}const O={pool:!0,options:!0,pgvector:!0,postgis:!0,databaseUrl:!0,namespace:!0,sharedRelationBodies:!0,relationsPerStatement:!0,migrationSessionAttestation:!0};var PgDriver=class extends g{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;ownedPoolErrors=new WeakMap;serverVersion;readsServer;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),this.readsServer=this.suppliedPool===void 0&&n.Client===void 0&&x(this.adapter,()=>this.serverVersion),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 C({types:T,...this.connectionOptions,...this.readsServer?{Client:this.readingClient()}:{}}),t=createOwnedPoolErrorState();return this.ownedPoolErrors.set(e,t),e.on(`error`,t.retain),Promise.resolve(e)}readingClient(){let read=e=>{this.serverVersion=e};return class extends S{constructor(e){super(e),this.connection.on(`parameterStatus`,e=>{e.parameterName===`server_version`&&read(e.parameterValue)})}}}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:T}).catch(i=>(b(this.adapter,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`,O);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,relationsPerStatement:e.relationsPerStatement}))}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-6op318w6.mjs";import{r as a}from"./validation-gwZYm3Yn.mjs";import{n as o}from"./transaction-4dfqals6.mjs";import{n as s}from"./suppressed-failure-Bdo2aK81.mjs";import{c}from"./execution-context-asSCmyas.mjs";import{n as l}from"./client-DACEO6tS.mjs";import{c as u,d,f,i as p,o as m,s as h,t as g,u as _}from"./driver-DseQwbsu.mjs";import{t as v}from"./postgres-result-BCUQf8b_.mjs";import{t as y}from"./postgres-adapter-B7hzWhky.mjs";import{n as b,t as x}from"./relation-bound-BrZLsSke.mjs";import{Client as S,Pool as C,types as w}from"pg";const identityParser=e=>e,T={getTypeParser:(e,t)=>[1082,1114,1184,1115,1182,1185].includes(e)&&t!==`binary`?identityParser:w.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 E=new Set([`user`,`password`,`host`,`port`]),D=[`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&&(E.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 D)i.searchParams.delete(e);else e===`database`?i.pathname=`/${String(t)}`:E.has(e)&&(typeof t==`string`||typeof t==`number`)&&i.searchParams.set(e,String(t));return{...e,connectionString:i.href}}const O={pool:!0,options:!0,pgvector:!0,postgis:!0,databaseUrl:!0,namespace:!0,sharedRelationBodies:!0,relationsPerStatement:!0,migrationSessionAttestation:!0};var PgDriver=class extends g{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;ownedPoolErrors=new WeakMap;serverVersion;readsServer;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),this.readsServer=this.suppliedPool===void 0&&n.Client===void 0&&x(this.adapter,()=>this.serverVersion),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 C({types:T,...this.connectionOptions,...this.readsServer?{Client:this.readingClient()}:{}}),t=createOwnedPoolErrorState();return this.ownedPoolErrors.set(e,t),e.on(`error`,t.retain),Promise.resolve(e)}readingClient(){let read=e=>{this.serverVersion=e};return class extends S{constructor(e){super(e),this.connection.on(`parameterStatus`,e=>{e.parameterName===`server_version`&&read(e.parameterValue)})}}}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:T}).catch(i=>(b(this.adapter,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`,O);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,relationsPerStatement:e.relationsPerStatement}))}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-oVv9RLt5.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-Ci8b13Lm.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{o as t}from"./normalized-result-BF7gr4_b.mjs";import{d as n,l as r}from"./error-mapping-6op318w6.mjs";import{c as i}from"./execution-context-asSCmyas.mjs";import{n as a}from"./client-DUulrWw5.mjs";import{a as o,n as s}from"./pinned-session-FYOFV_gB.mjs";import{c,d as l,r as u,t as d}from"./driver-DseQwbsu.mjs";import{t as f}from"./postgres-adapter-B7hzWhky.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,relationsPerStatement:!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,relationsPerStatement:e.relationsPerStatement,namespace:s}))}export{PGliteDriver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./normalized-result-BF7gr4_b.mjs";import{d as n,l as r}from"./error-mapping-6op318w6.mjs";import{c as i}from"./execution-context-asSCmyas.mjs";import{n as a}from"./client-DACEO6tS.mjs";import{a as o,n as s}from"./pinned-session-FYOFV_gB.mjs";import{c,d as l,r as u,t as d}from"./driver-DseQwbsu.mjs";import{t as f}from"./postgres-adapter-B7hzWhky.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,relationsPerStatement:!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,relationsPerStatement:e.relationsPerStatement,namespace:s}))}export{PGliteDriver,createClient};
2
2
  //# sourceMappingURL=pglite.mjs.map
@@ -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-oVv9RLt5.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-Ci8b13Lm.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{a as n,o as r}from"./normalized-result-BF7gr4_b.mjs";import{l as i,p as a}from"./error-mapping-6op318w6.mjs";import{p as o}from"./validation-gwZYm3Yn.mjs";import{c as s}from"./execution-context-asSCmyas.mjs";import{n as c}from"./client-DUulrWw5.mjs";import{a as l,c as u,d,o as f,t as p}from"./driver-DseQwbsu.mjs";import{t as m}from"./sql-statement-tokens-4J5l5Lyt.mjs";import{t as h}from"./mysql-adapter-B1U35CJn.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=n(e.insertId,i);return{rows:e.rows,rowCount:r(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{a as n,o as r}from"./normalized-result-BF7gr4_b.mjs";import{l as i,p as a}from"./error-mapping-6op318w6.mjs";import{p as o}from"./validation-gwZYm3Yn.mjs";import{c as s}from"./execution-context-asSCmyas.mjs";import{n as c}from"./client-DACEO6tS.mjs";import{a as l,c as u,d,o as f,t as p}from"./driver-DseQwbsu.mjs";import{t as m}from"./sql-statement-tokens-4J5l5Lyt.mjs";import{t as h}from"./mysql-adapter-B1U35CJn.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=n(e.insertId,i);return{rows:e.rows,rowCount:r(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-oVv9RLt5.mjs";
1
+ import { Ki as DecimalDescriptor, Un as AnyModel, l as AnyDriver, mn as DateTimePhysicalForm } from "./index-Ci8b13Lm.mjs";
2
2
 
3
3
  //#region src/migrations/limits.d.ts
4
4
 
@@ -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-oVv9RLt5.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-Ci8b13Lm.mjs";
2
2
  import postgres, { Options, Sql } from "postgres";
3
3
 
4
4
  //#region src/drivers/postgres/index.d.ts
package/dist/postgres.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-D3m1S7Uc.mjs";import{d as n,l as r,r as i}from"./error-mapping-6op318w6.mjs";import{r as a}from"./validation-gwZYm3Yn.mjs";import{n as o}from"./suppressed-failure-Bdo2aK81.mjs";import{c as s}from"./execution-context-asSCmyas.mjs";import{n as c}from"./client-DUulrWw5.mjs";import{i as l,t as u}from"./pinned-session-FYOFV_gB.mjs";import{c as d,d as f,f as p,i as m,o as h,s as g,t as _,u as v}from"./driver-DseQwbsu.mjs";import{t as y}from"./postgres-result-BCUQf8b_.mjs";import{t as b}from"./postgres-adapter-B7hzWhky.mjs";import{n as x,t as S}from"./relation-bound-BrZLsSke.mjs";import C from"postgres";const w={timestamp:{to:1114,from:[1082,1114,1184],serialize:e=>e instanceof Date?e.toISOString():String(e),parse:e=>e},json:{to:114,from:[114,3802],serialize:e=>typeof e==`string`?e:JSON.stringify(e),parse:e=>JSON.parse(e)}};function encodeListParameters(e){return e.map(e=>Array.isArray(e)?`{${e.map(e=>e===null?`NULL`:`"${String(e).replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`).join(`,`)}}`:e)}const withVibormTypes=(e={})=>({...e,types:{...w,...e.types}}),T={client:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,databaseUrl:!0,namespace:!0,migrationSessionAttestation:!0},isTransaction=e=>`savepoint`in e;var PostgresDriver=class extends _{maxBindParametersPerStatement=65533;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`postgres`);let t=f(e);this.driverOptions={databaseUrl:e.databaseUrl,options:{...e.options}},this.suppliedClient=e.client;let{host:n,hostname:r}=this.driverOptions.options??{};if(g(`postgres`,e,!!(this.suppliedClient||n||r)),this.suppliedClient){for(let e of[1082,1114,1184])if(this.suppliedClient.options?.parsers[e]!==w.timestamp?.parse)throw new a(`A supplied postgres.js client must use VibORM temporal parsers; construct postgres(url, { types: vibormTypes }).`,{meta:{driver:`postgres`,operation:`configuration`}});this.client=this.suppliedClient}b(this,t,e),S(this.adapter,()=>{let e=this.client;return e&&!isTransaction(e)?e.parameters.server_version:void 0}),h(this,`migrationSessionAttestation`,v(e))}migrationSessionEndpoints(){let{databaseUrl:e,options:t}=this.driverOptions;return[e,t?.host,t?.hostname,...this.suppliedClient?.options.host??[]]}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let{databaseUrl:e,options:t}=this.driverOptions;return e?C(p(e),withVibormTypes(t)):C(withVibormTypes(t))}async closeClient(e){e!==this.suppliedClient&&await e.end()}async execute(e,t,n,r){return this.executeQuery(e,t,encodeListParameters(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=await e.unsafe(t,n,{prepare:this.driverOptions.options?.prepare===!0}).catch(e=>{throw x(this.adapter,e),e});return{rows:o,rowCount:y(o.count,o.command,o,{provider:`postgres`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`postgres.js acquires the connection inside client.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said`}}async transaction(e,t,i,a){if(isTransaction(e))throw r(this.driverName);return n({run:async t=>{let n=!1;try{return await e.begin(e=>(n=!0,t(e)))}catch(t){throw!n&&this.isConnectionFailure(t)&&await this.recoverFailedBegin(e,t,a?.maxWaitMs??5e3),t}},callback:t,phases:s(i),close:async()=>void 0})}isConnectionFailure(e){let n=i(e,{driverName:this.driverName,dialect:this.dialect});return n.code===t.CONNECTION_FAILED||n.code===t.CONNECTION_TIMEOUT}async recoverFailedBegin(e,t,n){let r=Date.now()+n;for(let n=0;n<2;n++){let n=r-Date.now();if(n<=0)break;try{(await m(()=>e.reserve(),e=>e.release(),n,{driverName:this.driverName,form:`callback`})).release();return}catch(e){if(o(t,e),!this.isConnectionFailure(e))break}}}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(isTransaction(e))throw r(this.driverName);let t=await e.reserve();return{session:t,release:(n,r)=>l({driverName:this.driverName,discard:n,lost:r,reset:()=>t.unsafe(`SELECT pg_advisory_unlock_all()`),release:()=>t.release(),closeOwnedTransport:e===this.suppliedClient?void 0:async()=>{this.client=null,this.initPromise=null,await e.end({timeout:u/1e3})}})}}};function createClient(e){d(e,`postgres`,T);let{client:t,options:n={},pgvector:r,postgis:i,databaseUrl:a}=e,o=f(e),s=v(e);return c(e,new PostgresDriver({client:t,options:n,...Object.hasOwn(e,`databaseUrl`)?{databaseUrl:a}:{},pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:o,migrationSessionAttestation:s}))}export{PostgresDriver,createClient,w as vibormTypes};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-D3m1S7Uc.mjs";import{d as n,l as r,r as i}from"./error-mapping-6op318w6.mjs";import{r as a}from"./validation-gwZYm3Yn.mjs";import{n as o}from"./suppressed-failure-Bdo2aK81.mjs";import{c as s}from"./execution-context-asSCmyas.mjs";import{n as c}from"./client-DACEO6tS.mjs";import{i as l,t as u}from"./pinned-session-FYOFV_gB.mjs";import{c as d,d as f,f as p,i as m,o as h,s as g,t as _,u as v}from"./driver-DseQwbsu.mjs";import{t as y}from"./postgres-result-BCUQf8b_.mjs";import{t as b}from"./postgres-adapter-B7hzWhky.mjs";import{n as x,t as S}from"./relation-bound-BrZLsSke.mjs";import C from"postgres";const w={timestamp:{to:1114,from:[1082,1114,1184],serialize:e=>e instanceof Date?e.toISOString():String(e),parse:e=>e},json:{to:114,from:[114,3802],serialize:e=>typeof e==`string`?e:JSON.stringify(e),parse:e=>JSON.parse(e)}};function encodeListParameters(e){return e.map(e=>Array.isArray(e)?`{${e.map(e=>e===null?`NULL`:`"${String(e).replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`).join(`,`)}}`:e)}const withVibormTypes=(e={})=>({...e,types:{...w,...e.types}}),T={client:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,databaseUrl:!0,namespace:!0,migrationSessionAttestation:!0},isTransaction=e=>`savepoint`in e;var PostgresDriver=class extends _{maxBindParametersPerStatement=65533;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`postgres`);let t=f(e);this.driverOptions={databaseUrl:e.databaseUrl,options:{...e.options}},this.suppliedClient=e.client;let{host:n,hostname:r}=this.driverOptions.options??{};if(g(`postgres`,e,!!(this.suppliedClient||n||r)),this.suppliedClient){for(let e of[1082,1114,1184])if(this.suppliedClient.options?.parsers[e]!==w.timestamp?.parse)throw new a(`A supplied postgres.js client must use VibORM temporal parsers; construct postgres(url, { types: vibormTypes }).`,{meta:{driver:`postgres`,operation:`configuration`}});this.client=this.suppliedClient}b(this,t,e),S(this.adapter,()=>{let e=this.client;return e&&!isTransaction(e)?e.parameters.server_version:void 0}),h(this,`migrationSessionAttestation`,v(e))}migrationSessionEndpoints(){let{databaseUrl:e,options:t}=this.driverOptions;return[e,t?.host,t?.hostname,...this.suppliedClient?.options.host??[]]}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let{databaseUrl:e,options:t}=this.driverOptions;return e?C(p(e),withVibormTypes(t)):C(withVibormTypes(t))}async closeClient(e){e!==this.suppliedClient&&await e.end()}async execute(e,t,n,r){return this.executeQuery(e,t,encodeListParameters(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=await e.unsafe(t,n,{prepare:this.driverOptions.options?.prepare===!0}).catch(e=>{throw x(this.adapter,e),e});return{rows:o,rowCount:y(o.count,o.command,o,{provider:`postgres`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`postgres.js acquires the connection inside client.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said`}}async transaction(e,t,i,a){if(isTransaction(e))throw r(this.driverName);return n({run:async t=>{let n=!1;try{return await e.begin(e=>(n=!0,t(e)))}catch(t){throw!n&&this.isConnectionFailure(t)&&await this.recoverFailedBegin(e,t,a?.maxWaitMs??5e3),t}},callback:t,phases:s(i),close:async()=>void 0})}isConnectionFailure(e){let n=i(e,{driverName:this.driverName,dialect:this.dialect});return n.code===t.CONNECTION_FAILED||n.code===t.CONNECTION_TIMEOUT}async recoverFailedBegin(e,t,n){let r=Date.now()+n;for(let n=0;n<2;n++){let n=r-Date.now();if(n<=0)break;try{(await m(()=>e.reserve(),e=>e.release(),n,{driverName:this.driverName,form:`callback`})).release();return}catch(e){if(o(t,e),!this.isConnectionFailure(e))break}}}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(isTransaction(e))throw r(this.driverName);let t=await e.reserve();return{session:t,release:(n,r)=>l({driverName:this.driverName,discard:n,lost:r,reset:()=>t.unsafe(`SELECT pg_advisory_unlock_all()`),release:()=>t.release(),closeOwnedTransport:e===this.suppliedClient?void 0:async()=>{this.client=null,this.initPromise=null,await e.end({timeout:u/1e3})}})}}};function createClient(e){d(e,`postgres`,T);let{client:t,options:n={},pgvector:r,postgis:i,databaseUrl:a}=e,o=f(e),s=v(e);return c(e,new PostgresDriver({client:t,options:n,...Object.hasOwn(e,`databaseUrl`)?{databaseUrl:a}:{},pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:o,migrationSessionAttestation:s}))}export{PostgresDriver,createClient,w as vibormTypes};
2
2
  //# sourceMappingURL=postgres.mjs.map
@@ -1,4 +1,4 @@
1
- import { Ft as VibORMClient, It as VibORMConfig, Jr as JunctionReferentialAction, Kn as IndexType, Xi as NativeTypeMap, Yi as NativeType, Yr as ReferentialAction, er as AutoGenerateType, hn as Schema, ir as ScalarType, yr as JsonValue } from "../index-oVv9RLt5.mjs";
1
+ import { Ft as VibORMClient, It as VibORMConfig, Jr as JunctionReferentialAction, Kn as IndexType, Xi as NativeTypeMap, Yi as NativeType, Yr as ReferentialAction, er as AutoGenerateType, hn as Schema, ir as ScalarType, yr as JsonValue } from "../index-Ci8b13Lm.mjs";
2
2
  import { StandardSchemaV1 } from "@standard-schema/spec";
3
3
 
4
4
  //#region src/schema/json/document.d.ts
package/dist/schema.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { $n as AutoGenerate, B as VariantToOneRelation, Cr as IsoDateSchema, Ct as s, Dr as EnumSchema, H as BigIntScalar, Ji as MYSQL, Jn as Model, Ki as DecimalDescriptor, Kr as AnyRelation, Ln as StringSchema, Nr as BigIntSchema, Qi as SQLITE, Qn as DecimalSchema, R as ModelShape, St as ModelToManyRelation, Tr as IsoTimestampSchema, Un as AnyModel, V as Scalar, Wi as GeoPoint, Xi as NativeTypeMap, Xn as ModelState, Xr as RelationCardinality, Yi as NativeType, Yn as ModelInternal, Yr as ReferentialAction, Zi as PG, Zn as UpdateState, Zr as RelationSlot, _t as DateScalar, ar as UpdateState$1, bt as ModelToOneRelation, cr as VectorSchema, ct as StringScalar, dt as JsonScalar, ft as IntScalar, gt as DateTimeScalar, hr as NumberSchema, ht as TimeScalar, jr as BlobSchema, kr as BooleanSchema, lt as PointScalar, mr as IntegerSchema, mt as DecimalScalar, nr as InitialScalarState, ot as NumericScalar, pt as EnumScalar, qn as InitialModelState, qr as Getter, rr as ScalarState, st as VectorScalar, tr as GeneratorDefaultBrand, ur as PointSchema, ut as NumberScalar, vr as JsonSchema, vt as BooleanScalar, wr as IsoTimeSchema, xt as ReferencesStage, yt as BlobScalar, z as VariantToManyRelation } from "./index-oVv9RLt5.mjs";
1
+ import { $n as AutoGenerate, B as VariantToOneRelation, Cr as IsoDateSchema, Ct as s, Dr as EnumSchema, H as BigIntScalar, Ji as MYSQL, Jn as Model, Ki as DecimalDescriptor, Kr as AnyRelation, Ln as StringSchema, Nr as BigIntSchema, Qi as SQLITE, Qn as DecimalSchema, R as ModelShape, St as ModelToManyRelation, Tr as IsoTimestampSchema, Un as AnyModel, V as Scalar, Wi as GeoPoint, Xi as NativeTypeMap, Xn as ModelState, Xr as RelationCardinality, Yi as NativeType, Yn as ModelInternal, Yr as ReferentialAction, Zi as PG, Zn as UpdateState, Zr as RelationSlot, _t as DateScalar, ar as UpdateState$1, bt as ModelToOneRelation, cr as VectorSchema, ct as StringScalar, dt as JsonScalar, ft as IntScalar, gt as DateTimeScalar, hr as NumberSchema, ht as TimeScalar, jr as BlobSchema, kr as BooleanSchema, lt as PointScalar, mr as IntegerSchema, mt as DecimalScalar, nr as InitialScalarState, ot as NumericScalar, pt as EnumScalar, qn as InitialModelState, qr as Getter, rr as ScalarState, st as VectorScalar, tr as GeneratorDefaultBrand, ur as PointSchema, ut as NumberScalar, vr as JsonSchema, vt as BooleanScalar, wr as IsoTimeSchema, xt as ReferencesStage, yt as BlobScalar, z as VariantToManyRelation } from "./index-Ci8b13Lm.mjs";
2
2
  export { type AnyModel, type AnyRelation, type AutoGenerate, type BigIntScalar, type BigIntSchema, type BlobScalar, type BlobSchema, type BooleanScalar, type BooleanSchema, type DateScalar, type DateTimeScalar, type DecimalDescriptor, type DecimalScalar, type DecimalSchema, type EnumScalar, type EnumSchema, type GeneratorDefaultBrand, type GeoPoint, type Getter, type InitialModelState, type InitialScalarState, type IntScalar, type IntegerSchema, type IsoDateSchema, type IsoTimeSchema, type IsoTimestampSchema, type JsonScalar, type JsonSchema as JsonValueSchema, MYSQL, type Model, type ModelInternal, type ModelShape, type ModelState, type ModelToManyRelation, type ModelToOneRelation, type UpdateState as ModelUpdateState, type NativeType, type NativeTypeMap, type NumberScalar, type NumberSchema, type NumericScalar, PG, type PointScalar, type PointSchema, type ReferencesStage, type ReferentialAction, type RelationCardinality, type RelationSlot, SQLITE, type Scalar, type ScalarState, type UpdateState$1 as ScalarUpdateState, type StringScalar, type StringSchema, type TimeScalar, type VariantToManyRelation, type VariantToOneRelation, type VectorScalar, type VectorSchema, s };
@@ -1,4 +1,4 @@
1
- import { Bt as DefinitionControls, E as OperationPayload, Ft as VibORMClient, It as VibORMConfig, Jt as AccumulatedExtensionState, M as ClientSchema, Mt as ExtendedOperationResult, Nt as ExtensionState, Qt as ExtensionContributionState, Vt as NoControls, gn as PendingOperation, kt as ClientTypeState } from "./index-oVv9RLt5.mjs";
1
+ import { Bt as DefinitionControls, E as OperationPayload, Ft as VibORMClient, It as VibORMConfig, Jt as AccumulatedExtensionState, M as ClientSchema, Mt as ExtendedOperationResult, Nt as ExtensionState, Qt as ExtensionContributionState, Vt as NoControls, gn as PendingOperation, kt as ClientTypeState } from "./index-Ci8b13Lm.mjs";
2
2
  import "./client.mjs";
3
3
 
4
4
  //#region src/soft-delete/index.d.ts
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,m as n}from"./validation-gwZYm3Yn.mjs";import{E as r}from"./geo-point-codec-pAWYj5ZZ.mjs";import{o as i,t as a}from"./sql-BvHwL73I.mjs";import{a as o,t as s}from"./physical-C4D-979R.mjs";import{t as c}from"./adapter-result-parser-D6lluSMi.mjs";import{r as l}from"./adapter-internals-Cy2QEBnH.mjs";import{i as u}from"./datetime-physical-codec-CFoeuitT.mjs";import{t as ee}from"./json-number-CGXpPu4D.mjs";import{C as d,D as f,E as p,M as m,N as h,O as te,S as ne,T as re,_ as ie,a as ae,b as oe,d as g,f as _,g as v,h as y,i as b,j as x,k as S,l as C,n as w,o as T,p as E,r as D,s as O,v as k,w as A,x as j,y as M}from"./standard-sql-DmKF8msN.mjs";import{r as N,t as P}from"./batch-refs-BYCu1JnQ.mjs";import{f as F,h as I,n as L,o as R,p as z,r as B,t as V,u as H}from"./select-assembly-BjT_fDbu.mjs";const U=h(`"`),W={quotient:(e,t)=>i`(${e} / ${t})`,remainder:(e,t)=>i`(${e} % ${t})`};function sqliteIntegerPrecision(e){let t=te(e);if(t<19)return t;if(!(t>19))return(e.startsWith(`-`)?e.slice(1)<=`9223372036854775808`:e<=`9223372036854775807`)?t:void 0}const G=i.raw(`1000000000000000000`),overflowCoefficient=e=>i.raw(`1${`0`.repeat(Math.min(e.precision,18))}`),guardedCoefficientAssignment=(e,t,n,r)=>i`${e} = CASE WHEN ${e} IS NULL OR ${t} THEN ${n} ELSE ${overflowCoefficient(r)} END`,K=/^\d+$/,q=/["\\]/,jsonPathLeg=e=>{if(K.test(e))return`$[${e}]`;if(q.test(e))throw Error(`SQLite JSON path segments containing " or \\ must be rejected by the portable query contract.`);return`$."${e}"`},jsonExtract=(e,t)=>{let n=i`${e} -> '$'`;for(let e of t)n=i`${n} -> ${jsonPathLeg(e)}`;return n},jsonExtractText=(e,t)=>{if(t.length===0)return i`${e} ->> '$'`;let n=t.map(jsonPathLeg),r=n.pop(),a=e;for(let e of n)a=i`${a} -> ${e}`;return i`${a} ->> ${r}`},jsonArrayConcat=(e,t)=>i`(CASE WHEN ${e} = '[]' THEN ${t} WHEN ${t} = '[]' THEN ${e} ELSE substr(${e}, 1, length(${e}) - 1) || ',' || substr(${t}, 2) END)`,sqliteJsonListValue=e=>i`${m(e)}`,se=[``,``],J=[`CAST(`,` AS INTEGER)`],ce=/\p{Cs}/u,Y=p().list;function jsonMember(e){return typeof e==`string`?ce.test(e)?void 0:JSON.stringify(e):e instanceof Uint8Array?`"${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}"`:typeof e==`bigint`||typeof e==`boolean`||Number.isSafeInteger(e)?String(e):void 0}function sqliteList(e){if(e.length<=25)return Y(e);let[t]=e,n=t?.strings[0]===J[0]?J:se,r=[],o=0;for(let t of e){let[i,a,s]=t.strings,c=t.values[0],l=jsonMember(c);if(l===void 0||i!==n[0]||a!==n[1]||s!==void 0)return Y(e);c instanceof Uint8Array&&o++,r.push(l)}return o!==0&&o!==e.length?Y(e):i`(SELECT ${new a(n,[i.raw(o===0?`value`:`unhex(value)`)])} FROM json_each(${`[${r.join(`,`)}]`}))`}const X={...p(),value:e=>{if(typeof e==`bigint`&&sqliteIntegerPrecision(String(e))===void 0)throw new n(`SQLite bigint values must fit signed 64-bit integers.`);return i`${e}`},true:()=>i.raw(`1`),false:()=>i.raw(`0`),json:e=>i`${JSON.stringify(e)}`,dateTime:(e,t)=>i`${u(e,s(t))}`,decimal:(e,t)=>new a(J,[r(e,t,`coefficient`)]),id:(e,t)=>i`${e}`,list:sqliteList},Z={...ae(),like:(e,t)=>i`${e} LIKE ${t} ESCAPE '\\'`,notLike:(e,t)=>i`${e} NOT LIKE ${t} ESCAPE '\\'`,ilike:(e,t)=>i`lower(${e}) LIKE lower(${t}) ESCAPE '\\'`,notIlike:(e,t)=>i`lower(${e}) NOT LIKE lower(${t}) ESCAPE '\\'`,containsText:(e,t)=>i`instr(${e}, ${t}) > 0`,startsWithText:(e,t)=>i`substr(${e}, 1, length(${t})) COLLATE BINARY = ${t}`,endsWithText:(e,t)=>i`substr(${e}, length(${e}) - length(${t}) + 1) COLLATE BINARY = ${t}`,startsWithPrefix:(e,t)=>i`${e} GLOB ${`${S(t)}*`}`,exactTextEq:(e,t)=>i`${e} COLLATE BINARY = ${t}`,exactTextIn:(e,t)=>i`${e} COLLATE BINARY IN ${t}`,...v(),...k(),...j(),...y(X.true,X.false),...g()},le={...b(),asciiCaseFold:e=>i`lower(${e})`,caseSensitiveText:e=>i`${e} COLLATE BINARY`,concat:(...e)=>e.length===0?i.raw(`''`):e.length===1?e[0]:i`(${i.join(e,` || `)})`,greatest:(...e)=>i`MAX(${i.join(e,`, `)})`,least:(...e)=>i`MIN(${i.join(e,`, `)})`,integerDivide:(e,t)=>i`(${e} / CAST(${t} AS INTEGER))`,decimalCast:(e,t)=>i`CAST(${e} AS INTEGER)`,idCast:(e,t)=>t===`bytes`?i`unhex(${e})`:i`CAST(${e} AS TEXT)`,cast:D({text:`TEXT`,integer:`INTEGER`,bigint:`INTEGER`,boolean:`INTEGER`,numeric:`NUMERIC`}),blobToHex:e=>i`lower(hex(${e}))`},ue={...w(`9e999`),decimalAvg:(e,t)=>R(W,i`SUM(${e})`,i`COUNT(${e})`),decimalSumOperandPrecision:sqliteIntegerPrecision,integerSum:e=>{let t=i`SUM(${e} >> 32)`,n=i`SUM(${e} - ((${e} >> 32) << 32))`,r=i`(${t} + (${n} >> 32))`,a=i`(${n} & 4294967295)`,o=i`${r} * 4294967296.0 + ${a}`;return{parts:[t,n],value:i`CASE WHEN ${r} > 2147483647 THEN ${o} WHEN ${r} >= -2147483648 THEN ${r} * 4294967296 + ${a} ELSE MIN(${o}, -9223372036854777856.0) END`,order:[r,a]}}};function sqliteJsonEquals(e,t){let nodes=e=>i`SELECT fullkey, CASE WHEN type IN ('integer', 'real') THEN 'number' ELSE type END, atom FROM json_tree(${e})`;return i`(CASE WHEN ${e} IS NULL OR ${t} IS NULL THEN NULL ELSE NOT EXISTS (${nodes(e)} EXCEPT ${nodes(t)}) AND NOT EXISTS (${nodes(t)} EXCEPT ${nodes(e)}) END)`}const sqliteJsonObject=e=>{if(e.length===0)return i.raw(`json_object()`);let t=e.flatMap(([e,t])=>[i`${e}`,t]);return i`json_object(${i.join(t,`, `)})`},de={equals:sqliteJsonEquals,number:e=>i`CASE WHEN ${e} IS NULL THEN NULL ELSE printf(${i.raw(`'${ee}'`)}, ${e}) END`,boolean:e=>i`json(CASE WHEN ${e} THEN 'true' ELSE 'false' END)`,document:e=>i`json(${e})`,object:sqliteJsonObject,array:e=>e.length===0?i.raw(`json_array()`):i`json_array(${i.join(e,`, `)})`,emptyArray:()=>i.raw(`json_array()`),agg:e=>i`json_group_array(${e})`,objectFromColumns:sqliteJsonObject,extract:jsonExtract,extractText:jsonExtractText,numberAtPath:(e,t)=>i`(CASE WHEN json_type(${jsonExtract(e,t)}) IN ('integer', 'real') THEN CAST(${jsonExtractText(e,t)} AS REAL) END)`,stringAtPath:(e,t)=>i`((CASE WHEN json_type(${jsonExtract(e,t)}) = 'text' THEN ${jsonExtractText(e,t)} END) COLLATE BINARY)`,contains:(e,t)=>i`(json_type(${e}) = 'array' AND NOT EXISTS (SELECT 1 FROM json_each(${t}) AS required WHERE NOT EXISTS (SELECT 1 FROM json_each(${e}) AS candidate WHERE ${sqliteJsonEquals(i`${e} -> candidate.fullkey`,i`${t} -> required.fullkey`)})))`,lastElement:e=>i`${e} -> '$[#-1]'`,value:e=>i`${m(e)}`},fe={literal:e=>e.length===0?i.raw(`json_array()`):i`json_array(${i.join(e,`, `)})`,value:sqliteJsonListValue,enumValue:sqliteJsonListValue,has:(e,t)=>i`EXISTS (SELECT 1 FROM json_each(${e}) WHERE value = ${t})`,hasEvery:(e,t)=>i`(SELECT COUNT(*) FROM json_each(${t}) WHERE value IN (SELECT value FROM json_each(${e}))) = json_array_length(${t})`,hasSome:(e,t)=>i`EXISTS (SELECT 1 FROM json_each(${e}) AS a, json_each(${t}) AS b WHERE a.value = b.value)`,isEmpty:e=>i`(json_array_length(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>i`CAST(${e} AS TEXT)`,length:e=>i`json_array_length(${e})`,get:(e,t)=>i`json_extract(${e}, '$[' || ${t} || ']')`,push:(e,t)=>i`json_insert(${e}, '$[#]', ${t})`,set:(e,t,n)=>i`json_set(${e}, '$[' || ${t} || ']', ${n})`},pe={...C(),nullsFirst:(e,t)=>t===`desc`?i`${e} DESC NULLS FIRST`:i`${e} ASC NULLS FIRST`,nullsLast:(e,t)=>t===`desc`?i`${e} DESC NULLS LAST`:i`${e} ASC NULLS LAST`},me={...M(),multiply:(e,t,n)=>{let r=n?.decimal;return r?guardedCoefficientAssignment(e,i`${t} = 0 OR ABS(${e}) <= ${G} / ABS(${t})`,R(W,i`(${e} * ${t})`,H(r.scale)),r):i`${e} = ${e} * ${t}`},divide:(e,t,n)=>{let r=n?.decimal;if(r){let n=H(r.scale);return guardedCoefficientAssignment(e,i`ABS(${e}) <= ${G} / ${n}`,R(W,F(i`(${e} * ${n})`,t),i`ABS(${t})`),r)}return n?.integer?i`${e} = ${e} / CAST(${t} AS INTEGER)`:i`${e} = ${e} / ${t}`},push:(e,t)=>i`${e} = ${jsonArrayConcat(i`json(COALESCE(${e}, '[]'))`,t)}`,unshift:(e,t)=>i`${e} = ${jsonArrayConcat(t,i`json(COALESCE(${e}, '[]'))`)}`},Q={skipDuplicatesStrategy:`sql`,insert:E(U),insertDefault:e=>i`INSERT INTO ${e} DEFAULT VALUES`,...ie(),returning:e=>i`RETURNING ${e}`,...oe()},he={exists:e=>i`SELECT CASE WHEN EXISTS (${e}) THEN 1 ELSE json_extract('x', '$') END AS "__viborm_assert__"`,notExists:e=>i`SELECT CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE json_extract('x', '$') END AS "__viborm_assert__"`,holds:(e,t)=>i`SELECT CASE WHEN ${e} THEN 1 ELSE json_extract('{}', '__viborm_refused__') END AS "__viborm_judged__"${t?i` FROM ${t}`:i``}`},ge={...T(),right:(e,t)=>{throw Error(`SQLite does not support RIGHT JOIN. Restructure the query with joins.left and swapped operands.`)},full:(e,t)=>{throw Error(`SQLite does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.`)},lateral:(e,t)=>{throw Error(`SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.`)},lateralLeft:(e,t)=>{throw Error(`SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.`)}},_e={supportsReturning:!0,supportsCteWithMutations:!1,supportsFullOuterJoin:!1,supportsLateralJoins:!1,supportsVector:!1,supportsUpsertWhere:!0,supportsTargetedUpsert:!0,supportsMutationTargetInSubquery:!0,supportsMutationRowLimit:!1,supportsRowLocks:!1,joinsJunctionFilters:!0},ve={decimalRepresentation:`coefficient`,decimalListRepresentation:`coefficient`,dateTimeRepresentation:s,idRepresentation:(e,t)=>o(e,t,`sqlite`)?.representation??`text`,parseResult:c,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>n()},ye=_(U),be=re(),xe=d(),$=f(U),Se=O(U,{materializing:i.raw(`MATERIALIZED`)}),Ce=A(U,(e,t,n)=>i`(${e.head} UNION ALL VALUES ${i.join(t.map(x),`, `)}) AS ${i.raw(U(n))}`),we=ne();function balancedConjunction(e){let balanced=(...t)=>{if(t.length<=2)return e(...t);let n=Math.floor(t.length/2);return e(balanced(...t.slice(0,n)),balanced(...t.slice(n)))};return balanced}var SQLiteAdapter=class{constructor({temporaryObjects:e=!0,deepExpressions:t=!0,sharedRelationBodies:n=!1,compoundSelectTerms:r,relationsPerStatement:a}={}){z(this,this.geoPoint),t||(this.subqueries.existsCheck=(e,t)=>i`SELECT 1 FROM (${$.existsCheck(e,t)})`,this.subqueries.isolated=e=>i`EXISTS (SELECT 1 FROM (SELECT 1 WHERE ${e}))`,this.operators.and=balancedConjunction(Z.and),this.capabilities.boundsExpressionDepth=!0),n&&(this.capabilities.sharesRelationBodies=!0),r!==void 0&&(this.capabilities.compoundSelectTerms=r),a!==void 0&&(this.capabilities.relationsPerStatement=a);let o,createBatchRefs=()=>this.#t(e);l(this,{get batchRefs(){return o??=createBatchRefs(),o},constraints:I,select:this.#e.select})}raw=we;identifiers={...ye};literals={...X};operators={...Z};expressions={...le};aggregates={...ue};json={...de};arrays={...fe};orderBy={...pe};clauses={...be};set={...me};filters={...xe};subqueries={...$};noLimitValue=i.raw(`-1`);#e={select:e=>e.distinct?V(e,e.distinct,this.identifiers.escape,this.noLimitValue):L(i`SELECT ${e.columns}`,e,{forUpdate:`omit`,noLimitValue:this.noLimitValue})};cte={...Se};mutations={...Q};assertions={...he};joins={...ge};setOperations={...Ce};capabilities={..._e};lastInsertId=()=>i.raw(`last_insert_rowid()`);#t(e){let t=i.raw(U(P)),n=i.raw(e?`CREATE TEMP TABLE IF NOT EXISTS`:`CREATE TABLE IF NOT EXISTS`);return N({table:t,batchIdColumn:i.raw(`"batch_id"`),keyColumn:i.raw(`"ref_key"`),valueColumn:i.raw(`"ref_value"`),createTable:i`${n} ${t} ("batch_id" TEXT NOT NULL, "ref_key" TEXT NOT NULL, "ref_value" TEXT, PRIMARY KEY ("batch_id", "ref_key"))`,castValue:e=>i`CAST((${e}) AS TEXT)`,lastInsertId:()=>this.lastInsertId()})}vector=t;geoPoint=(()=>{let longitude=e=>this.json.numberAtPath(e,[`longitude`]),latitude=e=>this.json.numberAtPath(e,[`latitude`]);return{value:(e,t)=>i`json_object('longitude', ${this.json.document(this.json.number(e))}, 'latitude', ${this.json.document(this.json.number(t))})`,longitude,latitude,...B(longitude,latitude,this.operators)}})();result={...ve}};export{SQLiteAdapter as t};
2
- //# sourceMappingURL=sqlite-adapter-B3dRr5fl.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,m as n}from"./validation-gwZYm3Yn.mjs";import{E as r}from"./geo-point-codec-pAWYj5ZZ.mjs";import{o as i,t as a}from"./sql-BvHwL73I.mjs";import{a as o,t as s}from"./physical-C4D-979R.mjs";import{t as c}from"./adapter-result-parser-D6lluSMi.mjs";import{r as l}from"./adapter-internals-Cy2QEBnH.mjs";import{i as u}from"./datetime-physical-codec-CFoeuitT.mjs";import{t as ee}from"./json-number-CGXpPu4D.mjs";import{C as d,D as f,E as p,M as m,N as h,O as te,S as ne,T as re,_ as ie,a as ae,b as oe,d as g,f as _,g as v,h as y,i as b,j as x,k as S,l as C,n as w,o as T,p as E,r as D,s as O,v as k,w as A,x as j,y as M}from"./standard-sql-DmKF8msN.mjs";import{r as N,t as P}from"./batch-refs-BYCu1JnQ.mjs";import{f as F,h as I,n as L,o as R,p as z,r as B,t as V,u as H}from"./select-assembly-BjT_fDbu.mjs";const U=h(`"`),W={quotient:(e,t)=>i`(${e} / ${t})`,remainder:(e,t)=>i`(${e} % ${t})`};function sqliteIntegerPrecision(e){let t=te(e);if(t<19)return t;if(!(t>19))return(e.startsWith(`-`)?e.slice(1)<=`9223372036854775808`:e<=`9223372036854775807`)?t:void 0}const G=i.raw(`1000000000000000000`),overflowCoefficient=e=>i.raw(`1${`0`.repeat(Math.min(e.precision,18))}`),guardedCoefficientAssignment=(e,t,n,r)=>i`${e} = CASE WHEN ${e} IS NULL OR ${t} THEN ${n} ELSE ${overflowCoefficient(r)} END`,K=/^\d+$/,q=/["\\]/,jsonPathLeg=e=>{if(K.test(e))return`$[${e}]`;if(q.test(e))throw Error(`SQLite JSON path segments containing " or \\ must be rejected by the portable query contract.`);return`$."${e}"`},jsonExtract=(e,t)=>{let n=i`${e} -> '$'`;for(let e of t)n=i`${n} -> ${jsonPathLeg(e)}`;return n},jsonExtractText=(e,t)=>{if(t.length===0)return i`${e} ->> '$'`;let n=t.map(jsonPathLeg),r=n.pop(),a=e;for(let e of n)a=i`${a} -> ${e}`;return i`${a} ->> ${r}`},jsonArrayConcat=(e,t)=>i`(CASE WHEN ${e} = '[]' THEN ${t} WHEN ${t} = '[]' THEN ${e} ELSE substr(${e}, 1, length(${e}) - 1) || ',' || substr(${t}, 2) END)`,sqliteJsonListValue=e=>i`${m(e)}`,se=[``,``],J=[`CAST(`,` AS INTEGER)`],ce=/\p{Cs}/u,Y=p().list;function jsonMember(e){return typeof e==`string`?ce.test(e)?void 0:JSON.stringify(e):e instanceof Uint8Array?`"${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}"`:typeof e==`bigint`||typeof e==`boolean`||Number.isSafeInteger(e)?String(e):void 0}function sqliteList(e){if(e.length<=25)return Y(e);let[t]=e,n=t?.strings[0]===J[0]?J:se,r=[],o=0;for(let t of e){let[i,a,s]=t.strings,c=t.values[0],l=jsonMember(c);if(l===void 0||i!==n[0]||a!==n[1]||s!==void 0)return Y(e);c instanceof Uint8Array&&o++,r.push(l)}return o!==0&&o!==e.length?Y(e):i`(SELECT ${new a(n,[i.raw(o===0?`value`:`unhex(value)`)])} FROM json_each(${`[${r.join(`,`)}]`}))`}const X={...p(),value:e=>{if(typeof e==`bigint`&&sqliteIntegerPrecision(String(e))===void 0)throw new n(`SQLite bigint values must fit signed 64-bit integers.`);return i`${e}`},true:()=>i.raw(`1`),false:()=>i.raw(`0`),json:e=>i`${JSON.stringify(e)}`,dateTime:(e,t)=>i`${u(e,s(t))}`,decimal:(e,t)=>new a(J,[r(e,t,`coefficient`)]),id:(e,t)=>i`${e}`,list:sqliteList},Z={...ae(),like:(e,t)=>i`${e} LIKE ${t} ESCAPE '\\'`,notLike:(e,t)=>i`${e} NOT LIKE ${t} ESCAPE '\\'`,ilike:(e,t)=>i`lower(${e}) LIKE lower(${t}) ESCAPE '\\'`,notIlike:(e,t)=>i`lower(${e}) NOT LIKE lower(${t}) ESCAPE '\\'`,containsText:(e,t)=>i`instr(${e}, ${t}) > 0`,startsWithText:(e,t)=>i`substr(${e}, 1, length(${t})) COLLATE BINARY = ${t}`,endsWithText:(e,t)=>i`substr(${e}, length(${e}) - length(${t}) + 1) COLLATE BINARY = ${t}`,startsWithPrefix:(e,t)=>i`${e} GLOB ${`${S(t)}*`}`,exactTextEq:(e,t)=>i`${e} COLLATE BINARY = ${t}`,exactTextIn:(e,t)=>i`${e} COLLATE BINARY IN ${t}`,...v(),...k(),...j(),...y(X.true,X.false),...g()},le={...b(),asciiCaseFold:e=>i`lower(${e})`,caseSensitiveText:e=>i`${e} COLLATE BINARY`,concat:(...e)=>e.length===0?i.raw(`''`):e.length===1?e[0]:i`(${i.join(e,` || `)})`,greatest:(...e)=>i`MAX(${i.join(e,`, `)})`,least:(...e)=>i`MIN(${i.join(e,`, `)})`,integerDivide:(e,t)=>i`(${e} / CAST(${t} AS INTEGER))`,decimalCast:(e,t)=>i`CAST(${e} AS INTEGER)`,idCast:(e,t)=>t===`bytes`?i`unhex(${e})`:i`CAST(${e} AS TEXT)`,cast:D({text:`TEXT`,integer:`INTEGER`,bigint:`INTEGER`,boolean:`INTEGER`,numeric:`NUMERIC`}),blobToHex:e=>i`lower(hex(${e}))`},ue={...w(`9e999`),decimalAvg:(e,t)=>R(W,i`SUM(${e})`,i`COUNT(${e})`),decimalSumOperandPrecision:sqliteIntegerPrecision,integerSum:e=>{let t=i`SUM(${e} >> 32)`,n=i`SUM(${e} - ((${e} >> 32) << 32))`,r=i`(${t} + (${n} >> 32))`,a=i`(${n} & 4294967295)`,o=i`${r} * 4294967296.0 + ${a}`;return{parts:[t,n],value:i`CASE WHEN ${r} > 2147483647 THEN ${o} WHEN ${r} >= -2147483648 THEN ${r} * 4294967296 + ${a} ELSE MIN(${o}, -9223372036854777856.0) END`,order:[r,a]}}};function sqliteJsonEquals(e,t){let nodes=e=>i`SELECT fullkey, CASE WHEN type IN ('integer', 'real') THEN 'number' ELSE type END, atom FROM json_tree(${e})`;return i`(CASE WHEN ${e} IS NULL OR ${t} IS NULL THEN NULL ELSE NOT EXISTS (${nodes(e)} EXCEPT ${nodes(t)}) AND NOT EXISTS (${nodes(t)} EXCEPT ${nodes(e)}) END)`}const sqliteJsonObject=e=>{if(e.length===0)return i.raw(`json_object()`);let t=e.flatMap(([e,t])=>[i`${e}`,t]);return i`json_object(${i.join(t,`, `)})`},de={equals:sqliteJsonEquals,number:e=>i`CASE WHEN ${e} IS NULL THEN NULL ELSE printf(${i.raw(`'${ee}'`)}, ${e}) END`,boolean:e=>i`json(CASE WHEN ${e} THEN 'true' ELSE 'false' END)`,document:e=>i`json(${e})`,object:sqliteJsonObject,array:e=>e.length===0?i.raw(`json_array()`):i`json_array(${i.join(e,`, `)})`,emptyArray:()=>i.raw(`json_array()`),agg:e=>i`json_group_array(${e})`,objectFromColumns:sqliteJsonObject,extract:jsonExtract,extractText:jsonExtractText,numberAtPath:(e,t)=>i`(CASE WHEN json_type(${jsonExtract(e,t)}) IN ('integer', 'real') THEN CAST(${jsonExtractText(e,t)} AS REAL) END)`,stringAtPath:(e,t)=>i`((CASE WHEN json_type(${jsonExtract(e,t)}) = 'text' THEN ${jsonExtractText(e,t)} END) COLLATE BINARY)`,contains:(e,t)=>i`(json_type(${e}) = 'array' AND NOT EXISTS (SELECT 1 FROM json_each(${t}) AS required WHERE NOT EXISTS (SELECT 1 FROM json_each(${e}) AS candidate WHERE ${sqliteJsonEquals(i`${e} -> candidate.fullkey`,i`${t} -> required.fullkey`)})))`,lastElement:e=>i`${e} -> '$[#-1]'`,value:e=>i`${m(e)}`},fe={literal:e=>e.length===0?i.raw(`json_array()`):i`json_array(${i.join(e,`, `)})`,value:sqliteJsonListValue,enumValue:sqliteJsonListValue,has:(e,t)=>i`EXISTS (SELECT 1 FROM json_each(${e}) WHERE value = ${t})`,hasEvery:(e,t)=>i`(SELECT COUNT(*) FROM json_each(${t}) WHERE value IN (SELECT value FROM json_each(${e}))) = json_array_length(${t})`,hasSome:(e,t)=>i`EXISTS (SELECT 1 FROM json_each(${e}) AS a, json_each(${t}) AS b WHERE a.value = b.value)`,isEmpty:e=>i`(json_array_length(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>i`CAST(${e} AS TEXT)`,length:e=>i`json_array_length(${e})`,get:(e,t)=>i`json_extract(${e}, '$[' || ${t} || ']')`,push:(e,t)=>i`json_insert(${e}, '$[#]', ${t})`,set:(e,t,n)=>i`json_set(${e}, '$[' || ${t} || ']', ${n})`},pe={...C(),nullsFirst:(e,t)=>t===`desc`?i`${e} DESC NULLS FIRST`:i`${e} ASC NULLS FIRST`,nullsLast:(e,t)=>t===`desc`?i`${e} DESC NULLS LAST`:i`${e} ASC NULLS LAST`},me={...M(),multiply:(e,t,n)=>{let r=n?.decimal;return r?guardedCoefficientAssignment(e,i`${t} = 0 OR ABS(${e}) <= ${G} / ABS(${t})`,R(W,i`(${e} * ${t})`,H(r.scale)),r):i`${e} = ${e} * ${t}`},divide:(e,t,n)=>{let r=n?.decimal;if(r){let n=H(r.scale);return guardedCoefficientAssignment(e,i`ABS(${e}) <= ${G} / ${n}`,R(W,F(i`(${e} * ${n})`,t),i`ABS(${t})`),r)}return n?.integer?i`${e} = ${e} / CAST(${t} AS INTEGER)`:i`${e} = ${e} / ${t}`},push:(e,t)=>i`${e} = ${jsonArrayConcat(i`json(COALESCE(${e}, '[]'))`,t)}`,unshift:(e,t)=>i`${e} = ${jsonArrayConcat(t,i`json(COALESCE(${e}, '[]'))`)}`},Q={skipDuplicatesStrategy:`sql`,insert:E(U),insertDefault:e=>i`INSERT INTO ${e} DEFAULT VALUES`,...ie(),returning:e=>i`RETURNING ${e}`,...oe()},he={exists:e=>i`SELECT CASE WHEN EXISTS (${e}) THEN 1 ELSE json_extract('x', '$') END AS "__viborm_assert__"`,notExists:e=>i`SELECT CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE json_extract('x', '$') END AS "__viborm_assert__"`,holds:(e,t)=>i`SELECT CASE WHEN ${e} THEN 1 ELSE json_extract('{}', '__viborm_refused__') END AS "__viborm_judged__"${t?i` FROM ${t}`:i``}`},ge={...T(),right:(e,t)=>{throw Error(`SQLite does not support RIGHT JOIN. Restructure the query with joins.left and swapped operands.`)},full:(e,t)=>{throw Error(`SQLite does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.`)},lateral:(e,t)=>{throw Error(`SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.`)},lateralLeft:(e,t)=>{throw Error(`SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.`)}},_e={supportsReturning:!0,supportsCteWithMutations:!1,supportsFullOuterJoin:!1,supportsLateralJoins:!1,supportsVector:!1,supportsUpsertWhere:!0,supportsTargetedUpsert:!0,supportsMutationTargetInSubquery:!0,supportsMutationRowLimit:!1,supportsRowLocks:!1,joinsJunctionFilters:!0},ve={decimalRepresentation:`coefficient`,decimalListRepresentation:`coefficient`,dateTimeRepresentation:s,idRepresentation:(e,t)=>o(e,t,`sqlite`)?.representation??`text`,parseResult:c,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>n()},ye=_(U),be=re(),xe=d(),$=f(U),Se=O(U,{materializing:i.raw(`MATERIALIZED`)}),Ce=A(U,(e,t,n)=>i`(${e.head} UNION ALL VALUES ${i.join(t.map(x),`, `)}) AS ${i.raw(U(n))}`),we=ne();function balancedConjunction(e){let balanced=(...t)=>{if(t.length<=2)return e(...t);let n=Math.floor(t.length/2);return e(balanced(...t.slice(0,n)),balanced(...t.slice(n)))};return balanced}var SQLiteAdapter=class{constructor({temporaryObjects:e=!0,deepExpressions:t=!0,sharedRelationBodies:n=!1,compoundSelectTerms:r,relationsPerStatement:a,countsCascadedChanges:o}={}){z(this,this.geoPoint),t||(this.subqueries.existsCheck=(e,t)=>i`SELECT 1 FROM (${$.existsCheck(e,t)})`,this.subqueries.isolated=e=>i`EXISTS (SELECT 1 FROM (SELECT 1 WHERE ${e}))`,this.operators.and=balancedConjunction(Z.and),this.capabilities.boundsExpressionDepth=!0),n&&(this.capabilities.sharesRelationBodies=!0),r!==void 0&&(this.capabilities.compoundSelectTerms=r),a!==void 0&&(this.capabilities.relationsPerStatement=a),o&&(this.capabilities.countsCascadedChanges=!0);let s,createBatchRefs=()=>this.#t(e);l(this,{get batchRefs(){return s??=createBatchRefs(),s},constraints:I,select:this.#e.select})}raw=we;identifiers={...ye};literals={...X};operators={...Z};expressions={...le};aggregates={...ue};json={...de};arrays={...fe};orderBy={...pe};clauses={...be};set={...me};filters={...xe};subqueries={...$};noLimitValue=i.raw(`-1`);#e={select:e=>e.distinct?V(e,e.distinct,this.identifiers.escape,this.noLimitValue):L(i`SELECT ${e.columns}`,e,{forUpdate:`omit`,noLimitValue:this.noLimitValue})};cte={...Se};mutations={...Q};assertions={...he};joins={...ge};setOperations={...Ce};capabilities={..._e};lastInsertId=()=>i.raw(`last_insert_rowid()`);#t(e){let t=i.raw(U(P)),n=i.raw(e?`CREATE TEMP TABLE IF NOT EXISTS`:`CREATE TABLE IF NOT EXISTS`);return N({table:t,batchIdColumn:i.raw(`"batch_id"`),keyColumn:i.raw(`"ref_key"`),valueColumn:i.raw(`"ref_value"`),createTable:i`${n} ${t} ("batch_id" TEXT NOT NULL, "ref_key" TEXT NOT NULL, "ref_value" TEXT, PRIMARY KEY ("batch_id", "ref_key"))`,castValue:e=>i`CAST((${e}) AS TEXT)`,lastInsertId:()=>this.lastInsertId()})}vector=t;geoPoint=(()=>{let longitude=e=>this.json.numberAtPath(e,[`longitude`]),latitude=e=>this.json.numberAtPath(e,[`latitude`]);return{value:(e,t)=>i`json_object('longitude', ${this.json.document(this.json.number(e))}, 'latitude', ${this.json.document(this.json.number(t))})`,longitude,latitude,...B(longitude,latitude,this.operators)}})();result={...ve}};export{SQLiteAdapter as t};
2
+ //# sourceMappingURL=sqlite-adapter-CLWY4B8w.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite-adapter-CLWY4B8w.mjs","names":["sql","#createBatchRefs","#assemble"],"sources":["../src/adapters/databases/sqlite/sqlite-adapter.ts"],"sourcesContent":["import { UnsupportedOperationError, unsupportedVector } from \"@errors\";\nimport { sqliteDateTimePhysicalForm } from \"@schema/scalars/datetime/physical\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { Sql, sql } from \"@sql\";\nimport { encodePhysicalDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport type {\n ArithmeticTarget,\n BatchReferenceSqlAdapter,\n} from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport {\n type AdapterResultParser,\n passThroughParseResult,\n} from \"../../adapter-result-parser\";\nimport { sqliteConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n} from \"../../database-adapter\";\nimport {\n BATCH_REFS_TABLE,\n createOnConflictBatchRefs,\n} from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n halfEvenQuotient,\n scaleFactorSql,\n signedNumerator,\n} from \"../../shared/decimal-arithmetic\";\nimport { createGeoPointCoordinatePredicates } from \"../../shared/geo-point\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDirectionOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLogicalOperators,\n createMembershipOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createOnConflictBuilders,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n decimalCoefficientPrecision,\n escapeGlobLiteral,\n rowValues,\n stringifyJson,\n} from \"../../shared/standard-sql\";\nimport { SQLITE_BINARY64_FORMAT } from \"./storage/json-number\";\n\nconst quoteIdent = createIdentifierQuoter('\"');\n\n/**\n * Every SQLite decimal expression is signed-int64 integer arithmetic on the\n * stored unscaled coefficient, so `/` IS truncating integer division and `%`\n * carries the dividend's sign. Neither is true once an operand becomes REAL or\n * TEXT, which is why every operand below arrives as an INTEGER column, an\n * integer literal, or a `CAST(... AS INTEGER)` bind.\n */\nconst SQLITE_INTEGERS: ExactIntegerArithmetic = {\n quotient: (n: Sql, d: Sql): Sql => sql`(${n} / ${d})`,\n remainder: (n: Sql, d: Sql): Sql => sql`(${n} % ${d})`,\n};\n\nconst SQLITE_INT64_NEGATIVE_MAGNITUDE = \"9223372036854775808\";\nconst SQLITE_INT64_MAX = \"9223372036854775807\";\n\n/** Admit the exact TEXT-to-INTEGER cast domain, including its 19-digit edges. */\nfunction sqliteIntegerPrecision(coefficient: string): number | undefined {\n const precision = decimalCoefficientPrecision(coefficient);\n if (precision < 19) return precision;\n if (precision > 19) return undefined;\n const isAdmitted = coefficient.startsWith(\"-\")\n ? coefficient.slice(1) <= SQLITE_INT64_NEGATIVE_MAGNITUDE\n : coefficient <= SQLITE_INT64_MAX;\n return isAdmitted ? precision : undefined;\n}\n\n/**\n * The widest intermediate the guarded arms will evaluate: 10^18.\n *\n * SQLite does not raise on an integer multiply that overflows — it converts the\n * expression to REAL, which is the one representation an exact decimal must\n * never touch. So the arms are GUARDED: the guard compares magnitudes by\n * DIVISION (`|x| <= LIMIT / |y|`, exact for integers) instead of computing the\n * product it is protecting, and a `CASE` evaluates only the branch it selects.\n *\n * 10^18 is not arbitrary, and it is not independent. `precision + scale <= 18`\n * is SQLite's declared field limit (plan 3.1), ENFORCED once when the schema is\n * bound (`schema/scalars/decimal/provider-limits.ts`), so every mathematically\n * in-range result has `|x * y| <= 10^(p+s) <= 10^18`: the guard never rejects\n * an answer that fits the field, and int64 keeps a factor of nine in reserve\n * for the `+/- 1` step and the `d - |r|` tie test.\n *\n * THE COUPLING IS LOAD-BEARING, in both directions. This constant is flat where\n * the per-descriptor bound would be `B = scale === 0 ? M : M*F + F/2 - 1`, and\n * that is only equivalent because no descriptor past `p + s = 18` can reach it:\n * a product in `(B, 10^18]` is admitted here and then refused by the range\n * CHECK instead of by the sentinel — the same loud, atomic failure by the other\n * mechanism. Remove the bind limit and the flat guard stops being a bound on\n * the FIELD at all, which is exactly what {@link overflowCoefficient} depends\n * on below.\n */\nconst SQLITE_INTERMEDIATE_LIMIT = sql.raw(\"1000000000000000000\");\n\n/**\n * The coefficient an unsafe or out-of-domain arithmetic result becomes: 10^p,\n * the smallest integer OUTSIDE a `precision: p` field's declared range.\n *\n * The DDL's range check refuses it, so the statement fails atomically and\n * nothing is written — which is the contract for an overflow that is only\n * knowable mid-statement.\n *\n * THE CLAMP DEPENDS ON THE BIND LIMIT, and is only correct because of it. At 19\n * digits and beyond, `10^p` is a REAL to SQLite's own parser, so the sentinel\n * would stop being an integer the CHECK can refuse — and `min(p, 18)` would put\n * it INSIDE the range of a `precision >= 19` column, which is a silently\n * written wrong value rather than a failure. No such column exists: plan 3.1's\n * `precision <= 18 && precision + scale <= 18` is proven once at schema bind\n * (`schema/scalars/decimal/provider-limits.ts`), before any I/O, so\n * `min(p, 18)` is `p` for every descriptor that ever reaches here. The clamp is\n * what an unreachable arm does when it is reached anyway, not a policy — and it\n * is why the bind limit is load-bearing rather than ergonomic.\n */\nconst overflowCoefficient = (descriptor: DecimalDescriptor): Sql =>\n sql.raw(`1${\"0\".repeat(Math.min(descriptor.precision, 18))}`);\n\n/**\n * `column = <exact coefficient arithmetic>`, or the constraint-breaking\n * coefficient when the intermediate would leave int64.\n *\n * A NULL column is safe by definition and takes the guarded arm, where every\n * operator is null-strict and the assignment stays NULL.\n */\nconst guardedCoefficientAssignment = (\n column: Sql,\n safe: Sql,\n value: Sql,\n descriptor: DecimalDescriptor\n): Sql =>\n sql`${column} = CASE WHEN ${column} IS NULL OR ${safe} THEN ${value} ELSE ${overflowCoefficient(descriptor)} END`;\n\nconst JSON_ARRAY_INDEX_SEGMENT = /^\\d+$/;\nconst JSON_UNADDRESSABLE_LABEL = /[\"\\\\]/;\n\n// Each path segment binds as its own single-leg JSONPath ('$[N]' for\n// array indices, '$.\"seg\"' otherwise) chained with -> , so segments can\n// never splice extra legs into the path. SQLite's path grammar has no\n// escape syntax inside quoted labels, so the portable query contract rejects\n// keys containing \" or \\ before adapter execution. This throw is defensive.\nconst jsonPathLeg = (segment: string): string => {\n if (JSON_ARRAY_INDEX_SEGMENT.test(segment)) {\n return `$[${segment}]`;\n }\n if (JSON_UNADDRESSABLE_LABEL.test(segment)) {\n throw new Error(\n 'SQLite JSON path segments containing \" or \\\\ must be rejected by the portable query contract.'\n );\n }\n return `$.\"${segment}\"`;\n};\n\n/** Chain one bound `-> '$leg'` per path segment ('$' alone = document root). */\nconst jsonExtract = (column: Sql, path: string[]): Sql => {\n let expr = sql`${column} -> '$'`;\n for (const segment of path) {\n expr = sql`${expr} -> ${jsonPathLeg(segment)}`;\n }\n return expr;\n};\n\n/** Same chain, but the final leg uses `->>` so strings come back unquoted. */\nconst jsonExtractText = (column: Sql, path: string[]): Sql => {\n if (path.length === 0) {\n return sql`${column} ->> '$'`;\n }\n const legs = path.map(jsonPathLeg);\n const last = legs.pop()!;\n let expr: Sql = column;\n for (const leg of legs) {\n expr = sql`${expr} -> ${leg}`;\n }\n return sql`${expr} ->> ${last}`;\n};\n\n/**\n * Concatenate two JSON array texts by string surgery: strip `left`'s closing\n * bracket and `right`'s opening bracket. SQLite has no JSON array-concat\n * function, and json_insert('$[#]') can only append one element per pair.\n * Both sides must be canonical JSON (json() output or JSON.stringify).\n */\nconst jsonArrayConcat = (left: Sql, right: Sql): Sql =>\n sql`(CASE WHEN ${left} = '[]' THEN ${right} WHEN ${right} = '[]' THEN ${left} ELSE substr(${left}, 1, length(${left}) - 1) || ',' || substr(${right}, 2) END)`;\n\n/** The one JSON list container every SQLite list value crosses as. */\nconst sqliteJsonListValue = (values: unknown[]): Sql =>\n sql`${stringifyJson(values)}`;\n\n/** A bare operand, and a decimal operand: its coefficient read as INTEGER. */\nconst PARAMETER = [\"\", \"\"];\nconst COEFFICIENT = [\"CAST(\", \" AS INTEGER)\"];\nconst LONE_SURROGATE = /\\p{Cs}/u;\nconst PARENTHESIZED_LIST = createStandardLiterals().list;\n/**\n * The longest list kept parenthesized. Without `sqlite_stat1` SQLite sizes an\n * `IN (SELECT …)` at 25 rows and a list at its length, so up to 25 members the\n * list is planned no worse: a key list beside another indexed equality still\n * seeks the key. It is also a quarter of D1's 100-value bind budget.\n */\nconst PLANNED_LIST = 25;\n\n/**\n * One member as JSON text that `json_each` reads back as the value its own\n * parameter binds, or `undefined`. A non-integer number is not one: SQLite\n * reparses JSON text with an error in the last place for some doubles; nor is\n * a string with a lone surrogate, which a driver binds as U+FFFD.\n */\nfunction jsonMember(value: unknown): string | undefined {\n if (typeof value === \"string\")\n return LONE_SURROGATE.test(value) ? undefined : JSON.stringify(value);\n if (value instanceof Uint8Array)\n return `\"${Array.from(value, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}\"`;\n return typeof value === \"bigint\" ||\n typeof value === \"boolean\" ||\n Number.isSafeInteger(value)\n ? String(value)\n : undefined;\n}\n\n/**\n * engine-09: a list longer than {@link PLANNED_LIST} whose members are each one\n * parameter under one spelling — bare, or a decimal's coefficient cast — as\n * ONE parameter, a JSON array `json_each` reads back and spells per element as\n * each member was, so `IN` and `NOT IN` keep their answers, NULLs included.\n * Blobs travel as hex, read through `unhex` (SQLite 3.41). Any other list\n * keeps a parameter per member.\n */\nfunction sqliteList(members: Sql[]): Sql {\n if (members.length <= PLANNED_LIST) return PARENTHESIZED_LIST(members);\n const [first] = members;\n const spelling =\n first?.strings[0] === COEFFICIENT[0] ? COEFFICIENT : PARAMETER;\n const elements: string[] = [];\n let blobs = 0;\n for (const member of members) {\n const [head, tail, extra] = member.strings;\n const value = member.values[0];\n const element = jsonMember(value);\n if (\n element === undefined ||\n head !== spelling[0] ||\n tail !== spelling[1] ||\n extra !== undefined\n )\n return PARENTHESIZED_LIST(members);\n if (value instanceof Uint8Array) blobs++;\n elements.push(element);\n }\n // Blobs beside other values: nothing one spelling reads.\n if (blobs !== 0 && blobs !== members.length)\n return PARENTHESIZED_LIST(members);\n const read = new Sql(spelling, [\n sql.raw(blobs === 0 ? \"value\" : \"unhex(value)\"),\n ]);\n return sql`(SELECT ${read} FROM json_each(${`[${elements.join(\",\")}]`}))`;\n}\n\n/** Facts a SQLite driver states about its transport. */\nexport interface SQLiteAdapterOptions {\n /**\n * Whether the transport admits temporary objects (`CREATE TEMP TABLE`).\n * better-sqlite3, libSQL and bun:sqlite do; Cloudflare D1's authorizer\n * rejects them with `SQLITE_AUTH`, and rejects the whole batch with them.\n * Defaults to `true`.\n */\n readonly temporaryObjects?: boolean;\n /**\n * Whether the transport compiles deep expression trees. SQLite counts a\n * subquery's `WHERE` in the height of the expression that holds it, and sums\n * those heights again while it resolves names, so k nested relation filters\n * cost about k² of `SQLITE_MAX_EXPR_DEPTH`: SQLite's default (1000) admits\n * that; Cloudflare D1 compiles with 100 and refuses \"Expression tree is too\n * large\". Where it does not, each relation filter reads its rows from a\n * derived table, whose `WHERE` neither count reaches through the expression:\n * about four per level, the same plan (SQLite flattens it), one statement.\n * A conjunction of many members nests as a balanced tree where it does not,\n * as the engine already nests a disjunction: SQLite parses `a AND b AND …`\n * one level per member. A level's row domain, where the filter goes on\n * below it, is isolated the same way (`subqueries.isolated`), so a policy\n * costs its height once and not at every level (measured on D1: a\n * three-arm read policy 10 per level, failing at 9 levels; isolated, 5 per\n * level, 94 at the 15 levels admission takes).\n * Defaults to `true`.\n */\n readonly deepExpressions?: boolean;\n /**\n * Whether a statement states each relation filter body it repeats once\n * (`capabilities.sharesRelationBodies`), for a\n * transport that bounds statement text (Cloudflare D1: 100 KB). Defaults\n * to `false`.\n */\n readonly sharedRelationBodies?: boolean;\n /**\n * The most terms one compound `SELECT` may chain\n * (`capabilities.compoundSelectTerms`): Cloudflare D1 compiles SQLite with\n * 5 and refuses a sixth (\"too many terms in compound SELECT\"). Defaults to\n * SQLite's own bound, which the engine never reaches.\n */\n readonly compoundSelectTerms?: number;\n /**\n * Where bodies are shared, the relations a statement may reference before\n * its repeated walks become reaching sets and its rows join the key sets\n * they test (`capabilities.relationsPerStatement`). Absent: unbounded.\n */\n readonly relationsPerStatement?: number;\n /**\n * Whether the transport's affected-row count also counts the rows a foreign\n * key's cascade changed (`capabilities.countsCascadedChanges`): Cloudflare\n * D1's `meta.changes` does. Defaults to `false`, SQLite's own count.\n */\n readonly countsCascadedChanges?: boolean;\n}\n\n/**\n * The dialect's stateless SQL builders, built once per module. Each adapter\n * takes its own shallow copy of every group, so a driver that overrides one\n * hook (`driver.adapter.result.parseField = …`) changes only its own adapter,\n * as before, while a driver per request no longer rebuilds every closure.\n */\nconst SQLITE_LITERALS = {\n ...createStandardLiterals(),\n\n value: (value: unknown): Sql => {\n if (\n typeof value === \"bigint\" &&\n sqliteIntegerPrecision(String(value)) === undefined\n )\n throw new UnsupportedOperationError(\n \"SQLite bigint values must fit signed 64-bit integers.\"\n );\n return sql`${value}`;\n },\n\n // SQLite uses 1/0 for booleans\n true: (): Sql => sql.raw(\"1\"),\n\n false: (): Sql => sql.raw(\"0\"),\n\n // SQLite requires JSON values to be stringified\n json: (v: unknown): Sql => sql`${JSON.stringify(v)}`,\n\n // SQLite has no temporal type, so the field's declaration is what the column\n // physically holds and the operand has to be the same kind of value: an ISO\n // string bound against an epoch-millisecond INTEGER matches no row and,\n // written, stores text the typed read then refuses. A TEXT-declared or\n // undeclared field keeps the ISO spelling byte for byte. The string is a\n // validated ISO timestamp — the ISO boundary owns that — and every\n // four-digit public instant round-trips through the Julian-day double.\n dateTime: (iso: string, nativeType?: NativeTypeDeclaration): Sql =>\n sql`${encodePhysicalDateTime(iso, sqliteDateTimePhysicalForm(nativeType))}`,\n\n // SQLite has no exact decimal type, so a decimal column stores the UNSCALED\n // INTEGER COEFFICIENT and an operand becomes that same coefficient. Integer\n // comparison is then exact numeric comparison, and ordering, aggregation\n // and arithmetic are exact for the same reason.\n //\n // The digits bind as TEXT and `CAST(... AS INTEGER)` reads them, rather than\n // riding a JavaScript number (which rounds above 2^53) or a bigint (which\n // D1 will not bind). SQLite's TEXT-to-INTEGER cast is a decimal integer\n // parse, not a float one.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n new Sql(COEFFICIENT, [\n encodePhysicalDecimal(canonical, descriptor, \"coefficient\"),\n ]),\n\n // Every compact domain is a `BLOB` here and takes the payload's bytes as\n // the ordinary binary parameter a blob scalar already binds; a text-stored\n // domain takes the public string unchanged.\n id: (physical: string | Uint8Array, _representation: IdRepresentation): Sql =>\n sql`${physical}`,\n\n list: sqliteList,\n};\n\nconst SQLITE_OPERATORS = {\n ...createComparisonOperators(),\n\n // Explicit ESCAPE '\\' pairs with wildcard escaping in the where-builder\n like: (column: Sql, pattern: Sql): Sql =>\n sql`${column} LIKE ${pattern} ESCAPE '\\\\'`,\n notLike: (column: Sql, pattern: Sql): Sql =>\n sql`${column} NOT LIKE ${pattern} ESCAPE '\\\\'`,\n ilike: (column: Sql, pattern: Sql): Sql =>\n sql`lower(${column}) LIKE lower(${pattern}) ESCAPE '\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`lower(${column}) NOT LIKE lower(${pattern}) ESCAPE '\\\\'`,\n containsText: (column: Sql, value: Sql): Sql =>\n sql`instr(${column}, ${value}) > 0`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`substr(${column}, 1, length(${value})) COLLATE BINARY = ${value}`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`substr(${column}, length(${column}) - length(${value}) + 1) COLLATE BINARY = ${value}`,\n // GLOB, not LIKE — and this is the one place the \"portable escaped LIKE\"\n // premise of Decision 7.3 does not survive contact with SQLite. Both of\n // SQLite's LIKE-optimization preconditions fail here: an ESCAPE clause\n // disqualifies the optimization outright, and with `case_sensitive_like`\n // off (the default, and connection-global, so not ours to flip) the\n // optimization additionally wants a NOCASE-collated index, while `push()`\n // only ever creates BINARY ones. Measured on better-sqlite3, 20k rows,\n // plain index: `col LIKE ? ESCAPE '\\'` is a SCAN — exactly what the\n // `substr` spelling above already costs — AND it answers case-insensitively,\n // which would break the case-sensitivity contract this operator holds.\n //\n // GLOB has neither problem. It compares bytes, so it is case- and\n // accent-sensitive by construction (that is what `COLLATE BINARY` buys\n // above, so nothing is lost by dropping it), and it ranges on the ordinary\n // BINARY index: the same probe plans this as a covering index SEARCH over\n // 111 rows against a 20000-row SCAN. Its wildcards are `*`/`?`/`[`, and it\n // has no ESCAPE clause, so `escapeGlobLiteral` quotes them as classes.\n startsWithPrefix: (column: Sql, value: string): Sql =>\n sql`${column} GLOB ${`${escapeGlobLiteral(value)}*`}`,\n\n // `COLLATE BINARY` names a COLLATION, not a function of the column, and\n // SQLite's ordinary index is a BINARY index — so the case-sensitive\n // spelling is already the index-usable one and there is nothing to add.\n // Byte-identical to what shipped before §10.2.\n exactTextEq: (column: Sql, value: Sql): Sql =>\n sql`${column} COLLATE BINARY = ${value}`,\n exactTextIn: (column: Sql, values: Sql): Sql =>\n sql`${column} COLLATE BINARY IN ${values}`,\n\n ...createMembershipOperators(),\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n // Logical (vacuous cases use SQLite's 1/0 booleans)\n ...createLogicalOperators(SQLITE_LITERALS.true, SQLITE_LITERALS.false),\n\n ...createExistenceOperators(),\n};\n\nconst SQLITE_EXPRESSIONS = {\n ...createCommonExpressions(),\n\n // SQLite lower() intentionally provides the portable ASCII-only contract.\n asciiCaseFold: (expr: Sql): Sql => sql`lower(${expr})`,\n caseSensitiveText: (expr: Sql): Sql => sql`${expr} COLLATE BINARY`,\n\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw(\"''\");\n if (parts.length === 1) return parts[0]!;\n return sql`(${sql.join(parts, \" || \")})`;\n },\n\n // SQLite has no GREATEST/LEAST; multi-arg MAX/MIN are the scalar forms\n greatest: (...exprs: Sql[]): Sql => sql`MAX(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`MIN(${sql.join(exprs, \", \")})`,\n\n // The expression form of `set.divide`'s integer arm, and for the same\n // reason: SQLite drivers bind JS numbers as REAL, so `x / ?` would run real\n // division. Casting the divisor to INTEGER makes it native INT/INT\n // division, truncating toward zero.\n integerDivide: (left: Sql, right: Sql): Sql =>\n sql`(${left} / CAST(${right} AS INTEGER))`,\n\n // A deferred SQLite decimal is already a captured coefficient. The\n // descriptor still travels through the common contract so no caller can\n // select this physical cast without naming the destination domain.\n decimalCast: (expr: Sql, _descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${expr} AS INTEGER)`,\n\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`unhex(${expr})`\n : sql`CAST(${expr} AS TEXT)`,\n\n // SQLite type mappings\n cast: createCastExpression({\n text: \"TEXT\",\n integer: \"INTEGER\",\n bigint: \"INTEGER\",\n boolean: \"INTEGER\",\n numeric: \"NUMERIC\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`lower(hex(${expr}))`,\n};\n\nconst SQLITE_AGGREGATES = {\n ...createAggregateFunctions(\"9e999\"),\n\n // The average of a coefficient column IS the half-even integer quotient of\n // its exact sum by its non-null count: dividing both the sum and the count\n // of `logical x 10^s` values leaves `average x 10^s`, so no scale factor\n // appears at all. `COUNT(column)` is zero exactly when `SUM` is NULL, so\n // the null-strict operators answer NULL for an empty or all-null group and\n // the zero divisor is never reached with a value.\n decimalAvg: (column: Sql, _descriptor: DecimalDescriptor): Sql =>\n halfEvenQuotient(\n SQLITE_INTEGERS,\n sql`SUM(${column})`,\n sql`COUNT(${column})`\n ),\n\n // A SQLite decimal aggregate is an int64 `SUM` over coefficients. Exact\n // operand admission follows the signed range rather than digit count: some\n // 19-digit values fit, while the next value past either endpoint would make\n // `CAST(... AS INTEGER)` saturate. The sum itself is `integerSum`'s, exact\n // past that range.\n decimalSumOperandPrecision: sqliteIntegerPrecision,\n\n // `>>` is arithmetic, so an int64 member is exactly `(x >> 32) * 2^32` plus\n // its second part. That part stays REAL for a non-integer member, which the\n // reader refuses as it refused the plain `SUM`.\n // `low` sums non-negative 32-bit remainders: carrying its high bits into\n // `high` leaves a pair that sorts exactly as the total. `value` is that\n // total inside int64 and its nearest double outside, below -2^63 at most\n // `-2^63 - 2048`: SQLite compares an integer with a double exactly, so it\n // is exact against every int64 operand (a decimal coefficient's whole\n // domain), and a number operand past int64 is told apart from every total\n // but those that round to it.\n integerSum: (column: Sql) => {\n const high = sql`SUM(${column} >> 32)`;\n const low = sql`SUM(${column} - ((${column} >> 32) << 32))`;\n const carried = sql`(${high} + (${low} >> 32))`;\n const rest = sql`(${low} & 4294967295)`;\n const double = sql`${carried} * 4294967296.0 + ${rest}`;\n return {\n parts: [high, low] as const,\n value: sql`CASE WHEN ${carried} > 2147483647 THEN ${double} WHEN ${carried} >= -2147483648 THEN ${carried} * 4294967296 + ${rest} ELSE MIN(${double}, -9223372036854777856.0) END`,\n order: [carried, rest],\n };\n },\n};\n\n// Compare every node, including empty containers. Array indices remain part\n// of the path; object property insertion order does not. JSON numbers share\n// one domain, while booleans, strings and JSON null retain their distinct type.\nfunction sqliteJsonEquals(left: Sql, right: Sql): Sql {\n const nodes = (value: Sql) =>\n sql`SELECT fullkey, CASE WHEN type IN ('integer', 'real') THEN 'number' ELSE type END, atom FROM json_tree(${value})`;\n return sql`(CASE WHEN ${left} IS NULL OR ${right} IS NULL THEN NULL ELSE NOT EXISTS (${nodes(left)} EXCEPT ${nodes(right)}) AND NOT EXISTS (${nodes(right)} EXCEPT ${nodes(left)}) END)`;\n}\n\nconst sqliteJsonObject = (pairs: [string, Sql][]): Sql => {\n if (pairs.length === 0) return sql.raw(\"json_object()\");\n const args = pairs.flatMap(([key, value]) => [sql`${key}`, value]);\n return sql`json_object(${sql.join(args, \", \")})`;\n};\n\nconst SQLITE_JSON = {\n equals: sqliteJsonEquals,\n number: (expression: Sql): Sql =>\n sql`CASE WHEN ${expression} IS NULL THEN NULL ELSE printf(${sql.raw(`'${SQLITE_BINARY64_FORMAT}'`)}, ${expression}) END`,\n boolean: (condition: Sql): Sql =>\n sql`json(CASE WHEN ${condition} THEN 'true' ELSE 'false' END)`,\n // SQLite drops the JSON subtype across scalar-subquery boundaries. Restore it\n // before embedding the value in json_object/json_array, or an object becomes a\n // quoted JSON string inside the outer document.\n document: (expression: Sql): Sql => sql`json(${expression})`,\n\n object: sqliteJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw(\"json_array()\");\n return sql`json_array(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw(\"json_array()\"),\n\n // `expr` carries the JSON subtype (a json_object call, or a subquery\n // column restored through `document`), so it is aggregated as JSON, not\n // quoted as a string. Over no rows json_group_array is `[]`, never NULL.\n agg: (expr: Sql): Sql => sql`json_group_array(${expr})`,\n\n objectFromColumns: sqliteJsonObject,\n\n // `->` returns the value as canonical JSON text ('\"str\"', '2', 'null'),\n // the same format json.value binds, so extracted values compare with\n // plain equality (json_extract would return native SQL values instead)\n extract: jsonExtract,\n\n // `->>` returns text with strings unquoted, for LIKE matching\n extractText: jsonExtractText,\n\n // json_type reads the chained `->` result (canonical JSON text), so it\n // sees 'integer'/'real' only for real JSON numbers; every other shape —\n // and an absent path, where `->` is NULL — falls through to NULL\n numberAtPath: (column: Sql, path: string[]): Sql =>\n sql`(CASE WHEN json_type(${jsonExtract(column, path)}) IN ('integer', 'real') THEN CAST(${jsonExtractText(column, path)} AS REAL) END)`,\n\n // COLLATE BINARY is SQLite's default for these columns; naming it keeps\n // the code-point ordering contract explicit alongside PG's COLLATE \"C\"\n stringAtPath: (column: Sql, path: string[]): Sql =>\n sql`((CASE WHEN json_type(${jsonExtract(column, path)}) = 'text' THEN ${jsonExtractText(column, path)} END) COLLATE BINARY)`,\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`(json_type(${target}) = 'array' AND NOT EXISTS (SELECT 1 FROM json_each(${value}) AS required WHERE NOT EXISTS (SELECT 1 FROM json_each(${target}) AS candidate WHERE ${sqliteJsonEquals(sql`${target} -> candidate.fullkey`, sql`${value} -> required.fullkey`)})))`,\n\n lastElement: (target: Sql): Sql => sql`${target} -> '$[#-1]'`,\n\n value: (v: unknown): Sql => sql`${stringifyJson(v)}`,\n};\n\nconst SQLITE_ARRAYS = {\n // SQLite uses JSON arrays\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw(\"json_array()\");\n return sql`json_array(${sql.join(items, \", \")})`;\n },\n\n value: sqliteJsonListValue,\n\n // Deliberately the same container, by identity: SQLite stores an enum LIST\n // as JSON like every other list, so its members are ordinary JSON strings\n // and there is no element type to spell. The `TEXT CHECK(col IN ...)`\n // describes one member.\n enumValue: sqliteJsonListValue,\n\n // Check if value exists in JSON array using json_each\n has: (column: Sql, value: Sql): Sql =>\n sql`EXISTS (SELECT 1 FROM json_each(${column}) WHERE value = ${value})`,\n\n hasEvery: (column: Sql, values: Sql): Sql =>\n sql`(SELECT COUNT(*) FROM json_each(${values}) WHERE value IN (SELECT value FROM json_each(${column}))) = json_array_length(${values})`,\n\n hasSome: (column: Sql, values: Sql): Sql =>\n sql`EXISTS (SELECT 1 FROM json_each(${column}) AS a, json_each(${values}) AS b WHERE a.value = b.value)`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(json_array_length(${column}) = 0 OR ${column} IS NULL)`,\n\n // The column already stores the container as TEXT (its declared type is\n // TEXT, not JSON, precisely so the descriptor's CHECK can hold it). The\n // cast is what stops a JSON carrier from embedding it as a document and a\n // driver from handing back anything but the stored bytes.\n exactNumericProjection: (column: Sql): Sql => sql`CAST(${column} AS TEXT)`,\n\n length: (column: Sql): Sql => sql`json_array_length(${column})`,\n\n get: (column: Sql, index: Sql): Sql =>\n sql`json_extract(${column}, '$[' || ${index} || ']')`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`json_insert(${column}, '$[#]', ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`json_set(${column}, '$[' || ${index} || ']', ${value})`,\n};\n\nconst SQLITE_ORDER_BY = {\n ...createDirectionOrderBy(),\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS FIRST`\n : sql`${column} ASC NULLS FIRST`,\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS LAST`\n : sql`${column} ASC NULLS LAST`,\n};\n\nconst SQLITE_SET = {\n ...createNumericSetOperations(),\n\n // `x * y / 10^s` in coefficient space, rounded half to even. The guard is\n // the multiply's own: `x * y` is the only intermediate here that can leave\n // int64, and it does so exactly when the result cannot fit the field.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n const descriptor = target?.decimal;\n if (!descriptor) return sql`${column} = ${column} * ${by}`;\n return guardedCoefficientAssignment(\n column,\n sql`${by} = 0 OR ABS(${column}) <= ${SQLITE_INTERMEDIATE_LIMIT} / ABS(${by})`,\n halfEvenQuotient(\n SQLITE_INTEGERS,\n sql`(${column} * ${by})`,\n scaleFactorSql(descriptor.scale)\n ),\n descriptor\n );\n },\n\n // `x * 10^s / y` in coefficient space, rounded half to even; the divisor's\n // sign moves onto the numerator so the rule always sees a positive divisor.\n // `y` is never zero — division by canonical zero is refused before I/O.\n //\n // SQLite drivers bind JS numbers as REAL, so `col / ?` runs real division\n // and would persist a fractional value into an INTEGER column. Casting the\n // divisor to INTEGER makes it native INT/INT division (truncating toward\n // zero, matching Postgres) for integer columns; real columns keep real\n // division since the column itself carries REAL affinity.\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n const descriptor = target?.decimal;\n if (descriptor) {\n const factor = scaleFactorSql(descriptor.scale);\n return guardedCoefficientAssignment(\n column,\n sql`ABS(${column}) <= ${SQLITE_INTERMEDIATE_LIMIT} / ${factor}`,\n halfEvenQuotient(\n SQLITE_INTEGERS,\n signedNumerator(sql`(${column} * ${factor})`, by),\n sql`ABS(${by})`\n ),\n descriptor\n );\n }\n return target?.integer\n ? sql`${column} = ${column} / CAST(${by} AS INTEGER)`\n : sql`${column} = ${column} / ${by}`;\n },\n\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = ${jsonArrayConcat(\n sql`json(COALESCE(${column}, '[]'))`,\n values\n )}`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = ${jsonArrayConcat(\n values,\n sql`json(COALESCE(${column}, '[]'))`\n )}`,\n};\n\nconst SQLITE_MUTATIONS = {\n skipDuplicatesStrategy: \"sql\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql => sql`INSERT INTO ${table} DEFAULT VALUES`,\n\n ...createMutationCommands(),\n\n // SQLite 3.35+ supports RETURNING\n returning: (columns: Sql): Sql => sql`RETURNING ${columns}`,\n\n // SQLite uses same ON CONFLICT syntax as PostgreSQL (3.24+/3.35+)\n ...createOnConflictBuilders(),\n};\n\nconst SQLITE_ASSERTIONS = {\n exists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN EXISTS (${query}) THEN 1 ELSE json_extract('x', '$') END AS \"__viborm_assert__\"`,\n notExists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE json_extract('x', '$') END AS \"__viborm_assert__\"`,\n // The refusal names its sentinel (`bad JSON path: '__viborm_refused__'`).\n holds: (condition: Sql, from?: Sql): Sql =>\n sql`SELECT CASE WHEN ${condition} THEN 1 ELSE json_extract('{}', '__viborm_refused__') END AS \"__viborm_judged__\"${from ? sql` FROM ${from}` : sql``}`,\n};\n\nconst SQLITE_JOINS = {\n ...createCoreJoins(),\n\n // SQLite doesn't support RIGHT JOIN (before 3.39, and driver support varies).\n // Never silently downgrade: emitting LEFT JOIN without swapping operands\n // returns wrong rows. The query engine never calls this today.\n right: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\n \"SQLite does not support RIGHT JOIN. Restructure the query with joins.left and swapped operands.\"\n );\n },\n\n // SQLite doesn't support FULL OUTER JOIN (before 3.39, and driver support varies).\n full: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\n \"SQLite does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.\"\n );\n },\n\n // SQLite does NOT support LATERAL joins\n // These methods should never be called - query engine should check capability first\n lateral: (_subquery: Sql, _alias: string): Sql => {\n throw new Error(\n \"SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.\"\n );\n },\n\n lateralLeft: (_subquery: Sql, _alias: string): Sql => {\n throw new Error(\n \"SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.\"\n );\n },\n};\n\nconst SQLITE_CAPABILITIES = {\n supportsReturning: true, // SQLite 3.35+\n // FALSE IN FACT, and it read `true` until the Phase 8 fold gave the flag its\n // first reader (query-performance-plan Phase 10.1). SQLite's `WITH` grammar\n // admits a SELECT and nothing else: measured on SQLite 3.51.2, each of\n // `WITH x AS (UPDATE …/INSERT …/DELETE … RETURNING …) SELECT * FROM x` is a\n // parse error (`near \"UPDATE\": syntax error`). Kept as a capability rather\n // than deleted because Phase 8's `WITH u AS (UPDATE … RETURNING *) SELECT …`\n // fold reads it to decide whether it may emit at all.\n supportsCteWithMutations: false,\n supportsFullOuterJoin: false,\n supportsLateralJoins: false, // SQLite does not support LATERAL joins\n supportsVector: false,\n supportsUpsertWhere: true, // SQLite supports WHERE in ON CONFLICT (3.24+)\n supportsTargetedUpsert: true, // ON CONFLICT (cols) arbitrates on those cols\n supportsMutationTargetInSubquery: true,\n // UPDATE/DELETE ... LIMIT needs SQLITE_ENABLE_UPDATE_DELETE_LIMIT, which is\n // off in the builds this project targets (better-sqlite3, libSQL, D1).\n supportsMutationRowLimit: false,\n supportsRowLocks: false,\n joinsJunctionFilters: true,\n};\n\nconst SQLITE_RESULT: AdapterResultParser = {\n // SQLite has no exact decimal type: a decimal column IS its unscaled\n // integer coefficient, and every projection casts it to text before a\n // driver turns an int64 into a double. The result boundary cannot tell the\n // two vocabularies apart by inspection, so the promise is declared here.\n decimalRepresentation: \"coefficient\",\n\n // A decimal LIST is TEXT holding a JSON array of those same coefficients,\n // stated separately because the two facts are separate: a dialect can spell\n // its scalar decimals exactly and still have no exact decimal inside JSON.\n decimalListRepresentation: \"coefficient\",\n\n // The same reading the `dateTime` literal above lowers through, so a column\n // is read back in the vocabulary it was written in.\n dateTimeRepresentation: sqliteDateTimePhysicalForm,\n\n // Derived from the ONE storage owner, so the column the migration creates\n // and the value this reads back cannot be two decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"sqlite\")?.representation ?? \"text\",\n\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n\n parseField: (\n _value: unknown,\n _scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n};\n\nconst SQLITE_IDENTIFIERS = createIdentifiers(quoteIdent);\n\nconst SQLITE_CLAUSES = createStandardClauses();\n\nconst SQLITE_FILTERS = createRelationFilters();\n\nconst SQLITE_SUBQUERIES = createSubqueries(quoteIdent);\n\n// A member is written once and inlined at every use: one a nested body reads\n// is compiled again inside each use of that body, so it is materialized.\nconst SQLITE_CTE = createCteBuilders(quoteIdent, {\n materializing: sql.raw(\"MATERIALIZED\"),\n});\n\n/**\n * A multi-row `VALUES` is the one compound SQLite does not count against\n * `SQLITE_MAX_COMPOUND_SELECT` (500 terms; measured on 3.53.2: 500 `UNION\n * ALL SELECT` arms refused, 10,922 `VALUES` rows read), so the produced rows\n * follow their typed head as one: the head's columns still type every row,\n * as an arm's did (affinity and collation measured equal).\n */\nconst SQLITE_SET_OPERATIONS = createSetOperations(\n quoteIdent,\n (typed, rows, alias) =>\n sql`(${typed.head} UNION ALL VALUES ${sql.join(rows.map(rowValues), \", \")}) AS ${sql.raw(quoteIdent(alias))}`\n);\n\nconst SQLITE_RAW = createRawSql();\n\n/**\n * `and` nesting its members as a balanced tree, about log2(n) levels for n\n * members, where `and` itself nests one level per member.\n */\nfunction balancedConjunction(\n and: (...conditions: Sql[]) => Sql\n): (...conditions: Sql[]) => Sql {\n const balanced = (...conditions: Sql[]): Sql => {\n if (conditions.length <= 2) return and(...conditions);\n const middle = Math.floor(conditions.length / 2);\n return and(\n balanced(...conditions.slice(0, middle)),\n balanced(...conditions.slice(middle))\n );\n };\n return balanced;\n}\n\nexport class SQLiteAdapter implements DatabaseAdapter {\n constructor({\n temporaryObjects = true,\n deepExpressions = true,\n sharedRelationBodies = false,\n compoundSelectTerms,\n relationsPerStatement,\n countsCascadedChanges,\n }: SQLiteAdapterOptions = {}) {\n installGeoPointSql(this, this.geoPoint);\n if (!deepExpressions) {\n this.subqueries.existsCheck = (from, where) =>\n sql`SELECT 1 FROM (${SQLITE_SUBQUERIES.existsCheck(from, where)})`;\n // A derived table's `WHERE` is resolved on its own branch: a level's\n // row domain costs its height there, once, not at every level below.\n this.subqueries.isolated = (condition) =>\n sql`EXISTS (SELECT 1 FROM (SELECT 1 WHERE ${condition}))`;\n this.operators.and = balancedConjunction(SQLITE_OPERATORS.and);\n this.capabilities.boundsExpressionDepth = true;\n }\n if (sharedRelationBodies) this.capabilities.sharesRelationBodies = true;\n if (compoundSelectTerms !== undefined)\n this.capabilities.compoundSelectTerms = compoundSelectTerms;\n if (relationsPerStatement !== undefined)\n this.capabilities.relationsPerStatement = relationsPerStatement;\n if (countsCascadedChanges) this.capabilities.countsCascadedChanges = true;\n // Only batches read the reference-table SQL, so it is built on first use.\n let batchRefs: BatchReferenceSqlAdapter | undefined;\n const createBatchRefs = () => this.#createBatchRefs(temporaryObjects);\n installAdapterInternals(this, {\n get batchRefs() {\n batchRefs ??= createBatchRefs();\n return batchRefs;\n },\n constraints: sqliteConstraintIdentities,\n select: this.#assemble.select,\n });\n }\n\n raw = SQLITE_RAW;\n\n identifiers = { ...SQLITE_IDENTIFIERS };\n\n literals = { ...SQLITE_LITERALS };\n\n operators = { ...SQLITE_OPERATORS };\n\n expressions = { ...SQLITE_EXPRESSIONS };\n\n aggregates = { ...SQLITE_AGGREGATES };\n\n // SQLite 3.38+ JSON functions\n json = { ...SQLITE_JSON };\n\n arrays = { ...SQLITE_ARRAYS };\n\n // SQLite parses NULLS FIRST/LAST natively since 3.30 (2019-10-04), which is\n // below this adapter's documented 3.35+ floor. The `(col IS NULL)` emulation\n // this replaces was an extra leading sort key, and an index can never supply\n // a sort key that is an expression: on a 100,000-row table with an index over\n // the sort columns, the emulated spelling planned `SCAN t | USE TEMP B-TREE\n // FOR ORDER BY` at 3.356 ms per page and the native one plans `SCAN t USING\n // INDEX` at 0.005 ms. MySQL keeps the emulation — it has no native syntax at\n // any version.\n orderBy = { ...SQLITE_ORDER_BY };\n\n clauses = { ...SQLITE_CLAUSES };\n\n set = { ...SQLITE_SET };\n\n filters = { ...SQLITE_FILTERS };\n\n subqueries = { ...SQLITE_SUBQUERIES };\n\n // SQLite has no bare OFFSET; LIMIT -1 means \"no limit\"\n noLimitValue = sql.raw(\"-1\");\n\n readonly #assemble = {\n select: (parts: QueryParts): Sql => {\n // SQLite doesn't support DISTINCT ON natively\n // Simulate using ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)\n if (parts.distinct) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape,\n this.noLimitValue\n );\n }\n\n // SQLite uses database-level locking, so FOR UPDATE is a no-op\n // (ignoring parts.forUpdate intentionally)\n return assembleSelectQuery(sql`SELECT ${parts.columns}`, parts, {\n forUpdate: \"omit\",\n noLimitValue: this.noLimitValue,\n });\n },\n };\n\n cte = { ...SQLITE_CTE };\n\n mutations = { ...SQLITE_MUTATIONS };\n\n assertions = { ...SQLITE_ASSERTIONS };\n\n joins = { ...SQLITE_JOINS };\n\n setOperations = { ...SQLITE_SET_OPERATIONS };\n\n capabilities: DatabaseAdapter[\"capabilities\"] = { ...SQLITE_CAPABILITIES };\n\n lastInsertId = (): Sql => sql.raw(\"last_insert_rowid()\");\n\n // The scratch is a TEMP table wherever the transport admits one, so it never\n // enters the user's database file. Where it does not (D1), it is an ordinary\n // table in `main`: created once, kept, and EMPTY between batches — every\n // batch deletes the rows it stored, keyed by its own batch id, inside that\n // same batch, and a batch that fails rolls its rows back with it. The table\n // itself persists; SQLite migration introspection leaves it out of the\n // snapshot (`src/migrations/drivers/sqlite/introspect.ts`).\n #createBatchRefs(temporaryObjects: boolean): BatchReferenceSqlAdapter {\n const table = sql.raw(quoteIdent(BATCH_REFS_TABLE));\n const create = sql.raw(\n temporaryObjects\n ? \"CREATE TEMP TABLE IF NOT EXISTS\"\n : \"CREATE TABLE IF NOT EXISTS\"\n );\n return createOnConflictBatchRefs({\n table,\n batchIdColumn: sql.raw('\"batch_id\"'),\n keyColumn: sql.raw('\"ref_key\"'),\n valueColumn: sql.raw('\"ref_value\"'),\n createTable: sql`${create} ${table} (\"batch_id\" TEXT NOT NULL, \"ref_key\" TEXT NOT NULL, \"ref_value\" TEXT, PRIMARY KEY (\"batch_id\", \"ref_key\"))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS TEXT)`,\n lastInsertId: () => this.lastInsertId(),\n });\n }\n\n vector = unsupportedVector;\n\n readonly geoPoint: GeoPointSql = (() => {\n const longitude = (point: Sql): Sql =>\n this.json.numberAtPath(point, [\"longitude\"]);\n const latitude = (point: Sql): Sql =>\n this.json.numberAtPath(point, [\"latitude\"]);\n return {\n value: (pointLongitude, pointLatitude) =>\n sql`json_object('longitude', ${this.json.document(this.json.number(pointLongitude))}, 'latitude', ${this.json.document(this.json.number(pointLatitude))})`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators\n ),\n };\n })();\n\n result: AdapterResultParser = { ...SQLITE_RESULT };\n}\n"],"mappings":"u1BA0EA,MAAM,EAAa,EAAuB,IAAI,CASxC,EAA0C,CAC9C,UAAW,EAAQ,IAAgB,CAAG,IAAI,EAAE,KAAK,EAAE,GACnD,WAAY,EAAQ,IAAgB,CAAG,IAAI,EAAE,KAAK,EAAE,GACrD,CAMD,SAAS,uBAAuB,EAAyC,CACvE,IAAM,EAAY,GAA4B,EAAY,CAC1D,GAAI,EAAY,GAAI,OAAO,EACvB,OAAY,IAIhB,OAHmB,EAAY,WAAW,IAAI,CAC1C,EAAY,MAAM,EAAE,EAAI,sBACxB,GAAe,uBACC,EAAY,IAAA,GA4BlC,MAAM,EAA4BA,EAAI,IAAI,sBAAsB,CAqB1D,oBAAuB,GAC3BA,EAAI,IAAI,IAAI,IAAI,OAAO,KAAK,IAAI,EAAW,UAA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J,OAAS,EAET,cAAwC,CACtC,IAAM,UAAa,GACjB,KAAK,KAAK,aAAa,EAAO,CAAC,YAAY,CAAC,CACxC,SAAY,GAChB,KAAK,KAAK,aAAa,EAAO,CAAC,WAAW,CAAC,CAC7C,MAAO,CACL,OAAQ,EAAgB,IACtB,CAAG,4BAA4B,KAAK,KAAK,SAAS,KAAK,KAAK,OAAO,EAAe,CAAC,CAAC,gBAAgB,KAAK,KAAK,SAAS,KAAK,KAAK,OAAO,EAAc,CAAC,CAAC,GAC1J,UACA,SACA,GAAG,EACD,UACA,SACA,KAAK,UACN,CACF,IACC,CAEJ,OAA8B,CAAE,GAAG,GAAe"}
@@ -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, h as DriverResultParser, kn as TransactionOptionSupport, p as SqliteMigrationCapability, s as DatabaseAdapter, u as Driver } from "./index-oVv9RLt5.mjs";
1
+ import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, h as DriverResultParser, kn as TransactionOptionSupport, p as SqliteMigrationCapability, s as DatabaseAdapter, u as Driver } from "./index-Ci8b13Lm.mjs";
2
2
  import Database from "better-sqlite3";
3
3
 
4
4
  //#region src/drivers/sqlite3/index.d.ts
package/dist/sqlite3.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./normalized-result-BF7gr4_b.mjs";import{r as n}from"./validation-gwZYm3Yn.mjs";import{a as r,i,n as a,r as o}from"./client-DUulrWw5.mjs";import{c as s,n as c,r as l,t as u}from"./driver-DseQwbsu.mjs";import{a as d,c as f,i as p,l as m,n as h,o as g,s as _,t as v}from"./sqlite-utils-C5_KQPZn.mjs";import{t as y}from"./sqlite-adapter-B3dRr5fl.mjs";import{Buffer as b}from"node:buffer";import x from"better-sqlite3";const S=new WeakMap,C=x.prototype.prepare;function cachedStatement(e,t,n){if(e.prepare!==C)return e.prepare(t);let r=S.get(e);r||(r=[new Map,new Map],S.set(e,r));let i=r[n?0:1],a=i.get(t);return a===void 0?(a=e.prepare(t),i.size===100&&i.delete(i.keys().next().value)):i.delete(t),i.set(t,a),a}function convertValuesForSQLite3(e){return e.map(e=>{let t=h(e);if(b.isBuffer(t)||!p(t))return t;let n=f(t);return b.from(n.buffer,n.byteOffset,n.byteLength)})}const w={client:!0,dataDir:!0,options:!0};var T=class SQLite3Driver extends u{static canonicalExecuteEntry=SQLite3Driver.prototype._execute;static canonicalExecute=SQLite3Driver.prototype.execute;static canonicalRunStatement=SQLite3Driver.prototype.runStatement;static canonicalTypedStatement=SQLite3Driver.prototype.executeTypedStatement;static canonicalPositionalExecute=SQLite3Driver.prototype.executePositional;static canonicalNativePrepare=x.prototype.prepare;adapter=new y;maxBindParametersPerStatement=32766;result=m;sqliteMigrationCapability=c;serializeTransactions=!0;get numbersPlaceholders(){return!1}driverOptions;suppliedClient;canonicalAdapterParseResult=this.adapter.result.parseResult;canonicalAdapter=this.adapter;canonicalAdapterResult=this.adapter.result;canonicalAdapterParseField=this.adapter.result.parseField;canonicalAdapterParseRelation=this.adapter.result.parseRelation;constructor(e={}){if(super(`sqlite`,`sqlite3`),this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient){if(this.suppliedClient.pragma(`foreign_keys`,{simple:!0})!==1)throw new n(`A supplied SQLite database must enable PRAGMA foreign_keys = ON before wrapping.`,{meta:{driver:`sqlite3`}});this.client=this.suppliedClient,Object.defineProperty(this,`connectionQueue`,{value:l(this.suppliedClient)})}SQLite3Driver.isPositionalCandidate(this)&&r(this,(e,t)=>this.executePositional(e,t),SQLite3Driver.isPositionalCandidate)}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let e=this.driverOptions.dataDir??`:memory:`,t=this.driverOptions.options??{},n=new x(e,t);return n.pragma(`foreign_keys = ON`),t.timeout===void 0&&n.pragma(`busy_timeout = 5000`),n}async closeClient(e){e!==this.suppliedClient&&e.close()}async execute(e,t,n,r){let i=convertValuesForSQLite3(n);return this.runStatement(e,t,i,r?.model!==`$raw`)}async executeRaw(e,t,n){let r=n?convertValuesForSQLite3(n):void 0;return this.runStatement(e,t,r,!1)}async executePositional(e,n){let r,a=await this.executeTypedStatement(e,n,async(e,n,i,a)=>{let s={provider:this.driverName,operation:a.operation??`execute`};if(!SQLite3Driver.isPositionalProducer(this,e)){let r=await this.execute(e,n,i,a);return t(r,s),{kind:`borrowed`,result:r}}let c=convertValuesForSQLite3(i),l=cachedStatement(e,n,!0);if(!l.reader){let e={rows:[],rowCount:l.run(...c).changes};return t(e,s),{kind:`borrowed`,result:e}}r=e,l.safeIntegers(!0);let u=l.raw().all(...c),d=l.columns().map(e=>e.name);return o(u,d,s),{kind:`positional`,rows:u,columns:d}});return a.kind===`positional`&&!(r&&SQLite3Driver.isPositionalProducer(this,r))?{kind:`borrowed`,result:i(a)}:a}static isPositionalProducer(e,t){return SQLite3Driver.isPositionalCandidate(e)&&e.client===t}static isPositionalCandidate(e){return e instanceof SQLite3Driver?e.driverOptions.options?.nativeBinding===void 0&&SQLite3Driver.hasCanonicalProducerSurface(e)&&e.executeTypedStatement===SQLite3Driver.canonicalTypedStatement&&e.executePositional===SQLite3Driver.canonicalPositionalExecute&&e.result.parseField===g&&e.result.parseRelation===void 0&&e.result.parseResult===void 0&&e.adapter===e.canonicalAdapter&&e.adapter.result===e.canonicalAdapterResult&&e.adapter.result.parseField===e.canonicalAdapterParseField&&e.adapter.result.parseRelation===e.canonicalAdapterParseRelation&&(e.client===void 0||e.client===null||SQLite3Driver.isPositionalClient(e.client)):!1}static isPositionalClient(e){return Object.getPrototypeOf(e)===x.prototype&&!Object.hasOwn(e,`prepare`)&&Object.getOwnPropertyDescriptor(x.prototype,`prepare`)?.value===SQLite3Driver.canonicalNativePrepare}runStatement(e,t,n,r){let i=r?cachedStatement(e,t,!1):e.prepare(t);if(i.reader){i.safeIntegers(!0);let e=n?i.all(...n):i.all();return{rows:r?e:d(e),rowCount:e.length}}return{rows:[],rowCount:(n?i.run(...n):i.run()).changes}}static hasCanonicalProducerSurface(e){return Object.getPrototypeOf(e)===SQLite3Driver.prototype&&e._execute===SQLite3Driver.canonicalExecuteEntry&&e.execute===SQLite3Driver.canonicalExecute&&e.runStatement===SQLite3Driver.canonicalRunStatement&&e.result===m&&e.adapter.result.parseResult===e.canonicalAdapterParseResult}transactionOptionSupport(){return v}async transaction(e,t,n){return _(e,t,n)}};function createClient(e){s(e,`sqlite3`,w,{databaseUrl:`pass the database file as dataDir`});let{client:t,dataDir:n,options:r}=e;return a(e,new T({client:t,dataDir:n,options:r}))}export{T as SQLite3Driver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./normalized-result-BF7gr4_b.mjs";import{r as n}from"./validation-gwZYm3Yn.mjs";import{a as r,i,n as a,r as o}from"./client-DACEO6tS.mjs";import{c as s,n as c,r as l,t as u}from"./driver-DseQwbsu.mjs";import{a as d,c as f,i as p,l as m,n as h,o as g,s as _,t as v}from"./sqlite-utils-C5_KQPZn.mjs";import{t as y}from"./sqlite-adapter-CLWY4B8w.mjs";import{Buffer as b}from"node:buffer";import x from"better-sqlite3";const S=new WeakMap,C=x.prototype.prepare;function cachedStatement(e,t,n){if(e.prepare!==C)return e.prepare(t);let r=S.get(e);r||(r=[new Map,new Map],S.set(e,r));let i=r[n?0:1],a=i.get(t);return a===void 0?(a=e.prepare(t),i.size===100&&i.delete(i.keys().next().value)):i.delete(t),i.set(t,a),a}function convertValuesForSQLite3(e){return e.map(e=>{let t=h(e);if(b.isBuffer(t)||!p(t))return t;let n=f(t);return b.from(n.buffer,n.byteOffset,n.byteLength)})}const w={client:!0,dataDir:!0,options:!0};var T=class SQLite3Driver extends u{static canonicalExecuteEntry=SQLite3Driver.prototype._execute;static canonicalExecute=SQLite3Driver.prototype.execute;static canonicalRunStatement=SQLite3Driver.prototype.runStatement;static canonicalTypedStatement=SQLite3Driver.prototype.executeTypedStatement;static canonicalPositionalExecute=SQLite3Driver.prototype.executePositional;static canonicalNativePrepare=x.prototype.prepare;adapter=new y;maxBindParametersPerStatement=32766;result=m;sqliteMigrationCapability=c;serializeTransactions=!0;get numbersPlaceholders(){return!1}driverOptions;suppliedClient;canonicalAdapterParseResult=this.adapter.result.parseResult;canonicalAdapter=this.adapter;canonicalAdapterResult=this.adapter.result;canonicalAdapterParseField=this.adapter.result.parseField;canonicalAdapterParseRelation=this.adapter.result.parseRelation;constructor(e={}){if(super(`sqlite`,`sqlite3`),this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient){if(this.suppliedClient.pragma(`foreign_keys`,{simple:!0})!==1)throw new n(`A supplied SQLite database must enable PRAGMA foreign_keys = ON before wrapping.`,{meta:{driver:`sqlite3`}});this.client=this.suppliedClient,Object.defineProperty(this,`connectionQueue`,{value:l(this.suppliedClient)})}SQLite3Driver.isPositionalCandidate(this)&&r(this,(e,t)=>this.executePositional(e,t),SQLite3Driver.isPositionalCandidate)}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let e=this.driverOptions.dataDir??`:memory:`,t=this.driverOptions.options??{},n=new x(e,t);return n.pragma(`foreign_keys = ON`),t.timeout===void 0&&n.pragma(`busy_timeout = 5000`),n}async closeClient(e){e!==this.suppliedClient&&e.close()}async execute(e,t,n,r){let i=convertValuesForSQLite3(n);return this.runStatement(e,t,i,r?.model!==`$raw`)}async executeRaw(e,t,n){let r=n?convertValuesForSQLite3(n):void 0;return this.runStatement(e,t,r,!1)}async executePositional(e,n){let r,a=await this.executeTypedStatement(e,n,async(e,n,i,a)=>{let s={provider:this.driverName,operation:a.operation??`execute`};if(!SQLite3Driver.isPositionalProducer(this,e)){let r=await this.execute(e,n,i,a);return t(r,s),{kind:`borrowed`,result:r}}let c=convertValuesForSQLite3(i),l=cachedStatement(e,n,!0);if(!l.reader){let e={rows:[],rowCount:l.run(...c).changes};return t(e,s),{kind:`borrowed`,result:e}}r=e,l.safeIntegers(!0);let u=l.raw().all(...c),d=l.columns().map(e=>e.name);return o(u,d,s),{kind:`positional`,rows:u,columns:d}});return a.kind===`positional`&&!(r&&SQLite3Driver.isPositionalProducer(this,r))?{kind:`borrowed`,result:i(a)}:a}static isPositionalProducer(e,t){return SQLite3Driver.isPositionalCandidate(e)&&e.client===t}static isPositionalCandidate(e){return e instanceof SQLite3Driver?e.driverOptions.options?.nativeBinding===void 0&&SQLite3Driver.hasCanonicalProducerSurface(e)&&e.executeTypedStatement===SQLite3Driver.canonicalTypedStatement&&e.executePositional===SQLite3Driver.canonicalPositionalExecute&&e.result.parseField===g&&e.result.parseRelation===void 0&&e.result.parseResult===void 0&&e.adapter===e.canonicalAdapter&&e.adapter.result===e.canonicalAdapterResult&&e.adapter.result.parseField===e.canonicalAdapterParseField&&e.adapter.result.parseRelation===e.canonicalAdapterParseRelation&&(e.client===void 0||e.client===null||SQLite3Driver.isPositionalClient(e.client)):!1}static isPositionalClient(e){return Object.getPrototypeOf(e)===x.prototype&&!Object.hasOwn(e,`prepare`)&&Object.getOwnPropertyDescriptor(x.prototype,`prepare`)?.value===SQLite3Driver.canonicalNativePrepare}runStatement(e,t,n,r){let i=r?cachedStatement(e,t,!1):e.prepare(t);if(i.reader){i.safeIntegers(!0);let e=n?i.all(...n):i.all();return{rows:r?e:d(e),rowCount:e.length}}return{rows:[],rowCount:(n?i.run(...n):i.run()).changes}}static hasCanonicalProducerSurface(e){return Object.getPrototypeOf(e)===SQLite3Driver.prototype&&e._execute===SQLite3Driver.canonicalExecuteEntry&&e.execute===SQLite3Driver.canonicalExecute&&e.runStatement===SQLite3Driver.canonicalRunStatement&&e.result===m&&e.adapter.result.parseResult===e.canonicalAdapterParseResult}transactionOptionSupport(){return v}async transaction(e,t,n){return _(e,t,n)}};function createClient(e){s(e,`sqlite3`,w,{databaseUrl:`pass the database file as dataDir`});let{client:t,dataDir:n,options:r}=e;return a(e,new T({client:t,dataDir:n,options:r}))}export{T as SQLite3Driver,createClient};
2
2
  //# sourceMappingURL=sqlite3.mjs.map
@@ -1,2 +1,2 @@
1
- import { $ as ModelOperationInput, Ar as BaseBlobSchema, Er as BaseEnumSchema, Fn as V, Fr as toJsonSchema, G as ParseResult, Gi as GeoPolygon, Gr as inferred, Hi as GeoArea, In as v, Ir as createSchemaRegistry, J as SchemaRegistryOperation, K as Prettify, Mr as BaseBigIntSchema, Or as BaseBooleanSchema, Pr as createJsonSchemaConverter, Q as ModelCoreSchemas, Sr as BaseIsoTimestampSchema, U as InferInput, Ui as GeoBounds, W as InferOutput, Wi as GeoPoint, Wr as JsonSchema, X as ModelArgsSchemas, Y as VibSchema, Z as ModelCoreInput, _r as InputJsonValue, at as CoreSchemas, br as BaseIsoDateSchema, dr as ObjectSchema, et as ModelRelationNestedInput, fr as BaseIntegerSchema, gr as BaseJsonSchema, it as ArgsSchemas, lr as BasePointSchema, nt as ModelStateSchemas, or as parse, pr as BaseNumberSchema, q as SchemaRegistryLookup, rt as ScalarSchemas, sr as BaseVectorSchema, tt as ModelSchemas, xr as BaseIsoTimeSchema, yr as JsonValue } from "./index-oVv9RLt5.mjs";
1
+ import { $ as ModelOperationInput, Ar as BaseBlobSchema, Er as BaseEnumSchema, Fn as V, Fr as toJsonSchema, G as ParseResult, Gi as GeoPolygon, Gr as inferred, Hi as GeoArea, In as v, Ir as createSchemaRegistry, J as SchemaRegistryOperation, K as Prettify, Mr as BaseBigIntSchema, Or as BaseBooleanSchema, Pr as createJsonSchemaConverter, Q as ModelCoreSchemas, Sr as BaseIsoTimestampSchema, U as InferInput, Ui as GeoBounds, W as InferOutput, Wi as GeoPoint, Wr as JsonSchema, X as ModelArgsSchemas, Y as VibSchema, Z as ModelCoreInput, _r as InputJsonValue, at as CoreSchemas, br as BaseIsoDateSchema, dr as ObjectSchema, et as ModelRelationNestedInput, fr as BaseIntegerSchema, gr as BaseJsonSchema, it as ArgsSchemas, lr as BasePointSchema, nt as ModelStateSchemas, or as parse, pr as BaseNumberSchema, q as SchemaRegistryLookup, rt as ScalarSchemas, sr as BaseVectorSchema, tt as ModelSchemas, xr as BaseIsoTimeSchema, yr as JsonValue } from "./index-Ci8b13Lm.mjs";
2
2
  export { type ArgsSchemas, type BaseBigIntSchema, type BaseBlobSchema, type BaseBooleanSchema, type BaseEnumSchema, type BaseIntegerSchema, type BaseIsoDateSchema, type BaseIsoTimeSchema, type BaseIsoTimestampSchema, type BaseJsonSchema, type BaseNumberSchema, type BasePointSchema, type BaseVectorSchema, type CoreSchemas, type GeoArea, type GeoBounds, type GeoPoint, type GeoPolygon, type InferInput, type InferOutput, type InputJsonValue, type JsonSchema, type JsonValue, type ModelArgsSchemas, type ModelCoreInput, type ModelCoreSchemas, type ModelOperationInput, type ModelRelationNestedInput, type ModelSchemas, type ModelStateSchemas, type ObjectSchema, type ParseResult, type Prettify, type ScalarSchemas, type SchemaRegistryLookup, type SchemaRegistryOperation, type V, type VibSchema, createJsonSchemaConverter, createSchemaRegistry, v as default, v, inferred, type inferred as inferredType, parse, toJsonSchema };
@@ -0,0 +1,2 @@
1
+ const e=`1.4.2`;export{e as t};
2
+ //# sourceMappingURL=version-DLtcW9kn.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"version-B9azgPiR.mjs","names":["packageMetadata.version"],"sources":["../package.json","../src/version.ts"],"sourcesContent":["","import packageMetadata from \"../package.json\";\n\n/** Package version shared by runtime surfaces and bundled from package.json. */\nexport const VIBORM_VERSION = packageMetadata.version;\n"],"mappings":"ACGA,MAAa"}
1
+ {"version":3,"file":"version-DLtcW9kn.mjs","names":["packageMetadata.version"],"sources":["../package.json","../src/version.ts"],"sourcesContent":["","import packageMetadata from \"../package.json\";\n\n/** Package version shared by runtime surfaces and bundled from package.json. */\nexport const VIBORM_VERSION = packageMetadata.version;\n"],"mappings":"ACGA,MAAa"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "viborm",
3
- "version": "1.4.1",
3
+ "version": "1.4.2",
4
4
  "description": "Type-safe ORM for PostgreSQL, MySQL, and SQLite with a Prisma-inspired API",
5
5
  "repository": {
6
6
  "type": "git",