@lunora/sql-store 1.0.0-alpha.234 → 1.0.0-alpha.236

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportSqlGlobalRows as r,importSqlGlobalRows as a,selectGlobalTables as l}from"./packem_shared/exportSqlGlobalRows-DzCIGW9D.mjs";import{createSqlCtxDb as s,readSqlCdcChangedTables as S,readSqlCdcChanges as i,readSqlCdcFloor as n,runSqlCdcMigration as d,sweepSqlCdcRetention as q}from"./packem_shared/createSqlCtxDb-BCxpkRRt.mjs";import{runSqlGlobalTableMigrations as b}from"./packem_shared/runSqlGlobalTableMigrations-BARAefvR.mjs";import{runSqlAggregateMigrations as f,runSqlRankMigrations as g}from"./packem_shared/runSqlAggregateMigrations-D5_8KDaC.mjs";import{b as x,r as T}from"./packem_shared/ctx-db-search-bBDPdaOs.mjs";import{S as u,m as E}from"./packem_shared/ctx-db-search-state-BBPiVWjf.mjs";import{facetSqlGlobalColumn as M,listSqlGlobalTables as R,readSqlGlobalTablePage as h}from"./packem_shared/facetSqlGlobalColumn-BPU8EBYc.mjs";import{DEFAULT_QUERY_TIMEOUT_MS as _,SqlQueryTimeoutError as w}from"./packem_shared/DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import{d as U,e as k,s as y,a as B,t as F}from"./packem_shared/value-codec-CbyTgWR3.mjs";import{d as L}from"./packem_shared/sql-exec-enIOMsv0.mjs";export{_ as DEFAULT_QUERY_TIMEOUT_MS,u as SEARCH_STATE_TABLE,w as SqlQueryTimeoutError,x as backfillSqlSearchIndexes,s as createSqlCtxDb,U as decodeBigint,L as decodeGlobalRow,k as effectiveColumnKind,r as exportSqlGlobalRows,M as facetSqlGlobalColumn,a as importSqlGlobalRows,R as listSqlGlobalTables,E as migrateSearchState,S as readSqlCdcChangedTables,i as readSqlCdcChanges,n as readSqlCdcFloor,h as readSqlGlobalTablePage,f as runSqlAggregateMigrations,d as runSqlCdcMigration,b as runSqlGlobalTableMigrations,g as runSqlRankMigrations,T as runSqlSearchMigrations,l as selectGlobalTables,y as sqliteDecode,B as sqliteEncode,q as sweepSqlCdcRetention,F as tryJsonParse};
1
+ import{exportSqlGlobalRows as a,importSqlGlobalRows as o,selectGlobalTables as l}from"./packem_shared/exportSqlGlobalRows-BdZd_QWV.mjs";import{createSqlCtxDb as s,readSqlCdcChangedTables as S,readSqlCdcChanges as i,readSqlCdcFloor as n,runSqlCdcMigration as d,sweepSqlCdcRetention as q}from"./packem_shared/createSqlCtxDb-egdYH1wk.mjs";import{runSqlGlobalTableMigrations as b}from"./packem_shared/runSqlGlobalTableMigrations-BSYk8UQI.mjs";import{r as f,a as g}from"./packem_shared/ctx-db-migrations-BGcbBPWX.mjs";import{b as x,r as T}from"./packem_shared/ctx-db-search-Bp1PvUqO.mjs";import{S as u,m as E}from"./packem_shared/ctx-db-search-state-BBPiVWjf.mjs";import{facetSqlGlobalColumn as M,listSqlGlobalTables as R,readSqlGlobalTablePage as h}from"./packem_shared/facetSqlGlobalColumn-DC5_yIh7.mjs";import{DEFAULT_QUERY_TIMEOUT_MS as _,SqlQueryTimeoutError as w}from"./packem_shared/DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import{d as U,e as k,s as y,a as B,t as F}from"./packem_shared/value-codec-CbyTgWR3.mjs";import{d as L}from"./packem_shared/sql-exec-enIOMsv0.mjs";export{_ as DEFAULT_QUERY_TIMEOUT_MS,u as SEARCH_STATE_TABLE,w as SqlQueryTimeoutError,x as backfillSqlSearchIndexes,s as createSqlCtxDb,U as decodeBigint,L as decodeGlobalRow,k as effectiveColumnKind,a as exportSqlGlobalRows,M as facetSqlGlobalColumn,o as importSqlGlobalRows,R as listSqlGlobalTables,E as migrateSearchState,S as readSqlCdcChangedTables,i as readSqlCdcChanges,n as readSqlCdcFloor,h as readSqlGlobalTablePage,f as runSqlAggregateMigrations,d as runSqlCdcMigration,b as runSqlGlobalTableMigrations,g as runSqlRankMigrations,T as runSqlSearchMigrations,l as selectGlobalTables,y as sqliteDecode,B as sqliteEncode,q as sweepSqlCdcRetention,F as tryJsonParse};
@@ -1 +1 @@
1
- import"./ctx-db-search-state-BBPiVWjf.mjs";import{b as o,c as i,a as s,d as l,r as n}from"./ctx-db-search-bBDPdaOs.mjs";import"./DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import"./sql-exec-enIOMsv0.mjs";export{o as backfillSqlSearchIndexes,i as createSearchSync,s as reconcileSearchRow,l as runSqlSearch,n as runSqlSearchMigrations};
1
+ import"./ctx-db-search-state-BBPiVWjf.mjs";import{b as o,c as i,a as s,d as l,r as n}from"./ctx-db-search-Bp1PvUqO.mjs";import"./DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import"./sql-exec-enIOMsv0.mjs";export{o as backfillSqlSearchIndexes,i as createSearchSync,s as reconcileSearchRow,l as runSqlSearch,n as runSqlSearchMigrations};
@@ -0,0 +1,7 @@
1
+ import{LunoraError as g}from"@lunora/errors";import{m as mn,q as Sn}from"./ctx-db-search-state-BBPiVWjf.mjs";import{c as gn,r as Tn,a as vn,A as In,C as An,R as Cn,u as Ln,d as bn,I as Mn,x as Nn,e as On}from"./ctx-db-search-Bp1PvUqO.mjs";import{throwingScheduler as qn,describeRelationWrites as kn,CDC_LOG_TABLE as W,cdcForkedError as Dn,cursorBelowRetainedFloor as Bn,cdcTrimmedError as Wn,serverInList as Fn,assertNoExplicitUndefined as Ve,hasTrigger as xn,runRowValidators as Ye,assertFlatPredicate as St,mergeWhere as x,rankTableName as Ee,sortColumnName as me,resolveRankPartition as gt,encodePartitionKey as Oe,resolveRankSeekTuple as Un,RANK_TIEBREAK as Te,CountRlsUnsupportedError as Tt,compileWhereSql as ee,ConflictError as ne,patchDependsOnRow as Pn,normalizeIdStructurally as Hn,applyInsertDefaults as Kn,assertValidClientId as jn,assertStorableRowId as Gn,aggregateSqlFunction as pe,softDeleteScope as qe,findManyPage as Vn,resolveWith as Yn,relationHooks as Xn,applySelect as Qn,NotFoundError as zn,applyOnDelete as Jn,normalizeCountArgument as Zn,selectIndexForCount as ei,encodeAggregateKey as te,aggregateTableName as ae,selectIndexForAggregate as ti,readAggregateValue as Xe,runTriggers as ni,matchesRankStaticWhere as vt,nullsOrderSuffix as It,nullsFirstOf as At,rankPivotConditionSql as Gt,CURSOR_PREFIX as ii,resolvePatch as ri,stripReservedPatchFields as oi,assertPatchAllowed as si,resolveRelationPredicates as ai,selectIndexForGroupBy as ci,composeReadPredicate as di,fanOutScalarCounts as li,matchesStaticWhere as Qe,coerceAggregateNumber as ze,whereOfFilter as ui,isPushableWhere as fi,tiebreakDirectionFor as wi,foldAggregateTally as Ct,CDC_LOG_TABLE_SEQ_INDEX as hi,NotUniqueError as $i,WORKERD_SQLITE_LIMITS as _i,unionAll as Ei}from"@lunora/shard-engine";import{parseWire as pi,needsWireEncoding as Vt,encodeWire as Yt,decodeWire as yi}from"@lunora/wire";import{sql as e,SQL as Ri}from"drizzle-orm";import{p as Lt,b as bt,q as b,c as j,e as Xt,i as mi,f as Si,g as gi,h as Q,s as ce,j as K,k as Mt,t as Ti,l as Je,m as Be,n as at,O as ye,o as Nt,a as Ot,u as qt,v as kt,w as vi,B as Ze,x as Dt,y as Bt,M as Ii}from"./sql-exec-enIOMsv0.mjs";import{d as Mr}from"./sql-exec-enIOMsv0.mjs";import{runSqlGlobalTableMigrations as Ai}from"./runSqlGlobalTableMigrations-BSYk8UQI.mjs";import{r as Ci,a as Li}from"./ctx-db-migrations-BGcbBPWX.mjs";import{a as Re}from"./post-commit-error-hh-zQyjO.mjs";import{withQueryTimeout as bi,DEFAULT_QUERY_TIMEOUT_MS as Mi,abandonedWork as et,SqlQueryTimeoutError as Ni}from"./DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import{s as Qt,e as ct}from"./value-codec-CbyTgWR3.mjs";const Wt=50,Oi=(o,a={})=>{const f=a.maxBatch??Wt,_=Number.isInteger(f)&&f>0?f:Wt,l=new Map;let E=!1;const c=async(M,T)=>{const v=[...T.keys()];for(let A=0;A<v.length;A+=_){const N=v.slice(A,A+_);try{const B=await o(M,N);for(const G of N){const z=B.get(G);for(const ie of T.get(G)??[])ie.resolve(z)}}catch(B){for(const G of N)for(const z of T.get(G)??[])z.reject(B)}}},q=()=>{E=!1;const M=[...l.entries()];l.clear();for(const[T,v]of M)c(T,v).catch(()=>{})};return{async load(M,T){return new Promise((v,A)=>{let N=l.get(M);N||(N=new Map,l.set(M,N));const B=N.get(T);B?B.push({reject:A,resolve:v}):N.set(T,[{reject:A,resolve:v}]),E||(E=!0,queueMicrotask(q))})}}},qi=new Set(["_id","id"]),ki=o=>{throw new g("INTERNAL",`no ORDER BY NULL placement for dialect "${String(o)}"`)},zt=(o,a)=>{const f=a.direction==="desc"?"DESC":"ASC",_=a.nullable===!0,l=E=>e`${Be(o,a.field)} ${e.raw(`${f}${E}`)}`;switch(o.name){case"mysql":{const E=l("");return!_||a.nulls===void 0?[E]:[e`(${Be(o,a.field)} IS NULL) ${e.raw(a.nulls==="first"?"DESC":"ASC")}`,E]}case"postgres":return[l(_?It(At(a)):"")];case"sqlite":return[l(_&&a.nulls!==void 0?It(At(a)):"")];default:return ki(o.name)}},Di=(o,a)=>{const f=o.flatMap(_=>zt(a,_));if(!o.some(_=>qi.has(_.field))){const _=wi(o);f.push(e`${K("id")} ${e.raw(_==="desc"?"DESC":"ASC")}`)}return e.join(f,e`, `)},Ft=50,Bi=o=>{const a=o.detail??o["QUERY PLAN"];return typeof a=="string"?a:Object.values(o).map(String).join(" | ")},tt=(o,a,f,_)=>{for(const[l,E]of Ti(o)){if(E.serverDefault){l in a&&(f[l]=E.serverDefault({auth:_}));continue}E.onUpdateFn&&!(l in a)&&(f[l]=E.onUpdateFn())}},Wi=o=>o.shardMode===void 0||o.shardMode.kind==="global",ue=o=>o==null?null:Number(o),Fi=(o,a,f)=>f.map(_=>{const l={};for(const E of a){const c=o.shape[E];l[E]=Qt(_[E]??null,c&&ct(c))}return{key:l,value:ue(_.value)}}),xi=(o,a,f)=>[...o.partitionBy??[],...o.sortBy.map(l=>l.field),...o.where?Object.keys(o.where):[]].every(l=>qt(a,l)===qt(f,l)),Jt=o=>o.length===1?o[0]:e`(${e.join(o,e` AND `)})`,fe=o=>e.join(o.map(a=>e`${e.identifier(a)}`),e`, `),Se=o=>e.join(o.map(a=>e`${a}`),e`, `),nt=(o,a)=>{if(o==="postgres"){for(const[f,_]of Object.entries(a))if(typeof _=="string"&&_.includes("\0"))throw new g("BAD_REQUEST",`"${f}" holds a NUL character (U+0000), which a Postgres text column cannot store`)}},We=o=>o instanceof ArrayBuffer?new Uint8Array(o):Array.isArray(o)?Uint8Array.from(o):o,Ui=(o,a,f,_,l)=>{const E=[];for(let c=0;c<f.length+1;c+=1){const q=f[c],M=a.sortBy[c],T=c<f.length&&q!==void 0&&M!==void 0,v=M?.direction==="desc"?"desc":"asc",A=T?Gt(q,We(_[q]),v,!1):e`${e.identifier(Te)} < ${l}`;if(A===void 0)continue;const N=f.slice(0,c).map(B=>at(o,e`${e.identifier(B)}`,We(_[B])));N.push(A),E.push(Jt(N))}return E.length>0?e.join(E,e` OR `):e`1 = 0`},Pi=(o,a,f)=>{if(f.length!==a.length)return;const _=[];for(const[l,E]of a.entries()){const c=Gt(E.column,We(f[l]),E.direction,!0);if(c===void 0)continue;const q=[];for(let M=0;M<l;M+=1){const T=a[M];T!==void 0&&q.push(at(o,e`${e.identifier(T.column)}`,We(f[M])))}q.push(c),_.push(Jt(q))}return _.length===0?e`(1 = 0)`:e`(${e.join(_,e` OR `)})`},Hi=(o,a)=>{if(o.sortBy.length===0)throw new g("INTERNAL",`rankIndex "${o.name}" requires at least one "sortBy" column for stable pagination`);const f=[{column:"__partition__",direction:"asc",nullable:!1}];for(const[_,l]of o.sortBy.entries())f.push({column:a[_]??me(_),direction:l.direction,nullable:!0});return f.push({column:Te,direction:"asc",nullable:!1}),f},Ki=async(o,a,f,_,l)=>{const c=[];for(let v=0;v<l.length;v+=50)c.push(l.slice(v,v+50));const q=await Promise.all(c.map(async v=>b(o,a,e`SELECT * FROM ${e.identifier(_)} WHERE ${e.identifier("id")} IN (${Se(v)})`))),M=new Map;for(const v of q)for(const A of v)M.set(A.id,A);const T=[];for(const v of l){const A=Q(f,M.get(v));A&&T.push(A)}return T},ji=o=>{const a=o.map(E=>Qt(E,"bytes")),f=JSON.stringify(Vt(a)?Yt(a):a),_=new TextEncoder().encode(f);let l="";for(const E of _)l+=String.fromCodePoint(E);return ii+btoa(l)},Zt=o=>{if(o===void 0)return!1;const a=ct(o);return a==="any"||a==="bigint"||a==="from"||a==="union"},ot=(o,a,f)=>{if(Zt(o.shape[a]))throw new g("BAD_REQUEST",`${f}: "${a}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Gi=(o,a,f,_)=>{for(const l of f)ot(o,l,`groupBy(${a}, { by: [..."${l}"] })`);_.field!==void 0&&ot(o,_.field,`groupBy(${a}, { agg: { op: "${_.op}", field: "${_.field}" } })`)},st="__cdc_sweep",ke="__cdc_log_ts",en="global",Vi=6e4,Yi=1e4,Xi=3e4;let xt=0;const Qi=async(o,a)=>{const{autoincrementPrimaryKey:f,key:_,real:l,text:E}=a.companionTypes;await j(o,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(W)} (${e.identifier("seq")} ${e.raw(f)}, ${e.identifier("ts")} ${e.raw(l)} NOT NULL, ${e.identifier("table")} ${e.raw(_)} NOT NULL, ${e.identifier("id")} ${e.raw(_)} NOT NULL, ${e.identifier("op")} ${e.raw(_)} NOT NULL, ${e.identifier("doc")} ${e.raw(E)})`);const c=a.indexKeyPrefix?.("string");await Xt(o,a,{columns:e`${c===void 0?e`${e.identifier("table")}`:e`${e.identifier("table")}(${e.raw(String(c))})`}, ${e.identifier("seq")}`,name:hi,table:W,unique:!1}),await j(o,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(st)} (${e.identifier("id")} ${e.raw(_)} NOT NULL PRIMARY KEY, ${e.identifier("lease_until")} ${e.raw(l)} NOT NULL)`),await j(o,a,e`INSERT INTO ${e.identifier(st)} (${e.identifier("id")}, ${e.identifier("lease_until")}) VALUES (${en}, ${0}) ${a.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${e.identifier("id")} = ${e.identifier("id")}`:e`ON CONFLICT(${e.identifier("id")}) DO NOTHING`}`)},zi=async(o,a,f)=>{const _=e`UPDATE ${e.identifier(st)} SET ${e.identifier("lease_until")} = ${f+Vi} WHERE ${e.identifier("id")} = ${en} AND ${e.identifier("lease_until")} <= ${f}`;if(a.supportsReturning)return(await b(o,a,e`${_} RETURNING ${e.identifier("id")}`)).length>0;const l=await j(o,a,_);return(a.affectedRows?a.affectedRows(l??{rowsAffected:0}):0)>0},Ji=async(o,a,f,_)=>{if(!await zi(o,a,_))return;const l=_-f;let E=!0;try{const c=await mi(o,a,W,ke);c!=="valid"&&(c==="invalid"&&await Si(o,a,W,ke),await Xt(o,a,{columns:e`${e.identifier("ts")}`,concurrently:!0,name:ke,table:W,unique:!1}))}catch(c){E=!1,console.warn(`[@lunora/sql-store] changelog retention could not build "${ke}"; sweeping without it.`,c)}E&&(await b(o,a,e`SELECT 1 AS ${e.identifier("hit")} FROM ${e.identifier(W)} WHERE ${e.identifier("ts")} <= ${l} LIMIT 1`)).length===0||await j(o,a,e`
2
+ DELETE FROM ${e.identifier(W)} WHERE ${e.identifier("seq")} IN (
3
+ SELECT ${e.identifier("seq")} FROM (
4
+ SELECT ${e.identifier("seq")} FROM ${e.identifier(W)} WHERE +${e.identifier("ts")} <= ${l} ORDER BY ${e.identifier("seq")} ASC LIMIT ${e.raw(String(Yi))}
5
+ ) AS ${e.identifier("expired")}
6
+ )
7
+ `)},tn=async(o,a)=>{const f=await b(o,a,e`SELECT MIN(${e.identifier("seq")}) AS ${e.identifier("seq")} FROM ${e.identifier(W)}`),_=Number(f[0]?.seq??Number.NaN);return Number.isFinite(_)?_:void 0},Zi=async(o,a)=>{if(a.name!=="sqlite")return;const f=await b(o,a,e`SELECT ${e.identifier("seq")} AS ${e.identifier("seq")} FROM ${e.identifier("sqlite_sequence")} WHERE ${e.identifier("name")} = ${W}`),_=Number(f[0]?.seq??Number.NaN);return Number.isFinite(_)?_:0},er=o=>JSON.stringify(Vt(o)?Yt(o):o),tr=(o,a,f,_,l)=>e`INSERT INTO ${e.identifier(W)} (${e.identifier("ts")}, ${e.identifier("table")}, ${e.identifier("id")}, ${e.identifier("op")}, ${e.identifier("doc")}) VALUES (${o}, ${a}, ${f}, ${_}, ${l===void 0?null:er(l)})`,nn=1e4,nr=1e3,ir=(o,a,f)=>{let _=a;for(const[l,E]of o.entries()){const c=Number(E.seq);if(c>_+1&&Number(E.ts)>f)return o.slice(0,l);_=c}return o},Cr=async(o,a,f)=>{const _=a.sinceSeq??0,l=Math.max(1,Math.min(a.limit??1e3,1e4)),E=await tn(o,f),c=await Zi(o,f);if(c!==void 0&&_>c)throw Dn(c,_,"global");if(E!==void 0&&Bn(E,_))throw Wn(E,_,"global");const q=await b(o,f,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(W)} WHERE seq > ${_} ORDER BY seq ASC LIMIT ${e.raw(String(l))}`),T=(f.name==="sqlite"?q:ir(q,_,(a.now??Date.now())-nn)).map(v=>{const{doc:A}=v,N={id:String(v.id),op:String(v.op),seq:Number(v.seq),table:String(v.table),ts:Number(v.ts)};return typeof A=="string"?{...N,doc:pi(A)}:N});return{changes:T,cursor:T.at(-1)?.seq??_}},Ut=(o,a)=>{const f=e.identifier(W),_=e`(SELECT MIN(v.seq) FROM ${f} v WHERE v.seq > ${o} AND v.seq - 1 > ${o} AND v.ts > ${a} AND NOT EXISTS (SELECT 1 FROM ${f} p WHERE p.seq = v.seq - 1))`;return e`${_} AS ${e.identifier("gap")}, (SELECT MAX(q.seq) FROM ${f} q WHERE q.seq > ${o} AND q.seq < ${_}) AS ${e.identifier("below")}`},Pt=(o,a,f)=>{const _=Number(a?.gap??Number.NaN);if(!Number.isFinite(_))return o;const l=Number(a?.below??Number.NaN);return Math.min(o,Number.isFinite(l)?l:f)},rr=o=>{const a=e.identifier(W),f=e.identifier("table");return e`SELECT ${f}, seq FROM (WITH RECURSIVE "t"("name") AS (SELECT MIN(${f}) FROM ${a} UNION ALL SELECT (SELECT MIN(${f}) FROM ${a} WHERE ${f} > "t"."name") FROM "t" WHERE "t"."name" IS NOT NULL) SELECT "t"."name" AS ${f}, (SELECT MAX(seq) FROM ${a} WHERE ${f} = "t"."name" AND seq > ${o}) AS seq FROM "t" WHERE "t"."name" IS NOT NULL) WHERE seq IS NOT NULL ORDER BY ${f}`},or=async(o,a,f,_={})=>{const l=e.identifier(W),E=f.name!=="sqlite",c=(_.now??Date.now())-nn;if(_.cursorOnly){const A=e`GREATEST((SELECT MAX(seq) FROM ${l}) - ${e.raw(String(nr))}, ${a})`,N=await b(o,f,e`SELECT MAX(seq) AS seq${E?e`, ${Ut(A,c)}`:e``} FROM ${l}`),B=Number(N[0]?.seq??a);return{cursor:Pt(Number.isFinite(B)?B:a,N[0],a),tables:[]}}const q=await b(o,f,E?e`SELECT ${e.identifier("table")} AS ${e.identifier("table")}, MAX(seq) AS seq, ${Ut(e`${a}`,c)} FROM ${l} WHERE seq > ${a} GROUP BY ${e.identifier("table")}`:rr(a));let M=a;const T=[];for(const A of q){const N=Number(A.seq);Number.isFinite(N)&&N>M&&(M=N),T.push(String(A.table))}M=Pt(M,q[0],a);const v=_.retained===!0?await tn(o,f):void 0;return{cursor:M,tables:T,...v===void 0?{}:{floor:v}}},sr=/string or blob too big/iu,ar=/row is too big/iu,cr=(o,a)=>{const{code:f,errno:_}=a,l=a instanceof Error?a.message:"";switch(o.name){case"mysql":return _===1118||f==="ER_TOO_BIG_ROWSIZE"?"InnoDB's per-row ceiling — roughly 8 KB, half a 16 KB page, for the part of the row stored inline":void 0;case"postgres":return ar.test(l)?"the 8 KB heap page a tuple must fit once its wide columns have been TOASTed out":void 0;default:return sr.test(l)?"the storage engine's per-row ceiling (2 MB on D1)":void 0}},dr=(o,a,f)=>{const _=cr(o,a);if(_!==void 0)throw new g("PAYLOAD_TOO_LARGE",`document is too large to store in "${f}": a single row cannot exceed ${_}. The limit is on the STORED bytes, which are UTF-8. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},it=16,Ht="__lunora_patch_if_match__",Kt=(o,a,f)=>{throw o.isUniqueViolation(a)?new ne(`unique constraint violation on "${f}"`,"unique"):(dr(o,a,f),a)},lr=o=>{const{code:a,errno:f}=o??{};return a==="40P01"||a==="40001"||f===1213||a==="ER_LOCK_DEADLOCK"},ur=o=>{throw lr(o)?new ne("the write's transaction was rolled back by a lock conflict with a concurrent write; retry it","occ"):o},rt=new WeakMap,jt=new WeakMap,de="superseded",fr=3e4,ge="__lunora_companion_fence",wr=(o,a,f,_,l)=>{const E=Math.max(1,Math.floor((Ii-2)/_.length)),c=(T,v)=>{const A=o.name==="postgres"?e`CAST(${T} AS ${e.raw(v.type)})`:e`${T}`;return e`${A} AS ${e.identifier(v.name)}`},q=T=>e`SELECT ${e.join(T.map((v,A)=>c(v,_[A])),e`, `)}`,M=[];for(let T=0;T<l.length;T+=E){const v=l.slice(T,T+E).map(A=>q(A));M.push(e`INSERT INTO ${e.identifier(a)} (${fe(_.map(A=>A.name))}) SELECT * FROM (${Ei(v)}) AS ${e.identifier("__rows__")} WHERE EXISTS (SELECT 1 FROM ${e.identifier(ge)} WHERE ${f})`)}return M},le=(o,a,f)=>JSON.stringify([o,a,f]),De=o=>JSON.stringify(o,(a,f)=>typeof f=="bigint"?`${String(f)}n`:f),hr=o=>{const a=Fn(o);return(f,_,l,E)=>_.some(c=>c instanceof Ri)?gi(o,f,_,l):a(f,_,l,E)},$r=o=>{const{crossShardCounter:a,crossShardReader:f,maxRelationKeys:_,schema:l}=o,E=bi(o.exec,o.queryTimeoutMs??Mi,o.queryTimer),{dialect:c}=o,q={fieldRef:t=>Be(c,t),rangeTypeGuard:(t,n)=>vi(c,t,n),...c.name==="mysql"?{containsExpr:(t,n)=>{const i=Lt(t);return i===void 0?e`LOCATE(${n}, ${t}) > 0`:e`LOCATE(${bt("mysql",n)}, ${i}) > 0`}}:{},...c.name==="postgres"?{containsExpr:(t,n)=>{const i=Lt(t);return i===void 0?e`strpos(${t}, ${n}) > 0`:e`strpos(${i}, ${bt("postgres",n)}) > 0`}}:{},...c.name==="sqlite"?{}:{inList:hr(c.name)}},M=new WeakMap,T=t=>{const n=M.get(t);if(n!==void 0)return n;const i={...q,serialize:(r,s)=>kt(c,s,r,d=>ce(t,s,d))};return M.set(t,i),i},v=(t,n)=>at(c.name,t,n),A=t=>{const n=fe(t.columns),i=Se(t.values),r=$=>c.name==="mysql"?e`VALUES(${e.identifier($)})`:e`excluded.${e.identifier($)}`,s=$=>c.name==="postgres"?e`${e.identifier(t.table)}.${e.identifier($)}`:e`${e.identifier($)}`,d=e.join(Object.entries(t.set(r,s)).map(([$,y])=>e`${e.identifier($)} = ${y}`),e`, `),u=c.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${d}`:e`ON CONFLICT(${e.identifier(t.conflictKey)}) DO UPDATE SET ${d}`;return e`INSERT INTO ${e.identifier(t.table)} (${n}) VALUES (${i}) ${u}`},N=o.clock??(()=>Date.now()),B=o.idGenerator??(()=>crypto.randomUUID()),G=o.cdc??!1,z=typeof o.cdcRetentionMs=="number"&&Number.isFinite(o.cdcRetentionMs)&&o.cdcRetentionMs>0?o.cdcRetentionMs:void 0,ie=o.auth??{identity:null,userId:null},we=(t,n,i,r)=>G?[tr(N(),t,n,i,r)]:[],rn=async()=>{if(!G||z===void 0)return;const t=N();if(!(t-xt<Xi)){xt=t;try{await Ji(E,c,z,t)}catch{}}},on=o.scheduler??qn;let ve=0;const re=o.provisionScope??{},F=async()=>{const t=rt.get(re);if(t)return t;const n=(async()=>{const i=o.exec;await Ai(i,l,c),await Ci(i,l,c),await Li(i,l,c),await mn(i,c),await Tn(E,l,c),G&&await Qi(i,c)})().catch(i=>{throw rt.delete(re),i});return rt.set(re,n),n},he=async t=>{if(typeof t!="string"||!Object.hasOwn(l.tables,t))throw new g("BAD_REQUEST",`ctx.db by-id write (table, id): "${t}" is not a table in this schema`);await F();const n=l.tables[t];return n!==void 0&&Wi(n)?t:void 0};let Ie=jt.get(re);Ie===void 0&&(Ie=new Map,jt.set(re,Ie));const U=Ie;let Fe=0;const dt={},xe=(t,n,i)=>{const r=(async()=>(await F(),await i(()=>U.get(t)?.run!==r)))(),s={definition:n,owner:dt,run:r,settled:!1};return r.then(d=>{d===de&&U.get(t)===s?U.delete(t):s.settled=!0},()=>{U.get(t)===s&&U.delete(t)}).catch(()=>{}),U.set(t,s),r},lt=async(t,n,i)=>{const r=U.get(t);if(r===void 0)return await xe(t,n,i);const s=r.definition===n;if(s&&(r.settled||r.owner===dt))return await r.run;if(r.settled)return await xe(t,n,i);let d;const u=new Promise(y=>{d=setTimeout(y,fr,"stalled")}),$=await Promise.race([r.run,u]).finally(()=>{clearTimeout(d)});return $!=="stalled"&&s?$:U.get(t)===r?await xe(t,n,i):await lt(t,n,i)},Ue=async(t,n,i)=>{const r=await lt(t,n,i);return r===de?await Ue(t,n,i):r},ut=async(t,n)=>{const i=U.get(t),r=i?.settled===!0&&i.definition===n?await i.run:void 0;if(typeof r=="boolean")return r;U.delete(t),Fe+=1},J=t=>{const n=l.tables[t];for(const i of n?.aggregateIndexes??[])U.delete(le("aggregate",t,i.name));for(const i of n?.rankIndexes??[])U.delete(le("rank",t,i.name))},sn=async(t,n)=>{const i=ae(t,n);return(await b(E,c,c.tableExists(i))).length>0},ft=async t=>{const{key:n}=c.companionTypes,i=B();await j(E,c,e`CREATE TABLE IF NOT EXISTS ${e.identifier(ge)} (${e.identifier("name")} ${e.raw(n)} PRIMARY KEY, ${e.identifier("token")} ${e.raw(n)} NOT NULL)`),await j(E,c,A({columns:["name","token"],conflictKey:"name",set:s=>({token:s("token")}),table:ge,values:[t,i]}));const r=e`${e.identifier("name")} = ${t} AND ${e.identifier("token")} = ${i}`;return{guardedDelete:()=>e`DELETE FROM ${e.identifier(t)} WHERE EXISTS (SELECT 1 FROM ${e.identifier(ge)} WHERE ${r})`,stillHeld:async()=>(await b(E,c,e`SELECT 1 FROM ${e.identifier(ge)} WHERE ${r}`)).length>0,guardedInsertRows:(s,d)=>wr(c,t,r,s,d)}},an=async(t,n,i)=>{const r=l.tables[t];if(!r||!await sn(t,n.name))return!1;const s=n.by??[],d=new Map;await Dt(E,c,r,t,R=>{if(n.where&&!Qe(R,n.where))return;const m=te(s,R);Ct(d,m,n,R)});const u=ae(t,n.name);if(i())return de;const $=await ft(u);await j(E,c,$.guardedDelete());const{integer:y,key:p,real:h}=c.companionTypes,w=$.guardedInsertRows([{name:"__key__",type:p},{name:"__value__",type:h},{name:"__count__",type:y}],[...d].map(([R,m])=>[R,m.value,m.count]));return i()||await Bt(E,c,w),i()||!await $.stillHeld()?de:!0},Ae=(t,n)=>Ue(le("aggregate",t,n.name),De(n),i=>an(t,n,i)),cn=async(t,n,i,r,s)=>{const d=new Map;let u,$=!0;for(;$;){const y=u===void 0?r:[...r,e`${e.identifier("id")} > ${u}`],p=y.length>0?e` WHERE ${e.join(y,e` AND `)}`:e``,h=await b(s,c,e`SELECT ${e.identifier("id")}, ${K(i.field??"")} FROM ${e.identifier(n)}${p} ORDER BY ${e.identifier("id")} ASC LIMIT ${e.raw(String(Ze))}`);for(const w of Mt(t,h))Ct(d,"",i,w);u=h.at(-1)?.id,$=h.length===Ze}return d.get("")?.value??null},dn=async(t,n,i,r)=>{const s=n.field??"",d=[],u=l.tables[t],$=(w,R)=>kt(c,w,R,m=>u?ce(u,w,m):Je(m));for(const w of n.by??[]){const R=$(w,i[w]??null);d.push(R===null?e`${K(w)} IS NULL`:e`${K(w)} = ${R}`)}for(const[w,R]of Object.entries(n.where??{})){const m=R!==null&&typeof R=="object"&&!Array.isArray(R)?R.eq:R,S=$(w,m),C=Be(c,w);d.push(S===null?e`${C} IS NULL`:e`${C} = ${S}`)}const y=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``;if(u&&Zt(u.shape[s]))return cn(u,t,n,d,r);const p=pe(n.op),h=await b(r,c,e`SELECT ${e.raw(p)}(${K(s)}) AS ${e.identifier("value")} FROM ${e.identifier(t)}${y}`);return ue(h[0]?.value)},ln=(t,n)=>e`DELETE FROM ${e.identifier(t)} WHERE ${e.identifier("__key__")} = ${n} AND ${e.identifier("__count__")} <= 0`,un=async(t,n,i,r,s)=>{const d=ae(t,n.name),{op:u}=n,$=n.field??"",y=i&&(!n.where||Qe(i,n.where))?i:void 0,p=r&&(!n.where||Qe(r,n.where))?r:void 0;if(!y&&!p)return[];if(u==="count"||u==="sum"||u==="avg"){const S=[],C=new Set,L=[];for(const[I,O]of[[y,-1],[p,1]]){if(!I)continue;const k=u==="count"?1:ze(I[$]);k!==void 0&&L.push({encoded:te(n.by??[],I),numeric:k,sign:O})}L.sort((I,O)=>I.encoded<O.encoded?-1:+(I.encoded>O.encoded));for(const{encoded:I,numeric:O,sign:k}of L)C.add(I),S.push(A({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(P,H)=>({__count__:e`${H("__count__")} + ${P("__count__")}`,__value__:u==="count"?e`${H("__value__")} + ${P("__value__")}`:e`COALESCE(${H("__value__")}, 0) + ${P("__value__")}`}),table:d,values:[I,k*O,k]}));for(const I of C)S.push(ln(d,I));return S}const h=[],w=[];let R,m;if(y){const S=te(n.by??[],y);R=S;const C=ze(y[$]),I=(await b(s,c,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(d)} WHERE ${e.identifier("__key__")} = ${S}`))[0],O=ue(I?.value),k=(I?.count??0)-1;if(k<=0)h.push(e`DELETE FROM ${e.identifier(d)} WHERE ${e.identifier("__key__")} = ${S}`);else if(I&&C!==void 0&&O!==null&&C===O){const P=await dn(t,n,y,s);h.push(e`UPDATE ${e.identifier(d)} SET ${e.identifier("__value__")} = ${P}, ${e.identifier("__count__")} = ${k} WHERE ${e.identifier("__key__")} = ${S}`)}else h.push(e`UPDATE ${e.identifier(d)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${S}`)}if(p){const S=te(n.by??[],p);m=S;const C=ze(p[$]);if(C===void 0)w.push(A({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(L,I)=>({__count__:e`${I("__count__")} + 1`}),table:d,values:[S,null,1]}));else{const L=u==="min"?"MIN":"MAX";w.push(A({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(I,O)=>({__count__:e`${O("__count__")} + 1`,__value__:e`${e.raw(L)}(COALESCE(${O("__value__")}, ${I("__value__")}), ${I("__value__")})`}),table:d,values:[S,C,1]}))}}return R!==void 0&&m!==void 0&&m<R?[...w,...h]:[...h,...w]},Ce=async t=>{const n=l.tables[t]?.aggregateIndexes;if(!(!n||n.length===0))for(const i of n)await Ae(t,i)},$e=async(t,n,i,r)=>{const s=l.tables[t]?.aggregateIndexes,d=[];if(!s||s.length===0)return d;for(const u of s)await ut(le("aggregate",t,u.name),De(u))&&d.push(...await un(t,u,n,i,r));return d},fn=async(t,n)=>{const i=Ee(t,n);return(await b(E,c,c.tableExists(i))).length>0},wn=async(t,n,i)=>{const r=l.tables[t];if(!r||!await fn(t,n.name))return!1;const s=Ee(t,n.name);if(i())return de;const d=await ft(s);await j(E,c,d.guardedDelete());const u=c.companionTypes.key,$=[{name:"__id__",type:u},{name:"__partition__",type:u},...n.sortBy.map((h,w)=>{const R=r.shape[h.field];return{name:me(w),type:c.columnType(R?ct(R):void 0)}})];let y=[];const p=async()=>{const h=y;y=[],!(h.length===0||i())&&await Bt(E,c,d.guardedInsertRows($,h))};return await Dt(E,c,r,t,async h=>{if(n.where&&!vt(h,n.where))return;const w=Oe(n.partitionBy??[],h),R=n.sortBy.map(m=>Je(h[m.field]??null));y.push([h._id,w,...R]),y.length>=Ze&&await p()}),await p(),i()||!await d.stillHeld()?de:!0},Pe=(t,n)=>Ue(le("rank",t,n.name),De(n),i=>wn(t,n,i)),Le=async t=>{const n=l.tables[t]?.rankIndexes;if(!(!n||n.length===0))for(const i of n)await Pe(t,i)},oe=async(t,n,i,r)=>{const s=l.tables[t],d=s?.rankIndexes,u=[];if(!d||d.length===0)return u;const $=s?.softDeleteMode?.field,y=$===void 0||r===void 0?void 0:r[$],p=y!=null;for(const h of d){if(i!==void 0&&r!==void 0&&xi(h,i,r)||!await ut(le("rank",t,h.name),De(h)))continue;const R=Ee(t,h.name);if(i&&u.push(e`DELETE FROM ${e.identifier(R)} WHERE ${e.identifier("__id__")} = ${n}`),r&&!p){if(h.where&&!vt(r,h.where))continue;const m=h.sortBy.map((I,O)=>me(O)),S=fe(["__id__","__partition__",...m]),C=Oe(h.partitionBy??[],r),L=h.sortBy.map(I=>Je(r[I.field]??null));u.push(e`INSERT INTO ${e.identifier(R)} (${S}) VALUES (${Se([n,C,...L])})`)}}return u},hn=(t,n,i)=>{const r=et(n);if(r===void 0||!i.dispatched){J(t);return}r.then(()=>{i.batched||J(t)},()=>{J(t)}).catch(()=>{})},se=async(t,n,i,r,s)=>{const d=l.tables[t],u=G||(d?.aggregateIndexes?.length??0)>0||(d?.rankIndexes?.length??0)>0,$=E.transaction===void 0||!u,y=async w=>{let R;try{R=await n(w)}catch(S){if(E.transaction===void 0&&S instanceof Ni){J(t);const C=()=>{J(t)};et(S)?.then(C,C).catch(()=>{})}throw S}if(!R)return!1;const m={batched:!1,dispatched:!1};try{$&&s.length>0&&await Ot(w,c,s);const S=$?await i(w):[...await i(w),...s];S.length>0&&(m.batched=w.batch!==void 0&&c.name==="sqlite",m.dispatched=!0,await Ot(w,c,S))}catch(S){throw E.transaction===void 0&&hn(t,S,m),$&&await Re(t,r,async()=>{throw await Promise.resolve(),S}),S}return!0};let p;const h=Fe;try{p=E.transaction!==void 0&&u?await E.transaction(y).catch(ur):await y(E),p&&Fe!==h&&E.transaction!==void 0&&u&&J(t)}catch(w){const R=et(w);if(R!==void 0){const m=async()=>{await vn({dialect:c,exec:E,schema:l},t,r)};R.then(m,m).catch(()=>{})}throw w}return p&&await Re(t,r,rn),p},_e=gn({dialect:c,exec:E,schema:l}),wt=new Set;for(const[t,n]of Object.entries(l.tables))for(const i of Object.values(n.triggerMap??{}))wt.add(`${t} ${i.timing} ${i.op}`);const Y=(t,n,i)=>wt.has(`${t} ${n} ${i}`);let ht;const X=async(t,n,i)=>{if(ve+=1,ve>Ft)throw ve-=1,new ne(`trigger recursion exceeded ${String(Ft)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await ni({ctx:ht,event:i,op:n,schema:l,tableName:i.table,timing:t})}finally{ve-=1}},$n=async(t,n,i=E)=>{try{await j(i,c,n)}catch(r){Kt(c,r,t)}},be=async(t,n)=>(await b(E,c,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} = ${n}`))[0],$t=async(t,n,i,r,s,d)=>{const u=e`${e.identifier(ye)}`,$=e.join([v(e`${e.identifier("id")}`,r.id),v(u,r[ye]??null),...s===void 0?[]:[e`(${s})`]],e` AND `),y=n==="UPDATE"?e`UPDATE ${e.identifier(t)} SET ${i}, ${u} = ${Nt.sql(u)} WHERE ${$}`:e`DELETE FROM ${e.identifier(t)} WHERE ${$}`;try{if(c.supportsReturning)return(await b(d,c,e`${y} RETURNING ${e.identifier("id")}`)).length>0;const p=await j(d,c,y);return(c.affectedRows?c.affectedRows(p??{rowsAffected:0}):0)>0}catch(p){return Kt(c,p,t)}},He=async(t,n,i,r,s)=>{if(r!==void 0&&!await $t(t,n,i,r,void 0,s))throw new ne(`optimistic concurrency conflict on "${t}" — the row changed during this mutation; refetch and retry`,"occ")},Ke=(t,n=t?._creationTime)=>({_creationTime:n,[ye]:Nt.value(t?.[ye])}),_t=async(t,n,i,r,s,d,u)=>{const $=Q(n,s);if(!$||s===void 0)throw new g("INTERNAL",`document not found: ${i}`);const y=ri(n,r,$),p={...$,...oi(y),_id:i};tt(n,y,p,ie);const h=Ye(n,p,{only:new Set(Object.keys(y)),previous:()=>$,tolerateStoredNull:!0});nt(c.name,Object.fromEntries(Object.keys(y).map(S=>[S,h[S]]))),si(u,$,h),Y(t,"before","update")&&await X("before","update",{doc:{...h},id:i,op:"update",previous:$,table:t}),await Ce(t),await Le(t);const w=Object.keys(n.shape),R=e.join(w.map(S=>e`${e.identifier(S)} = ${ce(n,S,h[S]??null)}`),e`, `);if(await se(t,async S=>await $t(t,"UPDATE",R,s,d,S),async S=>[...await $e(t,$,h,S),...await oe(t,i,$,h)],i,we(t,i,"update",h)))return await _e(t,i,{document:h,previous:$,written:Ke(s)}),Y(t,"after","update")&&await X("after","update",{doc:h,id:i,op:"update",previous:$,table:t}),h},_n=(t,n,i,r)=>{const s=Object.keys(t.shape);return{columns:["id","_creationTime",...s],values:[n,i,...s.map(d=>ce(t,d,r[d]??null))]}},En=async(t,n,i,r)=>{const s=ci(n,i.op,i.field,r.by,r.where);if(!s||!await Ae(t,s.index))return;const u=ae(t,s.index.name),$=Object.keys(s.partial);if($.length===(s.index.by??[]).length&&$.length>0){const p=te(s.index.by??[],s.partial),h=await b(E,c,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(u)} WHERE ${e.identifier("__key__")} = ${p}`);if(h.length===0)return[];const w=h[0];return[{key:{...s.partial},value:Xe(i.op,{count:w.count,value:ue(w.value)})}]}return $.length>0?void 0:(await b(E,c,e`SELECT ${e.identifier("__key__")} AS ${e.identifier("key")}, ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(u)}`)).map(p=>{const h=p;return{key:yi(JSON.parse(h.key)),value:Xe(i.op,{count:h.count,value:ue(h.value)})}})},Et=t=>{const n=l.tables[t]?.shardMode?.kind;return n==="shardBy"||n==="root"},pt=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`)},pn=(t,n)=>{if(n?.relationMask!==void 0&&n.with!==void 0&&Object.keys(n.with).length>0)throw new g("MASK_UNSUPPORTED",`masking cannot follow a nested \`with\` across the cross-shard relation hop to "${t}" — the nested rows are hydrated on the serving shard, where the mask policy does not exist. Read the nested relation at its own (masked) call site instead.`);const i={};if(n?.relationBaseWhere)for(const r of Object.keys(l.tables)){const s=n.relationBaseWhere(r);s!==void 0&&(i[r]=s)}return{orderBy:n?.orderBy,relationPolicies:i,where:x(n?.baseWhere,n?.where),with:n?.with}},je=(t,n)=>Et(t)?f?f(t,pn(t,n)):pt(t):V.findMany(t,n),Me=(t,n,i)=>ai(t,{fetcher:je,maxRelationKeys:_,relationBaseWhere:i,schema:l,tableName:n}),yn=Oi(async(t,n)=>{const i=await b(E,c,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} IN (${Se(n)})`),r=new Map;for(const s of i){const{id:d}=s;typeof d=="string"&&r.set(d,s)}return r}),yt=async(t,n,i)=>{const{fetchLimit:r,limit:s,orderKeys:d,predicate:u}=await di(n,i,{fetcher:je,maxRelationKeys:_,schema:l,tableName:t}),$=ee(u,T(n)),y=Di(d,c);let p=e`SELECT * FROM ${e.identifier(t)}`;return $&&(p=e`${p} WHERE ${$}`),p=e`${p} ORDER BY ${y}`,r!==void 0&&(p=e`${p} LIMIT ${e.raw(String(r))}`),{limit:s,orderKeys:d,query:p}},Rn=kn(l);let Rt;const mt=async()=>{const{primary:t}=o.exec;if(t!==void 0)return await F(),Rt??=$r({...o,exec:t,provisionScope:re}),Rt},V={relationWrites:Rn,async cdcChangedTables(t,n){if(G)try{return await F(),await or(E,t,c,{...n,now:N(),retained:z!==void 0})}catch{return}},async aggregate(t,n){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);if(await F(),pe(n.op),n.op==="count")return V.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=qe(i.softDeleteMode,void 0),s=x(x(n.baseWhere,n.where),r),d=await Me(s,t,n.relationBaseWhere),u=d!==s;if(i.aggregateIndexes&&!n.baseWhere&&!u&&!r){const R=ti(i.aggregateIndexes,n.op,n.field,n.where);if(R&&await Ae(t,R.index)){const S=te(R.index.by??[],R.key),C=ae(t,R.index.name),I=(await b(E,c,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(C)} WHERE ${e.identifier("__key__")} = ${S}`))[0];return Xe(n.op,I===void 0?void 0:{count:I.count,value:ue(I.value)})}}ot(i,n.field,`aggregate(${t}, { op: "${n.op}", field: "${n.field}" })`);const $=ee(d,T(i)),y=e.raw(pe(n.op)),p=e`SELECT ${y}(${K(n.field)}) AS ${e.identifier("value")} FROM ${e.identifier(t)}`,w=(await b(E,c,$?e`${p} WHERE ${$}`:p))[0]?.value;return w==null?null:Number(w)},async count(t,n){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await F();const r=Zn(n);if(r.restrictsCounts)throw new Tt(t);const s=qe(i.softDeleteMode,void 0),d=x(x(r.baseWhere,r.where),s),u=await Me(d,t,r.relationBaseWhere),$=u!==d;if(i.aggregateIndexes&&!r.baseWhere&&!$&&!s){const w=ei(i.aggregateIndexes,r.where);if(w&&await Ae(t,w.index)){const m=te(w.index.by??[],w.key),S=ae(t,w.index.name),C=await b(E,c,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")} FROM ${e.identifier(S)} WHERE ${e.identifier("__key__")} = ${m}`);return Number(C[0]?.value??0)}}const y=ee(u,T(i)),p=e`SELECT COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(t)}`,h=await b(E,c,y?e`${p} WHERE ${y}`:p);return Number(h[0]?.count??0)},async delete(t,n,i){const r=await he(t);if(!r)return;const s=l.tables[r];if(!s)return;const d=await be(r,n);if(d===void 0)return;const u=Q(s,d),$=i?.hard===!0,y=!$&&s.softDeleteMode?s.softDeleteMode.field:void 0;if(!(y&&(!u||u[y]!==null&&u[y]!==void 0))){if(Y(r,"before","delete")&&await X("before","delete",{id:n,op:"delete",previous:u??void 0,table:r}),i?.skipOnDelete!==!0&&await Jn({deletedId:n,deletedReference:p=>u?.[p],findHolders:async(p,h,w,R)=>{if(l.tables[p]?.shardMode?.kind==="shardBy")throw new g("INTERNAL",`cross-backend cascade from global '${r}' into shardBy '${p}' is not supported — would require Query Coordinator fan-out across shards`);return(await V.findMany(p,{...R,includeDeleted:$,where:{[h]:w}})).page},onCascade:(p,h)=>V.delete(p,h,i),onRestrict:p=>{throw new ne(p,"restrict")},onSetNull:(p,h,w)=>V.patch(p,h,{[w]:null}),schema:l,tableName:r}),await Ce(r),await Le(r),y&&u){const p={[y]:N()},h={...u,...p};tt(s,p,h,ie);const w=e.join(Object.keys(s.shape).map(R=>e`${e.identifier(R)} = ${ce(s,R,h[R]??null)}`),e`, `);await se(r,async R=>(await He(r,"UPDATE",w,d,R),!0),async R=>[...await $e(r,u,h,R),...await oe(r,n,u,void 0)],n,we(r,n,"update",h)),await _e(r,n,{document:h,previous:u,written:Ke(d)}),Y(r,"after","delete")&&await X("after","delete",{id:n,op:"delete",previous:u,table:r});return}await se(r,async p=>(await He(r,"DELETE",void 0,d,p),!0),async p=>[...await $e(r,u??void 0,void 0,p),...await oe(r,n,u??void 0,void 0)],n,we(r,n,"delete")),await Re(r,n,async()=>{await _e(r,n,void 0),Y(r,"after","delete")&&await X("after","delete",{id:n,op:"delete",previous:u??void 0,table:r})})}},async findFirst(t,n={}){if(n.consistency==="primary"){const r=await mt();if(r!==void 0)return r.findFirst(t,n)}return(await V.findMany(t,{...n,limit:1})).page[0]??null},async findFirstOrThrow(t,n={}){const i=await V.findFirst(t,n);if(i===null)throw new zn(`findFirstOrThrow: no "${t}" document matched`);return i},async findMany(t,n={}){if(n.consistency==="primary"){const h=await mt();if(h!==void 0)return h.findMany(t,n)}const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await F();const r=async(h,w,R,m)=>{if(Et(h))return a?li(a,h,w,R,m):pt(h);const S=l.tables[h];if(!S)throw new g("INTERNAL",`unknown table: ${h}`);const C=qe(S.softDeleteMode,void 0),L={[w]:{in:R}},I=x(x(L,m),C),O=await Me(I,h,void 0),k=ee(O,T(S)),P=K(w);let H=e`SELECT ${P} AS __fk__, COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(h)}`;k&&(H=e`${H} WHERE ${k}`),H=e`${H} GROUP BY ${P}`;const Ne=await b(E,c,H),Z=new Map;for(const D of Ne)Z.set(D.__fk__,Number(D.count??0));return Z},{limit:s,orderKeys:d,query:u}=await yt(t,i,n),$=await b(E,c,u),y=Mt(i,$),p=Vn(y,{endCursor:n.endCursor,limit:s,omitContinueCursor:n.omitContinueCursor,orderKeys:d});return n.with&&await Yn({fetcher:je,groupedCounter:r,parents:p.page,...Xn(n),schema:l,tableName:t,with:n.with}),{...p,page:Qn(p.page,n.select,n.with)}},async explain(t,n={}){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await F();const{query:r}=await yt(t,i,n),s=c.name==="sqlite"?"EXPLAIN QUERY PLAN":"EXPLAIN",d=await b(E,c,e`${e.raw(s)} ${r}`),{params:u,sql:$}=c.render(r);return{params:u,plan:d.map(y=>Bi(y)),sql:$}},async get(t,n){const i=Object.hasOwn(l.tables,t)?l.tables[t]:void 0;if(!i)throw new g("BAD_REQUEST",`ctx.db.get(table, id): "${t}" is not a table in this schema`);return i.shardMode!==void 0&&i.shardMode.kind!=="global"?null:(await F(),Q(i,await yn.load(t,n)))},async groupBy(t,n){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await F();const r=n.agg??{op:"count"};if(pe(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 s=qe(i.softDeleteMode,void 0),d=x(x(n.baseWhere,n.where),s),u=await Me(d,t,n.relationBaseWhere),$=u!==d;if(i.aggregateIndexes&&!n.baseWhere&&!$&&!s){const m=await En(t,i.aggregateIndexes,r,n);if(m!==void 0)return m}Gi(i,t,n.by,r);const y=ee(u,T(i)),p=n.by.map(m=>e`${K(m)} AS ${e.identifier(m)}`);if(r.op==="count")p.push(e`COUNT(*) AS ${e.identifier("value")}`);else{if(!r.field)throw new g("INTERNAL",`groupBy(${t}, { agg: { op: "${r.op}" } }): "field" is required for non-count reducers`);p.push(e`${e.raw(pe(r.op))}(${K(r.field)}) AS ${e.identifier("value")}`)}const h=e.join(n.by.map(m=>K(m)),e`, `);let w=e`SELECT ${e.join(p,e`, `)} FROM ${e.identifier(t)}`;y&&(w=e`${w} WHERE ${y}`),w=e`${w} GROUP BY ${h}`;const R=await b(E,c,w);return Fi(i,n.by,R)},async insert(t,n,i){const r=l.tables[t];if(!r)throw new g("INTERNAL",`unknown table: ${t}`);await F();const s=Ye(r,Kn(r,n,ie),{supplied:n,trusted:i?.allowExplicitId===!0});nt(c.name,s);let d;i?.clientId!==void 0?(jn(i.clientId),d=i.clientId):i?.allowExplicitId&&typeof s._id=="string"?(Gn(s._id),d=s._id):d=B();const u=i?.allowExplicitId&&typeof s._creationTime=="number"?s._creationTime:N(),$={...s,_creationTime:u,_id:d};Y(t,"before","insert")&&await X("before","insert",{doc:{...$},id:d,op:"insert",table:t}),await Ce(t),await Le(t);const{columns:y,values:p}=_n(r,d,u,s);return await se(t,async h=>(await $n(t,e`INSERT INTO ${e.identifier(t)} (${fe(y)}) VALUES (${Se(p)})`,h),!0),async h=>[...await $e(t,void 0,$,h),...await oe(t,d,void 0,$)],d,we(t,d,"insert",$)),await Re(t,d,async()=>{await _e(t,d,{document:$,written:{_creationTime:u,[ye]:null}}),Y(t,"after","insert")&&await X("after","insert",{doc:$,id:d,op:"insert",table:t})}),d},normalizeId(t,n){return Hn(l,t,n)},async patch(t,n,i,r){Ve("patch",i);const s=await he(t);if(!s)throw new g("INTERNAL",`document not found: ${n}`);const d=l.tables[s];if(!d)throw new g("INTERNAL",`document not found: ${n}`);const u=Pn(d,i)?it:1;for(let $=0;$<u;$+=1){const y=await be(s,n);if(await _t(s,d,n,i,y,void 0,r))return}throw new ne(`optimistic concurrency conflict on "${s}" — the row changed during this mutation; refetch and retry`,"occ")},async patchIf(t,n,i){Ve("patchIf",i.patch);const r=await he(t),s=r===void 0?void 0:l.tables[r];if(r===void 0||!s)return{applied:!1,doc:null};const d=r,u=ee(i.where,T(s))??e`1 = 1`;for(let $=0;$<it;$+=1){const[y]=await b(E,c,e`SELECT *, CASE WHEN (${u}) THEN 1 ELSE 0 END AS ${e.identifier(Ht)} FROM ${e.identifier(d)} WHERE ${e.identifier("id")} = ${n}`);if(y===void 0)return{applied:!1,doc:null};const{[Ht]:p,...h}=y;if(Number(p)!==1)return{applied:!1,doc:Q(s,h)??null};const w=await _t(d,s,n,i.patch,h,u,{verify:i.verify});if(w)return{applied:!0,doc:w}}throw new ne(`patchIf on "${d}" lost the row to concurrent writes ${String(it)} times in a row; retry the operation`,"occ")},async restore(t,n){const i=await he(t),r=i===void 0?void 0:await be(i,n);if(!i||r===void 0)throw new g("INTERNAL",`document not found: ${n}`);const s=l.tables[i],d=s?.softDeleteMode?.field;if(!s||!d)throw new g("INTERNAL",`ctx.db.restore: table "${i}" is not a .softDelete() table`);const u=r[d]!==null&&r[d]!==void 0;if(await V.patch(t,n,{[d]:null}),u){const $=Q(s,r);$!==null&&await se(i,async()=>await Promise.resolve(!0),async()=>await oe(i,n,void 0,{...$,[d]:null}),n,[]).catch(y=>{throw E.transaction!==void 0&&J(i),y})}},query(t){const n=l.tables[t];if(!n)throw new g("INTERNAL",`unknown table: ${t}`);const i="the legacy query()/withIndex() reader is not available on the D1 (global) backend; use findMany",r=[];let s=0,d;const u=c.name!=="mysql",$={...T(n),fieldRef:w=>e`m.${K(w)}`,rangeTypeGuard:()=>{throw new g("INTERNAL","a path range is never pushed into a search")}},y=w=>r.every(R=>R(w)),p=async(w,R)=>{await F();const m=2*Ln+w.filters.length,S=d===void 0?void 0:ee(d,$,void 0,m),C=S!==void 0&&c.name==="sqlite"&&c.render(S).params.length+m>_i.boundParams,L=C?void 0:S,I=s>0||C,O=await bn(E,c,n,t,L===void 0?w:{...w,scope:L},Mn(I?void 0:R));!I&&R===void 0&&Nn(O);const k=O.filter(P=>y(P));return R===void 0?k:k.slice(0,R)},h=w=>{const R={async*[Symbol.asyncIterator](){if(!w)throw new g("INTERNAL",i);yield*await p(w,void 0)},async collect(){if(!w)throw new g("INTERNAL",i);return p(w,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(m){r.push(m);const S=ui(m);return S!==void 0&&fi(S,n.shape,u)?d=x(d,S):s+=1,R},async first(){if(!w)throw new g("INTERNAL",i);return(await p(w,1))[0]??null},order(){return R},async paginate(m){if(!w)throw new g("INTERNAL",i);const S=An(m);return Cn(await p(w,On(S)),S)},async take(m){if(!w)throw new g("INTERNAL",i);return p(w,m)},async unique(){if(!w)throw new g("INTERNAL",i);const m=await p(w,2);if(m.length>1)throw new $i(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(){throw new g("INTERNAL",`geo indexes are not supported on \`.global()\` tables (table "${t}") — geospatial queries run only on sharded tables`)},withIndex(){throw new g("INTERNAL",i)},withSearchIndex(m,S){const C=(n.searchIndexes??[]).find(I=>I.name===m);if(!C)throw new g("INTERNAL",`unknown search index "${m}" on table "${t}"`);const L={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:m,query:""};if(S(In(L,t,Sn(C.language))),!L.hasQuery)throw new g("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return h(L)}};return R};return h(void 0)},async rank(t,n,i){const r=l.tables[t];if(!r)throw new g("INTERNAL",`unknown table: ${t}`);const s=r.rankIndexes?.find(O=>O.name===n);if(!s)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(i.restrictsCounts)throw new Tt(t);if(await F(),!await Pe(t,s))return null;const u=typeof i.row=="string"?i.row:i.row._id;if(!u)return null;const $=Ee(t,s.name),y=s.sortBy.map((O,k)=>me(k)),p=fe(["__partition__",...y]),w=(await b(E,c,e`SELECT ${p} FROM ${e.identifier($)} WHERE ${e.identifier("__id__")} = ${u}`))[0];if(!w)return null;const R=w.__partition__,m=x(i.baseWhere,i.where);St(m,l,t,"rank");const S=gt(s,m);if(S&&Oe(s.partitionBy??[],S)!==R)return null;const C=Ui(c.name,s,y,w,u),L=await b(E,c,e`SELECT COUNT(*) AS c FROM ${e.identifier($)} WHERE ${e.identifier("__partition__")} = ${R} AND (${C})`),I=await b(E,c,e`SELECT COUNT(*) AS c FROM ${e.identifier($)} WHERE ${e.identifier("__partition__")} = ${R}`);return{position:Number(L[0]?.c??0)+1,total:Number(I[0]?.c??0)}},async rankPage(t,n,i={}){St(x(i.baseWhere,i.where),l,t,"rankPage");const r=l.tables[t];if(!r)throw new g("INTERNAL",`unknown table: ${t}`);const s=r.rankIndexes?.find(D=>D.name===n);if(!s)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(await F(),!await Pe(t,s))return{continueCursor:null,isDone:!0,page:[]};const u=Ee(t,s.name),$=s.sortBy.map((D,Ge)=>me(Ge)),y=Math.max(1,Math.min(1e3,Math.floor(i.take??100))),p=x(i.baseWhere,i.where),h=gt(s,p),w=Hi(s,$),R=e.join(w.flatMap(D=>zt(c,{direction:D.direction,field:D.column,nullable:D.nullable})),e`, `),m=[];typeof i.partitionKey=="string"?m.push(e`${e.identifier("__partition__")} = ${i.partitionKey}`):h&&m.push(e`${e.identifier("__partition__")} = ${Oe(s.partitionBy??[],h)}`);const S=Un(i);if(S!==void 0){const D=Pi(c.name,w,S);D!==void 0&&m.push(D)}const C=fe([Te,"__partition__",...$]);let L=e`SELECT ${C} FROM ${e.identifier(u)}`;m.length>0&&(L=e`${L} WHERE ${e.join(m,e` AND `)}`),L=e`${L} ORDER BY ${R} LIMIT ${e.raw(String(y+1))}`;const I=await b(E,c,L),O=I.length>y,k=O?I.slice(0,y):I,P=k.map(D=>D[Te]),H=await Ki(E,c,r,t,P);let Ne=null;const Z=k.at(-1);if(O&&Z!==void 0){const D=[Z.__partition__,...$.map(Ge=>Z[Ge]),Z[Te]];Ne=ji(D)}return{continueCursor:Ne,isDone:!O,page:H}},async replace(t,n,i,r){Ve("replace",i);const s=await he(t);if(!s)throw new g("INTERNAL",`document not found: ${n}`);const d=l.tables[s];if(!d)throw new g("INTERNAL",`document not found: ${n}`);const u=await be(s,n);if(u===void 0)throw new g("INTERNAL",`document not found: ${n}`);const y=xn(l,s,"update")||(d.aggregateIndexes??[]).length>0||(d.rankIndexes??[]).length>0?Q(d,u)??void 0:void 0,p=r?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,h=typeof u._creationTime=="number"?u._creationTime:void 0,w=p??h??N(),R={...i,_creationTime:w,_id:n};tt(d,i,R,ie);const m=Ye(d,R,{previous:()=>y??Q(d,u)??void 0,supplied:i,trusted:r?.allowExplicitId===!0});nt(c.name,m),Y(s,"before","update")&&await X("before","update",{doc:{...m},id:n,op:"update",previous:y,table:s}),await Ce(s),await Le(s);const S=Object.keys(d.shape),C=e.join([e`${e.identifier("_creationTime")} = ${w}`,...S.map(L=>e`${e.identifier(L)} = ${ce(d,L,m[L]??null)}`)],e`, `);await se(s,async L=>(await He(s,"UPDATE",C,u,L),!0),async L=>[...await $e(s,y,m,L),...await oe(s,n,y,m)],n,we(s,n,"update",m)),await Re(s,n,async()=>{await _e(s,n,{document:m,previous:y,written:Ke(u,w)}),Y(s,"after","update")&&await X("after","update",{doc:m,id:n,op:"update",previous:y,table:s})})}};return ht={db:V,scheduler:on},V};export{$r as createSqlCtxDb,Mr as decodeGlobalRow,or as readSqlCdcChangedTables,Cr as readSqlCdcChanges,tn as readSqlCdcFloor,Qi as runSqlCdcMigration,Ji as sweepSqlCdcRetention};
@@ -0,0 +1 @@
1
+ import{LunoraError as I}from"@lunora/errors";import{aggregateTableName as J,rankTableName as nn,sortColumnName as C,bigintSqlKey as en}from"@lunora/shard-engine";import{sql as i}from"drizzle-orm";import{b as tn,e as g,B as v,r as rn,i as on,U as sn,c as an}from"./value-codec-CbyTgWR3.mjs";import{q as m,c as $,a as un,O as A,z as ln,s as fn,t as cn,M as U,e as y,j as d,y as dn}from"./sql-exec-enIOMsv0.mjs";const $n=new Set(["any","null"]),M=(e,n)=>{const t=n.kindOf(e);return t!==void 0&&$n.has(t)||n.nullableOf(e)?!0:t==="union"&&(n.membersOf(e)??[]).some(r=>M(r,n))},R=e=>{const n=e._meta?.inner;return e.kind==="optional"&&n?R(n):e},N=e=>M(e,{kindOf:tn,membersOf:n=>R(n)._meta?.members,nullableOf:n=>R(n)._meta?.column?.notNull===!1}),B=(e,n,t=!1)=>n.columnType(g(e),{unique:t||e._meta?.column?.unique===!0}),D=new Set,F=e=>D.has(e)?!1:(D.add(e),!0),L=(e,n)=>{F(e)&&console.warn(`[@lunora/sql-store] ${n}`)},P=(e,n,t,r)=>{F(`backfill:${e}.${n}`)&&console.error(`[@lunora/sql-store] ${t}`,{column:n,error:r,table:e})},mn=e=>{const n=e._meta?.column;return n?.defaultFn?n.defaultFn():n&&"defaultValue"in n?n.defaultValue:void 0},En=(e,n,t)=>t._meta?.column?.unique===!0||e.indexes.some(r=>r.unique===!0&&r.fields.includes(n)),gn=(e,n,t,r)=>{if(r.kind==="optional"||N(r))return;const s=r._meta?.column;if(En(n,t,r))return{reason:"is unique, so one default cannot be written to every row"};if(s?.defaultFn===void 0&&s?.defaultValue===void 0)return{reason:"has no default"};let o;const a=()=>{try{const u=mn(r);if(u===void 0){L(`backfill:${e}.${t}`,`the default of "${e}.${t}" produced no value, so rows written before it read NULL. Run UPDATE "${e}" SET "${t}" = … WHERE "${t}" IS NULL.`);return}return i`UPDATE ${i.identifier(e)} SET ${i.identifier(t)} = ${fn(n,t,u)} WHERE ${i.identifier(t)} IS NULL`}catch(u){P(e,t,`could not compute the default of "${e}.${t}" (${u instanceof Error?u.message:String(u)}); rows written before it read NULL. Run UPDATE "${e}" SET "${t}" = … WHERE "${t}" IS NULL.`,u);return}};return{build:()=>(o??={query:a()},o.query)}},wn=async(e,n,t,r,s)=>{try{await $(e,n,s)}catch(o){P(t,r,`could not backfill "${t}.${r}" from its default (${o instanceof Error?o.message:String(o)}); rows written before it read NULL. Run UPDATE "${t}" SET "${r}" = … WHERE "${r}" IS NULL.`,o)}},hn=(e,n)=>[[A,n.companionTypes.integer],...Object.entries(e.shape).filter(([,t])=>t._meta?.column!==void 0).map(([t,r])=>[t,B(r,n),r])],O=async(e,n,t,r)=>{try{return await m(e,n,i`SELECT ${i.join(r.map(o=>ln("t",o)),i`, `)} FROM ${i.identifier(t)} AS ${i.identifier("t")} LIMIT 0`),!0}catch{return!1}},b=async(e,n,t,r,s,o)=>{if(await O(e,n,t,[r]))return"present";const a=i`ALTER TABLE ${i.identifier(t)} ADD COLUMN ${i.identifier(r)} ${i.raw(s)}`,u=o?.();try{return await un(e,n,u===void 0?[a]:[a,u]),u===void 0?"added":"filled"}catch(l){if(await O(e,n,t,[r]))return"raced";if(u===void 0)throw l}return b(e,n,t,r,s)},pn=async(e,n,t,r,s,o,a)=>{const u=a===void 0?void 0:gn(n,t,s,a),l=await b(e,r,n,s,o,u!==void 0&&"build"in u?u.build:void 0);if(u===void 0||l==="present"||l==="filled")return;if("reason"in u){l==="added"&&L(`backfill:${n}.${s}`,`"${n}.${s}" was added as a required field that ${u.reason}, so rows written before it read NULL. Backfill it with a migration (UPDATE "${n}" SET "${s}" = … WHERE "${s}" IS NULL).`);return}const f=u.build();f!==void 0&&await wn(e,r,n,s,f)},Tn=async(e,n,t,r)=>{const s=hn(t,r);if(!await O(e,r,n,s.map(([o])=>o)))for(const[o,a,u]of s)await pn(e,n,t,r,o,a,u)},_n=(e,n,t)=>{const r=typeof t.charset=="string"?` CHARACTER SET ${t.charset} COLLATE ${String(t.collation)}`:"";return`ALTER TABLE \`${e}\` MODIFY COLUMN \`${n}\` ${String(t.type)}${r} NULL`},yn=async(e,n,t,r)=>{if(r.name==="sqlite")return;const s=Object.keys(t.shape).filter(o=>{const a=t.shape[o];return a._meta?.column?.notNull===!0&&a.kind!=="optional"&&N(a)});if(s.length!==0)try{const o=r.name==="postgres"?i`column_name AS ${i.identifier("name")}`:i`column_name AS ${i.identifier("name")}, column_type AS ${i.identifier("type")}, character_set_name AS ${i.identifier("charset")}, collation_name AS ${i.identifier("collation")}`,a=r.name==="postgres"?i`table_schema = ANY (current_schemas(false))`:i`table_schema = DATABASE()`,u=await m(e,r,i`SELECT ${o} FROM information_schema.columns WHERE ${a} AND table_name = ${n} AND is_nullable = 'NO' AND column_name IN (${i.join(s.map(l=>i`${l}`),i`, `)})`);for(const l of u){const f=String(l.name);if(r.name==="postgres"){await $(e,r,i`ALTER TABLE ${i.identifier(n)} ALTER COLUMN ${i.identifier(f)} DROP NOT NULL`);continue}L(`${n}.${f}`,`"${n}"."${f}" accepts null in the schema but its column is NOT NULL, so writing null there fails. Relaxing it on MySQL can rebuild the table, so it is not done at startup; run this once, in a maintenance window: ${_n(n,f,l)};`)}}catch(o){L(`${n}:relax-failed`,`could not relax NOT NULL on the null-accepting columns of "${n}" (${s.join(", ")}): ${o instanceof Error?o.message:String(o)}. Writing null to them fails until the constraint is dropped by hand.`)}},j=e=>{const n=new Set;for(const t of e.indexes)t.unique===!0&&t.fields.length===1&&n.add(t.fields[0]);return n},Ln=(e,n,t)=>{if(t.indexKeyPrefix!==void 0)for(const r of n.indexes){if(r.unique!==!0||r.fields.length<=1)continue;const s=r.fields.filter(o=>{const a=n.shape[o];return a!==void 0&&t.indexKeyPrefix?.(g(a))!==void 0});if(s.length>0)throw new Error(`${e}.${r.name}: a composite unique index cannot cover ${s.join(", ")} in full on this engine (its key limit forces a prefix, which would constrain the prefix rather than the value). Split it into single-column unique indexes, or store those fields as a bounded type.`)}},Sn=e=>e._meta?.column?.notNull===!0&&e.kind!=="optional"&&!N(e),An=(e,n,t)=>{const r=[],s=j(n);for(const[l,f]of Object.entries(n.shape)){if(!f._meta?.column)continue;const c=Sn(f)?" NOT NULL":"";r.push(i`${i.identifier(l)} ${i.raw(`${B(f,t,s.has(l))}${c}`)}`)}const o=[...t.frameworkColumns().map(l=>i`${i.identifier(l.name)} ${i.raw(l.type)}`),i`${i.identifier(A)} ${i.raw(t.companionTypes.integer)}`],a=o.length+r.length,u=t.maxTableColumns;if(u!==void 0&&a>u){const l=a-1===u,f="Move one or more fields into a single object field, or split the table — either way the existing rows need a data migration (`defineMigration` + `lunora migrate up`); there is no in-place path.";throw new I("VALIDATION_ERROR",`@lunora/sql-store: global table "${e}" needs ${String(a)} columns, over this engine's ${String(u)}-column limit. ${l?`One of them is "${A}", the row version every guarded write reads, which caps declared fields at ${String(u-o.length)}. A table provisioned at ${String(u)} columns before that column existed cannot be widened to hold it. `:""}${f}`)}return i.join([...o,...r],i`, `)},K=e=>{if(e.indexKeyPrefix?.("string")===void 0)return i`${d("_creationTime")}, ${d("id")}`},k=new Set,H=async(e,n,t,r)=>{const s=i.join(t.refs.map(a=>i`${a} IS NOT NULL`),i` AND `);if((await m(e,n,i`SELECT ${t.columns} FROM ${i.identifier(t.table)} WHERE ${s} GROUP BY ${t.columns} HAVING COUNT(*) > 1 LIMIT 1`)).length>0){const a=`unique index "${t.name}" on "${t.table}" ${r}: existing rows are duplicates under it. De-duplicate the table with a data migration first.`;throw k.has(a)||(k.add(a),console.error(`[@lunora/sql-store] ${a}`)),new I("UNIQUE_INDEX_DUPLICATES",a)}},Rn=async(e,n,t)=>{if(!t.unique){await y(e,n,t);return}try{await y(e,n,t)}catch(r){throw n.isUniqueViolation(r)&&await H(e,n,t,"cannot be created"),r}},W=e=>{const n=e.indexOf("(");return n===-1?void 0:e.slice(n,e.lastIndexOf(")")+1)},On=(e,n)=>{const t=n.unique?i`UNIQUE `:i``;return W(e.render(i`CREATE ${t}INDEX ${i.identifier(n.name)} ON ${i.identifier(n.table)} (${n.columns})`).sql)},In=(e,n,t)=>{const r=On(e,t);return r!==void 0&&r!==W(n)},G=async(e,n,t)=>{if(n.name!=="sqlite")return;const s=(await m(e,n,i`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${t.name} COLLATE NOCASE AND tbl_name = ${t.table} COLLATE NOCASE`))[0]?.sql;typeof s=="string"&&In(n,s,t)&&(t.unique&&await H(e,n,t,"cannot be re-created with its new column list; the previous index is left in place"),await $(e,n,i`DROP INDEX IF EXISTS ${i.identifier(t.name)}`))},Cn=(e,n,t)=>{Ln(e,n,t);const r=j(n),s=u=>{const l=d(u),f=n.shape[u],c=f&&t.indexKeyPrefix&&f._meta?.column?.unique!==!0&&!r.has(u)?t.indexKeyPrefix(g(f)):void 0;return c===void 0?l:i`${l}(${i.raw(String(c))})`},o=K(t),a=[];for(const u of n.indexes){const l=u.fields.map(E=>s(E)),f=i.join(l,i`, `),c=u.unique??!1;a.push({columns:c||o===void 0?f:i`${f}, ${o}`,kind:"declared",name:`${e}_${u.name}`,refs:l,table:e,unique:c})}o!==void 0&&a.push({columns:o,kind:"default-order",name:`${e}__by_creation`,refs:[],table:e,unique:!1});for(const[u,l]of cn(n)){if(!l.unique)continue;const f=s(u);a.push({columns:f,kind:"unique-column",name:`${e}_unique_${u}`,refs:[f],table:e,unique:!0})}return a},Nn=/^\s*create\s+unique\s/iu,h="__lunora_framework_indexes",bn=()=>i`CREATE TABLE IF NOT EXISTS ${i.identifier(h)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`,X=(e,n)=>i`INSERT OR IGNORE INTO ${i.identifier(h)} (name, table_name) VALUES (${e}, ${n})`,w=e=>e.replaceAll(/[A-Z]/gu,n=>n.toLowerCase()),qn=async(e,n,t)=>{if(n.name!=="sqlite"||(await m(e,n,i`SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ${h} COLLATE NOCASE`)).length>0)return;await $(e,n,bn());const s=K(n),o=s===void 0?void 0:`, ${n.render(s).sql})`;for(const a of t){const u=`${w(a)}_`,l=await m(e,n,i`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`);for(const f of l){const c=String(f.name),E=String(f.sql);w(c).startsWith(u)&&w(c)!==w(`${a}__by_creation`)&&(Nn.test(E)||o!==void 0&&E.trimEnd().endsWith(o))&&await $(e,n,X(c,a))}}},vn=(e,n,t)=>{if(e.name!=="sqlite")return[];const r=new Set(n.map(s=>w(s.name)));return t.filter(s=>!r.has(w(s)))},Un=async(e,n,t,r)=>{if(r.name!=="sqlite")return;const s=await m(e,r,i`SELECT "l"."name" FROM ${i.identifier(h)} AS "l" WHERE "l"."table_name" = ${n} COLLATE NOCASE`);for(const o of vn(r,t,s.map(a=>String(a.name))))await $(e,r,i`DROP INDEX IF EXISTS ${i.identifier(o)}`),await $(e,r,i`DELETE FROM ${i.identifier(h)} WHERE ${i.identifier(h)}."name" = ${o}`)},Dn=async(e,n,t,r)=>{const s=Cn(n,t,r);for(const o of s){if(o.kind==="default-order"){await y(e,r,o);continue}o.kind==="declared"&&await G(e,r,o),await Rn(e,r,o),r.name==="sqlite"&&await $(e,r,X(o.name,o.table))}await Un(e,n,s,r)},q="__lunora_migration_state",kn=async(e,n)=>{await $(e,n,i`CREATE TABLE IF NOT EXISTS ${i.identifier(q)} (${i.identifier("name")} ${i.raw(n.companionTypes.key)} PRIMARY KEY)`)},xn=async(e,n,t)=>(await m(e,n,i`SELECT ${i.identifier("name")} FROM ${i.identifier(q)} WHERE ${i.identifier("name")} = ${t}`)).length>0,Mn=async(e,n,t,r,s,o)=>{s>0&&o!==void 0&&console.warn(`[@lunora/sql-store] storage migration "${t}" on "${r}": ${String(s)} row(s) ${o} and were left as stored — range filters and ORDER BY over them stay wrong until they are corrected by hand.`);try{await $(e,n,i`INSERT INTO ${i.identifier(q)} (${i.identifier("name")}) VALUES (${t})`)}catch(a){if(!n.isUniqueViolation(a))throw a}},Bn=100,Fn=(e,n)=>{const t=[],r=[];for(const s of n.fields){const o=e[s],a=n.convert(o);a!==void 0&&(t.push(i`${d(s)} = ${a}`),r.push(i`${d(s)} = ${o}`))}return{assignments:t,guards:r}},Pn=e=>i.join(e.fields.map(n=>e.probe(n)),i` OR `),Y=async(e,n,t,r)=>{if(r.fields.length===0||(await kn(e,t),await xn(e,t,r.marker)))return;const s=Pn(r),o=i.join([d("id"),...r.fields.map(l=>d(l))],i`, `);let a="",u=0;for(;;){const l=await m(e,t,i`SELECT ${o} FROM ${i.identifier(n)} WHERE (${s}) AND ${d("id")} > ${a} ORDER BY ${d("id")} LIMIT ${i.raw(String(Bn))}`);if(l.length===0){await Mn(e,t,r.marker,n,u,r.describeUnconvertible);return}const f=[];for(const E of l){const{id:p}=E,{assignments:T,guards:_}=typeof p=="string"?Fn(E,r):{assignments:[],guards:[]};if(T.length===0){u+=1;continue}f.push(i`UPDATE ${i.identifier(n)} SET ${i.join(T,i`, `)} WHERE ${d("id")} = ${p} AND ${i.join(_,i` AND `)}`)}await dn(e,t,f);const c=l.at(-1)?.id;if(typeof c!="string")return;a=c}},x=e=>`'${e}%'`,jn=e=>Object.entries(e.shape).filter(([,n])=>n._meta?.column!==void 0&&g(n)==="bigint").map(([n])=>n),Kn=e=>Object.entries(e.shape).filter(([,n])=>n._meta?.column!==void 0&&on(g(n))).map(([n])=>n),V=(e,n)=>({convert:t=>{if(!(typeof t!="string"||t.length===v))try{return en(BigInt(t))}catch{return}},describeUnconvertible:"hold a value the order-preserving key cannot represent (non-numeric text, or a magnitude past 39 digits)",fields:jn(n),marker:`bigint-key:${e}`,probe:t=>i`(${d(t)} IS NOT NULL AND LENGTH(${d(t)}) <> ${v})`}),Hn=async(e,n,t,r)=>Y(e,n,r,V(n,t)),Q=(e,n)=>({convert:rn,fields:Kn(n),marker:`untyped-number-key:${e}`,probe:t=>i`(${d(t)} LIKE ${i.raw(x(sn))} AND ${d(t)} NOT LIKE ${i.raw(x(an))})`}),Wn=async(e,n,t,r)=>Y(e,n,r,Q(n,t)),Gn=async(e,n,t,r)=>{const s=An(n,t,r);await $(e,r,i`CREATE TABLE IF NOT EXISTS ${i.identifier(n)} (${s})`),await Tn(e,n,t,r),await yn(e,n,t,r),await Dn(e,n,t,r),await Hn(e,n,t,r),await Wn(e,n,t,r)},ie=(e,n)=>[V(e,n),Q(e,n)].filter(t=>t.fields.length>0),re=async(e,n,t,r)=>{let s=!1;for(const[o,a]of Object.entries(n.tables))a.shardMode?.kind!=="global"||r!==void 0&&!r.has(o)||(s||(s=!0,await qn(e,t,Object.entries(n.tables).filter(([,u])=>u.shardMode?.kind==="global").map(([u])=>u))),await Gn(e,o,a,t))},z=e=>e.shardMode===void 0||e.shardMode.kind==="global",oe=async(e,n,t)=>{const{integer:r,key:s,real:o}=t.companionTypes;for(const[a,u]of Object.entries(n.tables)){const l=u.aggregateIndexes;if(!(!l||l.length===0||!z(u)))for(const f of l){const c=J(a,f.name);await $(e,t,i`CREATE TABLE IF NOT EXISTS ${i.identifier(c)} (${i.identifier("__key__")} ${i.raw(s)} PRIMARY KEY, ${i.identifier("__value__")} ${i.raw(o)}, ${i.identifier("__count__")} ${i.raw(r)} NOT NULL DEFAULT 0)`),t.name==="sqlite"&&await b(e,t,c,"__count__",`${r} NOT NULL DEFAULT 0`)}}},S=(e,n,t,r)=>{const s=e.name==="mysql"&&r?i`${i.identifier(n)}(191)`:i`${i.identifier(n)}`;return i`${s} ${i.raw(t)}`},Xn=(e,n,t)=>{const r=[S(e,"__partition__","ASC",!0)];for(const[s,o]of n.sortBy.entries()){const a=t.shape[o.field],u=a!==void 0&&e.indexKeyPrefix?.(g(a))!==void 0;r.push(S(e,C(s),o.direction==="desc"?"DESC":"ASC",u))}return r.push(S(e,"__id__","ASC",!0)),r},Yn=(e,n,t)=>n.sortBy.map((r,s)=>{const o=t.shape[r.field],a=e.columnType(o?g(o):void 0);return i`${i.identifier(C(s))} ${i.raw(a)}`}),Vn=/__sort_k\d+__/gu,Qn=async(e,n,t,r)=>{if(n.name!=="sqlite")return;const o=(await m(e,n,i`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ${t} COLLATE NOCASE`))[0]?.sql;if(typeof o!="string")return;const a=o.match(Vn)??[];(a.length!==r.length||a.some((u,l)=>u!==r[l]))&&await $(e,n,i`DROP TABLE ${i.identifier(t)}`)},se=async(e,n,t)=>{const{key:r}=t.companionTypes;for(const[s,o]of Object.entries(n.tables)){const a=o.rankIndexes;if(!(!a||a.length===0||!z(o)))for(const u of a){const l=U-4;if(u.sortBy.length>l)throw new I("BAD_REQUEST",`rank index "${u.name}" on ${s} has ${String(u.sortBy.length)} sort keys; at most ${String(l)} fit the ${String(U)} parameters one statement binds`);const f=nn(s,u.name),c=Yn(t,u,o);await Qn(e,t,f,u.sortBy.map((zn,Z)=>C(Z)));const E=c.length>0?i`, ${i.join(c,i`, `)}`:i``;await $(e,t,i`CREATE TABLE IF NOT EXISTS ${i.identifier(f)} (${i.identifier("__id__")} ${i.raw(r)} PRIMARY KEY, ${i.identifier("__partition__")} ${i.raw(r)} NOT NULL${E})`);const p=Xn(t,u,o),T=`${s}__rank_${u.name}__btree`,_={columns:i.join(p,i`, `),name:T,refs:[],table:f,unique:!1};await G(e,t,_),await y(e,t,_)}}};export{h as I,q as M,se as a,Cn as b,In as c,X as d,Pn as e,w as f,An as g,On as h,bn as i,W as j,Gn as k,ie as l,re as p,oe as r,vn as u,hn as w};
@@ -0,0 +1 @@
1
+ import{LunoraError as p}from"@lunora/errors";import{q as U,c as qt,m as Ft,r as C,a as Ut,l as q,w as F,b as kt}from"./ctx-db-search-state-BBPiVWjf.mjs";import{ftsUnmappedPage as bt,groupUnmappedRows as Ht,ftsWriteDocument as mt,ftsPurgeDocument as ht,ftsCompanionDdl as Pt,unionAll as Bt,ftsRowidMapName as Wt}from"@lunora/shard-engine";import{sql as r}from"drizzle-orm";import{abandonedWork as jt}from"./DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import{O as xt,q as h,n as Kt,h as X,a as N,i as L,e as J,f as v,c as y,k as pt,j as ot,l as Gt,r as Yt,x as Vt}from"./sql-exec-enIOMsv0.mjs";const Qt=n=>{const t=atob(n),e=Uint8Array.from(t,i=>i.codePointAt(0)??0);return new TextDecoder().decode(e)},Xt=()=>new p("INVALID_CURSOR","invalid cursor"),st=16,at=8,T=1024,k=(n,t)=>t.query(n),Jt=(n,t)=>{if(!t)return{exact:!0,lower:n,upper:n};const e=[...n].at(-1)??"",i=(e.codePointAt(0)??0)+1;if(i>=55296&&i<=57343||i>1114111)return{exact:!0,lower:n,upper:n};const o=n.slice(0,n.length-e.length);return{exact:!1,lower:n,upper:o+String.fromCodePoint(i)}},Dn=(n,t,e)=>{const i={eq:(o,s)=>{if(!n.definition.filterFields?.includes(o))throw new p("INTERNAL",`field "${o}" is not a filter field of search index "${n.indexName}" on table "${t}"`);if(n.filters.length>=at)throw new p("BAD_REQUEST",`search index "${n.indexName}" on table "${t}": at most ${String(at)} .eq() filters are supported per search query`);return n.filters.push({field:o,value:s}),i},search:(o,s)=>{const a=n;if(o!==a.definition.field)throw new p("INTERNAL",`search index "${a.indexName}" on table "${t}" indexes "${a.definition.field}", not "${o}"`);const f=k(s,e).length;if(f>st)throw new p("BAD_REQUEST",`search index "${a.indexName}" on table "${t}": at most ${String(st)} search terms are supported (got ${String(f)})`);return a.field=o,a.query=s,a.hasQuery=!0,i}};return i},qn=n=>{if(n.length>T)throw new p("BAD_REQUEST",`more than ${String(T)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Fn=n=>Math.min(n.offset+n.numItems+1,T),zt=n=>btoa(`search:${String(n)}`),Zt=n=>{let t;try{t=Qt(n)}catch{return}if(!t.startsWith("search:"))return;const e=Number(t.slice(7));return Number.isInteger(e)&&e>=0?e:void 0},Un=n=>{if(typeof n.endCursor=="string")throw new p("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new p("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const t=Math.max(0,Math.floor(n.numItems)),e=n.cursor?Zt(n.cursor):0;if(e===void 0)throw Xt();if(e+t>=T)throw new p("BAD_REQUEST",`search pagination reaches the ${String(T)}-document limit (offset ${String(e)} + ${String(t)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,T-e-1))} or fewer, or narrow the query or the filters instead`);return{numItems:t,offset:e}},kn=(n,t)=>{const e=t.offset+t.numItems,i=t.numItems>0&&n.length>e;return{continueCursor:i?zt(e):null,isDone:!i,page:n.slice(t.offset,e)}},bn=n=>{if(n===void 0)return T+1;if(!Number.isFinite(n))return T;const t=Math.max(0,Math.floor(n));if(t>T)throw new p("BAD_REQUEST",`search returns at most ${String(T)} documents (asked for ${String(t)}) — narrow the query or paginate instead`);return t},tn=(n,t)=>{if(!t.includes("."))return n[t];let e=n;for(const i of t.split(".")){if(e===null||typeof e!="object"||Array.isArray(e))return;e=e[i]}return e},b=(n,t)=>`${n}__fts_${t}`,l="__id__",g="__token__",A="__n__",nn=1e3,en=(n,t)=>t.document(n),G=(n,t)=>tn(n,t),rn=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",on=(n,t,e)=>n!==void 0&&t!==void 0&&G(n,e.field)===G(t,e.field),gt=(n,t)=>en(rn(G(n,t.field)),U(t.language)).slice(0,nn),z=(n,t)=>gt(n,t).join(" "),yt=(n,t)=>{const e=new Map;for(const i of gt(n,t))e.set(i,(e.get(i)??0)+1);return e},Tt=[xt,"_creationTime"],ft=50,d=(n,t)=>r`${r.identifier(n)}.${r.identifier(t)}`,M=(n,t,e)=>r`DELETE FROM ${r.identifier(n)} WHERE ${d(n,l)} = ${t}${e===void 0?r``:r` AND ${e}`}`,Rt=(n,{row:t,table:e})=>{const i=Tt.map(o=>r` AND ${Kt(n.name,d(e,o),t[o]??null)}`);return r`SELECT 1 FROM ${r.identifier(e)} WHERE ${d(e,"id")} = ${t.id}${r.join(i)}${n.name==="postgres"?r` FOR SHARE`:r``}`},D=(n,t)=>r`EXISTS (${Rt(n,t)})`,H=(n,t)=>r`NOT EXISTS (SELECT 1 FROM ${r.identifier(n)} WHERE ${d(n,"id")} = ${t})`,_t=(n,t,e,i)=>i===void 0?H(t,e):D(n,{row:i,table:t}),P=async(n,t,e,i)=>{const o=new Map;for(let s=0;s<i.length;s+=ft){const a=i.slice(s,s+ft),f=await h(n,t,r`SELECT * FROM ${r.identifier(e)} WHERE ${d(e,"id")} IN (${r.join(a.map(c=>r`${c}`),r`, `)})`);for(const c of f)o.set(String(c.id),c)}return o},Y=(n,t,e)=>n.name==="mysql"?r`${r.identifier(t)}(${r.raw(String(e))})`:n.textPatternOperatorClass===void 0?r`${r.identifier(t)}`:r`${r.identifier(t)} ${r.raw(n.textPatternOperatorClass)}`,Z=512,tt=(n,t)=>({columns:r`${Y(n,g,256)}, ${Y(n,l,Z)}`,concurrently:!0,name:`${t}__unique`,table:t,unique:!0}),x=n=>r`${n} COLLATE utf8mb4_0900_bin`,K=(n,t)=>{const e=JSON.stringify(t.map(([i,o])=>({o,t:i})));switch(n.name){case"mysql":return r`JSON_TABLE(${e}, '$[*]' COLUMNS (${r.identifier("t")} VARCHAR(256) PATH '$.t', ${r.identifier("o")} INT PATH '$.o')) AS ${r.identifier("j")}`;case"postgres":return r`json_to_recordset(${e}::text::json) AS ${r.identifier("j")}(${r.identifier("t")} text, ${r.identifier("o")} integer)`;default:return r`(SELECT json_extract(${d("e","value")}, '$.t') AS ${r.identifier("t")}, json_extract(${d("e","value")}, '$.o') AS ${r.identifier("o")} FROM json_each(${e}) AS ${r.identifier("e")}) AS ${r.identifier("j")}`}},Ot=(n,t,e,i,o)=>{const s=r.join([g,l,A].map(f=>r.identifier(f)),r`, `),a=f=>r`INSERT INTO ${r.identifier(t)} (${s}) SELECT ${d("j","t")}, ${e}, ${d("j","o")} FROM ${K(n,i)} WHERE ${f}`;switch(n.name){case"mysql":{const f=D(n,o),c=d(t,g),w=r.identifier("held");return[r`${a(r`${f} AND NOT EXISTS (SELECT 1 FROM ${r.identifier(t)} AS ${w} WHERE ${d("held",l)} = ${e} AND ${d("held",g)} = ${x(d("j","t"))})`)} ON DUPLICATE KEY UPDATE ${d(t,A)} = ${d(t,A)}`,r`UPDATE ${r.identifier(t)} JOIN ${K(n,i)} ON ${c} = ${x(d("j","t"))} SET ${d(t,A)} = ${d("j","o")} WHERE ${d(t,l)} = ${e} AND ${f}`,r`DELETE FROM ${r.identifier(t)} WHERE ${d(t,l)} = ${e} AND ${f} AND ${c} NOT IN (SELECT ${x(d("j","t"))} FROM ${K(n,i)})`]}case"postgres":{const f=r.identifier("__source__"),c=r.identifier("__purged__"),w=r`EXISTS (SELECT 1 FROM ${f})`;return[r`WITH ${f} AS (${Rt(n,o)}), ${c} AS (${M(t,e,w)} RETURNING 1) ${a(r`${w} AND (SELECT COUNT(*) FROM ${c}) >= 0`)} ON CONFLICT DO NOTHING`]}default:{const f=D(n,o);return[M(t,e,f),r`${a(f)} ON CONFLICT DO NOTHING`]}}},At={uniqueKeyMissing:!1,unmappedSkipped:0},ct=new Set,ut=(n,t)=>{ct.has(n)||(ct.add(n),console.warn(`[@lunora/sql-store] ${t}`))},dt=100,$t=3,V=async(n,t,e,i=0)=>{const{companion:o,definition:s,index:a,tableName:f}=e,c={done:!0,last:i,left:0};if((await h(n,t,t.tableExists(f))).length===0)return c;const u=await h(n,t,bt(o,dt,i));if(u.length===0)return c;const S=Math.max(...u.map(O=>Number(O.rowid))),E=Ht(u),m=await P(n,t,f,[...E.keys()]),$=[];for(const[O,et]of E){const j=m.get(O),rt=j===void 0?void 0:X(s,j),it=_t(t,f,O,j);$.push(...rt?mt(o,O,z(rt,a),{guard:it,unmappedRowids:et}):ht(o,O,{guard:it,unmappedRowids:et}))}await N(n,t,$);const _=await h(n,t,r`SELECT COUNT(*) AS ${r.identifier("n")} FROM ${r.identifier(o)} WHERE ${d(o,"rowid")} > ${Math.max(0,i)} AND ${d(o,"rowid")} <= ${S}`);return{done:u.length<dt,last:S,left:Number(_[0]?.n??0)}},sn=async(n,t,e)=>{let i=0,o=0;for(;;){let s=await V(n,t,e,i);for(let a=1;s.left>0&&a<$t;a+=1)s=await V(n,t,e,i);if(s.left>0&&(o+=s.left,console.warn(`[@lunora/sql-store] search migration of "${e.companion}": ${String(s.left)} row(s) lost every one of ${String($t)} attempts to a concurrent write and were left for a later pass.`)),s.done)return o;i=s.last}},an=async(n,t,e,i)=>i==="step"?(await V(n,t,e),At):{uniqueKeyMissing:!1,unmappedSkipped:await sn(n,t,e)},Q=n=>`${n}__btree`,fn=async(n,t,e)=>{const i=tt(t,e),o=await L(n,t,e,i.name);if(o!=="valid"){if(o==="absent"&&(await h(n,t,r`SELECT 1 AS ${r.identifier("present")} FROM ${r.identifier(e)} LIMIT 1`)).length===0)try{await J(n,t,{...i,concurrently:!1}),await v(n,t,e,Q(e));return}catch(a){if(await L(n,t,e,i.name).catch(()=>{})==="valid")return;ut(`${e}:empty`,`search companion "${e}": adding its unique key failed (${String(a)}); run backfillSqlSearchIndexes.`);return}ut(`${e}:missing`,`search companion "${e}" has no usable unique key, so two backfills racing over one row can index it twice. Run backfillSqlSearchIndexes, which adds it.`)}},cn=async(n,t,e)=>{const i=d(e,l),o=d(e,g);return(await h(n,t,r`SELECT ${i} AS ${r.identifier("id")}, ${o} AS ${r.identifier("token")}, COUNT(*) AS ${r.identifier("n")} FROM ${r.identifier(e)} GROUP BY ${i}, ${o} HAVING COUNT(*) > 1`)).map(a=>({count:Number(a.n),id:String(a.id),token:String(a.token)}))},un=(n,t,{count:e,id:i,token:o})=>{const s=r`${d(t,l)} = ${i} AND ${d(t,g)} = ${o}`;switch(n.name){case"mysql":return r`DELETE FROM ${r.identifier(t)} WHERE ${s} LIMIT ${r.raw(String(e-1))}`;case"postgres":return r`DELETE FROM ${r.identifier(t)} WHERE ctid = ANY (ARRAY(SELECT ctid FROM ${r.identifier(t)} WHERE ${s} OFFSET 1))`;default:return r`DELETE FROM ${r.identifier(t)} WHERE rowid IN (SELECT rowid FROM ${r.identifier(t)} WHERE ${s} LIMIT -1 OFFSET 1)`}},dn=async(n,t,e,i)=>{const{companion:o,definition:s,index:a,tableName:f}=e;for(const u of i)await y(n,t,un(t,o,u));const c=[...new Set(i.map(u=>u.id))],w=await P(n,t,f,c);for(const u of c){const S=w.get(u),E=S===void 0?void 0:X(s,S);if(S!==void 0&&E){const m=[...yt(E,a)];await N(n,t,Ot(t,o,u,m,{row:S,table:f}));continue}await y(n,t,M(o,u,_t(t,f,u,S)))}},$n=async(n,t,e)=>t.name!=="mysql"?"":(await h(n,t,r`SELECT COLUMN_NAME AS ${r.identifier("name")}, COLLATION_NAME AS ${r.identifier("collation")} FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ${e} AND COLUMN_NAME IN (${g}, ${l})`)).filter(o=>!String(o.collation).endsWith("_bin")).map(o=>` Its ${String(o.name)} column uses ${String(o.collation)}, which treats values differing only in case or accents as one; convert it with ALTER TABLE \`${e}\` MODIFY \`${String(o.name)}\` VARCHAR(768) COLLATE utf8mb4_0900_bin NOT NULL.`).join(""),wn=async(n,t,e)=>{if(t.name!=="mysql")return 0;const i=d(e,l),o=await h(n,t,r`SELECT COUNT(*) AS ${r.identifier("n")} FROM (SELECT 1 AS ${r.identifier("x")} FROM ${r.identifier(e)} GROUP BY LEFT(${i}, ${r.raw(String(Z))}), ${d(e,g)} HAVING COUNT(DISTINCT ${i}) > 1) AS ${r.identifier("shared")}`);return Number(o[0]?.n??0)},Sn=async(n,t,e)=>{const i=tt(t,e),o=await L(n,t,e,i.name);if(o==="valid")return"valid";o==="invalid"&&await v(n,t,e,i.name);try{return await J(n,t,i),"built"}catch(s){const a=await L(n,t,e,i.name);if(a==="valid")return"valid";if(a==="invalid"&&await v(n,t,e,i.name),!t.isUniqueViolation(s))throw s;return"refused"}},wt=3,ln=async(n,t,e)=>{const{companion:i}=e,o=await $n(n,t,i);let s="";o!==""&&console.warn(`[@lunora/sql-store] search companion "${i}" folds case and accents in its unique key.${o}`);for(let a=0;a<wt;a+=1){const f=await Sn(n,t,i);if(f==="valid")return await v(n,t,i,Q(i)),!0;if(f==="refused"){const c=await cn(n,t,i);if(c.length>0)await dn(n,t,e,c);else{const w=await wn(n,t,i);s=w>0?` ${String(w)} token(s) are held by document ids that agree on their first ${String(Z)} characters, which the key cannot tell apart; shorten those ids.`:o}}}return await L(n,t,i,tt(t,i).name)==="valid"?(await v(n,t,i,Q(i)),!0):(console.warn(`[@lunora/sql-store] search companion "${i}" still has no unique key after ${String(wt)} attempts: writes keep working, but two backfills racing over one row can index it twice.${s}`),!1)},En=async(n,t,e,i)=>i==="step"?At:{uniqueKeyMissing:!await ln(n,t,e),unmappedSkipped:0},mn=(n,t)=>t?r`${r.identifier(g)} LIKE ${`${n}%`}`:r`${r.identifier(g)} = ${n}`,Nt=(n,t)=>{const e=t.filters.map(i=>r`m.${ot(i.field)} = ${Gt(i.value)}`);return n.softDeleteMode&&e.push(r`m.${ot(n.softDeleteMode.field)} IS NULL`),t.scope!==void 0&&e.push(r`(${t.scope})`),e},It=async(n,t,e,i,o,s,a)=>{const f=Nt(e,o);let c=r`SELECT m.* FROM (${a}) s JOIN ${r.identifier(i)} m ON m.${r.identifier("id")} = s.${r.identifier(l)}`;return f.length>0&&(c=r`${c} WHERE ${r.join(f,r` AND `)}`),c=r`${c} ORDER BY s.${r.identifier("__score__")} DESC, m.${r.identifier("_creationTime")} DESC, m.${r.identifier("id")} ASC LIMIT ${r.raw(String(s))}`,pt(e,await h(n,t,c))},hn=async(n,t,e,i,o,s)=>{const a=k(o.query,U(o.definition.language));if(a.length===0)return[];const f=b(i,o.indexName),c=a.length-1,w=a.map(($,_)=>mn($,_===c)),u=r.join(w,r` OR `),S=w.map($=>r`SUM(CASE WHEN ${$} THEN ${r.identifier(A)} ELSE 0 END)`),E=r.join(S.map($=>r`${$} > 0`),r` AND `),m=r`SELECT ${r.identifier(l)}, ${r.join(S,r` + `)} AS ${r.identifier("__score__")} FROM ${r.identifier(f)} WHERE ${u} GROUP BY ${r.identifier(l)} HAVING ${E}`;return It(n,t,e,i,o,s,m)},pn=async(n,t,e,i,o,s)=>{const a=k(o.query,U(o.definition.language));if(a.length===0)return[];const f=b(i,o.indexName),c=`${f}__vocab`,w=a.length-1,u=a.map((m,$)=>{const _=Jt(m,$===w),O=_.exact?r`${r.identifier("term")} = ${_.lower}`:r`${r.identifier("term")} >= ${_.lower} AND ${r.identifier("term")} < ${_.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String($))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(c)} WHERE ${O} GROUP BY ${r.identifier("doc")}`}),S=a.map((m,$)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String($))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),E=r`SELECT f.${r.identifier(l)} AS ${r.identifier(l)}, ${r.join(S,r` + `)} AS ${r.identifier("__score__")} FROM (${Bt(u)}) u JOIN ${r.identifier(f)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(l)} HAVING ${r.join(S.map(m=>r`${m} > 0`),r` AND `)}`;return It(n,t,e,i,o,s,E)},gn=async(n,t,e,i,o,s)=>{const a=t.nativeTextSearch,f=k(o.query,U(o.definition.language));if(!a||f.length===0)return[];const c=b(i,o.indexName),w=[a.matches(c,f),...Nt(e,o)],u=r`SELECT m.* FROM ${r.identifier(c)} JOIN ${r.identifier(i)} m ON m.${r.identifier("id")} = ${r.identifier(c)}.${r.identifier(l)} WHERE ${r.join(w,r` AND `)} ORDER BY ${a.rank(c,f)} DESC, m.${r.identifier("_creationTime")} DESC, m.${r.identifier("id")} ASC LIMIT ${r.raw(String(s))}`;return pt(e,await h(n,t,u))},yn={ensureCompanion:async(n,t,e)=>{const{integer:i,key:o}=t.companionTypes;await y(n,t,r`CREATE TABLE IF NOT EXISTS ${r.identifier(e)} (${r.identifier(g)} ${r.raw(o)} NOT NULL, ${r.identifier(l)} ${r.raw(o)} NOT NULL, ${r.identifier(A)} ${r.raw(i)} NOT NULL)`),await J(n,t,{columns:Y(t,l,191),name:`${e}__by_id`,table:e,unique:!1}),await fn(n,t,e)},indexDocument:async(n,t,e,i,o,s)=>{const a=[...yt(i,o)];await N(n,t,Ot(t,e,String(s.row.id),a,s))},migrate:En,name:"inverted",purgeDocument:async(n,t,e,i,o)=>{await y(n,t,M(e,i,H(o,i)))},runSearch:hn},Tn={ensureCompanion:async(n,t,e)=>{await N(n,t,Pt(e))},indexDocument:async(n,t,e,i,o,s)=>{await N(n,t,mt(e,String(s.row.id),z(i,o),{guard:D(t,s)}))},migrate:an,name:"fts5",purgeDocument:async(n,t,e,i,o)=>{await N(n,t,ht(e,i,{guard:H(o,i)}))},runSearch:pn},Rn={ensureCompanion:async(n,t,e)=>{const i=t.nativeTextSearch;if(i){await y(n,t,i.createCompanion(e,t.companionTypes.key));for(const o of i.createIndexes(e))await y(n,t,o)}},indexDocument:async(n,t,e,i,o,s)=>{const a=t.nativeTextSearch;a&&await y(n,t,a.indexDocument(e,String(s.row.id),z(i,o),D(t,s)))},name:"native",purgeDocument:async(n,t,e,i,o)=>{await y(n,t,M(e,i,H(o,i)))},runSearch:gn},I=(n,t)=>n.strategy==="native"&&t.nativeTextSearch!==void 0?Rn:t.supportsFts5?Tn:yn,B=(n,t)=>`${qt(n)}/${I(n,t).name}`,nt=function*(n){for(const[t,e]of Object.entries(n.tables)){const i=e.searchIndexes;if(!(e.shardMode!==void 0&&e.shardMode.kind!=="global"||!i))for(const o of i)yield[t,e,o]}},R=(n,t)=>b(n,t.name),_n=async(n,t,e,i)=>{const o=R(e,i);return q(await C(n,t,o),B(i,t)).finished?!0:kt(n,t,o)},Hn=async(n,t,e,i,o,s)=>{if(!await _n(n,t,i,o.definition))throw new p("SEARCH_INDEX_BUILDING",`search index "${o.indexName}" on table "${i}" is still backfilling and currently covers only part of the table — retry once it finishes${t.searchBackfillHint===void 0?"":`, or complete it now: ${t.searchBackfillHint}`}`);return I(o.definition,t).runSearch(n,t,e,i,o,s)},St=n=>n.slice(n.lastIndexOf("/")+1),lt=200,Et=5,On=async(n,t,e,i)=>{const o=[...i.keys()],s=await h(n,t,r`SELECT * FROM ${r.identifier(e)} WHERE ${r.identifier("id")} >= ${o[0]} AND ${r.identifier("id")} <= ${o.at(-1)} ORDER BY ${r.identifier("id")} ASC`),a=new Map;for(const f of s){const c=f.id,w=i.get(c)?.row;w&&Tt.some(u=>String(w[u])!==String(f[u]))&&a.set(c,{row:f})}return a},W=async(n,t,e,i,o,s,a)=>{const f=I(s,t);let c=a;for(let w=0;c.size>0&&w<Et;w+=1){for(const{document:u,row:S}of c.values()){const E=u??X(e,S);E&&await f.indexDocument(n,t,o,E,s,{row:S,table:i})}c=await On(n,t,i,c)}c.size>0&&console.warn(`[@lunora/sql-store] search index "${o}": ${String(c.size)} row(s) were rewritten on every one of ${String(Et)} re-check rounds and were left to their writers — each stays stale only if none of those writes changed its indexed text.`)},Ct=async(n,t,e,i,o)=>{const s=R(i,o),a=B(o,t);let f=await C(n,t,s),c=q(f,a);if(c.finished)return!0;if(c.wipe){await F(n,t,s,void 0,!1,a,{cursor:f.cursor,done:f.done,profile:f.profile});const $=await C(n,t,s);if($.cursor!==f.cursor||$.done!==f.done||$.profile!==f.profile){if(f=$,c=q(f,a),c.wipe)return!1;if(c.finished)return!0}else f={cursor:void 0,done:!1,profile:a},c=q(f,a)}if((await h(n,t,t.tableExists(i))).length===0)return await F(n,t,s,void 0,!0,a),!0;const u=await Yt(n,t,i,c.cursor,lt),S=u.findLast($=>typeof $.id=="string")?.id,E=new Map;for(const $ of u)typeof $.id=="string"&&E.set($.id,{row:$});await W(n,t,e,i,s,o,E);const m=u.length<lt;return await F(n,t,s,S??c.cursor,m,a,{cursor:c.cursor,done:!1,profile:f.profile}),m},Lt=async(n,t,e)=>{await Ft(n,e);for(const[i,,o]of nt(t)){const s=R(i,o),a=B(o,e),f=await C(n,e,s);f.profile!==void 0&&St(f.profile)!==St(a)&&(await y(n,e,r`DROP TABLE IF EXISTS ${r.identifier(s)}`),await y(n,e,r`DROP TABLE IF EXISTS ${r.identifier(Wt(s))}`),await Ut(n,e,s)),await I(o,e).ensureCompanion(n,e,s)}},An=async(n,t,e,i,o)=>{const s=R(i,o);if((await C(n,t,s)).profile!==void 0)return;let f=0;(await h(n,t,t.tableExists(i))).length>0&&await Vt(n,t,e,i,()=>{f+=1},{limit:1}),await F(n,t,s,void 0,f===0,B(o,t))},vt=async(n,t,e,i,o,s)=>await I(o,t).migrate?.(n,t,{companion:R(i,o),definition:e,index:o,tableName:i},s)??{uniqueKeyMissing:!1,unmappedSkipped:0},Pn=async(n,t,e)=>{await Lt(n,t,e);for(const[i,o,s]of nt(t)){if(await vt(n,e,o,i,s,"step"),s.staged){await An(n,e,o,i,s);continue}await Ct(n,e,o,i,s)}},Bn=async(n,t,e)=>{const i={uniqueKeyMissing:[],unmappedSkipped:0};await Lt(n,t,e);for(const[o,s,a]of nt(t)){const f=await vt(n,e,s,o,a,"drain");i.unmappedSkipped+=f.unmappedSkipped,f.uniqueKeyMissing&&i.uniqueKeyMissing.push(R(o,a));let c=!1;for(;!c;)c=await Ct(n,e,s,o,a)}return i},Mt=async(n,t,e,i,o,s,a)=>{await I(s,t).purgeDocument(n,t,o,a,e);const c=(await P(n,t,e,[a])).get(a);c!==void 0&&await W(n,t,i,e,o,s,new Map([[a,{row:c}]]))},Dt=async(n,t,e,i,o,s,a)=>{const c=(await P(n,t,e,[a])).get(a);await(c===void 0?Mt(n,t,e,i,o,s,a):W(n,t,i,e,o,s,new Map([[a,{row:c}]])))},Wn=async(n,t,e)=>{const i=n.schema.tables[t];for(const o of i?.searchIndexes??[])await Dt(n.exec,n.dialect,t,i,R(t,o),o,e)},jn=n=>{const{dialect:t,exec:e,schema:i}=n;return async(o,s,a)=>{const f=i.tables[o],c=f?.searchIndexes;if(!(!f||!c||c.length===0))for(const[w,u]of c.entries()){const S=R(o,u);try{if(on(a?.previous,a?.document,u))continue;if(a){await W(e,t,f,o,S,u,new Map([[s,{document:a.document,row:{...a.written,id:s}}]]));continue}await Mt(e,t,o,f,S,u,s)}catch(E){const m=async()=>{for(const $ of c.slice(w))await Dt(e,t,o,f,R(o,$),$,s)};throw jt(E)?.then(m,m).catch(()=>{}),E}}}};export{Dn as A,Un as C,bn as I,kn as R,Wn as a,Bn as b,jn as c,Hn as d,Fn as e,Pn as r,st as u,qn as x};
@@ -1 +1 @@
1
- import{toErrorBody as b}from"@lunora/errors";import{needsWireEncoding as I,encodeWire as A,decodeWire as S}from"@lunora/wire";import{sql as m}from"drizzle-orm";import{runSqlGlobalTableMigrations as g}from"./runSqlGlobalTableMigrations-BARAefvR.mjs";import{t as y}from"./post-commit-error-hh-zQyjO.mjs";import{r as T,d as L,M as k,q as E}from"./sql-exec-enIOMsv0.mjs";const $=200,v=(r,o)=>{const t=e=>r.tables[e]?.shardMode?.kind==="global";return o&&o.length>0?o.filter(e=>t(e)):Object.keys(r.tables).filter(e=>t(e))},D=r=>I(r)?A(r):r,Y=async function*(r,o,t,e){const s=v(o,e.tables),n=e.batchSize??$;await g(r,o,t);for(const i of s){const d=o.tables[i];let a,c=!0;for(;c;){const f=await T(r,t,i,a,n);for(const u of f)yield{doc:D(L(d,u)),table:i};const l=f.at(-1);l!==void 0&&(a=String(l.id)),c=f.length===n}}},w=r=>r?._meta?.column?.notNull===!1,C=(r,o)=>{const t=new Set;for(const[e,s]of Object.entries(r.shape)){if(o[e]!==null||s.kind!=="optional"||w(s))continue;const n=s._meta?.inner;w(n)||t.add(e)}return t.size===0?o:Object.fromEntries(Object.entries(o).filter(([e])=>!t.has(e)))},F=new Set(["_creationTime","_id"]),M=(r,o)=>Object.keys(o).find(t=>!F.has(t)&&!Object.hasOwn(r.shape,t)),x=r=>{const o=r._id,t=r._creationTime;if(o!==void 0&&(typeof o!="string"||o===""))return'field "_id": must be a non-empty string';if(t!==void 0&&(typeof t!="number"||!Number.isFinite(t)))return'field "_creationTime": must be a finite number'},j=(r,o,t)=>{const e=r.tables[o];if(!e)return`unknown table: ${o}`;const s=M(e,t);if(s!==void 0)return`unexpected field "${s}": not declared in table "${o}"`;const n=x(t);if(n!==void 0)return n;for(const[i,d]of Object.entries(e.shape)){const a=t[i],c=d.kind==="optional";if(a===void 0&&c)continue;const f=d.parse;if(typeof f=="function")try{f(a)}catch(l){const u=l instanceof Error?l.message:String(l);return`field "${i}": ${u}`}}},R=async(r,o,t,e,s)=>t?(await E(t,o,m`SELECT 1 FROM ${m.identifier(e)} WHERE ${m.identifier("id")} = ${s} LIMIT 1`)).length>0:await r.get(e,s)!==null,O=async(r,o,t,e,s,n)=>{try{return{existingId:await R(r,o,t,e,s)?s:void 0}}catch(i){const{body:d}=b(i,{fallbackCode:"PROBE_FAILED"});return{error:{code:d.code,line:n,message:d.message,table:e}}}},h=(r,o,t)=>{const e=r.held.get(o)??new Set;e.add(t),r.held.set(o,e)},B=async(r,o,t)=>{const e=[...t.keys()],s=new Map;let n=[],i=k;const d=async()=>{if(n.length===0)return;const a=await E(r,o,m.join(n,m` UNION ALL `));for(const c of a)h({held:s},e[Number(c.slot)],String(c.id));n=[],i=k};try{for(const[a,c]of e.entries()){const f=[...t.get(c)];for(let l=0;l<f.length;){const u=f.slice(l,l+i);n.push(m`SELECT ${m.raw(String(a))} AS slot, ${m.identifier("id")} FROM ${m.identifier(c)} WHERE ${m.identifier("id")} IN (${m.join(u.map(p=>m.param(p)),m`, `)})`),l+=u.length,i-=u.length,i===0&&await d()}}await d()}catch(a){const{body:c}=b(a,{fallbackCode:"PROBE_FAILED"});return{failure:{code:c.code,message:c.message}}}return{held:s}},N=(r,o,t,e)=>"failure"in r?{error:{...r.failure,line:e,table:o}}:{existingId:r.held.get(o)?.has(t)===!0?t:void 0},W=r=>v(r).some(o=>Object.keys(r.tables[o]?.triggerMap??{}).length>0),P=async(r,o,t,e,s)=>{const{doc:n,table:i}=e,d=n._id;if(typeof d!="string")return{committed:!1,error:{code:"BAD_ROW",line:s,message:"a delete row needs the `_id` to delete",table:i},kind:"error"};if(t.dryRun===!0)return{kind:"checked"};const a=await O(r,o,t.exec,i,d,s);if("error"in a)return{committed:!1,error:a.error,kind:"error"};if(a.existingId===void 0)return{kind:"absent"};try{return await r.delete(i,d,{hard:!0,skipOnDelete:!0}),{kind:"deleted"}}catch(c){const{body:f}=b(c,{fallbackCode:"DELETE_FAILED"}),l=y(c,i,d),u=l?`${f.message} (row "${d}" was deleted before this failure, so its triggers or companion writes may not have completed; a re-run finds it absent and does not redo them)`:f.message;return{committed:l,error:{code:f.code,line:s,message:u,table:i},kind:"error"}}},_=async(r,o,t,e,s,n)=>{try{if(e!==void 0){const i={...t};return delete i._id,await r.replace(o,e,i,{allowExplicitId:!0}),{kind:"replaced"}}return await r.insert(o,t,{allowExplicitId:!0}),{inserted:o,kind:"inserted"}}catch(i){const{body:d}=b(i,{fallbackCode:e===void 0?"INSERT_FAILED":"REPLACE_FAILED"}),a=e??(typeof t._id=="string"?t._id:void 0),c=a!==void 0&&y(i,o,a),f=n==="replace"?'re-importing it with onConflict "replace" redoes that work':'a re-import skips it while it exists; use onConflict "replace" to redo that work',l=c?`${d.message} (row "${a}" committed before this failure, so its triggers or companion writes may not have completed; ${f})`:d.message;return{committed:c,error:{code:d.code,line:s,message:l,table:o},kind:"error"}}},G=(r,o,t,e)=>{const{doc:s,table:n}=t;if(typeof n!="string"||n.length===0)return{kind:"settled",outcome:{committed:!1,error:{code:"BAD_ROW",line:e,message:"row is missing `table`",table:n},kind:"error"}};if(r.tables[n]?.shardMode?.kind!=="global")return{kind:"settled",outcome:{kind:"skip"}};if(!s||typeof s!="object"||Array.isArray(s))return{kind:"settled",outcome:{committed:!1,error:{code:"BAD_ROW",line:e,message:"row is missing or malformed `doc`",table:n},kind:"error"}};if(t.op==="delete")return{kind:"delete",line:e,row:t};let i;try{i=S(s)}catch(a){return{kind:"settled",outcome:{committed:!1,error:{code:"BAD_ROW",line:e,message:a instanceof Error?a.message:String(a),table:n},kind:"error"}}}i=C(r.tables[n],i);const d=j(r,n,i);return d!==void 0?{kind:"settled",outcome:{committed:!1,error:{code:"VALIDATION_ERROR",line:e,message:d,table:n},kind:"error"}}:o?{kind:"settled",outcome:{kind:"checked"}}:{decoded:i,explicitId:typeof i._id=="string"?i._id:void 0,kind:"ready",line:e,table:n}},H=async(r,o,t,e,s,n)=>{const{decoded:i,explicitId:d,line:a,table:c}=s;try{if(!await R(r,o,t,c,d))return}catch{return}return e.snapshot!==void 0&&"held"in e.snapshot&&h(e.snapshot,c,d),n==="replace"?_(r,c,i,d,a,n):{kind:"conflict"}},z=async(r,o,t,e,s)=>{const{decoded:n,explicitId:i,line:d,table:a}=e;let c={existingId:void 0};if(i!==void 0&&(c=s.snapshot===void 0?await O(r,o,t.exec,a,i,d):N(s.snapshot,a,i,d)),"error"in c)return{committed:!1,error:c.error,kind:"error"};const{existingId:f}=c;if(f!==void 0&&t.onConflict!=="replace")return{kind:"conflict"};const l=await _(r,a,n,f,d,t.onConflict);if(i===void 0)return l;const{snapshot:u}=s;return u!==void 0&&"held"in u&&(l.kind==="inserted"||l.kind==="replaced"||l.kind==="error"&&l.committed)&&h(u,a,i),l.kind==="error"&&!l.committed&&l.error.code==="CONFLICT"&&f===void 0?await H(r,o,t.exec,s,{...e,explicitId:i},t.onConflict)??l:l},q=async(r,o,t,e,s)=>{const n=new Map;for(const i of e)if(i.kind==="ready"&&i.explicitId!==void 0){const d=n.get(i.table)??new Set;d.add(i.explicitId),n.set(i.table,d)}if(n.size===0)return s?{held:new Map}:void 0;try{await g(r,o,t)}catch(i){const{body:d}=b(i,{fallbackCode:"PROBE_FAILED"});return{failure:{code:d.code,message:d.message}}}return s?B(r,t,n):void 0},U=(r,o,t,e,s)=>e.kind==="settled"?Promise.resolve(e.outcome):e.kind==="delete"?P(r,o,t,e.row,e.line):z(r,o,t,e,s),ee=async(r,o,t,e)=>{const s=[],n={};let i=0,d=0,a=0,c=(e.startLine??1)-1;const f=e.rows.map(u=>(c+=1,G(o,e.dryRun===!0,u,u.line??c))),l={};e.exec&&e.dryRun!==!0&&(l.snapshot=await q(e.exec,o,t,f,!W(o)));for(const u of f){const p=await U(r,t,e,u,l);switch(p.kind){case"conflict":{i+=1;break}case"deleted":{d+=1;break}case"error":{s.push(p.error);break}case"inserted":{n[p.inserted]=(n[p.inserted]??0)+1;break}case"replaced":{a+=1;break}}}return{conflicts:i,deleted:d,errors:s,inserted:n,replaced:a}};export{Y as exportSqlGlobalRows,ee as importSqlGlobalRows,v as selectGlobalTables};
1
+ import{toErrorBody as b}from"@lunora/errors";import{needsWireEncoding as I,encodeWire as A,decodeWire as S}from"@lunora/wire";import{sql as m}from"drizzle-orm";import{runSqlGlobalTableMigrations as g}from"./runSqlGlobalTableMigrations-BSYk8UQI.mjs";import{t as y}from"./post-commit-error-hh-zQyjO.mjs";import{r as T,d as L,M as k,q as E}from"./sql-exec-enIOMsv0.mjs";const $=200,v=(r,o)=>{const t=e=>r.tables[e]?.shardMode?.kind==="global";return o&&o.length>0?o.filter(e=>t(e)):Object.keys(r.tables).filter(e=>t(e))},D=r=>I(r)?A(r):r,Y=async function*(r,o,t,e){const s=v(o,e.tables),n=e.batchSize??$;await g(r,o,t);for(const i of s){const d=o.tables[i];let a,c=!0;for(;c;){const f=await T(r,t,i,a,n);for(const u of f)yield{doc:D(L(d,u)),table:i};const l=f.at(-1);l!==void 0&&(a=String(l.id)),c=f.length===n}}},w=r=>r?._meta?.column?.notNull===!1,C=(r,o)=>{const t=new Set;for(const[e,s]of Object.entries(r.shape)){if(o[e]!==null||s.kind!=="optional"||w(s))continue;const n=s._meta?.inner;w(n)||t.add(e)}return t.size===0?o:Object.fromEntries(Object.entries(o).filter(([e])=>!t.has(e)))},F=new Set(["_creationTime","_id"]),M=(r,o)=>Object.keys(o).find(t=>!F.has(t)&&!Object.hasOwn(r.shape,t)),x=r=>{const o=r._id,t=r._creationTime;if(o!==void 0&&(typeof o!="string"||o===""))return'field "_id": must be a non-empty string';if(t!==void 0&&(typeof t!="number"||!Number.isFinite(t)))return'field "_creationTime": must be a finite number'},j=(r,o,t)=>{const e=r.tables[o];if(!e)return`unknown table: ${o}`;const s=M(e,t);if(s!==void 0)return`unexpected field "${s}": not declared in table "${o}"`;const n=x(t);if(n!==void 0)return n;for(const[i,d]of Object.entries(e.shape)){const a=t[i],c=d.kind==="optional";if(a===void 0&&c)continue;const f=d.parse;if(typeof f=="function")try{f(a)}catch(l){const u=l instanceof Error?l.message:String(l);return`field "${i}": ${u}`}}},R=async(r,o,t,e,s)=>t?(await E(t,o,m`SELECT 1 FROM ${m.identifier(e)} WHERE ${m.identifier("id")} = ${s} LIMIT 1`)).length>0:await r.get(e,s)!==null,O=async(r,o,t,e,s,n)=>{try{return{existingId:await R(r,o,t,e,s)?s:void 0}}catch(i){const{body:d}=b(i,{fallbackCode:"PROBE_FAILED"});return{error:{code:d.code,line:n,message:d.message,table:e}}}},h=(r,o,t)=>{const e=r.held.get(o)??new Set;e.add(t),r.held.set(o,e)},B=async(r,o,t)=>{const e=[...t.keys()],s=new Map;let n=[],i=k;const d=async()=>{if(n.length===0)return;const a=await E(r,o,m.join(n,m` UNION ALL `));for(const c of a)h({held:s},e[Number(c.slot)],String(c.id));n=[],i=k};try{for(const[a,c]of e.entries()){const f=[...t.get(c)];for(let l=0;l<f.length;){const u=f.slice(l,l+i);n.push(m`SELECT ${m.raw(String(a))} AS slot, ${m.identifier("id")} FROM ${m.identifier(c)} WHERE ${m.identifier("id")} IN (${m.join(u.map(p=>m.param(p)),m`, `)})`),l+=u.length,i-=u.length,i===0&&await d()}}await d()}catch(a){const{body:c}=b(a,{fallbackCode:"PROBE_FAILED"});return{failure:{code:c.code,message:c.message}}}return{held:s}},N=(r,o,t,e)=>"failure"in r?{error:{...r.failure,line:e,table:o}}:{existingId:r.held.get(o)?.has(t)===!0?t:void 0},W=r=>v(r).some(o=>Object.keys(r.tables[o]?.triggerMap??{}).length>0),P=async(r,o,t,e,s)=>{const{doc:n,table:i}=e,d=n._id;if(typeof d!="string")return{committed:!1,error:{code:"BAD_ROW",line:s,message:"a delete row needs the `_id` to delete",table:i},kind:"error"};if(t.dryRun===!0)return{kind:"checked"};const a=await O(r,o,t.exec,i,d,s);if("error"in a)return{committed:!1,error:a.error,kind:"error"};if(a.existingId===void 0)return{kind:"absent"};try{return await r.delete(i,d,{hard:!0,skipOnDelete:!0}),{kind:"deleted"}}catch(c){const{body:f}=b(c,{fallbackCode:"DELETE_FAILED"}),l=y(c,i,d),u=l?`${f.message} (row "${d}" was deleted before this failure, so its triggers or companion writes may not have completed; a re-run finds it absent and does not redo them)`:f.message;return{committed:l,error:{code:f.code,line:s,message:u,table:i},kind:"error"}}},_=async(r,o,t,e,s,n)=>{try{if(e!==void 0){const i={...t};return delete i._id,await r.replace(o,e,i,{allowExplicitId:!0}),{kind:"replaced"}}return await r.insert(o,t,{allowExplicitId:!0}),{inserted:o,kind:"inserted"}}catch(i){const{body:d}=b(i,{fallbackCode:e===void 0?"INSERT_FAILED":"REPLACE_FAILED"}),a=e??(typeof t._id=="string"?t._id:void 0),c=a!==void 0&&y(i,o,a),f=n==="replace"?'re-importing it with onConflict "replace" redoes that work':'a re-import skips it while it exists; use onConflict "replace" to redo that work',l=c?`${d.message} (row "${a}" committed before this failure, so its triggers or companion writes may not have completed; ${f})`:d.message;return{committed:c,error:{code:d.code,line:s,message:l,table:o},kind:"error"}}},G=(r,o,t,e)=>{const{doc:s,table:n}=t;if(typeof n!="string"||n.length===0)return{kind:"settled",outcome:{committed:!1,error:{code:"BAD_ROW",line:e,message:"row is missing `table`",table:n},kind:"error"}};if(r.tables[n]?.shardMode?.kind!=="global")return{kind:"settled",outcome:{kind:"skip"}};if(!s||typeof s!="object"||Array.isArray(s))return{kind:"settled",outcome:{committed:!1,error:{code:"BAD_ROW",line:e,message:"row is missing or malformed `doc`",table:n},kind:"error"}};if(t.op==="delete")return{kind:"delete",line:e,row:t};let i;try{i=S(s)}catch(a){return{kind:"settled",outcome:{committed:!1,error:{code:"BAD_ROW",line:e,message:a instanceof Error?a.message:String(a),table:n},kind:"error"}}}i=C(r.tables[n],i);const d=j(r,n,i);return d!==void 0?{kind:"settled",outcome:{committed:!1,error:{code:"VALIDATION_ERROR",line:e,message:d,table:n},kind:"error"}}:o?{kind:"settled",outcome:{kind:"checked"}}:{decoded:i,explicitId:typeof i._id=="string"?i._id:void 0,kind:"ready",line:e,table:n}},H=async(r,o,t,e,s,n)=>{const{decoded:i,explicitId:d,line:a,table:c}=s;try{if(!await R(r,o,t,c,d))return}catch{return}return e.snapshot!==void 0&&"held"in e.snapshot&&h(e.snapshot,c,d),n==="replace"?_(r,c,i,d,a,n):{kind:"conflict"}},z=async(r,o,t,e,s)=>{const{decoded:n,explicitId:i,line:d,table:a}=e;let c={existingId:void 0};if(i!==void 0&&(c=s.snapshot===void 0?await O(r,o,t.exec,a,i,d):N(s.snapshot,a,i,d)),"error"in c)return{committed:!1,error:c.error,kind:"error"};const{existingId:f}=c;if(f!==void 0&&t.onConflict!=="replace")return{kind:"conflict"};const l=await _(r,a,n,f,d,t.onConflict);if(i===void 0)return l;const{snapshot:u}=s;return u!==void 0&&"held"in u&&(l.kind==="inserted"||l.kind==="replaced"||l.kind==="error"&&l.committed)&&h(u,a,i),l.kind==="error"&&!l.committed&&l.error.code==="CONFLICT"&&f===void 0?await H(r,o,t.exec,s,{...e,explicitId:i},t.onConflict)??l:l},q=async(r,o,t,e,s)=>{const n=new Map;for(const i of e)if(i.kind==="ready"&&i.explicitId!==void 0){const d=n.get(i.table)??new Set;d.add(i.explicitId),n.set(i.table,d)}if(n.size===0)return s?{held:new Map}:void 0;try{await g(r,o,t)}catch(i){const{body:d}=b(i,{fallbackCode:"PROBE_FAILED"});return{failure:{code:d.code,message:d.message}}}return s?B(r,t,n):void 0},U=(r,o,t,e,s)=>e.kind==="settled"?Promise.resolve(e.outcome):e.kind==="delete"?P(r,o,t,e.row,e.line):z(r,o,t,e,s),ee=async(r,o,t,e)=>{const s=[],n={};let i=0,d=0,a=0,c=(e.startLine??1)-1;const f=e.rows.map(u=>(c+=1,G(o,e.dryRun===!0,u,u.line??c))),l={};e.exec&&e.dryRun!==!0&&(l.snapshot=await q(e.exec,o,t,f,!W(o)));for(const u of f){const p=await U(r,t,e,u,l);switch(p.kind){case"conflict":{i+=1;break}case"deleted":{d+=1;break}case"error":{s.push(p.error);break}case"inserted":{n[p.inserted]=(n[p.inserted]??0)+1;break}case"replaced":{a+=1;break}}}return{conflicts:i,deleted:d,errors:s,inserted:n,replaced:a}};export{Y as exportSqlGlobalRows,ee as importSqlGlobalRows,v as selectGlobalTables};
@@ -1 +1 @@
1
- import{LunoraError as w}from"@lunora/errors";import{isInternalTableName as G}from"@lunora/shard-engine";import{needsWireEncoding as v,encodeWire as M}from"@lunora/wire";import{sql as o}from"drizzle-orm";import{runSqlGlobalTableMigrations as k}from"./runSqlGlobalTableMigrations-BARAefvR.mjs";import{q as u,M as T,d as P}from"./sql-exec-enIOMsv0.mjs";import{s as W,e as Y,a as O}from"./value-codec-CbyTgWR3.mjs";const H=50,j=500,X=30,J=200,Q=(t,n,e)=>Math.min(Math.max(t,n),e),g=(t,n,e,a)=>Q(Math.trunc(t!==void 0&&Number.isFinite(t)?t:n),e,a),V=(t,n)=>G(t)||n.name==="sqlite"&&t.startsWith("d1_"),y=t=>t.name==="postgres"?o`current_schema()`:o`DATABASE()`,C=t=>t.filter(n=>Number(n.pk??0)>0).toSorted((n,e)=>Number(n.pk)-Number(e.pk)).map(n=>String(n.name)),p={columns:async(t,n,e)=>(n.name==="sqlite"?await u(t,n,o`PRAGMA table_info(${o.identifier(e)})`):await u(t,n,o`SELECT column_name AS name FROM information_schema.columns WHERE table_schema = ${y(n)} AND table_name = ${e} ORDER BY ordinal_position`)).map(r=>String(r.name)),foreignKeys:async(t,n,e)=>{let a;return n.name==="sqlite"?a=o`PRAGMA foreign_key_list(${o.identifier(e)})`:n.name==="mysql"?a=o`SELECT column_name AS ${o.identifier("from")}, referenced_table_name AS ${o.identifier("table")} FROM information_schema.key_column_usage WHERE table_schema = DATABASE() AND table_name = ${e} AND referenced_table_name IS NOT NULL AND referenced_table_schema = DATABASE()`:a=o`SELECT kcu.column_name AS ${o.identifier("from")}, ccu.table_name AS ${o.identifier("table")} FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON kcu.constraint_name = tc.constraint_name AND kcu.constraint_schema = tc.constraint_schema AND kcu.table_schema = tc.table_schema AND kcu.table_name = tc.table_name JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name AND ccu.constraint_schema = tc.constraint_schema WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = current_schema() AND tc.table_name = ${e} AND ccu.table_schema = current_schema()`,(await u(t,n,a)).map(s=>({from:String(s.from),target:String(s.table)}))},primaryKey:async(t,n,e)=>n.name==="sqlite"?C(await u(t,n,o`PRAGMA table_info(${o.identifier(e)})`)):(await u(t,n,o`SELECT kcu.column_name AS name FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema AND kcu.table_name = tc.table_name WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = ${y(n)} AND tc.table_name = ${e} ORDER BY kcu.ordinal_position`)).map(r=>String(r.name)),tables:async(t,n)=>(n.name==="sqlite"?await u(t,n,o`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name`):await u(t,n,o`SELECT table_name AS name FROM information_schema.tables WHERE table_schema = ${y(n)} AND table_type = 'BASE TABLE' ORDER BY table_name`)).map(a=>String(a.name))},z=/password|secret|token|hash|salt|credential/iu,Z=new Map([["apikey",new Set(["key"])],["jwks",new Set(["privatekey"])],["twofactor",new Set(["backupcodes"])],["verification",new Set(["value"])]]),D=t=>t.toLowerCase().replaceAll("_",""),h=(t,n)=>z.test(n)||Z.get(D(t))?.has(D(n))===!0,_=(t,n)=>{const e=t.tables[n];return e?.shardMode?.kind==="global"?e:void 0},L=async(t,n)=>(await p.tables(t,n)).filter(a=>!V(a,n)),I=async(t,n,e,a)=>{if(await k(t,e,n),!(await L(t,n)).includes(a))throw new w("UNKNOWN_TABLE",`unknown table: ${a}`,{status:404})},R=async(t,n,e,a=o``)=>{const r=await u(t,n,o`SELECT COUNT(*) AS c FROM ${o.identifier(e)}${a}`);return Number(r[0]?.c??0)},q=(t,n,e)=>_(t,n)!==void 0&&e==="_id"?"id":e,B=(t,n,e)=>{const a=_(t,n)?.shape[e];return a===void 0?void 0:Y(a)},x=/^-?\d+$/u,F=(t,n)=>{if(n>T)throw new w("BAD_REQUEST",`the query over ${t} binds ${String(n)} parameters, and a statement takes at most ${String(T)} — remove some filters`)},tt=(t,n,e)=>{if(e)return t instanceof ArrayBuffer?new Uint8Array(t):t;if(n!=="bigint")return O(t);const a=typeof t=="number"||typeof t=="string"?String(t).trim():void 0;return O(a!==void 0&&x.test(a)?BigInt(a):t,n)},nt=t=>{if(t.operator!==void 0&&t.operator!=="eq")throw new w("BAD_REQUEST",`operator "${t.operator}" is not supported on the global browser — only eq is`);if(t.path!==void 0&&!(Array.isArray(t.path)&&t.path.length===0))throw new w("BAD_REQUEST",`a nested path is not supported on the global browser, so ${t.column} must be a top-level column`)},U=(t,n,e,a,r)=>{const s=[],i=_(t,e)===void 0&&n.name!=="sqlite";let m=0;for(const c of r??[]){if(nt(c),!a.includes(c.column))throw new w("UNKNOWN_COLUMN",`unknown column: ${c.column}`,{status:404});if(_(t,e)===void 0&&h(e,c.column))throw new w("FORBIDDEN",`cannot filter on a redacted column: ${c.column}`,{status:403});const f=o.identifier(q(t,e,c.column));if(c.value===null||c.value===void 0)s.push(o`${f} IS NULL`);else{const l=tt(c.value,B(t,e,c.column),i);s.push(i&&n.name==="postgres"&&l instanceof Date?o`${f}::timestamptz = ${l}::timestamptz`:o`${f} = ${l}`),m+=1}}return{bound:m,where:s.length>0?o` WHERE ${o.join(s,o` AND `)}`:o``}},et=(t,n,e)=>{const a=_(t,n);if(a)return P(a,e);const r={};for(const[s,i]of Object.entries(e))r[s]=i!=null&&h(n,s)?"•••":i;return r},K=async(t,n,e,a)=>{const r=_(e,a);if(r)return{columns:["_id","_creationTime",...Object.keys(r.shape)],primaryKey:()=>Promise.resolve([])};if(n.name==="sqlite"){const s=await u(t,n,o`PRAGMA table_info(${o.identifier(a)})`);return{columns:s.map(i=>String(i.name)),primaryKey:()=>Promise.resolve(C(s))}}return{columns:await p.columns(t,n,a),primaryKey:()=>p.primaryKey(t,n,a)}},ot=async(t,n,e,a)=>{if(_(e,a))return;const r=await p.foreignKeys(t,n,a);if(r.length===0)return;const s={};for(const i of r){const{from:m,target:c}=i;s[m]??=c}return s},ft=async(t,n,e)=>{await k(t,n,e);const a=await L(t,e);return Promise.all(a.map(async r=>({name:r,rowCount:await R(t,e,r)})))},at=async(t,n,e,a,r)=>{if(_(n,e)!==void 0)return o`${o.identifier("id")}`;const s=await r();return s.length>0?o.join(s.map(i=>o.identifier(i)),o`, `):a.includes("id")?o`${o.identifier("id")}`:t.name==="sqlite"?o.raw("rowid"):o.join(a.map(i=>t.name==="postgres"?o`${o.identifier(i)}::text`:o.identifier(i)),o`, `)},_t=async(t,n,e,a)=>{const{table:r}=a;await I(t,e,n,r);const s=g(a.limit,H,1,j),i=g(a.offset,0,0,Number.MAX_SAFE_INTEGER),{columns:m,primaryKey:c}=await K(t,e,n,r),{bound:f,where:l}=U(n,e,r,m,a.filters);F(r,f);const A=await R(t,e,r,l),d=await at(e,n,r,m,c),S=(await u(t,e,o`SELECT * FROM ${o.identifier(r)}${l} ORDER BY ${d} LIMIT ${o.raw(String(s))} OFFSET ${o.raw(String(i))}`)).map(E=>{const N=et(n,r,E);return v(N)?M(N):N}),b=await ot(t,e,n,r);return b===void 0?{columns:m,rows:S,total:A}:{columns:m,refs:b,rows:S,total:A}},Et=async(t,n,e,a)=>{const{column:r,table:s}=a;await I(t,e,n,s);const{columns:i}=await K(t,e,n,s);if(!i.includes(r))throw new w("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const{bound:m,where:c}=U(n,e,s,i,a.filters);if(F(s,m),_(n,s)===void 0&&h(s,r)){const E=await R(t,e,s,c);return{truncated:!1,values:E===0?[]:[{count:E,value:"•••"}]}}const f=g(a.limit,X,1,J),l=o.identifier(q(n,s,r)),A=await u(t,e,o`SELECT ${l} AS value, COUNT(*) AS count FROM ${o.identifier(s)}${c} GROUP BY ${l} ORDER BY count DESC, ${l} ASC LIMIT ${o.raw(String(f+1))}`),d=A.length>f,$=d?A.slice(0,f):A,S=B(n,s,r)==="bigint",b=$.map(E=>({count:Number(E.count),value:S?W(E.value,"bigint"):E.value}));return{truncated:d,values:v(b)?M(b):b}};export{Et as facetSqlGlobalColumn,ft as listSqlGlobalTables,_t as readSqlGlobalTablePage};
1
+ import{LunoraError as w}from"@lunora/errors";import{isInternalTableName as G}from"@lunora/shard-engine";import{needsWireEncoding as v,encodeWire as M}from"@lunora/wire";import{sql as o}from"drizzle-orm";import{runSqlGlobalTableMigrations as k}from"./runSqlGlobalTableMigrations-BSYk8UQI.mjs";import{q as u,M as T,d as P}from"./sql-exec-enIOMsv0.mjs";import{s as W,e as Y,a as O}from"./value-codec-CbyTgWR3.mjs";const H=50,j=500,X=30,J=200,Q=(t,n,e)=>Math.min(Math.max(t,n),e),g=(t,n,e,a)=>Q(Math.trunc(t!==void 0&&Number.isFinite(t)?t:n),e,a),V=(t,n)=>G(t)||n.name==="sqlite"&&t.startsWith("d1_"),y=t=>t.name==="postgres"?o`current_schema()`:o`DATABASE()`,C=t=>t.filter(n=>Number(n.pk??0)>0).toSorted((n,e)=>Number(n.pk)-Number(e.pk)).map(n=>String(n.name)),p={columns:async(t,n,e)=>(n.name==="sqlite"?await u(t,n,o`PRAGMA table_info(${o.identifier(e)})`):await u(t,n,o`SELECT column_name AS name FROM information_schema.columns WHERE table_schema = ${y(n)} AND table_name = ${e} ORDER BY ordinal_position`)).map(r=>String(r.name)),foreignKeys:async(t,n,e)=>{let a;return n.name==="sqlite"?a=o`PRAGMA foreign_key_list(${o.identifier(e)})`:n.name==="mysql"?a=o`SELECT column_name AS ${o.identifier("from")}, referenced_table_name AS ${o.identifier("table")} FROM information_schema.key_column_usage WHERE table_schema = DATABASE() AND table_name = ${e} AND referenced_table_name IS NOT NULL AND referenced_table_schema = DATABASE()`:a=o`SELECT kcu.column_name AS ${o.identifier("from")}, ccu.table_name AS ${o.identifier("table")} FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON kcu.constraint_name = tc.constraint_name AND kcu.constraint_schema = tc.constraint_schema AND kcu.table_schema = tc.table_schema AND kcu.table_name = tc.table_name JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name AND ccu.constraint_schema = tc.constraint_schema WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = current_schema() AND tc.table_name = ${e} AND ccu.table_schema = current_schema()`,(await u(t,n,a)).map(s=>({from:String(s.from),target:String(s.table)}))},primaryKey:async(t,n,e)=>n.name==="sqlite"?C(await u(t,n,o`PRAGMA table_info(${o.identifier(e)})`)):(await u(t,n,o`SELECT kcu.column_name AS name FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema AND kcu.table_name = tc.table_name WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = ${y(n)} AND tc.table_name = ${e} ORDER BY kcu.ordinal_position`)).map(r=>String(r.name)),tables:async(t,n)=>(n.name==="sqlite"?await u(t,n,o`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name`):await u(t,n,o`SELECT table_name AS name FROM information_schema.tables WHERE table_schema = ${y(n)} AND table_type = 'BASE TABLE' ORDER BY table_name`)).map(a=>String(a.name))},z=/password|secret|token|hash|salt|credential/iu,Z=new Map([["apikey",new Set(["key"])],["jwks",new Set(["privatekey"])],["twofactor",new Set(["backupcodes"])],["verification",new Set(["value"])]]),D=t=>t.toLowerCase().replaceAll("_",""),h=(t,n)=>z.test(n)||Z.get(D(t))?.has(D(n))===!0,_=(t,n)=>{const e=t.tables[n];return e?.shardMode?.kind==="global"?e:void 0},L=async(t,n)=>(await p.tables(t,n)).filter(a=>!V(a,n)),I=async(t,n,e,a)=>{if(await k(t,e,n),!(await L(t,n)).includes(a))throw new w("UNKNOWN_TABLE",`unknown table: ${a}`,{status:404})},R=async(t,n,e,a=o``)=>{const r=await u(t,n,o`SELECT COUNT(*) AS c FROM ${o.identifier(e)}${a}`);return Number(r[0]?.c??0)},q=(t,n,e)=>_(t,n)!==void 0&&e==="_id"?"id":e,B=(t,n,e)=>{const a=_(t,n)?.shape[e];return a===void 0?void 0:Y(a)},x=/^-?\d+$/u,F=(t,n)=>{if(n>T)throw new w("BAD_REQUEST",`the query over ${t} binds ${String(n)} parameters, and a statement takes at most ${String(T)} — remove some filters`)},tt=(t,n,e)=>{if(e)return t instanceof ArrayBuffer?new Uint8Array(t):t;if(n!=="bigint")return O(t);const a=typeof t=="number"||typeof t=="string"?String(t).trim():void 0;return O(a!==void 0&&x.test(a)?BigInt(a):t,n)},nt=t=>{if(t.operator!==void 0&&t.operator!=="eq")throw new w("BAD_REQUEST",`operator "${t.operator}" is not supported on the global browser — only eq is`);if(t.path!==void 0&&!(Array.isArray(t.path)&&t.path.length===0))throw new w("BAD_REQUEST",`a nested path is not supported on the global browser, so ${t.column} must be a top-level column`)},U=(t,n,e,a,r)=>{const s=[],i=_(t,e)===void 0&&n.name!=="sqlite";let m=0;for(const c of r??[]){if(nt(c),!a.includes(c.column))throw new w("UNKNOWN_COLUMN",`unknown column: ${c.column}`,{status:404});if(_(t,e)===void 0&&h(e,c.column))throw new w("FORBIDDEN",`cannot filter on a redacted column: ${c.column}`,{status:403});const f=o.identifier(q(t,e,c.column));if(c.value===null||c.value===void 0)s.push(o`${f} IS NULL`);else{const l=tt(c.value,B(t,e,c.column),i);s.push(i&&n.name==="postgres"&&l instanceof Date?o`${f}::timestamptz = ${l}::timestamptz`:o`${f} = ${l}`),m+=1}}return{bound:m,where:s.length>0?o` WHERE ${o.join(s,o` AND `)}`:o``}},et=(t,n,e)=>{const a=_(t,n);if(a)return P(a,e);const r={};for(const[s,i]of Object.entries(e))r[s]=i!=null&&h(n,s)?"•••":i;return r},K=async(t,n,e,a)=>{const r=_(e,a);if(r)return{columns:["_id","_creationTime",...Object.keys(r.shape)],primaryKey:()=>Promise.resolve([])};if(n.name==="sqlite"){const s=await u(t,n,o`PRAGMA table_info(${o.identifier(a)})`);return{columns:s.map(i=>String(i.name)),primaryKey:()=>Promise.resolve(C(s))}}return{columns:await p.columns(t,n,a),primaryKey:()=>p.primaryKey(t,n,a)}},ot=async(t,n,e,a)=>{if(_(e,a))return;const r=await p.foreignKeys(t,n,a);if(r.length===0)return;const s={};for(const i of r){const{from:m,target:c}=i;s[m]??=c}return s},ft=async(t,n,e)=>{await k(t,n,e);const a=await L(t,e);return Promise.all(a.map(async r=>({name:r,rowCount:await R(t,e,r)})))},at=async(t,n,e,a,r)=>{if(_(n,e)!==void 0)return o`${o.identifier("id")}`;const s=await r();return s.length>0?o.join(s.map(i=>o.identifier(i)),o`, `):a.includes("id")?o`${o.identifier("id")}`:t.name==="sqlite"?o.raw("rowid"):o.join(a.map(i=>t.name==="postgres"?o`${o.identifier(i)}::text`:o.identifier(i)),o`, `)},_t=async(t,n,e,a)=>{const{table:r}=a;await I(t,e,n,r);const s=g(a.limit,H,1,j),i=g(a.offset,0,0,Number.MAX_SAFE_INTEGER),{columns:m,primaryKey:c}=await K(t,e,n,r),{bound:f,where:l}=U(n,e,r,m,a.filters);F(r,f);const A=await R(t,e,r,l),d=await at(e,n,r,m,c),S=(await u(t,e,o`SELECT * FROM ${o.identifier(r)}${l} ORDER BY ${d} LIMIT ${o.raw(String(s))} OFFSET ${o.raw(String(i))}`)).map(E=>{const N=et(n,r,E);return v(N)?M(N):N}),b=await ot(t,e,n,r);return b===void 0?{columns:m,rows:S,total:A}:{columns:m,refs:b,rows:S,total:A}},Et=async(t,n,e,a)=>{const{column:r,table:s}=a;await I(t,e,n,s);const{columns:i}=await K(t,e,n,s);if(!i.includes(r))throw new w("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const{bound:m,where:c}=U(n,e,s,i,a.filters);if(F(s,m),_(n,s)===void 0&&h(s,r)){const E=await R(t,e,s,c);return{truncated:!1,values:E===0?[]:[{count:E,value:"•••"}]}}const f=g(a.limit,X,1,J),l=o.identifier(q(n,s,r)),A=await u(t,e,o`SELECT ${l} AS value, COUNT(*) AS count FROM ${o.identifier(s)}${c} GROUP BY ${l} ORDER BY count DESC, ${l} ASC LIMIT ${o.raw(String(f+1))}`),d=A.length>f,$=d?A.slice(0,f):A,S=B(n,s,r)==="bigint",b=$.map(E=>({count:Number(E.count),value:S?W(E.value,"bigint"):E.value}));return{truncated:d,values:v(b)?M(b):b}};export{Et as facetSqlGlobalColumn,ft as listSqlGlobalTables,_t as readSqlGlobalTablePage};
@@ -0,0 +1 @@
1
+ import{I as n,M as r,h as i,f as o,g as d,b as t,j as g,i as b,c as I,l as T,e as c,k as m,p,d as u,r as x,a as S,u as E}from"./ctx-db-migrations-BGcbBPWX.mjs";import"./sql-exec-enIOMsv0.mjs";import"./value-codec-CbyTgWR3.mjs";export{n as INDEX_LEDGER_TABLE,r as MIGRATION_STATE_TABLE,i as declaredIndexColumnList,o as foldIdentifier,d as globalTableColumnsDdl,t as globalTableIndexSpecs,g as indexColumnList,b as indexLedgerDdl,I as indexShapeChanged,T as legacyRewrites,c as legacyRowPredicate,m as provisionGlobalTable,p as provisionGlobalTablesSequentially,u as recordIndexStatement,x as runSqlAggregateMigrations,S as runSqlRankMigrations,E as undeclaredFrameworkIndexes};
@@ -0,0 +1 @@
1
+ import{sql as a}from"drizzle-orm";import{p as m,f as c,g as A,b as L,l as O,i as R,w as k,u as y,c as $,I as T,M as E,d as M,e as C}from"./ctx-db-migrations-BGcbBPWX.mjs";import{a as q,q as g}from"./sql-exec-enIOMsv0.mjs";const v=50,h=new Map([["'","'"],["[","]"],["`","`"],['"','"']]),N=/^[\w$]+/u,b=(e,s)=>{const n=h.get(e[s]);let t=s+1;for(;t<e.length;)if(e[t]!==n)t+=1;else if(n!=="]"&&e[t+1]===n)t+=2;else return t+1;return t},_=e=>{const s=e.trim(),n=h.get(s[0]??"");if(n===void 0)return N.exec(s)?.[0];const t=b(s,0),r=s.slice(1,s[t-1]===n?t-1:t);return n==="]"?r:r.replaceAll(`${n}${n}`,n)},B=e=>{const s=new Set,n=i=>{const d=_(i);d!==void 0&&s.add(d)};let t=0,r=0,o=0;for(;o<e.length;){const i=e[o];if(h.has(i)){o=b(e,o);continue}if(i==="(")t+=1,r=t===1?o+1:r;else if(i===")"){if(t-=1,t===0)return n(e.slice(r,o)),s}else i===","&&t===1&&(n(e.slice(r,o)),r=o+1);o+=1}return s},F=async(e,s,n)=>{const t=new Set,r=new Map,o=n.has(c(T)),i=[];if(n.has(c(E))&&i.push(a`SELECT 'marker' AS kind, name, NULL AS owner FROM ${a.identifier(E)}`),o&&i.push(a`SELECT 'index' AS kind, "l"."name" AS name, "l"."table_name" AS owner FROM ${a.identifier(T)} AS "l"`),i.length===0)return{hasLedger:o,markers:t,owned:r};for(const d of await g(e,s,a.join(i,a` UNION ALL `)))if(d.kind==="marker")t.add(String(d.name));else{const f=c(String(d.owner));r.set(f,[...r.get(f)??[],String(d.name)])}return{hasLedger:o,markers:t,owned:r}},D=async(e,s)=>{try{const n=await g(e,s,a`SELECT type, name, tbl_name, sql FROM sqlite_master WHERE type IN ('table', 'index')`),t=new Set,r=new Map,o=new Map;for(const l of n){const u=String(l.name);if(u.startsWith("sqlite_"))continue;const S=typeof l.sql=="string"?l.sql:void 0;l.type==="table"?(t.add(c(u)),r.set(c(u),new Set([...S===void 0?[]:B(S)].map(I=>c(I))))):o.set(c(u),S)}const{hasLedger:i,markers:d,owned:f}=await F(e,s,t);return{columns:r,hasLedger:i,indexes:o,markers:d,owned:f,tables:t}}catch{return}},w=e=>e.kind==="default-order"?[]:[M(e.name,e.table)],p=e=>{const s=e.unique?a`UNIQUE `:a``;return a`CREATE ${s}INDEX IF NOT EXISTS ${a.identifier(e.name)} ON ${a.identifier(e.table)} (${e.columns})`},x=(e,s,n)=>n.length===0?[]:[a`CREATE TABLE IF NOT EXISTS ${a.identifier(E)} (${a.identifier("name")} ${a.raw(e.companionTypes.key)} PRIMARY KEY)`,...n.map(t=>a`INSERT OR IGNORE INTO ${a.identifier(E)} (${a.identifier("name")}) SELECT ${t.marker} WHERE NOT EXISTS (SELECT 1 FROM ${a.identifier(s)} WHERE ${C(t)})`)],G=(e,s,n,t)=>{const r=A(e,s,n),o=L(e,s,n),i=O(e,s);if(!t.tables.has(c(e)))return[...t.hasLedger?[]:[R()],a`CREATE TABLE IF NOT EXISTS ${a.identifier(e)} (${r})`,...o.flatMap(l=>[p(l),...w(l)]),...x(n,e,i)];const d=t.columns.get(c(e))??new Set;if(k(s,n).some(([l])=>!d.has(c(l)))||i.some(l=>!t.markers.has(l.marker))||y(n,o,t.owned.get(c(e))??[]).length>0)return;const f=[];for(const l of o){if(!t.indexes.has(c(l.name))){f.push(p(l),...w(l));continue}const u=t.indexes.get(c(l.name));if(l.kind==="declared"&&typeof u=="string"&&$(n,u,l))return}return f},X=e=>{const s=[];let n=[],t=0;for(const r of e)n.length>0&&t+r.statements.length>v&&(s.push(n),n=[],t=0),n.push(r),t+=r.statements.length;return n.length>0&&s.push(n),s},U=(e,s)=>!s.hasLedger&&Object.entries(e.tables).some(([n,t])=>t.shardMode?.kind==="global"&&s.tables.has(c(n))),Q=async(e,s,n)=>{if(!e.batch||n.name!=="sqlite"){await m(e,s,n);return}const t=await D(e,n);if(t===void 0){await m(e,s,n);return}if(U(s,t)){await m(e,s,n);return}const r=[],o=new Set;for(const[i,d]of Object.entries(s.tables)){if(d.shardMode?.kind!=="global")continue;const f=G(i,d,n,t);f===void 0?o.add(i):f.length>0&&r.push({statements:f,table:i})}for(const i of X(r))try{await q(e,n,i.flatMap(d=>d.statements))}catch{for(const d of i)o.add(d.table)}await m(e,s,n,o)};export{B as columnNamesOfCreateTable,Q as runSqlGlobalTableMigrations};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/sql-store",
3
- "version": "1.0.0-alpha.234",
3
+ "version": "1.0.0-alpha.236",
4
4
  "description": "Internal dialect-parameterized SQL store core for Lunora .global() backends (D1, PlanetScale)",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -51,7 +51,7 @@
51
51
  },
52
52
  "dependencies": {
53
53
  "@lunora/errors": ">=1.0.0-alpha.77 <2.0.0-0",
54
- "@lunora/shard-engine": "^1.0.0-alpha.187",
54
+ "@lunora/shard-engine": "^1.0.0-alpha.191",
55
55
  "@lunora/wire": "1.0.0-alpha.6",
56
56
  "drizzle-orm": "1.0.0-rc.5"
57
57
  },
@@ -1,7 +0,0 @@
1
- import{LunoraError as g}from"@lunora/errors";import{m as vn,q as In}from"./ctx-db-search-state-BBPiVWjf.mjs";import{c as An,r as Cn,a as Ln,A as bn,C as Mn,R as Nn,u as On,d as qn,T as kn,x as Dn,e as Bn}from"./ctx-db-search-bBDPdaOs.mjs";import{throwingScheduler as Wn,describeRelationWrites as Fn,CDC_LOG_TABLE as W,cdcForkedError as xn,cursorBelowRetainedFloor as Un,cdcTrimmedError as Pn,serverInList as Hn,assertNoExplicitUndefined as Ve,hasTrigger as Kn,runRowValidators as Ye,assertFlatPredicate as gt,mergeWhere as x,rankTableName as ye,sortColumnName as ge,resolveRankPartition as Tt,encodePartitionKey as ke,resolveRankSeekTuple as jn,RANK_TIEBREAK as Ie,CountRlsUnsupportedError as vt,compileWhereSql as ee,ConflictError as ne,patchDependsOnRow as Gn,normalizeIdStructurally as Vn,applyInsertDefaults as Yn,assertValidClientId as Xn,assertStorableRowId as Qn,aggregateSqlFunction as Re,softDeleteScope as De,resolveWith as It,relationHooks as At,applySelect as Ct,encodeCursor as zn,NotFoundError as Jn,applyOnDelete as Zn,normalizeCountArgument as ei,selectIndexForCount as ti,encodeAggregateKey as te,aggregateTableName as ce,selectIndexForAggregate as ni,readAggregateValue as Xe,runTriggers as ii,matchesRankStaticWhere as Lt,nullsOrderSuffix as bt,nullsFirstOf as Mt,rankPivotConditionSql as Qt,CURSOR_PREFIX as oi,resolvePatch as ri,stripReservedPatchFields as si,assertPatchAllowed as ai,resolveRelationPredicates as ci,selectIndexForGroupBy as di,composeReadPredicate as li,fanOutScalarCounts as ui,matchesStaticWhere as Qe,coerceAggregateNumber as ze,whereOfFilter as fi,isPushableWhere as wi,tiebreakDirectionFor as hi,foldAggregateTally as Nt,CDC_LOG_TABLE_SEQ_INDEX as $i,NotUniqueError as _i,WORKERD_SQLITE_LIMITS as Ei,unionAll as pi}from"@lunora/shard-engine";import{parseWire as yi,needsWireEncoding as zt,encodeWire as Jt,decodeWire as Ri}from"@lunora/wire";import{sql as e,SQL as mi}from"drizzle-orm";import{p as Ot,b as qt,q as b,c as K,e as Zt,i as Si,f as gi,g as Ti,h as z,s as de,j as H,k as kt,t as vi,l as Je,m as Fe,n as at,O as me,o as Dt,a as Bt,u as Wt,v as Ft,w as Ii,B as Ze,x as xt,y as Ut,M as Ai}from"./sql-exec-enIOMsv0.mjs";import{d as Oo}from"./sql-exec-enIOMsv0.mjs";import{runSqlGlobalTableMigrations as Ci}from"./runSqlGlobalTableMigrations-BARAefvR.mjs";import{runSqlAggregateMigrations as Li,runSqlRankMigrations as bi}from"./runSqlAggregateMigrations-D5_8KDaC.mjs";import{a as Se}from"./post-commit-error-hh-zQyjO.mjs";import{withQueryTimeout as Mi,DEFAULT_QUERY_TIMEOUT_MS as Ni,abandonedWork as et,SqlQueryTimeoutError as Oi}from"./DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import{s as en,e as ct}from"./value-codec-CbyTgWR3.mjs";const Pt=50,qi=(r,a={})=>{const f=a.maxBatch??Pt,$=Number.isInteger(f)&&f>0?f:Pt,l=new Map;let _=!1;const c=async(M,T)=>{const v=[...T.keys()];for(let A=0;A<v.length;A+=$){const N=v.slice(A,A+$);try{const D=await r(M,N);for(const j of N){const J=D.get(j);for(const ie of T.get(j)??[])ie.resolve(J)}}catch(D){for(const j of N)for(const J of T.get(j)??[])J.reject(D)}}},q=()=>{_=!1;const M=[...l.entries()];l.clear();for(const[T,v]of M)c(T,v).catch(()=>{})};return{async load(M,T){return new Promise((v,A)=>{let N=l.get(M);N||(N=new Map,l.set(M,N));const D=N.get(T);D?D.push({reject:A,resolve:v}):N.set(T,[{reject:A,resolve:v}]),_||(_=!0,queueMicrotask(q))})}}},ki=new Set(["_id","id"]),Di=r=>{throw new g("INTERNAL",`no ORDER BY NULL placement for dialect "${String(r)}"`)},tn=(r,a)=>{const f=a.direction==="desc"?"DESC":"ASC",$=a.nullable===!0,l=_=>e`${Fe(r,a.field)} ${e.raw(`${f}${_}`)}`;switch(r.name){case"mysql":{const _=l("");return!$||a.nulls===void 0?[_]:[e`(${Fe(r,a.field)} IS NULL) ${e.raw(a.nulls==="first"?"DESC":"ASC")}`,_]}case"postgres":return[l($?bt(Mt(a)):"")];case"sqlite":return[l($&&a.nulls!==void 0?bt(Mt(a)):"")];default:return Di(r.name)}},Bi=(r,a)=>{const f=r.flatMap($=>tn(a,$));if(!r.some($=>ki.has($.field))){const $=hi(r);f.push(e`${H("id")} ${e.raw($==="desc"?"DESC":"ASC")}`)}return e.join(f,e`, `)},Ht=50,Wi=r=>{const a=r.detail??r["QUERY PLAN"];return typeof a=="string"?a:Object.values(r).map(String).join(" | ")},tt=(r,a,f,$)=>{for(const[l,_]of vi(r)){if(_.serverDefault){l in a&&(f[l]=_.serverDefault({auth:$}));continue}_.onUpdateFn&&!(l in a)&&(f[l]=_.onUpdateFn())}},Fi=r=>r.shardMode===void 0||r.shardMode.kind==="global",fe=r=>r==null?null:Number(r),xi=(r,a,f)=>f.map($=>{const l={};for(const _ of a){const c=r.shape[_];l[_]=en($[_]??null,c&&ct(c))}return{key:l,value:fe($.value)}}),Ui=(r,a,f)=>[...r.partitionBy??[],...r.sortBy.map(l=>l.field),...r.where?Object.keys(r.where):[]].every(l=>Wt(a,l)===Wt(f,l)),nn=r=>r.length===1?r[0]:e`(${e.join(r,e` AND `)})`,we=r=>e.join(r.map(a=>e`${e.identifier(a)}`),e`, `),Te=r=>e.join(r.map(a=>e`${a}`),e`, `),nt=(r,a)=>{if(r==="postgres"){for(const[f,$]of Object.entries(a))if(typeof $=="string"&&$.includes("\0"))throw new g("BAD_REQUEST",`"${f}" holds a NUL character (U+0000), which a Postgres text column cannot store`)}},xe=r=>r instanceof ArrayBuffer?new Uint8Array(r):Array.isArray(r)?Uint8Array.from(r):r,Pi=(r,a,f,$,l)=>{const _=[];for(let c=0;c<f.length+1;c+=1){const q=f[c],M=a.sortBy[c],T=c<f.length&&q!==void 0&&M!==void 0,v=M?.direction==="desc"?"desc":"asc",A=T?Qt(q,xe($[q]),v,!1):e`${e.identifier(Ie)} < ${l}`;if(A===void 0)continue;const N=f.slice(0,c).map(D=>at(r,e`${e.identifier(D)}`,xe($[D])));N.push(A),_.push(nn(N))}return _.length>0?e.join(_,e` OR `):e`1 = 0`},Hi=(r,a,f)=>{if(f.length!==a.length)return;const $=[];for(const[l,_]of a.entries()){const c=Qt(_.column,xe(f[l]),_.direction,!0);if(c===void 0)continue;const q=[];for(let M=0;M<l;M+=1){const T=a[M];T!==void 0&&q.push(at(r,e`${e.identifier(T.column)}`,xe(f[M])))}q.push(c),$.push(nn(q))}return $.length===0?e`(1 = 0)`:e`(${e.join($,e` OR `)})`},Ki=(r,a)=>{if(r.sortBy.length===0)throw new g("INTERNAL",`rankIndex "${r.name}" requires at least one "sortBy" column for stable pagination`);const f=[{column:"__partition__",direction:"asc",nullable:!1}];for(const[$,l]of r.sortBy.entries())f.push({column:a[$]??ge($),direction:l.direction,nullable:!0});return f.push({column:Ie,direction:"asc",nullable:!1}),f},ji=async(r,a,f,$,l)=>{const c=[];for(let v=0;v<l.length;v+=50)c.push(l.slice(v,v+50));const q=await Promise.all(c.map(async v=>b(r,a,e`SELECT * FROM ${e.identifier($)} WHERE ${e.identifier("id")} IN (${Te(v)})`))),M=new Map;for(const v of q)for(const A of v)M.set(A.id,A);const T=[];for(const v of l){const A=z(f,M.get(v));A&&T.push(A)}return T},Gi=r=>{const a=r.map(_=>en(_,"bytes")),f=JSON.stringify(zt(a)?Jt(a):a),$=new TextEncoder().encode(f);let l="";for(const _ of $)l+=String.fromCodePoint(_);return oi+btoa(l)},on=r=>{if(r===void 0)return!1;const a=ct(r);return a==="any"||a==="bigint"||a==="from"||a==="union"},rt=(r,a,f)=>{if(on(r.shape[a]))throw new g("BAD_REQUEST",`${f}: "${a}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Vi=(r,a,f,$)=>{for(const l of f)rt(r,l,`groupBy(${a}, { by: [..."${l}"] })`);$.field!==void 0&&rt(r,$.field,`groupBy(${a}, { agg: { op: "${$.op}", field: "${$.field}" } })`)},st="__cdc_sweep",Be="__cdc_log_ts",rn="global",Yi=6e4,Xi=1e4,Qi=3e4;let Kt=0;const zi=async(r,a)=>{const{autoincrementPrimaryKey:f,key:$,real:l,text:_}=a.companionTypes;await K(r,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(W)} (${e.identifier("seq")} ${e.raw(f)}, ${e.identifier("ts")} ${e.raw(l)} NOT NULL, ${e.identifier("table")} ${e.raw($)} NOT NULL, ${e.identifier("id")} ${e.raw($)} NOT NULL, ${e.identifier("op")} ${e.raw($)} NOT NULL, ${e.identifier("doc")} ${e.raw(_)})`);const c=a.indexKeyPrefix?.("string");await Zt(r,a,{columns:e`${c===void 0?e`${e.identifier("table")}`:e`${e.identifier("table")}(${e.raw(String(c))})`}, ${e.identifier("seq")}`,name:$i,table:W,unique:!1}),await K(r,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(st)} (${e.identifier("id")} ${e.raw($)} NOT NULL PRIMARY KEY, ${e.identifier("lease_until")} ${e.raw(l)} NOT NULL)`),await K(r,a,e`INSERT INTO ${e.identifier(st)} (${e.identifier("id")}, ${e.identifier("lease_until")}) VALUES (${rn}, ${0}) ${a.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${e.identifier("id")} = ${e.identifier("id")}`:e`ON CONFLICT(${e.identifier("id")}) DO NOTHING`}`)},Ji=async(r,a,f)=>{const $=e`UPDATE ${e.identifier(st)} SET ${e.identifier("lease_until")} = ${f+Yi} WHERE ${e.identifier("id")} = ${rn} AND ${e.identifier("lease_until")} <= ${f}`;if(a.supportsReturning)return(await b(r,a,e`${$} RETURNING ${e.identifier("id")}`)).length>0;const l=await K(r,a,$);return(a.affectedRows?a.affectedRows(l??{rowsAffected:0}):0)>0},Zi=async(r,a,f,$)=>{if(!await Ji(r,a,$))return;const l=$-f;let _=!0;try{const c=await Si(r,a,W,Be);c!=="valid"&&(c==="invalid"&&await gi(r,a,W,Be),await Zt(r,a,{columns:e`${e.identifier("ts")}`,concurrently:!0,name:Be,table:W,unique:!1}))}catch(c){_=!1,console.warn(`[@lunora/sql-store] changelog retention could not build "${Be}"; sweeping without it.`,c)}_&&(await b(r,a,e`SELECT 1 AS ${e.identifier("hit")} FROM ${e.identifier(W)} WHERE ${e.identifier("ts")} <= ${l} LIMIT 1`)).length===0||await K(r,a,e`
2
- DELETE FROM ${e.identifier(W)} WHERE ${e.identifier("seq")} IN (
3
- SELECT ${e.identifier("seq")} FROM (
4
- SELECT ${e.identifier("seq")} FROM ${e.identifier(W)} WHERE +${e.identifier("ts")} <= ${l} ORDER BY ${e.identifier("seq")} ASC LIMIT ${e.raw(String(Xi))}
5
- ) AS ${e.identifier("expired")}
6
- )
7
- `)},sn=async(r,a)=>{const f=await b(r,a,e`SELECT MIN(${e.identifier("seq")}) AS ${e.identifier("seq")} FROM ${e.identifier(W)}`),$=Number(f[0]?.seq??Number.NaN);return Number.isFinite($)?$:void 0},eo=async(r,a)=>{if(a.name!=="sqlite")return;const f=await b(r,a,e`SELECT ${e.identifier("seq")} AS ${e.identifier("seq")} FROM ${e.identifier("sqlite_sequence")} WHERE ${e.identifier("name")} = ${W}`),$=Number(f[0]?.seq??Number.NaN);return Number.isFinite($)?$:0},to=r=>JSON.stringify(zt(r)?Jt(r):r),no=(r,a,f,$,l)=>e`INSERT INTO ${e.identifier(W)} (${e.identifier("ts")}, ${e.identifier("table")}, ${e.identifier("id")}, ${e.identifier("op")}, ${e.identifier("doc")}) VALUES (${r}, ${a}, ${f}, ${$}, ${l===void 0?null:to(l)})`,an=1e4,io=1e3,oo=(r,a,f)=>{let $=a;for(const[l,_]of r.entries()){const c=Number(_.seq);if(c>$+1&&Number(_.ts)>f)return r.slice(0,l);$=c}return r},bo=async(r,a,f)=>{const $=a.sinceSeq??0,l=Math.max(1,Math.min(a.limit??1e3,1e4)),_=await sn(r,f),c=await eo(r,f);if(c!==void 0&&$>c)throw xn(c,$,"global");if(_!==void 0&&Un(_,$))throw Pn(_,$,"global");const q=await b(r,f,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(W)} WHERE seq > ${$} ORDER BY seq ASC LIMIT ${e.raw(String(l))}`),T=(f.name==="sqlite"?q:oo(q,$,(a.now??Date.now())-an)).map(v=>{const{doc:A}=v,N={id:String(v.id),op:String(v.op),seq:Number(v.seq),table:String(v.table),ts:Number(v.ts)};return typeof A=="string"?{...N,doc:yi(A)}:N});return{changes:T,cursor:T.at(-1)?.seq??$}},jt=(r,a)=>{const f=e.identifier(W),$=e`(SELECT MIN(v.seq) FROM ${f} v WHERE v.seq > ${r} AND v.seq - 1 > ${r} AND v.ts > ${a} AND NOT EXISTS (SELECT 1 FROM ${f} p WHERE p.seq = v.seq - 1))`;return e`${$} AS ${e.identifier("gap")}, (SELECT MAX(q.seq) FROM ${f} q WHERE q.seq > ${r} AND q.seq < ${$}) AS ${e.identifier("below")}`},Gt=(r,a,f)=>{const $=Number(a?.gap??Number.NaN);if(!Number.isFinite($))return r;const l=Number(a?.below??Number.NaN);return Math.min(r,Number.isFinite(l)?l:f)},ro=r=>{const a=e.identifier(W),f=e.identifier("table");return e`SELECT ${f}, seq FROM (WITH RECURSIVE "t"("name") AS (SELECT MIN(${f}) FROM ${a} UNION ALL SELECT (SELECT MIN(${f}) FROM ${a} WHERE ${f} > "t"."name") FROM "t" WHERE "t"."name" IS NOT NULL) SELECT "t"."name" AS ${f}, (SELECT MAX(seq) FROM ${a} WHERE ${f} = "t"."name" AND seq > ${r}) AS seq FROM "t" WHERE "t"."name" IS NOT NULL) WHERE seq IS NOT NULL ORDER BY ${f}`},so=async(r,a,f,$={})=>{const l=e.identifier(W),_=f.name!=="sqlite",c=($.now??Date.now())-an;if($.cursorOnly){const A=e`GREATEST((SELECT MAX(seq) FROM ${l}) - ${e.raw(String(io))}, ${a})`,N=await b(r,f,e`SELECT MAX(seq) AS seq${_?e`, ${jt(A,c)}`:e``} FROM ${l}`),D=Number(N[0]?.seq??a);return{cursor:Gt(Number.isFinite(D)?D:a,N[0],a),tables:[]}}const q=await b(r,f,_?e`SELECT ${e.identifier("table")} AS ${e.identifier("table")}, MAX(seq) AS seq, ${jt(e`${a}`,c)} FROM ${l} WHERE seq > ${a} GROUP BY ${e.identifier("table")}`:ro(a));let M=a;const T=[];for(const A of q){const N=Number(A.seq);Number.isFinite(N)&&N>M&&(M=N),T.push(String(A.table))}M=Gt(M,q[0],a);const v=$.retained===!0?await sn(r,f):void 0;return{cursor:M,tables:T,...v===void 0?{}:{floor:v}}},ao=/string or blob too big/iu,co=/row is too big/iu,lo=(r,a)=>{const{code:f,errno:$}=a,l=a instanceof Error?a.message:"";switch(r.name){case"mysql":return $===1118||f==="ER_TOO_BIG_ROWSIZE"?"InnoDB's per-row ceiling — roughly 8 KB, half a 16 KB page, for the part of the row stored inline":void 0;case"postgres":return co.test(l)?"the 8 KB heap page a tuple must fit once its wide columns have been TOASTed out":void 0;default:return ao.test(l)?"the storage engine's per-row ceiling (2 MB on D1)":void 0}},uo=(r,a,f)=>{const $=lo(r,a);if($!==void 0)throw new g("PAYLOAD_TOO_LARGE",`document is too large to store in "${f}": a single row cannot exceed ${$}. The limit is on the STORED bytes, which are UTF-8. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},it=16,Vt="__lunora_patch_if_match__",Yt=(r,a,f)=>{throw r.isUniqueViolation(a)?new ne(`unique constraint violation on "${f}"`,"unique"):(uo(r,a,f),a)},fo=r=>{const{code:a,errno:f}=r??{};return a==="40P01"||a==="40001"||f===1213||a==="ER_LOCK_DEADLOCK"},wo=r=>{throw fo(r)?new ne("the write's transaction was rolled back by a lock conflict with a concurrent write; retry it","occ"):r},ot=new WeakMap,Xt=new WeakMap,le="superseded",ho=3e4,ve="__lunora_companion_fence",$o=(r,a,f,$,l)=>{const _=Math.max(1,Math.floor((Ai-2)/$.length)),c=(T,v)=>{const A=r.name==="postgres"?e`CAST(${T} AS ${e.raw(v.type)})`:e`${T}`;return e`${A} AS ${e.identifier(v.name)}`},q=T=>e`SELECT ${e.join(T.map((v,A)=>c(v,$[A])),e`, `)}`,M=[];for(let T=0;T<l.length;T+=_){const v=l.slice(T,T+_).map(A=>q(A));M.push(e`INSERT INTO ${e.identifier(a)} (${we($.map(A=>A.name))}) SELECT * FROM (${pi(v)}) AS ${e.identifier("__rows__")} WHERE EXISTS (SELECT 1 FROM ${e.identifier(ve)} WHERE ${f})`)}return M},ue=(r,a,f)=>JSON.stringify([r,a,f]),We=r=>JSON.stringify(r,(a,f)=>typeof f=="bigint"?`${String(f)}n`:f),_o=r=>{const a=Hn(r);return(f,$,l,_)=>$.some(c=>c instanceof mi)?Ti(r,f,$,l):a(f,$,l,_)},Eo=r=>{const{crossShardCounter:a,crossShardReader:f,maxRelationKeys:$,schema:l}=r,_=Mi(r.exec,r.queryTimeoutMs??Ni,r.queryTimer),{dialect:c}=r,q={fieldRef:t=>Fe(c,t),rangeTypeGuard:(t,n)=>Ii(c,t,n),...c.name==="mysql"?{containsExpr:(t,n)=>{const i=Ot(t);return i===void 0?e`LOCATE(${n}, ${t}) > 0`:e`LOCATE(${qt("mysql",n)}, ${i}) > 0`}}:{},...c.name==="postgres"?{containsExpr:(t,n)=>{const i=Ot(t);return i===void 0?e`strpos(${t}, ${n}) > 0`:e`strpos(${i}, ${qt("postgres",n)}) > 0`}}:{},...c.name==="sqlite"?{}:{inList:_o(c.name)}},M=new WeakMap,T=t=>{const n=M.get(t);if(n!==void 0)return n;const i={...q,serialize:(o,s)=>Ft(c,s,o,d=>de(t,s,d))};return M.set(t,i),i},v=(t,n)=>at(c.name,t,n),A=t=>{const n=we(t.columns),i=Te(t.values),o=h=>c.name==="mysql"?e`VALUES(${e.identifier(h)})`:e`excluded.${e.identifier(h)}`,s=h=>c.name==="postgres"?e`${e.identifier(t.table)}.${e.identifier(h)}`:e`${e.identifier(h)}`,d=e.join(Object.entries(t.set(o,s)).map(([h,y])=>e`${e.identifier(h)} = ${y}`),e`, `),u=c.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${d}`:e`ON CONFLICT(${e.identifier(t.conflictKey)}) DO UPDATE SET ${d}`;return e`INSERT INTO ${e.identifier(t.table)} (${n}) VALUES (${i}) ${u}`},N=r.clock??(()=>Date.now()),D=r.idGenerator??(()=>crypto.randomUUID()),j=r.cdc??!1,J=typeof r.cdcRetentionMs=="number"&&Number.isFinite(r.cdcRetentionMs)&&r.cdcRetentionMs>0?r.cdcRetentionMs:void 0,ie=r.auth??{identity:null,userId:null},he=(t,n,i,o)=>j?[no(N(),t,n,i,o)]:[],cn=async()=>{if(!j||J===void 0)return;const t=N();if(!(t-Kt<Qi)){Kt=t;try{await Zi(_,c,J,t)}catch{}}},dn=r.scheduler??Wn;let Ae=0;const oe=r.provisionScope??{},F=async()=>{const t=ot.get(oe);if(t)return t;const n=(async()=>{const i=r.exec;await Ci(i,l,c),await Li(i,l,c),await bi(i,l,c),await vn(i,c),await Cn(_,l,c),j&&await zi(i,c)})().catch(i=>{throw ot.delete(oe),i});return ot.set(oe,n),n},$e=async t=>{if(typeof t!="string"||!Object.hasOwn(l.tables,t))throw new g("BAD_REQUEST",`ctx.db by-id write (table, id): "${t}" is not a table in this schema`);await F();const n=l.tables[t];return n!==void 0&&Fi(n)?t:void 0};let Ce=Xt.get(oe);Ce===void 0&&(Ce=new Map,Xt.set(oe,Ce));const U=Ce;let Ue=0;const dt={},Pe=(t,n,i)=>{const o=(async()=>(await F(),await i(()=>U.get(t)?.run!==o)))(),s={definition:n,owner:dt,run:o,settled:!1};return o.then(d=>{d===le&&U.get(t)===s?U.delete(t):s.settled=!0},()=>{U.get(t)===s&&U.delete(t)}).catch(()=>{}),U.set(t,s),o},lt=async(t,n,i)=>{const o=U.get(t);if(o===void 0)return await Pe(t,n,i);const s=o.definition===n;if(s&&(o.settled||o.owner===dt))return await o.run;if(o.settled)return await Pe(t,n,i);let d;const u=new Promise(y=>{d=setTimeout(y,ho,"stalled")}),h=await Promise.race([o.run,u]).finally(()=>{clearTimeout(d)});return h!=="stalled"&&s?h:U.get(t)===o?await Pe(t,n,i):await lt(t,n,i)},He=async(t,n,i)=>{const o=await lt(t,n,i);return o===le?await He(t,n,i):o},ut=async(t,n)=>{const i=U.get(t),o=i?.settled===!0&&i.definition===n?await i.run:void 0;if(typeof o=="boolean")return o;U.delete(t),Ue+=1},Z=t=>{const n=l.tables[t];for(const i of n?.aggregateIndexes??[])U.delete(ue("aggregate",t,i.name));for(const i of n?.rankIndexes??[])U.delete(ue("rank",t,i.name))},ln=async(t,n)=>{const i=ce(t,n);return(await b(_,c,c.tableExists(i))).length>0},ft=async t=>{const{key:n}=c.companionTypes,i=D();await K(_,c,e`CREATE TABLE IF NOT EXISTS ${e.identifier(ve)} (${e.identifier("name")} ${e.raw(n)} PRIMARY KEY, ${e.identifier("token")} ${e.raw(n)} NOT NULL)`),await K(_,c,A({columns:["name","token"],conflictKey:"name",set:s=>({token:s("token")}),table:ve,values:[t,i]}));const o=e`${e.identifier("name")} = ${t} AND ${e.identifier("token")} = ${i}`;return{guardedDelete:()=>e`DELETE FROM ${e.identifier(t)} WHERE EXISTS (SELECT 1 FROM ${e.identifier(ve)} WHERE ${o})`,stillHeld:async()=>(await b(_,c,e`SELECT 1 FROM ${e.identifier(ve)} WHERE ${o}`)).length>0,guardedInsertRows:(s,d)=>$o(c,t,o,s,d)}},un=async(t,n,i)=>{const o=l.tables[t];if(!o||!await ln(t,n.name))return!1;const s=n.by??[],d=new Map;await xt(_,c,o,t,R=>{if(n.where&&!Qe(R,n.where))return;const m=te(s,R);Nt(d,m,n,R)});const u=ce(t,n.name);if(i())return le;const h=await ft(u);await K(_,c,h.guardedDelete());const{integer:y,key:p,real:E}=c.companionTypes,w=h.guardedInsertRows([{name:"__key__",type:p},{name:"__value__",type:E},{name:"__count__",type:y}],[...d].map(([R,m])=>[R,m.value,m.count]));return i()||await Ut(_,c,w),i()||!await h.stillHeld()?le:!0},Le=(t,n)=>He(ue("aggregate",t,n.name),We(n),i=>un(t,n,i)),fn=async(t,n,i,o,s)=>{const d=new Map;let u,h=!0;for(;h;){const y=u===void 0?o:[...o,e`${e.identifier("id")} > ${u}`],p=y.length>0?e` WHERE ${e.join(y,e` AND `)}`:e``,E=await b(s,c,e`SELECT ${e.identifier("id")}, ${H(i.field??"")} FROM ${e.identifier(n)}${p} ORDER BY ${e.identifier("id")} ASC LIMIT ${e.raw(String(Ze))}`);for(const w of kt(t,E))Nt(d,"",i,w);u=E.at(-1)?.id,h=E.length===Ze}return d.get("")?.value??null},wn=async(t,n,i,o)=>{const s=n.field??"",d=[],u=l.tables[t],h=(w,R)=>Ft(c,w,R,m=>u?de(u,w,m):Je(m));for(const w of n.by??[]){const R=h(w,i[w]??null);d.push(R===null?e`${H(w)} IS NULL`:e`${H(w)} = ${R}`)}for(const[w,R]of Object.entries(n.where??{})){const m=R!==null&&typeof R=="object"&&!Array.isArray(R)?R.eq:R,S=h(w,m),C=Fe(c,w);d.push(S===null?e`${C} IS NULL`:e`${C} = ${S}`)}const y=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``;if(u&&on(u.shape[s]))return fn(u,t,n,d,o);const p=Re(n.op),E=await b(o,c,e`SELECT ${e.raw(p)}(${H(s)}) AS ${e.identifier("value")} FROM ${e.identifier(t)}${y}`);return fe(E[0]?.value)},hn=(t,n)=>e`DELETE FROM ${e.identifier(t)} WHERE ${e.identifier("__key__")} = ${n} AND ${e.identifier("__count__")} <= 0`,$n=async(t,n,i,o,s)=>{const d=ce(t,n.name),{op:u}=n,h=n.field??"",y=i&&(!n.where||Qe(i,n.where))?i:void 0,p=o&&(!n.where||Qe(o,n.where))?o:void 0;if(!y&&!p)return[];if(u==="count"||u==="sum"||u==="avg"){const S=[],C=new Set,L=[];for(const[I,O]of[[y,-1],[p,1]]){if(!I)continue;const k=u==="count"?1:ze(I[h]);k!==void 0&&L.push({encoded:te(n.by??[],I),numeric:k,sign:O})}L.sort((I,O)=>I.encoded<O.encoded?-1:+(I.encoded>O.encoded));for(const{encoded:I,numeric:O,sign:k}of L)C.add(I),S.push(A({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(P,Q)=>({__count__:e`${Q("__count__")} + ${P("__count__")}`,__value__:u==="count"?e`${Q("__value__")} + ${P("__value__")}`:e`COALESCE(${Q("__value__")}, 0) + ${P("__value__")}`}),table:d,values:[I,k*O,k]}));for(const I of C)S.push(hn(d,I));return S}const E=[],w=[];let R,m;if(y){const S=te(n.by??[],y);R=S;const C=ze(y[h]),I=(await b(s,c,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(d)} WHERE ${e.identifier("__key__")} = ${S}`))[0],O=fe(I?.value),k=(I?.count??0)-1;if(k<=0)E.push(e`DELETE FROM ${e.identifier(d)} WHERE ${e.identifier("__key__")} = ${S}`);else if(I&&C!==void 0&&O!==null&&C===O){const P=await wn(t,n,y,s);E.push(e`UPDATE ${e.identifier(d)} SET ${e.identifier("__value__")} = ${P}, ${e.identifier("__count__")} = ${k} WHERE ${e.identifier("__key__")} = ${S}`)}else E.push(e`UPDATE ${e.identifier(d)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${S}`)}if(p){const S=te(n.by??[],p);m=S;const C=ze(p[h]);if(C===void 0)w.push(A({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(L,I)=>({__count__:e`${I("__count__")} + 1`}),table:d,values:[S,null,1]}));else{const L=u==="min"?"MIN":"MAX";w.push(A({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(I,O)=>({__count__:e`${O("__count__")} + 1`,__value__:e`${e.raw(L)}(COALESCE(${O("__value__")}, ${I("__value__")}), ${I("__value__")})`}),table:d,values:[S,C,1]}))}}return R!==void 0&&m!==void 0&&m<R?[...w,...E]:[...E,...w]},be=async t=>{const n=l.tables[t]?.aggregateIndexes;if(!(!n||n.length===0))for(const i of n)await Le(t,i)},_e=async(t,n,i,o)=>{const s=l.tables[t]?.aggregateIndexes,d=[];if(!s||s.length===0)return d;for(const u of s)await ut(ue("aggregate",t,u.name),We(u))&&d.push(...await $n(t,u,n,i,o));return d},_n=async(t,n)=>{const i=ye(t,n);return(await b(_,c,c.tableExists(i))).length>0},En=async(t,n,i)=>{const o=l.tables[t];if(!o||!await _n(t,n.name))return!1;const s=ye(t,n.name);if(i())return le;const d=await ft(s);await K(_,c,d.guardedDelete());const u=c.companionTypes.key,h=[{name:"__id__",type:u},{name:"__partition__",type:u},...n.sortBy.map((E,w)=>{const R=o.shape[E.field];return{name:ge(w),type:c.columnType(R?ct(R):void 0)}})];let y=[];const p=async()=>{const E=y;y=[],!(E.length===0||i())&&await Ut(_,c,d.guardedInsertRows(h,E))};return await xt(_,c,o,t,async E=>{if(n.where&&!Lt(E,n.where))return;const w=ke(n.partitionBy??[],E),R=n.sortBy.map(m=>Je(E[m.field]??null));y.push([E._id,w,...R]),y.length>=Ze&&await p()}),await p(),i()||!await d.stillHeld()?le:!0},Ke=(t,n)=>He(ue("rank",t,n.name),We(n),i=>En(t,n,i)),Me=async t=>{const n=l.tables[t]?.rankIndexes;if(!(!n||n.length===0))for(const i of n)await Ke(t,i)},re=async(t,n,i,o)=>{const s=l.tables[t],d=s?.rankIndexes,u=[];if(!d||d.length===0)return u;const h=s?.softDeleteMode?.field,y=h===void 0||o===void 0?void 0:o[h],p=y!=null;for(const E of d){if(i!==void 0&&o!==void 0&&Ui(E,i,o)||!await ut(ue("rank",t,E.name),We(E)))continue;const R=ye(t,E.name);if(i&&u.push(e`DELETE FROM ${e.identifier(R)} WHERE ${e.identifier("__id__")} = ${n}`),o&&!p){if(E.where&&!Lt(o,E.where))continue;const m=E.sortBy.map((I,O)=>ge(O)),S=we(["__id__","__partition__",...m]),C=ke(E.partitionBy??[],o),L=E.sortBy.map(I=>Je(o[I.field]??null));u.push(e`INSERT INTO ${e.identifier(R)} (${S}) VALUES (${Te([n,C,...L])})`)}}return u},pn=(t,n,i)=>{const o=et(n);if(o===void 0||!i.dispatched){Z(t);return}o.then(()=>{i.batched||Z(t)},()=>{Z(t)}).catch(()=>{})},se=async(t,n,i,o,s)=>{const d=l.tables[t],u=j||(d?.aggregateIndexes?.length??0)>0||(d?.rankIndexes?.length??0)>0,h=_.transaction===void 0||!u,y=async w=>{let R;try{R=await n(w)}catch(S){if(_.transaction===void 0&&S instanceof Oi){Z(t);const C=()=>{Z(t)};et(S)?.then(C,C).catch(()=>{})}throw S}if(!R)return!1;const m={batched:!1,dispatched:!1};try{h&&s.length>0&&await Bt(w,c,s);const S=h?await i(w):[...await i(w),...s];S.length>0&&(m.batched=w.batch!==void 0&&c.name==="sqlite",m.dispatched=!0,await Bt(w,c,S))}catch(S){throw _.transaction===void 0&&pn(t,S,m),h&&await Se(t,o,async()=>{throw await Promise.resolve(),S}),S}return!0};let p;const E=Ue;try{p=_.transaction!==void 0&&u?await _.transaction(y).catch(wo):await y(_),p&&Ue!==E&&_.transaction!==void 0&&u&&Z(t)}catch(w){const R=et(w);if(R!==void 0){const m=async()=>{await Ln({dialect:c,exec:_,schema:l},t,o)};R.then(m,m).catch(()=>{})}throw w}return p&&await Se(t,o,cn),p},Ee=An({dialect:c,exec:_,schema:l}),wt=new Set;for(const[t,n]of Object.entries(l.tables))for(const i of Object.values(n.triggerMap??{}))wt.add(`${t} ${i.timing} ${i.op}`);const Y=(t,n,i)=>wt.has(`${t} ${n} ${i}`);let ht;const X=async(t,n,i)=>{if(Ae+=1,Ae>Ht)throw Ae-=1,new ne(`trigger recursion exceeded ${String(Ht)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await ii({ctx:ht,event:i,op:n,schema:l,tableName:i.table,timing:t})}finally{Ae-=1}},yn=async(t,n,i=_)=>{try{await K(i,c,n)}catch(o){Yt(c,o,t)}},Ne=async(t,n)=>(await b(_,c,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} = ${n}`))[0],$t=async(t,n,i,o,s,d)=>{const u=e`${e.identifier(me)}`,h=e.join([v(e`${e.identifier("id")}`,o.id),v(u,o[me]??null),...s===void 0?[]:[e`(${s})`]],e` AND `),y=n==="UPDATE"?e`UPDATE ${e.identifier(t)} SET ${i}, ${u} = ${Dt.sql(u)} WHERE ${h}`:e`DELETE FROM ${e.identifier(t)} WHERE ${h}`;try{if(c.supportsReturning)return(await b(d,c,e`${y} RETURNING ${e.identifier("id")}`)).length>0;const p=await K(d,c,y);return(c.affectedRows?c.affectedRows(p??{rowsAffected:0}):0)>0}catch(p){return Yt(c,p,t)}},je=async(t,n,i,o,s)=>{if(o!==void 0&&!await $t(t,n,i,o,void 0,s))throw new ne(`optimistic concurrency conflict on "${t}" — the row changed during this mutation; refetch and retry`,"occ")},Ge=(t,n=t?._creationTime)=>({_creationTime:n,[me]:Dt.value(t?.[me])}),_t=async(t,n,i,o,s,d,u)=>{const h=z(n,s);if(!h||s===void 0)throw new g("INTERNAL",`document not found: ${i}`);const y=ri(n,o,h),p={...h,...si(y),_id:i};tt(n,y,p,ie);const E=Ye(n,p,{only:new Set(Object.keys(y)),previous:()=>h,tolerateStoredNull:!0});nt(c.name,Object.fromEntries(Object.keys(y).map(S=>[S,E[S]]))),ai(u,h,E),Y(t,"before","update")&&await X("before","update",{doc:{...E},id:i,op:"update",previous:h,table:t}),await be(t),await Me(t);const w=Object.keys(n.shape),R=e.join(w.map(S=>e`${e.identifier(S)} = ${de(n,S,E[S]??null)}`),e`, `);if(await se(t,async S=>await $t(t,"UPDATE",R,s,d,S),async S=>[...await _e(t,h,E,S),...await re(t,i,h,E)],i,he(t,i,"update",E)))return await Ee(t,i,{document:E,previous:h,written:Ge(s)}),Y(t,"after","update")&&await X("after","update",{doc:E,id:i,op:"update",previous:h,table:t}),E},Rn=(t,n,i,o)=>{const s=Object.keys(t.shape);return{columns:["id","_creationTime",...s],values:[n,i,...s.map(d=>de(t,d,o[d]??null))]}},mn=async(t,n,i,o)=>{const s=di(n,i.op,i.field,o.by,o.where);if(!s||!await Le(t,s.index))return;const u=ce(t,s.index.name),h=Object.keys(s.partial);if(h.length===(s.index.by??[]).length&&h.length>0){const p=te(s.index.by??[],s.partial),E=await b(_,c,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(u)} WHERE ${e.identifier("__key__")} = ${p}`);if(E.length===0)return[];const w=E[0];return[{key:{...s.partial},value:Xe(i.op,{count:w.count,value:fe(w.value)})}]}return h.length>0?void 0:(await b(_,c,e`SELECT ${e.identifier("__key__")} AS ${e.identifier("key")}, ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(u)}`)).map(p=>{const E=p;return{key:Ri(JSON.parse(E.key)),value:Xe(i.op,{count:E.count,value:fe(E.value)})}})},Et=t=>{const n=l.tables[t]?.shardMode?.kind;return n==="shardBy"||n==="root"},pt=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`)},Sn=(t,n)=>{if(n?.relationMask!==void 0&&n.with!==void 0&&Object.keys(n.with).length>0)throw new g("MASK_UNSUPPORTED",`masking cannot follow a nested \`with\` across the cross-shard relation hop to "${t}" — the nested rows are hydrated on the serving shard, where the mask policy does not exist. Read the nested relation at its own (masked) call site instead.`);const i={};if(n?.relationBaseWhere)for(const o of Object.keys(l.tables)){const s=n.relationBaseWhere(o);s!==void 0&&(i[o]=s)}return{orderBy:n?.orderBy,relationPolicies:i,where:x(n?.baseWhere,n?.where),with:n?.with}},Oe=(t,n)=>Et(t)?f?f(t,Sn(t,n)):pt(t):G.findMany(t,n),qe=(t,n,i)=>ci(t,{fetcher:Oe,maxRelationKeys:$,relationBaseWhere:i,schema:l,tableName:n}),gn=qi(async(t,n)=>{const i=await b(_,c,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} IN (${Te(n)})`),o=new Map;for(const s of i){const{id:d}=s;typeof d=="string"&&o.set(d,s)}return o}),yt=async(t,n,i)=>{const{fetchLimit:o,limit:s,orderKeys:d,predicate:u}=await li(n,i,{fetcher:Oe,maxRelationKeys:$,schema:l,tableName:t}),h=ee(u,T(n)),y=Bi(d,c);let p=e`SELECT * FROM ${e.identifier(t)}`;return h&&(p=e`${p} WHERE ${h}`),p=e`${p} ORDER BY ${y}`,o!==void 0&&(p=e`${p} LIMIT ${e.raw(String(o))}`),{limit:s,orderKeys:d,query:p}},Tn=Fn(l);let Rt;const mt=async()=>{const{primary:t}=r.exec;if(t!==void 0)return await F(),Rt??=Eo({...r,exec:t,provisionScope:oe}),Rt},G={relationWrites:Tn,async cdcChangedTables(t,n){if(j)try{return await F(),await so(_,t,c,{...n,now:N(),retained:J!==void 0})}catch{return}},async aggregate(t,n){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);if(await F(),Re(n.op),n.op==="count")return G.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 o=De(i.softDeleteMode,void 0),s=x(x(n.baseWhere,n.where),o),d=await qe(s,t,n.relationBaseWhere),u=d!==s;if(i.aggregateIndexes&&!n.baseWhere&&!u&&!o){const R=ni(i.aggregateIndexes,n.op,n.field,n.where);if(R&&await Le(t,R.index)){const S=te(R.index.by??[],R.key),C=ce(t,R.index.name),I=(await b(_,c,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(C)} WHERE ${e.identifier("__key__")} = ${S}`))[0];return Xe(n.op,I===void 0?void 0:{count:I.count,value:fe(I.value)})}}rt(i,n.field,`aggregate(${t}, { op: "${n.op}", field: "${n.field}" })`);const h=ee(d,T(i)),y=e.raw(Re(n.op)),p=e`SELECT ${y}(${H(n.field)}) AS ${e.identifier("value")} FROM ${e.identifier(t)}`,w=(await b(_,c,h?e`${p} WHERE ${h}`:p))[0]?.value;return w==null?null:Number(w)},async count(t,n){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await F();const o=ei(n);if(o.restrictsCounts)throw new vt(t);const s=De(i.softDeleteMode,void 0),d=x(x(o.baseWhere,o.where),s),u=await qe(d,t,o.relationBaseWhere),h=u!==d;if(i.aggregateIndexes&&!o.baseWhere&&!h&&!s){const w=ti(i.aggregateIndexes,o.where);if(w&&await Le(t,w.index)){const m=te(w.index.by??[],w.key),S=ce(t,w.index.name),C=await b(_,c,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")} FROM ${e.identifier(S)} WHERE ${e.identifier("__key__")} = ${m}`);return Number(C[0]?.value??0)}}const y=ee(u,T(i)),p=e`SELECT COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(t)}`,E=await b(_,c,y?e`${p} WHERE ${y}`:p);return Number(E[0]?.count??0)},async delete(t,n,i){const o=await $e(t);if(!o)return;const s=l.tables[o];if(!s)return;const d=await Ne(o,n);if(d===void 0)return;const u=z(s,d),h=i?.hard===!0,y=!h&&s.softDeleteMode?s.softDeleteMode.field:void 0;if(!(y&&(!u||u[y]!==null&&u[y]!==void 0))){if(Y(o,"before","delete")&&await X("before","delete",{id:n,op:"delete",previous:u??void 0,table:o}),i?.skipOnDelete!==!0&&await Zn({deletedId:n,deletedReference:p=>u?.[p],findHolders:async(p,E,w,R)=>{if(l.tables[p]?.shardMode?.kind==="shardBy")throw new g("INTERNAL",`cross-backend cascade from global '${o}' into shardBy '${p}' is not supported — would require Query Coordinator fan-out across shards`);return(await G.findMany(p,{...R,includeDeleted:h,where:{[E]:w}})).page},onCascade:(p,E)=>G.delete(p,E,i),onRestrict:p=>{throw new ne(p,"restrict")},onSetNull:(p,E,w)=>G.patch(p,E,{[w]:null}),schema:l,tableName:o}),await be(o),await Me(o),y&&u){const p={[y]:N()},E={...u,...p};tt(s,p,E,ie);const w=e.join(Object.keys(s.shape).map(R=>e`${e.identifier(R)} = ${de(s,R,E[R]??null)}`),e`, `);await se(o,async R=>(await je(o,"UPDATE",w,d,R),!0),async R=>[...await _e(o,u,E,R),...await re(o,n,u,void 0)],n,he(o,n,"update",E)),await Ee(o,n,{document:E,previous:u,written:Ge(d)}),Y(o,"after","delete")&&await X("after","delete",{id:n,op:"delete",previous:u,table:o});return}await se(o,async p=>(await je(o,"DELETE",void 0,d,p),!0),async p=>[...await _e(o,u??void 0,void 0,p),...await re(o,n,u??void 0,void 0)],n,he(o,n,"delete")),await Se(o,n,async()=>{await Ee(o,n,void 0),Y(o,"after","delete")&&await X("after","delete",{id:n,op:"delete",previous:u??void 0,table:o})})}},async findFirst(t,n={}){if(n.consistency==="primary"){const o=await mt();if(o!==void 0)return o.findFirst(t,n)}return(await G.findMany(t,{...n,limit:1})).page[0]??null},async findFirstOrThrow(t,n={}){const i=await G.findFirst(t,n);if(i===null)throw new Jn(`findFirstOrThrow: no "${t}" document matched`);return i},async findMany(t,n={}){if(n.consistency==="primary"){const R=await mt();if(R!==void 0)return R.findMany(t,n)}const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await F();const o=async(R,m,S,C)=>{if(Et(R))return a?ui(a,R,m,S,C):pt(R);const L=l.tables[R];if(!L)throw new g("INTERNAL",`unknown table: ${R}`);const I=De(L.softDeleteMode,void 0),O={[m]:{in:S}},k=x(x(O,C),I),P=await qe(k,R,void 0),Q=ee(P,T(L)),pe=H(m);let V=e`SELECT ${pe} AS __fk__, COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(R)}`;Q&&(V=e`${V} WHERE ${Q}`),V=e`${V} GROUP BY ${pe}`;const B=await b(_,c,V),ae=new Map;for(const St of B)ae.set(St.__fk__,Number(St.count??0));return ae},{limit:s,orderKeys:d,query:u}=await yt(t,i,n),h=await b(_,c,u),y=kt(i,h);if(s===void 0)return n.with&&await It({fetcher:Oe,groupedCounter:o,parents:y,...At(n),schema:l,tableName:t,with:n.with}),{continueCursor:null,isDone:!0,page:Ct(y,n.select,n.with)};const p=y.length>s,E=p?y.slice(0,s):y,w=E.at(-1);return n.with&&await It({fetcher:Oe,groupedCounter:o,parents:E,...At(n),schema:l,tableName:t,with:n.with}),{continueCursor:p&&w?zn(w,d):null,isDone:!p,page:Ct(E,n.select,n.with)}},async explain(t,n={}){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await F();const{query:o}=await yt(t,i,n),s=c.name==="sqlite"?"EXPLAIN QUERY PLAN":"EXPLAIN",d=await b(_,c,e`${e.raw(s)} ${o}`),{params:u,sql:h}=c.render(o);return{params:u,plan:d.map(y=>Wi(y)),sql:h}},async get(t,n){const i=Object.hasOwn(l.tables,t)?l.tables[t]:void 0;if(!i)throw new g("BAD_REQUEST",`ctx.db.get(table, id): "${t}" is not a table in this schema`);return i.shardMode!==void 0&&i.shardMode.kind!=="global"?null:(await F(),z(i,await gn.load(t,n)))},async groupBy(t,n){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await F();const o=n.agg??{op:"count"};if(Re(o.op),o.op!=="count"&&!o.field)throw new g("INTERNAL",`groupBy(${t}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);const s=De(i.softDeleteMode,void 0),d=x(x(n.baseWhere,n.where),s),u=await qe(d,t,n.relationBaseWhere),h=u!==d;if(i.aggregateIndexes&&!n.baseWhere&&!h&&!s){const m=await mn(t,i.aggregateIndexes,o,n);if(m!==void 0)return m}Vi(i,t,n.by,o);const y=ee(u,T(i)),p=n.by.map(m=>e`${H(m)} AS ${e.identifier(m)}`);if(o.op==="count")p.push(e`COUNT(*) AS ${e.identifier("value")}`);else{if(!o.field)throw new g("INTERNAL",`groupBy(${t}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);p.push(e`${e.raw(Re(o.op))}(${H(o.field)}) AS ${e.identifier("value")}`)}const E=e.join(n.by.map(m=>H(m)),e`, `);let w=e`SELECT ${e.join(p,e`, `)} FROM ${e.identifier(t)}`;y&&(w=e`${w} WHERE ${y}`),w=e`${w} GROUP BY ${E}`;const R=await b(_,c,w);return xi(i,n.by,R)},async insert(t,n,i){const o=l.tables[t];if(!o)throw new g("INTERNAL",`unknown table: ${t}`);await F();const s=Ye(o,Yn(o,n,ie),{supplied:n,trusted:i?.allowExplicitId===!0});nt(c.name,s);let d;i?.clientId!==void 0?(Xn(i.clientId),d=i.clientId):i?.allowExplicitId&&typeof s._id=="string"?(Qn(s._id),d=s._id):d=D();const u=i?.allowExplicitId&&typeof s._creationTime=="number"?s._creationTime:N(),h={...s,_creationTime:u,_id:d};Y(t,"before","insert")&&await X("before","insert",{doc:{...h},id:d,op:"insert",table:t}),await be(t),await Me(t);const{columns:y,values:p}=Rn(o,d,u,s);return await se(t,async E=>(await yn(t,e`INSERT INTO ${e.identifier(t)} (${we(y)}) VALUES (${Te(p)})`,E),!0),async E=>[...await _e(t,void 0,h,E),...await re(t,d,void 0,h)],d,he(t,d,"insert",h)),await Se(t,d,async()=>{await Ee(t,d,{document:h,written:{_creationTime:u,[me]:null}}),Y(t,"after","insert")&&await X("after","insert",{doc:h,id:d,op:"insert",table:t})}),d},normalizeId(t,n){return Vn(l,t,n)},async patch(t,n,i,o){Ve("patch",i);const s=await $e(t);if(!s)throw new g("INTERNAL",`document not found: ${n}`);const d=l.tables[s];if(!d)throw new g("INTERNAL",`document not found: ${n}`);const u=Gn(d,i)?it:1;for(let h=0;h<u;h+=1){const y=await Ne(s,n);if(await _t(s,d,n,i,y,void 0,o))return}throw new ne(`optimistic concurrency conflict on "${s}" — the row changed during this mutation; refetch and retry`,"occ")},async patchIf(t,n,i){Ve("patchIf",i.patch);const o=await $e(t),s=o===void 0?void 0:l.tables[o];if(o===void 0||!s)return{applied:!1,doc:null};const d=o,u=ee(i.where,T(s))??e`1 = 1`;for(let h=0;h<it;h+=1){const[y]=await b(_,c,e`SELECT *, CASE WHEN (${u}) THEN 1 ELSE 0 END AS ${e.identifier(Vt)} FROM ${e.identifier(d)} WHERE ${e.identifier("id")} = ${n}`);if(y===void 0)return{applied:!1,doc:null};const{[Vt]:p,...E}=y;if(Number(p)!==1)return{applied:!1,doc:z(s,E)??null};const w=await _t(d,s,n,i.patch,E,u,{verify:i.verify});if(w)return{applied:!0,doc:w}}throw new ne(`patchIf on "${d}" lost the row to concurrent writes ${String(it)} times in a row; retry the operation`,"occ")},async restore(t,n){const i=await $e(t),o=i===void 0?void 0:await Ne(i,n);if(!i||o===void 0)throw new g("INTERNAL",`document not found: ${n}`);const s=l.tables[i],d=s?.softDeleteMode?.field;if(!s||!d)throw new g("INTERNAL",`ctx.db.restore: table "${i}" is not a .softDelete() table`);const u=o[d]!==null&&o[d]!==void 0;if(await G.patch(t,n,{[d]:null}),u){const h=z(s,o);h!==null&&await se(i,async()=>await Promise.resolve(!0),async()=>await re(i,n,void 0,{...h,[d]:null}),n,[]).catch(y=>{throw _.transaction!==void 0&&Z(i),y})}},query(t){const n=l.tables[t];if(!n)throw new g("INTERNAL",`unknown table: ${t}`);const i="the legacy query()/withIndex() reader is not available on the D1 (global) backend; use findMany",o=[];let s=0,d;const u=c.name!=="mysql",h={...T(n),fieldRef:w=>e`m.${H(w)}`,rangeTypeGuard:()=>{throw new g("INTERNAL","a path range is never pushed into a search")}},y=w=>o.every(R=>R(w)),p=async(w,R)=>{await F();const m=2*On+w.filters.length,S=d===void 0?void 0:ee(d,h,void 0,m),C=S!==void 0&&c.name==="sqlite"&&c.render(S).params.length+m>Ei.boundParams,L=C?void 0:S,I=s>0||C,O=await qn(_,c,n,t,L===void 0?w:{...w,scope:L},kn(I?void 0:R));!I&&R===void 0&&Dn(O);const k=O.filter(P=>y(P));return R===void 0?k:k.slice(0,R)},E=w=>{const R={async*[Symbol.asyncIterator](){if(!w)throw new g("INTERNAL",i);yield*await p(w,void 0)},async collect(){if(!w)throw new g("INTERNAL",i);return p(w,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(m){o.push(m);const S=fi(m);return S!==void 0&&wi(S,n.shape,u)?d=x(d,S):s+=1,R},async first(){if(!w)throw new g("INTERNAL",i);return(await p(w,1))[0]??null},order(){return R},async paginate(m){if(!w)throw new g("INTERNAL",i);const S=Mn(m);return Nn(await p(w,Bn(S)),S)},async take(m){if(!w)throw new g("INTERNAL",i);return p(w,m)},async unique(){if(!w)throw new g("INTERNAL",i);const m=await p(w,2);if(m.length>1)throw new _i(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(){throw new g("INTERNAL",`geo indexes are not supported on \`.global()\` tables (table "${t}") — geospatial queries run only on sharded tables`)},withIndex(){throw new g("INTERNAL",i)},withSearchIndex(m,S){const C=(n.searchIndexes??[]).find(I=>I.name===m);if(!C)throw new g("INTERNAL",`unknown search index "${m}" on table "${t}"`);const L={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:m,query:""};if(S(bn(L,t,In(C.language))),!L.hasQuery)throw new g("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return E(L)}};return R};return E(void 0)},async rank(t,n,i){const o=l.tables[t];if(!o)throw new g("INTERNAL",`unknown table: ${t}`);const s=o.rankIndexes?.find(O=>O.name===n);if(!s)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(i.restrictsCounts)throw new vt(t);if(await F(),!await Ke(t,s))return null;const u=typeof i.row=="string"?i.row:i.row._id;if(!u)return null;const h=ye(t,s.name),y=s.sortBy.map((O,k)=>ge(k)),p=we(["__partition__",...y]),w=(await b(_,c,e`SELECT ${p} FROM ${e.identifier(h)} WHERE ${e.identifier("__id__")} = ${u}`))[0];if(!w)return null;const R=w.__partition__,m=x(i.baseWhere,i.where);gt(m,l,t,"rank");const S=Tt(s,m);if(S&&ke(s.partitionBy??[],S)!==R)return null;const C=Pi(c.name,s,y,w,u),L=await b(_,c,e`SELECT COUNT(*) AS c FROM ${e.identifier(h)} WHERE ${e.identifier("__partition__")} = ${R} AND (${C})`),I=await b(_,c,e`SELECT COUNT(*) AS c FROM ${e.identifier(h)} WHERE ${e.identifier("__partition__")} = ${R}`);return{position:Number(L[0]?.c??0)+1,total:Number(I[0]?.c??0)}},async rankPage(t,n,i={}){gt(x(i.baseWhere,i.where),l,t,"rankPage");const o=l.tables[t];if(!o)throw new g("INTERNAL",`unknown table: ${t}`);const s=o.rankIndexes?.find(B=>B.name===n);if(!s)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(await F(),!await Ke(t,s))return{continueCursor:null,isDone:!0,page:[]};const u=ye(t,s.name),h=s.sortBy.map((B,ae)=>ge(ae)),y=Math.max(1,Math.min(1e3,Math.floor(i.take??100))),p=x(i.baseWhere,i.where),E=Tt(s,p),w=Ki(s,h),R=e.join(w.flatMap(B=>tn(c,{direction:B.direction,field:B.column,nullable:B.nullable})),e`, `),m=[];typeof i.partitionKey=="string"?m.push(e`${e.identifier("__partition__")} = ${i.partitionKey}`):E&&m.push(e`${e.identifier("__partition__")} = ${ke(s.partitionBy??[],E)}`);const S=jn(i);if(S!==void 0){const B=Hi(c.name,w,S);B!==void 0&&m.push(B)}const C=we([Ie,"__partition__",...h]);let L=e`SELECT ${C} FROM ${e.identifier(u)}`;m.length>0&&(L=e`${L} WHERE ${e.join(m,e` AND `)}`),L=e`${L} ORDER BY ${R} LIMIT ${e.raw(String(y+1))}`;const I=await b(_,c,L),O=I.length>y,k=O?I.slice(0,y):I,P=k.map(B=>B[Ie]),Q=await ji(_,c,o,t,P);let pe=null;const V=k.at(-1);if(O&&V!==void 0){const B=[V.__partition__,...h.map(ae=>V[ae]),V[Ie]];pe=Gi(B)}return{continueCursor:pe,isDone:!O,page:Q}},async replace(t,n,i,o){Ve("replace",i);const s=await $e(t);if(!s)throw new g("INTERNAL",`document not found: ${n}`);const d=l.tables[s];if(!d)throw new g("INTERNAL",`document not found: ${n}`);const u=await Ne(s,n);if(u===void 0)throw new g("INTERNAL",`document not found: ${n}`);const y=Kn(l,s,"update")||(d.aggregateIndexes??[]).length>0||(d.rankIndexes??[]).length>0?z(d,u)??void 0:void 0,p=o?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,E=typeof u._creationTime=="number"?u._creationTime:void 0,w=p??E??N(),R={...i,_creationTime:w,_id:n};tt(d,i,R,ie);const m=Ye(d,R,{previous:()=>y??z(d,u)??void 0,supplied:i,trusted:o?.allowExplicitId===!0});nt(c.name,m),Y(s,"before","update")&&await X("before","update",{doc:{...m},id:n,op:"update",previous:y,table:s}),await be(s),await Me(s);const S=Object.keys(d.shape),C=e.join([e`${e.identifier("_creationTime")} = ${w}`,...S.map(L=>e`${e.identifier(L)} = ${de(d,L,m[L]??null)}`)],e`, `);await se(s,async L=>(await je(s,"UPDATE",C,u,L),!0),async L=>[...await _e(s,y,m,L),...await re(s,n,y,m)],n,he(s,n,"update",m)),await Se(s,n,async()=>{await Ee(s,n,{document:m,previous:y,written:Ge(u,w)}),Y(s,"after","update")&&await X("after","update",{doc:m,id:n,op:"update",previous:y,table:s})})}};return ht={db:G,scheduler:dn},G};export{Eo as createSqlCtxDb,Oo as decodeGlobalRow,so as readSqlCdcChangedTables,bo as readSqlCdcChanges,sn as readSqlCdcFloor,zi as runSqlCdcMigration,Zi as sweepSqlCdcRetention};
@@ -1 +0,0 @@
1
- import{LunoraError as p}from"@lunora/errors";import{q as U,c as qt,m as Ft,r as C,a as Ut,l as q,w as F,b as kt}from"./ctx-db-search-state-BBPiVWjf.mjs";import{ftsUnmappedPage as bt,groupUnmappedRows as Ht,ftsWriteDocument as mt,ftsPurgeDocument as ht,ftsCompanionDdl as Pt,unionAll as Bt,ftsRowidMapName as Wt}from"@lunora/shard-engine";import{sql as r}from"drizzle-orm";import{abandonedWork as jt}from"./DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import{O as xt,q as h,n as Kt,h as X,a as N,i as L,e as J,f as v,c as y,k as pt,j as ot,l as Gt,r as Yt,x as Qt}from"./sql-exec-enIOMsv0.mjs";const Vt=n=>{const t=atob(n),e=Uint8Array.from(t,i=>i.codePointAt(0)??0);return new TextDecoder().decode(e)},Xt=()=>new p("BAD_REQUEST","invalid cursor"),st=16,at=8,T=1024,k=(n,t)=>t.query(n),Jt=(n,t)=>{if(!t)return{exact:!0,lower:n,upper:n};const e=[...n].at(-1)??"",i=(e.codePointAt(0)??0)+1;if(i>=55296&&i<=57343||i>1114111)return{exact:!0,lower:n,upper:n};const o=n.slice(0,n.length-e.length);return{exact:!1,lower:n,upper:o+String.fromCodePoint(i)}},Dn=(n,t,e)=>{const i={eq:(o,s)=>{if(!n.definition.filterFields?.includes(o))throw new p("INTERNAL",`field "${o}" is not a filter field of search index "${n.indexName}" on table "${t}"`);if(n.filters.length>=at)throw new p("BAD_REQUEST",`search index "${n.indexName}" on table "${t}": at most ${String(at)} .eq() filters are supported per search query`);return n.filters.push({field:o,value:s}),i},search:(o,s)=>{const a=n;if(o!==a.definition.field)throw new p("INTERNAL",`search index "${a.indexName}" on table "${t}" indexes "${a.definition.field}", not "${o}"`);const f=k(s,e).length;if(f>st)throw new p("BAD_REQUEST",`search index "${a.indexName}" on table "${t}": at most ${String(st)} search terms are supported (got ${String(f)})`);return a.field=o,a.query=s,a.hasQuery=!0,i}};return i},qn=n=>{if(n.length>T)throw new p("BAD_REQUEST",`more than ${String(T)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Fn=n=>Math.min(n.offset+n.numItems+1,T),zt=n=>btoa(`search:${String(n)}`),Zt=n=>{let t;try{t=Vt(n)}catch{return}if(!t.startsWith("search:"))return;const e=Number(t.slice(7));return Number.isInteger(e)&&e>=0?e:void 0},Un=n=>{if(typeof n.endCursor=="string")throw new p("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new p("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const t=Math.max(0,Math.floor(n.numItems)),e=n.cursor?Zt(n.cursor):0;if(e===void 0)throw Xt();if(e+t>=T)throw new p("BAD_REQUEST",`search pagination reaches the ${String(T)}-document limit (offset ${String(e)} + ${String(t)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,T-e-1))} or fewer, or narrow the query or the filters instead`);return{numItems:t,offset:e}},kn=(n,t)=>{const e=t.offset+t.numItems,i=t.numItems>0&&n.length>e;return{continueCursor:i?zt(e):null,isDone:!i,page:n.slice(t.offset,e)}},bn=n=>{if(n===void 0)return T+1;if(!Number.isFinite(n))return T;const t=Math.max(0,Math.floor(n));if(t>T)throw new p("BAD_REQUEST",`search returns at most ${String(T)} documents (asked for ${String(t)}) — narrow the query or paginate instead`);return t},tn=(n,t)=>{if(!t.includes("."))return n[t];let e=n;for(const i of t.split(".")){if(e===null||typeof e!="object"||Array.isArray(e))return;e=e[i]}return e},b=(n,t)=>`${n}__fts_${t}`,l="__id__",g="__token__",O="__n__",nn=1e3,en=(n,t)=>t.document(n),G=(n,t)=>tn(n,t),rn=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",on=(n,t,e)=>n!==void 0&&t!==void 0&&G(n,e.field)===G(t,e.field),gt=(n,t)=>en(rn(G(n,t.field)),U(t.language)).slice(0,nn),z=(n,t)=>gt(n,t).join(" "),yt=(n,t)=>{const e=new Map;for(const i of gt(n,t))e.set(i,(e.get(i)??0)+1);return e},Tt=[xt,"_creationTime"],ft=50,d=(n,t)=>r`${r.identifier(n)}.${r.identifier(t)}`,M=(n,t,e)=>r`DELETE FROM ${r.identifier(n)} WHERE ${d(n,l)} = ${t}${e===void 0?r``:r` AND ${e}`}`,Rt=(n,{row:t,table:e})=>{const i=Tt.map(o=>r` AND ${Kt(n.name,d(e,o),t[o]??null)}`);return r`SELECT 1 FROM ${r.identifier(e)} WHERE ${d(e,"id")} = ${t.id}${r.join(i)}${n.name==="postgres"?r` FOR SHARE`:r``}`},D=(n,t)=>r`EXISTS (${Rt(n,t)})`,H=(n,t)=>r`NOT EXISTS (SELECT 1 FROM ${r.identifier(n)} WHERE ${d(n,"id")} = ${t})`,_t=(n,t,e,i)=>i===void 0?H(t,e):D(n,{row:i,table:t}),P=async(n,t,e,i)=>{const o=new Map;for(let s=0;s<i.length;s+=ft){const a=i.slice(s,s+ft),f=await h(n,t,r`SELECT * FROM ${r.identifier(e)} WHERE ${d(e,"id")} IN (${r.join(a.map(c=>r`${c}`),r`, `)})`);for(const c of f)o.set(String(c.id),c)}return o},Y=(n,t,e)=>n.name==="mysql"?r`${r.identifier(t)}(${r.raw(String(e))})`:n.textPatternOperatorClass===void 0?r`${r.identifier(t)}`:r`${r.identifier(t)} ${r.raw(n.textPatternOperatorClass)}`,Z=512,tt=(n,t)=>({columns:r`${Y(n,g,256)}, ${Y(n,l,Z)}`,concurrently:!0,name:`${t}__unique`,table:t,unique:!0}),x=n=>r`${n} COLLATE utf8mb4_0900_bin`,K=(n,t)=>{const e=JSON.stringify(t.map(([i,o])=>({o,t:i})));switch(n.name){case"mysql":return r`JSON_TABLE(${e}, '$[*]' COLUMNS (${r.identifier("t")} VARCHAR(256) PATH '$.t', ${r.identifier("o")} INT PATH '$.o')) AS ${r.identifier("j")}`;case"postgres":return r`json_to_recordset(${e}::text::json) AS ${r.identifier("j")}(${r.identifier("t")} text, ${r.identifier("o")} integer)`;default:return r`(SELECT json_extract(${d("e","value")}, '$.t') AS ${r.identifier("t")}, json_extract(${d("e","value")}, '$.o') AS ${r.identifier("o")} FROM json_each(${e}) AS ${r.identifier("e")}) AS ${r.identifier("j")}`}},At=(n,t,e,i,o)=>{const s=r.join([g,l,O].map(f=>r.identifier(f)),r`, `),a=f=>r`INSERT INTO ${r.identifier(t)} (${s}) SELECT ${d("j","t")}, ${e}, ${d("j","o")} FROM ${K(n,i)} WHERE ${f}`;switch(n.name){case"mysql":{const f=D(n,o),c=d(t,g),w=r.identifier("held");return[r`${a(r`${f} AND NOT EXISTS (SELECT 1 FROM ${r.identifier(t)} AS ${w} WHERE ${d("held",l)} = ${e} AND ${d("held",g)} = ${x(d("j","t"))})`)} ON DUPLICATE KEY UPDATE ${d(t,O)} = ${d(t,O)}`,r`UPDATE ${r.identifier(t)} JOIN ${K(n,i)} ON ${c} = ${x(d("j","t"))} SET ${d(t,O)} = ${d("j","o")} WHERE ${d(t,l)} = ${e} AND ${f}`,r`DELETE FROM ${r.identifier(t)} WHERE ${d(t,l)} = ${e} AND ${f} AND ${c} NOT IN (SELECT ${x(d("j","t"))} FROM ${K(n,i)})`]}case"postgres":{const f=r.identifier("__source__"),c=r.identifier("__purged__"),w=r`EXISTS (SELECT 1 FROM ${f})`;return[r`WITH ${f} AS (${Rt(n,o)}), ${c} AS (${M(t,e,w)} RETURNING 1) ${a(r`${w} AND (SELECT COUNT(*) FROM ${c}) >= 0`)} ON CONFLICT DO NOTHING`]}default:{const f=D(n,o);return[M(t,e,f),r`${a(f)} ON CONFLICT DO NOTHING`]}}},Ot={uniqueKeyMissing:!1,unmappedSkipped:0},ct=new Set,ut=(n,t)=>{ct.has(n)||(ct.add(n),console.warn(`[@lunora/sql-store] ${t}`))},dt=100,$t=3,Q=async(n,t,e,i=0)=>{const{companion:o,definition:s,index:a,tableName:f}=e,c={done:!0,last:i,left:0};if((await h(n,t,t.tableExists(f))).length===0)return c;const u=await h(n,t,bt(o,dt,i));if(u.length===0)return c;const S=Math.max(...u.map(A=>Number(A.rowid))),E=Ht(u),m=await P(n,t,f,[...E.keys()]),$=[];for(const[A,et]of E){const j=m.get(A),rt=j===void 0?void 0:X(s,j),it=_t(t,f,A,j);$.push(...rt?mt(o,A,z(rt,a),{guard:it,unmappedRowids:et}):ht(o,A,{guard:it,unmappedRowids:et}))}await N(n,t,$);const _=await h(n,t,r`SELECT COUNT(*) AS ${r.identifier("n")} FROM ${r.identifier(o)} WHERE ${d(o,"rowid")} > ${Math.max(0,i)} AND ${d(o,"rowid")} <= ${S}`);return{done:u.length<dt,last:S,left:Number(_[0]?.n??0)}},sn=async(n,t,e)=>{let i=0,o=0;for(;;){let s=await Q(n,t,e,i);for(let a=1;s.left>0&&a<$t;a+=1)s=await Q(n,t,e,i);if(s.left>0&&(o+=s.left,console.warn(`[@lunora/sql-store] search migration of "${e.companion}": ${String(s.left)} row(s) lost every one of ${String($t)} attempts to a concurrent write and were left for a later pass.`)),s.done)return o;i=s.last}},an=async(n,t,e,i)=>i==="step"?(await Q(n,t,e),Ot):{uniqueKeyMissing:!1,unmappedSkipped:await sn(n,t,e)},V=n=>`${n}__btree`,fn=async(n,t,e)=>{const i=tt(t,e),o=await L(n,t,e,i.name);if(o!=="valid"){if(o==="absent"&&(await h(n,t,r`SELECT 1 AS ${r.identifier("present")} FROM ${r.identifier(e)} LIMIT 1`)).length===0)try{await J(n,t,{...i,concurrently:!1}),await v(n,t,e,V(e));return}catch(a){if(await L(n,t,e,i.name).catch(()=>{})==="valid")return;ut(`${e}:empty`,`search companion "${e}": adding its unique key failed (${String(a)}); run backfillSqlSearchIndexes.`);return}ut(`${e}:missing`,`search companion "${e}" has no usable unique key, so two backfills racing over one row can index it twice. Run backfillSqlSearchIndexes, which adds it.`)}},cn=async(n,t,e)=>{const i=d(e,l),o=d(e,g);return(await h(n,t,r`SELECT ${i} AS ${r.identifier("id")}, ${o} AS ${r.identifier("token")}, COUNT(*) AS ${r.identifier("n")} FROM ${r.identifier(e)} GROUP BY ${i}, ${o} HAVING COUNT(*) > 1`)).map(a=>({count:Number(a.n),id:String(a.id),token:String(a.token)}))},un=(n,t,{count:e,id:i,token:o})=>{const s=r`${d(t,l)} = ${i} AND ${d(t,g)} = ${o}`;switch(n.name){case"mysql":return r`DELETE FROM ${r.identifier(t)} WHERE ${s} LIMIT ${r.raw(String(e-1))}`;case"postgres":return r`DELETE FROM ${r.identifier(t)} WHERE ctid = ANY (ARRAY(SELECT ctid FROM ${r.identifier(t)} WHERE ${s} OFFSET 1))`;default:return r`DELETE FROM ${r.identifier(t)} WHERE rowid IN (SELECT rowid FROM ${r.identifier(t)} WHERE ${s} LIMIT -1 OFFSET 1)`}},dn=async(n,t,e,i)=>{const{companion:o,definition:s,index:a,tableName:f}=e;for(const u of i)await y(n,t,un(t,o,u));const c=[...new Set(i.map(u=>u.id))],w=await P(n,t,f,c);for(const u of c){const S=w.get(u),E=S===void 0?void 0:X(s,S);if(S!==void 0&&E){const m=[...yt(E,a)];await N(n,t,At(t,o,u,m,{row:S,table:f}));continue}await y(n,t,M(o,u,_t(t,f,u,S)))}},$n=async(n,t,e)=>t.name!=="mysql"?"":(await h(n,t,r`SELECT COLUMN_NAME AS ${r.identifier("name")}, COLLATION_NAME AS ${r.identifier("collation")} FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ${e} AND COLUMN_NAME IN (${g}, ${l})`)).filter(o=>!String(o.collation).endsWith("_bin")).map(o=>` Its ${String(o.name)} column uses ${String(o.collation)}, which treats values differing only in case or accents as one; convert it with ALTER TABLE \`${e}\` MODIFY \`${String(o.name)}\` VARCHAR(768) COLLATE utf8mb4_0900_bin NOT NULL.`).join(""),wn=async(n,t,e)=>{if(t.name!=="mysql")return 0;const i=d(e,l),o=await h(n,t,r`SELECT COUNT(*) AS ${r.identifier("n")} FROM (SELECT 1 AS ${r.identifier("x")} FROM ${r.identifier(e)} GROUP BY LEFT(${i}, ${r.raw(String(Z))}), ${d(e,g)} HAVING COUNT(DISTINCT ${i}) > 1) AS ${r.identifier("shared")}`);return Number(o[0]?.n??0)},Sn=async(n,t,e)=>{const i=tt(t,e),o=await L(n,t,e,i.name);if(o==="valid")return"valid";o==="invalid"&&await v(n,t,e,i.name);try{return await J(n,t,i),"built"}catch(s){const a=await L(n,t,e,i.name);if(a==="valid")return"valid";if(a==="invalid"&&await v(n,t,e,i.name),!t.isUniqueViolation(s))throw s;return"refused"}},wt=3,ln=async(n,t,e)=>{const{companion:i}=e,o=await $n(n,t,i);let s="";o!==""&&console.warn(`[@lunora/sql-store] search companion "${i}" folds case and accents in its unique key.${o}`);for(let a=0;a<wt;a+=1){const f=await Sn(n,t,i);if(f==="valid")return await v(n,t,i,V(i)),!0;if(f==="refused"){const c=await cn(n,t,i);if(c.length>0)await dn(n,t,e,c);else{const w=await wn(n,t,i);s=w>0?` ${String(w)} token(s) are held by document ids that agree on their first ${String(Z)} characters, which the key cannot tell apart; shorten those ids.`:o}}}return await L(n,t,i,tt(t,i).name)==="valid"?(await v(n,t,i,V(i)),!0):(console.warn(`[@lunora/sql-store] search companion "${i}" still has no unique key after ${String(wt)} attempts: writes keep working, but two backfills racing over one row can index it twice.${s}`),!1)},En=async(n,t,e,i)=>i==="step"?Ot:{uniqueKeyMissing:!await ln(n,t,e),unmappedSkipped:0},mn=(n,t)=>t?r`${r.identifier(g)} LIKE ${`${n}%`}`:r`${r.identifier(g)} = ${n}`,Nt=(n,t)=>{const e=t.filters.map(i=>r`m.${ot(i.field)} = ${Gt(i.value)}`);return n.softDeleteMode&&e.push(r`m.${ot(n.softDeleteMode.field)} IS NULL`),t.scope!==void 0&&e.push(r`(${t.scope})`),e},It=async(n,t,e,i,o,s,a)=>{const f=Nt(e,o);let c=r`SELECT m.* FROM (${a}) s JOIN ${r.identifier(i)} m ON m.${r.identifier("id")} = s.${r.identifier(l)}`;return f.length>0&&(c=r`${c} WHERE ${r.join(f,r` AND `)}`),c=r`${c} ORDER BY s.${r.identifier("__score__")} DESC, m.${r.identifier("_creationTime")} DESC, m.${r.identifier("id")} ASC LIMIT ${r.raw(String(s))}`,pt(e,await h(n,t,c))},hn=async(n,t,e,i,o,s)=>{const a=k(o.query,U(o.definition.language));if(a.length===0)return[];const f=b(i,o.indexName),c=a.length-1,w=a.map(($,_)=>mn($,_===c)),u=r.join(w,r` OR `),S=w.map($=>r`SUM(CASE WHEN ${$} THEN ${r.identifier(O)} ELSE 0 END)`),E=r.join(S.map($=>r`${$} > 0`),r` AND `),m=r`SELECT ${r.identifier(l)}, ${r.join(S,r` + `)} AS ${r.identifier("__score__")} FROM ${r.identifier(f)} WHERE ${u} GROUP BY ${r.identifier(l)} HAVING ${E}`;return It(n,t,e,i,o,s,m)},pn=async(n,t,e,i,o,s)=>{const a=k(o.query,U(o.definition.language));if(a.length===0)return[];const f=b(i,o.indexName),c=`${f}__vocab`,w=a.length-1,u=a.map((m,$)=>{const _=Jt(m,$===w),A=_.exact?r`${r.identifier("term")} = ${_.lower}`:r`${r.identifier("term")} >= ${_.lower} AND ${r.identifier("term")} < ${_.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String($))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(c)} WHERE ${A} GROUP BY ${r.identifier("doc")}`}),S=a.map((m,$)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String($))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),E=r`SELECT f.${r.identifier(l)} AS ${r.identifier(l)}, ${r.join(S,r` + `)} AS ${r.identifier("__score__")} FROM (${Bt(u)}) u JOIN ${r.identifier(f)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(l)} HAVING ${r.join(S.map(m=>r`${m} > 0`),r` AND `)}`;return It(n,t,e,i,o,s,E)},gn=async(n,t,e,i,o,s)=>{const a=t.nativeTextSearch,f=k(o.query,U(o.definition.language));if(!a||f.length===0)return[];const c=b(i,o.indexName),w=[a.matches(c,f),...Nt(e,o)],u=r`SELECT m.* FROM ${r.identifier(c)} JOIN ${r.identifier(i)} m ON m.${r.identifier("id")} = ${r.identifier(c)}.${r.identifier(l)} WHERE ${r.join(w,r` AND `)} ORDER BY ${a.rank(c,f)} DESC, m.${r.identifier("_creationTime")} DESC, m.${r.identifier("id")} ASC LIMIT ${r.raw(String(s))}`;return pt(e,await h(n,t,u))},yn={ensureCompanion:async(n,t,e)=>{const{integer:i,key:o}=t.companionTypes;await y(n,t,r`CREATE TABLE IF NOT EXISTS ${r.identifier(e)} (${r.identifier(g)} ${r.raw(o)} NOT NULL, ${r.identifier(l)} ${r.raw(o)} NOT NULL, ${r.identifier(O)} ${r.raw(i)} NOT NULL)`),await J(n,t,{columns:Y(t,l,191),name:`${e}__by_id`,table:e,unique:!1}),await fn(n,t,e)},indexDocument:async(n,t,e,i,o,s)=>{const a=[...yt(i,o)];await N(n,t,At(t,e,String(s.row.id),a,s))},migrate:En,name:"inverted",purgeDocument:async(n,t,e,i,o)=>{await y(n,t,M(e,i,H(o,i)))},runSearch:hn},Tn={ensureCompanion:async(n,t,e)=>{await N(n,t,Pt(e))},indexDocument:async(n,t,e,i,o,s)=>{await N(n,t,mt(e,String(s.row.id),z(i,o),{guard:D(t,s)}))},migrate:an,name:"fts5",purgeDocument:async(n,t,e,i,o)=>{await N(n,t,ht(e,i,{guard:H(o,i)}))},runSearch:pn},Rn={ensureCompanion:async(n,t,e)=>{const i=t.nativeTextSearch;if(i){await y(n,t,i.createCompanion(e,t.companionTypes.key));for(const o of i.createIndexes(e))await y(n,t,o)}},indexDocument:async(n,t,e,i,o,s)=>{const a=t.nativeTextSearch;a&&await y(n,t,a.indexDocument(e,String(s.row.id),z(i,o),D(t,s)))},name:"native",purgeDocument:async(n,t,e,i,o)=>{await y(n,t,M(e,i,H(o,i)))},runSearch:gn},I=(n,t)=>n.strategy==="native"&&t.nativeTextSearch!==void 0?Rn:t.supportsFts5?Tn:yn,B=(n,t)=>`${qt(n)}/${I(n,t).name}`,nt=function*(n){for(const[t,e]of Object.entries(n.tables)){const i=e.searchIndexes;if(!(e.shardMode!==void 0&&e.shardMode.kind!=="global"||!i))for(const o of i)yield[t,e,o]}},R=(n,t)=>b(n,t.name),_n=async(n,t,e,i)=>{const o=R(e,i);return q(await C(n,t,o),B(i,t)).finished?!0:kt(n,t,o)},Hn=async(n,t,e,i,o,s)=>{if(!await _n(n,t,i,o.definition))throw new p("SEARCH_INDEX_BUILDING",`search index "${o.indexName}" on table "${i}" is still backfilling and currently covers only part of the table — retry once it finishes${t.searchBackfillHint===void 0?"":`, or complete it now: ${t.searchBackfillHint}`}`);return I(o.definition,t).runSearch(n,t,e,i,o,s)},St=n=>n.slice(n.lastIndexOf("/")+1),lt=200,Et=5,An=async(n,t,e,i)=>{const o=[...i.keys()],s=await h(n,t,r`SELECT * FROM ${r.identifier(e)} WHERE ${r.identifier("id")} >= ${o[0]} AND ${r.identifier("id")} <= ${o.at(-1)} ORDER BY ${r.identifier("id")} ASC`),a=new Map;for(const f of s){const c=f.id,w=i.get(c)?.row;w&&Tt.some(u=>String(w[u])!==String(f[u]))&&a.set(c,{row:f})}return a},W=async(n,t,e,i,o,s,a)=>{const f=I(s,t);let c=a;for(let w=0;c.size>0&&w<Et;w+=1){for(const{document:u,row:S}of c.values()){const E=u??X(e,S);E&&await f.indexDocument(n,t,o,E,s,{row:S,table:i})}c=await An(n,t,i,c)}c.size>0&&console.warn(`[@lunora/sql-store] search index "${o}": ${String(c.size)} row(s) were rewritten on every one of ${String(Et)} re-check rounds and were left to their writers — each stays stale only if none of those writes changed its indexed text.`)},Ct=async(n,t,e,i,o)=>{const s=R(i,o),a=B(o,t);let f=await C(n,t,s),c=q(f,a);if(c.finished)return!0;if(c.wipe){await F(n,t,s,void 0,!1,a,{cursor:f.cursor,done:f.done,profile:f.profile});const $=await C(n,t,s);if($.cursor!==f.cursor||$.done!==f.done||$.profile!==f.profile){if(f=$,c=q(f,a),c.wipe)return!1;if(c.finished)return!0}else f={cursor:void 0,done:!1,profile:a},c=q(f,a)}if((await h(n,t,t.tableExists(i))).length===0)return await F(n,t,s,void 0,!0,a),!0;const u=await Yt(n,t,i,c.cursor,lt),S=u.findLast($=>typeof $.id=="string")?.id,E=new Map;for(const $ of u)typeof $.id=="string"&&E.set($.id,{row:$});await W(n,t,e,i,s,o,E);const m=u.length<lt;return await F(n,t,s,S??c.cursor,m,a,{cursor:c.cursor,done:!1,profile:f.profile}),m},Lt=async(n,t,e)=>{await Ft(n,e);for(const[i,,o]of nt(t)){const s=R(i,o),a=B(o,e),f=await C(n,e,s);f.profile!==void 0&&St(f.profile)!==St(a)&&(await y(n,e,r`DROP TABLE IF EXISTS ${r.identifier(s)}`),await y(n,e,r`DROP TABLE IF EXISTS ${r.identifier(Wt(s))}`),await Ut(n,e,s)),await I(o,e).ensureCompanion(n,e,s)}},On=async(n,t,e,i,o)=>{const s=R(i,o);if((await C(n,t,s)).profile!==void 0)return;let f=0;(await h(n,t,t.tableExists(i))).length>0&&await Qt(n,t,e,i,()=>{f+=1},{limit:1}),await F(n,t,s,void 0,f===0,B(o,t))},vt=async(n,t,e,i,o,s)=>await I(o,t).migrate?.(n,t,{companion:R(i,o),definition:e,index:o,tableName:i},s)??{uniqueKeyMissing:!1,unmappedSkipped:0},Pn=async(n,t,e)=>{await Lt(n,t,e);for(const[i,o,s]of nt(t)){if(await vt(n,e,o,i,s,"step"),s.staged){await On(n,e,o,i,s);continue}await Ct(n,e,o,i,s)}},Bn=async(n,t,e)=>{const i={uniqueKeyMissing:[],unmappedSkipped:0};await Lt(n,t,e);for(const[o,s,a]of nt(t)){const f=await vt(n,e,s,o,a,"drain");i.unmappedSkipped+=f.unmappedSkipped,f.uniqueKeyMissing&&i.uniqueKeyMissing.push(R(o,a));let c=!1;for(;!c;)c=await Ct(n,e,s,o,a)}return i},Mt=async(n,t,e,i,o,s,a)=>{await I(s,t).purgeDocument(n,t,o,a,e);const c=(await P(n,t,e,[a])).get(a);c!==void 0&&await W(n,t,i,e,o,s,new Map([[a,{row:c}]]))},Dt=async(n,t,e,i,o,s,a)=>{const c=(await P(n,t,e,[a])).get(a);await(c===void 0?Mt(n,t,e,i,o,s,a):W(n,t,i,e,o,s,new Map([[a,{row:c}]])))},Wn=async(n,t,e)=>{const i=n.schema.tables[t];for(const o of i?.searchIndexes??[])await Dt(n.exec,n.dialect,t,i,R(t,o),o,e)},jn=n=>{const{dialect:t,exec:e,schema:i}=n;return async(o,s,a)=>{const f=i.tables[o],c=f?.searchIndexes;if(!(!f||!c||c.length===0))for(const[w,u]of c.entries()){const S=R(o,u);try{if(on(a?.previous,a?.document,u))continue;if(a){await W(e,t,f,o,S,u,new Map([[s,{document:a.document,row:{...a.written,id:s}}]]));continue}await Mt(e,t,o,f,S,u,s)}catch(E){const m=async()=>{for(const $ of c.slice(w))await Dt(e,t,o,f,R(o,$),$,s)};throw jt(E)?.then(m,m).catch(()=>{}),E}}}};export{Dn as A,Un as C,kn as R,bn as T,Wn as a,Bn as b,jn as c,Hn as d,Fn as e,Pn as r,st as u,qn as x};
@@ -1 +0,0 @@
1
- import{LunoraError as O}from"@lunora/errors";import{aggregateTableName as V,rankTableName as Q,sortColumnName as N,bigintSqlKey as z}from"@lunora/shard-engine";import{sql as t}from"drizzle-orm";import{b as Z,e as g,B as b,r as J,i as nn,U as en,c as tn}from"./value-codec-CbyTgWR3.mjs";import{O as S,t as on,c as d,q as $,M as q,e as y,j as m,z as rn,s as sn,y as an}from"./sql-exec-enIOMsv0.mjs";const ln=new Set(["any","null"]),k=(e,n)=>{const i=n.kindOf(e);return i!==void 0&&ln.has(i)||n.nullableOf(e)?!0:i==="union"&&(n.membersOf(e)??[]).some(o=>k(o,n))},R=e=>{const n=e._meta?.inner;return e.kind==="optional"&&n?R(n):e},I=e=>k(e,{kindOf:Z,membersOf:n=>R(n)._meta?.members,nullableOf:n=>R(n)._meta?.column?.notNull===!1}),x=(e,n,i=!1)=>n.columnType(g(e),{unique:i||e._meta?.column?.unique===!0}),M=e=>{const n=new Set;for(const i of e.indexes)i.unique===!0&&i.fields.length===1&&n.add(i.fields[0]);return n},un=(e,n,i)=>{if(i.indexKeyPrefix!==void 0)for(const o of n.indexes){if(o.unique!==!0||o.fields.length<=1)continue;const r=o.fields.filter(s=>{const a=n.shape[s];return a!==void 0&&i.indexKeyPrefix?.(g(a))!==void 0});if(r.length>0)throw new Error(`${e}.${o.name}: a composite unique index cannot cover ${r.join(", ")} in full on this engine (its key limit forces a prefix, which would constrain the prefix rather than the value). Split it into single-column unique indexes, or store those fields as a bounded type.`)}},cn=e=>e._meta?.column?.notNull===!0&&e.kind!=="optional"&&!I(e),fn=(e,n,i)=>{const o=[],r=M(n);for(const[u,c]of Object.entries(n.shape)){if(!c._meta?.column)continue;const f=cn(c)?" NOT NULL":"";o.push(t`${t.identifier(u)} ${t.raw(`${x(c,i,r.has(u))}${f}`)}`)}const s=[...i.frameworkColumns().map(u=>t`${t.identifier(u.name)} ${t.raw(u.type)}`),t`${t.identifier(S)} ${t.raw(i.companionTypes.integer)}`],a=s.length+o.length,l=i.maxTableColumns;if(l!==void 0&&a>l){const u=a-1===l,c="Move one or more fields into a single object field, or split the table — either way the existing rows need a data migration (`defineMigration` + `lunora migrate up`); there is no in-place path.";throw new O("VALIDATION_ERROR",`@lunora/sql-store: global table "${e}" needs ${String(a)} columns, over this engine's ${String(l)}-column limit. ${u?`One of them is "${S}", the row version every guarded write reads, which caps declared fields at ${String(l-s.length)}. A table provisioned at ${String(l)} columns before that column existed cannot be widened to hold it. `:""}${c}`)}return t.join([...s,...o],t`, `)},B=e=>{if(e.indexKeyPrefix?.("string")===void 0)return t`${m("_creationTime")}, ${m("id")}`},D=new Set,F=async(e,n,i,o)=>{const r=t.join(i.refs.map(a=>t`${a} IS NOT NULL`),t` AND `);if((await $(e,n,t`SELECT ${i.columns} FROM ${t.identifier(i.table)} WHERE ${r} GROUP BY ${i.columns} HAVING COUNT(*) > 1 LIMIT 1`)).length>0){const a=`unique index "${i.name}" on "${i.table}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first.`;throw D.has(a)||(D.add(a),console.error(`[@lunora/sql-store] ${a}`)),new O("UNIQUE_INDEX_DUPLICATES",a)}},dn=async(e,n,i)=>{if(!i.unique){await y(e,n,i);return}try{await y(e,n,i)}catch(o){throw n.isUniqueViolation(o)&&await F(e,n,i,"cannot be created"),o}},P=e=>{const n=e.indexOf("(");return n===-1?void 0:e.slice(n,e.lastIndexOf(")")+1)},mn=(e,n)=>{const i=n.unique?t`UNIQUE `:t``;return P(e.render(t`CREATE ${i}INDEX ${t.identifier(n.name)} ON ${t.identifier(n.table)} (${n.columns})`).sql)},$n=(e,n,i)=>{const o=mn(e,i);return o!==void 0&&o!==P(n)},j=async(e,n,i)=>{if(n.name!=="sqlite")return;const r=(await $(e,n,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${i.name} COLLATE NOCASE AND tbl_name = ${i.table} COLLATE NOCASE`))[0]?.sql;typeof r=="string"&&$n(n,r,i)&&(i.unique&&await F(e,n,i,"cannot be re-created with its new column list; the previous index is left in place"),await d(e,n,t`DROP INDEX IF EXISTS ${t.identifier(i.name)}`))},En=(e,n,i)=>{un(e,n,i);const o=M(n),r=l=>{const u=m(l),c=n.shape[l],f=c&&i.indexKeyPrefix&&c._meta?.column?.unique!==!0&&!o.has(l)?i.indexKeyPrefix(g(c)):void 0;return f===void 0?u:t`${u}(${t.raw(String(f))})`},s=B(i),a=[];for(const l of n.indexes){const u=l.fields.map(E=>r(E)),c=t.join(u,t`, `),f=l.unique??!1;a.push({columns:f||s===void 0?c:t`${c}, ${s}`,kind:"declared",name:`${e}_${l.name}`,refs:u,table:e,unique:f})}s!==void 0&&a.push({columns:s,kind:"default-order",name:`${e}__by_creation`,refs:[],table:e,unique:!1});for(const[l,u]of on(n)){if(!u.unique)continue;const c=r(l);a.push({columns:c,kind:"unique-column",name:`${e}_unique_${l}`,refs:[c],table:e,unique:!0})}return a},gn=/^\s*create\s+unique\s/iu,p="__lunora_framework_indexes",wn=()=>t`CREATE TABLE IF NOT EXISTS ${t.identifier(p)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`,K=(e,n)=>t`INSERT OR IGNORE INTO ${t.identifier(p)} (name, table_name) VALUES (${e}, ${n})`,h=e=>e.replaceAll(/[A-Z]/gu,n=>n.toLowerCase()),hn=async(e,n,i)=>{if(n.name!=="sqlite"||(await $(e,n,t`SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ${p} COLLATE NOCASE`)).length>0)return;await d(e,n,wn());const r=B(n),s=r===void 0?void 0:`, ${n.render(r).sql})`;for(const a of i){const l=`${h(a)}_`,u=await $(e,n,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`);for(const c of u){const f=String(c.name),E=String(c.sql);h(f).startsWith(l)&&h(f)!==h(`${a}__by_creation`)&&(gn.test(E)||s!==void 0&&E.trimEnd().endsWith(s))&&await d(e,n,K(f,a))}}},pn=(e,n,i)=>{if(e.name!=="sqlite")return[];const o=new Set(n.map(r=>h(r.name)));return i.filter(r=>!o.has(h(r)))},_n=async(e,n,i,o)=>{if(o.name!=="sqlite")return;const r=await $(e,o,t`SELECT "l"."name" FROM ${t.identifier(p)} AS "l" WHERE "l"."table_name" = ${n} COLLATE NOCASE`);for(const s of pn(o,i,r.map(a=>String(a.name))))await d(e,o,t`DROP INDEX IF EXISTS ${t.identifier(s)}`),await d(e,o,t`DELETE FROM ${t.identifier(p)} WHERE ${t.identifier(p)}."name" = ${s}`)},Tn=async(e,n,i,o)=>{const r=En(n,i,o);for(const s of r){if(s.kind==="default-order"){await y(e,o,s);continue}s.kind==="declared"&&await j(e,o,s),await dn(e,o,s),o.name==="sqlite"&&await d(e,o,K(s.name,s.table))}await _n(e,n,r,o)},C="__lunora_migration_state",yn=async(e,n)=>{await d(e,n,t`CREATE TABLE IF NOT EXISTS ${t.identifier(C)} (${t.identifier("name")} ${t.raw(n.companionTypes.key)} PRIMARY KEY)`)},Ln=async(e,n,i)=>(await $(e,n,t`SELECT ${t.identifier("name")} FROM ${t.identifier(C)} WHERE ${t.identifier("name")} = ${i}`)).length>0,An=async(e,n,i,o,r,s)=>{r>0&&s!==void 0&&console.warn(`[@lunora/sql-store] storage migration "${i}" on "${o}": ${String(r)} row(s) ${s} and were left as stored — range filters and ORDER BY over them stay wrong until they are corrected by hand.`);try{await d(e,n,t`INSERT INTO ${t.identifier(C)} (${t.identifier("name")}) VALUES (${i})`)}catch(a){if(!n.isUniqueViolation(a))throw a}},Sn=100,Rn=(e,n)=>{const i=[],o=[];for(const r of n.fields){const s=e[r],a=n.convert(s);a!==void 0&&(i.push(t`${m(r)} = ${a}`),o.push(t`${m(r)} = ${s}`))}return{assignments:i,guards:o}},On=e=>t.join(e.fields.map(n=>e.probe(n)),t` OR `),G=async(e,n,i,o)=>{if(o.fields.length===0||(await yn(e,i),await Ln(e,i,o.marker)))return;const r=On(o),s=t.join([m("id"),...o.fields.map(u=>m(u))],t`, `);let a="",l=0;for(;;){const u=await $(e,i,t`SELECT ${s} FROM ${t.identifier(n)} WHERE (${r}) AND ${m("id")} > ${a} ORDER BY ${m("id")} LIMIT ${t.raw(String(Sn))}`);if(u.length===0){await An(e,i,o.marker,n,l,o.describeUnconvertible);return}const c=[];for(const E of u){const{id:w}=E,{assignments:_,guards:T}=typeof w=="string"?Rn(E,o):{assignments:[],guards:[]};if(_.length===0){l+=1;continue}c.push(t`UPDATE ${t.identifier(n)} SET ${t.join(_,t`, `)} WHERE ${m("id")} = ${w} AND ${t.join(T,t` AND `)}`)}await an(e,i,c);const f=u.at(-1)?.id;if(typeof f!="string")return;a=f}},U=e=>`'${e}%'`,Nn=e=>Object.entries(e.shape).filter(([,n])=>n._meta?.column!==void 0&&g(n)==="bigint").map(([n])=>n),In=e=>Object.entries(e.shape).filter(([,n])=>n._meta?.column!==void 0&&nn(g(n))).map(([n])=>n),H=(e,n)=>({convert:i=>{if(!(typeof i!="string"||i.length===b))try{return z(BigInt(i))}catch{return}},describeUnconvertible:"hold a value the order-preserving key cannot represent (non-numeric text, or a magnitude past 39 digits)",fields:Nn(n),marker:`bigint-key:${e}`,probe:i=>t`(${m(i)} IS NOT NULL AND LENGTH(${m(i)}) <> ${b})`}),Cn=async(e,n,i,o)=>G(e,n,o,H(n,i)),W=(e,n)=>({convert:J,fields:In(n),marker:`untyped-number-key:${e}`,probe:i=>t`(${m(i)} LIKE ${t.raw(U(en))} AND ${m(i)} NOT LIKE ${t.raw(U(tn))})`}),bn=async(e,n,i,o)=>G(e,n,o,W(n,i)),v=new Set,L=(e,n)=>{v.has(e)||(v.add(e),console.warn(`[@lunora/sql-store] ${n}`))},qn=e=>{const n=e._meta?.column;return n?.defaultFn?n.defaultFn():n&&"defaultValue"in n?n.defaultValue:void 0},Dn=(e,n,i)=>i._meta?.column?.unique===!0||e.indexes.some(o=>o.unique===!0&&o.fields.includes(n)),Un=async(e,n,i,o,r,s)=>{if(s.kind==="optional"||I(s))return;const a=Dn(i,r,s),l=a?void 0:qn(s),u=`UPDATE "${n}" SET "${r}" = … WHERE "${r}" IS NULL`;if(l===void 0){const c=a?"is unique, so one default cannot be written to every row":"has no default";L(`backfill:${n}.${r}`,`"${n}.${r}" was added as a required field that ${c}, so rows written before it read NULL. Backfill it with a migration (${u}).`);return}try{await d(e,o,t`UPDATE ${t.identifier(n)} SET ${t.identifier(r)} = ${sn(i,r,l)} WHERE ${t.identifier(r)} IS NULL`)}catch(c){L(`backfill:${n}.${r}`,`could not backfill "${n}.${r}" from its default (${c instanceof Error?c.message:String(c)}); rows written before it read NULL. Run ${u}.`)}},vn=(e,n)=>[[S,n.companionTypes.integer],...Object.entries(e.shape).filter(([,i])=>i._meta?.column!==void 0).map(([i,o])=>[i,x(o,n),o])],kn=async(e,n,i,o)=>{const r=vn(i,o),s="t",a=async l=>{try{return await $(e,o,t`SELECT ${t.join(l.map(u=>rn(s,u)),t`, `)} FROM ${t.identifier(n)} AS ${t.identifier(s)} LIMIT 0`),!0}catch{return!1}};if(!await a(r.map(([l])=>l)))for(const[l,u,c]of r)await a([l])||(await d(e,o,t`ALTER TABLE ${t.identifier(n)} ADD COLUMN ${t.identifier(l)} ${t.raw(u)}`),c!==void 0&&await Un(e,n,i,o,l,c))},xn=(e,n,i)=>{const o=typeof i.charset=="string"?` CHARACTER SET ${i.charset} COLLATE ${String(i.collation)}`:"";return`ALTER TABLE \`${e}\` MODIFY COLUMN \`${n}\` ${String(i.type)}${o} NULL`},Mn=async(e,n,i,o)=>{if(o.name==="sqlite")return;const r=Object.keys(i.shape).filter(s=>{const a=i.shape[s];return a._meta?.column?.notNull===!0&&a.kind!=="optional"&&I(a)});if(r.length!==0)try{const s=o.name==="postgres"?t`column_name AS ${t.identifier("name")}`:t`column_name AS ${t.identifier("name")}, column_type AS ${t.identifier("type")}, character_set_name AS ${t.identifier("charset")}, collation_name AS ${t.identifier("collation")}`,a=o.name==="postgres"?t`table_schema = ANY (current_schemas(false))`:t`table_schema = DATABASE()`,l=await $(e,o,t`SELECT ${s} FROM information_schema.columns WHERE ${a} AND table_name = ${n} AND is_nullable = 'NO' AND column_name IN (${t.join(r.map(u=>t`${u}`),t`, `)})`);for(const u of l){const c=String(u.name);if(o.name==="postgres"){await d(e,o,t`ALTER TABLE ${t.identifier(n)} ALTER COLUMN ${t.identifier(c)} DROP NOT NULL`);continue}L(`${n}.${c}`,`"${n}"."${c}" accepts null in the schema but its column is NOT NULL, so writing null there fails. Relaxing it on MySQL can rebuild the table, so it is not done at startup; run this once, in a maintenance window: ${xn(n,c,u)};`)}}catch(s){L(`${n}:relax-failed`,`could not relax NOT NULL on the null-accepting columns of "${n}" (${r.join(", ")}): ${s instanceof Error?s.message:String(s)}. Writing null to them fails until the constraint is dropped by hand.`)}},Bn=async(e,n,i,o)=>{const r=fn(n,i,o);await d(e,o,t`CREATE TABLE IF NOT EXISTS ${t.identifier(n)} (${r})`),await kn(e,n,i,o),await Mn(e,n,i,o),await Tn(e,n,i,o),await Cn(e,n,i,o),await bn(e,n,i,o)},Qn=(e,n)=>[H(e,n),W(e,n)].filter(i=>i.fields.length>0),zn=async(e,n,i,o)=>{let r=!1;for(const[s,a]of Object.entries(n.tables))a.shardMode?.kind!=="global"||o!==void 0&&!o.has(s)||(r||(r=!0,await hn(e,i,Object.entries(n.tables).filter(([,l])=>l.shardMode?.kind==="global").map(([l])=>l))),await Bn(e,s,a,i))},X=e=>e.shardMode===void 0||e.shardMode.kind==="global",Zn=async(e,n,i)=>{const{integer:o,key:r,real:s}=i.companionTypes;for(const[a,l]of Object.entries(n.tables)){const u=l.aggregateIndexes;if(!(!u||u.length===0||!X(l)))for(const c of u){const f=V(a,c.name);await d(e,i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(f)} (${t.identifier("__key__")} ${t.raw(r)} PRIMARY KEY, ${t.identifier("__value__")} ${t.raw(s)}, ${t.identifier("__count__")} ${t.raw(o)} NOT NULL DEFAULT 0)`),i.name==="sqlite"&&((await $(e,i,t`PRAGMA table_info(${t.identifier(f)})`)).some(w=>w.name==="__count__")||await d(e,i,t`ALTER TABLE ${t.identifier(f)} ADD COLUMN ${t.identifier("__count__")} ${t.raw(o)} NOT NULL DEFAULT 0`))}}},A=(e,n,i,o)=>{const r=e.name==="mysql"&&o?t`${t.identifier(n)}(191)`:t`${t.identifier(n)}`;return t`${r} ${t.raw(i)}`},Fn=(e,n,i)=>{const o=[A(e,"__partition__","ASC",!0)];for(const[r,s]of n.sortBy.entries()){const a=i.shape[s.field],l=a!==void 0&&e.indexKeyPrefix?.(g(a))!==void 0;o.push(A(e,N(r),s.direction==="desc"?"DESC":"ASC",l))}return o.push(A(e,"__id__","ASC",!0)),o},Pn=(e,n,i)=>n.sortBy.map((o,r)=>{const s=i.shape[o.field],a=e.columnType(s?g(s):void 0);return t`${t.identifier(N(r))} ${t.raw(a)}`}),jn=/__sort_k\d+__/gu,Kn=async(e,n,i,o)=>{if(n.name!=="sqlite")return;const s=(await $(e,n,t`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ${i} COLLATE NOCASE`))[0]?.sql;if(typeof s!="string")return;const a=s.match(jn)??[];(a.length!==o.length||a.some((l,u)=>l!==o[u]))&&await d(e,n,t`DROP TABLE ${t.identifier(i)}`)},Jn=async(e,n,i)=>{const{key:o}=i.companionTypes;for(const[r,s]of Object.entries(n.tables)){const a=s.rankIndexes;if(!(!a||a.length===0||!X(s)))for(const l of a){const u=q-4;if(l.sortBy.length>u)throw new O("BAD_REQUEST",`rank index "${l.name}" on ${r} has ${String(l.sortBy.length)} sort keys; at most ${String(u)} fit the ${String(q)} parameters one statement binds`);const c=Q(r,l.name),f=Pn(i,l,s);await Kn(e,i,c,l.sortBy.map((Gn,Y)=>N(Y)));const E=f.length>0?t`, ${t.join(f,t`, `)}`:t``;await d(e,i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(c)} (${t.identifier("__id__")} ${t.raw(o)} PRIMARY KEY, ${t.identifier("__partition__")} ${t.raw(o)} NOT NULL${E})`);const w=Fn(i,l,s),_=`${r}__rank_${l.name}__btree`,T={columns:t.join(w,t`, `),name:_,refs:[],table:c,unique:!1};await j(e,i,T),await y(e,i,T)}}};export{p as INDEX_LEDGER_TABLE,C as MIGRATION_STATE_TABLE,mn as declaredIndexColumnList,h as foldIdentifier,fn as globalTableColumnsDdl,En as globalTableIndexSpecs,P as indexColumnList,wn as indexLedgerDdl,$n as indexShapeChanged,Qn as legacyRewrites,On as legacyRowPredicate,Bn as provisionGlobalTable,zn as provisionGlobalTablesSequentially,K as recordIndexStatement,Zn as runSqlAggregateMigrations,Jn as runSqlRankMigrations,pn as undeclaredFrameworkIndexes,vn as wantedGlobalColumns};
@@ -1 +0,0 @@
1
- import{sql as a}from"drizzle-orm";import{provisionGlobalTablesSequentially as m,foldIdentifier as c,globalTableColumnsDdl as A,globalTableIndexSpecs as L,legacyRewrites as O,indexLedgerDdl as R,wantedGlobalColumns as k,undeclaredFrameworkIndexes as y,indexShapeChanged as $,INDEX_LEDGER_TABLE as T,MIGRATION_STATE_TABLE as E,recordIndexStatement as M,legacyRowPredicate as C}from"./runSqlAggregateMigrations-D5_8KDaC.mjs";import{a as q,q as g}from"./sql-exec-enIOMsv0.mjs";const v=50,h=new Map([["'","'"],["[","]"],["`","`"],['"','"']]),N=/^[\w$]+/u,b=(e,s)=>{const n=h.get(e[s]);let t=s+1;for(;t<e.length;)if(e[t]!==n)t+=1;else if(n!=="]"&&e[t+1]===n)t+=2;else return t+1;return t},_=e=>{const s=e.trim(),n=h.get(s[0]??"");if(n===void 0)return N.exec(s)?.[0];const t=b(s,0),r=s.slice(1,s[t-1]===n?t-1:t);return n==="]"?r:r.replaceAll(`${n}${n}`,n)},B=e=>{const s=new Set,n=i=>{const d=_(i);d!==void 0&&s.add(d)};let t=0,r=0,o=0;for(;o<e.length;){const i=e[o];if(h.has(i)){o=b(e,o);continue}if(i==="(")t+=1,r=t===1?o+1:r;else if(i===")"){if(t-=1,t===0)return n(e.slice(r,o)),s}else i===","&&t===1&&(n(e.slice(r,o)),r=o+1);o+=1}return s},F=async(e,s,n)=>{const t=new Set,r=new Map,o=n.has(c(T)),i=[];if(n.has(c(E))&&i.push(a`SELECT 'marker' AS kind, name, NULL AS owner FROM ${a.identifier(E)}`),o&&i.push(a`SELECT 'index' AS kind, "l"."name" AS name, "l"."table_name" AS owner FROM ${a.identifier(T)} AS "l"`),i.length===0)return{hasLedger:o,markers:t,owned:r};for(const d of await g(e,s,a.join(i,a` UNION ALL `)))if(d.kind==="marker")t.add(String(d.name));else{const f=c(String(d.owner));r.set(f,[...r.get(f)??[],String(d.name)])}return{hasLedger:o,markers:t,owned:r}},D=async(e,s)=>{try{const n=await g(e,s,a`SELECT type, name, tbl_name, sql FROM sqlite_master WHERE type IN ('table', 'index')`),t=new Set,r=new Map,o=new Map;for(const l of n){const u=String(l.name);if(u.startsWith("sqlite_"))continue;const S=typeof l.sql=="string"?l.sql:void 0;l.type==="table"?(t.add(c(u)),r.set(c(u),new Set([...S===void 0?[]:B(S)].map(I=>c(I))))):o.set(c(u),S)}const{hasLedger:i,markers:d,owned:f}=await F(e,s,t);return{columns:r,hasLedger:i,indexes:o,markers:d,owned:f,tables:t}}catch{return}},w=e=>e.kind==="default-order"?[]:[M(e.name,e.table)],p=e=>{const s=e.unique?a`UNIQUE `:a``;return a`CREATE ${s}INDEX IF NOT EXISTS ${a.identifier(e.name)} ON ${a.identifier(e.table)} (${e.columns})`},x=(e,s,n)=>n.length===0?[]:[a`CREATE TABLE IF NOT EXISTS ${a.identifier(E)} (${a.identifier("name")} ${a.raw(e.companionTypes.key)} PRIMARY KEY)`,...n.map(t=>a`INSERT OR IGNORE INTO ${a.identifier(E)} (${a.identifier("name")}) SELECT ${t.marker} WHERE NOT EXISTS (SELECT 1 FROM ${a.identifier(s)} WHERE ${C(t)})`)],G=(e,s,n,t)=>{const r=A(e,s,n),o=L(e,s,n),i=O(e,s);if(!t.tables.has(c(e)))return[...t.hasLedger?[]:[R()],a`CREATE TABLE IF NOT EXISTS ${a.identifier(e)} (${r})`,...o.flatMap(l=>[p(l),...w(l)]),...x(n,e,i)];const d=t.columns.get(c(e))??new Set;if(k(s,n).some(([l])=>!d.has(c(l)))||i.some(l=>!t.markers.has(l.marker))||y(n,o,t.owned.get(c(e))??[]).length>0)return;const f=[];for(const l of o){if(!t.indexes.has(c(l.name))){f.push(p(l),...w(l));continue}const u=t.indexes.get(c(l.name));if(l.kind==="declared"&&typeof u=="string"&&$(n,u,l))return}return f},X=e=>{const s=[];let n=[],t=0;for(const r of e)n.length>0&&t+r.statements.length>v&&(s.push(n),n=[],t=0),n.push(r),t+=r.statements.length;return n.length>0&&s.push(n),s},U=(e,s)=>!s.hasLedger&&Object.entries(e.tables).some(([n,t])=>t.shardMode?.kind==="global"&&s.tables.has(c(n))),Q=async(e,s,n)=>{if(!e.batch||n.name!=="sqlite"){await m(e,s,n);return}const t=await D(e,n);if(t===void 0){await m(e,s,n);return}if(U(s,t)){await m(e,s,n);return}const r=[],o=new Set;for(const[i,d]of Object.entries(s.tables)){if(d.shardMode?.kind!=="global")continue;const f=G(i,d,n,t);f===void 0?o.add(i):f.length>0&&r.push({statements:f,table:i})}for(const i of X(r))try{await q(e,n,i.flatMap(d=>d.statements))}catch{for(const d of i)o.add(d.table)}await m(e,s,n,o)};export{B as columnNamesOfCreateTable,Q as runSqlGlobalTableMigrations};