@lunora/shard-engine 1.0.0-alpha.80 → 1.0.0-alpha.82

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.
Files changed (57) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +40 -3
  3. package/dist/index.d.ts +40 -3
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/ADMIN_FUNCTIONS-BdZ3gTHm.mjs +1 -0
  6. package/dist/packem_shared/{AGG_COUNT-TzzFAsyw.mjs → AGG_COUNT-B7izQELK.mjs} +1 -1
  7. package/dist/packem_shared/{AUDIT_LOG_TABLE-ONxmEAIz.mjs → AUDIT_LOG_TABLE-CEdsC6vT.mjs} +1 -1
  8. package/dist/packem_shared/{CDC_LOG_TABLE-DXEAcmsr.mjs → CDC_LOG_TABLE-BFbP2eiJ.mjs} +1 -1
  9. package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs → CLIENT_WATERMARK_TABLE-BdKYbah0.mjs} +1 -1
  10. package/dist/packem_shared/{COMMIT_SEQ_FIELD-BUdOMG5y.mjs → COMMIT_SEQ_FIELD-D6uMUaiR.mjs} +1 -1
  11. package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-BwFz6NTT.mjs → DATA_MIGRATION_STATE_TABLE-BbDr6pc7.mjs} +1 -1
  12. package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs → DEFAULT_MAX_RELATION_KEYS-BfAQvZT8.mjs} +1 -1
  13. package/dist/packem_shared/{DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs → DEFAULT_MAX_RELAYS-DG9iXjzF.mjs} +1 -1
  14. package/dist/packem_shared/{DurableStreamRunner-rTYp4v03.mjs → DurableStreamRunner-Cliu09-j.mjs} +1 -1
  15. package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-wWaEWj5f.mjs} +1 -1
  16. package/dist/packem_shared/{IDEMPOTENCY_TABLE-DOpm_oMF.mjs → IDEMPOTENCY_TABLE-DKrXVEUe.mjs} +1 -1
  17. package/dist/packem_shared/{MAIL_RETENTION-DGAQTHHs.mjs → MAIL_RETENTION-DXpGFjOt.mjs} +1 -1
  18. package/dist/packem_shared/NotUniqueError-D0LwVtXI.mjs +1 -0
  19. package/dist/packem_shared/{QUEUE_TABLE-s7QJZvBz.mjs → QUEUE_TABLE-D-cL1NPj.mjs} +1 -1
  20. package/dist/packem_shared/{REACTOR_STATE_TABLE-QPRFyxMS.mjs → REACTOR_STATE_TABLE-CBHASjH9.mjs} +1 -1
  21. package/dist/packem_shared/{SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs → SCHEDULE_OUTBOX_TABLE-BHpxtEy4.mjs} +1 -1
  22. package/dist/packem_shared/{SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs → SCHEMA_HISTORY_MAX_VERSIONS-CXznJRUG.mjs} +1 -1
  23. package/dist/packem_shared/SEARCH_STATE_TABLE-D_KJ04Bn.mjs +1 -0
  24. package/dist/packem_shared/{SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs → SHAPE_POKE_CURSOR_TABLE-Bbpou9XZ.mjs} +1 -1
  25. package/dist/packem_shared/VECTOR_BACKFILL_MAX_PAGES-C-KZJbgA.mjs +1 -0
  26. package/dist/packem_shared/{appendStreamChunk-C1Ok4b6J.mjs → appendStreamChunk-pPeR5nbF.mjs} +1 -1
  27. package/dist/packem_shared/{archiveCdcSegment-E_R_b5Qz.mjs → archiveCdcSegment-C7taIEpg.mjs} +1 -1
  28. package/dist/packem_shared/backfillAggregateIndexes-D-S4qiCu.mjs +1 -0
  29. package/dist/packem_shared/{buildReprojectionMigration-DNjOe6AP.mjs → buildReprojectionMigration-DDZhSO95.mjs} +1 -1
  30. package/dist/packem_shared/{buildShapeDiff-CnCHKdCw.mjs → buildShapeDiff-Bd5nLaY8.mjs} +1 -1
  31. package/dist/packem_shared/{clearMemoryTables-BGbmag2i.mjs → clearMemoryTables-C5Wivufe.mjs} +1 -1
  32. package/dist/packem_shared/{computeRankPage-pTaG_r9F.mjs → computeRankPage-CQewnemg.mjs} +1 -1
  33. package/dist/packem_shared/createCompanionSync-BwWcSwvy.mjs +1 -0
  34. package/dist/packem_shared/{createReplicaLink-CUnl1y_Q.mjs → createReplicaLink-CTyOjpjh.mjs} +1 -1
  35. package/dist/packem_shared/{ctx-db-relay-shapes-Bg5YYnmN.mjs → ctx-db-relay-shapes-BcgjOtG1.mjs} +1 -1
  36. package/dist/packem_shared/ctx-db-search-state-fIiMVPXO.mjs +1 -0
  37. package/dist/packem_shared/{defineEngineContractSuite-BS0T_g0Z.mjs → defineEngineContractSuite-BD9v9a97.mjs} +1 -1
  38. package/dist/packem_shared/{do-sql-kpl5Kt1j.mjs → do-sql-BSoH-O04.mjs} +1 -1
  39. package/dist/packem_shared/{exportShardRows-1TkeNJI6.mjs → exportShardRows-DmFKSzLZ.mjs} +1 -1
  40. package/dist/packem_shared/fts-companion-B7jllLhZ.mjs +1 -0
  41. package/dist/packem_shared/ftsCompanionDdl-BKeIk9KQ.mjs +1 -0
  42. package/dist/packem_shared/{isSoftDeleted-DIMlSsdB.mjs → isSoftDeleted-CCDHCtX3.mjs} +1 -1
  43. package/dist/packem_shared/{materializeExternalRows-B1623YXA.mjs → materializeExternalRows-j_8glxcE.mjs} +1 -1
  44. package/dist/packem_shared/runDrizzle-CfKnGpV2.mjs +1 -0
  45. package/dist/packem_shared/runShardMigrations-o-qjyKt5.mjs +5 -0
  46. package/dist/packem_shared/{selectExpiredIds-D5DEpBbi.mjs → selectExpiredIds-Do1q2HQr.mjs} +1 -1
  47. package/dist/packem_shared/{selectShapeMembers-B8gTOeOB.mjs → selectShapeMembers-Cp98I-ot.mjs} +1 -1
  48. package/package.json +2 -2
  49. package/dist/packem_shared/ADMIN_FUNCTIONS-BjpFlIz5.mjs +0 -1
  50. package/dist/packem_shared/NotUniqueError-1OMgp1sA.mjs +0 -1
  51. package/dist/packem_shared/SEARCH_STATE_TABLE-D5mnK5kX.mjs +0 -1
  52. package/dist/packem_shared/backfillAggregateIndexes-DTemznr7.mjs +0 -1
  53. package/dist/packem_shared/createCompanionSync-Cb567rkq.mjs +0 -1
  54. package/dist/packem_shared/ctx-db-companions-DsNfXSbb.mjs +0 -1
  55. package/dist/packem_shared/ctx-db-search-state-ruTuCsxa.mjs +0 -1
  56. package/dist/packem_shared/runDrizzle-2ULFQR_k.mjs +0 -1
  57. package/dist/packem_shared/runShardMigrations-DGlaC68E.mjs +0 -5
@@ -1 +0,0 @@
1
- import{LunoraError as $}from"@lunora/errors";import{D as dt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{c as mn,S as Sn,l as Fe,a as _n}from"./ctx-db-companions-DsNfXSbb.mjs";import{sql as i}from"drizzle-orm";import{d as Rn}from"./wire-codec-C-FpWm52.mjs";import{stableWireKey as At}from"./stableWireKey-D2US4k_J.mjs";import{throwingScheduler as Tn,aggregateSqlFunction as qe,normalizeCountArgument as vn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Je,encodeAggregateKey as Ye,readAggregateValue as Xe}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as z,CountRlsUnsupportedError as Ze,selectIndexForGroupBy as An,selectIndexForCount as In,selectIndexForAggregate as Cn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as xn,searchIndexCoversTable as bn}from"./backfillAggregateIndexes-DTemznr7.mjs";import{backfillAggregateIndexes as Pr,backfillRankIndexes as Ur,backfillSearchIndexes as Gr}from"./backfillAggregateIndexes-DTemznr7.mjs";import{appendCdcChange as Mn,readCdcDocAtOrBefore as Dn}from"./CDC_LOG_TABLE-DXEAcmsr.mjs";import{CDC_LOG_TABLE as Hr,applyCdcChanges as Nr,bumpCdcEpoch as jr,cdcCanVouchFor as Kr,cdcForkedError as Qr,cdcSeqLeavingRows as Vr,cdcTouchesTables as zr,cdcTrimmedError as Jr,compactCdcDocs as Yr,cursorBelowRetainedFloor as Xr,minCdcReplayableSeq as Zr,minCdcSeq as ei,readCdcChangeKeys as ti,readCdcChanges as ni,readCdcCursor as oi,readCdcEpoch as ri,trimCdcChanges as ii}from"./CDC_LOG_TABLE-DXEAcmsr.mjs";import{allocateCommitSeq as kn,COMMIT_SEQ_FIELD as Ln}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as It}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Ct}from"./computeRankPage-pTaG_r9F.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as N,runSql as _e}from"./runDrizzle-2ULFQR_k.mjs";import{D as ne,k as ce,r as le,b as Be,A as et,a as We,e as X,o as Fn,t as Yt,j as Ge,q as xt,i as qn,h as Xt,g as Bn}from"./do-sql-kpl5Kt1j.mjs";import{renderSql as Zt,unionAll as lt,WORKERD_SQLITE_LIMITS as en,sqliteInList as Wn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Pn,boundingBoxGeohashes as Un,haversineMeters as Gn,pointInBoundingBox as On}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Hn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as it,uniqueIndexFields as tn,equalityPinnedFields as Nn,buildSeekWhere as nn,decodeCursor as st,applySelect as bt,encodeCursor as ct,tiebreakDirectionFor as on,buildSeekBeforeWhere as jn}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as Mt,sortColumnName as Dt,resolveRankPartition as Kn,encodePartitionKey as Qn,RANK_TIEBREAK as Vn,rankPivotConditionSql as zn}from"./RANK_TIEBREAK-D5xNdzB3.mjs";import{UNVOUCHABLE_DEP as kt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Jn,buildIndexRange as Yn}from"./buildIndexRange-DvN8Qj8e.mjs";import{deriveRelationEdges as Xn,findRelated as Zn}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as tt,resolveRelationPredicates as Lt}from"./DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{runRowValidators as nt,resolveWith as Ft,relationHooks as qt,applyOnDelete as eo,fanOutScalarCounts as to}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as no}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{quoteIdentifier as Re}from"./quoteIdentifier-CObIFRhb.mjs";import{m as oo}from"./sql-projection-D3qdaItY.mjs";import{createSystemReader as ro}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as me}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as io}from"./hasTrigger-CjlwI4le.mjs";import{c as te,t as He,r as Oe,j as Se,i as Bt}from"./where-sql-x1YKldcq.mjs";import{CLIENT_WATERMARK_TABLE as ci,advanceClientWatermark as ai,migrateClientWatermark as di,readClientWatermark as li}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as fi,deleteGlobalShapeSnapshot as hi,deleteGlobalShapeSnapshotsForConnection as wi,migrateGlobalShapeSnapshot as pi,readGlobalShapeSnapshot as gi,writeGlobalShapeSnapshot as $i}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Ei,readIdempotent as mi,trimIdempotent as Si,writeIdempotent as _i}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as Ti}from"./runShardMigrations-DGlaC68E.mjs";import{S as Ai}from"./ctx-db-search-state-ruTuCsxa.mjs";import{selectShapeMembers as Ci,selectShapeRows as xi}from"./selectShapeMembers-B8gTOeOB.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-BEMMYX1n.mjs";const so=n=>{const r=atob(n),o=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(o)},co=()=>new $("BAD_REQUEST","invalid cursor"),Wt=16,Pt=8,Y=1024,ut=(n,r)=>r.query(n),ao=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[a,s]of r.entries()){const w=a===r.length-1;let y=0;for(const R of n)(w?R.startsWith(s):R===s)&&(y+=1);if(y===0)return 0;o+=y}return o},lo=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",a=(o.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>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(a)}},uo=(n,r,o)=>{const a={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>=Pt)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(Pt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),a},search:(s,w)=>{const y=n;if(s!==y.definition.field)throw new $("INTERNAL",`search index "${y.indexName}" on table "${r}" indexes "${y.definition.field}", not "${s}"`);const R=ut(w,o).length;if(R>Wt)throw new $("BAD_REQUEST",`search index "${y.indexName}" on table "${r}": at most ${String(Wt)} search terms are supported (got ${String(R)})`);return y.field=s,y.query=w,y.hasQuery=!0,a}};return a},fo=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()`)},ho=n=>Math.min(n.offset+n.numItems+1,Y),wo=n=>btoa(`search:${String(n)}`),po=n=>{let r;try{r=so(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},go=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?po(n.cursor):0;if(o===void 0)throw co();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}},$o=(n,r)=>{const o=r.offset+r.numItems,a=r.numItems>0&&n.length>o;return{continueCursor:a?wo(o):null,isDone:!a,page:n.slice(r.offset,o)}},yo=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},Ne=n=>{const r=new Map;return o=>{const a=r.get(o);if(a!==void 0)return a;const s=n(Re(o));return r.set(o,s),s}},ue=Re(ne),Eo=Ne(n=>`INSERT INTO ${n} (id, _creationTime, ${ue}) VALUES (?, ?, ?)`),Ut=Ne(n=>`UPDATE ${n} SET ${ue} = ? WHERE id = ? AND ${ue} = ?`),mo=Ne(n=>`UPDATE ${n} SET _creationTime = ?, ${ue} = ? WHERE id = ? AND ${ue} = ?`),So=Ne(n=>`DELETE FROM ${n} WHERE id = ? AND ${ue} = ?`),_o="SELECT changes() AS changed",Gt=new Map,Ro="",To=n=>{const r=JSON.stringify(n),o=Gt.get(r);if(o!==void 0)return o;const a=n.map(w=>i`SELECT ${i.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(w)} WHERE id = ${Ro}`),{sql:s}=Zt("sqlite",i`${lt(a)} LIMIT 1`);return Gt.set(r,s),s},vo=(n,r)=>r.map(()=>n),Ao=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Io=n=>{if(!Ao.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Ot=50,rn=500,Pe=Math.floor(en.boundParams/3),ye=en.boundParams,Co=128,ae=(n,r,o)=>{const a=r??rn;if(n>a)throw new $("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},xo=n=>{const r={eq:(o,a)=>(n.sqlConditions.push({comparator:"=",field:o,value:a}),r),gt:(o,a)=>(n.sqlConditions.push({comparator:">",field:o,value:a}),r),gte:(o,a)=>(n.sqlConditions.push({comparator:">=",field:o,value:a}),r),lt:(o,a)=>(n.sqlConditions.push({comparator:"<",field:o,value:a}),r),lte:(o,a)=>(n.sqlConditions.push({comparator:"<=",field:o,value:a}),r)};return r},bo=n=>Math.max(n,Y),sn=(n,r)=>{const o=n.filters.map(a=>i`${X(a.field)} = ${oe(a.value)}`);return r&&o.push(r),o},Mo=(n,r,o,a,s)=>{const w=ut(o.query,dt(o.definition.language));if(w.length===0)return[];const y=Sn(r,o.indexName),R=`${y}__vocab`,_=w.length-1,k=w.map((q,F)=>{const W=lo(q,F===_),x=W.exact?i`${i.identifier("term")} = ${W.lower}`:i`${i.identifier("term")} >= ${W.lower} AND ${i.identifier("term")} < ${W.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(F))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(R)} WHERE ${x} GROUP BY ${i.identifier("doc")}`}),g=w.map((q,F)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(F))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),v=i`SELECT f.${i.identifier(Fe)} AS ${i.identifier(Fe)}, ${i.join(g,i` + `)} AS ${i.identifier("__score__")} FROM (${lt(k)}) u JOIN ${i.identifier(y)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Fe)} HAVING ${i.join(g.map(q=>i`${q} > 0`),i` AND `)}`,T=sn(o,s);let L=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${v}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Fe)}`;T.length>0&&(L=i`${L} WHERE ${i.join(T,i` AND `)}`),L=i`${L} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const H=[];for(const q of N(n,L)){const F=Xt(q);if(F){const W=q.__score__;H.push({document:F,score:typeof W=="number"?W:Number(W??0)})}}return H},Do=(n,r,o,a,s)=>{const w=dt(o.definition.language),y=ut(o.query,w);if(y.length===0)return[];const R=sn(o,s);let _=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;R.length>0&&(_=i`${_} WHERE ${i.join(R,i` AND `)}`),_=i`${_} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(bo(a)))}`;const k=N(n,_).toArray(),g=[];for(const v of k){const T=Xt(v);if(!T)continue;const L=ao(_n(T,o.definition),y);L>0&&g.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:L})}return g.sort((v,T)=>T.score-v.score||T.creationTime-v.creationTime||v.id.localeCompare(T.id)),g.slice(0,a).map(v=>({document:v.doc,score:v.score}))},ot=(n,r,o,a)=>{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 "${a}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},ko=(n,r)=>{const o=n,a={near:(s,w)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ot(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},a},within:s=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ot(s.sw,".within() sw corner",r,o.indexName),ot(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}},a}};return a},Lo=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:a,lng:s}=o;return typeof a=="number"&&typeof s=="number"?{lat:a,lng:s}:void 0},Fo=(n,r)=>{const o=Lo(n,r.definition.field);if(!o)return;const a=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const s=Gn(r.near.point,o);return s<=r.near.radiusMeters?{creationTime:a,distance:s}:void 0}return On(o,r.within)?{creationTime:a,distance:0}:void 0},qo=(n,r,o,a)=>{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?Pn(o.near.point,o.near.radiusMeters):Un(o.within),w=Bn(r,o.indexName),y=s.map(v=>i`(g.${i.identifier("__geohash__")} >= ${v} AND g.${i.identifier("__geohash__")} < ${`${v}{`})`),R=[i`(${i.join(y,i` OR `)})`];a&&R.push(a);const _=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)} FROM ${i.identifier(w)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(R,i` AND `)}`,k=N(n,_).toArray(),g=[];for(const v of k){const T=le(v),L=T?Fo(T,o):void 0;T&&L&&g.push({creationTime:L.creationTime,distance:L.distance,doc:T})}return g.sort((v,T)=>v.distance-T.distance||T.creationTime-v.creationTime),g},cn=(n,r,o,a)=>{const s=[];for(const w of n)if(r.every(y=>y(a(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},Bo=(n,r,o,a,s,w=()=>{})=>{const y=o.within!==void 0,R=qo(n,r,o,s).map(_=>({distanceMeters:y?null:_.distance,document:_.doc}));return w(R.length),typeof a=="number"?R.slice(0,Math.max(0,Math.floor(a))):R},an=(n,r,o,a,s,w=()=>{})=>{const{geo:y}=o;if(!y)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=o.inMemoryFilters.length>0,_=Bo(n,r,y,R?void 0:s,a,w);return R?cn(_,o.inMemoryFilters,s,k=>k.document):_},dn=(n,r,o,a)=>{const s=`SELECT id, _creationTime, ${Re(ne)} FROM ${Re(n)}`,w=`ORDER BY ${o}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Oe(`${s} ${w}`):Se(`${s} WHERE `,r,` ${w}`)},Wo=(n,r,o,a,s,w=()=>{})=>an(n,r,o,a,s,w).map(y=>y.document),Po=(n,r,o,a,s,w,y=()=>{})=>{const R=[];for(const v of o.sqlConditions)R.push(i`${X(v.field)} ${i.raw(v.comparator)} ${oe(v.value)}`);a&&R.push(a);let _=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;R.length>0&&(_=i`${_} WHERE ${i.join(R,i` AND `)}`),_=i`${_} ORDER BY ${s}`,typeof w=="number"&&o.inMemoryFilters.length===0&&(_=i`${_} LIMIT ${i.raw(String(Math.max(0,Math.floor(w))))}`);const k=N(n,_).toArray();y(k.length);const g=[];for(const v of k){const T=le(v);if(T&&o.inMemoryFilters.every(L=>L(T))&&(g.push(T),typeof w=="number"&&g.length>=w))break}return g},Ee={fieldRef:X,serialize:oe},ln=(n,r)=>{const o=r===void 0?void 0:n.shape[r];return o!==void 0&&oo(o)},Ht=(n,r)=>r.some(o=>ln(n,o)),Nt=(n,r,o)=>{if(ln(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)`)},ft={fieldRef:n=>Oe(Ge(n)),serialize:oe},Uo=n=>{let r=0;const o=[],a={fieldRef:s=>Oe(Ge(s)),relationExists:s=>{const{childWhere:w,negated:y,parentTable:R,relation:_}=s,k=`__rel_${String(r)}`,g=o.at(-1)??R;r+=1,n(_.table,O);const v=_.kind==="one"?_.field:_.references,T=_.kind==="one"?_.references:_.field,L=Oe(`${xt(k,T)} = ${xt(g,v)}`);o.push(k);const H=te(w,a,He);o.pop();const q=H===void 0?L:Se(L," AND ",H),F=Se("EXISTS (SELECT 1 FROM ",Bt(_.table)," AS ",Bt(k)," WHERE ",q,")");return y?Se("NOT ",F):F},serialize:oe};return a},un=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(", ")},Go=n=>{const r=n.map(o=>i`${X(o.field)} ${i.raw(o.direction==="desc"?"DESC":"ASC")}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(i`${X("id")} ${i.raw(on(n)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},Oo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},fn=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),Ho=n=>{const r=fn(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},hn=(n,r)=>{const o=n.order,a=Ho(n),{shape:s}=r;return a.length>0?it(a.map(w=>({[w]:o})),s,{pinned:fn(n),uniqueBy:tn(r.indexes,s)}):it([{_creationTime:o}],s)},No=(n,r,o,a)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Oo[w.comparator]??"eq"]:w.value}}));if(o&&s.push(nn(r,st(o))),a&&s.push(jn(r,st(a))),s.length!==0)return s.length===1?s[0]:{AND:s}},jo=(n,r,o)=>{const a=[];for(const s of n){const w=le(s);if(w&&r.every(y=>y(w))&&(a.push(w),o!==void 0&&a.length>o))break}return a},Ko=(n,r,o,a,s,w,y=()=>{})=>{const R=Math.max(0,Math.floor(s.numItems)),_=hn(a,o),k=typeof s.endCursor=="string",g=te(No(a,_,s.cursor,s.endCursor),ft,He),v=w&&g?Se(g," AND ",w):w??g,T=a.inMemoryFilters.length>0,L=dn(r,v,un(_),T||k?void 0:R+1),H=_e(n,L.text,...L.params).toArray();y(H.length);const q=jo(H,a.inMemoryFilters,T||k?void 0:R);if(k){const j=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:s.endCursor??null,isDone:!0,page:q,splitCursor:j?ct(j,_):null}}const F=q.length>R,W=F?q.slice(0,R):q,x=W.at(-1);return{continueCursor:F&&x?ct(x,_):null,isDone:!F,page:W}};class Qo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Vo=/\s/u,zo=String.fromCodePoint(0),jt=(n,r,o)=>{if(!n.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Vo.test(o)||o.includes(zo)?null:o},Jo=(n,r,o,a=()=>{},s=()=>{},w=()=>{})=>{const y=r.tables[o];if(!y)throw new $("INTERNAL",`unknown table: ${o}`);const R=de(y.softDeleteMode,void 0),_=R?te(R,Ee):void 0,k=R?te(R,ft,He):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let v=0;const T=m=>{const{search:C}=g;if(!C)throw new $("INTERNAL","runSearchFetch called without a staged search");xn(n,o,y);const b=g.inMemoryFilters.length>0,M=yo(b?void 0:m),K=qn(n);if(K&&!bn(n,o,C.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${C.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 re=K?Mo(n,o,C,M,_):Do(n,o,C,M,_);return b?(v=re.length,cn(re,g.inMemoryFilters,m,Te=>Te.document)):(m===void 0&&fo(re),re)},L=m=>T(m).map(C=>C.document),H=m=>{const C=go(m);return $o(L(ho(C)),C)},q=()=>Go(hn(g,y)),F=()=>{if(g.search||g.geo||g.indexName===void 0){s(void 0);return}s(Yn(o,g.indexName,g.indexFields,g.sqlConditions,oe))},W=m=>{F();let C=0;const b=(()=>{if(g.search){const M=L(m);return C=v,M}return g.geo?Wo(n,o,g,_,m,M=>{C=M}):Po(n,o,g,_,q(),m,M=>{C=M})})();return w(Math.max(C,b.length)),b},x=()=>{if(!g.search&&!g.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);F();let m=0;const C=(()=>{if(g.search){const b=T(void 0);return m=v,b}return an(n,o,g,_,void 0,b=>{m=b})})();return w(Math.max(m,C.length)),C},j={async*[Symbol.asyncIterator](){if(g.search){yield*W(void 0);return}const m=[...g.inMemoryFilters];let C;g.inMemoryFilters=[];try{for(;;){const b=await j.paginate({cursor:C??null,numItems:Co});for(const M of b.page)m.every(K=>K(M))&&(yield M);if(b.isDone||b.continueCursor===null)return;C=b.continueCursor}}finally{g.inMemoryFilters=m}},async collect(){return W(void 0)},async collectWithScores(){return x()},filter(m){return g.inMemoryFilters.push(m),j},async first(){return W(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return g.order=m==="desc"?"desc":"asc",j},async paginate(m){let C=0;if(F(),g.search){const M=H(m);return w(M.page.length),M}if(g.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const b=Ko(n,o,y,g,m,k,M=>{C=M});return w(Math.max(C,b.page.length)),b},async take(m){return W(m)},async unique(){const m=W(g.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new Qo(`unique() on table "${o}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,C){const b=(y.geoIndexes??[]).find(K=>K.name===m);if(!b)throw new $("INTERNAL",`unknown geo index "${m}" on table "${o}"`);a(o,m,"geo");const M={definition:b,indexName:m};if(g.geo=M,C(ko(M,o)),!M.near&&!M.within)throw new $("INTERNAL",`geo index "${m}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(m,C){const b=y.indexes.find(M=>M.name===m);if(!b)throw new $("INTERNAL",`unknown index "${m}" on table "${o}"`);return a(o,m,"index"),g.indexName=m,g.indexFields=b.fields,C&&C(xo(g)),j},withSearchIndex(m,C){const b=(y.searchIndexes??[]).find(K=>K.name===m);if(!b)throw new $("INTERNAL",`unknown search index "${m}" on table "${o}"`);a(o,m,"search");const M={definition:b,field:b.field,filters:[],hasQuery:!1,indexName:m,query:""};if(g.search=M,C(uo(M,o,dt(b.language))),!M.hasQuery)throw new $("INTERNAL",`search index "${m}" on table "${o}" requires a .search(field, query) call`);return j}};return j},Kt=(n,r,o)=>{const a={...r};for(const[s,w]of Yt(n)){if(w.serverDefault){a[s]=w.serverDefault({auth:o});continue}a[s]===void 0&&(w.defaultFn?a[s]=w.defaultFn():"defaultValue"in w&&(a[s]=w.defaultValue))}return a},Qt=(n,r,o,a)=>{const s=o;for(const[w,y]of Yt(n)){if(y.serverDefault){w in r&&(s[w]=y.serverDefault({auth:a}));continue}y.onUpdateFn&&!(w in r)&&(s[w]=y.onUpdateFn())}},Vt=(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.`)},zt=["_commitSeq","_creationTime","_id"],rt=n=>zt.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!zt.includes(r))):n,Yo=/unique constraint failed/i,Xo=n=>n instanceof Error&&Yo.test(n.message),Zo=/string or blob too big/iu,er=(n,r)=>{if(!(!(n instanceof Error)||!Zo.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.`)},at=(n,r,o,a)=>{try{_e(n,o,...a)}catch(s){throw Xo(s)?new me(`unique constraint violation on "${r}"`,"unique"):(er(s,r),s)}},Ue=(n,r,o,a)=>{if(at(n,r,o,a),_e(n,_o).one().changed===0)throw new me(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Jt=(n,r,o,a,s,w,y)=>{const R=[];for(let v=0;v<o.length+1;v+=1){const T=o[v],L=a[v],H=L?.direction==="desc"?"desc":"asc",q=T===void 0||L===void 0?i`${i.identifier(Vn)} < ${y}`:zn(T,w[v],H,!1);if(q===void 0)continue;const F=[];for(let x=0;x<v;x+=1)F.push(i`${i.identifier(o[x])} IS ${w[x]}`);F.push(q);const[W]=F;R.push(F.length===1&&W!==void 0?W:i`(${i.join(F,i` AND `)})`)}const _=R.length>0?i.join(R,i` OR `):i`1 = 0`,k=N(n,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${s} AND (${_})`).one(),g=N(n,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${s}`).one();return{before:k.c,total:g.c}},qr=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{sql:a}=n,{schema:s}=n,w=n.broadcast??(()=>{}),y=Xn(s);let R;const _=()=>n.inTransaction?.()===!0,k=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((R===void 0||!_())&&(R=kn(a)),{[Ln]:R}),g=(e,...t)=>{const c=s.tables[e]?.indexes;if(!c||c.length===0)return;const f=[];for(const h of t)h&&f.push(...Jn(c,h,oe));return f.length>0?f:void 0},{headroom:v}=n;let T=!1;const L=async e=>{const t=T;T=!0;try{return await e()}finally{T=t}},H=n.onRead??(()=>{}),q=e=>{It(s.tables[e])&&H(kt,kt)},F=n.onReadRange??(e=>{H(e.table,O)}),W=e=>{q(e.table),F(e)},x=(e,t)=>{t!==void 0&&t!==O&&!T&&v?.recordRead(1),q(e),H(e,t)},j=n.onIndexUse??(()=>{}),m=n.onWrite??(()=>{}),C=e=>{T||v?.recordWrite(e)},b=async e=>{C(e.doc),await m(e)},{cache:M}=n,K=n.clock??(()=>Date.now()),re=n.idGenerator??(()=>crypto.randomUUID()),Te=n.scheduler??Tn,{globalDb:fe}=n,ve=n.auth??{identity:null,userId:null},ht=n.cdc??!1,je=Te,wn=ro({scheduler:typeof je.list=="function"&&typeof je.get=="function"?je:void 0,storage:n.storage}),he=(e,t,c,f)=>{ht&&!It(s.tables[e])&&Mn(a,K(),e,t,c,f)},pn=(e,t,c,f)=>{if(s.tables[e]?.dropStalePatchesMode!==!0||!ht)return!1;const h=r?.();if(h===void 0)return!1;const l=Dn(a,e,t,h);return l===void 0?!1:Object.keys(rt(c)).some(d=>At(l[d])!==At(f[d]))},ie=e=>s.tables[e]?.shardMode?.kind==="global",wt=(e,t)=>{if(ie(e)){if(!fe)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return fe}return U},Ke=e=>wt(e,"cascade"),V=(e,t)=>{if(ie(e)){if(!fe)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return fe}},pt=async(e,t,c,f,h)=>{h&&C(c);const l=await e.insert(t,c,f);return w({key:l,op:"insert",row:{...c,_id:l},table:t}),l},Qe=(e,t)=>wt(e,"relation load").findMany(e,t),gt=(e,t)=>(ie(e)&&x(e,O),Qe(e,t)),gn=e=>!ie(e.table),$t=n.relationExistsPushDown??"auto",yt=$t!=="never",{maxRelationKeys:Et}=n,Ae=(e,t,c)=>Lt(e,{fetcher:gt,maxRelationKeys:Et,relationBaseWhere:c,schema:s,tableName:t}),mt=async(e,t,c,f)=>{const h=V(e,"relation grouped count");if(h)return x(e,O),to((P,I)=>h.count(P,I),e,t,c,f);const l=s.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);x(e,O);const d=de(l.softDeleteMode,void 0),u={[t]:{in:c}},p=z(z(u,f),d),A=await Ae(p,e,void 0),E=te(A,Ee),D=X(t);let S=i`SELECT ${D} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;E&&(S=i`${S} WHERE ${E}`),S=i`${S} GROUP BY ${D}`;const B=N(a,S).toArray();return new Map(B.map(P=>[P.__fk__,P.count]))};let Ie=0;const St=new Set;for(const[e,t]of Object.entries(s.tables))for(const c of Object.values(t.triggerMap??{}))St.add(`${e} ${c.timing} ${c.op}`);const Z=(e,t,c)=>St.has(`${e} ${t} ${c}`),ee=async(e,t,c)=>{if(Ie+=1,Ie>Ot)throw Ie-=1,new me(`trigger recursion exceeded ${String(Ot)} levels on "${c.table}" — check for a self-triggering write`,"trigger");try{await io({ctx:yn,event:c,op:t,schema:s,tableName:c.table,timing:e})}finally{Ie-=1}},{ensureBackfilledForTable:we,ensureBackfilledIndex:Ve,ensureRankBackfilled:ze,ensureRankBackfilledForTable:pe,syncAggregates:Ce,syncCompanionsForInsert:_t,syncGeo:xe,syncRanks:ge,syncSearch:be}=mn({broadcast:w,indexKeysFor:(e,t)=>g(e,t),invalidateCache:(e,t,c)=>M?.invalidate(e,t,g(e,c)),recordCdc:he,schema:s,sql:a}),Rt=(e,t,c)=>{const{shardMode:f}=t;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(c.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${c.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})},Tt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),$e=e=>e===void 0||ie(e)?fe:void 0,se=(e,t)=>{const c=Tt(t);for(let f=0;f<c.length;f+=ye){const h=c.slice(f,f+ye),[l]=_e(a,To(h),...vo(e,h)).toArray();if(!l)continue;const d=l.__t__,u=le(l);if(typeof d!="string"||!u)return;const p=l[ne];return{docJson:typeof p=="string"?p:ce(p??{}),row:u,tableName:d}}},$n=(e,t)=>{const c=[...new Set(e)],f=new Map;if(c.length===0)return f;const h=Tt(t);for(let l=0;l<h.length;l+=ye){const d=h.slice(l,l+ye),u=Math.floor(ye/d.length),p=Wn(i`${i.identifier("id")}`,c,!1,u),A=d.map(E=>i`SELECT ${i.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(E)} WHERE ${p}`);for(const E of N(a,lt(A))){const{id:D,__t__:S}=E;typeof S=="string"&&typeof D=="string"&&f.set(D,S)}}return f},vt={assertRankPartitionLocal:Rt,ensureRankBackfilled:ze,onRead:x,rowToDocument:le,schema:s,sql:a},U={system:wn,async aggregate(e,t){const c=V(e,"aggregate");if(c)return x(e,O),c.aggregate(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(qe(t.op),t.op==="count")return U.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`);x(e,O);const h=de(f.softDeleteMode,void 0),l=z(z(t.baseWhere,t.where),h),d=await Ae(l,e,t.relationBaseWhere),u=d!==l;if(f.aggregateIndexes&&!t.baseWhere&&!u&&(!h||Ht(f,[t.field]))){const P=Cn(f.aggregateIndexes,t.op,t.field,t.where);if(P){Ve(e,P.index);const I=Ye(P.index.by??[],P.key),Q=Je(e,P.index.name),J=N(a,i`SELECT ${Be} AS value, ${et} AS count FROM ${i.identifier(Q)} WHERE ${We} = ${I}`).toArray()[0];return Xe(t.op,J)}}Nt(f,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=te(d,Ee),A=qe(t.op),E=X(t.field);let D=i`SELECT ${i.raw(A)}(${E}) AS value FROM ${i.identifier(e)}`;p&&(D=i`${D} WHERE ${p}`);const B=N(a,D).toArray()[0]?.value;return B??null},asId(e,t){const c=jt(s,e,t);if(c===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return c},async count(e,t){const c=V(e,"count");if(c)return x(e,O),c.count(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=vn(t);if(h.restrictsCounts)throw new Ze(e);x(e,O);const l=de(f.softDeleteMode,void 0),d=z(z(h.baseWhere,h.where),l),u=await Ae(d,e,h.relationBaseWhere),p=u!==d;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!l){const S=In(f.aggregateIndexes,h.where);if(S){Ve(e,S.index);const B=Ye(S.index.by??[],S.key),P=Je(e,S.index.name),I=N(a,i`SELECT ${Be} AS value FROM ${i.identifier(P)} WHERE ${We} = ${B}`).toArray();return I[0]===void 0?0:I[0].value??0}}const A=te(u,Ee);let E=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return A&&(E=i`${E} WHERE ${A}`),N(a,E).one().count},async delete(e,t,c){const f=se(e,t);if(!f){const E=$e(t);E&&(C(void 0),await E.delete(e,t,c));return}const{docJson:h,row:l,tableName:d}=f,u=s.tables[d],p=c?.hard===!0,A=!p&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(A&&l[A]!==null&&l[A]!==void 0)){if(Z(d,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:d}),await eo({deletedId:e,deletedReference:E=>l[E],findHolders:async(E,D,S)=>(await Ke(E).findMany(E,{includeDeleted:p,where:{[D]:S}})).page,onCascade:(E,D)=>Ke(E).delete(D,void 0,c),onRestrict:E=>{throw new me(E,"restrict")},onSetNull:(E,D,S)=>Ke(E).patch(D,{[S]:null}),schema:s,tableName:d}),we(d),pe(d),A){const E={...l,...k(d),[A]:K(),_id:e};Ue(a,d,Ut(d),[ce(E),e,h]),be(d,e,E,l),xe(d,e,void 0),Ce(d,l,E),ge(d,e,l,void 0),M?.invalidate(d,e,g(d,l,E)),he(d,e,"update",E),w({indexKeys:g(d,l,E),key:e,op:"update",row:E,table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:d}),await b({id:e,op:"delete",table:d});return}Ue(a,d,So(d),[e,h]),be(d,e,void 0),xe(d,e,void 0),Ce(d,l,void 0),ge(d,e,l,void 0),M?.invalidate(d,e,g(d,l)),he(d,e,"delete"),w({indexKeys:g(d,l),key:e,op:"delete",table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:d}),await b({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!s.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const c=Math.max(1,t?.chunkSize??rn),f=t?.hard===void 0?void 0:{hard:t.hard},h=ie(e)?void 0:e;let l=0;return await L(async()=>{for(;;){const u=(await U.findMany(e,{limit:c})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await U.delete(p,h,f),l+=1;if(u.length<c)break}}),{deleted:l}},async deleteMany(e,t,c){ae(e.length,t?.limit,"deleteMany");for(const f of e)await U.delete(f,c);return{deleted:e.length}},async deleteWhere(e,t,c){const l=(await(V(e,"deleteWhere")??U).findMany(e,{where:t})).page.map(d=>String(d._id));if(ae(l.length,c?.limit,"deleteWhere"),U.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(l,c)},async findFirst(e,t={}){return(await U.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const c=await U.findFirst(e,t);if(c===null)throw new Hn(`findFirstOrThrow: no "${e}" document matched`);return c},async findMany(e,t={}){const c=V(e,"findMany");if(c)return x(e,O),c.findMany(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?x(e,O):x(e);const l=it(t.orderBy,f.shape,{pinned:Nn(t.where),uniqueBy:tn(f.indexes,f.shape)}),d=t.cursor?nn(l,st(t.cursor)):void 0;let u=z(t.baseWhere,t.where);u=z(u,de(f.softDeleteMode,t.includeDeleted)),u=await Lt(u,{canPushExists:yt?gn:void 0,existsPushMode:$t==="always"?"always":"auto",fetcher:gt,maxRelationKeys:Et,relationBaseWhere:t.relationBaseWhere,schema:s,tableName:e}),d&&(u=u?{AND:[u,d]}:d);const p=yt?Uo(x):ft,A=te(u,p,He),E=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0,D=dn(e,A,un(l),E===void 0?void 0:E+1),S=_e(a,D.text,...D.params).toArray();h&&!T&&v?.recordRead(S.length);const B=[];for(const J of S){const G=le(J);G&&(B.push(G),!h&&typeof G._id=="string"&&x(e,G._id))}if(E===void 0)return t.with&&await Ft({groupedCounter:mt,fetcher:Qe,parents:B,...qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:bt(B,t.select,t.with)};const P=B.length>E,I=P?B.slice(0,E):B,Q=I.at(-1);return t.with&&await Ft({fetcher:Qe,groupedCounter:mt,parents:I,...qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:P&&Q&&t.omitContinueCursor!==!0?ct(Q,l):null,isDone:!P,page:bt(I,t.select,t.with)}},async get(e,t){const c=se(e,t);if(!c){const f=$e(t);return f?f.get(e,t):null}return x(c.tableName,e),c.row},async lookupById(e,t){const c=se(e,t);return c?(x(c.tableName,e),{row:c.row,tableName:c.tableName}):null},async groupBy(e,t){const c=V(e,"groupBy");if(c)return x(e,O),c.groupBy(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);x(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=de(f.softDeleteMode,void 0),d=z(z(t.baseWhere,t.where),l),u=await Ae(d,e,t.relationBaseWhere),p=u!==d,A=[...t.by,h.field];if(f.aggregateIndexes&&!t.baseWhere&&!p&&(!l||Ht(f,A))){const I=An(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)){Ve(e,I.index);const G=Je(e,I.index.name),Me=Object.keys(I.partial),De=[];if(Me.length===(I.index.by??[]).length&&Me.length>0){const ke=Ye(I.index.by??[],I.partial),Le=N(a,i`SELECT ${Be} AS value, ${et} AS count FROM ${i.identifier(G)} WHERE ${We} = ${ke}`).toArray();return Le.length>0&&De.push({key:{...I.partial},value:Xe(h.op,Le[0])}),De}const En=N(a,i`SELECT ${We} AS key, ${Be} AS value, ${et} AS count FROM ${i.identifier(G)}`).toArray();for(const ke of En){const Le=Rn(JSON.parse(ke.key));De.push({key:Le,value:Xe(h.op,ke)})}return De}}for(const I of A){if(I===void 0)continue;const Q=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Nt(f,I,Q)}const E=te(u,Ee),D=t.by.map(I=>i`${X(I)} AS ${i.identifier(I)}`);if(h.op==="count")D.push(i`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(i`${i.raw(qe(h.op))}(${X(I)}) AS value`)}let S=i`SELECT ${i.join(D,i`, `)} FROM ${i.identifier(e)}`;E&&(S=i`${S} WHERE ${E}`),S=i`${S} GROUP BY ${i.join(t.by.map(I=>X(I)),i`, `)}`;const B=N(a,S).toArray(),P=[];for(const I of B){const Q={};for(const G of t.by)Q[G]=Fn(f.shape[G],I[G]??null);const{value:J}=I;P.push({key:Q,value:J==null?null:Number(J)})}return P},async insert(e,t,c){const f=V(e,"insert");if(f)return pt(f,e,t,c,!0);const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Kt(h,t,ve);nt(h,l);let d;c?.clientId!==void 0?(Io(c.clientId),d=c.clientId):c?.allowExplicitId&&typeof l._id=="string"?d=l._id:d=re();const u=c?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:K(),p={...l,...k(e),_creationTime:u,_id:d};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...p},id:d,op:"insert",table:e}),we(e),pe(e),at(a,e,Eo(e),[d,u,ce(p)]),_t(e,d,p),Z(e,"after","insert")&&await ee("after","insert",{doc:p,id:d,op:"insert",table:e}),await b({doc:p,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,t,c){if(ae(t.length,c?.limit,"insertManyUnsafe"),t.length===0)return[];const f=V(e,"insert");if(f){const u=[];for(const p of t)C(p);for(const p of t){const A=await f.insert(e,p,{allowExplicitId:c?.allowExplicitId});w({key:A,op:"insert",row:{...p,_id:A},table:e}),u.push(A)}return u}const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);we(e),pe(e);const l=[];for(let u=0;u<t.length;u+=Pe)l.push(k(e));const d=t.map((u,p)=>{const A=Kt(h,u,ve),E=c?.allowExplicitId===!0&&typeof A._id=="string"?A._id:re(),D=c?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:K(),S={...A,...l[Math.floor(p/Pe)],_creationTime:D,_id:E};return{creationTime:D,document:S,id:E}});for(const u of d)C(u.document);for(let u=0;u<d.length;u+=Pe){const p=i.join(d.slice(u,u+Pe).map(E=>i`(${E.id}, ${E.creationTime}, ${ce(E.document)})`),i`, `),A=Zt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(ne)}) VALUES ${p}`);at(a,e,A.sql,A.params)}for(const{document:u,id:p}of d)_t(e,p,u),await m({doc:u,id:p,op:"insert",table:e});return d.map(u=>u.id)},async insertMany(e,t,c){ae(t.length,c?.limit,"insertMany");const f=c?.skipDuplicates===!0,h=[],l=V(e,"insert");if(l)for(const u of t)C(u);const d=async u=>l?pt(l,e,u,void 0,!1):U.insert(e,u);for(const u of t)try{h.push(await d(u))}catch(p){if(f&&p instanceof me&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return jt(s,e,t)},async patch(e,t,c){const f=se(e,c);if(!f){const A=$e(c);if(A){C(t),await A.patch(e,t,c);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:d}=f,u=s.tables[d];if(!u)throw new $("INTERNAL",`unknown table: ${d}`);if(x(d,e),Vt("patch",t),pn(d,e,t,l)){o?.({fields:Object.keys(rt(t)),id:e,table:d});return}const p={...l,...rt(t),...k(d),_id:e};Qt(u,t,p,ve),nt(u,p,!0),Z(d,"before","update")&&await ee("before","update",{doc:{...p},id:e,op:"update",previous:l,table:d}),we(d),pe(d),Ue(a,d,Ut(d),[ce(p),e,h]),be(d,e,p,l),xe(d,e,p),Ce(d,l,p),ge(d,e,l,p),M?.invalidate(d,e,g(d,l,p)),he(d,e,"update",p),w({indexKeys:g(d,l,p),key:e,op:"update",row:p,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:p,id:e,op:"update",previous:l,table:d}),await b({doc:p,id:e,op:"update",table:d})},async patchMany(e,t,c){ae(e.length,t?.limit,"patchMany");for(const f of e)await U.patch(f.id,f.patch,c);return{patched:e.length}},async patchWhere(e,t,c){const l=(await(V(e,"patchWhere")??U).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(ae(l.length,c?.limit,"patchWhere"),U.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(l,c),{patched:l.length}},async related(e,t){return Zn(U,y,e,t)},relationEdges:y,query(e){const t=V(e,"query");return t?(x(e,O),t.query(e)):Jo(a,s,e,j,c=>{c?W(c):x(e,O)},c=>{T||v?.recordRead(c)})},async rank(e,t,c){const f=V(e,"rank");if(f)return x(e,O),f.rank(e,t,c);j(e,t,"rank");const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===t);if(!l)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Rt(e,h,l),c.restrictsCounts)throw new Ze(e);x(e,O),ze(e,l);const d=typeof c.row=="string"?c.row:c.row._id;if(!d)return null;const u=Mt(e,l.name),p=l.sortBy.map((G,Me)=>Dt(Me)),A=p.map(G=>Re(G)).join(", "),E=N(a,i`SELECT ${i.identifier("__partition__")}, ${i.raw(A)} FROM ${i.identifier(u)} WHERE ${i.identifier("__id__")} = ${d}`).toArray(),[D]=E;if(D===void 0)return null;let S=D.__partition__;const B=z(c.baseWhere,c.where);tt(B,s,e,"rank");const P=Kn(l,B);if(P){const G=Qn(l.partitionBy??[],P);if(G!==S)return null;S=G}const I=p.map(G=>D[G]),{before:Q,total:J}=Jt(a,u,p,l.sortBy,S,I,d);return{position:Q+1,total:J}},async rankBefore(e,t,c){if(ie(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(c.restrictsCounts)throw new Ze(e);x(e,O),ze(e,h);const l=Mt(e,h.name),d=h.sortBy.map((p,A)=>Dt(A)),u=h.sortBy.map((p,A)=>oe(c.sortValues[A]??null));return Jt(a,l,d,h.sortBy,c.partitionKey,u,c.rowId)},async rankPage(e,t,c={}){tt(z(c.baseWhere,c.where),s,e,"rankPage");const f=V(e,"rankPage");if(f)return x(e,O),f.rankPage(e,t,c);j(e,t,"rank");const{continueCursor:h,hasMore:l,rows:d}=Ct(vt,e,t,c);return{continueCursor:h,isDone:!l,page:d.map(u=>u.doc)}},async rankPageRows(e,t,c={}){tt(z(c.baseWhere,c.where),s,e,"rankPage"),j(e,t,"rank");const{directions:f,hasMore:h,rows:l}=Ct(vt,e,t,c);return{directions:f,hasMore:h,rows:l}},async restore(e,t){const c=se(e,t);if(!c){const l=$e(t);if(l?.restore){await l.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=s.tables[c.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${c.tableName}" is not a .softDelete() table`);const h=c.row[f]!==null&&c.row[f]!==void 0;await U.patch(e,{[f]:null},t),h&&ge(c.tableName,e,void 0,c.row)},async replace(e,t,c,f){const h=se(e,c);if(!h){const B=$e(c);if(B){C(t),await B.replace(e,t,c,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:l,row:d,tableName:u}=h,p=s.tables[u];if(!p)throw new $("INTERNAL",`unknown table: ${u}`);Vt("replace",t);const A=f?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,E=typeof d._creationTime=="number"?d._creationTime:void 0,D=A??E??K(),S={...t,...k(u),_creationTime:D,_id:e};Qt(p,t,S,ve),nt(p,S),Z(u,"before","update")&&await ee("before","update",{doc:{...S},id:e,op:"update",previous:d,table:u}),we(u),pe(u),Ue(a,u,mo(u),[D,ce(S),e,l]),be(u,e,S,d),xe(u,e,S),Ce(u,d,S),ge(u,e,d,S),M?.invalidate(u,e,g(u,d,S)),he(u,e,"update",S),w({indexKeys:g(u,d,S),key:e,op:"update",row:S,table:u}),Z(u,"after","update")&&await ee("after","update",{doc:S,id:e,op:"update",previous:d,table:u}),await b({doc:S,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),c=e?.tables,f=Object.entries(s.tables).filter(([u,p])=>t.has(u)||c!==void 0&&!c.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(c!==void 0){for(const u of c)if(!s.tables[u])throw new $("INTERNAL",`wipeShard: unknown table: ${u}`)}const h={};let l=0;const{deleteAll:d}=U;if(d===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of f){const p=await d(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[u]=p.deleted,l+=p.deleted}return{deleted:l,tables:h}}},yn={db:U,scheduler:Te};return n.enforceRls===!0?no(U,s,(e,t)=>se(e,t)?.tableName,(e,t)=>$n(e,t),y):U};export{Hr as CDC_LOG_TABLE,ci as CLIENT_WATERMARK_TABLE,fi as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ei as IDEMPOTENCY_TABLE,Qo as NotUniqueError,Ai as SEARCH_STATE_TABLE,ai as advanceClientWatermark,Nr as applyCdcChanges,Vt as assertNoExplicitUndefined,Io as assertValidClientId,Pr as backfillAggregateIndexes,Ur as backfillRankIndexes,Gr as backfillSearchIndexes,jr as bumpCdcEpoch,Kr as cdcCanVouchFor,Qr as cdcForkedError,Vr as cdcSeqLeavingRows,zr as cdcTouchesTables,Jr as cdcTrimmedError,Yr as compactCdcDocs,qr as createShardCtxDb,Xr as cursorBelowRetainedFloor,hi as deleteGlobalShapeSnapshot,wi as deleteGlobalShapeSnapshotsForConnection,di as migrateClientWatermark,pi as migrateGlobalShapeSnapshot,Zr as minCdcReplayableSeq,ei as minCdcSeq,jt as normalizeIdStructurally,ti as readCdcChangeKeys,ni as readCdcChanges,oi as readCdcCursor,ri as readCdcEpoch,li as readClientWatermark,gi as readGlobalShapeSnapshot,mi as readIdempotent,Ti as runShardMigrations,Ci as selectShapeMembers,xi as selectShapeRows,rt as stripReservedPatchFields,ii as trimCdcChanges,Si as trimIdempotent,$i as writeGlobalShapeSnapshot,_i as writeIdempotent};
@@ -1 +0,0 @@
1
- import{S as t,m as S,r as c,a as i,w as s}from"./ctx-db-search-state-ruTuCsxa.mjs";import"./runDrizzle-2ULFQR_k.mjs";export{t as SEARCH_STATE_TABLE,S as migrateSearchState,c as readSearchBackfillState,i as readSearchIndexCoverage,s as writeSearchBackfillState};
@@ -1 +0,0 @@
1
- import{m as O,c as T,l as b,r as E,a as C,w as L}from"./ctx-db-search-state-ruTuCsxa.mjs";import{S as R,r as M,i as x,l as h,y as _,d as y}from"./ctx-db-companions-DsNfXSbb.mjs";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as F}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as N,encodeAggregateKey as D,foldAggregateTally as v}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{i as w,r as p,a as B,b as G,A as U,D as I,h as H}from"./do-sql-kpl5Kt1j.mjs";import{isLiveForCompanion as P}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as W,matchesRankStaticWhere as V}from"./RANK_TIEBREAK-D5xNdzB3.mjs";const k=(e,o)=>l(e,t`SELECT COUNT(*) AS count FROM ${t.identifier(o)}`).one().count>0,Y=(e,o)=>l(e,t`SELECT 1 FROM ${t.identifier(o)} LIMIT 1`).toArray().length>0,A=(e,o)=>l(e,t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)}`).toArray(),j=(e,o,n,r)=>{const i=N(o,n.name);if(k(e,i))return;const c=n.by??[],a=new Map,s=A(e,o);for(const d of s){const f=p(d);if(!f||!P(f,r)||n.where&&!F(f,n.where))continue;const g=D(c,f);v(a,g,n,f)}for(const[d,f]of a)l(e,t`INSERT INTO ${t.identifier(i)} (${B}, ${G}, ${U}) VALUES (${d}, ${f.value}, ${f.count})`)},te=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.aggregateIndexes))for(const i of r.aggregateIndexes)j(e,n,i,r.softDeleteMode?.field)},K=(e,o,n)=>{const r=W(o,n.name);if(k(e,r))return;const i=M(n),c=A(e,o);for(const a of c){const s=p(a);!s||n.where&&!V(s,n.where)||x(e,r,n,i,s._id,s)}},ie=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.rankIndexes))for(const i of r.rankIndexes)K(e,n,i)},u=500,$=(e,o,n)=>{const r=R(o,n.name),i=T(n),c=b(E(e,r),i);if(c.finished)return{done:!0,rows:0};const{cursor:a}=c,s=l(e,a===void 0?t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} ORDER BY id ASC LIMIT ${t.raw(String(u))}`:t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} WHERE id > ${a} ORDER BY id ASC LIMIT ${t.raw(String(u))}`).toArray();let d=a;for(const g of s){const{id:m}=g;if(typeof m!="string")continue;d=m,l(e,t`DELETE FROM ${t.identifier(r)} WHERE ${t.identifier(h)} = ${m}`);const S=H(g);S&&l(e,t`INSERT INTO ${t.identifier(r)} (${t.identifier(_)}, ${t.identifier(h)}) VALUES (${y(S,n)}, ${m})`)}const f=s.length<u;return L(e,r,d,f,i),{done:f,rows:s.length}},ae=(e,o,n)=>{const r=R(o,n.name),i=T(n);return b(E(e,r),i).finished?!0:C(e,r)},se=(e,o,n)=>{if(w(e))for(const r of n.searchIndexes??[])r.staged&&Y(e,o)||$(e,o,r)},z=(e,o,n,r)=>{let i=0;for(;;){if(i>=r)return{done:!1,pages:i};const c=$(e,o,n);if(c.rows>0&&(i+=1),c.done)return{done:!0,pages:i}}},ce=(e,o,n={})=>{if(!w(e))return{done:!0,pages:0};O(e);const r=n.maxPages??Number.POSITIVE_INFINITY;let i=0;for(const[c,a]of Object.entries(o.tables))if(!(a.shardMode?.kind==="global"||!a.searchIndexes))for(const s of a.searchIndexes){const d=z(e,c,s,r-i);if(i+=d.pages,!d.done)return{done:!1,pages:i}}return{done:!0,pages:i}};export{te as backfillAggregateIndexes,ie as backfillRankIndexes,ce as backfillSearchIndexes,se as backfillSearchIndexesForTable,ae as searchIndexCoversTable};
@@ -1 +0,0 @@
1
- import{c as l,i as C,r as R}from"./ctx-db-companions-DsNfXSbb.mjs";import"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import"./aggregateTableName-C7o-gpms.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./do-sql-kpl5Kt1j.mjs";import"./param-DlozcSQu.mjs";import"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import"./CURSOR_PREFIX-Bn8SFoGd.mjs";import"./RANK_TIEBREAK-D5xNdzB3.mjs";import"./sql-projection-D3qdaItY.mjs";import"./serializeSqlValue-BEMMYX1n.mjs";export{l as createCompanionSync,C as insertRankRow,R as rankColumnsSql};
@@ -1 +0,0 @@
1
- import{D as ie}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as ce}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as z,encodeAggregateKey as v,foldAggregateTally as J,coerceAggregateNumber as b}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as u}from"./runDrizzle-2ULFQR_k.mjs";import{i as fe,g as ae,D as M,r as q,a as L,b as h,A as p,c as D,e as U}from"./do-sql-kpl5Kt1j.mjs";import{param as le,WORKERD_SQLITE_LIMITS as $e}from"./param-DlozcSQu.mjs";import{encodeGeohash as de,GEO_DEFAULT_PRECISION as ue}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as N}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{encodePartitionKey as Ee,sortColumnName as _e,rankTableName as X,matchesRankStaticWhere as Y}from"./RANK_TIEBREAK-D5xNdzB3.mjs";import{m as ye}from"./sql-projection-D3qdaItY.mjs";import{serializeSqlValue as Z}from"./serializeSqlValue-BEMMYX1n.mjs";const ge=(t,i)=>{if(!i.includes("."))return t[i];let f=t;for(const A of i.split(".")){if(f===null||typeof f!="object"||Array.isArray(f))return;f=f[A]}return f},pe=(t,i)=>`${t}__fts_${i}`,me="__text__",Q="__id__",he=1e3,Se=(t,i)=>i.document(t),W=(t,i)=>ge(t,i),Te=t=>typeof t=="string"?t:t==null?"":typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?String(t):JSON.stringify(t)??"",Re=(t,i,f)=>t!==void 0&&i!==void 0&&W(t,f.field)===W(i,f.field),Ae=(t,i)=>Se(Te(W(t,i.field)),ie(i.language)).slice(0,he),we=(t,i)=>Ae(t,i).join(" "),Fe=(t,i,f)=>[...t.partitionBy??[],...t.sortBy.map(S=>S.field),...t.where?Object.keys(t.where):[]].every(S=>i[S]===f[S]),x=t=>e.join(["__id__","__partition__",...t.sortBy.map((i,f)=>_e(f))].map(i=>e.identifier(i)),e`, `),ee=(t,i,f,A,S,y)=>{const c=Ee(f.partitionBy??[],y),C=f.sortBy.map(I=>Z(y[I.field]??null)),k=e.join([S,c,...C].map(I=>le(I)),e`, `);u(t,e`INSERT INTO ${e.identifier(i)} (${A}) VALUES (${k})`)},Oe=(t,i,f,A,S,y)=>{if(S&&y&&Fe(f,S,y))return;const c=X(i,f.name);S&&u(t,e`DELETE FROM ${e.identifier(c)} WHERE ${e.identifier("__id__")} = ${A}`),!(!y||f.where&&!Y(y,f.where))&&ee(t,c,f,x(f),A,y)},Be=t=>{const{broadcast:i,indexKeysFor:f,invalidateCache:A,recordCdc:S,schema:y,sql:c}=t,C=new Set,k=n=>y.tables[n]?.softDeleteMode?.field,I=new Set,j=(n,o)=>{const s=`${n}::${o.name}`;if(C.has(s))return;const l=z(n,o.name),$=o.by??[],d=k(n),_=new Map,m=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}`).toArray();for(const T of m){const E=q(T);if(!E||!N(E,d)||o.where&&!P(E,o.where))continue;const R=v($,E);J(_,R,o,E)}u(c,e`DELETE FROM ${e.identifier(l)}`);const w=Math.floor($e.boundParams/3),F=[..._];for(let T=0;T<F.length;T+=w){const E=F.slice(T,T+w),R=e.join(E.map(([r,a])=>e`(${r}, ${a.value}, ${a.count})`),e`, `);u(c,e`INSERT INTO ${e.identifier(l)} (${L}, ${h}, ${p}) VALUES ${R}`)}C.add(s)},oe=(n,o,s)=>{const l=o.by??[],$=o.field??"",d=[],_=(r,a)=>{const g=Z(a);g===null?d.push(e`${U(r)} IS NULL`):d.push(e`${U(r)} = ${g}`)};for(const r of l)_(r,s[r]??null);const m=k(n);m!==void 0&&_(m,null);for(const[r,a]of Object.entries(o.where??{}))_(r,a!==null&&typeof a=="object"&&!Array.isArray(a)?a.eq:a);const w=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``,F=y.tables[n]?.shape[$];if(F&&ye(F)){const r=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}${w}`).toArray(),a=new Map;for(const g of r){const O=q(g);O&&J(a,"",o,O)}return{value:a.get("")?.value??null}}const T=ce(o.op),E=U($);return{value:u(c,e`SELECT ${e.raw(T)}(${E}) AS value FROM ${e.identifier(n)}${w}`).one().value??null}},ne=(n,o,s,l)=>{const $=z(n,o.name),{op:d}=o,_=o.field??"",m=r=>{u(c,e`DELETE FROM ${e.identifier($)} WHERE ${L} = ${r} AND ${p} <= 0`)},w=k(n),F=r=>!o.where||P(r,o.where),T=r=>N(r,w)&&F(r);l!==void 0&&d!=="count"&&F(l)&&b(l[_]);const E=s&&T(s)?s:void 0,R=l&&T(l)?l:void 0;if(!(!E&&!R)){if(d==="count"){for(const[r,a]of[[E,-1],[R,1]]){if(!r)continue;const g=v(o.by??[],r);u(c,D($,g,a,a,e`${h} = ${h} + excluded.${h}, ${p} = ${p} + excluded.${p}`))}E&&m(v(o.by??[],E));return}if(d==="sum"||d==="avg"){for(const[r,a]of[[E,-1],[R,1]]){if(!r)continue;const g=b(r[_]);if(g===void 0)continue;const O=v(o.by??[],r);u(c,D($,O,a*g,a,e`${h} = COALESCE(${h}, 0) + excluded.${h}, ${p} = ${p} + excluded.${p}`))}E&&m(v(o.by??[],E));return}if(E){const r=v(o.by??[],E),a=b(E[_]),g=u(c,e`SELECT ${h} AS value, ${p} AS count FROM ${e.identifier($)} WHERE ${L} = ${r}`).toArray()[0],O=(g?.count??0)-1;if(O<=0)u(c,e`DELETE FROM ${e.identifier($)} WHERE ${L} = ${r}`);else if(g&&a!==void 0&&g.value!==null&&a===g.value){const se=oe(n,o,E);u(c,e`UPDATE ${e.identifier($)} SET ${h} = ${se.value}, ${p} = ${O} WHERE ${L} = ${r}`)}else u(c,e`UPDATE ${e.identifier($)} SET ${p} = ${p} - 1 WHERE ${L} = ${r}`)}if(R){const r=v(o.by??[],R),a=b(R[_]);if(a===void 0)u(c,D($,r,null,1,e`${p} = ${p} + 1`));else{const g=d==="min"?"MIN":"MAX";u(c,D($,r,a,1,e`${h} = ${e.raw(g)}(COALESCE(${h}, excluded.${h}), excluded.${h}), ${p} = ${p} + 1`))}}}},te=n=>{for(const o of y.tables[n]?.aggregateIndexes??[])j(n,o)},H=(n,o,s)=>{for(const l of y.tables[n]?.aggregateIndexes??[])ne(n,l,o,s)},B=(n,o)=>{const s=`${n}::rank::${o.name}`;if(I.has(s))return;const l=X(n,o.name),$=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}`).toArray();u(c,e`DELETE FROM ${e.identifier(l)}`);const d=x(o);for(const _ of $){const m=q(_);!m||o.where&&!Y(m,o.where)||ee(c,l,o,d,m._id,m)}I.add(s)},re=n=>{for(const o of y.tables[n]?.rankIndexes??[])B(n,o)},K=(n,o,s,l)=>{for(const $ of y.tables[n]?.rankIndexes??[])Oe(c,n,$,o,s,l)},V=(n,o,s,l)=>{const $=y.tables[n]?.searchIndexes??[];if(!($.length===0||!fe(c)))for(const d of $){if(Re(l,s,d))continue;const _=pe(n,d.name);u(c,e`DELETE FROM ${e.identifier(_)} WHERE ${e.identifier(Q)} = ${o}`),s&&u(c,e`INSERT INTO ${e.identifier(_)} (${e.identifier(me)}, ${e.identifier(Q)}) VALUES (${we(s,d)}, ${o})`)}},G=(n,o,s)=>{for(const l of y.tables[n]?.geoIndexes??[]){const $=ae(n,l.name);u(c,e`DELETE FROM ${e.identifier($)} WHERE ${e.identifier("__id__")} = ${o}`);const d=s?.[l.field];if(d!==null&&typeof d=="object"&&typeof d.lat=="number"&&typeof d.lng=="number"){const{lat:_,lng:m}=d,w=de({lat:_,lng:m},l.precision??ue);u(c,e`INSERT INTO ${e.identifier($)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${w}, ${_}, ${m})`)}}};return{ensureBackfilledForTable:te,ensureBackfilledIndex:j,ensureRankBackfilled:B,ensureRankBackfilledForTable:re,syncAggregates:H,syncCompanionsForInsert:(n,o,s)=>{V(n,o,s),G(n,o,s),H(n,void 0,s),K(n,o,void 0,s),A(n,o,s),S(n,o,"insert",s),i({indexKeys:f(n,s),key:o,op:"insert",row:s,table:n})},syncGeo:G,syncRanks:K,syncSearch:V}};export{pe as S,Ae as a,Be as c,we as d,ee as i,Q as l,x as r,me as y};
@@ -1 +0,0 @@
1
- import{D as T}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{runDrizzle as t}from"./runDrizzle-2ULFQR_k.mjs";const v=i=>`${T(i.language).profile}:${i.field}`,c=i=>{const r=i.slice(i.indexOf(":")+1),n=r.lastIndexOf("/");return n===-1?r:r.slice(0,n)},S=(i,r)=>i.profile!==r?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},a=(i,r)=>typeof i=="string"&&c(i)===c(r),o="__lunora_search_state",N=i=>{t(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(o)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0)`);try{t(i,e`ALTER TABLE ${e.identifier(o)} ADD COLUMN ${e.identifier("profile")} TEXT`)}catch{}try{t(i,e`ALTER TABLE ${e.identifier(o)} ADD COLUMN ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0`)}catch{}t(i,e`UPDATE ${e.identifier(o)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},s=i=>i===1||i===!0||i==="1",R=(i,r)=>{const n=t(i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(o)} WHERE ${e.identifier("companion")} = ${r}`).toArray();return s(n[0]?.covered)},l=(i,r)=>{const d=t(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(o)} WHERE ${e.identifier("companion")} = ${r}`).toArray()[0];return d?{cursor:d.cursor??void 0,done:s(d.done),profile:d.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},O=(i,r,n,d,f)=>{const $=n??null,E=a(l(i,r).profile,f)?e`MAX(${e.identifier(o)}.${e.identifier("covered")}, excluded.${e.identifier("covered")})`:e`excluded.${e.identifier("covered")}`;t(i,e`INSERT INTO ${e.identifier(o)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${r}, ${$}, ${d?1:0}, ${f}, ${d?1:0}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("covered")} = ${E}`)};export{o as S,R as a,v as c,S as l,N as m,l as r,O as w};
@@ -1 +0,0 @@
1
- import{LunoraError as s}from"@lunora/errors";import{renderSql as l,WORKERD_SQLITE_LIMITS as r}from"./param-DlozcSQu.mjs";const c=(t,n,...e)=>{if(n.length*3>r.sqlTextLength){const i=new TextEncoder().encode(n).length;if(i>r.sqlTextLength)throw new s("INTERNAL",`SQL statement is ${String(i)} bytes, over this runtime's ${String(r.sqlTextLength)}-byte limit`)}if(e.length>r.boundParams)throw new s("INTERNAL",`SQL statement binds ${String(e.length)} parameters, over this runtime's limit of ${String(r.boundParams)}`);return t.exec.call(t,n,...e)},h=(t,n)=>{const{params:e,sql:o}=l("sqlite",n);return c(t,o,...e)},d=t=>t??null,g=t=>{if(!(t==null||t===""))try{return JSON.parse(t)}catch{return}};export{g as decodeJsonColumn,d as orNull,h as runDrizzle,c as runSql};
@@ -1,5 +0,0 @@
1
- import{LunoraError as L}from"@lunora/errors";import{S as l,y as h,l as N}from"./ctx-db-companions-DsNfXSbb.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as R}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as O}from"./backfillAggregateIndexes-DTemznr7.mjs";import{migrateCdcLog as x,migrateCdcMeta as C}from"./CDC_LOG_TABLE-DXEAcmsr.mjs";import{migrateClientWatermark as $}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{migrateCommitSeq as b}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{migrateGlobalShapeSnapshot as U}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{migrateIdempotency as D}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{m as M}from"./ctx-db-relay-shapes-Bg5YYnmN.mjs";import{migrateScheduleOutbox as X}from"./SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs";import{m as G}from"./ctx-db-search-state-ruTuCsxa.mjs";import{migrateShapePokeCursor as y}from"./SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{runDrizzle as s}from"./runDrizzle-2ULFQR_k.mjs";import{D as F,d as E,e as u,t as B,i as v,g as P,a as Y,b as k,A as g}from"./do-sql-kpl5Kt1j.mjs";import{renderSql as w}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as j}from"./appendStreamChunk-C1Ok4b6J.mjs";import{rankTableName as H,sortColumnName as K}from"./RANK_TIEBREAK-D5xNdzB3.mjs";import{migrateReactorState as V}from"./REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{recordSchemaVersion as W}from"./SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";const S=e`_creationTime, id`,p=(r,n,i,t,o,a)=>{const c=e.join(o.map(d=>e`${d} IS NOT NULL`),e` AND `);if(s(r,e`SELECT 1 FROM ${e.identifier(i)} WHERE ${c} GROUP BY ${t} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new L("INTERNAL",`unique index "${n}" on "${i}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},z=(r,n,i,t,o,a)=>{const m=s(r,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${n} AND tbl_name = ${i}`).toArray()[0]?.sql;if(m==null)return;const d=_=>{const I=_.indexOf("(");return I===-1?void 0:_.slice(I,_.lastIndexOf(")")+1)},T=d(w("sqlite",E(n,i,t,o)).sql),f=d(m);T===void 0||f===void 0||T===f||(o&&p(r,n,i,t,a,"cannot be re-created with its new column list"),s(r,e`DROP INDEX IF EXISTS ${e.identifier(n)}`))},J=(r,n,i)=>s(r,e`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${n} AND tbl_name = ${i} LIMIT 1`).toArray().length>0,A=(r,n,i,t,o,a)=>{o&&!J(r,n,i)&&p(r,n,i,t,a,"cannot be created"),s(r,E(n,i,t,o))},Q=(r,n,i)=>{for(const t of i.indexes){const o=`${n}_${t.name}`,a=t.unique??!1,c=t.fields.map(T=>u(T)),m=e.join(c,e`, `),d=a?m:e`${m}, ${S}`;z(r,o,n,d,a,c),A(r,o,n,d,a,c)}for(const[t,o]of B(i)){if(!o.unique)continue;const a=u(t);A(r,`${n}_unique_${t}`,n,a,!0,[a])}},Z=(r,n,i)=>{if(!(!i.searchIndexes||i.searchIndexes.length===0||!v(r))){for(const t of i.searchIndexes){const o=l(n,t.name);s(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(o)} USING fts5(${e.identifier(h)}, ${e.identifier(N)} UNINDEXED)`),s(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${o}__vocab`)} USING fts5vocab(${e.identifier(o)}, ${e.raw("instance")})`)}O(r,n,i)}},q=(r,n,i)=>{if(i.geoIndexes)for(const t of i.geoIndexes){const o=P(n,t.name);s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(o)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const a=`${n}__geo_${t.name}__btree`;s(r,E(a,o,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},ee=(r,n,i)=>{if(i.aggregateIndexes)for(const t of i.aggregateIndexes){const o=R(n,t.name);s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(o)} (${Y} TEXT PRIMARY KEY, ${k} REAL, ${g} INTEGER NOT NULL DEFAULT 0)`),s(r,e`PRAGMA table_info(${e.identifier(o)})`).toArray().some(c=>c.name==="__count__")||s(r,e`ALTER TABLE ${e.identifier(o)} ADD COLUMN ${g} INTEGER NOT NULL DEFAULT 0`)}},re=(r,n,i)=>{if(i.rankIndexes)for(const t of i.rankIndexes){const o=H(n,t.name),a=t.sortBy.map((f,_)=>K(_)),c=a.map(f=>e`${e.identifier(f)} BLOB`),m=c.length>0?e`, ${e.join(c,e`, `)}`:e``;s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(o)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${m})`);const d=[e`${e.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const I=t.sortBy[f]?.direction;d.push(e`${e.identifier(_)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}d.push(e`${e.identifier("__id__")} ASC`);const T=`${n}__rank_${t.name}__btree`;s(r,E(T,o,e.join(d,e`, `),!1))}},he=(r,n,i={})=>{i.schemaSnapshot!==void 0&&W(r,i.schemaSnapshot.hash,i.schemaSnapshot.json),G(r);for(const[t,o]of Object.entries(n.tables))o.shardMode?.kind!=="global"&&(s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (
2
- id TEXT PRIMARY KEY,
3
- _creationTime REAL NOT NULL,
4
- ${e.identifier(F)} TEXT NOT NULL
5
- )`),s(r,E(`${t}__by_creation`,t,S,!1)),Q(r,t,o),Z(r,t,o),q(r,t,o),ee(r,t,o),re(r,t,o));i.cdc&&(x(r,{rowHistoryIndex:Object.values(n.tables).some(t=>t.dropStalePatchesMode===!0)}),C(r),$(r),y(r),M(r)),Object.values(n.tables).some(t=>t.commitOrderedMode===!0)&&b(r),V(r),D(r),X(r),U(r),j(r)};export{he as runShardMigrations};