durable-db 0.8.0 → 0.9.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/README.md CHANGED
@@ -23,6 +23,7 @@ Define your schema with [Drizzle](https://orm.drizzle.team/), query with [Kysely
23
23
  - [Production Migrations](#production-migrations)
24
24
  - [Breakpoints](#breakpoints)
25
25
  - [Adding a required column](#adding-a-required-column)
26
+ - [Rebuilding a table that others reference](#rebuilding-a-table-that-others-reference)
26
27
  - [Epoch System](#epoch-system)
27
28
  - [Typical Workflow](#typical-workflow)
28
29
  - [Vite Plugin](#vite-plugin)
@@ -31,6 +32,8 @@ Define your schema with [Drizzle](https://orm.drizzle.team/), query with [Kysely
31
32
  - [Instance Strategies](#instance-strategies)
32
33
  - [Action-to-Action Calls](#action-to-action-calls)
33
34
  - [The Outbox](#the-outbox)
35
+ - [Shared Actions](#shared-actions)
36
+ - [Relations](#relations)
34
37
  - [PITR Safety](#pitr-safety)
35
38
  - [Recovery Workflows](#recovery-workflows)
36
39
  - [Architecture](#architecture)
@@ -692,6 +695,20 @@ SQLite rejects `ALTER TABLE … ADD … NOT NULL` without a default on a table t
692
695
 
693
696
  The same holds for renames: answering a rename question with "create" (or `--no-renames`) adds the new column — `NOT NULL` without a default fails the same way — and drops the old one with its data.
694
697
 
698
+ ### Rebuilding a table that others reference
699
+
700
+ SQLite cannot alter most of a table in place, so many schema changes become a rebuild: `CREATE TABLE __new_t`, copy the rows, `DROP TABLE t`, `ALTER TABLE __new_t RENAME TO t`, with `PRAGMA foreign_keys=OFF` around it. In a Durable Object that pragma does nothing — foreign keys are always enforced — so the `DROP` would run the `ON DELETE` of every table that references `t`: `cascade` would delete those rows, `set null` empty their column.
701
+
702
+ The runtime stands in for the pragma. While a chunk rebuilds a table, the rows of the tables that reference it (and of those that reference them) are moved aside before the `DROP` and put back after the `RENAME`, with none of their triggers run, and then checked: a rebuild that leaves out rows others still reference fails the migration, and nothing of it is kept. A referenced table that is dropped for good is dropped at the end of its chunk, once the tables that referenced it were rebuilt without the reference.
703
+
704
+ What to know when writing a migration by hand:
705
+
706
+ - keep a rebuild in one chunk: with a `--> breakpoint` between its `DROP TABLE` and its `RENAME TO`, the rows that reference the table are not kept;
707
+ - drop the old table, then rename the new one into its place — renaming the old one away first (`ALTER TABLE t RENAME TO old_t`) is not recognised as a rebuild;
708
+ - finish one rebuild before the next begins: `DROP a`, `DROP b`, then the renames, fails with a message that says so;
709
+ - a table that is dropped and created again (`DROP TABLE t`, `CREATE TABLE t`) loses its rows on purpose, and the rows that cascade from them;
710
+ - the rows that are moved aside are copied twice, so rebuilding a table costs in proportion to the rows that reference it.
711
+
695
712
  ### Epoch System
696
713
 
697
714
  In development, each database instance key gets an epoch suffix to enable clean resets:
@@ -1091,6 +1108,113 @@ export const createUser = action({
1091
1108
 
1092
1109
  ---
1093
1110
 
1111
+ ## Shared Actions
1112
+
1113
+ For a library that works on any schema — a query executor, an exporter — an action can be registered once and run in **every** database. It is opt-in: nothing changes for an app that never calls it.
1114
+
1115
+ ```ts
1116
+ import { registerSharedAction } from 'durable-db/registry';
1117
+
1118
+ registerSharedAction('export:rows', {
1119
+ validator: (args) => args as { table: string },
1120
+ handler: async (db, args, ctx) => db.selectFrom(args.table).selectAll().execute(),
1121
+ });
1122
+ ```
1123
+
1124
+ `stub.rpc('export:rows', { table: 'users' })` then runs it in whichever Durable Object is called, with that database's `db` and the action context. The module that registers it has to be loaded in the Durable Object's isolate (anything the worker's entry imports is). A database's own action of the same name wins, so give a shared action a name no export can have (`"lib:name"`).
1125
+
1126
+ `virtual:durable-db/__databases` lists what the plugin discovered — `databases: [{ name, bindingName, className, instance, schema }]`, the tables being the schema module's own objects — for a library that needs to know which database a table belongs to. It is generated only when something imports it.
1127
+
1128
+ `describeAction(action)` (from `durable-db`) answers what an action is, given the function an app exports: `{ database, name, args }`, `args` being its compiled schema — `.toJsonSchema()` for a library that maps actions to an API of its own. It reads what the build registered for the call site (in tests, where nothing is compiled, `database` and `name` are `null`), and `undefined` for anything that is not an action.
1129
+
1130
+ ```ts
1131
+ import { describeAction } from 'durable-db';
1132
+ import { createInvoice } from './databases/billing.actions';
1133
+
1134
+ describeAction(createInvoice)?.args?.toJsonSchema();
1135
+ // { type: 'object', properties: { customerId: { type: 'string' }, … }, required: [ … ] }
1136
+ ```
1137
+
1138
+ ---
1139
+
1140
+ ## Relations
1141
+
1142
+ A foreign key is a relation. Declare it once, on the column, and read along it in both directions — nothing else to write, nothing generated.
1143
+
1144
+ ```ts
1145
+ import { index, integer, table, text } from 'durable-db/schema';
1146
+
1147
+ export const customers = table('customers', {
1148
+ id: text().primaryKey(),
1149
+ name: text().notNull(),
1150
+ });
1151
+
1152
+ export const invoices = table('invoices', {
1153
+ id: text().primaryKey(),
1154
+ number: integer().notNull(),
1155
+ customerId: text().notNull().references(() => customers.id),
1156
+ });
1157
+
1158
+ export const invoiceLines = table(
1159
+ 'invoice_lines',
1160
+ {
1161
+ id: text().primaryKey(),
1162
+ invoiceId: text().notNull().references(() => invoices.id, { onDelete: 'cascade' }),
1163
+ description: text().notNull(),
1164
+ },
1165
+ (t) => [index('invoice_lines_invoice').on(t.invoiceId)],
1166
+ );
1167
+ ```
1168
+
1169
+ `defineDatabase()` hands out `related` next to `action`. It is a selection: put it in a `select()` (or a `returning()`) and the row gets the related rows under the relation's name, typed.
1170
+
1171
+ ```ts
1172
+ export const { action, related, relations } = defineDatabase({ schema });
1173
+
1174
+ export const listInvoices = action({
1175
+ args: {},
1176
+ handler: async (db) =>
1177
+ db
1178
+ .selectFrom('invoices')
1179
+ .select([
1180
+ 'invoices.number',
1181
+ related('invoices', 'customer', ['name']),
1182
+ related('invoices', 'invoiceLines', {
1183
+ columns: ['description'],
1184
+ orderBy: { id: 'asc' },
1185
+ limit: 50,
1186
+ }),
1187
+ ])
1188
+ .execute(),
1189
+ // { number: number; customer: { name: string }; invoiceLines: { description: string }[] }[]
1190
+ });
1191
+ ```
1192
+
1193
+ **Names.** The forward side (`one`) is the column's property without its `Id` (`customerId` → `customer`); it is nullable when the column is. The inverse side (`many`) is the schema key of the table that holds the foreign key (`customers` → `invoices`). A table that points at the same target twice gets `<key>As<Forward>` for each (`invoicesAsCustomer`, `invoicesAsReferee`).
1194
+
1195
+ **Nesting.** `with` reads relations of the related table, to any depth — still one SQL query:
1196
+
1197
+ ```ts
1198
+ related('customers', 'invoices', {
1199
+ columns: ['number'],
1200
+ orderBy: { number: 'desc' },
1201
+ with: [related('invoices', 'invoiceLines', ['description'])],
1202
+ });
1203
+ ```
1204
+
1205
+ Each relation is a correlated subquery that SQLite answers as JSON (`json_object`, `json_group_array`); dates and booleans inside come back as the columns say, like in any row. Index the foreign key column a `many` is read through (`invoice_lines_invoice` above): without one SQLite scans the child table once per parent row — 200 invoices over 10 000 lines took 80 ms without it and 1.4 ms with it.
1206
+
1207
+ **The registry.** `relations` (and `relationsOf(schema)` from `durable-db`) is the same information at runtime — `relations.invoices.customer` is `{ kind: 'one', name: 'customer', table: 'invoices', target: 'customers', local: 'customerId', foreign: 'id', nullable: false }` (tables as schema keys, columns as their properties) — for a library that maps a schema to an API. `Relations<typeof schema>` is its type.
1208
+
1209
+ What it does not do yet:
1210
+
1211
+ - A table that references itself (or two that reference each other) needs TypeScript's annotation on the callback — `.references((): AnySQLiteColumn => categories.id)` — and that hides the target from the types: the relation is in `relations`, but `related()` does not offer its name.
1212
+ - Composite foreign keys (`foreignKey({ columns: [a, b] })`) are not relations.
1213
+ - `related()` names the table as the query does: `selectFrom('invoices')`, not `selectFrom('invoices as i')`. It needs the default `camelCase` mapping.
1214
+ - No `where` on a relation; filter in the action.
1215
+
1216
+ ---
1217
+
1094
1218
  ## PITR Safety
1095
1219
 
1096
1220
  On Cloudflare with Point-in-Time Recovery (PITR) enabled, migrations are protected with automatic snapshots.
@@ -1,7 +1,7 @@
1
1
  import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
2
2
  import { S as parseRenameSpec, g as SchemaRenameRequiredError, h as SchemaAmbiguity, m as RenameAnswer, n as Snapshot, t as MigrationResolution, u as MigrationRisk } from "../snapshot-B9Ae2TrS.js";
3
- import { l as DatabaseInfo } from "../defineDatabase-By401iHp.js";
4
- import "../index-rlnVnzJJ.js";
3
+ import { l as DatabaseInfo } from "../defineDatabase-BvFOZVkv.js";
4
+ import "../index-DoxI1p4-.js";
5
5
  import { Command } from "commander";
6
6
  //#region src/cli/command.d.ts
7
7
  /**
@@ -1,5 +1,5 @@
1
1
  import { l as type } from "../index-bUUlOWfP.js";
2
- import { a as ActionInfo, c as DatabaseDefinition, d as InferArgs, f as ParsedDatabaseFile, i as ActionContext, l as DatabaseInfo, n as Action, o as ArgsSchema, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely } from "../defineDatabase-By401iHp.js";
2
+ import { _ as RelationMap, a as ActionInfo, b as relationOf, c as DatabaseDefinition, d as InferArgs, f as ParsedDatabaseFile, g as Relation, h as RelatedOptions, i as ActionContext, l as DatabaseInfo, m as RelatedExpression, n as Action, o as ArgsSchema, p as Related, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as RelationType, x as relationsOf, y as Relations } from "../defineDatabase-BvFOZVkv.js";
3
3
  import { a as OutboxSinkContext, c as queueOutboxSink, i as OutboxSink, l as tenantOfInstanceKey, n as OutboxEnvelope, o as OutboxSinkModule, r as OutboxMessage, s as outboxSink, t as Outbox } from "../outbox-D3Q9n7Rt.js";
4
- import { C as createKyselyFromSql, S as SqlExecutor, _ as MigrationAttemptInfo, a as QueryResult, b as SqliteDurableObject, c as DrizzleDefaultsPlugin, d as dateSerializers, f as DeleteClassMigration, g as Migration, h as removedDatabaseMessage, i as KyselyPlugin, l as SchemaPlugin, m as RemovedDatabaseError, n as CompiledQuery, o as studio, p as RemovedDatabaseDurableObject, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as createDrizzlePlugins, v as MigrationSchemaConflictError, x as CreateKyselyOptions, y as Migrations } from "../index-rlnVnzJJ.js";
5
- export { type Action, type ActionConfig, type ActionContext, type ActionInfo, type ArgsSchema, CamelCasePlugin, type CompiledQuery, type CreateKyselyOptions, type DatabaseConfig, type DatabaseDefinition, type DatabaseInfo, DateSerializePlugin, type DeleteClassMigration, DrizzleDefaultsPlugin, type DrizzleToKysely, type InferArgs, type Kysely, type KyselyPlugin, type Migration, type MigrationAttemptInfo, MigrationSchemaConflictError, type Migrations, type Outbox, type OutboxEnvelope, type OutboxMessage, type OutboxSink, type OutboxSinkContext, type OutboxSinkModule, type ParsedDatabaseFile, type QueryResult, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, type SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, outboxSink, queueOutboxSink, removedDatabaseMessage, studio, tenantOfInstanceKey, type };
4
+ import { C as createKyselyFromSql, S as SqlExecutor, _ as MigrationAttemptInfo, a as QueryResult, b as SqliteDurableObject, c as DrizzleDefaultsPlugin, d as dateSerializers, f as DeleteClassMigration, g as Migration, h as removedDatabaseMessage, i as KyselyPlugin, l as SchemaPlugin, m as RemovedDatabaseError, n as CompiledQuery, o as studio, p as RemovedDatabaseDurableObject, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as createDrizzlePlugins, v as MigrationSchemaConflictError, x as CreateKyselyOptions, y as Migrations } from "../index-DoxI1p4-.js";
5
+ export { type Action, type ActionConfig, type ActionContext, type ActionInfo, type ArgsSchema, CamelCasePlugin, type CompiledQuery, type CreateKyselyOptions, type DatabaseConfig, type DatabaseDefinition, type DatabaseInfo, DateSerializePlugin, type DeleteClassMigration, DrizzleDefaultsPlugin, type DrizzleToKysely, type InferArgs, type Kysely, type KyselyPlugin, type Migration, type MigrationAttemptInfo, MigrationSchemaConflictError, type Migrations, type Outbox, type OutboxEnvelope, type OutboxMessage, type OutboxSink, type OutboxSinkContext, type OutboxSinkModule, type ParsedDatabaseFile, type QueryResult, type Related, RelatedExpression, type RelatedOptions, type Relation, type RelationMap, type RelationType, type Relations, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, type SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, outboxSink, queueOutboxSink, relationOf, relationsOf, removedDatabaseMessage, studio, tenantOfInstanceKey, type };
package/dist/db/index.js CHANGED
@@ -1,13 +1,205 @@
1
1
  import { i as init_debug, n as debugMigrations } from "../debug-Cz8KzMft.js";
2
+ import { c as SchemaPlugin, d as relationOf, f as relationsOf, i as RelatedExpression, l as createDrizzlePlugins, n as defineDatabase, o as DateSerializePlugin, s as DrizzleDefaultsPlugin, u as dateSerializers } from "../defineDatabase-CaqKQagA.js";
2
3
  import { r as type } from "../type-CUgZsZp3.js";
3
4
  import "../actionArgs-DP2tQrlf.js";
4
- import { n as defineDatabase } from "../defineDatabase-595bNB6M.js";
5
- import { a as createDrizzlePlugins, c as OUTBOX_TABLE, d as outboxSink, f as queueOutboxSink, i as SchemaPlugin, l as createActionOutbox, n as DateSerializePlugin, o as dateSerializers, p as tenantOfInstanceKey, r as DrizzleDefaultsPlugin, s as OUTBOX_DDL, t as createKyselyFromSql, u as outboxRetryDelay } from "../kysely-DvAoap5h.js";
6
- import { DurableObject } from "cloudflare:workers";
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-D8JQ4v8n.js";
7
6
  import { CamelCasePlugin } from "kysely";
7
+ import { DurableObject } from "cloudflare:workers";
8
8
  import { studio } from "@outerbase/browsable-durable-object";
9
- //#region src/db/SqliteDurableObject.ts
9
+ //#region src/db/referencingRows.ts
10
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
+ //#region src/db/SqliteDurableObject.ts
11
203
  /**
12
204
  * Maximum number of PITR restore attempts before giving up
13
205
  */
@@ -516,6 +708,7 @@ var SqliteDurableObject = class extends DurableObject {
516
708
  let skipped = 0;
517
709
  const applyChunk = () => {
518
710
  skipped = 0;
711
+ const toRun = [];
519
712
  for (let i = 0; i < statements.length; i++) {
520
713
  const statement = statements[i];
521
714
  if (!statement.trim()) continue;
@@ -523,10 +716,24 @@ var SqliteDurableObject = class extends DurableObject {
523
716
  skipped++;
524
717
  continue;
525
718
  }
526
- currentIndex = i;
527
- currentStatement = statement;
528
- this.sql.exec(statement);
719
+ toRun.push({
720
+ index: i,
721
+ statement
722
+ });
529
723
  }
724
+ const guard = guardReferencingRows(this.sql, toRun.map(({ statement }) => statement));
725
+ toRun.forEach(({ index, statement }, at) => {
726
+ const execute = () => {
727
+ currentIndex = index;
728
+ currentStatement = statement;
729
+ this.sql.exec(statement);
730
+ };
731
+ if (!guard) return execute();
732
+ currentIndex = index;
733
+ currentStatement = statement;
734
+ guard.run(at, execute);
735
+ });
736
+ guard?.finish();
530
737
  currentIndex = -1;
531
738
  currentStatement = null;
532
739
  this.sql.exec("INSERT INTO __migrations (name, chunk_index, applied_at) VALUES (?, ?, ?)", name, chunkIndex, (/* @__PURE__ */ new Date()).toISOString());
@@ -760,4 +967,4 @@ var RemovedDatabaseDurableObject = class extends DurableObject {
760
967
  }
761
968
  };
762
969
  //#endregion
763
- export { CamelCasePlugin, DateSerializePlugin, DrizzleDefaultsPlugin, MigrationSchemaConflictError, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, outboxSink, queueOutboxSink, removedDatabaseMessage, studio, tenantOfInstanceKey, type };
970
+ export { CamelCasePlugin, DateSerializePlugin, DrizzleDefaultsPlugin, MigrationSchemaConflictError, RelatedExpression, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, outboxSink, queueOutboxSink, relationOf, relationsOf, removedDatabaseMessage, studio, tenantOfInstanceKey, type };