durable-db 0.8.0 → 0.10.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,13 +1,205 @@
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-CULpd87Z.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-DCQRqT62.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, createJsonPlugins, createKyselyFromSql, createRelated, dateSerializers, defineDatabase, outboxSink, parseJsonValue, queueOutboxSink, relationOf, relationsOf, removedDatabaseMessage, studio, tenantOfInstanceKey, type };
@@ -0,0 +1,407 @@
1
+ import "./index-bUUlOWfP.js";
2
+ import { t as Outbox } from "./outbox-D3Q9n7Rt.js";
3
+ import { type } from "arktype";
4
+ import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
5
+ import { AliasNode, AliasedExpression, Expression, Kysely, KyselyPlugin, Selectable } from "kysely";
6
+ import { Kyselify } from "drizzle-orm/kysely";
7
+ //#region src/db/relations.d.ts
8
+ type AnySchema = Record<string, SQLiteTableWithColumns<any>>;
9
+ type RefOf<Col> = Col extends {
10
+ _: {
11
+ references: infer C;
12
+ };
13
+ } ? C : never;
14
+ type TableNameOf<Col> = Col extends {
15
+ _: {
16
+ tableName: infer N;
17
+ };
18
+ } ? N : never;
19
+ type ColumnsOf<T> = T extends {
20
+ _: {
21
+ columns: infer C;
22
+ };
23
+ } ? C : never;
24
+ type NameOf<T> = T extends {
25
+ _: {
26
+ name: infer N;
27
+ };
28
+ } ? N : never;
29
+ type KeyOf<S, Name> = { [K in keyof S & string]: NameOf<S[K]> extends Name ? K : never; }[keyof S & string];
30
+ type TargetOf$1<S, Col> = [RefOf<Col>] extends [never] ? never : string extends TableNameOf<RefOf<Col>> ? never : KeyOf<S, TableNameOf<RefOf<Col>>>;
31
+ /** Every foreign key of a schema the types know: the table and column that hold it, the table it points at. */
32
+ type Edge<S> = { [TK in keyof S & string]: { [CK in keyof ColumnsOf<S[TK]> & string]: [TargetOf$1<S, ColumnsOf<S[TK]>[CK]>] extends [never] ? never : {
33
+ table: TK;
34
+ column: CK;
35
+ target: TargetOf$1<S, ColumnsOf<S[TK]>[CK]>;
36
+ nullable: ColumnsOf<S[TK]>[CK] extends {
37
+ _: {
38
+ notNull: true;
39
+ };
40
+ } ? false : true;
41
+ }; }[keyof ColumnsOf<S[TK]> & string]; }[keyof S & string];
42
+ type AnyEdge = {
43
+ table: string;
44
+ column: string;
45
+ target: string;
46
+ nullable: boolean;
47
+ };
48
+ type ForwardName<K extends string> = K extends `${infer P}Id` ? P extends '' ? K : P : K extends `${infer P}_id` ? P extends '' ? K : P : K;
49
+ type IsUnion<T, U = T> = [T] extends [never] ? false : T extends unknown ? ([U] extends [T] ? false : true) : never;
50
+ type InverseName<S, E extends AnyEdge> = IsUnion<Extract<Edge<S>, {
51
+ table: E['table'];
52
+ target: E['target'];
53
+ }>> extends true ? `${E['table']}As${Capitalize<ForwardName<E['column']>>}` : E['table'];
54
+ /** A relation as the types describe it. */
55
+ type RelationType = {
56
+ kind: 'one';
57
+ target: string;
58
+ nullable: boolean;
59
+ } | {
60
+ kind: 'many';
61
+ target: string;
62
+ };
63
+ type Forward<S, TK> = { [E in Extract<Edge<S>, {
64
+ table: TK;
65
+ }> as ForwardName<E['column']>]: {
66
+ kind: 'one';
67
+ target: E['target'];
68
+ nullable: E['nullable'];
69
+ }; };
70
+ type Inverse<S, TK> = { [E in Extract<Edge<S>, {
71
+ target: TK;
72
+ }> as InverseName<S, E>]: {
73
+ kind: 'many';
74
+ target: E['table'];
75
+ }; };
76
+ /**
77
+ * The relations of a schema, per table: what its foreign keys say, in both
78
+ * directions.
79
+ *
80
+ * ```ts
81
+ * type R = Relations<typeof schema>;
82
+ * // R['invoices']['customer'] → { kind: 'one'; target: 'customers'; nullable: false }
83
+ * // R['customers']['invoices'] → { kind: 'many'; target: 'invoices' }
84
+ * ```
85
+ */
86
+ type Relations<S> = { [TK in keyof S & string]: { [N in keyof (Forward<S, TK> & Inverse<S, TK>)]: (Forward<S, TK> & Inverse<S, TK>)[N]; }; };
87
+ /** A relation as the runtime knows it. Tables are schema keys, columns their properties. */
88
+ interface Relation {
89
+ kind: 'one' | 'many';
90
+ name: string;
91
+ /** The table that has the relation. */
92
+ table: string;
93
+ /** The table it leads to. */
94
+ target: string;
95
+ /** The column of `table` the relation is matched on: the foreign key of a `one`, the referenced column of a `many`. */
96
+ local: string;
97
+ /** The column of `target` it matches. */
98
+ foreign: string;
99
+ /** A `one` whose foreign key may be null. Always false for a `many`. */
100
+ nullable: boolean;
101
+ }
102
+ /** `relations[table][name]`. */
103
+ type RelationMap = Record<string, Record<string, Relation>>;
104
+ /**
105
+ * The relations a schema's foreign keys declare, per table. Read the first
106
+ * time it is asked for (a foreign key's target is a callback, so every table
107
+ * of the schema exists by then) and kept.
108
+ */
109
+ declare function relationsOf(schema: AnySchema): RelationMap;
110
+ /** One relation of a table, or an error that says what there is. */
111
+ declare function relationOf(schema: AnySchema, table: string, name: string): Relation;
112
+ //#endregion
113
+ //#region src/db/related.d.ts
114
+ type Simplify<T> = { [K in keyof T]: T[K]; } & {};
115
+ type Row<S extends AnySchema, TK> = TK extends keyof S ? Selectable<DrizzleToKysely<S>[TK]> : never;
116
+ type TargetOf<Rel> = Rel extends {
117
+ target: infer T;
118
+ } ? T : never;
119
+ /** What the relations in `with` add to a row: each under its name. */
120
+ type Nested<W> = W extends readonly RelatedExpression<string, string, unknown>[] ? { [E in W[number] as E['alias']]: E extends RelatedExpression<string, string, infer V> ? V : never; } : {};
121
+ /** A `one` answers its row (or null, when the foreign key may be null), a `many` a list. */
122
+ type Value<Rel, Item> = Rel extends {
123
+ kind: 'one';
124
+ nullable: false;
125
+ } ? Item : Rel extends {
126
+ kind: 'one';
127
+ } ? Item | null : Item[];
128
+ interface RelatedOptions<C extends string, W, K extends string = C> {
129
+ /** The columns of the related table to read. */
130
+ columns: readonly C[];
131
+ /** Relations of the related table, read with each row: `related('<that table>', …)`. */
132
+ with?: W;
133
+ /** A `many` only: the order of its rows, first key first. */
134
+ orderBy?: { [P in K]?: 'asc' | 'desc'; };
135
+ /** A `many` only: at most this many rows per parent. */
136
+ limit?: number;
137
+ }
138
+ /**
139
+ * `related(table, relation, columns)`: the rows `relation` leads to from each
140
+ * row of `table`, as a selection.
141
+ */
142
+ interface Related<S extends AnySchema> {
143
+ <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>>>>;
144
+ <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>): RelatedExpression<TK, R, Value<Relations<S>[TK][R], Simplify<Pick<Row<S, TargetOf<Relations<S>[TK][R]>>, C> & Nested<W>>>>;
145
+ }
146
+ /**
147
+ * `related` for a schema whose tables are known only when the code runs (a
148
+ * library that is handed one): the names are strings, checked against the
149
+ * schema when it is called, and what it answers is typed by the caller.
150
+ */
151
+ interface AnyRelated {
152
+ (table: string, relation: string, columns: readonly string[]): RelatedExpression<string, string, unknown>;
153
+ (table: string, relation: string, options: RelatedOptions<string, readonly RelatedExpression<string, string, unknown>[]>): RelatedExpression<string, string, unknown>;
154
+ }
155
+ /** A relation to read, checked against the schema: what `related()` builds. */
156
+ interface RelatedSpec {
157
+ schema: AnySchema;
158
+ relation: Relation;
159
+ /** The key it is answered under: the relation's name, or what `.as()` said. */
160
+ alias: string;
161
+ columns: string[];
162
+ with: RelatedSpec[];
163
+ orderBy: [column: string, direction: 'asc' | 'desc'][];
164
+ limit?: number;
165
+ }
166
+ /**
167
+ * A relation as a selection: what `related()` returns. `table` is the table
168
+ * it is a relation of (so `with` takes only the related table's own), `alias`
169
+ * the key it is answered under — the relation's name, until `.as()` says
170
+ * another.
171
+ */
172
+ declare class RelatedExpression<TK extends string, A extends string, V> implements AliasedExpression<V, A> {
173
+ readonly table: TK;
174
+ readonly alias: A;
175
+ constructor(spec: RelatedSpec);
176
+ /**
177
+ * The same relation, answered under `name` instead of its own:
178
+ * `related('customers', 'invoices', { columns: ['id'], limit: 1 }).as('latest')`.
179
+ * A new expression — this one keeps its name.
180
+ */
181
+ as<N extends string>(name: N): RelatedExpression<TK, N, V>;
182
+ get expression(): Expression<V>;
183
+ toOperationNode(): AliasNode;
184
+ }
185
+ /**
186
+ * `related` for a schema: what `defineDatabase()` hands out, and the way to
187
+ * it for code that is handed a schema — typed by the schema's tables, or by
188
+ * strings (`AnyRelated`) when its type names none.
189
+ */
190
+ declare function createRelated<S extends AnySchema>(schema: S): string extends keyof S ? AnyRelated : Related<S>;
191
+ //#endregion
192
+ //#region src/db/types.d.ts
193
+ /**
194
+ * Base type for ArkType schema definitions.
195
+ * This represents any valid arktype definition object.
196
+ */
197
+ type ArgsSchema = Record<string, unknown>;
198
+ /**
199
+ * Configuration for defineDatabase
200
+ */
201
+ interface DatabaseConfig<TSchema extends Record<string, SQLiteTableWithColumns<any>>> {
202
+ /** Drizzle schema tables */
203
+ schema: TSchema;
204
+ /** Instance strategy - 'per-tenant' (default) or 'global' */
205
+ instance?: 'per-tenant' | 'global';
206
+ /** Enable Outerbase Studio browsable SQL endpoint on this DO.
207
+ * - true: always enabled
208
+ * - false: always disabled (default)
209
+ * - 'development': enabled only in dev mode */
210
+ browsable?: boolean | 'development';
211
+ /** Transport for action stubs: 'rpc' (default) or 'websocket'.
212
+ * WebSocket uses Cloudflare's 20:1 message billing ratio for cheaper high-volume calls. */
213
+ transport?: 'rpc' | 'websocket';
214
+ }
215
+ /**
216
+ * Convert a Drizzle schema to Kysely database types using drizzle-kysely
217
+ */
218
+ type DrizzleToKysely<TSchema extends Record<string, SQLiteTableWithColumns<any>>> = { [K in keyof TSchema]: TSchema[K] extends SQLiteTableWithColumns<any> ? Kyselify<TSchema[K]> : never; };
219
+ /**
220
+ * ArkType helpers – mirror Ark's own API:
221
+ * - arkType.validate<Def> → definition shape with DSL validation/autocomplete
222
+ * - arkType.infer<Def> → inferred output type
223
+ */
224
+ type ArkDef<Def> = type.validate<Def>;
225
+ type InferArgs<Def> = type.infer<Def>;
226
+ /**
227
+ * Context passed to action handlers
228
+ */
229
+ interface ActionContext<TEnv = unknown> {
230
+ /** Environment bindings (DO bindings, KV, etc.) */
231
+ env: TEnv;
232
+ /**
233
+ * The instance key used to address this Durable Object.
234
+ * For per-tenant databases, this is the tenant ID.
235
+ * For global databases, this is 'global'.
236
+ */
237
+ instanceKey: string;
238
+ /**
239
+ * Messages for something outside the Durable Object — a queue, an email, a
240
+ * webhook — delivered after the action succeeds (`durableDb({ outbox })`
241
+ * names where): `ctx.outbox.push(message)`. Written with the action's
242
+ * writes, at least once; a handler that throws records none.
243
+ */
244
+ outbox: Outbox;
245
+ }
246
+ /**
247
+ * Configuration for an action
248
+ *
249
+ * `Def` is "the ArkType definition" – whatever you'd normally pass to `type(...)`:
250
+ * { name: "string", email: "string.email" }
251
+ * unions, tuples, ranges, etc. all work.
252
+ */
253
+ interface ActionConfig<Def, TResult, TSchema extends Record<string, SQLiteTableWithColumns<any>>, TEnv = unknown> {
254
+ /**
255
+ * ArkType definition for args.
256
+ * Typed as `arkType.validate<Def>` so you get the SAME DSL autocomplete
257
+ * as when you do `type(Def)` directly.
258
+ */
259
+ args: ArkDef<Def>;
260
+ /**
261
+ * The action handler
262
+ */
263
+ handler: (db: Kysely<DrizzleToKysely<TSchema>>, args: InferArgs<Def>, ctx: ActionContext<TEnv>) => Promise<TResult>;
264
+ }
265
+ /**
266
+ * An action function that can be called from routes or other actions
267
+ */
268
+ type Action<TArgs, TResult> = (args: TArgs) => Promise<TResult>;
269
+ /**
270
+ * Return type of defineDatabase
271
+ */
272
+ interface DatabaseDefinition<TSchema extends Record<string, SQLiteTableWithColumns<any>>> {
273
+ /**
274
+ * Define an action that runs within the database context
275
+ *
276
+ * NOTE: the `const Def` *here* is crucial – it matches ArkType's own
277
+ * `<const def>(def: type.validate<def>)` pattern and is what makes
278
+ * `"string.email"` etc. behave properly.
279
+ */
280
+ action: <const Def, TResult, TEnv = unknown>(config: ActionConfig<Def, TResult, TSchema, TEnv>) => Action<InferArgs<Def>, TResult>;
281
+ /**
282
+ * A relation of a table as a selection: the rows a foreign key leads to,
283
+ * read in the query that reads the row.
284
+ *
285
+ * db.selectFrom('invoices')
286
+ * .select(['invoices.id', related('invoices', 'customer', ['id', 'name'])])
287
+ *
288
+ * A relation is a column with `.references(() => other.column)`, named in
289
+ * both directions (see `relations`).
290
+ */
291
+ related: Related<TSchema>;
292
+ /**
293
+ * The relations the schema's foreign keys declare, by table and name:
294
+ * `relations.invoices.customer` (one), `relations.customers.invoices` (many).
295
+ */
296
+ readonly relations: RelationMap;
297
+ /**
298
+ * Destroy the database instance, clearing all data via `ctx.storage.deleteAll()`.
299
+ * The next action call will re-run migrations and start fresh.
300
+ *
301
+ * For per-tenant databases, targets the current tenant (via `getTenantId()`).
302
+ * For global databases, targets the single shared instance.
303
+ */
304
+ destroyDatabase: () => Promise<void>;
305
+ }
306
+ /**
307
+ * Information about a parsed database file
308
+ */
309
+ interface DatabaseInfo {
310
+ /** File path to the database definition file */
311
+ filePath: string;
312
+ /** Database name derived from filename */
313
+ name: string;
314
+ /** Class name for the Durable Object */
315
+ className: string;
316
+ /** Binding name for wrangler config */
317
+ bindingName: string;
318
+ /** Instance strategy */
319
+ instance: 'per-tenant' | 'global';
320
+ /** Path to migrations directory */
321
+ migrationsDir: string;
322
+ /** Schema import source (relative path) */
323
+ schemaImport: string | null;
324
+ /**
325
+ * The export of the schema module that is the whole schema — a const shared
326
+ * with other code (`export const schema = { users, posts }`, passed as
327
+ * `defineDatabase({ schema })`). Null when the tables are listed in the call.
328
+ */
329
+ schemaExport: string | null;
330
+ /** Names of schema tables, when they are listed in the call (empty with `schemaExport`: the const says) */
331
+ schemaTableNames: string[];
332
+ /** Whether the DO should expose a browsable SQL endpoint */
333
+ browsable: boolean | 'development';
334
+ /** Transport for action stubs */
335
+ transport: 'rpc' | 'websocket';
336
+ /** Loaded migrations - Map of name -> chunks (each chunk is array of SQL statements) */
337
+ migrations?: Map<string, string[][]>;
338
+ }
339
+ /**
340
+ * Information about a parsed action
341
+ */
342
+ interface ActionInfo {
343
+ /** Export name of the action */
344
+ exportName: string;
345
+ /** The args schema (as source code string for codegen) */
346
+ argsSchemaSource: string;
347
+ /** The handler function (as source code string for codegen) */
348
+ handlerSource: string;
349
+ /** The database this action belongs to */
350
+ databaseName: string;
351
+ /** File where the action is defined */
352
+ sourceFile: string;
353
+ }
354
+ /**
355
+ * Result of parsing a database file
356
+ */
357
+ interface ParsedDatabaseFile {
358
+ /** Absolute file path */
359
+ filePath: string;
360
+ /** Database configuration if this file has defineDatabase */
361
+ database: DatabaseInfo | null;
362
+ /** Actions defined in this file */
363
+ actions: ActionInfo[];
364
+ /** Local imports (for dependency resolution) */
365
+ localImports: Map<string, {
366
+ source: string;
367
+ imported: string;
368
+ }>;
369
+ }
370
+ //#endregion
371
+ //#region src/db/defineDatabase.d.ts
372
+ /**
373
+ * Define a database with its schema and migrations.
374
+ *
375
+ * This function is transformed at build time by the durable-db Vite plugin.
376
+ * At runtime, the actions returned will be RPC stubs that call into the
377
+ * generated Durable Object.
378
+ *
379
+ * Outside the build — code under test calling an action directly — an action
380
+ * runs against the test database `createTestDatabase()` created for its
381
+ * database's tables (the newest one, when there are several); without one it
382
+ * throws.
383
+ *
384
+ * @example
385
+ * ```ts
386
+ * import { defineDatabase } from 'durable-db';
387
+ * import { users, posts } from './schema';
388
+ *
389
+ * export const { action } = defineDatabase({
390
+ * schema: { users, posts },
391
+ * });
392
+ *
393
+ * export const createUser = action({
394
+ * args: { name: 'string', email: 'string.email' },
395
+ * handler: async (db, args) => {
396
+ * return db.insertInto('users').values({
397
+ * id: crypto.randomUUID(),
398
+ * name: args.name,
399
+ * email: args.email
400
+ * }).returningAll().executeTakeFirst();
401
+ * },
402
+ * });
403
+ * ```
404
+ */
405
+ declare function defineDatabase<TSchema extends Record<string, SQLiteTableWithColumns<any>>>(config: DatabaseConfig<TSchema>): DatabaseDefinition<TSchema>;
406
+ //#endregion
407
+ export { Relations as C, RelationType as S, relationsOf as T, RelatedSpec as _, ActionInfo as a, Relation as b, DatabaseDefinition as c, InferArgs as d, ParsedDatabaseFile as f, RelatedOptions as g, RelatedExpression as h, ActionContext as i, DatabaseInfo as l, Related as m, Action as n, ArgsSchema as o, AnyRelated as p, ActionConfig as r, DatabaseConfig as s, defineDatabase as t, DrizzleToKysely as u, createRelated as v, relationOf as w, RelationMap as x, AnySchema as y };