durable-db 0.11.0 → 0.13.0

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/db/index.js CHANGED
@@ -1,205 +1,14 @@
1
1
  import { i as init_debug, n as debugMigrations } from "../debug-Cz8KzMft.js";
2
- import { a as createRelated, c as DrizzleDefaultsPlugin, d as createJsonPlugins, f as dateSerializers, h as relationsOf, i as RelatedExpression, l as SchemaPlugin, m as relationOf, n as defineDatabase, p as parseJsonValue, s as DateSerializePlugin, u as createDrizzlePlugins } from "../defineDatabase-Cb5sMNg0.js";
2
+ import { a as createRelated, c as DrizzleDefaultsPlugin, d as createJsonPlugins, f as dateSerializers, h as relationsOf, i as RelatedExpression, l as SchemaPlugin, m as relationOf, n as defineDatabase, p as parseJsonValue, s as DateSerializePlugin, u as createDrizzlePlugins } from "../defineDatabase-DypFFfjn.js";
3
3
  import { r as type } from "../type-CUgZsZp3.js";
4
4
  import "../actionArgs-DP2tQrlf.js";
5
- import { a as outboxRetryDelay, c as tenantOfInstanceKey, i as createActionOutbox, n as OUTBOX_DDL, o as outboxSink, r as OUTBOX_TABLE, s as queueOutboxSink, t as createKyselyFromSql } from "../kysely-q97dtmaQ.js";
5
+ import { a as outboxRetryDelay, c as tenantOfInstanceKey, i as createActionOutbox, n as OUTBOX_DDL, o as outboxSink, r as OUTBOX_TABLE, s as queueOutboxSink, t as createKyselyFromSql } from "../kysely-DGc-CG_v.js";
6
+ import { t as guardReferencingRows } from "../referencingRows-B6rU7TDW.js";
6
7
  import { CamelCasePlugin } from "kysely";
7
8
  import { DurableObject } from "cloudflare:workers";
8
9
  import { studio } from "@outerbase/browsable-durable-object";
9
- //#region src/db/referencingRows.ts
10
- init_debug();
11
- const NAME = /^\s*(?:`((?:[^`]|``)*)`|"((?:[^"]|"")*)"|\[([^\]]*)\]|([A-Za-z_][\w$]*))/;
12
- function readName(text) {
13
- const match = NAME.exec(text);
14
- if (!match) return null;
15
- return {
16
- name: match[1]?.replaceAll("``", "`") ?? match[2]?.replaceAll("\"\"", "\"") ?? match[3] ?? match[4] ?? "",
17
- rest: text.slice(match[0].length)
18
- };
19
- }
20
- /** A table's name, with or without a schema in front (`main.t`). */
21
- function readTable(text) {
22
- const first = readName(text);
23
- if (!first) return null;
24
- const dot = /^\s*\./.exec(first.rest);
25
- return dot ? readName(first.rest.slice(dot[0].length)) : first;
26
- }
27
- /** What `statement` drops, creates or renames; null for anything else. */
28
- function effectOf(statement) {
29
- const text = statement.trimStart();
30
- const drop = /^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?/i.exec(text);
31
- if (drop) {
32
- const table = readTable(text.slice(drop[0].length));
33
- return table ? {
34
- kind: "drop",
35
- table: table.name
36
- } : null;
37
- }
38
- const create = /^CREATE\s+(?:TEMP(?:ORARY)?\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?/i.exec(text);
39
- if (create) {
40
- const table = readTable(text.slice(create[0].length));
41
- return table ? {
42
- kind: "create",
43
- table: table.name
44
- } : null;
45
- }
46
- const alter = /^ALTER\s+TABLE\s+/i.exec(text);
47
- if (alter) {
48
- const from = readTable(text.slice(alter[0].length));
49
- if (!from) return null;
50
- const rename = /^\s+RENAME\s+TO\s+/i.exec(from.rest);
51
- const to = rename && readName(from.rest.slice(rename[0].length));
52
- return to ? {
53
- kind: "rename",
54
- from: from.name,
55
- to: to.name
56
- } : null;
57
- }
58
- return null;
59
- }
60
- const HOLD = "__durable_db_hold_";
61
- const quote = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
62
- const lower = (name) => name.toLowerCase();
63
- const rows = (sql, query, ...bindings) => sql.exec(query, ...bindings).toArray();
64
- /** What a pragma that holds a switch answers. */
65
- function isOn(sql, pragma) {
66
- const [row] = rows(sql, `PRAGMA ${pragma}`);
67
- return Number(Object.values(row ?? {})[0] ?? 0) !== 0;
68
- }
69
- /**
70
- * The tables whose rows a DROP of `dropped` would act on: those that reference
71
- * it, and those that reference them. A table comes before the tables it
72
- * references.
73
- */
74
- function dependentsOf(sql, dropped) {
75
- const tables = rows(sql, "SELECT name FROM sqlite_master WHERE type = 'table'").map((row) => String(row.name)).filter((name) => !/^(sqlite_|_cf_)/i.test(name));
76
- if (!tables.some((table) => lower(table) === lower(dropped))) return [];
77
- const references = new Map(tables.map((table) => [table, new Set(rows(sql, `PRAGMA foreign_key_list(${quote(table)})`).map((key) => lower(String(key.table))))]));
78
- const found = [];
79
- const reached = /* @__PURE__ */ new Set([lower(dropped)]);
80
- const visit = (parent) => {
81
- for (const table of tables) {
82
- if (reached.has(lower(table)) || !references.get(table)?.has(lower(parent))) continue;
83
- reached.add(lower(table));
84
- if (rows(sql, `SELECT 1 FROM ${quote(table)} LIMIT 1`).length === 0) continue;
85
- visit(table);
86
- found.push(table);
87
- }
88
- };
89
- visit(dropped);
90
- return found;
91
- }
92
- /**
93
- * Runs `work` with no foreign key checked row by row: tables that reference
94
- * each other are emptied and filled one at a time. Nothing is checked at the
95
- * end either — whoever fills tables checks them.
96
- */
97
- function unchecked(sql, work) {
98
- if (isOn(sql, "defer_foreign_keys")) return work();
99
- sql.exec("PRAGMA defer_foreign_keys = ON");
100
- try {
101
- return work();
102
- } finally {
103
- sql.exec("PRAGMA defer_foreign_keys = OFF");
104
- }
105
- }
106
- /** Moves the rows of `tables` (a table before the tables it references) aside. */
107
- function hold(sql, tables) {
108
- return unchecked(sql, () => {
109
- const held = tables.map((table) => {
110
- const columns = rows(sql, `PRAGMA table_info(${quote(table)})`).map((column) => quote(String(column.name))).join(", ");
111
- sql.exec(`CREATE TABLE ${quote(HOLD + table)} AS SELECT ${columns} FROM ${quote(table)}`);
112
- const triggers = rows(sql, "SELECT name, sql FROM sqlite_master WHERE type = 'trigger' AND lower(tbl_name) = lower(?)", table);
113
- for (const trigger of triggers) sql.exec(`DROP TRIGGER ${quote(String(trigger.name))}`);
114
- return {
115
- table,
116
- columns,
117
- triggers: triggers.map((trigger) => String(trigger.sql))
118
- };
119
- });
120
- for (const { table } of held) sql.exec(`DELETE FROM ${quote(table)}`);
121
- return held;
122
- });
123
- }
124
- /** Puts the rows back once `renamed.from` has taken the dropped table's place, and checks what they reference. */
125
- function restore(sql, held, renamed) {
126
- const targetOf = (table) => lower(table) === lower(renamed.from) ? renamed.to : table;
127
- const filled = [...held].reverse();
128
- unchecked(sql, () => {
129
- for (const { table, columns } of filled) {
130
- sql.exec(`INSERT INTO ${quote(targetOf(table))} (${columns}) SELECT ${columns} FROM ${quote(HOLD + table)}`);
131
- sql.exec(`DROP TABLE ${quote(HOLD + table)}`);
132
- }
133
- for (const { triggers } of filled) for (const trigger of triggers) sql.exec(trigger);
134
- });
135
- for (const { table } of filled) {
136
- const broken = rows(sql, `PRAGMA foreign_key_check(${quote(targetOf(table))})`);
137
- if (broken.length === 0) continue;
138
- const parents = [...new Set(broken.map((row) => `"${String(row.parent)}"`))].join(", ");
139
- throw new Error(`[database] ${broken.length} row(s) of "${targetOf(table)}" reference rows of ${parents} that the rebuild of "${renamed.to}" leaves out: the migration has to delete those rows, or point them elsewhere, before it.`);
140
- }
141
- }
142
- /**
143
- * The guard for a chunk's statements (the ones that will run, in order), or
144
- * null when none of them drops a table.
145
- */
146
- function guardReferencingRows(sql, statements) {
147
- const effects = statements.map(effectOf);
148
- if (!effects.some((effect) => effect?.kind === "drop")) return null;
149
- const same = (a, b) => lower(a) === lower(b);
150
- /** The rows held aside, by the place of the RENAME that puts the table they reference back. */
151
- const aside = /* @__PURE__ */ new Map();
152
- const putOff = [];
153
- let enforced;
154
- /** The first statement after `at` that makes a table called `table`. */
155
- const madeAgain = (table, at) => {
156
- for (let next = at + 1; next < effects.length; next++) {
157
- const effect = effects[next];
158
- if (effect?.kind === "create" && same(effect.table, table)) return {
159
- at: next,
160
- renamed: false
161
- };
162
- if (effect?.kind === "rename" && same(effect.to, table)) return {
163
- at: next,
164
- renamed: true
165
- };
166
- }
167
- return null;
168
- };
169
- return {
170
- run(at, execute) {
171
- const effect = effects[at];
172
- if (effect?.kind === "rename") {
173
- execute();
174
- const rows = aside.get(at);
175
- if (!rows) return;
176
- aside.delete(at);
177
- restore(sql, rows.held, effect);
178
- return;
179
- }
180
- if (effect?.kind !== "drop" || !(enforced ??= isOn(sql, "foreign_keys"))) return execute();
181
- for (const { dropped, held } of aside.values()) {
182
- if (!held.some(({ table }) => same(table, effect.table))) continue;
183
- throw new Error(`[database] The migration drops "${effect.table}" in the middle of the rebuild of "${dropped}", which it references: one rebuild has to end (DROP TABLE, then RENAME TO) before the next begins.`);
184
- }
185
- const again = madeAgain(effect.table, at);
186
- if (again && !again.renamed) return execute();
187
- const dependents = dependentsOf(sql, effect.table);
188
- if (dependents.length === 0) return execute();
189
- if (!again) return void putOff.push(execute);
190
- aside.set(again.at, {
191
- dropped: effect.table,
192
- held: hold(sql, dependents)
193
- });
194
- execute();
195
- },
196
- finish() {
197
- for (const drop of putOff) drop();
198
- }
199
- };
200
- }
201
- //#endregion
202
10
  //#region src/db/SqliteDurableObject.ts
11
+ init_debug();
203
12
  /**
204
13
  * Maximum number of PITR restore attempts before giving up
205
14
  */
@@ -125,6 +125,12 @@ type Value<Rel, Item> = Rel extends {
125
125
  } ? Item : Rel extends {
126
126
  kind: 'one';
127
127
  } ? Item | null : Item[];
128
+ /** What the options say of the rows: a `where` on a `one` makes the row it leads to one that may not be there. */
129
+ type Conditioned<Rel, V, O> = Rel extends {
130
+ kind: 'one';
131
+ } ? (O extends {
132
+ where: (...args: never[]) => unknown;
133
+ } ? V | null : V) : V;
128
134
  /**
129
135
  * Which rows of a `many` to read: a condition on the related table `TK`,
130
136
  * written with Kysely's expression builder — `(eb) => eb('quantity', '>', 0)`.
@@ -140,11 +146,14 @@ interface RelatedOptions<C extends string, W, K extends string = C, E = Expressi
140
146
  /** A `many` only: at most this many rows per parent. */
141
147
  limit?: number;
142
148
  /**
143
- * A `many` only: which of its rows — a condition on the related table, by
144
- * Kysely's expression builder: `(eb) => eb('quantity', '>', 0)`. Its columns
145
- * are named alone or after the table (`'invoiceLines.quantity'`); another
146
- * table is read in a subquery (`eb.exists(eb.selectFrom(…))`), which names
147
- * the related row's columns after the table. It applies before `limit`.
149
+ * Which of its rows — a condition on the related table, by Kysely's
150
+ * expression builder: `(eb) => eb('quantity', '>', 0)`. Its columns are
151
+ * named alone or after the table (`'invoiceLines.quantity'`); another table
152
+ * is read in a subquery (`eb.exists(eb.selectFrom(…))`), which names the
153
+ * related row's columns after the table. On a `many` it applies before
154
+ * `limit`. On a `one` it says whether the row the foreign key leads to is
155
+ * read at all: where it does not hold, the relation answers null — also
156
+ * for a foreign key that is never null, and the type says so.
148
157
  */
149
158
  where?: (eb: E) => Expression<SqlBool>;
150
159
  }
@@ -154,7 +163,7 @@ interface RelatedOptions<C extends string, W, K extends string = C, E = Expressi
154
163
  */
155
164
  interface Related<S extends AnySchema> {
156
165
  <TK extends keyof Relations<S> & string, R extends keyof Relations<S>[TK] & string, C extends keyof Row<S, TargetOf<Relations<S>[TK][R]>> & string>(table: TK, relation: R, columns: readonly C[]): RelatedExpression<TK, R, Value<Relations<S>[TK][R], Simplify<Pick<Row<S, TargetOf<Relations<S>[TK][R]>>, C>>>>;
157
- <TK extends keyof Relations<S> & string, R extends keyof Relations<S>[TK] & string, C extends keyof Row<S, TargetOf<Relations<S>[TK][R]>> & string, W extends readonly RelatedExpression<TargetOf<Relations<S>[TK][R]> & string, string, unknown>[] = []>(table: TK, relation: R, options: RelatedOptions<C, W, keyof Row<S, TargetOf<Relations<S>[TK][R]>> & string, ExpressionBuilder<DrizzleToKysely<S>, TargetOf<Relations<S>[TK][R]> & keyof S>>): RelatedExpression<TK, R, Value<Relations<S>[TK][R], Simplify<Pick<Row<S, TargetOf<Relations<S>[TK][R]>>, C> & Nested<W>>>>;
166
+ <TK extends keyof Relations<S> & string, R extends keyof Relations<S>[TK] & string, C extends keyof Row<S, TargetOf<Relations<S>[TK][R]>> & string, W extends readonly RelatedExpression<TargetOf<Relations<S>[TK][R]> & string, string, unknown>[] = [], const O extends RelatedOptions<C, W, keyof Row<S, TargetOf<Relations<S>[TK][R]>> & string, ExpressionBuilder<DrizzleToKysely<S>, TargetOf<Relations<S>[TK][R]> & keyof S>> = RelatedOptions<C, W, keyof Row<S, TargetOf<Relations<S>[TK][R]>> & string, ExpressionBuilder<DrizzleToKysely<S>, TargetOf<Relations<S>[TK][R]> & keyof S>>>(table: TK, relation: R, options: O & RelatedOptions<C, W, keyof Row<S, TargetOf<Relations<S>[TK][R]>> & string, ExpressionBuilder<DrizzleToKysely<S>, TargetOf<Relations<S>[TK][R]> & keyof S>>): RelatedExpression<TK, R, Conditioned<Relations<S>[TK][R], Value<Relations<S>[TK][R], Simplify<Pick<Row<S, TargetOf<Relations<S>[TK][R]>>, C> & Nested<W>>>, O>>;
158
167
  }
159
168
  /**
160
169
  * `related` for a schema whose tables are known only when the code runs (a
@@ -871,7 +871,7 @@ function render(spec, outer, depth) {
871
871
  const object = sql`json_object(${sql.join(pairs)})`;
872
872
  const target = sql.table(relation.target);
873
873
  const matches = (alias) => sql`${sql.ref(`${alias}.${relation.foreign}`)} = ${sql.ref(`${outer}.${relation.local}`)}`;
874
- if (relation.kind === "one") return sql`(select ${object} from ${target} as ${sql.ref(row)} where ${matches(row)} limit 1)`;
874
+ if (relation.kind === "one") return sql`(select ${object} from ${target} as ${sql.ref(row)} where ${matches(row)}${filter(spec, row)} limit 1)`;
875
875
  if (spec.orderBy.length === 0 && spec.limit === void 0) return sql`(select json_group_array(${object}) from ${target} as ${sql.ref(row)} where ${matches(row)}${filter(spec, row)})`;
876
876
  const inner = `_s${depth}`;
877
877
  const order = spec.orderBy.length === 0 ? sql`` : sql` order by ${sql.join(spec.orderBy.map(([column, direction]) => sql`${sql.ref(`${inner}.${column}`)} ${sql.raw(direction)}`))}`;
@@ -954,7 +954,7 @@ function specOf(schema, table, name, arg) {
954
954
  }
955
955
  const { limit } = options;
956
956
  if (limit !== void 0 && (!Number.isSafeInteger(limit) || limit < 0)) throw new TypeError(`${where}: limit is a whole number, 0 or more.`);
957
- if (relation.kind === "one" && (orderBy.length > 0 || limit !== void 0 || options.where !== void 0)) throw new TypeError(`${where} leads to one row: orderBy, limit and where are for a relation that leads to many.`);
957
+ if (relation.kind === "one" && (orderBy.length > 0 || limit !== void 0)) throw new TypeError(`${where} leads to one row: orderBy and limit are for a relation that leads to many.`);
958
958
  let condition;
959
959
  if (options.where !== void 0) {
960
960
  const example = `where: (eb) => eb('<column>', '=', value)`;
@@ -1,4 +1,4 @@
1
- import "./defineDatabase-BE7YRtLh.js";
1
+ import "./defineDatabase-DlgYfwhP.js";
2
2
  import { i as OutboxSink, t as Outbox } from "./outbox-D3Q9n7Rt.js";
3
3
  import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
4
4
  import { CamelCasePlugin, CamelCasePlugin as CamelCasePlugin$1, CompiledQuery, Kysely, Kysely as Kysely$1, KyselyPlugin, KyselyPlugin as KyselyPlugin$1, PluginTransformQueryArgs, PluginTransformResultArgs, QueryResult, QueryResult as QueryResult$1, RootOperationNode, UnknownRow } from "kysely";
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { i as Type, l as type } from "./index-bUUlOWfP.js";
2
- import { C as RelationType, E as relationsOf, S as RelationMap, T as relationOf, _ as RelatedSpec, b as AnySchema, c as DatabaseDefinition, d as InferArgs, g as RelatedOptions, h as RelatedExpression, i as ActionContext, m as Related, n as Action, p as AnyRelated, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as RelatedWhere, w as Relations, x as Relation, y as createRelated } from "./defineDatabase-BE7YRtLh.js";
2
+ import { C as RelationType, E as relationsOf, S as RelationMap, T as relationOf, _ as RelatedSpec, b as AnySchema, c as DatabaseDefinition, d as InferArgs, g as RelatedOptions, h as RelatedExpression, i as ActionContext, m as Related, n as Action, p as AnyRelated, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as RelatedWhere, w as Relations, x as Relation, y as createRelated } from "./defineDatabase-DlgYfwhP.js";
3
3
  import { a as OutboxSinkContext, i as OutboxSink, n as OutboxEnvelope, o as OutboxSinkModule, r as OutboxMessage, t as Outbox } from "./outbox-D3Q9n7Rt.js";
4
4
  import { getTenantId, hasTenantId, setTenantIdResolver } from "./context/index.js";
5
5
  import { AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as createRelated, h as relationsOf, i as RelatedExpression, m as relationOf, n as defineDatabase } from "./defineDatabase-Cb5sMNg0.js";
1
+ import { a as createRelated, h as relationsOf, i as RelatedExpression, m as relationOf, n as defineDatabase } from "./defineDatabase-DypFFfjn.js";
2
2
  import { r as type } from "./type-CUgZsZp3.js";
3
3
  import "./actionArgs-DP2tQrlf.js";
4
4
  import { blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";
@@ -1,4 +1,4 @@
1
- import { l as SchemaPlugin, o as createRelatedPlugins, s as DateSerializePlugin, u as createDrizzlePlugins } from "./defineDatabase-Cb5sMNg0.js";
1
+ import { l as SchemaPlugin, o as createRelatedPlugins, s as DateSerializePlugin, u as createDrizzlePlugins } from "./defineDatabase-DypFFfjn.js";
2
2
  import { CamelCasePlugin, Kysely, SqliteDialect, SqliteQueryCompiler } from "kysely";
3
3
  //#region src/db/outbox.ts
4
4
  /** A sink module's default export as a sink: a deliver function, or an object with one. */
@@ -1,4 +1,4 @@
1
- import { n as Snapshot } from "../snapshot-B9Ae2TrS.js";
1
+ import { n as Snapshot } from "../snapshot-D3_SNABU.js";
2
2
  //#region src/migrations/generator.d.ts
3
3
  /**
4
4
  * Result of migration generation
@@ -1,11 +1,13 @@
1
1
  import { i as init_debug, n as debugMigrations } from "../debug-Cz8KzMft.js";
2
- import { a as generateSnapshotId, i as generateSnapshotFromSchema, n as createEmptySnapshot, r as generateMigrationStatements, s as snapshotsEqual } from "../snapshot-D_z95s6E.js";
2
+ import { f as init_state, n as SCHEMA_TEMP_PREFIX } from "../state-UT6GH0JD.js";
3
+ import { a as generateSnapshotId, i as generateSnapshotFromSchema, n as createEmptySnapshot, r as generateMigrationStatements, s as snapshotsEqual } from "../snapshot-CY4FLqAo.js";
3
4
  import * as fs from "node:fs";
4
5
  import * as path$1 from "node:path";
5
6
  import * as os from "node:os";
6
7
  import { pathToFileURL } from "node:url";
7
8
  //#region src/migrations/generator.ts
8
9
  init_debug();
10
+ init_state();
9
11
  /**
10
12
  * Snapshot file name
11
13
  */
@@ -175,7 +177,7 @@ async function buildAndLoadSchema(schemaPath, tableNames) {
175
177
  if (result.outputFiles?.length !== 1) throw new Error(`Unexpected esbuild output for ${schemaPath}`);
176
178
  const tempDir = resolveTempDir(schemaPath);
177
179
  fs.mkdirSync(tempDir, { recursive: true });
178
- const tempFile = path$1.join(tempDir, `_schema_temp_${Date.now()}.mjs`);
180
+ const tempFile = path$1.join(tempDir, `${SCHEMA_TEMP_PREFIX}${Date.now()}.mjs`);
179
181
  try {
180
182
  fs.writeFileSync(tempFile, result.outputFiles[0].text);
181
183
  const module = await import(pathToFileURL(tempFile).href);
@@ -1,2 +1,2 @@
1
- import { C as renamesFromStatements, S as parseRenameSpec, _ as applyRenames, a as generateMigrationStatements, b as findAmbiguities, c as hashSnapshot, d as MigrationRiskKind, f as NOT_NULL_WITHOUT_DEFAULT_HINT, g as SchemaRenameRequiredError, h as SchemaAmbiguity, i as createEmptySnapshot, l as snapshotsEqual, m as RenameAnswer, n as Snapshot, o as generateSnapshotFromSchema, p as analyzeMigrationRisks, r as canPrompt, s as generateSnapshotId, t as MigrationResolution, u as MigrationRisk, v as describeAmbiguity, w as unusedRenames, x as formatRename, y as exampleRenames } from "../snapshot-B9Ae2TrS.js";
2
- export { MigrationResolution, type MigrationRisk, type MigrationRiskKind, NOT_NULL_WITHOUT_DEFAULT_HINT, type RenameAnswer, type SchemaAmbiguity, SchemaRenameRequiredError, Snapshot, analyzeMigrationRisks, applyRenames, canPrompt, createEmptySnapshot, describeAmbiguity, exampleRenames, findAmbiguities, formatRename, generateMigrationStatements, generateSnapshotFromSchema, generateSnapshotId, hashSnapshot, parseRenameSpec, renamesFromStatements, snapshotsEqual, unusedRenames };
1
+ import { C as parseRenameSpec, S as obviousRenames, T as unusedRenames, _ as applyRenames, a as generateMigrationStatements, b as findAmbiguities, c as hashSnapshot, d as MigrationRiskKind, f as NOT_NULL_WITHOUT_DEFAULT_HINT, g as SchemaRenameRequiredError, h as SchemaAmbiguity, i as createEmptySnapshot, l as snapshotsEqual, m as RenameAnswer, n as Snapshot, o as generateSnapshotFromSchema, p as analyzeMigrationRisks, r as canPrompt, s as generateSnapshotId, t as MigrationResolution, u as MigrationRisk, v as describeAmbiguity, w as renamesFromStatements, x as formatRename, y as exampleRenames } from "../snapshot-D3_SNABU.js";
2
+ export { MigrationResolution, type MigrationRisk, type MigrationRiskKind, NOT_NULL_WITHOUT_DEFAULT_HINT, type RenameAnswer, type SchemaAmbiguity, SchemaRenameRequiredError, Snapshot, analyzeMigrationRisks, applyRenames, canPrompt, createEmptySnapshot, describeAmbiguity, exampleRenames, findAmbiguities, formatRename, generateMigrationStatements, generateSnapshotFromSchema, generateSnapshotId, hashSnapshot, obviousRenames, parseRenameSpec, renamesFromStatements, snapshotsEqual, unusedRenames };
@@ -1 +1 @@
1
- export { c as NOT_NULL_WITHOUT_DEFAULT_HINT, u as SchemaRenameRequiredError, l as analyzeMigrationRisks, d as applyRenames, t as canPrompt, n as createEmptySnapshot, f as describeAmbiguity, p as exampleRenames, m as findAmbiguities, h as formatRename, r as generateMigrationStatements, i as generateSnapshotFromSchema, a as generateSnapshotId, o as hashSnapshot, g as parseRenameSpec, _ as renamesFromStatements, s as snapshotsEqual, v as unusedRenames } from "../snapshot-D_z95s6E.js";
1
+ export { c as NOT_NULL_WITHOUT_DEFAULT_HINT, u as SchemaRenameRequiredError, l as analyzeMigrationRisks, d as applyRenames, t as canPrompt, n as createEmptySnapshot, f as describeAmbiguity, p as exampleRenames, m as findAmbiguities, h as formatRename, r as generateMigrationStatements, i as generateSnapshotFromSchema, a as generateSnapshotId, o as hashSnapshot, g as obviousRenames, _ as parseRenameSpec, v as renamesFromStatements, s as snapshotsEqual, y as unusedRenames } from "../snapshot-CY4FLqAo.js";
@@ -0,0 +1,193 @@
1
+ //#region src/db/referencingRows.ts
2
+ const NAME = /^\s*(?:`((?:[^`]|``)*)`|"((?:[^"]|"")*)"|\[([^\]]*)\]|([A-Za-z_][\w$]*))/;
3
+ function readName(text) {
4
+ const match = NAME.exec(text);
5
+ if (!match) return null;
6
+ return {
7
+ name: match[1]?.replaceAll("``", "`") ?? match[2]?.replaceAll("\"\"", "\"") ?? match[3] ?? match[4] ?? "",
8
+ rest: text.slice(match[0].length)
9
+ };
10
+ }
11
+ /** A table's name, with or without a schema in front (`main.t`). */
12
+ function readTable(text) {
13
+ const first = readName(text);
14
+ if (!first) return null;
15
+ const dot = /^\s*\./.exec(first.rest);
16
+ return dot ? readName(first.rest.slice(dot[0].length)) : first;
17
+ }
18
+ /** What `statement` drops, creates or renames; null for anything else. */
19
+ function effectOf(statement) {
20
+ const text = statement.trimStart();
21
+ const drop = /^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?/i.exec(text);
22
+ if (drop) {
23
+ const table = readTable(text.slice(drop[0].length));
24
+ return table ? {
25
+ kind: "drop",
26
+ table: table.name
27
+ } : null;
28
+ }
29
+ const create = /^CREATE\s+(?:TEMP(?:ORARY)?\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?/i.exec(text);
30
+ if (create) {
31
+ const table = readTable(text.slice(create[0].length));
32
+ return table ? {
33
+ kind: "create",
34
+ table: table.name
35
+ } : null;
36
+ }
37
+ const alter = /^ALTER\s+TABLE\s+/i.exec(text);
38
+ if (alter) {
39
+ const from = readTable(text.slice(alter[0].length));
40
+ if (!from) return null;
41
+ const rename = /^\s+RENAME\s+TO\s+/i.exec(from.rest);
42
+ const to = rename && readName(from.rest.slice(rename[0].length));
43
+ return to ? {
44
+ kind: "rename",
45
+ from: from.name,
46
+ to: to.name
47
+ } : null;
48
+ }
49
+ return null;
50
+ }
51
+ const HOLD = "__durable_db_hold_";
52
+ const quote = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
53
+ const lower = (name) => name.toLowerCase();
54
+ const rows = (sql, query, ...bindings) => sql.exec(query, ...bindings).toArray();
55
+ /** What a pragma that holds a switch answers. */
56
+ function isOn(sql, pragma) {
57
+ const [row] = rows(sql, `PRAGMA ${pragma}`);
58
+ return Number(Object.values(row ?? {})[0] ?? 0) !== 0;
59
+ }
60
+ /**
61
+ * The tables whose rows a DROP of `dropped` would act on: those that reference
62
+ * it, and those that reference them. A table comes before the tables it
63
+ * references.
64
+ */
65
+ function dependentsOf(sql, dropped) {
66
+ const tables = rows(sql, "SELECT name FROM sqlite_master WHERE type = 'table'").map((row) => String(row.name)).filter((name) => !/^(sqlite_|_cf_)/i.test(name));
67
+ if (!tables.some((table) => lower(table) === lower(dropped))) return [];
68
+ const references = new Map(tables.map((table) => [table, new Set(rows(sql, `PRAGMA foreign_key_list(${quote(table)})`).map((key) => lower(String(key.table))))]));
69
+ const found = [];
70
+ const reached = /* @__PURE__ */ new Set([lower(dropped)]);
71
+ const visit = (parent) => {
72
+ for (const table of tables) {
73
+ if (reached.has(lower(table)) || !references.get(table)?.has(lower(parent))) continue;
74
+ reached.add(lower(table));
75
+ if (rows(sql, `SELECT 1 FROM ${quote(table)} LIMIT 1`).length === 0) continue;
76
+ visit(table);
77
+ found.push(table);
78
+ }
79
+ };
80
+ visit(dropped);
81
+ return found;
82
+ }
83
+ /**
84
+ * Runs `work` with no foreign key checked row by row: tables that reference
85
+ * each other are emptied and filled one at a time. Nothing is checked at the
86
+ * end either — whoever fills tables checks them.
87
+ */
88
+ function unchecked(sql, work) {
89
+ if (isOn(sql, "defer_foreign_keys")) return work();
90
+ sql.exec("PRAGMA defer_foreign_keys = ON");
91
+ try {
92
+ return work();
93
+ } finally {
94
+ sql.exec("PRAGMA defer_foreign_keys = OFF");
95
+ }
96
+ }
97
+ /** Moves the rows of `tables` (a table before the tables it references) aside. */
98
+ function hold(sql, tables) {
99
+ return unchecked(sql, () => {
100
+ const held = tables.map((table) => {
101
+ const columns = rows(sql, `PRAGMA table_info(${quote(table)})`).map((column) => quote(String(column.name))).join(", ");
102
+ sql.exec(`CREATE TABLE ${quote(HOLD + table)} AS SELECT ${columns} FROM ${quote(table)}`);
103
+ const triggers = rows(sql, "SELECT name, sql FROM sqlite_master WHERE type = 'trigger' AND lower(tbl_name) = lower(?)", table);
104
+ for (const trigger of triggers) sql.exec(`DROP TRIGGER ${quote(String(trigger.name))}`);
105
+ return {
106
+ table,
107
+ columns,
108
+ triggers: triggers.map((trigger) => String(trigger.sql))
109
+ };
110
+ });
111
+ for (const { table } of held) sql.exec(`DELETE FROM ${quote(table)}`);
112
+ return held;
113
+ });
114
+ }
115
+ /** Puts the rows back once `renamed.from` has taken the dropped table's place, and checks what they reference. */
116
+ function restore(sql, held, renamed) {
117
+ const targetOf = (table) => lower(table) === lower(renamed.from) ? renamed.to : table;
118
+ const filled = [...held].reverse();
119
+ unchecked(sql, () => {
120
+ for (const { table, columns } of filled) {
121
+ sql.exec(`INSERT INTO ${quote(targetOf(table))} (${columns}) SELECT ${columns} FROM ${quote(HOLD + table)}`);
122
+ sql.exec(`DROP TABLE ${quote(HOLD + table)}`);
123
+ }
124
+ for (const { triggers } of filled) for (const trigger of triggers) sql.exec(trigger);
125
+ });
126
+ for (const { table } of filled) {
127
+ const broken = rows(sql, `PRAGMA foreign_key_check(${quote(targetOf(table))})`);
128
+ if (broken.length === 0) continue;
129
+ const parents = [...new Set(broken.map((row) => `"${String(row.parent)}"`))].join(", ");
130
+ throw new Error(`[database] ${broken.length} row(s) of "${targetOf(table)}" reference rows of ${parents} that the rebuild of "${renamed.to}" leaves out: the migration has to delete those rows, or point them elsewhere, before it.`);
131
+ }
132
+ }
133
+ /**
134
+ * The guard for a chunk's statements (the ones that will run, in order), or
135
+ * null when none of them drops a table.
136
+ */
137
+ function guardReferencingRows(sql, statements) {
138
+ const effects = statements.map(effectOf);
139
+ if (!effects.some((effect) => effect?.kind === "drop")) return null;
140
+ const same = (a, b) => lower(a) === lower(b);
141
+ /** The rows held aside, by the place of the RENAME that puts the table they reference back. */
142
+ const aside = /* @__PURE__ */ new Map();
143
+ const putOff = [];
144
+ let enforced;
145
+ /** The first statement after `at` that makes a table called `table`. */
146
+ const madeAgain = (table, at) => {
147
+ for (let next = at + 1; next < effects.length; next++) {
148
+ const effect = effects[next];
149
+ if (effect?.kind === "create" && same(effect.table, table)) return {
150
+ at: next,
151
+ renamed: false
152
+ };
153
+ if (effect?.kind === "rename" && same(effect.to, table)) return {
154
+ at: next,
155
+ renamed: true
156
+ };
157
+ }
158
+ return null;
159
+ };
160
+ return {
161
+ run(at, execute) {
162
+ const effect = effects[at];
163
+ if (effect?.kind === "rename") {
164
+ execute();
165
+ const rows = aside.get(at);
166
+ if (!rows) return;
167
+ aside.delete(at);
168
+ restore(sql, rows.held, effect);
169
+ return;
170
+ }
171
+ if (effect?.kind !== "drop" || !(enforced ??= isOn(sql, "foreign_keys"))) return execute();
172
+ for (const { dropped, held } of aside.values()) {
173
+ if (!held.some(({ table }) => same(table, effect.table))) continue;
174
+ throw new Error(`[database] The migration drops "${effect.table}" in the middle of the rebuild of "${dropped}", which it references: one rebuild has to end (DROP TABLE, then RENAME TO) before the next begins.`);
175
+ }
176
+ const again = madeAgain(effect.table, at);
177
+ if (again && !again.renamed) return execute();
178
+ const dependents = dependentsOf(sql, effect.table);
179
+ if (dependents.length === 0) return execute();
180
+ if (!again) return void putOff.push(execute);
181
+ aside.set(again.at, {
182
+ dropped: effect.table,
183
+ held: hold(sql, dependents)
184
+ });
185
+ execute();
186
+ },
187
+ finish() {
188
+ for (const drop of putOff) drop();
189
+ }
190
+ };
191
+ }
192
+ //#endregion
193
+ export { guardReferencingRows as t };
@@ -101,14 +101,25 @@ interface ActionNamespace {
101
101
  */
102
102
  export declare function cachedArgsSchema<T>(key: string, make: () => T): T;
103
103
  /**
104
- * Call an action on the Durable Object `instanceKey` of `namespace`. Calls to
105
- * the same object started before the code waits on I/O — `Promise.all([a(),
106
- * b()])` however deep in middleware, sibling server components awaiting at
107
- * once — travel in ONE RPC
108
- * (`rpcBatch`) and run there one after another, in the order they were made,
109
- * each result or error to its own caller; a lone call is a plain `rpc`, as
110
- * before. Results are plain values: the RPC's top-level `Symbol.dispose` is
111
- * dropped (React Server Components refuse symbol-keyed props).
104
+ * Runs `fn` as one invocation: the action calls it starts on the same Durable
105
+ * Object before it waits on I/O travel in ONE RPC. Wrap what the platform
106
+ * invokes — a worker's `fetch`, `queue` and `scheduled` handlers:
107
+ *
108
+ * export default { fetch: (request, env, ctx) => batchScope(() => app.fetch(request, env, ctx)) }
109
+ *
110
+ * Outside a scope every call is its own RPC: batching is only safe among the
111
+ * calls of one invocation, and nothing else tells them apart.
112
+ */
113
+ export declare function batchScope<T>(fn: () => T): T;
114
+ /**
115
+ * Call an action on the Durable Object `instanceKey` of `namespace`. Inside a
116
+ * `batchScope()`, calls to the same object started before the code waits on
117
+ * I/O — `Promise.all([a(), b()])` however deep in middleware, sibling server
118
+ * components awaiting at once — travel in ONE RPC (`rpcBatch`) and run there
119
+ * one after another, in the order they were made, each result or error to its
120
+ * own caller; a lone call, and every call outside a scope, is a plain `rpc`.
121
+ * Results are plain values: the RPC's top-level `Symbol.dispose` is dropped
122
+ * (React Server Components refuse symbol-keyed props).
112
123
  */
113
124
  export declare function batchedRpc(namespace: ActionNamespace, instanceKey: string, action: string, args: unknown): Promise<unknown>;
114
125
  //#endregion