durable-db 0.10.0 → 0.11.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
@@ -1224,6 +1224,32 @@ related('customers', 'invoices', {
1224
1224
  });
1225
1225
  ```
1226
1226
 
1227
+ **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:
1228
+
1229
+ ```ts
1230
+ related('invoices', 'invoiceLines', {
1231
+ columns: ['description'],
1232
+ where: (eb) => eb('quantity', '>', 0),
1233
+ });
1234
+
1235
+ // Whatever Kysely builds of the table's columns…
1236
+ related('invoices', 'invoiceLines', {
1237
+ columns: ['description'],
1238
+ where: (eb) => eb.or([eb('delivered', '=', false), eb('deliveredAt', '>', since)]),
1239
+ });
1240
+
1241
+ // …and another table in a subquery, which names the related row after its table.
1242
+ related('customers', 'invoices', {
1243
+ columns: ['number'],
1244
+ where: (eb) =>
1245
+ eb.exists(
1246
+ eb.selectFrom('invoiceLines').select('invoiceLines.id').whereRef('invoiceLines.invoiceId', '=', 'invoices.id'),
1247
+ ),
1248
+ });
1249
+ ```
1250
+
1251
+ 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.
1252
+
1227
1253
  **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
1254
 
1229
1255
  ```ts
@@ -1251,7 +1277,7 @@ What it does not do yet:
1251
1277
  - 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
1278
  - Composite foreign keys (`foreignKey({ columns: [a, b] })`) are not relations.
1253
1279
  - `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.
1280
+ - A `where` compares a JSON column with what is stored (its text), like any `where`.
1255
1281
 
1256
1282
  ---
1257
1283
 
@@ -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-Bww_w_n5.js";
4
- import "../index-BQ1hHyrq.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";
@@ -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,8 +1,8 @@
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";
5
+ import { c as tenantOfInstanceKey, i as createActionOutbox, t as createKyselyFromSql } from "../kysely-q97dtmaQ.js";
6
6
  import { i as generateSnapshotFromSchema, n as createEmptySnapshot, r as generateMigrationStatements } from "../snapshot-D_z95s6E.js";
7
7
  import { createRequire } from "node:module";
8
8
  //#region src/testing/index.ts
@@ -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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "durable-db",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/eagerpatch/durable-db.git"