@cossackframework/database 0.8.0-minimal.0 → 0.8.0-readmesafe.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 (2) hide show
  1. package/README.md +275 -0
  2. package/package.json +111 -3
package/README.md ADDED
@@ -0,0 +1,275 @@
1
+ # `@cossackframework/database`
2
+
3
+ An ESM-only, serverless-first Active Record ORM for Cossack. It provides decorated
4
+ models, safe SQL, a fluent query builder, explicit request scopes, schema metadata,
5
+ introspection, and deterministic migrations without a repository layer or a
6
+ runtime schema-sync mode.
7
+
8
+ ## Install
9
+
10
+ ```sh
11
+ pnpm add @cossackframework/database reflect-metadata
12
+ ```
13
+
14
+ Install only the optional driver used by the application (`pg`, `mysql2`,
15
+ `@libsql/client`, or `better-sqlite3`). Node 22's built-in `node:sqlite`, Bun SQL,
16
+ and Cloudflare D1 need no third-party database driver.
17
+
18
+ Use TypeScript legacy decorators:
19
+
20
+ ```json
21
+ {
22
+ "compilerOptions": {
23
+ "experimentalDecorators": true,
24
+ "emitDecoratorMetadata": true,
25
+ "useDefineForClassFields": false
26
+ }
27
+ }
28
+ ```
29
+
30
+ ## Documentation
31
+
32
+ - [Introduction](./docs/introduction.md)
33
+ - [Installation](./docs/installation.md)
34
+ - [Models](./docs/models.md)
35
+ - [Queries](./docs/queries.md)
36
+ - [Relationships](./docs/relationships.md)
37
+ - [Raw queries](./docs/raw-queries.md)
38
+ - [Runtimes](./docs/runtimes.md)
39
+ - [Migrations](./docs/migrations.md)
40
+ - [Seeders](./docs/seeders.md)
41
+ - [Advanced usage](./docs/advanced.md)
42
+ - [Comparison](./docs/comparison.md)
43
+
44
+ ## Models and request scope
45
+
46
+ ```ts
47
+ import "reflect-metadata";
48
+ import {
49
+ BaseEntity,
50
+ Column,
51
+ CreateDateColumn,
52
+ Entity,
53
+ PrimaryGeneratedColumn,
54
+ createORM,
55
+ } from "@cossackframework/database";
56
+ import { nodeSQLite } from "@cossackframework/database/node";
57
+
58
+ @Entity()
59
+ export class User extends BaseEntity {
60
+ @PrimaryGeneratedColumn()
61
+ declare id: number;
62
+
63
+ @Column()
64
+ declare email: string;
65
+
66
+ @Column({ type: "json" })
67
+ declare preferences: Record<string, unknown>;
68
+
69
+ @CreateDateColumn()
70
+ declare createdAt: Date;
71
+ }
72
+
73
+ const orm = createORM({
74
+ adapter: await nodeSQLite({ filename: "app.db" }),
75
+ entities: [User],
76
+ });
77
+
78
+ await orm.run(async () => {
79
+ const user = User.create({
80
+ email: "ada@example.com",
81
+ preferences: { theme: "dark" },
82
+ });
83
+ await user.save();
84
+
85
+ const active = await User.query("user")
86
+ .where((where) => where.like("email", "%@example.com"))
87
+ .orderBy("createdAt", "desc")
88
+ .limit(20)
89
+ .getMany();
90
+ });
91
+ ```
92
+
93
+ Static Active Record methods and the global `sql` tag deliberately throw outside
94
+ `orm.run()`. Put one scope around each request, queue job, scheduled task, or CLI
95
+ operation. Runtime adapters provide async-local isolation; a nested transaction
96
+ rebinds the scope to its transaction client and uses savepoints when supported.
97
+
98
+ ## Safe SQL
99
+
100
+ ```ts
101
+ import { sql } from "@cossackframework/database";
102
+
103
+ await orm.run(async () => {
104
+ const email = "ada@example.com";
105
+ const result = await sql`
106
+ SELECT ${sql.id("id")}, ${sql.id("email")}
107
+ FROM ${sql.id("users")}
108
+ WHERE ${sql.id("email")} = ${email}
109
+ `;
110
+ });
111
+ ```
112
+
113
+ Values always become parameters. `sql.id()` is the identifier escape hatch,
114
+ `sql.fragment` composes queries, `sql.join()` builds lists, and `sql.values()`
115
+ builds object/bulk insert tuples. `sql.unsafe()` is the only API that injects
116
+ literal SQL.
117
+
118
+ `new SQL({ adapter })` creates a standalone Bun-compatible tagged client. In Node,
119
+ `new SQL("postgres://…")`, `new SQL("mysql://…")`, `new SQL("libsql://…")`, and
120
+ SQLite paths select an adapter lazily. Workers intentionally require a binding or
121
+ explicit adapter rather than environment URL guessing.
122
+
123
+ ## Relations
124
+
125
+ Relations load only when requested:
126
+
127
+ ```ts
128
+ const users = await User.find({
129
+ where: { enabled: true },
130
+ relations: ["roles"],
131
+ });
132
+ ```
133
+
134
+ The loader batches keys and chunks them at the adapter's parameter limit. Owning
135
+ relations expose both logical metadata and physical join columns. Many-to-many
136
+ associations require `@JoinTable()` on one side. Cascades are opt-in with
137
+ `{ cascade: ["insert", "update"] }`; delete cascades remain database behavior and
138
+ are never replayed across an in-memory object graph.
139
+
140
+ ## Runtime adapters
141
+
142
+ | Runtime entry | Adapters |
143
+ | --- | --- |
144
+ | `@cossackframework/database/node` | `nodeSQLite`, `betterSQLite`, `postgres`, `mysql`, `libsql` |
145
+ | `@cossackframework/database/bun` | `bun` over the documented Bun SQL core API |
146
+ | `@cossackframework/database/cloudflare` | `d1`, `hyperdrivePostgres`, `hyperdriveMySQL` |
147
+ | `@cossackframework/database/deno` | `deno` with an injected remote or SQLite driver |
148
+ | `@cossackframework/database/adapter` | public dialect, driver, result, scope, and capability contracts |
149
+ | `@cossackframework/database/cossack` | middleware plus database cache/session stores |
150
+
151
+ D1 uses prepared statements and `batch()`. It supports atomic migration batches,
152
+ but rejects interactive transactions, savepoints, and connection reservation with
153
+ `UnsupportedCapabilityError`. Enable Workers' narrow `nodejs_als` compatibility
154
+ flag for request scope isolation.
155
+
156
+ Hyperdrive creates and closes a request-local `pg`/`mysql2` client while
157
+ Hyperdrive owns the global pool. Workers need `nodejs_compat`; `mysql2` uses
158
+ `disableEval: true`. See Cloudflare's current
159
+ [D1 binding API](https://developers.cloudflare.com/d1/worker-api/),
160
+ [Hyperdrive guide](https://developers.cloudflare.com/hyperdrive/get-started/),
161
+ and [Workers best practices](https://developers.cloudflare.com/workers/best-practices/workers-best-practices/).
162
+
163
+ ## Schema and migrations
164
+
165
+ `orm.config.ts` is the single configuration used by the CLI and Studio:
166
+
167
+ ```ts
168
+ import { defineConfig } from "@cossackframework/database";
169
+ import { nodeSQLite } from "@cossackframework/database/node";
170
+ import { entities } from "./src/entities/index.js";
171
+ import { migrations } from "./migrations/index.js";
172
+ import { seeders as seeds } from "./seeders/index.js";
173
+
174
+ export default defineConfig({
175
+ entities,
176
+ migrations,
177
+ migrationDirectory: "./migrations",
178
+ seeds,
179
+ adapter: () => nodeSQLite({ filename: "app.db" }),
180
+ });
181
+ ```
182
+
183
+ ```sh
184
+ cossack-orm migration snapshot
185
+ cossack-orm migration generate add_users
186
+ cossack-orm migration squash 0001_schema --prune
187
+ cossack-orm migration up
188
+ cossack-orm migration down
189
+ cossack-orm migration status
190
+ cossack-orm migration check
191
+ cossack-orm migration baseline
192
+ cossack-orm schema pull
193
+ cossack-orm schema diff
194
+ cossack-orm schema check
195
+ cossack-orm seed list
196
+ cossack-orm seed run
197
+ cossack-orm seed run --only users,posts
198
+ ```
199
+
200
+ Generated migrations compare current decorators with a committed model schema
201
+ snapshot; database introspection remains limited to `schema diff/check/pull`.
202
+ Migrations are reviewable TypeScript and are never run during application
203
+ startup. Dropped tables/columns and narrowing changes require
204
+ `--allow-destructive`. Rename detection is never heuristic: set `renamedFrom` on
205
+ the entity or column. `_cossack_migrations` stores the migration name, SHA-256
206
+ checksum, batch, and application timestamp.
207
+
208
+ `orm.schema()` returns versioned, serializable `OrmSchema` metadata. Studio can
209
+ merge it with `orm.introspect()` to display logical types and virtual relations
210
+ even where SQLite's physical affinity is less specific.
211
+
212
+ ## Seeders
213
+
214
+ Declare named seeders and keep their execution order in one exported array:
215
+
216
+ ```ts
217
+ import {
218
+ SeederRunner,
219
+ defineSeeder,
220
+ } from "@cossackframework/database";
221
+
222
+ export const usersSeeder = defineSeeder({
223
+ name: "users",
224
+ transaction: "auto",
225
+ async run({ orm, sql, signal }) {
226
+ // Active Record calls are already in ORM scope.
227
+ },
228
+ });
229
+
230
+ export const seeders = [usersSeeder] as const;
231
+
232
+ const results = await new SeederRunner(orm, seeders).run({
233
+ only: ["users"],
234
+ });
235
+ ```
236
+
237
+ Seeders run sequentially in configuration order and stop at the first failure.
238
+ `"auto"` uses one transaction per seeder where supported, `"required"` fails
239
+ before writing when interactive transactions are unavailable, and `"none"`
240
+ executes without a runner-managed transaction. On D1, `"auto"` runs without an
241
+ interactive transaction; use a database-specific batch inside a `"none"` seeder
242
+ when the work must be atomic.
243
+
244
+ `SeederRunner` owns scope, selection, transaction policy, cancellation, and
245
+ failure attribution. Framework CLIs should load `orm.config.ts` and delegate to
246
+ this runner instead of implementing their own seed loop. Environment and
247
+ production-confirmation policies belong in the framework CLI. Seed data remains
248
+ application-owned and should be idempotent through stable keys, existence checks,
249
+ or upserts; seeders are not recorded as migrations.
250
+
251
+ ## Deliberate v1 boundaries
252
+
253
+ There is no Data Mapper/repository API, legacy query-builder compatibility layer, automatic
254
+ schema mutation at startup, NoSQL/GraphQL integration, or ORM query-result cache.
255
+ Database-specific operations remain available through safe SQL fragments and
256
+ custom third-party adapters.
257
+
258
+ ## Complete SQLite example
259
+
260
+ [`examples/sqlite-starter`](./examples/sqlite-starter/README.md) contains
261
+ related `User` and `Post` models, a versioned migration, an idempotent seeder,
262
+ and executable create/migrate/seed/query scripts:
263
+
264
+ ```sh
265
+ pnpm example:sqlite
266
+ pnpm exec tsx ./examples/sqlite-starter/query.ts
267
+ ```
268
+
269
+ [`examples/multiple-connections`](./examples/multiple-connections/README.md)
270
+ demonstrates two independent SQLite connections with separate models,
271
+ migrations, transactions, CLI configs, and concurrent explicit-manager queries:
272
+
273
+ ```sh
274
+ pnpm example:multiple-connections
275
+ ```
package/package.json CHANGED
@@ -1,11 +1,119 @@
1
1
  {
2
2
  "name": "@cossackframework/database",
3
- "version": "0.8.0-minimal.0",
4
- "description": "Publish isolation probe",
5
- "keywords": [],
3
+ "version": "0.8.0-readmesafe.0",
4
+ "description": "Serverless-first Active Record ORM for Cossack",
6
5
  "type": "module",
7
6
  "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/cossackframework/cossack",
10
+ "directory": "packages/database"
11
+ },
12
+ "homepage": "https://github.com/cossackframework/cossack/tree/main/packages/database#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/cossackframework/cossack/issues"
15
+ },
16
+ "sideEffects": false,
17
+ "engines": {
18
+ "node": ">=22"
19
+ },
20
+ "bin": {
21
+ "cossack-orm": "dist/cli.js"
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "docs",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js"
33
+ },
34
+ "./adapter": {
35
+ "types": "./dist/adapter/index.d.ts",
36
+ "import": "./dist/adapter/index.js"
37
+ },
38
+ "./node": {
39
+ "types": "./dist/runtime/node.d.ts",
40
+ "import": "./dist/runtime/node.js"
41
+ },
42
+ "./bun": {
43
+ "types": "./dist/runtime/bun.d.ts",
44
+ "import": "./dist/runtime/bun.js"
45
+ },
46
+ "./cloudflare": {
47
+ "types": "./dist/runtime/cloudflare.d.ts",
48
+ "import": "./dist/runtime/cloudflare.js"
49
+ },
50
+ "./deno": {
51
+ "types": "./dist/runtime/deno.d.ts",
52
+ "import": "./dist/runtime/deno.js"
53
+ },
54
+ "./cossack": {
55
+ "types": "./dist/cossack/index.d.ts",
56
+ "import": "./dist/cossack/index.js"
57
+ },
58
+ "./tooling": {
59
+ "types": "./dist/tooling/index.d.ts",
60
+ "import": "./dist/tooling/index.js"
61
+ },
62
+ "./cli": "./dist/cli.js",
63
+ "./package.json": "./package.json"
64
+ },
8
65
  "publishConfig": {
9
66
  "access": "public"
67
+ },
68
+ "scripts": {
69
+ "build": "tsc -p tsconfig.build.json",
70
+ "check": "tsc --noEmit",
71
+ "test": "vitest run",
72
+ "test:watch": "vitest",
73
+ "audit:bundle": "node scripts/audit-bundles.mjs",
74
+ "example:sqlite": "tsx ./examples/sqlite-starter/run.ts",
75
+ "example:sqlite:reset": "tsx ./examples/sqlite-starter/run.ts --reset",
76
+ "example:sqlite:create": "tsx ./examples/sqlite-starter/create-database.ts",
77
+ "example:sqlite:migrate": "tsx ./examples/sqlite-starter/migrate.ts",
78
+ "example:sqlite:seed": "tsx ./examples/sqlite-starter/seed.ts",
79
+ "example:sqlite:query": "tsx ./examples/sqlite-starter/query.ts",
80
+ "example:multiple-connections": "tsx ./examples/multiple-connections/run.ts",
81
+ "example:multiple-connections:reset": "tsx ./examples/multiple-connections/run.ts --reset",
82
+ "prepack": "pnpm build && pnpm test && pnpm audit:bundle"
83
+ },
84
+ "dependencies": {
85
+ "tsx": "^4.23.0"
86
+ },
87
+ "peerDependencies": {
88
+ "@libsql/client": ">=0.14",
89
+ "better-sqlite3": ">=11",
90
+ "hono": "^4.12.0",
91
+ "mysql2": ">=3.11",
92
+ "pg": ">=8.13",
93
+ "reflect-metadata": ">=0.2"
94
+ },
95
+ "peerDependenciesMeta": {
96
+ "@libsql/client": {
97
+ "optional": true
98
+ },
99
+ "better-sqlite3": {
100
+ "optional": true
101
+ },
102
+ "mysql2": {
103
+ "optional": true
104
+ },
105
+ "pg": {
106
+ "optional": true
107
+ },
108
+ "reflect-metadata": {
109
+ "optional": true
110
+ }
111
+ },
112
+ "devDependencies": {
113
+ "@types/node": "^22.19.0",
114
+ "hono": "^4.12.31",
115
+ "reflect-metadata": "^0.2.2",
116
+ "typescript": "^7.0.2",
117
+ "vitest": "^4.1.10"
10
118
  }
11
119
  }