@lunora/sql-store 1.0.0-alpha.84 → 1.0.0-alpha.85

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{createSqlCtxDb as o,readSqlCdcChanges as a,runSqlAggregateMigrations as t,runSqlCdcMigration as i,runSqlGlobalTableMigrations as l,runSqlRankMigrations as n,trimSqlCdcChanges as S}from"./packem_shared/createSqlCtxDb-CRX3OS05.mjs";import{b as s,r as d}from"./packem_shared/ctx-db-search-Cl6zlJ11.mjs";import{SEARCH_STATE_TABLE as q,migrateSearchState as f}from"./packem_shared/SEARCH_STATE_TABLE-DA3LgCT0.mjs";import{decodeBigint as C,effectiveColumnKind as x,sqliteDecode as b,sqliteEncode as u,tryJsonParse as h}from"./packem_shared/decodeBigint-B4wY6fcF.mjs";import{decodeGlobalRow as M}from"./packem_shared/decodeGlobalRow-BKIjk_Zk.mjs";export{q as SEARCH_STATE_TABLE,s as backfillSqlSearchIndexes,o as createSqlCtxDb,C as decodeBigint,M as decodeGlobalRow,x as effectiveColumnKind,f as migrateSearchState,a as readSqlCdcChanges,t as runSqlAggregateMigrations,i as runSqlCdcMigration,l as runSqlGlobalTableMigrations,n as runSqlRankMigrations,d as runSqlSearchMigrations,b as sqliteDecode,u as sqliteEncode,S as trimSqlCdcChanges,h as tryJsonParse};
1
+ import{createSqlCtxDb as o,readSqlCdcChanges as a,runSqlAggregateMigrations as t,runSqlCdcMigration as i,runSqlGlobalTableMigrations as l,runSqlRankMigrations as n,trimSqlCdcChanges as S}from"./packem_shared/createSqlCtxDb-BUEDZFiZ.mjs";import{b as s,r as d}from"./packem_shared/ctx-db-search-DlItpO6A.mjs";import{SEARCH_STATE_TABLE as q,migrateSearchState as f}from"./packem_shared/SEARCH_STATE_TABLE-DA3LgCT0.mjs";import{decodeBigint as C,effectiveColumnKind as x,sqliteDecode as b,sqliteEncode as u,tryJsonParse as h}from"./packem_shared/decodeBigint-B4wY6fcF.mjs";import{decodeGlobalRow as M}from"./packem_shared/decodeGlobalRow-BKIjk_Zk.mjs";export{q as SEARCH_STATE_TABLE,s as backfillSqlSearchIndexes,o as createSqlCtxDb,C as decodeBigint,M as decodeGlobalRow,x as effectiveColumnKind,f as migrateSearchState,a as readSqlCdcChanges,t as runSqlAggregateMigrations,i as runSqlCdcMigration,l as runSqlGlobalTableMigrations,n as runSqlRankMigrations,d as runSqlSearchMigrations,b as sqliteDecode,u as sqliteEncode,S as trimSqlCdcChanges,h as tryJsonParse};
@@ -1 +1 @@
1
- import{b as S,c as s,a as i,r as l}from"./ctx-db-search-Cl6zlJ11.mjs";import"./SEARCH_STATE_TABLE-DA3LgCT0.mjs";import"./decodeGlobalRow-BKIjk_Zk.mjs";export{S as backfillSqlSearchIndexes,s as createSearchSync,i as runSqlSearch,l as runSqlSearchMigrations};
1
+ import{b as S,c as s,a as i,r as l}from"./ctx-db-search-DlItpO6A.mjs";import"./SEARCH_STATE_TABLE-DA3LgCT0.mjs";import"./decodeGlobalRow-BKIjk_Zk.mjs";export{S as backfillSqlSearchIndexes,s as createSearchSync,i as runSqlSearch,l as runSqlSearchMigrations};
@@ -1 +1 @@
1
- import{LunoraError as v}from"@lunora/errors";import{c as Tt,r as gt,R as vt,j as St,D as bt,M as It,a as At,B as Ct,y as Lt,_ as kt}from"./ctx-db-search-Cl6zlJ11.mjs";import{b as xn}from"./ctx-db-search-Cl6zlJ11.mjs";import{literalInList as Nt,throwingScheduler as Mt,aggregateTableName as z,rankTableName as ee,hasTrigger as Dt,runRowValidators as Ne,assertFlatPredicate as Je,mergeWhere as q,sortColumnName as X,resolveRankPartition as Qe,encodePartitionKey as Se,decodeCursor as Ze,RANK_TIEBREAK as he,CountRlsUnsupportedError as et,normalizeIdStructurally as qt,assertValidClientId as xt,aggregateSqlFunction as fe,softDeleteScope as we,compileWhereSql as _e,normalizeOrderKeys as Bt,buildSeekWhere as Ft,resolveRelationPredicates as tt,resolveWith as nt,relationHooks as ot,applySelect as it,encodeCursor as Ot,NotFoundError as Wt,applyOnDelete as Ut,ConflictError as $e,normalizeCountArgument as jt,selectIndexForCount as Pt,encodeAggregateKey as Y,selectIndexForAggregate as Kt,readAggregateValue as Me,runTriggers as Ht,matchesRankStaticWhere as rt,selectIndexForGroupBy as Vt,fanOutScalarCounts as Gt,matchesStaticWhere as De,foldAggregateTally as Yt,coerceAggregateNumber as qe,NotUniqueError as zt}from"@lunora/shard-engine";import{sql as e}from"drizzle-orm";import{migrateSearchState as Xt}from"./SEARCH_STATE_TABLE-DA3LgCT0.mjs";import{queryAll as A,queryRun as k,createIndexIfNotExists as Be,decodeRow as te,serializeColumnValue as H,columnRefSql as x,decodeRows as Jt,forEachRowPaged as st,queryBatch as at}from"./decodeGlobalRow-BKIjk_Zk.mjs";import{decodeGlobalRow as Fn}from"./decodeGlobalRow-BKIjk_Zk.mjs";import{effectiveColumnKind as be}from"./decodeBigint-B4wY6fcF.mjs";const Qt=(c,_)=>{if(c.size<_)return;const f=c.keys().next().value;f!==void 0&&c.delete(f)},ct=50,Zt=(c,_={})=>{const f=_.maxBatch??ct,r=Number.isInteger(f)&&f>0?f:ct,p=new Map;let l=!1;const a=async(m,b)=>{const S=[...b.keys()];for(let L=0;L<S.length;L+=r){const M=S.slice(L,L+r);try{const W=await c(m,M);for(const V of M){const U=W.get(V);for(const Ae of b.get(V)??[])Ae.resolve(U)}}catch(W){for(const V of M)for(const U of b.get(V)??[])U.reject(W)}}},R=()=>{l=!1;const m=[...p.entries()];p.clear();for(const[b,S]of m)a(b,S).catch(()=>{})};return{async load(m,b){return new Promise((S,L)=>{let M=p.get(m);M||(M=new Map,p.set(m,M));const W=M.get(b);W?W.push({reject:L,resolve:S}):M.set(b,[{reject:L,resolve:S}]),l||(l=!0,queueMicrotask(R))})}}},en=new Set(["_id","id"]),Fe=(c,_,f)=>c==="postgres"?e`${_} IS NOT DISTINCT FROM ${f}`:c==="mysql"?e`${_} <=> ${f}`:e`${_} IS ${f}`,tn=c=>{const _=c.map(f=>e`${x(f.field)} ${e.raw(f.direction==="desc"?"DESC":"ASC")}`);return c.some(f=>en.has(f.field))||_.push(e`${x("id")} ASC`),e.join(_,e`, `)},lt=50,Oe=c=>{const _=[];for(const[f,r]of Object.entries(c.shape)){const p=r._meta?.column;p&&_.push([f,p])}return _},nn=(c,_,f)=>{const r={..._};for(const[p,l]of Oe(c)){if(l.serverDefault){r[p]=l.serverDefault({auth:f});continue}r[p]===void 0&&(l.defaultFn?r[p]=l.defaultFn():"defaultValue"in l&&(r[p]=l.defaultValue))}return r},ut=(c,_,f,r)=>{for(const[p,l]of Oe(c)){if(l.serverDefault){p in _&&(f[p]=l.serverDefault({auth:r}));continue}l.onUpdateFn&&!(p in _)&&(f[p]=l.onUpdateFn())}},on=128,rn=()=>{const c=new Map;return{delete:_=>{c.delete(_)},get:_=>{const f=c.get(_);if(f!==void 0)return c.delete(_),c.set(_,f),f},set:(_,f)=>{c.has(_)?c.delete(_):Qt(c,on),c.set(_,f)}}},sn=async(c,_,f,r,p)=>{const l=p.get(r);if(l!==void 0)return l;const a=Object.entries(f.tables).filter(([,m])=>m.shardMode===void 0||m.shardMode.kind==="global").map(([m])=>m),R=await Promise.all(a.map(async m=>({found:(await A(c,_,e`SELECT 1 FROM ${e.identifier(m)} WHERE ${e.identifier("id")} = ${r} LIMIT 1`)).length>0,tableName:m})));for(const m of R)if(m.found)return p.set(r,m.tableName),m.tableName},ne=c=>c==null?null:Number(c),an=(c,_)=>_.map(f=>{const r={};for(const p of c)r[p]=f[p]??null;return{key:r,value:ne(f.value)}}),cn=(c,_,f)=>[...c.partitionBy??[],...c.sortBy.map(p=>p.field),...c.where?Object.keys(c.where):[]].every(p=>_[p]===f[p]),dt=c=>c.length===1?c[0]:e`(${e.join(c,e` AND `)})`,Z=c=>e.join(c.map(_=>e`${e.identifier(_)}`),e`, `),oe=c=>e.join(c.map(_=>e`${_}`),e`, `),ln=(c,_,f,r,p)=>{const l=[];for(let a=0;a<f.length+1;a+=1){const R=f.slice(0,a).map(S=>Fe(c,e`${e.identifier(S)}`,r[S])),m=f[a],b=_.sortBy[a];a<f.length&&m!==void 0&&b!==void 0?R.push(e`${e.identifier(m)} ${e.raw(b.direction==="desc"?">":"<")} ${r[m]}`):R.push(e`${e.identifier(he)} < ${p}`),l.push(dt(R))}return l.length>0?e.join(l,e` OR `):void 0},un=(c,_,f)=>{if(f.length!==_.length)return;const r=[];for(const[p,l]of _.entries()){const a=[];for(let R=0;R<p;R+=1){const m=_[R];m!==void 0&&a.push(Fe(c,e`${e.identifier(m.column)}`,f[R]))}a.push(e`${e.identifier(l.column)} ${e.raw(l.direction==="desc"?"<":">")} ${f[p]}`),r.push(dt(a))}return e`(${e.join(r,e` OR `)})`},dn=(c,_)=>{if(c.sortBy.length===0)throw new v("INTERNAL",`rankIndex "${c.name}" requires at least one "sortBy" column for stable pagination`);const f=[{column:"__partition__",direction:"asc"}];for(const[r,p]of c.sortBy.entries())f.push({column:_[r]??X(r),direction:p.direction});return f.push({column:he,direction:"asc"}),f},fn=async(c,_,f,r,p)=>{const a=[];for(let S=0;S<p.length;S+=50)a.push(p.slice(S,S+50));const R=await Promise.all(a.map(async S=>A(c,_,e`SELECT * FROM ${e.identifier(r)} WHERE ${e.identifier("id")} IN (${oe(S)})`))),m=new Map;for(const S of R)for(const L of S)m.set(L.id,L);const b=[];for(const S of p){const L=te(f,m.get(S));L&&b.push(L)}return b},wn=c=>{const _=JSON.stringify(c),f=new TextEncoder().encode(_);let r="";for(const p of f)r+=String.fromCodePoint(p);return btoa(r)},_n=(c,_)=>_.columnType(be(c)),$n=(c,_,f)=>{const r=[];for(const[a,R]of Object.entries(_.shape)){if(!R._meta?.column)continue;const m=R._meta.column.notNull&&R.kind!=="optional"?" NOT NULL":"";r.push(e`${e.identifier(a)} ${e.raw(`${_n(R,f)}${m}`)}`)}const p=f.frameworkColumns().map(a=>e`${e.identifier(a.name)} ${e.raw(a.type)}`),l=p.length+r.length;if(f.maxTableColumns!==void 0&&l>f.maxTableColumns)throw new v("VALIDATION_ERROR",`@lunora/sql-store: global table "${c}" needs ${String(l)} columns, over this engine's ${String(f.maxTableColumns)}-column limit — split the table, or move the extra fields into one object field`);return e.join([...p,...r],e`, `)},hn=async(c,_,f,r)=>{const p=l=>{const a=x(l),R=f.shape[l],m=R&&r.indexKeyPrefix?r.indexKeyPrefix(be(R)):void 0;return m===void 0?a:e`${a}(${e.raw(String(m))})`};for(const l of f.indexes){const a=e.join(l.fields.map(R=>p(R)),e`, `);await Be(c,r,{columns:a,name:`${_}_${l.name}`,table:_,unique:l.unique??!1})}for(const[l,a]of Oe(f))a.unique&&await Be(c,r,{columns:p(l),name:`${_}_unique_${l}`,table:_,unique:!0})},yn=async(c,_,f)=>{for(const[r,p]of Object.entries(_.tables)){if(p.shardMode?.kind!=="global")continue;const l=$n(r,p,f);await k(c,f,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (${l})`),await hn(c,r,p,f)}},En=async(c,_,f)=>{const{integer:r,key:p,real:l}=f.companionTypes;for(const[a,R]of Object.entries(_.tables)){const m=R.aggregateIndexes;if(!(!m||m.length===0))for(const b of m){const S=z(a,b.name);await k(c,f,e`CREATE TABLE IF NOT EXISTS ${e.identifier(S)} (${e.identifier("__key__")} ${e.raw(p)} PRIMARY KEY, ${e.identifier("__value__")} ${e.raw(l)}, ${e.identifier("__count__")} ${e.raw(r)} NOT NULL DEFAULT 0)`),f.name==="sqlite"&&((await A(c,f,e`PRAGMA table_info(${e.identifier(S)})`)).some(M=>M.name==="__count__")||await k(c,f,e`ALTER TABLE ${e.identifier(S)} ADD COLUMN ${e.identifier("__count__")} ${e.raw(r)} NOT NULL DEFAULT 0`))}}},xe=(c,_,f,r)=>{const p=c.name==="mysql"&&r?e`${e.identifier(_)}(191)`:e`${e.identifier(_)}`;return e`${p} ${e.raw(f)}`},pn=(c,_,f)=>{const r=[xe(c,"__partition__","ASC",!0)];for(const[p,l]of _.sortBy.entries()){const a=f.shape[l.field],R=a!==void 0&&c.indexKeyPrefix?.(be(a))!==void 0;r.push(xe(c,X(p),l.direction==="desc"?"DESC":"ASC",R))}return r.push(xe(c,"__id__","ASC",!0)),r},mn=(c,_,f)=>_.sortBy.map((r,p)=>{const l=f.shape[r.field],a=c.columnType(l?be(l):void 0);return e`${e.identifier(X(p))} ${e.raw(a)}`}),Rn=async(c,_,f)=>{const{key:r}=f.companionTypes;for(const[p,l]of Object.entries(_.tables)){const a=l.rankIndexes;if(!(!a||a.length===0))for(const R of a){const m=ee(p,R.name),b=mn(f,R,l),S=b.length>0?e`, ${e.join(b,e`, `)}`:e``;await k(c,f,e`CREATE TABLE IF NOT EXISTS ${e.identifier(m)} (${e.identifier("__id__")} ${e.raw(r)} PRIMARY KEY, ${e.identifier("__partition__")} ${e.raw(r)} NOT NULL${S})`);const L=pn(f,R,l),M=`${p}__rank_${R.name}__btree`;await Be(c,f,{columns:e.join(L,e`, `),name:M,table:m,unique:!1})}}},Ie="__cdc_log",Tn=async(c,_)=>{const{autoincrementPrimaryKey:f,key:r,real:p,text:l}=_.companionTypes;await k(c,_,e`CREATE TABLE IF NOT EXISTS ${e.identifier(Ie)} (${e.identifier("seq")} ${e.raw(f)}, ${e.identifier("ts")} ${e.raw(p)} NOT NULL, ${e.identifier("table")} ${e.raw(r)} NOT NULL, ${e.identifier("id")} ${e.raw(r)} NOT NULL, ${e.identifier("op")} ${e.raw(r)} NOT NULL, ${e.identifier("doc")} ${e.raw(l)})`)},gn=async(c,_,f,r,p,l,a)=>{await k(c,a,e`INSERT INTO ${e.identifier(Ie)} (${e.identifier("ts")}, ${e.identifier("table")}, ${e.identifier("id")}, ${e.identifier("op")}, ${e.identifier("doc")}) VALUES (${_}, ${f}, ${r}, ${p}, ${l===void 0?null:JSON.stringify(l)})`)},kn=async(c,_,f)=>{const r=_.sinceSeq??0,p=Math.max(1,Math.min(_.limit??1e3,1e4)),a=(await A(c,f,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(Ie)} WHERE seq > ${r} ORDER BY seq ASC LIMIT ${e.raw(String(p))}`)).map(R=>{const{doc:m}=R,b={id:String(R.id),op:String(R.op),seq:Number(R.seq),table:String(R.table),ts:Number(R.ts)};return typeof m=="string"?{...b,doc:JSON.parse(m)}:b});return{changes:a,cursor:a.at(-1)?.seq??r}},Nn=async(c,_,f)=>{await k(c,f,e`DELETE FROM ${e.identifier(Ie)} WHERE ${e.identifier("seq")} <= ${_}`)},Mn=c=>{const{crossShardCounter:_,crossShardReader:f,exec:r,maxRelationKeys:p,schema:l}=c,{dialect:a}=c,{isUniqueViolation:R}=a,m={fieldRef:x,serialize:H,...a.name==="mysql"?{containsExpr:(t,n)=>e`LOCATE(${n}, ${t}) > 0`}:{},...a.name==="postgres"?{containsExpr:(t,n)=>e`strpos(${t}, ${n}) > 0`}:{},...a.name==="sqlite"?{}:{inList:Nt}},b=(t,n)=>Fe(a.name,t,n),S=t=>{const n=Z(t.columns),o=oe(t.values),i=u=>a.name==="mysql"?e`VALUES(${e.identifier(u)})`:e`excluded.${e.identifier(u)}`,s=u=>a.name==="postgres"?e`${e.identifier(t.table)}.${e.identifier(u)}`:e`${e.identifier(u)}`,w=e.join(Object.entries(t.set(i,s)).map(([u,y])=>e`${e.identifier(u)} = ${y}`),e`, `),h=a.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${w}`:e`ON CONFLICT(${e.identifier(t.conflictKey)}) DO UPDATE SET ${w}`;return e`INSERT INTO ${e.identifier(t.table)} (${n}) VALUES (${o}) ${h}`},L=c.clock??(()=>Date.now()),M=c.idGenerator??(()=>crypto.randomUUID()),W=c.cdc??!1,V=c.auth??{identity:null,userId:null},U=async(t,n,o,i)=>{W&&await gn(r,L(),t,n,o,i,a)},Ae=c.scheduler??Mt,Ce=rn();let ye=0,Le;const j=async()=>(Le??=(async()=>{await yn(r,l,a),await En(r,l,a),await Rn(r,l,a),await Xt(r,a),await gt(r,l,a),W&&await Tn(r,a)})().catch(t=>{throw Le=void 0,t}),Le),ie=async(t,n)=>{await j();const o=await sn(r,a,l,t,Ce);if(!(n!==void 0&&o!==n))return o},re=new Map,We=async(t,n)=>{const o=z(t,n);return(await A(r,a,a.tableExists(o))).length>0},Ee=async(t,n)=>{const o=`${t}::${n.name}`,i=re.get(o);if(i!==void 0)return i;if(!await We(t,n.name))return re.set(o,!1),!1;const w=l.tables[t];if(!w)return re.set(o,!1),!1;const h=n.by??[],u=new Map;await st(r,a,w,t,$=>{if(n.where&&!De($,n.where))return;const E=Y(h,$);Yt(u,E,n,$)});const y=z(t,n.name);await k(r,a,e`DELETE FROM ${e.identifier(y)}`);const d=[];for(const[$,E]of u)d.push(e`INSERT INTO ${e.identifier(y)} (${e.identifier("__key__")}, ${e.identifier("__value__")}, ${e.identifier("__count__")}) VALUES (${$}, ${E.value}, ${E.count})`);return await at(r,a,d),re.set(o,!0),!0},ft=async(t,n,o)=>{const i=fe(n.op),s=n.field??"",w=[];for(const y of n.by??[]){const d=H(o[y]??null);w.push(d===null?e`${x(y)} IS NULL`:e`${x(y)} = ${d}`)}for(const[y,d]of Object.entries(n.where??{})){const $=d!==null&&typeof d=="object"&&!Array.isArray(d)?d.eq:d,E=H($);w.push(E===null?e`${x(y)} IS NULL`:e`${x(y)} = ${E}`)}const h=e`SELECT ${e.raw(i)}(${x(s)}) AS value FROM ${e.identifier(t)}`,u=await A(r,a,w.length>0?e`${h} WHERE ${e.join(w,e` AND `)}`:h);return ne(u[0]?.value)},wt=async(t,n)=>{await k(r,a,e`DELETE FROM ${e.identifier(t)} WHERE ${e.identifier("__key__")} = ${n} AND ${e.identifier("__count__")} <= 0`)},_t=async(t,n,o,i)=>{const s=z(t,n.name),{op:w}=n,h=n.field??"",u=o&&(!n.where||De(o,n.where))?o:void 0,y=i&&(!n.where||De(i,n.where))?i:void 0;if(!(!u&&!y)){if(w==="count"||w==="sum"||w==="avg"){const d=new Set;for(const[$,E]of[[u,-1],[y,1]]){if(!$)continue;const g=w==="count"?1:qe($[h]);if(g===void 0)continue;const T=Y(n.by??[],$);d.add(T),await k(r,a,S({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(C,I)=>({__count__:e`${I("__count__")} + ${C("__count__")}`,__value__:w==="count"?e`${I("__value__")} + ${C("__value__")}`:e`COALESCE(${I("__value__")}, 0) + ${C("__value__")}`}),table:s,values:[T,E*g,E]}))}for(const $ of d)await wt(s,$);return}if(u){const d=Y(n.by??[],u),$=qe(u[h]),g=(await A(r,a,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(s)} WHERE ${e.identifier("__key__")} = ${d}`))[0],T=ne(g?.value),C=(g?.count??0)-1;if(C<=0)await k(r,a,e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__key__")} = ${d}`);else if(g&&$!==void 0&&T!==null&&$===T){const I=await ft(t,n,u);await k(r,a,e`UPDATE ${e.identifier(s)} SET ${e.identifier("__value__")} = ${I}, ${e.identifier("__count__")} = ${C} WHERE ${e.identifier("__key__")} = ${d}`)}else await k(r,a,e`UPDATE ${e.identifier(s)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${d}`)}if(y){const d=Y(n.by??[],y),$=qe(y[h]);if($===void 0)await k(r,a,S({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(E,g)=>({__count__:e`${g("__count__")} + 1`}),table:s,values:[d,null,1]}));else{const E=w==="min"?"MIN":"MAX";await k(r,a,S({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(g,T)=>({__count__:e`${T("__count__")} + 1`,__value__:e`${e.raw(E)}(COALESCE(${T("__value__")}, ${g("__value__")}), ${g("__value__")})`}),table:s,values:[d,$,1]}))}}}},pe=async t=>{const n=l.tables[t]?.aggregateIndexes;if(!(!n||n.length===0))for(const o of n)await Ee(t,o)},se=async(t,n,o)=>{const i=l.tables[t]?.aggregateIndexes;if(!(!i||i.length===0))for(const s of i){const w=`${t}::${s.name}`;(re.get(w)??await We(t,s.name))&&await _t(t,s,n,o)}},ae=new Map,Ue=async(t,n)=>{const o=ee(t,n);return(await A(r,a,a.tableExists(o))).length>0},ke=async(t,n)=>{const o=`${t}::rank::${n.name}`,i=ae.get(o);if(i!==void 0)return i;if(!await Ue(t,n.name))return ae.set(o,!1),!1;const w=l.tables[t];if(!w)return ae.set(o,!1),!1;const h=ee(t,n.name);await k(r,a,e`DELETE FROM ${e.identifier(h)}`);const u=n.sortBy.map((E,g)=>X(g)),y=Z(["__id__","__partition__",...u]),d=[];await st(r,a,w,t,E=>{if(n.where&&!rt(E,n.where))return;const g=Se(n.partitionBy??[],E),T=n.sortBy.map(C=>H(E[C.field]??null));d.push([E._id,g,...T])});const $=d.map(E=>e`INSERT INTO ${e.identifier(h)} (${y}) VALUES (${oe(E)})`);return await at(r,a,$),ae.set(o,!0),!0},me=async t=>{const n=l.tables[t]?.rankIndexes;if(!(!n||n.length===0))for(const o of n)await ke(t,o)},J=async(t,n,o,i)=>{const s=l.tables[t],w=s?.rankIndexes;if(!w||w.length===0)return;const h=s?.softDeleteMode?.field,u=h===void 0||i===void 0?void 0:i[h],y=u!=null;for(const d of w){if(o!==void 0&&i!==void 0&&cn(d,o,i))continue;const $=`${t}::rank::${d.name}`;if(!(ae.get($)??await Ue(t,d.name)))continue;const T=ee(t,d.name);if(o&&await k(r,a,e`DELETE FROM ${e.identifier(T)} WHERE ${e.identifier("__id__")} = ${n}`),i&&!y){if(d.where&&!rt(i,d.where))continue;const C=d.sortBy.map((B,G)=>X(G)),I=Z(["__id__","__partition__",...C]),F=Se(d.partitionBy??[],i),N=d.sortBy.map(B=>H(i[B.field]??null));await k(r,a,e`INSERT INTO ${e.identifier(T)} (${I}) VALUES (${oe([n,F,...N])})`)}}},ce=Tt({dialect:a,exec:r,schema:l}),je=new Set;for(const[t,n]of Object.entries(l.tables))for(const o of Object.values(n.triggerMap??{}))je.add(`${t} ${o.timing} ${o.op}`);const P=(t,n,o)=>je.has(`${t} ${n} ${o}`);let Pe;const K=async(t,n,o)=>{if(ye+=1,ye>lt)throw ye-=1,new $e(`trigger recursion exceeded ${String(lt)} levels on "${o.table}" — check for a self-triggering write`,"trigger");try{await Ht({ctx:Pe,event:o,op:n,schema:l,tableName:o.table,timing:t})}finally{ye-=1}},$t=async(t,n)=>{try{await k(r,a,n)}catch(o){throw R(o)?new $e(`unique constraint violation on "${t}"`,"unique"):o}},Re=async(t,n)=>(await A(r,a,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} = ${n}`))[0],Te=async(t,n,o,i)=>{if(i===void 0)return;const s=e.join(Object.keys(i).map(u=>b(e`${e.identifier(u)}`,i[u])),e` AND `),w=n==="UPDATE"?e`UPDATE ${e.identifier(t)} SET ${o} WHERE ${s}`:e`DELETE FROM ${e.identifier(t)} WHERE ${s}`,h=()=>{throw new $e(`optimistic concurrency conflict on "${t}" — the row changed during this mutation; refetch and retry`,"occ")};try{if(a.supportsReturning)(await A(r,a,e`${w} RETURNING ${e.identifier("id")}`)).length===0&&h();else{const u=await k(r,a,w);(a.affectedRows?a.affectedRows(u??{rowsAffected:0}):0)===0&&h()}}catch(u){throw R(u)?new $e(`unique constraint violation on "${t}"`,"unique"):u}},ht=(t,n,o,i)=>{const s=Object.keys(t.shape);return{columns:["id","_creationTime",...s],values:[n,o,...s.map(w=>H(i[w]??null))]}},yt=async(t,n,o,i)=>{const s=Vt(n,o.op,o.field,i.by,i.where);if(!s||!await Ee(t,s.index))return;const h=z(t,s.index.name),u=Object.keys(s.partial);if(u.length===(s.index.by??[]).length&&u.length>0){const d=Y(s.index.by??[],s.partial),$=await A(r,a,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(h)} WHERE ${e.identifier("__key__")} = ${d}`);if($.length===0)return[];const E=$[0];return[{key:{...s.partial},value:Me(o.op,{count:E.count,value:ne(E.value)})}]}return u.length>0?void 0:(await A(r,a,e`SELECT ${e.identifier("__key__")} AS key, ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(h)}`)).map(d=>{const $=d;return{key:JSON.parse($.key),value:Me(o.op,{count:$.count,value:ne($.value)})}})},Ke=t=>{const n=l.tables[t]?.shardMode?.kind;return n==="shardBy"||n==="root"},He=t=>{throw new v("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`)},Et=(t,n)=>{if(n?.relationMask!==void 0&&n.with!==void 0&&Object.keys(n.with).length>0)throw new v("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 o={};if(n?.relationBaseWhere)for(const i of Object.keys(l.tables)){const s=n.relationBaseWhere(i);s!==void 0&&(o[i]=s)}return{orderBy:n?.orderBy,relationPolicies:o,where:q(n?.baseWhere,n?.where),with:n?.with}},Ve=(t,n)=>Ke(t)?f?f(t,Et(t,n)):He(t):O.findMany(t,n),ge=(t,n,o)=>tt(t,{fetcher:Ve,maxRelationKeys:p,relationBaseWhere:o,schema:l,tableName:n}),pt=Zt(async(t,n)=>{const o=await A(r,a,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} IN (${oe(n)})`),i=new Map;for(const s of o){const{id:w}=s;typeof w=="string"&&i.set(w,s)}return i}),O={async aggregate(t,n){const o=l.tables[t];if(!o)throw new v("INTERNAL",`unknown table: ${t}`);if(await j(),fe(n.op),n.op==="count")return O.count(t,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new v("INTERNAL",`aggregate(${t}, { op: "${n.op}" }): "field" is required for non-count reducers`);const i=we(o.softDeleteMode,void 0),s=q(q(n.baseWhere,n.where),i),w=await ge(s,t,n.relationBaseWhere),h=w!==s;if(o.aggregateIndexes&&!n.baseWhere&&!h&&!i){const g=Kt(o.aggregateIndexes,n.op,n.field,n.where);if(g&&await Ee(t,g.index)){const C=Y(g.index.by??[],g.key),I=z(t,g.index.name),N=(await A(r,a,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(I)} WHERE ${e.identifier("__key__")} = ${C}`))[0];return Me(n.op,N===void 0?void 0:{count:N.count,value:ne(N.value)})}}const u=_e(w,m),y=e.raw(fe(n.op)),d=e`SELECT ${y}(${x(n.field)}) AS value FROM ${e.identifier(t)}`,E=(await A(r,a,u?e`${d} WHERE ${u}`:d))[0]?.value;return E==null?null:Number(E)},async count(t,n){const o=l.tables[t];if(!o)throw new v("INTERNAL",`unknown table: ${t}`);await j();const i=jt(n);if(i.restrictsCounts)throw new et(t);const s=we(o.softDeleteMode,void 0),w=q(q(i.baseWhere,i.where),s),h=await ge(w,t,i.relationBaseWhere),u=h!==w;if(o.aggregateIndexes&&!i.baseWhere&&!u&&!s){const E=Pt(o.aggregateIndexes,i.where);if(E&&await Ee(t,E.index)){const T=Y(E.index.by??[],E.key),C=z(t,E.index.name),I=await A(r,a,e`SELECT ${e.identifier("__value__")} AS value FROM ${e.identifier(C)} WHERE ${e.identifier("__key__")} = ${T}`);return Number(I[0]?.value??0)}}const y=_e(h,m),d=e`SELECT COUNT(*) AS count FROM ${e.identifier(t)}`,$=await A(r,a,y?e`${d} WHERE ${y}`:d);return Number($[0]?.count??0)},async delete(t,n,o){const i=await ie(t,n);if(!i)return;const s=l.tables[i];if(!s)return;const w=await Re(i,t),h=te(s,w),u=o?.hard===!0,y=!u&&s.softDeleteMode?s.softDeleteMode.field:void 0;if(!(y&&(!h||h[y]!==null&&h[y]!==void 0))){if(P(i,"before","delete")&&await K("before","delete",{id:t,op:"delete",previous:h??void 0,table:i}),await Ut({deletedId:t,deletedReference:d=>h?.[d],findHolders:async(d,$,E)=>{if(l.tables[d]?.shardMode?.kind==="shardBy")throw new v("INTERNAL",`cross-backend cascade from global '${i}' into shardBy '${d}' is not supported — would require Query Coordinator fan-out across shards`);return(await O.findMany(d,{includeDeleted:u,where:{[$]:E}})).page},onCascade:(d,$)=>O.delete($,void 0,o),onRestrict:d=>{throw new $e(d,"restrict")},onSetNull:(d,$,E)=>O.patch($,{[E]:null}),schema:l,tableName:i}),await pe(i),await me(i),y&&h){const d={...h,[y]:L()},$=e.join(Object.keys(s.shape).map(E=>e`${e.identifier(E)} = ${H(d[E]??null)}`),e`, `);await Te(i,"UPDATE",$,w),await se(i,h,d),await J(i,t,h,void 0),await ce(i,t,d,h),await U(i,t,"update",d),P(i,"after","delete")&&await K("after","delete",{id:t,op:"delete",previous:h,table:i});return}await Te(i,"DELETE",void 0,w),Ce.delete(t),await se(i,h??void 0,void 0),await J(i,t,h??void 0,void 0),await ce(i,t,void 0),await U(i,t,"delete"),P(i,"after","delete")&&await K("after","delete",{id:t,op:"delete",previous:h??void 0,table:i})}},async findFirst(t,n={}){return(await O.findMany(t,{...n,limit:1})).page[0]??null},async findFirstOrThrow(t,n={}){const o=await O.findFirst(t,n);if(o===null)throw new Wt(`findFirstOrThrow: no "${t}" document matched`);return o},async findMany(t,n={}){const o=l.tables[t];if(!o)throw new v("INTERNAL",`unknown table: ${t}`);await j();const i=Bt(n.orderBy),s=n.cursor?Ft(i,Ze(n.cursor)):void 0,w=Ve,h=async(N,B,G,ve)=>{if(Ke(N))return _?Gt(_,N,B,G,ve):He(N);const le=l.tables[N];if(!le)throw new v("INTERNAL",`unknown table: ${N}`);const Q=we(le.softDeleteMode,void 0),D={[B]:{in:G}},ue=q(q(D,ve),Q),mt=await ge(ue,N,void 0),Ge=_e(mt,m),Ye=x(B);let de=e`SELECT ${Ye} AS __fk__, COUNT(*) AS count FROM ${e.identifier(N)}`;Ge&&(de=e`${de} WHERE ${Ge}`),de=e`${de} GROUP BY ${Ye}`;const Rt=await A(r,a,de),ze=new Map;for(const Xe of Rt)ze.set(Xe.__fk__,Number(Xe.count??0));return ze};let u=q(n.baseWhere,n.where);u=q(u,we(o.softDeleteMode,n.includeDeleted)),u=await tt(u,{fetcher:w,maxRelationKeys:p,relationBaseWhere:n.relationBaseWhere,schema:l,tableName:t}),s&&(u=u?{AND:[u,s]}:s);const y=_e(u,m),d=tn(i);let $=e`SELECT * FROM ${e.identifier(t)}`;y&&($=e`${$} WHERE ${y}`),$=e`${$} ORDER BY ${d}`;const E=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;E!==void 0&&($=e`${$} LIMIT ${e.raw(String(E+1))}`);const g=await A(r,a,$),T=Jt(o,g);if(E===void 0)return n.with&&await nt({fetcher:w,groupedCounter:h,parents:T,...ot(n),schema:l,tableName:t,with:n.with}),{continueCursor:null,isDone:!0,page:it(T,n.select,n.with)};const C=T.length>E,I=C?T.slice(0,E):T,F=I.at(-1);return n.with&&await nt({fetcher:w,groupedCounter:h,parents:I,...ot(n),schema:l,tableName:t,with:n.with}),{continueCursor:C&&F?Ot(F,i):null,isDone:!C,page:it(I,n.select,n.with)}},async get(t,n){const o=await ie(t,n);if(!o)return null;const i=l.tables[o];return i?te(i,await pt.load(o,t)):null},async groupBy(t,n){const o=l.tables[t];if(!o)throw new v("INTERNAL",`unknown table: ${t}`);await j();const i=n.agg??{op:"count"};if(fe(i.op),i.op!=="count"&&!i.field)throw new v("INTERNAL",`groupBy(${t}, { agg: { op: "${i.op}" } }): "field" is required for non-count reducers`);const s=we(o.softDeleteMode,void 0),w=q(q(n.baseWhere,n.where),s),h=await ge(w,t,n.relationBaseWhere),u=h!==w;if(o.aggregateIndexes&&!n.baseWhere&&!u&&!s){const T=await yt(t,o.aggregateIndexes,i,n);if(T!==void 0)return T}const y=_e(h,m),d=n.by.map(T=>e`${x(T)} AS ${e.identifier(T)}`);if(i.op==="count")d.push(e`COUNT(*) AS value`);else{if(!i.field)throw new v("INTERNAL",`groupBy(${t}, { agg: { op: "${i.op}" } }): "field" is required for non-count reducers`);d.push(e`${e.raw(fe(i.op))}(${x(i.field)}) AS value`)}const $=e.join(n.by.map(T=>x(T)),e`, `);let E=e`SELECT ${e.join(d,e`, `)} FROM ${e.identifier(t)}`;y&&(E=e`${E} WHERE ${y}`),E=e`${E} GROUP BY ${$}`;const g=await A(r,a,E);return an(n.by,g)},async insert(t,n,o){const i=l.tables[t];if(!i)throw new v("INTERNAL",`unknown table: ${t}`);await j();const s=nn(i,n,V);Ne(i,s);let w,h=!0;o?.clientId!==void 0?(xt(o.clientId),w=o.clientId):o?.allowExplicitId&&typeof s._id=="string"?w=s._id:(w=M(),h=!1);const u=o?.allowExplicitId&&typeof s._creationTime=="number"?s._creationTime:L(),y={...s,_creationTime:u,_id:w};P(t,"before","insert")&&await K("before","insert",{doc:{...y},id:w,op:"insert",table:t}),await pe(t),await me(t);const{columns:d,values:$}=ht(i,w,u,s);return await $t(t,e`INSERT INTO ${e.identifier(t)} (${Z(d)}) VALUES (${oe($)})`),h&&Ce.set(w,t),await se(t,void 0,y),await J(t,w,void 0,y),await ce(t,w,y),await U(t,w,"insert",y),P(t,"after","insert")&&await K("after","insert",{doc:y,id:w,op:"insert",table:t}),w},normalizeId(t,n){return qt(l,t,n)},async patch(t,n,o){const i=await ie(t,o);if(!i)throw new v("INTERNAL",`document not found: ${t}`);const s=l.tables[i];if(!s)throw new v("INTERNAL",`document not found: ${t}`);const w=await Re(i,t),h=te(s,w);if(!h)throw new v("INTERNAL",`document not found: ${t}`);const u={...h,...n,_id:t};ut(s,n,u,V),Ne(s,u,!0),P(i,"before","update")&&await K("before","update",{doc:{...u},id:t,op:"update",previous:h,table:i}),await pe(i),await me(i);const y=Object.keys(s.shape),d=e.join(y.map($=>e`${e.identifier($)} = ${H(u[$]??null)}`),e`, `);await Te(i,"UPDATE",d,w),await se(i,h,u),await J(i,t,h,u),await ce(i,t,u,h),await U(i,t,"update",u),P(i,"after","update")&&await K("after","update",{doc:u,id:t,op:"update",previous:h,table:i})},async restore(t,n){const o=await ie(t,n);if(!o)throw new v("INTERNAL",`document not found: ${t}`);const i=l.tables[o],s=i?.softDeleteMode?.field;if(!i||!s)throw new v("INTERNAL",`ctx.db.restore: table "${o}" is not a .softDelete() table`);const w=await Re(o,t),h=w?.[s]!==null&&w?.[s]!==void 0;if(await O.patch(t,{[s]:null},n),h){const u=te(i,w);u!==null&&await J(o,t,void 0,{...u,[s]:null})}},query(t){const n=l.tables[t];if(!n)throw new v("INTERNAL",`unknown table: ${t}`);const o="the legacy query()/withIndex() reader is not available on the D1 (global) backend; use findMany",i=[],s=u=>i.every(y=>y(u)),w=async(u,y)=>{await j();const d=i.length>0,$=await At(r,a,n,t,u,Ct(d?void 0:y));if(!d)return y===void 0&&Lt($),$;const E=$.filter(g=>s(g));return y===void 0?E:E.slice(0,y)},h=u=>{const y={async*[Symbol.asyncIterator](){if(!u)throw new v("INTERNAL",o);yield*await w(u,void 0)},async collect(){if(!u)throw new v("INTERNAL",o);return w(u,void 0)},async collectWithScores(){throw new v("INTERNAL",`collectWithScores() is not supported on \`.global()\` tables (table "${t}") — relevance scores are not yet surfaced on this backend; use .collect() instead`)},filter(d){return i.push(d),y},async first(){if(!u)throw new v("INTERNAL",o);return(await w(u,1))[0]??null},order(){return y},async paginate(d){if(!u)throw new v("INTERNAL",o);const $=bt(d);return It(await w(u,kt($)),$)},async take(d){if(!u)throw new v("INTERNAL",o);return w(u,d)},async unique(){if(!u)throw new v("INTERNAL",o);const d=await w(u,2);if(d.length>1)throw new zt(`unique() on table "${t}" matched ${String(d.length)} documents; expected at most one`);return d[0]??null},withGeoIndex(){throw new v("INTERNAL",`geo indexes are not supported on \`.global()\` tables (table "${t}") — geospatial queries run only on sharded tables`)},withIndex(){throw new v("INTERNAL",o)},withSearchIndex(d,$){const E=(n.searchIndexes??[]).find(T=>T.name===d);if(!E)throw new v("INTERNAL",`unknown search index "${d}" on table "${t}"`);const g={definition:E,field:E.field,filters:[],hasQuery:!1,indexName:d,query:""};if($(vt(g,t,St(E.language))),!g.hasQuery)throw new v("INTERNAL",`search index "${d}" on table "${t}" requires a .search(field, query) call`);return h(g)}};return y};return h(void 0)},async rank(t,n,o){const i=l.tables[t];if(!i)throw new v("INTERNAL",`unknown table: ${t}`);const s=i.rankIndexes?.find(B=>B.name===n);if(!s)throw new v("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(o.restrictsCounts)throw new et(t);if(await j(),!await ke(t,s))return null;const h=typeof o.row=="string"?o.row:o.row._id;if(!h)return null;const u=ee(t,s.name),y=s.sortBy.map((B,G)=>X(G)),d=Z(["__partition__",...y]),E=(await A(r,a,e`SELECT ${d} FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${h}`))[0];if(!E)return null;const g=E.__partition__,T=q(o.baseWhere,o.where);Je(T,l,t,"rank");const C=Qe(s,T);if(C&&Se(s.partitionBy??[],C)!==g)return null;const I=ln(a.name,s,y,E,h),F=await A(r,a,e`SELECT COUNT(*) AS c FROM ${e.identifier(u)} WHERE ${e.identifier("__partition__")} = ${g}${I?e` AND (${I})`:e``}`),N=await A(r,a,e`SELECT COUNT(*) AS c FROM ${e.identifier(u)} WHERE ${e.identifier("__partition__")} = ${g}`);return{position:Number(F[0]?.c??0)+1,total:Number(N[0]?.c??0)}},async rankPage(t,n,o={}){Je(q(o.baseWhere,o.where),l,t,"rankPage");const i=l.tables[t];if(!i)throw new v("INTERNAL",`unknown table: ${t}`);const s=i.rankIndexes?.find(D=>D.name===n);if(!s)throw new v("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(await j(),!await ke(t,s))return{continueCursor:null,isDone:!0,page:[]};const h=ee(t,s.name),u=s.sortBy.map((D,ue)=>X(ue)),y=Math.max(1,Math.min(1e3,Math.floor(o.take??100))),d=q(o.baseWhere,o.where),$=Qe(s,d),E=dn(s,u),g=e.join(E.map(D=>e`${e.identifier(D.column)} ${e.raw(D.direction==="desc"?"DESC":"ASC")}`),e`, `),T=[];if($&&T.push(e`${e.identifier("__partition__")} = ${Se(s.partitionBy??[],$)}`),o.cursor){const D=un(a.name,E,Ze(o.cursor));D!==void 0&&T.push(D)}const C=Z([he,"__partition__",...u]);let I=e`SELECT ${C} FROM ${e.identifier(h)}`;T.length>0&&(I=e`${I} WHERE ${e.join(T,e` AND `)}`),I=e`${I} ORDER BY ${g} LIMIT ${e.raw(String(y+1))}`;const F=await A(r,a,I),N=F.length>y,B=N?F.slice(0,y):F,G=B.map(D=>D[he]),ve=await fn(r,a,i,t,G);let le=null;const Q=B.at(-1);if(N&&Q!==void 0){const D=[Q.__partition__,...u.map(ue=>Q[ue]),Q[he]];le=wn(D)}return{continueCursor:le,isDone:!N,page:ve}},async replace(t,n,o,i){const s=await ie(t,o);if(!s)throw new v("INTERNAL",`document not found: ${t}`);const w=l.tables[s];if(!w)throw new v("INTERNAL",`document not found: ${t}`);const h=await Re(s,t);if(h===void 0)throw new v("INTERNAL",`document not found: ${t}`);const y=Dt(l,s,"update")||(w.aggregateIndexes??[]).length>0||(w.rankIndexes??[]).length>0?te(w,h)??void 0:void 0,d=i?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:L(),$={...n,_creationTime:d,_id:t};ut(w,n,$,V),Ne(w,$),P(s,"before","update")&&await K("before","update",{doc:{...$},id:t,op:"update",previous:y,table:s}),await pe(s),await me(s);const E=Object.keys(w.shape),g=e.join([e`${e.identifier("_creationTime")} = ${d}`,...E.map(T=>e`${e.identifier(T)} = ${H($[T]??null)}`)],e`, `);await Te(s,"UPDATE",g,h),await se(s,y,$),await J(s,t,y,$),await ce(s,t,$,y),await U(s,t,"update",$),P(s,"after","update")&&await K("after","update",{doc:$,id:t,op:"update",previous:y,table:s})}};return Pe={db:O,scheduler:Ae},O};export{xn as backfillSqlSearchIndexes,Mn as createSqlCtxDb,Fn as decodeGlobalRow,kn as readSqlCdcChanges,En as runSqlAggregateMigrations,Tn as runSqlCdcMigration,yn as runSqlGlobalTableMigrations,Rn as runSqlRankMigrations,gt as runSqlSearchMigrations,Nn as trimSqlCdcChanges};
1
+ import{LunoraError as v}from"@lunora/errors";import{c as Tt,r as gt,R as vt,j as St,_ as It,M as bt,a as At,D as Ct,y as Lt,I as kt}from"./ctx-db-search-DlItpO6A.mjs";import{b as xn}from"./ctx-db-search-DlItpO6A.mjs";import{literalInList as Nt,throwingScheduler as Mt,aggregateTableName as z,rankTableName as ee,hasTrigger as Dt,runRowValidators as Ne,assertFlatPredicate as Je,mergeWhere as q,sortColumnName as X,resolveRankPartition as Qe,encodePartitionKey as Se,decodeCursor as Ze,RANK_TIEBREAK as he,CountRlsUnsupportedError as et,normalizeIdStructurally as qt,assertValidClientId as xt,aggregateSqlFunction as fe,softDeleteScope as we,compileWhereSql as _e,normalizeOrderKeys as Bt,buildSeekWhere as Ft,resolveRelationPredicates as tt,resolveWith as nt,relationHooks as ot,applySelect as it,encodeCursor as Ot,NotFoundError as Wt,applyOnDelete as Ut,ConflictError as $e,normalizeCountArgument as jt,selectIndexForCount as Pt,encodeAggregateKey as Y,selectIndexForAggregate as Kt,readAggregateValue as Me,runTriggers as Ht,matchesRankStaticWhere as rt,selectIndexForGroupBy as Vt,fanOutScalarCounts as Gt,matchesStaticWhere as De,foldAggregateTally as Yt,coerceAggregateNumber as qe,NotUniqueError as zt}from"@lunora/shard-engine";import{sql as e}from"drizzle-orm";import{migrateSearchState as Xt}from"./SEARCH_STATE_TABLE-DA3LgCT0.mjs";import{queryAll as A,queryRun as k,createIndexIfNotExists as Be,decodeRow as te,serializeColumnValue as H,columnRefSql as x,decodeRows as Jt,forEachRowPaged as st,queryBatch as at}from"./decodeGlobalRow-BKIjk_Zk.mjs";import{decodeGlobalRow as Fn}from"./decodeGlobalRow-BKIjk_Zk.mjs";import{effectiveColumnKind as Ie}from"./decodeBigint-B4wY6fcF.mjs";const Qt=(c,_)=>{if(c.size<_)return;const f=c.keys().next().value;f!==void 0&&c.delete(f)},ct=50,Zt=(c,_={})=>{const f=_.maxBatch??ct,r=Number.isInteger(f)&&f>0?f:ct,p=new Map;let l=!1;const a=async(m,I)=>{const S=[...I.keys()];for(let L=0;L<S.length;L+=r){const M=S.slice(L,L+r);try{const W=await c(m,M);for(const V of M){const U=W.get(V);for(const Ae of I.get(V)??[])Ae.resolve(U)}}catch(W){for(const V of M)for(const U of I.get(V)??[])U.reject(W)}}},R=()=>{l=!1;const m=[...p.entries()];p.clear();for(const[I,S]of m)a(I,S).catch(()=>{})};return{async load(m,I){return new Promise((S,L)=>{let M=p.get(m);M||(M=new Map,p.set(m,M));const W=M.get(I);W?W.push({reject:L,resolve:S}):M.set(I,[{reject:L,resolve:S}]),l||(l=!0,queueMicrotask(R))})}}},en=new Set(["_id","id"]),Fe=(c,_,f)=>c==="postgres"?e`${_} IS NOT DISTINCT FROM ${f}`:c==="mysql"?e`${_} <=> ${f}`:e`${_} IS ${f}`,tn=c=>{const _=c.map(f=>e`${x(f.field)} ${e.raw(f.direction==="desc"?"DESC":"ASC")}`);return c.some(f=>en.has(f.field))||_.push(e`${x("id")} ASC`),e.join(_,e`, `)},lt=50,Oe=c=>{const _=[];for(const[f,r]of Object.entries(c.shape)){const p=r._meta?.column;p&&_.push([f,p])}return _},nn=(c,_,f)=>{const r={..._};for(const[p,l]of Oe(c)){if(l.serverDefault){r[p]=l.serverDefault({auth:f});continue}r[p]===void 0&&(l.defaultFn?r[p]=l.defaultFn():"defaultValue"in l&&(r[p]=l.defaultValue))}return r},ut=(c,_,f,r)=>{for(const[p,l]of Oe(c)){if(l.serverDefault){p in _&&(f[p]=l.serverDefault({auth:r}));continue}l.onUpdateFn&&!(p in _)&&(f[p]=l.onUpdateFn())}},on=128,rn=()=>{const c=new Map;return{delete:_=>{c.delete(_)},get:_=>{const f=c.get(_);if(f!==void 0)return c.delete(_),c.set(_,f),f},set:(_,f)=>{c.has(_)?c.delete(_):Qt(c,on),c.set(_,f)}}},sn=async(c,_,f,r,p)=>{const l=p.get(r);if(l!==void 0)return l;const a=Object.entries(f.tables).filter(([,m])=>m.shardMode===void 0||m.shardMode.kind==="global").map(([m])=>m),R=await Promise.all(a.map(async m=>({found:(await A(c,_,e`SELECT 1 FROM ${e.identifier(m)} WHERE ${e.identifier("id")} = ${r} LIMIT 1`)).length>0,tableName:m})));for(const m of R)if(m.found)return p.set(r,m.tableName),m.tableName},ne=c=>c==null?null:Number(c),an=(c,_)=>_.map(f=>{const r={};for(const p of c)r[p]=f[p]??null;return{key:r,value:ne(f.value)}}),cn=(c,_,f)=>[...c.partitionBy??[],...c.sortBy.map(p=>p.field),...c.where?Object.keys(c.where):[]].every(p=>_[p]===f[p]),dt=c=>c.length===1?c[0]:e`(${e.join(c,e` AND `)})`,Z=c=>e.join(c.map(_=>e`${e.identifier(_)}`),e`, `),oe=c=>e.join(c.map(_=>e`${_}`),e`, `),ln=(c,_,f,r,p)=>{const l=[];for(let a=0;a<f.length+1;a+=1){const R=f.slice(0,a).map(S=>Fe(c,e`${e.identifier(S)}`,r[S])),m=f[a],I=_.sortBy[a];a<f.length&&m!==void 0&&I!==void 0?R.push(e`${e.identifier(m)} ${e.raw(I.direction==="desc"?">":"<")} ${r[m]}`):R.push(e`${e.identifier(he)} < ${p}`),l.push(dt(R))}return l.length>0?e.join(l,e` OR `):void 0},un=(c,_,f)=>{if(f.length!==_.length)return;const r=[];for(const[p,l]of _.entries()){const a=[];for(let R=0;R<p;R+=1){const m=_[R];m!==void 0&&a.push(Fe(c,e`${e.identifier(m.column)}`,f[R]))}a.push(e`${e.identifier(l.column)} ${e.raw(l.direction==="desc"?"<":">")} ${f[p]}`),r.push(dt(a))}return e`(${e.join(r,e` OR `)})`},dn=(c,_)=>{if(c.sortBy.length===0)throw new v("INTERNAL",`rankIndex "${c.name}" requires at least one "sortBy" column for stable pagination`);const f=[{column:"__partition__",direction:"asc"}];for(const[r,p]of c.sortBy.entries())f.push({column:_[r]??X(r),direction:p.direction});return f.push({column:he,direction:"asc"}),f},fn=async(c,_,f,r,p)=>{const a=[];for(let S=0;S<p.length;S+=50)a.push(p.slice(S,S+50));const R=await Promise.all(a.map(async S=>A(c,_,e`SELECT * FROM ${e.identifier(r)} WHERE ${e.identifier("id")} IN (${oe(S)})`))),m=new Map;for(const S of R)for(const L of S)m.set(L.id,L);const I=[];for(const S of p){const L=te(f,m.get(S));L&&I.push(L)}return I},wn=c=>{const _=JSON.stringify(c),f=new TextEncoder().encode(_);let r="";for(const p of f)r+=String.fromCodePoint(p);return btoa(r)},_n=(c,_)=>_.columnType(Ie(c)),$n=(c,_,f)=>{const r=[];for(const[a,R]of Object.entries(_.shape)){if(!R._meta?.column)continue;const m=R._meta.column.notNull&&R.kind!=="optional"?" NOT NULL":"";r.push(e`${e.identifier(a)} ${e.raw(`${_n(R,f)}${m}`)}`)}const p=f.frameworkColumns().map(a=>e`${e.identifier(a.name)} ${e.raw(a.type)}`),l=p.length+r.length;if(f.maxTableColumns!==void 0&&l>f.maxTableColumns)throw new v("VALIDATION_ERROR",`@lunora/sql-store: global table "${c}" needs ${String(l)} columns, over this engine's ${String(f.maxTableColumns)}-column limit — split the table, or move the extra fields into one object field`);return e.join([...p,...r],e`, `)},hn=async(c,_,f,r)=>{const p=l=>{const a=x(l),R=f.shape[l],m=R&&r.indexKeyPrefix?r.indexKeyPrefix(Ie(R)):void 0;return m===void 0?a:e`${a}(${e.raw(String(m))})`};for(const l of f.indexes){const a=e.join(l.fields.map(R=>p(R)),e`, `);await Be(c,r,{columns:a,name:`${_}_${l.name}`,table:_,unique:l.unique??!1})}for(const[l,a]of Oe(f))a.unique&&await Be(c,r,{columns:p(l),name:`${_}_unique_${l}`,table:_,unique:!0})},yn=async(c,_,f)=>{for(const[r,p]of Object.entries(_.tables)){if(p.shardMode?.kind!=="global")continue;const l=$n(r,p,f);await k(c,f,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (${l})`),await hn(c,r,p,f)}},En=async(c,_,f)=>{const{integer:r,key:p,real:l}=f.companionTypes;for(const[a,R]of Object.entries(_.tables)){const m=R.aggregateIndexes;if(!(!m||m.length===0))for(const I of m){const S=z(a,I.name);await k(c,f,e`CREATE TABLE IF NOT EXISTS ${e.identifier(S)} (${e.identifier("__key__")} ${e.raw(p)} PRIMARY KEY, ${e.identifier("__value__")} ${e.raw(l)}, ${e.identifier("__count__")} ${e.raw(r)} NOT NULL DEFAULT 0)`),f.name==="sqlite"&&((await A(c,f,e`PRAGMA table_info(${e.identifier(S)})`)).some(M=>M.name==="__count__")||await k(c,f,e`ALTER TABLE ${e.identifier(S)} ADD COLUMN ${e.identifier("__count__")} ${e.raw(r)} NOT NULL DEFAULT 0`))}}},xe=(c,_,f,r)=>{const p=c.name==="mysql"&&r?e`${e.identifier(_)}(191)`:e`${e.identifier(_)}`;return e`${p} ${e.raw(f)}`},pn=(c,_,f)=>{const r=[xe(c,"__partition__","ASC",!0)];for(const[p,l]of _.sortBy.entries()){const a=f.shape[l.field],R=a!==void 0&&c.indexKeyPrefix?.(Ie(a))!==void 0;r.push(xe(c,X(p),l.direction==="desc"?"DESC":"ASC",R))}return r.push(xe(c,"__id__","ASC",!0)),r},mn=(c,_,f)=>_.sortBy.map((r,p)=>{const l=f.shape[r.field],a=c.columnType(l?Ie(l):void 0);return e`${e.identifier(X(p))} ${e.raw(a)}`}),Rn=async(c,_,f)=>{const{key:r}=f.companionTypes;for(const[p,l]of Object.entries(_.tables)){const a=l.rankIndexes;if(!(!a||a.length===0))for(const R of a){const m=ee(p,R.name),I=mn(f,R,l),S=I.length>0?e`, ${e.join(I,e`, `)}`:e``;await k(c,f,e`CREATE TABLE IF NOT EXISTS ${e.identifier(m)} (${e.identifier("__id__")} ${e.raw(r)} PRIMARY KEY, ${e.identifier("__partition__")} ${e.raw(r)} NOT NULL${S})`);const L=pn(f,R,l),M=`${p}__rank_${R.name}__btree`;await Be(c,f,{columns:e.join(L,e`, `),name:M,table:m,unique:!1})}}},be="__cdc_log",Tn=async(c,_)=>{const{autoincrementPrimaryKey:f,key:r,real:p,text:l}=_.companionTypes;await k(c,_,e`CREATE TABLE IF NOT EXISTS ${e.identifier(be)} (${e.identifier("seq")} ${e.raw(f)}, ${e.identifier("ts")} ${e.raw(p)} NOT NULL, ${e.identifier("table")} ${e.raw(r)} NOT NULL, ${e.identifier("id")} ${e.raw(r)} NOT NULL, ${e.identifier("op")} ${e.raw(r)} NOT NULL, ${e.identifier("doc")} ${e.raw(l)})`)},gn=async(c,_,f,r,p,l,a)=>{await k(c,a,e`INSERT INTO ${e.identifier(be)} (${e.identifier("ts")}, ${e.identifier("table")}, ${e.identifier("id")}, ${e.identifier("op")}, ${e.identifier("doc")}) VALUES (${_}, ${f}, ${r}, ${p}, ${l===void 0?null:JSON.stringify(l)})`)},kn=async(c,_,f)=>{const r=_.sinceSeq??0,p=Math.max(1,Math.min(_.limit??1e3,1e4)),a=(await A(c,f,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(be)} WHERE seq > ${r} ORDER BY seq ASC LIMIT ${e.raw(String(p))}`)).map(R=>{const{doc:m}=R,I={id:String(R.id),op:String(R.op),seq:Number(R.seq),table:String(R.table),ts:Number(R.ts)};return typeof m=="string"?{...I,doc:JSON.parse(m)}:I});return{changes:a,cursor:a.at(-1)?.seq??r}},Nn=async(c,_,f)=>{await k(c,f,e`DELETE FROM ${e.identifier(be)} WHERE ${e.identifier("seq")} <= ${_}`)},Mn=c=>{const{crossShardCounter:_,crossShardReader:f,exec:r,maxRelationKeys:p,schema:l}=c,{dialect:a}=c,{isUniqueViolation:R}=a,m={fieldRef:x,serialize:H,...a.name==="mysql"?{containsExpr:(t,n)=>e`LOCATE(${n}, ${t}) > 0`}:{},...a.name==="postgres"?{containsExpr:(t,n)=>e`strpos(${t}, ${n}) > 0`}:{},...a.name==="sqlite"?{}:{inList:Nt}},I=(t,n)=>Fe(a.name,t,n),S=t=>{const n=Z(t.columns),o=oe(t.values),i=u=>a.name==="mysql"?e`VALUES(${e.identifier(u)})`:e`excluded.${e.identifier(u)}`,s=u=>a.name==="postgres"?e`${e.identifier(t.table)}.${e.identifier(u)}`:e`${e.identifier(u)}`,w=e.join(Object.entries(t.set(i,s)).map(([u,y])=>e`${e.identifier(u)} = ${y}`),e`, `),h=a.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${w}`:e`ON CONFLICT(${e.identifier(t.conflictKey)}) DO UPDATE SET ${w}`;return e`INSERT INTO ${e.identifier(t.table)} (${n}) VALUES (${o}) ${h}`},L=c.clock??(()=>Date.now()),M=c.idGenerator??(()=>crypto.randomUUID()),W=c.cdc??!1,V=c.auth??{identity:null,userId:null},U=async(t,n,o,i)=>{W&&await gn(r,L(),t,n,o,i,a)},Ae=c.scheduler??Mt,Ce=rn();let ye=0,Le;const j=async()=>(Le??=(async()=>{await yn(r,l,a),await En(r,l,a),await Rn(r,l,a),await Xt(r,a),await gt(r,l,a),W&&await Tn(r,a)})().catch(t=>{throw Le=void 0,t}),Le),ie=async(t,n)=>{await j();const o=await sn(r,a,l,t,Ce);if(!(n!==void 0&&o!==n))return o},re=new Map,We=async(t,n)=>{const o=z(t,n);return(await A(r,a,a.tableExists(o))).length>0},Ee=async(t,n)=>{const o=`${t}::${n.name}`,i=re.get(o);if(i!==void 0)return i;if(!await We(t,n.name))return re.set(o,!1),!1;const w=l.tables[t];if(!w)return re.set(o,!1),!1;const h=n.by??[],u=new Map;await st(r,a,w,t,$=>{if(n.where&&!De($,n.where))return;const E=Y(h,$);Yt(u,E,n,$)});const y=z(t,n.name);await k(r,a,e`DELETE FROM ${e.identifier(y)}`);const d=[];for(const[$,E]of u)d.push(e`INSERT INTO ${e.identifier(y)} (${e.identifier("__key__")}, ${e.identifier("__value__")}, ${e.identifier("__count__")}) VALUES (${$}, ${E.value}, ${E.count})`);return await at(r,a,d),re.set(o,!0),!0},ft=async(t,n,o)=>{const i=fe(n.op),s=n.field??"",w=[];for(const y of n.by??[]){const d=H(o[y]??null);w.push(d===null?e`${x(y)} IS NULL`:e`${x(y)} = ${d}`)}for(const[y,d]of Object.entries(n.where??{})){const $=d!==null&&typeof d=="object"&&!Array.isArray(d)?d.eq:d,E=H($);w.push(E===null?e`${x(y)} IS NULL`:e`${x(y)} = ${E}`)}const h=e`SELECT ${e.raw(i)}(${x(s)}) AS value FROM ${e.identifier(t)}`,u=await A(r,a,w.length>0?e`${h} WHERE ${e.join(w,e` AND `)}`:h);return ne(u[0]?.value)},wt=async(t,n)=>{await k(r,a,e`DELETE FROM ${e.identifier(t)} WHERE ${e.identifier("__key__")} = ${n} AND ${e.identifier("__count__")} <= 0`)},_t=async(t,n,o,i)=>{const s=z(t,n.name),{op:w}=n,h=n.field??"",u=o&&(!n.where||De(o,n.where))?o:void 0,y=i&&(!n.where||De(i,n.where))?i:void 0;if(!(!u&&!y)){if(w==="count"||w==="sum"||w==="avg"){const d=new Set;for(const[$,E]of[[u,-1],[y,1]]){if(!$)continue;const g=w==="count"?1:qe($[h]);if(g===void 0)continue;const T=Y(n.by??[],$);d.add(T),await k(r,a,S({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(C,b)=>({__count__:e`${b("__count__")} + ${C("__count__")}`,__value__:w==="count"?e`${b("__value__")} + ${C("__value__")}`:e`COALESCE(${b("__value__")}, 0) + ${C("__value__")}`}),table:s,values:[T,E*g,E]}))}for(const $ of d)await wt(s,$);return}if(u){const d=Y(n.by??[],u),$=qe(u[h]),g=(await A(r,a,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(s)} WHERE ${e.identifier("__key__")} = ${d}`))[0],T=ne(g?.value),C=(g?.count??0)-1;if(C<=0)await k(r,a,e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__key__")} = ${d}`);else if(g&&$!==void 0&&T!==null&&$===T){const b=await ft(t,n,u);await k(r,a,e`UPDATE ${e.identifier(s)} SET ${e.identifier("__value__")} = ${b}, ${e.identifier("__count__")} = ${C} WHERE ${e.identifier("__key__")} = ${d}`)}else await k(r,a,e`UPDATE ${e.identifier(s)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${d}`)}if(y){const d=Y(n.by??[],y),$=qe(y[h]);if($===void 0)await k(r,a,S({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(E,g)=>({__count__:e`${g("__count__")} + 1`}),table:s,values:[d,null,1]}));else{const E=w==="min"?"MIN":"MAX";await k(r,a,S({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(g,T)=>({__count__:e`${T("__count__")} + 1`,__value__:e`${e.raw(E)}(COALESCE(${T("__value__")}, ${g("__value__")}), ${g("__value__")})`}),table:s,values:[d,$,1]}))}}}},pe=async t=>{const n=l.tables[t]?.aggregateIndexes;if(!(!n||n.length===0))for(const o of n)await Ee(t,o)},se=async(t,n,o)=>{const i=l.tables[t]?.aggregateIndexes;if(!(!i||i.length===0))for(const s of i){const w=`${t}::${s.name}`;(re.get(w)??await We(t,s.name))&&await _t(t,s,n,o)}},ae=new Map,Ue=async(t,n)=>{const o=ee(t,n);return(await A(r,a,a.tableExists(o))).length>0},ke=async(t,n)=>{const o=`${t}::rank::${n.name}`,i=ae.get(o);if(i!==void 0)return i;if(!await Ue(t,n.name))return ae.set(o,!1),!1;const w=l.tables[t];if(!w)return ae.set(o,!1),!1;const h=ee(t,n.name);await k(r,a,e`DELETE FROM ${e.identifier(h)}`);const u=n.sortBy.map((E,g)=>X(g)),y=Z(["__id__","__partition__",...u]),d=[];await st(r,a,w,t,E=>{if(n.where&&!rt(E,n.where))return;const g=Se(n.partitionBy??[],E),T=n.sortBy.map(C=>H(E[C.field]??null));d.push([E._id,g,...T])});const $=d.map(E=>e`INSERT INTO ${e.identifier(h)} (${y}) VALUES (${oe(E)})`);return await at(r,a,$),ae.set(o,!0),!0},me=async t=>{const n=l.tables[t]?.rankIndexes;if(!(!n||n.length===0))for(const o of n)await ke(t,o)},J=async(t,n,o,i)=>{const s=l.tables[t],w=s?.rankIndexes;if(!w||w.length===0)return;const h=s?.softDeleteMode?.field,u=h===void 0||i===void 0?void 0:i[h],y=u!=null;for(const d of w){if(o!==void 0&&i!==void 0&&cn(d,o,i))continue;const $=`${t}::rank::${d.name}`;if(!(ae.get($)??await Ue(t,d.name)))continue;const T=ee(t,d.name);if(o&&await k(r,a,e`DELETE FROM ${e.identifier(T)} WHERE ${e.identifier("__id__")} = ${n}`),i&&!y){if(d.where&&!rt(i,d.where))continue;const C=d.sortBy.map((B,G)=>X(G)),b=Z(["__id__","__partition__",...C]),F=Se(d.partitionBy??[],i),N=d.sortBy.map(B=>H(i[B.field]??null));await k(r,a,e`INSERT INTO ${e.identifier(T)} (${b}) VALUES (${oe([n,F,...N])})`)}}},ce=Tt({dialect:a,exec:r,schema:l}),je=new Set;for(const[t,n]of Object.entries(l.tables))for(const o of Object.values(n.triggerMap??{}))je.add(`${t} ${o.timing} ${o.op}`);const P=(t,n,o)=>je.has(`${t} ${n} ${o}`);let Pe;const K=async(t,n,o)=>{if(ye+=1,ye>lt)throw ye-=1,new $e(`trigger recursion exceeded ${String(lt)} levels on "${o.table}" — check for a self-triggering write`,"trigger");try{await Ht({ctx:Pe,event:o,op:n,schema:l,tableName:o.table,timing:t})}finally{ye-=1}},$t=async(t,n)=>{try{await k(r,a,n)}catch(o){throw R(o)?new $e(`unique constraint violation on "${t}"`,"unique"):o}},Re=async(t,n)=>(await A(r,a,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} = ${n}`))[0],Te=async(t,n,o,i)=>{if(i===void 0)return;const s=e.join(Object.keys(i).map(u=>I(e`${e.identifier(u)}`,i[u])),e` AND `),w=n==="UPDATE"?e`UPDATE ${e.identifier(t)} SET ${o} WHERE ${s}`:e`DELETE FROM ${e.identifier(t)} WHERE ${s}`,h=()=>{throw new $e(`optimistic concurrency conflict on "${t}" — the row changed during this mutation; refetch and retry`,"occ")};try{if(a.supportsReturning)(await A(r,a,e`${w} RETURNING ${e.identifier("id")}`)).length===0&&h();else{const u=await k(r,a,w);(a.affectedRows?a.affectedRows(u??{rowsAffected:0}):0)===0&&h()}}catch(u){throw R(u)?new $e(`unique constraint violation on "${t}"`,"unique"):u}},ht=(t,n,o,i)=>{const s=Object.keys(t.shape);return{columns:["id","_creationTime",...s],values:[n,o,...s.map(w=>H(i[w]??null))]}},yt=async(t,n,o,i)=>{const s=Vt(n,o.op,o.field,i.by,i.where);if(!s||!await Ee(t,s.index))return;const h=z(t,s.index.name),u=Object.keys(s.partial);if(u.length===(s.index.by??[]).length&&u.length>0){const d=Y(s.index.by??[],s.partial),$=await A(r,a,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(h)} WHERE ${e.identifier("__key__")} = ${d}`);if($.length===0)return[];const E=$[0];return[{key:{...s.partial},value:Me(o.op,{count:E.count,value:ne(E.value)})}]}return u.length>0?void 0:(await A(r,a,e`SELECT ${e.identifier("__key__")} AS key, ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(h)}`)).map(d=>{const $=d;return{key:JSON.parse($.key),value:Me(o.op,{count:$.count,value:ne($.value)})}})},Ke=t=>{const n=l.tables[t]?.shardMode?.kind;return n==="shardBy"||n==="root"},He=t=>{throw new v("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`)},Et=(t,n)=>{if(n?.relationMask!==void 0&&n.with!==void 0&&Object.keys(n.with).length>0)throw new v("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 o={};if(n?.relationBaseWhere)for(const i of Object.keys(l.tables)){const s=n.relationBaseWhere(i);s!==void 0&&(o[i]=s)}return{orderBy:n?.orderBy,relationPolicies:o,where:q(n?.baseWhere,n?.where),with:n?.with}},Ve=(t,n)=>Ke(t)?f?f(t,Et(t,n)):He(t):O.findMany(t,n),ge=(t,n,o)=>tt(t,{fetcher:Ve,maxRelationKeys:p,relationBaseWhere:o,schema:l,tableName:n}),pt=Zt(async(t,n)=>{const o=await A(r,a,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} IN (${oe(n)})`),i=new Map;for(const s of o){const{id:w}=s;typeof w=="string"&&i.set(w,s)}return i}),O={async aggregate(t,n){const o=l.tables[t];if(!o)throw new v("INTERNAL",`unknown table: ${t}`);if(await j(),fe(n.op),n.op==="count")return O.count(t,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new v("INTERNAL",`aggregate(${t}, { op: "${n.op}" }): "field" is required for non-count reducers`);const i=we(o.softDeleteMode,void 0),s=q(q(n.baseWhere,n.where),i),w=await ge(s,t,n.relationBaseWhere),h=w!==s;if(o.aggregateIndexes&&!n.baseWhere&&!h&&!i){const g=Kt(o.aggregateIndexes,n.op,n.field,n.where);if(g&&await Ee(t,g.index)){const C=Y(g.index.by??[],g.key),b=z(t,g.index.name),N=(await A(r,a,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(b)} WHERE ${e.identifier("__key__")} = ${C}`))[0];return Me(n.op,N===void 0?void 0:{count:N.count,value:ne(N.value)})}}const u=_e(w,m),y=e.raw(fe(n.op)),d=e`SELECT ${y}(${x(n.field)}) AS value FROM ${e.identifier(t)}`,E=(await A(r,a,u?e`${d} WHERE ${u}`:d))[0]?.value;return E==null?null:Number(E)},async count(t,n){const o=l.tables[t];if(!o)throw new v("INTERNAL",`unknown table: ${t}`);await j();const i=jt(n);if(i.restrictsCounts)throw new et(t);const s=we(o.softDeleteMode,void 0),w=q(q(i.baseWhere,i.where),s),h=await ge(w,t,i.relationBaseWhere),u=h!==w;if(o.aggregateIndexes&&!i.baseWhere&&!u&&!s){const E=Pt(o.aggregateIndexes,i.where);if(E&&await Ee(t,E.index)){const T=Y(E.index.by??[],E.key),C=z(t,E.index.name),b=await A(r,a,e`SELECT ${e.identifier("__value__")} AS value FROM ${e.identifier(C)} WHERE ${e.identifier("__key__")} = ${T}`);return Number(b[0]?.value??0)}}const y=_e(h,m),d=e`SELECT COUNT(*) AS count FROM ${e.identifier(t)}`,$=await A(r,a,y?e`${d} WHERE ${y}`:d);return Number($[0]?.count??0)},async delete(t,n,o){const i=await ie(t,n);if(!i)return;const s=l.tables[i];if(!s)return;const w=await Re(i,t),h=te(s,w),u=o?.hard===!0,y=!u&&s.softDeleteMode?s.softDeleteMode.field:void 0;if(!(y&&(!h||h[y]!==null&&h[y]!==void 0))){if(P(i,"before","delete")&&await K("before","delete",{id:t,op:"delete",previous:h??void 0,table:i}),await Ut({deletedId:t,deletedReference:d=>h?.[d],findHolders:async(d,$,E)=>{if(l.tables[d]?.shardMode?.kind==="shardBy")throw new v("INTERNAL",`cross-backend cascade from global '${i}' into shardBy '${d}' is not supported — would require Query Coordinator fan-out across shards`);return(await O.findMany(d,{includeDeleted:u,where:{[$]:E}})).page},onCascade:(d,$)=>O.delete($,void 0,o),onRestrict:d=>{throw new $e(d,"restrict")},onSetNull:(d,$,E)=>O.patch($,{[E]:null}),schema:l,tableName:i}),await pe(i),await me(i),y&&h){const d={...h,[y]:L()},$=e.join(Object.keys(s.shape).map(E=>e`${e.identifier(E)} = ${H(d[E]??null)}`),e`, `);await Te(i,"UPDATE",$,w),await se(i,h,d),await J(i,t,h,void 0),await ce(i,t,d,h),await U(i,t,"update",d),P(i,"after","delete")&&await K("after","delete",{id:t,op:"delete",previous:h,table:i});return}await Te(i,"DELETE",void 0,w),Ce.delete(t),await se(i,h??void 0,void 0),await J(i,t,h??void 0,void 0),await ce(i,t,void 0),await U(i,t,"delete"),P(i,"after","delete")&&await K("after","delete",{id:t,op:"delete",previous:h??void 0,table:i})}},async findFirst(t,n={}){return(await O.findMany(t,{...n,limit:1})).page[0]??null},async findFirstOrThrow(t,n={}){const o=await O.findFirst(t,n);if(o===null)throw new Wt(`findFirstOrThrow: no "${t}" document matched`);return o},async findMany(t,n={}){const o=l.tables[t];if(!o)throw new v("INTERNAL",`unknown table: ${t}`);await j();const i=Bt(n.orderBy),s=n.cursor?Ft(i,Ze(n.cursor)):void 0,w=Ve,h=async(N,B,G,ve)=>{if(Ke(N))return _?Gt(_,N,B,G,ve):He(N);const le=l.tables[N];if(!le)throw new v("INTERNAL",`unknown table: ${N}`);const Q=we(le.softDeleteMode,void 0),D={[B]:{in:G}},ue=q(q(D,ve),Q),mt=await ge(ue,N,void 0),Ge=_e(mt,m),Ye=x(B);let de=e`SELECT ${Ye} AS __fk__, COUNT(*) AS count FROM ${e.identifier(N)}`;Ge&&(de=e`${de} WHERE ${Ge}`),de=e`${de} GROUP BY ${Ye}`;const Rt=await A(r,a,de),ze=new Map;for(const Xe of Rt)ze.set(Xe.__fk__,Number(Xe.count??0));return ze};let u=q(n.baseWhere,n.where);u=q(u,we(o.softDeleteMode,n.includeDeleted)),u=await tt(u,{fetcher:w,maxRelationKeys:p,relationBaseWhere:n.relationBaseWhere,schema:l,tableName:t}),s&&(u=u?{AND:[u,s]}:s);const y=_e(u,m),d=tn(i);let $=e`SELECT * FROM ${e.identifier(t)}`;y&&($=e`${$} WHERE ${y}`),$=e`${$} ORDER BY ${d}`;const E=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;E!==void 0&&($=e`${$} LIMIT ${e.raw(String(E+1))}`);const g=await A(r,a,$),T=Jt(o,g);if(E===void 0)return n.with&&await nt({fetcher:w,groupedCounter:h,parents:T,...ot(n),schema:l,tableName:t,with:n.with}),{continueCursor:null,isDone:!0,page:it(T,n.select,n.with)};const C=T.length>E,b=C?T.slice(0,E):T,F=b.at(-1);return n.with&&await nt({fetcher:w,groupedCounter:h,parents:b,...ot(n),schema:l,tableName:t,with:n.with}),{continueCursor:C&&F?Ot(F,i):null,isDone:!C,page:it(b,n.select,n.with)}},async get(t,n){const o=await ie(t,n);if(!o)return null;const i=l.tables[o];return i?te(i,await pt.load(o,t)):null},async groupBy(t,n){const o=l.tables[t];if(!o)throw new v("INTERNAL",`unknown table: ${t}`);await j();const i=n.agg??{op:"count"};if(fe(i.op),i.op!=="count"&&!i.field)throw new v("INTERNAL",`groupBy(${t}, { agg: { op: "${i.op}" } }): "field" is required for non-count reducers`);const s=we(o.softDeleteMode,void 0),w=q(q(n.baseWhere,n.where),s),h=await ge(w,t,n.relationBaseWhere),u=h!==w;if(o.aggregateIndexes&&!n.baseWhere&&!u&&!s){const T=await yt(t,o.aggregateIndexes,i,n);if(T!==void 0)return T}const y=_e(h,m),d=n.by.map(T=>e`${x(T)} AS ${e.identifier(T)}`);if(i.op==="count")d.push(e`COUNT(*) AS value`);else{if(!i.field)throw new v("INTERNAL",`groupBy(${t}, { agg: { op: "${i.op}" } }): "field" is required for non-count reducers`);d.push(e`${e.raw(fe(i.op))}(${x(i.field)}) AS value`)}const $=e.join(n.by.map(T=>x(T)),e`, `);let E=e`SELECT ${e.join(d,e`, `)} FROM ${e.identifier(t)}`;y&&(E=e`${E} WHERE ${y}`),E=e`${E} GROUP BY ${$}`;const g=await A(r,a,E);return an(n.by,g)},async insert(t,n,o){const i=l.tables[t];if(!i)throw new v("INTERNAL",`unknown table: ${t}`);await j();const s=nn(i,n,V);Ne(i,s);let w,h=!0;o?.clientId!==void 0?(xt(o.clientId),w=o.clientId):o?.allowExplicitId&&typeof s._id=="string"?w=s._id:(w=M(),h=!1);const u=o?.allowExplicitId&&typeof s._creationTime=="number"?s._creationTime:L(),y={...s,_creationTime:u,_id:w};P(t,"before","insert")&&await K("before","insert",{doc:{...y},id:w,op:"insert",table:t}),await pe(t),await me(t);const{columns:d,values:$}=ht(i,w,u,s);return await $t(t,e`INSERT INTO ${e.identifier(t)} (${Z(d)}) VALUES (${oe($)})`),h&&Ce.set(w,t),await se(t,void 0,y),await J(t,w,void 0,y),await ce(t,w,y),await U(t,w,"insert",y),P(t,"after","insert")&&await K("after","insert",{doc:y,id:w,op:"insert",table:t}),w},normalizeId(t,n){return qt(l,t,n)},async patch(t,n,o){const i=await ie(t,o);if(!i)throw new v("INTERNAL",`document not found: ${t}`);const s=l.tables[i];if(!s)throw new v("INTERNAL",`document not found: ${t}`);const w=await Re(i,t),h=te(s,w);if(!h)throw new v("INTERNAL",`document not found: ${t}`);const u={...h,...n,_id:t};ut(s,n,u,V),Ne(s,u,!0),P(i,"before","update")&&await K("before","update",{doc:{...u},id:t,op:"update",previous:h,table:i}),await pe(i),await me(i);const y=Object.keys(s.shape),d=e.join(y.map($=>e`${e.identifier($)} = ${H(u[$]??null)}`),e`, `);await Te(i,"UPDATE",d,w),await se(i,h,u),await J(i,t,h,u),await ce(i,t,u,h),await U(i,t,"update",u),P(i,"after","update")&&await K("after","update",{doc:u,id:t,op:"update",previous:h,table:i})},async restore(t,n){const o=await ie(t,n);if(!o)throw new v("INTERNAL",`document not found: ${t}`);const i=l.tables[o],s=i?.softDeleteMode?.field;if(!i||!s)throw new v("INTERNAL",`ctx.db.restore: table "${o}" is not a .softDelete() table`);const w=await Re(o,t),h=w?.[s]!==null&&w?.[s]!==void 0;if(await O.patch(t,{[s]:null},n),h){const u=te(i,w);u!==null&&await J(o,t,void 0,{...u,[s]:null})}},query(t){const n=l.tables[t];if(!n)throw new v("INTERNAL",`unknown table: ${t}`);const o="the legacy query()/withIndex() reader is not available on the D1 (global) backend; use findMany",i=[],s=u=>i.every(y=>y(u)),w=async(u,y)=>{await j();const d=i.length>0,$=await At(r,a,n,t,u,Ct(d?void 0:y));if(!d)return y===void 0&&Lt($),$;const E=$.filter(g=>s(g));return y===void 0?E:E.slice(0,y)},h=u=>{const y={async*[Symbol.asyncIterator](){if(!u)throw new v("INTERNAL",o);yield*await w(u,void 0)},async collect(){if(!u)throw new v("INTERNAL",o);return w(u,void 0)},async collectWithScores(){throw new v("INTERNAL",`collectWithScores() is not supported on \`.global()\` tables (table "${t}") — relevance scores are not yet surfaced on this backend; use .collect() instead`)},filter(d){return i.push(d),y},async first(){if(!u)throw new v("INTERNAL",o);return(await w(u,1))[0]??null},order(){return y},async paginate(d){if(!u)throw new v("INTERNAL",o);const $=It(d);return bt(await w(u,kt($)),$)},async take(d){if(!u)throw new v("INTERNAL",o);return w(u,d)},async unique(){if(!u)throw new v("INTERNAL",o);const d=await w(u,2);if(d.length>1)throw new zt(`unique() on table "${t}" matched ${String(d.length)} documents; expected at most one`);return d[0]??null},withGeoIndex(){throw new v("INTERNAL",`geo indexes are not supported on \`.global()\` tables (table "${t}") — geospatial queries run only on sharded tables`)},withIndex(){throw new v("INTERNAL",o)},withSearchIndex(d,$){const E=(n.searchIndexes??[]).find(T=>T.name===d);if(!E)throw new v("INTERNAL",`unknown search index "${d}" on table "${t}"`);const g={definition:E,field:E.field,filters:[],hasQuery:!1,indexName:d,query:""};if($(vt(g,t,St(E.language))),!g.hasQuery)throw new v("INTERNAL",`search index "${d}" on table "${t}" requires a .search(field, query) call`);return h(g)}};return y};return h(void 0)},async rank(t,n,o){const i=l.tables[t];if(!i)throw new v("INTERNAL",`unknown table: ${t}`);const s=i.rankIndexes?.find(B=>B.name===n);if(!s)throw new v("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(o.restrictsCounts)throw new et(t);if(await j(),!await ke(t,s))return null;const h=typeof o.row=="string"?o.row:o.row._id;if(!h)return null;const u=ee(t,s.name),y=s.sortBy.map((B,G)=>X(G)),d=Z(["__partition__",...y]),E=(await A(r,a,e`SELECT ${d} FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${h}`))[0];if(!E)return null;const g=E.__partition__,T=q(o.baseWhere,o.where);Je(T,l,t,"rank");const C=Qe(s,T);if(C&&Se(s.partitionBy??[],C)!==g)return null;const b=ln(a.name,s,y,E,h),F=await A(r,a,e`SELECT COUNT(*) AS c FROM ${e.identifier(u)} WHERE ${e.identifier("__partition__")} = ${g}${b?e` AND (${b})`:e``}`),N=await A(r,a,e`SELECT COUNT(*) AS c FROM ${e.identifier(u)} WHERE ${e.identifier("__partition__")} = ${g}`);return{position:Number(F[0]?.c??0)+1,total:Number(N[0]?.c??0)}},async rankPage(t,n,o={}){Je(q(o.baseWhere,o.where),l,t,"rankPage");const i=l.tables[t];if(!i)throw new v("INTERNAL",`unknown table: ${t}`);const s=i.rankIndexes?.find(D=>D.name===n);if(!s)throw new v("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(await j(),!await ke(t,s))return{continueCursor:null,isDone:!0,page:[]};const h=ee(t,s.name),u=s.sortBy.map((D,ue)=>X(ue)),y=Math.max(1,Math.min(1e3,Math.floor(o.take??100))),d=q(o.baseWhere,o.where),$=Qe(s,d),E=dn(s,u),g=e.join(E.map(D=>e`${e.identifier(D.column)} ${e.raw(D.direction==="desc"?"DESC":"ASC")}`),e`, `),T=[];if($&&T.push(e`${e.identifier("__partition__")} = ${Se(s.partitionBy??[],$)}`),o.cursor){const D=un(a.name,E,Ze(o.cursor));D!==void 0&&T.push(D)}const C=Z([he,"__partition__",...u]);let b=e`SELECT ${C} FROM ${e.identifier(h)}`;T.length>0&&(b=e`${b} WHERE ${e.join(T,e` AND `)}`),b=e`${b} ORDER BY ${g} LIMIT ${e.raw(String(y+1))}`;const F=await A(r,a,b),N=F.length>y,B=N?F.slice(0,y):F,G=B.map(D=>D[he]),ve=await fn(r,a,i,t,G);let le=null;const Q=B.at(-1);if(N&&Q!==void 0){const D=[Q.__partition__,...u.map(ue=>Q[ue]),Q[he]];le=wn(D)}return{continueCursor:le,isDone:!N,page:ve}},async replace(t,n,o,i){const s=await ie(t,o);if(!s)throw new v("INTERNAL",`document not found: ${t}`);const w=l.tables[s];if(!w)throw new v("INTERNAL",`document not found: ${t}`);const h=await Re(s,t);if(h===void 0)throw new v("INTERNAL",`document not found: ${t}`);const y=Dt(l,s,"update")||(w.aggregateIndexes??[]).length>0||(w.rankIndexes??[]).length>0?te(w,h)??void 0:void 0,d=i?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:L(),$={...n,_creationTime:d,_id:t};ut(w,n,$,V),Ne(w,$),P(s,"before","update")&&await K("before","update",{doc:{...$},id:t,op:"update",previous:y,table:s}),await pe(s),await me(s);const E=Object.keys(w.shape),g=e.join([e`${e.identifier("_creationTime")} = ${d}`,...E.map(T=>e`${e.identifier(T)} = ${H($[T]??null)}`)],e`, `);await Te(s,"UPDATE",g,h),await se(s,y,$),await J(s,t,y,$),await ce(s,t,$,y),await U(s,t,"update",$),P(s,"after","update")&&await K("after","update",{doc:$,id:t,op:"update",previous:y,table:s})}};return Pe={db:O,scheduler:Ae},O};export{xn as backfillSqlSearchIndexes,Mn as createSqlCtxDb,Fn as decodeGlobalRow,kn as readSqlCdcChanges,En as runSqlAggregateMigrations,Tn as runSqlCdcMigration,yn as runSqlGlobalTableMigrations,Rn as runSqlRankMigrations,gt as runSqlSearchMigrations,Nn as trimSqlCdcChanges};
@@ -0,0 +1 @@
1
+ import{sql as t}from"drizzle-orm";import{migrateSearchState as Z,readSearchBackfillState as P,writeSearchBackfillState as I}from"./SEARCH_STATE_TABLE-DA3LgCT0.mjs";import{LunoraError as h}from"@lunora/errors";import{unionAll as ee}from"@lunora/shard-engine";import{queryRun as S,decodeRows as z,queryAll as L,queryBatch as ne,createIndexIfNotExists as U,columnRefSql as M,serializeColumnValue as te,forEachRowPaged as ie}from"./decodeGlobalRow-BKIjk_Zk.mjs";const re=["de","en","es","fr","it","nl","none","pt"],oe=e=>re.includes(e),se="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",ae="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",ce="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",ue="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",fe="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",de="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",le="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ê",me=/[\u0300-\u036F]/gu,W=e=>e.normalize("NFD").replaceAll(me,"").normalize("NFC").toLowerCase(),g=e=>new Set(W(e).split(" ")),$e={de:g(ae),en:g(se),es:g(ce),fr:g(ue),it:g(fe),nl:g(de),none:new Set,pt:g(le)},he=2,we=256,j=new Map,y=e=>{const n=e!==void 0&&oe(e)?e:"none",i=j.get(n);if(i)return i;const r=$e[n],o=a=>{const c=(W(a).match(/[\p{L}\p{N}]+/gu)??[]).filter(u=>u.length<=we);return r.size===0?c:c.filter(u=>!r.has(u))},s={document:o,profile:`${n}-v${String(he)}`,query:a=>{const c=o(a);return c.filter((u,f)=>c.lastIndexOf(u)===f)}};return j.set(n,s),s},Se=(e,n)=>e.profile!==n?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},pe=(e,n)=>{if(!n.includes("."))return e[n];let i=e;for(const r of n.split(".")){if(i===null||typeof i!="object"||Array.isArray(i))return;i=i[r]}return i},v=(e,n)=>`${e}__fts_${n}`,Ee="__text__",l="__id__",T="__token__",D="__n__",ge=1e3,Q=(e,n)=>n.document(e),C=(e,n)=>pe(e,n),_e=e=>typeof e=="string"?e:e==null?"":typeof e=="number"||typeof e=="bigint"||typeof e=="boolean"?String(e):JSON.stringify(e)??"",ye=(e,n,i)=>e!==void 0&&n!==void 0&&C(e,i.field)===C(n,i.field),O=(e,n)=>Q(_e(C(e,n.field)),y(n.language)).slice(0,ge).join(" "),Te=(e,n)=>{const i=new Map;for(const r of Q(e,n))i.set(r,(i.get(r)??0)+1);return i},Ne=e=>{const n=new TextEncoder().encode(e);let i="";for(const r of n)i+=String.fromCodePoint(r);return btoa(i)},Ie=e=>{const n=atob(e),i=Uint8Array.from(n,r=>r.codePointAt(0)??0);return new TextDecoder().decode(i)},ve=()=>new h("BAD_REQUEST","invalid cursor"),B=16,F=8,w=1024,R=(e,n)=>n.query(e),Re=(e,n)=>{if(!n)return{exact:!0,lower:e,upper:e};const i=[...e].at(-1)??"",r=(i.codePointAt(0)??0)+1;if(r>=55296&&r<=57343||r>1114111)return{exact:!0,lower:e,upper:e};const o=e.slice(0,e.length-i.length);return{exact:!1,lower:e,upper:o+String.fromCodePoint(r)}},He=(e,n,i)=>{const r={eq:(o,s)=>{if(!e.definition.filterFields?.includes(o))throw new h("INTERNAL",`field "${o}" is not a filter field of search index "${e.indexName}" on table "${n}"`);if(e.filters.length>=F)throw new h("BAD_REQUEST",`search index "${e.indexName}" on table "${n}": at most ${String(F)} .eq() filters are supported per search query`);return e.filters.push({field:o,value:s}),r},search:(o,s)=>{const a=e;if(o!==a.definition.field)throw new h("INTERNAL",`search index "${a.indexName}" on table "${n}" indexes "${a.definition.field}", not "${o}"`);const c=R(s,i).length;if(c>B)throw new h("BAD_REQUEST",`search index "${a.indexName}" on table "${n}": at most ${String(B)} search terms are supported (got ${String(c)})`);return a.field=o,a.query=s,a.hasQuery=!0,r}};return r},Pe=e=>{if(e.length>w)throw new h("BAD_REQUEST",`more than ${String(w)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},ze=e=>Math.min(e.offset+e.numItems+1,w),be=e=>Ne(`search:${String(e)}`),Ae=e=>{let n;try{n=Ie(e)}catch{return}if(!n.startsWith("search:"))return;const i=Number(n.slice(7));return Number.isInteger(i)&&i>=0?i:void 0},We=e=>{if(typeof e.endCursor=="string")throw new h("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(e.numItems))throw new h("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(e.numItems)}`);const n=Math.max(0,Math.floor(e.numItems)),i=e.cursor?Ae(e.cursor):0;if(i===void 0)throw ve();if(i+n>=w)throw new h("BAD_REQUEST",`search pagination reaches the ${String(w)}-document limit (offset ${String(i)} + ${String(n)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,w-i-1))} or fewer, or narrow the query or the filters instead`);return{numItems:n,offset:i}},Qe=(e,n)=>{const i=n.offset+n.numItems,r=n.numItems>0&&e.length>i;return{continueCursor:r?be(i):null,isDone:!r,page:e.slice(n.offset,i)}},Ge=e=>{if(e===void 0)return w+1;if(!Number.isFinite(e))return w;const n=Math.max(0,Math.floor(e));if(n>w)throw new h("BAD_REQUEST",`search returns at most ${String(w)} documents (asked for ${String(n)}) — narrow the query or paginate instead`);return n},b=async(e,n,i,r)=>{await S(e,n,t`DELETE FROM ${t.identifier(i)} WHERE ${t.identifier(l)} = ${r}`)},A=(e,n)=>e.name==="mysql"?t`${t.identifier(n)}(191)`:e.textPatternOperatorClass===void 0?t`${t.identifier(n)}`:t`${t.identifier(n)} ${t.raw(e.textPatternOperatorClass)}`,k=50,De=(e,n)=>n?t`${t.identifier(T)} LIKE ${`${e}%`}`:t`${t.identifier(T)} = ${e}`,G=(e,n)=>{const i=n.filters.map(r=>t`m.${M(r.field)} = ${te(r.value)}`);return e.softDeleteMode&&i.push(t`m.${M(e.softDeleteMode.field)} IS NULL`),i},V=async(e,n,i,r,o,s,a)=>{const c=G(i,o);let u=t`SELECT m.* FROM (${a}) s JOIN ${t.identifier(r)} m ON m.${t.identifier("id")} = s.${t.identifier(l)}`;return c.length>0&&(u=t`${u} WHERE ${t.join(c,t` AND `)}`),u=t`${u} ORDER BY s.${t.identifier("__score__")} DESC, m.${t.identifier("_creationTime")} DESC, m.${t.identifier("id")} ASC LIMIT ${t.raw(String(s))}`,z(i,await L(e,n,u))},Ce=async(e,n,i,r,o,s)=>{const a=R(o.query,y(o.definition.language));if(a.length===0)return[];const c=v(r,o.indexName),u=a.length-1,f=a.map((d,_)=>De(d,_===u)),m=t.join(f,t` OR `),$=f.map(d=>t`SUM(CASE WHEN ${d} THEN ${t.identifier(D)} ELSE 0 END)`),E=t.join($.map(d=>t`${d} > 0`),t` AND `),p=t`SELECT ${t.identifier(l)}, ${t.join($,t` + `)} AS ${t.identifier("__score__")} FROM ${t.identifier(c)} WHERE ${m} GROUP BY ${t.identifier(l)} HAVING ${E}`;return V(e,n,i,r,o,s,p)},Le=async(e,n,i,r,o,s)=>{const a=R(o.query,y(o.definition.language));if(a.length===0)return[];const c=v(r,o.indexName),u=`${c}__vocab`,f=a.length-1,m=a.map((p,d)=>{const _=Re(p,d===f),K=_.exact?t`${t.identifier("term")} = ${_.lower}`:t`${t.identifier("term")} >= ${_.lower} AND ${t.identifier("term")} < ${_.upper}`;return t`SELECT ${t.identifier("doc")}, ${t.raw(String(d))} AS ${t.identifier("__term__")}, COUNT(*) AS ${t.identifier("__n__")} FROM ${t.identifier(u)} WHERE ${K} GROUP BY ${t.identifier("doc")}`}),$=a.map((p,d)=>t`SUM(CASE WHEN u.${t.identifier("__term__")} = ${t.raw(String(d))} THEN u.${t.identifier("__n__")} ELSE 0 END)`),E=t`SELECT f.${t.identifier(l)} AS ${t.identifier(l)}, ${t.join($,t` + `)} AS ${t.identifier("__score__")} FROM (${ee(m)}) u JOIN ${t.identifier(c)} f ON f.rowid = u.${t.identifier("doc")} GROUP BY f.${t.identifier(l)} HAVING ${t.join($.map(p=>t`${p} > 0`),t` AND `)}`;return V(e,n,i,r,o,s,E)},Oe=async(e,n,i,r,o,s)=>{const a=n.nativeTextSearch,c=R(o.query,y(o.definition.language));if(!a||c.length===0)return[];const u=v(r,o.indexName),f=[a.matches(u,c),...G(i,o)],m=t`SELECT m.* FROM ${t.identifier(u)} JOIN ${t.identifier(r)} m ON m.${t.identifier("id")} = ${t.identifier(u)}.${t.identifier(l)} WHERE ${t.join(f,t` AND `)} ORDER BY ${a.rank(u,c)} DESC, m.${t.identifier("_creationTime")} DESC, m.${t.identifier("id")} ASC LIMIT ${t.raw(String(s))}`;return z(i,await L(e,n,m))},qe={ensureCompanion:async(e,n,i)=>{const{integer:r,key:o}=n.companionTypes;await S(e,n,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier(T)} ${t.raw(o)} NOT NULL, ${t.identifier(l)} ${t.raw(o)} NOT NULL, ${t.identifier(D)} ${t.raw(r)} NOT NULL)`),await U(e,n,{columns:t`${A(n,T)}, ${A(n,l)}`,name:`${i}__btree`,table:i,unique:!1}),await U(e,n,{columns:A(n,l),name:`${i}__by_id`,table:i,unique:!1})},indexDocument:async(e,n,i,r,o,s)=>{await b(e,n,i,r);const a=[...Te(O(o,s),y(s.language))],c=t.join([T,l,D].map(f=>t.identifier(f)),t`, `),u=[];for(let f=0;f<a.length;f+=k){const m=t.join(a.slice(f,f+k).map(([$,E])=>t`(${$}, ${r}, ${E})`),t`, `);u.push(t`INSERT INTO ${t.identifier(i)} (${c}) VALUES ${m}`)}await ne(e,n,u)},name:"inverted",runSearch:Ce},xe={ensureCompanion:async(e,n,i)=>{await S(e,n,t`CREATE VIRTUAL TABLE IF NOT EXISTS ${t.identifier(i)} USING fts5(${t.identifier(Ee)}, ${t.identifier(l)} UNINDEXED)`),await S(e,n,t`CREATE VIRTUAL TABLE IF NOT EXISTS ${t.identifier(`${i}__vocab`)} USING fts5vocab(${t.identifier(i)}, ${t.raw("instance")})`)},indexDocument:async(e,n,i,r,o,s)=>{await b(e,n,i,r),await S(e,n,t`INSERT INTO ${t.identifier(i)} (${t.identifier("__text__")}, ${t.identifier(l)}) VALUES (${O(o,s)}, ${r})`)},name:"fts5",runSearch:Le},Ue={ensureCompanion:async(e,n,i)=>{const r=n.nativeTextSearch;if(r){await S(e,n,r.createCompanion(i,n.companionTypes.key));for(const o of r.createIndexes(i))await S(e,n,o)}},indexDocument:async(e,n,i,r,o,s)=>{const a=n.nativeTextSearch;a&&(await b(e,n,i,r),await S(e,n,a.indexDocument(i,r,O(o,s))))},name:"native",runSearch:Oe},N=(e,n)=>e.strategy==="native"&&n.nativeTextSearch!==void 0?Ue:n.supportsFts5?xe:qe,J=(e,n)=>`${y(e.language).profile}/${N(e,n).name}`,q=function*(e){for(const[n,i]of Object.entries(e.tables)){const r=i.searchIndexes;if(!(i.shardMode!==void 0&&i.shardMode.kind!=="global"||!r))for(const o of r)yield[n,i,o]}},x=(e,n)=>v(e,n.name),Ve=async(e,n,i,r,o,s)=>N(o.definition,n).runSearch(e,n,i,r,o,s),H=200,X=async(e,n,i,r,o)=>{const s=x(r,o),a=N(o,n),c=J(o,n),u=Se(await P(e,n,s),c);if(u.finished)return!0;if(u.wipe&&(await S(e,n,t`DELETE FROM ${t.identifier(s)}`),await I(e,n,s,void 0,!1,c)),(await L(e,n,n.tableExists(r))).length===0)return await I(e,n,s,void 0,!0,c),!0;let m=0,$=u.cursor;await ie(e,n,i,r,async p=>{m+=1;const d=p._id;typeof d=="string"&&($=d,await a.indexDocument(e,n,s,d,p,o))},{after:u.cursor,limit:H});const E=m<H;return await I(e,n,s,$,E,c),E},Y=async(e,n,i)=>{await Z(e,i);for(const[r,,o]of q(n)){const s=x(r,o),a=J(o,i),c=await P(e,i,s);c.profile!==void 0&&c.profile!==a&&(await S(e,i,t`DROP TABLE IF EXISTS ${t.identifier(s)}`),await I(e,i,s,void 0,!1,a)),await N(o,i).ensureCompanion(e,i,s)}},Je=async(e,n,i)=>{await Y(e,n,i);for(const[r,o,s]of q(n))s.staged||await X(e,i,o,r,s)},Xe=async(e,n,i)=>{await Y(e,n,i);for(const[r,o,s]of q(n)){let a=!1;for(;!a;)a=await X(e,i,o,r,s)}},Ye=e=>{const{dialect:n,exec:i,schema:r}=e;return async(o,s,a,c)=>{const u=r.tables[o]?.searchIndexes;if(!(!u||u.length===0))for(const f of u){if(ye(c,a,f))continue;const m=x(o,f);if(a){await N(f,n).indexDocument(i,n,m,s,a,f);continue}await b(i,n,m,s)}}};export{Ge as D,ze as I,Qe as M,He as R,We as _,Ve as a,Xe as b,Ye as c,y as j,Je as r,Pe as y};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/sql-store",
3
- "version": "1.0.0-alpha.84",
3
+ "version": "1.0.0-alpha.85",
4
4
  "description": "Internal dialect-parameterized SQL store core for Lunora .global() backends (D1, PlanetScale)",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -51,7 +51,7 @@
51
51
  },
52
52
  "dependencies": {
53
53
  "@lunora/errors": "1.0.0-alpha.22",
54
- "@lunora/shard-engine": "1.0.0-alpha.32",
54
+ "@lunora/shard-engine": "1.0.0-alpha.33",
55
55
  "drizzle-orm": "^0.45.2"
56
56
  },
57
57
  "engines": {
@@ -1 +0,0 @@
1
- import{sql as t}from"drizzle-orm";import{migrateSearchState as Z,readSearchBackfillState as P,writeSearchBackfillState as v}from"./SEARCH_STATE_TABLE-DA3LgCT0.mjs";import{LunoraError as S}from"@lunora/errors";import{unionAll as ee}from"@lunora/shard-engine";import{queryRun as h,decodeRows as z,queryAll as C,queryBatch as ne,createIndexIfNotExists as U,columnRefSql as M,serializeColumnValue as te,forEachRowPaged as ie}from"./decodeGlobalRow-BKIjk_Zk.mjs";const oe=["de","en","es","fr","it","nl","none","pt"],re=e=>oe.includes(e),se="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",ae="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",ce="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",ue="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",fe="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",de="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",le="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ê",me=/[\u0300-\u036F]/gu,W=e=>e.normalize("NFD").replaceAll(me,"").normalize("NFC").toLowerCase(),g=e=>new Set(W(e).split(" ")),$e={de:g(ae),en:g(se),es:g(ce),fr:g(ue),it:g(fe),nl:g(de),none:new Set,pt:g(le)},he=2,we=256,j=new Map,y=e=>{const n=e!==void 0&&re(e)?e:"none",i=j.get(n);if(i)return i;const o=$e[n],r=a=>{const c=(W(a).match(/[\p{L}\p{N}]+/gu)??[]).filter(u=>u.length<=we);return o.size===0?c:c.filter(u=>!o.has(u))},s={document:r,profile:`${n}-v${String(he)}`,query:a=>{const c=r(a);return c.filter((u,f)=>c.lastIndexOf(u)===f)}};return j.set(n,s),s},Se=(e,n)=>e.profile!==n?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},pe=(e,n)=>{if(!n.includes("."))return e[n];let i=e;for(const o of n.split(".")){if(i===null||typeof i!="object"||Array.isArray(i))return;i=i[o]}return i},I=(e,n)=>`${e}__fts_${n}`,Ee="__text__",l="__id__",T="__token__",D="__n__",ge=1e3,Q=(e,n)=>n.document(e),L=(e,n)=>pe(e,n),_e=e=>typeof e=="string"?e:e==null?"":typeof e=="number"||typeof e=="bigint"||typeof e=="boolean"?String(e):JSON.stringify(e)??"",ye=(e,n,i)=>e!==void 0&&n!==void 0&&L(e,i.field)===L(n,i.field),O=(e,n)=>Q(_e(L(e,n.field)),y(n.language)).slice(0,ge).join(" "),Te=(e,n)=>{const i=new Map;for(const o of Q(e,n))i.set(o,(i.get(o)??0)+1);return i},Ne=e=>{const n=new TextEncoder().encode(e);let i="";for(const o of n)i+=String.fromCodePoint(o);return btoa(i)},ve=e=>{const n=atob(e),i=Uint8Array.from(n,o=>o.codePointAt(0)??0);return new TextDecoder().decode(i)},Ie=()=>new S("BAD_REQUEST","invalid cursor"),B=16,F=8,p=1024,R=(e,n)=>n.query(e),Re=(e,n)=>{if(!n)return{exact:!0,lower:e,upper:e};const i=[...e].at(-1)??"",o=(i.codePointAt(0)??0)+1;if(o>=55296&&o<=57343||o>1114111)return{exact:!0,lower:e,upper:e};const r=e.slice(0,e.length-i.length);return{exact:!1,lower:e,upper:r+String.fromCodePoint(o)}},He=(e,n,i)=>{const o={eq:(r,s)=>{if(!e.definition.filterFields?.includes(r))throw new S("INTERNAL",`field "${r}" is not a filter field of search index "${e.indexName}" on table "${n}"`);if(e.filters.length>=F)throw new S("BAD_REQUEST",`search index "${e.indexName}" on table "${n}": at most ${String(F)} .eq() filters are supported per search query`);return e.filters.push({field:r,value:s}),o},search:(r,s)=>{const a=e;if(r!==a.definition.field)throw new S("INTERNAL",`search index "${a.indexName}" on table "${n}" indexes "${a.definition.field}", not "${r}"`);const c=R(s,i).length;if(c>B)throw new S("BAD_REQUEST",`search index "${a.indexName}" on table "${n}": at most ${String(B)} search terms are supported (got ${String(c)})`);return a.field=r,a.query=s,a.hasQuery=!0,o}};return o},Pe=e=>{if(e.length>p)throw new S("BAD_REQUEST",`more than ${String(p)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},ze=e=>Math.min(e.offset+e.numItems+1,p),Ae=e=>Ne(`search:${String(e)}`),be=e=>{let n;try{n=ve(e)}catch{return}if(!n.startsWith("search:"))return;const i=Number(n.slice(7));return Number.isInteger(i)&&i>=0?i:void 0},We=e=>{if(typeof e.endCursor=="string")throw new S("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const n=Math.max(0,Math.floor(e.numItems)),i=e.cursor?be(e.cursor):0;if(i===void 0)throw Ie();if(i+n>p)throw new S("BAD_REQUEST",`search pagination reaches past the ${String(p)}-document limit (offset ${String(i)} + ${String(n)} requested) — narrow the query or the filters instead`);return{numItems:n,offset:i}},Qe=(e,n)=>{const i=n.offset+n.numItems,o=n.numItems>0&&e.length>i;return{continueCursor:o?Ae(i):null,isDone:!o,page:e.slice(n.offset,i)}},Ge=e=>{if(e===void 0)return p+1;if(!Number.isFinite(e))return p;const n=Math.max(0,Math.floor(e));if(n>p)throw new S("BAD_REQUEST",`search returns at most ${String(p)} documents (asked for ${String(n)}) — narrow the query or paginate instead`);return n},A=async(e,n,i,o)=>{await h(e,n,t`DELETE FROM ${t.identifier(i)} WHERE ${t.identifier(l)} = ${o}`)},b=(e,n)=>e.name==="mysql"?t`${t.identifier(n)}(191)`:e.textPatternOperatorClass===void 0?t`${t.identifier(n)}`:t`${t.identifier(n)} ${t.raw(e.textPatternOperatorClass)}`,k=50,De=(e,n)=>n?t`${t.identifier(T)} LIKE ${`${e}%`}`:t`${t.identifier(T)} = ${e}`,G=(e,n)=>{const i=n.filters.map(o=>t`m.${M(o.field)} = ${te(o.value)}`);return e.softDeleteMode&&i.push(t`m.${M(e.softDeleteMode.field)} IS NULL`),i},V=async(e,n,i,o,r,s,a)=>{const c=G(i,r);let u=t`SELECT m.* FROM (${a}) s JOIN ${t.identifier(o)} m ON m.${t.identifier("id")} = s.${t.identifier(l)}`;return c.length>0&&(u=t`${u} WHERE ${t.join(c,t` AND `)}`),u=t`${u} ORDER BY s.${t.identifier("__score__")} DESC, m.${t.identifier("_creationTime")} DESC, m.${t.identifier("id")} ASC LIMIT ${t.raw(String(s))}`,z(i,await C(e,n,u))},Le=async(e,n,i,o,r,s)=>{const a=R(r.query,y(r.definition.language));if(a.length===0)return[];const c=I(o,r.indexName),u=a.length-1,f=a.map((d,_)=>De(d,_===u)),m=t.join(f,t` OR `),$=f.map(d=>t`SUM(CASE WHEN ${d} THEN ${t.identifier(D)} ELSE 0 END)`),E=t.join($.map(d=>t`${d} > 0`),t` AND `),w=t`SELECT ${t.identifier(l)}, ${t.join($,t` + `)} AS ${t.identifier("__score__")} FROM ${t.identifier(c)} WHERE ${m} GROUP BY ${t.identifier(l)} HAVING ${E}`;return V(e,n,i,o,r,s,w)},Ce=async(e,n,i,o,r,s)=>{const a=R(r.query,y(r.definition.language));if(a.length===0)return[];const c=I(o,r.indexName),u=`${c}__vocab`,f=a.length-1,m=a.map((w,d)=>{const _=Re(w,d===f),K=_.exact?t`${t.identifier("term")} = ${_.lower}`:t`${t.identifier("term")} >= ${_.lower} AND ${t.identifier("term")} < ${_.upper}`;return t`SELECT ${t.identifier("doc")}, ${t.raw(String(d))} AS ${t.identifier("__term__")}, COUNT(*) AS ${t.identifier("__n__")} FROM ${t.identifier(u)} WHERE ${K} GROUP BY ${t.identifier("doc")}`}),$=a.map((w,d)=>t`SUM(CASE WHEN u.${t.identifier("__term__")} = ${t.raw(String(d))} THEN u.${t.identifier("__n__")} ELSE 0 END)`),E=t`SELECT f.${t.identifier(l)} AS ${t.identifier(l)}, ${t.join($,t` + `)} AS ${t.identifier("__score__")} FROM (${ee(m)}) u JOIN ${t.identifier(c)} f ON f.rowid = u.${t.identifier("doc")} GROUP BY f.${t.identifier(l)} HAVING ${t.join($.map(w=>t`${w} > 0`),t` AND `)}`;return V(e,n,i,o,r,s,E)},Oe=async(e,n,i,o,r,s)=>{const a=n.nativeTextSearch,c=R(r.query,y(r.definition.language));if(!a||c.length===0)return[];const u=I(o,r.indexName),f=[a.matches(u,c),...G(i,r)],m=t`SELECT m.* FROM ${t.identifier(u)} JOIN ${t.identifier(o)} m ON m.${t.identifier("id")} = ${t.identifier(u)}.${t.identifier(l)} WHERE ${t.join(f,t` AND `)} ORDER BY ${a.rank(u,c)} DESC, m.${t.identifier("_creationTime")} DESC, m.${t.identifier("id")} ASC LIMIT ${t.raw(String(s))}`;return z(i,await C(e,n,m))},qe={ensureCompanion:async(e,n,i)=>{const{integer:o,key:r}=n.companionTypes;await h(e,n,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier(T)} ${t.raw(r)} NOT NULL, ${t.identifier(l)} ${t.raw(r)} NOT NULL, ${t.identifier(D)} ${t.raw(o)} NOT NULL)`),await U(e,n,{columns:t`${b(n,T)}, ${b(n,l)}`,name:`${i}__btree`,table:i,unique:!1}),await U(e,n,{columns:b(n,l),name:`${i}__by_id`,table:i,unique:!1})},indexDocument:async(e,n,i,o,r,s)=>{await A(e,n,i,o);const a=[...Te(O(r,s),y(s.language))],c=t.join([T,l,D].map(f=>t.identifier(f)),t`, `),u=[];for(let f=0;f<a.length;f+=k){const m=t.join(a.slice(f,f+k).map(([$,E])=>t`(${$}, ${o}, ${E})`),t`, `);u.push(t`INSERT INTO ${t.identifier(i)} (${c}) VALUES ${m}`)}await ne(e,n,u)},name:"inverted",runSearch:Le},xe={ensureCompanion:async(e,n,i)=>{await h(e,n,t`CREATE VIRTUAL TABLE IF NOT EXISTS ${t.identifier(i)} USING fts5(${t.identifier(Ee)}, ${t.identifier(l)} UNINDEXED)`),await h(e,n,t`CREATE VIRTUAL TABLE IF NOT EXISTS ${t.identifier(`${i}__vocab`)} USING fts5vocab(${t.identifier(i)}, ${t.raw("instance")})`)},indexDocument:async(e,n,i,o,r,s)=>{await A(e,n,i,o),await h(e,n,t`INSERT INTO ${t.identifier(i)} (${t.identifier("__text__")}, ${t.identifier(l)}) VALUES (${O(r,s)}, ${o})`)},name:"fts5",runSearch:Ce},Ue={ensureCompanion:async(e,n,i)=>{const o=n.nativeTextSearch;if(o){await h(e,n,o.createCompanion(i,n.companionTypes.key));for(const r of o.createIndexes(i))await h(e,n,r)}},indexDocument:async(e,n,i,o,r,s)=>{const a=n.nativeTextSearch;a&&(await A(e,n,i,o),await h(e,n,a.indexDocument(i,o,O(r,s))))},name:"native",runSearch:Oe},N=(e,n)=>e.strategy==="native"&&n.nativeTextSearch!==void 0?Ue:n.supportsFts5?xe:qe,J=(e,n)=>`${y(e.language).profile}/${N(e,n).name}`,q=function*(e){for(const[n,i]of Object.entries(e.tables)){const o=i.searchIndexes;if(!(i.shardMode!==void 0&&i.shardMode.kind!=="global"||!o))for(const r of o)yield[n,i,r]}},x=(e,n)=>I(e,n.name),Ve=async(e,n,i,o,r,s)=>N(r.definition,n).runSearch(e,n,i,o,r,s),H=200,X=async(e,n,i,o,r)=>{const s=x(o,r),a=N(r,n),c=J(r,n),u=Se(await P(e,n,s),c);if(u.finished)return!0;if(u.wipe&&(await h(e,n,t`DELETE FROM ${t.identifier(s)}`),await v(e,n,s,void 0,!1,c)),(await C(e,n,n.tableExists(o))).length===0)return await v(e,n,s,void 0,!0,c),!0;let m=0,$=u.cursor;await ie(e,n,i,o,async w=>{m+=1;const d=w._id;typeof d=="string"&&($=d,await a.indexDocument(e,n,s,d,w,r))},{after:u.cursor,limit:H});const E=m<H;return await v(e,n,s,$,E,c),E},Y=async(e,n,i)=>{await Z(e,i);for(const[o,,r]of q(n)){const s=x(o,r),a=J(r,i),c=await P(e,i,s);c.profile!==void 0&&c.profile!==a&&(await h(e,i,t`DROP TABLE IF EXISTS ${t.identifier(s)}`),await v(e,i,s,void 0,!1,a)),await N(r,i).ensureCompanion(e,i,s)}},Je=async(e,n,i)=>{await Y(e,n,i);for(const[o,r,s]of q(n))s.staged||await X(e,i,r,o,s)},Xe=async(e,n,i)=>{await Y(e,n,i);for(const[o,r,s]of q(n)){let a=!1;for(;!a;)a=await X(e,i,r,o,s)}},Ye=e=>{const{dialect:n,exec:i,schema:o}=e;return async(r,s,a,c)=>{const u=o.tables[r]?.searchIndexes;if(!(!u||u.length===0))for(const f of u){if(ye(c,a,f))continue;const m=x(r,f);if(a){await N(f,n).indexDocument(i,n,m,s,a,f);continue}await A(i,n,m,s)}}};export{Ge as B,We as D,Qe as M,He as R,ze as _,Ve as a,Xe as b,Ye as c,y as j,Je as r,Pe as y};