@lunora/sql-store 1.0.0-alpha.21 → 1.0.0-alpha.210

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.
@@ -0,0 +1,7 @@
1
+ import{LunoraError as g}from"@lunora/errors";import{m as rn,D as sn}from"./ctx-db-search-state-DRiojLLm.mjs";import{c as an,r as cn,A as dn,C as ln,R as un,u as fn,a as wn,T as hn,x as $n,b as _n}from"./ctx-db-search-DB_ejfgj.mjs";import{throwingScheduler as En,describeRelationWrites as pn,CDC_LOG_TABLE as H,cdcForkedError as yn,cursorBelowRetainedFloor as Rn,cdcTrimmedError as Sn,serverInList as gn,assertNoExplicitUndefined as We,hasTrigger as vn,runRowValidators as Fe,assertFlatPredicate as dt,mergeWhere as B,rankTableName as $e,sortColumnName as pe,resolveRankPartition as lt,encodePartitionKey as Le,resolveRankSeekTuple as Tn,RANK_TIEBREAK as ye,CountRlsUnsupportedError as ut,compileWhereSql as z,ConflictError as se,patchDependsOnRow as mn,normalizeIdStructurally as In,applyInsertDefaults as An,assertValidClientId as bn,assertStorableRowId as Cn,aggregateSqlFunction as _e,softDeleteScope as Me,resolveWith as ft,relationHooks as wt,applySelect as ht,encodeCursor as Ln,NotFoundError as Mn,applyOnDelete as Nn,normalizeCountArgument as qn,selectIndexForCount as kn,encodeAggregateKey as J,aggregateTableName as ie,selectIndexForAggregate as Dn,readAggregateValue as Ue,runTriggers as On,matchesRankStaticWhere as $t,nullsOrderSuffix as _t,nullsFirstOf as Et,rankPivotConditionSql as kt,CURSOR_PREFIX as Bn,resolvePatch as Wn,stripReservedPatchFields as Fn,assertPatchAllowed as Un,resolveRelationPredicates as xn,selectIndexForGroupBy as Pn,composeReadPredicate as Hn,fanOutScalarCounts as Kn,matchesStaticWhere as xe,foldAggregateTally as pt,coerceAggregateNumber as Pe,whereOfFilter as jn,isPushableWhere as Gn,tiebreakDirectionFor as Vn,CDC_LOG_TABLE_SEQ_INDEX as Yn,NotUniqueError as Xn,WORKERD_SQLITE_LIMITS as Qn}from"@lunora/shard-engine";import{decodeWire as Dt,needsWireEncoding as Ot,encodeWire as Bt}from"@lunora/wire";import{sql as e,SQL as zn}from"drizzle-orm";import{p as yt,m as Rt,q as b,a as V,c as Jn,o as Zn,f as Y,s as oe,O as Ee,b as U,h as St,t as ei,r as ti,j as He,u as gt,l as vt,B as Ke,v as Ne,n as Je,e as Tt,w as mt,x as It,y as ni}from"./sql-exec-UH-aJj2C.mjs";import{z as to}from"./sql-exec-UH-aJj2C.mjs";import{runSqlGlobalTableMigrations as ii}from"./runSqlGlobalTableMigrations-qVa5Q8BM.mjs";import{runSqlAggregateMigrations as oi,runSqlRankMigrations as ri}from"./runSqlAggregateMigrations-BqfzHcG8.mjs";import{c as Wt,a as Ft}from"./value-codec-CiS1h_97.mjs";const si=(o,c)=>{if(o.size<c)return;const h=o.keys().next().value;h!==void 0&&o.delete(h)},At=50,ai=(o,c={})=>{const h=c.maxBatch??At,a=Number.isInteger(h)&&h>0?h:At,R=new Map;let f=!1;const l=async(I,m)=>{const T=[...m.keys()];for(let C=0;C<T.length;C+=a){const M=T.slice(C,C+a);try{const D=await o(I,M);for(const K of M){const X=D.get(K);for(const Z of m.get(K)??[])Z.resolve(X)}}catch(D){for(const K of M)for(const X of m.get(K)??[])X.reject(D)}}},q=()=>{f=!1;const I=[...R.entries()];R.clear();for(const[m,T]of I)l(m,T).catch(()=>{})};return{async load(I,m){return new Promise((T,C)=>{let M=R.get(I);M||(M=new Map,R.set(I,M));const D=M.get(m);D?D.push({reject:C,resolve:T}):M.set(m,[{reject:C,resolve:T}]),f||(f=!0,queueMicrotask(q))})}}},ci=new Set(["_id","id"]),di=o=>{throw new g("INTERNAL",`no ORDER BY NULL placement for dialect "${String(o)}"`)},Ut=(o,c)=>{const h=c.direction==="desc"?"DESC":"ASC",a=c.nullable===!0,R=f=>e`${Ne(o,c.field)} ${e.raw(`${h}${f}`)}`;switch(o.name){case"mysql":{const f=R("");return!a||c.nulls===void 0?[f]:[e`(${Ne(o,c.field)} IS NULL) ${e.raw(c.nulls==="first"?"DESC":"ASC")}`,f]}case"postgres":return[R(a?_t(Et(c)):"")];case"sqlite":return[R(a&&c.nulls!==void 0?_t(Et(c)):"")];default:return di(o.name)}},li=(o,c)=>{const h=o.flatMap(a=>Ut(c,a));if(!o.some(a=>ci.has(a.field))){const a=Vn(o);h.push(e`${U("id")} ${e.raw(a==="desc"?"DESC":"ASC")}`)}return e.join(h,e`, `)},bt=50,ui=o=>{const c=o.detail??o["QUERY PLAN"];return typeof c=="string"?c:Object.values(o).map(String).join(" | ")},je=(o,c,h,a)=>{for(const[R,f]of ei(o)){if(f.serverDefault){R in c&&(h[R]=f.serverDefault({auth:a}));continue}f.onUpdateFn&&!(R in c)&&(h[R]=f.onUpdateFn())}},fi=128,wi=()=>{const o=new Map;return{delete:c=>{o.delete(c)},get:c=>{const h=o.get(c);if(h!==void 0)return o.delete(c),o.set(c,h),h},set:(c,h)=>{o.has(c)?o.delete(c):si(o,fi),o.set(c,h)}}},Xe=o=>`u${o}`,xt=(o,c)=>`p${o}\0${c}`,hi=async(o,c,h,a,R,f)=>{const l=f===void 0?Xe(a):xt(f,a),q=R.get(l);if(q!==void 0)return q;const I=Object.entries(h.tables).filter(([,T])=>T.shardMode===void 0||T.shardMode.kind==="global").map(([T])=>T).filter(T=>f===void 0||T===f),m=await Promise.all(I.map(async T=>({found:(await b(o,c,e`SELECT 1 FROM ${e.identifier(T)} WHERE ${e.identifier("id")} = ${a} LIMIT 1`)).length>0,tableName:T})));for(const T of m)if(T.found)return R.set(l,T.tableName),T.tableName},ae=o=>o==null?null:Number(o),$i=(o,c,h)=>h.map(a=>{const R={};for(const f of c){const l=o.shape[f];R[f]=Wt(a[f]??null,l&&Ft(l))}return{key:R,value:ae(a.value)}}),_i=(o,c,h)=>[...o.partitionBy??[],...o.sortBy.map(R=>R.field),...o.where?Object.keys(o.where):[]].every(R=>mt(c,R)===mt(h,R)),Pt=o=>o.length===1?o[0]:e`(${e.join(o,e` AND `)})`,re=o=>e.join(o.map(c=>e`${e.identifier(c)}`),e`, `),ce=o=>e.join(o.map(c=>e`${c}`),e`, `),Ge=(o,c)=>{if(o==="postgres"){for(const[h,a]of Object.entries(c))if(typeof a=="string"&&a.includes("\0"))throw new g("BAD_REQUEST",`"${h}" holds a NUL character (U+0000), which a Postgres text column cannot store`)}},qe=o=>o instanceof ArrayBuffer?new Uint8Array(o):Array.isArray(o)?Uint8Array.from(o):o,Ei=(o,c,h,a,R)=>{const f=[];for(let l=0;l<h.length+1;l+=1){const q=h[l],I=c.sortBy[l],m=l<h.length&&q!==void 0&&I!==void 0,T=I?.direction==="desc"?"desc":"asc",C=m?kt(q,qe(a[q]),T,!1):e`${e.identifier(ye)} < ${R}`;if(C===void 0)continue;const M=h.slice(0,l).map(D=>Je(o,e`${e.identifier(D)}`,qe(a[D])));M.push(C),f.push(Pt(M))}return f.length>0?e.join(f,e` OR `):e`1 = 0`},pi=(o,c,h)=>{if(h.length!==c.length)return;const a=[];for(const[R,f]of c.entries()){const l=kt(f.column,qe(h[R]),f.direction,!0);if(l===void 0)continue;const q=[];for(let I=0;I<R;I+=1){const m=c[I];m!==void 0&&q.push(Je(o,e`${e.identifier(m.column)}`,qe(h[I])))}q.push(l),a.push(Pt(q))}return a.length===0?e`(1 = 0)`:e`(${e.join(a,e` OR `)})`},yi=(o,c)=>{if(o.sortBy.length===0)throw new g("INTERNAL",`rankIndex "${o.name}" requires at least one "sortBy" column for stable pagination`);const h=[{column:"__partition__",direction:"asc",nullable:!1}];for(const[a,R]of o.sortBy.entries())h.push({column:c[a]??pe(a),direction:R.direction,nullable:!0});return h.push({column:ye,direction:"asc",nullable:!1}),h},Ri=async(o,c,h,a,R)=>{const l=[];for(let T=0;T<R.length;T+=50)l.push(R.slice(T,T+50));const q=await Promise.all(l.map(async T=>b(o,c,e`SELECT * FROM ${e.identifier(a)} WHERE ${e.identifier("id")} IN (${ce(T)})`))),I=new Map;for(const T of q)for(const C of T)I.set(C.id,C);const m=[];for(const T of R){const C=Y(h,I.get(T));C&&m.push(C)}return m},Si=o=>{const c=o.map(f=>Wt(f,"bytes")),h=JSON.stringify(Ot(c)?Bt(c):c),a=new TextEncoder().encode(h);let R="";for(const f of a)R+=String.fromCodePoint(f);return Bn+btoa(R)},Ht=o=>{if(o===void 0)return!1;const c=Ft(o);return c==="any"||c==="bigint"||c==="from"||c==="union"},Qe=(o,c,h)=>{if(Ht(o.shape[c]))throw new g("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)`)},gi=(o,c,h,a)=>{for(const R of h)Qe(o,R,`groupBy(${c}, { by: [..."${R}"] })`);a.field!==void 0&&Qe(o,a.field,`groupBy(${c}, { agg: { op: "${a.op}", field: "${a.field}" } })`)},ze="__cdc_sweep",Kt="global",vi=6e4,Ti=1e4,mi=3e4;let Ct=0;const Ii=async(o,c)=>{const{autoincrementPrimaryKey:h,key:a,real:R,text:f}=c.companionTypes;await V(o,c,e`CREATE TABLE IF NOT EXISTS ${e.identifier(H)} (${e.identifier("seq")} ${e.raw(h)}, ${e.identifier("ts")} ${e.raw(R)} NOT NULL, ${e.identifier("table")} ${e.raw(a)} NOT NULL, ${e.identifier("id")} ${e.raw(a)} NOT NULL, ${e.identifier("op")} ${e.raw(a)} NOT NULL, ${e.identifier("doc")} ${e.raw(f)})`);const l=c.indexKeyPrefix?.("string");await Jn(o,c,{columns:e`${l===void 0?e`${e.identifier("table")}`:e`${e.identifier("table")}(${e.raw(String(l))})`}, ${e.identifier("seq")}`,name:Yn,table:H,unique:!1}),await V(o,c,e`CREATE TABLE IF NOT EXISTS ${e.identifier(ze)} (${e.identifier("id")} ${e.raw(a)} NOT NULL PRIMARY KEY, ${e.identifier("lease_until")} ${e.raw(R)} NOT NULL)`),await V(o,c,e`INSERT INTO ${e.identifier(ze)} (${e.identifier("id")}, ${e.identifier("lease_until")}) VALUES (${Kt}, ${0}) ${c.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${e.identifier("id")} = ${e.identifier("id")}`:e`ON CONFLICT(${e.identifier("id")}) DO NOTHING`}`)},Ai=async(o,c,h)=>{const a=e`UPDATE ${e.identifier(ze)} SET ${e.identifier("lease_until")} = ${h+vi} WHERE ${e.identifier("id")} = ${Kt} AND ${e.identifier("lease_until")} <= ${h}`;if(c.supportsReturning)return(await b(o,c,e`${a} RETURNING ${e.identifier("id")}`)).length>0;const R=await V(o,c,a);return(c.affectedRows?c.affectedRows(R??{rowsAffected:0}):0)>0},bi=async(o,c,h,a)=>{if(!await Ai(o,c,a))return;const R=a-h;await V(o,c,e`
2
+ DELETE FROM ${e.identifier(H)} WHERE ${e.identifier("seq")} IN (
3
+ SELECT ${e.identifier("seq")} FROM (
4
+ SELECT ${e.identifier("seq")} FROM ${e.identifier(H)} WHERE ${e.identifier("ts")} <= ${R} ORDER BY ${e.identifier("seq")} ASC LIMIT ${e.raw(String(Ti))}
5
+ ) AS ${e.identifier("expired")}
6
+ )
7
+ `)},jt=async(o,c)=>{const h=await b(o,c,e`SELECT MIN(${e.identifier("seq")}) AS ${e.identifier("seq")} FROM ${e.identifier(H)}`),a=Number(h[0]?.seq??Number.NaN);return Number.isFinite(a)?a:void 0},Ci=async(o,c)=>{if(c.name!=="sqlite")return;const h=await b(o,c,e`SELECT ${e.identifier("seq")} AS ${e.identifier("seq")} FROM ${e.identifier("sqlite_sequence")} WHERE ${e.identifier("name")} = ${H}`),a=Number(h[0]?.seq??Number.NaN);return Number.isFinite(a)?a:0},Li=o=>JSON.stringify(Ot(o)?Bt(o):o),Mi=(o,c,h,a,R)=>e`INSERT INTO ${e.identifier(H)} (${e.identifier("ts")}, ${e.identifier("table")}, ${e.identifier("id")}, ${e.identifier("op")}, ${e.identifier("doc")}) VALUES (${o}, ${c}, ${h}, ${a}, ${R===void 0?null:Li(R)})`,zi=async(o,c,h)=>{const a=c.sinceSeq??0,R=Math.max(1,Math.min(c.limit??1e3,1e4)),f=await jt(o,h),l=await Ci(o,h);if(l!==void 0&&a>l)throw yn(l,a,"global");if(f!==void 0&&Rn(f,a))throw Sn(f,a,"global");const I=(await b(o,h,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(H)} WHERE seq > ${a} ORDER BY seq ASC LIMIT ${e.raw(String(R))}`)).map(m=>{const{doc:T}=m,C={id:String(m.id),op:String(m.op),seq:Number(m.seq),table:String(m.table),ts:Number(m.ts)};return typeof T=="string"?{...C,doc:Dt(JSON.parse(T))}:C});return{changes:I,cursor:I.at(-1)?.seq??a}},Ni=1e4,qi=1e3,Lt=(o,c)=>{const h=e.identifier(H),a=e`(SELECT MIN(v.seq) FROM ${h} v WHERE v.seq > ${o} AND v.seq - 1 > ${o} AND v.ts > ${c} AND NOT EXISTS (SELECT 1 FROM ${h} p WHERE p.seq = v.seq - 1))`;return e`${a} AS ${e.identifier("gap")}, (SELECT MAX(q.seq) FROM ${h} q WHERE q.seq > ${o} AND q.seq < ${a}) AS ${e.identifier("below")}`},Mt=(o,c,h)=>{const a=Number(c?.gap??Number.NaN);if(!Number.isFinite(a))return o;const R=Number(c?.below??Number.NaN);return Math.min(o,Number.isFinite(R)?R:h)},ki=async(o,c,h,a={})=>{const R=e.identifier(H),f=h.name!=="sqlite",l=(a.now??Date.now())-Ni;if(a.cursorOnly){const C=e`GREATEST((SELECT MAX(seq) FROM ${R}) - ${e.raw(String(qi))}, ${c})`,M=await b(o,h,e`SELECT MAX(seq) AS seq${f?e`, ${Lt(C,l)}`:e``} FROM ${R}`),D=Number(M[0]?.seq??c);return{cursor:Mt(Number.isFinite(D)?D:c,M[0],c),tables:[]}}const q=await b(o,h,e`SELECT ${e.identifier("table")} AS ${e.identifier("table")}, MAX(seq) AS seq${f?e`, ${Lt(e`${c}`,l)}`:e``} FROM ${R} WHERE seq > ${c} GROUP BY ${e.identifier("table")}`);let I=c;const m=[];for(const C of q){const M=Number(C.seq);Number.isFinite(M)&&M>I&&(I=M),m.push(String(C.table))}I=Mt(I,q[0],c);const T=a.retained===!0?await jt(o,h):void 0;return{cursor:I,tables:m,...T===void 0?{}:{floor:T}}},Di=/string or blob too big/iu,Oi=/row is too big/iu,Bi=(o,c)=>{const{code:h,errno:a}=c,R=c instanceof Error?c.message:"";switch(o.name){case"mysql":return a===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 Oi.test(R)?"the 8 KB heap page a tuple must fit once its wide columns have been TOASTed out":void 0;default:return Di.test(R)?"the storage engine's per-row ceiling (2 MB on D1)":void 0}},Wi=(o,c,h)=>{const a=Bi(o,c);if(a!==void 0)throw new g("PAYLOAD_TOO_LARGE",`document is too large to store in "${h}": a single row cannot exceed ${a}. 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.`)},Ve=16,Nt="__lunora_patch_if_match__",qt=(o,c,h)=>{throw o.isUniqueViolation(c)?new se(`unique constraint violation on "${h}"`,"unique"):(Wi(o,c,h),c)},Ye=new WeakMap,Fi=o=>{const c=gn(o);return(h,a,R,f)=>a.some(l=>l instanceof zn)?Zn(o,h,a,R):c(h,a,R,f)},Ji=o=>{const{crossShardCounter:c,crossShardReader:h,exec:a,maxRelationKeys:R,schema:f}=o,{dialect:l}=o,q={fieldRef:t=>Ne(l,t),rangeTypeGuard:(t,n)=>ni(l,t,n),...l.name==="mysql"?{containsExpr:(t,n)=>{const i=yt(t);return i===void 0?e`LOCATE(${n}, ${t}) > 0`:e`LOCATE(${Rt("mysql",n)}, ${i}) > 0`}}:{},...l.name==="postgres"?{containsExpr:(t,n)=>{const i=yt(t);return i===void 0?e`strpos(${t}, ${n}) > 0`:e`strpos(${i}, ${Rt("postgres",n)}) > 0`}}:{},...l.name==="sqlite"?{}:{inList:Fi(l.name)}},I=new WeakMap,m=t=>{const n=I.get(t);if(n!==void 0)return n;const i={...q,serialize:(s,r)=>It(l,r,s,d=>oe(t,r,d))};return I.set(t,i),i},T=(t,n)=>Je(l.name,t,n),C=t=>{const n=re(t.columns),i=ce(t.values),s=_=>l.name==="mysql"?e`VALUES(${e.identifier(_)})`:e`excluded.${e.identifier(_)}`,r=_=>l.name==="postgres"?e`${e.identifier(t.table)}.${e.identifier(_)}`:e`${e.identifier(_)}`,d=e.join(Object.entries(t.set(s,r)).map(([_,p])=>e`${e.identifier(_)} = ${p}`),e`, `),$=l.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${d}`:e`ON CONFLICT(${e.identifier(t.conflictKey)}) DO UPDATE SET ${d}`;return e`INSERT INTO ${e.identifier(t.table)} (${n}) VALUES (${i}) ${$}`},M=o.clock??(()=>Date.now()),D=o.idGenerator??(()=>crypto.randomUUID()),K=o.cdc??!1,X=typeof o.cdcRetentionMs=="number"&&Number.isFinite(o.cdcRetentionMs)&&o.cdcRetentionMs>0?o.cdcRetentionMs:void 0,Z=o.auth??{identity:null,userId:null},de=(t,n,i,s)=>K?[Mi(M(),t,n,i,s)]:[],Gt=async()=>{if(!K||X===void 0)return;const t=M();if(!(t-Ct<mi)){Ct=t;try{await bi(a,l,X,t)}catch{}}},Vt=o.scheduler??En,Re=wi(),Yt=Object.entries(f.tables).filter(([,t])=>t.shardMode===void 0||t.shardMode.kind==="global").map(([t])=>t);let Se=0;const ke=o.provisionScope??{},W=async()=>{const t=Ye.get(ke);if(t)return t;const n=(async()=>{await ii(a,f,l),await oi(a,f,l),await ri(a,f,l),await rn(a,l),await cn(a,f,l),K&&await Ii(a,l)})().catch(i=>{throw Ye.delete(ke),i});return Ye.set(ke,n),n},ge=async(t,n)=>{await W();const i=await hi(a,l,f,t,Re,n);if(!(n!==void 0&&i!==n))return i},le=new Map,Ze=async(t,n)=>{const i=ie(t,n);return(await b(a,l,l.tableExists(i))).length>0},ve=async(t,n)=>{const i=`${t}::${n.name}`,s=le.get(i);if(s!==void 0)return s;if(!await Ze(t,n.name))return le.set(i,!1),!1;const d=f.tables[t];if(!d)return le.set(i,!1),!1;const $=n.by??[],_=new Map;await vt(a,l,d,t,w=>{if(n.where&&!xe(w,n.where))return;const u=J($,w);pt(_,u,n,w)});const p=ie(t,n.name);await V(a,l,e`DELETE FROM ${e.identifier(p)}`);const E=[];for(const[w,u]of _)E.push(e`INSERT INTO ${e.identifier(p)} (${e.identifier("__key__")}, ${e.identifier("__value__")}, ${e.identifier("__count__")}) VALUES (${w}, ${u.value}, ${u.count})`);return await Tt(a,l,E),le.set(i,!0),!0},Xt=async(t,n,i,s)=>{const r=new Map;let d,$=!0;for(;$;){const _=d===void 0?s:[...s,e`${e.identifier("id")} > ${d}`],p=_.length>0?e` WHERE ${e.join(_,e` AND `)}`:e``,E=await b(a,l,e`SELECT ${e.identifier("id")}, ${U(i.field??"")} FROM ${e.identifier(n)}${p} ORDER BY ${e.identifier("id")} ASC LIMIT ${e.raw(String(Ke))}`);for(const w of St(t,E))pt(r,"",i,w);d=E.at(-1)?.id,$=E.length===Ke}return r.get("")?.value??null},Qt=async(t,n,i)=>{const s=n.field??"",r=[],d=f.tables[t],$=(w,u)=>It(l,w,u,S=>d?oe(d,w,S):He(S));for(const w of n.by??[]){const u=$(w,i[w]??null);r.push(u===null?e`${U(w)} IS NULL`:e`${U(w)} = ${u}`)}for(const[w,u]of Object.entries(n.where??{})){const S=u!==null&&typeof u=="object"&&!Array.isArray(u)?u.eq:u,y=$(w,S),v=Ne(l,w);r.push(y===null?e`${v} IS NULL`:e`${v} = ${y}`)}const _=r.length>0?e` WHERE ${e.join(r,e` AND `)}`:e``;if(d&&Ht(d.shape[s]))return Xt(d,t,n,r);const p=_e(n.op),E=await b(a,l,e`SELECT ${e.raw(p)}(${U(s)}) AS ${e.identifier("value")} FROM ${e.identifier(t)}${_}`);return ae(E[0]?.value)},zt=(t,n)=>e`DELETE FROM ${e.identifier(t)} WHERE ${e.identifier("__key__")} = ${n} AND ${e.identifier("__count__")} <= 0`,Jt=async(t,n,i,s)=>{const r=ie(t,n.name),{op:d}=n,$=n.field??"",_=i&&(!n.where||xe(i,n.where))?i:void 0,p=s&&(!n.where||xe(s,n.where))?s:void 0;if(!_&&!p)return[];if(d==="count"||d==="sum"||d==="avg"){const w=[],u=new Set;for(const[S,y]of[[_,-1],[p,1]]){if(!S)continue;const v=d==="count"?1:Pe(S[$]);if(v===void 0)continue;const L=J(n.by??[],S);u.add(L),w.push(C({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(A,N)=>({__count__:e`${N("__count__")} + ${A("__count__")}`,__value__:d==="count"?e`${N("__value__")} + ${A("__value__")}`:e`COALESCE(${N("__value__")}, 0) + ${A("__value__")}`}),table:r,values:[L,y*v,y]}))}for(const S of u)w.push(zt(r,S));return w}const E=[];if(_){const w=J(n.by??[],_),u=Pe(_[$]),y=(await b(a,l,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(r)} WHERE ${e.identifier("__key__")} = ${w}`))[0],v=ae(y?.value),L=(y?.count??0)-1;if(L<=0)E.push(e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__key__")} = ${w}`);else if(y&&u!==void 0&&v!==null&&u===v){const A=await Qt(t,n,_);E.push(e`UPDATE ${e.identifier(r)} SET ${e.identifier("__value__")} = ${A}, ${e.identifier("__count__")} = ${L} WHERE ${e.identifier("__key__")} = ${w}`)}else E.push(e`UPDATE ${e.identifier(r)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${w}`)}if(p){const w=J(n.by??[],p),u=Pe(p[$]);if(u===void 0)E.push(C({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(S,y)=>({__count__:e`${y("__count__")} + 1`}),table:r,values:[w,null,1]}));else{const S=d==="min"?"MIN":"MAX";E.push(C({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(y,v)=>({__count__:e`${v("__count__")} + 1`,__value__:e`${e.raw(S)}(COALESCE(${v("__value__")}, ${y("__value__")}), ${y("__value__")})`}),table:r,values:[w,u,1]}))}}return E},Te=async t=>{const n=f.tables[t]?.aggregateIndexes;if(!(!n||n.length===0))for(const i of n)await ve(t,i)},ue=async(t,n,i)=>{const s=f.tables[t]?.aggregateIndexes,r=[];if(!s||s.length===0)return r;for(const d of s){const $=`${t}::${d.name}`;(le.get($)??await Ze(t,d.name))&&r.push(...await Jt(t,d,n,i))}return r},fe=new Map,et=async(t,n)=>{const i=$e(t,n);return(await b(a,l,l.tableExists(i))).length>0},De=async(t,n)=>{const i=`${t}::rank::${n.name}`,s=fe.get(i);if(s!==void 0)return s;if(!await et(t,n.name))return fe.set(i,!1),!1;const d=f.tables[t];if(!d)return fe.set(i,!1),!1;const $=$e(t,n.name);await V(a,l,e`DELETE FROM ${e.identifier($)}`);const _=n.sortBy.map((u,S)=>pe(S)),p=re(["__id__","__partition__",..._]);let E=[];const w=async()=>{if(E.length===0)return;const u=E;E=[],await Tt(a,l,u)};return await vt(a,l,d,t,async u=>{if(n.where&&!$t(u,n.where))return;const S=Le(n.partitionBy??[],u),y=n.sortBy.map(v=>He(u[v.field]??null));E.push(e`INSERT INTO ${e.identifier($)} (${p}) VALUES (${ce([u._id,S,...y])})`),E.length>=Ke&&await w()}),await w(),fe.set(i,!0),!0},me=async t=>{const n=f.tables[t]?.rankIndexes;if(!(!n||n.length===0))for(const i of n)await De(t,i)},ee=async(t,n,i,s)=>{const r=f.tables[t],d=r?.rankIndexes,$=[];if(!d||d.length===0)return $;const _=r?.softDeleteMode?.field,p=_===void 0||s===void 0?void 0:s[_],E=p!=null;for(const w of d){if(i!==void 0&&s!==void 0&&_i(w,i,s))continue;const u=`${t}::rank::${w.name}`;if(!(fe.get(u)??await et(t,w.name)))continue;const v=$e(t,w.name);if(i&&$.push(e`DELETE FROM ${e.identifier(v)} WHERE ${e.identifier("__id__")} = ${n}`),s&&!E){if(w.where&&!$t(s,w.where))continue;const L=w.sortBy.map((F,Q)=>pe(Q)),A=re(["__id__","__partition__",...L]),N=Le(w.partitionBy??[],s),O=w.sortBy.map(F=>He(s[F.field]??null));$.push(e`INSERT INTO ${e.identifier(v)} (${A}) VALUES (${ce([n,N,...O])})`)}}return $},te=async t=>{t.length>0&&await ti(a,l,t),await Gt()},we=an({dialect:l,exec:a,schema:f}),tt=new Set;for(const[t,n]of Object.entries(f.tables))for(const i of Object.values(n.triggerMap??{}))tt.add(`${t} ${i.timing} ${i.op}`);const j=(t,n,i)=>tt.has(`${t} ${n} ${i}`);let nt;const G=async(t,n,i)=>{if(Se+=1,Se>bt)throw Se-=1,new se(`trigger recursion exceeded ${String(bt)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await On({ctx:nt,event:i,op:n,schema:f,tableName:i.table,timing:t})}finally{Se-=1}},Zt=async(t,n)=>{try{await V(a,l,n)}catch(i){qt(l,i,t)}},Ie=async(t,n)=>(await b(a,l,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} = ${n}`))[0],it=async(t,n,i,s,r)=>{const d=e`${e.identifier(Ee)}`,$=e.join([T(e`${e.identifier("id")}`,s.id),T(d,s[Ee]??null),...r===void 0?[]:[e`(${r})`]],e` AND `),_=n==="UPDATE"?e`UPDATE ${e.identifier(t)} SET ${i}, ${d} = ${gt.sql(d)} WHERE ${$}`:e`DELETE FROM ${e.identifier(t)} WHERE ${$}`;try{if(l.supportsReturning)return(await b(a,l,e`${_} RETURNING ${e.identifier("id")}`)).length>0;const p=await V(a,l,_);return(l.affectedRows?l.affectedRows(p??{rowsAffected:0}):0)>0}catch(p){return qt(l,p,t)}},Oe=async(t,n,i,s)=>{if(s!==void 0&&!await it(t,n,i,s))throw new se(`optimistic concurrency conflict on "${t}" — the row changed during this mutation; refetch and retry`,"occ")},Be=(t,n=t?._creationTime)=>({_creationTime:n,[Ee]:gt.value(t?.[Ee])}),ot=async(t,n,i,s,r,d,$)=>{const _=Y(n,r);if(!_||r===void 0)throw new g("INTERNAL",`document not found: ${i}`);const p=Wn(n,s,_),E={..._,...Fn(p),_id:i};je(n,p,E,Z);const w=Fe(n,E,{only:new Set(Object.keys(p)),previous:()=>_,tolerateStoredNull:!0});Ge(l.name,Object.fromEntries(Object.keys(p).map(y=>[y,w[y]]))),Un($,_,w),j(t,"before","update")&&await G("before","update",{doc:{...w},id:i,op:"update",previous:_,table:t}),await Te(t),await me(t);const u=Object.keys(n.shape),S=e.join(u.map(y=>e`${e.identifier(y)} = ${oe(n,y,w[y]??null)}`),e`, `);if(await it(t,"UPDATE",S,r,d))return await te([...await ue(t,_,w),...await ee(t,i,_,w),...de(t,i,"update",w)]),await we(t,i,{document:w,previous:_,written:Be(r)}),j(t,"after","update")&&await G("after","update",{doc:w,id:i,op:"update",previous:_,table:t}),w},en=(t,n,i,s)=>{const r=Object.keys(t.shape);return{columns:["id","_creationTime",...r],values:[n,i,...r.map(d=>oe(t,d,s[d]??null))]}},tn=async(t,n,i,s)=>{const r=Pn(n,i.op,i.field,s.by,s.where);if(!r||!await ve(t,r.index))return;const $=ie(t,r.index.name),_=Object.keys(r.partial);if(_.length===(r.index.by??[]).length&&_.length>0){const E=J(r.index.by??[],r.partial),w=await b(a,l,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier($)} WHERE ${e.identifier("__key__")} = ${E}`);if(w.length===0)return[];const u=w[0];return[{key:{...r.partial},value:Ue(i.op,{count:u.count,value:ae(u.value)})}]}return _.length>0?void 0:(await b(a,l,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($)}`)).map(E=>{const w=E;return{key:Dt(JSON.parse(w.key)),value:Ue(i.op,{count:w.count,value:ae(w.value)})}})},rt=t=>{const n=f.tables[t]?.shardMode?.kind;return n==="shardBy"||n==="root"},st=t=>{throw new g("INTERNAL",`cross-backend relation: a global table cannot load the shard-local relation '${t}' (it spans every shard) — wire a cross-shard reader to support it`)},nn=(t,n)=>{if(n?.relationMask!==void 0&&n.with!==void 0&&Object.keys(n.with).length>0)throw new g("MASK_UNSUPPORTED",`masking cannot follow a nested \`with\` across the cross-shard relation hop to "${t}" — the nested rows are hydrated on the serving shard, where the mask policy does not exist. Read the nested relation at its own (masked) call site instead.`);const i={};if(n?.relationBaseWhere)for(const s of Object.keys(f.tables)){const r=n.relationBaseWhere(s);r!==void 0&&(i[s]=r)}return{orderBy:n?.orderBy,relationPolicies:i,where:B(n?.baseWhere,n?.where),with:n?.with}},Ae=(t,n)=>rt(t)?h?h(t,nn(t,n)):st(t):x.findMany(t,n),be=(t,n,i)=>xn(t,{fetcher:Ae,maxRelationKeys:R,relationBaseWhere:i,schema:f,tableName:n}),on=ai(async(t,n)=>{const i=await b(a,l,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} IN (${ce(n)})`),s=new Map;for(const r of i){const{id:d}=r;typeof d=="string"&&s.set(d,r)}return s}),at=async(t,n,i)=>{const{fetchLimit:s,limit:r,orderKeys:d,predicate:$}=await Hn(n,i,{fetcher:Ae,maxRelationKeys:R,schema:f,tableName:t}),_=z($,m(n)),p=li(d,l);let E=e`SELECT * FROM ${e.identifier(t)}`;return _&&(E=e`${E} WHERE ${_}`),E=e`${E} ORDER BY ${p}`,s!==void 0&&(E=e`${E} LIMIT ${e.raw(String(s))}`),{limit:r,orderKeys:d,query:E}},x={relationWrites:pn(f),async cdcChangedTables(t,n){if(K)try{return await W(),await ki(a,t,l,{...n,now:M(),retained:X!==void 0})}catch{return}},async aggregate(t,n){const i=f.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);if(await W(),_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 g("INTERNAL",`aggregate(${t}, { op: "${n.op}" }): "field" is required for non-count reducers`);const s=Me(i.softDeleteMode,void 0),r=B(B(n.baseWhere,n.where),s),d=await be(r,t,n.relationBaseWhere),$=d!==r;if(i.aggregateIndexes&&!n.baseWhere&&!$&&!s){const S=Dn(i.aggregateIndexes,n.op,n.field,n.where);if(S&&await ve(t,S.index)){const v=J(S.index.by??[],S.key),L=ie(t,S.index.name),N=(await b(a,l,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(L)} WHERE ${e.identifier("__key__")} = ${v}`))[0];return Ue(n.op,N===void 0?void 0:{count:N.count,value:ae(N.value)})}}Qe(i,n.field,`aggregate(${t}, { op: "${n.op}", field: "${n.field}" })`);const _=z(d,m(i)),p=e.raw(_e(n.op)),E=e`SELECT ${p}(${U(n.field)}) AS ${e.identifier("value")} FROM ${e.identifier(t)}`,u=(await b(a,l,_?e`${E} WHERE ${_}`:E))[0]?.value;return u==null?null:Number(u)},async count(t,n){const i=f.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await W();const s=qn(n);if(s.restrictsCounts)throw new ut(t);const r=Me(i.softDeleteMode,void 0),d=B(B(s.baseWhere,s.where),r),$=await be(d,t,s.relationBaseWhere),_=$!==d;if(i.aggregateIndexes&&!s.baseWhere&&!_&&!r){const u=kn(i.aggregateIndexes,s.where);if(u&&await ve(t,u.index)){const y=J(u.index.by??[],u.key),v=ie(t,u.index.name),L=await b(a,l,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")} FROM ${e.identifier(v)} WHERE ${e.identifier("__key__")} = ${y}`);return Number(L[0]?.value??0)}}const p=z($,m(i)),E=e`SELECT COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(t)}`,w=await b(a,l,p?e`${E} WHERE ${p}`:E);return Number(w[0]?.count??0)},async delete(t,n,i){const s=await ge(t,n);if(!s)return;const r=f.tables[s];if(!r)return;const d=await Ie(s,t),$=Y(r,d),_=i?.hard===!0,p=!_&&r.softDeleteMode?r.softDeleteMode.field:void 0;if(!(p&&(!$||$[p]!==null&&$[p]!==void 0))){if(j(s,"before","delete")&&await G("before","delete",{id:t,op:"delete",previous:$??void 0,table:s}),await Nn({deletedId:t,deletedReference:E=>$?.[E],findHolders:async(E,w,u,S)=>{if(f.tables[E]?.shardMode?.kind==="shardBy")throw new g("INTERNAL",`cross-backend cascade from global '${s}' into shardBy '${E}' is not supported — would require Query Coordinator fan-out across shards`);return(await x.findMany(E,{...S,includeDeleted:_,where:{[w]:u}})).page},onCascade:(E,w)=>x.delete(w,void 0,i),onRestrict:E=>{throw new se(E,"restrict")},onSetNull:(E,w,u)=>x.patch(w,{[u]:null}),schema:f,tableName:s}),await Te(s),await me(s),p&&$){const E={[p]:M()},w={...$,...E};je(r,E,w,Z);const u=e.join(Object.keys(r.shape).map(S=>e`${e.identifier(S)} = ${oe(r,S,w[S]??null)}`),e`, `);await Oe(s,"UPDATE",u,d),await te([...await ue(s,$,w),...await ee(s,t,$,void 0),...de(s,t,"update",w)]),await we(s,t,{document:w,previous:$,written:Be(d)}),j(s,"after","delete")&&await G("after","delete",{id:t,op:"delete",previous:$,table:s});return}await Oe(s,"DELETE",void 0,d),Re.delete(Xe(t));for(const E of Yt)Re.delete(xt(E,t));await te([...await ue(s,$??void 0,void 0),...await ee(s,t,$??void 0,void 0),...de(s,t,"delete")]),await we(s,t,void 0),j(s,"after","delete")&&await G("after","delete",{id:t,op:"delete",previous:$??void 0,table:s})}},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 Mn(`findFirstOrThrow: no "${t}" document matched`);return i},async findMany(t,n={}){const i=f.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await W();const s=async(S,y,v,L)=>{if(rt(S))return c?Kn(c,S,y,v,L):st(S);const A=f.tables[S];if(!A)throw new g("INTERNAL",`unknown table: ${S}`);const N=Me(A.softDeleteMode,void 0),O={[y]:{in:v}},F=B(B(O,L),N),Q=await be(F,S,void 0),Ce=z(Q,m(A)),he=U(y);let P=e`SELECT ${he} AS __fk__, COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(S)}`;Ce&&(P=e`${P} WHERE ${Ce}`),P=e`${P} GROUP BY ${he}`;const k=await b(a,l,P),ne=new Map;for(const ct of k)ne.set(ct.__fk__,Number(ct.count??0));return ne},{limit:r,orderKeys:d,query:$}=await at(t,i,n),_=await b(a,l,$),p=St(i,_);if(r===void 0)return n.with&&await ft({fetcher:Ae,groupedCounter:s,parents:p,...wt(n),schema:f,tableName:t,with:n.with}),{continueCursor:null,isDone:!0,page:ht(p,n.select,n.with)};const E=p.length>r,w=E?p.slice(0,r):p,u=w.at(-1);return n.with&&await ft({fetcher:Ae,groupedCounter:s,parents:w,...wt(n),schema:f,tableName:t,with:n.with}),{continueCursor:E&&u?Ln(u,d):null,isDone:!E,page:ht(w,n.select,n.with)}},async explain(t,n={}){const i=f.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await W();const{query:s}=await at(t,i,n),r=l.name==="sqlite"?"EXPLAIN QUERY PLAN":"EXPLAIN",d=await b(a,l,e`${e.raw(r)} ${s}`),{params:$,sql:_}=l.render(s);return{params:$,plan:d.map(p=>ui(p)),sql:_}},async get(t,n){const i=Object.hasOwn(f.tables,t)?f.tables[t]:void 0;if(!i)throw new g("BAD_REQUEST",`ctx.db.get(table, id): "${t}" is not a table in this schema`);return i.shardMode!==void 0&&i.shardMode.kind!=="global"?null:(await W(),Y(i,await on.load(t,n)))},async groupBy(t,n){const i=f.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await W();const s=n.agg??{op:"count"};if(_e(s.op),s.op!=="count"&&!s.field)throw new g("INTERNAL",`groupBy(${t}, { agg: { op: "${s.op}" } }): "field" is required for non-count reducers`);const r=Me(i.softDeleteMode,void 0),d=B(B(n.baseWhere,n.where),r),$=await be(d,t,n.relationBaseWhere),_=$!==d;if(i.aggregateIndexes&&!n.baseWhere&&!_&&!r){const y=await tn(t,i.aggregateIndexes,s,n);if(y!==void 0)return y}gi(i,t,n.by,s);const p=z($,m(i)),E=n.by.map(y=>e`${U(y)} AS ${e.identifier(y)}`);if(s.op==="count")E.push(e`COUNT(*) AS ${e.identifier("value")}`);else{if(!s.field)throw new g("INTERNAL",`groupBy(${t}, { agg: { op: "${s.op}" } }): "field" is required for non-count reducers`);E.push(e`${e.raw(_e(s.op))}(${U(s.field)}) AS ${e.identifier("value")}`)}const w=e.join(n.by.map(y=>U(y)),e`, `);let u=e`SELECT ${e.join(E,e`, `)} FROM ${e.identifier(t)}`;p&&(u=e`${u} WHERE ${p}`),u=e`${u} GROUP BY ${w}`;const S=await b(a,l,u);return $i(i,n.by,S)},async insert(t,n,i){const s=f.tables[t];if(!s)throw new g("INTERNAL",`unknown table: ${t}`);await W();const r=Fe(s,An(s,n,Z),{supplied:n,trusted:i?.allowExplicitId===!0});Ge(l.name,r);let d,$=!0;i?.clientId!==void 0?(bn(i.clientId),d=i.clientId):i?.allowExplicitId&&typeof r._id=="string"?(Cn(r._id),d=r._id):(d=D(),$=!1);const _=i?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:M(),p={...r,_creationTime:_,_id:d};j(t,"before","insert")&&await G("before","insert",{doc:{...p},id:d,op:"insert",table:t}),await Te(t),await me(t);const{columns:E,values:w}=en(s,d,_,r);return await Zt(t,e`INSERT INTO ${e.identifier(t)} (${re(E)}) VALUES (${ce(w)})`),$&&Re.set(Xe(d),t),await te([...await ue(t,void 0,p),...await ee(t,d,void 0,p),...de(t,d,"insert",p)]),await we(t,d,{document:p,written:{_creationTime:_,[Ee]:null}}),j(t,"after","insert")&&await G("after","insert",{doc:p,id:d,op:"insert",table:t}),d},normalizeId(t,n){return In(f,t,n)},async patch(t,n,i,s){We("patch",n);const r=await ge(t,i);if(!r)throw new g("INTERNAL",`document not found: ${t}`);const d=f.tables[r];if(!d)throw new g("INTERNAL",`document not found: ${t}`);const $=mn(d,n)?Ve:1;for(let _=0;_<$;_+=1){const p=await Ie(r,t);if(await ot(r,d,t,n,p,void 0,s))return}throw new se(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},async patchIf(t,n,i){We("patchIf",i.patch);const s=f.tables[t];if(!s)throw new g("INTERNAL",`unknown table: ${t}`);const r=z(i.where,m(s))??e`1 = 1`;for(let d=0;d<Ve;d+=1){const[$]=await b(a,l,e`SELECT *, CASE WHEN (${r}) THEN 1 ELSE 0 END AS ${e.identifier(Nt)} FROM ${e.identifier(t)} WHERE ${e.identifier("id")} = ${n}`);if($===void 0)return{applied:!1,doc:null};const{[Nt]:_,...p}=$;if(Number(_)!==1)return{applied:!1,doc:Y(s,p)??null};const E=await ot(t,s,n,i.patch,p,r,{verify:i.verify});if(E)return{applied:!0,doc:E}}throw new se(`patchIf on "${t}" lost the row to concurrent writes ${String(Ve)} times in a row; retry the operation`,"occ")},async restore(t,n){const i=await ge(t,n);if(!i)throw new g("INTERNAL",`document not found: ${t}`);const s=f.tables[i],r=s?.softDeleteMode?.field;if(!s||!r)throw new g("INTERNAL",`ctx.db.restore: table "${i}" is not a .softDelete() table`);const d=await Ie(i,t),$=d?.[r]!==null&&d?.[r]!==void 0;if(await x.patch(t,{[r]:null},n),$){const _=Y(s,d);_!==null&&await te(await ee(i,t,void 0,{..._,[r]:null}))}},query(t){const n=f.tables[t];if(!n)throw new g("INTERNAL",`unknown table: ${t}`);const i="the legacy query()/withIndex() reader is not available on the D1 (global) backend; use findMany",s=[];let r=0,d;const $=l.name!=="mysql",_={...m(n),fieldRef:u=>e`m.${U(u)}`,rangeTypeGuard:()=>{throw new g("INTERNAL","a path range is never pushed into a search")}},p=u=>s.every(S=>S(u)),E=async(u,S)=>{await W();const y=2*fn+u.filters.length,v=d===void 0?void 0:z(d,_,void 0,y),L=v!==void 0&&l.name==="sqlite"&&l.render(v).params.length+y>Qn.boundParams,A=L?void 0:v,N=r>0||L,O=await wn(a,l,n,t,A===void 0?u:{...u,scope:A},hn(N?void 0:S));!N&&S===void 0&&$n(O);const F=O.filter(Q=>p(Q));return S===void 0?F:F.slice(0,S)},w=u=>{const S={async*[Symbol.asyncIterator](){if(!u)throw new g("INTERNAL",i);yield*await E(u,void 0)},async collect(){if(!u)throw new g("INTERNAL",i);return E(u,void 0)},async collectWithScores(){throw new g("GLOBAL_SEARCH_SCORES_UNSUPPORTED",`collectWithScores() is not supported on \`.global()\` tables (table "${t}") — relevance scores are not yet surfaced on this backend; use .collect() instead`)},filter(y){s.push(y);const v=jn(y);return v!==void 0&&Gn(v,n.shape,$)?d=B(d,v):r+=1,S},async first(){if(!u)throw new g("INTERNAL",i);return(await E(u,1))[0]??null},order(){return S},async paginate(y){if(!u)throw new g("INTERNAL",i);const v=ln(y);return un(await E(u,_n(v)),v)},async take(y){if(!u)throw new g("INTERNAL",i);return E(u,y)},async unique(){if(!u)throw new g("INTERNAL",i);const y=await E(u,2);if(y.length>1)throw new Xn(`unique() on table "${t}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(){throw new g("INTERNAL",`geo indexes are not supported on \`.global()\` tables (table "${t}") — geospatial queries run only on sharded tables`)},withIndex(){throw new g("INTERNAL",i)},withSearchIndex(y,v){const L=(n.searchIndexes??[]).find(N=>N.name===y);if(!L)throw new g("INTERNAL",`unknown search index "${y}" on table "${t}"`);const A={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:y,query:""};if(v(dn(A,t,sn(L.language))),!A.hasQuery)throw new g("INTERNAL",`search index "${y}" on table "${t}" requires a .search(field, query) call`);return w(A)}};return S};return w(void 0)},async rank(t,n,i){const s=f.tables[t];if(!s)throw new g("INTERNAL",`unknown table: ${t}`);const r=s.rankIndexes?.find(O=>O.name===n);if(!r)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(i.restrictsCounts)throw new ut(t);if(await W(),!await De(t,r))return null;const $=typeof i.row=="string"?i.row:i.row._id;if(!$)return null;const _=$e(t,r.name),p=r.sortBy.map((O,F)=>pe(F)),E=re(["__partition__",...p]),u=(await b(a,l,e`SELECT ${E} FROM ${e.identifier(_)} WHERE ${e.identifier("__id__")} = ${$}`))[0];if(!u)return null;const S=u.__partition__,y=B(i.baseWhere,i.where);dt(y,f,t,"rank");const v=lt(r,y);if(v&&Le(r.partitionBy??[],v)!==S)return null;const L=Ei(l.name,r,p,u,$),A=await b(a,l,e`SELECT COUNT(*) AS c FROM ${e.identifier(_)} WHERE ${e.identifier("__partition__")} = ${S} AND (${L})`),N=await b(a,l,e`SELECT COUNT(*) AS c FROM ${e.identifier(_)} WHERE ${e.identifier("__partition__")} = ${S}`);return{position:Number(A[0]?.c??0)+1,total:Number(N[0]?.c??0)}},async rankPage(t,n,i={}){dt(B(i.baseWhere,i.where),f,t,"rankPage");const s=f.tables[t];if(!s)throw new g("INTERNAL",`unknown table: ${t}`);const r=s.rankIndexes?.find(k=>k.name===n);if(!r)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(await W(),!await De(t,r))return{continueCursor:null,isDone:!0,page:[]};const $=$e(t,r.name),_=r.sortBy.map((k,ne)=>pe(ne)),p=Math.max(1,Math.min(1e3,Math.floor(i.take??100))),E=B(i.baseWhere,i.where),w=lt(r,E),u=yi(r,_),S=e.join(u.flatMap(k=>Ut(l,{direction:k.direction,field:k.column,nullable:k.nullable})),e`, `),y=[];typeof i.partitionKey=="string"?y.push(e`${e.identifier("__partition__")} = ${i.partitionKey}`):w&&y.push(e`${e.identifier("__partition__")} = ${Le(r.partitionBy??[],w)}`);const v=Tn(i);if(v!==void 0){const k=pi(l.name,u,v);k!==void 0&&y.push(k)}const L=re([ye,"__partition__",..._]);let A=e`SELECT ${L} FROM ${e.identifier($)}`;y.length>0&&(A=e`${A} WHERE ${e.join(y,e` AND `)}`),A=e`${A} ORDER BY ${S} LIMIT ${e.raw(String(p+1))}`;const N=await b(a,l,A),O=N.length>p,F=O?N.slice(0,p):N,Q=F.map(k=>k[ye]),Ce=await Ri(a,l,s,t,Q);let he=null;const P=F.at(-1);if(O&&P!==void 0){const k=[P.__partition__,..._.map(ne=>P[ne]),P[ye]];he=Si(k)}return{continueCursor:he,isDone:!O,page:Ce}},async replace(t,n,i,s){We("replace",n);const r=await ge(t,i);if(!r)throw new g("INTERNAL",`document not found: ${t}`);const d=f.tables[r];if(!d)throw new g("INTERNAL",`document not found: ${t}`);const $=await Ie(r,t);if($===void 0)throw new g("INTERNAL",`document not found: ${t}`);const p=vn(f,r,"update")||(d.aggregateIndexes??[]).length>0||(d.rankIndexes??[]).length>0?Y(d,$)??void 0:void 0,E=s?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:void 0,w=typeof $._creationTime=="number"?$._creationTime:void 0,u=E??w??M(),S={...n,_creationTime:u,_id:t};je(d,n,S,Z);const y=Fe(d,S,{previous:()=>p??Y(d,$)??void 0,supplied:n,trusted:s?.allowExplicitId===!0});Ge(l.name,y),j(r,"before","update")&&await G("before","update",{doc:{...y},id:t,op:"update",previous:p,table:r}),await Te(r),await me(r);const v=Object.keys(d.shape),L=e.join([e`${e.identifier("_creationTime")} = ${u}`,...v.map(A=>e`${e.identifier(A)} = ${oe(d,A,y[A]??null)}`)],e`, `);await Oe(r,"UPDATE",L,$),await te([...await ue(r,p,y),...await ee(r,t,p,y),...de(r,t,"update",y)]),await we(r,t,{document:y,previous:p,written:Be($,u)}),j(r,"after","update")&&await G("after","update",{doc:y,id:t,op:"update",previous:p,table:r})}};return nt={db:x,scheduler:Vt},x};export{Ji as createSqlCtxDb,to as decodeGlobalRow,ki as readSqlCdcChangedTables,zi as readSqlCdcChanges,jt as readSqlCdcFloor,Ii as runSqlCdcMigration,bi as sweepSqlCdcRetention};
@@ -0,0 +1 @@
1
+ import{LunoraError as p}from"@lunora/errors";import{D as I,c as vt,m as Dt,r as U,a as qt,l as lt,w as F,b as Ft}from"./ctx-db-search-state-DRiojLLm.mjs";import{ftsUnmappedPage as Ut,groupUnmappedRows as bt,ftsWriteDocument as mt,ftsPurgeDocument as ht,ftsCompanionDdl as kt,unionAll as Ht,ftsRowidMapName as Pt}from"@lunora/shard-engine";import{sql as i}from"drizzle-orm";import{q as h,O as Bt,n as jt,f as V,r as A,i as L,c as X,g as M,a as T,h as pt,b as rt,j as Wt,k as xt,l as Kt}from"./sql-exec-UH-aJj2C.mjs";const Gt=n=>{const t=atob(n),e=Uint8Array.from(t,r=>r.codePointAt(0)??0);return new TextDecoder().decode(e)},Yt=()=>new p("BAD_REQUEST","invalid cursor"),st=16,ot=8,y=1024,b=(n,t)=>t.query(n),Qt=(n,t)=>{if(!t)return{exact:!0,lower:n,upper:n};const e=[...n].at(-1)??"",r=(e.codePointAt(0)??0)+1;if(r>=55296&&r<=57343||r>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-e.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(r)}},Cn=(n,t,e)=>{const r={eq:(s,o)=>{if(!n.definition.filterFields?.includes(s))throw new p("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${t}"`);if(n.filters.length>=ot)throw new p("BAD_REQUEST",`search index "${n.indexName}" on table "${t}": at most ${String(ot)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:o}),r},search:(s,o)=>{const a=n;if(s!==a.definition.field)throw new p("INTERNAL",`search index "${a.indexName}" on table "${t}" indexes "${a.definition.field}", not "${s}"`);const f=b(o,e).length;if(f>st)throw new p("BAD_REQUEST",`search index "${a.indexName}" on table "${t}": at most ${String(st)} search terms are supported (got ${String(f)})`);return a.field=s,a.query=o,a.hasQuery=!0,r}};return r},Ln=n=>{if(n.length>y)throw new p("BAD_REQUEST",`more than ${String(y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Mn=n=>Math.min(n.offset+n.numItems+1,y),Vt=n=>btoa(`search:${String(n)}`),Xt=n=>{let t;try{t=Gt(n)}catch{return}if(!t.startsWith("search:"))return;const e=Number(t.slice(7));return Number.isInteger(e)&&e>=0?e:void 0},vn=n=>{if(typeof n.endCursor=="string")throw new p("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new p("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const t=Math.max(0,Math.floor(n.numItems)),e=n.cursor?Xt(n.cursor):0;if(e===void 0)throw Yt();if(e+t>=y)throw new p("BAD_REQUEST",`search pagination reaches the ${String(y)}-document limit (offset ${String(e)} + ${String(t)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,y-e-1))} or fewer, or narrow the query or the filters instead`);return{numItems:t,offset:e}},Dn=(n,t)=>{const e=t.offset+t.numItems,r=t.numItems>0&&n.length>e;return{continueCursor:r?Vt(e):null,isDone:!r,page:n.slice(t.offset,e)}},qn=n=>{if(n===void 0)return y+1;if(!Number.isFinite(n))return y;const t=Math.max(0,Math.floor(n));if(t>y)throw new p("BAD_REQUEST",`search returns at most ${String(y)} documents (asked for ${String(t)}) — narrow the query or paginate instead`);return t},Jt=(n,t)=>{if(!t.includes("."))return n[t];let e=n;for(const r of t.split(".")){if(e===null||typeof e!="object"||Array.isArray(e))return;e=e[r]}return e},k=(n,t)=>`${n}__fts_${t}`,S="__id__",g="__token__",O="__n__",zt=1e3,gt=(n,t)=>t.document(n),x=(n,t)=>Jt(n,t),Zt=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",tn=(n,t,e)=>n!==void 0&&t!==void 0&&x(n,e.field)===x(t,e.field),nn=(n,t)=>gt(Zt(x(n,t.field)),I(t.language)).slice(0,zt),q=(n,t)=>nn(n,t).join(" "),Tt=(n,t)=>{const e=new Map;for(const r of gt(n,t))e.set(r,(e.get(r)??0)+1);return e},yt=[Bt,"_creationTime"],at=50,$=(n,t)=>i`${i.identifier(n)}.${i.identifier(t)}`,v=(n,t,e)=>i`DELETE FROM ${i.identifier(n)} WHERE ${$(n,S)} = ${t}${e===void 0?i``:i` AND ${e}`}`,Rt=(n,{row:t,table:e})=>{const r=yt.map(s=>i` AND ${jt(n.name,$(e,s),t[s]??null)}`);return i`SELECT 1 FROM ${i.identifier(e)} WHERE ${$(e,"id")} = ${t.id}${i.join(r)}${n.name==="postgres"?i` FOR SHARE`:i``}`},D=(n,t)=>i`EXISTS (${Rt(n,t)})`,H=(n,t)=>i`NOT EXISTS (SELECT 1 FROM ${i.identifier(n)} WHERE ${$(n,"id")} = ${t})`,_t=(n,t,e,r)=>r===void 0?H(t,e):D(n,{row:r,table:t}),J=async(n,t,e,r)=>{const s=new Map;for(let o=0;o<r.length;o+=at){const a=r.slice(o,o+at),f=await h(n,t,i`SELECT * FROM ${i.identifier(e)} WHERE ${$(e,"id")} IN (${i.join(a.map(u=>i`${u}`),i`, `)})`);for(const u of f)s.set(String(u.id),u)}return s},K=(n,t,e)=>n.name==="mysql"?i`${i.identifier(t)}(${i.raw(String(e))})`:n.textPatternOperatorClass===void 0?i`${i.identifier(t)}`:i`${i.identifier(t)} ${i.raw(n.textPatternOperatorClass)}`,z=512,Z=(n,t)=>({columns:i`${K(n,g,256)}, ${K(n,S,z)}`,concurrently:!0,name:`${t}__unique`,table:t,unique:!0}),j=n=>i`${n} COLLATE utf8mb4_0900_bin`,W=(n,t)=>{const e=JSON.stringify(t.map(([r,s])=>({o:s,t:r})));switch(n.name){case"mysql":return i`JSON_TABLE(${e}, '$[*]' COLUMNS (${i.identifier("t")} VARCHAR(256) PATH '$.t', ${i.identifier("o")} INT PATH '$.o')) AS ${i.identifier("j")}`;case"postgres":return i`json_to_recordset(${e}::json) AS ${i.identifier("j")}(${i.identifier("t")} text, ${i.identifier("o")} integer)`;default:return i`(SELECT json_extract(${$("e","value")}, '$.t') AS ${i.identifier("t")}, json_extract(${$("e","value")}, '$.o') AS ${i.identifier("o")} FROM json_each(${e}) AS ${i.identifier("e")}) AS ${i.identifier("j")}`}},Nt=(n,t,e,r,s)=>{const o=i.join([g,S,O].map(f=>i.identifier(f)),i`, `),a=f=>i`INSERT INTO ${i.identifier(t)} (${o}) SELECT ${$("j","t")}, ${e}, ${$("j","o")} FROM ${W(n,r)} WHERE ${f}`;switch(n.name){case"mysql":{const f=D(n,s),u=$(t,g),c=i.identifier("held");return[i`${a(i`${f} AND NOT EXISTS (SELECT 1 FROM ${i.identifier(t)} AS ${c} WHERE ${$("held",S)} = ${e} AND ${$("held",g)} = ${j($("j","t"))})`)} ON DUPLICATE KEY UPDATE ${$(t,O)} = ${$(t,O)}`,i`UPDATE ${i.identifier(t)} JOIN ${W(n,r)} ON ${u} = ${j($("j","t"))} SET ${$(t,O)} = ${$("j","o")} WHERE ${$(t,S)} = ${e} AND ${f}`,i`DELETE FROM ${i.identifier(t)} WHERE ${$(t,S)} = ${e} AND ${f} AND ${u} NOT IN (SELECT ${j($("j","t"))} FROM ${W(n,r)})`]}case"postgres":{const f=i.identifier("__source__"),u=i.identifier("__purged__"),c=i`EXISTS (SELECT 1 FROM ${f})`;return[i`WITH ${f} AS (${Rt(n,s)}), ${u} AS (${v(t,e,c)} RETURNING 1) ${a(i`${c} AND (SELECT COUNT(*) FROM ${u}) >= 0`)} ON CONFLICT DO NOTHING`]}default:{const f=D(n,s);return[v(t,e,f),i`${a(f)} ON CONFLICT DO NOTHING`]}}},Ot={uniqueKeyMissing:!1,unmappedSkipped:0},ft=new Set,ut=(n,t)=>{ft.has(n)||(ft.add(n),console.warn(`[@lunora/sql-store] ${t}`))},ct=100,dt=3,G=async(n,t,e,r=0)=>{const{companion:s,definition:o,index:a,tableName:f}=e,u={done:!0,last:r,left:0};if((await h(n,t,t.tableExists(f))).length===0)return u;const d=await h(n,t,Ut(s,ct,r));if(d.length===0)return u;const w=Math.max(...d.map(_=>Number(_.rowid))),E=bt(d),l=await J(n,t,f,[...E.keys()]),m=[];for(const[_,nt]of E){const B=l.get(_),et=B===void 0?void 0:V(o,B),it=_t(t,f,_,B);m.push(...et?mt(s,_,q(et,a),{guard:it,unmappedRowids:nt}):ht(s,_,{guard:it,unmappedRowids:nt}))}await A(n,t,m);const R=await h(n,t,i`SELECT COUNT(*) AS ${i.identifier("n")} FROM ${i.identifier(s)} WHERE ${$(s,"rowid")} > ${Math.max(0,r)} AND ${$(s,"rowid")} <= ${w}`);return{done:d.length<ct,last:w,left:Number(R[0]?.n??0)}},en=async(n,t,e)=>{let r=0,s=0;for(;;){let o=await G(n,t,e,r);for(let a=1;o.left>0&&a<dt;a+=1)o=await G(n,t,e,r);if(o.left>0&&(s+=o.left,console.warn(`[@lunora/sql-store] search migration of "${e.companion}": ${String(o.left)} row(s) lost every one of ${String(dt)} attempts to a concurrent write and were left for a later pass.`)),o.done)return s;r=o.last}},rn=async(n,t,e,r)=>r==="step"?(await G(n,t,e),Ot):{uniqueKeyMissing:!1,unmappedSkipped:await en(n,t,e)},Y=n=>`${n}__btree`,sn=async(n,t,e)=>{const r=Z(t,e),s=await L(n,t,e,r.name);if(s!=="valid"){if(s==="absent"&&(await h(n,t,i`SELECT 1 AS ${i.identifier("present")} FROM ${i.identifier(e)} LIMIT 1`)).length===0)try{await X(n,t,{...r,concurrently:!1}),await M(n,t,e,Y(e));return}catch(a){if(await L(n,t,e,r.name).catch(()=>{})==="valid")return;ut(`${e}:empty`,`search companion "${e}": adding its unique key failed (${String(a)}); run backfillSqlSearchIndexes.`);return}ut(`${e}:missing`,`search companion "${e}" has no usable unique key, so two backfills racing over one row can index it twice. Run backfillSqlSearchIndexes, which adds it.`)}},on=async(n,t,e)=>{const r=$(e,S),s=$(e,g);return(await h(n,t,i`SELECT ${r} AS ${i.identifier("id")}, ${s} AS ${i.identifier("token")}, COUNT(*) AS ${i.identifier("n")} FROM ${i.identifier(e)} GROUP BY ${r}, ${s} HAVING COUNT(*) > 1`)).map(a=>({count:Number(a.n),id:String(a.id),token:String(a.token)}))},an=(n,t,{count:e,id:r,token:s})=>{const o=i`${$(t,S)} = ${r} AND ${$(t,g)} = ${s}`;switch(n.name){case"mysql":return i`DELETE FROM ${i.identifier(t)} WHERE ${o} LIMIT ${i.raw(String(e-1))}`;case"postgres":return i`DELETE FROM ${i.identifier(t)} WHERE ctid = ANY (ARRAY(SELECT ctid FROM ${i.identifier(t)} WHERE ${o} OFFSET 1))`;default:return i`DELETE FROM ${i.identifier(t)} WHERE rowid IN (SELECT rowid FROM ${i.identifier(t)} WHERE ${o} LIMIT -1 OFFSET 1)`}},fn=async(n,t,e,r)=>{const{companion:s,definition:o,index:a,tableName:f}=e;for(const d of r)await T(n,t,an(t,s,d));const u=[...new Set(r.map(d=>d.id))],c=await J(n,t,f,u);for(const d of u){const w=c.get(d),E=w===void 0?void 0:V(o,w);if(w!==void 0&&E){const l=[...Tt(q(E,a),I(a.language))];await A(n,t,Nt(t,s,d,l,{row:w,table:f}));continue}await T(n,t,v(s,d,_t(t,f,d,w)))}},un=async(n,t,e)=>t.name!=="mysql"?"":(await h(n,t,i`SELECT COLUMN_NAME AS ${i.identifier("name")}, COLLATION_NAME AS ${i.identifier("collation")} FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ${e} AND COLUMN_NAME IN (${g}, ${S})`)).filter(s=>!String(s.collation).endsWith("_bin")).map(s=>` Its ${String(s.name)} column uses ${String(s.collation)}, which treats values differing only in case or accents as one; convert it with ALTER TABLE \`${e}\` MODIFY \`${String(s.name)}\` VARCHAR(768) COLLATE utf8mb4_0900_bin NOT NULL.`).join(""),cn=async(n,t,e)=>{if(t.name!=="mysql")return 0;const r=$(e,S),s=await h(n,t,i`SELECT COUNT(*) AS ${i.identifier("n")} FROM (SELECT 1 AS ${i.identifier("x")} FROM ${i.identifier(e)} GROUP BY LEFT(${r}, ${i.raw(String(z))}), ${$(e,g)} HAVING COUNT(DISTINCT ${r}) > 1) AS ${i.identifier("shared")}`);return Number(s[0]?.n??0)},dn=async(n,t,e)=>{const r=Z(t,e),s=await L(n,t,e,r.name);if(s==="valid")return"valid";s==="invalid"&&await M(n,t,e,r.name);try{return await X(n,t,r),"built"}catch(o){const a=await L(n,t,e,r.name);if(a==="valid")return"valid";if(a==="invalid"&&await M(n,t,e,r.name),!t.isUniqueViolation(o))throw o;return"refused"}},$t=3,$n=async(n,t,e)=>{const{companion:r}=e,s=await un(n,t,r);let o="";s!==""&&console.warn(`[@lunora/sql-store] search companion "${r}" folds case and accents in its unique key.${s}`);for(let a=0;a<$t;a+=1){const f=await dn(n,t,r);if(f==="valid")return await M(n,t,r,Y(r)),!0;if(f==="refused"){const u=await on(n,t,r);if(u.length>0)await fn(n,t,e,u);else{const c=await cn(n,t,r);o=c>0?` ${String(c)} token(s) are held by document ids that agree on their first ${String(z)} characters, which the key cannot tell apart; shorten those ids.`:s}}}return await L(n,t,r,Z(t,r).name)==="valid"?(await M(n,t,r,Y(r)),!0):(console.warn(`[@lunora/sql-store] search companion "${r}" still has no unique key after ${String($t)} attempts: writes keep working, but two backfills racing over one row can index it twice.${o}`),!1)},wn=async(n,t,e,r)=>r==="step"?Ot:{uniqueKeyMissing:!await $n(n,t,e),unmappedSkipped:0},Sn=(n,t)=>t?i`${i.identifier(g)} LIKE ${`${n}%`}`:i`${i.identifier(g)} = ${n}`,At=(n,t)=>{const e=t.filters.map(r=>i`m.${rt(r.field)} = ${Wt(r.value)}`);return n.softDeleteMode&&e.push(i`m.${rt(n.softDeleteMode.field)} IS NULL`),t.scope!==void 0&&e.push(i`(${t.scope})`),e},It=async(n,t,e,r,s,o,a)=>{const f=At(e,s);let u=i`SELECT m.* FROM (${a}) s JOIN ${i.identifier(r)} m ON m.${i.identifier("id")} = s.${i.identifier(S)}`;return f.length>0&&(u=i`${u} WHERE ${i.join(f,i` AND `)}`),u=i`${u} ORDER BY s.${i.identifier("__score__")} DESC, m.${i.identifier("_creationTime")} DESC, m.${i.identifier("id")} ASC LIMIT ${i.raw(String(o))}`,pt(e,await h(n,t,u))},En=async(n,t,e,r,s,o)=>{const a=b(s.query,I(s.definition.language));if(a.length===0)return[];const f=k(r,s.indexName),u=a.length-1,c=a.map((m,R)=>Sn(m,R===u)),d=i.join(c,i` OR `),w=c.map(m=>i`SUM(CASE WHEN ${m} THEN ${i.identifier(O)} ELSE 0 END)`),E=i.join(w.map(m=>i`${m} > 0`),i` AND `),l=i`SELECT ${i.identifier(S)}, ${i.join(w,i` + `)} AS ${i.identifier("__score__")} FROM ${i.identifier(f)} WHERE ${d} GROUP BY ${i.identifier(S)} HAVING ${E}`;return It(n,t,e,r,s,o,l)},ln=async(n,t,e,r,s,o)=>{const a=b(s.query,I(s.definition.language));if(a.length===0)return[];const f=k(r,s.indexName),u=`${f}__vocab`,c=a.length-1,d=a.map((l,m)=>{const R=Qt(l,m===c),_=R.exact?i`${i.identifier("term")} = ${R.lower}`:i`${i.identifier("term")} >= ${R.lower} AND ${i.identifier("term")} < ${R.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(m))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(u)} WHERE ${_} GROUP BY ${i.identifier("doc")}`}),w=a.map((l,m)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(m))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),E=i`SELECT f.${i.identifier(S)} AS ${i.identifier(S)}, ${i.join(w,i` + `)} AS ${i.identifier("__score__")} FROM (${Ht(d)}) u JOIN ${i.identifier(f)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(S)} HAVING ${i.join(w.map(l=>i`${l} > 0`),i` AND `)}`;return It(n,t,e,r,s,o,E)},mn=async(n,t,e,r,s,o)=>{const a=t.nativeTextSearch,f=b(s.query,I(s.definition.language));if(!a||f.length===0)return[];const u=k(r,s.indexName),c=[a.matches(u,f),...At(e,s)],d=i`SELECT m.* FROM ${i.identifier(u)} JOIN ${i.identifier(r)} m ON m.${i.identifier("id")} = ${i.identifier(u)}.${i.identifier(S)} WHERE ${i.join(c,i` AND `)} ORDER BY ${a.rank(u,f)} DESC, m.${i.identifier("_creationTime")} DESC, m.${i.identifier("id")} ASC LIMIT ${i.raw(String(o))}`;return pt(e,await h(n,t,d))},hn={ensureCompanion:async(n,t,e)=>{const{integer:r,key:s}=t.companionTypes;await T(n,t,i`CREATE TABLE IF NOT EXISTS ${i.identifier(e)} (${i.identifier(g)} ${i.raw(s)} NOT NULL, ${i.identifier(S)} ${i.raw(s)} NOT NULL, ${i.identifier(O)} ${i.raw(r)} NOT NULL)`),await X(n,t,{columns:K(t,S,191),name:`${e}__by_id`,table:e,unique:!1}),await sn(n,t,e)},indexDocument:async(n,t,e,r,s,o)=>{const a=[...Tt(q(r,s),I(s.language))];await A(n,t,Nt(t,e,String(o.row.id),a,o))},migrate:wn,name:"inverted",purgeDocument:async(n,t,e,r,s)=>{await T(n,t,v(e,r,H(s,r)))},runSearch:En},pn={ensureCompanion:async(n,t,e)=>{await A(n,t,kt(e))},indexDocument:async(n,t,e,r,s,o)=>{await A(n,t,mt(e,String(o.row.id),q(r,s),{guard:D(t,o)}))},migrate:rn,name:"fts5",purgeDocument:async(n,t,e,r,s)=>{await A(n,t,ht(e,r,{guard:H(s,r)}))},runSearch:ln},gn={ensureCompanion:async(n,t,e)=>{const r=t.nativeTextSearch;if(r){await T(n,t,r.createCompanion(e,t.companionTypes.key));for(const s of r.createIndexes(e))await T(n,t,s)}},indexDocument:async(n,t,e,r,s,o)=>{const a=t.nativeTextSearch;a&&await T(n,t,a.indexDocument(e,String(o.row.id),q(r,s),D(t,o)))},name:"native",purgeDocument:async(n,t,e,r,s)=>{await T(n,t,v(e,r,H(s,r)))},runSearch:mn},C=(n,t)=>n.strategy==="native"&&t.nativeTextSearch!==void 0?gn:t.supportsFts5?pn:hn,P=(n,t)=>`${vt(n)}/${C(n,t).name}`,tt=function*(n){for(const[t,e]of Object.entries(n.tables)){const r=e.searchIndexes;if(!(e.shardMode!==void 0&&e.shardMode.kind!=="global"||!r))for(const s of r)yield[t,e,s]}},N=(n,t)=>k(n,t.name),Tn=async(n,t,e,r)=>{const s=N(e,r);return lt(await U(n,t,s),P(r,t)).finished?!0:Ft(n,t,s)},Fn=async(n,t,e,r,s,o)=>{if(!await Tn(n,t,r,s.definition))throw new p("SEARCH_INDEX_BUILDING",`search index "${s.indexName}" on table "${r}" is still backfilling and currently covers only part of the table — retry once it finishes${t.searchBackfillHint===void 0?"":`, or complete it now: ${t.searchBackfillHint}`}`);return C(s.definition,t).runSearch(n,t,e,r,s,o)},wt=n=>n.slice(n.lastIndexOf("/")+1),St=200,Et=5,yn=async(n,t,e,r)=>{const s=[...r.keys()],o=await h(n,t,i`SELECT * FROM ${i.identifier(e)} WHERE ${i.identifier("id")} >= ${s[0]} AND ${i.identifier("id")} <= ${s.at(-1)} ORDER BY ${i.identifier("id")} ASC`),a=new Map;for(const f of o){const u=f.id,c=r.get(u)?.row;c&&yt.some(d=>String(c[d])!==String(f[d]))&&a.set(u,{row:f})}return a},Q=async(n,t,e,r,s,o,a)=>{const f=C(o,t);let u=a;for(let c=0;u.size>0&&c<Et;c+=1){for(const{document:d,row:w}of u.values()){const E=d??V(e,w);E&&await f.indexDocument(n,t,s,E,o,{row:w,table:r})}u=await yn(n,t,r,u)}u.size>0&&console.warn(`[@lunora/sql-store] search index "${s}": ${String(u.size)} row(s) were rewritten on every one of ${String(Et)} re-check rounds and were left to their writers — each stays stale only if none of those writes changed its indexed text.`)},Ct=async(n,t,e,r,s)=>{const o=N(r,s),a=P(s,t),f=lt(await U(n,t,o),a);if(f.finished)return!0;if(f.wipe&&await F(n,t,o,void 0,!1,a),(await h(n,t,t.tableExists(r))).length===0)return await F(n,t,o,void 0,!0,a),!0;const c=await xt(n,t,r,f.cursor,St),d=c.findLast(l=>typeof l.id=="string")?.id,w=new Map;for(const l of c)typeof l.id=="string"&&w.set(l.id,{row:l});await Q(n,t,e,r,o,s,w);const E=c.length<St;return await F(n,t,o,d??f.cursor,E,a),E},Lt=async(n,t,e)=>{await Dt(n,e);for(const[r,,s]of tt(t)){const o=N(r,s),a=P(s,e),f=await U(n,e,o);f.profile!==void 0&&wt(f.profile)!==wt(a)&&(await T(n,e,i`DROP TABLE IF EXISTS ${i.identifier(o)}`),await T(n,e,i`DROP TABLE IF EXISTS ${i.identifier(Pt(o))}`),await qt(n,e,o)),await C(s,e).ensureCompanion(n,e,o)}},Rn=async(n,t,e,r,s)=>{const o=N(r,s);if((await U(n,t,o)).profile!==void 0)return;let f=0;(await h(n,t,t.tableExists(r))).length>0&&await Kt(n,t,e,r,()=>{f+=1},{limit:1}),await F(n,t,o,void 0,f===0,P(s,t))},Mt=async(n,t,e,r,s,o)=>await C(s,t).migrate?.(n,t,{companion:N(r,s),definition:e,index:s,tableName:r},o)??{uniqueKeyMissing:!1,unmappedSkipped:0},Un=async(n,t,e)=>{await Lt(n,t,e);for(const[r,s,o]of tt(t)){if(await Mt(n,e,s,r,o,"step"),o.staged){await Rn(n,e,s,r,o);continue}await Ct(n,e,s,r,o)}},bn=async(n,t,e)=>{const r={uniqueKeyMissing:[],unmappedSkipped:0};await Lt(n,t,e);for(const[s,o,a]of tt(t)){const f=await Mt(n,e,o,s,a,"drain");r.unmappedSkipped+=f.unmappedSkipped,f.uniqueKeyMissing&&r.uniqueKeyMissing.push(N(s,a));let u=!1;for(;!u;)u=await Ct(n,e,o,s,a)}return r},kn=n=>{const{dialect:t,exec:e,schema:r}=n;return async(s,o,a)=>{const f=r.tables[s],u=f?.searchIndexes;if(!(!f||!u||u.length===0))for(const c of u){if(tn(a?.previous,a?.document,c))continue;const d=N(s,c);if(a){await Q(e,t,f,s,d,c,new Map([[o,{document:a.document,row:{...a.written,id:o}}]]));continue}await C(c,t).purgeDocument(e,t,d,o,s);const E=(await J(e,t,s,[o])).get(o);E!==void 0&&await Q(e,t,f,s,d,c,new Map([[o,{row:E}]]))}}};export{Cn as A,vn as C,Dn as R,qn as T,Fn as a,Mn as b,kn as c,bn as d,Un as r,st as u,Ln as x};
@@ -0,0 +1 @@
1
+ import{sql as e}from"drizzle-orm";import{a as p,q as m}from"./sql-exec-UH-aJj2C.mjs";const y=["de","en","es","fr","it","nl","none","pt"],L=i=>y.includes(i),A="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",R="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",F="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",q="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",N="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",_="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",x="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",C=new RegExp("(?<=\\p{Script=Cyrillic})[\\u0300-\\u0305\\u0307\\u0309-\\u036F]|(?<!\\p{Script=Cyrillic})[\\u0300-\\u036F]","gu"),O=/[\u0080-\u{10FFFF}]/u,b=/[\p{L}\p{N}]+/gu,H=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]+/gu,g=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]/u,D=i=>{if(!g.test(i))return[i];const n=[];let t=0;for(const r of i.matchAll(H)){const o=r.index,s=[...r[0]];if(o>t&&n.push(i.slice(t,o)),t=o+r[0].length,s.length===1){n.push(r[0]);continue}for(let a=0;a+1<s.length;a+=1)n.push(`${String(s[a])}${String(s[a+1])}`)}return t<i.length&&n.push(i.slice(t)),n},v=i=>O.test(i)?i.normalize("NFD").replaceAll(C,"").normalize("NFC").toLowerCase():i.toLowerCase(),f=i=>new Set(v(i).split(" ")),j={de:f(R),en:f(A),es:f(F),fr:f(q),it:f(N),nl:f(_),none:new Set,pt:f(x)},z=3,U=256,w=new Map,k=i=>{const n=i!==void 0&&L(i)?i:"none",t=w.get(n);if(t)return t;const r=j[n],o=a=>{const d=v(a),$=d.match(b)??[],u=(g.test(d)?$.flatMap(l=>D(l)):$).filter(l=>l.length<=U);return r.size===0?u:u.filter(l=>!r.has(l))},s={document:o,profile:`${n}-v${String(z)}`,query:a=>{const d=o(a);return d.filter(($,u)=>d.lastIndexOf($)===u)}};return w.set(n,s),s},W=i=>`${k(i.language).profile}:${i.field}`,S=i=>{const n=i.slice(i.indexOf(":")+1),t=n.lastIndexOf("/");return t===-1?n:n.slice(0,t)},V=(i,n)=>i.profile!==n?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},I=(i,n)=>typeof i=="string"&&S(i)===S(n),c="__lunora_search_state",K=async(i,n)=>{const{integer:t,key:r}=n.companionTypes,o=async(s,a)=>{try{await p(i,n,e`ALTER TABLE ${e.identifier(c)} ADD COLUMN ${e.identifier(s)} ${e.raw(a)}`)}catch{}};await p(i,n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(c)} (${e.identifier("companion")} ${e.raw(r)} PRIMARY KEY, ${e.identifier("cursor")} ${e.raw(r)}, ${e.identifier("done")} ${e.raw(t)} NOT NULL DEFAULT 0, ${e.identifier("profile")} ${e.raw(r)}, ${e.identifier("covered")} ${e.raw(t)} NOT NULL DEFAULT 0)`),await o("profile",r),await o("covered",`${t} NOT NULL DEFAULT 0`),await p(i,n,e`UPDATE ${e.identifier(c)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},T=i=>i===1||i===!0||i==="1",P=async(i,n,t)=>{const r=await m(i,n,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(c)} WHERE ${e.identifier("companion")} = ${t}`);return T(r[0]?.covered)},Y=async(i,n,t)=>{await p(i,n,e`DELETE FROM ${e.identifier(c)} WHERE ${e.identifier("companion")} = ${t}`)},X=async(i,n,t)=>{const o=(await m(i,n,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(c)} WHERE ${e.identifier("companion")} = ${t}`))[0];if(!o)return{cursor:void 0,done:!1,profile:void 0};const{cursor:s,profile:a}=o;return{cursor:typeof s=="string"?s:void 0,done:T(o.done),profile:typeof a=="string"?a:void 0}},G=async(i,n,t,r,o,s)=>{const a=r??null,d=await m(i,n,e`SELECT ${e.identifier("profile")} FROM ${e.identifier(c)} WHERE ${e.identifier("companion")} = ${t}`),$=I(d[0]?.profile,s),u=o?1:0,l=o||!$?e`${e.identifier("covered")} = ${u}`:e`${e.identifier("covered")} = ${e.identifier("covered")}`,h=e`UPDATE ${e.identifier(c)} SET ${e.identifier("cursor")} = ${a}, ${e.identifier("done")} = ${u}, ${e.identifier("profile")} = ${s}, ${l} WHERE ${e.identifier("companion")} = ${t}`;if(d.length>0){await p(i,n,h);return}try{await p(i,n,e`INSERT INTO ${e.identifier(c)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${t}, ${a}, ${o?1:0}, ${s}, ${o?1:0})`)}catch(E){if(!n.isUniqueViolation(E))throw E;await p(i,n,h)}};export{k as D,c as S,Y as a,P as b,W as c,V as l,K as m,X as r,G as w};
@@ -0,0 +1 @@
1
+ import{bigintSqlKey as a}from"@lunora/shard-engine";import{B as t,b as n,U as o,d as r,a as d,i as E,r as c,c as N,s as U,t as _}from"./value-codec-CiS1h_97.mjs";export{t as BIGINT_KEY_LENGTH,n as UNTYPED_NUMBER_PREFIX,o as UNTYPED_WIRE_PREFIX,a as bigintSqlKey,r as decodeBigint,d as effectiveColumnKind,E as isUntypedColumnKind,c as rewriteLegacyUntypedNumber,N as sqliteDecode,U as sqliteEncode,_ as tryJsonParse};
@@ -0,0 +1 @@
1
+ import{B as l,O as o,b as n,c as r,z as t,f as d,h as i,g as u,v as f,l as R,i as q,u as c,n as C,m,o as p,p as x,y as I,d as S,q as h,e as w,a as E,k as y,r as O,j as z,s as B,x as L,t as N}from"./sql-exec-UH-aJj2C.mjs";import"./value-codec-CiS1h_97.mjs";export{l as BACKFILL_BATCH_SIZE,o as OCC_VERSION_COLUMN,n as columnRefSql,r as createIndexIfNotExists,t as decodeGlobalRow,d as decodeRow,i as decodeRows,u as dropIndexIfExists,f as fieldRefSql,R as forEachRowPaged,q as indexState,c as nextRowVersion,C as nullSafeEqualsSql,m as pathContainsNeedle,p as pathInList,x as pathTextReference,I as pathTypeGuardSql,S as qualifiedColumnRefSql,h as queryAll,w as queryBatch,E as queryRun,y as readRowsPage,O as runInOrder,z as serializeColumnValue,B as serializeDocumentColumn,L as serializeFieldValue,N as tableColumns};
@@ -0,0 +1 @@
1
+ import{LunoraError as v}from"@lunora/errors";import{aggregateTableName as Y,rankTableName as X,sortColumnName as O,bigintSqlKey as V}from"@lunora/shard-engine";import{sql as t}from"drizzle-orm";import{e as Q,a as g,B as b,r as z,i as Z,U as J,b as nn}from"./value-codec-CiS1h_97.mjs";import{O as A,t as en,a as d,q as $,c as _,b as m,d as tn,s as on,e as rn}from"./sql-exec-UH-aJj2C.mjs";const sn=new Set(["any","null"]),D=(e,n)=>{const i=n.kindOf(e);return i!==void 0&&sn.has(i)||n.nullableOf(e)?!0:i==="union"&&(n.membersOf(e)??[]).some(o=>D(o,n))},S=e=>{const n=e._meta?.inner;return e.kind==="optional"&&n?S(n):e},R=e=>D(e,{kindOf:Q,membersOf:n=>S(n)._meta?.members,nullableOf:n=>S(n)._meta?.column?.notNull===!1}),U=(e,n,i=!1)=>n.columnType(g(e),{unique:i||e._meta?.column?.unique===!0}),k=e=>{const n=new Set;for(const i of e.indexes)i.unique===!0&&i.fields.length===1&&n.add(i.fields[0]);return n},an=(e,n,i)=>{if(i.indexKeyPrefix!==void 0)for(const o of n.indexes){if(o.unique!==!0||o.fields.length<=1)continue;const r=o.fields.filter(s=>{const a=n.shape[s];return a!==void 0&&i.indexKeyPrefix?.(g(a))!==void 0});if(r.length>0)throw new Error(`${e}.${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.`)}},ln=e=>e._meta?.column?.notNull===!0&&e.kind!=="optional"&&!R(e),un=(e,n,i)=>{const o=[],r=k(n);for(const[u,c]of Object.entries(n.shape)){if(!c._meta?.column)continue;const f=ln(c)?" NOT NULL":"";o.push(t`${t.identifier(u)} ${t.raw(`${U(c,i,r.has(u))}${f}`)}`)}const s=[...i.frameworkColumns().map(u=>t`${t.identifier(u.name)} ${t.raw(u.type)}`),t`${t.identifier(A)} ${t.raw(i.companionTypes.integer)}`],a=s.length+o.length,l=i.maxTableColumns;if(l!==void 0&&a>l){const u=a-1===l,c="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 v("VALIDATION_ERROR",`@lunora/sql-store: global table "${e}" needs ${String(a)} columns, over this engine's ${String(l)}-column limit. ${u?`One of them is "${A}", the row version every guarded write reads, which caps declared fields at ${String(l-s.length)}. A table provisioned at ${String(l)} columns before that column existed cannot be widened to hold it. `:""}${c}`)}return t.join([...s,...o],t`, `)},x=e=>{if(e.indexKeyPrefix?.("string")===void 0)return t`${m("_creationTime")}, ${m("id")}`},M=async(e,n,i,o)=>{const r=t.join(i.refs.map(a=>t`${a} IS NOT NULL`),t` AND `);if((await $(e,n,t`SELECT ${i.columns} FROM ${t.identifier(i.table)} WHERE ${r} GROUP BY ${i.columns} HAVING COUNT(*) > 1 LIMIT 1`)).length>0)throw new v("INTERNAL",`unique index "${i.name}" on "${i.table}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first.`)},cn=async(e,n,i)=>{if(!i.unique){await _(e,n,i);return}try{await _(e,n,i)}catch(o){throw n.isUniqueViolation(o)&&await M(e,n,i,"cannot be created"),o}},F=e=>{const n=e.indexOf("(");return n===-1?void 0:e.slice(n,e.lastIndexOf(")")+1)},fn=(e,n)=>{const i=n.unique?t`UNIQUE `:t``;return F(e.render(t`CREATE ${i}INDEX ${t.identifier(n.name)} ON ${t.identifier(n.table)} (${n.columns})`).sql)},dn=(e,n,i)=>{const o=fn(e,i);return o!==void 0&&o!==F(n)},B=async(e,n,i)=>{if(n.name!=="sqlite")return;const r=(await $(e,n,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${i.name} COLLATE NOCASE AND tbl_name = ${i.table} COLLATE NOCASE`))[0]?.sql;typeof r=="string"&&dn(n,r,i)&&(i.unique&&await M(e,n,i,"cannot be re-created with its new column list; the previous index is left in place"),await d(e,n,t`DROP INDEX IF EXISTS ${t.identifier(i.name)}`))},mn=(e,n,i)=>{an(e,n,i);const o=k(n),r=l=>{const u=m(l),c=n.shape[l],f=c&&i.indexKeyPrefix&&c._meta?.column?.unique!==!0&&!o.has(l)?i.indexKeyPrefix(g(c)):void 0;return f===void 0?u:t`${u}(${t.raw(String(f))})`},s=x(i),a=[];for(const l of n.indexes){const u=l.fields.map(E=>r(E)),c=t.join(u,t`, `),f=l.unique??!1;a.push({columns:f||s===void 0?c:t`${c}, ${s}`,kind:"declared",name:`${e}_${l.name}`,refs:u,table:e,unique:f})}s!==void 0&&a.push({columns:s,kind:"default-order",name:`${e}__by_creation`,refs:[],table:e,unique:!1});for(const[l,u]of en(n)){if(!u.unique)continue;const c=r(l);a.push({columns:c,kind:"unique-column",name:`${e}_unique_${l}`,refs:[c],table:e,unique:!0})}return a},$n=/^\s*create\s+unique\s/iu,T="__lunora_framework_indexes",En=()=>t`CREATE TABLE IF NOT EXISTS ${t.identifier(T)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`,P=(e,n)=>t`INSERT OR IGNORE INTO ${t.identifier(T)} (name, table_name) VALUES (${e}, ${n})`,w=e=>e.replaceAll(/[A-Z]/gu,n=>n.toLowerCase()),gn=async(e,n,i)=>{if(n.name!=="sqlite"||(await $(e,n,t`SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ${T} COLLATE NOCASE`)).length>0)return;await d(e,n,En());const r=x(n),s=r===void 0?void 0:`, ${n.render(r).sql})`;for(const a of i){const l=`${w(a)}_`,u=await $(e,n,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`);for(const c of u){const f=String(c.name),E=String(c.sql);w(f).startsWith(l)&&w(f)!==w(`${a}__by_creation`)&&($n.test(E)||s!==void 0&&E.trimEnd().endsWith(s))&&await d(e,n,P(f,a))}}},pn=(e,n,i)=>{if(e.name!=="sqlite")return[];const o=new Set(n.map(r=>w(r.name)));return i.filter(r=>!o.has(w(r)))},wn=async(e,n,i,o)=>{if(o.name!=="sqlite")return;const r=await $(e,o,t`SELECT "l"."name" FROM ${t.identifier(T)} AS "l" WHERE "l"."table_name" = ${n} COLLATE NOCASE`);for(const s of pn(o,i,r.map(a=>String(a.name))))await d(e,o,t`DROP INDEX IF EXISTS ${t.identifier(s)}`),await d(e,o,t`DELETE FROM ${t.identifier(T)} WHERE ${t.identifier(T)}."name" = ${s}`)},Tn=async(e,n,i,o)=>{const r=mn(n,i,o);for(const s of r){if(s.kind==="default-order"){await _(e,o,s);continue}s.kind==="declared"&&await B(e,o,s),await cn(e,o,s),o.name==="sqlite"&&await d(e,o,P(s.name,s.table))}await wn(e,n,r,o)},N="__lunora_migration_state",hn=async(e,n)=>{await d(e,n,t`CREATE TABLE IF NOT EXISTS ${t.identifier(N)} (${t.identifier("name")} ${t.raw(n.companionTypes.key)} PRIMARY KEY)`)},_n=async(e,n,i)=>(await $(e,n,t`SELECT ${t.identifier("name")} FROM ${t.identifier(N)} WHERE ${t.identifier("name")} = ${i}`)).length>0,Ln=async(e,n,i,o,r,s)=>{r>0&&s!==void 0&&console.warn(`[@lunora/sql-store] storage migration "${i}" on "${o}": ${String(r)} row(s) ${s} and were left as stored — range filters and ORDER BY over them stay wrong until they are corrected by hand.`);try{await d(e,n,t`INSERT INTO ${t.identifier(N)} (${t.identifier("name")}) VALUES (${i})`)}catch(a){if(!n.isUniqueViolation(a))throw a}},yn=100,An=(e,n)=>{const i=[],o=[];for(const r of n.fields){const s=e[r],a=n.convert(s);a!==void 0&&(i.push(t`${m(r)} = ${a}`),o.push(t`${m(r)} = ${s}`))}return{assignments:i,guards:o}},Sn=e=>t.join(e.fields.map(n=>e.probe(n)),t` OR `),j=async(e,n,i,o)=>{if(o.fields.length===0||(await hn(e,i),await _n(e,i,o.marker)))return;const r=Sn(o),s=t.join([m("id"),...o.fields.map(u=>m(u))],t`, `);let a="",l=0;for(;;){const u=await $(e,i,t`SELECT ${s} FROM ${t.identifier(n)} WHERE (${r}) AND ${m("id")} > ${a} ORDER BY ${m("id")} LIMIT ${t.raw(String(yn))}`);if(u.length===0){await Ln(e,i,o.marker,n,l,o.describeUnconvertible);return}const c=[];for(const E of u){const{id:p}=E,{assignments:h,guards:I}=typeof p=="string"?An(E,o):{assignments:[],guards:[]};if(h.length===0){l+=1;continue}c.push(t`UPDATE ${t.identifier(n)} SET ${t.join(h,t`, `)} WHERE ${m("id")} = ${p} AND ${t.join(I,t` AND `)}`)}await rn(e,i,c);const f=u.at(-1)?.id;if(typeof f!="string")return;a=f}},C=e=>`'${e}%'`,On=e=>Object.entries(e.shape).filter(([,n])=>n._meta?.column!==void 0&&g(n)==="bigint").map(([n])=>n),Rn=e=>Object.entries(e.shape).filter(([,n])=>n._meta?.column!==void 0&&Z(g(n))).map(([n])=>n),K=(e,n)=>({convert:i=>{if(!(typeof i!="string"||i.length===b))try{return V(BigInt(i))}catch{return}},describeUnconvertible:"hold a value the order-preserving key cannot represent (non-numeric text, or a magnitude past 39 digits)",fields:On(n),marker:`bigint-key:${e}`,probe:i=>t`(${m(i)} IS NOT NULL AND LENGTH(${m(i)}) <> ${b})`}),Nn=async(e,n,i,o)=>j(e,n,o,K(n,i)),G=(e,n)=>({convert:z,fields:Rn(n),marker:`untyped-number-key:${e}`,probe:i=>t`(${m(i)} LIKE ${t.raw(C(J))} AND ${m(i)} NOT LIKE ${t.raw(C(nn))})`}),In=async(e,n,i,o)=>j(e,n,o,G(n,i)),q=new Set,L=(e,n)=>{q.has(e)||(q.add(e),console.warn(`[@lunora/sql-store] ${n}`))},bn=e=>{const n=e._meta?.column;return n?.defaultFn?n.defaultFn():n&&"defaultValue"in n?n.defaultValue:void 0},Cn=(e,n,i)=>i._meta?.column?.unique===!0||e.indexes.some(o=>o.unique===!0&&o.fields.includes(n)),qn=async(e,n,i,o,r,s)=>{if(s.kind==="optional"||R(s))return;const a=Cn(i,r,s),l=a?void 0:bn(s),u=`UPDATE "${n}" SET "${r}" = … WHERE "${r}" IS NULL`;if(l===void 0){const c=a?"is unique, so one default cannot be written to every row":"has no default";L(`backfill:${n}.${r}`,`"${n}.${r}" was added as a required field that ${c}, so rows written before it read NULL. Backfill it with a migration (${u}).`);return}try{await d(e,o,t`UPDATE ${t.identifier(n)} SET ${t.identifier(r)} = ${on(i,r,l)} WHERE ${t.identifier(r)} IS NULL`)}catch(c){L(`backfill:${n}.${r}`,`could not backfill "${n}.${r}" from its default (${c instanceof Error?c.message:String(c)}); rows written before it read NULL. Run ${u}.`)}},vn=(e,n)=>[[A,n.companionTypes.integer],...Object.entries(e.shape).filter(([,i])=>i._meta?.column!==void 0).map(([i,o])=>[i,U(o,n),o])],Dn=async(e,n,i,o)=>{const r=vn(i,o),s="t",a=async l=>{try{return await $(e,o,t`SELECT ${t.join(l.map(u=>tn(s,u)),t`, `)} FROM ${t.identifier(n)} AS ${t.identifier(s)} LIMIT 0`),!0}catch{return!1}};if(!await a(r.map(([l])=>l)))for(const[l,u,c]of r)await a([l])||(await d(e,o,t`ALTER TABLE ${t.identifier(n)} ADD COLUMN ${t.identifier(l)} ${t.raw(u)}`),c!==void 0&&await qn(e,n,i,o,l,c))},Un=(e,n,i)=>{const o=typeof i.charset=="string"?` CHARACTER SET ${i.charset} COLLATE ${String(i.collation)}`:"";return`ALTER TABLE \`${e}\` MODIFY COLUMN \`${n}\` ${String(i.type)}${o} NULL`},kn=async(e,n,i,o)=>{if(o.name==="sqlite")return;const r=Object.keys(i.shape).filter(s=>{const a=i.shape[s];return a._meta?.column?.notNull===!0&&a.kind!=="optional"&&R(a)});if(r.length!==0)try{const s=o.name==="postgres"?t`column_name AS ${t.identifier("name")}`:t`column_name AS ${t.identifier("name")}, column_type AS ${t.identifier("type")}, character_set_name AS ${t.identifier("charset")}, collation_name AS ${t.identifier("collation")}`,a=o.name==="postgres"?t`table_schema = ANY (current_schemas(false))`:t`table_schema = DATABASE()`,l=await $(e,o,t`SELECT ${s} FROM information_schema.columns WHERE ${a} AND table_name = ${n} AND is_nullable = 'NO' AND column_name IN (${t.join(r.map(u=>t`${u}`),t`, `)})`);for(const u of l){const c=String(u.name);if(o.name==="postgres"){await d(e,o,t`ALTER TABLE ${t.identifier(n)} ALTER COLUMN ${t.identifier(c)} DROP NOT NULL`);continue}L(`${n}.${c}`,`"${n}"."${c}" accepts null in the schema but its column is NOT NULL, so writing null there fails. Relaxing it on MySQL can rebuild the table, so it is not done at startup; run this once, in a maintenance window: ${Un(n,c,u)};`)}}catch(s){L(`${n}:relax-failed`,`could not relax NOT NULL on the null-accepting columns of "${n}" (${r.join(", ")}): ${s instanceof Error?s.message:String(s)}. Writing null to them fails until the constraint is dropped by hand.`)}},xn=async(e,n,i,o)=>{const r=un(n,i,o);await d(e,o,t`CREATE TABLE IF NOT EXISTS ${t.identifier(n)} (${r})`),await Dn(e,n,i,o),await kn(e,n,i,o),await Tn(e,n,i,o),await Nn(e,n,i,o),await In(e,n,i,o)},Yn=(e,n)=>[K(e,n),G(e,n)].filter(i=>i.fields.length>0),Xn=async(e,n,i,o)=>{let r=!1;for(const[s,a]of Object.entries(n.tables))a.shardMode?.kind!=="global"||o!==void 0&&!o.has(s)||(r||(r=!0,await gn(e,i,Object.entries(n.tables).filter(([,l])=>l.shardMode?.kind==="global").map(([l])=>l))),await xn(e,s,a,i))},H=e=>e.shardMode===void 0||e.shardMode.kind==="global",Vn=async(e,n,i)=>{const{integer:o,key:r,real:s}=i.companionTypes;for(const[a,l]of Object.entries(n.tables)){const u=l.aggregateIndexes;if(!(!u||u.length===0||!H(l)))for(const c of u){const f=Y(a,c.name);await d(e,i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(f)} (${t.identifier("__key__")} ${t.raw(r)} PRIMARY KEY, ${t.identifier("__value__")} ${t.raw(s)}, ${t.identifier("__count__")} ${t.raw(o)} NOT NULL DEFAULT 0)`),i.name==="sqlite"&&((await $(e,i,t`PRAGMA table_info(${t.identifier(f)})`)).some(p=>p.name==="__count__")||await d(e,i,t`ALTER TABLE ${t.identifier(f)} ADD COLUMN ${t.identifier("__count__")} ${t.raw(o)} NOT NULL DEFAULT 0`))}}},y=(e,n,i,o)=>{const r=e.name==="mysql"&&o?t`${t.identifier(n)}(191)`:t`${t.identifier(n)}`;return t`${r} ${t.raw(i)}`},Mn=(e,n,i)=>{const o=[y(e,"__partition__","ASC",!0)];for(const[r,s]of n.sortBy.entries()){const a=i.shape[s.field],l=a!==void 0&&e.indexKeyPrefix?.(g(a))!==void 0;o.push(y(e,O(r),s.direction==="desc"?"DESC":"ASC",l))}return o.push(y(e,"__id__","ASC",!0)),o},Fn=(e,n,i)=>n.sortBy.map((o,r)=>{const s=i.shape[o.field],a=e.columnType(s?g(s):void 0);return t`${t.identifier(O(r))} ${t.raw(a)}`}),Bn=/__sort_k\d+__/gu,Pn=async(e,n,i,o)=>{if(n.name!=="sqlite")return;const s=(await $(e,n,t`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ${i} COLLATE NOCASE`))[0]?.sql;if(typeof s!="string")return;const a=s.match(Bn)??[];(a.length!==o.length||a.some((l,u)=>l!==o[u]))&&await d(e,n,t`DROP TABLE ${t.identifier(i)}`)},Qn=async(e,n,i)=>{const{key:o}=i.companionTypes;for(const[r,s]of Object.entries(n.tables)){const a=s.rankIndexes;if(!(!a||a.length===0||!H(s)))for(const l of a){const u=X(r,l.name),c=Fn(i,l,s);await Pn(e,i,u,l.sortBy.map((I,W)=>O(W)));const f=c.length>0?t`, ${t.join(c,t`, `)}`:t``;await d(e,i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(u)} (${t.identifier("__id__")} ${t.raw(o)} PRIMARY KEY, ${t.identifier("__partition__")} ${t.raw(o)} NOT NULL${f})`);const E=Mn(i,l,s),p=`${r}__rank_${l.name}__btree`,h={columns:t.join(E,t`, `),name:p,refs:[],table:u,unique:!1};await B(e,i,h),await _(e,i,h)}}};export{T as INDEX_LEDGER_TABLE,N as MIGRATION_STATE_TABLE,fn as declaredIndexColumnList,w as foldIdentifier,un as globalTableColumnsDdl,mn as globalTableIndexSpecs,F as indexColumnList,En as indexLedgerDdl,dn as indexShapeChanged,Yn as legacyRewrites,Sn as legacyRowPredicate,xn as provisionGlobalTable,Xn as provisionGlobalTablesSequentially,P as recordIndexStatement,Vn as runSqlAggregateMigrations,Qn as runSqlRankMigrations,pn as undeclaredFrameworkIndexes,vn as wantedGlobalColumns};
@@ -0,0 +1 @@
1
+ import{sql as a}from"drizzle-orm";import{provisionGlobalTablesSequentially as m,foldIdentifier as c,globalTableColumnsDdl as A,globalTableIndexSpecs as L,legacyRewrites as O,indexLedgerDdl as R,wantedGlobalColumns as k,undeclaredFrameworkIndexes as y,indexShapeChanged as $,INDEX_LEDGER_TABLE as T,MIGRATION_STATE_TABLE as E,recordIndexStatement as M,legacyRowPredicate as C}from"./runSqlAggregateMigrations-BqfzHcG8.mjs";import{r as q,q as g}from"./sql-exec-UH-aJj2C.mjs";const v=50,h=new Map([["'","'"],["[","]"],["`","`"],['"','"']]),N=/^[\w$]+/u,b=(e,r)=>{const n=h.get(e[r]);let t=r+1;for(;t<e.length;)if(e[t]!==n)t+=1;else if(n!=="]"&&e[t+1]===n)t+=2;else return t+1;return t},_=e=>{const r=e.trim(),n=h.get(r[0]??"");if(n===void 0)return N.exec(r)?.[0];const t=b(r,0),s=r.slice(1,r[t-1]===n?t-1:t);return n==="]"?s:s.replaceAll(`${n}${n}`,n)},B=e=>{const r=new Set,n=i=>{const d=_(i);d!==void 0&&r.add(d)};let t=0,s=0,o=0;for(;o<e.length;){const i=e[o];if(h.has(i)){o=b(e,o);continue}if(i==="(")t+=1,s=t===1?o+1:s;else if(i===")"){if(t-=1,t===0)return n(e.slice(s,o)),r}else i===","&&t===1&&(n(e.slice(s,o)),s=o+1);o+=1}return r},F=async(e,r,n)=>{const t=new Set,s=new Map,o=n.has(c(T)),i=[];if(n.has(c(E))&&i.push(a`SELECT 'marker' AS kind, name, NULL AS owner FROM ${a.identifier(E)}`),o&&i.push(a`SELECT 'index' AS kind, "l"."name" AS name, "l"."table_name" AS owner FROM ${a.identifier(T)} AS "l"`),i.length===0)return{hasLedger:o,markers:t,owned:s};for(const d of await g(e,r,a.join(i,a` UNION ALL `)))if(d.kind==="marker")t.add(String(d.name));else{const f=c(String(d.owner));s.set(f,[...s.get(f)??[],String(d.name)])}return{hasLedger:o,markers:t,owned:s}},D=async(e,r)=>{try{const n=await g(e,r,a`SELECT type, name, tbl_name, sql FROM sqlite_master WHERE type IN ('table', 'index')`),t=new Set,s=new Map,o=new Map;for(const l of n){const u=String(l.name);if(u.startsWith("sqlite_"))continue;const S=typeof l.sql=="string"?l.sql:void 0;l.type==="table"?(t.add(c(u)),s.set(c(u),new Set([...S===void 0?[]:B(S)].map(I=>c(I))))):o.set(c(u),S)}const{hasLedger:i,markers:d,owned:f}=await F(e,r,t);return{columns:s,hasLedger:i,indexes:o,markers:d,owned:f,tables:t}}catch{return}},w=e=>e.kind==="default-order"?[]:[M(e.name,e.table)],p=e=>{const r=e.unique?a`UNIQUE `:a``;return a`CREATE ${r}INDEX IF NOT EXISTS ${a.identifier(e.name)} ON ${a.identifier(e.table)} (${e.columns})`},x=(e,r,n)=>n.length===0?[]:[a`CREATE TABLE IF NOT EXISTS ${a.identifier(E)} (${a.identifier("name")} ${a.raw(e.companionTypes.key)} PRIMARY KEY)`,...n.map(t=>a`INSERT OR IGNORE INTO ${a.identifier(E)} (${a.identifier("name")}) SELECT ${t.marker} WHERE NOT EXISTS (SELECT 1 FROM ${a.identifier(r)} WHERE ${C(t)})`)],G=(e,r,n,t)=>{const s=A(e,r,n),o=L(e,r,n),i=O(e,r);if(!t.tables.has(c(e)))return[...t.hasLedger?[]:[R()],a`CREATE TABLE IF NOT EXISTS ${a.identifier(e)} (${s})`,...o.flatMap(l=>[p(l),...w(l)]),...x(n,e,i)];const d=t.columns.get(c(e))??new Set;if(k(r,n).some(([l])=>!d.has(c(l)))||i.some(l=>!t.markers.has(l.marker))||y(n,o,t.owned.get(c(e))??[]).length>0)return;const f=[];for(const l of o){if(!t.indexes.has(c(l.name))){f.push(p(l),...w(l));continue}const u=t.indexes.get(c(l.name));if(l.kind==="declared"&&typeof u=="string"&&$(n,u,l))return}return f},X=e=>{const r=[];let n=[],t=0;for(const s of e)n.length>0&&t+s.statements.length>v&&(r.push(n),n=[],t=0),n.push(s),t+=s.statements.length;return n.length>0&&r.push(n),r},U=(e,r)=>!r.hasLedger&&Object.entries(e.tables).some(([n,t])=>t.shardMode?.kind==="global"&&r.tables.has(c(n))),Q=async(e,r,n)=>{if(!e.batch||n.name!=="sqlite"){await m(e,r,n);return}const t=await D(e,n);if(t===void 0){await m(e,r,n);return}if(U(r,t)){await m(e,r,n);return}const s=[],o=new Set;for(const[i,d]of Object.entries(r.tables)){if(d.shardMode?.kind!=="global")continue;const f=G(i,d,n,t);f===void 0?o.add(i):f.length>0&&s.push({statements:f,table:i})}for(const i of X(s))try{await q(e,n,i.flatMap(d=>d.statements))}catch{for(const d of i)o.add(d.table)}await m(e,r,n,o)};export{B as columnNamesOfCreateTable,Q as runSqlGlobalTableMigrations};
@@ -0,0 +1 @@
1
+ import{LunoraError as T}from"@lunora/errors";import{needsWireEncoding as v}from"@lunora/wire";import{sql as s,SQL as H}from"drizzle-orm";import{s as A,c as x,a as J}from"./value-codec-CiS1h_97.mjs";const U=t=>{if(t===null||typeof t!="object")return!1;const n=Object.getPrototypeOf(t);return n===null||n===Object.prototype},p=4;class g extends Error{}const S=t=>t.includes("."),w=t=>{const n=t.split(".");if(n.length>p||n.includes(""))throw new g(`field path "${t}" must have 1 to ${String(p)} non-empty segments`);return n},ot=(t,n)=>{if(!S(n))return t[n];let e=t;for(const r of w(n)){if(!U(e)||!Object.hasOwn(e,r))return;e=e[r]}return e},W={boolean:"'true', 'false'",number:"'integer', 'real'",string:"'text'"},B=/^[A-Za-z_$][\w$]*$/u,R=t=>B.test(t)?t:`"${t.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,at="_version",I=t=>t==="_id"||t==="id"?"id":t,d=t=>s`${s.identifier(I(t))}`,C=t=>{try{return w(t)}catch(n){throw n instanceof g?new T("VALIDATION_ERROR",n.message):n}},b=new WeakMap,it=t=>b.get(t),y=(t,n)=>{let e=s`${t}::jsonb`;for(const r of n)e=s`${e} -> ${r}::text`;return s`NULLIF(${e}, 'null'::jsonb)`},k=(t,n)=>s`CASE WHEN pg_input_is_valid(${t}, 'jsonb') THEN ${y(t,n)} END`,K=(t,n)=>s`CASE WHEN pg_input_is_valid(${t}, 'jsonb') THEN ${y(t,n)} #>> '{}' END`,L=(t,n)=>{const e=`$${n.map(r=>`.${R(r)}`).join("")}`;return s`NULLIF(JSON_EXTRACT(${t}, ${e}), CAST('null' AS JSON))`},V=(t,n)=>s`CASE WHEN JSON_VALID(${t}) THEN ${L(t,n)} END`,X=(t,n)=>s`CASE WHEN JSON_VALID(${t}) THEN JSON_UNQUOTE(${L(t,n)}) END`,ct=(t,n)=>t==="postgres"?s`(${n})::jsonb #>> '{}'`:s`JSON_UNQUOTE(${n})`,q=(t,n)=>{const[e="",...r]=C(n),o=d(e);return s`CASE WHEN json_valid(${o}) THEN ${s.raw(t)}(${o}, ${`$.${r.map(a=>R(a)).join(".")}`}) END`},z=(t,n)=>{if(!S(n))return d(n);if(t.name==="sqlite")return q("json_extract",n);const[e="",...r]=C(n),o=d(e),a=t.name==="postgres",i=a?k(o,r):V(o,r);return b.set(i,a?K(o,r):X(o,r)),i},D=new WeakMap,j=t=>s`CAST(CAST(${t} AS text) AS jsonb)`,lt=(t,n,e)=>{if(t.name==="sqlite")return s`NULLIF(${q("json_type",n)}, 'null') IN (${s.raw(W[e])})`;const r=z(t,n);if(t.name==="postgres")return s`jsonb_typeof(${r}) = ${s.raw(`'${e}'`)}`;const o={boolean:"'BOOLEAN'",number:"'INTEGER', 'UNSIGNED INTEGER', 'DOUBLE', 'DECIMAL'",string:"'STRING'"}[e];return s`JSON_TYPE(${r}) IN (${s.raw(o)})`},G=(t,n)=>{if(n===void 0)return n;if(typeof n=="bigint"||v(n))return t==="postgres"?s`CAST(NULL AS jsonb)`:s`CAST(NULL AS JSON)`;const e=JSON.stringify(n),r=t==="postgres"?s`${j(e)}`:s`CAST(${e} AS JSON)`;return D.set(r,e),r},ut=(t,n,e,r)=>{const o=[];let a=!1;for(const l of e){if(l===void 0)throw new T("BAD_REQUEST","an `in` list holds an undefined value");const E=l instanceof H?D.get(l):void 0;E===void 0?a=!0:o.push(E)}if(o.length===0||r&&a)return s`1 = 0`;const i=`[${o.join(",")}]`,c=t==="postgres"?s`SELECT e.v FROM jsonb_array_elements(${j(i)}) AS e(v)`:s`SELECT jt.v FROM JSON_TABLE(${i}, '$[*]' COLUMNS (v JSON PATH '$')) AS jt`;return r?s`${n} NOT IN (${c})`:s`${n} IN (${c})`},Et=(t,n,e,r)=>t.name==="sqlite"||!S(n)||e===null?r(e):G(t.name,e),ft=(t,n)=>s`${s.identifier(t)}.${s.identifier(I(n))}`,mt=t=>{const n=[];for(const[e,r]of Object.entries(t.shape)){const o=r._meta?.column;o&&n.push([e,o])}return n},m=(t,n,e)=>{const{params:r,sql:o}=n.render(e);return t.all(o,r)},u=(t,n,e)=>{const{params:r,sql:o}=n.render(e);return t.run(o,r)},dt=(t,n,e)=>t==="postgres"?s`${n} IS NOT DISTINCT FROM ${e}`:t==="mysql"?s`${n} <=> ${e}`:s`${n} IS ${e}`,$t={sql:t=>s`COALESCE(${t}, 0) + 1`,value:t=>(t==null?0:Number(t))+1},St=async(t,n,e)=>{if(e.length!==0){if(!t.batch){for(const r of e)await u(t,n,r);return}await t.batch(e.map(r=>n.render(r)))}},Nt=async(t,n,e)=>{if(t.batch&&n.name==="sqlite"){await t.batch(e.map(r=>n.render(r)));return}for(const r of e)await u(t,n,r)},pt=async(t,n,e)=>{const r=e.unique?s`UNIQUE `:s``,o=e.concurrently===!0&&n.name==="postgres"?s`CONCURRENTLY `:s``;if(n.name==="mysql"){try{await u(t,n,s`CREATE ${r}INDEX ${s.identifier(e.name)} ON ${s.identifier(e.table)} (${e.columns})`)}catch(a){const i=a;if(i.errno!==1061&&i.code!=="ER_DUP_KEYNAME"&&i.code!==1061)throw a}return}await u(t,n,s`CREATE ${r}INDEX ${o}IF NOT EXISTS ${s.identifier(e.name)} ON ${s.identifier(e.table)} (${e.columns})`)},ht=async(t,n,e,r)=>{if(n.name!=="mysql"){await u(t,n,s`DROP INDEX IF EXISTS ${s.identifier(r)}`);return}try{await u(t,n,s`DROP INDEX ${s.identifier(r)} ON ${s.identifier(e)}`)}catch(o){const a=o;if(a.errno!==1091&&a.code!=="ER_CANT_DROP_FIELD_OR_KEY"&&a.code!==1091)throw o}},_t=async(t,n,e,r)=>{switch(n.name){case"mysql":return(await m(t,n,s`SELECT 1 AS ${s.identifier("present")} FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ${e} AND index_name = ${r} LIMIT 1`)).length>0?"valid":"absent";case"postgres":{const o=await m(t,n,s`SELECT indisvalid FROM pg_index WHERE indexrelid = to_regclass(quote_ident(${r}))`);return o.length===0?"absent":o[0]?.indisvalid===!0?"valid":"invalid"}default:return(await m(t,n,s`SELECT 1 AS ${s.identifier("present")} FROM sqlite_master WHERE type = 'index' AND name = ${r}`)).length>0?"valid":"absent"}},Ot=A,$=t=>{if(t===void 0)return!1;if(t._meta?.column?.notNull===!1)return!0;switch(t.kind){case"any":case"null":return!0;case"literal":return t._meta?.value===null;case"optional":return $(t._meta?.inner);case"union":return t._meta?.members?.some(n=>$(n))===!0;default:return!1}},Q=t=>t.kind==="optional"&&!$(t),h=new WeakMap,M=t=>{let n=h.get(t);return n===void 0&&(n=Object.entries(t.shape).map(([e,r])=>[e,J(r),Q(r)]),h.set(t,n)),n},_=new WeakMap,Y=(t,n)=>{let e=_.get(t);return e===void 0&&(e=new Map(M(t).map(([r,o])=>[r,o])),_.set(t,e)),e.get(n)},Tt=(t,n,e)=>A(e,Y(t,n)),Z=(t,n)=>{const e={};for(const[r,o,a]of M(t)){const i=n[r];i===void 0||a&&i===null||(e[r]=x(i,o))}return e._id=n.id,e._creationTime=n._creationTime,e},P=(t,n)=>n?Z(t,n):null,At=(t,n)=>{const e=[];for(const r of n){const o=P(t,r);o&&e.push(o)}return e},O=500,tt=(t,n,e,r,o)=>{const a=s`${s.identifier(e)}.${s.identifier("id")}`,i=r===void 0?s``:s` WHERE ${a} > ${r}`;return m(t,n,s`SELECT * FROM ${s.identifier(e)}${i} ORDER BY ${a} ASC LIMIT ${s.raw(String(o))}`)},gt=async(t,n,e,r,o,a={})=>{let i=a.after,c=a.limit,l=!0;for(;l&&(c===void 0||c>0);){const E=c===void 0?O:Math.min(O,c),f=await tt(t,n,r,i,E);for(const F of f){const N=P(e,F);N&&await o(N)}i=f.at(-1)?.id,l=f.length===E,c=c===void 0?void 0:c-f.length}};export{O as B,at as O,u as a,d as b,pt as c,ft as d,St as e,P as f,ht as g,At as h,_t as i,Ot as j,tt as k,gt as l,ct as m,dt as n,ut as o,it as p,m as q,Nt as r,Tt as s,mt as t,$t as u,z as v,ot as w,Et as x,lt as y,Z as z};
@@ -0,0 +1 @@
1
+ import{LunoraError as b}from"@lunora/errors";import{bigintSqlKey as m,float64SqlKey as d,decodeBigintSqlKey as g,BIGINT_KEY_DIGITS as E,decodeFloat64SqlKey as _}from"@lunora/shard-engine";import{WIRE_TAG as y,needsWireEncoding as l,encodeWire as I,decodeWire as N}from"@lunora/wire";const S=t=>{const{value:e}=t._meta??{};if(e===null)return"null";switch(typeof e){case"bigint":case"boolean":case"number":case"string":return typeof e;default:return t.kind}},p=t=>{if(t.kind==="literal")return S(t);if(t.kind!=="optional")return t.kind;const e=t._meta?.inner;return e?p(e):t.kind},n=y,s="#",o="$",c=y+s,a=y,u=(t,e)=>{if(!t.startsWith(n))return e(t);const r=t.slice(n.length);return r.startsWith(s)?_(r.slice(s.length))??t:r.startsWith(o)?r.slice(o.length):N(e(r))},h=new Set(["any","from","union"]),W=(t,e)=>{if(!(e===void 0||!h.has(e)))return typeof t=="number"?c+d(t):typeof t=="string"?t.startsWith(n)?n+o+t:void 0:typeof t=="boolean"?n+JSON.stringify(t):void 0},A=t=>t instanceof ArrayBuffer?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice().buffer:Array.isArray(t)?Uint8Array.from(t).buffer:t,R=(t,e)=>{const r=W(t,e);if(r!==void 0)return r;if(typeof t=="boolean")return t?1:0;if(t===null||typeof t=="string"||typeof t=="number")return t;if(typeof t=="bigint")return m(t);if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);try{return l(t)?n+JSON.stringify(I(t)):JSON.stringify(t)}catch(i){throw new b("BAD_REQUEST",`this value cannot be stored: ${i instanceof Error?i.message:String(i)}`)}},f=t=>{try{return JSON.parse(t)}catch{return t}},G=t=>{if(typeof t!="string"||!t.startsWith(n)||t.startsWith(c))return;const e=f(t.slice(n.length));return typeof e=="number"?c+d(e):void 0},P=t=>t!==void 0&&h.has(t),B=t=>{if(typeof t!="string")return t;const e=g(t);if(e!==void 0)return e;try{return BigInt(t)}catch{return t}},D=t=>p(t),q=(t,e)=>{if(t===null)return t;switch(e){case"any":case"from":case"union":return typeof t!="string"?t:t.startsWith("{")||t.startsWith("[")||t.startsWith(n)?u(t,f):g(t)??t;case"array":case"geoPoint":case"object":case"record":return typeof t=="string"?u(t,f):t;case"bigint":return B(t);case"boolean":return t===0||t===1?t===1:t;case"bytes":return A(t);default:return t}},J=E+1;export{J as B,a as U,D as a,c as b,q as c,B as d,p as e,P as i,G as r,R as s,f as t};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/sql-store",
3
- "version": "1.0.0-alpha.21",
3
+ "version": "1.0.0-alpha.210",
4
4
  "description": "Internal dialect-parameterized SQL store core for Lunora .global() backends (D1, PlanetScale)",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -50,8 +50,10 @@
50
50
  "access": "public"
51
51
  },
52
52
  "dependencies": {
53
- "@lunora/do": "1.0.0-alpha.21",
54
- "drizzle-orm": "^0.45.2"
53
+ "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
54
+ "@lunora/shard-engine": "1.0.0-alpha.161",
55
+ "@lunora/wire": "1.0.0-alpha.2",
56
+ "drizzle-orm": "1.0.0-rc.5"
55
57
  },
56
58
  "engines": {
57
59
  "node": "^22.15.0 || >=24.11.0"