durable-db 0.9.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/README.md CHANGED
@@ -67,7 +67,11 @@ Column names are derived from JS property keys and auto-converted to snake_case
67
67
 
68
68
  **Date columns**: use `integer({ mode: 'timestamp' })` and pass `Date` values — they round-trip as `Date` objects automatically. Plain `text()` columns always round-trip verbatim: if you store an ISO string (`new Date().toISOString()`), you get the exact same string back, never a `Date`.
69
69
 
70
- > ⚠️ All tables referenced in `defineDatabase({ schema })` must be **exported from the schema module** and imported into the database file. Tables defined inline in the database file (or not exported) cannot be loaded by the migration CLI — `db push`/`db generate` will fail with an explicit error rather than silently generating empty migrations.
70
+ **JSON columns**: `text({ mode: 'json' })` (or `blob({ mode: 'json' })`) takes the value itself — an object, an array, a string, a number — and gives it back parsed. Don't `JSON.stringify()` it yourself: a string is stored as a JSON string and comes back as that string. Dates inside it are ISO strings, as in any JSON. That holds for values written with `values()` / `set()` and for columns a query reads by name (`select`, `selectAll`, `returning`, through an alias or a join). An expression — `INSERT … SELECT`, `excluded.meta` in an upsert, a `sql` fragment, a `where` against the column — works on the stored text, and its encoding is yours.
71
+
72
+ **Blob columns**: pass an `ArrayBuffer` or a typed array (`Uint8Array`). A Durable Object answers a blob as an `ArrayBuffer`.
73
+
74
+ > ⚠️ `schema` is read at build time. All tables referenced in `defineDatabase({ schema })` must be **exported from the schema module** and imported into the database file — listed one by one (`schema: { users }`), or as one object the schema module exports (see below). Tables defined inline in the database file (or not exported) cannot be loaded by the migration CLI — `db push`/`db generate` will fail with an explicit error rather than silently generating empty migrations. Anything else passed as `schema` (a function call, a namespace import, a value built at runtime) is not read: the build warns and the database gets no schema.
71
75
 
72
76
  ### 3. Define your database
73
77
 
@@ -81,6 +85,20 @@ export const { action } = defineDatabase({
81
85
  });
82
86
  ```
83
87
 
88
+ The schema module can also hand its tables over as one object — the way to go when something else wants the very same object (a test database, a library that reads the relations):
89
+
90
+ ```ts
91
+ // src/databases/schema.ts
92
+ export const schema = { users, posts };
93
+
94
+ // src/databases/main.ts
95
+ import { schema } from './schema';
96
+
97
+ export const { action } = defineDatabase({ schema });
98
+ ```
99
+
100
+ The keys of that object are the table names actions use (`selectFrom('users')`), exactly as in the listed form; the CLI and the generated Durable Object class read the tables from that export. `as const` and `satisfies` are seen through, a default export works (`import schema from './schema'`), and so does a `const` of listed tables in the database file itself.
101
+
84
102
  ### 4. Write actions
85
103
 
86
104
  ```ts
@@ -187,7 +205,7 @@ The destructured `action` function is your factory for creating database actions
187
205
 
188
206
  | Option | Type | Default | Description |
189
207
  |--------|------|---------|-------------|
190
- | `schema` | `object` | `{}` | Drizzle schema tables |
208
+ | `schema` | `object` | `{}` | Drizzle schema tables: listed (`{ users, posts }`), or one object the schema module exports (`import { schema } from './schema'`). Read at build time |
191
209
  | `instance` | `'per-tenant' \| 'global'` | `'per-tenant'` | Instance strategy (see [Instance Strategies](#instance-strategies)) |
192
210
  | `transport` | `'rpc' \| 'websocket'` | `'rpc'` | Transport for action stubs. WebSocket uses Cloudflare's 20:1 message billing ratio for cheaper high-volume calls |
193
211
  | `browsable` | `boolean \| 'development'` | `false` | Enable Outerbase SQL browsing (see [Outerbase Studio](#outerbase-studio-integration)) |
@@ -1164,11 +1182,15 @@ export const invoiceLines = table(
1164
1182
  },
1165
1183
  (t) => [index('invoice_lines_invoice').on(t.invoiceId)],
1166
1184
  );
1185
+
1186
+ export const schema = { customers, invoices, invoiceLines };
1167
1187
  ```
1168
1188
 
1169
1189
  `defineDatabase()` hands out `related` next to `action`. It is a selection: put it in a `select()` (or a `returning()`) and the row gets the related rows under the relation's name, typed.
1170
1190
 
1171
1191
  ```ts
1192
+ import { schema } from './schema';
1193
+
1172
1194
  export const { action, related, relations } = defineDatabase({ schema });
1173
1195
 
1174
1196
  export const listInvoices = action({
@@ -1202,10 +1224,28 @@ related('customers', 'invoices', {
1202
1224
  });
1203
1225
  ```
1204
1226
 
1205
- Each relation is a correlated subquery that SQLite answers as JSON (`json_object`, `json_group_array`); dates and booleans inside come back as the columns say, like in any row. Index the foreign key column a `many` is read through (`invoice_lines_invoice` above): without one SQLite scans the child table once per parent row — 200 invoices over 10 000 lines took 80 ms without it and 1.4 ms with it.
1227
+ **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
+
1229
+ ```ts
1230
+ related('invoices', 'customer', ['name']).as('buyer');
1231
+ // { buyer: { name: string } }
1232
+
1233
+ related('customers', 'invoices', { columns: ['number'], orderBy: { number: 'desc' }, limit: 1 }).as('latest');
1234
+ ```
1235
+
1236
+ Each relation is a correlated subquery that SQLite answers as JSON (`json_object`, `json_group_array`); dates, booleans and JSON columns inside come back as the columns say, like in any row. A blob column cannot be read through a relation (JSON holds none): read it in a query of its own. Index the foreign key column a `many` is read through (`invoice_lines_invoice` above): without one SQLite scans the child table once per parent row — 200 invoices over 10 000 lines took 80 ms without it and 1.4 ms with it.
1206
1237
 
1207
1238
  **The registry.** `relations` (and `relationsOf(schema)` from `durable-db`) is the same information at runtime — `relations.invoices.customer` is `{ kind: 'one', name: 'customer', table: 'invoices', target: 'customers', local: 'customerId', foreign: 'id', nullable: false }` (tables as schema keys, columns as their properties) — for a library that maps a schema to an API. `Relations<typeof schema>` is its type.
1208
1239
 
1240
+ **Outside `defineDatabase()`.** `createRelated(schema)` (from `durable-db`) is the same builder for code that is handed a schema and not the database file — that library, again. For a schema whose tables TypeScript knows it is typed like `related`; for one known only at runtime (`AnySchema`) it takes strings (`AnyRelated`) and checks them when called: the table, the relation, its columns, the order. Give it the schema object the database is defined with — a nested relation built for another object is refused. `RelatedSpec` is what a `RelatedExpression` is made from.
1241
+
1242
+ ```ts
1243
+ import { createRelated } from 'durable-db';
1244
+
1245
+ const related = createRelated(schema);
1246
+ related('invoices', 'customer', ['name']);
1247
+ ```
1248
+
1209
1249
  What it does not do yet:
1210
1250
 
1211
1251
  - 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.
@@ -1343,9 +1383,11 @@ The library includes plugins for transparent data mapping between JavaScript and
1343
1383
 
1344
1384
  - **DrizzleDefaultsPlugin**: Auto-populates columns with Drizzle's `$defaultFn()` on INSERT (e.g. auto-generated IDs, `createdAt` timestamps) and `$onUpdateFn()` on UPDATE (e.g. `updatedAt` timestamps). Columns that are explicitly provided in the query are not overridden.
1345
1385
  - **SchemaPlugin**: Schema-aware extension of Kysely's `CamelCasePlugin`. Maps camelCase JS property names to snake_case SQL names for both tables and columns using Drizzle schema metadata. Falls back to standard CamelCasePlugin behavior for names not in the schema.
1346
- - **DateSerializePlugin**: Converts `Date` objects to `YYYY-MM-DD HH:MM:SS` strings for SQLite storage, and parses them back into `Date` objects on read. The read path is deliberately conservative: only values in exactly the format the write path produces (also what SQLite's `CURRENT_TIMESTAMP` emits) are converted, and — when constructed with a schema — only for columns Drizzle declares as date-typed (e.g. `integer({ mode: 'timestamp' })`). User-stored strings in `text()` columns (ISO strings with a `T` separator, timezone, or milliseconds) round-trip verbatim.
1386
+ - **DateSerializePlugin**: Converts `Date` objects to `YYYY-MM-DD HH:MM:SS` strings for SQLite storage, and parses them back into `Date` objects on read. The read path is deliberately conservative: only values in exactly the format the write path produces (also what SQLite's `CURRENT_TIMESTAMP` emits) are converted, and — when constructed with a schema — only for columns Drizzle declares as date-typed (e.g. `integer({ mode: 'timestamp' })`). User-stored strings in `text()` columns (ISO strings with a `T` separator, timezone, or milliseconds) round-trip verbatim. Binary values (`ArrayBuffer`, typed arrays) pass through untouched and are bound as blobs.
1387
+ - **BooleanDeserializePlugin**: answers `integer({ mode: 'boolean' })` columns as `true`/`false`.
1388
+ - **The JSON plugins** (`createJsonPlugins(schema)`, only for a schema with a JSON-mode column): one serialises the values an INSERT or UPDATE writes to a `text({ mode: 'json' })` / `blob({ mode: 'json' })` column, the other parses those columns in the rows a query answers — resolved per selection (table, alias, `selectAll`, joins, `returning`), by column name across the schema for a raw `sql` query. Text that is no JSON is answered as it is.
1347
1389
 
1348
- All three plugins are automatically configured when using `createDrizzlePlugins(schema)`.
1390
+ All of them are configured by `createDrizzlePlugins(schema)`.
1349
1391
 
1350
1392
  ---
1351
1393
 
package/dist/cli/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { n as registerDbCommands } from "../cli-CVS0b2im.js";
2
+ import { n as registerDbCommands } from "../cli-5KmSf8wx.js";
3
3
  import { Command } from "commander";
4
4
  //#region src/cli/bin.ts
5
5
  const program = new Command();
@@ -1,8 +1,10 @@
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-BvFOZVkv.js";
4
- import "../index-DoxI1p4-.js";
3
+ import { l as DatabaseInfo } from "../defineDatabase-Bww_w_n5.js";
4
+ import "../index-BQ1hHyrq.js";
5
5
  import { Command } from "commander";
6
+ import "vite";
7
+ import "@babel/types";
6
8
  //#region src/cli/command.d.ts
7
9
  /**
8
10
  * Register all database subcommands (push, generate, status, reset,
@@ -160,6 +162,12 @@ export declare function selectDatabases(opts: DiscoverOptions): DatabaseInfo[];
160
162
  * Returns parsed DatabaseInfo[] with migrationsDir already set.
161
163
  */
162
164
  export declare function discoverDatabases(opts: DiscoverOptions): DatabaseInfo[];
165
+ /**
166
+ * The tables of a database's schema, built from the schema module at
167
+ * `schemaPath`: the tables `defineDatabase({ schema: { … } })` lists, or the
168
+ * const the module exports as the whole schema (`db.schemaExport`).
169
+ */
170
+ export declare function loadSchemaTables(db: DatabaseInfo, schemaPath: string): Promise<Record<string, unknown>>;
163
171
  /**
164
172
  * Load and validate schema for a database.
165
173
  *
@@ -480,4 +488,11 @@ interface ValidateResult {
480
488
  */
481
489
  export declare function validate(ctx?: ValidateContext): Promise<ValidateResult[]>;
482
490
  //#endregion
491
+ //#region src/vite/modules/parser.d.ts
492
+ /**
493
+ * Whether a database was given a schema discovery could read: tables listed
494
+ * in the call, or a const the schema module exports.
495
+ */
496
+ export declare function declaresSchema(db: Pick<DatabaseInfo, 'schemaExport' | 'schemaTableNames'>): boolean;
497
+ //#endregion
483
498
  export { type DatabaseDevState, type DatabaseDiff, type DatabaseSource, type DatabaseStatus, type DbCommandDefaults, type DevPaths, type DevServerLock, type DevState, type DiffResult, type DiscoverOptions, type GenerateContext, type GenerateOptions, type GenerateResult, type MigrationRisk, type PushContext, type PushResult, type RenameAnswer, type RenameResolutionOptions, type ResetContext, type ResetOptions, type ResetResult, type SchemaAmbiguity, SchemaRenameRequiredError, type StatusContext, type StatusResult, type ValidateContext, type ValidateError, type ValidateResult, parseRenameSpec };
package/dist/cli/index.js CHANGED
@@ -1,5 +1,6 @@
1
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
2
  import { g as parseRenameSpec, u as SchemaRenameRequiredError } from "../snapshot-D_z95s6E.js";
3
- import { _ as discoverDatabases, a as reset, b as selectDatabases, 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, y as reportCliError } from "../cli-CVS0b2im.js";
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
5
  init_state();
5
- export { DevServerRunningError, SchemaRenameRequiredError, UnknownDatabaseError, UnsafeMigrationError, createDbCommand, diffDatabases, diffSchema, discoverDatabases, formatStatus, generate, generateEpoch, generateOne, getDatabaseEpoch, getDatabaseEpochs, getDevEpoch, getDevPaths, getInstanceKey, loadDevMigrations, loadDevState, loadSchema, parseRenameSpec, push, pushOne, registerDbCommands, reportCliError, reset, resetAndPush, runningDevServer, saveDevState, selectDatabases, status, validate };
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 };
@@ -2,7 +2,7 @@ import { i as init_debug, o as __exportAll, t as debugCli } from "./debug-Cz8KzM
2
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
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";
4
4
  import { buildAndLoadSchema, generateCreateTableSQL, generateMigrationName, loadMigrationFiles, loadSnapshot, saveSnapshot } from "./migrations/generator.js";
5
- import { c as resolveImportPath, l as loadViteAliases, n as parseDatabaseFile, o as discoverDatabaseFiles, s as readFile } from "./parser-DyepmXzE.js";
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";
7
7
  import * as path$1 from "node:path";
8
8
  import * as crypto from "node:crypto";
@@ -70,6 +70,28 @@ function discoverDatabases(opts) {
70
70
  }
71
71
  return databases;
72
72
  }
73
+ /** What to read from a database's schema module: the const that is the schema, or each listed table. */
74
+ function schemaExportNames(db) {
75
+ return db.schemaExport ? [db.schemaExport] : db.schemaTableNames;
76
+ }
77
+ /** The tables in what the schema module answered for `schemaExportNames(db)`. */
78
+ function schemaTablesFrom(db, loaded, schemaPath) {
79
+ if (!db.schemaExport) return loaded;
80
+ const schema = loaded[db.schemaExport];
81
+ if (typeof schema !== "object" || schema === null || Array.isArray(schema)) {
82
+ const what = db.schemaExport === "default" ? "the default export" : `the export '${db.schemaExport}'`;
83
+ throw new Error(`[db] Database '${db.name}': ${what} of schema module ${schemaPath} is not an object of tables. defineDatabase({ schema }) is given that export, so it must be the tables by name — e.g. export const schema = { users, posts }.`);
84
+ }
85
+ return { ...schema };
86
+ }
87
+ /**
88
+ * The tables of a database's schema, built from the schema module at
89
+ * `schemaPath`: the tables `defineDatabase({ schema: { … } })` lists, or the
90
+ * const the module exports as the whole schema (`db.schemaExport`).
91
+ */
92
+ async function loadSchemaTables(db, schemaPath) {
93
+ return schemaTablesFrom(db, await buildAndLoadSchema(schemaPath, schemaExportNames(db)), schemaPath);
94
+ }
73
95
  /**
74
96
  * Load and validate schema for a database.
75
97
  *
@@ -85,7 +107,7 @@ function discoverDatabases(opts) {
85
107
  * imports only.
86
108
  */
87
109
  async function loadSchema(db, projectRoot) {
88
- if (db.schemaTableNames.length === 0) {
110
+ if (!declaresSchema(db)) {
89
111
  debugCli("Skipping %s: no schema defined", db.name);
90
112
  return null;
91
113
  }
@@ -93,14 +115,22 @@ async function loadSchema(db, projectRoot) {
93
115
  const aliases = projectRoot ? await loadViteAliases(projectRoot) : void 0;
94
116
  const schemaPath = resolveImportPath(db.filePath, db.schemaImport, aliases);
95
117
  if (!schemaPath) throw new Error(`[db] Database '${db.name}': could not resolve schema import '${db.schemaImport}' from ${db.filePath}.` + (db.schemaImport.startsWith(".") ? "" : ` '${db.schemaImport}' looks like an alias — ensure it's defined in the project's Vite config (resolve.alias / tsconfig paths wired into Vite).`));
96
- let schema;
118
+ let loaded;
97
119
  try {
98
- schema = await buildAndLoadSchema(schemaPath, db.schemaTableNames);
120
+ loaded = await buildAndLoadSchema(schemaPath, schemaExportNames(db));
99
121
  } catch (error) {
100
122
  const message = error instanceof Error ? error.message : String(error);
101
123
  debugCli("Failed to load schema for %s: %O", db.name, error);
102
124
  throw new Error(`[db] Could not build schema for database '${db.name}' (${schemaPath}): ${message}`, { cause: error });
103
125
  }
126
+ const schema = schemaTablesFrom(db, loaded, schemaPath);
127
+ if (db.schemaExport) {
128
+ if (Object.keys(schema).length === 0) {
129
+ debugCli("Skipping %s: its schema (%s) has no tables", db.name, db.schemaExport);
130
+ return null;
131
+ }
132
+ return schema;
133
+ }
104
134
  const missing = db.schemaTableNames.filter((name) => !(name in schema));
105
135
  if (missing.length > 0) throw new Error(`[db] Database '${db.name}': schema module ${schemaPath} does not export: ${missing.join(", ")}. Every table referenced in defineDatabase({ schema }) must be exported from the same schema module.`);
106
136
  return schema;
@@ -862,11 +892,11 @@ async function validateDatabase(db, opts) {
862
892
  }
863
893
  }
864
894
  }
865
- if (db.schemaImport && db.schemaTableNames.length > 0) {
895
+ if (db.schemaImport && declaresSchema(db)) {
866
896
  const aliases = await loadViteAliases(projectRoot);
867
897
  const schemaPath = resolveImportPath(db.filePath, db.schemaImport, aliases);
868
898
  if (schemaPath) try {
869
- const schema = await buildAndLoadSchema(schemaPath, db.schemaTableNames);
899
+ const schema = await loadSchemaTables(db, schemaPath);
870
900
  if (Object.keys(schema).length > 0) {
871
901
  result.pendingWarnings = await pendingChangeWarnings(db.migrationsDir, schema);
872
902
  const createStatements = await generateCreateTableSQL(schema);
@@ -1058,4 +1088,4 @@ function createDbCommand(defaults = {}) {
1058
1088
  //#region src/cli/index.ts
1059
1089
  init_state();
1060
1090
  //#endregion
1061
- export { discoverDatabases as _, reset as a, selectDatabases as b, status as c, generateOne as d, push as f, diffSchema as g, diffDatabases as h, DevServerRunningError as i, UnsafeMigrationError as l, UnknownDatabaseError as m, registerDbCommands as n, resetAndPush as o, pushOne as p, validate as r, formatStatus as s, createDbCommand as t, generate as u, loadSchema as v, reportCliError as y };
1091
+ export { discoverDatabases as _, reset as a, reportCliError as b, status as c, generateOne as d, push as f, diffSchema as g, diffDatabases as h, DevServerRunningError as i, UnsafeMigrationError as l, UnknownDatabaseError as m, registerDbCommands as n, resetAndPush as o, pushOne as p, validate as r, formatStatus as s, createDbCommand as t, generate as u, loadSchema as v, selectDatabases as x, loadSchemaTables as y };
@@ -1,5 +1,5 @@
1
1
  import { l as type } from "../index-bUUlOWfP.js";
2
- import { _ as RelationMap, a as ActionInfo, b as relationOf, c as DatabaseDefinition, d as InferArgs, f as ParsedDatabaseFile, g as Relation, h as RelatedOptions, i as ActionContext, l as DatabaseInfo, m as RelatedExpression, n as Action, o as ArgsSchema, p as Related, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as RelationType, x as relationsOf, y as Relations } from "../defineDatabase-BvFOZVkv.js";
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";
3
3
  import { a as OutboxSinkContext, c as queueOutboxSink, i as OutboxSink, l as tenantOfInstanceKey, n as OutboxEnvelope, o as OutboxSinkModule, r as OutboxMessage, s as outboxSink, t as Outbox } from "../outbox-D3Q9n7Rt.js";
4
- import { C as createKyselyFromSql, S as SqlExecutor, _ as MigrationAttemptInfo, a as QueryResult, b as SqliteDurableObject, c as DrizzleDefaultsPlugin, d as dateSerializers, f as DeleteClassMigration, g as Migration, h as removedDatabaseMessage, i as KyselyPlugin, l as SchemaPlugin, m as RemovedDatabaseError, n as CompiledQuery, o as studio, p as RemovedDatabaseDurableObject, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as createDrizzlePlugins, v as MigrationSchemaConflictError, x as CreateKyselyOptions, y as Migrations } from "../index-DoxI1p4-.js";
5
- export { type Action, type ActionConfig, type ActionContext, type ActionInfo, type ArgsSchema, CamelCasePlugin, type CompiledQuery, type CreateKyselyOptions, type DatabaseConfig, type DatabaseDefinition, type DatabaseInfo, DateSerializePlugin, type DeleteClassMigration, DrizzleDefaultsPlugin, type DrizzleToKysely, type InferArgs, type Kysely, type KyselyPlugin, type Migration, type MigrationAttemptInfo, MigrationSchemaConflictError, type Migrations, type Outbox, type OutboxEnvelope, type OutboxMessage, type OutboxSink, type OutboxSinkContext, type OutboxSinkModule, type ParsedDatabaseFile, type QueryResult, type Related, RelatedExpression, type RelatedOptions, type Relation, type RelationMap, type RelationType, type Relations, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, type SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, outboxSink, queueOutboxSink, relationOf, relationsOf, removedDatabaseMessage, studio, tenantOfInstanceKey, type };
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 };
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 { c as SchemaPlugin, d as relationOf, f as relationsOf, i as RelatedExpression, l as createDrizzlePlugins, n as defineDatabase, o as DateSerializePlugin, s as DrizzleDefaultsPlugin, u as dateSerializers } from "../defineDatabase-CaqKQagA.js";
2
+ 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";
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-D8JQ4v8n.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";
6
6
  import { CamelCasePlugin } from "kysely";
7
7
  import { DurableObject } from "cloudflare:workers";
8
8
  import { studio } from "@outerbase/browsable-durable-object";
@@ -967,4 +967,4 @@ var RemovedDatabaseDurableObject = class extends DurableObject {
967
967
  }
968
968
  };
969
969
  //#endregion
970
- export { CamelCasePlugin, DateSerializePlugin, DrizzleDefaultsPlugin, MigrationSchemaConflictError, RelatedExpression, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, outboxSink, queueOutboxSink, relationOf, relationsOf, 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 };
@@ -143,10 +143,21 @@ interface Related<S extends AnySchema> {
143
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
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
145
  }
146
- /** A relation to read, checked against the schema. Internal: what `related()` builds. */
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. */
147
156
  interface RelatedSpec {
148
157
  schema: AnySchema;
149
158
  relation: Relation;
159
+ /** The key it is answered under: the relation's name, or what `.as()` said. */
160
+ alias: string;
150
161
  columns: string[];
151
162
  with: RelatedSpec[];
152
163
  orderBy: [column: string, direction: 'asc' | 'desc'][];
@@ -155,15 +166,28 @@ interface RelatedSpec {
155
166
  /**
156
167
  * A relation as a selection: what `related()` returns. `table` is the table
157
168
  * it is a relation of (so `with` takes only the related table's own), `alias`
158
- * the relation's name — the key it is answered under.
169
+ * the key it is answered under — the relation's name, until `.as()` says
170
+ * another.
159
171
  */
160
172
  declare class RelatedExpression<TK extends string, A extends string, V> implements AliasedExpression<V, A> {
161
173
  readonly table: TK;
162
174
  readonly alias: A;
163
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>;
164
182
  get expression(): Expression<V>;
165
183
  toOperationNode(): AliasNode;
166
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>;
167
191
  //#endregion
168
192
  //#region src/db/types.d.ts
169
193
  /**
@@ -297,7 +321,13 @@ interface DatabaseInfo {
297
321
  migrationsDir: string;
298
322
  /** Schema import source (relative path) */
299
323
  schemaImport: string | null;
300
- /** Names of schema tables */
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) */
301
331
  schemaTableNames: string[];
302
332
  /** Whether the DO should expose a browsable SQL endpoint */
303
333
  browsable: boolean | 'development';
@@ -374,4 +404,4 @@ interface ParsedDatabaseFile {
374
404
  */
375
405
  declare function defineDatabase<TSchema extends Record<string, SQLiteTableWithColumns<any>>>(config: DatabaseConfig<TSchema>): DatabaseDefinition<TSchema>;
376
406
  //#endregion
377
- export { RelationMap as _, ActionInfo as a, relationOf as b, DatabaseDefinition as c, InferArgs as d, ParsedDatabaseFile as f, Relation as g, RelatedOptions as h, ActionContext as i, DatabaseInfo as l, RelatedExpression as m, Action as n, ArgsSchema as o, Related as p, ActionConfig as r, DatabaseConfig as s, defineDatabase as t, DrizzleToKysely as u, RelationType as v, relationsOf as x, Relations as y };
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 };
@@ -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, IdentifierNode, InsertQueryNode, PrimitiveValueListNode, TableNode, ValueListNode, ValueNode, ValuesNode, sql } from "kysely";
5
+ import { AliasNode, CamelCasePlugin, ColumnNode, ColumnUpdateNode, DeleteQueryNode, IdentifierNode, InsertQueryNode, PrimitiveValueListNode, ReferenceNode, SelectAllNode, SelectQueryNode, TableNode, UpdateQueryNode, ValueListNode, ValueNode, ValuesNode, 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();
@@ -142,11 +142,22 @@ var SchemaPlugin = class extends CamelCasePlugin {
142
142
  camelCase(str) {
143
143
  return this.sqlToJs.get(str) ?? super.camelCase(str);
144
144
  }
145
+ /**
146
+ * The key a result row has for an identifier a query writes as `name`: it
147
+ * is snake_cased on the way in and camelCased on the way out.
148
+ */
149
+ resultKey(name) {
150
+ return this.camelCase(this.snakeCase(name));
151
+ }
145
152
  };
146
153
  function getKyselyTableName(node) {
147
154
  if (node && TableNode.is(node)) return node.table.identifier.name;
148
155
  return null;
149
156
  }
157
+ /** A binary value: an ArrayBuffer or a view of one (a Uint8Array, a Buffer). */
158
+ function isBinary(value) {
159
+ return value instanceof ArrayBuffer || ArrayBuffer.isView(value);
160
+ }
150
161
  function getKyselyColumnName(node) {
151
162
  if (!node) return null;
152
163
  if (ColumnNode.is(node)) return node.column.name;
@@ -343,6 +354,7 @@ var DateSerializePlugin = class {
343
354
  transformNode(node) {
344
355
  if (node === null || node === void 0) return node;
345
356
  if (node instanceof Date) return dateSerializers.serialize(node);
357
+ if (isBinary(node)) return node;
346
358
  if (Array.isArray(node)) return node.map((item) => this.transformNode(item));
347
359
  if (typeof node === "object") {
348
360
  const result = {};
@@ -426,6 +438,326 @@ var BooleanDeserializePlugin = class {
426
438
  }
427
439
  };
428
440
  /**
441
+ * The JSON-mode columns of a schema, table by table. A table is found under
442
+ * its schema key and its SQL name; a column under its property name, its name
443
+ * and its snake_cased property name, like collectDateColumnNames — so a
444
+ * lookup works on either side of the CamelCasePlugin.
445
+ */
446
+ function collectJsonTables(schema) {
447
+ const tables = /* @__PURE__ */ new Map();
448
+ for (const [schemaKey, table] of Object.entries(schema)) {
449
+ const facts = {
450
+ json: /* @__PURE__ */ new Map(),
451
+ plain: /* @__PURE__ */ new Set()
452
+ };
453
+ for (const [propertyName, column] of Object.entries(getTableColumns(table))) {
454
+ const names = [
455
+ propertyName,
456
+ column.name,
457
+ toSnakeCase(propertyName)
458
+ ];
459
+ if (column.dataType === "json") {
460
+ const storage = column.getSQLType() === "blob" ? "blob" : "text";
461
+ for (const name of names) facts.json.set(name, storage);
462
+ } else for (const name of names) facts.plain.add(name);
463
+ }
464
+ const tableName = getTableName(table);
465
+ for (const name of [
466
+ schemaKey,
467
+ tableName,
468
+ toCamelCase(tableName)
469
+ ]) if (!tables.has(name)) tables.set(name, facts);
470
+ }
471
+ return tables;
472
+ }
473
+ function hasJsonColumn(schema) {
474
+ return Object.values(schema).some((table) => Object.values(getTableColumns(table)).some((column) => column.dataType === "json"));
475
+ }
476
+ /**
477
+ * What a JSON-mode column stores for a value: its JSON text, as UTF-8 bytes
478
+ * in a blob column. A string is JSON too (`"text"`), so it reads back as the
479
+ * string it was.
480
+ */
481
+ function serializeJsonValue(value, storage) {
482
+ if (value === null || value === void 0) return value;
483
+ const json = JSON.stringify(value);
484
+ if (json === void 0) return value;
485
+ return storage === "blob" ? new TextEncoder().encode(json) : json;
486
+ }
487
+ /**
488
+ * What a JSON-mode column holds, from what SQLite answered: text is parsed,
489
+ * bytes (a blob column) are read as UTF-8 first. What is no JSON — a row
490
+ * written before these columns were serialized — is answered as it is.
491
+ */
492
+ function parseJsonValue(value) {
493
+ let text = value;
494
+ if (isBinary(value)) try {
495
+ text = new TextDecoder("utf-8", { fatal: true }).decode(value);
496
+ } catch {
497
+ return value;
498
+ }
499
+ if (typeof text !== "string") return value;
500
+ try {
501
+ return JSON.parse(text);
502
+ } catch {
503
+ return value;
504
+ }
505
+ }
506
+ /** The table a node names: `invoices`, or the one behind `invoices as i`. */
507
+ function tableNameOf(node) {
508
+ if (!node) return null;
509
+ if (TableNode.is(node)) return node.table.identifier.name;
510
+ if (AliasNode.is(node) && TableNode.is(node.node)) return node.node.table.identifier.name;
511
+ return null;
512
+ }
513
+ /** The column a node names: `meta`, or the one in `i.meta`. */
514
+ function columnNameOf(node) {
515
+ if (!node) return null;
516
+ if (ColumnNode.is(node)) return node.column.name;
517
+ if (ReferenceNode.is(node) && ColumnNode.is(node.column)) return node.column.column.name;
518
+ return null;
519
+ }
520
+ /** Every table a query names, however deep — never walking the values it carries. */
521
+ function walkTables(node, visit) {
522
+ if (Array.isArray(node)) {
523
+ for (const item of node) walkTables(item, visit);
524
+ return;
525
+ }
526
+ if (typeof node !== "object" || node === null) return;
527
+ const kind = node.kind;
528
+ if (typeof kind !== "string" || kind === "ValueNode" || kind === "PrimitiveValueListNode") return;
529
+ if (TableNode.is(node)) {
530
+ visit(node.table.identifier.name);
531
+ return;
532
+ }
533
+ for (const value of Object.values(node)) walkTables(value, visit);
534
+ }
535
+ /** The names that are a JSON-mode column in one of `tables` and another kind of column in none. */
536
+ function jsonNamesAmong(tables) {
537
+ const json = /* @__PURE__ */ new Set();
538
+ const plain = /* @__PURE__ */ new Set();
539
+ for (const facts of new Set(tables)) {
540
+ for (const name of facts.json.keys()) json.add(name);
541
+ for (const name of facts.plain) plain.add(name);
542
+ }
543
+ for (const name of plain) json.delete(name);
544
+ return json;
545
+ }
546
+ /**
547
+ * The two plugins behind JSON-mode columns (`text({ mode: 'json' })`,
548
+ * `blob({ mode: 'json' })`): a value written to one is stored as its JSON, and
549
+ * one that is read comes back as the value.
550
+ *
551
+ * `write` goes before the plugin that renames identifiers and before
552
+ * DateSerializePlugin; `read` after them. In between they share which keys of
553
+ * a query's rows are JSON columns, worked out from what the query selects:
554
+ *
555
+ * - a column (`meta`, `i.meta`, `i.meta as m`) is resolved against the tables
556
+ * the query reads from — the same name in a table where it is another kind
557
+ * of column is left alone;
558
+ * - `selectAll()` / `returningAll()` are every JSON column of those tables;
559
+ * - where the source is no table of the schema (a subquery, a CTE, a raw
560
+ * query), a name goes for a JSON column when it is one in a table the query
561
+ * names (in any table, for a query that names none) and another kind of
562
+ * column in none of them.
563
+ *
564
+ * An expression (a JSON path, a function call, `related()`) is the caller's:
565
+ * it is neither serialized nor parsed. So is a value compared with a JSON
566
+ * column in a `where`.
567
+ */
568
+ function createJsonPlugins(schema, options = {}) {
569
+ const tables = collectJsonTables(schema);
570
+ const resultKey = options.resultKey ?? ((name) => name);
571
+ const selected = /* @__PURE__ */ new WeakMap();
572
+ let everywhere;
573
+ const writeValue = (facts, column, node) => {
574
+ const storage = column === null ? void 0 : facts.json.get(column);
575
+ if (!storage || !ValueNode.is(node)) return node;
576
+ return Object.freeze({
577
+ ...node,
578
+ value: serializeJsonValue(node.value, storage)
579
+ });
580
+ };
581
+ const writeUpdates = (facts, updates) => updates.map((update) => {
582
+ const value = writeValue(facts, columnNameOf(update.column), update.value);
583
+ return value === update.value ? update : Object.freeze({
584
+ ...update,
585
+ value
586
+ });
587
+ });
588
+ const writeInsert = (node) => {
589
+ const facts = tables.get(tableNameOf(node.into) ?? "");
590
+ if (!facts || facts.json.size === 0) return node;
591
+ let out = node;
592
+ if (node.columns && node.values && ValuesNode.is(node.values)) {
593
+ const storages = node.columns.map((column) => facts.json.get(column.column.name));
594
+ if (storages.some((storage) => storage !== void 0)) {
595
+ const rows = node.values.values.map((row) => {
596
+ if (PrimitiveValueListNode.is(row)) return PrimitiveValueListNode.create(row.values.map((value, i) => storages[i] ? serializeJsonValue(value, storages[i]) : value));
597
+ if (ValueListNode.is(row)) return ValueListNode.create(row.values.map((value, i) => {
598
+ const storage = storages[i];
599
+ if (!storage || !ValueNode.is(value)) return value;
600
+ return Object.freeze({
601
+ ...value,
602
+ value: serializeJsonValue(value.value, storage)
603
+ });
604
+ }));
605
+ return row;
606
+ });
607
+ out = InsertQueryNode.cloneWith(out, { values: ValuesNode.create(rows) });
608
+ }
609
+ }
610
+ if (node.onConflict?.updates) out = InsertQueryNode.cloneWith(out, { onConflict: Object.freeze({
611
+ ...node.onConflict,
612
+ updates: writeUpdates(facts, node.onConflict.updates)
613
+ }) });
614
+ return out;
615
+ };
616
+ const writeUpdate = (node) => {
617
+ const facts = tables.get(tableNameOf(node.table) ?? "");
618
+ if (!facts || facts.json.size === 0 || !node.updates) return node;
619
+ return Object.freeze({
620
+ ...node,
621
+ updates: writeUpdates(facts, node.updates)
622
+ });
623
+ };
624
+ const fallbackFor = (root) => {
625
+ const named = /* @__PURE__ */ new Set();
626
+ let any = false;
627
+ walkTables(root, (name) => {
628
+ any = true;
629
+ const facts = tables.get(name);
630
+ if (facts) named.add(facts);
631
+ });
632
+ if (any) return jsonNamesAmong(named);
633
+ return everywhere ??= jsonNamesAmong(tables.values());
634
+ };
635
+ const scopeOf = (root, sources) => {
636
+ let fallback;
637
+ const scope = {
638
+ sources: /* @__PURE__ */ new Map(),
639
+ opaque: false,
640
+ fallback: () => fallback ??= fallbackFor(root)
641
+ };
642
+ for (const node of sources) {
643
+ if (!node) continue;
644
+ if (TableNode.is(node)) {
645
+ const name = node.table.identifier.name;
646
+ scope.sources.set(name, tables.get(name) ?? null);
647
+ } else if (AliasNode.is(node) && IdentifierNode.is(node.alias)) {
648
+ const table = TableNode.is(node.node) ? tables.get(node.node.table.identifier.name) : void 0;
649
+ scope.sources.set(node.alias.name, table ?? null);
650
+ } else scope.opaque = true;
651
+ }
652
+ return scope;
653
+ };
654
+ const isJson = (scope, qualifier, column) => {
655
+ if (qualifier !== null) {
656
+ const facts = scope.sources.get(qualifier);
657
+ return facts ? facts.json.has(column) : scope.fallback().has(column);
658
+ }
659
+ let json = false;
660
+ for (const facts of scope.sources.values()) {
661
+ if (!facts) continue;
662
+ if (facts.plain.has(column)) return false;
663
+ if (facts.json.has(column)) json = true;
664
+ }
665
+ return json || scope.fallback().has(column);
666
+ };
667
+ const keysOf = (root) => {
668
+ const keys = /* @__PURE__ */ new Set();
669
+ const addAll = (names) => {
670
+ for (const name of names) {
671
+ keys.add(name);
672
+ keys.add(resultKey(name));
673
+ }
674
+ };
675
+ let scope;
676
+ let selections;
677
+ if (SelectQueryNode.is(root)) {
678
+ scope = scopeOf(root, [...root.from?.froms ?? [], ...(root.joins ?? []).map((join) => join.table)]);
679
+ selections = root.selections;
680
+ } else if (InsertQueryNode.is(root)) {
681
+ scope = scopeOf(root, [root.into]);
682
+ selections = root.returning?.selections;
683
+ } else if (UpdateQueryNode.is(root)) {
684
+ scope = scopeOf(root, [
685
+ root.table,
686
+ ...root.from?.froms ?? [],
687
+ ...(root.joins ?? []).map((join) => join.table)
688
+ ]);
689
+ selections = root.returning?.selections;
690
+ } else if (DeleteQueryNode.is(root)) {
691
+ scope = scopeOf(root, [
692
+ ...root.from.froms,
693
+ ...(root.joins ?? []).map((join) => join.table),
694
+ ...root.using?.tables ?? []
695
+ ]);
696
+ selections = root.returning?.selections;
697
+ } else if (root.kind === "RawNode") {
698
+ addAll(fallbackFor(root));
699
+ return keys.size > 0 ? keys : void 0;
700
+ } else return;
701
+ if (!selections) return void 0;
702
+ const unknown = scope.opaque || [...scope.sources.values()].some((facts) => facts === null);
703
+ for (const { selection } of selections) if (SelectAllNode.is(selection)) {
704
+ addAll(jsonNamesAmong([...scope.sources.values()].filter((facts) => facts !== null)));
705
+ if (unknown) addAll(scope.fallback());
706
+ } else if (ReferenceNode.is(selection)) {
707
+ const qualifier = tableNameOf(selection.table);
708
+ if (SelectAllNode.is(selection.column)) {
709
+ const facts = qualifier === null ? void 0 : scope.sources.get(qualifier);
710
+ addAll(facts ? facts.json.keys() : scope.fallback());
711
+ } else if (isJson(scope, qualifier, selection.column.column.name)) keys.add(resultKey(selection.column.column.name));
712
+ } else if (ColumnNode.is(selection)) {
713
+ if (isJson(scope, null, selection.column.name)) keys.add(resultKey(selection.column.name));
714
+ } else if (AliasNode.is(selection) && IdentifierNode.is(selection.alias)) {
715
+ const aliased = selection.node;
716
+ const column = ReferenceNode.is(aliased) || ColumnNode.is(aliased) ? columnNameOf(aliased) : null;
717
+ const qualifier = ReferenceNode.is(aliased) ? tableNameOf(aliased.table) : null;
718
+ if (column !== null && isJson(scope, qualifier, column)) keys.add(resultKey(selection.alias.name));
719
+ }
720
+ return keys.size > 0 ? keys : void 0;
721
+ };
722
+ return {
723
+ write: {
724
+ transformQuery({ node, queryId }) {
725
+ const keys = keysOf(node);
726
+ if (keys) selected.set(queryId, keys);
727
+ if (InsertQueryNode.is(node)) return writeInsert(node);
728
+ if (UpdateQueryNode.is(node)) return writeUpdate(node);
729
+ return node;
730
+ },
731
+ async transformResult({ result }) {
732
+ return result;
733
+ }
734
+ },
735
+ read: {
736
+ transformQuery({ node }) {
737
+ return node;
738
+ },
739
+ async transformResult({ result, queryId }) {
740
+ const keys = selected.get(queryId);
741
+ if (!keys || result.rows.length === 0) return result;
742
+ const rows = result.rows.map((row) => {
743
+ let out;
744
+ for (const key of keys) {
745
+ const value = row[key];
746
+ if (value === void 0 || value === null) continue;
747
+ const parsed = parseJsonValue(value);
748
+ if (parsed !== value) (out ??= { ...row })[key] = parsed;
749
+ }
750
+ return out ?? row;
751
+ });
752
+ return {
753
+ ...result,
754
+ rows
755
+ };
756
+ }
757
+ }
758
+ };
759
+ }
760
+ /**
429
761
  * Validate that a schema object is shaped like a record of Drizzle tables.
430
762
  *
431
763
  * Throws a descriptive error pointing at the offending key when the schema
@@ -446,16 +778,23 @@ function assertValidSchema(schema) {
446
778
  * - SchemaPlugin (extends CamelCasePlugin): schema-aware camelCase ↔ snake_case
447
779
  * - DateSerializePlugin: Date ↔ SQLite text serialization
448
780
  * - BooleanDeserializePlugin: boolean-mode columns read back as booleans
781
+ * - createJsonPlugins' two: JSON-mode columns written as JSON and read back
782
+ * as their value — only for a schema that has such a column
449
783
  *
450
784
  * When camelCase is false, SchemaPlugin is omitted.
451
785
  */
452
786
  function createDrizzlePlugins(schema, camelCase = true) {
453
787
  assertValidSchema(schema);
788
+ const tables = schema;
789
+ const schemaPlugin = camelCase ? new SchemaPlugin(schema) : void 0;
790
+ const json = hasJsonColumn(tables) ? createJsonPlugins(tables, schemaPlugin ? { resultKey: (name) => schemaPlugin.resultKey(name) } : {}) : void 0;
454
791
  const plugins = [];
455
- plugins.push(new DrizzleDefaultsPlugin(schema));
456
- if (camelCase) plugins.push(new SchemaPlugin(schema));
457
- plugins.push(new DateSerializePlugin(schema));
458
- plugins.push(new BooleanDeserializePlugin(schema));
792
+ plugins.push(new DrizzleDefaultsPlugin(tables));
793
+ if (json) plugins.push(json.write);
794
+ if (schemaPlugin) plugins.push(schemaPlugin);
795
+ plugins.push(new DateSerializePlugin(tables));
796
+ plugins.push(new BooleanDeserializePlugin(tables));
797
+ if (json) plugins.push(json.read);
459
798
  return plugins;
460
799
  }
461
800
  //#endregion
@@ -465,14 +804,14 @@ const specs = /* @__PURE__ */ new WeakMap();
465
804
  function metaOf(spec) {
466
805
  return {
467
806
  target: spec.relation.target,
468
- with: new Map(spec.with.map((nested) => [nested.relation.name, metaOf(nested)]))
807
+ with: new Map(spec.with.map((nested) => [nested.alias, metaOf(nested)]))
469
808
  };
470
809
  }
471
810
  function render(spec, outer, depth) {
472
811
  const { relation } = spec;
473
812
  const row = `_r${depth}`;
474
813
  const pairs = spec.columns.map((column) => sql`${sql.lit(column)}, ${sql.ref(`${row}.${column}`)}`);
475
- for (const nested of spec.with) pairs.push(sql`${sql.lit(nested.relation.name)}, json(${render(nested, row, depth + 1)})`);
814
+ for (const nested of spec.with) pairs.push(sql`${sql.lit(nested.alias)}, json(${render(nested, row, depth + 1)})`);
476
815
  const object = sql`json_object(${sql.join(pairs)})`;
477
816
  const target = sql.table(relation.target);
478
817
  const matches = (alias) => sql`${sql.ref(`${alias}.${relation.foreign}`)} = ${sql.ref(`${outer}.${relation.local}`)}`;
@@ -486,16 +825,30 @@ function render(spec, outer, depth) {
486
825
  /**
487
826
  * A relation as a selection: what `related()` returns. `table` is the table
488
827
  * it is a relation of (so `with` takes only the related table's own), `alias`
489
- * the relation's name — the key it is answered under.
828
+ * the key it is answered under — the relation's name, until `.as()` says
829
+ * another.
490
830
  */
491
- var RelatedExpression = class {
831
+ var RelatedExpression = class RelatedExpression {
492
832
  table;
493
833
  alias;
494
834
  constructor(spec) {
495
835
  this.table = spec.relation.table;
496
- this.alias = spec.relation.name;
836
+ this.alias = spec.alias;
497
837
  specs.set(this, spec);
498
838
  }
839
+ /**
840
+ * The same relation, answered under `name` instead of its own:
841
+ * `related('customers', 'invoices', { columns: ['id'], limit: 1 }).as('latest')`.
842
+ * A new expression — this one keeps its name.
843
+ */
844
+ as(name) {
845
+ const spec = specs.get(this);
846
+ if (typeof name !== "string" || name === "") throw new TypeError(`[durable-db] related('${spec.relation.table}', '${spec.relation.name}').as() takes the name to answer it under.`);
847
+ return new RelatedExpression({
848
+ ...spec,
849
+ alias: name
850
+ });
851
+ }
499
852
  get expression() {
500
853
  return render(specs.get(this), this.table, 1);
501
854
  }
@@ -532,8 +885,8 @@ function specOf(schema, table, name, arg) {
532
885
  const other = spec.schema === schema ? "" : " of another database";
533
886
  throw new TypeError(`${where}: with takes relations of "${relation.target}", and "${spec.relation.name}" is one of "${spec.relation.table}"${other}.`);
534
887
  }
535
- if (names.has(spec.relation.name)) throw new TypeError(`${where}: "${spec.relation.name}" is there twice — as a column and a relation, or the relation twice.`);
536
- names.add(spec.relation.name);
888
+ if (names.has(spec.alias)) throw new TypeError(`${where}: "${spec.alias}" is there twice — as a column and a relation, or two relations under one name.`);
889
+ names.add(spec.alias);
537
890
  inner.push(spec);
538
891
  }
539
892
  if (names.size === 0) throw new TypeError(`${where} reads nothing: name the columns to read.`);
@@ -549,13 +902,18 @@ function specOf(schema, table, name, arg) {
549
902
  return {
550
903
  schema,
551
904
  relation,
905
+ alias: relation.name,
552
906
  columns,
553
907
  with: inner,
554
908
  orderBy,
555
909
  limit
556
910
  };
557
911
  }
558
- /** `related` for a schema: what `defineDatabase()` hands out. */
912
+ /**
913
+ * `related` for a schema: what `defineDatabase()` hands out, and the way to
914
+ * it for code that is handed a schema — typed by the schema's tables, or by
915
+ * strings (`AnyRelated`) when its type names none.
916
+ */
559
917
  function createRelated(schema) {
560
918
  const related = (table, relation, arg) => new RelatedExpression(specOf(schema, table, relation, arg));
561
919
  return related;
@@ -586,7 +944,8 @@ function toBoolean(value) {
586
944
  * query as the builder made it, marks and all — and `results` last, when the
587
945
  * row's keys are the schema's again.
588
946
  */
589
- function createRelatedPlugins(schema) {
947
+ function createRelatedPlugins(schema, options = {}) {
948
+ const resultKey = options.resultKey ?? ((name) => name);
590
949
  const selected = /* @__PURE__ */ new WeakMap();
591
950
  const kinds = /* @__PURE__ */ new Map();
592
951
  const kindsOf = (table) => {
@@ -594,12 +953,14 @@ function createRelatedPlugins(schema) {
594
953
  if (!kind) {
595
954
  kind = {
596
955
  dates: /* @__PURE__ */ new Set(),
597
- booleans: /* @__PURE__ */ new Set()
956
+ booleans: /* @__PURE__ */ new Set(),
957
+ jsons: /* @__PURE__ */ new Set()
598
958
  };
599
959
  const target = schema[table];
600
960
  const columns = target ? getTableColumns(target) : {};
601
961
  for (const [key, column] of Object.entries(columns)) if (column.dataType === "date") kind.dates.add(key);
602
962
  else if (column.dataType === "boolean") kind.booleans.add(key);
963
+ else if (column.dataType === "json") kind.jsons.add(key);
603
964
  kinds.set(table, kind);
604
965
  }
605
966
  return kind;
@@ -607,7 +968,7 @@ function createRelatedPlugins(schema) {
607
968
  const revive = (value, meta) => {
608
969
  if (Array.isArray(value)) return value.map((item) => revive(item, meta));
609
970
  if (typeof value !== "object" || value === null) return value;
610
- const { dates, booleans } = kindsOf(meta.target);
971
+ const { dates, booleans, jsons } = kindsOf(meta.target);
611
972
  const row = value;
612
973
  for (const [key, item] of Object.entries(row)) {
613
974
  const nested = meta.with.get(key);
@@ -615,6 +976,7 @@ function createRelatedPlugins(schema) {
615
976
  else if (dates.has(key)) {
616
977
  if (typeof item === "string" && dateSerializers.isSerializedDateString(item)) row[key] = dateSerializers.deserialize(item);
617
978
  } else if (booleans.has(key)) row[key] = toBoolean(item);
979
+ else if (jsons.has(key)) row[key] = parseJsonValue(item);
618
980
  }
619
981
  return row;
620
982
  };
@@ -638,9 +1000,14 @@ function createRelatedPlugins(schema) {
638
1000
  if (!relations) return result;
639
1001
  const rows = result.rows.map((row) => {
640
1002
  const out = { ...row };
641
- for (const [key, meta] of relations) {
642
- const raw = out[key];
643
- if (typeof raw === "string") out[key] = revive(JSON.parse(raw), meta);
1003
+ for (const [alias, meta] of relations) {
1004
+ const key = resultKey(alias);
1005
+ if (key !== alias && Object.hasOwn(out, key)) {
1006
+ out[alias] = out[key];
1007
+ delete out[key];
1008
+ }
1009
+ const raw = out[alias];
1010
+ if (typeof raw === "string") out[alias] = revive(JSON.parse(raw), meta);
644
1011
  }
645
1012
  return out;
646
1013
  });
@@ -764,4 +1131,4 @@ function defineDatabase(config) {
764
1131
  };
765
1132
  }
766
1133
  //#endregion
767
- export { createRelatedPlugins as a, SchemaPlugin as c, relationOf as d, relationsOf as f, RelatedExpression as i, createDrizzlePlugins as l, defineDatabase as n, DateSerializePlugin as o, liveTestDatabases as r, DrizzleDefaultsPlugin as s, ACTION_TEST_META as t, dateSerializers as u };
1134
+ export { createRelated as a, DrizzleDefaultsPlugin as c, createJsonPlugins as d, dateSerializers as f, relationsOf as h, RelatedExpression as i, SchemaPlugin as l, relationOf as m, defineDatabase as n, createRelatedPlugins as o, parseJsonValue as p, liveTestDatabases as r, DateSerializePlugin as s, ACTION_TEST_META as t, createDrizzlePlugins as u };
@@ -1,4 +1,4 @@
1
- import "./defineDatabase-BvFOZVkv.js";
1
+ import "./defineDatabase-Bww_w_n5.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";
@@ -416,6 +416,11 @@ declare class SchemaPlugin extends CamelCasePlugin {
416
416
  constructor(schema: Record<string, SQLiteTableWithColumns<any>>);
417
417
  protected snakeCase(str: string): string;
418
418
  protected camelCase(str: string): string;
419
+ /**
420
+ * The key a result row has for an identifier a query writes as `name`: it
421
+ * is snake_cased on the way in and camelCased on the way out.
422
+ */
423
+ resultKey(name: string): string;
419
424
  }
420
425
  /**
421
426
  * Plugin that handles Drizzle's defaultFn and onUpdateFn during Kysely queries.
@@ -486,6 +491,46 @@ declare class DateSerializePlugin implements KyselyPlugin {
486
491
  private transformRow;
487
492
  private shouldDeserialize;
488
493
  }
494
+ /**
495
+ * What a JSON-mode column holds, from what SQLite answered: text is parsed,
496
+ * bytes (a blob column) are read as UTF-8 first. What is no JSON — a row
497
+ * written before these columns were serialized — is answered as it is.
498
+ */
499
+ declare function parseJsonValue(value: unknown): unknown;
500
+ interface JsonPluginOptions {
501
+ /**
502
+ * The key a result row has for an identifier as a query writes it —
503
+ * SchemaPlugin's `resultKey` when the names are camelCased. Default: the
504
+ * identifier itself.
505
+ */
506
+ resultKey?: (name: string) => string;
507
+ }
508
+ /**
509
+ * The two plugins behind JSON-mode columns (`text({ mode: 'json' })`,
510
+ * `blob({ mode: 'json' })`): a value written to one is stored as its JSON, and
511
+ * one that is read comes back as the value.
512
+ *
513
+ * `write` goes before the plugin that renames identifiers and before
514
+ * DateSerializePlugin; `read` after them. In between they share which keys of
515
+ * a query's rows are JSON columns, worked out from what the query selects:
516
+ *
517
+ * - a column (`meta`, `i.meta`, `i.meta as m`) is resolved against the tables
518
+ * the query reads from — the same name in a table where it is another kind
519
+ * of column is left alone;
520
+ * - `selectAll()` / `returningAll()` are every JSON column of those tables;
521
+ * - where the source is no table of the schema (a subquery, a CTE, a raw
522
+ * query), a name goes for a JSON column when it is one in a table the query
523
+ * names (in any table, for a query that names none) and another kind of
524
+ * column in none of them.
525
+ *
526
+ * An expression (a JSON path, a function call, `related()`) is the caller's:
527
+ * it is neither serialized nor parsed. So is a value compared with a JSON
528
+ * column in a `where`.
529
+ */
530
+ declare function createJsonPlugins(schema: Record<string, Table>, options?: JsonPluginOptions): {
531
+ write: KyselyPlugin;
532
+ read: KyselyPlugin;
533
+ };
489
534
  /**
490
535
  * Create all recommended plugins for use with Drizzle schemas.
491
536
  *
@@ -494,9 +539,11 @@ declare class DateSerializePlugin implements KyselyPlugin {
494
539
  * - SchemaPlugin (extends CamelCasePlugin): schema-aware camelCase ↔ snake_case
495
540
  * - DateSerializePlugin: Date ↔ SQLite text serialization
496
541
  * - BooleanDeserializePlugin: boolean-mode columns read back as booleans
542
+ * - createJsonPlugins' two: JSON-mode columns written as JSON and read back
543
+ * as their value — only for a schema that has such a column
497
544
  *
498
545
  * When camelCase is false, SchemaPlugin is omitted.
499
546
  */
500
547
  declare function createDrizzlePlugins(schema: Record<string, SQLiteTableWithColumns<any>>, camelCase?: boolean): KyselyPlugin[];
501
548
  //#endregion
502
- export { createKyselyFromSql as C, SqlExecutor as S, MigrationAttemptInfo as _, QueryResult$1 as a, SqliteDurableObject as b, DrizzleDefaultsPlugin as c, dateSerializers as d, DeleteClassMigration as f, Migration as g, removedDatabaseMessage as h, KyselyPlugin$1 as i, SchemaPlugin as l, RemovedDatabaseError as m, CompiledQuery as n, studio as o, RemovedDatabaseDurableObject as p, Kysely$1 as r, DateSerializePlugin as s, CamelCasePlugin$1 as t, createDrizzlePlugins as u, MigrationSchemaConflictError as v, CreateKyselyOptions as x, Migrations as y };
549
+ export { SqliteDurableObject as C, createKyselyFromSql as E, Migrations as S, SqlExecutor as T, RemovedDatabaseError as _, QueryResult$1 as a, MigrationAttemptInfo as b, DrizzleDefaultsPlugin as c, createDrizzlePlugins as d, createJsonPlugins as f, RemovedDatabaseDurableObject as g, DeleteClassMigration as h, KyselyPlugin$1 as i, JsonPluginOptions as l, parseJsonValue as m, CompiledQuery as n, studio as o, dateSerializers as p, Kysely$1 as r, DateSerializePlugin as s, CamelCasePlugin$1 as t, SchemaPlugin as u, removedDatabaseMessage as v, CreateKyselyOptions as w, MigrationSchemaConflictError as x, Migration as y };
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 { _ as RelationMap, b as relationOf, c as DatabaseDefinition, d as InferArgs, g as Relation, h as RelatedOptions, i as ActionContext, m as RelatedExpression, n as Action, p as Related, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as RelationType, x as relationsOf, y as Relations } from "./defineDatabase-BvFOZVkv.js";
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";
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 AnySQLiteColumn, 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 Relation, type RelationMap, type RelationType, type Relations, blob, 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 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,7 +1,7 @@
1
- import { d as relationOf, f as relationsOf, i as RelatedExpression, n as defineDatabase } from "./defineDatabase-CaqKQagA.js";
1
+ import { a as createRelated, h as relationsOf, i as RelatedExpression, m as relationOf, n as defineDatabase } from "./defineDatabase-CULpd87Z.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";
5
5
  import { n as describeAction } from "./describeAction-CEKfxTQ4.js";
6
6
  import { getTenantId, hasTenantId, setTenantIdResolver } from "./context/index.js";
7
- export { RelatedExpression, blob, defineDatabase, describeAction, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, relationOf, relationsOf, setTenantIdResolver, table, text, type, uniqueIndex };
7
+ export { RelatedExpression, blob, createRelated, defineDatabase, describeAction, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, relationOf, relationsOf, setTenantIdResolver, table, text, type, uniqueIndex };
@@ -1,4 +1,4 @@
1
- import { a as createRelatedPlugins, l as createDrizzlePlugins, o as DateSerializePlugin } from "./defineDatabase-CaqKQagA.js";
1
+ import { l as SchemaPlugin, o as createRelatedPlugins, s as DateSerializePlugin, u as createDrizzlePlugins } from "./defineDatabase-CULpd87Z.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. */
@@ -255,7 +255,8 @@ function createKyselyFromSql(sqlStorage, options = {}) {
255
255
  const { schema, plugins = [], camelCase = true } = options;
256
256
  const sqliteDialect = new SqliteDialect({ database: null });
257
257
  const allPlugins = [];
258
- const related = schema ? createRelatedPlugins(schema) : void 0;
258
+ const naming = schema && camelCase ? new SchemaPlugin(schema) : void 0;
259
+ const related = schema ? createRelatedPlugins(schema, naming ? { resultKey: (name) => naming.resultKey(name) } : {}) : void 0;
259
260
  if (related) allPlugins.push(related.capture);
260
261
  if (schema) allPlugins.push(...createDrizzlePlugins(schema, camelCase));
261
262
  else if (camelCase) {
@@ -332,6 +332,63 @@ function warnNonLiteral(filePath, key, defaultValue) {
332
332
  console.warn(`[durable-db] '${key}' in defineDatabase() must be a static literal for build-time analysis. Got a dynamic expression in ${path$1.basename(filePath)} — defaulting to '${defaultValue}'.`);
333
333
  }
334
334
  /**
335
+ * Whether a database was given a schema discovery could read: tables listed
336
+ * in the call, or a const the schema module exports.
337
+ */
338
+ function declaresSchema(db) {
339
+ return !!db.schemaExport || db.schemaTableNames.length > 0;
340
+ }
341
+ /** `x as const`, `x satisfies T`, `x!`: the expression itself. */
342
+ function unwrapExpression(node) {
343
+ let current = node;
344
+ while (t.isTSAsExpression(current) || t.isTSSatisfiesExpression(current) || t.isTSNonNullExpression(current)) current = current.expression;
345
+ return current;
346
+ }
347
+ /** `{ users, posts }`: the tables by name, and the module they are imported from. */
348
+ function listedTables(object, imports) {
349
+ const declared = {
350
+ schemaImport: null,
351
+ schemaExport: null,
352
+ schemaTableNames: []
353
+ };
354
+ for (const schemaProp of object.properties) if (t.isObjectProperty(schemaProp) && t.isIdentifier(schemaProp.key)) {
355
+ const tableName = schemaProp.key.name;
356
+ declared.schemaTableNames.push(tableName);
357
+ const importInfo = imports.get(tableName);
358
+ if (importInfo && !declared.schemaImport) declared.schemaImport = importInfo.source;
359
+ }
360
+ return declared;
361
+ }
362
+ /**
363
+ * The schema of a defineDatabase() call. Three shapes can be read:
364
+ *
365
+ * defineDatabase({ schema: { users, posts } }) // the tables, listed
366
+ * const schema = { users, posts }; // … or listed in a const of this file
367
+ * import { schema } from './schema'; // a const the schema module exports,
368
+ * defineDatabase({ schema }) // shared with whoever else needs the tables
369
+ *
370
+ * An imported const is not followed into its module here: it is recorded as
371
+ * the export to import (`schemaExport`), and whoever needs the tables loads it.
372
+ */
373
+ function extractSchema(declaratorPath, value, filePath, imports) {
374
+ const node = unwrapExpression(value);
375
+ if (t.isObjectExpression(node)) return listedTables(node, imports);
376
+ if (t.isIdentifier(node)) {
377
+ const imported = imports.get(node.name);
378
+ if (imported && imported.imported !== "*") return {
379
+ schemaImport: imported.source,
380
+ schemaExport: imported.imported,
381
+ schemaTableNames: []
382
+ };
383
+ const binding = imported ? void 0 : declaratorPath.scope.getBinding(node.name);
384
+ const init = binding?.path.isVariableDeclarator() ? binding.path.node.init : null;
385
+ const local = init ? unwrapExpression(init) : null;
386
+ if (binding?.constant && t.isObjectExpression(local)) return listedTables(local, imports);
387
+ }
388
+ console.warn(`[durable-db] 'schema' in defineDatabase() is read at build time: list the tables ({ schema: { users, posts } }) or pass a const the schema module exports (import { schema } from './schema'). ${path$1.basename(filePath)} passes something else, so its database gets no schema — no migrations, no column mapping.`);
389
+ return null;
390
+ }
391
+ /**
335
392
  * Extract database configuration from a defineDatabase() call
336
393
  */
337
394
  function extractDatabaseInfo(declaratorPath, callExpr, filePath, imports, namePrefix) {
@@ -340,8 +397,11 @@ function extractDatabaseInfo(declaratorPath, callExpr, filePath, imports, namePr
340
397
  let instance = "per-tenant";
341
398
  let browsable = false;
342
399
  let transport = "rpc";
343
- let schemaImport = null;
344
- const schemaTableNames = [];
400
+ let schema = {
401
+ schemaImport: null,
402
+ schemaExport: null,
403
+ schemaTableNames: []
404
+ };
345
405
  for (const prop of configArg.properties) {
346
406
  if (!t.isObjectProperty(prop) || !t.isIdentifier(prop.key)) continue;
347
407
  const key = prop.key.name;
@@ -362,16 +422,7 @@ function extractDatabaseInfo(declaratorPath, callExpr, filePath, imports, namePr
362
422
  if (value === "rpc" || value === "websocket") transport = value;
363
423
  } else warnNonLiteral(filePath, "transport", "rpc");
364
424
  }
365
- if (key === "schema" && t.isObjectExpression(prop.value)) {
366
- for (const schemaProp of prop.value.properties) if (t.isObjectProperty(schemaProp) || t.isSpreadElement(schemaProp)) {
367
- if (t.isObjectProperty(schemaProp) && t.isIdentifier(schemaProp.key)) {
368
- const tableName = schemaProp.key.name;
369
- schemaTableNames.push(tableName);
370
- const importInfo = imports.get(tableName);
371
- if (importInfo && !schemaImport) schemaImport = importInfo.source;
372
- }
373
- }
374
- }
425
+ if (key === "schema") schema = extractSchema(declaratorPath, prop.value, filePath, imports) ?? schema;
375
426
  }
376
427
  const base = path$1.basename(filePath).replace(/\.(ts|js)$/, "");
377
428
  const name = namePrefix ? `${namePrefix}-${base}` : base;
@@ -384,8 +435,7 @@ function extractDatabaseInfo(declaratorPath, callExpr, filePath, imports, namePr
384
435
  browsable,
385
436
  transport,
386
437
  migrationsDir: "",
387
- schemaImport,
388
- schemaTableNames
438
+ ...schema
389
439
  };
390
440
  }
391
441
  /**
@@ -426,4 +476,4 @@ function toScreamingSnakeCase(str) {
426
476
  return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[-]/g, "_").toUpperCase();
427
477
  }
428
478
  //#endregion
429
- export { discoverActionFiles as a, resolveImportPath as c, databaseSources as i, loadViteAliases as l, parseDatabaseFile as n, discoverDatabaseFiles as o, toPascalCase as r, readFile as s, BABEL_PARSER_PLUGINS as t };
479
+ export { databaseSources as a, readFile as c, toPascalCase as i, resolveImportPath as l, declaresSchema as n, discoverActionFiles as o, parseDatabaseFile as r, discoverDatabaseFiles as s, BABEL_PARSER_PLUGINS as t, loadViteAliases as u };
@@ -1,8 +1,8 @@
1
- import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-CaqKQagA.js";
1
+ import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-CULpd87Z.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-D8JQ4v8n.js";
5
+ import { c as tenantOfInstanceKey, i as createActionOutbox, t as createKyselyFromSql } from "../kysely-DCQRqT62.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
@@ -13,11 +13,21 @@ const loadSqlite = () => createRequire(import.meta.url)("node:sqlite");
13
13
  */
14
14
  function sqlStorageShim(sqlite) {
15
15
  const isReader = (sql) => /^\s*(SELECT|PRAGMA|WITH)/i.test(sql) || /\bRETURNING\b/i.test(sql);
16
- const normalize = (p) => typeof p === "boolean" ? p ? 1 : 0 : p === void 0 ? null : p;
16
+ const normalize = (p) => typeof p === "boolean" ? p ? 1 : 0 : p === void 0 ? null : p instanceof ArrayBuffer ? new Uint8Array(p) : p;
17
+ const asStored = (row) => {
18
+ if (typeof row !== "object" || row === null) return row;
19
+ let out;
20
+ for (const [key, value] of Object.entries(row)) {
21
+ if (!(value instanceof Uint8Array)) continue;
22
+ out ??= { ...row };
23
+ out[key] = value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength);
24
+ }
25
+ return out ?? row;
26
+ };
17
27
  return { exec(query, ...bindings) {
18
28
  const stmt = sqlite.prepare(query);
19
29
  const params = bindings.map(normalize);
20
- const rows = isReader(query) ? stmt.all(...params) : (stmt.run(...params), []);
30
+ const rows = isReader(query) ? stmt.all(...params).map(asStored) : (stmt.run(...params), []);
21
31
  return { toArray: () => rows };
22
32
  } };
23
33
  }
@@ -1,5 +1,5 @@
1
1
  import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
2
- import "../index-DoxI1p4-.js";
2
+ import "../index-BQ1hHyrq.js";
3
3
  import { Plugin } from "vite";
4
4
  import "@babel/types";
5
5
  //#region src/vite/modules/wrangler.d.ts
@@ -1,7 +1,7 @@
1
1
  import { i as init_debug, r as debugVite } from "../debug-Cz8KzMft.js";
2
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";
3
3
  import { loadMigrationFiles } from "../migrations/generator.js";
4
- import { a as discoverActionFiles, i as databaseSources, n as parseDatabaseFile, o as discoverDatabaseFiles, r as toPascalCase, s as readFile, t as BABEL_PARSER_PLUGINS } from "../parser-DyepmXzE.js";
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";
6
6
  import path, * as path$1 from "node:path";
7
7
  import { parse } from "@babel/parser";
@@ -745,8 +745,12 @@ function schemaLocalName(db, tableName) {
745
745
  const safe = (s) => s.replace(/[^A-Za-z0-9_$]/g, "_");
746
746
  return `__schema_${safe(db.name)}_${safe(tableName)}`;
747
747
  }
748
+ /** The schema as one object, when the schema module exports it whole (`schemaExport`). */
749
+ function schemaConstLocalName(db) {
750
+ return `__schema_${db.name.replace(/[^A-Za-z0-9_$]/g, "_")}`;
751
+ }
748
752
  function hasSchema(db) {
749
- return !!db.schemaImport && db.schemaTableNames.length > 0;
753
+ return !!db.schemaImport && declaresSchema(db);
750
754
  }
751
755
  /**
752
756
  * Import declaration bringing a database's schema tables into the generated
@@ -759,13 +763,26 @@ function hasSchema(db) {
759
763
  */
760
764
  function buildSchemaImport(db) {
761
765
  const source = db.schemaImport.startsWith(".") ? path.resolve(path.dirname(db.filePath), db.schemaImport) : db.schemaImport;
766
+ if (db.schemaExport) return createNamedImport([{
767
+ imported: db.schemaExport,
768
+ local: schemaConstLocalName(db)
769
+ }], source);
762
770
  return createNamedImport(db.schemaTableNames.map((tableName) => ({
763
771
  imported: tableName,
764
772
  local: schemaLocalName(db, tableName)
765
773
  })), source);
766
774
  }
775
+ /**
776
+ * The schema in the generated module: the const the schema module exports —
777
+ * the very object the app's own code holds —, or the listed tables under
778
+ * their names.
779
+ */
780
+ function buildSchemaExpression(db) {
781
+ if (db.schemaExport) return t.identifier(schemaConstLocalName(db));
782
+ return t.objectExpression(db.schemaTableNames.map((tableName) => t.objectProperty(t.identifier(tableName), t.identifier(schemaLocalName(db, tableName)))));
783
+ }
767
784
  function buildSchemaProperty(db) {
768
- return t.classProperty(t.identifier("schema"), t.objectExpression(db.schemaTableNames.map((tableName) => t.objectProperty(t.identifier(tableName), t.identifier(schemaLocalName(db, tableName))))));
785
+ return t.classProperty(t.identifier("schema"), buildSchemaExpression(db));
769
786
  }
770
787
  function buildDbTransportsObject(databases) {
771
788
  const properties = databases.map((db) => t.objectProperty(t.stringLiteral(db.name), t.stringLiteral(db.transport)));
@@ -836,7 +853,7 @@ function generateDatabasesModule(databases) {
836
853
  t.objectProperty(t.identifier("bindingName"), t.stringLiteral(db.bindingName)),
837
854
  t.objectProperty(t.identifier("className"), t.stringLiteral(db.className)),
838
855
  t.objectProperty(t.identifier("instance"), t.stringLiteral(db.instance)),
839
- t.objectProperty(t.identifier("schema"), hasSchema(db) ? buildSchemaProperty(db).value : t.objectExpression([]))
856
+ t.objectProperty(t.identifier("schema"), hasSchema(db) ? buildSchemaExpression(db) : t.objectExpression([]))
840
857
  ]));
841
858
  const program = t.program([...databases.filter(hasSchema).map(buildSchemaImport), t.exportNamedDeclaration(t.variableDeclaration("const", [t.variableDeclarator(t.identifier("databases"), t.arrayExpression(entries))]))]);
842
859
  return generateCode(t.file(program));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "durable-db",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/eagerpatch/durable-db.git"