@cossackframework/database 0.8.0 → 0.8.1
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/package.json +17 -19
- package/docs/advanced.md +0 -290
- package/docs/comparison.md +0 -188
- package/docs/installation.md +0 -139
- package/docs/introduction.md +0 -126
- package/docs/migrations.md +0 -232
- package/docs/models.md +0 -241
- package/docs/queries.md +0 -261
- package/docs/raw-queries.md +0 -183
- package/docs/relationships.md +0 -243
- package/docs/runtimes.md +0 -422
- package/docs/seeders.md +0 -198
package/docs/runtimes.md
DELETED
|
@@ -1,422 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
title: Runtimes
|
|
3
|
-
description: Configure runtime adapters, custom drivers, and multiple database connections across Node.js, Bun, Workers, and Deno.
|
|
4
|
-
---
|
|
5
|
-
|
|
6
|
-
# Runtimes
|
|
7
|
-
|
|
8
|
-
Runtime adapters live in isolated entry points so a neutral import does not
|
|
9
|
-
eagerly include Node built-ins, native SQLite packages, or unused drivers.
|
|
10
|
-
|
|
11
|
-
| Runtime entry | Adapters |
|
|
12
|
-
| --- | --- |
|
|
13
|
-
| `@cossackframework/database/node` | Node SQLite, better-sqlite3, PostgreSQL, MySQL, libSQL |
|
|
14
|
-
| `@cossackframework/database/bun` | Native Bun SQL for SQLite, PostgreSQL, MySQL |
|
|
15
|
-
| `@cossackframework/database/cloudflare` | D1 and Hyperdrive PostgreSQL/MySQL |
|
|
16
|
-
| `@cossackframework/database/deno` | Injected SQLite, PostgreSQL, MySQL-compatible drivers |
|
|
17
|
-
| `@cossackframework/database/adapter` | Public contracts for custom adapters |
|
|
18
|
-
|
|
19
|
-
## Node.js
|
|
20
|
-
|
|
21
|
-
Node 22's built-in SQLite:
|
|
22
|
-
|
|
23
|
-
```ts
|
|
24
|
-
import { createORM } from "@cossackframework/database";
|
|
25
|
-
import { nodeSQLite } from "@cossackframework/database/node";
|
|
26
|
-
|
|
27
|
-
const orm = createORM({
|
|
28
|
-
adapter: await nodeSQLite({
|
|
29
|
-
filename: "app.db",
|
|
30
|
-
foreignKeys: true,
|
|
31
|
-
}),
|
|
32
|
-
entities,
|
|
33
|
-
});
|
|
34
|
-
```
|
|
35
|
-
|
|
36
|
-
The default filename is `:memory:` and foreign keys are enabled by default.
|
|
37
|
-
|
|
38
|
-
Use better-sqlite3 when an application already depends on it:
|
|
39
|
-
|
|
40
|
-
```sh
|
|
41
|
-
pnpm add better-sqlite3
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
```ts
|
|
45
|
-
import { betterSQLite } from "@cossackframework/database/node";
|
|
46
|
-
|
|
47
|
-
const adapter = await betterSQLite({ filename: "app.db" });
|
|
48
|
-
```
|
|
49
|
-
|
|
50
|
-
PostgreSQL:
|
|
51
|
-
|
|
52
|
-
```sh
|
|
53
|
-
pnpm add pg
|
|
54
|
-
```
|
|
55
|
-
|
|
56
|
-
```ts
|
|
57
|
-
import { postgres } from "@cossackframework/database/node";
|
|
58
|
-
|
|
59
|
-
const adapter = await postgres(process.env.DATABASE_URL!);
|
|
60
|
-
```
|
|
61
|
-
|
|
62
|
-
MySQL:
|
|
63
|
-
|
|
64
|
-
```sh
|
|
65
|
-
pnpm add mysql2
|
|
66
|
-
```
|
|
67
|
-
|
|
68
|
-
```ts
|
|
69
|
-
import { mysql } from "@cossackframework/database/node";
|
|
70
|
-
|
|
71
|
-
const adapter = await mysql({
|
|
72
|
-
host: process.env.MYSQL_HOST,
|
|
73
|
-
port: Number(process.env.MYSQL_PORT ?? 3306),
|
|
74
|
-
user: process.env.MYSQL_USER,
|
|
75
|
-
password: process.env.MYSQL_PASSWORD,
|
|
76
|
-
database: process.env.MYSQL_DATABASE,
|
|
77
|
-
connectionLimit: 10,
|
|
78
|
-
});
|
|
79
|
-
```
|
|
80
|
-
|
|
81
|
-
libSQL or Turso:
|
|
82
|
-
|
|
83
|
-
```sh
|
|
84
|
-
pnpm add @libsql/client
|
|
85
|
-
```
|
|
86
|
-
|
|
87
|
-
```ts
|
|
88
|
-
import { libsql } from "@cossackframework/database/node";
|
|
89
|
-
|
|
90
|
-
const adapter = await libsql({
|
|
91
|
-
url: process.env.TURSO_DATABASE_URL!,
|
|
92
|
-
authToken: process.env.TURSO_AUTH_TOKEN!,
|
|
93
|
-
});
|
|
94
|
-
```
|
|
95
|
-
|
|
96
|
-
Node adapters install `AsyncLocalStorage` request scopes automatically.
|
|
97
|
-
|
|
98
|
-
## Bun
|
|
99
|
-
|
|
100
|
-
Bun uses the native `Bun.SQL` client:
|
|
101
|
-
|
|
102
|
-
```ts
|
|
103
|
-
import { createORM } from "@cossackframework/database";
|
|
104
|
-
import { bun } from "@cossackframework/database/bun";
|
|
105
|
-
|
|
106
|
-
const orm = createORM({
|
|
107
|
-
adapter: bun({
|
|
108
|
-
url: "sqlite://app.db",
|
|
109
|
-
dialect: "sqlite",
|
|
110
|
-
}),
|
|
111
|
-
entities,
|
|
112
|
-
});
|
|
113
|
-
```
|
|
114
|
-
|
|
115
|
-
The adapter accepts SQLite, PostgreSQL, and MySQL. Pass `dialect` explicitly
|
|
116
|
-
when the URL is unconventional:
|
|
117
|
-
|
|
118
|
-
```ts
|
|
119
|
-
const adapter = bun({
|
|
120
|
-
url: process.env.DATABASE_URL,
|
|
121
|
-
dialect: "postgres",
|
|
122
|
-
});
|
|
123
|
-
```
|
|
124
|
-
|
|
125
|
-
An existing compatible Bun SQL client can be injected through `client`.
|
|
126
|
-
Transaction and connection-reservation capabilities follow the methods exposed
|
|
127
|
-
by that client.
|
|
128
|
-
|
|
129
|
-
## Cloudflare D1
|
|
130
|
-
|
|
131
|
-
Create the adapter from a D1 binding:
|
|
132
|
-
|
|
133
|
-
```ts
|
|
134
|
-
import { createORM } from "@cossackframework/database";
|
|
135
|
-
import { d1 } from "@cossackframework/database/cloudflare";
|
|
136
|
-
|
|
137
|
-
interface Env {
|
|
138
|
-
DB: D1Database;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
export async function createRequestORM(env: Env) {
|
|
142
|
-
return createORM({
|
|
143
|
-
adapter: await d1(env.DB),
|
|
144
|
-
entities,
|
|
145
|
-
});
|
|
146
|
-
}
|
|
147
|
-
```
|
|
148
|
-
|
|
149
|
-
D1 compiles SQLite SQL and uses prepared bindings. It supports prepared batches
|
|
150
|
-
but not interactive transactions, savepoints, connection reservation, or query
|
|
151
|
-
cancellation. Unsupported operations throw `UnsupportedCapabilityError`; the ORM
|
|
152
|
-
does not emulate them unsafely.
|
|
153
|
-
|
|
154
|
-
Migration schema operations and migration bookkeeping are submitted in one D1
|
|
155
|
-
batch. General callback-based transactions remain unsupported.
|
|
156
|
-
|
|
157
|
-
The adapter uses async-local request scoping through `node:async_hooks`. Enable
|
|
158
|
-
the Workers compatibility support required by the deployment's compatibility
|
|
159
|
-
date, such as
|
|
160
|
-
[`nodejs_als`](https://developers.cloudflare.com/workers/runtime-apis/nodejs/asynclocalstorage/).
|
|
161
|
-
|
|
162
|
-
## Cloudflare Hyperdrive
|
|
163
|
-
|
|
164
|
-
PostgreSQL through Hyperdrive:
|
|
165
|
-
|
|
166
|
-
```sh
|
|
167
|
-
pnpm add pg
|
|
168
|
-
```
|
|
169
|
-
|
|
170
|
-
```ts
|
|
171
|
-
import {
|
|
172
|
-
hyperdrivePostgres,
|
|
173
|
-
} from "@cossackframework/database/cloudflare";
|
|
174
|
-
|
|
175
|
-
const adapter = await hyperdrivePostgres(env.HYPERDRIVE);
|
|
176
|
-
```
|
|
177
|
-
|
|
178
|
-
MySQL through Hyperdrive:
|
|
179
|
-
|
|
180
|
-
```sh
|
|
181
|
-
pnpm add mysql2
|
|
182
|
-
```
|
|
183
|
-
|
|
184
|
-
```ts
|
|
185
|
-
import {
|
|
186
|
-
hyperdriveMySQL,
|
|
187
|
-
} from "@cossackframework/database/cloudflare";
|
|
188
|
-
|
|
189
|
-
const adapter = await hyperdriveMySQL(env.HYPERDRIVE);
|
|
190
|
-
```
|
|
191
|
-
|
|
192
|
-
Hyperdrive owns the global connection pool. The adapters create request-local
|
|
193
|
-
clients and release them deterministically. Enable `nodejs_compat` for the
|
|
194
|
-
official `pg` and `mysql2` drivers. See Cloudflare's
|
|
195
|
-
[Hyperdrive driver guidance](https://developers.cloudflare.com/hyperdrive/).
|
|
196
|
-
|
|
197
|
-
## Deno
|
|
198
|
-
|
|
199
|
-
Deno accepts an injected driver rather than importing a specific database
|
|
200
|
-
library into the neutral package:
|
|
201
|
-
|
|
202
|
-
```ts
|
|
203
|
-
import { createORM } from "@cossackframework/database";
|
|
204
|
-
import {
|
|
205
|
-
deno,
|
|
206
|
-
type InjectedDenoDriver,
|
|
207
|
-
} from "@cossackframework/database/deno";
|
|
208
|
-
|
|
209
|
-
declare const driver: InjectedDenoDriver;
|
|
210
|
-
|
|
211
|
-
const orm = createORM({
|
|
212
|
-
adapter: deno(driver),
|
|
213
|
-
entities,
|
|
214
|
-
});
|
|
215
|
-
```
|
|
216
|
-
|
|
217
|
-
The injected driver declares its dialect, executes parameterized statements,
|
|
218
|
-
normalizes rows affected and insert IDs, and optionally supplies transactions.
|
|
219
|
-
An application can also inject a runtime-appropriate `ScopeStorage`.
|
|
220
|
-
|
|
221
|
-
Deno can connect through npm-compatible PostgreSQL/MySQL clients or an
|
|
222
|
-
application-provided SQLite driver. See Deno's
|
|
223
|
-
[database connection guide](https://docs.deno.com/examples/connecting_to_databases_tutorial/)
|
|
224
|
-
for runtime permissions and driver choices.
|
|
225
|
-
|
|
226
|
-
## Custom Runtime
|
|
227
|
-
|
|
228
|
-
Cossack ORM does not require runtime support to live in this package. A custom
|
|
229
|
-
runtime can construct an `Adapter` from a third-party `Driver` and, where
|
|
230
|
-
available, an async-local `ScopeStorage`:
|
|
231
|
-
|
|
232
|
-
```ts
|
|
233
|
-
import type {
|
|
234
|
-
Adapter,
|
|
235
|
-
Driver,
|
|
236
|
-
ScopeStorage,
|
|
237
|
-
} from "@cossackframework/database/adapter";
|
|
238
|
-
|
|
239
|
-
export function customRuntime(
|
|
240
|
-
driver: Driver,
|
|
241
|
-
scope?: ScopeStorage<unknown>,
|
|
242
|
-
): Adapter {
|
|
243
|
-
return {
|
|
244
|
-
driver,
|
|
245
|
-
...(scope ? { scope } : {}),
|
|
246
|
-
};
|
|
247
|
-
}
|
|
248
|
-
```
|
|
249
|
-
|
|
250
|
-
The driver owns connection lifecycle, pooling, execution, transactions,
|
|
251
|
-
reservation, cancellation, result normalization, and introspection. Its
|
|
252
|
-
capability flags must describe what it actually implements. See
|
|
253
|
-
[Custom adapters](./advanced.md#custom-adapters) for a complete driver outline.
|
|
254
|
-
|
|
255
|
-
### Multiple connections
|
|
256
|
-
|
|
257
|
-
Like the multiple-data-source pattern used by other ORMs, create one independent
|
|
258
|
-
ORM instance per database connection:
|
|
259
|
-
|
|
260
|
-
```ts
|
|
261
|
-
import { createORM } from "@cossackframework/database";
|
|
262
|
-
import {
|
|
263
|
-
nodeSQLite,
|
|
264
|
-
postgres,
|
|
265
|
-
} from "@cossackframework/database/node";
|
|
266
|
-
import { Post, User } from "./models/primary.js";
|
|
267
|
-
import { AuditEvent } from "./models/analytics.js";
|
|
268
|
-
|
|
269
|
-
export const databases = {
|
|
270
|
-
primary: createORM({
|
|
271
|
-
adapter: await nodeSQLite({ filename: "app.db" }),
|
|
272
|
-
entities: [User, Post],
|
|
273
|
-
}),
|
|
274
|
-
|
|
275
|
-
analytics: createORM({
|
|
276
|
-
adapter: await postgres(process.env.ANALYTICS_DATABASE_URL!),
|
|
277
|
-
entities: [AuditEvent],
|
|
278
|
-
}),
|
|
279
|
-
} as const;
|
|
280
|
-
```
|
|
281
|
-
|
|
282
|
-
Each instance owns its adapter, model metadata, entity snapshots, transaction
|
|
283
|
-
scope, and shutdown lifecycle. It may use a different dialect and a different
|
|
284
|
-
entity list.
|
|
285
|
-
|
|
286
|
-
When a function touches one connection, Active Record syntax remains available
|
|
287
|
-
inside that connection's scope:
|
|
288
|
-
|
|
289
|
-
```ts
|
|
290
|
-
const users = await databases.primary.run(() =>
|
|
291
|
-
User.find({ order: { name: "asc" } })
|
|
292
|
-
);
|
|
293
|
-
|
|
294
|
-
const events = await databases.analytics.run(() =>
|
|
295
|
-
AuditEvent.find({ take: 100 })
|
|
296
|
-
);
|
|
297
|
-
```
|
|
298
|
-
|
|
299
|
-
When one function touches multiple connections, prefer explicit model managers:
|
|
300
|
-
|
|
301
|
-
```ts
|
|
302
|
-
const primaryUsers = databases.primary.model(User);
|
|
303
|
-
const analyticsEvents = databases.analytics.model(AuditEvent);
|
|
304
|
-
|
|
305
|
-
const [users, events] = await Promise.all([
|
|
306
|
-
primaryUsers.find({ order: { name: "asc" } }),
|
|
307
|
-
analyticsEvents.find({ take: 100 }),
|
|
308
|
-
]);
|
|
309
|
-
```
|
|
310
|
-
|
|
311
|
-
This avoids asking a static model method to infer which ORM should handle the
|
|
312
|
-
query. It also supports registering the same entity class with two connections:
|
|
313
|
-
|
|
314
|
-
```ts
|
|
315
|
-
const liveUsers = databases.primary.model(User);
|
|
316
|
-
const archivedUsers = archiveORM.model(User);
|
|
317
|
-
|
|
318
|
-
const [live, archived] = await Promise.all([
|
|
319
|
-
liveUsers.find(),
|
|
320
|
-
archivedUsers.find(),
|
|
321
|
-
]);
|
|
322
|
-
```
|
|
323
|
-
|
|
324
|
-
Do not nest Active Record scopes from different ORM instances. Both scopes
|
|
325
|
-
would be active in the same asynchronous chain, making a static call such as
|
|
326
|
-
`User.find()` ambiguous. Use `orm.model(Entity)`, `orm.sql`, and explicit ORM
|
|
327
|
-
methods for cross-connection work.
|
|
328
|
-
|
|
329
|
-
### Concurrent scopes
|
|
330
|
-
|
|
331
|
-
Independent scopes can run concurrently when each adapter supplies isolated
|
|
332
|
-
async-local storage:
|
|
333
|
-
|
|
334
|
-
```ts
|
|
335
|
-
await Promise.all([
|
|
336
|
-
databases.primary.run(() => User.count()),
|
|
337
|
-
databases.analytics.run(() => AuditEvent.count()),
|
|
338
|
-
]);
|
|
339
|
-
```
|
|
340
|
-
|
|
341
|
-
Built-in Node, Bun, D1, and Hyperdrive adapters provide runtime-appropriate
|
|
342
|
-
scope storage. A custom runtime must supply `ScopeStorage` before using static
|
|
343
|
-
Active Record concurrently. Explicit `orm.model(Entity)` access does not depend
|
|
344
|
-
on global scope lookup.
|
|
345
|
-
|
|
346
|
-
### Transactions across connections
|
|
347
|
-
|
|
348
|
-
A transaction belongs to exactly one ORM:
|
|
349
|
-
|
|
350
|
-
```ts
|
|
351
|
-
await databases.primary.transaction(async () => {
|
|
352
|
-
await databases.primary.model(User).update(
|
|
353
|
-
{ id: userId },
|
|
354
|
-
{ active: false },
|
|
355
|
-
);
|
|
356
|
-
});
|
|
357
|
-
```
|
|
358
|
-
|
|
359
|
-
Starting separate transactions on `primary` and `analytics` does not create a
|
|
360
|
-
distributed transaction. A failure cannot atomically roll back work already
|
|
361
|
-
committed to another database. Use an outbox, saga, or another application-level
|
|
362
|
-
coordination strategy for cross-database consistency.
|
|
363
|
-
|
|
364
|
-
Relations also stay within one ORM instance. For cross-database data, query each
|
|
365
|
-
connection explicitly and combine the results in application code.
|
|
366
|
-
|
|
367
|
-
### Migrations and shutdown
|
|
368
|
-
|
|
369
|
-
Give each database its own config so schema commands cannot target the wrong
|
|
370
|
-
connection:
|
|
371
|
-
|
|
372
|
-
```text
|
|
373
|
-
orm.primary.config.ts
|
|
374
|
-
orm.analytics.config.ts
|
|
375
|
-
```
|
|
376
|
-
|
|
377
|
-
```sh
|
|
378
|
-
cossack-orm migration up --config orm.primary.config.ts
|
|
379
|
-
cossack-orm migration up --config orm.analytics.config.ts
|
|
380
|
-
```
|
|
381
|
-
|
|
382
|
-
Close every long-lived connection during graceful shutdown:
|
|
383
|
-
|
|
384
|
-
```ts
|
|
385
|
-
await Promise.all(
|
|
386
|
-
Object.values(databases).map((orm) => orm.close()),
|
|
387
|
-
);
|
|
388
|
-
```
|
|
389
|
-
|
|
390
|
-
See the runnable
|
|
391
|
-
[multiple-connections SQLite example](../examples/multiple-connections/README.md)
|
|
392
|
-
for separate models, migrations, CLI configs, transactions, and
|
|
393
|
-
application-side result joining.
|
|
394
|
-
|
|
395
|
-
## Closing adapters
|
|
396
|
-
|
|
397
|
-
Long-lived applications usually create one ORM for a process or runtime
|
|
398
|
-
container. Close it during graceful shutdown:
|
|
399
|
-
|
|
400
|
-
```ts
|
|
401
|
-
await orm.close();
|
|
402
|
-
```
|
|
403
|
-
|
|
404
|
-
Request-local adapters may make `close()` a no-op, but calling it remains safe
|
|
405
|
-
and idempotent.
|
|
406
|
-
|
|
407
|
-
## Capabilities
|
|
408
|
-
|
|
409
|
-
Inspect capabilities instead of branching only on a dialect name:
|
|
410
|
-
|
|
411
|
-
```ts
|
|
412
|
-
if (orm.driver.capabilities.returning) {
|
|
413
|
-
// Use a mutation returning clause.
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
if (orm.driver.capabilities.transactions) {
|
|
417
|
-
// Interactive transaction support is available.
|
|
418
|
-
}
|
|
419
|
-
```
|
|
420
|
-
|
|
421
|
-
Capabilities include transactions, savepoints, returning clauses, batches,
|
|
422
|
-
connection reservation, cancellation, parameter limits, and batch limits.
|
package/docs/seeders.md
DELETED
|
@@ -1,198 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
title: Seeders
|
|
3
|
-
description: Define and run ordered, idempotent seed data with scope and transaction policies.
|
|
4
|
-
---
|
|
5
|
-
|
|
6
|
-
# Seeders
|
|
7
|
-
|
|
8
|
-
Seeders create or update application data after migrations have established the
|
|
9
|
-
schema. Cossack ORM provides a reusable `SeederRunner`; `tsx` or another runtime
|
|
10
|
-
loader only executes the TypeScript entry point.
|
|
11
|
-
|
|
12
|
-
## Define a named seeder
|
|
13
|
-
|
|
14
|
-
```ts
|
|
15
|
-
import { defineSeeder } from "@cossackframework/database";
|
|
16
|
-
import { User } from "../src/models/User.js";
|
|
17
|
-
|
|
18
|
-
export const usersSeeder = defineSeeder({
|
|
19
|
-
name: "users",
|
|
20
|
-
transaction: "auto",
|
|
21
|
-
|
|
22
|
-
async run() {
|
|
23
|
-
const email = "admin@example.com";
|
|
24
|
-
const existing = await User.findOne({
|
|
25
|
-
where: { email },
|
|
26
|
-
});
|
|
27
|
-
|
|
28
|
-
if (!existing) {
|
|
29
|
-
await User.create({
|
|
30
|
-
email,
|
|
31
|
-
name: "Administrator",
|
|
32
|
-
}).save();
|
|
33
|
-
}
|
|
34
|
-
},
|
|
35
|
-
});
|
|
36
|
-
```
|
|
37
|
-
|
|
38
|
-
`SeederRunner` establishes ORM scope, so static Active Record calls work inside
|
|
39
|
-
`run()` without another `orm.run()` wrapper.
|
|
40
|
-
|
|
41
|
-
The context also exposes bound ORM and SQL access:
|
|
42
|
-
|
|
43
|
-
```ts
|
|
44
|
-
export const settingsSeeder = defineSeeder({
|
|
45
|
-
name: "settings",
|
|
46
|
-
|
|
47
|
-
async run({ orm, sql, signal }) {
|
|
48
|
-
// SQLite/PostgreSQL upsert syntax; use the model API for portable upserts.
|
|
49
|
-
await sql`
|
|
50
|
-
INSERT INTO ${sql.id("settings")}
|
|
51
|
-
(${sql.id("key")}, ${sql.id("value")})
|
|
52
|
-
VALUES (${"theme"}, ${"system"})
|
|
53
|
-
ON CONFLICT (${sql.id("key")})
|
|
54
|
-
DO UPDATE SET ${sql.id("value")} = ${"system"}
|
|
55
|
-
`;
|
|
56
|
-
},
|
|
57
|
-
});
|
|
58
|
-
```
|
|
59
|
-
|
|
60
|
-
## Export one ordered list
|
|
61
|
-
|
|
62
|
-
```ts
|
|
63
|
-
// seeders/index.ts
|
|
64
|
-
import { rolesSeeder } from "./roles.seeder.js";
|
|
65
|
-
import { usersSeeder } from "./users.seeder.js";
|
|
66
|
-
import { postsSeeder } from "./posts.seeder.js";
|
|
67
|
-
|
|
68
|
-
// Configuration order is execution order.
|
|
69
|
-
export const seeders = [
|
|
70
|
-
rolesSeeder,
|
|
71
|
-
usersSeeder,
|
|
72
|
-
postsSeeder,
|
|
73
|
-
] as const;
|
|
74
|
-
```
|
|
75
|
-
|
|
76
|
-
Seeder names must be non-empty and unique. Execution is sequential and stops at
|
|
77
|
-
the first failure, preserving declared dependencies.
|
|
78
|
-
|
|
79
|
-
Register the same list in `orm.config.ts`:
|
|
80
|
-
|
|
81
|
-
```ts
|
|
82
|
-
export default defineConfig({
|
|
83
|
-
adapter: createAdapter,
|
|
84
|
-
entities,
|
|
85
|
-
migrations,
|
|
86
|
-
seeds: seeders,
|
|
87
|
-
});
|
|
88
|
-
```
|
|
89
|
-
|
|
90
|
-
## Run seeders
|
|
91
|
-
|
|
92
|
-
```sh
|
|
93
|
-
cossack-orm seed list
|
|
94
|
-
cossack-orm seed run
|
|
95
|
-
cossack-orm seed run --only users,posts
|
|
96
|
-
```
|
|
97
|
-
|
|
98
|
-
`--only` selects names but preserves configuration order. Unknown names fail
|
|
99
|
-
with a list of available seeders.
|
|
100
|
-
|
|
101
|
-
Programmatic execution uses the same runner:
|
|
102
|
-
|
|
103
|
-
```ts
|
|
104
|
-
import { SeederRunner } from "@cossackframework/database";
|
|
105
|
-
|
|
106
|
-
const runner = new SeederRunner(orm, seeders);
|
|
107
|
-
|
|
108
|
-
try {
|
|
109
|
-
const results = await runner.run({
|
|
110
|
-
only: ["users", "posts"],
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
for (const result of results) {
|
|
114
|
-
console.log(
|
|
115
|
-
result.name,
|
|
116
|
-
result.durationMs,
|
|
117
|
-
result.usedTransaction,
|
|
118
|
-
);
|
|
119
|
-
}
|
|
120
|
-
} finally {
|
|
121
|
-
await orm.close();
|
|
122
|
-
}
|
|
123
|
-
```
|
|
124
|
-
|
|
125
|
-
Use an `AbortSignal` for cooperative cancellation:
|
|
126
|
-
|
|
127
|
-
```ts
|
|
128
|
-
const controller = new AbortController();
|
|
129
|
-
|
|
130
|
-
await runner.run({
|
|
131
|
-
signal: controller.signal,
|
|
132
|
-
});
|
|
133
|
-
```
|
|
134
|
-
|
|
135
|
-
The signal is exposed to the seeder context. A seeder should pass it to any
|
|
136
|
-
lower-level operation that supports cancellation.
|
|
137
|
-
|
|
138
|
-
## Transaction policies
|
|
139
|
-
|
|
140
|
-
Each seeder declares one of three policies:
|
|
141
|
-
|
|
142
|
-
| Policy | Behavior |
|
|
143
|
-
| --- | --- |
|
|
144
|
-
| `"auto"` | Use one transaction when supported; otherwise run without one |
|
|
145
|
-
| `"required"` | Fail before executing when interactive transactions are unavailable |
|
|
146
|
-
| `"none"` | Never create a runner-managed transaction |
|
|
147
|
-
|
|
148
|
-
`"auto"` is the default.
|
|
149
|
-
|
|
150
|
-
```ts
|
|
151
|
-
export const billingSeeder = defineSeeder({
|
|
152
|
-
name: "billing",
|
|
153
|
-
transaction: "required",
|
|
154
|
-
async run() {
|
|
155
|
-
// All writes must commit or roll back together.
|
|
156
|
-
},
|
|
157
|
-
});
|
|
158
|
-
```
|
|
159
|
-
|
|
160
|
-
D1 does not support callback-based interactive transactions. An `"auto"` seeder
|
|
161
|
-
runs without one, while `"required"` fails with a `SeederError` whose cause is
|
|
162
|
-
`UnsupportedCapabilityError`. Use `"none"` and a database-specific prepared
|
|
163
|
-
batch when D1 seed work must be atomic.
|
|
164
|
-
|
|
165
|
-
## Make seeders idempotent
|
|
166
|
-
|
|
167
|
-
Seeders are not tracked like migrations because they commonly need to be
|
|
168
|
-
rerunnable and environment-specific. Use stable natural keys, existence checks,
|
|
169
|
-
or upserts:
|
|
170
|
-
|
|
171
|
-
```ts
|
|
172
|
-
await User.upsert(
|
|
173
|
-
{
|
|
174
|
-
email: "admin@example.com",
|
|
175
|
-
name: "Administrator",
|
|
176
|
-
},
|
|
177
|
-
["email"],
|
|
178
|
-
);
|
|
179
|
-
```
|
|
180
|
-
|
|
181
|
-
Avoid random identifiers for records that must not be duplicated. Keep
|
|
182
|
-
production-only or destructive data policies in the application/framework CLI,
|
|
183
|
-
where environment and confirmation information is available.
|
|
184
|
-
|
|
185
|
-
## Framework integration
|
|
186
|
-
|
|
187
|
-
A framework should:
|
|
188
|
-
|
|
189
|
-
1. Load the application's `orm.config.ts`.
|
|
190
|
-
2. Construct its normal ORM instance.
|
|
191
|
-
3. Delegate execution to `SeederRunner`.
|
|
192
|
-
4. Add framework-specific environment and production confirmation checks.
|
|
193
|
-
5. Close the ORM in `finally`.
|
|
194
|
-
|
|
195
|
-
Do not create a second seeding engine or reimplement transaction behavior.
|
|
196
|
-
|
|
197
|
-
The complete pattern is available in the
|
|
198
|
-
[SQLite starter](../examples/sqlite-starter/README.md).
|