@cossackframework/database 0.8.3 → 0.9.1
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 +21 -22
- package/agent-docs.json +90 -0
- package/dist/adapter/types.d.ts +14 -1
- package/dist/adapter/types.d.ts.map +1 -1
- package/dist/codec.d.ts +7 -0
- package/dist/codec.d.ts.map +1 -1
- package/dist/codec.js +31 -2
- package/dist/codec.js.map +1 -1
- package/dist/config.d.ts +10 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js.map +1 -1
- package/dist/cossack/cache-policy.d.ts +18 -0
- package/dist/cossack/cache-policy.d.ts.map +1 -0
- package/dist/cossack/cache-policy.js +64 -0
- package/dist/cossack/cache-policy.js.map +1 -0
- package/dist/cossack/index.d.ts +20 -3
- package/dist/cossack/index.d.ts.map +1 -1
- package/dist/cossack/index.js +105 -51
- package/dist/cossack/index.js.map +1 -1
- package/dist/dialect/dialects.d.ts.map +1 -1
- package/dist/dialect/dialects.js +6 -0
- package/dist/dialect/dialects.js.map +1 -1
- package/dist/entity/base-entity.d.ts +22 -6
- package/dist/entity/base-entity.d.ts.map +1 -1
- package/dist/entity/base-entity.js +37 -8
- package/dist/entity/base-entity.js.map +1 -1
- package/dist/entity/manager.d.ts +22 -5
- package/dist/entity/manager.d.ts.map +1 -1
- package/dist/entity/manager.js +89 -4
- package/dist/entity/manager.js.map +1 -1
- package/dist/index.d.ts +7 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/metadata/finalize.d.ts.map +1 -1
- package/dist/metadata/finalize.js +27 -5
- package/dist/metadata/finalize.js.map +1 -1
- package/dist/metadata/inspection.d.ts +51 -0
- package/dist/metadata/inspection.d.ts.map +1 -0
- package/dist/metadata/inspection.js +19 -0
- package/dist/metadata/inspection.js.map +1 -0
- package/dist/migration/checksum.d.ts +18 -0
- package/dist/migration/checksum.d.ts.map +1 -0
- package/dist/migration/checksum.js +164 -0
- package/dist/migration/checksum.js.map +1 -0
- package/dist/migration/plan.d.ts +13 -0
- package/dist/migration/plan.d.ts.map +1 -0
- package/dist/migration/plan.js +73 -0
- package/dist/migration/plan.js.map +1 -0
- package/dist/migration/runner.d.ts +17 -3
- package/dist/migration/runner.d.ts.map +1 -1
- package/dist/migration/runner.js +175 -14
- package/dist/migration/runner.js.map +1 -1
- package/dist/migration/types.d.ts +47 -2
- package/dist/migration/types.d.ts.map +1 -1
- package/dist/orm.d.ts +68 -2
- package/dist/orm.d.ts.map +1 -1
- package/dist/orm.js +181 -50
- package/dist/orm.js.map +1 -1
- package/dist/query/builder.d.ts +33 -4
- package/dist/query/builder.d.ts.map +1 -1
- package/dist/query/builder.js +200 -23
- package/dist/query/builder.js.map +1 -1
- package/dist/query/diagnostics.d.ts +3 -0
- package/dist/query/diagnostics.d.ts.map +1 -0
- package/dist/query/diagnostics.js +75 -0
- package/dist/query/diagnostics.js.map +1 -0
- package/dist/query/expression.d.ts +2 -0
- package/dist/query/expression.d.ts.map +1 -1
- package/dist/query/expression.js +16 -1
- package/dist/query/expression.js.map +1 -1
- package/dist/query/types.d.ts +17 -2
- package/dist/query/types.d.ts.map +1 -1
- package/dist/query/types.js +3 -0
- package/dist/query/types.js.map +1 -1
- package/dist/runtime/cloudflare-turso.d.ts +29 -0
- package/dist/runtime/cloudflare-turso.d.ts.map +1 -0
- package/dist/runtime/cloudflare-turso.js +47 -0
- package/dist/runtime/cloudflare-turso.js.map +1 -0
- package/dist/runtime/cloudflare.d.ts +40 -21
- package/dist/runtime/cloudflare.d.ts.map +1 -1
- package/dist/runtime/cloudflare.js +69 -79
- package/dist/runtime/cloudflare.js.map +1 -1
- package/dist/runtime/helpers.d.ts +21 -0
- package/dist/runtime/helpers.d.ts.map +1 -1
- package/dist/runtime/helpers.js +34 -0
- package/dist/runtime/helpers.js.map +1 -1
- package/dist/runtime/node.d.ts +16 -0
- package/dist/runtime/node.d.ts.map +1 -1
- package/dist/runtime/node.js +107 -23
- package/dist/runtime/node.js.map +1 -1
- package/dist/runtime/turso.d.ts +5 -1
- package/dist/runtime/turso.d.ts.map +1 -1
- package/dist/runtime/turso.js +19 -5
- package/dist/runtime/turso.js.map +1 -1
- package/dist/runtime-capabilities.d.ts +25 -0
- package/dist/runtime-capabilities.d.ts.map +1 -0
- package/dist/runtime-capabilities.js +17 -0
- package/dist/runtime-capabilities.js.map +1 -0
- package/dist/schema/builder.d.ts.map +1 -1
- package/dist/schema/builder.js +6 -10
- package/dist/schema/builder.js.map +1 -1
- package/dist/schema/ddl.d.ts.map +1 -1
- package/dist/schema/ddl.js +42 -7
- package/dist/schema/ddl.js.map +1 -1
- package/dist/schema/diff.d.ts.map +1 -1
- package/dist/schema/diff.js +62 -10
- package/dist/schema/diff.js.map +1 -1
- package/dist/schema/introspection.d.ts +3 -1
- package/dist/schema/introspection.d.ts.map +1 -1
- package/dist/schema/introspection.js +274 -36
- package/dist/schema/introspection.js.map +1 -1
- package/dist/seeding/runner.d.ts +5 -1
- package/dist/seeding/runner.d.ts.map +1 -1
- package/dist/seeding/runner.js +66 -1
- package/dist/seeding/runner.js.map +1 -1
- package/dist/seeding/types.d.ts +15 -1
- package/dist/seeding/types.d.ts.map +1 -1
- package/dist/seeding/types.js.map +1 -1
- package/dist/sql/client.d.ts +1 -1
- package/dist/sql/client.d.ts.map +1 -1
- package/dist/sql/client.js +10 -51
- package/dist/sql/client.js.map +1 -1
- package/dist/sql/fragment.d.ts.map +1 -1
- package/dist/sql/fragment.js +5 -1
- package/dist/sql/fragment.js.map +1 -1
- package/dist/sql/node-client.d.ts +7 -0
- package/dist/sql/node-client.d.ts.map +1 -0
- package/dist/sql/node-client.js +61 -0
- package/dist/sql/node-client.js.map +1 -0
- package/dist/sql/tag.d.ts.map +1 -1
- package/dist/sql/tag.js +8 -0
- package/dist/sql/tag.js.map +1 -1
- package/dist/tooling/cloudflare.d.ts +77 -0
- package/dist/tooling/cloudflare.d.ts.map +1 -0
- package/dist/tooling/cloudflare.js +193 -0
- package/dist/tooling/cloudflare.js.map +1 -0
- package/dist/tooling/generate.d.ts.map +1 -1
- package/dist/tooling/generate.js +5 -15
- package/dist/tooling/generate.js.map +1 -1
- package/dist/tooling/index.d.ts +6 -2
- package/dist/tooling/index.d.ts.map +1 -1
- package/dist/tooling/index.js +247 -64
- package/dist/tooling/index.js.map +1 -1
- package/dist/tooling/inspection.d.ts +40 -0
- package/dist/tooling/inspection.d.ts.map +1 -0
- package/dist/tooling/inspection.js +63 -0
- package/dist/tooling/inspection.js.map +1 -0
- package/dist/tooling/process-json.d.ts +4 -0
- package/dist/tooling/process-json.d.ts.map +1 -0
- package/dist/tooling/process-json.js +79 -0
- package/dist/tooling/process-json.js.map +1 -0
- package/dist/uuid.d.ts +2 -0
- package/dist/uuid.d.ts.map +1 -0
- package/dist/uuid.js +22 -0
- package/dist/uuid.js.map +1 -0
- package/docs/advanced.md +1 -2
- package/docs/comparison.md +42 -45
- package/docs/inspection.md +50 -0
- package/docs/installation.md +1 -3
- package/docs/introduction.md +11 -10
- package/docs/migrations.md +118 -5
- package/docs/models.md +40 -7
- package/docs/queries.md +53 -4
- package/docs/raw-queries.md +26 -6
- package/docs/relationships.md +17 -3
- package/docs/runtimes.md +130 -45
- package/docs/seeders.md +42 -4
- package/package.json +7 -5
- package/dist/runtime/deno.d.ts +0 -38
- package/dist/runtime/deno.d.ts.map +0 -1
- package/dist/runtime/deno.js +0 -57
- package/dist/runtime/deno.js.map +0 -1
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Database inspection
|
|
3
|
+
description: Shared read-only schema, model, capability and migration facts for CLI and Studio.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Database inspection
|
|
7
|
+
|
|
8
|
+
Run `cossack schema inspect --json --env staging --target local` to inspect the
|
|
9
|
+
selected database. The result contains physical schema, declared model and
|
|
10
|
+
relationship metadata, provider capabilities, migration status and existing
|
|
11
|
+
history. Inspection does not create migration bookkeeping or apply migrations.
|
|
12
|
+
A named Cloudflare environment never falls back to top-level D1 bindings.
|
|
13
|
+
|
|
14
|
+
The database tooling entry exports the same service used by Studio:
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { inspectConfiguredDatabase } from '@cossackframework/database/tooling';
|
|
18
|
+
import config from './orm.config.js';
|
|
19
|
+
|
|
20
|
+
const facts = await inspectConfiguredDatabase(config, {
|
|
21
|
+
cwd: process.cwd(),
|
|
22
|
+
configPath: 'orm.config.ts',
|
|
23
|
+
environment: 'staging',
|
|
24
|
+
target: 'local',
|
|
25
|
+
readOnly: true,
|
|
26
|
+
});
|
|
27
|
+
console.log(facts.migrations.map(item => ({ name: item.name, state: item.state })));
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
This service passes `readOnly: true` to the application adapter factory and closes
|
|
31
|
+
its temporary connection after success or failure. Factories must honor the
|
|
32
|
+
selected environment/target and avoid setup writes when read-only. If ORM model
|
|
33
|
+
validation fails after creating an adapter, the adapter is closed too.
|
|
34
|
+
`inspectDatabase(orm, migrations)` inspects an existing borrowed connection.
|
|
35
|
+
Its owner remains responsible for closing it.
|
|
36
|
+
|
|
37
|
+
Resolved identity includes only bounded public fields. Connection URLs, credential
|
|
38
|
+
fields, getter properties and bound SQL values are excluded. Driver capabilities
|
|
39
|
+
are declarations of support, not a connectivity check or proof of server version.
|
|
40
|
+
Absent target metadata remains unspecified rather than guessing from a URL.
|
|
41
|
+
The `defaultValues: omitted` policy removes model and physical column default
|
|
42
|
+
values from shared inspection. Entity metadata reports `hasDefault`. Use the
|
|
43
|
+
application-owned migration SQL when reviewing an explicit default change. Unknown historical migration names remain in `history` even
|
|
44
|
+
when their declarations are no longer loaded.
|
|
45
|
+
|
|
46
|
+
Studio displays these same facts under "Database capabilities and migrations".
|
|
47
|
+
Its richer row editor still provides indexes, views and row locators. Those editor
|
|
48
|
+
details are separate from the shared versioned inspection result. Remote Studio
|
|
49
|
+
inspection loads the application's `orm.config.ts` and uses its remote adapter
|
|
50
|
+
factory. The selected binding must match an explicit `--database` request.
|
package/docs/installation.md
CHANGED
|
@@ -11,7 +11,6 @@ Cossack ORM is ESM-only and targets:
|
|
|
11
11
|
|
|
12
12
|
- Node.js 22 or newer
|
|
13
13
|
- A current stable Bun release
|
|
14
|
-
- A current stable Deno release
|
|
15
14
|
- Modern Cloudflare Workers compatibility dates
|
|
16
15
|
- TypeScript with decorator metadata enabled
|
|
17
16
|
|
|
@@ -64,7 +63,6 @@ for the runtime where the application executes:
|
|
|
64
63
|
| Runtime | Import | Available adapters |
|
|
65
64
|
| --- | --- | --- |
|
|
66
65
|
| Node.js | `@cossackframework/database/node` | `nodeSQLite`, `betterSQLite`, `postgres`, `mysql`, `turso` |
|
|
67
|
-
| Deno | `@cossackframework/database/deno` | `deno`, `denoSQLite`, `postgres`, `mysql`, `turso` |
|
|
68
66
|
| Bun | `@cossackframework/database/bun` | `bun` for SQLite, PostgreSQL, or MySQL |
|
|
69
67
|
| Cloudflare Workers | `@cossackframework/database/cloudflare` | `d1`, `hyperdrivePostgres`, `hyperdriveMySQL`, `turso` |
|
|
70
68
|
|
|
@@ -130,7 +128,7 @@ cossack-orm migration status
|
|
|
130
128
|
cossack-orm seed list
|
|
131
129
|
```
|
|
132
130
|
|
|
133
|
-
Pass a non-default
|
|
131
|
+
Pass a non-default configuration location with `--config`:
|
|
134
132
|
|
|
135
133
|
```sh
|
|
136
134
|
cossack-orm schema check --config ./config/orm.config.ts
|
package/docs/introduction.md
CHANGED
|
@@ -6,18 +6,18 @@ description: Learn the design, core concepts, and first steps of Cossack ORM.
|
|
|
6
6
|
# Introduction
|
|
7
7
|
|
|
8
8
|
Cossack ORM is an ESM-only, serverless-first SQL ORM for Node.js, Bun,
|
|
9
|
-
Cloudflare Workers
|
|
9
|
+
and Cloudflare Workers. It combines decorated models, Active Record
|
|
10
10
|
methods, a typed query builder, safe SQL fragments, migrations, introspection,
|
|
11
11
|
and explicit runtime adapters.
|
|
12
12
|
|
|
13
|
-
The package is deliberately small
|
|
13
|
+
The package is deliberately small:
|
|
14
14
|
|
|
15
15
|
- Models are ordinary classes that extend `BaseEntity`.
|
|
16
16
|
- Every application registers its complete entity list with `createORM()`.
|
|
17
17
|
- Static Active Record methods resolve through the current request or job scope.
|
|
18
18
|
- Dialects compile SQL while adapters execute it.
|
|
19
19
|
- Relations are loaded explicitly and batched.
|
|
20
|
-
- Migrations are generated and reviewed
|
|
20
|
+
- Migrations are generated and reviewed. Startup never mutates the schema.
|
|
21
21
|
|
|
22
22
|
## A first model and query
|
|
23
23
|
|
|
@@ -67,7 +67,8 @@ try {
|
|
|
67
67
|
|
|
68
68
|
`orm.run()` establishes the current ORM for static methods such as
|
|
69
69
|
`User.find()`, `entity.save()`, and the global `sql` tag. Put one scope around a
|
|
70
|
-
request, queue job, scheduled task, or command
|
|
70
|
+
request, queue job, scheduled task, or command. Do not put a scope around each
|
|
71
|
+
query.
|
|
71
72
|
|
|
72
73
|
Framework middleware normally installs this scope automatically. For example,
|
|
73
74
|
the Cossack/Hono middleware wraps the request once:
|
|
@@ -91,26 +92,26 @@ const users = await orm.model(User).find({
|
|
|
91
92
|
});
|
|
92
93
|
```
|
|
93
94
|
|
|
94
|
-
This form is useful for framework integrations and
|
|
95
|
+
This form is useful for framework integrations and read-only scripts.
|
|
95
96
|
Use `orm.run()` when you want static Active Record methods, instance persistence,
|
|
96
97
|
the global `sql` tag, or automatic transaction rebinding.
|
|
97
98
|
|
|
98
99
|
## What `orm.run()` does
|
|
99
100
|
|
|
100
101
|
An ORM scope identifies the correct ORM and transaction client across
|
|
101
|
-
asynchronous calls. It does not
|
|
102
|
-
|
|
102
|
+
asynchronous calls. It does not reserve a database connection by itself.
|
|
103
|
+
Pooling adapters generally acquire connections as needed.
|
|
103
104
|
`orm.transaction()` and `orm.reserve()` explicitly pin the appropriate client
|
|
104
105
|
when the adapter supports those capabilities.
|
|
105
106
|
|
|
106
|
-
This distinction
|
|
107
|
+
This distinction applies when an application has multiple databases, concurrent
|
|
107
108
|
requests, request-specific Workers bindings, or nested transactions. Cossack ORM
|
|
108
|
-
throws an actionable `ScopeError` instead of
|
|
109
|
+
throws an actionable `ScopeError` instead of guessing a global
|
|
109
110
|
connection.
|
|
110
111
|
|
|
111
112
|
## Design boundaries
|
|
112
113
|
|
|
113
|
-
Cossack ORM
|
|
114
|
+
Cossack ORM does not provide a repository/Data Mapper layer, automatic schema
|
|
114
115
|
synchronization, a legacy query-builder compatibility API, NoSQL or GraphQL integration, or
|
|
115
116
|
query-result caching. Database-specific work remains possible through safe SQL
|
|
116
117
|
fragments and public adapter contracts.
|
package/docs/migrations.md
CHANGED
|
@@ -71,10 +71,10 @@ cossack-orm migration generate add_user_profiles \
|
|
|
71
71
|
Generation compares the committed model snapshot with current decorated model
|
|
72
72
|
metadata. It does not introspect the database. Adding or removing a `@Column()`,
|
|
73
73
|
entity, rename marker, or index produces deterministic TypeScript containing
|
|
74
|
-
reviewable `up
|
|
74
|
+
reviewable `operations.up` and inverse `operations.down` SQL. The snapshot advances only after the
|
|
75
75
|
migration file is written successfully. When the output is directly inside
|
|
76
76
|
`migrationDirectory` and its `index.ts` exports the standard `migrations` array,
|
|
77
|
-
the generator registers the new migration automatically
|
|
77
|
+
the generator registers the new migration automatically. Otherwise it prints a
|
|
78
78
|
registration reminder.
|
|
79
79
|
|
|
80
80
|
A migration has this contract:
|
|
@@ -141,7 +141,102 @@ cossack-orm migration check
|
|
|
141
141
|
|
|
142
142
|
Applied migrations are recorded in `_cossack_migrations` with their name,
|
|
143
143
|
SHA-256 checksum, batch, and application timestamp. Editing an applied migration
|
|
144
|
-
causes checksum validation to fail
|
|
144
|
+
causes checksum validation to fail. Create a new migration instead.
|
|
145
|
+
|
|
146
|
+
Operation-based migrations (the generated form) hash their declared operations,
|
|
147
|
+
so their checksum is the same in every build. A callback-only migration hashes
|
|
148
|
+
the normalized source of `up()` and `down()`: comments, whitespace, `;`,
|
|
149
|
+
trailing commas and quote style are ignored. A build that rewrites the code
|
|
150
|
+
(minification, renamed variables, older `async` targets) still changes it, so
|
|
151
|
+
use `operations` when the checksum must survive different build tools.
|
|
152
|
+
|
|
153
|
+
## Targets and plans
|
|
154
|
+
|
|
155
|
+
Select the environment and database target explicitly:
|
|
156
|
+
|
|
157
|
+
```sh
|
|
158
|
+
pnpm exec cossack migration plan --env staging --target remote --json
|
|
159
|
+
pnpm exec cossack migration up --env staging --target remote --dry-run --json
|
|
160
|
+
pnpm exec cossack migration up --env staging --target remote
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
`--local` and `--remote` are aliases for `--target`. The default is local.
|
|
164
|
+
The selected environment also accepts `CLOUDFLARE_ENV`. Adapter factories
|
|
165
|
+
receive an `ORMToolingContext` with the project root, configuration path, environment,
|
|
166
|
+
target, and `readOnly` flag. A remote command requires a factory so the adapter
|
|
167
|
+
can honor that selection. See [D1 tooling](./runtimes.md#d1-tooling) for generated
|
|
168
|
+
Cloudflare projects.
|
|
169
|
+
|
|
170
|
+
`plan` reads migration history without creating its table and never executes
|
|
171
|
+
migration callbacks. Generated migrations declare authoritative `operations` for
|
|
172
|
+
`up` and `down`. Those same operations drive execution. Callbacks cannot override
|
|
173
|
+
them. Each entry includes its direction, checksum, mode, ordered SQL, affected
|
|
174
|
+
objects, parameter counts, risk, target connection identity, atomicity and
|
|
175
|
+
provider limitations. Parameter values are omitted. Raw SQL object discovery and
|
|
176
|
+
risk classification are conservative. `affectedObjectsComplete: false` makes
|
|
177
|
+
that limit explicit. Review the SQL itself.
|
|
178
|
+
Use `--direction down` to preview the most recent reversal. A squash that
|
|
179
|
+
replaces fully applied migrations reports `mode: "consolidate"` without
|
|
180
|
+
replaying application SQL.
|
|
181
|
+
|
|
182
|
+
For a remote smoke test, first point a named Wrangler environment such as
|
|
183
|
+
`staging` at a dedicated disposable D1 database. Review its resolved target and
|
|
184
|
+
plan, then apply only the reviewed migration set:
|
|
185
|
+
|
|
186
|
+
```sh
|
|
187
|
+
pnpm exec cossack migration plan --env staging --target remote --json
|
|
188
|
+
pnpm exec cossack migration up --env staging --target remote --dry-run --json
|
|
189
|
+
pnpm exec cossack migration up --env staging --target remote
|
|
190
|
+
pnpm exec cossack migration check --env staging --target remote --json
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
This procedure is opt-in. Never point it at production for a smoke test. Remote
|
|
194
|
+
commands require `--target remote` (or `--remote`). An environment name alone
|
|
195
|
+
always uses local state.
|
|
196
|
+
|
|
197
|
+
Legacy callbacks remain executable through explicit `up()` and `down()`, but
|
|
198
|
+
planning reports them as incomplete without invoking them. Planning does not
|
|
199
|
+
invoke a callback because a disconnected ORM cannot stop it from writing files,
|
|
200
|
+
calling external services, or using another captured connection. Configuration
|
|
201
|
+
module loading is trusted application code. This boundary does not sandbox imports.
|
|
202
|
+
|
|
203
|
+
For application-controlled review and apply in one process:
|
|
204
|
+
|
|
205
|
+
```ts
|
|
206
|
+
const runner = new MigrationRunner(orm, migrations);
|
|
207
|
+
const plan = await runner.plan();
|
|
208
|
+
// Review plan, including incomplete entries and provider limitations.
|
|
209
|
+
await runner.applyPlan(plan);
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
`applyPlan()` accepts only the exact plan returned by that live runner. It rejects
|
|
213
|
+
incomplete plans and rechecks all migration definitions, checksums, history and
|
|
214
|
+
target identity before writing. Its private SQL/parameter snapshot prevents later
|
|
215
|
+
application mutations from changing the approved batch. JSON reports are inspection
|
|
216
|
+
artifacts. They cannot be imported as executable approvals. Separate CLI invocations
|
|
217
|
+
must replan on their selected target. Concurrent external writers still need a
|
|
218
|
+
provider-specific deployment lock. History rechecks are not a distributed lock.
|
|
219
|
+
|
|
220
|
+
Bookkeeping SQL is reported separately, including squash consolidation deletes
|
|
221
|
+
and the replacement history insert. Missing declarative `down` operations mean a
|
|
222
|
+
reversal is unknown and cannot be applied from a plan. MySQL DDL can commit
|
|
223
|
+
implicitly. A transaction does not guarantee schema rollback. Providers with
|
|
224
|
+
neither transactions nor an atomic batch report possible partial application.
|
|
225
|
+
|
|
226
|
+
`--dry-run` also previews snapshot, generate, squash, and schema pull file
|
|
227
|
+
changes without writing them. `status` and `check` read history without
|
|
228
|
+
initializing bookkeeping. JSON commands emit one `schemaVersion: 1` envelope
|
|
229
|
+
with `ok`, target context, resolved adapter identity when available, results,
|
|
230
|
+
and diagnostics. Invalid flags, conflicting targets, and extra arguments fail
|
|
231
|
+
before opening the adapter.
|
|
232
|
+
|
|
233
|
+
JSON commands execute configuration and adapters in a child process. Console
|
|
234
|
+
messages, direct stdout/stderr writes, and inherited subprocess output are
|
|
235
|
+
suppressed. The structured result returns over IPC. This keeps Wrangler
|
|
236
|
+
connection logs out of JSON and prevents configuration code from changing the
|
|
237
|
+
calling process's environment. It is output isolation, not a sandbox for
|
|
238
|
+
application code. Unexpected child termination produces
|
|
239
|
+
`COSSACK_ORM_PROCESS_FAILED`. Text mode retains raw diagnostics.
|
|
145
240
|
|
|
146
241
|
## Destructive changes
|
|
147
242
|
|
|
@@ -201,6 +296,24 @@ cossack-orm schema pull \
|
|
|
201
296
|
Unknown physical database types are retained with a `custom:<type>` logical
|
|
202
297
|
type rather than discarded.
|
|
203
298
|
|
|
299
|
+
The comparison ignores differences that the database cannot store or that
|
|
300
|
+
mean the same thing:
|
|
301
|
+
|
|
302
|
+
- `now()`, `CURRENT_TIMESTAMP` and `transaction_timestamp()` are the same
|
|
303
|
+
default.
|
|
304
|
+
- The enum `CHECK (column IN (...))` that the ORM creates is read back as an
|
|
305
|
+
`enum` column with the same values. Other check constraints still stop
|
|
306
|
+
PostgreSQL and MySQL introspection, because they cannot be represented.
|
|
307
|
+
- On SQLite, a single `INTEGER PRIMARY KEY` matches a model key whether or not
|
|
308
|
+
the model marks it as generated. Only `UNIQUE` constraints mark a column as
|
|
309
|
+
unique. A `CREATE UNIQUE INDEX` stays an index.
|
|
310
|
+
- On PostgreSQL, `increment` and identity columns match.
|
|
311
|
+
- On MySQL, a column-level `UNIQUE` is recognized by its index name, which is
|
|
312
|
+
the column name. Indexes that MySQL creates for foreign keys are not reported.
|
|
313
|
+
Functional, prefix, `FULLTEXT` and `SPATIAL` indexes stop introspection.
|
|
314
|
+
- Many-to-many join tables belong to their owning model and are not reported as
|
|
315
|
+
extra tables.
|
|
316
|
+
|
|
204
317
|
## Baseline an existing database
|
|
205
318
|
|
|
206
319
|
Baseline lets an existing deployment adopt migration bookkeeping without
|
|
@@ -210,7 +323,7 @@ replaying its historical schema creation:
|
|
|
210
323
|
cossack-orm migration baseline
|
|
211
324
|
```
|
|
212
325
|
|
|
213
|
-
The CLI first
|
|
326
|
+
The CLI first makes sure that the live database matches current model metadata.
|
|
214
327
|
Only then does it record the schema hash. Resolve drift before baselining.
|
|
215
328
|
|
|
216
329
|
## Programmatic runner
|
|
@@ -229,4 +342,4 @@ const status = await orm.run(() => runner.status());
|
|
|
229
342
|
Transactional adapters apply a migration and its bookkeeping together. D1 uses
|
|
230
343
|
an atomic prepared batch for schema statements plus bookkeeping.
|
|
231
344
|
|
|
232
|
-
See [Seeders](./seeders.md) for application data that
|
|
345
|
+
See [Seeders](./seeders.md) for application data that is safe to rerun.
|
package/docs/models.md
CHANGED
|
@@ -6,7 +6,7 @@ description: Define decorated Active Record models, columns, keys, indexes, time
|
|
|
6
6
|
# Models
|
|
7
7
|
|
|
8
8
|
A model is a decorated class extending `BaseEntity`. Decorators describe its
|
|
9
|
-
logical schema
|
|
9
|
+
logical schema. `BaseEntity` supplies static query methods and instance
|
|
10
10
|
persistence methods.
|
|
11
11
|
|
|
12
12
|
```ts
|
|
@@ -73,11 +73,11 @@ class User extends BaseEntity {
|
|
|
73
73
|
}
|
|
74
74
|
```
|
|
75
75
|
|
|
76
|
-
`name` is the logical model name
|
|
76
|
+
`name` is the logical model name. `tableName` is the database table.
|
|
77
77
|
|
|
78
78
|
## Column types
|
|
79
79
|
|
|
80
|
-
When reflection is available, `@Column()`
|
|
80
|
+
When reflection is available, `@Column()` infers these logical types:
|
|
81
81
|
|
|
82
82
|
| TypeScript design type | Logical type |
|
|
83
83
|
| --- | --- |
|
|
@@ -107,6 +107,24 @@ Supported logical types are `varchar`, `text`, `integer`, `bigint`, `decimal`,
|
|
|
107
107
|
`boolean`, `datetime`, `date`, `json`, `enum`, `blob`, `uuid`, and
|
|
108
108
|
`custom:<database-type>`.
|
|
109
109
|
|
|
110
|
+
`datetime` values are always stored in UTC. On SQLite, D1, Turso and MySQL, the
|
|
111
|
+
ORM writes a `Date` as `YYYY-MM-DD HH:MM:SS.SSS`. This is the same text shape
|
|
112
|
+
that `DEFAULT CURRENT_TIMESTAMP` produces, so values that the application writes
|
|
113
|
+
and values that the database fills in sort and compare correctly. On
|
|
114
|
+
PostgreSQL, the ORM sends an ISO string with `Z` to a `timestamptz` column. When
|
|
115
|
+
the ORM reads a timestamp that has no offset, it reads it as UTC, not as the
|
|
116
|
+
time zone of the server or of the process. `date` values are written as
|
|
117
|
+
`YYYY-MM-DD` and read as midnight UTC.
|
|
118
|
+
|
|
119
|
+
On MySQL, a `datetime` column is `DATETIME(3)`, so milliseconds survive a round
|
|
120
|
+
trip, and a `CURRENT_TIMESTAMP` default is written as `CURRENT_TIMESTAMP(3)`.
|
|
121
|
+
Tables created before this keep a `DATETIME` column, which rounds values to
|
|
122
|
+
whole seconds. Change such a column with explicit SQL, for example
|
|
123
|
+
`ALTER TABLE events MODIFY created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3)`.
|
|
124
|
+
The Node MySQL adapter sets each session's time zone to UTC so that
|
|
125
|
+
`CURRENT_TIMESTAMP` defaults are UTC. Through Hyperdrive, the MySQL server's
|
|
126
|
+
time zone must be UTC (see [Runtimes](./runtimes.md#cloudflare-hyperdrive)).
|
|
127
|
+
|
|
110
128
|
Common column options include:
|
|
111
129
|
|
|
112
130
|
```ts
|
|
@@ -123,6 +141,20 @@ Common column options include:
|
|
|
123
141
|
declare externalId: string;
|
|
124
142
|
```
|
|
125
143
|
|
|
144
|
+
`select: false` hides a column (for example a password hash) from every query
|
|
145
|
+
that does not ask for it: `find()`, `findOne()`, `query().getMany()` and raw
|
|
146
|
+
rows. The property stays `undefined`, and saving such an entity leaves the
|
|
147
|
+
stored value alone. Load it explicitly with `query().addSelect("passwordHash")`,
|
|
148
|
+
which keeps the default columns, or with `find({ select: [...] })`, which loads
|
|
149
|
+
only the listed columns. The default columns always include primary, version
|
|
150
|
+
and owned relation join columns, even when they are marked `select: false`.
|
|
151
|
+
`reload()` refreshes a hidden column only when the instance already holds it.
|
|
152
|
+
|
|
153
|
+
`insert: false` and `update: false` apply to entity saves and to the static
|
|
154
|
+
`insert()`, `upsert()` and `update()` methods. Entity saves skip such columns.
|
|
155
|
+
The static methods reject a value for them with a `ConfigurationError`. An
|
|
156
|
+
upsert inserts `update: false` columns but never overwrites them on conflict.
|
|
157
|
+
|
|
126
158
|
Use `renamedFrom` when a model property maps to a renamed database column.
|
|
127
159
|
Migration generation never guesses renames heuristically.
|
|
128
160
|
|
|
@@ -197,8 +229,9 @@ declare version: number;
|
|
|
197
229
|
```
|
|
198
230
|
|
|
199
231
|
`save()` fills create/update timestamps and increments version columns.
|
|
200
|
-
Optimistic updates fail when the stored version
|
|
201
|
-
|
|
232
|
+
Optimistic updates fail when another writer changed the stored version.
|
|
233
|
+
`remove()` writes the
|
|
234
|
+
delete timestamp when a `@DeleteDateColumn()` exists. Otherwise it deletes the
|
|
202
235
|
row. Queries do not implicitly hide timestamped rows, so add an explicit
|
|
203
236
|
`deletedAt: null` predicate when that is the desired application policy.
|
|
204
237
|
|
|
@@ -222,7 +255,7 @@ await orm.run(async () => {
|
|
|
222
255
|
```
|
|
223
256
|
|
|
224
257
|
Hydrated entities retain an original snapshot. Existing entities update only
|
|
225
|
-
changed persisted fields
|
|
258
|
+
changed persisted fields. New entities are inserted.
|
|
226
259
|
|
|
227
260
|
## Lifecycle hooks
|
|
228
261
|
|
|
@@ -233,7 +266,7 @@ Available hook decorators are:
|
|
|
233
266
|
- `@BeforeRemove()` and `@AfterRemove()`
|
|
234
267
|
- `@AfterLoad()`
|
|
235
268
|
|
|
236
|
-
Hooks
|
|
269
|
+
Hooks can be synchronous or asynchronous. Keep database side effects deliberate:
|
|
237
270
|
a hook runs as part of the surrounding save/remove operation and uses the
|
|
238
271
|
current ORM or transaction scope.
|
|
239
272
|
|
package/docs/queries.md
CHANGED
|
@@ -101,6 +101,11 @@ const users = await User.find({
|
|
|
101
101
|
|
|
102
102
|
Properties inside one object are joined with `AND`.
|
|
103
103
|
|
|
104
|
+
A property set to `undefined` throws a `ConfigurationError` instead of
|
|
105
|
+
compiling to `= NULL`, which never matches. Use `null` or `IsNull()` to match
|
|
106
|
+
`NULL`, or leave the property out to skip that filter. `In([])` matches no rows,
|
|
107
|
+
and an empty array of `where` objects also matches no rows.
|
|
108
|
+
|
|
104
109
|
## Query builder
|
|
105
110
|
|
|
106
111
|
Start a builder with `Entity.query()`:
|
|
@@ -145,6 +150,17 @@ const rows = await User.query("user")
|
|
|
145
150
|
.getRawMany();
|
|
146
151
|
```
|
|
147
152
|
|
|
153
|
+
`addSelect()` adds properties to the default columns (or to an earlier
|
|
154
|
+
`select()`). Use it to load `select: false` columns:
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
const user = await User.query().addSelect("passwordHash").where({ email }).getOne();
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
A `select()` that includes every primary column still hydrates entities and
|
|
161
|
+
paginates like a default query. Projections without the primary key need an
|
|
162
|
+
explicit unique `orderBy()` before `limit()` or `offset()`.
|
|
163
|
+
|
|
148
164
|
Use `selectRaw()` for calculated or database-specific projections:
|
|
149
165
|
|
|
150
166
|
```ts
|
|
@@ -159,8 +175,8 @@ const totals = await User.query("user")
|
|
|
159
175
|
.getRawMany();
|
|
160
176
|
```
|
|
161
177
|
|
|
162
|
-
Use `getMany()`
|
|
163
|
-
|
|
178
|
+
Use `getMany()` for complete entity rows. The ORM hydrates them as model
|
|
179
|
+
instances. Use `getRawMany()` for custom projections.
|
|
164
180
|
|
|
165
181
|
## Joins
|
|
166
182
|
|
|
@@ -182,7 +198,7 @@ const rows = await User.query("user")
|
|
|
182
198
|
```
|
|
183
199
|
|
|
184
200
|
Available joins are `innerJoin()` and `leftJoin()`. For ordinary model
|
|
185
|
-
relationships, prefer explicit `relations` loading
|
|
201
|
+
relationships, prefer explicit `relations` loading. It hydrates both sides and
|
|
186
202
|
batches relation keys.
|
|
187
203
|
|
|
188
204
|
## Aggregates
|
|
@@ -225,7 +241,22 @@ await User.delete({ active: false });
|
|
|
225
241
|
```
|
|
226
242
|
|
|
227
243
|
These methods return a normalized `QueryResult` containing `rows` and `meta`.
|
|
228
|
-
|
|
244
|
+
They reject values for columns declared with `insert: false` (insert/upsert) or
|
|
245
|
+
`update: false` (update).
|
|
246
|
+
|
|
247
|
+
`update()` and `delete()` need a `where` with at least one condition. An empty
|
|
248
|
+
object such as `User.delete({})` throws a `ConfigurationError`, because it
|
|
249
|
+
would change every row. To change every row on purpose, call the explicit
|
|
250
|
+
methods:
|
|
251
|
+
|
|
252
|
+
```ts
|
|
253
|
+
await Session.deleteAll();
|
|
254
|
+
await User.updateAll({ active: false });
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
`User.insert({})` inserts one row of column defaults. It compiles to
|
|
258
|
+
`INSERT INTO ... DEFAULT VALUES` on SQLite and PostgreSQL, and to
|
|
259
|
+
`INSERT INTO ... () VALUES ()` on MySQL.
|
|
229
260
|
|
|
230
261
|
For adapters that support `RETURNING`, use a mutation builder:
|
|
231
262
|
|
|
@@ -259,3 +290,21 @@ console.log(result.meta.operation);
|
|
|
259
290
|
|
|
260
291
|
See [Raw queries](./raw-queries.md) when a query cannot be expressed cleanly by
|
|
261
292
|
the model APIs.
|
|
293
|
+
|
|
294
|
+
## Stable pagination
|
|
295
|
+
|
|
296
|
+
For an entity query with `limit()` or `offset()`, Cossack appends each primary
|
|
297
|
+
key field to the order. An explicit primary key order keeps its direction.
|
|
298
|
+
This makes ties in other sort fields deterministic. An entity without a primary
|
|
299
|
+
key cannot use this automatic order.
|
|
300
|
+
|
|
301
|
+
Joined, grouped, distinct, and projected pages require an explicit unique order.
|
|
302
|
+
Include all fields needed to distinguish result rows. Cossack cannot infer their
|
|
303
|
+
uniqueness. Offset pages can shift when concurrent writes insert or delete rows.
|
|
304
|
+
Use a transaction when the provider supports the consistency your application needs.
|
|
305
|
+
|
|
306
|
+
For keyset pagination, use the existing predicate and order APIs. For example,
|
|
307
|
+
query rows with `id > lastSeenId`, order by `id`, and apply a limit. Composite
|
|
308
|
+
orders need a matching lexicographic predicate. There is no opaque cursor API.
|
|
309
|
+
`count()` and aggregates operate on the full predicate, independent of pagination,
|
|
310
|
+
and restore the query's original window after execution.
|
package/docs/raw-queries.md
CHANGED
|
@@ -49,7 +49,7 @@ await orm.sql`
|
|
|
49
49
|
`;
|
|
50
50
|
```
|
|
51
51
|
|
|
52
|
-
`input` is data, never executable SQL. PostgreSQL compiles it to `$1
|
|
52
|
+
`input` is data, never executable SQL. PostgreSQL compiles it to `$1`. SQLite
|
|
53
53
|
and MySQL use their corresponding placeholders.
|
|
54
54
|
|
|
55
55
|
Do not interpolate table or column names as strings. Use `sql.id()`:
|
|
@@ -102,6 +102,11 @@ const result = await orm.sql`
|
|
|
102
102
|
`;
|
|
103
103
|
```
|
|
104
104
|
|
|
105
|
+
An empty list throws a `ConfigurationError`, both in `sql.join([])` and when
|
|
106
|
+
you interpolate an empty array directly. Otherwise the query would compile to
|
|
107
|
+
`IN ()`, which is invalid SQL. Check for an empty list before you build the
|
|
108
|
+
query.
|
|
109
|
+
|
|
105
110
|
Use `values()` for object or bulk inserts:
|
|
106
111
|
|
|
107
112
|
```ts
|
|
@@ -116,7 +121,7 @@ await orm.sql`
|
|
|
116
121
|
```
|
|
117
122
|
|
|
118
123
|
Every row passed to `values()` must have the same columns in the same order.
|
|
119
|
-
Large application writes
|
|
124
|
+
Large application writes must respect `orm.driver.capabilities.parameterLimit`
|
|
120
125
|
and `batchLimit`.
|
|
121
126
|
|
|
122
127
|
## Unsafe SQL
|
|
@@ -150,10 +155,10 @@ Within a scope, the global tag also exposes `execute()`, `transaction()`,
|
|
|
150
155
|
|
|
151
156
|
## Standalone SQL client
|
|
152
157
|
|
|
153
|
-
Use `SQL` when models and entity metadata are unnecessary:
|
|
158
|
+
Use the Node runtime's `SQL` client when models and entity metadata are unnecessary:
|
|
154
159
|
|
|
155
160
|
```ts
|
|
156
|
-
import { SQL } from "@cossackframework/database";
|
|
161
|
+
import { SQL } from "@cossackframework/database/node";
|
|
157
162
|
|
|
158
163
|
const client = new SQL("sqlite:app.db");
|
|
159
164
|
|
|
@@ -172,8 +177,9 @@ try {
|
|
|
172
177
|
```
|
|
173
178
|
|
|
174
179
|
In Node.js, URL or path inference supports PostgreSQL, MySQL, Turso HTTPS URLs, and
|
|
175
|
-
SQLite. Bun delegates to native Bun SQL.
|
|
176
|
-
|
|
180
|
+
SQLite. Bun delegates to native Bun SQL. The package root's `SQL` export accepts
|
|
181
|
+
explicit adapters and remains runtime neutral. On Workers, use an
|
|
182
|
+
explicit adapter rather than URL guessing:
|
|
177
183
|
|
|
178
184
|
```ts
|
|
179
185
|
const client = new SQL({ adapter });
|
|
@@ -181,3 +187,17 @@ const client = new SQL({ adapter });
|
|
|
181
187
|
|
|
182
188
|
See [Runtimes](./runtimes.md) for adapter setup and
|
|
183
189
|
[Advanced usage](./advanced.md) for transactions and connection reservation.
|
|
190
|
+
|
|
191
|
+
## Query diagnostics
|
|
192
|
+
|
|
193
|
+
The ORM logger receives `sql`, parameter type markers, `durationMs`, `dialect`,
|
|
194
|
+
`provider`, `operation`, and `outcome`. A failed query includes only the fixed
|
|
195
|
+
code `COSSACK_DATABASE_QUERY_FAILED`. The event has no error object or message.
|
|
196
|
+
The SQL field is a bounded structural representation: literals and comments are
|
|
197
|
+
removed, and quoted identifiers are anonymous because some providers interpret
|
|
198
|
+
those tokens as values. It is diagnostic output, not executable SQL.
|
|
199
|
+
|
|
200
|
+
Parameter values are never included. Markers describe null, dates, binary size,
|
|
201
|
+
and JavaScript types. Logger exceptions are ignored so an observer cannot change
|
|
202
|
+
query or transaction results. Explicit callers still receive a `QueryError` and
|
|
203
|
+
must decide separately whether its private cause is safe to disclose.
|
package/docs/relationships.md
CHANGED
|
@@ -137,6 +137,9 @@ class User extends BaseEntity {
|
|
|
137
137
|
}
|
|
138
138
|
```
|
|
139
139
|
|
|
140
|
+
Load either side with `relations`. `User.find({ relations: ["profile"] })` sets
|
|
141
|
+
`profile` to the matching profile, or `null` when there is none.
|
|
142
|
+
|
|
140
143
|
## Many-to-many
|
|
141
144
|
|
|
142
145
|
Put `@JoinTable()` on exactly one side:
|
|
@@ -199,7 +202,7 @@ does not walk an in-memory object graph and delete related entities.
|
|
|
199
202
|
|
|
200
203
|
## Nullable and logical relations
|
|
201
204
|
|
|
202
|
-
Use `nullable` to describe whether an owning relation
|
|
205
|
+
Use `nullable` to describe whether an owning relation can be absent:
|
|
203
206
|
|
|
204
207
|
```ts
|
|
205
208
|
@ManyToOne(() => Team, (team) => team.members, {
|
|
@@ -209,8 +212,8 @@ Use `nullable` to describe whether an owning relation may be absent:
|
|
|
209
212
|
declare team: Relation<Team | null>;
|
|
210
213
|
```
|
|
211
214
|
|
|
212
|
-
Set `createForeignKeyConstraints: false` for a logical relation that
|
|
213
|
-
|
|
215
|
+
Set `createForeignKeyConstraints: false` for a logical relation that appears
|
|
216
|
+
in ORM metadata without creating a database foreign-key constraint:
|
|
214
217
|
|
|
215
218
|
```ts
|
|
216
219
|
@ManyToOne(() => ExternalAccount, {
|
|
@@ -241,3 +244,14 @@ export const entities = [User, Post, Role, UserProfile] as const;
|
|
|
241
244
|
|
|
242
245
|
ORM creation validates missing targets, invalid inverse properties, and
|
|
243
246
|
unresolved join metadata.
|
|
247
|
+
|
|
248
|
+
## Inspect finalized relationships
|
|
249
|
+
|
|
250
|
+
`orm.inspectMetadata()` returns a detached, frozen description of registered
|
|
251
|
+
entities, columns, indexes, and resolved relationship fields. It includes both
|
|
252
|
+
ends of relations and physical join names, but excludes constructors, callbacks,
|
|
253
|
+
and default values. Use it for tooling without mutating ORM metadata.
|
|
254
|
+
|
|
255
|
+
Registration rejects missing referenced fields, missing inverse relations,
|
|
256
|
+
incompatible inverse relation kinds, and inverses that point at another entity.
|
|
257
|
+
These errors identify both entity and field names before database statements run.
|