@mikro-orm/sql 7.0.2-dev.9 → 7.0.3-dev.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.
- package/AbstractSqlConnection.d.ts +12 -0
- package/AbstractSqlConnection.js +11 -0
- package/AbstractSqlDriver.d.ts +1 -0
- package/AbstractSqlDriver.js +1 -0
- package/AbstractSqlPlatform.d.ts +1 -0
- package/AbstractSqlPlatform.js +1 -0
- package/README.md +128 -294
- package/SqlEntityManager.d.ts +3 -0
- package/SqlEntityManager.js +1 -0
- package/SqlEntityRepository.d.ts +1 -0
- package/SqlEntityRepository.js +1 -0
- package/dialects/sqlite/SqliteSchemaHelper.js +1 -1
- package/package.json +4 -4
- package/plugin/index.d.ts +2 -0
- package/plugin/index.js +1 -0
- package/query/NativeQueryBuilder.d.ts +3 -0
- package/query/enums.d.ts +2 -0
- package/query/enums.js +2 -0
- package/schema/SchemaHelper.d.ts +16 -0
- package/schema/SchemaHelper.js +15 -0
- package/schema/SqlSchemaGenerator.d.ts +1 -0
- package/schema/SqlSchemaGenerator.js +1 -0
|
@@ -2,13 +2,17 @@ import { type ControlledTransaction, type Dialect, Kysely } from 'kysely';
|
|
|
2
2
|
import { type AnyEntity, Connection, type Dictionary, type EntityData, type IsolationLevel, type LogContext, type LoggingOptions, type MaybePromise, type QueryResult, RawQueryFragment, type Transaction, type TransactionEventBroadcaster } from '@mikro-orm/core';
|
|
3
3
|
import type { AbstractSqlPlatform } from './AbstractSqlPlatform.js';
|
|
4
4
|
import { NativeQueryBuilder } from './query/NativeQueryBuilder.js';
|
|
5
|
+
/** Base class for SQL database connections, built on top of Kysely. */
|
|
5
6
|
export declare abstract class AbstractSqlConnection extends Connection {
|
|
6
7
|
#private;
|
|
7
8
|
protected platform: AbstractSqlPlatform;
|
|
9
|
+
/** Creates a Kysely dialect instance with driver-specific configuration. */
|
|
8
10
|
abstract createKyselyDialect(overrides: Dictionary): MaybePromise<Dialect>;
|
|
11
|
+
/** Establishes the database connection and runs the onConnect hook. */
|
|
9
12
|
connect(options?: {
|
|
10
13
|
skipOnConnect?: boolean;
|
|
11
14
|
}): Promise<void>;
|
|
15
|
+
/** Initializes the Kysely client from driver options or a user-provided Kysely instance. */
|
|
12
16
|
createKysely(): MaybePromise<void>;
|
|
13
17
|
/**
|
|
14
18
|
* @inheritDoc
|
|
@@ -28,8 +32,11 @@ export declare abstract class AbstractSqlConnection extends Connection {
|
|
|
28
32
|
reason: string;
|
|
29
33
|
error?: Error;
|
|
30
34
|
}>;
|
|
35
|
+
/** Returns the underlying Kysely client, creating it synchronously if needed. */
|
|
31
36
|
getClient<T = any>(): Kysely<T>;
|
|
37
|
+
/** Ensures the Kysely client is initialized, creating it asynchronously if needed. */
|
|
32
38
|
initClient(): Promise<void>;
|
|
39
|
+
/** Executes a callback within a transaction, committing on success and rolling back on error. */
|
|
33
40
|
transactional<T>(cb: (trx: Transaction<ControlledTransaction<any, any>>) => Promise<T>, options?: {
|
|
34
41
|
isolationLevel?: IsolationLevel;
|
|
35
42
|
readOnly?: boolean;
|
|
@@ -37,6 +44,7 @@ export declare abstract class AbstractSqlConnection extends Connection {
|
|
|
37
44
|
eventBroadcaster?: TransactionEventBroadcaster;
|
|
38
45
|
loggerContext?: LogContext;
|
|
39
46
|
}): Promise<T>;
|
|
47
|
+
/** Begins a new transaction or creates a savepoint if a transaction context already exists. */
|
|
40
48
|
begin(options?: {
|
|
41
49
|
isolationLevel?: IsolationLevel;
|
|
42
50
|
readOnly?: boolean;
|
|
@@ -44,10 +52,14 @@ export declare abstract class AbstractSqlConnection extends Connection {
|
|
|
44
52
|
eventBroadcaster?: TransactionEventBroadcaster;
|
|
45
53
|
loggerContext?: LogContext;
|
|
46
54
|
}): Promise<ControlledTransaction<any, any>>;
|
|
55
|
+
/** Commits the transaction or releases the savepoint. */
|
|
47
56
|
commit(ctx: ControlledTransaction<any, any>, eventBroadcaster?: TransactionEventBroadcaster, loggerContext?: LogContext): Promise<void>;
|
|
57
|
+
/** Rolls back the transaction or rolls back to the savepoint. */
|
|
48
58
|
rollback(ctx: ControlledTransaction<any, any>, eventBroadcaster?: TransactionEventBroadcaster, loggerContext?: LogContext): Promise<void>;
|
|
49
59
|
private prepareQuery;
|
|
60
|
+
/** Executes a SQL query and returns the result based on the method: `'all'` for rows, `'get'` for single row, `'run'` for affected count. */
|
|
50
61
|
execute<T extends QueryResult | EntityData<AnyEntity> | EntityData<AnyEntity>[] = EntityData<AnyEntity>[]>(query: string | NativeQueryBuilder | RawQueryFragment, params?: readonly unknown[], method?: 'all' | 'get' | 'run', ctx?: Transaction, loggerContext?: LoggingOptions): Promise<T>;
|
|
62
|
+
/** Executes a SQL query and returns an async iterable that yields results row by row. */
|
|
51
63
|
stream<T extends EntityData<AnyEntity>>(query: string | NativeQueryBuilder | RawQueryFragment, params?: readonly unknown[], ctx?: Transaction<Kysely<any>>, loggerContext?: LoggingOptions): AsyncIterableIterator<T>;
|
|
52
64
|
/** @inheritDoc */
|
|
53
65
|
executeDump(dump: string): Promise<void>;
|
package/AbstractSqlConnection.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { CompiledQuery, Kysely } from 'kysely';
|
|
2
2
|
import { Connection, EventType, RawQueryFragment, Utils, } from '@mikro-orm/core';
|
|
3
3
|
import { NativeQueryBuilder } from './query/NativeQueryBuilder.js';
|
|
4
|
+
/** Base class for SQL database connections, built on top of Kysely. */
|
|
4
5
|
export class AbstractSqlConnection extends Connection {
|
|
5
6
|
#client;
|
|
7
|
+
/** Establishes the database connection and runs the onConnect hook. */
|
|
6
8
|
async connect(options) {
|
|
7
9
|
await this.initClient();
|
|
8
10
|
this.connected = true;
|
|
@@ -10,6 +12,7 @@ export class AbstractSqlConnection extends Connection {
|
|
|
10
12
|
await this.onConnect();
|
|
11
13
|
}
|
|
12
14
|
}
|
|
15
|
+
/** Initializes the Kysely client from driver options or a user-provided Kysely instance. */
|
|
13
16
|
createKysely() {
|
|
14
17
|
let driverOptions = this.options.driverOptions ?? this.config.get('driverOptions');
|
|
15
18
|
if (typeof driverOptions === 'function') {
|
|
@@ -64,6 +67,7 @@ export class AbstractSqlConnection extends Connection {
|
|
|
64
67
|
return { ok: false, reason: error.message, error };
|
|
65
68
|
}
|
|
66
69
|
}
|
|
70
|
+
/** Returns the underlying Kysely client, creating it synchronously if needed. */
|
|
67
71
|
getClient() {
|
|
68
72
|
if (!this.#client) {
|
|
69
73
|
const maybePromise = this.createKysely();
|
|
@@ -74,11 +78,13 @@ export class AbstractSqlConnection extends Connection {
|
|
|
74
78
|
}
|
|
75
79
|
return this.#client;
|
|
76
80
|
}
|
|
81
|
+
/** Ensures the Kysely client is initialized, creating it asynchronously if needed. */
|
|
77
82
|
async initClient() {
|
|
78
83
|
if (!this.#client) {
|
|
79
84
|
await this.createKysely();
|
|
80
85
|
}
|
|
81
86
|
}
|
|
87
|
+
/** Executes a callback within a transaction, committing on success and rolling back on error. */
|
|
82
88
|
async transactional(cb, options = {}) {
|
|
83
89
|
const trx = await this.begin(options);
|
|
84
90
|
try {
|
|
@@ -91,6 +97,7 @@ export class AbstractSqlConnection extends Connection {
|
|
|
91
97
|
throw error;
|
|
92
98
|
}
|
|
93
99
|
}
|
|
100
|
+
/** Begins a new transaction or creates a savepoint if a transaction context already exists. */
|
|
94
101
|
async begin(options = {}) {
|
|
95
102
|
if (options.ctx) {
|
|
96
103
|
const ctx = options.ctx;
|
|
@@ -130,6 +137,7 @@ export class AbstractSqlConnection extends Connection {
|
|
|
130
137
|
await options.eventBroadcaster?.dispatchEvent(EventType.afterTransactionStart, trx);
|
|
131
138
|
return trx;
|
|
132
139
|
}
|
|
140
|
+
/** Commits the transaction or releases the savepoint. */
|
|
133
141
|
async commit(ctx, eventBroadcaster, loggerContext) {
|
|
134
142
|
if (ctx.isRolledBack) {
|
|
135
143
|
return;
|
|
@@ -145,6 +153,7 @@ export class AbstractSqlConnection extends Connection {
|
|
|
145
153
|
}
|
|
146
154
|
await eventBroadcaster?.dispatchEvent(EventType.afterTransactionCommit, ctx);
|
|
147
155
|
}
|
|
156
|
+
/** Rolls back the transaction or rolls back to the savepoint. */
|
|
148
157
|
async rollback(ctx, eventBroadcaster, loggerContext) {
|
|
149
158
|
await eventBroadcaster?.dispatchEvent(EventType.beforeTransactionRollback, ctx);
|
|
150
159
|
if ('savepointName' in ctx) {
|
|
@@ -169,6 +178,7 @@ export class AbstractSqlConnection extends Connection {
|
|
|
169
178
|
const formatted = this.platform.formatQuery(query, params);
|
|
170
179
|
return { query, params, formatted };
|
|
171
180
|
}
|
|
181
|
+
/** Executes a SQL query and returns the result based on the method: `'all'` for rows, `'get'` for single row, `'run'` for affected count. */
|
|
172
182
|
async execute(query, params = [], method = 'all', ctx, loggerContext) {
|
|
173
183
|
await this.ensureConnection();
|
|
174
184
|
const q = this.prepareQuery(query, params);
|
|
@@ -179,6 +189,7 @@ export class AbstractSqlConnection extends Connection {
|
|
|
179
189
|
return this.transformRawResult(res, method);
|
|
180
190
|
}, { ...q, ...loggerContext });
|
|
181
191
|
}
|
|
192
|
+
/** Executes a SQL query and returns an async iterable that yields results row by row. */
|
|
182
193
|
async *stream(query, params = [], ctx, loggerContext) {
|
|
183
194
|
await this.ensureConnection();
|
|
184
195
|
const q = this.prepareQuery(query, params);
|
package/AbstractSqlDriver.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { type NativeQueryBuilder } from './query/NativeQueryBuilder.js';
|
|
|
6
6
|
import { QueryType } from './query/enums.js';
|
|
7
7
|
import { SqlEntityManager } from './SqlEntityManager.js';
|
|
8
8
|
import type { InternalField } from './typings.js';
|
|
9
|
+
/** Base class for SQL database drivers, implementing find/insert/update/delete using QueryBuilder. */
|
|
9
10
|
export declare abstract class AbstractSqlDriver<Connection extends AbstractSqlConnection = AbstractSqlConnection, Platform extends AbstractSqlPlatform = AbstractSqlPlatform> extends DatabaseDriver<Connection> {
|
|
10
11
|
[EntityManagerType]: SqlEntityManager<this>;
|
|
11
12
|
protected readonly connection: Connection;
|
package/AbstractSqlDriver.js
CHANGED
|
@@ -3,6 +3,7 @@ import { QueryBuilder } from './query/QueryBuilder.js';
|
|
|
3
3
|
import { JoinType, QueryType } from './query/enums.js';
|
|
4
4
|
import { SqlEntityManager } from './SqlEntityManager.js';
|
|
5
5
|
import { PivotCollectionPersister } from './PivotCollectionPersister.js';
|
|
6
|
+
/** Base class for SQL database drivers, implementing find/insert/update/delete using QueryBuilder. */
|
|
6
7
|
export class AbstractSqlDriver extends DatabaseDriver {
|
|
7
8
|
[EntityManagerType];
|
|
8
9
|
connection;
|
package/AbstractSqlPlatform.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { SqlSchemaGenerator } from './schema/SqlSchemaGenerator.js';
|
|
|
3
3
|
import { type SchemaHelper } from './schema/SchemaHelper.js';
|
|
4
4
|
import type { IndexDef } from './typings.js';
|
|
5
5
|
import { NativeQueryBuilder } from './query/NativeQueryBuilder.js';
|
|
6
|
+
/** Base class for SQL database platforms, providing SQL generation and quoting utilities. */
|
|
6
7
|
export declare abstract class AbstractSqlPlatform extends Platform {
|
|
7
8
|
#private;
|
|
8
9
|
protected readonly schemaHelper?: SchemaHelper;
|
package/AbstractSqlPlatform.js
CHANGED
|
@@ -2,6 +2,7 @@ import { isRaw, JsonProperty, Platform, raw, Utils, } from '@mikro-orm/core';
|
|
|
2
2
|
import { SqlEntityRepository } from './SqlEntityRepository.js';
|
|
3
3
|
import { SqlSchemaGenerator } from './schema/SqlSchemaGenerator.js';
|
|
4
4
|
import { NativeQueryBuilder } from './query/NativeQueryBuilder.js';
|
|
5
|
+
/** Base class for SQL database platforms, providing SQL generation and quoting utilities. */
|
|
5
6
|
export class AbstractSqlPlatform extends Platform {
|
|
6
7
|
static #JSON_PROPERTY_NAME_RE = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
|
|
7
8
|
schemaHelper;
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
<a href="https://mikro-orm.io"><img src="https://raw.githubusercontent.com/mikro-orm/mikro-orm/master/docs/static/img/logo-readme.svg?sanitize=true" alt="MikroORM" /></a>
|
|
3
3
|
</h1>
|
|
4
4
|
|
|
5
|
-
TypeScript ORM for Node.js based on Data Mapper, [Unit of Work](https://mikro-orm.io/docs/unit-of-work/) and [Identity Map](https://mikro-orm.io/docs/identity-map/) patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL, SQLite (including libSQL), MSSQL and Oracle databases.
|
|
5
|
+
TypeScript ORM for Node.js based on Data Mapper, [Unit of Work](https://mikro-orm.io/docs/unit-of-work/) and [Identity Map](https://mikro-orm.io/docs/identity-map/) patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL, SQLite (including libSQL), MSSQL and Oracle databases.
|
|
6
6
|
|
|
7
7
|
> Heavily inspired by [Doctrine](https://www.doctrine-project.org/) and [Hibernate](https://hibernate.org/).
|
|
8
8
|
|
|
@@ -13,143 +13,173 @@ TypeScript ORM for Node.js based on Data Mapper, [Unit of Work](https://mikro-or
|
|
|
13
13
|
[](https://coveralls.io/r/mikro-orm/mikro-orm?branch=master)
|
|
14
14
|
[](https://github.com/mikro-orm/mikro-orm/actions?workflow=tests)
|
|
15
15
|
|
|
16
|
-
##
|
|
16
|
+
## Quick Start
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
Install a driver package for your database:
|
|
19
19
|
|
|
20
|
-
|
|
21
|
-
|
|
20
|
+
```sh
|
|
21
|
+
npm install @mikro-orm/postgresql # PostgreSQL
|
|
22
|
+
npm install @mikro-orm/mysql # MySQL
|
|
23
|
+
npm install @mikro-orm/mariadb # MariaDB
|
|
24
|
+
npm install @mikro-orm/sqlite # SQLite
|
|
25
|
+
npm install @mikro-orm/libsql # libSQL / Turso
|
|
26
|
+
npm install @mikro-orm/mongodb # MongoDB
|
|
27
|
+
npm install @mikro-orm/mssql # MS SQL Server
|
|
28
|
+
npm install @mikro-orm/oracledb # Oracle
|
|
29
|
+
```
|
|
22
30
|
|
|
23
|
-
>
|
|
24
|
-
> loaded object in a map. Looks up objects using the map when referring to them.
|
|
25
|
-
> [(Martin Fowler)](https://www.martinfowler.com/eaaCatalog/identityMap.html)
|
|
31
|
+
> If you use additional packages like `@mikro-orm/cli`, `@mikro-orm/migrations`, or `@mikro-orm/entity-generator`, install `@mikro-orm/core` explicitly as well. See the [quick start guide](https://mikro-orm.io/docs/quick-start) for details.
|
|
26
32
|
|
|
27
|
-
|
|
33
|
+
### Define Entities
|
|
28
34
|
|
|
29
|
-
|
|
35
|
+
The recommended way to define entities is using [`defineEntity`](https://mikro-orm.io/docs/define-entity) with `setClass`:
|
|
30
36
|
|
|
31
|
-
|
|
37
|
+
```typescript
|
|
38
|
+
import { defineEntity, p, MikroORM } from '@mikro-orm/postgresql';
|
|
39
|
+
|
|
40
|
+
const AuthorSchema = defineEntity({
|
|
41
|
+
name: 'Author',
|
|
42
|
+
properties: {
|
|
43
|
+
id: p.integer().primary(),
|
|
44
|
+
name: p.string(),
|
|
45
|
+
email: p.string(),
|
|
46
|
+
born: p.datetime().nullable(),
|
|
47
|
+
books: () => p.oneToMany(Book).mappedBy('author'),
|
|
48
|
+
},
|
|
49
|
+
});
|
|
32
50
|
|
|
33
|
-
|
|
51
|
+
export class Author extends AuthorSchema.class {}
|
|
52
|
+
AuthorSchema.setClass(Author);
|
|
34
53
|
|
|
35
|
-
|
|
54
|
+
const BookSchema = defineEntity({
|
|
55
|
+
name: 'Book',
|
|
56
|
+
properties: {
|
|
57
|
+
id: p.integer().primary(),
|
|
58
|
+
title: p.string(),
|
|
59
|
+
author: () => p.manyToOne(Author).inversedBy('books'),
|
|
60
|
+
},
|
|
61
|
+
});
|
|
36
62
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
user.email = 'foo@bar.com';
|
|
40
|
-
const car = new Car();
|
|
41
|
-
user.cars.add(car);
|
|
42
|
-
|
|
43
|
-
// thanks to bi-directional cascading we only need to persist user entity
|
|
44
|
-
// flushing will create a transaction, insert new car and update user with new email
|
|
45
|
-
// as user entity is managed, calling flush() is enough
|
|
46
|
-
await em.flush();
|
|
63
|
+
export class Book extends BookSchema.class {}
|
|
64
|
+
BookSchema.setClass(Book);
|
|
47
65
|
```
|
|
48
66
|
|
|
49
|
-
|
|
67
|
+
You can also define entities using [decorators](https://mikro-orm.io/docs/defining-entities) or [`EntitySchema`](https://mikro-orm.io/docs/entity-schema). See the [defining entities guide](https://mikro-orm.io/docs/defining-entities) for all options.
|
|
50
68
|
|
|
51
|
-
|
|
69
|
+
### Initialize and Use
|
|
52
70
|
|
|
53
71
|
```typescript
|
|
54
|
-
@
|
|
55
|
-
export class User {
|
|
72
|
+
import { MikroORM, RequestContext } from '@mikro-orm/postgresql';
|
|
56
73
|
|
|
57
|
-
|
|
58
|
-
|
|
74
|
+
const orm = await MikroORM.init({
|
|
75
|
+
entities: [Author, Book],
|
|
76
|
+
dbName: 'my-db',
|
|
77
|
+
});
|
|
59
78
|
|
|
60
|
-
|
|
61
|
-
|
|
79
|
+
// Create new entities
|
|
80
|
+
const author = orm.em.create(Author, {
|
|
81
|
+
name: 'Jon Snow',
|
|
82
|
+
email: 'snow@wall.st',
|
|
83
|
+
});
|
|
84
|
+
const book = orm.em.create(Book, {
|
|
85
|
+
title: 'My Life on The Wall',
|
|
86
|
+
author,
|
|
87
|
+
});
|
|
62
88
|
|
|
63
|
-
|
|
64
|
-
|
|
89
|
+
// Flush persists all tracked changes in a single transaction
|
|
90
|
+
await orm.em.flush();
|
|
91
|
+
```
|
|
65
92
|
|
|
66
|
-
|
|
67
|
-
cars = new Collection<Car>(this);
|
|
93
|
+
### Querying
|
|
68
94
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
95
|
+
```typescript
|
|
96
|
+
// Find with relations
|
|
97
|
+
const authors = await orm.em.findAll(Author, {
|
|
98
|
+
populate: ['books'],
|
|
99
|
+
orderBy: { name: 'asc' },
|
|
100
|
+
});
|
|
72
101
|
|
|
73
|
-
|
|
102
|
+
// Type-safe QueryBuilder
|
|
103
|
+
const qb = orm.em.createQueryBuilder(Author);
|
|
104
|
+
const result = await qb
|
|
105
|
+
.select('*')
|
|
106
|
+
.where({ books: { title: { $like: '%Wall%' } } })
|
|
107
|
+
.getResult();
|
|
74
108
|
```
|
|
75
109
|
|
|
76
|
-
|
|
110
|
+
### Request Context
|
|
111
|
+
|
|
112
|
+
In web applications, use `RequestContext` to isolate the identity map per request:
|
|
77
113
|
|
|
78
114
|
```typescript
|
|
79
|
-
const
|
|
80
|
-
|
|
115
|
+
const app = express();
|
|
116
|
+
|
|
117
|
+
app.use((req, res, next) => {
|
|
118
|
+
RequestContext.create(orm.em, next);
|
|
119
|
+
});
|
|
81
120
|
```
|
|
82
121
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
122
|
+
More info about `RequestContext` is described [here](https://mikro-orm.io/docs/identity-map/#request-context).
|
|
123
|
+
|
|
124
|
+
## Unit of Work
|
|
125
|
+
|
|
126
|
+
> Unit of Work maintains a list of objects (_entities_) affected by a business transaction
|
|
127
|
+
> and coordinates the writing out of changes. [(Martin Fowler)](https://www.martinfowler.com/eaaCatalog/unitOfWork.html)
|
|
128
|
+
|
|
129
|
+
When you call `em.flush()`, all computed changes are queried inside a database transaction. This means you can control transaction boundaries simply by making changes to your entities and calling `flush()` when ready.
|
|
87
130
|
|
|
88
131
|
```typescript
|
|
89
|
-
const
|
|
90
|
-
populate: ['
|
|
132
|
+
const author = await em.findOneOrFail(Author, 1, {
|
|
133
|
+
populate: ['books'],
|
|
91
134
|
});
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
const car = new Car('VW');
|
|
96
|
-
user.cars.add(car);
|
|
135
|
+
author.name = 'Jon Snow II';
|
|
136
|
+
author.books.getItems().forEach(book => book.title += ' (2nd ed.)');
|
|
137
|
+
author.books.add(orm.em.create(Book, { title: 'New Book', author }));
|
|
97
138
|
|
|
98
|
-
//
|
|
139
|
+
// Flush computes change sets and executes them in a single transaction
|
|
99
140
|
await em.flush();
|
|
100
141
|
```
|
|
101
142
|
|
|
102
|
-
|
|
143
|
+
The above flush will execute:
|
|
103
144
|
|
|
104
145
|
```sql
|
|
105
146
|
begin;
|
|
106
|
-
update "
|
|
107
|
-
update "
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
when ("id" =
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
where "id" in (1, 2, 3)
|
|
115
|
-
insert into "car" ("brand", "owner") values ('VW', 1);
|
|
147
|
+
update "author" set "name" = 'Jon Snow II' where "id" = 1;
|
|
148
|
+
update "book"
|
|
149
|
+
set "title" = case
|
|
150
|
+
when ("id" = 1) then 'My Life on The Wall (2nd ed.)'
|
|
151
|
+
when ("id" = 2) then 'Another Book (2nd ed.)'
|
|
152
|
+
else "title" end
|
|
153
|
+
where "id" in (1, 2);
|
|
154
|
+
insert into "book" ("title", "author_id") values ('New Book', 1);
|
|
116
155
|
commit;
|
|
117
156
|
```
|
|
118
157
|
|
|
119
|
-
|
|
158
|
+
## Core Features
|
|
120
159
|
|
|
121
|
-
|
|
160
|
+
- [Clean and Simple Entity Definition](https://mikro-orm.io/docs/defining-entities) — decorators, `EntitySchema`, or `defineEntity`
|
|
161
|
+
- [Identity Map](https://mikro-orm.io/docs/identity-map) and [Unit of Work](https://mikro-orm.io/docs/unit-of-work) — automatic change tracking
|
|
162
|
+
- [Entity References](https://mikro-orm.io/docs/entity-references) and [Collections](https://mikro-orm.io/docs/collections)
|
|
163
|
+
- [QueryBuilder](https://mikro-orm.io/docs/query-builder) and [Kysely Integration](https://mikro-orm.io/docs/kysely)
|
|
164
|
+
- [Transactions](https://mikro-orm.io/docs/transactions) and [Cascading](https://mikro-orm.io/docs/cascading)
|
|
165
|
+
- [Populating Relations](https://mikro-orm.io/docs/populating-relations) and [Loading Strategies](https://mikro-orm.io/docs/loading-strategies)
|
|
166
|
+
- [Filters](https://mikro-orm.io/docs/filters) and [Lifecycle Hooks](https://mikro-orm.io/docs/events#hooks)
|
|
167
|
+
- [Schema Generator](https://mikro-orm.io/docs/schema-generator) and [Migrations](https://mikro-orm.io/docs/migrations)
|
|
168
|
+
- [Entity Generator](https://mikro-orm.io/docs/entity-generator) and [Seeding](https://mikro-orm.io/docs/seeding)
|
|
169
|
+
- [Embeddables](https://mikro-orm.io/docs/embeddables), [Custom Types](https://mikro-orm.io/docs/custom-types), and [Serialization](https://mikro-orm.io/docs/serializing)
|
|
170
|
+
- [Composite and Foreign Keys as Primary Key](https://mikro-orm.io/docs/composite-keys)
|
|
171
|
+
- [Entity Constructors](https://mikro-orm.io/docs/entity-constructors) and [Property Validation](https://mikro-orm.io/docs/property-validation)
|
|
172
|
+
- [Modelling Relationships](https://mikro-orm.io/docs/relationships) and [Vanilla JS Support](https://mikro-orm.io/docs/usage-with-js)
|
|
122
173
|
|
|
123
|
-
##
|
|
174
|
+
## Documentation
|
|
124
175
|
|
|
125
176
|
MikroORM documentation, included in this repo in the root directory, is built with [Docusaurus](https://docusaurus.io) and publicly hosted on GitHub Pages at https://mikro-orm.io.
|
|
126
177
|
|
|
127
|
-
There is also auto-generated [CHANGELOG.md](CHANGELOG.md) file based on commit messages (via `semantic-release`).
|
|
128
|
-
|
|
129
|
-
## ✨ Core Features
|
|
130
|
-
|
|
131
|
-
- [Clean and Simple Entity Definition](https://mikro-orm.io/docs/defining-entities)
|
|
132
|
-
- [Identity Map](https://mikro-orm.io/docs/identity-map)
|
|
133
|
-
- [Entity References](https://mikro-orm.io/docs/entity-references)
|
|
134
|
-
- [Using Entity Constructors](https://mikro-orm.io/docs/entity-constructors)
|
|
135
|
-
- [Modelling Relationships](https://mikro-orm.io/docs/relationships)
|
|
136
|
-
- [Collections](https://mikro-orm.io/docs/collections)
|
|
137
|
-
- [Unit of Work](https://mikro-orm.io/docs/unit-of-work)
|
|
138
|
-
- [Transactions](https://mikro-orm.io/docs/transactions)
|
|
139
|
-
- [Cascading persist and remove](https://mikro-orm.io/docs/cascading)
|
|
140
|
-
- [Composite and Foreign Keys as Primary Key](https://mikro-orm.io/docs/composite-keys)
|
|
141
|
-
- [Filters](https://mikro-orm.io/docs/filters)
|
|
142
|
-
- [Using `QueryBuilder`](https://mikro-orm.io/docs/query-builder)
|
|
143
|
-
- [Populating relations](https://mikro-orm.io/docs/populating-relations)
|
|
144
|
-
- [Property Validation](https://mikro-orm.io/docs/property-validation)
|
|
145
|
-
- [Lifecycle Hooks](https://mikro-orm.io/docs/events#hooks)
|
|
146
|
-
- [Vanilla JS Support](https://mikro-orm.io/docs/usage-with-js)
|
|
147
|
-
- [Schema Generator](https://mikro-orm.io/docs/schema-generator)
|
|
148
|
-
- [Entity Generator](https://mikro-orm.io/docs/entity-generator)
|
|
178
|
+
There is also auto-generated [CHANGELOG.md](CHANGELOG.md) file based on commit messages (via `semantic-release`).
|
|
149
179
|
|
|
150
|
-
##
|
|
180
|
+
## Example Integrations
|
|
151
181
|
|
|
152
|
-
You can find example integrations for some popular frameworks in the [`mikro-orm-examples` repository](https://github.com/mikro-orm/mikro-orm-examples):
|
|
182
|
+
You can find example integrations for some popular frameworks in the [`mikro-orm-examples` repository](https://github.com/mikro-orm/mikro-orm-examples):
|
|
153
183
|
|
|
154
184
|
### TypeScript Examples
|
|
155
185
|
|
|
@@ -165,213 +195,17 @@ You can find example integrations for some popular frameworks in the [`mikro-orm
|
|
|
165
195
|
- [Elysia.js + libSQL + Bun](https://github.com/mikro-orm/elysia-bun-example-app)
|
|
166
196
|
- [Electron.js + PostgreSQL](https://github.com/adnanlah/electron-mikro-orm-example-app)
|
|
167
197
|
|
|
168
|
-
### JavaScript Examples
|
|
198
|
+
### JavaScript Examples
|
|
169
199
|
|
|
170
200
|
- [Express + SQLite](https://github.com/mikro-orm/express-js-example-app)
|
|
171
201
|
|
|
172
|
-
##
|
|
173
|
-
|
|
174
|
-
First install the module via `yarn` or `npm` and do not forget to install the database driver as well:
|
|
175
|
-
|
|
176
|
-
> Since v4, you should install the driver package, but not the db connector itself, e.g. install `@mikro-orm/sqlite`, but not `sqlite3` as that is already included in the driver package.
|
|
177
|
-
|
|
178
|
-
```sh
|
|
179
|
-
yarn add @mikro-orm/core @mikro-orm/mongodb # for mongo
|
|
180
|
-
yarn add @mikro-orm/core @mikro-orm/mysql # for mysql/mariadb
|
|
181
|
-
yarn add @mikro-orm/core @mikro-orm/mariadb # for mysql/mariadb
|
|
182
|
-
yarn add @mikro-orm/core @mikro-orm/postgresql # for postgresql
|
|
183
|
-
yarn add @mikro-orm/core @mikro-orm/mssql # for mssql
|
|
184
|
-
yarn add @mikro-orm/core @mikro-orm/oracledb # for oracle
|
|
185
|
-
yarn add @mikro-orm/core @mikro-orm/sqlite # for sqlite
|
|
186
|
-
yarn add @mikro-orm/core @mikro-orm/libsql # for libsql
|
|
187
|
-
```
|
|
188
|
-
|
|
189
|
-
or
|
|
190
|
-
|
|
191
|
-
```sh
|
|
192
|
-
npm i -s @mikro-orm/core @mikro-orm/mongodb # for mongo
|
|
193
|
-
npm i -s @mikro-orm/core @mikro-orm/mysql # for mysql/mariadb
|
|
194
|
-
npm i -s @mikro-orm/core @mikro-orm/mariadb # for mysql/mariadb
|
|
195
|
-
npm i -s @mikro-orm/core @mikro-orm/postgresql # for postgresql
|
|
196
|
-
npm i -s @mikro-orm/core @mikro-orm/mssql # for mssql
|
|
197
|
-
npm i -s @mikro-orm/core @mikro-orm/sqlite # for sqlite
|
|
198
|
-
npm i -s @mikro-orm/core @mikro-orm/libsql # for libsql
|
|
199
|
-
```
|
|
200
|
-
|
|
201
|
-
Next, if you want to use decorators for your entity definition, you will need to enable support for [decorators](https://www.typescriptlang.org/docs/handbook/decorators.html) as well as `esModuleInterop` in `tsconfig.json` via:
|
|
202
|
-
|
|
203
|
-
```json
|
|
204
|
-
"experimentalDecorators": true,
|
|
205
|
-
"emitDecoratorMetadata": true,
|
|
206
|
-
"esModuleInterop": true,
|
|
207
|
-
```
|
|
208
|
-
|
|
209
|
-
Alternatively, you can use [`EntitySchema`](https://mikro-orm.io/docs/entity-schema).
|
|
210
|
-
|
|
211
|
-
Then call `MikroORM.init` as part of bootstrapping your app:
|
|
212
|
-
|
|
213
|
-
> To access driver specific methods like `em.createQueryBuilder()` we need to specify the driver type when calling `MikroORM.init()`. Alternatively we can cast the `orm.em` to `EntityManager` exported from the driver package:
|
|
214
|
-
>
|
|
215
|
-
> ```ts
|
|
216
|
-
> import { EntityManager } from '@mikro-orm/postgresql';
|
|
217
|
-
> const em = orm.em as EntityManager;
|
|
218
|
-
> const qb = em.createQueryBuilder(...);
|
|
219
|
-
> ```
|
|
220
|
-
|
|
221
|
-
```typescript
|
|
222
|
-
import type { PostgreSqlDriver } from '@mikro-orm/postgresql'; // or any other SQL driver package
|
|
223
|
-
|
|
224
|
-
const orm = await MikroORM.init<PostgreSqlDriver>({
|
|
225
|
-
entities: ['./dist/entities'], // path to your JS entities (dist), relative to `baseDir`
|
|
226
|
-
dbName: 'my-db-name',
|
|
227
|
-
type: 'postgresql',
|
|
228
|
-
});
|
|
229
|
-
console.log(orm.em); // access EntityManager via `em` property
|
|
230
|
-
```
|
|
231
|
-
|
|
232
|
-
There are more ways to configure your entities, take a look at [installation page](https://mikro-orm.io/docs/installation/).
|
|
233
|
-
|
|
234
|
-
> Read more about all the possible configuration options in [Advanced Configuration](https://mikro-orm.io/docs/configuration) section.
|
|
235
|
-
|
|
236
|
-
Then you will need to fork entity manager for each request so their [identity maps](https://mikro-orm.io/docs/identity-map/) will not collide. To do so, use the `RequestContext` helper:
|
|
237
|
-
|
|
238
|
-
```typescript
|
|
239
|
-
const app = express();
|
|
240
|
-
|
|
241
|
-
app.use((req, res, next) => {
|
|
242
|
-
RequestContext.create(orm.em, next);
|
|
243
|
-
});
|
|
244
|
-
```
|
|
245
|
-
|
|
246
|
-
> You should register this middleware as the last one just before request handlers and before any of your custom middleware that is using the ORM. There might be issues when you register it before request processing middleware like `queryParser` or `bodyParser`, so definitely register the context after them.
|
|
247
|
-
|
|
248
|
-
More info about `RequestContext` is described [here](https://mikro-orm.io/docs/identity-map/#request-context).
|
|
249
|
-
|
|
250
|
-
Now you can start defining your entities (in one of the `entities` folders). This is how simple entity can look like in mongo driver:
|
|
251
|
-
|
|
252
|
-
**`./entities/MongoBook.ts`**
|
|
253
|
-
|
|
254
|
-
```typescript
|
|
255
|
-
@Entity()
|
|
256
|
-
export class MongoBook {
|
|
257
|
-
|
|
258
|
-
@PrimaryKey()
|
|
259
|
-
_id: ObjectID;
|
|
260
|
-
|
|
261
|
-
@SerializedPrimaryKey()
|
|
262
|
-
id: string;
|
|
263
|
-
|
|
264
|
-
@Property()
|
|
265
|
-
title: string;
|
|
266
|
-
|
|
267
|
-
@ManyToOne(() => Author)
|
|
268
|
-
author: Author;
|
|
269
|
-
|
|
270
|
-
@ManyToMany(() => BookTag)
|
|
271
|
-
tags = new Collection<BookTag>(this);
|
|
272
|
-
|
|
273
|
-
constructor(title: string, author: Author) {
|
|
274
|
-
this.title = title;
|
|
275
|
-
this.author = author;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
}
|
|
279
|
-
```
|
|
280
|
-
|
|
281
|
-
For SQL drivers, you can use `id: number` PK:
|
|
282
|
-
|
|
283
|
-
**`./entities/SqlBook.ts`**
|
|
284
|
-
|
|
285
|
-
```typescript
|
|
286
|
-
@Entity()
|
|
287
|
-
export class SqlBook {
|
|
288
|
-
|
|
289
|
-
@PrimaryKey()
|
|
290
|
-
id: number;
|
|
291
|
-
|
|
292
|
-
}
|
|
293
|
-
```
|
|
294
|
-
|
|
295
|
-
Or if you want to use UUID primary keys:
|
|
296
|
-
|
|
297
|
-
**`./entities/UuidBook.ts`**
|
|
298
|
-
|
|
299
|
-
```typescript
|
|
300
|
-
import { randomUUID } from 'node:crypto';
|
|
301
|
-
|
|
302
|
-
@Entity()
|
|
303
|
-
export class UuidBook {
|
|
304
|
-
|
|
305
|
-
@PrimaryKey()
|
|
306
|
-
uuid = randomUUID();
|
|
307
|
-
|
|
308
|
-
}
|
|
309
|
-
```
|
|
310
|
-
|
|
311
|
-
More information can be found in [defining entities section](https://mikro-orm.io/docs/defining-entities/) in docs.
|
|
312
|
-
|
|
313
|
-
When you have your entities defined, you can start using ORM either via `EntityManager` or via `EntityRepository`s.
|
|
314
|
-
|
|
315
|
-
To save entity state to database, you need to persist it. Persist takes care or deciding whether to use `insert` or `update` and computes appropriate change-set. Entity references that are not persisted yet (does not have identifier) will be cascade persisted automatically.
|
|
316
|
-
|
|
317
|
-
```typescript
|
|
318
|
-
// use constructors in your entities for required parameters
|
|
319
|
-
const author = new Author('Jon Snow', 'snow@wall.st');
|
|
320
|
-
author.born = new Date();
|
|
321
|
-
|
|
322
|
-
const publisher = new Publisher('7K publisher');
|
|
323
|
-
|
|
324
|
-
const book1 = new Book('My Life on The Wall, part 1', author);
|
|
325
|
-
book1.publisher = publisher;
|
|
326
|
-
const book2 = new Book('My Life on The Wall, part 2', author);
|
|
327
|
-
book2.publisher = publisher;
|
|
328
|
-
const book3 = new Book('My Life on The Wall, part 3', author);
|
|
329
|
-
book3.publisher = publisher;
|
|
330
|
-
|
|
331
|
-
// just persist books, author and publisher will be automatically cascade persisted
|
|
332
|
-
await em.persistAndFlush([book1, book2, book3]);
|
|
333
|
-
```
|
|
334
|
-
|
|
335
|
-
To fetch entities from database you can use `find()` and `findOne()` of `EntityManager`:
|
|
336
|
-
|
|
337
|
-
```typescript
|
|
338
|
-
const authors = em.find(Author, {}, { populate: ['books'] });
|
|
339
|
-
|
|
340
|
-
for (const author of authors) {
|
|
341
|
-
console.log(author); // instance of Author entity
|
|
342
|
-
console.log(author.name); // Jon Snow
|
|
343
|
-
|
|
344
|
-
for (const book of author.books) { // iterating books collection
|
|
345
|
-
console.log(book); // instance of Book entity
|
|
346
|
-
console.log(book.title); // My Life on The Wall, part 1/2/3
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
```
|
|
350
|
-
|
|
351
|
-
More convenient way of fetching entities from database is by using `EntityRepository`, that carries the entity name, so you do not have to pass it to every `find` and `findOne` calls:
|
|
352
|
-
|
|
353
|
-
```typescript
|
|
354
|
-
const booksRepository = em.getRepository(Book);
|
|
355
|
-
|
|
356
|
-
const books = await booksRepository.find({ author: '...' }, {
|
|
357
|
-
populate: ['author'],
|
|
358
|
-
limit: 1,
|
|
359
|
-
offset: 2,
|
|
360
|
-
orderBy: { title: QueryOrder.DESC },
|
|
361
|
-
});
|
|
362
|
-
|
|
363
|
-
console.log(books); // Loaded<Book, 'author'>[]
|
|
364
|
-
```
|
|
365
|
-
|
|
366
|
-
Take a look at docs about [working with `EntityManager`](https://mikro-orm.io/docs/entity-manager/) or [using `EntityRepository` instead](https://mikro-orm.io/docs/repositories/).
|
|
367
|
-
|
|
368
|
-
## 🤝 Contributing
|
|
202
|
+
## Contributing
|
|
369
203
|
|
|
370
204
|
Contributions, issues and feature requests are welcome. Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on the process for submitting pull requests to us.
|
|
371
205
|
|
|
372
206
|
## Authors
|
|
373
207
|
|
|
374
|
-
|
|
208
|
+
**Martin Adámek**
|
|
375
209
|
|
|
376
210
|
- Twitter: [@B4nan](https://twitter.com/B4nan)
|
|
377
211
|
- Github: [@b4nan](https://github.com/b4nan)
|
|
@@ -380,12 +214,12 @@ See also the list of contributors who [participated](https://github.com/mikro-or
|
|
|
380
214
|
|
|
381
215
|
## Show Your Support
|
|
382
216
|
|
|
383
|
-
Please
|
|
217
|
+
Please star this repository if this project helped you!
|
|
384
218
|
|
|
385
219
|
> If you'd like to support my open-source work, consider sponsoring me directly at [github.com/sponsors/b4nan](https://github.com/sponsors/b4nan).
|
|
386
220
|
|
|
387
|
-
##
|
|
221
|
+
## License
|
|
388
222
|
|
|
389
|
-
Copyright © 2018 [Martin Adámek](https://github.com/b4nan).
|
|
223
|
+
Copyright © 2018-present [Martin Adámek](https://github.com/b4nan).
|
|
390
224
|
|
|
391
225
|
This project is licensed under the MIT License - see the [LICENSE file](LICENSE) for details.
|
package/SqlEntityManager.d.ts
CHANGED
|
@@ -6,7 +6,9 @@ import type { SqlEntityRepository } from './SqlEntityRepository.js';
|
|
|
6
6
|
import type { Kysely } from 'kysely';
|
|
7
7
|
import type { InferClassEntityDB, InferKyselyDB } from './typings.js';
|
|
8
8
|
import { type MikroKyselyPluginOptions } from './plugin/index.js';
|
|
9
|
+
/** Options for `SqlEntityManager.getKysely()`. */
|
|
9
10
|
export interface GetKyselyOptions extends MikroKyselyPluginOptions {
|
|
11
|
+
/** Connection type to use (`'read'` or `'write'`). */
|
|
10
12
|
type?: ConnectionType;
|
|
11
13
|
}
|
|
12
14
|
/**
|
|
@@ -25,6 +27,7 @@ export declare class SqlEntityManager<Driver extends AbstractSqlDriver = Abstrac
|
|
|
25
27
|
* Returns configured Kysely instance.
|
|
26
28
|
*/
|
|
27
29
|
getKysely<TDB = undefined, TOptions extends GetKyselyOptions = GetKyselyOptions>(options?: TOptions): Kysely<TDB extends undefined ? InferKyselyDB<EntitiesFromManager<this>, TOptions> & InferClassEntityDB<AllEntitiesFromManager<this>, TOptions> : TDB>;
|
|
30
|
+
/** Executes a raw SQL query, using the current transaction context if available. */
|
|
28
31
|
execute<T extends QueryResult | EntityData<AnyEntity> | EntityData<AnyEntity>[] = EntityData<AnyEntity>[]>(query: string | NativeQueryBuilder | RawQueryFragment, params?: any[], method?: 'all' | 'get' | 'run', loggerContext?: LoggingOptions): Promise<T>;
|
|
29
32
|
getRepository<T extends object, U extends EntityRepository<T> = SqlEntityRepository<T>>(entityName: EntityName<T>): GetRepository<T, U>;
|
|
30
33
|
protected applyDiscriminatorCondition<Entity extends object>(entityName: EntityName<Entity>, where: FilterQuery<Entity>): FilterQuery<Entity>;
|
package/SqlEntityManager.js
CHANGED
|
@@ -31,6 +31,7 @@ export class SqlEntityManager extends EntityManager {
|
|
|
31
31
|
}
|
|
32
32
|
return kysely;
|
|
33
33
|
}
|
|
34
|
+
/** Executes a raw SQL query, using the current transaction context if available. */
|
|
34
35
|
async execute(query, params = [], method = 'all', loggerContext) {
|
|
35
36
|
return this.getDriver().execute(query, params, method, this.getContext(false).getTransactionContext(), loggerContext);
|
|
36
37
|
}
|
package/SqlEntityRepository.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { EntityRepository, type EntityName } from '@mikro-orm/core';
|
|
2
2
|
import type { SqlEntityManager } from './SqlEntityManager.js';
|
|
3
3
|
import type { QueryBuilder } from './query/QueryBuilder.js';
|
|
4
|
+
/** SQL-specific entity repository with QueryBuilder support. */
|
|
4
5
|
export declare class SqlEntityRepository<Entity extends object> extends EntityRepository<Entity> {
|
|
5
6
|
protected readonly em: SqlEntityManager;
|
|
6
7
|
constructor(em: SqlEntityManager, entityName: EntityName<Entity>);
|
package/SqlEntityRepository.js
CHANGED
|
@@ -260,7 +260,7 @@ export class SqliteSchemaHelper extends SchemaHelper {
|
|
|
260
260
|
* Extracts the SELECT part from a CREATE VIEW statement.
|
|
261
261
|
*/
|
|
262
262
|
extractViewDefinition(viewDefinition) {
|
|
263
|
-
const match = /create\s+view\s+[`"']?\w+[`"']?\s+as\s+(.*)/
|
|
263
|
+
const match = /create\s+view\s+[`"']?\w+[`"']?\s+as\s+(.*)/is.exec(viewDefinition);
|
|
264
264
|
/* v8 ignore next - fallback for non-standard view definitions */
|
|
265
265
|
return match ? match[1] : viewDefinition;
|
|
266
266
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mikro-orm/sql",
|
|
3
|
-
"version": "7.0.
|
|
3
|
+
"version": "7.0.3-dev.0",
|
|
4
4
|
"description": "TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"data-mapper",
|
|
@@ -47,13 +47,13 @@
|
|
|
47
47
|
"copy": "node ../../scripts/copy.mjs"
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
|
-
"kysely": "0.28.
|
|
50
|
+
"kysely": "0.28.12"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
|
-
"@mikro-orm/core": "^7.0.
|
|
53
|
+
"@mikro-orm/core": "^7.0.2"
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
56
|
-
"@mikro-orm/core": "7.0.
|
|
56
|
+
"@mikro-orm/core": "7.0.3-dev.0"
|
|
57
57
|
},
|
|
58
58
|
"engines": {
|
|
59
59
|
"node": ">= 22.17.0"
|
package/plugin/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type KyselyPlugin, type PluginTransformQueryArgs, type PluginTransformResultArgs, type QueryResult, type RootOperationNode, type UnknownRow } from 'kysely';
|
|
2
2
|
import type { SqlEntityManager } from '../SqlEntityManager.js';
|
|
3
|
+
/** Configuration options for the MikroKyselyPlugin. */
|
|
3
4
|
export interface MikroKyselyPluginOptions {
|
|
4
5
|
/**
|
|
5
6
|
* Use database table names ('table') or entity names ('entity') in queries.
|
|
@@ -32,6 +33,7 @@ export interface MikroKyselyPluginOptions {
|
|
|
32
33
|
*/
|
|
33
34
|
convertValues?: boolean;
|
|
34
35
|
}
|
|
36
|
+
/** Kysely plugin that transforms queries and results to use MikroORM entity/property naming conventions. */
|
|
35
37
|
export declare class MikroKyselyPlugin implements KyselyPlugin {
|
|
36
38
|
#private;
|
|
37
39
|
constructor(em: SqlEntityManager, options?: MikroKyselyPluginOptions);
|
package/plugin/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { SelectQueryNode as SelectQueryNodeClass, InsertQueryNode as InsertQueryNodeClass, UpdateQueryNode as UpdateQueryNodeClass, DeleteQueryNode as DeleteQueryNodeClass, } from 'kysely';
|
|
2
2
|
import { MikroTransformer } from './transformer.js';
|
|
3
|
+
/** Kysely plugin that transforms queries and results to use MikroORM entity/property naming conventions. */
|
|
3
4
|
export class MikroKyselyPlugin {
|
|
4
5
|
static #queryNodeCache = new WeakMap();
|
|
5
6
|
#transformer;
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { type Dictionary, LockMode, type QueryFlag, RawQueryFragment, type Subquery } from '@mikro-orm/core';
|
|
2
2
|
import { QueryType } from './enums.js';
|
|
3
3
|
import type { AbstractSqlPlatform } from '../AbstractSqlPlatform.js';
|
|
4
|
+
/** Options for Common Table Expression (CTE) definitions. */
|
|
4
5
|
export interface CteOptions {
|
|
6
|
+
/** Column names for the CTE. */
|
|
5
7
|
columns?: string[];
|
|
6
8
|
/** PostgreSQL: MATERIALIZED / NOT MATERIALIZED */
|
|
7
9
|
materialized?: boolean;
|
|
@@ -45,6 +47,7 @@ interface Options {
|
|
|
45
47
|
wrap?: [prefix: string, suffix: string];
|
|
46
48
|
ctes?: CteClause[];
|
|
47
49
|
}
|
|
50
|
+
/** Options for specifying the target table in FROM/INTO clauses. */
|
|
48
51
|
export interface TableOptions {
|
|
49
52
|
schema?: string;
|
|
50
53
|
indexHint?: string;
|
package/query/enums.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/** Type of SQL query to be generated. */
|
|
1
2
|
export declare enum QueryType {
|
|
2
3
|
TRUNCATE = "TRUNCATE",
|
|
3
4
|
SELECT = "SELECT",
|
|
@@ -9,6 +10,7 @@ export declare enum QueryType {
|
|
|
9
10
|
}
|
|
10
11
|
/** Operators that apply to the embedded array column itself, not to individual elements. */
|
|
11
12
|
export declare const EMBEDDABLE_ARRAY_OPS: string[];
|
|
13
|
+
/** Type of SQL JOIN clause. */
|
|
12
14
|
export declare enum JoinType {
|
|
13
15
|
leftJoin = "left join",
|
|
14
16
|
innerJoin = "inner join",
|
package/query/enums.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/** Type of SQL query to be generated. */
|
|
1
2
|
export var QueryType;
|
|
2
3
|
(function (QueryType) {
|
|
3
4
|
QueryType["TRUNCATE"] = "TRUNCATE";
|
|
@@ -10,6 +11,7 @@ export var QueryType;
|
|
|
10
11
|
})(QueryType || (QueryType = {}));
|
|
11
12
|
/** Operators that apply to the embedded array column itself, not to individual elements. */
|
|
12
13
|
export const EMBEDDABLE_ARRAY_OPS = ['$contains', '$contained', '$overlap'];
|
|
14
|
+
/** Type of SQL JOIN clause. */
|
|
13
15
|
export var JoinType;
|
|
14
16
|
(function (JoinType) {
|
|
15
17
|
JoinType["leftJoin"] = "left join";
|
package/schema/SchemaHelper.d.ts
CHANGED
|
@@ -4,12 +4,17 @@ import type { AbstractSqlPlatform } from '../AbstractSqlPlatform.js';
|
|
|
4
4
|
import type { CheckDef, Column, ForeignKey, IndexDef, Table, TableDifference } from '../typings.js';
|
|
5
5
|
import type { DatabaseSchema } from './DatabaseSchema.js';
|
|
6
6
|
import type { DatabaseTable } from './DatabaseTable.js';
|
|
7
|
+
/** Base class for database-specific schema helpers. Provides SQL generation for DDL operations. */
|
|
7
8
|
export declare abstract class SchemaHelper {
|
|
8
9
|
protected readonly platform: AbstractSqlPlatform;
|
|
9
10
|
constructor(platform: AbstractSqlPlatform);
|
|
11
|
+
/** Returns SQL to prepend to schema migration scripts (e.g., disabling FK checks). */
|
|
10
12
|
getSchemaBeginning(_charset: string, disableForeignKeys?: boolean): string;
|
|
13
|
+
/** Returns SQL to disable foreign key checks. */
|
|
11
14
|
disableForeignKeysSQL(): string;
|
|
15
|
+
/** Returns SQL to re-enable foreign key checks. */
|
|
12
16
|
enableForeignKeysSQL(): string;
|
|
17
|
+
/** Returns SQL to append to schema migration scripts (e.g., re-enabling FK checks). */
|
|
13
18
|
getSchemaEnd(disableForeignKeys?: boolean): string;
|
|
14
19
|
finalizeTable(table: DatabaseTable, charset: string, collate?: string): string;
|
|
15
20
|
appendComments(table: DatabaseTable): string[];
|
|
@@ -20,12 +25,17 @@ export declare abstract class SchemaHelper {
|
|
|
20
25
|
getCreateNativeEnumSQL(name: string, values: unknown[], schema?: string): string;
|
|
21
26
|
getDropNativeEnumSQL(name: string, schema?: string): string;
|
|
22
27
|
getAlterNativeEnumSQL(name: string, schema?: string, value?: string, items?: string[], oldItems?: string[]): string;
|
|
28
|
+
/** Loads table metadata (columns, indexes, foreign keys) from the database information schema. */
|
|
23
29
|
abstract loadInformationSchema(schema: DatabaseSchema, connection: AbstractSqlConnection, tables: Table[], schemas?: string[]): Promise<void>;
|
|
30
|
+
/** Returns the SQL query to list all tables in the database. */
|
|
24
31
|
getListTablesSQL(): string;
|
|
32
|
+
/** Retrieves all tables from the database. */
|
|
25
33
|
getAllTables(connection: AbstractSqlConnection, schemas?: string[]): Promise<Table[]>;
|
|
26
34
|
getListViewsSQL(): string;
|
|
27
35
|
loadViews(schema: DatabaseSchema, connection: AbstractSqlConnection, schemaName?: string): Promise<void>;
|
|
36
|
+
/** Returns SQL to rename a column in a table. */
|
|
28
37
|
getRenameColumnSQL(tableName: string, oldColumnName: string, to: Column, schemaName?: string): string;
|
|
38
|
+
/** Returns SQL to create an index on a table. */
|
|
29
39
|
getCreateIndexSQL(tableName: string, index: IndexDef): string;
|
|
30
40
|
/**
|
|
31
41
|
* Hook for adding driver-specific index options (e.g., fill factor for PostgreSQL).
|
|
@@ -36,9 +46,12 @@ export declare abstract class SchemaHelper {
|
|
|
36
46
|
* Note: Prefix length is only supported by MySQL/MariaDB which override this method.
|
|
37
47
|
*/
|
|
38
48
|
protected getIndexColumns(index: IndexDef): string;
|
|
49
|
+
/** Returns SQL to drop an index. */
|
|
39
50
|
getDropIndexSQL(tableName: string, index: IndexDef): string;
|
|
40
51
|
getRenameIndexSQL(tableName: string, index: IndexDef, oldIndexName: string): string[];
|
|
52
|
+
/** Returns SQL statements to apply a table difference (add/drop/alter columns, indexes, foreign keys). */
|
|
41
53
|
alterTable(diff: TableDifference, safe?: boolean): string[];
|
|
54
|
+
/** Returns SQL to add columns to an existing table. */
|
|
42
55
|
getAddColumnsSQL(table: DatabaseTable, columns: Column[]): string[];
|
|
43
56
|
getDropColumnsSQL(tableName: string, columns: Column[], schemaName?: string): string;
|
|
44
57
|
hasNonDefaultPrimaryKeyName(table: DatabaseTable): boolean;
|
|
@@ -62,8 +75,10 @@ export declare abstract class SchemaHelper {
|
|
|
62
75
|
getDefaultEmptyString(): string;
|
|
63
76
|
databaseExists(connection: Connection, name: string): Promise<boolean>;
|
|
64
77
|
append(array: string[], sql: string | string[], pad?: boolean): void;
|
|
78
|
+
/** Returns SQL statements to create a table with all its columns, primary key, indexes, and checks. */
|
|
65
79
|
createTable(table: DatabaseTable, alter?: boolean): string[];
|
|
66
80
|
alterTableComment(table: DatabaseTable, comment?: string): string;
|
|
81
|
+
/** Returns SQL to create a foreign key constraint on a table. */
|
|
67
82
|
createForeignKey(table: DatabaseTable, foreignKey: ForeignKey, alterTable?: boolean, inline?: boolean): string;
|
|
68
83
|
splitTableName(name: string, skipDefaultSchema?: boolean): [string | undefined, string];
|
|
69
84
|
getReferencedTableName(referencedTableName: string, schema?: string): string;
|
|
@@ -77,6 +92,7 @@ export declare abstract class SchemaHelper {
|
|
|
77
92
|
dropForeignKey(tableName: string, constraintName: string): string;
|
|
78
93
|
dropIndex(table: string, index: IndexDef, oldIndexName?: string): string;
|
|
79
94
|
dropConstraint(table: string, name: string): string;
|
|
95
|
+
/** Returns SQL to drop a table if it exists. */
|
|
80
96
|
dropTableIfExists(name: string, schema?: string): string;
|
|
81
97
|
createView(name: string, schema: string | undefined, definition: string): string;
|
|
82
98
|
dropViewIfExists(name: string, schema?: string): string;
|
package/schema/SchemaHelper.js
CHANGED
|
@@ -1,21 +1,26 @@
|
|
|
1
1
|
import { RawQueryFragment, Utils } from '@mikro-orm/core';
|
|
2
|
+
/** Base class for database-specific schema helpers. Provides SQL generation for DDL operations. */
|
|
2
3
|
export class SchemaHelper {
|
|
3
4
|
platform;
|
|
4
5
|
constructor(platform) {
|
|
5
6
|
this.platform = platform;
|
|
6
7
|
}
|
|
8
|
+
/** Returns SQL to prepend to schema migration scripts (e.g., disabling FK checks). */
|
|
7
9
|
getSchemaBeginning(_charset, disableForeignKeys) {
|
|
8
10
|
if (disableForeignKeys) {
|
|
9
11
|
return `${this.disableForeignKeysSQL()}\n`;
|
|
10
12
|
}
|
|
11
13
|
return '';
|
|
12
14
|
}
|
|
15
|
+
/** Returns SQL to disable foreign key checks. */
|
|
13
16
|
disableForeignKeysSQL() {
|
|
14
17
|
return '';
|
|
15
18
|
}
|
|
19
|
+
/** Returns SQL to re-enable foreign key checks. */
|
|
16
20
|
enableForeignKeysSQL() {
|
|
17
21
|
return '';
|
|
18
22
|
}
|
|
23
|
+
/** Returns SQL to append to schema migration scripts (e.g., re-enabling FK checks). */
|
|
19
24
|
getSchemaEnd(disableForeignKeys) {
|
|
20
25
|
if (disableForeignKeys) {
|
|
21
26
|
return `${this.enableForeignKeysSQL()}\n`;
|
|
@@ -62,9 +67,11 @@ export class SchemaHelper {
|
|
|
62
67
|
getAlterNativeEnumSQL(name, schema, value, items, oldItems) {
|
|
63
68
|
throw new Error('Not supported by given driver');
|
|
64
69
|
}
|
|
70
|
+
/** Returns the SQL query to list all tables in the database. */
|
|
65
71
|
getListTablesSQL() {
|
|
66
72
|
throw new Error('Not supported by given driver');
|
|
67
73
|
}
|
|
74
|
+
/** Retrieves all tables from the database. */
|
|
68
75
|
async getAllTables(connection, schemas) {
|
|
69
76
|
return connection.execute(this.getListTablesSQL());
|
|
70
77
|
}
|
|
@@ -74,6 +81,7 @@ export class SchemaHelper {
|
|
|
74
81
|
async loadViews(schema, connection, schemaName) {
|
|
75
82
|
throw new Error('Not supported by given driver');
|
|
76
83
|
}
|
|
84
|
+
/** Returns SQL to rename a column in a table. */
|
|
77
85
|
getRenameColumnSQL(tableName, oldColumnName, to, schemaName) {
|
|
78
86
|
tableName = this.quote(tableName);
|
|
79
87
|
oldColumnName = this.quote(oldColumnName);
|
|
@@ -82,6 +90,7 @@ export class SchemaHelper {
|
|
|
82
90
|
const tableReference = schemaReference + tableName;
|
|
83
91
|
return `alter table ${tableReference} rename column ${oldColumnName} to ${columnName}`;
|
|
84
92
|
}
|
|
93
|
+
/** Returns SQL to create an index on a table. */
|
|
85
94
|
getCreateIndexSQL(tableName, index) {
|
|
86
95
|
/* v8 ignore next */
|
|
87
96
|
if (index.expression) {
|
|
@@ -145,6 +154,7 @@ export class SchemaHelper {
|
|
|
145
154
|
}
|
|
146
155
|
return index.columnNames.map(c => this.quote(c)).join(', ');
|
|
147
156
|
}
|
|
157
|
+
/** Returns SQL to drop an index. */
|
|
148
158
|
getDropIndexSQL(tableName, index) {
|
|
149
159
|
return `drop index ${this.quote(index.keyName)}`;
|
|
150
160
|
}
|
|
@@ -154,6 +164,7 @@ export class SchemaHelper {
|
|
|
154
164
|
this.getCreateIndexSQL(tableName, index),
|
|
155
165
|
];
|
|
156
166
|
}
|
|
167
|
+
/** Returns SQL statements to apply a table difference (add/drop/alter columns, indexes, foreign keys). */
|
|
157
168
|
alterTable(diff, safe) {
|
|
158
169
|
const ret = [];
|
|
159
170
|
const [schemaName, tableName] = this.splitTableName(diff.name);
|
|
@@ -257,6 +268,7 @@ export class SchemaHelper {
|
|
|
257
268
|
}
|
|
258
269
|
return ret;
|
|
259
270
|
}
|
|
271
|
+
/** Returns SQL to add columns to an existing table. */
|
|
260
272
|
getAddColumnsSQL(table, columns) {
|
|
261
273
|
const adds = columns
|
|
262
274
|
.map(column => {
|
|
@@ -472,6 +484,7 @@ export class SchemaHelper {
|
|
|
472
484
|
array.push('');
|
|
473
485
|
}
|
|
474
486
|
}
|
|
487
|
+
/** Returns SQL statements to create a table with all its columns, primary key, indexes, and checks. */
|
|
475
488
|
createTable(table, alter) {
|
|
476
489
|
let sql = `create table ${table.getQuotedName()} (`;
|
|
477
490
|
const columns = table.getColumns();
|
|
@@ -507,6 +520,7 @@ export class SchemaHelper {
|
|
|
507
520
|
alterTableComment(table, comment) {
|
|
508
521
|
return `alter table ${table.getQuotedName()} comment = ${this.platform.quoteValue(comment ?? '')}`;
|
|
509
522
|
}
|
|
523
|
+
/** Returns SQL to create a foreign key constraint on a table. */
|
|
510
524
|
createForeignKey(table, foreignKey, alterTable = true, inline = false) {
|
|
511
525
|
if (!this.options.createForeignKeyConstraints) {
|
|
512
526
|
return '';
|
|
@@ -617,6 +631,7 @@ export class SchemaHelper {
|
|
|
617
631
|
dropConstraint(table, name) {
|
|
618
632
|
return `alter table ${this.quote(table)} drop constraint ${this.quote(name)}`;
|
|
619
633
|
}
|
|
634
|
+
/** Returns SQL to drop a table if it exists. */
|
|
620
635
|
dropTableIfExists(name, schema) {
|
|
621
636
|
let sql = `drop table if exists ${this.quote(this.getTableName(name, schema))}`;
|
|
622
637
|
if (this.platform.usesCascadeStatement()) {
|
|
@@ -4,6 +4,7 @@ import type { SchemaDifference } from '../typings.js';
|
|
|
4
4
|
import { DatabaseSchema } from './DatabaseSchema.js';
|
|
5
5
|
import type { AbstractSqlDriver } from '../AbstractSqlDriver.js';
|
|
6
6
|
import type { SchemaHelper } from './SchemaHelper.js';
|
|
7
|
+
/** Generates and manages SQL database schemas based on entity metadata. Supports create, update, and drop operations. */
|
|
7
8
|
export declare class SqlSchemaGenerator extends AbstractSchemaGenerator<AbstractSqlDriver> implements ISchemaGenerator {
|
|
8
9
|
protected readonly helper: SchemaHelper;
|
|
9
10
|
protected readonly options: NonNullable<Options['schemaGenerator']>;
|
|
@@ -2,6 +2,7 @@ import { CommitOrderCalculator, TableNotFoundException, Utils, } from '@mikro-or
|
|
|
2
2
|
import { AbstractSchemaGenerator } from '@mikro-orm/core/schema';
|
|
3
3
|
import { DatabaseSchema } from './DatabaseSchema.js';
|
|
4
4
|
import { SchemaComparator } from './SchemaComparator.js';
|
|
5
|
+
/** Generates and manages SQL database schemas based on entity metadata. Supports create, update, and drop operations. */
|
|
5
6
|
export class SqlSchemaGenerator extends AbstractSchemaGenerator {
|
|
6
7
|
helper = this.platform.getSchemaHelper();
|
|
7
8
|
options = this.config.get('schemaGenerator');
|