@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.
- package/README.md +6 -4
- package/dist/runtime/cloudflare.d.ts +17 -19
- package/dist/runtime/cloudflare.d.ts.map +1 -1
- package/dist/runtime/cloudflare.js +20 -17
- package/dist/runtime/cloudflare.js.map +1 -1
- package/dist/runtime/deno.d.ts +12 -0
- package/dist/runtime/deno.d.ts.map +1 -1
- package/dist/runtime/deno.js +17 -0
- package/dist/runtime/deno.js.map +1 -1
- package/dist/runtime/node.d.ts +1 -1
- package/dist/runtime/node.d.ts.map +1 -1
- package/dist/runtime/node.js +2 -23
- package/dist/runtime/node.js.map +1 -1
- package/dist/runtime/turso.d.ts +33 -0
- package/dist/runtime/turso.d.ts.map +1 -0
- package/dist/runtime/turso.js +54 -0
- package/dist/runtime/turso.js.map +1 -0
- package/dist/schema/introspection.d.ts.map +1 -1
- package/dist/schema/introspection.js +213 -15
- package/dist/schema/introspection.js.map +1 -1
- package/dist/sql/client.js +4 -3
- package/dist/sql/client.js.map +1 -1
- package/docs/advanced.md +290 -0
- package/docs/comparison.md +188 -0
- package/docs/installation.md +140 -0
- package/docs/introduction.md +126 -0
- package/docs/migrations.md +232 -0
- package/docs/models.md +241 -0
- package/docs/queries.md +261 -0
- package/docs/raw-queries.md +183 -0
- package/docs/relationships.md +243 -0
- package/docs/runtimes.md +426 -0
- package/docs/seeders.md +198 -0
- package/package.json +10 -5
|
@@ -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 current Turso 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,140 @@
|
|
|
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`, `turso` |
|
|
67
|
+
| Deno | `@cossackframework/database/deno` | `deno`, `denoSQLite`, `postgres`, `mysql`, `turso` |
|
|
68
|
+
| Bun | `@cossackframework/database/bun` | `bun` for SQLite, PostgreSQL, or MySQL |
|
|
69
|
+
| Cloudflare Workers | `@cossackframework/database/cloudflare` | `d1`, `hyperdrivePostgres`, `hyperdriveMySQL`, `turso` |
|
|
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 @tursodatabase/database # embedded SQLite / Desktop
|
|
78
|
+
pnpm add @tursodatabase/serverless # remote Turso / edge runtimes
|
|
79
|
+
pnpm add better-sqlite3
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Node 22's built-in SQLite adapter, Cloudflare D1, and Bun's native SQL client do
|
|
83
|
+
not require one of these packages.
|
|
84
|
+
|
|
85
|
+
## Create an ORM
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
import { createORM } from "@cossackframework/database";
|
|
89
|
+
import { nodeSQLite } from "@cossackframework/database/node";
|
|
90
|
+
import { entities } from "./models/index.js";
|
|
91
|
+
|
|
92
|
+
export const orm = createORM({
|
|
93
|
+
adapter: await nodeSQLite({ filename: "app.db" }),
|
|
94
|
+
entities,
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Every relation target must appear in `entities`. Metadata is finalized when the
|
|
99
|
+
ORM is created, so duplicate names, missing primary keys, unresolved relations,
|
|
100
|
+
and ambiguous column types fail during startup rather than during the first
|
|
101
|
+
query.
|
|
102
|
+
|
|
103
|
+
## Create `orm.config.ts`
|
|
104
|
+
|
|
105
|
+
The CLI and Studio use one configuration file:
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
import { defineConfig } from "@cossackframework/database";
|
|
109
|
+
import { nodeSQLite } from "@cossackframework/database/node";
|
|
110
|
+
import { entities } from "./src/models/index.js";
|
|
111
|
+
import { migrations } from "./migrations/index.js";
|
|
112
|
+
import { seeders } from "./seeders/index.js";
|
|
113
|
+
|
|
114
|
+
export default defineConfig({
|
|
115
|
+
entities,
|
|
116
|
+
migrations,
|
|
117
|
+
seeds: seeders,
|
|
118
|
+
adapter: () => nodeSQLite({ filename: "app.db" }),
|
|
119
|
+
});
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
An adapter factory is recommended in configuration files. It delays opening the
|
|
123
|
+
database until a command needs it.
|
|
124
|
+
|
|
125
|
+
## Verify the setup
|
|
126
|
+
|
|
127
|
+
```sh
|
|
128
|
+
cossack-orm schema check
|
|
129
|
+
cossack-orm migration status
|
|
130
|
+
cossack-orm seed list
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Pass a non-default config location with `--config`:
|
|
134
|
+
|
|
135
|
+
```sh
|
|
136
|
+
cossack-orm schema check --config ./config/orm.config.ts
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Next, define application data in [Models](./models.md) and choose the correct
|
|
140
|
+
adapter details in [Runtimes](./runtimes.md).
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Introduction
|
|
3
|
+
description: Learn the design, core concepts, and first steps of Cossack ORM.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Introduction
|
|
7
|
+
|
|
8
|
+
Cossack ORM is an ESM-only, serverless-first SQL ORM for Node.js, Bun,
|
|
9
|
+
Cloudflare Workers, and Deno. It combines decorated models, Active Record
|
|
10
|
+
methods, a typed query builder, safe SQL fragments, migrations, introspection,
|
|
11
|
+
and explicit runtime adapters.
|
|
12
|
+
|
|
13
|
+
The package is deliberately small in shape:
|
|
14
|
+
|
|
15
|
+
- Models are ordinary classes that extend `BaseEntity`.
|
|
16
|
+
- Every application registers its complete entity list with `createORM()`.
|
|
17
|
+
- Static Active Record methods resolve through the current request or job scope.
|
|
18
|
+
- Dialects compile SQL while adapters execute it.
|
|
19
|
+
- Relations are loaded explicitly and batched.
|
|
20
|
+
- Migrations are generated and reviewed; startup never mutates the schema.
|
|
21
|
+
|
|
22
|
+
## A first model and query
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import "reflect-metadata";
|
|
26
|
+
import {
|
|
27
|
+
BaseEntity,
|
|
28
|
+
Column,
|
|
29
|
+
Entity,
|
|
30
|
+
PrimaryGeneratedColumn,
|
|
31
|
+
createORM,
|
|
32
|
+
} from "@cossackframework/database";
|
|
33
|
+
import { nodeSQLite } from "@cossackframework/database/node";
|
|
34
|
+
|
|
35
|
+
@Entity()
|
|
36
|
+
class User extends BaseEntity {
|
|
37
|
+
@PrimaryGeneratedColumn()
|
|
38
|
+
declare id: number;
|
|
39
|
+
|
|
40
|
+
@Column({ unique: true })
|
|
41
|
+
declare email: string;
|
|
42
|
+
|
|
43
|
+
@Column()
|
|
44
|
+
declare name: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const orm = createORM({
|
|
48
|
+
adapter: await nodeSQLite({ filename: "app.db" }),
|
|
49
|
+
entities: [User],
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
try {
|
|
53
|
+
await orm.run(async () => {
|
|
54
|
+
await User.create({
|
|
55
|
+
email: "ada@example.com",
|
|
56
|
+
name: "Ada Lovelace",
|
|
57
|
+
}).save();
|
|
58
|
+
|
|
59
|
+
const users = await User.find({
|
|
60
|
+
order: { name: "asc" },
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
} finally {
|
|
64
|
+
await orm.close();
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`orm.run()` establishes the current ORM for static methods such as
|
|
69
|
+
`User.find()`, `entity.save()`, and the global `sql` tag. Put one scope around a
|
|
70
|
+
request, queue job, scheduled task, or command—not around each query.
|
|
71
|
+
|
|
72
|
+
Framework middleware normally installs this scope automatically. For example,
|
|
73
|
+
the Cossack/Hono middleware wraps the request once:
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
import { ormMiddleware } from "@cossackframework/database/cossack";
|
|
77
|
+
|
|
78
|
+
app.use("*", ormMiddleware(orm));
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Handlers below that middleware can call `User.find()` directly.
|
|
82
|
+
|
|
83
|
+
## Explicit model access
|
|
84
|
+
|
|
85
|
+
Code that already owns an ORM instance can query through a model manager without
|
|
86
|
+
an Active Record scope:
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
const users = await orm.model(User).find({
|
|
90
|
+
order: { name: "asc" },
|
|
91
|
+
});
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
This form is useful for framework integrations and simple read-only scripts.
|
|
95
|
+
Use `orm.run()` when you want static Active Record methods, instance persistence,
|
|
96
|
+
the global `sql` tag, or automatic transaction rebinding.
|
|
97
|
+
|
|
98
|
+
## What `orm.run()` does
|
|
99
|
+
|
|
100
|
+
An ORM scope identifies the correct ORM and transaction client across
|
|
101
|
+
asynchronous calls. It does not, by itself, promise to reserve a database
|
|
102
|
+
connection. Pooling adapters generally acquire connections as needed.
|
|
103
|
+
`orm.transaction()` and `orm.reserve()` explicitly pin the appropriate client
|
|
104
|
+
when the adapter supports those capabilities.
|
|
105
|
+
|
|
106
|
+
This distinction matters when an application has multiple databases, concurrent
|
|
107
|
+
requests, request-specific Workers bindings, or nested transactions. Cossack ORM
|
|
108
|
+
throws an actionable `ScopeError` instead of silently guessing a global
|
|
109
|
+
connection.
|
|
110
|
+
|
|
111
|
+
## Design boundaries
|
|
112
|
+
|
|
113
|
+
Cossack ORM v1 does not provide a repository/Data Mapper layer, automatic schema
|
|
114
|
+
synchronization, a legacy query-builder compatibility API, NoSQL or GraphQL integration, or
|
|
115
|
+
query-result caching. Database-specific work remains possible through safe SQL
|
|
116
|
+
fragments and public adapter contracts.
|
|
117
|
+
|
|
118
|
+
## Continue reading
|
|
119
|
+
|
|
120
|
+
- [Installation](./installation.md)
|
|
121
|
+
- [Models](./models.md)
|
|
122
|
+
- [Queries](./queries.md)
|
|
123
|
+
- [Relationships](./relationships.md)
|
|
124
|
+
- [Raw queries](./raw-queries.md)
|
|
125
|
+
- [Comparison](./comparison.md)
|
|
126
|
+
- [Complete SQLite starter](../examples/sqlite-starter/README.md)
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Migrations
|
|
3
|
+
description: Generate, review, apply, revert, baseline, and inspect deterministic database migrations.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Migrations
|
|
7
|
+
|
|
8
|
+
Migrations are explicit, versioned changes to a database schema. Cossack ORM
|
|
9
|
+
never synchronizes models to the database during application startup.
|
|
10
|
+
|
|
11
|
+
The normal workflow is:
|
|
12
|
+
|
|
13
|
+
1. Change decorated models.
|
|
14
|
+
2. Generate a migration from the committed model snapshot diff.
|
|
15
|
+
3. Review its generated forward and inverse SQL.
|
|
16
|
+
4. Apply it in development and CI.
|
|
17
|
+
5. Commit the model and migration together.
|
|
18
|
+
|
|
19
|
+
## Configuration
|
|
20
|
+
|
|
21
|
+
Register migrations in `orm.config.ts`:
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { defineConfig } from "@cossackframework/database";
|
|
25
|
+
import { nodeSQLite } from "@cossackframework/database/node";
|
|
26
|
+
import { entities } from "./src/models/index.js";
|
|
27
|
+
import { migrations } from "./migrations/index.js";
|
|
28
|
+
|
|
29
|
+
export default defineConfig({
|
|
30
|
+
adapter: () => nodeSQLite({ filename: "app.db" }),
|
|
31
|
+
entities,
|
|
32
|
+
migrations,
|
|
33
|
+
migrationDirectory: "./migrations",
|
|
34
|
+
});
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Keep their configured names stable and unique:
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
import createUsers from "./0001_create_users.js";
|
|
41
|
+
import createPosts from "./0002_create_posts.js";
|
|
42
|
+
|
|
43
|
+
export const migrations = [
|
|
44
|
+
createUsers,
|
|
45
|
+
createPosts,
|
|
46
|
+
] as const;
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Generate a migration
|
|
50
|
+
|
|
51
|
+
Existing projects first record their current decorated models once:
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
cossack-orm migration snapshot
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
This writes `.cossack-schema.json` inside `migrationDirectory`. Commit the
|
|
58
|
+
snapshot with the migrations. It is model metadata, not a database dump.
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
cossack-orm migration generate add_user_profiles
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Choose another output path when needed:
|
|
65
|
+
|
|
66
|
+
```sh
|
|
67
|
+
cossack-orm migration generate add_user_profiles \
|
|
68
|
+
--output ./src/database/migrations/0003_add_user_profiles.ts
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Generation compares the committed model snapshot with current decorated model
|
|
72
|
+
metadata. It does not introspect the database. Adding or removing a `@Column()`,
|
|
73
|
+
entity, rename marker, or index produces deterministic TypeScript containing
|
|
74
|
+
reviewable `up()` and inverse `down()` SQL. The snapshot advances only after the
|
|
75
|
+
migration file is written successfully. When the output is directly inside
|
|
76
|
+
`migrationDirectory` and its `index.ts` exports the standard `migrations` array,
|
|
77
|
+
the generator registers the new migration automatically; otherwise it prints a
|
|
78
|
+
registration reminder.
|
|
79
|
+
|
|
80
|
+
A migration has this contract:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
import {
|
|
84
|
+
sql,
|
|
85
|
+
type Migration,
|
|
86
|
+
} from "@cossackframework/database";
|
|
87
|
+
|
|
88
|
+
export default {
|
|
89
|
+
name: "0003_add_user_profiles",
|
|
90
|
+
|
|
91
|
+
up({ schema }) {
|
|
92
|
+
schema.raw(sql.unsafe(
|
|
93
|
+
"ALTER TABLE users ADD COLUMN biography text",
|
|
94
|
+
));
|
|
95
|
+
},
|
|
96
|
+
|
|
97
|
+
down({ schema }) {
|
|
98
|
+
schema.dropColumn("users", "biography");
|
|
99
|
+
},
|
|
100
|
+
} satisfies Migration;
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
`sql.unsafe()` is appropriate here only because the statement is trusted,
|
|
104
|
+
static, and reviewed. Use schema operations where they express the change
|
|
105
|
+
portably.
|
|
106
|
+
|
|
107
|
+
## Squash migration history
|
|
108
|
+
|
|
109
|
+
Create one baseline migration directly from the current models:
|
|
110
|
+
|
|
111
|
+
```sh
|
|
112
|
+
cossack-orm migration squash 0001_schema
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
After reviewing it, prune the replaced migration source files and rewrite the
|
|
116
|
+
migration barrel:
|
|
117
|
+
|
|
118
|
+
```sh
|
|
119
|
+
cossack-orm migration squash 0001_schema --prune
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
The squashed migration records the migration names it replaces. On a fresh
|
|
123
|
+
database its full schema is applied. On an existing database where every
|
|
124
|
+
replaced migration is already applied, `migration up` consolidates only the
|
|
125
|
+
bookkeeping and does not replay schema creation. A partially applied replacement
|
|
126
|
+
set is rejected. Squashed baselines are intentionally not reversible.
|
|
127
|
+
|
|
128
|
+
## Apply and revert
|
|
129
|
+
|
|
130
|
+
```sh
|
|
131
|
+
cossack-orm migration up
|
|
132
|
+
cossack-orm migration down
|
|
133
|
+
cossack-orm migration status
|
|
134
|
+
cossack-orm migration check
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
- `up` applies pending migrations in deterministic name order.
|
|
138
|
+
- `down` reverts the most recently applied migration by default.
|
|
139
|
+
- `status` reports pending, applied, or checksum-changed migrations.
|
|
140
|
+
- `check` fails unless all configured migrations are applied and unchanged.
|
|
141
|
+
|
|
142
|
+
Applied migrations are recorded in `_cossack_migrations` with their name,
|
|
143
|
+
SHA-256 checksum, batch, and application timestamp. Editing an applied migration
|
|
144
|
+
causes checksum validation to fail; create a new migration instead.
|
|
145
|
+
|
|
146
|
+
## Destructive changes
|
|
147
|
+
|
|
148
|
+
Dropping tables or columns and potentially narrowing column changes fail
|
|
149
|
+
generation/checking by default:
|
|
150
|
+
|
|
151
|
+
```sh
|
|
152
|
+
cossack-orm migration generate remove_legacy_data \
|
|
153
|
+
--allow-destructive
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
Use this flag only after reviewing the generated operation and planning data
|
|
157
|
+
retention, backfills, and deployment ordering.
|
|
158
|
+
|
|
159
|
+
Renames are never guessed. Record their source explicitly:
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
@Entity({
|
|
163
|
+
tableName: "accounts",
|
|
164
|
+
renamedFrom: "users",
|
|
165
|
+
})
|
|
166
|
+
class Account extends BaseEntity {
|
|
167
|
+
@Column({
|
|
168
|
+
name: "display_name",
|
|
169
|
+
renamedFrom: "name",
|
|
170
|
+
})
|
|
171
|
+
declare displayName: string;
|
|
172
|
+
}
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
## Schema commands
|
|
176
|
+
|
|
177
|
+
```sh
|
|
178
|
+
cossack-orm schema diff
|
|
179
|
+
cossack-orm schema check
|
|
180
|
+
cossack-orm schema pull
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
- `schema diff` describes physical/model differences.
|
|
184
|
+
- `schema check` fails when drift exists.
|
|
185
|
+
- `schema pull` generates decorated models with explicit physical names and
|
|
186
|
+
logical types.
|
|
187
|
+
|
|
188
|
+
Unlike model-first migration generation, schema commands inspect the live
|
|
189
|
+
database. Destructive differences also require `--allow-destructive` for
|
|
190
|
+
`schema diff` and `schema check`.
|
|
191
|
+
|
|
192
|
+
By default, pulled models are written to `src/entities.generated.ts`. Existing
|
|
193
|
+
files are not overwritten unless `--force` is supplied:
|
|
194
|
+
|
|
195
|
+
```sh
|
|
196
|
+
cossack-orm schema pull \
|
|
197
|
+
--output ./src/models/generated.ts \
|
|
198
|
+
--force
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
Unknown physical database types are retained with a `custom:<type>` logical
|
|
202
|
+
type rather than discarded.
|
|
203
|
+
|
|
204
|
+
## Baseline an existing database
|
|
205
|
+
|
|
206
|
+
Baseline lets an existing deployment adopt migration bookkeeping without
|
|
207
|
+
replaying its historical schema creation:
|
|
208
|
+
|
|
209
|
+
```sh
|
|
210
|
+
cossack-orm migration baseline
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
The CLI first verifies that the live database matches current model metadata.
|
|
214
|
+
Only then does it record the schema hash. Resolve drift before baselining.
|
|
215
|
+
|
|
216
|
+
## Programmatic runner
|
|
217
|
+
|
|
218
|
+
Framework CLIs can delegate to `MigrationRunner`:
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
import { MigrationRunner } from "@cossackframework/database";
|
|
222
|
+
|
|
223
|
+
const runner = new MigrationRunner(orm, migrations);
|
|
224
|
+
|
|
225
|
+
const applied = await orm.run(() => runner.up());
|
|
226
|
+
const status = await orm.run(() => runner.status());
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
Transactional adapters apply a migration and its bookkeeping together. D1 uses
|
|
230
|
+
an atomic prepared batch for schema statements plus bookkeeping.
|
|
231
|
+
|
|
232
|
+
See [Seeders](./seeders.md) for application data that may be safely rerun.
|