@lunora/sql-store 1.0.0-alpha.66 → 1.0.0-alpha.68

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