metal-orm 1.0.43 β 1.0.45
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 +700 -557
- package/dist/index.cjs +896 -476
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1146 -275
- package/dist/index.d.ts +1146 -275
- package/dist/index.js +896 -474
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/core/ast/adapters.ts +8 -2
- package/src/core/ast/builders.ts +105 -81
- package/src/core/ast/expression-builders.ts +430 -390
- package/src/core/ast/expression-visitor.ts +47 -8
- package/src/core/ast/helpers.ts +23 -0
- package/src/core/ast/join-node.ts +17 -1
- package/src/core/ddl/dialects/base-schema-dialect.ts +7 -1
- package/src/core/ddl/dialects/index.ts +1 -0
- package/src/core/ddl/dialects/mssql-schema-dialect.ts +1 -0
- package/src/core/ddl/dialects/mysql-schema-dialect.ts +1 -0
- package/src/core/ddl/dialects/postgres-schema-dialect.ts +1 -0
- package/src/core/ddl/dialects/sqlite-schema-dialect.ts +1 -0
- package/src/core/ddl/introspect/catalogs/index.ts +1 -0
- package/src/core/ddl/introspect/catalogs/postgres.ts +2 -0
- package/src/core/ddl/introspect/context.ts +6 -0
- package/src/core/ddl/introspect/functions/postgres.ts +13 -0
- package/src/core/ddl/introspect/mssql.ts +11 -0
- package/src/core/ddl/introspect/mysql.ts +2 -0
- package/src/core/ddl/introspect/postgres.ts +14 -0
- package/src/core/ddl/introspect/registry.ts +14 -0
- package/src/core/ddl/introspect/run-select.ts +13 -0
- package/src/core/ddl/introspect/sqlite.ts +22 -0
- package/src/core/ddl/introspect/utils.ts +18 -0
- package/src/core/ddl/naming-strategy.ts +6 -0
- package/src/core/ddl/schema-dialect.ts +19 -6
- package/src/core/ddl/schema-diff.ts +22 -0
- package/src/core/ddl/schema-generator.ts +22 -0
- package/src/core/ddl/schema-plan-executor.ts +6 -0
- package/src/core/ddl/schema-types.ts +6 -0
- package/src/core/dialect/abstract.ts +2 -2
- package/src/core/execution/pooling/pool.ts +12 -7
- package/src/core/functions/datetime.ts +57 -33
- package/src/core/functions/numeric.ts +95 -30
- package/src/core/functions/standard-strategy.ts +35 -0
- package/src/core/functions/text.ts +83 -22
- package/src/core/functions/types.ts +23 -8
- package/src/decorators/bootstrap.ts +16 -4
- package/src/decorators/column.ts +17 -0
- package/src/decorators/decorator-metadata.ts +27 -0
- package/src/decorators/entity.ts +8 -0
- package/src/decorators/index.ts +3 -0
- package/src/decorators/relations.ts +32 -0
- package/src/orm/als.ts +34 -9
- package/src/orm/entity-context.ts +54 -0
- package/src/orm/entity-metadata.ts +122 -9
- package/src/orm/execute.ts +15 -0
- package/src/orm/lazy-batch.ts +158 -98
- package/src/orm/relations/has-many.ts +44 -0
- package/src/orm/save-graph.ts +45 -0
- package/src/query/index.ts +74 -0
- package/src/query/target.ts +46 -0
- package/src/query-builder/delete-query-state.ts +30 -0
- package/src/query-builder/delete.ts +64 -19
- package/src/query-builder/hydration-manager.ts +46 -0
- package/src/query-builder/insert-query-state.ts +30 -0
- package/src/query-builder/insert.ts +46 -2
- package/src/query-builder/query-ast-service.ts +5 -0
- package/src/query-builder/query-resolution.ts +78 -0
- package/src/query-builder/raw-column-parser.ts +5 -0
- package/src/query-builder/relation-alias.ts +7 -0
- package/src/query-builder/relation-conditions.ts +61 -48
- package/src/query-builder/relation-service.ts +68 -63
- package/src/query-builder/relation-utils.ts +3 -0
- package/src/query-builder/select/cte-facet.ts +40 -0
- package/src/query-builder/select/from-facet.ts +80 -0
- package/src/query-builder/select/join-facet.ts +62 -0
- package/src/query-builder/select/predicate-facet.ts +103 -0
- package/src/query-builder/select/projection-facet.ts +69 -0
- package/src/query-builder/select/relation-facet.ts +81 -0
- package/src/query-builder/select/setop-facet.ts +36 -0
- package/src/query-builder/select-helpers.ts +13 -0
- package/src/query-builder/select-query-builder-deps.ts +19 -1
- package/src/query-builder/select-query-state.ts +2 -1
- package/src/query-builder/select.ts +795 -1163
- package/src/query-builder/update-query-state.ts +52 -0
- package/src/query-builder/update.ts +69 -19
- package/src/schema/table-guards.ts +31 -0
package/README.md
CHANGED
|
@@ -1,557 +1,700 @@
|
|
|
1
|
-
# MetalORM βοΈ
|
|
2
|
-
|
|
3
|
-
[](https://www.npmjs.com/package/metal-orm)
|
|
4
|
-
[](https://github.com/celsowm/metal-orm/blob/main/LICENSE)
|
|
5
|
-
[](https://www.typescriptlang.org/)
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
- **
|
|
12
|
-
|
|
13
|
-
- **
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
---
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
-
|
|
64
|
-
-
|
|
65
|
-
-
|
|
66
|
-
|
|
67
|
-
-
|
|
68
|
-
-
|
|
69
|
-
-
|
|
70
|
-
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
-
|
|
86
|
-
-
|
|
87
|
-
-
|
|
88
|
-
-
|
|
89
|
-
-
|
|
90
|
-
-
|
|
91
|
-
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
-
|
|
106
|
-
-
|
|
107
|
-
-
|
|
108
|
-
-
|
|
109
|
-
-
|
|
110
|
-
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
**
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
const
|
|
278
|
-
id
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
.
|
|
316
|
-
.
|
|
317
|
-
.
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
)
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
//
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
//
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
//
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
//
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
.
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
1
|
+
# MetalORM βοΈ
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/metal-orm)
|
|
4
|
+
[](https://github.com/celsowm/metal-orm/blob/main/LICENSE)
|
|
5
|
+
[](https://www.typescriptlang.org/)
|
|
6
|
+
|
|
7
|
+
> **TypeScript-first ORM that adapts to your needs**: use it as a type-safe query builder, a full-featured ORM runtime, or anything in between.
|
|
8
|
+
|
|
9
|
+
## Why MetalORM? π‘
|
|
10
|
+
|
|
11
|
+
- π― **Gradual adoption**: Start with just SQL building, add ORM features when you need them
|
|
12
|
+
- π **Exceptionally strongly typed**: Built with TypeScript generics and type inferenceβ**zero** `any` types in the entire codebase
|
|
13
|
+
- ποΈ **Well-architected**: Implements proven design patterns (Strategy, Visitor, Builder, Unit of Work, Identity Map, Interceptor, and more)
|
|
14
|
+
- π¨ **One AST, multiple levels**: All features share the same SQL AST foundationβno magic, just composable layers
|
|
15
|
+
- π **Multi-dialect from the start**: MySQL, PostgreSQL, SQLite, SQL Server support built-in
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## β‘ 30-Second Quick Start
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { defineTable, col, selectFrom, MySqlDialect } from 'metal-orm';
|
|
23
|
+
|
|
24
|
+
const users = defineTable('users', {
|
|
25
|
+
id: col.primaryKey(col.int()),
|
|
26
|
+
name: col.varchar(255),
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
const query = selectFrom(users).select('id', 'name').limit(10);
|
|
30
|
+
const { sql, params } = query.compile(new MySqlDialect());
|
|
31
|
+
// That's it! Use sql + params with any driver.
|
|
32
|
+
// β Fully typedβno casting, no 'any', just strong types all the way down
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## Three Levels of Abstraction
|
|
38
|
+
|
|
39
|
+
MetalORM is a TypeScript-first, AST-driven SQL toolkit you can dial up or down depending on how "ORM-y" you want to be:
|
|
40
|
+
|
|
41
|
+
- **Level 1 β Query builder & hydration π§©**
|
|
42
|
+
Define tables with `defineTable` / `col.*`, build strongly-typed queries on a real SQL AST, and hydrate flat result sets into nested objects β no ORM runtime involved.
|
|
43
|
+
|
|
44
|
+
- **Level 2 β ORM runtime (entities + Unit of Work π§ )**
|
|
45
|
+
Let `OrmSession` (created from `Orm`) turn rows into tracked entities with lazy relations, cascades, and a [Unit of Work](https://en.wikipedia.org/wiki/Unit_of_work) that flushes changes with `session.commit()`.
|
|
46
|
+
|
|
47
|
+
- **Level 3 β Decorator entities (classes + metadata β¨)**
|
|
48
|
+
Use `@Entity`, `@Column`, `@PrimaryKey`, relation decorators, `bootstrapEntities()` (or the lazy bootstrapping in `getTableDefFromEntity` / `selectFromEntity`) to describe your model classes. MetalORM bootstraps schema & relations from metadata and plugs them into the same runtime and query builder.
|
|
49
|
+
|
|
50
|
+
**Use only the layer you need in each part of your codebase.**
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
<a id="table-of-contents"></a>
|
|
55
|
+
## Table of Contents π§
|
|
56
|
+
|
|
57
|
+
- [Documentation](#documentation)
|
|
58
|
+
- [Features](#features)
|
|
59
|
+
- [Installation](#installation)
|
|
60
|
+
- [Quick start - three levels](#quick-start)
|
|
61
|
+
- [Level 1 β Query builder & hydration](#level-1)
|
|
62
|
+
- [Level 2 β Entities + Unit of Work](#level-2)
|
|
63
|
+
- [Level 3 β Decorator entities](#level-3)
|
|
64
|
+
- [When to use which level?](#when-to-use-which-level)
|
|
65
|
+
- [Design & Architecture](#design-notes)
|
|
66
|
+
- [FAQ](#frequently-asked-questions-)
|
|
67
|
+
- [Performance & Production](#performance--production-)
|
|
68
|
+
- [Community & Support](#community--support-)
|
|
69
|
+
- [Contributing](#contributing)
|
|
70
|
+
- [License](#license)
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
74
|
+
<a id="documentation"></a>
|
|
75
|
+
## Documentation π
|
|
76
|
+
|
|
77
|
+
Full docs live in the `docs/` folder:
|
|
78
|
+
|
|
79
|
+
- [Introduction](https://github.com/celsowm/metal-orm/blob/main/docs/index.md)
|
|
80
|
+
- [Getting Started](https://github.com/celsowm/metal-orm/blob/main/docs/getting-started.md)
|
|
81
|
+
- [Level 3 Backend Tutorial](https://github.com/celsowm/metal-orm/blob/main/docs/level-3-backend-tutorial.md)
|
|
82
|
+
- [Schema Definition](https://github.com/celsowm/metal-orm/blob/main/docs/schema-definition.md)
|
|
83
|
+
- [Query Builder](https://github.com/celsowm/metal-orm/blob/main/docs/query-builder.md)
|
|
84
|
+
- [DML Operations](https://github.com/celsowm/metal-orm/blob/main/docs/dml-operations.md)
|
|
85
|
+
- [Hydration & Entities](https://github.com/celsowm/metal-orm/blob/main/docs/hydration.md)
|
|
86
|
+
- [Runtime & Unit of Work](https://github.com/celsowm/metal-orm/blob/main/docs/runtime.md)
|
|
87
|
+
- [Advanced Features](https://github.com/celsowm/metal-orm/blob/main/docs/advanced-features.md)
|
|
88
|
+
- [Multi-Dialect Support](https://github.com/celsowm/metal-orm/blob/main/docs/multi-dialect-support.md)
|
|
89
|
+
- [Schema Generation (DDL)](https://github.com/celsowm/metal-orm/blob/main/docs/schema-generation.md)
|
|
90
|
+
- [API Reference](https://github.com/celsowm/metal-orm/blob/main/docs/api-reference.md)
|
|
91
|
+
- [DB β TS Type Mapping](https://github.com/celsowm/metal-orm/blob/main/docs/db-to-ts-types.md)
|
|
92
|
+
|
|
93
|
+
---
|
|
94
|
+
|
|
95
|
+
<a id="features"></a>
|
|
96
|
+
## Features π
|
|
97
|
+
|
|
98
|
+
### Level 1 β Query builder & hydration
|
|
99
|
+
|
|
100
|
+
- **Declarative schema definition** with `defineTable`, `col.*`, and typed relations.
|
|
101
|
+
- **Typed temporal columns**: `col.date()` / `col.datetime()` / `col.timestamp()` default to `string` but accept a generic when your driver returns `Date` (e.g. `col.date<Date>()`).
|
|
102
|
+
- **Fluent query builder** over a real SQL AST
|
|
103
|
+
(`SelectQueryBuilder`, `InsertQueryBuilder`, `UpdateQueryBuilder`, `DeleteQueryBuilder`).
|
|
104
|
+
- **Advanced SQL**: CTEs, aggregates, window functions, subqueries, JSON, CASE, EXISTS.
|
|
105
|
+
- **String helpers**: `lower`, `upper`, `trim`, `ltrim/rtrim`, `concat/concatWs`, `substr/left/right`, `position/instr/locate`, `replace`, `repeat`, `lpad/rpad`, `space`, and more with dialect-aware rendering.
|
|
106
|
+
- **Set operations**: `union`, `unionAll`, `intersect`, `except` across all dialects (ORDER/LIMIT apply to the combined result; hydration is disabled for compound queries so rows are returned as-is without collapsing duplicates).
|
|
107
|
+
- **Expression builders**: `eq`, `and`, `or`, `between`, `inList`, `exists`, `jsonPath`, `caseWhen`, window functions like `rowNumber`, `rank`, `lag`, `lead`, etc., all backed by typed AST nodes.
|
|
108
|
+
- **Relation-aware hydration**: turn flat rows into nested objects (`user.posts`, `user.roles`, etc.) using a hydration plan derived from the AST metadata.
|
|
109
|
+
- **Multi-dialect**: compile once, run on MySQL/MariaDB, PostgreSQL, SQLite, or SQL Server via pluggable dialects.
|
|
110
|
+
- **DML**: type-safe INSERT / UPDATE / DELETE with `RETURNING` where supported.
|
|
111
|
+
|
|
112
|
+
Level 1 is ideal when you:
|
|
113
|
+
|
|
114
|
+
- Already have a domain model and just want a serious SQL builder.
|
|
115
|
+
- Want deterministic SQL (no magical query generation).
|
|
116
|
+
- Need to share the same AST across tooling (e.g. codegen, diagnostics, logging).
|
|
117
|
+
|
|
118
|
+
### Level 2 β ORM runtime (`OrmSession`)
|
|
119
|
+
|
|
120
|
+
On top of the query builder, MetalORM ships a focused runtime managed by `Orm` and its request-scoped `OrmSession`s:
|
|
121
|
+
|
|
122
|
+
- **Entities inferred from your `TableDef`s** (no separate mapping file).
|
|
123
|
+
- **Lazy, batched relations**: `user.posts.load()`, `user.roles.syncByIds([...])`, etc.
|
|
124
|
+
- **Scoped transactions**: `session.transaction(async s => { ... })` wraps `begin/commit/rollback` on the existing executor; `Orm.transaction` remains available when you want a fresh transactional executor per call.
|
|
125
|
+
- **Identity map**: the same row becomes the same entity instance within a session (see the [Identity map pattern](https://en.wikipedia.org/wiki/Identity_map_pattern)).
|
|
126
|
+
- **Unit of Work (`OrmSession`)** tracking New/Dirty/Removed entities and relation changes, inspired by the classic [Unit of Work pattern](https://en.wikipedia.org/wiki/Unit_of_work).
|
|
127
|
+
- **Graph persistence**: mutate a whole object graph and flush once with `session.commit()`.
|
|
128
|
+
- **Relation change processor** that knows how to deal with has-many and many-to-many pivot tables.
|
|
129
|
+
- **Interceptors**: `beforeFlush` / `afterFlush` hooks for cross-cutting concerns (auditing, multi-tenant filters, soft delete filters, etc.).
|
|
130
|
+
- **Domain events**: `addDomainEvent` and a DomainEventBus integrated into `session.commit()`, aligned with domain events from [Domain-driven design](https://en.wikipedia.org/wiki/Domain-driven_design).
|
|
131
|
+
- **JSON-safe entities**: relation wrappers hide internal references and implement `toJSON`, so `JSON.stringify` of hydrated entities works without circular reference errors.
|
|
132
|
+
|
|
133
|
+
Use this layer where:
|
|
134
|
+
|
|
135
|
+
- A request-scoped context fits (web/API handlers, jobs).
|
|
136
|
+
- You want change tracking, cascades, and relation helpers instead of manual SQL for every update.
|
|
137
|
+
|
|
138
|
+
### Level 3 β Decorator entities
|
|
139
|
+
|
|
140
|
+
If you like explicit model classes, you can add a thin decorator layer on top of the same schema/runtime:
|
|
141
|
+
|
|
142
|
+
- `@Entity()` on a class to derive and register a table name (by default snake_case plural of the class name, with an optional `tableName` override).
|
|
143
|
+
- `@Column(...)` and `@PrimaryKey(...)` on properties; decorators collect column metadata and later build `TableDef`s from it.
|
|
144
|
+
- Relation decorators:
|
|
145
|
+
- `@HasMany({ target, foreignKey, ... })`
|
|
146
|
+
- `@HasOne({ target, foreignKey, ... })`
|
|
147
|
+
- `@BelongsTo({ target, foreignKey, ... })`
|
|
148
|
+
- `@BelongsToMany({ target, pivotTable, ... })`
|
|
149
|
+
- `bootstrapEntities()` scans metadata, builds `TableDef`s, wires relations with the same `hasOne` / `hasMany` / `belongsTo` / `belongsToMany` helpers you would use manually, and returns the resulting tables. (If you forget to call it, `getTableDefFromEntity` / `selectFromEntity` will bootstrap lazily on first use, but bootstrapping once at startup lets you reuse the same table defs and generate schema SQL.)
|
|
150
|
+
- `selectFromEntity(MyEntity)` lets you start a `SelectQueryBuilder` directly from the class.
|
|
151
|
+
- **Generate entities from an existing DB**: `npx metal-orm-gen -- --dialect=postgres --url=$DATABASE_URL --schema=public --out=src/entities.ts` introspects your schema and spits out `@Entity` / `@Column` classes you can immediately `bootstrapEntities()` with.
|
|
152
|
+
|
|
153
|
+
You donβt have to use decorators, but when you do, youβre still on the same AST + dialect + runtime foundation.
|
|
154
|
+
|
|
155
|
+
---
|
|
156
|
+
|
|
157
|
+
<a id="installation"></a>
|
|
158
|
+
## Installation π¦
|
|
159
|
+
|
|
160
|
+
**Requirements:** Node.js β₯ 20.0.0. For TypeScript projects, use TS 5.6+ to get the standard decorators API and typings.
|
|
161
|
+
|
|
162
|
+
```bash
|
|
163
|
+
# npm
|
|
164
|
+
npm install metal-orm
|
|
165
|
+
|
|
166
|
+
# yarn
|
|
167
|
+
yarn add metal-orm
|
|
168
|
+
|
|
169
|
+
# pnpm
|
|
170
|
+
pnpm add metal-orm
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
MetalORM compiles SQL; you bring your own driver:
|
|
174
|
+
|
|
175
|
+
| Dialect | Driver | Install |
|
|
176
|
+
| ------------------ | --------- | ---------------------- |
|
|
177
|
+
| MySQL / MariaDB | `mysql2` | `npm install mysql2` |
|
|
178
|
+
| SQLite | `sqlite3` | `npm install sqlite3` |
|
|
179
|
+
| PostgreSQL | `pg` | `npm install pg` |
|
|
180
|
+
| SQL Server | `tedious` | `npm install tedious` |
|
|
181
|
+
|
|
182
|
+
Pick the matching dialect (`MySqlDialect`, `SQLiteDialect`, `PostgresDialect`, `MSSQLDialect`) when compiling queries.
|
|
183
|
+
|
|
184
|
+
> Drivers are declared as optional peer dependencies. Install only the ones you actually use in your project.
|
|
185
|
+
|
|
186
|
+
### Playground (optional) π§ͺ
|
|
187
|
+
|
|
188
|
+
The React playground lives in `playground/` and is no longer part of the published package or its dependency tree. To run it locally:
|
|
189
|
+
|
|
190
|
+
1. `cd playground && npm install`
|
|
191
|
+
2. `npm run dev` (uses the root `vite.config.ts`)
|
|
192
|
+
|
|
193
|
+
It boots against an in-memory SQLite database seeded from fixtures under `playground/shared/`.
|
|
194
|
+
|
|
195
|
+
---
|
|
196
|
+
|
|
197
|
+
<a id="quick-start"></a>
|
|
198
|
+
## Quick start β three levels
|
|
199
|
+
|
|
200
|
+
<a id="level-1"></a>
|
|
201
|
+
### Level 1: Query builder & hydration π§©
|
|
202
|
+
|
|
203
|
+
#### 1. Tiny table, tiny query
|
|
204
|
+
|
|
205
|
+
MetalORM can be just a straightforward query builder.
|
|
206
|
+
|
|
207
|
+
```ts
|
|
208
|
+
import mysql from 'mysql2/promise';
|
|
209
|
+
import {
|
|
210
|
+
defineTable,
|
|
211
|
+
tableRef,
|
|
212
|
+
col,
|
|
213
|
+
selectFrom,
|
|
214
|
+
eq,
|
|
215
|
+
MySqlDialect,
|
|
216
|
+
} from 'metal-orm';
|
|
217
|
+
|
|
218
|
+
// 1) A very small table
|
|
219
|
+
const todos = defineTable('todos', {
|
|
220
|
+
id: col.primaryKey(col.int()),
|
|
221
|
+
title: col.varchar(255),
|
|
222
|
+
done: col.boolean(),
|
|
223
|
+
});
|
|
224
|
+
// Add constraints
|
|
225
|
+
todos.columns.title.notNull = true;
|
|
226
|
+
todos.columns.done.default = false;
|
|
227
|
+
|
|
228
|
+
// Optional: opt-in ergonomic column access
|
|
229
|
+
const t = tableRef(todos);
|
|
230
|
+
|
|
231
|
+
// 2) Build a simple query
|
|
232
|
+
const listOpenTodos = selectFrom(todos)
|
|
233
|
+
.select('id', 'title', 'done')
|
|
234
|
+
.where(eq(t.done, false))
|
|
235
|
+
.orderBy(t.id, 'ASC');
|
|
236
|
+
|
|
237
|
+
// 3) Compile to SQL + params
|
|
238
|
+
const dialect = new MySqlDialect();
|
|
239
|
+
const { sql, params } = listOpenTodos.compile(dialect);
|
|
240
|
+
|
|
241
|
+
// 4) Run with your favorite driver
|
|
242
|
+
const connection = await mysql.createConnection({ /* ... */ });
|
|
243
|
+
const [rows] = await connection.execute(sql, params);
|
|
244
|
+
|
|
245
|
+
console.log(rows);
|
|
246
|
+
// [
|
|
247
|
+
// { id: 1, title: 'Write docs', done: 0 },
|
|
248
|
+
// { id: 2, title: 'Ship feature', done: 0 },
|
|
249
|
+
// ]
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
Thatβs it: schema, query, SQL, done.
|
|
253
|
+
|
|
254
|
+
#### Column pickers (preferred selection helpers)
|
|
255
|
+
|
|
256
|
+
`defineTable` still exposes the full `table.columns` map for schema metadata and constraint tweaks, but modern queries usually benefit from higher-level helpers instead of spelling `todo.columns.*` everywhere.
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
const t = tableRef(todos);
|
|
260
|
+
|
|
261
|
+
const listOpenTodos = selectFrom(todos)
|
|
262
|
+
.select('id', 'title', 'done') // typed shorthand for the same fields
|
|
263
|
+
.where(eq(t.done, false))
|
|
264
|
+
.orderBy(t.id, 'ASC');
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
`select`, `selectRelationColumns`, `includePick`, `selectColumnsDeep`, the `sel()` helpers for tables, and `esel()` for entities all build typed selection maps without repeating `table.columns.*`. Use those helpers when building query selections and reserve `table.columns.*` for schema definition, relations, or rare cases where you need a column reference outside of a picker. See the [Query Builder docs](./docs/query-builder.md#selection-helpers) for the reference, examples, and best practices for these helpers.
|
|
268
|
+
|
|
269
|
+
#### Ergonomic column access (opt-in) with `tableRef`
|
|
270
|
+
|
|
271
|
+
If you still want the convenience of accessing columns without spelling `.columns`, you can opt-in with `tableRef()`:
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
import { tableRef, eq, selectFrom } from 'metal-orm';
|
|
275
|
+
|
|
276
|
+
// Existing style (always works)
|
|
277
|
+
const listOpenTodos = selectFrom(todos)
|
|
278
|
+
.select('id', 'title', 'done')
|
|
279
|
+
.where(eq(todos.columns.done, false))
|
|
280
|
+
.orderBy(todos.columns.id, 'ASC');
|
|
281
|
+
|
|
282
|
+
// Opt-in ergonomic style
|
|
283
|
+
const t = tableRef(todos);
|
|
284
|
+
|
|
285
|
+
const listOpenTodos2 = selectFrom(todos)
|
|
286
|
+
.select('id', 'title', 'done')
|
|
287
|
+
.where(eq(t.done, false))
|
|
288
|
+
.orderBy(t.id, 'ASC');
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
Collision rule: real table fields win.
|
|
292
|
+
|
|
293
|
+
- `t.name` is the table name (string)
|
|
294
|
+
- `t.$.name` is the column definition for a colliding column name (escape hatch)
|
|
295
|
+
|
|
296
|
+
#### 2. Relations & hydration (still no ORM)
|
|
297
|
+
|
|
298
|
+
Now add relations and get nested objects, still without committing to a runtime.
|
|
299
|
+
|
|
300
|
+
```ts
|
|
301
|
+
import {
|
|
302
|
+
defineTable,
|
|
303
|
+
col,
|
|
304
|
+
hasMany,
|
|
305
|
+
selectFrom,
|
|
306
|
+
eq,
|
|
307
|
+
count,
|
|
308
|
+
rowNumber,
|
|
309
|
+
MySqlDialect,
|
|
310
|
+
sel,
|
|
311
|
+
hydrateRows,
|
|
312
|
+
} from 'metal-orm';
|
|
313
|
+
|
|
314
|
+
const posts = defineTable('posts', {
|
|
315
|
+
id: col.primaryKey(col.int()),
|
|
316
|
+
title: col.varchar(255),
|
|
317
|
+
userId: col.int(),
|
|
318
|
+
createdAt: col.timestamp(),
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
// Add constraints
|
|
322
|
+
posts.columns.title.notNull = true;
|
|
323
|
+
posts.columns.userId.notNull = true;
|
|
324
|
+
|
|
325
|
+
const users = defineTable('users', {
|
|
326
|
+
id: col.primaryKey(col.int()),
|
|
327
|
+
name: col.varchar(255),
|
|
328
|
+
email: col.varchar(255),
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
// Add relations and constraints
|
|
332
|
+
users.relations = {
|
|
333
|
+
posts: hasMany(posts, 'userId'),
|
|
334
|
+
};
|
|
335
|
+
users.columns.name.notNull = true;
|
|
336
|
+
users.columns.email.unique = true;
|
|
337
|
+
|
|
338
|
+
// Build a query with relation & window function
|
|
339
|
+
const u = sel(users, 'id', 'name', 'email');
|
|
340
|
+
const p = sel(posts, 'id', 'userId');
|
|
341
|
+
|
|
342
|
+
const builder = selectFrom(users)
|
|
343
|
+
.select({
|
|
344
|
+
...u,
|
|
345
|
+
postCount: count(p.id),
|
|
346
|
+
rank: rowNumber(), // window function helper
|
|
347
|
+
})
|
|
348
|
+
.leftJoin(posts, eq(p.userId, u.id))
|
|
349
|
+
.groupBy(u.id)
|
|
350
|
+
.groupBy(u.name)
|
|
351
|
+
.groupBy(u.email)
|
|
352
|
+
.orderBy(count(p.id), 'DESC')
|
|
353
|
+
.limit(10)
|
|
354
|
+
.includePick('posts', ['id', 'title', 'createdAt']); // eager relation for hydration
|
|
355
|
+
|
|
356
|
+
const dialect = new MySqlDialect();
|
|
357
|
+
const { sql, params } = builder.compile(dialect);
|
|
358
|
+
const [rows] = await connection.execute(sql, params);
|
|
359
|
+
|
|
360
|
+
// Turn flat rows into nested objects
|
|
361
|
+
const hydrated = hydrateRows(
|
|
362
|
+
rows as Record<string, unknown>[],
|
|
363
|
+
builder.getHydrationPlan(),
|
|
364
|
+
);
|
|
365
|
+
|
|
366
|
+
console.log(hydrated);
|
|
367
|
+
// [
|
|
368
|
+
// {
|
|
369
|
+
// id: 1,
|
|
370
|
+
// name: 'John Doe',
|
|
371
|
+
// email: 'john@example.com',
|
|
372
|
+
// postCount: 15,
|
|
373
|
+
// rank: 1,
|
|
374
|
+
// posts: [
|
|
375
|
+
// { id: 101, title: 'Latest Post', createdAt: '2023-05-15T10:00:00Z' },
|
|
376
|
+
// // ...
|
|
377
|
+
// ],
|
|
378
|
+
// },
|
|
379
|
+
// // ...
|
|
380
|
+
// ]
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
Use this mode anywhere you want powerful SQL + nice nested results, without changing how you manage your models.
|
|
384
|
+
|
|
385
|
+
<a id="level-2"></a>
|
|
386
|
+
### Level 2: Entities + Unit of Work (ORM runtime) π§
|
|
387
|
+
|
|
388
|
+
When you're ready, you can let MetalORM manage entities and relations for you.
|
|
389
|
+
|
|
390
|
+
Instead of βnaked objectsβ, your queries can return entities attached to an `OrmSession`:
|
|
391
|
+
|
|
392
|
+
```ts
|
|
393
|
+
import mysql from 'mysql2/promise';
|
|
394
|
+
import {
|
|
395
|
+
Orm,
|
|
396
|
+
OrmSession,
|
|
397
|
+
MySqlDialect,
|
|
398
|
+
selectFrom,
|
|
399
|
+
eq,
|
|
400
|
+
tableRef,
|
|
401
|
+
createMysqlExecutor,
|
|
402
|
+
} from 'metal-orm';
|
|
403
|
+
|
|
404
|
+
// 1) Create an Orm + session for this request
|
|
405
|
+
|
|
406
|
+
const connection = await mysql.createConnection({ /* ... */ });
|
|
407
|
+
const executor = createMysqlExecutor(connection);
|
|
408
|
+
const orm = new Orm({
|
|
409
|
+
dialect: new MySqlDialect(),
|
|
410
|
+
executorFactory: {
|
|
411
|
+
createExecutor: () => executor,
|
|
412
|
+
createTransactionalExecutor: () => executor,
|
|
413
|
+
dispose: async () => {},
|
|
414
|
+
},
|
|
415
|
+
});
|
|
416
|
+
const session = new OrmSession({ orm, executor });
|
|
417
|
+
|
|
418
|
+
const u = tableRef(users);
|
|
419
|
+
|
|
420
|
+
// 2) Load entities with lazy relations
|
|
421
|
+
const [user] = await selectFrom(users)
|
|
422
|
+
.select('id', 'name', 'email')
|
|
423
|
+
.includeLazy('posts') // HasMany as a lazy collection
|
|
424
|
+
.includeLazy('roles') // BelongsToMany as a lazy collection
|
|
425
|
+
.where(eq(u.id, 1))
|
|
426
|
+
.execute(session);
|
|
427
|
+
|
|
428
|
+
// user is an EntityInstance<typeof users>
|
|
429
|
+
// scalar props are normal:
|
|
430
|
+
user.name = 'Updated Name'; // marks entity as Dirty
|
|
431
|
+
|
|
432
|
+
// relations are live collections:
|
|
433
|
+
const postsCollection = await user.posts.load(); // batched lazy load
|
|
434
|
+
const newPost = user.posts.add({ title: 'Hello from ORM mode' });
|
|
435
|
+
|
|
436
|
+
// Many-to-many via pivot:
|
|
437
|
+
await user.roles.syncByIds([1, 2, 3]);
|
|
438
|
+
|
|
439
|
+
// 3) Persist the entire graph
|
|
440
|
+
await session.commit();
|
|
441
|
+
// INSERT/UPDATE/DELETE + pivot updates happen in a single Unit of Work.
|
|
442
|
+
```
|
|
443
|
+
|
|
444
|
+
What the runtime gives you:
|
|
445
|
+
|
|
446
|
+
- [Identity map](https://en.wikipedia.org/wiki/Identity_map_pattern) (per context).
|
|
447
|
+
- [Unit of Work](https://en.wikipedia.org/wiki/Unit_of_work) style change tracking on scalar properties.
|
|
448
|
+
- Relation tracking (add/remove/sync on collections).
|
|
449
|
+
- Cascades on relations: `'all' | 'persist' | 'remove' | 'link'`.
|
|
450
|
+
- Single flush: `session.commit()` figures out inserts, updates, deletes, and pivot changes.
|
|
451
|
+
- Column pickers to stay DRY: `select` on the root table, `selectRelationColumns` / `includePick` on relations, and `selectColumnsDeep` or the `sel`/`esel` helpers to build typed selection maps without repeating `table.columns.*`.
|
|
452
|
+
|
|
453
|
+
<a id="level-3"></a>
|
|
454
|
+
### Level 3: Decorator entities β¨
|
|
455
|
+
|
|
456
|
+
Finally, you can describe your models with decorators and still use the same runtime and query builder.
|
|
457
|
+
|
|
458
|
+
```ts
|
|
459
|
+
import mysql from 'mysql2/promise';
|
|
460
|
+
import {
|
|
461
|
+
Orm,
|
|
462
|
+
OrmSession,
|
|
463
|
+
MySqlDialect,
|
|
464
|
+
col,
|
|
465
|
+
createMysqlExecutor,
|
|
466
|
+
Entity,
|
|
467
|
+
Column,
|
|
468
|
+
PrimaryKey,
|
|
469
|
+
HasMany,
|
|
470
|
+
BelongsTo,
|
|
471
|
+
bootstrapEntities,
|
|
472
|
+
selectFromEntity,
|
|
473
|
+
entityRef,
|
|
474
|
+
eq,
|
|
475
|
+
} from 'metal-orm';
|
|
476
|
+
|
|
477
|
+
@Entity()
|
|
478
|
+
class User {
|
|
479
|
+
@PrimaryKey(col.int())
|
|
480
|
+
id!: number;
|
|
481
|
+
|
|
482
|
+
@Column(col.varchar(255))
|
|
483
|
+
name!: string;
|
|
484
|
+
|
|
485
|
+
@Column(col.varchar(255))
|
|
486
|
+
email?: string;
|
|
487
|
+
|
|
488
|
+
@HasMany({
|
|
489
|
+
target: () => Post,
|
|
490
|
+
foreignKey: 'userId',
|
|
491
|
+
})
|
|
492
|
+
posts!: any; // relation wrapper; type omitted for brevity
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
@Entity()
|
|
496
|
+
class Post {
|
|
497
|
+
@PrimaryKey(col.int())
|
|
498
|
+
id!: number;
|
|
499
|
+
|
|
500
|
+
@Column(col.varchar(255))
|
|
501
|
+
title!: string;
|
|
502
|
+
|
|
503
|
+
@Column(col.int())
|
|
504
|
+
userId!: number;
|
|
505
|
+
|
|
506
|
+
@BelongsTo({
|
|
507
|
+
target: () => User,
|
|
508
|
+
foreignKey: 'userId',
|
|
509
|
+
})
|
|
510
|
+
user!: any;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// 1) Bootstrap metadata once at startup (recommended so you reuse the same TableDefs)
|
|
514
|
+
const tables = bootstrapEntities(); // getTableDefFromEntity/selectFromEntity can bootstrap lazily if you forget
|
|
515
|
+
// tables: TableDef[] β compatible with the rest of MetalORM
|
|
516
|
+
|
|
517
|
+
// 2) Create an Orm + session
|
|
518
|
+
const connection = await mysql.createConnection({ /* ... */ });
|
|
519
|
+
const executor = createMysqlExecutor(connection);
|
|
520
|
+
const orm = new Orm({
|
|
521
|
+
dialect: new MySqlDialect(),
|
|
522
|
+
executorFactory: {
|
|
523
|
+
createExecutor: () => executor,
|
|
524
|
+
createTransactionalExecutor: () => executor,
|
|
525
|
+
dispose: async () => {},
|
|
526
|
+
},
|
|
527
|
+
});
|
|
528
|
+
const session = new OrmSession({ orm, executor });
|
|
529
|
+
|
|
530
|
+
// 3) Query starting from the entity class
|
|
531
|
+
const U = entityRef(User);
|
|
532
|
+
const [user] = await selectFromEntity(User)
|
|
533
|
+
.select('id', 'name')
|
|
534
|
+
.includeLazy('posts')
|
|
535
|
+
.where(eq(U.id, 1))
|
|
536
|
+
.execute(session);
|
|
537
|
+
|
|
538
|
+
user.posts.add({ title: 'From decorators' });
|
|
539
|
+
await session.commit();
|
|
540
|
+
```
|
|
541
|
+
|
|
542
|
+
Tip: to keep selections terse, use `select`/`selectRelationColumns` or the `sel`/`esel` helpers instead of spelling `table.columns.*` over and over.
|
|
543
|
+
|
|
544
|
+
This level is nice when:
|
|
545
|
+
|
|
546
|
+
- You want classes as your domain model, but don't want a separate schema DSL.
|
|
547
|
+
- You like decorators for explicit mapping but still want AST-first SQL and a disciplined runtime.
|
|
548
|
+
|
|
549
|
+
---
|
|
550
|
+
|
|
551
|
+
<a id="when-to-use-which-level"></a>
|
|
552
|
+
## When to use which level? π€
|
|
553
|
+
|
|
554
|
+
- **Query builder + hydration (Level 1)**
|
|
555
|
+
Great for reporting/analytics, existing codebases with their own models, and services that need strong SQL but minimal runtime magic.
|
|
556
|
+
|
|
557
|
+
- **ORM runtime (Level 2)**
|
|
558
|
+
Great for request-scoped application logic and domain modeling where lazy relations, cascades, and graph persistence pay off.
|
|
559
|
+
|
|
560
|
+
- **Decorator entities (Level 3)**
|
|
561
|
+
Great when you want class-based entities and decorators, but still want to keep the underlying architecture explicit and layered.
|
|
562
|
+
|
|
563
|
+
All three levels share the same schema, AST, and dialects, so you can mix them as needed and migrate gradually.
|
|
564
|
+
|
|
565
|
+
---
|
|
566
|
+
|
|
567
|
+
<a id="design-notes"></a>
|
|
568
|
+
## Design & Architecture ποΈ
|
|
569
|
+
|
|
570
|
+
MetalORM is built on solid software engineering principles and proven design patterns.
|
|
571
|
+
|
|
572
|
+
### Architecture Layers
|
|
573
|
+
|
|
574
|
+
```
|
|
575
|
+
βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
576
|
+
β Your Application β
|
|
577
|
+
βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
578
|
+
β
|
|
579
|
+
ββββββββββββββββββββΌβββββββββββββββββββ
|
|
580
|
+
β β β
|
|
581
|
+
βΌ βΌ βΌ
|
|
582
|
+
βββββββββββ ββββββββββββ ββββββββββββ
|
|
583
|
+
β Level 1 β β Level 2 β β Level 3 β
|
|
584
|
+
β Query ββββββββ€ ORM ββββββββ€Decoratorsβ
|
|
585
|
+
β Builder β β Runtime β β β
|
|
586
|
+
βββββββββββ ββββββββββββ ββββββββββββ
|
|
587
|
+
β β β
|
|
588
|
+
ββββββββββββββββββββΌβββββββββββββββββββ
|
|
589
|
+
βΌ
|
|
590
|
+
ββββββββββββββββββ
|
|
591
|
+
β SQL AST β
|
|
592
|
+
β (Typed Nodes) β
|
|
593
|
+
ββββββββββββββββββ
|
|
594
|
+
βΌ
|
|
595
|
+
ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
596
|
+
β Strategy Pattern: Dialects β
|
|
597
|
+
β MySQL | PostgreSQL | SQLite | SQL Server β
|
|
598
|
+
ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
599
|
+
βΌ
|
|
600
|
+
ββββββββββββββββββ
|
|
601
|
+
β Database β
|
|
602
|
+
ββββββββββββββββββ
|
|
603
|
+
```
|
|
604
|
+
|
|
605
|
+
### Design Patterns
|
|
606
|
+
|
|
607
|
+
- **Strategy Pattern**: Pluggable dialects (MySQL, PostgreSQL, SQLite, SQL Server) and function renderers allow the same query to target different databases
|
|
608
|
+
- **Visitor Pattern**: AST traversal for SQL compilation and expression processing
|
|
609
|
+
- **Builder Pattern**: Fluent query builders (Select, Insert, Update, Delete) for constructing queries step-by-step
|
|
610
|
+
- **Factory Pattern**: Dialect factory and executor creation abstract instantiation logic
|
|
611
|
+
- **Unit of Work**: Change tracking and batch persistence in `OrmSession` coordinate all modifications
|
|
612
|
+
- **Identity Map**: One entity instance per row within a session prevents duplicate object issues
|
|
613
|
+
- **Interceptor/Pipeline**: Query interceptors and flush lifecycle hooks enable cross-cutting concerns
|
|
614
|
+
- **Adapter Pattern**: Connection pooling adapters allow different pool implementations
|
|
615
|
+
|
|
616
|
+
### Type Safety
|
|
617
|
+
|
|
618
|
+
- **Zero `any` types**: The entire src codebase contains zero `any` typesβevery value is properly typed
|
|
619
|
+
- **100% typed public API**: Every public method, parameter, and return value is fully typed
|
|
620
|
+
- **Full type inference**: From schema definition through query building to result hydration
|
|
621
|
+
- **Compile-time safety**: Catch SQL errors at TypeScript compile time, not runtime
|
|
622
|
+
- **Generic-driven**: Leverages TypeScript generics extensively for type propagation
|
|
623
|
+
|
|
624
|
+
### Separation of Concerns
|
|
625
|
+
|
|
626
|
+
Each layer has a clear, focused responsibility:
|
|
627
|
+
|
|
628
|
+
- **Core AST layer**: SQL representation independent of any specific dialect
|
|
629
|
+
- **Dialect layer**: Vendor-specific SQL compilation (MySQL, PostgreSQL, etc.)
|
|
630
|
+
- **Schema layer**: Table and column definitions with relations
|
|
631
|
+
- **Query builder layer**: Fluent API for building type-safe queries
|
|
632
|
+
- **Hydration layer**: Transforms flat result sets into nested object graphs
|
|
633
|
+
- **ORM runtime layer**: Entity management, change tracking, lazy relations, transactions
|
|
634
|
+
|
|
635
|
+
You can use just the layers you need and stay at the low level (AST + dialects) or adopt higher levels when beneficial.
|
|
636
|
+
|
|
637
|
+
---
|
|
638
|
+
|
|
639
|
+
## Frequently Asked Questions β
|
|
640
|
+
|
|
641
|
+
**Q: How does MetalORM differ from other ORMs?**
|
|
642
|
+
A: MetalORM's unique three-level architecture lets you choose your abstraction levelβuse just the query builder, add the ORM runtime when needed, or go full decorator-based entities. This gradual adoption path is uncommon in the TypeScript ecosystem. You're not locked into an all-or-nothing ORM approach.
|
|
643
|
+
|
|
644
|
+
**Q: Can I use this in production?**
|
|
645
|
+
A: Yes! MetalORM is designed for production use with robust patterns like Unit of Work, Identity Map, and connection pooling support. The type-safe query builder ensures SQL correctness at compile time.
|
|
646
|
+
|
|
647
|
+
**Q: Do I need to use all three levels?**
|
|
648
|
+
A: No! Use only what you need. Many projects stay at Level 1 (query builder) for its type-safe SQL building without any ORM overhead. Add runtime features (Level 2) or decorators (Level 3) only where they provide value.
|
|
649
|
+
|
|
650
|
+
**Q: What about migrations?**
|
|
651
|
+
A: MetalORM provides schema generation via DDL builders. See the [Schema Generation docs](./docs/schema-generation.md) for details on generating CREATE TABLE statements from your table definitions.
|
|
652
|
+
|
|
653
|
+
**Q: How type-safe is it really?**
|
|
654
|
+
A: Exceptionally. The entire codebase contains **zero** `any` typesβevery value is properly typed with TypeScript generics and inference. All public APIs are fully typed, and your queries, entities, and results get full TypeScript checking at compile time.
|
|
655
|
+
|
|
656
|
+
**Q: What design patterns are used?**
|
|
657
|
+
A: MetalORM implements several well-known patterns: Strategy (dialects & functions), Visitor (AST traversal), Builder (query construction), Factory (dialect & executor creation), Unit of Work (change tracking), Identity Map (entity caching), Interceptor (query hooks), and Adapter (pooling). This makes the codebase maintainable and extensible.
|
|
658
|
+
|
|
659
|
+
---
|
|
660
|
+
|
|
661
|
+
## Performance & Production π
|
|
662
|
+
|
|
663
|
+
- **Zero runtime overhead for Level 1** (query builder) - it's just SQL compilation and hydration
|
|
664
|
+
- **Efficient batching** for Level 2 lazy relations minimizes database round-trips
|
|
665
|
+
- **Identity Map** prevents duplicate entity instances and unnecessary queries
|
|
666
|
+
- **Connection pooling** supported via executor factory pattern (see [pooling docs](./docs/pooling.md))
|
|
667
|
+
- **Prepared statements** with parameterized queries protect against SQL injection
|
|
668
|
+
|
|
669
|
+
**Production checklist:**
|
|
670
|
+
- β
Use connection pooling for better resource management
|
|
671
|
+
- β
Enable query logging in development for debugging
|
|
672
|
+
- β
Set up proper error handling and retries
|
|
673
|
+
- β
Use transactions for multi-statement operations
|
|
674
|
+
- β
Monitor query performance with interceptors
|
|
675
|
+
|
|
676
|
+
---
|
|
677
|
+
|
|
678
|
+
## Community & Support π¬
|
|
679
|
+
|
|
680
|
+
- π **Issues:** [GitHub Issues](https://github.com/celsowm/metal-orm/issues)
|
|
681
|
+
- π‘ **Discussions:** [GitHub Discussions](https://github.com/celsowm/metal-orm/discussions)
|
|
682
|
+
- π **Documentation:** [Full docs](./docs/index.md)
|
|
683
|
+
- πΊοΈ **Roadmap:** [See what's planned](./ROADMAP.md)
|
|
684
|
+
- π¦ **Changelog:** [View releases](https://github.com/celsowm/metal-orm/releases)
|
|
685
|
+
|
|
686
|
+
---
|
|
687
|
+
|
|
688
|
+
<a id="contributing"></a>
|
|
689
|
+
## Contributing π€
|
|
690
|
+
|
|
691
|
+
Issues and PRs are welcome! If you're interested in pushing the runtime/ORM side further (soft deletes, multi-tenant filters, outbox patterns, etc.), contributions are especially appreciated.
|
|
692
|
+
|
|
693
|
+
See the contributing guide for details.
|
|
694
|
+
|
|
695
|
+
---
|
|
696
|
+
|
|
697
|
+
<a id="license"></a>
|
|
698
|
+
## License π
|
|
699
|
+
|
|
700
|
+
MetalORM is MIT licensed.
|