@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/docs/models.md ADDED
@@ -0,0 +1,241 @@
1
+ ---
2
+ title: Models
3
+ description: Define decorated Active Record models, columns, keys, indexes, timestamps, and hooks.
4
+ ---
5
+
6
+ # Models
7
+
8
+ A model is a decorated class extending `BaseEntity`. Decorators describe its
9
+ logical schema; `BaseEntity` supplies static query methods and instance
10
+ persistence methods.
11
+
12
+ ```ts
13
+ import {
14
+ BaseEntity,
15
+ BeforeInsert,
16
+ Column,
17
+ CreateDateColumn,
18
+ Entity,
19
+ Index,
20
+ PrimaryGeneratedColumn,
21
+ UpdateDateColumn,
22
+ } from "@cossackframework/database";
23
+
24
+ @Entity()
25
+ @Index("idx_users_name", ["name"])
26
+ export class User extends BaseEntity {
27
+ @PrimaryGeneratedColumn()
28
+ declare id: number;
29
+
30
+ @Column({ unique: true })
31
+ declare email: string;
32
+
33
+ @Column()
34
+ declare name: string;
35
+
36
+ @Column({ type: "json", nullable: true })
37
+ declare preferences: Record<string, unknown> | null;
38
+
39
+ @CreateDateColumn({ default: "CURRENT_TIMESTAMP" })
40
+ declare createdAt: Date;
41
+
42
+ @UpdateDateColumn({ default: "CURRENT_TIMESTAMP" })
43
+ declare updatedAt: Date;
44
+
45
+ @BeforeInsert()
46
+ normalizeEmail() {
47
+ this.email = this.email.trim().toLowerCase();
48
+ }
49
+ }
50
+ ```
51
+
52
+ ## Naming
53
+
54
+ The default naming strategy:
55
+
56
+ - Converts entity names to plural `snake_case` table names.
57
+ - Converts properties to `snake_case` columns.
58
+ - Builds relation and join-table names from those physical names.
59
+
60
+ `UserProfile` therefore maps to `user_profiles`, and `createdAt` maps to
61
+ `created_at`.
62
+
63
+ Override physical names when needed:
64
+
65
+ ```ts
66
+ @Entity({ name: "Account", tableName: "legacy_accounts" })
67
+ class User extends BaseEntity {
68
+ @PrimaryColumn({ name: "account_id", type: "uuid" })
69
+ declare id: string;
70
+
71
+ @Column({ name: "display_name" })
72
+ declare name: string;
73
+ }
74
+ ```
75
+
76
+ `name` is the logical model name; `tableName` is the database table.
77
+
78
+ ## Column types
79
+
80
+ When reflection is available, `@Column()` safely infers:
81
+
82
+ | TypeScript design type | Logical type |
83
+ | --- | --- |
84
+ | `String` | `varchar(255)` |
85
+ | `Number` | `integer` |
86
+ | `Boolean` | `boolean` |
87
+ | `Date` | `datetime` |
88
+ | `Uint8Array` or `ArrayBuffer` | `blob` |
89
+
90
+ Values that lose information through reflection require an explicit type:
91
+
92
+ ```ts
93
+ @Column({ type: "decimal", precision: 12, scale: 2 })
94
+ declare total: string;
95
+
96
+ @Column({ type: "enum", enum: ["draft", "published"] })
97
+ declare status: "draft" | "published";
98
+
99
+ @Column({ type: "json" })
100
+ declare metadata: Record<string, unknown>;
101
+
102
+ @Column({ type: "custom:geography", name: "location" })
103
+ declare location: unknown;
104
+ ```
105
+
106
+ Supported logical types are `varchar`, `text`, `integer`, `bigint`, `decimal`,
107
+ `boolean`, `datetime`, `date`, `json`, `enum`, `blob`, `uuid`, and
108
+ `custom:<database-type>`.
109
+
110
+ Common column options include:
111
+
112
+ ```ts
113
+ @Column({
114
+ name: "external_id",
115
+ type: "varchar",
116
+ length: 64,
117
+ nullable: false,
118
+ unique: true,
119
+ insert: true,
120
+ update: false,
121
+ select: true,
122
+ })
123
+ declare externalId: string;
124
+ ```
125
+
126
+ Use `renamedFrom` when a model property maps to a renamed database column.
127
+ Migration generation never guesses renames heuristically.
128
+
129
+ ## Primary and generated columns
130
+
131
+ ```ts
132
+ @PrimaryGeneratedColumn() // incrementing integer
133
+ declare id: number;
134
+
135
+ @PrimaryGeneratedColumn("identity") // SQL identity where supported
136
+ declare id: number;
137
+
138
+ @PrimaryGeneratedColumn("uuid")
139
+ declare id: string;
140
+ ```
141
+
142
+ For application-assigned or composite keys, use `@PrimaryColumn()`:
143
+
144
+ ```ts
145
+ @Entity()
146
+ class Translation extends BaseEntity {
147
+ @PrimaryColumn()
148
+ declare articleId: number;
149
+
150
+ @PrimaryColumn()
151
+ declare locale: string;
152
+
153
+ @Column("text")
154
+ declare body: string;
155
+ }
156
+ ```
157
+
158
+ Generated columns cannot participate in a composite primary key.
159
+
160
+ ## Indexes and unique constraints
161
+
162
+ Decorate one property:
163
+
164
+ ```ts
165
+ @Index("idx_posts_created_at")
166
+ @Column({ type: "datetime" })
167
+ declare createdAt: Date;
168
+ ```
169
+
170
+ Or decorate the class for compound indexes:
171
+
172
+ ```ts
173
+ @Entity()
174
+ @Index("idx_posts_author_status", ["authorId", "status"])
175
+ @Unique("uq_posts_author_slug", ["authorId", "slug"])
176
+ class Post extends BaseEntity {
177
+ // ...
178
+ }
179
+ ```
180
+
181
+ ## Timestamps, versions, and soft deletion
182
+
183
+ Special columns participate in persistence hooks:
184
+
185
+ ```ts
186
+ @CreateDateColumn()
187
+ declare createdAt: Date;
188
+
189
+ @UpdateDateColumn()
190
+ declare updatedAt: Date;
191
+
192
+ @DeleteDateColumn()
193
+ declare deletedAt: Date | null;
194
+
195
+ @VersionColumn()
196
+ declare version: number;
197
+ ```
198
+
199
+ `save()` fills create/update timestamps and increments version columns.
200
+ Optimistic updates fail when the stored version changed. `remove()` writes the
201
+ delete timestamp when a `@DeleteDateColumn()` exists; otherwise it deletes the
202
+ row. Queries do not implicitly hide timestamped rows, so add an explicit
203
+ `deletedAt: null` predicate when that is the desired application policy.
204
+
205
+ ## Creating and saving entities
206
+
207
+ ```ts
208
+ await orm.run(async () => {
209
+ const user = User.create({
210
+ email: "ada@example.com",
211
+ name: "Ada Lovelace",
212
+ });
213
+
214
+ await user.save();
215
+
216
+ user.name = "Augusta Ada King";
217
+ await user.save(); // updates only changed persisted fields
218
+
219
+ await user.reload();
220
+ await user.remove();
221
+ });
222
+ ```
223
+
224
+ Hydrated entities retain an original snapshot. Existing entities update only
225
+ changed persisted fields; new entities are inserted.
226
+
227
+ ## Lifecycle hooks
228
+
229
+ Available hook decorators are:
230
+
231
+ - `@BeforeInsert()` and `@AfterInsert()`
232
+ - `@BeforeUpdate()` and `@AfterUpdate()`
233
+ - `@BeforeRemove()` and `@AfterRemove()`
234
+ - `@AfterLoad()`
235
+
236
+ Hooks may be synchronous or asynchronous. Keep database side effects deliberate:
237
+ a hook runs as part of the surrounding save/remove operation and uses the
238
+ current ORM or transaction scope.
239
+
240
+ Continue with [Queries](./queries.md) and
241
+ [Relationships](./relationships.md).
@@ -0,0 +1,261 @@
1
+ ---
2
+ title: Queries
3
+ description: Read and mutate records with Active Record methods, find options, operators, and the fluent query builder.
4
+ ---
5
+
6
+ # Queries
7
+
8
+ Cossack ORM offers two complementary query APIs:
9
+
10
+ - Active Record methods for common reads and writes.
11
+ - A fluent query builder for projections, compound predicates, joins,
12
+ aggregates, grouping, and mutation `RETURNING` clauses.
13
+
14
+ Static methods require an active scope:
15
+
16
+ ```ts
17
+ await orm.run(async () => {
18
+ const users = await User.find();
19
+ });
20
+ ```
21
+
22
+ Framework middleware can establish this scope once for a request. When code
23
+ already owns an ORM instance, `orm.model(User)` provides explicit access without
24
+ static scope lookup:
25
+
26
+ ```ts
27
+ const users = await orm.model(User).find();
28
+ ```
29
+
30
+ ## Finding records
31
+
32
+ ```ts
33
+ const users = await User.find({
34
+ where: { active: true },
35
+ select: ["id", "email", "name"],
36
+ order: { name: "asc" },
37
+ take: 25,
38
+ skip: 50,
39
+ relations: ["posts"],
40
+ });
41
+ ```
42
+
43
+ When combining `select` with `relations`, include the primary/foreign-key
44
+ properties required to associate the requested relation.
45
+
46
+ Available read methods:
47
+
48
+ ```ts
49
+ const all = await User.find();
50
+
51
+ const one = await User.findOne({
52
+ where: { email: "ada@example.com" },
53
+ });
54
+
55
+ const admins = await User.findBy({ role: "admin" });
56
+ const count = await User.count({ active: true });
57
+ const exists = await User.exists({ email: "ada@example.com" });
58
+ ```
59
+
60
+ `findOne()` returns `null` when no row matches. `find()` and `findBy()` return
61
+ readonly arrays.
62
+
63
+ ## Find operators
64
+
65
+ Import operators for comparisons that cannot be represented by a plain value:
66
+
67
+ ```ts
68
+ import {
69
+ In,
70
+ IsNull,
71
+ LessThan,
72
+ Like,
73
+ MoreThanOrEqual,
74
+ Not,
75
+ NotIn,
76
+ } from "@cossackframework/database";
77
+
78
+ const users = await User.find({
79
+ where: {
80
+ age: MoreThanOrEqual(18),
81
+ email: Like("%@example.com"),
82
+ role: In(["admin", "editor"]),
83
+ deletedAt: IsNull(),
84
+ },
85
+ });
86
+ ```
87
+
88
+ Operators include `Equal`, `Not`, `MoreThan`, `MoreThanOrEqual`, `LessThan`,
89
+ `LessThanOrEqual`, `Like`, `In`, `NotIn`, and `IsNull`.
90
+
91
+ An array of `where` objects is joined with `OR`:
92
+
93
+ ```ts
94
+ const users = await User.find({
95
+ where: [
96
+ { email: "ada@example.com" },
97
+ { email: "grace@example.com" },
98
+ ],
99
+ });
100
+ ```
101
+
102
+ Properties inside one object are joined with `AND`.
103
+
104
+ ## Query builder
105
+
106
+ Start a builder with `Entity.query()`:
107
+
108
+ ```ts
109
+ const users = await User.query("user")
110
+ .where({ active: true })
111
+ .andWhere((where) => where.like("email", "%@example.com"))
112
+ .orderBy("createdAt", "desc")
113
+ .limit(20)
114
+ .offset(0)
115
+ .getMany();
116
+ ```
117
+
118
+ Callback predicates expose typed columns and boolean composition:
119
+
120
+ ```ts
121
+ const users = await User.query("user")
122
+ .where((where) =>
123
+ where.and(
124
+ where.eq("active", true),
125
+ where.or(
126
+ where.like("email", "%@example.com"),
127
+ where.like("email", "%@cossack.dev"),
128
+ ),
129
+ )
130
+ )
131
+ .getMany();
132
+ ```
133
+
134
+ The expression builder provides `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `like`,
135
+ `in`, `isNull`, `and`, `or`, and `not`.
136
+
137
+ ## Projection and raw rows
138
+
139
+ `select()` narrows the result shape at compile time:
140
+
141
+ ```ts
142
+ const rows = await User.query("user")
143
+ .select("id", "email")
144
+ .where({ active: true })
145
+ .getRawMany();
146
+ ```
147
+
148
+ Use `selectRaw()` for calculated or database-specific projections:
149
+
150
+ ```ts
151
+ const totals = await User.query("user")
152
+ .selectRaw<{ role: string; total: number }>(
153
+ orm.sql.fragment`
154
+ ${orm.sql.id("user", "role")},
155
+ COUNT(*) AS ${orm.sql.id("total")}
156
+ `,
157
+ )
158
+ .groupBy("role")
159
+ .getRawMany();
160
+ ```
161
+
162
+ Use `getMany()` when selecting complete entity rows that should be hydrated as
163
+ model instances. Use `getRawMany()` for custom projections.
164
+
165
+ ## Joins
166
+
167
+ Query-builder joins use physical table names and explicit safe SQL fragments:
168
+
169
+ ```ts
170
+ const rows = await User.query("user")
171
+ .innerJoin(
172
+ "posts",
173
+ "post",
174
+ orm.sql.fragment`
175
+ ${orm.sql.id("post", "author_id")} =
176
+ ${orm.sql.id("user", "id")}
177
+ `,
178
+ )
179
+ .where((where) => where.eq("active", true))
180
+ .distinct()
181
+ .getMany();
182
+ ```
183
+
184
+ Available joins are `innerJoin()` and `leftJoin()`. For ordinary model
185
+ relationships, prefer explicit `relations` loading; it hydrates both sides and
186
+ batches relation keys.
187
+
188
+ ## Aggregates
189
+
190
+ ```ts
191
+ const total = await User.query().count();
192
+ const hasAny = await User.query().where({ active: true }).exists();
193
+ const sum = await Invoice.query().sum("amount");
194
+ const average = await Invoice.query().average("amount");
195
+ const minimum = await Invoice.query().minimum("amount");
196
+ const maximum = await Invoice.query().maximum("amount");
197
+ ```
198
+
199
+ `sum`, `average`, `minimum`, and `maximum` return `number | null`.
200
+
201
+ ## Inserts, upserts, updates, and deletes
202
+
203
+ ```ts
204
+ await User.insert({
205
+ email: "ada@example.com",
206
+ name: "Ada Lovelace",
207
+ });
208
+
209
+ await User.insert([
210
+ { email: "ada@example.com", name: "Ada" },
211
+ { email: "grace@example.com", name: "Grace" },
212
+ ]);
213
+
214
+ await User.upsert(
215
+ { email: "ada@example.com", name: "Augusta Ada King" },
216
+ ["email"],
217
+ );
218
+
219
+ await User.update(
220
+ { email: "ada@example.com" },
221
+ { name: "Ada Lovelace" },
222
+ );
223
+
224
+ await User.delete({ active: false });
225
+ ```
226
+
227
+ These methods return a normalized `QueryResult` containing `rows` and `meta`.
228
+ Always make bulk update/delete predicates explicit.
229
+
230
+ For adapters that support `RETURNING`, use a mutation builder:
231
+
232
+ ```ts
233
+ const result = await orm.model(User)
234
+ .insertQuery({
235
+ email: "ada@example.com",
236
+ name: "Ada",
237
+ })
238
+ .returning("id", "email")
239
+ .execute<{ id: number; email: string }>();
240
+ ```
241
+
242
+ MySQL reports `RETURNING` as an unsupported capability instead of emulating it.
243
+
244
+ ## Result metadata
245
+
246
+ Every execution returns normalized metadata:
247
+
248
+ ```ts
249
+ const result = await User.update(
250
+ { active: false },
251
+ { active: true },
252
+ );
253
+
254
+ console.log(result.meta.rowsAffected);
255
+ console.log(result.meta.durationMs);
256
+ console.log(result.meta.dialect);
257
+ console.log(result.meta.operation);
258
+ ```
259
+
260
+ See [Raw queries](./raw-queries.md) when a query cannot be expressed cleanly by
261
+ the model APIs.
@@ -0,0 +1,183 @@
1
+ ---
2
+ title: Raw Queries
3
+ description: Write parameterized, dialect-aware SQL with safe fragments, identifiers, bulk values, and normalized results.
4
+ ---
5
+
6
+ # Raw Queries
7
+
8
+ The `sql` API is the escape hatch for database-specific or unusually complex
9
+ queries. It builds an immutable fragment tree: interpolated values become bound
10
+ parameters, while identifiers are quoted by the selected dialect.
11
+
12
+ ## Scoped and bound SQL tags
13
+
14
+ The global tag resolves through the current ORM scope:
15
+
16
+ ```ts
17
+ import { sql } from "@cossackframework/database";
18
+
19
+ await orm.run(async () => {
20
+ const email = "ada@example.com";
21
+ const result = await sql<{ id: number; email: string }>`
22
+ SELECT ${sql.id("id")}, ${sql.id("email")}
23
+ FROM ${sql.id("users")}
24
+ WHERE ${sql.id("email")} = ${email}
25
+ `;
26
+ });
27
+ ```
28
+
29
+ When code owns an ORM instance, use its bound tag without scope lookup:
30
+
31
+ ```ts
32
+ const result = await orm.sql<{ total: number }>`
33
+ SELECT COUNT(*) AS ${orm.sql.id("total")}
34
+ FROM ${orm.sql.id("users")}
35
+ `;
36
+ ```
37
+
38
+ The result has `rows` and normalized `meta`.
39
+
40
+ ## Values are always parameters
41
+
42
+ ```ts
43
+ const input = "'; DROP TABLE users; --";
44
+
45
+ await orm.sql`
46
+ SELECT *
47
+ FROM ${orm.sql.id("users")}
48
+ WHERE ${orm.sql.id("email")} = ${input}
49
+ `;
50
+ ```
51
+
52
+ `input` is data, never executable SQL. PostgreSQL compiles it to `$1`; SQLite
53
+ and MySQL use their corresponding placeholders.
54
+
55
+ Do not interpolate table or column names as strings. Use `sql.id()`:
56
+
57
+ ```ts
58
+ const table = "audit_events";
59
+ const column = "created_at";
60
+
61
+ const rows = await orm.sql`
62
+ SELECT ${orm.sql.id(column)}
63
+ FROM ${orm.sql.id(table)}
64
+ `;
65
+ ```
66
+
67
+ Multiple arguments form a qualified identifier:
68
+
69
+ ```ts
70
+ orm.sql.id("user", "email");
71
+ ```
72
+
73
+ ## Reusable fragments
74
+
75
+ Build a fragment without executing it:
76
+
77
+ ```ts
78
+ const published = orm.sql.fragment`
79
+ ${orm.sql.id("published")} = ${true}
80
+ `;
81
+
82
+ const result = await orm.sql`
83
+ SELECT *
84
+ FROM ${orm.sql.id("posts")}
85
+ WHERE ${published}
86
+ `;
87
+ ```
88
+
89
+ Fragments remain parameterized when nested.
90
+
91
+ ## Lists and bulk values
92
+
93
+ Use `join()` for a dynamic list:
94
+
95
+ ```ts
96
+ const ids = [1, 2, 3];
97
+
98
+ const result = await orm.sql`
99
+ SELECT *
100
+ FROM ${orm.sql.id("users")}
101
+ WHERE ${orm.sql.id("id")} IN (${orm.sql.join(ids)})
102
+ `;
103
+ ```
104
+
105
+ Use `values()` for object or bulk inserts:
106
+
107
+ ```ts
108
+ const values = orm.sql.values([
109
+ { email: "ada@example.com", active: true },
110
+ { email: "grace@example.com", active: false },
111
+ ]);
112
+
113
+ await orm.sql`
114
+ INSERT INTO ${orm.sql.id("users")} ${values}
115
+ `;
116
+ ```
117
+
118
+ Every row passed to `values()` must have the same columns in the same order.
119
+ Large application writes should respect `orm.driver.capabilities.parameterLimit`
120
+ and `batchLimit`.
121
+
122
+ ## Unsafe SQL
123
+
124
+ `unsafe()` is the only API that injects literal SQL:
125
+
126
+ ```ts
127
+ await orm.sql`
128
+ SELECT ${orm.sql.unsafe("CURRENT_TIMESTAMP")}
129
+ `;
130
+ ```
131
+
132
+ Use it only for trusted static syntax such as a SQL function, operator, or
133
+ reviewed migration statement. Never pass request data, form values, headers, or
134
+ untrusted configuration to `unsafe()`.
135
+
136
+ ## Executing an existing fragment
137
+
138
+ ```ts
139
+ const fragment = orm.sql.fragment`
140
+ DELETE FROM ${orm.sql.id("sessions")}
141
+ WHERE ${orm.sql.id("expires_at")} < ${new Date()}
142
+ `;
143
+
144
+ const result = await orm.sql.execute(fragment);
145
+ console.log(result.meta.rowsAffected);
146
+ ```
147
+
148
+ Within a scope, the global tag also exposes `execute()`, `transaction()`,
149
+ `reserve()`, and `close()`.
150
+
151
+ ## Standalone SQL client
152
+
153
+ Use `SQL` when models and entity metadata are unnecessary:
154
+
155
+ ```ts
156
+ import { SQL } from "@cossackframework/database";
157
+
158
+ const client = new SQL("sqlite:app.db");
159
+
160
+ try {
161
+ await client`
162
+ INSERT INTO messages (body)
163
+ VALUES (${"Safe value"})
164
+ `;
165
+
166
+ const result = await client<{ body: string }>`
167
+ SELECT body FROM messages
168
+ `;
169
+ } finally {
170
+ await client.close();
171
+ }
172
+ ```
173
+
174
+ In Node.js, URL or path inference supports PostgreSQL, MySQL, Turso HTTPS URLs, and
175
+ SQLite. Bun delegates to native Bun SQL. Workers and Deno require an explicit
176
+ adapter rather than environment guessing:
177
+
178
+ ```ts
179
+ const client = new SQL({ adapter });
180
+ ```
181
+
182
+ See [Runtimes](./runtimes.md) for adapter setup and
183
+ [Advanced usage](./advanced.md) for transactions and connection reservation.