@cossackframework/database 0.8.0-minimal.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 +275 -0
  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 +111 -3
@@ -0,0 +1,290 @@
1
+ ---
2
+ title: Advanced Usage
3
+ description: Work with scopes, transactions, reserved connections, logging, metadata, errors, naming strategies, and custom adapters.
4
+ ---
5
+
6
+ # Advanced Usage
7
+
8
+ ## Request and async scopes
9
+
10
+ Static Active Record methods and the global `sql` tag resolve the current ORM
11
+ through async-local scope:
12
+
13
+ ```ts
14
+ await orm.run(async () => {
15
+ const user = await User.findOne({
16
+ where: { id: 1 },
17
+ });
18
+
19
+ await sql`SELECT ${1}`;
20
+ });
21
+ ```
22
+
23
+ Put one scope around the outer unit of work. Nested calls reuse the current
24
+ scope, so helper functions do not need to receive or reopen it.
25
+
26
+ The Cossack/Hono integration installs the scope as middleware:
27
+
28
+ ```ts
29
+ import { ormMiddleware } from "@cossackframework/database/cossack";
30
+
31
+ app.use("*", ormMiddleware(orm));
32
+ ```
33
+
34
+ Concurrent request scopes remain isolated when the runtime adapter supplies
35
+ async-local storage.
36
+
37
+ ## Transactions and savepoints
38
+
39
+ ```ts
40
+ await orm.transaction(async () => {
41
+ const account = await Account.findOne({
42
+ where: { id: accountId },
43
+ });
44
+
45
+ if (!account) throw new Error("Account not found");
46
+
47
+ account.balance -= amount;
48
+ await account.save();
49
+
50
+ await LedgerEntry.create({
51
+ accountId,
52
+ amount: -amount,
53
+ }).save();
54
+ });
55
+ ```
56
+
57
+ `orm.transaction()` creates a scope automatically when called outside
58
+ `orm.run()`. Active Record calls and the global SQL tag inside the callback use
59
+ the transaction driver.
60
+
61
+ Nested transactions use savepoints:
62
+
63
+ ```ts
64
+ await orm.transaction(async () => {
65
+ await User.create({ email: "ada@example.com" }).save();
66
+
67
+ await orm.transaction(async () => {
68
+ await AuditEvent.create({ action: "user.created" }).save();
69
+ });
70
+ });
71
+ ```
72
+
73
+ If an adapter does not support savepoints, nested transactions throw
74
+ `UnsupportedCapabilityError`. D1 also rejects top-level interactive
75
+ transactions.
76
+
77
+ ## Reserved connections
78
+
79
+ Reserve a connection when several non-transactional statements must use the same
80
+ session:
81
+
82
+ ```ts
83
+ await orm.reserve(async () => {
84
+ await orm.sql`SELECT set_config('application_name', ${"worker"}, false)`;
85
+ const result = await orm.sql`SELECT current_setting('application_name')`;
86
+ });
87
+ ```
88
+
89
+ Reservation support is capability-dependent. Always let the callback finish so
90
+ the adapter can release the client deterministically.
91
+
92
+ ## Query logging
93
+
94
+ Pass a logger object:
95
+
96
+ ```ts
97
+ const orm = createORM({
98
+ adapter,
99
+ entities,
100
+ logger: {
101
+ query(event) {
102
+ console.log({
103
+ sql: event.sql,
104
+ parameters: event.parameters,
105
+ durationMs: event.durationMs,
106
+ dialect: event.dialect,
107
+ operation: event.operation,
108
+ error: event.error,
109
+ });
110
+ },
111
+ },
112
+ });
113
+ ```
114
+
115
+ Instrumentation includes compiled SQL, redacted parameter descriptions,
116
+ duration, dialect, operation, and an optional error. Parameter values are not
117
+ placed directly in logger events.
118
+
119
+ ## Custom naming strategies
120
+
121
+ ```ts
122
+ import {
123
+ defaultNamingStrategy,
124
+ type NamingStrategy,
125
+ } from "@cossackframework/database";
126
+
127
+ const namingStrategy: NamingStrategy = {
128
+ ...defaultNamingStrategy,
129
+ tableName(entityName) {
130
+ return `app_${defaultNamingStrategy.tableName(entityName)}`;
131
+ },
132
+ };
133
+
134
+ const orm = createORM({
135
+ adapter,
136
+ entities,
137
+ namingStrategy,
138
+ });
139
+ ```
140
+
141
+ A strategy controls table names, column names, relation join columns, and join
142
+ table names. Explicit decorator names always take precedence.
143
+
144
+ ## Schema metadata and introspection
145
+
146
+ `orm.schema()` returns the finalized logical model graph:
147
+
148
+ ```ts
149
+ const modelSchema = orm.schema();
150
+ ```
151
+
152
+ `orm.introspect()` returns the adapter's view of the physical database:
153
+
154
+ ```ts
155
+ const databaseSchema = await orm.introspect();
156
+ ```
157
+
158
+ Both use the versioned, serializable `OrmSchema` contract:
159
+
160
+ ```ts
161
+ import type {
162
+ ColumnSchema,
163
+ EntitySchema,
164
+ OrmSchema,
165
+ RelationSchema,
166
+ } from "@cossackframework/database";
167
+ ```
168
+
169
+ Tooling can compare them:
170
+
171
+ ```ts
172
+ import {
173
+ describeOperation,
174
+ diffSchemas,
175
+ } from "@cossackframework/database";
176
+
177
+ const diff = diffSchemas(
178
+ await orm.introspect(),
179
+ orm.schema(),
180
+ );
181
+
182
+ for (const operation of diff.operations) {
183
+ console.log(describeOperation(operation));
184
+ }
185
+ ```
186
+
187
+ Pass `{ allowDestructive: true }` only after the caller has made a deliberate
188
+ safety decision.
189
+
190
+ ## Error handling
191
+
192
+ Normalized error classes include:
193
+
194
+ - `ConfigurationError`
195
+ - `MetadataError`
196
+ - `ScopeError`
197
+ - `QueryError`
198
+ - `UnsupportedCapabilityError`
199
+ - `DestructiveSchemaChangeError`
200
+ - `MigrationError`
201
+ - `SeederError`
202
+
203
+ ```ts
204
+ import {
205
+ QueryError,
206
+ UnsupportedCapabilityError,
207
+ } from "@cossackframework/database";
208
+
209
+ try {
210
+ await orm.transaction(work);
211
+ } catch (error) {
212
+ if (error instanceof UnsupportedCapabilityError) {
213
+ console.error(error.capability, error.dialect);
214
+ } else if (error instanceof QueryError) {
215
+ console.error(error.sql, error.cause);
216
+ }
217
+ }
218
+ ```
219
+
220
+ Capability errors are intentional: the ORM does not silently emulate
221
+ transactions, savepoints, returning clauses, reservation, or cancellation.
222
+
223
+ ## Custom adapters
224
+
225
+ Third-party integrations import public contracts from the adapter entry point:
226
+
227
+ ```ts
228
+ import type {
229
+ Adapter,
230
+ Driver,
231
+ DriverCapabilities,
232
+ QueryResult,
233
+ } from "@cossackframework/database/adapter";
234
+
235
+ const capabilities = {
236
+ transactions: false,
237
+ savepoints: false,
238
+ returning: true,
239
+ batch: false,
240
+ reserveConnection: false,
241
+ cancellation: false,
242
+ parameterLimit: 999,
243
+ batchLimit: 100,
244
+ } satisfies DriverCapabilities;
245
+
246
+ const driver: Driver = {
247
+ dialect: "sqlite",
248
+ capabilities,
249
+
250
+ async execute(query, operation = "raw"): Promise<QueryResult> {
251
+ // Bind query.parameters; never concatenate them into query.text.
252
+ return {
253
+ rows: [],
254
+ meta: {
255
+ durationMs: 0,
256
+ dialect: "sqlite",
257
+ operation,
258
+ rowsAffected: 0,
259
+ },
260
+ };
261
+ },
262
+
263
+ async close() {},
264
+ };
265
+
266
+ const adapter: Adapter = { driver };
267
+ ```
268
+
269
+ Drivers own execution, pooling, transactions, reservation, cancellation, result
270
+ normalization, and physical introspection. Dialects own quoting, placeholders,
271
+ DDL rendering, type mapping, and SQL capabilities.
272
+
273
+ Supply a `ScopeStorage` implementation when the runtime supports concurrent
274
+ requests and static Active Record methods.
275
+
276
+ ## Cossack stores
277
+
278
+ The Cossack entry point also provides:
279
+
280
+ ```ts
281
+ import {
282
+ createDatabaseCacheStore,
283
+ createDatabaseSessionStore,
284
+ ormMiddleware,
285
+ } from "@cossackframework/database/cossack";
286
+ ```
287
+
288
+ These helpers execute through the ORM driver contract and share the same
289
+ request/transaction scope. Their backing tables must be created by application
290
+ migrations.
@@ -0,0 +1,188 @@
1
+ ---
2
+ title: ORM Comparison
3
+ description: Compare Cossack ORM with Drizzle ORM, TypeORM, Kysely, and Prisma across modeling, queries, relations, tooling, runtimes, and maturity.
4
+ ---
5
+
6
+ # ORM Comparison
7
+
8
+ Cossack ORM is not intended to be a universal replacement for every TypeScript
9
+ database library. It is a focused choice for applications that want decorated
10
+ Active Record models, explicit relation loading, safe SQL, and runtime-specific
11
+ adapters—especially Cossack applications.
12
+
13
+ This page compares architecture and currently implemented features, not
14
+ benchmarks. “Yes” means the feature is part of the project's supported API; it
15
+ does not imply that every implementation has equal depth. “Manual” means the
16
+ result is possible with SQL or application code but is not modeled as a
17
+ first-class ORM feature.
18
+
19
+ Last reviewed: July 2026.
20
+
21
+ ## Feature matrix
22
+
23
+ | Area | Cossack ORM | Drizzle ORM | TypeORM | Kysely | Prisma ORM |
24
+ | --- | --- | --- | --- | --- | --- |
25
+ | Primary abstraction | Decorated Active Record classes | TypeScript table schemas | Decorated entities with Active Record or Data Mapper | Typed SQL query builder | Prisma schema and generated client |
26
+ | Active Record methods | Yes | No | Yes | No | No |
27
+ | Repository/Data Mapper API | No, by design | No repository layer | Yes | No | Generated client, not a classic repository |
28
+ | Code generation required for queries | No | No | No | No | Yes |
29
+ | Typed SQL-style query builder | Yes, with some less precise complex join/projection types | Yes; a primary interface | Yes; entity-aware QueryBuilder | Yes; the primary focus | No general SQL builder; client API plus raw/TypedSQL |
30
+ | Relation metadata | Decorators and a serializable schema graph | TypeScript relation declarations | Decorators with extensive relation options | None in core | Prisma schema relations |
31
+ | Relation loading | Explicit `relations`/`with`; batched follow-up queries | Relational query API, normally one SQL statement | Explicit, eager, or lazy | Manual joins or application code | `include`/`select` and nested queries |
32
+ | Entity instances, hooks, and dirty tracking | Yes | No | Yes | No | Returns plain objects |
33
+ | Parameterized raw SQL | Fragment AST and tagged template | Tagged SQL templates | `sql` tag and lower-level query APIs | Tagged SQL templates | `$queryRaw`/`$executeRaw` and TypedSQL |
34
+ | Generated migrations | Yes; model-snapshot diffs with reviewable TypeScript and generated inverses | Yes, through Drizzle Kit | Yes | Migration primitives; generation is not the core focus | Yes, through Prisma Migrate |
35
+ | Migration baseline | Built in | Possible through migration workflow | Manual migration-history workflow | Application-managed | Built in |
36
+ | Database introspection | SQLite, PostgreSQL, and MySQL adapters | Yes | Used for schema comparison; no first-party entity pull | Types commonly generated by external `kysely-codegen` | `db pull` |
37
+ | Model generation from a database | Decorated classes through `schema pull` | TypeScript schema through `pull` | Not built in | External code generator | Prisma schema through `db pull` |
38
+ | Runtime schema push/synchronization | No, by design | `push` available | `synchronize`/`schema:sync` available | No | `db push` available |
39
+ | First-party seeding support | Ordered `SeederRunner` with transaction policy | `drizzle-seed` data generator | Application or community tooling | Application code | CLI seed command runs an application script |
40
+ | SQL database coverage | SQLite, PostgreSQL, MySQL; D1 and libSQL adapters | Broad PostgreSQL, MySQL, SQLite, SingleStore, MSSQL, and CockroachDB ecosystem | Broad SQL driver set | Official PostgreSQL, MySQL, MSSQL, SQLite, and PGlite dialects | PostgreSQL, MySQL/MariaDB, SQLite, SQL Server, and CockroachDB |
41
+ | MongoDB/NoSQL | No | No | MongoDB support | No | MongoDB support |
42
+ | Edge/serverless focus | First-class Bun, D1, Hyperdrive, and injected Deno entry points | Strong, with many serverless drivers | Driver-dependent | Runtime-neutral; dialect/driver-dependent | Supported through driver adapters and supported deployments |
43
+ | Multiple connections | Multiple isolated `ORM` instances | Multiple database instances | Multiple `DataSource` instances | Multiple `Kysely` instances | Separate schemas/generated clients |
44
+ | Cross-database relations or transactions | No | No general cross-database unit of work | Limited multi-database querying; no general distributed transaction | No | No general distributed transaction |
45
+ | Maturity and ecosystem | New v1 package | Established ecosystem | Long-established, feature-rich ORM | Established and deliberately focused | Long-established ecosystem and tooling |
46
+
47
+ Database support in this table describes first-party, documented paths rather
48
+ than every community adapter. Capabilities still vary by driver. For example,
49
+ Cossack's D1 adapter supports atomic migration batches but not interactive
50
+ transactions or savepoints.
51
+
52
+ ## Where Cossack ORM fits
53
+
54
+ Choose Cossack ORM when most of these are true:
55
+
56
+ - Entity classes should own persistence methods such as `find()`, `save()`, and
57
+ `remove()`.
58
+ - Decorators are an acceptable source of schema metadata.
59
+ - Request-scoped Active Record calls should automatically participate in the
60
+ current transaction.
61
+ - Relations should be requested explicitly and loaded in batches rather than
62
+ hidden behind lazy properties.
63
+ - The same model layer must run through isolated Node, Bun, Cloudflare, or Deno
64
+ adapters.
65
+ - Cossack Studio or other framework tooling needs serializable logical schema
66
+ metadata, including virtual relations.
67
+
68
+ Do not choose it merely because it has a familiar API. The alternatives below
69
+ are stronger in several important areas.
70
+
71
+ ## Compared with Drizzle ORM
72
+
73
+ Drizzle is a better fit for teams that think in tables and SQL and want strong
74
+ type inference close to the database. It has broader documented driver support,
75
+ a larger ecosystem, relational queries designed to compile to one SQL
76
+ statement, Drizzle Kit, Drizzle Studio, and a dedicated data-generation package.
77
+
78
+ Cossack adds stateful entity instances, decorators, lifecycle hooks, dirty
79
+ tracking, and Active Record methods. Its relation loader intentionally uses
80
+ batched follow-up queries, which can be easier to reason about across adapters
81
+ but may add round trips compared with Drizzle's relational query API. For
82
+ complex joins and calculated projections, Drizzle's types are currently more
83
+ complete.
84
+
85
+ Choose Drizzle for a SQL-first, schema-object workflow. Choose Cossack when the
86
+ entity class and its behavior should be the center of the application model.
87
+
88
+ See Drizzle's official [overview](https://orm.drizzle.team/docs/overview),
89
+ [migration workflows](https://orm.drizzle.team/docs/migrations), and
90
+ [relations documentation](https://orm.drizzle.team/docs/relations).
91
+
92
+ ## Compared with TypeORM
93
+
94
+ TypeORM is the closest match in surface style: both use decorated entities and
95
+ support Active Record. TypeORM also supports Data Mapper repositories, eager
96
+ and lazy relations, more cascade and relation options, subscribers, additional
97
+ database families, schema synchronization, and other features accumulated over
98
+ a much longer lifetime.
99
+
100
+ Cossack is narrower. It has no repository layer, lazy relations, runtime schema
101
+ synchronization, query-result cache, or comparable extension ecosystem. In
102
+ return, it has an ESM-only package shape, explicit request/transaction scoping,
103
+ isolated runtime adapters, explicit batched relation loading, and a versioned
104
+ logical schema contract intended for framework tooling.
105
+
106
+ Choose TypeORM when feature breadth, database breadth, or Data Mapper is
107
+ important. Choose Cossack when its smaller Active Record-only model and
108
+ serverless/runtime boundaries align with the application.
109
+
110
+ See TypeORM's official [Active Record and Data Mapper
111
+ guide](https://typeorm.io/docs/guides/active-record-data-mapper/),
112
+ [relations reference](https://typeorm.io/docs/relations/relations/),
113
+ [migration generator](https://typeorm.io/docs/migrations/generating/), and
114
+ [multiple data source guide](https://typeorm.io/docs/data-source/multiple-data-sources/).
115
+
116
+ ## Compared with Kysely
117
+
118
+ Kysely is a query builder, not an entity ORM. That is its advantage when a team
119
+ wants a thin, SQL-shaped abstraction with excellent composability and
120
+ compile-time result inference. It does not impose model instances, decorators,
121
+ relation loaders, dirty tracking, or lifecycle behavior.
122
+
123
+ Cossack's query builder covers common application queries, but Kysely is the
124
+ more capable and precise choice for deeply composed SQL, complex aliases, and
125
+ advanced projections. Cossack instead supplies the higher-level model and
126
+ tooling layers: Active Record, relation metadata, codecs, migrations,
127
+ introspection, generated models, and seed orchestration.
128
+
129
+ Choose Kysely when SQL and query typing are the product boundary and the
130
+ application will own its model conventions. Choose Cossack when those
131
+ conventions should be supplied by the ORM.
132
+
133
+ See the official [Kysely overview](https://www.kysely.dev/), which describes
134
+ its SQL-first scope, dialects, runtimes, migrations, and external code-generation
135
+ workflow.
136
+
137
+ ## Compared with Prisma ORM
138
+
139
+ Prisma provides a mature schema language, generated type-safe client,
140
+ introspection, migration workflow, Studio, and broad ecosystem. Its records are
141
+ plain objects queried through `PrismaClient`; they are not Active Record
142
+ instances. The generated client and Prisma schema are intentional parts of its
143
+ workflow.
144
+
145
+ Cossack keeps the TypeScript entity class as the model source and does not
146
+ require client generation. It offers direct adapters, scoped static methods,
147
+ and a SQL-style builder, but it has fewer supported databases, less polished
148
+ tooling, and far less production history. Prisma is the safer default when its
149
+ schema/client workflow is acceptable and mature tooling matters more than
150
+ Active Record.
151
+
152
+ Choose Prisma for its generated-client workflow and established tooling. Choose
153
+ Cossack when decorated entity behavior, direct runtime adapters, and Cossack
154
+ framework integration are more important.
155
+
156
+ See Prisma's official [ORM overview](https://docs.prisma.io/docs/orm),
157
+ [supported databases](https://docs.prisma.io/docs/orm/reference/supported-databases),
158
+ and [Prisma Migrate guide](https://www.prisma.io/docs/orm/prisma-migrate/getting-started).
159
+
160
+ ## Current Cossack limitations
161
+
162
+ The most important differences are not syntax:
163
+
164
+ - Cossack ORM is new. It does not yet have the production history, community
165
+ integrations, or troubleshooting corpus of these alternatives.
166
+ - Its first-party database surface is intentionally smaller. SQL Server,
167
+ CockroachDB-specific behavior, Oracle, MongoDB, and many specialized drivers
168
+ are outside v1.
169
+ - Query types are strong for model properties and common operations, but
170
+ complex raw joins, aliases, and computed projections can require explicit
171
+ typing. Kysely and Drizzle are stronger for this work.
172
+ - Relation loading is explicit and batched, not lazy and not guaranteed to use
173
+ one statement. TypeORM and Prisma support more relation behaviors; Drizzle
174
+ can produce a single relational statement.
175
+ - Generated migrations require review. Ordinary model-diff migrations include
176
+ generated `down()` operations where the schema operation is reversible;
177
+ squashed baselines are deliberately non-reversible. There is no automatic
178
+ startup synchronization.
179
+ - Automated integration coverage in this repository is currently strongest for
180
+ Node SQLite. The runtime adapters and public contracts exist, but PostgreSQL,
181
+ MySQL, Bun, Deno, and Hyperdrive do not yet have the same public integration
182
+ evidence as mature competitors.
183
+ - Cossack provides schema metadata for Studio integration, not a standalone
184
+ database GUI in this package.
185
+
186
+ These are acceptable tradeoffs only when Cossack's focused model is useful to
187
+ the application. If an alternative already fits the preferred architecture,
188
+ its maturity is a substantial reason to use it.
@@ -0,0 +1,139 @@
1
+ ---
2
+ title: Installation
3
+ description: Install Cossack ORM, configure TypeScript decorators, and create an ORM instance.
4
+ ---
5
+
6
+ # Installation
7
+
8
+ ## Requirements
9
+
10
+ Cossack ORM is ESM-only and targets:
11
+
12
+ - Node.js 22 or newer
13
+ - A current stable Bun release
14
+ - A current stable Deno release
15
+ - Modern Cloudflare Workers compatibility dates
16
+ - TypeScript with decorator metadata enabled
17
+
18
+ Install the ORM and decorator metadata support:
19
+
20
+ ```sh
21
+ pnpm add @cossackframework/database reflect-metadata
22
+ ```
23
+
24
+ Equivalent npm, Yarn, and Bun commands work as well.
25
+
26
+ ```sh
27
+ npm install @cossackframework/database reflect-metadata
28
+ yarn add @cossackframework/database reflect-metadata
29
+ bun add @cossackframework/database reflect-metadata
30
+ ```
31
+
32
+ Import `reflect-metadata` once before decorated models are evaluated:
33
+
34
+ ```ts
35
+ import "reflect-metadata";
36
+ ```
37
+
38
+ ## TypeScript configuration
39
+
40
+ Cossack applications use legacy TypeScript decorators. Add these options to
41
+ `tsconfig.json`:
42
+
43
+ ```json
44
+ {
45
+ "compilerOptions": {
46
+ "target": "ES2022",
47
+ "module": "NodeNext",
48
+ "moduleResolution": "NodeNext",
49
+ "experimentalDecorators": true,
50
+ "emitDecoratorMetadata": true,
51
+ "useDefineForClassFields": false
52
+ }
53
+ }
54
+ ```
55
+
56
+ Because the package is ESM-only, set `"type": "module"` in `package.json` and
57
+ use `.js` extensions in relative TypeScript imports when using `NodeNext`.
58
+
59
+ ## Choose a runtime adapter
60
+
61
+ The root package does not eagerly bundle database drivers. Import the adapter
62
+ for the runtime where the application executes:
63
+
64
+ | Runtime | Import | Available adapters |
65
+ | --- | --- | --- |
66
+ | Node.js | `@cossackframework/database/node` | `nodeSQLite`, `betterSQLite`, `postgres`, `mysql`, `libsql` |
67
+ | Bun | `@cossackframework/database/bun` | `bun` for SQLite, PostgreSQL, or MySQL |
68
+ | Cloudflare Workers | `@cossackframework/database/cloudflare` | `d1`, `hyperdrivePostgres`, `hyperdriveMySQL` |
69
+ | Deno | `@cossackframework/database/deno` | `deno` with an injected driver |
70
+
71
+ Some Node and Workers adapters require an optional peer driver:
72
+
73
+ ```sh
74
+ # Install only what the application uses.
75
+ pnpm add pg
76
+ pnpm add mysql2
77
+ pnpm add @libsql/client
78
+ pnpm add better-sqlite3
79
+ ```
80
+
81
+ Node 22's built-in SQLite adapter, Cloudflare D1, and Bun's native SQL client do
82
+ not require one of these packages.
83
+
84
+ ## Create an ORM
85
+
86
+ ```ts
87
+ import { createORM } from "@cossackframework/database";
88
+ import { nodeSQLite } from "@cossackframework/database/node";
89
+ import { entities } from "./models/index.js";
90
+
91
+ export const orm = createORM({
92
+ adapter: await nodeSQLite({ filename: "app.db" }),
93
+ entities,
94
+ });
95
+ ```
96
+
97
+ Every relation target must appear in `entities`. Metadata is finalized when the
98
+ ORM is created, so duplicate names, missing primary keys, unresolved relations,
99
+ and ambiguous column types fail during startup rather than during the first
100
+ query.
101
+
102
+ ## Create `orm.config.ts`
103
+
104
+ The CLI and Studio use one configuration file:
105
+
106
+ ```ts
107
+ import { defineConfig } from "@cossackframework/database";
108
+ import { nodeSQLite } from "@cossackframework/database/node";
109
+ import { entities } from "./src/models/index.js";
110
+ import { migrations } from "./migrations/index.js";
111
+ import { seeders } from "./seeders/index.js";
112
+
113
+ export default defineConfig({
114
+ entities,
115
+ migrations,
116
+ seeds: seeders,
117
+ adapter: () => nodeSQLite({ filename: "app.db" }),
118
+ });
119
+ ```
120
+
121
+ An adapter factory is recommended in configuration files. It delays opening the
122
+ database until a command needs it.
123
+
124
+ ## Verify the setup
125
+
126
+ ```sh
127
+ cossack-orm schema check
128
+ cossack-orm migration status
129
+ cossack-orm seed list
130
+ ```
131
+
132
+ Pass a non-default config location with `--config`:
133
+
134
+ ```sh
135
+ cossack-orm schema check --config ./config/orm.config.ts
136
+ ```
137
+
138
+ Next, define application data in [Models](./models.md) and choose the correct
139
+ adapter details in [Runtimes](./runtimes.md).