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