@lunora/sql-store 1.0.0-alpha.70 → 1.0.0-alpha.71
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.d.mts +7 -6
- package/dist/index.d.ts +7 -6
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{SEARCH_STATE_TABLE-DT7nfOye.mjs → SEARCH_STATE_TABLE-Bw9dhHy2.mjs} +1 -1
- package/dist/packem_shared/{backfillSqlSearchIndexes-DJNCwy44.mjs → backfillSqlSearchIndexes-DJXPzGlf.mjs} +1 -1
- package/dist/packem_shared/{createSqlCtxDb-DGQ1bJSP.mjs → createSqlCtxDb-LDUa2axW.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-search-IjbCKWI8.mjs → ctx-db-search-BLgb2vJY.mjs} +1 -1
- package/dist/packem_shared/decodeBigint-DrEQib7C.mjs +1 -0
- package/dist/packem_shared/{decodeGlobalRow-DOhQ8Anj.mjs → decodeGlobalRow-BwzH1RLd.mjs} +1 -1
- package/package.json +2 -2
- package/dist/packem_shared/decodeBigint-DWHvvLGA.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -170,12 +170,13 @@ declare const tryJsonParse: (raw: string) => unknown;
|
|
|
170
170
|
/** Decode a `bigint` column: a decimal string back into a `BigInt`, else verbatim. */
|
|
171
171
|
declare const decodeBigint: (raw: unknown) => unknown;
|
|
172
172
|
/**
|
|
173
|
-
* Resolve the *effective* storage kind of a column validator.
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
*
|
|
178
|
-
*
|
|
173
|
+
* Resolve the *effective* storage kind of a column validator: `v.optional(inner)`
|
|
174
|
+
* unwrapped to `inner`'s kind, since encoding keys off the runtime value's JS
|
|
175
|
+
* type and the validator's own `kind` of `"optional"` hides that.
|
|
176
|
+
*
|
|
177
|
+
* A thin alias over `shared/effective-kind`, which is where the rule lives so
|
|
178
|
+
* the DO row store applies the identical one — it reads the same validators and
|
|
179
|
+
* has the same failure mode, and two copies drifted the last time.
|
|
179
180
|
*/
|
|
180
181
|
declare const effectiveColumnKind: (validator: ValidatorLike) => string | undefined;
|
|
181
182
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -170,12 +170,13 @@ declare const tryJsonParse: (raw: string) => unknown;
|
|
|
170
170
|
/** Decode a `bigint` column: a decimal string back into a `BigInt`, else verbatim. */
|
|
171
171
|
declare const decodeBigint: (raw: unknown) => unknown;
|
|
172
172
|
/**
|
|
173
|
-
* Resolve the *effective* storage kind of a column validator.
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
*
|
|
178
|
-
*
|
|
173
|
+
* Resolve the *effective* storage kind of a column validator: `v.optional(inner)`
|
|
174
|
+
* unwrapped to `inner`'s kind, since encoding keys off the runtime value's JS
|
|
175
|
+
* type and the validator's own `kind` of `"optional"` hides that.
|
|
176
|
+
*
|
|
177
|
+
* A thin alias over `shared/effective-kind`, which is where the rule lives so
|
|
178
|
+
* the DO row store applies the identical one — it reads the same validators and
|
|
179
|
+
* has the same failure mode, and two copies drifted the last time.
|
|
179
180
|
*/
|
|
180
181
|
declare const effectiveColumnKind: (validator: ValidatorLike) => string | undefined;
|
|
181
182
|
/**
|
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-
|
|
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-LDUa2axW.mjs";import{A as s,B as d}from"./packem_shared/ctx-db-search-BLgb2vJY.mjs";import{SEARCH_STATE_TABLE as q,migrateSearchState as f}from"./packem_shared/SEARCH_STATE_TABLE-Bw9dhHy2.mjs";import{decodeBigint as C,effectiveColumnKind as x,sqliteDecode as u,sqliteEncode as b,tryJsonParse as h}from"./packem_shared/decodeBigint-DrEQib7C.mjs";import{decodeGlobalRow as A}from"./packem_shared/decodeGlobalRow-BwzH1RLd.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};
|
package/dist/packem_shared/{SEARCH_STATE_TABLE-DT7nfOye.mjs → SEARCH_STATE_TABLE-Bw9dhHy2.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as i}from"drizzle-orm";import{queryRun as $,queryAll as E}from"./decodeGlobalRow-
|
|
1
|
+
import{sql as i}from"drizzle-orm";import{queryRun as $,queryAll as E}from"./decodeGlobalRow-BwzH1RLd.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-
|
|
1
|
+
import{A as o,F as t,v as s,B as l}from"./ctx-db-search-BLgb2vJY.mjs";import"@lunora/errors";import"drizzle-orm";import"./SEARCH_STATE_TABLE-Bw9dhHy2.mjs";import"./decodeGlobalRow-BwzH1RLd.mjs";export{o as backfillSqlSearchIndexes,t as createSearchSync,s as runSqlSearch,l as runSqlSearchMigrations};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as N}from"@lunora/errors";import{F as bt,B as gt,T as Nt,x as Tt,_ as vt,C as Rt,v as St,D as It,b as At,N as Lt}from"./ctx-db-search-IjbCKWI8.mjs";import{A as Ci}from"./ctx-db-search-IjbCKWI8.mjs";import{aggregateTableName as G,rankTableName as Q,hasTrigger as kt,runRowValidators as ke,assertFlatPredicate as Je,mergeWhere as M,sortColumnName as z,resolveRankPartition as Xe,encodePartitionKey as Te,decodeCursor as Qe,RANK_TIEBREAK as $e,CountRlsUnsupportedError as Ze,normalizeIdStructurally as Ot,assertValidClientId as Ct,aggregateSqlFunction as ue,softDeleteScope as fe,compileWhereSql as _e,normalizeOrderKeys as Mt,buildSeekWhere as xt,resolveRelationPredicates as et,resolveWith as tt,relationHooks as it,applySelect as nt,encodeCursor as Dt,NotFoundError as Wt,applyOnDelete as qt,ConflictError as we,normalizeCountArgument as Bt,selectIndexForCount as Ft,encodeAggregateKey as Y,selectIndexForAggregate as Ut,readAggregateValue as Oe,runTriggers as jt,matchesRankStaticWhere as at,selectIndexForGroupBy as Pt,fanOutScalarCounts as Ht,matchesStaticWhere as Ce,foldAggregateTally as Kt,coerceAggregateNumber as Me,NotUniqueError as Vt,throwingScheduler as Yt}from"@lunora/shard-engine";import{sql as e}from"drizzle-orm";import{migrateSearchState as Gt}from"./SEARCH_STATE_TABLE-DT7nfOye.mjs";import{queryAll as I,queryRun as A,createIndexIfNotExists as De,decodeRow as Z,serializeColumnValue as H,columnRefSql as x,decodeRows as zt,forEachRowPaged as ot,queryBatch as rt}from"./decodeGlobalRow-DOhQ8Anj.mjs";import{decodeGlobalRow as xi}from"./decodeGlobalRow-DOhQ8Anj.mjs";import{effectiveColumnKind as ve}from"./decodeBigint-DWHvvLGA.mjs";const Jt=(l,w)=>{if(l.size<w)return;const _=l.keys().next().value;_!==void 0&&l.delete(_)},Xt=(l,w={})=>{const _=w.maxBatch??50,o=Number.isInteger(_)&&_>0?_:50,E=new Map;let c=!1;const s=async(y,v)=>{const R=[...v.keys()];for(let L=0;L<R.length;L+=o){const D=R.slice(L,L+o);try{const B=await l(y,D);for(const K of D){const F=B.get(K);for(const Se of v.get(K)??[])Se.resolve(F)}}catch(B){for(const K of D)for(const F of v.get(K)??[])F.reject(B)}}},T=()=>{c=!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 D=E.get(y);D||(D=new Map,E.set(y,D));const B=D.get(v);B?B.push({reject:L,resolve:R}):D.set(v,[{reject:L,resolve:R}]),c||(c=!0,queueMicrotask(T))})}}},Qt=new Set(["_id","id"]),We=(l,w,_)=>l==="postgres"?e`${w} IS NOT DISTINCT FROM ${_}`:l==="mysql"?e`${w} <=> ${_}`:e`${w} IS ${_}`,Zt=l=>{const w=l.map(_=>e`${x(_.field)} ${e.raw(_.direction==="desc"?"DESC":"ASC")}`);return l.some(_=>Qt.has(_.field))||w.push(e`${x("id")} ASC`),e.join(w,e`, `)},st=50,qe=l=>{const w=[];for(const[_,o]of Object.entries(l.shape)){const E=o._meta?.column;E&&w.push([_,E])}return w},ei=(l,w,_)=>{const o={...w};for(const[E,c]of qe(l)){if(c.serverDefault){o[E]=c.serverDefault({auth:_});continue}o[E]===void 0&&(c.defaultFn?o[E]=c.defaultFn():"defaultValue"in c&&(o[E]=c.defaultValue))}return o},ct=(l,w,_,o)=>{for(const[E,c]of qe(l)){if(c.serverDefault){E in w&&(_[E]=c.serverDefault({auth:o}));continue}c.onUpdateFn&&!(E in w)&&(_[E]=c.onUpdateFn())}},ti=128,ii=()=>{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):Jt(l,ti),l.set(w,_)}}},ni=async(l,w,_,o,E)=>{const c=E.get(o);if(c!==void 0)return c;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")} = ${o} LIMIT 1`)).length>0,tableName:y})));for(const y of T)if(y.found)return E.set(o,y.tableName),y.tableName},ee=l=>l==null?null:Number(l),ai=(l,w)=>w.map(_=>{const o={};for(const E of l)o[E]=_[E]??null;return{key:o,value:ee(_.value)}}),oi=(l,w,_)=>[...l.partitionBy??[],...l.sortBy.map(o=>o.field),...l.where?Object.keys(l.where):[]].every(o=>w[o]===_[o]),dt=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`, `),ri=(l,w,_,o,E)=>{const c=[];for(let s=0;s<_.length+1;s+=1){const T=_.slice(0,s).map(R=>We(l,e`${e.identifier(R)}`,o[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"?">":"<")} ${o[y]}`):T.push(e`${e.identifier($e)} < ${E}`),c.push(dt(T))}return c.length>0?e.join(c,e` OR `):void 0},si=(l,w,_)=>{if(_.length!==w.length)return;const o=[];for(const[E,c]of w.entries()){const s=[];for(let T=0;T<E;T+=1){const y=w[T];y!==void 0&&s.push(We(l,e`${e.identifier(y.column)}`,_[T]))}s.push(e`${e.identifier(c.column)} ${e.raw(c.direction==="desc"?"<":">")} ${_[E]}`),o.push(dt(s))}return e`(${e.join(o,e` OR `)})`},ci=(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[o,E]of l.sortBy.entries())_.push({column:w[o]??z(o),direction:E.direction});return _.push({column:$e,direction:"asc"}),_},di=async(l,w,_,o,E)=>{const c=[];for(let v=0;v<E.length;v+=50)c.push(E.slice(v,v+50));const s=await Promise.all(c.map(async v=>I(l,w,e`SELECT * FROM ${e.identifier(o)} 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},li=l=>{const w=JSON.stringify(l),_=new TextEncoder().encode(w);let o="";for(const E of _)o+=String.fromCodePoint(E);return btoa(o)},ui=(l,w)=>w.columnType(ve(l)),fi=(l,w)=>{const _=[];for(const[E,c]of Object.entries(l.shape)){if(!c._meta?.column)continue;const s=c._meta.column.notNull&&c.kind!=="optional"?" NOT NULL":"";_.push(e`${e.identifier(E)} ${e.raw(`${ui(c,w)}${s}`)}`)}const o=w.frameworkColumns().map(E=>e`${e.identifier(E.name)} ${e.raw(E.type)}`);return e.join([...o,..._],e`, `)},_i=async(l,w,_,o)=>{const E=c=>{const s=x(c),T=_.shape[c],y=T&&o.indexKeyPrefix?o.indexKeyPrefix(ve(T)):void 0;return y===void 0?s:e`${s}(${e.raw(String(y))})`};for(const c of _.indexes){const s=e.join(c.fields.map(T=>E(T)),e`, `);await De(l,o,{columns:s,name:`${w}_${c.name}`,table:w,unique:c.unique??!1})}for(const[c,s]of qe(_))s.unique&&await De(l,o,{columns:E(c),name:`${w}_unique_${c}`,table:w,unique:!0})},wi=async(l,w,_)=>{for(const[o,E]of Object.entries(w.tables)){if(E.shardMode?.kind!=="global")continue;const c=fi(E,_);await A(l,_,e`CREATE TABLE IF NOT EXISTS ${e.identifier(o)} (${c})`),await _i(l,o,E,_)}},$i=async(l,w,_)=>{const{integer:o,key:E,real:c}=_.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(c)}, ${e.identifier("__count__")} ${e.raw(o)} 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(o)} NOT NULL DEFAULT 0`))}}},xe=(l,w,_,o)=>{const E=l.name==="mysql"&&o?e`${e.identifier(w)}(191)`:e`${e.identifier(w)}`;return e`${E} ${e.raw(_)}`},hi=(l,w,_)=>{const o=[xe(l,"__partition__","ASC",!0)];for(const[E,c]of w.sortBy.entries()){const s=_.shape[c.field],T=s!==void 0&&l.indexKeyPrefix?.(ve(s))!==void 0;o.push(xe(l,z(E),c.direction==="desc"?"DESC":"ASC",T))}return o.push(xe(l,"__id__","ASC",!0)),o},pi=(l,w,_)=>w.sortBy.map((o,E)=>{const c=_.shape[o.field],s=l.columnType(c?ve(c):void 0);return e`${e.identifier(z(E))} ${e.raw(s)}`}),Ei=async(l,w,_)=>{const{key:o}=_.companionTypes;for(const[E,c]of Object.entries(w.tables)){const s=c.rankIndexes;if(!(!s||s.length===0))for(const T of s){const y=Q(E,T.name),v=pi(_,T,c),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(o)} PRIMARY KEY, ${e.identifier("__partition__")} ${e.raw(o)} NOT NULL${R})`);const L=hi(_,T,c),D=`${E}__rank_${T.name}__btree`;await De(l,_,{columns:e.join(L,e`, `),name:D,table:y,unique:!1})}}},Re="__cdc_log",mi=async(l,w)=>{const{autoincrementPrimaryKey:_,key:o,real:E,text:c}=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(o)} NOT NULL, ${e.identifier("id")} ${e.raw(o)} NOT NULL, ${e.identifier("op")} ${e.raw(o)} NOT NULL, ${e.identifier("doc")} ${e.raw(c)})`)},yi=async(l,w,_,o,E,c,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}, ${_}, ${o}, ${E}, ${c===void 0?null:JSON.stringify(c)})`)},Ii=async(l,w,_)=>{const o=w.sinceSeq??0,E=Math.max(1,Math.min(w.limit??1e3,1e4)),c=(await I(l,_,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(Re)} WHERE seq > ${o} 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:c,cursor:c.at(-1)?.seq??o}},Ai=async(l,w,_)=>{await A(l,_,e`DELETE FROM ${e.identifier(Re)} WHERE ${e.identifier("seq")} <= ${w}`)},Li=l=>{const{crossShardCounter:w,crossShardReader:_,exec:o,maxRelationKeys:E,schema:c}=l,{dialect:s}=l,{isUniqueViolation:T}=s,y={fieldRef:x,serialize:H,...s.name==="mysql"?{likeContains:(t,i)=>e`${t} LIKE CONCAT('%', ${i}, '%') ESCAPE '\\\\'`}:{}},v=(t,i)=>We(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)}`,r=u=>s.name==="postgres"?e`${e.identifier(t.table)}.${e.identifier(u)}`:e`${e.identifier(u)}`,f=e.join(Object.entries(t.set(a,r)).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()),D=l.idGenerator??(()=>crypto.randomUUID()),B=l.cdc??!1,K=l.auth??{identity:null,userId:null},F=async(t,i,n,a)=>{B&&await yi(o,L(),t,i,n,a,s)},Se=l.scheduler??Yt,Ie=ii();let he=0,Ae;const U=async()=>(Ae??=(async()=>{await wi(o,c,s),await $i(o,c,s),await Ei(o,c,s),await Gt(o,s),await gt(o,c,s),B&&await mi(o,s)})().catch(t=>{throw Ae=void 0,t}),Ae),ie=async(t,i)=>{await U();const n=await ni(o,s,c,t,Ie);if(!(i!==void 0&&n!==i))return n},ne=new Map,Be=async(t,i)=>{const n=G(t,i);return(await I(o,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 Be(t,i.name))return ne.set(n,!1),!1;const r=c.tables[t];if(!r)return ne.set(n,!1),!1;const f=i.by??[],$=new Map;await ot(o,s,r,t,d=>{if(i.where&&!Ce(d,i.where))return;const h=Y(f,d);Kt($,h,i,d)});const u=G(t,i.name);await A(o,s,e`DELETE FROM ${e.identifier(u)}`);const p=[];for(const[d,h]of $)p.push(e`INSERT INTO ${e.identifier(u)} (${e.identifier("__key__")}, ${e.identifier("__value__")}, ${e.identifier("__count__")}) VALUES (${d}, ${h.value}, ${h.count})`);return await rt(o,s,p),ne.set(n,!0),!0},lt=async(t,i,n)=>{const a=ue(i.op),r=i.field??"",f=[];for(const p of i.by??[]){const d=H(n[p]??null);f.push(d===null?e`${x(p)} IS NULL`:e`${x(p)} = ${d}`)}for(const[p,d]of Object.entries(i.where??{})){const h=d!==null&&typeof d=="object"&&!Array.isArray(d)?d.eq:d,m=H(h);f.push(m===null?e`${x(p)} IS NULL`:e`${x(p)} = ${m}`)}const $=e`SELECT ${e.raw(a)}(${x(r)}) AS value FROM ${e.identifier(t)}`,u=await I(o,s,f.length>0?e`${$} WHERE ${e.join(f,e` AND `)}`:$);return ee(u[0]?.value)},ut=async(t,i)=>{await A(o,s,e`DELETE FROM ${e.identifier(t)} WHERE ${e.identifier("__key__")} = ${i} AND ${e.identifier("__count__")} <= 0`)},ft=async(t,i,n,a)=>{const r=G(t,i.name),{op:f}=i,$=i.field??"",u=n&&(!i.where||Ce(n,i.where))?n:void 0,p=a&&(!i.where||Ce(a,i.where))?a:void 0;if(!(!u&&!p)){if(f==="count"||f==="sum"||f==="avg"){const d=new Set;for(const[h,m]of[[u,-1],[p,1]]){if(!h)continue;const b=f==="count"?1:Me(h[$]);if(b===void 0)continue;const g=Y(i.by??[],h);d.add(g),await A(o,s,R({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(S,k)=>({__count__:e`${k("__count__")} + ${S("__count__")}`,__value__:f==="count"?e`${k("__value__")} + ${S("__value__")}`:e`COALESCE(${k("__value__")}, 0) + ${S("__value__")}`}),table:r,values:[g,m*b,m]}))}for(const h of d)await ut(r,h);return}if(u){const d=Y(i.by??[],u),h=Me(u[$]),m=(await I(o,s,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(r)} WHERE ${e.identifier("__key__")} = ${d}`))[0],b=ee(m?.value),g=(m?.count??0)-1;if(g<=0)await A(o,s,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__key__")} = ${d}`);else if(m&&h!==void 0&&b!==null&&h===b){const S=await lt(t,i,u);await A(o,s,e`UPDATE ${e.identifier(r)} SET ${e.identifier("__value__")} = ${S}, ${e.identifier("__count__")} = ${g} WHERE ${e.identifier("__key__")} = ${d}`)}else await A(o,s,e`UPDATE ${e.identifier(r)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${d}`)}if(p){const d=Y(i.by??[],p),h=Me(p[$]);if(h===void 0)await A(o,s,R({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(m,b)=>({__count__:e`${b("__count__")} + 1`}),table:r,values:[d,null,1]}));else{const m=f==="min"?"MIN":"MAX";await A(o,s,R({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(b,g)=>({__count__:e`${g("__count__")} + 1`,__value__:e`${e.raw(m)}(COALESCE(${g("__value__")}, ${b("__value__")}), ${b("__value__")})`}),table:r,values:[d,h,1]}))}}}},Ee=async t=>{const i=c.tables[t]?.aggregateIndexes;if(!(!i||i.length===0))for(const n of i)await pe(t,n)},ae=async(t,i,n)=>{const a=c.tables[t]?.aggregateIndexes;if(!(!a||a.length===0))for(const r of a){const f=`${t}::${r.name}`;(ne.get(f)??await Be(t,r.name))&&await ft(t,r,i,n)}},oe=new Map,Fe=async(t,i)=>{const n=Q(t,i);return(await I(o,s,s.tableExists(n))).length>0},Le=async(t,i)=>{const n=`${t}::rank::${i.name}`,a=oe.get(n);if(a!==void 0)return a;if(!await Fe(t,i.name))return oe.set(n,!1),!1;const r=c.tables[t];if(!r)return oe.set(n,!1),!1;const f=Q(t,i.name);await A(o,s,e`DELETE FROM ${e.identifier(f)}`);const $=i.sortBy.map((h,m)=>z(m)),u=X(["__id__","__partition__",...$]),p=[];await ot(o,s,r,t,h=>{if(i.where&&!at(h,i.where))return;const m=Te(i.partitionBy??[],h),b=i.sortBy.map(g=>H(h[g.field]??null));p.push([h._id,m,...b])});const d=p.map(h=>e`INSERT INTO ${e.identifier(f)} (${u}) VALUES (${te(h)})`);return await rt(o,s,d),oe.set(n,!0),!0},me=async t=>{const i=c.tables[t]?.rankIndexes;if(!(!i||i.length===0))for(const n of i)await Le(t,n)},J=async(t,i,n,a)=>{const r=c.tables[t],f=r?.rankIndexes;if(!f||f.length===0)return;const $=r?.softDeleteMode?.field,u=$===void 0||a===void 0?void 0:a[$],p=u!=null;for(const d of f){if(n!==void 0&&a!==void 0&&oi(d,n,a))continue;const h=`${t}::rank::${d.name}`;if(!(oe.get(h)??await Fe(t,d.name)))continue;const m=Q(t,d.name);if(n&&await A(o,s,e`DELETE FROM ${e.identifier(m)} WHERE ${e.identifier("__id__")} = ${i}`),a&&!p){if(d.where&&!at(a,d.where))continue;const b=d.sortBy.map((W,O)=>z(O)),g=X(["__id__","__partition__",...b]),S=Te(d.partitionBy??[],a),k=d.sortBy.map(W=>H(a[W.field]??null));await A(o,s,e`INSERT INTO ${e.identifier(m)} (${g}) VALUES (${te([i,S,...k])})`)}}},re=bt({dialect:s,exec:o,schema:c}),Ue=new Set;for(const[t,i]of Object.entries(c.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>st)throw he-=1,new we(`trigger recursion exceeded ${String(st)} levels on "${n.table}" — check for a self-triggering write`,"trigger");try{await jt({ctx:je,event:n,op:i,schema:c,tableName:n.table,timing:t})}finally{he-=1}},_t=async(t,i)=>{try{await A(o,s,i)}catch(n){throw T(n)?new we(`unique constraint violation on "${t}"`,"unique"):n}},ye=async(t,i)=>(await I(o,s,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} = ${i}`))[0],be=async(t,i,n,a)=>{if(a===void 0)return;const r=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 ${r}`:e`DELETE FROM ${e.identifier(t)} WHERE ${r}`,$=()=>{throw new we(`optimistic concurrency conflict on "${t}" — the row changed during this mutation; refetch and retry`,"occ")};try{if(s.supportsReturning)(await I(o,s,e`${f} RETURNING ${e.identifier("id")}`)).length===0&&$();else{const u=await A(o,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}},wt=(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))]}},$t=async(t,i,n,a)=>{const r=Pt(i,n.op,n.field,a.by,a.where);if(!r||!await pe(t,r.index))return;const f=G(t,r.index.name),$=Object.keys(r.partial);if($.length===(r.index.by??[]).length&&$.length>0){const u=Y(r.index.by??[],r.partial),p=await I(o,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 d=p[0];return[{key:{...r.partial},value:Oe(n.op,{count:d.count,value:ee(d.value)})}]}return $.length>0?void 0:(await I(o,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:Oe(n.op,{count:p.count,value:ee(p.value)})}})},Pe=t=>{const i=c.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`)},ht=(t,i)=>{if(i?.relationMask!==void 0&&i.with!==void 0&&Object.keys(i.with).length>0)throw new N("MASK_UNSUPPORTED",`masking cannot follow a nested \`with\` across the cross-shard relation hop to "${t}" — the nested rows are hydrated on the serving shard, where the mask policy does not exist. Read the nested relation at its own (masked) call site instead.`);const n={};if(i?.relationBaseWhere)for(const a of Object.keys(c.tables)){const r=i.relationBaseWhere(a);r!==void 0&&(n[a]=r)}return{orderBy:i?.orderBy,relationPolicies:n,where:M(i?.baseWhere,i?.where),with:i?.with}},Ke=(t,i)=>Pe(t)?_?_(t,ht(t,i)):He(t):q.findMany(t,i),ge=(t,i,n)=>et(t,{fetcher:Ke,maxRelationKeys:E,relationBaseWhere:n,schema:c,tableName:i}),pt=Xt(async(t,i)=>{const n=await I(o,s,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} IN (${te(i)})`),a=new Map;for(const r of n){const{id:f}=r;typeof f=="string"&&a.set(f,r)}return a}),q={async aggregate(t,i){const n=c.tables[t];if(!n)throw new N("INTERNAL",`unknown table: ${t}`);if(await U(),ue(i.op),i.op==="count")return q.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),r=M(M(i.baseWhere,i.where),a),f=await ge(r,t,i.relationBaseWhere),$=f!==r;if(n.aggregateIndexes&&!i.baseWhere&&!$&&!a){const m=Ut(n.aggregateIndexes,i.op,i.field,i.where);if(m&&await pe(t,m.index)){const b=Y(m.index.by??[],m.key),g=G(t,m.index.name),S=(await I(o,s,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(g)} WHERE ${e.identifier("__key__")} = ${b}`))[0];return Oe(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)),d=e`SELECT ${p}(${x(i.field)}) AS value FROM ${e.identifier(t)}`,h=(await I(o,s,u?e`${d} WHERE ${u}`:d))[0]?.value;return h==null?null:Number(h)},async count(t,i){const n=c.tables[t];if(!n)throw new N("INTERNAL",`unknown table: ${t}`);await U();const a=Bt(i);if(a.restrictsCounts)throw new Ze(t);const r=fe(n.softDeleteMode,void 0),f=M(M(a.baseWhere,a.where),r),$=await ge(f,t,a.relationBaseWhere),u=$!==f;if(n.aggregateIndexes&&!a.baseWhere&&!u&&!r){const m=Ft(n.aggregateIndexes,a.where);if(m&&await pe(t,m.index)){const b=Y(m.index.by??[],m.key),g=G(t,m.index.name),S=await I(o,s,e`SELECT ${e.identifier("__value__")} AS value FROM ${e.identifier(g)} WHERE ${e.identifier("__key__")} = ${b}`);return Number(S[0]?.value??0)}}const p=_e($,y),d=e`SELECT COUNT(*) AS count FROM ${e.identifier(t)}`,h=await I(o,s,p?e`${d} WHERE ${p}`:d);return Number(h[0]?.count??0)},async delete(t,i,n){const a=await ie(t,i);if(!a)return;const r=c.tables[a];if(!r)return;const f=await ye(a,t),$=Z(r,f),u=n?.hard===!0,p=!u&&r.softDeleteMode?r.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 qt({deletedId:t,deletedReference:d=>$?.[d],findHolders:async(d,h,m)=>{if(c.tables[d]?.shardMode?.kind==="shardBy")throw new N("INTERNAL",`cross-backend cascade from global '${a}' into shardBy '${d}' is not supported — would require Query Coordinator fan-out across shards`);return(await q.findMany(d,{includeDeleted:u,where:{[h]:m}})).page},onCascade:(d,h)=>q.delete(h,void 0,n),onRestrict:d=>{throw new we(d,"restrict")},onSetNull:(d,h,m)=>q.patch(h,{[m]:null}),schema:c,tableName:a}),await Ee(a),await me(a),p&&$){const d={...$,[p]:L()},h=e.join(Object.keys(r.shape).map(m=>e`${e.identifier(m)} = ${H(d[m]??null)}`),e`, `);await be(a,"UPDATE",h,f),await ae(a,$,d),await J(a,t,$,void 0),await re(a,t,d,$),await F(a,t,"update",d),j(a,"after","delete")&&await P("after","delete",{id:t,op:"delete",previous:$,table:a});return}await be(a,"DELETE",void 0,f),Ie.delete(t),await ae(a,$??void 0,void 0),await J(a,t,$??void 0,void 0),await re(a,t,void 0),await F(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 q.findMany(t,{...i,limit:1})).page[0]??null},async findFirstOrThrow(t,i={}){const n=await q.findFirst(t,i);if(n===null)throw new Wt(`findFirstOrThrow: no "${t}" document matched`);return n},async findMany(t,i={}){const n=c.tables[t];if(!n)throw new N("INTERNAL",`unknown table: ${t}`);await U();const a=Mt(i.orderBy),r=i.cursor?xt(a,Qe(i.cursor)):void 0,f=Ke,$=async(O,se,Ne,ce)=>{if(Pe(O))return w?Ht(w,O,se,Ne,ce):He(O);const V=c.tables[O];if(!V)throw new N("INTERNAL",`unknown table: ${O}`);const C=fe(V.softDeleteMode,void 0),de={[se]:{in:Ne}},Et=M(M(de,ce),C),mt=await ge(Et,O,void 0),Ve=_e(mt,y),Ye=x(se);let le=e`SELECT ${Ye} AS __fk__, COUNT(*) AS count FROM ${e.identifier(O)}`;Ve&&(le=e`${le} WHERE ${Ve}`),le=e`${le} GROUP BY ${Ye}`;const yt=await I(o,s,le),Ge=new Map;for(const ze of yt)Ge.set(ze.__fk__,Number(ze.count??0));return Ge};let u=M(i.baseWhere,i.where);u=M(u,fe(n.softDeleteMode,i.includeDeleted)),u=await et(u,{fetcher:f,maxRelationKeys:E,relationBaseWhere:i.relationBaseWhere,schema:c,tableName:t}),r&&(u=u?{AND:[u,r]}:r);const p=_e(u,y),d=Zt(a);let h=e`SELECT * FROM ${e.identifier(t)}`;p&&(h=e`${h} WHERE ${p}`),h=e`${h} ORDER BY ${d}`;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 b=await I(o,s,h),g=zt(n,b);if(m===void 0)return i.with&&await tt({fetcher:f,groupedCounter:$,parents:g,...it(i),schema:c,tableName:t,with:i.with}),{continueCursor:null,isDone:!0,page:nt(g,i.select,i.with)};const S=g.length>m,k=S?g.slice(0,m):g,W=k.at(-1);return i.with&&await tt({fetcher:f,groupedCounter:$,parents:k,...it(i),schema:c,tableName:t,with:i.with}),{continueCursor:S&&W?Dt(W,a):null,isDone:!S,page:nt(k,i.select,i.with)}},async get(t,i){const n=await ie(t,i);if(!n)return null;const a=c.tables[n];return a?Z(a,await pt.load(n,t)):null},async groupBy(t,i){const n=c.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 r=fe(n.softDeleteMode,void 0),f=M(M(i.baseWhere,i.where),r),$=await ge(f,t,i.relationBaseWhere),u=$!==f;if(n.aggregateIndexes&&!i.baseWhere&&!u&&!r){const g=await $t(t,n.aggregateIndexes,a,i);if(g!==void 0)return g}const p=_e($,y),d=i.by.map(g=>e`${x(g)} AS ${e.identifier(g)}`);if(a.op==="count")d.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`);d.push(e`${e.raw(ue(a.op))}(${x(a.field)}) AS value`)}const h=e.join(i.by.map(g=>x(g)),e`, `);let m=e`SELECT ${e.join(d,e`, `)} FROM ${e.identifier(t)}`;p&&(m=e`${m} WHERE ${p}`),m=e`${m} GROUP BY ${h}`;const b=await I(o,s,m);return ai(i.by,b)},async insert(t,i,n){const a=c.tables[t];if(!a)throw new N("INTERNAL",`unknown table: ${t}`);await U();const r=ei(a,i,K);ke(a,r);let f,$=!0;n?.clientId!==void 0?(Ct(n.clientId),f=n.clientId):n?.allowExplicitId&&typeof r._id=="string"?f=r._id:(f=D(),$=!1);const u=n?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:L(),p={...r,_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:d,values:h}=wt(a,f,u,r);return await _t(t,e`INSERT INTO ${e.identifier(t)} (${X(d)}) VALUES (${te(h)})`),$&&Ie.set(f,t),await ae(t,void 0,p),await J(t,f,void 0,p),await re(t,f,p),await F(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 Ot(c,t,i)},async patch(t,i,n){const a=await ie(t,n);if(!a)throw new N("INTERNAL",`document not found: ${t}`);const r=c.tables[a];if(!r)throw new N("INTERNAL",`document not found: ${t}`);const f=await ye(a,t),$=Z(r,f);if(!$)throw new N("INTERNAL",`document not found: ${t}`);const u={...$,...i,_id:t};ct(r,i,u,K),ke(r,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(r.shape),d=e.join(p.map(h=>e`${e.identifier(h)} = ${H(u[h]??null)}`),e`, `);await be(a,"UPDATE",d,f),await ae(a,$,u),await J(a,t,$,u),await re(a,t,u,$),await F(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=c.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 ye(n,t),$=f?.[r]!==null&&f?.[r]!==void 0;if(await q.patch(t,{[r]:null},i),$){const u=Z(a,f);u!==null&&await J(n,t,void 0,{...u,[r]:null})}},query(t){const i=c.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=u=>a.every(p=>p(u)),f=async(u,p)=>{await U();const d=a.length>0,h=await St(o,s,i,t,u,It(d?void 0:p));if(!d)return p===void 0&&At(h),h;const m=h.filter(b=>r(b));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(d){return a.push(d),p},async first(){if(!u)throw new N("INTERNAL",n);return(await f(u,1))[0]??null},order(){return p},async paginate(d){if(!u)throw new N("INTERNAL",n);const h=vt(d);return Rt(await f(u,Lt(h)),h)},async take(d){if(!u)throw new N("INTERNAL",n);return f(u,d)},async unique(){if(!u)throw new N("INTERNAL",n);const d=await f(u,2);if(d.length>1)throw new Vt(`unique() on table "${t}" matched ${String(d.length)} documents; expected at most one`);return d[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(d,h){const m=(i.searchIndexes??[]).find(g=>g.name===d);if(!m)throw new N("INTERNAL",`unknown search index "${d}" on table "${t}"`);const b={definition:m,field:m.field,filters:[],hasQuery:!1,indexName:d,query:""};if(h(Nt(b,t,Tt(m.language))),!b.hasQuery)throw new N("INTERNAL",`search index "${d}" on table "${t}" requires a .search(field, query) call`);return $(b)}};return p};return $(void 0)},async rank(t,i,n){const a=c.tables[t];if(!a)throw new N("INTERNAL",`unknown table: ${t}`);const r=a.rankIndexes?.find(W=>W.name===i);if(!r)throw new N("INTERNAL",`unknown rankIndex "${i}" on table "${t}"`);if(n.restrictsCounts)throw new Ze(t);if(await U(),!await Le(t,r))return null;const f=typeof n.row=="string"?n.row:n.row._id;if(!f)return null;const $=Q(t,r.name),u=r.sortBy.map((W,O)=>z(O)),p=X(["__partition__",...u]),d=(await I(o,s,e`SELECT ${p} FROM ${e.identifier($)} WHERE ${e.identifier("__id__")} = ${f}`))[0];if(!d)return null;const h=d.__partition__,m=M(n.baseWhere,n.where);Je(m,c,t,"rank");const b=Xe(r,m);if(b&&Te(r.partitionBy??[],b)!==h)return null;const g=ri(s.name,r,u,d,f),S=await I(o,s,e`SELECT COUNT(*) AS c FROM ${e.identifier($)} WHERE ${e.identifier("__partition__")} = ${h}${g?e` AND (${g})`:e``}`),k=await I(o,s,e`SELECT COUNT(*) AS c FROM ${e.identifier($)} WHERE ${e.identifier("__partition__")} = ${h}`);return{position:Number(S[0]?.c??0)+1,total:Number(k[0]?.c??0)}},async rankPage(t,i,n={}){Je(M(n.baseWhere,n.where),c,t,"rankPage");const a=c.tables[t];if(!a)throw new N("INTERNAL",`unknown table: ${t}`);const r=a.rankIndexes?.find(C=>C.name===i);if(!r)throw new N("INTERNAL",`unknown rankIndex "${i}" on table "${t}"`);if(await U(),!await Le(t,r))return{continueCursor:null,isDone:!0,page:[]};const f=Q(t,r.name),$=r.sortBy.map((C,de)=>z(de)),u=Math.max(1,Math.min(1e3,Math.floor(n.take??100))),p=M(n.baseWhere,n.where),d=Xe(r,p),h=ci(r,$),m=e.join(h.map(C=>e`${e.identifier(C.column)} ${e.raw(C.direction==="desc"?"DESC":"ASC")}`),e`, `),b=[];if(d&&b.push(e`${e.identifier("__partition__")} = ${Te(r.partitionBy??[],d)}`),n.cursor){const C=si(s.name,h,Qe(n.cursor));C!==void 0&&b.push(C)}const g=X([$e,"__partition__",...$]);let S=e`SELECT ${g} FROM ${e.identifier(f)}`;b.length>0&&(S=e`${S} WHERE ${e.join(b,e` AND `)}`),S=e`${S} ORDER BY ${m} LIMIT ${e.raw(String(u+1))}`;const k=await I(o,s,S),W=k.length>u,O=W?k.slice(0,u):k,se=O.map(C=>C[$e]),Ne=await di(o,s,a,t,se);let ce=null;const V=O.at(-1);if(W&&V!==void 0){const C=[V.__partition__,...$.map(de=>V[de]),V[$e]];ce=li(C)}return{continueCursor:ce,isDone:!W,page:Ne}},async replace(t,i,n,a){const r=await ie(t,n);if(!r)throw new N("INTERNAL",`document not found: ${t}`);const f=c.tables[r];if(!f)throw new N("INTERNAL",`document not found: ${t}`);const $=await ye(r,t);if($===void 0)throw new N("INTERNAL",`document not found: ${t}`);const u=kt(c,r,"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(),d={...i,_creationTime:p,_id:t};ct(f,i,d,K),ke(f,d),j(r,"before","update")&&await P("before","update",{doc:{...d},id:t,op:"update",previous:u,table:r}),await Ee(r),await me(r);const h=Object.keys(f.shape),m=e.join([e`${e.identifier("_creationTime")} = ${p}`,...h.map(b=>e`${e.identifier(b)} = ${H(d[b]??null)}`)],e`, `);await be(r,"UPDATE",m,$),await ae(r,u,d),await J(r,t,u,d),await re(r,t,d,u),await F(r,t,"update",d),j(r,"after","update")&&await P("after","update",{doc:d,id:t,op:"update",previous:u,table:r})}};return je={db:q,scheduler:Se},q};export{Ci as backfillSqlSearchIndexes,Li as createSqlCtxDb,xi as decodeGlobalRow,Ii as readSqlCdcChanges,$i as runSqlAggregateMigrations,mi as runSqlCdcMigration,wi as runSqlGlobalTableMigrations,Ei as runSqlRankMigrations,gt as runSqlSearchMigrations,Ai as trimSqlCdcChanges};
|
|
1
|
+
import{LunoraError as N}from"@lunora/errors";import{F as bt,B as gt,T as Nt,x as Tt,_ as vt,C as Rt,v as St,D as It,b as At,N as Lt}from"./ctx-db-search-BLgb2vJY.mjs";import{A as Ci}from"./ctx-db-search-BLgb2vJY.mjs";import{aggregateTableName as G,rankTableName as Q,hasTrigger as kt,runRowValidators as ke,assertFlatPredicate as Je,mergeWhere as M,sortColumnName as z,resolveRankPartition as Xe,encodePartitionKey as Te,decodeCursor as Qe,RANK_TIEBREAK as $e,CountRlsUnsupportedError as Ze,normalizeIdStructurally as Ot,assertValidClientId as Ct,aggregateSqlFunction as ue,softDeleteScope as fe,compileWhereSql as _e,normalizeOrderKeys as Mt,buildSeekWhere as xt,resolveRelationPredicates as et,resolveWith as tt,relationHooks as it,applySelect as nt,encodeCursor as Dt,NotFoundError as Wt,applyOnDelete as qt,ConflictError as we,normalizeCountArgument as Bt,selectIndexForCount as Ft,encodeAggregateKey as Y,selectIndexForAggregate as Ut,readAggregateValue as Oe,runTriggers as jt,matchesRankStaticWhere as at,selectIndexForGroupBy as Pt,fanOutScalarCounts as Ht,matchesStaticWhere as Ce,foldAggregateTally as Kt,coerceAggregateNumber as Me,NotUniqueError as Vt,throwingScheduler as Yt}from"@lunora/shard-engine";import{sql as e}from"drizzle-orm";import{migrateSearchState as Gt}from"./SEARCH_STATE_TABLE-Bw9dhHy2.mjs";import{queryAll as I,queryRun as A,createIndexIfNotExists as De,decodeRow as Z,serializeColumnValue as H,columnRefSql as x,decodeRows as zt,forEachRowPaged as ot,queryBatch as rt}from"./decodeGlobalRow-BwzH1RLd.mjs";import{decodeGlobalRow as xi}from"./decodeGlobalRow-BwzH1RLd.mjs";import{effectiveColumnKind as ve}from"./decodeBigint-DrEQib7C.mjs";const Jt=(l,w)=>{if(l.size<w)return;const _=l.keys().next().value;_!==void 0&&l.delete(_)},Xt=(l,w={})=>{const _=w.maxBatch??50,o=Number.isInteger(_)&&_>0?_:50,E=new Map;let c=!1;const s=async(y,v)=>{const R=[...v.keys()];for(let L=0;L<R.length;L+=o){const D=R.slice(L,L+o);try{const B=await l(y,D);for(const K of D){const F=B.get(K);for(const Se of v.get(K)??[])Se.resolve(F)}}catch(B){for(const K of D)for(const F of v.get(K)??[])F.reject(B)}}},T=()=>{c=!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 D=E.get(y);D||(D=new Map,E.set(y,D));const B=D.get(v);B?B.push({reject:L,resolve:R}):D.set(v,[{reject:L,resolve:R}]),c||(c=!0,queueMicrotask(T))})}}},Qt=new Set(["_id","id"]),We=(l,w,_)=>l==="postgres"?e`${w} IS NOT DISTINCT FROM ${_}`:l==="mysql"?e`${w} <=> ${_}`:e`${w} IS ${_}`,Zt=l=>{const w=l.map(_=>e`${x(_.field)} ${e.raw(_.direction==="desc"?"DESC":"ASC")}`);return l.some(_=>Qt.has(_.field))||w.push(e`${x("id")} ASC`),e.join(w,e`, `)},st=50,qe=l=>{const w=[];for(const[_,o]of Object.entries(l.shape)){const E=o._meta?.column;E&&w.push([_,E])}return w},ei=(l,w,_)=>{const o={...w};for(const[E,c]of qe(l)){if(c.serverDefault){o[E]=c.serverDefault({auth:_});continue}o[E]===void 0&&(c.defaultFn?o[E]=c.defaultFn():"defaultValue"in c&&(o[E]=c.defaultValue))}return o},ct=(l,w,_,o)=>{for(const[E,c]of qe(l)){if(c.serverDefault){E in w&&(_[E]=c.serverDefault({auth:o}));continue}c.onUpdateFn&&!(E in w)&&(_[E]=c.onUpdateFn())}},ti=128,ii=()=>{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):Jt(l,ti),l.set(w,_)}}},ni=async(l,w,_,o,E)=>{const c=E.get(o);if(c!==void 0)return c;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")} = ${o} LIMIT 1`)).length>0,tableName:y})));for(const y of T)if(y.found)return E.set(o,y.tableName),y.tableName},ee=l=>l==null?null:Number(l),ai=(l,w)=>w.map(_=>{const o={};for(const E of l)o[E]=_[E]??null;return{key:o,value:ee(_.value)}}),oi=(l,w,_)=>[...l.partitionBy??[],...l.sortBy.map(o=>o.field),...l.where?Object.keys(l.where):[]].every(o=>w[o]===_[o]),dt=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`, `),ri=(l,w,_,o,E)=>{const c=[];for(let s=0;s<_.length+1;s+=1){const T=_.slice(0,s).map(R=>We(l,e`${e.identifier(R)}`,o[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"?">":"<")} ${o[y]}`):T.push(e`${e.identifier($e)} < ${E}`),c.push(dt(T))}return c.length>0?e.join(c,e` OR `):void 0},si=(l,w,_)=>{if(_.length!==w.length)return;const o=[];for(const[E,c]of w.entries()){const s=[];for(let T=0;T<E;T+=1){const y=w[T];y!==void 0&&s.push(We(l,e`${e.identifier(y.column)}`,_[T]))}s.push(e`${e.identifier(c.column)} ${e.raw(c.direction==="desc"?"<":">")} ${_[E]}`),o.push(dt(s))}return e`(${e.join(o,e` OR `)})`},ci=(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[o,E]of l.sortBy.entries())_.push({column:w[o]??z(o),direction:E.direction});return _.push({column:$e,direction:"asc"}),_},di=async(l,w,_,o,E)=>{const c=[];for(let v=0;v<E.length;v+=50)c.push(E.slice(v,v+50));const s=await Promise.all(c.map(async v=>I(l,w,e`SELECT * FROM ${e.identifier(o)} 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},li=l=>{const w=JSON.stringify(l),_=new TextEncoder().encode(w);let o="";for(const E of _)o+=String.fromCodePoint(E);return btoa(o)},ui=(l,w)=>w.columnType(ve(l)),fi=(l,w)=>{const _=[];for(const[E,c]of Object.entries(l.shape)){if(!c._meta?.column)continue;const s=c._meta.column.notNull&&c.kind!=="optional"?" NOT NULL":"";_.push(e`${e.identifier(E)} ${e.raw(`${ui(c,w)}${s}`)}`)}const o=w.frameworkColumns().map(E=>e`${e.identifier(E.name)} ${e.raw(E.type)}`);return e.join([...o,..._],e`, `)},_i=async(l,w,_,o)=>{const E=c=>{const s=x(c),T=_.shape[c],y=T&&o.indexKeyPrefix?o.indexKeyPrefix(ve(T)):void 0;return y===void 0?s:e`${s}(${e.raw(String(y))})`};for(const c of _.indexes){const s=e.join(c.fields.map(T=>E(T)),e`, `);await De(l,o,{columns:s,name:`${w}_${c.name}`,table:w,unique:c.unique??!1})}for(const[c,s]of qe(_))s.unique&&await De(l,o,{columns:E(c),name:`${w}_unique_${c}`,table:w,unique:!0})},wi=async(l,w,_)=>{for(const[o,E]of Object.entries(w.tables)){if(E.shardMode?.kind!=="global")continue;const c=fi(E,_);await A(l,_,e`CREATE TABLE IF NOT EXISTS ${e.identifier(o)} (${c})`),await _i(l,o,E,_)}},$i=async(l,w,_)=>{const{integer:o,key:E,real:c}=_.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(c)}, ${e.identifier("__count__")} ${e.raw(o)} 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(o)} NOT NULL DEFAULT 0`))}}},xe=(l,w,_,o)=>{const E=l.name==="mysql"&&o?e`${e.identifier(w)}(191)`:e`${e.identifier(w)}`;return e`${E} ${e.raw(_)}`},hi=(l,w,_)=>{const o=[xe(l,"__partition__","ASC",!0)];for(const[E,c]of w.sortBy.entries()){const s=_.shape[c.field],T=s!==void 0&&l.indexKeyPrefix?.(ve(s))!==void 0;o.push(xe(l,z(E),c.direction==="desc"?"DESC":"ASC",T))}return o.push(xe(l,"__id__","ASC",!0)),o},pi=(l,w,_)=>w.sortBy.map((o,E)=>{const c=_.shape[o.field],s=l.columnType(c?ve(c):void 0);return e`${e.identifier(z(E))} ${e.raw(s)}`}),Ei=async(l,w,_)=>{const{key:o}=_.companionTypes;for(const[E,c]of Object.entries(w.tables)){const s=c.rankIndexes;if(!(!s||s.length===0))for(const T of s){const y=Q(E,T.name),v=pi(_,T,c),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(o)} PRIMARY KEY, ${e.identifier("__partition__")} ${e.raw(o)} NOT NULL${R})`);const L=hi(_,T,c),D=`${E}__rank_${T.name}__btree`;await De(l,_,{columns:e.join(L,e`, `),name:D,table:y,unique:!1})}}},Re="__cdc_log",mi=async(l,w)=>{const{autoincrementPrimaryKey:_,key:o,real:E,text:c}=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(o)} NOT NULL, ${e.identifier("id")} ${e.raw(o)} NOT NULL, ${e.identifier("op")} ${e.raw(o)} NOT NULL, ${e.identifier("doc")} ${e.raw(c)})`)},yi=async(l,w,_,o,E,c,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}, ${_}, ${o}, ${E}, ${c===void 0?null:JSON.stringify(c)})`)},Ii=async(l,w,_)=>{const o=w.sinceSeq??0,E=Math.max(1,Math.min(w.limit??1e3,1e4)),c=(await I(l,_,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(Re)} WHERE seq > ${o} 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:c,cursor:c.at(-1)?.seq??o}},Ai=async(l,w,_)=>{await A(l,_,e`DELETE FROM ${e.identifier(Re)} WHERE ${e.identifier("seq")} <= ${w}`)},Li=l=>{const{crossShardCounter:w,crossShardReader:_,exec:o,maxRelationKeys:E,schema:c}=l,{dialect:s}=l,{isUniqueViolation:T}=s,y={fieldRef:x,serialize:H,...s.name==="mysql"?{likeContains:(t,i)=>e`${t} LIKE CONCAT('%', ${i}, '%') ESCAPE '\\\\'`}:{}},v=(t,i)=>We(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)}`,r=u=>s.name==="postgres"?e`${e.identifier(t.table)}.${e.identifier(u)}`:e`${e.identifier(u)}`,f=e.join(Object.entries(t.set(a,r)).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()),D=l.idGenerator??(()=>crypto.randomUUID()),B=l.cdc??!1,K=l.auth??{identity:null,userId:null},F=async(t,i,n,a)=>{B&&await yi(o,L(),t,i,n,a,s)},Se=l.scheduler??Yt,Ie=ii();let he=0,Ae;const U=async()=>(Ae??=(async()=>{await wi(o,c,s),await $i(o,c,s),await Ei(o,c,s),await Gt(o,s),await gt(o,c,s),B&&await mi(o,s)})().catch(t=>{throw Ae=void 0,t}),Ae),ie=async(t,i)=>{await U();const n=await ni(o,s,c,t,Ie);if(!(i!==void 0&&n!==i))return n},ne=new Map,Be=async(t,i)=>{const n=G(t,i);return(await I(o,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 Be(t,i.name))return ne.set(n,!1),!1;const r=c.tables[t];if(!r)return ne.set(n,!1),!1;const f=i.by??[],$=new Map;await ot(o,s,r,t,d=>{if(i.where&&!Ce(d,i.where))return;const h=Y(f,d);Kt($,h,i,d)});const u=G(t,i.name);await A(o,s,e`DELETE FROM ${e.identifier(u)}`);const p=[];for(const[d,h]of $)p.push(e`INSERT INTO ${e.identifier(u)} (${e.identifier("__key__")}, ${e.identifier("__value__")}, ${e.identifier("__count__")}) VALUES (${d}, ${h.value}, ${h.count})`);return await rt(o,s,p),ne.set(n,!0),!0},lt=async(t,i,n)=>{const a=ue(i.op),r=i.field??"",f=[];for(const p of i.by??[]){const d=H(n[p]??null);f.push(d===null?e`${x(p)} IS NULL`:e`${x(p)} = ${d}`)}for(const[p,d]of Object.entries(i.where??{})){const h=d!==null&&typeof d=="object"&&!Array.isArray(d)?d.eq:d,m=H(h);f.push(m===null?e`${x(p)} IS NULL`:e`${x(p)} = ${m}`)}const $=e`SELECT ${e.raw(a)}(${x(r)}) AS value FROM ${e.identifier(t)}`,u=await I(o,s,f.length>0?e`${$} WHERE ${e.join(f,e` AND `)}`:$);return ee(u[0]?.value)},ut=async(t,i)=>{await A(o,s,e`DELETE FROM ${e.identifier(t)} WHERE ${e.identifier("__key__")} = ${i} AND ${e.identifier("__count__")} <= 0`)},ft=async(t,i,n,a)=>{const r=G(t,i.name),{op:f}=i,$=i.field??"",u=n&&(!i.where||Ce(n,i.where))?n:void 0,p=a&&(!i.where||Ce(a,i.where))?a:void 0;if(!(!u&&!p)){if(f==="count"||f==="sum"||f==="avg"){const d=new Set;for(const[h,m]of[[u,-1],[p,1]]){if(!h)continue;const b=f==="count"?1:Me(h[$]);if(b===void 0)continue;const g=Y(i.by??[],h);d.add(g),await A(o,s,R({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(S,k)=>({__count__:e`${k("__count__")} + ${S("__count__")}`,__value__:f==="count"?e`${k("__value__")} + ${S("__value__")}`:e`COALESCE(${k("__value__")}, 0) + ${S("__value__")}`}),table:r,values:[g,m*b,m]}))}for(const h of d)await ut(r,h);return}if(u){const d=Y(i.by??[],u),h=Me(u[$]),m=(await I(o,s,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(r)} WHERE ${e.identifier("__key__")} = ${d}`))[0],b=ee(m?.value),g=(m?.count??0)-1;if(g<=0)await A(o,s,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__key__")} = ${d}`);else if(m&&h!==void 0&&b!==null&&h===b){const S=await lt(t,i,u);await A(o,s,e`UPDATE ${e.identifier(r)} SET ${e.identifier("__value__")} = ${S}, ${e.identifier("__count__")} = ${g} WHERE ${e.identifier("__key__")} = ${d}`)}else await A(o,s,e`UPDATE ${e.identifier(r)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${d}`)}if(p){const d=Y(i.by??[],p),h=Me(p[$]);if(h===void 0)await A(o,s,R({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(m,b)=>({__count__:e`${b("__count__")} + 1`}),table:r,values:[d,null,1]}));else{const m=f==="min"?"MIN":"MAX";await A(o,s,R({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(b,g)=>({__count__:e`${g("__count__")} + 1`,__value__:e`${e.raw(m)}(COALESCE(${g("__value__")}, ${b("__value__")}), ${b("__value__")})`}),table:r,values:[d,h,1]}))}}}},Ee=async t=>{const i=c.tables[t]?.aggregateIndexes;if(!(!i||i.length===0))for(const n of i)await pe(t,n)},ae=async(t,i,n)=>{const a=c.tables[t]?.aggregateIndexes;if(!(!a||a.length===0))for(const r of a){const f=`${t}::${r.name}`;(ne.get(f)??await Be(t,r.name))&&await ft(t,r,i,n)}},oe=new Map,Fe=async(t,i)=>{const n=Q(t,i);return(await I(o,s,s.tableExists(n))).length>0},Le=async(t,i)=>{const n=`${t}::rank::${i.name}`,a=oe.get(n);if(a!==void 0)return a;if(!await Fe(t,i.name))return oe.set(n,!1),!1;const r=c.tables[t];if(!r)return oe.set(n,!1),!1;const f=Q(t,i.name);await A(o,s,e`DELETE FROM ${e.identifier(f)}`);const $=i.sortBy.map((h,m)=>z(m)),u=X(["__id__","__partition__",...$]),p=[];await ot(o,s,r,t,h=>{if(i.where&&!at(h,i.where))return;const m=Te(i.partitionBy??[],h),b=i.sortBy.map(g=>H(h[g.field]??null));p.push([h._id,m,...b])});const d=p.map(h=>e`INSERT INTO ${e.identifier(f)} (${u}) VALUES (${te(h)})`);return await rt(o,s,d),oe.set(n,!0),!0},me=async t=>{const i=c.tables[t]?.rankIndexes;if(!(!i||i.length===0))for(const n of i)await Le(t,n)},J=async(t,i,n,a)=>{const r=c.tables[t],f=r?.rankIndexes;if(!f||f.length===0)return;const $=r?.softDeleteMode?.field,u=$===void 0||a===void 0?void 0:a[$],p=u!=null;for(const d of f){if(n!==void 0&&a!==void 0&&oi(d,n,a))continue;const h=`${t}::rank::${d.name}`;if(!(oe.get(h)??await Fe(t,d.name)))continue;const m=Q(t,d.name);if(n&&await A(o,s,e`DELETE FROM ${e.identifier(m)} WHERE ${e.identifier("__id__")} = ${i}`),a&&!p){if(d.where&&!at(a,d.where))continue;const b=d.sortBy.map((W,O)=>z(O)),g=X(["__id__","__partition__",...b]),S=Te(d.partitionBy??[],a),k=d.sortBy.map(W=>H(a[W.field]??null));await A(o,s,e`INSERT INTO ${e.identifier(m)} (${g}) VALUES (${te([i,S,...k])})`)}}},re=bt({dialect:s,exec:o,schema:c}),Ue=new Set;for(const[t,i]of Object.entries(c.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>st)throw he-=1,new we(`trigger recursion exceeded ${String(st)} levels on "${n.table}" — check for a self-triggering write`,"trigger");try{await jt({ctx:je,event:n,op:i,schema:c,tableName:n.table,timing:t})}finally{he-=1}},_t=async(t,i)=>{try{await A(o,s,i)}catch(n){throw T(n)?new we(`unique constraint violation on "${t}"`,"unique"):n}},ye=async(t,i)=>(await I(o,s,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} = ${i}`))[0],be=async(t,i,n,a)=>{if(a===void 0)return;const r=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 ${r}`:e`DELETE FROM ${e.identifier(t)} WHERE ${r}`,$=()=>{throw new we(`optimistic concurrency conflict on "${t}" — the row changed during this mutation; refetch and retry`,"occ")};try{if(s.supportsReturning)(await I(o,s,e`${f} RETURNING ${e.identifier("id")}`)).length===0&&$();else{const u=await A(o,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}},wt=(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))]}},$t=async(t,i,n,a)=>{const r=Pt(i,n.op,n.field,a.by,a.where);if(!r||!await pe(t,r.index))return;const f=G(t,r.index.name),$=Object.keys(r.partial);if($.length===(r.index.by??[]).length&&$.length>0){const u=Y(r.index.by??[],r.partial),p=await I(o,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 d=p[0];return[{key:{...r.partial},value:Oe(n.op,{count:d.count,value:ee(d.value)})}]}return $.length>0?void 0:(await I(o,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:Oe(n.op,{count:p.count,value:ee(p.value)})}})},Pe=t=>{const i=c.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`)},ht=(t,i)=>{if(i?.relationMask!==void 0&&i.with!==void 0&&Object.keys(i.with).length>0)throw new N("MASK_UNSUPPORTED",`masking cannot follow a nested \`with\` across the cross-shard relation hop to "${t}" — the nested rows are hydrated on the serving shard, where the mask policy does not exist. Read the nested relation at its own (masked) call site instead.`);const n={};if(i?.relationBaseWhere)for(const a of Object.keys(c.tables)){const r=i.relationBaseWhere(a);r!==void 0&&(n[a]=r)}return{orderBy:i?.orderBy,relationPolicies:n,where:M(i?.baseWhere,i?.where),with:i?.with}},Ke=(t,i)=>Pe(t)?_?_(t,ht(t,i)):He(t):q.findMany(t,i),ge=(t,i,n)=>et(t,{fetcher:Ke,maxRelationKeys:E,relationBaseWhere:n,schema:c,tableName:i}),pt=Xt(async(t,i)=>{const n=await I(o,s,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} IN (${te(i)})`),a=new Map;for(const r of n){const{id:f}=r;typeof f=="string"&&a.set(f,r)}return a}),q={async aggregate(t,i){const n=c.tables[t];if(!n)throw new N("INTERNAL",`unknown table: ${t}`);if(await U(),ue(i.op),i.op==="count")return q.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),r=M(M(i.baseWhere,i.where),a),f=await ge(r,t,i.relationBaseWhere),$=f!==r;if(n.aggregateIndexes&&!i.baseWhere&&!$&&!a){const m=Ut(n.aggregateIndexes,i.op,i.field,i.where);if(m&&await pe(t,m.index)){const b=Y(m.index.by??[],m.key),g=G(t,m.index.name),S=(await I(o,s,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(g)} WHERE ${e.identifier("__key__")} = ${b}`))[0];return Oe(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)),d=e`SELECT ${p}(${x(i.field)}) AS value FROM ${e.identifier(t)}`,h=(await I(o,s,u?e`${d} WHERE ${u}`:d))[0]?.value;return h==null?null:Number(h)},async count(t,i){const n=c.tables[t];if(!n)throw new N("INTERNAL",`unknown table: ${t}`);await U();const a=Bt(i);if(a.restrictsCounts)throw new Ze(t);const r=fe(n.softDeleteMode,void 0),f=M(M(a.baseWhere,a.where),r),$=await ge(f,t,a.relationBaseWhere),u=$!==f;if(n.aggregateIndexes&&!a.baseWhere&&!u&&!r){const m=Ft(n.aggregateIndexes,a.where);if(m&&await pe(t,m.index)){const b=Y(m.index.by??[],m.key),g=G(t,m.index.name),S=await I(o,s,e`SELECT ${e.identifier("__value__")} AS value FROM ${e.identifier(g)} WHERE ${e.identifier("__key__")} = ${b}`);return Number(S[0]?.value??0)}}const p=_e($,y),d=e`SELECT COUNT(*) AS count FROM ${e.identifier(t)}`,h=await I(o,s,p?e`${d} WHERE ${p}`:d);return Number(h[0]?.count??0)},async delete(t,i,n){const a=await ie(t,i);if(!a)return;const r=c.tables[a];if(!r)return;const f=await ye(a,t),$=Z(r,f),u=n?.hard===!0,p=!u&&r.softDeleteMode?r.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 qt({deletedId:t,deletedReference:d=>$?.[d],findHolders:async(d,h,m)=>{if(c.tables[d]?.shardMode?.kind==="shardBy")throw new N("INTERNAL",`cross-backend cascade from global '${a}' into shardBy '${d}' is not supported — would require Query Coordinator fan-out across shards`);return(await q.findMany(d,{includeDeleted:u,where:{[h]:m}})).page},onCascade:(d,h)=>q.delete(h,void 0,n),onRestrict:d=>{throw new we(d,"restrict")},onSetNull:(d,h,m)=>q.patch(h,{[m]:null}),schema:c,tableName:a}),await Ee(a),await me(a),p&&$){const d={...$,[p]:L()},h=e.join(Object.keys(r.shape).map(m=>e`${e.identifier(m)} = ${H(d[m]??null)}`),e`, `);await be(a,"UPDATE",h,f),await ae(a,$,d),await J(a,t,$,void 0),await re(a,t,d,$),await F(a,t,"update",d),j(a,"after","delete")&&await P("after","delete",{id:t,op:"delete",previous:$,table:a});return}await be(a,"DELETE",void 0,f),Ie.delete(t),await ae(a,$??void 0,void 0),await J(a,t,$??void 0,void 0),await re(a,t,void 0),await F(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 q.findMany(t,{...i,limit:1})).page[0]??null},async findFirstOrThrow(t,i={}){const n=await q.findFirst(t,i);if(n===null)throw new Wt(`findFirstOrThrow: no "${t}" document matched`);return n},async findMany(t,i={}){const n=c.tables[t];if(!n)throw new N("INTERNAL",`unknown table: ${t}`);await U();const a=Mt(i.orderBy),r=i.cursor?xt(a,Qe(i.cursor)):void 0,f=Ke,$=async(O,se,Ne,ce)=>{if(Pe(O))return w?Ht(w,O,se,Ne,ce):He(O);const V=c.tables[O];if(!V)throw new N("INTERNAL",`unknown table: ${O}`);const C=fe(V.softDeleteMode,void 0),de={[se]:{in:Ne}},Et=M(M(de,ce),C),mt=await ge(Et,O,void 0),Ve=_e(mt,y),Ye=x(se);let le=e`SELECT ${Ye} AS __fk__, COUNT(*) AS count FROM ${e.identifier(O)}`;Ve&&(le=e`${le} WHERE ${Ve}`),le=e`${le} GROUP BY ${Ye}`;const yt=await I(o,s,le),Ge=new Map;for(const ze of yt)Ge.set(ze.__fk__,Number(ze.count??0));return Ge};let u=M(i.baseWhere,i.where);u=M(u,fe(n.softDeleteMode,i.includeDeleted)),u=await et(u,{fetcher:f,maxRelationKeys:E,relationBaseWhere:i.relationBaseWhere,schema:c,tableName:t}),r&&(u=u?{AND:[u,r]}:r);const p=_e(u,y),d=Zt(a);let h=e`SELECT * FROM ${e.identifier(t)}`;p&&(h=e`${h} WHERE ${p}`),h=e`${h} ORDER BY ${d}`;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 b=await I(o,s,h),g=zt(n,b);if(m===void 0)return i.with&&await tt({fetcher:f,groupedCounter:$,parents:g,...it(i),schema:c,tableName:t,with:i.with}),{continueCursor:null,isDone:!0,page:nt(g,i.select,i.with)};const S=g.length>m,k=S?g.slice(0,m):g,W=k.at(-1);return i.with&&await tt({fetcher:f,groupedCounter:$,parents:k,...it(i),schema:c,tableName:t,with:i.with}),{continueCursor:S&&W?Dt(W,a):null,isDone:!S,page:nt(k,i.select,i.with)}},async get(t,i){const n=await ie(t,i);if(!n)return null;const a=c.tables[n];return a?Z(a,await pt.load(n,t)):null},async groupBy(t,i){const n=c.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 r=fe(n.softDeleteMode,void 0),f=M(M(i.baseWhere,i.where),r),$=await ge(f,t,i.relationBaseWhere),u=$!==f;if(n.aggregateIndexes&&!i.baseWhere&&!u&&!r){const g=await $t(t,n.aggregateIndexes,a,i);if(g!==void 0)return g}const p=_e($,y),d=i.by.map(g=>e`${x(g)} AS ${e.identifier(g)}`);if(a.op==="count")d.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`);d.push(e`${e.raw(ue(a.op))}(${x(a.field)}) AS value`)}const h=e.join(i.by.map(g=>x(g)),e`, `);let m=e`SELECT ${e.join(d,e`, `)} FROM ${e.identifier(t)}`;p&&(m=e`${m} WHERE ${p}`),m=e`${m} GROUP BY ${h}`;const b=await I(o,s,m);return ai(i.by,b)},async insert(t,i,n){const a=c.tables[t];if(!a)throw new N("INTERNAL",`unknown table: ${t}`);await U();const r=ei(a,i,K);ke(a,r);let f,$=!0;n?.clientId!==void 0?(Ct(n.clientId),f=n.clientId):n?.allowExplicitId&&typeof r._id=="string"?f=r._id:(f=D(),$=!1);const u=n?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:L(),p={...r,_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:d,values:h}=wt(a,f,u,r);return await _t(t,e`INSERT INTO ${e.identifier(t)} (${X(d)}) VALUES (${te(h)})`),$&&Ie.set(f,t),await ae(t,void 0,p),await J(t,f,void 0,p),await re(t,f,p),await F(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 Ot(c,t,i)},async patch(t,i,n){const a=await ie(t,n);if(!a)throw new N("INTERNAL",`document not found: ${t}`);const r=c.tables[a];if(!r)throw new N("INTERNAL",`document not found: ${t}`);const f=await ye(a,t),$=Z(r,f);if(!$)throw new N("INTERNAL",`document not found: ${t}`);const u={...$,...i,_id:t};ct(r,i,u,K),ke(r,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(r.shape),d=e.join(p.map(h=>e`${e.identifier(h)} = ${H(u[h]??null)}`),e`, `);await be(a,"UPDATE",d,f),await ae(a,$,u),await J(a,t,$,u),await re(a,t,u,$),await F(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=c.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 ye(n,t),$=f?.[r]!==null&&f?.[r]!==void 0;if(await q.patch(t,{[r]:null},i),$){const u=Z(a,f);u!==null&&await J(n,t,void 0,{...u,[r]:null})}},query(t){const i=c.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=u=>a.every(p=>p(u)),f=async(u,p)=>{await U();const d=a.length>0,h=await St(o,s,i,t,u,It(d?void 0:p));if(!d)return p===void 0&&At(h),h;const m=h.filter(b=>r(b));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(d){return a.push(d),p},async first(){if(!u)throw new N("INTERNAL",n);return(await f(u,1))[0]??null},order(){return p},async paginate(d){if(!u)throw new N("INTERNAL",n);const h=vt(d);return Rt(await f(u,Lt(h)),h)},async take(d){if(!u)throw new N("INTERNAL",n);return f(u,d)},async unique(){if(!u)throw new N("INTERNAL",n);const d=await f(u,2);if(d.length>1)throw new Vt(`unique() on table "${t}" matched ${String(d.length)} documents; expected at most one`);return d[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(d,h){const m=(i.searchIndexes??[]).find(g=>g.name===d);if(!m)throw new N("INTERNAL",`unknown search index "${d}" on table "${t}"`);const b={definition:m,field:m.field,filters:[],hasQuery:!1,indexName:d,query:""};if(h(Nt(b,t,Tt(m.language))),!b.hasQuery)throw new N("INTERNAL",`search index "${d}" on table "${t}" requires a .search(field, query) call`);return $(b)}};return p};return $(void 0)},async rank(t,i,n){const a=c.tables[t];if(!a)throw new N("INTERNAL",`unknown table: ${t}`);const r=a.rankIndexes?.find(W=>W.name===i);if(!r)throw new N("INTERNAL",`unknown rankIndex "${i}" on table "${t}"`);if(n.restrictsCounts)throw new Ze(t);if(await U(),!await Le(t,r))return null;const f=typeof n.row=="string"?n.row:n.row._id;if(!f)return null;const $=Q(t,r.name),u=r.sortBy.map((W,O)=>z(O)),p=X(["__partition__",...u]),d=(await I(o,s,e`SELECT ${p} FROM ${e.identifier($)} WHERE ${e.identifier("__id__")} = ${f}`))[0];if(!d)return null;const h=d.__partition__,m=M(n.baseWhere,n.where);Je(m,c,t,"rank");const b=Xe(r,m);if(b&&Te(r.partitionBy??[],b)!==h)return null;const g=ri(s.name,r,u,d,f),S=await I(o,s,e`SELECT COUNT(*) AS c FROM ${e.identifier($)} WHERE ${e.identifier("__partition__")} = ${h}${g?e` AND (${g})`:e``}`),k=await I(o,s,e`SELECT COUNT(*) AS c FROM ${e.identifier($)} WHERE ${e.identifier("__partition__")} = ${h}`);return{position:Number(S[0]?.c??0)+1,total:Number(k[0]?.c??0)}},async rankPage(t,i,n={}){Je(M(n.baseWhere,n.where),c,t,"rankPage");const a=c.tables[t];if(!a)throw new N("INTERNAL",`unknown table: ${t}`);const r=a.rankIndexes?.find(C=>C.name===i);if(!r)throw new N("INTERNAL",`unknown rankIndex "${i}" on table "${t}"`);if(await U(),!await Le(t,r))return{continueCursor:null,isDone:!0,page:[]};const f=Q(t,r.name),$=r.sortBy.map((C,de)=>z(de)),u=Math.max(1,Math.min(1e3,Math.floor(n.take??100))),p=M(n.baseWhere,n.where),d=Xe(r,p),h=ci(r,$),m=e.join(h.map(C=>e`${e.identifier(C.column)} ${e.raw(C.direction==="desc"?"DESC":"ASC")}`),e`, `),b=[];if(d&&b.push(e`${e.identifier("__partition__")} = ${Te(r.partitionBy??[],d)}`),n.cursor){const C=si(s.name,h,Qe(n.cursor));C!==void 0&&b.push(C)}const g=X([$e,"__partition__",...$]);let S=e`SELECT ${g} FROM ${e.identifier(f)}`;b.length>0&&(S=e`${S} WHERE ${e.join(b,e` AND `)}`),S=e`${S} ORDER BY ${m} LIMIT ${e.raw(String(u+1))}`;const k=await I(o,s,S),W=k.length>u,O=W?k.slice(0,u):k,se=O.map(C=>C[$e]),Ne=await di(o,s,a,t,se);let ce=null;const V=O.at(-1);if(W&&V!==void 0){const C=[V.__partition__,...$.map(de=>V[de]),V[$e]];ce=li(C)}return{continueCursor:ce,isDone:!W,page:Ne}},async replace(t,i,n,a){const r=await ie(t,n);if(!r)throw new N("INTERNAL",`document not found: ${t}`);const f=c.tables[r];if(!f)throw new N("INTERNAL",`document not found: ${t}`);const $=await ye(r,t);if($===void 0)throw new N("INTERNAL",`document not found: ${t}`);const u=kt(c,r,"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(),d={...i,_creationTime:p,_id:t};ct(f,i,d,K),ke(f,d),j(r,"before","update")&&await P("before","update",{doc:{...d},id:t,op:"update",previous:u,table:r}),await Ee(r),await me(r);const h=Object.keys(f.shape),m=e.join([e`${e.identifier("_creationTime")} = ${p}`,...h.map(b=>e`${e.identifier(b)} = ${H(d[b]??null)}`)],e`, `);await be(r,"UPDATE",m,$),await ae(r,u,d),await J(r,t,u,d),await re(r,t,d,u),await F(r,t,"update",d),j(r,"after","update")&&await P("after","update",{doc:d,id:t,op:"update",previous:u,table:r})}};return je={db:q,scheduler:Se},q};export{Ci as backfillSqlSearchIndexes,Li as createSqlCtxDb,xi as decodeGlobalRow,Ii as readSqlCdcChanges,$i as runSqlAggregateMigrations,mi as runSqlCdcMigration,wi as runSqlGlobalTableMigrations,Ei as runSqlRankMigrations,gt as runSqlSearchMigrations,Ai as trimSqlCdcChanges};
|
|
@@ -1 +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};
|
|
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-Bw9dhHy2.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-BwzH1RLd.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
|
+
const i=e=>{if(e.kind!=="optional")return e.kind;const r=e._meta?.inner;return r?i(r):e.kind},a=e=>typeof e=="boolean"?e?1:0:e===null||typeof e=="string"||typeof e=="number"?e:typeof e=="bigint"?e.toString():e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):JSON.stringify(e),t=e=>{try{return JSON.parse(e)}catch{return e}},s=e=>{if(typeof e!="string")return e;try{return BigInt(e)}catch{return e}},f=e=>i(e),o=(e,r)=>{if(e===null)return e;switch(r){case"any":case"from":case"union":return typeof e=="string"&&(e.startsWith("{")||e.startsWith("["))?t(e):e;case"array":case"object":case"record":return typeof e=="string"?t(e):e;case"bigint":return s(e);case"boolean":return e===0||e===1?e===1:e;case"bytes":return e instanceof ArrayBuffer?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer:e;default:return e}};export{s as decodeBigint,f as effectiveColumnKind,o as sqliteDecode,a as sqliteEncode,t as tryJsonParse};
|
|
@@ -1 +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-
|
|
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-DrEQib7C.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.
|
|
3
|
+
"version": "1.0.0-alpha.71",
|
|
4
4
|
"description": "Internal dialect-parameterized SQL store core for Lunora .global() backends (D1, PlanetScale)",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
53
|
"@lunora/errors": "1.0.0-alpha.16",
|
|
54
|
-
"@lunora/shard-engine": "1.0.0-alpha.
|
|
54
|
+
"@lunora/shard-engine": "1.0.0-alpha.17",
|
|
55
55
|
"drizzle-orm": "^0.45.2"
|
|
56
56
|
},
|
|
57
57
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const a=e=>typeof e=="boolean"?e?1:0:e===null||typeof e=="string"||typeof e=="number"?e:typeof e=="bigint"?e.toString():e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):JSON.stringify(e),t=e=>{try{return JSON.parse(e)}catch{return e}},i=e=>{if(typeof e!="string")return e;try{return BigInt(e)}catch{return e}},s=e=>{if(e.kind!=="optional")return e.kind;const r=e._meta?.inner;return r?s(r):e.kind},f=(e,r)=>{if(e===null)return e;switch(r){case"any":case"from":case"union":return typeof e=="string"&&(e.startsWith("{")||e.startsWith("["))?t(e):e;case"array":case"object":case"record":return typeof e=="string"?t(e):e;case"bigint":return i(e);case"boolean":return e===0||e===1?e===1:e;case"bytes":return e instanceof ArrayBuffer?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer:e;default:return e}};export{i as decodeBigint,s as effectiveColumnKind,f as sqliteDecode,a as sqliteEncode,t as tryJsonParse};
|