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