@lunora/sql-store 1.0.0-alpha.222 → 1.0.0-alpha.224

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportSqlGlobalRows as l,importSqlGlobalRows as o,selectGlobalTables as r}from"./packem_shared/exportSqlGlobalRows-IxOHBsm_.mjs";import{createSqlCtxDb as s,readSqlCdcChangedTables as S,readSqlCdcChanges as n,readSqlCdcFloor as i,runSqlCdcMigration as d,sweepSqlCdcRetention as q}from"./packem_shared/createSqlCtxDb-J4itUFJ_.mjs";import{runSqlGlobalTableMigrations as b}from"./packem_shared/runSqlGlobalTableMigrations-C7teG_kd.mjs";import{runSqlAggregateMigrations as f,runSqlRankMigrations as g}from"./packem_shared/runSqlAggregateMigrations-5fjwAdYh.mjs";import{b as x,r as C}from"./packem_shared/ctx-db-search-D_0SkyeY.mjs";import{S as T,m as u}from"./packem_shared/ctx-db-search-state-C4l9QBq-.mjs";import{facetSqlGlobalColumn as h,listSqlGlobalTables as M,readSqlGlobalTablePage as w}from"./packem_shared/facetSqlGlobalColumn-f5GVnQn4.mjs";import{d as E,e as k,s as B,a as D,t as P}from"./packem_shared/value-codec-C52YW-Do.mjs";import{d as v}from"./packem_shared/sql-exec-CkHeSf_v.mjs";export{T as SEARCH_STATE_TABLE,x as backfillSqlSearchIndexes,s as createSqlCtxDb,E as decodeBigint,v as decodeGlobalRow,k as effectiveColumnKind,l as exportSqlGlobalRows,h as facetSqlGlobalColumn,o as importSqlGlobalRows,M as listSqlGlobalTables,u as migrateSearchState,S as readSqlCdcChangedTables,n as readSqlCdcChanges,i as readSqlCdcFloor,w as readSqlGlobalTablePage,f as runSqlAggregateMigrations,d as runSqlCdcMigration,b as runSqlGlobalTableMigrations,g as runSqlRankMigrations,C as runSqlSearchMigrations,r as selectGlobalTables,B as sqliteDecode,D as sqliteEncode,q as sweepSqlCdcRetention,P as tryJsonParse};
1
+ import{exportSqlGlobalRows as l,importSqlGlobalRows as o,selectGlobalTables as r}from"./packem_shared/exportSqlGlobalRows-IxOHBsm_.mjs";import{createSqlCtxDb as s,readSqlCdcChangedTables as S,readSqlCdcChanges as n,readSqlCdcFloor as i,runSqlCdcMigration as d,sweepSqlCdcRetention as q}from"./packem_shared/createSqlCtxDb-Dok-o1HT.mjs";import{runSqlGlobalTableMigrations as b}from"./packem_shared/runSqlGlobalTableMigrations-C7teG_kd.mjs";import{runSqlAggregateMigrations as f,runSqlRankMigrations as g}from"./packem_shared/runSqlAggregateMigrations-5fjwAdYh.mjs";import{b as x,r as C}from"./packem_shared/ctx-db-search-D_0SkyeY.mjs";import{S as T,m as u}from"./packem_shared/ctx-db-search-state-C4l9QBq-.mjs";import{facetSqlGlobalColumn as h,listSqlGlobalTables as M,readSqlGlobalTablePage as w}from"./packem_shared/facetSqlGlobalColumn-f5GVnQn4.mjs";import{d as E,e as k,s as B,a as D,t as P}from"./packem_shared/value-codec-C52YW-Do.mjs";import{d as v}from"./packem_shared/sql-exec-CkHeSf_v.mjs";export{T as SEARCH_STATE_TABLE,x as backfillSqlSearchIndexes,s as createSqlCtxDb,E as decodeBigint,v as decodeGlobalRow,k as effectiveColumnKind,l as exportSqlGlobalRows,h as facetSqlGlobalColumn,o as importSqlGlobalRows,M as listSqlGlobalTables,u as migrateSearchState,S as readSqlCdcChangedTables,n as readSqlCdcChanges,i as readSqlCdcFloor,w as readSqlGlobalTablePage,f as runSqlAggregateMigrations,d as runSqlCdcMigration,b as runSqlGlobalTableMigrations,g as runSqlRankMigrations,C as runSqlSearchMigrations,r as selectGlobalTables,B as sqliteDecode,D as sqliteEncode,q as sweepSqlCdcRetention,P as tryJsonParse};
@@ -0,0 +1,7 @@
1
+ import{LunoraError as g}from"@lunora/errors";import{m as yn,q as Rn}from"./ctx-db-search-state-C4l9QBq-.mjs";import{c as Sn,r as gn,A as mn,C as Tn,R as vn,u as In,a as An,T as Cn,x as Ln,d as bn}from"./ctx-db-search-D_0SkyeY.mjs";import{throwingScheduler as Nn,describeRelationWrites as Mn,CDC_LOG_TABLE as D,cdcForkedError as On,cursorBelowRetainedFloor as qn,cdcTrimmedError as kn,serverInList as Dn,assertNoExplicitUndefined as Ke,hasTrigger as Bn,runRowValidators as Ge,assertFlatPredicate as Et,mergeWhere as F,rankTableName as _e,sortColumnName as Re,resolveRankPartition as pt,encodePartitionKey as Me,resolveRankSeekTuple as Wn,RANK_TIEBREAK as Se,CountRlsUnsupportedError as yt,compileWhereSql as z,ConflictError as ae,patchDependsOnRow as Fn,normalizeIdStructurally as Un,applyInsertDefaults as xn,assertValidClientId as Pn,assertStorableRowId as Hn,aggregateSqlFunction as Ee,softDeleteScope as Oe,resolveWith as Rt,relationHooks as St,applySelect as gt,encodeCursor as jn,NotFoundError as Kn,applyOnDelete as Gn,normalizeCountArgument as Vn,selectIndexForCount as Yn,encodeAggregateKey as J,aggregateTableName as ie,selectIndexForAggregate as Xn,readAggregateValue as Ve,runTriggers as Qn,nullsOrderSuffix as mt,nullsFirstOf as Tt,rankPivotConditionSql as Ht,CURSOR_PREFIX as zn,resolvePatch as Jn,stripReservedPatchFields as Zn,assertPatchAllowed as ei,resolveRelationPredicates as ti,selectIndexForGroupBy as ni,composeReadPredicate as ii,fanOutScalarCounts as oi,whereOfFilter as ri,isPushableWhere as si,matchesRankStaticWhere as vt,tiebreakDirectionFor as ai,matchesStaticWhere as Ye,coerceAggregateNumber as Xe,foldAggregateTally as It,CDC_LOG_TABLE_SEQ_INDEX as ci,NotUniqueError as di,WORKERD_SQLITE_LIMITS as li}from"@lunora/shard-engine";import{parseWire as ui,needsWireEncoding as jt,encodeWire as Kt,decodeWire as fi}from"@lunora/wire";import{sql as e,SQL as wi}from"drizzle-orm";import{p as At,h as Ct,q as I,b as x,c as Gt,i as $i,j as hi,k as _i,l as X,s as oe,O as pe,e as U,m as Lt,t as Ei,a as pi,n as bt,o as Be,u as ot,v as Nt,w as yi,x as Qe,y as Mt,B as ze,z as Ot,g as qt}from"./sql-exec-CkHeSf_v.mjs";import{d as So}from"./sql-exec-CkHeSf_v.mjs";import{runSqlGlobalTableMigrations as Ri}from"./runSqlGlobalTableMigrations-C7teG_kd.mjs";import{runSqlAggregateMigrations as Si,runSqlRankMigrations as gi}from"./runSqlAggregateMigrations-5fjwAdYh.mjs";import{s as Vt,e as Yt}from"./value-codec-C52YW-Do.mjs";const mi=(r,a)=>{if(r.size<a)return;const u=r.keys().next().value;u!==void 0&&r.delete(u)},kt=50,Ti=(r,a={})=>{const u=a.maxBatch??kt,c=Number.isInteger(u)&&u>0?u:kt,R=new Map;let f=!1;const d=async(T,A)=>{const v=[...A.keys()];for(let L=0;L<v.length;L+=c){const b=v.slice(L,L+c);try{const q=await r(T,b);for(const K of b){const Q=q.get(K);for(const Z of A.get(K)??[])Z.resolve(Q)}}catch(q){for(const K of b)for(const Q of A.get(K)??[])Q.reject(q)}}},O=()=>{f=!1;const T=[...R.entries()];R.clear();for(const[A,v]of T)d(A,v).catch(()=>{})};return{async load(T,A){return new Promise((v,L)=>{let b=R.get(T);b||(b=new Map,R.set(T,b));const q=b.get(A);q?q.push({reject:L,resolve:v}):b.set(A,[{reject:L,resolve:v}]),f||(f=!0,queueMicrotask(O))})}}},vi=new Set(["_id","id"]),Ii=r=>{throw new g("INTERNAL",`no ORDER BY NULL placement for dialect "${String(r)}"`)},Xt=(r,a)=>{const u=a.direction==="desc"?"DESC":"ASC",c=a.nullable===!0,R=f=>e`${Be(r,a.field)} ${e.raw(`${u}${f}`)}`;switch(r.name){case"mysql":{const f=R("");return!c||a.nulls===void 0?[f]:[e`(${Be(r,a.field)} IS NULL) ${e.raw(a.nulls==="first"?"DESC":"ASC")}`,f]}case"postgres":return[R(c?mt(Tt(a)):"")];case"sqlite":return[R(c&&a.nulls!==void 0?mt(Tt(a)):"")];default:return Ii(r.name)}},Ai=(r,a)=>{const u=r.flatMap(c=>Xt(a,c));if(!r.some(c=>vi.has(c.field))){const c=ai(r);u.push(e`${U("id")} ${e.raw(c==="desc"?"DESC":"ASC")}`)}return e.join(u,e`, `)},Dt=50,Ci=r=>{const a=r.detail??r["QUERY PLAN"];return typeof a=="string"?a:Object.values(r).map(String).join(" | ")},Je=(r,a,u,c)=>{for(const[R,f]of Ei(r)){if(f.serverDefault){R in a&&(u[R]=f.serverDefault({auth:c}));continue}f.onUpdateFn&&!(R in a)&&(u[R]=f.onUpdateFn())}},Li=128,bi=()=>{const r=new Map;return{delete:a=>{r.delete(a)},get:a=>{const u=r.get(a);if(u!==void 0)return r.delete(a),r.set(a,u),u},set:(a,u)=>{r.has(a)?r.delete(a):mi(r,Li),r.set(a,u)}}},Qt=r=>r.shardMode===void 0||r.shardMode.kind==="global",Ni=async(r,a,u,c,R)=>{const f=R.get(c);if(f!==void 0)return f;const d=Object.entries(u.tables).filter(([,T])=>Qt(T)).map(([T])=>T),O=await Promise.all(d.map(async T=>({found:(await I(r,a,e`SELECT 1 FROM ${e.identifier(T)} WHERE ${e.identifier("id")} = ${c} LIMIT 1`)).length>0,tableName:T})));for(const T of O)if(T.found)return R.set(c,T.tableName),T.tableName},ce=r=>r==null?null:Number(r),Mi=(r,a,u)=>u.map(c=>{const R={};for(const f of a){const d=r.shape[f];R[f]=Vt(c[f]??null,d&&Yt(d))}return{key:R,value:ce(c.value)}}),Oi=(r,a,u)=>[...r.partitionBy??[],...r.sortBy.map(R=>R.field),...r.where?Object.keys(r.where):[]].every(R=>Mt(a,R)===Mt(u,R)),zt=r=>r.length===1?r[0]:e`(${e.join(r,e` AND `)})`,re=r=>e.join(r.map(a=>e`${e.identifier(a)}`),e`, `),de=r=>e.join(r.map(a=>e`${a}`),e`, `),Ze=(r,a)=>{if(r==="postgres"){for(const[u,c]of Object.entries(a))if(typeof c=="string"&&c.includes("\0"))throw new g("BAD_REQUEST",`"${u}" holds a NUL character (U+0000), which a Postgres text column cannot store`)}},We=r=>r instanceof ArrayBuffer?new Uint8Array(r):Array.isArray(r)?Uint8Array.from(r):r,qi=(r,a,u,c,R)=>{const f=[];for(let d=0;d<u.length+1;d+=1){const O=u[d],T=a.sortBy[d],A=d<u.length&&O!==void 0&&T!==void 0,v=T?.direction==="desc"?"desc":"asc",L=A?Ht(O,We(c[O]),v,!1):e`${e.identifier(Se)} < ${R}`;if(L===void 0)continue;const b=u.slice(0,d).map(q=>ot(r,e`${e.identifier(q)}`,We(c[q])));b.push(L),f.push(zt(b))}return f.length>0?e.join(f,e` OR `):e`1 = 0`},ki=(r,a,u)=>{if(u.length!==a.length)return;const c=[];for(const[R,f]of a.entries()){const d=Ht(f.column,We(u[R]),f.direction,!0);if(d===void 0)continue;const O=[];for(let T=0;T<R;T+=1){const A=a[T];A!==void 0&&O.push(ot(r,e`${e.identifier(A.column)}`,We(u[T])))}O.push(d),c.push(zt(O))}return c.length===0?e`(1 = 0)`:e`(${e.join(c,e` OR `)})`},Di=(r,a)=>{if(r.sortBy.length===0)throw new g("INTERNAL",`rankIndex "${r.name}" requires at least one "sortBy" column for stable pagination`);const u=[{column:"__partition__",direction:"asc",nullable:!1}];for(const[c,R]of r.sortBy.entries())u.push({column:a[c]??Re(c),direction:R.direction,nullable:!0});return u.push({column:Se,direction:"asc",nullable:!1}),u},Bi=async(r,a,u,c,R)=>{const d=[];for(let v=0;v<R.length;v+=50)d.push(R.slice(v,v+50));const O=await Promise.all(d.map(async v=>I(r,a,e`SELECT * FROM ${e.identifier(c)} WHERE ${e.identifier("id")} IN (${de(v)})`))),T=new Map;for(const v of O)for(const L of v)T.set(L.id,L);const A=[];for(const v of R){const L=X(u,T.get(v));L&&A.push(L)}return A},Wi=r=>{const a=r.map(f=>Vt(f,"bytes")),u=JSON.stringify(jt(a)?Kt(a):a),c=new TextEncoder().encode(u);let R="";for(const f of c)R+=String.fromCodePoint(f);return zn+btoa(R)},Jt=r=>{if(r===void 0)return!1;const a=Yt(r);return a==="any"||a==="bigint"||a==="from"||a==="union"},nt=(r,a,u)=>{if(Jt(r.shape[a]))throw new g("BAD_REQUEST",`${u}: "${a}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Fi=(r,a,u,c)=>{for(const R of u)nt(r,R,`groupBy(${a}, { by: [..."${R}"] })`);c.field!==void 0&&nt(r,c.field,`groupBy(${a}, { agg: { op: "${c.op}", field: "${c.field}" } })`)},it="__cdc_sweep",qe="__cdc_log_ts",Zt="global",Ui=6e4,xi=1e4,Pi=3e4;let Bt=0;const Hi=async(r,a)=>{const{autoincrementPrimaryKey:u,key:c,real:R,text:f}=a.companionTypes;await x(r,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(D)} (${e.identifier("seq")} ${e.raw(u)}, ${e.identifier("ts")} ${e.raw(R)} NOT NULL, ${e.identifier("table")} ${e.raw(c)} NOT NULL, ${e.identifier("id")} ${e.raw(c)} NOT NULL, ${e.identifier("op")} ${e.raw(c)} NOT NULL, ${e.identifier("doc")} ${e.raw(f)})`);const d=a.indexKeyPrefix?.("string");await Gt(r,a,{columns:e`${d===void 0?e`${e.identifier("table")}`:e`${e.identifier("table")}(${e.raw(String(d))})`}, ${e.identifier("seq")}`,name:ci,table:D,unique:!1}),await x(r,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(it)} (${e.identifier("id")} ${e.raw(c)} NOT NULL PRIMARY KEY, ${e.identifier("lease_until")} ${e.raw(R)} NOT NULL)`),await x(r,a,e`INSERT INTO ${e.identifier(it)} (${e.identifier("id")}, ${e.identifier("lease_until")}) VALUES (${Zt}, ${0}) ${a.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${e.identifier("id")} = ${e.identifier("id")}`:e`ON CONFLICT(${e.identifier("id")}) DO NOTHING`}`)},ji=async(r,a,u)=>{const c=e`UPDATE ${e.identifier(it)} SET ${e.identifier("lease_until")} = ${u+Ui} WHERE ${e.identifier("id")} = ${Zt} AND ${e.identifier("lease_until")} <= ${u}`;if(a.supportsReturning)return(await I(r,a,e`${c} RETURNING ${e.identifier("id")}`)).length>0;const R=await x(r,a,c);return(a.affectedRows?a.affectedRows(R??{rowsAffected:0}):0)>0},Ki=async(r,a,u,c)=>{if(!await ji(r,a,c))return;const R=c-u;let f=!0;try{const d=await $i(r,a,D,qe);d!=="valid"&&(d==="invalid"&&await hi(r,a,D,qe),await Gt(r,a,{columns:e`${e.identifier("ts")}`,concurrently:!0,name:qe,table:D,unique:!1}))}catch(d){f=!1,console.warn(`[@lunora/sql-store] changelog retention could not build "${qe}"; sweeping without it.`,d)}f&&(await I(r,a,e`SELECT 1 AS ${e.identifier("hit")} FROM ${e.identifier(D)} WHERE ${e.identifier("ts")} <= ${R} LIMIT 1`)).length===0||await x(r,a,e`
2
+ DELETE FROM ${e.identifier(D)} WHERE ${e.identifier("seq")} IN (
3
+ SELECT ${e.identifier("seq")} FROM (
4
+ SELECT ${e.identifier("seq")} FROM ${e.identifier(D)} WHERE +${e.identifier("ts")} <= ${R} ORDER BY ${e.identifier("seq")} ASC LIMIT ${e.raw(String(xi))}
5
+ ) AS ${e.identifier("expired")}
6
+ )
7
+ `)},en=async(r,a)=>{const u=await I(r,a,e`SELECT MIN(${e.identifier("seq")}) AS ${e.identifier("seq")} FROM ${e.identifier(D)}`),c=Number(u[0]?.seq??Number.NaN);return Number.isFinite(c)?c:void 0},Gi=async(r,a)=>{if(a.name!=="sqlite")return;const u=await I(r,a,e`SELECT ${e.identifier("seq")} AS ${e.identifier("seq")} FROM ${e.identifier("sqlite_sequence")} WHERE ${e.identifier("name")} = ${D}`),c=Number(u[0]?.seq??Number.NaN);return Number.isFinite(c)?c:0},Vi=r=>JSON.stringify(jt(r)?Kt(r):r),Yi=(r,a,u,c,R)=>e`INSERT INTO ${e.identifier(D)} (${e.identifier("ts")}, ${e.identifier("table")}, ${e.identifier("id")}, ${e.identifier("op")}, ${e.identifier("doc")}) VALUES (${r}, ${a}, ${u}, ${c}, ${R===void 0?null:Vi(R)})`,tn=1e4,Xi=1e3,Qi=(r,a,u)=>{let c=a;for(const[R,f]of r.entries()){const d=Number(f.seq);if(d>c+1&&Number(f.ts)>u)return r.slice(0,R);c=d}return r},Eo=async(r,a,u)=>{const c=a.sinceSeq??0,R=Math.max(1,Math.min(a.limit??1e3,1e4)),f=await en(r,u),d=await Gi(r,u);if(d!==void 0&&c>d)throw On(d,c,"global");if(f!==void 0&&qn(f,c))throw kn(f,c,"global");const O=await I(r,u,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(D)} WHERE seq > ${c} ORDER BY seq ASC LIMIT ${e.raw(String(R))}`),A=(u.name==="sqlite"?O:Qi(O,c,(a.now??Date.now())-tn)).map(v=>{const{doc:L}=v,b={id:String(v.id),op:String(v.op),seq:Number(v.seq),table:String(v.table),ts:Number(v.ts)};return typeof L=="string"?{...b,doc:ui(L)}:b});return{changes:A,cursor:A.at(-1)?.seq??c}},Wt=(r,a)=>{const u=e.identifier(D),c=e`(SELECT MIN(v.seq) FROM ${u} v WHERE v.seq > ${r} AND v.seq - 1 > ${r} AND v.ts > ${a} AND NOT EXISTS (SELECT 1 FROM ${u} p WHERE p.seq = v.seq - 1))`;return e`${c} AS ${e.identifier("gap")}, (SELECT MAX(q.seq) FROM ${u} q WHERE q.seq > ${r} AND q.seq < ${c}) AS ${e.identifier("below")}`},Ft=(r,a,u)=>{const c=Number(a?.gap??Number.NaN);if(!Number.isFinite(c))return r;const R=Number(a?.below??Number.NaN);return Math.min(r,Number.isFinite(R)?R:u)},zi=r=>{const a=e.identifier(D),u=e.identifier("table");return e`SELECT ${u}, seq FROM (WITH RECURSIVE "t"("name") AS (SELECT MIN(${u}) FROM ${a} UNION ALL SELECT (SELECT MIN(${u}) FROM ${a} WHERE ${u} > "t"."name") FROM "t" WHERE "t"."name" IS NOT NULL) SELECT "t"."name" AS ${u}, (SELECT MAX(seq) FROM ${a} WHERE ${u} = "t"."name" AND seq > ${r}) AS seq FROM "t" WHERE "t"."name" IS NOT NULL) WHERE seq IS NOT NULL ORDER BY ${u}`},Ji=async(r,a,u,c={})=>{const R=e.identifier(D),f=u.name!=="sqlite",d=(c.now??Date.now())-tn;if(c.cursorOnly){const L=e`GREATEST((SELECT MAX(seq) FROM ${R}) - ${e.raw(String(Xi))}, ${a})`,b=await I(r,u,e`SELECT MAX(seq) AS seq${f?e`, ${Wt(L,d)}`:e``} FROM ${R}`),q=Number(b[0]?.seq??a);return{cursor:Ft(Number.isFinite(q)?q:a,b[0],a),tables:[]}}const O=await I(r,u,f?e`SELECT ${e.identifier("table")} AS ${e.identifier("table")}, MAX(seq) AS seq, ${Wt(e`${a}`,d)} FROM ${R} WHERE seq > ${a} GROUP BY ${e.identifier("table")}`:zi(a));let T=a;const A=[];for(const L of O){const b=Number(L.seq);Number.isFinite(b)&&b>T&&(T=b),A.push(String(L.table))}T=Ft(T,O[0],a);const v=c.retained===!0?await en(r,u):void 0;return{cursor:T,tables:A,...v===void 0?{}:{floor:v}}},Zi=/string or blob too big/iu,eo=/row is too big/iu,to=(r,a)=>{const{code:u,errno:c}=a,R=a instanceof Error?a.message:"";switch(r.name){case"mysql":return c===1118||u==="ER_TOO_BIG_ROWSIZE"?"InnoDB's per-row ceiling — roughly 8 KB, half a 16 KB page, for the part of the row stored inline":void 0;case"postgres":return eo.test(R)?"the 8 KB heap page a tuple must fit once its wide columns have been TOASTed out":void 0;default:return Zi.test(R)?"the storage engine's per-row ceiling (2 MB on D1)":void 0}},no=(r,a,u)=>{const c=to(r,a);if(c!==void 0)throw new g("PAYLOAD_TOO_LARGE",`document is too large to store in "${u}": a single row cannot exceed ${c}. The limit is on the STORED bytes, which are UTF-8. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},et=16,Ut="__lunora_patch_if_match__",xt=(r,a,u)=>{throw r.isUniqueViolation(a)?new ae(`unique constraint violation on "${u}"`,"unique"):(no(r,a,u),a)},tt=new WeakMap,Pt=new WeakMap,ye="superseded",io=3e4,ke="__lunora_companion_fence",se=(r,a,u)=>JSON.stringify([r,a,u]),De=r=>JSON.stringify(r,(a,u)=>typeof u=="bigint"?`${String(u)}n`:u),oo=r=>{const a=Dn(r);return(u,c,R,f)=>c.some(d=>d instanceof wi)?_i(r,u,c,R):a(u,c,R,f)},po=r=>{const{crossShardCounter:a,crossShardReader:u,exec:c,maxRelationKeys:R,schema:f}=r,{dialect:d}=r,O={fieldRef:n=>Be(d,n),rangeTypeGuard:(n,t)=>yi(d,n,t),...d.name==="mysql"?{containsExpr:(n,t)=>{const i=At(n);return i===void 0?e`LOCATE(${t}, ${n}) > 0`:e`LOCATE(${Ct("mysql",t)}, ${i}) > 0`}}:{},...d.name==="postgres"?{containsExpr:(n,t)=>{const i=At(n);return i===void 0?e`strpos(${n}, ${t}) > 0`:e`strpos(${i}, ${Ct("postgres",t)}) > 0`}}:{},...d.name==="sqlite"?{}:{inList:oo(d.name)}},T=new WeakMap,A=n=>{const t=T.get(n);if(t!==void 0)return t;const i={...O,serialize:(o,s)=>Nt(d,s,o,l=>oe(n,s,l))};return T.set(n,i),i},v=(n,t)=>ot(d.name,n,t),L=n=>{const t=re(n.columns),i=de(n.values),o=$=>d.name==="mysql"?e`VALUES(${e.identifier($)})`:e`excluded.${e.identifier($)}`,s=$=>d.name==="postgres"?e`${e.identifier(n.table)}.${e.identifier($)}`:e`${e.identifier($)}`,l=e.join(Object.entries(n.set(o,s)).map(([$,h])=>e`${e.identifier($)} = ${h}`),e`, `),p=d.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${l}`:e`ON CONFLICT(${e.identifier(n.conflictKey)}) DO UPDATE SET ${l}`;return e`INSERT INTO ${e.identifier(n.table)} (${t}) VALUES (${i}) ${p}`},b=r.clock??(()=>Date.now()),q=r.idGenerator??(()=>crypto.randomUUID()),K=r.cdc??!1,Q=typeof r.cdcRetentionMs=="number"&&Number.isFinite(r.cdcRetentionMs)&&r.cdcRetentionMs>0?r.cdcRetentionMs:void 0,Z=r.auth??{identity:null,userId:null},le=(n,t,i,o)=>K?[Yi(b(),n,t,i,o)]:[],nn=async()=>{if(!K||Q===void 0)return;const n=b();if(!(n-Bt<Pi)){Bt=n;try{await Ki(c,d,Q,n)}catch{}}},on=r.scheduler??Nn,Fe=bi();let ge=0;const ue=r.provisionScope??{},B=async()=>{const n=tt.get(ue);if(n)return n;const t=(async()=>{await Ri(c,f,d),await Si(c,f,d),await gi(c,f,d),await yn(c,d),await gn(c,f,d),K&&await Hi(c,d)})().catch(i=>{throw tt.delete(ue),i});return tt.set(ue,t),t},me=async(n,t)=>{if(t!==void 0&&!Object.hasOwn(f.tables,t))throw new g("BAD_REQUEST",`ctx.db by-id write (table, id): "${t}" is not a table in this schema`);if(await B(),t===void 0)return Ni(c,d,f,n,Fe);const i=Object.hasOwn(f.tables,t)?f.tables[t]:void 0;return i!==void 0&&Qt(i)?t:void 0};let Te=Pt.get(ue);Te===void 0&&(Te=new Map,Pt.set(ue,Te));const P=Te,rt={},Ue=(n,t,i)=>{const o=(async()=>(await B(),await i(()=>P.get(n)?.run!==o)))(),s={definition:t,owner:rt,run:o,settled:!1};return o.then(()=>{s.settled=!0},()=>{P.get(n)===s&&P.delete(n)}).catch(()=>{}),P.set(n,s),o},st=async(n,t,i)=>{const o=P.get(n);if(o===void 0)return await Ue(n,t,i);const s=o.definition===t;if(s&&(o.settled||o.owner===rt))return await o.run;if(o.settled)return await Ue(n,t,i);let l;const p=new Promise(h=>{l=setTimeout(h,io,"stalled")}),$=await Promise.race([o.run,p]).finally(()=>{clearTimeout(l)});return $!=="stalled"&&s?$:P.get(n)===o?await Ue(n,t,i):await st(n,t,i)},xe=async(n,t,i)=>{const o=await st(n,t,i);return o===ye?await xe(n,t,i):o},at=async(n,t)=>{const i=P.get(n),o=i?.settled===!0&&i.definition===t?await i.run:void 0;if(typeof o=="boolean")return o;P.delete(n)},rn=n=>{const t=f.tables[n];for(const i of t?.aggregateIndexes??[])P.delete(se("aggregate",n,i.name));for(const i of t?.rankIndexes??[])P.delete(se("rank",n,i.name))},sn=async(n,t)=>{const i=ie(n,t);return(await I(c,d,d.tableExists(i))).length>0},ct=async n=>{const{key:t}=d.companionTypes,i=q();await x(c,d,e`CREATE TABLE IF NOT EXISTS ${e.identifier(ke)} (${e.identifier("name")} ${e.raw(t)} PRIMARY KEY, ${e.identifier("token")} ${e.raw(t)} NOT NULL)`),await x(c,d,L({columns:["name","token"],conflictKey:"name",set:s=>({token:s("token")}),table:ke,values:[n,i]}));const o=e`${e.identifier("name")} = ${n} AND ${e.identifier("token")} = ${i}`;return{guardedDelete:()=>e`DELETE FROM ${e.identifier(n)} WHERE EXISTS (SELECT 1 FROM ${e.identifier(ke)} WHERE ${o})`,guardedInsert:(s,l)=>e`INSERT INTO ${e.identifier(n)} (${re(s)}) SELECT ${de(l)} FROM ${e.identifier(ke)} WHERE ${o}`}},an=async(n,t,i)=>{const o=f.tables[n];if(!o||!await sn(n,t.name))return!1;const s=t.by??[],l=new Map;await Ot(c,d,o,n,_=>{if(t.where&&!Ye(_,t.where))return;const w=J(s,_);It(l,w,t,_)});const p=ie(n,t.name);if(i())return ye;const $=await ct(p);await x(c,d,$.guardedDelete());const h=[];for(const[_,w]of l)h.push($.guardedInsert(["__key__","__value__","__count__"],[_,w.value,w.count]));return i()||await qt(c,d,h),i()?ye:!0},ve=(n,t)=>xe(se("aggregate",n,t.name),De(t),i=>an(n,t,i)),cn=async(n,t,i,o)=>{const s=new Map;let l,p=!0;for(;p;){const $=l===void 0?o:[...o,e`${e.identifier("id")} > ${l}`],h=$.length>0?e` WHERE ${e.join($,e` AND `)}`:e``,_=await I(c,d,e`SELECT ${e.identifier("id")}, ${U(i.field??"")} FROM ${e.identifier(t)}${h} ORDER BY ${e.identifier("id")} ASC LIMIT ${e.raw(String(ze))}`);for(const w of Lt(n,_))It(s,"",i,w);l=_.at(-1)?.id,p=_.length===ze}return s.get("")?.value??null},dn=async(n,t,i)=>{const o=t.field??"",s=[],l=f.tables[n],p=(w,E)=>Nt(d,w,E,S=>l?oe(l,w,S):Qe(S));for(const w of t.by??[]){const E=p(w,i[w]??null);s.push(E===null?e`${U(w)} IS NULL`:e`${U(w)} = ${E}`)}for(const[w,E]of Object.entries(t.where??{})){const S=E!==null&&typeof E=="object"&&!Array.isArray(E)?E.eq:E,y=p(w,S),m=Be(d,w);s.push(y===null?e`${m} IS NULL`:e`${m} = ${y}`)}const $=s.length>0?e` WHERE ${e.join(s,e` AND `)}`:e``;if(l&&Jt(l.shape[o]))return cn(l,n,t,s);const h=Ee(t.op),_=await I(c,d,e`SELECT ${e.raw(h)}(${U(o)}) AS ${e.identifier("value")} FROM ${e.identifier(n)}${$}`);return ce(_[0]?.value)},ln=(n,t)=>e`DELETE FROM ${e.identifier(n)} WHERE ${e.identifier("__key__")} = ${t} AND ${e.identifier("__count__")} <= 0`,un=async(n,t,i,o)=>{const s=ie(n,t.name),{op:l}=t,p=t.field??"",$=i&&(!t.where||Ye(i,t.where))?i:void 0,h=o&&(!t.where||Ye(o,t.where))?o:void 0;if(!$&&!h)return[];if(l==="count"||l==="sum"||l==="avg"){const w=[],E=new Set;for(const[S,y]of[[$,-1],[h,1]]){if(!S)continue;const m=l==="count"?1:Xe(S[p]);if(m===void 0)continue;const N=J(t.by??[],S);E.add(N),w.push(L({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(C,M)=>({__count__:e`${M("__count__")} + ${C("__count__")}`,__value__:l==="count"?e`${M("__value__")} + ${C("__value__")}`:e`COALESCE(${M("__value__")}, 0) + ${C("__value__")}`}),table:s,values:[N,y*m,y]}))}for(const S of E)w.push(ln(s,S));return w}const _=[];if($){const w=J(t.by??[],$),E=Xe($[p]),y=(await I(c,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(s)} WHERE ${e.identifier("__key__")} = ${w}`))[0],m=ce(y?.value),N=(y?.count??0)-1;if(N<=0)_.push(e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__key__")} = ${w}`);else if(y&&E!==void 0&&m!==null&&E===m){const C=await dn(n,t,$);_.push(e`UPDATE ${e.identifier(s)} SET ${e.identifier("__value__")} = ${C}, ${e.identifier("__count__")} = ${N} WHERE ${e.identifier("__key__")} = ${w}`)}else _.push(e`UPDATE ${e.identifier(s)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${w}`)}if(h){const w=J(t.by??[],h),E=Xe(h[p]);if(E===void 0)_.push(L({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(S,y)=>({__count__:e`${y("__count__")} + 1`}),table:s,values:[w,null,1]}));else{const S=l==="min"?"MIN":"MAX";_.push(L({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(y,m)=>({__count__:e`${m("__count__")} + 1`,__value__:e`${e.raw(S)}(COALESCE(${m("__value__")}, ${y("__value__")}), ${y("__value__")})`}),table:s,values:[w,E,1]}))}}return _},Ie=async n=>{const t=f.tables[n]?.aggregateIndexes;if(!(!t||t.length===0))for(const i of t)await ve(n,i)},fe=async(n,t,i)=>{const o=f.tables[n]?.aggregateIndexes,s=[];if(!o||o.length===0)return s;for(const l of o)await at(se("aggregate",n,l.name),De(l))&&s.push(...await un(n,l,t,i));return s},fn=async(n,t)=>{const i=_e(n,t);return(await I(c,d,d.tableExists(i))).length>0},wn=async(n,t,i)=>{const o=f.tables[n];if(!o||!await fn(n,t.name))return!1;const s=_e(n,t.name);if(i())return ye;const l=await ct(s);await x(c,d,l.guardedDelete());const $=["__id__","__partition__",...t.sortBy.map((w,E)=>Re(E))];let h=[];const _=async()=>{const w=h;h=[],!(w.length===0||i())&&await qt(c,d,w)};return await Ot(c,d,o,n,async w=>{if(t.where&&!vt(w,t.where))return;const E=Me(t.partitionBy??[],w),S=t.sortBy.map(y=>Qe(w[y.field]??null));h.push(l.guardedInsert($,[w._id,E,...S])),h.length>=ze&&await _()}),await _(),i()?ye:!0},Pe=(n,t)=>xe(se("rank",n,t.name),De(t),i=>wn(n,t,i)),Ae=async n=>{const t=f.tables[n]?.rankIndexes;if(!(!t||t.length===0))for(const i of t)await Pe(n,i)},ee=async(n,t,i,o)=>{const s=f.tables[n],l=s?.rankIndexes,p=[];if(!l||l.length===0)return p;const $=s?.softDeleteMode?.field,h=$===void 0||o===void 0?void 0:o[$],_=h!=null;for(const w of l){if(i!==void 0&&o!==void 0&&Oi(w,i,o)||!await at(se("rank",n,w.name),De(w)))continue;const S=_e(n,w.name);if(i&&p.push(e`DELETE FROM ${e.identifier(S)} WHERE ${e.identifier("__id__")} = ${t}`),o&&!_){if(w.where&&!vt(o,w.where))continue;const y=w.sortBy.map((M,W)=>Re(W)),m=re(["__id__","__partition__",...y]),N=Me(w.partitionBy??[],o),C=w.sortBy.map(M=>Qe(o[M.field]??null));p.push(e`INSERT INTO ${e.identifier(S)} (${m}) VALUES (${de([t,N,...C])})`)}}return p},te=async(n,t)=>{try{const i=await t();i.length>0&&await pi(c,d,i)}catch(i){throw rn(n),i}await nn()},we=Sn({dialect:d,exec:c,schema:f}),dt=new Set;for(const[n,t]of Object.entries(f.tables))for(const i of Object.values(t.triggerMap??{}))dt.add(`${n} ${i.timing} ${i.op}`);const G=(n,t,i)=>dt.has(`${n} ${t} ${i}`);let lt;const V=async(n,t,i)=>{if(ge+=1,ge>Dt)throw ge-=1,new ae(`trigger recursion exceeded ${String(Dt)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await Qn({ctx:lt,event:i,op:t,schema:f,tableName:i.table,timing:n})}finally{ge-=1}},$n=async(n,t)=>{try{await x(c,d,t)}catch(i){xt(d,i,n)}},Ce=async(n,t)=>(await I(c,d,e`SELECT * FROM ${e.identifier(n)} WHERE ${e.identifier("id")} = ${t}`))[0],ut=async(n,t,i,o,s)=>{const l=e`${e.identifier(pe)}`,p=e.join([v(e`${e.identifier("id")}`,o.id),v(l,o[pe]??null),...s===void 0?[]:[e`(${s})`]],e` AND `),$=t==="UPDATE"?e`UPDATE ${e.identifier(n)} SET ${i}, ${l} = ${bt.sql(l)} WHERE ${p}`:e`DELETE FROM ${e.identifier(n)} WHERE ${p}`;try{if(d.supportsReturning)return(await I(c,d,e`${$} RETURNING ${e.identifier("id")}`)).length>0;const h=await x(c,d,$);return(d.affectedRows?d.affectedRows(h??{rowsAffected:0}):0)>0}catch(h){return xt(d,h,n)}},He=async(n,t,i,o)=>{if(o!==void 0&&!await ut(n,t,i,o))throw new ae(`optimistic concurrency conflict on "${n}" — the row changed during this mutation; refetch and retry`,"occ")},je=(n,t=n?._creationTime)=>({_creationTime:t,[pe]:bt.value(n?.[pe])}),ft=async(n,t,i,o,s,l,p)=>{const $=X(t,s);if(!$||s===void 0)throw new g("INTERNAL",`document not found: ${i}`);const h=Jn(t,o,$),_={...$,...Zn(h),_id:i};Je(t,h,_,Z);const w=Ge(t,_,{only:new Set(Object.keys(h)),previous:()=>$,tolerateStoredNull:!0});Ze(d.name,Object.fromEntries(Object.keys(h).map(y=>[y,w[y]]))),ei(p,$,w),G(n,"before","update")&&await V("before","update",{doc:{...w},id:i,op:"update",previous:$,table:n}),await Ie(n),await Ae(n);const E=Object.keys(t.shape),S=e.join(E.map(y=>e`${e.identifier(y)} = ${oe(t,y,w[y]??null)}`),e`, `);if(await ut(n,"UPDATE",S,s,l))return await te(n,async()=>[...await fe(n,$,w),...await ee(n,i,$,w),...le(n,i,"update",w)]),await we(n,i,{document:w,previous:$,written:je(s)}),G(n,"after","update")&&await V("after","update",{doc:w,id:i,op:"update",previous:$,table:n}),w},hn=(n,t,i,o)=>{const s=Object.keys(n.shape);return{columns:["id","_creationTime",...s],values:[t,i,...s.map(l=>oe(n,l,o[l]??null))]}},_n=async(n,t,i,o)=>{const s=ni(t,i.op,i.field,o.by,o.where);if(!s||!await ve(n,s.index))return;const p=ie(n,s.index.name),$=Object.keys(s.partial);if($.length===(s.index.by??[]).length&&$.length>0){const _=J(s.index.by??[],s.partial),w=await I(c,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(p)} WHERE ${e.identifier("__key__")} = ${_}`);if(w.length===0)return[];const E=w[0];return[{key:{...s.partial},value:Ve(i.op,{count:E.count,value:ce(E.value)})}]}return $.length>0?void 0:(await I(c,d,e`SELECT ${e.identifier("__key__")} AS ${e.identifier("key")}, ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(p)}`)).map(_=>{const w=_;return{key:fi(JSON.parse(w.key)),value:Ve(i.op,{count:w.count,value:ce(w.value)})}})},wt=n=>{const t=f.tables[n]?.shardMode?.kind;return t==="shardBy"||t==="root"},$t=n=>{throw new g("INTERNAL",`cross-backend relation: a global table cannot load the shard-local relation '${n}' (it spans every shard) — wire a cross-shard reader to support it`)},En=(n,t)=>{if(t?.relationMask!==void 0&&t.with!==void 0&&Object.keys(t.with).length>0)throw new g("MASK_UNSUPPORTED",`masking cannot follow a nested \`with\` across the cross-shard relation hop to "${n}" — the nested rows are hydrated on the serving shard, where the mask policy does not exist. Read the nested relation at its own (masked) call site instead.`);const i={};if(t?.relationBaseWhere)for(const o of Object.keys(f.tables)){const s=t.relationBaseWhere(o);s!==void 0&&(i[o]=s)}return{orderBy:t?.orderBy,relationPolicies:i,where:F(t?.baseWhere,t?.where),with:t?.with}},Le=(n,t)=>wt(n)?u?u(n,En(n,t)):$t(n):H.findMany(n,t),be=(n,t,i)=>ti(n,{fetcher:Le,maxRelationKeys:R,relationBaseWhere:i,schema:f,tableName:t}),pn=Ti(async(n,t)=>{const i=await I(c,d,e`SELECT * FROM ${e.identifier(n)} WHERE ${e.identifier("id")} IN (${de(t)})`),o=new Map;for(const s of i){const{id:l}=s;typeof l=="string"&&o.set(l,s)}return o}),ht=async(n,t,i)=>{const{fetchLimit:o,limit:s,orderKeys:l,predicate:p}=await ii(t,i,{fetcher:Le,maxRelationKeys:R,schema:f,tableName:n}),$=z(p,A(t)),h=Ai(l,d);let _=e`SELECT * FROM ${e.identifier(n)}`;return $&&(_=e`${_} WHERE ${$}`),_=e`${_} ORDER BY ${h}`,o!==void 0&&(_=e`${_} LIMIT ${e.raw(String(o))}`),{limit:s,orderKeys:l,query:_}},H={relationWrites:Mn(f),async cdcChangedTables(n,t){if(K)try{return await B(),await Ji(c,n,d,{...t,now:b(),retained:Q!==void 0})}catch{return}},async aggregate(n,t){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);if(await B(),Ee(t.op),t.op==="count")return H.count(n,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new g("INTERNAL",`aggregate(${n}, { op: "${t.op}" }): "field" is required for non-count reducers`);const o=Oe(i.softDeleteMode,void 0),s=F(F(t.baseWhere,t.where),o),l=await be(s,n,t.relationBaseWhere),p=l!==s;if(i.aggregateIndexes&&!t.baseWhere&&!p&&!o){const S=Xn(i.aggregateIndexes,t.op,t.field,t.where);if(S&&await ve(n,S.index)){const m=J(S.index.by??[],S.key),N=ie(n,S.index.name),M=(await I(c,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(N)} WHERE ${e.identifier("__key__")} = ${m}`))[0];return Ve(t.op,M===void 0?void 0:{count:M.count,value:ce(M.value)})}}nt(i,t.field,`aggregate(${n}, { op: "${t.op}", field: "${t.field}" })`);const $=z(l,A(i)),h=e.raw(Ee(t.op)),_=e`SELECT ${h}(${U(t.field)}) AS ${e.identifier("value")} FROM ${e.identifier(n)}`,E=(await I(c,d,$?e`${_} WHERE ${$}`:_))[0]?.value;return E==null?null:Number(E)},async count(n,t){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);await B();const o=Vn(t);if(o.restrictsCounts)throw new yt(n);const s=Oe(i.softDeleteMode,void 0),l=F(F(o.baseWhere,o.where),s),p=await be(l,n,o.relationBaseWhere),$=p!==l;if(i.aggregateIndexes&&!o.baseWhere&&!$&&!s){const E=Yn(i.aggregateIndexes,o.where);if(E&&await ve(n,E.index)){const y=J(E.index.by??[],E.key),m=ie(n,E.index.name),N=await I(c,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")} FROM ${e.identifier(m)} WHERE ${e.identifier("__key__")} = ${y}`);return Number(N[0]?.value??0)}}const h=z(p,A(i)),_=e`SELECT COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(n)}`,w=await I(c,d,h?e`${_} WHERE ${h}`:_);return Number(w[0]?.count??0)},async delete(n,t,i){const o=await me(t,n);if(!o)return;const s=f.tables[o];if(!s)return;const l=await Ce(o,t);if(l===void 0)return;const p=X(s,l),$=i?.hard===!0,h=!$&&s.softDeleteMode?s.softDeleteMode.field:void 0;if(!(h&&(!p||p[h]!==null&&p[h]!==void 0))){if(G(o,"before","delete")&&await V("before","delete",{id:t,op:"delete",previous:p??void 0,table:o}),await Gn({deletedId:t,deletedReference:_=>p?.[_],findHolders:async(_,w,E,S)=>{if(f.tables[_]?.shardMode?.kind==="shardBy")throw new g("INTERNAL",`cross-backend cascade from global '${o}' into shardBy '${_}' is not supported — would require Query Coordinator fan-out across shards`);return(await H.findMany(_,{...S,includeDeleted:$,where:{[w]:E}})).page},onCascade:(_,w)=>H.delete(_,w,i),onRestrict:_=>{throw new ae(_,"restrict")},onSetNull:(_,w,E)=>H.patch(_,w,{[E]:null}),schema:f,tableName:o}),await Ie(o),await Ae(o),h&&p){const _={[h]:b()},w={...p,..._};Je(s,_,w,Z);const E=e.join(Object.keys(s.shape).map(S=>e`${e.identifier(S)} = ${oe(s,S,w[S]??null)}`),e`, `);await He(o,"UPDATE",E,l),await te(o,async()=>[...await fe(o,p,w),...await ee(o,t,p,void 0),...le(o,t,"update",w)]),await we(o,t,{document:w,previous:p,written:je(l)}),G(o,"after","delete")&&await V("after","delete",{id:t,op:"delete",previous:p,table:o});return}await He(o,"DELETE",void 0,l),Fe.delete(t),await te(o,async()=>[...await fe(o,p??void 0,void 0),...await ee(o,t,p??void 0,void 0),...le(o,t,"delete")]),await we(o,t,void 0),G(o,"after","delete")&&await V("after","delete",{id:t,op:"delete",previous:p??void 0,table:o})}},async findFirst(n,t={}){return(await H.findMany(n,{...t,limit:1})).page[0]??null},async findFirstOrThrow(n,t={}){const i=await H.findFirst(n,t);if(i===null)throw new Kn(`findFirstOrThrow: no "${n}" document matched`);return i},async findMany(n,t={}){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);await B();const o=async(S,y,m,N)=>{if(wt(S))return a?oi(a,S,y,m,N):$t(S);const C=f.tables[S];if(!C)throw new g("INTERNAL",`unknown table: ${S}`);const M=Oe(C.softDeleteMode,void 0),W={[y]:{in:m}},Y=F(F(W,N),M),$e=await be(Y,S,void 0),Ne=z($e,A(C)),he=U(y);let j=e`SELECT ${he} AS __fk__, COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(S)}`;Ne&&(j=e`${j} WHERE ${Ne}`),j=e`${j} GROUP BY ${he}`;const k=await I(c,d,j),ne=new Map;for(const _t of k)ne.set(_t.__fk__,Number(_t.count??0));return ne},{limit:s,orderKeys:l,query:p}=await ht(n,i,t),$=await I(c,d,p),h=Lt(i,$);if(s===void 0)return t.with&&await Rt({fetcher:Le,groupedCounter:o,parents:h,...St(t),schema:f,tableName:n,with:t.with}),{continueCursor:null,isDone:!0,page:gt(h,t.select,t.with)};const _=h.length>s,w=_?h.slice(0,s):h,E=w.at(-1);return t.with&&await Rt({fetcher:Le,groupedCounter:o,parents:w,...St(t),schema:f,tableName:n,with:t.with}),{continueCursor:_&&E?jn(E,l):null,isDone:!_,page:gt(w,t.select,t.with)}},async explain(n,t={}){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);await B();const{query:o}=await ht(n,i,t),s=d.name==="sqlite"?"EXPLAIN QUERY PLAN":"EXPLAIN",l=await I(c,d,e`${e.raw(s)} ${o}`),{params:p,sql:$}=d.render(o);return{params:p,plan:l.map(h=>Ci(h)),sql:$}},async get(n,t){const i=Object.hasOwn(f.tables,n)?f.tables[n]:void 0;if(!i)throw new g("BAD_REQUEST",`ctx.db.get(table, id): "${n}" is not a table in this schema`);return i.shardMode!==void 0&&i.shardMode.kind!=="global"?null:(await B(),X(i,await pn.load(n,t)))},async groupBy(n,t){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);await B();const o=t.agg??{op:"count"};if(Ee(o.op),o.op!=="count"&&!o.field)throw new g("INTERNAL",`groupBy(${n}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);const s=Oe(i.softDeleteMode,void 0),l=F(F(t.baseWhere,t.where),s),p=await be(l,n,t.relationBaseWhere),$=p!==l;if(i.aggregateIndexes&&!t.baseWhere&&!$&&!s){const y=await _n(n,i.aggregateIndexes,o,t);if(y!==void 0)return y}Fi(i,n,t.by,o);const h=z(p,A(i)),_=t.by.map(y=>e`${U(y)} AS ${e.identifier(y)}`);if(o.op==="count")_.push(e`COUNT(*) AS ${e.identifier("value")}`);else{if(!o.field)throw new g("INTERNAL",`groupBy(${n}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);_.push(e`${e.raw(Ee(o.op))}(${U(o.field)}) AS ${e.identifier("value")}`)}const w=e.join(t.by.map(y=>U(y)),e`, `);let E=e`SELECT ${e.join(_,e`, `)} FROM ${e.identifier(n)}`;h&&(E=e`${E} WHERE ${h}`),E=e`${E} GROUP BY ${w}`;const S=await I(c,d,E);return Mi(i,t.by,S)},async insert(n,t,i){const o=f.tables[n];if(!o)throw new g("INTERNAL",`unknown table: ${n}`);await B();const s=Ge(o,xn(o,t,Z),{supplied:t,trusted:i?.allowExplicitId===!0});Ze(d.name,s);let l,p=!0;i?.clientId!==void 0?(Pn(i.clientId),l=i.clientId):i?.allowExplicitId&&typeof s._id=="string"?(Hn(s._id),l=s._id):(l=q(),p=!1);const $=i?.allowExplicitId&&typeof s._creationTime=="number"?s._creationTime:b(),h={...s,_creationTime:$,_id:l};G(n,"before","insert")&&await V("before","insert",{doc:{...h},id:l,op:"insert",table:n}),await Ie(n),await Ae(n);const{columns:_,values:w}=hn(o,l,$,s);return await $n(n,e`INSERT INTO ${e.identifier(n)} (${re(_)}) VALUES (${de(w)})`),p&&Fe.set(l,n),await te(n,async()=>[...await fe(n,void 0,h),...await ee(n,l,void 0,h),...le(n,l,"insert",h)]),await we(n,l,{document:h,written:{_creationTime:$,[pe]:null}}),G(n,"after","insert")&&await V("after","insert",{doc:h,id:l,op:"insert",table:n}),l},normalizeId(n,t){return Un(f,n,t)},async patch(n,t,i,o){Ke("patch",i);const s=await me(t,n);if(!s)throw new g("INTERNAL",`document not found: ${t}`);const l=f.tables[s];if(!l)throw new g("INTERNAL",`document not found: ${t}`);const p=Fn(l,i)?et:1;for(let $=0;$<p;$+=1){const h=await Ce(s,t);if(await ft(s,l,t,i,h,void 0,o))return}throw new ae(`optimistic concurrency conflict on "${s}" — the row changed during this mutation; refetch and retry`,"occ")},async patchIf(n,t,i){Ke("patchIf",i.patch),await B();const o=f.tables[n];if(!o)throw new g("INTERNAL",`unknown table: ${n}`);const s=z(i.where,A(o))??e`1 = 1`;for(let l=0;l<et;l+=1){const[p]=await I(c,d,e`SELECT *, CASE WHEN (${s}) THEN 1 ELSE 0 END AS ${e.identifier(Ut)} FROM ${e.identifier(n)} WHERE ${e.identifier("id")} = ${t}`);if(p===void 0)return{applied:!1,doc:null};const{[Ut]:$,...h}=p;if(Number($)!==1)return{applied:!1,doc:X(o,h)??null};const _=await ft(n,o,t,i.patch,h,s,{verify:i.verify});if(_)return{applied:!0,doc:_}}throw new ae(`patchIf on "${n}" lost the row to concurrent writes ${String(et)} times in a row; retry the operation`,"occ")},async restore(n,t){const i=await me(t,n),o=i===void 0?void 0:await Ce(i,t);if(!i||o===void 0)throw new g("INTERNAL",`document not found: ${t}`);const s=f.tables[i],l=s?.softDeleteMode?.field;if(!s||!l)throw new g("INTERNAL",`ctx.db.restore: table "${i}" is not a .softDelete() table`);const p=o[l]!==null&&o[l]!==void 0;if(await H.patch(n,t,{[l]:null}),p){const $=X(s,o);$!==null&&await te(i,async()=>await ee(i,t,void 0,{...$,[l]:null}))}},query(n){const t=f.tables[n];if(!t)throw new g("INTERNAL",`unknown table: ${n}`);const i="the legacy query()/withIndex() reader is not available on the D1 (global) backend; use findMany",o=[];let s=0,l;const p=d.name!=="mysql",$={...A(t),fieldRef:E=>e`m.${U(E)}`,rangeTypeGuard:()=>{throw new g("INTERNAL","a path range is never pushed into a search")}},h=E=>o.every(S=>S(E)),_=async(E,S)=>{await B();const y=2*In+E.filters.length,m=l===void 0?void 0:z(l,$,void 0,y),N=m!==void 0&&d.name==="sqlite"&&d.render(m).params.length+y>li.boundParams,C=N?void 0:m,M=s>0||N,W=await An(c,d,t,n,C===void 0?E:{...E,scope:C},Cn(M?void 0:S));!M&&S===void 0&&Ln(W);const Y=W.filter($e=>h($e));return S===void 0?Y:Y.slice(0,S)},w=E=>{const S={async*[Symbol.asyncIterator](){if(!E)throw new g("INTERNAL",i);yield*await _(E,void 0)},async collect(){if(!E)throw new g("INTERNAL",i);return _(E,void 0)},async collectWithScores(){throw new g("GLOBAL_SEARCH_SCORES_UNSUPPORTED",`collectWithScores() is not supported on \`.global()\` tables (table "${n}") — relevance scores are not yet surfaced on this backend; use .collect() instead`)},filter(y){o.push(y);const m=ri(y);return m!==void 0&&si(m,t.shape,p)?l=F(l,m):s+=1,S},async first(){if(!E)throw new g("INTERNAL",i);return(await _(E,1))[0]??null},order(){return S},async paginate(y){if(!E)throw new g("INTERNAL",i);const m=Tn(y);return vn(await _(E,bn(m)),m)},async take(y){if(!E)throw new g("INTERNAL",i);return _(E,y)},async unique(){if(!E)throw new g("INTERNAL",i);const y=await _(E,2);if(y.length>1)throw new di(`unique() on table "${n}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(){throw new g("INTERNAL",`geo indexes are not supported on \`.global()\` tables (table "${n}") — geospatial queries run only on sharded tables`)},withIndex(){throw new g("INTERNAL",i)},withSearchIndex(y,m){const N=(t.searchIndexes??[]).find(M=>M.name===y);if(!N)throw new g("INTERNAL",`unknown search index "${y}" on table "${n}"`);const C={definition:N,field:N.field,filters:[],hasQuery:!1,indexName:y,query:""};if(m(mn(C,n,Rn(N.language))),!C.hasQuery)throw new g("INTERNAL",`search index "${y}" on table "${n}" requires a .search(field, query) call`);return w(C)}};return S};return w(void 0)},async rank(n,t,i){const o=f.tables[n];if(!o)throw new g("INTERNAL",`unknown table: ${n}`);const s=o.rankIndexes?.find(W=>W.name===t);if(!s)throw new g("INTERNAL",`unknown rankIndex "${t}" on table "${n}"`);if(i.restrictsCounts)throw new yt(n);if(await B(),!await Pe(n,s))return null;const p=typeof i.row=="string"?i.row:i.row._id;if(!p)return null;const $=_e(n,s.name),h=s.sortBy.map((W,Y)=>Re(Y)),_=re(["__partition__",...h]),E=(await I(c,d,e`SELECT ${_} FROM ${e.identifier($)} WHERE ${e.identifier("__id__")} = ${p}`))[0];if(!E)return null;const S=E.__partition__,y=F(i.baseWhere,i.where);Et(y,f,n,"rank");const m=pt(s,y);if(m&&Me(s.partitionBy??[],m)!==S)return null;const N=qi(d.name,s,h,E,p),C=await I(c,d,e`SELECT COUNT(*) AS c FROM ${e.identifier($)} WHERE ${e.identifier("__partition__")} = ${S} AND (${N})`),M=await I(c,d,e`SELECT COUNT(*) AS c FROM ${e.identifier($)} WHERE ${e.identifier("__partition__")} = ${S}`);return{position:Number(C[0]?.c??0)+1,total:Number(M[0]?.c??0)}},async rankPage(n,t,i={}){Et(F(i.baseWhere,i.where),f,n,"rankPage");const o=f.tables[n];if(!o)throw new g("INTERNAL",`unknown table: ${n}`);const s=o.rankIndexes?.find(k=>k.name===t);if(!s)throw new g("INTERNAL",`unknown rankIndex "${t}" on table "${n}"`);if(await B(),!await Pe(n,s))return{continueCursor:null,isDone:!0,page:[]};const p=_e(n,s.name),$=s.sortBy.map((k,ne)=>Re(ne)),h=Math.max(1,Math.min(1e3,Math.floor(i.take??100))),_=F(i.baseWhere,i.where),w=pt(s,_),E=Di(s,$),S=e.join(E.flatMap(k=>Xt(d,{direction:k.direction,field:k.column,nullable:k.nullable})),e`, `),y=[];typeof i.partitionKey=="string"?y.push(e`${e.identifier("__partition__")} = ${i.partitionKey}`):w&&y.push(e`${e.identifier("__partition__")} = ${Me(s.partitionBy??[],w)}`);const m=Wn(i);if(m!==void 0){const k=ki(d.name,E,m);k!==void 0&&y.push(k)}const N=re([Se,"__partition__",...$]);let C=e`SELECT ${N} FROM ${e.identifier(p)}`;y.length>0&&(C=e`${C} WHERE ${e.join(y,e` AND `)}`),C=e`${C} ORDER BY ${S} LIMIT ${e.raw(String(h+1))}`;const M=await I(c,d,C),W=M.length>h,Y=W?M.slice(0,h):M,$e=Y.map(k=>k[Se]),Ne=await Bi(c,d,o,n,$e);let he=null;const j=Y.at(-1);if(W&&j!==void 0){const k=[j.__partition__,...$.map(ne=>j[ne]),j[Se]];he=Wi(k)}return{continueCursor:he,isDone:!W,page:Ne}},async replace(n,t,i,o){Ke("replace",i);const s=await me(t,n);if(!s)throw new g("INTERNAL",`document not found: ${t}`);const l=f.tables[s];if(!l)throw new g("INTERNAL",`document not found: ${t}`);const p=await Ce(s,t);if(p===void 0)throw new g("INTERNAL",`document not found: ${t}`);const h=Bn(f,s,"update")||(l.aggregateIndexes??[]).length>0||(l.rankIndexes??[]).length>0?X(l,p)??void 0:void 0,_=o?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,w=typeof p._creationTime=="number"?p._creationTime:void 0,E=_??w??b(),S={...i,_creationTime:E,_id:t};Je(l,i,S,Z);const y=Ge(l,S,{previous:()=>h??X(l,p)??void 0,supplied:i,trusted:o?.allowExplicitId===!0});Ze(d.name,y),G(s,"before","update")&&await V("before","update",{doc:{...y},id:t,op:"update",previous:h,table:s}),await Ie(s),await Ae(s);const m=Object.keys(l.shape),N=e.join([e`${e.identifier("_creationTime")} = ${E}`,...m.map(C=>e`${e.identifier(C)} = ${oe(l,C,y[C]??null)}`)],e`, `);await He(s,"UPDATE",N,p),await te(s,async()=>[...await fe(s,h,y),...await ee(s,t,h,y),...le(s,t,"update",y)]),await we(s,t,{document:y,previous:h,written:je(p,E)}),G(s,"after","update")&&await V("after","update",{doc:y,id:t,op:"update",previous:h,table:s})}};return lt={db:H,scheduler:on},H};export{po as createSqlCtxDb,So as decodeGlobalRow,Ji as readSqlCdcChangedTables,Eo as readSqlCdcChanges,en as readSqlCdcFloor,Hi as runSqlCdcMigration,Ki as sweepSqlCdcRetention};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/sql-store",
3
- "version": "1.0.0-alpha.222",
3
+ "version": "1.0.0-alpha.224",
4
4
  "description": "Internal dialect-parameterized SQL store core for Lunora .global() backends (D1, PlanetScale)",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -50,9 +50,9 @@
50
50
  "access": "public"
51
51
  },
52
52
  "dependencies": {
53
- "@lunora/errors": ">=1.0.0-alpha.75 <2.0.0-0",
54
- "@lunora/shard-engine": "1.0.0-alpha.173",
55
- "@lunora/wire": "1.0.0-alpha.4",
53
+ "@lunora/errors": ">=1.0.0-alpha.77 <2.0.0-0",
54
+ "@lunora/shard-engine": "1.0.0-alpha.175",
55
+ "@lunora/wire": "1.0.0-alpha.5",
56
56
  "drizzle-orm": "1.0.0-rc.5"
57
57
  },
58
58
  "engines": {
@@ -1,7 +0,0 @@
1
- import{LunoraError as g}from"@lunora/errors";import{m as Rn,q as Sn}from"./ctx-db-search-state-C4l9QBq-.mjs";import{c as gn,r as mn,A as Tn,C as vn,R as In,u as An,a as Cn,T as Ln,x as bn,d as Nn}from"./ctx-db-search-D_0SkyeY.mjs";import{throwingScheduler as Mn,describeRelationWrites as On,CDC_LOG_TABLE as D,cdcForkedError as qn,cursorBelowRetainedFloor as kn,cdcTrimmedError as Dn,serverInList as Bn,assertNoExplicitUndefined as Ke,hasTrigger as Wn,runRowValidators as Ge,assertFlatPredicate as Et,mergeWhere as F,rankTableName as _e,sortColumnName as Re,resolveRankPartition as pt,encodePartitionKey as Me,resolveRankSeekTuple as Fn,RANK_TIEBREAK as Se,CountRlsUnsupportedError as yt,compileWhereSql as z,ConflictError as ae,patchDependsOnRow as Un,normalizeIdStructurally as xn,applyInsertDefaults as Pn,assertValidClientId as Hn,assertStorableRowId as jn,aggregateSqlFunction as Ee,softDeleteScope as Oe,resolveWith as Rt,relationHooks as St,applySelect as gt,encodeCursor as Kn,NotFoundError as Gn,applyOnDelete as Vn,normalizeCountArgument as Yn,selectIndexForCount as Xn,encodeAggregateKey as J,aggregateTableName as ie,selectIndexForAggregate as Qn,readAggregateValue as Ve,runTriggers as zn,nullsOrderSuffix as mt,nullsFirstOf as Tt,rankPivotConditionSql as Ht,CURSOR_PREFIX as Jn,resolvePatch as Zn,stripReservedPatchFields as ei,assertPatchAllowed as ti,resolveRelationPredicates as ni,selectIndexForGroupBy as ii,composeReadPredicate as oi,fanOutScalarCounts as ri,whereOfFilter as si,isPushableWhere as ai,matchesRankStaticWhere as vt,tiebreakDirectionFor as ci,matchesStaticWhere as Ye,coerceAggregateNumber as Xe,foldAggregateTally as It,CDC_LOG_TABLE_SEQ_INDEX as di,NotUniqueError as li,WORKERD_SQLITE_LIMITS as ui}from"@lunora/shard-engine";import{decodeWire as jt,needsWireEncoding as Kt,encodeWire as Gt}from"@lunora/wire";import{sql as e,SQL as fi}from"drizzle-orm";import{p as At,h as Ct,q as I,b as x,c as Vt,i as wi,j as $i,k as hi,l as X,s as oe,O as pe,e as U,m as Lt,t as _i,a as Ei,n as bt,o as Be,u as ot,v as Nt,w as pi,x as Qe,y as Mt,B as ze,z as Ot,g as qt}from"./sql-exec-CkHeSf_v.mjs";import{d as Ro}from"./sql-exec-CkHeSf_v.mjs";import{runSqlGlobalTableMigrations as yi}from"./runSqlGlobalTableMigrations-C7teG_kd.mjs";import{runSqlAggregateMigrations as Ri,runSqlRankMigrations as Si}from"./runSqlAggregateMigrations-5fjwAdYh.mjs";import{s as Yt,e as Xt}from"./value-codec-C52YW-Do.mjs";const gi=(r,a)=>{if(r.size<a)return;const u=r.keys().next().value;u!==void 0&&r.delete(u)},kt=50,mi=(r,a={})=>{const u=a.maxBatch??kt,c=Number.isInteger(u)&&u>0?u:kt,R=new Map;let f=!1;const d=async(T,A)=>{const v=[...A.keys()];for(let L=0;L<v.length;L+=c){const b=v.slice(L,L+c);try{const q=await r(T,b);for(const K of b){const Q=q.get(K);for(const Z of A.get(K)??[])Z.resolve(Q)}}catch(q){for(const K of b)for(const Q of A.get(K)??[])Q.reject(q)}}},O=()=>{f=!1;const T=[...R.entries()];R.clear();for(const[A,v]of T)d(A,v).catch(()=>{})};return{async load(T,A){return new Promise((v,L)=>{let b=R.get(T);b||(b=new Map,R.set(T,b));const q=b.get(A);q?q.push({reject:L,resolve:v}):b.set(A,[{reject:L,resolve:v}]),f||(f=!0,queueMicrotask(O))})}}},Ti=new Set(["_id","id"]),vi=r=>{throw new g("INTERNAL",`no ORDER BY NULL placement for dialect "${String(r)}"`)},Qt=(r,a)=>{const u=a.direction==="desc"?"DESC":"ASC",c=a.nullable===!0,R=f=>e`${Be(r,a.field)} ${e.raw(`${u}${f}`)}`;switch(r.name){case"mysql":{const f=R("");return!c||a.nulls===void 0?[f]:[e`(${Be(r,a.field)} IS NULL) ${e.raw(a.nulls==="first"?"DESC":"ASC")}`,f]}case"postgres":return[R(c?mt(Tt(a)):"")];case"sqlite":return[R(c&&a.nulls!==void 0?mt(Tt(a)):"")];default:return vi(r.name)}},Ii=(r,a)=>{const u=r.flatMap(c=>Qt(a,c));if(!r.some(c=>Ti.has(c.field))){const c=ci(r);u.push(e`${U("id")} ${e.raw(c==="desc"?"DESC":"ASC")}`)}return e.join(u,e`, `)},Dt=50,Ai=r=>{const a=r.detail??r["QUERY PLAN"];return typeof a=="string"?a:Object.values(r).map(String).join(" | ")},Je=(r,a,u,c)=>{for(const[R,f]of _i(r)){if(f.serverDefault){R in a&&(u[R]=f.serverDefault({auth:c}));continue}f.onUpdateFn&&!(R in a)&&(u[R]=f.onUpdateFn())}},Ci=128,Li=()=>{const r=new Map;return{delete:a=>{r.delete(a)},get:a=>{const u=r.get(a);if(u!==void 0)return r.delete(a),r.set(a,u),u},set:(a,u)=>{r.has(a)?r.delete(a):gi(r,Ci),r.set(a,u)}}},zt=r=>r.shardMode===void 0||r.shardMode.kind==="global",bi=async(r,a,u,c,R)=>{const f=R.get(c);if(f!==void 0)return f;const d=Object.entries(u.tables).filter(([,T])=>zt(T)).map(([T])=>T),O=await Promise.all(d.map(async T=>({found:(await I(r,a,e`SELECT 1 FROM ${e.identifier(T)} WHERE ${e.identifier("id")} = ${c} LIMIT 1`)).length>0,tableName:T})));for(const T of O)if(T.found)return R.set(c,T.tableName),T.tableName},ce=r=>r==null?null:Number(r),Ni=(r,a,u)=>u.map(c=>{const R={};for(const f of a){const d=r.shape[f];R[f]=Yt(c[f]??null,d&&Xt(d))}return{key:R,value:ce(c.value)}}),Mi=(r,a,u)=>[...r.partitionBy??[],...r.sortBy.map(R=>R.field),...r.where?Object.keys(r.where):[]].every(R=>Mt(a,R)===Mt(u,R)),Jt=r=>r.length===1?r[0]:e`(${e.join(r,e` AND `)})`,re=r=>e.join(r.map(a=>e`${e.identifier(a)}`),e`, `),de=r=>e.join(r.map(a=>e`${a}`),e`, `),Ze=(r,a)=>{if(r==="postgres"){for(const[u,c]of Object.entries(a))if(typeof c=="string"&&c.includes("\0"))throw new g("BAD_REQUEST",`"${u}" holds a NUL character (U+0000), which a Postgres text column cannot store`)}},We=r=>r instanceof ArrayBuffer?new Uint8Array(r):Array.isArray(r)?Uint8Array.from(r):r,Oi=(r,a,u,c,R)=>{const f=[];for(let d=0;d<u.length+1;d+=1){const O=u[d],T=a.sortBy[d],A=d<u.length&&O!==void 0&&T!==void 0,v=T?.direction==="desc"?"desc":"asc",L=A?Ht(O,We(c[O]),v,!1):e`${e.identifier(Se)} < ${R}`;if(L===void 0)continue;const b=u.slice(0,d).map(q=>ot(r,e`${e.identifier(q)}`,We(c[q])));b.push(L),f.push(Jt(b))}return f.length>0?e.join(f,e` OR `):e`1 = 0`},qi=(r,a,u)=>{if(u.length!==a.length)return;const c=[];for(const[R,f]of a.entries()){const d=Ht(f.column,We(u[R]),f.direction,!0);if(d===void 0)continue;const O=[];for(let T=0;T<R;T+=1){const A=a[T];A!==void 0&&O.push(ot(r,e`${e.identifier(A.column)}`,We(u[T])))}O.push(d),c.push(Jt(O))}return c.length===0?e`(1 = 0)`:e`(${e.join(c,e` OR `)})`},ki=(r,a)=>{if(r.sortBy.length===0)throw new g("INTERNAL",`rankIndex "${r.name}" requires at least one "sortBy" column for stable pagination`);const u=[{column:"__partition__",direction:"asc",nullable:!1}];for(const[c,R]of r.sortBy.entries())u.push({column:a[c]??Re(c),direction:R.direction,nullable:!0});return u.push({column:Se,direction:"asc",nullable:!1}),u},Di=async(r,a,u,c,R)=>{const d=[];for(let v=0;v<R.length;v+=50)d.push(R.slice(v,v+50));const O=await Promise.all(d.map(async v=>I(r,a,e`SELECT * FROM ${e.identifier(c)} WHERE ${e.identifier("id")} IN (${de(v)})`))),T=new Map;for(const v of O)for(const L of v)T.set(L.id,L);const A=[];for(const v of R){const L=X(u,T.get(v));L&&A.push(L)}return A},Bi=r=>{const a=r.map(f=>Yt(f,"bytes")),u=JSON.stringify(Kt(a)?Gt(a):a),c=new TextEncoder().encode(u);let R="";for(const f of c)R+=String.fromCodePoint(f);return Jn+btoa(R)},Zt=r=>{if(r===void 0)return!1;const a=Xt(r);return a==="any"||a==="bigint"||a==="from"||a==="union"},nt=(r,a,u)=>{if(Zt(r.shape[a]))throw new g("BAD_REQUEST",`${u}: "${a}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Wi=(r,a,u,c)=>{for(const R of u)nt(r,R,`groupBy(${a}, { by: [..."${R}"] })`);c.field!==void 0&&nt(r,c.field,`groupBy(${a}, { agg: { op: "${c.op}", field: "${c.field}" } })`)},it="__cdc_sweep",qe="__cdc_log_ts",en="global",Fi=6e4,Ui=1e4,xi=3e4;let Bt=0;const Pi=async(r,a)=>{const{autoincrementPrimaryKey:u,key:c,real:R,text:f}=a.companionTypes;await x(r,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(D)} (${e.identifier("seq")} ${e.raw(u)}, ${e.identifier("ts")} ${e.raw(R)} NOT NULL, ${e.identifier("table")} ${e.raw(c)} NOT NULL, ${e.identifier("id")} ${e.raw(c)} NOT NULL, ${e.identifier("op")} ${e.raw(c)} NOT NULL, ${e.identifier("doc")} ${e.raw(f)})`);const d=a.indexKeyPrefix?.("string");await Vt(r,a,{columns:e`${d===void 0?e`${e.identifier("table")}`:e`${e.identifier("table")}(${e.raw(String(d))})`}, ${e.identifier("seq")}`,name:di,table:D,unique:!1}),await x(r,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(it)} (${e.identifier("id")} ${e.raw(c)} NOT NULL PRIMARY KEY, ${e.identifier("lease_until")} ${e.raw(R)} NOT NULL)`),await x(r,a,e`INSERT INTO ${e.identifier(it)} (${e.identifier("id")}, ${e.identifier("lease_until")}) VALUES (${en}, ${0}) ${a.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${e.identifier("id")} = ${e.identifier("id")}`:e`ON CONFLICT(${e.identifier("id")}) DO NOTHING`}`)},Hi=async(r,a,u)=>{const c=e`UPDATE ${e.identifier(it)} SET ${e.identifier("lease_until")} = ${u+Fi} WHERE ${e.identifier("id")} = ${en} AND ${e.identifier("lease_until")} <= ${u}`;if(a.supportsReturning)return(await I(r,a,e`${c} RETURNING ${e.identifier("id")}`)).length>0;const R=await x(r,a,c);return(a.affectedRows?a.affectedRows(R??{rowsAffected:0}):0)>0},ji=async(r,a,u,c)=>{if(!await Hi(r,a,c))return;const R=c-u;let f=!0;try{const d=await wi(r,a,D,qe);d!=="valid"&&(d==="invalid"&&await $i(r,a,D,qe),await Vt(r,a,{columns:e`${e.identifier("ts")}`,concurrently:!0,name:qe,table:D,unique:!1}))}catch(d){f=!1,console.warn(`[@lunora/sql-store] changelog retention could not build "${qe}"; sweeping without it.`,d)}f&&(await I(r,a,e`SELECT 1 AS ${e.identifier("hit")} FROM ${e.identifier(D)} WHERE ${e.identifier("ts")} <= ${R} LIMIT 1`)).length===0||await x(r,a,e`
2
- DELETE FROM ${e.identifier(D)} WHERE ${e.identifier("seq")} IN (
3
- SELECT ${e.identifier("seq")} FROM (
4
- SELECT ${e.identifier("seq")} FROM ${e.identifier(D)} WHERE +${e.identifier("ts")} <= ${R} ORDER BY ${e.identifier("seq")} ASC LIMIT ${e.raw(String(Ui))}
5
- ) AS ${e.identifier("expired")}
6
- )
7
- `)},tn=async(r,a)=>{const u=await I(r,a,e`SELECT MIN(${e.identifier("seq")}) AS ${e.identifier("seq")} FROM ${e.identifier(D)}`),c=Number(u[0]?.seq??Number.NaN);return Number.isFinite(c)?c:void 0},Ki=async(r,a)=>{if(a.name!=="sqlite")return;const u=await I(r,a,e`SELECT ${e.identifier("seq")} AS ${e.identifier("seq")} FROM ${e.identifier("sqlite_sequence")} WHERE ${e.identifier("name")} = ${D}`),c=Number(u[0]?.seq??Number.NaN);return Number.isFinite(c)?c:0},Gi=r=>JSON.stringify(Kt(r)?Gt(r):r),Vi=(r,a,u,c,R)=>e`INSERT INTO ${e.identifier(D)} (${e.identifier("ts")}, ${e.identifier("table")}, ${e.identifier("id")}, ${e.identifier("op")}, ${e.identifier("doc")}) VALUES (${r}, ${a}, ${u}, ${c}, ${R===void 0?null:Gi(R)})`,nn=1e4,Yi=1e3,Xi=(r,a,u)=>{let c=a;for(const[R,f]of r.entries()){const d=Number(f.seq);if(d>c+1&&Number(f.ts)>u)return r.slice(0,R);c=d}return r},_o=async(r,a,u)=>{const c=a.sinceSeq??0,R=Math.max(1,Math.min(a.limit??1e3,1e4)),f=await tn(r,u),d=await Ki(r,u);if(d!==void 0&&c>d)throw qn(d,c,"global");if(f!==void 0&&kn(f,c))throw Dn(f,c,"global");const O=await I(r,u,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(D)} WHERE seq > ${c} ORDER BY seq ASC LIMIT ${e.raw(String(R))}`),A=(u.name==="sqlite"?O:Xi(O,c,(a.now??Date.now())-nn)).map(v=>{const{doc:L}=v,b={id:String(v.id),op:String(v.op),seq:Number(v.seq),table:String(v.table),ts:Number(v.ts)};return typeof L=="string"?{...b,doc:jt(JSON.parse(L))}:b});return{changes:A,cursor:A.at(-1)?.seq??c}},Wt=(r,a)=>{const u=e.identifier(D),c=e`(SELECT MIN(v.seq) FROM ${u} v WHERE v.seq > ${r} AND v.seq - 1 > ${r} AND v.ts > ${a} AND NOT EXISTS (SELECT 1 FROM ${u} p WHERE p.seq = v.seq - 1))`;return e`${c} AS ${e.identifier("gap")}, (SELECT MAX(q.seq) FROM ${u} q WHERE q.seq > ${r} AND q.seq < ${c}) AS ${e.identifier("below")}`},Ft=(r,a,u)=>{const c=Number(a?.gap??Number.NaN);if(!Number.isFinite(c))return r;const R=Number(a?.below??Number.NaN);return Math.min(r,Number.isFinite(R)?R:u)},Qi=r=>{const a=e.identifier(D),u=e.identifier("table");return e`SELECT ${u}, seq FROM (WITH RECURSIVE "t"("name") AS (SELECT MIN(${u}) FROM ${a} UNION ALL SELECT (SELECT MIN(${u}) FROM ${a} WHERE ${u} > "t"."name") FROM "t" WHERE "t"."name" IS NOT NULL) SELECT "t"."name" AS ${u}, (SELECT MAX(seq) FROM ${a} WHERE ${u} = "t"."name" AND seq > ${r}) AS seq FROM "t" WHERE "t"."name" IS NOT NULL) WHERE seq IS NOT NULL ORDER BY ${u}`},zi=async(r,a,u,c={})=>{const R=e.identifier(D),f=u.name!=="sqlite",d=(c.now??Date.now())-nn;if(c.cursorOnly){const L=e`GREATEST((SELECT MAX(seq) FROM ${R}) - ${e.raw(String(Yi))}, ${a})`,b=await I(r,u,e`SELECT MAX(seq) AS seq${f?e`, ${Wt(L,d)}`:e``} FROM ${R}`),q=Number(b[0]?.seq??a);return{cursor:Ft(Number.isFinite(q)?q:a,b[0],a),tables:[]}}const O=await I(r,u,f?e`SELECT ${e.identifier("table")} AS ${e.identifier("table")}, MAX(seq) AS seq, ${Wt(e`${a}`,d)} FROM ${R} WHERE seq > ${a} GROUP BY ${e.identifier("table")}`:Qi(a));let T=a;const A=[];for(const L of O){const b=Number(L.seq);Number.isFinite(b)&&b>T&&(T=b),A.push(String(L.table))}T=Ft(T,O[0],a);const v=c.retained===!0?await tn(r,u):void 0;return{cursor:T,tables:A,...v===void 0?{}:{floor:v}}},Ji=/string or blob too big/iu,Zi=/row is too big/iu,eo=(r,a)=>{const{code:u,errno:c}=a,R=a instanceof Error?a.message:"";switch(r.name){case"mysql":return c===1118||u==="ER_TOO_BIG_ROWSIZE"?"InnoDB's per-row ceiling — roughly 8 KB, half a 16 KB page, for the part of the row stored inline":void 0;case"postgres":return Zi.test(R)?"the 8 KB heap page a tuple must fit once its wide columns have been TOASTed out":void 0;default:return Ji.test(R)?"the storage engine's per-row ceiling (2 MB on D1)":void 0}},to=(r,a,u)=>{const c=eo(r,a);if(c!==void 0)throw new g("PAYLOAD_TOO_LARGE",`document is too large to store in "${u}": a single row cannot exceed ${c}. The limit is on the STORED bytes, which are UTF-8. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},et=16,Ut="__lunora_patch_if_match__",xt=(r,a,u)=>{throw r.isUniqueViolation(a)?new ae(`unique constraint violation on "${u}"`,"unique"):(to(r,a,u),a)},tt=new WeakMap,Pt=new WeakMap,ye="superseded",no=3e4,ke="__lunora_companion_fence",se=(r,a,u)=>JSON.stringify([r,a,u]),De=r=>JSON.stringify(r,(a,u)=>typeof u=="bigint"?`${String(u)}n`:u),io=r=>{const a=Bn(r);return(u,c,R,f)=>c.some(d=>d instanceof fi)?hi(r,u,c,R):a(u,c,R,f)},Eo=r=>{const{crossShardCounter:a,crossShardReader:u,exec:c,maxRelationKeys:R,schema:f}=r,{dialect:d}=r,O={fieldRef:n=>Be(d,n),rangeTypeGuard:(n,t)=>pi(d,n,t),...d.name==="mysql"?{containsExpr:(n,t)=>{const i=At(n);return i===void 0?e`LOCATE(${t}, ${n}) > 0`:e`LOCATE(${Ct("mysql",t)}, ${i}) > 0`}}:{},...d.name==="postgres"?{containsExpr:(n,t)=>{const i=At(n);return i===void 0?e`strpos(${n}, ${t}) > 0`:e`strpos(${i}, ${Ct("postgres",t)}) > 0`}}:{},...d.name==="sqlite"?{}:{inList:io(d.name)}},T=new WeakMap,A=n=>{const t=T.get(n);if(t!==void 0)return t;const i={...O,serialize:(o,s)=>Nt(d,s,o,l=>oe(n,s,l))};return T.set(n,i),i},v=(n,t)=>ot(d.name,n,t),L=n=>{const t=re(n.columns),i=de(n.values),o=$=>d.name==="mysql"?e`VALUES(${e.identifier($)})`:e`excluded.${e.identifier($)}`,s=$=>d.name==="postgres"?e`${e.identifier(n.table)}.${e.identifier($)}`:e`${e.identifier($)}`,l=e.join(Object.entries(n.set(o,s)).map(([$,h])=>e`${e.identifier($)} = ${h}`),e`, `),p=d.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${l}`:e`ON CONFLICT(${e.identifier(n.conflictKey)}) DO UPDATE SET ${l}`;return e`INSERT INTO ${e.identifier(n.table)} (${t}) VALUES (${i}) ${p}`},b=r.clock??(()=>Date.now()),q=r.idGenerator??(()=>crypto.randomUUID()),K=r.cdc??!1,Q=typeof r.cdcRetentionMs=="number"&&Number.isFinite(r.cdcRetentionMs)&&r.cdcRetentionMs>0?r.cdcRetentionMs:void 0,Z=r.auth??{identity:null,userId:null},le=(n,t,i,o)=>K?[Vi(b(),n,t,i,o)]:[],on=async()=>{if(!K||Q===void 0)return;const n=b();if(!(n-Bt<xi)){Bt=n;try{await ji(c,d,Q,n)}catch{}}},rn=r.scheduler??Mn,Fe=Li();let ge=0;const ue=r.provisionScope??{},B=async()=>{const n=tt.get(ue);if(n)return n;const t=(async()=>{await yi(c,f,d),await Ri(c,f,d),await Si(c,f,d),await Rn(c,d),await mn(c,f,d),K&&await Pi(c,d)})().catch(i=>{throw tt.delete(ue),i});return tt.set(ue,t),t},me=async(n,t)=>{if(t!==void 0&&!Object.hasOwn(f.tables,t))throw new g("BAD_REQUEST",`ctx.db by-id write (table, id): "${t}" is not a table in this schema`);if(await B(),t===void 0)return bi(c,d,f,n,Fe);const i=Object.hasOwn(f.tables,t)?f.tables[t]:void 0;return i!==void 0&&zt(i)?t:void 0};let Te=Pt.get(ue);Te===void 0&&(Te=new Map,Pt.set(ue,Te));const P=Te,rt={},Ue=(n,t,i)=>{const o=(async()=>(await B(),await i(()=>P.get(n)?.run!==o)))(),s={definition:t,owner:rt,run:o,settled:!1};return o.then(()=>{s.settled=!0},()=>{P.get(n)===s&&P.delete(n)}).catch(()=>{}),P.set(n,s),o},st=async(n,t,i)=>{const o=P.get(n);if(o===void 0)return await Ue(n,t,i);const s=o.definition===t;if(s&&(o.settled||o.owner===rt))return await o.run;if(o.settled)return await Ue(n,t,i);let l;const p=new Promise(h=>{l=setTimeout(h,no,"stalled")}),$=await Promise.race([o.run,p]).finally(()=>{clearTimeout(l)});return $!=="stalled"&&s?$:P.get(n)===o?await Ue(n,t,i):await st(n,t,i)},xe=async(n,t,i)=>{const o=await st(n,t,i);return o===ye?await xe(n,t,i):o},at=async(n,t)=>{const i=P.get(n),o=i?.settled===!0&&i.definition===t?await i.run:void 0;if(typeof o=="boolean")return o;P.delete(n)},sn=n=>{const t=f.tables[n];for(const i of t?.aggregateIndexes??[])P.delete(se("aggregate",n,i.name));for(const i of t?.rankIndexes??[])P.delete(se("rank",n,i.name))},an=async(n,t)=>{const i=ie(n,t);return(await I(c,d,d.tableExists(i))).length>0},ct=async n=>{const{key:t}=d.companionTypes,i=q();await x(c,d,e`CREATE TABLE IF NOT EXISTS ${e.identifier(ke)} (${e.identifier("name")} ${e.raw(t)} PRIMARY KEY, ${e.identifier("token")} ${e.raw(t)} NOT NULL)`),await x(c,d,L({columns:["name","token"],conflictKey:"name",set:s=>({token:s("token")}),table:ke,values:[n,i]}));const o=e`${e.identifier("name")} = ${n} AND ${e.identifier("token")} = ${i}`;return{guardedDelete:()=>e`DELETE FROM ${e.identifier(n)} WHERE EXISTS (SELECT 1 FROM ${e.identifier(ke)} WHERE ${o})`,guardedInsert:(s,l)=>e`INSERT INTO ${e.identifier(n)} (${re(s)}) SELECT ${de(l)} FROM ${e.identifier(ke)} WHERE ${o}`}},cn=async(n,t,i)=>{const o=f.tables[n];if(!o||!await an(n,t.name))return!1;const s=t.by??[],l=new Map;await Ot(c,d,o,n,_=>{if(t.where&&!Ye(_,t.where))return;const w=J(s,_);It(l,w,t,_)});const p=ie(n,t.name);if(i())return ye;const $=await ct(p);await x(c,d,$.guardedDelete());const h=[];for(const[_,w]of l)h.push($.guardedInsert(["__key__","__value__","__count__"],[_,w.value,w.count]));return i()||await qt(c,d,h),i()?ye:!0},ve=(n,t)=>xe(se("aggregate",n,t.name),De(t),i=>cn(n,t,i)),dn=async(n,t,i,o)=>{const s=new Map;let l,p=!0;for(;p;){const $=l===void 0?o:[...o,e`${e.identifier("id")} > ${l}`],h=$.length>0?e` WHERE ${e.join($,e` AND `)}`:e``,_=await I(c,d,e`SELECT ${e.identifier("id")}, ${U(i.field??"")} FROM ${e.identifier(t)}${h} ORDER BY ${e.identifier("id")} ASC LIMIT ${e.raw(String(ze))}`);for(const w of Lt(n,_))It(s,"",i,w);l=_.at(-1)?.id,p=_.length===ze}return s.get("")?.value??null},ln=async(n,t,i)=>{const o=t.field??"",s=[],l=f.tables[n],p=(w,E)=>Nt(d,w,E,S=>l?oe(l,w,S):Qe(S));for(const w of t.by??[]){const E=p(w,i[w]??null);s.push(E===null?e`${U(w)} IS NULL`:e`${U(w)} = ${E}`)}for(const[w,E]of Object.entries(t.where??{})){const S=E!==null&&typeof E=="object"&&!Array.isArray(E)?E.eq:E,y=p(w,S),m=Be(d,w);s.push(y===null?e`${m} IS NULL`:e`${m} = ${y}`)}const $=s.length>0?e` WHERE ${e.join(s,e` AND `)}`:e``;if(l&&Zt(l.shape[o]))return dn(l,n,t,s);const h=Ee(t.op),_=await I(c,d,e`SELECT ${e.raw(h)}(${U(o)}) AS ${e.identifier("value")} FROM ${e.identifier(n)}${$}`);return ce(_[0]?.value)},un=(n,t)=>e`DELETE FROM ${e.identifier(n)} WHERE ${e.identifier("__key__")} = ${t} AND ${e.identifier("__count__")} <= 0`,fn=async(n,t,i,o)=>{const s=ie(n,t.name),{op:l}=t,p=t.field??"",$=i&&(!t.where||Ye(i,t.where))?i:void 0,h=o&&(!t.where||Ye(o,t.where))?o:void 0;if(!$&&!h)return[];if(l==="count"||l==="sum"||l==="avg"){const w=[],E=new Set;for(const[S,y]of[[$,-1],[h,1]]){if(!S)continue;const m=l==="count"?1:Xe(S[p]);if(m===void 0)continue;const N=J(t.by??[],S);E.add(N),w.push(L({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(C,M)=>({__count__:e`${M("__count__")} + ${C("__count__")}`,__value__:l==="count"?e`${M("__value__")} + ${C("__value__")}`:e`COALESCE(${M("__value__")}, 0) + ${C("__value__")}`}),table:s,values:[N,y*m,y]}))}for(const S of E)w.push(un(s,S));return w}const _=[];if($){const w=J(t.by??[],$),E=Xe($[p]),y=(await I(c,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(s)} WHERE ${e.identifier("__key__")} = ${w}`))[0],m=ce(y?.value),N=(y?.count??0)-1;if(N<=0)_.push(e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__key__")} = ${w}`);else if(y&&E!==void 0&&m!==null&&E===m){const C=await ln(n,t,$);_.push(e`UPDATE ${e.identifier(s)} SET ${e.identifier("__value__")} = ${C}, ${e.identifier("__count__")} = ${N} WHERE ${e.identifier("__key__")} = ${w}`)}else _.push(e`UPDATE ${e.identifier(s)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${w}`)}if(h){const w=J(t.by??[],h),E=Xe(h[p]);if(E===void 0)_.push(L({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(S,y)=>({__count__:e`${y("__count__")} + 1`}),table:s,values:[w,null,1]}));else{const S=l==="min"?"MIN":"MAX";_.push(L({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(y,m)=>({__count__:e`${m("__count__")} + 1`,__value__:e`${e.raw(S)}(COALESCE(${m("__value__")}, ${y("__value__")}), ${y("__value__")})`}),table:s,values:[w,E,1]}))}}return _},Ie=async n=>{const t=f.tables[n]?.aggregateIndexes;if(!(!t||t.length===0))for(const i of t)await ve(n,i)},fe=async(n,t,i)=>{const o=f.tables[n]?.aggregateIndexes,s=[];if(!o||o.length===0)return s;for(const l of o)await at(se("aggregate",n,l.name),De(l))&&s.push(...await fn(n,l,t,i));return s},wn=async(n,t)=>{const i=_e(n,t);return(await I(c,d,d.tableExists(i))).length>0},$n=async(n,t,i)=>{const o=f.tables[n];if(!o||!await wn(n,t.name))return!1;const s=_e(n,t.name);if(i())return ye;const l=await ct(s);await x(c,d,l.guardedDelete());const $=["__id__","__partition__",...t.sortBy.map((w,E)=>Re(E))];let h=[];const _=async()=>{const w=h;h=[],!(w.length===0||i())&&await qt(c,d,w)};return await Ot(c,d,o,n,async w=>{if(t.where&&!vt(w,t.where))return;const E=Me(t.partitionBy??[],w),S=t.sortBy.map(y=>Qe(w[y.field]??null));h.push(l.guardedInsert($,[w._id,E,...S])),h.length>=ze&&await _()}),await _(),i()?ye:!0},Pe=(n,t)=>xe(se("rank",n,t.name),De(t),i=>$n(n,t,i)),Ae=async n=>{const t=f.tables[n]?.rankIndexes;if(!(!t||t.length===0))for(const i of t)await Pe(n,i)},ee=async(n,t,i,o)=>{const s=f.tables[n],l=s?.rankIndexes,p=[];if(!l||l.length===0)return p;const $=s?.softDeleteMode?.field,h=$===void 0||o===void 0?void 0:o[$],_=h!=null;for(const w of l){if(i!==void 0&&o!==void 0&&Mi(w,i,o)||!await at(se("rank",n,w.name),De(w)))continue;const S=_e(n,w.name);if(i&&p.push(e`DELETE FROM ${e.identifier(S)} WHERE ${e.identifier("__id__")} = ${t}`),o&&!_){if(w.where&&!vt(o,w.where))continue;const y=w.sortBy.map((M,W)=>Re(W)),m=re(["__id__","__partition__",...y]),N=Me(w.partitionBy??[],o),C=w.sortBy.map(M=>Qe(o[M.field]??null));p.push(e`INSERT INTO ${e.identifier(S)} (${m}) VALUES (${de([t,N,...C])})`)}}return p},te=async(n,t)=>{try{const i=await t();i.length>0&&await Ei(c,d,i)}catch(i){throw sn(n),i}await on()},we=gn({dialect:d,exec:c,schema:f}),dt=new Set;for(const[n,t]of Object.entries(f.tables))for(const i of Object.values(t.triggerMap??{}))dt.add(`${n} ${i.timing} ${i.op}`);const G=(n,t,i)=>dt.has(`${n} ${t} ${i}`);let lt;const V=async(n,t,i)=>{if(ge+=1,ge>Dt)throw ge-=1,new ae(`trigger recursion exceeded ${String(Dt)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await zn({ctx:lt,event:i,op:t,schema:f,tableName:i.table,timing:n})}finally{ge-=1}},hn=async(n,t)=>{try{await x(c,d,t)}catch(i){xt(d,i,n)}},Ce=async(n,t)=>(await I(c,d,e`SELECT * FROM ${e.identifier(n)} WHERE ${e.identifier("id")} = ${t}`))[0],ut=async(n,t,i,o,s)=>{const l=e`${e.identifier(pe)}`,p=e.join([v(e`${e.identifier("id")}`,o.id),v(l,o[pe]??null),...s===void 0?[]:[e`(${s})`]],e` AND `),$=t==="UPDATE"?e`UPDATE ${e.identifier(n)} SET ${i}, ${l} = ${bt.sql(l)} WHERE ${p}`:e`DELETE FROM ${e.identifier(n)} WHERE ${p}`;try{if(d.supportsReturning)return(await I(c,d,e`${$} RETURNING ${e.identifier("id")}`)).length>0;const h=await x(c,d,$);return(d.affectedRows?d.affectedRows(h??{rowsAffected:0}):0)>0}catch(h){return xt(d,h,n)}},He=async(n,t,i,o)=>{if(o!==void 0&&!await ut(n,t,i,o))throw new ae(`optimistic concurrency conflict on "${n}" — the row changed during this mutation; refetch and retry`,"occ")},je=(n,t=n?._creationTime)=>({_creationTime:t,[pe]:bt.value(n?.[pe])}),ft=async(n,t,i,o,s,l,p)=>{const $=X(t,s);if(!$||s===void 0)throw new g("INTERNAL",`document not found: ${i}`);const h=Zn(t,o,$),_={...$,...ei(h),_id:i};Je(t,h,_,Z);const w=Ge(t,_,{only:new Set(Object.keys(h)),previous:()=>$,tolerateStoredNull:!0});Ze(d.name,Object.fromEntries(Object.keys(h).map(y=>[y,w[y]]))),ti(p,$,w),G(n,"before","update")&&await V("before","update",{doc:{...w},id:i,op:"update",previous:$,table:n}),await Ie(n),await Ae(n);const E=Object.keys(t.shape),S=e.join(E.map(y=>e`${e.identifier(y)} = ${oe(t,y,w[y]??null)}`),e`, `);if(await ut(n,"UPDATE",S,s,l))return await te(n,async()=>[...await fe(n,$,w),...await ee(n,i,$,w),...le(n,i,"update",w)]),await we(n,i,{document:w,previous:$,written:je(s)}),G(n,"after","update")&&await V("after","update",{doc:w,id:i,op:"update",previous:$,table:n}),w},_n=(n,t,i,o)=>{const s=Object.keys(n.shape);return{columns:["id","_creationTime",...s],values:[t,i,...s.map(l=>oe(n,l,o[l]??null))]}},En=async(n,t,i,o)=>{const s=ii(t,i.op,i.field,o.by,o.where);if(!s||!await ve(n,s.index))return;const p=ie(n,s.index.name),$=Object.keys(s.partial);if($.length===(s.index.by??[]).length&&$.length>0){const _=J(s.index.by??[],s.partial),w=await I(c,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(p)} WHERE ${e.identifier("__key__")} = ${_}`);if(w.length===0)return[];const E=w[0];return[{key:{...s.partial},value:Ve(i.op,{count:E.count,value:ce(E.value)})}]}return $.length>0?void 0:(await I(c,d,e`SELECT ${e.identifier("__key__")} AS ${e.identifier("key")}, ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(p)}`)).map(_=>{const w=_;return{key:jt(JSON.parse(w.key)),value:Ve(i.op,{count:w.count,value:ce(w.value)})}})},wt=n=>{const t=f.tables[n]?.shardMode?.kind;return t==="shardBy"||t==="root"},$t=n=>{throw new g("INTERNAL",`cross-backend relation: a global table cannot load the shard-local relation '${n}' (it spans every shard) — wire a cross-shard reader to support it`)},pn=(n,t)=>{if(t?.relationMask!==void 0&&t.with!==void 0&&Object.keys(t.with).length>0)throw new g("MASK_UNSUPPORTED",`masking cannot follow a nested \`with\` across the cross-shard relation hop to "${n}" — the nested rows are hydrated on the serving shard, where the mask policy does not exist. Read the nested relation at its own (masked) call site instead.`);const i={};if(t?.relationBaseWhere)for(const o of Object.keys(f.tables)){const s=t.relationBaseWhere(o);s!==void 0&&(i[o]=s)}return{orderBy:t?.orderBy,relationPolicies:i,where:F(t?.baseWhere,t?.where),with:t?.with}},Le=(n,t)=>wt(n)?u?u(n,pn(n,t)):$t(n):H.findMany(n,t),be=(n,t,i)=>ni(n,{fetcher:Le,maxRelationKeys:R,relationBaseWhere:i,schema:f,tableName:t}),yn=mi(async(n,t)=>{const i=await I(c,d,e`SELECT * FROM ${e.identifier(n)} WHERE ${e.identifier("id")} IN (${de(t)})`),o=new Map;for(const s of i){const{id:l}=s;typeof l=="string"&&o.set(l,s)}return o}),ht=async(n,t,i)=>{const{fetchLimit:o,limit:s,orderKeys:l,predicate:p}=await oi(t,i,{fetcher:Le,maxRelationKeys:R,schema:f,tableName:n}),$=z(p,A(t)),h=Ii(l,d);let _=e`SELECT * FROM ${e.identifier(n)}`;return $&&(_=e`${_} WHERE ${$}`),_=e`${_} ORDER BY ${h}`,o!==void 0&&(_=e`${_} LIMIT ${e.raw(String(o))}`),{limit:s,orderKeys:l,query:_}},H={relationWrites:On(f),async cdcChangedTables(n,t){if(K)try{return await B(),await zi(c,n,d,{...t,now:b(),retained:Q!==void 0})}catch{return}},async aggregate(n,t){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);if(await B(),Ee(t.op),t.op==="count")return H.count(n,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new g("INTERNAL",`aggregate(${n}, { op: "${t.op}" }): "field" is required for non-count reducers`);const o=Oe(i.softDeleteMode,void 0),s=F(F(t.baseWhere,t.where),o),l=await be(s,n,t.relationBaseWhere),p=l!==s;if(i.aggregateIndexes&&!t.baseWhere&&!p&&!o){const S=Qn(i.aggregateIndexes,t.op,t.field,t.where);if(S&&await ve(n,S.index)){const m=J(S.index.by??[],S.key),N=ie(n,S.index.name),M=(await I(c,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(N)} WHERE ${e.identifier("__key__")} = ${m}`))[0];return Ve(t.op,M===void 0?void 0:{count:M.count,value:ce(M.value)})}}nt(i,t.field,`aggregate(${n}, { op: "${t.op}", field: "${t.field}" })`);const $=z(l,A(i)),h=e.raw(Ee(t.op)),_=e`SELECT ${h}(${U(t.field)}) AS ${e.identifier("value")} FROM ${e.identifier(n)}`,E=(await I(c,d,$?e`${_} WHERE ${$}`:_))[0]?.value;return E==null?null:Number(E)},async count(n,t){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);await B();const o=Yn(t);if(o.restrictsCounts)throw new yt(n);const s=Oe(i.softDeleteMode,void 0),l=F(F(o.baseWhere,o.where),s),p=await be(l,n,o.relationBaseWhere),$=p!==l;if(i.aggregateIndexes&&!o.baseWhere&&!$&&!s){const E=Xn(i.aggregateIndexes,o.where);if(E&&await ve(n,E.index)){const y=J(E.index.by??[],E.key),m=ie(n,E.index.name),N=await I(c,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")} FROM ${e.identifier(m)} WHERE ${e.identifier("__key__")} = ${y}`);return Number(N[0]?.value??0)}}const h=z(p,A(i)),_=e`SELECT COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(n)}`,w=await I(c,d,h?e`${_} WHERE ${h}`:_);return Number(w[0]?.count??0)},async delete(n,t,i){const o=await me(t,n);if(!o)return;const s=f.tables[o];if(!s)return;const l=await Ce(o,t);if(l===void 0)return;const p=X(s,l),$=i?.hard===!0,h=!$&&s.softDeleteMode?s.softDeleteMode.field:void 0;if(!(h&&(!p||p[h]!==null&&p[h]!==void 0))){if(G(o,"before","delete")&&await V("before","delete",{id:t,op:"delete",previous:p??void 0,table:o}),await Vn({deletedId:t,deletedReference:_=>p?.[_],findHolders:async(_,w,E,S)=>{if(f.tables[_]?.shardMode?.kind==="shardBy")throw new g("INTERNAL",`cross-backend cascade from global '${o}' into shardBy '${_}' is not supported — would require Query Coordinator fan-out across shards`);return(await H.findMany(_,{...S,includeDeleted:$,where:{[w]:E}})).page},onCascade:(_,w)=>H.delete(_,w,i),onRestrict:_=>{throw new ae(_,"restrict")},onSetNull:(_,w,E)=>H.patch(_,w,{[E]:null}),schema:f,tableName:o}),await Ie(o),await Ae(o),h&&p){const _={[h]:b()},w={...p,..._};Je(s,_,w,Z);const E=e.join(Object.keys(s.shape).map(S=>e`${e.identifier(S)} = ${oe(s,S,w[S]??null)}`),e`, `);await He(o,"UPDATE",E,l),await te(o,async()=>[...await fe(o,p,w),...await ee(o,t,p,void 0),...le(o,t,"update",w)]),await we(o,t,{document:w,previous:p,written:je(l)}),G(o,"after","delete")&&await V("after","delete",{id:t,op:"delete",previous:p,table:o});return}await He(o,"DELETE",void 0,l),Fe.delete(t),await te(o,async()=>[...await fe(o,p??void 0,void 0),...await ee(o,t,p??void 0,void 0),...le(o,t,"delete")]),await we(o,t,void 0),G(o,"after","delete")&&await V("after","delete",{id:t,op:"delete",previous:p??void 0,table:o})}},async findFirst(n,t={}){return(await H.findMany(n,{...t,limit:1})).page[0]??null},async findFirstOrThrow(n,t={}){const i=await H.findFirst(n,t);if(i===null)throw new Gn(`findFirstOrThrow: no "${n}" document matched`);return i},async findMany(n,t={}){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);await B();const o=async(S,y,m,N)=>{if(wt(S))return a?ri(a,S,y,m,N):$t(S);const C=f.tables[S];if(!C)throw new g("INTERNAL",`unknown table: ${S}`);const M=Oe(C.softDeleteMode,void 0),W={[y]:{in:m}},Y=F(F(W,N),M),$e=await be(Y,S,void 0),Ne=z($e,A(C)),he=U(y);let j=e`SELECT ${he} AS __fk__, COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(S)}`;Ne&&(j=e`${j} WHERE ${Ne}`),j=e`${j} GROUP BY ${he}`;const k=await I(c,d,j),ne=new Map;for(const _t of k)ne.set(_t.__fk__,Number(_t.count??0));return ne},{limit:s,orderKeys:l,query:p}=await ht(n,i,t),$=await I(c,d,p),h=Lt(i,$);if(s===void 0)return t.with&&await Rt({fetcher:Le,groupedCounter:o,parents:h,...St(t),schema:f,tableName:n,with:t.with}),{continueCursor:null,isDone:!0,page:gt(h,t.select,t.with)};const _=h.length>s,w=_?h.slice(0,s):h,E=w.at(-1);return t.with&&await Rt({fetcher:Le,groupedCounter:o,parents:w,...St(t),schema:f,tableName:n,with:t.with}),{continueCursor:_&&E?Kn(E,l):null,isDone:!_,page:gt(w,t.select,t.with)}},async explain(n,t={}){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);await B();const{query:o}=await ht(n,i,t),s=d.name==="sqlite"?"EXPLAIN QUERY PLAN":"EXPLAIN",l=await I(c,d,e`${e.raw(s)} ${o}`),{params:p,sql:$}=d.render(o);return{params:p,plan:l.map(h=>Ai(h)),sql:$}},async get(n,t){const i=Object.hasOwn(f.tables,n)?f.tables[n]:void 0;if(!i)throw new g("BAD_REQUEST",`ctx.db.get(table, id): "${n}" is not a table in this schema`);return i.shardMode!==void 0&&i.shardMode.kind!=="global"?null:(await B(),X(i,await yn.load(n,t)))},async groupBy(n,t){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);await B();const o=t.agg??{op:"count"};if(Ee(o.op),o.op!=="count"&&!o.field)throw new g("INTERNAL",`groupBy(${n}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);const s=Oe(i.softDeleteMode,void 0),l=F(F(t.baseWhere,t.where),s),p=await be(l,n,t.relationBaseWhere),$=p!==l;if(i.aggregateIndexes&&!t.baseWhere&&!$&&!s){const y=await En(n,i.aggregateIndexes,o,t);if(y!==void 0)return y}Wi(i,n,t.by,o);const h=z(p,A(i)),_=t.by.map(y=>e`${U(y)} AS ${e.identifier(y)}`);if(o.op==="count")_.push(e`COUNT(*) AS ${e.identifier("value")}`);else{if(!o.field)throw new g("INTERNAL",`groupBy(${n}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);_.push(e`${e.raw(Ee(o.op))}(${U(o.field)}) AS ${e.identifier("value")}`)}const w=e.join(t.by.map(y=>U(y)),e`, `);let E=e`SELECT ${e.join(_,e`, `)} FROM ${e.identifier(n)}`;h&&(E=e`${E} WHERE ${h}`),E=e`${E} GROUP BY ${w}`;const S=await I(c,d,E);return Ni(i,t.by,S)},async insert(n,t,i){const o=f.tables[n];if(!o)throw new g("INTERNAL",`unknown table: ${n}`);await B();const s=Ge(o,Pn(o,t,Z),{supplied:t,trusted:i?.allowExplicitId===!0});Ze(d.name,s);let l,p=!0;i?.clientId!==void 0?(Hn(i.clientId),l=i.clientId):i?.allowExplicitId&&typeof s._id=="string"?(jn(s._id),l=s._id):(l=q(),p=!1);const $=i?.allowExplicitId&&typeof s._creationTime=="number"?s._creationTime:b(),h={...s,_creationTime:$,_id:l};G(n,"before","insert")&&await V("before","insert",{doc:{...h},id:l,op:"insert",table:n}),await Ie(n),await Ae(n);const{columns:_,values:w}=_n(o,l,$,s);return await hn(n,e`INSERT INTO ${e.identifier(n)} (${re(_)}) VALUES (${de(w)})`),p&&Fe.set(l,n),await te(n,async()=>[...await fe(n,void 0,h),...await ee(n,l,void 0,h),...le(n,l,"insert",h)]),await we(n,l,{document:h,written:{_creationTime:$,[pe]:null}}),G(n,"after","insert")&&await V("after","insert",{doc:h,id:l,op:"insert",table:n}),l},normalizeId(n,t){return xn(f,n,t)},async patch(n,t,i,o){Ke("patch",i);const s=await me(t,n);if(!s)throw new g("INTERNAL",`document not found: ${t}`);const l=f.tables[s];if(!l)throw new g("INTERNAL",`document not found: ${t}`);const p=Un(l,i)?et:1;for(let $=0;$<p;$+=1){const h=await Ce(s,t);if(await ft(s,l,t,i,h,void 0,o))return}throw new ae(`optimistic concurrency conflict on "${s}" — the row changed during this mutation; refetch and retry`,"occ")},async patchIf(n,t,i){Ke("patchIf",i.patch),await B();const o=f.tables[n];if(!o)throw new g("INTERNAL",`unknown table: ${n}`);const s=z(i.where,A(o))??e`1 = 1`;for(let l=0;l<et;l+=1){const[p]=await I(c,d,e`SELECT *, CASE WHEN (${s}) THEN 1 ELSE 0 END AS ${e.identifier(Ut)} FROM ${e.identifier(n)} WHERE ${e.identifier("id")} = ${t}`);if(p===void 0)return{applied:!1,doc:null};const{[Ut]:$,...h}=p;if(Number($)!==1)return{applied:!1,doc:X(o,h)??null};const _=await ft(n,o,t,i.patch,h,s,{verify:i.verify});if(_)return{applied:!0,doc:_}}throw new ae(`patchIf on "${n}" lost the row to concurrent writes ${String(et)} times in a row; retry the operation`,"occ")},async restore(n,t){const i=await me(t,n),o=i===void 0?void 0:await Ce(i,t);if(!i||o===void 0)throw new g("INTERNAL",`document not found: ${t}`);const s=f.tables[i],l=s?.softDeleteMode?.field;if(!s||!l)throw new g("INTERNAL",`ctx.db.restore: table "${i}" is not a .softDelete() table`);const p=o[l]!==null&&o[l]!==void 0;if(await H.patch(n,t,{[l]:null}),p){const $=X(s,o);$!==null&&await te(i,async()=>await ee(i,t,void 0,{...$,[l]:null}))}},query(n){const t=f.tables[n];if(!t)throw new g("INTERNAL",`unknown table: ${n}`);const i="the legacy query()/withIndex() reader is not available on the D1 (global) backend; use findMany",o=[];let s=0,l;const p=d.name!=="mysql",$={...A(t),fieldRef:E=>e`m.${U(E)}`,rangeTypeGuard:()=>{throw new g("INTERNAL","a path range is never pushed into a search")}},h=E=>o.every(S=>S(E)),_=async(E,S)=>{await B();const y=2*An+E.filters.length,m=l===void 0?void 0:z(l,$,void 0,y),N=m!==void 0&&d.name==="sqlite"&&d.render(m).params.length+y>ui.boundParams,C=N?void 0:m,M=s>0||N,W=await Cn(c,d,t,n,C===void 0?E:{...E,scope:C},Ln(M?void 0:S));!M&&S===void 0&&bn(W);const Y=W.filter($e=>h($e));return S===void 0?Y:Y.slice(0,S)},w=E=>{const S={async*[Symbol.asyncIterator](){if(!E)throw new g("INTERNAL",i);yield*await _(E,void 0)},async collect(){if(!E)throw new g("INTERNAL",i);return _(E,void 0)},async collectWithScores(){throw new g("GLOBAL_SEARCH_SCORES_UNSUPPORTED",`collectWithScores() is not supported on \`.global()\` tables (table "${n}") — relevance scores are not yet surfaced on this backend; use .collect() instead`)},filter(y){o.push(y);const m=si(y);return m!==void 0&&ai(m,t.shape,p)?l=F(l,m):s+=1,S},async first(){if(!E)throw new g("INTERNAL",i);return(await _(E,1))[0]??null},order(){return S},async paginate(y){if(!E)throw new g("INTERNAL",i);const m=vn(y);return In(await _(E,Nn(m)),m)},async take(y){if(!E)throw new g("INTERNAL",i);return _(E,y)},async unique(){if(!E)throw new g("INTERNAL",i);const y=await _(E,2);if(y.length>1)throw new li(`unique() on table "${n}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(){throw new g("INTERNAL",`geo indexes are not supported on \`.global()\` tables (table "${n}") — geospatial queries run only on sharded tables`)},withIndex(){throw new g("INTERNAL",i)},withSearchIndex(y,m){const N=(t.searchIndexes??[]).find(M=>M.name===y);if(!N)throw new g("INTERNAL",`unknown search index "${y}" on table "${n}"`);const C={definition:N,field:N.field,filters:[],hasQuery:!1,indexName:y,query:""};if(m(Tn(C,n,Sn(N.language))),!C.hasQuery)throw new g("INTERNAL",`search index "${y}" on table "${n}" requires a .search(field, query) call`);return w(C)}};return S};return w(void 0)},async rank(n,t,i){const o=f.tables[n];if(!o)throw new g("INTERNAL",`unknown table: ${n}`);const s=o.rankIndexes?.find(W=>W.name===t);if(!s)throw new g("INTERNAL",`unknown rankIndex "${t}" on table "${n}"`);if(i.restrictsCounts)throw new yt(n);if(await B(),!await Pe(n,s))return null;const p=typeof i.row=="string"?i.row:i.row._id;if(!p)return null;const $=_e(n,s.name),h=s.sortBy.map((W,Y)=>Re(Y)),_=re(["__partition__",...h]),E=(await I(c,d,e`SELECT ${_} FROM ${e.identifier($)} WHERE ${e.identifier("__id__")} = ${p}`))[0];if(!E)return null;const S=E.__partition__,y=F(i.baseWhere,i.where);Et(y,f,n,"rank");const m=pt(s,y);if(m&&Me(s.partitionBy??[],m)!==S)return null;const N=Oi(d.name,s,h,E,p),C=await I(c,d,e`SELECT COUNT(*) AS c FROM ${e.identifier($)} WHERE ${e.identifier("__partition__")} = ${S} AND (${N})`),M=await I(c,d,e`SELECT COUNT(*) AS c FROM ${e.identifier($)} WHERE ${e.identifier("__partition__")} = ${S}`);return{position:Number(C[0]?.c??0)+1,total:Number(M[0]?.c??0)}},async rankPage(n,t,i={}){Et(F(i.baseWhere,i.where),f,n,"rankPage");const o=f.tables[n];if(!o)throw new g("INTERNAL",`unknown table: ${n}`);const s=o.rankIndexes?.find(k=>k.name===t);if(!s)throw new g("INTERNAL",`unknown rankIndex "${t}" on table "${n}"`);if(await B(),!await Pe(n,s))return{continueCursor:null,isDone:!0,page:[]};const p=_e(n,s.name),$=s.sortBy.map((k,ne)=>Re(ne)),h=Math.max(1,Math.min(1e3,Math.floor(i.take??100))),_=F(i.baseWhere,i.where),w=pt(s,_),E=ki(s,$),S=e.join(E.flatMap(k=>Qt(d,{direction:k.direction,field:k.column,nullable:k.nullable})),e`, `),y=[];typeof i.partitionKey=="string"?y.push(e`${e.identifier("__partition__")} = ${i.partitionKey}`):w&&y.push(e`${e.identifier("__partition__")} = ${Me(s.partitionBy??[],w)}`);const m=Fn(i);if(m!==void 0){const k=qi(d.name,E,m);k!==void 0&&y.push(k)}const N=re([Se,"__partition__",...$]);let C=e`SELECT ${N} FROM ${e.identifier(p)}`;y.length>0&&(C=e`${C} WHERE ${e.join(y,e` AND `)}`),C=e`${C} ORDER BY ${S} LIMIT ${e.raw(String(h+1))}`;const M=await I(c,d,C),W=M.length>h,Y=W?M.slice(0,h):M,$e=Y.map(k=>k[Se]),Ne=await Di(c,d,o,n,$e);let he=null;const j=Y.at(-1);if(W&&j!==void 0){const k=[j.__partition__,...$.map(ne=>j[ne]),j[Se]];he=Bi(k)}return{continueCursor:he,isDone:!W,page:Ne}},async replace(n,t,i,o){Ke("replace",i);const s=await me(t,n);if(!s)throw new g("INTERNAL",`document not found: ${t}`);const l=f.tables[s];if(!l)throw new g("INTERNAL",`document not found: ${t}`);const p=await Ce(s,t);if(p===void 0)throw new g("INTERNAL",`document not found: ${t}`);const h=Wn(f,s,"update")||(l.aggregateIndexes??[]).length>0||(l.rankIndexes??[]).length>0?X(l,p)??void 0:void 0,_=o?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,w=typeof p._creationTime=="number"?p._creationTime:void 0,E=_??w??b(),S={...i,_creationTime:E,_id:t};Je(l,i,S,Z);const y=Ge(l,S,{previous:()=>h??X(l,p)??void 0,supplied:i,trusted:o?.allowExplicitId===!0});Ze(d.name,y),G(s,"before","update")&&await V("before","update",{doc:{...y},id:t,op:"update",previous:h,table:s}),await Ie(s),await Ae(s);const m=Object.keys(l.shape),N=e.join([e`${e.identifier("_creationTime")} = ${E}`,...m.map(C=>e`${e.identifier(C)} = ${oe(l,C,y[C]??null)}`)],e`, `);await He(s,"UPDATE",N,p),await te(s,async()=>[...await fe(s,h,y),...await ee(s,t,h,y),...le(s,t,"update",y)]),await we(s,t,{document:y,previous:h,written:je(p,E)}),G(s,"after","update")&&await V("after","update",{doc:y,id:t,op:"update",previous:h,table:s})}};return lt={db:H,scheduler:rn},H};export{Eo as createSqlCtxDb,Ro as decodeGlobalRow,zi as readSqlCdcChangedTables,_o as readSqlCdcChanges,tn as readSqlCdcFloor,Pi as runSqlCdcMigration,ji as sweepSqlCdcRetention};