@mikro-orm/mysql 7.0.2-dev.8 → 7.0.2

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.
@@ -1,8 +1,9 @@
1
1
  import { type ControlledTransaction, MysqlDialect } from 'kysely';
2
2
  import { type PoolOptions } from 'mysql2';
3
3
  import { AbstractSqlConnection, type TransactionEventBroadcaster } from '@mikro-orm/sql';
4
+ /** MySQL database connection using the `mysql2` driver. */
4
5
  export declare class MySqlConnection extends AbstractSqlConnection {
5
- createKyselyDialect(overrides: PoolOptions): MysqlDialect;
6
- mapOptions(overrides: PoolOptions): PoolOptions;
7
- commit(ctx: ControlledTransaction<any, any>, eventBroadcaster?: TransactionEventBroadcaster): Promise<void>;
6
+ createKyselyDialect(overrides: PoolOptions): MysqlDialect;
7
+ mapOptions(overrides: PoolOptions): PoolOptions;
8
+ commit(ctx: ControlledTransaction<any, any>, eventBroadcaster?: TransactionEventBroadcaster): Promise<void>;
8
9
  }
@@ -1,56 +1,57 @@
1
1
  import { MysqlDialect } from 'kysely';
2
2
  import { createPool } from 'mysql2';
3
3
  import { Utils, AbstractSqlConnection } from '@mikro-orm/sql';
4
+ /** MySQL database connection using the `mysql2` driver. */
4
5
  export class MySqlConnection extends AbstractSqlConnection {
5
- createKyselyDialect(overrides) {
6
- const options = this.mapOptions(overrides);
7
- const password = options.password;
8
- if (typeof password === 'function') {
9
- return new MysqlDialect({
10
- pool: async () => createPool({
11
- ...options,
12
- password: await password(),
13
- }),
14
- onCreateConnection: this.options.onCreateConnection ?? this.config.get('onCreateConnection'),
15
- });
16
- }
17
- return new MysqlDialect({
18
- pool: createPool(options),
19
- onCreateConnection: this.options.onCreateConnection ?? this.config.get('onCreateConnection'),
20
- });
6
+ createKyselyDialect(overrides) {
7
+ const options = this.mapOptions(overrides);
8
+ const password = options.password;
9
+ if (typeof password === 'function') {
10
+ return new MysqlDialect({
11
+ pool: async () =>
12
+ createPool({
13
+ ...options,
14
+ password: await password(),
15
+ }),
16
+ onCreateConnection: this.options.onCreateConnection ?? this.config.get('onCreateConnection'),
17
+ });
21
18
  }
22
- mapOptions(overrides) {
23
- const ret = { ...this.getConnectionOptions() };
24
- const pool = this.config.get('pool');
25
- ret.connectionLimit = pool?.max;
26
- ret.idleTimeout = pool?.idleTimeoutMillis;
27
- if (this.config.get('multipleStatements')) {
28
- ret.multipleStatements = this.config.get('multipleStatements');
29
- }
30
- if (this.config.get('forceUtcTimezone')) {
31
- ret.timezone = 'Z';
32
- }
33
- if (this.config.get('timezone')) {
34
- ret.timezone = this.config.get('timezone');
35
- }
36
- ret.supportBigNumbers = true;
37
- ret.dateStrings = true;
38
- return Utils.mergeConfig(ret, overrides);
19
+ return new MysqlDialect({
20
+ pool: createPool(options),
21
+ onCreateConnection: this.options.onCreateConnection ?? this.config.get('onCreateConnection'),
22
+ });
23
+ }
24
+ mapOptions(overrides) {
25
+ const ret = { ...this.getConnectionOptions() };
26
+ const pool = this.config.get('pool');
27
+ ret.connectionLimit = pool?.max;
28
+ ret.idleTimeout = pool?.idleTimeoutMillis;
29
+ if (this.config.get('multipleStatements')) {
30
+ ret.multipleStatements = this.config.get('multipleStatements');
31
+ }
32
+ if (this.config.get('forceUtcTimezone')) {
33
+ ret.timezone = 'Z';
34
+ }
35
+ if (this.config.get('timezone')) {
36
+ ret.timezone = this.config.get('timezone');
39
37
  }
40
- async commit(ctx, eventBroadcaster) {
41
- if (!ctx.isRolledBack && 'savepointName' in ctx) {
42
- try {
43
- await ctx.releaseSavepoint(ctx.savepointName).execute();
44
- }
45
- catch (e) {
46
- /* v8 ignore next */
47
- // https://github.com/knex/knex/issues/805
48
- if (e.errno !== 1305) {
49
- throw e;
50
- }
51
- }
52
- return this.logQuery(this.platform.getReleaseSavepointSQL(ctx.savepointName));
38
+ ret.supportBigNumbers = true;
39
+ ret.dateStrings = true;
40
+ return Utils.mergeConfig(ret, overrides);
41
+ }
42
+ async commit(ctx, eventBroadcaster) {
43
+ if (!ctx.isRolledBack && 'savepointName' in ctx) {
44
+ try {
45
+ await ctx.releaseSavepoint(ctx.savepointName).execute();
46
+ } catch (e) {
47
+ /* v8 ignore next */
48
+ // https://github.com/knex/knex/issues/805
49
+ if (e.errno !== 1305) {
50
+ throw e;
53
51
  }
54
- await super.commit(ctx, eventBroadcaster);
52
+ }
53
+ return this.logQuery(this.platform.getReleaseSavepointSQL(ctx.savepointName));
55
54
  }
55
+ await super.commit(ctx, eventBroadcaster);
56
+ }
56
57
  }
package/MySqlDriver.d.ts CHANGED
@@ -1,14 +1,33 @@
1
- import type { Configuration, Constructor, EntityDictionary, EntityName, FilterQuery, NativeInsertUpdateManyOptions, QueryResult, UpsertManyOptions } from '@mikro-orm/core';
1
+ import type {
2
+ Configuration,
3
+ Constructor,
4
+ EntityDictionary,
5
+ EntityName,
6
+ FilterQuery,
7
+ NativeInsertUpdateManyOptions,
8
+ QueryResult,
9
+ UpsertManyOptions,
10
+ } from '@mikro-orm/core';
2
11
  import { AbstractSqlDriver } from '@mikro-orm/sql';
3
12
  import { MySqlConnection } from './MySqlConnection.js';
4
13
  import { MySqlMikroORM } from './MySqlMikroORM.js';
5
14
  import { MySqlPlatform } from './MySqlPlatform.js';
15
+ /** Database driver for MySQL. */
6
16
  export declare class MySqlDriver extends AbstractSqlDriver<MySqlConnection, MySqlPlatform> {
7
- private autoIncrementIncrement?;
8
- constructor(config: Configuration);
9
- private getAutoIncrementIncrement;
10
- nativeInsertMany<T extends object>(entityName: EntityName<T>, data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T>): Promise<QueryResult<T>>;
11
- nativeUpdateMany<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>[], data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T> & UpsertManyOptions<T>): Promise<QueryResult<T>>;
12
- /** @inheritDoc */
13
- getORMClass(): Constructor<MySqlMikroORM>;
17
+ private autoIncrementIncrement?;
18
+ constructor(config: Configuration);
19
+ private getAutoIncrementIncrement;
20
+ nativeInsertMany<T extends object>(
21
+ entityName: EntityName<T>,
22
+ data: EntityDictionary<T>[],
23
+ options?: NativeInsertUpdateManyOptions<T>,
24
+ ): Promise<QueryResult<T>>;
25
+ nativeUpdateMany<T extends object>(
26
+ entityName: EntityName<T>,
27
+ where: FilterQuery<T>[],
28
+ data: EntityDictionary<T>[],
29
+ options?: NativeInsertUpdateManyOptions<T> & UpsertManyOptions<T>,
30
+ ): Promise<QueryResult<T>>;
31
+ /** @inheritDoc */
32
+ getORMClass(): Constructor<MySqlMikroORM>;
14
33
  }
package/MySqlDriver.js CHANGED
@@ -2,55 +2,60 @@ import { AbstractSqlDriver, Utils } from '@mikro-orm/sql';
2
2
  import { MySqlConnection } from './MySqlConnection.js';
3
3
  import { MySqlMikroORM } from './MySqlMikroORM.js';
4
4
  import { MySqlPlatform } from './MySqlPlatform.js';
5
+ /** Database driver for MySQL. */
5
6
  export class MySqlDriver extends AbstractSqlDriver {
6
- autoIncrementIncrement;
7
- constructor(config) {
8
- super(config, new MySqlPlatform(), MySqlConnection, ['kysely', 'mysql2']);
7
+ autoIncrementIncrement;
8
+ constructor(config) {
9
+ super(config, new MySqlPlatform(), MySqlConnection, ['kysely', 'mysql2']);
10
+ }
11
+ async getAutoIncrementIncrement(ctx) {
12
+ if (this.autoIncrementIncrement == null) {
13
+ // the increment step may differ when running a cluster, see https://github.com/mikro-orm/mikro-orm/issues/3828
14
+ const res = await this.connection.execute(`show variables like 'auto_increment_increment'`, [], 'get', ctx, {
15
+ enabled: false,
16
+ });
17
+ /* v8 ignore next */
18
+ this.autoIncrementIncrement = res?.Value ? +res?.Value : 1;
9
19
  }
10
- async getAutoIncrementIncrement(ctx) {
11
- if (this.autoIncrementIncrement == null) {
12
- // the increment step may differ when running a cluster, see https://github.com/mikro-orm/mikro-orm/issues/3828
13
- const res = await this.connection.execute(`show variables like 'auto_increment_increment'`, [], 'get', ctx, { enabled: false });
14
- /* v8 ignore next */
15
- this.autoIncrementIncrement = res?.Value ? +res?.Value : 1;
16
- }
17
- return this.autoIncrementIncrement;
18
- }
19
- async nativeInsertMany(entityName, data, options = {}) {
20
- options.processCollections ??= true;
21
- const res = await super.nativeInsertMany(entityName, data, options);
22
- const meta = this.metadata.get(entityName);
23
- const pks = this.getPrimaryKeyFields(meta);
24
- const ctx = options.ctx;
25
- const autoIncrementIncrement = await this.getAutoIncrementIncrement(ctx);
26
- data.forEach((item, idx) => (res.rows[idx] = { [pks[0]]: item[pks[0]] ?? res.insertId + idx * autoIncrementIncrement }));
27
- res.row = res.rows[0];
28
- return res;
29
- }
30
- async nativeUpdateMany(entityName, where, data, options = {}) {
31
- const res = await super.nativeUpdateMany(entityName, where, data, options);
32
- const meta = this.metadata.get(entityName);
33
- const pks = this.getPrimaryKeyFields(meta);
34
- const ctx = options.ctx;
35
- const autoIncrementIncrement = await this.getAutoIncrementIncrement(ctx);
36
- let i = 0;
37
- const rows = where.map(cond => {
38
- if (res.insertId != null && Utils.isEmpty(cond)) {
39
- return { [pks[0]]: res.insertId + i++ * autoIncrementIncrement };
40
- }
41
- if (cond[pks[0]] == null) {
42
- return undefined;
43
- }
44
- return { [pks[0]]: cond[pks[0]] };
45
- });
46
- if (rows.every(i => i !== undefined)) {
47
- res.rows = rows;
48
- }
49
- res.row = res.rows[0];
50
- return res;
51
- }
52
- /** @inheritDoc */
53
- getORMClass() {
54
- return MySqlMikroORM;
20
+ return this.autoIncrementIncrement;
21
+ }
22
+ async nativeInsertMany(entityName, data, options = {}) {
23
+ options.processCollections ??= true;
24
+ const res = await super.nativeInsertMany(entityName, data, options);
25
+ const meta = this.metadata.get(entityName);
26
+ const pks = this.getPrimaryKeyFields(meta);
27
+ const ctx = options.ctx;
28
+ const autoIncrementIncrement = await this.getAutoIncrementIncrement(ctx);
29
+ data.forEach(
30
+ (item, idx) => (res.rows[idx] = { [pks[0]]: item[pks[0]] ?? res.insertId + idx * autoIncrementIncrement }),
31
+ );
32
+ res.row = res.rows[0];
33
+ return res;
34
+ }
35
+ async nativeUpdateMany(entityName, where, data, options = {}) {
36
+ const res = await super.nativeUpdateMany(entityName, where, data, options);
37
+ const meta = this.metadata.get(entityName);
38
+ const pks = this.getPrimaryKeyFields(meta);
39
+ const ctx = options.ctx;
40
+ const autoIncrementIncrement = await this.getAutoIncrementIncrement(ctx);
41
+ let i = 0;
42
+ const rows = where.map(cond => {
43
+ if (res.insertId != null && Utils.isEmpty(cond)) {
44
+ return { [pks[0]]: res.insertId + i++ * autoIncrementIncrement };
45
+ }
46
+ if (cond[pks[0]] == null) {
47
+ return undefined;
48
+ }
49
+ return { [pks[0]]: cond[pks[0]] };
50
+ });
51
+ if (rows.every(i => i !== undefined)) {
52
+ res.rows = rows;
55
53
  }
54
+ res.row = res.rows[0];
55
+ return res;
56
+ }
57
+ /** @inheritDoc */
58
+ getORMClass() {
59
+ return MySqlMikroORM;
60
+ }
56
61
  }
@@ -1,18 +1,58 @@
1
- import { type AnyEntity, type EntityClass, type EntitySchema, MikroORM, type Options, type IDatabaseDriver, type EntityManager, type EntityManagerType } from '@mikro-orm/core';
1
+ import {
2
+ type AnyEntity,
3
+ type EntityClass,
4
+ type EntitySchema,
5
+ MikroORM,
6
+ type Options,
7
+ type IDatabaseDriver,
8
+ type EntityManager,
9
+ type EntityManagerType,
10
+ } from '@mikro-orm/core';
2
11
  import type { SqlEntityManager } from '@mikro-orm/sql';
3
12
  import { MySqlDriver } from './MySqlDriver.js';
4
- export type MySqlOptions<EM extends SqlEntityManager<MySqlDriver> = SqlEntityManager<MySqlDriver>, Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]> = Partial<Options<MySqlDriver, EM, Entities>>;
5
- export declare function defineMySqlConfig<EM extends SqlEntityManager<MySqlDriver> = SqlEntityManager<MySqlDriver>, Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]>(options: Partial<Options<MySqlDriver, EM, Entities>>): Partial<Options<MySqlDriver, EM, Entities>>;
13
+ /** Configuration options for the MySQL driver. */
14
+ export type MySqlOptions<
15
+ EM extends SqlEntityManager<MySqlDriver> = SqlEntityManager<MySqlDriver>,
16
+ Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (
17
+ | string
18
+ | EntityClass<AnyEntity>
19
+ | EntitySchema
20
+ )[],
21
+ > = Partial<Options<MySqlDriver, EM, Entities>>;
22
+ /** Creates a type-safe configuration object for the MySQL driver. */
23
+ export declare function defineMySqlConfig<
24
+ EM extends SqlEntityManager<MySqlDriver> = SqlEntityManager<MySqlDriver>,
25
+ Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (
26
+ | string
27
+ | EntityClass<AnyEntity>
28
+ | EntitySchema
29
+ )[],
30
+ >(options: Partial<Options<MySqlDriver, EM, Entities>>): Partial<Options<MySqlDriver, EM, Entities>>;
6
31
  /**
7
32
  * @inheritDoc
8
33
  */
9
- export declare class MySqlMikroORM<EM extends SqlEntityManager<MySqlDriver> = SqlEntityManager<MySqlDriver>, Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]> extends MikroORM<MySqlDriver, EM, Entities> {
10
- /**
11
- * @inheritDoc
12
- */
13
- static init<D extends IDatabaseDriver = MySqlDriver, EM extends EntityManager<D> = D[typeof EntityManagerType] & EntityManager<D>, Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]>(options: Partial<Options<D, EM, Entities>>): Promise<MikroORM<D, EM, Entities>>;
14
- /**
15
- * @inheritDoc
16
- */
17
- constructor(options: Partial<Options<MySqlDriver, EM, Entities>>);
34
+ export declare class MySqlMikroORM<
35
+ EM extends SqlEntityManager<MySqlDriver> = SqlEntityManager<MySqlDriver>,
36
+ Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (
37
+ | string
38
+ | EntityClass<AnyEntity>
39
+ | EntitySchema
40
+ )[],
41
+ > extends MikroORM<MySqlDriver, EM, Entities> {
42
+ /**
43
+ * @inheritDoc
44
+ */
45
+ static init<
46
+ D extends IDatabaseDriver = MySqlDriver,
47
+ EM extends EntityManager<D> = D[typeof EntityManagerType] & EntityManager<D>,
48
+ Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (
49
+ | string
50
+ | EntityClass<AnyEntity>
51
+ | EntitySchema
52
+ )[],
53
+ >(options: Partial<Options<D, EM, Entities>>): Promise<MikroORM<D, EM, Entities>>;
54
+ /**
55
+ * @inheritDoc
56
+ */
57
+ constructor(options: Partial<Options<MySqlDriver, EM, Entities>>);
18
58
  }
package/MySqlMikroORM.js CHANGED
@@ -1,22 +1,23 @@
1
- import { defineConfig, MikroORM, } from '@mikro-orm/core';
1
+ import { defineConfig, MikroORM } from '@mikro-orm/core';
2
2
  import { MySqlDriver } from './MySqlDriver.js';
3
+ /** Creates a type-safe configuration object for the MySQL driver. */
3
4
  export function defineMySqlConfig(options) {
4
- return defineConfig({ driver: MySqlDriver, ...options });
5
+ return defineConfig({ driver: MySqlDriver, ...options });
5
6
  }
6
7
  /**
7
8
  * @inheritDoc
8
9
  */
9
10
  export class MySqlMikroORM extends MikroORM {
10
- /**
11
- * @inheritDoc
12
- */
13
- static async init(options) {
14
- return super.init(defineMySqlConfig(options));
15
- }
16
- /**
17
- * @inheritDoc
18
- */
19
- constructor(options) {
20
- super(defineMySqlConfig(options));
21
- }
11
+ /**
12
+ * @inheritDoc
13
+ */
14
+ static async init(options) {
15
+ return super.init(defineMySqlConfig(options));
16
+ }
17
+ /**
18
+ * @inheritDoc
19
+ */
20
+ constructor(options) {
21
+ super(defineMySqlConfig(options));
22
+ }
22
23
  }
@@ -1,4 +1,5 @@
1
1
  import { BaseMySqlPlatform } from '@mikro-orm/sql';
2
+ /** Platform implementation for MySQL. */
2
3
  export declare class MySqlPlatform extends BaseMySqlPlatform {
3
- escape(value: any): string;
4
+ escape(value: any): string;
4
5
  }
package/MySqlPlatform.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import SqlString from 'sqlstring';
2
2
  import { BaseMySqlPlatform } from '@mikro-orm/sql';
3
+ /** Platform implementation for MySQL. */
3
4
  export class MySqlPlatform extends BaseMySqlPlatform {
4
- escape(value) {
5
- return SqlString.escape(value, true, this.timezone);
6
- }
5
+ escape(value) {
6
+ return SqlString.escape(value, true, this.timezone);
7
+ }
7
8
  }
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
  [![Coverage Status](https://img.shields.io/coveralls/mikro-orm/mikro-orm.svg)](https://coveralls.io/r/mikro-orm/mikro-orm?branch=master)
14
14
  [![Build Status](https://github.com/mikro-orm/mikro-orm/workflows/tests/badge.svg?branch=master)](https://github.com/mikro-orm/mikro-orm/actions?workflow=tests)
15
15
 
16
- ## 🤔 Unit of What?
16
+ ## Quick Start
17
17
 
18
- You might be asking: _What the hell is Unit of Work and why should I care about it?_
18
+ Install a driver package for your database:
19
19
 
20
- > Unit of Work maintains a list of objects (_entities_) affected by a business transaction
21
- > and coordinates the writing out of changes. [(Martin Fowler)](https://www.martinfowler.com/eaaCatalog/unitOfWork.html)
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
- > Identity Map ensures that each object (_entity_) gets loaded only once by keeping every
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
- So what benefits does it bring to us?
33
+ ### Define Entities
28
34
 
29
- ### Implicit Transactions
35
+ The recommended way to define entities is using [`defineEntity`](https://mikro-orm.io/docs/define-entity) with `setClass`:
30
36
 
31
- First and most important implication of having Unit of Work is that it allows handling transactions automatically.
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
- When you call `em.flush()`, all computed changes are queried inside a database transaction (if supported by given driver). This means that you can control the boundaries of transactions simply by calling `em.persistLater()` and once all your changes are ready, calling `flush()` will run them inside a transaction.
51
+ export class Author extends AuthorSchema.class {}
52
+ AuthorSchema.setClass(Author);
34
53
 
35
- > You can also control the transaction boundaries manually via `em.transactional(cb)`.
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
- ```typescript
38
- const user = await em.findOneOrFail(User, 1);
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
- ### ChangeSet based persistence
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
- MikroORM allows you to implement your domain/business logic directly in the entities. To maintain always valid entities, you can use constructors to mark required properties. Let's define the `User` entity used in previous example:
69
+ ### Initialize and Use
52
70
 
53
71
  ```typescript
54
- @Entity()
55
- export class User {
72
+ import { MikroORM, RequestContext } from '@mikro-orm/postgresql';
56
73
 
57
- @PrimaryKey()
58
- id!: number;
74
+ const orm = await MikroORM.init({
75
+ entities: [Author, Book],
76
+ dbName: 'my-db',
77
+ });
59
78
 
60
- @Property()
61
- name!: string;
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
- @OneToOne(() => Address)
64
- address?: Address;
89
+ // Flush persists all tracked changes in a single transaction
90
+ await orm.em.flush();
91
+ ```
65
92
 
66
- @ManyToMany(() => Car)
67
- cars = new Collection<Car>(this);
93
+ ### Querying
68
94
 
69
- constructor(name: string) {
70
- this.name = name;
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
- Now to create new instance of the `User` entity, we are forced to provide the `name`:
110
+ ### Request Context
111
+
112
+ In web applications, use `RequestContext` to isolate the identity map per request:
77
113
 
78
114
  ```typescript
79
- const user = new User('John Doe'); // name is required to create new user instance
80
- user.address = new Address('10 Downing Street'); // address is optional
115
+ const app = express();
116
+
117
+ app.use((req, res, next) => {
118
+ RequestContext.create(orm.em, next);
119
+ });
81
120
  ```
82
121
 
83
- Once your entities are loaded, make a number of synchronous actions on your entities,
84
- then call `em.flush()`. This will trigger computing of change sets. Only entities
85
- (and properties) that were changed will generate database queries, if there are no changes,
86
- no transaction will be started.
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 user = await em.findOneOrFail(User, 1, {
90
- populate: ['cars', 'address.city'],
132
+ const author = await em.findOneOrFail(Author, 1, {
133
+ populate: ['books'],
91
134
  });
92
- user.title = 'Mr.';
93
- user.address.street = '10 Downing Street'; // address is 1:1 relation of Address entity
94
- user.cars.getItems().forEach(car => car.forSale = true); // cars is 1:m collection of Car entities
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
- // now we can flush all changes done to managed entities
139
+ // Flush computes change sets and executes them in a single transaction
99
140
  await em.flush();
100
141
  ```
101
142
 
102
- `em.flush()` will then execute these queries from the example above:
143
+ The above flush will execute:
103
144
 
104
145
  ```sql
105
146
  begin;
106
- update "user" set "title" = 'Mr.' where "id" = 1;
107
- update "user_address" set "street" = '10 Downing Street' where "id" = 123;
108
- update "car"
109
- set "for_sale" = case
110
- when ("id" = 1) then true
111
- when ("id" = 2) then true
112
- when ("id" = 3) then true
113
- else "for_sale" end
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
- ### Identity Map
158
+ ## Core Features
120
159
 
121
- Thanks to Identity Map, you will always have only one instance of given entity in one context. This allows for some optimizations (skipping loading of already loaded entities), as well as comparison by identity (`ent1 === ent2`).
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
- ## 📖 Documentation
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
- ## 📦 Example Integrations
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
- ## 🚀 Quick Start
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
- 👤 **Martin Adámek**
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 ⭐️ this repository if this project helped you!
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
- ## 📝 License
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/index.d.ts CHANGED
@@ -2,4 +2,8 @@ export * from '@mikro-orm/sql';
2
2
  export * from './MySqlDriver.js';
3
3
  export * from './MySqlPlatform.js';
4
4
  export * from './MySqlConnection.js';
5
- export { MySqlMikroORM as MikroORM, type MySqlOptions as Options, defineMySqlConfig as defineConfig, } from './MySqlMikroORM.js';
5
+ export {
6
+ MySqlMikroORM as MikroORM,
7
+ type MySqlOptions as Options,
8
+ defineMySqlConfig as defineConfig,
9
+ } from './MySqlMikroORM.js';
package/index.js CHANGED
@@ -2,4 +2,4 @@ export * from '@mikro-orm/sql';
2
2
  export * from './MySqlDriver.js';
3
3
  export * from './MySqlPlatform.js';
4
4
  export * from './MySqlConnection.js';
5
- export { MySqlMikroORM as MikroORM, defineMySqlConfig as defineConfig, } from './MySqlMikroORM.js';
5
+ export { MySqlMikroORM as MikroORM, defineMySqlConfig as defineConfig } from './MySqlMikroORM.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/mysql",
3
- "version": "7.0.2-dev.8",
3
+ "version": "7.0.2",
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,16 +47,16 @@
47
47
  "copy": "node ../../scripts/copy.mjs"
48
48
  },
49
49
  "dependencies": {
50
- "@mikro-orm/sql": "7.0.2-dev.8",
51
- "kysely": "0.28.11",
50
+ "@mikro-orm/sql": "7.0.2",
51
+ "kysely": "0.28.12",
52
52
  "mysql2": "3.19.1",
53
53
  "sqlstring": "2.3.3"
54
54
  },
55
55
  "devDependencies": {
56
- "@mikro-orm/core": "^7.0.1"
56
+ "@mikro-orm/core": "^7.0.2"
57
57
  },
58
58
  "peerDependencies": {
59
- "@mikro-orm/core": "7.0.2-dev.8"
59
+ "@mikro-orm/core": "7.0.2"
60
60
  },
61
61
  "engines": {
62
62
  "node": ">= 22.17.0"