@lunora/shard-engine 1.0.0-alpha.212 → 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.
Files changed (88) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +4 -930
  3. package/dist/index.d.ts +4 -930
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/{ADMIN_FUNCTIONS-olXwJWFQ.mjs → ADMIN_FUNCTIONS-voPpYb3p.mjs} +1 -1
  6. package/dist/packem_shared/AGG_COUNT-DzvM-UU5.mjs +1 -0
  7. package/dist/packem_shared/{AUDIT_LOG_TABLE-BFJ65SRS.mjs → AUDIT_LOG_TABLE-CGyZ2LNx.mjs} +1 -1
  8. package/dist/packem_shared/{CDC_LOG_TABLE-fCPCjSE4.mjs → CDC_LOG_TABLE-DchHJJ5G.mjs} +6 -6
  9. package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-De7z_OHV.mjs → CLIENT_WATERMARK_TABLE-CMUFBMfO.mjs} +1 -1
  10. package/dist/packem_shared/{COMMIT_SEQ_FIELD-Da1DjGqo.mjs → COMMIT_SEQ_FIELD-lEe6aaMv.mjs} +1 -1
  11. package/dist/packem_shared/CompanionMemo-CYnosDCb.mjs +1 -0
  12. package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-CPWZjliE.mjs → DATA_MIGRATION_STATE_TABLE-D5giMetp.mjs} +1 -1
  13. package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-xz76_vX6.mjs → DEFAULT_MAX_RELATION_KEYS-UrlFzZB3.mjs} +1 -1
  14. package/dist/packem_shared/{DEFAULT_MAX_RELAYS-BZLpaaq1.mjs → DEFAULT_MAX_RELAYS-BcyWWSdU.mjs} +1 -1
  15. package/dist/packem_shared/DOC_COLUMN-BNhw3l1X.mjs +1 -0
  16. package/dist/packem_shared/{DurableStreamRunner-MMlV5qKQ.mjs → DurableStreamRunner-BikgXQLq.mjs} +1 -1
  17. package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-Cdq1nHtu.mjs} +1 -1
  18. package/dist/packem_shared/{IDEMPOTENCY_TABLE-BVosXEq_.mjs → IDEMPOTENCY_TABLE-DyKgfnGa.mjs} +1 -1
  19. package/dist/packem_shared/IMPORT_MANIFEST_TTL_MS-g0o4UIT_.mjs +1 -0
  20. package/dist/packem_shared/{MAIL_RETENTION-DMolrLYt.mjs → MAIL_RETENTION-C0LZvTbG.mjs} +3 -3
  21. package/dist/packem_shared/NotUniqueError-DlNAfu1a.mjs +1 -0
  22. package/dist/packem_shared/{QUEUE_TABLE-C-goXtGd.mjs → QUEUE_TABLE-CWUNphDm.mjs} +3 -3
  23. package/dist/packem_shared/RANK_TIEBREAK-BknRdgt8.mjs +1 -0
  24. package/dist/packem_shared/{REACTOR_STATE_TABLE-D2Mn204f.mjs → REACTOR_STATE_TABLE-B2x69RYJ.mjs} +1 -1
  25. package/dist/packem_shared/{SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs → SCHEDULE_OUTBOX_TABLE-BPs0yEDb.mjs} +1 -1
  26. package/dist/packem_shared/{SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs → SCHEMA_HISTORY_MAX_VERSIONS-Cgw1Tg1r.mjs} +1 -1
  27. package/dist/packem_shared/{SEARCH_STATE_TABLE-D7w8mRsm.mjs → SEARCH_STATE_TABLE-DJywWtgJ.mjs} +1 -1
  28. package/dist/packem_shared/{SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs → SHAPE_POKE_CURSOR_TABLE-CKl7syse.mjs} +1 -1
  29. package/dist/packem_shared/VECTOR_BACKFILL_MAX_PAGES-CxiEhH8V.mjs +1 -0
  30. package/dist/packem_shared/WORKERD_SQLITE_LIMITS-C9dUlw3o.mjs +1 -0
  31. package/dist/packem_shared/{adminTokenExists-CQ0qedmu.mjs → adminTokenExists-CDwEWaFF.mjs} +1 -1
  32. package/dist/packem_shared/{appendStreamChunk-BZYgGE9Y.mjs → appendStreamChunk-DIxOE9q_.mjs} +1 -1
  33. package/dist/packem_shared/{applyInsertDefaults-CaVH3fJ7.mjs → applyInsertDefaults-Bt6LYmPD.mjs} +1 -1
  34. package/dist/packem_shared/{archiveCdcSegment-Cr8oGLfB.mjs → archiveCdcSegment-B3UKVQ9U.mjs} +1 -1
  35. package/dist/packem_shared/backfillAggregateIndexes-BkCo8Dpf.mjs +1 -0
  36. package/dist/packem_shared/buildReprojectionMigration-CCr-Pv9T.mjs +1 -0
  37. package/dist/packem_shared/{buildShapeDiff-DrXTkXKH.mjs → buildShapeDiff-CrLtKTuR.mjs} +1 -1
  38. package/dist/packem_shared/{clearMemoryTables-aMRERF0w.mjs → clearMemoryTables-CIfrwTj8.mjs} +1 -1
  39. package/dist/packem_shared/compileWhereSql-CEy6QwJx.mjs +1 -0
  40. package/dist/packem_shared/computeRankPage-De_JKnna.mjs +1 -0
  41. package/dist/packem_shared/createCompanionSync-D5cqtwqR.mjs +1 -0
  42. package/dist/packem_shared/{createReplicaLink-BapaAUfm.mjs → createReplicaLink-auEtD_6G.mjs} +1 -1
  43. package/dist/packem_shared/{ctx-db-relay-shapes-DBobAek2.mjs → ctx-db-relay-shapes-V1HnPPPX.mjs} +1 -1
  44. package/dist/packem_shared/{ctx-db-search-state-CPKPy8N6.mjs → ctx-db-search-state-Bv_NxB1g.mjs} +1 -1
  45. package/dist/packem_shared/{defineEngineContractSuite-BnnvYfoI.mjs → defineEngineContractSuite-C_pEZ8_E.mjs} +1 -1
  46. package/dist/packem_shared/describeRelationWrites-BKd7YU5R.mjs +1 -0
  47. package/dist/packem_shared/do-sql-DT8JBpG8.mjs +1 -0
  48. package/dist/packem_shared/{exportShardRows-BEzRTBwD.mjs → exportShardRows-BxhBKedl.mjs} +1 -1
  49. package/dist/packem_shared/fts-companion-Cfz-hJum.mjs +1 -0
  50. package/dist/packem_shared/ftsCompanionDdl-NFICsmqs.mjs +1 -0
  51. package/dist/packem_shared/ftsRowidMapName-CGnFBC6P.mjs +1 -0
  52. package/dist/packem_shared/{isSoftDeleted-By7iuPdW.mjs → isSoftDeleted-Dc3VHgrR.mjs} +1 -1
  53. package/dist/packem_shared/isTtlExpired-ktYeluAa.mjs +1 -0
  54. package/dist/packem_shared/{materializeExternalRows-gZqs4Rsj.mjs → materializeExternalRows-LugivbOG.mjs} +1 -1
  55. package/dist/packem_shared/param-Y0zw_1Cv.mjs +1 -0
  56. package/dist/packem_shared/rankPivotConditionSql-CUX4Vuhv.mjs +1 -0
  57. package/dist/packem_shared/runDrizzle-DAtZbzBn.mjs +1 -0
  58. package/dist/packem_shared/runShardMigrations-DeOECCjz.mjs +5 -0
  59. package/dist/packem_shared/runSql-BBRXi81G.mjs +1 -0
  60. package/dist/packem_shared/selectShapeMembers-BP30uxpp.mjs +1 -0
  61. package/dist/packem_shared/sql-engine.d-DN1kL76Y.d.mts +886 -0
  62. package/dist/packem_shared/sql-engine.d-DN1kL76Y.d.ts +886 -0
  63. package/dist/packem_shared/where-sql-AVR5KloI.mjs +1 -0
  64. package/dist/sql.d.mts +47 -0
  65. package/dist/sql.d.ts +47 -0
  66. package/dist/sql.mjs +1 -0
  67. package/package.json +5 -1
  68. package/dist/packem_shared/AGG_COUNT-BaMXGlVQ.mjs +0 -1
  69. package/dist/packem_shared/CompanionMemo-jmlDbPlr.mjs +0 -1
  70. package/dist/packem_shared/IMPORT_MANIFEST_TTL_MS-BrNT0vUO.mjs +0 -1
  71. package/dist/packem_shared/NotUniqueError-DceH7dQi.mjs +0 -1
  72. package/dist/packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs +0 -1
  73. package/dist/packem_shared/VECTOR_BACKFILL_MAX_PAGES-DbNHRd5m.mjs +0 -1
  74. package/dist/packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs +0 -1
  75. package/dist/packem_shared/backfillAggregateIndexes-BfJ2FeLv.mjs +0 -1
  76. package/dist/packem_shared/buildReprojectionMigration-wSas3lLT.mjs +0 -1
  77. package/dist/packem_shared/compileWhereSql--dIcrS0b.mjs +0 -1
  78. package/dist/packem_shared/computeRankPage-B6umzbg4.mjs +0 -1
  79. package/dist/packem_shared/createCompanionSync-DmciS_rv.mjs +0 -1
  80. package/dist/packem_shared/describeRelationWrites-omar6-u9.mjs +0 -1
  81. package/dist/packem_shared/do-sql-Cf2rnuLV.mjs +0 -1
  82. package/dist/packem_shared/fts-companion-CE3EmIjk.mjs +0 -1
  83. package/dist/packem_shared/ftsCompanionDdl-B0bFCy6d.mjs +0 -1
  84. package/dist/packem_shared/isTtlExpired-Bymg2-13.mjs +0 -1
  85. package/dist/packem_shared/runDrizzle-RC09zZrh.mjs +0 -1
  86. package/dist/packem_shared/runShardMigrations-4_ene2xR.mjs +0 -5
  87. package/dist/packem_shared/selectShapeMembers-Ce6pOHKe.mjs +0 -1
  88. 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.212",
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 v}from"@lunora/errors";import{q as _t}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as zn,l as Ue,s as Yn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Xn,stableWireKey as jt}from"@lunora/wire";import{sql as f}from"drizzle-orm";import{throwingScheduler as Zn,aggregateSqlFunction as Oe,normalizeCountArgument as Ht}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as at,encodeAggregateKey as dt,readAggregateValue as lt}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as N,CountRlsUnsupportedError as ut,selectIndexForGroupBy as eo,selectIndexForCount as to,selectIndexForAggregate as no}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as oo,searchIndexCoversTable as ro}from"./backfillAggregateIndexes-BfJ2FeLv.mjs";import{backfillAggregateIndexes as os,backfillRankIndexes as rs,backfillSearchIndexes as is}from"./backfillAggregateIndexes-BfJ2FeLv.mjs";import{appendCdcChange as io,readCdcDocAtOrBefore as so}from"./CDC_LOG_TABLE-fCPCjSE4.mjs";import{CDC_LOG_TABLE as cs,applyCdcChanges as as,bumpCdcEpoch as ds,cdcCanVouchFor as ls,cdcForkedError as us,cdcSeqLeavingRows as fs,cdcTouchesTables as hs,cdcTrimmedError as ws,compactCdcDocs as ps,cursorBelowRetainedFloor as gs,minCdcReplayableSeq as ys,minCdcSeq as $s,readCdcChangeKeys as Es,readCdcChanges as ms,readCdcCursor as Rs,readCdcEpoch as vs,trimCdcChanges as Ss}from"./CDC_LOG_TABLE-fCPCjSE4.mjs";import{allocateCommitSeq as co,COMMIT_SEQ_FIELD as ao}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as lo}from"./createCompanionSync-DmciS_rv.mjs";import{isMemoryTable as Kt}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Qt}from"./computeRankPage-B6umzbg4.mjs";import{SCAN_DEP as G,PRIMARY_READ as uo}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runSql as ye,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as fo,j as yt,D as ie,r as Ce,W as ho,k as ae,b as Ge,A as ft,a as je,m as pe,e as ge,s as wo,t as po,u as go,i as yo,q as Nt,h as mn,g as $o}from"./do-sql-Cf2rnuLV.mjs";import{renderSql as Rn,unionAll as vn,WORKERD_SQLITE_LIMITS as Sn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as Eo,u as mo}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as Ro,boundingBoxGeohashes as vo,haversineMeters as So,pointInBoundingBox as _o}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as To}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Ao,assertPatchAllowed as Io,operatorFields as bo,readPatchField as Vt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as xo,encodeCursor as $t,nullsOrderSuffix as Co,normalizeOrderKeys as Jt,uniqueIndexFields as Mo,buildSeekWhere as Do,decodeCursor as zt,buildSeekBeforeWhere as ko,softDeleteScope as be,applySelect as _n}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as Yt,sortColumnName as Xt,resolveRankPartition as Lo,encodePartitionKey as Fo,RANK_TIEBREAK as Wo,rankPivotConditionSql as Bo}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Zt}from"./ADMIN_WILDCARD-BUrgWQ3-.mjs";import{idIndexKey as qo,withUnknownIndexKeys as Po,indexKeysForRow as Uo,buildIndexRange as Oo}from"./buildIndexRange-BTChxh3k.mjs";import{r as Je,j as Me,c as ee,t as Xe,i as en}from"./where-sql-Cb_dSAMj.mjs";import{serializeSqlValue as De}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as ke}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Go,isPushableWhere as jo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Ho,findRelated as Ko}from"./RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{assertFlatPredicate as ht,findManyPage as Qo,relationPredicateTables as No,resolveRelationPredicates as Vo,composeReadPredicate as Jo}from"./DEFAULT_MAX_RELATION_KEYS-xz76_vX6.mjs";import{describeRelationWrites as zo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as He,transformOnlyDefinition as Yo,applyInsertDefaults as Et,resolveWith as Xo,relationHooks as Zo,applyOnDelete as er,fanOutScalarCounts as tr,CASCADE_MAX_ROWS as nr}from"./applyInsertDefaults-CaVH3fJ7.mjs";import{guardWriter as or}from"./RLS_UNWRAP_SYMBOL-CWo1Bk9y.mjs";import{mayHoldProjectedValue as rr}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as ir}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as de}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as tn,runTriggers as sr}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ts,migrateClientWatermark as As,readClientWatermark as Is}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as xs,readIdempotent as Cs,trimIdempotent as Ms,writeIdempotent as Ds}from"./IDEMPOTENCY_TABLE-BVosXEq_.mjs";import{runShardMigrations as Ls}from"./runShardMigrations-4_ene2xR.mjs";import{selectShapeMembers as Ws,selectShapeRows as Bs}from"./selectShapeMembers-Ce6pOHKe.mjs";const cr=n=>{const i=atob(n),o=Uint8Array.from(i,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},ar=()=>new v("INVALID_CURSOR","invalid cursor"),nn=16,on=8,Z=1024,Tt=(n,i)=>i.query(n),dr=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[s,a]of i.entries()){const w=s===i.length-1;let g=0;for(const E of n)(w?E.startsWith(a):E===a)&&(g+=1);if(g===0)return 0;o+=g}return o},lr=(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 a=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:a+String.fromCodePoint(s)}},ur=(n,i,o)=>{const s={eq:(a,w)=>{if(!n.definition.filterFields?.includes(a))throw new v("INTERNAL",`field "${a}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=on)throw new v("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(on)} .eq() filters are supported per search query`);return n.filters.push({field:a,value:w}),s},search:(a,w)=>{const g=n;if(a!==g.definition.field)throw new v("INTERNAL",`search index "${g.indexName}" on table "${i}" indexes "${g.definition.field}", not "${a}"`);const E=Tt(w,o).length;if(E>nn)throw new v("BAD_REQUEST",`search index "${g.indexName}" on table "${i}": at most ${String(nn)} search terms are supported (got ${String(E)})`);return g.field=a,g.query=w,g.hasQuery=!0,s}};return s},fr=n=>{if(n.length>Z)throw new v("BAD_REQUEST",`more than ${String(Z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},hr=n=>Math.min(n.offset+n.numItems+1,Z),wr=n=>btoa(`search:${String(n)}`),pr=n=>{let i;try{i=cr(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},gr=n=>{if(typeof n.endCursor=="string")throw new v("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 v("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?pr(n.cursor):0;if(o===void 0)throw ar();if(o+i>=Z)throw new v("BAD_REQUEST",`search pagination reaches the ${String(Z)}-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,Z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},yr=(n,i)=>{const o=i.offset+i.numItems,s=i.numItems>0&&n.length>o;return{continueCursor:s?wr(o):null,isDone:!s,page:n.slice(i.offset,o)}},$r=n=>{if(n===void 0)return Z+1;if(!Number.isFinite(n))return Z;const i=Math.max(0,Math.floor(n));if(i>Z)throw new v("BAD_REQUEST",`search returns at most ${String(Z)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Tn=500,An=(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??Tn},In=(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)`)},Er=32,mr=1024,bn=(n,i,o,s)=>{const a=`SELECT id, _creationTime, ${ke(ie)} FROM ${ke(n)}`,w=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return i===void 0?Je(`${a} ${w}`):Me(`${a} WHERE `,i,` ${w}`)},Ze={fieldRef:n=>Je(yt(n)),rangeTypeGuard:(n,i)=>Je(fo(n,i)),serialize:De},Rr=n=>n===void 0?"":Co(n==="first"),xn=n=>{const i=n.map(o=>`${yt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Rr(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${yt("id")} ${xo(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},vr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Cn=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Sr=n=>{const i=Cn(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},_r=(n,i)=>{const o=n.order,s=Sr(n),{shape:a}=i;return s.length>0?Jt(s.map(w=>({[w]:o})),a,{pinned:Cn(n),uniqueBy:Mo(i.indexes,a)}):Jt([{_creationTime:o}],a)},Tr=(n,i,o,s)=>{const a=n.sqlConditions.map(w=>({[w.field]:{[vr[w.comparator]??"eq"]:w.value}}));if(o&&a.push(Do(i,zt(o))),s&&a.push(ko(i,zt(s))),a.length!==0)return a.length===1?a[0]:{AND:a}},Ar=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Er):n.want},mt=(n,i,o,s,a,w,g)=>{const E=_r(s,o),y=xn(E),u=[],{filters:C,want:A}=w;let T=w.cursor??void 0,b=Ar(w);if(A===0)return{documents:u,orderKeys:E};for(;;){const q=ee(Tr(s,E,T,w.endCursor),Ze,Xe),P=bn(i,a&&q?Me(q," AND ",a):a??q,y,b),W=ye(n,P.text,...P.params).toArray();let U={};g(W.length);for(const j of W)if(U=Ce(j),C.every(te=>te(U))&&u.push(U)===A)return{documents:u,orderKeys:E};if(b===void 0||W.length<b)return{documents:u,orderKeys:E};T=$t(U,E),b=Math.max(b,Math.min(b*2,mr))}},Ir=(n,i,o,s,a,w,g,E)=>{const y=Math.max(0,Math.floor(a.numItems));if(typeof a.endCursor=="string"){const{documents:q,orderKeys:P}=mt(n,i,o,s,w,{cursor:a.cursor,endCursor:a.endCursor,filters:g.all,selective:g.selective,want:void 0},E),W=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:a.endCursor,isDone:!0,page:q,splitCursor:W?$t(W,P):null}}const{documents:u,orderKeys:C}=mt(n,i,o,s,w,{cursor:a.cursor,filters:g.all,selective:g.selective,want:y+1},E),A=u.length>y,T=A?u.slice(0,y):u,b=T.at(-1);return{continueCursor:A&&b?$t(b,C):null,isDone:!A,page:T}},et=n=>{const i=new Map;return o=>{const s=i.get(o);if(s!==void 0)return s;const a=n(ke(o));return i.set(o,a),a}},$e=ke(ie),br=et(n=>`INSERT INTO ${n} (id, _creationTime, ${$e}) VALUES (?, ?, ?)`),rn=et(n=>`UPDATE ${n} SET ${$e} = ? WHERE id = ? AND ${$e} = ?`),xr=et(n=>`UPDATE ${n} SET _creationTime = ?, ${$e} = ? WHERE id = ? AND ${$e} = ?`),Cr=et(n=>`DELETE FROM ${n} WHERE id = ? AND ${$e} = ?`),Mr="SELECT changes() AS changed",sn=new Map,Dr="",kr=n=>{const i=JSON.stringify(n),o=sn.get(i);if(o!==void 0)return o;const s=n.map(w=>f`SELECT ${f.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${f.identifier(ie)} FROM ${f.identifier(w)} WHERE id = ${Dr}`),{sql:a}=Rn("sqlite",f`${vn(s)} LIMIT 1`);return sn.set(i,a),a},Lr=(n,i)=>i.map(()=>n),Fr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Wr=n=>{if(!Fr.test(n))throw new v("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Rt=n=>{if(n.includes("\0"))throw new v("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},Br=(n,i,o,s)=>{if(o!==!0)return;const a=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const w of i){const g=a?Et(n,w,s)._id:w._id;typeof g=="string"&&Rt(g)}},cn=50,Ke=Math.floor(Sn.boundParams/3),an=Sn.boundParams,qr=128,ze=n=>new v("BATCH_LIMIT_EXCEEDED",n,{status:400}),Qe=(n,i,o)=>{In(n,An(i,o,ze),o,ze)},dn=async(n,i,o,s,a)=>{const w=An(s,a,ze),{page:g}=await n.findMany(i,Number.isFinite(w)?{limit:w+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>w&&In(Math.max(await n.count(i,{where:o}),g.length),w,a,ze),g},Pr=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},Ur=n=>Math.max(n,Z),Mn=(n,i)=>{const o=n.filters.map(s=>f`${ge(s.field)} = ${De(s.value)}`);return i&&o.push(i),o},Or=(n,i,o,s,a)=>{const w=Tt(o.query,_t(o.definition.language));if(w.length===0)return[];const g=zn(i,o.indexName),E=`${g}__vocab`,y=w.length-1,u=w.map((P,W)=>{const U=lr(P,W===y),j=U.exact?f`${f.identifier("term")} = ${U.lower}`:f`${f.identifier("term")} >= ${U.lower} AND ${f.identifier("term")} < ${U.upper}`;return f`SELECT ${f.identifier("doc")}, ${f.raw(String(W))} AS ${f.identifier("__term__")}, COUNT(*) AS ${f.identifier("__n__")} FROM ${f.identifier(E)} WHERE ${j} GROUP BY ${f.identifier("doc")}`}),C=w.map((P,W)=>f`SUM(CASE WHEN u.${f.identifier("__term__")} = ${f.raw(String(W))} THEN u.${f.identifier("__n__")} ELSE 0 END)`),A=f`SELECT f.${f.identifier(Ue)} AS ${f.identifier(Ue)}, ${f.join(C,f` + `)} AS ${f.identifier("__score__")} FROM (${vn(u)}) u JOIN ${f.identifier(g)} f ON f.rowid = u.${f.identifier("doc")} GROUP BY f.${f.identifier(Ue)} HAVING ${f.join(C.map(P=>f`${P} > 0`),f` AND `)}`,T=Mn(o,a);let b=f`SELECT m.id, m._creationTime, m.${f.identifier(ie)}, s.${f.identifier("__score__")} AS ${f.identifier("__score__")} FROM (${A}) s JOIN ${f.identifier(i)} m ON m.id = s.${f.identifier(Ue)}`;T.length>0&&(b=f`${b} WHERE ${f.join(T,f` AND `)}`),b=f`${b} ORDER BY s.${f.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${f.raw(String(s))}`;const q=[];for(const P of K(n,b)){const W=mn(P);if(W){const U=P.__score__;q.push({document:W,score:typeof U=="number"?U:Number(U??0)})}}return q},Gr=(n,i,o,s,a)=>{const w=_t(o.definition.language),g=Tt(o.query,w);if(g.length===0)return[];const E=Mn(o,a);let y=f`SELECT id, _creationTime, ${f.identifier(ie)} FROM ${f.identifier(i)}`;E.length>0&&(y=f`${y} WHERE ${f.join(E,f` AND `)}`),y=f`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${f.raw(String(Ur(s)))}`;const u=K(n,y).toArray(),C=[];for(const A of u){const T=mn(A);if(!T)continue;const b=dr(Yn(T,o.definition),g);b>0&&C.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:b})}return C.sort((A,T)=>T.score-A.score||T.creationTime-A.creationTime||A.id.localeCompare(T.id)),C.slice(0,s).map(A=>({document:A.doc,score:A.score}))},wt=(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 v("BAD_REQUEST",`geo index "${s}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},jr=(n,i)=>{const o=n,s={near:(a,w)=>{if(o.within)throw new v("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(wt(a,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new v("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:a.lat,lng:a.lng},radiusMeters:w},s},within:a=>{if(o.near)throw new v("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(wt(a.sw,".within() sw corner",i,o.indexName),wt(a.ne,".within() ne corner",i,o.indexName),a.sw.lat>a.ne.lat)throw new v("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(a.sw.lng>a.ne.lng)throw new v("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:a.ne.lat,lng:a.ne.lng},sw:{lat:a.sw.lat,lng:a.sw.lng}},s}};return s},Hr=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:s,lng:a}=o;return typeof s=="number"&&typeof a=="number"?{lat:s,lng:a}:void 0},Kr=(n,i)=>{const o=Hr(n,i.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const a=So(i.near.point,o);return a<=i.near.radiusMeters?{creationTime:s,distance:a}:void 0}return _o(o,i.within)?{creationTime:s,distance:0}:void 0},Qr=(n,i,o,s)=>{if(!o.near&&!o.within)throw new v("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const a=o.near?Ro(o.near.point,o.near.radiusMeters):vo(o.within),w=$o(i,o.indexName),g=a.map(A=>f`(g.${f.identifier("__geohash__")} >= ${A} AND g.${f.identifier("__geohash__")} < ${`${A}{`})`),E=[f`(${f.join(g,f` OR `)})`];s&&E.push(s);const y=f`SELECT m.id, m._creationTime, m.${f.identifier(ie)} FROM ${f.identifier(w)} g JOIN ${f.identifier(i)} m ON m.id = g.${f.identifier("__id__")} WHERE ${f.join(E,f` AND `)}`,u=K(n,y).toArray(),C=[];for(const A of u){const T=Ce(A),b=T?Kr(T,o):void 0;T&&b&&C.push({creationTime:b.creationTime,distance:b.distance,doc:T})}return C.sort((A,T)=>A.distance-T.distance||T.creationTime-A.creationTime),C},Dn=(n,i,o,s)=>{const a=[];for(const w of n)if(i.every(g=>g(s(w)))&&(a.push(w),typeof o=="number"&&a.length>=o))break;return a},Nr=(n,i,o,s,a,w=()=>{})=>{const g=o.within!==void 0,E=Qr(n,i,o,a).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return w(E.length),typeof s=="number"?E.slice(0,Math.max(0,Math.floor(s))):E},ln=(n,i,o,s,a,w,g=()=>{})=>{const{geo:E}=o;if(!E)throw new v("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=a.length>0,u=Nr(n,i,E,y?void 0:w,s,g);return y?Dn(u,a,w,C=>C.document):u},un=(n,i,o)=>{const s=n.shape[i];if(s!==void 0&&rr(s))throw new v("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)`)},Vr=n=>{let i=0;const o=[],s={...Ze,relationExists:a=>{const{childWhere:w,negated:g,parentTable:E,relation:y}=a,u=`__rel_${String(i)}`,C=o.at(-1)??E;i+=1,n(y.table,G);const A=y.kind==="one"?y.field:y.references,T=y.kind==="one"?y.references:y.field,b=Je(`${Nt(u,T)} = ${Nt(C,A)}`);o.push(u);const q=ee(w,s,Xe);o.pop();const P=q===void 0?b:Me(b," AND ",q),W=Me("EXISTS (SELECT 1 FROM ",en(y.table)," AS ",en(u)," WHERE ",P,")");return g?Me("NOT ",W):W}};return s};class Jr extends v{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const zr=/\s/u,Yr=String.fromCodePoint(0),fn=(n,i,o)=>{if(!n.tables[i])throw new v("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||zr.test(o)||o.includes(Yr)?null:o},kn=(n,i,o,s=()=>{},a=()=>{},w=()=>{},g)=>{const E=i.tables[o];if(!E)throw new v("INTERNAL",`unknown table: ${o}`);const y=be(E.softDeleteMode,void 0),u=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},C=()=>{const S=N(y,u.pushedWhere);return S?ee(S,pe):void 0},A=()=>{const S=N(y,u.pushedWhere);return S?ee(S,Ze,Xe):void 0},T=()=>[...u.inMemoryFilters,...u.verifyFilters];let b=0;const q=S=>{const{search:D}=u;if(!D)throw new v("INTERNAL","runSearchFetch called without a staged search");oo(go(n),o,E);const k=u.inMemoryFilters.length>0,F=$r(k?void 0:S),L=yo(n);if(L&&!ro(n,o,D.definition))throw new v("SEARCH_INDEX_BUILDING",`search index "${D.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 Ee=C(),ne=L?Or(n,o,D,F,Ee):Gr(n,o,D,F,Ee);!k&&S===void 0&&fr(ne);const le=T();return b=ne.length,le.length>0?Dn(ne,le,S,Y=>Y.document):ne},P=S=>q(S).map(D=>D.document),W=S=>{const D=gr(S);return yr(P(hr(D)),D)},U=()=>{if(u.search||u.geo||u.indexName===void 0){a(void 0);return}a(Oo(o,u.indexName,u.indexFields,u.sqlConditions,De))},j=S=>{U();let D=0;const k=(()=>{if(u.search){const F=P(S);return D=b,F}return u.geo?ln(n,o,u,C(),T(),S,F=>{D=F}).map(F=>F.document):mt(n,o,E,u,A(),{filters:T(),selective:u.inMemoryFilters.length>0,want:S===void 0?void 0:Math.max(0,Math.floor(S))},F=>{D+=F}).documents})();return w(Math.max(D,k.length)),k},te=()=>{if(!u.search&&!u.geo)throw new v("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);U();let S=0;const D=(()=>{if(u.search){const k=q(void 0);return S=b,k}return ln(n,o,u,C(),T(),void 0,k=>{S=k})})();return w(Math.max(S,D.length)),D},V={async*[Symbol.asyncIterator](){const S=kn(n,i,o,s,a,w,{...u,indexFields:[...u.indexFields],inMemoryFilters:[...u.inMemoryFilters],sqlConditions:[...u.sqlConditions],verifyFilters:[...u.verifyFilters]});if(u.search){yield*await S.collect();return}let D;for(;;){const k=await S.paginate({cursor:D??null,numItems:qr});if(yield*k.page,k.isDone||k.continueCursor===null)return;D=k.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return te()},filter(S){const D=Go(S);return D!==void 0&&jo(D,E.shape)?(u.pushedWhere=N(u.pushedWhere,D),u.verifyFilters.push(S)):u.inMemoryFilters.push(S),V},async first(){return j(1)[0]??null},order(S){return u.order=S==="desc"?"desc":"asc",V},async paginate(S){let D=0;if(U(),u.search){const F=W(S);return w(F.page.length),F}if(u.geo)throw new v("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const k=Ir(n,o,E,u,S,A(),{all:T(),selective:u.inMemoryFilters.length>0},F=>{D+=F});return w(Math.max(D,k.page.length)),k},async take(S){return j(S)},async unique(){const S=j(2);if(S.length>1)throw new Jr(`unique() on table "${o}" matched ${String(S.length)} documents; expected at most one`);return S[0]??null},withGeoIndex(S,D){const k=(E.geoIndexes??[]).find(L=>L.name===S);if(!k)throw new v("INTERNAL",`unknown geo index "${S}" on table "${o}"`);s(o,S,"geo");const F={definition:k,indexName:S};if(u.geo=F,D(jr(F,o)),!F.near&&!F.within)throw new v("INTERNAL",`geo index "${S}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return V},withIndex(S,D){const k=E.indexes.find(F=>F.name===S);if(!k)throw new v("INTERNAL",`unknown index "${S}" on table "${o}"`);return s(o,S,"index"),u.indexName=S,u.indexFields=k.fields,D&&D(Pr(u)),V},withSearchIndex(S,D){const k=(E.searchIndexes??[]).find(L=>L.name===S);if(!k)throw new v("INTERNAL",`unknown search index "${S}" on table "${o}"`);s(o,S,"search");const F={definition:k,field:k.field,filters:[],hasQuery:!1,indexName:S,query:""};if(u.search=F,D(ur(F,o,_t(k.language))),!F.hasQuery)throw new v("INTERNAL",`search index "${S}" on table "${o}" requires a .search(field, query) call`);return V}};return V},pt=(n,i,o,s)=>{const a=o;for(const[w,g]of po(n)){if(g.serverDefault){w in i&&(a[w]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(w in i)&&(a[w]=g.onUpdateFn())}},hn=5,wn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new v("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},pn=["_commitSeq","_creationTime","_id"],Ne=n=>pn.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!pn.includes(i))):n,Xr=/unique constraint failed/i,Zr=n=>n instanceof Error&&Xr.test(n.message),ei=/string or blob too big/iu,ti=(n,i)=>{if(!(!(n instanceof Error)||!ei.test(n.message)))throw new v("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.`)},vt=(n,i,o,s)=>{try{ye(n,o,...s)}catch(a){throw Zr(a)?new de(`unique constraint violation on "${i}"`,"unique"):(ti(a,i),a)}},Ve=(n,i,o,s)=>{if(vt(n,i,o,s),ye(n,Mr).one().changed===0)throw new de(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},gn=(n,i,o,s,a,w,g)=>{const E=[];for(let A=0;A<o.length+1;A+=1){const T=o[A],b=s[A],q=b?.direction==="desc"?"desc":"asc",P=T===void 0||b===void 0?f`${f.identifier(Wo)} < ${g}`:Bo(T,w[A],q,!1);if(P===void 0)continue;const W=[];for(let j=0;j<A;j+=1)W.push(f`${f.identifier(o[j])} IS ${w[j]}`);W.push(P);const[U]=W;E.push(W.length===1&&U!==void 0?U:f`(${f.join(W,f` AND `)})`)}const y=E.length>0?f.join(E,f` OR `):f`1 = 0`,u=K(n,f`SELECT COUNT(*) AS c FROM ${f.identifier(i)} WHERE ${f.identifier("__partition__")} = ${a} AND (${y})`).one(),C=K(n,f`SELECT COUNT(*) AS c FROM ${f.identifier(i)} WHERE ${f.identifier("__partition__")} = ${a}`).one();return{before:u.c,total:C.c}},ni=n=>{const i=new Map;for(const[s,a]of Object.entries(n.tables))for(const w of Object.values(a.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:s,op:w.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const a=new Set,w=[s];for(let g=w.pop();g!==void 0;g=w.pop())for(const{holder:E,op:y}of i.get(g)??[]){if(E===s||tn(n,E,y))return!0;a.has(E)||(a.add(E),w.push(E))}return!1};return new Set(Object.entries(n.tables).filter(([s,a])=>a.shardMode?.kind==="global"||tn(n,s,"delete")||o(s)).map(([s])=>s))},oi=n=>{const i=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&i.set(o,s.softDeleteMode.field);return i},gt=new WeakMap,ri=(n,i)=>{let o=gt.get(i.tables);if(!gt.has(i.tables)){const a=Object.keys(i.tables).map(w=>w.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=a.length===0?void 0:new RegExp(`"(${a.join("|")})"`,"gu"),gt.set(i.tables,o)}if(o===void 0)return;const s=new Set;for(const a of n.matchAll(o))s.add(a[1]);return s.size===1?[...s][0]:void 0},ii=(n,i,o)=>{for(const s of n){const a=s,w=a?.[ie];if(typeof w=="string"){const g=a?.id,E=mo(w);typeof g!="string"?i.recordReadBytes(E):o===void 0?i.recordDocumentRead(`${g}\0${String(E)}`,E):i.recordDocumentRead(`${o}\0${g}`,E)}}},si=(n,i,o)=>{if(i===void 0)return n;const s=(a,...w)=>{const g=n.exec(a,...w),E=g.one.bind(g),y=g[Symbol.iterator].bind(g),u=o===void 0?void 0:ri(a,o);let C=!1;const A=T=>{ii(T,i,u)};return g.toArray=()=>{const T=[];for(const b of{[Symbol.iterator]:y})A([b]),T.push(b);return T},g.one=()=>{C=!0;try{const T=E();return A([T]),T}finally{C=!1}},g[Symbol.iterator]=function*(){for(const b of{[Symbol.iterator]:y})C||A([b]),yield b},g};return new Proxy(n,{get:(a,w)=>w==="exec"?s:w===ho?a:Reflect.get(a,w,a)})},ci=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),ai=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),xe=(n,i,o)=>{if(typeof n!="object"||n===null)return;const s=Eo(n);if(s===void 0)return;const a=n._id;typeof a=="string"?o.recordDocumentRead(`global\0${i}\0${a}`,s):o.recordReadBytes(s)},Ye=(n,i,o,s)=>{if(typeof n!="object"||n===null)return;const a=n;switch(i){case"lookup":{xe(a.row,typeof a.tableName=="string"?a.tableName:o,s);return}case"page":{for(const w of a.page??[])xe(w,o,s);return}case"rows":{for(const w of Array.isArray(n)?n:[n])xe(w,o,s);return}default:for(const w of Array.isArray(n)?n:[])xe(w.document,o,s)}},Ln=(n,i,o)=>new Proxy(n,{get:(s,a)=>{const w=Reflect.get(s,a,s);if(typeof w!="function")return w;if(a===Symbol.asyncIterator)return async function*(){for await(const y of Reflect.apply(w,s,[]))xe(y,i,o),yield y};const g=ai.get(a);return(...E)=>{const y=Reflect.apply(w,s,E);return g!==void 0?Promise.resolve(y).then(u=>(Ye(u,g,i,o),u)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?Ln(y,i,o):y}}}),di=new Set(["findFirst","findFirstOrThrow","findMany"]),li=n=>{const i=n[1],o=i?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(i).filter(([g])=>g!=="select")),a=s.with,w=g=>_n(g,o,a);return{args:[n[0],s,...n.slice(2)],project:(g,E)=>typeof g!="object"||g===null?g:E==="page"?{...g,page:w(g.page)}:w([g])[0]}},yn=256,St=4096,ui=1024*1024,fi=async(n,i,o,s)=>{const a=i[1]??{},w=[];let{cursor:g}=a,E=yn,y=0;for(;;){const u=await n([i[0],{...a,cursor:g,limit:E},...i.slice(2)]);if(Array.isArray(u))return Ye(u,"rows",o,s),[...w,...u];const C=s.headroom().readBytes;if(Ye(u,"page",o,s),w.push(...u.page),u.isDone||typeof u.continueCursor!="string")return{continueCursor:null,isDone:!0,page:w};g=u.continueCursor,y+=s.headroom().readBytes-C,E=y>0?Math.min(St,Math.max(yn,Math.floor(ui*w.length/y))):St}},hi=(n,i)=>n===void 0||i===void 0?n:new Proxy(n,{get:(o,s)=>{const a=Reflect.get(o,s,o);if(typeof a!="function")return a;if(s==="query")return(...g)=>Ln(Reflect.apply(a,o,g),String(g[0]),i);const w=ci.get(s);return w===void 0?a:async(...g)=>{const E=di.has(s)?li(g):void 0;let y=E?.args??g;const u=String(g[0]),C=y[1],A=s==="findMany"&&typeof C?.endCursor=="string",T=s==="findMany"&&typeof C?.limit!="number"&&!A;if(A&&typeof C.limit!="number"&&(y=[y[0],{...C,limit:St},...y.slice(2)]),T){const q=await fi(P=>Reflect.apply(a,o,P),y,u,i);return E===void 0?q:E.project(q,w)}const b=await Reflect.apply(a,o,y);return Ye(b,w,u,i),E===void 0?b:E.project(b,w)}}}),$n=new WeakMap,En=new WeakMap,wi=500,pi=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{headroom:s}=n,a=$n.get(n)??{value:void 0},w=En.get(n)??{value:0};let g;const E=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};$n.set(e,a),En.set(e,w),g=pi(e)}return g},y=si(n.sql,s,n.schema),{schema:u}=n,C=n.broadcast??(()=>{}),A=(e,t)=>{if(!Object.hasOwn(u.tables,e))throw new v("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},T=Ho(u),b=new Map;for(const e of T){const t=r=>(u.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&b.set(e.sourceTable,[...b.get(e.sourceTable)??[],e])}const q=(e,t,r)=>{for(const c of b.get(e)??[]){const l=t[c.column];if(typeof l!="string"||r?.[c.column]===l||c.targetTable===e&&t._id===l)continue;if(K(y,f`SELECT 1 FROM ${f.identifier(c.targetTable)} WHERE id = ${l} LIMIT 1`).toArray().length===0)throw new v("VALIDATION_ERROR",`${c.name} references ${c.targetTable} row "${l}", which does not exist`)}},P=zo(u,n.inTransaction),W=ni(u),U=oi(u),j=()=>n.inTransaction?.()===!0,te=e=>u.tables[e]?.commitOrderedMode!==!0?{}:((a.value===void 0||!j())&&(a.value=co(y)),{[ao]:a.value}),V=(e,...t)=>{const r=u.tables[e]?.indexes??[],c=[];let l;for(const p of t)p&&(typeof p._id=="string"&&p._id!==l&&(l=p._id,c.push(qo(l))),c.push(...Po(r,Uo(r,p,De))));return c.length>0?c:void 0},S=n.onRead??(()=>{}),D=e=>{Kt(u.tables[e])&&S(Zt,Zt)},k=n.onReadRange??(e=>{S(e.table,G)}),F=e=>{D(e.table),k(e)},L=(e,t,r)=>{t!==void 0&&(r===!0||t!==G)&&s?.recordRead(1),D(e),S(e,t,r)},Ee=(e,t)=>{const r=e.row._id;L(e.tableName,typeof r=="string"?r:t,typeof r=="string")},ne=n.onIndexUse??(()=>{}),le=n.onWrite??(()=>{}),Y=e=>{s?.recordWrite(e)},me=async e=>{Y(e.doc),await le(e)},{cache:ue}=n,Re=n.clock??(()=>Date.now()),At=n.idGenerator??(()=>crypto.randomUUID()),It=n.scheduler??Zn,ve=hi(n.globalDb,s),fe=n.auth??{identity:null,userId:null},bt=n.cdc??!1,tt=It,Fn=ir({scheduler:typeof tt.list=="function"&&typeof tt.get=="function"?tt:void 0,storage:n.storage}),Se=(e,t,r,c)=>{bt&&!Kt(u.tables[e])&&io(y,Re(),e,t,r,c)},xt=(e,t,r,c)=>{const l=u.tables[e];if(l?.dropStalePatchesMode!==!0||!bt)return!1;const p=i?.();if(p===void 0)return!1;const d=so(y,e,t,p);if(d===void 0)return!1;const h=bo(l,r);return Object.keys(Ne(r)).some(m=>!h.has(m)&&jt(Vt(d,m))!==jt(Vt(c,m)))},se=e=>u.tables[e]?.shardMode?.kind==="global",Ct=(e,t)=>{if(se(e)){if(!ve)throw new v("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ve}return O},nt=e=>Ct(e,"cascade"),H=(e,t)=>{if(se(e)){if(!ve)throw new v("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ve}},_e=(e,t)=>{L(e,G);for(const r of No(N(t.baseWhere,t.where),u,e,t.relationBaseWhere))L(r,G)},ce=(e,t,r)=>{ue?.invalidateTable(t),C({key:r,op:e,table:t})},Mt=async(e,t,r,c,l)=>{l&&Y(r);const p=await e.insert(t,r,c);return C({key:p,op:"insert",row:{...r,_id:p},table:t}),p},Wn=(e,t)=>Ct(e,"relation load").findMany(e,t),Bn=e=>e.through===void 0?[e.table]:[e.through.table,e.table],Dt=e=>{for(const t of e===void 0?[]:Bn(e))se(t)&&L(t,G)},kt=(e,t)=>{const r=u.tables[e]?.relationMap??{};for(const[c,l]of Object.entries(t??{})){if(c==="_count"){for(const d of Object.keys(typeof l=="object"?l:{}))Dt(r[d]);continue}const p=r[c];p===void 0||l===void 0||l===!1||(Dt(p),typeof l=="object"&&kt(p.table,l.with))}},ot=(e,t)=>(se(e)&&(L(e,G),kt(e,t.with)),Wn(e,t)),qn=e=>!se(e.table),Lt=n.relationExistsPushDown??"auto",Ft=Lt!=="never",{maxRelationKeys:Wt}=n,Le=(e,t,r)=>Vo(e,{fetcher:ot,maxRelationKeys:Wt,relationBaseWhere:r,schema:u,tableName:t}),Pn=async(e,t,r,c,l)=>{const p=H(e,"relation grouped count");if(p)return _e(e,{relationBaseWhere:l,where:c}),tr((B,Q)=>p.count(B,{relationBaseWhere:l,where:Q}),e,t,r,c);const d=u.tables[e];if(!d)throw new v("INTERNAL",`unknown table: ${e}`);L(e,G);const h=be(d.softDeleteMode,void 0),m={[t]:{in:r}},M=N(N(m,c),h),_=await Le(M,e,l),x=ee(_,pe),R=ge(t);let I=f`SELECT ${R} AS __fk__, COUNT(*) AS count FROM ${f.identifier(e)}`;x&&(I=f`${I} WHERE ${x}`),I=f`${I} GROUP BY ${R}`;const $=K(y,I).toArray();return new Map($.map(B=>[B.__fk__,B.count]))},Bt=new Set;for(const[e,t]of Object.entries(u.tables))for(const r of Object.values(t.triggerMap??{}))Bt.add(`${e} ${r.timing} ${r.op}`);const oe=(e,t,r)=>Bt.has(`${e} ${t} ${r}`),re=async(e,t,r)=>{if(w.value+=1,w.value>cn)throw w.value-=1,new de(`trigger recursion exceeded ${String(cn)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await sr({ctx:Vn,event:r,op:t,schema:u,tableName:r.table,timing:e})}finally{w.value-=1}},{ensureBackfilledForTable:Te,ensureBackfilledIndex:rt,ensureRankBackfilled:it,ensureRankBackfilledForTable:Ae,syncAggregates:Fe,syncCompanionsForInsert:st,syncGeo:We,syncRanks:he,syncSearch:Be}=lo({broadcast:C,indexKeysFor:(e,t)=>V(e,t),invalidateCache:(e,t,r)=>ue?.invalidate(e,t,V(e,r)),recordCdc:Se,schema:u,sql:y,verified:n.companionMemo?.verified}),Un=async(e,t)=>{const r=t.filter(({document:c,id:l})=>{try{return st(e,l,c),!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:c,id:l}of r)if(X(l,e)?.docJson===ae(c))try{await le({doc:c,id:l,op:"insert",table:e})}catch(p){console.warn(`[@lunora/shard-engine] insertManyUnsafe: write report of committed row "${l}" in "${e}" failed:`,p)}},qt=(e,t,r)=>{const{shardMode:c}=t;if(c?.kind==="shardBy"&&!(c.field!==void 0&&(r.partitionBy??[]).includes(c.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${c.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})},Pt=e=>Object.entries(u.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Ie=e=>e===void 0||se(e)?ve:void 0,On=e=>Object.entries(u.tables).flatMap(([t,r])=>se(t)?Object.values(r.relationMap??{}).flatMap(c=>c.through!==void 0||c.kind!=="one"||c.table!==e?[]:c.onDelete!=="cascade"&&c.onDelete!=="set null"?[]:[{action:c.onDelete==="cascade"?"delete":"update",field:c.field,holderTable:t,references:c.references}]):[]),Gn=async(e,t,r,c)=>r==="_id"?c:(await e.get(t,c))?.[r],jn=async(e,t,r,c,l)=>{const p=[];let d;do{const h=await e.findMany(t,{cursor:d,includeDeleted:l,limit:wi,where:{[r]:c}});for(const m of h.page)p.push(String(m._id));d=h.isDone?void 0:h.continueCursor??void 0}while(d!==void 0&&p.length<=nr);return p},Hn=async(e,t,r,c,l,p)=>{const{action:d,field:h,holderTable:m,references:M}=r,_=await Gn(e,t,M,c);if(_==null)return{effects:[],toExpand:[]};const x=await jn(e,m,h,_,p),R=x.filter($=>!l.announced.has(`${d}:${m}:${$}`)),I=d==="delete"?x.filter($=>!l.expanded.has(`${m}:${$}`)):[];for(const $ of R)l.announced.add(`${d}:${m}:${$}`);for(const $ of I)l.expanded.add(`${m}:${$}`);return{effects:R.map($=>({id:$,op:d,table:m})),toExpand:I}},Ut=async(e,t,r,c,l)=>{const p=[];for(const d of On(t))for(const h of r){const m=await Hn(e,t,d,h,c,l);p.push(...m.effects),m.toExpand.length>0&&p.push(...await Ut(e,d.holderTable,m.toExpand,c,l))}return p},ct=async(e,t,r,c,l)=>{for(let d=0;d<r.length;d+=1)Y(void 0);const p=c?.skipOnDelete===!0?[]:await Ut(e,t,r,{announced:new Set,expanded:new Set},c?.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)ce("delete",t,d)}for(const d of r)try{await e.delete(t,d,c)}finally{ce("delete",t,d)}return{deleted:r.length}}finally{for(const d of p)ce(d.op,d.table,d.id)}},X=(e,t)=>{const r=Pt(t);for(let c=0;c<r.length;c+=an){const l=r.slice(c,c+an),[p]=ye(y,kr(l),...Lr(e,l)).toArray();if(!p)continue;const d=p.__t__,h=Ce(p);if(typeof d!="string"||!h)return;const m=p[ie];return{docJson:typeof m=="string"?m:ae(m??{}),row:h,tableName:d}}},Ot={assertRankPartitionLocal:qt,ensureRankBackfilled:it,onRead:L,rowToDocument:Ce,schema:u,sql:y},Kn=(e,t,r)=>{const c=ee(r,pe);return c===void 0||K(y,f`SELECT 1 FROM ${f.identifier(e)} WHERE ${f.identifier("id")} = ${t} AND ${c}`).toArray().length>0},Qn=(e,t,r,c)=>xt(e,t,r,c)?(o?.({fields:Object.keys(Ne(r)),id:t,table:e}),!0):!1,Nn=async(e,t,r,c,l)=>{const p=X(t,e);if(!p)return{applied:!1,doc:null};if(L(e,t),!Kn(e,t,r.where)||Qn(e,t,r.patch,p.row))return{applied:!1,doc:p.row};try{await l(r.patch)}catch(d){if(d instanceof de&&d.kind==="occ"&&c)return;throw d}return{applied:!0,doc:X(t,e)?.row??null}},Gt=async(e,t,r,c)=>{const{fetchLimit:l,limit:p,orderKeys:d,predicate:h}=await Jo(t,r,{canPushExists:Ft?qn:void 0,existsPushMode:Lt==="always"?"always":"auto",fetcher:ot,maxRelationKeys:Wt,schema:u,tableName:e}),m=Ft?Vr(c):Ze,M=ee(h,m,Xe),_=bn(e,M,xn(d),l);return{limit:p,orderKeys:d,statement:_}},O={system:Fn,async aggregate(e,t){const r=H(e,"aggregate");if(r)return _e(e,t),r.aggregate(e,t);const c=u.tables[e];if(!c)throw new v("INTERNAL",`unknown table: ${e}`);if(Oe(t.op),t.op==="count")return O.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new v("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);L(e,G);const l=be(c.softDeleteMode,void 0),p=N(N(t.baseWhere,t.where),l),d=await Le(p,e,t.relationBaseWhere),h=d!==p;if(c.aggregateIndexes&&!t.baseWhere&&!h){const $=no(c.aggregateIndexes,t.op,t.field,t.where);if($){rt(e,$.index);const B=dt($.index.by??[],$.key),Q=at(e,$.index.name),J=K(y,f`SELECT ${Ge} AS value, ${ft} AS count FROM ${f.identifier(Q)} WHERE ${je} = ${B}`).toArray()[0];return lt(t.op,J)}}un(c,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const m=ee(d,pe),M=Oe(t.op),_=ge(t.field);let x=f`SELECT ${f.raw(M)}(${_}) AS value FROM ${f.identifier(e)}`;m&&(x=f`${x} WHERE ${m}`);const I=K(y,x).toArray()[0]?.value;return I??null},asId(e,t){const r=fn(u,e,t);if(r===null)throw new v("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=H(e,"count");if(r)return _e(e,Ht(t)),r.count(e,t);const c=u.tables[e];if(!c)throw new v("INTERNAL",`unknown table: ${e}`);const l=Ht(t);if(l.restrictsCounts)throw new ut(e);L(e,G);const p=be(c.softDeleteMode,void 0),d=N(N(l.baseWhere,l.where),p),h=await Le(d,e,l.relationBaseWhere),m=h!==d;if(c.aggregateIndexes&&!l.baseWhere&&!m){const R=to(c.aggregateIndexes,l.where);if(R){rt(e,R.index);const I=dt(R.index.by??[],R.key),$=at(e,R.index.name),B=K(y,f`SELECT ${Ge} AS value FROM ${f.identifier($)} WHERE ${je} = ${I}`).toArray();return B[0]===void 0?0:B[0].value??0}}const M=ee(h,pe);let _=f`SELECT COUNT(*) AS count FROM ${f.identifier(e)}`;return M&&(_=f`${_} WHERE ${M}`),K(y,_).one().count},async delete(e,t,r){A(e,"ctx.db.delete(table, id)");const c=X(t,e);if(!c){const R=Ie(e);R&&await ct(R,e,[t],r);return}const{docJson:l,row:p,tableName:d}=c,h=u.tables[d],m=r?.hard===!0,M=!m&&h?.softDeleteMode?h:void 0,_=M?.softDeleteMode?.field;if(_&&p[_]!==null&&p[_]!==void 0)return;if(oe(d,"before","delete")&&await re("before","delete",{id:t,op:"delete",previous:p,table:d}),r?.skipOnDelete!==!0&&await er({deletedId:t,deletedReference:R=>p[R],findHolders:async(R,I,$,B)=>(await nt(R).findMany(R,{...B,includeDeleted:m,where:{[I]:$}})).page,onCascade:(R,I)=>nt(R).delete(R,I,r),onRestrict:R=>{throw new de(R,"restrict")},onSetNull:(R,I,$)=>nt(R).patch(R,I,{[$]:null}),schema:u,tableName:d}),Te(d),Ae(d),M&&_){const R={[_]:Re()},I={...p,...te(d),...R,_id:t};pt(M,R,I,fe),Ve(y,d,rn(d),[ae(I),t,l]),Be(d,t,I,p),We(d,t,void 0),Fe(d,p,I),he(d,t,p,void 0);const $=V(d,p,I);ue?.invalidate(d,t,$),Se(d,t,"update",I),C({indexKeys:$,key:t,op:"update",row:I,table:d}),oe(d,"after","delete")&&await re("after","delete",{id:t,op:"delete",previous:p,table:d}),await me({id:t,op:"delete",table:d});return}Ve(y,d,Cr(d),[t,l]),Be(d,t,void 0),We(d,t,void 0),Fe(d,p,void 0),he(d,t,p,void 0);const x=V(d,p);ue?.invalidate(d,t,x),Se(d,t,"delete"),C({indexKeys:x,key:t,op:"delete",table:d}),oe(d,"after","delete")&&await re("after","delete",{id:t,op:"delete",previous:p,table:d}),await me({id:t,op:"delete",table:d})},async deleteAll(e,t){if(!u.tables[e])throw new v("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return E().deleteAll(e,t);const r=Math.max(1,t?.chunkSize??Tn),c=t?.hard===void 0?void 0:{hard:t.hard},l=H(e,"deleteAll");let p=0;for(;;){const h=(await O.findMany(e,{includeDeleted:t?.hard===!0,limit:r})).page.map(m=>String(m._id));if(h.length===0)break;for(const m of h)await(l===void 0?O.delete(e,m,c):ct(l,e,[m],c)),p+=1;if(h.length<r)break}return{deleted:p}},async deleteMany(e,t,r){A(e,"ctx.db.deleteMany(table, ids)"),Qe(t.length,r?.limit,"deleteMany");for(const c of t)await O.delete(e,c);return{deleted:t.length}},async deleteWhere(e,t,r){const c=H(e,"deleteWhere"),p=(await dn(c??O,e,t,r?.limit,"deleteWhere")).map(d=>String(d._id));if(c)return ct(c,e,p,void 0,{options:r});if(O.deleteMany===void 0)throw new v("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return O.deleteMany(e,p,r)},async findFirst(e,t={}){return(await O.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await O.findFirst(e,t);if(r===null)throw new To(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=H(e,"findMany");if(r)return _e(e,t),t.consistency==="primary"&&S(e,uo),r.findMany(e,t);const c=u.tables[e];if(!c)throw new v("INTERNAL",`unknown table: ${e}`);const l=!t.where&&!t.baseWhere;l?L(e,G):L(e);const{limit:p,orderKeys:d,statement:h}=await Gt(e,c,t,L),m=ye(y,h.text,...h.params).toArray();l&&s?.recordRead(m.length);const M=[];for(const x of m){const R=Ce(x);R&&(M.push(R),!l&&typeof R._id=="string"&&L(e,R._id))}const _=Qo(M,{endCursor:t.endCursor,limit:p,omitContinueCursor:t.omitContinueCursor,orderKeys:d});return t.with&&await Xo({fetcher:ot,groupedCounter:Pn,parents:_.page,...Zo(t),schema:u,tableName:e,with:t.with}),{..._,page:_n(_.page,t.select,t.with)}},async explain(e,t={}){const r=H(e,"explain");if(r)return r.explain(e,t);const c=u.tables[e];if(!c)throw new v("INTERNAL",`unknown table: ${e}`);const{statement:l}=await Gt(e,c,t,()=>{}),p=ye(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){A(e,"ctx.db.get(table, id)");const r=X(t,e);if(!r){const c=Ie(e);return c?(S(e,t,!0),c.get(e,t)):(D(e),S(e,t,!0),null)}return Ee(r,t),r.row},async lookupById(e,t){const r=X(e,t);if(!r){for(const c of Pt(t))D(c),S(c,e,!0);return null}return Ee(r,e),{row:r.row,tableName:r.tableName}},async groupBy(e,t){const r=H(e,"groupBy");if(r)return _e(e,t),r.groupBy(e,t);const c=u.tables[e];if(!c)throw new v("INTERNAL",`unknown table: ${e}`);L(e,G);const l=t.agg??{op:"count"};if(Oe(l.op),l.op!=="count"&&!l.field)throw new v("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);const p=be(c.softDeleteMode,void 0),d=N(N(t.baseWhere,t.where),p),h=await Le(d,e,t.relationBaseWhere),m=h!==d;if(c.aggregateIndexes&&!t.baseWhere&&!m){const $=eo(c.aggregateIndexes,l.op,l.field,t.by,t.where),B=$===void 0?0:Object.keys($.partial).length,Q=$?.index.by?.length??0;if($&&(B===0||B===Q)){rt(e,$.index);const J=at(e,$.index.name),z=Object.keys($.partial),we=[];if(z.length===($.index.by??[]).length&&z.length>0){const qe=dt($.index.by??[],$.partial),Pe=K(y,f`SELECT ${Ge} AS value, ${ft} AS count FROM ${f.identifier(J)} WHERE ${je} = ${qe}`).toArray();return Pe.length>0&&we.push({key:{...$.partial},value:lt(l.op,Pe[0])}),we}const Jn=K(y,f`SELECT ${je} AS key, ${Ge} AS value, ${ft} AS count FROM ${f.identifier(J)}`).toArray();for(const qe of Jn){const Pe=Xn(JSON.parse(qe.key));we.push({key:Pe,value:lt(l.op,qe)})}return we}}for(const $ of[...t.by,l.field]){if($===void 0)continue;const B=$===l.field?`groupBy(${e}, { agg: { op: "${l.op}", field: "${$}" } })`:`groupBy(${e}, { by: [..."${$}"] })`;un(c,$,B)}const M=ee(h,pe),_=t.by.map($=>f`${ge($)} AS ${f.identifier($)}`);if(l.op==="count")_.push(f`COUNT(*) AS value`);else{const{field:$}=l;if($===void 0)throw new v("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);_.push(f`${f.raw(Oe(l.op))}(${ge($)}) AS value`)}let x=f`SELECT ${f.join(_,f`, `)} FROM ${f.identifier(e)}`;M&&(x=f`${x} WHERE ${M}`),x=f`${x} GROUP BY ${f.join(t.by.map($=>ge($)),f`, `)}`;const R=K(y,x).toArray(),I=[];for(const $ of R){const B={};for(const J of t.by)B[J]=wo(c.shape[J],$[J]??null);const{value:Q}=$;I.push({key:B,value:Q==null?null:Number(Q)})}return I},async insert(e,t,r){const c=H(e,"insert");if(c)return Mt(c,e,t,r,!0);const l=u.tables[e];if(!l)throw new v("INTERNAL",`unknown table: ${e}`);const p=r?.allowExplicitId===!0,d=He(l,Et(l,t,fe),{supplied:t,table:e,trusted:p});let h;r?.clientId!==void 0?(Wr(r.clientId),h=r.clientId):r?.allowExplicitId&&typeof d._id=="string"?(Rt(d._id),h=d._id):h=At();const m=r?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:Re(),M={...d,...te(e),_creationTime:m,_id:h};return oe(e,"before","insert")&&await re("before","insert",{doc:{...M},id:h,op:"insert",table:e}),p||q(e,M),Te(e),Ae(e),vt(y,e,br(e),[h,m,ae(M)]),st(e,h,M),oe(e,"after","insert")&&await re("after","insert",{doc:M,id:h,op:"insert",table:e}),await me({doc:M,id:h,op:"insert",table:e}),h},async insertManyUnsafe(e,t,r){if(Qe(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const c=H(e,"insert");if(c){const _=[];Br(u.tables[e],t,r?.allowExplicitId,fe);for(const x of t)Y(x);for(const x of t){const R=await c.insert(e,x,{allowExplicitId:r?.allowExplicitId});C({key:R,op:"insert",row:{...x,_id:R},table:e}),_.push(R)}return _}const l=u.tables[e];if(!l)throw new v("INTERNAL",`unknown table: ${e}`);Te(e),Ae(e);const p=[];for(let _=0;_<t.length;_+=Ke)p.push(te(e));const d=r?.allowExplicitId===!0?void 0:Yo(l),h=t.map((_,x)=>{const R=Et(l,_,fe),I=d===void 0?R:He(d,R,{supplied:_,table:e}),$=r?.allowExplicitId===!0&&typeof I._id=="string"?I._id:void 0;$!==void 0&&Rt($);const B=$??At(),Q=r?.allowExplicitId===!0&&typeof I._creationTime=="number"?I._creationTime:Re(),J={...I,...p[Math.floor(x/Ke)],_creationTime:Q,_id:B};return{creationTime:Q,document:J,id:B}});for(const _ of h)Y(_.document);const m=async _=>{for(const{document:x,id:R}of _)st(e,R,x);for(const{document:x,id:R}of _)await le({doc:x,id:R,op:"insert",table:e})};let M=0;try{for(let _=0;_<h.length;_+=Ke){const x=h.slice(_,_+Ke),R=f.join(x.map($=>f`(${$.id}, ${$.creationTime}, ${ae($.document)})`),f`, `),I=Rn("sqlite",f`INSERT INTO ${f.identifier(e)} (id, _creationTime, ${f.identifier(ie)}) VALUES ${R}`);vt(y,e,I.sql,I.params),M=_+x.length}}catch(_){throw await Un(e,h.slice(0,M)),_}return await m(h),h.map(_=>_.id)},async insertMany(e,t,r){Qe(t.length,r?.limit,"insertMany");const c=r?.skipDuplicates===!0,l=[],p=H(e,"insert");if(p)for(const h of t)Y(h);const d=async h=>p?Mt(p,e,h,void 0,!1):O.insert(e,h);for(const h of t)try{l.push(await d(h))}catch(m){if(c&&m instanceof de&&m.kind==="unique")l.push(null);else throw m}return l},normalizeId(e,t){return fn(u,e,t)},async patch(e,t,r,c){A(e,"ctx.db.patch(table, id, values)");const l=X(t,e);if(!l){const $=Ie(e);if($){Y(r);try{await $.patch(e,t,r,c)}finally{ce("update",e,t)}return}throw new v("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:h}=l,m=u.tables[h];if(!m)throw new v("INTERNAL",`unknown table: ${h}`);if(L(h,t),wn("patch",r),xt(h,t,r,d)){o?.({fields:Object.keys(Ne(r)),id:t,table:h});return}const M=Ao(m,r,d),_={...d,...Ne(M),...te(h),_id:t};pt(m,M,_,fe);const x=new Set(Object.keys(M)),R=He(m,_,{only:x,patched:x,previous:()=>d,table:h,tolerateStoredNull:!0});Io(c,d,R),oe(h,"before","update")&&await re("before","update",{doc:{...R},id:t,op:"update",previous:d,table:h}),q(h,R,d),Te(h),Ae(h),Ve(y,h,rn(h),[ae(R),t,p]),Be(h,t,R,d),We(h,t,R),Fe(h,d,R),he(h,t,d,R);const I=V(h,d,R);ue?.invalidate(h,t,I),Se(h,t,"update",R),C({indexKeys:I,key:t,op:"update",row:R,table:h}),oe(h,"after","update")&&await re("after","update",{doc:R,id:t,op:"update",previous:d,table:h}),await me({doc:R,id:t,op:"update",table:h})},async patchIf(e,t,r){const c=H(e,"patchIf");if(c){if(c.patchIf===void 0)throw new v("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);Y(r.patch);let l;try{l=await c.patchIf(e,t,r)}catch(p){throw ce("update",e,t),p}return l.applied&&ce("update",e,t),l}if(!u.tables[e])throw new v("INTERNAL",`unknown table: ${e}`);for(let l=1;l<=hn;l+=1){const p=await Nn(e,t,r,l<hn,d=>O.patch(e,t,d,{verify:r.verify}));if(p!==void 0)return p}throw new de(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){A(e,"ctx.db.patchMany(table, patches)"),Qe(t.length,r?.limit,"patchMany");for(const c of t)await O.patch(e,c.id,c.patch);return{patched:t.length}},async patchWhere(e,t,r){const c=H(e,"patchWhere")??O,p=(await dn(c,e,t.where,r?.limit,"patchWhere")).map(d=>({id:String(d._id),patch:t.patch}));if(O.patchMany===void 0)throw new v("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await O.patchMany(e,p,r),{patched:p.length}},async related(e,t){return Ko(O,T,e,t)},relationEdges:T,deleteRereadTables:W,inTransaction:j,softDeleteFields:U,relationWrites:P,query(e){const t=H(e,"query");return t?(L(e,G),t.query(e)):kn(y,u,e,ne,r=>{r?F(r):L(e,G)},r=>{s?.recordRead(r)})},async rank(e,t,r){const c=H(e,"rank");if(ne(e,t,"rank"),c)return L(e,G),c.rank(e,t,r);const l=u.tables[e];if(!l)throw new v("INTERNAL",`unknown table: ${e}`);const p=l.rankIndexes?.find(z=>z.name===t);if(!p)throw new v("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(qt(e,l,p),r.restrictsCounts)throw new ut(e);L(e,G),it(e,p);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const h=Yt(e,p.name),m=p.sortBy.map((z,we)=>Xt(we)),M=m.map(z=>ke(z)).join(", "),_=K(y,f`SELECT ${f.identifier("__partition__")}, ${f.raw(M)} FROM ${f.identifier(h)} WHERE ${f.identifier("__id__")} = ${d}`).toArray(),[x]=_;if(x===void 0)return null;let R=x.__partition__;const I=N(r.baseWhere,r.where);ht(I,u,e,"rank");const $=Lo(p,I);if($){const z=Fo(p.partitionBy??[],$);if(z!==R)return null;R=z}const B=m.map(z=>x[z]),{before:Q,total:J}=gn(y,h,m,p.sortBy,R,B,d);return{position:Q+1,total:J}},async rankBefore(e,t,r){if(se(e))throw new v("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const c=u.tables[e];if(!c)throw new v("INTERNAL",`unknown table: ${e}`);const l=c.rankIndexes?.find(m=>m.name===t);if(!l)throw new v("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new ut(e);L(e,G),it(e,l);const p=Yt(e,l.name),d=l.sortBy.map((m,M)=>Xt(M)),h=l.sortBy.map((m,M)=>De(r.sortValues[M]??null));return gn(y,p,d,l.sortBy,r.partitionKey,h,r.rowId)},async rankPage(e,t,r={}){ht(N(r.baseWhere,r.where),u,e,"rankPage");const c=H(e,"rankPage");if(ne(e,t,"rank"),c)return L(e,G),c.rankPage(e,t,r);const{continueCursor:l,hasMore:p,rows:d}=Qt(Ot,e,t,r);return{continueCursor:l,isDone:!p,page:d.map(h=>h.doc)}},async rankPageRows(e,t,r={}){ht(N(r.baseWhere,r.where),u,e,"rankPage"),ne(e,t,"rank");const{directions:c,hasMore:l,rows:p}=Qt(Ot,e,t,r);return{directions:c,hasMore:l,rows:p}},async restore(e,t){A(e,"ctx.db.restore(table, id)");const r=X(t,e);if(!r){const d=Ie(e);if(d?.restore){try{await d.restore(e,t)}finally{ce("update",e,t)}return}throw new v("NOT_FOUND",`document not found: ${t}`)}const c=u.tables[r.tableName]?.softDeleteMode?.field;if(!c)throw new v("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const l=r.row[c]!==null&&r.row[c]!==void 0;await O.patch(e,t,{[c]:null});const p=l?X(t,e)?.row:void 0;p&&(he(r.tableName,t,p,void 0),he(r.tableName,t,void 0,p))},async replace(e,t,r,c){A(e,"ctx.db.replace(table, id, document)");const l=X(t,e);if(!l){const B=Ie(e);if(B){Y(r);try{await B.replace(e,t,r,c)}finally{ce("update",e,t)}return}throw new v("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:h}=l,m=u.tables[h];if(!m)throw new v("INTERNAL",`unknown table: ${h}`);wn("replace",r);const M=c?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:void 0,_=typeof d._creationTime=="number"?d._creationTime:void 0,x=M??_??Re(),R={...r,...te(h),_creationTime:x,_id:t};pt(m,r,R,fe);const I=c?.allowExplicitId===!0,$=He(m,R,{previous:()=>d,supplied:r,table:h,trusted:I});oe(h,"before","update")&&await re("before","update",{doc:{...$},id:t,op:"update",previous:d,table:h}),I||q(h,$,d),Te(h),Ae(h),Ve(y,h,xr(h),[x,ae($),t,p]),Be(h,t,$,d),We(h,t,$),Fe(h,d,$),he(h,t,d,$),ue?.invalidate(h,t,V(h,d,$)),Se(h,t,"update",$),C({indexKeys:V(h,d,$),key:t,op:"update",row:$,table:h}),oe(h,"after","update")&&await re("after","update",{doc:$,id:t,op:"update",previous:d,table:h}),await me({doc:$,id:t,op:"update",table:h})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,c=Object.entries(u.tables).filter(([h,m])=>t.has(h)||r!==void 0&&!r.includes(h)?!1:m.shardMode?.kind!=="global").map(([h])=>h);if(r!==void 0){for(const h of r)if(!u.tables[h])throw new v("INTERNAL",`wipeShard: unknown table: ${h}`)}const l={};let p=0;const{deleteAll:d}=O;if(d===void 0)throw new v("INTERNAL","wipeShard: this writer has no deleteAll");for(const h of c){const m=await d(h,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});l[h]=m.deleted,p+=m.deleted}return{deleted:p,tables:l}}},Vn={db:O,scheduler:It};return n.enforceRls===!0?or(O,u,(e,t)=>X(e,t)?.tableName,T):O};export{cs as CDC_LOG_TABLE,xs as IDEMPOTENCY_TABLE,Jr as NotUniqueError,Ts as advanceClientWatermark,as as applyCdcChanges,wn as assertNoExplicitUndefined,Rt as assertStorableRowId,Wr as assertValidClientId,os as backfillAggregateIndexes,rs as backfillRankIndexes,is as backfillSearchIndexes,ds as bumpCdcEpoch,ls as cdcCanVouchFor,us as cdcForkedError,fs as cdcSeqLeavingRows,hs as cdcTouchesTables,ws as cdcTrimmedError,ps as compactCdcDocs,pi as createShardCtxDb,gs as cursorBelowRetainedFloor,si as meterReadBytes,As as migrateClientWatermark,ys as minCdcReplayableSeq,$s as minCdcSeq,fn as normalizeIdStructurally,Es as readCdcChangeKeys,ms as readCdcChanges,Rs as readCdcCursor,vs as readCdcEpoch,Is as readClientWatermark,Cs as readIdempotent,Ls as runShardMigrations,Ws as selectShapeMembers,Bs as selectShapeRows,Ne as stripReservedPatchFields,Ss as trimCdcChanges,Ms as trimIdempotent,Ds 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{v}from"./accepts-null-D1zmJbyR.mjs";const k=(n,o,t)=>n.some(e=>e.unique===!0&&e.fields.length===2&&e.fields.includes(o)&&e.fields.includes(t)),f=(n,o)=>{const t=n.shardMode??{kind:"root"},e=o.shardMode??{kind:"root"};return t.kind!=="global"&&t.kind===e.kind&&t.field===e.field},p=(n,o)=>{const t=n?.shape[o];return t!==void 0&&v(t)},N=(n,o,t)=>Object.entries(n?.shape??{}).filter(([e,s])=>e!==o&&e!==t&&!e.startsWith("_")&&s.kind!=="optional"&&s._meta?.column?.serverDefault===void 0).map(([e])=>e),O="a many-to-many write is several row writes and only a mutation's transaction makes them atomic; run it in a mutation",q=(n,o,t)=>n!==void 0&&n.indexes.filter(e=>e.unique===!0).every(e=>k([e],o,t))&&!Object.values(n.shape).some(e=>e._meta?.column?.unique===!0),y=(n,o)=>{const t={};for(const[e,s]of Object.entries(n.tables))for(const[b,i]of Object.entries(s.relationMap??{})){const r=n.tables[i.table],c=t[e]??{};if(t[e]=c,i.through!==void 0){const{from:a,table:u,to:l}=i.through,d=n.tables[u],m=N(d,a,l);c[b]={colocated:r!==void 0&&d!==void 0&&f(s,r)&&f(s,d),kind:"many",pairIsOnlyUnique:q(d,a,l),refusalNow:()=>o?.()===!0?void 0:O,table:i.table,through:{from:a,table:u,to:l},...m.length===0?{}:{refusal:`"${u}" has required columns besides "${a}" and "${l}" (${m.join(", ")}); write its rows directly`}};continue}const h=i.kind==="one"?s:r;c[b]={field:i.field,kind:i.kind,nullable:p(h,i.field),references:i.references,table:i.table,colocated:r!==void 0&&f(s,r)}}return t};export{y as describeRelationWrites};
@@ -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};