@mikro-orm/migrations 7.0.4-dev.8 → 7.0.4

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,11 +1,14 @@
1
1
  import { MigrationGenerator } from './MigrationGenerator.js';
2
2
  /** Generates migration files in CommonJS JavaScript format. */
3
3
  export declare class JSMigrationGenerator extends MigrationGenerator {
4
- /**
5
- * @inheritDoc
6
- */
7
- generateMigrationFile(className: string, diff: {
8
- up: string[];
9
- down: string[];
10
- }): string;
4
+ /**
5
+ * @inheritDoc
6
+ */
7
+ generateMigrationFile(
8
+ className: string,
9
+ diff: {
10
+ up: string[];
11
+ down: string[];
12
+ },
13
+ ): string;
11
14
  }
@@ -1,25 +1,25 @@
1
1
  import { MigrationGenerator } from './MigrationGenerator.js';
2
2
  /** Generates migration files in CommonJS JavaScript format. */
3
3
  export class JSMigrationGenerator extends MigrationGenerator {
4
- /**
5
- * @inheritDoc
6
- */
7
- generateMigrationFile(className, diff) {
8
- let ret = `'use strict';\n`;
9
- ret += `Object.defineProperty(exports, '__esModule', { value: true });\n`;
10
- ret += `const { Migration } = require('@mikro-orm/migrations');\n\n`;
11
- ret += `class ${className} extends Migration {\n\n`;
12
- ret += ` async up() {\n`;
13
- diff.up.forEach(sql => (ret += this.createStatement(sql, 4)));
14
- ret += ` }\n\n`;
15
- /* v8 ignore next */
16
- if (diff.down.length > 0) {
17
- ret += ` async down() {\n`;
18
- diff.down.forEach(sql => (ret += this.createStatement(sql, 4)));
19
- ret += ` }\n\n`;
20
- }
21
- ret += `}\n`;
22
- ret += `exports.${className} = ${className};\n`;
23
- return ret;
4
+ /**
5
+ * @inheritDoc
6
+ */
7
+ generateMigrationFile(className, diff) {
8
+ let ret = `'use strict';\n`;
9
+ ret += `Object.defineProperty(exports, '__esModule', { value: true });\n`;
10
+ ret += `const { Migration } = require('@mikro-orm/migrations');\n\n`;
11
+ ret += `class ${className} extends Migration {\n\n`;
12
+ ret += ` async up() {\n`;
13
+ diff.up.forEach(sql => (ret += this.createStatement(sql, 4)));
14
+ ret += ` }\n\n`;
15
+ /* v8 ignore next */
16
+ if (diff.down.length > 0) {
17
+ ret += ` async down() {\n`;
18
+ diff.down.forEach(sql => (ret += this.createStatement(sql, 4)));
19
+ ret += ` }\n\n`;
24
20
  }
21
+ ret += `}\n`;
22
+ ret += `exports.${className} = ${className};\n`;
23
+ return ret;
24
+ }
25
25
  }
package/Migration.d.ts CHANGED
@@ -1,29 +1,35 @@
1
- import { type AnyEntity, type Configuration, type EntityData, type RawQueryFragment, type Transaction } from '@mikro-orm/core';
1
+ import {
2
+ type AnyEntity,
3
+ type Configuration,
4
+ type EntityData,
5
+ type RawQueryFragment,
6
+ type Transaction,
7
+ } from '@mikro-orm/core';
2
8
  import type { AbstractSqlDriver, EntityManager, NativeQueryBuilder } from '@mikro-orm/sql';
3
9
  /** A migration query: raw SQL string, a native query builder instance, or a `raw()` SQL fragment. */
4
10
  export type Query = string | NativeQueryBuilder | RawQueryFragment;
5
11
  /** Base class for SQL database migrations. Extend this class and implement `up()` (and optionally `down()`). */
6
12
  export declare abstract class Migration {
7
- #private;
8
- protected readonly driver: AbstractSqlDriver;
9
- protected readonly config: Configuration;
10
- protected ctx?: Transaction;
11
- constructor(driver: AbstractSqlDriver, config: Configuration);
12
- abstract up(): Promise<void> | void;
13
- down(): Promise<void> | void;
14
- isTransactional(): boolean;
15
- addSql(sql: Query): void;
16
- reset(): void;
17
- setTransactionContext(ctx: Transaction): void;
18
- /**
19
- * Executes a raw SQL query. Accepts a string SQL, `raw()` SQL fragment, or a native query builder instance.
20
- * The `params` parameter is respected only if you use string SQL in the first parameter.
21
- */
22
- execute(sql: Query, params?: unknown[]): Promise<EntityData<AnyEntity>[]>;
23
- /**
24
- * Creates a cached `EntityManager` instance for this migration, which will respect
25
- * the current transaction context.
26
- */
27
- getEntityManager(): EntityManager;
28
- getQueries(): Query[];
13
+ #private;
14
+ protected readonly driver: AbstractSqlDriver;
15
+ protected readonly config: Configuration;
16
+ protected ctx?: Transaction;
17
+ constructor(driver: AbstractSqlDriver, config: Configuration);
18
+ abstract up(): Promise<void> | void;
19
+ down(): Promise<void> | void;
20
+ isTransactional(): boolean;
21
+ addSql(sql: Query): void;
22
+ reset(): void;
23
+ setTransactionContext(ctx: Transaction): void;
24
+ /**
25
+ * Executes a raw SQL query. Accepts a string SQL, `raw()` SQL fragment, or a native query builder instance.
26
+ * The `params` parameter is respected only if you use string SQL in the first parameter.
27
+ */
28
+ execute(sql: Query, params?: unknown[]): Promise<EntityData<AnyEntity>[]>;
29
+ /**
30
+ * Creates a cached `EntityManager` instance for this migration, which will respect
31
+ * the current transaction context.
32
+ */
33
+ getEntityManager(): EntityManager;
34
+ getQueries(): Query[];
29
35
  }
package/Migration.js CHANGED
@@ -1,49 +1,49 @@
1
1
  /** Base class for SQL database migrations. Extend this class and implement `up()` (and optionally `down()`). */
2
2
  export class Migration {
3
- driver;
4
- config;
5
- #queries = [];
6
- ctx;
7
- #em;
8
- constructor(driver, config) {
9
- this.driver = driver;
10
- this.config = config;
11
- }
12
- down() {
13
- throw new Error('This migration cannot be reverted');
14
- }
15
- isTransactional() {
16
- return true;
17
- }
18
- addSql(sql) {
19
- this.#queries.push(sql);
20
- }
21
- reset() {
22
- this.#queries.length = 0;
23
- this.ctx = undefined;
24
- }
25
- setTransactionContext(ctx) {
26
- this.ctx = ctx;
27
- }
28
- /**
29
- * Executes a raw SQL query. Accepts a string SQL, `raw()` SQL fragment, or a native query builder instance.
30
- * The `params` parameter is respected only if you use string SQL in the first parameter.
31
- */
32
- async execute(sql, params) {
33
- return this.driver.execute(sql, params, 'all', this.ctx);
34
- }
35
- /**
36
- * Creates a cached `EntityManager` instance for this migration, which will respect
37
- * the current transaction context.
38
- */
39
- getEntityManager() {
40
- if (!this.#em) {
41
- this.#em = this.driver.createEntityManager();
42
- this.#em.setTransactionContext(this.ctx);
43
- }
44
- return this.#em;
45
- }
46
- getQueries() {
47
- return this.#queries;
48
- }
3
+ driver;
4
+ config;
5
+ #queries = [];
6
+ ctx;
7
+ #em;
8
+ constructor(driver, config) {
9
+ this.driver = driver;
10
+ this.config = config;
11
+ }
12
+ down() {
13
+ throw new Error('This migration cannot be reverted');
14
+ }
15
+ isTransactional() {
16
+ return true;
17
+ }
18
+ addSql(sql) {
19
+ this.#queries.push(sql);
20
+ }
21
+ reset() {
22
+ this.#queries.length = 0;
23
+ this.ctx = undefined;
24
+ }
25
+ setTransactionContext(ctx) {
26
+ this.ctx = ctx;
27
+ }
28
+ /**
29
+ * Executes a raw SQL query. Accepts a string SQL, `raw()` SQL fragment, or a native query builder instance.
30
+ * The `params` parameter is respected only if you use string SQL in the first parameter.
31
+ */
32
+ async execute(sql, params) {
33
+ return this.driver.execute(sql, params, 'all', this.ctx);
34
+ }
35
+ /**
36
+ * Creates a cached `EntityManager` instance for this migration, which will respect
37
+ * the current transaction context.
38
+ */
39
+ getEntityManager() {
40
+ if (!this.#em) {
41
+ this.#em = this.driver.createEntityManager();
42
+ this.#em.setTransactionContext(this.ctx);
43
+ }
44
+ return this.#em;
45
+ }
46
+ getQueries() {
47
+ return this.#queries;
48
+ }
49
49
  }
@@ -1,27 +1,39 @@
1
- import { type IMigrationGenerator, type MaybePromise, type MigrationsOptions, type NamingStrategy } from '@mikro-orm/core';
1
+ import {
2
+ type IMigrationGenerator,
3
+ type MaybePromise,
4
+ type MigrationsOptions,
5
+ type NamingStrategy,
6
+ } from '@mikro-orm/core';
2
7
  import type { AbstractSqlDriver } from '@mikro-orm/sql';
3
8
  /** Base class for generating migration source files from schema diffs. */
4
9
  export declare abstract class MigrationGenerator implements IMigrationGenerator {
5
- protected readonly driver: AbstractSqlDriver;
6
- protected readonly namingStrategy: NamingStrategy;
7
- protected readonly options: MigrationsOptions;
8
- constructor(driver: AbstractSqlDriver, namingStrategy: NamingStrategy, options: MigrationsOptions);
9
- /**
10
- * @inheritDoc
11
- */
12
- generate(diff: {
13
- up: string[];
14
- down: string[];
15
- }, path?: string, name?: string): Promise<[string, string]>;
16
- /**
17
- * @inheritDoc
18
- */
19
- createStatement(sql: string, padLeft: number): string;
20
- /**
21
- * @inheritDoc
22
- */
23
- abstract generateMigrationFile(className: string, diff: {
24
- up: string[];
25
- down: string[];
26
- }): MaybePromise<string>;
10
+ protected readonly driver: AbstractSqlDriver;
11
+ protected readonly namingStrategy: NamingStrategy;
12
+ protected readonly options: MigrationsOptions;
13
+ constructor(driver: AbstractSqlDriver, namingStrategy: NamingStrategy, options: MigrationsOptions);
14
+ /**
15
+ * @inheritDoc
16
+ */
17
+ generate(
18
+ diff: {
19
+ up: string[];
20
+ down: string[];
21
+ },
22
+ path?: string,
23
+ name?: string,
24
+ ): Promise<[string, string]>;
25
+ /**
26
+ * @inheritDoc
27
+ */
28
+ createStatement(sql: string, padLeft: number): string;
29
+ /**
30
+ * @inheritDoc
31
+ */
32
+ abstract generateMigrationFile(
33
+ className: string,
34
+ diff: {
35
+ up: string[];
36
+ down: string[];
37
+ },
38
+ ): MaybePromise<string>;
27
39
  }
@@ -1,37 +1,37 @@
1
1
  /** Base class for generating migration source files from schema diffs. */
2
2
  export class MigrationGenerator {
3
- driver;
4
- namingStrategy;
5
- options;
6
- constructor(driver, namingStrategy, options) {
7
- this.driver = driver;
8
- this.namingStrategy = namingStrategy;
9
- this.options = options;
10
- }
11
- /**
12
- * @inheritDoc
13
- */
14
- async generate(diff, path, name) {
15
- const { fs } = await import('@mikro-orm/core/fs-utils');
16
- /* v8 ignore next */
17
- const defaultPath = this.options.emit === 'ts' && this.options.pathTs ? this.options.pathTs : this.options.path;
18
- path = fs.normalizePath(this.driver.config.get('baseDir'), path ?? defaultPath);
19
- fs.ensureDir(path);
20
- const timestamp = new Date().toISOString().replace(/[-T:]|\.\d{3}z$/gi, '');
21
- const className = this.namingStrategy.classToMigrationName(timestamp, name);
22
- const fileName = `${this.options.fileName(timestamp, name)}.${this.options.emit}`;
23
- const ret = await this.generateMigrationFile(className, diff);
24
- await fs.writeFile(path + '/' + fileName, ret, { flush: true });
25
- return [ret, fileName];
26
- }
27
- /**
28
- * @inheritDoc
29
- */
30
- createStatement(sql, padLeft) {
31
- if (sql) {
32
- const padding = ' '.repeat(padLeft);
33
- return `${padding}this.addSql(\`${sql.replace(/[`$\\]/g, '\\$&')}\`);\n`;
34
- }
35
- return '\n';
3
+ driver;
4
+ namingStrategy;
5
+ options;
6
+ constructor(driver, namingStrategy, options) {
7
+ this.driver = driver;
8
+ this.namingStrategy = namingStrategy;
9
+ this.options = options;
10
+ }
11
+ /**
12
+ * @inheritDoc
13
+ */
14
+ async generate(diff, path, name) {
15
+ const { fs } = await import('@mikro-orm/core/fs-utils');
16
+ /* v8 ignore next */
17
+ const defaultPath = this.options.emit === 'ts' && this.options.pathTs ? this.options.pathTs : this.options.path;
18
+ path = fs.normalizePath(this.driver.config.get('baseDir'), path ?? defaultPath);
19
+ fs.ensureDir(path);
20
+ const timestamp = new Date().toISOString().replace(/[-T:]|\.\d{3}z$/gi, '');
21
+ const className = this.namingStrategy.classToMigrationName(timestamp, name);
22
+ const fileName = `${this.options.fileName(timestamp, name)}.${this.options.emit}`;
23
+ const ret = await this.generateMigrationFile(className, diff);
24
+ await fs.writeFile(path + '/' + fileName, ret, { flush: true });
25
+ return [ret, fileName];
26
+ }
27
+ /**
28
+ * @inheritDoc
29
+ */
30
+ createStatement(sql, padLeft) {
31
+ if (sql) {
32
+ const padding = ' '.repeat(padLeft);
33
+ return `${padding}this.addSql(\`${sql.replace(/[`$\\]/g, '\\$&')}\`);\n`;
36
34
  }
35
+ return '\n';
36
+ }
37
37
  }
@@ -3,13 +3,13 @@ import type { AbstractSqlDriver } from '@mikro-orm/sql';
3
3
  import type { Migration } from './Migration.js';
4
4
  /** Executes individual migration files within optional transaction contexts. */
5
5
  export declare class MigrationRunner {
6
- #private;
7
- protected readonly driver: AbstractSqlDriver;
8
- protected readonly options: MigrationsOptions;
9
- protected readonly config: Configuration;
10
- constructor(driver: AbstractSqlDriver, options: MigrationsOptions, config: Configuration);
11
- run(migration: Migration, method: 'up' | 'down'): Promise<void>;
12
- setMasterMigration(trx: Transaction): void;
13
- unsetMasterMigration(): void;
14
- private getQueries;
6
+ #private;
7
+ protected readonly driver: AbstractSqlDriver;
8
+ protected readonly options: MigrationsOptions;
9
+ protected readonly config: Configuration;
10
+ constructor(driver: AbstractSqlDriver, options: MigrationsOptions, config: Configuration);
11
+ run(migration: Migration, method: 'up' | 'down'): Promise<void>;
12
+ setMasterMigration(trx: Transaction): void;
13
+ unsetMasterMigration(): void;
14
+ private getQueries;
15
15
  }
@@ -1,46 +1,48 @@
1
1
  import { Utils } from '@mikro-orm/core';
2
2
  /** Executes individual migration files within optional transaction contexts. */
3
3
  export class MigrationRunner {
4
- driver;
5
- options;
6
- config;
7
- #connection;
8
- #helper;
9
- #masterTransaction;
10
- constructor(driver, options, config) {
11
- this.driver = driver;
12
- this.options = options;
13
- this.config = config;
14
- this.#connection = this.driver.getConnection();
15
- this.#helper = this.driver.getPlatform().getSchemaHelper();
16
- }
17
- async run(migration, method) {
18
- migration.reset();
19
- if (!this.options.transactional || !migration.isTransactional()) {
20
- const queries = await this.getQueries(migration, method);
21
- await Utils.runSerial(queries, sql => this.driver.execute(sql));
22
- }
23
- else {
24
- await this.#connection.transactional(async (tx) => {
25
- migration.setTransactionContext(tx);
26
- const queries = await this.getQueries(migration, method);
27
- await Utils.runSerial(queries, sql => this.driver.execute(sql, undefined, 'all', tx));
28
- }, { ctx: this.#masterTransaction });
29
- }
30
- }
31
- setMasterMigration(trx) {
32
- this.#masterTransaction = trx;
33
- }
34
- unsetMasterMigration() {
35
- this.#masterTransaction = undefined;
36
- }
37
- async getQueries(migration, method) {
38
- await migration[method]();
39
- const charset = this.config.get('charset');
40
- let queries = migration.getQueries();
41
- queries.unshift(...this.#helper.getSchemaBeginning(charset, this.options.disableForeignKeys).split('\n'));
42
- queries.push(...this.#helper.getSchemaEnd(this.options.disableForeignKeys).split('\n'));
43
- queries = queries.filter(sql => typeof sql !== 'string' || sql.trim().length > 0);
44
- return queries;
4
+ driver;
5
+ options;
6
+ config;
7
+ #connection;
8
+ #helper;
9
+ #masterTransaction;
10
+ constructor(driver, options, config) {
11
+ this.driver = driver;
12
+ this.options = options;
13
+ this.config = config;
14
+ this.#connection = this.driver.getConnection();
15
+ this.#helper = this.driver.getPlatform().getSchemaHelper();
16
+ }
17
+ async run(migration, method) {
18
+ migration.reset();
19
+ if (!this.options.transactional || !migration.isTransactional()) {
20
+ const queries = await this.getQueries(migration, method);
21
+ await Utils.runSerial(queries, sql => this.driver.execute(sql));
22
+ } else {
23
+ await this.#connection.transactional(
24
+ async tx => {
25
+ migration.setTransactionContext(tx);
26
+ const queries = await this.getQueries(migration, method);
27
+ await Utils.runSerial(queries, sql => this.driver.execute(sql, undefined, 'all', tx));
28
+ },
29
+ { ctx: this.#masterTransaction },
30
+ );
45
31
  }
32
+ }
33
+ setMasterMigration(trx) {
34
+ this.#masterTransaction = trx;
35
+ }
36
+ unsetMasterMigration() {
37
+ this.#masterTransaction = undefined;
38
+ }
39
+ async getQueries(migration, method) {
40
+ await migration[method]();
41
+ const charset = this.config.get('charset');
42
+ let queries = migration.getQueries();
43
+ queries.unshift(...this.#helper.getSchemaBeginning(charset, this.options.disableForeignKeys).split('\n'));
44
+ queries.push(...this.#helper.getSchemaEnd(this.options.disableForeignKeys).split('\n'));
45
+ queries = queries.filter(sql => typeof sql !== 'string' || sql.trim().length > 0);
46
+ return queries;
47
+ }
46
48
  }
@@ -3,31 +3,27 @@ import { type AbstractSqlDriver } from '@mikro-orm/sql';
3
3
  import type { MigrationRow } from './typings.js';
4
4
  /** Tracks executed migrations in a database table. */
5
5
  export declare class MigrationStorage {
6
- #private;
7
- protected readonly driver: AbstractSqlDriver;
8
- protected readonly options: MigrationsOptions;
9
- constructor(driver: AbstractSqlDriver, options: MigrationsOptions);
10
- executed(): Promise<string[]>;
11
- logMigration(params: {
12
- name: string;
13
- }): Promise<void>;
14
- unlogMigration(params: {
15
- name: string;
16
- }): Promise<void>;
17
- getExecutedMigrations(): Promise<MigrationRow[]>;
18
- ensureTable(): Promise<void>;
19
- setMasterMigration(trx: Transaction): void;
20
- unsetMasterMigration(): void;
21
- /**
22
- * @internal
23
- */
24
- getMigrationName(name: string): string;
25
- /**
26
- * @internal
27
- */
28
- getTableName(): {
29
- tableName: string;
30
- schemaName: string;
31
- entity: EntitySchema;
32
- };
6
+ #private;
7
+ protected readonly driver: AbstractSqlDriver;
8
+ protected readonly options: MigrationsOptions;
9
+ constructor(driver: AbstractSqlDriver, options: MigrationsOptions);
10
+ executed(): Promise<string[]>;
11
+ logMigration(params: { name: string }): Promise<void>;
12
+ unlogMigration(params: { name: string }): Promise<void>;
13
+ getExecutedMigrations(): Promise<MigrationRow[]>;
14
+ ensureTable(): Promise<void>;
15
+ setMasterMigration(trx: Transaction): void;
16
+ unsetMasterMigration(): void;
17
+ /**
18
+ * @internal
19
+ */
20
+ getMigrationName(name: string): string;
21
+ /**
22
+ * @internal
23
+ */
24
+ getTableName(): {
25
+ tableName: string;
26
+ schemaName: string;
27
+ entity: EntitySchema;
28
+ };
33
29
  }