@lunora/do 1.0.0-alpha.51 → 1.0.0-alpha.53
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.d.mts +136 -40
- package/dist/index.d.ts +136 -40
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-CjgwJp2Q.mjs +1 -0
- package/dist/packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-Dicm4iLF.mjs +3 -0
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-BRdmX7WW.mjs → DEFAULT_MAX_RELATION_KEYS-BcW3nUKL.mjs} +1 -1
- package/dist/packem_shared/NotUniqueError-BDYkMtJP.mjs +1 -0
- package/dist/packem_shared/{ROOT_DO_SIZE_WARN_BYTES-oZjI_5uF.mjs → ROOT_DO_SIZE_WARN_BYTES-jp8WQaE9.mjs} +16 -16
- package/dist/packem_shared/{applyOnDelete-BvQN7pDL.mjs → applyOnDelete-CafQWSqu.mjs} +1 -1
- package/dist/packem_shared/applySelect-B0CF8T7y.mjs +1 -0
- package/dist/packem_shared/backfillAggregateIndexes-DUrhkmiz.mjs +1 -0
- package/dist/packem_shared/ctx-db-backfill-C4rAzsQo.mjs +1 -0
- package/dist/packem_shared/ctx-db-shapes-CHC2cS0g.mjs +1 -0
- package/dist/packem_shared/do-sql-x0AjZhaN.mjs +1 -0
- package/dist/packem_shared/{isSoftDeleted-BvhQov04.mjs → isSoftDeleted-juJOq515.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-BFmT9gsw.mjs → materializeExternalRows-BUmj_9WO.mjs} +1 -1
- package/dist/packem_shared/runShardMigrations-CcSFXtXZ.mjs +5 -0
- package/dist/packem_shared/{selectExpiredIds-BGVP3d8-.mjs → selectExpiredIds-BXJDiUtz.mjs} +1 -1
- package/dist/packem_shared/{serveRelationFanout-Ct5D2Tbk.mjs → serveRelationFanout-CK8xbCFx.mjs} +1 -1
- package/package.json +4 -3
- package/dist/packem_shared/ADMIN_FUNCTIONS-PxZ8Lr9e.mjs +0 -1
- package/dist/packem_shared/NotUniqueError-GI79LNJB.mjs +0 -1
- package/dist/packem_shared/applySelect-Bq2KOrkL.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-BAQ3Fwwh.mjs +0 -1
- package/dist/packem_shared/buildFtsMatch-CV0Z7PWv.mjs +0 -1
- package/dist/packem_shared/ctx-db-shapes-DzX_H5q8.mjs +0 -1
- package/dist/packem_shared/do-sql-BYIQTG3z.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-bxOHpfID.mjs +0 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{distinctValues as O}from"./applyOnDelete-
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{distinctValues as O}from"./applyOnDelete-CafQWSqu.mjs";const k="__relationExists",f={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},R=new Set(Object.keys(f)),A=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},j=5e3,u=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],g=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},p=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>R.has(n))},d=(e,t,n)=>{const a=t.tables[n]?.relationMap??{};return Object.keys(e).some(s=>{const r=e[s];return s==="AND"||s==="OR"?b(r).some(o=>d(o,t,n)):s==="NOT"?d(r??{},t,n):!!a[s]&&p(r)})},I=(e,t,n,a)=>{if(e&&d(e,t,n))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${a}() — use them in findMany/findFirst or an RLS read policy`)},E=async(e,t,n,a,s)=>{const r=await c(t,e.table,a),{page:o}=await a.fetcher(e.table,{baseWhere:a.relationBaseWhere?.(e.table),relationBaseWhere:a.relationBaseWhere,where:r}),i=O(o,n);if(i.length>a.maxRelationKeys){if(s)return u;throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(a.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},T=async(e,t,n,a,s)=>{const r=f[e];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);const{clause:o,project:i}=A(t),l=await E(t,r.negateChild?{NOT:n}:n,i,a,s);return l===u?u:r.negated?r.nullDisjunct?{OR:[{[o]:{notIn:l}},{[o]:{isNull:!0}}]}:{[o]:{notIn:l}}:{[o]:{in:l}}},m=async(e,t,n,a,s)=>{const r=f[e];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);const o=s.relationBaseWhere?.(t.table),i=r.negateChild?{NOT:n}:n,l={childWhere:await c(o?{AND:[o,i]}:i,t.table,s),negated:r.negated,parentTable:a,relation:t};return{[k]:l}},$=(e,t,n)=>{const a=f[e];if(a&&a.kind!==n.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${a.kind} relation, but "${t}" is to-${n.kind}`)},x=async(e,t,n,a,s)=>{const r=[];for(const o of Object.keys(n)){$(o,e,t);const i=n[o]??{},l=s.canPushExists?.(t)??!1;if(l&&s.existsPushMode==="always"){r.push(await m(o,t,i,a,s));continue}const w=await T(o,t,i,s,l);w===u?r.push(await m(o,t,i,a,s)):r.push(w)}return g(r)},S=async(e,t,n,a)=>{if(e==="AND"||e==="OR"){const r=[];for(const o of b(t))r.push(await c(o,n,a));return{[e]:r}}if(e==="NOT")return{NOT:await c(t??{},n,a)};const s=a.schema.tables[n]?.relationMap?.[e];return s&&p(t)?x(e,s,t,n,a):{[e]:t}},c=async(e,t,n)=>{const a=[];for(const s of Object.keys(e))a.push(await S(s,e[s],t,n));return g(a)},L=async(e,t)=>!e||!d(e,t.schema,t.tableName)?e:c(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??j,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),y=(e,t,n)=>{for(const a of e){const s=N(a,t,n);if(s)return s}},D=(e,t,n,a)=>{if(e==="AND"||e==="OR")return y(b(t),n,a);if(e==="NOT")return y([t??{}],n,a);const s=n.tables[a]?.relationMap?.[e];if(!(!s||!p(t)))return n.tables[s.table]?.shardMode?.kind==="shardBy"?{relation:e,target:s.table}:y(Object.values(t),n,s.table)},N=(e,t,n)=>{for(const a of Object.keys(e)){const s=D(a,e[a],t,n);if(s)return s}},M=(e,t,n)=>{if(!e)return;const a=N(e,t,n);if(a)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${a.target}" via relation "${a.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${n}", or (b) moving "${a.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{j as DEFAULT_MAX_RELATION_KEYS,I as assertFlatPredicate,M as assertShapeShardable,d as containsRelationPredicate,p as isRelationPredicate,L as resolveRelationPredicates};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{searchTextUnchanged as Tt,ftsTableName as dt,FTS_ID_COLUMN as be,FTS_TEXT_COLUMN as Nt,analyzedSearchText as ct,createSearchBuilder as St,createSearchAnalyzer as Ve,planSearchPage as Rt,finishSearchPage as At,searchPageScan as It,resolveSearchScan as vt,assertSearchWithinCap as Ct,tokenizeSearch as ft,searchTermRange as kt,scoreDocument as Mt,MAX_SEARCH_SCAN as Lt}from"@lunora/search-core";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as Fe,aggregateSqlFunction as Ne,normalizeCountArgument as xt,throwingScheduler as Ot}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as de,foldAggregateTally as Dt,aggregateTableName as Se,coerceAggregateNumber as qe,readAggregateValue as Ue}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as re,CountRlsUnsupportedError as Pe,selectIndexForGroupBy as Wt,selectIndexForCount as Bt,selectIndexForAggregate as Ft}from"./CountRlsUnsupportedError-Cl8XpYDL.mjs";import{Y as qt}from"./ctx-db-backfill-C4rAzsQo.mjs";import{o as fi,H as ui,P as hi,X as $i}from"./ctx-db-backfill-C4rAzsQo.mjs";import{appendCdcChange as Ut}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{CDC_LOG_TABLE as mi,applyCdcChanges as wi,bumpCdcEpoch as gi,minCdcSeq as Ei,readCdcChanges as bi,readCdcCursor as yi,readCdcEpoch as _i,trimCdcChanges as Ti}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{r as M}from"./do-exec-BLe9lLrN.mjs";import{b as ut,s as Z,g as he,a as ce,_ as te,m as X,T as ht,E as Le,$ as ee,l as Pt,L as $t,N as pt,S as Xe}from"./do-sql-x0AjZhaN.mjs";import{param as Ye}from"./renderSql-B5lF5Jd9.mjs";import{encodeGeohash as Ht,GEO_DEFAULT_PRECISION as jt,coveringGeohashes as Gt,boundingBoxGeohashes as Jt,pointInBoundingBox as Vt,haversineMeters as Yt}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{sortColumnName as Ae,matchesRankStaticWhere as mt,encodePartitionKey as De,rankTableName as Ie,resolveRankPartition as wt,RANK_TIEBREAK as me}from"./RANK_TIEBREAK-DtX8zQyc.mjs";import{t as fe}from"./serialize-sql-DiRzL7A4.mjs";import{SCAN_DEP as Q}from"./SCAN_DEP-D_yR9EeV.mjs";import{decodeCursor as Oe,normalizeOrderKeys as zt,buildSeekWhere as gt,applySelect as Ze,encodeCursor as Ge,softDeleteScope as Ee,buildSeekBeforeWhere as Kt}from"./applySelect-B0CF8T7y.mjs";import Qt from"./NotFoundError-J3tjf4Uo.mjs";import{assertFlatPredicate as He,resolveRelationPredicates as et}from"./DEFAULT_MAX_RELATION_KEYS-BcW3nUKL.mjs";import{runRowValidators as je,resolveWith as tt,applyOnDelete as Xt,fanOutScalarCounts as Zt}from"./applyOnDelete-CafQWSqu.mjs";import{guardWriter as en}from"./RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{createSystemReader as tn}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as Re}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as nn}from"./hasTrigger-_rexbWMO.mjs";import{compileWhereSql as ue}from"./compileWhereSql-BLcfs4QW.mjs";import{e as Si,t as Ri,r as Ai,o as Ii,l as vi,p as Ci,_ as ki,a as Mi,b as Li,d as xi,m as Oi,u as Di,S as Wi,T as Bi}from"./ctx-db-idempotency-wiVoGnpQ.mjs";import{runShardMigrations as qi}from"./runShardMigrations-CcSFXtXZ.mjs";import{a as Pi,s as Hi}from"./ctx-db-shapes-CHC2cS0g.mjs";const on=(o,r,n)=>[...o.partitionBy??[],...o.sortBy.map(l=>l.field),...o.where?Object.keys(o.where):[]].every(l=>r[l]===n[l]),rn=(o,r,n,l,s,c)=>{if(s&&c&&on(n,s,c))return;const E=Ie(r,n.name);if(s&&M(o,e`DELETE FROM ${e.identifier(E)} WHERE ${e.identifier("__id__")} = ${l}`),!c||n.where&&!mt(c,n.where))return;const m=n.sortBy.map((b,h)=>Ae(h)),_=e.join(["__id__","__partition__",...m].map(b=>e.identifier(b)),e`, `),v=De(n.partitionBy??[],c),L=n.sortBy.map(b=>fe(c[b.field]??null)),T=e.join([l,v,...L].map(b=>Ye(b)),e`, `);M(o,e`INSERT INTO ${e.identifier(E)} (${_}) VALUES (${T})`)},an=o=>{const{broadcast:r,invalidateCache:n,recordCdc:l,schema:s,sql:c}=o,E=new Set,m=new Set,_=(N,w)=>{const S=`${N}::${w.name}`;if(E.has(S))return;const F=Se(N,w.name),W=w.by??[],j=new Map,q=M(c,e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(N)}`).toArray();for(const U of q){const x=he(U);if(!x||w.where&&!Fe(x,w.where))continue;const G=de(W,x);Dt(j,G,w,x)}M(c,e`DELETE FROM ${e.identifier(F)}`);const J=32,B=[...j];for(let U=0;U<B.length;U+=J){const x=B.slice(U,U+J),G=e.join(x.map(([H,Y])=>e`(${H}, ${Y.value}, ${Y.count})`),e`, `);M(c,e`INSERT INTO ${e.identifier(F)} (${ce}, ${te}, ${X}) VALUES ${G}`)}E.add(S)},v=(N,w,S)=>{const F=w.by??[],W=Ne(w.op),j=w.field??"",q=[];for(const U of F){const x=fe(S[U]??null);x===null?q.push(e`${ee(U)} IS NULL`):q.push(e`${ee(U)} = ${x}`)}for(const[U,x]of Object.entries(w.where??{})){const G=x!==null&&typeof x=="object"&&!Array.isArray(x)?x.eq:x,H=fe(G);H===null?q.push(e`${ee(U)} IS NULL`):q.push(e`${ee(U)} = ${H}`)}const J=q.length>0?e` WHERE ${e.join(q,e` AND `)}`:e``,B=ee(j);return{value:M(c,e`SELECT ${e.raw(W)}(${B}) AS value FROM ${e.identifier(N)}${J}`).one().value??null}},L=(N,w,S,F)=>{const W=Se(N,w.name),{op:j}=w,q=w.field??"",J=x=>{M(c,e`DELETE FROM ${e.identifier(W)} WHERE ${ce} = ${x} AND ${X} <= 0`)},B=S&&(!w.where||Fe(S,w.where))?S:void 0,U=F&&(!w.where||Fe(F,w.where))?F:void 0;if(!(!B&&!U)){if(j==="count"){for(const[x,G]of[[B,-1],[U,1]]){if(!x)continue;const H=de(w.by??[],x);M(c,Le(W,H,G,G,e`${te} = ${te} + excluded.${te}, ${X} = ${X} + excluded.${X}`))}B&&J(de(w.by??[],B));return}if(j==="sum"||j==="avg"){for(const[x,G]of[[B,-1],[U,1]]){if(!x)continue;const H=qe(x[q]);if(H===void 0)continue;const Y=de(w.by??[],x);M(c,Le(W,Y,G*H,G,e`${te} = COALESCE(${te}, 0) + excluded.${te}, ${X} = ${X} + excluded.${X}`))}B&&J(de(w.by??[],B));return}if(B){const x=de(w.by??[],B),G=qe(B[q]),H=M(c,e`SELECT ${te} AS value, ${X} AS count FROM ${e.identifier(W)} WHERE ${ce} = ${x}`).toArray()[0],Y=(H?.count??0)-1;if(Y<=0)M(c,e`DELETE FROM ${e.identifier(W)} WHERE ${ce} = ${x}`);else if(H&&G!==void 0&&H.value!==null&&G===H.value){const ie=v(N,w,B);M(c,e`UPDATE ${e.identifier(W)} SET ${te} = ${ie.value}, ${X} = ${Y} WHERE ${ce} = ${x}`)}else M(c,e`UPDATE ${e.identifier(W)} SET ${X} = ${X} - 1 WHERE ${ce} = ${x}`)}if(U){const x=de(w.by??[],U),G=qe(U[q]);if(G===void 0)M(c,Le(W,x,null,1,e`${X} = ${X} + 1`));else{const H=j==="min"?"MIN":"MAX";M(c,Le(W,x,G,1,e`${te} = ${e.raw(H)}(COALESCE(${te}, excluded.${te}), excluded.${te}), ${X} = ${X} + 1`))}}}},T=N=>{const w=s.tables[N]?.aggregateIndexes;if(!(!w||w.length===0))for(const S of w)_(N,S)},b=(N,w,S)=>{const F=s.tables[N]?.aggregateIndexes;if(!(!F||F.length===0))for(const W of F)L(N,W,w,S)},h=(N,w)=>{const S=`${N}::rank::${w.name}`;if(m.has(S))return;const F=Ie(N,w.name),W=M(c,e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(N)}`).toArray();M(c,e`DELETE FROM ${e.identifier(F)}`);const j=w.sortBy.map((J,B)=>Ae(B)),q=e.join(["__id__","__partition__",...j].map(J=>e.identifier(J)),e`, `);for(const J of W){const B=he(J);if(!B||w.where&&!mt(B,w.where))continue;const U=De(w.partitionBy??[],B),x=w.sortBy.map(H=>fe(B[H.field]??null)),G=e.join([B._id,U,...x].map(H=>Ye(H)),e`, `);M(c,e`INSERT INTO ${e.identifier(F)} (${q}) VALUES (${G})`)}m.add(S)},k=N=>{const w=s.tables[N]?.rankIndexes;if(!(!w||w.length===0))for(const S of w)h(N,S)},C=(N,w,S,F)=>{const W=s.tables[N]?.rankIndexes;if(!(!W||W.length===0))for(const j of W)rn(c,N,j,w,S,F)},I=(N,w,S,F)=>{const W=s.tables[N]?.searchIndexes;if(!(!W||W.length===0||!ut(c)))for(const j of W){if(Tt(F,S,j))continue;const q=dt(N,j.name);M(c,e`DELETE FROM ${e.identifier(q)} WHERE ${e.identifier(be)} = ${w}`),S&&M(c,e`INSERT INTO ${e.identifier(q)} (${e.identifier(Nt)}, ${e.identifier(be)}) VALUES (${ct(S,j)}, ${w})`)}},P=(N,w,S)=>{const F=s.tables[N]?.geoIndexes;if(!(!F||F.length===0))for(const W of F){const j=ht(N,W.name);M(c,e`DELETE FROM ${e.identifier(j)} WHERE ${e.identifier("__id__")} = ${w}`);const q=S?.[W.field];if(q!==null&&typeof q=="object"&&typeof q.lat=="number"&&typeof q.lng=="number"){const{lat:J,lng:B}=q,U=Ht({lat:J,lng:B},W.precision??jt);M(c,e`INSERT INTO ${e.identifier(j)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${w}, ${U}, ${J}, ${B})`)}}};return{ensureBackfilledForTable:T,ensureBackfilledIndex:_,ensureRankBackfilled:h,ensureRankBackfilledForTable:k,syncAggregates:b,syncCompanionsForInsert:(N,w,S)=>{I(N,w,S),P(N,w,S),b(N,void 0,S),C(N,w,void 0,S),n(N,w),l(N,w,"insert",S),r({key:w,op:"insert",row:S,table:N})},syncGeo:P,syncRanks:C,syncSearch:I}},sn="__doc__",ln=o=>{const r=JSON.stringify(o),n=new TextEncoder().encode(r);let l="";for(const s of n)l+=String.fromCodePoint(s);return btoa(l)},dn=o=>o.after?[o.after.partitionKey,...o.after.sortValues,o.after.rowId]:o.cursor?Oe(o.cursor):void 0,cn=(o,r,n)=>{if(o?.length!==1+r.length+1)return;const l=[{column:"__partition__",direction:"asc"}];for(const[c,E]of r.entries())l.push({column:E,direction:n[c]?.direction??"asc"});l.push({column:me,direction:"asc"});const s=[];for(const[c,E]of l.entries()){const m=[];for(const[v,L]of l.slice(0,c).entries())m.push(e`${e.identifier(L.column)} IS ${o[v]}`);m.push(e`${e.identifier(E.column)} ${e.raw(E.direction==="desc"?"<":">")} ${o[c]}`);const[_]=m;s.push(m.length===1&&_!==void 0?_:e`(${e.join(m,e` AND `)})`)}return e`(${e.join(s,e` OR `)})`},Et=null,fn=(o,r)=>{if(o===void 0)return Et;const n=[o.__partition__,...r.map(l=>o[l]),o[me]];return ln(n)},un=(o,r,n)=>{const l=[];for(const s of o){const c=s[me];if(typeof c!="string")continue;const E=r.get(c);if(!E)continue;const m=typeof s.__partition__=="string"?s.__partition__:"",_=n.map(v=>s[v]??null);l.push({doc:E,key:{partitionKey:m,rowId:c,sortValues:_}})}return l},hn=(o,r,n)=>{const{rowToDocument:l}=o,s=new Map;if(n.length===0)return s;const c=e.join(n.map(m=>Ye(m)),e`, `),E=M(o.sql,e`SELECT id, _creationTime, ${e.identifier(sn)} FROM ${e.identifier(r)} WHERE id IN (${c})`).toArray();for(const m of E){const _=l(m),v=m.id;_&&typeof v=="string"&&s.set(v,_)}return s},nt=(o,r,n,l)=>{const{assertRankPartitionLocal:s,ensureRankBackfilled:c,onRead:E,schema:m}=o,_=m.tables[r];if(!_)throw new A("INTERNAL",`unknown table: ${r}`);const v=_.rankIndexes?.find(Y=>Y.name===n);if(!v)throw new A("INTERNAL",`unknown rankIndex "${n}" on table "${r}"`);s(r,_,v),E(r,Q),c(r,v);const L=Ie(r,v.name),T=v.sortBy.map((Y,ie)=>Ae(ie)),b=Math.max(1,Math.min(1e3,Math.floor(l.take??100))),h=re(l.baseWhere,l.where),k=wt(v,h),C=[e`${e.identifier("__partition__")} ASC`];for(const[Y,ie]of T.entries()){const se=v.sortBy[Y]?.direction;C.push(e`${e.identifier(ie)} ${e.raw(se==="desc"?"DESC":"ASC")}`)}C.push(e`${e.identifier(me)} ASC`);const I=[];typeof l.partitionKey=="string"?I.push(e`${e.identifier("__partition__")} = ${l.partitionKey}`):k&&I.push(e`${e.identifier("__partition__")} = ${De(v.partitionBy??[],k)}`);const P=dn(l),N=cn(P,T,v.sortBy);N&&I.push(N);const w=e.identifier(me),S=e.identifier("__partition__"),F=I.length>0?e` WHERE ${e.join(I,e` AND `)}`:e``,W=T.length>0?e`${w}, ${S}, ${e.join(T.map(Y=>e.identifier(Y)),e`, `)}`:e`${w}, ${S}`,j=e`SELECT ${W} FROM ${e.identifier(L)}${F} ORDER BY ${e.join(C,e`, `)} LIMIT ${e.raw(String(b+1))}`,q=M(o.sql,j).toArray(),J=q.length>b,B=J?q.slice(0,b):q,U=B.map(Y=>Y[me]),x=un(B,hn(o,r,U),T),G=J?fn(B.at(-1),T):Et,H=v.sortBy.map(Y=>Y.direction==="desc"?"desc":"asc");return{continueCursor:G,directions:H,hasMore:J,rows:x}},$n=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,pn=o=>{if(!$n.test(o))throw new A("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},it=50,bt=500,ge=(o,r,n)=>{const l=r??bt;if(o>l)throw new A("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(o)} exceeds the limit of ${String(l)} (raise options.limit or chunk the call)`,{status:400})},mn=o=>{const r={eq:(n,l)=>(o.sqlConditions.push({comparator:"=",field:n,value:l}),r),gt:(n,l)=>(o.sqlConditions.push({comparator:">",field:n,value:l}),r),gte:(n,l)=>(o.sqlConditions.push({comparator:">=",field:n,value:l}),r),lt:(n,l)=>(o.sqlConditions.push({comparator:"<",field:n,value:l}),r),lte:(n,l)=>(o.sqlConditions.push({comparator:"<=",field:n,value:l}),r)};return r},wn=o=>Math.max(o,Lt),gn=(o,r,n,l,s)=>{const c=ft(n.query,Ve(n.definition.language));if(c.length===0)return[];const E=dt(r,n.indexName),m=`${E}__vocab`,_=c.length-1,v=c.map((C,I)=>{const P=kt(C,I===_),N=P.exact?e`${e.identifier("term")} = ${P.lower}`:e`${e.identifier("term")} >= ${P.lower} AND ${e.identifier("term")} < ${P.upper}`;return e`SELECT ${e.identifier("doc")}, ${e.raw(String(I))} AS ${e.identifier("__term__")}, COUNT(*) AS ${e.identifier("__n__")} FROM ${e.identifier(m)} WHERE ${N} GROUP BY ${e.identifier("doc")}`}),L=c.map((C,I)=>e`SUM(CASE WHEN u.${e.identifier("__term__")} = ${e.raw(String(I))} THEN u.${e.identifier("__n__")} ELSE 0 END)`),T=e`SELECT f.${e.identifier(be)} AS ${e.identifier(be)}, ${e.join(L,e` + `)} AS ${e.identifier("__score__")} FROM (${e.join(v,e` UNION ALL `)}) u JOIN ${e.identifier(E)} f ON f.rowid = u.${e.identifier("doc")} GROUP BY f.${e.identifier(be)} HAVING ${e.join(L.map(C=>e`${C} > 0`),e` AND `)}`,b=[];for(const C of n.filters)b.push(e`${ee(C.field)} = ${fe(C.value)}`);s&&b.push(s);let h=e`SELECT m.id, m._creationTime, m.${e.identifier(Z)} FROM (${T}) s JOIN ${e.identifier(r)} m ON m.id = s.${e.identifier(be)}`;b.length>0&&(h=e`${h} WHERE ${e.join(b,e` AND `)}`),h=e`${h} ORDER BY s.${e.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${e.raw(String(l))}`;const k=[];for(const C of M(o,h)){const I=pt(C);I&&k.push(I)}return k},En=(o,r,n,l,s)=>{const c=Ve(n.definition.language),E=ft(n.query,c);if(E.length===0)return[];const m=[];for(const T of n.filters)m.push(e`${ee(T.field)} = ${fe(T.value)}`);s&&m.push(s);let _=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(r)}`;m.length>0&&(_=e`${_} WHERE ${e.join(m,e` AND `)}`),_=e`${_} ORDER BY _creationTime DESC, id ASC LIMIT ${e.raw(String(wn(l)))}`;const v=M(o,_).toArray(),L=[];for(const T of v){const b=pt(T);if(!b)continue;const h=Mt(ct(b,n.definition),E,c);h>0&&L.push({creationTime:typeof b._creationTime=="number"?b._creationTime:0,doc:b,id:typeof b._id=="string"?b._id:"",score:h})}return L.sort((T,b)=>b.score-T.score||b.creationTime-T.creationTime||T.id.localeCompare(b.id)),L.slice(0,l).map(T=>T.doc)},bn=(o,r)=>{const n=o,l={near:(s,c)=>{if(n.within)throw new A("INTERNAL",`geo index "${n.indexName}" on table "${r}": call .near() or .within(), not both`);return n.near={point:{lat:s.lat,lng:s.lng},radiusMeters:c},l},within:s=>{if(n.near)throw new A("INTERNAL",`geo index "${n.indexName}" on table "${r}": call .near() or .within(), not both`);return n.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},l}};return l},yn=(o,r)=>{const n=o[r];if(n===null||typeof n!="object")return;const{lat:l,lng:s}=n;return typeof l=="number"&&typeof s=="number"?{lat:l,lng:s}:void 0},_n=(o,r)=>{const n=yn(o,r.definition.field);if(!n)return;const l=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const s=Yt(r.near.point,n);return s<=r.near.radiusMeters?{creationTime:l,distance:s}:void 0}return Vt(n,r.within)?{creationTime:l,distance:0}:void 0},Tn=(o,r,n,l,s)=>{if(!n.near&&!n.within)throw new A("INTERNAL",`geo index "${n.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const c=n.near?Gt(n.near.point,n.near.radiusMeters):Jt(n.within),E=ht(r,n.indexName),m=c.map(h=>e`(g.${e.identifier("__geohash__")} >= ${h} AND g.${e.identifier("__geohash__")} < ${`${h}{`})`),_=[e`(${e.join(m,e` OR `)})`];s&&_.push(s);const v=e`SELECT m.id, m._creationTime, m.${e.identifier(Z)} FROM ${e.identifier(E)} g JOIN ${e.identifier(r)} m ON m.id = g.${e.identifier("__id__")} WHERE ${e.join(_,e` AND `)}`,L=M(o,v).toArray(),T=[];for(const h of L){const k=he(h),C=k?_n(k,n):void 0;k&&C&&T.push({creationTime:C.creationTime,distance:C.distance,doc:k})}T.sort((h,k)=>h.distance-k.distance||k.creationTime-h.creationTime);const b=T.map(h=>h.doc);return typeof l=="number"?b.slice(0,Math.max(0,Math.floor(l))):b},Nn=(o,r,n,l,s)=>{const{geo:c}=n;if(!c)throw new A("INTERNAL","runGeoTerminal called without a staged geo query");const E=n.inMemoryFilters.length>0,m=Tn(o,r,c,E?void 0:s,l);if(!E)return m;const _=[];for(const v of m)if(n.inMemoryFilters.every(L=>L(v))&&(_.push(v),typeof s=="number"&&_.length>=s))break;return _},Sn=(o,r,n,l,s,c)=>{const E=[];for(const L of n.sqlConditions)E.push(e`${ee(L.field)} ${e.raw(L.comparator)} ${fe(L.value)}`);l&&E.push(l);let m=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(r)}`;E.length>0&&(m=e`${m} WHERE ${e.join(E,e` AND `)}`),m=e`${m} ORDER BY ${s}`,typeof c=="number"&&n.inMemoryFilters.length===0&&(m=e`${m} LIMIT ${e.raw(String(Math.max(0,Math.floor(c))))}`);const _=M(o,m).toArray(),v=[];for(const L of _){const T=he(L);if(T&&n.inMemoryFilters.every(b=>b(T))&&(v.push(T),typeof c=="number"&&v.length>=c))break}return v},pe={fieldRef:ee,serialize:fe},Rn=o=>{let r=0;const n=[],l={fieldRef:ee,relationExists:s=>{const{childWhere:c,negated:E,parentTable:m,relation:_}=s,v=`__rel_${String(r)}`,L=n.at(-1)??m;r+=1,o(_.table,Q);const T=_.kind==="one"?_.field:_.references,b=_.kind==="one"?_.references:_.field,h=e`${Xe(v,b)} = ${Xe(L,T)}`;n.push(v);const k=ue(c,l);n.pop();const C=k?e`${h} AND ${k}`:h,I=e`EXISTS (SELECT 1 FROM ${e.identifier(_.table)} AS ${e.identifier(v)} WHERE ${C})`;return E?e`NOT ${I}`:I},serialize:fe};return l},yt=o=>{const r=o.map(n=>e`${ee(n.field)} ${e.raw(n.direction==="desc"?"DESC":"ASC")}`);return o.some(n=>n.field==="_id"||n.field==="id")||r.push(e`${ee("id")} ASC`),e.join(r,e`, `)},An={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},In=o=>{const r=o.order;return o.indexFields.length>0?o.indexFields.map(n=>({direction:r,field:n})):[{direction:r,field:"_creationTime"}]},vn=(o,r,n,l)=>{const s=o.sqlConditions.map(c=>({[c.field]:{[An[c.comparator]??"eq"]:c.value}}));if(n&&s.push(gt(r,Oe(n))),l&&s.push(Kt(r,Oe(l))),s.length!==0)return s.length===1?s[0]:{AND:s}},Cn=(o,r,n)=>{const l=[];for(const s of o){const c=he(s);if(c&&r.every(E=>E(c))&&(l.push(c),n!==void 0&&l.length>n))break}return l},kn=(o,r,n,l,s)=>{const c=Math.max(0,Math.floor(l.numItems)),E=In(n),m=typeof l.endCursor=="string",_=ue(vn(n,E,l.cursor,l.endCursor),pe),v=s&&_?e`${_} AND ${s}`:s??_;let L=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(r)}`;v&&(L=e`${L} WHERE ${v}`),L=e`${L} ORDER BY ${yt(E)}`;const T=n.inMemoryFilters.length>0;!T&&!m&&(L=e`${L} LIMIT ${e.raw(String(c+1))}`);const b=M(o,L).toArray(),h=Cn(b,n.inMemoryFilters,T||m?void 0:c);if(m){const P=h.length>=2?h[Math.floor(h.length/2)-1]:void 0;return{continueCursor:l.endCursor??null,isDone:!0,page:h,splitCursor:P?Ge(P,E):null}}const k=h.length>c,C=k?h.slice(0,c):h,I=C.at(-1);return{continueCursor:k&&I?Ge(I,E):null,isDone:!k,page:C}};class Mn extends A{constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Ln=/\s/u,xn=String.fromCodePoint(0),ot=(o,r,n)=>{if(!o.tables[r])throw new A("INTERNAL",`unknown table: ${r}`);return typeof n!="string"||n.length===0||Ln.test(n)||n.includes(xn)?null:n},On=(o,r,n,l=()=>{})=>{const s=r.tables[n];if(!s)throw new A("INTERNAL",`unknown table: ${n}`);const c=Ee(s.softDeleteMode,void 0),E=c?ue(c,pe):void 0,m={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]},_=h=>{const{search:k}=m;if(!k)throw new A("INTERNAL","runSearchFetch called without a staged search");qt(o,n,s);const C=m.inMemoryFilters.length>0,I=vt(C?void 0:h),P=ut(o)?gn(o,n,k,I,E):En(o,n,k,I,E);if(!C)return h===void 0&&Ct(P),P;const N=[];for(const w of P)if(m.inMemoryFilters.every(S=>S(w))&&(N.push(w),typeof h=="number"&&N.length>=h))break;return N},v=h=>{const k=Rt(h);return At(_(It(k)),k)},L=()=>{const h=m.indexFields.length>0?m.indexFields:["_creationTime"],k=m.order==="desc"?"DESC":"ASC";return e.join(h.map(C=>e`${ee(C)} ${e.raw(k)}`),e`, `)},T=h=>m.search?_(h):m.geo?Nn(o,n,m,E,h):Sn(o,n,m,E,L(),h),b={async collect(){return T(void 0)},filter(h){return m.inMemoryFilters.push(h),b},async first(){return T(m.inMemoryFilters.length>0?void 0:1)[0]??null},order(h){return m.order=h==="desc"?"desc":"asc",b},async paginate(h){if(m.search)return v(h);if(m.geo)throw new A("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");return kn(o,n,m,h,E)},async take(h){return T(h)},async unique(){const h=T(m.inMemoryFilters.length>0?void 0:2);if(h.length>1)throw new Mn(`unique() on table "${n}" matched ${String(h.length)} documents; expected at most one`);return h[0]??null},withGeoIndex(h,k){const C=(s.geoIndexes??[]).find(P=>P.name===h);if(!C)throw new A("INTERNAL",`unknown geo index "${h}" on table "${n}"`);l(n,h,"geo");const I={definition:C,indexName:h};if(m.geo=I,k(bn(I,n)),!I.near&&!I.within)throw new A("INTERNAL",`geo index "${h}" on table "${n}" requires a .near(point, radius) or .within(box) call`);return b},withIndex(h,k){const C=s.indexes.find(I=>I.name===h);if(!C)throw new A("INTERNAL",`unknown index "${h}" on table "${n}"`);return l(n,h,"index"),m.indexName=h,m.indexFields=C.fields,k&&k(mn(m)),b},withSearchIndex(h,k){const C=(s.searchIndexes??[]).find(P=>P.name===h);if(!C)throw new A("INTERNAL",`unknown search index "${h}" on table "${n}"`);l(n,h,"search");const I={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:h,query:""};if(m.search=I,k(St(I,n,Ve(C.language))),!I.hasQuery)throw new A("INTERNAL",`search index "${h}" on table "${n}" requires a .search(field, query) call`);return b}};return b},rt=(o,r,n)=>{const l={...r};for(const[s,c]of $t(o)){if(c.serverDefault){l[s]=c.serverDefault({auth:n});continue}l[s]===void 0&&(c.defaultFn?l[s]=c.defaultFn():"defaultValue"in c&&(l[s]=c.defaultValue))}return l},at=(o,r,n,l)=>{const s=n;for(const[c,E]of $t(o)){if(E.serverDefault){c in r&&(s[c]=E.serverDefault({auth:l}));continue}E.onUpdateFn&&!(c in r)&&(s[c]=E.onUpdateFn())}},st=(o,r)=>{for(const n of Object.keys(r))if(r[n]===void 0)throw new A("INTERNAL",`Cannot ${o} field '${n}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Dn=/unique constraint failed/i,Wn=o=>o instanceof Error&&Dn.test(o.message),Je=(o,r,n)=>{try{M(o,n)}catch(l){throw Wn(l)?new Re(`unique constraint violation on "${r}"`,"unique"):l}},xe=(o,r,n)=>{if(Je(o,r,n),M(o,e`SELECT changes() AS changed`).one().changed===0)throw new Re(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},lt=(o,r,n,l,s,c,E)=>{const m=[];for(let T=0;T<n.length+1;T+=1){const b=[];for(let I=0;I<T;I+=1)b.push(e`${e.identifier(n[I])} IS ${c[I]}`);const h=n[T],k=l[T];if(h!==void 0&&k!==void 0){const I=k.direction==="desc"?">":"<";b.push(e`${e.identifier(h)} ${e.raw(I)} ${c[T]}`)}else b.push(e`${e.identifier(me)} < ${E}`);const[C]=b;m.push(b.length===1&&C!==void 0?C:e`(${e.join(b,e` AND `)})`)}const _=e.join(m,e` OR `),v=M(o,e`SELECT COUNT(*) AS c FROM ${e.identifier(r)} WHERE ${e.identifier("__partition__")} = ${s} AND (${_})`).one(),L=M(o,e`SELECT COUNT(*) AS c FROM ${e.identifier(r)} WHERE ${e.identifier("__partition__")} = ${s}`).one();return{before:v.c,total:L.c}},li=o=>{const{sql:r}=o,{schema:n}=o,l=o.broadcast??(()=>{}),s=o.onRead??(()=>{}),c=o.onIndexUse??(()=>{}),E=o.onWrite??(()=>{}),{cache:m}=o,_=o.clock??(()=>Date.now()),v=o.idGenerator??(()=>crypto.randomUUID()),L=o.scheduler??Ot,{globalDb:T}=o,b=o.auth??{identity:null,userId:null},h=o.cdc??!1,k=L,C=tn({scheduler:typeof k.list=="function"&&typeof k.get=="function"?k:void 0,storage:o.storage}),I=(t,i,a,p)=>{h&&Ut(r,_(),t,i,a,p)},P=t=>n.tables[t]?.shardMode?.kind==="global",N=(t,i)=>{if(P(t)){if(!T)throw new A("INTERNAL",`cross-backend ${i} for global table '${t}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return T}return z},w=t=>N(t,"cascade"),S=(t,i)=>{if(P(t)){if(!T)throw new A("INTERNAL",`${i} on global table '${t}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return T}},F=()=>T,W=(t,i)=>N(t,"relation load").findMany(t,i),j=(t,i)=>(P(t)&&s(t,Q),W(t,i)),q=t=>!P(t.table),J=o.relationExistsPushDown??"auto",B=J!=="never",{maxRelationKeys:U}=o,x=(t,i,a)=>et(t,{fetcher:j,maxRelationKeys:U,relationBaseWhere:a,schema:n,tableName:i}),G=async(t,i,a,p)=>{const $=S(t,"relation grouped count");if($)return s(t,Q),Zt((D,oe)=>$.count(D,oe),t,i,a,p);const f=n.tables[t];if(!f)throw new A("INTERNAL",`unknown table: ${t}`);s(t,Q);const d=Ee(f.softDeleteMode,void 0),u={[i]:{in:a}},g=re(re(u,p),d),R=await x(g,t,void 0),y=ue(R,pe),O=ee(i);let K=e`SELECT ${O} AS __fk__, COUNT(*) AS count FROM ${e.identifier(t)}`;y&&(K=e`${K} WHERE ${y}`),K=e`${K} GROUP BY ${O}`;const V=M(r,K).toArray();return new Map(V.map(D=>[D.__fk__,D.count]))};let H=0;const Y=new Set;for(const[t,i]of Object.entries(n.tables))for(const a of Object.values(i.triggerMap??{}))Y.add(`${t} ${a.timing} ${a.op}`);const ie=(t,i,a)=>Y.has(`${t} ${i} ${a}`),se=async(t,i,a)=>{if(H+=1,H>it)throw H-=1,new Re(`trigger recursion exceeded ${String(it)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await nn({ctx:_t,event:a,op:i,schema:n,tableName:a.table,timing:t})}finally{H-=1}},{ensureBackfilledForTable:ye,ensureBackfilledIndex:We,ensureRankBackfilled:Be,ensureRankBackfilledForTable:_e,syncAggregates:ve,syncCompanionsForInsert:ze,syncGeo:Ce,syncRanks:Te,syncSearch:ke}=an({broadcast:l,invalidateCache:(t,i)=>m?.invalidate(t,i),recordCdc:I,schema:n,sql:r}),Ke=(t,i,a)=>{const{shardMode:p}=i;if(p?.kind==="shardBy"&&!(p.field!==void 0&&(a.partitionBy??[]).includes(p.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${t}" partitions across shards (shard key "${p.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},$e=(t,i)=>{const a=Object.entries(n.tables).filter(([,R])=>R.shardMode?.kind!=="global").map(([R])=>R).filter(R=>i===void 0||R===i);if(a.length===0)return;const p=a.map(R=>e`SELECT ${e.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(R)} WHERE id = ${t}`),$=e`${e.join(p,e` UNION ALL `)} LIMIT 1`,[f]=M(r,$).toArray();if(!f)return;const d=f.__t__,u=he(f);if(typeof d!="string"||!u)return;const g=f[Z];return{docJson:typeof g=="string"?g:JSON.stringify(g??{}),row:u,tableName:d}},Qe={assertRankPartitionLocal:Ke,ensureRankBackfilled:Be,onRead:s,rowToDocument:he,schema:n,sql:r},z={system:C,async aggregate(t,i){const a=S(t,"aggregate");if(a)return s(t,Q),a.aggregate(t,i);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);if(Ne(i.op),i.op==="count")return z.count(t,{baseWhere:i.baseWhere,relationBaseWhere:i.relationBaseWhere,restrictsCounts:i.restrictsCounts,where:i.where});if(!i.field)throw new A("INTERNAL",`aggregate(${t}, { op: "${i.op}" }): "field" is required for non-count reducers`);s(t,Q);const $=Ee(p.softDeleteMode,void 0),f=re(re(i.baseWhere,i.where),$),d=await x(f,t,i.relationBaseWhere),u=d!==f;if(p.aggregateIndexes&&!i.baseWhere&&!u&&!$){const V=Ft(p.aggregateIndexes,i.op,i.field,i.where);if(V){We(t,V.index);const D=de(V.index.by??[],V.key),oe=Se(t,V.index.name),ae=M(r,e`SELECT ${te} AS value, ${X} AS count FROM ${e.identifier(oe)} WHERE ${ce} = ${D}`).toArray()[0];return Ue(i.op,ae)}}const g=ue(d,pe),R=Ne(i.op),y=ee(i.field);let O=e`SELECT ${e.raw(R)}(${y}) AS value FROM ${e.identifier(t)}`;return g&&(O=e`${O} WHERE ${g}`),M(r,O).toArray()[0]?.value??null},asId(t,i){const a=ot(n,t,i);if(a===null)throw new A("BAD_REQUEST",`asId("${t}", …): "${i}" is not a valid id for table "${t}"`,{status:400});return a},async count(t,i){const a=S(t,"count");if(a)return s(t,Q),a.count(t,i);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);const $=xt(i);if($.restrictsCounts)throw new Pe(t);s(t,Q);const f=Ee(p.softDeleteMode,void 0),d=re(re($.baseWhere,$.where),f),u=await x(d,t,$.relationBaseWhere),g=u!==d;if(p.aggregateIndexes&&!$.baseWhere&&!g&&!f){const O=Bt(p.aggregateIndexes,$.where);if(O){We(t,O.index);const K=de(O.index.by??[],O.key),V=Se(t,O.index.name),D=M(r,e`SELECT ${te} AS value FROM ${e.identifier(V)} WHERE ${ce} = ${K}`).toArray();return D[0]===void 0?0:D[0].value??0}}const R=ue(u,pe);let y=e`SELECT COUNT(*) AS count FROM ${e.identifier(t)}`;return R&&(y=e`${y} WHERE ${R}`),M(r,y).one().count},async delete(t,i,a){const p=$e(t,i);if(!p){const y=i===void 0?F():void 0;y&&await y.delete(t,void 0,a);return}const{docJson:$,row:f,tableName:d}=p,u=n.tables[d],g=a?.hard===!0,R=!g&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(R&&f[R]!==null&&f[R]!==void 0)){if(ie(d,"before","delete")&&await se("before","delete",{id:t,op:"delete",previous:f,table:d}),await Xt({deletedId:t,deletedReference:y=>f[y],findHolders:async(y,O,K)=>(await w(y).findMany(y,{includeDeleted:g,where:{[O]:K}})).page,onCascade:(y,O)=>w(y).delete(O,void 0,a),onRestrict:y=>{throw new Re(y,"restrict")},onSetNull:(y,O,K)=>w(y).patch(O,{[K]:null}),schema:n,tableName:d}),ye(d),_e(d),R){const y={...f,[R]:_(),_id:t};xe(r,d,e`UPDATE ${e.identifier(d)} SET ${e.identifier(Z)} = ${JSON.stringify(y)} WHERE id = ${t} AND ${e.identifier(Z)} = ${$}`),ke(d,t,y,f),Ce(d,t,void 0),ve(d,f,y),Te(d,t,f,void 0),m?.invalidate(d,t),I(d,t,"update",y),l({key:t,op:"update",row:y,table:d}),ie(d,"after","delete")&&await se("after","delete",{id:t,op:"delete",previous:f,table:d}),await E({id:t,op:"delete",table:d});return}xe(r,d,e`DELETE FROM ${e.identifier(d)} WHERE id = ${t} AND ${e.identifier(Z)} = ${$}`),ke(d,t,void 0),Ce(d,t,void 0),ve(d,f,void 0),Te(d,t,f,void 0),m?.invalidate(d,t),I(d,t,"delete"),l({key:t,op:"delete",table:d}),ie(d,"after","delete")&&await se("after","delete",{id:t,op:"delete",previous:f,table:d}),await E({id:t,op:"delete",table:d})}},async deleteAll(t,i){if(!n.tables[t])throw new A("INTERNAL",`unknown table: ${t}`);const a=Math.max(1,i?.chunkSize??bt),p=i?.hard===void 0?void 0:{hard:i.hard},$=P(t)?void 0:t;let f=0;for(;;){const d=(await z.findMany(t,{limit:a})).page.map(u=>String(u._id));if(d.length===0)break;for(const u of d)await z.delete(u,$,p),f+=1;if(d.length<a)break}return{deleted:f}},async deleteMany(t,i,a){ge(t.length,i?.limit,"deleteMany");for(const p of t)await z.delete(p,a);return{deleted:t.length}},async deleteWhere(t,i,a){const p=S(t,"deleteWhere");let $;if(p)$=(await p.findMany(t,{where:i})).page.map(f=>String(f._id));else{if(!n.tables[t])throw new A("INTERNAL",`unknown table: ${t}`);$=(await z.findMany(t,{where:i})).page.map(f=>String(f._id))}if(ge($.length,a?.limit,"deleteWhere"),z.deleteMany===void 0)throw new A("INTERNAL",`ctx.db.${t}.deleteMany is unavailable: this writer has no batch delete`);return z.deleteMany($,a)},async findFirst(t,i={}){return(await z.findMany(t,{...i,limit:1})).page[0]??null},async findFirstOrThrow(t,i={}){const a=await z.findFirst(t,i);if(a===null)throw new Qt(`findFirstOrThrow: no "${t}" document matched`);return a},async findMany(t,i={}){const a=S(t,"findMany");if(a)return s(t,Q),a.findMany(t,i);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);const $=!i.where&&!i.baseWhere;$?s(t,Q):s(t);const f=zt(i.orderBy),d=i.cursor?gt(f,Oe(i.cursor)):void 0;let u=re(i.baseWhere,i.where);u=re(u,Ee(p.softDeleteMode,i.includeDeleted)),u=await et(u,{canPushExists:B?q:void 0,existsPushMode:J==="always"?"always":"auto",fetcher:j,maxRelationKeys:U,relationBaseWhere:i.relationBaseWhere,schema:n,tableName:t}),d&&(u=u?{AND:[u,d]}:d);const g=B?Rn(s):pe,R=ue(u,g);let y=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(t)}`;R&&(y=e`${y} WHERE ${R}`),y=e`${y} ORDER BY ${yt(f)}`;const O=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0;O!==void 0&&(y=e`${y} LIMIT ${e.raw(String(O+1))}`);const K=M(r,y).toArray(),V=[];for(const le of K){const ne=he(le);ne&&(V.push(ne),!$&&typeof ne._id=="string"&&s(t,ne._id))}if(O===void 0)return i.with&&await tt({groupedCounter:G,fetcher:W,parents:V,relationBaseWhere:i.relationBaseWhere,schema:n,tableName:t,with:i.with}),{continueCursor:null,isDone:!0,page:Ze(V,i.select,i.with)};const D=V.length>O,oe=D?V.slice(0,O):V,ae=oe.at(-1);return i.with&&await tt({fetcher:W,groupedCounter:G,parents:oe,relationBaseWhere:i.relationBaseWhere,schema:n,tableName:t,with:i.with}),{continueCursor:D&&ae?Ge(ae,f):null,isDone:!D,page:Ze(oe,i.select,i.with)}},async get(t,i){const a=$e(t,i);if(!a){const p=i===void 0?F():void 0;return p?p.get(t):null}return s(a.tableName,t),a.row},async lookupById(t,i){const a=$e(t,i);return a?(s(a.tableName,t),{row:a.row,tableName:a.tableName}):null},async groupBy(t,i){const a=S(t,"groupBy");if(a)return s(t,Q),a.groupBy(t,i);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);s(t,Q);const $=i.agg??{op:"count"};if(Ne($.op),$.op!=="count"&&!$.field)throw new A("INTERNAL",`groupBy(${t}, { agg: { op: "${$.op}" } }): "field" is required for non-count reducers`);const f=Ee(p.softDeleteMode,void 0),d=re(re(i.baseWhere,i.where),f),u=await x(d,t,i.relationBaseWhere),g=u!==d;if(p.aggregateIndexes&&!i.baseWhere&&!g&&!f){const D=Wt(p.aggregateIndexes,$.op,$.field,i.by,i.where);if(D){We(t,D.index);const oe=Se(t,D.index.name),ae=Object.keys(D.partial),le=[];if(ae.length===(D.index.by??[]).length&&ae.length>0){const we=de(D.index.by??[],D.partial),Me=M(r,e`SELECT ${te} AS value, ${X} AS count FROM ${e.identifier(oe)} WHERE ${ce} = ${we}`).toArray();return Me.length>0&&le.push({key:{...D.partial},value:Ue($.op,Me[0])}),le}const ne=M(r,e`SELECT ${ce} AS key, ${te} AS value, ${X} AS count FROM ${e.identifier(oe)}`).toArray();for(const we of ne){const Me=JSON.parse(we.key);le.push({key:Me,value:Ue($.op,we)})}return le}}const R=ue(u,pe),y=i.by.map(D=>e`${ee(D)} AS ${e.identifier(D)}`);if($.op==="count")y.push(e`COUNT(*) AS value`);else{const{field:D}=$;if(D===void 0)throw new A("INTERNAL",`groupBy(${t}, { agg: { op: "${$.op}" } }): "field" is required for non-count reducers`);y.push(e`${e.raw(Ne($.op))}(${ee(D)}) AS value`)}let O=e`SELECT ${e.join(y,e`, `)} FROM ${e.identifier(t)}`;R&&(O=e`${O} WHERE ${R}`),O=e`${O} GROUP BY ${e.join(i.by.map(D=>ee(D)),e`, `)}`;const K=M(r,O).toArray(),V=[];for(const D of K){const oe={};for(const le of i.by)oe[le]=D[le]??null;const{value:ae}=D;V.push({key:oe,value:ae==null?null:Number(ae)})}return V},async insert(t,i,a){const p=S(t,"insert");if(p){const R=await p.insert(t,i,a);return l({key:R,op:"insert",row:{...i,_id:R},table:t}),R}const $=n.tables[t];if(!$)throw new A("INTERNAL",`unknown table: ${t}`);const f=rt($,i,b);je($,f);let d;a?.clientId!==void 0?(pn(a.clientId),d=a.clientId):a?.allowExplicitId&&typeof f._id=="string"?d=f._id:d=v();const u=a?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:_(),g={...f,_creationTime:u,_id:d};return ie(t,"before","insert")&&await se("before","insert",{doc:{...g},id:d,op:"insert",table:t}),ye(t),_e(t),Je(r,t,e`INSERT INTO ${e.identifier(t)} (id, _creationTime, ${e.identifier(Z)}) VALUES (${d}, ${u}, ${JSON.stringify(g)})`),ze(t,d,g),ie(t,"after","insert")&&await se("after","insert",{doc:g,id:d,op:"insert",table:t}),await E({doc:g,id:d,op:"insert",table:t}),d},async insertManyUnsafe(t,i,a){if(ge(i.length,a?.limit,"insertManyUnsafe"),i.length===0)return[];const p=S(t,"insert");if(p){const u=[];for(const g of i){const R=await p.insert(t,g,{allowExplicitId:a?.allowExplicitId});l({key:R,op:"insert",row:{...g,_id:R},table:t}),u.push(R)}return u}const $=n.tables[t];if(!$)throw new A("INTERNAL",`unknown table: ${t}`);ye(t),_e(t);const f=i.map(u=>{const g=rt($,u,b),R=a?.allowExplicitId===!0&&typeof g._id=="string"?g._id:v(),y=a?.allowExplicitId===!0&&typeof g._creationTime=="number"?g._creationTime:_();return{creationTime:y,document:{...g,_creationTime:y,_id:R},id:R}}),d=e.join(f.map(u=>e`(${u.id}, ${u.creationTime}, ${JSON.stringify(u.document)})`),e`, `);Je(r,t,e`INSERT INTO ${e.identifier(t)} (id, _creationTime, ${e.identifier(Z)}) VALUES ${d}`);for(const{document:u,id:g}of f)ze(t,g,u),await E({doc:u,id:g,op:"insert",table:t});return f.map(u=>u.id)},async insertMany(t,i,a){ge(i.length,a?.limit,"insertMany");const p=a?.skipDuplicates===!0,$=[];for(const f of i)try{$.push(await z.insert(t,f))}catch(d){if(p&&d instanceof Re&&d.kind==="unique")$.push(null);else throw d}return $},normalizeId(t,i){return ot(n,t,i)},async patch(t,i,a){const p=$e(t,a);if(!p){const R=a===void 0?F():void 0;if(R){await R.patch(t,i);return}throw new A("INTERNAL",`document not found: ${t}`)}const{docJson:$,row:f,tableName:d}=p,u=n.tables[d];if(!u)throw new A("INTERNAL",`unknown table: ${d}`);s(d,t),st("patch",i);const g={...f,...i,_id:t};at(u,i,g,b),je(u,g),ie(d,"before","update")&&await se("before","update",{doc:{...g},id:t,op:"update",previous:f,table:d}),ye(d),_e(d),xe(r,d,e`UPDATE ${e.identifier(d)} SET ${e.identifier(Z)} = ${JSON.stringify(g)} WHERE id = ${t} AND ${e.identifier(Z)} = ${$}`),ke(d,t,g,f),Ce(d,t,g),ve(d,f,g),Te(d,t,f,g),m?.invalidate(d,t),I(d,t,"update",g),l({key:t,op:"update",row:g,table:d}),ie(d,"after","update")&&await se("after","update",{doc:g,id:t,op:"update",previous:f,table:d}),await E({doc:g,id:t,op:"update",table:d})},async patchMany(t,i,a){ge(t.length,i?.limit,"patchMany");for(const p of t)await z.patch(p.id,p.patch,a);return{patched:t.length}},async patchWhere(t,i,a){const p=S(t,"patchWhere");let $;if(p)$=(await p.findMany(t,{where:i.where})).page.map(f=>({id:String(f._id),patch:i.patch}));else{if(!n.tables[t])throw new A("INTERNAL",`unknown table: ${t}`);$=(await z.findMany(t,{where:i.where})).page.map(f=>({id:String(f._id),patch:i.patch}))}if(ge($.length,a?.limit,"patchWhere"),z.patchMany===void 0)throw new A("INTERNAL",`ctx.db.${t}.patchMany is unavailable: this writer has no batch patch`);return await z.patchMany($,a),{patched:$.length}},query(t){const i=S(t,"query");return i?(s(t,Q),i.query(t)):(s(t,Q),On(r,n,t,c))},async rank(t,i,a){const p=S(t,"rank");if(p)return s(t,Q),p.rank(t,i,a);c(t,i,"rank");const $=n.tables[t];if(!$)throw new A("INTERNAL",`unknown table: ${t}`);const f=$.rankIndexes?.find(ne=>ne.name===i);if(!f)throw new A("INTERNAL",`unknown rankIndex "${i}" on table "${t}"`);if(Ke(t,$,f),a.restrictsCounts)throw new Pe(t);s(t,Q),Be(t,f);const d=typeof a.row=="string"?a.row:a.row._id;if(!d)return null;const u=Ie(t,f.name),g=f.sortBy.map((ne,we)=>Ae(we)),R=g.map(ne=>Pt(ne)).join(", "),y=M(r,e`SELECT ${e.identifier("__partition__")}, ${e.raw(R)} FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${d}`).toArray(),[O]=y;if(O===void 0)return null;let K=O.__partition__;const V=re(a.baseWhere,a.where);He(V,n,t,"rank");const D=wt(f,V);if(D){const ne=De(f.partitionBy??[],D);if(ne!==K)return null;K=ne}const oe=g.map(ne=>O[ne]),{before:ae,total:le}=lt(r,u,g,f.sortBy,K,oe,d);return{position:ae+1,total:le}},async rankBefore(t,i,a){if(P(t))throw new A("INTERNAL",`rankBefore is not supported on the global (.global()) table '${t}' — cross-shard rank cursors apply only to sharded tables`);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);const $=p.rankIndexes?.find(g=>g.name===i);if(!$)throw new A("INTERNAL",`unknown rankIndex "${i}" on table "${t}"`);if(a.restrictsCounts)throw new Pe(t);s(t,Q),Be(t,$);const f=Ie(t,$.name),d=$.sortBy.map((g,R)=>Ae(R)),u=$.sortBy.map((g,R)=>fe(a.sortValues[R]??null));return lt(r,f,d,$.sortBy,a.partitionKey,u,a.rowId)},async rankPage(t,i,a={}){He(re(a.baseWhere,a.where),n,t,"rankPage");const p=S(t,"rankPage");if(p)return s(t,Q),p.rankPage(t,i,a);c(t,i,"rank");const{continueCursor:$,hasMore:f,rows:d}=nt(Qe,t,i,a);return{continueCursor:$,isDone:!f,page:d.map(u=>u.doc)}},async rankPageRows(t,i,a={}){He(re(a.baseWhere,a.where),n,t,"rankPage"),c(t,i,"rank");const{directions:p,hasMore:$,rows:f}=nt(Qe,t,i,a);return{directions:p,hasMore:$,rows:f}},async restore(t,i){const a=$e(t,i);if(!a){const f=i===void 0?F():void 0;if(f?.restore){await f.restore(t);return}throw new A("INTERNAL",`document not found: ${t}`)}const p=n.tables[a.tableName]?.softDeleteMode?.field;if(!p)throw new A("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const $=a.row[p]!==null&&a.row[p]!==void 0;await z.patch(t,{[p]:null},i),$&&Te(a.tableName,t,void 0,a.row)},async replace(t,i,a,p){const $=$e(t,a);if(!$){const O=a===void 0?F():void 0;if(O){await O.replace(t,i,void 0,p);return}throw new A("INTERNAL",`document not found: ${t}`)}const{docJson:f,row:d,tableName:u}=$,g=n.tables[u];if(!g)throw new A("INTERNAL",`unknown table: ${u}`);st("replace",i);const R=p?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:_(),y={...i,_creationTime:R,_id:t};at(g,i,y,b),je(g,y),ie(u,"before","update")&&await se("before","update",{doc:{...y},id:t,op:"update",previous:d,table:u}),ye(u),_e(u),xe(r,u,e`UPDATE ${e.identifier(u)} SET _creationTime = ${R}, ${e.identifier(Z)} = ${JSON.stringify(y)} WHERE id = ${t} AND ${e.identifier(Z)} = ${f}`),ke(u,t,y,d),Ce(u,t,y),ve(u,d,y),Te(u,t,d,y),m?.invalidate(u,t),I(u,t,"update",y),l({key:t,op:"update",row:y,table:u}),ie(u,"after","update")&&await se("after","update",{doc:y,id:t,op:"update",previous:d,table:u}),await E({doc:y,id:t,op:"update",table:u})},async wipeShard(t){const i=new Set(t?.exclude),a=t?.tables,p=Object.entries(n.tables).filter(([u,g])=>i.has(u)||a!==void 0&&!a.includes(u)?!1:g.shardMode?.kind!=="global").map(([u])=>u);if(a!==void 0){for(const u of a)if(!n.tables[u])throw new A("INTERNAL",`wipeShard: unknown table: ${u}`)}const $={};let f=0;const{deleteAll:d}=z;if(d===void 0)throw new A("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of p){const g=await d(u,{...t?.chunkSize===void 0?{}:{chunkSize:t.chunkSize},hard:!0});$[u]=g.deleted,f+=g.deleted}return{deleted:f,tables:$}}},_t={db:z,scheduler:L};return o.enforceRls===!0?en(z,n,(t,i)=>$e(t,i)?.tableName):z};export{mi as CDC_LOG_TABLE,Si as CLIENT_WATERMARK_TABLE,Ri as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ai as IDEMPOTENCY_TABLE,Mn as NotUniqueError,fi as SEARCH_STATE_TABLE,Ii as advanceClientWatermark,wi as applyCdcChanges,pn as assertValidClientId,ui as backfillAggregateIndexes,hi as backfillRankIndexes,$i as backfillSearchIndexes,gi as bumpCdcEpoch,li as createShardCtxDb,vi as deleteGlobalShapeSnapshot,Ci as deleteGlobalShapeSnapshotsForConnection,ki as migrateClientWatermark,Mi as migrateGlobalShapeSnapshot,Ei as minCdcSeq,ot as normalizeIdStructurally,bi as readCdcChanges,yi as readCdcCursor,_i as readCdcEpoch,Li as readClientWatermark,xi as readGlobalShapeSnapshot,Oi as readIdempotent,qi as runShardMigrations,Pi as selectShapeMemberIds,Hi as selectShapeRows,Ti as trimCdcChanges,Di as trimIdempotent,Wi as writeGlobalShapeSnapshot,Bi as writeIdempotent};
|