@mikro-orm/migrations 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,113 +1,119 @@
1
1
  import { defineEntity, p } from '@mikro-orm/core';
2
- import { DatabaseTable, } from '@mikro-orm/sql';
2
+ import { DatabaseTable } from '@mikro-orm/sql';
3
+ /** Tracks executed migrations in a database table. */
3
4
  export class MigrationStorage {
4
- driver;
5
- options;
6
- #connection;
7
- #helper;
8
- #masterTransaction;
9
- #platform;
10
- constructor(driver, options) {
11
- this.driver = driver;
12
- this.options = options;
13
- this.#connection = this.driver.getConnection();
14
- this.#platform = this.driver.getPlatform();
15
- this.#helper = this.#platform.getSchemaHelper();
5
+ driver;
6
+ options;
7
+ #connection;
8
+ #helper;
9
+ #masterTransaction;
10
+ #platform;
11
+ constructor(driver, options) {
12
+ this.driver = driver;
13
+ this.options = options;
14
+ this.#connection = this.driver.getConnection();
15
+ this.#platform = this.driver.getPlatform();
16
+ this.#helper = this.#platform.getSchemaHelper();
17
+ }
18
+ async executed() {
19
+ const migrations = await this.getExecutedMigrations();
20
+ return migrations.map(({ name }) => this.getMigrationName(name));
21
+ }
22
+ async logMigration(params) {
23
+ const { entity } = this.getTableName();
24
+ const name = this.getMigrationName(params.name);
25
+ await this.driver.nativeInsert(entity, { name }, { ctx: this.#masterTransaction });
26
+ }
27
+ async unlogMigration(params) {
28
+ const { entity } = this.getTableName();
29
+ const withoutExt = this.getMigrationName(params.name);
30
+ const names = [withoutExt, withoutExt + '.js', withoutExt + '.ts'];
31
+ await this.driver.nativeDelete(
32
+ entity,
33
+ { name: { $in: [params.name, ...names] } },
34
+ { ctx: this.#masterTransaction },
35
+ );
36
+ }
37
+ async getExecutedMigrations() {
38
+ const { entity, schemaName } = this.getTableName();
39
+ const res = await this.driver
40
+ .createQueryBuilder(entity, this.#masterTransaction)
41
+ .withSchema(schemaName)
42
+ .orderBy({ id: 'asc' })
43
+ .execute('all', false);
44
+ return res.map(row => {
45
+ if (typeof row.executed_at === 'string' || typeof row.executed_at === 'number') {
46
+ row.executed_at = new Date(row.executed_at);
47
+ }
48
+ return row;
49
+ });
50
+ }
51
+ async ensureTable() {
52
+ const tables = await this.#connection.execute(this.#helper.getListTablesSQL(), [], 'all', this.#masterTransaction);
53
+ const { tableName, schemaName } = this.getTableName();
54
+ if (tables.find(t => t.table_name === tableName && (!t.schema_name || t.schema_name === schemaName))) {
55
+ return;
16
56
  }
17
- async executed() {
18
- const migrations = await this.getExecutedMigrations();
19
- return migrations.map(({ name }) => this.getMigrationName(name));
20
- }
21
- async logMigration(params) {
22
- const { entity } = this.getTableName();
23
- const name = this.getMigrationName(params.name);
24
- await this.driver.nativeInsert(entity, { name }, { ctx: this.#masterTransaction });
25
- }
26
- async unlogMigration(params) {
27
- const { entity } = this.getTableName();
28
- const withoutExt = this.getMigrationName(params.name);
29
- const names = [withoutExt, withoutExt + '.js', withoutExt + '.ts'];
30
- await this.driver.nativeDelete(entity, { name: { $in: [params.name, ...names] } }, { ctx: this.#masterTransaction });
31
- }
32
- async getExecutedMigrations() {
33
- const { entity, schemaName } = this.getTableName();
34
- const res = await this.driver
35
- .createQueryBuilder(entity, this.#masterTransaction)
36
- .withSchema(schemaName)
37
- .orderBy({ id: 'asc' })
38
- .execute('all', false);
39
- return res.map(row => {
40
- if (typeof row.executed_at === 'string' || typeof row.executed_at === 'number') {
41
- row.executed_at = new Date(row.executed_at);
42
- }
43
- return row;
44
- });
45
- }
46
- async ensureTable() {
47
- const tables = await this.#connection.execute(this.#helper.getListTablesSQL(), [], 'all', this.#masterTransaction);
48
- const { tableName, schemaName } = this.getTableName();
49
- if (tables.find(t => t.table_name === tableName && (!t.schema_name || t.schema_name === schemaName))) {
50
- return;
51
- }
52
- const schemas = await this.#helper.getNamespaces(this.#connection);
53
- if (schemaName && !schemas.includes(schemaName)) {
54
- const sql = this.#helper.getCreateNamespaceSQL(schemaName);
55
- await this.#connection.execute(sql);
56
- }
57
- const table = new DatabaseTable(this.#platform, tableName, schemaName);
58
- table.addColumn({
59
- name: 'id',
60
- type: this.#platform.getIntegerTypeDeclarationSQL({ autoincrement: true, unsigned: true }),
61
- mappedType: this.#platform.getMappedType('number'),
62
- primary: true,
63
- autoincrement: true,
64
- });
65
- table.addColumn({
66
- name: 'name',
67
- type: this.#platform.getVarcharTypeDeclarationSQL({}),
68
- mappedType: this.#platform.getMappedType('string'),
69
- });
70
- const length = this.#platform.getDefaultDateTimeLength();
71
- table.addColumn({
72
- name: 'executed_at',
73
- type: this.#platform.getDateTimeTypeDeclarationSQL({ length }),
74
- mappedType: this.#platform.getMappedType('datetime'),
75
- default: this.#platform.getCurrentTimestampSQL(length),
76
- length,
77
- });
78
- const sql = this.#helper.createTable(table);
79
- await this.#connection.execute(sql.join(';\n'), [], 'run', this.#masterTransaction);
80
- }
81
- setMasterMigration(trx) {
82
- this.#masterTransaction = trx;
83
- }
84
- unsetMasterMigration() {
85
- this.#masterTransaction = undefined;
86
- }
87
- /**
88
- * @internal
89
- */
90
- getMigrationName(name) {
91
- return name.replace(/\.[jt]s$/, '');
92
- }
93
- /**
94
- * @internal
95
- */
96
- getTableName() {
97
- const parts = this.options.tableName.split('.');
98
- const tableName = parts.length > 1 ? parts[1] : parts[0];
99
- const schemaName = parts.length > 1 ? parts[0] : this.driver.config.get('schema', this.driver.getPlatform().getDefaultSchemaName());
100
- const entity = defineEntity({
101
- name: 'Migration',
102
- tableName,
103
- schema: schemaName,
104
- properties: {
105
- id: p.integer().primary().fieldNames('id'),
106
- name: p.string().fieldNames('name'),
107
- executedAt: p.datetime().defaultRaw('current_timestamp').fieldNames('executed_at'),
108
- },
109
- }).init();
110
- entity.meta.sync();
111
- return { tableName, schemaName, entity };
57
+ const schemas = await this.#helper.getNamespaces(this.#connection);
58
+ if (schemaName && !schemas.includes(schemaName)) {
59
+ const sql = this.#helper.getCreateNamespaceSQL(schemaName);
60
+ await this.#connection.execute(sql);
112
61
  }
62
+ const table = new DatabaseTable(this.#platform, tableName, schemaName);
63
+ table.addColumn({
64
+ name: 'id',
65
+ type: this.#platform.getIntegerTypeDeclarationSQL({ autoincrement: true, unsigned: true }),
66
+ mappedType: this.#platform.getMappedType('number'),
67
+ primary: true,
68
+ autoincrement: true,
69
+ });
70
+ table.addColumn({
71
+ name: 'name',
72
+ type: this.#platform.getVarcharTypeDeclarationSQL({}),
73
+ mappedType: this.#platform.getMappedType('string'),
74
+ });
75
+ const length = this.#platform.getDefaultDateTimeLength();
76
+ table.addColumn({
77
+ name: 'executed_at',
78
+ type: this.#platform.getDateTimeTypeDeclarationSQL({ length }),
79
+ mappedType: this.#platform.getMappedType('datetime'),
80
+ default: this.#platform.getCurrentTimestampSQL(length),
81
+ length,
82
+ });
83
+ const sql = this.#helper.createTable(table);
84
+ await this.#connection.execute(sql.join(';\n'), [], 'run', this.#masterTransaction);
85
+ }
86
+ setMasterMigration(trx) {
87
+ this.#masterTransaction = trx;
88
+ }
89
+ unsetMasterMigration() {
90
+ this.#masterTransaction = undefined;
91
+ }
92
+ /**
93
+ * @internal
94
+ */
95
+ getMigrationName(name) {
96
+ return name.replace(/\.[jt]s$/, '');
97
+ }
98
+ /**
99
+ * @internal
100
+ */
101
+ getTableName() {
102
+ const parts = this.options.tableName.split('.');
103
+ const tableName = parts.length > 1 ? parts[1] : parts[0];
104
+ const schemaName =
105
+ parts.length > 1 ? parts[0] : this.driver.config.get('schema', this.driver.getPlatform().getDefaultSchemaName());
106
+ const entity = defineEntity({
107
+ name: 'Migration',
108
+ tableName,
109
+ schema: schemaName,
110
+ properties: {
111
+ id: p.integer().primary().fieldNames('id'),
112
+ name: p.string().fieldNames('name'),
113
+ executedAt: p.datetime().defaultRaw('current_timestamp').fieldNames('executed_at'),
114
+ },
115
+ }).init();
116
+ entity.meta.sync();
117
+ return { tableName, schemaName, entity };
118
+ }
113
119
  }
package/Migrator.d.ts CHANGED
@@ -1,38 +1,49 @@
1
- import { type IMigrationGenerator, type IMigrationRunner, type IMigratorStorage, type MigrateOptions, type MigrationInfo, type MikroORM } from '@mikro-orm/core';
1
+ import {
2
+ type IMigrationGenerator,
3
+ type IMigrationRunner,
4
+ type IMigratorStorage,
5
+ type MigrateOptions,
6
+ type MigrationInfo,
7
+ type MikroORM,
8
+ } from '@mikro-orm/core';
2
9
  import { AbstractMigrator } from '@mikro-orm/core/migrations';
3
10
  import { type AbstractSqlDriver, DatabaseSchema, type EntityManager } from '@mikro-orm/sql';
4
11
  import { MigrationStorage } from './MigrationStorage.js';
5
12
  import type { MigrationResult } from './typings.js';
13
+ /** Manages SQL database migrations: creation, execution, and rollback of schema changes. */
6
14
  export declare class Migrator extends AbstractMigrator<AbstractSqlDriver> {
7
- #private;
8
- constructor(em: EntityManager);
9
- static register(orm: MikroORM): void;
10
- protected createRunner(): IMigrationRunner;
11
- protected createStorage(): IMigratorStorage;
12
- protected getDefaultGenerator(): IMigrationGenerator;
13
- private getSnapshotPath;
14
- protected init(): Promise<void>;
15
- /**
16
- * @inheritDoc
17
- */
18
- create(path?: string, blank?: boolean, initial?: boolean, name?: string): Promise<MigrationResult>;
19
- checkSchema(): Promise<boolean>;
20
- /**
21
- * @inheritDoc
22
- */
23
- createInitial(path?: string, name?: string, blank?: boolean): Promise<MigrationResult>;
24
- protected runMigrations(method: 'up' | 'down', options?: string | string[] | MigrateOptions): Promise<MigrationInfo[]>;
25
- getStorage(): MigrationStorage;
26
- /**
27
- * Initial migration can be created only if:
28
- * 1. no previous migrations were generated or executed
29
- * 2. existing schema do not contain any of the tables defined by metadata
30
- *
31
- * If existing schema contains all of the tables already, we return true, based on that we mark the migration as already executed.
32
- * If only some of the tables are present, exception is thrown.
33
- */
34
- private validateInitialMigration;
35
- protected getSchemaFromSnapshot(): Promise<DatabaseSchema | undefined>;
36
- protected storeCurrentSchema(schema?: DatabaseSchema): Promise<void>;
37
- private getSchemaDiff;
15
+ #private;
16
+ constructor(em: EntityManager);
17
+ static register(orm: MikroORM): void;
18
+ protected createRunner(): IMigrationRunner;
19
+ protected createStorage(): IMigratorStorage;
20
+ protected getDefaultGenerator(): IMigrationGenerator;
21
+ private getSnapshotPath;
22
+ protected init(): Promise<void>;
23
+ /**
24
+ * @inheritDoc
25
+ */
26
+ create(path?: string, blank?: boolean, initial?: boolean, name?: string): Promise<MigrationResult>;
27
+ checkSchema(): Promise<boolean>;
28
+ /**
29
+ * @inheritDoc
30
+ */
31
+ createInitial(path?: string, name?: string, blank?: boolean): Promise<MigrationResult>;
32
+ protected runMigrations(
33
+ method: 'up' | 'down',
34
+ options?: string | string[] | MigrateOptions,
35
+ ): Promise<MigrationInfo[]>;
36
+ getStorage(): MigrationStorage;
37
+ /**
38
+ * Initial migration can be created only if:
39
+ * 1. no previous migrations were generated or executed
40
+ * 2. existing schema do not contain any of the tables defined by metadata
41
+ *
42
+ * If existing schema contains all of the tables already, we return true, based on that we mark the migration as already executed.
43
+ * If only some of the tables are present, exception is thrown.
44
+ */
45
+ private validateInitialMigration;
46
+ protected getSchemaFromSnapshot(): Promise<DatabaseSchema | undefined>;
47
+ protected storeCurrentSchema(schema?: DatabaseSchema): Promise<void>;
48
+ private getSchemaDiff;
38
49
  }