@lunora/shard-engine 1.0.0-alpha.85 → 1.0.0-alpha.87
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/conformance/index.mjs +1 -1
- package/dist/index.d.mts +10 -2
- package/dist/index.d.ts +10 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-5o1gzcJV.mjs → ADMIN_FUNCTIONS-BctXwzu5.mjs} +1 -1
- package/dist/packem_shared/{AGG_COUNT-B_w7MnCY.mjs → AGG_COUNT-HNcZ6gXQ.mjs} +1 -1
- package/dist/packem_shared/{AUDIT_LOG_TABLE-CEdsC6vT.mjs → AUDIT_LOG_TABLE-CMhmmmgR.mjs} +1 -1
- package/dist/packem_shared/{CDC_LOG_TABLE-C5XCNb2J.mjs → CDC_LOG_TABLE-kGina9SW.mjs} +1 -1
- package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-BdKYbah0.mjs → CLIENT_WATERMARK_TABLE-DPY-NtOH.mjs} +1 -1
- package/dist/packem_shared/{COMMIT_SEQ_FIELD-D6uMUaiR.mjs → COMMIT_SEQ_FIELD-6lGDFLgk.mjs} +1 -1
- package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-BbDr6pc7.mjs → DATA_MIGRATION_STATE_TABLE-mUH4b2lA.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-fYrcrp5Z.mjs → DEFAULT_MAX_RELATION_KEYS-B1zeutIo.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-DG9iXjzF.mjs → DEFAULT_MAX_RELAYS-CSb6oGUZ.mjs} +1 -1
- package/dist/packem_shared/{DurableStreamRunner-Cliu09-j.mjs → DurableStreamRunner-k4x__lMt.mjs} +1 -1
- package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-wWaEWj5f.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-BpFE-qYL.mjs} +1 -1
- package/dist/packem_shared/{IDEMPOTENCY_TABLE-DKrXVEUe.mjs → IDEMPOTENCY_TABLE-CUc9L-o_.mjs} +1 -1
- package/dist/packem_shared/{MAIL_RETENTION-DXpGFjOt.mjs → MAIL_RETENTION-kYNWpCbY.mjs} +1 -1
- package/dist/packem_shared/NotUniqueError-CRj5uEio.mjs +1 -0
- package/dist/packem_shared/{QUEUE_TABLE-D-cL1NPj.mjs → QUEUE_TABLE-D-5_s2hl.mjs} +1 -1
- package/dist/packem_shared/{REACTOR_STATE_TABLE-CBHASjH9.mjs → REACTOR_STATE_TABLE-XAIYdVL0.mjs} +1 -1
- package/dist/packem_shared/{SCHEDULE_OUTBOX_TABLE-BHpxtEy4.mjs → SCHEDULE_OUTBOX_TABLE-wAAIitt2.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_HISTORY_MAX_VERSIONS-CXznJRUG.mjs → SCHEMA_HISTORY_MAX_VERSIONS-CYVBglZe.mjs} +1 -1
- package/dist/packem_shared/{SEARCH_STATE_TABLE-D_KJ04Bn.mjs → SEARCH_STATE_TABLE-BlVsBsix.mjs} +1 -1
- package/dist/packem_shared/{SHAPE_POKE_CURSOR_TABLE-Bbpou9XZ.mjs → SHAPE_POKE_CURSOR_TABLE-BVskv7ei.mjs} +1 -1
- package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-Dcj-4L8Q.mjs → VECTOR_BACKFILL_MAX_PAGES-Dy3_CF69.mjs} +1 -1
- package/dist/packem_shared/{appendStreamChunk-pPeR5nbF.mjs → appendStreamChunk-BRwBOTEN.mjs} +1 -1
- package/dist/packem_shared/{archiveCdcSegment-C7taIEpg.mjs → archiveCdcSegment-CMAVUCck.mjs} +1 -1
- package/dist/packem_shared/backfillAggregateIndexes-BCSZxzPj.mjs +1 -0
- package/dist/packem_shared/{buildReprojectionMigration-DYjcBhki.mjs → buildReprojectionMigration-Cvq70FvX.mjs} +1 -1
- package/dist/packem_shared/{buildShapeDiff-BMe0ktEG.mjs → buildShapeDiff-BZN27cem.mjs} +1 -1
- package/dist/packem_shared/{clearMemoryTables-C5Wivufe.mjs → clearMemoryTables-BCDG0X9P.mjs} +1 -1
- package/dist/packem_shared/compileWhereSql-Bi04r4ut.mjs +1 -0
- package/dist/packem_shared/computeRankPage-BEyDlhws.mjs +1 -0
- package/dist/packem_shared/createCompanionSync-CeSm2u-U.mjs +1 -0
- package/dist/packem_shared/{createReplicaLink-S5xtsySX.mjs → createReplicaLink-D48HC2Ev.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-relay-shapes-BcgjOtG1.mjs → ctx-db-relay-shapes-DBRHlvNu.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-search-state-fIiMVPXO.mjs → ctx-db-search-state-z0OqNIGe.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-Bi_xWgJR.mjs → defineEngineContractSuite-C-LduuFT.mjs} +1 -1
- package/dist/packem_shared/{do-sql-C7TkRQqw.mjs → do-sql-BgeJDhxn.mjs} +1 -1
- package/dist/packem_shared/{exportShardRows-DmFKSzLZ.mjs → exportShardRows-BFpaZI99.mjs} +1 -1
- package/dist/packem_shared/fts-companion-DcGBHZiM.mjs +1 -0
- package/dist/packem_shared/ftsCompanionDdl-BaLv81YG.mjs +1 -0
- package/dist/packem_shared/isPushableWhere-BeYAOjUb.mjs +1 -0
- package/dist/packem_shared/{isSoftDeleted-DDKwGeyk.mjs → isSoftDeleted-z1u8hGqI.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-N-f9jaQE.mjs → materializeExternalRows-D887_FTq.mjs} +1 -1
- package/dist/packem_shared/runDrizzle-BlpM0R9P.mjs +1 -0
- package/dist/packem_shared/runShardMigrations-B2euqCut.mjs +5 -0
- package/dist/packem_shared/{selectExpiredIds-BuLDf-k0.mjs → selectExpiredIds-DZhnNuXX.mjs} +1 -1
- package/dist/packem_shared/selectShapeMembers-scSb4F0Y.mjs +1 -0
- package/dist/packem_shared/where-sql-BV8Kg4_B.mjs +1 -0
- package/package.json +2 -2
- package/dist/packem_shared/NotUniqueError-2vJ9edyE.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-yFyVVEHD.mjs +0 -1
- package/dist/packem_shared/compileWhereSql-B8tS0_nD.mjs +0 -1
- package/dist/packem_shared/computeRankPage-Bg1_6fPP.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-CGVFf7GK.mjs +0 -1
- package/dist/packem_shared/fts-companion-B7jllLhZ.mjs +0 -1
- package/dist/packem_shared/ftsCompanionDdl-BKeIk9KQ.mjs +0 -1
- package/dist/packem_shared/runDrizzle-CfKnGpV2.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-HaS2tHTS.mjs +0 -5
- package/dist/packem_shared/selectShapeMembers-CIfYJUcu.mjs +0 -1
- package/dist/packem_shared/where-sql-x1YKldcq.mjs +0 -1
- package/dist/packem_shared/whereFilter-CLmm3TFe.mjs +0 -1
- /package/dist/packem_shared/{param-DlozcSQu.mjs → WORKERD_SQLITE_LIMITS-DlozcSQu.mjs} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as $}from"@lunora/errors";import{D as lt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as En,l as Fe,h as mn}from"./fts-companion-B7jllLhZ.mjs";import{sql as c}from"drizzle-orm";import{d as Sn}from"./wire-codec-C-FpWm52.mjs";import{stableWireKey as It}from"./stableWireKey-D2US4k_J.mjs";import{throwingScheduler as _n,aggregateSqlFunction as qe,normalizeCountArgument as Rn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Ye,encodeAggregateKey as Xe,readAggregateValue as Ze}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as N,CountRlsUnsupportedError as et,selectIndexForGroupBy as Tn,selectIndexForCount as vn,selectIndexForAggregate as An}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as In,searchIndexCoversTable as Cn}from"./backfillAggregateIndexes-yFyVVEHD.mjs";import{backfillAggregateIndexes as Or,backfillRankIndexes as Nr,backfillSearchIndexes as jr}from"./backfillAggregateIndexes-yFyVVEHD.mjs";import{appendCdcChange as xn,readCdcDocAtOrBefore as bn}from"./CDC_LOG_TABLE-C5XCNb2J.mjs";import{CDC_LOG_TABLE as Qr,applyCdcChanges as Vr,bumpCdcEpoch as zr,cdcCanVouchFor as Jr,cdcForkedError as Yr,cdcSeqLeavingRows as Xr,cdcTouchesTables as Zr,cdcTrimmedError as ei,compactCdcDocs as ti,cursorBelowRetainedFloor as ni,minCdcReplayableSeq as oi,minCdcSeq as ri,readCdcChangeKeys as ii,readCdcChanges as si,readCdcCursor as ci,readCdcEpoch as ai,trimCdcChanges as di}from"./CDC_LOG_TABLE-C5XCNb2J.mjs";import{allocateCommitSeq as Mn,COMMIT_SEQ_FIELD as Dn}from"./COMMIT_SEQ_FIELD-D6uMUaiR.mjs";import{createCompanionSync as kn}from"./createCompanionSync-CGVFf7GK.mjs";import{isMemoryTable as Ct}from"./clearMemoryTables-C5Wivufe.mjs";import{computeRankPage as xt}from"./computeRankPage-Bg1_6fPP.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as Te,runDrizzle as j}from"./runDrizzle-CfKnGpV2.mjs";import{j as Ge,D as ne,r as Se,k as de,b as Be,A as tt,a as We,e as se,o as Ln,t as Zt,q as bt,i as Fn,h as en,g as qn}from"./do-sql-C7TkRQqw.mjs";import{renderSql as tn,unionAll as ut,WORKERD_SQLITE_LIMITS as nn,sqliteInList as Bn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Wn,boundingBoxGeohashes as Pn,haversineMeters as Un,pointInBoundingBox as Gn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Hn}from"./NotFoundError-BhF7FeFr.mjs";import{tiebreakDirectionFor as On,encodeCursor as He,normalizeOrderKeys as st,uniqueIndexFields as on,buildSeekWhere as rn,decodeCursor as ct,buildSeekBeforeWhere as Nn,softDeleteScope as ue,equalityPinnedFields as jn,applySelect as Mt}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as Dt,sortColumnName as kt,resolveRankPartition as Kn,encodePartitionKey as Qn,RANK_TIEBREAK as Vn,rankPivotConditionSql as zn}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{UNVOUCHABLE_DEP as Lt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Jn,buildIndexRange as Yn}from"./buildIndexRange-6nIZDf4m.mjs";import{r as Oe,j as _e,c as ee,t as Ne,i as Ft}from"./where-sql-x1YKldcq.mjs";import{serializeSqlValue as ce}from"./serializeSqlValue-BbZ5hKM7.mjs";import{quoteIdentifier as ve}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Xn,isPushableWhere as Zn}from"./whereFilter-CLmm3TFe.mjs";import{deriveRelationEdges as eo,findRelated as to}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as nt,resolveRelationPredicates as qt}from"./DEFAULT_MAX_RELATION_KEYS-fYrcrp5Z.mjs";import{runRowValidators as ot,resolveWith as Bt,relationHooks as Wt,applyOnDelete as no,fanOutScalarCounts as oo}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as ro}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{mayHoldProjectedValue as io}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{createSystemReader as so}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as Re}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as co}from"./hasTrigger-CjlwI4le.mjs";import{CLIENT_WATERMARK_TABLE as ui,advanceClientWatermark as fi,migrateClientWatermark as hi,readClientWatermark as wi}from"./CLIENT_WATERMARK_TABLE-BdKYbah0.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as gi,deleteGlobalShapeSnapshot as $i,deleteGlobalShapeSnapshotsForConnection as yi,migrateGlobalShapeSnapshot as Ei,readGlobalShapeSnapshot as mi,writeGlobalShapeSnapshot as Si}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-wWaEWj5f.mjs";import{IDEMPOTENCY_TABLE as Ri,readIdempotent as Ti,trimIdempotent as vi,writeIdempotent as Ai}from"./IDEMPOTENCY_TABLE-DKrXVEUe.mjs";import{runShardMigrations as Ci}from"./runShardMigrations-HaS2tHTS.mjs";import{S as bi}from"./ctx-db-search-state-fIiMVPXO.mjs";import{selectShapeMembers as Di,selectShapeRows as ki}from"./selectShapeMembers-CIfYJUcu.mjs";const ao=n=>{const r=atob(n),o=Uint8Array.from(r,d=>d.codePointAt(0)??0);return new TextDecoder().decode(o)},lo=()=>new $("BAD_REQUEST","invalid cursor"),Pt=16,Ut=8,Y=1024,ft=(n,r)=>r.query(n),uo=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[d,s]of r.entries()){const w=d===r.length-1;let E=0;for(const A of n)(w?A.startsWith(s):A===s)&&(E+=1);if(E===0)return 0;o+=E}return o},fo=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",d=(o.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(d)}},ho=(n,r,o)=>{const d={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new $("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=Ut)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(Ut)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),d},search:(s,w)=>{const E=n;if(s!==E.definition.field)throw new $("INTERNAL",`search index "${E.indexName}" on table "${r}" indexes "${E.definition.field}", not "${s}"`);const A=ft(w,o).length;if(A>Pt)throw new $("BAD_REQUEST",`search index "${E.indexName}" on table "${r}": at most ${String(Pt)} search terms are supported (got ${String(A)})`);return E.field=s,E.query=w,E.hasQuery=!0,d}};return d},wo=n=>{if(n.length>Y)throw new $("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},po=n=>Math.min(n.offset+n.numItems+1,Y),go=n=>btoa(`search:${String(n)}`),$o=n=>{let r;try{r=ao(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},yo=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?$o(n.cursor):0;if(o===void 0)throw lo();if(o+r>=Y)throw new $("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Y-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},Eo=(n,r)=>{const o=r.offset+r.numItems,d=r.numItems>0&&n.length>o;return{continueCursor:d?go(o):null,isDone:!d,page:n.slice(r.offset,o)}},mo=n=>{if(n===void 0)return Y+1;if(!Number.isFinite(n))return Y;const r=Math.max(0,Math.floor(n));if(r>Y)throw new $("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},So=32,_o=1024,sn=(n,r,o,d)=>{const s=`SELECT id, _creationTime, ${ve(ne)} FROM ${ve(n)}`,w=`ORDER BY ${o}${d===void 0?"":` LIMIT ${String(d)}`}`;return r===void 0?Oe(`${s} ${w}`):_e(`${s} WHERE `,r,` ${w}`)},ht={fieldRef:n=>Oe(Ge(n)),serialize:ce},cn=n=>{const r=n.map(o=>`${Ge(o.field)} ${o.direction==="desc"?"DESC":"ASC"}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${Ge("id")} ${On(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},Ro={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},an=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),To=n=>{const r=an(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},vo=(n,r)=>{const o=n.order,d=To(n),{shape:s}=r;return d.length>0?st(d.map(w=>({[w]:o})),s,{pinned:an(n),uniqueBy:on(r.indexes,s)}):st([{_creationTime:o}],s)},Ao=(n,r,o,d)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Ro[w.comparator]??"eq"]:w.value}}));if(o&&s.push(rn(r,ct(o))),d&&s.push(Nn(r,ct(d))),s.length!==0)return s.length===1?s[0]:{AND:s}},Io=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,So):n.want},at=(n,r,o,d,s,w,E)=>{const A=vo(d,o),g=cn(A),b=[],{filters:x,want:R}=w;let T=w.cursor??void 0,M=Io(w);if(R===0)return{documents:b,orderKeys:A};for(;;){const B=ee(Ao(d,A,T,w.endCursor),ht,Ne),P=sn(r,s&&B?_e(B," AND ",s):s??B,g,M),L=Te(n,P.text,...P.params).toArray();let q={};E(L.length);for(const C of L)if(q=Se(C),x.every(K=>K(q))&&b.push(q)===R)return{documents:b,orderKeys:A};if(M===void 0||L.length<M)return{documents:b,orderKeys:A};T=He(q,A),M=Math.max(M,Math.min(M*2,_o))}},Co=(n,r,o,d,s,w,E,A)=>{const g=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:B,orderKeys:P}=at(n,r,o,d,w,{cursor:s.cursor,endCursor:s.endCursor,filters:E.all,selective:E.selective,want:void 0},A),L=B.length>=2?B[Math.floor(B.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:B,splitCursor:L?He(L,P):null}}const{documents:b,orderKeys:x}=at(n,r,o,d,w,{cursor:s.cursor,filters:E.all,selective:E.selective,want:g+1},A),R=b.length>g,T=R?b.slice(0,g):b,M=T.at(-1);return{continueCursor:R&&M?He(M,x):null,isDone:!R,page:T}},je=n=>{const r=new Map;return o=>{const d=r.get(o);if(d!==void 0)return d;const s=n(ve(o));return r.set(o,s),s}},fe=ve(ne),xo=je(n=>`INSERT INTO ${n} (id, _creationTime, ${fe}) VALUES (?, ?, ?)`),Gt=je(n=>`UPDATE ${n} SET ${fe} = ? WHERE id = ? AND ${fe} = ?`),bo=je(n=>`UPDATE ${n} SET _creationTime = ?, ${fe} = ? WHERE id = ? AND ${fe} = ?`),Mo=je(n=>`DELETE FROM ${n} WHERE id = ? AND ${fe} = ?`),Do="SELECT changes() AS changed",Ht=new Map,ko="",Lo=n=>{const r=JSON.stringify(n),o=Ht.get(r);if(o!==void 0)return o;const d=n.map(w=>c`SELECT ${c.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${c.identifier(ne)} FROM ${c.identifier(w)} WHERE id = ${ko}`),{sql:s}=tn("sqlite",c`${ut(d)} LIMIT 1`);return Ht.set(r,s),s},Fo=(n,r)=>r.map(()=>n),qo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Bo=n=>{if(!qo.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Ot=50,dn=500,Pe=Math.floor(nn.boundParams/3),Ee=nn.boundParams,Wo=128,le=(n,r,o)=>{const d=r??dn;if(n>d)throw new $("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},Po=n=>{const r={eq:(o,d)=>(n.sqlConditions.push({comparator:"=",field:o,value:d}),r),gt:(o,d)=>(n.sqlConditions.push({comparator:">",field:o,value:d}),r),gte:(o,d)=>(n.sqlConditions.push({comparator:">=",field:o,value:d}),r),lt:(o,d)=>(n.sqlConditions.push({comparator:"<",field:o,value:d}),r),lte:(o,d)=>(n.sqlConditions.push({comparator:"<=",field:o,value:d}),r)};return r},Uo=n=>Math.max(n,Y),ln=(n,r)=>{const o=n.filters.map(d=>c`${se(d.field)} = ${ce(d.value)}`);return r&&o.push(r),o},Go=(n,r,o,d,s)=>{const w=ft(o.query,lt(o.definition.language));if(w.length===0)return[];const E=En(r,o.indexName),A=`${E}__vocab`,g=w.length-1,b=w.map((P,L)=>{const q=fo(P,L===g),C=q.exact?c`${c.identifier("term")} = ${q.lower}`:c`${c.identifier("term")} >= ${q.lower} AND ${c.identifier("term")} < ${q.upper}`;return c`SELECT ${c.identifier("doc")}, ${c.raw(String(L))} AS ${c.identifier("__term__")}, COUNT(*) AS ${c.identifier("__n__")} FROM ${c.identifier(A)} WHERE ${C} GROUP BY ${c.identifier("doc")}`}),x=w.map((P,L)=>c`SUM(CASE WHEN u.${c.identifier("__term__")} = ${c.raw(String(L))} THEN u.${c.identifier("__n__")} ELSE 0 END)`),R=c`SELECT f.${c.identifier(Fe)} AS ${c.identifier(Fe)}, ${c.join(x,c` + `)} AS ${c.identifier("__score__")} FROM (${ut(b)}) u JOIN ${c.identifier(E)} f ON f.rowid = u.${c.identifier("doc")} GROUP BY f.${c.identifier(Fe)} HAVING ${c.join(x.map(P=>c`${P} > 0`),c` AND `)}`,T=ln(o,s);let M=c`SELECT m.id, m._creationTime, m.${c.identifier(ne)}, s.${c.identifier("__score__")} AS ${c.identifier("__score__")} FROM (${R}) s JOIN ${c.identifier(r)} m ON m.id = s.${c.identifier(Fe)}`;T.length>0&&(M=c`${M} WHERE ${c.join(T,c` AND `)}`),M=c`${M} ORDER BY s.${c.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${c.raw(String(d))}`;const B=[];for(const P of j(n,M)){const L=en(P);if(L){const q=P.__score__;B.push({document:L,score:typeof q=="number"?q:Number(q??0)})}}return B},Ho=(n,r,o,d,s)=>{const w=lt(o.definition.language),E=ft(o.query,w);if(E.length===0)return[];const A=ln(o,s);let g=c`SELECT id, _creationTime, ${c.identifier(ne)} FROM ${c.identifier(r)}`;A.length>0&&(g=c`${g} WHERE ${c.join(A,c` AND `)}`),g=c`${g} ORDER BY _creationTime DESC, id ASC LIMIT ${c.raw(String(Uo(d)))}`;const b=j(n,g).toArray(),x=[];for(const R of b){const T=en(R);if(!T)continue;const M=uo(mn(T,o.definition),E);M>0&&x.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:M})}return x.sort((R,T)=>T.score-R.score||T.creationTime-R.creationTime||R.id.localeCompare(T.id)),x.slice(0,d).map(R=>({document:R.doc,score:R.score}))},rt=(n,r,o,d)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${d}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Oo=(n,r)=>{const o=n,d={near:(s,w)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(rt(s,".near() point",r,o.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},d},within:s=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(rt(s.sw,".within() sw corner",r,o.indexName),rt(s.ne,".within() ne corner",r,o.indexName),s.sw.lat>s.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},d}};return d},No=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:d,lng:s}=o;return typeof d=="number"&&typeof s=="number"?{lat:d,lng:s}:void 0},jo=(n,r)=>{const o=No(n,r.definition.field);if(!o)return;const d=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const s=Un(r.near.point,o);return s<=r.near.radiusMeters?{creationTime:d,distance:s}:void 0}return Gn(o,r.within)?{creationTime:d,distance:0}:void 0},Ko=(n,r,o,d)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const s=o.near?Wn(o.near.point,o.near.radiusMeters):Pn(o.within),w=qn(r,o.indexName),E=s.map(R=>c`(g.${c.identifier("__geohash__")} >= ${R} AND g.${c.identifier("__geohash__")} < ${`${R}{`})`),A=[c`(${c.join(E,c` OR `)})`];d&&A.push(d);const g=c`SELECT m.id, m._creationTime, m.${c.identifier(ne)} FROM ${c.identifier(w)} g JOIN ${c.identifier(r)} m ON m.id = g.${c.identifier("__id__")} WHERE ${c.join(A,c` AND `)}`,b=j(n,g).toArray(),x=[];for(const R of b){const T=Se(R),M=T?jo(T,o):void 0;T&&M&&x.push({creationTime:M.creationTime,distance:M.distance,doc:T})}return x.sort((R,T)=>R.distance-T.distance||T.creationTime-R.creationTime),x},un=(n,r,o,d)=>{const s=[];for(const w of n)if(r.every(E=>E(d(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},Qo=(n,r,o,d,s,w=()=>{})=>{const E=o.within!==void 0,A=Ko(n,r,o,s).map(g=>({distanceMeters:E?null:g.distance,document:g.doc}));return w(A.length),typeof d=="number"?A.slice(0,Math.max(0,Math.floor(d))):A},Nt=(n,r,o,d,s,w,E=()=>{})=>{const{geo:A}=o;if(!A)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const g=s.length>0,b=Qo(n,r,A,g?void 0:w,d,E);return g?un(b,s,w,x=>x.document):b},me={fieldRef:se,serialize:ce},fn=(n,r)=>{const o=r===void 0?void 0:n.shape[r];return o!==void 0&&io(o)},jt=(n,r)=>r.some(o=>fn(n,o)),Kt=(n,r,o)=>{if(fn(n,r))throw new $("BAD_REQUEST",`${o}: "${r}" 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)`)},Vo=n=>{let r=0;const o=[],d={fieldRef:s=>Oe(Ge(s)),relationExists:s=>{const{childWhere:w,negated:E,parentTable:A,relation:g}=s,b=`__rel_${String(r)}`,x=o.at(-1)??A;r+=1,n(g.table,O);const R=g.kind==="one"?g.field:g.references,T=g.kind==="one"?g.references:g.field,M=Oe(`${bt(b,T)} = ${bt(x,R)}`);o.push(b);const B=ee(w,d,Ne);o.pop();const P=B===void 0?M:_e(M," AND ",B),L=_e("EXISTS (SELECT 1 FROM ",Ft(g.table)," AS ",Ft(b)," WHERE ",P,")");return E?_e("NOT ",L):L},serialize:ce};return d};class zo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Jo=/\s/u,Yo=String.fromCodePoint(0),Qt=(n,r,o)=>{if(!n.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Jo.test(o)||o.includes(Yo)?null:o},Xo=(n,r,o,d=()=>{},s=()=>{},w=()=>{})=>{const E=r.tables[o];if(!E)throw new $("INTERNAL",`unknown table: ${o}`);const A=ue(E.softDeleteMode,void 0),g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},b=()=>{const y=N(A,g.pushedWhere);return y?ee(y,me):void 0},x=()=>{const y=N(A,g.pushedWhere);return y?ee(y,ht,Ne):void 0},R=()=>[...g.inMemoryFilters,...g.verifyFilters];let T=0;const M=y=>{const{search:_}=g;if(!_)throw new $("INTERNAL","runSearchFetch called without a staged search");In(n,o,E);const F=g.inMemoryFilters.length>0,k=mo(F?void 0:y),z=Fn(n);if(z&&!Cn(n,o,_.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${_.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const he=b(),oe=z?Go(n,o,_,k,he):Ho(n,o,_,k,he);!F&&y===void 0&&wo(oe);const te=R();return T=oe.length,te.length>0?un(oe,te,y,ae=>ae.document):oe},B=y=>M(y).map(_=>_.document),P=y=>{const _=yo(y);return Eo(B(po(_)),_)},L=()=>{if(g.search||g.geo||g.indexName===void 0){s(void 0);return}s(Yn(o,g.indexName,g.indexFields,g.sqlConditions,ce))},q=y=>{L();let _=0;const F=(()=>{if(g.search){const k=B(y);return _=T,k}return g.geo?Nt(n,o,g,b(),R(),y,k=>{_=k}).map(k=>k.document):at(n,o,E,g,x(),{filters:R(),selective:g.inMemoryFilters.length>0,want:y===void 0?void 0:Math.max(0,Math.floor(y))},k=>{_+=k}).documents})();return w(Math.max(_,F.length)),F},C=()=>{if(!g.search&&!g.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);L();let y=0;const _=(()=>{if(g.search){const F=M(void 0);return y=T,F}return Nt(n,o,g,b(),R(),void 0,F=>{y=F})})();return w(Math.max(y,_.length)),_},K={async*[Symbol.asyncIterator](){if(g.search){yield*q(void 0);return}let y;for(;;){const _=await K.paginate({cursor:y??null,numItems:Wo});if(yield*_.page,_.isDone||_.continueCursor===null)return;y=_.continueCursor}},async collect(){return q(void 0)},async collectWithScores(){return C()},filter(y){const _=Xn(y);return _!==void 0&&Zn(_,E.shape)?(g.pushedWhere=N(g.pushedWhere,_),g.verifyFilters.push(y)):g.inMemoryFilters.push(y),K},async first(){return q(1)[0]??null},order(y){return g.order=y==="desc"?"desc":"asc",K},async paginate(y){let _=0;if(L(),g.search){const k=P(y);return w(k.page.length),k}if(g.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const F=Co(n,o,E,g,y,x(),{all:R(),selective:g.inMemoryFilters.length>0},k=>{_+=k});return w(Math.max(_,F.page.length)),F},async take(y){return q(y)},async unique(){const y=q(2);if(y.length>1)throw new zo(`unique() on table "${o}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(y,_){const F=(E.geoIndexes??[]).find(z=>z.name===y);if(!F)throw new $("INTERNAL",`unknown geo index "${y}" on table "${o}"`);d(o,y,"geo");const k={definition:F,indexName:y};if(g.geo=k,_(Oo(k,o)),!k.near&&!k.within)throw new $("INTERNAL",`geo index "${y}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return K},withIndex(y,_){const F=E.indexes.find(k=>k.name===y);if(!F)throw new $("INTERNAL",`unknown index "${y}" on table "${o}"`);return d(o,y,"index"),g.indexName=y,g.indexFields=F.fields,_&&_(Po(g)),K},withSearchIndex(y,_){const F=(E.searchIndexes??[]).find(z=>z.name===y);if(!F)throw new $("INTERNAL",`unknown search index "${y}" on table "${o}"`);d(o,y,"search");const k={definition:F,field:F.field,filters:[],hasQuery:!1,indexName:y,query:""};if(g.search=k,_(ho(k,o,lt(F.language))),!k.hasQuery)throw new $("INTERNAL",`search index "${y}" on table "${o}" requires a .search(field, query) call`);return K}};return K},Vt=(n,r,o)=>{const d={...r};for(const[s,w]of Zt(n)){if(w.serverDefault){d[s]=w.serverDefault({auth:o});continue}d[s]===void 0&&(w.defaultFn?d[s]=w.defaultFn():"defaultValue"in w&&(d[s]=w.defaultValue))}return d},zt=(n,r,o,d)=>{const s=o;for(const[w,E]of Zt(n)){if(E.serverDefault){w in r&&(s[w]=E.serverDefault({auth:d}));continue}E.onUpdateFn&&!(w in r)&&(s[w]=E.onUpdateFn())}},Jt=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Yt=["_commitSeq","_creationTime","_id"],it=n=>Yt.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!Yt.includes(r))):n,Zo=/unique constraint failed/i,er=n=>n instanceof Error&&Zo.test(n.message),tr=/string or blob too big/iu,nr=(n,r)=>{if(!(!(n instanceof Error)||!tr.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},dt=(n,r,o,d)=>{try{Te(n,o,...d)}catch(s){throw er(s)?new Re(`unique constraint violation on "${r}"`,"unique"):(nr(s,r),s)}},Ue=(n,r,o,d)=>{if(dt(n,r,o,d),Te(n,Do).one().changed===0)throw new Re(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Xt=(n,r,o,d,s,w,E)=>{const A=[];for(let R=0;R<o.length+1;R+=1){const T=o[R],M=d[R],B=M?.direction==="desc"?"desc":"asc",P=T===void 0||M===void 0?c`${c.identifier(Vn)} < ${E}`:zn(T,w[R],B,!1);if(P===void 0)continue;const L=[];for(let C=0;C<R;C+=1)L.push(c`${c.identifier(o[C])} IS ${w[C]}`);L.push(P);const[q]=L;A.push(L.length===1&&q!==void 0?q:c`(${c.join(L,c` AND `)})`)}const g=A.length>0?c.join(A,c` OR `):c`1 = 0`,b=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(r)} WHERE ${c.identifier("__partition__")} = ${s} AND (${g})`).one(),x=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(r)} WHERE ${c.identifier("__partition__")} = ${s}`).one();return{before:b.c,total:x.c}},Ur=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{sql:d}=n,{schema:s}=n,w=n.broadcast??(()=>{}),E=eo(s);let A;const g=()=>n.inTransaction?.()===!0,b=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((A===void 0||!g())&&(A=Mn(d)),{[Dn]:A}),x=(e,...t)=>{const i=s.tables[e]?.indexes;if(!i||i.length===0)return;const f=[];for(const h of t)h&&f.push(...Jn(i,h,ce));return f.length>0?f:void 0},{headroom:R}=n;let T=!1;const M=async e=>{const t=T;T=!0;try{return await e()}finally{T=t}},B=n.onRead??(()=>{}),P=e=>{Ct(s.tables[e])&&B(Lt,Lt)},L=n.onReadRange??(e=>{B(e.table,O)}),q=e=>{P(e.table),L(e)},C=(e,t)=>{t!==void 0&&t!==O&&!T&&R?.recordRead(1),P(e),B(e,t)},K=n.onIndexUse??(()=>{}),y=n.onWrite??(()=>{}),_=e=>{T||R?.recordWrite(e)},F=async e=>{_(e.doc),await y(e)},{cache:k}=n,z=n.clock??(()=>Date.now()),he=n.idGenerator??(()=>crypto.randomUUID()),oe=n.scheduler??_n,{globalDb:te}=n,ae=n.auth??{identity:null,userId:null},wt=n.cdc??!1,Ke=oe,hn=so({scheduler:typeof Ke.list=="function"&&typeof Ke.get=="function"?Ke:void 0,storage:n.storage}),we=(e,t,i,f)=>{wt&&!Ct(s.tables[e])&&xn(d,z(),e,t,i,f)},wn=(e,t,i,f)=>{if(s.tables[e]?.dropStalePatchesMode!==!0||!wt)return!1;const h=r?.();if(h===void 0)return!1;const l=bn(d,e,t,h);return l===void 0?!1:Object.keys(it(i)).some(a=>It(l[a])!==It(f[a]))},re=e=>s.tables[e]?.shardMode?.kind==="global",pt=(e,t)=>{if(re(e)){if(!te)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return te}return G},Qe=e=>pt(e,"cascade"),V=(e,t)=>{if(re(e)){if(!te)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return te}},gt=async(e,t,i,f,h)=>{h&&_(i);const l=await e.insert(t,i,f);return w({key:l,op:"insert",row:{...i,_id:l},table:t}),l},Ve=(e,t)=>pt(e,"relation load").findMany(e,t),$t=(e,t)=>(re(e)&&C(e,O),Ve(e,t)),pn=e=>!re(e.table),yt=n.relationExistsPushDown??"auto",Et=yt!=="never",{maxRelationKeys:mt}=n,Ae=(e,t,i)=>qt(e,{fetcher:$t,maxRelationKeys:mt,relationBaseWhere:i,schema:s,tableName:t}),St=async(e,t,i,f)=>{const h=V(e,"relation grouped count");if(h)return C(e,O),oo((U,I)=>h.count(U,I),e,t,i,f);const l=s.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);C(e,O);const a=ue(l.softDeleteMode,void 0),u={[t]:{in:i}},p=N(N(u,f),a),v=await Ae(p,e,void 0),m=ee(v,me),D=se(t);let S=c`SELECT ${D} AS __fk__, COUNT(*) AS count FROM ${c.identifier(e)}`;m&&(S=c`${S} WHERE ${m}`),S=c`${S} GROUP BY ${D}`;const W=j(d,S).toArray();return new Map(W.map(U=>[U.__fk__,U.count]))};let Ie=0;const _t=new Set;for(const[e,t]of Object.entries(s.tables))for(const i of Object.values(t.triggerMap??{}))_t.add(`${e} ${i.timing} ${i.op}`);const X=(e,t,i)=>_t.has(`${e} ${t} ${i}`),Z=async(e,t,i)=>{if(Ie+=1,Ie>Ot)throw Ie-=1,new Re(`trigger recursion exceeded ${String(Ot)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await co({ctx:$n,event:i,op:t,schema:s,tableName:i.table,timing:e})}finally{Ie-=1}},{ensureBackfilledForTable:pe,ensureBackfilledIndex:ze,ensureRankBackfilled:Je,ensureRankBackfilledForTable:ge,syncAggregates:Ce,syncCompanionsForInsert:Rt,syncGeo:xe,syncRanks:$e,syncSearch:be}=kn({broadcast:w,indexKeysFor:(e,t)=>x(e,t),invalidateCache:(e,t,i)=>k?.invalidate(e,t,x(e,i)),recordCdc:we,schema:s,sql:d}),Tt=(e,t,i)=>{const{shardMode:f}=t;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(i.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${i.name}" on "${e}" partitions across shards (shard key "${f.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})},vt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),ye=e=>e===void 0||re(e)?te:void 0,ie=(e,t)=>{const i=vt(t);for(let f=0;f<i.length;f+=Ee){const h=i.slice(f,f+Ee),[l]=Te(d,Lo(h),...Fo(e,h)).toArray();if(!l)continue;const a=l.__t__,u=Se(l);if(typeof a!="string"||!u)return;const p=l[ne];return{docJson:typeof p=="string"?p:de(p??{}),row:u,tableName:a}}},gn=(e,t)=>{const i=[...new Set(e)],f=new Map;if(i.length===0)return f;const h=vt(t);for(let l=0;l<h.length;l+=Ee){const a=h.slice(l,l+Ee),u=Math.floor(Ee/a.length),p=Bn(c`${c.identifier("id")}`,i,!1,u),v=a.map(m=>c`SELECT ${c.raw(`'${m.replaceAll("'","''")}'`)} AS __t__, id FROM ${c.identifier(m)} WHERE ${p}`);for(const m of j(d,ut(v))){const{id:D,__t__:S}=m;typeof S=="string"&&typeof D=="string"&&f.set(D,S)}}return f},At={assertRankPartitionLocal:Tt,ensureRankBackfilled:Je,onRead:C,rowToDocument:Se,schema:s,sql:d},G={system:hn,async aggregate(e,t){const i=V(e,"aggregate");if(i)return C(e,O),i.aggregate(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(qe(t.op),t.op==="count")return G.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);C(e,O);const h=ue(f.softDeleteMode,void 0),l=N(N(t.baseWhere,t.where),h),a=await Ae(l,e,t.relationBaseWhere),u=a!==l;if(f.aggregateIndexes&&!t.baseWhere&&!u&&(!h||jt(f,[t.field]))){const U=An(f.aggregateIndexes,t.op,t.field,t.where);if(U){ze(e,U.index);const I=Xe(U.index.by??[],U.key),Q=Ye(e,U.index.name),J=j(d,c`SELECT ${Be} AS value, ${tt} AS count FROM ${c.identifier(Q)} WHERE ${We} = ${I}`).toArray()[0];return Ze(t.op,J)}}Kt(f,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=ee(a,me),v=qe(t.op),m=se(t.field);let D=c`SELECT ${c.raw(v)}(${m}) AS value FROM ${c.identifier(e)}`;p&&(D=c`${D} WHERE ${p}`);const W=j(d,D).toArray()[0]?.value;return W??null},asId(e,t){const i=Qt(s,e,t);if(i===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return i},async count(e,t){const i=V(e,"count");if(i)return C(e,O),i.count(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=Rn(t);if(h.restrictsCounts)throw new et(e);C(e,O);const l=ue(f.softDeleteMode,void 0),a=N(N(h.baseWhere,h.where),l),u=await Ae(a,e,h.relationBaseWhere),p=u!==a;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!l){const S=vn(f.aggregateIndexes,h.where);if(S){ze(e,S.index);const W=Xe(S.index.by??[],S.key),U=Ye(e,S.index.name),I=j(d,c`SELECT ${Be} AS value FROM ${c.identifier(U)} WHERE ${We} = ${W}`).toArray();return I[0]===void 0?0:I[0].value??0}}const v=ee(u,me);let m=c`SELECT COUNT(*) AS count FROM ${c.identifier(e)}`;return v&&(m=c`${m} WHERE ${v}`),j(d,m).one().count},async delete(e,t,i){const f=ie(e,t);if(!f){const m=ye(t);m&&(_(void 0),await m.delete(e,t,i));return}const{docJson:h,row:l,tableName:a}=f,u=s.tables[a],p=i?.hard===!0,v=!p&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(v&&l[v]!==null&&l[v]!==void 0)){if(X(a,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:l,table:a}),await no({deletedId:e,deletedReference:m=>l[m],findHolders:async(m,D,S)=>(await Qe(m).findMany(m,{includeDeleted:p,where:{[D]:S}})).page,onCascade:(m,D)=>Qe(m).delete(D,void 0,i),onRestrict:m=>{throw new Re(m,"restrict")},onSetNull:(m,D,S)=>Qe(m).patch(D,{[S]:null}),schema:s,tableName:a}),pe(a),ge(a),v){const m={...l,...b(a),[v]:z(),_id:e};Ue(d,a,Gt(a),[de(m),e,h]),be(a,e,m,l),xe(a,e,void 0),Ce(a,l,m),$e(a,e,l,void 0),k?.invalidate(a,e,x(a,l,m)),we(a,e,"update",m),w({indexKeys:x(a,l,m),key:e,op:"update",row:m,table:a}),X(a,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:l,table:a}),await F({id:e,op:"delete",table:a});return}Ue(d,a,Mo(a),[e,h]),be(a,e,void 0),xe(a,e,void 0),Ce(a,l,void 0),$e(a,e,l,void 0),k?.invalidate(a,e,x(a,l)),we(a,e,"delete"),w({indexKeys:x(a,l),key:e,op:"delete",table:a}),X(a,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:l,table:a}),await F({id:e,op:"delete",table:a})}},async deleteAll(e,t){if(!s.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const i=Math.max(1,t?.chunkSize??dn),f=t?.hard===void 0?void 0:{hard:t.hard},h=re(e)?void 0:e;let l=0;return await M(async()=>{for(;;){const u=(await G.findMany(e,{limit:i})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await G.delete(p,h,f),l+=1;if(u.length<i)break}}),{deleted:l}},async deleteMany(e,t,i){le(e.length,t?.limit,"deleteMany");for(const f of e)await G.delete(f,i);return{deleted:e.length}},async deleteWhere(e,t,i){const l=(await(V(e,"deleteWhere")??G).findMany(e,{where:t})).page.map(a=>String(a._id));if(le(l.length,i?.limit,"deleteWhere"),G.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return G.deleteMany(l,i)},async findFirst(e,t={}){return(await G.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const i=await G.findFirst(e,t);if(i===null)throw new Hn(`findFirstOrThrow: no "${e}" document matched`);return i},async findMany(e,t={}){const i=V(e,"findMany");if(i)return C(e,O),i.findMany(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?C(e,O):C(e);const l=st(t.orderBy,f.shape,{pinned:jn(t.where),uniqueBy:on(f.indexes,f.shape)}),a=t.cursor?rn(l,ct(t.cursor)):void 0;let u=N(t.baseWhere,t.where);u=N(u,ue(f.softDeleteMode,t.includeDeleted)),u=await qt(u,{canPushExists:Et?pn:void 0,existsPushMode:yt==="always"?"always":"auto",fetcher:$t,maxRelationKeys:mt,relationBaseWhere:t.relationBaseWhere,schema:s,tableName:e}),a&&(u=u?{AND:[u,a]}:a);const p=Et?Vo(C):ht,v=ee(u,p,Ne),m=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0,D=sn(e,v,cn(l),m===void 0?void 0:m+1),S=Te(d,D.text,...D.params).toArray();h&&!T&&R?.recordRead(S.length);const W=[];for(const J of S){const H=Se(J);H&&(W.push(H),!h&&typeof H._id=="string"&&C(e,H._id))}if(m===void 0)return t.with&&await Bt({groupedCounter:St,fetcher:Ve,parents:W,...Wt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Mt(W,t.select,t.with)};const U=W.length>m,I=U?W.slice(0,m):W,Q=I.at(-1);return t.with&&await Bt({fetcher:Ve,groupedCounter:St,parents:I,...Wt(t),schema:s,tableName:e,with:t.with}),{continueCursor:U&&Q&&t.omitContinueCursor!==!0?He(Q,l):null,isDone:!U,page:Mt(I,t.select,t.with)}},async get(e,t){const i=ie(e,t);if(!i){const f=ye(t);return f?f.get(e,t):null}return C(i.tableName,e),i.row},async lookupById(e,t){const i=ie(e,t);return i?(C(i.tableName,e),{row:i.row,tableName:i.tableName}):null},async groupBy(e,t){const i=V(e,"groupBy");if(i)return C(e,O),i.groupBy(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);C(e,O);const h=t.agg??{op:"count"};if(qe(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=ue(f.softDeleteMode,void 0),a=N(N(t.baseWhere,t.where),l),u=await Ae(a,e,t.relationBaseWhere),p=u!==a,v=[...t.by,h.field];if(f.aggregateIndexes&&!t.baseWhere&&!p&&(!l||jt(f,v))){const I=Tn(f.aggregateIndexes,h.op,h.field,t.by,t.where),Q=I===void 0?0:Object.keys(I.partial).length,J=I?.index.by?.length??0;if(I&&(Q===0||Q===J)){ze(e,I.index);const H=Ye(e,I.index.name),Me=Object.keys(I.partial),De=[];if(Me.length===(I.index.by??[]).length&&Me.length>0){const ke=Xe(I.index.by??[],I.partial),Le=j(d,c`SELECT ${Be} AS value, ${tt} AS count FROM ${c.identifier(H)} WHERE ${We} = ${ke}`).toArray();return Le.length>0&&De.push({key:{...I.partial},value:Ze(h.op,Le[0])}),De}const yn=j(d,c`SELECT ${We} AS key, ${Be} AS value, ${tt} AS count FROM ${c.identifier(H)}`).toArray();for(const ke of yn){const Le=Sn(JSON.parse(ke.key));De.push({key:Le,value:Ze(h.op,ke)})}return De}}for(const I of v){if(I===void 0)continue;const Q=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Kt(f,I,Q)}const m=ee(u,me),D=t.by.map(I=>c`${se(I)} AS ${c.identifier(I)}`);if(h.op==="count")D.push(c`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);D.push(c`${c.raw(qe(h.op))}(${se(I)}) AS value`)}let S=c`SELECT ${c.join(D,c`, `)} FROM ${c.identifier(e)}`;m&&(S=c`${S} WHERE ${m}`),S=c`${S} GROUP BY ${c.join(t.by.map(I=>se(I)),c`, `)}`;const W=j(d,S).toArray(),U=[];for(const I of W){const Q={};for(const H of t.by)Q[H]=Ln(f.shape[H],I[H]??null);const{value:J}=I;U.push({key:Q,value:J==null?null:Number(J)})}return U},async insert(e,t,i){const f=V(e,"insert");if(f)return gt(f,e,t,i,!0);const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Vt(h,t,ae);ot(h,l);let a;i?.clientId!==void 0?(Bo(i.clientId),a=i.clientId):i?.allowExplicitId&&typeof l._id=="string"?a=l._id:a=he();const u=i?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:z(),p={...l,...b(e),_creationTime:u,_id:a};return X(e,"before","insert")&&await Z("before","insert",{doc:{...p},id:a,op:"insert",table:e}),pe(e),ge(e),dt(d,e,xo(e),[a,u,de(p)]),Rt(e,a,p),X(e,"after","insert")&&await Z("after","insert",{doc:p,id:a,op:"insert",table:e}),await F({doc:p,id:a,op:"insert",table:e}),a},async insertManyUnsafe(e,t,i){if(le(t.length,i?.limit,"insertManyUnsafe"),t.length===0)return[];const f=V(e,"insert");if(f){const u=[];for(const p of t)_(p);for(const p of t){const v=await f.insert(e,p,{allowExplicitId:i?.allowExplicitId});w({key:v,op:"insert",row:{...p,_id:v},table:e}),u.push(v)}return u}const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);pe(e),ge(e);const l=[];for(let u=0;u<t.length;u+=Pe)l.push(b(e));const a=t.map((u,p)=>{const v=Vt(h,u,ae),m=i?.allowExplicitId===!0&&typeof v._id=="string"?v._id:he(),D=i?.allowExplicitId===!0&&typeof v._creationTime=="number"?v._creationTime:z(),S={...v,...l[Math.floor(p/Pe)],_creationTime:D,_id:m};return{creationTime:D,document:S,id:m}});for(const u of a)_(u.document);for(let u=0;u<a.length;u+=Pe){const p=c.join(a.slice(u,u+Pe).map(m=>c`(${m.id}, ${m.creationTime}, ${de(m.document)})`),c`, `),v=tn("sqlite",c`INSERT INTO ${c.identifier(e)} (id, _creationTime, ${c.identifier(ne)}) VALUES ${p}`);dt(d,e,v.sql,v.params)}for(const{document:u,id:p}of a)Rt(e,p,u),await y({doc:u,id:p,op:"insert",table:e});return a.map(u=>u.id)},async insertMany(e,t,i){le(t.length,i?.limit,"insertMany");const f=i?.skipDuplicates===!0,h=[],l=V(e,"insert");if(l)for(const u of t)_(u);const a=async u=>l?gt(l,e,u,void 0,!1):G.insert(e,u);for(const u of t)try{h.push(await a(u))}catch(p){if(f&&p instanceof Re&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return Qt(s,e,t)},async patch(e,t,i){const f=ie(e,i);if(!f){const v=ye(i);if(v){_(t),await v.patch(e,t,i);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:a}=f,u=s.tables[a];if(!u)throw new $("INTERNAL",`unknown table: ${a}`);if(C(a,e),Jt("patch",t),wn(a,e,t,l)){o?.({fields:Object.keys(it(t)),id:e,table:a});return}const p={...l,...it(t),...b(a),_id:e};zt(u,t,p,ae),ot(u,p,!0),X(a,"before","update")&&await Z("before","update",{doc:{...p},id:e,op:"update",previous:l,table:a}),pe(a),ge(a),Ue(d,a,Gt(a),[de(p),e,h]),be(a,e,p,l),xe(a,e,p),Ce(a,l,p),$e(a,e,l,p),k?.invalidate(a,e,x(a,l,p)),we(a,e,"update",p),w({indexKeys:x(a,l,p),key:e,op:"update",row:p,table:a}),X(a,"after","update")&&await Z("after","update",{doc:p,id:e,op:"update",previous:l,table:a}),await F({doc:p,id:e,op:"update",table:a})},async patchMany(e,t,i){le(e.length,t?.limit,"patchMany");for(const f of e)await G.patch(f.id,f.patch,i);return{patched:e.length}},async patchWhere(e,t,i){const l=(await(V(e,"patchWhere")??G).findMany(e,{where:t.where})).page.map(a=>({id:String(a._id),patch:t.patch}));if(le(l.length,i?.limit,"patchWhere"),G.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await G.patchMany(l,i),{patched:l.length}},async related(e,t){return to(G,E,e,t)},relationEdges:E,query(e){const t=V(e,"query");return t?(C(e,O),t.query(e)):Xo(d,s,e,K,i=>{i?q(i):C(e,O)},i=>{T||R?.recordRead(i)})},async rank(e,t,i){const f=V(e,"rank");if(f)return C(e,O),f.rank(e,t,i);K(e,t,"rank");const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(H=>H.name===t);if(!l)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Tt(e,h,l),i.restrictsCounts)throw new et(e);C(e,O),Je(e,l);const a=typeof i.row=="string"?i.row:i.row._id;if(!a)return null;const u=Dt(e,l.name),p=l.sortBy.map((H,Me)=>kt(Me)),v=p.map(H=>ve(H)).join(", "),m=j(d,c`SELECT ${c.identifier("__partition__")}, ${c.raw(v)} FROM ${c.identifier(u)} WHERE ${c.identifier("__id__")} = ${a}`).toArray(),[D]=m;if(D===void 0)return null;let S=D.__partition__;const W=N(i.baseWhere,i.where);nt(W,s,e,"rank");const U=Kn(l,W);if(U){const H=Qn(l.partitionBy??[],U);if(H!==S)return null;S=H}const I=p.map(H=>D[H]),{before:Q,total:J}=Xt(d,u,p,l.sortBy,S,I,a);return{position:Q+1,total:J}},async rankBefore(e,t,i){if(re(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===t);if(!h)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(i.restrictsCounts)throw new et(e);C(e,O),Je(e,h);const l=Dt(e,h.name),a=h.sortBy.map((p,v)=>kt(v)),u=h.sortBy.map((p,v)=>ce(i.sortValues[v]??null));return Xt(d,l,a,h.sortBy,i.partitionKey,u,i.rowId)},async rankPage(e,t,i={}){nt(N(i.baseWhere,i.where),s,e,"rankPage");const f=V(e,"rankPage");if(f)return C(e,O),f.rankPage(e,t,i);K(e,t,"rank");const{continueCursor:h,hasMore:l,rows:a}=xt(At,e,t,i);return{continueCursor:h,isDone:!l,page:a.map(u=>u.doc)}},async rankPageRows(e,t,i={}){nt(N(i.baseWhere,i.where),s,e,"rankPage"),K(e,t,"rank");const{directions:f,hasMore:h,rows:l}=xt(At,e,t,i);return{directions:f,hasMore:h,rows:l}},async restore(e,t){const i=ie(e,t);if(!i){const l=ye(t);if(l?.restore){await l.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=s.tables[i.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${i.tableName}" is not a .softDelete() table`);const h=i.row[f]!==null&&i.row[f]!==void 0;await G.patch(e,{[f]:null},t),h&&$e(i.tableName,e,void 0,i.row)},async replace(e,t,i,f){const h=ie(e,i);if(!h){const W=ye(i);if(W){_(t),await W.replace(e,t,i,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:l,row:a,tableName:u}=h,p=s.tables[u];if(!p)throw new $("INTERNAL",`unknown table: ${u}`);Jt("replace",t);const v=f?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,m=typeof a._creationTime=="number"?a._creationTime:void 0,D=v??m??z(),S={...t,...b(u),_creationTime:D,_id:e};zt(p,t,S,ae),ot(p,S),X(u,"before","update")&&await Z("before","update",{doc:{...S},id:e,op:"update",previous:a,table:u}),pe(u),ge(u),Ue(d,u,bo(u),[D,de(S),e,l]),be(u,e,S,a),xe(u,e,S),Ce(u,a,S),$e(u,e,a,S),k?.invalidate(u,e,x(u,a,S)),we(u,e,"update",S),w({indexKeys:x(u,a,S),key:e,op:"update",row:S,table:u}),X(u,"after","update")&&await Z("after","update",{doc:S,id:e,op:"update",previous:a,table:u}),await F({doc:S,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),i=e?.tables,f=Object.entries(s.tables).filter(([u,p])=>t.has(u)||i!==void 0&&!i.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(i!==void 0){for(const u of i)if(!s.tables[u])throw new $("INTERNAL",`wipeShard: unknown table: ${u}`)}const h={};let l=0;const{deleteAll:a}=G;if(a===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of f){const p=await a(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[u]=p.deleted,l+=p.deleted}return{deleted:l,tables:h}}},$n={db:G,scheduler:oe};return n.enforceRls===!0?ro(G,s,(e,t)=>ie(e,t)?.tableName,(e,t)=>gn(e,t),E):G};export{Qr as CDC_LOG_TABLE,ui as CLIENT_WATERMARK_TABLE,gi as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ri as IDEMPOTENCY_TABLE,zo as NotUniqueError,bi as SEARCH_STATE_TABLE,fi as advanceClientWatermark,Vr as applyCdcChanges,Jt as assertNoExplicitUndefined,Bo as assertValidClientId,Or as backfillAggregateIndexes,Nr as backfillRankIndexes,jr as backfillSearchIndexes,zr as bumpCdcEpoch,Jr as cdcCanVouchFor,Yr as cdcForkedError,Xr as cdcSeqLeavingRows,Zr as cdcTouchesTables,ei as cdcTrimmedError,ti as compactCdcDocs,Ur as createShardCtxDb,ni as cursorBelowRetainedFloor,$i as deleteGlobalShapeSnapshot,yi as deleteGlobalShapeSnapshotsForConnection,hi as migrateClientWatermark,Ei as migrateGlobalShapeSnapshot,oi as minCdcReplayableSeq,ri as minCdcSeq,Qt as normalizeIdStructurally,ii as readCdcChangeKeys,si as readCdcChanges,ci as readCdcCursor,ai as readCdcEpoch,wi as readClientWatermark,mi as readGlobalShapeSnapshot,Ti as readIdempotent,Ci as runShardMigrations,Di as selectShapeMembers,ki as selectShapeRows,it as stripReservedPatchFields,di as trimCdcChanges,vi as trimIdempotent,Si as writeGlobalShapeSnapshot,Ai as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{m as x,c as T,l as R,r as E,a as P,w as D}from"./ctx-db-search-state-fIiMVPXO.mjs";import{S,c as U,g as v,d as A,e as k,a as b}from"./fts-companion-B7jllLhZ.mjs";import{sql as s}from"drizzle-orm";import{matchesStaticWhere as G}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as W,encodeAggregateKey as B,foldAggregateTally as H}from"./aggregateTableName-C7o-gpms.mjs";import{rankColumnsSql as N,insertRankRow as K}from"./createCompanionSync-CGVFf7GK.mjs";import{runDrizzle as l,runAll as $}from"./runDrizzle-CfKnGpV2.mjs";import{i as C,h as O,D as p,r as M,a as Y,b as j,A as z}from"./do-sql-C7TkRQqw.mjs";import{sqliteInList as V}from"./param-DlozcSQu.mjs";import{isLiveForCompanion as J}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as Q,matchesRankStaticWhere as X}from"./RANK_TIEBREAK-B0_x8iev.mjs";const L=(e,o)=>l(e,s`SELECT COUNT(*) AS count FROM ${s.identifier(o)}`).one().count>0,Z=(e,o)=>l(e,s`SELECT 1 FROM ${s.identifier(o)} LIMIT 1`).toArray().length>0,_=(e,o)=>l(e,s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)}`).toArray(),q=(e,o,r,n)=>{const t=W(o,r.name);if(L(e,t))return;const a=r.by??[],c=new Map,i=_(e,o);for(const d of i){const f=M(d);if(!f||!J(f,n)||r.where&&!G(f,r.where))continue;const g=B(a,f);H(c,g,r,f)}for(const[d,f]of c)l(e,s`INSERT INTO ${s.identifier(t)} (${Y}, ${j}, ${z}) VALUES (${d}, ${f.value}, ${f.count})`)},pe=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(!(n.shardMode?.kind==="global"||!n.aggregateIndexes))for(const t of n.aggregateIndexes)q(e,r,t,n.softDeleteMode?.field)},ee=(e,o,r)=>{const n=Q(o,r.name);if(L(e,n))return;const t=N(r),a=_(e,o);for(const c of a){const i=M(c);!i||r.where&&!X(i,r.where)||K(e,n,r,t,i._id,i)}},Se=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(!(n.shardMode?.kind==="global"||!n.rankIndexes))for(const t of n.rankIndexes)ee(e,r,t)},oe=(e,o,r,n)=>l(e,r===void 0?s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)} ORDER BY id ASC LIMIT ${s.raw(String(n))}`:s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${s.raw(String(n))}`).toArray(),h=500,y=(e,o,r)=>{const n=S(o,r.name),t=T(r),a=R(E(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,i=oe(e,o,c,h);let d=c;for(const g of i){const{id:u}=g;if(typeof u!="string")continue;d=u;const I=O(g);$(e,I?A(n,u,k(I,r)):b(n,u))}const f=i.length<h;return D(e,n,d,f,t),{done:f,rows:i.length}},m=(e,o)=>s`${s.identifier(e)}.${s.identifier(o)}`,w=500,F=(e,o,r)=>{const n=S(o,r.name),t=l(e,U(n,w)).toArray(),a=v(t);if(a.size===0)return!0;const c=new Map;for(const i of l(e,s`SELECT ${m(o,"id")}, ${m(o,"_creationTime")}, ${m(o,p)} FROM ${s.identifier(o)} WHERE ${V(m(o,"id"),[...a.keys()],!1)}`))c.set(String(i.id),i);for(const[i,d]of a){const f=c.get(i),g=f?O(f):void 0;$(e,g?A(n,i,k(g,r),{unmappedRowids:d}):b(n,i,{unmappedRowids:d}))}return t.length<w},ne=(e,o,r,n)=>{let t=0;for(;t<n&&!F(e,o,r);)t+=1;return t},Ie=(e,o,r)=>{const n=S(o,r.name),t=T(r);return R(E(e,n),t).finished?!0:P(e,n)},he=(e,o,r)=>{if(C(e))for(const n of r.searchIndexes??[])F(e,o,n),!(n.staged&&Z(e,o))&&y(e,o,n)},re=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=y(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},we=(e,o,r={})=>{if(!C(e))return{done:!0,pages:0};x(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const i of c.searchIndexes){if(t+=ne(e,a,i,n-t),t>=n)return{done:!1,pages:t};const d=re(e,a,i,n-t);if(t+=d.pages,!d.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{pe as backfillAggregateIndexes,Se as backfillRankIndexes,we as backfillSearchIndexes,he as backfillSearchIndexesForTable,F as drainUnmappedFtsRows,oe as readKeysetPage,Ie as searchIndexCoversTable};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./param-DlozcSQu.mjs";import{c as o,l as t}from"./where-sql-x1YKldcq.mjs";import"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";export{o as compileWhereSql,t as literalInList};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-CfKnGpV2.mjs";import{sqliteInList as O}from"./param-DlozcSQu.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-B0_x8iev.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[m,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[m]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},_o=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const m=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const p=[];typeof t.partitionKey=="string"?p.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&p.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&p.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=p.length>0?o` WHERE ${o.join(p,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(m)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{_o as computeRankPage,Q as resolveRankSeekTuple};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{N as re,S as se,d as ie,e as ce,a as ae}from"./fts-companion-B7jllLhZ.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as V,aggregateSqlFunction as fe}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as P,encodeAggregateKey as v,foldAggregateTally as z,coerceAggregateNumber as D}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as $,runAll as le}from"./runDrizzle-CfKnGpV2.mjs";import{i as $e,g as de,D as b,r as q,a as O,b as m,A as g,c as M,e as W}from"./do-sql-C7TkRQqw.mjs";import{param as ue,WORKERD_SQLITE_LIMITS as Ee}from"./param-DlozcSQu.mjs";import{encodeGeohash as ge,GEO_DEFAULT_PRECISION as pe}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{encodePartitionKey as ye,sortColumnName as _e,rankTableName as X,matchesRankStaticWhere as Y}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{mayHoldProjectedValue as me}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{serializeSqlValue as J}from"./serializeSqlValue-BbZ5hKM7.mjs";const he=(_,R,p)=>[..._.partitionBy??[],..._.sortBy.map(h=>h.field),..._.where?Object.keys(_.where):[]].every(h=>R[h]===p[h]),Z=_=>e.join(["__id__","__partition__",..._.sortBy.map((R,p)=>_e(p))].map(R=>e.identifier(R)),e`, `),N=(_,R,p,F,h,u)=>{const s=ye(p.partitionBy??[],u),C=p.sortBy.map(I=>J(u[I.field]??null)),L=e.join([h,s,...C].map(I=>ue(I)),e`, `);$(_,e`INSERT INTO ${e.identifier(R)} (${F}) VALUES (${L})`)},Te=(_,R,p,F,h,u)=>{if(h&&u&&he(p,h,u))return;const s=X(R,p.name);h&&$(_,e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__id__")} = ${F}`),!(!u||p.where&&!Y(u,p.where))&&N(_,s,p,Z(p),F,u)},be=_=>{const{broadcast:R,indexKeysFor:p,invalidateCache:F,recordCdc:h,schema:u,sql:s}=_,C=new Set,L=n=>u.tables[n]?.softDeleteMode?.field,I=new Set,U=(n,o)=>{const r=`${n}::${o.name}`;if(C.has(r))return;const c=P(n,o.name),a=o.by??[],f=L(n),d=new Map,y=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}`).toArray();for(const T of y){const l=q(T);if(!l||!Q(l,f)||o.where&&!V(l,o.where))continue;const S=v(a,l);z(d,S,o,l)}$(s,e`DELETE FROM ${e.identifier(c)}`);const A=Math.floor(Ee.boundParams/3),w=[...d];for(let T=0;T<w.length;T+=A){const l=w.slice(T,T+A),S=e.join(l.map(([t,i])=>e`(${t}, ${i.value}, ${i.count})`),e`, `);$(s,e`INSERT INTO ${e.identifier(c)} (${O}, ${m}, ${g}) VALUES ${S}`)}C.add(r)},x=(n,o,r)=>{const c=o.by??[],a=o.field??"",f=[],d=(t,i)=>{const E=J(i);E===null?f.push(e`${W(t)} IS NULL`):f.push(e`${W(t)} = ${E}`)};for(const t of c)d(t,r[t]??null);const y=L(n);y!==void 0&&d(y,null);for(const[t,i]of Object.entries(o.where??{}))d(t,i!==null&&typeof i=="object"&&!Array.isArray(i)?i.eq:i);const A=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,w=u.tables[n]?.shape[a];if(w&&me(w)){const t=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}${A}`).toArray(),i=new Map;for(const E of t){const k=q(E);k&&z(i,"",o,k)}return{value:i.get("")?.value??null}}const T=fe(o.op),l=W(a);return{value:$(s,e`SELECT ${e.raw(T)}(${l}) AS value FROM ${e.identifier(n)}${A}`).one().value??null}},ee=(n,o,r,c)=>{const a=P(n,o.name),{op:f}=o,d=o.field??"",y=t=>{$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${O} = ${t} AND ${g} <= 0`)},A=L(n),w=t=>!o.where||V(t,o.where),T=t=>Q(t,A)&&w(t);c!==void 0&&f!=="count"&&w(c)&&D(c[d]);const l=r&&T(r)?r:void 0,S=c&&T(c)?c:void 0;if(!(!l&&!S)){if(f==="count"){for(const[t,i]of[[l,-1],[S,1]]){if(!t)continue;const E=v(o.by??[],t);$(s,M(a,E,i,i,e`${m} = ${m} + excluded.${m}, ${g} = ${g} + excluded.${g}`))}l&&y(v(o.by??[],l));return}if(f==="sum"||f==="avg"){for(const[t,i]of[[l,-1],[S,1]]){if(!t)continue;const E=D(t[d]);if(E===void 0)continue;const k=v(o.by??[],t);$(s,M(a,k,i*E,i,e`${m} = COALESCE(${m}, 0) + excluded.${m}, ${g} = ${g} + excluded.${g}`))}l&&y(v(o.by??[],l));return}if(l){const t=v(o.by??[],l),i=D(l[d]),E=$(s,e`SELECT ${m} AS value, ${g} AS count FROM ${e.identifier(a)} WHERE ${O} = ${t}`).toArray()[0],k=(E?.count??0)-1;if(k<=0)$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${O} = ${t}`);else if(E&&i!==void 0&&E.value!==null&&i===E.value){const te=x(n,o,l);$(s,e`UPDATE ${e.identifier(a)} SET ${m} = ${te.value}, ${g} = ${k} WHERE ${O} = ${t}`)}else $(s,e`UPDATE ${e.identifier(a)} SET ${g} = ${g} - 1 WHERE ${O} = ${t}`)}if(S){const t=v(o.by??[],S),i=D(S[d]);if(i===void 0)$(s,M(a,t,null,1,e`${g} = ${g} + 1`));else{const E=f==="min"?"MIN":"MAX";$(s,M(a,t,i,1,e`${m} = ${e.raw(E)}(COALESCE(${m}, excluded.${m}), excluded.${m}), ${g} = ${g} + 1`))}}}},oe=n=>{for(const o of u.tables[n]?.aggregateIndexes??[])U(n,o)},j=(n,o,r)=>{for(const c of u.tables[n]?.aggregateIndexes??[])ee(n,c,o,r)},B=(n,o)=>{const r=`${n}::rank::${o.name}`;if(I.has(r))return;const c=X(n,o.name),a=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}`).toArray();$(s,e`DELETE FROM ${e.identifier(c)}`);const f=Z(o);for(const d of a){const y=q(d);!y||o.where&&!Y(y,o.where)||N(s,c,o,f,y._id,y)}I.add(r)},ne=n=>{for(const o of u.tables[n]?.rankIndexes??[])B(n,o)},H=(n,o,r,c)=>{for(const a of u.tables[n]?.rankIndexes??[])Te(s,n,a,o,r,c)},K=(n,o,r,c)=>{const a=u.tables[n]?.searchIndexes??[];if(!(a.length===0||!$e(s)))for(const f of a){if(re(c,r,f))continue;const d=se(n,f.name);le(s,r?ie(d,o,ce(r,f)):ae(d,o))}},G=(n,o,r)=>{for(const c of u.tables[n]?.geoIndexes??[]){const a=de(n,c.name);$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${e.identifier("__id__")} = ${o}`);const f=r?.[c.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:d,lng:y}=f,A=ge({lat:d,lng:y},c.precision??pe);$(s,e`INSERT INTO ${e.identifier(a)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${A}, ${d}, ${y})`)}}};return{ensureBackfilledForTable:oe,ensureBackfilledIndex:U,ensureRankBackfilled:B,ensureRankBackfilledForTable:ne,syncAggregates:j,syncCompanionsForInsert:(n,o,r)=>{K(n,o,r),G(n,o,r),j(n,void 0,r),H(n,o,void 0,r),F(n,o,r),h(n,o,"insert",r),R({indexKeys:p(n,r),key:o,op:"insert",row:r,table:n})},syncGeo:G,syncRanks:H,syncSearch:K}};export{be as createCompanionSync,N as insertRankRow,Z as rankColumnsSql};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{D as I}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{sqliteInList as L}from"./param-DlozcSQu.mjs";const u=(i,t)=>{if(!t.includes("."))return i[t];let r=i;for(const $ of t.split(".")){if(r===null||typeof r!="object"||Array.isArray(r))return;r=r[$]}return r},D=(i,t)=>`${i}__fts_${t}`,o="__text__",s="__id__",A=1e3,O=(i,t)=>t.document(i),N=(i,t)=>u(i,t),_=i=>typeof i=="string"?i:i==null?"":typeof i=="number"||typeof i=="bigint"||typeof i=="boolean"?String(i):JSON.stringify(i)??"",w=(i,t,r)=>i!==void 0&&t!==void 0&&N(i,r.field)===N(t,r.field),c=(i,t)=>O(_(N(i,t.field)),I(t.language)).slice(0,A),M=(i,t)=>c(i,t).join(" "),a=50,n="__rowid__",T=i=>`${i}__ids`,E=(i,t)=>e`${e.identifier(i)}.${e.identifier(t)}`,S=(i,t,{guard:r,unmappedRowids:$})=>{const d=T(i),f=r===void 0?e``:e` AND ${r}`,R=$===void 0?e`${E(i,"rowid")} > 0`:L(E(i,"rowid"),$,!1,a);return[e`DELETE FROM ${e.identifier(i)} WHERE ${R} AND CAST(${E(i,s)} AS TEXT) = ${t}${f}`,e`DELETE FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = (SELECT ${E(d,n)} FROM ${e.identifier(d)} WHERE ${E(d,s)} = ${t}) AND ${E(i,s)} = ${t}${f}`]},U=i=>[e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(i)} USING fts5(${e.identifier(o)}, ${e.identifier(s)} UNINDEXED)`,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${i}__vocab`)} USING fts5vocab(${e.identifier(i)}, ${e.raw("instance")})`,e`CREATE TABLE IF NOT EXISTS ${e.identifier(T(i))} (${e.identifier(n)} INTEGER PRIMARY KEY, ${e.identifier(s)} TEXT NOT NULL UNIQUE)`,e`INSERT INTO ${e.identifier(i)} (rowid, ${e.identifier(o)}, ${e.identifier(s)}) SELECT 0, '', '' WHERE NOT EXISTS (SELECT 1 FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = 0)`],F=(i,t,r,$={})=>{const d=T(i),f=$.guard===void 0?e``:e` AND ${$.guard}`,R=e`MIN(COALESCE((SELECT MIN(${E(d,n)}) FROM ${e.identifier(d)}), 0), 0) - 1`;return[...S(i,t,$),e`INSERT OR REPLACE INTO ${e.identifier(d)} (${e.identifier(n)}, ${e.identifier(s)}) SELECT ${R}, ${t} WHERE 1 = 1${f}`,e`INSERT OR REPLACE INTO ${e.identifier(i)} (rowid, ${e.identifier(o)}, ${e.identifier(s)}) SELECT ${E(d,n)}, ${r}, ${E(d,s)} FROM ${e.identifier(d)} WHERE ${E(d,s)} = ${t}${f}`]},y=(i,t,r={})=>{const $=T(i),d=r.guard===void 0?e``:e` AND ${r.guard}`;return[...S(i,t,r),e`DELETE FROM ${e.identifier($)} WHERE ${E($,s)} = ${t}${d}`]},W=(i,t,r=0)=>e`SELECT ${E(i,"rowid")} AS ${e.identifier("rowid")}, ${E(i,s)} AS ${e.identifier("id")} FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} > ${e.param(Math.max(0,r))} AND ${E(i,s)} IS NOT NULL ORDER BY ${E(i,"rowid")} ASC LIMIT ${e.raw(String(t))}`,b=i=>{const t=new Map;for(const r of i){const $=String(r.id);t.set($,[...t.get($)??[],Number(r.rowid)])}return t};export{w as N,D as S,y as a,T as b,W as c,F as d,M as e,U as f,b as g,c as h,s as l};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as t,a as e,b as p,c as m,d as f,g as n}from"./fts-companion-B7jllLhZ.mjs";import"./param-DlozcSQu.mjs";export{t as ftsCompanionDdl,e as ftsPurgeDocument,p as ftsRowidMapName,m as ftsUnmappedPage,f as ftsWriteDocument,n as groupUnmappedRows};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{renderSql as l,WORKERD_SQLITE_LIMITS as e}from"./param-DlozcSQu.mjs";const c=(t,n,...r)=>{if(n.length*3>e.sqlTextLength){const s=new TextEncoder().encode(n).length;if(s>e.sqlTextLength)throw new i("INTERNAL",`SQL statement is ${String(s)} bytes, over this runtime's ${String(e.sqlTextLength)}-byte limit`)}if(r.length>e.boundParams)throw new i("INTERNAL",`SQL statement binds ${String(r.length)} parameters, over this runtime's limit of ${String(e.boundParams)}`);return t.exec.call(t,n,...r)},u=(t,n)=>{const{params:r,sql:o}=l("sqlite",n);return c(t,o,...r)},d=(t,n)=>{for(const r of n)u(t,r)},g=t=>t??null,S=t=>{if(!(t==null||t===""))try{return JSON.parse(t)}catch{return}};export{S as decodeJsonColumn,g as orNull,d as runAll,u as runDrizzle,c as runSql};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{LunoraError as l}from"@lunora/errors";import{f as L,S as h}from"./fts-companion-B7jllLhZ.mjs";import{sql as r}from"drizzle-orm";import{aggregateTableName as O}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-yFyVVEHD.mjs";import{migrateCdcLog as x,migrateCdcMeta as N}from"./CDC_LOG_TABLE-C5XCNb2J.mjs";import{migrateClientWatermark as C}from"./CLIENT_WATERMARK_TABLE-BdKYbah0.mjs";import{migrateCommitSeq as $}from"./COMMIT_SEQ_FIELD-D6uMUaiR.mjs";import{migrateGlobalShapeSnapshot as b}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-wWaEWj5f.mjs";import{migrateIdempotency as D}from"./IDEMPOTENCY_TABLE-DKrXVEUe.mjs";import{m as U}from"./ctx-db-relay-shapes-BcgjOtG1.mjs";import{migrateScheduleOutbox as M}from"./SCHEDULE_OUTBOX_TABLE-BHpxtEy4.mjs";import{m as G}from"./ctx-db-search-state-fIiMVPXO.mjs";import{migrateShapePokeCursor as X}from"./SHAPE_POKE_CURSOR_TABLE-Bbpou9XZ.mjs";import{runDrizzle as s,runAll as y}from"./runDrizzle-CfKnGpV2.mjs";import{D as F,d as E,e as g,t as P,i as Y,g as k,a as B,b as j,A as p}from"./do-sql-C7TkRQqw.mjs";import{renderSql as v}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as w}from"./appendStreamChunk-pPeR5nbF.mjs";import{rankTableName as H,sortColumnName as K}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{migrateReactorState as W}from"./REACTOR_STATE_TABLE-CBHASjH9.mjs";import{recordSchemaVersion as V}from"./SCHEMA_HISTORY_MAX_VERSIONS-CXznJRUG.mjs";const A=r`_creationTime, id`,S=(e,i,o,t,n,a)=>{const c=r.join(n.map(d=>r`${d} IS NOT NULL`),r` AND `);if(s(e,r`SELECT 1 FROM ${r.identifier(o)} WHERE ${c} GROUP BY ${t} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new l("INTERNAL",`unique index "${i}" on "${o}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},z=(e,i,o,t,n,a)=>{const m=s(e,r`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${i} AND tbl_name = ${o}`).toArray()[0]?.sql;if(m==null)return;const d=_=>{const u=_.indexOf("(");return u===-1?void 0:_.slice(u,_.lastIndexOf(")")+1)},T=d(v("sqlite",E(i,o,t,n)).sql),f=d(m);T===void 0||f===void 0||T===f||(n&&S(e,i,o,t,a,"cannot be re-created with its new column list"),s(e,r`DROP INDEX IF EXISTS ${r.identifier(i)}`))},J=(e,i,o)=>s(e,r`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${i} AND tbl_name = ${o} LIMIT 1`).toArray().length>0,I=(e,i,o,t,n,a)=>{n&&!J(e,i,o)&&S(e,i,o,t,a,"cannot be created"),s(e,E(i,o,t,n))},Q=(e,i,o)=>{for(const t of o.indexes){const n=`${i}_${t.name}`,a=t.unique??!1,c=t.fields.map(T=>g(T)),m=r.join(c,r`, `),d=a?m:r`${m}, ${A}`;z(e,n,i,d,a,c),I(e,n,i,d,a,c)}for(const[t,n]of P(o)){if(!n.unique)continue;const a=g(t);I(e,`${i}_unique_${t}`,i,a,!0,[a])}},Z=(e,i,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!Y(e))){for(const t of o.searchIndexes)y(e,L(h(i,t.name)));R(e,i,o)}},q=(e,i,o)=>{if(o.geoIndexes)for(const t of o.geoIndexes){const n=k(i,t.name);s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__geohash__")} TEXT NOT NULL, ${r.identifier("__lat__")} REAL NOT NULL, ${r.identifier("__lng__")} REAL NOT NULL)`);const a=`${i}__geo_${t.name}__btree`;s(e,E(a,n,r`${r.identifier("__geohash__")} ASC, ${r.identifier("__id__")} ASC`,!1))}},ee=(e,i,o)=>{if(o.aggregateIndexes)for(const t of o.aggregateIndexes){const n=O(i,t.name);s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${B} TEXT PRIMARY KEY, ${j} REAL, ${p} INTEGER NOT NULL DEFAULT 0)`),s(e,r`PRAGMA table_info(${r.identifier(n)})`).toArray().some(c=>c.name==="__count__")||s(e,r`ALTER TABLE ${r.identifier(n)} ADD COLUMN ${p} INTEGER NOT NULL DEFAULT 0`)}},re=(e,i,o)=>{if(o.rankIndexes)for(const t of o.rankIndexes){const n=H(i,t.name),a=t.sortBy.map((f,_)=>K(_)),c=a.map(f=>r`${r.identifier(f)} BLOB`),m=c.length>0?r`, ${r.join(c,r`, `)}`:r``;s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__partition__")} TEXT NOT NULL${m})`);const d=[r`${r.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const u=t.sortBy[f]?.direction;d.push(r`${r.identifier(_)} ${r.raw(u==="desc"?"DESC":"ASC")}`)}d.push(r`${r.identifier("__id__")} ASC`);const T=`${i}__rank_${t.name}__btree`;s(e,E(T,n,r.join(d,r`, `),!1))}},he=(e,i,o={})=>{o.schemaSnapshot!==void 0&&V(e,o.schemaSnapshot.hash,o.schemaSnapshot.json),G(e);for(const[t,n]of Object.entries(i.tables))n.shardMode?.kind!=="global"&&(s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
_creationTime REAL NOT NULL,
|
|
4
|
-
${r.identifier(F)} TEXT NOT NULL
|
|
5
|
-
)`),s(e,E(`${t}__by_creation`,t,A,!1)),Q(e,t,n),Z(e,t,n),q(e,t,n),ee(e,t,n),re(e,t,n));o.cdc&&(x(e,{rowHistoryIndex:Object.values(i.tables).some(t=>t.dropStalePatchesMode===!0)}),N(e),C(e),X(e),U(e)),Object.values(i.tables).some(t=>t.commitOrderedMode===!0)&&$(e),W(e),D(e),M(e),b(e),w(e)};export{he as runShardMigrations};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-CfKnGpV2.mjs";import{D as p,r as d,e as h}from"./do-sql-C7TkRQqw.mjs";import{sqliteInList as w}from"./param-DlozcSQu.mjs";import{c as S}from"./where-sql-x1YKldcq.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-BbZ5hKM7.mjs";const C={fieldRef:h,serialize:$},g=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=S(o,C);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},v=(o,i,r)=>{const t=u(r,void 0),s=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const l of s){const n=d(l),{id:c}=l;n!==void 0&&typeof c=="string"&&f.push({doc:n,id:c})}return f},z=(o,i,r,t)=>{const s=new Map;if(t.length===0)return s;const f=u(r,g(t)),l=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const n of l){const c=d(n),{id:a}=n;c!==void 0&&typeof a=="string"&&s.set(a,c)}return s};export{z as selectShapeMembers,v as selectShapeRows};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{sql as l}from"drizzle-orm";import{sqliteInList as d,isJsonSafe as $,WORKERD_SQLITE_LIMITS as O}from"./param-DlozcSQu.mjs";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as L}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const R={binary:(n,t,o)=>l`${n} ${l.raw(t)} ${o}`,constant:n=>n?l`1 = 1`:l`0 = 1`,connect:(n,t,o)=>l`(${n}) ${l.raw(o)} (${t})`,contains:(n,t)=>l`instr(lower(${n}), lower(${t})) > 0`,inList:(n,t,o,s)=>d(n,t,o,s),negate:n=>l`NOT (${n})`,nullCheck:(n,t)=>t?l`${n} IS NOT NULL`:l`${n} IS NULL`,value:n=>l`${n}`},p=(...n)=>{let t="";const o=[];for(const s of n)typeof s=="string"?t+=s:(t+=s.text,o.push(...s.params));return{params:o,text:t}},h=n=>({params:[n],text:"?"}),I=n=>({params:[],text:n}),Y=n=>I(m(n)),Q={binary:(n,t,o)=>p(n," ".concat(t," "),h(o)),constant:n=>I(n?"1 = 1":"0 = 1"),connect:(n,t,o)=>p("(",n,") ".concat(o," ("),t,")"),contains:(n,t)=>p("instr(lower(",n,"), lower(",t,")) > 0"),inList:(n,t,o,s)=>{const i=o?" NOT IN ":" IN ";if(t.length>s&&!t.every(r=>$(r)))throw new T("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(t.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(s)} values or fewer.`);if(t.length<=s){const r=[n,i,"("];for(const[e,c]of t.entries())e>0&&r.push(", "),r.push(h(c));return r.push(")"),p(...r)}return p(n,i,'(SELECT "value" FROM json_each(',h(JSON.stringify(t)),"))")},negate:n=>p("NOT (",n,")"),nullCheck:(n,t)=>p(n,t?" IS NOT NULL":" IS NULL"),value:h},x=O.boundParams/2,S=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],_=new Set(S),j={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},E=n=>{if(n===null||typeof n!="object"||Array.isArray(n))return!1;const t=Object.keys(n);return t.length>0&&t.every(o=>_.has(o))},w=(n,t,o,s,i)=>{const r=i.value(s.serialize(o,n));return s.containsExpr?s.containsExpr(t,r):i.contains(t,r)},y=(n,t,o,s,i,r,e)=>i===null?o==="eq"||o==="ne"?e.nullCheck(t,o==="ne"):e.constant(!1):e.binary(t,s,r.serialize(i,n)),C=(n,t,o,s,i,r)=>{if(!Array.isArray(s))throw new T("BAD_REQUEST",`\`${o==="IN"?"in":"notIn"}\` on "${n}" expects an array of values, received ${s===null?"null":typeof s}`);const e=s;if(e.length===0)return r.constant(o==="NOT IN");const c=e.map(u=>i.serialize(u,n)),a=o==="NOT IN";return i.inList?i.inList(t,c,a):r.inList(t,c,a,x)},G=(n,t,o)=>{const s=l.join(t.map(i=>l`${i}`),l`, `);return o?l`${n} NOT IN (${s})`:l`${n} IN (${s})`},D=(n,t,o,s,i)=>{const r=o,e=[];for(const c of S){if(!(c in r))continue;const a=r[c],u=j[c];u?e.push(y(n,t,c,u,a,s,i)):c==="isNull"?e.push(i.nullCheck(t,!a)):c==="contains"?e.push(w(n,t,a,s,i)):e.push(C(n,t,c==="in"?"IN":"NOT IN",a,s,i))}return e},U=(n,t,o,s)=>{const i=o.fieldRef(n);return E(t)?D(n,i,t,o,s):t===null?[s.nullCheck(i,!1)]:[s.binary(i,"=",o.serialize(t,n))]},N=(n,t,o)=>{if(n.length<=1)return n[0];const s=Math.floor(n.length/2);return o.connect(N(n.slice(0,s),t,o),N(n.slice(s),t,o),t)},k=(n,t,o,s)=>{const i=Array.isArray(n)?n:[],r=[];for(const e of i){const c=f(e??{},o,s);c!==void 0&&r.push(c)}return r.length===0?t==="OR"?s.constant(!1):void 0:N(r,t,s)},M=new Set(["AND","NOT","OR",L]),P=(n,t,o,s)=>{if(n===L){if(!o.relationExists)throw new T("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return o.relationExists(t)}if(n==="NOT"){const i=f(t??{},o,s);return i===void 0?void 0:s.negate(i)}return k(t,n,o,s)},f=(n,t,o)=>{const s=[];for(const[i,r]of Object.entries(n))if(M.has(i)){const e=P(i,r,t,o);e!==void 0&&s.push(e)}else s.push(...U(i,r,t,o));return N(s,"AND",o)},q=O.boundParams/2,b=n=>{let t=0,o=0;const s=i=>{const r=b(i);t+=r.lists,o+=r.scalars};if(Array.isArray(n)){for(const i of n)s(i);return{lists:t,scalars:o}}if(n===null||typeof n!="object")return{lists:t,scalars:o};for(const[i,r]of Object.entries(n))i==="in"||i==="notIn"?t+=1:i==="AND"||i==="NOT"||i==="OR"||E(r)?s(r):o+=1;return{lists:t,scalars:o}},J=(n,t,o=R)=>{if(!n||Object.keys(n).length===0)return;const{lists:s,scalars:i}=b(n);if(s===0)return f(n,t,o);const r=Math.max(1,Math.floor(Math.min(q,O.boundParams-i)/s)),e=t.inList??((c,a,u,A)=>o.inList(c,a,u,A??r));return f(n,{...t,inList:(c,a,u)=>e(c,a,u,r)},o)};export{J as c,Y as i,p as j,G as l,I as r,Q as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{e as O}from"./effective-kind-BmG_zCAy.mjs";import{i as a}from"./relation-operators-BEg-CvCH.mjs";const u=Symbol.for("lunora.reader.whereFilter"),A=(e,r)=>Object.assign(t=>r(t),{[u]:e}),R=e=>e[u],m=new Set(["eq","in","isNull","ne","notIn"]),b=e=>e!==null&&typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype,l=(e,r)=>{if(e==="_id")return"string";if(e==="_creationTime")return"number";const t=e==="id"||!Object.hasOwn(r,e)?void 0:r[e];switch(t===void 0?void 0:O(t)){case"boolean":return"boolean";case"id":case"string":return"string";case"number":return"number";default:return}},c=(e,r)=>e===null||(r==="number"?typeof e=="number"&&Number.isFinite(e):typeof e===r),d=(e,r)=>Object.entries(e).every(([t,i])=>{if(t==="AND"||t==="OR")return Array.isArray(i)&&i.every(n=>b(n)&&d(n,r));if(t==="NOT"||a(i))return!1;const o=l(t,r);if(o===void 0)return!1;if(!b(i))return c(i,o);const f=Object.entries(i);return f.length>0&&f.every(([n,s])=>m.has(n)?n==="isNull"?typeof s=="boolean":n==="in"||n==="notIn"?Array.isArray(s)&&s.every(y=>c(y,o)):c(s,o):!1)});export{d as isPushableWhere,A as whereFilter,R as whereOfFilter};
|
|
File without changes
|