@cossackframework/database 0.8.1 → 0.8.2

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.
@@ -0,0 +1,243 @@
1
+ ---
2
+ title: Relationships
3
+ description: Define, persist, and explicitly load one-to-one, one-to-many, many-to-one, and many-to-many relations.
4
+ ---
5
+
6
+ # Relationships
7
+
8
+ Relations describe links between registered entities. They are explicit:
9
+ Cossack ORM does not lazy-load a property when it is accessed. Request the
10
+ relations needed by a query with `relations` or `with`.
11
+
12
+ ## One-to-many and many-to-one
13
+
14
+ A post owns the foreign key to its author:
15
+
16
+ ```ts
17
+ // User.ts
18
+ import {
19
+ BaseEntity,
20
+ Column,
21
+ Entity,
22
+ OneToMany,
23
+ PrimaryGeneratedColumn,
24
+ type Relation,
25
+ } from "@cossackframework/database";
26
+ import { Post } from "./Post.js";
27
+
28
+ @Entity()
29
+ export class User extends BaseEntity {
30
+ @PrimaryGeneratedColumn()
31
+ declare id: number;
32
+
33
+ @Column()
34
+ declare name: string;
35
+
36
+ @OneToMany(() => Post, (post) => post.author)
37
+ declare posts: Relation<Post[]>;
38
+ }
39
+ ```
40
+
41
+ ```ts
42
+ // Post.ts
43
+ import {
44
+ BaseEntity,
45
+ Column,
46
+ Entity,
47
+ JoinColumn,
48
+ ManyToOne,
49
+ PrimaryGeneratedColumn,
50
+ type Relation,
51
+ } from "@cossackframework/database";
52
+ import { User } from "./User.js";
53
+
54
+ @Entity()
55
+ export class Post extends BaseEntity {
56
+ @PrimaryGeneratedColumn()
57
+ declare id: number;
58
+
59
+ @Column()
60
+ declare title: string;
61
+
62
+ @Column({ name: "author_id", type: "integer" })
63
+ declare authorId: number;
64
+
65
+ @ManyToOne(() => User, (user) => user.posts, {
66
+ nullable: false,
67
+ onDelete: "CASCADE",
68
+ })
69
+ @JoinColumn({ name: "author_id", referencedColumnName: "id" })
70
+ declare author: Relation<User>;
71
+ }
72
+ ```
73
+
74
+ Keep the physical foreign-key column as a decorated property when application
75
+ code needs to query or assign it directly. Assigning the owning relation also
76
+ synchronizes that property before persistence:
77
+
78
+ ```ts
79
+ await orm.run(async () => {
80
+ const user = User.create({ name: "Ada Lovelace" });
81
+ await user.save();
82
+
83
+ const post = Post.create({ title: "Poetical Science" });
84
+ post.author = user;
85
+ await post.save();
86
+ });
87
+ ```
88
+
89
+ ## Loading relations
90
+
91
+ ```ts
92
+ const users = await User.find({
93
+ relations: ["posts"],
94
+ order: { name: "asc" },
95
+ });
96
+
97
+ const posts = await Post.find({
98
+ with: ["author"],
99
+ });
100
+ ```
101
+
102
+ `relations` and `with` are aliases. The loader collects relation keys and
103
+ fetches related rows in batches, chunked according to the adapter parameter
104
+ limit. This avoids issuing one query per parent row.
105
+
106
+ Relations are not recursive by default. Request only the relation properties
107
+ needed by the operation.
108
+
109
+ ## One-to-one
110
+
111
+ Place `@JoinColumn()` on the owning side:
112
+
113
+ ```ts
114
+ @Entity()
115
+ class UserProfile extends BaseEntity {
116
+ @PrimaryGeneratedColumn()
117
+ declare id: number;
118
+
119
+ @Column("text")
120
+ declare biography: string;
121
+
122
+ @OneToOne(() => User, (user) => user.profile, {
123
+ nullable: false,
124
+ onDelete: "CASCADE",
125
+ })
126
+ @JoinColumn({ name: "user_id", referencedColumnName: "id" })
127
+ declare user: Relation<User>;
128
+ }
129
+
130
+ @Entity()
131
+ class User extends BaseEntity {
132
+ @PrimaryGeneratedColumn()
133
+ declare id: number;
134
+
135
+ @OneToOne(() => UserProfile, (profile) => profile.user)
136
+ declare profile: Relation<UserProfile>;
137
+ }
138
+ ```
139
+
140
+ ## Many-to-many
141
+
142
+ Put `@JoinTable()` on exactly one side:
143
+
144
+ ```ts
145
+ @Entity()
146
+ class User extends BaseEntity {
147
+ @PrimaryGeneratedColumn()
148
+ declare id: number;
149
+
150
+ @ManyToMany(() => Role, (role) => role.users, {
151
+ cascade: ["insert", "update"],
152
+ })
153
+ @JoinTable({
154
+ name: "user_roles",
155
+ joinColumn: {
156
+ name: "user_id",
157
+ referencedColumnName: "id",
158
+ },
159
+ inverseJoinColumn: {
160
+ name: "role_id",
161
+ referencedColumnName: "id",
162
+ },
163
+ })
164
+ declare roles: Relation<Role[]>;
165
+ }
166
+
167
+ @Entity()
168
+ class Role extends BaseEntity {
169
+ @PrimaryGeneratedColumn()
170
+ declare id: number;
171
+
172
+ @Column({ unique: true })
173
+ declare name: string;
174
+
175
+ @ManyToMany(() => User, (user) => user.roles)
176
+ declare users: Relation<User[]>;
177
+ }
178
+ ```
179
+
180
+ Join-table synchronization occurs on the owning side when the relation opts into
181
+ the relevant insert/update cascade.
182
+
183
+ ## Cascades
184
+
185
+ Cascades are disabled by default:
186
+
187
+ ```ts
188
+ @OneToMany(() => Post, (post) => post.author, {
189
+ cascade: ["insert", "update"],
190
+ })
191
+ declare posts: Relation<Post[]>;
192
+ ```
193
+
194
+ `cascade: true` enables both insert and update cascades. Prefer the explicit
195
+ array in reusable packages so the persistence behavior is visible.
196
+
197
+ Delete cascades are database behavior configured with `onDelete`. Cossack ORM
198
+ does not walk an in-memory object graph and delete related entities.
199
+
200
+ ## Nullable and logical relations
201
+
202
+ Use `nullable` to describe whether an owning relation may be absent:
203
+
204
+ ```ts
205
+ @ManyToOne(() => Team, (team) => team.members, {
206
+ nullable: true,
207
+ })
208
+ @JoinColumn({ name: "team_id" })
209
+ declare team: Relation<Team | null>;
210
+ ```
211
+
212
+ Set `createForeignKeyConstraints: false` for a logical relation that should
213
+ appear in ORM metadata without creating a database foreign-key constraint:
214
+
215
+ ```ts
216
+ @ManyToOne(() => ExternalAccount, {
217
+ createForeignKeyConstraints: false,
218
+ })
219
+ @JoinColumn({ name: "external_account_id" })
220
+ declare externalAccount: Relation<ExternalAccount>;
221
+ ```
222
+
223
+ Logical and physical relation provenance is included in `orm.schema()` for
224
+ Studio and other tooling.
225
+
226
+ ## Registration and circular imports
227
+
228
+ Relation targets are callbacks so circular model references resolve after class
229
+ evaluation:
230
+
231
+ ```ts
232
+ @ManyToOne(() => User, (user) => user.posts)
233
+ declare author: Relation<User>;
234
+ ```
235
+
236
+ Still register every target:
237
+
238
+ ```ts
239
+ export const entities = [User, Post, Role, UserProfile] as const;
240
+ ```
241
+
242
+ ORM creation validates missing targets, invalid inverse properties, and
243
+ unresolved join metadata.
@@ -0,0 +1,426 @@
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, Turso |
14
+ | `@cossackframework/database/deno` | Turso embedded SQLite, PostgreSQL, MySQL, remote Turso, or an injected driver |
15
+ | `@cossackframework/database/bun` | Native Bun SQL for SQLite, PostgreSQL, MySQL |
16
+ | `@cossackframework/database/cloudflare` | D1 and Hyperdrive PostgreSQL/MySQL |
17
+ | `@cossackframework/database/deno` | Injected SQLite, PostgreSQL, MySQL-compatible drivers |
18
+ | `@cossackframework/database/adapter` | Public contracts for custom adapters |
19
+
20
+ ## Node.js
21
+
22
+ Node 22's built-in SQLite:
23
+
24
+ ```ts
25
+ import { createORM } from "@cossackframework/database";
26
+ import { nodeSQLite } from "@cossackframework/database/node";
27
+
28
+ const orm = createORM({
29
+ adapter: await nodeSQLite({
30
+ filename: "app.db",
31
+ foreignKeys: true,
32
+ }),
33
+ entities,
34
+ });
35
+ ```
36
+
37
+ The default filename is `:memory:` and foreign keys are enabled by default.
38
+
39
+ Use better-sqlite3 when an application already depends on it:
40
+
41
+ ```sh
42
+ pnpm add better-sqlite3
43
+ ```
44
+
45
+ ```ts
46
+ import { betterSQLite } from "@cossackframework/database/node";
47
+
48
+ const adapter = await betterSQLite({ filename: "app.db" });
49
+ ```
50
+
51
+ PostgreSQL:
52
+
53
+ ```sh
54
+ pnpm add pg
55
+ ```
56
+
57
+ ```ts
58
+ import { postgres } from "@cossackframework/database/node";
59
+
60
+ const adapter = await postgres(process.env.DATABASE_URL!);
61
+ ```
62
+
63
+ MySQL:
64
+
65
+ ```sh
66
+ pnpm add mysql2
67
+ ```
68
+
69
+ ```ts
70
+ import { mysql } from "@cossackframework/database/node";
71
+
72
+ const adapter = await mysql({
73
+ host: process.env.MYSQL_HOST,
74
+ port: Number(process.env.MYSQL_PORT ?? 3306),
75
+ user: process.env.MYSQL_USER,
76
+ password: process.env.MYSQL_PASSWORD,
77
+ database: process.env.MYSQL_DATABASE,
78
+ connectionLimit: 10,
79
+ });
80
+ ```
81
+
82
+ Turso (choose the client matching the connection):
83
+
84
+ ```sh
85
+ pnpm add @tursodatabase/database # embedded SQLite / Desktop
86
+ pnpm add @tursodatabase/serverless # remote Turso / Deno Deploy
87
+ ```
88
+
89
+ ```ts
90
+ import { turso } from "@cossackframework/database/node";
91
+
92
+ const embedded = await turso({ path: "./app.turso" });
93
+
94
+ const adapter = await turso({
95
+ url: process.env.TURSO_DATABASE_URL!,
96
+ authToken: process.env.TURSO_AUTH_TOKEN!,
97
+ });
98
+ ```
99
+
100
+ Node adapters install `AsyncLocalStorage` request scopes automatically.
101
+
102
+ ## Bun
103
+
104
+ Bun uses the native `Bun.SQL` client:
105
+
106
+ ```ts
107
+ import { createORM } from "@cossackframework/database";
108
+ import { bun } from "@cossackframework/database/bun";
109
+
110
+ const orm = createORM({
111
+ adapter: bun({
112
+ url: "sqlite://app.db",
113
+ dialect: "sqlite",
114
+ }),
115
+ entities,
116
+ });
117
+ ```
118
+
119
+ The adapter accepts SQLite, PostgreSQL, and MySQL. Pass `dialect` explicitly
120
+ when the URL is unconventional:
121
+
122
+ ```ts
123
+ const adapter = bun({
124
+ url: process.env.DATABASE_URL,
125
+ dialect: "postgres",
126
+ });
127
+ ```
128
+
129
+ An existing compatible Bun SQL client can be injected through `client`.
130
+ Transaction and connection-reservation capabilities follow the methods exposed
131
+ by that client.
132
+
133
+ ## Cloudflare D1
134
+
135
+ Create the adapter from a D1 binding:
136
+
137
+ ```ts
138
+ import { createORM } from "@cossackframework/database";
139
+ import { d1 } from "@cossackframework/database/cloudflare";
140
+
141
+ interface Env {
142
+ DB: D1Database;
143
+ }
144
+
145
+ export async function createRequestORM(env: Env) {
146
+ return createORM({
147
+ adapter: await d1(env.DB),
148
+ entities,
149
+ });
150
+ }
151
+ ```
152
+
153
+ D1 compiles SQLite SQL and uses prepared bindings. It supports prepared batches
154
+ but not interactive transactions, savepoints, connection reservation, or query
155
+ cancellation. Unsupported operations throw `UnsupportedCapabilityError`; the ORM
156
+ does not emulate them unsafely.
157
+
158
+ Migration schema operations and migration bookkeeping are submitted in one D1
159
+ batch. General callback-based transactions remain unsupported.
160
+
161
+ The adapter uses async-local request scoping through `node:async_hooks`. Enable
162
+ the Workers compatibility support required by the deployment's compatibility
163
+ date, such as
164
+ [`nodejs_als`](https://developers.cloudflare.com/workers/runtime-apis/nodejs/asynclocalstorage/).
165
+
166
+ ## Cloudflare Hyperdrive
167
+
168
+ PostgreSQL through Hyperdrive:
169
+
170
+ ```sh
171
+ pnpm add pg
172
+ ```
173
+
174
+ ```ts
175
+ import {
176
+ hyperdrivePostgres,
177
+ } from "@cossackframework/database/cloudflare";
178
+
179
+ const adapter = await hyperdrivePostgres(env.HYPERDRIVE);
180
+ ```
181
+
182
+ MySQL through Hyperdrive:
183
+
184
+ ```sh
185
+ pnpm add mysql2
186
+ ```
187
+
188
+ ```ts
189
+ import {
190
+ hyperdriveMySQL,
191
+ } from "@cossackframework/database/cloudflare";
192
+
193
+ const adapter = await hyperdriveMySQL(env.HYPERDRIVE);
194
+ ```
195
+
196
+ Hyperdrive owns the global connection pool. The adapters create request-local
197
+ clients and release them deterministically. Enable `nodejs_compat` for the
198
+ official `pg` and `mysql2` drivers. See Cloudflare's
199
+ [Hyperdrive driver guidance](https://developers.cloudflare.com/hyperdrive/).
200
+
201
+ ## Deno
202
+
203
+ Deno accepts an injected driver rather than importing a specific database
204
+ library into the neutral package:
205
+
206
+ ```ts
207
+ import { createORM } from "@cossackframework/database";
208
+ import {
209
+ deno,
210
+ type InjectedDenoDriver,
211
+ } from "@cossackframework/database/deno";
212
+
213
+ declare const driver: InjectedDenoDriver;
214
+
215
+ const orm = createORM({
216
+ adapter: deno(driver),
217
+ entities,
218
+ });
219
+ ```
220
+
221
+ The injected driver declares its dialect, executes parameterized statements,
222
+ normalizes rows affected and insert IDs, and optionally supplies transactions.
223
+ An application can also inject a runtime-appropriate `ScopeStorage`.
224
+
225
+ Deno can connect through npm-compatible PostgreSQL/MySQL clients or an
226
+ application-provided SQLite driver. See Deno's
227
+ [database connection guide](https://docs.deno.com/examples/connecting_to_databases_tutorial/)
228
+ for runtime permissions and driver choices.
229
+
230
+ ## Custom Runtime
231
+
232
+ Cossack ORM does not require runtime support to live in this package. A custom
233
+ runtime can construct an `Adapter` from a third-party `Driver` and, where
234
+ available, an async-local `ScopeStorage`:
235
+
236
+ ```ts
237
+ import type {
238
+ Adapter,
239
+ Driver,
240
+ ScopeStorage,
241
+ } from "@cossackframework/database/adapter";
242
+
243
+ export function customRuntime(
244
+ driver: Driver,
245
+ scope?: ScopeStorage<unknown>,
246
+ ): Adapter {
247
+ return {
248
+ driver,
249
+ ...(scope ? { scope } : {}),
250
+ };
251
+ }
252
+ ```
253
+
254
+ The driver owns connection lifecycle, pooling, execution, transactions,
255
+ reservation, cancellation, result normalization, and introspection. Its
256
+ capability flags must describe what it actually implements. See
257
+ [Custom adapters](./advanced.md#custom-adapters) for a complete driver outline.
258
+
259
+ ### Multiple connections
260
+
261
+ Like the multiple-data-source pattern used by other ORMs, create one independent
262
+ ORM instance per database connection:
263
+
264
+ ```ts
265
+ import { createORM } from "@cossackframework/database";
266
+ import {
267
+ nodeSQLite,
268
+ postgres,
269
+ } from "@cossackframework/database/node";
270
+ import { Post, User } from "./models/primary.js";
271
+ import { AuditEvent } from "./models/analytics.js";
272
+
273
+ export const databases = {
274
+ primary: createORM({
275
+ adapter: await nodeSQLite({ filename: "app.db" }),
276
+ entities: [User, Post],
277
+ }),
278
+
279
+ analytics: createORM({
280
+ adapter: await postgres(process.env.ANALYTICS_DATABASE_URL!),
281
+ entities: [AuditEvent],
282
+ }),
283
+ } as const;
284
+ ```
285
+
286
+ Each instance owns its adapter, model metadata, entity snapshots, transaction
287
+ scope, and shutdown lifecycle. It may use a different dialect and a different
288
+ entity list.
289
+
290
+ When a function touches one connection, Active Record syntax remains available
291
+ inside that connection's scope:
292
+
293
+ ```ts
294
+ const users = await databases.primary.run(() =>
295
+ User.find({ order: { name: "asc" } })
296
+ );
297
+
298
+ const events = await databases.analytics.run(() =>
299
+ AuditEvent.find({ take: 100 })
300
+ );
301
+ ```
302
+
303
+ When one function touches multiple connections, prefer explicit model managers:
304
+
305
+ ```ts
306
+ const primaryUsers = databases.primary.model(User);
307
+ const analyticsEvents = databases.analytics.model(AuditEvent);
308
+
309
+ const [users, events] = await Promise.all([
310
+ primaryUsers.find({ order: { name: "asc" } }),
311
+ analyticsEvents.find({ take: 100 }),
312
+ ]);
313
+ ```
314
+
315
+ This avoids asking a static model method to infer which ORM should handle the
316
+ query. It also supports registering the same entity class with two connections:
317
+
318
+ ```ts
319
+ const liveUsers = databases.primary.model(User);
320
+ const archivedUsers = archiveORM.model(User);
321
+
322
+ const [live, archived] = await Promise.all([
323
+ liveUsers.find(),
324
+ archivedUsers.find(),
325
+ ]);
326
+ ```
327
+
328
+ Do not nest Active Record scopes from different ORM instances. Both scopes
329
+ would be active in the same asynchronous chain, making a static call such as
330
+ `User.find()` ambiguous. Use `orm.model(Entity)`, `orm.sql`, and explicit ORM
331
+ methods for cross-connection work.
332
+
333
+ ### Concurrent scopes
334
+
335
+ Independent scopes can run concurrently when each adapter supplies isolated
336
+ async-local storage:
337
+
338
+ ```ts
339
+ await Promise.all([
340
+ databases.primary.run(() => User.count()),
341
+ databases.analytics.run(() => AuditEvent.count()),
342
+ ]);
343
+ ```
344
+
345
+ Built-in Node, Bun, D1, and Hyperdrive adapters provide runtime-appropriate
346
+ scope storage. A custom runtime must supply `ScopeStorage` before using static
347
+ Active Record concurrently. Explicit `orm.model(Entity)` access does not depend
348
+ on global scope lookup.
349
+
350
+ ### Transactions across connections
351
+
352
+ A transaction belongs to exactly one ORM:
353
+
354
+ ```ts
355
+ await databases.primary.transaction(async () => {
356
+ await databases.primary.model(User).update(
357
+ { id: userId },
358
+ { active: false },
359
+ );
360
+ });
361
+ ```
362
+
363
+ Starting separate transactions on `primary` and `analytics` does not create a
364
+ distributed transaction. A failure cannot atomically roll back work already
365
+ committed to another database. Use an outbox, saga, or another application-level
366
+ coordination strategy for cross-database consistency.
367
+
368
+ Relations also stay within one ORM instance. For cross-database data, query each
369
+ connection explicitly and combine the results in application code.
370
+
371
+ ### Migrations and shutdown
372
+
373
+ Give each database its own config so schema commands cannot target the wrong
374
+ connection:
375
+
376
+ ```text
377
+ orm.primary.config.ts
378
+ orm.analytics.config.ts
379
+ ```
380
+
381
+ ```sh
382
+ cossack-orm migration up --config orm.primary.config.ts
383
+ cossack-orm migration up --config orm.analytics.config.ts
384
+ ```
385
+
386
+ Close every long-lived connection during graceful shutdown:
387
+
388
+ ```ts
389
+ await Promise.all(
390
+ Object.values(databases).map((orm) => orm.close()),
391
+ );
392
+ ```
393
+
394
+ See the runnable
395
+ [multiple-connections SQLite example](../examples/multiple-connections/README.md)
396
+ for separate models, migrations, CLI configs, transactions, and
397
+ application-side result joining.
398
+
399
+ ## Closing adapters
400
+
401
+ Long-lived applications usually create one ORM for a process or runtime
402
+ container. Close it during graceful shutdown:
403
+
404
+ ```ts
405
+ await orm.close();
406
+ ```
407
+
408
+ Request-local adapters may make `close()` a no-op, but calling it remains safe
409
+ and idempotent.
410
+
411
+ ## Capabilities
412
+
413
+ Inspect capabilities instead of branching only on a dialect name:
414
+
415
+ ```ts
416
+ if (orm.driver.capabilities.returning) {
417
+ // Use a mutation returning clause.
418
+ }
419
+
420
+ if (orm.driver.capabilities.transactions) {
421
+ // Interactive transaction support is available.
422
+ }
423
+ ```
424
+
425
+ Capabilities include transactions, savepoints, returning clauses, batches,
426
+ connection reservation, cancellation, parameter limits, and batch limits.