@lunora/sql-store 1.0.0-alpha.203 → 1.0.0-alpha.205

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