@lunora/sql-store 1.0.0-alpha.103 → 1.0.0-alpha.104
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{SEARCH_STATE_TABLE-B5a5xBwB.mjs → SEARCH_STATE_TABLE-DxsFPib5.mjs} +1 -1
- package/dist/packem_shared/backfillSqlSearchIndexes-DKyn3LSL.mjs +1 -0
- package/dist/packem_shared/createSqlCtxDb-Dk81vqqt.mjs +7 -0
- package/dist/packem_shared/{ctx-db-search-BiMTuJzw.mjs → ctx-db-search-rNutkVme.mjs} +1 -1
- package/dist/packem_shared/decodeGlobalRow-DeKnMoxP.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/backfillSqlSearchIndexes-DjIUfk0C.mjs +0 -1
- package/dist/packem_shared/createSqlCtxDb-B9-Pge3V.mjs +0 -7
- package/dist/packem_shared/decodeGlobalRow-C8O2hy0d.mjs +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createSqlCtxDb as a,readSqlCdcChangedTables as o,readSqlCdcChanges as t,readSqlCdcFloor as l,runSqlAggregateMigrations as n,runSqlCdcMigration as s,runSqlGlobalTableMigrations as i,runSqlRankMigrations as d,sweepSqlCdcRetention as S}from"./packem_shared/createSqlCtxDb-
|
|
1
|
+
import{createSqlCtxDb as a,readSqlCdcChangedTables as o,readSqlCdcChanges as t,readSqlCdcFloor as l,runSqlAggregateMigrations as n,runSqlCdcMigration as s,runSqlGlobalTableMigrations as i,runSqlRankMigrations as d,sweepSqlCdcRetention as S}from"./packem_shared/createSqlCtxDb-Dk81vqqt.mjs";import{d as q,r as g}from"./packem_shared/ctx-db-search-rNutkVme.mjs";import{SEARCH_STATE_TABLE as f,migrateSearchState as m}from"./packem_shared/SEARCH_STATE_TABLE-DxsFPib5.mjs";import{c as b,e as p,a as u,s as h,t as M}from"./packem_shared/value-codec-CwTLrqfU.mjs";import{decodeGlobalRow as A}from"./packem_shared/decodeGlobalRow-DeKnMoxP.mjs";export{f as SEARCH_STATE_TABLE,q as backfillSqlSearchIndexes,a as createSqlCtxDb,b as decodeBigint,A as decodeGlobalRow,p as effectiveColumnKind,m as migrateSearchState,o as readSqlCdcChangedTables,t as readSqlCdcChanges,l as readSqlCdcFloor,n as runSqlAggregateMigrations,s as runSqlCdcMigration,i as runSqlGlobalTableMigrations,d as runSqlRankMigrations,g as runSqlSearchMigrations,u as sqliteDecode,h as sqliteEncode,S as sweepSqlCdcRetention,M as tryJsonParse};
|
package/dist/packem_shared/{SEARCH_STATE_TABLE-B5a5xBwB.mjs → SEARCH_STATE_TABLE-DxsFPib5.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as i}from"drizzle-orm";import{queryRun as s,queryAll as E}from"./decodeGlobalRow-
|
|
1
|
+
import{sql as i}from"drizzle-orm";import{queryRun as s,queryAll as E}from"./decodeGlobalRow-DeKnMoxP.mjs";const f="__lunora_search_state",l=async(r,e)=>{const{integer:t,key:o}=e.companionTypes,n=async()=>{try{await s(r,e,i`ALTER TABLE ${i.identifier(f)} ADD COLUMN ${i.identifier("profile")} ${i.raw(o)}`)}catch{}};await s(r,e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(f)} (${i.identifier("companion")} ${i.raw(o)} PRIMARY KEY, ${i.identifier("cursor")} ${i.raw(o)}, ${i.identifier("done")} ${i.raw(t)} NOT NULL DEFAULT 0, ${i.identifier("profile")} ${i.raw(o)})`),await n()},p=r=>r===1||r===!0||r==="1",S=async(r,e,t)=>{const n=(await E(r,e,i`SELECT ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")} FROM ${i.identifier(f)} WHERE ${i.identifier("companion")} = ${t}`))[0];if(!n)return{cursor:void 0,done:!1,profile:void 0};const{cursor:a,profile:$}=n;return{cursor:typeof a=="string"?a:void 0,done:p(n.done),profile:typeof $=="string"?$:void 0}},A=async(r,e,t,o,n,a)=>{const $=o??null,d=i`UPDATE ${i.identifier(f)} SET ${i.identifier("cursor")} = ${$}, ${i.identifier("done")} = ${n?1:0}, ${i.identifier("profile")} = ${a} WHERE ${i.identifier("companion")} = ${t}`;if((await E(r,e,i`SELECT ${i.identifier("companion")} FROM ${i.identifier(f)} WHERE ${i.identifier("companion")} = ${t}`)).length>0){await s(r,e,d);return}try{await s(r,e,i`INSERT INTO ${i.identifier(f)} (${i.identifier("companion")}, ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")}) VALUES (${t}, ${$}, ${n?1:0}, ${a})`)}catch(c){if(!e.isUniqueViolation(c))throw c;await s(r,e,d)}};export{f as SEARCH_STATE_TABLE,l as migrateSearchState,S as readSearchBackfillState,A as writeSearchBackfillState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as S,c as s,a as i,r as l}from"./ctx-db-search-rNutkVme.mjs";import"./SEARCH_STATE_TABLE-DxsFPib5.mjs";import"./decodeGlobalRow-DeKnMoxP.mjs";export{S as backfillSqlSearchIndexes,s as createSearchSync,i as runSqlSearch,l as runSqlSearchMigrations};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{LunoraError as v}from"@lunora/errors";import{c as Ct,r as At,A as Lt,q as Nt,C as kt,R as Mt,a as qt,T as Dt,x as Ot,b as Ft}from"./ctx-db-search-rNutkVme.mjs";import{d as ai}from"./ctx-db-search-rNutkVme.mjs";import{literalInList as xt,throwingScheduler as Bt,CDC_LOG_TABLE as G,cursorBelowRetainedFloor as Wt,cdcTrimmedError as Ut,aggregateTableName as Q,rankTableName as ne,assertNoExplicitUndefined as Ze,hasTrigger as Pt,runRowValidators as qe,assertFlatPredicate as et,mergeWhere as F,sortColumnName as J,resolveRankPartition as tt,encodePartitionKey as Ae,resolveRankSeekTuple as Kt,RANK_TIEBREAK as Ee,CountRlsUnsupportedError as nt,normalizeIdStructurally as jt,assertValidClientId as Ht,aggregateSqlFunction as we,softDeleteScope as _e,compileWhereSql as $e,normalizeOrderKeys as Gt,buildSeekWhere as Vt,decodeCursor as Yt,resolveRelationPredicates as it,resolveWith as ot,relationHooks as rt,applySelect as st,encodeCursor as Xt,NotFoundError as zt,applyOnDelete as Qt,ConflictError as he,normalizeCountArgument as Jt,selectIndexForCount as Zt,encodeAggregateKey as z,selectIndexForAggregate as en,readAggregateValue as De,runTriggers as tn,matchesRankStaticWhere as at,CURSOR_PREFIX as nn,selectIndexForGroupBy as on,tiebreakDirectionFor as rn,fanOutScalarCounts as sn,matchesStaticWhere as Oe,foldAggregateTally as an,renderSql as cn,coerceAggregateNumber as Fe,CDC_LOG_TABLE_SEQ_INDEX as dn,NotUniqueError as ln}from"@lunora/shard-engine";import{sql as e}from"drizzle-orm";import{d as _t,e as Le,n as un,b as fn}from"./value-codec-CwTLrqfU.mjs";import{migrateSearchState as wn}from"./SEARCH_STATE_TABLE-DxsFPib5.mjs";import{queryAll as I,queryRun as A,createIndexIfNotExists as ye,decodeRow as ie,serializeColumnValue as H,columnRefSql as M,decodeRows as _n,forEachRowPaged as ct,queryBatch as dt}from"./decodeGlobalRow-DeKnMoxP.mjs";import{decodeGlobalRow as di}from"./decodeGlobalRow-DeKnMoxP.mjs";const $n=(r,l)=>{if(r.size<l)return;const d=r.keys().next().value;d!==void 0&&r.delete(d)},lt=50,hn=(r,l={})=>{const d=l.maxBatch??lt,i=Number.isInteger(d)&&d>0?d:lt,$=new Map;let u=!1;const a=async(R,g)=>{const b=[...g.keys()];for(let L=0;L<b.length;L+=i){const q=b.slice(L,L+i);try{const B=await r(R,q);for(const V of q){const Y=B.get(V);for(const X of g.get(V)??[])X.resolve(Y)}}catch(B){for(const V of q)for(const Y of g.get(V)??[])Y.reject(B)}}},m=()=>{u=!1;const R=[...$.entries()];$.clear();for(const[g,b]of R)a(g,b).catch(()=>{})};return{async load(R,g){return new Promise((b,L)=>{let q=$.get(R);q||(q=new Map,$.set(R,q));const B=q.get(g);B?B.push({reject:L,resolve:b}):q.set(g,[{reject:L,resolve:b}]),u||(u=!0,queueMicrotask(m))})}}},En=new Set(["_id","id"]),We=(r,l,d)=>r==="postgres"?e`${l} IS NOT DISTINCT FROM ${d}`:r==="mysql"?e`${l} <=> ${d}`:e`${l} IS ${d}`,yn=(r,l)=>r.name!=="postgres"||l.nullable!==!0?"":l.direction==="desc"?" NULLS LAST":" NULLS FIRST",pn=(r,l)=>{const d=r.map(i=>e`${M(i.field)} ${e.raw(`${i.direction==="desc"?"DESC":"ASC"}${yn(l,i)}`)}`);if(!r.some(i=>En.has(i.field))){const i=rn(r);d.push(e`${M("id")} ${e.raw(i==="desc"?"DESC":"ASC")}`)}return e.join(d,e`, `)},ut=50,Ue=r=>{const l=[];for(const[d,i]of Object.entries(r.shape)){const $=i._meta?.column;$&&l.push([d,$])}return l},Rn=(r,l,d)=>{const i={...l};for(const[$,u]of Ue(r)){if(u.serverDefault){i[$]=u.serverDefault({auth:d});continue}i[$]===void 0&&(u.defaultFn?i[$]=u.defaultFn():"defaultValue"in u&&(i[$]=u.defaultValue))}return i},ft=(r,l,d,i)=>{for(const[$,u]of Ue(r)){if(u.serverDefault){$ in l&&(d[$]=u.serverDefault({auth:i}));continue}u.onUpdateFn&&!($ in l)&&(d[$]=u.onUpdateFn())}},mn=128,Tn=()=>{const r=new Map;return{delete:l=>{r.delete(l)},get:l=>{const d=r.get(l);if(d!==void 0)return r.delete(l),r.set(l,d),d},set:(l,d)=>{r.has(l)?r.delete(l):$n(r,mn),r.set(l,d)}}},Sn=async(r,l,d,i,$)=>{const u=$.get(i);if(u!==void 0)return u;const a=Object.entries(d.tables).filter(([,R])=>R.shardMode===void 0||R.shardMode.kind==="global").map(([R])=>R),m=await Promise.all(a.map(async R=>({found:(await I(r,l,e`SELECT 1 FROM ${e.identifier(R)} WHERE ${e.identifier("id")} = ${i} LIMIT 1`)).length>0,tableName:R})));for(const R of m)if(R.found)return $.set(i,R.tableName),R.tableName},oe=r=>r==null?null:Number(r),gn=(r,l)=>l.map(d=>{const i={};for(const $ of r)i[$]=d[$]??null;return{key:i,value:oe(d.value)}}),vn=(r,l,d)=>[...r.partitionBy??[],...r.sortBy.map($=>$.field),...r.where?Object.keys(r.where):[]].every($=>l[$]===d[$]),$t=r=>r.length===1?r[0]:e`(${e.join(r,e` AND `)})`,te=r=>e.join(r.map(l=>e`${e.identifier(l)}`),e`, `),re=r=>e.join(r.map(l=>e`${l}`),e`, `),bn=(r,l,d,i,$)=>{const u=[];for(let a=0;a<d.length+1;a+=1){const m=d.slice(0,a).map(b=>We(r,e`${e.identifier(b)}`,i[b])),R=d[a],g=l.sortBy[a];a<d.length&&R!==void 0&&g!==void 0?m.push(e`${e.identifier(R)} ${e.raw(g.direction==="desc"?">":"<")} ${i[R]}`):m.push(e`${e.identifier(Ee)} < ${$}`),u.push($t(m))}return u.length>0?e.join(u,e` OR `):void 0},In=(r,l,d)=>{if(d.length!==l.length)return;const i=[];for(const[$,u]of l.entries()){const a=[];for(let m=0;m<$;m+=1){const R=l[m];R!==void 0&&a.push(We(r,e`${e.identifier(R.column)}`,d[m]))}a.push(e`${e.identifier(u.column)} ${e.raw(u.direction==="desc"?"<":">")} ${d[$]}`),i.push($t(a))}return e`(${e.join(i,e` OR `)})`},Cn=(r,l)=>{if(r.sortBy.length===0)throw new v("INTERNAL",`rankIndex "${r.name}" requires at least one "sortBy" column for stable pagination`);const d=[{column:"__partition__",direction:"asc"}];for(const[i,$]of r.sortBy.entries())d.push({column:l[i]??J(i),direction:$.direction});return d.push({column:Ee,direction:"asc"}),d},An=async(r,l,d,i,$)=>{const a=[];for(let b=0;b<$.length;b+=50)a.push($.slice(b,b+50));const m=await Promise.all(a.map(async b=>I(r,l,e`SELECT * FROM ${e.identifier(i)} WHERE ${e.identifier("id")} IN (${re(b)})`))),R=new Map;for(const b of m)for(const L of b)R.set(L.id,L);const g=[];for(const b of $){const L=ie(d,R.get(b));L&&g.push(L)}return g},Ln=r=>{const l=JSON.stringify(r),d=new TextEncoder().encode(l);let i="";for(const $ of d)i+=String.fromCodePoint($);return nn+btoa(i)},Nn=(r,l)=>l.columnType(Le(r)),kn=(r,l,d)=>{const i=[];for(const[a,m]of Object.entries(l.shape)){if(!m._meta?.column)continue;const R=m._meta.column.notNull&&m.kind!=="optional"?" NOT NULL":"";i.push(e`${e.identifier(a)} ${e.raw(`${Nn(m,d)}${R}`)}`)}const $=d.frameworkColumns().map(a=>e`${e.identifier(a.name)} ${e.raw(a.type)}`),u=$.length+i.length;if(d.maxTableColumns!==void 0&&u>d.maxTableColumns)throw new v("VALIDATION_ERROR",`@lunora/sql-store: global table "${r}" needs ${String(u)} columns, over this engine's ${String(d.maxTableColumns)}-column limit — split the table, or move the extra fields into one object field`);return e.join([...$,...i],e`, `)},Mn=r=>{if(r.indexKeyPrefix?.("string")===void 0)return e`${M("_creationTime")}, ${M("id")}`},qn=async(r,l,d)=>{if(l.name!=="sqlite")return;const $=(await I(r,l,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${d.name} AND tbl_name = ${d.table}`))[0]?.sql;if(typeof $!="string")return;const u=R=>{const g=R.indexOf("(");return g===-1?void 0:R.slice(g,R.lastIndexOf(")")+1)},a=d.unique?e`UNIQUE `:e``,m=u(cn(l.name,e`CREATE ${a}INDEX ${e.identifier(d.name)} ON ${e.identifier(d.table)} (${d.columns})`).sql);if(!(m===void 0||m===u($))){if(d.unique&&(await I(r,l,e`SELECT ${d.columns} FROM ${e.identifier(d.table)} GROUP BY ${d.columns} HAVING COUNT(*) > 1 LIMIT 1`)).length>0)throw new v("INTERNAL",`unique index "${d.name}" on "${d.table}" cannot be re-created with its new column list: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`);await A(r,l,e`DROP INDEX IF EXISTS ${e.identifier(d.name)}`)}},Dn=async(r,l,d,i)=>{const $=a=>{const m=M(a),R=d.shape[a],g=R&&i.indexKeyPrefix?i.indexKeyPrefix(Le(R)):void 0;return g===void 0?m:e`${m}(${e.raw(String(g))})`},u=Mn(i);for(const a of d.indexes){const m=e.join(a.fields.map(b=>$(b)),e`, `),R=a.unique??!1,g={columns:R||u===void 0?m:e`${m}, ${u}`,name:`${l}_${a.name}`,table:l,unique:R};await qn(r,i,g),await ye(r,i,g)}u!==void 0&&await ye(r,i,{columns:u,name:`${l}__by_creation`,table:l,unique:!1});for(const[a,m]of Ue(d))m.unique&&await ye(r,i,{columns:$(a),name:`${l}_unique_${a}`,table:l,unique:!0})},On=async(r,l,d)=>{for(const[i,$]of Object.entries(l.tables)){if($.shardMode?.kind!=="global")continue;const u=kn(i,$,d);await A(r,d,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (${u})`),await Dn(r,i,$,d)}},Fn=async(r,l,d)=>{const{integer:i,key:$,real:u}=d.companionTypes;for(const[a,m]of Object.entries(l.tables)){const R=m.aggregateIndexes;if(!(!R||R.length===0))for(const g of R){const b=Q(a,g.name);await A(r,d,e`CREATE TABLE IF NOT EXISTS ${e.identifier(b)} (${e.identifier("__key__")} ${e.raw($)} PRIMARY KEY, ${e.identifier("__value__")} ${e.raw(u)}, ${e.identifier("__count__")} ${e.raw(i)} NOT NULL DEFAULT 0)`),d.name==="sqlite"&&((await I(r,d,e`PRAGMA table_info(${e.identifier(b)})`)).some(q=>q.name==="__count__")||await A(r,d,e`ALTER TABLE ${e.identifier(b)} ADD COLUMN ${e.identifier("__count__")} ${e.raw(i)} NOT NULL DEFAULT 0`))}}},xe=(r,l,d,i)=>{const $=r.name==="mysql"&&i?e`${e.identifier(l)}(191)`:e`${e.identifier(l)}`;return e`${$} ${e.raw(d)}`},xn=(r,l,d)=>{const i=[xe(r,"__partition__","ASC",!0)];for(const[$,u]of l.sortBy.entries()){const a=d.shape[u.field],m=a!==void 0&&r.indexKeyPrefix?.(Le(a))!==void 0;i.push(xe(r,J($),u.direction==="desc"?"DESC":"ASC",m))}return i.push(xe(r,"__id__","ASC",!0)),i},Bn=(r,l,d)=>l.sortBy.map((i,$)=>{const u=d.shape[i.field],a=r.columnType(u?Le(u):void 0);return e`${e.identifier(J($))} ${e.raw(a)}`}),Wn=async(r,l,d)=>{const{key:i}=d.companionTypes;for(const[$,u]of Object.entries(l.tables)){const a=u.rankIndexes;if(!(!a||a.length===0))for(const m of a){const R=ne($,m.name),g=Bn(d,m,u),b=g.length>0?e`, ${e.join(g,e`, `)}`:e``;await A(r,d,e`CREATE TABLE IF NOT EXISTS ${e.identifier(R)} (${e.identifier("__id__")} ${e.raw(i)} PRIMARY KEY, ${e.identifier("__partition__")} ${e.raw(i)} NOT NULL${b})`);const L=xn(d,m,u),q=`${$}__rank_${m.name}__btree`;await ye(r,d,{columns:e.join(L,e`, `),name:q,table:R,unique:!1})}}},Be="__cdc_sweep",ht="global",Un=6e4,Pn=1e4,Kn=3e4;let wt=0;const jn=async(r,l)=>{const{autoincrementPrimaryKey:d,key:i,real:$,text:u}=l.companionTypes;await A(r,l,e`CREATE TABLE IF NOT EXISTS ${e.identifier(G)} (${e.identifier("seq")} ${e.raw(d)}, ${e.identifier("ts")} ${e.raw($)} NOT NULL, ${e.identifier("table")} ${e.raw(i)} NOT NULL, ${e.identifier("id")} ${e.raw(i)} NOT NULL, ${e.identifier("op")} ${e.raw(i)} NOT NULL, ${e.identifier("doc")} ${e.raw(u)})`);const a=l.indexKeyPrefix?.("string");await ye(r,l,{columns:e`${a===void 0?e`${e.identifier("table")}`:e`${e.identifier("table")}(${e.raw(String(a))})`}, ${e.identifier("seq")}`,name:dn,table:G,unique:!1}),await A(r,l,e`CREATE TABLE IF NOT EXISTS ${e.identifier(Be)} (${e.identifier("id")} ${e.raw(i)} NOT NULL PRIMARY KEY, ${e.identifier("lease_until")} ${e.raw($)} NOT NULL)`),await A(r,l,e`INSERT INTO ${e.identifier(Be)} (${e.identifier("id")}, ${e.identifier("lease_until")}) VALUES (${ht}, ${0}) ${l.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${e.identifier("id")} = ${e.identifier("id")}`:e`ON CONFLICT(${e.identifier("id")}) DO NOTHING`}`)},Hn=async(r,l,d)=>{const i=e`UPDATE ${e.identifier(Be)} SET ${e.identifier("lease_until")} = ${d+Un} WHERE ${e.identifier("id")} = ${ht} AND ${e.identifier("lease_until")} <= ${d}`;if(l.supportsReturning)return(await I(r,l,e`${i} RETURNING ${e.identifier("id")}`)).length>0;const $=await A(r,l,i);return(l.affectedRows?l.affectedRows($??{rowsAffected:0}):0)>0},Gn=async(r,l,d,i)=>{if(!await Hn(r,l,i))return;const $=i-d;await A(r,l,e`
|
|
2
|
+
DELETE FROM ${e.identifier(G)} WHERE ${e.identifier("seq")} IN (
|
|
3
|
+
SELECT ${e.identifier("seq")} FROM (
|
|
4
|
+
SELECT ${e.identifier("seq")} FROM ${e.identifier(G)} WHERE ${e.identifier("ts")} <= ${$} ORDER BY ${e.identifier("seq")} ASC LIMIT ${e.raw(String(Pn))}
|
|
5
|
+
) AS ${e.identifier("expired")}
|
|
6
|
+
)
|
|
7
|
+
`)},Et=async(r,l)=>{const d=await I(r,l,e`SELECT MIN(${e.identifier("seq")}) AS ${e.identifier("seq")} FROM ${e.identifier(G)}`),i=Number(d[0]?.seq??Number.NaN);return Number.isFinite(i)?i:void 0},Vn=r=>JSON.stringify(un(r)?fn(r):r),Yn=async(r,l,d,i,$,u,a)=>{await A(r,a,e`INSERT INTO ${e.identifier(G)} (${e.identifier("ts")}, ${e.identifier("table")}, ${e.identifier("id")}, ${e.identifier("op")}, ${e.identifier("doc")}) VALUES (${l}, ${d}, ${i}, ${$}, ${u===void 0?null:Vn(u)})`)},ii=async(r,l,d)=>{const i=l.sinceSeq??0,$=Math.max(1,Math.min(l.limit??1e3,1e4)),u=await Et(r,d);if(u!==void 0&&Wt(u,i))throw Ut(u,i,"global");const m=(await I(r,d,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(G)} WHERE seq > ${i} ORDER BY seq ASC LIMIT ${e.raw(String($))}`)).map(R=>{const{doc:g}=R,b={id:String(R.id),op:String(R.op),seq:Number(R.seq),table:String(R.table),ts:Number(R.ts)};return typeof g=="string"?{...b,doc:_t(JSON.parse(g))}:b});return{changes:m,cursor:m.at(-1)?.seq??i}},Xn=async(r,l,d,i={})=>{if(i.cursorOnly){const R=await I(r,d,e`SELECT MAX(seq) AS seq FROM ${e.identifier(G)}`),g=Number(R[0]?.seq??l);return{cursor:Number.isFinite(g)?g:l,tables:[]}}const $=await I(r,d,e`SELECT ${e.identifier("table")} AS ${e.identifier("table")}, MAX(seq) AS seq FROM ${e.identifier(G)} WHERE seq > ${l} GROUP BY ${e.identifier("table")}`);let u=l;const a=[];for(const R of $){const g=Number(R.seq);Number.isFinite(g)&&g>u&&(u=g),a.push(String(R.table))}const m=i.retained===!0?await Et(r,d):void 0;return{cursor:u,tables:a,...m===void 0?{}:{floor:m}}},oi=r=>{const{crossShardCounter:l,crossShardReader:d,exec:i,maxRelationKeys:$,schema:u}=r,{dialect:a}=r,{isUniqueViolation:m}=a,R={fieldRef:M,serialize:H,...a.name==="mysql"?{containsExpr:(t,n)=>e`LOCATE(${n}, ${t}) > 0`}:{},...a.name==="postgres"?{containsExpr:(t,n)=>e`strpos(${t}, ${n}) > 0`}:{},...a.name==="sqlite"?{}:{inList:xt}},g=(t,n)=>We(a.name,t,n),b=t=>{const n=te(t.columns),o=re(t.values),s=f=>a.name==="mysql"?e`VALUES(${e.identifier(f)})`:e`excluded.${e.identifier(f)}`,c=f=>a.name==="postgres"?e`${e.identifier(t.table)}.${e.identifier(f)}`:e`${e.identifier(f)}`,_=e.join(Object.entries(t.set(s,c)).map(([f,y])=>e`${e.identifier(f)} = ${y}`),e`, `),E=a.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${_}`:e`ON CONFLICT(${e.identifier(t.conflictKey)}) DO UPDATE SET ${_}`;return e`INSERT INTO ${e.identifier(t.table)} (${n}) VALUES (${o}) ${E}`},L=r.clock??(()=>Date.now()),q=r.idGenerator??(()=>crypto.randomUUID()),B=r.cdc??!1,V=typeof r.cdcRetentionMs=="number"&&Number.isFinite(r.cdcRetentionMs)&&r.cdcRetentionMs>0?r.cdcRetentionMs:void 0,Y=r.auth??{identity:null,userId:null},X=async(t,n,o,s)=>{if(!B||(await Yn(i,L(),t,n,o,s,a),V===void 0))return;const c=L();if(!(c-wt<Kn)){wt=c;try{await Gn(i,a,V,c)}catch{}}},yt=r.scheduler??Bt,Ne=Tn();let pe=0,ke;const W=async()=>(ke??=(async()=>{await On(i,u,a),await Fn(i,u,a),await Wn(i,u,a),await wn(i,a),await At(i,u,a),B&&await jn(i,a)})().catch(t=>{throw ke=void 0,t}),ke),se=async(t,n)=>{await W();const o=await Sn(i,a,u,t,Ne);if(!(n!==void 0&&o!==n))return o},ae=new Map,Pe=async(t,n)=>{const o=Q(t,n);return(await I(i,a,a.tableExists(o))).length>0},Re=async(t,n)=>{const o=`${t}::${n.name}`,s=ae.get(o);if(s!==void 0)return s;if(!await Pe(t,n.name))return ae.set(o,!1),!1;const _=u.tables[t];if(!_)return ae.set(o,!1),!1;const E=n.by??[],f=new Map;await ct(i,a,_,t,h=>{if(n.where&&!Oe(h,n.where))return;const p=z(E,h);an(f,p,n,h)});const y=Q(t,n.name);await A(i,a,e`DELETE FROM ${e.identifier(y)}`);const w=[];for(const[h,p]of f)w.push(e`INSERT INTO ${e.identifier(y)} (${e.identifier("__key__")}, ${e.identifier("__value__")}, ${e.identifier("__count__")}) VALUES (${h}, ${p.value}, ${p.count})`);return await dt(i,a,w),ae.set(o,!0),!0},pt=async(t,n,o)=>{const s=we(n.op),c=n.field??"",_=[];for(const y of n.by??[]){const w=H(o[y]??null);_.push(w===null?e`${M(y)} IS NULL`:e`${M(y)} = ${w}`)}for(const[y,w]of Object.entries(n.where??{})){const h=w!==null&&typeof w=="object"&&!Array.isArray(w)?w.eq:w,p=H(h);_.push(p===null?e`${M(y)} IS NULL`:e`${M(y)} = ${p}`)}const E=e`SELECT ${e.raw(s)}(${M(c)}) AS value FROM ${e.identifier(t)}`,f=await I(i,a,_.length>0?e`${E} WHERE ${e.join(_,e` AND `)}`:E);return oe(f[0]?.value)},Rt=async(t,n)=>{await A(i,a,e`DELETE FROM ${e.identifier(t)} WHERE ${e.identifier("__key__")} = ${n} AND ${e.identifier("__count__")} <= 0`)},mt=async(t,n,o,s)=>{const c=Q(t,n.name),{op:_}=n,E=n.field??"",f=o&&(!n.where||Oe(o,n.where))?o:void 0,y=s&&(!n.where||Oe(s,n.where))?s:void 0;if(!(!f&&!y)){if(_==="count"||_==="sum"||_==="avg"){const w=new Set;for(const[h,p]of[[f,-1],[y,1]]){if(!h)continue;const S=_==="count"?1:Fe(h[E]);if(S===void 0)continue;const T=z(n.by??[],h);w.add(T),await A(i,a,b({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(C,N)=>({__count__:e`${N("__count__")} + ${C("__count__")}`,__value__:_==="count"?e`${N("__value__")} + ${C("__value__")}`:e`COALESCE(${N("__value__")}, 0) + ${C("__value__")}`}),table:c,values:[T,p*S,p]}))}for(const h of w)await Rt(c,h);return}if(f){const w=z(n.by??[],f),h=Fe(f[E]),S=(await I(i,a,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(c)} WHERE ${e.identifier("__key__")} = ${w}`))[0],T=oe(S?.value),C=(S?.count??0)-1;if(C<=0)await A(i,a,e`DELETE FROM ${e.identifier(c)} WHERE ${e.identifier("__key__")} = ${w}`);else if(S&&h!==void 0&&T!==null&&h===T){const N=await pt(t,n,f);await A(i,a,e`UPDATE ${e.identifier(c)} SET ${e.identifier("__value__")} = ${N}, ${e.identifier("__count__")} = ${C} WHERE ${e.identifier("__key__")} = ${w}`)}else await A(i,a,e`UPDATE ${e.identifier(c)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${w}`)}if(y){const w=z(n.by??[],y),h=Fe(y[E]);if(h===void 0)await A(i,a,b({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(p,S)=>({__count__:e`${S("__count__")} + 1`}),table:c,values:[w,null,1]}));else{const p=_==="min"?"MIN":"MAX";await A(i,a,b({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(S,T)=>({__count__:e`${T("__count__")} + 1`,__value__:e`${e.raw(p)}(COALESCE(${T("__value__")}, ${S("__value__")}), ${S("__value__")})`}),table:c,values:[w,h,1]}))}}}},me=async t=>{const n=u.tables[t]?.aggregateIndexes;if(!(!n||n.length===0))for(const o of n)await Re(t,o)},ce=async(t,n,o)=>{const s=u.tables[t]?.aggregateIndexes;if(!(!s||s.length===0))for(const c of s){const _=`${t}::${c.name}`;(ae.get(_)??await Pe(t,c.name))&&await mt(t,c,n,o)}},de=new Map,Ke=async(t,n)=>{const o=ne(t,n);return(await I(i,a,a.tableExists(o))).length>0},Me=async(t,n)=>{const o=`${t}::rank::${n.name}`,s=de.get(o);if(s!==void 0)return s;if(!await Ke(t,n.name))return de.set(o,!1),!1;const _=u.tables[t];if(!_)return de.set(o,!1),!1;const E=ne(t,n.name);await A(i,a,e`DELETE FROM ${e.identifier(E)}`);const f=n.sortBy.map((p,S)=>J(S)),y=te(["__id__","__partition__",...f]),w=[];await ct(i,a,_,t,p=>{if(n.where&&!at(p,n.where))return;const S=Ae(n.partitionBy??[],p),T=n.sortBy.map(C=>H(p[C.field]??null));w.push([p._id,S,...T])});const h=w.map(p=>e`INSERT INTO ${e.identifier(E)} (${y}) VALUES (${re(p)})`);return await dt(i,a,h),de.set(o,!0),!0},Te=async t=>{const n=u.tables[t]?.rankIndexes;if(!(!n||n.length===0))for(const o of n)await Me(t,o)},Z=async(t,n,o,s)=>{const c=u.tables[t],_=c?.rankIndexes;if(!_||_.length===0)return;const E=c?.softDeleteMode?.field,f=E===void 0||s===void 0?void 0:s[E],y=f!=null;for(const w of _){if(o!==void 0&&s!==void 0&&vn(w,o,s))continue;const h=`${t}::rank::${w.name}`;if(!(de.get(h)??await Ke(t,w.name)))continue;const T=ne(t,w.name);if(o&&await A(i,a,e`DELETE FROM ${e.identifier(T)} WHERE ${e.identifier("__id__")} = ${n}`),s&&!y){if(w.where&&!at(s,w.where))continue;const C=w.sortBy.map((D,j)=>J(j)),N=te(["__id__","__partition__",...C]),x=Ae(w.partitionBy??[],s),k=w.sortBy.map(D=>H(s[D.field]??null));await A(i,a,e`INSERT INTO ${e.identifier(T)} (${N}) VALUES (${re([n,x,...k])})`)}}},le=Ct({dialect:a,exec:i,schema:u}),je=new Set;for(const[t,n]of Object.entries(u.tables))for(const o of Object.values(n.triggerMap??{}))je.add(`${t} ${o.timing} ${o.op}`);const P=(t,n,o)=>je.has(`${t} ${n} ${o}`);let He;const K=async(t,n,o)=>{if(pe+=1,pe>ut)throw pe-=1,new he(`trigger recursion exceeded ${String(ut)} levels on "${o.table}" — check for a self-triggering write`,"trigger");try{await tn({ctx:He,event:o,op:n,schema:u,tableName:o.table,timing:t})}finally{pe-=1}},Tt=async(t,n)=>{try{await A(i,a,n)}catch(o){throw m(o)?new he(`unique constraint violation on "${t}"`,"unique"):o}},Se=async(t,n)=>(await I(i,a,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} = ${n}`))[0],ge=async(t,n,o,s)=>{if(s===void 0)return;const c=e.join(Object.keys(s).map(f=>g(e`${e.identifier(f)}`,s[f])),e` AND `),_=n==="UPDATE"?e`UPDATE ${e.identifier(t)} SET ${o} WHERE ${c}`:e`DELETE FROM ${e.identifier(t)} WHERE ${c}`,E=()=>{throw new he(`optimistic concurrency conflict on "${t}" — the row changed during this mutation; refetch and retry`,"occ")};try{if(a.supportsReturning)(await I(i,a,e`${_} RETURNING ${e.identifier("id")}`)).length===0&&E();else{const f=await A(i,a,_);(a.affectedRows?a.affectedRows(f??{rowsAffected:0}):0)===0&&E()}}catch(f){throw m(f)?new he(`unique constraint violation on "${t}"`,"unique"):f}},St=(t,n,o,s)=>{const c=Object.keys(t.shape);return{columns:["id","_creationTime",...c],values:[n,o,...c.map(_=>H(s[_]??null))]}},gt=async(t,n,o,s)=>{const c=on(n,o.op,o.field,s.by,s.where);if(!c||!await Re(t,c.index))return;const E=Q(t,c.index.name),f=Object.keys(c.partial);if(f.length===(c.index.by??[]).length&&f.length>0){const w=z(c.index.by??[],c.partial),h=await I(i,a,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(E)} WHERE ${e.identifier("__key__")} = ${w}`);if(h.length===0)return[];const p=h[0];return[{key:{...c.partial},value:De(o.op,{count:p.count,value:oe(p.value)})}]}return f.length>0?void 0:(await I(i,a,e`SELECT ${e.identifier("__key__")} AS key, ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(E)}`)).map(w=>{const h=w;return{key:_t(JSON.parse(h.key)),value:De(o.op,{count:h.count,value:oe(h.value)})}})},Ge=t=>{const n=u.tables[t]?.shardMode?.kind;return n==="shardBy"||n==="root"},Ve=t=>{throw new v("INTERNAL",`cross-backend relation: a global table cannot load the shard-local relation '${t}' (it spans every shard) — wire a cross-shard reader to support it`)},vt=(t,n)=>{if(n?.relationMask!==void 0&&n.with!==void 0&&Object.keys(n.with).length>0)throw new v("MASK_UNSUPPORTED",`masking cannot follow a nested \`with\` across the cross-shard relation hop to "${t}" — the nested rows are hydrated on the serving shard, where the mask policy does not exist. Read the nested relation at its own (masked) call site instead.`);const o={};if(n?.relationBaseWhere)for(const s of Object.keys(u.tables)){const c=n.relationBaseWhere(s);c!==void 0&&(o[s]=c)}return{orderBy:n?.orderBy,relationPolicies:o,where:F(n?.baseWhere,n?.where),with:n?.with}},Ye=(t,n)=>Ge(t)?d?d(t,vt(t,n)):Ve(t):U.findMany(t,n),ve=(t,n,o)=>it(t,{fetcher:Ye,maxRelationKeys:$,relationBaseWhere:o,schema:u,tableName:n}),bt=hn(async(t,n)=>{const o=await I(i,a,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} IN (${re(n)})`),s=new Map;for(const c of o){const{id:_}=c;typeof _=="string"&&s.set(_,c)}return s}),U={async cdcChangedTables(t,n){if(B)try{return await W(),await Xn(i,t,a,{...n,retained:V!==void 0})}catch{return}},async aggregate(t,n){const o=u.tables[t];if(!o)throw new v("INTERNAL",`unknown table: ${t}`);if(await W(),we(n.op),n.op==="count")return U.count(t,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new v("INTERNAL",`aggregate(${t}, { op: "${n.op}" }): "field" is required for non-count reducers`);const s=_e(o.softDeleteMode,void 0),c=F(F(n.baseWhere,n.where),s),_=await ve(c,t,n.relationBaseWhere),E=_!==c;if(o.aggregateIndexes&&!n.baseWhere&&!E&&!s){const S=en(o.aggregateIndexes,n.op,n.field,n.where);if(S&&await Re(t,S.index)){const C=z(S.index.by??[],S.key),N=Q(t,S.index.name),k=(await I(i,a,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(N)} WHERE ${e.identifier("__key__")} = ${C}`))[0];return De(n.op,k===void 0?void 0:{count:k.count,value:oe(k.value)})}}const f=$e(_,R),y=e.raw(we(n.op)),w=e`SELECT ${y}(${M(n.field)}) AS value FROM ${e.identifier(t)}`,p=(await I(i,a,f?e`${w} WHERE ${f}`:w))[0]?.value;return p==null?null:Number(p)},async count(t,n){const o=u.tables[t];if(!o)throw new v("INTERNAL",`unknown table: ${t}`);await W();const s=Jt(n);if(s.restrictsCounts)throw new nt(t);const c=_e(o.softDeleteMode,void 0),_=F(F(s.baseWhere,s.where),c),E=await ve(_,t,s.relationBaseWhere),f=E!==_;if(o.aggregateIndexes&&!s.baseWhere&&!f&&!c){const p=Zt(o.aggregateIndexes,s.where);if(p&&await Re(t,p.index)){const T=z(p.index.by??[],p.key),C=Q(t,p.index.name),N=await I(i,a,e`SELECT ${e.identifier("__value__")} AS value FROM ${e.identifier(C)} WHERE ${e.identifier("__key__")} = ${T}`);return Number(N[0]?.value??0)}}const y=$e(E,R),w=e`SELECT COUNT(*) AS count FROM ${e.identifier(t)}`,h=await I(i,a,y?e`${w} WHERE ${y}`:w);return Number(h[0]?.count??0)},async delete(t,n,o){const s=await se(t,n);if(!s)return;const c=u.tables[s];if(!c)return;const _=await Se(s,t),E=ie(c,_),f=o?.hard===!0,y=!f&&c.softDeleteMode?c.softDeleteMode.field:void 0;if(!(y&&(!E||E[y]!==null&&E[y]!==void 0))){if(P(s,"before","delete")&&await K("before","delete",{id:t,op:"delete",previous:E??void 0,table:s}),await Qt({deletedId:t,deletedReference:w=>E?.[w],findHolders:async(w,h,p)=>{if(u.tables[w]?.shardMode?.kind==="shardBy")throw new v("INTERNAL",`cross-backend cascade from global '${s}' into shardBy '${w}' is not supported — would require Query Coordinator fan-out across shards`);return(await U.findMany(w,{includeDeleted:f,where:{[h]:p}})).page},onCascade:(w,h)=>U.delete(h,void 0,o),onRestrict:w=>{throw new he(w,"restrict")},onSetNull:(w,h,p)=>U.patch(h,{[p]:null}),schema:u,tableName:s}),await me(s),await Te(s),y&&E){const w={...E,[y]:L()},h=e.join(Object.keys(c.shape).map(p=>e`${e.identifier(p)} = ${H(w[p]??null)}`),e`, `);await ge(s,"UPDATE",h,_),await ce(s,E,w),await Z(s,t,E,void 0),await le(s,t,w,E),await X(s,t,"update",w),P(s,"after","delete")&&await K("after","delete",{id:t,op:"delete",previous:E,table:s});return}await ge(s,"DELETE",void 0,_),Ne.delete(t),await ce(s,E??void 0,void 0),await Z(s,t,E??void 0,void 0),await le(s,t,void 0),await X(s,t,"delete"),P(s,"after","delete")&&await K("after","delete",{id:t,op:"delete",previous:E??void 0,table:s})}},async findFirst(t,n={}){return(await U.findMany(t,{...n,limit:1})).page[0]??null},async findFirstOrThrow(t,n={}){const o=await U.findFirst(t,n);if(o===null)throw new zt(`findFirstOrThrow: no "${t}" document matched`);return o},async findMany(t,n={}){const o=u.tables[t];if(!o)throw new v("INTERNAL",`unknown table: ${t}`);await W();const s=Gt(n.orderBy,o.shape),c=n.cursor?Vt(s,Yt(n.cursor)):void 0,_=Ye,E=async(k,D,j,be)=>{if(Ge(k))return l?sn(l,k,D,j,be):Ve(k);const Ie=u.tables[k];if(!Ie)throw new v("INTERNAL",`unknown table: ${k}`);const Ce=_e(Ie.softDeleteMode,void 0),ee={[D]:{in:j}},O=F(F(ee,be),Ce),ue=await ve(O,k,void 0),Xe=$e(ue,R),ze=M(D);let fe=e`SELECT ${ze} AS __fk__, COUNT(*) AS count FROM ${e.identifier(k)}`;Xe&&(fe=e`${fe} WHERE ${Xe}`),fe=e`${fe} GROUP BY ${ze}`;const It=await I(i,a,fe),Qe=new Map;for(const Je of It)Qe.set(Je.__fk__,Number(Je.count??0));return Qe};let f=F(n.baseWhere,n.where);f=F(f,_e(o.softDeleteMode,n.includeDeleted)),f=await it(f,{fetcher:_,maxRelationKeys:$,relationBaseWhere:n.relationBaseWhere,schema:u,tableName:t}),c&&(f=f?{AND:[f,c]}:c);const y=$e(f,R),w=pn(s,a);let h=e`SELECT * FROM ${e.identifier(t)}`;y&&(h=e`${h} WHERE ${y}`),h=e`${h} ORDER BY ${w}`;const p=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;p!==void 0&&(h=e`${h} LIMIT ${e.raw(String(p+1))}`);const S=await I(i,a,h),T=_n(o,S);if(p===void 0)return n.with&&await ot({fetcher:_,groupedCounter:E,parents:T,...rt(n),schema:u,tableName:t,with:n.with}),{continueCursor:null,isDone:!0,page:st(T,n.select,n.with)};const C=T.length>p,N=C?T.slice(0,p):T,x=N.at(-1);return n.with&&await ot({fetcher:_,groupedCounter:E,parents:N,...rt(n),schema:u,tableName:t,with:n.with}),{continueCursor:C&&x?Xt(x,s):null,isDone:!C,page:st(N,n.select,n.with)}},async get(t,n){const o=await se(t,n);if(!o)return null;const s=u.tables[o];return s?ie(s,await bt.load(o,t)):null},async groupBy(t,n){const o=u.tables[t];if(!o)throw new v("INTERNAL",`unknown table: ${t}`);await W();const s=n.agg??{op:"count"};if(we(s.op),s.op!=="count"&&!s.field)throw new v("INTERNAL",`groupBy(${t}, { agg: { op: "${s.op}" } }): "field" is required for non-count reducers`);const c=_e(o.softDeleteMode,void 0),_=F(F(n.baseWhere,n.where),c),E=await ve(_,t,n.relationBaseWhere),f=E!==_;if(o.aggregateIndexes&&!n.baseWhere&&!f&&!c){const T=await gt(t,o.aggregateIndexes,s,n);if(T!==void 0)return T}const y=$e(E,R),w=n.by.map(T=>e`${M(T)} AS ${e.identifier(T)}`);if(s.op==="count")w.push(e`COUNT(*) AS value`);else{if(!s.field)throw new v("INTERNAL",`groupBy(${t}, { agg: { op: "${s.op}" } }): "field" is required for non-count reducers`);w.push(e`${e.raw(we(s.op))}(${M(s.field)}) AS value`)}const h=e.join(n.by.map(T=>M(T)),e`, `);let p=e`SELECT ${e.join(w,e`, `)} FROM ${e.identifier(t)}`;y&&(p=e`${p} WHERE ${y}`),p=e`${p} GROUP BY ${h}`;const S=await I(i,a,p);return gn(n.by,S)},async insert(t,n,o){const s=u.tables[t];if(!s)throw new v("INTERNAL",`unknown table: ${t}`);await W();const c=Rn(s,n,Y);qe(s,c);let _,E=!0;o?.clientId!==void 0?(Ht(o.clientId),_=o.clientId):o?.allowExplicitId&&typeof c._id=="string"?_=c._id:(_=q(),E=!1);const f=o?.allowExplicitId&&typeof c._creationTime=="number"?c._creationTime:L(),y={...c,_creationTime:f,_id:_};P(t,"before","insert")&&await K("before","insert",{doc:{...y},id:_,op:"insert",table:t}),await me(t),await Te(t);const{columns:w,values:h}=St(s,_,f,c);return await Tt(t,e`INSERT INTO ${e.identifier(t)} (${te(w)}) VALUES (${re(h)})`),E&&Ne.set(_,t),await ce(t,void 0,y),await Z(t,_,void 0,y),await le(t,_,y),await X(t,_,"insert",y),P(t,"after","insert")&&await K("after","insert",{doc:y,id:_,op:"insert",table:t}),_},normalizeId(t,n){return jt(u,t,n)},async patch(t,n,o){Ze("patch",n);const s=await se(t,o);if(!s)throw new v("INTERNAL",`document not found: ${t}`);const c=u.tables[s];if(!c)throw new v("INTERNAL",`document not found: ${t}`);const _=await Se(s,t),E=ie(c,_);if(!E)throw new v("INTERNAL",`document not found: ${t}`);const f={...E,...n,_id:t};ft(c,n,f,Y),qe(c,f,!0),P(s,"before","update")&&await K("before","update",{doc:{...f},id:t,op:"update",previous:E,table:s}),await me(s),await Te(s);const y=Object.keys(c.shape),w=e.join(y.map(h=>e`${e.identifier(h)} = ${H(f[h]??null)}`),e`, `);await ge(s,"UPDATE",w,_),await ce(s,E,f),await Z(s,t,E,f),await le(s,t,f,E),await X(s,t,"update",f),P(s,"after","update")&&await K("after","update",{doc:f,id:t,op:"update",previous:E,table:s})},async restore(t,n){const o=await se(t,n);if(!o)throw new v("INTERNAL",`document not found: ${t}`);const s=u.tables[o],c=s?.softDeleteMode?.field;if(!s||!c)throw new v("INTERNAL",`ctx.db.restore: table "${o}" is not a .softDelete() table`);const _=await Se(o,t),E=_?.[c]!==null&&_?.[c]!==void 0;if(await U.patch(t,{[c]:null},n),E){const f=ie(s,_);f!==null&&await Z(o,t,void 0,{...f,[c]:null})}},query(t){const n=u.tables[t];if(!n)throw new v("INTERNAL",`unknown table: ${t}`);const o="the legacy query()/withIndex() reader is not available on the D1 (global) backend; use findMany",s=[],c=f=>s.every(y=>y(f)),_=async(f,y)=>{await W();const w=s.length>0,h=await qt(i,a,n,t,f,Dt(w?void 0:y));if(!w)return y===void 0&&Ot(h),h;const p=h.filter(S=>c(S));return y===void 0?p:p.slice(0,y)},E=f=>{const y={async*[Symbol.asyncIterator](){if(!f)throw new v("INTERNAL",o);yield*await _(f,void 0)},async collect(){if(!f)throw new v("INTERNAL",o);return _(f,void 0)},async collectWithScores(){throw new v("GLOBAL_SEARCH_SCORES_UNSUPPORTED",`collectWithScores() is not supported on \`.global()\` tables (table "${t}") — relevance scores are not yet surfaced on this backend; use .collect() instead`)},filter(w){return s.push(w),y},async first(){if(!f)throw new v("INTERNAL",o);return(await _(f,1))[0]??null},order(){return y},async paginate(w){if(!f)throw new v("INTERNAL",o);const h=kt(w);return Mt(await _(f,Ft(h)),h)},async take(w){if(!f)throw new v("INTERNAL",o);return _(f,w)},async unique(){if(!f)throw new v("INTERNAL",o);const w=await _(f,2);if(w.length>1)throw new ln(`unique() on table "${t}" matched ${String(w.length)} documents; expected at most one`);return w[0]??null},withGeoIndex(){throw new v("INTERNAL",`geo indexes are not supported on \`.global()\` tables (table "${t}") — geospatial queries run only on sharded tables`)},withIndex(){throw new v("INTERNAL",o)},withSearchIndex(w,h){const p=(n.searchIndexes??[]).find(T=>T.name===w);if(!p)throw new v("INTERNAL",`unknown search index "${w}" on table "${t}"`);const S={definition:p,field:p.field,filters:[],hasQuery:!1,indexName:w,query:""};if(h(Lt(S,t,Nt(p.language))),!S.hasQuery)throw new v("INTERNAL",`search index "${w}" on table "${t}" requires a .search(field, query) call`);return E(S)}};return y};return E(void 0)},async rank(t,n,o){const s=u.tables[t];if(!s)throw new v("INTERNAL",`unknown table: ${t}`);const c=s.rankIndexes?.find(D=>D.name===n);if(!c)throw new v("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(o.restrictsCounts)throw new nt(t);if(await W(),!await Me(t,c))return null;const E=typeof o.row=="string"?o.row:o.row._id;if(!E)return null;const f=ne(t,c.name),y=c.sortBy.map((D,j)=>J(j)),w=te(["__partition__",...y]),p=(await I(i,a,e`SELECT ${w} FROM ${e.identifier(f)} WHERE ${e.identifier("__id__")} = ${E}`))[0];if(!p)return null;const S=p.__partition__,T=F(o.baseWhere,o.where);et(T,u,t,"rank");const C=tt(c,T);if(C&&Ae(c.partitionBy??[],C)!==S)return null;const N=bn(a.name,c,y,p,E),x=await I(i,a,e`SELECT COUNT(*) AS c FROM ${e.identifier(f)} WHERE ${e.identifier("__partition__")} = ${S}${N?e` AND (${N})`:e``}`),k=await I(i,a,e`SELECT COUNT(*) AS c FROM ${e.identifier(f)} WHERE ${e.identifier("__partition__")} = ${S}`);return{position:Number(x[0]?.c??0)+1,total:Number(k[0]?.c??0)}},async rankPage(t,n,o={}){et(F(o.baseWhere,o.where),u,t,"rankPage");const s=u.tables[t];if(!s)throw new v("INTERNAL",`unknown table: ${t}`);const c=s.rankIndexes?.find(O=>O.name===n);if(!c)throw new v("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(await W(),!await Me(t,c))return{continueCursor:null,isDone:!0,page:[]};const E=ne(t,c.name),f=c.sortBy.map((O,ue)=>J(ue)),y=Math.max(1,Math.min(1e3,Math.floor(o.take??100))),w=F(o.baseWhere,o.where),h=tt(c,w),p=Cn(c,f),S=e.join(p.map(O=>e`${e.identifier(O.column)} ${e.raw(O.direction==="desc"?"DESC":"ASC")}`),e`, `),T=[];typeof o.partitionKey=="string"?T.push(e`${e.identifier("__partition__")} = ${o.partitionKey}`):h&&T.push(e`${e.identifier("__partition__")} = ${Ae(c.partitionBy??[],h)}`);const C=Kt(o);if(C!==void 0){const O=In(a.name,p,C);O!==void 0&&T.push(O)}const N=te([Ee,"__partition__",...f]);let x=e`SELECT ${N} FROM ${e.identifier(E)}`;T.length>0&&(x=e`${x} WHERE ${e.join(T,e` AND `)}`),x=e`${x} ORDER BY ${S} LIMIT ${e.raw(String(y+1))}`;const k=await I(i,a,x),D=k.length>y,j=D?k.slice(0,y):k,be=j.map(O=>O[Ee]),Ie=await An(i,a,s,t,be);let Ce=null;const ee=j.at(-1);if(D&&ee!==void 0){const O=[ee.__partition__,...f.map(ue=>ee[ue]),ee[Ee]];Ce=Ln(O)}return{continueCursor:Ce,isDone:!D,page:Ie}},async replace(t,n,o,s){Ze("replace",n);const c=await se(t,o);if(!c)throw new v("INTERNAL",`document not found: ${t}`);const _=u.tables[c];if(!_)throw new v("INTERNAL",`document not found: ${t}`);const E=await Se(c,t);if(E===void 0)throw new v("INTERNAL",`document not found: ${t}`);const y=Pt(u,c,"update")||(_.aggregateIndexes??[]).length>0||(_.rankIndexes??[]).length>0?ie(_,E)??void 0:void 0,w=s?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:L(),h={...n,_creationTime:w,_id:t};ft(_,n,h,Y),qe(_,h),P(c,"before","update")&&await K("before","update",{doc:{...h},id:t,op:"update",previous:y,table:c}),await me(c),await Te(c);const p=Object.keys(_.shape),S=e.join([e`${e.identifier("_creationTime")} = ${w}`,...p.map(T=>e`${e.identifier(T)} = ${H(h[T]??null)}`)],e`, `);await ge(c,"UPDATE",S,E),await ce(c,y,h),await Z(c,t,y,h),await le(c,t,h,y),await X(c,t,"update",h),P(c,"after","update")&&await K("after","update",{doc:h,id:t,op:"update",previous:y,table:c})}};return He={db:U,scheduler:yt},U};export{ai as backfillSqlSearchIndexes,oi as createSqlCtxDb,di as decodeGlobalRow,Xn as readSqlCdcChangedTables,ii as readSqlCdcChanges,Et as readSqlCdcFloor,Fn as runSqlAggregateMigrations,jn as runSqlCdcMigration,On as runSqlGlobalTableMigrations,Wn as runSqlRankMigrations,At as runSqlSearchMigrations,Gn as sweepSqlCdcRetention};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{migrateSearchState as Z,readSearchBackfillState as P,writeSearchBackfillState as I}from"./SEARCH_STATE_TABLE-B5a5xBwB.mjs";import{LunoraError as h}from"@lunora/errors";import{unionAll as ee}from"@lunora/shard-engine";import{queryRun as S,decodeRows as z,queryAll as D,queryBatch as ne,createIndexIfNotExists as U,columnRefSql as F,serializeColumnValue as te,forEachRowPaged as ie}from"./decodeGlobalRow-C8O2hy0d.mjs";const oe=["de","en","es","fr","it","nl","none","pt"],re=e=>oe.includes(e),se="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",ae="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",ce="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",ue="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",fe="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",de="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",le="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",me=/[\u0300-\u036F]/gu,$e=/[\u0080-\u{10FFFF}]/u,he=/[\p{L}\p{N}]+/gu,W=e=>$e.test(e)?e.normalize("NFD").replaceAll(me,"").normalize("NFC").toLowerCase():e.toLowerCase(),g=e=>new Set(W(e).split(" ")),we={de:g(ae),en:g(se),es:g(ce),fr:g(ue),it:g(fe),nl:g(de),none:new Set,pt:g(le)},Se=2,pe=256,M=new Map,y=e=>{const n=e!==void 0&&re(e)?e:"none",i=M.get(n);if(i)return i;const o=we[n],r=a=>{const c=(W(a).match(he)??[]).filter(u=>u.length<=pe);return o.size===0?c:c.filter(u=>!o.has(u))},s={document:r,profile:`${n}-v${String(Se)}`,query:a=>{const c=r(a);return c.filter((u,f)=>c.lastIndexOf(u)===f)}};return M.set(n,s),s},Ee=(e,n)=>e.profile!==n?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},ge=e=>{const n=atob(e),i=Uint8Array.from(n,o=>o.codePointAt(0)??0);return new TextDecoder().decode(i)},_e=()=>new h("BAD_REQUEST","invalid cursor"),j=16,B=8,w=1024,v=(e,n)=>n.query(e),ye=(e,n)=>{if(!n)return{exact:!0,lower:e,upper:e};const i=[...e].at(-1)??"",o=(i.codePointAt(0)??0)+1;if(o>=55296&&o<=57343||o>1114111)return{exact:!0,lower:e,upper:e};const r=e.slice(0,e.length-i.length);return{exact:!1,lower:e,upper:r+String.fromCodePoint(o)}},ze=(e,n,i)=>{const o={eq:(r,s)=>{if(!e.definition.filterFields?.includes(r))throw new h("INTERNAL",`field "${r}" is not a filter field of search index "${e.indexName}" on table "${n}"`);if(e.filters.length>=B)throw new h("BAD_REQUEST",`search index "${e.indexName}" on table "${n}": at most ${String(B)} .eq() filters are supported per search query`);return e.filters.push({field:r,value:s}),o},search:(r,s)=>{const a=e;if(r!==a.definition.field)throw new h("INTERNAL",`search index "${a.indexName}" on table "${n}" indexes "${a.definition.field}", not "${r}"`);const c=v(s,i).length;if(c>j)throw new h("BAD_REQUEST",`search index "${a.indexName}" on table "${n}": at most ${String(j)} search terms are supported (got ${String(c)})`);return a.field=r,a.query=s,a.hasQuery=!0,o}};return o},We=e=>{if(e.length>w)throw new h("BAD_REQUEST",`more than ${String(w)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Qe=e=>Math.min(e.offset+e.numItems+1,w),Te=e=>btoa(`search:${String(e)}`),Ne=e=>{let n;try{n=ge(e)}catch{return}if(!n.startsWith("search:"))return;const i=Number(n.slice(7));return Number.isInteger(i)&&i>=0?i:void 0},Ge=e=>{if(typeof e.endCursor=="string")throw new h("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(e.numItems))throw new h("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(e.numItems)}`);const n=Math.max(0,Math.floor(e.numItems)),i=e.cursor?Ne(e.cursor):0;if(i===void 0)throw _e();if(i+n>=w)throw new h("BAD_REQUEST",`search pagination reaches the ${String(w)}-document limit (offset ${String(i)} + ${String(n)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,w-i-1))} or fewer, or narrow the query or the filters instead`);return{numItems:n,offset:i}},Ve=(e,n)=>{const i=n.offset+n.numItems,o=n.numItems>0&&e.length>i;return{continueCursor:o?Te(i):null,isDone:!o,page:e.slice(n.offset,i)}},Je=e=>{if(e===void 0)return w+1;if(!Number.isFinite(e))return w;const n=Math.max(0,Math.floor(e));if(n>w)throw new h("BAD_REQUEST",`search returns at most ${String(w)} documents (asked for ${String(n)}) — narrow the query or paginate instead`);return n},Ie=(e,n)=>{if(!n.includes("."))return e[n];let i=e;for(const o of n.split(".")){if(i===null||typeof i!="object"||Array.isArray(i))return;i=i[o]}return i},R=(e,n)=>`${e}__fts_${n}`,ve="__text__",l="__id__",T="__token__",L="__n__",Re=1e3,Q=(e,n)=>n.document(e),C=(e,n)=>Ie(e,n),Ae=e=>typeof e=="string"?e:e==null?"":typeof e=="number"||typeof e=="bigint"||typeof e=="boolean"?String(e):JSON.stringify(e)??"",be=(e,n,i)=>e!==void 0&&n!==void 0&&C(e,i.field)===C(n,i.field),Le=(e,n)=>Q(Ae(C(e,n.field)),y(n.language)).slice(0,Re),O=(e,n)=>Le(e,n).join(" "),Ce=(e,n)=>{const i=new Map;for(const o of Q(e,n))i.set(o,(i.get(o)??0)+1);return i},A=async(e,n,i,o)=>{await S(e,n,t`DELETE FROM ${t.identifier(i)} WHERE ${t.identifier(l)} = ${o}`)},b=(e,n)=>e.name==="mysql"?t`${t.identifier(n)}(191)`:e.textPatternOperatorClass===void 0?t`${t.identifier(n)}`:t`${t.identifier(n)} ${t.raw(e.textPatternOperatorClass)}`,k=50,De=(e,n)=>n?t`${t.identifier(T)} LIKE ${`${e}%`}`:t`${t.identifier(T)} = ${e}`,G=(e,n)=>{const i=n.filters.map(o=>t`m.${F(o.field)} = ${te(o.value)}`);return e.softDeleteMode&&i.push(t`m.${F(e.softDeleteMode.field)} IS NULL`),i},V=async(e,n,i,o,r,s,a)=>{const c=G(i,r);let u=t`SELECT m.* FROM (${a}) s JOIN ${t.identifier(o)} m ON m.${t.identifier("id")} = s.${t.identifier(l)}`;return c.length>0&&(u=t`${u} WHERE ${t.join(c,t` AND `)}`),u=t`${u} ORDER BY s.${t.identifier("__score__")} DESC, m.${t.identifier("_creationTime")} DESC, m.${t.identifier("id")} ASC LIMIT ${t.raw(String(s))}`,z(i,await D(e,n,u))},Oe=async(e,n,i,o,r,s)=>{const a=v(r.query,y(r.definition.language));if(a.length===0)return[];const c=R(o,r.indexName),u=a.length-1,f=a.map((d,_)=>De(d,_===u)),m=t.join(f,t` OR `),$=f.map(d=>t`SUM(CASE WHEN ${d} THEN ${t.identifier(L)} ELSE 0 END)`),E=t.join($.map(d=>t`${d} > 0`),t` AND `),p=t`SELECT ${t.identifier(l)}, ${t.join($,t` + `)} AS ${t.identifier("__score__")} FROM ${t.identifier(c)} WHERE ${m} GROUP BY ${t.identifier(l)} HAVING ${E}`;return V(e,n,i,o,r,s,p)},qe=async(e,n,i,o,r,s)=>{const a=v(r.query,y(r.definition.language));if(a.length===0)return[];const c=R(o,r.indexName),u=`${c}__vocab`,f=a.length-1,m=a.map((p,d)=>{const _=ye(p,d===f),K=_.exact?t`${t.identifier("term")} = ${_.lower}`:t`${t.identifier("term")} >= ${_.lower} AND ${t.identifier("term")} < ${_.upper}`;return t`SELECT ${t.identifier("doc")}, ${t.raw(String(d))} AS ${t.identifier("__term__")}, COUNT(*) AS ${t.identifier("__n__")} FROM ${t.identifier(u)} WHERE ${K} GROUP BY ${t.identifier("doc")}`}),$=a.map((p,d)=>t`SUM(CASE WHEN u.${t.identifier("__term__")} = ${t.raw(String(d))} THEN u.${t.identifier("__n__")} ELSE 0 END)`),E=t`SELECT f.${t.identifier(l)} AS ${t.identifier(l)}, ${t.join($,t` + `)} AS ${t.identifier("__score__")} FROM (${ee(m)}) u JOIN ${t.identifier(c)} f ON f.rowid = u.${t.identifier("doc")} GROUP BY f.${t.identifier(l)} HAVING ${t.join($.map(p=>t`${p} > 0`),t` AND `)}`;return V(e,n,i,o,r,s,E)},xe=async(e,n,i,o,r,s)=>{const a=n.nativeTextSearch,c=v(r.query,y(r.definition.language));if(!a||c.length===0)return[];const u=R(o,r.indexName),f=[a.matches(u,c),...G(i,r)],m=t`SELECT m.* FROM ${t.identifier(u)} JOIN ${t.identifier(o)} m ON m.${t.identifier("id")} = ${t.identifier(u)}.${t.identifier(l)} WHERE ${t.join(f,t` AND `)} ORDER BY ${a.rank(u,c)} DESC, m.${t.identifier("_creationTime")} DESC, m.${t.identifier("id")} ASC LIMIT ${t.raw(String(s))}`;return z(i,await D(e,n,m))},Ue={ensureCompanion:async(e,n,i)=>{const{integer:o,key:r}=n.companionTypes;await S(e,n,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier(T)} ${t.raw(r)} NOT NULL, ${t.identifier(l)} ${t.raw(r)} NOT NULL, ${t.identifier(L)} ${t.raw(o)} NOT NULL)`),await U(e,n,{columns:t`${b(n,T)}, ${b(n,l)}`,name:`${i}__btree`,table:i,unique:!1}),await U(e,n,{columns:b(n,l),name:`${i}__by_id`,table:i,unique:!1})},indexDocument:async(e,n,i,o,r,s)=>{await A(e,n,i,o);const a=[...Ce(O(r,s),y(s.language))],c=t.join([T,l,L].map(f=>t.identifier(f)),t`, `),u=[];for(let f=0;f<a.length;f+=k){const m=t.join(a.slice(f,f+k).map(([$,E])=>t`(${$}, ${o}, ${E})`),t`, `);u.push(t`INSERT INTO ${t.identifier(i)} (${c}) VALUES ${m}`)}await ne(e,n,u)},name:"inverted",runSearch:Oe},Fe={ensureCompanion:async(e,n,i)=>{await S(e,n,t`CREATE VIRTUAL TABLE IF NOT EXISTS ${t.identifier(i)} USING fts5(${t.identifier(ve)}, ${t.identifier(l)} UNINDEXED)`),await S(e,n,t`CREATE VIRTUAL TABLE IF NOT EXISTS ${t.identifier(`${i}__vocab`)} USING fts5vocab(${t.identifier(i)}, ${t.raw("instance")})`)},indexDocument:async(e,n,i,o,r,s)=>{await A(e,n,i,o),await S(e,n,t`INSERT INTO ${t.identifier(i)} (${t.identifier("__text__")}, ${t.identifier(l)}) VALUES (${O(r,s)}, ${o})`)},name:"fts5",runSearch:qe},Me={ensureCompanion:async(e,n,i)=>{const o=n.nativeTextSearch;if(o){await S(e,n,o.createCompanion(i,n.companionTypes.key));for(const r of o.createIndexes(i))await S(e,n,r)}},indexDocument:async(e,n,i,o,r,s)=>{const a=n.nativeTextSearch;a&&(await A(e,n,i,o),await S(e,n,a.indexDocument(i,o,O(r,s))))},name:"native",runSearch:xe},N=(e,n)=>e.strategy==="native"&&n.nativeTextSearch!==void 0?Me:n.supportsFts5?Fe:Ue,J=(e,n)=>`${y(e.language).profile}/${N(e,n).name}`,q=function*(e){for(const[n,i]of Object.entries(e.tables)){const o=i.searchIndexes;if(!(i.shardMode!==void 0&&i.shardMode.kind!=="global"||!o))for(const r of o)yield[n,i,r]}},x=(e,n)=>R(e,n.name),Xe=async(e,n,i,o,r,s)=>N(r.definition,n).runSearch(e,n,i,o,r,s),H=200,X=async(e,n,i,o,r)=>{const s=x(o,r),a=N(r,n),c=J(r,n),u=Ee(await P(e,n,s),c);if(u.finished)return!0;if(u.wipe&&(await S(e,n,t`DELETE FROM ${t.identifier(s)}`),await I(e,n,s,void 0,!1,c)),(await D(e,n,n.tableExists(o))).length===0)return await I(e,n,s,void 0,!0,c),!0;let m=0,$=u.cursor;await ie(e,n,i,o,async p=>{m+=1;const d=p._id;typeof d=="string"&&($=d,await a.indexDocument(e,n,s,d,p,r))},{after:u.cursor,limit:H});const E=m<H;return await I(e,n,s,$,E,c),E},Y=async(e,n,i)=>{await Z(e,i);for(const[o,,r]of q(n)){const s=x(o,r),a=J(r,i),c=await P(e,i,s);c.profile!==void 0&&c.profile!==a&&(await S(e,i,t`DROP TABLE IF EXISTS ${t.identifier(s)}`),await I(e,i,s,void 0,!1,a)),await N(r,i).ensureCompanion(e,i,s)}},Ye=async(e,n,i)=>{await Y(e,n,i);for(const[o,r,s]of q(n))s.staged||await X(e,i,r,o,s)},Ke=async(e,n,i)=>{await Y(e,n,i);for(const[o,r,s]of q(n)){let a=!1;for(;!a;)a=await X(e,i,r,o,s)}},Ze=e=>{const{dialect:n,exec:i,schema:o}=e;return async(r,s,a,c)=>{const u=o.tables[r]?.searchIndexes;if(!(!u||u.length===0))for(const f of u){if(be(c,a,f))continue;const m=x(r,f);if(a){await N(f,n).indexDocument(i,n,m,s,a,f);continue}await A(i,n,m,s)}}};export{ze as A,Ge as C,Ve as R,Je as T,Xe as a,Qe as b,Ze as c,Ke as d,y as q,Ye as r,We as x};
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{migrateSearchState as Z,readSearchBackfillState as P,writeSearchBackfillState as I}from"./SEARCH_STATE_TABLE-DxsFPib5.mjs";import{LunoraError as h}from"@lunora/errors";import{unionAll as ee}from"@lunora/shard-engine";import{queryRun as S,decodeRows as z,queryAll as D,queryBatch as ne,createIndexIfNotExists as U,columnRefSql as F,serializeColumnValue as te,forEachRowPaged as ie}from"./decodeGlobalRow-DeKnMoxP.mjs";const oe=["de","en","es","fr","it","nl","none","pt"],re=e=>oe.includes(e),se="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",ae="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",ce="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",ue="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",fe="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",de="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",le="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",me=/[\u0300-\u036F]/gu,$e=/[\u0080-\u{10FFFF}]/u,he=/[\p{L}\p{N}]+/gu,W=e=>$e.test(e)?e.normalize("NFD").replaceAll(me,"").normalize("NFC").toLowerCase():e.toLowerCase(),g=e=>new Set(W(e).split(" ")),we={de:g(ae),en:g(se),es:g(ce),fr:g(ue),it:g(fe),nl:g(de),none:new Set,pt:g(le)},Se=2,pe=256,M=new Map,y=e=>{const n=e!==void 0&&re(e)?e:"none",i=M.get(n);if(i)return i;const o=we[n],r=a=>{const c=(W(a).match(he)??[]).filter(u=>u.length<=pe);return o.size===0?c:c.filter(u=>!o.has(u))},s={document:r,profile:`${n}-v${String(Se)}`,query:a=>{const c=r(a);return c.filter((u,f)=>c.lastIndexOf(u)===f)}};return M.set(n,s),s},Ee=(e,n)=>e.profile!==n?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},ge=e=>{const n=atob(e),i=Uint8Array.from(n,o=>o.codePointAt(0)??0);return new TextDecoder().decode(i)},_e=()=>new h("BAD_REQUEST","invalid cursor"),j=16,B=8,w=1024,v=(e,n)=>n.query(e),ye=(e,n)=>{if(!n)return{exact:!0,lower:e,upper:e};const i=[...e].at(-1)??"",o=(i.codePointAt(0)??0)+1;if(o>=55296&&o<=57343||o>1114111)return{exact:!0,lower:e,upper:e};const r=e.slice(0,e.length-i.length);return{exact:!1,lower:e,upper:r+String.fromCodePoint(o)}},ze=(e,n,i)=>{const o={eq:(r,s)=>{if(!e.definition.filterFields?.includes(r))throw new h("INTERNAL",`field "${r}" is not a filter field of search index "${e.indexName}" on table "${n}"`);if(e.filters.length>=B)throw new h("BAD_REQUEST",`search index "${e.indexName}" on table "${n}": at most ${String(B)} .eq() filters are supported per search query`);return e.filters.push({field:r,value:s}),o},search:(r,s)=>{const a=e;if(r!==a.definition.field)throw new h("INTERNAL",`search index "${a.indexName}" on table "${n}" indexes "${a.definition.field}", not "${r}"`);const c=v(s,i).length;if(c>j)throw new h("BAD_REQUEST",`search index "${a.indexName}" on table "${n}": at most ${String(j)} search terms are supported (got ${String(c)})`);return a.field=r,a.query=s,a.hasQuery=!0,o}};return o},We=e=>{if(e.length>w)throw new h("BAD_REQUEST",`more than ${String(w)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Qe=e=>Math.min(e.offset+e.numItems+1,w),Te=e=>btoa(`search:${String(e)}`),Ne=e=>{let n;try{n=ge(e)}catch{return}if(!n.startsWith("search:"))return;const i=Number(n.slice(7));return Number.isInteger(i)&&i>=0?i:void 0},Ge=e=>{if(typeof e.endCursor=="string")throw new h("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(e.numItems))throw new h("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(e.numItems)}`);const n=Math.max(0,Math.floor(e.numItems)),i=e.cursor?Ne(e.cursor):0;if(i===void 0)throw _e();if(i+n>=w)throw new h("BAD_REQUEST",`search pagination reaches the ${String(w)}-document limit (offset ${String(i)} + ${String(n)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,w-i-1))} or fewer, or narrow the query or the filters instead`);return{numItems:n,offset:i}},Ve=(e,n)=>{const i=n.offset+n.numItems,o=n.numItems>0&&e.length>i;return{continueCursor:o?Te(i):null,isDone:!o,page:e.slice(n.offset,i)}},Je=e=>{if(e===void 0)return w+1;if(!Number.isFinite(e))return w;const n=Math.max(0,Math.floor(e));if(n>w)throw new h("BAD_REQUEST",`search returns at most ${String(w)} documents (asked for ${String(n)}) — narrow the query or paginate instead`);return n},Ie=(e,n)=>{if(!n.includes("."))return e[n];let i=e;for(const o of n.split(".")){if(i===null||typeof i!="object"||Array.isArray(i))return;i=i[o]}return i},R=(e,n)=>`${e}__fts_${n}`,ve="__text__",l="__id__",T="__token__",L="__n__",Re=1e3,Q=(e,n)=>n.document(e),C=(e,n)=>Ie(e,n),Ae=e=>typeof e=="string"?e:e==null?"":typeof e=="number"||typeof e=="bigint"||typeof e=="boolean"?String(e):JSON.stringify(e)??"",be=(e,n,i)=>e!==void 0&&n!==void 0&&C(e,i.field)===C(n,i.field),Le=(e,n)=>Q(Ae(C(e,n.field)),y(n.language)).slice(0,Re),O=(e,n)=>Le(e,n).join(" "),Ce=(e,n)=>{const i=new Map;for(const o of Q(e,n))i.set(o,(i.get(o)??0)+1);return i},A=async(e,n,i,o)=>{await S(e,n,t`DELETE FROM ${t.identifier(i)} WHERE ${t.identifier(l)} = ${o}`)},b=(e,n)=>e.name==="mysql"?t`${t.identifier(n)}(191)`:e.textPatternOperatorClass===void 0?t`${t.identifier(n)}`:t`${t.identifier(n)} ${t.raw(e.textPatternOperatorClass)}`,k=50,De=(e,n)=>n?t`${t.identifier(T)} LIKE ${`${e}%`}`:t`${t.identifier(T)} = ${e}`,G=(e,n)=>{const i=n.filters.map(o=>t`m.${F(o.field)} = ${te(o.value)}`);return e.softDeleteMode&&i.push(t`m.${F(e.softDeleteMode.field)} IS NULL`),i},V=async(e,n,i,o,r,s,a)=>{const c=G(i,r);let u=t`SELECT m.* FROM (${a}) s JOIN ${t.identifier(o)} m ON m.${t.identifier("id")} = s.${t.identifier(l)}`;return c.length>0&&(u=t`${u} WHERE ${t.join(c,t` AND `)}`),u=t`${u} ORDER BY s.${t.identifier("__score__")} DESC, m.${t.identifier("_creationTime")} DESC, m.${t.identifier("id")} ASC LIMIT ${t.raw(String(s))}`,z(i,await D(e,n,u))},Oe=async(e,n,i,o,r,s)=>{const a=v(r.query,y(r.definition.language));if(a.length===0)return[];const c=R(o,r.indexName),u=a.length-1,f=a.map((d,_)=>De(d,_===u)),m=t.join(f,t` OR `),$=f.map(d=>t`SUM(CASE WHEN ${d} THEN ${t.identifier(L)} ELSE 0 END)`),E=t.join($.map(d=>t`${d} > 0`),t` AND `),p=t`SELECT ${t.identifier(l)}, ${t.join($,t` + `)} AS ${t.identifier("__score__")} FROM ${t.identifier(c)} WHERE ${m} GROUP BY ${t.identifier(l)} HAVING ${E}`;return V(e,n,i,o,r,s,p)},qe=async(e,n,i,o,r,s)=>{const a=v(r.query,y(r.definition.language));if(a.length===0)return[];const c=R(o,r.indexName),u=`${c}__vocab`,f=a.length-1,m=a.map((p,d)=>{const _=ye(p,d===f),K=_.exact?t`${t.identifier("term")} = ${_.lower}`:t`${t.identifier("term")} >= ${_.lower} AND ${t.identifier("term")} < ${_.upper}`;return t`SELECT ${t.identifier("doc")}, ${t.raw(String(d))} AS ${t.identifier("__term__")}, COUNT(*) AS ${t.identifier("__n__")} FROM ${t.identifier(u)} WHERE ${K} GROUP BY ${t.identifier("doc")}`}),$=a.map((p,d)=>t`SUM(CASE WHEN u.${t.identifier("__term__")} = ${t.raw(String(d))} THEN u.${t.identifier("__n__")} ELSE 0 END)`),E=t`SELECT f.${t.identifier(l)} AS ${t.identifier(l)}, ${t.join($,t` + `)} AS ${t.identifier("__score__")} FROM (${ee(m)}) u JOIN ${t.identifier(c)} f ON f.rowid = u.${t.identifier("doc")} GROUP BY f.${t.identifier(l)} HAVING ${t.join($.map(p=>t`${p} > 0`),t` AND `)}`;return V(e,n,i,o,r,s,E)},xe=async(e,n,i,o,r,s)=>{const a=n.nativeTextSearch,c=v(r.query,y(r.definition.language));if(!a||c.length===0)return[];const u=R(o,r.indexName),f=[a.matches(u,c),...G(i,r)],m=t`SELECT m.* FROM ${t.identifier(u)} JOIN ${t.identifier(o)} m ON m.${t.identifier("id")} = ${t.identifier(u)}.${t.identifier(l)} WHERE ${t.join(f,t` AND `)} ORDER BY ${a.rank(u,c)} DESC, m.${t.identifier("_creationTime")} DESC, m.${t.identifier("id")} ASC LIMIT ${t.raw(String(s))}`;return z(i,await D(e,n,m))},Ue={ensureCompanion:async(e,n,i)=>{const{integer:o,key:r}=n.companionTypes;await S(e,n,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier(T)} ${t.raw(r)} NOT NULL, ${t.identifier(l)} ${t.raw(r)} NOT NULL, ${t.identifier(L)} ${t.raw(o)} NOT NULL)`),await U(e,n,{columns:t`${b(n,T)}, ${b(n,l)}`,name:`${i}__btree`,table:i,unique:!1}),await U(e,n,{columns:b(n,l),name:`${i}__by_id`,table:i,unique:!1})},indexDocument:async(e,n,i,o,r,s)=>{await A(e,n,i,o);const a=[...Ce(O(r,s),y(s.language))],c=t.join([T,l,L].map(f=>t.identifier(f)),t`, `),u=[];for(let f=0;f<a.length;f+=k){const m=t.join(a.slice(f,f+k).map(([$,E])=>t`(${$}, ${o}, ${E})`),t`, `);u.push(t`INSERT INTO ${t.identifier(i)} (${c}) VALUES ${m}`)}await ne(e,n,u)},name:"inverted",runSearch:Oe},Fe={ensureCompanion:async(e,n,i)=>{await S(e,n,t`CREATE VIRTUAL TABLE IF NOT EXISTS ${t.identifier(i)} USING fts5(${t.identifier(ve)}, ${t.identifier(l)} UNINDEXED)`),await S(e,n,t`CREATE VIRTUAL TABLE IF NOT EXISTS ${t.identifier(`${i}__vocab`)} USING fts5vocab(${t.identifier(i)}, ${t.raw("instance")})`)},indexDocument:async(e,n,i,o,r,s)=>{await A(e,n,i,o),await S(e,n,t`INSERT INTO ${t.identifier(i)} (${t.identifier("__text__")}, ${t.identifier(l)}) VALUES (${O(r,s)}, ${o})`)},name:"fts5",runSearch:qe},Me={ensureCompanion:async(e,n,i)=>{const o=n.nativeTextSearch;if(o){await S(e,n,o.createCompanion(i,n.companionTypes.key));for(const r of o.createIndexes(i))await S(e,n,r)}},indexDocument:async(e,n,i,o,r,s)=>{const a=n.nativeTextSearch;a&&(await A(e,n,i,o),await S(e,n,a.indexDocument(i,o,O(r,s))))},name:"native",runSearch:xe},N=(e,n)=>e.strategy==="native"&&n.nativeTextSearch!==void 0?Me:n.supportsFts5?Fe:Ue,J=(e,n)=>`${y(e.language).profile}/${N(e,n).name}`,q=function*(e){for(const[n,i]of Object.entries(e.tables)){const o=i.searchIndexes;if(!(i.shardMode!==void 0&&i.shardMode.kind!=="global"||!o))for(const r of o)yield[n,i,r]}},x=(e,n)=>R(e,n.name),Xe=async(e,n,i,o,r,s)=>N(r.definition,n).runSearch(e,n,i,o,r,s),H=200,X=async(e,n,i,o,r)=>{const s=x(o,r),a=N(r,n),c=J(r,n),u=Ee(await P(e,n,s),c);if(u.finished)return!0;if(u.wipe&&(await S(e,n,t`DELETE FROM ${t.identifier(s)}`),await I(e,n,s,void 0,!1,c)),(await D(e,n,n.tableExists(o))).length===0)return await I(e,n,s,void 0,!0,c),!0;let m=0,$=u.cursor;await ie(e,n,i,o,async p=>{m+=1;const d=p._id;typeof d=="string"&&($=d,await a.indexDocument(e,n,s,d,p,r))},{after:u.cursor,limit:H});const E=m<H;return await I(e,n,s,$,E,c),E},Y=async(e,n,i)=>{await Z(e,i);for(const[o,,r]of q(n)){const s=x(o,r),a=J(r,i),c=await P(e,i,s);c.profile!==void 0&&c.profile!==a&&(await S(e,i,t`DROP TABLE IF EXISTS ${t.identifier(s)}`),await I(e,i,s,void 0,!1,a)),await N(r,i).ensureCompanion(e,i,s)}},Ye=async(e,n,i)=>{await Y(e,n,i);for(const[o,r,s]of q(n))s.staged||await X(e,i,r,o,s)},Ke=async(e,n,i)=>{await Y(e,n,i);for(const[o,r,s]of q(n)){let a=!1;for(;!a;)a=await X(e,i,r,o,s)}},Ze=e=>{const{dialect:n,exec:i,schema:o}=e;return async(r,s,a,c)=>{const u=o.tables[r]?.searchIndexes;if(!(!u||u.length===0))for(const f of u){if(be(c,a,f))continue;const m=x(r,f);if(a){await N(f,n).indexDocument(i,n,m,s,a,f);continue}await A(i,n,m,s)}}};export{ze as A,Ge as C,Ve as R,Je as T,Xe as a,Qe as b,Ze as c,Ke as d,y as q,Ye as r,We as x};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{renderSql as u}from"@lunora/shard-engine";import{sql as i}from"drizzle-orm";import{s as N,a as p,e as y}from"./value-codec-CwTLrqfU.mjs";const C=n=>n==="_id"||n==="id"?"id":n,O=n=>i`${i.identifier(C(n))}`,_=(n,e,t)=>{const{params:o,sql:r}=u(e.name,t);return n.all(r,o)},d=(n,e,t)=>{const{params:o,sql:r}=u(e.name,t);return n.run(r,o)},k=async(n,e,t)=>{if(t.length!==0){if(!n.batch){for(const o of t)await d(n,e,o);return}await n.batch(t.map(o=>u(e.name,o)))}},v=async(n,e,t)=>{const o=t.unique?i`UNIQUE `:i``;if(e.name==="mysql"){try{await d(n,e,i`CREATE ${o}INDEX ${i.identifier(t.name)} ON ${i.identifier(t.table)} (${t.columns})`)}catch(r){const s=r;if(s.errno!==1061&&s.code!=="ER_DUP_KEYNAME"&&s.code!==1061)throw r}return}await d(n,e,i`CREATE ${o}INDEX IF NOT EXISTS ${i.identifier(t.name)} ON ${i.identifier(t.table)} (${t.columns})`)},D=N,h=n=>n?._meta?.column?.notNull===!1,g=n=>{if(n.kind!=="optional"||h(n))return!1;const e=n._meta?.inner;return!h(e)},w=new WeakMap,S=n=>{let e=w.get(n);return e===void 0&&(e=Object.entries(n.shape).map(([t,o])=>[t,y(o),g(o)]),w.set(n,e)),e},T=(n,e)=>{const t={};for(const[o,r,s]of S(n)){const a=e[o];a===void 0||s&&a===null||(t[o]=p(a,r))}return t._id=e.id,t._creationTime=e._creationTime,t},R=(n,e)=>e?T(n,e):null,K=(n,e)=>{const t=[];for(const o of e){const r=R(n,o);r&&t.push(r)}return t},$=500,B=async(n,e,t,o,r,s={})=>{let a=s.after,c=s.limit,f=!0;for(;f&&(c===void 0||c>0);){const m=c===void 0?$:Math.min($,c),q=a===void 0?i``:i` WHERE ${i.identifier("id")} > ${a}`,l=await _(n,e,i`SELECT * FROM ${i.identifier(o)}${q} ORDER BY ${i.identifier("id")} ASC LIMIT ${i.raw(String(m))}`);for(const I of l){const E=R(t,I);E&&await r(E)}a=l.at(-1)?.id,f=l.length===m,c=c===void 0?void 0:c-l.length}};export{$ as BACKFILL_BATCH_SIZE,O as columnRefSql,v as createIndexIfNotExists,T as decodeGlobalRow,R as decodeRow,K as decodeRows,B as forEachRowPaged,C as physicalColumn,_ as queryAll,k as queryBatch,d 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.104",
|
|
4
4
|
"description": "Internal dialect-parameterized SQL store core for Lunora .global() backends (D1, PlanetScale)",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -50,8 +50,8 @@
|
|
|
50
50
|
"access": "public"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
54
|
-
"@lunora/shard-engine": "1.0.0-alpha.
|
|
53
|
+
"@lunora/errors": "1.0.0-alpha.28",
|
|
54
|
+
"@lunora/shard-engine": "1.0.0-alpha.51",
|
|
55
55
|
"drizzle-orm": "^0.45.2"
|
|
56
56
|
},
|
|
57
57
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as S,c as s,a as i,r as l}from"./ctx-db-search-BiMTuJzw.mjs";import"./SEARCH_STATE_TABLE-B5a5xBwB.mjs";import"./decodeGlobalRow-C8O2hy0d.mjs";export{S as backfillSqlSearchIndexes,s as createSearchSync,i as runSqlSearch,l as runSqlSearchMigrations};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{c as Ct,r as At,A as Lt,q as Nt,C as kt,R as Mt,a as Dt,T as qt,x as Ot,b as Ft}from"./ctx-db-search-BiMTuJzw.mjs";import{d as oi}from"./ctx-db-search-BiMTuJzw.mjs";import{literalInList as Bt,throwingScheduler as xt,CDC_LOG_TABLE as G,cursorBelowRetainedFloor as Wt,cdcTrimmedError as Ut,aggregateTableName as J,rankTableName as ne,assertNoExplicitUndefined as Ze,hasTrigger as Pt,runRowValidators as De,assertFlatPredicate as et,mergeWhere as O,sortColumnName as Q,resolveRankPartition as tt,encodePartitionKey as Ce,resolveRankSeekTuple as jt,RANK_TIEBREAK as Ee,CountRlsUnsupportedError as nt,normalizeIdStructurally as Kt,assertValidClientId as Ht,aggregateSqlFunction as we,softDeleteScope as _e,compileWhereSql as $e,normalizeOrderKeys as Gt,buildSeekWhere as Vt,decodeCursor as Yt,resolveRelationPredicates as it,resolveWith as ot,relationHooks as rt,applySelect as st,encodeCursor as Xt,NotFoundError as zt,applyOnDelete as Jt,ConflictError as he,normalizeCountArgument as Qt,selectIndexForCount as Zt,encodeAggregateKey as z,selectIndexForAggregate as en,readAggregateValue as qe,runTriggers as tn,matchesRankStaticWhere as at,CURSOR_PREFIX as nn,selectIndexForGroupBy as on,tiebreakDirectionFor as rn,fanOutScalarCounts as sn,matchesStaticWhere as Oe,foldAggregateTally as an,coerceAggregateNumber as Fe,CDC_LOG_TABLE_SEQ_INDEX as cn,NotUniqueError as dn}from"@lunora/shard-engine";import{sql as e}from"drizzle-orm";import{d as _t,e as Le,n as ln,b as un}from"./value-codec-CwTLrqfU.mjs";import{migrateSearchState as fn}from"./SEARCH_STATE_TABLE-B5a5xBwB.mjs";import{queryAll as I,queryRun as A,createIndexIfNotExists as Ae,decodeRow as ie,serializeColumnValue as H,columnRefSql as F,decodeRows as wn,forEachRowPaged as ct,queryBatch as dt}from"./decodeGlobalRow-C8O2hy0d.mjs";import{decodeGlobalRow as si}from"./decodeGlobalRow-C8O2hy0d.mjs";const _n=(s,l)=>{if(s.size<l)return;const u=s.keys().next().value;u!==void 0&&s.delete(u)},lt=50,$n=(s,l={})=>{const u=l.maxBatch??lt,i=Number.isInteger(u)&&u>0?u:lt,h=new Map;let d=!1;const c=async(R,b)=>{const v=[...b.keys()];for(let L=0;L<v.length;L+=i){const M=v.slice(L,L+i);try{const x=await s(R,M);for(const V of M){const Y=x.get(V);for(const X of b.get(V)??[])X.resolve(Y)}}catch(x){for(const V of M)for(const Y of b.get(V)??[])Y.reject(x)}}},m=()=>{d=!1;const R=[...h.entries()];h.clear();for(const[b,v]of R)c(b,v).catch(()=>{})};return{async load(R,b){return new Promise((v,L)=>{let M=h.get(R);M||(M=new Map,h.set(R,M));const x=M.get(b);x?x.push({reject:L,resolve:v}):M.set(b,[{reject:L,resolve:v}]),d||(d=!0,queueMicrotask(m))})}}},hn=new Set(["_id","id"]),We=(s,l,u)=>s==="postgres"?e`${l} IS NOT DISTINCT FROM ${u}`:s==="mysql"?e`${l} <=> ${u}`:e`${l} IS ${u}`,En=(s,l)=>s.name!=="postgres"||l.nullable!==!0?"":l.direction==="desc"?" NULLS LAST":" NULLS FIRST",yn=(s,l)=>{const u=s.map(i=>e`${F(i.field)} ${e.raw(`${i.direction==="desc"?"DESC":"ASC"}${En(l,i)}`)}`);if(!s.some(i=>hn.has(i.field))){const i=rn(s);u.push(e`${F("id")} ${e.raw(i==="desc"?"DESC":"ASC")}`)}return e.join(u,e`, `)},ut=50,Ue=s=>{const l=[];for(const[u,i]of Object.entries(s.shape)){const h=i._meta?.column;h&&l.push([u,h])}return l},pn=(s,l,u)=>{const i={...l};for(const[h,d]of Ue(s)){if(d.serverDefault){i[h]=d.serverDefault({auth:u});continue}i[h]===void 0&&(d.defaultFn?i[h]=d.defaultFn():"defaultValue"in d&&(i[h]=d.defaultValue))}return i},ft=(s,l,u,i)=>{for(const[h,d]of Ue(s)){if(d.serverDefault){h in l&&(u[h]=d.serverDefault({auth:i}));continue}d.onUpdateFn&&!(h in l)&&(u[h]=d.onUpdateFn())}},Rn=128,Tn=()=>{const s=new Map;return{delete:l=>{s.delete(l)},get:l=>{const u=s.get(l);if(u!==void 0)return s.delete(l),s.set(l,u),u},set:(l,u)=>{s.has(l)?s.delete(l):_n(s,Rn),s.set(l,u)}}},mn=async(s,l,u,i,h)=>{const d=h.get(i);if(d!==void 0)return d;const c=Object.entries(u.tables).filter(([,R])=>R.shardMode===void 0||R.shardMode.kind==="global").map(([R])=>R),m=await Promise.all(c.map(async R=>({found:(await I(s,l,e`SELECT 1 FROM ${e.identifier(R)} WHERE ${e.identifier("id")} = ${i} LIMIT 1`)).length>0,tableName:R})));for(const R of m)if(R.found)return h.set(i,R.tableName),R.tableName},oe=s=>s==null?null:Number(s),Sn=(s,l)=>l.map(u=>{const i={};for(const h of s)i[h]=u[h]??null;return{key:i,value:oe(u.value)}}),gn=(s,l,u)=>[...s.partitionBy??[],...s.sortBy.map(h=>h.field),...s.where?Object.keys(s.where):[]].every(h=>l[h]===u[h]),$t=s=>s.length===1?s[0]:e`(${e.join(s,e` AND `)})`,te=s=>e.join(s.map(l=>e`${e.identifier(l)}`),e`, `),re=s=>e.join(s.map(l=>e`${l}`),e`, `),vn=(s,l,u,i,h)=>{const d=[];for(let c=0;c<u.length+1;c+=1){const m=u.slice(0,c).map(v=>We(s,e`${e.identifier(v)}`,i[v])),R=u[c],b=l.sortBy[c];c<u.length&&R!==void 0&&b!==void 0?m.push(e`${e.identifier(R)} ${e.raw(b.direction==="desc"?">":"<")} ${i[R]}`):m.push(e`${e.identifier(Ee)} < ${h}`),d.push($t(m))}return d.length>0?e.join(d,e` OR `):void 0},bn=(s,l,u)=>{if(u.length!==l.length)return;const i=[];for(const[h,d]of l.entries()){const c=[];for(let m=0;m<h;m+=1){const R=l[m];R!==void 0&&c.push(We(s,e`${e.identifier(R.column)}`,u[m]))}c.push(e`${e.identifier(d.column)} ${e.raw(d.direction==="desc"?"<":">")} ${u[h]}`),i.push($t(c))}return e`(${e.join(i,e` OR `)})`},In=(s,l)=>{if(s.sortBy.length===0)throw new g("INTERNAL",`rankIndex "${s.name}" requires at least one "sortBy" column for stable pagination`);const u=[{column:"__partition__",direction:"asc"}];for(const[i,h]of s.sortBy.entries())u.push({column:l[i]??Q(i),direction:h.direction});return u.push({column:Ee,direction:"asc"}),u},Cn=async(s,l,u,i,h)=>{const c=[];for(let v=0;v<h.length;v+=50)c.push(h.slice(v,v+50));const m=await Promise.all(c.map(async v=>I(s,l,e`SELECT * FROM ${e.identifier(i)} WHERE ${e.identifier("id")} IN (${re(v)})`))),R=new Map;for(const v of m)for(const L of v)R.set(L.id,L);const b=[];for(const v of h){const L=ie(u,R.get(v));L&&b.push(L)}return b},An=s=>{const l=JSON.stringify(s),u=new TextEncoder().encode(l);let i="";for(const h of u)i+=String.fromCodePoint(h);return nn+btoa(i)},Ln=(s,l)=>l.columnType(Le(s)),Nn=(s,l,u)=>{const i=[];for(const[c,m]of Object.entries(l.shape)){if(!m._meta?.column)continue;const R=m._meta.column.notNull&&m.kind!=="optional"?" NOT NULL":"";i.push(e`${e.identifier(c)} ${e.raw(`${Ln(m,u)}${R}`)}`)}const h=u.frameworkColumns().map(c=>e`${e.identifier(c.name)} ${e.raw(c.type)}`),d=h.length+i.length;if(u.maxTableColumns!==void 0&&d>u.maxTableColumns)throw new g("VALIDATION_ERROR",`@lunora/sql-store: global table "${s}" needs ${String(d)} columns, over this engine's ${String(u.maxTableColumns)}-column limit — split the table, or move the extra fields into one object field`);return e.join([...h,...i],e`, `)},kn=async(s,l,u,i)=>{const h=d=>{const c=F(d),m=u.shape[d],R=m&&i.indexKeyPrefix?i.indexKeyPrefix(Le(m)):void 0;return R===void 0?c:e`${c}(${e.raw(String(R))})`};for(const d of u.indexes){const c=e.join(d.fields.map(m=>h(m)),e`, `);await Ae(s,i,{columns:c,name:`${l}_${d.name}`,table:l,unique:d.unique??!1})}for(const[d,c]of Ue(u))c.unique&&await Ae(s,i,{columns:h(d),name:`${l}_unique_${d}`,table:l,unique:!0})},Mn=async(s,l,u)=>{for(const[i,h]of Object.entries(l.tables)){if(h.shardMode?.kind!=="global")continue;const d=Nn(i,h,u);await A(s,u,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (${d})`),await kn(s,i,h,u)}},Dn=async(s,l,u)=>{const{integer:i,key:h,real:d}=u.companionTypes;for(const[c,m]of Object.entries(l.tables)){const R=m.aggregateIndexes;if(!(!R||R.length===0))for(const b of R){const v=J(c,b.name);await A(s,u,e`CREATE TABLE IF NOT EXISTS ${e.identifier(v)} (${e.identifier("__key__")} ${e.raw(h)} PRIMARY KEY, ${e.identifier("__value__")} ${e.raw(d)}, ${e.identifier("__count__")} ${e.raw(i)} NOT NULL DEFAULT 0)`),u.name==="sqlite"&&((await I(s,u,e`PRAGMA table_info(${e.identifier(v)})`)).some(M=>M.name==="__count__")||await A(s,u,e`ALTER TABLE ${e.identifier(v)} ADD COLUMN ${e.identifier("__count__")} ${e.raw(i)} NOT NULL DEFAULT 0`))}}},Be=(s,l,u,i)=>{const h=s.name==="mysql"&&i?e`${e.identifier(l)}(191)`:e`${e.identifier(l)}`;return e`${h} ${e.raw(u)}`},qn=(s,l,u)=>{const i=[Be(s,"__partition__","ASC",!0)];for(const[h,d]of l.sortBy.entries()){const c=u.shape[d.field],m=c!==void 0&&s.indexKeyPrefix?.(Le(c))!==void 0;i.push(Be(s,Q(h),d.direction==="desc"?"DESC":"ASC",m))}return i.push(Be(s,"__id__","ASC",!0)),i},On=(s,l,u)=>l.sortBy.map((i,h)=>{const d=u.shape[i.field],c=s.columnType(d?Le(d):void 0);return e`${e.identifier(Q(h))} ${e.raw(c)}`}),Fn=async(s,l,u)=>{const{key:i}=u.companionTypes;for(const[h,d]of Object.entries(l.tables)){const c=d.rankIndexes;if(!(!c||c.length===0))for(const m of c){const R=ne(h,m.name),b=On(u,m,d),v=b.length>0?e`, ${e.join(b,e`, `)}`:e``;await A(s,u,e`CREATE TABLE IF NOT EXISTS ${e.identifier(R)} (${e.identifier("__id__")} ${e.raw(i)} PRIMARY KEY, ${e.identifier("__partition__")} ${e.raw(i)} NOT NULL${v})`);const L=qn(u,m,d),M=`${h}__rank_${m.name}__btree`;await Ae(s,u,{columns:e.join(L,e`, `),name:M,table:R,unique:!1})}}},xe="__cdc_sweep",ht="global",Bn=6e4,xn=1e4,Wn=3e4;let wt=0;const Un=async(s,l)=>{const{autoincrementPrimaryKey:u,key:i,real:h,text:d}=l.companionTypes;await A(s,l,e`CREATE TABLE IF NOT EXISTS ${e.identifier(G)} (${e.identifier("seq")} ${e.raw(u)}, ${e.identifier("ts")} ${e.raw(h)} NOT NULL, ${e.identifier("table")} ${e.raw(i)} NOT NULL, ${e.identifier("id")} ${e.raw(i)} NOT NULL, ${e.identifier("op")} ${e.raw(i)} NOT NULL, ${e.identifier("doc")} ${e.raw(d)})`);const c=l.indexKeyPrefix?.("string");await Ae(s,l,{columns:e`${c===void 0?e`${e.identifier("table")}`:e`${e.identifier("table")}(${e.raw(String(c))})`}, ${e.identifier("seq")}`,name:cn,table:G,unique:!1}),await A(s,l,e`CREATE TABLE IF NOT EXISTS ${e.identifier(xe)} (${e.identifier("id")} ${e.raw(i)} NOT NULL PRIMARY KEY, ${e.identifier("lease_until")} ${e.raw(h)} NOT NULL)`),await A(s,l,e`INSERT INTO ${e.identifier(xe)} (${e.identifier("id")}, ${e.identifier("lease_until")}) VALUES (${ht}, ${0}) ${l.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${e.identifier("id")} = ${e.identifier("id")}`:e`ON CONFLICT(${e.identifier("id")}) DO NOTHING`}`)},Pn=async(s,l,u)=>{const i=e`UPDATE ${e.identifier(xe)} SET ${e.identifier("lease_until")} = ${u+Bn} WHERE ${e.identifier("id")} = ${ht} AND ${e.identifier("lease_until")} <= ${u}`;if(l.supportsReturning)return(await I(s,l,e`${i} RETURNING ${e.identifier("id")}`)).length>0;const h=await A(s,l,i);return(l.affectedRows?l.affectedRows(h??{rowsAffected:0}):0)>0},jn=async(s,l,u,i)=>{if(!await Pn(s,l,i))return;const h=i-u;await A(s,l,e`
|
|
2
|
-
DELETE FROM ${e.identifier(G)} WHERE ${e.identifier("seq")} IN (
|
|
3
|
-
SELECT ${e.identifier("seq")} FROM (
|
|
4
|
-
SELECT ${e.identifier("seq")} FROM ${e.identifier(G)} WHERE ${e.identifier("ts")} <= ${h} ORDER BY ${e.identifier("seq")} ASC LIMIT ${e.raw(String(xn))}
|
|
5
|
-
) AS ${e.identifier("expired")}
|
|
6
|
-
)
|
|
7
|
-
`)},Et=async(s,l)=>{const u=await I(s,l,e`SELECT MIN(${e.identifier("seq")}) AS ${e.identifier("seq")} FROM ${e.identifier(G)}`),i=Number(u[0]?.seq??Number.NaN);return Number.isFinite(i)?i:void 0},Kn=s=>JSON.stringify(ln(s)?un(s):s),Hn=async(s,l,u,i,h,d,c)=>{await A(s,c,e`INSERT INTO ${e.identifier(G)} (${e.identifier("ts")}, ${e.identifier("table")}, ${e.identifier("id")}, ${e.identifier("op")}, ${e.identifier("doc")}) VALUES (${l}, ${u}, ${i}, ${h}, ${d===void 0?null:Kn(d)})`)},ei=async(s,l,u)=>{const i=l.sinceSeq??0,h=Math.max(1,Math.min(l.limit??1e3,1e4)),d=await Et(s,u);if(d!==void 0&&Wt(d,i))throw Ut(d,i,"global");const m=(await I(s,u,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(G)} WHERE seq > ${i} ORDER BY seq ASC LIMIT ${e.raw(String(h))}`)).map(R=>{const{doc:b}=R,v={id:String(R.id),op:String(R.op),seq:Number(R.seq),table:String(R.table),ts:Number(R.ts)};return typeof b=="string"?{...v,doc:_t(JSON.parse(b))}:v});return{changes:m,cursor:m.at(-1)?.seq??i}},Gn=async(s,l,u,i={})=>{if(i.cursorOnly){const R=await I(s,u,e`SELECT MAX(seq) AS seq FROM ${e.identifier(G)}`),b=Number(R[0]?.seq??l);return{cursor:Number.isFinite(b)?b:l,tables:[]}}const h=await I(s,u,e`SELECT ${e.identifier("table")} AS ${e.identifier("table")}, MAX(seq) AS seq FROM ${e.identifier(G)} WHERE seq > ${l} GROUP BY ${e.identifier("table")}`);let d=l;const c=[];for(const R of h){const b=Number(R.seq);Number.isFinite(b)&&b>d&&(d=b),c.push(String(R.table))}const m=i.retained===!0?await Et(s,u):void 0;return{cursor:d,tables:c,...m===void 0?{}:{floor:m}}},ti=s=>{const{crossShardCounter:l,crossShardReader:u,exec:i,maxRelationKeys:h,schema:d}=s,{dialect:c}=s,{isUniqueViolation:m}=c,R={fieldRef:F,serialize:H,...c.name==="mysql"?{containsExpr:(t,n)=>e`LOCATE(${n}, ${t}) > 0`}:{},...c.name==="postgres"?{containsExpr:(t,n)=>e`strpos(${t}, ${n}) > 0`}:{},...c.name==="sqlite"?{}:{inList:Bt}},b=(t,n)=>We(c.name,t,n),v=t=>{const n=te(t.columns),o=re(t.values),r=f=>c.name==="mysql"?e`VALUES(${e.identifier(f)})`:e`excluded.${e.identifier(f)}`,a=f=>c.name==="postgres"?e`${e.identifier(t.table)}.${e.identifier(f)}`:e`${e.identifier(f)}`,_=e.join(Object.entries(t.set(r,a)).map(([f,y])=>e`${e.identifier(f)} = ${y}`),e`, `),E=c.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${_}`:e`ON CONFLICT(${e.identifier(t.conflictKey)}) DO UPDATE SET ${_}`;return e`INSERT INTO ${e.identifier(t.table)} (${n}) VALUES (${o}) ${E}`},L=s.clock??(()=>Date.now()),M=s.idGenerator??(()=>crypto.randomUUID()),x=s.cdc??!1,V=typeof s.cdcRetentionMs=="number"&&Number.isFinite(s.cdcRetentionMs)&&s.cdcRetentionMs>0?s.cdcRetentionMs:void 0,Y=s.auth??{identity:null,userId:null},X=async(t,n,o,r)=>{if(!x||(await Hn(i,L(),t,n,o,r,c),V===void 0))return;const a=L();if(!(a-wt<Wn)){wt=a;try{await jn(i,c,V,a)}catch{}}},yt=s.scheduler??xt,Ne=Tn();let ye=0,ke;const W=async()=>(ke??=(async()=>{await Mn(i,d,c),await Dn(i,d,c),await Fn(i,d,c),await fn(i,c),await At(i,d,c),x&&await Un(i,c)})().catch(t=>{throw ke=void 0,t}),ke),se=async(t,n)=>{await W();const o=await mn(i,c,d,t,Ne);if(!(n!==void 0&&o!==n))return o},ae=new Map,Pe=async(t,n)=>{const o=J(t,n);return(await I(i,c,c.tableExists(o))).length>0},pe=async(t,n)=>{const o=`${t}::${n.name}`,r=ae.get(o);if(r!==void 0)return r;if(!await Pe(t,n.name))return ae.set(o,!1),!1;const _=d.tables[t];if(!_)return ae.set(o,!1),!1;const E=n.by??[],f=new Map;await ct(i,c,_,t,$=>{if(n.where&&!Oe($,n.where))return;const p=z(E,$);an(f,p,n,$)});const y=J(t,n.name);await A(i,c,e`DELETE FROM ${e.identifier(y)}`);const w=[];for(const[$,p]of f)w.push(e`INSERT INTO ${e.identifier(y)} (${e.identifier("__key__")}, ${e.identifier("__value__")}, ${e.identifier("__count__")}) VALUES (${$}, ${p.value}, ${p.count})`);return await dt(i,c,w),ae.set(o,!0),!0},pt=async(t,n,o)=>{const r=we(n.op),a=n.field??"",_=[];for(const y of n.by??[]){const w=H(o[y]??null);_.push(w===null?e`${F(y)} IS NULL`:e`${F(y)} = ${w}`)}for(const[y,w]of Object.entries(n.where??{})){const $=w!==null&&typeof w=="object"&&!Array.isArray(w)?w.eq:w,p=H($);_.push(p===null?e`${F(y)} IS NULL`:e`${F(y)} = ${p}`)}const E=e`SELECT ${e.raw(r)}(${F(a)}) AS value FROM ${e.identifier(t)}`,f=await I(i,c,_.length>0?e`${E} WHERE ${e.join(_,e` AND `)}`:E);return oe(f[0]?.value)},Rt=async(t,n)=>{await A(i,c,e`DELETE FROM ${e.identifier(t)} WHERE ${e.identifier("__key__")} = ${n} AND ${e.identifier("__count__")} <= 0`)},Tt=async(t,n,o,r)=>{const a=J(t,n.name),{op:_}=n,E=n.field??"",f=o&&(!n.where||Oe(o,n.where))?o:void 0,y=r&&(!n.where||Oe(r,n.where))?r:void 0;if(!(!f&&!y)){if(_==="count"||_==="sum"||_==="avg"){const w=new Set;for(const[$,p]of[[f,-1],[y,1]]){if(!$)continue;const S=_==="count"?1:Fe($[E]);if(S===void 0)continue;const T=z(n.by??[],$);w.add(T),await A(i,c,v({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(C,N)=>({__count__:e`${N("__count__")} + ${C("__count__")}`,__value__:_==="count"?e`${N("__value__")} + ${C("__value__")}`:e`COALESCE(${N("__value__")}, 0) + ${C("__value__")}`}),table:a,values:[T,p*S,p]}))}for(const $ of w)await Rt(a,$);return}if(f){const w=z(n.by??[],f),$=Fe(f[E]),S=(await I(i,c,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(a)} WHERE ${e.identifier("__key__")} = ${w}`))[0],T=oe(S?.value),C=(S?.count??0)-1;if(C<=0)await A(i,c,e`DELETE FROM ${e.identifier(a)} WHERE ${e.identifier("__key__")} = ${w}`);else if(S&&$!==void 0&&T!==null&&$===T){const N=await pt(t,n,f);await A(i,c,e`UPDATE ${e.identifier(a)} SET ${e.identifier("__value__")} = ${N}, ${e.identifier("__count__")} = ${C} WHERE ${e.identifier("__key__")} = ${w}`)}else await A(i,c,e`UPDATE ${e.identifier(a)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${w}`)}if(y){const w=z(n.by??[],y),$=Fe(y[E]);if($===void 0)await A(i,c,v({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(p,S)=>({__count__:e`${S("__count__")} + 1`}),table:a,values:[w,null,1]}));else{const p=_==="min"?"MIN":"MAX";await A(i,c,v({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(S,T)=>({__count__:e`${T("__count__")} + 1`,__value__:e`${e.raw(p)}(COALESCE(${T("__value__")}, ${S("__value__")}), ${S("__value__")})`}),table:a,values:[w,$,1]}))}}}},Re=async t=>{const n=d.tables[t]?.aggregateIndexes;if(!(!n||n.length===0))for(const o of n)await pe(t,o)},ce=async(t,n,o)=>{const r=d.tables[t]?.aggregateIndexes;if(!(!r||r.length===0))for(const a of r){const _=`${t}::${a.name}`;(ae.get(_)??await Pe(t,a.name))&&await Tt(t,a,n,o)}},de=new Map,je=async(t,n)=>{const o=ne(t,n);return(await I(i,c,c.tableExists(o))).length>0},Me=async(t,n)=>{const o=`${t}::rank::${n.name}`,r=de.get(o);if(r!==void 0)return r;if(!await je(t,n.name))return de.set(o,!1),!1;const _=d.tables[t];if(!_)return de.set(o,!1),!1;const E=ne(t,n.name);await A(i,c,e`DELETE FROM ${e.identifier(E)}`);const f=n.sortBy.map((p,S)=>Q(S)),y=te(["__id__","__partition__",...f]),w=[];await ct(i,c,_,t,p=>{if(n.where&&!at(p,n.where))return;const S=Ce(n.partitionBy??[],p),T=n.sortBy.map(C=>H(p[C.field]??null));w.push([p._id,S,...T])});const $=w.map(p=>e`INSERT INTO ${e.identifier(E)} (${y}) VALUES (${re(p)})`);return await dt(i,c,$),de.set(o,!0),!0},Te=async t=>{const n=d.tables[t]?.rankIndexes;if(!(!n||n.length===0))for(const o of n)await Me(t,o)},Z=async(t,n,o,r)=>{const a=d.tables[t],_=a?.rankIndexes;if(!_||_.length===0)return;const E=a?.softDeleteMode?.field,f=E===void 0||r===void 0?void 0:r[E],y=f!=null;for(const w of _){if(o!==void 0&&r!==void 0&&gn(w,o,r))continue;const $=`${t}::rank::${w.name}`;if(!(de.get($)??await je(t,w.name)))continue;const T=ne(t,w.name);if(o&&await A(i,c,e`DELETE FROM ${e.identifier(T)} WHERE ${e.identifier("__id__")} = ${n}`),r&&!y){if(w.where&&!at(r,w.where))continue;const C=w.sortBy.map((D,K)=>Q(K)),N=te(["__id__","__partition__",...C]),B=Ce(w.partitionBy??[],r),k=w.sortBy.map(D=>H(r[D.field]??null));await A(i,c,e`INSERT INTO ${e.identifier(T)} (${N}) VALUES (${re([n,B,...k])})`)}}},le=Ct({dialect:c,exec:i,schema:d}),Ke=new Set;for(const[t,n]of Object.entries(d.tables))for(const o of Object.values(n.triggerMap??{}))Ke.add(`${t} ${o.timing} ${o.op}`);const P=(t,n,o)=>Ke.has(`${t} ${n} ${o}`);let He;const j=async(t,n,o)=>{if(ye+=1,ye>ut)throw ye-=1,new he(`trigger recursion exceeded ${String(ut)} levels on "${o.table}" — check for a self-triggering write`,"trigger");try{await tn({ctx:He,event:o,op:n,schema:d,tableName:o.table,timing:t})}finally{ye-=1}},mt=async(t,n)=>{try{await A(i,c,n)}catch(o){throw m(o)?new he(`unique constraint violation on "${t}"`,"unique"):o}},me=async(t,n)=>(await I(i,c,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} = ${n}`))[0],Se=async(t,n,o,r)=>{if(r===void 0)return;const a=e.join(Object.keys(r).map(f=>b(e`${e.identifier(f)}`,r[f])),e` AND `),_=n==="UPDATE"?e`UPDATE ${e.identifier(t)} SET ${o} WHERE ${a}`:e`DELETE FROM ${e.identifier(t)} WHERE ${a}`,E=()=>{throw new he(`optimistic concurrency conflict on "${t}" — the row changed during this mutation; refetch and retry`,"occ")};try{if(c.supportsReturning)(await I(i,c,e`${_} RETURNING ${e.identifier("id")}`)).length===0&&E();else{const f=await A(i,c,_);(c.affectedRows?c.affectedRows(f??{rowsAffected:0}):0)===0&&E()}}catch(f){throw m(f)?new he(`unique constraint violation on "${t}"`,"unique"):f}},St=(t,n,o,r)=>{const a=Object.keys(t.shape);return{columns:["id","_creationTime",...a],values:[n,o,...a.map(_=>H(r[_]??null))]}},gt=async(t,n,o,r)=>{const a=on(n,o.op,o.field,r.by,r.where);if(!a||!await pe(t,a.index))return;const E=J(t,a.index.name),f=Object.keys(a.partial);if(f.length===(a.index.by??[]).length&&f.length>0){const w=z(a.index.by??[],a.partial),$=await I(i,c,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(E)} WHERE ${e.identifier("__key__")} = ${w}`);if($.length===0)return[];const p=$[0];return[{key:{...a.partial},value:qe(o.op,{count:p.count,value:oe(p.value)})}]}return f.length>0?void 0:(await I(i,c,e`SELECT ${e.identifier("__key__")} AS key, ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(E)}`)).map(w=>{const $=w;return{key:_t(JSON.parse($.key)),value:qe(o.op,{count:$.count,value:oe($.value)})}})},Ge=t=>{const n=d.tables[t]?.shardMode?.kind;return n==="shardBy"||n==="root"},Ve=t=>{throw new g("INTERNAL",`cross-backend relation: a global table cannot load the shard-local relation '${t}' (it spans every shard) — wire a cross-shard reader to support it`)},vt=(t,n)=>{if(n?.relationMask!==void 0&&n.with!==void 0&&Object.keys(n.with).length>0)throw new g("MASK_UNSUPPORTED",`masking cannot follow a nested \`with\` across the cross-shard relation hop to "${t}" — the nested rows are hydrated on the serving shard, where the mask policy does not exist. Read the nested relation at its own (masked) call site instead.`);const o={};if(n?.relationBaseWhere)for(const r of Object.keys(d.tables)){const a=n.relationBaseWhere(r);a!==void 0&&(o[r]=a)}return{orderBy:n?.orderBy,relationPolicies:o,where:O(n?.baseWhere,n?.where),with:n?.with}},Ye=(t,n)=>Ge(t)?u?u(t,vt(t,n)):Ve(t):U.findMany(t,n),ge=(t,n,o)=>it(t,{fetcher:Ye,maxRelationKeys:h,relationBaseWhere:o,schema:d,tableName:n}),bt=$n(async(t,n)=>{const o=await I(i,c,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} IN (${re(n)})`),r=new Map;for(const a of o){const{id:_}=a;typeof _=="string"&&r.set(_,a)}return r}),U={async cdcChangedTables(t,n){if(x)try{return await W(),await Gn(i,t,c,{...n,retained:V!==void 0})}catch{return}},async aggregate(t,n){const o=d.tables[t];if(!o)throw new g("INTERNAL",`unknown table: ${t}`);if(await W(),we(n.op),n.op==="count")return U.count(t,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new g("INTERNAL",`aggregate(${t}, { op: "${n.op}" }): "field" is required for non-count reducers`);const r=_e(o.softDeleteMode,void 0),a=O(O(n.baseWhere,n.where),r),_=await ge(a,t,n.relationBaseWhere),E=_!==a;if(o.aggregateIndexes&&!n.baseWhere&&!E&&!r){const S=en(o.aggregateIndexes,n.op,n.field,n.where);if(S&&await pe(t,S.index)){const C=z(S.index.by??[],S.key),N=J(t,S.index.name),k=(await I(i,c,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(N)} WHERE ${e.identifier("__key__")} = ${C}`))[0];return qe(n.op,k===void 0?void 0:{count:k.count,value:oe(k.value)})}}const f=$e(_,R),y=e.raw(we(n.op)),w=e`SELECT ${y}(${F(n.field)}) AS value FROM ${e.identifier(t)}`,p=(await I(i,c,f?e`${w} WHERE ${f}`:w))[0]?.value;return p==null?null:Number(p)},async count(t,n){const o=d.tables[t];if(!o)throw new g("INTERNAL",`unknown table: ${t}`);await W();const r=Qt(n);if(r.restrictsCounts)throw new nt(t);const a=_e(o.softDeleteMode,void 0),_=O(O(r.baseWhere,r.where),a),E=await ge(_,t,r.relationBaseWhere),f=E!==_;if(o.aggregateIndexes&&!r.baseWhere&&!f&&!a){const p=Zt(o.aggregateIndexes,r.where);if(p&&await pe(t,p.index)){const T=z(p.index.by??[],p.key),C=J(t,p.index.name),N=await I(i,c,e`SELECT ${e.identifier("__value__")} AS value FROM ${e.identifier(C)} WHERE ${e.identifier("__key__")} = ${T}`);return Number(N[0]?.value??0)}}const y=$e(E,R),w=e`SELECT COUNT(*) AS count FROM ${e.identifier(t)}`,$=await I(i,c,y?e`${w} WHERE ${y}`:w);return Number($[0]?.count??0)},async delete(t,n,o){const r=await se(t,n);if(!r)return;const a=d.tables[r];if(!a)return;const _=await me(r,t),E=ie(a,_),f=o?.hard===!0,y=!f&&a.softDeleteMode?a.softDeleteMode.field:void 0;if(!(y&&(!E||E[y]!==null&&E[y]!==void 0))){if(P(r,"before","delete")&&await j("before","delete",{id:t,op:"delete",previous:E??void 0,table:r}),await Jt({deletedId:t,deletedReference:w=>E?.[w],findHolders:async(w,$,p)=>{if(d.tables[w]?.shardMode?.kind==="shardBy")throw new g("INTERNAL",`cross-backend cascade from global '${r}' into shardBy '${w}' is not supported — would require Query Coordinator fan-out across shards`);return(await U.findMany(w,{includeDeleted:f,where:{[$]:p}})).page},onCascade:(w,$)=>U.delete($,void 0,o),onRestrict:w=>{throw new he(w,"restrict")},onSetNull:(w,$,p)=>U.patch($,{[p]:null}),schema:d,tableName:r}),await Re(r),await Te(r),y&&E){const w={...E,[y]:L()},$=e.join(Object.keys(a.shape).map(p=>e`${e.identifier(p)} = ${H(w[p]??null)}`),e`, `);await Se(r,"UPDATE",$,_),await ce(r,E,w),await Z(r,t,E,void 0),await le(r,t,w,E),await X(r,t,"update",w),P(r,"after","delete")&&await j("after","delete",{id:t,op:"delete",previous:E,table:r});return}await Se(r,"DELETE",void 0,_),Ne.delete(t),await ce(r,E??void 0,void 0),await Z(r,t,E??void 0,void 0),await le(r,t,void 0),await X(r,t,"delete"),P(r,"after","delete")&&await j("after","delete",{id:t,op:"delete",previous:E??void 0,table:r})}},async findFirst(t,n={}){return(await U.findMany(t,{...n,limit:1})).page[0]??null},async findFirstOrThrow(t,n={}){const o=await U.findFirst(t,n);if(o===null)throw new zt(`findFirstOrThrow: no "${t}" document matched`);return o},async findMany(t,n={}){const o=d.tables[t];if(!o)throw new g("INTERNAL",`unknown table: ${t}`);await W();const r=Gt(n.orderBy,o.shape),a=n.cursor?Vt(r,Yt(n.cursor)):void 0,_=Ye,E=async(k,D,K,ve)=>{if(Ge(k))return l?sn(l,k,D,K,ve):Ve(k);const be=d.tables[k];if(!be)throw new g("INTERNAL",`unknown table: ${k}`);const Ie=_e(be.softDeleteMode,void 0),ee={[D]:{in:K}},q=O(O(ee,ve),Ie),ue=await ge(q,k,void 0),Xe=$e(ue,R),ze=F(D);let fe=e`SELECT ${ze} AS __fk__, COUNT(*) AS count FROM ${e.identifier(k)}`;Xe&&(fe=e`${fe} WHERE ${Xe}`),fe=e`${fe} GROUP BY ${ze}`;const It=await I(i,c,fe),Je=new Map;for(const Qe of It)Je.set(Qe.__fk__,Number(Qe.count??0));return Je};let f=O(n.baseWhere,n.where);f=O(f,_e(o.softDeleteMode,n.includeDeleted)),f=await it(f,{fetcher:_,maxRelationKeys:h,relationBaseWhere:n.relationBaseWhere,schema:d,tableName:t}),a&&(f=f?{AND:[f,a]}:a);const y=$e(f,R),w=yn(r,c);let $=e`SELECT * FROM ${e.identifier(t)}`;y&&($=e`${$} WHERE ${y}`),$=e`${$} ORDER BY ${w}`;const p=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;p!==void 0&&($=e`${$} LIMIT ${e.raw(String(p+1))}`);const S=await I(i,c,$),T=wn(o,S);if(p===void 0)return n.with&&await ot({fetcher:_,groupedCounter:E,parents:T,...rt(n),schema:d,tableName:t,with:n.with}),{continueCursor:null,isDone:!0,page:st(T,n.select,n.with)};const C=T.length>p,N=C?T.slice(0,p):T,B=N.at(-1);return n.with&&await ot({fetcher:_,groupedCounter:E,parents:N,...rt(n),schema:d,tableName:t,with:n.with}),{continueCursor:C&&B?Xt(B,r):null,isDone:!C,page:st(N,n.select,n.with)}},async get(t,n){const o=await se(t,n);if(!o)return null;const r=d.tables[o];return r?ie(r,await bt.load(o,t)):null},async groupBy(t,n){const o=d.tables[t];if(!o)throw new g("INTERNAL",`unknown table: ${t}`);await W();const r=n.agg??{op:"count"};if(we(r.op),r.op!=="count"&&!r.field)throw new g("INTERNAL",`groupBy(${t}, { agg: { op: "${r.op}" } }): "field" is required for non-count reducers`);const a=_e(o.softDeleteMode,void 0),_=O(O(n.baseWhere,n.where),a),E=await ge(_,t,n.relationBaseWhere),f=E!==_;if(o.aggregateIndexes&&!n.baseWhere&&!f&&!a){const T=await gt(t,o.aggregateIndexes,r,n);if(T!==void 0)return T}const y=$e(E,R),w=n.by.map(T=>e`${F(T)} AS ${e.identifier(T)}`);if(r.op==="count")w.push(e`COUNT(*) AS value`);else{if(!r.field)throw new g("INTERNAL",`groupBy(${t}, { agg: { op: "${r.op}" } }): "field" is required for non-count reducers`);w.push(e`${e.raw(we(r.op))}(${F(r.field)}) AS value`)}const $=e.join(n.by.map(T=>F(T)),e`, `);let p=e`SELECT ${e.join(w,e`, `)} FROM ${e.identifier(t)}`;y&&(p=e`${p} WHERE ${y}`),p=e`${p} GROUP BY ${$}`;const S=await I(i,c,p);return Sn(n.by,S)},async insert(t,n,o){const r=d.tables[t];if(!r)throw new g("INTERNAL",`unknown table: ${t}`);await W();const a=pn(r,n,Y);De(r,a);let _,E=!0;o?.clientId!==void 0?(Ht(o.clientId),_=o.clientId):o?.allowExplicitId&&typeof a._id=="string"?_=a._id:(_=M(),E=!1);const f=o?.allowExplicitId&&typeof a._creationTime=="number"?a._creationTime:L(),y={...a,_creationTime:f,_id:_};P(t,"before","insert")&&await j("before","insert",{doc:{...y},id:_,op:"insert",table:t}),await Re(t),await Te(t);const{columns:w,values:$}=St(r,_,f,a);return await mt(t,e`INSERT INTO ${e.identifier(t)} (${te(w)}) VALUES (${re($)})`),E&&Ne.set(_,t),await ce(t,void 0,y),await Z(t,_,void 0,y),await le(t,_,y),await X(t,_,"insert",y),P(t,"after","insert")&&await j("after","insert",{doc:y,id:_,op:"insert",table:t}),_},normalizeId(t,n){return Kt(d,t,n)},async patch(t,n,o){Ze("patch",n);const r=await se(t,o);if(!r)throw new g("INTERNAL",`document not found: ${t}`);const a=d.tables[r];if(!a)throw new g("INTERNAL",`document not found: ${t}`);const _=await me(r,t),E=ie(a,_);if(!E)throw new g("INTERNAL",`document not found: ${t}`);const f={...E,...n,_id:t};ft(a,n,f,Y),De(a,f,!0),P(r,"before","update")&&await j("before","update",{doc:{...f},id:t,op:"update",previous:E,table:r}),await Re(r),await Te(r);const y=Object.keys(a.shape),w=e.join(y.map($=>e`${e.identifier($)} = ${H(f[$]??null)}`),e`, `);await Se(r,"UPDATE",w,_),await ce(r,E,f),await Z(r,t,E,f),await le(r,t,f,E),await X(r,t,"update",f),P(r,"after","update")&&await j("after","update",{doc:f,id:t,op:"update",previous:E,table:r})},async restore(t,n){const o=await se(t,n);if(!o)throw new g("INTERNAL",`document not found: ${t}`);const r=d.tables[o],a=r?.softDeleteMode?.field;if(!r||!a)throw new g("INTERNAL",`ctx.db.restore: table "${o}" is not a .softDelete() table`);const _=await me(o,t),E=_?.[a]!==null&&_?.[a]!==void 0;if(await U.patch(t,{[a]:null},n),E){const f=ie(r,_);f!==null&&await Z(o,t,void 0,{...f,[a]:null})}},query(t){const n=d.tables[t];if(!n)throw new g("INTERNAL",`unknown table: ${t}`);const o="the legacy query()/withIndex() reader is not available on the D1 (global) backend; use findMany",r=[],a=f=>r.every(y=>y(f)),_=async(f,y)=>{await W();const w=r.length>0,$=await Dt(i,c,n,t,f,qt(w?void 0:y));if(!w)return y===void 0&&Ot($),$;const p=$.filter(S=>a(S));return y===void 0?p:p.slice(0,y)},E=f=>{const y={async*[Symbol.asyncIterator](){if(!f)throw new g("INTERNAL",o);yield*await _(f,void 0)},async collect(){if(!f)throw new g("INTERNAL",o);return _(f,void 0)},async collectWithScores(){throw new g("GLOBAL_SEARCH_SCORES_UNSUPPORTED",`collectWithScores() is not supported on \`.global()\` tables (table "${t}") — relevance scores are not yet surfaced on this backend; use .collect() instead`)},filter(w){return r.push(w),y},async first(){if(!f)throw new g("INTERNAL",o);return(await _(f,1))[0]??null},order(){return y},async paginate(w){if(!f)throw new g("INTERNAL",o);const $=kt(w);return Mt(await _(f,Ft($)),$)},async take(w){if(!f)throw new g("INTERNAL",o);return _(f,w)},async unique(){if(!f)throw new g("INTERNAL",o);const w=await _(f,2);if(w.length>1)throw new dn(`unique() on table "${t}" matched ${String(w.length)} documents; expected at most one`);return w[0]??null},withGeoIndex(){throw new g("INTERNAL",`geo indexes are not supported on \`.global()\` tables (table "${t}") — geospatial queries run only on sharded tables`)},withIndex(){throw new g("INTERNAL",o)},withSearchIndex(w,$){const p=(n.searchIndexes??[]).find(T=>T.name===w);if(!p)throw new g("INTERNAL",`unknown search index "${w}" on table "${t}"`);const S={definition:p,field:p.field,filters:[],hasQuery:!1,indexName:w,query:""};if($(Lt(S,t,Nt(p.language))),!S.hasQuery)throw new g("INTERNAL",`search index "${w}" on table "${t}" requires a .search(field, query) call`);return E(S)}};return y};return E(void 0)},async rank(t,n,o){const r=d.tables[t];if(!r)throw new g("INTERNAL",`unknown table: ${t}`);const a=r.rankIndexes?.find(D=>D.name===n);if(!a)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(o.restrictsCounts)throw new nt(t);if(await W(),!await Me(t,a))return null;const E=typeof o.row=="string"?o.row:o.row._id;if(!E)return null;const f=ne(t,a.name),y=a.sortBy.map((D,K)=>Q(K)),w=te(["__partition__",...y]),p=(await I(i,c,e`SELECT ${w} FROM ${e.identifier(f)} WHERE ${e.identifier("__id__")} = ${E}`))[0];if(!p)return null;const S=p.__partition__,T=O(o.baseWhere,o.where);et(T,d,t,"rank");const C=tt(a,T);if(C&&Ce(a.partitionBy??[],C)!==S)return null;const N=vn(c.name,a,y,p,E),B=await I(i,c,e`SELECT COUNT(*) AS c FROM ${e.identifier(f)} WHERE ${e.identifier("__partition__")} = ${S}${N?e` AND (${N})`:e``}`),k=await I(i,c,e`SELECT COUNT(*) AS c FROM ${e.identifier(f)} WHERE ${e.identifier("__partition__")} = ${S}`);return{position:Number(B[0]?.c??0)+1,total:Number(k[0]?.c??0)}},async rankPage(t,n,o={}){et(O(o.baseWhere,o.where),d,t,"rankPage");const r=d.tables[t];if(!r)throw new g("INTERNAL",`unknown table: ${t}`);const a=r.rankIndexes?.find(q=>q.name===n);if(!a)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(await W(),!await Me(t,a))return{continueCursor:null,isDone:!0,page:[]};const E=ne(t,a.name),f=a.sortBy.map((q,ue)=>Q(ue)),y=Math.max(1,Math.min(1e3,Math.floor(o.take??100))),w=O(o.baseWhere,o.where),$=tt(a,w),p=In(a,f),S=e.join(p.map(q=>e`${e.identifier(q.column)} ${e.raw(q.direction==="desc"?"DESC":"ASC")}`),e`, `),T=[];typeof o.partitionKey=="string"?T.push(e`${e.identifier("__partition__")} = ${o.partitionKey}`):$&&T.push(e`${e.identifier("__partition__")} = ${Ce(a.partitionBy??[],$)}`);const C=jt(o);if(C!==void 0){const q=bn(c.name,p,C);q!==void 0&&T.push(q)}const N=te([Ee,"__partition__",...f]);let B=e`SELECT ${N} FROM ${e.identifier(E)}`;T.length>0&&(B=e`${B} WHERE ${e.join(T,e` AND `)}`),B=e`${B} ORDER BY ${S} LIMIT ${e.raw(String(y+1))}`;const k=await I(i,c,B),D=k.length>y,K=D?k.slice(0,y):k,ve=K.map(q=>q[Ee]),be=await Cn(i,c,r,t,ve);let Ie=null;const ee=K.at(-1);if(D&&ee!==void 0){const q=[ee.__partition__,...f.map(ue=>ee[ue]),ee[Ee]];Ie=An(q)}return{continueCursor:Ie,isDone:!D,page:be}},async replace(t,n,o,r){Ze("replace",n);const a=await se(t,o);if(!a)throw new g("INTERNAL",`document not found: ${t}`);const _=d.tables[a];if(!_)throw new g("INTERNAL",`document not found: ${t}`);const E=await me(a,t);if(E===void 0)throw new g("INTERNAL",`document not found: ${t}`);const y=Pt(d,a,"update")||(_.aggregateIndexes??[]).length>0||(_.rankIndexes??[]).length>0?ie(_,E)??void 0:void 0,w=r?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:L(),$={...n,_creationTime:w,_id:t};ft(_,n,$,Y),De(_,$),P(a,"before","update")&&await j("before","update",{doc:{...$},id:t,op:"update",previous:y,table:a}),await Re(a),await Te(a);const p=Object.keys(_.shape),S=e.join([e`${e.identifier("_creationTime")} = ${w}`,...p.map(T=>e`${e.identifier(T)} = ${H($[T]??null)}`)],e`, `);await Se(a,"UPDATE",S,E),await ce(a,y,$),await Z(a,t,y,$),await le(a,t,$,y),await X(a,t,"update",$),P(a,"after","update")&&await j("after","update",{doc:$,id:t,op:"update",previous:y,table:a})}};return He={db:U,scheduler:yt},U};export{oi as backfillSqlSearchIndexes,ti as createSqlCtxDb,si as decodeGlobalRow,Gn as readSqlCdcChangedTables,ei as readSqlCdcChanges,Et as readSqlCdcFloor,Dn as runSqlAggregateMigrations,Un as runSqlCdcMigration,Mn as runSqlGlobalTableMigrations,Fn as runSqlRankMigrations,At as runSqlSearchMigrations,jn as sweepSqlCdcRetention};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{renderSql as u}from"@lunora/shard-engine";import{sql as i}from"drizzle-orm";import{s as I,a as y,e as C}from"./value-codec-CwTLrqfU.mjs";const g=t=>t==="_id"||t==="id"?"id":t,A=t=>i`${i.identifier(g(t))}`,S=(t,n,e)=>{const{params:o,sql:r}=u(n.name,e);return t.all(r,o)},l=(t,n,e)=>{const{params:o,sql:r}=u(n.name,e);return t.run(r,o)},b=async(t,n,e)=>{if(e.length!==0){if(!t.batch){for(const o of e)await l(t,n,o);return}await t.batch(e.map(o=>u(n.name,o)))}},M=async(t,n,e)=>{const o=e.unique?i`UNIQUE `:i``;if(n.name==="mysql"){try{await l(t,n,i`CREATE ${o}INDEX ${i.identifier(e.name)} ON ${i.identifier(e.table)} (${e.columns})`)}catch(r){const a=r;if(a.errno!==1061&&a.code!=="ER_DUP_KEYNAME"&&a.code!==1061)throw r}return}await l(t,n,i`CREATE ${o}INDEX IF NOT EXISTS ${i.identifier(e.name)} ON ${i.identifier(e.table)} (${e.columns})`)},O=I,h=new WeakMap,T=t=>{let n=h.get(t);return n===void 0&&(n=Object.entries(t.shape).map(([e,o])=>[e,C(o)]),h.set(t,n)),n},p=(t,n)=>{const e={};for(const[o,r]of T(t)){const a=n[o];a!==void 0&&(e[o]=y(a,r))}return e._id=n.id,e._creationTime=n._creationTime,e},$=(t,n)=>n?p(t,n):null,D=(t,n)=>{const e=[];for(const o of n){const r=$(t,o);r&&e.push(r)}return e},w=500,K=async(t,n,e,o,r,a={})=>{let d=a.after,s=a.limit,f=!0;for(;f&&(s===void 0||s>0);){const m=s===void 0?w:Math.min(w,s),R=d===void 0?i``:i` WHERE ${i.identifier("id")} > ${d}`,c=await S(t,n,i`SELECT * FROM ${i.identifier(o)}${R} ORDER BY ${i.identifier("id")} ASC LIMIT ${i.raw(String(m))}`);for(const q of c){const E=$(e,q);E&&await r(E)}d=c.at(-1)?.id,f=c.length===m,s=s===void 0?void 0:s-c.length}};export{w as BACKFILL_BATCH_SIZE,A as columnRefSql,M as createIndexIfNotExists,p as decodeGlobalRow,$ as decodeRow,D as decodeRows,K as forEachRowPaged,g as physicalColumn,S as queryAll,b as queryBatch,l as queryRun,O as serializeColumnValue};
|