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