metal-orm 1.0.9 → 1.0.11
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 +333 -148
- package/package.json +1 -1
- package/src/index.ts +11 -10
package/README.md
CHANGED
|
@@ -1,59 +1,117 @@
|
|
|
1
|
-
# MetalORM
|
|
1
|
+
# MetalORM ⚙️
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/metal-orm)
|
|
4
4
|
[](https://github.com/celsowm/metal-orm/blob/main/LICENSE)
|
|
5
5
|
[](https://www.typescriptlang.org/)
|
|
6
6
|
|
|
7
|
-
**
|
|
7
|
+
**Type-safe SQL, layered ORM, decorator-based entities – all on the same core.**
|
|
8
8
|
|
|
9
|
-
MetalORM is a TypeScript-first, AST-driven SQL toolkit:
|
|
9
|
+
MetalORM is a TypeScript-first, AST-driven SQL toolkit you can dial up or down depending on how “ORM-y” you want to be:
|
|
10
10
|
|
|
11
|
-
-
|
|
12
|
-
|
|
11
|
+
- **Level 1 – Query builder & hydration 🧩**
|
|
12
|
+
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.
|
|
13
|
+
- **Level 2 – ORM runtime (entities + Unit of Work 🧠)**
|
|
14
|
+
Let `OrmContext` 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 `saveChanges()`.
|
|
15
|
+
- **Level 3 – Decorator entities (classes + metadata ✨)**
|
|
16
|
+
Use `@Entity`, `@Column`, `@PrimaryKey`, relation decorators, `bootstrapEntities()` and `selectFromEntity()` to describe your model classes. MetalORM bootstraps schema & relations from metadata and plugs them into the same runtime and query builder.
|
|
13
17
|
|
|
14
|
-
Use only the
|
|
18
|
+
Use only the layer you need in each part of your codebase.
|
|
15
19
|
|
|
16
20
|
---
|
|
17
21
|
|
|
18
|
-
|
|
22
|
+
<a id="table-of-contents"></a>
|
|
23
|
+
## Table of Contents 🧭
|
|
24
|
+
|
|
25
|
+
- [Documentation](#documentation)
|
|
26
|
+
- [Features](#features)
|
|
27
|
+
- [Installation](#installation)
|
|
28
|
+
- [Quick start - three levels](#quick-start)
|
|
29
|
+
- [Level 1 – Query builder & hydration](#level-1)
|
|
30
|
+
- [Level 2 – Entities + Unit of Work](#level-2)
|
|
31
|
+
- [Level 3 – Decorator entities](#level-3)
|
|
32
|
+
- [When to use which level?](#when-to-use-which-level)
|
|
33
|
+
- [Design notes](#design-notes)
|
|
34
|
+
- [Contributing](#contributing)
|
|
35
|
+
- [License](#license)
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
<a id="documentation"></a>
|
|
40
|
+
## Documentation 📚
|
|
41
|
+
|
|
42
|
+
Full docs live in the `docs/` folder:
|
|
19
43
|
|
|
20
|
-
Full docs live in the `docs/` folder:
|
|
21
|
-
|
|
22
44
|
- [Introduction](https://github.com/celsowm/metal-orm/blob/main/docs/index.md)
|
|
23
45
|
- [Getting Started](https://github.com/celsowm/metal-orm/blob/main/docs/getting-started.md)
|
|
46
|
+
- [Level 3 Backend Tutorial](https://github.com/celsowm/metal-orm/blob/main/docs/level-3-backend-tutorial.md)
|
|
24
47
|
- [Schema Definition](https://github.com/celsowm/metal-orm/blob/main/docs/schema-definition.md)
|
|
25
48
|
- [Query Builder](https://github.com/celsowm/metal-orm/blob/main/docs/query-builder.md)
|
|
26
49
|
- [DML Operations](https://github.com/celsowm/metal-orm/blob/main/docs/dml-operations.md)
|
|
27
50
|
- [Hydration & Entities](https://github.com/celsowm/metal-orm/blob/main/docs/hydration.md)
|
|
28
51
|
- [Runtime & Unit of Work](https://github.com/celsowm/metal-orm/blob/main/docs/runtime.md)
|
|
29
|
-
- [Advanced Features](https://github.com/celsowm/metal-orm/blob/main/docs/advanced-features.md)
|
|
30
|
-
- [Multi-Dialect Support](https://github.com/celsowm/metal-orm/blob/main/docs/multi-dialect-support.md)
|
|
31
|
-
- [API Reference](https://github.com/celsowm/metal-orm/blob/main/docs/api-reference.md)
|
|
52
|
+
- [Advanced Features](https://github.com/celsowm/metal-orm/blob/main/docs/advanced-features.md)
|
|
53
|
+
- [Multi-Dialect Support](https://github.com/celsowm/metal-orm/blob/main/docs/multi-dialect-support.md)
|
|
54
|
+
- [API Reference](https://github.com/celsowm/metal-orm/blob/main/docs/api-reference.md)
|
|
32
55
|
|
|
33
56
|
---
|
|
34
57
|
|
|
35
|
-
|
|
58
|
+
<a id="features"></a>
|
|
59
|
+
## Features 🚀
|
|
60
|
+
|
|
61
|
+
### Level 1 – Query builder & hydration
|
|
62
|
+
|
|
63
|
+
- **Declarative schema definition** with `defineTable`, `col.*`, and typed relations.
|
|
64
|
+
- **Fluent query builder** over a real SQL AST
|
|
65
|
+
(`SelectQueryBuilder`, `InsertQueryBuilder`, `UpdateQueryBuilder`, `DeleteQueryBuilder`).
|
|
66
|
+
- **Advanced SQL**: CTEs, aggregates, window functions, subqueries, JSON, CASE, EXISTS.
|
|
67
|
+
- **Expression builders**: `eq`, `and`, `or`, `between`, `inList`, `exists`, `jsonPath`, `caseWhen`, window functions like `rowNumber`, `rank`, `lag`, `lead`, etc., all backed by typed AST nodes.
|
|
68
|
+
- **Relation-aware hydration**: turn flat rows into nested objects (`user.posts`, `user.roles`, etc.) using a hydration plan derived from the AST metadata.
|
|
69
|
+
- **Multi-dialect**: compile once, run on MySQL/MariaDB, PostgreSQL, SQLite, or SQL Server via pluggable dialects.
|
|
70
|
+
- **DML**: type-safe INSERT / UPDATE / DELETE with `RETURNING` where supported.
|
|
71
|
+
|
|
72
|
+
Level 1 is ideal when you:
|
|
73
|
+
|
|
74
|
+
- Already have a domain model and just want a serious SQL builder.
|
|
75
|
+
- Want deterministic SQL (no magical query generation).
|
|
76
|
+
- Need to share the same AST across tooling (e.g. codegen, diagnostics, logging).
|
|
77
|
+
|
|
78
|
+
### Level 2 – ORM runtime (`OrmContext`)
|
|
79
|
+
|
|
80
|
+
On top of the query builder, MetalORM ships a focused runtime:
|
|
81
|
+
|
|
82
|
+
- **Entities inferred from your `TableDef`s** (no separate mapping file).
|
|
83
|
+
- **Lazy, batched relations**: `user.posts.load()`, `user.roles.syncByIds([...])`, etc.
|
|
84
|
+
- **Identity map**: the same row becomes the same entity instance within a context (see the [Identity map pattern](https://en.wikipedia.org/wiki/Identity_map_pattern)).
|
|
85
|
+
- **Unit of Work (`OrmContext`)** tracking New/Dirty/Removed entities and relation changes, inspired by the classic [Unit of Work pattern](https://en.wikipedia.org/wiki/Unit_of_work).
|
|
86
|
+
- **Graph persistence**: mutate a whole object graph and flush once with `ctx.saveChanges()`.
|
|
87
|
+
- **Relation change processor** that knows how to deal with has-many and many-to-many pivot tables.
|
|
88
|
+
- **Interceptors**: `beforeFlush` / `afterFlush` hooks for cross-cutting concerns (auditing, multi-tenant filters, soft delete filters, etc.).
|
|
89
|
+
- **Domain events**: `addDomainEvent` and a DomainEventBus integrated into `saveChanges()`, aligned with domain events from [Domain-driven design](https://en.wikipedia.org/wiki/Domain-driven_design).
|
|
90
|
+
|
|
91
|
+
Use this layer where:
|
|
36
92
|
|
|
37
|
-
|
|
93
|
+
- A request-scoped context fits (web/API handlers, jobs).
|
|
94
|
+
- You want change tracking, cascades, and relation helpers instead of manual SQL for every update.
|
|
38
95
|
|
|
39
|
-
|
|
40
|
-
- **Fluent query builder** over a real SQL AST (`SelectQueryBuilder`, `InsertQueryBuilder`, `UpdateQueryBuilder`, `DeleteQueryBuilder`).
|
|
41
|
-
- **Advanced SQL**: CTEs, aggregates, window functions, subqueries, JSON, CASE, EXISTS.
|
|
42
|
-
- **Relation hydration**: turn flat rows into nested objects (`user.posts`, `user.roles`, etc.).
|
|
43
|
-
- **Multi-dialect**: compile once, run on MySQL, PostgreSQL, SQLite, or SQL Server.
|
|
44
|
-
- **DML**: type-safe INSERT / UPDATE / DELETE with `RETURNING` where supported.
|
|
96
|
+
### Level 3 – Decorator entities
|
|
45
97
|
|
|
46
|
-
|
|
98
|
+
If you like explicit model classes, you can add a thin decorator layer on top of the same schema/runtime:
|
|
47
99
|
|
|
48
|
-
-
|
|
49
|
-
-
|
|
50
|
-
-
|
|
51
|
-
-
|
|
52
|
-
-
|
|
100
|
+
- `@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).
|
|
101
|
+
- `@Column(...)` and `@PrimaryKey(...)` on properties; decorators collect column metadata and later build `TableDef`s from it.
|
|
102
|
+
- Relation decorators:
|
|
103
|
+
- `@HasMany({ target, foreignKey, ... })`
|
|
104
|
+
- `@BelongsTo({ target, foreignKey, ... })`
|
|
105
|
+
- `@BelongsToMany({ target, pivotTable, ... })`
|
|
106
|
+
- `bootstrapEntities()` scans metadata, builds `TableDef`s, wires relations with the same `hasMany` / `belongsTo` / `belongsToMany` helpers you would use manually, and returns the resulting tables.
|
|
107
|
+
- `selectFromEntity(MyEntity)` lets you start a `SelectQueryBuilder` directly from the class.
|
|
108
|
+
|
|
109
|
+
You don’t have to use decorators, but when you do, you’re still on the same AST + dialect + runtime foundation.
|
|
53
110
|
|
|
54
111
|
---
|
|
55
112
|
|
|
56
|
-
|
|
113
|
+
<a id="installation"></a>
|
|
114
|
+
## Installation 📦
|
|
57
115
|
|
|
58
116
|
```bash
|
|
59
117
|
# npm
|
|
@@ -62,40 +120,46 @@ npm install metal-orm
|
|
|
62
120
|
# yarn
|
|
63
121
|
yarn add metal-orm
|
|
64
122
|
|
|
65
|
-
# pnpm
|
|
66
|
-
pnpm add metal-orm
|
|
67
|
-
```
|
|
68
|
-
|
|
69
|
-
MetalORM compiles SQL; you bring your own driver:
|
|
70
|
-
|
|
71
|
-
| Dialect
|
|
72
|
-
|
|
|
73
|
-
| MySQL / MariaDB
|
|
74
|
-
| SQLite
|
|
75
|
-
| PostgreSQL
|
|
76
|
-
| SQL Server
|
|
77
|
-
|
|
78
|
-
Pick the matching dialect (MySqlDialect
|
|
79
|
-
|
|
80
|
-
> Drivers are declared as optional peer dependencies. Install only the ones you actually use in your project.
|
|
81
|
-
|
|
82
|
-
### Playground (optional)
|
|
83
|
-
|
|
84
|
-
The React playground lives in `playground/` and is no longer part of the published package or its dependency tree. To run it locally:
|
|
85
|
-
|
|
86
|
-
1. `cd playground && npm install`
|
|
87
|
-
2. `npm run dev` (uses the root `vite.config.ts`)
|
|
88
|
-
|
|
89
|
-
It boots against an in-memory SQLite database seeded from
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
123
|
+
# pnpm
|
|
124
|
+
pnpm add metal-orm
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
MetalORM compiles SQL; you bring your own driver:
|
|
128
|
+
|
|
129
|
+
| Dialect | Driver | Install |
|
|
130
|
+
| ------------------ | --------- | ---------------------- |
|
|
131
|
+
| MySQL / MariaDB | `mysql2` | `npm install mysql2` |
|
|
132
|
+
| SQLite | `sqlite3` | `npm install sqlite3` |
|
|
133
|
+
| PostgreSQL | `pg` | `npm install pg` |
|
|
134
|
+
| SQL Server | `tedious` | `npm install tedious` |
|
|
135
|
+
|
|
136
|
+
Pick the matching dialect (`MySqlDialect`, `SQLiteDialect`, `PostgresDialect`, `MSSQLDialect`) when compiling queries.
|
|
137
|
+
|
|
138
|
+
> Drivers are declared as optional peer dependencies. Install only the ones you actually use in your project.
|
|
139
|
+
|
|
140
|
+
### Playground (optional) 🧪
|
|
141
|
+
|
|
142
|
+
The React playground lives in `playground/` and is no longer part of the published package or its dependency tree. To run it locally:
|
|
143
|
+
|
|
144
|
+
1. `cd playground && npm install`
|
|
145
|
+
2. `npm run dev` (uses the root `vite.config.ts`)
|
|
146
|
+
|
|
147
|
+
It boots against an in-memory SQLite database seeded from fixtures under `playground/shared/`.
|
|
148
|
+
|
|
149
|
+
---
|
|
150
|
+
|
|
151
|
+
<a id="quick-start"></a>
|
|
152
|
+
## Quick start – three levels
|
|
153
|
+
|
|
154
|
+
<a id="level-1"></a>
|
|
155
|
+
### Level 1: Query builder & hydration 🧩
|
|
156
|
+
|
|
157
|
+
#### 1. Tiny table, tiny query
|
|
158
|
+
|
|
159
|
+
MetalORM can be just a straightforward query builder.
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
import mysql from 'mysql2/promise';
|
|
99
163
|
import {
|
|
100
164
|
defineTable,
|
|
101
165
|
col,
|
|
@@ -127,24 +191,23 @@ const { sql, params } = listOpenTodos.compile(dialect);
|
|
|
127
191
|
|
|
128
192
|
// 4) Run with your favorite driver
|
|
129
193
|
const connection = await mysql.createConnection({ /* ... */ });
|
|
130
|
-
const [rows] = await connection.execute(sql, params);
|
|
131
|
-
|
|
132
|
-
console.log(rows);
|
|
133
|
-
// [
|
|
134
|
-
// { id: 1, title: 'Write docs', done: 0 },
|
|
135
|
-
// { id: 2, title: 'Ship feature', done: 0 },
|
|
136
|
-
// ]
|
|
137
|
-
```
|
|
194
|
+
const [rows] = await connection.execute(sql, params);
|
|
138
195
|
|
|
196
|
+
console.log(rows);
|
|
197
|
+
// [
|
|
198
|
+
// { id: 1, title: 'Write docs', done: 0 },
|
|
199
|
+
// { id: 2, title: 'Ship feature', done: 0 },
|
|
200
|
+
// ]
|
|
201
|
+
```
|
|
139
202
|
|
|
140
203
|
That’s it: schema, query, SQL, done.
|
|
141
204
|
|
|
142
|
-
2. Relations & hydration
|
|
205
|
+
#### 2. Relations & hydration (still no ORM)
|
|
206
|
+
|
|
207
|
+
Now add relations and get nested objects, still without committing to a runtime.
|
|
143
208
|
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
```ts
|
|
147
|
-
import {
|
|
209
|
+
```ts
|
|
210
|
+
import {
|
|
148
211
|
defineTable,
|
|
149
212
|
col,
|
|
150
213
|
hasMany,
|
|
@@ -187,43 +250,43 @@ const builder = new SelectQueryBuilder(users)
|
|
|
187
250
|
columns: [posts.columns.id, posts.columns.title, posts.columns.createdAt],
|
|
188
251
|
}); // eager relation for hydration
|
|
189
252
|
|
|
190
|
-
const { sql, params } = builder.compile(dialect);
|
|
191
|
-
const [rows] = await connection.execute(sql, params);
|
|
192
|
-
|
|
193
|
-
// Turn flat rows into nested objects
|
|
194
|
-
const hydrated = hydrateRows(
|
|
195
|
-
rows as Record<string, unknown>[],
|
|
196
|
-
builder.getHydrationPlan(),
|
|
197
|
-
);
|
|
198
|
-
|
|
199
|
-
console.log(hydrated);
|
|
200
|
-
// [
|
|
201
|
-
// {
|
|
202
|
-
// id: 1,
|
|
203
|
-
// name: 'John Doe',
|
|
204
|
-
// email: 'john@example.com',
|
|
205
|
-
// postCount: 15,
|
|
206
|
-
// rank: 1,
|
|
207
|
-
// posts: [
|
|
208
|
-
// { id: 101, title: 'Latest Post', createdAt: '2023-05-15T10:00:00Z' },
|
|
209
|
-
// // ...
|
|
210
|
-
// ],
|
|
211
|
-
// },
|
|
212
|
-
// // ...
|
|
213
|
-
// ]
|
|
214
|
-
```
|
|
215
|
-
|
|
253
|
+
const { sql, params } = builder.compile(dialect);
|
|
254
|
+
const [rows] = await connection.execute(sql, params);
|
|
255
|
+
|
|
256
|
+
// Turn flat rows into nested objects
|
|
257
|
+
const hydrated = hydrateRows(
|
|
258
|
+
rows as Record<string, unknown>[],
|
|
259
|
+
builder.getHydrationPlan(),
|
|
260
|
+
);
|
|
261
|
+
|
|
262
|
+
console.log(hydrated);
|
|
263
|
+
// [
|
|
264
|
+
// {
|
|
265
|
+
// id: 1,
|
|
266
|
+
// name: 'John Doe',
|
|
267
|
+
// email: 'john@example.com',
|
|
268
|
+
// postCount: 15,
|
|
269
|
+
// rank: 1,
|
|
270
|
+
// posts: [
|
|
271
|
+
// { id: 101, title: 'Latest Post', createdAt: '2023-05-15T10:00:00Z' },
|
|
272
|
+
// // ...
|
|
273
|
+
// ],
|
|
274
|
+
// },
|
|
275
|
+
// // ...
|
|
276
|
+
// ]
|
|
277
|
+
```
|
|
216
278
|
|
|
217
279
|
Use this mode anywhere you want powerful SQL + nice nested results, without changing how you manage your models.
|
|
218
280
|
|
|
219
|
-
|
|
281
|
+
<a id="level-2"></a>
|
|
282
|
+
### Level 2: Entities + Unit of Work (ORM runtime) 🧠
|
|
283
|
+
|
|
284
|
+
When you're ready, you can let MetalORM manage entities and relations for you.
|
|
285
|
+
|
|
286
|
+
Instead of “naked objects”, your queries can return entities attached to an `OrmContext`:
|
|
220
287
|
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
Instead of "naked objects", your queries can return entities attached to an OrmContext:
|
|
224
|
-
|
|
225
|
-
```ts
|
|
226
|
-
import {
|
|
288
|
+
```ts
|
|
289
|
+
import {
|
|
227
290
|
OrmContext,
|
|
228
291
|
MySqlDialect,
|
|
229
292
|
SelectQueryBuilder,
|
|
@@ -233,7 +296,7 @@ import {
|
|
|
233
296
|
// 1) Create an OrmContext for this request
|
|
234
297
|
const ctx = new OrmContext({
|
|
235
298
|
dialect: new MySqlDialect(),
|
|
236
|
-
|
|
299
|
+
executor: {
|
|
237
300
|
async executeSql(sql, params) {
|
|
238
301
|
const [rows] = await connection.execute(sql, params);
|
|
239
302
|
// MetalORM expects columns + values; adapt as needed
|
|
@@ -242,6 +305,16 @@ const ctx = new OrmContext({
|
|
|
242
305
|
values: rows.map(row => Object.values(row)),
|
|
243
306
|
}];
|
|
244
307
|
},
|
|
308
|
+
// Optional: if you want MetalORM to handle transactions around saveChanges()
|
|
309
|
+
async beginTransaction() {
|
|
310
|
+
await connection.beginTransaction();
|
|
311
|
+
},
|
|
312
|
+
async commitTransaction() {
|
|
313
|
+
await connection.commit();
|
|
314
|
+
},
|
|
315
|
+
async rollbackTransaction() {
|
|
316
|
+
await connection.rollback();
|
|
317
|
+
},
|
|
245
318
|
},
|
|
246
319
|
});
|
|
247
320
|
|
|
@@ -268,44 +341,156 @@ const newPost = user.posts.add({ title: 'Hello from ORM mode' });
|
|
|
268
341
|
// Many-to-many via pivot:
|
|
269
342
|
await user.roles.syncByIds([1, 2, 3]);
|
|
270
343
|
|
|
271
|
-
// 3) Persist the entire graph
|
|
272
|
-
await ctx.saveChanges();
|
|
273
|
-
// INSERT/UPDATE/DELETE + pivot updates happen in a single Unit of Work.
|
|
274
|
-
```
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
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
|
-
|
|
344
|
+
// 3) Persist the entire graph
|
|
345
|
+
await ctx.saveChanges();
|
|
346
|
+
// INSERT/UPDATE/DELETE + pivot updates happen in a single Unit of Work.
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
What the runtime gives you:
|
|
350
|
+
|
|
351
|
+
- [Identity map](https://en.wikipedia.org/wiki/Identity_map_pattern) (per context).
|
|
352
|
+
- [Unit of Work](https://en.wikipedia.org/wiki/Unit_of_work) style change tracking on scalar properties.
|
|
353
|
+
- Relation tracking (add/remove/sync on collections).
|
|
354
|
+
- Cascades on relations: `'all' | 'persist' | 'remove' | 'link'`.
|
|
355
|
+
- Single flush: `ctx.saveChanges()` figures out inserts, updates, deletes, and pivot changes.
|
|
356
|
+
|
|
357
|
+
<a id="level-3"></a>
|
|
358
|
+
### Level 3: Decorator entities ✨
|
|
359
|
+
|
|
360
|
+
Finally, you can describe your models with decorators and still use the same runtime and query builder.
|
|
361
|
+
|
|
362
|
+
> Import paths here assume a `metal-orm/decorators` subpath export – adjust if your bundle exposes them differently.
|
|
363
|
+
|
|
364
|
+
```ts
|
|
365
|
+
import mysql from 'mysql2/promise';
|
|
366
|
+
import { OrmContext, MySqlDialect, col } from 'metal-orm';
|
|
367
|
+
import {
|
|
368
|
+
Entity,
|
|
369
|
+
Column,
|
|
370
|
+
PrimaryKey,
|
|
371
|
+
HasMany,
|
|
372
|
+
BelongsTo,
|
|
373
|
+
bootstrapEntities,
|
|
374
|
+
selectFromEntity,
|
|
375
|
+
} from 'metal-orm/decorators';
|
|
376
|
+
|
|
377
|
+
@Entity()
|
|
378
|
+
class User {
|
|
379
|
+
@PrimaryKey(col.int())
|
|
380
|
+
id!: number;
|
|
381
|
+
|
|
382
|
+
@Column(col.varchar(255).notNull())
|
|
383
|
+
name!: string;
|
|
384
|
+
|
|
385
|
+
@Column(col.varchar(255))
|
|
386
|
+
email?: string;
|
|
387
|
+
|
|
388
|
+
@HasMany({
|
|
389
|
+
target: () => Post,
|
|
390
|
+
foreignKey: 'userId',
|
|
391
|
+
})
|
|
392
|
+
posts!: any; // relation wrapper; type omitted for brevity
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
@Entity()
|
|
396
|
+
class Post {
|
|
397
|
+
@PrimaryKey(col.int())
|
|
398
|
+
id!: number;
|
|
399
|
+
|
|
400
|
+
@Column(col.varchar(255).notNull())
|
|
401
|
+
title!: string;
|
|
402
|
+
|
|
403
|
+
@Column(col.int().notNull())
|
|
404
|
+
userId!: number;
|
|
405
|
+
|
|
406
|
+
@BelongsTo({
|
|
407
|
+
target: () => User,
|
|
408
|
+
foreignKey: 'userId',
|
|
409
|
+
})
|
|
410
|
+
user!: any;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// 1) Bootstrap metadata once at startup
|
|
414
|
+
const tables = bootstrapEntities();
|
|
415
|
+
// tables: TableDef[] – compatible with the rest of MetalORM
|
|
416
|
+
|
|
417
|
+
// 2) Create OrmContext as before
|
|
418
|
+
const connection = await mysql.createConnection({ /* ... */ });
|
|
419
|
+
|
|
420
|
+
const ctx = new OrmContext({
|
|
421
|
+
dialect: new MySqlDialect(),
|
|
422
|
+
executor: {
|
|
423
|
+
async executeSql(sql, params) {
|
|
424
|
+
const [rows] = await connection.execute(sql, params);
|
|
425
|
+
return [{
|
|
426
|
+
columns: Object.keys(rows[0] ?? {}),
|
|
427
|
+
values: rows.map(row => Object.values(row)),
|
|
428
|
+
}];
|
|
429
|
+
},
|
|
430
|
+
},
|
|
431
|
+
});
|
|
432
|
+
|
|
433
|
+
// 3) Query starting from the entity class
|
|
434
|
+
const [user] = await selectFromEntity(User)
|
|
435
|
+
.select({
|
|
436
|
+
id: User.prototype.id, // or map to columns by name/alias as you prefer
|
|
437
|
+
name: User.prototype.name,
|
|
438
|
+
})
|
|
439
|
+
.includeLazy('posts')
|
|
440
|
+
.where(/* same eq()/and() API as before */)
|
|
441
|
+
.execute(ctx);
|
|
442
|
+
|
|
443
|
+
user.posts.add({ title: 'From decorators' });
|
|
444
|
+
await ctx.saveChanges();
|
|
445
|
+
```
|
|
446
|
+
|
|
447
|
+
This level is nice when:
|
|
448
|
+
|
|
449
|
+
- You want classes as your domain model, but don’t want a separate schema DSL.
|
|
450
|
+
- You like decorators for explicit mapping but still want AST-first SQL and a disciplined runtime.
|
|
451
|
+
|
|
452
|
+
---
|
|
453
|
+
|
|
454
|
+
<a id="when-to-use-which-level"></a>
|
|
455
|
+
## When to use which level? 🤔
|
|
456
|
+
|
|
457
|
+
- **Query builder + hydration (Level 1)**
|
|
458
|
+
Great for reporting/analytics, existing codebases with their own models, and services that need strong SQL but minimal runtime magic.
|
|
459
|
+
|
|
460
|
+
- **ORM runtime (Level 2)**
|
|
461
|
+
Great for request-scoped application logic and domain modeling where lazy relations, cascades, and graph persistence pay off.
|
|
462
|
+
|
|
463
|
+
- **Decorator entities (Level 3)**
|
|
464
|
+
Great when you want class-based entities and decorators, but still want to keep the underlying architecture explicit and layered.
|
|
465
|
+
|
|
466
|
+
All three levels share the same schema, AST, and dialects, so you can mix them as needed and migrate gradually.
|
|
467
|
+
|
|
468
|
+
---
|
|
469
|
+
|
|
470
|
+
<a id="design-notes"></a>
|
|
471
|
+
## Design notes 🧱
|
|
472
|
+
|
|
473
|
+
Under the hood, MetalORM leans on well-known patterns:
|
|
474
|
+
|
|
475
|
+
- **AST + dialect abstraction**: SQL is modeled as typed AST nodes, compiled by dialects that you can extend.
|
|
476
|
+
- **Separation of concerns**: schema, AST, SQL compilation, execution, and ORM runtime are separate layers.
|
|
477
|
+
- **Unit of Work + Identity Map**: `OrmContext` coordinates changes and enforces one entity instance per row, following the [Unit of Work](https://en.wikipedia.org/wiki/Unit_of_work) and [Identity map](https://en.wikipedia.org/wiki/Identity_map_pattern) patterns.
|
|
478
|
+
- **Domain events + interceptors**: decouple side-effects from persistence and let cross-cutting concerns hook into flush points, similar in spirit to domain events in [Domain-driven design](https://en.wikipedia.org/wiki/Domain-driven_design).
|
|
479
|
+
|
|
480
|
+
You can stay at the low level (just AST + dialects) or adopt the higher levels when it makes your code simpler.
|
|
481
|
+
|
|
482
|
+
---
|
|
483
|
+
|
|
484
|
+
<a id="contributing"></a>
|
|
485
|
+
## Contributing 🤝
|
|
486
|
+
|
|
487
|
+
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.
|
|
488
|
+
|
|
489
|
+
See the contributing guide for details.
|
|
490
|
+
|
|
491
|
+
---
|
|
492
|
+
|
|
493
|
+
<a id="license"></a>
|
|
494
|
+
## License 📄
|
|
495
|
+
|
|
311
496
|
MetalORM is MIT licensed.
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -3,19 +3,20 @@ export * from './schema/table.js';
|
|
|
3
3
|
export * from './schema/column.js';
|
|
4
4
|
export * from './schema/relation.js';
|
|
5
5
|
export * from './schema/types.js';
|
|
6
|
-
export * from './query-builder/select.js';
|
|
7
|
-
export * from './query-builder/insert.js';
|
|
8
|
-
export * from './query-builder/update.js';
|
|
9
|
-
export * from './query-builder/delete.js';
|
|
10
|
-
export * from './core/ast/expression.js';
|
|
6
|
+
export * from './query-builder/select.js';
|
|
7
|
+
export * from './query-builder/insert.js';
|
|
8
|
+
export * from './query-builder/update.js';
|
|
9
|
+
export * from './query-builder/delete.js';
|
|
10
|
+
export * from './core/ast/expression.js';
|
|
11
11
|
export * from './core/dialect/mysql/index.js';
|
|
12
12
|
export * from './core/dialect/mssql/index.js';
|
|
13
13
|
export * from './core/dialect/sqlite/index.js';
|
|
14
|
-
export * from './
|
|
15
|
-
export * from './orm/
|
|
16
|
-
export * from './
|
|
17
|
-
export * from './
|
|
18
|
-
export * from './orm/
|
|
14
|
+
export * from './core/dialect/postgres/index.js';
|
|
15
|
+
export * from './orm/als.js';
|
|
16
|
+
export * from './orm/hydration.js';
|
|
17
|
+
export * from './codegen/typescript.js';
|
|
18
|
+
export * from './orm/orm-context.js';
|
|
19
|
+
export * from './orm/entity.js';
|
|
19
20
|
export * from './orm/lazy-batch.js';
|
|
20
21
|
export * from './orm/relations/has-many.js';
|
|
21
22
|
export * from './orm/relations/belongs-to.js';
|