@lunora/sql-store 1.0.0-alpha.224 → 1.0.0-alpha.227
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dialect.d.mts +19 -5
- package/dist/dialect.d.ts +19 -5
- package/dist/index.d.mts +39 -11
- package/dist/index.d.ts +39 -11
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs +1 -0
- package/dist/packem_shared/{SEARCH_STATE_TABLE-CtoIJ1PM.mjs → SEARCH_STATE_TABLE-C518HmG4.mjs} +1 -1
- package/dist/packem_shared/backfillSqlSearchIndexes-D51kmgfu.mjs +1 -0
- package/dist/packem_shared/createSqlCtxDb-nFFLsLPe.mjs +7 -0
- package/dist/packem_shared/ctx-db-search-DH6CwEsG.mjs +1 -0
- package/dist/packem_shared/ctx-db-search-state-BFQG9D20.mjs +1 -0
- package/dist/packem_shared/{decodeGlobalRow-DC2qlCZl.mjs → decodeGlobalRow-Ct74lsu4.mjs} +1 -1
- package/dist/packem_shared/exportSqlGlobalRows-CdZOH72U.mjs +1 -0
- package/dist/packem_shared/{facetSqlGlobalColumn-f5GVnQn4.mjs → facetSqlGlobalColumn-CAQNCBVu.mjs} +1 -1
- package/dist/packem_shared/post-commit-error-hh-zQyjO.mjs +1 -0
- package/dist/packem_shared/runSqlAggregateMigrations-CvZiVJ9S.mjs +1 -0
- package/dist/packem_shared/{runSqlGlobalTableMigrations-C7teG_kd.mjs → runSqlGlobalTableMigrations-C4_8w8pO.mjs} +1 -1
- package/dist/packem_shared/{sql-exec-CkHeSf_v.mjs → sql-exec-ChIYvWnI.mjs} +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/backfillSqlSearchIndexes-LRAu-CxC.mjs +0 -1
- package/dist/packem_shared/createSqlCtxDb-Dok-o1HT.mjs +0 -7
- package/dist/packem_shared/ctx-db-search-D_0SkyeY.mjs +0 -1
- package/dist/packem_shared/ctx-db-search-state-C4l9QBq-.mjs +0 -1
- package/dist/packem_shared/exportSqlGlobalRows-IxOHBsm_.mjs +0 -1
- package/dist/packem_shared/runSqlAggregateMigrations-5fjwAdYh.mjs +0 -1
package/dist/dialect.d.mts
CHANGED
|
@@ -29,11 +29,12 @@ interface SqlRunResult {
|
|
|
29
29
|
* write and reports `rowsAffected` — the matched-rows count that drives the
|
|
30
30
|
* MySQL optimistic-concurrency guard (which has no `RETURNING`).
|
|
31
31
|
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
32
|
+
* A row write and its aggregate/rank/CDC companion statements commit together
|
|
33
|
+
* when the executor provides `transaction`. Without it they run after the row
|
|
34
|
+
* write: as one ordered batch where the executor provides `batch` on the sqlite
|
|
35
|
+
* dialect, otherwise as sequential statements, and a failure partway through
|
|
36
|
+
* leaves the earlier ones applied. The FTS search companion always follows the
|
|
37
|
+
* row write on its own, guarded by the row's version.
|
|
37
38
|
*/
|
|
38
39
|
interface SqlExec {
|
|
39
40
|
all: (sql: string, params: ReadonlyArray<unknown>) => Promise<Record<string, unknown>[]>;
|
|
@@ -68,6 +69,19 @@ interface SqlExec {
|
|
|
68
69
|
sql: string;
|
|
69
70
|
}>) => Promise<void>;
|
|
70
71
|
run: (sql: string, params: ReadonlyArray<unknown>) => Promise<SqlRunResult>;
|
|
72
|
+
/**
|
|
73
|
+
* Optional: run `work` against an exec pinned to ONE connection inside one
|
|
74
|
+
* transaction, committed when `work` resolves and rolled back when it
|
|
75
|
+
* throws. The store runs a row write, the reads its companions need and the
|
|
76
|
+
* companion writes through it, so the row and its counters never drift
|
|
77
|
+
* apart. Statements inside see each other's effects, and `RETURNING` /
|
|
78
|
+
* affected-rows report as they do outside.
|
|
79
|
+
*
|
|
80
|
+
* Never implement it by sending `BEGIN`/`COMMIT` through a pool: consecutive
|
|
81
|
+
* calls may land on different connections. D1 has no interactive
|
|
82
|
+
* transaction, so its execs leave this out.
|
|
83
|
+
*/
|
|
84
|
+
transaction?: <T>(work: (tx: SqlExec) => Promise<T>) => Promise<T>;
|
|
71
85
|
}
|
|
72
86
|
/** Everything engine-specific the store core needs. One value per engine; `sqliteDialect` (in `@lunora/d1`) is the reference, Postgres/MySQL live in `@lunora/hyperdrive/global`. */
|
|
73
87
|
interface SqlDialect {
|
package/dist/dialect.d.ts
CHANGED
|
@@ -29,11 +29,12 @@ interface SqlRunResult {
|
|
|
29
29
|
* write and reports `rowsAffected` — the matched-rows count that drives the
|
|
30
30
|
* MySQL optimistic-concurrency guard (which has no `RETURNING`).
|
|
31
31
|
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
32
|
+
* A row write and its aggregate/rank/CDC companion statements commit together
|
|
33
|
+
* when the executor provides `transaction`. Without it they run after the row
|
|
34
|
+
* write: as one ordered batch where the executor provides `batch` on the sqlite
|
|
35
|
+
* dialect, otherwise as sequential statements, and a failure partway through
|
|
36
|
+
* leaves the earlier ones applied. The FTS search companion always follows the
|
|
37
|
+
* row write on its own, guarded by the row's version.
|
|
37
38
|
*/
|
|
38
39
|
interface SqlExec {
|
|
39
40
|
all: (sql: string, params: ReadonlyArray<unknown>) => Promise<Record<string, unknown>[]>;
|
|
@@ -68,6 +69,19 @@ interface SqlExec {
|
|
|
68
69
|
sql: string;
|
|
69
70
|
}>) => Promise<void>;
|
|
70
71
|
run: (sql: string, params: ReadonlyArray<unknown>) => Promise<SqlRunResult>;
|
|
72
|
+
/**
|
|
73
|
+
* Optional: run `work` against an exec pinned to ONE connection inside one
|
|
74
|
+
* transaction, committed when `work` resolves and rolled back when it
|
|
75
|
+
* throws. The store runs a row write, the reads its companions need and the
|
|
76
|
+
* companion writes through it, so the row and its counters never drift
|
|
77
|
+
* apart. Statements inside see each other's effects, and `RETURNING` /
|
|
78
|
+
* affected-rows report as they do outside.
|
|
79
|
+
*
|
|
80
|
+
* Never implement it by sending `BEGIN`/`COMMIT` through a pool: consecutive
|
|
81
|
+
* calls may land on different connections. D1 has no interactive
|
|
82
|
+
* transaction, so its execs leave this out.
|
|
83
|
+
*/
|
|
84
|
+
transaction?: <T>(work: (tx: SqlExec) => Promise<T>) => Promise<T>;
|
|
71
85
|
}
|
|
72
86
|
/** Everything engine-specific the store core needs. One value per engine; `sqliteDialect` (in `@lunora/d1`) is the reference, Postgres/MySQL live in `@lunora/hyperdrive/global`. */
|
|
73
87
|
interface SqlDialect {
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { TableDefinitionLike, ImportConflictMode, SchemaLike, DatabaseWriterLike, ServerDefaultContextLike, CrossShardReadArgs, QueryPage, SchedulerLike, CdcChange, ValidatorLike } from '@lunora/shard-engine';
|
|
2
2
|
import { SqlRunResult, SqlDialect } from "./dialect.mjs";
|
|
3
3
|
export type { SqlExec } from "./dialect.mjs";
|
|
4
|
+
import { LunoraError } from '@lunora/errors';
|
|
4
5
|
import 'drizzle-orm';
|
|
5
6
|
/**
|
|
6
7
|
* Async SQL surface the D1 ORM needs: `all` for reads, `run` for writes.
|
|
@@ -14,6 +15,7 @@ interface SqlCtxExec {
|
|
|
14
15
|
sql: string;
|
|
15
16
|
}>) => Promise<void>;
|
|
16
17
|
run: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<SqlRunResult | void>;
|
|
18
|
+
transaction?: <T>(work: (tx: SqlCtxExec) => Promise<T>) => Promise<T>;
|
|
17
19
|
}
|
|
18
20
|
/**
|
|
19
21
|
* Decode a SELECTed row back into a document: `id` → `_id`, `_creationTime`
|
|
@@ -42,6 +44,12 @@ interface ExportRow {
|
|
|
42
44
|
* in tests), which keeps the positional fallback.
|
|
43
45
|
*/
|
|
44
46
|
line?: number;
|
|
47
|
+
/**
|
|
48
|
+
* Import only: `"delete"` removes the stored row whose `_id` the doc carries
|
|
49
|
+
* instead of writing the doc — how a replace-mode restore prunes the rows its
|
|
50
|
+
* source no longer has.
|
|
51
|
+
*/
|
|
52
|
+
op?: "delete";
|
|
45
53
|
table: string;
|
|
46
54
|
}
|
|
47
55
|
interface ImportError {
|
|
@@ -53,6 +61,8 @@ interface ImportError {
|
|
|
53
61
|
interface ImportResult {
|
|
54
62
|
/** Skipped rows whose `_id` already exists (the default `onConflict: "skip"`). */
|
|
55
63
|
conflicts: number;
|
|
64
|
+
/** Stored rows removed by `op: "delete"` rows. A delete whose `_id` is already gone removes nothing and is not counted. */
|
|
65
|
+
deleted: number;
|
|
56
66
|
errors: ImportError[];
|
|
57
67
|
inserted: Record<string, number>;
|
|
58
68
|
/** Existing rows overwritten under `onConflict: "replace"`. */
|
|
@@ -93,12 +103,9 @@ interface ImportGlobalArgs {
|
|
|
93
103
|
*/
|
|
94
104
|
dryRun?: boolean;
|
|
95
105
|
/**
|
|
96
|
-
* Optional direct exec handle to the same database the writer targets.
|
|
97
|
-
*
|
|
98
|
-
* `SELECT 1
|
|
99
|
-
* table instead of falling back to an unscoped id probe, which scans every
|
|
100
|
-
* global table looking for the id. Strongly recommended for large schemas
|
|
101
|
-
* — the writer-fallback is O(N tables) per row.
|
|
106
|
+
* Optional direct exec handle to the same database the writer targets. When supplied, the conflict probe
|
|
107
|
+
* is a batched `SELECT id ... WHERE id IN (...)` per table (or, for a schema with triggers, one
|
|
108
|
+
* `SELECT 1 ... WHERE id = ?` per row) instead of a writer `get` per row.
|
|
102
109
|
*/
|
|
103
110
|
exec?: SqlCtxExec;
|
|
104
111
|
/**
|
|
@@ -119,11 +126,24 @@ interface ImportGlobalArgs {
|
|
|
119
126
|
* conflict instead of bubbled as a UNIQUE error. Schema-failed rows surface in
|
|
120
127
|
* `errors`; the rest land.
|
|
121
128
|
*
|
|
122
|
-
* With an `exec` handle the probe is batched
|
|
123
|
-
* the whole call
|
|
124
|
-
*
|
|
129
|
+
* Only a row's own table is probed. With an `exec` handle and no triggers the probe is batched
|
|
130
|
+
* ({@link probeHeldIds}) once for the whole call; a schema with triggers probes each row right before its write,
|
|
131
|
+
* because a trigger can create or delete rows in the table mid-import.
|
|
125
132
|
*/
|
|
126
133
|
declare const importSqlGlobalRows: (writer: DatabaseWriterLike, schema: SchemaLike, dialect: SqlDialect, args: ImportGlobalArgs) => Promise<ImportResult>;
|
|
134
|
+
/** Arm a timer that calls `fire` after `ms`, returning the function that disarms it. Injectable so tests fire it by hand. */
|
|
135
|
+
type QueryTimer = (fire: () => void, ms: number) => () => void;
|
|
136
|
+
/** The bound a `.global()` statement gets when the host names none: past it, the dispatch waiting on it is released. */
|
|
137
|
+
declare const DEFAULT_QUERY_TIMEOUT_MS = 3e4;
|
|
138
|
+
/**
|
|
139
|
+
* A `.global()` statement outlived its deadline and was abandoned. `503` and retryable, as an upstream that did not
|
|
140
|
+
* answer is. The engine may still run it, so a write that timed out may or may not have applied, and the store
|
|
141
|
+
* never retries one itself.
|
|
142
|
+
*/
|
|
143
|
+
declare class SqlQueryTimeoutError extends LunoraError {
|
|
144
|
+
readonly timeoutMs: number;
|
|
145
|
+
constructor(timeoutMs: number);
|
|
146
|
+
}
|
|
127
147
|
interface SqlCtxDbOptions {
|
|
128
148
|
/**
|
|
129
149
|
* Resolved request auth handed to `.serverDefault(fn)` column factories so
|
|
@@ -246,6 +266,14 @@ interface SqlCtxDbOptions {
|
|
|
246
266
|
* tests want (they pair a fresh database with a reused schema object).
|
|
247
267
|
*/
|
|
248
268
|
provisionScope?: object;
|
|
269
|
+
/**
|
|
270
|
+
* Deadline for each statement this writer sends, in milliseconds; past it the statement is abandoned with a
|
|
271
|
+
* retryable `SqlQueryTimeoutError` instead of holding the dispatch that awaits it. Defaults to
|
|
272
|
+
* {@link DEFAULT_QUERY_TIMEOUT_MS}; `0` or `Infinity` leaves statements unbounded.
|
|
273
|
+
*/
|
|
274
|
+
queryTimeoutMs?: number;
|
|
275
|
+
/** The timer that arms each statement's deadline; tests inject one to fire it by hand. */
|
|
276
|
+
queryTimer?: QueryTimer;
|
|
249
277
|
/**
|
|
250
278
|
* Scheduler exposed to global-table trigger handlers as `ctx.scheduler`.
|
|
251
279
|
* Absent it, `ctx.scheduler` is a stub that throws on use — pass one when
|
|
@@ -615,7 +643,7 @@ declare const effectiveColumnKind: (validator: ValidatorLike) => string | undefi
|
|
|
615
643
|
* - everything else (string/number/date/timestamp/id/literal): verbatim.
|
|
616
644
|
*/
|
|
617
645
|
declare const sqliteDecode: (raw: unknown, kind: string | undefined) => unknown;
|
|
618
|
-
export {
|
|
646
|
+
export { DEFAULT_QUERY_TIMEOUT_MS,
|
|
619
647
|
/**
|
|
620
648
|
* `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
|
|
621
649
|
* shared by Lunora's `.global()` table backends.
|
|
@@ -685,4 +713,4 @@ type ImportGlobalArgs,
|
|
|
685
713
|
* This package is internal: consumers depend on `@lunora/d1` or
|
|
686
714
|
* `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
|
|
687
715
|
*/
|
|
688
|
-
type ImportResult, type ReadGlobalTablePageOptions, SEARCH_STATE_TABLE, type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, exportSqlGlobalRows, facetSqlGlobalColumn, importSqlGlobalRows, listSqlGlobalTables, migrateSearchState, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, readSqlGlobalTablePage, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, selectGlobalTables, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };
|
|
716
|
+
type ImportResult, type QueryTimer, type ReadGlobalTablePageOptions, SEARCH_STATE_TABLE, type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, SqlQueryTimeoutError, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, exportSqlGlobalRows, facetSqlGlobalColumn, importSqlGlobalRows, listSqlGlobalTables, migrateSearchState, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, readSqlGlobalTablePage, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, selectGlobalTables, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { TableDefinitionLike, ImportConflictMode, SchemaLike, DatabaseWriterLike, ServerDefaultContextLike, CrossShardReadArgs, QueryPage, SchedulerLike, CdcChange, ValidatorLike } from '@lunora/shard-engine';
|
|
2
2
|
import { SqlRunResult, SqlDialect } from "./dialect.js";
|
|
3
3
|
export type { SqlExec } from "./dialect.js";
|
|
4
|
+
import { LunoraError } from '@lunora/errors';
|
|
4
5
|
import 'drizzle-orm';
|
|
5
6
|
/**
|
|
6
7
|
* Async SQL surface the D1 ORM needs: `all` for reads, `run` for writes.
|
|
@@ -14,6 +15,7 @@ interface SqlCtxExec {
|
|
|
14
15
|
sql: string;
|
|
15
16
|
}>) => Promise<void>;
|
|
16
17
|
run: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<SqlRunResult | void>;
|
|
18
|
+
transaction?: <T>(work: (tx: SqlCtxExec) => Promise<T>) => Promise<T>;
|
|
17
19
|
}
|
|
18
20
|
/**
|
|
19
21
|
* Decode a SELECTed row back into a document: `id` → `_id`, `_creationTime`
|
|
@@ -42,6 +44,12 @@ interface ExportRow {
|
|
|
42
44
|
* in tests), which keeps the positional fallback.
|
|
43
45
|
*/
|
|
44
46
|
line?: number;
|
|
47
|
+
/**
|
|
48
|
+
* Import only: `"delete"` removes the stored row whose `_id` the doc carries
|
|
49
|
+
* instead of writing the doc — how a replace-mode restore prunes the rows its
|
|
50
|
+
* source no longer has.
|
|
51
|
+
*/
|
|
52
|
+
op?: "delete";
|
|
45
53
|
table: string;
|
|
46
54
|
}
|
|
47
55
|
interface ImportError {
|
|
@@ -53,6 +61,8 @@ interface ImportError {
|
|
|
53
61
|
interface ImportResult {
|
|
54
62
|
/** Skipped rows whose `_id` already exists (the default `onConflict: "skip"`). */
|
|
55
63
|
conflicts: number;
|
|
64
|
+
/** Stored rows removed by `op: "delete"` rows. A delete whose `_id` is already gone removes nothing and is not counted. */
|
|
65
|
+
deleted: number;
|
|
56
66
|
errors: ImportError[];
|
|
57
67
|
inserted: Record<string, number>;
|
|
58
68
|
/** Existing rows overwritten under `onConflict: "replace"`. */
|
|
@@ -93,12 +103,9 @@ interface ImportGlobalArgs {
|
|
|
93
103
|
*/
|
|
94
104
|
dryRun?: boolean;
|
|
95
105
|
/**
|
|
96
|
-
* Optional direct exec handle to the same database the writer targets.
|
|
97
|
-
*
|
|
98
|
-
* `SELECT 1
|
|
99
|
-
* table instead of falling back to an unscoped id probe, which scans every
|
|
100
|
-
* global table looking for the id. Strongly recommended for large schemas
|
|
101
|
-
* — the writer-fallback is O(N tables) per row.
|
|
106
|
+
* Optional direct exec handle to the same database the writer targets. When supplied, the conflict probe
|
|
107
|
+
* is a batched `SELECT id ... WHERE id IN (...)` per table (or, for a schema with triggers, one
|
|
108
|
+
* `SELECT 1 ... WHERE id = ?` per row) instead of a writer `get` per row.
|
|
102
109
|
*/
|
|
103
110
|
exec?: SqlCtxExec;
|
|
104
111
|
/**
|
|
@@ -119,11 +126,24 @@ interface ImportGlobalArgs {
|
|
|
119
126
|
* conflict instead of bubbled as a UNIQUE error. Schema-failed rows surface in
|
|
120
127
|
* `errors`; the rest land.
|
|
121
128
|
*
|
|
122
|
-
* With an `exec` handle the probe is batched
|
|
123
|
-
* the whole call
|
|
124
|
-
*
|
|
129
|
+
* Only a row's own table is probed. With an `exec` handle and no triggers the probe is batched
|
|
130
|
+
* ({@link probeHeldIds}) once for the whole call; a schema with triggers probes each row right before its write,
|
|
131
|
+
* because a trigger can create or delete rows in the table mid-import.
|
|
125
132
|
*/
|
|
126
133
|
declare const importSqlGlobalRows: (writer: DatabaseWriterLike, schema: SchemaLike, dialect: SqlDialect, args: ImportGlobalArgs) => Promise<ImportResult>;
|
|
134
|
+
/** Arm a timer that calls `fire` after `ms`, returning the function that disarms it. Injectable so tests fire it by hand. */
|
|
135
|
+
type QueryTimer = (fire: () => void, ms: number) => () => void;
|
|
136
|
+
/** The bound a `.global()` statement gets when the host names none: past it, the dispatch waiting on it is released. */
|
|
137
|
+
declare const DEFAULT_QUERY_TIMEOUT_MS = 3e4;
|
|
138
|
+
/**
|
|
139
|
+
* A `.global()` statement outlived its deadline and was abandoned. `503` and retryable, as an upstream that did not
|
|
140
|
+
* answer is. The engine may still run it, so a write that timed out may or may not have applied, and the store
|
|
141
|
+
* never retries one itself.
|
|
142
|
+
*/
|
|
143
|
+
declare class SqlQueryTimeoutError extends LunoraError {
|
|
144
|
+
readonly timeoutMs: number;
|
|
145
|
+
constructor(timeoutMs: number);
|
|
146
|
+
}
|
|
127
147
|
interface SqlCtxDbOptions {
|
|
128
148
|
/**
|
|
129
149
|
* Resolved request auth handed to `.serverDefault(fn)` column factories so
|
|
@@ -246,6 +266,14 @@ interface SqlCtxDbOptions {
|
|
|
246
266
|
* tests want (they pair a fresh database with a reused schema object).
|
|
247
267
|
*/
|
|
248
268
|
provisionScope?: object;
|
|
269
|
+
/**
|
|
270
|
+
* Deadline for each statement this writer sends, in milliseconds; past it the statement is abandoned with a
|
|
271
|
+
* retryable `SqlQueryTimeoutError` instead of holding the dispatch that awaits it. Defaults to
|
|
272
|
+
* {@link DEFAULT_QUERY_TIMEOUT_MS}; `0` or `Infinity` leaves statements unbounded.
|
|
273
|
+
*/
|
|
274
|
+
queryTimeoutMs?: number;
|
|
275
|
+
/** The timer that arms each statement's deadline; tests inject one to fire it by hand. */
|
|
276
|
+
queryTimer?: QueryTimer;
|
|
249
277
|
/**
|
|
250
278
|
* Scheduler exposed to global-table trigger handlers as `ctx.scheduler`.
|
|
251
279
|
* Absent it, `ctx.scheduler` is a stub that throws on use — pass one when
|
|
@@ -615,7 +643,7 @@ declare const effectiveColumnKind: (validator: ValidatorLike) => string | undefi
|
|
|
615
643
|
* - everything else (string/number/date/timestamp/id/literal): verbatim.
|
|
616
644
|
*/
|
|
617
645
|
declare const sqliteDecode: (raw: unknown, kind: string | undefined) => unknown;
|
|
618
|
-
export {
|
|
646
|
+
export { DEFAULT_QUERY_TIMEOUT_MS,
|
|
619
647
|
/**
|
|
620
648
|
* `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
|
|
621
649
|
* shared by Lunora's `.global()` table backends.
|
|
@@ -685,4 +713,4 @@ type ImportGlobalArgs,
|
|
|
685
713
|
* This package is internal: consumers depend on `@lunora/d1` or
|
|
686
714
|
* `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
|
|
687
715
|
*/
|
|
688
|
-
type ImportResult, type ReadGlobalTablePageOptions, SEARCH_STATE_TABLE, type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, exportSqlGlobalRows, facetSqlGlobalColumn, importSqlGlobalRows, listSqlGlobalTables, migrateSearchState, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, readSqlGlobalTablePage, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, selectGlobalTables, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };
|
|
716
|
+
type ImportResult, type QueryTimer, type ReadGlobalTablePageOptions, SEARCH_STATE_TABLE, type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, SqlQueryTimeoutError, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, exportSqlGlobalRows, facetSqlGlobalColumn, importSqlGlobalRows, listSqlGlobalTables, migrateSearchState, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, readSqlGlobalTablePage, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, selectGlobalTables, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportSqlGlobalRows as
|
|
1
|
+
import{exportSqlGlobalRows as r,importSqlGlobalRows as a,selectGlobalTables as l}from"./packem_shared/exportSqlGlobalRows-CdZOH72U.mjs";import{createSqlCtxDb as s,readSqlCdcChangedTables as S,readSqlCdcChanges as i,readSqlCdcFloor as n,runSqlCdcMigration as d,sweepSqlCdcRetention as q}from"./packem_shared/createSqlCtxDb-nFFLsLPe.mjs";import{runSqlGlobalTableMigrations as b}from"./packem_shared/runSqlGlobalTableMigrations-C4_8w8pO.mjs";import{runSqlAggregateMigrations as f,runSqlRankMigrations as g}from"./packem_shared/runSqlAggregateMigrations-CvZiVJ9S.mjs";import{b as x,r as T}from"./packem_shared/ctx-db-search-DH6CwEsG.mjs";import{S as u,m as E}from"./packem_shared/ctx-db-search-state-BFQG9D20.mjs";import{facetSqlGlobalColumn as M,listSqlGlobalTables as R,readSqlGlobalTablePage as h}from"./packem_shared/facetSqlGlobalColumn-CAQNCBVu.mjs";import{DEFAULT_QUERY_TIMEOUT_MS as _,SqlQueryTimeoutError as w}from"./packem_shared/DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import{d as U,e as k,s as y,a as B,t as F}from"./packem_shared/value-codec-C52YW-Do.mjs";import{d as L}from"./packem_shared/sql-exec-ChIYvWnI.mjs";export{_ as DEFAULT_QUERY_TIMEOUT_MS,u as SEARCH_STATE_TABLE,w as SqlQueryTimeoutError,x as backfillSqlSearchIndexes,s as createSqlCtxDb,U as decodeBigint,L as decodeGlobalRow,k as effectiveColumnKind,r as exportSqlGlobalRows,M as facetSqlGlobalColumn,a as importSqlGlobalRows,R as listSqlGlobalTables,E as migrateSearchState,S as readSqlCdcChangedTables,i as readSqlCdcChanges,n as readSqlCdcFloor,h as readSqlGlobalTablePage,f as runSqlAggregateMigrations,d as runSqlCdcMigration,b as runSqlGlobalTableMigrations,g as runSqlRankMigrations,T as runSqlSearchMigrations,l as selectGlobalTables,y as sqliteDecode,B as sqliteEncode,q as sweepSqlCdcRetention,F as tryJsonParse};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";const T=3e4,h=(a,n)=>{const t=setTimeout(a,n);return()=>{clearTimeout(t)}};class l extends y{timeoutMs;constructor(n){super("SERVICE_UNAVAILABLE",`the .global() database did not answer within ${String(n)}ms; the statement was abandoned and, if it was a write, may or may not have applied`,{internal:{timeoutMs:n},name:"SqlQueryTimeoutError"}),this.timeoutMs=n}}const d=new WeakMap,f=a=>a instanceof l?d.get(a):void 0,b=(a,n)=>({all:async(t,e)=>(n(),await a.all(t,e)),...a.batch===void 0?{}:{batch:async t=>{n(),await a.batch?.(t)}},run:async(t,e)=>(n(),await a.run(t,e))}),m=(a,n,t=h)=>{if(!Number.isFinite(n)||n<=0)return a;const e=async(r,o)=>{let i;const s=new Promise((c,w)=>{i=t(()=>{const u=new l(n);d.set(u,r),o?.(),w(u)},n)});try{return await Promise.race([r,s])}finally{i?.()}};return{all:async(r,o)=>await e(a.all(r,o)),...a.batch===void 0?{}:{batch:async r=>{await e(a.batch?.(r)??Promise.resolve())}},run:async(r,o)=>await e(a.run(r,o)),...a.transaction===void 0?{}:{transaction:async r=>{let o=!1;const i=()=>{if(o)throw new l(n)};return await e(a.transaction(async s=>{i();const c=await r(b(m(s,n,t),i));return i(),c}),()=>{o=!0})}}}};export{T as DEFAULT_QUERY_TIMEOUT_MS,l as SqlQueryTimeoutError,f as abandonedWork,m as withQueryTimeout};
|
package/dist/packem_shared/{SEARCH_STATE_TABLE-CtoIJ1PM.mjs → SEARCH_STATE_TABLE-C518HmG4.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{S as t,a as S,m as c,r as l,b as i,w as s}from"./ctx-db-search-state-
|
|
1
|
+
import{S as t,a as S,m as c,r as l,b as i,w as s}from"./ctx-db-search-state-BFQG9D20.mjs";import"./sql-exec-ChIYvWnI.mjs";export{t as SEARCH_STATE_TABLE,S as clearSearchBackfillState,c as migrateSearchState,l as readSearchBackfillState,i as readSearchIndexCoverage,s as writeSearchBackfillState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./ctx-db-search-state-BFQG9D20.mjs";import{b as o,c as i,a as s,d as l,r as n}from"./ctx-db-search-DH6CwEsG.mjs";import"./DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import"./sql-exec-ChIYvWnI.mjs";export{o as backfillSqlSearchIndexes,i as createSearchSync,s as reconcileSearchRow,l as runSqlSearch,n as runSqlSearchMigrations};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{m as mn,q as gn}from"./ctx-db-search-state-BFQG9D20.mjs";import{c as Tn,r as vn,a as In,A as An,C as Cn,R as Ln,u as bn,d as Mn,T as Nn,x as On,e as qn}from"./ctx-db-search-DH6CwEsG.mjs";import{throwingScheduler as kn,describeRelationWrites as Dn,CDC_LOG_TABLE as W,cdcForkedError as Bn,cursorBelowRetainedFloor as Wn,cdcTrimmedError as Fn,serverInList as Un,assertNoExplicitUndefined as Ve,hasTrigger as xn,runRowValidators as Ye,assertFlatPredicate as St,mergeWhere as U,rankTableName as ye,sortColumnName as ge,resolveRankPartition as mt,encodePartitionKey as ke,resolveRankSeekTuple as Pn,RANK_TIEBREAK as Ie,CountRlsUnsupportedError as gt,compileWhereSql as ee,ConflictError as ne,patchDependsOnRow as Hn,normalizeIdStructurally as Kn,applyInsertDefaults as jn,assertValidClientId as Gn,assertStorableRowId as Vn,aggregateSqlFunction as Re,softDeleteScope as De,resolveWith as Tt,relationHooks as vt,applySelect as It,encodeCursor as Yn,NotFoundError as Xn,applyOnDelete as Qn,normalizeCountArgument as zn,selectIndexForCount as Jn,encodeAggregateKey as te,aggregateTableName as ae,selectIndexForAggregate as Zn,readAggregateValue as Xe,runTriggers as ei,matchesRankStaticWhere as At,nullsOrderSuffix as Ct,nullsFirstOf as Lt,rankPivotConditionSql as Yt,CURSOR_PREFIX as ti,resolvePatch as ni,stripReservedPatchFields as ii,assertPatchAllowed as oi,resolveRelationPredicates as ri,selectIndexForGroupBy as si,composeReadPredicate as ai,fanOutScalarCounts as ci,matchesStaticWhere as Qe,coerceAggregateNumber as ze,whereOfFilter as di,isPushableWhere as li,tiebreakDirectionFor as ui,foldAggregateTally as bt,CDC_LOG_TABLE_SEQ_INDEX as fi,NotUniqueError as wi,WORKERD_SQLITE_LIMITS as hi,unionAll as $i}from"@lunora/shard-engine";import{parseWire as _i,needsWireEncoding as Xt,encodeWire as Qt,decodeWire as Ei}from"@lunora/wire";import{sql as e,SQL as pi}from"drizzle-orm";import{p as Mt,b as Nt,q as b,c as K,e as zt,i as yi,f as Ri,g as Si,h as z,s as ce,j as H,k as Ot,t as mi,l as Je,m as Fe,n as at,O as Se,o as qt,a as kt,u as Dt,v as Bt,w as gi,B as Ze,x as Wt,y as Ft,M as Ti}from"./sql-exec-ChIYvWnI.mjs";import{d as Mo}from"./sql-exec-ChIYvWnI.mjs";import{runSqlGlobalTableMigrations as vi}from"./runSqlGlobalTableMigrations-C4_8w8pO.mjs";import{runSqlAggregateMigrations as Ii,runSqlRankMigrations as Ai}from"./runSqlAggregateMigrations-CvZiVJ9S.mjs";import{a as me}from"./post-commit-error-hh-zQyjO.mjs";import{withQueryTimeout as Ci,DEFAULT_QUERY_TIMEOUT_MS as Li,abandonedWork as et,SqlQueryTimeoutError as bi}from"./DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import{s as Jt,e as ct}from"./value-codec-C52YW-Do.mjs";const Ut=50,Mi=(s,a={})=>{const f=a.maxBatch??Ut,$=Number.isInteger(f)&&f>0?f:Ut,l=new Map;let _=!1;const c=async(M,T)=>{const v=[...T.keys()];for(let A=0;A<v.length;A+=$){const N=v.slice(A,A+$);try{const D=await s(M,N);for(const j of N){const J=D.get(j);for(const ie of T.get(j)??[])ie.resolve(J)}}catch(D){for(const j of N)for(const J of T.get(j)??[])J.reject(D)}}},q=()=>{_=!1;const M=[...l.entries()];l.clear();for(const[T,v]of M)c(T,v).catch(()=>{})};return{async load(M,T){return new Promise((v,A)=>{let N=l.get(M);N||(N=new Map,l.set(M,N));const D=N.get(T);D?D.push({reject:A,resolve:v}):N.set(T,[{reject:A,resolve:v}]),_||(_=!0,queueMicrotask(q))})}}},Ni=new Set(["_id","id"]),Oi=s=>{throw new g("INTERNAL",`no ORDER BY NULL placement for dialect "${String(s)}"`)},Zt=(s,a)=>{const f=a.direction==="desc"?"DESC":"ASC",$=a.nullable===!0,l=_=>e`${Fe(s,a.field)} ${e.raw(`${f}${_}`)}`;switch(s.name){case"mysql":{const _=l("");return!$||a.nulls===void 0?[_]:[e`(${Fe(s,a.field)} IS NULL) ${e.raw(a.nulls==="first"?"DESC":"ASC")}`,_]}case"postgres":return[l($?Ct(Lt(a)):"")];case"sqlite":return[l($&&a.nulls!==void 0?Ct(Lt(a)):"")];default:return Oi(s.name)}},qi=(s,a)=>{const f=s.flatMap($=>Zt(a,$));if(!s.some($=>Ni.has($.field))){const $=ui(s);f.push(e`${H("id")} ${e.raw($==="desc"?"DESC":"ASC")}`)}return e.join(f,e`, `)},xt=50,ki=s=>{const a=s.detail??s["QUERY PLAN"];return typeof a=="string"?a:Object.values(s).map(String).join(" | ")},tt=(s,a,f,$)=>{for(const[l,_]of mi(s)){if(_.serverDefault){l in a&&(f[l]=_.serverDefault({auth:$}));continue}_.onUpdateFn&&!(l in a)&&(f[l]=_.onUpdateFn())}},Di=s=>s.shardMode===void 0||s.shardMode.kind==="global",ue=s=>s==null?null:Number(s),Bi=(s,a,f)=>f.map($=>{const l={};for(const _ of a){const c=s.shape[_];l[_]=Jt($[_]??null,c&&ct(c))}return{key:l,value:ue($.value)}}),Wi=(s,a,f)=>[...s.partitionBy??[],...s.sortBy.map(l=>l.field),...s.where?Object.keys(s.where):[]].every(l=>Dt(a,l)===Dt(f,l)),en=s=>s.length===1?s[0]:e`(${e.join(s,e` AND `)})`,fe=s=>e.join(s.map(a=>e`${e.identifier(a)}`),e`, `),Te=s=>e.join(s.map(a=>e`${a}`),e`, `),nt=(s,a)=>{if(s==="postgres"){for(const[f,$]of Object.entries(a))if(typeof $=="string"&&$.includes("\0"))throw new g("BAD_REQUEST",`"${f}" holds a NUL character (U+0000), which a Postgres text column cannot store`)}},Ue=s=>s instanceof ArrayBuffer?new Uint8Array(s):Array.isArray(s)?Uint8Array.from(s):s,Fi=(s,a,f,$,l)=>{const _=[];for(let c=0;c<f.length+1;c+=1){const q=f[c],M=a.sortBy[c],T=c<f.length&&q!==void 0&&M!==void 0,v=M?.direction==="desc"?"desc":"asc",A=T?Yt(q,Ue($[q]),v,!1):e`${e.identifier(Ie)} < ${l}`;if(A===void 0)continue;const N=f.slice(0,c).map(D=>at(s,e`${e.identifier(D)}`,Ue($[D])));N.push(A),_.push(en(N))}return _.length>0?e.join(_,e` OR `):e`1 = 0`},Ui=(s,a,f)=>{if(f.length!==a.length)return;const $=[];for(const[l,_]of a.entries()){const c=Yt(_.column,Ue(f[l]),_.direction,!0);if(c===void 0)continue;const q=[];for(let M=0;M<l;M+=1){const T=a[M];T!==void 0&&q.push(at(s,e`${e.identifier(T.column)}`,Ue(f[M])))}q.push(c),$.push(en(q))}return $.length===0?e`(1 = 0)`:e`(${e.join($,e` OR `)})`},xi=(s,a)=>{if(s.sortBy.length===0)throw new g("INTERNAL",`rankIndex "${s.name}" requires at least one "sortBy" column for stable pagination`);const f=[{column:"__partition__",direction:"asc",nullable:!1}];for(const[$,l]of s.sortBy.entries())f.push({column:a[$]??ge($),direction:l.direction,nullable:!0});return f.push({column:Ie,direction:"asc",nullable:!1}),f},Pi=async(s,a,f,$,l)=>{const c=[];for(let v=0;v<l.length;v+=50)c.push(l.slice(v,v+50));const q=await Promise.all(c.map(async v=>b(s,a,e`SELECT * FROM ${e.identifier($)} WHERE ${e.identifier("id")} IN (${Te(v)})`))),M=new Map;for(const v of q)for(const A of v)M.set(A.id,A);const T=[];for(const v of l){const A=z(f,M.get(v));A&&T.push(A)}return T},Hi=s=>{const a=s.map(_=>Jt(_,"bytes")),f=JSON.stringify(Xt(a)?Qt(a):a),$=new TextEncoder().encode(f);let l="";for(const _ of $)l+=String.fromCodePoint(_);return ti+btoa(l)},tn=s=>{if(s===void 0)return!1;const a=ct(s);return a==="any"||a==="bigint"||a==="from"||a==="union"},rt=(s,a,f)=>{if(tn(s.shape[a]))throw new g("BAD_REQUEST",`${f}: "${a}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Ki=(s,a,f,$)=>{for(const l of f)rt(s,l,`groupBy(${a}, { by: [..."${l}"] })`);$.field!==void 0&&rt(s,$.field,`groupBy(${a}, { agg: { op: "${$.op}", field: "${$.field}" } })`)},st="__cdc_sweep",Be="__cdc_log_ts",nn="global",ji=6e4,Gi=1e4,Vi=3e4;let Pt=0;const Yi=async(s,a)=>{const{autoincrementPrimaryKey:f,key:$,real:l,text:_}=a.companionTypes;await K(s,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(W)} (${e.identifier("seq")} ${e.raw(f)}, ${e.identifier("ts")} ${e.raw(l)} NOT NULL, ${e.identifier("table")} ${e.raw($)} NOT NULL, ${e.identifier("id")} ${e.raw($)} NOT NULL, ${e.identifier("op")} ${e.raw($)} NOT NULL, ${e.identifier("doc")} ${e.raw(_)})`);const c=a.indexKeyPrefix?.("string");await zt(s,a,{columns:e`${c===void 0?e`${e.identifier("table")}`:e`${e.identifier("table")}(${e.raw(String(c))})`}, ${e.identifier("seq")}`,name:fi,table:W,unique:!1}),await K(s,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(st)} (${e.identifier("id")} ${e.raw($)} NOT NULL PRIMARY KEY, ${e.identifier("lease_until")} ${e.raw(l)} NOT NULL)`),await K(s,a,e`INSERT INTO ${e.identifier(st)} (${e.identifier("id")}, ${e.identifier("lease_until")}) VALUES (${nn}, ${0}) ${a.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${e.identifier("id")} = ${e.identifier("id")}`:e`ON CONFLICT(${e.identifier("id")}) DO NOTHING`}`)},Xi=async(s,a,f)=>{const $=e`UPDATE ${e.identifier(st)} SET ${e.identifier("lease_until")} = ${f+ji} WHERE ${e.identifier("id")} = ${nn} AND ${e.identifier("lease_until")} <= ${f}`;if(a.supportsReturning)return(await b(s,a,e`${$} RETURNING ${e.identifier("id")}`)).length>0;const l=await K(s,a,$);return(a.affectedRows?a.affectedRows(l??{rowsAffected:0}):0)>0},Qi=async(s,a,f,$)=>{if(!await Xi(s,a,$))return;const l=$-f;let _=!0;try{const c=await yi(s,a,W,Be);c!=="valid"&&(c==="invalid"&&await Ri(s,a,W,Be),await zt(s,a,{columns:e`${e.identifier("ts")}`,concurrently:!0,name:Be,table:W,unique:!1}))}catch(c){_=!1,console.warn(`[@lunora/sql-store] changelog retention could not build "${Be}"; sweeping without it.`,c)}_&&(await b(s,a,e`SELECT 1 AS ${e.identifier("hit")} FROM ${e.identifier(W)} WHERE ${e.identifier("ts")} <= ${l} LIMIT 1`)).length===0||await K(s,a,e`
|
|
2
|
+
DELETE FROM ${e.identifier(W)} WHERE ${e.identifier("seq")} IN (
|
|
3
|
+
SELECT ${e.identifier("seq")} FROM (
|
|
4
|
+
SELECT ${e.identifier("seq")} FROM ${e.identifier(W)} WHERE +${e.identifier("ts")} <= ${l} ORDER BY ${e.identifier("seq")} ASC LIMIT ${e.raw(String(Gi))}
|
|
5
|
+
) AS ${e.identifier("expired")}
|
|
6
|
+
)
|
|
7
|
+
`)},on=async(s,a)=>{const f=await b(s,a,e`SELECT MIN(${e.identifier("seq")}) AS ${e.identifier("seq")} FROM ${e.identifier(W)}`),$=Number(f[0]?.seq??Number.NaN);return Number.isFinite($)?$:void 0},zi=async(s,a)=>{if(a.name!=="sqlite")return;const f=await b(s,a,e`SELECT ${e.identifier("seq")} AS ${e.identifier("seq")} FROM ${e.identifier("sqlite_sequence")} WHERE ${e.identifier("name")} = ${W}`),$=Number(f[0]?.seq??Number.NaN);return Number.isFinite($)?$:0},Ji=s=>JSON.stringify(Xt(s)?Qt(s):s),Zi=(s,a,f,$,l)=>e`INSERT INTO ${e.identifier(W)} (${e.identifier("ts")}, ${e.identifier("table")}, ${e.identifier("id")}, ${e.identifier("op")}, ${e.identifier("doc")}) VALUES (${s}, ${a}, ${f}, ${$}, ${l===void 0?null:Ji(l)})`,rn=1e4,eo=1e3,to=(s,a,f)=>{let $=a;for(const[l,_]of s.entries()){const c=Number(_.seq);if(c>$+1&&Number(_.ts)>f)return s.slice(0,l);$=c}return s},Ao=async(s,a,f)=>{const $=a.sinceSeq??0,l=Math.max(1,Math.min(a.limit??1e3,1e4)),_=await on(s,f),c=await zi(s,f);if(c!==void 0&&$>c)throw Bn(c,$,"global");if(_!==void 0&&Wn(_,$))throw Fn(_,$,"global");const q=await b(s,f,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(W)} WHERE seq > ${$} ORDER BY seq ASC LIMIT ${e.raw(String(l))}`),T=(f.name==="sqlite"?q:to(q,$,(a.now??Date.now())-rn)).map(v=>{const{doc:A}=v,N={id:String(v.id),op:String(v.op),seq:Number(v.seq),table:String(v.table),ts:Number(v.ts)};return typeof A=="string"?{...N,doc:_i(A)}:N});return{changes:T,cursor:T.at(-1)?.seq??$}},Ht=(s,a)=>{const f=e.identifier(W),$=e`(SELECT MIN(v.seq) FROM ${f} v WHERE v.seq > ${s} AND v.seq - 1 > ${s} AND v.ts > ${a} AND NOT EXISTS (SELECT 1 FROM ${f} p WHERE p.seq = v.seq - 1))`;return e`${$} AS ${e.identifier("gap")}, (SELECT MAX(q.seq) FROM ${f} q WHERE q.seq > ${s} AND q.seq < ${$}) AS ${e.identifier("below")}`},Kt=(s,a,f)=>{const $=Number(a?.gap??Number.NaN);if(!Number.isFinite($))return s;const l=Number(a?.below??Number.NaN);return Math.min(s,Number.isFinite(l)?l:f)},no=s=>{const a=e.identifier(W),f=e.identifier("table");return e`SELECT ${f}, seq FROM (WITH RECURSIVE "t"("name") AS (SELECT MIN(${f}) FROM ${a} UNION ALL SELECT (SELECT MIN(${f}) FROM ${a} WHERE ${f} > "t"."name") FROM "t" WHERE "t"."name" IS NOT NULL) SELECT "t"."name" AS ${f}, (SELECT MAX(seq) FROM ${a} WHERE ${f} = "t"."name" AND seq > ${s}) AS seq FROM "t" WHERE "t"."name" IS NOT NULL) WHERE seq IS NOT NULL ORDER BY ${f}`},io=async(s,a,f,$={})=>{const l=e.identifier(W),_=f.name!=="sqlite",c=($.now??Date.now())-rn;if($.cursorOnly){const A=e`GREATEST((SELECT MAX(seq) FROM ${l}) - ${e.raw(String(eo))}, ${a})`,N=await b(s,f,e`SELECT MAX(seq) AS seq${_?e`, ${Ht(A,c)}`:e``} FROM ${l}`),D=Number(N[0]?.seq??a);return{cursor:Kt(Number.isFinite(D)?D:a,N[0],a),tables:[]}}const q=await b(s,f,_?e`SELECT ${e.identifier("table")} AS ${e.identifier("table")}, MAX(seq) AS seq, ${Ht(e`${a}`,c)} FROM ${l} WHERE seq > ${a} GROUP BY ${e.identifier("table")}`:no(a));let M=a;const T=[];for(const A of q){const N=Number(A.seq);Number.isFinite(N)&&N>M&&(M=N),T.push(String(A.table))}M=Kt(M,q[0],a);const v=$.retained===!0?await on(s,f):void 0;return{cursor:M,tables:T,...v===void 0?{}:{floor:v}}},oo=/string or blob too big/iu,ro=/row is too big/iu,so=(s,a)=>{const{code:f,errno:$}=a,l=a instanceof Error?a.message:"";switch(s.name){case"mysql":return $===1118||f==="ER_TOO_BIG_ROWSIZE"?"InnoDB's per-row ceiling — roughly 8 KB, half a 16 KB page, for the part of the row stored inline":void 0;case"postgres":return ro.test(l)?"the 8 KB heap page a tuple must fit once its wide columns have been TOASTed out":void 0;default:return oo.test(l)?"the storage engine's per-row ceiling (2 MB on D1)":void 0}},ao=(s,a,f)=>{const $=so(s,a);if($!==void 0)throw new g("PAYLOAD_TOO_LARGE",`document is too large to store in "${f}": a single row cannot exceed ${$}. The limit is on the STORED bytes, which are UTF-8. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},it=16,jt="__lunora_patch_if_match__",Gt=(s,a,f)=>{throw s.isUniqueViolation(a)?new ne(`unique constraint violation on "${f}"`,"unique"):(ao(s,a,f),a)},co=s=>{const{code:a,errno:f}=s??{};return a==="40P01"||a==="40001"||f===1213||a==="ER_LOCK_DEADLOCK"},lo=s=>{throw co(s)?new ne("the write's transaction was rolled back by a lock conflict with a concurrent write; retry it","occ"):s},ot=new WeakMap,Vt=new WeakMap,de="superseded",uo=3e4,ve="__lunora_companion_fence",fo=(s,a,f,$,l)=>{const _=Math.max(1,Math.floor((Ti-2)/$.length)),c=(T,v)=>{const A=s.name==="postgres"?e`CAST(${T} AS ${e.raw(v.type)})`:e`${T}`;return e`${A} AS ${e.identifier(v.name)}`},q=T=>e`SELECT ${e.join(T.map((v,A)=>c(v,$[A])),e`, `)}`,M=[];for(let T=0;T<l.length;T+=_){const v=l.slice(T,T+_).map(A=>q(A));M.push(e`INSERT INTO ${e.identifier(a)} (${fe($.map(A=>A.name))}) SELECT * FROM (${$i(v)}) AS ${e.identifier("__rows__")} WHERE EXISTS (SELECT 1 FROM ${e.identifier(ve)} WHERE ${f})`)}return M},le=(s,a,f)=>JSON.stringify([s,a,f]),We=s=>JSON.stringify(s,(a,f)=>typeof f=="bigint"?`${String(f)}n`:f),wo=s=>{const a=Un(s);return(f,$,l,_)=>$.some(c=>c instanceof pi)?Si(s,f,$,l):a(f,$,l,_)},Co=s=>{const{crossShardCounter:a,crossShardReader:f,maxRelationKeys:$,schema:l}=s,_=Ci(s.exec,s.queryTimeoutMs??Li,s.queryTimer),{dialect:c}=s,q={fieldRef:t=>Fe(c,t),rangeTypeGuard:(t,n)=>gi(c,t,n),...c.name==="mysql"?{containsExpr:(t,n)=>{const i=Mt(t);return i===void 0?e`LOCATE(${n}, ${t}) > 0`:e`LOCATE(${Nt("mysql",n)}, ${i}) > 0`}}:{},...c.name==="postgres"?{containsExpr:(t,n)=>{const i=Mt(t);return i===void 0?e`strpos(${t}, ${n}) > 0`:e`strpos(${i}, ${Nt("postgres",n)}) > 0`}}:{},...c.name==="sqlite"?{}:{inList:wo(c.name)}},M=new WeakMap,T=t=>{const n=M.get(t);if(n!==void 0)return n;const i={...q,serialize:(o,r)=>Bt(c,r,o,d=>ce(t,r,d))};return M.set(t,i),i},v=(t,n)=>at(c.name,t,n),A=t=>{const n=fe(t.columns),i=Te(t.values),o=h=>c.name==="mysql"?e`VALUES(${e.identifier(h)})`:e`excluded.${e.identifier(h)}`,r=h=>c.name==="postgres"?e`${e.identifier(t.table)}.${e.identifier(h)}`:e`${e.identifier(h)}`,d=e.join(Object.entries(t.set(o,r)).map(([h,y])=>e`${e.identifier(h)} = ${y}`),e`, `),u=c.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${d}`:e`ON CONFLICT(${e.identifier(t.conflictKey)}) DO UPDATE SET ${d}`;return e`INSERT INTO ${e.identifier(t.table)} (${n}) VALUES (${i}) ${u}`},N=s.clock??(()=>Date.now()),D=s.idGenerator??(()=>crypto.randomUUID()),j=s.cdc??!1,J=typeof s.cdcRetentionMs=="number"&&Number.isFinite(s.cdcRetentionMs)&&s.cdcRetentionMs>0?s.cdcRetentionMs:void 0,ie=s.auth??{identity:null,userId:null},we=(t,n,i,o)=>j?[Zi(N(),t,n,i,o)]:[],sn=async()=>{if(!j||J===void 0)return;const t=N();if(!(t-Pt<Vi)){Pt=t;try{await Qi(_,c,J,t)}catch{}}},an=s.scheduler??kn;let Ae=0;const he=s.provisionScope??{},F=async()=>{const t=ot.get(he);if(t)return t;const n=(async()=>{const i=s.exec;await vi(i,l,c),await Ii(i,l,c),await Ai(i,l,c),await mn(i,c),await vn(_,l,c),j&&await Yi(i,c)})().catch(i=>{throw ot.delete(he),i});return ot.set(he,n),n},$e=async t=>{if(typeof t!="string"||!Object.hasOwn(l.tables,t))throw new g("BAD_REQUEST",`ctx.db by-id write (table, id): "${t}" is not a table in this schema`);await F();const n=l.tables[t];return n!==void 0&&Di(n)?t:void 0};let Ce=Vt.get(he);Ce===void 0&&(Ce=new Map,Vt.set(he,Ce));const x=Ce;let xe=0;const dt={},Pe=(t,n,i)=>{const o=(async()=>(await F(),await i(()=>x.get(t)?.run!==o)))(),r={definition:n,owner:dt,run:o,settled:!1};return o.then(d=>{d===de&&x.get(t)===r?x.delete(t):r.settled=!0},()=>{x.get(t)===r&&x.delete(t)}).catch(()=>{}),x.set(t,r),o},lt=async(t,n,i)=>{const o=x.get(t);if(o===void 0)return await Pe(t,n,i);const r=o.definition===n;if(r&&(o.settled||o.owner===dt))return await o.run;if(o.settled)return await Pe(t,n,i);let d;const u=new Promise(y=>{d=setTimeout(y,uo,"stalled")}),h=await Promise.race([o.run,u]).finally(()=>{clearTimeout(d)});return h!=="stalled"&&r?h:x.get(t)===o?await Pe(t,n,i):await lt(t,n,i)},He=async(t,n,i)=>{const o=await lt(t,n,i);return o===de?await He(t,n,i):o},ut=async(t,n)=>{const i=x.get(t),o=i?.settled===!0&&i.definition===n?await i.run:void 0;if(typeof o=="boolean")return o;x.delete(t),xe+=1},Z=t=>{const n=l.tables[t];for(const i of n?.aggregateIndexes??[])x.delete(le("aggregate",t,i.name));for(const i of n?.rankIndexes??[])x.delete(le("rank",t,i.name))},cn=async(t,n)=>{const i=ae(t,n);return(await b(_,c,c.tableExists(i))).length>0},ft=async t=>{const{key:n}=c.companionTypes,i=D();await K(_,c,e`CREATE TABLE IF NOT EXISTS ${e.identifier(ve)} (${e.identifier("name")} ${e.raw(n)} PRIMARY KEY, ${e.identifier("token")} ${e.raw(n)} NOT NULL)`),await K(_,c,A({columns:["name","token"],conflictKey:"name",set:r=>({token:r("token")}),table:ve,values:[t,i]}));const o=e`${e.identifier("name")} = ${t} AND ${e.identifier("token")} = ${i}`;return{guardedDelete:()=>e`DELETE FROM ${e.identifier(t)} WHERE EXISTS (SELECT 1 FROM ${e.identifier(ve)} WHERE ${o})`,stillHeld:async()=>(await b(_,c,e`SELECT 1 FROM ${e.identifier(ve)} WHERE ${o}`)).length>0,guardedInsertRows:(r,d)=>fo(c,t,o,r,d)}},dn=async(t,n,i)=>{const o=l.tables[t];if(!o||!await cn(t,n.name))return!1;const r=n.by??[],d=new Map;await Wt(_,c,o,t,R=>{if(n.where&&!Qe(R,n.where))return;const S=te(r,R);bt(d,S,n,R)});const u=ae(t,n.name);if(i())return de;const h=await ft(u);await K(_,c,h.guardedDelete());const{integer:y,key:p,real:E}=c.companionTypes,w=h.guardedInsertRows([{name:"__key__",type:p},{name:"__value__",type:E},{name:"__count__",type:y}],[...d].map(([R,S])=>[R,S.value,S.count]));return i()||await Ft(_,c,w),i()||!await h.stillHeld()?de:!0},Le=(t,n)=>He(le("aggregate",t,n.name),We(n),i=>dn(t,n,i)),ln=async(t,n,i,o,r)=>{const d=new Map;let u,h=!0;for(;h;){const y=u===void 0?o:[...o,e`${e.identifier("id")} > ${u}`],p=y.length>0?e` WHERE ${e.join(y,e` AND `)}`:e``,E=await b(r,c,e`SELECT ${e.identifier("id")}, ${H(i.field??"")} FROM ${e.identifier(n)}${p} ORDER BY ${e.identifier("id")} ASC LIMIT ${e.raw(String(Ze))}`);for(const w of Ot(t,E))bt(d,"",i,w);u=E.at(-1)?.id,h=E.length===Ze}return d.get("")?.value??null},un=async(t,n,i,o)=>{const r=n.field??"",d=[],u=l.tables[t],h=(w,R)=>Bt(c,w,R,S=>u?ce(u,w,S):Je(S));for(const w of n.by??[]){const R=h(w,i[w]??null);d.push(R===null?e`${H(w)} IS NULL`:e`${H(w)} = ${R}`)}for(const[w,R]of Object.entries(n.where??{})){const S=R!==null&&typeof R=="object"&&!Array.isArray(R)?R.eq:R,m=h(w,S),C=Fe(c,w);d.push(m===null?e`${C} IS NULL`:e`${C} = ${m}`)}const y=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``;if(u&&tn(u.shape[r]))return ln(u,t,n,d,o);const p=Re(n.op),E=await b(o,c,e`SELECT ${e.raw(p)}(${H(r)}) AS ${e.identifier("value")} FROM ${e.identifier(t)}${y}`);return ue(E[0]?.value)},fn=(t,n)=>e`DELETE FROM ${e.identifier(t)} WHERE ${e.identifier("__key__")} = ${n} AND ${e.identifier("__count__")} <= 0`,wn=async(t,n,i,o,r)=>{const d=ae(t,n.name),{op:u}=n,h=n.field??"",y=i&&(!n.where||Qe(i,n.where))?i:void 0,p=o&&(!n.where||Qe(o,n.where))?o:void 0;if(!y&&!p)return[];if(u==="count"||u==="sum"||u==="avg"){const m=[],C=new Set,L=[];for(const[I,O]of[[y,-1],[p,1]]){if(!I)continue;const k=u==="count"?1:ze(I[h]);k!==void 0&&L.push({encoded:te(n.by??[],I),numeric:k,sign:O})}L.sort((I,O)=>I.encoded<O.encoded?-1:+(I.encoded>O.encoded));for(const{encoded:I,numeric:O,sign:k}of L)C.add(I),m.push(A({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(P,Q)=>({__count__:e`${Q("__count__")} + ${P("__count__")}`,__value__:u==="count"?e`${Q("__value__")} + ${P("__value__")}`:e`COALESCE(${Q("__value__")}, 0) + ${P("__value__")}`}),table:d,values:[I,k*O,k]}));for(const I of C)m.push(fn(d,I));return m}const E=[],w=[];let R,S;if(y){const m=te(n.by??[],y);R=m;const C=ze(y[h]),I=(await b(r,c,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(d)} WHERE ${e.identifier("__key__")} = ${m}`))[0],O=ue(I?.value),k=(I?.count??0)-1;if(k<=0)E.push(e`DELETE FROM ${e.identifier(d)} WHERE ${e.identifier("__key__")} = ${m}`);else if(I&&C!==void 0&&O!==null&&C===O){const P=await un(t,n,y,r);E.push(e`UPDATE ${e.identifier(d)} SET ${e.identifier("__value__")} = ${P}, ${e.identifier("__count__")} = ${k} WHERE ${e.identifier("__key__")} = ${m}`)}else E.push(e`UPDATE ${e.identifier(d)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${m}`)}if(p){const m=te(n.by??[],p);S=m;const C=ze(p[h]);if(C===void 0)w.push(A({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(L,I)=>({__count__:e`${I("__count__")} + 1`}),table:d,values:[m,null,1]}));else{const L=u==="min"?"MIN":"MAX";w.push(A({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(I,O)=>({__count__:e`${O("__count__")} + 1`,__value__:e`${e.raw(L)}(COALESCE(${O("__value__")}, ${I("__value__")}), ${I("__value__")})`}),table:d,values:[m,C,1]}))}}return R!==void 0&&S!==void 0&&S<R?[...w,...E]:[...E,...w]},be=async t=>{const n=l.tables[t]?.aggregateIndexes;if(!(!n||n.length===0))for(const i of n)await Le(t,i)},_e=async(t,n,i,o)=>{const r=l.tables[t]?.aggregateIndexes,d=[];if(!r||r.length===0)return d;for(const u of r)await ut(le("aggregate",t,u.name),We(u))&&d.push(...await wn(t,u,n,i,o));return d},hn=async(t,n)=>{const i=ye(t,n);return(await b(_,c,c.tableExists(i))).length>0},$n=async(t,n,i)=>{const o=l.tables[t];if(!o||!await hn(t,n.name))return!1;const r=ye(t,n.name);if(i())return de;const d=await ft(r);await K(_,c,d.guardedDelete());const u=c.companionTypes.key,h=[{name:"__id__",type:u},{name:"__partition__",type:u},...n.sortBy.map((E,w)=>{const R=o.shape[E.field];return{name:ge(w),type:c.columnType(R?ct(R):void 0)}})];let y=[];const p=async()=>{const E=y;y=[],!(E.length===0||i())&&await Ft(_,c,d.guardedInsertRows(h,E))};return await Wt(_,c,o,t,async E=>{if(n.where&&!At(E,n.where))return;const w=ke(n.partitionBy??[],E),R=n.sortBy.map(S=>Je(E[S.field]??null));y.push([E._id,w,...R]),y.length>=Ze&&await p()}),await p(),i()||!await d.stillHeld()?de:!0},Ke=(t,n)=>He(le("rank",t,n.name),We(n),i=>$n(t,n,i)),Me=async t=>{const n=l.tables[t]?.rankIndexes;if(!(!n||n.length===0))for(const i of n)await Ke(t,i)},oe=async(t,n,i,o)=>{const r=l.tables[t],d=r?.rankIndexes,u=[];if(!d||d.length===0)return u;const h=r?.softDeleteMode?.field,y=h===void 0||o===void 0?void 0:o[h],p=y!=null;for(const E of d){if(i!==void 0&&o!==void 0&&Wi(E,i,o)||!await ut(le("rank",t,E.name),We(E)))continue;const R=ye(t,E.name);if(i&&u.push(e`DELETE FROM ${e.identifier(R)} WHERE ${e.identifier("__id__")} = ${n}`),o&&!p){if(E.where&&!At(o,E.where))continue;const S=E.sortBy.map((I,O)=>ge(O)),m=fe(["__id__","__partition__",...S]),C=ke(E.partitionBy??[],o),L=E.sortBy.map(I=>Je(o[I.field]??null));u.push(e`INSERT INTO ${e.identifier(R)} (${m}) VALUES (${Te([n,C,...L])})`)}}return u},_n=(t,n,i)=>{const o=et(n);if(o===void 0||!i.dispatched){Z(t);return}o.then(()=>{i.batched||Z(t)},()=>{Z(t)}).catch(()=>{})},re=async(t,n,i,o,r)=>{const d=l.tables[t],u=j||(d?.aggregateIndexes?.length??0)>0||(d?.rankIndexes?.length??0)>0,h=_.transaction===void 0||!u,y=async w=>{let R;try{R=await n(w)}catch(m){if(_.transaction===void 0&&m instanceof bi){Z(t);const C=()=>{Z(t)};et(m)?.then(C,C).catch(()=>{})}throw m}if(!R)return!1;const S={batched:!1,dispatched:!1};try{h&&r.length>0&&await kt(w,c,r);const m=h?await i(w):[...await i(w),...r];m.length>0&&(S.batched=w.batch!==void 0&&c.name==="sqlite",S.dispatched=!0,await kt(w,c,m))}catch(m){throw _.transaction===void 0&&_n(t,m,S),h&&await me(t,o,async()=>{throw await Promise.resolve(),m}),m}return!0};let p;const E=xe;try{p=_.transaction!==void 0&&u?await _.transaction(y).catch(lo):await y(_),p&&xe!==E&&_.transaction!==void 0&&u&&Z(t)}catch(w){const R=et(w);if(R!==void 0){const S=async()=>{await In({dialect:c,exec:_,schema:l},t,o)};R.then(S,S).catch(()=>{})}throw w}return p&&await me(t,o,sn),p},Ee=Tn({dialect:c,exec:_,schema:l}),wt=new Set;for(const[t,n]of Object.entries(l.tables))for(const i of Object.values(n.triggerMap??{}))wt.add(`${t} ${i.timing} ${i.op}`);const Y=(t,n,i)=>wt.has(`${t} ${n} ${i}`);let ht;const X=async(t,n,i)=>{if(Ae+=1,Ae>xt)throw Ae-=1,new ne(`trigger recursion exceeded ${String(xt)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await ei({ctx:ht,event:i,op:n,schema:l,tableName:i.table,timing:t})}finally{Ae-=1}},En=async(t,n,i=_)=>{try{await K(i,c,n)}catch(o){Gt(c,o,t)}},Ne=async(t,n)=>(await b(_,c,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} = ${n}`))[0],$t=async(t,n,i,o,r,d)=>{const u=e`${e.identifier(Se)}`,h=e.join([v(e`${e.identifier("id")}`,o.id),v(u,o[Se]??null),...r===void 0?[]:[e`(${r})`]],e` AND `),y=n==="UPDATE"?e`UPDATE ${e.identifier(t)} SET ${i}, ${u} = ${qt.sql(u)} WHERE ${h}`:e`DELETE FROM ${e.identifier(t)} WHERE ${h}`;try{if(c.supportsReturning)return(await b(d,c,e`${y} RETURNING ${e.identifier("id")}`)).length>0;const p=await K(d,c,y);return(c.affectedRows?c.affectedRows(p??{rowsAffected:0}):0)>0}catch(p){return Gt(c,p,t)}},je=async(t,n,i,o,r)=>{if(o!==void 0&&!await $t(t,n,i,o,void 0,r))throw new ne(`optimistic concurrency conflict on "${t}" — the row changed during this mutation; refetch and retry`,"occ")},Ge=(t,n=t?._creationTime)=>({_creationTime:n,[Se]:qt.value(t?.[Se])}),_t=async(t,n,i,o,r,d,u)=>{const h=z(n,r);if(!h||r===void 0)throw new g("INTERNAL",`document not found: ${i}`);const y=ni(n,o,h),p={...h,...ii(y),_id:i};tt(n,y,p,ie);const E=Ye(n,p,{only:new Set(Object.keys(y)),previous:()=>h,tolerateStoredNull:!0});nt(c.name,Object.fromEntries(Object.keys(y).map(m=>[m,E[m]]))),oi(u,h,E),Y(t,"before","update")&&await X("before","update",{doc:{...E},id:i,op:"update",previous:h,table:t}),await be(t),await Me(t);const w=Object.keys(n.shape),R=e.join(w.map(m=>e`${e.identifier(m)} = ${ce(n,m,E[m]??null)}`),e`, `);if(await re(t,async m=>await $t(t,"UPDATE",R,r,d,m),async m=>[...await _e(t,h,E,m),...await oe(t,i,h,E)],i,we(t,i,"update",E)))return await Ee(t,i,{document:E,previous:h,written:Ge(r)}),Y(t,"after","update")&&await X("after","update",{doc:E,id:i,op:"update",previous:h,table:t}),E},pn=(t,n,i,o)=>{const r=Object.keys(t.shape);return{columns:["id","_creationTime",...r],values:[n,i,...r.map(d=>ce(t,d,o[d]??null))]}},yn=async(t,n,i,o)=>{const r=si(n,i.op,i.field,o.by,o.where);if(!r||!await Le(t,r.index))return;const u=ae(t,r.index.name),h=Object.keys(r.partial);if(h.length===(r.index.by??[]).length&&h.length>0){const p=te(r.index.by??[],r.partial),E=await b(_,c,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(u)} WHERE ${e.identifier("__key__")} = ${p}`);if(E.length===0)return[];const w=E[0];return[{key:{...r.partial},value:Xe(i.op,{count:w.count,value:ue(w.value)})}]}return h.length>0?void 0:(await b(_,c,e`SELECT ${e.identifier("__key__")} AS ${e.identifier("key")}, ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(u)}`)).map(p=>{const E=p;return{key:Ei(JSON.parse(E.key)),value:Xe(i.op,{count:E.count,value:ue(E.value)})}})},Et=t=>{const n=l.tables[t]?.shardMode?.kind;return n==="shardBy"||n==="root"},pt=t=>{throw new g("INTERNAL",`cross-backend relation: a global table cannot load the shard-local relation '${t}' (it spans every shard) — wire a cross-shard reader to support it`)},Rn=(t,n)=>{if(n?.relationMask!==void 0&&n.with!==void 0&&Object.keys(n.with).length>0)throw new g("MASK_UNSUPPORTED",`masking cannot follow a nested \`with\` across the cross-shard relation hop to "${t}" — the nested rows are hydrated on the serving shard, where the mask policy does not exist. Read the nested relation at its own (masked) call site instead.`);const i={};if(n?.relationBaseWhere)for(const o of Object.keys(l.tables)){const r=n.relationBaseWhere(o);r!==void 0&&(i[o]=r)}return{orderBy:n?.orderBy,relationPolicies:i,where:U(n?.baseWhere,n?.where),with:n?.with}},Oe=(t,n)=>Et(t)?f?f(t,Rn(t,n)):pt(t):G.findMany(t,n),qe=(t,n,i)=>ri(t,{fetcher:Oe,maxRelationKeys:$,relationBaseWhere:i,schema:l,tableName:n}),Sn=Mi(async(t,n)=>{const i=await b(_,c,e`SELECT * FROM ${e.identifier(t)} WHERE ${e.identifier("id")} IN (${Te(n)})`),o=new Map;for(const r of i){const{id:d}=r;typeof d=="string"&&o.set(d,r)}return o}),yt=async(t,n,i)=>{const{fetchLimit:o,limit:r,orderKeys:d,predicate:u}=await ai(n,i,{fetcher:Oe,maxRelationKeys:$,schema:l,tableName:t}),h=ee(u,T(n)),y=qi(d,c);let p=e`SELECT * FROM ${e.identifier(t)}`;return h&&(p=e`${p} WHERE ${h}`),p=e`${p} ORDER BY ${y}`,o!==void 0&&(p=e`${p} LIMIT ${e.raw(String(o))}`),{limit:r,orderKeys:d,query:p}},G={relationWrites:Dn(l),async cdcChangedTables(t,n){if(j)try{return await F(),await io(_,t,c,{...n,now:N(),retained:J!==void 0})}catch{return}},async aggregate(t,n){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);if(await F(),Re(n.op),n.op==="count")return G.count(t,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new g("INTERNAL",`aggregate(${t}, { op: "${n.op}" }): "field" is required for non-count reducers`);const o=De(i.softDeleteMode,void 0),r=U(U(n.baseWhere,n.where),o),d=await qe(r,t,n.relationBaseWhere),u=d!==r;if(i.aggregateIndexes&&!n.baseWhere&&!u&&!o){const R=Zn(i.aggregateIndexes,n.op,n.field,n.where);if(R&&await Le(t,R.index)){const m=te(R.index.by??[],R.key),C=ae(t,R.index.name),I=(await b(_,c,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(C)} WHERE ${e.identifier("__key__")} = ${m}`))[0];return Xe(n.op,I===void 0?void 0:{count:I.count,value:ue(I.value)})}}rt(i,n.field,`aggregate(${t}, { op: "${n.op}", field: "${n.field}" })`);const h=ee(d,T(i)),y=e.raw(Re(n.op)),p=e`SELECT ${y}(${H(n.field)}) AS ${e.identifier("value")} FROM ${e.identifier(t)}`,w=(await b(_,c,h?e`${p} WHERE ${h}`:p))[0]?.value;return w==null?null:Number(w)},async count(t,n){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await F();const o=zn(n);if(o.restrictsCounts)throw new gt(t);const r=De(i.softDeleteMode,void 0),d=U(U(o.baseWhere,o.where),r),u=await qe(d,t,o.relationBaseWhere),h=u!==d;if(i.aggregateIndexes&&!o.baseWhere&&!h&&!r){const w=Jn(i.aggregateIndexes,o.where);if(w&&await Le(t,w.index)){const S=te(w.index.by??[],w.key),m=ae(t,w.index.name),C=await b(_,c,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")} FROM ${e.identifier(m)} WHERE ${e.identifier("__key__")} = ${S}`);return Number(C[0]?.value??0)}}const y=ee(u,T(i)),p=e`SELECT COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(t)}`,E=await b(_,c,y?e`${p} WHERE ${y}`:p);return Number(E[0]?.count??0)},async delete(t,n,i){const o=await $e(t);if(!o)return;const r=l.tables[o];if(!r)return;const d=await Ne(o,n);if(d===void 0)return;const u=z(r,d),h=i?.hard===!0,y=!h&&r.softDeleteMode?r.softDeleteMode.field:void 0;if(!(y&&(!u||u[y]!==null&&u[y]!==void 0))){if(Y(o,"before","delete")&&await X("before","delete",{id:n,op:"delete",previous:u??void 0,table:o}),i?.skipOnDelete!==!0&&await Qn({deletedId:n,deletedReference:p=>u?.[p],findHolders:async(p,E,w,R)=>{if(l.tables[p]?.shardMode?.kind==="shardBy")throw new g("INTERNAL",`cross-backend cascade from global '${o}' into shardBy '${p}' is not supported — would require Query Coordinator fan-out across shards`);return(await G.findMany(p,{...R,includeDeleted:h,where:{[E]:w}})).page},onCascade:(p,E)=>G.delete(p,E,i),onRestrict:p=>{throw new ne(p,"restrict")},onSetNull:(p,E,w)=>G.patch(p,E,{[w]:null}),schema:l,tableName:o}),await be(o),await Me(o),y&&u){const p={[y]:N()},E={...u,...p};tt(r,p,E,ie);const w=e.join(Object.keys(r.shape).map(R=>e`${e.identifier(R)} = ${ce(r,R,E[R]??null)}`),e`, `);await re(o,async R=>(await je(o,"UPDATE",w,d,R),!0),async R=>[...await _e(o,u,E,R),...await oe(o,n,u,void 0)],n,we(o,n,"update",E)),await Ee(o,n,{document:E,previous:u,written:Ge(d)}),Y(o,"after","delete")&&await X("after","delete",{id:n,op:"delete",previous:u,table:o});return}await re(o,async p=>(await je(o,"DELETE",void 0,d,p),!0),async p=>[...await _e(o,u??void 0,void 0,p),...await oe(o,n,u??void 0,void 0)],n,we(o,n,"delete")),await me(o,n,async()=>{await Ee(o,n,void 0),Y(o,"after","delete")&&await X("after","delete",{id:n,op:"delete",previous:u??void 0,table:o})})}},async findFirst(t,n={}){return(await G.findMany(t,{...n,limit:1})).page[0]??null},async findFirstOrThrow(t,n={}){const i=await G.findFirst(t,n);if(i===null)throw new Xn(`findFirstOrThrow: no "${t}" document matched`);return i},async findMany(t,n={}){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await F();const o=async(R,S,m,C)=>{if(Et(R))return a?ci(a,R,S,m,C):pt(R);const L=l.tables[R];if(!L)throw new g("INTERNAL",`unknown table: ${R}`);const I=De(L.softDeleteMode,void 0),O={[S]:{in:m}},k=U(U(O,C),I),P=await qe(k,R,void 0),Q=ee(P,T(L)),pe=H(S);let V=e`SELECT ${pe} AS __fk__, COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(R)}`;Q&&(V=e`${V} WHERE ${Q}`),V=e`${V} GROUP BY ${pe}`;const B=await b(_,c,V),se=new Map;for(const Rt of B)se.set(Rt.__fk__,Number(Rt.count??0));return se},{limit:r,orderKeys:d,query:u}=await yt(t,i,n),h=await b(_,c,u),y=Ot(i,h);if(r===void 0)return n.with&&await Tt({fetcher:Oe,groupedCounter:o,parents:y,...vt(n),schema:l,tableName:t,with:n.with}),{continueCursor:null,isDone:!0,page:It(y,n.select,n.with)};const p=y.length>r,E=p?y.slice(0,r):y,w=E.at(-1);return n.with&&await Tt({fetcher:Oe,groupedCounter:o,parents:E,...vt(n),schema:l,tableName:t,with:n.with}),{continueCursor:p&&w?Yn(w,d):null,isDone:!p,page:It(E,n.select,n.with)}},async explain(t,n={}){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await F();const{query:o}=await yt(t,i,n),r=c.name==="sqlite"?"EXPLAIN QUERY PLAN":"EXPLAIN",d=await b(_,c,e`${e.raw(r)} ${o}`),{params:u,sql:h}=c.render(o);return{params:u,plan:d.map(y=>ki(y)),sql:h}},async get(t,n){const i=Object.hasOwn(l.tables,t)?l.tables[t]:void 0;if(!i)throw new g("BAD_REQUEST",`ctx.db.get(table, id): "${t}" is not a table in this schema`);return i.shardMode!==void 0&&i.shardMode.kind!=="global"?null:(await F(),z(i,await Sn.load(t,n)))},async groupBy(t,n){const i=l.tables[t];if(!i)throw new g("INTERNAL",`unknown table: ${t}`);await F();const o=n.agg??{op:"count"};if(Re(o.op),o.op!=="count"&&!o.field)throw new g("INTERNAL",`groupBy(${t}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);const r=De(i.softDeleteMode,void 0),d=U(U(n.baseWhere,n.where),r),u=await qe(d,t,n.relationBaseWhere),h=u!==d;if(i.aggregateIndexes&&!n.baseWhere&&!h&&!r){const S=await yn(t,i.aggregateIndexes,o,n);if(S!==void 0)return S}Ki(i,t,n.by,o);const y=ee(u,T(i)),p=n.by.map(S=>e`${H(S)} AS ${e.identifier(S)}`);if(o.op==="count")p.push(e`COUNT(*) AS ${e.identifier("value")}`);else{if(!o.field)throw new g("INTERNAL",`groupBy(${t}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);p.push(e`${e.raw(Re(o.op))}(${H(o.field)}) AS ${e.identifier("value")}`)}const E=e.join(n.by.map(S=>H(S)),e`, `);let w=e`SELECT ${e.join(p,e`, `)} FROM ${e.identifier(t)}`;y&&(w=e`${w} WHERE ${y}`),w=e`${w} GROUP BY ${E}`;const R=await b(_,c,w);return Bi(i,n.by,R)},async insert(t,n,i){const o=l.tables[t];if(!o)throw new g("INTERNAL",`unknown table: ${t}`);await F();const r=Ye(o,jn(o,n,ie),{supplied:n,trusted:i?.allowExplicitId===!0});nt(c.name,r);let d;i?.clientId!==void 0?(Gn(i.clientId),d=i.clientId):i?.allowExplicitId&&typeof r._id=="string"?(Vn(r._id),d=r._id):d=D();const u=i?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:N(),h={...r,_creationTime:u,_id:d};Y(t,"before","insert")&&await X("before","insert",{doc:{...h},id:d,op:"insert",table:t}),await be(t),await Me(t);const{columns:y,values:p}=pn(o,d,u,r);return await re(t,async E=>(await En(t,e`INSERT INTO ${e.identifier(t)} (${fe(y)}) VALUES (${Te(p)})`,E),!0),async E=>[...await _e(t,void 0,h,E),...await oe(t,d,void 0,h)],d,we(t,d,"insert",h)),await me(t,d,async()=>{await Ee(t,d,{document:h,written:{_creationTime:u,[Se]:null}}),Y(t,"after","insert")&&await X("after","insert",{doc:h,id:d,op:"insert",table:t})}),d},normalizeId(t,n){return Kn(l,t,n)},async patch(t,n,i,o){Ve("patch",i);const r=await $e(t);if(!r)throw new g("INTERNAL",`document not found: ${n}`);const d=l.tables[r];if(!d)throw new g("INTERNAL",`document not found: ${n}`);const u=Hn(d,i)?it:1;for(let h=0;h<u;h+=1){const y=await Ne(r,n);if(await _t(r,d,n,i,y,void 0,o))return}throw new ne(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},async patchIf(t,n,i){Ve("patchIf",i.patch);const o=await $e(t),r=o===void 0?void 0:l.tables[o];if(o===void 0||!r)return{applied:!1,doc:null};const d=o,u=ee(i.where,T(r))??e`1 = 1`;for(let h=0;h<it;h+=1){const[y]=await b(_,c,e`SELECT *, CASE WHEN (${u}) THEN 1 ELSE 0 END AS ${e.identifier(jt)} FROM ${e.identifier(d)} WHERE ${e.identifier("id")} = ${n}`);if(y===void 0)return{applied:!1,doc:null};const{[jt]:p,...E}=y;if(Number(p)!==1)return{applied:!1,doc:z(r,E)??null};const w=await _t(d,r,n,i.patch,E,u,{verify:i.verify});if(w)return{applied:!0,doc:w}}throw new ne(`patchIf on "${d}" lost the row to concurrent writes ${String(it)} times in a row; retry the operation`,"occ")},async restore(t,n){const i=await $e(t),o=i===void 0?void 0:await Ne(i,n);if(!i||o===void 0)throw new g("INTERNAL",`document not found: ${n}`);const r=l.tables[i],d=r?.softDeleteMode?.field;if(!r||!d)throw new g("INTERNAL",`ctx.db.restore: table "${i}" is not a .softDelete() table`);const u=o[d]!==null&&o[d]!==void 0;if(await G.patch(t,n,{[d]:null}),u){const h=z(r,o);h!==null&&await re(i,async()=>await Promise.resolve(!0),async()=>await oe(i,n,void 0,{...h,[d]:null}),n,[]).catch(y=>{throw _.transaction!==void 0&&Z(i),y})}},query(t){const n=l.tables[t];if(!n)throw new g("INTERNAL",`unknown table: ${t}`);const i="the legacy query()/withIndex() reader is not available on the D1 (global) backend; use findMany",o=[];let r=0,d;const u=c.name!=="mysql",h={...T(n),fieldRef:w=>e`m.${H(w)}`,rangeTypeGuard:()=>{throw new g("INTERNAL","a path range is never pushed into a search")}},y=w=>o.every(R=>R(w)),p=async(w,R)=>{await F();const S=2*bn+w.filters.length,m=d===void 0?void 0:ee(d,h,void 0,S),C=m!==void 0&&c.name==="sqlite"&&c.render(m).params.length+S>hi.boundParams,L=C?void 0:m,I=r>0||C,O=await Mn(_,c,n,t,L===void 0?w:{...w,scope:L},Nn(I?void 0:R));!I&&R===void 0&&On(O);const k=O.filter(P=>y(P));return R===void 0?k:k.slice(0,R)},E=w=>{const R={async*[Symbol.asyncIterator](){if(!w)throw new g("INTERNAL",i);yield*await p(w,void 0)},async collect(){if(!w)throw new g("INTERNAL",i);return p(w,void 0)},async collectWithScores(){throw new g("GLOBAL_SEARCH_SCORES_UNSUPPORTED",`collectWithScores() is not supported on \`.global()\` tables (table "${t}") — relevance scores are not yet surfaced on this backend; use .collect() instead`)},filter(S){o.push(S);const m=di(S);return m!==void 0&&li(m,n.shape,u)?d=U(d,m):r+=1,R},async first(){if(!w)throw new g("INTERNAL",i);return(await p(w,1))[0]??null},order(){return R},async paginate(S){if(!w)throw new g("INTERNAL",i);const m=Cn(S);return Ln(await p(w,qn(m)),m)},async take(S){if(!w)throw new g("INTERNAL",i);return p(w,S)},async unique(){if(!w)throw new g("INTERNAL",i);const S=await p(w,2);if(S.length>1)throw new wi(`unique() on table "${t}" matched ${String(S.length)} documents; expected at most one`);return S[0]??null},withGeoIndex(){throw new g("INTERNAL",`geo indexes are not supported on \`.global()\` tables (table "${t}") — geospatial queries run only on sharded tables`)},withIndex(){throw new g("INTERNAL",i)},withSearchIndex(S,m){const C=(n.searchIndexes??[]).find(I=>I.name===S);if(!C)throw new g("INTERNAL",`unknown search index "${S}" on table "${t}"`);const L={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:S,query:""};if(m(An(L,t,gn(C.language))),!L.hasQuery)throw new g("INTERNAL",`search index "${S}" on table "${t}" requires a .search(field, query) call`);return E(L)}};return R};return E(void 0)},async rank(t,n,i){const o=l.tables[t];if(!o)throw new g("INTERNAL",`unknown table: ${t}`);const r=o.rankIndexes?.find(O=>O.name===n);if(!r)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(i.restrictsCounts)throw new gt(t);if(await F(),!await Ke(t,r))return null;const u=typeof i.row=="string"?i.row:i.row._id;if(!u)return null;const h=ye(t,r.name),y=r.sortBy.map((O,k)=>ge(k)),p=fe(["__partition__",...y]),w=(await b(_,c,e`SELECT ${p} FROM ${e.identifier(h)} WHERE ${e.identifier("__id__")} = ${u}`))[0];if(!w)return null;const R=w.__partition__,S=U(i.baseWhere,i.where);St(S,l,t,"rank");const m=mt(r,S);if(m&&ke(r.partitionBy??[],m)!==R)return null;const C=Fi(c.name,r,y,w,u),L=await b(_,c,e`SELECT COUNT(*) AS c FROM ${e.identifier(h)} WHERE ${e.identifier("__partition__")} = ${R} AND (${C})`),I=await b(_,c,e`SELECT COUNT(*) AS c FROM ${e.identifier(h)} WHERE ${e.identifier("__partition__")} = ${R}`);return{position:Number(L[0]?.c??0)+1,total:Number(I[0]?.c??0)}},async rankPage(t,n,i={}){St(U(i.baseWhere,i.where),l,t,"rankPage");const o=l.tables[t];if(!o)throw new g("INTERNAL",`unknown table: ${t}`);const r=o.rankIndexes?.find(B=>B.name===n);if(!r)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${t}"`);if(await F(),!await Ke(t,r))return{continueCursor:null,isDone:!0,page:[]};const u=ye(t,r.name),h=r.sortBy.map((B,se)=>ge(se)),y=Math.max(1,Math.min(1e3,Math.floor(i.take??100))),p=U(i.baseWhere,i.where),E=mt(r,p),w=xi(r,h),R=e.join(w.flatMap(B=>Zt(c,{direction:B.direction,field:B.column,nullable:B.nullable})),e`, `),S=[];typeof i.partitionKey=="string"?S.push(e`${e.identifier("__partition__")} = ${i.partitionKey}`):E&&S.push(e`${e.identifier("__partition__")} = ${ke(r.partitionBy??[],E)}`);const m=Pn(i);if(m!==void 0){const B=Ui(c.name,w,m);B!==void 0&&S.push(B)}const C=fe([Ie,"__partition__",...h]);let L=e`SELECT ${C} FROM ${e.identifier(u)}`;S.length>0&&(L=e`${L} WHERE ${e.join(S,e` AND `)}`),L=e`${L} ORDER BY ${R} LIMIT ${e.raw(String(y+1))}`;const I=await b(_,c,L),O=I.length>y,k=O?I.slice(0,y):I,P=k.map(B=>B[Ie]),Q=await Pi(_,c,o,t,P);let pe=null;const V=k.at(-1);if(O&&V!==void 0){const B=[V.__partition__,...h.map(se=>V[se]),V[Ie]];pe=Hi(B)}return{continueCursor:pe,isDone:!O,page:Q}},async replace(t,n,i,o){Ve("replace",i);const r=await $e(t);if(!r)throw new g("INTERNAL",`document not found: ${n}`);const d=l.tables[r];if(!d)throw new g("INTERNAL",`document not found: ${n}`);const u=await Ne(r,n);if(u===void 0)throw new g("INTERNAL",`document not found: ${n}`);const y=xn(l,r,"update")||(d.aggregateIndexes??[]).length>0||(d.rankIndexes??[]).length>0?z(d,u)??void 0:void 0,p=o?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,E=typeof u._creationTime=="number"?u._creationTime:void 0,w=p??E??N(),R={...i,_creationTime:w,_id:n};tt(d,i,R,ie);const S=Ye(d,R,{previous:()=>y??z(d,u)??void 0,supplied:i,trusted:o?.allowExplicitId===!0});nt(c.name,S),Y(r,"before","update")&&await X("before","update",{doc:{...S},id:n,op:"update",previous:y,table:r}),await be(r),await Me(r);const m=Object.keys(d.shape),C=e.join([e`${e.identifier("_creationTime")} = ${w}`,...m.map(L=>e`${e.identifier(L)} = ${ce(d,L,S[L]??null)}`)],e`, `);await re(r,async L=>(await je(r,"UPDATE",C,u,L),!0),async L=>[...await _e(r,y,S,L),...await oe(r,n,y,S)],n,we(r,n,"update",S)),await me(r,n,async()=>{await Ee(r,n,{document:S,previous:y,written:Ge(u,w)}),Y(r,"after","update")&&await X("after","update",{doc:S,id:n,op:"update",previous:y,table:r})})}};return ht={db:G,scheduler:an},G};export{Co as createSqlCtxDb,Mo as decodeGlobalRow,io as readSqlCdcChangedTables,Ao as readSqlCdcChanges,on as readSqlCdcFloor,Yi as runSqlCdcMigration,Qi as sweepSqlCdcRetention};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";import{q as U,c as qt,m as Ft,r as C,a as Ut,l as q,w as F,b as kt}from"./ctx-db-search-state-BFQG9D20.mjs";import{ftsUnmappedPage as bt,groupUnmappedRows as Ht,ftsWriteDocument as mt,ftsPurgeDocument as ht,ftsCompanionDdl as Pt,unionAll as Bt,ftsRowidMapName as Wt}from"@lunora/shard-engine";import{sql as r}from"drizzle-orm";import{abandonedWork as jt}from"./DEFAULT_QUERY_TIMEOUT_MS-D7YkDNaV.mjs";import{O as xt,q as h,n as Kt,h as X,a as N,i as L,e as J,f as v,c as y,k as pt,j as ot,l as Gt,r as Yt,x as Qt}from"./sql-exec-ChIYvWnI.mjs";const Vt=n=>{const t=atob(n),e=Uint8Array.from(t,i=>i.codePointAt(0)??0);return new TextDecoder().decode(e)},Xt=()=>new p("BAD_REQUEST","invalid cursor"),st=16,at=8,T=1024,k=(n,t)=>t.query(n),Jt=(n,t)=>{if(!t)return{exact:!0,lower:n,upper:n};const e=[...n].at(-1)??"",i=(e.codePointAt(0)??0)+1;if(i>=55296&&i<=57343||i>1114111)return{exact:!0,lower:n,upper:n};const o=n.slice(0,n.length-e.length);return{exact:!1,lower:n,upper:o+String.fromCodePoint(i)}},Dn=(n,t,e)=>{const i={eq:(o,s)=>{if(!n.definition.filterFields?.includes(o))throw new p("INTERNAL",`field "${o}" is not a filter field of search index "${n.indexName}" on table "${t}"`);if(n.filters.length>=at)throw new p("BAD_REQUEST",`search index "${n.indexName}" on table "${t}": at most ${String(at)} .eq() filters are supported per search query`);return n.filters.push({field:o,value:s}),i},search:(o,s)=>{const a=n;if(o!==a.definition.field)throw new p("INTERNAL",`search index "${a.indexName}" on table "${t}" indexes "${a.definition.field}", not "${o}"`);const f=k(s,e).length;if(f>st)throw new p("BAD_REQUEST",`search index "${a.indexName}" on table "${t}": at most ${String(st)} search terms are supported (got ${String(f)})`);return a.field=o,a.query=s,a.hasQuery=!0,i}};return i},qn=n=>{if(n.length>T)throw new p("BAD_REQUEST",`more than ${String(T)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Fn=n=>Math.min(n.offset+n.numItems+1,T),zt=n=>btoa(`search:${String(n)}`),Zt=n=>{let t;try{t=Vt(n)}catch{return}if(!t.startsWith("search:"))return;const e=Number(t.slice(7));return Number.isInteger(e)&&e>=0?e:void 0},Un=n=>{if(typeof n.endCursor=="string")throw new p("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 p("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const t=Math.max(0,Math.floor(n.numItems)),e=n.cursor?Zt(n.cursor):0;if(e===void 0)throw Xt();if(e+t>=T)throw new p("BAD_REQUEST",`search pagination reaches the ${String(T)}-document limit (offset ${String(e)} + ${String(t)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,T-e-1))} or fewer, or narrow the query or the filters instead`);return{numItems:t,offset:e}},kn=(n,t)=>{const e=t.offset+t.numItems,i=t.numItems>0&&n.length>e;return{continueCursor:i?zt(e):null,isDone:!i,page:n.slice(t.offset,e)}},bn=n=>{if(n===void 0)return T+1;if(!Number.isFinite(n))return T;const t=Math.max(0,Math.floor(n));if(t>T)throw new p("BAD_REQUEST",`search returns at most ${String(T)} documents (asked for ${String(t)}) — narrow the query or paginate instead`);return t},tn=(n,t)=>{if(!t.includes("."))return n[t];let e=n;for(const i of t.split(".")){if(e===null||typeof e!="object"||Array.isArray(e))return;e=e[i]}return e},b=(n,t)=>`${n}__fts_${t}`,l="__id__",g="__token__",O="__n__",nn=1e3,en=(n,t)=>t.document(n),G=(n,t)=>tn(n,t),rn=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",on=(n,t,e)=>n!==void 0&&t!==void 0&&G(n,e.field)===G(t,e.field),gt=(n,t)=>en(rn(G(n,t.field)),U(t.language)).slice(0,nn),z=(n,t)=>gt(n,t).join(" "),yt=(n,t)=>{const e=new Map;for(const i of gt(n,t))e.set(i,(e.get(i)??0)+1);return e},Tt=[xt,"_creationTime"],ft=50,d=(n,t)=>r`${r.identifier(n)}.${r.identifier(t)}`,M=(n,t,e)=>r`DELETE FROM ${r.identifier(n)} WHERE ${d(n,l)} = ${t}${e===void 0?r``:r` AND ${e}`}`,Rt=(n,{row:t,table:e})=>{const i=Tt.map(o=>r` AND ${Kt(n.name,d(e,o),t[o]??null)}`);return r`SELECT 1 FROM ${r.identifier(e)} WHERE ${d(e,"id")} = ${t.id}${r.join(i)}${n.name==="postgres"?r` FOR SHARE`:r``}`},D=(n,t)=>r`EXISTS (${Rt(n,t)})`,H=(n,t)=>r`NOT EXISTS (SELECT 1 FROM ${r.identifier(n)} WHERE ${d(n,"id")} = ${t})`,_t=(n,t,e,i)=>i===void 0?H(t,e):D(n,{row:i,table:t}),P=async(n,t,e,i)=>{const o=new Map;for(let s=0;s<i.length;s+=ft){const a=i.slice(s,s+ft),f=await h(n,t,r`SELECT * FROM ${r.identifier(e)} WHERE ${d(e,"id")} IN (${r.join(a.map(c=>r`${c}`),r`, `)})`);for(const c of f)o.set(String(c.id),c)}return o},Y=(n,t,e)=>n.name==="mysql"?r`${r.identifier(t)}(${r.raw(String(e))})`:n.textPatternOperatorClass===void 0?r`${r.identifier(t)}`:r`${r.identifier(t)} ${r.raw(n.textPatternOperatorClass)}`,Z=512,tt=(n,t)=>({columns:r`${Y(n,g,256)}, ${Y(n,l,Z)}`,concurrently:!0,name:`${t}__unique`,table:t,unique:!0}),x=n=>r`${n} COLLATE utf8mb4_0900_bin`,K=(n,t)=>{const e=JSON.stringify(t.map(([i,o])=>({o,t:i})));switch(n.name){case"mysql":return r`JSON_TABLE(${e}, '$[*]' COLUMNS (${r.identifier("t")} VARCHAR(256) PATH '$.t', ${r.identifier("o")} INT PATH '$.o')) AS ${r.identifier("j")}`;case"postgres":return r`json_to_recordset(${e}::text::json) AS ${r.identifier("j")}(${r.identifier("t")} text, ${r.identifier("o")} integer)`;default:return r`(SELECT json_extract(${d("e","value")}, '$.t') AS ${r.identifier("t")}, json_extract(${d("e","value")}, '$.o') AS ${r.identifier("o")} FROM json_each(${e}) AS ${r.identifier("e")}) AS ${r.identifier("j")}`}},At=(n,t,e,i,o)=>{const s=r.join([g,l,O].map(f=>r.identifier(f)),r`, `),a=f=>r`INSERT INTO ${r.identifier(t)} (${s}) SELECT ${d("j","t")}, ${e}, ${d("j","o")} FROM ${K(n,i)} WHERE ${f}`;switch(n.name){case"mysql":{const f=D(n,o),c=d(t,g),w=r.identifier("held");return[r`${a(r`${f} AND NOT EXISTS (SELECT 1 FROM ${r.identifier(t)} AS ${w} WHERE ${d("held",l)} = ${e} AND ${d("held",g)} = ${x(d("j","t"))})`)} ON DUPLICATE KEY UPDATE ${d(t,O)} = ${d(t,O)}`,r`UPDATE ${r.identifier(t)} JOIN ${K(n,i)} ON ${c} = ${x(d("j","t"))} SET ${d(t,O)} = ${d("j","o")} WHERE ${d(t,l)} = ${e} AND ${f}`,r`DELETE FROM ${r.identifier(t)} WHERE ${d(t,l)} = ${e} AND ${f} AND ${c} NOT IN (SELECT ${x(d("j","t"))} FROM ${K(n,i)})`]}case"postgres":{const f=r.identifier("__source__"),c=r.identifier("__purged__"),w=r`EXISTS (SELECT 1 FROM ${f})`;return[r`WITH ${f} AS (${Rt(n,o)}), ${c} AS (${M(t,e,w)} RETURNING 1) ${a(r`${w} AND (SELECT COUNT(*) FROM ${c}) >= 0`)} ON CONFLICT DO NOTHING`]}default:{const f=D(n,o);return[M(t,e,f),r`${a(f)} ON CONFLICT DO NOTHING`]}}},Ot={uniqueKeyMissing:!1,unmappedSkipped:0},ct=new Set,ut=(n,t)=>{ct.has(n)||(ct.add(n),console.warn(`[@lunora/sql-store] ${t}`))},dt=100,$t=3,Q=async(n,t,e,i=0)=>{const{companion:o,definition:s,index:a,tableName:f}=e,c={done:!0,last:i,left:0};if((await h(n,t,t.tableExists(f))).length===0)return c;const u=await h(n,t,bt(o,dt,i));if(u.length===0)return c;const S=Math.max(...u.map(A=>Number(A.rowid))),E=Ht(u),m=await P(n,t,f,[...E.keys()]),$=[];for(const[A,et]of E){const j=m.get(A),rt=j===void 0?void 0:X(s,j),it=_t(t,f,A,j);$.push(...rt?mt(o,A,z(rt,a),{guard:it,unmappedRowids:et}):ht(o,A,{guard:it,unmappedRowids:et}))}await N(n,t,$);const _=await h(n,t,r`SELECT COUNT(*) AS ${r.identifier("n")} FROM ${r.identifier(o)} WHERE ${d(o,"rowid")} > ${Math.max(0,i)} AND ${d(o,"rowid")} <= ${S}`);return{done:u.length<dt,last:S,left:Number(_[0]?.n??0)}},sn=async(n,t,e)=>{let i=0,o=0;for(;;){let s=await Q(n,t,e,i);for(let a=1;s.left>0&&a<$t;a+=1)s=await Q(n,t,e,i);if(s.left>0&&(o+=s.left,console.warn(`[@lunora/sql-store] search migration of "${e.companion}": ${String(s.left)} row(s) lost every one of ${String($t)} attempts to a concurrent write and were left for a later pass.`)),s.done)return o;i=s.last}},an=async(n,t,e,i)=>i==="step"?(await Q(n,t,e),Ot):{uniqueKeyMissing:!1,unmappedSkipped:await sn(n,t,e)},V=n=>`${n}__btree`,fn=async(n,t,e)=>{const i=tt(t,e),o=await L(n,t,e,i.name);if(o!=="valid"){if(o==="absent"&&(await h(n,t,r`SELECT 1 AS ${r.identifier("present")} FROM ${r.identifier(e)} LIMIT 1`)).length===0)try{await J(n,t,{...i,concurrently:!1}),await v(n,t,e,V(e));return}catch(a){if(await L(n,t,e,i.name).catch(()=>{})==="valid")return;ut(`${e}:empty`,`search companion "${e}": adding its unique key failed (${String(a)}); run backfillSqlSearchIndexes.`);return}ut(`${e}:missing`,`search companion "${e}" has no usable unique key, so two backfills racing over one row can index it twice. Run backfillSqlSearchIndexes, which adds it.`)}},cn=async(n,t,e)=>{const i=d(e,l),o=d(e,g);return(await h(n,t,r`SELECT ${i} AS ${r.identifier("id")}, ${o} AS ${r.identifier("token")}, COUNT(*) AS ${r.identifier("n")} FROM ${r.identifier(e)} GROUP BY ${i}, ${o} HAVING COUNT(*) > 1`)).map(a=>({count:Number(a.n),id:String(a.id),token:String(a.token)}))},un=(n,t,{count:e,id:i,token:o})=>{const s=r`${d(t,l)} = ${i} AND ${d(t,g)} = ${o}`;switch(n.name){case"mysql":return r`DELETE FROM ${r.identifier(t)} WHERE ${s} LIMIT ${r.raw(String(e-1))}`;case"postgres":return r`DELETE FROM ${r.identifier(t)} WHERE ctid = ANY (ARRAY(SELECT ctid FROM ${r.identifier(t)} WHERE ${s} OFFSET 1))`;default:return r`DELETE FROM ${r.identifier(t)} WHERE rowid IN (SELECT rowid FROM ${r.identifier(t)} WHERE ${s} LIMIT -1 OFFSET 1)`}},dn=async(n,t,e,i)=>{const{companion:o,definition:s,index:a,tableName:f}=e;for(const u of i)await y(n,t,un(t,o,u));const c=[...new Set(i.map(u=>u.id))],w=await P(n,t,f,c);for(const u of c){const S=w.get(u),E=S===void 0?void 0:X(s,S);if(S!==void 0&&E){const m=[...yt(E,a)];await N(n,t,At(t,o,u,m,{row:S,table:f}));continue}await y(n,t,M(o,u,_t(t,f,u,S)))}},$n=async(n,t,e)=>t.name!=="mysql"?"":(await h(n,t,r`SELECT COLUMN_NAME AS ${r.identifier("name")}, COLLATION_NAME AS ${r.identifier("collation")} FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ${e} AND COLUMN_NAME IN (${g}, ${l})`)).filter(o=>!String(o.collation).endsWith("_bin")).map(o=>` Its ${String(o.name)} column uses ${String(o.collation)}, which treats values differing only in case or accents as one; convert it with ALTER TABLE \`${e}\` MODIFY \`${String(o.name)}\` VARCHAR(768) COLLATE utf8mb4_0900_bin NOT NULL.`).join(""),wn=async(n,t,e)=>{if(t.name!=="mysql")return 0;const i=d(e,l),o=await h(n,t,r`SELECT COUNT(*) AS ${r.identifier("n")} FROM (SELECT 1 AS ${r.identifier("x")} FROM ${r.identifier(e)} GROUP BY LEFT(${i}, ${r.raw(String(Z))}), ${d(e,g)} HAVING COUNT(DISTINCT ${i}) > 1) AS ${r.identifier("shared")}`);return Number(o[0]?.n??0)},Sn=async(n,t,e)=>{const i=tt(t,e),o=await L(n,t,e,i.name);if(o==="valid")return"valid";o==="invalid"&&await v(n,t,e,i.name);try{return await J(n,t,i),"built"}catch(s){const a=await L(n,t,e,i.name);if(a==="valid")return"valid";if(a==="invalid"&&await v(n,t,e,i.name),!t.isUniqueViolation(s))throw s;return"refused"}},wt=3,ln=async(n,t,e)=>{const{companion:i}=e,o=await $n(n,t,i);let s="";o!==""&&console.warn(`[@lunora/sql-store] search companion "${i}" folds case and accents in its unique key.${o}`);for(let a=0;a<wt;a+=1){const f=await Sn(n,t,i);if(f==="valid")return await v(n,t,i,V(i)),!0;if(f==="refused"){const c=await cn(n,t,i);if(c.length>0)await dn(n,t,e,c);else{const w=await wn(n,t,i);s=w>0?` ${String(w)} token(s) are held by document ids that agree on their first ${String(Z)} characters, which the key cannot tell apart; shorten those ids.`:o}}}return await L(n,t,i,tt(t,i).name)==="valid"?(await v(n,t,i,V(i)),!0):(console.warn(`[@lunora/sql-store] search companion "${i}" still has no unique key after ${String(wt)} attempts: writes keep working, but two backfills racing over one row can index it twice.${s}`),!1)},En=async(n,t,e,i)=>i==="step"?Ot:{uniqueKeyMissing:!await ln(n,t,e),unmappedSkipped:0},mn=(n,t)=>t?r`${r.identifier(g)} LIKE ${`${n}%`}`:r`${r.identifier(g)} = ${n}`,Nt=(n,t)=>{const e=t.filters.map(i=>r`m.${ot(i.field)} = ${Gt(i.value)}`);return n.softDeleteMode&&e.push(r`m.${ot(n.softDeleteMode.field)} IS NULL`),t.scope!==void 0&&e.push(r`(${t.scope})`),e},It=async(n,t,e,i,o,s,a)=>{const f=Nt(e,o);let c=r`SELECT m.* FROM (${a}) s JOIN ${r.identifier(i)} m ON m.${r.identifier("id")} = s.${r.identifier(l)}`;return f.length>0&&(c=r`${c} WHERE ${r.join(f,r` AND `)}`),c=r`${c} ORDER BY s.${r.identifier("__score__")} DESC, m.${r.identifier("_creationTime")} DESC, m.${r.identifier("id")} ASC LIMIT ${r.raw(String(s))}`,pt(e,await h(n,t,c))},hn=async(n,t,e,i,o,s)=>{const a=k(o.query,U(o.definition.language));if(a.length===0)return[];const f=b(i,o.indexName),c=a.length-1,w=a.map(($,_)=>mn($,_===c)),u=r.join(w,r` OR `),S=w.map($=>r`SUM(CASE WHEN ${$} THEN ${r.identifier(O)} ELSE 0 END)`),E=r.join(S.map($=>r`${$} > 0`),r` AND `),m=r`SELECT ${r.identifier(l)}, ${r.join(S,r` + `)} AS ${r.identifier("__score__")} FROM ${r.identifier(f)} WHERE ${u} GROUP BY ${r.identifier(l)} HAVING ${E}`;return It(n,t,e,i,o,s,m)},pn=async(n,t,e,i,o,s)=>{const a=k(o.query,U(o.definition.language));if(a.length===0)return[];const f=b(i,o.indexName),c=`${f}__vocab`,w=a.length-1,u=a.map((m,$)=>{const _=Jt(m,$===w),A=_.exact?r`${r.identifier("term")} = ${_.lower}`:r`${r.identifier("term")} >= ${_.lower} AND ${r.identifier("term")} < ${_.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String($))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(c)} WHERE ${A} GROUP BY ${r.identifier("doc")}`}),S=a.map((m,$)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String($))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),E=r`SELECT f.${r.identifier(l)} AS ${r.identifier(l)}, ${r.join(S,r` + `)} AS ${r.identifier("__score__")} FROM (${Bt(u)}) u JOIN ${r.identifier(f)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(l)} HAVING ${r.join(S.map(m=>r`${m} > 0`),r` AND `)}`;return It(n,t,e,i,o,s,E)},gn=async(n,t,e,i,o,s)=>{const a=t.nativeTextSearch,f=k(o.query,U(o.definition.language));if(!a||f.length===0)return[];const c=b(i,o.indexName),w=[a.matches(c,f),...Nt(e,o)],u=r`SELECT m.* FROM ${r.identifier(c)} JOIN ${r.identifier(i)} m ON m.${r.identifier("id")} = ${r.identifier(c)}.${r.identifier(l)} WHERE ${r.join(w,r` AND `)} ORDER BY ${a.rank(c,f)} DESC, m.${r.identifier("_creationTime")} DESC, m.${r.identifier("id")} ASC LIMIT ${r.raw(String(s))}`;return pt(e,await h(n,t,u))},yn={ensureCompanion:async(n,t,e)=>{const{integer:i,key:o}=t.companionTypes;await y(n,t,r`CREATE TABLE IF NOT EXISTS ${r.identifier(e)} (${r.identifier(g)} ${r.raw(o)} NOT NULL, ${r.identifier(l)} ${r.raw(o)} NOT NULL, ${r.identifier(O)} ${r.raw(i)} NOT NULL)`),await J(n,t,{columns:Y(t,l,191),name:`${e}__by_id`,table:e,unique:!1}),await fn(n,t,e)},indexDocument:async(n,t,e,i,o,s)=>{const a=[...yt(i,o)];await N(n,t,At(t,e,String(s.row.id),a,s))},migrate:En,name:"inverted",purgeDocument:async(n,t,e,i,o)=>{await y(n,t,M(e,i,H(o,i)))},runSearch:hn},Tn={ensureCompanion:async(n,t,e)=>{await N(n,t,Pt(e))},indexDocument:async(n,t,e,i,o,s)=>{await N(n,t,mt(e,String(s.row.id),z(i,o),{guard:D(t,s)}))},migrate:an,name:"fts5",purgeDocument:async(n,t,e,i,o)=>{await N(n,t,ht(e,i,{guard:H(o,i)}))},runSearch:pn},Rn={ensureCompanion:async(n,t,e)=>{const i=t.nativeTextSearch;if(i){await y(n,t,i.createCompanion(e,t.companionTypes.key));for(const o of i.createIndexes(e))await y(n,t,o)}},indexDocument:async(n,t,e,i,o,s)=>{const a=t.nativeTextSearch;a&&await y(n,t,a.indexDocument(e,String(s.row.id),z(i,o),D(t,s)))},name:"native",purgeDocument:async(n,t,e,i,o)=>{await y(n,t,M(e,i,H(o,i)))},runSearch:gn},I=(n,t)=>n.strategy==="native"&&t.nativeTextSearch!==void 0?Rn:t.supportsFts5?Tn:yn,B=(n,t)=>`${qt(n)}/${I(n,t).name}`,nt=function*(n){for(const[t,e]of Object.entries(n.tables)){const i=e.searchIndexes;if(!(e.shardMode!==void 0&&e.shardMode.kind!=="global"||!i))for(const o of i)yield[t,e,o]}},R=(n,t)=>b(n,t.name),_n=async(n,t,e,i)=>{const o=R(e,i);return q(await C(n,t,o),B(i,t)).finished?!0:kt(n,t,o)},Hn=async(n,t,e,i,o,s)=>{if(!await _n(n,t,i,o.definition))throw new p("SEARCH_INDEX_BUILDING",`search index "${o.indexName}" on table "${i}" is still backfilling and currently covers only part of the table — retry once it finishes${t.searchBackfillHint===void 0?"":`, or complete it now: ${t.searchBackfillHint}`}`);return I(o.definition,t).runSearch(n,t,e,i,o,s)},St=n=>n.slice(n.lastIndexOf("/")+1),lt=200,Et=5,An=async(n,t,e,i)=>{const o=[...i.keys()],s=await h(n,t,r`SELECT * FROM ${r.identifier(e)} WHERE ${r.identifier("id")} >= ${o[0]} AND ${r.identifier("id")} <= ${o.at(-1)} ORDER BY ${r.identifier("id")} ASC`),a=new Map;for(const f of s){const c=f.id,w=i.get(c)?.row;w&&Tt.some(u=>String(w[u])!==String(f[u]))&&a.set(c,{row:f})}return a},W=async(n,t,e,i,o,s,a)=>{const f=I(s,t);let c=a;for(let w=0;c.size>0&&w<Et;w+=1){for(const{document:u,row:S}of c.values()){const E=u??X(e,S);E&&await f.indexDocument(n,t,o,E,s,{row:S,table:i})}c=await An(n,t,i,c)}c.size>0&&console.warn(`[@lunora/sql-store] search index "${o}": ${String(c.size)} row(s) were rewritten on every one of ${String(Et)} re-check rounds and were left to their writers — each stays stale only if none of those writes changed its indexed text.`)},Ct=async(n,t,e,i,o)=>{const s=R(i,o),a=B(o,t);let f=await C(n,t,s),c=q(f,a);if(c.finished)return!0;if(c.wipe){await F(n,t,s,void 0,!1,a,{cursor:f.cursor,done:f.done,profile:f.profile});const $=await C(n,t,s);if($.cursor!==f.cursor||$.done!==f.done||$.profile!==f.profile){if(f=$,c=q(f,a),c.wipe)return!1;if(c.finished)return!0}else f={cursor:void 0,done:!1,profile:a},c=q(f,a)}if((await h(n,t,t.tableExists(i))).length===0)return await F(n,t,s,void 0,!0,a),!0;const u=await Yt(n,t,i,c.cursor,lt),S=u.findLast($=>typeof $.id=="string")?.id,E=new Map;for(const $ of u)typeof $.id=="string"&&E.set($.id,{row:$});await W(n,t,e,i,s,o,E);const m=u.length<lt;return await F(n,t,s,S??c.cursor,m,a,{cursor:c.cursor,done:!1,profile:f.profile}),m},Lt=async(n,t,e)=>{await Ft(n,e);for(const[i,,o]of nt(t)){const s=R(i,o),a=B(o,e),f=await C(n,e,s);f.profile!==void 0&&St(f.profile)!==St(a)&&(await y(n,e,r`DROP TABLE IF EXISTS ${r.identifier(s)}`),await y(n,e,r`DROP TABLE IF EXISTS ${r.identifier(Wt(s))}`),await Ut(n,e,s)),await I(o,e).ensureCompanion(n,e,s)}},On=async(n,t,e,i,o)=>{const s=R(i,o);if((await C(n,t,s)).profile!==void 0)return;let f=0;(await h(n,t,t.tableExists(i))).length>0&&await Qt(n,t,e,i,()=>{f+=1},{limit:1}),await F(n,t,s,void 0,f===0,B(o,t))},vt=async(n,t,e,i,o,s)=>await I(o,t).migrate?.(n,t,{companion:R(i,o),definition:e,index:o,tableName:i},s)??{uniqueKeyMissing:!1,unmappedSkipped:0},Pn=async(n,t,e)=>{await Lt(n,t,e);for(const[i,o,s]of nt(t)){if(await vt(n,e,o,i,s,"step"),s.staged){await On(n,e,o,i,s);continue}await Ct(n,e,o,i,s)}},Bn=async(n,t,e)=>{const i={uniqueKeyMissing:[],unmappedSkipped:0};await Lt(n,t,e);for(const[o,s,a]of nt(t)){const f=await vt(n,e,s,o,a,"drain");i.unmappedSkipped+=f.unmappedSkipped,f.uniqueKeyMissing&&i.uniqueKeyMissing.push(R(o,a));let c=!1;for(;!c;)c=await Ct(n,e,s,o,a)}return i},Mt=async(n,t,e,i,o,s,a)=>{await I(s,t).purgeDocument(n,t,o,a,e);const c=(await P(n,t,e,[a])).get(a);c!==void 0&&await W(n,t,i,e,o,s,new Map([[a,{row:c}]]))},Dt=async(n,t,e,i,o,s,a)=>{const c=(await P(n,t,e,[a])).get(a);await(c===void 0?Mt(n,t,e,i,o,s,a):W(n,t,i,e,o,s,new Map([[a,{row:c}]])))},Wn=async(n,t,e)=>{const i=n.schema.tables[t];for(const o of i?.searchIndexes??[])await Dt(n.exec,n.dialect,t,i,R(t,o),o,e)},jn=n=>{const{dialect:t,exec:e,schema:i}=n;return async(o,s,a)=>{const f=i.tables[o],c=f?.searchIndexes;if(!(!f||!c||c.length===0))for(const[w,u]of c.entries()){const S=R(o,u);try{if(on(a?.previous,a?.document,u))continue;if(a){await W(e,t,f,o,S,u,new Map([[s,{document:a.document,row:{...a.written,id:s}}]]));continue}await Mt(e,t,o,f,S,u,s)}catch(E){const m=async()=>{for(const $ of c.slice(w))await Dt(e,t,o,f,R(o,$),$,s)};throw jt(E)?.then(m,m).catch(()=>{}),E}}}};export{Dn as A,Un as C,kn as R,bn as T,Wn as a,Bn as b,jn as c,Hn as d,Fn as e,Pn as r,st as u,qn as x};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{c as p,q as h,n as S,j as v}from"./sql-exec-ChIYvWnI.mjs";const N=["de","en","es","fr","it","nl","none","pt"],F=n=>N.includes(n),D="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",_="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",C="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",b="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",H="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",O="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",j="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ê",z=new RegExp("(?<=\\p{Script=Cyrillic})[\\u0300-\\u0305\\u0307\\u0309-\\u036F]|(?<!\\p{Script=Cyrillic})[\\u0300-\\u036F]","gu"),U=/[\u0080-\u{10FFFF}]/u,k=/[\p{L}\p{N}]+/gu,M=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]+/gu,y=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]/u,x=n=>{if(!y.test(n))return[n];const i=[];let o=0;for(const s of n.matchAll(M)){const r=s.index,a=[...s[0]];if(r>o&&i.push(n.slice(o,r)),o=r+s[0].length,a.length===1){i.push(s[0]);continue}for(let t=0;t+1<a.length;t+=1)i.push(`${String(a[t])}${String(a[t+1])}`)}return o<n.length&&i.push(n.slice(o)),i},A=n=>U.test(n)?n.normalize("NFD").replaceAll(z,"").normalize("NFC").toLowerCase():n.toLowerCase(),$=n=>new Set(A(n).split(" ")),I={de:$(_),en:$(D),es:$(C),fr:$(b),it:$(H),nl:$(O),none:new Set,pt:$(j)},B=3,W=256,g=new Map,V=n=>{const i=n!==void 0&&F(n)?n:"none",o=g.get(i);if(o)return o;const s=I[i],r=t=>{const d=A(t),l=d.match(k)??[],f=(y.test(d)?l.flatMap(c=>x(c)):l).filter(c=>c.length<=W);return s.size===0?f:f.filter(c=>!s.has(c))},a={document:r,profile:`${i}-v${String(B)}`,query:t=>{const d=r(t),l=new Set,f=[];for(let c=d.length-1;c>=0;c-=1){const m=d[c];l.has(m)||(l.add(m),f.push(m))}return f.toReversed()}};return g.set(i,a),a},X=n=>`${V(n.language).profile}:${n.field}`,T=n=>{const i=n.slice(n.indexOf(":")+1),o=i.lastIndexOf("/");return o===-1?i:i.slice(0,o)},G=(n,i)=>n.profile!==i?{cursor:void 0,finished:!1,wipe:n.cursor!==void 0||n.done}:{cursor:n.cursor,finished:n.done,wipe:!1},K=(n,i)=>typeof n=="string"&&T(n)===T(i),u="__lunora_search_state",J=async(n,i)=>{const{integer:o,key:s}=i.companionTypes,r=async(a,t)=>{try{await p(n,i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier(a)} ${e.raw(t)}`)}catch{}};await p(n,i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} ${e.raw(s)} PRIMARY KEY, ${e.identifier("cursor")} ${e.raw(s)}, ${e.identifier("done")} ${e.raw(o)} NOT NULL DEFAULT 0, ${e.identifier("profile")} ${e.raw(s)}, ${e.identifier("covered")} ${e.raw(o)} NOT NULL DEFAULT 0)`),await r("profile",s),await r("covered",`${o} NOT NULL DEFAULT 0`),await p(n,i,e`UPDATE ${e.identifier(u)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},L=n=>n===1||n===!0||n==="1",Q=async(n,i,o)=>{const s=await h(n,i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`);return L(s[0]?.covered)},Z=async(n,i,o)=>{await p(n,i,e`DELETE FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`)},ee=async(n,i,o)=>{const r=(await h(n,i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`))[0];if(!r)return{cursor:void 0,done:!1,profile:void 0};const{cursor:a,profile:t}=r;return{cursor:typeof a=="string"?a:void 0,done:L(r.done),profile:typeof t=="string"?t:void 0}},ne=async(n,i,o,s,r,a,t)=>{const d=s??null,l=await h(n,i,e`SELECT ${e.identifier("profile")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`),f=K(l[0]?.profile,a),c=r?1:0,m=r||!f?e`${e.identifier("covered")} = ${c}`:e`${e.identifier("covered")} = ${e.identifier("covered")}`,R=t?.done===!0?1:0,q=t===void 0?e``:e` AND ${S(i.name,v("cursor"),t.cursor??null)} AND ${S(i.name,v("profile"),t.profile??null)} AND ${e.identifier("done")} = ${R}`,E=e`UPDATE ${e.identifier(u)} SET ${e.identifier("cursor")} = ${d}, ${e.identifier("done")} = ${c}, ${e.identifier("profile")} = ${a}, ${m} WHERE ${e.identifier("companion")} = ${o}${q}`;if(l.length>0){await p(n,i,E);return}if(!(t!==void 0&&(t.cursor!==void 0||t.done||t.profile!==void 0)))try{await p(n,i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${o}, ${d}, ${r?1:0}, ${a}, ${r?1:0})`)}catch(w){if(!i.isUniqueViolation(w))throw w;await p(n,i,E)}};export{u as S,Z as a,Q as b,X as c,G as l,J as m,V as q,ee as r,ne as w};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{B as l,M as o,O as n,
|
|
1
|
+
import{B as l,M as o,O as n,j as r,e as t,d,h as i,k as u,f as R,m as f,x as q,i as c,o as C,n as S,b as m,g as p,p as x,w as I,z as E,q as h,y as w,c as A,r as O,a as _,l as y,s as B,v as N,t as z}from"./sql-exec-ChIYvWnI.mjs";import"./value-codec-C52YW-Do.mjs";export{l as BACKFILL_BATCH_SIZE,o as MAX_BOUND_PARAMETERS,n as OCC_VERSION_COLUMN,r as columnRefSql,t as createIndexIfNotExists,d as decodeGlobalRow,i as decodeRow,u as decodeRows,R as dropIndexIfExists,f as fieldRefSql,q as forEachRowPaged,c as indexState,C as nextRowVersion,S as nullSafeEqualsSql,m as pathContainsNeedle,p as pathInList,x as pathTextReference,I as pathTypeGuardSql,E as qualifiedColumnRefSql,h as queryAll,w as queryBatch,A as queryRun,O as readRowsPage,_ as runInOrder,y as serializeColumnValue,B as serializeDocumentColumn,N as serializeFieldValue,z as tableColumns};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as b}from"@lunora/errors";import{needsWireEncoding as I,encodeWire as A,decodeWire as S}from"@lunora/wire";import{sql as m}from"drizzle-orm";import{runSqlGlobalTableMigrations as g}from"./runSqlGlobalTableMigrations-C4_8w8pO.mjs";import{t as y}from"./post-commit-error-hh-zQyjO.mjs";import{r as T,d as L,M as k,q as E}from"./sql-exec-ChIYvWnI.mjs";const $=200,v=(r,o)=>{const t=e=>r.tables[e]?.shardMode?.kind==="global";return o&&o.length>0?o.filter(e=>t(e)):Object.keys(r.tables).filter(e=>t(e))},D=r=>I(r)?A(r):r,Y=async function*(r,o,t,e){const s=v(o,e.tables),n=e.batchSize??$;await g(r,o,t);for(const i of s){const d=o.tables[i];let a,c=!0;for(;c;){const f=await T(r,t,i,a,n);for(const u of f)yield{doc:D(L(d,u)),table:i};const l=f.at(-1);l!==void 0&&(a=String(l.id)),c=f.length===n}}},w=r=>r?._meta?.column?.notNull===!1,C=(r,o)=>{const t=new Set;for(const[e,s]of Object.entries(r.shape)){if(o[e]!==null||s.kind!=="optional"||w(s))continue;const n=s._meta?.inner;w(n)||t.add(e)}return t.size===0?o:Object.fromEntries(Object.entries(o).filter(([e])=>!t.has(e)))},F=new Set(["_creationTime","_id"]),M=(r,o)=>Object.keys(o).find(t=>!F.has(t)&&!Object.hasOwn(r.shape,t)),x=r=>{const o=r._id,t=r._creationTime;if(o!==void 0&&(typeof o!="string"||o===""))return'field "_id": must be a non-empty string';if(t!==void 0&&(typeof t!="number"||!Number.isFinite(t)))return'field "_creationTime": must be a finite number'},j=(r,o,t)=>{const e=r.tables[o];if(!e)return`unknown table: ${o}`;const s=M(e,t);if(s!==void 0)return`unexpected field "${s}": not declared in table "${o}"`;const n=x(t);if(n!==void 0)return n;for(const[i,d]of Object.entries(e.shape)){const a=t[i],c=d.kind==="optional";if(a===void 0&&c)continue;const f=d.parse;if(typeof f=="function")try{f(a)}catch(l){const u=l instanceof Error?l.message:String(l);return`field "${i}": ${u}`}}},R=async(r,o,t,e,s)=>t?(await E(t,o,m`SELECT 1 FROM ${m.identifier(e)} WHERE ${m.identifier("id")} = ${s} LIMIT 1`)).length>0:await r.get(e,s)!==null,O=async(r,o,t,e,s,n)=>{try{return{existingId:await R(r,o,t,e,s)?s:void 0}}catch(i){const{body:d}=b(i,{fallbackCode:"PROBE_FAILED"});return{error:{code:d.code,line:n,message:d.message,table:e}}}},h=(r,o,t)=>{const e=r.held.get(o)??new Set;e.add(t),r.held.set(o,e)},B=async(r,o,t)=>{const e=[...t.keys()],s=new Map;let n=[],i=k;const d=async()=>{if(n.length===0)return;const a=await E(r,o,m.join(n,m` UNION ALL `));for(const c of a)h({held:s},e[Number(c.slot)],String(c.id));n=[],i=k};try{for(const[a,c]of e.entries()){const f=[...t.get(c)];for(let l=0;l<f.length;){const u=f.slice(l,l+i);n.push(m`SELECT ${m.raw(String(a))} AS slot, ${m.identifier("id")} FROM ${m.identifier(c)} WHERE ${m.identifier("id")} IN (${m.join(u.map(p=>m.param(p)),m`, `)})`),l+=u.length,i-=u.length,i===0&&await d()}}await d()}catch(a){const{body:c}=b(a,{fallbackCode:"PROBE_FAILED"});return{failure:{code:c.code,message:c.message}}}return{held:s}},N=(r,o,t,e)=>"failure"in r?{error:{...r.failure,line:e,table:o}}:{existingId:r.held.get(o)?.has(t)===!0?t:void 0},W=r=>v(r).some(o=>Object.keys(r.tables[o]?.triggerMap??{}).length>0),P=async(r,o,t,e,s)=>{const{doc:n,table:i}=e,d=n._id;if(typeof d!="string")return{committed:!1,error:{code:"BAD_ROW",line:s,message:"a delete row needs the `_id` to delete",table:i},kind:"error"};if(t.dryRun===!0)return{kind:"checked"};const a=await O(r,o,t.exec,i,d,s);if("error"in a)return{committed:!1,error:a.error,kind:"error"};if(a.existingId===void 0)return{kind:"absent"};try{return await r.delete(i,d,{hard:!0,skipOnDelete:!0}),{kind:"deleted"}}catch(c){const{body:f}=b(c,{fallbackCode:"DELETE_FAILED"}),l=y(c,i,d),u=l?`${f.message} (row "${d}" was deleted before this failure, so its triggers or companion writes may not have completed; a re-run finds it absent and does not redo them)`:f.message;return{committed:l,error:{code:f.code,line:s,message:u,table:i},kind:"error"}}},_=async(r,o,t,e,s,n)=>{try{if(e!==void 0){const i={...t};return delete i._id,await r.replace(o,e,i,{allowExplicitId:!0}),{kind:"replaced"}}return await r.insert(o,t,{allowExplicitId:!0}),{inserted:o,kind:"inserted"}}catch(i){const{body:d}=b(i,{fallbackCode:e===void 0?"INSERT_FAILED":"REPLACE_FAILED"}),a=e??(typeof t._id=="string"?t._id:void 0),c=a!==void 0&&y(i,o,a),f=n==="replace"?'re-importing it with onConflict "replace" redoes that work':'a re-import skips it while it exists; use onConflict "replace" to redo that work',l=c?`${d.message} (row "${a}" committed before this failure, so its triggers or companion writes may not have completed; ${f})`:d.message;return{committed:c,error:{code:d.code,line:s,message:l,table:o},kind:"error"}}},G=(r,o,t,e)=>{const{doc:s,table:n}=t;if(typeof n!="string"||n.length===0)return{kind:"settled",outcome:{committed:!1,error:{code:"BAD_ROW",line:e,message:"row is missing `table`",table:n},kind:"error"}};if(r.tables[n]?.shardMode?.kind!=="global")return{kind:"settled",outcome:{kind:"skip"}};if(!s||typeof s!="object"||Array.isArray(s))return{kind:"settled",outcome:{committed:!1,error:{code:"BAD_ROW",line:e,message:"row is missing or malformed `doc`",table:n},kind:"error"}};if(t.op==="delete")return{kind:"delete",line:e,row:t};let i;try{i=S(s)}catch(a){return{kind:"settled",outcome:{committed:!1,error:{code:"BAD_ROW",line:e,message:a instanceof Error?a.message:String(a),table:n},kind:"error"}}}i=C(r.tables[n],i);const d=j(r,n,i);return d!==void 0?{kind:"settled",outcome:{committed:!1,error:{code:"VALIDATION_ERROR",line:e,message:d,table:n},kind:"error"}}:o?{kind:"settled",outcome:{kind:"checked"}}:{decoded:i,explicitId:typeof i._id=="string"?i._id:void 0,kind:"ready",line:e,table:n}},H=async(r,o,t,e,s,n)=>{const{decoded:i,explicitId:d,line:a,table:c}=s;try{if(!await R(r,o,t,c,d))return}catch{return}return e.snapshot!==void 0&&"held"in e.snapshot&&h(e.snapshot,c,d),n==="replace"?_(r,c,i,d,a,n):{kind:"conflict"}},z=async(r,o,t,e,s)=>{const{decoded:n,explicitId:i,line:d,table:a}=e;let c={existingId:void 0};if(i!==void 0&&(c=s.snapshot===void 0?await O(r,o,t.exec,a,i,d):N(s.snapshot,a,i,d)),"error"in c)return{committed:!1,error:c.error,kind:"error"};const{existingId:f}=c;if(f!==void 0&&t.onConflict!=="replace")return{kind:"conflict"};const l=await _(r,a,n,f,d,t.onConflict);if(i===void 0)return l;const{snapshot:u}=s;return u!==void 0&&"held"in u&&(l.kind==="inserted"||l.kind==="replaced"||l.kind==="error"&&l.committed)&&h(u,a,i),l.kind==="error"&&!l.committed&&l.error.code==="CONFLICT"&&f===void 0?await H(r,o,t.exec,s,{...e,explicitId:i},t.onConflict)??l:l},q=async(r,o,t,e,s)=>{const n=new Map;for(const i of e)if(i.kind==="ready"&&i.explicitId!==void 0){const d=n.get(i.table)??new Set;d.add(i.explicitId),n.set(i.table,d)}if(n.size===0)return s?{held:new Map}:void 0;try{await g(r,o,t)}catch(i){const{body:d}=b(i,{fallbackCode:"PROBE_FAILED"});return{failure:{code:d.code,message:d.message}}}return s?B(r,t,n):void 0},U=(r,o,t,e,s)=>e.kind==="settled"?Promise.resolve(e.outcome):e.kind==="delete"?P(r,o,t,e.row,e.line):z(r,o,t,e,s),ee=async(r,o,t,e)=>{const s=[],n={};let i=0,d=0,a=0,c=(e.startLine??1)-1;const f=e.rows.map(u=>(c+=1,G(o,e.dryRun===!0,u,u.line??c))),l={};e.exec&&e.dryRun!==!0&&(l.snapshot=await q(e.exec,o,t,f,!W(o)));for(const u of f){const p=await U(r,t,e,u,l);switch(p.kind){case"conflict":{i+=1;break}case"deleted":{d+=1;break}case"error":{s.push(p.error);break}case"inserted":{n[p.inserted]=(n[p.inserted]??0)+1;break}case"replaced":{a+=1;break}}}return{conflicts:i,deleted:d,errors:s,inserted:n,replaced:a}};export{Y as exportSqlGlobalRows,ee as importSqlGlobalRows,v as selectGlobalTables};
|
package/dist/packem_shared/{facetSqlGlobalColumn-f5GVnQn4.mjs → facetSqlGlobalColumn-CAQNCBVu.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as w}from"@lunora/errors";import{isInternalTableName as G}from"@lunora/shard-engine";import{needsWireEncoding as v,encodeWire as M}from"@lunora/wire";import{sql as o}from"drizzle-orm";import{runSqlGlobalTableMigrations as k}from"./runSqlGlobalTableMigrations-
|
|
1
|
+
import{LunoraError as w}from"@lunora/errors";import{isInternalTableName as G}from"@lunora/shard-engine";import{needsWireEncoding as v,encodeWire as M}from"@lunora/wire";import{sql as o}from"drizzle-orm";import{runSqlGlobalTableMigrations as k}from"./runSqlGlobalTableMigrations-C4_8w8pO.mjs";import{q as u,M as T,d as P}from"./sql-exec-ChIYvWnI.mjs";import{s as W,e as Y,a as O}from"./value-codec-C52YW-Do.mjs";const H=50,j=500,X=30,J=200,Q=(t,n,e)=>Math.min(Math.max(t,n),e),g=(t,n,e,a)=>Q(Math.trunc(t!==void 0&&Number.isFinite(t)?t:n),e,a),V=(t,n)=>G(t)||n.name==="sqlite"&&t.startsWith("d1_"),y=t=>t.name==="postgres"?o`current_schema()`:o`DATABASE()`,C=t=>t.filter(n=>Number(n.pk??0)>0).toSorted((n,e)=>Number(n.pk)-Number(e.pk)).map(n=>String(n.name)),p={columns:async(t,n,e)=>(n.name==="sqlite"?await u(t,n,o`PRAGMA table_info(${o.identifier(e)})`):await u(t,n,o`SELECT column_name AS name FROM information_schema.columns WHERE table_schema = ${y(n)} AND table_name = ${e} ORDER BY ordinal_position`)).map(r=>String(r.name)),foreignKeys:async(t,n,e)=>{let a;return n.name==="sqlite"?a=o`PRAGMA foreign_key_list(${o.identifier(e)})`:n.name==="mysql"?a=o`SELECT column_name AS ${o.identifier("from")}, referenced_table_name AS ${o.identifier("table")} FROM information_schema.key_column_usage WHERE table_schema = DATABASE() AND table_name = ${e} AND referenced_table_name IS NOT NULL AND referenced_table_schema = DATABASE()`:a=o`SELECT kcu.column_name AS ${o.identifier("from")}, ccu.table_name AS ${o.identifier("table")} FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON kcu.constraint_name = tc.constraint_name AND kcu.constraint_schema = tc.constraint_schema AND kcu.table_schema = tc.table_schema AND kcu.table_name = tc.table_name JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name AND ccu.constraint_schema = tc.constraint_schema WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = current_schema() AND tc.table_name = ${e} AND ccu.table_schema = current_schema()`,(await u(t,n,a)).map(s=>({from:String(s.from),target:String(s.table)}))},primaryKey:async(t,n,e)=>n.name==="sqlite"?C(await u(t,n,o`PRAGMA table_info(${o.identifier(e)})`)):(await u(t,n,o`SELECT kcu.column_name AS name FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema AND kcu.table_name = tc.table_name WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = ${y(n)} AND tc.table_name = ${e} ORDER BY kcu.ordinal_position`)).map(r=>String(r.name)),tables:async(t,n)=>(n.name==="sqlite"?await u(t,n,o`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name`):await u(t,n,o`SELECT table_name AS name FROM information_schema.tables WHERE table_schema = ${y(n)} AND table_type = 'BASE TABLE' ORDER BY table_name`)).map(a=>String(a.name))},z=/password|secret|token|hash|salt|credential/iu,Z=new Map([["apikey",new Set(["key"])],["jwks",new Set(["privatekey"])],["twofactor",new Set(["backupcodes"])],["verification",new Set(["value"])]]),D=t=>t.toLowerCase().replaceAll("_",""),h=(t,n)=>z.test(n)||Z.get(D(t))?.has(D(n))===!0,_=(t,n)=>{const e=t.tables[n];return e?.shardMode?.kind==="global"?e:void 0},L=async(t,n)=>(await p.tables(t,n)).filter(a=>!V(a,n)),I=async(t,n,e,a)=>{if(await k(t,e,n),!(await L(t,n)).includes(a))throw new w("UNKNOWN_TABLE",`unknown table: ${a}`,{status:404})},R=async(t,n,e,a=o``)=>{const r=await u(t,n,o`SELECT COUNT(*) AS c FROM ${o.identifier(e)}${a}`);return Number(r[0]?.c??0)},q=(t,n,e)=>_(t,n)!==void 0&&e==="_id"?"id":e,B=(t,n,e)=>{const a=_(t,n)?.shape[e];return a===void 0?void 0:Y(a)},x=/^-?\d+$/u,F=(t,n)=>{if(n>T)throw new w("BAD_REQUEST",`the query over ${t} binds ${String(n)} parameters, and a statement takes at most ${String(T)} — remove some filters`)},tt=(t,n,e)=>{if(e)return t instanceof ArrayBuffer?new Uint8Array(t):t;if(n!=="bigint")return O(t);const a=typeof t=="number"||typeof t=="string"?String(t).trim():void 0;return O(a!==void 0&&x.test(a)?BigInt(a):t,n)},nt=t=>{if(t.operator!==void 0&&t.operator!=="eq")throw new w("BAD_REQUEST",`operator "${t.operator}" is not supported on the global browser — only eq is`);if(t.path!==void 0&&!(Array.isArray(t.path)&&t.path.length===0))throw new w("BAD_REQUEST",`a nested path is not supported on the global browser, so ${t.column} must be a top-level column`)},U=(t,n,e,a,r)=>{const s=[],i=_(t,e)===void 0&&n.name!=="sqlite";let m=0;for(const c of r??[]){if(nt(c),!a.includes(c.column))throw new w("UNKNOWN_COLUMN",`unknown column: ${c.column}`,{status:404});if(_(t,e)===void 0&&h(e,c.column))throw new w("FORBIDDEN",`cannot filter on a redacted column: ${c.column}`,{status:403});const f=o.identifier(q(t,e,c.column));if(c.value===null||c.value===void 0)s.push(o`${f} IS NULL`);else{const l=tt(c.value,B(t,e,c.column),i);s.push(i&&n.name==="postgres"&&l instanceof Date?o`${f}::timestamptz = ${l}::timestamptz`:o`${f} = ${l}`),m+=1}}return{bound:m,where:s.length>0?o` WHERE ${o.join(s,o` AND `)}`:o``}},et=(t,n,e)=>{const a=_(t,n);if(a)return P(a,e);const r={};for(const[s,i]of Object.entries(e))r[s]=i!=null&&h(n,s)?"•••":i;return r},K=async(t,n,e,a)=>{const r=_(e,a);if(r)return{columns:["_id","_creationTime",...Object.keys(r.shape)],primaryKey:()=>Promise.resolve([])};if(n.name==="sqlite"){const s=await u(t,n,o`PRAGMA table_info(${o.identifier(a)})`);return{columns:s.map(i=>String(i.name)),primaryKey:()=>Promise.resolve(C(s))}}return{columns:await p.columns(t,n,a),primaryKey:()=>p.primaryKey(t,n,a)}},ot=async(t,n,e,a)=>{if(_(e,a))return;const r=await p.foreignKeys(t,n,a);if(r.length===0)return;const s={};for(const i of r){const{from:m,target:c}=i;s[m]??=c}return s},ft=async(t,n,e)=>{await k(t,n,e);const a=await L(t,e);return Promise.all(a.map(async r=>({name:r,rowCount:await R(t,e,r)})))},at=async(t,n,e,a,r)=>{if(_(n,e)!==void 0)return o`${o.identifier("id")}`;const s=await r();return s.length>0?o.join(s.map(i=>o.identifier(i)),o`, `):a.includes("id")?o`${o.identifier("id")}`:t.name==="sqlite"?o.raw("rowid"):o.join(a.map(i=>t.name==="postgres"?o`${o.identifier(i)}::text`:o.identifier(i)),o`, `)},_t=async(t,n,e,a)=>{const{table:r}=a;await I(t,e,n,r);const s=g(a.limit,H,1,j),i=g(a.offset,0,0,Number.MAX_SAFE_INTEGER),{columns:m,primaryKey:c}=await K(t,e,n,r),{bound:f,where:l}=U(n,e,r,m,a.filters);F(r,f);const A=await R(t,e,r,l),d=await at(e,n,r,m,c),S=(await u(t,e,o`SELECT * FROM ${o.identifier(r)}${l} ORDER BY ${d} LIMIT ${o.raw(String(s))} OFFSET ${o.raw(String(i))}`)).map(E=>{const N=et(n,r,E);return v(N)?M(N):N}),b=await ot(t,e,n,r);return b===void 0?{columns:m,rows:S,total:A}:{columns:m,refs:b,rows:S,total:A}},Et=async(t,n,e,a)=>{const{column:r,table:s}=a;await I(t,e,n,s);const{columns:i}=await K(t,e,n,s);if(!i.includes(r))throw new w("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const{bound:m,where:c}=U(n,e,s,i,a.filters);if(F(s,m),_(n,s)===void 0&&h(s,r)){const E=await R(t,e,s,c);return{truncated:!1,values:E===0?[]:[{count:E,value:"•••"}]}}const f=g(a.limit,X,1,J),l=o.identifier(q(n,s,r)),A=await u(t,e,o`SELECT ${l} AS value, COUNT(*) AS count FROM ${o.identifier(s)}${c} GROUP BY ${l} ORDER BY count DESC, ${l} ASC LIMIT ${o.raw(String(f+1))}`),d=A.length>f,$=d?A.slice(0,f):A,S=B(n,s,r)==="bigint",b=$.map(E=>({count:Number(E.count),value:S?W(E.value,"bigint"):E.value}));return{truncated:d,values:v(b)?M(b):b}};export{Et as facetSqlGlobalColumn,ft as listSqlGlobalTables,_t as readSqlGlobalTablePage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const c=(t,o)=>`${t}\0${o}`,n=new WeakMap,w=async(t,o,r)=>{try{return await r()}catch(e){const s=typeof e=="object"&&e!==null?e:new Error(String(e),{cause:e}),a=n.get(s)??new Set;throw a.add(c(t,o)),n.set(s,a),s}},d=(t,o,r)=>(typeof t=="object"&&t!==null?n.get(t):void 0)?.delete(c(o,r))===!0;export{w as a,d as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as O}from"@lunora/errors";import{aggregateTableName as V,rankTableName as Q,sortColumnName as N,bigintSqlKey as z}from"@lunora/shard-engine";import{sql as t}from"drizzle-orm";import{b as Z,e as g,B as b,r as J,i as nn,U as en,c as tn}from"./value-codec-C52YW-Do.mjs";import{O as S,t as on,c as d,q as $,M as q,e as y,j as m,z as rn,s as sn,y as an}from"./sql-exec-ChIYvWnI.mjs";const ln=new Set(["any","null"]),k=(e,n)=>{const i=n.kindOf(e);return i!==void 0&&ln.has(i)||n.nullableOf(e)?!0:i==="union"&&(n.membersOf(e)??[]).some(o=>k(o,n))},R=e=>{const n=e._meta?.inner;return e.kind==="optional"&&n?R(n):e},I=e=>k(e,{kindOf:Z,membersOf:n=>R(n)._meta?.members,nullableOf:n=>R(n)._meta?.column?.notNull===!1}),x=(e,n,i=!1)=>n.columnType(g(e),{unique:i||e._meta?.column?.unique===!0}),M=e=>{const n=new Set;for(const i of e.indexes)i.unique===!0&&i.fields.length===1&&n.add(i.fields[0]);return n},un=(e,n,i)=>{if(i.indexKeyPrefix!==void 0)for(const o of n.indexes){if(o.unique!==!0||o.fields.length<=1)continue;const r=o.fields.filter(s=>{const a=n.shape[s];return a!==void 0&&i.indexKeyPrefix?.(g(a))!==void 0});if(r.length>0)throw new Error(`${e}.${o.name}: a composite unique index cannot cover ${r.join(", ")} in full on this engine (its key limit forces a prefix, which would constrain the prefix rather than the value). Split it into single-column unique indexes, or store those fields as a bounded type.`)}},cn=e=>e._meta?.column?.notNull===!0&&e.kind!=="optional"&&!I(e),fn=(e,n,i)=>{const o=[],r=M(n);for(const[u,c]of Object.entries(n.shape)){if(!c._meta?.column)continue;const f=cn(c)?" NOT NULL":"";o.push(t`${t.identifier(u)} ${t.raw(`${x(c,i,r.has(u))}${f}`)}`)}const s=[...i.frameworkColumns().map(u=>t`${t.identifier(u.name)} ${t.raw(u.type)}`),t`${t.identifier(S)} ${t.raw(i.companionTypes.integer)}`],a=s.length+o.length,l=i.maxTableColumns;if(l!==void 0&&a>l){const u=a-1===l,c="Move one or more fields into a single object field, or split the table — either way the existing rows need a data migration (`defineMigration` + `lunora migrate up`); there is no in-place path.";throw new O("VALIDATION_ERROR",`@lunora/sql-store: global table "${e}" needs ${String(a)} columns, over this engine's ${String(l)}-column limit. ${u?`One of them is "${S}", the row version every guarded write reads, which caps declared fields at ${String(l-s.length)}. A table provisioned at ${String(l)} columns before that column existed cannot be widened to hold it. `:""}${c}`)}return t.join([...s,...o],t`, `)},B=e=>{if(e.indexKeyPrefix?.("string")===void 0)return t`${m("_creationTime")}, ${m("id")}`},D=new Set,F=async(e,n,i,o)=>{const r=t.join(i.refs.map(a=>t`${a} IS NOT NULL`),t` AND `);if((await $(e,n,t`SELECT ${i.columns} FROM ${t.identifier(i.table)} WHERE ${r} GROUP BY ${i.columns} HAVING COUNT(*) > 1 LIMIT 1`)).length>0){const a=`unique index "${i.name}" on "${i.table}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first.`;throw D.has(a)||(D.add(a),console.error(`[@lunora/sql-store] ${a}`)),new O("UNIQUE_INDEX_DUPLICATES",a)}},dn=async(e,n,i)=>{if(!i.unique){await y(e,n,i);return}try{await y(e,n,i)}catch(o){throw n.isUniqueViolation(o)&&await F(e,n,i,"cannot be created"),o}},P=e=>{const n=e.indexOf("(");return n===-1?void 0:e.slice(n,e.lastIndexOf(")")+1)},mn=(e,n)=>{const i=n.unique?t`UNIQUE `:t``;return P(e.render(t`CREATE ${i}INDEX ${t.identifier(n.name)} ON ${t.identifier(n.table)} (${n.columns})`).sql)},$n=(e,n,i)=>{const o=mn(e,i);return o!==void 0&&o!==P(n)},j=async(e,n,i)=>{if(n.name!=="sqlite")return;const r=(await $(e,n,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${i.name} COLLATE NOCASE AND tbl_name = ${i.table} COLLATE NOCASE`))[0]?.sql;typeof r=="string"&&$n(n,r,i)&&(i.unique&&await F(e,n,i,"cannot be re-created with its new column list; the previous index is left in place"),await d(e,n,t`DROP INDEX IF EXISTS ${t.identifier(i.name)}`))},En=(e,n,i)=>{un(e,n,i);const o=M(n),r=l=>{const u=m(l),c=n.shape[l],f=c&&i.indexKeyPrefix&&c._meta?.column?.unique!==!0&&!o.has(l)?i.indexKeyPrefix(g(c)):void 0;return f===void 0?u:t`${u}(${t.raw(String(f))})`},s=B(i),a=[];for(const l of n.indexes){const u=l.fields.map(E=>r(E)),c=t.join(u,t`, `),f=l.unique??!1;a.push({columns:f||s===void 0?c:t`${c}, ${s}`,kind:"declared",name:`${e}_${l.name}`,refs:u,table:e,unique:f})}s!==void 0&&a.push({columns:s,kind:"default-order",name:`${e}__by_creation`,refs:[],table:e,unique:!1});for(const[l,u]of on(n)){if(!u.unique)continue;const c=r(l);a.push({columns:c,kind:"unique-column",name:`${e}_unique_${l}`,refs:[c],table:e,unique:!0})}return a},gn=/^\s*create\s+unique\s/iu,p="__lunora_framework_indexes",wn=()=>t`CREATE TABLE IF NOT EXISTS ${t.identifier(p)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`,K=(e,n)=>t`INSERT OR IGNORE INTO ${t.identifier(p)} (name, table_name) VALUES (${e}, ${n})`,h=e=>e.replaceAll(/[A-Z]/gu,n=>n.toLowerCase()),hn=async(e,n,i)=>{if(n.name!=="sqlite"||(await $(e,n,t`SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ${p} COLLATE NOCASE`)).length>0)return;await d(e,n,wn());const r=B(n),s=r===void 0?void 0:`, ${n.render(r).sql})`;for(const a of i){const l=`${h(a)}_`,u=await $(e,n,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`);for(const c of u){const f=String(c.name),E=String(c.sql);h(f).startsWith(l)&&h(f)!==h(`${a}__by_creation`)&&(gn.test(E)||s!==void 0&&E.trimEnd().endsWith(s))&&await d(e,n,K(f,a))}}},pn=(e,n,i)=>{if(e.name!=="sqlite")return[];const o=new Set(n.map(r=>h(r.name)));return i.filter(r=>!o.has(h(r)))},_n=async(e,n,i,o)=>{if(o.name!=="sqlite")return;const r=await $(e,o,t`SELECT "l"."name" FROM ${t.identifier(p)} AS "l" WHERE "l"."table_name" = ${n} COLLATE NOCASE`);for(const s of pn(o,i,r.map(a=>String(a.name))))await d(e,o,t`DROP INDEX IF EXISTS ${t.identifier(s)}`),await d(e,o,t`DELETE FROM ${t.identifier(p)} WHERE ${t.identifier(p)}."name" = ${s}`)},Tn=async(e,n,i,o)=>{const r=En(n,i,o);for(const s of r){if(s.kind==="default-order"){await y(e,o,s);continue}s.kind==="declared"&&await j(e,o,s),await dn(e,o,s),o.name==="sqlite"&&await d(e,o,K(s.name,s.table))}await _n(e,n,r,o)},C="__lunora_migration_state",yn=async(e,n)=>{await d(e,n,t`CREATE TABLE IF NOT EXISTS ${t.identifier(C)} (${t.identifier("name")} ${t.raw(n.companionTypes.key)} PRIMARY KEY)`)},Ln=async(e,n,i)=>(await $(e,n,t`SELECT ${t.identifier("name")} FROM ${t.identifier(C)} WHERE ${t.identifier("name")} = ${i}`)).length>0,An=async(e,n,i,o,r,s)=>{r>0&&s!==void 0&&console.warn(`[@lunora/sql-store] storage migration "${i}" on "${o}": ${String(r)} row(s) ${s} and were left as stored — range filters and ORDER BY over them stay wrong until they are corrected by hand.`);try{await d(e,n,t`INSERT INTO ${t.identifier(C)} (${t.identifier("name")}) VALUES (${i})`)}catch(a){if(!n.isUniqueViolation(a))throw a}},Sn=100,Rn=(e,n)=>{const i=[],o=[];for(const r of n.fields){const s=e[r],a=n.convert(s);a!==void 0&&(i.push(t`${m(r)} = ${a}`),o.push(t`${m(r)} = ${s}`))}return{assignments:i,guards:o}},On=e=>t.join(e.fields.map(n=>e.probe(n)),t` OR `),G=async(e,n,i,o)=>{if(o.fields.length===0||(await yn(e,i),await Ln(e,i,o.marker)))return;const r=On(o),s=t.join([m("id"),...o.fields.map(u=>m(u))],t`, `);let a="",l=0;for(;;){const u=await $(e,i,t`SELECT ${s} FROM ${t.identifier(n)} WHERE (${r}) AND ${m("id")} > ${a} ORDER BY ${m("id")} LIMIT ${t.raw(String(Sn))}`);if(u.length===0){await An(e,i,o.marker,n,l,o.describeUnconvertible);return}const c=[];for(const E of u){const{id:w}=E,{assignments:_,guards:T}=typeof w=="string"?Rn(E,o):{assignments:[],guards:[]};if(_.length===0){l+=1;continue}c.push(t`UPDATE ${t.identifier(n)} SET ${t.join(_,t`, `)} WHERE ${m("id")} = ${w} AND ${t.join(T,t` AND `)}`)}await an(e,i,c);const f=u.at(-1)?.id;if(typeof f!="string")return;a=f}},U=e=>`'${e}%'`,Nn=e=>Object.entries(e.shape).filter(([,n])=>n._meta?.column!==void 0&&g(n)==="bigint").map(([n])=>n),In=e=>Object.entries(e.shape).filter(([,n])=>n._meta?.column!==void 0&&nn(g(n))).map(([n])=>n),H=(e,n)=>({convert:i=>{if(!(typeof i!="string"||i.length===b))try{return z(BigInt(i))}catch{return}},describeUnconvertible:"hold a value the order-preserving key cannot represent (non-numeric text, or a magnitude past 39 digits)",fields:Nn(n),marker:`bigint-key:${e}`,probe:i=>t`(${m(i)} IS NOT NULL AND LENGTH(${m(i)}) <> ${b})`}),Cn=async(e,n,i,o)=>G(e,n,o,H(n,i)),W=(e,n)=>({convert:J,fields:In(n),marker:`untyped-number-key:${e}`,probe:i=>t`(${m(i)} LIKE ${t.raw(U(en))} AND ${m(i)} NOT LIKE ${t.raw(U(tn))})`}),bn=async(e,n,i,o)=>G(e,n,o,W(n,i)),v=new Set,L=(e,n)=>{v.has(e)||(v.add(e),console.warn(`[@lunora/sql-store] ${n}`))},qn=e=>{const n=e._meta?.column;return n?.defaultFn?n.defaultFn():n&&"defaultValue"in n?n.defaultValue:void 0},Dn=(e,n,i)=>i._meta?.column?.unique===!0||e.indexes.some(o=>o.unique===!0&&o.fields.includes(n)),Un=async(e,n,i,o,r,s)=>{if(s.kind==="optional"||I(s))return;const a=Dn(i,r,s),l=a?void 0:qn(s),u=`UPDATE "${n}" SET "${r}" = … WHERE "${r}" IS NULL`;if(l===void 0){const c=a?"is unique, so one default cannot be written to every row":"has no default";L(`backfill:${n}.${r}`,`"${n}.${r}" was added as a required field that ${c}, so rows written before it read NULL. Backfill it with a migration (${u}).`);return}try{await d(e,o,t`UPDATE ${t.identifier(n)} SET ${t.identifier(r)} = ${sn(i,r,l)} WHERE ${t.identifier(r)} IS NULL`)}catch(c){L(`backfill:${n}.${r}`,`could not backfill "${n}.${r}" from its default (${c instanceof Error?c.message:String(c)}); rows written before it read NULL. Run ${u}.`)}},vn=(e,n)=>[[S,n.companionTypes.integer],...Object.entries(e.shape).filter(([,i])=>i._meta?.column!==void 0).map(([i,o])=>[i,x(o,n),o])],kn=async(e,n,i,o)=>{const r=vn(i,o),s="t",a=async l=>{try{return await $(e,o,t`SELECT ${t.join(l.map(u=>rn(s,u)),t`, `)} FROM ${t.identifier(n)} AS ${t.identifier(s)} LIMIT 0`),!0}catch{return!1}};if(!await a(r.map(([l])=>l)))for(const[l,u,c]of r)await a([l])||(await d(e,o,t`ALTER TABLE ${t.identifier(n)} ADD COLUMN ${t.identifier(l)} ${t.raw(u)}`),c!==void 0&&await Un(e,n,i,o,l,c))},xn=(e,n,i)=>{const o=typeof i.charset=="string"?` CHARACTER SET ${i.charset} COLLATE ${String(i.collation)}`:"";return`ALTER TABLE \`${e}\` MODIFY COLUMN \`${n}\` ${String(i.type)}${o} NULL`},Mn=async(e,n,i,o)=>{if(o.name==="sqlite")return;const r=Object.keys(i.shape).filter(s=>{const a=i.shape[s];return a._meta?.column?.notNull===!0&&a.kind!=="optional"&&I(a)});if(r.length!==0)try{const s=o.name==="postgres"?t`column_name AS ${t.identifier("name")}`:t`column_name AS ${t.identifier("name")}, column_type AS ${t.identifier("type")}, character_set_name AS ${t.identifier("charset")}, collation_name AS ${t.identifier("collation")}`,a=o.name==="postgres"?t`table_schema = ANY (current_schemas(false))`:t`table_schema = DATABASE()`,l=await $(e,o,t`SELECT ${s} FROM information_schema.columns WHERE ${a} AND table_name = ${n} AND is_nullable = 'NO' AND column_name IN (${t.join(r.map(u=>t`${u}`),t`, `)})`);for(const u of l){const c=String(u.name);if(o.name==="postgres"){await d(e,o,t`ALTER TABLE ${t.identifier(n)} ALTER COLUMN ${t.identifier(c)} DROP NOT NULL`);continue}L(`${n}.${c}`,`"${n}"."${c}" accepts null in the schema but its column is NOT NULL, so writing null there fails. Relaxing it on MySQL can rebuild the table, so it is not done at startup; run this once, in a maintenance window: ${xn(n,c,u)};`)}}catch(s){L(`${n}:relax-failed`,`could not relax NOT NULL on the null-accepting columns of "${n}" (${r.join(", ")}): ${s instanceof Error?s.message:String(s)}. Writing null to them fails until the constraint is dropped by hand.`)}},Bn=async(e,n,i,o)=>{const r=fn(n,i,o);await d(e,o,t`CREATE TABLE IF NOT EXISTS ${t.identifier(n)} (${r})`),await kn(e,n,i,o),await Mn(e,n,i,o),await Tn(e,n,i,o),await Cn(e,n,i,o),await bn(e,n,i,o)},Qn=(e,n)=>[H(e,n),W(e,n)].filter(i=>i.fields.length>0),zn=async(e,n,i,o)=>{let r=!1;for(const[s,a]of Object.entries(n.tables))a.shardMode?.kind!=="global"||o!==void 0&&!o.has(s)||(r||(r=!0,await hn(e,i,Object.entries(n.tables).filter(([,l])=>l.shardMode?.kind==="global").map(([l])=>l))),await Bn(e,s,a,i))},X=e=>e.shardMode===void 0||e.shardMode.kind==="global",Zn=async(e,n,i)=>{const{integer:o,key:r,real:s}=i.companionTypes;for(const[a,l]of Object.entries(n.tables)){const u=l.aggregateIndexes;if(!(!u||u.length===0||!X(l)))for(const c of u){const f=V(a,c.name);await d(e,i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(f)} (${t.identifier("__key__")} ${t.raw(r)} PRIMARY KEY, ${t.identifier("__value__")} ${t.raw(s)}, ${t.identifier("__count__")} ${t.raw(o)} NOT NULL DEFAULT 0)`),i.name==="sqlite"&&((await $(e,i,t`PRAGMA table_info(${t.identifier(f)})`)).some(w=>w.name==="__count__")||await d(e,i,t`ALTER TABLE ${t.identifier(f)} ADD COLUMN ${t.identifier("__count__")} ${t.raw(o)} NOT NULL DEFAULT 0`))}}},A=(e,n,i,o)=>{const r=e.name==="mysql"&&o?t`${t.identifier(n)}(191)`:t`${t.identifier(n)}`;return t`${r} ${t.raw(i)}`},Fn=(e,n,i)=>{const o=[A(e,"__partition__","ASC",!0)];for(const[r,s]of n.sortBy.entries()){const a=i.shape[s.field],l=a!==void 0&&e.indexKeyPrefix?.(g(a))!==void 0;o.push(A(e,N(r),s.direction==="desc"?"DESC":"ASC",l))}return o.push(A(e,"__id__","ASC",!0)),o},Pn=(e,n,i)=>n.sortBy.map((o,r)=>{const s=i.shape[o.field],a=e.columnType(s?g(s):void 0);return t`${t.identifier(N(r))} ${t.raw(a)}`}),jn=/__sort_k\d+__/gu,Kn=async(e,n,i,o)=>{if(n.name!=="sqlite")return;const s=(await $(e,n,t`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ${i} COLLATE NOCASE`))[0]?.sql;if(typeof s!="string")return;const a=s.match(jn)??[];(a.length!==o.length||a.some((l,u)=>l!==o[u]))&&await d(e,n,t`DROP TABLE ${t.identifier(i)}`)},Jn=async(e,n,i)=>{const{key:o}=i.companionTypes;for(const[r,s]of Object.entries(n.tables)){const a=s.rankIndexes;if(!(!a||a.length===0||!X(s)))for(const l of a){const u=q-4;if(l.sortBy.length>u)throw new O("BAD_REQUEST",`rank index "${l.name}" on ${r} has ${String(l.sortBy.length)} sort keys; at most ${String(u)} fit the ${String(q)} parameters one statement binds`);const c=Q(r,l.name),f=Pn(i,l,s);await Kn(e,i,c,l.sortBy.map((Gn,Y)=>N(Y)));const E=f.length>0?t`, ${t.join(f,t`, `)}`:t``;await d(e,i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(c)} (${t.identifier("__id__")} ${t.raw(o)} PRIMARY KEY, ${t.identifier("__partition__")} ${t.raw(o)} NOT NULL${E})`);const w=Fn(i,l,s),_=`${r}__rank_${l.name}__btree`,T={columns:t.join(w,t`, `),name:_,refs:[],table:c,unique:!1};await j(e,i,T),await y(e,i,T)}}};export{p as INDEX_LEDGER_TABLE,C as MIGRATION_STATE_TABLE,mn as declaredIndexColumnList,h as foldIdentifier,fn as globalTableColumnsDdl,En as globalTableIndexSpecs,P as indexColumnList,wn as indexLedgerDdl,$n as indexShapeChanged,Qn as legacyRewrites,On as legacyRowPredicate,Bn as provisionGlobalTable,zn as provisionGlobalTablesSequentially,K as recordIndexStatement,Zn as runSqlAggregateMigrations,Jn as runSqlRankMigrations,pn as undeclaredFrameworkIndexes,vn as wantedGlobalColumns};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as a}from"drizzle-orm";import{provisionGlobalTablesSequentially as m,foldIdentifier as c,globalTableColumnsDdl as A,globalTableIndexSpecs as L,legacyRewrites as O,indexLedgerDdl as R,wantedGlobalColumns as k,undeclaredFrameworkIndexes as y,indexShapeChanged as $,INDEX_LEDGER_TABLE as T,MIGRATION_STATE_TABLE as E,recordIndexStatement as M,legacyRowPredicate as C}from"./runSqlAggregateMigrations-
|
|
1
|
+
import{sql as a}from"drizzle-orm";import{provisionGlobalTablesSequentially as m,foldIdentifier as c,globalTableColumnsDdl as A,globalTableIndexSpecs as L,legacyRewrites as O,indexLedgerDdl as R,wantedGlobalColumns as k,undeclaredFrameworkIndexes as y,indexShapeChanged as $,INDEX_LEDGER_TABLE as T,MIGRATION_STATE_TABLE as E,recordIndexStatement as M,legacyRowPredicate as C}from"./runSqlAggregateMigrations-CvZiVJ9S.mjs";import{a as q,q as g}from"./sql-exec-ChIYvWnI.mjs";const v=50,h=new Map([["'","'"],["[","]"],["`","`"],['"','"']]),N=/^[\w$]+/u,b=(e,s)=>{const n=h.get(e[s]);let t=s+1;for(;t<e.length;)if(e[t]!==n)t+=1;else if(n!=="]"&&e[t+1]===n)t+=2;else return t+1;return t},_=e=>{const s=e.trim(),n=h.get(s[0]??"");if(n===void 0)return N.exec(s)?.[0];const t=b(s,0),r=s.slice(1,s[t-1]===n?t-1:t);return n==="]"?r:r.replaceAll(`${n}${n}`,n)},B=e=>{const s=new Set,n=i=>{const d=_(i);d!==void 0&&s.add(d)};let t=0,r=0,o=0;for(;o<e.length;){const i=e[o];if(h.has(i)){o=b(e,o);continue}if(i==="(")t+=1,r=t===1?o+1:r;else if(i===")"){if(t-=1,t===0)return n(e.slice(r,o)),s}else i===","&&t===1&&(n(e.slice(r,o)),r=o+1);o+=1}return s},F=async(e,s,n)=>{const t=new Set,r=new Map,o=n.has(c(T)),i=[];if(n.has(c(E))&&i.push(a`SELECT 'marker' AS kind, name, NULL AS owner FROM ${a.identifier(E)}`),o&&i.push(a`SELECT 'index' AS kind, "l"."name" AS name, "l"."table_name" AS owner FROM ${a.identifier(T)} AS "l"`),i.length===0)return{hasLedger:o,markers:t,owned:r};for(const d of await g(e,s,a.join(i,a` UNION ALL `)))if(d.kind==="marker")t.add(String(d.name));else{const f=c(String(d.owner));r.set(f,[...r.get(f)??[],String(d.name)])}return{hasLedger:o,markers:t,owned:r}},D=async(e,s)=>{try{const n=await g(e,s,a`SELECT type, name, tbl_name, sql FROM sqlite_master WHERE type IN ('table', 'index')`),t=new Set,r=new Map,o=new Map;for(const l of n){const u=String(l.name);if(u.startsWith("sqlite_"))continue;const S=typeof l.sql=="string"?l.sql:void 0;l.type==="table"?(t.add(c(u)),r.set(c(u),new Set([...S===void 0?[]:B(S)].map(I=>c(I))))):o.set(c(u),S)}const{hasLedger:i,markers:d,owned:f}=await F(e,s,t);return{columns:r,hasLedger:i,indexes:o,markers:d,owned:f,tables:t}}catch{return}},w=e=>e.kind==="default-order"?[]:[M(e.name,e.table)],p=e=>{const s=e.unique?a`UNIQUE `:a``;return a`CREATE ${s}INDEX IF NOT EXISTS ${a.identifier(e.name)} ON ${a.identifier(e.table)} (${e.columns})`},x=(e,s,n)=>n.length===0?[]:[a`CREATE TABLE IF NOT EXISTS ${a.identifier(E)} (${a.identifier("name")} ${a.raw(e.companionTypes.key)} PRIMARY KEY)`,...n.map(t=>a`INSERT OR IGNORE INTO ${a.identifier(E)} (${a.identifier("name")}) SELECT ${t.marker} WHERE NOT EXISTS (SELECT 1 FROM ${a.identifier(s)} WHERE ${C(t)})`)],G=(e,s,n,t)=>{const r=A(e,s,n),o=L(e,s,n),i=O(e,s);if(!t.tables.has(c(e)))return[...t.hasLedger?[]:[R()],a`CREATE TABLE IF NOT EXISTS ${a.identifier(e)} (${r})`,...o.flatMap(l=>[p(l),...w(l)]),...x(n,e,i)];const d=t.columns.get(c(e))??new Set;if(k(s,n).some(([l])=>!d.has(c(l)))||i.some(l=>!t.markers.has(l.marker))||y(n,o,t.owned.get(c(e))??[]).length>0)return;const f=[];for(const l of o){if(!t.indexes.has(c(l.name))){f.push(p(l),...w(l));continue}const u=t.indexes.get(c(l.name));if(l.kind==="declared"&&typeof u=="string"&&$(n,u,l))return}return f},X=e=>{const s=[];let n=[],t=0;for(const r of e)n.length>0&&t+r.statements.length>v&&(s.push(n),n=[],t=0),n.push(r),t+=r.statements.length;return n.length>0&&s.push(n),s},U=(e,s)=>!s.hasLedger&&Object.entries(e.tables).some(([n,t])=>t.shardMode?.kind==="global"&&s.tables.has(c(n))),Q=async(e,s,n)=>{if(!e.batch||n.name!=="sqlite"){await m(e,s,n);return}const t=await D(e,n);if(t===void 0){await m(e,s,n);return}if(U(s,t)){await m(e,s,n);return}const r=[],o=new Set;for(const[i,d]of Object.entries(s.tables)){if(d.shardMode?.kind!=="global")continue;const f=G(i,d,n,t);f===void 0?o.add(i):f.length>0&&r.push({statements:f,table:i})}for(const i of X(r))try{await q(e,n,i.flatMap(d=>d.statements))}catch{for(const d of i)o.add(d.table)}await m(e,s,n,o)};export{B as columnNamesOfCreateTable,Q as runSqlGlobalTableMigrations};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{needsWireEncoding as J}from"@lunora/wire";import{sql as e,SQL as v}from"drizzle-orm";import{a as A,s as x,e as U}from"./value-codec-C52YW-Do.mjs";const W=t=>{if(t===null||typeof t!="object")return!1;const n=Object.getPrototypeOf(t);return n===null||n===Object.prototype},p=4;class T extends Error{}const S=t=>t.includes("."),w=t=>{const n=t.split(".");if(n.length>p||n.includes(""))throw new T(`field path "${t}" must have 1 to ${String(p)} non-empty segments`);return n},it=(t,n)=>{if(!S(n))return t[n];let s=t;for(const r of w(n)){if(!W(s)||!Object.hasOwn(s,r))return;s=s[r]}return s},B={boolean:"'true', 'false'",number:"'integer', 'real'",string:"'text'"},X=/^[A-Za-z_$][\w$]*$/u,R=t=>X.test(t)?t:`"${t.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,at="_version",ct=100,I=t=>t==="_id"||t==="id"?"id":t,$=t=>e`${e.identifier(I(t))}`,C=t=>{try{return w(t)}catch(n){throw n instanceof T?new g("VALIDATION_ERROR",n.message):n}},q=new WeakMap,lt=t=>q.get(t),b=(t,n)=>{let s=e`${t}::jsonb`;for(const r of n)s=e`${s} -> ${r}::text`;return e`NULLIF(${s}, 'null'::jsonb)`},k=(t,n)=>e`CASE WHEN pg_input_is_valid(${t}, 'jsonb') THEN ${b(t,n)} END`,K=(t,n)=>e`CASE WHEN pg_input_is_valid(${t}, 'jsonb') THEN ${b(t,n)} #>> '{}' END`,L=(t,n)=>{const s=`$${n.map(r=>`.${R(r)}`).join("")}`;return e`NULLIF(JSON_EXTRACT(${t}, ${s}), CAST('null' AS JSON))`},V=(t,n)=>e`CASE WHEN JSON_VALID(${t}) THEN ${L(t,n)} END`,z=(t,n)=>e`CASE WHEN JSON_VALID(${t}) THEN JSON_UNQUOTE(${L(t,n)}) END`,ut=(t,n)=>t==="postgres"?e`(${n})::jsonb #>> '{}'`:e`JSON_UNQUOTE(${n})`,y=(t,n)=>{const[s="",...r]=C(n),o=$(s);return e`CASE WHEN json_valid(${o}) THEN ${e.raw(t)}(${o}, ${`$.${r.map(i=>R(i)).join(".")}`}) END`},G=(t,n)=>{if(!S(n))return $(n);if(t.name==="sqlite")return y("json_extract",n);const[s="",...r]=C(n),o=$(s),i=t.name==="postgres",a=i?k(o,r):V(o,r);return q.set(a,i?K(o,r):z(o,r)),a},D=new WeakMap,M=t=>e`CAST(CAST(${t} AS text) AS jsonb)`,dt=(t,n,s)=>{if(t.name==="sqlite")return e`NULLIF(${y("json_type",n)}, 'null') IN (${e.raw(B[s])})`;const r=G(t,n);if(t.name==="postgres")return e`jsonb_typeof(${r}) = ${e.raw(`'${s}'`)}`;const o={boolean:"'BOOLEAN'",number:"'INTEGER', 'UNSIGNED INTEGER', 'DOUBLE', 'DECIMAL'",string:"'STRING'"}[s];return e`JSON_TYPE(${r}) IN (${e.raw(o)})`},Q=(t,n)=>{if(n===void 0)return n;if(typeof n=="bigint"||J(n))return t==="postgres"?e`CAST(NULL AS jsonb)`:e`CAST(NULL AS JSON)`;const s=JSON.stringify(n),r=t==="postgres"?e`${M(s)}`:e`CAST(${s} AS JSON)`;return D.set(r,s),r},ft=(t,n,s,r)=>{const o=[];let i=!1;for(const u of s){if(u===void 0)throw new g("BAD_REQUEST","an `in` list holds an undefined value");const d=u instanceof v?D.get(u):void 0;d===void 0?i=!0:o.push(d)}if(o.length===0||r&&i)return e`1 = 0`;const a=`[${o.join(",")}]`,c=t==="postgres"?e`SELECT e.v FROM jsonb_array_elements(${M(a)}) AS e(v)`:e`SELECT jt.v FROM JSON_TABLE(${a}, '$[*]' COLUMNS (v JSON PATH '$')) AS jt`;return r?e`${n} NOT IN (${c})`:e`${n} IN (${c})`},Et=(t,n,s,r)=>t.name==="sqlite"||!S(n)||s===null?r(s):Q(t.name,s),$t=(t,n)=>e`${e.identifier(t)}.${e.identifier(I(n))}`,mt=t=>{const n=[];for(const[s,r]of Object.entries(t.shape)){const o=r._meta?.column;o&&n.push([s,o])}return n},f=(t,n,s)=>{const{params:r,sql:o}=n.render(s);return t.all(o,r)},l=(t,n,s)=>{const{params:r,sql:o}=n.render(s);return t.run(o,r)},St=(t,n,s)=>t==="postgres"?e`${n} IS NOT DISTINCT FROM ${s}`:t==="mysql"?e`${n} <=> ${s}`:e`${n} IS ${s}`,Nt={sql:t=>e`COALESCE(${t}, 0) + 1`,value:t=>(t==null?0:Number(t))+1},pt=async(t,n,s)=>{if(s.length!==0){if(!t.batch){for(const r of s)await l(t,n,r);return}await t.batch(s.map(r=>n.render(r)))}},_t=async(t,n,s)=>{if(t.batch&&n.name==="sqlite"){await t.batch(s.map(r=>n.render(r)));return}for(const r of s)await l(t,n,r)},Ot=async(t,n,s)=>{const r=s.unique?e`UNIQUE `:e``,o=s.concurrently===!0&&n.name==="postgres"?e`CONCURRENTLY `:e``;if(n.name==="mysql"){try{await l(t,n,e`CREATE ${r}INDEX ${e.identifier(s.name)} ON ${e.identifier(s.table)} (${s.columns})`)}catch(i){const a=i;if(a.errno!==1061&&a.code!=="ER_DUP_KEYNAME"&&a.code!==1061)throw i}return}await l(t,n,e`CREATE ${r}INDEX ${o}IF NOT EXISTS ${e.identifier(s.name)} ON ${e.identifier(s.table)} (${s.columns})`)},j=(t,n)=>e`(SELECT ${e.identifier("c")}.oid FROM pg_index ${e.identifier("i")} JOIN pg_class ${e.identifier("c")} ON ${e.identifier("c")}.oid = ${e.identifier("i")}.indexrelid WHERE ${e.identifier("i")}.indrelid = to_regclass(quote_ident(${t})) AND ${e.identifier("c")}.relname = ${n}::name)`,ht=async(t,n,s,r)=>{if(n.name==="postgres"){const[o]=await f(t,n,e`SELECT quote_ident(${e.identifier("n")}.nspname) || '.' || quote_ident(${e.identifier("c")}.relname) AS ${e.identifier("qualified")} FROM pg_class ${e.identifier("c")} JOIN pg_namespace ${e.identifier("n")} ON ${e.identifier("n")}.oid = ${e.identifier("c")}.relnamespace WHERE ${e.identifier("c")}.oid = ${j(s,r)}`),i=o?.qualified;typeof i=="string"&&await l(t,n,e`DROP INDEX IF EXISTS ${e.raw(i)}`);return}if(n.name!=="mysql"){await l(t,n,e`DROP INDEX IF EXISTS ${e.identifier(r)}`);return}try{await l(t,n,e`DROP INDEX ${e.identifier(r)} ON ${e.identifier(s)}`)}catch(o){const i=o;if(i.errno!==1091&&i.code!=="ER_CANT_DROP_FIELD_OR_KEY"&&i.code!==1091)throw o}},gt=async(t,n,s,r)=>{switch(n.name){case"mysql":return(await f(t,n,e`SELECT 1 AS ${e.identifier("present")} FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ${s} AND index_name = ${r} LIMIT 1`)).length>0?"valid":"absent";case"postgres":{const o=await f(t,n,e`SELECT indisvalid FROM pg_index WHERE indexrelid = ${j(s,r)}`);return o.length===0?"absent":o[0]?.indisvalid===!0?"valid":"invalid"}default:return(await f(t,n,e`SELECT 1 AS ${e.identifier("present")} FROM sqlite_master WHERE type = 'index' AND name = ${r}`)).length>0?"valid":"absent"}},At=A,m=t=>{if(t===void 0)return!1;if(t._meta?.column?.notNull===!1)return!0;switch(t.kind){case"any":case"null":return!0;case"literal":return t._meta?.value===null;case"optional":return m(t._meta?.inner);case"union":return t._meta?.members?.some(n=>m(n))===!0;default:return!1}},Y=t=>t.kind==="optional"&&!m(t),_=new WeakMap,P=t=>{let n=_.get(t);return n===void 0&&(n=Object.entries(t.shape).map(([s,r])=>[s,U(r),Y(r)]),_.set(t,n)),n},O=new WeakMap,Z=(t,n)=>{let s=O.get(t);return s===void 0&&(s=new Map(P(t).map(([r,o])=>[r,o])),O.set(t,s)),s.get(n)},Tt=(t,n,s)=>A(s,Z(t,n)),tt=(t,n)=>{const s={};for(const[r,o,i]of P(t)){const a=n[r];a===void 0||i&&a===null||(s[r]=x(a,o))}return s._id=n.id,s._creationTime=n._creationTime,s},F=(t,n)=>n?tt(t,n):null,wt=(t,n)=>{const s=[];for(const r of n){const o=F(t,r);o&&s.push(o)}return s},h=500,nt=(t,n,s,r,o)=>{const i=e`${e.identifier(s)}.${e.identifier("id")}`,a=r===void 0?e``:e` WHERE ${i} > ${r}`;return f(t,n,e`SELECT * FROM ${e.identifier(s)}${a} ORDER BY ${i} ASC LIMIT ${e.raw(String(o))}`)},Rt=async(t,n,s,r,o,i={})=>{let a=i.after,c=i.limit,u=!0;for(;u&&(c===void 0||c>0);){const d=c===void 0?h:Math.min(h,c),E=await nt(t,n,r,a,d);for(const H of E){const N=F(s,H);N&&await o(N)}a=E.at(-1)?.id,u=E.length===d,c=c===void 0?void 0:c-E.length}};export{h as B,ct as M,at as O,_t as a,
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{needsWireEncoding as J}from"@lunora/wire";import{sql as e,SQL as v}from"drizzle-orm";import{a as A,s as x,e as U}from"./value-codec-C52YW-Do.mjs";const W=t=>{if(t===null||typeof t!="object")return!1;const n=Object.getPrototypeOf(t);return n===null||n===Object.prototype},p=4;class T extends Error{}const S=t=>t.includes("."),w=t=>{const n=t.split(".");if(n.length>p||n.includes(""))throw new T(`field path "${t}" must have 1 to ${String(p)} non-empty segments`);return n},it=(t,n)=>{if(!S(n))return t[n];let s=t;for(const r of w(n)){if(!W(s)||!Object.hasOwn(s,r))return;s=s[r]}return s},B={boolean:"'true', 'false'",number:"'integer', 'real'",string:"'text'"},X=/^[A-Za-z_$][\w$]*$/u,R=t=>X.test(t)?t:`"${t.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,at="_version",ct=100,I=t=>t==="_id"||t==="id"?"id":t,$=t=>e`${e.identifier(I(t))}`,C=t=>{try{return w(t)}catch(n){throw n instanceof T?new g("VALIDATION_ERROR",n.message):n}},q=new WeakMap,lt=t=>q.get(t),b=(t,n)=>{let s=e`${t}::jsonb`;for(const r of n)s=e`${s} -> ${r}::text`;return e`NULLIF(${s}, 'null'::jsonb)`},k=(t,n)=>e`CASE WHEN pg_input_is_valid(${t}, 'jsonb') THEN ${b(t,n)} END`,K=(t,n)=>e`CASE WHEN pg_input_is_valid(${t}, 'jsonb') THEN ${b(t,n)} #>> '{}' END`,L=(t,n)=>{const s=`$${n.map(r=>`.${R(r)}`).join("")}`;return e`NULLIF(JSON_EXTRACT(${t}, ${s}), CAST('null' AS JSON))`},V=(t,n)=>e`CASE WHEN JSON_VALID(${t}) THEN ${L(t,n)} END`,z=(t,n)=>e`CASE WHEN JSON_VALID(${t}) THEN JSON_UNQUOTE(${L(t,n)}) END`,ut=(t,n)=>t==="postgres"?e`(${n})::jsonb #>> '{}'`:e`JSON_UNQUOTE(${n})`,y=(t,n)=>{const[s="",...r]=C(n),o=$(s);return e`CASE WHEN json_valid(${o}) THEN ${e.raw(t)}(${o}, ${`$.${r.map(i=>R(i)).join(".")}`}) END`},G=(t,n)=>{if(!S(n))return $(n);if(t.name==="sqlite")return y("json_extract",n);const[s="",...r]=C(n),o=$(s),i=t.name==="postgres",a=i?k(o,r):V(o,r);return q.set(a,i?K(o,r):z(o,r)),a},D=new WeakMap,M=t=>e`CAST(CAST(${t} AS text) AS jsonb)`,dt=(t,n,s)=>{if(t.name==="sqlite")return e`NULLIF(${y("json_type",n)}, 'null') IN (${e.raw(B[s])})`;const r=G(t,n);if(t.name==="postgres")return e`jsonb_typeof(${r}) = ${e.raw(`'${s}'`)}`;const o={boolean:"'BOOLEAN'",number:"'INTEGER', 'UNSIGNED INTEGER', 'DOUBLE', 'DECIMAL'",string:"'STRING'"}[s];return e`JSON_TYPE(${r}) IN (${e.raw(o)})`},Q=(t,n)=>{if(n===void 0)return n;if(typeof n=="bigint"||J(n))return t==="postgres"?e`CAST(NULL AS jsonb)`:e`CAST(NULL AS JSON)`;const s=JSON.stringify(n),r=t==="postgres"?e`${M(s)}`:e`CAST(${s} AS JSON)`;return D.set(r,s),r},ft=(t,n,s,r)=>{const o=[];let i=!1;for(const u of s){if(u===void 0)throw new g("BAD_REQUEST","an `in` list holds an undefined value");const d=u instanceof v?D.get(u):void 0;d===void 0?i=!0:o.push(d)}if(o.length===0||r&&i)return e`1 = 0`;const a=`[${o.join(",")}]`,c=t==="postgres"?e`SELECT e.v FROM jsonb_array_elements(${M(a)}) AS e(v)`:e`SELECT jt.v FROM JSON_TABLE(${a}, '$[*]' COLUMNS (v JSON PATH '$')) AS jt`;return r?e`${n} NOT IN (${c})`:e`${n} IN (${c})`},Et=(t,n,s,r)=>t.name==="sqlite"||!S(n)||s===null?r(s):Q(t.name,s),$t=(t,n)=>e`${e.identifier(t)}.${e.identifier(I(n))}`,mt=t=>{const n=[];for(const[s,r]of Object.entries(t.shape)){const o=r._meta?.column;o&&n.push([s,o])}return n},f=(t,n,s)=>{const{params:r,sql:o}=n.render(s);return t.all(o,r)},l=(t,n,s)=>{const{params:r,sql:o}=n.render(s);return t.run(o,r)},St=(t,n,s)=>t==="postgres"?e`${n} IS NOT DISTINCT FROM ${s}`:t==="mysql"?e`${n} <=> ${s}`:e`${n} IS ${s}`,Nt={sql:t=>e`COALESCE(${t}, 0) + 1`,value:t=>(t==null?0:Number(t))+1},pt=async(t,n,s)=>{if(s.length!==0){if(!t.batch){for(const r of s)await l(t,n,r);return}await t.batch(s.map(r=>n.render(r)))}},_t=async(t,n,s)=>{if(t.batch&&n.name==="sqlite"){await t.batch(s.map(r=>n.render(r)));return}for(const r of s)await l(t,n,r)},Ot=async(t,n,s)=>{const r=s.unique?e`UNIQUE `:e``,o=s.concurrently===!0&&n.name==="postgres"?e`CONCURRENTLY `:e``;if(n.name==="mysql"){try{await l(t,n,e`CREATE ${r}INDEX ${e.identifier(s.name)} ON ${e.identifier(s.table)} (${s.columns})`)}catch(i){const a=i;if(a.errno!==1061&&a.code!=="ER_DUP_KEYNAME"&&a.code!==1061)throw i}return}await l(t,n,e`CREATE ${r}INDEX ${o}IF NOT EXISTS ${e.identifier(s.name)} ON ${e.identifier(s.table)} (${s.columns})`)},j=(t,n)=>e`(SELECT ${e.identifier("c")}.oid FROM pg_index ${e.identifier("i")} JOIN pg_class ${e.identifier("c")} ON ${e.identifier("c")}.oid = ${e.identifier("i")}.indexrelid WHERE ${e.identifier("i")}.indrelid = to_regclass(quote_ident(${t})) AND ${e.identifier("c")}.relname = ${n}::name)`,ht=async(t,n,s,r)=>{if(n.name==="postgres"){const[o]=await f(t,n,e`SELECT quote_ident(${e.identifier("n")}.nspname) || '.' || quote_ident(${e.identifier("c")}.relname) AS ${e.identifier("qualified")} FROM pg_class ${e.identifier("c")} JOIN pg_namespace ${e.identifier("n")} ON ${e.identifier("n")}.oid = ${e.identifier("c")}.relnamespace WHERE ${e.identifier("c")}.oid = ${j(s,r)}`),i=o?.qualified;typeof i=="string"&&await l(t,n,e`DROP INDEX IF EXISTS ${e.raw(i)}`);return}if(n.name!=="mysql"){await l(t,n,e`DROP INDEX IF EXISTS ${e.identifier(r)}`);return}try{await l(t,n,e`DROP INDEX ${e.identifier(r)} ON ${e.identifier(s)}`)}catch(o){const i=o;if(i.errno!==1091&&i.code!=="ER_CANT_DROP_FIELD_OR_KEY"&&i.code!==1091)throw o}},gt=async(t,n,s,r)=>{switch(n.name){case"mysql":return(await f(t,n,e`SELECT 1 AS ${e.identifier("present")} FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ${s} AND index_name = ${r} LIMIT 1`)).length>0?"valid":"absent";case"postgres":{const o=await f(t,n,e`SELECT indisvalid FROM pg_index WHERE indexrelid = ${j(s,r)}`);return o.length===0?"absent":o[0]?.indisvalid===!0?"valid":"invalid"}default:return(await f(t,n,e`SELECT 1 AS ${e.identifier("present")} FROM sqlite_master WHERE type = 'index' AND name = ${r}`)).length>0?"valid":"absent"}},At=A,m=t=>{if(t===void 0)return!1;if(t._meta?.column?.notNull===!1)return!0;switch(t.kind){case"any":case"null":return!0;case"literal":return t._meta?.value===null;case"optional":return m(t._meta?.inner);case"union":return t._meta?.members?.some(n=>m(n))===!0;default:return!1}},Y=t=>t.kind==="optional"&&!m(t),_=new WeakMap,P=t=>{let n=_.get(t);return n===void 0&&(n=Object.entries(t.shape).map(([s,r])=>[s,U(r),Y(r)]),_.set(t,n)),n},O=new WeakMap,Z=(t,n)=>{let s=O.get(t);return s===void 0&&(s=new Map(P(t).map(([r,o])=>[r,o])),O.set(t,s)),s.get(n)},Tt=(t,n,s)=>A(s,Z(t,n)),tt=(t,n)=>{const s={};for(const[r,o,i]of P(t)){const a=n[r];a===void 0||i&&a===null||(s[r]=x(a,o))}return s._id=n.id,s._creationTime=n._creationTime,s},F=(t,n)=>n?tt(t,n):null,wt=(t,n)=>{const s=[];for(const r of n){const o=F(t,r);o&&s.push(o)}return s},h=500,nt=(t,n,s,r,o)=>{const i=e`${e.identifier(s)}.${e.identifier("id")}`,a=r===void 0?e``:e` WHERE ${i} > ${r}`;return f(t,n,e`SELECT * FROM ${e.identifier(s)}${a} ORDER BY ${i} ASC LIMIT ${e.raw(String(o))}`)},Rt=async(t,n,s,r,o,i={})=>{let a=i.after,c=i.limit,u=!0;for(;u&&(c===void 0||c>0);){const d=c===void 0?h:Math.min(h,c),E=await nt(t,n,r,a,d);for(const H of E){const N=F(s,H);N&&await o(N)}a=E.at(-1)?.id,u=E.length===d,c=c===void 0?void 0:c-E.length}};export{h as B,ct as M,at as O,_t as a,ut as b,l as c,tt as d,Ot as e,ht as f,ft as g,F as h,gt as i,$ as j,wt as k,At as l,G as m,St as n,Nt as o,lt as p,f as q,nt as r,Tt as s,mt as t,it as u,Et as v,dt as w,Rt as x,pt as y,$t as z};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/sql-store",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.227",
|
|
4
4
|
"description": "Internal dialect-parameterized SQL store core for Lunora .global() backends (D1, PlanetScale)",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -51,8 +51,8 @@
|
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
53
|
"@lunora/errors": ">=1.0.0-alpha.77 <2.0.0-0",
|
|
54
|
-
"@lunora/shard-engine": "1.0.0-alpha.
|
|
55
|
-
"@lunora/wire": "1.0.0-alpha.
|
|
54
|
+
"@lunora/shard-engine": "1.0.0-alpha.179",
|
|
55
|
+
"@lunora/wire": "1.0.0-alpha.6",
|
|
56
56
|
"drizzle-orm": "1.0.0-rc.5"
|
|
57
57
|
},
|
|
58
58
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./ctx-db-search-state-C4l9QBq-.mjs";import{b as S,c as s,a as i,r as l}from"./ctx-db-search-D_0SkyeY.mjs";import"./sql-exec-CkHeSf_v.mjs";export{S as backfillSqlSearchIndexes,s as createSearchSync,i as runSqlSearch,l as runSqlSearchMigrations};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{m as yn,q as Rn}from"./ctx-db-search-state-C4l9QBq-.mjs";import{c as Sn,r as gn,A as mn,C as Tn,R as vn,u as In,a as An,T as Cn,x as Ln,d as bn}from"./ctx-db-search-D_0SkyeY.mjs";import{throwingScheduler as Nn,describeRelationWrites as Mn,CDC_LOG_TABLE as D,cdcForkedError as On,cursorBelowRetainedFloor as qn,cdcTrimmedError as kn,serverInList as Dn,assertNoExplicitUndefined as Ke,hasTrigger as Bn,runRowValidators as Ge,assertFlatPredicate as Et,mergeWhere as F,rankTableName as _e,sortColumnName as Re,resolveRankPartition as pt,encodePartitionKey as Me,resolveRankSeekTuple as Wn,RANK_TIEBREAK as Se,CountRlsUnsupportedError as yt,compileWhereSql as z,ConflictError as ae,patchDependsOnRow as Fn,normalizeIdStructurally as Un,applyInsertDefaults as xn,assertValidClientId as Pn,assertStorableRowId as Hn,aggregateSqlFunction as Ee,softDeleteScope as Oe,resolveWith as Rt,relationHooks as St,applySelect as gt,encodeCursor as jn,NotFoundError as Kn,applyOnDelete as Gn,normalizeCountArgument as Vn,selectIndexForCount as Yn,encodeAggregateKey as J,aggregateTableName as ie,selectIndexForAggregate as Xn,readAggregateValue as Ve,runTriggers as Qn,nullsOrderSuffix as mt,nullsFirstOf as Tt,rankPivotConditionSql as Ht,CURSOR_PREFIX as zn,resolvePatch as Jn,stripReservedPatchFields as Zn,assertPatchAllowed as ei,resolveRelationPredicates as ti,selectIndexForGroupBy as ni,composeReadPredicate as ii,fanOutScalarCounts as oi,whereOfFilter as ri,isPushableWhere as si,matchesRankStaticWhere as vt,tiebreakDirectionFor as ai,matchesStaticWhere as Ye,coerceAggregateNumber as Xe,foldAggregateTally as It,CDC_LOG_TABLE_SEQ_INDEX as ci,NotUniqueError as di,WORKERD_SQLITE_LIMITS as li}from"@lunora/shard-engine";import{parseWire as ui,needsWireEncoding as jt,encodeWire as Kt,decodeWire as fi}from"@lunora/wire";import{sql as e,SQL as wi}from"drizzle-orm";import{p as At,h as Ct,q as I,b as x,c as Gt,i as $i,j as hi,k as _i,l as X,s as oe,O as pe,e as U,m as Lt,t as Ei,a as pi,n as bt,o as Be,u as ot,v as Nt,w as yi,x as Qe,y as Mt,B as ze,z as Ot,g as qt}from"./sql-exec-CkHeSf_v.mjs";import{d as So}from"./sql-exec-CkHeSf_v.mjs";import{runSqlGlobalTableMigrations as Ri}from"./runSqlGlobalTableMigrations-C7teG_kd.mjs";import{runSqlAggregateMigrations as Si,runSqlRankMigrations as gi}from"./runSqlAggregateMigrations-5fjwAdYh.mjs";import{s as Vt,e as Yt}from"./value-codec-C52YW-Do.mjs";const mi=(r,a)=>{if(r.size<a)return;const u=r.keys().next().value;u!==void 0&&r.delete(u)},kt=50,Ti=(r,a={})=>{const u=a.maxBatch??kt,c=Number.isInteger(u)&&u>0?u:kt,R=new Map;let f=!1;const d=async(T,A)=>{const v=[...A.keys()];for(let L=0;L<v.length;L+=c){const b=v.slice(L,L+c);try{const q=await r(T,b);for(const K of b){const Q=q.get(K);for(const Z of A.get(K)??[])Z.resolve(Q)}}catch(q){for(const K of b)for(const Q of A.get(K)??[])Q.reject(q)}}},O=()=>{f=!1;const T=[...R.entries()];R.clear();for(const[A,v]of T)d(A,v).catch(()=>{})};return{async load(T,A){return new Promise((v,L)=>{let b=R.get(T);b||(b=new Map,R.set(T,b));const q=b.get(A);q?q.push({reject:L,resolve:v}):b.set(A,[{reject:L,resolve:v}]),f||(f=!0,queueMicrotask(O))})}}},vi=new Set(["_id","id"]),Ii=r=>{throw new g("INTERNAL",`no ORDER BY NULL placement for dialect "${String(r)}"`)},Xt=(r,a)=>{const u=a.direction==="desc"?"DESC":"ASC",c=a.nullable===!0,R=f=>e`${Be(r,a.field)} ${e.raw(`${u}${f}`)}`;switch(r.name){case"mysql":{const f=R("");return!c||a.nulls===void 0?[f]:[e`(${Be(r,a.field)} IS NULL) ${e.raw(a.nulls==="first"?"DESC":"ASC")}`,f]}case"postgres":return[R(c?mt(Tt(a)):"")];case"sqlite":return[R(c&&a.nulls!==void 0?mt(Tt(a)):"")];default:return Ii(r.name)}},Ai=(r,a)=>{const u=r.flatMap(c=>Xt(a,c));if(!r.some(c=>vi.has(c.field))){const c=ai(r);u.push(e`${U("id")} ${e.raw(c==="desc"?"DESC":"ASC")}`)}return e.join(u,e`, `)},Dt=50,Ci=r=>{const a=r.detail??r["QUERY PLAN"];return typeof a=="string"?a:Object.values(r).map(String).join(" | ")},Je=(r,a,u,c)=>{for(const[R,f]of Ei(r)){if(f.serverDefault){R in a&&(u[R]=f.serverDefault({auth:c}));continue}f.onUpdateFn&&!(R in a)&&(u[R]=f.onUpdateFn())}},Li=128,bi=()=>{const r=new Map;return{delete:a=>{r.delete(a)},get:a=>{const u=r.get(a);if(u!==void 0)return r.delete(a),r.set(a,u),u},set:(a,u)=>{r.has(a)?r.delete(a):mi(r,Li),r.set(a,u)}}},Qt=r=>r.shardMode===void 0||r.shardMode.kind==="global",Ni=async(r,a,u,c,R)=>{const f=R.get(c);if(f!==void 0)return f;const d=Object.entries(u.tables).filter(([,T])=>Qt(T)).map(([T])=>T),O=await Promise.all(d.map(async T=>({found:(await I(r,a,e`SELECT 1 FROM ${e.identifier(T)} WHERE ${e.identifier("id")} = ${c} LIMIT 1`)).length>0,tableName:T})));for(const T of O)if(T.found)return R.set(c,T.tableName),T.tableName},ce=r=>r==null?null:Number(r),Mi=(r,a,u)=>u.map(c=>{const R={};for(const f of a){const d=r.shape[f];R[f]=Vt(c[f]??null,d&&Yt(d))}return{key:R,value:ce(c.value)}}),Oi=(r,a,u)=>[...r.partitionBy??[],...r.sortBy.map(R=>R.field),...r.where?Object.keys(r.where):[]].every(R=>Mt(a,R)===Mt(u,R)),zt=r=>r.length===1?r[0]:e`(${e.join(r,e` AND `)})`,re=r=>e.join(r.map(a=>e`${e.identifier(a)}`),e`, `),de=r=>e.join(r.map(a=>e`${a}`),e`, `),Ze=(r,a)=>{if(r==="postgres"){for(const[u,c]of Object.entries(a))if(typeof c=="string"&&c.includes("\0"))throw new g("BAD_REQUEST",`"${u}" holds a NUL character (U+0000), which a Postgres text column cannot store`)}},We=r=>r instanceof ArrayBuffer?new Uint8Array(r):Array.isArray(r)?Uint8Array.from(r):r,qi=(r,a,u,c,R)=>{const f=[];for(let d=0;d<u.length+1;d+=1){const O=u[d],T=a.sortBy[d],A=d<u.length&&O!==void 0&&T!==void 0,v=T?.direction==="desc"?"desc":"asc",L=A?Ht(O,We(c[O]),v,!1):e`${e.identifier(Se)} < ${R}`;if(L===void 0)continue;const b=u.slice(0,d).map(q=>ot(r,e`${e.identifier(q)}`,We(c[q])));b.push(L),f.push(zt(b))}return f.length>0?e.join(f,e` OR `):e`1 = 0`},ki=(r,a,u)=>{if(u.length!==a.length)return;const c=[];for(const[R,f]of a.entries()){const d=Ht(f.column,We(u[R]),f.direction,!0);if(d===void 0)continue;const O=[];for(let T=0;T<R;T+=1){const A=a[T];A!==void 0&&O.push(ot(r,e`${e.identifier(A.column)}`,We(u[T])))}O.push(d),c.push(zt(O))}return c.length===0?e`(1 = 0)`:e`(${e.join(c,e` OR `)})`},Di=(r,a)=>{if(r.sortBy.length===0)throw new g("INTERNAL",`rankIndex "${r.name}" requires at least one "sortBy" column for stable pagination`);const u=[{column:"__partition__",direction:"asc",nullable:!1}];for(const[c,R]of r.sortBy.entries())u.push({column:a[c]??Re(c),direction:R.direction,nullable:!0});return u.push({column:Se,direction:"asc",nullable:!1}),u},Bi=async(r,a,u,c,R)=>{const d=[];for(let v=0;v<R.length;v+=50)d.push(R.slice(v,v+50));const O=await Promise.all(d.map(async v=>I(r,a,e`SELECT * FROM ${e.identifier(c)} WHERE ${e.identifier("id")} IN (${de(v)})`))),T=new Map;for(const v of O)for(const L of v)T.set(L.id,L);const A=[];for(const v of R){const L=X(u,T.get(v));L&&A.push(L)}return A},Wi=r=>{const a=r.map(f=>Vt(f,"bytes")),u=JSON.stringify(jt(a)?Kt(a):a),c=new TextEncoder().encode(u);let R="";for(const f of c)R+=String.fromCodePoint(f);return zn+btoa(R)},Jt=r=>{if(r===void 0)return!1;const a=Yt(r);return a==="any"||a==="bigint"||a==="from"||a==="union"},nt=(r,a,u)=>{if(Jt(r.shape[a]))throw new g("BAD_REQUEST",`${u}: "${a}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Fi=(r,a,u,c)=>{for(const R of u)nt(r,R,`groupBy(${a}, { by: [..."${R}"] })`);c.field!==void 0&&nt(r,c.field,`groupBy(${a}, { agg: { op: "${c.op}", field: "${c.field}" } })`)},it="__cdc_sweep",qe="__cdc_log_ts",Zt="global",Ui=6e4,xi=1e4,Pi=3e4;let Bt=0;const Hi=async(r,a)=>{const{autoincrementPrimaryKey:u,key:c,real:R,text:f}=a.companionTypes;await x(r,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(D)} (${e.identifier("seq")} ${e.raw(u)}, ${e.identifier("ts")} ${e.raw(R)} NOT NULL, ${e.identifier("table")} ${e.raw(c)} NOT NULL, ${e.identifier("id")} ${e.raw(c)} NOT NULL, ${e.identifier("op")} ${e.raw(c)} NOT NULL, ${e.identifier("doc")} ${e.raw(f)})`);const d=a.indexKeyPrefix?.("string");await Gt(r,a,{columns:e`${d===void 0?e`${e.identifier("table")}`:e`${e.identifier("table")}(${e.raw(String(d))})`}, ${e.identifier("seq")}`,name:ci,table:D,unique:!1}),await x(r,a,e`CREATE TABLE IF NOT EXISTS ${e.identifier(it)} (${e.identifier("id")} ${e.raw(c)} NOT NULL PRIMARY KEY, ${e.identifier("lease_until")} ${e.raw(R)} NOT NULL)`),await x(r,a,e`INSERT INTO ${e.identifier(it)} (${e.identifier("id")}, ${e.identifier("lease_until")}) VALUES (${Zt}, ${0}) ${a.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${e.identifier("id")} = ${e.identifier("id")}`:e`ON CONFLICT(${e.identifier("id")}) DO NOTHING`}`)},ji=async(r,a,u)=>{const c=e`UPDATE ${e.identifier(it)} SET ${e.identifier("lease_until")} = ${u+Ui} WHERE ${e.identifier("id")} = ${Zt} AND ${e.identifier("lease_until")} <= ${u}`;if(a.supportsReturning)return(await I(r,a,e`${c} RETURNING ${e.identifier("id")}`)).length>0;const R=await x(r,a,c);return(a.affectedRows?a.affectedRows(R??{rowsAffected:0}):0)>0},Ki=async(r,a,u,c)=>{if(!await ji(r,a,c))return;const R=c-u;let f=!0;try{const d=await $i(r,a,D,qe);d!=="valid"&&(d==="invalid"&&await hi(r,a,D,qe),await Gt(r,a,{columns:e`${e.identifier("ts")}`,concurrently:!0,name:qe,table:D,unique:!1}))}catch(d){f=!1,console.warn(`[@lunora/sql-store] changelog retention could not build "${qe}"; sweeping without it.`,d)}f&&(await I(r,a,e`SELECT 1 AS ${e.identifier("hit")} FROM ${e.identifier(D)} WHERE ${e.identifier("ts")} <= ${R} LIMIT 1`)).length===0||await x(r,a,e`
|
|
2
|
-
DELETE FROM ${e.identifier(D)} WHERE ${e.identifier("seq")} IN (
|
|
3
|
-
SELECT ${e.identifier("seq")} FROM (
|
|
4
|
-
SELECT ${e.identifier("seq")} FROM ${e.identifier(D)} WHERE +${e.identifier("ts")} <= ${R} ORDER BY ${e.identifier("seq")} ASC LIMIT ${e.raw(String(xi))}
|
|
5
|
-
) AS ${e.identifier("expired")}
|
|
6
|
-
)
|
|
7
|
-
`)},en=async(r,a)=>{const u=await I(r,a,e`SELECT MIN(${e.identifier("seq")}) AS ${e.identifier("seq")} FROM ${e.identifier(D)}`),c=Number(u[0]?.seq??Number.NaN);return Number.isFinite(c)?c:void 0},Gi=async(r,a)=>{if(a.name!=="sqlite")return;const u=await I(r,a,e`SELECT ${e.identifier("seq")} AS ${e.identifier("seq")} FROM ${e.identifier("sqlite_sequence")} WHERE ${e.identifier("name")} = ${D}`),c=Number(u[0]?.seq??Number.NaN);return Number.isFinite(c)?c:0},Vi=r=>JSON.stringify(jt(r)?Kt(r):r),Yi=(r,a,u,c,R)=>e`INSERT INTO ${e.identifier(D)} (${e.identifier("ts")}, ${e.identifier("table")}, ${e.identifier("id")}, ${e.identifier("op")}, ${e.identifier("doc")}) VALUES (${r}, ${a}, ${u}, ${c}, ${R===void 0?null:Vi(R)})`,tn=1e4,Xi=1e3,Qi=(r,a,u)=>{let c=a;for(const[R,f]of r.entries()){const d=Number(f.seq);if(d>c+1&&Number(f.ts)>u)return r.slice(0,R);c=d}return r},Eo=async(r,a,u)=>{const c=a.sinceSeq??0,R=Math.max(1,Math.min(a.limit??1e3,1e4)),f=await en(r,u),d=await Gi(r,u);if(d!==void 0&&c>d)throw On(d,c,"global");if(f!==void 0&&qn(f,c))throw kn(f,c,"global");const O=await I(r,u,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(D)} WHERE seq > ${c} ORDER BY seq ASC LIMIT ${e.raw(String(R))}`),A=(u.name==="sqlite"?O:Qi(O,c,(a.now??Date.now())-tn)).map(v=>{const{doc:L}=v,b={id:String(v.id),op:String(v.op),seq:Number(v.seq),table:String(v.table),ts:Number(v.ts)};return typeof L=="string"?{...b,doc:ui(L)}:b});return{changes:A,cursor:A.at(-1)?.seq??c}},Wt=(r,a)=>{const u=e.identifier(D),c=e`(SELECT MIN(v.seq) FROM ${u} v WHERE v.seq > ${r} AND v.seq - 1 > ${r} AND v.ts > ${a} AND NOT EXISTS (SELECT 1 FROM ${u} p WHERE p.seq = v.seq - 1))`;return e`${c} AS ${e.identifier("gap")}, (SELECT MAX(q.seq) FROM ${u} q WHERE q.seq > ${r} AND q.seq < ${c}) AS ${e.identifier("below")}`},Ft=(r,a,u)=>{const c=Number(a?.gap??Number.NaN);if(!Number.isFinite(c))return r;const R=Number(a?.below??Number.NaN);return Math.min(r,Number.isFinite(R)?R:u)},zi=r=>{const a=e.identifier(D),u=e.identifier("table");return e`SELECT ${u}, seq FROM (WITH RECURSIVE "t"("name") AS (SELECT MIN(${u}) FROM ${a} UNION ALL SELECT (SELECT MIN(${u}) FROM ${a} WHERE ${u} > "t"."name") FROM "t" WHERE "t"."name" IS NOT NULL) SELECT "t"."name" AS ${u}, (SELECT MAX(seq) FROM ${a} WHERE ${u} = "t"."name" AND seq > ${r}) AS seq FROM "t" WHERE "t"."name" IS NOT NULL) WHERE seq IS NOT NULL ORDER BY ${u}`},Ji=async(r,a,u,c={})=>{const R=e.identifier(D),f=u.name!=="sqlite",d=(c.now??Date.now())-tn;if(c.cursorOnly){const L=e`GREATEST((SELECT MAX(seq) FROM ${R}) - ${e.raw(String(Xi))}, ${a})`,b=await I(r,u,e`SELECT MAX(seq) AS seq${f?e`, ${Wt(L,d)}`:e``} FROM ${R}`),q=Number(b[0]?.seq??a);return{cursor:Ft(Number.isFinite(q)?q:a,b[0],a),tables:[]}}const O=await I(r,u,f?e`SELECT ${e.identifier("table")} AS ${e.identifier("table")}, MAX(seq) AS seq, ${Wt(e`${a}`,d)} FROM ${R} WHERE seq > ${a} GROUP BY ${e.identifier("table")}`:zi(a));let T=a;const A=[];for(const L of O){const b=Number(L.seq);Number.isFinite(b)&&b>T&&(T=b),A.push(String(L.table))}T=Ft(T,O[0],a);const v=c.retained===!0?await en(r,u):void 0;return{cursor:T,tables:A,...v===void 0?{}:{floor:v}}},Zi=/string or blob too big/iu,eo=/row is too big/iu,to=(r,a)=>{const{code:u,errno:c}=a,R=a instanceof Error?a.message:"";switch(r.name){case"mysql":return c===1118||u==="ER_TOO_BIG_ROWSIZE"?"InnoDB's per-row ceiling — roughly 8 KB, half a 16 KB page, for the part of the row stored inline":void 0;case"postgres":return eo.test(R)?"the 8 KB heap page a tuple must fit once its wide columns have been TOASTed out":void 0;default:return Zi.test(R)?"the storage engine's per-row ceiling (2 MB on D1)":void 0}},no=(r,a,u)=>{const c=to(r,a);if(c!==void 0)throw new g("PAYLOAD_TOO_LARGE",`document is too large to store in "${u}": a single row cannot exceed ${c}. The limit is on the STORED bytes, which are UTF-8. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},et=16,Ut="__lunora_patch_if_match__",xt=(r,a,u)=>{throw r.isUniqueViolation(a)?new ae(`unique constraint violation on "${u}"`,"unique"):(no(r,a,u),a)},tt=new WeakMap,Pt=new WeakMap,ye="superseded",io=3e4,ke="__lunora_companion_fence",se=(r,a,u)=>JSON.stringify([r,a,u]),De=r=>JSON.stringify(r,(a,u)=>typeof u=="bigint"?`${String(u)}n`:u),oo=r=>{const a=Dn(r);return(u,c,R,f)=>c.some(d=>d instanceof wi)?_i(r,u,c,R):a(u,c,R,f)},po=r=>{const{crossShardCounter:a,crossShardReader:u,exec:c,maxRelationKeys:R,schema:f}=r,{dialect:d}=r,O={fieldRef:n=>Be(d,n),rangeTypeGuard:(n,t)=>yi(d,n,t),...d.name==="mysql"?{containsExpr:(n,t)=>{const i=At(n);return i===void 0?e`LOCATE(${t}, ${n}) > 0`:e`LOCATE(${Ct("mysql",t)}, ${i}) > 0`}}:{},...d.name==="postgres"?{containsExpr:(n,t)=>{const i=At(n);return i===void 0?e`strpos(${n}, ${t}) > 0`:e`strpos(${i}, ${Ct("postgres",t)}) > 0`}}:{},...d.name==="sqlite"?{}:{inList:oo(d.name)}},T=new WeakMap,A=n=>{const t=T.get(n);if(t!==void 0)return t;const i={...O,serialize:(o,s)=>Nt(d,s,o,l=>oe(n,s,l))};return T.set(n,i),i},v=(n,t)=>ot(d.name,n,t),L=n=>{const t=re(n.columns),i=de(n.values),o=$=>d.name==="mysql"?e`VALUES(${e.identifier($)})`:e`excluded.${e.identifier($)}`,s=$=>d.name==="postgres"?e`${e.identifier(n.table)}.${e.identifier($)}`:e`${e.identifier($)}`,l=e.join(Object.entries(n.set(o,s)).map(([$,h])=>e`${e.identifier($)} = ${h}`),e`, `),p=d.name==="mysql"?e`ON DUPLICATE KEY UPDATE ${l}`:e`ON CONFLICT(${e.identifier(n.conflictKey)}) DO UPDATE SET ${l}`;return e`INSERT INTO ${e.identifier(n.table)} (${t}) VALUES (${i}) ${p}`},b=r.clock??(()=>Date.now()),q=r.idGenerator??(()=>crypto.randomUUID()),K=r.cdc??!1,Q=typeof r.cdcRetentionMs=="number"&&Number.isFinite(r.cdcRetentionMs)&&r.cdcRetentionMs>0?r.cdcRetentionMs:void 0,Z=r.auth??{identity:null,userId:null},le=(n,t,i,o)=>K?[Yi(b(),n,t,i,o)]:[],nn=async()=>{if(!K||Q===void 0)return;const n=b();if(!(n-Bt<Pi)){Bt=n;try{await Ki(c,d,Q,n)}catch{}}},on=r.scheduler??Nn,Fe=bi();let ge=0;const ue=r.provisionScope??{},B=async()=>{const n=tt.get(ue);if(n)return n;const t=(async()=>{await Ri(c,f,d),await Si(c,f,d),await gi(c,f,d),await yn(c,d),await gn(c,f,d),K&&await Hi(c,d)})().catch(i=>{throw tt.delete(ue),i});return tt.set(ue,t),t},me=async(n,t)=>{if(t!==void 0&&!Object.hasOwn(f.tables,t))throw new g("BAD_REQUEST",`ctx.db by-id write (table, id): "${t}" is not a table in this schema`);if(await B(),t===void 0)return Ni(c,d,f,n,Fe);const i=Object.hasOwn(f.tables,t)?f.tables[t]:void 0;return i!==void 0&&Qt(i)?t:void 0};let Te=Pt.get(ue);Te===void 0&&(Te=new Map,Pt.set(ue,Te));const P=Te,rt={},Ue=(n,t,i)=>{const o=(async()=>(await B(),await i(()=>P.get(n)?.run!==o)))(),s={definition:t,owner:rt,run:o,settled:!1};return o.then(()=>{s.settled=!0},()=>{P.get(n)===s&&P.delete(n)}).catch(()=>{}),P.set(n,s),o},st=async(n,t,i)=>{const o=P.get(n);if(o===void 0)return await Ue(n,t,i);const s=o.definition===t;if(s&&(o.settled||o.owner===rt))return await o.run;if(o.settled)return await Ue(n,t,i);let l;const p=new Promise(h=>{l=setTimeout(h,io,"stalled")}),$=await Promise.race([o.run,p]).finally(()=>{clearTimeout(l)});return $!=="stalled"&&s?$:P.get(n)===o?await Ue(n,t,i):await st(n,t,i)},xe=async(n,t,i)=>{const o=await st(n,t,i);return o===ye?await xe(n,t,i):o},at=async(n,t)=>{const i=P.get(n),o=i?.settled===!0&&i.definition===t?await i.run:void 0;if(typeof o=="boolean")return o;P.delete(n)},rn=n=>{const t=f.tables[n];for(const i of t?.aggregateIndexes??[])P.delete(se("aggregate",n,i.name));for(const i of t?.rankIndexes??[])P.delete(se("rank",n,i.name))},sn=async(n,t)=>{const i=ie(n,t);return(await I(c,d,d.tableExists(i))).length>0},ct=async n=>{const{key:t}=d.companionTypes,i=q();await x(c,d,e`CREATE TABLE IF NOT EXISTS ${e.identifier(ke)} (${e.identifier("name")} ${e.raw(t)} PRIMARY KEY, ${e.identifier("token")} ${e.raw(t)} NOT NULL)`),await x(c,d,L({columns:["name","token"],conflictKey:"name",set:s=>({token:s("token")}),table:ke,values:[n,i]}));const o=e`${e.identifier("name")} = ${n} AND ${e.identifier("token")} = ${i}`;return{guardedDelete:()=>e`DELETE FROM ${e.identifier(n)} WHERE EXISTS (SELECT 1 FROM ${e.identifier(ke)} WHERE ${o})`,guardedInsert:(s,l)=>e`INSERT INTO ${e.identifier(n)} (${re(s)}) SELECT ${de(l)} FROM ${e.identifier(ke)} WHERE ${o}`}},an=async(n,t,i)=>{const o=f.tables[n];if(!o||!await sn(n,t.name))return!1;const s=t.by??[],l=new Map;await Ot(c,d,o,n,_=>{if(t.where&&!Ye(_,t.where))return;const w=J(s,_);It(l,w,t,_)});const p=ie(n,t.name);if(i())return ye;const $=await ct(p);await x(c,d,$.guardedDelete());const h=[];for(const[_,w]of l)h.push($.guardedInsert(["__key__","__value__","__count__"],[_,w.value,w.count]));return i()||await qt(c,d,h),i()?ye:!0},ve=(n,t)=>xe(se("aggregate",n,t.name),De(t),i=>an(n,t,i)),cn=async(n,t,i,o)=>{const s=new Map;let l,p=!0;for(;p;){const $=l===void 0?o:[...o,e`${e.identifier("id")} > ${l}`],h=$.length>0?e` WHERE ${e.join($,e` AND `)}`:e``,_=await I(c,d,e`SELECT ${e.identifier("id")}, ${U(i.field??"")} FROM ${e.identifier(t)}${h} ORDER BY ${e.identifier("id")} ASC LIMIT ${e.raw(String(ze))}`);for(const w of Lt(n,_))It(s,"",i,w);l=_.at(-1)?.id,p=_.length===ze}return s.get("")?.value??null},dn=async(n,t,i)=>{const o=t.field??"",s=[],l=f.tables[n],p=(w,E)=>Nt(d,w,E,S=>l?oe(l,w,S):Qe(S));for(const w of t.by??[]){const E=p(w,i[w]??null);s.push(E===null?e`${U(w)} IS NULL`:e`${U(w)} = ${E}`)}for(const[w,E]of Object.entries(t.where??{})){const S=E!==null&&typeof E=="object"&&!Array.isArray(E)?E.eq:E,y=p(w,S),m=Be(d,w);s.push(y===null?e`${m} IS NULL`:e`${m} = ${y}`)}const $=s.length>0?e` WHERE ${e.join(s,e` AND `)}`:e``;if(l&&Jt(l.shape[o]))return cn(l,n,t,s);const h=Ee(t.op),_=await I(c,d,e`SELECT ${e.raw(h)}(${U(o)}) AS ${e.identifier("value")} FROM ${e.identifier(n)}${$}`);return ce(_[0]?.value)},ln=(n,t)=>e`DELETE FROM ${e.identifier(n)} WHERE ${e.identifier("__key__")} = ${t} AND ${e.identifier("__count__")} <= 0`,un=async(n,t,i,o)=>{const s=ie(n,t.name),{op:l}=t,p=t.field??"",$=i&&(!t.where||Ye(i,t.where))?i:void 0,h=o&&(!t.where||Ye(o,t.where))?o:void 0;if(!$&&!h)return[];if(l==="count"||l==="sum"||l==="avg"){const w=[],E=new Set;for(const[S,y]of[[$,-1],[h,1]]){if(!S)continue;const m=l==="count"?1:Xe(S[p]);if(m===void 0)continue;const N=J(t.by??[],S);E.add(N),w.push(L({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(C,M)=>({__count__:e`${M("__count__")} + ${C("__count__")}`,__value__:l==="count"?e`${M("__value__")} + ${C("__value__")}`:e`COALESCE(${M("__value__")}, 0) + ${C("__value__")}`}),table:s,values:[N,y*m,y]}))}for(const S of E)w.push(ln(s,S));return w}const _=[];if($){const w=J(t.by??[],$),E=Xe($[p]),y=(await I(c,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(s)} WHERE ${e.identifier("__key__")} = ${w}`))[0],m=ce(y?.value),N=(y?.count??0)-1;if(N<=0)_.push(e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__key__")} = ${w}`);else if(y&&E!==void 0&&m!==null&&E===m){const C=await dn(n,t,$);_.push(e`UPDATE ${e.identifier(s)} SET ${e.identifier("__value__")} = ${C}, ${e.identifier("__count__")} = ${N} WHERE ${e.identifier("__key__")} = ${w}`)}else _.push(e`UPDATE ${e.identifier(s)} SET ${e.identifier("__count__")} = ${e.identifier("__count__")} - 1 WHERE ${e.identifier("__key__")} = ${w}`)}if(h){const w=J(t.by??[],h),E=Xe(h[p]);if(E===void 0)_.push(L({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(S,y)=>({__count__:e`${y("__count__")} + 1`}),table:s,values:[w,null,1]}));else{const S=l==="min"?"MIN":"MAX";_.push(L({columns:["__key__","__value__","__count__"],conflictKey:"__key__",set:(y,m)=>({__count__:e`${m("__count__")} + 1`,__value__:e`${e.raw(S)}(COALESCE(${m("__value__")}, ${y("__value__")}), ${y("__value__")})`}),table:s,values:[w,E,1]}))}}return _},Ie=async n=>{const t=f.tables[n]?.aggregateIndexes;if(!(!t||t.length===0))for(const i of t)await ve(n,i)},fe=async(n,t,i)=>{const o=f.tables[n]?.aggregateIndexes,s=[];if(!o||o.length===0)return s;for(const l of o)await at(se("aggregate",n,l.name),De(l))&&s.push(...await un(n,l,t,i));return s},fn=async(n,t)=>{const i=_e(n,t);return(await I(c,d,d.tableExists(i))).length>0},wn=async(n,t,i)=>{const o=f.tables[n];if(!o||!await fn(n,t.name))return!1;const s=_e(n,t.name);if(i())return ye;const l=await ct(s);await x(c,d,l.guardedDelete());const $=["__id__","__partition__",...t.sortBy.map((w,E)=>Re(E))];let h=[];const _=async()=>{const w=h;h=[],!(w.length===0||i())&&await qt(c,d,w)};return await Ot(c,d,o,n,async w=>{if(t.where&&!vt(w,t.where))return;const E=Me(t.partitionBy??[],w),S=t.sortBy.map(y=>Qe(w[y.field]??null));h.push(l.guardedInsert($,[w._id,E,...S])),h.length>=ze&&await _()}),await _(),i()?ye:!0},Pe=(n,t)=>xe(se("rank",n,t.name),De(t),i=>wn(n,t,i)),Ae=async n=>{const t=f.tables[n]?.rankIndexes;if(!(!t||t.length===0))for(const i of t)await Pe(n,i)},ee=async(n,t,i,o)=>{const s=f.tables[n],l=s?.rankIndexes,p=[];if(!l||l.length===0)return p;const $=s?.softDeleteMode?.field,h=$===void 0||o===void 0?void 0:o[$],_=h!=null;for(const w of l){if(i!==void 0&&o!==void 0&&Oi(w,i,o)||!await at(se("rank",n,w.name),De(w)))continue;const S=_e(n,w.name);if(i&&p.push(e`DELETE FROM ${e.identifier(S)} WHERE ${e.identifier("__id__")} = ${t}`),o&&!_){if(w.where&&!vt(o,w.where))continue;const y=w.sortBy.map((M,W)=>Re(W)),m=re(["__id__","__partition__",...y]),N=Me(w.partitionBy??[],o),C=w.sortBy.map(M=>Qe(o[M.field]??null));p.push(e`INSERT INTO ${e.identifier(S)} (${m}) VALUES (${de([t,N,...C])})`)}}return p},te=async(n,t)=>{try{const i=await t();i.length>0&&await pi(c,d,i)}catch(i){throw rn(n),i}await nn()},we=Sn({dialect:d,exec:c,schema:f}),dt=new Set;for(const[n,t]of Object.entries(f.tables))for(const i of Object.values(t.triggerMap??{}))dt.add(`${n} ${i.timing} ${i.op}`);const G=(n,t,i)=>dt.has(`${n} ${t} ${i}`);let lt;const V=async(n,t,i)=>{if(ge+=1,ge>Dt)throw ge-=1,new ae(`trigger recursion exceeded ${String(Dt)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await Qn({ctx:lt,event:i,op:t,schema:f,tableName:i.table,timing:n})}finally{ge-=1}},$n=async(n,t)=>{try{await x(c,d,t)}catch(i){xt(d,i,n)}},Ce=async(n,t)=>(await I(c,d,e`SELECT * FROM ${e.identifier(n)} WHERE ${e.identifier("id")} = ${t}`))[0],ut=async(n,t,i,o,s)=>{const l=e`${e.identifier(pe)}`,p=e.join([v(e`${e.identifier("id")}`,o.id),v(l,o[pe]??null),...s===void 0?[]:[e`(${s})`]],e` AND `),$=t==="UPDATE"?e`UPDATE ${e.identifier(n)} SET ${i}, ${l} = ${bt.sql(l)} WHERE ${p}`:e`DELETE FROM ${e.identifier(n)} WHERE ${p}`;try{if(d.supportsReturning)return(await I(c,d,e`${$} RETURNING ${e.identifier("id")}`)).length>0;const h=await x(c,d,$);return(d.affectedRows?d.affectedRows(h??{rowsAffected:0}):0)>0}catch(h){return xt(d,h,n)}},He=async(n,t,i,o)=>{if(o!==void 0&&!await ut(n,t,i,o))throw new ae(`optimistic concurrency conflict on "${n}" — the row changed during this mutation; refetch and retry`,"occ")},je=(n,t=n?._creationTime)=>({_creationTime:t,[pe]:bt.value(n?.[pe])}),ft=async(n,t,i,o,s,l,p)=>{const $=X(t,s);if(!$||s===void 0)throw new g("INTERNAL",`document not found: ${i}`);const h=Jn(t,o,$),_={...$,...Zn(h),_id:i};Je(t,h,_,Z);const w=Ge(t,_,{only:new Set(Object.keys(h)),previous:()=>$,tolerateStoredNull:!0});Ze(d.name,Object.fromEntries(Object.keys(h).map(y=>[y,w[y]]))),ei(p,$,w),G(n,"before","update")&&await V("before","update",{doc:{...w},id:i,op:"update",previous:$,table:n}),await Ie(n),await Ae(n);const E=Object.keys(t.shape),S=e.join(E.map(y=>e`${e.identifier(y)} = ${oe(t,y,w[y]??null)}`),e`, `);if(await ut(n,"UPDATE",S,s,l))return await te(n,async()=>[...await fe(n,$,w),...await ee(n,i,$,w),...le(n,i,"update",w)]),await we(n,i,{document:w,previous:$,written:je(s)}),G(n,"after","update")&&await V("after","update",{doc:w,id:i,op:"update",previous:$,table:n}),w},hn=(n,t,i,o)=>{const s=Object.keys(n.shape);return{columns:["id","_creationTime",...s],values:[t,i,...s.map(l=>oe(n,l,o[l]??null))]}},_n=async(n,t,i,o)=>{const s=ni(t,i.op,i.field,o.by,o.where);if(!s||!await ve(n,s.index))return;const p=ie(n,s.index.name),$=Object.keys(s.partial);if($.length===(s.index.by??[]).length&&$.length>0){const _=J(s.index.by??[],s.partial),w=await I(c,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(p)} WHERE ${e.identifier("__key__")} = ${_}`);if(w.length===0)return[];const E=w[0];return[{key:{...s.partial},value:Ve(i.op,{count:E.count,value:ce(E.value)})}]}return $.length>0?void 0:(await I(c,d,e`SELECT ${e.identifier("__key__")} AS ${e.identifier("key")}, ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(p)}`)).map(_=>{const w=_;return{key:fi(JSON.parse(w.key)),value:Ve(i.op,{count:w.count,value:ce(w.value)})}})},wt=n=>{const t=f.tables[n]?.shardMode?.kind;return t==="shardBy"||t==="root"},$t=n=>{throw new g("INTERNAL",`cross-backend relation: a global table cannot load the shard-local relation '${n}' (it spans every shard) — wire a cross-shard reader to support it`)},En=(n,t)=>{if(t?.relationMask!==void 0&&t.with!==void 0&&Object.keys(t.with).length>0)throw new g("MASK_UNSUPPORTED",`masking cannot follow a nested \`with\` across the cross-shard relation hop to "${n}" — the nested rows are hydrated on the serving shard, where the mask policy does not exist. Read the nested relation at its own (masked) call site instead.`);const i={};if(t?.relationBaseWhere)for(const o of Object.keys(f.tables)){const s=t.relationBaseWhere(o);s!==void 0&&(i[o]=s)}return{orderBy:t?.orderBy,relationPolicies:i,where:F(t?.baseWhere,t?.where),with:t?.with}},Le=(n,t)=>wt(n)?u?u(n,En(n,t)):$t(n):H.findMany(n,t),be=(n,t,i)=>ti(n,{fetcher:Le,maxRelationKeys:R,relationBaseWhere:i,schema:f,tableName:t}),pn=Ti(async(n,t)=>{const i=await I(c,d,e`SELECT * FROM ${e.identifier(n)} WHERE ${e.identifier("id")} IN (${de(t)})`),o=new Map;for(const s of i){const{id:l}=s;typeof l=="string"&&o.set(l,s)}return o}),ht=async(n,t,i)=>{const{fetchLimit:o,limit:s,orderKeys:l,predicate:p}=await ii(t,i,{fetcher:Le,maxRelationKeys:R,schema:f,tableName:n}),$=z(p,A(t)),h=Ai(l,d);let _=e`SELECT * FROM ${e.identifier(n)}`;return $&&(_=e`${_} WHERE ${$}`),_=e`${_} ORDER BY ${h}`,o!==void 0&&(_=e`${_} LIMIT ${e.raw(String(o))}`),{limit:s,orderKeys:l,query:_}},H={relationWrites:Mn(f),async cdcChangedTables(n,t){if(K)try{return await B(),await Ji(c,n,d,{...t,now:b(),retained:Q!==void 0})}catch{return}},async aggregate(n,t){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);if(await B(),Ee(t.op),t.op==="count")return H.count(n,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new g("INTERNAL",`aggregate(${n}, { op: "${t.op}" }): "field" is required for non-count reducers`);const o=Oe(i.softDeleteMode,void 0),s=F(F(t.baseWhere,t.where),o),l=await be(s,n,t.relationBaseWhere),p=l!==s;if(i.aggregateIndexes&&!t.baseWhere&&!p&&!o){const S=Xn(i.aggregateIndexes,t.op,t.field,t.where);if(S&&await ve(n,S.index)){const m=J(S.index.by??[],S.key),N=ie(n,S.index.name),M=(await I(c,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")}, ${e.identifier("__count__")} AS ${e.identifier("count")} FROM ${e.identifier(N)} WHERE ${e.identifier("__key__")} = ${m}`))[0];return Ve(t.op,M===void 0?void 0:{count:M.count,value:ce(M.value)})}}nt(i,t.field,`aggregate(${n}, { op: "${t.op}", field: "${t.field}" })`);const $=z(l,A(i)),h=e.raw(Ee(t.op)),_=e`SELECT ${h}(${U(t.field)}) AS ${e.identifier("value")} FROM ${e.identifier(n)}`,E=(await I(c,d,$?e`${_} WHERE ${$}`:_))[0]?.value;return E==null?null:Number(E)},async count(n,t){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);await B();const o=Vn(t);if(o.restrictsCounts)throw new yt(n);const s=Oe(i.softDeleteMode,void 0),l=F(F(o.baseWhere,o.where),s),p=await be(l,n,o.relationBaseWhere),$=p!==l;if(i.aggregateIndexes&&!o.baseWhere&&!$&&!s){const E=Yn(i.aggregateIndexes,o.where);if(E&&await ve(n,E.index)){const y=J(E.index.by??[],E.key),m=ie(n,E.index.name),N=await I(c,d,e`SELECT ${e.identifier("__value__")} AS ${e.identifier("value")} FROM ${e.identifier(m)} WHERE ${e.identifier("__key__")} = ${y}`);return Number(N[0]?.value??0)}}const h=z(p,A(i)),_=e`SELECT COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(n)}`,w=await I(c,d,h?e`${_} WHERE ${h}`:_);return Number(w[0]?.count??0)},async delete(n,t,i){const o=await me(t,n);if(!o)return;const s=f.tables[o];if(!s)return;const l=await Ce(o,t);if(l===void 0)return;const p=X(s,l),$=i?.hard===!0,h=!$&&s.softDeleteMode?s.softDeleteMode.field:void 0;if(!(h&&(!p||p[h]!==null&&p[h]!==void 0))){if(G(o,"before","delete")&&await V("before","delete",{id:t,op:"delete",previous:p??void 0,table:o}),await Gn({deletedId:t,deletedReference:_=>p?.[_],findHolders:async(_,w,E,S)=>{if(f.tables[_]?.shardMode?.kind==="shardBy")throw new g("INTERNAL",`cross-backend cascade from global '${o}' into shardBy '${_}' is not supported — would require Query Coordinator fan-out across shards`);return(await H.findMany(_,{...S,includeDeleted:$,where:{[w]:E}})).page},onCascade:(_,w)=>H.delete(_,w,i),onRestrict:_=>{throw new ae(_,"restrict")},onSetNull:(_,w,E)=>H.patch(_,w,{[E]:null}),schema:f,tableName:o}),await Ie(o),await Ae(o),h&&p){const _={[h]:b()},w={...p,..._};Je(s,_,w,Z);const E=e.join(Object.keys(s.shape).map(S=>e`${e.identifier(S)} = ${oe(s,S,w[S]??null)}`),e`, `);await He(o,"UPDATE",E,l),await te(o,async()=>[...await fe(o,p,w),...await ee(o,t,p,void 0),...le(o,t,"update",w)]),await we(o,t,{document:w,previous:p,written:je(l)}),G(o,"after","delete")&&await V("after","delete",{id:t,op:"delete",previous:p,table:o});return}await He(o,"DELETE",void 0,l),Fe.delete(t),await te(o,async()=>[...await fe(o,p??void 0,void 0),...await ee(o,t,p??void 0,void 0),...le(o,t,"delete")]),await we(o,t,void 0),G(o,"after","delete")&&await V("after","delete",{id:t,op:"delete",previous:p??void 0,table:o})}},async findFirst(n,t={}){return(await H.findMany(n,{...t,limit:1})).page[0]??null},async findFirstOrThrow(n,t={}){const i=await H.findFirst(n,t);if(i===null)throw new Kn(`findFirstOrThrow: no "${n}" document matched`);return i},async findMany(n,t={}){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);await B();const o=async(S,y,m,N)=>{if(wt(S))return a?oi(a,S,y,m,N):$t(S);const C=f.tables[S];if(!C)throw new g("INTERNAL",`unknown table: ${S}`);const M=Oe(C.softDeleteMode,void 0),W={[y]:{in:m}},Y=F(F(W,N),M),$e=await be(Y,S,void 0),Ne=z($e,A(C)),he=U(y);let j=e`SELECT ${he} AS __fk__, COUNT(*) AS ${e.identifier("count")} FROM ${e.identifier(S)}`;Ne&&(j=e`${j} WHERE ${Ne}`),j=e`${j} GROUP BY ${he}`;const k=await I(c,d,j),ne=new Map;for(const _t of k)ne.set(_t.__fk__,Number(_t.count??0));return ne},{limit:s,orderKeys:l,query:p}=await ht(n,i,t),$=await I(c,d,p),h=Lt(i,$);if(s===void 0)return t.with&&await Rt({fetcher:Le,groupedCounter:o,parents:h,...St(t),schema:f,tableName:n,with:t.with}),{continueCursor:null,isDone:!0,page:gt(h,t.select,t.with)};const _=h.length>s,w=_?h.slice(0,s):h,E=w.at(-1);return t.with&&await Rt({fetcher:Le,groupedCounter:o,parents:w,...St(t),schema:f,tableName:n,with:t.with}),{continueCursor:_&&E?jn(E,l):null,isDone:!_,page:gt(w,t.select,t.with)}},async explain(n,t={}){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);await B();const{query:o}=await ht(n,i,t),s=d.name==="sqlite"?"EXPLAIN QUERY PLAN":"EXPLAIN",l=await I(c,d,e`${e.raw(s)} ${o}`),{params:p,sql:$}=d.render(o);return{params:p,plan:l.map(h=>Ci(h)),sql:$}},async get(n,t){const i=Object.hasOwn(f.tables,n)?f.tables[n]:void 0;if(!i)throw new g("BAD_REQUEST",`ctx.db.get(table, id): "${n}" is not a table in this schema`);return i.shardMode!==void 0&&i.shardMode.kind!=="global"?null:(await B(),X(i,await pn.load(n,t)))},async groupBy(n,t){const i=f.tables[n];if(!i)throw new g("INTERNAL",`unknown table: ${n}`);await B();const o=t.agg??{op:"count"};if(Ee(o.op),o.op!=="count"&&!o.field)throw new g("INTERNAL",`groupBy(${n}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);const s=Oe(i.softDeleteMode,void 0),l=F(F(t.baseWhere,t.where),s),p=await be(l,n,t.relationBaseWhere),$=p!==l;if(i.aggregateIndexes&&!t.baseWhere&&!$&&!s){const y=await _n(n,i.aggregateIndexes,o,t);if(y!==void 0)return y}Fi(i,n,t.by,o);const h=z(p,A(i)),_=t.by.map(y=>e`${U(y)} AS ${e.identifier(y)}`);if(o.op==="count")_.push(e`COUNT(*) AS ${e.identifier("value")}`);else{if(!o.field)throw new g("INTERNAL",`groupBy(${n}, { agg: { op: "${o.op}" } }): "field" is required for non-count reducers`);_.push(e`${e.raw(Ee(o.op))}(${U(o.field)}) AS ${e.identifier("value")}`)}const w=e.join(t.by.map(y=>U(y)),e`, `);let E=e`SELECT ${e.join(_,e`, `)} FROM ${e.identifier(n)}`;h&&(E=e`${E} WHERE ${h}`),E=e`${E} GROUP BY ${w}`;const S=await I(c,d,E);return Mi(i,t.by,S)},async insert(n,t,i){const o=f.tables[n];if(!o)throw new g("INTERNAL",`unknown table: ${n}`);await B();const s=Ge(o,xn(o,t,Z),{supplied:t,trusted:i?.allowExplicitId===!0});Ze(d.name,s);let l,p=!0;i?.clientId!==void 0?(Pn(i.clientId),l=i.clientId):i?.allowExplicitId&&typeof s._id=="string"?(Hn(s._id),l=s._id):(l=q(),p=!1);const $=i?.allowExplicitId&&typeof s._creationTime=="number"?s._creationTime:b(),h={...s,_creationTime:$,_id:l};G(n,"before","insert")&&await V("before","insert",{doc:{...h},id:l,op:"insert",table:n}),await Ie(n),await Ae(n);const{columns:_,values:w}=hn(o,l,$,s);return await $n(n,e`INSERT INTO ${e.identifier(n)} (${re(_)}) VALUES (${de(w)})`),p&&Fe.set(l,n),await te(n,async()=>[...await fe(n,void 0,h),...await ee(n,l,void 0,h),...le(n,l,"insert",h)]),await we(n,l,{document:h,written:{_creationTime:$,[pe]:null}}),G(n,"after","insert")&&await V("after","insert",{doc:h,id:l,op:"insert",table:n}),l},normalizeId(n,t){return Un(f,n,t)},async patch(n,t,i,o){Ke("patch",i);const s=await me(t,n);if(!s)throw new g("INTERNAL",`document not found: ${t}`);const l=f.tables[s];if(!l)throw new g("INTERNAL",`document not found: ${t}`);const p=Fn(l,i)?et:1;for(let $=0;$<p;$+=1){const h=await Ce(s,t);if(await ft(s,l,t,i,h,void 0,o))return}throw new ae(`optimistic concurrency conflict on "${s}" — the row changed during this mutation; refetch and retry`,"occ")},async patchIf(n,t,i){Ke("patchIf",i.patch),await B();const o=f.tables[n];if(!o)throw new g("INTERNAL",`unknown table: ${n}`);const s=z(i.where,A(o))??e`1 = 1`;for(let l=0;l<et;l+=1){const[p]=await I(c,d,e`SELECT *, CASE WHEN (${s}) THEN 1 ELSE 0 END AS ${e.identifier(Ut)} FROM ${e.identifier(n)} WHERE ${e.identifier("id")} = ${t}`);if(p===void 0)return{applied:!1,doc:null};const{[Ut]:$,...h}=p;if(Number($)!==1)return{applied:!1,doc:X(o,h)??null};const _=await ft(n,o,t,i.patch,h,s,{verify:i.verify});if(_)return{applied:!0,doc:_}}throw new ae(`patchIf on "${n}" lost the row to concurrent writes ${String(et)} times in a row; retry the operation`,"occ")},async restore(n,t){const i=await me(t,n),o=i===void 0?void 0:await Ce(i,t);if(!i||o===void 0)throw new g("INTERNAL",`document not found: ${t}`);const s=f.tables[i],l=s?.softDeleteMode?.field;if(!s||!l)throw new g("INTERNAL",`ctx.db.restore: table "${i}" is not a .softDelete() table`);const p=o[l]!==null&&o[l]!==void 0;if(await H.patch(n,t,{[l]:null}),p){const $=X(s,o);$!==null&&await te(i,async()=>await ee(i,t,void 0,{...$,[l]:null}))}},query(n){const t=f.tables[n];if(!t)throw new g("INTERNAL",`unknown table: ${n}`);const i="the legacy query()/withIndex() reader is not available on the D1 (global) backend; use findMany",o=[];let s=0,l;const p=d.name!=="mysql",$={...A(t),fieldRef:E=>e`m.${U(E)}`,rangeTypeGuard:()=>{throw new g("INTERNAL","a path range is never pushed into a search")}},h=E=>o.every(S=>S(E)),_=async(E,S)=>{await B();const y=2*In+E.filters.length,m=l===void 0?void 0:z(l,$,void 0,y),N=m!==void 0&&d.name==="sqlite"&&d.render(m).params.length+y>li.boundParams,C=N?void 0:m,M=s>0||N,W=await An(c,d,t,n,C===void 0?E:{...E,scope:C},Cn(M?void 0:S));!M&&S===void 0&&Ln(W);const Y=W.filter($e=>h($e));return S===void 0?Y:Y.slice(0,S)},w=E=>{const S={async*[Symbol.asyncIterator](){if(!E)throw new g("INTERNAL",i);yield*await _(E,void 0)},async collect(){if(!E)throw new g("INTERNAL",i);return _(E,void 0)},async collectWithScores(){throw new g("GLOBAL_SEARCH_SCORES_UNSUPPORTED",`collectWithScores() is not supported on \`.global()\` tables (table "${n}") — relevance scores are not yet surfaced on this backend; use .collect() instead`)},filter(y){o.push(y);const m=ri(y);return m!==void 0&&si(m,t.shape,p)?l=F(l,m):s+=1,S},async first(){if(!E)throw new g("INTERNAL",i);return(await _(E,1))[0]??null},order(){return S},async paginate(y){if(!E)throw new g("INTERNAL",i);const m=Tn(y);return vn(await _(E,bn(m)),m)},async take(y){if(!E)throw new g("INTERNAL",i);return _(E,y)},async unique(){if(!E)throw new g("INTERNAL",i);const y=await _(E,2);if(y.length>1)throw new di(`unique() on table "${n}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(){throw new g("INTERNAL",`geo indexes are not supported on \`.global()\` tables (table "${n}") — geospatial queries run only on sharded tables`)},withIndex(){throw new g("INTERNAL",i)},withSearchIndex(y,m){const N=(t.searchIndexes??[]).find(M=>M.name===y);if(!N)throw new g("INTERNAL",`unknown search index "${y}" on table "${n}"`);const C={definition:N,field:N.field,filters:[],hasQuery:!1,indexName:y,query:""};if(m(mn(C,n,Rn(N.language))),!C.hasQuery)throw new g("INTERNAL",`search index "${y}" on table "${n}" requires a .search(field, query) call`);return w(C)}};return S};return w(void 0)},async rank(n,t,i){const o=f.tables[n];if(!o)throw new g("INTERNAL",`unknown table: ${n}`);const s=o.rankIndexes?.find(W=>W.name===t);if(!s)throw new g("INTERNAL",`unknown rankIndex "${t}" on table "${n}"`);if(i.restrictsCounts)throw new yt(n);if(await B(),!await Pe(n,s))return null;const p=typeof i.row=="string"?i.row:i.row._id;if(!p)return null;const $=_e(n,s.name),h=s.sortBy.map((W,Y)=>Re(Y)),_=re(["__partition__",...h]),E=(await I(c,d,e`SELECT ${_} FROM ${e.identifier($)} WHERE ${e.identifier("__id__")} = ${p}`))[0];if(!E)return null;const S=E.__partition__,y=F(i.baseWhere,i.where);Et(y,f,n,"rank");const m=pt(s,y);if(m&&Me(s.partitionBy??[],m)!==S)return null;const N=qi(d.name,s,h,E,p),C=await I(c,d,e`SELECT COUNT(*) AS c FROM ${e.identifier($)} WHERE ${e.identifier("__partition__")} = ${S} AND (${N})`),M=await I(c,d,e`SELECT COUNT(*) AS c FROM ${e.identifier($)} WHERE ${e.identifier("__partition__")} = ${S}`);return{position:Number(C[0]?.c??0)+1,total:Number(M[0]?.c??0)}},async rankPage(n,t,i={}){Et(F(i.baseWhere,i.where),f,n,"rankPage");const o=f.tables[n];if(!o)throw new g("INTERNAL",`unknown table: ${n}`);const s=o.rankIndexes?.find(k=>k.name===t);if(!s)throw new g("INTERNAL",`unknown rankIndex "${t}" on table "${n}"`);if(await B(),!await Pe(n,s))return{continueCursor:null,isDone:!0,page:[]};const p=_e(n,s.name),$=s.sortBy.map((k,ne)=>Re(ne)),h=Math.max(1,Math.min(1e3,Math.floor(i.take??100))),_=F(i.baseWhere,i.where),w=pt(s,_),E=Di(s,$),S=e.join(E.flatMap(k=>Xt(d,{direction:k.direction,field:k.column,nullable:k.nullable})),e`, `),y=[];typeof i.partitionKey=="string"?y.push(e`${e.identifier("__partition__")} = ${i.partitionKey}`):w&&y.push(e`${e.identifier("__partition__")} = ${Me(s.partitionBy??[],w)}`);const m=Wn(i);if(m!==void 0){const k=ki(d.name,E,m);k!==void 0&&y.push(k)}const N=re([Se,"__partition__",...$]);let C=e`SELECT ${N} FROM ${e.identifier(p)}`;y.length>0&&(C=e`${C} WHERE ${e.join(y,e` AND `)}`),C=e`${C} ORDER BY ${S} LIMIT ${e.raw(String(h+1))}`;const M=await I(c,d,C),W=M.length>h,Y=W?M.slice(0,h):M,$e=Y.map(k=>k[Se]),Ne=await Bi(c,d,o,n,$e);let he=null;const j=Y.at(-1);if(W&&j!==void 0){const k=[j.__partition__,...$.map(ne=>j[ne]),j[Se]];he=Wi(k)}return{continueCursor:he,isDone:!W,page:Ne}},async replace(n,t,i,o){Ke("replace",i);const s=await me(t,n);if(!s)throw new g("INTERNAL",`document not found: ${t}`);const l=f.tables[s];if(!l)throw new g("INTERNAL",`document not found: ${t}`);const p=await Ce(s,t);if(p===void 0)throw new g("INTERNAL",`document not found: ${t}`);const h=Bn(f,s,"update")||(l.aggregateIndexes??[]).length>0||(l.rankIndexes??[]).length>0?X(l,p)??void 0:void 0,_=o?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,w=typeof p._creationTime=="number"?p._creationTime:void 0,E=_??w??b(),S={...i,_creationTime:E,_id:t};Je(l,i,S,Z);const y=Ge(l,S,{previous:()=>h??X(l,p)??void 0,supplied:i,trusted:o?.allowExplicitId===!0});Ze(d.name,y),G(s,"before","update")&&await V("before","update",{doc:{...y},id:t,op:"update",previous:h,table:s}),await Ie(s),await Ae(s);const m=Object.keys(l.shape),N=e.join([e`${e.identifier("_creationTime")} = ${E}`,...m.map(C=>e`${e.identifier(C)} = ${oe(l,C,y[C]??null)}`)],e`, `);await He(s,"UPDATE",N,p),await te(s,async()=>[...await fe(s,h,y),...await ee(s,t,h,y),...le(s,t,"update",y)]),await we(s,t,{document:y,previous:h,written:je(p,E)}),G(s,"after","update")&&await V("after","update",{doc:y,id:t,op:"update",previous:h,table:s})}};return lt={db:H,scheduler:on},H};export{po as createSqlCtxDb,So as decodeGlobalRow,Ji as readSqlCdcChangedTables,Eo as readSqlCdcChanges,en as readSqlCdcFloor,Hi as runSqlCdcMigration,Ki as sweepSqlCdcRetention};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{q,c as vt,m as Dt,r as F,a as qt,l as lt,w as D,b as Ft}from"./ctx-db-search-state-C4l9QBq-.mjs";import{ftsUnmappedPage as bt,groupUnmappedRows as Ut,ftsWriteDocument as mt,ftsPurgeDocument as pt,ftsCompanionDdl as kt,unionAll as Ht,ftsRowidMapName as Pt}from"@lunora/shard-engine";import{sql as i}from"drizzle-orm";import{q as p,O as Bt,u as jt,l as Q,a as A,i as C,c as V,j as L,b as T,m as ht,e as rt,x as Wt,r as xt,z as Kt}from"./sql-exec-CkHeSf_v.mjs";const Gt=n=>{const t=atob(n),e=Uint8Array.from(t,r=>r.codePointAt(0)??0);return new TextDecoder().decode(e)},Yt=()=>new h("BAD_REQUEST","invalid cursor"),st=16,ot=8,y=1024,b=(n,t)=>t.query(n),Qt=(n,t)=>{if(!t)return{exact:!0,lower:n,upper:n};const e=[...n].at(-1)??"",r=(e.codePointAt(0)??0)+1;if(r>=55296&&r<=57343||r>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-e.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(r)}},Cn=(n,t,e)=>{const r={eq:(s,o)=>{if(!n.definition.filterFields?.includes(s))throw new h("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${t}"`);if(n.filters.length>=ot)throw new h("BAD_REQUEST",`search index "${n.indexName}" on table "${t}": at most ${String(ot)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:o}),r},search:(s,o)=>{const a=n;if(s!==a.definition.field)throw new h("INTERNAL",`search index "${a.indexName}" on table "${t}" indexes "${a.definition.field}", not "${s}"`);const f=b(o,e).length;if(f>st)throw new h("BAD_REQUEST",`search index "${a.indexName}" on table "${t}": at most ${String(st)} search terms are supported (got ${String(f)})`);return a.field=s,a.query=o,a.hasQuery=!0,r}};return r},Ln=n=>{if(n.length>y)throw new h("BAD_REQUEST",`more than ${String(y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Mn=n=>Math.min(n.offset+n.numItems+1,y),Vt=n=>btoa(`search:${String(n)}`),Xt=n=>{let t;try{t=Gt(n)}catch{return}if(!t.startsWith("search:"))return;const e=Number(t.slice(7));return Number.isInteger(e)&&e>=0?e:void 0},vn=n=>{if(typeof n.endCursor=="string")throw new h("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 h("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const t=Math.max(0,Math.floor(n.numItems)),e=n.cursor?Xt(n.cursor):0;if(e===void 0)throw Yt();if(e+t>=y)throw new h("BAD_REQUEST",`search pagination reaches the ${String(y)}-document limit (offset ${String(e)} + ${String(t)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,y-e-1))} or fewer, or narrow the query or the filters instead`);return{numItems:t,offset:e}},Dn=(n,t)=>{const e=t.offset+t.numItems,r=t.numItems>0&&n.length>e;return{continueCursor:r?Vt(e):null,isDone:!r,page:n.slice(t.offset,e)}},qn=n=>{if(n===void 0)return y+1;if(!Number.isFinite(n))return y;const t=Math.max(0,Math.floor(n));if(t>y)throw new h("BAD_REQUEST",`search returns at most ${String(y)} documents (asked for ${String(t)}) — narrow the query or paginate instead`);return t},Jt=(n,t)=>{if(!t.includes("."))return n[t];let e=n;for(const r of t.split(".")){if(e===null||typeof e!="object"||Array.isArray(e))return;e=e[r]}return e},U=(n,t)=>`${n}__fts_${t}`,S="__id__",g="__token__",O="__n__",zt=1e3,Zt=(n,t)=>t.document(n),W=(n,t)=>Jt(n,t),tn=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",nn=(n,t,e)=>n!==void 0&&t!==void 0&&W(n,e.field)===W(t,e.field),gt=(n,t)=>Zt(tn(W(n,t.field)),q(t.language)).slice(0,zt),X=(n,t)=>gt(n,t).join(" "),Tt=(n,t)=>{const e=new Map;for(const r of gt(n,t))e.set(r,(e.get(r)??0)+1);return e},yt=[Bt,"_creationTime"],at=50,$=(n,t)=>i`${i.identifier(n)}.${i.identifier(t)}`,M=(n,t,e)=>i`DELETE FROM ${i.identifier(n)} WHERE ${$(n,S)} = ${t}${e===void 0?i``:i` AND ${e}`}`,Rt=(n,{row:t,table:e})=>{const r=yt.map(s=>i` AND ${jt(n.name,$(e,s),t[s]??null)}`);return i`SELECT 1 FROM ${i.identifier(e)} WHERE ${$(e,"id")} = ${t.id}${i.join(r)}${n.name==="postgres"?i` FOR SHARE`:i``}`},v=(n,t)=>i`EXISTS (${Rt(n,t)})`,k=(n,t)=>i`NOT EXISTS (SELECT 1 FROM ${i.identifier(n)} WHERE ${$(n,"id")} = ${t})`,_t=(n,t,e,r)=>r===void 0?k(t,e):v(n,{row:r,table:t}),J=async(n,t,e,r)=>{const s=new Map;for(let o=0;o<r.length;o+=at){const a=r.slice(o,o+at),f=await p(n,t,i`SELECT * FROM ${i.identifier(e)} WHERE ${$(e,"id")} IN (${i.join(a.map(u=>i`${u}`),i`, `)})`);for(const u of f)s.set(String(u.id),u)}return s},x=(n,t,e)=>n.name==="mysql"?i`${i.identifier(t)}(${i.raw(String(e))})`:n.textPatternOperatorClass===void 0?i`${i.identifier(t)}`:i`${i.identifier(t)} ${i.raw(n.textPatternOperatorClass)}`,z=512,Z=(n,t)=>({columns:i`${x(n,g,256)}, ${x(n,S,z)}`,concurrently:!0,name:`${t}__unique`,table:t,unique:!0}),B=n=>i`${n} COLLATE utf8mb4_0900_bin`,j=(n,t)=>{const e=JSON.stringify(t.map(([r,s])=>({o:s,t:r})));switch(n.name){case"mysql":return i`JSON_TABLE(${e}, '$[*]' COLUMNS (${i.identifier("t")} VARCHAR(256) PATH '$.t', ${i.identifier("o")} INT PATH '$.o')) AS ${i.identifier("j")}`;case"postgres":return i`json_to_recordset(${e}::text::json) AS ${i.identifier("j")}(${i.identifier("t")} text, ${i.identifier("o")} integer)`;default:return i`(SELECT json_extract(${$("e","value")}, '$.t') AS ${i.identifier("t")}, json_extract(${$("e","value")}, '$.o') AS ${i.identifier("o")} FROM json_each(${e}) AS ${i.identifier("e")}) AS ${i.identifier("j")}`}},Nt=(n,t,e,r,s)=>{const o=i.join([g,S,O].map(f=>i.identifier(f)),i`, `),a=f=>i`INSERT INTO ${i.identifier(t)} (${o}) SELECT ${$("j","t")}, ${e}, ${$("j","o")} FROM ${j(n,r)} WHERE ${f}`;switch(n.name){case"mysql":{const f=v(n,s),u=$(t,g),c=i.identifier("held");return[i`${a(i`${f} AND NOT EXISTS (SELECT 1 FROM ${i.identifier(t)} AS ${c} WHERE ${$("held",S)} = ${e} AND ${$("held",g)} = ${B($("j","t"))})`)} ON DUPLICATE KEY UPDATE ${$(t,O)} = ${$(t,O)}`,i`UPDATE ${i.identifier(t)} JOIN ${j(n,r)} ON ${u} = ${B($("j","t"))} SET ${$(t,O)} = ${$("j","o")} WHERE ${$(t,S)} = ${e} AND ${f}`,i`DELETE FROM ${i.identifier(t)} WHERE ${$(t,S)} = ${e} AND ${f} AND ${u} NOT IN (SELECT ${B($("j","t"))} FROM ${j(n,r)})`]}case"postgres":{const f=i.identifier("__source__"),u=i.identifier("__purged__"),c=i`EXISTS (SELECT 1 FROM ${f})`;return[i`WITH ${f} AS (${Rt(n,s)}), ${u} AS (${M(t,e,c)} RETURNING 1) ${a(i`${c} AND (SELECT COUNT(*) FROM ${u}) >= 0`)} ON CONFLICT DO NOTHING`]}default:{const f=v(n,s);return[M(t,e,f),i`${a(f)} ON CONFLICT DO NOTHING`]}}},Ot={uniqueKeyMissing:!1,unmappedSkipped:0},ft=new Set,ut=(n,t)=>{ft.has(n)||(ft.add(n),console.warn(`[@lunora/sql-store] ${t}`))},ct=100,dt=3,K=async(n,t,e,r=0)=>{const{companion:s,definition:o,index:a,tableName:f}=e,u={done:!0,last:r,left:0};if((await p(n,t,t.tableExists(f))).length===0)return u;const d=await p(n,t,bt(s,ct,r));if(d.length===0)return u;const w=Math.max(...d.map(_=>Number(_.rowid))),E=Ut(d),l=await J(n,t,f,[...E.keys()]),m=[];for(const[_,nt]of E){const P=l.get(_),et=P===void 0?void 0:Q(o,P),it=_t(t,f,_,P);m.push(...et?mt(s,_,X(et,a),{guard:it,unmappedRowids:nt}):pt(s,_,{guard:it,unmappedRowids:nt}))}await A(n,t,m);const R=await p(n,t,i`SELECT COUNT(*) AS ${i.identifier("n")} FROM ${i.identifier(s)} WHERE ${$(s,"rowid")} > ${Math.max(0,r)} AND ${$(s,"rowid")} <= ${w}`);return{done:d.length<ct,last:w,left:Number(R[0]?.n??0)}},en=async(n,t,e)=>{let r=0,s=0;for(;;){let o=await K(n,t,e,r);for(let a=1;o.left>0&&a<dt;a+=1)o=await K(n,t,e,r);if(o.left>0&&(s+=o.left,console.warn(`[@lunora/sql-store] search migration of "${e.companion}": ${String(o.left)} row(s) lost every one of ${String(dt)} attempts to a concurrent write and were left for a later pass.`)),o.done)return s;r=o.last}},rn=async(n,t,e,r)=>r==="step"?(await K(n,t,e),Ot):{uniqueKeyMissing:!1,unmappedSkipped:await en(n,t,e)},G=n=>`${n}__btree`,sn=async(n,t,e)=>{const r=Z(t,e),s=await C(n,t,e,r.name);if(s!=="valid"){if(s==="absent"&&(await p(n,t,i`SELECT 1 AS ${i.identifier("present")} FROM ${i.identifier(e)} LIMIT 1`)).length===0)try{await V(n,t,{...r,concurrently:!1}),await L(n,t,e,G(e));return}catch(a){if(await C(n,t,e,r.name).catch(()=>{})==="valid")return;ut(`${e}:empty`,`search companion "${e}": adding its unique key failed (${String(a)}); run backfillSqlSearchIndexes.`);return}ut(`${e}:missing`,`search companion "${e}" has no usable unique key, so two backfills racing over one row can index it twice. Run backfillSqlSearchIndexes, which adds it.`)}},on=async(n,t,e)=>{const r=$(e,S),s=$(e,g);return(await p(n,t,i`SELECT ${r} AS ${i.identifier("id")}, ${s} AS ${i.identifier("token")}, COUNT(*) AS ${i.identifier("n")} FROM ${i.identifier(e)} GROUP BY ${r}, ${s} HAVING COUNT(*) > 1`)).map(a=>({count:Number(a.n),id:String(a.id),token:String(a.token)}))},an=(n,t,{count:e,id:r,token:s})=>{const o=i`${$(t,S)} = ${r} AND ${$(t,g)} = ${s}`;switch(n.name){case"mysql":return i`DELETE FROM ${i.identifier(t)} WHERE ${o} LIMIT ${i.raw(String(e-1))}`;case"postgres":return i`DELETE FROM ${i.identifier(t)} WHERE ctid = ANY (ARRAY(SELECT ctid FROM ${i.identifier(t)} WHERE ${o} OFFSET 1))`;default:return i`DELETE FROM ${i.identifier(t)} WHERE rowid IN (SELECT rowid FROM ${i.identifier(t)} WHERE ${o} LIMIT -1 OFFSET 1)`}},fn=async(n,t,e,r)=>{const{companion:s,definition:o,index:a,tableName:f}=e;for(const d of r)await T(n,t,an(t,s,d));const u=[...new Set(r.map(d=>d.id))],c=await J(n,t,f,u);for(const d of u){const w=c.get(d),E=w===void 0?void 0:Q(o,w);if(w!==void 0&&E){const l=[...Tt(E,a)];await A(n,t,Nt(t,s,d,l,{row:w,table:f}));continue}await T(n,t,M(s,d,_t(t,f,d,w)))}},un=async(n,t,e)=>t.name!=="mysql"?"":(await p(n,t,i`SELECT COLUMN_NAME AS ${i.identifier("name")}, COLLATION_NAME AS ${i.identifier("collation")} FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ${e} AND COLUMN_NAME IN (${g}, ${S})`)).filter(s=>!String(s.collation).endsWith("_bin")).map(s=>` Its ${String(s.name)} column uses ${String(s.collation)}, which treats values differing only in case or accents as one; convert it with ALTER TABLE \`${e}\` MODIFY \`${String(s.name)}\` VARCHAR(768) COLLATE utf8mb4_0900_bin NOT NULL.`).join(""),cn=async(n,t,e)=>{if(t.name!=="mysql")return 0;const r=$(e,S),s=await p(n,t,i`SELECT COUNT(*) AS ${i.identifier("n")} FROM (SELECT 1 AS ${i.identifier("x")} FROM ${i.identifier(e)} GROUP BY LEFT(${r}, ${i.raw(String(z))}), ${$(e,g)} HAVING COUNT(DISTINCT ${r}) > 1) AS ${i.identifier("shared")}`);return Number(s[0]?.n??0)},dn=async(n,t,e)=>{const r=Z(t,e),s=await C(n,t,e,r.name);if(s==="valid")return"valid";s==="invalid"&&await L(n,t,e,r.name);try{return await V(n,t,r),"built"}catch(o){const a=await C(n,t,e,r.name);if(a==="valid")return"valid";if(a==="invalid"&&await L(n,t,e,r.name),!t.isUniqueViolation(o))throw o;return"refused"}},$t=3,$n=async(n,t,e)=>{const{companion:r}=e,s=await un(n,t,r);let o="";s!==""&&console.warn(`[@lunora/sql-store] search companion "${r}" folds case and accents in its unique key.${s}`);for(let a=0;a<$t;a+=1){const f=await dn(n,t,r);if(f==="valid")return await L(n,t,r,G(r)),!0;if(f==="refused"){const u=await on(n,t,r);if(u.length>0)await fn(n,t,e,u);else{const c=await cn(n,t,r);o=c>0?` ${String(c)} token(s) are held by document ids that agree on their first ${String(z)} characters, which the key cannot tell apart; shorten those ids.`:s}}}return await C(n,t,r,Z(t,r).name)==="valid"?(await L(n,t,r,G(r)),!0):(console.warn(`[@lunora/sql-store] search companion "${r}" still has no unique key after ${String($t)} attempts: writes keep working, but two backfills racing over one row can index it twice.${o}`),!1)},wn=async(n,t,e,r)=>r==="step"?Ot:{uniqueKeyMissing:!await $n(n,t,e),unmappedSkipped:0},Sn=(n,t)=>t?i`${i.identifier(g)} LIKE ${`${n}%`}`:i`${i.identifier(g)} = ${n}`,At=(n,t)=>{const e=t.filters.map(r=>i`m.${rt(r.field)} = ${Wt(r.value)}`);return n.softDeleteMode&&e.push(i`m.${rt(n.softDeleteMode.field)} IS NULL`),t.scope!==void 0&&e.push(i`(${t.scope})`),e},It=async(n,t,e,r,s,o,a)=>{const f=At(e,s);let u=i`SELECT m.* FROM (${a}) s JOIN ${i.identifier(r)} m ON m.${i.identifier("id")} = s.${i.identifier(S)}`;return f.length>0&&(u=i`${u} WHERE ${i.join(f,i` AND `)}`),u=i`${u} ORDER BY s.${i.identifier("__score__")} DESC, m.${i.identifier("_creationTime")} DESC, m.${i.identifier("id")} ASC LIMIT ${i.raw(String(o))}`,ht(e,await p(n,t,u))},En=async(n,t,e,r,s,o)=>{const a=b(s.query,q(s.definition.language));if(a.length===0)return[];const f=U(r,s.indexName),u=a.length-1,c=a.map((m,R)=>Sn(m,R===u)),d=i.join(c,i` OR `),w=c.map(m=>i`SUM(CASE WHEN ${m} THEN ${i.identifier(O)} ELSE 0 END)`),E=i.join(w.map(m=>i`${m} > 0`),i` AND `),l=i`SELECT ${i.identifier(S)}, ${i.join(w,i` + `)} AS ${i.identifier("__score__")} FROM ${i.identifier(f)} WHERE ${d} GROUP BY ${i.identifier(S)} HAVING ${E}`;return It(n,t,e,r,s,o,l)},ln=async(n,t,e,r,s,o)=>{const a=b(s.query,q(s.definition.language));if(a.length===0)return[];const f=U(r,s.indexName),u=`${f}__vocab`,c=a.length-1,d=a.map((l,m)=>{const R=Qt(l,m===c),_=R.exact?i`${i.identifier("term")} = ${R.lower}`:i`${i.identifier("term")} >= ${R.lower} AND ${i.identifier("term")} < ${R.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(m))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(u)} WHERE ${_} GROUP BY ${i.identifier("doc")}`}),w=a.map((l,m)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(m))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),E=i`SELECT f.${i.identifier(S)} AS ${i.identifier(S)}, ${i.join(w,i` + `)} AS ${i.identifier("__score__")} FROM (${Ht(d)}) u JOIN ${i.identifier(f)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(S)} HAVING ${i.join(w.map(l=>i`${l} > 0`),i` AND `)}`;return It(n,t,e,r,s,o,E)},mn=async(n,t,e,r,s,o)=>{const a=t.nativeTextSearch,f=b(s.query,q(s.definition.language));if(!a||f.length===0)return[];const u=U(r,s.indexName),c=[a.matches(u,f),...At(e,s)],d=i`SELECT m.* FROM ${i.identifier(u)} JOIN ${i.identifier(r)} m ON m.${i.identifier("id")} = ${i.identifier(u)}.${i.identifier(S)} WHERE ${i.join(c,i` AND `)} ORDER BY ${a.rank(u,f)} DESC, m.${i.identifier("_creationTime")} DESC, m.${i.identifier("id")} ASC LIMIT ${i.raw(String(o))}`;return ht(e,await p(n,t,d))},pn={ensureCompanion:async(n,t,e)=>{const{integer:r,key:s}=t.companionTypes;await T(n,t,i`CREATE TABLE IF NOT EXISTS ${i.identifier(e)} (${i.identifier(g)} ${i.raw(s)} NOT NULL, ${i.identifier(S)} ${i.raw(s)} NOT NULL, ${i.identifier(O)} ${i.raw(r)} NOT NULL)`),await V(n,t,{columns:x(t,S,191),name:`${e}__by_id`,table:e,unique:!1}),await sn(n,t,e)},indexDocument:async(n,t,e,r,s,o)=>{const a=[...Tt(r,s)];await A(n,t,Nt(t,e,String(o.row.id),a,o))},migrate:wn,name:"inverted",purgeDocument:async(n,t,e,r,s)=>{await T(n,t,M(e,r,k(s,r)))},runSearch:En},hn={ensureCompanion:async(n,t,e)=>{await A(n,t,kt(e))},indexDocument:async(n,t,e,r,s,o)=>{await A(n,t,mt(e,String(o.row.id),X(r,s),{guard:v(t,o)}))},migrate:rn,name:"fts5",purgeDocument:async(n,t,e,r,s)=>{await A(n,t,pt(e,r,{guard:k(s,r)}))},runSearch:ln},gn={ensureCompanion:async(n,t,e)=>{const r=t.nativeTextSearch;if(r){await T(n,t,r.createCompanion(e,t.companionTypes.key));for(const s of r.createIndexes(e))await T(n,t,s)}},indexDocument:async(n,t,e,r,s,o)=>{const a=t.nativeTextSearch;a&&await T(n,t,a.indexDocument(e,String(o.row.id),X(r,s),v(t,o)))},name:"native",purgeDocument:async(n,t,e,r,s)=>{await T(n,t,M(e,r,k(s,r)))},runSearch:mn},I=(n,t)=>n.strategy==="native"&&t.nativeTextSearch!==void 0?gn:t.supportsFts5?hn:pn,H=(n,t)=>`${vt(n)}/${I(n,t).name}`,tt=function*(n){for(const[t,e]of Object.entries(n.tables)){const r=e.searchIndexes;if(!(e.shardMode!==void 0&&e.shardMode.kind!=="global"||!r))for(const s of r)yield[t,e,s]}},N=(n,t)=>U(n,t.name),Tn=async(n,t,e,r)=>{const s=N(e,r);return lt(await F(n,t,s),H(r,t)).finished?!0:Ft(n,t,s)},Fn=async(n,t,e,r,s,o)=>{if(!await Tn(n,t,r,s.definition))throw new h("SEARCH_INDEX_BUILDING",`search index "${s.indexName}" on table "${r}" is still backfilling and currently covers only part of the table — retry once it finishes${t.searchBackfillHint===void 0?"":`, or complete it now: ${t.searchBackfillHint}`}`);return I(s.definition,t).runSearch(n,t,e,r,s,o)},wt=n=>n.slice(n.lastIndexOf("/")+1),St=200,Et=5,yn=async(n,t,e,r)=>{const s=[...r.keys()],o=await p(n,t,i`SELECT * FROM ${i.identifier(e)} WHERE ${i.identifier("id")} >= ${s[0]} AND ${i.identifier("id")} <= ${s.at(-1)} ORDER BY ${i.identifier("id")} ASC`),a=new Map;for(const f of o){const u=f.id,c=r.get(u)?.row;c&&yt.some(d=>String(c[d])!==String(f[d]))&&a.set(u,{row:f})}return a},Y=async(n,t,e,r,s,o,a)=>{const f=I(o,t);let u=a;for(let c=0;u.size>0&&c<Et;c+=1){for(const{document:d,row:w}of u.values()){const E=d??Q(e,w);E&&await f.indexDocument(n,t,s,E,o,{row:w,table:r})}u=await yn(n,t,r,u)}u.size>0&&console.warn(`[@lunora/sql-store] search index "${s}": ${String(u.size)} row(s) were rewritten on every one of ${String(Et)} re-check rounds and were left to their writers — each stays stale only if none of those writes changed its indexed text.`)},Ct=async(n,t,e,r,s)=>{const o=N(r,s),a=H(s,t),f=lt(await F(n,t,o),a);if(f.finished)return!0;if(f.wipe&&await D(n,t,o,void 0,!1,a),(await p(n,t,t.tableExists(r))).length===0)return await D(n,t,o,void 0,!0,a),!0;const c=await xt(n,t,r,f.cursor,St),d=c.findLast(l=>typeof l.id=="string")?.id,w=new Map;for(const l of c)typeof l.id=="string"&&w.set(l.id,{row:l});await Y(n,t,e,r,o,s,w);const E=c.length<St;return await D(n,t,o,d??f.cursor,E,a),E},Lt=async(n,t,e)=>{await Dt(n,e);for(const[r,,s]of tt(t)){const o=N(r,s),a=H(s,e),f=await F(n,e,o);f.profile!==void 0&&wt(f.profile)!==wt(a)&&(await T(n,e,i`DROP TABLE IF EXISTS ${i.identifier(o)}`),await T(n,e,i`DROP TABLE IF EXISTS ${i.identifier(Pt(o))}`),await qt(n,e,o)),await I(s,e).ensureCompanion(n,e,o)}},Rn=async(n,t,e,r,s)=>{const o=N(r,s);if((await F(n,t,o)).profile!==void 0)return;let f=0;(await p(n,t,t.tableExists(r))).length>0&&await Kt(n,t,e,r,()=>{f+=1},{limit:1}),await D(n,t,o,void 0,f===0,H(s,t))},Mt=async(n,t,e,r,s,o)=>await I(s,t).migrate?.(n,t,{companion:N(r,s),definition:e,index:s,tableName:r},o)??{uniqueKeyMissing:!1,unmappedSkipped:0},bn=async(n,t,e)=>{await Lt(n,t,e);for(const[r,s,o]of tt(t)){if(await Mt(n,e,s,r,o,"step"),o.staged){await Rn(n,e,s,r,o);continue}await Ct(n,e,s,r,o)}},Un=async(n,t,e)=>{const r={uniqueKeyMissing:[],unmappedSkipped:0};await Lt(n,t,e);for(const[s,o,a]of tt(t)){const f=await Mt(n,e,o,s,a,"drain");r.unmappedSkipped+=f.unmappedSkipped,f.uniqueKeyMissing&&r.uniqueKeyMissing.push(N(s,a));let u=!1;for(;!u;)u=await Ct(n,e,o,s,a)}return r},kn=n=>{const{dialect:t,exec:e,schema:r}=n;return async(s,o,a)=>{const f=r.tables[s],u=f?.searchIndexes;if(!(!f||!u||u.length===0))for(const c of u){if(nn(a?.previous,a?.document,c))continue;const d=N(s,c);if(a){await Y(e,t,f,s,d,c,new Map([[o,{document:a.document,row:{...a.written,id:o}}]]));continue}await I(c,t).purgeDocument(e,t,d,o,s);const E=(await J(e,t,s,[o])).get(o);E!==void 0&&await Y(e,t,f,s,d,c,new Map([[o,{row:E}]]))}}};export{Cn as A,vn as C,Dn as R,qn as T,Fn as a,Un as b,kn as c,Mn as d,bn as r,st as u,Ln as x};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{b as $,q as h}from"./sql-exec-CkHeSf_v.mjs";const y=["de","en","es","fr","it","nl","none","pt"],L=i=>y.includes(i),R="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",A="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",q="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",F="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",N="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",_="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",b="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ê",C=new RegExp("(?<=\\p{Script=Cyrillic})[\\u0300-\\u0305\\u0307\\u0309-\\u036F]|(?<!\\p{Script=Cyrillic})[\\u0300-\\u036F]","gu"),x=/[\u0080-\u{10FFFF}]/u,H=/[\p{L}\p{N}]+/gu,O=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]+/gu,g=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]/u,j=i=>{if(!g.test(i))return[i];const n=[];let t=0;for(const r of i.matchAll(O)){const o=r.index,s=[...r[0]];if(o>t&&n.push(i.slice(t,o)),t=o+r[0].length,s.length===1){n.push(r[0]);continue}for(let a=0;a+1<s.length;a+=1)n.push(`${String(s[a])}${String(s[a+1])}`)}return t<i.length&&n.push(i.slice(t)),n},v=i=>x.test(i)?i.normalize("NFD").replaceAll(C,"").normalize("NFC").toLowerCase():i.toLowerCase(),p=i=>new Set(v(i).split(" ")),z={de:p(A),en:p(R),es:p(q),fr:p(F),it:p(N),nl:p(_),none:new Set,pt:p(b)},D=3,U=256,w=new Map,k=i=>{const n=i!==void 0&&L(i)?i:"none",t=w.get(n);if(t)return t;const r=z[n],o=a=>{const u=v(a),f=u.match(H)??[],l=(g.test(u)?f.flatMap(c=>j(c)):f).filter(c=>c.length<=U);return r.size===0?l:l.filter(c=>!r.has(c))},s={document:o,profile:`${n}-v${String(D)}`,query:a=>{const u=o(a),f=new Set,l=[];for(let c=u.length-1;c>=0;c-=1){const m=u[c];f.has(m)||(f.add(m),l.push(m))}return l.toReversed()}};return w.set(n,s),s},W=i=>`${k(i.language).profile}:${i.field}`,S=i=>{const n=i.slice(i.indexOf(":")+1),t=n.lastIndexOf("/");return t===-1?n:n.slice(0,t)},V=(i,n)=>i.profile!==n?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},M=(i,n)=>typeof i=="string"&&S(i)===S(n),d="__lunora_search_state",K=async(i,n)=>{const{integer:t,key:r}=n.companionTypes,o=async(s,a)=>{try{await $(i,n,e`ALTER TABLE ${e.identifier(d)} ADD COLUMN ${e.identifier(s)} ${e.raw(a)}`)}catch{}};await $(i,n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(d)} (${e.identifier("companion")} ${e.raw(r)} PRIMARY KEY, ${e.identifier("cursor")} ${e.raw(r)}, ${e.identifier("done")} ${e.raw(t)} NOT NULL DEFAULT 0, ${e.identifier("profile")} ${e.raw(r)}, ${e.identifier("covered")} ${e.raw(t)} NOT NULL DEFAULT 0)`),await o("profile",r),await o("covered",`${t} NOT NULL DEFAULT 0`),await $(i,n,e`UPDATE ${e.identifier(d)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},T=i=>i===1||i===!0||i==="1",P=async(i,n,t)=>{const r=await h(i,n,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(d)} WHERE ${e.identifier("companion")} = ${t}`);return T(r[0]?.covered)},Y=async(i,n,t)=>{await $(i,n,e`DELETE FROM ${e.identifier(d)} WHERE ${e.identifier("companion")} = ${t}`)},X=async(i,n,t)=>{const o=(await h(i,n,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(d)} WHERE ${e.identifier("companion")} = ${t}`))[0];if(!o)return{cursor:void 0,done:!1,profile:void 0};const{cursor:s,profile:a}=o;return{cursor:typeof s=="string"?s:void 0,done:T(o.done),profile:typeof a=="string"?a:void 0}},G=async(i,n,t,r,o,s)=>{const a=r??null,u=await h(i,n,e`SELECT ${e.identifier("profile")} FROM ${e.identifier(d)} WHERE ${e.identifier("companion")} = ${t}`),f=M(u[0]?.profile,s),l=o?1:0,c=o||!f?e`${e.identifier("covered")} = ${l}`:e`${e.identifier("covered")} = ${e.identifier("covered")}`,m=e`UPDATE ${e.identifier(d)} SET ${e.identifier("cursor")} = ${a}, ${e.identifier("done")} = ${l}, ${e.identifier("profile")} = ${s}, ${c} WHERE ${e.identifier("companion")} = ${t}`;if(u.length>0){await $(i,n,m);return}try{await $(i,n,e`INSERT INTO ${e.identifier(d)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${t}, ${a}, ${o?1:0}, ${s}, ${o?1:0})`)}catch(E){if(!n.isUniqueViolation(E))throw E;await $(i,n,m)}};export{d as S,Y as a,P as b,W as c,V as l,K as m,k as q,X as r,G as w};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as k}from"@lunora/errors";import{needsWireEncoding as _,encodeWire as A,decodeWire as S}from"@lunora/wire";import{sql as p}from"drizzle-orm";import{runSqlGlobalTableMigrations as E}from"./runSqlGlobalTableMigrations-C7teG_kd.mjs";import{r as L,d as $,M as w,q as O}from"./sql-exec-CkHeSf_v.mjs";const D=200,m=(o,t)=>{const n=e=>o.tables[e]?.shardMode?.kind==="global";return t&&t.length>0?t.filter(e=>n(e)):Object.keys(o.tables).filter(e=>n(e))},F=o=>_(o)?A(o):o,Y=async function*(o,t,n,e){const i=m(t,e.tables),r=e.batchSize??D;await E(o,t,n);for(const s of i){const d=t.tables[s];let c,a=!0;for(;a;){const f=await L(o,n,s,c,r);for(const u of f)yield{doc:F($(d,u)),table:s};const l=f.at(-1);l!==void 0&&(c=String(l.id)),a=f.length===r}}},h=o=>o?._meta?.column?.notNull===!1,N=(o,t)=>{const n=new Set;for(const[e,i]of Object.entries(o.shape)){if(t[e]!==null||i.kind!=="optional"||h(i))continue;const r=i._meta?.inner;h(r)||n.add(e)}return n.size===0?t:Object.fromEntries(Object.entries(t).filter(([e])=>!n.has(e)))},T=new Set(["_creationTime","_id"]),M=(o,t)=>Object.keys(t).find(n=>!T.has(n)&&!Object.hasOwn(o.shape,n)),C=o=>{const t=o._id,n=o._creationTime;if(t!==void 0&&(typeof t!="string"||t===""))return'field "_id": must be a non-empty string';if(n!==void 0&&(typeof n!="number"||!Number.isFinite(n)))return'field "_creationTime": must be a finite number'},j=(o,t,n)=>{const e=o.tables[t];if(!e)return`unknown table: ${t}`;const i=M(e,n);if(i!==void 0)return`unexpected field "${i}": not declared in table "${t}"`;const r=C(n);if(r!==void 0)return r;for(const[s,d]of Object.entries(e.shape)){const c=n[s],a=d.kind==="optional";if(c===void 0&&a)continue;const f=d.parse;if(typeof f=="function")try{f(c)}catch(l){const u=l instanceof Error?l.message:String(l);return`field "${s}": ${u}`}}},v=async(o,t,n,e,i,r)=>{const s=Object.keys(t.tables).filter(c=>c!==i&&t.tables[c]?.shardMode?.kind==="global"),d=[i,...s];for(let c=0;c<d.length;c+=w){const a=d.slice(c,c+w);if(!e){for(const b of a)if(await o.get(b,r)!==null)return b;continue}const f=a.map((b,I)=>p`SELECT ${p.raw(String(I))} AS slot FROM ${p.identifier(b)} WHERE ${p.identifier("id")} = ${r}`),u=(await O(e,n,p`${p.join(f,p` UNION ALL `)} ORDER BY slot LIMIT 1`))[0]?.slot;if(u!==void 0)return a[Number(u)]}},y=(o,t,n,e)=>({code:"ID_COLLISION",line:n,message:`_id "${t}" already belongs to table "${o}"`,table:e}),x=async(o,t,n,e,i,r,s)=>{let d;try{d=await v(o,t,n,e,i,r)}catch(c){const{body:a}=k(c,{fallbackCode:"PROBE_FAILED"});return{error:{code:a.code,line:s,message:a.message,table:i}}}return d!==void 0&&d!==i?{error:y(d,r,s,i)}:{existingId:d===i?r:void 0}},g=(o,t,n)=>{const e=o.owners.get(t)??new Set;e.add(n),o.owners.set(t,e)},B=async(o,t,n,e)=>{const i=new Map;let r=[],s=w;const d=async()=>{if(r.length===0)return;const c=await O(o,t,p.join(r,p` UNION ALL `));for(const a of c)g({owners:i},String(a.id),n[Number(a.slot)]);r=[],s=w};try{for(const[c,a]of n.entries())for(let f=0;f<e.length;){const l=e.slice(f,f+s);r.push(p`SELECT ${p.raw(String(c))} AS slot, ${p.identifier("id")} FROM ${p.identifier(a)} WHERE ${p.identifier("id")} IN (${p.join(l.map(u=>p.param(u)),p`, `)})`),f+=l.length,s-=l.length,s===0&&await d()}await d()}catch(c){const{body:a}=k(c,{fallbackCode:"PROBE_FAILED"});return{failure:{code:a.code,message:a.message}}}return{owners:i}},W=(o,t,n,e,i)=>{if("failure"in o)return{error:{...o.failure,line:i,table:n}};const r=o.owners.get(e);if(r?.has(n)===!0)return{existingId:e};const s=t.find(d=>r?.has(d)===!0);return s===void 0?{existingId:void 0}:{error:y(s,e,i,n)}},R=async(o,t,n,e,i)=>{try{if(e!==void 0){const r={...n};return delete r._id,await o.replace(t,e,r,{allowExplicitId:!0}),{kind:"replaced"}}return await o.insert(t,n,{allowExplicitId:!0}),{inserted:t,kind:"inserted"}}catch(r){const{body:s}=k(r,{fallbackCode:e===void 0?"INSERT_FAILED":"REPLACE_FAILED"});return{error:{code:s.code,line:i,message:s.message,table:t},kind:"error"}}},G=(o,t,n,e)=>{const{doc:i,table:r}=n;if(typeof r!="string"||r.length===0)return{kind:"settled",outcome:{error:{code:"BAD_ROW",line:e,message:"row is missing `table`",table:r},kind:"error"}};if(o.tables[r]?.shardMode?.kind!=="global")return{kind:"settled",outcome:{kind:"skip"}};if(!i||typeof i!="object"||Array.isArray(i))return{kind:"settled",outcome:{error:{code:"BAD_ROW",line:e,message:"row is missing or malformed `doc`",table:r},kind:"error"}};let s;try{s=S(i)}catch(c){return{kind:"settled",outcome:{error:{code:"BAD_ROW",line:e,message:c instanceof Error?c.message:String(c),table:r},kind:"error"}}}s=N(o.tables[r],s);const d=j(o,r,s);return d!==void 0?{kind:"settled",outcome:{error:{code:"VALIDATION_ERROR",line:e,message:d,table:r},kind:"error"}}:t?{kind:"settled",outcome:{kind:"checked"}}:{decoded:s,explicitId:typeof s._id=="string"?s._id:void 0,kind:"ready",line:e,table:r}},P=async(o,t,n,e,i,r,s)=>{const{decoded:d,explicitId:c,line:a,table:f}=r;let l;try{l=await v(o,t,n,e,f,c)}catch{return}if(l!==void 0)return g(i,c,l),l!==f?{error:y(l,c,a,f),kind:"error"}:s==="replace"?R(o,f,d,c,a):{kind:"conflict"}},z=async(o,t,n,e,i,r)=>{const{decoded:s,explicitId:d,line:c,table:a}=i;let f={existingId:void 0};if(d!==void 0&&(f=r===void 0?await x(o,t,n,e.exec,a,d,c):W(r,m(t),a,d,c)),"error"in f)return{error:f.error,kind:"error"};const{existingId:l}=f;if(l!==void 0&&e.onConflict!=="replace")return{kind:"conflict"};const u=await R(o,a,s,l,c);if(r===void 0||"failure"in r||e.exec===void 0||d===void 0)return u;if(u.kind==="inserted"||u.kind==="replaced")g(r,d,a);else if(u.kind==="error"&&u.error.code==="CONFLICT"&&l===void 0)return await P(o,t,n,e.exec,r,{...i,explicitId:d},e.onConflict)??u;return u},U=async(o,t,n,e)=>{const i=new Set;for(const r of e)r.kind==="ready"&&r.explicitId!==void 0&&i.add(r.explicitId);if(i.size===0)return{owners:new Map};try{await E(o,t,n)}catch(r){const{body:s}=k(r,{fallbackCode:"PROBE_FAILED"});return{failure:{code:s.code,message:s.message}}}return B(o,n,m(t),[...i])},Z=async(o,t,n,e)=>{const i=[],r={};let s=0,d=0,c=(e.startLine??1)-1;const a=e.rows.map(l=>(c+=1,G(t,e.dryRun===!0,l,l.line??c)));let f;e.exec&&e.dryRun!==!0&&(f=await U(e.exec,t,n,a));for(const l of a){const u=l.kind==="settled"?l.outcome:await z(o,t,n,e,l,f);switch(u.kind){case"conflict":{s+=1;break}case"error":{i.push(u.error);break}case"inserted":{r[u.inserted]=(r[u.inserted]??0)+1;break}case"replaced":{d+=1;break}}}return{conflicts:s,errors:i,inserted:r,replaced:d}};export{Y as exportSqlGlobalRows,Z as importSqlGlobalRows,m as selectGlobalTables};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as v}from"@lunora/errors";import{aggregateTableName as Y,rankTableName as V,sortColumnName as O,bigintSqlKey as Q}from"@lunora/shard-engine";import{sql as t}from"drizzle-orm";import{b as z,e as g,B as C,r as Z,i as J,U as nn,c as en}from"./value-codec-C52YW-Do.mjs";import{O as A,t as tn,b as d,q as $,c as _,e as m,f as on,s as rn,g as sn}from"./sql-exec-CkHeSf_v.mjs";const an=new Set(["any","null"]),U=(e,n)=>{const i=n.kindOf(e);return i!==void 0&&an.has(i)||n.nullableOf(e)?!0:i==="union"&&(n.membersOf(e)??[]).some(o=>U(o,n))},S=e=>{const n=e._meta?.inner;return e.kind==="optional"&&n?S(n):e},R=e=>U(e,{kindOf:z,membersOf:n=>S(n)._meta?.members,nullableOf:n=>S(n)._meta?.column?.notNull===!1}),k=(e,n,i=!1)=>n.columnType(g(e),{unique:i||e._meta?.column?.unique===!0}),x=e=>{const n=new Set;for(const i of e.indexes)i.unique===!0&&i.fields.length===1&&n.add(i.fields[0]);return n},ln=(e,n,i)=>{if(i.indexKeyPrefix!==void 0)for(const o of n.indexes){if(o.unique!==!0||o.fields.length<=1)continue;const r=o.fields.filter(s=>{const a=n.shape[s];return a!==void 0&&i.indexKeyPrefix?.(g(a))!==void 0});if(r.length>0)throw new Error(`${e}.${o.name}: a composite unique index cannot cover ${r.join(", ")} in full on this engine (its key limit forces a prefix, which would constrain the prefix rather than the value). Split it into single-column unique indexes, or store those fields as a bounded type.`)}},un=e=>e._meta?.column?.notNull===!0&&e.kind!=="optional"&&!R(e),cn=(e,n,i)=>{const o=[],r=x(n);for(const[u,c]of Object.entries(n.shape)){if(!c._meta?.column)continue;const f=un(c)?" NOT NULL":"";o.push(t`${t.identifier(u)} ${t.raw(`${k(c,i,r.has(u))}${f}`)}`)}const s=[...i.frameworkColumns().map(u=>t`${t.identifier(u.name)} ${t.raw(u.type)}`),t`${t.identifier(A)} ${t.raw(i.companionTypes.integer)}`],a=s.length+o.length,l=i.maxTableColumns;if(l!==void 0&&a>l){const u=a-1===l,c="Move one or more fields into a single object field, or split the table — either way the existing rows need a data migration (`defineMigration` + `lunora migrate up`); there is no in-place path.";throw new v("VALIDATION_ERROR",`@lunora/sql-store: global table "${e}" needs ${String(a)} columns, over this engine's ${String(l)}-column limit. ${u?`One of them is "${A}", the row version every guarded write reads, which caps declared fields at ${String(l-s.length)}. A table provisioned at ${String(l)} columns before that column existed cannot be widened to hold it. `:""}${c}`)}return t.join([...s,...o],t`, `)},M=e=>{if(e.indexKeyPrefix?.("string")===void 0)return t`${m("_creationTime")}, ${m("id")}`},b=new Set,B=async(e,n,i,o)=>{const r=t.join(i.refs.map(a=>t`${a} IS NOT NULL`),t` AND `);if((await $(e,n,t`SELECT ${i.columns} FROM ${t.identifier(i.table)} WHERE ${r} GROUP BY ${i.columns} HAVING COUNT(*) > 1 LIMIT 1`)).length>0){const a=`unique index "${i.name}" on "${i.table}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first.`;throw b.has(a)||(b.add(a),console.error(`[@lunora/sql-store] ${a}`)),new v("UNIQUE_INDEX_DUPLICATES",a)}},fn=async(e,n,i)=>{if(!i.unique){await _(e,n,i);return}try{await _(e,n,i)}catch(o){throw n.isUniqueViolation(o)&&await B(e,n,i,"cannot be created"),o}},F=e=>{const n=e.indexOf("(");return n===-1?void 0:e.slice(n,e.lastIndexOf(")")+1)},dn=(e,n)=>{const i=n.unique?t`UNIQUE `:t``;return F(e.render(t`CREATE ${i}INDEX ${t.identifier(n.name)} ON ${t.identifier(n.table)} (${n.columns})`).sql)},mn=(e,n,i)=>{const o=dn(e,i);return o!==void 0&&o!==F(n)},P=async(e,n,i)=>{if(n.name!=="sqlite")return;const r=(await $(e,n,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${i.name} COLLATE NOCASE AND tbl_name = ${i.table} COLLATE NOCASE`))[0]?.sql;typeof r=="string"&&mn(n,r,i)&&(i.unique&&await B(e,n,i,"cannot be re-created with its new column list; the previous index is left in place"),await d(e,n,t`DROP INDEX IF EXISTS ${t.identifier(i.name)}`))},$n=(e,n,i)=>{ln(e,n,i);const o=x(n),r=l=>{const u=m(l),c=n.shape[l],f=c&&i.indexKeyPrefix&&c._meta?.column?.unique!==!0&&!o.has(l)?i.indexKeyPrefix(g(c)):void 0;return f===void 0?u:t`${u}(${t.raw(String(f))})`},s=M(i),a=[];for(const l of n.indexes){const u=l.fields.map(E=>r(E)),c=t.join(u,t`, `),f=l.unique??!1;a.push({columns:f||s===void 0?c:t`${c}, ${s}`,kind:"declared",name:`${e}_${l.name}`,refs:u,table:e,unique:f})}s!==void 0&&a.push({columns:s,kind:"default-order",name:`${e}__by_creation`,refs:[],table:e,unique:!1});for(const[l,u]of tn(n)){if(!u.unique)continue;const c=r(l);a.push({columns:c,kind:"unique-column",name:`${e}_unique_${l}`,refs:[c],table:e,unique:!0})}return a},En=/^\s*create\s+unique\s/iu,h="__lunora_framework_indexes",gn=()=>t`CREATE TABLE IF NOT EXISTS ${t.identifier(h)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`,j=(e,n)=>t`INSERT OR IGNORE INTO ${t.identifier(h)} (name, table_name) VALUES (${e}, ${n})`,w=e=>e.replaceAll(/[A-Z]/gu,n=>n.toLowerCase()),pn=async(e,n,i)=>{if(n.name!=="sqlite"||(await $(e,n,t`SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ${h} COLLATE NOCASE`)).length>0)return;await d(e,n,gn());const r=M(n),s=r===void 0?void 0:`, ${n.render(r).sql})`;for(const a of i){const l=`${w(a)}_`,u=await $(e,n,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`);for(const c of u){const f=String(c.name),E=String(c.sql);w(f).startsWith(l)&&w(f)!==w(`${a}__by_creation`)&&(En.test(E)||s!==void 0&&E.trimEnd().endsWith(s))&&await d(e,n,j(f,a))}}},wn=(e,n,i)=>{if(e.name!=="sqlite")return[];const o=new Set(n.map(r=>w(r.name)));return i.filter(r=>!o.has(w(r)))},hn=async(e,n,i,o)=>{if(o.name!=="sqlite")return;const r=await $(e,o,t`SELECT "l"."name" FROM ${t.identifier(h)} AS "l" WHERE "l"."table_name" = ${n} COLLATE NOCASE`);for(const s of wn(o,i,r.map(a=>String(a.name))))await d(e,o,t`DROP INDEX IF EXISTS ${t.identifier(s)}`),await d(e,o,t`DELETE FROM ${t.identifier(h)} WHERE ${t.identifier(h)}."name" = ${s}`)},Tn=async(e,n,i,o)=>{const r=$n(n,i,o);for(const s of r){if(s.kind==="default-order"){await _(e,o,s);continue}s.kind==="declared"&&await P(e,o,s),await fn(e,o,s),o.name==="sqlite"&&await d(e,o,j(s.name,s.table))}await hn(e,n,r,o)},N="__lunora_migration_state",_n=async(e,n)=>{await d(e,n,t`CREATE TABLE IF NOT EXISTS ${t.identifier(N)} (${t.identifier("name")} ${t.raw(n.companionTypes.key)} PRIMARY KEY)`)},Ln=async(e,n,i)=>(await $(e,n,t`SELECT ${t.identifier("name")} FROM ${t.identifier(N)} WHERE ${t.identifier("name")} = ${i}`)).length>0,yn=async(e,n,i,o,r,s)=>{r>0&&s!==void 0&&console.warn(`[@lunora/sql-store] storage migration "${i}" on "${o}": ${String(r)} row(s) ${s} and were left as stored — range filters and ORDER BY over them stay wrong until they are corrected by hand.`);try{await d(e,n,t`INSERT INTO ${t.identifier(N)} (${t.identifier("name")}) VALUES (${i})`)}catch(a){if(!n.isUniqueViolation(a))throw a}},An=100,Sn=(e,n)=>{const i=[],o=[];for(const r of n.fields){const s=e[r],a=n.convert(s);a!==void 0&&(i.push(t`${m(r)} = ${a}`),o.push(t`${m(r)} = ${s}`))}return{assignments:i,guards:o}},On=e=>t.join(e.fields.map(n=>e.probe(n)),t` OR `),K=async(e,n,i,o)=>{if(o.fields.length===0||(await _n(e,i),await Ln(e,i,o.marker)))return;const r=On(o),s=t.join([m("id"),...o.fields.map(u=>m(u))],t`, `);let a="",l=0;for(;;){const u=await $(e,i,t`SELECT ${s} FROM ${t.identifier(n)} WHERE (${r}) AND ${m("id")} > ${a} ORDER BY ${m("id")} LIMIT ${t.raw(String(An))}`);if(u.length===0){await yn(e,i,o.marker,n,l,o.describeUnconvertible);return}const c=[];for(const E of u){const{id:p}=E,{assignments:T,guards:I}=typeof p=="string"?Sn(E,o):{assignments:[],guards:[]};if(T.length===0){l+=1;continue}c.push(t`UPDATE ${t.identifier(n)} SET ${t.join(T,t`, `)} WHERE ${m("id")} = ${p} AND ${t.join(I,t` AND `)}`)}await sn(e,i,c);const f=u.at(-1)?.id;if(typeof f!="string")return;a=f}},q=e=>`'${e}%'`,Rn=e=>Object.entries(e.shape).filter(([,n])=>n._meta?.column!==void 0&&g(n)==="bigint").map(([n])=>n),Nn=e=>Object.entries(e.shape).filter(([,n])=>n._meta?.column!==void 0&&J(g(n))).map(([n])=>n),G=(e,n)=>({convert:i=>{if(!(typeof i!="string"||i.length===C))try{return Q(BigInt(i))}catch{return}},describeUnconvertible:"hold a value the order-preserving key cannot represent (non-numeric text, or a magnitude past 39 digits)",fields:Rn(n),marker:`bigint-key:${e}`,probe:i=>t`(${m(i)} IS NOT NULL AND LENGTH(${m(i)}) <> ${C})`}),In=async(e,n,i,o)=>K(e,n,o,G(n,i)),H=(e,n)=>({convert:Z,fields:Nn(n),marker:`untyped-number-key:${e}`,probe:i=>t`(${m(i)} LIKE ${t.raw(q(nn))} AND ${m(i)} NOT LIKE ${t.raw(q(en))})`}),Cn=async(e,n,i,o)=>K(e,n,o,H(n,i)),D=new Set,L=(e,n)=>{D.has(e)||(D.add(e),console.warn(`[@lunora/sql-store] ${n}`))},bn=e=>{const n=e._meta?.column;return n?.defaultFn?n.defaultFn():n&&"defaultValue"in n?n.defaultValue:void 0},qn=(e,n,i)=>i._meta?.column?.unique===!0||e.indexes.some(o=>o.unique===!0&&o.fields.includes(n)),Dn=async(e,n,i,o,r,s)=>{if(s.kind==="optional"||R(s))return;const a=qn(i,r,s),l=a?void 0:bn(s),u=`UPDATE "${n}" SET "${r}" = … WHERE "${r}" IS NULL`;if(l===void 0){const c=a?"is unique, so one default cannot be written to every row":"has no default";L(`backfill:${n}.${r}`,`"${n}.${r}" was added as a required field that ${c}, so rows written before it read NULL. Backfill it with a migration (${u}).`);return}try{await d(e,o,t`UPDATE ${t.identifier(n)} SET ${t.identifier(r)} = ${rn(i,r,l)} WHERE ${t.identifier(r)} IS NULL`)}catch(c){L(`backfill:${n}.${r}`,`could not backfill "${n}.${r}" from its default (${c instanceof Error?c.message:String(c)}); rows written before it read NULL. Run ${u}.`)}},vn=(e,n)=>[[A,n.companionTypes.integer],...Object.entries(e.shape).filter(([,i])=>i._meta?.column!==void 0).map(([i,o])=>[i,k(o,n),o])],Un=async(e,n,i,o)=>{const r=vn(i,o),s="t",a=async l=>{try{return await $(e,o,t`SELECT ${t.join(l.map(u=>on(s,u)),t`, `)} FROM ${t.identifier(n)} AS ${t.identifier(s)} LIMIT 0`),!0}catch{return!1}};if(!await a(r.map(([l])=>l)))for(const[l,u,c]of r)await a([l])||(await d(e,o,t`ALTER TABLE ${t.identifier(n)} ADD COLUMN ${t.identifier(l)} ${t.raw(u)}`),c!==void 0&&await Dn(e,n,i,o,l,c))},kn=(e,n,i)=>{const o=typeof i.charset=="string"?` CHARACTER SET ${i.charset} COLLATE ${String(i.collation)}`:"";return`ALTER TABLE \`${e}\` MODIFY COLUMN \`${n}\` ${String(i.type)}${o} NULL`},xn=async(e,n,i,o)=>{if(o.name==="sqlite")return;const r=Object.keys(i.shape).filter(s=>{const a=i.shape[s];return a._meta?.column?.notNull===!0&&a.kind!=="optional"&&R(a)});if(r.length!==0)try{const s=o.name==="postgres"?t`column_name AS ${t.identifier("name")}`:t`column_name AS ${t.identifier("name")}, column_type AS ${t.identifier("type")}, character_set_name AS ${t.identifier("charset")}, collation_name AS ${t.identifier("collation")}`,a=o.name==="postgres"?t`table_schema = ANY (current_schemas(false))`:t`table_schema = DATABASE()`,l=await $(e,o,t`SELECT ${s} FROM information_schema.columns WHERE ${a} AND table_name = ${n} AND is_nullable = 'NO' AND column_name IN (${t.join(r.map(u=>t`${u}`),t`, `)})`);for(const u of l){const c=String(u.name);if(o.name==="postgres"){await d(e,o,t`ALTER TABLE ${t.identifier(n)} ALTER COLUMN ${t.identifier(c)} DROP NOT NULL`);continue}L(`${n}.${c}`,`"${n}"."${c}" accepts null in the schema but its column is NOT NULL, so writing null there fails. Relaxing it on MySQL can rebuild the table, so it is not done at startup; run this once, in a maintenance window: ${kn(n,c,u)};`)}}catch(s){L(`${n}:relax-failed`,`could not relax NOT NULL on the null-accepting columns of "${n}" (${r.join(", ")}): ${s instanceof Error?s.message:String(s)}. Writing null to them fails until the constraint is dropped by hand.`)}},Mn=async(e,n,i,o)=>{const r=cn(n,i,o);await d(e,o,t`CREATE TABLE IF NOT EXISTS ${t.identifier(n)} (${r})`),await Un(e,n,i,o),await xn(e,n,i,o),await Tn(e,n,i,o),await In(e,n,i,o),await Cn(e,n,i,o)},Yn=(e,n)=>[G(e,n),H(e,n)].filter(i=>i.fields.length>0),Vn=async(e,n,i,o)=>{let r=!1;for(const[s,a]of Object.entries(n.tables))a.shardMode?.kind!=="global"||o!==void 0&&!o.has(s)||(r||(r=!0,await pn(e,i,Object.entries(n.tables).filter(([,l])=>l.shardMode?.kind==="global").map(([l])=>l))),await Mn(e,s,a,i))},W=e=>e.shardMode===void 0||e.shardMode.kind==="global",Qn=async(e,n,i)=>{const{integer:o,key:r,real:s}=i.companionTypes;for(const[a,l]of Object.entries(n.tables)){const u=l.aggregateIndexes;if(!(!u||u.length===0||!W(l)))for(const c of u){const f=Y(a,c.name);await d(e,i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(f)} (${t.identifier("__key__")} ${t.raw(r)} PRIMARY KEY, ${t.identifier("__value__")} ${t.raw(s)}, ${t.identifier("__count__")} ${t.raw(o)} NOT NULL DEFAULT 0)`),i.name==="sqlite"&&((await $(e,i,t`PRAGMA table_info(${t.identifier(f)})`)).some(p=>p.name==="__count__")||await d(e,i,t`ALTER TABLE ${t.identifier(f)} ADD COLUMN ${t.identifier("__count__")} ${t.raw(o)} NOT NULL DEFAULT 0`))}}},y=(e,n,i,o)=>{const r=e.name==="mysql"&&o?t`${t.identifier(n)}(191)`:t`${t.identifier(n)}`;return t`${r} ${t.raw(i)}`},Bn=(e,n,i)=>{const o=[y(e,"__partition__","ASC",!0)];for(const[r,s]of n.sortBy.entries()){const a=i.shape[s.field],l=a!==void 0&&e.indexKeyPrefix?.(g(a))!==void 0;o.push(y(e,O(r),s.direction==="desc"?"DESC":"ASC",l))}return o.push(y(e,"__id__","ASC",!0)),o},Fn=(e,n,i)=>n.sortBy.map((o,r)=>{const s=i.shape[o.field],a=e.columnType(s?g(s):void 0);return t`${t.identifier(O(r))} ${t.raw(a)}`}),Pn=/__sort_k\d+__/gu,jn=async(e,n,i,o)=>{if(n.name!=="sqlite")return;const s=(await $(e,n,t`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ${i} COLLATE NOCASE`))[0]?.sql;if(typeof s!="string")return;const a=s.match(Pn)??[];(a.length!==o.length||a.some((l,u)=>l!==o[u]))&&await d(e,n,t`DROP TABLE ${t.identifier(i)}`)},zn=async(e,n,i)=>{const{key:o}=i.companionTypes;for(const[r,s]of Object.entries(n.tables)){const a=s.rankIndexes;if(!(!a||a.length===0||!W(s)))for(const l of a){const u=V(r,l.name),c=Fn(i,l,s);await jn(e,i,u,l.sortBy.map((I,X)=>O(X)));const f=c.length>0?t`, ${t.join(c,t`, `)}`:t``;await d(e,i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(u)} (${t.identifier("__id__")} ${t.raw(o)} PRIMARY KEY, ${t.identifier("__partition__")} ${t.raw(o)} NOT NULL${f})`);const E=Bn(i,l,s),p=`${r}__rank_${l.name}__btree`,T={columns:t.join(E,t`, `),name:p,refs:[],table:u,unique:!1};await P(e,i,T),await _(e,i,T)}}};export{h as INDEX_LEDGER_TABLE,N as MIGRATION_STATE_TABLE,dn as declaredIndexColumnList,w as foldIdentifier,cn as globalTableColumnsDdl,$n as globalTableIndexSpecs,F as indexColumnList,gn as indexLedgerDdl,mn as indexShapeChanged,Yn as legacyRewrites,On as legacyRowPredicate,Mn as provisionGlobalTable,Vn as provisionGlobalTablesSequentially,j as recordIndexStatement,Qn as runSqlAggregateMigrations,zn as runSqlRankMigrations,wn as undeclaredFrameworkIndexes,vn as wantedGlobalColumns};
|