durable-db 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +170 -4
- 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 +215 -8
- package/dist/defineDatabase-Bww_w_n5.d.ts +407 -0
- package/dist/defineDatabase-CULpd87Z.js +1134 -0
- package/dist/describeAction-CEKfxTQ4.js +24 -0
- package/dist/{index-rlnVnzJJ.d.ts → index-BQ1hHyrq.d.ts} +49 -2
- package/dist/index.d.ts +19 -3
- package/dist/index.js +3 -2
- package/dist/kysely-DCQRqT62.js +279 -0
- package/dist/{parser-DyepmXzE.js → parser-mUnAtllk.js} +65 -15
- package/dist/registry.d.ts +15 -0
- package/dist/registry.js +30 -2
- package/dist/schema.d.ts +15 -2
- package/dist/testing/index.js +14 -4
- package/dist/vite/durableDb.d.ts +1 -1
- package/dist/vite/durableDb.js +55 -4
- package/package.json +1 -1
- package/virtual.d.ts +12 -0
- package/dist/defineDatabase-595bNB6M.js +0 -110
- package/dist/defineDatabase-By401iHp.d.ts +0 -200
- package/dist/kysely-DvAoap5h.js +0 -631
package/README.md
CHANGED
|
@@ -23,6 +23,7 @@ Define your schema with [Drizzle](https://orm.drizzle.team/), query with [Kysely
|
|
|
23
23
|
- [Production Migrations](#production-migrations)
|
|
24
24
|
- [Breakpoints](#breakpoints)
|
|
25
25
|
- [Adding a required column](#adding-a-required-column)
|
|
26
|
+
- [Rebuilding a table that others reference](#rebuilding-a-table-that-others-reference)
|
|
26
27
|
- [Epoch System](#epoch-system)
|
|
27
28
|
- [Typical Workflow](#typical-workflow)
|
|
28
29
|
- [Vite Plugin](#vite-plugin)
|
|
@@ -31,6 +32,8 @@ Define your schema with [Drizzle](https://orm.drizzle.team/), query with [Kysely
|
|
|
31
32
|
- [Instance Strategies](#instance-strategies)
|
|
32
33
|
- [Action-to-Action Calls](#action-to-action-calls)
|
|
33
34
|
- [The Outbox](#the-outbox)
|
|
35
|
+
- [Shared Actions](#shared-actions)
|
|
36
|
+
- [Relations](#relations)
|
|
34
37
|
- [PITR Safety](#pitr-safety)
|
|
35
38
|
- [Recovery Workflows](#recovery-workflows)
|
|
36
39
|
- [Architecture](#architecture)
|
|
@@ -64,7 +67,11 @@ Column names are derived from JS property keys and auto-converted to snake_case
|
|
|
64
67
|
|
|
65
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`.
|
|
66
69
|
|
|
67
|
-
|
|
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.
|
|
68
75
|
|
|
69
76
|
### 3. Define your database
|
|
70
77
|
|
|
@@ -78,6 +85,20 @@ export const { action } = defineDatabase({
|
|
|
78
85
|
});
|
|
79
86
|
```
|
|
80
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
|
+
|
|
81
102
|
### 4. Write actions
|
|
82
103
|
|
|
83
104
|
```ts
|
|
@@ -184,7 +205,7 @@ The destructured `action` function is your factory for creating database actions
|
|
|
184
205
|
|
|
185
206
|
| Option | Type | Default | Description |
|
|
186
207
|
|--------|------|---------|-------------|
|
|
187
|
-
| `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 |
|
|
188
209
|
| `instance` | `'per-tenant' \| 'global'` | `'per-tenant'` | Instance strategy (see [Instance Strategies](#instance-strategies)) |
|
|
189
210
|
| `transport` | `'rpc' \| 'websocket'` | `'rpc'` | Transport for action stubs. WebSocket uses Cloudflare's 20:1 message billing ratio for cheaper high-volume calls |
|
|
190
211
|
| `browsable` | `boolean \| 'development'` | `false` | Enable Outerbase SQL browsing (see [Outerbase Studio](#outerbase-studio-integration)) |
|
|
@@ -692,6 +713,20 @@ SQLite rejects `ALTER TABLE … ADD … NOT NULL` without a default on a table t
|
|
|
692
713
|
|
|
693
714
|
The same holds for renames: answering a rename question with "create" (or `--no-renames`) adds the new column — `NOT NULL` without a default fails the same way — and drops the old one with its data.
|
|
694
715
|
|
|
716
|
+
### Rebuilding a table that others reference
|
|
717
|
+
|
|
718
|
+
SQLite cannot alter most of a table in place, so many schema changes become a rebuild: `CREATE TABLE __new_t`, copy the rows, `DROP TABLE t`, `ALTER TABLE __new_t RENAME TO t`, with `PRAGMA foreign_keys=OFF` around it. In a Durable Object that pragma does nothing — foreign keys are always enforced — so the `DROP` would run the `ON DELETE` of every table that references `t`: `cascade` would delete those rows, `set null` empty their column.
|
|
719
|
+
|
|
720
|
+
The runtime stands in for the pragma. While a chunk rebuilds a table, the rows of the tables that reference it (and of those that reference them) are moved aside before the `DROP` and put back after the `RENAME`, with none of their triggers run, and then checked: a rebuild that leaves out rows others still reference fails the migration, and nothing of it is kept. A referenced table that is dropped for good is dropped at the end of its chunk, once the tables that referenced it were rebuilt without the reference.
|
|
721
|
+
|
|
722
|
+
What to know when writing a migration by hand:
|
|
723
|
+
|
|
724
|
+
- keep a rebuild in one chunk: with a `--> breakpoint` between its `DROP TABLE` and its `RENAME TO`, the rows that reference the table are not kept;
|
|
725
|
+
- drop the old table, then rename the new one into its place — renaming the old one away first (`ALTER TABLE t RENAME TO old_t`) is not recognised as a rebuild;
|
|
726
|
+
- finish one rebuild before the next begins: `DROP a`, `DROP b`, then the renames, fails with a message that says so;
|
|
727
|
+
- a table that is dropped and created again (`DROP TABLE t`, `CREATE TABLE t`) loses its rows on purpose, and the rows that cascade from them;
|
|
728
|
+
- the rows that are moved aside are copied twice, so rebuilding a table costs in proportion to the rows that reference it.
|
|
729
|
+
|
|
695
730
|
### Epoch System
|
|
696
731
|
|
|
697
732
|
In development, each database instance key gets an epoch suffix to enable clean resets:
|
|
@@ -1091,6 +1126,135 @@ export const createUser = action({
|
|
|
1091
1126
|
|
|
1092
1127
|
---
|
|
1093
1128
|
|
|
1129
|
+
## Shared Actions
|
|
1130
|
+
|
|
1131
|
+
For a library that works on any schema — a query executor, an exporter — an action can be registered once and run in **every** database. It is opt-in: nothing changes for an app that never calls it.
|
|
1132
|
+
|
|
1133
|
+
```ts
|
|
1134
|
+
import { registerSharedAction } from 'durable-db/registry';
|
|
1135
|
+
|
|
1136
|
+
registerSharedAction('export:rows', {
|
|
1137
|
+
validator: (args) => args as { table: string },
|
|
1138
|
+
handler: async (db, args, ctx) => db.selectFrom(args.table).selectAll().execute(),
|
|
1139
|
+
});
|
|
1140
|
+
```
|
|
1141
|
+
|
|
1142
|
+
`stub.rpc('export:rows', { table: 'users' })` then runs it in whichever Durable Object is called, with that database's `db` and the action context. The module that registers it has to be loaded in the Durable Object's isolate (anything the worker's entry imports is). A database's own action of the same name wins, so give a shared action a name no export can have (`"lib:name"`).
|
|
1143
|
+
|
|
1144
|
+
`virtual:durable-db/__databases` lists what the plugin discovered — `databases: [{ name, bindingName, className, instance, schema }]`, the tables being the schema module's own objects — for a library that needs to know which database a table belongs to. It is generated only when something imports it.
|
|
1145
|
+
|
|
1146
|
+
`describeAction(action)` (from `durable-db`) answers what an action is, given the function an app exports: `{ database, name, args }`, `args` being its compiled schema — `.toJsonSchema()` for a library that maps actions to an API of its own. It reads what the build registered for the call site (in tests, where nothing is compiled, `database` and `name` are `null`), and `undefined` for anything that is not an action.
|
|
1147
|
+
|
|
1148
|
+
```ts
|
|
1149
|
+
import { describeAction } from 'durable-db';
|
|
1150
|
+
import { createInvoice } from './databases/billing.actions';
|
|
1151
|
+
|
|
1152
|
+
describeAction(createInvoice)?.args?.toJsonSchema();
|
|
1153
|
+
// { type: 'object', properties: { customerId: { type: 'string' }, … }, required: [ … ] }
|
|
1154
|
+
```
|
|
1155
|
+
|
|
1156
|
+
---
|
|
1157
|
+
|
|
1158
|
+
## Relations
|
|
1159
|
+
|
|
1160
|
+
A foreign key is a relation. Declare it once, on the column, and read along it in both directions — nothing else to write, nothing generated.
|
|
1161
|
+
|
|
1162
|
+
```ts
|
|
1163
|
+
import { index, integer, table, text } from 'durable-db/schema';
|
|
1164
|
+
|
|
1165
|
+
export const customers = table('customers', {
|
|
1166
|
+
id: text().primaryKey(),
|
|
1167
|
+
name: text().notNull(),
|
|
1168
|
+
});
|
|
1169
|
+
|
|
1170
|
+
export const invoices = table('invoices', {
|
|
1171
|
+
id: text().primaryKey(),
|
|
1172
|
+
number: integer().notNull(),
|
|
1173
|
+
customerId: text().notNull().references(() => customers.id),
|
|
1174
|
+
});
|
|
1175
|
+
|
|
1176
|
+
export const invoiceLines = table(
|
|
1177
|
+
'invoice_lines',
|
|
1178
|
+
{
|
|
1179
|
+
id: text().primaryKey(),
|
|
1180
|
+
invoiceId: text().notNull().references(() => invoices.id, { onDelete: 'cascade' }),
|
|
1181
|
+
description: text().notNull(),
|
|
1182
|
+
},
|
|
1183
|
+
(t) => [index('invoice_lines_invoice').on(t.invoiceId)],
|
|
1184
|
+
);
|
|
1185
|
+
|
|
1186
|
+
export const schema = { customers, invoices, invoiceLines };
|
|
1187
|
+
```
|
|
1188
|
+
|
|
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.
|
|
1190
|
+
|
|
1191
|
+
```ts
|
|
1192
|
+
import { schema } from './schema';
|
|
1193
|
+
|
|
1194
|
+
export const { action, related, relations } = defineDatabase({ schema });
|
|
1195
|
+
|
|
1196
|
+
export const listInvoices = action({
|
|
1197
|
+
args: {},
|
|
1198
|
+
handler: async (db) =>
|
|
1199
|
+
db
|
|
1200
|
+
.selectFrom('invoices')
|
|
1201
|
+
.select([
|
|
1202
|
+
'invoices.number',
|
|
1203
|
+
related('invoices', 'customer', ['name']),
|
|
1204
|
+
related('invoices', 'invoiceLines', {
|
|
1205
|
+
columns: ['description'],
|
|
1206
|
+
orderBy: { id: 'asc' },
|
|
1207
|
+
limit: 50,
|
|
1208
|
+
}),
|
|
1209
|
+
])
|
|
1210
|
+
.execute(),
|
|
1211
|
+
// { number: number; customer: { name: string }; invoiceLines: { description: string }[] }[]
|
|
1212
|
+
});
|
|
1213
|
+
```
|
|
1214
|
+
|
|
1215
|
+
**Names.** The forward side (`one`) is the column's property without its `Id` (`customerId` → `customer`); it is nullable when the column is. The inverse side (`many`) is the schema key of the table that holds the foreign key (`customers` → `invoices`). A table that points at the same target twice gets `<key>As<Forward>` for each (`invoicesAsCustomer`, `invoicesAsReferee`).
|
|
1216
|
+
|
|
1217
|
+
**Nesting.** `with` reads relations of the related table, to any depth — still one SQL query:
|
|
1218
|
+
|
|
1219
|
+
```ts
|
|
1220
|
+
related('customers', 'invoices', {
|
|
1221
|
+
columns: ['number'],
|
|
1222
|
+
orderBy: { number: 'desc' },
|
|
1223
|
+
with: [related('invoices', 'invoiceLines', ['description'])],
|
|
1224
|
+
});
|
|
1225
|
+
```
|
|
1226
|
+
|
|
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.
|
|
1237
|
+
|
|
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.
|
|
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
|
+
|
|
1249
|
+
What it does not do yet:
|
|
1250
|
+
|
|
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.
|
|
1252
|
+
- Composite foreign keys (`foreignKey({ columns: [a, b] })`) are not relations.
|
|
1253
|
+
- `related()` names the table as the query does: `selectFrom('invoices')`, not `selectFrom('invoices as i')`. It needs the default `camelCase` mapping.
|
|
1254
|
+
- No `where` on a relation; filter in the action.
|
|
1255
|
+
|
|
1256
|
+
---
|
|
1257
|
+
|
|
1094
1258
|
## PITR Safety
|
|
1095
1259
|
|
|
1096
1260
|
On Cloudflare with Point-in-Time Recovery (PITR) enabled, migrations are protected with automatic snapshots.
|
|
@@ -1219,9 +1383,11 @@ The library includes plugins for transparent data mapping between JavaScript and
|
|
|
1219
1383
|
|
|
1220
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.
|
|
1221
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.
|
|
1222
|
-
- **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.
|
|
1223
1389
|
|
|
1224
|
-
All
|
|
1390
|
+
All of them are configured by `createDrizzlePlugins(schema)`.
|
|
1225
1391
|
|
|
1226
1392
|
---
|
|
1227
1393
|
|
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-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 {
|
|
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 { a as ActionInfo, c as DatabaseDefinition, d as InferArgs, f as ParsedDatabaseFile, i as ActionContext, l as DatabaseInfo, n as Action, o as ArgsSchema, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely } from "../defineDatabase-
|
|
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
|
|
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, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, type SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, outboxSink, queueOutboxSink, 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 };
|