@lunora/sql-store 1.0.0-alpha.226 → 1.0.0-alpha.227
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +8 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{createSqlCtxDb-BViKQ0rC.mjs → createSqlCtxDb-nFFLsLPe.mjs} +2 -2
- package/dist/packem_shared/exportSqlGlobalRows-CdZOH72U.mjs +1 -0
- package/package.json +2 -2
- package/dist/packem_shared/exportSqlGlobalRows-ENXsoTkI.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -44,6 +44,12 @@ interface ExportRow {
|
|
|
44
44
|
* in tests), which keeps the positional fallback.
|
|
45
45
|
*/
|
|
46
46
|
line?: number;
|
|
47
|
+
/**
|
|
48
|
+
* Import only: `"delete"` removes the stored row whose `_id` the doc carries
|
|
49
|
+
* instead of writing the doc — how a replace-mode restore prunes the rows its
|
|
50
|
+
* source no longer has.
|
|
51
|
+
*/
|
|
52
|
+
op?: "delete";
|
|
47
53
|
table: string;
|
|
48
54
|
}
|
|
49
55
|
interface ImportError {
|
|
@@ -55,6 +61,8 @@ interface ImportError {
|
|
|
55
61
|
interface ImportResult {
|
|
56
62
|
/** Skipped rows whose `_id` already exists (the default `onConflict: "skip"`). */
|
|
57
63
|
conflicts: number;
|
|
64
|
+
/** Stored rows removed by `op: "delete"` rows. A delete whose `_id` is already gone removes nothing and is not counted. */
|
|
65
|
+
deleted: number;
|
|
58
66
|
errors: ImportError[];
|
|
59
67
|
inserted: Record<string, number>;
|
|
60
68
|
/** Existing rows overwritten under `onConflict: "replace"`. */
|
package/dist/index.d.ts
CHANGED
|
@@ -44,6 +44,12 @@ interface ExportRow {
|
|
|
44
44
|
* in tests), which keeps the positional fallback.
|
|
45
45
|
*/
|
|
46
46
|
line?: number;
|
|
47
|
+
/**
|
|
48
|
+
* Import only: `"delete"` removes the stored row whose `_id` the doc carries
|
|
49
|
+
* instead of writing the doc — how a replace-mode restore prunes the rows its
|
|
50
|
+
* source no longer has.
|
|
51
|
+
*/
|
|
52
|
+
op?: "delete";
|
|
47
53
|
table: string;
|
|
48
54
|
}
|
|
49
55
|
interface ImportError {
|
|
@@ -55,6 +61,8 @@ interface ImportError {
|
|
|
55
61
|
interface ImportResult {
|
|
56
62
|
/** Skipped rows whose `_id` already exists (the default `onConflict: "skip"`). */
|
|
57
63
|
conflicts: number;
|
|
64
|
+
/** Stored rows removed by `op: "delete"` rows. A delete whose `_id` is already gone removes nothing and is not counted. */
|
|
65
|
+
deleted: number;
|
|
58
66
|
errors: ImportError[];
|
|
59
67
|
inserted: Record<string, number>;
|
|
60
68
|
/** Existing rows overwritten under `onConflict: "replace"`. */
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportSqlGlobalRows as r,importSqlGlobalRows as a,selectGlobalTables as l}from"./packem_shared/exportSqlGlobalRows-
|
|
1
|
+
import{exportSqlGlobalRows as r,importSqlGlobalRows as a,selectGlobalTables as l}from"./packem_shared/exportSqlGlobalRows-CdZOH72U.mjs";import{createSqlCtxDb as s,readSqlCdcChangedTables as S,readSqlCdcChanges as i,readSqlCdcFloor as n,runSqlCdcMigration as d,sweepSqlCdcRetention as q}from"./packem_shared/createSqlCtxDb-nFFLsLPe.mjs";import{runSqlGlobalTableMigrations as b}from"./packem_shared/runSqlGlobalTableMigrations-C4_8w8pO.mjs";import{runSqlAggregateMigrations as f,runSqlRankMigrations as g}from"./packem_shared/runSqlAggregateMigrations-CvZiVJ9S.mjs";import{b as x,r as T}from"./packem_shared/ctx-db-search-DH6CwEsG.mjs";import{S as u,m as E}from"./packem_shared/ctx-db-search-state-BFQG9D20.mjs";import{facetSqlGlobalColumn as M,listSqlGlobalTables as R,readSqlGlobalTablePage as h}from"./packem_shared/facetSqlGlobalColumn-CAQNCBVu.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-C52YW-Do.mjs";import{d as L}from"./packem_shared/sql-exec-ChIYvWnI.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,7 +1,7 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{m as mn,q as gn}from"./ctx-db-search-state-BFQG9D20.mjs";import{c as Tn,r as vn,a as In,A as An,C as Cn,R as Ln,u as bn,d as Mn,T as Nn,x as On,e as qn}from"./ctx-db-search-DH6CwEsG.mjs";import{throwingScheduler as kn,describeRelationWrites as Dn,CDC_LOG_TABLE as W,cdcForkedError as Bn,cursorBelowRetainedFloor as Wn,cdcTrimmedError as Fn,serverInList as Un,assertNoExplicitUndefined as Ve,hasTrigger as xn,runRowValidators as Ye,assertFlatPredicate as St,mergeWhere as U,rankTableName as ye,sortColumnName as
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{m as mn,q as gn}from"./ctx-db-search-state-BFQG9D20.mjs";import{c as Tn,r as vn,a as In,A as An,C as Cn,R as Ln,u as bn,d as Mn,T as Nn,x as On,e as qn}from"./ctx-db-search-DH6CwEsG.mjs";import{throwingScheduler as kn,describeRelationWrites as Dn,CDC_LOG_TABLE as W,cdcForkedError as Bn,cursorBelowRetainedFloor as Wn,cdcTrimmedError as Fn,serverInList as Un,assertNoExplicitUndefined as Ve,hasTrigger as xn,runRowValidators as Ye,assertFlatPredicate as St,mergeWhere as U,rankTableName as ye,sortColumnName as ge,resolveRankPartition as mt,encodePartitionKey as ke,resolveRankSeekTuple as Pn,RANK_TIEBREAK as Ie,CountRlsUnsupportedError as gt,compileWhereSql as ee,ConflictError as ne,patchDependsOnRow as Hn,normalizeIdStructurally as Kn,applyInsertDefaults as jn,assertValidClientId as Gn,assertStorableRowId as Vn,aggregateSqlFunction as Re,softDeleteScope as De,resolveWith as Tt,relationHooks as vt,applySelect as It,encodeCursor as Yn,NotFoundError as Xn,applyOnDelete as Qn,normalizeCountArgument as zn,selectIndexForCount as Jn,encodeAggregateKey as te,aggregateTableName as ae,selectIndexForAggregate as Zn,readAggregateValue as Xe,runTriggers as ei,matchesRankStaticWhere as At,nullsOrderSuffix as Ct,nullsFirstOf as Lt,rankPivotConditionSql as Yt,CURSOR_PREFIX as ti,resolvePatch as ni,stripReservedPatchFields as ii,assertPatchAllowed as oi,resolveRelationPredicates as ri,selectIndexForGroupBy as si,composeReadPredicate as ai,fanOutScalarCounts as ci,matchesStaticWhere as Qe,coerceAggregateNumber as ze,whereOfFilter as di,isPushableWhere as li,tiebreakDirectionFor as ui,foldAggregateTally as bt,CDC_LOG_TABLE_SEQ_INDEX as fi,NotUniqueError as wi,WORKERD_SQLITE_LIMITS as hi,unionAll as $i}from"@lunora/shard-engine";import{parseWire as _i,needsWireEncoding as Xt,encodeWire as Qt,decodeWire as Ei}from"@lunora/wire";import{sql as e,SQL as pi}from"drizzle-orm";import{p as Mt,b as Nt,q as b,c as K,e as zt,i as yi,f as Ri,g as Si,h as z,s as ce,j as H,k as Ot,t as mi,l as Je,m as Fe,n as at,O as Se,o as qt,a as kt,u as Dt,v as Bt,w as gi,B as Ze,x as Wt,y as Ft,M as Ti}from"./sql-exec-ChIYvWnI.mjs";import{d as Mo}from"./sql-exec-ChIYvWnI.mjs";import{runSqlGlobalTableMigrations as vi}from"./runSqlGlobalTableMigrations-C4_8w8pO.mjs";import{runSqlAggregateMigrations as Ii,runSqlRankMigrations as Ai}from"./runSqlAggregateMigrations-CvZiVJ9S.mjs";import{a as me}from"./post-commit-error-hh-zQyjO.mjs";import{withQueryTimeout as Ci,DEFAULT_QUERY_TIMEOUT_MS as Li,abandonedWork as et,SqlQueryTimeoutError as bi}from"./DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import{s as Jt,e as ct}from"./value-codec-C52YW-Do.mjs";const Ut=50,Mi=(s,a={})=>{const f=a.maxBatch??Ut,$=Number.isInteger(f)&&f>0?f:Ut,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 s(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))})}}},Ni=new Set(["_id","id"]),Oi=s=>{throw new g("INTERNAL",`no ORDER BY NULL placement for dialect "${String(s)}"`)},Zt=(s,a)=>{const f=a.direction==="desc"?"DESC":"ASC",$=a.nullable===!0,l=_=>e`${Fe(s,a.field)} ${e.raw(`${f}${_}`)}`;switch(s.name){case"mysql":{const _=l("");return!$||a.nulls===void 0?[_]:[e`(${Fe(s,a.field)} IS NULL) ${e.raw(a.nulls==="first"?"DESC":"ASC")}`,_]}case"postgres":return[l($?Ct(Lt(a)):"")];case"sqlite":return[l($&&a.nulls!==void 0?Ct(Lt(a)):"")];default:return Oi(s.name)}},qi=(s,a)=>{const f=s.flatMap($=>Zt(a,$));if(!s.some($=>Ni.has($.field))){const $=ui(s);f.push(e`${H("id")} ${e.raw($==="desc"?"DESC":"ASC")}`)}return e.join(f,e`, `)},xt=50,ki=s=>{const a=s.detail??s["QUERY PLAN"];return typeof a=="string"?a:Object.values(s).map(String).join(" | ")},tt=(s,a,f,$)=>{for(const[l,_]of mi(s)){if(_.serverDefault){l in a&&(f[l]=_.serverDefault({auth:$}));continue}_.onUpdateFn&&!(l in a)&&(f[l]=_.onUpdateFn())}},Di=s=>s.shardMode===void 0||s.shardMode.kind==="global",ue=s=>s==null?null:Number(s),Bi=(s,a,f)=>f.map($=>{const l={};for(const _ of a){const c=s.shape[_];l[_]=Jt($[_]??null,c&&ct(c))}return{key:l,value:ue($.value)}}),Wi=(s,a,f)=>[...s.partitionBy??[],...s.sortBy.map(l=>l.field),...s.where?Object.keys(s.where):[]].every(l=>Dt(a,l)===Dt(f,l)),en=s=>s.length===1?s[0]:e`(${e.join(s,e` AND `)})`,fe=s=>e.join(s.map(a=>e`${e.identifier(a)}`),e`, `),Te=s=>e.join(s.map(a=>e`${a}`),e`, `),nt=(s,a)=>{if(s==="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`)}},Ue=s=>s instanceof ArrayBuffer?new Uint8Array(s):Array.isArray(s)?Uint8Array.from(s):s,Fi=(s,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?Yt(q,Ue($[q]),v,!1):e`${e.identifier(Ie)} < ${l}`;if(A===void 0)continue;const N=f.slice(0,c).map(D=>at(s,e`${e.identifier(D)}`,Ue($[D])));N.push(A),_.push(en(N))}return _.length>0?e.join(_,e` OR `):e`1 = 0`},Ui=(s,a,f)=>{if(f.length!==a.length)return;const $=[];for(const[l,_]of a.entries()){const c=Yt(_.column,Ue(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(s,e`${e.identifier(T.column)}`,Ue(f[M])))}q.push(c),$.push(en(q))}return $.length===0?e`(1 = 0)`:e`(${e.join($,e` OR `)})`},xi=(s,a)=>{if(s.sortBy.length===0)throw new g("INTERNAL",`rankIndex "${s.name}" requires at least one "sortBy" column for stable pagination`);const f=[{column:"__partition__",direction:"asc",nullable:!1}];for(const[$,l]of s.sortBy.entries())f.push({column:a[$]??ge($),direction:l.direction,nullable:!0});return f.push({column:Ie,direction:"asc",nullable:!1}),f},Pi=async(s,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(s,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},Hi=s=>{const a=s.map(_=>Jt(_,"bytes")),f=JSON.stringify(Xt(a)?Qt(a):a),$=new TextEncoder().encode(f);let l="";for(const _ of $)l+=String.fromCodePoint(_);return ti+btoa(l)},tn=s=>{if(s===void 0)return!1;const a=ct(s);return a==="any"||a==="bigint"||a==="from"||a==="union"},rt=(s,a,f)=>{if(tn(s.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)`)},Ki=(s,a,f,$)=>{for(const l of f)rt(s,l,`groupBy(${a}, { by: [..."${l}"] })`);$.field!==void 0&&rt(s,$.field,`groupBy(${a}, { agg: { op: "${$.op}", field: "${$.field}" } })`)},st="__cdc_sweep",Be="__cdc_log_ts",nn="global",ji=6e4,Gi=1e4,Vi=3e4;let Pt=0;const Yi=async(s,a)=>{const{autoincrementPrimaryKey:f,key:$,real:l,text:_}=a.companionTypes;await K(s,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(s,a,{columns:e`${c===void 0?e`${e.identifier("table")}`:e`${e.identifier("table")}(${e.raw(String(c))})`}, ${e.identifier("seq")}`,name:fi,table:W,unique:!1}),await K(s,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(s,a,e`INSERT INTO ${e.identifier(st)} (${e.identifier("id")}, ${e.identifier("lease_until")}) VALUES (${nn}, ${0}) ${a.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${e.identifier("id")} = ${e.identifier("id")}`:e`ON CONFLICT(${e.identifier("id")}) DO NOTHING`}`)},Xi=async(s,a,f)=>{const $=e`UPDATE ${e.identifier(st)} SET ${e.identifier("lease_until")} = ${f+ji} WHERE ${e.identifier("id")} = ${nn} AND ${e.identifier("lease_until")} <= ${f}`;if(a.supportsReturning)return(await b(s,a,e`${$} RETURNING ${e.identifier("id")}`)).length>0;const l=await K(s,a,$);return(a.affectedRows?a.affectedRows(l??{rowsAffected:0}):0)>0},Qi=async(s,a,f,$)=>{if(!await Xi(s,a,$))return;const l=$-f;let _=!0;try{const c=await yi(s,a,W,Be);c!=="valid"&&(c==="invalid"&&await Ri(s,a,W,Be),await zt(s,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(s,a,e`SELECT 1 AS ${e.identifier("hit")} FROM ${e.identifier(W)} WHERE ${e.identifier("ts")} <= ${l} LIMIT 1`)).length===0||await K(s,a,e`
|
|
2
2
|
DELETE FROM ${e.identifier(W)} WHERE ${e.identifier("seq")} IN (
|
|
3
3
|
SELECT ${e.identifier("seq")} FROM (
|
|
4
4
|
SELECT ${e.identifier("seq")} FROM ${e.identifier(W)} WHERE +${e.identifier("ts")} <= ${l} ORDER BY ${e.identifier("seq")} ASC LIMIT ${e.raw(String(Gi))}
|
|
5
5
|
) AS ${e.identifier("expired")}
|
|
6
6
|
)
|
|
7
|
-
`)},on=async(s,a)=>{const f=await b(s,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(s,a)=>{if(a.name!=="sqlite")return;const f=await b(s,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},Ji=s=>JSON.stringify(Xt(s)?Qt(s):s),Zi=(s,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 (${s}, ${a}, ${f}, ${$}, ${l===void 0?null:Ji(l)})`,rn=1e4,eo=1e3,to=(s,a,f)=>{let $=a;for(const[l,_]of s.entries()){const c=Number(_.seq);if(c>$+1&&Number(_.ts)>f)return s.slice(0,l);$=c}return s},Ao=async(s,a,f)=>{const $=a.sinceSeq??0,l=Math.max(1,Math.min(a.limit??1e3,1e4)),_=await on(s,f),c=await zi(s,f);if(c!==void 0&&$>c)throw Bn(c,$,"global");if(_!==void 0&&Wn(_,$))throw Fn(_,$,"global");const q=await b(s,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:to(q,$,(a.now??Date.now())-rn)).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:_i(A)}:N});return{changes:T,cursor:T.at(-1)?.seq??$}},Ht=(s,a)=>{const f=e.identifier(W),$=e`(SELECT MIN(v.seq) FROM ${f} v WHERE v.seq > ${s} AND v.seq - 1 > ${s} 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 > ${s} AND q.seq < ${$}) AS ${e.identifier("below")}`},Kt=(s,a,f)=>{const $=Number(a?.gap??Number.NaN);if(!Number.isFinite($))return s;const l=Number(a?.below??Number.NaN);return Math.min(s,Number.isFinite(l)?l:f)},no=s=>{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 > ${s}) AS seq FROM "t" WHERE "t"."name" IS NOT NULL) WHERE seq IS NOT NULL ORDER BY ${f}`},io=async(s,a,f,$={})=>{const l=e.identifier(W),_=f.name!=="sqlite",c=($.now??Date.now())-rn;if($.cursorOnly){const A=e`GREATEST((SELECT MAX(seq) FROM ${l}) - ${e.raw(String(eo))}, ${a})`,N=await b(s,f,e`SELECT MAX(seq) AS seq${_?e`, ${Ht(A,c)}`:e``} FROM ${l}`),D=Number(N[0]?.seq??a);return{cursor:Kt(Number.isFinite(D)?D:a,N[0],a),tables:[]}}const q=await b(s,f,_?e`SELECT ${e.identifier("table")} AS ${e.identifier("table")}, MAX(seq) AS seq, ${Ht(e`${a}`,c)} FROM ${l} WHERE seq > ${a} GROUP BY ${e.identifier("table")}`:no(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=Kt(M,q[0],a);const v=$.retained===!0?await on(s,f):void 0;return{cursor:M,tables:T,...v===void 0?{}:{floor:v}}},oo=/string or blob too big/iu,ro=/row is too big/iu,so=(s,a)=>{const{code:f,errno:$}=a,l=a instanceof Error?a.message:"";switch(s.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 ro.test(l)?"the 8 KB heap page a tuple must fit once its wide columns have been TOASTed out":void 0;default:return oo.test(l)?"the storage engine's per-row ceiling (2 MB on D1)":void 0}},ao=(s,a,f)=>{const $=so(s,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,jt="__lunora_patch_if_match__",Gt=(s,a,f)=>{throw s.isUniqueViolation(a)?new ne(`unique constraint violation on "${f}"`,"unique"):(ao(s,a,f),a)},co=s=>{const{code:a,errno:f}=s??{};return a==="40P01"||a==="40001"||f===1213||a==="ER_LOCK_DEADLOCK"},lo=s=>{throw co(s)?new ne("the write's transaction was rolled back by a lock conflict with a concurrent write; retry it","occ"):s},ot=new WeakMap,Vt=new WeakMap,de="superseded",uo=3e4,Te="__lunora_companion_fence",fo=(s,a,f,$,l)=>{const _=Math.max(1,Math.floor((Ti-2)/$.length)),c=(T,v)=>{const A=s.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)} (${fe($.map(A=>A.name))}) SELECT * FROM (${$i(v)}) AS ${e.identifier("__rows__")} WHERE EXISTS (SELECT 1 FROM ${e.identifier(Te)} WHERE ${f})`)}return M},le=(s,a,f)=>JSON.stringify([s,a,f]),We=s=>JSON.stringify(s,(a,f)=>typeof f=="bigint"?`${String(f)}n`:f),wo=s=>{const a=Un(s);return(f,$,l,_)=>$.some(c=>c instanceof pi)?Si(s,f,$,l):a(f,$,l,_)},Co=s=>{const{crossShardCounter:a,crossShardReader:f,maxRelationKeys:$,schema:l}=s,_=Ci(s.exec,s.queryTimeoutMs??Li,s.queryTimer),{dialect:c}=s,q={fieldRef:t=>Fe(c,t),rangeTypeGuard:(t,n)=>gi(c,t,n),...c.name==="mysql"?{containsExpr:(t,n)=>{const i=Mt(t);return i===void 0?e`LOCATE(${n}, ${t}) > 0`:e`LOCATE(${Nt("mysql",n)}, ${i}) > 0`}}:{},...c.name==="postgres"?{containsExpr:(t,n)=>{const i=Mt(t);return i===void 0?e`strpos(${t}, ${n}) > 0`:e`strpos(${i}, ${Nt("postgres",n)}) > 0`}}:{},...c.name==="sqlite"?{}:{inList:wo(c.name)}},M=new WeakMap,T=t=>{const n=M.get(t);if(n!==void 0)return n;const i={...q,serialize:(o,r)=>Bt(c,r,o,d=>ce(t,r,d))};return M.set(t,i),i},v=(t,n)=>at(c.name,t,n),A=t=>{const n=fe(t.columns),i=ge(t.values),o=h=>c.name==="mysql"?e`VALUES(${e.identifier(h)})`:e`excluded.${e.identifier(h)}`,r=h=>c.name==="postgres"?e`${e.identifier(t.table)}.${e.identifier(h)}`:e`${e.identifier(h)}`,d=e.join(Object.entries(t.set(o,r)).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=s.clock??(()=>Date.now()),D=s.idGenerator??(()=>crypto.randomUUID()),j=s.cdc??!1,J=typeof s.cdcRetentionMs=="number"&&Number.isFinite(s.cdcRetentionMs)&&s.cdcRetentionMs>0?s.cdcRetentionMs:void 0,ie=s.auth??{identity:null,userId:null},we=(t,n,i,o)=>j?[Zi(N(),t,n,i,o)]:[],sn=async()=>{if(!j||J===void 0)return;const t=N();if(!(t-Pt<Vi)){Pt=t;try{await Qi(_,c,J,t)}catch{}}},an=s.scheduler??kn;let Ie=0;const he=s.provisionScope??{},F=async()=>{const t=ot.get(he);if(t)return t;const n=(async()=>{const i=s.exec;await vi(i,l,c),await Ii(i,l,c),await Ai(i,l,c),await mn(i,c),await vn(_,l,c),j&&await Yi(i,c)})().catch(i=>{throw ot.delete(he),i});return ot.set(he,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&&Di(n)?t:void 0};let Ae=Vt.get(he);Ae===void 0&&(Ae=new Map,Vt.set(he,Ae));const x=Ae;let xe=0;const dt={},Pe=(t,n,i)=>{const o=(async()=>(await F(),await i(()=>x.get(t)?.run!==o)))(),r={definition:n,owner:dt,run:o,settled:!1};return o.then(d=>{d===de&&x.get(t)===r?x.delete(t):r.settled=!0},()=>{x.get(t)===r&&x.delete(t)}).catch(()=>{}),x.set(t,r),o},lt=async(t,n,i)=>{const o=x.get(t);if(o===void 0)return await Pe(t,n,i);const r=o.definition===n;if(r&&(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,uo,"stalled")}),h=await Promise.race([o.run,u]).finally(()=>{clearTimeout(d)});return h!=="stalled"&&r?h:x.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===de?await He(t,n,i):o},ut=async(t,n)=>{const i=x.get(t),o=i?.settled===!0&&i.definition===n?await i.run:void 0;if(typeof o=="boolean")return o;x.delete(t),xe+=1},Z=t=>{const n=l.tables[t];for(const i of n?.aggregateIndexes??[])x.delete(le("aggregate",t,i.name));for(const i of n?.rankIndexes??[])x.delete(le("rank",t,i.name))},cn=async(t,n)=>{const i=ae(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(Te)} (${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:r=>({token:r("token")}),table:Te,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(Te)} WHERE ${o})`,stillHeld:async()=>(await b(_,c,e`SELECT 1 FROM ${e.identifier(Te)} WHERE ${o}`)).length>0,guardedInsertRows:(r,d)=>fo(c,t,o,r,d)}},dn=async(t,n,i)=>{const o=l.tables[t];if(!o||!await cn(t,n.name))return!1;const r=n.by??[],d=new Map;await Wt(_,c,o,t,R=>{if(n.where&&!Qe(R,n.where))return;const S=te(r,R);bt(d,S,n,R)});const u=ae(t,n.name);if(i())return de;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,S])=>[R,S.value,S.count]));return i()||await Ft(_,c,w),i()||!await h.stillHeld()?de:!0},Ce=(t,n)=>He(le("aggregate",t,n.name),We(n),i=>dn(t,n,i)),ln=async(t,n,i,o,r)=>{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(r,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 Ot(t,E))bt(d,"",i,w);u=E.at(-1)?.id,h=E.length===Ze}return d.get("")?.value??null},un=async(t,n,i,o)=>{const r=n.field??"",d=[],u=l.tables[t],h=(w,R)=>Bt(c,w,R,S=>u?ce(u,w,S):Je(S));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 S=R!==null&&typeof R=="object"&&!Array.isArray(R)?R.eq:R,m=h(w,S),C=Fe(c,w);d.push(m===null?e`${C} IS NULL`:e`${C} = ${m}`)}const y=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``;if(u&&tn(u.shape[r]))return ln(u,t,n,d,o);const p=Re(n.op),E=await b(o,c,e`SELECT ${e.raw(p)}(${H(r)}) AS ${e.identifier("value")} FROM ${e.identifier(t)}${y}`);return ue(E[0]?.value)},fn=(t,n)=>e`DELETE FROM ${e.identifier(t)} WHERE ${e.identifier("__key__")} = ${n} AND ${e.identifier("__count__")} <= 0`,wn=async(t,n,i,o,r)=>{const d=ae(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 m=[],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),m.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)m.push(fn(d,I));return m}const E=[],w=[];let R,S;if(y){const m=te(n.by??[],y);R=m;const C=ze(y[h]),I=(await b(r,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__")} = ${m}`))[0],O=ue(I?.value),k=(I?.count??0)-1;if(k<=0)E.push(e`DELETE FROM ${e.identifier(d)} WHERE ${e.identifier("__key__")} = ${m}`);else if(I&&C!==void 0&&O!==null&&C===O){const P=await un(t,n,y,r);E.push(e`UPDATE ${e.identifier(d)} SET ${e.identifier("__value__")} = ${P}, ${e.identifier("__count__")} = ${k} WHERE ${e.identifier("__key__")} = ${m}`)}else E.push(e`UPDATE ${e.identifier(d)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${m}`)}if(p){const m=te(n.by??[],p);S=m;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:[m,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:[m,C,1]}))}}return R!==void 0&&S!==void 0&&S<R?[...w,...E]:[...E,...w]},Le=async t=>{const n=l.tables[t]?.aggregateIndexes;if(!(!n||n.length===0))for(const i of n)await Ce(t,i)},_e=async(t,n,i,o)=>{const r=l.tables[t]?.aggregateIndexes,d=[];if(!r||r.length===0)return d;for(const u of r)await ut(le("aggregate",t,u.name),We(u))&&d.push(...await wn(t,u,n,i,o));return d},hn=async(t,n)=>{const i=ye(t,n);return(await b(_,c,c.tableExists(i))).length>0},$n=async(t,n,i)=>{const o=l.tables[t];if(!o||!await hn(t,n.name))return!1;const r=ye(t,n.name);if(i())return de;const d=await ft(r);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:me(w),type:c.columnType(R?ct(R):void 0)}})];let y=[];const p=async()=>{const E=y;y=[],!(E.length===0||i())&&await Ft(_,c,d.guardedInsertRows(h,E))};return await Wt(_,c,o,t,async E=>{if(n.where&&!At(E,n.where))return;const w=qe(n.partitionBy??[],E),R=n.sortBy.map(S=>Je(E[S.field]??null));y.push([E._id,w,...R]),y.length>=Ze&&await p()}),await p(),i()||!await d.stillHeld()?de:!0},Ke=(t,n)=>He(le("rank",t,n.name),We(n),i=>$n(t,n,i)),be=async t=>{const n=l.tables[t]?.rankIndexes;if(!(!n||n.length===0))for(const i of n)await Ke(t,i)},oe=async(t,n,i,o)=>{const r=l.tables[t],d=r?.rankIndexes,u=[];if(!d||d.length===0)return u;const h=r?.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&&Wi(E,i,o)||!await ut(le("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&&!At(o,E.where))continue;const S=E.sortBy.map((I,O)=>me(O)),m=fe(["__id__","__partition__",...S]),C=qe(E.partitionBy??[],o),L=E.sortBy.map(I=>Je(o[I.field]??null));u.push(e`INSERT INTO ${e.identifier(R)} (${m}) VALUES (${ge([n,C,...L])})`)}}return u},_n=(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(()=>{})},re=async(t,n,i,o,r)=>{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(m){if(_.transaction===void 0&&m instanceof bi){Z(t);const C=()=>{Z(t)};et(m)?.then(C,C).catch(()=>{})}throw m}if(!R)return!1;const S={batched:!1,dispatched:!1};try{h&&r.length>0&&await kt(w,c,r);const m=h?await i(w):[...await i(w),...r];m.length>0&&(S.batched=w.batch!==void 0&&c.name==="sqlite",S.dispatched=!0,await kt(w,c,m))}catch(m){throw _.transaction===void 0&&_n(t,m,S),h&&await De(t,o,async()=>{throw await Promise.resolve(),m}),m}return!0};let p;const E=xe;try{p=_.transaction!==void 0&&u?await _.transaction(y).catch(lo):await y(_),p&&xe!==E&&_.transaction!==void 0&&u&&Z(t)}catch(w){const R=et(w);if(R!==void 0){const S=async()=>{await In({dialect:c,exec:_,schema:l},t,o)};R.then(S,S).catch(()=>{})}throw w}return p&&await De(t,o,sn),p},Ee=Tn({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(Ie+=1,Ie>xt)throw Ie-=1,new ne(`trigger recursion exceeded ${String(xt)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await ei({ctx:ht,event:i,op:n,schema:l,tableName:i.table,timing:t})}finally{Ie-=1}},En=async(t,n,i=_)=>{try{await K(i,c,n)}catch(o){Gt(c,o,t)}},Me=async(t,n)=>(await b(_,c,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} = ${n}`))[0],$t=async(t,n,i,o,r,d)=>{const u=e`${e.identifier(Se)}`,h=e.join([v(e`${e.identifier("id")}`,o.id),v(u,o[Se]??null),...r===void 0?[]:[e`(${r})`]],e` AND `),y=n==="UPDATE"?e`UPDATE ${e.identifier(t)} SET ${i}, ${u} = ${qt.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 Gt(c,p,t)}},je=async(t,n,i,o,r)=>{if(o!==void 0&&!await $t(t,n,i,o,void 0,r))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,[Se]:qt.value(t?.[Se])}),_t=async(t,n,i,o,r,d,u)=>{const h=z(n,r);if(!h||r===void 0)throw new g("INTERNAL",`document not found: ${i}`);const y=ni(n,o,h),p={...h,...ii(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(m=>[m,E[m]]))),oi(u,h,E),Y(t,"before","update")&&await X("before","update",{doc:{...E},id:i,op:"update",previous:h,table:t}),await Le(t),await be(t);const w=Object.keys(n.shape),R=e.join(w.map(m=>e`${e.identifier(m)} = ${ce(n,m,E[m]??null)}`),e`, `);if(await re(t,async m=>await $t(t,"UPDATE",R,r,d,m),async m=>[...await _e(t,h,E,m),...await oe(t,i,h,E)],i,we(t,i,"update",E)))return await Ee(t,i,{document:E,previous:h,written:Ge(r)}),Y(t,"after","update")&&await X("after","update",{doc:E,id:i,op:"update",previous:h,table:t}),E},pn=(t,n,i,o)=>{const r=Object.keys(t.shape);return{columns:["id","_creationTime",...r],values:[n,i,...r.map(d=>ce(t,d,o[d]??null))]}},yn=async(t,n,i,o)=>{const r=si(n,i.op,i.field,o.by,o.where);if(!r||!await Ce(t,r.index))return;const u=ae(t,r.index.name),h=Object.keys(r.partial);if(h.length===(r.index.by??[]).length&&h.length>0){const p=te(r.index.by??[],r.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:{...r.partial},value:Xe(i.op,{count:w.count,value:ue(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:Ei(JSON.parse(E.key)),value:Xe(i.op,{count:E.count,value:ue(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`)},Rn=(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 r=n.relationBaseWhere(o);r!==void 0&&(i[o]=r)}return{orderBy:n?.orderBy,relationPolicies:i,where:U(n?.baseWhere,n?.where),with:n?.with}},Ne=(t,n)=>Et(t)?f?f(t,Rn(t,n)):pt(t):G.findMany(t,n),Oe=(t,n,i)=>ri(t,{fetcher:Ne,maxRelationKeys:$,relationBaseWhere:i,schema:l,tableName:n}),Sn=Mi(async(t,n)=>{const i=await b(_,c,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} IN (${ge(n)})`),o=new Map;for(const r of i){const{id:d}=r;typeof d=="string"&&o.set(d,r)}return o}),yt=async(t,n,i)=>{const{fetchLimit:o,limit:r,orderKeys:d,predicate:u}=await ai(n,i,{fetcher:Ne,maxRelationKeys:$,schema:l,tableName:t}),h=ee(u,T(n)),y=qi(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:r,orderKeys:d,query:p}},G={relationWrites:Dn(l),async cdcChangedTables(t,n){if(j)try{return await F(),await io(_,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=ke(i.softDeleteMode,void 0),r=U(U(n.baseWhere,n.where),o),d=await Oe(r,t,n.relationBaseWhere),u=d!==r;if(i.aggregateIndexes&&!n.baseWhere&&!u&&!o){const R=Zn(i.aggregateIndexes,n.op,n.field,n.where);if(R&&await Ce(t,R.index)){const m=te(R.index.by??[],R.key),C=ae(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__")} = ${m}`))[0];return Xe(n.op,I===void 0?void 0:{count:I.count,value:ue(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=zn(n);if(o.restrictsCounts)throw new gt(t);const r=ke(i.softDeleteMode,void 0),d=U(U(o.baseWhere,o.where),r),u=await Oe(d,t,o.relationBaseWhere),h=u!==d;if(i.aggregateIndexes&&!o.baseWhere&&!h&&!r){const w=Jn(i.aggregateIndexes,o.where);if(w&&await Ce(t,w.index)){const S=te(w.index.by??[],w.key),m=ae(t,w.index.name),C=await b(_,c,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")} FROM ${e.identifier(m)} WHERE ${e.identifier("__key__")} = ${S}`);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 r=l.tables[o];if(!r)return;const d=await Me(o,n);if(d===void 0)return;const u=z(r,d),h=i?.hard===!0,y=!h&&r.softDeleteMode?r.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}),await Qn({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 Le(o),await be(o),y&&u){const p={[y]:N()},E={...u,...p};tt(r,p,E,ie);const w=e.join(Object.keys(r.shape).map(R=>e`${e.identifier(R)} = ${ce(r,R,E[R]??null)}`),e`, `);await re(o,async R=>(await je(o,"UPDATE",w,d,R),!0),async R=>[...await _e(o,u,E,R),...await oe(o,n,u,void 0)],n,we(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 re(o,async p=>(await je(o,"DELETE",void 0,d,p),!0),async p=>[...await _e(o,u??void 0,void 0,p),...await oe(o,n,u??void 0,void 0)],n,we(o,n,"delete")),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={}){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 Xn(`findFirstOrThrow: no "${t}" document matched`);return i},async findMany(t,n={}){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await F();const o=async(R,S,m,C)=>{if(Et(R))return a?ci(a,R,S,m,C):pt(R);const L=l.tables[R];if(!L)throw new g("INTERNAL",`unknown table: ${R}`);const I=ke(L.softDeleteMode,void 0),O={[S]:{in:m}},k=U(U(O,C),I),P=await Oe(k,R,void 0),Q=ee(P,T(L)),pe=H(S);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),se=new Map;for(const Rt of B)se.set(Rt.__fk__,Number(Rt.count??0));return se},{limit:r,orderKeys:d,query:u}=await yt(t,i,n),h=await b(_,c,u),y=Ot(i,h);if(r===void 0)return n.with&&await Tt({fetcher:Ne,groupedCounter:o,parents:y,...vt(n),schema:l,tableName:t,with:n.with}),{continueCursor:null,isDone:!0,page:It(y,n.select,n.with)};const p=y.length>r,E=p?y.slice(0,r):y,w=E.at(-1);return n.with&&await Tt({fetcher:Ne,groupedCounter:o,parents:E,...vt(n),schema:l,tableName:t,with:n.with}),{continueCursor:p&&w?Yn(w,d):null,isDone:!p,page:It(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),r=c.name==="sqlite"?"EXPLAIN QUERY PLAN":"EXPLAIN",d=await b(_,c,e`${e.raw(r)} ${o}`),{params:u,sql:h}=c.render(o);return{params:u,plan:d.map(y=>ki(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 Sn.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 r=ke(i.softDeleteMode,void 0),d=U(U(n.baseWhere,n.where),r),u=await Oe(d,t,n.relationBaseWhere),h=u!==d;if(i.aggregateIndexes&&!n.baseWhere&&!h&&!r){const S=await yn(t,i.aggregateIndexes,o,n);if(S!==void 0)return S}Ki(i,t,n.by,o);const y=ee(u,T(i)),p=n.by.map(S=>e`${H(S)} AS ${e.identifier(S)}`);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(S=>H(S)),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 Bi(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 r=Ye(o,jn(o,n,ie),{supplied:n,trusted:i?.allowExplicitId===!0});nt(c.name,r);let d;i?.clientId!==void 0?(Gn(i.clientId),d=i.clientId):i?.allowExplicitId&&typeof r._id=="string"?(Vn(r._id),d=r._id):d=D();const u=i?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:N(),h={...r,_creationTime:u,_id:d};Y(t,"before","insert")&&await X("before","insert",{doc:{...h},id:d,op:"insert",table:t}),await Le(t),await be(t);const{columns:y,values:p}=pn(o,d,u,r);return await re(t,async E=>(await En(t,e`INSERT INTO ${e.identifier(t)} (${fe(y)}) VALUES (${ge(p)})`,E),!0),async E=>[...await _e(t,void 0,h,E),...await oe(t,d,void 0,h)],d,we(t,d,"insert",h)),await De(t,d,async()=>{await Ee(t,d,{document:h,written:{_creationTime:u,[Se]:null}}),Y(t,"after","insert")&&await X("after","insert",{doc:h,id:d,op:"insert",table:t})}),d},normalizeId(t,n){return Kn(l,t,n)},async patch(t,n,i,o){Ve("patch",i);const r=await $e(t);if(!r)throw new g("INTERNAL",`document not found: ${n}`);const d=l.tables[r];if(!d)throw new g("INTERNAL",`document not found: ${n}`);const u=Hn(d,i)?it:1;for(let h=0;h<u;h+=1){const y=await Me(r,n);if(await _t(r,d,n,i,y,void 0,o))return}throw new ne(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},async patchIf(t,n,i){Ve("patchIf",i.patch);const o=await $e(t),r=o===void 0?void 0:l.tables[o];if(o===void 0||!r)return{applied:!1,doc:null};const d=o,u=ee(i.where,T(r))??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(jt)} FROM ${e.identifier(d)} WHERE ${e.identifier("id")} = ${n}`);if(y===void 0)return{applied:!1,doc:null};const{[jt]:p,...E}=y;if(Number(p)!==1)return{applied:!1,doc:z(r,E)??null};const w=await _t(d,r,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 Me(i,n);if(!i||o===void 0)throw new g("INTERNAL",`document not found: ${n}`);const r=l.tables[i],d=r?.softDeleteMode?.field;if(!r||!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(r,o);h!==null&&await re(i,async()=>await Promise.resolve(!0),async()=>await oe(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 r=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 S=2*bn+w.filters.length,m=d===void 0?void 0:ee(d,h,void 0,S),C=m!==void 0&&c.name==="sqlite"&&c.render(m).params.length+S>hi.boundParams,L=C?void 0:m,I=r>0||C,O=await Mn(_,c,n,t,L===void 0?w:{...w,scope:L},Nn(I?void 0:R));!I&&R===void 0&&On(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(S){o.push(S);const m=di(S);return m!==void 0&&li(m,n.shape,u)?d=U(d,m):r+=1,R},async first(){if(!w)throw new g("INTERNAL",i);return(await p(w,1))[0]??null},order(){return R},async paginate(S){if(!w)throw new g("INTERNAL",i);const m=Cn(S);return Ln(await p(w,qn(m)),m)},async take(S){if(!w)throw new g("INTERNAL",i);return p(w,S)},async unique(){if(!w)throw new g("INTERNAL",i);const S=await p(w,2);if(S.length>1)throw new wi(`unique() on table "${t}" matched ${String(S.length)} documents; expected at most one`);return S[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(S,m){const C=(n.searchIndexes??[]).find(I=>I.name===S);if(!C)throw new g("INTERNAL",`unknown search index "${S}" on table "${t}"`);const L={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:S,query:""};if(m(An(L,t,gn(C.language))),!L.hasQuery)throw new g("INTERNAL",`search index "${S}" 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 r=o.rankIndexes?.find(O=>O.name===n);if(!r)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(i.restrictsCounts)throw new gt(t);if(await F(),!await Ke(t,r))return null;const u=typeof i.row=="string"?i.row:i.row._id;if(!u)return null;const h=ye(t,r.name),y=r.sortBy.map((O,k)=>me(k)),p=fe(["__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__,S=U(i.baseWhere,i.where);St(S,l,t,"rank");const m=mt(r,S);if(m&&qe(r.partitionBy??[],m)!==R)return null;const C=Fi(c.name,r,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={}){St(U(i.baseWhere,i.where),l,t,"rankPage");const o=l.tables[t];if(!o)throw new g("INTERNAL",`unknown table: ${t}`);const r=o.rankIndexes?.find(B=>B.name===n);if(!r)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(await F(),!await Ke(t,r))return{continueCursor:null,isDone:!0,page:[]};const u=ye(t,r.name),h=r.sortBy.map((B,se)=>me(se)),y=Math.max(1,Math.min(1e3,Math.floor(i.take??100))),p=U(i.baseWhere,i.where),E=mt(r,p),w=xi(r,h),R=e.join(w.flatMap(B=>Zt(c,{direction:B.direction,field:B.column,nullable:B.nullable})),e`, `),S=[];typeof i.partitionKey=="string"?S.push(e`${e.identifier("__partition__")} = ${i.partitionKey}`):E&&S.push(e`${e.identifier("__partition__")} = ${qe(r.partitionBy??[],E)}`);const m=Pn(i);if(m!==void 0){const B=Ui(c.name,w,m);B!==void 0&&S.push(B)}const C=fe([ve,"__partition__",...h]);let L=e`SELECT ${C} FROM ${e.identifier(u)}`;S.length>0&&(L=e`${L} WHERE ${e.join(S,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[ve]),Q=await Pi(_,c,o,t,P);let pe=null;const V=k.at(-1);if(O&&V!==void 0){const B=[V.__partition__,...h.map(se=>V[se]),V[ve]];pe=Hi(B)}return{continueCursor:pe,isDone:!O,page:Q}},async replace(t,n,i,o){Ve("replace",i);const r=await $e(t);if(!r)throw new g("INTERNAL",`document not found: ${n}`);const d=l.tables[r];if(!d)throw new g("INTERNAL",`document not found: ${n}`);const u=await Me(r,n);if(u===void 0)throw new g("INTERNAL",`document not found: ${n}`);const y=xn(l,r,"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 S=Ye(d,R,{previous:()=>y??z(d,u)??void 0,supplied:i,trusted:o?.allowExplicitId===!0});nt(c.name,S),Y(r,"before","update")&&await X("before","update",{doc:{...S},id:n,op:"update",previous:y,table:r}),await Le(r),await be(r);const m=Object.keys(d.shape),C=e.join([e`${e.identifier("_creationTime")} = ${w}`,...m.map(L=>e`${e.identifier(L)} = ${ce(d,L,S[L]??null)}`)],e`, `);await re(r,async L=>(await je(r,"UPDATE",C,u,L),!0),async L=>[...await _e(r,y,S,L),...await oe(r,n,y,S)],n,we(r,n,"update",S)),await De(r,n,async()=>{await Ee(r,n,{document:S,previous:y,written:Ge(u,w)}),Y(r,"after","update")&&await X("after","update",{doc:S,id:n,op:"update",previous:y,table:r})})}};return ht={db:G,scheduler:an},G};export{Co as createSqlCtxDb,Mo as decodeGlobalRow,io as readSqlCdcChangedTables,Ao as readSqlCdcChanges,on as readSqlCdcFloor,Yi as runSqlCdcMigration,Qi as sweepSqlCdcRetention};
|
|
7
|
+
`)},on=async(s,a)=>{const f=await b(s,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(s,a)=>{if(a.name!=="sqlite")return;const f=await b(s,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},Ji=s=>JSON.stringify(Xt(s)?Qt(s):s),Zi=(s,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 (${s}, ${a}, ${f}, ${$}, ${l===void 0?null:Ji(l)})`,rn=1e4,eo=1e3,to=(s,a,f)=>{let $=a;for(const[l,_]of s.entries()){const c=Number(_.seq);if(c>$+1&&Number(_.ts)>f)return s.slice(0,l);$=c}return s},Ao=async(s,a,f)=>{const $=a.sinceSeq??0,l=Math.max(1,Math.min(a.limit??1e3,1e4)),_=await on(s,f),c=await zi(s,f);if(c!==void 0&&$>c)throw Bn(c,$,"global");if(_!==void 0&&Wn(_,$))throw Fn(_,$,"global");const q=await b(s,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:to(q,$,(a.now??Date.now())-rn)).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:_i(A)}:N});return{changes:T,cursor:T.at(-1)?.seq??$}},Ht=(s,a)=>{const f=e.identifier(W),$=e`(SELECT MIN(v.seq) FROM ${f} v WHERE v.seq > ${s} AND v.seq - 1 > ${s} 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 > ${s} AND q.seq < ${$}) AS ${e.identifier("below")}`},Kt=(s,a,f)=>{const $=Number(a?.gap??Number.NaN);if(!Number.isFinite($))return s;const l=Number(a?.below??Number.NaN);return Math.min(s,Number.isFinite(l)?l:f)},no=s=>{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 > ${s}) AS seq FROM "t" WHERE "t"."name" IS NOT NULL) WHERE seq IS NOT NULL ORDER BY ${f}`},io=async(s,a,f,$={})=>{const l=e.identifier(W),_=f.name!=="sqlite",c=($.now??Date.now())-rn;if($.cursorOnly){const A=e`GREATEST((SELECT MAX(seq) FROM ${l}) - ${e.raw(String(eo))}, ${a})`,N=await b(s,f,e`SELECT MAX(seq) AS seq${_?e`, ${Ht(A,c)}`:e``} FROM ${l}`),D=Number(N[0]?.seq??a);return{cursor:Kt(Number.isFinite(D)?D:a,N[0],a),tables:[]}}const q=await b(s,f,_?e`SELECT ${e.identifier("table")} AS ${e.identifier("table")}, MAX(seq) AS seq, ${Ht(e`${a}`,c)} FROM ${l} WHERE seq > ${a} GROUP BY ${e.identifier("table")}`:no(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=Kt(M,q[0],a);const v=$.retained===!0?await on(s,f):void 0;return{cursor:M,tables:T,...v===void 0?{}:{floor:v}}},oo=/string or blob too big/iu,ro=/row is too big/iu,so=(s,a)=>{const{code:f,errno:$}=a,l=a instanceof Error?a.message:"";switch(s.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 ro.test(l)?"the 8 KB heap page a tuple must fit once its wide columns have been TOASTed out":void 0;default:return oo.test(l)?"the storage engine's per-row ceiling (2 MB on D1)":void 0}},ao=(s,a,f)=>{const $=so(s,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,jt="__lunora_patch_if_match__",Gt=(s,a,f)=>{throw s.isUniqueViolation(a)?new ne(`unique constraint violation on "${f}"`,"unique"):(ao(s,a,f),a)},co=s=>{const{code:a,errno:f}=s??{};return a==="40P01"||a==="40001"||f===1213||a==="ER_LOCK_DEADLOCK"},lo=s=>{throw co(s)?new ne("the write's transaction was rolled back by a lock conflict with a concurrent write; retry it","occ"):s},ot=new WeakMap,Vt=new WeakMap,de="superseded",uo=3e4,ve="__lunora_companion_fence",fo=(s,a,f,$,l)=>{const _=Math.max(1,Math.floor((Ti-2)/$.length)),c=(T,v)=>{const A=s.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)} (${fe($.map(A=>A.name))}) SELECT * FROM (${$i(v)}) AS ${e.identifier("__rows__")} WHERE EXISTS (SELECT 1 FROM ${e.identifier(ve)} WHERE ${f})`)}return M},le=(s,a,f)=>JSON.stringify([s,a,f]),We=s=>JSON.stringify(s,(a,f)=>typeof f=="bigint"?`${String(f)}n`:f),wo=s=>{const a=Un(s);return(f,$,l,_)=>$.some(c=>c instanceof pi)?Si(s,f,$,l):a(f,$,l,_)},Co=s=>{const{crossShardCounter:a,crossShardReader:f,maxRelationKeys:$,schema:l}=s,_=Ci(s.exec,s.queryTimeoutMs??Li,s.queryTimer),{dialect:c}=s,q={fieldRef:t=>Fe(c,t),rangeTypeGuard:(t,n)=>gi(c,t,n),...c.name==="mysql"?{containsExpr:(t,n)=>{const i=Mt(t);return i===void 0?e`LOCATE(${n}, ${t}) > 0`:e`LOCATE(${Nt("mysql",n)}, ${i}) > 0`}}:{},...c.name==="postgres"?{containsExpr:(t,n)=>{const i=Mt(t);return i===void 0?e`strpos(${t}, ${n}) > 0`:e`strpos(${i}, ${Nt("postgres",n)}) > 0`}}:{},...c.name==="sqlite"?{}:{inList:wo(c.name)}},M=new WeakMap,T=t=>{const n=M.get(t);if(n!==void 0)return n;const i={...q,serialize:(o,r)=>Bt(c,r,o,d=>ce(t,r,d))};return M.set(t,i),i},v=(t,n)=>at(c.name,t,n),A=t=>{const n=fe(t.columns),i=Te(t.values),o=h=>c.name==="mysql"?e`VALUES(${e.identifier(h)})`:e`excluded.${e.identifier(h)}`,r=h=>c.name==="postgres"?e`${e.identifier(t.table)}.${e.identifier(h)}`:e`${e.identifier(h)}`,d=e.join(Object.entries(t.set(o,r)).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=s.clock??(()=>Date.now()),D=s.idGenerator??(()=>crypto.randomUUID()),j=s.cdc??!1,J=typeof s.cdcRetentionMs=="number"&&Number.isFinite(s.cdcRetentionMs)&&s.cdcRetentionMs>0?s.cdcRetentionMs:void 0,ie=s.auth??{identity:null,userId:null},we=(t,n,i,o)=>j?[Zi(N(),t,n,i,o)]:[],sn=async()=>{if(!j||J===void 0)return;const t=N();if(!(t-Pt<Vi)){Pt=t;try{await Qi(_,c,J,t)}catch{}}},an=s.scheduler??kn;let Ae=0;const he=s.provisionScope??{},F=async()=>{const t=ot.get(he);if(t)return t;const n=(async()=>{const i=s.exec;await vi(i,l,c),await Ii(i,l,c),await Ai(i,l,c),await mn(i,c),await vn(_,l,c),j&&await Yi(i,c)})().catch(i=>{throw ot.delete(he),i});return ot.set(he,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&&Di(n)?t:void 0};let Ce=Vt.get(he);Ce===void 0&&(Ce=new Map,Vt.set(he,Ce));const x=Ce;let xe=0;const dt={},Pe=(t,n,i)=>{const o=(async()=>(await F(),await i(()=>x.get(t)?.run!==o)))(),r={definition:n,owner:dt,run:o,settled:!1};return o.then(d=>{d===de&&x.get(t)===r?x.delete(t):r.settled=!0},()=>{x.get(t)===r&&x.delete(t)}).catch(()=>{}),x.set(t,r),o},lt=async(t,n,i)=>{const o=x.get(t);if(o===void 0)return await Pe(t,n,i);const r=o.definition===n;if(r&&(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,uo,"stalled")}),h=await Promise.race([o.run,u]).finally(()=>{clearTimeout(d)});return h!=="stalled"&&r?h:x.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===de?await He(t,n,i):o},ut=async(t,n)=>{const i=x.get(t),o=i?.settled===!0&&i.definition===n?await i.run:void 0;if(typeof o=="boolean")return o;x.delete(t),xe+=1},Z=t=>{const n=l.tables[t];for(const i of n?.aggregateIndexes??[])x.delete(le("aggregate",t,i.name));for(const i of n?.rankIndexes??[])x.delete(le("rank",t,i.name))},cn=async(t,n)=>{const i=ae(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:r=>({token:r("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:(r,d)=>fo(c,t,o,r,d)}},dn=async(t,n,i)=>{const o=l.tables[t];if(!o||!await cn(t,n.name))return!1;const r=n.by??[],d=new Map;await Wt(_,c,o,t,R=>{if(n.where&&!Qe(R,n.where))return;const S=te(r,R);bt(d,S,n,R)});const u=ae(t,n.name);if(i())return de;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,S])=>[R,S.value,S.count]));return i()||await Ft(_,c,w),i()||!await h.stillHeld()?de:!0},Le=(t,n)=>He(le("aggregate",t,n.name),We(n),i=>dn(t,n,i)),ln=async(t,n,i,o,r)=>{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(r,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 Ot(t,E))bt(d,"",i,w);u=E.at(-1)?.id,h=E.length===Ze}return d.get("")?.value??null},un=async(t,n,i,o)=>{const r=n.field??"",d=[],u=l.tables[t],h=(w,R)=>Bt(c,w,R,S=>u?ce(u,w,S):Je(S));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 S=R!==null&&typeof R=="object"&&!Array.isArray(R)?R.eq:R,m=h(w,S),C=Fe(c,w);d.push(m===null?e`${C} IS NULL`:e`${C} = ${m}`)}const y=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``;if(u&&tn(u.shape[r]))return ln(u,t,n,d,o);const p=Re(n.op),E=await b(o,c,e`SELECT ${e.raw(p)}(${H(r)}) AS ${e.identifier("value")} FROM ${e.identifier(t)}${y}`);return ue(E[0]?.value)},fn=(t,n)=>e`DELETE FROM ${e.identifier(t)} WHERE ${e.identifier("__key__")} = ${n} AND ${e.identifier("__count__")} <= 0`,wn=async(t,n,i,o,r)=>{const d=ae(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 m=[],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),m.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)m.push(fn(d,I));return m}const E=[],w=[];let R,S;if(y){const m=te(n.by??[],y);R=m;const C=ze(y[h]),I=(await b(r,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__")} = ${m}`))[0],O=ue(I?.value),k=(I?.count??0)-1;if(k<=0)E.push(e`DELETE FROM ${e.identifier(d)} WHERE ${e.identifier("__key__")} = ${m}`);else if(I&&C!==void 0&&O!==null&&C===O){const P=await un(t,n,y,r);E.push(e`UPDATE ${e.identifier(d)} SET ${e.identifier("__value__")} = ${P}, ${e.identifier("__count__")} = ${k} WHERE ${e.identifier("__key__")} = ${m}`)}else E.push(e`UPDATE ${e.identifier(d)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${m}`)}if(p){const m=te(n.by??[],p);S=m;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:[m,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:[m,C,1]}))}}return R!==void 0&&S!==void 0&&S<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 r=l.tables[t]?.aggregateIndexes,d=[];if(!r||r.length===0)return d;for(const u of r)await ut(le("aggregate",t,u.name),We(u))&&d.push(...await wn(t,u,n,i,o));return d},hn=async(t,n)=>{const i=ye(t,n);return(await b(_,c,c.tableExists(i))).length>0},$n=async(t,n,i)=>{const o=l.tables[t];if(!o||!await hn(t,n.name))return!1;const r=ye(t,n.name);if(i())return de;const d=await ft(r);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 Ft(_,c,d.guardedInsertRows(h,E))};return await Wt(_,c,o,t,async E=>{if(n.where&&!At(E,n.where))return;const w=ke(n.partitionBy??[],E),R=n.sortBy.map(S=>Je(E[S.field]??null));y.push([E._id,w,...R]),y.length>=Ze&&await p()}),await p(),i()||!await d.stillHeld()?de:!0},Ke=(t,n)=>He(le("rank",t,n.name),We(n),i=>$n(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)},oe=async(t,n,i,o)=>{const r=l.tables[t],d=r?.rankIndexes,u=[];if(!d||d.length===0)return u;const h=r?.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&&Wi(E,i,o)||!await ut(le("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&&!At(o,E.where))continue;const S=E.sortBy.map((I,O)=>ge(O)),m=fe(["__id__","__partition__",...S]),C=ke(E.partitionBy??[],o),L=E.sortBy.map(I=>Je(o[I.field]??null));u.push(e`INSERT INTO ${e.identifier(R)} (${m}) VALUES (${Te([n,C,...L])})`)}}return u},_n=(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(()=>{})},re=async(t,n,i,o,r)=>{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(m){if(_.transaction===void 0&&m instanceof bi){Z(t);const C=()=>{Z(t)};et(m)?.then(C,C).catch(()=>{})}throw m}if(!R)return!1;const S={batched:!1,dispatched:!1};try{h&&r.length>0&&await kt(w,c,r);const m=h?await i(w):[...await i(w),...r];m.length>0&&(S.batched=w.batch!==void 0&&c.name==="sqlite",S.dispatched=!0,await kt(w,c,m))}catch(m){throw _.transaction===void 0&&_n(t,m,S),h&&await me(t,o,async()=>{throw await Promise.resolve(),m}),m}return!0};let p;const E=xe;try{p=_.transaction!==void 0&&u?await _.transaction(y).catch(lo):await y(_),p&&xe!==E&&_.transaction!==void 0&&u&&Z(t)}catch(w){const R=et(w);if(R!==void 0){const S=async()=>{await In({dialect:c,exec:_,schema:l},t,o)};R.then(S,S).catch(()=>{})}throw w}return p&&await me(t,o,sn),p},Ee=Tn({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>xt)throw Ae-=1,new ne(`trigger recursion exceeded ${String(xt)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await ei({ctx:ht,event:i,op:n,schema:l,tableName:i.table,timing:t})}finally{Ae-=1}},En=async(t,n,i=_)=>{try{await K(i,c,n)}catch(o){Gt(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,r,d)=>{const u=e`${e.identifier(Se)}`,h=e.join([v(e`${e.identifier("id")}`,o.id),v(u,o[Se]??null),...r===void 0?[]:[e`(${r})`]],e` AND `),y=n==="UPDATE"?e`UPDATE ${e.identifier(t)} SET ${i}, ${u} = ${qt.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 Gt(c,p,t)}},je=async(t,n,i,o,r)=>{if(o!==void 0&&!await $t(t,n,i,o,void 0,r))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,[Se]:qt.value(t?.[Se])}),_t=async(t,n,i,o,r,d,u)=>{const h=z(n,r);if(!h||r===void 0)throw new g("INTERNAL",`document not found: ${i}`);const y=ni(n,o,h),p={...h,...ii(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(m=>[m,E[m]]))),oi(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(m=>e`${e.identifier(m)} = ${ce(n,m,E[m]??null)}`),e`, `);if(await re(t,async m=>await $t(t,"UPDATE",R,r,d,m),async m=>[...await _e(t,h,E,m),...await oe(t,i,h,E)],i,we(t,i,"update",E)))return await Ee(t,i,{document:E,previous:h,written:Ge(r)}),Y(t,"after","update")&&await X("after","update",{doc:E,id:i,op:"update",previous:h,table:t}),E},pn=(t,n,i,o)=>{const r=Object.keys(t.shape);return{columns:["id","_creationTime",...r],values:[n,i,...r.map(d=>ce(t,d,o[d]??null))]}},yn=async(t,n,i,o)=>{const r=si(n,i.op,i.field,o.by,o.where);if(!r||!await Le(t,r.index))return;const u=ae(t,r.index.name),h=Object.keys(r.partial);if(h.length===(r.index.by??[]).length&&h.length>0){const p=te(r.index.by??[],r.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:{...r.partial},value:Xe(i.op,{count:w.count,value:ue(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:Ei(JSON.parse(E.key)),value:Xe(i.op,{count:E.count,value:ue(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`)},Rn=(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 r=n.relationBaseWhere(o);r!==void 0&&(i[o]=r)}return{orderBy:n?.orderBy,relationPolicies:i,where:U(n?.baseWhere,n?.where),with:n?.with}},Oe=(t,n)=>Et(t)?f?f(t,Rn(t,n)):pt(t):G.findMany(t,n),qe=(t,n,i)=>ri(t,{fetcher:Oe,maxRelationKeys:$,relationBaseWhere:i,schema:l,tableName:n}),Sn=Mi(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 r of i){const{id:d}=r;typeof d=="string"&&o.set(d,r)}return o}),yt=async(t,n,i)=>{const{fetchLimit:o,limit:r,orderKeys:d,predicate:u}=await ai(n,i,{fetcher:Oe,maxRelationKeys:$,schema:l,tableName:t}),h=ee(u,T(n)),y=qi(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:r,orderKeys:d,query:p}},G={relationWrites:Dn(l),async cdcChangedTables(t,n){if(j)try{return await F(),await io(_,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),r=U(U(n.baseWhere,n.where),o),d=await qe(r,t,n.relationBaseWhere),u=d!==r;if(i.aggregateIndexes&&!n.baseWhere&&!u&&!o){const R=Zn(i.aggregateIndexes,n.op,n.field,n.where);if(R&&await Le(t,R.index)){const m=te(R.index.by??[],R.key),C=ae(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__")} = ${m}`))[0];return Xe(n.op,I===void 0?void 0:{count:I.count,value:ue(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=zn(n);if(o.restrictsCounts)throw new gt(t);const r=De(i.softDeleteMode,void 0),d=U(U(o.baseWhere,o.where),r),u=await qe(d,t,o.relationBaseWhere),h=u!==d;if(i.aggregateIndexes&&!o.baseWhere&&!h&&!r){const w=Jn(i.aggregateIndexes,o.where);if(w&&await Le(t,w.index)){const S=te(w.index.by??[],w.key),m=ae(t,w.index.name),C=await b(_,c,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")} FROM ${e.identifier(m)} WHERE ${e.identifier("__key__")} = ${S}`);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 r=l.tables[o];if(!r)return;const d=await Ne(o,n);if(d===void 0)return;const u=z(r,d),h=i?.hard===!0,y=!h&&r.softDeleteMode?r.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 Qn({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(r,p,E,ie);const w=e.join(Object.keys(r.shape).map(R=>e`${e.identifier(R)} = ${ce(r,R,E[R]??null)}`),e`, `);await re(o,async R=>(await je(o,"UPDATE",w,d,R),!0),async R=>[...await _e(o,u,E,R),...await oe(o,n,u,void 0)],n,we(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 re(o,async p=>(await je(o,"DELETE",void 0,d,p),!0),async p=>[...await _e(o,u??void 0,void 0,p),...await oe(o,n,u??void 0,void 0)],n,we(o,n,"delete")),await me(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={}){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 Xn(`findFirstOrThrow: no "${t}" document matched`);return i},async findMany(t,n={}){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await F();const o=async(R,S,m,C)=>{if(Et(R))return a?ci(a,R,S,m,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={[S]:{in:m}},k=U(U(O,C),I),P=await qe(k,R,void 0),Q=ee(P,T(L)),pe=H(S);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),se=new Map;for(const Rt of B)se.set(Rt.__fk__,Number(Rt.count??0));return se},{limit:r,orderKeys:d,query:u}=await yt(t,i,n),h=await b(_,c,u),y=Ot(i,h);if(r===void 0)return n.with&&await Tt({fetcher:Oe,groupedCounter:o,parents:y,...vt(n),schema:l,tableName:t,with:n.with}),{continueCursor:null,isDone:!0,page:It(y,n.select,n.with)};const p=y.length>r,E=p?y.slice(0,r):y,w=E.at(-1);return n.with&&await Tt({fetcher:Oe,groupedCounter:o,parents:E,...vt(n),schema:l,tableName:t,with:n.with}),{continueCursor:p&&w?Yn(w,d):null,isDone:!p,page:It(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),r=c.name==="sqlite"?"EXPLAIN QUERY PLAN":"EXPLAIN",d=await b(_,c,e`${e.raw(r)} ${o}`),{params:u,sql:h}=c.render(o);return{params:u,plan:d.map(y=>ki(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 Sn.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 r=De(i.softDeleteMode,void 0),d=U(U(n.baseWhere,n.where),r),u=await qe(d,t,n.relationBaseWhere),h=u!==d;if(i.aggregateIndexes&&!n.baseWhere&&!h&&!r){const S=await yn(t,i.aggregateIndexes,o,n);if(S!==void 0)return S}Ki(i,t,n.by,o);const y=ee(u,T(i)),p=n.by.map(S=>e`${H(S)} AS ${e.identifier(S)}`);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(S=>H(S)),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 Bi(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 r=Ye(o,jn(o,n,ie),{supplied:n,trusted:i?.allowExplicitId===!0});nt(c.name,r);let d;i?.clientId!==void 0?(Gn(i.clientId),d=i.clientId):i?.allowExplicitId&&typeof r._id=="string"?(Vn(r._id),d=r._id):d=D();const u=i?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:N(),h={...r,_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}=pn(o,d,u,r);return await re(t,async E=>(await En(t,e`INSERT INTO ${e.identifier(t)} (${fe(y)}) VALUES (${Te(p)})`,E),!0),async E=>[...await _e(t,void 0,h,E),...await oe(t,d,void 0,h)],d,we(t,d,"insert",h)),await me(t,d,async()=>{await Ee(t,d,{document:h,written:{_creationTime:u,[Se]:null}}),Y(t,"after","insert")&&await X("after","insert",{doc:h,id:d,op:"insert",table:t})}),d},normalizeId(t,n){return Kn(l,t,n)},async patch(t,n,i,o){Ve("patch",i);const r=await $e(t);if(!r)throw new g("INTERNAL",`document not found: ${n}`);const d=l.tables[r];if(!d)throw new g("INTERNAL",`document not found: ${n}`);const u=Hn(d,i)?it:1;for(let h=0;h<u;h+=1){const y=await Ne(r,n);if(await _t(r,d,n,i,y,void 0,o))return}throw new ne(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},async patchIf(t,n,i){Ve("patchIf",i.patch);const o=await $e(t),r=o===void 0?void 0:l.tables[o];if(o===void 0||!r)return{applied:!1,doc:null};const d=o,u=ee(i.where,T(r))??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(jt)} FROM ${e.identifier(d)} WHERE ${e.identifier("id")} = ${n}`);if(y===void 0)return{applied:!1,doc:null};const{[jt]:p,...E}=y;if(Number(p)!==1)return{applied:!1,doc:z(r,E)??null};const w=await _t(d,r,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 r=l.tables[i],d=r?.softDeleteMode?.field;if(!r||!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(r,o);h!==null&&await re(i,async()=>await Promise.resolve(!0),async()=>await oe(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 r=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 S=2*bn+w.filters.length,m=d===void 0?void 0:ee(d,h,void 0,S),C=m!==void 0&&c.name==="sqlite"&&c.render(m).params.length+S>hi.boundParams,L=C?void 0:m,I=r>0||C,O=await Mn(_,c,n,t,L===void 0?w:{...w,scope:L},Nn(I?void 0:R));!I&&R===void 0&&On(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(S){o.push(S);const m=di(S);return m!==void 0&&li(m,n.shape,u)?d=U(d,m):r+=1,R},async first(){if(!w)throw new g("INTERNAL",i);return(await p(w,1))[0]??null},order(){return R},async paginate(S){if(!w)throw new g("INTERNAL",i);const m=Cn(S);return Ln(await p(w,qn(m)),m)},async take(S){if(!w)throw new g("INTERNAL",i);return p(w,S)},async unique(){if(!w)throw new g("INTERNAL",i);const S=await p(w,2);if(S.length>1)throw new wi(`unique() on table "${t}" matched ${String(S.length)} documents; expected at most one`);return S[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(S,m){const C=(n.searchIndexes??[]).find(I=>I.name===S);if(!C)throw new g("INTERNAL",`unknown search index "${S}" on table "${t}"`);const L={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:S,query:""};if(m(An(L,t,gn(C.language))),!L.hasQuery)throw new g("INTERNAL",`search index "${S}" 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 r=o.rankIndexes?.find(O=>O.name===n);if(!r)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(i.restrictsCounts)throw new gt(t);if(await F(),!await Ke(t,r))return null;const u=typeof i.row=="string"?i.row:i.row._id;if(!u)return null;const h=ye(t,r.name),y=r.sortBy.map((O,k)=>ge(k)),p=fe(["__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__,S=U(i.baseWhere,i.where);St(S,l,t,"rank");const m=mt(r,S);if(m&&ke(r.partitionBy??[],m)!==R)return null;const C=Fi(c.name,r,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={}){St(U(i.baseWhere,i.where),l,t,"rankPage");const o=l.tables[t];if(!o)throw new g("INTERNAL",`unknown table: ${t}`);const r=o.rankIndexes?.find(B=>B.name===n);if(!r)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(await F(),!await Ke(t,r))return{continueCursor:null,isDone:!0,page:[]};const u=ye(t,r.name),h=r.sortBy.map((B,se)=>ge(se)),y=Math.max(1,Math.min(1e3,Math.floor(i.take??100))),p=U(i.baseWhere,i.where),E=mt(r,p),w=xi(r,h),R=e.join(w.flatMap(B=>Zt(c,{direction:B.direction,field:B.column,nullable:B.nullable})),e`, `),S=[];typeof i.partitionKey=="string"?S.push(e`${e.identifier("__partition__")} = ${i.partitionKey}`):E&&S.push(e`${e.identifier("__partition__")} = ${ke(r.partitionBy??[],E)}`);const m=Pn(i);if(m!==void 0){const B=Ui(c.name,w,m);B!==void 0&&S.push(B)}const C=fe([Ie,"__partition__",...h]);let L=e`SELECT ${C} FROM ${e.identifier(u)}`;S.length>0&&(L=e`${L} WHERE ${e.join(S,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 Pi(_,c,o,t,P);let pe=null;const V=k.at(-1);if(O&&V!==void 0){const B=[V.__partition__,...h.map(se=>V[se]),V[Ie]];pe=Hi(B)}return{continueCursor:pe,isDone:!O,page:Q}},async replace(t,n,i,o){Ve("replace",i);const r=await $e(t);if(!r)throw new g("INTERNAL",`document not found: ${n}`);const d=l.tables[r];if(!d)throw new g("INTERNAL",`document not found: ${n}`);const u=await Ne(r,n);if(u===void 0)throw new g("INTERNAL",`document not found: ${n}`);const y=xn(l,r,"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 S=Ye(d,R,{previous:()=>y??z(d,u)??void 0,supplied:i,trusted:o?.allowExplicitId===!0});nt(c.name,S),Y(r,"before","update")&&await X("before","update",{doc:{...S},id:n,op:"update",previous:y,table:r}),await be(r),await Me(r);const m=Object.keys(d.shape),C=e.join([e`${e.identifier("_creationTime")} = ${w}`,...m.map(L=>e`${e.identifier(L)} = ${ce(d,L,S[L]??null)}`)],e`, `);await re(r,async L=>(await je(r,"UPDATE",C,u,L),!0),async L=>[...await _e(r,y,S,L),...await oe(r,n,y,S)],n,we(r,n,"update",S)),await me(r,n,async()=>{await Ee(r,n,{document:S,previous:y,written:Ge(u,w)}),Y(r,"after","update")&&await X("after","update",{doc:S,id:n,op:"update",previous:y,table:r})})}};return ht={db:G,scheduler:an},G};export{Co as createSqlCtxDb,Mo as decodeGlobalRow,io as readSqlCdcChangedTables,Ao as readSqlCdcChanges,on as readSqlCdcFloor,Yi as runSqlCdcMigration,Qi as sweepSqlCdcRetention};
|
|
@@ -0,0 +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-C4_8w8pO.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-ChIYvWnI.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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/sql-store",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.227",
|
|
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.
|
|
54
|
+
"@lunora/shard-engine": "1.0.0-alpha.179",
|
|
55
55
|
"@lunora/wire": "1.0.0-alpha.6",
|
|
56
56
|
"drizzle-orm": "1.0.0-rc.5"
|
|
57
57
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as m}from"@lunora/errors";import{needsWireEncoding as O,encodeWire as _,decodeWire as I}from"@lunora/wire";import{sql as u}from"drizzle-orm";import{runSqlGlobalTableMigrations as w}from"./runSqlGlobalTableMigrations-C4_8w8pO.mjs";import{t as A}from"./post-commit-error-hh-zQyjO.mjs";import{r as S,d as T,M as h,q as y}from"./sql-exec-ChIYvWnI.mjs";const L=200,g=(t,o)=>{const r=e=>t.tables[e]?.shardMode?.kind==="global";return o&&o.length>0?o.filter(e=>r(e)):Object.keys(t.tables).filter(e=>r(e))},$=t=>O(t)?_(t):t,J=async function*(t,o,r,e){const s=g(o,e.tables),n=e.batchSize??L;await w(t,o,r);for(const i of s){const d=o.tables[i];let c,l=!0;for(;l;){const f=await S(t,r,i,c,n);for(const p of f)yield{doc:$(T(d,p)),table:i};const a=f.at(-1);a!==void 0&&(c=String(a.id)),l=f.length===n}}},k=t=>t?._meta?.column?.notNull===!1,C=(t,o)=>{const r=new Set;for(const[e,s]of Object.entries(t.shape)){if(o[e]!==null||s.kind!=="optional"||k(s))continue;const n=s._meta?.inner;k(n)||r.add(e)}return r.size===0?o:Object.fromEntries(Object.entries(o).filter(([e])=>!r.has(e)))},F=new Set(["_creationTime","_id"]),M=(t,o)=>Object.keys(o).find(r=>!F.has(r)&&!Object.hasOwn(t.shape,r)),D=t=>{const o=t._id,r=t._creationTime;if(o!==void 0&&(typeof o!="string"||o===""))return'field "_id": must be a non-empty string';if(r!==void 0&&(typeof r!="number"||!Number.isFinite(r)))return'field "_creationTime": must be a finite number'},x=(t,o,r)=>{const e=t.tables[o];if(!e)return`unknown table: ${o}`;const s=M(e,r);if(s!==void 0)return`unexpected field "${s}": not declared in table "${o}"`;const n=D(r);if(n!==void 0)return n;for(const[i,d]of Object.entries(e.shape)){const c=r[i],l=d.kind==="optional";if(c===void 0&&l)continue;const f=d.parse;if(typeof f=="function")try{f(c)}catch(a){const p=a instanceof Error?a.message:String(a);return`field "${i}": ${p}`}}},E=async(t,o,r,e,s)=>r?(await y(r,o,u`SELECT 1 FROM ${u.identifier(e)} WHERE ${u.identifier("id")} = ${s} LIMIT 1`)).length>0:await t.get(e,s)!==null,j=async(t,o,r,e,s,n)=>{try{return{existingId:await E(t,o,r,e,s)?s:void 0}}catch(i){const{body:d}=m(i,{fallbackCode:"PROBE_FAILED"});return{error:{code:d.code,line:n,message:d.message,table:e}}}},b=(t,o,r)=>{const e=t.held.get(o)??new Set;e.add(r),t.held.set(o,e)},N=async(t,o,r)=>{const e=[...r.keys()],s=new Map;let n=[],i=h;const d=async()=>{if(n.length===0)return;const c=await y(t,o,u.join(n,u` UNION ALL `));for(const l of c)b({held:s},e[Number(l.slot)],String(l.id));n=[],i=h};try{for(const[c,l]of e.entries()){const f=[...r.get(l)];for(let a=0;a<f.length;){const p=f.slice(a,a+i);n.push(u`SELECT ${u.raw(String(c))} AS slot, ${u.identifier("id")} FROM ${u.identifier(l)} WHERE ${u.identifier("id")} IN (${u.join(p.map(R=>u.param(R)),u`, `)})`),a+=p.length,i-=p.length,i===0&&await d()}}await d()}catch(c){const{body:l}=m(c,{fallbackCode:"PROBE_FAILED"});return{failure:{code:l.code,message:l.message}}}return{held:s}},B=(t,o,r,e)=>"failure"in t?{error:{...t.failure,line:e,table:o}}:{existingId:t.held.get(o)?.has(r)===!0?r:void 0},W=t=>g(t).some(o=>Object.keys(t.tables[o]?.triggerMap??{}).length>0),v=async(t,o,r,e,s,n)=>{try{if(e!==void 0){const i={...r};return delete i._id,await t.replace(o,e,i,{allowExplicitId:!0}),{kind:"replaced"}}return await t.insert(o,r,{allowExplicitId:!0}),{inserted:o,kind:"inserted"}}catch(i){const{body:d}=m(i,{fallbackCode:e===void 0?"INSERT_FAILED":"REPLACE_FAILED"}),c=e??(typeof r._id=="string"?r._id:void 0),l=c!==void 0&&A(i,o,c),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',a=l?`${d.message} (row "${c}" committed before this failure, so its triggers or companion writes may not have completed; ${f})`:d.message;return{committed:l,error:{code:d.code,line:s,message:a,table:o},kind:"error"}}},G=(t,o,r,e)=>{const{doc:s,table:n}=r;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(t.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"}};let i;try{i=I(s)}catch(c){return{kind:"settled",outcome:{committed:!1,error:{code:"BAD_ROW",line:e,message:c instanceof Error?c.message:String(c),table:n},kind:"error"}}}i=C(t.tables[n],i);const d=x(t,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}},P=async(t,o,r,e,s,n)=>{const{decoded:i,explicitId:d,line:c,table:l}=s;try{if(!await E(t,o,r,l,d))return}catch{return}return e.snapshot!==void 0&&"held"in e.snapshot&&b(e.snapshot,l,d),n==="replace"?v(t,l,i,d,c,n):{kind:"conflict"}},H=async(t,o,r,e,s)=>{const{decoded:n,explicitId:i,line:d,table:c}=e;let l={existingId:void 0};if(i!==void 0&&(l=s.snapshot===void 0?await j(t,o,r.exec,c,i,d):B(s.snapshot,c,i,d)),"error"in l)return{committed:!1,error:l.error,kind:"error"};const{existingId:f}=l;if(f!==void 0&&r.onConflict!=="replace")return{kind:"conflict"};const a=await v(t,c,n,f,d,r.onConflict);if(i===void 0)return a;const{snapshot:p}=s;return p!==void 0&&"held"in p&&(a.kind==="inserted"||a.kind==="replaced"||a.kind==="error"&&a.committed)&&b(p,c,i),a.kind==="error"&&!a.committed&&a.error.code==="CONFLICT"&&f===void 0?await P(t,o,r.exec,s,{...e,explicitId:i},r.onConflict)??a:a},z=async(t,o,r,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 w(t,o,r)}catch(i){const{body:d}=m(i,{fallbackCode:"PROBE_FAILED"});return{failure:{code:d.code,message:d.message}}}return s?N(t,r,n):void 0},Q=async(t,o,r,e)=>{const s=[],n={};let i=0,d=0,c=(e.startLine??1)-1;const l=e.rows.map(a=>(c+=1,G(o,e.dryRun===!0,a,a.line??c))),f={};e.exec&&e.dryRun!==!0&&(f.snapshot=await z(e.exec,o,r,l,!W(o)));for(const a of l){const p=a.kind==="settled"?a.outcome:await H(t,r,e,a,f);switch(p.kind){case"conflict":{i+=1;break}case"error":{s.push(p.error);break}case"inserted":{n[p.inserted]=(n[p.inserted]??0)+1;break}case"replaced":{d+=1;break}}}return{conflicts:i,errors:s,inserted:n,replaced:d}};export{J as exportSqlGlobalRows,Q as importSqlGlobalRows,g as selectGlobalTables};
|