@cossackframework/database 0.8.0-readmesafe.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/dist/adapter/index.d.ts +4 -0
  4. package/dist/adapter/index.d.ts.map +1 -0
  5. package/dist/adapter/index.js +3 -0
  6. package/dist/adapter/index.js.map +1 -0
  7. package/dist/adapter/memory.d.ts +23 -0
  8. package/dist/adapter/memory.d.ts.map +1 -0
  9. package/dist/adapter/memory.js +53 -0
  10. package/dist/adapter/memory.js.map +1 -0
  11. package/dist/adapter/scope.d.ts +7 -0
  12. package/dist/adapter/scope.d.ts.map +1 -0
  13. package/dist/adapter/scope.js +7 -0
  14. package/dist/adapter/scope.js.map +1 -0
  15. package/dist/adapter/types.d.ts +73 -0
  16. package/dist/adapter/types.d.ts.map +1 -0
  17. package/dist/adapter/types.js +2 -0
  18. package/dist/adapter/types.js.map +1 -0
  19. package/dist/cli.d.ts +3 -0
  20. package/dist/cli.d.ts.map +1 -0
  21. package/dist/cli.js +6 -0
  22. package/dist/cli.js.map +1 -0
  23. package/dist/codec.d.ts +4 -0
  24. package/dist/codec.d.ts.map +1 -0
  25. package/dist/codec.js +52 -0
  26. package/dist/codec.js.map +1 -0
  27. package/dist/config.d.ts +19 -0
  28. package/dist/config.d.ts.map +1 -0
  29. package/dist/config.js +4 -0
  30. package/dist/config.js.map +1 -0
  31. package/dist/cossack/index.d.ts +49 -0
  32. package/dist/cossack/index.d.ts.map +1 -0
  33. package/dist/cossack/index.js +254 -0
  34. package/dist/cossack/index.js.map +1 -0
  35. package/dist/dialect/dialects.d.ts +6 -0
  36. package/dist/dialect/dialects.d.ts.map +1 -0
  37. package/dist/dialect/dialects.js +102 -0
  38. package/dist/dialect/dialects.js.map +1 -0
  39. package/dist/entity/base-entity.d.ts +21 -0
  40. package/dist/entity/base-entity.d.ts.map +1 -0
  41. package/dist/entity/base-entity.js +64 -0
  42. package/dist/entity/base-entity.js.map +1 -0
  43. package/dist/entity/manager.d.ts +25 -0
  44. package/dist/entity/manager.d.ts.map +1 -0
  45. package/dist/entity/manager.js +72 -0
  46. package/dist/entity/manager.js.map +1 -0
  47. package/dist/errors.d.ts +37 -0
  48. package/dist/errors.d.ts.map +1 -0
  49. package/dist/errors.js +62 -0
  50. package/dist/errors.js.map +1 -0
  51. package/dist/index.d.ts +25 -0
  52. package/dist/index.d.ts.map +1 -0
  53. package/dist/index.js +21 -0
  54. package/dist/index.js.map +1 -0
  55. package/dist/metadata/decorators.d.ts +27 -0
  56. package/dist/metadata/decorators.d.ts.map +1 -0
  57. package/dist/metadata/decorators.js +271 -0
  58. package/dist/metadata/decorators.js.map +1 -0
  59. package/dist/metadata/finalize.d.ts +4 -0
  60. package/dist/metadata/finalize.d.ts.map +1 -0
  61. package/dist/metadata/finalize.js +267 -0
  62. package/dist/metadata/finalize.js.map +1 -0
  63. package/dist/metadata/naming.d.ts +9 -0
  64. package/dist/metadata/naming.d.ts.map +1 -0
  65. package/dist/metadata/naming.js +21 -0
  66. package/dist/metadata/naming.js.map +1 -0
  67. package/dist/metadata/stage3.d.ts +26 -0
  68. package/dist/metadata/stage3.d.ts.map +1 -0
  69. package/dist/metadata/stage3.js +38 -0
  70. package/dist/metadata/stage3.js.map +1 -0
  71. package/dist/metadata/store.d.ts +29 -0
  72. package/dist/metadata/store.d.ts.map +1 -0
  73. package/dist/metadata/store.js +22 -0
  74. package/dist/metadata/store.js.map +1 -0
  75. package/dist/metadata/types.d.ts +83 -0
  76. package/dist/metadata/types.d.ts.map +1 -0
  77. package/dist/metadata/types.js +2 -0
  78. package/dist/metadata/types.js.map +1 -0
  79. package/dist/migration/runner.d.ts +22 -0
  80. package/dist/migration/runner.d.ts.map +1 -0
  81. package/dist/migration/runner.js +182 -0
  82. package/dist/migration/runner.js.map +1 -0
  83. package/dist/migration/types.d.ts +26 -0
  84. package/dist/migration/types.d.ts.map +1 -0
  85. package/dist/migration/types.js +2 -0
  86. package/dist/migration/types.js.map +1 -0
  87. package/dist/orm.d.ts +63 -0
  88. package/dist/orm.d.ts.map +1 -0
  89. package/dist/orm.js +643 -0
  90. package/dist/orm.js.map +1 -0
  91. package/dist/query/builder.d.ts +63 -0
  92. package/dist/query/builder.d.ts.map +1 -0
  93. package/dist/query/builder.js +303 -0
  94. package/dist/query/builder.js.map +1 -0
  95. package/dist/query/expression.d.ts +27 -0
  96. package/dist/query/expression.d.ts.map +1 -0
  97. package/dist/query/expression.js +90 -0
  98. package/dist/query/expression.js.map +1 -0
  99. package/dist/query/types.d.ts +33 -0
  100. package/dist/query/types.d.ts.map +1 -0
  101. package/dist/query/types.js +11 -0
  102. package/dist/query/types.js.map +1 -0
  103. package/dist/runtime/bun.d.ts +30 -0
  104. package/dist/runtime/bun.d.ts.map +1 -0
  105. package/dist/runtime/bun.js +63 -0
  106. package/dist/runtime/bun.js.map +1 -0
  107. package/dist/runtime/cloudflare.d.ts +70 -0
  108. package/dist/runtime/cloudflare.d.ts.map +1 -0
  109. package/dist/runtime/cloudflare.js +230 -0
  110. package/dist/runtime/cloudflare.js.map +1 -0
  111. package/dist/runtime/deno.d.ts +26 -0
  112. package/dist/runtime/deno.d.ts.map +1 -0
  113. package/dist/runtime/deno.js +40 -0
  114. package/dist/runtime/deno.js.map +1 -0
  115. package/dist/runtime/helpers.d.ts +4 -0
  116. package/dist/runtime/helpers.d.ts.map +1 -0
  117. package/dist/runtime/helpers.js +22 -0
  118. package/dist/runtime/helpers.js.map +1 -0
  119. package/dist/runtime/node.d.ts +88 -0
  120. package/dist/runtime/node.d.ts.map +1 -0
  121. package/dist/runtime/node.js +221 -0
  122. package/dist/runtime/node.js.map +1 -0
  123. package/dist/schema/builder.d.ts +16 -0
  124. package/dist/schema/builder.d.ts.map +1 -0
  125. package/dist/schema/builder.js +49 -0
  126. package/dist/schema/builder.js.map +1 -0
  127. package/dist/schema/ddl.d.ts +7 -0
  128. package/dist/schema/ddl.d.ts.map +1 -0
  129. package/dist/schema/ddl.js +114 -0
  130. package/dist/schema/ddl.js.map +1 -0
  131. package/dist/schema/diff.d.ts +8 -0
  132. package/dist/schema/diff.d.ts.map +1 -0
  133. package/dist/schema/diff.js +224 -0
  134. package/dist/schema/diff.js.map +1 -0
  135. package/dist/schema/introspection.d.ts +8 -0
  136. package/dist/schema/introspection.d.ts.map +1 -0
  137. package/dist/schema/introspection.js +165 -0
  138. package/dist/schema/introspection.js.map +1 -0
  139. package/dist/schema/operations.d.ts +44 -0
  140. package/dist/schema/operations.d.ts.map +1 -0
  141. package/dist/schema/operations.js +2 -0
  142. package/dist/schema/operations.js.map +1 -0
  143. package/dist/schema/types.d.ts +76 -0
  144. package/dist/schema/types.d.ts.map +1 -0
  145. package/dist/schema/types.js +2 -0
  146. package/dist/schema/types.js.map +1 -0
  147. package/dist/scope.d.ts +5 -0
  148. package/dist/scope.d.ts.map +1 -0
  149. package/dist/scope.js +28 -0
  150. package/dist/scope.js.map +1 -0
  151. package/dist/seeding/runner.d.ts +14 -0
  152. package/dist/seeding/runner.d.ts.map +1 -0
  153. package/dist/seeding/runner.js +107 -0
  154. package/dist/seeding/runner.js.map +1 -0
  155. package/dist/seeding/types.d.ts +33 -0
  156. package/dist/seeding/types.d.ts.map +1 -0
  157. package/dist/seeding/types.js +4 -0
  158. package/dist/seeding/types.js.map +1 -0
  159. package/dist/sql/client.d.ts +16 -0
  160. package/dist/sql/client.d.ts.map +1 -0
  161. package/dist/sql/client.js +71 -0
  162. package/dist/sql/client.js.map +1 -0
  163. package/dist/sql/executable.d.ts +8 -0
  164. package/dist/sql/executable.d.ts.map +1 -0
  165. package/dist/sql/executable.js +11 -0
  166. package/dist/sql/executable.js.map +1 -0
  167. package/dist/sql/fragment.d.ts +37 -0
  168. package/dist/sql/fragment.d.ts.map +1 -0
  169. package/dist/sql/fragment.js +40 -0
  170. package/dist/sql/fragment.js.map +1 -0
  171. package/dist/sql/tag.d.ts +20 -0
  172. package/dist/sql/tag.d.ts.map +1 -0
  173. package/dist/sql/tag.js +123 -0
  174. package/dist/sql/tag.js.map +1 -0
  175. package/dist/tooling/generate.d.ts +9 -0
  176. package/dist/tooling/generate.d.ts.map +1 -0
  177. package/dist/tooling/generate.js +83 -0
  178. package/dist/tooling/generate.js.map +1 -0
  179. package/dist/tooling/index.d.ts +12 -0
  180. package/dist/tooling/index.d.ts.map +1 -0
  181. package/dist/tooling/index.js +389 -0
  182. package/dist/tooling/index.js.map +1 -0
  183. package/docs/advanced.md +290 -0
  184. package/docs/comparison.md +188 -0
  185. package/docs/installation.md +139 -0
  186. package/docs/introduction.md +126 -0
  187. package/docs/migrations.md +232 -0
  188. package/docs/models.md +241 -0
  189. package/docs/queries.md +261 -0
  190. package/docs/raw-queries.md +183 -0
  191. package/docs/relationships.md +243 -0
  192. package/docs/runtimes.md +422 -0
  193. package/docs/seeders.md +198 -0
  194. package/package.json +1 -1
@@ -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, libSQL, 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.
@@ -0,0 +1,243 @@
1
+ ---
2
+ title: Relationships
3
+ description: Define, persist, and explicitly load one-to-one, one-to-many, many-to-one, and many-to-many relations.
4
+ ---
5
+
6
+ # Relationships
7
+
8
+ Relations describe links between registered entities. They are explicit:
9
+ Cossack ORM does not lazy-load a property when it is accessed. Request the
10
+ relations needed by a query with `relations` or `with`.
11
+
12
+ ## One-to-many and many-to-one
13
+
14
+ A post owns the foreign key to its author:
15
+
16
+ ```ts
17
+ // User.ts
18
+ import {
19
+ BaseEntity,
20
+ Column,
21
+ Entity,
22
+ OneToMany,
23
+ PrimaryGeneratedColumn,
24
+ type Relation,
25
+ } from "@cossackframework/database";
26
+ import { Post } from "./Post.js";
27
+
28
+ @Entity()
29
+ export class User extends BaseEntity {
30
+ @PrimaryGeneratedColumn()
31
+ declare id: number;
32
+
33
+ @Column()
34
+ declare name: string;
35
+
36
+ @OneToMany(() => Post, (post) => post.author)
37
+ declare posts: Relation<Post[]>;
38
+ }
39
+ ```
40
+
41
+ ```ts
42
+ // Post.ts
43
+ import {
44
+ BaseEntity,
45
+ Column,
46
+ Entity,
47
+ JoinColumn,
48
+ ManyToOne,
49
+ PrimaryGeneratedColumn,
50
+ type Relation,
51
+ } from "@cossackframework/database";
52
+ import { User } from "./User.js";
53
+
54
+ @Entity()
55
+ export class Post extends BaseEntity {
56
+ @PrimaryGeneratedColumn()
57
+ declare id: number;
58
+
59
+ @Column()
60
+ declare title: string;
61
+
62
+ @Column({ name: "author_id", type: "integer" })
63
+ declare authorId: number;
64
+
65
+ @ManyToOne(() => User, (user) => user.posts, {
66
+ nullable: false,
67
+ onDelete: "CASCADE",
68
+ })
69
+ @JoinColumn({ name: "author_id", referencedColumnName: "id" })
70
+ declare author: Relation<User>;
71
+ }
72
+ ```
73
+
74
+ Keep the physical foreign-key column as a decorated property when application
75
+ code needs to query or assign it directly. Assigning the owning relation also
76
+ synchronizes that property before persistence:
77
+
78
+ ```ts
79
+ await orm.run(async () => {
80
+ const user = User.create({ name: "Ada Lovelace" });
81
+ await user.save();
82
+
83
+ const post = Post.create({ title: "Poetical Science" });
84
+ post.author = user;
85
+ await post.save();
86
+ });
87
+ ```
88
+
89
+ ## Loading relations
90
+
91
+ ```ts
92
+ const users = await User.find({
93
+ relations: ["posts"],
94
+ order: { name: "asc" },
95
+ });
96
+
97
+ const posts = await Post.find({
98
+ with: ["author"],
99
+ });
100
+ ```
101
+
102
+ `relations` and `with` are aliases. The loader collects relation keys and
103
+ fetches related rows in batches, chunked according to the adapter parameter
104
+ limit. This avoids issuing one query per parent row.
105
+
106
+ Relations are not recursive by default. Request only the relation properties
107
+ needed by the operation.
108
+
109
+ ## One-to-one
110
+
111
+ Place `@JoinColumn()` on the owning side:
112
+
113
+ ```ts
114
+ @Entity()
115
+ class UserProfile extends BaseEntity {
116
+ @PrimaryGeneratedColumn()
117
+ declare id: number;
118
+
119
+ @Column("text")
120
+ declare biography: string;
121
+
122
+ @OneToOne(() => User, (user) => user.profile, {
123
+ nullable: false,
124
+ onDelete: "CASCADE",
125
+ })
126
+ @JoinColumn({ name: "user_id", referencedColumnName: "id" })
127
+ declare user: Relation<User>;
128
+ }
129
+
130
+ @Entity()
131
+ class User extends BaseEntity {
132
+ @PrimaryGeneratedColumn()
133
+ declare id: number;
134
+
135
+ @OneToOne(() => UserProfile, (profile) => profile.user)
136
+ declare profile: Relation<UserProfile>;
137
+ }
138
+ ```
139
+
140
+ ## Many-to-many
141
+
142
+ Put `@JoinTable()` on exactly one side:
143
+
144
+ ```ts
145
+ @Entity()
146
+ class User extends BaseEntity {
147
+ @PrimaryGeneratedColumn()
148
+ declare id: number;
149
+
150
+ @ManyToMany(() => Role, (role) => role.users, {
151
+ cascade: ["insert", "update"],
152
+ })
153
+ @JoinTable({
154
+ name: "user_roles",
155
+ joinColumn: {
156
+ name: "user_id",
157
+ referencedColumnName: "id",
158
+ },
159
+ inverseJoinColumn: {
160
+ name: "role_id",
161
+ referencedColumnName: "id",
162
+ },
163
+ })
164
+ declare roles: Relation<Role[]>;
165
+ }
166
+
167
+ @Entity()
168
+ class Role extends BaseEntity {
169
+ @PrimaryGeneratedColumn()
170
+ declare id: number;
171
+
172
+ @Column({ unique: true })
173
+ declare name: string;
174
+
175
+ @ManyToMany(() => User, (user) => user.roles)
176
+ declare users: Relation<User[]>;
177
+ }
178
+ ```
179
+
180
+ Join-table synchronization occurs on the owning side when the relation opts into
181
+ the relevant insert/update cascade.
182
+
183
+ ## Cascades
184
+
185
+ Cascades are disabled by default:
186
+
187
+ ```ts
188
+ @OneToMany(() => Post, (post) => post.author, {
189
+ cascade: ["insert", "update"],
190
+ })
191
+ declare posts: Relation<Post[]>;
192
+ ```
193
+
194
+ `cascade: true` enables both insert and update cascades. Prefer the explicit
195
+ array in reusable packages so the persistence behavior is visible.
196
+
197
+ Delete cascades are database behavior configured with `onDelete`. Cossack ORM
198
+ does not walk an in-memory object graph and delete related entities.
199
+
200
+ ## Nullable and logical relations
201
+
202
+ Use `nullable` to describe whether an owning relation may be absent:
203
+
204
+ ```ts
205
+ @ManyToOne(() => Team, (team) => team.members, {
206
+ nullable: true,
207
+ })
208
+ @JoinColumn({ name: "team_id" })
209
+ declare team: Relation<Team | null>;
210
+ ```
211
+
212
+ Set `createForeignKeyConstraints: false` for a logical relation that should
213
+ appear in ORM metadata without creating a database foreign-key constraint:
214
+
215
+ ```ts
216
+ @ManyToOne(() => ExternalAccount, {
217
+ createForeignKeyConstraints: false,
218
+ })
219
+ @JoinColumn({ name: "external_account_id" })
220
+ declare externalAccount: Relation<ExternalAccount>;
221
+ ```
222
+
223
+ Logical and physical relation provenance is included in `orm.schema()` for
224
+ Studio and other tooling.
225
+
226
+ ## Registration and circular imports
227
+
228
+ Relation targets are callbacks so circular model references resolve after class
229
+ evaluation:
230
+
231
+ ```ts
232
+ @ManyToOne(() => User, (user) => user.posts)
233
+ declare author: Relation<User>;
234
+ ```
235
+
236
+ Still register every target:
237
+
238
+ ```ts
239
+ export const entities = [User, Post, Role, UserProfile] as const;
240
+ ```
241
+
242
+ ORM creation validates missing targets, invalid inverse properties, and
243
+ unresolved join metadata.