durable-db 0.10.0 → 0.12.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
@@ -339,7 +339,24 @@ The resolver is called at the moment a database operation needs the tenant ID
339
339
 
340
340
  Behind the scenes, each action call is an RPC call to the correct Durable Object instance. The Vite plugin generates stubs that handle instance routing, argument validation, and DO communication transparently.
341
341
 
342
- Calls to the **same** Durable Object instance that start before the code waits on I/O share one round trip: `Promise.all([countProducts({}), listProducts({ featuredOnly: true })])` (or sibling server components fetching at once, or two RPC procedures whose middleware awaits a different number of times before their action calls) sends both in a single RPC, and the object runs them one after another, in the order they were made — each result or error goes back to its own caller. A lone call, or calls made one after another, are plain RPCs as before. Each action's args schema is compiled on its first call and reused.
342
+ Each action's args schema is compiled on its first call and reused.
343
+
344
+ ### One round trip per invocation: `batchScope()`
345
+
346
+ Calls to the **same** Durable Object instance that one invocation starts before it waits on I/O can share one round trip. Say what an invocation is by wrapping what the platform invokes:
347
+
348
+ ```ts
349
+ import { batchScope } from 'durable-db/registry';
350
+
351
+ export default {
352
+ fetch: (request: Request, env: Env, ctx: ExecutionContext) => batchScope(() => app.fetch(request, env, ctx)),
353
+ queue: (batch: MessageBatch, env: Env) => batchScope(() => consume(batch, env)),
354
+ };
355
+ ```
356
+
357
+ Inside it, `Promise.all([countProducts({}), listProducts({ featuredOnly: true })])` (or sibling server components fetching at once, or two RPC procedures whose middleware awaits a different number of times before their action calls) sends both in a single RPC, and the object runs them one after another, in the order they were made — each result or error goes back to its own caller. A lone call, and calls made one after another, are plain RPCs.
358
+
359
+ Outside a scope every call is its own RPC. A batch is only safe among the calls of one invocation — the Workers runtime refuses to settle one request's promise from another request's context — and nothing but the scope tells two concurrent requests' calls apart. (Before 0.12 calls were batched per object across the whole isolate, and two requests that reached one object in the same turn could leave one of them hanging.)
343
360
 
344
361
  ---
345
362
 
@@ -1224,6 +1241,32 @@ related('customers', 'invoices', {
1224
1241
  });
1225
1242
  ```
1226
1243
 
1244
+ **Filtering.** `where` says which rows of a `many` to read — a condition on the related table, written with Kysely's expression builder and typed from the schema. It applies before `limit`, and its values are bound like those of any condition:
1245
+
1246
+ ```ts
1247
+ related('invoices', 'invoiceLines', {
1248
+ columns: ['description'],
1249
+ where: (eb) => eb('quantity', '>', 0),
1250
+ });
1251
+
1252
+ // Whatever Kysely builds of the table's columns…
1253
+ related('invoices', 'invoiceLines', {
1254
+ columns: ['description'],
1255
+ where: (eb) => eb.or([eb('delivered', '=', false), eb('deliveredAt', '>', since)]),
1256
+ });
1257
+
1258
+ // …and another table in a subquery, which names the related row after its table.
1259
+ related('customers', 'invoices', {
1260
+ columns: ['number'],
1261
+ where: (eb) =>
1262
+ eb.exists(
1263
+ eb.selectFrom('invoiceLines').select('invoiceLines.id').whereRef('invoiceLines.invoiceId', '=', 'invoices.id'),
1264
+ ),
1265
+ });
1266
+ ```
1267
+
1268
+ A column is named alone or after its table (`'quantity'`, `'invoiceLines.quantity'`). A `one` takes no `where` (the row a foreign key leads to is there or it is not), and a column of another table outside a subquery is refused when `related()` is called. `RelatedWhere<Schema, '<table>'>` is the type of a condition kept in a variable.
1269
+
1227
1270
  **Another name.** `.as()` answers a relation under a name of your choosing, at the top of a query and inside `with`, and the type follows. The same relation can then be read twice in one query:
1228
1271
 
1229
1272
  ```ts
@@ -1251,7 +1294,7 @@ What it does not do yet:
1251
1294
  - 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.
1252
1295
  - Composite foreign keys (`foreignKey({ columns: [a, b] })`) are not relations.
1253
1296
  - `related()` names the table as the query does: `selectFrom('invoices')`, not `selectFrom('invoices as i')`. It needs the default `camelCase` mapping.
1254
- - No `where` on a relation; filter in the action.
1297
+ - A `where` compares a JSON column with what is stored (its text), like any `where`.
1255
1298
 
1256
1299
  ---
1257
1300
 
package/dist/cli/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { n as registerDbCommands } from "../cli-5KmSf8wx.js";
2
+ import { n as registerDbCommands } from "../cli-CRZWralu.js";
3
3
  import { Command } from "commander";
4
4
  //#region src/cli/bin.ts
5
5
  const program = new Command();
@@ -1,7 +1,7 @@
1
1
  import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
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-Bww_w_n5.js";
4
- import "../index-BQ1hHyrq.js";
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-RFLfeZGw.js";
3
+ import { l as DatabaseInfo } from "../defineDatabase-BE7YRtLh.js";
4
+ import "../index-CUkSkt7G.js";
5
5
  import { Command } from "commander";
6
6
  import "vite";
7
7
  import "@babel/types";
package/dist/cli/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { _ as saveDevState, a as generateEpoch, c as getDevEpoch, d as init_state, f as loadDevMigrations, h as runningDevServer, l as getDevPaths, o as getDatabaseEpoch, p as loadDevState, s as getDatabaseEpochs, u as getInstanceKey } from "../state-DGYycIoJ.js";
2
- import { g as parseRenameSpec, u as SchemaRenameRequiredError } from "../snapshot-D_z95s6E.js";
1
+ import { c as getDatabaseEpochs, d as getInstanceKey, f as init_state, g as runningDevServer, l as getDevEpoch, m as loadDevState, o as generateEpoch, p as loadDevMigrations, s as getDatabaseEpoch, u as getDevPaths, v as saveDevState } from "../state-UT6GH0JD.js";
2
+ import { g as parseRenameSpec, u as SchemaRenameRequiredError } from "../snapshot-CCIE4_Le.js";
3
3
  import { n as declaresSchema } from "../parser-mUnAtllk.js";
4
- import { _ as discoverDatabases, a as reset, b as reportCliError, c as status, d as generateOne, f as push, g as diffSchema, h as diffDatabases, i as DevServerRunningError, l as UnsafeMigrationError, m as UnknownDatabaseError, n as registerDbCommands, o as resetAndPush, p as pushOne, r as validate, s as formatStatus, t as createDbCommand, u as generate, v as loadSchema, x as selectDatabases, y as loadSchemaTables } from "../cli-5KmSf8wx.js";
4
+ import { _ as discoverDatabases, a as reset, b as reportCliError, c as status, d as generateOne, f as push, g as diffSchema, h as diffDatabases, i as DevServerRunningError, l as UnsafeMigrationError, m as UnknownDatabaseError, n as registerDbCommands, o as resetAndPush, p as pushOne, r as validate, s as formatStatus, t as createDbCommand, u as generate, v as loadSchema, x as selectDatabases, y as loadSchemaTables } from "../cli-CRZWralu.js";
5
5
  init_state();
6
6
  export { DevServerRunningError, SchemaRenameRequiredError, UnknownDatabaseError, UnsafeMigrationError, createDbCommand, declaresSchema, diffDatabases, diffSchema, discoverDatabases, formatStatus, generate, generateEpoch, generateOne, getDatabaseEpoch, getDatabaseEpochs, getDevEpoch, getDevPaths, getInstanceKey, loadDevMigrations, loadDevState, loadSchema, loadSchemaTables, parseRenameSpec, push, pushOne, registerDbCommands, reportCliError, reset, resetAndPush, runningDevServer, saveDevState, selectDatabases, status, validate };
@@ -1,6 +1,6 @@
1
1
  import { i as init_debug, o as __exportAll, t as debugCli } from "./debug-Cz8KzMft.js";
2
- import { _ as saveDevState, a as generateEpoch, d as init_state, f as loadDevMigrations, g as saveDevMigration, h as runningDevServer, i as forgetDatabaseDevState, l as getDevPaths, n as clearDatabaseDevState, o as getDatabaseEpoch, p as loadDevState, r as clearDevMigrations } from "./state-DGYycIoJ.js";
3
- import { _ as renamesFromStatements, f as describeAmbiguity, g as parseRenameSpec, h as formatRename, i as generateSnapshotFromSchema, l as analyzeMigrationRisks, m as findAmbiguities, o as hashSnapshot, p as exampleRenames, r as generateMigrationStatements, s as snapshotsEqual, u as SchemaRenameRequiredError, v as unusedRenames } from "./snapshot-D_z95s6E.js";
2
+ import { _ as saveDevMigration, a as forgetDatabaseDevState, f as init_state, g as runningDevServer, i as clearDevMigrations, m as loadDevState, o as generateEpoch, p as loadDevMigrations, r as clearDatabaseDevState, s as getDatabaseEpoch, u as getDevPaths, v as saveDevState } from "./state-UT6GH0JD.js";
3
+ import { _ as renamesFromStatements, f as describeAmbiguity, g as parseRenameSpec, h as formatRename, i as generateSnapshotFromSchema, l as analyzeMigrationRisks, m as findAmbiguities, o as hashSnapshot, p as exampleRenames, r as generateMigrationStatements, s as snapshotsEqual, u as SchemaRenameRequiredError, v as unusedRenames } from "./snapshot-CCIE4_Le.js";
4
4
  import { buildAndLoadSchema, generateCreateTableSQL, generateMigrationName, loadMigrationFiles, loadSnapshot, saveSnapshot } from "./migrations/generator.js";
5
5
  import { c as readFile, l as resolveImportPath, n as declaresSchema, r as parseDatabaseFile, s as discoverDatabaseFiles, u as loadViteAliases } from "./parser-mUnAtllk.js";
6
6
  import * as fs from "node:fs";
@@ -1,5 +1,5 @@
1
1
  import { s as __toCommonJS } from "../debug-Cz8KzMft.js";
2
- import { d as init_state, v as state_exports } from "../state-DGYycIoJ.js";
2
+ import { f as init_state, y as state_exports } from "../state-UT6GH0JD.js";
3
3
  //#region src/context/index.ts
4
4
  /**
5
5
  * Tenant ID resolver for framework integration.
@@ -1,5 +1,5 @@
1
1
  import { l as type } from "../index-bUUlOWfP.js";
2
- import { C as Relations, S as RelationType, T as relationsOf, _ as RelatedSpec, a as ActionInfo, b as Relation, c as DatabaseDefinition, d as InferArgs, f as ParsedDatabaseFile, g as RelatedOptions, h as RelatedExpression, i as ActionContext, l as DatabaseInfo, m as Related, n as Action, o as ArgsSchema, p as AnyRelated, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as createRelated, w as relationOf, x as RelationMap, y as AnySchema } from "../defineDatabase-Bww_w_n5.js";
2
+ import { C as RelationType, E as relationsOf, S as RelationMap, T as relationOf, _ as RelatedSpec, a as ActionInfo, b as AnySchema, c as DatabaseDefinition, d as InferArgs, f as ParsedDatabaseFile, g as RelatedOptions, h as RelatedExpression, i as ActionContext, l as DatabaseInfo, m as Related, n as Action, o as ArgsSchema, 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";
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 SqliteDurableObject, E as createKyselyFromSql, S as Migrations, T as SqlExecutor, _ as RemovedDatabaseError, a as QueryResult, b as MigrationAttemptInfo, c as DrizzleDefaultsPlugin, d as createDrizzlePlugins, f as createJsonPlugins, g as RemovedDatabaseDurableObject, h as DeleteClassMigration, i as KyselyPlugin, l as JsonPluginOptions, m as parseJsonValue, n as CompiledQuery, o as studio, p as dateSerializers, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as SchemaPlugin, v as removedDatabaseMessage, w as CreateKyselyOptions, x as MigrationSchemaConflictError, y as Migration } from "../index-BQ1hHyrq.js";
5
- export { type Action, type ActionConfig, type ActionContext, type ActionInfo, type AnyRelated, type AnySchema, type ArgsSchema, CamelCasePlugin, type CompiledQuery, type CreateKyselyOptions, type DatabaseConfig, type DatabaseDefinition, type DatabaseInfo, DateSerializePlugin, type DeleteClassMigration, DrizzleDefaultsPlugin, type DrizzleToKysely, type InferArgs, type JsonPluginOptions, 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 RelatedSpec, type Relation, type RelationMap, type RelationType, type Relations, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, type SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createJsonPlugins, createKyselyFromSql, createRelated, dateSerializers, defineDatabase, outboxSink, parseJsonValue, queueOutboxSink, relationOf, relationsOf, removedDatabaseMessage, studio, tenantOfInstanceKey, type };
4
+ import { C as SqliteDurableObject, E as createKyselyFromSql, S as Migrations, T as SqlExecutor, _ as RemovedDatabaseError, a as QueryResult, b as MigrationAttemptInfo, c as DrizzleDefaultsPlugin, d as createDrizzlePlugins, f as createJsonPlugins, g as RemovedDatabaseDurableObject, h as DeleteClassMigration, i as KyselyPlugin, l as JsonPluginOptions, m as parseJsonValue, n as CompiledQuery, o as studio, p as dateSerializers, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as SchemaPlugin, v as removedDatabaseMessage, w as CreateKyselyOptions, x as MigrationSchemaConflictError, y as Migration } from "../index-CUkSkt7G.js";
5
+ export { type Action, type ActionConfig, type ActionContext, type ActionInfo, type AnyRelated, type AnySchema, type ArgsSchema, CamelCasePlugin, type CompiledQuery, type CreateKyselyOptions, type DatabaseConfig, type DatabaseDefinition, type DatabaseInfo, DateSerializePlugin, type DeleteClassMigration, DrizzleDefaultsPlugin, type DrizzleToKysely, type InferArgs, type JsonPluginOptions, 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 RelatedSpec, type RelatedWhere, type Relation, type RelationMap, type RelationType, type Relations, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, type SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createJsonPlugins, createKyselyFromSql, createRelated, dateSerializers, defineDatabase, outboxSink, parseJsonValue, queueOutboxSink, relationOf, relationsOf, removedDatabaseMessage, studio, tenantOfInstanceKey, type };
package/dist/db/index.js CHANGED
@@ -1,8 +1,8 @@
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
+ 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";
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-DCQRqT62.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";
6
6
  import { CamelCasePlugin } from "kysely";
7
7
  import { DurableObject } from "cloudflare:workers";
8
8
  import { studio } from "@outerbase/browsable-durable-object";
@@ -2,7 +2,7 @@ import "./index-bUUlOWfP.js";
2
2
  import { t as Outbox } from "./outbox-D3Q9n7Rt.js";
3
3
  import { type } from "arktype";
4
4
  import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
5
- import { AliasNode, AliasedExpression, Expression, Kysely, KyselyPlugin, Selectable } from "kysely";
5
+ import { AliasNode, AliasedExpression, Expression, ExpressionBuilder, Kysely, KyselyPlugin, OperationNode, Selectable, SqlBool } from "kysely";
6
6
  import { Kyselify } from "drizzle-orm/kysely";
7
7
  //#region src/db/relations.d.ts
8
8
  type AnySchema = Record<string, SQLiteTableWithColumns<any>>;
@@ -125,7 +125,12 @@ type Value<Rel, Item> = Rel extends {
125
125
  } ? Item : Rel extends {
126
126
  kind: 'one';
127
127
  } ? Item | null : Item[];
128
- interface RelatedOptions<C extends string, W, K extends string = C> {
128
+ /**
129
+ * Which rows of a `many` to read: a condition on the related table `TK`,
130
+ * written with Kysely's expression builder — `(eb) => eb('quantity', '>', 0)`.
131
+ */
132
+ type RelatedWhere<S extends AnySchema, TK extends keyof S> = (eb: ExpressionBuilder<DrizzleToKysely<S>, TK>) => Expression<SqlBool>;
133
+ interface RelatedOptions<C extends string, W, K extends string = C, E = ExpressionBuilder<any, any>> {
129
134
  /** The columns of the related table to read. */
130
135
  columns: readonly C[];
131
136
  /** Relations of the related table, read with each row: `related('<that table>', …)`. */
@@ -134,6 +139,14 @@ interface RelatedOptions<C extends string, W, K extends string = C> {
134
139
  orderBy?: { [P in K]?: 'asc' | 'desc'; };
135
140
  /** A `many` only: at most this many rows per parent. */
136
141
  limit?: number;
142
+ /**
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`.
148
+ */
149
+ where?: (eb: E) => Expression<SqlBool>;
137
150
  }
138
151
  /**
139
152
  * `related(table, relation, columns)`: the rows `relation` leads to from each
@@ -141,7 +154,7 @@ interface RelatedOptions<C extends string, W, K extends string = C> {
141
154
  */
142
155
  interface Related<S extends AnySchema> {
143
156
  <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>>>>;
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>>>>;
145
158
  }
146
159
  /**
147
160
  * `related` for a schema whose tables are known only when the code runs (a
@@ -162,6 +175,8 @@ interface RelatedSpec {
162
175
  with: RelatedSpec[];
163
176
  orderBy: [column: string, direction: 'asc' | 'desc'][];
164
177
  limit?: number;
178
+ /** The condition `where` answered, as written: its columns are qualified when it is rendered. */
179
+ where?: OperationNode;
165
180
  }
166
181
  /**
167
182
  * A relation as a selection: what `related()` returns. `table` is the table
@@ -404,4 +419,4 @@ interface ParsedDatabaseFile {
404
419
  */
405
420
  declare function defineDatabase<TSchema extends Record<string, SQLiteTableWithColumns<any>>>(config: DatabaseConfig<TSchema>): DatabaseDefinition<TSchema>;
406
421
  //#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 };
422
+ export { RelationType as C, relationsOf as E, RelationMap as S, relationOf as T, RelatedSpec as _, ActionInfo as a, AnySchema 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, RelatedWhere as v, Relations as w, Relation as x, createRelated as y };
@@ -2,7 +2,7 @@ import { r as type } from "./type-CUgZsZp3.js";
2
2
  import { t as actionArgsType } from "./actionArgs-DP2tQrlf.js";
3
3
  import { Table, getTableColumns, getTableName, is, isSQLWrapper } from "drizzle-orm";
4
4
  import { SQLiteSyncDialect, getTableConfig } from "drizzle-orm/sqlite-core";
5
- import { AliasNode, CamelCasePlugin, ColumnNode, ColumnUpdateNode, DeleteQueryNode, IdentifierNode, InsertQueryNode, PrimitiveValueListNode, ReferenceNode, SelectAllNode, SelectQueryNode, TableNode, UpdateQueryNode, ValueListNode, ValueNode, ValuesNode, sql } from "kysely";
5
+ import { AliasNode, CamelCasePlugin, ColumnNode, ColumnUpdateNode, DeleteQueryNode, IdentifierNode, InsertQueryNode, OperationNodeTransformer, PrimitiveValueListNode, ReferenceNode, SelectAllNode, SelectQueryNode, TableNode, UpdateQueryNode, ValueListNode, ValueNode, ValuesNode, expressionBuilder, sql } from "kysely";
6
6
  import { toCamelCase, toSnakeCase } from "drizzle-orm/casing";
7
7
  //#region src/db/relations.ts
8
8
  const registries = /* @__PURE__ */ new WeakMap();
@@ -807,6 +807,62 @@ function metaOf(spec) {
807
807
  with: new Map(spec.with.map((nested) => [nested.alias, metaOf(nested)]))
808
808
  };
809
809
  }
810
+ /** The names a select reads its tables under: a table's own, or its alias. */
811
+ function namesIn(node) {
812
+ const names = /* @__PURE__ */ new Set();
813
+ const add = (source) => {
814
+ if (TableNode.is(source)) names.add(source.table.identifier.name);
815
+ else if (AliasNode.is(source) && IdentifierNode.is(source.alias)) names.add(source.alias.name);
816
+ };
817
+ for (const source of node.from?.froms ?? []) add(source);
818
+ for (const join of node.joins ?? []) add(join.table);
819
+ return names;
820
+ }
821
+ var Qualify = class extends OperationNodeTransformer {
822
+ #target;
823
+ #alias;
824
+ #where;
825
+ /** How many selects of the condition's own this is inside. */
826
+ #depth = 0;
827
+ /** How many of those read the related table under its name. */
828
+ #shadowed = 0;
829
+ constructor(target, alias, where) {
830
+ super();
831
+ this.#target = target;
832
+ this.#alias = alias;
833
+ this.#where = where;
834
+ }
835
+ transformSelectQuery(node, queryId) {
836
+ const shadows = namesIn(node).has(this.#target);
837
+ this.#depth++;
838
+ if (shadows) this.#shadowed++;
839
+ try {
840
+ return super.transformSelectQuery(node, queryId);
841
+ } finally {
842
+ this.#depth--;
843
+ if (shadows) this.#shadowed--;
844
+ }
845
+ }
846
+ transformReference(node, queryId) {
847
+ const table = node.table?.table.identifier.name;
848
+ if (table === void 0 ? this.#depth === 0 : table === this.#target && this.#shadowed === 0) return super.transformReference({
849
+ ...node,
850
+ table: TableNode.create(this.#alias)
851
+ }, queryId);
852
+ if (table !== void 0 && table !== this.#target && this.#depth === 0) {
853
+ const column = "column" in node.column ? node.column.column.name : "*";
854
+ throw new TypeError(`${this.#where}: where is a condition on "${this.#target}", and "${table}.${column}" is of another table — read that one in a subquery: eb.exists(eb.selectFrom('${table}')…).`);
855
+ }
856
+ return super.transformReference(node, queryId);
857
+ }
858
+ };
859
+ const messageOf = (spec) => `[durable-db] related('${spec.relation.table}', '${spec.relation.name}')`;
860
+ /** ` and (<the condition>)` about the rows that go by `alias` — or nothing. */
861
+ function filter(spec, alias) {
862
+ if (!spec.where) return sql``;
863
+ const node = new Qualify(spec.relation.target, alias, messageOf(spec)).transformNode(spec.where);
864
+ return sql` and (${{ toOperationNode: () => node }})`;
865
+ }
810
866
  function render(spec, outer, depth) {
811
867
  const { relation } = spec;
812
868
  const row = `_r${depth}`;
@@ -816,11 +872,11 @@ function render(spec, outer, depth) {
816
872
  const target = sql.table(relation.target);
817
873
  const matches = (alias) => sql`${sql.ref(`${alias}.${relation.foreign}`)} = ${sql.ref(`${outer}.${relation.local}`)}`;
818
874
  if (relation.kind === "one") return sql`(select ${object} from ${target} as ${sql.ref(row)} where ${matches(row)} limit 1)`;
819
- 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)})`;
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)})`;
820
876
  const inner = `_s${depth}`;
821
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)}`))}`;
822
878
  const limit = spec.limit === void 0 ? sql`` : sql` limit ${sql.lit(spec.limit)}`;
823
- return sql`(select json_group_array(${object}) from (select * from ${target} as ${sql.ref(inner)} where ${matches(inner)}${order}${limit}) as ${sql.ref(row)})`;
879
+ return sql`(select json_group_array(${object}) from (select * from ${target} as ${sql.ref(inner)} where ${matches(inner)}${filter(spec, inner)}${order}${limit}) as ${sql.ref(row)})`;
824
880
  }
825
881
  /**
826
882
  * A relation as a selection: what `related()` returns. `table` is the table
@@ -863,9 +919,9 @@ var RelatedExpression = class RelatedExpression {
863
919
  };
864
920
  function specOf(schema, table, name, arg) {
865
921
  const relation = relationOf(schema, table, name);
866
- const where = `[durable-db] related('${table}', '${name}')`;
922
+ const where = messageOf({ relation });
867
923
  const options = Array.isArray(arg) ? { columns: arg } : arg;
868
- if (typeof options !== "object" || options === null) throw new TypeError(`${where} takes the columns to read: ['id', …], or { columns, with, orderBy, limit }.`);
924
+ if (typeof options !== "object" || options === null) throw new TypeError(`${where} takes the columns to read: ['id', …], or { columns, with, orderBy, limit, where }.`);
869
925
  const known = getTableColumns(schema[relation.target]);
870
926
  const column = (key, what) => {
871
927
  if (typeof key !== "string" || !Object.hasOwn(known, key)) throw new TypeError(`${where}: ${what} "${String(key)}" is not a column of "${relation.target}". Its columns: ${Object.keys(known).join(", ")}.`);
@@ -898,7 +954,16 @@ function specOf(schema, table, name, arg) {
898
954
  }
899
955
  const { limit } = options;
900
956
  if (limit !== void 0 && (!Number.isSafeInteger(limit) || limit < 0)) throw new TypeError(`${where}: limit is a whole number, 0 or more.`);
901
- 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.`);
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.`);
958
+ let condition;
959
+ if (options.where !== void 0) {
960
+ const example = `where: (eb) => eb('<column>', '=', value)`;
961
+ if (typeof options.where !== "function") throw new TypeError(`${where}: where is a function that answers a condition — ${example}`);
962
+ const answered = options.where(expressionBuilder());
963
+ if (typeof answered !== "object" || answered === null || typeof answered.toOperationNode !== "function") throw new TypeError(`${where}: where answers a condition — ${example}`);
964
+ condition = answered.toOperationNode();
965
+ new Qualify(relation.target, relation.target, where).transformNode(condition);
966
+ }
902
967
  return {
903
968
  schema,
904
969
  relation,
@@ -906,7 +971,8 @@ function specOf(schema, table, name, arg) {
906
971
  columns,
907
972
  with: inner,
908
973
  orderBy,
909
- limit
974
+ limit,
975
+ where: condition
910
976
  };
911
977
  }
912
978
  /**
@@ -1,4 +1,4 @@
1
- import "./defineDatabase-Bww_w_n5.js";
1
+ import "./defineDatabase-BE7YRtLh.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 Relations, S as RelationType, T as relationsOf, _ as RelatedSpec, b as Relation, 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 createRelated, w as relationOf, x as RelationMap, y as AnySchema } from "./defineDatabase-Bww_w_n5.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";
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";
@@ -20,4 +20,4 @@ interface ActionDescription {
20
20
  /** The description of an action, or undefined for anything that is not one. */
21
21
  export declare function describeAction(action: unknown): ActionDescription | undefined;
22
22
  //#endregion
23
- export { type Action, type ActionConfig, type ActionContext, type ActionDescription, type AnyRelated, type AnySQLiteColumn, type AnySchema, type DatabaseConfig, type DatabaseDefinition, type DrizzleToKysely, type InferArgs, type Kysely, type Outbox, type OutboxEnvelope, type OutboxMessage, type OutboxSink, type OutboxSinkContext, type OutboxSinkModule, type Related, RelatedExpression, type RelatedOptions, type RelatedSpec, type Relation, type RelationMap, type RelationType, type Relations, blob, createRelated, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, relationOf, relationsOf, setTenantIdResolver, table, text, type, uniqueIndex };
23
+ export { type Action, type ActionConfig, type ActionContext, type ActionDescription, type AnyRelated, type AnySQLiteColumn, type AnySchema, type DatabaseConfig, type DatabaseDefinition, type DrizzleToKysely, type InferArgs, type Kysely, type Outbox, type OutboxEnvelope, type OutboxMessage, type OutboxSink, type OutboxSinkContext, type OutboxSinkModule, type Related, RelatedExpression, type RelatedOptions, type RelatedSpec, type RelatedWhere, type Relation, type RelationMap, type RelationType, type Relations, blob, createRelated, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, relationOf, relationsOf, setTenantIdResolver, table, text, type, uniqueIndex };
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-CULpd87Z.js";
1
+ import { a as createRelated, h as relationsOf, i as RelatedExpression, m as relationOf, n as defineDatabase } from "./defineDatabase-Cb5sMNg0.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-CULpd87Z.js";
1
+ import { l as SchemaPlugin, o as createRelatedPlugins, s as DateSerializePlugin, u as createDrizzlePlugins } from "./defineDatabase-Cb5sMNg0.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-RFLfeZGw.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-CCIE4_Le.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";
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-RFLfeZGw.js";
2
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 +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 parseRenameSpec, _ as renamesFromStatements, s as snapshotsEqual, v as unusedRenames } from "../snapshot-CCIE4_Le.js";
@@ -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
package/dist/registry.js CHANGED
@@ -107,38 +107,61 @@ function cachedArgsSchema(key, make) {
107
107
  if (!schema) argsSchemas.set(key, schema = make());
108
108
  return schema;
109
109
  }
110
- const pending = /* @__PURE__ */ new WeakMap();
110
+ const BATCH_SCOPES = Symbol.for("durable-db.batchScopes");
111
+ const batchScopes = globalThis[BATCH_SCOPES] ??= new AsyncLocalStorage();
111
112
  /**
112
- * Call an action on the Durable Object `instanceKey` of `namespace`. Calls to
113
- * the same object started before the code waits on I/O — `Promise.all([a(),
114
- * b()])` however deep in middleware, sibling server components awaiting at
115
- * once — travel in ONE RPC
116
- * (`rpcBatch`) and run there one after another, in the order they were made,
117
- * each result or error to its own caller; a lone call is a plain `rpc`, as
118
- * before. Results are plain values: the RPC's top-level `Symbol.dispose` is
119
- * dropped (React Server Components refuse symbol-keyed props).
113
+ * Runs `fn` as one invocation: the action calls it starts on the same Durable
114
+ * Object before it waits on I/O travel in ONE RPC. Wrap what the platform
115
+ * invokes — a worker's `fetch`, `queue` and `scheduled` handlers:
116
+ *
117
+ * export default { fetch: (request, env, ctx) => batchScope(() => app.fetch(request, env, ctx)) }
118
+ *
119
+ * Outside a scope every call is its own RPC: batching is only safe among the
120
+ * calls of one invocation, and nothing else tells them apart.
121
+ */
122
+ function batchScope(fn) {
123
+ return batchScopes.run({ pending: /* @__PURE__ */ new WeakMap() }, fn);
124
+ }
125
+ /**
126
+ * Call an action on the Durable Object `instanceKey` of `namespace`. Inside a
127
+ * `batchScope()`, calls to the same object started before the code waits on
128
+ * I/O — `Promise.all([a(), b()])` however deep in middleware, sibling server
129
+ * components awaiting at once — travel in ONE RPC (`rpcBatch`) and run there
130
+ * one after another, in the order they were made, each result or error to its
131
+ * own caller; a lone call, and every call outside a scope, is a plain `rpc`.
132
+ * Results are plain values: the RPC's top-level `Symbol.dispose` is dropped
133
+ * (React Server Components refuse symbol-keyed props).
120
134
  */
121
135
  function batchedRpc(namespace, instanceKey, action, args) {
136
+ const scope = batchScopes.getStore();
122
137
  return new Promise((resolve, reject) => {
123
- let byKey = pending.get(namespace);
124
- if (!byKey) pending.set(namespace, byKey = /* @__PURE__ */ new Map());
138
+ const call = {
139
+ action,
140
+ args,
141
+ resolve,
142
+ reject
143
+ };
144
+ if (!scope) {
145
+ sendCalls(namespace, instanceKey, [call]);
146
+ return;
147
+ }
148
+ let byKey = scope.pending.get(namespace);
149
+ if (!byKey) scope.pending.set(namespace, byKey = /* @__PURE__ */ new Map());
125
150
  let calls = byKey.get(instanceKey);
126
151
  if (!calls) {
127
152
  byKey.set(instanceKey, calls = []);
128
153
  const queued = byKey;
129
154
  setTimeout(() => flushCalls(namespace, instanceKey, queued), 0);
130
155
  }
131
- calls.push({
132
- action,
133
- args,
134
- resolve,
135
- reject
136
- });
156
+ calls.push(call);
137
157
  });
138
158
  }
139
159
  function flushCalls(namespace, instanceKey, byKey) {
140
160
  const calls = byKey.get(instanceKey) ?? [];
141
161
  byKey.delete(instanceKey);
162
+ sendCalls(namespace, instanceKey, calls);
163
+ }
164
+ function sendCalls(namespace, instanceKey, calls) {
142
165
  if (calls.length === 0) return;
143
166
  let stub;
144
167
  try {
@@ -168,4 +191,4 @@ function flushCalls(namespace, instanceKey, byKey) {
168
191
  });
169
192
  }
170
193
  //#endregion
171
- export { batchedRpc, cachedArgsSchema, callAction, getAction, getDoContext, registerAction, registerSharedAction, runWithDoContext, actionArgsType as type };
194
+ export { batchScope, batchedRpc, cachedArgsSchema, callAction, getAction, getDoContext, registerAction, registerSharedAction, runWithDoContext, actionArgsType as type };
@@ -294,6 +294,8 @@ function renamesFromStatements(statements) {
294
294
  }
295
295
  //#endregion
296
296
  //#region src/migrations/risks.ts
297
+ /** What a foreign key references, as one string: the same key before and after is no change. */
298
+ const referenceOf = (key) => `${key.columnsFrom.join(",")}->${key.tableTo}(${key.columnsTo.join(",")})`;
297
299
  /** The remedy `db generate` prints when it refuses a NOT NULL column without a default. */
298
300
  const NOT_NULL_WITHOUT_DEFAULT_HINT = "fails on every table that has rows: add .default(...) or add it nullable and backfill";
299
301
  /**
@@ -343,6 +345,18 @@ function analyzeMigrationRisks(prevSnapshot, curSnapshot, renames = []) {
343
345
  message: `${name}.${column} becomes NOT NULL — the migration fails on a database where a row holds NULL there: backfill it first`
344
346
  });
345
347
  }
348
+ const had = new Set(Object.values(table.foreignKeys ?? {}).map(referenceOf));
349
+ for (const key of Object.values(after.foreignKeys ?? {})) {
350
+ if (had.has(referenceOf(key))) continue;
351
+ const from = key.columnsFrom.join(", ");
352
+ risks.push({
353
+ kind: "add-foreign-key",
354
+ severity: "warning",
355
+ table: name,
356
+ ...key.columnsFrom.length === 1 ? { column: key.columnsFrom[0] } : {},
357
+ message: `${name}.${from} now references ${key.tableTo}.${key.columnsTo.join(", ")} — the migration fails on a database where a row of ${name} references a row of ${key.tableTo} that is not there, and that database answers nothing until it passes: remove or repair those rows in a migration before this one`
358
+ });
359
+ }
346
360
  }
347
361
  return risks;
348
362
  }
@@ -88,7 +88,7 @@ declare function renamesFromStatements(statements: string[]): RenameAnswer[];
88
88
  //#endregion
89
89
  //#region src/migrations/risks.d.ts
90
90
  type Snapshot$1 = DrizzleSQLiteSnapshotJSON;
91
- type MigrationRiskKind = 'add-not-null-without-default' | 'set-not-null' | 'drop-column' | 'drop-table';
91
+ type MigrationRiskKind = 'add-not-null-without-default' | 'set-not-null' | 'add-foreign-key' | 'drop-column' | 'drop-table';
92
92
  interface MigrationRisk {
93
93
  kind: MigrationRiskKind;
94
94
  /** `error`: fails on every table that has rows. `warning`: loses data, or may fail. */
@@ -5,6 +5,7 @@ import * as crypto from "node:crypto";
5
5
  //#region src/cli/state.ts
6
6
  var state_exports = /* @__PURE__ */ __exportAll({
7
7
  DEV_SERVER_LOCK_FILE: () => DEV_SERVER_LOCK_FILE,
8
+ SCHEMA_TEMP_PREFIX: () => SCHEMA_TEMP_PREFIX,
8
9
  clearDatabaseDevState: () => clearDatabaseDevState,
9
10
  clearDevMigrations: () => clearDevMigrations,
10
11
  createEmptyDevState: () => createEmptyDevState,
@@ -284,15 +285,16 @@ function parseSqlMigration(content) {
284
285
  return chunk.split("\n").filter((line) => !line.trim().startsWith("--")).join("\n").split(/;(?:\s*\n|\s*$)/).map((s) => s.trim()).filter((s) => s.length > 0);
285
286
  }).filter((chunk) => chunk.length > 0);
286
287
  }
287
- var CACHE_DIR_NAME, STATE_FILE_NAME, DEV_SERVER_LOCK_FILE, DEV_MIGRATIONS_DIR, DEV_SNAPSHOT_FILE, BREAKPOINT_MARKER;
288
+ var CACHE_DIR_NAME, STATE_FILE_NAME, DEV_SERVER_LOCK_FILE, SCHEMA_TEMP_PREFIX, DEV_MIGRATIONS_DIR, DEV_SNAPSHOT_FILE, BREAKPOINT_MARKER;
288
289
  var init_state = __esmMin((() => {
289
290
  init_debug();
290
291
  CACHE_DIR_NAME = ".cache/durable-db";
291
292
  STATE_FILE_NAME = "state.json";
292
293
  DEV_SERVER_LOCK_FILE = "dev-server.json";
294
+ SCHEMA_TEMP_PREFIX = "_schema_temp_";
293
295
  DEV_MIGRATIONS_DIR = "migrations";
294
296
  DEV_SNAPSHOT_FILE = "_snapshot.json";
295
297
  BREAKPOINT_MARKER = /^-->\s*breakpoint\s*$/im;
296
298
  }));
297
299
  //#endregion
298
- export { saveDevState as _, generateEpoch as a, getDevEpoch as c, init_state as d, loadDevMigrations as f, saveDevMigration as g, runningDevServer as h, forgetDatabaseDevState as i, getDevPaths as l, removeDevServerLock as m, clearDatabaseDevState as n, getDatabaseEpoch as o, loadDevState as p, clearDevMigrations as r, getDatabaseEpochs as s, DEV_SERVER_LOCK_FILE as t, getInstanceKey as u, state_exports as v, writeDevServerLock as y };
300
+ export { saveDevMigration as _, forgetDatabaseDevState as a, writeDevServerLock as b, getDatabaseEpochs as c, getInstanceKey as d, init_state as f, runningDevServer as g, removeDevServerLock as h, clearDevMigrations as i, getDevEpoch as l, loadDevState as m, SCHEMA_TEMP_PREFIX as n, generateEpoch as o, loadDevMigrations as p, clearDatabaseDevState as r, getDatabaseEpoch as s, DEV_SERVER_LOCK_FILE as t, getDevPaths as u, saveDevState as v, state_exports as y };
@@ -1,9 +1,9 @@
1
- import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-CULpd87Z.js";
1
+ import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-Cb5sMNg0.js";
2
2
  import { r as type } from "../type-CUgZsZp3.js";
3
3
  import "../actionArgs-DP2tQrlf.js";
4
4
  import { setTenantIdResolver } from "../context/index.js";
5
- import { c as tenantOfInstanceKey, i as createActionOutbox, t as createKyselyFromSql } from "../kysely-DCQRqT62.js";
6
- import { i as generateSnapshotFromSchema, n as createEmptySnapshot, r as generateMigrationStatements } from "../snapshot-D_z95s6E.js";
5
+ import { c as tenantOfInstanceKey, i as createActionOutbox, t as createKyselyFromSql } from "../kysely-q97dtmaQ.js";
6
+ import { i as generateSnapshotFromSchema, n as createEmptySnapshot, r as generateMigrationStatements } from "../snapshot-CCIE4_Le.js";
7
7
  import { createRequire } from "node:module";
8
8
  //#region src/testing/index.ts
9
9
  const loadSqlite = () => createRequire(import.meta.url)("node:sqlite");
@@ -1,5 +1,5 @@
1
1
  import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
2
- import "../index-BQ1hHyrq.js";
2
+ import "../index-CUkSkt7G.js";
3
3
  import { Plugin } from "vite";
4
4
  import "@babel/types";
5
5
  //#region src/vite/modules/wrangler.d.ts
@@ -1,5 +1,5 @@
1
1
  import { i as init_debug, r as debugVite } from "../debug-Cz8KzMft.js";
2
- import { _ as saveDevState, d as init_state, l as getDevPaths, m as removeDevServerLock, p as loadDevState, s as getDatabaseEpochs, y as writeDevServerLock } from "../state-DGYycIoJ.js";
2
+ import { b as writeDevServerLock, c as getDatabaseEpochs, f as init_state, h as removeDevServerLock, m as loadDevState, u as getDevPaths, v as saveDevState } from "../state-UT6GH0JD.js";
3
3
  import { loadMigrationFiles } from "../migrations/generator.js";
4
4
  import { a as databaseSources, c as readFile, i as toPascalCase, n as declaresSchema, o as discoverActionFiles, r as parseDatabaseFile, s as discoverDatabaseFiles, t as BABEL_PARSER_PLUGINS } from "../parser-mUnAtllk.js";
5
5
  import * as fs from "node:fs";
@@ -1548,7 +1548,7 @@ var PluginState = class {
1548
1548
  const isDev = this.config.command === "serve";
1549
1549
  db.migrations = loadMigrationFiles(migrationsDir);
1550
1550
  if (isDev) try {
1551
- const { loadDevMigrations } = await import("../state-DGYycIoJ.js").then((n) => (n.d(), n.v));
1551
+ const { loadDevMigrations } = await import("../state-UT6GH0JD.js").then((n) => (n.f(), n.y));
1552
1552
  const devMigrations = loadDevMigrations(this.projectRoot, db.name);
1553
1553
  for (const [name, chunks] of devMigrations) db.migrations.set(`_dev_${name}`, chunks);
1554
1554
  if (devMigrations.size > 0) debugVite("Loaded %d dev migration(s) for %s", devMigrations.size, db.name);
@@ -1658,6 +1658,7 @@ function durableDb(options = {}) {
1658
1658
  const cacheDirName = path$1.basename(devPaths.cacheDir);
1659
1659
  const onDevStateChange = (_event, filename) => {
1660
1660
  if (typeof filename === "string" && (path$1.basename(filename) === "dev-server.json" || filename === cacheDirName)) return;
1661
+ if (typeof filename === "string" && path$1.basename(filename).startsWith("_schema_temp_")) return;
1661
1662
  if (state.isWithinSelfDevStateWriteWindow()) {
1662
1663
  debugVite("Ignoring dev cache event caused by the plugin itself");
1663
1664
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "durable-db",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/eagerpatch/durable-db.git"