durable-db 0.9.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 +74 -6
- package/dist/cli/bin.js +1 -1
- package/dist/cli/index.d.ts +17 -2
- package/dist/cli/index.js +3 -2
- package/dist/{cli-CVS0b2im.js → cli-5KmSf8wx.js} +37 -7
- package/dist/db/index.d.ts +3 -3
- package/dist/db/index.js +3 -3
- package/dist/{defineDatabase-BvFOZVkv.d.ts → defineDatabase-BE7YRtLh.d.ts} +52 -7
- package/dist/{defineDatabase-CaqKQagA.js → defineDatabase-Cb5sMNg0.js} +459 -26
- package/dist/{index-DoxI1p4-.d.ts → index-CUkSkt7G.d.ts} +49 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/{kysely-D8JQ4v8n.js → kysely-q97dtmaQ.js} +3 -2
- package/dist/{parser-DyepmXzE.js → parser-mUnAtllk.js} +65 -15
- package/dist/testing/index.js +14 -4
- package/dist/vite/durableDb.d.ts +1 -1
- package/dist/vite/durableDb.js +21 -4
- package/package.json +1 -1
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
|
-
|
|
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,16 +1224,60 @@ related('customers', 'invoices', {
|
|
|
1202
1224
|
});
|
|
1203
1225
|
```
|
|
1204
1226
|
|
|
1205
|
-
|
|
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
|
+
|
|
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:
|
|
1254
|
+
|
|
1255
|
+
```ts
|
|
1256
|
+
related('invoices', 'customer', ['name']).as('buyer');
|
|
1257
|
+
// { buyer: { name: string } }
|
|
1258
|
+
|
|
1259
|
+
related('customers', 'invoices', { columns: ['number'], orderBy: { number: 'desc' }, limit: 1 }).as('latest');
|
|
1260
|
+
```
|
|
1261
|
+
|
|
1262
|
+
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
1263
|
|
|
1207
1264
|
**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
1265
|
|
|
1266
|
+
**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.
|
|
1267
|
+
|
|
1268
|
+
```ts
|
|
1269
|
+
import { createRelated } from 'durable-db';
|
|
1270
|
+
|
|
1271
|
+
const related = createRelated(schema);
|
|
1272
|
+
related('invoices', 'customer', ['name']);
|
|
1273
|
+
```
|
|
1274
|
+
|
|
1209
1275
|
What it does not do yet:
|
|
1210
1276
|
|
|
1211
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.
|
|
1212
1278
|
- Composite foreign keys (`foreignKey({ columns: [a, b] })`) are not relations.
|
|
1213
1279
|
- `related()` names the table as the query does: `selectFrom('invoices')`, not `selectFrom('invoices as i')`. It needs the default `camelCase` mapping.
|
|
1214
|
-
-
|
|
1280
|
+
- A `where` compares a JSON column with what is stored (its text), like any `where`.
|
|
1215
1281
|
|
|
1216
1282
|
---
|
|
1217
1283
|
|
|
@@ -1343,9 +1409,11 @@ The library includes plugins for transparent data mapping between JavaScript and
|
|
|
1343
1409
|
|
|
1344
1410
|
- **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
1411
|
- **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.
|
|
1412
|
+
- **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.
|
|
1413
|
+
- **BooleanDeserializePlugin**: answers `integer({ mode: 'boolean' })` columns as `true`/`false`.
|
|
1414
|
+
- **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
1415
|
|
|
1348
|
-
All
|
|
1416
|
+
All of them are configured by `createDrizzlePlugins(schema)`.
|
|
1349
1417
|
|
|
1350
1418
|
---
|
|
1351
1419
|
|
package/dist/cli/bin.js
CHANGED
package/dist/cli/index.d.ts
CHANGED
|
@@ -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-
|
|
4
|
-
import "../index-
|
|
3
|
+
import { l as DatabaseInfo } from "../defineDatabase-BE7YRtLh.js";
|
|
4
|
+
import "../index-CUkSkt7G.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 {
|
|
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
|
|
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
|
|
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
|
|
118
|
+
let loaded;
|
|
97
119
|
try {
|
|
98
|
-
|
|
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
|
|
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
|
|
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,
|
|
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 };
|
package/dist/db/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { l as type } from "../index-bUUlOWfP.js";
|
|
2
|
-
import {
|
|
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 createKyselyFromSql, S as SqlExecutor, _ as
|
|
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-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 { c as
|
|
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-
|
|
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";
|
|
@@ -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 };
|
|
@@ -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
|
-
|
|
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,29 +154,55 @@ 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>>>>;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* `related` for a schema whose tables are known only when the code runs (a
|
|
161
|
+
* library that is handed one): the names are strings, checked against the
|
|
162
|
+
* schema when it is called, and what it answers is typed by the caller.
|
|
163
|
+
*/
|
|
164
|
+
interface AnyRelated {
|
|
165
|
+
(table: string, relation: string, columns: readonly string[]): RelatedExpression<string, string, unknown>;
|
|
166
|
+
(table: string, relation: string, options: RelatedOptions<string, readonly RelatedExpression<string, string, unknown>[]>): RelatedExpression<string, string, unknown>;
|
|
145
167
|
}
|
|
146
|
-
/** A relation to read, checked against the schema
|
|
168
|
+
/** A relation to read, checked against the schema: what `related()` builds. */
|
|
147
169
|
interface RelatedSpec {
|
|
148
170
|
schema: AnySchema;
|
|
149
171
|
relation: Relation;
|
|
172
|
+
/** The key it is answered under: the relation's name, or what `.as()` said. */
|
|
173
|
+
alias: string;
|
|
150
174
|
columns: string[];
|
|
151
175
|
with: RelatedSpec[];
|
|
152
176
|
orderBy: [column: string, direction: 'asc' | 'desc'][];
|
|
153
177
|
limit?: number;
|
|
178
|
+
/** The condition `where` answered, as written: its columns are qualified when it is rendered. */
|
|
179
|
+
where?: OperationNode;
|
|
154
180
|
}
|
|
155
181
|
/**
|
|
156
182
|
* A relation as a selection: what `related()` returns. `table` is the table
|
|
157
183
|
* it is a relation of (so `with` takes only the related table's own), `alias`
|
|
158
|
-
* the
|
|
184
|
+
* the key it is answered under — the relation's name, until `.as()` says
|
|
185
|
+
* another.
|
|
159
186
|
*/
|
|
160
187
|
declare class RelatedExpression<TK extends string, A extends string, V> implements AliasedExpression<V, A> {
|
|
161
188
|
readonly table: TK;
|
|
162
189
|
readonly alias: A;
|
|
163
190
|
constructor(spec: RelatedSpec);
|
|
191
|
+
/**
|
|
192
|
+
* The same relation, answered under `name` instead of its own:
|
|
193
|
+
* `related('customers', 'invoices', { columns: ['id'], limit: 1 }).as('latest')`.
|
|
194
|
+
* A new expression — this one keeps its name.
|
|
195
|
+
*/
|
|
196
|
+
as<N extends string>(name: N): RelatedExpression<TK, N, V>;
|
|
164
197
|
get expression(): Expression<V>;
|
|
165
198
|
toOperationNode(): AliasNode;
|
|
166
199
|
}
|
|
200
|
+
/**
|
|
201
|
+
* `related` for a schema: what `defineDatabase()` hands out, and the way to
|
|
202
|
+
* it for code that is handed a schema — typed by the schema's tables, or by
|
|
203
|
+
* strings (`AnyRelated`) when its type names none.
|
|
204
|
+
*/
|
|
205
|
+
declare function createRelated<S extends AnySchema>(schema: S): string extends keyof S ? AnyRelated : Related<S>;
|
|
167
206
|
//#endregion
|
|
168
207
|
//#region src/db/types.d.ts
|
|
169
208
|
/**
|
|
@@ -297,7 +336,13 @@ interface DatabaseInfo {
|
|
|
297
336
|
migrationsDir: string;
|
|
298
337
|
/** Schema import source (relative path) */
|
|
299
338
|
schemaImport: string | null;
|
|
300
|
-
/**
|
|
339
|
+
/**
|
|
340
|
+
* The export of the schema module that is the whole schema — a const shared
|
|
341
|
+
* with other code (`export const schema = { users, posts }`, passed as
|
|
342
|
+
* `defineDatabase({ schema })`). Null when the tables are listed in the call.
|
|
343
|
+
*/
|
|
344
|
+
schemaExport: string | null;
|
|
345
|
+
/** Names of schema tables, when they are listed in the call (empty with `schemaExport`: the const says) */
|
|
301
346
|
schemaTableNames: string[];
|
|
302
347
|
/** Whether the DO should expose a browsable SQL endpoint */
|
|
303
348
|
browsable: boolean | 'development';
|
|
@@ -374,4 +419,4 @@ interface ParsedDatabaseFile {
|
|
|
374
419
|
*/
|
|
375
420
|
declare function defineDatabase<TSchema extends Record<string, SQLiteTableWithColumns<any>>>(config: DatabaseConfig<TSchema>): DatabaseDefinition<TSchema>;
|
|
376
421
|
//#endregion
|
|
377
|
-
export { RelationMap as _, ActionInfo as a,
|
|
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 };
|