@lunora/shard-engine 1.0.0-alpha.213 → 1.0.0-alpha.214
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/conformance/index.mjs +1 -1
- package/dist/index.d.mts +4 -930
- package/dist/index.d.ts +4 -930
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-olXwJWFQ.mjs → ADMIN_FUNCTIONS-voPpYb3p.mjs} +1 -1
- package/dist/packem_shared/AGG_COUNT-DzvM-UU5.mjs +1 -0
- package/dist/packem_shared/{AUDIT_LOG_TABLE-BFJ65SRS.mjs → AUDIT_LOG_TABLE-CGyZ2LNx.mjs} +1 -1
- package/dist/packem_shared/{CDC_LOG_TABLE-fCPCjSE4.mjs → CDC_LOG_TABLE-DchHJJ5G.mjs} +6 -6
- package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-De7z_OHV.mjs → CLIENT_WATERMARK_TABLE-CMUFBMfO.mjs} +1 -1
- package/dist/packem_shared/{COMMIT_SEQ_FIELD-Da1DjGqo.mjs → COMMIT_SEQ_FIELD-lEe6aaMv.mjs} +1 -1
- package/dist/packem_shared/CompanionMemo-CYnosDCb.mjs +1 -0
- package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-CPWZjliE.mjs → DATA_MIGRATION_STATE_TABLE-D5giMetp.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-xz76_vX6.mjs → DEFAULT_MAX_RELATION_KEYS-UrlFzZB3.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-BZLpaaq1.mjs → DEFAULT_MAX_RELAYS-BcyWWSdU.mjs} +1 -1
- package/dist/packem_shared/DOC_COLUMN-BNhw3l1X.mjs +1 -0
- package/dist/packem_shared/{DurableStreamRunner-MMlV5qKQ.mjs → DurableStreamRunner-BikgXQLq.mjs} +1 -1
- package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-Cdq1nHtu.mjs} +1 -1
- package/dist/packem_shared/{IDEMPOTENCY_TABLE-BVosXEq_.mjs → IDEMPOTENCY_TABLE-DyKgfnGa.mjs} +1 -1
- package/dist/packem_shared/IMPORT_MANIFEST_TTL_MS-g0o4UIT_.mjs +1 -0
- package/dist/packem_shared/{MAIL_RETENTION-DMolrLYt.mjs → MAIL_RETENTION-C0LZvTbG.mjs} +3 -3
- package/dist/packem_shared/NotUniqueError-DlNAfu1a.mjs +1 -0
- package/dist/packem_shared/{QUEUE_TABLE-C-goXtGd.mjs → QUEUE_TABLE-CWUNphDm.mjs} +3 -3
- package/dist/packem_shared/RANK_TIEBREAK-BknRdgt8.mjs +1 -0
- package/dist/packem_shared/{REACTOR_STATE_TABLE-D2Mn204f.mjs → REACTOR_STATE_TABLE-B2x69RYJ.mjs} +1 -1
- package/dist/packem_shared/{SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs → SCHEDULE_OUTBOX_TABLE-BPs0yEDb.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs → SCHEMA_HISTORY_MAX_VERSIONS-Cgw1Tg1r.mjs} +1 -1
- package/dist/packem_shared/{SEARCH_STATE_TABLE-D7w8mRsm.mjs → SEARCH_STATE_TABLE-DJywWtgJ.mjs} +1 -1
- package/dist/packem_shared/{SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs → SHAPE_POKE_CURSOR_TABLE-CKl7syse.mjs} +1 -1
- package/dist/packem_shared/VECTOR_BACKFILL_MAX_PAGES-CxiEhH8V.mjs +1 -0
- package/dist/packem_shared/WORKERD_SQLITE_LIMITS-C9dUlw3o.mjs +1 -0
- package/dist/packem_shared/{adminTokenExists-CQ0qedmu.mjs → adminTokenExists-CDwEWaFF.mjs} +1 -1
- package/dist/packem_shared/{appendStreamChunk-BZYgGE9Y.mjs → appendStreamChunk-DIxOE9q_.mjs} +1 -1
- package/dist/packem_shared/{applyInsertDefaults-CaVH3fJ7.mjs → applyInsertDefaults-Bt6LYmPD.mjs} +1 -1
- package/dist/packem_shared/{archiveCdcSegment-Cr8oGLfB.mjs → archiveCdcSegment-B3UKVQ9U.mjs} +1 -1
- package/dist/packem_shared/backfillAggregateIndexes-BkCo8Dpf.mjs +1 -0
- package/dist/packem_shared/buildReprojectionMigration-CCr-Pv9T.mjs +1 -0
- package/dist/packem_shared/{buildShapeDiff-DrXTkXKH.mjs → buildShapeDiff-CrLtKTuR.mjs} +1 -1
- package/dist/packem_shared/{clearMemoryTables-aMRERF0w.mjs → clearMemoryTables-CIfrwTj8.mjs} +1 -1
- package/dist/packem_shared/compileWhereSql-CEy6QwJx.mjs +1 -0
- package/dist/packem_shared/computeRankPage-De_JKnna.mjs +1 -0
- package/dist/packem_shared/createCompanionSync-D5cqtwqR.mjs +1 -0
- package/dist/packem_shared/{createReplicaLink-BapaAUfm.mjs → createReplicaLink-auEtD_6G.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-relay-shapes-DBobAek2.mjs → ctx-db-relay-shapes-V1HnPPPX.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-search-state-CPKPy8N6.mjs → ctx-db-search-state-Bv_NxB1g.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-BGiRhp-9.mjs → defineEngineContractSuite-C_pEZ8_E.mjs} +1 -1
- package/dist/packem_shared/do-sql-DT8JBpG8.mjs +1 -0
- package/dist/packem_shared/{exportShardRows-BEzRTBwD.mjs → exportShardRows-BxhBKedl.mjs} +1 -1
- package/dist/packem_shared/fts-companion-Cfz-hJum.mjs +1 -0
- package/dist/packem_shared/ftsCompanionDdl-NFICsmqs.mjs +1 -0
- package/dist/packem_shared/ftsRowidMapName-CGnFBC6P.mjs +1 -0
- package/dist/packem_shared/{isSoftDeleted-By7iuPdW.mjs → isSoftDeleted-Dc3VHgrR.mjs} +1 -1
- package/dist/packem_shared/isTtlExpired-ktYeluAa.mjs +1 -0
- package/dist/packem_shared/{materializeExternalRows-gZqs4Rsj.mjs → materializeExternalRows-LugivbOG.mjs} +1 -1
- package/dist/packem_shared/param-Y0zw_1Cv.mjs +1 -0
- package/dist/packem_shared/rankPivotConditionSql-CUX4Vuhv.mjs +1 -0
- package/dist/packem_shared/runDrizzle-DAtZbzBn.mjs +1 -0
- package/dist/packem_shared/runShardMigrations-DeOECCjz.mjs +5 -0
- package/dist/packem_shared/runSql-BBRXi81G.mjs +1 -0
- package/dist/packem_shared/selectShapeMembers-BP30uxpp.mjs +1 -0
- package/dist/packem_shared/sql-engine.d-DN1kL76Y.d.mts +886 -0
- package/dist/packem_shared/sql-engine.d-DN1kL76Y.d.ts +886 -0
- package/dist/packem_shared/where-sql-AVR5KloI.mjs +1 -0
- package/dist/sql.d.mts +47 -0
- package/dist/sql.d.ts +47 -0
- package/dist/sql.mjs +1 -0
- package/package.json +5 -1
- package/dist/packem_shared/AGG_COUNT-BaMXGlVQ.mjs +0 -1
- package/dist/packem_shared/CompanionMemo-jmlDbPlr.mjs +0 -1
- package/dist/packem_shared/IMPORT_MANIFEST_TTL_MS-BrNT0vUO.mjs +0 -1
- package/dist/packem_shared/NotUniqueError-Cv97uGOS.mjs +0 -1
- package/dist/packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs +0 -1
- package/dist/packem_shared/VECTOR_BACKFILL_MAX_PAGES-DbNHRd5m.mjs +0 -1
- package/dist/packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-BfJ2FeLv.mjs +0 -1
- package/dist/packem_shared/buildReprojectionMigration-wSas3lLT.mjs +0 -1
- package/dist/packem_shared/compileWhereSql--dIcrS0b.mjs +0 -1
- package/dist/packem_shared/computeRankPage-B6umzbg4.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-DmciS_rv.mjs +0 -1
- package/dist/packem_shared/do-sql-Cf2rnuLV.mjs +0 -1
- package/dist/packem_shared/fts-companion-CE3EmIjk.mjs +0 -1
- package/dist/packem_shared/ftsCompanionDdl-B0bFCy6d.mjs +0 -1
- package/dist/packem_shared/isTtlExpired-Bymg2-13.mjs +0 -1
- package/dist/packem_shared/runDrizzle-RC09zZrh.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-4_ene2xR.mjs +0 -5
- package/dist/packem_shared/selectShapeMembers-Ce6pOHKe.mjs +0 -1
- package/dist/packem_shared/where-sql-Cb_dSAMj.mjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as l}from"drizzle-orm";import{i as O,b as x}from"./json-field-path-DeJW4U9z.mjs";import{sqliteInList as C,isJsonSafe as L,bytesAsHexJson as w}from"./param-Y0zw_1Cv.mjs";import{WORKERD_SQLITE_LIMITS as b}from"./WORKERD_SQLITE_LIMITS-C9dUlw3o.mjs";import{quoteIdentifier as j}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as A,SEEK_RANGE as U}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const v={binary:(t,n,s)=>l`${t} ${l.raw(n)} ${s}`,constant:t=>t?l`1 = 1`:l`0 = 1`,connect:(t,n,s)=>l`(${t}) ${l.raw(s)} (${n})`,contains:(t,n)=>l`instr(lower(${t}), lower(${n})) > 0`,inList:(t,n,s,o)=>C(t,n,s,o),negate:t=>l`NOT (${t})`,nullCheck:(t,n)=>n?l`${t} IS NOT NULL`:l`${t} IS NULL`,value:t=>l`${t}`},h=(...t)=>{let n="";const s=[];for(const o of t)typeof o=="string"?n+=o:(n+=o.text,s.push(...o.params));return{params:s,text:n}},N=t=>({params:[t],text:"?"}),I=t=>({params:[],text:t}),ot=t=>I(j(t)),it={binary:(t,n,s)=>h(t," ".concat(n," "),N(s)),constant:t=>I(t?"1 = 1":"0 = 1"),connect:(t,n,s)=>h("(",t,") ".concat(s," ("),n,")"),contains:(t,n)=>h("instr(lower(",t,"), lower(",n,")) > 0"),inList:(t,n,s,o)=>{const i=s?" NOT IN ":" IN ",e=n.every(c=>L(c)),r=n.length>o&&!e?w(n):void 0;if(r!==void 0)return h(t,i,'(SELECT unhex("value") FROM json_each(',N(r),"))");if(n.length>o&&!e)throw new T("BAD_REQUEST",`an "in" list of ${String(n.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(n.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);if(n.length<=o){const c=[t,i,"("];for(const[a,u]of n.entries())a>0&&c.push(", "),c.push(N(u));return c.push(")"),h(...c)}return h(t,i,'(SELECT "value" FROM json_each(',N(JSON.stringify(n)),"))")},negate:t=>h("NOT (",t,")"),nullCheck:(t,n)=>h(t,n?" IS NOT NULL":" IS NULL"),value:N},M=b.boundParams/2,R=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],D=new Set(R),m=new Set(["gt","gte","lt","lte"]),k={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},d=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return!1;const n=Object.keys(t);return n.length>0&&n.every(s=>D.has(s))},P=(t,n,s,o,i)=>{const e=i.value(o.serialize(s,t));return o.containsExpr?o.containsExpr(n,e):i.contains(n,e)},F=(t,n,s,o,i)=>{const e=x(s);return e===void 0?i.constant(!1):i.connect(n,o.rangeTypeGuard(t,e),"AND")},g=(t,n,s,o,i,e,r,c)=>{if(i===null)return s==="eq"||s==="ne"?r.nullCheck(n,s==="ne"):r.constant(!1);const a=r.binary(n,o,e.serialize(i,t));return!c&&m.has(s)&&O(t)?F(t,a,i,e,r):a},G=(t,n,s,o,i,e)=>{if(!Array.isArray(o))throw new T("BAD_REQUEST",`\`${s==="IN"?"in":"notIn"}\` on "${t}" expects an array of values, received ${o===null?"null":typeof o}`);const r=o;if(r.length===0)return e.constant(s==="NOT IN");const c=r.map(u=>i.serialize(u,t)),a=s==="NOT IN";return i.inList?i.inList(n,c,a):e.inList(n,c,a,M)},$=b.boundParams/2,B=6e4,q=(t,n)=>{const s={bytes:[],hasNull:!1,numbers:[],strings:[]};for(const o of t)if(o===null)s.hasNull=!0;else if(o instanceof Uint8Array)s.bytes.push(Array.from(o,i=>i.toString(16).padStart(2,"0")).join(""));else if(typeof o=="number"&&L(o))s.numbers.push(o);else if(typeof o=="string"&&L(o))s.strings.push(o);else throw new T("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value that cannot be bound as one parameter (a non-finite number, or malformed text). Narrow the list to ${String(n)} values or fewer.`);return s},K=(t,n,s)=>{const o=[],i=l.identifier("v"),e=l.identifier("__in__"),r=a=>l`jsonb_array_elements_text(CAST(CAST(${JSON.stringify(a)} AS text) AS jsonb))`,c=(a,u)=>l`JSON_TABLE(${JSON.stringify(a)}, '$[*]' COLUMNS (${i} ${l.raw(u)} PATH '$')) ${e}`;return s.strings.length>0&&o.push(t==="postgres"?l`${n} IN (SELECT ${r(s.strings)})`:l`${n} IN (SELECT CONVERT(${i} USING utf8mb4) FROM ${c(s.strings,"LONGTEXT")})`),s.numbers.length>0&&o.push(t==="postgres"?l`${n} IN (SELECT CAST(${r(s.numbers)} AS double precision))`:l`${n} IN (SELECT ${i} FROM ${c(s.numbers,"DOUBLE")})`),s.bytes.length>0&&o.push(t==="postgres"?l`${n} IN (SELECT decode(${r(s.bytes)}, 'hex'))`:l`${n} IN (SELECT UNHEX(${i}) FROM ${c(s.bytes,"LONGTEXT")})`),o},et=t=>(n,s,o,i=$)=>{const e=Math.floor(B*i/$);if(s.length<=e){const E=l.join(s.map(y=>l`${y}`),l`, `);return o?l`${n} NOT IN (${E})`:l`${n} IN (${E})`}const r=q(s,e);if(o&&r.hasNull)return l`1 = 0`;const c=K(t,n,r),a=r.hasNull?[l`1 = NULL`]:[],u=[...c,...a],p=u.length===1?u[0]:l`(${l.join(u,l` OR `)})`;return o?l`NOT (${p})`:p},z=(t,n,s,o,i)=>{const e=s,r=[];for(const c of R){if(!(c in e))continue;const a=e[c],u=k[c];u?r.push(g(t,n,c,u,a,o,i,s[U]===!0)):c==="isNull"?r.push(i.nullCheck(n,!a)):c==="contains"?r.push(P(t,n,a,o,i)):r.push(G(t,n,c==="in"?"IN":"NOT IN",a,o,i))}return r},J=(t,n,s,o)=>{const i=s.fieldRef(t);return d(n)?z(t,i,n,s,o):n===null?[o.nullCheck(i,!1)]:[o.binary(i,"=",s.serialize(n,t))]},f=(t,n,s)=>{if(t.length<=1)return t[0];const o=Math.floor(t.length/2);return s.connect(f(t.slice(0,o),n,s),f(t.slice(o),n,s),n)},Y=(t,n,s,o)=>{const i=Array.isArray(t)?t:[],e=[];for(const r of i){const c=S(r??{},s,o);if(c!==void 0)e.push(c);else if(n==="OR")return}return e.length===0?n==="OR"?o.constant(!1):void 0:f(e,n,o)},Q=new Set(["AND","NOT","OR",A]),X=(t,n,s,o)=>{if(t===A){if(!s.relationExists)throw new T("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return s.relationExists(n)}if(t==="NOT"){const i=S(n??{},s,o);return i===void 0?o.constant(!1):o.negate(i)}return Y(n,t,s,o)},S=(t,n,s)=>{const o=[];for(const[i,e]of Object.entries(t))if(Q.has(i)){const r=X(i,e,n,s);r!==void 0&&o.push(r)}else o.push(...J(i,e,n,s));return f(o,"AND",s)},_=t=>{let n=0,s=0;const o=i=>{const e=_(i);n+=e.lists,s+=e.scalars};if(Array.isArray(t)){for(const i of t)o(i);return{lists:n,scalars:s}}if(t===null||typeof t!="object")return{lists:n,scalars:s};for(const[i,e]of Object.entries(t))i==="in"||i==="notIn"?n+=1:i==="AND"||i==="NOT"||i==="OR"||d(e)?(o(e),O(i)&&(s+=1+Object.keys(e).filter(r=>m.has(r)).length)):s+=O(i)?2:1;return{lists:n,scalars:s}},rt=(t,n,s=v,o=0)=>{if(!t||Object.keys(t).length===0)return;const{lists:i,scalars:e}=_(t);if(i===0)return S(t,n,s);const r=Math.max(1,Math.floor(Math.min($,b.boundParams-e-o)/i)),c=n.inList??((a,u,p,E)=>s.inList(a,u,p,E??r));return S(t,{...n,inList:(a,u,p)=>c(a,u,p,r)},s)};export{rt as c,ot as i,h as j,I as r,et as s,it as t};
|
package/dist/sql.d.mts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { SQL, Name } from 'drizzle-orm';
|
|
2
|
+
import { S as SqlExec, a as SqlCursor, R as RangeOperandType, W as WhereInput, b as SqlEngine, c as RenderedSql } from "./packem_shared/sql-engine.d-DN1kL76Y.mjs";
|
|
3
|
+
import '@lunora/errors';
|
|
4
|
+
declare const runDrizzle: <Row = Record<string, unknown>>(exec: SqlExec, query: SQL) => SqlCursor<Row>;
|
|
5
|
+
interface WhereFragments<T> {
|
|
6
|
+
binary: (reference: T, comparator: string, value: unknown) => T;
|
|
7
|
+
connect: (left: T, right: T, connector: "AND" | "OR") => T;
|
|
8
|
+
constant: (value: boolean) => T;
|
|
9
|
+
contains: (reference: T, term: T) => T;
|
|
10
|
+
inList: (reference: T, items: ReadonlyArray<unknown>, negated: boolean, budget: number) => T;
|
|
11
|
+
negate: (inner: T) => T;
|
|
12
|
+
nullCheck: (reference: T, negated: boolean) => T;
|
|
13
|
+
value: (value: unknown) => T;
|
|
14
|
+
}
|
|
15
|
+
type FieldRefSql<T> = (field: string) => T;
|
|
16
|
+
type SerializeValue = (value: unknown, field: string) => unknown;
|
|
17
|
+
interface WhereSqlStrategy<T = SQL> {
|
|
18
|
+
containsExpr?: (reference: T, term: T) => T;
|
|
19
|
+
fieldRef: FieldRefSql<T>;
|
|
20
|
+
inList?: (reference: T, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => T;
|
|
21
|
+
rangeTypeGuard: (field: string, type: RangeOperandType) => T;
|
|
22
|
+
relationExists?: (request: unknown) => T;
|
|
23
|
+
serialize: SerializeValue;
|
|
24
|
+
}
|
|
25
|
+
declare const serverInList: (engine: "mysql" | "postgres") => (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
|
|
26
|
+
declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>, reservedParams?: number) => T | undefined;
|
|
27
|
+
declare const jsonPathSql: (field: string) => SQL;
|
|
28
|
+
declare const qualifiedJsonPathSql: (table: string, field: string) => SQL;
|
|
29
|
+
declare const createIndexSql: (name: string, table: string, columns: SQL, unique: boolean) => SQL;
|
|
30
|
+
declare const AGG_KEY: Name;
|
|
31
|
+
declare const AGG_VALUE: Name;
|
|
32
|
+
declare const AGG_COUNT: Name;
|
|
33
|
+
declare const aggUpsertSql: (aggTable: string, key: unknown, value: unknown, count: unknown, set: SQL) => SQL;
|
|
34
|
+
declare const renderSql: (engine: SqlEngine, query: SQL) => RenderedSql;
|
|
35
|
+
declare const param: (value: unknown) => SQL;
|
|
36
|
+
declare const unionAll: (branches: ReadonlyArray<SQL>) => SQL;
|
|
37
|
+
declare const sqliteInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
|
|
38
|
+
interface FtsWriteOptions {
|
|
39
|
+
guard?: SQL;
|
|
40
|
+
unmappedRowids?: ReadonlyArray<number>;
|
|
41
|
+
}
|
|
42
|
+
declare const ftsCompanionDdl: (companion: string) => SQL[];
|
|
43
|
+
declare const ftsWriteDocument: (companion: string, id: string, text: string, options?: FtsWriteOptions) => SQL[];
|
|
44
|
+
declare const ftsPurgeDocument: (companion: string, id: string, options?: FtsWriteOptions) => SQL[];
|
|
45
|
+
declare const ftsUnmappedPage: (companion: string, limit: number, after?: number) => SQL;
|
|
46
|
+
declare const rankPivotConditionSql: (column: string, value: unknown, direction: "asc" | "desc", wantLater: boolean) => SQL | undefined;
|
|
47
|
+
export { AGG_COUNT, AGG_KEY, AGG_VALUE, type FtsWriteOptions, type WhereSqlStrategy, aggUpsertSql, compileWhereSql, createIndexSql, ftsCompanionDdl, ftsPurgeDocument, ftsUnmappedPage, ftsWriteDocument, jsonPathSql, param, qualifiedJsonPathSql, rankPivotConditionSql, renderSql, runDrizzle, serverInList, sqliteInList, unionAll };
|
package/dist/sql.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { SQL, Name } from 'drizzle-orm';
|
|
2
|
+
import { S as SqlExec, a as SqlCursor, R as RangeOperandType, W as WhereInput, b as SqlEngine, c as RenderedSql } from "./packem_shared/sql-engine.d-DN1kL76Y.js";
|
|
3
|
+
import '@lunora/errors';
|
|
4
|
+
declare const runDrizzle: <Row = Record<string, unknown>>(exec: SqlExec, query: SQL) => SqlCursor<Row>;
|
|
5
|
+
interface WhereFragments<T> {
|
|
6
|
+
binary: (reference: T, comparator: string, value: unknown) => T;
|
|
7
|
+
connect: (left: T, right: T, connector: "AND" | "OR") => T;
|
|
8
|
+
constant: (value: boolean) => T;
|
|
9
|
+
contains: (reference: T, term: T) => T;
|
|
10
|
+
inList: (reference: T, items: ReadonlyArray<unknown>, negated: boolean, budget: number) => T;
|
|
11
|
+
negate: (inner: T) => T;
|
|
12
|
+
nullCheck: (reference: T, negated: boolean) => T;
|
|
13
|
+
value: (value: unknown) => T;
|
|
14
|
+
}
|
|
15
|
+
type FieldRefSql<T> = (field: string) => T;
|
|
16
|
+
type SerializeValue = (value: unknown, field: string) => unknown;
|
|
17
|
+
interface WhereSqlStrategy<T = SQL> {
|
|
18
|
+
containsExpr?: (reference: T, term: T) => T;
|
|
19
|
+
fieldRef: FieldRefSql<T>;
|
|
20
|
+
inList?: (reference: T, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => T;
|
|
21
|
+
rangeTypeGuard: (field: string, type: RangeOperandType) => T;
|
|
22
|
+
relationExists?: (request: unknown) => T;
|
|
23
|
+
serialize: SerializeValue;
|
|
24
|
+
}
|
|
25
|
+
declare const serverInList: (engine: "mysql" | "postgres") => (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
|
|
26
|
+
declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>, reservedParams?: number) => T | undefined;
|
|
27
|
+
declare const jsonPathSql: (field: string) => SQL;
|
|
28
|
+
declare const qualifiedJsonPathSql: (table: string, field: string) => SQL;
|
|
29
|
+
declare const createIndexSql: (name: string, table: string, columns: SQL, unique: boolean) => SQL;
|
|
30
|
+
declare const AGG_KEY: Name;
|
|
31
|
+
declare const AGG_VALUE: Name;
|
|
32
|
+
declare const AGG_COUNT: Name;
|
|
33
|
+
declare const aggUpsertSql: (aggTable: string, key: unknown, value: unknown, count: unknown, set: SQL) => SQL;
|
|
34
|
+
declare const renderSql: (engine: SqlEngine, query: SQL) => RenderedSql;
|
|
35
|
+
declare const param: (value: unknown) => SQL;
|
|
36
|
+
declare const unionAll: (branches: ReadonlyArray<SQL>) => SQL;
|
|
37
|
+
declare const sqliteInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
|
|
38
|
+
interface FtsWriteOptions {
|
|
39
|
+
guard?: SQL;
|
|
40
|
+
unmappedRowids?: ReadonlyArray<number>;
|
|
41
|
+
}
|
|
42
|
+
declare const ftsCompanionDdl: (companion: string) => SQL[];
|
|
43
|
+
declare const ftsWriteDocument: (companion: string, id: string, text: string, options?: FtsWriteOptions) => SQL[];
|
|
44
|
+
declare const ftsPurgeDocument: (companion: string, id: string, options?: FtsWriteOptions) => SQL[];
|
|
45
|
+
declare const ftsUnmappedPage: (companion: string, limit: number, after?: number) => SQL;
|
|
46
|
+
declare const rankPivotConditionSql: (column: string, value: unknown, direction: "asc" | "desc", wantLater: boolean) => SQL | undefined;
|
|
47
|
+
export { AGG_COUNT, AGG_KEY, AGG_VALUE, type FtsWriteOptions, type WhereSqlStrategy, aggUpsertSql, compileWhereSql, createIndexSql, ftsCompanionDdl, ftsPurgeDocument, ftsUnmappedPage, ftsWriteDocument, jsonPathSql, param, qualifiedJsonPathSql, rankPivotConditionSql, renderSql, runDrizzle, serverInList, sqliteInList, unionAll };
|
package/dist/sql.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{runDrizzle as o}from"./packem_shared/runDrizzle-DAtZbzBn.mjs";import{AGG_COUNT as a,AGG_KEY as s,AGG_VALUE as n,aggUpsertSql as l,createIndexSql as f,jsonPathSql as i,qualifiedJsonPathSql as m}from"./packem_shared/AGG_COUNT-DzvM-UU5.mjs";import{param as q,renderSql as d,sqliteInList as u,unionAll as x}from"./packem_shared/param-Y0zw_1Cv.mjs";import{f as c,a as G,b as A,c as P}from"./packem_shared/fts-companion-Cfz-hJum.mjs";import{default as D}from"./packem_shared/rankPivotConditionSql-CUX4Vuhv.mjs";import{c as h,s as C}from"./packem_shared/where-sql-AVR5KloI.mjs";export{a as AGG_COUNT,s as AGG_KEY,n as AGG_VALUE,l as aggUpsertSql,h as compileWhereSql,f as createIndexSql,c as ftsCompanionDdl,G as ftsPurgeDocument,A as ftsUnmappedPage,P as ftsWriteDocument,i as jsonPathSql,q as param,m as qualifiedJsonPathSql,D as rankPivotConditionSql,d as renderSql,o as runDrizzle,C as serverInList,u as sqliteInList,x as unionAll};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.214",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -42,6 +42,10 @@
|
|
|
42
42
|
"types": "./dist/conformance/index.d.ts",
|
|
43
43
|
"import": "./dist/conformance/index.mjs"
|
|
44
44
|
},
|
|
45
|
+
"./sql": {
|
|
46
|
+
"types": "./dist/sql.d.ts",
|
|
47
|
+
"import": "./dist/sql.mjs"
|
|
48
|
+
},
|
|
45
49
|
"./package.json": "./package.json"
|
|
46
50
|
},
|
|
47
51
|
"publishConfig": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./effective-kind-BmG_zCAy.mjs";import"./json-field-path-DeJW4U9z.mjs";import{A as l,a as n,b as i,D as d,n as p,W as u,c as m,d as q,l as S,s as G,m as c,k as A,g as D,i as f,j as _,e as h,p as P,v as T,q as g,f as j,r as y,t as C,h as O,u as b}from"./do-sql-Cf2rnuLV.mjs";import{quoteIdentifier as E}from"./quoteIdentifier-CObIFRhb.mjs";import"./runDrizzle-RC09zZrh.mjs";import{serializeSqlValue as J}from"./serializeSqlValue-DeoBMpZ2.mjs";import"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";export{l as AGG_COUNT,n as AGG_KEY,i as AGG_VALUE,d as DOC_COLUMN,p as DOC_ORIGINALS_KEY,u as WRAPPED_SQL,m as aggUpsertSql,q as createIndexSql,S as decodeDocJson,G as decodeGroupKeyValue,c as doWhereSqlStrategy,A as encodeDocJson,D as geoTableName,f as isFtsAvailable,_ as jsonPath,h as jsonPathSql,P as jsonTypeGuard,T as jsonTypeGuardSql,g as qualifiedJsonPath,j as qualifiedJsonPathSql,E as quoteIdentifier,y as rowToDocument,J as serializeSqlValue,C as tableColumns,O as tryRowToDocument,b as unwrapSql};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{compareStrings as a,encodeAggregateKey as f}from"./aggregateTableName-B_CtIQCS.mjs";import{runDrizzle as r}from"./runDrizzle-RC09zZrh.mjs";import{sqliteInList as T}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const n="__lunora_companion_state",c=1,g=2,E=i=>i?f(Object.keys(i),i):"",O=(i,t)=>JSON.stringify([c,(i.by??[]).toSorted(a),i.field??"",i.op,E(i.where),t??""]),$=(i,t)=>JSON.stringify([g,(i.partitionBy??[]).toSorted(a),i.sortBy.map(o=>o.field),E(i.where),t??""]),s=i=>{r(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("signature")} TEXT NOT NULL)`)},u=(i,t)=>{s(i),r(i,t.length===0?e`DELETE FROM ${e.identifier(n)}`:e`DELETE FROM ${e.identifier(n)} WHERE ${T(e.raw('"companion"'),t,!0)}`)},R=(i,t)=>r(i,e`SELECT ${e.identifier("signature")} FROM ${e.identifier(n)} WHERE ${e.identifier("companion")} = ${t}`).toArray()[0]?.signature,A=(i,t,o)=>{r(i,e`INSERT INTO ${e.identifier(n)} (${e.identifier("companion")}, ${e.identifier("signature")}) VALUES (${t}, ${o}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("signature")} = excluded.${e.identifier("signature")}`)},N=i=>{s(i),r(i,e`DELETE FROM ${e.identifier(n)}`)};class L{verified=new Set;invalidate(){this.verified.clear()}}export{L as CompanionMemo,O as aggregateSignature,N as clearCompanionSignatures,u as migrateCompanionState,$ as rankSignature,R as readCompanionSignature,A as writeCompanionSignature};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as p}from"@lunora/errors";import{encodeWire as L,decodeWire as $}from"@lunora/wire";import{runSql as n}from"./runDrizzle-RC09zZrh.mjs";const T="__lunora_import_stage__",d="__lunora_import_session__",c="__lunora_import_manifest__",N=1440*60*1e3,f=3600*1e3,A=600*1e3,P=/^[\w-]{1,64}$/u,D=new Set(["committed","staging"]),C=new Set(["aborting","committed","committing","open"]),a=(t,e)=>new p(t,e,{status:409}),G=t=>{if(typeof t!="string"||!P.test(t))throw new p("BAD_REQUEST","an import session id is 1-64 characters of [A-Za-z0-9_-]",{status:400});return t},I=t=>{n(t,`CREATE TABLE IF NOT EXISTS "${T}" (seq INTEGER PRIMARY KEY AUTOINCREMENT, session TEXT NOT NULL, tbl TEXT NOT NULL, id TEXT, line INTEGER NOT NULL, doc TEXT NOT NULL)`),n(t,`CREATE INDEX IF NOT EXISTS "${T}_by_session" ON "${T}" (session, seq)`),n(t,`CREATE TABLE IF NOT EXISTS "${d}" (session TEXT PRIMARY KEY, state TEXT NOT NULL, generation TEXT NOT NULL, expires_at INTEGER NOT NULL, result TEXT)`),n(t,`CREATE TABLE IF NOT EXISTS "${c}" (session TEXT PRIMARY KEY, state TEXT NOT NULL, expires_at INTEGER NOT NULL, manifest TEXT NOT NULL)`)},O=t=>typeof t=="number"&&Number.isInteger(t)&&t>=0,m=t=>Array.isArray(t)&&t.every(e=>typeof e=="string"),M=t=>{let e;try{e=JSON.parse(t)}catch{return}const s=e;if(!(s===null||typeof s!="object"||typeof s.session!="string"||typeof s.generation!="string"||typeof s.state!="string"||!C.has(s.state)||typeof s.expiresAt!="number"||!O(s.batches)||!O(s.pending)||!O(s.rejected)||!O(s.received)||typeof s.globals!="boolean"||typeof s.storage!="boolean"||!m(s.sections)||!m(s.shards)||!m(s.tables)||typeof s.steps!="object"||s.steps===null))return s},_=(t,e)=>{I(t);const s=n(t,`SELECT state, generation, result FROM "${d}" WHERE session = ?`,e).toArray()[0];if(s===void 0)return;if(!D.has(s.state))throw a("IMPORT_SESSION_CORRUPT",`import session "${e}" has an unreadable state on this shard`);const o=s.state;return s.result===null?{generation:s.generation,state:o}:{generation:s.generation,result:JSON.parse(s.result),state:o}},g=(t,e)=>{n(t,`DELETE FROM "${T}" WHERE session = ?`,e),n(t,`DELETE FROM "${d}" WHERE session = ?`,e)},B=(t,e)=>{I(t),n(t,`DELETE FROM "${T}" WHERE session IN (SELECT session FROM "${d}" WHERE expires_at < ? AND state IN ('staging', 'committed'))`,e),n(t,`DELETE FROM "${d}" WHERE expires_at < ? AND state IN ('staging', 'committed')`,e);const s=[];for(const o of n(t,`SELECT session, manifest FROM "${c}" WHERE expires_at < ?`,e)){const i=M(o.manifest);i===void 0||i.state==="committing"||(i.state!=="committed"&&_(t,o.session)?.generation===i.generation&&g(t,o.session),n(t,`DELETE FROM "${c}" WHERE session = ?`,o.session),s.push(i))}return s},h=(t,e,s)=>{if(t!==void 0&&t.generation!==s)throw a("IMPORT_SESSION_STALE",`import session "${e}" on this shard belongs to an earlier session of the same id`)},J=(t,e,s,o,i)=>{const r=_(t,e);if(h(r,e,s),r?.state==="committed")throw a("IMPORT_SESSION_COMMITTED",`import session "${e}" is already committed`);n(t,`INSERT INTO "${d}" (session, state, generation, expires_at) VALUES (?, 'staging', ?, ?) ON CONFLICT (session) DO UPDATE SET expires_at = excluded.expires_at`,e,s,i+N);const E={};for(const S of o){const l=S.doc._id;n(t,`INSERT INTO "${T}" (session, tbl, id, line, doc) VALUES (?, ?, ?, ?, ?)`,e,S.table,typeof l=="string"?l:null,S.line,JSON.stringify(L(S.doc))),E[S.table]=(E[S.table]??0)+1}return E},v=(t,e,s)=>{n(t,`UPDATE "${d}" SET expires_at = ? WHERE session = ?`,s+N,e)},Y=(t,e,s)=>{I(t);let o="substr(tbl, 1, 1) <> '$'";s.sections!==void 0&&(o=s.sections.length===0?"0":`tbl IN (${s.sections.map(()=>"?").join(", ")})`);const i=n(t,`SELECT seq, tbl, line, doc FROM "${T}" WHERE session = ? AND seq > ? AND ${o} ORDER BY seq LIMIT ?`,e,s.afterSeq,...s.sections??[],s.limit).toArray();return{rows:i.map(r=>({doc:$(JSON.parse(r.doc)),line:r.line,table:r.tbl})),seq:i.at(-1)?.seq??s.afterSeq}},V=(t,e)=>new Set(n(t,`SELECT id FROM "${T}" WHERE session = ? AND id IS NOT NULL AND substr(tbl, 1, 1) <> '$'`,e).toArray().map(({id:s})=>s)),K=(t,e,s,o,i)=>{n(t,`DELETE FROM "${T}" WHERE session = ? AND substr(tbl, 1, 1) <> '$'`,e),n(t,`INSERT INTO "${d}" (session, state, generation, expires_at, result) VALUES (?, 'committed', ?, ?, ?) ON CONFLICT (session) DO UPDATE SET state = 'committed', expires_at = excluded.expires_at, result = excluded.result`,e,s,i+N,JSON.stringify(o))},x=(t,e,s)=>{const o=_(t,e);return o!==void 0&&o.generation!==s?!1:(g(t,e),!0)},R=(t,e,s)=>{I(t);const o=n(t,`SELECT manifest FROM "${c}" WHERE session = ?`,e).toArray()[0];if(o===void 0)return;const i=M(o.manifest);if(i===void 0)throw a("IMPORT_SESSION_CORRUPT",`import session "${e}" has a manifest that cannot be read`);return i.state==="open"&&i.expiresAt<s?void 0:i},b=(t,e)=>{n(t,`INSERT INTO "${c}" (session, state, expires_at, manifest) VALUES (?, ?, ?, ?) ON CONFLICT (session) DO UPDATE SET state = excluded.state, expires_at = excluded.expires_at, manifest = excluded.manifest`,e.session,e.state,e.expiresAt,JSON.stringify(e))},y=(t,e)=>{const s=(o,i)=>o.localeCompare(i);return[...t].toSorted(s).join(",")===[...e].toSorted(s).join(",")},U=(t,e)=>({batches:0,expiresAt:0,generation:crypto.randomUUID(),globals:!1,pending:0,received:0,rejected:0,sections:[],session:t,shards:[],state:"open",steps:{},storage:!1,tables:[...e]}),k=(t,e,s,o)=>{const i=R(t,e,o);if(i===void 0&&!s.begin)throw new p("IMPORT_SESSION_NOT_FOUND",`import session "${e}" does not exist or has expired`,{status:404});if(i!==void 0&&i.state!=="open")throw a(i.state==="committed"?"IMPORT_SESSION_COMMITTED":"IMPORT_SESSION_CLOSED",`import session "${e}" is ${i.state==="committed"?"already committed":i.state}`);if(i!==void 0&&!y(i.tables,s.tables))throw new p("IMPORT_SESSION_MISMATCH",`import session "${e}" was opened over other tables`,{status:400});if(i!==void 0&&!s.begin&&i.pending===0)throw a("IMPORT_SESSION_CORRUPT",`import session "${e}" has no staging request in flight to finish`);const r=i??U(e,s.tables),E={...r,batches:r.batches+(s.begin?1:0),expiresAt:o+f,globals:r.globals||s.globals===!0,pending:r.pending+(s.begin?1:-1),received:r.received+(s.received??0),rejected:r.rejected+(s.rejected??0),sections:[...new Set([...r.sections,...s.sections??[]])],shards:[...new Set([...r.shards,...s.shards??[]])],storage:r.storage||s.storage===!0};return b(t,E),{created:i===void 0,manifest:E}},u=(t,e,s,o,i)=>{if(t.steps[e]!==void 0)return a("IMPORT_STEP_DONE",`import session "${t.session}" already ran its ${e} step — send the commit again for its totals`);const r=t.claims?.[e],E=r?.by===s;if(i?!E:r!==void 0&&!E&&r.until>=o)return a("IMPORT_STEP_CLAIMED",`another commit of import session "${t.session}" is running its ${e} step — send the commit again later`)},F=(t,e,s)=>{if(t.state!=="committing")return a("IMPORT_SESSION_NOT_COMMITTING",`import session "${t.session}" is ${t.state}`);if(!("release"in e))return"claim"in e?u(t,e.step,e.claim,s,!1):u(t,e.step,e.claimant,s,!0)},w=(t,e,s)=>"step"in e?F(t,e,s):e.state==="committed"?t.state==="committing"?void 0:a("IMPORT_SESSION_NOT_COMMITTING",`import session "${t.session}" is ${t.state}`):e.state==="aborting"?t.state==="open"||t.state==="aborting"?void 0:a("IMPORT_SESSION_COMMITTING",`import session "${t.session}" is ${t.state} — send the commit again to finish it`):t.state!=="open"?a("IMPORT_SESSION_CLOSED",`import session "${t.session}" is ${t.state}`):t.rejected>0?a("IMPORT_SESSION_REJECTED",`import session "${t.session}" had refused rows or unreachable shards while staging — abort it`):t.pending>0?a("IMPORT_SESSION_INCOMPLETE",`import session "${t.session}" has ${String(t.pending)} staging request(s) that never finished — abort it`):t.batches===e.batches?void 0:a("IMPORT_SESSION_CHANGED",`import session "${t.session}" took another batch after the commit's prepare — commit again`),H=(t,e,s)=>{if(!("step"in e))return{state:e.state};const{[e.step]:o,...i}=t.claims??{};return"claim"in e?{claims:{...i,[e.step]:{by:e.claim,until:s+A}}}:"release"in e?{claims:o===void 0||o.by===e.release?i:{...i,[e.step]:o}}:{claims:i,steps:{...t.steps,[e.step]:e.stepResult}}},z=(t,e,s,o)=>{const i=R(t,e,o);if(i===void 0)throw new p("IMPORT_SESSION_NOT_FOUND",`import session "${e}" does not exist or has expired`,{status:404});const r=w(i,s,o);if(r!==void 0)throw r;const E={...i,...H(i,s,o),expiresAt:o+f};return b(t,E),v(t,e,o),"state"in s&&s.state==="committed"&&n(t,`DELETE FROM "${T}" WHERE session = ? AND substr(tbl, 1, 1) = '$'`,e),E},Q=(t,e,s)=>{const o=R(t,e,s);if(o!==void 0){if(o.state!=="aborting")throw a("IMPORT_SESSION_CLOSED",`import session "${e}" is ${o.state}, not aborting`);x(t,e,o.generation),n(t,`DELETE FROM "${c}" WHERE session = ?`,e)}};export{f as IMPORT_MANIFEST_TTL_MS,N as IMPORT_STAGE_TTL_MS,A as IMPORT_STEP_CLAIM_MS,z as advanceImportManifest,G as assertImportSessionId,Q as dropImportManifest,x as dropImportSession,K as markShardImportCommitted,R as readImportManifest,_ as readShardImportSession,J as stageImportRows,V as stagedImportIds,Y as stagedImportPage,B as sweepImportStaging,k as touchImportManifest,v as touchShardImportSession};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as R}from"@lunora/errors";import{q as Tt}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as Xn,l as Ue,s as Zn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as eo,stableWireKey as Ht}from"@lunora/wire";import{sql as u}from"drizzle-orm";import{throwingScheduler as to,aggregateSqlFunction as je,normalizeCountArgument as Kt}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as dt,encodeAggregateKey as lt,readAggregateValue as ut}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as z,CountRlsUnsupportedError as ft,selectIndexForGroupBy as no,selectIndexForCount as oo,selectIndexForAggregate as ro}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as io,searchIndexCoversTable as so}from"./backfillAggregateIndexes-BfJ2FeLv.mjs";import{backfillAggregateIndexes as ds,backfillRankIndexes as ls,backfillSearchIndexes as us}from"./backfillAggregateIndexes-BfJ2FeLv.mjs";import{appendCdcChange as co,readCdcDocAtOrBefore as ao}from"./CDC_LOG_TABLE-fCPCjSE4.mjs";import{CDC_LOG_TABLE as hs,applyCdcChanges as ws,bumpCdcEpoch as ps,cdcCanVouchFor as gs,cdcForkedError as ys,cdcSeqLeavingRows as $s,cdcTouchesTables as Es,cdcTrimmedError as ms,compactCdcDocs as vs,cursorBelowRetainedFloor as Rs,minCdcReplayableSeq as Ss,minCdcSeq as _s,readCdcChangeKeys as Ts,readCdcChanges as As,readCdcCursor as Is,readCdcEpoch as bs,trimCdcChanges as xs}from"./CDC_LOG_TABLE-fCPCjSE4.mjs";import{allocateCommitSeq as lo,COMMIT_SEQ_FIELD as uo}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as fo}from"./createCompanionSync-DmciS_rv.mjs";import{isMemoryTable as Qt}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as zt}from"./computeRankPage-B6umzbg4.mjs";import{SCAN_DEP as j,PRIMARY_READ as ho}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runSql as $e,runDrizzle as H}from"./runDrizzle-RC09zZrh.mjs";import{p as wo,j as $t,D as oe,r as Me,W as po,k as de,b as Ge,A as ht,a as He,m as ge,e as ye,s as go,t as yo,u as $o,i as Eo,q as Nt,h as Rn,g as mo}from"./do-sql-Cf2rnuLV.mjs";import{renderSql as Sn,unionAll as _n,WORKERD_SQLITE_LIMITS as Tn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as vo,u as Ro}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as So,boundingBoxGeohashes as _o,haversineMeters as To,pointInBoundingBox as Ao}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Io}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as bo,assertPatchAllowed as xo,operatorFields as Co,readPatchField as Vt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as Mo,encodeCursor as Et,nullsOrderSuffix as Do,normalizeOrderKeys as Jt,uniqueIndexFields as ko,buildSeekWhere as Lo,decodeCursor as Yt,buildSeekBeforeWhere as Fo,softDeleteScope as xe,applySelect as An}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as Xt,sortColumnName as Zt,resolveRankPartition as Wo,encodePartitionKey as Bo,RANK_TIEBREAK as qo,rankPivotConditionSql as Po}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as en}from"./ADMIN_WILDCARD-BUrgWQ3-.mjs";import{idIndexKey as Oo,withUnknownIndexKeys as Uo,indexKeysForRow as jo,buildIndexRange as Go}from"./buildIndexRange-BTChxh3k.mjs";import{r as Je,j as De,c as Z,t as Ze,i as tn}from"./where-sql-Cb_dSAMj.mjs";import{serializeSqlValue as ke}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Le}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Ho,isPushableWhere as Ko}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Qo,findRelated as zo}from"./RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{assertFlatPredicate as wt,findManyPage as No,relationPredicateTables as Vo,resolveRelationPredicates as Jo,composeReadPredicate as Yo}from"./DEFAULT_MAX_RELATION_KEYS-xz76_vX6.mjs";import{bindRelationWrites as Xo,describeSchemaRelationWrites as Zo}from"./describeRelationWrites-BKd7YU5R.mjs";import{runRowValidators as Ke,transformOnlyDefinition as er,applyInsertDefaults as mt,resolveWith as tr,relationHooks as nr,applyOnDelete as or,fanOutScalarCounts as rr,CASCADE_MAX_ROWS as ir}from"./applyInsertDefaults-CaVH3fJ7.mjs";import{guardWriter as sr}from"./RLS_UNWRAP_SYMBOL-CWo1Bk9y.mjs";import{mayHoldProjectedValue as cr}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as ar}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as le}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as nn,runTriggers as dr}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ms,migrateClientWatermark as Ds,readClientWatermark as ks}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as Fs,readIdempotent as Ws,trimIdempotent as Bs,writeIdempotent as qs}from"./IDEMPOTENCY_TABLE-BVosXEq_.mjs";import{runShardMigrations as Os}from"./runShardMigrations-4_ene2xR.mjs";import{selectShapeMembers as js,selectShapeRows as Gs}from"./selectShapeMembers-Ce6pOHKe.mjs";const lr=n=>{const i=atob(n),o=Uint8Array.from(i,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},ur=()=>new R("INVALID_CURSOR","invalid cursor"),on=16,rn=8,X=1024,At=(n,i)=>i.query(n),fr=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[s,c]of i.entries()){const f=s===i.length-1;let g=0;for(const E of n)(f?E.startsWith(c):E===c)&&(g+=1);if(g===0)return 0;o+=g}return o},hr=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",s=(o.codePointAt(0)??0)+1;if(s>=55296&&s<=57343||s>1114111)return{exact:!0,lower:n,upper:n};const c=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:c+String.fromCodePoint(s)}},wr=(n,i,o)=>{const s={eq:(c,f)=>{if(!n.definition.filterFields?.includes(c))throw new R("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=rn)throw new R("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(rn)} .eq() filters are supported per search query`);return n.filters.push({field:c,value:f}),s},search:(c,f)=>{const g=n;if(c!==g.definition.field)throw new R("INTERNAL",`search index "${g.indexName}" on table "${i}" indexes "${g.definition.field}", not "${c}"`);const E=At(f,o).length;if(E>on)throw new R("BAD_REQUEST",`search index "${g.indexName}" on table "${i}": at most ${String(on)} search terms are supported (got ${String(E)})`);return g.field=c,g.query=f,g.hasQuery=!0,s}};return s},pr=n=>{if(n.length>X)throw new R("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},gr=n=>Math.min(n.offset+n.numItems+1,X),yr=n=>btoa(`search:${String(n)}`),$r=n=>{let i;try{i=lr(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Er=n=>{if(typeof n.endCursor=="string")throw new R("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new R("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?$r(n.cursor):0;if(o===void 0)throw ur();if(o+i>=X)throw new R("BAD_REQUEST",`search pagination reaches the ${String(X)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,X-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},mr=(n,i)=>{const o=i.offset+i.numItems,s=i.numItems>0&&n.length>o;return{continueCursor:s?yr(o):null,isDone:!s,page:n.slice(i.offset,o)}},vr=n=>{if(n===void 0)return X+1;if(!Number.isFinite(n))return X;const i=Math.max(0,Math.floor(n));if(i>X)throw new R("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},In=500,bn=(n,i,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${i}: batch limit must be a non-negative integer`);return n??In},xn=(n,i,o,s)=>{if(n>i)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},Rr=32,Sr=1024,Cn=(n,i,o,s)=>{const c=`SELECT id, _creationTime, ${Le(oe)} FROM ${Le(n)}`,f=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return i===void 0?Je(`${c} ${f}`):De(`${c} WHERE `,i,` ${f}`)},et={fieldRef:n=>Je($t(n)),rangeTypeGuard:(n,i)=>Je(wo(n,i)),serialize:ke},_r=n=>n===void 0?"":Do(n==="first"),Mn=n=>{const i=n.map(o=>`${$t(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${_r(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${$t("id")} ${Mo(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Tr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Dn=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Ar=n=>{const i=Dn(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Ir=(n,i)=>{const o=n.order,s=Ar(n),{shape:c}=i;return s.length>0?Jt(s.map(f=>({[f]:o})),c,{pinned:Dn(n),uniqueBy:ko(i.indexes,c)}):Jt([{_creationTime:o}],c)},br=(n,i,o,s)=>{const c=n.sqlConditions.map(f=>({[f.field]:{[Tr[f.comparator]??"eq"]:f.value}}));if(o&&c.push(Lo(i,Yt(o))),s&&c.push(Fo(i,Yt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},xr=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Rr):n.want},vt=(n,i,o,s,c,f,g)=>{const E=Ir(s,o),y=Mn(E),h=[],{filters:x,want:T}=f;let A=f.cursor??void 0,C=xr(f);if(T===0)return{documents:h,orderKeys:E};for(;;){const B=Z(br(s,E,A,f.endCursor),et,Ze),P=Cn(i,c&&B?De(B," AND ",c):c??B,y,C),F=$e(n,P.text,...P.params).toArray();let O={};g(F.length);for(const K of F)if(O=Me(K),x.every(ue=>ue(O))&&h.push(O)===T)return{documents:h,orderKeys:E};if(C===void 0||F.length<C)return{documents:h,orderKeys:E};A=Et(O,E),C=Math.max(C,Math.min(C*2,Sr))}},Cr=(n,i,o,s,c,f,g,E)=>{const y=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:B,orderKeys:P}=vt(n,i,o,s,f,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},E),F=B.length>=2?B[Math.floor(B.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:B,splitCursor:F?Et(F,P):null}}const{documents:h,orderKeys:x}=vt(n,i,o,s,f,{cursor:c.cursor,filters:g.all,selective:g.selective,want:y+1},E),T=h.length>y,A=T?h.slice(0,y):h,C=A.at(-1);return{continueCursor:T&&C?Et(C,x):null,isDone:!T,page:A}},tt=n=>{const i=new Map;return o=>{const s=i.get(o);if(s!==void 0)return s;const c=n(Le(o));return i.set(o,c),c}},Ee=Le(oe),Mr=tt(n=>`INSERT INTO ${n} (id, _creationTime, ${Ee}) VALUES (?, ?, ?)`),sn=tt(n=>`UPDATE ${n} SET ${Ee} = ? WHERE id = ? AND ${Ee} = ?`),Dr=tt(n=>`UPDATE ${n} SET _creationTime = ?, ${Ee} = ? WHERE id = ? AND ${Ee} = ?`),kr=tt(n=>`DELETE FROM ${n} WHERE id = ? AND ${Ee} = ?`),Lr="SELECT changes() AS changed",cn=new Map,Fr="",Wr=n=>{const i=JSON.stringify(n),o=cn.get(i);if(o!==void 0)return o;const s=n.map(f=>u`SELECT ${u.raw(`'${f.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${u.identifier(oe)} FROM ${u.identifier(f)} WHERE id = ${Fr}`),{sql:c}=Sn("sqlite",u`${_n(s)} LIMIT 1`);return cn.set(i,c),c},Br=(n,i)=>i.map(()=>n),qr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Pr=n=>{if(!qr.test(n))throw new R("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Rt=n=>{if(n.includes("\0"))throw new R("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},Or=(n,i,o,s)=>{if(o!==!0)return;const c=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const f of i){const g=c?mt(n,f,s)._id:f._id;typeof g=="string"&&Rt(g)}},an=50,Qe=Math.floor(Tn.boundParams/3),dn=Tn.boundParams,Ur=128,Ye=n=>new R("BATCH_LIMIT_EXCEEDED",n,{status:400}),ze=(n,i,o)=>{xn(n,bn(i,o,Ye),o,Ye)},ln=async(n,i,o,s,c)=>{const f=bn(s,c,Ye),{page:g}=await n.findMany(i,Number.isFinite(f)?{limit:f+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>f&&xn(Math.max(await n.count(i,{where:o}),g.length),f,c,Ye),g},jr=n=>{const i={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),i),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),i),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),i),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),i),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),i)};return i},Gr=n=>Math.max(n,X),kn=(n,i)=>{const o=n.filters.map(s=>u`${ye(s.field)} = ${ke(s.value)}`);return i&&o.push(i),o},Hr=(n,i,o,s,c)=>{const f=At(o.query,Tt(o.definition.language));if(f.length===0)return[];const g=Xn(i,o.indexName),E=`${g}__vocab`,y=f.length-1,h=f.map((P,F)=>{const O=hr(P,F===y),K=O.exact?u`${u.identifier("term")} = ${O.lower}`:u`${u.identifier("term")} >= ${O.lower} AND ${u.identifier("term")} < ${O.upper}`;return u`SELECT ${u.identifier("doc")}, ${u.raw(String(F))} AS ${u.identifier("__term__")}, COUNT(*) AS ${u.identifier("__n__")} FROM ${u.identifier(E)} WHERE ${K} GROUP BY ${u.identifier("doc")}`}),x=f.map((P,F)=>u`SUM(CASE WHEN u.${u.identifier("__term__")} = ${u.raw(String(F))} THEN u.${u.identifier("__n__")} ELSE 0 END)`),T=u`SELECT f.${u.identifier(Ue)} AS ${u.identifier(Ue)}, ${u.join(x,u` + `)} AS ${u.identifier("__score__")} FROM (${_n(h)}) u JOIN ${u.identifier(g)} f ON f.rowid = u.${u.identifier("doc")} GROUP BY f.${u.identifier(Ue)} HAVING ${u.join(x.map(P=>u`${P} > 0`),u` AND `)}`,A=kn(o,c);let C=u`SELECT m.id, m._creationTime, m.${u.identifier(oe)}, s.${u.identifier("__score__")} AS ${u.identifier("__score__")} FROM (${T}) s JOIN ${u.identifier(i)} m ON m.id = s.${u.identifier(Ue)}`;A.length>0&&(C=u`${C} WHERE ${u.join(A,u` AND `)}`),C=u`${C} ORDER BY s.${u.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${u.raw(String(s))}`;const B=[];for(const P of H(n,C)){const F=Rn(P);if(F){const O=P.__score__;B.push({document:F,score:typeof O=="number"?O:Number(O??0)})}}return B},Kr=(n,i,o,s,c)=>{const f=Tt(o.definition.language),g=At(o.query,f);if(g.length===0)return[];const E=kn(o,c);let y=u`SELECT id, _creationTime, ${u.identifier(oe)} FROM ${u.identifier(i)}`;E.length>0&&(y=u`${y} WHERE ${u.join(E,u` AND `)}`),y=u`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${u.raw(String(Gr(s)))}`;const h=H(n,y).toArray(),x=[];for(const T of h){const A=Rn(T);if(!A)continue;const C=fr(Zn(A,o.definition),g);C>0&&x.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:C})}return x.sort((T,A)=>A.score-T.score||A.creationTime-T.creationTime||T.id.localeCompare(A.id)),x.slice(0,s).map(T=>({document:T.doc,score:T.score}))},pt=(n,i,o,s)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new R("BAD_REQUEST",`geo index "${s}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Qr=(n,i)=>{const o=n,s={near:(c,f)=>{if(o.within)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(pt(c,".near() point",i,o.indexName),!Number.isFinite(f)||f<=0)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(f)}`);return o.near={point:{lat:c.lat,lng:c.lng},radiusMeters:f},s},within:c=>{if(o.near)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(pt(c.sw,".within() sw corner",i,o.indexName),pt(c.ne,".within() ne corner",i,o.indexName),c.sw.lat>c.ne.lat)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},s}};return s},zr=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:s,lng:c}=o;return typeof s=="number"&&typeof c=="number"?{lat:s,lng:c}:void 0},Nr=(n,i)=>{const o=zr(n,i.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const c=To(i.near.point,o);return c<=i.near.radiusMeters?{creationTime:s,distance:c}:void 0}return Ao(o,i.within)?{creationTime:s,distance:0}:void 0},Vr=(n,i,o,s)=>{if(!o.near&&!o.within)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const c=o.near?So(o.near.point,o.near.radiusMeters):_o(o.within),f=mo(i,o.indexName),g=c.map(T=>u`(g.${u.identifier("__geohash__")} >= ${T} AND g.${u.identifier("__geohash__")} < ${`${T}{`})`),E=[u`(${u.join(g,u` OR `)})`];s&&E.push(s);const y=u`SELECT m.id, m._creationTime, m.${u.identifier(oe)} FROM ${u.identifier(f)} g JOIN ${u.identifier(i)} m ON m.id = g.${u.identifier("__id__")} WHERE ${u.join(E,u` AND `)}`,h=H(n,y).toArray(),x=[];for(const T of h){const A=Me(T),C=A?Nr(A,o):void 0;A&&C&&x.push({creationTime:C.creationTime,distance:C.distance,doc:A})}return x.sort((T,A)=>T.distance-A.distance||A.creationTime-T.creationTime),x},Ln=(n,i,o,s)=>{const c=[];for(const f of n)if(i.every(g=>g(s(f)))&&(c.push(f),typeof o=="number"&&c.length>=o))break;return c},Jr=(n,i,o,s,c,f=()=>{})=>{const g=o.within!==void 0,E=Vr(n,i,o,c).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return f(E.length),typeof s=="number"?E.slice(0,Math.max(0,Math.floor(s))):E},un=(n,i,o,s,c,f,g=()=>{})=>{const{geo:E}=o;if(!E)throw new R("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=c.length>0,h=Jr(n,i,E,y?void 0:f,s,g);return y?Ln(h,c,f,x=>x.document):h},fn=(n,i,o)=>{const s=n.shape[i];if(s!==void 0&&cr(s))throw new R("BAD_REQUEST",`${o}: "${i}" 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)`)},Yr=n=>{let i=0;const o=[],s={...et,relationExists:c=>{const{childWhere:f,negated:g,parentTable:E,relation:y}=c,h=`__rel_${String(i)}`,x=o.at(-1)??E;i+=1,n(y.table,j);const T=y.kind==="one"?y.field:y.references,A=y.kind==="one"?y.references:y.field,C=Je(`${Nt(h,A)} = ${Nt(x,T)}`);o.push(h);const B=Z(f,s,Ze);o.pop();const P=B===void 0?C:De(C," AND ",B),F=De("EXISTS (SELECT 1 FROM ",tn(y.table)," AS ",tn(h)," WHERE ",P,")");return g?De("NOT ",F):F}};return s};class Xr extends R{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const Zr=/\s/u,ei=String.fromCodePoint(0),hn=(n,i,o)=>{if(!n.tables[i])throw new R("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||Zr.test(o)||o.includes(ei)?null:o},Fn=(n,i,o,s=()=>{},c=()=>{},f=()=>{},g)=>{const E=i.tables[o];if(!E)throw new R("INTERNAL",`unknown table: ${o}`);const y=xe(E.softDeleteMode,void 0),h=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},x=()=>{const S=z(y,h.pushedWhere);return S?Z(S,ge):void 0},T=()=>{const S=z(y,h.pushedWhere);return S?Z(S,et,Ze):void 0},A=()=>[...h.inMemoryFilters,...h.verifyFilters];let C=0;const B=S=>{const{search:M}=h;if(!M)throw new R("INTERNAL","runSearchFetch called without a staged search");io($o(n),o,E);const k=h.inMemoryFilters.length>0,L=vr(k?void 0:S),re=Eo(n);if(re&&!so(n,o,M.definition))throw new R("SEARCH_INDEX_BUILDING",`search index "${M.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const q=x(),ce=re?Hr(n,o,M,L,q):Kr(n,o,M,L,q);!k&&S===void 0&&pr(ce);const ae=A();return C=ce.length,ae.length>0?Ln(ce,ae,S,me=>me.document):ce},P=S=>B(S).map(M=>M.document),F=S=>{const M=Er(S);return mr(P(gr(M)),M)},O=()=>{if(h.search||h.geo||h.indexName===void 0){c(void 0);return}c(Go(o,h.indexName,h.indexFields,h.sqlConditions,ke))},K=S=>{O();let M=0;const k=(()=>{if(h.search){const L=P(S);return M=C,L}return h.geo?un(n,o,h,x(),A(),S,L=>{M=L}).map(L=>L.document):vt(n,o,E,h,T(),{filters:A(),selective:h.inMemoryFilters.length>0,want:S===void 0?void 0:Math.max(0,Math.floor(S))},L=>{M+=L}).documents})();return f(Math.max(M,k.length)),k},ue=()=>{if(!h.search&&!h.geo)throw new R("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);O();let S=0;const M=(()=>{if(h.search){const k=B(void 0);return S=C,k}return un(n,o,h,x(),A(),void 0,k=>{S=k})})();return f(Math.max(S,M.length)),M},N={async*[Symbol.asyncIterator](){const S=Fn(n,i,o,s,c,f,{...h,indexFields:[...h.indexFields],inMemoryFilters:[...h.inMemoryFilters],sqlConditions:[...h.sqlConditions],verifyFilters:[...h.verifyFilters]});if(h.search){yield*await S.collect();return}let M;for(;;){const k=await S.paginate({cursor:M??null,numItems:Ur});if(yield*k.page,k.isDone||k.continueCursor===null)return;M=k.continueCursor}},async collect(){return K(void 0)},async collectWithScores(){return ue()},filter(S){const M=Ho(S);return M!==void 0&&Ko(M,E.shape)?(h.pushedWhere=z(h.pushedWhere,M),h.verifyFilters.push(S)):h.inMemoryFilters.push(S),N},async first(){return K(1)[0]??null},order(S){return h.order=S==="desc"?"desc":"asc",N},async paginate(S){let M=0;if(O(),h.search){const L=F(S);return f(L.page.length),L}if(h.geo)throw new R("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const k=Cr(n,o,E,h,S,T(),{all:A(),selective:h.inMemoryFilters.length>0},L=>{M+=L});return f(Math.max(M,k.page.length)),k},async take(S){return K(S)},async unique(){const S=K(2);if(S.length>1)throw new Xr(`unique() on table "${o}" matched ${String(S.length)} documents; expected at most one`);return S[0]??null},withGeoIndex(S,M){const k=(E.geoIndexes??[]).find(re=>re.name===S);if(!k)throw new R("INTERNAL",`unknown geo index "${S}" on table "${o}"`);s(o,S,"geo");const L={definition:k,indexName:S};if(h.geo=L,M(Qr(L,o)),!L.near&&!L.within)throw new R("INTERNAL",`geo index "${S}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(S,M){const k=E.indexes.find(L=>L.name===S);if(!k)throw new R("INTERNAL",`unknown index "${S}" on table "${o}"`);return s(o,S,"index"),h.indexName=S,h.indexFields=k.fields,M&&M(jr(h)),N},withSearchIndex(S,M){const k=(E.searchIndexes??[]).find(re=>re.name===S);if(!k)throw new R("INTERNAL",`unknown search index "${S}" on table "${o}"`);s(o,S,"search");const L={definition:k,field:k.field,filters:[],hasQuery:!1,indexName:S,query:""};if(h.search=L,M(wr(L,o,Tt(k.language))),!L.hasQuery)throw new R("INTERNAL",`search index "${S}" on table "${o}" requires a .search(field, query) call`);return N}};return N},gt=(n,i,o,s)=>{const c=o;for(const[f,g]of yo(n)){if(g.serverDefault){f in i&&(c[f]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(f in i)&&(c[f]=g.onUpdateFn())}},wn=5,pn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new R("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},gn=["_commitSeq","_creationTime","_id"],Ne=n=>gn.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!gn.includes(i))):n,ti=/unique constraint failed/i,ni=n=>n instanceof Error&&ti.test(n.message),oi=/string or blob too big/iu,ri=(n,i)=>{if(!(!(n instanceof Error)||!oi.test(n.message)))throw new R("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},St=(n,i,o,s)=>{try{$e(n,o,...s)}catch(c){throw ni(c)?new le(`unique constraint violation on "${i}"`,"unique"):(ri(c,i),c)}},Ve=(n,i,o,s)=>{if(St(n,i,o,s),$e(n,Lr).one().changed===0)throw new le(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},yn=(n,i,o,s,c,f,g)=>{const E=[];for(let T=0;T<o.length+1;T+=1){const A=o[T],C=s[T],B=C?.direction==="desc"?"desc":"asc",P=A===void 0||C===void 0?u`${u.identifier(qo)} < ${g}`:Po(A,f[T],B,!1);if(P===void 0)continue;const F=[];for(let K=0;K<T;K+=1)F.push(u`${u.identifier(o[K])} IS ${f[K]}`);F.push(P);const[O]=F;E.push(F.length===1&&O!==void 0?O:u`(${u.join(F,u` AND `)})`)}const y=E.length>0?u.join(E,u` OR `):u`1 = 0`,h=H(n,u`SELECT COUNT(*) AS c FROM ${u.identifier(i)} WHERE ${u.identifier("__partition__")} = ${c} AND (${y})`).one(),x=H(n,u`SELECT COUNT(*) AS c FROM ${u.identifier(i)} WHERE ${u.identifier("__partition__")} = ${c}`).one();return{before:h.c,total:x.c}},ii=n=>{const i=new Map;for(const[s,c]of Object.entries(n.tables))for(const f of Object.values(c.relationMap??{}))f.kind==="one"&&(f.onDelete==="cascade"||f.onDelete==="set null")&&i.set(f.table,[...i.get(f.table)??[],{holder:s,op:f.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const c=new Set,f=[s];for(let g=f.pop();g!==void 0;g=f.pop())for(const{holder:E,op:y}of i.get(g)??[]){if(E===s||nn(n,E,y))return!0;c.has(E)||(c.add(E),f.push(E))}return!1};return new Set(Object.entries(n.tables).filter(([s,c])=>c.shardMode?.kind==="global"||nn(n,s,"delete")||o(s)).map(([s])=>s))},si=n=>{const i=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&i.set(o,s.softDeleteMode.field);return i},$n=new WeakMap,ci=n=>{const i=Object.freeze({entries:()=>n.entries(),forEach:(o,s)=>{for(const c of n)o.call(s,c,c,i)},has:o=>n.has(o),keys:()=>n.keys(),get size(){return n.size},values:()=>n.values(),[Symbol.iterator]:()=>n.values()});return i},ai=n=>{const i=Object.freeze({entries:()=>n.entries(),forEach:(o,s)=>{for(const[c,f]of n)o.call(s,f,c,i)},get:o=>n.get(o),has:o=>n.has(o),keys:()=>n.keys(),get size(){return n.size},values:()=>n.values(),[Symbol.iterator]:()=>n.entries()});return i},di=n=>{const i=$n.get(n);if(i!==void 0)return i;const o=Object.freeze(Qo(n).map(g=>Object.freeze(g))),s=new Map,c=g=>(n.tables[g]?.shardMode?.kind??"root")==="root";for(const g of o)!g.array&&c(g.sourceTable)&&c(g.targetTable)&&s.set(g.sourceTable,[...s.get(g.sourceTable)??[],g]);for(const g of s.values())Object.freeze(g);const f={checkedForeignKeys:s,deleteRereadTables:ci(ii(n)),relationEdges:o,relationWrites:Zo(n),softDeleteFields:ai(si(n))};return $n.set(n,f),f},yt=new WeakMap,li=(n,i)=>{let o=yt.get(i.tables);if(!yt.has(i.tables)){const c=Object.keys(i.tables).map(f=>f.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=c.length===0?void 0:new RegExp(`"(${c.join("|")})"`,"gu"),yt.set(i.tables,o)}if(o===void 0)return;const s=new Set;for(const c of n.matchAll(o))s.add(c[1]);return s.size===1?[...s][0]:void 0},ui=(n,i,o)=>{for(const s of n){const c=s,f=c?.[oe];if(typeof f=="string"){const g=c?.id,E=Ro(f);typeof g!="string"?i.recordReadBytes(E):o===void 0?i.recordDocumentRead(`${g}\0${String(E)}`,E):i.recordDocumentRead(`${o}\0${g}`,E)}}},fi=(n,i,o)=>{if(i===void 0)return n;const s=(c,...f)=>{const g=n.exec(c,...f),E=g.one.bind(g),y=g[Symbol.iterator].bind(g),h=o===void 0?void 0:li(c,o);let x=!1;const T=A=>{ui(A,i,h)};return g.toArray=()=>{const A=[];for(const C of{[Symbol.iterator]:y})T([C]),A.push(C);return A},g.one=()=>{x=!0;try{const A=E();return T([A]),A}finally{x=!1}},g[Symbol.iterator]=function*(){for(const C of{[Symbol.iterator]:y})x||T([C]),yield C},g};return new Proxy(n,{get:(c,f)=>f==="exec"?s:f===po?c:Reflect.get(c,f,c)})},hi=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),wi=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),Ce=(n,i,o)=>{if(typeof n!="object"||n===null)return;const s=vo(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${i}\0${c}`,s):o.recordReadBytes(s)},Xe=(n,i,o,s)=>{if(typeof n!="object"||n===null)return;const c=n;switch(i){case"lookup":{Ce(c.row,typeof c.tableName=="string"?c.tableName:o,s);return}case"page":{for(const f of c.page??[])Ce(f,o,s);return}case"rows":{for(const f of Array.isArray(n)?n:[n])Ce(f,o,s);return}default:for(const f of Array.isArray(n)?n:[])Ce(f.document,o,s)}},Wn=(n,i,o)=>new Proxy(n,{get:(s,c)=>{const f=Reflect.get(s,c,s);if(typeof f!="function")return f;if(c===Symbol.asyncIterator)return async function*(){for await(const y of Reflect.apply(f,s,[]))Ce(y,i,o),yield y};const g=wi.get(c);return(...E)=>{const y=Reflect.apply(f,s,E);return g!==void 0?Promise.resolve(y).then(h=>(Xe(h,g,i,o),h)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?Wn(y,i,o):y}}}),pi=new Set(["findFirst","findFirstOrThrow","findMany"]),gi=n=>{const i=n[1],o=i?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(i).filter(([g])=>g!=="select")),c=s.with,f=g=>An(g,o,c);return{args:[n[0],s,...n.slice(2)],project:(g,E)=>typeof g!="object"||g===null?g:E==="page"?{...g,page:f(g.page)}:f([g])[0]}},En=256,_t=4096,yi=1024*1024,$i=async(n,i,o,s)=>{const c=i[1]??{},f=[];let{cursor:g}=c,E=En,y=0;for(;;){const h=await n([i[0],{...c,cursor:g,limit:E},...i.slice(2)]);if(Array.isArray(h))return Xe(h,"rows",o,s),[...f,...h];const x=s.headroom().readBytes;if(Xe(h,"page",o,s),f.push(...h.page),h.isDone||typeof h.continueCursor!="string")return{continueCursor:null,isDone:!0,page:f};g=h.continueCursor,y+=s.headroom().readBytes-x,E=y>0?Math.min(_t,Math.max(En,Math.floor(yi*f.length/y))):_t}},Ei=(n,i)=>n===void 0||i===void 0?n:new Proxy(n,{get:(o,s)=>{const c=Reflect.get(o,s,o);if(typeof c!="function")return c;if(s==="query")return(...g)=>Wn(Reflect.apply(c,o,g),String(g[0]),i);const f=hi.get(s);return f===void 0?c:async(...g)=>{const E=pi.has(s)?gi(g):void 0;let y=E?.args??g;const h=String(g[0]),x=y[1],T=s==="findMany"&&typeof x?.endCursor=="string",A=s==="findMany"&&typeof x?.limit!="number"&&!T;if(T&&typeof x.limit!="number"&&(y=[y[0],{...x,limit:_t},...y.slice(2)]),A){const B=await $i(P=>Reflect.apply(c,o,P),y,h,i);return E===void 0?B:E.project(B,f)}const C=await Reflect.apply(c,o,y);return Xe(C,f,h,i),E===void 0?C:E.project(C,f)}}}),mn=new WeakMap,vn=new WeakMap,mi=500,vi=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{headroom:s}=n,c=mn.get(n)??{value:void 0},f=vn.get(n)??{value:0};let g;const E=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};mn.set(e,c),vn.set(e,f),g=vi(e)}return g},y=fi(n.sql,s,n.schema),{schema:h}=n,x=n.broadcast??(()=>{}),T=(e,t)=>{if(!Object.hasOwn(h.tables,e))throw new R("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},{checkedForeignKeys:A,deleteRereadTables:C,relationEdges:B,relationWrites:P,softDeleteFields:F}=di(h),O=(e,t,r)=>{for(const a of A.get(e)??[]){const l=t[a.column];if(typeof l!="string"||r?.[a.column]===l||a.targetTable===e&&t._id===l)continue;if(H(y,u`SELECT 1 FROM ${u.identifier(a.targetTable)} WHERE id = ${l} LIMIT 1`).toArray().length===0)throw new R("VALIDATION_ERROR",`${a.name} references ${a.targetTable} row "${l}", which does not exist`)}},K=Xo(P,n.inTransaction),ue=()=>n.inTransaction?.()===!0,N=e=>h.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!ue())&&(c.value=lo(y)),{[uo]:c.value}),S=(e,...t)=>{const r=h.tables[e]?.indexes??[],a=[];let l;for(const p of t)p&&(typeof p._id=="string"&&p._id!==l&&(l=p._id,a.push(Oo(l))),a.push(...Uo(r,jo(r,p,ke))));return a.length>0?a:void 0},M=n.onRead??(()=>{}),k=e=>{Qt(h.tables[e])&&M(en,en)},L=n.onReadRange??(e=>{M(e.table,j)}),re=e=>{k(e.table),L(e)},q=(e,t,r)=>{t!==void 0&&(r===!0||t!==j)&&s?.recordRead(1),k(e),M(e,t,r)},ce=(e,t)=>{const r=e.row._id;q(e.tableName,typeof r=="string"?r:t,typeof r=="string")},ae=n.onIndexUse??(()=>{}),me=n.onWrite??(()=>{}),ee=e=>{s?.recordWrite(e)},ve=async e=>{ee(e.doc),await me(e)},{cache:fe}=n,Re=n.clock??(()=>Date.now()),It=n.idGenerator??(()=>crypto.randomUUID()),bt=n.scheduler??to,Se=Ei(n.globalDb,s),he=n.auth??{identity:null,userId:null},xt=n.cdc??!1,nt=bt,Bn=ar({scheduler:typeof nt.list=="function"&&typeof nt.get=="function"?nt:void 0,storage:n.storage}),_e=(e,t,r,a)=>{xt&&!Qt(h.tables[e])&&co(y,Re(),e,t,r,a)},Ct=(e,t,r,a)=>{const l=h.tables[e];if(l?.dropStalePatchesMode!==!0||!xt)return!1;const p=i?.();if(p===void 0)return!1;const d=ao(y,e,t,p);if(d===void 0)return!1;const w=Co(l,r);return Object.keys(Ne(r)).some(m=>!w.has(m)&&Ht(Vt(d,m))!==Ht(Vt(a,m)))},ie=e=>h.tables[e]?.shardMode?.kind==="global",Mt=(e,t)=>{if(ie(e)){if(!Se)throw new R("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return Se}return U},ot=e=>Mt(e,"cascade"),G=(e,t)=>{if(ie(e)){if(!Se)throw new R("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return Se}},Te=(e,t)=>{q(e,j);for(const r of Vo(z(t.baseWhere,t.where),h,e,t.relationBaseWhere))q(r,j)},se=(e,t,r)=>{fe?.invalidateTable(t),x({key:r,op:e,table:t})},Dt=async(e,t,r,a,l)=>{l&&ee(r);const p=await e.insert(t,r,a);return x({key:p,op:"insert",row:{...r,_id:p},table:t}),p},qn=(e,t)=>Mt(e,"relation load").findMany(e,t),Pn=e=>e.through===void 0?[e.table]:[e.through.table,e.table],kt=e=>{for(const t of e===void 0?[]:Pn(e))ie(t)&&q(t,j)},Lt=(e,t)=>{const r=h.tables[e]?.relationMap??{};for(const[a,l]of Object.entries(t??{})){if(a==="_count"){for(const d of Object.keys(typeof l=="object"?l:{}))kt(r[d]);continue}const p=r[a];p===void 0||l===void 0||l===!1||(kt(p),typeof l=="object"&&Lt(p.table,l.with))}},rt=(e,t)=>(ie(e)&&(q(e,j),Lt(e,t.with)),qn(e,t)),On=e=>!ie(e.table),Ft=n.relationExistsPushDown??"auto",Wt=Ft!=="never",{maxRelationKeys:Bt}=n,Fe=(e,t,r)=>Jo(e,{fetcher:rt,maxRelationKeys:Bt,relationBaseWhere:r,schema:h,tableName:t}),Un=async(e,t,r,a,l)=>{const p=G(e,"relation grouped count");if(p)return Te(e,{relationBaseWhere:l,where:a}),rr((W,Q)=>p.count(W,{relationBaseWhere:l,where:Q}),e,t,r,a);const d=h.tables[e];if(!d)throw new R("INTERNAL",`unknown table: ${e}`);q(e,j);const w=xe(d.softDeleteMode,void 0),m={[t]:{in:r}},D=z(z(m,a),w),_=await Fe(D,e,l),b=Z(_,ge),v=ye(t);let I=u`SELECT ${v} AS __fk__, COUNT(*) AS count FROM ${u.identifier(e)}`;b&&(I=u`${I} WHERE ${b}`),I=u`${I} GROUP BY ${v}`;const $=H(y,I).toArray();return new Map($.map(W=>[W.__fk__,W.count]))},qt=new Set;for(const[e,t]of Object.entries(h.tables))for(const r of Object.values(t.triggerMap??{}))qt.add(`${e} ${r.timing} ${r.op}`);const te=(e,t,r)=>qt.has(`${e} ${t} ${r}`),ne=async(e,t,r)=>{if(f.value+=1,f.value>an)throw f.value-=1,new le(`trigger recursion exceeded ${String(an)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await dr({ctx:Jn,event:r,op:t,schema:h,tableName:r.table,timing:e})}finally{f.value-=1}},{ensureBackfilledForTable:Ae,ensureBackfilledIndex:it,ensureRankBackfilled:st,ensureRankBackfilledForTable:Ie,syncAggregates:We,syncCompanionsForInsert:ct,syncGeo:Be,syncRanks:we,syncSearch:qe}=fo({broadcast:x,indexKeysFor:(e,t)=>S(e,t),invalidateCache:(e,t,r)=>fe?.invalidate(e,t,S(e,r)),recordCdc:_e,schema:h,sql:y,verified:n.companionMemo?.verified}),jn=async(e,t)=>{const r=t.filter(({document:a,id:l})=>{try{return ct(e,l,a),!0}catch(p){return console.warn(`[@lunora/shard-engine] insertManyUnsafe: companions of committed row "${l}" in "${e}" could not be synced:`,p),!1}});for(const{document:a,id:l}of r)if(Y(l,e)?.docJson===de(a))try{await me({doc:a,id:l,op:"insert",table:e})}catch(p){console.warn(`[@lunora/shard-engine] insertManyUnsafe: write report of committed row "${l}" in "${e}" failed:`,p)}},Pt=(e,t,r)=>{const{shardMode:a}=t;if(a?.kind==="shardBy"&&!(a.field!==void 0&&(r.partitionBy??[]).includes(a.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${a.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Ot=e=>Object.entries(h.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),be=e=>e===void 0||ie(e)?Se:void 0,Gn=e=>Object.entries(h.tables).flatMap(([t,r])=>ie(t)?Object.values(r.relationMap??{}).flatMap(a=>a.through!==void 0||a.kind!=="one"||a.table!==e?[]:a.onDelete!=="cascade"&&a.onDelete!=="set null"?[]:[{action:a.onDelete==="cascade"?"delete":"update",field:a.field,holderTable:t,references:a.references}]):[]),Hn=async(e,t,r,a)=>r==="_id"?a:(await e.get(t,a))?.[r],Kn=async(e,t,r,a,l)=>{const p=[];let d;do{const w=await e.findMany(t,{cursor:d,includeDeleted:l,limit:mi,where:{[r]:a}});for(const m of w.page)p.push(String(m._id));d=w.isDone?void 0:w.continueCursor??void 0}while(d!==void 0&&p.length<=ir);return p},Qn=async(e,t,r,a,l,p)=>{const{action:d,field:w,holderTable:m,references:D}=r,_=await Hn(e,t,D,a);if(_==null)return{effects:[],toExpand:[]};const b=await Kn(e,m,w,_,p),v=b.filter($=>!l.announced.has(`${d}:${m}:${$}`)),I=d==="delete"?b.filter($=>!l.expanded.has(`${m}:${$}`)):[];for(const $ of v)l.announced.add(`${d}:${m}:${$}`);for(const $ of I)l.expanded.add(`${m}:${$}`);return{effects:v.map($=>({id:$,op:d,table:m})),toExpand:I}},Ut=async(e,t,r,a,l)=>{const p=[];for(const d of Gn(t))for(const w of r){const m=await Qn(e,t,d,w,a,l);p.push(...m.effects),m.toExpand.length>0&&p.push(...await Ut(e,d.holderTable,m.toExpand,a,l))}return p},at=async(e,t,r,a,l)=>{for(let d=0;d<r.length;d+=1)ee(void 0);const p=a?.skipOnDelete===!0?[]:await Ut(e,t,r,{announced:new Set,expanded:new Set},a?.hard===!0);try{if(l!==void 0&&e.deleteMany!==void 0)try{return await e.deleteMany(t,r,l.options)}finally{for(const d of r)se("delete",t,d)}for(const d of r)try{await e.delete(t,d,a)}finally{se("delete",t,d)}return{deleted:r.length}}finally{for(const d of p)se(d.op,d.table,d.id)}},Y=(e,t)=>{const r=Ot(t);for(let a=0;a<r.length;a+=dn){const l=r.slice(a,a+dn),[p]=$e(y,Wr(l),...Br(e,l)).toArray();if(!p)continue;const d=p.__t__,w=Me(p);if(typeof d!="string"||!w)return;const m=p[oe];return{docJson:typeof m=="string"?m:de(m??{}),row:w,tableName:d}}},jt={assertRankPartitionLocal:Pt,ensureRankBackfilled:st,onRead:q,rowToDocument:Me,schema:h,sql:y},zn=(e,t,r)=>{const a=Z(r,ge);return a===void 0||H(y,u`SELECT 1 FROM ${u.identifier(e)} WHERE ${u.identifier("id")} = ${t} AND ${a}`).toArray().length>0},Nn=(e,t,r,a)=>Ct(e,t,r,a)?(o?.({fields:Object.keys(Ne(r)),id:t,table:e}),!0):!1,Vn=async(e,t,r,a,l)=>{const p=Y(t,e);if(!p)return{applied:!1,doc:null};if(q(e,t),!zn(e,t,r.where)||Nn(e,t,r.patch,p.row))return{applied:!1,doc:p.row};try{await l(r.patch)}catch(d){if(d instanceof le&&d.kind==="occ"&&a)return;throw d}return{applied:!0,doc:Y(t,e)?.row??null}},Gt=async(e,t,r,a)=>{const{fetchLimit:l,limit:p,orderKeys:d,predicate:w}=await Yo(t,r,{canPushExists:Wt?On:void 0,existsPushMode:Ft==="always"?"always":"auto",fetcher:rt,maxRelationKeys:Bt,schema:h,tableName:e}),m=Wt?Yr(a):et,D=Z(w,m,Ze),_=Cn(e,D,Mn(d),l);return{limit:p,orderKeys:d,statement:_}},U={system:Bn,async aggregate(e,t){const r=G(e,"aggregate");if(r)return Te(e,t),r.aggregate(e,t);const a=h.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);if(je(t.op),t.op==="count")return U.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new R("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);q(e,j);const l=xe(a.softDeleteMode,void 0),p=z(z(t.baseWhere,t.where),l),d=await Fe(p,e,t.relationBaseWhere),w=d!==p;if(a.aggregateIndexes&&!t.baseWhere&&!w){const $=ro(a.aggregateIndexes,t.op,t.field,t.where);if($){it(e,$.index);const W=lt($.index.by??[],$.key),Q=dt(e,$.index.name),V=H(y,u`SELECT ${Ge} AS value, ${ht} AS count FROM ${u.identifier(Q)} WHERE ${He} = ${W}`).toArray()[0];return ut(t.op,V)}}fn(a,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const m=Z(d,ge),D=je(t.op),_=ye(t.field);let b=u`SELECT ${u.raw(D)}(${_}) AS value FROM ${u.identifier(e)}`;m&&(b=u`${b} WHERE ${m}`);const I=H(y,b).toArray()[0]?.value;return I??null},asId(e,t){const r=hn(h,e,t);if(r===null)throw new R("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=G(e,"count");if(r)return Te(e,Kt(t)),r.count(e,t);const a=h.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);const l=Kt(t);if(l.restrictsCounts)throw new ft(e);q(e,j);const p=xe(a.softDeleteMode,void 0),d=z(z(l.baseWhere,l.where),p),w=await Fe(d,e,l.relationBaseWhere),m=w!==d;if(a.aggregateIndexes&&!l.baseWhere&&!m){const v=oo(a.aggregateIndexes,l.where);if(v){it(e,v.index);const I=lt(v.index.by??[],v.key),$=dt(e,v.index.name),W=H(y,u`SELECT ${Ge} AS value FROM ${u.identifier($)} WHERE ${He} = ${I}`).toArray();return W[0]===void 0?0:W[0].value??0}}const D=Z(w,ge);let _=u`SELECT COUNT(*) AS count FROM ${u.identifier(e)}`;return D&&(_=u`${_} WHERE ${D}`),H(y,_).one().count},async delete(e,t,r){T(e,"ctx.db.delete(table, id)");const a=Y(t,e);if(!a){const v=be(e);v&&await at(v,e,[t],r);return}const{docJson:l,row:p,tableName:d}=a,w=h.tables[d],m=r?.hard===!0,D=!m&&w?.softDeleteMode?w:void 0,_=D?.softDeleteMode?.field;if(_&&p[_]!==null&&p[_]!==void 0)return;if(te(d,"before","delete")&&await ne("before","delete",{id:t,op:"delete",previous:p,table:d}),r?.skipOnDelete!==!0&&await or({deletedId:t,deletedReference:v=>p[v],findHolders:async(v,I,$,W)=>(await ot(v).findMany(v,{...W,includeDeleted:m,where:{[I]:$}})).page,onCascade:(v,I)=>ot(v).delete(v,I,r),onRestrict:v=>{throw new le(v,"restrict")},onSetNull:(v,I,$)=>ot(v).patch(v,I,{[$]:null}),schema:h,tableName:d}),Ae(d),Ie(d),D&&_){const v={[_]:Re()},I={...p,...N(d),...v,_id:t};gt(D,v,I,he),Ve(y,d,sn(d),[de(I),t,l]),qe(d,t,I,p),Be(d,t,void 0),We(d,p,I),we(d,t,p,void 0);const $=S(d,p,I);fe?.invalidate(d,t,$),_e(d,t,"update",I),x({indexKeys:$,key:t,op:"update",row:I,table:d}),te(d,"after","delete")&&await ne("after","delete",{id:t,op:"delete",previous:p,table:d}),await ve({id:t,op:"delete",table:d});return}Ve(y,d,kr(d),[t,l]),qe(d,t,void 0),Be(d,t,void 0),We(d,p,void 0),we(d,t,p,void 0);const b=S(d,p);fe?.invalidate(d,t,b),_e(d,t,"delete"),x({indexKeys:b,key:t,op:"delete",table:d}),te(d,"after","delete")&&await ne("after","delete",{id:t,op:"delete",previous:p,table:d}),await ve({id:t,op:"delete",table:d})},async deleteAll(e,t){if(!h.tables[e])throw new R("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return E().deleteAll(e,t);const r=Math.max(1,t?.chunkSize??In),a=t?.hard===void 0?void 0:{hard:t.hard},l=G(e,"deleteAll");let p=0;for(;;){const w=(await U.findMany(e,{includeDeleted:t?.hard===!0,limit:r})).page.map(m=>String(m._id));if(w.length===0)break;for(const m of w)await(l===void 0?U.delete(e,m,a):at(l,e,[m],a)),p+=1;if(w.length<r)break}return{deleted:p}},async deleteMany(e,t,r){T(e,"ctx.db.deleteMany(table, ids)"),ze(t.length,r?.limit,"deleteMany");for(const a of t)await U.delete(e,a);return{deleted:t.length}},async deleteWhere(e,t,r){const a=G(e,"deleteWhere"),p=(await ln(a??U,e,t,r?.limit,"deleteWhere")).map(d=>String(d._id));if(a)return at(a,e,p,void 0,{options:r});if(U.deleteMany===void 0)throw new R("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(e,p,r)},async findFirst(e,t={}){return(await U.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await U.findFirst(e,t);if(r===null)throw new Io(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=G(e,"findMany");if(r)return Te(e,t),t.consistency==="primary"&&M(e,ho),r.findMany(e,t);const a=h.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);const l=!t.where&&!t.baseWhere;l?q(e,j):q(e);const{limit:p,orderKeys:d,statement:w}=await Gt(e,a,t,q),m=$e(y,w.text,...w.params).toArray();l&&s?.recordRead(m.length);const D=[];for(const b of m){const v=Me(b);v&&(D.push(v),!l&&typeof v._id=="string"&&q(e,v._id))}const _=No(D,{endCursor:t.endCursor,limit:p,omitContinueCursor:t.omitContinueCursor,orderKeys:d});return t.with&&await tr({fetcher:rt,groupedCounter:Un,parents:_.page,...nr(t),schema:h,tableName:e,with:t.with}),{..._,page:An(_.page,t.select,t.with)}},async explain(e,t={}){const r=G(e,"explain");if(r)return r.explain(e,t);const a=h.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);const{statement:l}=await Gt(e,a,t,()=>{}),p=$e(y,`EXPLAIN QUERY PLAN ${l.text}`,...l.params).toArray();return{params:l.params,plan:p.map(d=>String(d.detail)),sql:l.text}},async get(e,t){T(e,"ctx.db.get(table, id)");const r=Y(t,e);if(!r){const a=be(e);return a?(M(e,t,!0),a.get(e,t)):(k(e),M(e,t,!0),null)}return ce(r,t),r.row},async lookupById(e,t){const r=Y(e,t);if(!r){for(const a of Ot(t))k(a),M(a,e,!0);return null}return ce(r,e),{row:r.row,tableName:r.tableName}},async groupBy(e,t){const r=G(e,"groupBy");if(r)return Te(e,t),r.groupBy(e,t);const a=h.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);q(e,j);const l=t.agg??{op:"count"};if(je(l.op),l.op!=="count"&&!l.field)throw new R("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);const p=xe(a.softDeleteMode,void 0),d=z(z(t.baseWhere,t.where),p),w=await Fe(d,e,t.relationBaseWhere),m=w!==d;if(a.aggregateIndexes&&!t.baseWhere&&!m){const $=no(a.aggregateIndexes,l.op,l.field,t.by,t.where),W=$===void 0?0:Object.keys($.partial).length,Q=$?.index.by?.length??0;if($&&(W===0||W===Q)){it(e,$.index);const V=dt(e,$.index.name),J=Object.keys($.partial),pe=[];if(J.length===($.index.by??[]).length&&J.length>0){const Pe=lt($.index.by??[],$.partial),Oe=H(y,u`SELECT ${Ge} AS value, ${ht} AS count FROM ${u.identifier(V)} WHERE ${He} = ${Pe}`).toArray();return Oe.length>0&&pe.push({key:{...$.partial},value:ut(l.op,Oe[0])}),pe}const Yn=H(y,u`SELECT ${He} AS key, ${Ge} AS value, ${ht} AS count FROM ${u.identifier(V)}`).toArray();for(const Pe of Yn){const Oe=eo(JSON.parse(Pe.key));pe.push({key:Oe,value:ut(l.op,Pe)})}return pe}}for(const $ of[...t.by,l.field]){if($===void 0)continue;const W=$===l.field?`groupBy(${e}, { agg: { op: "${l.op}", field: "${$}" } })`:`groupBy(${e}, { by: [..."${$}"] })`;fn(a,$,W)}const D=Z(w,ge),_=t.by.map($=>u`${ye($)} AS ${u.identifier($)}`);if(l.op==="count")_.push(u`COUNT(*) AS value`);else{const{field:$}=l;if($===void 0)throw new R("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);_.push(u`${u.raw(je(l.op))}(${ye($)}) AS value`)}let b=u`SELECT ${u.join(_,u`, `)} FROM ${u.identifier(e)}`;D&&(b=u`${b} WHERE ${D}`),b=u`${b} GROUP BY ${u.join(t.by.map($=>ye($)),u`, `)}`;const v=H(y,b).toArray(),I=[];for(const $ of v){const W={};for(const V of t.by)W[V]=go(a.shape[V],$[V]??null);const{value:Q}=$;I.push({key:W,value:Q==null?null:Number(Q)})}return I},async insert(e,t,r){const a=G(e,"insert");if(a)return Dt(a,e,t,r,!0);const l=h.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const p=r?.allowExplicitId===!0,d=Ke(l,mt(l,t,he),{supplied:t,table:e,trusted:p});let w;r?.clientId!==void 0?(Pr(r.clientId),w=r.clientId):r?.allowExplicitId&&typeof d._id=="string"?(Rt(d._id),w=d._id):w=It();const m=r?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:Re(),D={...d,...N(e),_creationTime:m,_id:w};return te(e,"before","insert")&&await ne("before","insert",{doc:{...D},id:w,op:"insert",table:e}),p||O(e,D),Ae(e),Ie(e),St(y,e,Mr(e),[w,m,de(D)]),ct(e,w,D),te(e,"after","insert")&&await ne("after","insert",{doc:D,id:w,op:"insert",table:e}),await ve({doc:D,id:w,op:"insert",table:e}),w},async insertManyUnsafe(e,t,r){if(ze(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const a=G(e,"insert");if(a){const _=[];Or(h.tables[e],t,r?.allowExplicitId,he);for(const b of t)ee(b);for(const b of t){const v=await a.insert(e,b,{allowExplicitId:r?.allowExplicitId});x({key:v,op:"insert",row:{...b,_id:v},table:e}),_.push(v)}return _}const l=h.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);Ae(e),Ie(e);const p=[];for(let _=0;_<t.length;_+=Qe)p.push(N(e));const d=r?.allowExplicitId===!0?void 0:er(l),w=t.map((_,b)=>{const v=mt(l,_,he),I=d===void 0?v:Ke(d,v,{supplied:_,table:e}),$=r?.allowExplicitId===!0&&typeof I._id=="string"?I._id:void 0;$!==void 0&&Rt($);const W=$??It(),Q=r?.allowExplicitId===!0&&typeof I._creationTime=="number"?I._creationTime:Re(),V={...I,...p[Math.floor(b/Qe)],_creationTime:Q,_id:W};return{creationTime:Q,document:V,id:W}});for(const _ of w)ee(_.document);const m=async _=>{for(const{document:b,id:v}of _)ct(e,v,b);for(const{document:b,id:v}of _)await me({doc:b,id:v,op:"insert",table:e})};let D=0;try{for(let _=0;_<w.length;_+=Qe){const b=w.slice(_,_+Qe),v=u.join(b.map($=>u`(${$.id}, ${$.creationTime}, ${de($.document)})`),u`, `),I=Sn("sqlite",u`INSERT INTO ${u.identifier(e)} (id, _creationTime, ${u.identifier(oe)}) VALUES ${v}`);St(y,e,I.sql,I.params),D=_+b.length}}catch(_){throw await jn(e,w.slice(0,D)),_}return await m(w),w.map(_=>_.id)},async insertMany(e,t,r){ze(t.length,r?.limit,"insertMany");const a=r?.skipDuplicates===!0,l=[],p=G(e,"insert");if(p)for(const w of t)ee(w);const d=async w=>p?Dt(p,e,w,void 0,!1):U.insert(e,w);for(const w of t)try{l.push(await d(w))}catch(m){if(a&&m instanceof le&&m.kind==="unique")l.push(null);else throw m}return l},normalizeId(e,t){return hn(h,e,t)},async patch(e,t,r,a){T(e,"ctx.db.patch(table, id, values)");const l=Y(t,e);if(!l){const $=be(e);if($){ee(r);try{await $.patch(e,t,r,a)}finally{se("update",e,t)}return}throw new R("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:w}=l,m=h.tables[w];if(!m)throw new R("INTERNAL",`unknown table: ${w}`);if(q(w,t),pn("patch",r),Ct(w,t,r,d)){o?.({fields:Object.keys(Ne(r)),id:t,table:w});return}const D=bo(m,r,d),_={...d,...Ne(D),...N(w),_id:t};gt(m,D,_,he);const b=new Set(Object.keys(D)),v=Ke(m,_,{only:b,patched:b,previous:()=>d,table:w,tolerateStoredNull:!0});xo(a,d,v),te(w,"before","update")&&await ne("before","update",{doc:{...v},id:t,op:"update",previous:d,table:w}),O(w,v,d),Ae(w),Ie(w),Ve(y,w,sn(w),[de(v),t,p]),qe(w,t,v,d),Be(w,t,v),We(w,d,v),we(w,t,d,v);const I=S(w,d,v);fe?.invalidate(w,t,I),_e(w,t,"update",v),x({indexKeys:I,key:t,op:"update",row:v,table:w}),te(w,"after","update")&&await ne("after","update",{doc:v,id:t,op:"update",previous:d,table:w}),await ve({doc:v,id:t,op:"update",table:w})},async patchIf(e,t,r){const a=G(e,"patchIf");if(a){if(a.patchIf===void 0)throw new R("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);ee(r.patch);let l;try{l=await a.patchIf(e,t,r)}catch(p){throw se("update",e,t),p}return l.applied&&se("update",e,t),l}if(!h.tables[e])throw new R("INTERNAL",`unknown table: ${e}`);for(let l=1;l<=wn;l+=1){const p=await Vn(e,t,r,l<wn,d=>U.patch(e,t,d,{verify:r.verify}));if(p!==void 0)return p}throw new le(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){T(e,"ctx.db.patchMany(table, patches)"),ze(t.length,r?.limit,"patchMany");for(const a of t)await U.patch(e,a.id,a.patch);return{patched:t.length}},async patchWhere(e,t,r){const a=G(e,"patchWhere")??U,p=(await ln(a,e,t.where,r?.limit,"patchWhere")).map(d=>({id:String(d._id),patch:t.patch}));if(U.patchMany===void 0)throw new R("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(e,p,r),{patched:p.length}},async related(e,t){return zo(U,B,e,t)},relationEdges:B,deleteRereadTables:C,inTransaction:ue,softDeleteFields:F,relationWrites:K,query(e){const t=G(e,"query");return t?(q(e,j),t.query(e)):Fn(y,h,e,ae,r=>{r?re(r):q(e,j)},r=>{s?.recordRead(r)})},async rank(e,t,r){const a=G(e,"rank");if(ae(e,t,"rank"),a)return q(e,j),a.rank(e,t,r);const l=h.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const p=l.rankIndexes?.find(J=>J.name===t);if(!p)throw new R("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Pt(e,l,p),r.restrictsCounts)throw new ft(e);q(e,j),st(e,p);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const w=Xt(e,p.name),m=p.sortBy.map((J,pe)=>Zt(pe)),D=m.map(J=>Le(J)).join(", "),_=H(y,u`SELECT ${u.identifier("__partition__")}, ${u.raw(D)} FROM ${u.identifier(w)} WHERE ${u.identifier("__id__")} = ${d}`).toArray(),[b]=_;if(b===void 0)return null;let v=b.__partition__;const I=z(r.baseWhere,r.where);wt(I,h,e,"rank");const $=Wo(p,I);if($){const J=Bo(p.partitionBy??[],$);if(J!==v)return null;v=J}const W=m.map(J=>b[J]),{before:Q,total:V}=yn(y,w,m,p.sortBy,v,W,d);return{position:Q+1,total:V}},async rankBefore(e,t,r){if(ie(e))throw new R("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const a=h.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);const l=a.rankIndexes?.find(m=>m.name===t);if(!l)throw new R("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new ft(e);q(e,j),st(e,l);const p=Xt(e,l.name),d=l.sortBy.map((m,D)=>Zt(D)),w=l.sortBy.map((m,D)=>ke(r.sortValues[D]??null));return yn(y,p,d,l.sortBy,r.partitionKey,w,r.rowId)},async rankPage(e,t,r={}){wt(z(r.baseWhere,r.where),h,e,"rankPage");const a=G(e,"rankPage");if(ae(e,t,"rank"),a)return q(e,j),a.rankPage(e,t,r);const{continueCursor:l,hasMore:p,rows:d}=zt(jt,e,t,r);return{continueCursor:l,isDone:!p,page:d.map(w=>w.doc)}},async rankPageRows(e,t,r={}){wt(z(r.baseWhere,r.where),h,e,"rankPage"),ae(e,t,"rank");const{directions:a,hasMore:l,rows:p}=zt(jt,e,t,r);return{directions:a,hasMore:l,rows:p}},async restore(e,t){T(e,"ctx.db.restore(table, id)");const r=Y(t,e);if(!r){const d=be(e);if(d?.restore){try{await d.restore(e,t)}finally{se("update",e,t)}return}throw new R("NOT_FOUND",`document not found: ${t}`)}const a=h.tables[r.tableName]?.softDeleteMode?.field;if(!a)throw new R("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const l=r.row[a]!==null&&r.row[a]!==void 0;await U.patch(e,t,{[a]:null});const p=l?Y(t,e)?.row:void 0;p&&(we(r.tableName,t,p,void 0),we(r.tableName,t,void 0,p))},async replace(e,t,r,a){T(e,"ctx.db.replace(table, id, document)");const l=Y(t,e);if(!l){const W=be(e);if(W){ee(r);try{await W.replace(e,t,r,a)}finally{se("update",e,t)}return}throw new R("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:w}=l,m=h.tables[w];if(!m)throw new R("INTERNAL",`unknown table: ${w}`);pn("replace",r);const D=a?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:void 0,_=typeof d._creationTime=="number"?d._creationTime:void 0,b=D??_??Re(),v={...r,...N(w),_creationTime:b,_id:t};gt(m,r,v,he);const I=a?.allowExplicitId===!0,$=Ke(m,v,{previous:()=>d,supplied:r,table:w,trusted:I});te(w,"before","update")&&await ne("before","update",{doc:{...$},id:t,op:"update",previous:d,table:w}),I||O(w,$,d),Ae(w),Ie(w),Ve(y,w,Dr(w),[b,de($),t,p]),qe(w,t,$,d),Be(w,t,$),We(w,d,$),we(w,t,d,$),fe?.invalidate(w,t,S(w,d,$)),_e(w,t,"update",$),x({indexKeys:S(w,d,$),key:t,op:"update",row:$,table:w}),te(w,"after","update")&&await ne("after","update",{doc:$,id:t,op:"update",previous:d,table:w}),await ve({doc:$,id:t,op:"update",table:w})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,a=Object.entries(h.tables).filter(([w,m])=>t.has(w)||r!==void 0&&!r.includes(w)?!1:m.shardMode?.kind!=="global").map(([w])=>w);if(r!==void 0){for(const w of r)if(!h.tables[w])throw new R("INTERNAL",`wipeShard: unknown table: ${w}`)}const l={};let p=0;const{deleteAll:d}=U;if(d===void 0)throw new R("INTERNAL","wipeShard: this writer has no deleteAll");for(const w of a){const m=await d(w,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});l[w]=m.deleted,p+=m.deleted}return{deleted:p,tables:l}}},Jn={db:U,scheduler:bt};return n.enforceRls===!0?sr(U,h,(e,t)=>Y(e,t)?.tableName,B):U};export{hs as CDC_LOG_TABLE,Fs as IDEMPOTENCY_TABLE,Xr as NotUniqueError,Ms as advanceClientWatermark,ws as applyCdcChanges,pn as assertNoExplicitUndefined,Rt as assertStorableRowId,Pr as assertValidClientId,ds as backfillAggregateIndexes,ls as backfillRankIndexes,us as backfillSearchIndexes,ps as bumpCdcEpoch,gs as cdcCanVouchFor,ys as cdcForkedError,$s as cdcSeqLeavingRows,Es as cdcTouchesTables,ms as cdcTrimmedError,vs as compactCdcDocs,vi as createShardCtxDb,Rs as cursorBelowRetainedFloor,fi as meterReadBytes,Ds as migrateClientWatermark,Ss as minCdcReplayableSeq,_s as minCdcSeq,hn as normalizeIdStructurally,Ts as readCdcChangeKeys,As as readCdcChanges,Is as readCdcCursor,bs as readCdcEpoch,ks as readClientWatermark,Ws as readIdempotent,Os as runShardMigrations,js as selectShapeMembers,Gs as selectShapeRows,Ne as stripReservedPatchFields,xs as trimCdcChanges,Bs as trimIdempotent,qs as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as s}from"drizzle-orm";import{matchesStaticWhere as f}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{compareStrings as l}from"./aggregateTableName-B_CtIQCS.mjs";import{serializeSqlValue as d}from"./serializeSqlValue-DeoBMpZ2.mjs";const a=Symbol("not-resolvable"),m=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:a}return r},y=(r,t)=>{if(r.length===0)return"";const e={};for(const n of r.toSorted(l))e[n]=t[n]??null;return JSON.stringify(e)},k="__id__",N=r=>`__sort_k${String(r)}__`,h=(r,t)=>{const e=r.partitionBy??[],n=t??{};for(const o of Object.keys(n))if(o==="AND"||o==="OR"||o==="NOT")return;const i={};for(const o of e)if(o in n){const c=m(n[o]);if(c===a)return;i[o]=c}else if(r.where&&o in r.where)i[o]=r.where[o];else return;return i},O=(r,t)=>`${r}__rank_${t}`,$=(r,t)=>({partitionKey:y(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(e=>d(t[e.field]??null))}),K=(r,t,e,n)=>{const i=e!=="desc"===n;if(t==null)return i?s`${s.identifier(r)} IS NOT NULL`:void 0;const o=s`${s.identifier(r)} ${s.raw(i?">":"<")} ${t}`;return i?o:s`(${o} OR ${s.identifier(r)} IS NULL)`},R=f;export{k as RANK_TIEBREAK,y as encodePartitionKey,R as matchesRankStaticWhere,$ as rankKeyFromDoc,K as rankPivotConditionSql,O as rankTableName,h as resolveRankPartition,N as sortColumnName};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-CPKPy8N6.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-BfJ2FeLv.mjs";import{runDrizzle as p}from"./runDrizzle-RC09zZrh.mjs";import{h}from"./do-sql-Cf2rnuLV.mjs";const u="__lunora_vector_backfill",m=50,k=20,w=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=h(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,k),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,w),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{k as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as f}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{SQLiteDialect as u}from"drizzle-orm/sqlite-core";const S=new u,s={boundParams:100,compoundSelect:5,likePattern:50,sqlTextLength:1e5},d=s.boundParams/2,h=n=>n===null||typeof n=="boolean"?!0:typeof n=="number"?Number.isFinite(n):typeof n=="string"&&n.isWellFormed(),p=n=>{const e=[];for(const r of n){if(!(r instanceof Uint8Array))return;e.push(Array.from(r,o=>o.toString(16).padStart(2,"0")).join(""))}return JSON.stringify(e)},N=(n,e)=>{if(n!=="sqlite")throw new f("INTERNAL",`renderSql only renders SQLite; use SqlDialect.render for "${n}"`);const{params:r,sql:o}=S.sqlToQuery(e);return{params:r,sql:o}},L=n=>t`${n}`,y=n=>{if(n.length===0)throw new Error("unionAll: expected at least one branch");let e=[...n];for(;e.length>s.compoundSelect;){const r=[];for(let o=0;o<e.length;o+=s.compoundSelect){const i=t.join(e.slice(o,o+s.compoundSelect),t` UNION ALL `);r.push(t`SELECT * FROM (${i}) ${t.identifier("__u__")}`)}e=r}return t.join(e,t` UNION ALL `)},T=(n,e,r,o=d)=>{const i=r?t` NOT IN `:t` IN `,a=e.every(l=>h(l)),c=e.length>o&&!a?p(e):void 0;if(c!==void 0)return t`${n}${i}(SELECT unhex(${t.identifier("value")}) FROM json_each(${c}))`;if(e.length>o&&!a)throw new f("BAD_REQUEST",`an "in" list of ${String(e.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(e.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);return e.length<=o?t`${n}${i}(${t.join(e.map(l=>L(l)),t`, `)})`:t`${n}${i}(SELECT ${t.identifier("value")} FROM json_each(${JSON.stringify(e)}))`};export{s as WORKERD_SQLITE_LIMITS,p as bytesAsHexJson,h as isJsonSafe,L as param,N as renderSql,T as sqliteInList,y as unionAll};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-CPKPy8N6.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-CE3EmIjk.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-DmciS_rv.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-RC09zZrh.mjs";import{i as M,D as m,h as A}from"./do-sql-Cf2rnuLV.mjs";import{sqliteInList as U}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const v=(e,o)=>p(e,i`SELECT 1 FROM ${i.identifier(o)} LIMIT 1`).toArray().length>0,Q=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.aggregateIndexes??[])y(e,r,t,n.softDeleteMode?.field)},X=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.rankIndexes??[])B(e,r,t,n.softDeleteMode?.field)},H=(e,o,r,n)=>p(e,r===void 0?i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} ORDER BY id ASC LIMIT ${i.raw(String(n))}`:i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${i.raw(String(n))}`).toArray(),h=500,O=(e,o,r)=>{const n=I(o,r.name),t=E(r),a=w(T(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,s=H(e,o,c,h);let f=c;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;f=u;const S=A(g);C(e,S?x(n,u,b(S,r)):k(n,u))}const d=s.length<h;return F(e,n,f,d,t),{done:d,rows:s.length}},l=(e,o)=>i`${i.identifier(e)}.${i.identifier(o)}`,R=500,$=(e,o,r)=>{const n=I(o,r.name),t=p(e,L(n,R)).toArray(),a=_(t);if(a.size===0)return!0;const c=new Map;for(const s of p(e,i`SELECT ${l(o,"id")}, ${l(o,"_creationTime")}, ${l(o,m)} FROM ${i.identifier(o)} WHERE ${U(l(o,"id"),[...a.keys()],!1)}`))c.set(String(s.id),s);for(const[s,f]of a){const d=c.get(s),g=d?A(d):void 0;C(e,g?x(n,s,b(g,r),{unmappedRowids:f}):k(n,s,{unmappedRowids:f}))}return t.length<R},W=(e,o,r,n)=>{let t=0;for(;t<n&&!$(e,o,r);)t+=1;return t},Z=(e,o,r)=>{const n=I(o,r.name),t=E(r);return w(T(e,n),t).finished?!0:D(e,n)},q=(e,o,r)=>{if(M(e))for(const n of r.searchIndexes??[])$(e,o,n),!(n.staged&&v(e,o))&&O(e,o,n)},j=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=O(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},ee=(e,o,r={})=>{if(!M(e))return{done:!0,pages:0};P(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const s of c.searchIndexes){if(t+=W(e,a,s,n-t),t>=n)return{done:!1,pages:t};const f=j(e,a,s,n-t);if(t+=f.pages,!f.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{Q as backfillAggregateIndexes,X as backfillRankIndexes,ee as backfillSearchIndexes,q as backfillSearchIndexesForTable,H as readKeysetPage,Z as searchIndexCoversTable};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{encodeWire as u}from"@lunora/wire";import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as d}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{runSql as p}from"./runDrizzle-RC09zZrh.mjs";import{k as m,D as E}from"./do-sql-Cf2rnuLV.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const b=u(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=d(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{m(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./json-field-path-DeJW4U9z.mjs";import"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{c as p,s}from"./where-sql-Cb_dSAMj.mjs";import"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";export{p as compileWhereSql,s as serverInList};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as A}from"./runDrizzle-RC09zZrh.mjs";import{sqliteInList as O}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-D3ye2GsL.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[m,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[m]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},_o=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const m=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const p=[];typeof t.partitionKey=="string"?p.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&p.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&p.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=p.length>0?o` WHERE ${o.join(p,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(m)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{_o as computeRankPage,Q as resolveRankSeekTuple};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{N as uo,S as $o,d as Eo,e as go,a as po}from"./fts-companion-CE3EmIjk.mjs";import{sql as o}from"drizzle-orm";import{r as Q}from"./json-field-path-DeJW4U9z.mjs";import{matchesStaticWhere as J,aggregateSqlFunction as mo}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as B,foldAggregateTally as Z,encodeAggregateKey as v,coerceAggregateNumber as H}from"./aggregateTableName-B_CtIQCS.mjs";import{aggregateSignature as ho,readCompanionSignature as N,rankSignature as So,writeCompanionSignature as x}from"./CompanionMemo-jmlDbPlr.mjs";import{runAll as _o,runDrizzle as g}from"./runDrizzle-RC09zZrh.mjs";import{i as yo,g as Ro,a as D,b as A,A as _,c as j,D as oo,u as eo,r as no,e as q}from"./do-sql-Cf2rnuLV.mjs";import{WORKERD_SQLITE_LIMITS as to,param as G}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{encodeGeohash as To,GEO_DEFAULT_PRECISION as Ao}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as W}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as P,matchesRankStaticWhere as ro,sortColumnName as wo,encodePartitionKey as Co}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{mayHoldProjectedValue as Io}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{serializeSqlValue as so}from"./serializeSqlValue-DeoBMpZ2.mjs";const Oo=(s,f,t)=>[...s.partitionBy??[],...s.sortBy.map(l=>l.field),...s.where?Object.keys(s.where):[]].every(l=>Q(f,l)===Q(t,l)),io=s=>o.join(["__id__","__partition__",...s.sortBy.map((f,t)=>wo(t))].map(f=>o.identifier(f)),o`, `),co=(s,f,t)=>{const u=Co(s.partitionBy??[],t),l=s.sortBy.map(r=>so(t[r.field]??null)),a=o.join([f,u,...l].map(r=>G(r)),o`, `);return o`(${a})`},ko=(s,f,t,u,l,a)=>{g(s,o`INSERT INTO ${o.identifier(f)} (${u}) VALUES ${co(t,l,a)}`)},X=1e3,ao=function*(f,t,u,l){let a;for(;;){const r=a===void 0?o``:o` WHERE id > ${G(a)}`,m=[...g(eo(f),o`SELECT id, _creationTime, ${o.identifier(oo)} FROM ${o.identifier(t)}${r} ORDER BY id LIMIT ${G(X)}`)];for(const h of m){const R=no(h);R&&W(R,u)&&l(R)&&(yield R)}if(m.length<X)return;a=String(m.at(-1)?.id)}},vo=(s,f,t,u,l)=>{const a=B(f,t.name),r=t.by??[],m=new Map;for(const w of ao(s,f,u,I=>!t.where||J(I,t.where)))Z(m,v(r,w),t,w);g(s,o`DELETE FROM ${o.identifier(a)}`);const h=Math.floor(to.boundParams/3),R=[...m];for(let w=0;w<R.length;w+=h){const I=R.slice(w,w+h),V=o.join(I.map(([b,F])=>o`(${b}, ${F.value}, ${F.count})`),o`, `);g(s,o`INSERT INTO ${o.identifier(a)} (${D}, ${A}, ${_}) VALUES ${V}`)}x(s,a,l)},Lo=(s,f,t,u)=>{const l=ho(t,u);N(s,B(f,t.name))!==l&&vo(s,f,t,u,l)},Do=(s,f,t,u,l)=>{const a=P(f,t.name),r=io(t);g(s,o`DELETE FROM ${o.identifier(a)}`);const m=Math.max(1,Math.floor(to.boundParams/(2+t.sortBy.length)));let h=[];const R=()=>{h.length>0&&(g(s,o`INSERT INTO ${o.identifier(a)} (${r}) VALUES ${o.join(h,o`, `)}`),h=[])};for(const w of ao(s,f,u,I=>!t.where||ro(I,t.where)))h.push(co(t,w._id,w)),h.length>=m&&R();R(),x(s,a,l)},Fo=(s,f,t,u)=>{const l=So(t,u);N(s,P(f,t.name))!==l&&Do(s,f,t,u,l)},Mo=(s,f,t,u,l,a,r)=>{if(a&&r&&W(a,u)===W(r,u)&&Oo(t,a,r))return;const m=P(f,t.name);a&&g(s,o`DELETE FROM ${o.identifier(m)} WHERE ${o.identifier("__id__")} = ${l}`),!(!r||!W(r,u)||t.where&&!ro(r,t.where))&&ko(s,m,t,io(t),l,r)},Jo=s=>{const{broadcast:f,indexKeysFor:t,invalidateCache:u,recordCdc:l,schema:a,sql:r}=s,m=s.verified??new Set,h=e=>a.tables[e]?.softDeleteMode?.field,R=(e,n)=>{const c=B(e,n.name);m.has(c)||(Lo(r,e,n,h(e)),m.add(c))},w=(e,n,c)=>{const p=n.by??[],d=n.field??"",E=[],y=(i,$)=>{const S=so($);S===null?E.push(o`${q(i)} IS NULL`):E.push(o`${q(i)} = ${S}`)};for(const i of p)y(i,c[i]??null);const C=h(e);C!==void 0&&y(C,null);for(const[i,$]of Object.entries(n.where??{}))y(i,$!==null&&typeof $=="object"&&!Array.isArray($)?$.eq:$);const L=E.length>0?o` WHERE ${o.join(E,o` AND `)}`:o``,M=a.tables[e]?.shape[d];if(M&&Io(M)){const i=g(eo(r),o`SELECT id, _creationTime, ${o.identifier(oo)} FROM ${o.identifier(e)}${L}`).toArray(),$=new Map;for(const S of i){const k=no(S);k&&Z($,"",n,k)}return{value:$.get("")?.value??null}}const U=mo(n.op),T=q(d);return{value:g(r,o`SELECT ${o.raw(U)}(${T}) AS value FROM ${o.identifier(e)}${L}`).one().value??null}},I=(e,n,c,p)=>{const d=B(e,n.name),{op:E}=n,y=n.field??"",C=i=>{g(r,o`DELETE FROM ${o.identifier(d)} WHERE ${D} = ${i} AND ${_} <= 0`)},L=h(e),M=i=>!n.where||J(i,n.where),U=i=>W(i,L)&&M(i);p!==void 0&&E!=="count"&&M(p)&&H(p[y]);const T=c&&U(c)?c:void 0,O=p&&U(p)?p:void 0;if(!(!T&&!O)){if(E==="count"){for(const[i,$]of[[T,-1],[O,1]]){if(!i)continue;const S=v(n.by??[],i);g(r,j(d,S,$,$,o`${A} = ${A} + excluded.${A}, ${_} = ${_} + excluded.${_}`))}T&&C(v(n.by??[],T));return}if(E==="sum"||E==="avg"){for(const[i,$]of[[T,-1],[O,1]]){if(!i)continue;const S=H(i[y]);if(S===void 0)continue;const k=v(n.by??[],i);g(r,j(d,k,$*S,$,o`${A} = COALESCE(${A}, 0) + excluded.${A}, ${_} = ${_} + excluded.${_}`))}T&&C(v(n.by??[],T));return}if(T){const i=v(n.by??[],T),$=H(T[y]),S=g(r,o`SELECT ${A} AS value, ${_} AS count FROM ${o.identifier(d)} WHERE ${D} = ${i}`).toArray()[0],k=(S?.count??0)-1;if(k<=0)g(r,o`DELETE FROM ${o.identifier(d)} WHERE ${D} = ${i}`);else if(S&&$!==void 0&&S.value!==null&&$===S.value){const lo=w(e,n,T);g(r,o`UPDATE ${o.identifier(d)} SET ${A} = ${lo.value}, ${_} = ${k} WHERE ${D} = ${i}`)}else g(r,o`UPDATE ${o.identifier(d)} SET ${_} = ${_} - 1 WHERE ${D} = ${i}`)}if(O){const i=v(n.by??[],O),$=H(O[y]);if($===void 0)g(r,j(d,i,null,1,o`${_} = ${_} + 1`));else{const S=E==="min"?"MIN":"MAX";g(r,j(d,i,$,1,o`${A} = ${o.raw(S)}(COALESCE(${A}, excluded.${A}), excluded.${A}), ${_} = ${_} + 1`))}}}},V=e=>{for(const n of a.tables[e]?.aggregateIndexes??[])R(e,n)},b=(e,n,c)=>{for(const p of a.tables[e]?.aggregateIndexes??[])I(e,p,n,c)},F=(e,n)=>{const c=P(e,n.name);m.has(c)||(Fo(r,e,n,h(e)),m.add(c))},fo=e=>{for(const n of a.tables[e]?.rankIndexes??[])F(e,n)},K=(e,n,c,p)=>{for(const d of a.tables[e]?.rankIndexes??[])Mo(r,e,d,h(e),n,c,p)},z=(e,n,c,p)=>{const d=a.tables[e]?.searchIndexes??[];if(!(d.length===0||!yo(r)))for(const E of d){if(uo(p,c,E))continue;const y=$o(e,E.name);_o(r,c?Eo(y,n,go(c,E)):po(y,n))}},Y=(e,n,c)=>{for(const p of a.tables[e]?.geoIndexes??[]){const d=Ro(e,p.name);g(r,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const E=c?.[p.field];if(E!==null&&typeof E=="object"&&typeof E.lat=="number"&&typeof E.lng=="number"){const{lat:y,lng:C}=E,L=To({lat:y,lng:C},p.precision??Ao);g(r,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${L}, ${y}, ${C})`)}}};return{ensureBackfilledForTable:V,ensureBackfilledIndex:R,ensureRankBackfilled:F,ensureRankBackfilledForTable:fo,syncAggregates:b,syncCompanionsForInsert:(e,n,c)=>{z(e,n,c),Y(e,n,c),b(e,void 0,c),K(e,n,void 0,c),u(e,n,c),l(e,n,"insert",c),f({indexKeys:t(e,c),key:n,op:"insert",row:c,table:e})},syncGeo:Y,syncRanks:K,syncSearch:z}};export{Jo as createCompanionSync,Lo as ensureAggregateCompanion,Fo as ensureRankCompanion};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as _}from"@lunora/errors";import{WIRE_TAG as T,decodeWire as $,needsWireEncoding as h,encodeWire as A}from"@lunora/wire";import{sql as s}from"drizzle-orm";import{e as O}from"./effective-kind-BmG_zCAy.mjs";import{S as y,i as g,s as I,F as N}from"./json-field-path-DeJW4U9z.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import{runDrizzle as c}from"./runDrizzle-RC09zZrh.mjs";import{serializeSqlValue as L}from"./serializeSqlValue-DeoBMpZ2.mjs";import{sqlComparableProjection as j}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const w=/^[A-Za-z_$][\w$]*$/u,u=e=>w.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,d="__doc__",i="__originals__",x=e=>{if(Object.hasOwn(e,i))throw new _("BAD_REQUEST",`"${i}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[o,a]of Object.entries(e)){const f=j(a);f!==void 0&&(t??={...e},r??=Object.create(null),t[o]=f,r[o]=a)}t&&r&&(t[i]=r);const n=t??e;try{return h(n)?JSON.stringify(A(n)):JSON.stringify(n)}catch(o){throw new _("BAD_REQUEST",`this document cannot be stored: ${o instanceof Error?o.message:String(o)}`)}},P=e=>{const t=JSON.parse(e),r=e.includes(T)||e.includes(String.raw`\u`)?$(t):t,n=r[i];if(n===null||typeof n!="object"||Array.isArray(n))return r;const o={...r};return delete o[i],{...o,...n}},Z=(e,t)=>`${e}__geo_${t}`,R=e=>{try{return I(e)}catch(t){throw t instanceof N?new _("VALIDATION_ERROR",t.message):t}},S=e=>`'$.${(g(e)?R(e).map(r=>u(r)).join("."):u(e)).replaceAll("'","''")}'`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${d}, ${S(t)})`,D=e=>E("",e),q=(e,t)=>`NULLIF(json_type(${d}, ${S(e)}), 'null') IN (${y[t]})`,C=e=>s.raw(D(e)),U=(e,t)=>s.raw(q(e,t)),G=(e,t)=>E(`${b(e)}.`,t),ee=(e,t)=>s.raw(G(e,t)),te=(e,t,r,n)=>s`CREATE ${n?s`UNIQUE `:s``}INDEX IF NOT EXISTS ${s.identifier(e)} ON ${s.identifier(t)} (${r})`,m=s.identifier("__key__"),v=s.identifier("__value__"),F=s.identifier("__count__"),re=(e,t,r,n,o)=>s`INSERT INTO ${s.identifier(e)} (${m}, ${v}, ${F}) VALUES (${t}, ${r}, ${n}) ON CONFLICT(${m}) DO UPDATE SET ${o}`,oe=(e,t)=>e===void 0||t!==0&&t!==1||O(e)!=="boolean"?t:t===1,p=new WeakMap,ne=e=>{const t=p.get(e);if(t!==void 0)return t;const r=[];for(const[n,o]of Object.entries(e.shape)){const a=o._meta?.column;a&&r.push(Object.freeze([n,a]))}return Object.freeze(r),p.set(e,r),r},J=e=>{if(!e)return;const t=e[d];let r;typeof t=="string"?r=P(t):t&&typeof t=="object"?r=t:r={};const{id:n}=e;typeof n=="string"&&(r._id=n);const o=e._creationTime;return typeof o=="number"&&(r._creationTime=o),r},se=e=>{try{return J(e)}catch{return}},l=new WeakMap,W=Symbol("lunora.wrappedSql"),z=e=>e[W]??e,ae=(e,t)=>{const r=z(e),n=l.get(r);if(n!==void 0)return n;if(t!==void 0)try{return c(r,s`SELECT 1 FROM ${s.identifier(t)} LIMIT 0`).toArray(),l.set(r,!0),!0}catch{}let o;try{c(r,s`CREATE VIRTUAL TABLE IF NOT EXISTS ${s.identifier("__lunora_fts_probe")} USING fts5(x)`),o=!0}catch{o=!1}finally{try{c(r,s`DROP TABLE IF EXISTS ${s.identifier("__lunora_fts_probe")}`)}catch{}}return l.set(r,o),o},ie={fieldRef:C,rangeTypeGuard:U,serialize:L};export{F as A,d as D,W,m as a,v as b,re as c,te as d,C as e,ee as f,Z as g,se as h,ae as i,D as j,x as k,P as l,ie as m,i as n,u as o,q as p,G as q,J as r,oe as s,ne as t,z as u,U as v};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{q as I}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{sql as e}from"drizzle-orm";import{sqliteInList as L}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const u=(i,t)=>{if(!t.includes("."))return i[t];let r=i;for(const $ of t.split(".")){if(r===null||typeof r!="object"||Array.isArray(r))return;r=r[$]}return r},w=(i,t)=>`${i}__fts_${t}`,o="__text__",f="__id__",A=1e3,O=(i,t)=>t.document(i),N=(i,t)=>u(i,t),_=i=>typeof i=="string"?i:i==null?"":typeof i=="number"||typeof i=="bigint"||typeof i=="boolean"?String(i):JSON.stringify(i)??"",D=(i,t,r)=>i!==void 0&&t!==void 0&&N(i,r.field)===N(t,r.field),c=(i,t)=>O(_(N(i,t.field)),I(t.language)).slice(0,A),M=(i,t)=>c(i,t).join(" "),a=50,n="__rowid__",T=i=>`${i}__ids`,E=(i,t)=>e`${e.identifier(i)}.${e.identifier(t)}`,S=(i,t,{guard:r,unmappedRowids:$})=>{const d=T(i),s=r===void 0?e``:e` AND ${r}`,R=$===void 0?e`${E(i,"rowid")} > 0`:L(E(i,"rowid"),$,!1,a);return[e`DELETE FROM ${e.identifier(i)} WHERE ${R} AND CAST(${E(i,f)} AS TEXT) = ${t}${s}`,e`DELETE FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = (SELECT ${E(d,n)} FROM ${e.identifier(d)} WHERE ${E(d,f)} = ${t}) AND ${E(i,f)} = ${t}${s}`]},U=i=>[e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(i)} USING fts5(${e.identifier(o)}, ${e.identifier(f)} UNINDEXED)`,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${i}__vocab`)} USING fts5vocab(${e.identifier(i)}, ${e.raw("instance")})`,e`CREATE TABLE IF NOT EXISTS ${e.identifier(T(i))} (${e.identifier(n)} INTEGER PRIMARY KEY, ${e.identifier(f)} TEXT NOT NULL UNIQUE)`,e`INSERT INTO ${e.identifier(i)} (rowid, ${e.identifier(o)}, ${e.identifier(f)}) SELECT 0, '', '' WHERE NOT EXISTS (SELECT 1 FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = 0)`],F=(i,t,r,$={})=>{const d=T(i),s=$.guard===void 0?e``:e` AND ${$.guard}`,R=e`MIN(COALESCE((SELECT MIN(${E(d,n)}) FROM ${e.identifier(d)}), 0), 0) - 1`;return[...S(i,t,$),e`INSERT OR REPLACE INTO ${e.identifier(d)} (${e.identifier(n)}, ${e.identifier(f)}) SELECT ${R}, ${t} WHERE 1 = 1${s}`,e`INSERT OR REPLACE INTO ${e.identifier(i)} (rowid, ${e.identifier(o)}, ${e.identifier(f)}) SELECT ${E(d,n)}, ${r}, ${E(d,f)} FROM ${e.identifier(d)} WHERE ${E(d,f)} = ${t}${s}`]},y=(i,t,r={})=>{const $=T(i),d=r.guard===void 0?e``:e` AND ${r.guard}`;return[...S(i,t,r),e`DELETE FROM ${e.identifier($)} WHERE ${E($,f)} = ${t}${d}`]},W=(i,t,r=0)=>e`SELECT ${E(i,"rowid")} AS ${e.identifier("rowid")}, ${E(i,f)} AS ${e.identifier("id")} FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} > ${e.param(Math.max(0,r))} AND ${E(i,f)} IS NOT NULL ORDER BY ${E(i,"rowid")} ASC LIMIT ${e.raw(String(t))}`,b=i=>{const t=new Map;for(const r of i){const $=String(r.id);t.set($,[...t.get($)??[],Number(r.rowid)])}return t};export{D as N,w as S,y as a,T as b,W as c,F as d,M as e,U as f,b as g,f as l,c as s};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as t,a as e,b as p,c as m,d as f,g as n}from"./fts-companion-CE3EmIjk.mjs";import"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";export{t as ftsCompanionDdl,e as ftsPurgeDocument,p as ftsRowidMapName,m as ftsUnmappedPage,f as ftsWriteDocument,n as groupUnmappedRows};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-RC09zZrh.mjs";import{e as i}from"./do-sql-Cf2rnuLV.mjs";const f=(r,o)=>{const n=o-(r.after??0),e=[t`${i(r.field)} IS NOT NULL`,t`${i(r.field)} < ${n}`];return r.softDeleteField!==void 0&&e.push(t`${i(r.softDeleteField)} IS NULL`),e},L=(r,o,n,e)=>{const d=t`SELECT id FROM ${t.identifier(o.table)} WHERE ${t.join(f(o,n),t` AND `)} LIMIT ${t.raw(String(Math.max(0,Math.floor(e))+1))}`,s=l(r,d).toArray(),a=s.length>e,$=s.slice(0,e).map(E=>E.id);return{hasMore:a,ids:$}},S=(r,o,n,e)=>{const d=t`SELECT 1 AS hit FROM ${t.identifier(o.table)} WHERE id = ${n} AND ${t.join(f(o,e),t` AND `)}`;return l(r,d).toArray().length>0},c=(r,o)=>o===void 0?i(r):t`${i(o)}, ${i(r)}`,h=(r,o)=>{const n=o.softDeleteField===void 0?t``:t` WHERE ${i(o.softDeleteField)} IS NULL`,e=t`SELECT MIN(${i(o.field)}) AS expiry FROM ${t.identifier(o.table)}${n}`,d=l(r,e).toArray()[0]?.expiry;return typeof d=="number"?d+(o.after??0):void 0};export{S as isTtlExpired,h as nextTtlExpiry,L as selectExpiredIds,c as ttlIndexColumns};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{renderSql as l,WORKERD_SQLITE_LIMITS as e}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const c=(t,n,...r)=>{if(n.length*3>e.sqlTextLength){const s=new TextEncoder().encode(n).length;if(s>e.sqlTextLength)throw new i("INTERNAL",`SQL statement is ${String(s)} bytes, over this runtime's ${String(e.sqlTextLength)}-byte limit`)}if(r.length>e.boundParams)throw new i("INTERNAL",`SQL statement binds ${String(r.length)} parameters, over this runtime's limit of ${String(e.boundParams)}`);return t.exec.call(t,n,...r)},u=(t,n)=>{const{params:r,sql:o}=l("sqlite",n);return c(t,o,...r)},d=(t,n)=>{for(const r of n)u(t,r)},g=t=>t??null,S=t=>{if(!(t==null||t===""))try{return JSON.parse(t)}catch{return}};export{S as decodeJsonColumn,g as orNull,d as runAll,u as runDrizzle,c as runSql};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{LunoraError as w}from"@lunora/errors";import{f as X,S as y}from"./fts-companion-CE3EmIjk.mjs";import{sql as n}from"drizzle-orm";import{aggregateTableName as O}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as k}from"./backfillAggregateIndexes-BfJ2FeLv.mjs";import{migrateCdcLog as B,migrateCdcMeta as G}from"./CDC_LOG_TABLE-fCPCjSE4.mjs";import{migrateClientWatermark as P}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{migrateCommitSeq as v}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{migrateCompanionState as Y}from"./CompanionMemo-jmlDbPlr.mjs";import{migrateGlobalShapeSnapshot as q}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{migrateIdempotency as j}from"./IDEMPOTENCY_TABLE-BVosXEq_.mjs";import{m as K}from"./ctx-db-relay-shapes-DBobAek2.mjs";import{migrateScheduleOutbox as V}from"./SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{m as W}from"./ctx-db-search-state-CPKPy8N6.mjs";import{migrateShapePokeCursor as H}from"./SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{runDrizzle as _,runAll as z}from"./runDrizzle-RC09zZrh.mjs";import{D as Q,d as p,e as h,t as Z,i as J,g as ee,a as te,b as oe,A as x}from"./do-sql-Cf2rnuLV.mjs";import{renderSql as A}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{migrateDurableStreams as ne}from"./appendStreamChunk-BZYgGE9Y.mjs";import{rankTableName as F,sortColumnName as re}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as ie}from"./REACTOR_STATE_TABLE-D2Mn204f.mjs";import{recordSchemaVersion as de}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{ttlIndexColumns as ae}from"./isTtlExpired-Bymg2-13.mjs";const L=n`_creationTime, id`,$="__by_creation",se="__ttl",ce=`, ${A("sqlite",L).sql})`,g="__lunora_framework_indexes",c=e=>e.replaceAll(/[A-Z]/gu,t=>t.toLowerCase()),le=/^CREATE\s+VIRTUAL\s+TABLE\b/iu,fe=/\bUSING\s+fts5\b/iu,me=e=>e!==null&&le.test(e)&&fe.test(e),_e=e=>{const t=new Map,o=c(g);let d=!1,r;for(const i of _(e,n`SELECT type, name, tbl_name, sql FROM sqlite_master`))i.type==="index"?t.set(c(i.name),{name:i.name,sql:i.sql,tableFolded:c(i.tbl_name)}):i.type==="table"&&(c(i.name)===o&&(d=!0),r===void 0&&me(i.sql)&&(r=i.name));return{existingFtsTable:r,indexes:t,ledgerExists:d}},u=(e,t,o,d,r)=>{const i=p(t,o,d,r);_(e.sql,i);const a=c(t);e.catalog.has(a)||e.catalog.set(a,{name:t,sql:A("sqlite",i).sql,tableFolded:c(o)})},b=(e,t)=>{_(e.sql,n`DROP INDEX IF EXISTS ${n.identifier(t)}`),e.catalog.delete(c(t))};class U extends w{}const D=(e,t,o,d,r,i)=>{const a=n.join(r.map(f=>n`${f} IS NOT NULL`),n` AND `);if(_(e,n`SELECT 1 FROM ${n.identifier(o)} WHERE ${a} GROUP BY ${d} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new U("UNIQUE_INDEX_DUPLICATES",`unique index "${t}" on "${o}" ${i}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},I=(e,t,o,d,r,i)=>{const a=e.catalog.get(c(t)),l=a?.tableFolded===c(o)?a.sql:void 0;if(l==null)return;const f=E=>{const T=E.indexOf("(");return T===-1?void 0:E.slice(T,E.lastIndexOf(")")+1)},s=f(A("sqlite",p(t,o,d,r)).sql),m=f(l);s===void 0||m===void 0||s===m||(r&&D(e.sql,t,o,d,i,"cannot be re-created with its new column list"),b(e,t))},N=(e,t,o)=>e.get(c(t))?.tableFolded===c(o),R=(e,t,o,d,r,i)=>{r&&!N(e.catalog,t,o)&&D(e.sql,t,o,d,i,"cannot be created"),u(e,t,o,d,r)},C=(e,t)=>{try{t()}catch(o){if(e===void 0||!(o instanceof U))throw o;e.push(o.message)}},Ee=(e,t,o)=>c(t).startsWith(`${c(e)}_`)&&c(t)!==c(`${e}${$}`)&&o!==null&&(o.includes("json_extract(")||o.trimEnd().endsWith(ce)),Te=e=>{const t=new Map;for(const o of _(e,n`SELECT name, table_name FROM ${n.identifier(g)}`))t.set(c(o.name),{name:o.name,tableFolded:c(o.table_name)});return t},S=(e,t,o)=>{const d=c(t);e.ledger.has(d)||(_(e.sql,n`INSERT OR IGNORE INTO ${n.identifier(g)} (name, table_name) VALUES (${t}, ${o})`),e.ledger.set(d,{name:t,tableFolded:c(o)}))},ge=(e,t)=>e.has(c(t)),ue=(e,t,o)=>{if(_(e,n`CREATE TABLE IF NOT EXISTS ${n.identifier(g)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),t.ledgerExists)return Te(e);const d={ledger:new Map,sql:e},r=new Map(o.map(i=>[c(i),i]));for(const i of t.indexes.values()){if(i.sql===null)continue;const a=r.get(i.tableFolded);a!==void 0&&Ee(a,i.name,i.sql)&&S(d,i.name,a)}return d.ledger},Ie=(e,t,o)=>{const d=c(t),r=new Set([...o].map(i=>c(i)));for(const[i,a]of e.ledger)a.tableFolded!==d||r.has(i)||(b(e,a.name),_(e.sql,n`DELETE FROM ${n.identifier(g)} WHERE ${n.identifier(g)}."name" = ${a.name}`),e.ledger.delete(i))},Se=(e,t,o,d)=>{const r=`${t}${se}`,i=new Set([...d].map(l=>c(l)));if(o.ttlPolicy===void 0||i.has(c(r))||N(e.catalog,r,t)&&!ge(e.ledger,r))return;const a=ae(o.ttlPolicy.field,o.softDeleteMode?.field);d.add(r);try{I(e,r,t,a,!1,[]),u(e,r,t,a,!1),S(e,r,t)}catch{}},Ae=(e,t,o,d)=>{const r=new Set;for(const i of o.indexes){const a=`${t}_${i.name}`,l=i.unique??!1,f=i.fields.map(E=>h(E)),s=n.join(f,n`, `),m=l?s:n`${s}, ${L}`;r.add(a),C(d,()=>{I(e,a,t,m,l,f),R(e,a,t,m,l,f),S(e,a,t)})}for(const[i,a]of Z(o)){if(!a.unique)continue;const l=h(i),f=`${t}_unique_${i}`;r.add(f),C(d,()=>{I(e,f,t,l,!0,[l]),R(e,f,t,l,!0,[l]),S(e,f,t)})}Se(e,t,o,r),Ie(e,t,r)},Le=(e,t,o,d)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!J(e,d))){for(const r of o.searchIndexes)z(e,X(y(t,r.name)));k(e,t,o)}},he=(e,t,o)=>{if(o.geoIndexes)for(const d of o.geoIndexes){const r=ee(t,d.name);_(e.sql,n`CREATE TABLE IF NOT EXISTS ${n.identifier(r)} (${n.identifier("__id__")} TEXT PRIMARY KEY, ${n.identifier("__geohash__")} TEXT NOT NULL, ${n.identifier("__lat__")} REAL NOT NULL, ${n.identifier("__lng__")} REAL NOT NULL)`);const i=`${t}__geo_${d.name}__btree`;u(e,i,r,n`${n.identifier("__geohash__")} ASC, ${n.identifier("__id__")} ASC`,!1)}},xe=(e,t,o)=>{if(o.aggregateIndexes)for(const d of o.aggregateIndexes){const r=O(t,d.name);_(e,n`CREATE TABLE IF NOT EXISTS ${n.identifier(r)} (${te} TEXT PRIMARY KEY, ${oe} REAL, ${x} INTEGER NOT NULL DEFAULT 0)`),_(e,n`PRAGMA table_info(${n.identifier(r)})`).toArray().some(a=>a.name==="__count__")||_(e,n`ALTER TABLE ${n.identifier(r)} ADD COLUMN ${x} INTEGER NOT NULL DEFAULT 0`)}},Re=(e,t,o)=>{const d=_(e.sql,n`PRAGMA table_info(${n.identifier(t)})`).toArray().map(r=>r.name).filter(r=>r.startsWith("__sort_k"));if(d.length>0&&(d.length!==o.length||d.some((r,i)=>r!==o[i]))){_(e.sql,n`DROP TABLE ${n.identifier(t)}`);const r=c(t);for(const[i,a]of e.catalog)a.tableFolded===r&&e.catalog.delete(i)}},Ce=(e,t,o)=>{if(o.rankIndexes)for(const d of o.rankIndexes){const r=F(t,d.name),i=d.sortBy.map((E,T)=>re(T)),a=i.map(E=>n`${n.identifier(E)} BLOB`),l=a.length>0?n`, ${n.join(a,n`, `)}`:n``;Re(e,r,i),_(e.sql,n`CREATE TABLE IF NOT EXISTS ${n.identifier(r)} (${n.identifier("__id__")} TEXT PRIMARY KEY, ${n.identifier("__partition__")} TEXT NOT NULL${l})`);const f=[n`${n.identifier("__partition__")} ASC`];for(const[E,T]of i.entries()){const M=d.sortBy[E]?.direction;f.push(n`${n.identifier(T)} ${n.raw(M==="desc"?"DESC":"ASC")}`)}f.push(n`${n.identifier("__id__")} ASC`);const s=`${t}__rank_${d.name}__btree`,m=n.join(f,n`, `);I(e,s,r,m,!1,[]),u(e,s,r,m,!1)}},He=(e,t,o={})=>{const d=o.deferBlockedUniqueIndexes?[]:void 0;o.schemaSnapshot!==void 0&&de(e,o.schemaSnapshot.hash,o.schemaSnapshot.json);const r=_e(e),i=Object.entries(t.tables).filter(([,s])=>s.shardMode?.kind!=="global");W(e);const a=ue(e,r,i.map(([s])=>s)),l={catalog:r.indexes,ledger:a,sql:e},f=[];for(const[s,m]of i)_(e,n`CREATE TABLE IF NOT EXISTS ${n.identifier(s)} (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
_creationTime REAL NOT NULL,
|
|
4
|
-
${n.identifier(Q)} TEXT NOT NULL
|
|
5
|
-
)`),u(l,`${s}${$}`,s,L,!1),Ae(l,s,m,d),Le(e,s,m,r.existingFtsTable),he(l,s,m),xe(e,s,m),Ce(l,s,m),f.push(...(m.aggregateIndexes??[]).map(E=>O(s,E.name)),...(m.rankIndexes??[]).map(E=>F(s,E.name)));return Y(e,f),o.cdc&&(B(e,{rowHistoryIndex:Object.values(t.tables).some(s=>s.dropStalePatchesMode===!0)}),G(e),P(e),H(e),K(e)),Object.values(t.tables).some(s=>s.commitOrderedMode===!0)&&v(e),ie(e),j(e),V(e),q(e),ne(e),d??[]};export{He as runShardMigrations};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-RC09zZrh.mjs";import{D as p,r as a,m as h}from"./do-sql-Cf2rnuLV.mjs";import{sqliteInList as w}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{c as $}from"./where-sql-Cb_dSAMj.mjs";const C=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=$(o,h);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},M=(o,i,r)=>{const t=u(r,void 0),n=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const m of n){const s=a(m),{id:c}=m;s!==void 0&&typeof c=="string"&&f.push({doc:s,id:c})}return f},T=(o,i,r,t)=>{const n=new Map;if(t.length===0)return n;const f=u(r,C(t)),m=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const s of m){const c=a(s),{id:d}=s;c!==void 0&&typeof d=="string"&&n.set(d,c)}return n};export{T as selectShapeMembers,M as selectShapeRows};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{sql as l}from"drizzle-orm";import{i as O,b as x}from"./json-field-path-DeJW4U9z.mjs";import{sqliteInList as C,isJsonSafe as L,bytesAsHexJson as w,WORKERD_SQLITE_LIMITS as b}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{quoteIdentifier as j}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as A,SEEK_RANGE as U}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const v={binary:(t,n,s)=>l`${t} ${l.raw(n)} ${s}`,constant:t=>t?l`1 = 1`:l`0 = 1`,connect:(t,n,s)=>l`(${t}) ${l.raw(s)} (${n})`,contains:(t,n)=>l`instr(lower(${t}), lower(${n})) > 0`,inList:(t,n,s,o)=>C(t,n,s,o),negate:t=>l`NOT (${t})`,nullCheck:(t,n)=>n?l`${t} IS NOT NULL`:l`${t} IS NULL`,value:t=>l`${t}`},h=(...t)=>{let n="";const s=[];for(const o of t)typeof o=="string"?n+=o:(n+=o.text,s.push(...o.params));return{params:s,text:n}},N=t=>({params:[t],text:"?"}),I=t=>({params:[],text:t}),st=t=>I(j(t)),ot={binary:(t,n,s)=>h(t," ".concat(n," "),N(s)),constant:t=>I(t?"1 = 1":"0 = 1"),connect:(t,n,s)=>h("(",t,") ".concat(s," ("),n,")"),contains:(t,n)=>h("instr(lower(",t,"), lower(",n,")) > 0"),inList:(t,n,s,o)=>{const i=s?" NOT IN ":" IN ",e=n.every(c=>L(c)),r=n.length>o&&!e?w(n):void 0;if(r!==void 0)return h(t,i,'(SELECT unhex("value") FROM json_each(',N(r),"))");if(n.length>o&&!e)throw new T("BAD_REQUEST",`an "in" list of ${String(n.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(n.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);if(n.length<=o){const c=[t,i,"("];for(const[a,u]of n.entries())a>0&&c.push(", "),c.push(N(u));return c.push(")"),h(...c)}return h(t,i,'(SELECT "value" FROM json_each(',N(JSON.stringify(n)),"))")},negate:t=>h("NOT (",t,")"),nullCheck:(t,n)=>h(t,n?" IS NOT NULL":" IS NULL"),value:N},M=b.boundParams/2,R=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],D=new Set(R),m=new Set(["gt","gte","lt","lte"]),k={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},d=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return!1;const n=Object.keys(t);return n.length>0&&n.every(s=>D.has(s))},P=(t,n,s,o,i)=>{const e=i.value(o.serialize(s,t));return o.containsExpr?o.containsExpr(n,e):i.contains(n,e)},F=(t,n,s,o,i)=>{const e=x(s);return e===void 0?i.constant(!1):i.connect(n,o.rangeTypeGuard(t,e),"AND")},g=(t,n,s,o,i,e,r,c)=>{if(i===null)return s==="eq"||s==="ne"?r.nullCheck(n,s==="ne"):r.constant(!1);const a=r.binary(n,o,e.serialize(i,t));return!c&&m.has(s)&&O(t)?F(t,a,i,e,r):a},G=(t,n,s,o,i,e)=>{if(!Array.isArray(o))throw new T("BAD_REQUEST",`\`${s==="IN"?"in":"notIn"}\` on "${t}" expects an array of values, received ${o===null?"null":typeof o}`);const r=o;if(r.length===0)return e.constant(s==="NOT IN");const c=r.map(u=>i.serialize(u,t)),a=s==="NOT IN";return i.inList?i.inList(n,c,a):e.inList(n,c,a,M)},$=b.boundParams/2,B=6e4,q=(t,n)=>{const s={bytes:[],hasNull:!1,numbers:[],strings:[]};for(const o of t)if(o===null)s.hasNull=!0;else if(o instanceof Uint8Array)s.bytes.push(Array.from(o,i=>i.toString(16).padStart(2,"0")).join(""));else if(typeof o=="number"&&L(o))s.numbers.push(o);else if(typeof o=="string"&&L(o))s.strings.push(o);else throw new T("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value that cannot be bound as one parameter (a non-finite number, or malformed text). Narrow the list to ${String(n)} values or fewer.`);return s},K=(t,n,s)=>{const o=[],i=l.identifier("v"),e=l.identifier("__in__"),r=a=>l`jsonb_array_elements_text(CAST(CAST(${JSON.stringify(a)} AS text) AS jsonb))`,c=(a,u)=>l`JSON_TABLE(${JSON.stringify(a)}, '$[*]' COLUMNS (${i} ${l.raw(u)} PATH '$')) ${e}`;return s.strings.length>0&&o.push(t==="postgres"?l`${n} IN (SELECT ${r(s.strings)})`:l`${n} IN (SELECT CONVERT(${i} USING utf8mb4) FROM ${c(s.strings,"LONGTEXT")})`),s.numbers.length>0&&o.push(t==="postgres"?l`${n} IN (SELECT CAST(${r(s.numbers)} AS double precision))`:l`${n} IN (SELECT ${i} FROM ${c(s.numbers,"DOUBLE")})`),s.bytes.length>0&&o.push(t==="postgres"?l`${n} IN (SELECT decode(${r(s.bytes)}, 'hex'))`:l`${n} IN (SELECT UNHEX(${i}) FROM ${c(s.bytes,"LONGTEXT")})`),o},it=t=>(n,s,o,i=$)=>{const e=Math.floor(B*i/$);if(s.length<=e){const E=l.join(s.map(y=>l`${y}`),l`, `);return o?l`${n} NOT IN (${E})`:l`${n} IN (${E})`}const r=q(s,e);if(o&&r.hasNull)return l`1 = 0`;const c=K(t,n,r),a=r.hasNull?[l`1 = NULL`]:[],u=[...c,...a],p=u.length===1?u[0]:l`(${l.join(u,l` OR `)})`;return o?l`NOT (${p})`:p},z=(t,n,s,o,i)=>{const e=s,r=[];for(const c of R){if(!(c in e))continue;const a=e[c],u=k[c];u?r.push(g(t,n,c,u,a,o,i,s[U]===!0)):c==="isNull"?r.push(i.nullCheck(n,!a)):c==="contains"?r.push(P(t,n,a,o,i)):r.push(G(t,n,c==="in"?"IN":"NOT IN",a,o,i))}return r},J=(t,n,s,o)=>{const i=s.fieldRef(t);return d(n)?z(t,i,n,s,o):n===null?[o.nullCheck(i,!1)]:[o.binary(i,"=",s.serialize(n,t))]},f=(t,n,s)=>{if(t.length<=1)return t[0];const o=Math.floor(t.length/2);return s.connect(f(t.slice(0,o),n,s),f(t.slice(o),n,s),n)},Y=(t,n,s,o)=>{const i=Array.isArray(t)?t:[],e=[];for(const r of i){const c=S(r??{},s,o);if(c!==void 0)e.push(c);else if(n==="OR")return}return e.length===0?n==="OR"?o.constant(!1):void 0:f(e,n,o)},Q=new Set(["AND","NOT","OR",A]),X=(t,n,s,o)=>{if(t===A){if(!s.relationExists)throw new T("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return s.relationExists(n)}if(t==="NOT"){const i=S(n??{},s,o);return i===void 0?o.constant(!1):o.negate(i)}return Y(n,t,s,o)},S=(t,n,s)=>{const o=[];for(const[i,e]of Object.entries(t))if(Q.has(i)){const r=X(i,e,n,s);r!==void 0&&o.push(r)}else o.push(...J(i,e,n,s));return f(o,"AND",s)},_=t=>{let n=0,s=0;const o=i=>{const e=_(i);n+=e.lists,s+=e.scalars};if(Array.isArray(t)){for(const i of t)o(i);return{lists:n,scalars:s}}if(t===null||typeof t!="object")return{lists:n,scalars:s};for(const[i,e]of Object.entries(t))i==="in"||i==="notIn"?n+=1:i==="AND"||i==="NOT"||i==="OR"||d(e)?(o(e),O(i)&&(s+=1+Object.keys(e).filter(r=>m.has(r)).length)):s+=O(i)?2:1;return{lists:n,scalars:s}},et=(t,n,s=v,o=0)=>{if(!t||Object.keys(t).length===0)return;const{lists:i,scalars:e}=_(t);if(i===0)return S(t,n,s);const r=Math.max(1,Math.floor(Math.min($,b.boundParams-e-o)/i)),c=n.inList??((a,u,p,E)=>s.inList(a,u,p,E??r));return S(t,{...n,inList:(a,u,p)=>c(a,u,p,r)},s)};export{et as c,st as i,h as j,I as r,it as s,ot as t};
|