@lunora/sql-store 1.0.0-alpha.237 → 1.0.0-alpha.239

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 CHANGED
@@ -120,6 +120,41 @@ interface ImportGlobalArgs {
120
120
  rows: ReadonlyArray<ExportRow>;
121
121
  startLine?: number;
122
122
  }
123
+ type RowOutcome = {
124
+ committed: boolean;
125
+ error: ImportError;
126
+ kind: "error";
127
+ } | {
128
+ inserted: string;
129
+ kind: "inserted";
130
+ } | {
131
+ kind: "absent";
132
+ } | {
133
+ kind: "checked";
134
+ } | {
135
+ kind: "conflict";
136
+ } | {
137
+ kind: "deleted";
138
+ } | {
139
+ kind: "replaced";
140
+ } | {
141
+ kind: "skip";
142
+ };
143
+ type ReadyRow = {
144
+ decoded: Record<string, unknown>;
145
+ explicitId: string | undefined;
146
+ kind: "ready";
147
+ line: number;
148
+ table: string;
149
+ };
150
+ type PreparedRow = ReadyRow | {
151
+ kind: "delete";
152
+ line: number;
153
+ row: ExportRow;
154
+ } | {
155
+ kind: "settled";
156
+ outcome: RowOutcome;
157
+ };
123
158
  /**
124
159
  * Import rows into `.global()` tables via the schema-aware writer. The
125
160
  * writer rejects unknown ids on `insert` (the writer assigns one when `_id` is
@@ -132,6 +167,13 @@ interface ImportGlobalArgs {
132
167
  * because a trigger can create or delete rows in the table mid-import.
133
168
  */
134
169
  declare const importSqlGlobalRows: (writer: DatabaseWriterLike, schema: SchemaLike, dialect: SqlDialect, args: ImportGlobalArgs) => Promise<ImportResult>;
170
+ /**
171
+ * The shape check an import runs on one `.global()` row before any query — routing, `doc` envelope, wire decode,
172
+ * unset optionals, validation — exposed for a staged replace (`@lunora/d1`'s `import-staging.ts`), so a row it
173
+ * stages is refused exactly when an ordinary import would refuse it. `ready` carries the decoded document; a row
174
+ * of a shard-local table settles as `skip`, and a malformed one as an `error` outcome.
175
+ */
176
+ declare const prepareGlobalImportRow: (schema: SchemaLike, row: ExportRow, line: number) => PreparedRow;
135
177
  /**
136
178
  * The `UPDATE` that fills the rows a column predates, for a column a SQL migration file adds. It is the one the
137
179
  * provisioner writes when it adds the same column itself, so a file that runs first does not leave NULL rows that
@@ -721,4 +763,18 @@ type ImportGlobalArgs,
721
763
  * This package is internal: consumers depend on `@lunora/d1` or
722
764
  * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
723
765
  */
724
- type ImportResult, type QueryTimer, type ReadGlobalTablePageOptions, SEARCH_STATE_TABLE, type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, SqlQueryTimeoutError, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, exportSqlGlobalRows, facetSqlGlobalColumn, globalColumnBackfill, importSqlGlobalRows, listSqlGlobalTables, migrateSearchState, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, readSqlGlobalTablePage, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, selectGlobalTables, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };
766
+ type ImportResult,
767
+ /**
768
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
769
+ * shared by Lunora's `.global()` table backends.
770
+ *
771
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
772
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
773
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
774
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
775
+ * whose `broadcast` hook drives live queries regardless of engine.
776
+ *
777
+ * This package is internal: consumers depend on `@lunora/d1` or
778
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
779
+ */
780
+ type PreparedRow as PreparedGlobalImportRow, type QueryTimer, type ReadGlobalTablePageOptions, SEARCH_STATE_TABLE, type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, SqlQueryTimeoutError, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, exportSqlGlobalRows, facetSqlGlobalColumn, globalColumnBackfill, importSqlGlobalRows, listSqlGlobalTables, migrateSearchState, prepareGlobalImportRow, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, readSqlGlobalTablePage, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, selectGlobalTables, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };
package/dist/index.d.ts CHANGED
@@ -120,6 +120,41 @@ interface ImportGlobalArgs {
120
120
  rows: ReadonlyArray<ExportRow>;
121
121
  startLine?: number;
122
122
  }
123
+ type RowOutcome = {
124
+ committed: boolean;
125
+ error: ImportError;
126
+ kind: "error";
127
+ } | {
128
+ inserted: string;
129
+ kind: "inserted";
130
+ } | {
131
+ kind: "absent";
132
+ } | {
133
+ kind: "checked";
134
+ } | {
135
+ kind: "conflict";
136
+ } | {
137
+ kind: "deleted";
138
+ } | {
139
+ kind: "replaced";
140
+ } | {
141
+ kind: "skip";
142
+ };
143
+ type ReadyRow = {
144
+ decoded: Record<string, unknown>;
145
+ explicitId: string | undefined;
146
+ kind: "ready";
147
+ line: number;
148
+ table: string;
149
+ };
150
+ type PreparedRow = ReadyRow | {
151
+ kind: "delete";
152
+ line: number;
153
+ row: ExportRow;
154
+ } | {
155
+ kind: "settled";
156
+ outcome: RowOutcome;
157
+ };
123
158
  /**
124
159
  * Import rows into `.global()` tables via the schema-aware writer. The
125
160
  * writer rejects unknown ids on `insert` (the writer assigns one when `_id` is
@@ -132,6 +167,13 @@ interface ImportGlobalArgs {
132
167
  * because a trigger can create or delete rows in the table mid-import.
133
168
  */
134
169
  declare const importSqlGlobalRows: (writer: DatabaseWriterLike, schema: SchemaLike, dialect: SqlDialect, args: ImportGlobalArgs) => Promise<ImportResult>;
170
+ /**
171
+ * The shape check an import runs on one `.global()` row before any query — routing, `doc` envelope, wire decode,
172
+ * unset optionals, validation — exposed for a staged replace (`@lunora/d1`'s `import-staging.ts`), so a row it
173
+ * stages is refused exactly when an ordinary import would refuse it. `ready` carries the decoded document; a row
174
+ * of a shard-local table settles as `skip`, and a malformed one as an `error` outcome.
175
+ */
176
+ declare const prepareGlobalImportRow: (schema: SchemaLike, row: ExportRow, line: number) => PreparedRow;
135
177
  /**
136
178
  * The `UPDATE` that fills the rows a column predates, for a column a SQL migration file adds. It is the one the
137
179
  * provisioner writes when it adds the same column itself, so a file that runs first does not leave NULL rows that
@@ -721,4 +763,18 @@ type ImportGlobalArgs,
721
763
  * This package is internal: consumers depend on `@lunora/d1` or
722
764
  * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
723
765
  */
724
- type ImportResult, type QueryTimer, type ReadGlobalTablePageOptions, SEARCH_STATE_TABLE, type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, SqlQueryTimeoutError, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, exportSqlGlobalRows, facetSqlGlobalColumn, globalColumnBackfill, importSqlGlobalRows, listSqlGlobalTables, migrateSearchState, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, readSqlGlobalTablePage, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, selectGlobalTables, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };
766
+ type ImportResult,
767
+ /**
768
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
769
+ * shared by Lunora's `.global()` table backends.
770
+ *
771
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
772
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
773
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
774
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
775
+ * whose `broadcast` hook drives live queries regardless of engine.
776
+ *
777
+ * This package is internal: consumers depend on `@lunora/d1` or
778
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
779
+ */
780
+ type PreparedRow as PreparedGlobalImportRow, type QueryTimer, type ReadGlobalTablePageOptions, SEARCH_STATE_TABLE, type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, SqlQueryTimeoutError, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, exportSqlGlobalRows, facetSqlGlobalColumn, globalColumnBackfill, importSqlGlobalRows, listSqlGlobalTables, migrateSearchState, prepareGlobalImportRow, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, readSqlGlobalTablePage, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, selectGlobalTables, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportSqlGlobalRows as l,importSqlGlobalRows as r,selectGlobalTables as a}from"./packem_shared/exportSqlGlobalRows-BMOYQhJf.mjs";import{g as s}from"./packem_shared/column-provisioning-DsVyt-k5.mjs";import{createSqlCtxDb as i,readSqlCdcChangedTables as n,readSqlCdcChanges as d,readSqlCdcFloor as q,runSqlCdcMigration as c,sweepSqlCdcRetention as m}from"./packem_shared/createSqlCtxDb-CBGjLZPE.mjs";import{runSqlGlobalTableMigrations as f}from"./packem_shared/runSqlGlobalTableMigrations-B00G2E1V.mjs";import{runSqlAggregateMigrations as p,runSqlRankMigrations as x}from"./packem_shared/runSqlAggregateMigrations-l-lqWvIq.mjs";import{b as T,r as u}from"./packem_shared/ctx-db-search-C-Gs6PkL.mjs";import{S as G,m as M}from"./packem_shared/ctx-db-search-state-CcUMouNm.mjs";import{facetSqlGlobalColumn as h,listSqlGlobalTables as A,readSqlGlobalTablePage as _}from"./packem_shared/facetSqlGlobalColumn-DF3p8q4R.mjs";import{DEFAULT_QUERY_TIMEOUT_MS as k,SqlQueryTimeoutError as B}from"./packem_shared/DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import{d as U,e as y,s as F,a as I,t as L}from"./packem_shared/value-codec-DhzLXsqv.mjs";import{d as Q}from"./packem_shared/sql-exec-j9zVLMn5.mjs";export{k as DEFAULT_QUERY_TIMEOUT_MS,G as SEARCH_STATE_TABLE,B as SqlQueryTimeoutError,T as backfillSqlSearchIndexes,i as createSqlCtxDb,U as decodeBigint,Q as decodeGlobalRow,y as effectiveColumnKind,l as exportSqlGlobalRows,h as facetSqlGlobalColumn,s as globalColumnBackfill,r as importSqlGlobalRows,A as listSqlGlobalTables,M as migrateSearchState,n as readSqlCdcChangedTables,d as readSqlCdcChanges,q as readSqlCdcFloor,_ as readSqlGlobalTablePage,p as runSqlAggregateMigrations,c as runSqlCdcMigration,f as runSqlGlobalTableMigrations,x as runSqlRankMigrations,u as runSqlSearchMigrations,a as selectGlobalTables,F as sqliteDecode,I as sqliteEncode,m as sweepSqlCdcRetention,L as tryJsonParse};
1
+ import{exportSqlGlobalRows as r,importSqlGlobalRows as l,prepareGlobalImportRow as a,selectGlobalTables as t}from"./packem_shared/exportSqlGlobalRows-DZwklEXx.mjs";import{g as S}from"./packem_shared/column-provisioning-DsVyt-k5.mjs";import{createSqlCtxDb as n,readSqlCdcChangedTables as d,readSqlCdcChanges as m,readSqlCdcFloor as q,runSqlCdcMigration as b,sweepSqlCdcRetention as c}from"./packem_shared/createSqlCtxDb-PQzIlvAE.mjs";import{runSqlGlobalTableMigrations as f}from"./packem_shared/runSqlGlobalTableMigrations-B00G2E1V.mjs";import{runSqlAggregateMigrations as x,runSqlRankMigrations as C}from"./packem_shared/runSqlAggregateMigrations-l-lqWvIq.mjs";import{b as u,r as G}from"./packem_shared/ctx-db-search-C-Gs6PkL.mjs";import{S as R,m as M}from"./packem_shared/ctx-db-search-state-CcUMouNm.mjs";import{facetSqlGlobalColumn as w,listSqlGlobalTables as A,readSqlGlobalTablePage as _}from"./packem_shared/facetSqlGlobalColumn-DF3p8q4R.mjs";import{DEFAULT_QUERY_TIMEOUT_MS as B,SqlQueryTimeoutError as D}from"./packem_shared/DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import{d as U,e as y,s as F,a as L,t as P}from"./packem_shared/value-codec-DhzLXsqv.mjs";import{d as v}from"./packem_shared/sql-exec-j9zVLMn5.mjs";export{B as DEFAULT_QUERY_TIMEOUT_MS,R as SEARCH_STATE_TABLE,D as SqlQueryTimeoutError,u as backfillSqlSearchIndexes,n as createSqlCtxDb,U as decodeBigint,v as decodeGlobalRow,y as effectiveColumnKind,r as exportSqlGlobalRows,w as facetSqlGlobalColumn,S as globalColumnBackfill,l as importSqlGlobalRows,A as listSqlGlobalTables,M as migrateSearchState,a as prepareGlobalImportRow,d as readSqlCdcChangedTables,m as readSqlCdcChanges,q as readSqlCdcFloor,_ as readSqlGlobalTablePage,x as runSqlAggregateMigrations,b as runSqlCdcMigration,f as runSqlGlobalTableMigrations,C as runSqlRankMigrations,G as runSqlSearchMigrations,t as selectGlobalTables,F as sqliteDecode,L as sqliteEncode,c as sweepSqlCdcRetention,P as tryJsonParse};
@@ -0,0 +1,7 @@
1
+ import{LunoraError as T}from"@lunora/errors";import{m as Tn,q as vn}from"./ctx-db-search-state-CcUMouNm.mjs";import{c as In,r as An,a as Cn,A as Ln,C as bn,R as Mn,u as Nn,d as qn,I as On,x as kn,e as Dn}from"./ctx-db-search-C-Gs6PkL.mjs";import{throwingScheduler as Bn,describeRelationWrites as Wn,CDC_LOG_TABLE as W,cdcForkedError as Fn,cursorBelowRetainedFloor as xn,cdcTrimmedError as Un,serverInList as Pn,assertNoExplicitUndefined as Ye,hasTrigger as Hn,runRowValidators as Xe,assertFlatPredicate as gt,mergeWhere as x,rankTableName as Ee,sortColumnName as me,resolveRankPartition as Tt,encodePartitionKey as Oe,resolveRankSeekTuple as Kn,RANK_TIEBREAK as Te,CountRlsUnsupportedError as vt,compileWhereSql as ee,ConflictError as ne,patchDependsOnRow as jn,normalizeIdStructurally as Gn,applyInsertDefaults as Vn,assertValidClientId as Yn,assertStorableRowId as Xn,aggregateSqlFunction as pe,softDeleteScope as ke,findManyPage as Qn,resolveWith as zn,relationHooks as Jn,applySelect as Zn,NotFoundError as ei,applyOnDelete as ti,normalizeCountArgument as ni,selectIndexForCount as ii,encodeAggregateKey as te,aggregateTableName as se,selectIndexForAggregate as ri,readAggregateValue as Qe,runTriggers as oi,matchesRankStaticWhere as It,nullsOrderSuffix as At,nullsFirstOf as Ct,rankPivotConditionSql as Xt,CURSOR_PREFIX as si,resolvePatch as ai,stripReservedPatchFields as ci,assertPatchAllowed as di,resolveRelationPredicates as li,selectIndexForGroupBy as ui,composeReadPredicate as fi,fanOutScalarCounts as wi,matchesStaticWhere as ze,coerceAggregateNumber as Je,whereOfFilter as hi,isPushableWhere as $i,tiebreakDirectionFor as _i,foldAggregateTally as Lt,CDC_LOG_TABLE_SEQ_INDEX as Ei,NotUniqueError as pi,WORKERD_SQLITE_LIMITS as yi,unionAll as Ri}from"@lunora/shard-engine";import{parseWire as mi,needsWireEncoding as Qt,encodeWire as zt,decodeWire as Si}from"@lunora/wire";import{sql as e,SQL as gi}from"drizzle-orm";import{p as bt,g as Mt,q as M,b as j,c as Jt,i as Ti,h as vi,j as Ii,k as Q,s as ae,e as K,l as Nt,t as Ai,m as Ze,n as We,o as ct,O as ye,u as qt,a as Ot,v as kt,w as Dt,x as Ci,B as et,y as Bt,f as Wt,M as Li}from"./sql-exec-j9zVLMn5.mjs";import{d as Nr}from"./sql-exec-j9zVLMn5.mjs";import{runSqlGlobalTableMigrations as bi}from"./runSqlGlobalTableMigrations-B00G2E1V.mjs";import{runSqlAggregateMigrations as Mi,runSqlRankMigrations as Ni}from"./runSqlAggregateMigrations-l-lqWvIq.mjs";import{a as Re}from"./post-commit-error-hh-zQyjO.mjs";import{withQueryTimeout as Ft,DEFAULT_QUERY_TIMEOUT_MS as xt,abandonedWork as tt,SqlQueryTimeoutError as qi}from"./DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import{s as Zt,e as dt}from"./value-codec-DhzLXsqv.mjs";const Ut=50,Oi=(o,a={})=>{const f=a.maxBatch??Ut,_=Number.isInteger(f)&&f>0?f:Ut,d=new Map;let E=!1;const v=async(N,C)=>{const g=[...C.keys()];for(let L=0;L<g.length;L+=_){const q=g.slice(L,L+_);try{const k=await o(N,q);for(const z of q){const V=k.get(z);for(const fe of C.get(z)??[])fe.resolve(V)}}catch(k){for(const z of q)for(const V of C.get(z)??[])V.reject(k)}}},l=()=>{E=!1;const N=[...d.entries()];d.clear();for(const[C,g]of N)v(C,g).catch(()=>{})};return{async load(N,C){return new Promise((g,L)=>{let q=d.get(N);q||(q=new Map,d.set(N,q));const k=q.get(C);k?k.push({reject:L,resolve:g}):q.set(C,[{reject:L,resolve:g}]),E||(E=!0,queueMicrotask(l))})}}},ki=new Set(["_id","id"]),Di=o=>{throw new T("INTERNAL",`no ORDER BY NULL placement for dialect "${String(o)}"`)},en=(o,a)=>{const f=a.direction==="desc"?"DESC":"ASC",_=a.nullable===!0,d=E=>e`${We(o,a.field)} ${e.raw(`${f}${E}`)}`;switch(o.name){case"mysql":{const E=d("");return!_||a.nulls===void 0?[E]:[e`(${We(o,a.field)} IS NULL) ${e.raw(a.nulls==="first"?"DESC":"ASC")}`,E]}case"postgres":return[d(_?At(Ct(a)):"")];case"sqlite":return[d(_&&a.nulls!==void 0?At(Ct(a)):"")];default:return Di(o.name)}},Bi=(o,a)=>{const f=o.flatMap(_=>en(a,_));if(!o.some(_=>ki.has(_.field))){const _=_i(o);f.push(e`${K("id")} ${e.raw(_==="desc"?"DESC":"ASC")}`)}return e.join(f,e`, `)},Pt=50,Wi=o=>{const a=o.detail??o["QUERY PLAN"];return typeof a=="string"?a:Object.values(o).map(String).join(" | ")},nt=(o,a,f,_)=>{for(const[d,E]of Ai(o)){if(E.serverDefault){d in a&&(f[d]=E.serverDefault({auth:_}));continue}E.onUpdateFn&&!(d in a)&&(f[d]=E.onUpdateFn())}},Fi=o=>o.shardMode===void 0||o.shardMode.kind==="global",le=o=>o==null?null:Number(o),xi=(o,a,f)=>f.map(_=>{const d={};for(const E of a){const v=o.shape[E];d[E]=Zt(_[E]??null,v&&dt(v))}return{key:d,value:le(_.value)}}),Ui=(o,a,f)=>[...o.partitionBy??[],...o.sortBy.map(d=>d.field),...o.where?Object.keys(o.where):[]].every(d=>kt(a,d)===kt(f,d)),tn=o=>o.length===1?o[0]:e`(${e.join(o,e` AND `)})`,ue=o=>e.join(o.map(a=>e`${e.identifier(a)}`),e`, `),Se=o=>e.join(o.map(a=>e`${a}`),e`, `),it=(o,a)=>{if(o==="postgres"){for(const[f,_]of Object.entries(a))if(typeof _=="string"&&_.includes("\0"))throw new T("BAD_REQUEST",`"${f}" holds a NUL character (U+0000), which a Postgres text column cannot store`)}},Fe=o=>o instanceof ArrayBuffer?new Uint8Array(o):Array.isArray(o)?Uint8Array.from(o):o,Pi=(o,a,f,_,d)=>{const E=[];for(let v=0;v<f.length+1;v+=1){const l=f[v],N=a.sortBy[v],C=v<f.length&&l!==void 0&&N!==void 0,g=N?.direction==="desc"?"desc":"asc",L=C?Xt(l,Fe(_[l]),g,!1):e`${e.identifier(Te)} < ${d}`;if(L===void 0)continue;const q=f.slice(0,v).map(k=>ct(o,e`${e.identifier(k)}`,Fe(_[k])));q.push(L),E.push(tn(q))}return E.length>0?e.join(E,e` OR `):e`1 = 0`},Hi=(o,a,f)=>{if(f.length!==a.length)return;const _=[];for(const[d,E]of a.entries()){const v=Xt(E.column,Fe(f[d]),E.direction,!0);if(v===void 0)continue;const l=[];for(let N=0;N<d;N+=1){const C=a[N];C!==void 0&&l.push(ct(o,e`${e.identifier(C.column)}`,Fe(f[N])))}l.push(v),_.push(tn(l))}return _.length===0?e`(1 = 0)`:e`(${e.join(_,e` OR `)})`},Ki=(o,a)=>{if(o.sortBy.length===0)throw new T("INTERNAL",`rankIndex "${o.name}" requires at least one "sortBy" column for stable pagination`);const f=[{column:"__partition__",direction:"asc",nullable:!1}];for(const[_,d]of o.sortBy.entries())f.push({column:a[_]??me(_),direction:d.direction,nullable:!0});return f.push({column:Te,direction:"asc",nullable:!1}),f},ji=async(o,a,f,_,d)=>{const v=[];for(let g=0;g<d.length;g+=50)v.push(d.slice(g,g+50));const l=await Promise.all(v.map(async g=>M(o,a,e`SELECT * FROM ${e.identifier(_)} WHERE ${e.identifier("id")} IN (${Se(g)})`))),N=new Map;for(const g of l)for(const L of g)N.set(L.id,L);const C=[];for(const g of d){const L=Q(f,N.get(g));L&&C.push(L)}return C},Gi=o=>{const a=o.map(E=>Zt(E,"bytes")),f=JSON.stringify(Qt(a)?zt(a):a),_=new TextEncoder().encode(f);let d="";for(const E of _)d+=String.fromCodePoint(E);return si+btoa(d)},nn=o=>{if(o===void 0)return!1;const a=dt(o);return a==="any"||a==="bigint"||a==="from"||a==="union"},st=(o,a,f)=>{if(nn(o.shape[a]))throw new T("BAD_REQUEST",`${f}: "${a}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Vi=(o,a,f,_)=>{for(const d of f)st(o,d,`groupBy(${a}, { by: [..."${d}"] })`);_.field!==void 0&&st(o,_.field,`groupBy(${a}, { agg: { op: "${_.op}", field: "${_.field}" } })`)},at="__cdc_sweep",De="__cdc_log_ts",rn="global",Yi=6e4,Xi=1e4,Qi=3e4;let Ht=0;const zi=async(o,a)=>{const{autoincrementPrimaryKey:f,key:_,real:d,text:E}=a.companionTypes;await j(o,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(W)} (${e.identifier("seq")} ${e.raw(f)}, ${e.identifier("ts")} ${e.raw(d)} NOT NULL, ${e.identifier("table")} ${e.raw(_)} NOT NULL, ${e.identifier("id")} ${e.raw(_)} NOT NULL, ${e.identifier("op")} ${e.raw(_)} NOT NULL, ${e.identifier("doc")} ${e.raw(E)})`);const v=a.indexKeyPrefix?.("string");await Jt(o,a,{columns:e`${v===void 0?e`${e.identifier("table")}`:e`${e.identifier("table")}(${e.raw(String(v))})`}, ${e.identifier("seq")}`,name:Ei,table:W,unique:!1}),await j(o,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(at)} (${e.identifier("id")} ${e.raw(_)} NOT NULL PRIMARY KEY, ${e.identifier("lease_until")} ${e.raw(d)} NOT NULL)`),await j(o,a,e`INSERT INTO ${e.identifier(at)} (${e.identifier("id")}, ${e.identifier("lease_until")}) VALUES (${rn}, ${0}) ${a.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${e.identifier("id")} = ${e.identifier("id")}`:e`ON CONFLICT(${e.identifier("id")}) DO NOTHING`}`)},Ji=async(o,a,f)=>{const _=e`UPDATE ${e.identifier(at)} SET ${e.identifier("lease_until")} = ${f+Yi} WHERE ${e.identifier("id")} = ${rn} AND ${e.identifier("lease_until")} <= ${f}`;if(a.supportsReturning)return(await M(o,a,e`${_} RETURNING ${e.identifier("id")}`)).length>0;const d=await j(o,a,_);return(a.affectedRows?a.affectedRows(d??{rowsAffected:0}):0)>0},Zi=async(o,a,f,_)=>{if(!await Ji(o,a,_))return;const d=_-f;let E=!0;try{const v=await Ti(o,a,W,De);v!=="valid"&&(v==="invalid"&&await vi(o,a,W,De),await Jt(o,a,{columns:e`${e.identifier("ts")}`,concurrently:!0,name:De,table:W,unique:!1}))}catch(v){E=!1,console.warn(`[@lunora/sql-store] changelog retention could not build "${De}"; sweeping without it.`,v)}E&&(await M(o,a,e`SELECT 1 AS ${e.identifier("hit")} FROM ${e.identifier(W)} WHERE ${e.identifier("ts")} <= ${d} LIMIT 1`)).length===0||await j(o,a,e`
2
+ DELETE FROM ${e.identifier(W)} WHERE ${e.identifier("seq")} IN (
3
+ SELECT ${e.identifier("seq")} FROM (
4
+ SELECT ${e.identifier("seq")} FROM ${e.identifier(W)} WHERE +${e.identifier("ts")} <= ${d} ORDER BY ${e.identifier("seq")} ASC LIMIT ${e.raw(String(Xi))}
5
+ ) AS ${e.identifier("expired")}
6
+ )
7
+ `)},on=async(o,a)=>{const f=await M(o,a,e`SELECT MIN(${e.identifier("seq")}) AS ${e.identifier("seq")} FROM ${e.identifier(W)}`),_=Number(f[0]?.seq??Number.NaN);return Number.isFinite(_)?_:void 0},er=async(o,a)=>{if(a.name!=="sqlite")return;const f=await M(o,a,e`SELECT ${e.identifier("seq")} AS ${e.identifier("seq")} FROM ${e.identifier("sqlite_sequence")} WHERE ${e.identifier("name")} = ${W}`),_=Number(f[0]?.seq??Number.NaN);return Number.isFinite(_)?_:0},tr=o=>JSON.stringify(Qt(o)?zt(o):o),nr=(o,a,f,_,d)=>e`INSERT INTO ${e.identifier(W)} (${e.identifier("ts")}, ${e.identifier("table")}, ${e.identifier("id")}, ${e.identifier("op")}, ${e.identifier("doc")}) VALUES (${o}, ${a}, ${f}, ${_}, ${d===void 0?null:tr(d)})`,sn=1e4,ir=1e3,rr=(o,a,f)=>{let _=a;for(const[d,E]of o.entries()){const v=Number(E.seq);if(v>_+1&&Number(E.ts)>f)return o.slice(0,d);_=v}return o},Lr=async(o,a,f)=>{const _=a.sinceSeq??0,d=Math.max(1,Math.min(a.limit??1e3,1e4)),E=await on(o,f),v=await er(o,f);if(v!==void 0&&_>v)throw Fn(v,_,"global");if(E!==void 0&&xn(E,_))throw Un(E,_,"global");const l=await M(o,f,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(W)} WHERE seq > ${_} ORDER BY seq ASC LIMIT ${e.raw(String(d))}`),C=(f.name==="sqlite"?l:rr(l,_,(a.now??Date.now())-sn)).map(g=>{const{doc:L}=g,q={id:String(g.id),op:String(g.op),seq:Number(g.seq),table:String(g.table),ts:Number(g.ts)};return typeof L=="string"?{...q,doc:mi(L)}:q});return{changes:C,cursor:C.at(-1)?.seq??_}},Kt=(o,a)=>{const f=e.identifier(W),_=e`(SELECT MIN(v.seq) FROM ${f} v WHERE v.seq > ${o} AND v.seq - 1 > ${o} AND v.ts > ${a} AND NOT EXISTS (SELECT 1 FROM ${f} p WHERE p.seq = v.seq - 1))`;return e`${_} AS ${e.identifier("gap")}, (SELECT MAX(q.seq) FROM ${f} q WHERE q.seq > ${o} AND q.seq < ${_}) AS ${e.identifier("below")}`},jt=(o,a,f)=>{const _=Number(a?.gap??Number.NaN);if(!Number.isFinite(_))return o;const d=Number(a?.below??Number.NaN);return Math.min(o,Number.isFinite(d)?d:f)},or=o=>{const a=e.identifier(W),f=e.identifier("table");return e`SELECT ${f}, seq FROM (WITH RECURSIVE "t"("name") AS (SELECT MIN(${f}) FROM ${a} UNION ALL SELECT (SELECT MIN(${f}) FROM ${a} WHERE ${f} > "t"."name") FROM "t" WHERE "t"."name" IS NOT NULL) SELECT "t"."name" AS ${f}, (SELECT MAX(seq) FROM ${a} WHERE ${f} = "t"."name" AND seq > ${o}) AS seq FROM "t" WHERE "t"."name" IS NOT NULL) WHERE seq IS NOT NULL ORDER BY ${f}`},sr=async(o,a,f,_={})=>{const d=e.identifier(W),E=f.name!=="sqlite",v=(_.now??Date.now())-sn;if(_.cursorOnly){const L=e`GREATEST((SELECT MAX(seq) FROM ${d}) - ${e.raw(String(ir))}, ${a})`,q=await M(o,f,e`SELECT MAX(seq) AS seq${E?e`, ${Kt(L,v)}`:e``} FROM ${d}`),k=Number(q[0]?.seq??a);return{cursor:jt(Number.isFinite(k)?k:a,q[0],a),tables:[]}}const l=await M(o,f,E?e`SELECT ${e.identifier("table")} AS ${e.identifier("table")}, MAX(seq) AS seq, ${Kt(e`${a}`,v)} FROM ${d} WHERE seq > ${a} GROUP BY ${e.identifier("table")}`:or(a));let N=a;const C=[];for(const L of l){const q=Number(L.seq);Number.isFinite(q)&&q>N&&(N=q),C.push(String(L.table))}N=jt(N,l[0],a);const g=_.retained===!0?await on(o,f):void 0;return{cursor:N,tables:C,...g===void 0?{}:{floor:g}}},ar=/string or blob too big/iu,cr=/row is too big/iu,dr=(o,a)=>{const{code:f,errno:_}=a,d=a instanceof Error?a.message:"";switch(o.name){case"mysql":return _===1118||f==="ER_TOO_BIG_ROWSIZE"?"InnoDB's per-row ceiling — roughly 8 KB, half a 16 KB page, for the part of the row stored inline":void 0;case"postgres":return cr.test(d)?"the 8 KB heap page a tuple must fit once its wide columns have been TOASTed out":void 0;default:return ar.test(d)?"the storage engine's per-row ceiling (2 MB on D1)":void 0}},lr=(o,a,f)=>{const _=dr(o,a);if(_!==void 0)throw new T("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.`)},rt=16,Gt="__lunora_patch_if_match__",Vt=(o,a,f)=>{throw o.isUniqueViolation(a)?new ne(`unique constraint violation on "${f}"`,"unique"):(lr(o,a,f),a)},ur=o=>{const{code:a,errno:f}=o??{};return a==="40P01"||a==="40001"||f===1213||a==="ER_LOCK_DEADLOCK"},fr=o=>{throw ur(o)?new ne("the write's transaction was rolled back by a lock conflict with a concurrent write; retry it","occ"):o},ot=new WeakMap,Yt=new WeakMap,ce="superseded",wr=3e4,ge="__lunora_companion_fence",hr=(o,a,f,_,d)=>{const E=Math.max(1,Math.floor((Li-2)/_.length)),v=(C,g)=>{const L=o.name==="postgres"?e`CAST(${C} AS ${e.raw(g.type)})`:e`${C}`;return e`${L} AS ${e.identifier(g.name)}`},l=C=>e`SELECT ${e.join(C.map((g,L)=>v(g,_[L])),e`, `)}`,N=[];for(let C=0;C<d.length;C+=E){const g=d.slice(C,C+E).map(L=>l(L));N.push(e`INSERT INTO ${e.identifier(a)} (${ue(_.map(L=>L.name))}) SELECT * FROM (${Ri(g)}) AS ${e.identifier("__rows__")} WHERE EXISTS (SELECT 1 FROM ${e.identifier(ge)} WHERE ${f})`)}return N},de=(o,a,f)=>JSON.stringify([o,a,f]),Be=o=>JSON.stringify(o,(a,f)=>typeof f=="bigint"?`${String(f)}n`:f),$r=o=>{const a=Pn(o);return(f,_,d,E)=>_.some(v=>v instanceof gi)?Ii(o,f,_,d):a(f,_,d,E)},_r=o=>{const{crossShardCounter:a,crossShardReader:f,maxRelationKeys:_,schema:d}=o,E=Ft(o.exec,o.queryTimeoutMs??xt,o.queryTimer),v=o.exec.primary===void 0?E:Ft(o.exec.primary,o.queryTimeoutMs??xt,o.queryTimer),{dialect:l}=o,N={fieldRef:t=>We(l,t),rangeTypeGuard:(t,n)=>Ci(l,t,n),...l.name==="mysql"?{containsExpr:(t,n)=>{const i=bt(t);return i===void 0?e`LOCATE(${n}, ${t}) > 0`:e`LOCATE(${Mt("mysql",n)}, ${i}) > 0`}}:{},...l.name==="postgres"?{containsExpr:(t,n)=>{const i=bt(t);return i===void 0?e`strpos(${t}, ${n}) > 0`:e`strpos(${i}, ${Mt("postgres",n)}) > 0`}}:{},...l.name==="sqlite"?{}:{inList:$r(l.name)}},C=new WeakMap,g=t=>{const n=C.get(t);if(n!==void 0)return n;const i={...N,serialize:(r,s)=>Dt(l,s,r,c=>ae(t,s,c))};return C.set(t,i),i},L=(t,n)=>ct(l.name,t,n),q=t=>{const n=ue(t.columns),i=Se(t.values),r=$=>l.name==="mysql"?e`VALUES(${e.identifier($)})`:e`excluded.${e.identifier($)}`,s=$=>l.name==="postgres"?e`${e.identifier(t.table)}.${e.identifier($)}`:e`${e.identifier($)}`,c=e.join(Object.entries(t.set(r,s)).map(([$,y])=>e`${e.identifier($)} = ${y}`),e`, `),u=l.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${c}`:e`ON CONFLICT(${e.identifier(t.conflictKey)}) DO UPDATE SET ${c}`;return e`INSERT INTO ${e.identifier(t.table)} (${n}) VALUES (${i}) ${u}`},k=o.clock??(()=>Date.now()),z=o.idGenerator??(()=>crypto.randomUUID()),V=o.cdc??!1,fe=typeof o.cdcRetentionMs=="number"&&Number.isFinite(o.cdcRetentionMs)&&o.cdcRetentionMs>0?o.cdcRetentionMs:void 0,ve=o.auth??{identity:null,userId:null},we=(t,n,i,r)=>V?[nr(k(),t,n,i,r)]:[],an=async()=>{if(!V||fe===void 0)return;const t=k();if(!(t-Ht<Qi)){Ht=t;try{await Zi(E,l,fe,t)}catch{}}},cn=o.scheduler??Bn;let Ie=0;const ie=o.provisionScope??{},F=async()=>{const t=ot.get(ie);if(t)return t;const n=(async()=>{const i=o.exec;await bi(i,d,l),await Mi(i,d,l),await Ni(i,d,l),await Tn(i,l),await An(E,d,l),V&&await zi(i,l)})().catch(i=>{throw ot.delete(ie),i});return ot.set(ie,n),n},he=async t=>{if(typeof t!="string"||!Object.hasOwn(d.tables,t))throw new T("BAD_REQUEST",`ctx.db by-id write (table, id): "${t}" is not a table in this schema`);await F();const n=d.tables[t];return n!==void 0&&Fi(n)?t:void 0};let Ae=Yt.get(ie);Ae===void 0&&(Ae=new Map,Yt.set(ie,Ae));const U=Ae;let xe=0;const lt={},Ue=(t,n,i)=>{const r=(async()=>(await F(),await i(()=>U.get(t)?.run!==r)))(),s={definition:n,owner:lt,run:r,settled:!1};return r.then(c=>{c===ce&&U.get(t)===s?U.delete(t):s.settled=!0},()=>{U.get(t)===s&&U.delete(t)}).catch(()=>{}),U.set(t,s),r},ut=async(t,n,i)=>{const r=U.get(t);if(r===void 0)return await Ue(t,n,i);const s=r.definition===n;if(s&&(r.settled||r.owner===lt))return await r.run;if(r.settled)return await Ue(t,n,i);let c;const u=new Promise(y=>{c=setTimeout(y,wr,"stalled")}),$=await Promise.race([r.run,u]).finally(()=>{clearTimeout(c)});return $!=="stalled"&&s?$:U.get(t)===r?await Ue(t,n,i):await ut(t,n,i)},Pe=async(t,n,i)=>{const r=await ut(t,n,i);return r===ce?await Pe(t,n,i):r},ft=async(t,n)=>{const i=U.get(t),r=i?.settled===!0&&i.definition===n?await i.run:void 0;if(typeof r=="boolean")return r;U.delete(t),xe+=1},J=t=>{const n=d.tables[t];for(const i of n?.aggregateIndexes??[])U.delete(de("aggregate",t,i.name));for(const i of n?.rankIndexes??[])U.delete(de("rank",t,i.name))},dn=async(t,n)=>{const i=se(t,n);return(await M(E,l,l.tableExists(i))).length>0},wt=async t=>{const{key:n}=l.companionTypes,i=z();await j(E,l,e`CREATE TABLE IF NOT EXISTS ${e.identifier(ge)} (${e.identifier("name")} ${e.raw(n)} PRIMARY KEY, ${e.identifier("token")} ${e.raw(n)} NOT NULL)`),await j(E,l,q({columns:["name","token"],conflictKey:"name",set:s=>({token:s("token")}),table:ge,values:[t,i]}));const r=e`${e.identifier("name")} = ${t} AND ${e.identifier("token")} = ${i}`;return{guardedDelete:()=>e`DELETE FROM ${e.identifier(t)} WHERE EXISTS (SELECT 1 FROM ${e.identifier(ge)} WHERE ${r})`,stillHeld:async()=>(await M(E,l,e`SELECT 1 FROM ${e.identifier(ge)} WHERE ${r}`)).length>0,guardedInsertRows:(s,c)=>hr(l,t,r,s,c)}},ln=async(t,n,i)=>{const r=d.tables[t];if(!r||!await dn(t,n.name))return!1;const s=n.by??[],c=new Map;await Bt(E,l,r,t,R=>{if(n.where&&!ze(R,n.where))return;const m=te(s,R);Lt(c,m,n,R)});const u=se(t,n.name);if(i())return ce;const $=await wt(u);await j(E,l,$.guardedDelete());const{integer:y,key:p,real:h}=l.companionTypes,w=$.guardedInsertRows([{name:"__key__",type:p},{name:"__value__",type:h},{name:"__count__",type:y}],[...c].map(([R,m])=>[R,m.value,m.count]));return i()||await Wt(E,l,w),i()||!await $.stillHeld()?ce:!0},Ce=(t,n)=>Pe(de("aggregate",t,n.name),Be(n),i=>ln(t,n,i)),un=async(t,n,i,r,s)=>{const c=new Map;let u,$=!0;for(;$;){const y=u===void 0?r:[...r,e`${e.identifier("id")} > ${u}`],p=y.length>0?e` WHERE ${e.join(y,e` AND `)}`:e``,h=await M(s,l,e`SELECT ${e.identifier("id")}, ${K(i.field??"")} FROM ${e.identifier(n)}${p} ORDER BY ${e.identifier("id")} ASC LIMIT ${e.raw(String(et))}`);for(const w of Nt(t,h))Lt(c,"",i,w);u=h.at(-1)?.id,$=h.length===et}return c.get("")?.value??null},fn=async(t,n,i,r)=>{const s=n.field??"",c=[],u=d.tables[t],$=(w,R)=>Dt(l,w,R,m=>u?ae(u,w,m):Ze(m));for(const w of n.by??[]){const R=$(w,i[w]??null);c.push(R===null?e`${K(w)} IS NULL`:e`${K(w)} = ${R}`)}for(const[w,R]of Object.entries(n.where??{})){const m=R!==null&&typeof R=="object"&&!Array.isArray(R)?R.eq:R,S=$(w,m),A=We(l,w);c.push(S===null?e`${A} IS NULL`:e`${A} = ${S}`)}const y=c.length>0?e` WHERE ${e.join(c,e` AND `)}`:e``;if(u&&nn(u.shape[s]))return un(u,t,n,c,r);const p=pe(n.op),h=await M(r,l,e`SELECT ${e.raw(p)}(${K(s)}) AS ${e.identifier("value")} FROM ${e.identifier(t)}${y}`);return le(h[0]?.value)},wn=(t,n)=>e`DELETE FROM ${e.identifier(t)} WHERE ${e.identifier("__key__")} = ${n} AND ${e.identifier("__count__")} <= 0`,hn=async(t,n,i,r,s)=>{const c=se(t,n.name),{op:u}=n,$=n.field??"",y=i&&(!n.where||ze(i,n.where))?i:void 0,p=r&&(!n.where||ze(r,n.where))?r:void 0;if(!y&&!p)return[];if(u==="count"||u==="sum"||u==="avg"){const S=[],A=new Set,b=[];for(const[I,O]of[[y,-1],[p,1]]){if(!I)continue;const D=u==="count"?1:Je(I[$]);D!==void 0&&b.push({encoded:te(n.by??[],I),numeric:D,sign:O})}b.sort((I,O)=>I.encoded<O.encoded?-1:+(I.encoded>O.encoded));for(const{encoded:I,numeric:O,sign:D}of b)A.add(I),S.push(q({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(P,H)=>({__count__:e`${H("__count__")} + ${P("__count__")}`,__value__:u==="count"?e`${H("__value__")} + ${P("__value__")}`:e`COALESCE(${H("__value__")}, 0) + ${P("__value__")}`}),table:c,values:[I,D*O,D]}));for(const I of A)S.push(wn(c,I));return S}const h=[],w=[];let R,m;if(y){const S=te(n.by??[],y);R=S;const A=Je(y[$]),I=(await M(s,l,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(c)} WHERE ${e.identifier("__key__")} = ${S}`))[0],O=le(I?.value),D=(I?.count??0)-1;if(D<=0)h.push(e`DELETE FROM ${e.identifier(c)} WHERE ${e.identifier("__key__")} = ${S}`);else if(I&&A!==void 0&&O!==null&&A===O){const P=await fn(t,n,y,s);h.push(e`UPDATE ${e.identifier(c)} SET ${e.identifier("__value__")} = ${P}, ${e.identifier("__count__")} = ${D} WHERE ${e.identifier("__key__")} = ${S}`)}else h.push(e`UPDATE ${e.identifier(c)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${S}`)}if(p){const S=te(n.by??[],p);m=S;const A=Je(p[$]);if(A===void 0)w.push(q({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(b,I)=>({__count__:e`${I("__count__")} + 1`}),table:c,values:[S,null,1]}));else{const b=u==="min"?"MIN":"MAX";w.push(q({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(I,O)=>({__count__:e`${O("__count__")} + 1`,__value__:e`${e.raw(b)}(COALESCE(${O("__value__")}, ${I("__value__")}), ${I("__value__")})`}),table:c,values:[S,A,1]}))}}return R!==void 0&&m!==void 0&&m<R?[...w,...h]:[...h,...w]},Le=async t=>{const n=d.tables[t]?.aggregateIndexes;if(!(!n||n.length===0))for(const i of n)await Ce(t,i)},$e=async(t,n,i,r)=>{const s=d.tables[t]?.aggregateIndexes,c=[];if(!s||s.length===0)return c;for(const u of s)await ft(de("aggregate",t,u.name),Be(u))&&c.push(...await hn(t,u,n,i,r));return c},$n=async(t,n)=>{const i=Ee(t,n);return(await M(E,l,l.tableExists(i))).length>0},_n=async(t,n,i)=>{const r=d.tables[t];if(!r||!await $n(t,n.name))return!1;const s=Ee(t,n.name);if(i())return ce;const c=await wt(s);await j(E,l,c.guardedDelete());const u=l.companionTypes.key,$=[{name:"__id__",type:u},{name:"__partition__",type:u},...n.sortBy.map((h,w)=>{const R=r.shape[h.field];return{name:me(w),type:l.columnType(R?dt(R):void 0)}})];let y=[];const p=async()=>{const h=y;y=[],!(h.length===0||i())&&await Wt(E,l,c.guardedInsertRows($,h))};return await Bt(E,l,r,t,async h=>{if(n.where&&!It(h,n.where))return;const w=Oe(n.partitionBy??[],h),R=n.sortBy.map(m=>Ze(h[m.field]??null));y.push([h._id,w,...R]),y.length>=et&&await p()}),await p(),i()||!await c.stillHeld()?ce:!0},He=(t,n)=>Pe(de("rank",t,n.name),Be(n),i=>_n(t,n,i)),be=async t=>{const n=d.tables[t]?.rankIndexes;if(!(!n||n.length===0))for(const i of n)await He(t,i)},re=async(t,n,i,r)=>{const s=d.tables[t],c=s?.rankIndexes,u=[];if(!c||c.length===0)return u;const $=s?.softDeleteMode?.field,y=$===void 0||r===void 0?void 0:r[$],p=y!=null;for(const h of c){if(i!==void 0&&r!==void 0&&Ui(h,i,r)||!await ft(de("rank",t,h.name),Be(h)))continue;const R=Ee(t,h.name);if(i&&u.push(e`DELETE FROM ${e.identifier(R)} WHERE ${e.identifier("__id__")} = ${n}`),r&&!p){if(h.where&&!It(r,h.where))continue;const m=h.sortBy.map((I,O)=>me(O)),S=ue(["__id__","__partition__",...m]),A=Oe(h.partitionBy??[],r),b=h.sortBy.map(I=>Ze(r[I.field]??null));u.push(e`INSERT INTO ${e.identifier(R)} (${S}) VALUES (${Se([n,A,...b])})`)}}return u},En=(t,n,i)=>{const r=tt(n);if(r===void 0||!i.dispatched){J(t);return}r.then(()=>{i.batched||J(t)},()=>{J(t)}).catch(()=>{})},oe=async(t,n,i,r,s)=>{const c=d.tables[t],u=V||(c?.aggregateIndexes?.length??0)>0||(c?.rankIndexes?.length??0)>0,$=E.transaction===void 0||!u,y=async w=>{let R;try{R=await n(w)}catch(S){if(E.transaction===void 0&&S instanceof qi){J(t);const A=()=>{J(t)};tt(S)?.then(A,A).catch(()=>{})}throw S}if(!R)return!1;const m={batched:!1,dispatched:!1};try{$&&s.length>0&&await Ot(w,l,s);const S=$?await i(w):[...await i(w),...s];S.length>0&&(m.batched=w.batch!==void 0&&l.name==="sqlite",m.dispatched=!0,await Ot(w,l,S))}catch(S){throw E.transaction===void 0&&En(t,S,m),$&&await Re(t,r,async()=>{throw await Promise.resolve(),S}),S}return!0};let p;const h=xe;try{p=E.transaction!==void 0&&u?await E.transaction(y).catch(fr):await y(E),p&&xe!==h&&E.transaction!==void 0&&u&&J(t)}catch(w){const R=tt(w);if(R!==void 0){const m=async()=>{await Cn({dialect:l,exec:E,schema:d},t,r)};R.then(m,m).catch(()=>{})}throw w}return p&&await Re(t,r,an),p},_e=In({dialect:l,exec:E,schema:d}),ht=new Set;for(const[t,n]of Object.entries(d.tables))for(const i of Object.values(n.triggerMap??{}))ht.add(`${t} ${i.timing} ${i.op}`);const Y=(t,n,i)=>ht.has(`${t} ${n} ${i}`);let $t;const X=async(t,n,i)=>{if(Ie+=1,Ie>Pt)throw Ie-=1,new ne(`trigger recursion exceeded ${String(Pt)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await oi({ctx:$t,event:i,op:n,schema:d,tableName:i.table,timing:t})}finally{Ie-=1}},pn=async(t,n,i=E)=>{try{await j(i,l,n)}catch(r){Vt(l,r,t)}},Me=async(t,n)=>(await M(v,l,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} = ${n}`))[0],_t=async(t,n,i,r,s,c)=>{const u=e`${e.identifier(ye)}`,$=e.join([L(e`${e.identifier("id")}`,r.id),L(u,r[ye]??null),...s===void 0?[]:[e`(${s})`]],e` AND `),y=n==="UPDATE"?e`UPDATE ${e.identifier(t)} SET ${i}, ${u} = ${qt.sql(u)} WHERE ${$}`:e`DELETE FROM ${e.identifier(t)} WHERE ${$}`;try{if(l.supportsReturning)return(await M(c,l,e`${y} RETURNING ${e.identifier("id")}`)).length>0;const p=await j(c,l,y);return(l.affectedRows?l.affectedRows(p??{rowsAffected:0}):0)>0}catch(p){return Vt(l,p,t)}},Ke=async(t,n,i,r,s)=>{if(r!==void 0&&!await _t(t,n,i,r,void 0,s))throw new ne(`optimistic concurrency conflict on "${t}" — the row changed during this mutation; refetch and retry`,"occ")},je=(t,n=t?._creationTime)=>({_creationTime:n,[ye]:qt.value(t?.[ye])}),Et=async(t,n,i,r,s,c,u)=>{const $=Q(n,s);if(!$||s===void 0)throw new T("INTERNAL",`document not found: ${i}`);const y=ai(n,r,$),p={...$,...ci(y),_id:i};nt(n,y,p,ve);const h=Xe(n,p,{only:new Set(Object.keys(y)),previous:()=>$,tolerateStoredNull:!0});it(l.name,Object.fromEntries(Object.keys(y).map(S=>[S,h[S]]))),di(u,$,h),Y(t,"before","update")&&await X("before","update",{doc:{...h},id:i,op:"update",previous:$,table:t}),await Le(t),await be(t);const w=Object.keys(n.shape),R=e.join(w.map(S=>e`${e.identifier(S)} = ${ae(n,S,h[S]??null)}`),e`, `);if(await oe(t,async S=>await _t(t,"UPDATE",R,s,c,S),async S=>[...await $e(t,$,h,S),...await re(t,i,$,h)],i,we(t,i,"update",h)))return await _e(t,i,{document:h,previous:$,written:je(s)}),Y(t,"after","update")&&await X("after","update",{doc:h,id:i,op:"update",previous:$,table:t}),h},yn=(t,n,i,r)=>{const s=Object.keys(t.shape);return{columns:["id","_creationTime",...s],values:[n,i,...s.map(c=>ae(t,c,r[c]??null))]}},Rn=async(t,n,i,r)=>{const s=ui(n,i.op,i.field,r.by,r.where);if(!s||!await Ce(t,s.index))return;const u=se(t,s.index.name),$=Object.keys(s.partial);if($.length===(s.index.by??[]).length&&$.length>0){const p=te(s.index.by??[],s.partial),h=await M(E,l,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(u)} WHERE ${e.identifier("__key__")} = ${p}`);if(h.length===0)return[];const w=h[0];return[{key:{...s.partial},value:Qe(i.op,{count:w.count,value:le(w.value)})}]}return $.length>0?void 0:(await M(E,l,e`SELECT ${e.identifier("__key__")} AS ${e.identifier("key")}, ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(u)}`)).map(p=>{const h=p;return{key:Si(JSON.parse(h.key)),value:Qe(i.op,{count:h.count,value:le(h.value)})}})},pt=t=>{const n=d.tables[t]?.shardMode?.kind;return n==="shardBy"||n==="root"},yt=t=>{throw new T("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`)},mn=(t,n)=>{if(n?.relationMask!==void 0&&n.with!==void 0&&Object.keys(n.with).length>0)throw new T("MASK_UNSUPPORTED",`masking cannot follow a nested \`with\` across the cross-shard relation hop to "${t}" — the nested rows are hydrated on the serving shard, where the mask policy does not exist. Read the nested relation at its own (masked) call site instead.`);const i={};if(n?.relationBaseWhere)for(const r of Object.keys(d.tables)){const s=n.relationBaseWhere(r);s!==void 0&&(i[r]=s)}return{orderBy:n?.orderBy,relationPolicies:i,where:x(n?.baseWhere,n?.where),with:n?.with}},Ge=(t,n)=>pt(t)?f?f(t,mn(t,n)):yt(t):G.findMany(t,n),Ne=(t,n,i)=>li(t,{fetcher:Ge,maxRelationKeys:_,relationBaseWhere:i,schema:d,tableName:n}),Sn=Oi(async(t,n)=>{const i=await M(E,l,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} IN (${Se(n)})`),r=new Map;for(const s of i){const{id:c}=s;typeof c=="string"&&r.set(c,s)}return r}),Rt=async(t,n,i)=>{const{fetchLimit:r,limit:s,orderKeys:c,predicate:u}=await fi(n,i,{fetcher:Ge,maxRelationKeys:_,schema:d,tableName:t}),$=ee(u,g(n)),y=Bi(c,l);let p=e`SELECT * FROM ${e.identifier(t)}`;return $&&(p=e`${p} WHERE ${$}`),p=e`${p} ORDER BY ${y}`,r!==void 0&&(p=e`${p} LIMIT ${e.raw(String(r))}`),{limit:s,orderKeys:c,query:p}},gn=Wn(d);let mt;const St=async()=>{const{primary:t}=o.exec;if(t!==void 0)return await F(),mt??=_r({...o,exec:t,provisionScope:ie}),mt},G={relationWrites:gn,async cdcChangedTables(t,n){if(V)try{return await F(),await sr(E,t,l,{...n,now:k(),retained:fe!==void 0})}catch{return}},async aggregate(t,n){const i=d.tables[t];if(!i)throw new T("INTERNAL",`unknown table: ${t}`);if(await F(),pe(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 T("INTERNAL",`aggregate(${t}, { op: "${n.op}" }): "field" is required for non-count reducers`);const r=ke(i.softDeleteMode,void 0),s=x(x(n.baseWhere,n.where),r),c=await Ne(s,t,n.relationBaseWhere),u=c!==s;if(i.aggregateIndexes&&!n.baseWhere&&!u&&!r){const R=ri(i.aggregateIndexes,n.op,n.field,n.where);if(R&&await Ce(t,R.index)){const S=te(R.index.by??[],R.key),A=se(t,R.index.name),I=(await M(E,l,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(A)} WHERE ${e.identifier("__key__")} = ${S}`))[0];return Qe(n.op,I===void 0?void 0:{count:I.count,value:le(I.value)})}}st(i,n.field,`aggregate(${t}, { op: "${n.op}", field: "${n.field}" })`);const $=ee(c,g(i)),y=e.raw(pe(n.op)),p=e`SELECT ${y}(${K(n.field)}) AS ${e.identifier("value")} FROM ${e.identifier(t)}`,w=(await M(E,l,$?e`${p} WHERE ${$}`:p))[0]?.value;return w==null?null:Number(w)},async count(t,n){const i=d.tables[t];if(!i)throw new T("INTERNAL",`unknown table: ${t}`);await F();const r=ni(n);if(r.restrictsCounts)throw new vt(t);const s=ke(i.softDeleteMode,void 0),c=x(x(r.baseWhere,r.where),s),u=await Ne(c,t,r.relationBaseWhere),$=u!==c;if(i.aggregateIndexes&&!r.baseWhere&&!$&&!s){const w=ii(i.aggregateIndexes,r.where);if(w&&await Ce(t,w.index)){const m=te(w.index.by??[],w.key),S=se(t,w.index.name),A=await M(E,l,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")} FROM ${e.identifier(S)} WHERE ${e.identifier("__key__")} = ${m}`);return Number(A[0]?.value??0)}}const y=ee(u,g(i)),p=e`SELECT COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(t)}`,h=await M(E,l,y?e`${p} WHERE ${y}`:p);return Number(h[0]?.count??0)},async delete(t,n,i){const r=await he(t);if(!r)return;const s=d.tables[r];if(!s)return;const c=await Me(r,n);if(c===void 0)return;const u=Q(s,c),$=i?.hard===!0,y=!$&&s.softDeleteMode?s.softDeleteMode.field:void 0;if(!(y&&(!u||u[y]!==null&&u[y]!==void 0))){if(Y(r,"before","delete")&&await X("before","delete",{id:n,op:"delete",previous:u??void 0,table:r}),i?.skipOnDelete!==!0&&await ti({deletedId:n,deletedReference:p=>u?.[p],findHolders:async(p,h,w,R)=>{if(d.tables[p]?.shardMode?.kind==="shardBy")throw new T("INTERNAL",`cross-backend cascade from global '${r}' into shardBy '${p}' is not supported — would require Query Coordinator fan-out across shards`);return(await G.findMany(p,{...R,consistency:"primary",includeDeleted:$,where:{[h]:w}})).page},onCascade:(p,h)=>G.delete(p,h,i),onRestrict:p=>{throw new ne(p,"restrict")},onSetNull:(p,h,w)=>G.patch(p,h,{[w]:null}),schema:d,tableName:r}),await Le(r),await be(r),y&&u){const p={[y]:k()},h={...u,...p};nt(s,p,h,ve);const w=e.join(Object.keys(s.shape).map(R=>e`${e.identifier(R)} = ${ae(s,R,h[R]??null)}`),e`, `);await oe(r,async R=>(await Ke(r,"UPDATE",w,c,R),!0),async R=>[...await $e(r,u,h,R),...await re(r,n,u,void 0)],n,we(r,n,"update",h)),await _e(r,n,{document:h,previous:u,written:je(c)}),Y(r,"after","delete")&&await X("after","delete",{id:n,op:"delete",previous:u,table:r});return}await oe(r,async p=>(await Ke(r,"DELETE",void 0,c,p),!0),async p=>[...await $e(r,u??void 0,void 0,p),...await re(r,n,u??void 0,void 0)],n,we(r,n,"delete")),await Re(r,n,async()=>{await _e(r,n,void 0),Y(r,"after","delete")&&await X("after","delete",{id:n,op:"delete",previous:u??void 0,table:r})})}},async findFirst(t,n={}){if(n.consistency==="primary"){const r=await St();if(r!==void 0)return r.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 ei(`findFirstOrThrow: no "${t}" document matched`);return i},async findMany(t,n={}){if(n.consistency==="primary"){const h=await St();if(h!==void 0)return h.findMany(t,n)}const i=d.tables[t];if(!i)throw new T("INTERNAL",`unknown table: ${t}`);await F();const r=async(h,w,R,m)=>{if(pt(h))return a?wi(a,h,w,R,m):yt(h);const S=d.tables[h];if(!S)throw new T("INTERNAL",`unknown table: ${h}`);const A=ke(S.softDeleteMode,void 0),b={[w]:{in:R}},I=x(x(b,m),A),O=await Ne(I,h,void 0),D=ee(O,g(S)),P=K(w);let H=e`SELECT ${P} AS __fk__, COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(h)}`;D&&(H=e`${H} WHERE ${D}`),H=e`${H} GROUP BY ${P}`;const qe=await M(E,l,H),Z=new Map;for(const B of qe)Z.set(B.__fk__,Number(B.count??0));return Z},{limit:s,orderKeys:c,query:u}=await Rt(t,i,n),$=await M(E,l,u),y=Nt(i,$),p=Qn(y,{endCursor:n.endCursor,limit:s,omitContinueCursor:n.omitContinueCursor,orderKeys:c});return n.with&&await zn({fetcher:Ge,groupedCounter:r,parents:p.page,...Jn(n),schema:d,tableName:t,with:n.with}),{...p,page:Zn(p.page,n.select,n.with)}},async explain(t,n={}){const i=d.tables[t];if(!i)throw new T("INTERNAL",`unknown table: ${t}`);await F();const{query:r}=await Rt(t,i,n),s=l.name==="sqlite"?"EXPLAIN QUERY PLAN":"EXPLAIN",c=await M(E,l,e`${e.raw(s)} ${r}`),{params:u,sql:$}=l.render(r);return{params:u,plan:c.map(y=>Wi(y)),sql:$}},async get(t,n){const i=Object.hasOwn(d.tables,t)?d.tables[t]:void 0;if(!i)throw new T("BAD_REQUEST",`ctx.db.get(table, id): "${t}" is not a table in this schema`);return i.shardMode!==void 0&&i.shardMode.kind!=="global"?null:(await F(),Q(i,await Sn.load(t,n)))},async groupBy(t,n){const i=d.tables[t];if(!i)throw new T("INTERNAL",`unknown table: ${t}`);await F();const r=n.agg??{op:"count"};if(pe(r.op),r.op!=="count"&&!r.field)throw new T("INTERNAL",`groupBy(${t}, { agg: { op: "${r.op}" } }): "field" is required for non-count reducers`);const s=ke(i.softDeleteMode,void 0),c=x(x(n.baseWhere,n.where),s),u=await Ne(c,t,n.relationBaseWhere),$=u!==c;if(i.aggregateIndexes&&!n.baseWhere&&!$&&!s){const m=await Rn(t,i.aggregateIndexes,r,n);if(m!==void 0)return m}Vi(i,t,n.by,r);const y=ee(u,g(i)),p=n.by.map(m=>e`${K(m)} AS ${e.identifier(m)}`);if(r.op==="count")p.push(e`COUNT(*) AS ${e.identifier("value")}`);else{if(!r.field)throw new T("INTERNAL",`groupBy(${t}, { agg: { op: "${r.op}" } }): "field" is required for non-count reducers`);p.push(e`${e.raw(pe(r.op))}(${K(r.field)}) AS ${e.identifier("value")}`)}const h=e.join(n.by.map(m=>K(m)),e`, `);let w=e`SELECT ${e.join(p,e`, `)} FROM ${e.identifier(t)}`;y&&(w=e`${w} WHERE ${y}`),w=e`${w} GROUP BY ${h}`;const R=await M(E,l,w);return xi(i,n.by,R)},async insert(t,n,i){const r=d.tables[t];if(!r)throw new T("INTERNAL",`unknown table: ${t}`);await F();const s=Xe(r,Vn(r,n,ve),{supplied:n,trusted:i?.allowExplicitId===!0});it(l.name,s);let c;i?.clientId!==void 0?(Yn(i.clientId),c=i.clientId):i?.allowExplicitId&&typeof s._id=="string"?(Xn(s._id),c=s._id):c=z();const u=i?.allowExplicitId&&typeof s._creationTime=="number"?s._creationTime:k(),$={...s,_creationTime:u,_id:c};Y(t,"before","insert")&&await X("before","insert",{doc:{...$},id:c,op:"insert",table:t}),await Le(t),await be(t);const{columns:y,values:p}=yn(r,c,u,s);return await oe(t,async h=>(await pn(t,e`INSERT INTO ${e.identifier(t)} (${ue(y)}) VALUES (${Se(p)})`,h),!0),async h=>[...await $e(t,void 0,$,h),...await re(t,c,void 0,$)],c,we(t,c,"insert",$)),await Re(t,c,async()=>{await _e(t,c,{document:$,written:{_creationTime:u,[ye]:null}}),Y(t,"after","insert")&&await X("after","insert",{doc:$,id:c,op:"insert",table:t})}),c},normalizeId(t,n){return Gn(d,t,n)},async patch(t,n,i,r){Ye("patch",i);const s=await he(t);if(!s)throw new T("INTERNAL",`document not found: ${n}`);const c=d.tables[s];if(!c)throw new T("INTERNAL",`document not found: ${n}`);const u=jn(c,i)?rt:1;for(let $=0;$<u;$+=1){const y=await Me(s,n);if(await Et(s,c,n,i,y,void 0,r))return}throw new ne(`optimistic concurrency conflict on "${s}" — the row changed during this mutation; refetch and retry`,"occ")},async patchIf(t,n,i){Ye("patchIf",i.patch);const r=await he(t),s=r===void 0?void 0:d.tables[r];if(r===void 0||!s)return{applied:!1,doc:null};const c=r,u=ee(i.where,g(s))??e`1 = 1`;for(let $=0;$<rt;$+=1){const[y]=await M(v,l,e`SELECT *, CASE WHEN (${u}) THEN 1 ELSE 0 END AS ${e.identifier(Gt)} FROM ${e.identifier(c)} WHERE ${e.identifier("id")} = ${n}`);if(y===void 0)return{applied:!1,doc:null};const{[Gt]:p,...h}=y;if(Number(p)!==1)return{applied:!1,doc:Q(s,h)??null};const w=await Et(c,s,n,i.patch,h,u,{verify:i.verify});if(w)return{applied:!0,doc:w}}throw new ne(`patchIf on "${c}" lost the row to concurrent writes ${String(rt)} times in a row; retry the operation`,"occ")},async restore(t,n){const i=await he(t),r=i===void 0?void 0:await Me(i,n);if(!i||r===void 0)throw new T("INTERNAL",`document not found: ${n}`);const s=d.tables[i],c=s?.softDeleteMode?.field;if(!s||!c)throw new T("INTERNAL",`ctx.db.restore: table "${i}" is not a .softDelete() table`);const u=r[c]!==null&&r[c]!==void 0;if(await G.patch(t,n,{[c]:null}),u){const $=Q(s,r);$!==null&&await oe(i,async()=>await Promise.resolve(!0),async()=>await re(i,n,void 0,{...$,[c]:null}),n,[]).catch(y=>{throw E.transaction!==void 0&&J(i),y})}},query(t){const n=d.tables[t];if(!n)throw new T("INTERNAL",`unknown table: ${t}`);const i="the legacy query()/withIndex() reader is not available on the D1 (global) backend; use findMany",r=[];let s=0,c;const u=l.name!=="mysql",$={...g(n),fieldRef:w=>e`m.${K(w)}`,rangeTypeGuard:()=>{throw new T("INTERNAL","a path range is never pushed into a search")}},y=w=>r.every(R=>R(w)),p=async(w,R)=>{await F();const m=2*Nn+w.filters.length,S=c===void 0?void 0:ee(c,$,void 0,m),A=S!==void 0&&l.name==="sqlite"&&l.render(S).params.length+m>yi.boundParams,b=A?void 0:S,I=s>0||A,O=await qn(E,l,n,t,b===void 0?w:{...w,scope:b},On(I?void 0:R));!I&&R===void 0&&kn(O);const D=O.filter(P=>y(P));return R===void 0?D:D.slice(0,R)},h=w=>{const R={async*[Symbol.asyncIterator](){if(!w)throw new T("INTERNAL",i);yield*await p(w,void 0)},async collect(){if(!w)throw new T("INTERNAL",i);return p(w,void 0)},async collectWithScores(){throw new T("GLOBAL_SEARCH_SCORES_UNSUPPORTED",`collectWithScores() is not supported on \`.global()\` tables (table "${t}") — relevance scores are not yet surfaced on this backend; use .collect() instead`)},filter(m){r.push(m);const S=hi(m);return S!==void 0&&$i(S,n.shape,u)?c=x(c,S):s+=1,R},async first(){if(!w)throw new T("INTERNAL",i);return(await p(w,1))[0]??null},order(){return R},async paginate(m){if(!w)throw new T("INTERNAL",i);const S=bn(m);return Mn(await p(w,Dn(S)),S)},async take(m){if(!w)throw new T("INTERNAL",i);return p(w,m)},async unique(){if(!w)throw new T("INTERNAL",i);const m=await p(w,2);if(m.length>1)throw new pi(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(){throw new T("INTERNAL",`geo indexes are not supported on \`.global()\` tables (table "${t}") — geospatial queries run only on sharded tables`)},withIndex(){throw new T("INTERNAL",i)},withSearchIndex(m,S){const A=(n.searchIndexes??[]).find(I=>I.name===m);if(!A)throw new T("INTERNAL",`unknown search index "${m}" on table "${t}"`);const b={definition:A,field:A.field,filters:[],hasQuery:!1,indexName:m,query:""};if(S(Ln(b,t,vn(A.language))),!b.hasQuery)throw new T("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return h(b)}};return R};return h(void 0)},async rank(t,n,i){const r=d.tables[t];if(!r)throw new T("INTERNAL",`unknown table: ${t}`);const s=r.rankIndexes?.find(O=>O.name===n);if(!s)throw new T("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(i.restrictsCounts)throw new vt(t);if(await F(),!await He(t,s))return null;const u=typeof i.row=="string"?i.row:i.row._id;if(!u)return null;const $=Ee(t,s.name),y=s.sortBy.map((O,D)=>me(D)),p=ue(["__partition__",...y]),w=(await M(E,l,e`SELECT ${p} FROM ${e.identifier($)} WHERE ${e.identifier("__id__")} = ${u}`))[0];if(!w)return null;const R=w.__partition__,m=x(i.baseWhere,i.where);gt(m,d,t,"rank");const S=Tt(s,m);if(S&&Oe(s.partitionBy??[],S)!==R)return null;const A=Pi(l.name,s,y,w,u),b=await M(E,l,e`SELECT COUNT(*) AS c FROM ${e.identifier($)} WHERE ${e.identifier("__partition__")} = ${R} AND (${A})`),I=await M(E,l,e`SELECT COUNT(*) AS c FROM ${e.identifier($)} WHERE ${e.identifier("__partition__")} = ${R}`);return{position:Number(b[0]?.c??0)+1,total:Number(I[0]?.c??0)}},async rankPage(t,n,i={}){gt(x(i.baseWhere,i.where),d,t,"rankPage");const r=d.tables[t];if(!r)throw new T("INTERNAL",`unknown table: ${t}`);const s=r.rankIndexes?.find(B=>B.name===n);if(!s)throw new T("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(await F(),!await He(t,s))return{continueCursor:null,isDone:!0,page:[]};const u=Ee(t,s.name),$=s.sortBy.map((B,Ve)=>me(Ve)),y=Math.max(1,Math.min(1e3,Math.floor(i.take??100))),p=x(i.baseWhere,i.where),h=Tt(s,p),w=Ki(s,$),R=e.join(w.flatMap(B=>en(l,{direction:B.direction,field:B.column,nullable:B.nullable})),e`, `),m=[];typeof i.partitionKey=="string"?m.push(e`${e.identifier("__partition__")} = ${i.partitionKey}`):h&&m.push(e`${e.identifier("__partition__")} = ${Oe(s.partitionBy??[],h)}`);const S=Kn(i);if(S!==void 0){const B=Hi(l.name,w,S);B!==void 0&&m.push(B)}const A=ue([Te,"__partition__",...$]);let b=e`SELECT ${A} FROM ${e.identifier(u)}`;m.length>0&&(b=e`${b} WHERE ${e.join(m,e` AND `)}`),b=e`${b} ORDER BY ${R} LIMIT ${e.raw(String(y+1))}`;const I=await M(E,l,b),O=I.length>y,D=O?I.slice(0,y):I,P=D.map(B=>B[Te]),H=await ji(E,l,r,t,P);let qe=null;const Z=D.at(-1);if(O&&Z!==void 0){const B=[Z.__partition__,...$.map(Ve=>Z[Ve]),Z[Te]];qe=Gi(B)}return{continueCursor:qe,isDone:!O,page:H}},async replace(t,n,i,r){Ye("replace",i);const s=await he(t);if(!s)throw new T("INTERNAL",`document not found: ${n}`);const c=d.tables[s];if(!c)throw new T("INTERNAL",`document not found: ${n}`);const u=await Me(s,n);if(u===void 0)throw new T("INTERNAL",`document not found: ${n}`);const y=Hn(d,s,"update")||(c.aggregateIndexes??[]).length>0||(c.rankIndexes??[]).length>0?Q(c,u)??void 0:void 0,p=r?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,h=typeof u._creationTime=="number"?u._creationTime:void 0,w=p??h??k(),R={...i,_creationTime:w,_id:n};nt(c,i,R,ve);const m=Xe(c,R,{previous:()=>y??Q(c,u)??void 0,supplied:i,trusted:r?.allowExplicitId===!0});it(l.name,m),Y(s,"before","update")&&await X("before","update",{doc:{...m},id:n,op:"update",previous:y,table:s}),await Le(s),await be(s);const S=Object.keys(c.shape),A=e.join([e`${e.identifier("_creationTime")} = ${w}`,...S.map(b=>e`${e.identifier(b)} = ${ae(c,b,m[b]??null)}`)],e`, `);await oe(s,async b=>(await Ke(s,"UPDATE",A,u,b),!0),async b=>[...await $e(s,y,m,b),...await re(s,n,y,m)],n,we(s,n,"update",m)),await Re(s,n,async()=>{await _e(s,n,{document:m,previous:y,written:je(u,w)}),Y(s,"after","update")&&await X("after","update",{doc:m,id:n,op:"update",previous:y,table:s})})}};return $t={db:G,scheduler:cn},G};export{_r as createSqlCtxDb,Nr as decodeGlobalRow,sr as readSqlCdcChangedTables,Lr as readSqlCdcChanges,on as readSqlCdcFloor,zi as runSqlCdcMigration,Zi as sweepSqlCdcRetention};
@@ -1 +1 @@
1
- import{toErrorBody as b}from"@lunora/errors";import{needsWireEncoding as I,encodeWire as A,decodeWire as S}from"@lunora/wire";import{sql as m}from"drizzle-orm";import{runSqlGlobalTableMigrations as g}from"./runSqlGlobalTableMigrations-B00G2E1V.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-j9zVLMn5.mjs";const $=200,v=(r,o)=>{const t=e=>r.tables[e]?.shardMode?.kind==="global";return o&&o.length>0?o.filter(e=>t(e)):Object.keys(r.tables).filter(e=>t(e))},D=r=>I(r)?A(r):r,Y=async function*(r,o,t,e){const s=v(o,e.tables),n=e.batchSize??$;await g(r,o,t);for(const i of s){const d=o.tables[i];let a,c=!0;for(;c;){const f=await T(r,t,i,a,n);for(const u of f)yield{doc:D(L(d,u)),table:i};const l=f.at(-1);l!==void 0&&(a=String(l.id)),c=f.length===n}}},w=r=>r?._meta?.column?.notNull===!1,C=(r,o)=>{const t=new Set;for(const[e,s]of Object.entries(r.shape)){if(o[e]!==null||s.kind!=="optional"||w(s))continue;const n=s._meta?.inner;w(n)||t.add(e)}return t.size===0?o:Object.fromEntries(Object.entries(o).filter(([e])=>!t.has(e)))},F=new Set(["_creationTime","_id"]),M=(r,o)=>Object.keys(o).find(t=>!F.has(t)&&!Object.hasOwn(r.shape,t)),x=r=>{const o=r._id,t=r._creationTime;if(o!==void 0&&(typeof o!="string"||o===""))return'field "_id": must be a non-empty string';if(t!==void 0&&(typeof t!="number"||!Number.isFinite(t)))return'field "_creationTime": must be a finite number'},j=(r,o,t)=>{const e=r.tables[o];if(!e)return`unknown table: ${o}`;const s=M(e,t);if(s!==void 0)return`unexpected field "${s}": not declared in table "${o}"`;const n=x(t);if(n!==void 0)return n;for(const[i,d]of Object.entries(e.shape)){const a=t[i],c=d.kind==="optional";if(a===void 0&&c)continue;const f=d.parse;if(typeof f=="function")try{f(a)}catch(l){const u=l instanceof Error?l.message:String(l);return`field "${i}": ${u}`}}},R=async(r,o,t,e,s)=>t?(await E(t,o,m`SELECT 1 FROM ${m.identifier(e)} WHERE ${m.identifier("id")} = ${s} LIMIT 1`)).length>0:await r.get(e,s)!==null,O=async(r,o,t,e,s,n)=>{try{return{existingId:await R(r,o,t,e,s)?s:void 0}}catch(i){const{body:d}=b(i,{fallbackCode:"PROBE_FAILED"});return{error:{code:d.code,line:n,message:d.message,table:e}}}},h=(r,o,t)=>{const e=r.held.get(o)??new Set;e.add(t),r.held.set(o,e)},B=async(r,o,t)=>{const e=[...t.keys()],s=new Map;let n=[],i=k;const d=async()=>{if(n.length===0)return;const a=await E(r,o,m.join(n,m` UNION ALL `));for(const c of a)h({held:s},e[Number(c.slot)],String(c.id));n=[],i=k};try{for(const[a,c]of e.entries()){const f=[...t.get(c)];for(let l=0;l<f.length;){const u=f.slice(l,l+i);n.push(m`SELECT ${m.raw(String(a))} AS slot, ${m.identifier("id")} FROM ${m.identifier(c)} WHERE ${m.identifier("id")} IN (${m.join(u.map(p=>m.param(p)),m`, `)})`),l+=u.length,i-=u.length,i===0&&await d()}}await d()}catch(a){const{body:c}=b(a,{fallbackCode:"PROBE_FAILED"});return{failure:{code:c.code,message:c.message}}}return{held:s}},N=(r,o,t,e)=>"failure"in r?{error:{...r.failure,line:e,table:o}}:{existingId:r.held.get(o)?.has(t)===!0?t:void 0},W=r=>v(r).some(o=>Object.keys(r.tables[o]?.triggerMap??{}).length>0),P=async(r,o,t,e,s)=>{const{doc:n,table:i}=e,d=n._id;if(typeof d!="string")return{committed:!1,error:{code:"BAD_ROW",line:s,message:"a delete row needs the `_id` to delete",table:i},kind:"error"};if(t.dryRun===!0)return{kind:"checked"};const a=await O(r,o,t.exec,i,d,s);if("error"in a)return{committed:!1,error:a.error,kind:"error"};if(a.existingId===void 0)return{kind:"absent"};try{return await r.delete(i,d,{hard:!0,skipOnDelete:!0}),{kind:"deleted"}}catch(c){const{body:f}=b(c,{fallbackCode:"DELETE_FAILED"}),l=y(c,i,d),u=l?`${f.message} (row "${d}" was deleted before this failure, so its triggers or companion writes may not have completed; a re-run finds it absent and does not redo them)`:f.message;return{committed:l,error:{code:f.code,line:s,message:u,table:i},kind:"error"}}},_=async(r,o,t,e,s,n)=>{try{if(e!==void 0){const i={...t};return delete i._id,await r.replace(o,e,i,{allowExplicitId:!0}),{kind:"replaced"}}return await r.insert(o,t,{allowExplicitId:!0}),{inserted:o,kind:"inserted"}}catch(i){const{body:d}=b(i,{fallbackCode:e===void 0?"INSERT_FAILED":"REPLACE_FAILED"}),a=e??(typeof t._id=="string"?t._id:void 0),c=a!==void 0&&y(i,o,a),f=n==="replace"?'re-importing it with onConflict "replace" redoes that work':'a re-import skips it while it exists; use onConflict "replace" to redo that work',l=c?`${d.message} (row "${a}" committed before this failure, so its triggers or companion writes may not have completed; ${f})`:d.message;return{committed:c,error:{code:d.code,line:s,message:l,table:o},kind:"error"}}},G=(r,o,t,e)=>{const{doc:s,table:n}=t;if(typeof n!="string"||n.length===0)return{kind:"settled",outcome:{committed:!1,error:{code:"BAD_ROW",line:e,message:"row is missing `table`",table:n},kind:"error"}};if(r.tables[n]?.shardMode?.kind!=="global")return{kind:"settled",outcome:{kind:"skip"}};if(!s||typeof s!="object"||Array.isArray(s))return{kind:"settled",outcome:{committed:!1,error:{code:"BAD_ROW",line:e,message:"row is missing or malformed `doc`",table:n},kind:"error"}};if(t.op==="delete")return{kind:"delete",line:e,row:t};let i;try{i=S(s)}catch(a){return{kind:"settled",outcome:{committed:!1,error:{code:"BAD_ROW",line:e,message:a instanceof Error?a.message:String(a),table:n},kind:"error"}}}i=C(r.tables[n],i);const d=j(r,n,i);return d!==void 0?{kind:"settled",outcome:{committed:!1,error:{code:"VALIDATION_ERROR",line:e,message:d,table:n},kind:"error"}}:o?{kind:"settled",outcome:{kind:"checked"}}:{decoded:i,explicitId:typeof i._id=="string"?i._id:void 0,kind:"ready",line:e,table:n}},H=async(r,o,t,e,s,n)=>{const{decoded:i,explicitId:d,line:a,table:c}=s;try{if(!await R(r,o,t,c,d))return}catch{return}return e.snapshot!==void 0&&"held"in e.snapshot&&h(e.snapshot,c,d),n==="replace"?_(r,c,i,d,a,n):{kind:"conflict"}},z=async(r,o,t,e,s)=>{const{decoded:n,explicitId:i,line:d,table:a}=e;let c={existingId:void 0};if(i!==void 0&&(c=s.snapshot===void 0?await O(r,o,t.exec,a,i,d):N(s.snapshot,a,i,d)),"error"in c)return{committed:!1,error:c.error,kind:"error"};const{existingId:f}=c;if(f!==void 0&&t.onConflict!=="replace")return{kind:"conflict"};const l=await _(r,a,n,f,d,t.onConflict);if(i===void 0)return l;const{snapshot:u}=s;return u!==void 0&&"held"in u&&(l.kind==="inserted"||l.kind==="replaced"||l.kind==="error"&&l.committed)&&h(u,a,i),l.kind==="error"&&!l.committed&&l.error.code==="CONFLICT"&&f===void 0?await H(r,o,t.exec,s,{...e,explicitId:i},t.onConflict)??l:l},q=async(r,o,t,e,s)=>{const n=new Map;for(const i of e)if(i.kind==="ready"&&i.explicitId!==void 0){const d=n.get(i.table)??new Set;d.add(i.explicitId),n.set(i.table,d)}if(n.size===0)return s?{held:new Map}:void 0;try{await g(r,o,t)}catch(i){const{body:d}=b(i,{fallbackCode:"PROBE_FAILED"});return{failure:{code:d.code,message:d.message}}}return s?B(r,t,n):void 0},U=(r,o,t,e,s)=>e.kind==="settled"?Promise.resolve(e.outcome):e.kind==="delete"?P(r,o,t,e.row,e.line):z(r,o,t,e,s),ee=async(r,o,t,e)=>{const s=[],n={};let i=0,d=0,a=0,c=(e.startLine??1)-1;const f=e.rows.map(u=>(c+=1,G(o,e.dryRun===!0,u,u.line??c))),l={};e.exec&&e.dryRun!==!0&&(l.snapshot=await q(e.exec,o,t,f,!W(o)));for(const u of f){const p=await U(r,t,e,u,l);switch(p.kind){case"conflict":{i+=1;break}case"deleted":{d+=1;break}case"error":{s.push(p.error);break}case"inserted":{n[p.inserted]=(n[p.inserted]??0)+1;break}case"replaced":{a+=1;break}}}return{conflicts:i,deleted:d,errors:s,inserted:n,replaced:a}};export{Y as exportSqlGlobalRows,ee as importSqlGlobalRows,v as selectGlobalTables};
1
+ import{toErrorBody as b}from"@lunora/errors";import{needsWireEncoding as A,encodeWire as S,decodeWire as T}from"@lunora/wire";import{sql as u}from"drizzle-orm";import{runSqlGlobalTableMigrations as g}from"./runSqlGlobalTableMigrations-B00G2E1V.mjs";import{t as y}from"./post-commit-error-hh-zQyjO.mjs";import{r as L,d as $,M as k,q as E}from"./sql-exec-j9zVLMn5.mjs";const D=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))},C=r=>A(r)?S(r):r,Y=async function*(r,o,t,e){const s=v(o,e.tables),n=e.batchSize??D;await g(r,o,t);for(const i of s){const d=o.tables[i];let a,c=!0;for(;c;){const f=await L(r,t,i,a,n);for(const m of f)yield{doc:C($(d,m)),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,F=(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)))},M=new Set(["_creationTime","_id"]),x=(r,o)=>Object.keys(o).find(t=>!M.has(t)&&!Object.hasOwn(r.shape,t)),j=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'},B=(r,o,t)=>{const e=r.tables[o];if(!e)return`unknown table: ${o}`;const s=x(e,t);if(s!==void 0)return`unexpected field "${s}": not declared in table "${o}"`;const n=j(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 m=l instanceof Error?l.message:String(l);return`field "${i}": ${m}`}}},R=async(r,o,t,e,s)=>t?(await E(t,o,u`SELECT 1 FROM ${u.identifier(e)} WHERE ${u.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)},N=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,u.join(n,u` 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 m=f.slice(l,l+i);n.push(u`SELECT ${u.raw(String(a))} AS slot, ${u.identifier("id")} FROM ${u.identifier(c)} WHERE ${u.identifier("id")} IN (${u.join(m.map(p=>u.param(p)),u`, `)})`),l+=m.length,i-=m.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}},W=(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},P=r=>v(r).some(o=>Object.keys(r.tables[o]?.triggerMap??{}).length>0),G=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),m=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:m,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"}}},I=(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=T(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=F(r.tables[n],i);const d=B(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):W(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:m}=s;return m!==void 0&&"held"in m&&(l.kind==="inserted"||l.kind==="replaced"||l.kind==="error"&&l.committed)&&h(m,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?N(r,t,n):void 0},U=(r,o,t,e,s)=>e.kind==="settled"?Promise.resolve(e.outcome):e.kind==="delete"?G(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(m=>(c+=1,I(o,e.dryRun===!0,m,m.line??c))),l={};e.exec&&e.dryRun!==!0&&(l.snapshot=await q(e.exec,o,t,f,!P(o)));for(const m of f){const p=await U(r,t,e,m,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}},te=(r,o,t)=>I(r,!1,o,t);export{Y as exportSqlGlobalRows,ee as importSqlGlobalRows,te as prepareGlobalImportRow,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.237",
3
+ "version": "1.0.0-alpha.239",
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.191",
54
+ "@lunora/shard-engine": "^1.0.0-alpha.194",
55
55
  "@lunora/wire": "1.0.0-alpha.6",
56
56
  "drizzle-orm": "1.0.0-rc.5"
57
57
  },
@@ -1,7 +0,0 @@
1
- import{LunoraError as g}from"@lunora/errors";import{m as mn,q as Sn}from"./ctx-db-search-state-CcUMouNm.mjs";import{c as gn,r as Tn,a as vn,A as In,C as An,R as Cn,u as Ln,d as bn,I as Mn,x as Nn,e as On}from"./ctx-db-search-C-Gs6PkL.mjs";import{throwingScheduler as qn,describeRelationWrites as kn,CDC_LOG_TABLE as W,cdcForkedError as Dn,cursorBelowRetainedFloor as Bn,cdcTrimmedError as Wn,serverInList as Fn,assertNoExplicitUndefined as Ve,hasTrigger as xn,runRowValidators as Ye,assertFlatPredicate as St,mergeWhere as x,rankTableName as Ee,sortColumnName as me,resolveRankPartition as gt,encodePartitionKey as Oe,resolveRankSeekTuple as Un,RANK_TIEBREAK as Te,CountRlsUnsupportedError as Tt,compileWhereSql as ee,ConflictError as ne,patchDependsOnRow as Pn,normalizeIdStructurally as Hn,applyInsertDefaults as Kn,assertValidClientId as jn,assertStorableRowId as Gn,aggregateSqlFunction as pe,softDeleteScope as qe,findManyPage as Vn,resolveWith as Yn,relationHooks as Xn,applySelect as Qn,NotFoundError as zn,applyOnDelete as Jn,normalizeCountArgument as Zn,selectIndexForCount as ei,encodeAggregateKey as te,aggregateTableName as ae,selectIndexForAggregate as ti,readAggregateValue as Xe,runTriggers as ni,matchesRankStaticWhere as vt,nullsOrderSuffix as It,nullsFirstOf as At,rankPivotConditionSql as Gt,CURSOR_PREFIX as ii,resolvePatch as oi,stripReservedPatchFields as ri,assertPatchAllowed as si,resolveRelationPredicates as ai,selectIndexForGroupBy as ci,composeReadPredicate as di,fanOutScalarCounts as li,matchesStaticWhere as Qe,coerceAggregateNumber as ze,whereOfFilter as ui,isPushableWhere as fi,tiebreakDirectionFor as wi,foldAggregateTally as Ct,CDC_LOG_TABLE_SEQ_INDEX as hi,NotUniqueError as $i,WORKERD_SQLITE_LIMITS as _i,unionAll as Ei}from"@lunora/shard-engine";import{parseWire as pi,needsWireEncoding as Vt,encodeWire as Yt,decodeWire as yi}from"@lunora/wire";import{sql as e,SQL as Ri}from"drizzle-orm";import{p as Lt,g as bt,q as b,b as j,c as Xt,i as mi,h as Si,j as gi,k as Q,s as ce,e as K,l as Mt,t as Ti,m as Je,n as Be,o as at,O as ye,u as Nt,a as Ot,v as qt,w as kt,x as vi,B as Ze,y as Dt,f as Bt,M as Ii}from"./sql-exec-j9zVLMn5.mjs";import{d as No}from"./sql-exec-j9zVLMn5.mjs";import{runSqlGlobalTableMigrations as Ai}from"./runSqlGlobalTableMigrations-B00G2E1V.mjs";import{runSqlAggregateMigrations as Ci,runSqlRankMigrations as Li}from"./runSqlAggregateMigrations-l-lqWvIq.mjs";import{a as Re}from"./post-commit-error-hh-zQyjO.mjs";import{withQueryTimeout as bi,DEFAULT_QUERY_TIMEOUT_MS as Mi,abandonedWork as et,SqlQueryTimeoutError as Ni}from"./DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import{s as Qt,e as ct}from"./value-codec-DhzLXsqv.mjs";const Wt=50,Oi=(r,a={})=>{const f=a.maxBatch??Wt,_=Number.isInteger(f)&&f>0?f:Wt,l=new Map;let E=!1;const c=async(M,T)=>{const v=[...T.keys()];for(let A=0;A<v.length;A+=_){const N=v.slice(A,A+_);try{const B=await r(M,N);for(const G of N){const z=B.get(G);for(const ie of T.get(G)??[])ie.resolve(z)}}catch(B){for(const G of N)for(const z of T.get(G)??[])z.reject(B)}}},q=()=>{E=!1;const M=[...l.entries()];l.clear();for(const[T,v]of M)c(T,v).catch(()=>{})};return{async load(M,T){return new Promise((v,A)=>{let N=l.get(M);N||(N=new Map,l.set(M,N));const B=N.get(T);B?B.push({reject:A,resolve:v}):N.set(T,[{reject:A,resolve:v}]),E||(E=!0,queueMicrotask(q))})}}},qi=new Set(["_id","id"]),ki=r=>{throw new g("INTERNAL",`no ORDER BY NULL placement for dialect "${String(r)}"`)},zt=(r,a)=>{const f=a.direction==="desc"?"DESC":"ASC",_=a.nullable===!0,l=E=>e`${Be(r,a.field)} ${e.raw(`${f}${E}`)}`;switch(r.name){case"mysql":{const E=l("");return!_||a.nulls===void 0?[E]:[e`(${Be(r,a.field)} IS NULL) ${e.raw(a.nulls==="first"?"DESC":"ASC")}`,E]}case"postgres":return[l(_?It(At(a)):"")];case"sqlite":return[l(_&&a.nulls!==void 0?It(At(a)):"")];default:return ki(r.name)}},Di=(r,a)=>{const f=r.flatMap(_=>zt(a,_));if(!r.some(_=>qi.has(_.field))){const _=wi(r);f.push(e`${K("id")} ${e.raw(_==="desc"?"DESC":"ASC")}`)}return e.join(f,e`, `)},Ft=50,Bi=r=>{const a=r.detail??r["QUERY PLAN"];return typeof a=="string"?a:Object.values(r).map(String).join(" | ")},tt=(r,a,f,_)=>{for(const[l,E]of Ti(r)){if(E.serverDefault){l in a&&(f[l]=E.serverDefault({auth:_}));continue}E.onUpdateFn&&!(l in a)&&(f[l]=E.onUpdateFn())}},Wi=r=>r.shardMode===void 0||r.shardMode.kind==="global",ue=r=>r==null?null:Number(r),Fi=(r,a,f)=>f.map(_=>{const l={};for(const E of a){const c=r.shape[E];l[E]=Qt(_[E]??null,c&&ct(c))}return{key:l,value:ue(_.value)}}),xi=(r,a,f)=>[...r.partitionBy??[],...r.sortBy.map(l=>l.field),...r.where?Object.keys(r.where):[]].every(l=>qt(a,l)===qt(f,l)),Jt=r=>r.length===1?r[0]:e`(${e.join(r,e` AND `)})`,fe=r=>e.join(r.map(a=>e`${e.identifier(a)}`),e`, `),Se=r=>e.join(r.map(a=>e`${a}`),e`, `),nt=(r,a)=>{if(r==="postgres"){for(const[f,_]of Object.entries(a))if(typeof _=="string"&&_.includes("\0"))throw new g("BAD_REQUEST",`"${f}" holds a NUL character (U+0000), which a Postgres text column cannot store`)}},We=r=>r instanceof ArrayBuffer?new Uint8Array(r):Array.isArray(r)?Uint8Array.from(r):r,Ui=(r,a,f,_,l)=>{const E=[];for(let c=0;c<f.length+1;c+=1){const q=f[c],M=a.sortBy[c],T=c<f.length&&q!==void 0&&M!==void 0,v=M?.direction==="desc"?"desc":"asc",A=T?Gt(q,We(_[q]),v,!1):e`${e.identifier(Te)} < ${l}`;if(A===void 0)continue;const N=f.slice(0,c).map(B=>at(r,e`${e.identifier(B)}`,We(_[B])));N.push(A),E.push(Jt(N))}return E.length>0?e.join(E,e` OR `):e`1 = 0`},Pi=(r,a,f)=>{if(f.length!==a.length)return;const _=[];for(const[l,E]of a.entries()){const c=Gt(E.column,We(f[l]),E.direction,!0);if(c===void 0)continue;const q=[];for(let M=0;M<l;M+=1){const T=a[M];T!==void 0&&q.push(at(r,e`${e.identifier(T.column)}`,We(f[M])))}q.push(c),_.push(Jt(q))}return _.length===0?e`(1 = 0)`:e`(${e.join(_,e` OR `)})`},Hi=(r,a)=>{if(r.sortBy.length===0)throw new g("INTERNAL",`rankIndex "${r.name}" requires at least one "sortBy" column for stable pagination`);const f=[{column:"__partition__",direction:"asc",nullable:!1}];for(const[_,l]of r.sortBy.entries())f.push({column:a[_]??me(_),direction:l.direction,nullable:!0});return f.push({column:Te,direction:"asc",nullable:!1}),f},Ki=async(r,a,f,_,l)=>{const c=[];for(let v=0;v<l.length;v+=50)c.push(l.slice(v,v+50));const q=await Promise.all(c.map(async v=>b(r,a,e`SELECT * FROM ${e.identifier(_)} WHERE ${e.identifier("id")} IN (${Se(v)})`))),M=new Map;for(const v of q)for(const A of v)M.set(A.id,A);const T=[];for(const v of l){const A=Q(f,M.get(v));A&&T.push(A)}return T},ji=r=>{const a=r.map(E=>Qt(E,"bytes")),f=JSON.stringify(Vt(a)?Yt(a):a),_=new TextEncoder().encode(f);let l="";for(const E of _)l+=String.fromCodePoint(E);return ii+btoa(l)},Zt=r=>{if(r===void 0)return!1;const a=ct(r);return a==="any"||a==="bigint"||a==="from"||a==="union"},rt=(r,a,f)=>{if(Zt(r.shape[a]))throw new g("BAD_REQUEST",`${f}: "${a}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Gi=(r,a,f,_)=>{for(const l of f)rt(r,l,`groupBy(${a}, { by: [..."${l}"] })`);_.field!==void 0&&rt(r,_.field,`groupBy(${a}, { agg: { op: "${_.op}", field: "${_.field}" } })`)},st="__cdc_sweep",ke="__cdc_log_ts",en="global",Vi=6e4,Yi=1e4,Xi=3e4;let xt=0;const Qi=async(r,a)=>{const{autoincrementPrimaryKey:f,key:_,real:l,text:E}=a.companionTypes;await j(r,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(W)} (${e.identifier("seq")} ${e.raw(f)}, ${e.identifier("ts")} ${e.raw(l)} NOT NULL, ${e.identifier("table")} ${e.raw(_)} NOT NULL, ${e.identifier("id")} ${e.raw(_)} NOT NULL, ${e.identifier("op")} ${e.raw(_)} NOT NULL, ${e.identifier("doc")} ${e.raw(E)})`);const c=a.indexKeyPrefix?.("string");await Xt(r,a,{columns:e`${c===void 0?e`${e.identifier("table")}`:e`${e.identifier("table")}(${e.raw(String(c))})`}, ${e.identifier("seq")}`,name:hi,table:W,unique:!1}),await j(r,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(st)} (${e.identifier("id")} ${e.raw(_)} NOT NULL PRIMARY KEY, ${e.identifier("lease_until")} ${e.raw(l)} NOT NULL)`),await j(r,a,e`INSERT INTO ${e.identifier(st)} (${e.identifier("id")}, ${e.identifier("lease_until")}) VALUES (${en}, ${0}) ${a.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${e.identifier("id")} = ${e.identifier("id")}`:e`ON CONFLICT(${e.identifier("id")}) DO NOTHING`}`)},zi=async(r,a,f)=>{const _=e`UPDATE ${e.identifier(st)} SET ${e.identifier("lease_until")} = ${f+Vi} WHERE ${e.identifier("id")} = ${en} AND ${e.identifier("lease_until")} <= ${f}`;if(a.supportsReturning)return(await b(r,a,e`${_} RETURNING ${e.identifier("id")}`)).length>0;const l=await j(r,a,_);return(a.affectedRows?a.affectedRows(l??{rowsAffected:0}):0)>0},Ji=async(r,a,f,_)=>{if(!await zi(r,a,_))return;const l=_-f;let E=!0;try{const c=await mi(r,a,W,ke);c!=="valid"&&(c==="invalid"&&await Si(r,a,W,ke),await Xt(r,a,{columns:e`${e.identifier("ts")}`,concurrently:!0,name:ke,table:W,unique:!1}))}catch(c){E=!1,console.warn(`[@lunora/sql-store] changelog retention could not build "${ke}"; sweeping without it.`,c)}E&&(await b(r,a,e`SELECT 1 AS ${e.identifier("hit")} FROM ${e.identifier(W)} WHERE ${e.identifier("ts")} <= ${l} LIMIT 1`)).length===0||await j(r,a,e`
2
- DELETE FROM ${e.identifier(W)} WHERE ${e.identifier("seq")} IN (
3
- SELECT ${e.identifier("seq")} FROM (
4
- SELECT ${e.identifier("seq")} FROM ${e.identifier(W)} WHERE +${e.identifier("ts")} <= ${l} ORDER BY ${e.identifier("seq")} ASC LIMIT ${e.raw(String(Yi))}
5
- ) AS ${e.identifier("expired")}
6
- )
7
- `)},tn=async(r,a)=>{const f=await b(r,a,e`SELECT MIN(${e.identifier("seq")}) AS ${e.identifier("seq")} FROM ${e.identifier(W)}`),_=Number(f[0]?.seq??Number.NaN);return Number.isFinite(_)?_:void 0},Zi=async(r,a)=>{if(a.name!=="sqlite")return;const f=await b(r,a,e`SELECT ${e.identifier("seq")} AS ${e.identifier("seq")} FROM ${e.identifier("sqlite_sequence")} WHERE ${e.identifier("name")} = ${W}`),_=Number(f[0]?.seq??Number.NaN);return Number.isFinite(_)?_:0},eo=r=>JSON.stringify(Vt(r)?Yt(r):r),to=(r,a,f,_,l)=>e`INSERT INTO ${e.identifier(W)} (${e.identifier("ts")}, ${e.identifier("table")}, ${e.identifier("id")}, ${e.identifier("op")}, ${e.identifier("doc")}) VALUES (${r}, ${a}, ${f}, ${_}, ${l===void 0?null:eo(l)})`,nn=1e4,no=1e3,io=(r,a,f)=>{let _=a;for(const[l,E]of r.entries()){const c=Number(E.seq);if(c>_+1&&Number(E.ts)>f)return r.slice(0,l);_=c}return r},Lo=async(r,a,f)=>{const _=a.sinceSeq??0,l=Math.max(1,Math.min(a.limit??1e3,1e4)),E=await tn(r,f),c=await Zi(r,f);if(c!==void 0&&_>c)throw Dn(c,_,"global");if(E!==void 0&&Bn(E,_))throw Wn(E,_,"global");const q=await b(r,f,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(W)} WHERE seq > ${_} ORDER BY seq ASC LIMIT ${e.raw(String(l))}`),T=(f.name==="sqlite"?q:io(q,_,(a.now??Date.now())-nn)).map(v=>{const{doc:A}=v,N={id:String(v.id),op:String(v.op),seq:Number(v.seq),table:String(v.table),ts:Number(v.ts)};return typeof A=="string"?{...N,doc:pi(A)}:N});return{changes:T,cursor:T.at(-1)?.seq??_}},Ut=(r,a)=>{const f=e.identifier(W),_=e`(SELECT MIN(v.seq) FROM ${f} v WHERE v.seq > ${r} AND v.seq - 1 > ${r} AND v.ts > ${a} AND NOT EXISTS (SELECT 1 FROM ${f} p WHERE p.seq = v.seq - 1))`;return e`${_} AS ${e.identifier("gap")}, (SELECT MAX(q.seq) FROM ${f} q WHERE q.seq > ${r} AND q.seq < ${_}) AS ${e.identifier("below")}`},Pt=(r,a,f)=>{const _=Number(a?.gap??Number.NaN);if(!Number.isFinite(_))return r;const l=Number(a?.below??Number.NaN);return Math.min(r,Number.isFinite(l)?l:f)},oo=r=>{const a=e.identifier(W),f=e.identifier("table");return e`SELECT ${f}, seq FROM (WITH RECURSIVE "t"("name") AS (SELECT MIN(${f}) FROM ${a} UNION ALL SELECT (SELECT MIN(${f}) FROM ${a} WHERE ${f} > "t"."name") FROM "t" WHERE "t"."name" IS NOT NULL) SELECT "t"."name" AS ${f}, (SELECT MAX(seq) FROM ${a} WHERE ${f} = "t"."name" AND seq > ${r}) AS seq FROM "t" WHERE "t"."name" IS NOT NULL) WHERE seq IS NOT NULL ORDER BY ${f}`},ro=async(r,a,f,_={})=>{const l=e.identifier(W),E=f.name!=="sqlite",c=(_.now??Date.now())-nn;if(_.cursorOnly){const A=e`GREATEST((SELECT MAX(seq) FROM ${l}) - ${e.raw(String(no))}, ${a})`,N=await b(r,f,e`SELECT MAX(seq) AS seq${E?e`, ${Ut(A,c)}`:e``} FROM ${l}`),B=Number(N[0]?.seq??a);return{cursor:Pt(Number.isFinite(B)?B:a,N[0],a),tables:[]}}const q=await b(r,f,E?e`SELECT ${e.identifier("table")} AS ${e.identifier("table")}, MAX(seq) AS seq, ${Ut(e`${a}`,c)} FROM ${l} WHERE seq > ${a} GROUP BY ${e.identifier("table")}`:oo(a));let M=a;const T=[];for(const A of q){const N=Number(A.seq);Number.isFinite(N)&&N>M&&(M=N),T.push(String(A.table))}M=Pt(M,q[0],a);const v=_.retained===!0?await tn(r,f):void 0;return{cursor:M,tables:T,...v===void 0?{}:{floor:v}}},so=/string or blob too big/iu,ao=/row is too big/iu,co=(r,a)=>{const{code:f,errno:_}=a,l=a instanceof Error?a.message:"";switch(r.name){case"mysql":return _===1118||f==="ER_TOO_BIG_ROWSIZE"?"InnoDB's per-row ceiling — roughly 8 KB, half a 16 KB page, for the part of the row stored inline":void 0;case"postgres":return ao.test(l)?"the 8 KB heap page a tuple must fit once its wide columns have been TOASTed out":void 0;default:return so.test(l)?"the storage engine's per-row ceiling (2 MB on D1)":void 0}},lo=(r,a,f)=>{const _=co(r,a);if(_!==void 0)throw new g("PAYLOAD_TOO_LARGE",`document is too large to store in "${f}": a single row cannot exceed ${_}. The limit is on the STORED bytes, which are UTF-8. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},it=16,Ht="__lunora_patch_if_match__",Kt=(r,a,f)=>{throw r.isUniqueViolation(a)?new ne(`unique constraint violation on "${f}"`,"unique"):(lo(r,a,f),a)},uo=r=>{const{code:a,errno:f}=r??{};return a==="40P01"||a==="40001"||f===1213||a==="ER_LOCK_DEADLOCK"},fo=r=>{throw uo(r)?new ne("the write's transaction was rolled back by a lock conflict with a concurrent write; retry it","occ"):r},ot=new WeakMap,jt=new WeakMap,de="superseded",wo=3e4,ge="__lunora_companion_fence",ho=(r,a,f,_,l)=>{const E=Math.max(1,Math.floor((Ii-2)/_.length)),c=(T,v)=>{const A=r.name==="postgres"?e`CAST(${T} AS ${e.raw(v.type)})`:e`${T}`;return e`${A} AS ${e.identifier(v.name)}`},q=T=>e`SELECT ${e.join(T.map((v,A)=>c(v,_[A])),e`, `)}`,M=[];for(let T=0;T<l.length;T+=E){const v=l.slice(T,T+E).map(A=>q(A));M.push(e`INSERT INTO ${e.identifier(a)} (${fe(_.map(A=>A.name))}) SELECT * FROM (${Ei(v)}) AS ${e.identifier("__rows__")} WHERE EXISTS (SELECT 1 FROM ${e.identifier(ge)} WHERE ${f})`)}return M},le=(r,a,f)=>JSON.stringify([r,a,f]),De=r=>JSON.stringify(r,(a,f)=>typeof f=="bigint"?`${String(f)}n`:f),$o=r=>{const a=Fn(r);return(f,_,l,E)=>_.some(c=>c instanceof Ri)?gi(r,f,_,l):a(f,_,l,E)},_o=r=>{const{crossShardCounter:a,crossShardReader:f,maxRelationKeys:_,schema:l}=r,E=bi(r.exec,r.queryTimeoutMs??Mi,r.queryTimer),{dialect:c}=r,q={fieldRef:t=>Be(c,t),rangeTypeGuard:(t,n)=>vi(c,t,n),...c.name==="mysql"?{containsExpr:(t,n)=>{const i=Lt(t);return i===void 0?e`LOCATE(${n}, ${t}) > 0`:e`LOCATE(${bt("mysql",n)}, ${i}) > 0`}}:{},...c.name==="postgres"?{containsExpr:(t,n)=>{const i=Lt(t);return i===void 0?e`strpos(${t}, ${n}) > 0`:e`strpos(${i}, ${bt("postgres",n)}) > 0`}}:{},...c.name==="sqlite"?{}:{inList:$o(c.name)}},M=new WeakMap,T=t=>{const n=M.get(t);if(n!==void 0)return n;const i={...q,serialize:(o,s)=>kt(c,s,o,d=>ce(t,s,d))};return M.set(t,i),i},v=(t,n)=>at(c.name,t,n),A=t=>{const n=fe(t.columns),i=Se(t.values),o=$=>c.name==="mysql"?e`VALUES(${e.identifier($)})`:e`excluded.${e.identifier($)}`,s=$=>c.name==="postgres"?e`${e.identifier(t.table)}.${e.identifier($)}`:e`${e.identifier($)}`,d=e.join(Object.entries(t.set(o,s)).map(([$,y])=>e`${e.identifier($)} = ${y}`),e`, `),u=c.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${d}`:e`ON CONFLICT(${e.identifier(t.conflictKey)}) DO UPDATE SET ${d}`;return e`INSERT INTO ${e.identifier(t.table)} (${n}) VALUES (${i}) ${u}`},N=r.clock??(()=>Date.now()),B=r.idGenerator??(()=>crypto.randomUUID()),G=r.cdc??!1,z=typeof r.cdcRetentionMs=="number"&&Number.isFinite(r.cdcRetentionMs)&&r.cdcRetentionMs>0?r.cdcRetentionMs:void 0,ie=r.auth??{identity:null,userId:null},we=(t,n,i,o)=>G?[to(N(),t,n,i,o)]:[],on=async()=>{if(!G||z===void 0)return;const t=N();if(!(t-xt<Xi)){xt=t;try{await Ji(E,c,z,t)}catch{}}},rn=r.scheduler??qn;let ve=0;const oe=r.provisionScope??{},F=async()=>{const t=ot.get(oe);if(t)return t;const n=(async()=>{const i=r.exec;await Ai(i,l,c),await Ci(i,l,c),await Li(i,l,c),await mn(i,c),await Tn(E,l,c),G&&await Qi(i,c)})().catch(i=>{throw ot.delete(oe),i});return ot.set(oe,n),n},he=async t=>{if(typeof t!="string"||!Object.hasOwn(l.tables,t))throw new g("BAD_REQUEST",`ctx.db by-id write (table, id): "${t}" is not a table in this schema`);await F();const n=l.tables[t];return n!==void 0&&Wi(n)?t:void 0};let Ie=jt.get(oe);Ie===void 0&&(Ie=new Map,jt.set(oe,Ie));const U=Ie;let Fe=0;const dt={},xe=(t,n,i)=>{const o=(async()=>(await F(),await i(()=>U.get(t)?.run!==o)))(),s={definition:n,owner:dt,run:o,settled:!1};return o.then(d=>{d===de&&U.get(t)===s?U.delete(t):s.settled=!0},()=>{U.get(t)===s&&U.delete(t)}).catch(()=>{}),U.set(t,s),o},lt=async(t,n,i)=>{const o=U.get(t);if(o===void 0)return await xe(t,n,i);const s=o.definition===n;if(s&&(o.settled||o.owner===dt))return await o.run;if(o.settled)return await xe(t,n,i);let d;const u=new Promise(y=>{d=setTimeout(y,wo,"stalled")}),$=await Promise.race([o.run,u]).finally(()=>{clearTimeout(d)});return $!=="stalled"&&s?$:U.get(t)===o?await xe(t,n,i):await lt(t,n,i)},Ue=async(t,n,i)=>{const o=await lt(t,n,i);return o===de?await Ue(t,n,i):o},ut=async(t,n)=>{const i=U.get(t),o=i?.settled===!0&&i.definition===n?await i.run:void 0;if(typeof o=="boolean")return o;U.delete(t),Fe+=1},J=t=>{const n=l.tables[t];for(const i of n?.aggregateIndexes??[])U.delete(le("aggregate",t,i.name));for(const i of n?.rankIndexes??[])U.delete(le("rank",t,i.name))},sn=async(t,n)=>{const i=ae(t,n);return(await b(E,c,c.tableExists(i))).length>0},ft=async t=>{const{key:n}=c.companionTypes,i=B();await j(E,c,e`CREATE TABLE IF NOT EXISTS ${e.identifier(ge)} (${e.identifier("name")} ${e.raw(n)} PRIMARY KEY, ${e.identifier("token")} ${e.raw(n)} NOT NULL)`),await j(E,c,A({columns:["name","token"],conflictKey:"name",set:s=>({token:s("token")}),table:ge,values:[t,i]}));const 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(ge)} WHERE ${o})`,stillHeld:async()=>(await b(E,c,e`SELECT 1 FROM ${e.identifier(ge)} WHERE ${o}`)).length>0,guardedInsertRows:(s,d)=>ho(c,t,o,s,d)}},an=async(t,n,i)=>{const o=l.tables[t];if(!o||!await sn(t,n.name))return!1;const s=n.by??[],d=new Map;await Dt(E,c,o,t,R=>{if(n.where&&!Qe(R,n.where))return;const m=te(s,R);Ct(d,m,n,R)});const u=ae(t,n.name);if(i())return de;const $=await ft(u);await j(E,c,$.guardedDelete());const{integer:y,key:p,real:h}=c.companionTypes,w=$.guardedInsertRows([{name:"__key__",type:p},{name:"__value__",type:h},{name:"__count__",type:y}],[...d].map(([R,m])=>[R,m.value,m.count]));return i()||await Bt(E,c,w),i()||!await $.stillHeld()?de:!0},Ae=(t,n)=>Ue(le("aggregate",t,n.name),De(n),i=>an(t,n,i)),cn=async(t,n,i,o,s)=>{const d=new Map;let u,$=!0;for(;$;){const y=u===void 0?o:[...o,e`${e.identifier("id")} > ${u}`],p=y.length>0?e` WHERE ${e.join(y,e` AND `)}`:e``,h=await b(s,c,e`SELECT ${e.identifier("id")}, ${K(i.field??"")} FROM ${e.identifier(n)}${p} ORDER BY ${e.identifier("id")} ASC LIMIT ${e.raw(String(Ze))}`);for(const w of Mt(t,h))Ct(d,"",i,w);u=h.at(-1)?.id,$=h.length===Ze}return d.get("")?.value??null},dn=async(t,n,i,o)=>{const s=n.field??"",d=[],u=l.tables[t],$=(w,R)=>kt(c,w,R,m=>u?ce(u,w,m):Je(m));for(const w of n.by??[]){const R=$(w,i[w]??null);d.push(R===null?e`${K(w)} IS NULL`:e`${K(w)} = ${R}`)}for(const[w,R]of Object.entries(n.where??{})){const m=R!==null&&typeof R=="object"&&!Array.isArray(R)?R.eq:R,S=$(w,m),C=Be(c,w);d.push(S===null?e`${C} IS NULL`:e`${C} = ${S}`)}const y=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``;if(u&&Zt(u.shape[s]))return cn(u,t,n,d,o);const p=pe(n.op),h=await b(o,c,e`SELECT ${e.raw(p)}(${K(s)}) AS ${e.identifier("value")} FROM ${e.identifier(t)}${y}`);return ue(h[0]?.value)},ln=(t,n)=>e`DELETE FROM ${e.identifier(t)} WHERE ${e.identifier("__key__")} = ${n} AND ${e.identifier("__count__")} <= 0`,un=async(t,n,i,o,s)=>{const d=ae(t,n.name),{op:u}=n,$=n.field??"",y=i&&(!n.where||Qe(i,n.where))?i:void 0,p=o&&(!n.where||Qe(o,n.where))?o:void 0;if(!y&&!p)return[];if(u==="count"||u==="sum"||u==="avg"){const S=[],C=new Set,L=[];for(const[I,O]of[[y,-1],[p,1]]){if(!I)continue;const k=u==="count"?1:ze(I[$]);k!==void 0&&L.push({encoded:te(n.by??[],I),numeric:k,sign:O})}L.sort((I,O)=>I.encoded<O.encoded?-1:+(I.encoded>O.encoded));for(const{encoded:I,numeric:O,sign:k}of L)C.add(I),S.push(A({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(P,H)=>({__count__:e`${H("__count__")} + ${P("__count__")}`,__value__:u==="count"?e`${H("__value__")} + ${P("__value__")}`:e`COALESCE(${H("__value__")}, 0) + ${P("__value__")}`}),table:d,values:[I,k*O,k]}));for(const I of C)S.push(ln(d,I));return S}const h=[],w=[];let R,m;if(y){const S=te(n.by??[],y);R=S;const C=ze(y[$]),I=(await b(s,c,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(d)} WHERE ${e.identifier("__key__")} = ${S}`))[0],O=ue(I?.value),k=(I?.count??0)-1;if(k<=0)h.push(e`DELETE FROM ${e.identifier(d)} WHERE ${e.identifier("__key__")} = ${S}`);else if(I&&C!==void 0&&O!==null&&C===O){const P=await dn(t,n,y,s);h.push(e`UPDATE ${e.identifier(d)} SET ${e.identifier("__value__")} = ${P}, ${e.identifier("__count__")} = ${k} WHERE ${e.identifier("__key__")} = ${S}`)}else h.push(e`UPDATE ${e.identifier(d)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${S}`)}if(p){const S=te(n.by??[],p);m=S;const C=ze(p[$]);if(C===void 0)w.push(A({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(L,I)=>({__count__:e`${I("__count__")} + 1`}),table:d,values:[S,null,1]}));else{const L=u==="min"?"MIN":"MAX";w.push(A({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(I,O)=>({__count__:e`${O("__count__")} + 1`,__value__:e`${e.raw(L)}(COALESCE(${O("__value__")}, ${I("__value__")}), ${I("__value__")})`}),table:d,values:[S,C,1]}))}}return R!==void 0&&m!==void 0&&m<R?[...w,...h]:[...h,...w]},Ce=async t=>{const n=l.tables[t]?.aggregateIndexes;if(!(!n||n.length===0))for(const i of n)await Ae(t,i)},$e=async(t,n,i,o)=>{const s=l.tables[t]?.aggregateIndexes,d=[];if(!s||s.length===0)return d;for(const u of s)await ut(le("aggregate",t,u.name),De(u))&&d.push(...await un(t,u,n,i,o));return d},fn=async(t,n)=>{const i=Ee(t,n);return(await b(E,c,c.tableExists(i))).length>0},wn=async(t,n,i)=>{const o=l.tables[t];if(!o||!await fn(t,n.name))return!1;const s=Ee(t,n.name);if(i())return de;const d=await ft(s);await j(E,c,d.guardedDelete());const u=c.companionTypes.key,$=[{name:"__id__",type:u},{name:"__partition__",type:u},...n.sortBy.map((h,w)=>{const R=o.shape[h.field];return{name:me(w),type:c.columnType(R?ct(R):void 0)}})];let y=[];const p=async()=>{const h=y;y=[],!(h.length===0||i())&&await Bt(E,c,d.guardedInsertRows($,h))};return await Dt(E,c,o,t,async h=>{if(n.where&&!vt(h,n.where))return;const w=Oe(n.partitionBy??[],h),R=n.sortBy.map(m=>Je(h[m.field]??null));y.push([h._id,w,...R]),y.length>=Ze&&await p()}),await p(),i()||!await d.stillHeld()?de:!0},Pe=(t,n)=>Ue(le("rank",t,n.name),De(n),i=>wn(t,n,i)),Le=async t=>{const n=l.tables[t]?.rankIndexes;if(!(!n||n.length===0))for(const i of n)await Pe(t,i)},re=async(t,n,i,o)=>{const s=l.tables[t],d=s?.rankIndexes,u=[];if(!d||d.length===0)return u;const $=s?.softDeleteMode?.field,y=$===void 0||o===void 0?void 0:o[$],p=y!=null;for(const h of d){if(i!==void 0&&o!==void 0&&xi(h,i,o)||!await ut(le("rank",t,h.name),De(h)))continue;const R=Ee(t,h.name);if(i&&u.push(e`DELETE FROM ${e.identifier(R)} WHERE ${e.identifier("__id__")} = ${n}`),o&&!p){if(h.where&&!vt(o,h.where))continue;const m=h.sortBy.map((I,O)=>me(O)),S=fe(["__id__","__partition__",...m]),C=Oe(h.partitionBy??[],o),L=h.sortBy.map(I=>Je(o[I.field]??null));u.push(e`INSERT INTO ${e.identifier(R)} (${S}) VALUES (${Se([n,C,...L])})`)}}return u},hn=(t,n,i)=>{const o=et(n);if(o===void 0||!i.dispatched){J(t);return}o.then(()=>{i.batched||J(t)},()=>{J(t)}).catch(()=>{})},se=async(t,n,i,o,s)=>{const d=l.tables[t],u=G||(d?.aggregateIndexes?.length??0)>0||(d?.rankIndexes?.length??0)>0,$=E.transaction===void 0||!u,y=async w=>{let R;try{R=await n(w)}catch(S){if(E.transaction===void 0&&S instanceof Ni){J(t);const C=()=>{J(t)};et(S)?.then(C,C).catch(()=>{})}throw S}if(!R)return!1;const m={batched:!1,dispatched:!1};try{$&&s.length>0&&await Ot(w,c,s);const S=$?await i(w):[...await i(w),...s];S.length>0&&(m.batched=w.batch!==void 0&&c.name==="sqlite",m.dispatched=!0,await Ot(w,c,S))}catch(S){throw E.transaction===void 0&&hn(t,S,m),$&&await Re(t,o,async()=>{throw await Promise.resolve(),S}),S}return!0};let p;const h=Fe;try{p=E.transaction!==void 0&&u?await E.transaction(y).catch(fo):await y(E),p&&Fe!==h&&E.transaction!==void 0&&u&&J(t)}catch(w){const R=et(w);if(R!==void 0){const m=async()=>{await vn({dialect:c,exec:E,schema:l},t,o)};R.then(m,m).catch(()=>{})}throw w}return p&&await Re(t,o,on),p},_e=gn({dialect:c,exec:E,schema:l}),wt=new Set;for(const[t,n]of Object.entries(l.tables))for(const i of Object.values(n.triggerMap??{}))wt.add(`${t} ${i.timing} ${i.op}`);const Y=(t,n,i)=>wt.has(`${t} ${n} ${i}`);let ht;const X=async(t,n,i)=>{if(ve+=1,ve>Ft)throw ve-=1,new ne(`trigger recursion exceeded ${String(Ft)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await ni({ctx:ht,event:i,op:n,schema:l,tableName:i.table,timing:t})}finally{ve-=1}},$n=async(t,n,i=E)=>{try{await j(i,c,n)}catch(o){Kt(c,o,t)}},be=async(t,n)=>(await b(E,c,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} = ${n}`))[0],$t=async(t,n,i,o,s,d)=>{const u=e`${e.identifier(ye)}`,$=e.join([v(e`${e.identifier("id")}`,o.id),v(u,o[ye]??null),...s===void 0?[]:[e`(${s})`]],e` AND `),y=n==="UPDATE"?e`UPDATE ${e.identifier(t)} SET ${i}, ${u} = ${Nt.sql(u)} WHERE ${$}`:e`DELETE FROM ${e.identifier(t)} WHERE ${$}`;try{if(c.supportsReturning)return(await b(d,c,e`${y} RETURNING ${e.identifier("id")}`)).length>0;const p=await j(d,c,y);return(c.affectedRows?c.affectedRows(p??{rowsAffected:0}):0)>0}catch(p){return Kt(c,p,t)}},He=async(t,n,i,o,s)=>{if(o!==void 0&&!await $t(t,n,i,o,void 0,s))throw new ne(`optimistic concurrency conflict on "${t}" — the row changed during this mutation; refetch and retry`,"occ")},Ke=(t,n=t?._creationTime)=>({_creationTime:n,[ye]:Nt.value(t?.[ye])}),_t=async(t,n,i,o,s,d,u)=>{const $=Q(n,s);if(!$||s===void 0)throw new g("INTERNAL",`document not found: ${i}`);const y=oi(n,o,$),p={...$,...ri(y),_id:i};tt(n,y,p,ie);const h=Ye(n,p,{only:new Set(Object.keys(y)),previous:()=>$,tolerateStoredNull:!0});nt(c.name,Object.fromEntries(Object.keys(y).map(S=>[S,h[S]]))),si(u,$,h),Y(t,"before","update")&&await X("before","update",{doc:{...h},id:i,op:"update",previous:$,table:t}),await Ce(t),await Le(t);const w=Object.keys(n.shape),R=e.join(w.map(S=>e`${e.identifier(S)} = ${ce(n,S,h[S]??null)}`),e`, `);if(await se(t,async S=>await $t(t,"UPDATE",R,s,d,S),async S=>[...await $e(t,$,h,S),...await re(t,i,$,h)],i,we(t,i,"update",h)))return await _e(t,i,{document:h,previous:$,written:Ke(s)}),Y(t,"after","update")&&await X("after","update",{doc:h,id:i,op:"update",previous:$,table:t}),h},_n=(t,n,i,o)=>{const s=Object.keys(t.shape);return{columns:["id","_creationTime",...s],values:[n,i,...s.map(d=>ce(t,d,o[d]??null))]}},En=async(t,n,i,o)=>{const s=ci(n,i.op,i.field,o.by,o.where);if(!s||!await Ae(t,s.index))return;const u=ae(t,s.index.name),$=Object.keys(s.partial);if($.length===(s.index.by??[]).length&&$.length>0){const p=te(s.index.by??[],s.partial),h=await b(E,c,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(u)} WHERE ${e.identifier("__key__")} = ${p}`);if(h.length===0)return[];const w=h[0];return[{key:{...s.partial},value:Xe(i.op,{count:w.count,value:ue(w.value)})}]}return $.length>0?void 0:(await b(E,c,e`SELECT ${e.identifier("__key__")} AS ${e.identifier("key")}, ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(u)}`)).map(p=>{const h=p;return{key:yi(JSON.parse(h.key)),value:Xe(i.op,{count:h.count,value:ue(h.value)})}})},Et=t=>{const n=l.tables[t]?.shardMode?.kind;return n==="shardBy"||n==="root"},pt=t=>{throw new g("INTERNAL",`cross-backend relation: a global table cannot load the shard-local relation '${t}' (it spans every shard) — wire a cross-shard reader to support it`)},pn=(t,n)=>{if(n?.relationMask!==void 0&&n.with!==void 0&&Object.keys(n.with).length>0)throw new g("MASK_UNSUPPORTED",`masking cannot follow a nested \`with\` across the cross-shard relation hop to "${t}" — the nested rows are hydrated on the serving shard, where the mask policy does not exist. Read the nested relation at its own (masked) call site instead.`);const i={};if(n?.relationBaseWhere)for(const o of Object.keys(l.tables)){const s=n.relationBaseWhere(o);s!==void 0&&(i[o]=s)}return{orderBy:n?.orderBy,relationPolicies:i,where:x(n?.baseWhere,n?.where),with:n?.with}},je=(t,n)=>Et(t)?f?f(t,pn(t,n)):pt(t):V.findMany(t,n),Me=(t,n,i)=>ai(t,{fetcher:je,maxRelationKeys:_,relationBaseWhere:i,schema:l,tableName:n}),yn=Oi(async(t,n)=>{const i=await b(E,c,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} IN (${Se(n)})`),o=new Map;for(const s of i){const{id:d}=s;typeof d=="string"&&o.set(d,s)}return o}),yt=async(t,n,i)=>{const{fetchLimit:o,limit:s,orderKeys:d,predicate:u}=await di(n,i,{fetcher:je,maxRelationKeys:_,schema:l,tableName:t}),$=ee(u,T(n)),y=Di(d,c);let p=e`SELECT * FROM ${e.identifier(t)}`;return $&&(p=e`${p} WHERE ${$}`),p=e`${p} ORDER BY ${y}`,o!==void 0&&(p=e`${p} LIMIT ${e.raw(String(o))}`),{limit:s,orderKeys:d,query:p}},Rn=kn(l);let Rt;const mt=async()=>{const{primary:t}=r.exec;if(t!==void 0)return await F(),Rt??=_o({...r,exec:t,provisionScope:oe}),Rt},V={relationWrites:Rn,async cdcChangedTables(t,n){if(G)try{return await F(),await ro(E,t,c,{...n,now:N(),retained:z!==void 0})}catch{return}},async aggregate(t,n){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);if(await F(),pe(n.op),n.op==="count")return V.count(t,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new g("INTERNAL",`aggregate(${t}, { op: "${n.op}" }): "field" is required for non-count reducers`);const o=qe(i.softDeleteMode,void 0),s=x(x(n.baseWhere,n.where),o),d=await Me(s,t,n.relationBaseWhere),u=d!==s;if(i.aggregateIndexes&&!n.baseWhere&&!u&&!o){const R=ti(i.aggregateIndexes,n.op,n.field,n.where);if(R&&await Ae(t,R.index)){const S=te(R.index.by??[],R.key),C=ae(t,R.index.name),I=(await b(E,c,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(C)} WHERE ${e.identifier("__key__")} = ${S}`))[0];return Xe(n.op,I===void 0?void 0:{count:I.count,value:ue(I.value)})}}rt(i,n.field,`aggregate(${t}, { op: "${n.op}", field: "${n.field}" })`);const $=ee(d,T(i)),y=e.raw(pe(n.op)),p=e`SELECT ${y}(${K(n.field)}) AS ${e.identifier("value")} FROM ${e.identifier(t)}`,w=(await b(E,c,$?e`${p} WHERE ${$}`:p))[0]?.value;return w==null?null:Number(w)},async count(t,n){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await F();const o=Zn(n);if(o.restrictsCounts)throw new Tt(t);const s=qe(i.softDeleteMode,void 0),d=x(x(o.baseWhere,o.where),s),u=await Me(d,t,o.relationBaseWhere),$=u!==d;if(i.aggregateIndexes&&!o.baseWhere&&!$&&!s){const w=ei(i.aggregateIndexes,o.where);if(w&&await Ae(t,w.index)){const m=te(w.index.by??[],w.key),S=ae(t,w.index.name),C=await b(E,c,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")} FROM ${e.identifier(S)} WHERE ${e.identifier("__key__")} = ${m}`);return Number(C[0]?.value??0)}}const y=ee(u,T(i)),p=e`SELECT COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(t)}`,h=await b(E,c,y?e`${p} WHERE ${y}`:p);return Number(h[0]?.count??0)},async delete(t,n,i){const o=await he(t);if(!o)return;const s=l.tables[o];if(!s)return;const d=await be(o,n);if(d===void 0)return;const u=Q(s,d),$=i?.hard===!0,y=!$&&s.softDeleteMode?s.softDeleteMode.field:void 0;if(!(y&&(!u||u[y]!==null&&u[y]!==void 0))){if(Y(o,"before","delete")&&await X("before","delete",{id:n,op:"delete",previous:u??void 0,table:o}),i?.skipOnDelete!==!0&&await Jn({deletedId:n,deletedReference:p=>u?.[p],findHolders:async(p,h,w,R)=>{if(l.tables[p]?.shardMode?.kind==="shardBy")throw new g("INTERNAL",`cross-backend cascade from global '${o}' into shardBy '${p}' is not supported — would require Query Coordinator fan-out across shards`);return(await V.findMany(p,{...R,includeDeleted:$,where:{[h]:w}})).page},onCascade:(p,h)=>V.delete(p,h,i),onRestrict:p=>{throw new ne(p,"restrict")},onSetNull:(p,h,w)=>V.patch(p,h,{[w]:null}),schema:l,tableName:o}),await Ce(o),await Le(o),y&&u){const p={[y]:N()},h={...u,...p};tt(s,p,h,ie);const w=e.join(Object.keys(s.shape).map(R=>e`${e.identifier(R)} = ${ce(s,R,h[R]??null)}`),e`, `);await se(o,async R=>(await He(o,"UPDATE",w,d,R),!0),async R=>[...await $e(o,u,h,R),...await re(o,n,u,void 0)],n,we(o,n,"update",h)),await _e(o,n,{document:h,previous:u,written:Ke(d)}),Y(o,"after","delete")&&await X("after","delete",{id:n,op:"delete",previous:u,table:o});return}await se(o,async p=>(await He(o,"DELETE",void 0,d,p),!0),async p=>[...await $e(o,u??void 0,void 0,p),...await re(o,n,u??void 0,void 0)],n,we(o,n,"delete")),await Re(o,n,async()=>{await _e(o,n,void 0),Y(o,"after","delete")&&await X("after","delete",{id:n,op:"delete",previous:u??void 0,table:o})})}},async findFirst(t,n={}){if(n.consistency==="primary"){const o=await mt();if(o!==void 0)return o.findFirst(t,n)}return(await V.findMany(t,{...n,limit:1})).page[0]??null},async findFirstOrThrow(t,n={}){const i=await V.findFirst(t,n);if(i===null)throw new zn(`findFirstOrThrow: no "${t}" document matched`);return i},async findMany(t,n={}){if(n.consistency==="primary"){const h=await mt();if(h!==void 0)return h.findMany(t,n)}const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await F();const o=async(h,w,R,m)=>{if(Et(h))return a?li(a,h,w,R,m):pt(h);const S=l.tables[h];if(!S)throw new g("INTERNAL",`unknown table: ${h}`);const C=qe(S.softDeleteMode,void 0),L={[w]:{in:R}},I=x(x(L,m),C),O=await Me(I,h,void 0),k=ee(O,T(S)),P=K(w);let H=e`SELECT ${P} AS __fk__, COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(h)}`;k&&(H=e`${H} WHERE ${k}`),H=e`${H} GROUP BY ${P}`;const Ne=await b(E,c,H),Z=new Map;for(const D of Ne)Z.set(D.__fk__,Number(D.count??0));return Z},{limit:s,orderKeys:d,query:u}=await yt(t,i,n),$=await b(E,c,u),y=Mt(i,$),p=Vn(y,{endCursor:n.endCursor,limit:s,omitContinueCursor:n.omitContinueCursor,orderKeys:d});return n.with&&await Yn({fetcher:je,groupedCounter:o,parents:p.page,...Xn(n),schema:l,tableName:t,with:n.with}),{...p,page:Qn(p.page,n.select,n.with)}},async explain(t,n={}){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await F();const{query:o}=await yt(t,i,n),s=c.name==="sqlite"?"EXPLAIN QUERY PLAN":"EXPLAIN",d=await b(E,c,e`${e.raw(s)} ${o}`),{params:u,sql:$}=c.render(o);return{params:u,plan:d.map(y=>Bi(y)),sql:$}},async get(t,n){const i=Object.hasOwn(l.tables,t)?l.tables[t]:void 0;if(!i)throw new g("BAD_REQUEST",`ctx.db.get(table, id): "${t}" is not a table in this schema`);return i.shardMode!==void 0&&i.shardMode.kind!=="global"?null:(await F(),Q(i,await yn.load(t,n)))},async groupBy(t,n){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await F();const o=n.agg??{op:"count"};if(pe(o.op),o.op!=="count"&&!o.field)throw new g("INTERNAL",`groupBy(${t}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);const s=qe(i.softDeleteMode,void 0),d=x(x(n.baseWhere,n.where),s),u=await Me(d,t,n.relationBaseWhere),$=u!==d;if(i.aggregateIndexes&&!n.baseWhere&&!$&&!s){const m=await En(t,i.aggregateIndexes,o,n);if(m!==void 0)return m}Gi(i,t,n.by,o);const y=ee(u,T(i)),p=n.by.map(m=>e`${K(m)} AS ${e.identifier(m)}`);if(o.op==="count")p.push(e`COUNT(*) AS ${e.identifier("value")}`);else{if(!o.field)throw new g("INTERNAL",`groupBy(${t}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);p.push(e`${e.raw(pe(o.op))}(${K(o.field)}) AS ${e.identifier("value")}`)}const h=e.join(n.by.map(m=>K(m)),e`, `);let w=e`SELECT ${e.join(p,e`, `)} FROM ${e.identifier(t)}`;y&&(w=e`${w} WHERE ${y}`),w=e`${w} GROUP BY ${h}`;const R=await b(E,c,w);return Fi(i,n.by,R)},async insert(t,n,i){const o=l.tables[t];if(!o)throw new g("INTERNAL",`unknown table: ${t}`);await F();const s=Ye(o,Kn(o,n,ie),{supplied:n,trusted:i?.allowExplicitId===!0});nt(c.name,s);let d;i?.clientId!==void 0?(jn(i.clientId),d=i.clientId):i?.allowExplicitId&&typeof s._id=="string"?(Gn(s._id),d=s._id):d=B();const u=i?.allowExplicitId&&typeof s._creationTime=="number"?s._creationTime:N(),$={...s,_creationTime:u,_id:d};Y(t,"before","insert")&&await X("before","insert",{doc:{...$},id:d,op:"insert",table:t}),await Ce(t),await Le(t);const{columns:y,values:p}=_n(o,d,u,s);return await se(t,async h=>(await $n(t,e`INSERT INTO ${e.identifier(t)} (${fe(y)}) VALUES (${Se(p)})`,h),!0),async h=>[...await $e(t,void 0,$,h),...await re(t,d,void 0,$)],d,we(t,d,"insert",$)),await Re(t,d,async()=>{await _e(t,d,{document:$,written:{_creationTime:u,[ye]:null}}),Y(t,"after","insert")&&await X("after","insert",{doc:$,id:d,op:"insert",table:t})}),d},normalizeId(t,n){return Hn(l,t,n)},async patch(t,n,i,o){Ve("patch",i);const s=await he(t);if(!s)throw new g("INTERNAL",`document not found: ${n}`);const d=l.tables[s];if(!d)throw new g("INTERNAL",`document not found: ${n}`);const u=Pn(d,i)?it:1;for(let $=0;$<u;$+=1){const y=await be(s,n);if(await _t(s,d,n,i,y,void 0,o))return}throw new ne(`optimistic concurrency conflict on "${s}" — the row changed during this mutation; refetch and retry`,"occ")},async patchIf(t,n,i){Ve("patchIf",i.patch);const o=await he(t),s=o===void 0?void 0:l.tables[o];if(o===void 0||!s)return{applied:!1,doc:null};const d=o,u=ee(i.where,T(s))??e`1 = 1`;for(let $=0;$<it;$+=1){const[y]=await b(E,c,e`SELECT *, CASE WHEN (${u}) THEN 1 ELSE 0 END AS ${e.identifier(Ht)} FROM ${e.identifier(d)} WHERE ${e.identifier("id")} = ${n}`);if(y===void 0)return{applied:!1,doc:null};const{[Ht]:p,...h}=y;if(Number(p)!==1)return{applied:!1,doc:Q(s,h)??null};const w=await _t(d,s,n,i.patch,h,u,{verify:i.verify});if(w)return{applied:!0,doc:w}}throw new ne(`patchIf on "${d}" lost the row to concurrent writes ${String(it)} times in a row; retry the operation`,"occ")},async restore(t,n){const i=await he(t),o=i===void 0?void 0:await be(i,n);if(!i||o===void 0)throw new g("INTERNAL",`document not found: ${n}`);const s=l.tables[i],d=s?.softDeleteMode?.field;if(!s||!d)throw new g("INTERNAL",`ctx.db.restore: table "${i}" is not a .softDelete() table`);const u=o[d]!==null&&o[d]!==void 0;if(await V.patch(t,n,{[d]:null}),u){const $=Q(s,o);$!==null&&await se(i,async()=>await Promise.resolve(!0),async()=>await re(i,n,void 0,{...$,[d]:null}),n,[]).catch(y=>{throw E.transaction!==void 0&&J(i),y})}},query(t){const n=l.tables[t];if(!n)throw new g("INTERNAL",`unknown table: ${t}`);const i="the legacy query()/withIndex() reader is not available on the D1 (global) backend; use findMany",o=[];let s=0,d;const u=c.name!=="mysql",$={...T(n),fieldRef:w=>e`m.${K(w)}`,rangeTypeGuard:()=>{throw new g("INTERNAL","a path range is never pushed into a search")}},y=w=>o.every(R=>R(w)),p=async(w,R)=>{await F();const m=2*Ln+w.filters.length,S=d===void 0?void 0:ee(d,$,void 0,m),C=S!==void 0&&c.name==="sqlite"&&c.render(S).params.length+m>_i.boundParams,L=C?void 0:S,I=s>0||C,O=await bn(E,c,n,t,L===void 0?w:{...w,scope:L},Mn(I?void 0:R));!I&&R===void 0&&Nn(O);const k=O.filter(P=>y(P));return R===void 0?k:k.slice(0,R)},h=w=>{const R={async*[Symbol.asyncIterator](){if(!w)throw new g("INTERNAL",i);yield*await p(w,void 0)},async collect(){if(!w)throw new g("INTERNAL",i);return p(w,void 0)},async collectWithScores(){throw new g("GLOBAL_SEARCH_SCORES_UNSUPPORTED",`collectWithScores() is not supported on \`.global()\` tables (table "${t}") — relevance scores are not yet surfaced on this backend; use .collect() instead`)},filter(m){o.push(m);const S=ui(m);return S!==void 0&&fi(S,n.shape,u)?d=x(d,S):s+=1,R},async first(){if(!w)throw new g("INTERNAL",i);return(await p(w,1))[0]??null},order(){return R},async paginate(m){if(!w)throw new g("INTERNAL",i);const S=An(m);return Cn(await p(w,On(S)),S)},async take(m){if(!w)throw new g("INTERNAL",i);return p(w,m)},async unique(){if(!w)throw new g("INTERNAL",i);const m=await p(w,2);if(m.length>1)throw new $i(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(){throw new g("INTERNAL",`geo indexes are not supported on \`.global()\` tables (table "${t}") — geospatial queries run only on sharded tables`)},withIndex(){throw new g("INTERNAL",i)},withSearchIndex(m,S){const C=(n.searchIndexes??[]).find(I=>I.name===m);if(!C)throw new g("INTERNAL",`unknown search index "${m}" on table "${t}"`);const L={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:m,query:""};if(S(In(L,t,Sn(C.language))),!L.hasQuery)throw new g("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return h(L)}};return R};return h(void 0)},async rank(t,n,i){const o=l.tables[t];if(!o)throw new g("INTERNAL",`unknown table: ${t}`);const s=o.rankIndexes?.find(O=>O.name===n);if(!s)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(i.restrictsCounts)throw new Tt(t);if(await F(),!await Pe(t,s))return null;const u=typeof i.row=="string"?i.row:i.row._id;if(!u)return null;const $=Ee(t,s.name),y=s.sortBy.map((O,k)=>me(k)),p=fe(["__partition__",...y]),w=(await b(E,c,e`SELECT ${p} FROM ${e.identifier($)} WHERE ${e.identifier("__id__")} = ${u}`))[0];if(!w)return null;const R=w.__partition__,m=x(i.baseWhere,i.where);St(m,l,t,"rank");const S=gt(s,m);if(S&&Oe(s.partitionBy??[],S)!==R)return null;const C=Ui(c.name,s,y,w,u),L=await b(E,c,e`SELECT COUNT(*) AS c FROM ${e.identifier($)} WHERE ${e.identifier("__partition__")} = ${R} AND (${C})`),I=await b(E,c,e`SELECT COUNT(*) AS c FROM ${e.identifier($)} WHERE ${e.identifier("__partition__")} = ${R}`);return{position:Number(L[0]?.c??0)+1,total:Number(I[0]?.c??0)}},async rankPage(t,n,i={}){St(x(i.baseWhere,i.where),l,t,"rankPage");const o=l.tables[t];if(!o)throw new g("INTERNAL",`unknown table: ${t}`);const s=o.rankIndexes?.find(D=>D.name===n);if(!s)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(await F(),!await Pe(t,s))return{continueCursor:null,isDone:!0,page:[]};const u=Ee(t,s.name),$=s.sortBy.map((D,Ge)=>me(Ge)),y=Math.max(1,Math.min(1e3,Math.floor(i.take??100))),p=x(i.baseWhere,i.where),h=gt(s,p),w=Hi(s,$),R=e.join(w.flatMap(D=>zt(c,{direction:D.direction,field:D.column,nullable:D.nullable})),e`, `),m=[];typeof i.partitionKey=="string"?m.push(e`${e.identifier("__partition__")} = ${i.partitionKey}`):h&&m.push(e`${e.identifier("__partition__")} = ${Oe(s.partitionBy??[],h)}`);const S=Un(i);if(S!==void 0){const D=Pi(c.name,w,S);D!==void 0&&m.push(D)}const C=fe([Te,"__partition__",...$]);let L=e`SELECT ${C} FROM ${e.identifier(u)}`;m.length>0&&(L=e`${L} WHERE ${e.join(m,e` AND `)}`),L=e`${L} ORDER BY ${R} LIMIT ${e.raw(String(y+1))}`;const I=await b(E,c,L),O=I.length>y,k=O?I.slice(0,y):I,P=k.map(D=>D[Te]),H=await Ki(E,c,o,t,P);let Ne=null;const Z=k.at(-1);if(O&&Z!==void 0){const D=[Z.__partition__,...$.map(Ge=>Z[Ge]),Z[Te]];Ne=ji(D)}return{continueCursor:Ne,isDone:!O,page:H}},async replace(t,n,i,o){Ve("replace",i);const s=await he(t);if(!s)throw new g("INTERNAL",`document not found: ${n}`);const d=l.tables[s];if(!d)throw new g("INTERNAL",`document not found: ${n}`);const u=await be(s,n);if(u===void 0)throw new g("INTERNAL",`document not found: ${n}`);const y=xn(l,s,"update")||(d.aggregateIndexes??[]).length>0||(d.rankIndexes??[]).length>0?Q(d,u)??void 0:void 0,p=o?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,h=typeof u._creationTime=="number"?u._creationTime:void 0,w=p??h??N(),R={...i,_creationTime:w,_id:n};tt(d,i,R,ie);const m=Ye(d,R,{previous:()=>y??Q(d,u)??void 0,supplied:i,trusted:o?.allowExplicitId===!0});nt(c.name,m),Y(s,"before","update")&&await X("before","update",{doc:{...m},id:n,op:"update",previous:y,table:s}),await Ce(s),await Le(s);const S=Object.keys(d.shape),C=e.join([e`${e.identifier("_creationTime")} = ${w}`,...S.map(L=>e`${e.identifier(L)} = ${ce(d,L,m[L]??null)}`)],e`, `);await se(s,async L=>(await He(s,"UPDATE",C,u,L),!0),async L=>[...await $e(s,y,m,L),...await re(s,n,y,m)],n,we(s,n,"update",m)),await Re(s,n,async()=>{await _e(s,n,{document:m,previous:y,written:Ke(u,w)}),Y(s,"after","update")&&await X("after","update",{doc:m,id:n,op:"update",previous:y,table:s})})}};return ht={db:V,scheduler:rn},V};export{_o as createSqlCtxDb,No as decodeGlobalRow,ro as readSqlCdcChangedTables,Lo as readSqlCdcChanges,tn as readSqlCdcFloor,Qi as runSqlCdcMigration,Ji as sweepSqlCdcRetention};