@lunora/sql-store 1.0.0-alpha.123 → 1.0.0-alpha.125

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{createSqlCtxDb as a,readSqlCdcChangedTables as o,readSqlCdcChanges as t,readSqlCdcFloor as l,runSqlCdcMigration as s,sweepSqlCdcRetention as n}from"./packem_shared/createSqlCtxDb-BvYPYbKh.mjs";import{runSqlAggregateMigrations as d,runSqlGlobalTableMigrations as S,runSqlRankMigrations as c}from"./packem_shared/runSqlAggregateMigrations-FPKBRRzo.mjs";import{d as g,r as f}from"./packem_shared/ctx-db-search-C9UlHY9M.mjs";import{S as m,m as x}from"./packem_shared/ctx-db-search-state-DfmFuOtg.mjs";import{f as p,e as u,b as h,s as M,t as T}from"./packem_shared/value-codec-DC_dHxUY.mjs";import{decodeGlobalRow as E}from"./packem_shared/decodeGlobalRow-D9KXPy-S.mjs";export{m as SEARCH_STATE_TABLE,g as backfillSqlSearchIndexes,a as createSqlCtxDb,p as decodeBigint,E as decodeGlobalRow,u as effectiveColumnKind,x as migrateSearchState,o as readSqlCdcChangedTables,t as readSqlCdcChanges,l as readSqlCdcFloor,d as runSqlAggregateMigrations,s as runSqlCdcMigration,S as runSqlGlobalTableMigrations,c as runSqlRankMigrations,f as runSqlSearchMigrations,h as sqliteDecode,M as sqliteEncode,n as sweepSqlCdcRetention,T as tryJsonParse};
1
+ import{createSqlCtxDb as a,readSqlCdcChangedTables as o,readSqlCdcChanges as t,readSqlCdcFloor as l,runSqlCdcMigration as s,sweepSqlCdcRetention as n}from"./packem_shared/createSqlCtxDb-_IUy1aD6.mjs";import{runSqlAggregateMigrations as d,runSqlGlobalTableMigrations as S,runSqlRankMigrations as c}from"./packem_shared/runSqlAggregateMigrations-8GlS6aU6.mjs";import{d as g,r as f}from"./packem_shared/ctx-db-search-C9UlHY9M.mjs";import{S as m,m as x}from"./packem_shared/ctx-db-search-state-DfmFuOtg.mjs";import{f as p,e as u,b as h,s as M,t as T}from"./packem_shared/value-codec-DC_dHxUY.mjs";import{decodeGlobalRow as E}from"./packem_shared/decodeGlobalRow-D9KXPy-S.mjs";export{m as SEARCH_STATE_TABLE,g as backfillSqlSearchIndexes,a as createSqlCtxDb,p as decodeBigint,E as decodeGlobalRow,u as effectiveColumnKind,x as migrateSearchState,o as readSqlCdcChangedTables,t as readSqlCdcChanges,l as readSqlCdcFloor,d as runSqlAggregateMigrations,s as runSqlCdcMigration,S as runSqlGlobalTableMigrations,c as runSqlRankMigrations,f as runSqlSearchMigrations,h as sqliteDecode,M as sqliteEncode,n as sweepSqlCdcRetention,T as tryJsonParse};
@@ -0,0 +1,7 @@
1
+ import{LunoraError as T}from"@lunora/errors";import{m as Wt,D as Ut}from"./ctx-db-search-state-DfmFuOtg.mjs";import{c as xt,r as Pt,A as Ht,C as Kt,R as jt,a as Gt,T as Vt,x as Yt,b as Xt}from"./ctx-db-search-C9UlHY9M.mjs";import{d as Ri}from"./ctx-db-search-C9UlHY9M.mjs";import{literalInList as zt,throwingScheduler as Qt,CDC_LOG_TABLE as P,cdcForkedError as Jt,cursorBelowRetainedFloor as Zt,cdcTrimmedError as en,assertNoExplicitUndefined as et,hasTrigger as tn,runRowValidators as Ne,assertFlatPredicate as tt,mergeWhere as B,rankTableName as we,sortColumnName as Ee,resolveRankPartition as nt,encodePartitionKey as Ce,resolveRankSeekTuple as nn,RANK_TIEBREAK as ye,CountRlsUnsupportedError as it,stripReservedPatchFields as on,normalizeIdStructurally as rn,assertValidClientId as sn,aggregateSqlFunction as $e,softDeleteScope as _e,compileWhereSql as he,normalizeOrderKeys as an,uniqueIndexFields as cn,equalityPinnedFields as dn,buildSeekWhere as ln,decodeCursor as un,resolveRelationPredicates as ot,resolveWith as rt,relationHooks as st,applySelect as at,encodeCursor as fn,NotFoundError as wn,applyOnDelete as $n,ConflictError as Ae,normalizeCountArgument as _n,selectIndexForCount as hn,encodeAggregateKey as Y,aggregateTableName as Q,selectIndexForAggregate as En,readAggregateValue as qe,runTriggers as yn,matchesRankStaticWhere as ct,rankPivotConditionSql as pt,CURSOR_PREFIX as pn,selectIndexForGroupBy as Rn,tiebreakDirectionFor as Sn,fanOutScalarCounts as gn,matchesStaticWhere as De,foldAggregateTally as dt,coerceAggregateNumber as Be,CDC_LOG_TABLE_SEQ_INDEX as Tn,NotUniqueError as vn}from"@lunora/shard-engine";import{sql as e}from"drizzle-orm";import{d as Rt,b as mn,e as St,n as In,c as bn}from"./value-codec-DC_dHxUY.mjs";import{runSqlGlobalTableMigrations as Cn,runSqlAggregateMigrations as An,runSqlRankMigrations as Ln}from"./runSqlAggregateMigrations-8GlS6aU6.mjs";import{queryAll as m,queryRun as M,createIndexIfNotExists as kn,decodeRow as ee,serializeDocumentColumn as J,columnRefSql as O,decodeRows as lt,tableColumns as gt,OCC_VERSION_COLUMN as ut,serializeColumnValue as Oe,forEachRowPaged as ft,BACKFILL_BATCH_SIZE as Fe,queryBatch as wt}from"./decodeGlobalRow-D9KXPy-S.mjs";import{decodeGlobalRow as gi}from"./decodeGlobalRow-D9KXPy-S.mjs";const Mn=(a,c)=>{if(a.size<c)return;const h=a.keys().next().value;h!==void 0&&a.delete(h)},$t=50,Nn=(a,c={})=>{const h=c.maxBatch??$t,r=Number.isInteger(h)&&h>0?h:$t,p=new Map;let w=!1;const d=async(g,v)=>{const I=[...v.keys()];for(let C=0;C<I.length;C+=r){const N=I.slice(C,C+r);try{const W=await a(g,N);for(const G of N){const V=W.get(G);for(const ie of v.get(G)??[])ie.resolve(V)}}catch(W){for(const G of N)for(const V of v.get(G)??[])V.reject(W)}}},L=()=>{w=!1;const g=[...p.entries()];p.clear();for(const[v,I]of g)d(v,I).catch(()=>{})};return{async load(g,v){return new Promise((I,C)=>{let N=p.get(g);N||(N=new Map,p.set(g,N));const W=N.get(v);W?W.push({reject:C,resolve:I}):N.set(v,[{reject:C,resolve:I}]),w||(w=!0,queueMicrotask(L))})}}},qn=new Set(["_id","id"]),Pe=(a,c,h)=>a==="postgres"?e`${c} IS NOT DISTINCT FROM ${h}`:a==="mysql"?e`${c} <=> ${h}`:e`${c} IS ${h}`,Tt=(a,c)=>a.name!=="postgres"||c.nullable!==!0?"":c.direction==="desc"?" NULLS LAST":" NULLS FIRST",Dn=(a,c)=>{const h=a.map(r=>e`${O(r.field)} ${e.raw(`${r.direction==="desc"?"DESC":"ASC"}${Tt(c,r)}`)}`);if(!a.some(r=>qn.has(r.field))){const r=Sn(a);h.push(e`${O("id")} ${e.raw(r==="desc"?"DESC":"ASC")}`)}return e.join(h,e`, `)},_t=50,Bn=(a,c,h)=>{const r={...c};for(const[p,w]of gt(a)){if(w.serverDefault){r[p]=w.serverDefault({auth:h});continue}r[p]===void 0&&(w.defaultFn?r[p]=w.defaultFn():"defaultValue"in w&&(r[p]=w.defaultValue))}return r},ht=(a,c,h,r)=>{for(const[p,w]of gt(a)){if(w.serverDefault){p in c&&(h[p]=w.serverDefault({auth:r}));continue}w.onUpdateFn&&!(p in c)&&(h[p]=w.onUpdateFn())}},On=128,Fn=()=>{const a=new Map;return{delete:c=>{a.delete(c)},get:c=>{const h=a.get(c);if(h!==void 0)return a.delete(c),a.set(c,h),h},set:(c,h)=>{a.has(c)?a.delete(c):Mn(a,On),a.set(c,h)}}},Wn=async(a,c,h,r,p)=>{const w=p.get(r);if(w!==void 0)return w;const d=Object.entries(h.tables).filter(([,g])=>g.shardMode===void 0||g.shardMode.kind==="global").map(([g])=>g),L=await Promise.all(d.map(async g=>({found:(await m(a,c,e`SELECT 1 FROM ${e.identifier(g)} WHERE ${e.identifier("id")} = ${r} LIMIT 1`)).length>0,tableName:g})));for(const g of L)if(g.found)return p.set(r,g.tableName),g.tableName},te=a=>a==null?null:Number(a),Un=(a,c,h)=>h.map(r=>{const p={};for(const w of c){const d=a.shape[w];p[w]=mn(r[w]??null,d&&St(d))}return{key:p,value:te(r.value)}}),xn=(a,c,h)=>[...a.partitionBy??[],...a.sortBy.map(p=>p.field),...a.where?Object.keys(a.where):[]].every(p=>c[p]===h[p]),vt=a=>a.length===1?a[0]:e`(${e.join(a,e` AND `)})`,Z=a=>e.join(a.map(c=>e`${e.identifier(c)}`),e`, `),ne=a=>e.join(a.map(c=>e`${c}`),e`, `),Pn=(a,c,h,r,p)=>{const w=[];for(let d=0;d<h.length+1;d+=1){const L=h[d],g=c.sortBy[d],v=d<h.length&&L!==void 0&&g!==void 0,I=g?.direction==="desc"?"desc":"asc",C=v?pt(L,r[L],I,!1):e`${e.identifier(ye)} < ${p}`;if(C===void 0)continue;const N=h.slice(0,d).map(W=>Pe(a,e`${e.identifier(W)}`,r[W]));N.push(C),w.push(vt(N))}return w.length>0?e.join(w,e` OR `):e`1 = 0`},Hn=(a,c,h)=>{if(h.length!==c.length)return;const r=[];for(const[p,w]of c.entries()){const d=pt(w.column,h[p],w.direction,!0);if(d===void 0)continue;const L=[];for(let g=0;g<p;g+=1){const v=c[g];v!==void 0&&L.push(Pe(a,e`${e.identifier(v.column)}`,h[g]))}L.push(d),r.push(vt(L))}return r.length===0?e`(1 = 0)`:e`(${e.join(r,e` OR `)})`},Kn=(a,c)=>{if(a.sortBy.length===0)throw new T("INTERNAL",`rankIndex "${a.name}" requires at least one "sortBy" column for stable pagination`);const h=[{column:"__partition__",direction:"asc",nullable:!1}];for(const[r,p]of a.sortBy.entries())h.push({column:c[r]??Ee(r),direction:p.direction,nullable:!0});return h.push({column:ye,direction:"asc",nullable:!1}),h},jn=async(a,c,h,r,p)=>{const d=[];for(let I=0;I<p.length;I+=50)d.push(p.slice(I,I+50));const L=await Promise.all(d.map(async I=>m(a,c,e`SELECT * FROM ${e.identifier(r)} WHERE ${e.identifier("id")} IN (${ne(I)})`))),g=new Map;for(const I of L)for(const C of I)g.set(C.id,C);const v=[];for(const I of p){const C=ee(h,g.get(I));C&&v.push(C)}return v},Gn=a=>{const c=JSON.stringify(a),h=new TextEncoder().encode(c);let r="";for(const p of h)r+=String.fromCodePoint(p);return pn+btoa(r)},mt=a=>{if(a===void 0)return!1;const c=St(a);return c==="any"||c==="bigint"||c==="from"||c==="union"},Ue=(a,c,h)=>{if(mt(a.shape[c]))throw new T("BAD_REQUEST",`${h}: "${c}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Vn=(a,c,h,r)=>{for(const p of h)Ue(a,p,`groupBy(${c}, { by: [..."${p}"] })`);r.field!==void 0&&Ue(a,r.field,`groupBy(${c}, { agg: { op: "${r.op}", field: "${r.field}" } })`)},xe="__cdc_sweep",It="global",Yn=6e4,Xn=1e4,zn=3e4;let Et=0;const Qn=async(a,c)=>{const{autoincrementPrimaryKey:h,key:r,real:p,text:w}=c.companionTypes;await M(a,c,e`CREATE TABLE IF NOT EXISTS ${e.identifier(P)} (${e.identifier("seq")} ${e.raw(h)}, ${e.identifier("ts")} ${e.raw(p)} NOT NULL, ${e.identifier("table")} ${e.raw(r)} NOT NULL, ${e.identifier("id")} ${e.raw(r)} NOT NULL, ${e.identifier("op")} ${e.raw(r)} NOT NULL, ${e.identifier("doc")} ${e.raw(w)})`);const d=c.indexKeyPrefix?.("string");await kn(a,c,{columns:e`${d===void 0?e`${e.identifier("table")}`:e`${e.identifier("table")}(${e.raw(String(d))})`}, ${e.identifier("seq")}`,name:Tn,table:P,unique:!1}),await M(a,c,e`CREATE TABLE IF NOT EXISTS ${e.identifier(xe)} (${e.identifier("id")} ${e.raw(r)} NOT NULL PRIMARY KEY, ${e.identifier("lease_until")} ${e.raw(p)} NOT NULL)`),await M(a,c,e`INSERT INTO ${e.identifier(xe)} (${e.identifier("id")}, ${e.identifier("lease_until")}) VALUES (${It}, ${0}) ${c.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${e.identifier("id")} = ${e.identifier("id")}`:e`ON CONFLICT(${e.identifier("id")}) DO NOTHING`}`)},Jn=async(a,c,h)=>{const r=e`UPDATE ${e.identifier(xe)} SET ${e.identifier("lease_until")} = ${h+Yn} WHERE ${e.identifier("id")} = ${It} AND ${e.identifier("lease_until")} <= ${h}`;if(c.supportsReturning)return(await m(a,c,e`${r} RETURNING ${e.identifier("id")}`)).length>0;const p=await M(a,c,r);return(c.affectedRows?c.affectedRows(p??{rowsAffected:0}):0)>0},Zn=async(a,c,h,r)=>{if(!await Jn(a,c,r))return;const p=r-h;await M(a,c,e`
2
+ DELETE FROM ${e.identifier(P)} WHERE ${e.identifier("seq")} IN (
3
+ SELECT ${e.identifier("seq")} FROM (
4
+ SELECT ${e.identifier("seq")} FROM ${e.identifier(P)} WHERE ${e.identifier("ts")} <= ${p} ORDER BY ${e.identifier("seq")} ASC LIMIT ${e.raw(String(Xn))}
5
+ ) AS ${e.identifier("expired")}
6
+ )
7
+ `)},bt=async(a,c)=>{const h=await m(a,c,e`SELECT MIN(${e.identifier("seq")}) AS ${e.identifier("seq")} FROM ${e.identifier(P)}`),r=Number(h[0]?.seq??Number.NaN);return Number.isFinite(r)?r:void 0},ei=async(a,c)=>{if(c.name!=="sqlite")return;const h=await m(a,c,e`SELECT ${e.identifier("seq")} AS ${e.identifier("seq")} FROM ${e.identifier("sqlite_sequence")} WHERE ${e.identifier("name")} = ${P}`),r=Number(h[0]?.seq??Number.NaN);return Number.isFinite(r)?r:0},ti=a=>JSON.stringify(In(a)?bn(a):a),ni=async(a,c,h,r,p,w,d)=>{await M(a,d,e`INSERT INTO ${e.identifier(P)} (${e.identifier("ts")}, ${e.identifier("table")}, ${e.identifier("id")}, ${e.identifier("op")}, ${e.identifier("doc")}) VALUES (${c}, ${h}, ${r}, ${p}, ${w===void 0?null:ti(w)})`)},hi=async(a,c,h)=>{const r=c.sinceSeq??0,p=Math.max(1,Math.min(c.limit??1e3,1e4)),w=await bt(a,h),d=await ei(a,h);if(d!==void 0&&r>d)throw Jt(d,r,"global");if(w!==void 0&&Zt(w,r))throw en(w,r,"global");const g=(await m(a,h,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(P)} WHERE seq > ${r} ORDER BY seq ASC LIMIT ${e.raw(String(p))}`)).map(v=>{const{doc:I}=v,C={id:String(v.id),op:String(v.op),seq:Number(v.seq),table:String(v.table),ts:Number(v.ts)};return typeof I=="string"?{...C,doc:Rt(JSON.parse(I))}:C});return{changes:g,cursor:g.at(-1)?.seq??r}},ii=async(a,c,h,r={})=>{if(r.cursorOnly){const g=await m(a,h,e`SELECT MAX(seq) AS seq FROM ${e.identifier(P)}`),v=Number(g[0]?.seq??c);return{cursor:Number.isFinite(v)?v:c,tables:[]}}const p=await m(a,h,e`SELECT ${e.identifier("table")} AS ${e.identifier("table")}, MAX(seq) AS seq FROM ${e.identifier(P)} WHERE seq > ${c} GROUP BY ${e.identifier("table")}`);let w=c;const d=[];for(const g of p){const v=Number(g.seq);Number.isFinite(v)&&v>w&&(w=v),d.push(String(g.table))}const L=r.retained===!0?await bt(a,h):void 0;return{cursor:w,tables:d,...L===void 0?{}:{floor:L}}},oi=/string or blob too big/iu,ri=/row is too big/iu,si=(a,c)=>{const{code:h,errno:r}=c,p=c instanceof Error?c.message:"";switch(a.name){case"mysql":return r===1118||h==="ER_TOO_BIG_ROWSIZE"?"InnoDB's per-row ceiling — roughly 8 KB, half a 16 KB page, for the part of the row stored inline":void 0;case"postgres":return ri.test(p)?"the 8 KB heap page a tuple must fit once its wide columns have been TOASTed out":void 0;default:return oi.test(p)?"the storage engine's per-row ceiling (2 MB on D1)":void 0}},ai=(a,c,h)=>{const r=si(a,c);if(r!==void 0)throw new T("PAYLOAD_TOO_LARGE",`document is too large to store in "${h}": a single row cannot exceed ${r}. The limit is on the STORED bytes, which are UTF-8. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},yt=(a,c,h)=>{throw a.isUniqueViolation(c)?new Ae(`unique constraint violation on "${h}"`,"unique"):(ai(a,c,h),c)},We=new WeakMap,Ei=a=>{const{crossShardCounter:c,crossShardReader:h,exec:r,maxRelationKeys:p,schema:w}=a,{dialect:d}=a,L={fieldRef:O,...d.name==="mysql"?{containsExpr:(t,n)=>e`LOCATE(${n}, ${t}) > 0`}:{},...d.name==="postgres"?{containsExpr:(t,n)=>e`strpos(${t}, ${n}) > 0`}:{},...d.name==="sqlite"?{}:{inList:zt}},g=new WeakMap,v=t=>{const n=g.get(t);if(n!==void 0)return n;const i={...L,serialize:(o,s)=>J(t,s,o)};return g.set(t,i),i},I=(t,n)=>Pe(d.name,t,n),C=t=>{const n=Z(t.columns),i=ne(t.values),o=u=>d.name==="mysql"?e`VALUES(${e.identifier(u)})`:e`excluded.${e.identifier(u)}`,s=u=>d.name==="postgres"?e`${e.identifier(t.table)}.${e.identifier(u)}`:e`${e.identifier(u)}`,l=e.join(Object.entries(t.set(o,s)).map(([u,y])=>e`${e.identifier(u)} = ${y}`),e`, `),E=d.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${l}`:e`ON CONFLICT(${e.identifier(t.conflictKey)}) DO UPDATE SET ${l}`;return e`INSERT INTO ${e.identifier(t.table)} (${n}) VALUES (${i}) ${E}`},N=a.clock??(()=>Date.now()),W=a.idGenerator??(()=>crypto.randomUUID()),G=a.cdc??!1,V=typeof a.cdcRetentionMs=="number"&&Number.isFinite(a.cdcRetentionMs)&&a.cdcRetentionMs>0?a.cdcRetentionMs:void 0,ie=a.auth??{identity:null,userId:null},oe=async(t,n,i,o)=>{if(!G||(await ni(r,N(),t,n,i,o,d),V===void 0))return;const s=N();if(!(s-Et<zn)){Et=s;try{await Zn(r,d,V,s)}catch{}}},Ct=a.scheduler??Qt,Le=Fn();let pe=0;const ke=a.provisionScope??{},U=async()=>{const t=We.get(ke);if(t)return t;const n=(async()=>{await Cn(r,w,d),await An(r,w,d),await Ln(r,w,d),await Wt(r,d),await Pt(r,w,d),G&&await Qn(r,d)})().catch(i=>{throw We.delete(ke),i});return We.set(ke,n),n},re=async(t,n)=>{await U();const i=await Wn(r,d,w,t,Le);if(!(n!==void 0&&i!==n))return i},se=new Map,He=async(t,n)=>{const i=Q(t,n);return(await m(r,d,d.tableExists(i))).length>0},Re=async(t,n)=>{const i=`${t}::${n.name}`,o=se.get(i);if(o!==void 0)return o;if(!await He(t,n.name))return se.set(i,!1),!1;const l=w.tables[t];if(!l)return se.set(i,!1),!1;const E=n.by??[],u=new Map;await ft(r,d,l,t,$=>{if(n.where&&!De($,n.where))return;const _=Y(E,$);dt(u,_,n,$)});const y=Q(t,n.name);await M(r,d,e`DELETE FROM ${e.identifier(y)}`);const f=[];for(const[$,_]of u)f.push(e`INSERT INTO ${e.identifier(y)} (${e.identifier("__key__")}, ${e.identifier("__value__")}, ${e.identifier("__count__")}) VALUES (${$}, ${_.value}, ${_.count})`);return await wt(r,d,f),se.set(i,!0),!0},At=async(t,n,i,o)=>{const s=new Map;let l,E=!0;for(;E;){const u=l===void 0?o:[...o,e`${e.identifier("id")} > ${l}`],y=u.length>0?e` WHERE ${e.join(u,e` AND `)}`:e``,f=await m(r,d,e`SELECT ${e.identifier("id")}, ${O(i.field??"")} FROM ${e.identifier(n)}${y} ORDER BY ${e.identifier("id")} ASC LIMIT ${e.raw(String(Fe))}`);for(const $ of lt(t,f))dt(s,"",i,$);l=f.at(-1)?.id,E=f.length===Fe}return s.get("")?.value??null},Lt=async(t,n,i)=>{const o=n.field??"",s=[],l=w.tables[t],E=($,_)=>l?J(l,$,_):Oe(_);for(const $ of n.by??[]){const _=E($,i[$]??null);s.push(_===null?e`${O($)} IS NULL`:e`${O($)} = ${_}`)}for(const[$,_]of Object.entries(n.where??{})){const R=_!==null&&typeof _=="object"&&!Array.isArray(_)?_.eq:_,S=E($,R);s.push(S===null?e`${O($)} IS NULL`:e`${O($)} = ${S}`)}const u=s.length>0?e` WHERE ${e.join(s,e` AND `)}`:e``;if(l&&mt(l.shape[o]))return At(l,t,n,s);const y=$e(n.op),f=await m(r,d,e`SELECT ${e.raw(y)}(${O(o)}) AS ${e.identifier("value")} FROM ${e.identifier(t)}${u}`);return te(f[0]?.value)},kt=async(t,n)=>{await M(r,d,e`DELETE FROM ${e.identifier(t)} WHERE ${e.identifier("__key__")} = ${n} AND ${e.identifier("__count__")} <= 0`)},Mt=async(t,n,i,o)=>{const s=Q(t,n.name),{op:l}=n,E=n.field??"",u=i&&(!n.where||De(i,n.where))?i:void 0,y=o&&(!n.where||De(o,n.where))?o:void 0;if(!(!u&&!y)){if(l==="count"||l==="sum"||l==="avg"){const f=new Set;for(const[$,_]of[[u,-1],[y,1]]){if(!$)continue;const R=l==="count"?1:Be($[E]);if(R===void 0)continue;const S=Y(n.by??[],$);f.add(S),await M(r,d,C({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(b,A)=>({__count__:e`${A("__count__")} + ${b("__count__")}`,__value__:l==="count"?e`${A("__value__")} + ${b("__value__")}`:e`COALESCE(${A("__value__")}, 0) + ${b("__value__")}`}),table:s,values:[S,_*R,_]}))}for(const $ of f)await kt(s,$);return}if(u){const f=Y(n.by??[],u),$=Be(u[E]),R=(await m(r,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(s)} WHERE ${e.identifier("__key__")} = ${f}`))[0],S=te(R?.value),b=(R?.count??0)-1;if(b<=0)await M(r,d,e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__key__")} = ${f}`);else if(R&&$!==void 0&&S!==null&&$===S){const A=await Lt(t,n,u);await M(r,d,e`UPDATE ${e.identifier(s)} SET ${e.identifier("__value__")} = ${A}, ${e.identifier("__count__")} = ${b} WHERE ${e.identifier("__key__")} = ${f}`)}else await M(r,d,e`UPDATE ${e.identifier(s)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${f}`)}if(y){const f=Y(n.by??[],y),$=Be(y[E]);if($===void 0)await M(r,d,C({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(_,R)=>({__count__:e`${R("__count__")} + 1`}),table:s,values:[f,null,1]}));else{const _=l==="min"?"MIN":"MAX";await M(r,d,C({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(R,S)=>({__count__:e`${S("__count__")} + 1`,__value__:e`${e.raw(_)}(COALESCE(${S("__value__")}, ${R("__value__")}), ${R("__value__")})`}),table:s,values:[f,$,1]}))}}}},Se=async t=>{const n=w.tables[t]?.aggregateIndexes;if(!(!n||n.length===0))for(const i of n)await Re(t,i)},ae=async(t,n,i)=>{const o=w.tables[t]?.aggregateIndexes;if(!(!o||o.length===0))for(const s of o){const l=`${t}::${s.name}`;(se.get(l)??await He(t,s.name))&&await Mt(t,s,n,i)}},ce=new Map,Ke=async(t,n)=>{const i=we(t,n);return(await m(r,d,d.tableExists(i))).length>0},Me=async(t,n)=>{const i=`${t}::rank::${n.name}`,o=ce.get(i);if(o!==void 0)return o;if(!await Ke(t,n.name))return ce.set(i,!1),!1;const l=w.tables[t];if(!l)return ce.set(i,!1),!1;const E=we(t,n.name);await M(r,d,e`DELETE FROM ${e.identifier(E)}`);const u=n.sortBy.map((_,R)=>Ee(R)),y=Z(["__id__","__partition__",...u]);let f=[];const $=async()=>{if(f.length===0)return;const _=f;f=[],await wt(r,d,_)};return await ft(r,d,l,t,async _=>{if(n.where&&!ct(_,n.where))return;const R=Ce(n.partitionBy??[],_),S=n.sortBy.map(b=>Oe(_[b.field]??null));f.push(e`INSERT INTO ${e.identifier(E)} (${y}) VALUES (${ne([_._id,R,...S])})`),f.length>=Fe&&await $()}),await $(),ce.set(i,!0),!0},ge=async t=>{const n=w.tables[t]?.rankIndexes;if(!(!n||n.length===0))for(const i of n)await Me(t,i)},X=async(t,n,i,o)=>{const s=w.tables[t],l=s?.rankIndexes;if(!l||l.length===0)return;const E=s?.softDeleteMode?.field,u=E===void 0||o===void 0?void 0:o[E],y=u!=null;for(const f of l){if(i!==void 0&&o!==void 0&&xn(f,i,o))continue;const $=`${t}::rank::${f.name}`;if(!(ce.get($)??await Ke(t,f.name)))continue;const S=we(t,f.name);if(i&&await M(r,d,e`DELETE FROM ${e.identifier(S)} WHERE ${e.identifier("__id__")} = ${n}`),o&&!y){if(f.where&&!ct(o,f.where))continue;const b=f.sortBy.map((D,j)=>Ee(j)),A=Z(["__id__","__partition__",...b]),F=Ce(f.partitionBy??[],o),k=f.sortBy.map(D=>Oe(o[D.field]??null));await M(r,d,e`INSERT INTO ${e.identifier(S)} (${A}) VALUES (${ne([n,F,...k])})`)}}},de=xt({dialect:d,exec:r,schema:w}),je=new Set;for(const[t,n]of Object.entries(w.tables))for(const i of Object.values(n.triggerMap??{}))je.add(`${t} ${i.timing} ${i.op}`);const H=(t,n,i)=>je.has(`${t} ${n} ${i}`);let Ge;const K=async(t,n,i)=>{if(pe+=1,pe>_t)throw pe-=1,new Ae(`trigger recursion exceeded ${String(_t)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await yn({ctx:Ge,event:i,op:n,schema:w,tableName:i.table,timing:t})}finally{pe-=1}},Nt=async(t,n)=>{try{await M(r,d,n)}catch(i){yt(d,i,t)}},Te=async(t,n)=>(await m(r,d,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} = ${n}`))[0],ve=async(t,n,i,o)=>{if(o===void 0)return;const s=e`${e.identifier(ut)}`,l=e.join([I(e`${e.identifier("id")}`,o.id),I(s,o[ut]??null)],e` AND `),E=n==="UPDATE"?e`UPDATE ${e.identifier(t)} SET ${i}, ${s} = COALESCE(${s}, 0) + 1 WHERE ${l}`:e`DELETE FROM ${e.identifier(t)} WHERE ${l}`,u=()=>{throw new Ae(`optimistic concurrency conflict on "${t}" — the row changed during this mutation; refetch and retry`,"occ")};try{if(d.supportsReturning)(await m(r,d,e`${E} RETURNING ${e.identifier("id")}`)).length===0&&u();else{const y=await M(r,d,E);(d.affectedRows?d.affectedRows(y??{rowsAffected:0}):0)===0&&u()}}catch(y){yt(d,y,t)}},qt=(t,n,i,o)=>{const s=Object.keys(t.shape);return{columns:["id","_creationTime",...s],values:[n,i,...s.map(l=>J(t,l,o[l]??null))]}},Dt=async(t,n,i,o)=>{const s=Rn(n,i.op,i.field,o.by,o.where);if(!s||!await Re(t,s.index))return;const E=Q(t,s.index.name),u=Object.keys(s.partial);if(u.length===(s.index.by??[]).length&&u.length>0){const f=Y(s.index.by??[],s.partial),$=await m(r,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(E)} WHERE ${e.identifier("__key__")} = ${f}`);if($.length===0)return[];const _=$[0];return[{key:{...s.partial},value:qe(i.op,{count:_.count,value:te(_.value)})}]}return u.length>0?void 0:(await m(r,d,e`SELECT ${e.identifier("__key__")} AS ${e.identifier("key")}, ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(E)}`)).map(f=>{const $=f;return{key:Rt(JSON.parse($.key)),value:qe(i.op,{count:$.count,value:te($.value)})}})},Ve=t=>{const n=w.tables[t]?.shardMode?.kind;return n==="shardBy"||n==="root"},Ye=t=>{throw new T("INTERNAL",`cross-backend relation: a global table cannot load the shard-local relation '${t}' (it spans every shard) — wire a cross-shard reader to support it`)},Bt=(t,n)=>{if(n?.relationMask!==void 0&&n.with!==void 0&&Object.keys(n.with).length>0)throw new T("MASK_UNSUPPORTED",`masking cannot follow a nested \`with\` across the cross-shard relation hop to "${t}" — the nested rows are hydrated on the serving shard, where the mask policy does not exist. Read the nested relation at its own (masked) call site instead.`);const i={};if(n?.relationBaseWhere)for(const o of Object.keys(w.tables)){const s=n.relationBaseWhere(o);s!==void 0&&(i[o]=s)}return{orderBy:n?.orderBy,relationPolicies:i,where:B(n?.baseWhere,n?.where),with:n?.with}},Xe=(t,n)=>Ve(t)?h?h(t,Bt(t,n)):Ye(t):x.findMany(t,n),me=(t,n,i)=>ot(t,{fetcher:Xe,maxRelationKeys:p,relationBaseWhere:i,schema:w,tableName:n}),Ot=Nn(async(t,n)=>{const i=await m(r,d,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} IN (${ne(n)})`),o=new Map;for(const s of i){const{id:l}=s;typeof l=="string"&&o.set(l,s)}return o}),x={async cdcChangedTables(t,n){if(G)try{return await U(),await ii(r,t,d,{...n,retained:V!==void 0})}catch{return}},async aggregate(t,n){const i=w.tables[t];if(!i)throw new T("INTERNAL",`unknown table: ${t}`);if(await U(),$e(n.op),n.op==="count")return x.count(t,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new T("INTERNAL",`aggregate(${t}, { op: "${n.op}" }): "field" is required for non-count reducers`);const o=_e(i.softDeleteMode,void 0),s=B(B(n.baseWhere,n.where),o),l=await me(s,t,n.relationBaseWhere),E=l!==s;if(i.aggregateIndexes&&!n.baseWhere&&!E&&!o){const R=En(i.aggregateIndexes,n.op,n.field,n.where);if(R&&await Re(t,R.index)){const b=Y(R.index.by??[],R.key),A=Q(t,R.index.name),k=(await m(r,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(A)} WHERE ${e.identifier("__key__")} = ${b}`))[0];return qe(n.op,k===void 0?void 0:{count:k.count,value:te(k.value)})}}Ue(i,n.field,`aggregate(${t}, { op: "${n.op}", field: "${n.field}" })`);const u=he(l,v(i)),y=e.raw($e(n.op)),f=e`SELECT ${y}(${O(n.field)}) AS ${e.identifier("value")} FROM ${e.identifier(t)}`,_=(await m(r,d,u?e`${f} WHERE ${u}`:f))[0]?.value;return _==null?null:Number(_)},async count(t,n){const i=w.tables[t];if(!i)throw new T("INTERNAL",`unknown table: ${t}`);await U();const o=_n(n);if(o.restrictsCounts)throw new it(t);const s=_e(i.softDeleteMode,void 0),l=B(B(o.baseWhere,o.where),s),E=await me(l,t,o.relationBaseWhere),u=E!==l;if(i.aggregateIndexes&&!o.baseWhere&&!u&&!s){const _=hn(i.aggregateIndexes,o.where);if(_&&await Re(t,_.index)){const S=Y(_.index.by??[],_.key),b=Q(t,_.index.name),A=await m(r,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")} FROM ${e.identifier(b)} WHERE ${e.identifier("__key__")} = ${S}`);return Number(A[0]?.value??0)}}const y=he(E,v(i)),f=e`SELECT COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(t)}`,$=await m(r,d,y?e`${f} WHERE ${y}`:f);return Number($[0]?.count??0)},async delete(t,n,i){const o=await re(t,n);if(!o)return;const s=w.tables[o];if(!s)return;const l=await Te(o,t),E=ee(s,l),u=i?.hard===!0,y=!u&&s.softDeleteMode?s.softDeleteMode.field:void 0;if(!(y&&(!E||E[y]!==null&&E[y]!==void 0))){if(H(o,"before","delete")&&await K("before","delete",{id:t,op:"delete",previous:E??void 0,table:o}),await $n({deletedId:t,deletedReference:f=>E?.[f],findHolders:async(f,$,_)=>{if(w.tables[f]?.shardMode?.kind==="shardBy")throw new T("INTERNAL",`cross-backend cascade from global '${o}' into shardBy '${f}' is not supported — would require Query Coordinator fan-out across shards`);return(await x.findMany(f,{includeDeleted:u,where:{[$]:_}})).page},onCascade:(f,$)=>x.delete($,void 0,i),onRestrict:f=>{throw new Ae(f,"restrict")},onSetNull:(f,$,_)=>x.patch($,{[_]:null}),schema:w,tableName:o}),await Se(o),await ge(o),y&&E){const f={...E,[y]:N()},$=e.join(Object.keys(s.shape).map(_=>e`${e.identifier(_)} = ${J(s,_,f[_]??null)}`),e`, `);await ve(o,"UPDATE",$,l),await ae(o,E,f),await X(o,t,E,void 0),await de(o,t,f,E),await oe(o,t,"update",f),H(o,"after","delete")&&await K("after","delete",{id:t,op:"delete",previous:E,table:o});return}await ve(o,"DELETE",void 0,l),Le.delete(t),await ae(o,E??void 0,void 0),await X(o,t,E??void 0,void 0),await de(o,t,void 0),await oe(o,t,"delete"),H(o,"after","delete")&&await K("after","delete",{id:t,op:"delete",previous:E??void 0,table:o})}},async findFirst(t,n={}){return(await x.findMany(t,{...n,limit:1})).page[0]??null},async findFirstOrThrow(t,n={}){const i=await x.findFirst(t,n);if(i===null)throw new wn(`findFirstOrThrow: no "${t}" document matched`);return i},async findMany(t,n={}){const i=w.tables[t];if(!i)throw new T("INTERNAL",`unknown table: ${t}`);await U();const o=an(n.orderBy,i.shape,{pinned:dn(n.where),uniqueBy:cn(i.indexes,i.shape)}),s=n.cursor?ln(o,un(n.cursor)):void 0,l=Xe,E=async(k,D,j,Ie)=>{if(Ve(k))return c?gn(c,k,D,j,Ie):Ye(k);const le=w.tables[k];if(!le)throw new T("INTERNAL",`unknown table: ${k}`);const be=_e(le.softDeleteMode,void 0),z={[D]:{in:j}},q=B(B(z,Ie),be),ue=await me(q,k,void 0),ze=he(ue,v(le)),Qe=O(D);let fe=e`SELECT ${Qe} AS __fk__, COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(k)}`;ze&&(fe=e`${fe} WHERE ${ze}`),fe=e`${fe} GROUP BY ${Qe}`;const Ft=await m(r,d,fe),Je=new Map;for(const Ze of Ft)Je.set(Ze.__fk__,Number(Ze.count??0));return Je};let u=B(n.baseWhere,n.where);u=B(u,_e(i.softDeleteMode,n.includeDeleted)),u=await ot(u,{fetcher:l,maxRelationKeys:p,relationBaseWhere:n.relationBaseWhere,schema:w,tableName:t}),s&&(u=u?{AND:[u,s]}:s);const y=he(u,v(i)),f=Dn(o,d);let $=e`SELECT * FROM ${e.identifier(t)}`;y&&($=e`${$} WHERE ${y}`),$=e`${$} ORDER BY ${f}`;const _=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;_!==void 0&&($=e`${$} LIMIT ${e.raw(String(_+1))}`);const R=await m(r,d,$),S=lt(i,R);if(_===void 0)return n.with&&await rt({fetcher:l,groupedCounter:E,parents:S,...st(n),schema:w,tableName:t,with:n.with}),{continueCursor:null,isDone:!0,page:at(S,n.select,n.with)};const b=S.length>_,A=b?S.slice(0,_):S,F=A.at(-1);return n.with&&await rt({fetcher:l,groupedCounter:E,parents:A,...st(n),schema:w,tableName:t,with:n.with}),{continueCursor:b&&F?fn(F,o):null,isDone:!b,page:at(A,n.select,n.with)}},async get(t,n){const i=await re(t,n);if(!i)return null;const o=w.tables[i];return o?ee(o,await Ot.load(i,t)):null},async groupBy(t,n){const i=w.tables[t];if(!i)throw new T("INTERNAL",`unknown table: ${t}`);await U();const o=n.agg??{op:"count"};if($e(o.op),o.op!=="count"&&!o.field)throw new T("INTERNAL",`groupBy(${t}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);const s=_e(i.softDeleteMode,void 0),l=B(B(n.baseWhere,n.where),s),E=await me(l,t,n.relationBaseWhere),u=E!==l;if(i.aggregateIndexes&&!n.baseWhere&&!u&&!s){const S=await Dt(t,i.aggregateIndexes,o,n);if(S!==void 0)return S}Vn(i,t,n.by,o);const y=he(E,v(i)),f=n.by.map(S=>e`${O(S)} AS ${e.identifier(S)}`);if(o.op==="count")f.push(e`COUNT(*) AS ${e.identifier("value")}`);else{if(!o.field)throw new T("INTERNAL",`groupBy(${t}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);f.push(e`${e.raw($e(o.op))}(${O(o.field)}) AS ${e.identifier("value")}`)}const $=e.join(n.by.map(S=>O(S)),e`, `);let _=e`SELECT ${e.join(f,e`, `)} FROM ${e.identifier(t)}`;y&&(_=e`${_} WHERE ${y}`),_=e`${_} GROUP BY ${$}`;const R=await m(r,d,_);return Un(i,n.by,R)},async insert(t,n,i){const o=w.tables[t];if(!o)throw new T("INTERNAL",`unknown table: ${t}`);await U();const s=Bn(o,n,ie);Ne(o,s);let l,E=!0;i?.clientId!==void 0?(sn(i.clientId),l=i.clientId):i?.allowExplicitId&&typeof s._id=="string"?l=s._id:(l=W(),E=!1);const u=i?.allowExplicitId&&typeof s._creationTime=="number"?s._creationTime:N(),y={...s,_creationTime:u,_id:l};H(t,"before","insert")&&await K("before","insert",{doc:{...y},id:l,op:"insert",table:t}),await Se(t),await ge(t);const{columns:f,values:$}=qt(o,l,u,s);return await Nt(t,e`INSERT INTO ${e.identifier(t)} (${Z(f)}) VALUES (${ne($)})`),E&&Le.set(l,t),await ae(t,void 0,y),await X(t,l,void 0,y),await de(t,l,y),await oe(t,l,"insert",y),H(t,"after","insert")&&await K("after","insert",{doc:y,id:l,op:"insert",table:t}),l},normalizeId(t,n){return rn(w,t,n)},async patch(t,n,i){et("patch",n);const o=await re(t,i);if(!o)throw new T("INTERNAL",`document not found: ${t}`);const s=w.tables[o];if(!s)throw new T("INTERNAL",`document not found: ${t}`);const l=await Te(o,t),E=ee(s,l);if(!E)throw new T("INTERNAL",`document not found: ${t}`);const u={...E,...on(n),_id:t};ht(s,n,u,ie),Ne(s,u,!0),H(o,"before","update")&&await K("before","update",{doc:{...u},id:t,op:"update",previous:E,table:o}),await Se(o),await ge(o);const y=Object.keys(s.shape),f=e.join(y.map($=>e`${e.identifier($)} = ${J(s,$,u[$]??null)}`),e`, `);await ve(o,"UPDATE",f,l),await ae(o,E,u),await X(o,t,E,u),await de(o,t,u,E),await oe(o,t,"update",u),H(o,"after","update")&&await K("after","update",{doc:u,id:t,op:"update",previous:E,table:o})},async restore(t,n){const i=await re(t,n);if(!i)throw new T("INTERNAL",`document not found: ${t}`);const o=w.tables[i],s=o?.softDeleteMode?.field;if(!o||!s)throw new T("INTERNAL",`ctx.db.restore: table "${i}" is not a .softDelete() table`);const l=await Te(i,t),E=l?.[s]!==null&&l?.[s]!==void 0;if(await x.patch(t,{[s]:null},n),E){const u=ee(o,l);u!==null&&await X(i,t,void 0,{...u,[s]:null})}},query(t){const n=w.tables[t];if(!n)throw new T("INTERNAL",`unknown table: ${t}`);const i="the legacy query()/withIndex() reader is not available on the D1 (global) backend; use findMany",o=[],s=u=>o.every(y=>y(u)),l=async(u,y)=>{await U();const f=o.length>0,$=await Gt(r,d,n,t,u,Vt(f?void 0:y));if(!f)return y===void 0&&Yt($),$;const _=$.filter(R=>s(R));return y===void 0?_:_.slice(0,y)},E=u=>{const y={async*[Symbol.asyncIterator](){if(!u)throw new T("INTERNAL",i);yield*await l(u,void 0)},async collect(){if(!u)throw new T("INTERNAL",i);return l(u,void 0)},async collectWithScores(){throw new T("GLOBAL_SEARCH_SCORES_UNSUPPORTED",`collectWithScores() is not supported on \`.global()\` tables (table "${t}") — relevance scores are not yet surfaced on this backend; use .collect() instead`)},filter(f){return o.push(f),y},async first(){if(!u)throw new T("INTERNAL",i);return(await l(u,1))[0]??null},order(){return y},async paginate(f){if(!u)throw new T("INTERNAL",i);const $=Kt(f);return jt(await l(u,Xt($)),$)},async take(f){if(!u)throw new T("INTERNAL",i);return l(u,f)},async unique(){if(!u)throw new T("INTERNAL",i);const f=await l(u,2);if(f.length>1)throw new vn(`unique() on table "${t}" matched ${String(f.length)} documents; expected at most one`);return f[0]??null},withGeoIndex(){throw new T("INTERNAL",`geo indexes are not supported on \`.global()\` tables (table "${t}") — geospatial queries run only on sharded tables`)},withIndex(){throw new T("INTERNAL",i)},withSearchIndex(f,$){const _=(n.searchIndexes??[]).find(S=>S.name===f);if(!_)throw new T("INTERNAL",`unknown search index "${f}" on table "${t}"`);const R={definition:_,field:_.field,filters:[],hasQuery:!1,indexName:f,query:""};if($(Ht(R,t,Ut(_.language))),!R.hasQuery)throw new T("INTERNAL",`search index "${f}" on table "${t}" requires a .search(field, query) call`);return E(R)}};return y};return E(void 0)},async rank(t,n,i){const o=w.tables[t];if(!o)throw new T("INTERNAL",`unknown table: ${t}`);const s=o.rankIndexes?.find(D=>D.name===n);if(!s)throw new T("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(i.restrictsCounts)throw new it(t);if(await U(),!await Me(t,s))return null;const E=typeof i.row=="string"?i.row:i.row._id;if(!E)return null;const u=we(t,s.name),y=s.sortBy.map((D,j)=>Ee(j)),f=Z(["__partition__",...y]),_=(await m(r,d,e`SELECT ${f} FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${E}`))[0];if(!_)return null;const R=_.__partition__,S=B(i.baseWhere,i.where);tt(S,w,t,"rank");const b=nt(s,S);if(b&&Ce(s.partitionBy??[],b)!==R)return null;const A=Pn(d.name,s,y,_,E),F=await m(r,d,e`SELECT COUNT(*) AS c FROM ${e.identifier(u)} WHERE ${e.identifier("__partition__")} = ${R} AND (${A})`),k=await m(r,d,e`SELECT COUNT(*) AS c FROM ${e.identifier(u)} WHERE ${e.identifier("__partition__")} = ${R}`);return{position:Number(F[0]?.c??0)+1,total:Number(k[0]?.c??0)}},async rankPage(t,n,i={}){tt(B(i.baseWhere,i.where),w,t,"rankPage");const o=w.tables[t];if(!o)throw new T("INTERNAL",`unknown table: ${t}`);const s=o.rankIndexes?.find(q=>q.name===n);if(!s)throw new T("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(await U(),!await Me(t,s))return{continueCursor:null,isDone:!0,page:[]};const E=we(t,s.name),u=s.sortBy.map((q,ue)=>Ee(ue)),y=Math.max(1,Math.min(1e3,Math.floor(i.take??100))),f=B(i.baseWhere,i.where),$=nt(s,f),_=Kn(s,u),R=e.join(_.map(q=>e`${e.identifier(q.column)} ${e.raw(`${q.direction==="desc"?"DESC":"ASC"}${Tt(d,{direction:q.direction,nullable:q.nullable})}`)}`),e`, `),S=[];typeof i.partitionKey=="string"?S.push(e`${e.identifier("__partition__")} = ${i.partitionKey}`):$&&S.push(e`${e.identifier("__partition__")} = ${Ce(s.partitionBy??[],$)}`);const b=nn(i);if(b!==void 0){const q=Hn(d.name,_,b);q!==void 0&&S.push(q)}const A=Z([ye,"__partition__",...u]);let F=e`SELECT ${A} FROM ${e.identifier(E)}`;S.length>0&&(F=e`${F} WHERE ${e.join(S,e` AND `)}`),F=e`${F} ORDER BY ${R} LIMIT ${e.raw(String(y+1))}`;const k=await m(r,d,F),D=k.length>y,j=D?k.slice(0,y):k,Ie=j.map(q=>q[ye]),le=await jn(r,d,o,t,Ie);let be=null;const z=j.at(-1);if(D&&z!==void 0){const q=[z.__partition__,...u.map(ue=>z[ue]),z[ye]];be=Gn(q)}return{continueCursor:be,isDone:!D,page:le}},async replace(t,n,i,o){et("replace",n);const s=await re(t,i);if(!s)throw new T("INTERNAL",`document not found: ${t}`);const l=w.tables[s];if(!l)throw new T("INTERNAL",`document not found: ${t}`);const E=await Te(s,t);if(E===void 0)throw new T("INTERNAL",`document not found: ${t}`);const y=tn(w,s,"update")||(l.aggregateIndexes??[]).length>0||(l.rankIndexes??[]).length>0?ee(l,E)??void 0:void 0,f=o?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:void 0,$=typeof E._creationTime=="number"?E._creationTime:void 0,_=f??$??N(),R={...n,_creationTime:_,_id:t};ht(l,n,R,ie),Ne(l,R),H(s,"before","update")&&await K("before","update",{doc:{...R},id:t,op:"update",previous:y,table:s}),await Se(s),await ge(s);const S=Object.keys(l.shape),b=e.join([e`${e.identifier("_creationTime")} = ${_}`,...S.map(A=>e`${e.identifier(A)} = ${J(l,A,R[A]??null)}`)],e`, `);await ve(s,"UPDATE",b,E),await ae(s,y,R),await X(s,t,y,R),await de(s,t,R,y),await oe(s,t,"update",R),H(s,"after","update")&&await K("after","update",{doc:R,id:t,op:"update",previous:y,table:s})}};return Ge={db:x,scheduler:Ct},x};export{Ri as backfillSqlSearchIndexes,Ei as createSqlCtxDb,gi as decodeGlobalRow,ii as readSqlCdcChangedTables,hi as readSqlCdcChanges,bt as readSqlCdcFloor,Qn as runSqlCdcMigration,Pt as runSqlSearchMigrations,Zn as sweepSqlCdcRetention};
@@ -0,0 +1 @@
1
+ import{LunoraError as N}from"@lunora/errors";import{aggregateTableName as x,rankTableName as D,sortColumnName as L,renderSql as U,bigintSqlKey as M}from"@lunora/shard-engine";import{sql as n}from"drizzle-orm";import{queryRun as g,queryAll as E,createIndexIfNotExists as p,OCC_VERSION_COLUMN as h,tableColumns as k,columnRefSql as d,queryBatch as B}from"./decodeGlobalRow-D9KXPy-S.mjs";import{e as w,i as P,B as b,r as j,U as F,a as K}from"./value-codec-DC_dHxUY.mjs";const A=(i,t,e=!1)=>t.columnType(w(i),{unique:e||i._meta?.column?.unique===!0}),S=i=>{const t=new Set;for(const e of i.indexes)e.unique===!0&&e.fields.length===1&&t.add(e.fields[0]);return t},G=(i,t,e)=>{if(e.indexKeyPrefix!==void 0)for(const o of t.indexes){if(o.unique!==!0||o.fields.length<=1)continue;const r=o.fields.filter(u=>{const s=t.shape[u];return s!==void 0&&e.indexKeyPrefix?.(w(s))!==void 0});if(r.length>0)throw new Error(`${i}.${o.name}: a composite unique index cannot cover ${r.join(", ")} in full on this engine (its key limit forces a prefix, which would constrain the prefix rather than the value). Split it into single-column unique indexes, or store those fields as a bounded type.`)}},Y=(i,t,e)=>{const o=[],r=S(t);for(const[l,f]of Object.entries(t.shape)){if(!f._meta?.column)continue;const c=f._meta.column.notNull&&f.kind!=="optional"?" NOT NULL":"";o.push(n`${n.identifier(l)} ${n.raw(`${A(f,e,r.has(l))}${c}`)}`)}const u=[...e.frameworkColumns().map(l=>n`${n.identifier(l.name)} ${n.raw(l.type)}`),n`${n.identifier(h)} ${n.raw(e.companionTypes.integer)}`],s=u.length+o.length,a=e.maxTableColumns;if(a!==void 0&&s>a){const l=s-1===a,f="Move one or more fields into a single object field, or split the table — either way the existing rows need a data migration (`defineMigration` + `lunora migrate up`); there is no in-place path.";throw new N("VALIDATION_ERROR",`@lunora/sql-store: global table "${i}" needs ${String(s)} columns, over this engine's ${String(a)}-column limit. ${l?`One of them is "${h}", the row version every guarded write reads, which caps declared fields at ${String(a-u.length)}. A table provisioned at ${String(a)} columns before that column existed cannot be widened to hold it. `:""}${f}`)}return n.join([...u,...o],n`, `)},V=i=>{if(i.indexKeyPrefix?.("string")===void 0)return n`${d("_creationTime")}, ${d("id")}`},O=async(i,t,e,o)=>{const r=n.join(e.refs.map(s=>n`${s} IS NOT NULL`),n` AND `);if((await E(i,t,n`SELECT ${e.columns} FROM ${n.identifier(e.table)} WHERE ${r} GROUP BY ${e.columns} HAVING COUNT(*) > 1 LIMIT 1`)).length>0)throw new N("INTERNAL",`unique index "${e.name}" on "${e.table}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first.`)},I=async(i,t,e)=>{if(!e.unique){await p(i,t,e);return}try{await p(i,t,e)}catch(o){throw t.isUniqueViolation(o)&&await O(i,t,e,"cannot be created"),o}},H=async(i,t,e)=>{if(t.name!=="sqlite")return;const r=(await E(i,t,n`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${e.name} AND tbl_name = ${e.table}`))[0]?.sql;if(typeof r!="string")return;const u=l=>{const f=l.indexOf("(");return f===-1?void 0:l.slice(f,l.lastIndexOf(")")+1)},s=e.unique?n`UNIQUE `:n``,a=u(U(t.name,n`CREATE ${s}INDEX ${n.identifier(e.name)} ON ${n.identifier(e.table)} (${e.columns})`).sql);a===void 0||a===u(r)||(e.unique&&await O(i,t,e,"cannot be re-created with its new column list; the previous index is left in place"),await g(i,t,n`DROP INDEX IF EXISTS ${n.identifier(e.name)}`))},X=async(i,t,e,o)=>{G(t,e,o);const r=S(e),u=a=>{const l=d(a),f=e.shape[a],c=f&&o.indexKeyPrefix&&f._meta?.column?.unique!==!0&&!r.has(a)?o.indexKeyPrefix(w(f)):void 0;return c===void 0?l:n`${l}(${n.raw(String(c))})`},s=V(o);for(const a of e.indexes){const l=a.fields.map($=>u($)),f=n.join(l,n`, `),c=a.unique??!1,m={columns:c||s===void 0?f:n`${f}, ${s}`,name:`${t}_${a.name}`,refs:l,table:t,unique:c};await H(i,o,m),await I(i,o,m)}s!==void 0&&await p(i,o,{columns:s,name:`${t}__by_creation`,table:t,unique:!1});for(const[a,l]of k(e)){if(!l.unique)continue;const f=u(a);await I(i,o,{columns:f,name:`${t}_unique_${a}`,refs:[f],table:t,unique:!0})}},_="__lunora_migration_state",W=async(i,t)=>{await g(i,t,n`CREATE TABLE IF NOT EXISTS ${n.identifier(_)} (${n.identifier("name")} ${n.raw(t.companionTypes.key)} PRIMARY KEY)`)},Q=async(i,t,e)=>(await E(i,t,n`SELECT ${n.identifier("name")} FROM ${n.identifier(_)} WHERE ${n.identifier("name")} = ${e}`)).length>0,z=async(i,t,e,o,r,u)=>{r>0&&u!==void 0&&console.warn(`[@lunora/sql-store] storage migration "${e}" on "${o}": ${String(r)} row(s) ${u} and were left as stored — range filters and ORDER BY over them stay wrong until they are corrected by hand.`);try{await g(i,t,n`INSERT INTO ${n.identifier(_)} (${n.identifier("name")}) VALUES (${e})`)}catch(s){if(!t.isUniqueViolation(s))throw s}},J=100,Z=(i,t)=>{const e=[],o=[];for(const r of t.fields){const u=i[r],s=t.convert(u);s!==void 0&&(e.push(n`${d(r)} = ${s}`),o.push(n`${d(r)} = ${u}`))}return{assignments:e,guards:o}},v=async(i,t,e,o)=>{if(o.fields.length===0||(await W(i,e),await Q(i,e,o.marker)))return;const r=n.join(o.fields.map(l=>o.probe(l)),n` OR `),u=n.join([d("id"),...o.fields.map(l=>d(l))],n`, `);let s="",a=0;for(;;){const l=await E(i,e,n`SELECT ${u} FROM ${n.identifier(t)} WHERE (${r}) AND ${d("id")} > ${s} ORDER BY ${d("id")} LIMIT ${n.raw(String(J))}`);if(l.length===0){await z(i,e,o.marker,t,a,o.describeUnconvertible);return}const f=[];for(const m of l){const{id:$}=m,{assignments:T,guards:C}=typeof $=="string"?Z(m,o):{assignments:[],guards:[]};if(T.length===0){a+=1;continue}f.push(n`UPDATE ${n.identifier(t)} SET ${n.join(T,n`, `)} WHERE ${d("id")} = ${$} AND ${n.join(C,n` AND `)}`)}await B(i,e,f);const c=l.at(-1)?.id;if(typeof c!="string")return;s=c}},R=i=>`'${i}%'`,nn=i=>Object.entries(i.shape).filter(([,t])=>t._meta?.column!==void 0&&w(t)==="bigint").map(([t])=>t),en=i=>Object.entries(i.shape).filter(([,t])=>t._meta?.column!==void 0&&P(w(t))).map(([t])=>t),tn=async(i,t,e,o)=>v(i,t,o,{convert:r=>{if(!(typeof r!="string"||r.length===b))try{return M(BigInt(r))}catch{return}},describeUnconvertible:"hold a value the order-preserving key cannot represent (non-numeric text, or a magnitude past 39 digits)",fields:nn(e),marker:`bigint-key:${t}`,probe:r=>n`(${d(r)} IS NOT NULL AND LENGTH(${d(r)}) <> ${b})`}),on=async(i,t,e,o)=>v(i,t,o,{convert:j,fields:en(e),marker:`untyped-number-key:${t}`,probe:r=>n`(${d(r)} LIKE ${n.raw(R(F))} AND ${d(r)} NOT LIKE ${n.raw(R(K))})`}),rn=async(i,t,e,o)=>{const r=[[h,o.companionTypes.integer],...Object.entries(e.shape).filter(([,s])=>s._meta?.column!==void 0).map(([s,a])=>[s,A(a,o)])],u=async s=>{try{return await E(i,o,n`SELECT ${n.join(s.map(a=>d(a)),n`, `)} FROM ${n.identifier(t)} LIMIT 0`),!0}catch{return!1}};if(!await u(r.map(([s])=>s)))for(const[s,a]of r)await u([s])||await g(i,o,n`ALTER TABLE ${n.identifier(t)} ADD COLUMN ${n.identifier(s)} ${n.raw(a)}`)},mn=async(i,t,e)=>{for(const[o,r]of Object.entries(t.tables)){if(r.shardMode?.kind!=="global")continue;const u=Y(o,r,e);await g(i,e,n`CREATE TABLE IF NOT EXISTS ${n.identifier(o)} (${u})`),await rn(i,o,r,e),await X(i,o,r,e),await tn(i,o,r,e),await on(i,o,r,e)}},q=i=>i.shardMode===void 0||i.shardMode.kind==="global",$n=async(i,t,e)=>{const{integer:o,key:r,real:u}=e.companionTypes;for(const[s,a]of Object.entries(t.tables)){const l=a.aggregateIndexes;if(!(!l||l.length===0||!q(a)))for(const f of l){const c=x(s,f.name);await g(i,e,n`CREATE TABLE IF NOT EXISTS ${n.identifier(c)} (${n.identifier("__key__")} ${n.raw(r)} PRIMARY KEY, ${n.identifier("__value__")} ${n.raw(u)}, ${n.identifier("__count__")} ${n.raw(o)} NOT NULL DEFAULT 0)`),e.name==="sqlite"&&((await E(i,e,n`PRAGMA table_info(${n.identifier(c)})`)).some($=>$.name==="__count__")||await g(i,e,n`ALTER TABLE ${n.identifier(c)} ADD COLUMN ${n.identifier("__count__")} ${n.raw(o)} NOT NULL DEFAULT 0`))}}},y=(i,t,e,o)=>{const r=i.name==="mysql"&&o?n`${n.identifier(t)}(191)`:n`${n.identifier(t)}`;return n`${r} ${n.raw(e)}`},sn=(i,t,e)=>{const o=[y(i,"__partition__","ASC",!0)];for(const[r,u]of t.sortBy.entries()){const s=e.shape[u.field],a=s!==void 0&&i.indexKeyPrefix?.(w(s))!==void 0;o.push(y(i,L(r),u.direction==="desc"?"DESC":"ASC",a))}return o.push(y(i,"__id__","ASC",!0)),o},an=(i,t,e)=>t.sortBy.map((o,r)=>{const u=e.shape[o.field],s=i.columnType(u?w(u):void 0);return n`${n.identifier(L(r))} ${n.raw(s)}`}),gn=async(i,t,e)=>{const{key:o}=e.companionTypes;for(const[r,u]of Object.entries(t.tables)){const s=u.rankIndexes;if(!(!s||s.length===0||!q(u)))for(const a of s){const l=D(r,a.name),f=an(e,a,u),c=f.length>0?n`, ${n.join(f,n`, `)}`:n``;await g(i,e,n`CREATE TABLE IF NOT EXISTS ${n.identifier(l)} (${n.identifier("__id__")} ${n.raw(o)} PRIMARY KEY, ${n.identifier("__partition__")} ${n.raw(o)} NOT NULL${c})`);const m=sn(e,a,u),$=`${r}__rank_${a.name}__btree`;await p(i,e,{columns:n.join(m,n`, `),name:$,table:l,unique:!1})}}};export{$n as runSqlAggregateMigrations,mn as runSqlGlobalTableMigrations,gn as runSqlRankMigrations};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/sql-store",
3
- "version": "1.0.0-alpha.123",
3
+ "version": "1.0.0-alpha.125",
4
4
  "description": "Internal dialect-parameterized SQL store core for Lunora .global() backends (D1, PlanetScale)",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -51,7 +51,7 @@
51
51
  },
52
52
  "dependencies": {
53
53
  "@lunora/errors": "1.0.0-alpha.39",
54
- "@lunora/shard-engine": "1.0.0-alpha.72",
54
+ "@lunora/shard-engine": "1.0.0-alpha.74",
55
55
  "drizzle-orm": "^0.45.2"
56
56
  },
57
57
  "engines": {
@@ -1,7 +0,0 @@
1
- import{LunoraError as T}from"@lunora/errors";import{m as Wt,D as Ut}from"./ctx-db-search-state-DfmFuOtg.mjs";import{c as xt,r as Pt,A as Ht,C as Kt,R as jt,a as Gt,T as Vt,x as Yt,b as Xt}from"./ctx-db-search-C9UlHY9M.mjs";import{d as yi}from"./ctx-db-search-C9UlHY9M.mjs";import{literalInList as zt,throwingScheduler as Qt,CDC_LOG_TABLE as j,cursorBelowRetainedFloor as Jt,cdcTrimmedError as Zt,assertNoExplicitUndefined as et,hasTrigger as en,runRowValidators as Ne,assertFlatPredicate as tt,mergeWhere as q,rankTableName as we,sortColumnName as Ee,resolveRankPartition as nt,encodePartitionKey as Ce,resolveRankSeekTuple as tn,RANK_TIEBREAK as ye,CountRlsUnsupportedError as it,stripReservedPatchFields as nn,normalizeIdStructurally as on,assertValidClientId as rn,aggregateSqlFunction as $e,softDeleteScope as _e,compileWhereSql as he,normalizeOrderKeys as sn,uniqueIndexFields as an,equalityPinnedFields as cn,buildSeekWhere as dn,decodeCursor as ln,resolveRelationPredicates as ot,resolveWith as rt,relationHooks as st,applySelect as at,encodeCursor as un,NotFoundError as fn,applyOnDelete as wn,ConflictError as Ae,normalizeCountArgument as $n,selectIndexForCount as _n,encodeAggregateKey as Y,aggregateTableName as Q,selectIndexForAggregate as hn,readAggregateValue as De,runTriggers as En,matchesRankStaticWhere as ct,rankPivotConditionSql as pt,CURSOR_PREFIX as yn,selectIndexForGroupBy as pn,tiebreakDirectionFor as Rn,fanOutScalarCounts as Sn,matchesStaticWhere as Be,foldAggregateTally as dt,coerceAggregateNumber as qe,CDC_LOG_TABLE_SEQ_INDEX as gn,NotUniqueError as Tn}from"@lunora/shard-engine";import{sql as e}from"drizzle-orm";import{d as Rt,b as vn,e as St,n as mn,c as In}from"./value-codec-DC_dHxUY.mjs";import{runSqlGlobalTableMigrations as bn,runSqlAggregateMigrations as Cn,runSqlRankMigrations as An}from"./runSqlAggregateMigrations-FPKBRRzo.mjs";import{queryAll as m,queryRun as M,createIndexIfNotExists as Ln,decodeRow as ee,serializeDocumentColumn as J,columnRefSql as O,decodeRows as lt,tableColumns as gt,OCC_VERSION_COLUMN as ut,serializeColumnValue as Oe,forEachRowPaged as ft,BACKFILL_BATCH_SIZE as Fe,queryBatch as wt}from"./decodeGlobalRow-D9KXPy-S.mjs";import{decodeGlobalRow as Ri}from"./decodeGlobalRow-D9KXPy-S.mjs";const kn=(a,c)=>{if(a.size<c)return;const E=a.keys().next().value;E!==void 0&&a.delete(E)},$t=50,Mn=(a,c={})=>{const E=c.maxBatch??$t,s=Number.isInteger(E)&&E>0?E:$t,p=new Map;let w=!1;const d=async(g,v)=>{const I=[...v.keys()];for(let L=0;L<I.length;L+=s){const N=I.slice(L,L+s);try{const W=await a(g,N);for(const G of N){const V=W.get(G);for(const ie of v.get(G)??[])ie.resolve(V)}}catch(W){for(const G of N)for(const V of v.get(G)??[])V.reject(W)}}},A=()=>{w=!1;const g=[...p.entries()];p.clear();for(const[v,I]of g)d(v,I).catch(()=>{})};return{async load(g,v){return new Promise((I,L)=>{let N=p.get(g);N||(N=new Map,p.set(g,N));const W=N.get(v);W?W.push({reject:L,resolve:I}):N.set(v,[{reject:L,resolve:I}]),w||(w=!0,queueMicrotask(A))})}}},Nn=new Set(["_id","id"]),Pe=(a,c,E)=>a==="postgres"?e`${c} IS NOT DISTINCT FROM ${E}`:a==="mysql"?e`${c} <=> ${E}`:e`${c} IS ${E}`,Tt=(a,c)=>a.name!=="postgres"||c.nullable!==!0?"":c.direction==="desc"?" NULLS LAST":" NULLS FIRST",Dn=(a,c)=>{const E=a.map(s=>e`${O(s.field)} ${e.raw(`${s.direction==="desc"?"DESC":"ASC"}${Tt(c,s)}`)}`);if(!a.some(s=>Nn.has(s.field))){const s=Rn(a);E.push(e`${O("id")} ${e.raw(s==="desc"?"DESC":"ASC")}`)}return e.join(E,e`, `)},_t=50,Bn=(a,c,E)=>{const s={...c};for(const[p,w]of gt(a)){if(w.serverDefault){s[p]=w.serverDefault({auth:E});continue}s[p]===void 0&&(w.defaultFn?s[p]=w.defaultFn():"defaultValue"in w&&(s[p]=w.defaultValue))}return s},ht=(a,c,E,s)=>{for(const[p,w]of gt(a)){if(w.serverDefault){p in c&&(E[p]=w.serverDefault({auth:s}));continue}w.onUpdateFn&&!(p in c)&&(E[p]=w.onUpdateFn())}},qn=128,On=()=>{const a=new Map;return{delete:c=>{a.delete(c)},get:c=>{const E=a.get(c);if(E!==void 0)return a.delete(c),a.set(c,E),E},set:(c,E)=>{a.has(c)?a.delete(c):kn(a,qn),a.set(c,E)}}},Fn=async(a,c,E,s,p)=>{const w=p.get(s);if(w!==void 0)return w;const d=Object.entries(E.tables).filter(([,g])=>g.shardMode===void 0||g.shardMode.kind==="global").map(([g])=>g),A=await Promise.all(d.map(async g=>({found:(await m(a,c,e`SELECT 1 FROM ${e.identifier(g)} WHERE ${e.identifier("id")} = ${s} LIMIT 1`)).length>0,tableName:g})));for(const g of A)if(g.found)return p.set(s,g.tableName),g.tableName},te=a=>a==null?null:Number(a),Wn=(a,c,E)=>E.map(s=>{const p={};for(const w of c){const d=a.shape[w];p[w]=vn(s[w]??null,d&&St(d))}return{key:p,value:te(s.value)}}),Un=(a,c,E)=>[...a.partitionBy??[],...a.sortBy.map(p=>p.field),...a.where?Object.keys(a.where):[]].every(p=>c[p]===E[p]),vt=a=>a.length===1?a[0]:e`(${e.join(a,e` AND `)})`,Z=a=>e.join(a.map(c=>e`${e.identifier(c)}`),e`, `),ne=a=>e.join(a.map(c=>e`${c}`),e`, `),xn=(a,c,E,s,p)=>{const w=[];for(let d=0;d<E.length+1;d+=1){const A=E[d],g=c.sortBy[d],v=d<E.length&&A!==void 0&&g!==void 0,I=g?.direction==="desc"?"desc":"asc",L=v?pt(A,s[A],I,!1):e`${e.identifier(ye)} < ${p}`;if(L===void 0)continue;const N=E.slice(0,d).map(W=>Pe(a,e`${e.identifier(W)}`,s[W]));N.push(L),w.push(vt(N))}return w.length>0?e.join(w,e` OR `):e`1 = 0`},Pn=(a,c,E)=>{if(E.length!==c.length)return;const s=[];for(const[p,w]of c.entries()){const d=pt(w.column,E[p],w.direction,!0);if(d===void 0)continue;const A=[];for(let g=0;g<p;g+=1){const v=c[g];v!==void 0&&A.push(Pe(a,e`${e.identifier(v.column)}`,E[g]))}A.push(d),s.push(vt(A))}return s.length===0?e`(1 = 0)`:e`(${e.join(s,e` OR `)})`},Hn=(a,c)=>{if(a.sortBy.length===0)throw new T("INTERNAL",`rankIndex "${a.name}" requires at least one "sortBy" column for stable pagination`);const E=[{column:"__partition__",direction:"asc",nullable:!1}];for(const[s,p]of a.sortBy.entries())E.push({column:c[s]??Ee(s),direction:p.direction,nullable:!0});return E.push({column:ye,direction:"asc",nullable:!1}),E},Kn=async(a,c,E,s,p)=>{const d=[];for(let I=0;I<p.length;I+=50)d.push(p.slice(I,I+50));const A=await Promise.all(d.map(async I=>m(a,c,e`SELECT * FROM ${e.identifier(s)} WHERE ${e.identifier("id")} IN (${ne(I)})`))),g=new Map;for(const I of A)for(const L of I)g.set(L.id,L);const v=[];for(const I of p){const L=ee(E,g.get(I));L&&v.push(L)}return v},jn=a=>{const c=JSON.stringify(a),E=new TextEncoder().encode(c);let s="";for(const p of E)s+=String.fromCodePoint(p);return yn+btoa(s)},mt=a=>{if(a===void 0)return!1;const c=St(a);return c==="any"||c==="bigint"||c==="from"||c==="union"},Ue=(a,c,E)=>{if(mt(a.shape[c]))throw new T("BAD_REQUEST",`${E}: "${c}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Gn=(a,c,E,s)=>{for(const p of E)Ue(a,p,`groupBy(${c}, { by: [..."${p}"] })`);s.field!==void 0&&Ue(a,s.field,`groupBy(${c}, { agg: { op: "${s.op}", field: "${s.field}" } })`)},xe="__cdc_sweep",It="global",Vn=6e4,Yn=1e4,Xn=3e4;let Et=0;const zn=async(a,c)=>{const{autoincrementPrimaryKey:E,key:s,real:p,text:w}=c.companionTypes;await M(a,c,e`CREATE TABLE IF NOT EXISTS ${e.identifier(j)} (${e.identifier("seq")} ${e.raw(E)}, ${e.identifier("ts")} ${e.raw(p)} NOT NULL, ${e.identifier("table")} ${e.raw(s)} NOT NULL, ${e.identifier("id")} ${e.raw(s)} NOT NULL, ${e.identifier("op")} ${e.raw(s)} NOT NULL, ${e.identifier("doc")} ${e.raw(w)})`);const d=c.indexKeyPrefix?.("string");await Ln(a,c,{columns:e`${d===void 0?e`${e.identifier("table")}`:e`${e.identifier("table")}(${e.raw(String(d))})`}, ${e.identifier("seq")}`,name:gn,table:j,unique:!1}),await M(a,c,e`CREATE TABLE IF NOT EXISTS ${e.identifier(xe)} (${e.identifier("id")} ${e.raw(s)} NOT NULL PRIMARY KEY, ${e.identifier("lease_until")} ${e.raw(p)} NOT NULL)`),await M(a,c,e`INSERT INTO ${e.identifier(xe)} (${e.identifier("id")}, ${e.identifier("lease_until")}) VALUES (${It}, ${0}) ${c.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${e.identifier("id")} = ${e.identifier("id")}`:e`ON CONFLICT(${e.identifier("id")}) DO NOTHING`}`)},Qn=async(a,c,E)=>{const s=e`UPDATE ${e.identifier(xe)} SET ${e.identifier("lease_until")} = ${E+Vn} WHERE ${e.identifier("id")} = ${It} AND ${e.identifier("lease_until")} <= ${E}`;if(c.supportsReturning)return(await m(a,c,e`${s} RETURNING ${e.identifier("id")}`)).length>0;const p=await M(a,c,s);return(c.affectedRows?c.affectedRows(p??{rowsAffected:0}):0)>0},Jn=async(a,c,E,s)=>{if(!await Qn(a,c,s))return;const p=s-E;await M(a,c,e`
2
- DELETE FROM ${e.identifier(j)} WHERE ${e.identifier("seq")} IN (
3
- SELECT ${e.identifier("seq")} FROM (
4
- SELECT ${e.identifier("seq")} FROM ${e.identifier(j)} WHERE ${e.identifier("ts")} <= ${p} ORDER BY ${e.identifier("seq")} ASC LIMIT ${e.raw(String(Yn))}
5
- ) AS ${e.identifier("expired")}
6
- )
7
- `)},bt=async(a,c)=>{const E=await m(a,c,e`SELECT MIN(${e.identifier("seq")}) AS ${e.identifier("seq")} FROM ${e.identifier(j)}`),s=Number(E[0]?.seq??Number.NaN);return Number.isFinite(s)?s:void 0},Zn=a=>JSON.stringify(mn(a)?In(a):a),ei=async(a,c,E,s,p,w,d)=>{await M(a,d,e`INSERT INTO ${e.identifier(j)} (${e.identifier("ts")}, ${e.identifier("table")}, ${e.identifier("id")}, ${e.identifier("op")}, ${e.identifier("doc")}) VALUES (${c}, ${E}, ${s}, ${p}, ${w===void 0?null:Zn(w)})`)},$i=async(a,c,E)=>{const s=c.sinceSeq??0,p=Math.max(1,Math.min(c.limit??1e3,1e4)),w=await bt(a,E);if(w!==void 0&&Jt(w,s))throw Zt(w,s,"global");const A=(await m(a,E,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(j)} WHERE seq > ${s} ORDER BY seq ASC LIMIT ${e.raw(String(p))}`)).map(g=>{const{doc:v}=g,I={id:String(g.id),op:String(g.op),seq:Number(g.seq),table:String(g.table),ts:Number(g.ts)};return typeof v=="string"?{...I,doc:Rt(JSON.parse(v))}:I});return{changes:A,cursor:A.at(-1)?.seq??s}},ti=async(a,c,E,s={})=>{if(s.cursorOnly){const g=await m(a,E,e`SELECT MAX(seq) AS seq FROM ${e.identifier(j)}`),v=Number(g[0]?.seq??c);return{cursor:Number.isFinite(v)?v:c,tables:[]}}const p=await m(a,E,e`SELECT ${e.identifier("table")} AS ${e.identifier("table")}, MAX(seq) AS seq FROM ${e.identifier(j)} WHERE seq > ${c} GROUP BY ${e.identifier("table")}`);let w=c;const d=[];for(const g of p){const v=Number(g.seq);Number.isFinite(v)&&v>w&&(w=v),d.push(String(g.table))}const A=s.retained===!0?await bt(a,E):void 0;return{cursor:w,tables:d,...A===void 0?{}:{floor:A}}},ni=/string or blob too big/iu,ii=/row is too big/iu,oi=(a,c)=>{const{code:E,errno:s}=c,p=c instanceof Error?c.message:"";switch(a.name){case"mysql":return s===1118||E==="ER_TOO_BIG_ROWSIZE"?"InnoDB's per-row ceiling — roughly 8 KB, half a 16 KB page, for the part of the row stored inline":void 0;case"postgres":return ii.test(p)?"the 8 KB heap page a tuple must fit once its wide columns have been TOASTed out":void 0;default:return ni.test(p)?"the storage engine's per-row ceiling (2 MB on D1)":void 0}},ri=(a,c,E)=>{const s=oi(a,c);if(s!==void 0)throw new T("PAYLOAD_TOO_LARGE",`document is too large to store in "${E}": a single row cannot exceed ${s}. The limit is on the STORED bytes, which are UTF-8. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},yt=(a,c,E)=>{throw a.isUniqueViolation(c)?new Ae(`unique constraint violation on "${E}"`,"unique"):(ri(a,c,E),c)},We=new WeakMap,_i=a=>{const{crossShardCounter:c,crossShardReader:E,exec:s,maxRelationKeys:p,schema:w}=a,{dialect:d}=a,A={fieldRef:O,...d.name==="mysql"?{containsExpr:(t,n)=>e`LOCATE(${n}, ${t}) > 0`}:{},...d.name==="postgres"?{containsExpr:(t,n)=>e`strpos(${t}, ${n}) > 0`}:{},...d.name==="sqlite"?{}:{inList:zt}},g=new WeakMap,v=t=>{const n=g.get(t);if(n!==void 0)return n;const i={...A,serialize:(o,r)=>J(t,r,o)};return g.set(t,i),i},I=(t,n)=>Pe(d.name,t,n),L=t=>{const n=Z(t.columns),i=ne(t.values),o=u=>d.name==="mysql"?e`VALUES(${e.identifier(u)})`:e`excluded.${e.identifier(u)}`,r=u=>d.name==="postgres"?e`${e.identifier(t.table)}.${e.identifier(u)}`:e`${e.identifier(u)}`,l=e.join(Object.entries(t.set(o,r)).map(([u,y])=>e`${e.identifier(u)} = ${y}`),e`, `),h=d.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${l}`:e`ON CONFLICT(${e.identifier(t.conflictKey)}) DO UPDATE SET ${l}`;return e`INSERT INTO ${e.identifier(t.table)} (${n}) VALUES (${i}) ${h}`},N=a.clock??(()=>Date.now()),W=a.idGenerator??(()=>crypto.randomUUID()),G=a.cdc??!1,V=typeof a.cdcRetentionMs=="number"&&Number.isFinite(a.cdcRetentionMs)&&a.cdcRetentionMs>0?a.cdcRetentionMs:void 0,ie=a.auth??{identity:null,userId:null},oe=async(t,n,i,o)=>{if(!G||(await ei(s,N(),t,n,i,o,d),V===void 0))return;const r=N();if(!(r-Et<Xn)){Et=r;try{await Jn(s,d,V,r)}catch{}}},Ct=a.scheduler??Qt,Le=On();let pe=0;const ke=a.provisionScope??{},U=async()=>{const t=We.get(ke);if(t)return t;const n=(async()=>{await bn(s,w,d),await Cn(s,w,d),await An(s,w,d),await Wt(s,d),await Pt(s,w,d),G&&await zn(s,d)})().catch(i=>{throw We.delete(ke),i});return We.set(ke,n),n},re=async(t,n)=>{await U();const i=await Fn(s,d,w,t,Le);if(!(n!==void 0&&i!==n))return i},se=new Map,He=async(t,n)=>{const i=Q(t,n);return(await m(s,d,d.tableExists(i))).length>0},Re=async(t,n)=>{const i=`${t}::${n.name}`,o=se.get(i);if(o!==void 0)return o;if(!await He(t,n.name))return se.set(i,!1),!1;const l=w.tables[t];if(!l)return se.set(i,!1),!1;const h=n.by??[],u=new Map;await ft(s,d,l,t,$=>{if(n.where&&!Be($,n.where))return;const _=Y(h,$);dt(u,_,n,$)});const y=Q(t,n.name);await M(s,d,e`DELETE FROM ${e.identifier(y)}`);const f=[];for(const[$,_]of u)f.push(e`INSERT INTO ${e.identifier(y)} (${e.identifier("__key__")}, ${e.identifier("__value__")}, ${e.identifier("__count__")}) VALUES (${$}, ${_.value}, ${_.count})`);return await wt(s,d,f),se.set(i,!0),!0},At=async(t,n,i,o)=>{const r=new Map;let l,h=!0;for(;h;){const u=l===void 0?o:[...o,e`${e.identifier("id")} > ${l}`],y=u.length>0?e` WHERE ${e.join(u,e` AND `)}`:e``,f=await m(s,d,e`SELECT ${e.identifier("id")}, ${O(i.field??"")} FROM ${e.identifier(n)}${y} ORDER BY ${e.identifier("id")} ASC LIMIT ${e.raw(String(Fe))}`);for(const $ of lt(t,f))dt(r,"",i,$);l=f.at(-1)?.id,h=f.length===Fe}return r.get("")?.value??null},Lt=async(t,n,i)=>{const o=n.field??"",r=[],l=w.tables[t],h=($,_)=>l?J(l,$,_):Oe(_);for(const $ of n.by??[]){const _=h($,i[$]??null);r.push(_===null?e`${O($)} IS NULL`:e`${O($)} = ${_}`)}for(const[$,_]of Object.entries(n.where??{})){const R=_!==null&&typeof _=="object"&&!Array.isArray(_)?_.eq:_,S=h($,R);r.push(S===null?e`${O($)} IS NULL`:e`${O($)} = ${S}`)}const u=r.length>0?e` WHERE ${e.join(r,e` AND `)}`:e``;if(l&&mt(l.shape[o]))return At(l,t,n,r);const y=$e(n.op),f=await m(s,d,e`SELECT ${e.raw(y)}(${O(o)}) AS ${e.identifier("value")} FROM ${e.identifier(t)}${u}`);return te(f[0]?.value)},kt=async(t,n)=>{await M(s,d,e`DELETE FROM ${e.identifier(t)} WHERE ${e.identifier("__key__")} = ${n} AND ${e.identifier("__count__")} <= 0`)},Mt=async(t,n,i,o)=>{const r=Q(t,n.name),{op:l}=n,h=n.field??"",u=i&&(!n.where||Be(i,n.where))?i:void 0,y=o&&(!n.where||Be(o,n.where))?o:void 0;if(!(!u&&!y)){if(l==="count"||l==="sum"||l==="avg"){const f=new Set;for(const[$,_]of[[u,-1],[y,1]]){if(!$)continue;const R=l==="count"?1:qe($[h]);if(R===void 0)continue;const S=Y(n.by??[],$);f.add(S),await M(s,d,L({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(b,C)=>({__count__:e`${C("__count__")} + ${b("__count__")}`,__value__:l==="count"?e`${C("__value__")} + ${b("__value__")}`:e`COALESCE(${C("__value__")}, 0) + ${b("__value__")}`}),table:r,values:[S,_*R,_]}))}for(const $ of f)await kt(r,$);return}if(u){const f=Y(n.by??[],u),$=qe(u[h]),R=(await m(s,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(r)} WHERE ${e.identifier("__key__")} = ${f}`))[0],S=te(R?.value),b=(R?.count??0)-1;if(b<=0)await M(s,d,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__key__")} = ${f}`);else if(R&&$!==void 0&&S!==null&&$===S){const C=await Lt(t,n,u);await M(s,d,e`UPDATE ${e.identifier(r)} SET ${e.identifier("__value__")} = ${C}, ${e.identifier("__count__")} = ${b} WHERE ${e.identifier("__key__")} = ${f}`)}else await M(s,d,e`UPDATE ${e.identifier(r)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${f}`)}if(y){const f=Y(n.by??[],y),$=qe(y[h]);if($===void 0)await M(s,d,L({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(_,R)=>({__count__:e`${R("__count__")} + 1`}),table:r,values:[f,null,1]}));else{const _=l==="min"?"MIN":"MAX";await M(s,d,L({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(R,S)=>({__count__:e`${S("__count__")} + 1`,__value__:e`${e.raw(_)}(COALESCE(${S("__value__")}, ${R("__value__")}), ${R("__value__")})`}),table:r,values:[f,$,1]}))}}}},Se=async t=>{const n=w.tables[t]?.aggregateIndexes;if(!(!n||n.length===0))for(const i of n)await Re(t,i)},ae=async(t,n,i)=>{const o=w.tables[t]?.aggregateIndexes;if(!(!o||o.length===0))for(const r of o){const l=`${t}::${r.name}`;(se.get(l)??await He(t,r.name))&&await Mt(t,r,n,i)}},ce=new Map,Ke=async(t,n)=>{const i=we(t,n);return(await m(s,d,d.tableExists(i))).length>0},Me=async(t,n)=>{const i=`${t}::rank::${n.name}`,o=ce.get(i);if(o!==void 0)return o;if(!await Ke(t,n.name))return ce.set(i,!1),!1;const l=w.tables[t];if(!l)return ce.set(i,!1),!1;const h=we(t,n.name);await M(s,d,e`DELETE FROM ${e.identifier(h)}`);const u=n.sortBy.map((_,R)=>Ee(R)),y=Z(["__id__","__partition__",...u]);let f=[];const $=async()=>{if(f.length===0)return;const _=f;f=[],await wt(s,d,_)};return await ft(s,d,l,t,async _=>{if(n.where&&!ct(_,n.where))return;const R=Ce(n.partitionBy??[],_),S=n.sortBy.map(b=>Oe(_[b.field]??null));f.push(e`INSERT INTO ${e.identifier(h)} (${y}) VALUES (${ne([_._id,R,...S])})`),f.length>=Fe&&await $()}),await $(),ce.set(i,!0),!0},ge=async t=>{const n=w.tables[t]?.rankIndexes;if(!(!n||n.length===0))for(const i of n)await Me(t,i)},X=async(t,n,i,o)=>{const r=w.tables[t],l=r?.rankIndexes;if(!l||l.length===0)return;const h=r?.softDeleteMode?.field,u=h===void 0||o===void 0?void 0:o[h],y=u!=null;for(const f of l){if(i!==void 0&&o!==void 0&&Un(f,i,o))continue;const $=`${t}::rank::${f.name}`;if(!(ce.get($)??await Ke(t,f.name)))continue;const S=we(t,f.name);if(i&&await M(s,d,e`DELETE FROM ${e.identifier(S)} WHERE ${e.identifier("__id__")} = ${n}`),o&&!y){if(f.where&&!ct(o,f.where))continue;const b=f.sortBy.map((B,K)=>Ee(K)),C=Z(["__id__","__partition__",...b]),F=Ce(f.partitionBy??[],o),k=f.sortBy.map(B=>Oe(o[B.field]??null));await M(s,d,e`INSERT INTO ${e.identifier(S)} (${C}) VALUES (${ne([n,F,...k])})`)}}},de=xt({dialect:d,exec:s,schema:w}),je=new Set;for(const[t,n]of Object.entries(w.tables))for(const i of Object.values(n.triggerMap??{}))je.add(`${t} ${i.timing} ${i.op}`);const P=(t,n,i)=>je.has(`${t} ${n} ${i}`);let Ge;const H=async(t,n,i)=>{if(pe+=1,pe>_t)throw pe-=1,new Ae(`trigger recursion exceeded ${String(_t)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await En({ctx:Ge,event:i,op:n,schema:w,tableName:i.table,timing:t})}finally{pe-=1}},Nt=async(t,n)=>{try{await M(s,d,n)}catch(i){yt(d,i,t)}},Te=async(t,n)=>(await m(s,d,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} = ${n}`))[0],ve=async(t,n,i,o)=>{if(o===void 0)return;const r=e`${e.identifier(ut)}`,l=e.join([I(e`${e.identifier("id")}`,o.id),I(r,o[ut]??null)],e` AND `),h=n==="UPDATE"?e`UPDATE ${e.identifier(t)} SET ${i}, ${r} = COALESCE(${r}, 0) + 1 WHERE ${l}`:e`DELETE FROM ${e.identifier(t)} WHERE ${l}`,u=()=>{throw new Ae(`optimistic concurrency conflict on "${t}" — the row changed during this mutation; refetch and retry`,"occ")};try{if(d.supportsReturning)(await m(s,d,e`${h} RETURNING ${e.identifier("id")}`)).length===0&&u();else{const y=await M(s,d,h);(d.affectedRows?d.affectedRows(y??{rowsAffected:0}):0)===0&&u()}}catch(y){yt(d,y,t)}},Dt=(t,n,i,o)=>{const r=Object.keys(t.shape);return{columns:["id","_creationTime",...r],values:[n,i,...r.map(l=>J(t,l,o[l]??null))]}},Bt=async(t,n,i,o)=>{const r=pn(n,i.op,i.field,o.by,o.where);if(!r||!await Re(t,r.index))return;const h=Q(t,r.index.name),u=Object.keys(r.partial);if(u.length===(r.index.by??[]).length&&u.length>0){const f=Y(r.index.by??[],r.partial),$=await m(s,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(h)} WHERE ${e.identifier("__key__")} = ${f}`);if($.length===0)return[];const _=$[0];return[{key:{...r.partial},value:De(i.op,{count:_.count,value:te(_.value)})}]}return u.length>0?void 0:(await m(s,d,e`SELECT ${e.identifier("__key__")} AS ${e.identifier("key")}, ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(h)}`)).map(f=>{const $=f;return{key:Rt(JSON.parse($.key)),value:De(i.op,{count:$.count,value:te($.value)})}})},Ve=t=>{const n=w.tables[t]?.shardMode?.kind;return n==="shardBy"||n==="root"},Ye=t=>{throw new T("INTERNAL",`cross-backend relation: a global table cannot load the shard-local relation '${t}' (it spans every shard) — wire a cross-shard reader to support it`)},qt=(t,n)=>{if(n?.relationMask!==void 0&&n.with!==void 0&&Object.keys(n.with).length>0)throw new T("MASK_UNSUPPORTED",`masking cannot follow a nested \`with\` across the cross-shard relation hop to "${t}" — the nested rows are hydrated on the serving shard, where the mask policy does not exist. Read the nested relation at its own (masked) call site instead.`);const i={};if(n?.relationBaseWhere)for(const o of Object.keys(w.tables)){const r=n.relationBaseWhere(o);r!==void 0&&(i[o]=r)}return{orderBy:n?.orderBy,relationPolicies:i,where:q(n?.baseWhere,n?.where),with:n?.with}},Xe=(t,n)=>Ve(t)?E?E(t,qt(t,n)):Ye(t):x.findMany(t,n),me=(t,n,i)=>ot(t,{fetcher:Xe,maxRelationKeys:p,relationBaseWhere:i,schema:w,tableName:n}),Ot=Mn(async(t,n)=>{const i=await m(s,d,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} IN (${ne(n)})`),o=new Map;for(const r of i){const{id:l}=r;typeof l=="string"&&o.set(l,r)}return o}),x={async cdcChangedTables(t,n){if(G)try{return await U(),await ti(s,t,d,{...n,retained:V!==void 0})}catch{return}},async aggregate(t,n){const i=w.tables[t];if(!i)throw new T("INTERNAL",`unknown table: ${t}`);if(await U(),$e(n.op),n.op==="count")return x.count(t,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new T("INTERNAL",`aggregate(${t}, { op: "${n.op}" }): "field" is required for non-count reducers`);const o=_e(i.softDeleteMode,void 0),r=q(q(n.baseWhere,n.where),o),l=await me(r,t,n.relationBaseWhere),h=l!==r;if(i.aggregateIndexes&&!n.baseWhere&&!h&&!o){const R=hn(i.aggregateIndexes,n.op,n.field,n.where);if(R&&await Re(t,R.index)){const b=Y(R.index.by??[],R.key),C=Q(t,R.index.name),k=(await m(s,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(C)} WHERE ${e.identifier("__key__")} = ${b}`))[0];return De(n.op,k===void 0?void 0:{count:k.count,value:te(k.value)})}}Ue(i,n.field,`aggregate(${t}, { op: "${n.op}", field: "${n.field}" })`);const u=he(l,v(i)),y=e.raw($e(n.op)),f=e`SELECT ${y}(${O(n.field)}) AS ${e.identifier("value")} FROM ${e.identifier(t)}`,_=(await m(s,d,u?e`${f} WHERE ${u}`:f))[0]?.value;return _==null?null:Number(_)},async count(t,n){const i=w.tables[t];if(!i)throw new T("INTERNAL",`unknown table: ${t}`);await U();const o=$n(n);if(o.restrictsCounts)throw new it(t);const r=_e(i.softDeleteMode,void 0),l=q(q(o.baseWhere,o.where),r),h=await me(l,t,o.relationBaseWhere),u=h!==l;if(i.aggregateIndexes&&!o.baseWhere&&!u&&!r){const _=_n(i.aggregateIndexes,o.where);if(_&&await Re(t,_.index)){const S=Y(_.index.by??[],_.key),b=Q(t,_.index.name),C=await m(s,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")} FROM ${e.identifier(b)} WHERE ${e.identifier("__key__")} = ${S}`);return Number(C[0]?.value??0)}}const y=he(h,v(i)),f=e`SELECT COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(t)}`,$=await m(s,d,y?e`${f} WHERE ${y}`:f);return Number($[0]?.count??0)},async delete(t,n,i){const o=await re(t,n);if(!o)return;const r=w.tables[o];if(!r)return;const l=await Te(o,t),h=ee(r,l),u=i?.hard===!0,y=!u&&r.softDeleteMode?r.softDeleteMode.field:void 0;if(!(y&&(!h||h[y]!==null&&h[y]!==void 0))){if(P(o,"before","delete")&&await H("before","delete",{id:t,op:"delete",previous:h??void 0,table:o}),await wn({deletedId:t,deletedReference:f=>h?.[f],findHolders:async(f,$,_)=>{if(w.tables[f]?.shardMode?.kind==="shardBy")throw new T("INTERNAL",`cross-backend cascade from global '${o}' into shardBy '${f}' is not supported — would require Query Coordinator fan-out across shards`);return(await x.findMany(f,{includeDeleted:u,where:{[$]:_}})).page},onCascade:(f,$)=>x.delete($,void 0,i),onRestrict:f=>{throw new Ae(f,"restrict")},onSetNull:(f,$,_)=>x.patch($,{[_]:null}),schema:w,tableName:o}),await Se(o),await ge(o),y&&h){const f={...h,[y]:N()},$=e.join(Object.keys(r.shape).map(_=>e`${e.identifier(_)} = ${J(r,_,f[_]??null)}`),e`, `);await ve(o,"UPDATE",$,l),await ae(o,h,f),await X(o,t,h,void 0),await de(o,t,f,h),await oe(o,t,"update",f),P(o,"after","delete")&&await H("after","delete",{id:t,op:"delete",previous:h,table:o});return}await ve(o,"DELETE",void 0,l),Le.delete(t),await ae(o,h??void 0,void 0),await X(o,t,h??void 0,void 0),await de(o,t,void 0),await oe(o,t,"delete"),P(o,"after","delete")&&await H("after","delete",{id:t,op:"delete",previous:h??void 0,table:o})}},async findFirst(t,n={}){return(await x.findMany(t,{...n,limit:1})).page[0]??null},async findFirstOrThrow(t,n={}){const i=await x.findFirst(t,n);if(i===null)throw new fn(`findFirstOrThrow: no "${t}" document matched`);return i},async findMany(t,n={}){const i=w.tables[t];if(!i)throw new T("INTERNAL",`unknown table: ${t}`);await U();const o=sn(n.orderBy,i.shape,{pinned:cn(n.where),uniqueBy:an(i.indexes,i.shape)}),r=n.cursor?dn(o,ln(n.cursor)):void 0,l=Xe,h=async(k,B,K,Ie)=>{if(Ve(k))return c?Sn(c,k,B,K,Ie):Ye(k);const le=w.tables[k];if(!le)throw new T("INTERNAL",`unknown table: ${k}`);const be=_e(le.softDeleteMode,void 0),z={[B]:{in:K}},D=q(q(z,Ie),be),ue=await me(D,k,void 0),ze=he(ue,v(le)),Qe=O(B);let fe=e`SELECT ${Qe} AS __fk__, COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(k)}`;ze&&(fe=e`${fe} WHERE ${ze}`),fe=e`${fe} GROUP BY ${Qe}`;const Ft=await m(s,d,fe),Je=new Map;for(const Ze of Ft)Je.set(Ze.__fk__,Number(Ze.count??0));return Je};let u=q(n.baseWhere,n.where);u=q(u,_e(i.softDeleteMode,n.includeDeleted)),u=await ot(u,{fetcher:l,maxRelationKeys:p,relationBaseWhere:n.relationBaseWhere,schema:w,tableName:t}),r&&(u=u?{AND:[u,r]}:r);const y=he(u,v(i)),f=Dn(o,d);let $=e`SELECT * FROM ${e.identifier(t)}`;y&&($=e`${$} WHERE ${y}`),$=e`${$} ORDER BY ${f}`;const _=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;_!==void 0&&($=e`${$} LIMIT ${e.raw(String(_+1))}`);const R=await m(s,d,$),S=lt(i,R);if(_===void 0)return n.with&&await rt({fetcher:l,groupedCounter:h,parents:S,...st(n),schema:w,tableName:t,with:n.with}),{continueCursor:null,isDone:!0,page:at(S,n.select,n.with)};const b=S.length>_,C=b?S.slice(0,_):S,F=C.at(-1);return n.with&&await rt({fetcher:l,groupedCounter:h,parents:C,...st(n),schema:w,tableName:t,with:n.with}),{continueCursor:b&&F?un(F,o):null,isDone:!b,page:at(C,n.select,n.with)}},async get(t,n){const i=await re(t,n);if(!i)return null;const o=w.tables[i];return o?ee(o,await Ot.load(i,t)):null},async groupBy(t,n){const i=w.tables[t];if(!i)throw new T("INTERNAL",`unknown table: ${t}`);await U();const o=n.agg??{op:"count"};if($e(o.op),o.op!=="count"&&!o.field)throw new T("INTERNAL",`groupBy(${t}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);const r=_e(i.softDeleteMode,void 0),l=q(q(n.baseWhere,n.where),r),h=await me(l,t,n.relationBaseWhere),u=h!==l;if(i.aggregateIndexes&&!n.baseWhere&&!u&&!r){const S=await Bt(t,i.aggregateIndexes,o,n);if(S!==void 0)return S}Gn(i,t,n.by,o);const y=he(h,v(i)),f=n.by.map(S=>e`${O(S)} AS ${e.identifier(S)}`);if(o.op==="count")f.push(e`COUNT(*) AS ${e.identifier("value")}`);else{if(!o.field)throw new T("INTERNAL",`groupBy(${t}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);f.push(e`${e.raw($e(o.op))}(${O(o.field)}) AS ${e.identifier("value")}`)}const $=e.join(n.by.map(S=>O(S)),e`, `);let _=e`SELECT ${e.join(f,e`, `)} FROM ${e.identifier(t)}`;y&&(_=e`${_} WHERE ${y}`),_=e`${_} GROUP BY ${$}`;const R=await m(s,d,_);return Wn(i,n.by,R)},async insert(t,n,i){const o=w.tables[t];if(!o)throw new T("INTERNAL",`unknown table: ${t}`);await U();const r=Bn(o,n,ie);Ne(o,r);let l,h=!0;i?.clientId!==void 0?(rn(i.clientId),l=i.clientId):i?.allowExplicitId&&typeof r._id=="string"?l=r._id:(l=W(),h=!1);const u=i?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:N(),y={...r,_creationTime:u,_id:l};P(t,"before","insert")&&await H("before","insert",{doc:{...y},id:l,op:"insert",table:t}),await Se(t),await ge(t);const{columns:f,values:$}=Dt(o,l,u,r);return await Nt(t,e`INSERT INTO ${e.identifier(t)} (${Z(f)}) VALUES (${ne($)})`),h&&Le.set(l,t),await ae(t,void 0,y),await X(t,l,void 0,y),await de(t,l,y),await oe(t,l,"insert",y),P(t,"after","insert")&&await H("after","insert",{doc:y,id:l,op:"insert",table:t}),l},normalizeId(t,n){return on(w,t,n)},async patch(t,n,i){et("patch",n);const o=await re(t,i);if(!o)throw new T("INTERNAL",`document not found: ${t}`);const r=w.tables[o];if(!r)throw new T("INTERNAL",`document not found: ${t}`);const l=await Te(o,t),h=ee(r,l);if(!h)throw new T("INTERNAL",`document not found: ${t}`);const u={...h,...nn(n),_id:t};ht(r,n,u,ie),Ne(r,u,!0),P(o,"before","update")&&await H("before","update",{doc:{...u},id:t,op:"update",previous:h,table:o}),await Se(o),await ge(o);const y=Object.keys(r.shape),f=e.join(y.map($=>e`${e.identifier($)} = ${J(r,$,u[$]??null)}`),e`, `);await ve(o,"UPDATE",f,l),await ae(o,h,u),await X(o,t,h,u),await de(o,t,u,h),await oe(o,t,"update",u),P(o,"after","update")&&await H("after","update",{doc:u,id:t,op:"update",previous:h,table:o})},async restore(t,n){const i=await re(t,n);if(!i)throw new T("INTERNAL",`document not found: ${t}`);const o=w.tables[i],r=o?.softDeleteMode?.field;if(!o||!r)throw new T("INTERNAL",`ctx.db.restore: table "${i}" is not a .softDelete() table`);const l=await Te(i,t),h=l?.[r]!==null&&l?.[r]!==void 0;if(await x.patch(t,{[r]:null},n),h){const u=ee(o,l);u!==null&&await X(i,t,void 0,{...u,[r]:null})}},query(t){const n=w.tables[t];if(!n)throw new T("INTERNAL",`unknown table: ${t}`);const i="the legacy query()/withIndex() reader is not available on the D1 (global) backend; use findMany",o=[],r=u=>o.every(y=>y(u)),l=async(u,y)=>{await U();const f=o.length>0,$=await Gt(s,d,n,t,u,Vt(f?void 0:y));if(!f)return y===void 0&&Yt($),$;const _=$.filter(R=>r(R));return y===void 0?_:_.slice(0,y)},h=u=>{const y={async*[Symbol.asyncIterator](){if(!u)throw new T("INTERNAL",i);yield*await l(u,void 0)},async collect(){if(!u)throw new T("INTERNAL",i);return l(u,void 0)},async collectWithScores(){throw new T("GLOBAL_SEARCH_SCORES_UNSUPPORTED",`collectWithScores() is not supported on \`.global()\` tables (table "${t}") — relevance scores are not yet surfaced on this backend; use .collect() instead`)},filter(f){return o.push(f),y},async first(){if(!u)throw new T("INTERNAL",i);return(await l(u,1))[0]??null},order(){return y},async paginate(f){if(!u)throw new T("INTERNAL",i);const $=Kt(f);return jt(await l(u,Xt($)),$)},async take(f){if(!u)throw new T("INTERNAL",i);return l(u,f)},async unique(){if(!u)throw new T("INTERNAL",i);const f=await l(u,2);if(f.length>1)throw new Tn(`unique() on table "${t}" matched ${String(f.length)} documents; expected at most one`);return f[0]??null},withGeoIndex(){throw new T("INTERNAL",`geo indexes are not supported on \`.global()\` tables (table "${t}") — geospatial queries run only on sharded tables`)},withIndex(){throw new T("INTERNAL",i)},withSearchIndex(f,$){const _=(n.searchIndexes??[]).find(S=>S.name===f);if(!_)throw new T("INTERNAL",`unknown search index "${f}" on table "${t}"`);const R={definition:_,field:_.field,filters:[],hasQuery:!1,indexName:f,query:""};if($(Ht(R,t,Ut(_.language))),!R.hasQuery)throw new T("INTERNAL",`search index "${f}" on table "${t}" requires a .search(field, query) call`);return h(R)}};return y};return h(void 0)},async rank(t,n,i){const o=w.tables[t];if(!o)throw new T("INTERNAL",`unknown table: ${t}`);const r=o.rankIndexes?.find(B=>B.name===n);if(!r)throw new T("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(i.restrictsCounts)throw new it(t);if(await U(),!await Me(t,r))return null;const h=typeof i.row=="string"?i.row:i.row._id;if(!h)return null;const u=we(t,r.name),y=r.sortBy.map((B,K)=>Ee(K)),f=Z(["__partition__",...y]),_=(await m(s,d,e`SELECT ${f} FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${h}`))[0];if(!_)return null;const R=_.__partition__,S=q(i.baseWhere,i.where);tt(S,w,t,"rank");const b=nt(r,S);if(b&&Ce(r.partitionBy??[],b)!==R)return null;const C=xn(d.name,r,y,_,h),F=await m(s,d,e`SELECT COUNT(*) AS c FROM ${e.identifier(u)} WHERE ${e.identifier("__partition__")} = ${R} AND (${C})`),k=await m(s,d,e`SELECT COUNT(*) AS c FROM ${e.identifier(u)} WHERE ${e.identifier("__partition__")} = ${R}`);return{position:Number(F[0]?.c??0)+1,total:Number(k[0]?.c??0)}},async rankPage(t,n,i={}){tt(q(i.baseWhere,i.where),w,t,"rankPage");const o=w.tables[t];if(!o)throw new T("INTERNAL",`unknown table: ${t}`);const r=o.rankIndexes?.find(D=>D.name===n);if(!r)throw new T("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(await U(),!await Me(t,r))return{continueCursor:null,isDone:!0,page:[]};const h=we(t,r.name),u=r.sortBy.map((D,ue)=>Ee(ue)),y=Math.max(1,Math.min(1e3,Math.floor(i.take??100))),f=q(i.baseWhere,i.where),$=nt(r,f),_=Hn(r,u),R=e.join(_.map(D=>e`${e.identifier(D.column)} ${e.raw(`${D.direction==="desc"?"DESC":"ASC"}${Tt(d,{direction:D.direction,nullable:D.nullable})}`)}`),e`, `),S=[];typeof i.partitionKey=="string"?S.push(e`${e.identifier("__partition__")} = ${i.partitionKey}`):$&&S.push(e`${e.identifier("__partition__")} = ${Ce(r.partitionBy??[],$)}`);const b=tn(i);if(b!==void 0){const D=Pn(d.name,_,b);D!==void 0&&S.push(D)}const C=Z([ye,"__partition__",...u]);let F=e`SELECT ${C} FROM ${e.identifier(h)}`;S.length>0&&(F=e`${F} WHERE ${e.join(S,e` AND `)}`),F=e`${F} ORDER BY ${R} LIMIT ${e.raw(String(y+1))}`;const k=await m(s,d,F),B=k.length>y,K=B?k.slice(0,y):k,Ie=K.map(D=>D[ye]),le=await Kn(s,d,o,t,Ie);let be=null;const z=K.at(-1);if(B&&z!==void 0){const D=[z.__partition__,...u.map(ue=>z[ue]),z[ye]];be=jn(D)}return{continueCursor:be,isDone:!B,page:le}},async replace(t,n,i,o){et("replace",n);const r=await re(t,i);if(!r)throw new T("INTERNAL",`document not found: ${t}`);const l=w.tables[r];if(!l)throw new T("INTERNAL",`document not found: ${t}`);const h=await Te(r,t);if(h===void 0)throw new T("INTERNAL",`document not found: ${t}`);const y=en(w,r,"update")||(l.aggregateIndexes??[]).length>0||(l.rankIndexes??[]).length>0?ee(l,h)??void 0:void 0,f=o?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:void 0,$=typeof h._creationTime=="number"?h._creationTime:void 0,_=f??$??N(),R={...n,_creationTime:_,_id:t};ht(l,n,R,ie),Ne(l,R),P(r,"before","update")&&await H("before","update",{doc:{...R},id:t,op:"update",previous:y,table:r}),await Se(r),await ge(r);const S=Object.keys(l.shape),b=e.join([e`${e.identifier("_creationTime")} = ${_}`,...S.map(C=>e`${e.identifier(C)} = ${J(l,C,R[C]??null)}`)],e`, `);await ve(r,"UPDATE",b,h),await ae(r,y,R),await X(r,t,y,R),await de(r,t,R,y),await oe(r,t,"update",R),P(r,"after","update")&&await H("after","update",{doc:R,id:t,op:"update",previous:y,table:r})}};return Ge={db:x,scheduler:Ct},x};export{yi as backfillSqlSearchIndexes,_i as createSqlCtxDb,Ri as decodeGlobalRow,ti as readSqlCdcChangedTables,$i as readSqlCdcChanges,bt as readSqlCdcFloor,zn as runSqlCdcMigration,Pt as runSqlSearchMigrations,Jn as sweepSqlCdcRetention};
@@ -1 +0,0 @@
1
- import{LunoraError as R}from"@lunora/errors";import{aggregateTableName as C,rankTableName as q,sortColumnName as L,renderSql as x,bigintSqlKey as D}from"@lunora/shard-engine";import{sql as n}from"drizzle-orm";import{queryRun as g,queryAll as E,createIndexIfNotExists as h,OCC_VERSION_COLUMN as y,tableColumns as U,columnRefSql as d,queryBatch as M}from"./decodeGlobalRow-D9KXPy-S.mjs";import{e as p,i as k,B as b,r as B,U as P,a as j}from"./value-codec-DC_dHxUY.mjs";const N=(t,i,e=!1)=>i.columnType(p(t),{unique:e||t._meta?.column?.unique===!0}),A=t=>{const i=new Set;for(const e of t.indexes)e.unique===!0&&e.fields.length===1&&i.add(e.fields[0]);return i},F=(t,i,e)=>{if(e.indexKeyPrefix!==void 0)for(const o of i.indexes){if(o.unique!==!0||o.fields.length<=1)continue;const r=o.fields.filter(u=>{const s=i.shape[u];return s!==void 0&&e.indexKeyPrefix?.(p(s))!==void 0});if(r.length>0)throw new Error(`${t}.${o.name}: a composite unique index cannot cover ${r.join(", ")} in full on this engine (its key limit forces a prefix, which would constrain the prefix rather than the value). Split it into single-column unique indexes, or store those fields as a bounded type.`)}},K=(t,i,e)=>{const o=[],r=A(i);for(const[l,f]of Object.entries(i.shape)){if(!f._meta?.column)continue;const c=f._meta.column.notNull&&f.kind!=="optional"?" NOT NULL":"";o.push(n`${n.identifier(l)} ${n.raw(`${N(f,e,r.has(l))}${c}`)}`)}const u=[...e.frameworkColumns().map(l=>n`${n.identifier(l.name)} ${n.raw(l.type)}`),n`${n.identifier(y)} ${n.raw(e.companionTypes.integer)}`],s=u.length+o.length,a=e.maxTableColumns;if(a!==void 0&&s>a){const l=s-1===a,f="Move one or more fields into a single object field, or split the table — either way the existing rows need a data migration (`defineMigration` + `lunora migrate up`); there is no in-place path.";throw new R("VALIDATION_ERROR",`@lunora/sql-store: global table "${t}" needs ${String(s)} columns, over this engine's ${String(a)}-column limit. ${l?`One of them is "${y}", the row version every guarded write reads, which caps declared fields at ${String(a-u.length)}. A table provisioned at ${String(a)} columns before that column existed cannot be widened to hold it. `:""}${f}`)}return n.join([...u,...o],n`, `)},Y=t=>{if(t.indexKeyPrefix?.("string")===void 0)return n`${d("_creationTime")}, ${d("id")}`},G=async(t,i,e)=>{if(i.name!=="sqlite")return;const r=(await E(t,i,n`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${e.name} AND tbl_name = ${e.table}`))[0]?.sql;if(typeof r!="string")return;const u=l=>{const f=l.indexOf("(");return f===-1?void 0:l.slice(f,l.lastIndexOf(")")+1)},s=e.unique?n`UNIQUE `:n``,a=u(x(i.name,n`CREATE ${s}INDEX ${n.identifier(e.name)} ON ${n.identifier(e.table)} (${e.columns})`).sql);if(!(a===void 0||a===u(r))){if(e.unique){const l=n.join(e.refs.map(c=>n`${c} IS NOT NULL`),n` AND `);if((await E(t,i,n`SELECT ${e.columns} FROM ${n.identifier(e.table)} WHERE ${l} GROUP BY ${e.columns} HAVING COUNT(*) > 1 LIMIT 1`)).length>0)throw new R("INTERNAL",`unique index "${e.name}" on "${e.table}" cannot be re-created with its new column list: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)}await g(t,i,n`DROP INDEX IF EXISTS ${n.identifier(e.name)}`)}},H=async(t,i,e,o)=>{F(i,e,o);const r=A(e),u=a=>{const l=d(a),f=e.shape[a],c=f&&o.indexKeyPrefix&&f._meta?.column?.unique!==!0&&!r.has(a)?o.indexKeyPrefix(p(f)):void 0;return c===void 0?l:n`${l}(${n.raw(String(c))})`},s=Y(o);for(const a of e.indexes){const l=a.fields.map($=>u($)),f=n.join(l,n`, `),c=a.unique??!1,m={columns:c||s===void 0?f:n`${f}, ${s}`,name:`${i}_${a.name}`,refs:l,table:i,unique:c};await G(t,o,m),await h(t,o,m)}s!==void 0&&await h(t,o,{columns:s,name:`${i}__by_creation`,table:i,unique:!1});for(const[a,l]of U(e))l.unique&&await h(t,o,{columns:u(a),name:`${i}_unique_${a}`,table:i,unique:!0})},_="__lunora_migration_state",V=async(t,i)=>{await g(t,i,n`CREATE TABLE IF NOT EXISTS ${n.identifier(_)} (${n.identifier("name")} ${n.raw(i.companionTypes.key)} PRIMARY KEY)`)},X=async(t,i,e)=>(await E(t,i,n`SELECT ${n.identifier("name")} FROM ${n.identifier(_)} WHERE ${n.identifier("name")} = ${e}`)).length>0,W=async(t,i,e,o,r,u)=>{r>0&&u!==void 0&&console.warn(`[@lunora/sql-store] storage migration "${e}" on "${o}": ${String(r)} row(s) ${u} and were left as stored — range filters and ORDER BY over them stay wrong until they are corrected by hand.`);try{await g(t,i,n`INSERT INTO ${n.identifier(_)} (${n.identifier("name")}) VALUES (${e})`)}catch(s){if(!i.isUniqueViolation(s))throw s}},Q=100,z=(t,i)=>{const e=[],o=[];for(const r of i.fields){const u=t[r],s=i.convert(u);s!==void 0&&(e.push(n`${d(r)} = ${s}`),o.push(n`${d(r)} = ${u}`))}return{assignments:e,guards:o}},S=async(t,i,e,o)=>{if(o.fields.length===0||(await V(t,e),await X(t,e,o.marker)))return;const r=n.join(o.fields.map(l=>o.probe(l)),n` OR `),u=n.join([d("id"),...o.fields.map(l=>d(l))],n`, `);let s="",a=0;for(;;){const l=await E(t,e,n`SELECT ${u} FROM ${n.identifier(i)} WHERE (${r}) AND ${d("id")} > ${s} ORDER BY ${d("id")} LIMIT ${n.raw(String(Q))}`);if(l.length===0){await W(t,e,o.marker,i,a,o.describeUnconvertible);return}const f=[];for(const m of l){const{id:$}=m,{assignments:T,guards:v}=typeof $=="string"?z(m,o):{assignments:[],guards:[]};if(T.length===0){a+=1;continue}f.push(n`UPDATE ${n.identifier(i)} SET ${n.join(T,n`, `)} WHERE ${d("id")} = ${$} AND ${n.join(v,n` AND `)}`)}await M(t,e,f);const c=l.at(-1)?.id;if(typeof c!="string")return;s=c}},I=t=>`'${t}%'`,J=t=>Object.entries(t.shape).filter(([,i])=>i._meta?.column!==void 0&&p(i)==="bigint").map(([i])=>i),Z=t=>Object.entries(t.shape).filter(([,i])=>i._meta?.column!==void 0&&k(p(i))).map(([i])=>i),nn=async(t,i,e,o)=>S(t,i,o,{convert:r=>{if(!(typeof r!="string"||r.length===b))try{return D(BigInt(r))}catch{return}},describeUnconvertible:"hold a value the order-preserving key cannot represent (non-numeric text, or a magnitude past 39 digits)",fields:J(e),marker:`bigint-key:${i}`,probe:r=>n`(${d(r)} IS NOT NULL AND LENGTH(${d(r)}) <> ${b})`}),en=async(t,i,e,o)=>S(t,i,o,{convert:B,fields:Z(e),marker:`untyped-number-key:${i}`,probe:r=>n`(${d(r)} LIKE ${n.raw(I(P))} AND ${d(r)} NOT LIKE ${n.raw(I(j))})`}),tn=async(t,i,e,o)=>{const r=[[y,o.companionTypes.integer],...Object.entries(e.shape).filter(([,s])=>s._meta?.column!==void 0).map(([s,a])=>[s,N(a,o)])],u=async s=>{try{return await E(t,o,n`SELECT ${n.join(s.map(a=>d(a)),n`, `)} FROM ${n.identifier(i)} LIMIT 0`),!0}catch{return!1}};if(!await u(r.map(([s])=>s)))for(const[s,a]of r)await u([s])||await g(t,o,n`ALTER TABLE ${n.identifier(i)} ADD COLUMN ${n.identifier(s)} ${n.raw(a)}`)},cn=async(t,i,e)=>{for(const[o,r]of Object.entries(i.tables)){if(r.shardMode?.kind!=="global")continue;const u=K(o,r,e);await g(t,e,n`CREATE TABLE IF NOT EXISTS ${n.identifier(o)} (${u})`),await tn(t,o,r,e),await H(t,o,r,e),await nn(t,o,r,e),await en(t,o,r,e)}},O=t=>t.shardMode===void 0||t.shardMode.kind==="global",dn=async(t,i,e)=>{const{integer:o,key:r,real:u}=e.companionTypes;for(const[s,a]of Object.entries(i.tables)){const l=a.aggregateIndexes;if(!(!l||l.length===0||!O(a)))for(const f of l){const c=C(s,f.name);await g(t,e,n`CREATE TABLE IF NOT EXISTS ${n.identifier(c)} (${n.identifier("__key__")} ${n.raw(r)} PRIMARY KEY, ${n.identifier("__value__")} ${n.raw(u)}, ${n.identifier("__count__")} ${n.raw(o)} NOT NULL DEFAULT 0)`),e.name==="sqlite"&&((await E(t,e,n`PRAGMA table_info(${n.identifier(c)})`)).some($=>$.name==="__count__")||await g(t,e,n`ALTER TABLE ${n.identifier(c)} ADD COLUMN ${n.identifier("__count__")} ${n.raw(o)} NOT NULL DEFAULT 0`))}}},w=(t,i,e,o)=>{const r=t.name==="mysql"&&o?n`${n.identifier(i)}(191)`:n`${n.identifier(i)}`;return n`${r} ${n.raw(e)}`},on=(t,i,e)=>{const o=[w(t,"__partition__","ASC",!0)];for(const[r,u]of i.sortBy.entries()){const s=e.shape[u.field],a=s!==void 0&&t.indexKeyPrefix?.(p(s))!==void 0;o.push(w(t,L(r),u.direction==="desc"?"DESC":"ASC",a))}return o.push(w(t,"__id__","ASC",!0)),o},rn=(t,i,e)=>i.sortBy.map((o,r)=>{const u=e.shape[o.field],s=t.columnType(u?p(u):void 0);return n`${n.identifier(L(r))} ${n.raw(s)}`}),mn=async(t,i,e)=>{const{key:o}=e.companionTypes;for(const[r,u]of Object.entries(i.tables)){const s=u.rankIndexes;if(!(!s||s.length===0||!O(u)))for(const a of s){const l=q(r,a.name),f=rn(e,a,u),c=f.length>0?n`, ${n.join(f,n`, `)}`:n``;await g(t,e,n`CREATE TABLE IF NOT EXISTS ${n.identifier(l)} (${n.identifier("__id__")} ${n.raw(o)} PRIMARY KEY, ${n.identifier("__partition__")} ${n.raw(o)} NOT NULL${c})`);const m=on(e,a,u),$=`${r}__rank_${a.name}__btree`;await h(t,e,{columns:n.join(m,n`, `),name:$,table:l,unique:!1})}}};export{dn as runSqlAggregateMigrations,cn as runSqlGlobalTableMigrations,mn as runSqlRankMigrations};