durable-db 0.7.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)
@@ -30,6 +31,9 @@ Define your schema with [Drizzle](https://orm.drizzle.team/), query with [Kysely
30
31
  - [Outerbase Studio Integration](#outerbase-studio-integration)
31
32
  - [Instance Strategies](#instance-strategies)
32
33
  - [Action-to-Action Calls](#action-to-action-calls)
34
+ - [The Outbox](#the-outbox)
35
+ - [Shared Actions](#shared-actions)
36
+ - [Relations](#relations)
33
37
  - [PITR Safety](#pitr-safety)
34
38
  - [Recovery Workflows](#recovery-workflows)
35
39
  - [Architecture](#architecture)
@@ -691,6 +695,20 @@ SQLite rejects `ALTER TABLE … ADD … NOT NULL` without a default on a table t
691
695
 
692
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.
693
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
+
694
712
  ### Epoch System
695
713
 
696
714
  In development, each database instance key gets an epoch suffix to enable clean resets:
@@ -1018,6 +1036,45 @@ defineDatabase({
1018
1036
 
1019
1037
  ---
1020
1038
 
1039
+ ## The Outbox
1040
+
1041
+ An action runs inside its Durable Object, in the middle of its writes: it should not send an email, call a webhook or enqueue a job itself — that would happen even if the action then failed, and its code would have to be in the object. It records a message instead, and something outside acts on it after the action has succeeded:
1042
+
1043
+ ```ts
1044
+ export const signUp = action({
1045
+ args: { email: 'string.email' },
1046
+ handler: async (db, { email }, ctx) => {
1047
+ const user = await db.insertInto('users').values({ id: crypto.randomUUID(), email }).returningAll().executeTakeFirstOrThrow();
1048
+ ctx.outbox.push({ type: 'welcome-email', userId: user.id });
1049
+ return user;
1050
+ },
1051
+ });
1052
+ ```
1053
+
1054
+ Where the messages go is configured once, in the plugin:
1055
+
1056
+ ```ts
1057
+ durableDb({ outbox: { queue: 'EVENTS' } }) // each message to the Queue binding EVENTS, as it is
1058
+ durableDb({ outbox: { module: './src/outbox.ts' } }) // a module whose default export delivers them
1059
+ ```
1060
+
1061
+ ```ts
1062
+ // src/outbox.ts — a function, or an object with `deliver`
1063
+ import type { OutboxEnvelope } from 'durable-db/db';
1064
+
1065
+ export default async function deliver(envelopes: OutboxEnvelope[], { env }: { env: Env }) {
1066
+ for (const { message, tenantId } of envelopes) await env.WEBHOOKS.send({ ...message, tenant: tenantId });
1067
+ }
1068
+ ```
1069
+
1070
+ - **With the action's writes.** The messages are written to the object's `__outbox` table when the handler resolves, in the same synchronous block as its last writes — the Durable Object commits them together — and the alarm that delivers them is set with them. A handler that throws records none. An action called from another action of the same database shares its outbox.
1071
+ - **At least once.** The alarm hands the oldest messages (up to 100 per delivery) to the sink and deletes what was delivered; a delivery that throws stays in the table, with its error, and is retried with backoff (5 s, doubling, at most 5 minutes). A message may arrive twice — make what consumes it idempotent.
1072
+ - **Envelopes.** The sink gets `{ message, instanceKey, tenantId, recordedAt }`: `tenantId` is a per-tenant instance's tenant (null for a global database).
1073
+ - **JSON.** A message is a JSON value, checked when it is pushed.
1074
+ - **Typed.** `push()` takes any JSON value until you declare the message: `declare global { interface DurableDbOutbox { message: { type: 'welcome-email'; userId: string } } }`.
1075
+ - **Without a sink** `ctx.outbox.push()` throws, naming the option. The generated classes use the alarm for the outbox; a hand-written subclass with an alarm of its own calls `super.alarm()`.
1076
+ - **Tests.** `createTestDatabase()` keeps what successful actions pushed in `t.outbox`, and its `outbox` option delivers them as the sink would.
1077
+
1021
1078
  ## Action-to-Action Calls
1022
1079
 
1023
1080
  Actions can call other actions. The Vite plugin detects these calls at build time and routes them correctly.
@@ -1051,6 +1108,113 @@ export const createUser = action({
1051
1108
 
1052
1109
  ---
1053
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
+
1054
1218
  ## PITR Safety
1055
1219
 
1056
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-COek3gjm.js";
4
- import "../index-DOoXuKtZ.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,4 +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-COek3gjm.js";
3
- 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-DOoXuKtZ.js";
4
- 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 ParsedDatabaseFile, type QueryResult, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, type SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, removedDatabaseMessage, studio, type };
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
+ 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-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, i as SchemaPlugin, n as DateSerializePlugin, o as dateSerializers, r as DrizzleDefaultsPlugin, t as createKyselyFromSql } from "../kysely-BZNv9gpz.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
  */
@@ -165,6 +357,71 @@ var SqliteDurableObject = class extends DurableObject {
165
357
  this.sql = ctx.storage.sql;
166
358
  }
167
359
  /**
360
+ * Where the outbox delivers (`./outbox`): the generated class sets it from
361
+ * `durableDb({ outbox })`. Null: `ctx.outbox.push()` refuses, naming the option.
362
+ */
363
+ outboxSink = null;
364
+ outboxReady = false;
365
+ ensureOutboxTable() {
366
+ if (this.outboxReady) return;
367
+ this.sql.exec(OUTBOX_DDL);
368
+ this.outboxReady = true;
369
+ }
370
+ /**
371
+ * Runs an action with `ctx.outbox`. The messages it pushed are written when
372
+ * it resolves — in the same synchronous block as its last writes, which the
373
+ * Durable Object commits together — and the alarm that delivers them is set
374
+ * with them. A handler that throws records nothing. An action called from
375
+ * another action of this database runs on the caller's context, and so on
376
+ * its outbox.
377
+ */
378
+ async runWithOutbox(ctx, run) {
379
+ if (ctx.outbox) return run();
380
+ const outbox = createActionOutbox(this.outboxSink !== null);
381
+ ctx.outbox = outbox;
382
+ const result = await run();
383
+ const messages = outbox.take();
384
+ if (messages.length > 0) {
385
+ this.ensureOutboxTable();
386
+ const now = Date.now();
387
+ for (const message of messages) this.sql.exec(`INSERT INTO ${OUTBOX_TABLE} (instance_key, message, recorded_at) VALUES (?, ?, ?)`, ctx.instanceKey, message, now);
388
+ await this.ctx.storage.setAlarm(now);
389
+ }
390
+ return result;
391
+ }
392
+ /**
393
+ * Delivers the outbox: up to OUTBOX_DELIVERY_SIZE messages, oldest first, to
394
+ * the sink; what was delivered is deleted, and the alarm comes back while
395
+ * more are waiting. A delivery that throws stays in the table and is retried
396
+ * with backoff (5 s, doubling, at most 5 minutes), so a message arrives at
397
+ * least once. A subclass with an alarm of its own calls `super.alarm()`.
398
+ */
399
+ async alarm() {
400
+ if (!this.outboxSink) return;
401
+ this.ensureOutboxTable();
402
+ const rows = this.sql.exec(`SELECT id, instance_key, message, recorded_at, attempts FROM ${OUTBOX_TABLE} ORDER BY id LIMIT ?`, 100).toArray();
403
+ if (rows.length === 0) return;
404
+ const lastId = rows[rows.length - 1].id;
405
+ const envelopes = rows.map((row) => ({
406
+ message: JSON.parse(row.message),
407
+ instanceKey: row.instance_key,
408
+ tenantId: tenantOfInstanceKey(row.instance_key),
409
+ recordedAt: row.recorded_at
410
+ }));
411
+ try {
412
+ await this.outboxSink.deliver(envelopes, { env: this.env });
413
+ } catch (error) {
414
+ const attempts = Math.max(...rows.map((row) => row.attempts)) + 1;
415
+ const delay = outboxRetryDelay(attempts);
416
+ this.sql.exec(`UPDATE ${OUTBOX_TABLE} SET attempts = attempts + 1, last_error = ? WHERE id <= ?`, String(error), lastId);
417
+ console.error(`[db] Outbox delivery failed (attempt ${attempts}, ${rows.length} message(s)); retrying in ${delay / 1e3}s:`, error);
418
+ await this.ctx.storage.setAlarm(Date.now() + delay);
419
+ return;
420
+ }
421
+ this.sql.exec(`DELETE FROM ${OUTBOX_TABLE} WHERE id <= ?`, lastId);
422
+ if (this.sql.exec(`SELECT 1 FROM __outbox LIMIT 1`).toArray().length > 0) await this.ctx.storage.setAlarm(Date.now());
423
+ }
424
+ /**
168
425
  * Check if PITR is available on this DO's storage.
169
426
  * Result is cached after the first call.
170
427
  */
@@ -451,6 +708,7 @@ var SqliteDurableObject = class extends DurableObject {
451
708
  let skipped = 0;
452
709
  const applyChunk = () => {
453
710
  skipped = 0;
711
+ const toRun = [];
454
712
  for (let i = 0; i < statements.length; i++) {
455
713
  const statement = statements[i];
456
714
  if (!statement.trim()) continue;
@@ -458,10 +716,24 @@ var SqliteDurableObject = class extends DurableObject {
458
716
  skipped++;
459
717
  continue;
460
718
  }
461
- currentIndex = i;
462
- currentStatement = statement;
463
- this.sql.exec(statement);
719
+ toRun.push({
720
+ index: i,
721
+ statement
722
+ });
464
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();
465
737
  currentIndex = -1;
466
738
  currentStatement = null;
467
739
  this.sql.exec("INSERT INTO __migrations (name, chunk_index, applied_at) VALUES (?, ?, ?)", name, chunkIndex, (/* @__PURE__ */ new Date()).toISOString());
@@ -695,4 +967,4 @@ var RemovedDatabaseDurableObject = class extends DurableObject {
695
967
  }
696
968
  };
697
969
  //#endregion
698
- export { CamelCasePlugin, DateSerializePlugin, DrizzleDefaultsPlugin, MigrationSchemaConflictError, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, removedDatabaseMessage, studio, type };
970
+ export { CamelCasePlugin, DateSerializePlugin, DrizzleDefaultsPlugin, MigrationSchemaConflictError, RelatedExpression, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, outboxSink, queueOutboxSink, relationOf, relationsOf, removedDatabaseMessage, studio, tenantOfInstanceKey, type };