@cossackframework/database 0.8.0-readmesafe.0 → 0.8.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.
Files changed (194) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/dist/adapter/index.d.ts +4 -0
  4. package/dist/adapter/index.d.ts.map +1 -0
  5. package/dist/adapter/index.js +3 -0
  6. package/dist/adapter/index.js.map +1 -0
  7. package/dist/adapter/memory.d.ts +23 -0
  8. package/dist/adapter/memory.d.ts.map +1 -0
  9. package/dist/adapter/memory.js +53 -0
  10. package/dist/adapter/memory.js.map +1 -0
  11. package/dist/adapter/scope.d.ts +7 -0
  12. package/dist/adapter/scope.d.ts.map +1 -0
  13. package/dist/adapter/scope.js +7 -0
  14. package/dist/adapter/scope.js.map +1 -0
  15. package/dist/adapter/types.d.ts +73 -0
  16. package/dist/adapter/types.d.ts.map +1 -0
  17. package/dist/adapter/types.js +2 -0
  18. package/dist/adapter/types.js.map +1 -0
  19. package/dist/cli.d.ts +3 -0
  20. package/dist/cli.d.ts.map +1 -0
  21. package/dist/cli.js +6 -0
  22. package/dist/cli.js.map +1 -0
  23. package/dist/codec.d.ts +4 -0
  24. package/dist/codec.d.ts.map +1 -0
  25. package/dist/codec.js +52 -0
  26. package/dist/codec.js.map +1 -0
  27. package/dist/config.d.ts +19 -0
  28. package/dist/config.d.ts.map +1 -0
  29. package/dist/config.js +4 -0
  30. package/dist/config.js.map +1 -0
  31. package/dist/cossack/index.d.ts +49 -0
  32. package/dist/cossack/index.d.ts.map +1 -0
  33. package/dist/cossack/index.js +254 -0
  34. package/dist/cossack/index.js.map +1 -0
  35. package/dist/dialect/dialects.d.ts +6 -0
  36. package/dist/dialect/dialects.d.ts.map +1 -0
  37. package/dist/dialect/dialects.js +102 -0
  38. package/dist/dialect/dialects.js.map +1 -0
  39. package/dist/entity/base-entity.d.ts +21 -0
  40. package/dist/entity/base-entity.d.ts.map +1 -0
  41. package/dist/entity/base-entity.js +64 -0
  42. package/dist/entity/base-entity.js.map +1 -0
  43. package/dist/entity/manager.d.ts +25 -0
  44. package/dist/entity/manager.d.ts.map +1 -0
  45. package/dist/entity/manager.js +72 -0
  46. package/dist/entity/manager.js.map +1 -0
  47. package/dist/errors.d.ts +37 -0
  48. package/dist/errors.d.ts.map +1 -0
  49. package/dist/errors.js +62 -0
  50. package/dist/errors.js.map +1 -0
  51. package/dist/index.d.ts +25 -0
  52. package/dist/index.d.ts.map +1 -0
  53. package/dist/index.js +21 -0
  54. package/dist/index.js.map +1 -0
  55. package/dist/metadata/decorators.d.ts +27 -0
  56. package/dist/metadata/decorators.d.ts.map +1 -0
  57. package/dist/metadata/decorators.js +271 -0
  58. package/dist/metadata/decorators.js.map +1 -0
  59. package/dist/metadata/finalize.d.ts +4 -0
  60. package/dist/metadata/finalize.d.ts.map +1 -0
  61. package/dist/metadata/finalize.js +267 -0
  62. package/dist/metadata/finalize.js.map +1 -0
  63. package/dist/metadata/naming.d.ts +9 -0
  64. package/dist/metadata/naming.d.ts.map +1 -0
  65. package/dist/metadata/naming.js +21 -0
  66. package/dist/metadata/naming.js.map +1 -0
  67. package/dist/metadata/stage3.d.ts +26 -0
  68. package/dist/metadata/stage3.d.ts.map +1 -0
  69. package/dist/metadata/stage3.js +38 -0
  70. package/dist/metadata/stage3.js.map +1 -0
  71. package/dist/metadata/store.d.ts +29 -0
  72. package/dist/metadata/store.d.ts.map +1 -0
  73. package/dist/metadata/store.js +22 -0
  74. package/dist/metadata/store.js.map +1 -0
  75. package/dist/metadata/types.d.ts +83 -0
  76. package/dist/metadata/types.d.ts.map +1 -0
  77. package/dist/metadata/types.js +2 -0
  78. package/dist/metadata/types.js.map +1 -0
  79. package/dist/migration/runner.d.ts +22 -0
  80. package/dist/migration/runner.d.ts.map +1 -0
  81. package/dist/migration/runner.js +182 -0
  82. package/dist/migration/runner.js.map +1 -0
  83. package/dist/migration/types.d.ts +26 -0
  84. package/dist/migration/types.d.ts.map +1 -0
  85. package/dist/migration/types.js +2 -0
  86. package/dist/migration/types.js.map +1 -0
  87. package/dist/orm.d.ts +63 -0
  88. package/dist/orm.d.ts.map +1 -0
  89. package/dist/orm.js +643 -0
  90. package/dist/orm.js.map +1 -0
  91. package/dist/query/builder.d.ts +63 -0
  92. package/dist/query/builder.d.ts.map +1 -0
  93. package/dist/query/builder.js +303 -0
  94. package/dist/query/builder.js.map +1 -0
  95. package/dist/query/expression.d.ts +27 -0
  96. package/dist/query/expression.d.ts.map +1 -0
  97. package/dist/query/expression.js +90 -0
  98. package/dist/query/expression.js.map +1 -0
  99. package/dist/query/types.d.ts +33 -0
  100. package/dist/query/types.d.ts.map +1 -0
  101. package/dist/query/types.js +11 -0
  102. package/dist/query/types.js.map +1 -0
  103. package/dist/runtime/bun.d.ts +30 -0
  104. package/dist/runtime/bun.d.ts.map +1 -0
  105. package/dist/runtime/bun.js +63 -0
  106. package/dist/runtime/bun.js.map +1 -0
  107. package/dist/runtime/cloudflare.d.ts +70 -0
  108. package/dist/runtime/cloudflare.d.ts.map +1 -0
  109. package/dist/runtime/cloudflare.js +230 -0
  110. package/dist/runtime/cloudflare.js.map +1 -0
  111. package/dist/runtime/deno.d.ts +26 -0
  112. package/dist/runtime/deno.d.ts.map +1 -0
  113. package/dist/runtime/deno.js +40 -0
  114. package/dist/runtime/deno.js.map +1 -0
  115. package/dist/runtime/helpers.d.ts +4 -0
  116. package/dist/runtime/helpers.d.ts.map +1 -0
  117. package/dist/runtime/helpers.js +22 -0
  118. package/dist/runtime/helpers.js.map +1 -0
  119. package/dist/runtime/node.d.ts +88 -0
  120. package/dist/runtime/node.d.ts.map +1 -0
  121. package/dist/runtime/node.js +221 -0
  122. package/dist/runtime/node.js.map +1 -0
  123. package/dist/schema/builder.d.ts +16 -0
  124. package/dist/schema/builder.d.ts.map +1 -0
  125. package/dist/schema/builder.js +49 -0
  126. package/dist/schema/builder.js.map +1 -0
  127. package/dist/schema/ddl.d.ts +7 -0
  128. package/dist/schema/ddl.d.ts.map +1 -0
  129. package/dist/schema/ddl.js +114 -0
  130. package/dist/schema/ddl.js.map +1 -0
  131. package/dist/schema/diff.d.ts +8 -0
  132. package/dist/schema/diff.d.ts.map +1 -0
  133. package/dist/schema/diff.js +224 -0
  134. package/dist/schema/diff.js.map +1 -0
  135. package/dist/schema/introspection.d.ts +8 -0
  136. package/dist/schema/introspection.d.ts.map +1 -0
  137. package/dist/schema/introspection.js +165 -0
  138. package/dist/schema/introspection.js.map +1 -0
  139. package/dist/schema/operations.d.ts +44 -0
  140. package/dist/schema/operations.d.ts.map +1 -0
  141. package/dist/schema/operations.js +2 -0
  142. package/dist/schema/operations.js.map +1 -0
  143. package/dist/schema/types.d.ts +76 -0
  144. package/dist/schema/types.d.ts.map +1 -0
  145. package/dist/schema/types.js +2 -0
  146. package/dist/schema/types.js.map +1 -0
  147. package/dist/scope.d.ts +5 -0
  148. package/dist/scope.d.ts.map +1 -0
  149. package/dist/scope.js +28 -0
  150. package/dist/scope.js.map +1 -0
  151. package/dist/seeding/runner.d.ts +14 -0
  152. package/dist/seeding/runner.d.ts.map +1 -0
  153. package/dist/seeding/runner.js +107 -0
  154. package/dist/seeding/runner.js.map +1 -0
  155. package/dist/seeding/types.d.ts +33 -0
  156. package/dist/seeding/types.d.ts.map +1 -0
  157. package/dist/seeding/types.js +4 -0
  158. package/dist/seeding/types.js.map +1 -0
  159. package/dist/sql/client.d.ts +16 -0
  160. package/dist/sql/client.d.ts.map +1 -0
  161. package/dist/sql/client.js +71 -0
  162. package/dist/sql/client.js.map +1 -0
  163. package/dist/sql/executable.d.ts +8 -0
  164. package/dist/sql/executable.d.ts.map +1 -0
  165. package/dist/sql/executable.js +11 -0
  166. package/dist/sql/executable.js.map +1 -0
  167. package/dist/sql/fragment.d.ts +37 -0
  168. package/dist/sql/fragment.d.ts.map +1 -0
  169. package/dist/sql/fragment.js +40 -0
  170. package/dist/sql/fragment.js.map +1 -0
  171. package/dist/sql/tag.d.ts +20 -0
  172. package/dist/sql/tag.d.ts.map +1 -0
  173. package/dist/sql/tag.js +123 -0
  174. package/dist/sql/tag.js.map +1 -0
  175. package/dist/tooling/generate.d.ts +9 -0
  176. package/dist/tooling/generate.d.ts.map +1 -0
  177. package/dist/tooling/generate.js +83 -0
  178. package/dist/tooling/generate.js.map +1 -0
  179. package/dist/tooling/index.d.ts +12 -0
  180. package/dist/tooling/index.d.ts.map +1 -0
  181. package/dist/tooling/index.js +389 -0
  182. package/dist/tooling/index.js.map +1 -0
  183. package/docs/advanced.md +290 -0
  184. package/docs/comparison.md +188 -0
  185. package/docs/installation.md +139 -0
  186. package/docs/introduction.md +126 -0
  187. package/docs/migrations.md +232 -0
  188. package/docs/models.md +241 -0
  189. package/docs/queries.md +261 -0
  190. package/docs/raw-queries.md +183 -0
  191. package/docs/relationships.md +243 -0
  192. package/docs/runtimes.md +422 -0
  193. package/docs/seeders.md +198 -0
  194. package/package.json +1 -1
@@ -0,0 +1,422 @@
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.
@@ -0,0 +1,198 @@
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).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cossackframework/database",
3
- "version": "0.8.0-readmesafe.0",
3
+ "version": "0.8.0",
4
4
  "description": "Serverless-first Active Record ORM for Cossack",
5
5
  "type": "module",
6
6
  "license": "MIT",