@lunora/sql-store 1.0.0-alpha.8 → 1.0.0-alpha.80
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +6 -0
- package/dist/dialect.d.mts +136 -38
- package/dist/dialect.d.ts +136 -38
- package/dist/dialect.mjs +0 -1
- package/dist/index.d.mts +185 -107
- package/dist/index.d.ts +185 -107
- package/dist/index.mjs +1 -2
- package/dist/packem_shared/SEARCH_STATE_TABLE-DA3LgCT0.mjs +1 -0
- package/dist/packem_shared/backfillSqlSearchIndexes-BRlUTReN.mjs +1 -0
- package/dist/packem_shared/createSqlCtxDb-CRX3OS05.mjs +1 -0
- package/dist/packem_shared/ctx-db-search-Cl6zlJ11.mjs +1 -0
- package/dist/packem_shared/decodeBigint-B4wY6fcF.mjs +1 -0
- package/dist/packem_shared/decodeGlobalRow-BKIjk_Zk.mjs +1 -0
- package/package.json +3 -2
- package/dist/packem_shared/createSqlCtxDb-DYqDyPq8.mjs +0 -1754
- package/dist/packem_shared/decodeBigint-Dedu92k4.mjs +0 -69
package/dist/index.d.ts
CHANGED
|
@@ -1,121 +1,150 @@
|
|
|
1
|
-
import { ServerDefaultContextLike, DatabaseWriterLike,
|
|
2
|
-
import {
|
|
1
|
+
import { TableDefinitionLike, SchemaLike, ServerDefaultContextLike, DatabaseWriterLike, CrossShardReadArgs, QueryPage, SchedulerLike, ValidatorLike } from '@lunora/shard-engine';
|
|
2
|
+
import { SqlRunResult, SqlDialect } from "./dialect.js";
|
|
3
3
|
export type { SqlExec } from "./dialect.js";
|
|
4
4
|
import 'drizzle-orm';
|
|
5
5
|
/**
|
|
6
|
-
* Async SQL surface the D1 ORM needs: `all` for reads, `run` for writes.
|
|
7
|
-
* Satisfied by a `D1Session`/`D1Client` in production and a `node:sqlite`
|
|
8
|
-
* adapter in tests, so the query logic runs against a real SQLite engine.
|
|
9
|
-
*/
|
|
6
|
+
* Async SQL surface the D1 ORM needs: `all` for reads, `run` for writes.
|
|
7
|
+
* Satisfied by a `D1Session`/`D1Client` in production and a `node:sqlite`
|
|
8
|
+
* adapter in tests, so the query logic runs against a real SQLite engine.
|
|
9
|
+
*/
|
|
10
10
|
interface SqlCtxExec {
|
|
11
11
|
all: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<Record<string, unknown>[]>;
|
|
12
|
+
batch?: (statements: ReadonlyArray<{
|
|
13
|
+
params: ReadonlyArray<unknown>;
|
|
14
|
+
sql: string;
|
|
15
|
+
}>) => Promise<void>;
|
|
12
16
|
run: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<SqlRunResult | void>;
|
|
13
17
|
}
|
|
18
|
+
/**
|
|
19
|
+
* Decode a SELECTed row back into a document: `id` → `_id`, `_creationTime`
|
|
20
|
+
* preserved, and every column run through the shared {@link sqliteDecode} so the
|
|
21
|
+
* stored form is reversed back into its JS shape. Exported so the data-browser
|
|
22
|
+
* (`introspect.ts`) and admin export/import paths share the exact same decode.
|
|
23
|
+
*
|
|
24
|
+
* The decode is engine-agnostic: every backend stores SQLite-shaped values
|
|
25
|
+
* (boolean → 1/0, JSON → text, bigint → decimal string), and `sqliteDecode` is
|
|
26
|
+
* robust to a driver returning either the stored string OR a natively-parsed
|
|
27
|
+
* value (e.g. mysql2 returns JSON columns pre-parsed) — so the same decoder is
|
|
28
|
+
* correct on SQLite, Postgres and MySQL.
|
|
29
|
+
*/
|
|
30
|
+
declare const decodeGlobalRow: (definition: TableDefinitionLike, row: Record<string, unknown>) => Record<string, unknown>;
|
|
31
|
+
/**
|
|
32
|
+
* Provision the search companions, then index one bounded page of the rows that
|
|
33
|
+
* predate each index — unless it is declared `staged: true`, which leaves the
|
|
34
|
+
* whole backfill to {@link backfillSqlSearchIndexes}.
|
|
35
|
+
*
|
|
36
|
+
* Idempotent (`CREATE … IF NOT EXISTS` throughout, and the backfill resumes
|
|
37
|
+
* from recorded progress).
|
|
38
|
+
*/
|
|
39
|
+
declare const runSqlSearchMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
|
|
40
|
+
/**
|
|
41
|
+
* Run every declared search index — including the `staged: true` ones the
|
|
42
|
+
* migration pass skips — through to completion. The entry point a host calls
|
|
43
|
+
* out-of-band after deploying a search index over a table too large to index a
|
|
44
|
+
* page at a time.
|
|
45
|
+
*
|
|
46
|
+
* Idempotent and resumable: an index recorded as complete is skipped, and an
|
|
47
|
+
* interrupted run picks up from its cursor.
|
|
48
|
+
*/
|
|
49
|
+
declare const backfillSqlSearchIndexes: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
|
|
14
50
|
interface SqlCtxDbOptions {
|
|
15
51
|
/**
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
52
|
+
* Resolved request auth handed to `.serverDefault(fn)` column factories so
|
|
53
|
+
* server-trusted columns (owner/tenant ids) stamp from the verified caller,
|
|
54
|
+
* never the client. The generated worker passes the per-request identity;
|
|
55
|
+
* absent it, server-trusted columns stamp the anonymous slice (`userId: null`).
|
|
56
|
+
*/
|
|
21
57
|
auth?: ServerDefaultContextLike["auth"];
|
|
22
58
|
/**
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
59
|
+
* Opt into change-data-capture: when `true`, every committed write appends a
|
|
60
|
+
* post-image to the `__cdc_log` table (created lazily alongside the other
|
|
61
|
+
* companion tables). Backs CDC streaming export for `.global()` tables — the
|
|
62
|
+
* log is for export/CDC consumers, NOT point-in-time recovery: D1's PITR is
|
|
63
|
+
* the platform's own Time Travel (`wrangler d1 time-travel restore`), an
|
|
64
|
+
* atomic restore, not a changelog replay. Leave undefined for zero-cost
|
|
65
|
+
* legacy behaviour.
|
|
66
|
+
*/
|
|
31
67
|
cdc?: boolean;
|
|
32
68
|
clock?: () => number;
|
|
33
69
|
/**
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
70
|
+
* Cross-shard counter for **reverse cross-backend relations** — the `_count`
|
|
71
|
+
* mirror of the `crossShardReader` option below.
|
|
72
|
+
*/
|
|
37
73
|
crossShardCounter?: DatabaseWriterLike["count"];
|
|
38
74
|
/**
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
75
|
+
* Optional cross-shard reader for **reverse cross-backend relations**: a
|
|
76
|
+
* `.global()` (D1) parent loading a shard-local (`.shardBy()`/root) child.
|
|
77
|
+
* Such a child's rows are partitioned across every shard DO, so the local D1
|
|
78
|
+
* writer can't resolve it. When provided, the relation loader routes the
|
|
79
|
+
* child's read through this (the host wires it to the Query Coordinator's
|
|
80
|
+
* RLS-correct `fanOut`, with identity forwarded so each shard applies its own
|
|
81
|
+
* RLS). Absent it, loading such a relation throws a clear "not supported"
|
|
82
|
+
* error (legacy behaviour). The forward direction (shard-local parent →
|
|
83
|
+
* global child) and same-backend relations never touch this.
|
|
84
|
+
*
|
|
85
|
+
* Takes {@link CrossShardReadArgs}, not `QueryArgs`: the hop is JSON, so the
|
|
86
|
+
* RLS filters are handed over as data (see that type's docblock).
|
|
87
|
+
*/
|
|
88
|
+
crossShardReader?: (table: string, args: CrossShardReadArgs) => Promise<QueryPage>;
|
|
50
89
|
/**
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
90
|
+
* The SQL dialect that shapes every statement (identifier quoting, value
|
|
91
|
+
* encode/decode, column types, upserts, RETURNING vs affected-rows).
|
|
92
|
+
* `@lunora/d1` passes its `sqliteDialect`; the PlanetScale/Hyperdrive backend
|
|
93
|
+
* passes its Postgres/MySQL dialect. Required — the core is engine-blind.
|
|
94
|
+
*/
|
|
56
95
|
dialect: SqlDialect;
|
|
57
96
|
exec: SqlCtxExec;
|
|
58
97
|
idGenerator?: () => string;
|
|
59
98
|
/**
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
99
|
+
* Ceiling on the number of child join keys a relation-crossing `where`
|
|
100
|
+
* predicate may materialize before the semijoin pre-resolver fails closed
|
|
101
|
+
* (`relation predicate … exceeding the N-key limit`). D1 has no EXISTS
|
|
102
|
+
* push-down, so an overflow here can only fail closed — never truncate the
|
|
103
|
+
* `IN (...)` and silently mis-match. Defaults to the pre-resolver's shared
|
|
104
|
+
* key cap when omitted.
|
|
105
|
+
*/
|
|
67
106
|
maxRelationKeys?: number;
|
|
68
107
|
/**
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
108
|
+
* Scheduler exposed to global-table trigger handlers as `ctx.scheduler`.
|
|
109
|
+
* Absent it, `ctx.scheduler` is a stub that throws on use — pass one when
|
|
110
|
+
* triggers on `.global()` tables need to enqueue follow-up work.
|
|
111
|
+
*/
|
|
73
112
|
scheduler?: SchedulerLike;
|
|
74
113
|
schema: SchemaLike;
|
|
75
114
|
}
|
|
76
115
|
/**
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
|
|
88
|
-
|
|
116
|
+
* Auto-provision every `.global()` table from the schema: `CREATE TABLE IF NOT
|
|
117
|
+
* EXISTS` with the physical `id`/`_creationTime` columns plus a typed column per
|
|
118
|
+
* declared field, then its secondary and `.unique()` indexes. This is the D1
|
|
119
|
+
* twin of `@lunora/do`'s `runShardMigrations` (which self-creates shard-local
|
|
120
|
+
* tables) — it makes the schema the single source of truth for global tables
|
|
121
|
+
* too, so a fresh database serves them without a hand-applied migration. The
|
|
122
|
+
* column set and dialect match exactly what this module reads and writes
|
|
123
|
+
* (`columnRef`, `serializeColumnValue`, `decodeGlobalRow`).
|
|
124
|
+
*
|
|
125
|
+
* Idempotent (`CREATE TABLE/INDEX IF NOT EXISTS`); additive only — it never
|
|
126
|
+
* drops or retypes an existing column, so destructive schema changes still need
|
|
127
|
+
* an explicit migration.
|
|
128
|
+
*/
|
|
89
129
|
declare const runSqlGlobalTableMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
|
|
90
130
|
/**
|
|
91
|
-
* Materialize the `__agg_
|
|
92
|
-
* `aggregateIndex` on a global table. Global tables in Lunora ship their own
|
|
93
|
-
* DDL — counter tables are opt-in so production hosts can decide where they
|
|
94
|
-
* live. Tests and dev hosts can call this once after their schema migration to
|
|
95
|
-
* unlock O(1) counts.
|
|
96
|
-
*
|
|
97
|
-
* Idempotent (`CREATE TABLE IF NOT EXISTS`).
|
|
98
|
-
*/
|
|
131
|
+
* Materialize the `__agg_<index>` companion tables for every declared
|
|
132
|
+
* `aggregateIndex` on a global table. Global tables in Lunora ship their own
|
|
133
|
+
* DDL — counter tables are opt-in so production hosts can decide where they
|
|
134
|
+
* live. Tests and dev hosts can call this once after their schema migration to
|
|
135
|
+
* unlock O(1) counts.
|
|
136
|
+
*
|
|
137
|
+
* Idempotent (`CREATE TABLE IF NOT EXISTS`).
|
|
138
|
+
*/
|
|
99
139
|
declare const runSqlAggregateMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
|
|
100
140
|
/**
|
|
101
|
-
* Materialize the `__rank_
|
|
102
|
-
* `rankIndex` on a global table. Mirrors `runSqlAggregateMigrations` — same
|
|
103
|
-
* opt-in pattern so production hosts decide whether to spend the DDL.
|
|
104
|
-
*
|
|
105
|
-
* Idempotent (`CREATE TABLE IF NOT EXISTS` + `createIndexIfNotExists`).
|
|
106
|
-
*/
|
|
141
|
+
* Materialize the `__rank_<index>` companion tables for every declared
|
|
142
|
+
* `rankIndex` on a global table. Mirrors `runSqlAggregateMigrations` — same
|
|
143
|
+
* opt-in pattern so production hosts decide whether to spend the DDL.
|
|
144
|
+
*
|
|
145
|
+
* Idempotent (`CREATE TABLE IF NOT EXISTS` + `createIndexIfNotExists`).
|
|
146
|
+
*/
|
|
107
147
|
declare const runSqlRankMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
|
|
108
|
-
/**
|
|
109
|
-
* Materialize the `__fts_<index>` FTS5 shadow tables for every declared
|
|
110
|
-
* `.searchIndex()` on a global table. Mirrors `runSqlAggregateMigrations` — same
|
|
111
|
-
* opt-in pattern so production hosts decide whether to spend the DDL. Only runs
|
|
112
|
-
* on engines that ship FTS5 (D1 does; the `node:sqlite` test runner doesn't,
|
|
113
|
-
* where `.search()` transparently falls back to a scan). `__text__` holds the
|
|
114
|
-
* indexed field; `__id__` (UNINDEXED) joins back to the row.
|
|
115
|
-
*
|
|
116
|
-
* Idempotent (`CREATE VIRTUAL TABLE IF NOT EXISTS`).
|
|
117
|
-
*/
|
|
118
|
-
declare const runSqlSearchMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
|
|
119
148
|
/** One change-data-capture entry: a committed mutation, in monotonic `seq` order. Mirrors the DO twin. */
|
|
120
149
|
interface CdcChange {
|
|
121
150
|
/** Post-image document for insert/update; absent for delete (the `id` identifies the removed row). */
|
|
@@ -131,9 +160,9 @@ interface CdcChange {
|
|
|
131
160
|
/** Create the `__cdc_log` table. Idempotent; only run when CDC is enabled. */
|
|
132
161
|
declare const runSqlCdcMigration: (exec: SqlCtxExec, dialect: SqlDialect) => Promise<void>;
|
|
133
162
|
/**
|
|
134
|
-
* Read changelog entries newer than `sinceSeq` in commit order, up to `limit`
|
|
135
|
-
* (clamped to [1, 10000]); plus the cursor to resume from.
|
|
136
|
-
*/
|
|
163
|
+
* Read changelog entries newer than `sinceSeq` in commit order, up to `limit`
|
|
164
|
+
* (clamped to [1, 10000]); plus the cursor to resume from.
|
|
165
|
+
*/
|
|
137
166
|
declare const readSqlCdcChanges: (exec: SqlCtxExec, options: {
|
|
138
167
|
limit?: number;
|
|
139
168
|
sinceSeq?: number;
|
|
@@ -144,6 +173,10 @@ declare const readSqlCdcChanges: (exec: SqlCtxExec, options: {
|
|
|
144
173
|
/** Drop changelog entries at or below a checkpointed `throughSeq` (retention). */
|
|
145
174
|
declare const trimSqlCdcChanges: (exec: SqlCtxExec, throughSeq: number, dialect: SqlDialect) => Promise<void>;
|
|
146
175
|
declare const createSqlCtxDb: (options: SqlCtxDbOptions) => DatabaseWriterLike;
|
|
176
|
+
/** Reserved table holding one backfill-progress row per search companion. */
|
|
177
|
+
declare const SEARCH_STATE_TABLE = "__lunora_search_state";
|
|
178
|
+
/** Create the progress table. Idempotent; runs alongside the companion DDL. */
|
|
179
|
+
declare const migrateSearchState: (exec: SqlCtxExec, dialect: SqlDialect) => Promise<void>;
|
|
147
180
|
/** Map a JS value onto its SQLite storage form — SQLite has no boolean, so true/false → 1/0. */
|
|
148
181
|
declare const sqliteEncode: (value: unknown) => unknown;
|
|
149
182
|
/** Parse `raw` as JSON, returning `raw` unchanged when it is not valid JSON. */
|
|
@@ -151,24 +184,69 @@ declare const tryJsonParse: (raw: string) => unknown;
|
|
|
151
184
|
/** Decode a `bigint` column: a decimal string back into a `BigInt`, else verbatim. */
|
|
152
185
|
declare const decodeBigint: (raw: unknown) => unknown;
|
|
153
186
|
/**
|
|
154
|
-
* Resolve the *effective* storage kind of a column validator.
|
|
155
|
-
*
|
|
156
|
-
*
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
|
|
187
|
+
* Resolve the *effective* storage kind of a column validator: `v.optional(inner)`
|
|
188
|
+
* unwrapped to `inner`'s kind, since encoding keys off the runtime value's JS
|
|
189
|
+
* type and the validator's own `kind` of `"optional"` hides that.
|
|
190
|
+
*
|
|
191
|
+
* A thin alias over `shared/effective-kind`, which is where the rule lives so
|
|
192
|
+
* the DO row store applies the identical one — it reads the same validators and
|
|
193
|
+
* has the same failure mode, and two copies drifted the last time.
|
|
194
|
+
*/
|
|
161
195
|
declare const effectiveColumnKind: (validator: ValidatorLike) => string | undefined;
|
|
162
196
|
/**
|
|
163
|
-
* Inverse of {@link sqliteEncode}: map a SQLite storage value back onto its JS
|
|
164
|
-
* form, driven by the field's effective validator `kind`:
|
|
165
|
-
*
|
|
166
|
-
* - `boolean`: 1/0 → true/false (SQLite has no boolean type).
|
|
167
|
-
* - `bigint`: decimal string → `BigInt`.
|
|
168
|
-
* - `
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
*
|
|
172
|
-
|
|
197
|
+
* Inverse of {@link sqliteEncode}: map a SQLite storage value back onto its JS
|
|
198
|
+
* form, driven by the field's effective validator `kind`:
|
|
199
|
+
*
|
|
200
|
+
* - `boolean`: 1/0 → true/false (SQLite has no boolean type).
|
|
201
|
+
* - `bigint`: decimal string → `BigInt`.
|
|
202
|
+
* - `bytes`: normalizes any driver return shape to a genuine `ArrayBuffer` — a
|
|
203
|
+
* view (`Uint8Array`/`Buffer`/…) is sliced to its own byte window, a plain
|
|
204
|
+
* `ArrayBuffer` passes through. Required because `v.bytes()` validates
|
|
205
|
+
* `value instanceof ArrayBuffer` and different backends return different BLOB
|
|
206
|
+
* shapes (workerd D1 `ArrayBuffer`, node:sqlite `Uint8Array`, pg/mysql2 `Buffer`).
|
|
207
|
+
* - `object`/`array`/`record`: JSON string → parsed value.
|
|
208
|
+
* - `union`/`any`/`from`: parsed back only when the stored string is a JSON
|
|
209
|
+
* non-scalar (a scalar member round-trips through SQLite's native column type).
|
|
210
|
+
* `from` belongs to THIS group, not to `object`/`array`/`record`: an external
|
|
211
|
+
* Standard Schema can describe a string just as easily as an object, and
|
|
212
|
+
* {@link sqliteEncode} keys off the runtime JS type — so a `v.from(z.string())`
|
|
213
|
+
* column holding `"123"` is stored verbatim, and unconditional parsing would
|
|
214
|
+
* read it back as the NUMBER 123.
|
|
215
|
+
* CAVEAT: a union/any/from member is stored verbatim by {@link sqliteEncode}, so
|
|
216
|
+
* a legitimate *string* value that itself looks like JSON (`'{"a":1}'`, `'[1,2]'`)
|
|
217
|
+
* is ambiguous on read and decodes back to the parsed object/array, not the
|
|
218
|
+
* original string. This is inherent to sharing one TEXT column between a string
|
|
219
|
+
* and an object member; disambiguating would require a breaking storage-format
|
|
220
|
+
* change (tagging encoded non-scalars), so it is documented rather than fixed.
|
|
221
|
+
* - everything else (string/number/date/timestamp/id/literal): verbatim.
|
|
222
|
+
*/
|
|
173
223
|
declare const sqliteDecode: (raw: unknown, kind: string | undefined) => unknown;
|
|
174
|
-
export {
|
|
224
|
+
export { SEARCH_STATE_TABLE,
|
|
225
|
+
/**
|
|
226
|
+
* `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
|
|
227
|
+
* shared by Lunora's `.global()` table backends.
|
|
228
|
+
*
|
|
229
|
+
* One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
|
|
230
|
+
* `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
|
|
231
|
+
* any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
|
|
232
|
+
* unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
|
|
233
|
+
* whose `broadcast` hook drives live queries regardless of engine.
|
|
234
|
+
*
|
|
235
|
+
* This package is internal: consumers depend on `@lunora/d1` or
|
|
236
|
+
* `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
|
|
237
|
+
*/
|
|
238
|
+
type SqlCtxDbOptions,
|
|
239
|
+
/**
|
|
240
|
+
* `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
|
|
241
|
+
* shared by Lunora's `.global()` table backends.
|
|
242
|
+
*
|
|
243
|
+
* One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
|
|
244
|
+
* `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
|
|
245
|
+
* any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
|
|
246
|
+
* unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
|
|
247
|
+
* whose `broadcast` hook drives live queries regardless of engine.
|
|
248
|
+
*
|
|
249
|
+
* This package is internal: consumers depend on `@lunora/d1` or
|
|
250
|
+
* `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
|
|
251
|
+
*/
|
|
252
|
+
type SqlCtxExec, type SqlDialect, type SqlRunResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, migrateSearchState, readSqlCdcChanges, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, sqliteDecode, sqliteEncode, trimSqlCdcChanges, tryJsonParse };
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { decodeBigint, effectiveColumnKind, sqliteDecode, sqliteEncode, tryJsonParse } from './packem_shared/decodeBigint-Dedu92k4.mjs';
|
|
1
|
+
import{createSqlCtxDb as o,readSqlCdcChanges as a,runSqlAggregateMigrations as t,runSqlCdcMigration as i,runSqlGlobalTableMigrations as l,runSqlRankMigrations as n,trimSqlCdcChanges as S}from"./packem_shared/createSqlCtxDb-CRX3OS05.mjs";import{b as s,r as d}from"./packem_shared/ctx-db-search-Cl6zlJ11.mjs";import{SEARCH_STATE_TABLE as q,migrateSearchState as f}from"./packem_shared/SEARCH_STATE_TABLE-DA3LgCT0.mjs";import{decodeBigint as C,effectiveColumnKind as x,sqliteDecode as b,sqliteEncode as u,tryJsonParse as h}from"./packem_shared/decodeBigint-B4wY6fcF.mjs";import{decodeGlobalRow as M}from"./packem_shared/decodeGlobalRow-BKIjk_Zk.mjs";export{q as SEARCH_STATE_TABLE,s as backfillSqlSearchIndexes,o as createSqlCtxDb,C as decodeBigint,M as decodeGlobalRow,x as effectiveColumnKind,f as migrateSearchState,a as readSqlCdcChanges,t as runSqlAggregateMigrations,i as runSqlCdcMigration,l as runSqlGlobalTableMigrations,n as runSqlRankMigrations,d as runSqlSearchMigrations,b as sqliteDecode,u as sqliteEncode,S as trimSqlCdcChanges,h as tryJsonParse};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as i}from"drizzle-orm";import{queryRun as s,queryAll as E}from"./decodeGlobalRow-BKIjk_Zk.mjs";const f="__lunora_search_state",l=async(r,e)=>{const{integer:t,key:o}=e.companionTypes,n=async()=>{try{await s(r,e,i`ALTER TABLE ${i.identifier(f)} ADD COLUMN ${i.identifier("profile")} ${i.raw(o)}`)}catch{}};await s(r,e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(f)} (${i.identifier("companion")} ${i.raw(o)} PRIMARY KEY, ${i.identifier("cursor")} ${i.raw(o)}, ${i.identifier("done")} ${i.raw(t)} NOT NULL DEFAULT 0, ${i.identifier("profile")} ${i.raw(o)})`),await n()},p=r=>r===1||r===!0||r==="1",S=async(r,e,t)=>{const n=(await E(r,e,i`SELECT ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")} FROM ${i.identifier(f)} WHERE ${i.identifier("companion")} = ${t}`))[0];if(!n)return{cursor:void 0,done:!1,profile:void 0};const{cursor:a,profile:$}=n;return{cursor:typeof a=="string"?a:void 0,done:p(n.done),profile:typeof $=="string"?$:void 0}},A=async(r,e,t,o,n,a)=>{const $=o??null,d=i`UPDATE ${i.identifier(f)} SET ${i.identifier("cursor")} = ${$}, ${i.identifier("done")} = ${n?1:0}, ${i.identifier("profile")} = ${a} WHERE ${i.identifier("companion")} = ${t}`;if((await E(r,e,i`SELECT ${i.identifier("companion")} FROM ${i.identifier(f)} WHERE ${i.identifier("companion")} = ${t}`)).length>0){await s(r,e,d);return}try{await s(r,e,i`INSERT INTO ${i.identifier(f)} (${i.identifier("companion")}, ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")}) VALUES (${t}, ${$}, ${n?1:0}, ${a})`)}catch(c){if(!e.isUniqueViolation(c))throw c;await s(r,e,d)}};export{f as SEARCH_STATE_TABLE,l as migrateSearchState,S as readSearchBackfillState,A as writeSearchBackfillState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as S,c as s,a as i,r as l}from"./ctx-db-search-Cl6zlJ11.mjs";import"./SEARCH_STATE_TABLE-DA3LgCT0.mjs";import"./decodeGlobalRow-BKIjk_Zk.mjs";export{S as backfillSqlSearchIndexes,s as createSearchSync,i as runSqlSearch,l as runSqlSearchMigrations};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as v}from"@lunora/errors";import{c as Tt,r as gt,R as vt,j as St,D as bt,M as It,a as At,B as Ct,y as Lt,_ as kt}from"./ctx-db-search-Cl6zlJ11.mjs";import{b as xn}from"./ctx-db-search-Cl6zlJ11.mjs";import{literalInList as Nt,throwingScheduler as Mt,aggregateTableName as z,rankTableName as ee,hasTrigger as Dt,runRowValidators as Ne,assertFlatPredicate as Je,mergeWhere as q,sortColumnName as X,resolveRankPartition as Qe,encodePartitionKey as Se,decodeCursor as Ze,RANK_TIEBREAK as he,CountRlsUnsupportedError as et,normalizeIdStructurally as qt,assertValidClientId as xt,aggregateSqlFunction as fe,softDeleteScope as we,compileWhereSql as _e,normalizeOrderKeys as Bt,buildSeekWhere as Ft,resolveRelationPredicates as tt,resolveWith as nt,relationHooks as ot,applySelect as it,encodeCursor as Ot,NotFoundError as Wt,applyOnDelete as Ut,ConflictError as $e,normalizeCountArgument as jt,selectIndexForCount as Pt,encodeAggregateKey as Y,selectIndexForAggregate as Kt,readAggregateValue as Me,runTriggers as Ht,matchesRankStaticWhere as rt,selectIndexForGroupBy as Vt,fanOutScalarCounts as Gt,matchesStaticWhere as De,foldAggregateTally as Yt,coerceAggregateNumber as qe,NotUniqueError as zt}from"@lunora/shard-engine";import{sql as e}from"drizzle-orm";import{migrateSearchState as Xt}from"./SEARCH_STATE_TABLE-DA3LgCT0.mjs";import{queryAll as A,queryRun as k,createIndexIfNotExists as Be,decodeRow as te,serializeColumnValue as H,columnRefSql as x,decodeRows as Jt,forEachRowPaged as st,queryBatch as at}from"./decodeGlobalRow-BKIjk_Zk.mjs";import{decodeGlobalRow as Fn}from"./decodeGlobalRow-BKIjk_Zk.mjs";import{effectiveColumnKind as be}from"./decodeBigint-B4wY6fcF.mjs";const Qt=(c,_)=>{if(c.size<_)return;const f=c.keys().next().value;f!==void 0&&c.delete(f)},ct=50,Zt=(c,_={})=>{const f=_.maxBatch??ct,r=Number.isInteger(f)&&f>0?f:ct,p=new Map;let l=!1;const a=async(m,b)=>{const S=[...b.keys()];for(let L=0;L<S.length;L+=r){const M=S.slice(L,L+r);try{const W=await c(m,M);for(const V of M){const U=W.get(V);for(const Ae of b.get(V)??[])Ae.resolve(U)}}catch(W){for(const V of M)for(const U of b.get(V)??[])U.reject(W)}}},R=()=>{l=!1;const m=[...p.entries()];p.clear();for(const[b,S]of m)a(b,S).catch(()=>{})};return{async load(m,b){return new Promise((S,L)=>{let M=p.get(m);M||(M=new Map,p.set(m,M));const W=M.get(b);W?W.push({reject:L,resolve:S}):M.set(b,[{reject:L,resolve:S}]),l||(l=!0,queueMicrotask(R))})}}},en=new Set(["_id","id"]),Fe=(c,_,f)=>c==="postgres"?e`${_} IS NOT DISTINCT FROM ${f}`:c==="mysql"?e`${_} <=> ${f}`:e`${_} IS ${f}`,tn=c=>{const _=c.map(f=>e`${x(f.field)} ${e.raw(f.direction==="desc"?"DESC":"ASC")}`);return c.some(f=>en.has(f.field))||_.push(e`${x("id")} ASC`),e.join(_,e`, `)},lt=50,Oe=c=>{const _=[];for(const[f,r]of Object.entries(c.shape)){const p=r._meta?.column;p&&_.push([f,p])}return _},nn=(c,_,f)=>{const r={..._};for(const[p,l]of Oe(c)){if(l.serverDefault){r[p]=l.serverDefault({auth:f});continue}r[p]===void 0&&(l.defaultFn?r[p]=l.defaultFn():"defaultValue"in l&&(r[p]=l.defaultValue))}return r},ut=(c,_,f,r)=>{for(const[p,l]of Oe(c)){if(l.serverDefault){p in _&&(f[p]=l.serverDefault({auth:r}));continue}l.onUpdateFn&&!(p in _)&&(f[p]=l.onUpdateFn())}},on=128,rn=()=>{const c=new Map;return{delete:_=>{c.delete(_)},get:_=>{const f=c.get(_);if(f!==void 0)return c.delete(_),c.set(_,f),f},set:(_,f)=>{c.has(_)?c.delete(_):Qt(c,on),c.set(_,f)}}},sn=async(c,_,f,r,p)=>{const l=p.get(r);if(l!==void 0)return l;const a=Object.entries(f.tables).filter(([,m])=>m.shardMode===void 0||m.shardMode.kind==="global").map(([m])=>m),R=await Promise.all(a.map(async m=>({found:(await A(c,_,e`SELECT 1 FROM ${e.identifier(m)} WHERE ${e.identifier("id")} = ${r} LIMIT 1`)).length>0,tableName:m})));for(const m of R)if(m.found)return p.set(r,m.tableName),m.tableName},ne=c=>c==null?null:Number(c),an=(c,_)=>_.map(f=>{const r={};for(const p of c)r[p]=f[p]??null;return{key:r,value:ne(f.value)}}),cn=(c,_,f)=>[...c.partitionBy??[],...c.sortBy.map(p=>p.field),...c.where?Object.keys(c.where):[]].every(p=>_[p]===f[p]),dt=c=>c.length===1?c[0]:e`(${e.join(c,e` AND `)})`,Z=c=>e.join(c.map(_=>e`${e.identifier(_)}`),e`, `),oe=c=>e.join(c.map(_=>e`${_}`),e`, `),ln=(c,_,f,r,p)=>{const l=[];for(let a=0;a<f.length+1;a+=1){const R=f.slice(0,a).map(S=>Fe(c,e`${e.identifier(S)}`,r[S])),m=f[a],b=_.sortBy[a];a<f.length&&m!==void 0&&b!==void 0?R.push(e`${e.identifier(m)} ${e.raw(b.direction==="desc"?">":"<")} ${r[m]}`):R.push(e`${e.identifier(he)} < ${p}`),l.push(dt(R))}return l.length>0?e.join(l,e` OR `):void 0},un=(c,_,f)=>{if(f.length!==_.length)return;const r=[];for(const[p,l]of _.entries()){const a=[];for(let R=0;R<p;R+=1){const m=_[R];m!==void 0&&a.push(Fe(c,e`${e.identifier(m.column)}`,f[R]))}a.push(e`${e.identifier(l.column)} ${e.raw(l.direction==="desc"?"<":">")} ${f[p]}`),r.push(dt(a))}return e`(${e.join(r,e` OR `)})`},dn=(c,_)=>{if(c.sortBy.length===0)throw new v("INTERNAL",`rankIndex "${c.name}" requires at least one "sortBy" column for stable pagination`);const f=[{column:"__partition__",direction:"asc"}];for(const[r,p]of c.sortBy.entries())f.push({column:_[r]??X(r),direction:p.direction});return f.push({column:he,direction:"asc"}),f},fn=async(c,_,f,r,p)=>{const a=[];for(let S=0;S<p.length;S+=50)a.push(p.slice(S,S+50));const R=await Promise.all(a.map(async S=>A(c,_,e`SELECT * FROM ${e.identifier(r)} WHERE ${e.identifier("id")} IN (${oe(S)})`))),m=new Map;for(const S of R)for(const L of S)m.set(L.id,L);const b=[];for(const S of p){const L=te(f,m.get(S));L&&b.push(L)}return b},wn=c=>{const _=JSON.stringify(c),f=new TextEncoder().encode(_);let r="";for(const p of f)r+=String.fromCodePoint(p);return btoa(r)},_n=(c,_)=>_.columnType(be(c)),$n=(c,_,f)=>{const r=[];for(const[a,R]of Object.entries(_.shape)){if(!R._meta?.column)continue;const m=R._meta.column.notNull&&R.kind!=="optional"?" NOT NULL":"";r.push(e`${e.identifier(a)} ${e.raw(`${_n(R,f)}${m}`)}`)}const p=f.frameworkColumns().map(a=>e`${e.identifier(a.name)} ${e.raw(a.type)}`),l=p.length+r.length;if(f.maxTableColumns!==void 0&&l>f.maxTableColumns)throw new v("VALIDATION_ERROR",`@lunora/sql-store: global table "${c}" needs ${String(l)} columns, over this engine's ${String(f.maxTableColumns)}-column limit — split the table, or move the extra fields into one object field`);return e.join([...p,...r],e`, `)},hn=async(c,_,f,r)=>{const p=l=>{const a=x(l),R=f.shape[l],m=R&&r.indexKeyPrefix?r.indexKeyPrefix(be(R)):void 0;return m===void 0?a:e`${a}(${e.raw(String(m))})`};for(const l of f.indexes){const a=e.join(l.fields.map(R=>p(R)),e`, `);await Be(c,r,{columns:a,name:`${_}_${l.name}`,table:_,unique:l.unique??!1})}for(const[l,a]of Oe(f))a.unique&&await Be(c,r,{columns:p(l),name:`${_}_unique_${l}`,table:_,unique:!0})},yn=async(c,_,f)=>{for(const[r,p]of Object.entries(_.tables)){if(p.shardMode?.kind!=="global")continue;const l=$n(r,p,f);await k(c,f,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (${l})`),await hn(c,r,p,f)}},En=async(c,_,f)=>{const{integer:r,key:p,real:l}=f.companionTypes;for(const[a,R]of Object.entries(_.tables)){const m=R.aggregateIndexes;if(!(!m||m.length===0))for(const b of m){const S=z(a,b.name);await k(c,f,e`CREATE TABLE IF NOT EXISTS ${e.identifier(S)} (${e.identifier("__key__")} ${e.raw(p)} PRIMARY KEY, ${e.identifier("__value__")} ${e.raw(l)}, ${e.identifier("__count__")} ${e.raw(r)} NOT NULL DEFAULT 0)`),f.name==="sqlite"&&((await A(c,f,e`PRAGMA table_info(${e.identifier(S)})`)).some(M=>M.name==="__count__")||await k(c,f,e`ALTER TABLE ${e.identifier(S)} ADD COLUMN ${e.identifier("__count__")} ${e.raw(r)} NOT NULL DEFAULT 0`))}}},xe=(c,_,f,r)=>{const p=c.name==="mysql"&&r?e`${e.identifier(_)}(191)`:e`${e.identifier(_)}`;return e`${p} ${e.raw(f)}`},pn=(c,_,f)=>{const r=[xe(c,"__partition__","ASC",!0)];for(const[p,l]of _.sortBy.entries()){const a=f.shape[l.field],R=a!==void 0&&c.indexKeyPrefix?.(be(a))!==void 0;r.push(xe(c,X(p),l.direction==="desc"?"DESC":"ASC",R))}return r.push(xe(c,"__id__","ASC",!0)),r},mn=(c,_,f)=>_.sortBy.map((r,p)=>{const l=f.shape[r.field],a=c.columnType(l?be(l):void 0);return e`${e.identifier(X(p))} ${e.raw(a)}`}),Rn=async(c,_,f)=>{const{key:r}=f.companionTypes;for(const[p,l]of Object.entries(_.tables)){const a=l.rankIndexes;if(!(!a||a.length===0))for(const R of a){const m=ee(p,R.name),b=mn(f,R,l),S=b.length>0?e`, ${e.join(b,e`, `)}`:e``;await k(c,f,e`CREATE TABLE IF NOT EXISTS ${e.identifier(m)} (${e.identifier("__id__")} ${e.raw(r)} PRIMARY KEY, ${e.identifier("__partition__")} ${e.raw(r)} NOT NULL${S})`);const L=pn(f,R,l),M=`${p}__rank_${R.name}__btree`;await Be(c,f,{columns:e.join(L,e`, `),name:M,table:m,unique:!1})}}},Ie="__cdc_log",Tn=async(c,_)=>{const{autoincrementPrimaryKey:f,key:r,real:p,text:l}=_.companionTypes;await k(c,_,e`CREATE TABLE IF NOT EXISTS ${e.identifier(Ie)} (${e.identifier("seq")} ${e.raw(f)}, ${e.identifier("ts")} ${e.raw(p)} NOT NULL, ${e.identifier("table")} ${e.raw(r)} NOT NULL, ${e.identifier("id")} ${e.raw(r)} NOT NULL, ${e.identifier("op")} ${e.raw(r)} NOT NULL, ${e.identifier("doc")} ${e.raw(l)})`)},gn=async(c,_,f,r,p,l,a)=>{await k(c,a,e`INSERT INTO ${e.identifier(Ie)} (${e.identifier("ts")}, ${e.identifier("table")}, ${e.identifier("id")}, ${e.identifier("op")}, ${e.identifier("doc")}) VALUES (${_}, ${f}, ${r}, ${p}, ${l===void 0?null:JSON.stringify(l)})`)},kn=async(c,_,f)=>{const r=_.sinceSeq??0,p=Math.max(1,Math.min(_.limit??1e3,1e4)),a=(await A(c,f,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(Ie)} WHERE seq > ${r} ORDER BY seq ASC LIMIT ${e.raw(String(p))}`)).map(R=>{const{doc:m}=R,b={id:String(R.id),op:String(R.op),seq:Number(R.seq),table:String(R.table),ts:Number(R.ts)};return typeof m=="string"?{...b,doc:JSON.parse(m)}:b});return{changes:a,cursor:a.at(-1)?.seq??r}},Nn=async(c,_,f)=>{await k(c,f,e`DELETE FROM ${e.identifier(Ie)} WHERE ${e.identifier("seq")} <= ${_}`)},Mn=c=>{const{crossShardCounter:_,crossShardReader:f,exec:r,maxRelationKeys:p,schema:l}=c,{dialect:a}=c,{isUniqueViolation:R}=a,m={fieldRef:x,serialize:H,...a.name==="mysql"?{containsExpr:(t,n)=>e`LOCATE(${n}, ${t}) > 0`}:{},...a.name==="postgres"?{containsExpr:(t,n)=>e`strpos(${t}, ${n}) > 0`}:{},...a.name==="sqlite"?{}:{inList:Nt}},b=(t,n)=>Fe(a.name,t,n),S=t=>{const n=Z(t.columns),o=oe(t.values),i=u=>a.name==="mysql"?e`VALUES(${e.identifier(u)})`:e`excluded.${e.identifier(u)}`,s=u=>a.name==="postgres"?e`${e.identifier(t.table)}.${e.identifier(u)}`:e`${e.identifier(u)}`,w=e.join(Object.entries(t.set(i,s)).map(([u,y])=>e`${e.identifier(u)} = ${y}`),e`, `),h=a.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${w}`:e`ON CONFLICT(${e.identifier(t.conflictKey)}) DO UPDATE SET ${w}`;return e`INSERT INTO ${e.identifier(t.table)} (${n}) VALUES (${o}) ${h}`},L=c.clock??(()=>Date.now()),M=c.idGenerator??(()=>crypto.randomUUID()),W=c.cdc??!1,V=c.auth??{identity:null,userId:null},U=async(t,n,o,i)=>{W&&await gn(r,L(),t,n,o,i,a)},Ae=c.scheduler??Mt,Ce=rn();let ye=0,Le;const j=async()=>(Le??=(async()=>{await yn(r,l,a),await En(r,l,a),await Rn(r,l,a),await Xt(r,a),await gt(r,l,a),W&&await Tn(r,a)})().catch(t=>{throw Le=void 0,t}),Le),ie=async(t,n)=>{await j();const o=await sn(r,a,l,t,Ce);if(!(n!==void 0&&o!==n))return o},re=new Map,We=async(t,n)=>{const o=z(t,n);return(await A(r,a,a.tableExists(o))).length>0},Ee=async(t,n)=>{const o=`${t}::${n.name}`,i=re.get(o);if(i!==void 0)return i;if(!await We(t,n.name))return re.set(o,!1),!1;const w=l.tables[t];if(!w)return re.set(o,!1),!1;const h=n.by??[],u=new Map;await st(r,a,w,t,$=>{if(n.where&&!De($,n.where))return;const E=Y(h,$);Yt(u,E,n,$)});const y=z(t,n.name);await k(r,a,e`DELETE FROM ${e.identifier(y)}`);const d=[];for(const[$,E]of u)d.push(e`INSERT INTO ${e.identifier(y)} (${e.identifier("__key__")}, ${e.identifier("__value__")}, ${e.identifier("__count__")}) VALUES (${$}, ${E.value}, ${E.count})`);return await at(r,a,d),re.set(o,!0),!0},ft=async(t,n,o)=>{const i=fe(n.op),s=n.field??"",w=[];for(const y of n.by??[]){const d=H(o[y]??null);w.push(d===null?e`${x(y)} IS NULL`:e`${x(y)} = ${d}`)}for(const[y,d]of Object.entries(n.where??{})){const $=d!==null&&typeof d=="object"&&!Array.isArray(d)?d.eq:d,E=H($);w.push(E===null?e`${x(y)} IS NULL`:e`${x(y)} = ${E}`)}const h=e`SELECT ${e.raw(i)}(${x(s)}) AS value FROM ${e.identifier(t)}`,u=await A(r,a,w.length>0?e`${h} WHERE ${e.join(w,e` AND `)}`:h);return ne(u[0]?.value)},wt=async(t,n)=>{await k(r,a,e`DELETE FROM ${e.identifier(t)} WHERE ${e.identifier("__key__")} = ${n} AND ${e.identifier("__count__")} <= 0`)},_t=async(t,n,o,i)=>{const s=z(t,n.name),{op:w}=n,h=n.field??"",u=o&&(!n.where||De(o,n.where))?o:void 0,y=i&&(!n.where||De(i,n.where))?i:void 0;if(!(!u&&!y)){if(w==="count"||w==="sum"||w==="avg"){const d=new Set;for(const[$,E]of[[u,-1],[y,1]]){if(!$)continue;const g=w==="count"?1:qe($[h]);if(g===void 0)continue;const T=Y(n.by??[],$);d.add(T),await k(r,a,S({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(C,I)=>({__count__:e`${I("__count__")} + ${C("__count__")}`,__value__:w==="count"?e`${I("__value__")} + ${C("__value__")}`:e`COALESCE(${I("__value__")}, 0) + ${C("__value__")}`}),table:s,values:[T,E*g,E]}))}for(const $ of d)await wt(s,$);return}if(u){const d=Y(n.by??[],u),$=qe(u[h]),g=(await A(r,a,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(s)} WHERE ${e.identifier("__key__")} = ${d}`))[0],T=ne(g?.value),C=(g?.count??0)-1;if(C<=0)await k(r,a,e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__key__")} = ${d}`);else if(g&&$!==void 0&&T!==null&&$===T){const I=await ft(t,n,u);await k(r,a,e`UPDATE ${e.identifier(s)} SET ${e.identifier("__value__")} = ${I}, ${e.identifier("__count__")} = ${C} WHERE ${e.identifier("__key__")} = ${d}`)}else await k(r,a,e`UPDATE ${e.identifier(s)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${d}`)}if(y){const d=Y(n.by??[],y),$=qe(y[h]);if($===void 0)await k(r,a,S({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(E,g)=>({__count__:e`${g("__count__")} + 1`}),table:s,values:[d,null,1]}));else{const E=w==="min"?"MIN":"MAX";await k(r,a,S({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(g,T)=>({__count__:e`${T("__count__")} + 1`,__value__:e`${e.raw(E)}(COALESCE(${T("__value__")}, ${g("__value__")}), ${g("__value__")})`}),table:s,values:[d,$,1]}))}}}},pe=async t=>{const n=l.tables[t]?.aggregateIndexes;if(!(!n||n.length===0))for(const o of n)await Ee(t,o)},se=async(t,n,o)=>{const i=l.tables[t]?.aggregateIndexes;if(!(!i||i.length===0))for(const s of i){const w=`${t}::${s.name}`;(re.get(w)??await We(t,s.name))&&await _t(t,s,n,o)}},ae=new Map,Ue=async(t,n)=>{const o=ee(t,n);return(await A(r,a,a.tableExists(o))).length>0},ke=async(t,n)=>{const o=`${t}::rank::${n.name}`,i=ae.get(o);if(i!==void 0)return i;if(!await Ue(t,n.name))return ae.set(o,!1),!1;const w=l.tables[t];if(!w)return ae.set(o,!1),!1;const h=ee(t,n.name);await k(r,a,e`DELETE FROM ${e.identifier(h)}`);const u=n.sortBy.map((E,g)=>X(g)),y=Z(["__id__","__partition__",...u]),d=[];await st(r,a,w,t,E=>{if(n.where&&!rt(E,n.where))return;const g=Se(n.partitionBy??[],E),T=n.sortBy.map(C=>H(E[C.field]??null));d.push([E._id,g,...T])});const $=d.map(E=>e`INSERT INTO ${e.identifier(h)} (${y}) VALUES (${oe(E)})`);return await at(r,a,$),ae.set(o,!0),!0},me=async t=>{const n=l.tables[t]?.rankIndexes;if(!(!n||n.length===0))for(const o of n)await ke(t,o)},J=async(t,n,o,i)=>{const s=l.tables[t],w=s?.rankIndexes;if(!w||w.length===0)return;const h=s?.softDeleteMode?.field,u=h===void 0||i===void 0?void 0:i[h],y=u!=null;for(const d of w){if(o!==void 0&&i!==void 0&&cn(d,o,i))continue;const $=`${t}::rank::${d.name}`;if(!(ae.get($)??await Ue(t,d.name)))continue;const T=ee(t,d.name);if(o&&await k(r,a,e`DELETE FROM ${e.identifier(T)} WHERE ${e.identifier("__id__")} = ${n}`),i&&!y){if(d.where&&!rt(i,d.where))continue;const C=d.sortBy.map((B,G)=>X(G)),I=Z(["__id__","__partition__",...C]),F=Se(d.partitionBy??[],i),N=d.sortBy.map(B=>H(i[B.field]??null));await k(r,a,e`INSERT INTO ${e.identifier(T)} (${I}) VALUES (${oe([n,F,...N])})`)}}},ce=Tt({dialect:a,exec:r,schema:l}),je=new Set;for(const[t,n]of Object.entries(l.tables))for(const o of Object.values(n.triggerMap??{}))je.add(`${t} ${o.timing} ${o.op}`);const P=(t,n,o)=>je.has(`${t} ${n} ${o}`);let Pe;const K=async(t,n,o)=>{if(ye+=1,ye>lt)throw ye-=1,new $e(`trigger recursion exceeded ${String(lt)} levels on "${o.table}" — check for a self-triggering write`,"trigger");try{await Ht({ctx:Pe,event:o,op:n,schema:l,tableName:o.table,timing:t})}finally{ye-=1}},$t=async(t,n)=>{try{await k(r,a,n)}catch(o){throw R(o)?new $e(`unique constraint violation on "${t}"`,"unique"):o}},Re=async(t,n)=>(await A(r,a,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} = ${n}`))[0],Te=async(t,n,o,i)=>{if(i===void 0)return;const s=e.join(Object.keys(i).map(u=>b(e`${e.identifier(u)}`,i[u])),e` AND `),w=n==="UPDATE"?e`UPDATE ${e.identifier(t)} SET ${o} WHERE ${s}`:e`DELETE FROM ${e.identifier(t)} WHERE ${s}`,h=()=>{throw new $e(`optimistic concurrency conflict on "${t}" — the row changed during this mutation; refetch and retry`,"occ")};try{if(a.supportsReturning)(await A(r,a,e`${w} RETURNING ${e.identifier("id")}`)).length===0&&h();else{const u=await k(r,a,w);(a.affectedRows?a.affectedRows(u??{rowsAffected:0}):0)===0&&h()}}catch(u){throw R(u)?new $e(`unique constraint violation on "${t}"`,"unique"):u}},ht=(t,n,o,i)=>{const s=Object.keys(t.shape);return{columns:["id","_creationTime",...s],values:[n,o,...s.map(w=>H(i[w]??null))]}},yt=async(t,n,o,i)=>{const s=Vt(n,o.op,o.field,i.by,i.where);if(!s||!await Ee(t,s.index))return;const h=z(t,s.index.name),u=Object.keys(s.partial);if(u.length===(s.index.by??[]).length&&u.length>0){const d=Y(s.index.by??[],s.partial),$=await A(r,a,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(h)} WHERE ${e.identifier("__key__")} = ${d}`);if($.length===0)return[];const E=$[0];return[{key:{...s.partial},value:Me(o.op,{count:E.count,value:ne(E.value)})}]}return u.length>0?void 0:(await A(r,a,e`SELECT ${e.identifier("__key__")} AS key, ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(h)}`)).map(d=>{const $=d;return{key:JSON.parse($.key),value:Me(o.op,{count:$.count,value:ne($.value)})}})},Ke=t=>{const n=l.tables[t]?.shardMode?.kind;return n==="shardBy"||n==="root"},He=t=>{throw new v("INTERNAL",`cross-backend relation: a global table cannot load the shard-local relation '${t}' (it spans every shard) — wire a cross-shard reader to support it`)},Et=(t,n)=>{if(n?.relationMask!==void 0&&n.with!==void 0&&Object.keys(n.with).length>0)throw new v("MASK_UNSUPPORTED",`masking cannot follow a nested \`with\` across the cross-shard relation hop to "${t}" — the nested rows are hydrated on the serving shard, where the mask policy does not exist. Read the nested relation at its own (masked) call site instead.`);const o={};if(n?.relationBaseWhere)for(const i of Object.keys(l.tables)){const s=n.relationBaseWhere(i);s!==void 0&&(o[i]=s)}return{orderBy:n?.orderBy,relationPolicies:o,where:q(n?.baseWhere,n?.where),with:n?.with}},Ve=(t,n)=>Ke(t)?f?f(t,Et(t,n)):He(t):O.findMany(t,n),ge=(t,n,o)=>tt(t,{fetcher:Ve,maxRelationKeys:p,relationBaseWhere:o,schema:l,tableName:n}),pt=Zt(async(t,n)=>{const o=await A(r,a,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} IN (${oe(n)})`),i=new Map;for(const s of o){const{id:w}=s;typeof w=="string"&&i.set(w,s)}return i}),O={async aggregate(t,n){const o=l.tables[t];if(!o)throw new v("INTERNAL",`unknown table: ${t}`);if(await j(),fe(n.op),n.op==="count")return O.count(t,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new v("INTERNAL",`aggregate(${t}, { op: "${n.op}" }): "field" is required for non-count reducers`);const i=we(o.softDeleteMode,void 0),s=q(q(n.baseWhere,n.where),i),w=await ge(s,t,n.relationBaseWhere),h=w!==s;if(o.aggregateIndexes&&!n.baseWhere&&!h&&!i){const g=Kt(o.aggregateIndexes,n.op,n.field,n.where);if(g&&await Ee(t,g.index)){const C=Y(g.index.by??[],g.key),I=z(t,g.index.name),N=(await A(r,a,e`SELECT ${e.identifier("__value__")} AS value, ${e.identifier("__count__")} AS count FROM ${e.identifier(I)} WHERE ${e.identifier("__key__")} = ${C}`))[0];return Me(n.op,N===void 0?void 0:{count:N.count,value:ne(N.value)})}}const u=_e(w,m),y=e.raw(fe(n.op)),d=e`SELECT ${y}(${x(n.field)}) AS value FROM ${e.identifier(t)}`,E=(await A(r,a,u?e`${d} WHERE ${u}`:d))[0]?.value;return E==null?null:Number(E)},async count(t,n){const o=l.tables[t];if(!o)throw new v("INTERNAL",`unknown table: ${t}`);await j();const i=jt(n);if(i.restrictsCounts)throw new et(t);const s=we(o.softDeleteMode,void 0),w=q(q(i.baseWhere,i.where),s),h=await ge(w,t,i.relationBaseWhere),u=h!==w;if(o.aggregateIndexes&&!i.baseWhere&&!u&&!s){const E=Pt(o.aggregateIndexes,i.where);if(E&&await Ee(t,E.index)){const T=Y(E.index.by??[],E.key),C=z(t,E.index.name),I=await A(r,a,e`SELECT ${e.identifier("__value__")} AS value FROM ${e.identifier(C)} WHERE ${e.identifier("__key__")} = ${T}`);return Number(I[0]?.value??0)}}const y=_e(h,m),d=e`SELECT COUNT(*) AS count FROM ${e.identifier(t)}`,$=await A(r,a,y?e`${d} WHERE ${y}`:d);return Number($[0]?.count??0)},async delete(t,n,o){const i=await ie(t,n);if(!i)return;const s=l.tables[i];if(!s)return;const w=await Re(i,t),h=te(s,w),u=o?.hard===!0,y=!u&&s.softDeleteMode?s.softDeleteMode.field:void 0;if(!(y&&(!h||h[y]!==null&&h[y]!==void 0))){if(P(i,"before","delete")&&await K("before","delete",{id:t,op:"delete",previous:h??void 0,table:i}),await Ut({deletedId:t,deletedReference:d=>h?.[d],findHolders:async(d,$,E)=>{if(l.tables[d]?.shardMode?.kind==="shardBy")throw new v("INTERNAL",`cross-backend cascade from global '${i}' into shardBy '${d}' is not supported — would require Query Coordinator fan-out across shards`);return(await O.findMany(d,{includeDeleted:u,where:{[$]:E}})).page},onCascade:(d,$)=>O.delete($,void 0,o),onRestrict:d=>{throw new $e(d,"restrict")},onSetNull:(d,$,E)=>O.patch($,{[E]:null}),schema:l,tableName:i}),await pe(i),await me(i),y&&h){const d={...h,[y]:L()},$=e.join(Object.keys(s.shape).map(E=>e`${e.identifier(E)} = ${H(d[E]??null)}`),e`, `);await Te(i,"UPDATE",$,w),await se(i,h,d),await J(i,t,h,void 0),await ce(i,t,d,h),await U(i,t,"update",d),P(i,"after","delete")&&await K("after","delete",{id:t,op:"delete",previous:h,table:i});return}await Te(i,"DELETE",void 0,w),Ce.delete(t),await se(i,h??void 0,void 0),await J(i,t,h??void 0,void 0),await ce(i,t,void 0),await U(i,t,"delete"),P(i,"after","delete")&&await K("after","delete",{id:t,op:"delete",previous:h??void 0,table:i})}},async findFirst(t,n={}){return(await O.findMany(t,{...n,limit:1})).page[0]??null},async findFirstOrThrow(t,n={}){const o=await O.findFirst(t,n);if(o===null)throw new Wt(`findFirstOrThrow: no "${t}" document matched`);return o},async findMany(t,n={}){const o=l.tables[t];if(!o)throw new v("INTERNAL",`unknown table: ${t}`);await j();const i=Bt(n.orderBy),s=n.cursor?Ft(i,Ze(n.cursor)):void 0,w=Ve,h=async(N,B,G,ve)=>{if(Ke(N))return _?Gt(_,N,B,G,ve):He(N);const le=l.tables[N];if(!le)throw new v("INTERNAL",`unknown table: ${N}`);const Q=we(le.softDeleteMode,void 0),D={[B]:{in:G}},ue=q(q(D,ve),Q),mt=await ge(ue,N,void 0),Ge=_e(mt,m),Ye=x(B);let de=e`SELECT ${Ye} AS __fk__, COUNT(*) AS count FROM ${e.identifier(N)}`;Ge&&(de=e`${de} WHERE ${Ge}`),de=e`${de} GROUP BY ${Ye}`;const Rt=await A(r,a,de),ze=new Map;for(const Xe of Rt)ze.set(Xe.__fk__,Number(Xe.count??0));return ze};let u=q(n.baseWhere,n.where);u=q(u,we(o.softDeleteMode,n.includeDeleted)),u=await tt(u,{fetcher:w,maxRelationKeys:p,relationBaseWhere:n.relationBaseWhere,schema:l,tableName:t}),s&&(u=u?{AND:[u,s]}:s);const y=_e(u,m),d=tn(i);let $=e`SELECT * FROM ${e.identifier(t)}`;y&&($=e`${$} WHERE ${y}`),$=e`${$} ORDER BY ${d}`;const E=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;E!==void 0&&($=e`${$} LIMIT ${e.raw(String(E+1))}`);const g=await A(r,a,$),T=Jt(o,g);if(E===void 0)return n.with&&await nt({fetcher:w,groupedCounter:h,parents:T,...ot(n),schema:l,tableName:t,with:n.with}),{continueCursor:null,isDone:!0,page:it(T,n.select,n.with)};const C=T.length>E,I=C?T.slice(0,E):T,F=I.at(-1);return n.with&&await nt({fetcher:w,groupedCounter:h,parents:I,...ot(n),schema:l,tableName:t,with:n.with}),{continueCursor:C&&F?Ot(F,i):null,isDone:!C,page:it(I,n.select,n.with)}},async get(t,n){const o=await ie(t,n);if(!o)return null;const i=l.tables[o];return i?te(i,await pt.load(o,t)):null},async groupBy(t,n){const o=l.tables[t];if(!o)throw new v("INTERNAL",`unknown table: ${t}`);await j();const i=n.agg??{op:"count"};if(fe(i.op),i.op!=="count"&&!i.field)throw new v("INTERNAL",`groupBy(${t}, { agg: { op: "${i.op}" } }): "field" is required for non-count reducers`);const s=we(o.softDeleteMode,void 0),w=q(q(n.baseWhere,n.where),s),h=await ge(w,t,n.relationBaseWhere),u=h!==w;if(o.aggregateIndexes&&!n.baseWhere&&!u&&!s){const T=await yt(t,o.aggregateIndexes,i,n);if(T!==void 0)return T}const y=_e(h,m),d=n.by.map(T=>e`${x(T)} AS ${e.identifier(T)}`);if(i.op==="count")d.push(e`COUNT(*) AS value`);else{if(!i.field)throw new v("INTERNAL",`groupBy(${t}, { agg: { op: "${i.op}" } }): "field" is required for non-count reducers`);d.push(e`${e.raw(fe(i.op))}(${x(i.field)}) AS value`)}const $=e.join(n.by.map(T=>x(T)),e`, `);let E=e`SELECT ${e.join(d,e`, `)} FROM ${e.identifier(t)}`;y&&(E=e`${E} WHERE ${y}`),E=e`${E} GROUP BY ${$}`;const g=await A(r,a,E);return an(n.by,g)},async insert(t,n,o){const i=l.tables[t];if(!i)throw new v("INTERNAL",`unknown table: ${t}`);await j();const s=nn(i,n,V);Ne(i,s);let w,h=!0;o?.clientId!==void 0?(xt(o.clientId),w=o.clientId):o?.allowExplicitId&&typeof s._id=="string"?w=s._id:(w=M(),h=!1);const u=o?.allowExplicitId&&typeof s._creationTime=="number"?s._creationTime:L(),y={...s,_creationTime:u,_id:w};P(t,"before","insert")&&await K("before","insert",{doc:{...y},id:w,op:"insert",table:t}),await pe(t),await me(t);const{columns:d,values:$}=ht(i,w,u,s);return await $t(t,e`INSERT INTO ${e.identifier(t)} (${Z(d)}) VALUES (${oe($)})`),h&&Ce.set(w,t),await se(t,void 0,y),await J(t,w,void 0,y),await ce(t,w,y),await U(t,w,"insert",y),P(t,"after","insert")&&await K("after","insert",{doc:y,id:w,op:"insert",table:t}),w},normalizeId(t,n){return qt(l,t,n)},async patch(t,n,o){const i=await ie(t,o);if(!i)throw new v("INTERNAL",`document not found: ${t}`);const s=l.tables[i];if(!s)throw new v("INTERNAL",`document not found: ${t}`);const w=await Re(i,t),h=te(s,w);if(!h)throw new v("INTERNAL",`document not found: ${t}`);const u={...h,...n,_id:t};ut(s,n,u,V),Ne(s,u,!0),P(i,"before","update")&&await K("before","update",{doc:{...u},id:t,op:"update",previous:h,table:i}),await pe(i),await me(i);const y=Object.keys(s.shape),d=e.join(y.map($=>e`${e.identifier($)} = ${H(u[$]??null)}`),e`, `);await Te(i,"UPDATE",d,w),await se(i,h,u),await J(i,t,h,u),await ce(i,t,u,h),await U(i,t,"update",u),P(i,"after","update")&&await K("after","update",{doc:u,id:t,op:"update",previous:h,table:i})},async restore(t,n){const o=await ie(t,n);if(!o)throw new v("INTERNAL",`document not found: ${t}`);const i=l.tables[o],s=i?.softDeleteMode?.field;if(!i||!s)throw new v("INTERNAL",`ctx.db.restore: table "${o}" is not a .softDelete() table`);const w=await Re(o,t),h=w?.[s]!==null&&w?.[s]!==void 0;if(await O.patch(t,{[s]:null},n),h){const u=te(i,w);u!==null&&await J(o,t,void 0,{...u,[s]:null})}},query(t){const n=l.tables[t];if(!n)throw new v("INTERNAL",`unknown table: ${t}`);const o="the legacy query()/withIndex() reader is not available on the D1 (global) backend; use findMany",i=[],s=u=>i.every(y=>y(u)),w=async(u,y)=>{await j();const d=i.length>0,$=await At(r,a,n,t,u,Ct(d?void 0:y));if(!d)return y===void 0&&Lt($),$;const E=$.filter(g=>s(g));return y===void 0?E:E.slice(0,y)},h=u=>{const y={async*[Symbol.asyncIterator](){if(!u)throw new v("INTERNAL",o);yield*await w(u,void 0)},async collect(){if(!u)throw new v("INTERNAL",o);return w(u,void 0)},async collectWithScores(){throw new v("INTERNAL",`collectWithScores() is not supported on \`.global()\` tables (table "${t}") — relevance scores are not yet surfaced on this backend; use .collect() instead`)},filter(d){return i.push(d),y},async first(){if(!u)throw new v("INTERNAL",o);return(await w(u,1))[0]??null},order(){return y},async paginate(d){if(!u)throw new v("INTERNAL",o);const $=bt(d);return It(await w(u,kt($)),$)},async take(d){if(!u)throw new v("INTERNAL",o);return w(u,d)},async unique(){if(!u)throw new v("INTERNAL",o);const d=await w(u,2);if(d.length>1)throw new zt(`unique() on table "${t}" matched ${String(d.length)} documents; expected at most one`);return d[0]??null},withGeoIndex(){throw new v("INTERNAL",`geo indexes are not supported on \`.global()\` tables (table "${t}") — geospatial queries run only on sharded tables`)},withIndex(){throw new v("INTERNAL",o)},withSearchIndex(d,$){const E=(n.searchIndexes??[]).find(T=>T.name===d);if(!E)throw new v("INTERNAL",`unknown search index "${d}" on table "${t}"`);const g={definition:E,field:E.field,filters:[],hasQuery:!1,indexName:d,query:""};if($(vt(g,t,St(E.language))),!g.hasQuery)throw new v("INTERNAL",`search index "${d}" on table "${t}" requires a .search(field, query) call`);return h(g)}};return y};return h(void 0)},async rank(t,n,o){const i=l.tables[t];if(!i)throw new v("INTERNAL",`unknown table: ${t}`);const s=i.rankIndexes?.find(B=>B.name===n);if(!s)throw new v("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(o.restrictsCounts)throw new et(t);if(await j(),!await ke(t,s))return null;const h=typeof o.row=="string"?o.row:o.row._id;if(!h)return null;const u=ee(t,s.name),y=s.sortBy.map((B,G)=>X(G)),d=Z(["__partition__",...y]),E=(await A(r,a,e`SELECT ${d} FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${h}`))[0];if(!E)return null;const g=E.__partition__,T=q(o.baseWhere,o.where);Je(T,l,t,"rank");const C=Qe(s,T);if(C&&Se(s.partitionBy??[],C)!==g)return null;const I=ln(a.name,s,y,E,h),F=await A(r,a,e`SELECT COUNT(*) AS c FROM ${e.identifier(u)} WHERE ${e.identifier("__partition__")} = ${g}${I?e` AND (${I})`:e``}`),N=await A(r,a,e`SELECT COUNT(*) AS c FROM ${e.identifier(u)} WHERE ${e.identifier("__partition__")} = ${g}`);return{position:Number(F[0]?.c??0)+1,total:Number(N[0]?.c??0)}},async rankPage(t,n,o={}){Je(q(o.baseWhere,o.where),l,t,"rankPage");const i=l.tables[t];if(!i)throw new v("INTERNAL",`unknown table: ${t}`);const s=i.rankIndexes?.find(D=>D.name===n);if(!s)throw new v("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(await j(),!await ke(t,s))return{continueCursor:null,isDone:!0,page:[]};const h=ee(t,s.name),u=s.sortBy.map((D,ue)=>X(ue)),y=Math.max(1,Math.min(1e3,Math.floor(o.take??100))),d=q(o.baseWhere,o.where),$=Qe(s,d),E=dn(s,u),g=e.join(E.map(D=>e`${e.identifier(D.column)} ${e.raw(D.direction==="desc"?"DESC":"ASC")}`),e`, `),T=[];if($&&T.push(e`${e.identifier("__partition__")} = ${Se(s.partitionBy??[],$)}`),o.cursor){const D=un(a.name,E,Ze(o.cursor));D!==void 0&&T.push(D)}const C=Z([he,"__partition__",...u]);let I=e`SELECT ${C} FROM ${e.identifier(h)}`;T.length>0&&(I=e`${I} WHERE ${e.join(T,e` AND `)}`),I=e`${I} ORDER BY ${g} LIMIT ${e.raw(String(y+1))}`;const F=await A(r,a,I),N=F.length>y,B=N?F.slice(0,y):F,G=B.map(D=>D[he]),ve=await fn(r,a,i,t,G);let le=null;const Q=B.at(-1);if(N&&Q!==void 0){const D=[Q.__partition__,...u.map(ue=>Q[ue]),Q[he]];le=wn(D)}return{continueCursor:le,isDone:!N,page:ve}},async replace(t,n,o,i){const s=await ie(t,o);if(!s)throw new v("INTERNAL",`document not found: ${t}`);const w=l.tables[s];if(!w)throw new v("INTERNAL",`document not found: ${t}`);const h=await Re(s,t);if(h===void 0)throw new v("INTERNAL",`document not found: ${t}`);const y=Dt(l,s,"update")||(w.aggregateIndexes??[]).length>0||(w.rankIndexes??[]).length>0?te(w,h)??void 0:void 0,d=i?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:L(),$={...n,_creationTime:d,_id:t};ut(w,n,$,V),Ne(w,$),P(s,"before","update")&&await K("before","update",{doc:{...$},id:t,op:"update",previous:y,table:s}),await pe(s),await me(s);const E=Object.keys(w.shape),g=e.join([e`${e.identifier("_creationTime")} = ${d}`,...E.map(T=>e`${e.identifier(T)} = ${H($[T]??null)}`)],e`, `);await Te(s,"UPDATE",g,h),await se(s,y,$),await J(s,t,y,$),await ce(s,t,$,y),await U(s,t,"update",$),P(s,"after","update")&&await K("after","update",{doc:$,id:t,op:"update",previous:y,table:s})}};return Pe={db:O,scheduler:Ae},O};export{xn as backfillSqlSearchIndexes,Mn as createSqlCtxDb,Fn as decodeGlobalRow,kn as readSqlCdcChanges,En as runSqlAggregateMigrations,Tn as runSqlCdcMigration,yn as runSqlGlobalTableMigrations,Rn as runSqlRankMigrations,gt as runSqlSearchMigrations,Nn as trimSqlCdcChanges};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{migrateSearchState as Z,readSearchBackfillState as P,writeSearchBackfillState as v}from"./SEARCH_STATE_TABLE-DA3LgCT0.mjs";import{LunoraError as S}from"@lunora/errors";import{unionAll as ee}from"@lunora/shard-engine";import{queryRun as h,decodeRows as z,queryAll as C,queryBatch as ne,createIndexIfNotExists as U,columnRefSql as M,serializeColumnValue as te,forEachRowPaged as ie}from"./decodeGlobalRow-BKIjk_Zk.mjs";const oe=["de","en","es","fr","it","nl","none","pt"],re=e=>oe.includes(e),se="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",ae="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",ce="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",ue="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",fe="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",de="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",le="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",me=/[\u0300-\u036F]/gu,W=e=>e.normalize("NFD").replaceAll(me,"").normalize("NFC").toLowerCase(),g=e=>new Set(W(e).split(" ")),$e={de:g(ae),en:g(se),es:g(ce),fr:g(ue),it:g(fe),nl:g(de),none:new Set,pt:g(le)},he=2,we=256,j=new Map,y=e=>{const n=e!==void 0&&re(e)?e:"none",i=j.get(n);if(i)return i;const o=$e[n],r=a=>{const c=(W(a).match(/[\p{L}\p{N}]+/gu)??[]).filter(u=>u.length<=we);return o.size===0?c:c.filter(u=>!o.has(u))},s={document:r,profile:`${n}-v${String(he)}`,query:a=>{const c=r(a);return c.filter((u,f)=>c.lastIndexOf(u)===f)}};return j.set(n,s),s},Se=(e,n)=>e.profile!==n?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},pe=(e,n)=>{if(!n.includes("."))return e[n];let i=e;for(const o of n.split(".")){if(i===null||typeof i!="object"||Array.isArray(i))return;i=i[o]}return i},I=(e,n)=>`${e}__fts_${n}`,Ee="__text__",l="__id__",T="__token__",D="__n__",ge=1e3,Q=(e,n)=>n.document(e),L=(e,n)=>pe(e,n),_e=e=>typeof e=="string"?e:e==null?"":typeof e=="number"||typeof e=="bigint"||typeof e=="boolean"?String(e):JSON.stringify(e)??"",ye=(e,n,i)=>e!==void 0&&n!==void 0&&L(e,i.field)===L(n,i.field),O=(e,n)=>Q(_e(L(e,n.field)),y(n.language)).slice(0,ge).join(" "),Te=(e,n)=>{const i=new Map;for(const o of Q(e,n))i.set(o,(i.get(o)??0)+1);return i},Ne=e=>{const n=new TextEncoder().encode(e);let i="";for(const o of n)i+=String.fromCodePoint(o);return btoa(i)},ve=e=>{const n=atob(e),i=Uint8Array.from(n,o=>o.codePointAt(0)??0);return new TextDecoder().decode(i)},Ie=()=>new S("BAD_REQUEST","invalid cursor"),B=16,F=8,p=1024,R=(e,n)=>n.query(e),Re=(e,n)=>{if(!n)return{exact:!0,lower:e,upper:e};const i=[...e].at(-1)??"",o=(i.codePointAt(0)??0)+1;if(o>=55296&&o<=57343||o>1114111)return{exact:!0,lower:e,upper:e};const r=e.slice(0,e.length-i.length);return{exact:!1,lower:e,upper:r+String.fromCodePoint(o)}},He=(e,n,i)=>{const o={eq:(r,s)=>{if(!e.definition.filterFields?.includes(r))throw new S("INTERNAL",`field "${r}" is not a filter field of search index "${e.indexName}" on table "${n}"`);if(e.filters.length>=F)throw new S("BAD_REQUEST",`search index "${e.indexName}" on table "${n}": at most ${String(F)} .eq() filters are supported per search query`);return e.filters.push({field:r,value:s}),o},search:(r,s)=>{const a=e;if(r!==a.definition.field)throw new S("INTERNAL",`search index "${a.indexName}" on table "${n}" indexes "${a.definition.field}", not "${r}"`);const c=R(s,i).length;if(c>B)throw new S("BAD_REQUEST",`search index "${a.indexName}" on table "${n}": at most ${String(B)} search terms are supported (got ${String(c)})`);return a.field=r,a.query=s,a.hasQuery=!0,o}};return o},Pe=e=>{if(e.length>p)throw new S("BAD_REQUEST",`more than ${String(p)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},ze=e=>Math.min(e.offset+e.numItems+1,p),Ae=e=>Ne(`search:${String(e)}`),be=e=>{let n;try{n=ve(e)}catch{return}if(!n.startsWith("search:"))return;const i=Number(n.slice(7));return Number.isInteger(i)&&i>=0?i:void 0},We=e=>{if(typeof e.endCursor=="string")throw new S("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const n=Math.max(0,Math.floor(e.numItems)),i=e.cursor?be(e.cursor):0;if(i===void 0)throw Ie();if(i+n>p)throw new S("BAD_REQUEST",`search pagination reaches past the ${String(p)}-document limit (offset ${String(i)} + ${String(n)} requested) — narrow the query or the filters instead`);return{numItems:n,offset:i}},Qe=(e,n)=>{const i=n.offset+n.numItems,o=n.numItems>0&&e.length>i;return{continueCursor:o?Ae(i):null,isDone:!o,page:e.slice(n.offset,i)}},Ge=e=>{if(e===void 0)return p+1;if(!Number.isFinite(e))return p;const n=Math.max(0,Math.floor(e));if(n>p)throw new S("BAD_REQUEST",`search returns at most ${String(p)} documents (asked for ${String(n)}) — narrow the query or paginate instead`);return n},A=async(e,n,i,o)=>{await h(e,n,t`DELETE FROM ${t.identifier(i)} WHERE ${t.identifier(l)} = ${o}`)},b=(e,n)=>e.name==="mysql"?t`${t.identifier(n)}(191)`:e.textPatternOperatorClass===void 0?t`${t.identifier(n)}`:t`${t.identifier(n)} ${t.raw(e.textPatternOperatorClass)}`,k=50,De=(e,n)=>n?t`${t.identifier(T)} LIKE ${`${e}%`}`:t`${t.identifier(T)} = ${e}`,G=(e,n)=>{const i=n.filters.map(o=>t`m.${M(o.field)} = ${te(o.value)}`);return e.softDeleteMode&&i.push(t`m.${M(e.softDeleteMode.field)} IS NULL`),i},V=async(e,n,i,o,r,s,a)=>{const c=G(i,r);let u=t`SELECT m.* FROM (${a}) s JOIN ${t.identifier(o)} m ON m.${t.identifier("id")} = s.${t.identifier(l)}`;return c.length>0&&(u=t`${u} WHERE ${t.join(c,t` AND `)}`),u=t`${u} ORDER BY s.${t.identifier("__score__")} DESC, m.${t.identifier("_creationTime")} DESC, m.${t.identifier("id")} ASC LIMIT ${t.raw(String(s))}`,z(i,await C(e,n,u))},Le=async(e,n,i,o,r,s)=>{const a=R(r.query,y(r.definition.language));if(a.length===0)return[];const c=I(o,r.indexName),u=a.length-1,f=a.map((d,_)=>De(d,_===u)),m=t.join(f,t` OR `),$=f.map(d=>t`SUM(CASE WHEN ${d} THEN ${t.identifier(D)} ELSE 0 END)`),E=t.join($.map(d=>t`${d} > 0`),t` AND `),w=t`SELECT ${t.identifier(l)}, ${t.join($,t` + `)} AS ${t.identifier("__score__")} FROM ${t.identifier(c)} WHERE ${m} GROUP BY ${t.identifier(l)} HAVING ${E}`;return V(e,n,i,o,r,s,w)},Ce=async(e,n,i,o,r,s)=>{const a=R(r.query,y(r.definition.language));if(a.length===0)return[];const c=I(o,r.indexName),u=`${c}__vocab`,f=a.length-1,m=a.map((w,d)=>{const _=Re(w,d===f),K=_.exact?t`${t.identifier("term")} = ${_.lower}`:t`${t.identifier("term")} >= ${_.lower} AND ${t.identifier("term")} < ${_.upper}`;return t`SELECT ${t.identifier("doc")}, ${t.raw(String(d))} AS ${t.identifier("__term__")}, COUNT(*) AS ${t.identifier("__n__")} FROM ${t.identifier(u)} WHERE ${K} GROUP BY ${t.identifier("doc")}`}),$=a.map((w,d)=>t`SUM(CASE WHEN u.${t.identifier("__term__")} = ${t.raw(String(d))} THEN u.${t.identifier("__n__")} ELSE 0 END)`),E=t`SELECT f.${t.identifier(l)} AS ${t.identifier(l)}, ${t.join($,t` + `)} AS ${t.identifier("__score__")} FROM (${ee(m)}) u JOIN ${t.identifier(c)} f ON f.rowid = u.${t.identifier("doc")} GROUP BY f.${t.identifier(l)} HAVING ${t.join($.map(w=>t`${w} > 0`),t` AND `)}`;return V(e,n,i,o,r,s,E)},Oe=async(e,n,i,o,r,s)=>{const a=n.nativeTextSearch,c=R(r.query,y(r.definition.language));if(!a||c.length===0)return[];const u=I(o,r.indexName),f=[a.matches(u,c),...G(i,r)],m=t`SELECT m.* FROM ${t.identifier(u)} JOIN ${t.identifier(o)} m ON m.${t.identifier("id")} = ${t.identifier(u)}.${t.identifier(l)} WHERE ${t.join(f,t` AND `)} ORDER BY ${a.rank(u,c)} DESC, m.${t.identifier("_creationTime")} DESC, m.${t.identifier("id")} ASC LIMIT ${t.raw(String(s))}`;return z(i,await C(e,n,m))},qe={ensureCompanion:async(e,n,i)=>{const{integer:o,key:r}=n.companionTypes;await h(e,n,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier(T)} ${t.raw(r)} NOT NULL, ${t.identifier(l)} ${t.raw(r)} NOT NULL, ${t.identifier(D)} ${t.raw(o)} NOT NULL)`),await U(e,n,{columns:t`${b(n,T)}, ${b(n,l)}`,name:`${i}__btree`,table:i,unique:!1}),await U(e,n,{columns:b(n,l),name:`${i}__by_id`,table:i,unique:!1})},indexDocument:async(e,n,i,o,r,s)=>{await A(e,n,i,o);const a=[...Te(O(r,s),y(s.language))],c=t.join([T,l,D].map(f=>t.identifier(f)),t`, `),u=[];for(let f=0;f<a.length;f+=k){const m=t.join(a.slice(f,f+k).map(([$,E])=>t`(${$}, ${o}, ${E})`),t`, `);u.push(t`INSERT INTO ${t.identifier(i)} (${c}) VALUES ${m}`)}await ne(e,n,u)},name:"inverted",runSearch:Le},xe={ensureCompanion:async(e,n,i)=>{await h(e,n,t`CREATE VIRTUAL TABLE IF NOT EXISTS ${t.identifier(i)} USING fts5(${t.identifier(Ee)}, ${t.identifier(l)} UNINDEXED)`),await h(e,n,t`CREATE VIRTUAL TABLE IF NOT EXISTS ${t.identifier(`${i}__vocab`)} USING fts5vocab(${t.identifier(i)}, ${t.raw("instance")})`)},indexDocument:async(e,n,i,o,r,s)=>{await A(e,n,i,o),await h(e,n,t`INSERT INTO ${t.identifier(i)} (${t.identifier("__text__")}, ${t.identifier(l)}) VALUES (${O(r,s)}, ${o})`)},name:"fts5",runSearch:Ce},Ue={ensureCompanion:async(e,n,i)=>{const o=n.nativeTextSearch;if(o){await h(e,n,o.createCompanion(i,n.companionTypes.key));for(const r of o.createIndexes(i))await h(e,n,r)}},indexDocument:async(e,n,i,o,r,s)=>{const a=n.nativeTextSearch;a&&(await A(e,n,i,o),await h(e,n,a.indexDocument(i,o,O(r,s))))},name:"native",runSearch:Oe},N=(e,n)=>e.strategy==="native"&&n.nativeTextSearch!==void 0?Ue:n.supportsFts5?xe:qe,J=(e,n)=>`${y(e.language).profile}/${N(e,n).name}`,q=function*(e){for(const[n,i]of Object.entries(e.tables)){const o=i.searchIndexes;if(!(i.shardMode!==void 0&&i.shardMode.kind!=="global"||!o))for(const r of o)yield[n,i,r]}},x=(e,n)=>I(e,n.name),Ve=async(e,n,i,o,r,s)=>N(r.definition,n).runSearch(e,n,i,o,r,s),H=200,X=async(e,n,i,o,r)=>{const s=x(o,r),a=N(r,n),c=J(r,n),u=Se(await P(e,n,s),c);if(u.finished)return!0;if(u.wipe&&(await h(e,n,t`DELETE FROM ${t.identifier(s)}`),await v(e,n,s,void 0,!1,c)),(await C(e,n,n.tableExists(o))).length===0)return await v(e,n,s,void 0,!0,c),!0;let m=0,$=u.cursor;await ie(e,n,i,o,async w=>{m+=1;const d=w._id;typeof d=="string"&&($=d,await a.indexDocument(e,n,s,d,w,r))},{after:u.cursor,limit:H});const E=m<H;return await v(e,n,s,$,E,c),E},Y=async(e,n,i)=>{await Z(e,i);for(const[o,,r]of q(n)){const s=x(o,r),a=J(r,i),c=await P(e,i,s);c.profile!==void 0&&c.profile!==a&&(await h(e,i,t`DROP TABLE IF EXISTS ${t.identifier(s)}`),await v(e,i,s,void 0,!1,a)),await N(r,i).ensureCompanion(e,i,s)}},Je=async(e,n,i)=>{await Y(e,n,i);for(const[o,r,s]of q(n))s.staged||await X(e,i,r,o,s)},Xe=async(e,n,i)=>{await Y(e,n,i);for(const[o,r,s]of q(n)){let a=!1;for(;!a;)a=await X(e,i,r,o,s)}},Ye=e=>{const{dialect:n,exec:i,schema:o}=e;return async(r,s,a,c)=>{const u=o.tables[r]?.searchIndexes;if(!(!u||u.length===0))for(const f of u){if(ye(c,a,f))continue;const m=x(r,f);if(a){await N(f,n).indexDocument(i,n,m,s,a,f);continue}await A(i,n,m,s)}}};export{Ge as B,We as D,Qe as M,He as R,ze as _,Ve as a,Xe as b,Ye as c,y as j,Je as r,Pe as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r=t=>{if(t.kind!=="optional")return t.kind;const n=t._meta?.inner;return n?r(n):t.kind},f=t=>typeof t=="boolean"?t?1:0:t===null||typeof t=="string"||typeof t=="number"?t:typeof t=="bigint"?t.toString():t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):JSON.stringify(t),e=t=>{try{return JSON.parse(t)}catch{return t}},i=t=>{if(typeof t!="string")return t;try{return BigInt(t)}catch{return t}},s=t=>r(t),c=(t,n)=>{if(t===null)return t;switch(n){case"any":case"from":case"union":return typeof t=="string"&&(t.startsWith("{")||t.startsWith("["))?e(t):t;case"array":case"object":case"record":return typeof t=="string"?e(t):t;case"bigint":return i(t);case"boolean":return t===0||t===1?t===1:t;case"bytes":return t instanceof ArrayBuffer?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice().buffer:t;default:return t}};export{i as decodeBigint,s as effectiveColumnKind,c as sqliteDecode,f as sqliteEncode,e as tryJsonParse};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{renderSql as u}from"@lunora/shard-engine";import{sql as i}from"drizzle-orm";import{sqliteEncode as I,sqliteDecode as y,effectiveColumnKind as C}from"./decodeBigint-B4wY6fcF.mjs";const g=t=>t==="_id"||t==="id"?"id":t,A=t=>i`${i.identifier(g(t))}`,S=(t,n,e)=>{const{params:o,sql:r}=u(n.name,e);return t.all(r,o)},l=(t,n,e)=>{const{params:o,sql:r}=u(n.name,e);return t.run(r,o)},b=async(t,n,e)=>{if(e.length!==0){if(!t.batch){for(const o of e)await l(t,n,o);return}await t.batch(e.map(o=>u(n.name,o)))}},M=async(t,n,e)=>{const o=e.unique?i`UNIQUE `:i``;if(n.name==="mysql"){try{await l(t,n,i`CREATE ${o}INDEX ${i.identifier(e.name)} ON ${i.identifier(e.table)} (${e.columns})`)}catch(r){const a=r;if(a.errno!==1061&&a.code!=="ER_DUP_KEYNAME"&&a.code!==1061)throw r}return}await l(t,n,i`CREATE ${o}INDEX IF NOT EXISTS ${i.identifier(e.name)} ON ${i.identifier(e.table)} (${e.columns})`)},O=I,h=new WeakMap,T=t=>{let n=h.get(t);return n===void 0&&(n=Object.entries(t.shape).map(([e,o])=>[e,C(o)]),h.set(t,n)),n},p=(t,n)=>{const e={};for(const[o,r]of T(t)){const a=n[o];a!==void 0&&(e[o]=y(a,r))}return e._id=n.id,e._creationTime=n._creationTime,e},$=(t,n)=>n?p(t,n):null,D=(t,n)=>{const e=[];for(const o of n){const r=$(t,o);r&&e.push(r)}return e},w=500,K=async(t,n,e,o,r,a={})=>{let d=a.after,c=a.limit,f=!0;for(;f&&(c===void 0||c>0);){const m=c===void 0?w:Math.min(w,c),R=d===void 0?i``:i` WHERE ${i.identifier("id")} > ${d}`,s=await S(t,n,i`SELECT * FROM ${i.identifier(o)}${R} ORDER BY ${i.identifier("id")} ASC LIMIT ${i.raw(String(m))}`);for(const q of s){const E=$(e,q);E&&await r(E)}d=s.at(-1)?.id,f=s.length===m,c=c===void 0?void 0:c-s.length}};export{w as BACKFILL_BATCH_SIZE,A as columnRefSql,M as createIndexIfNotExists,p as decodeGlobalRow,$ as decodeRow,D as decodeRows,K as forEachRowPaged,g as physicalColumn,S as queryAll,b as queryBatch,l as queryRun,O as serializeColumnValue};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/sql-store",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.80",
|
|
4
4
|
"description": "Internal dialect-parameterized SQL store core for Lunora .global() backends (D1, PlanetScale)",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -50,7 +50,8 @@
|
|
|
50
50
|
"access": "public"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@lunora/
|
|
53
|
+
"@lunora/errors": "1.0.0-alpha.22",
|
|
54
|
+
"@lunora/shard-engine": "1.0.0-alpha.28",
|
|
54
55
|
"drizzle-orm": "^0.45.2"
|
|
55
56
|
},
|
|
56
57
|
"engines": {
|