@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.
package/Migrator.js CHANGED
@@ -1,264 +1,264 @@
1
- import { t, Type, UnknownType, } from '@mikro-orm/core';
1
+ import { t, Type, UnknownType } from '@mikro-orm/core';
2
2
  import { AbstractMigrator } from '@mikro-orm/core/migrations';
3
- import { DatabaseSchema, DatabaseTable, } from '@mikro-orm/sql';
3
+ import { DatabaseSchema, DatabaseTable } from '@mikro-orm/sql';
4
4
  import { MigrationRunner } from './MigrationRunner.js';
5
5
  import { MigrationStorage } from './MigrationStorage.js';
6
6
  import { TSMigrationGenerator } from './TSMigrationGenerator.js';
7
7
  import { JSMigrationGenerator } from './JSMigrationGenerator.js';
8
+ /** Manages SQL database migrations: creation, execution, and rollback of schema changes. */
8
9
  export class Migrator extends AbstractMigrator {
9
- #schemaGenerator;
10
- #snapshotPath;
11
- constructor(em) {
12
- super(em);
13
- this.#schemaGenerator = this.config.getExtension('@mikro-orm/schema-generator');
10
+ #schemaGenerator;
11
+ #snapshotPath;
12
+ constructor(em) {
13
+ super(em);
14
+ this.#schemaGenerator = this.config.getExtension('@mikro-orm/schema-generator');
15
+ }
16
+ static register(orm) {
17
+ orm.config.registerExtension('@mikro-orm/migrator', () => new Migrator(orm.em));
18
+ }
19
+ createRunner() {
20
+ return new MigrationRunner(this.driver, this.options, this.config);
21
+ }
22
+ createStorage() {
23
+ return new MigrationStorage(this.driver, this.options);
24
+ }
25
+ getDefaultGenerator() {
26
+ if (this.options.emit === 'js' || this.options.emit === 'cjs') {
27
+ return new JSMigrationGenerator(this.driver, this.config.getNamingStrategy(), this.options);
14
28
  }
15
- static register(orm) {
16
- orm.config.registerExtension('@mikro-orm/migrator', () => new Migrator(orm.em));
29
+ return new TSMigrationGenerator(this.driver, this.config.getNamingStrategy(), this.options);
30
+ }
31
+ async getSnapshotPath() {
32
+ if (!this.#snapshotPath) {
33
+ const { fs } = await import('@mikro-orm/core/fs-utils');
34
+ // for snapshots, we always want to use the path based on `emit` option, regardless of whether we run in TS context
35
+ /* v8 ignore next */
36
+ const snapshotPath = this.options.emit === 'ts' && this.options.pathTs ? this.options.pathTs : this.options.path;
37
+ const absoluteSnapshotPath = fs.absolutePath(snapshotPath, this.config.get('baseDir'));
38
+ const dbName = this.config.get('dbName').replace(/\\/g, '/').split('/').pop().replace(/:/g, '');
39
+ const snapshotName = this.options.snapshotName ?? `.snapshot-${dbName}`;
40
+ this.#snapshotPath = fs.normalizePath(absoluteSnapshotPath, `${snapshotName}.json`);
17
41
  }
18
- createRunner() {
19
- return new MigrationRunner(this.driver, this.options, this.config);
42
+ return this.#snapshotPath;
43
+ }
44
+ async init() {
45
+ if (this.initialized) {
46
+ return;
20
47
  }
21
- createStorage() {
22
- return new MigrationStorage(this.driver, this.options);
48
+ await super.init();
49
+ const created = await this.#schemaGenerator.ensureDatabase();
50
+ /* v8 ignore next */
51
+ if (created) {
52
+ this.initServices();
23
53
  }
24
- getDefaultGenerator() {
25
- if (this.options.emit === 'js' || this.options.emit === 'cjs') {
26
- return new JSMigrationGenerator(this.driver, this.config.getNamingStrategy(), this.options);
27
- }
28
- return new TSMigrationGenerator(this.driver, this.config.getNamingStrategy(), this.options);
54
+ await this.storage.ensureTable();
55
+ }
56
+ /**
57
+ * @inheritDoc
58
+ */
59
+ async create(path, blank = false, initial = false, name) {
60
+ await this.init();
61
+ if (initial) {
62
+ return this.createInitial(path, name, blank);
29
63
  }
30
- async getSnapshotPath() {
31
- if (!this.#snapshotPath) {
32
- const { fs } = await import('@mikro-orm/core/fs-utils');
33
- // for snapshots, we always want to use the path based on `emit` option, regardless of whether we run in TS context
34
- /* v8 ignore next */
35
- const snapshotPath = this.options.emit === 'ts' && this.options.pathTs ? this.options.pathTs : this.options.path;
36
- const absoluteSnapshotPath = fs.absolutePath(snapshotPath, this.config.get('baseDir'));
37
- const dbName = this.config.get('dbName').replace(/\\/g, '/').split('/').pop().replace(/:/g, '');
38
- const snapshotName = this.options.snapshotName ?? `.snapshot-${dbName}`;
39
- this.#snapshotPath = fs.normalizePath(absoluteSnapshotPath, `${snapshotName}.json`);
40
- }
41
- return this.#snapshotPath;
64
+ const diff = await this.getSchemaDiff(blank, initial);
65
+ if (diff.up.length === 0) {
66
+ return { fileName: '', code: '', diff };
42
67
  }
43
- async init() {
44
- if (this.initialized) {
45
- return;
46
- }
47
- await super.init();
48
- const created = await this.#schemaGenerator.ensureDatabase();
49
- /* v8 ignore next */
50
- if (created) {
51
- this.initServices();
52
- }
53
- await this.storage.ensureTable();
68
+ const migration = await this.generator.generate(diff, path, name);
69
+ await this.storeCurrentSchema();
70
+ return {
71
+ fileName: migration[1],
72
+ code: migration[0],
73
+ diff,
74
+ };
75
+ }
76
+ async checkSchema() {
77
+ await this.init();
78
+ const diff = await this.getSchemaDiff(false, false);
79
+ return diff.up.length > 0;
80
+ }
81
+ /**
82
+ * @inheritDoc
83
+ */
84
+ async createInitial(path, name, blank = false) {
85
+ await this.init();
86
+ const schemaExists = await this.validateInitialMigration(blank);
87
+ const diff = await this.getSchemaDiff(blank, true);
88
+ const migration = await this.generator.generate(diff, path, name);
89
+ await this.storeCurrentSchema();
90
+ if (schemaExists && !blank) {
91
+ await this.storage.logMigration({ name: migration[1] });
54
92
  }
55
- /**
56
- * @inheritDoc
57
- */
58
- async create(path, blank = false, initial = false, name) {
59
- await this.init();
60
- if (initial) {
61
- return this.createInitial(path, name, blank);
62
- }
63
- const diff = await this.getSchemaDiff(blank, initial);
64
- if (diff.up.length === 0) {
65
- return { fileName: '', code: '', diff };
66
- }
67
- const migration = await this.generator.generate(diff, path, name);
68
- await this.storeCurrentSchema();
69
- return {
70
- fileName: migration[1],
71
- code: migration[0],
72
- diff,
73
- };
93
+ return {
94
+ fileName: migration[1],
95
+ code: migration[0],
96
+ diff,
97
+ };
98
+ }
99
+ async runMigrations(method, options) {
100
+ const result = await super.runMigrations(method, options);
101
+ if (result.length > 0 && this.options.snapshot) {
102
+ const schema = await DatabaseSchema.create(this.em.getConnection(), this.em.getPlatform(), this.config);
103
+ try {
104
+ await this.storeCurrentSchema(schema);
105
+ } catch {
106
+ // Silently ignore for read-only filesystems (production).
107
+ }
74
108
  }
75
- async checkSchema() {
76
- await this.init();
77
- const diff = await this.getSchemaDiff(false, false);
78
- return diff.up.length > 0;
109
+ return result;
110
+ }
111
+ getStorage() {
112
+ return this.storage;
113
+ }
114
+ /**
115
+ * Initial migration can be created only if:
116
+ * 1. no previous migrations were generated or executed
117
+ * 2. existing schema do not contain any of the tables defined by metadata
118
+ *
119
+ * If existing schema contains all of the tables already, we return true, based on that we mark the migration as already executed.
120
+ * If only some of the tables are present, exception is thrown.
121
+ */
122
+ async validateInitialMigration(blank) {
123
+ const executed = await this.getExecuted();
124
+ const pending = await this.getPending();
125
+ if (executed.length > 0 || pending.length > 0) {
126
+ throw new Error('Initial migration cannot be created, as some migrations already exist');
79
127
  }
80
- /**
81
- * @inheritDoc
82
- */
83
- async createInitial(path, name, blank = false) {
84
- await this.init();
85
- const schemaExists = await this.validateInitialMigration(blank);
86
- const diff = await this.getSchemaDiff(blank, true);
87
- const migration = await this.generator.generate(diff, path, name);
88
- await this.storeCurrentSchema();
89
- if (schemaExists && !blank) {
90
- await this.storage.logMigration({ name: migration[1] });
91
- }
92
- return {
93
- fileName: migration[1],
94
- code: migration[0],
95
- diff,
96
- };
128
+ const schema = await DatabaseSchema.create(this.em.getConnection(), this.em.getPlatform(), this.config);
129
+ const exists = new Set();
130
+ const expected = new Set();
131
+ [...this.em.getMetadata().getAll().values()]
132
+ .filter(meta => meta.tableName && !meta.embeddable && !meta.virtual)
133
+ .forEach(meta => {
134
+ const schema = meta.schema ?? this.config.get('schema', this.em.getPlatform().getDefaultSchemaName());
135
+ expected.add(schema ? `${schema}.${meta.collection}` : meta.collection);
136
+ });
137
+ schema.getTables().forEach(table => {
138
+ const schema = table.schema ?? this.em.getPlatform().getDefaultSchemaName();
139
+ const tableName = schema ? `${schema}.${table.name}` : table.name;
140
+ if (expected.has(tableName)) {
141
+ exists.add(table.schema ? `${table.schema}.${table.name}` : table.name);
142
+ }
143
+ });
144
+ if (expected.size === 0 && !blank) {
145
+ throw new Error('No entities found');
97
146
  }
98
- async runMigrations(method, options) {
99
- const result = await super.runMigrations(method, options);
100
- if (result.length > 0 && this.options.snapshot) {
101
- const schema = await DatabaseSchema.create(this.em.getConnection(), this.em.getPlatform(), this.config);
102
- try {
103
- await this.storeCurrentSchema(schema);
104
- }
105
- catch {
106
- // Silently ignore for read-only filesystems (production).
107
- }
108
- }
109
- return result;
147
+ if (exists.size > 0 && expected.size !== exists.size) {
148
+ throw new Error(
149
+ `Some tables already exist in your schema, remove them first to create the initial migration: ${[...exists].join(', ')}`,
150
+ );
110
151
  }
111
- getStorage() {
112
- return this.storage;
152
+ return expected.size === exists.size;
153
+ }
154
+ async getSchemaFromSnapshot() {
155
+ if (!this.options.snapshot) {
156
+ return undefined;
113
157
  }
114
- /**
115
- * Initial migration can be created only if:
116
- * 1. no previous migrations were generated or executed
117
- * 2. existing schema do not contain any of the tables defined by metadata
118
- *
119
- * If existing schema contains all of the tables already, we return true, based on that we mark the migration as already executed.
120
- * If only some of the tables are present, exception is thrown.
121
- */
122
- async validateInitialMigration(blank) {
123
- const executed = await this.getExecuted();
124
- const pending = await this.getPending();
125
- if (executed.length > 0 || pending.length > 0) {
126
- throw new Error('Initial migration cannot be created, as some migrations already exist');
127
- }
128
- const schema = await DatabaseSchema.create(this.em.getConnection(), this.em.getPlatform(), this.config);
129
- const exists = new Set();
130
- const expected = new Set();
131
- [...this.em.getMetadata().getAll().values()]
132
- .filter(meta => meta.tableName && !meta.embeddable && !meta.virtual)
133
- .forEach(meta => {
134
- const schema = meta.schema ?? this.config.get('schema', this.em.getPlatform().getDefaultSchemaName());
135
- expected.add(schema ? `${schema}.${meta.collection}` : meta.collection);
136
- });
137
- schema.getTables().forEach(table => {
138
- const schema = table.schema ?? this.em.getPlatform().getDefaultSchemaName();
139
- const tableName = schema ? `${schema}.${table.name}` : table.name;
140
- if (expected.has(tableName)) {
141
- exists.add(table.schema ? `${table.schema}.${table.name}` : table.name);
142
- }
143
- });
144
- if (expected.size === 0 && !blank) {
145
- throw new Error('No entities found');
146
- }
147
- if (exists.size > 0 && expected.size !== exists.size) {
148
- throw new Error(`Some tables already exist in your schema, remove them first to create the initial migration: ${[...exists].join(', ')}`);
149
- }
150
- return expected.size === exists.size;
158
+ const snapshotPath = await this.getSnapshotPath();
159
+ const { fs } = await import('@mikro-orm/core/fs-utils');
160
+ if (!fs.pathExists(snapshotPath)) {
161
+ return undefined;
151
162
  }
152
- async getSchemaFromSnapshot() {
153
- if (!this.options.snapshot) {
154
- return undefined;
155
- }
156
- const snapshotPath = await this.getSnapshotPath();
157
- const { fs } = await import('@mikro-orm/core/fs-utils');
158
- if (!fs.pathExists(snapshotPath)) {
159
- return undefined;
160
- }
161
- const data = fs.readJSONSync(snapshotPath);
162
- const schema = new DatabaseSchema(this.driver.getPlatform(), this.config.get('schema'));
163
- const { tables, namespaces, ...rest } = data;
164
- const tableInstances = tables.map((tbl) => {
165
- const table = new DatabaseTable(this.driver.getPlatform(), tbl.name, tbl.schema);
166
- table.nativeEnums = tbl.nativeEnums ?? {};
167
- table.comment = tbl.comment;
168
- if (tbl.indexes) {
169
- table.setIndexes(tbl.indexes);
170
- }
171
- if (tbl.checks) {
172
- table.setChecks(tbl.checks);
173
- }
174
- if (tbl.foreignKeys) {
175
- table.setForeignKeys(tbl.foreignKeys);
176
- }
177
- const cols = tbl.columns;
178
- Object.keys(cols).forEach(col => {
179
- const column = { ...cols[col] };
180
- /* v8 ignore next */
181
- column.mappedType = Type.getType(t[cols[col].mappedType] ?? UnknownType);
182
- table.addColumn(column);
183
- });
184
- return table;
185
- });
186
- schema.setTables(tableInstances);
187
- schema.setNamespaces(new Set(namespaces));
188
- if (rest.nativeEnums) {
189
- schema.setNativeEnums(rest.nativeEnums);
190
- }
191
- if (rest.views) {
192
- schema.setViews(rest.views);
193
- }
194
- return schema;
163
+ const data = fs.readJSONSync(snapshotPath);
164
+ const schema = new DatabaseSchema(this.driver.getPlatform(), this.config.get('schema'));
165
+ const { tables, namespaces, ...rest } = data;
166
+ const tableInstances = tables.map(tbl => {
167
+ const table = new DatabaseTable(this.driver.getPlatform(), tbl.name, tbl.schema);
168
+ table.nativeEnums = tbl.nativeEnums ?? {};
169
+ table.comment = tbl.comment;
170
+ if (tbl.indexes) {
171
+ table.setIndexes(tbl.indexes);
172
+ }
173
+ if (tbl.checks) {
174
+ table.setChecks(tbl.checks);
175
+ }
176
+ if (tbl.foreignKeys) {
177
+ table.setForeignKeys(tbl.foreignKeys);
178
+ }
179
+ const cols = tbl.columns;
180
+ Object.keys(cols).forEach(col => {
181
+ const column = { ...cols[col] };
182
+ /* v8 ignore next */
183
+ column.mappedType = Type.getType(t[cols[col].mappedType] ?? UnknownType);
184
+ table.addColumn(column);
185
+ });
186
+ return table;
187
+ });
188
+ schema.setTables(tableInstances);
189
+ schema.setNamespaces(new Set(namespaces));
190
+ if (rest.nativeEnums) {
191
+ schema.setNativeEnums(rest.nativeEnums);
195
192
  }
196
- async storeCurrentSchema(schema) {
197
- if (!this.options.snapshot) {
198
- return;
199
- }
200
- const snapshotPath = await this.getSnapshotPath();
201
- schema ??= this.#schemaGenerator.getTargetSchema();
202
- const { fs } = await import('@mikro-orm/core/fs-utils');
203
- await fs.writeFile(snapshotPath, JSON.stringify(schema, null, 2));
193
+ if (rest.views) {
194
+ schema.setViews(rest.views);
195
+ }
196
+ return schema;
197
+ }
198
+ async storeCurrentSchema(schema) {
199
+ if (!this.options.snapshot) {
200
+ return;
204
201
  }
205
- async getSchemaDiff(blank, initial) {
206
- const up = [];
207
- const down = [];
208
- // Split SQL by statement boundaries (semicolons followed by newline) rather than
209
- // just newlines, to preserve multiline statements like view definitions.
210
- // Blank lines (from double newlines) are preserved as empty strings for grouping.
211
- // Splits inside single-quoted string literals are re-merged (GH #7185).
212
- const splitStatements = (sql) => {
213
- const result = [];
214
- let buf = '';
215
- for (const chunk of sql.split(/;\n/)) {
216
- buf += (buf ? ';\n' : '') + chunk;
217
- // odd number of single quotes means we're inside a string literal
218
- if (buf.split(`'`).length % 2 === 0) {
219
- continue;
220
- }
221
- // A chunk starting with \n indicates there was a blank line (grouping separator)
222
- if (buf.startsWith('\n')) {
223
- result.push('');
224
- }
225
- const trimmed = buf.trim();
226
- if (trimmed) {
227
- result.push(trimmed.endsWith(';') ? trimmed : trimmed + ';');
228
- }
229
- buf = '';
230
- }
231
- return result;
232
- };
233
- if (blank) {
234
- up.push('select 1');
235
- down.push('select 1');
202
+ const snapshotPath = await this.getSnapshotPath();
203
+ schema ??= this.#schemaGenerator.getTargetSchema();
204
+ const { fs } = await import('@mikro-orm/core/fs-utils');
205
+ await fs.writeFile(snapshotPath, JSON.stringify(schema, null, 2));
206
+ }
207
+ async getSchemaDiff(blank, initial) {
208
+ const up = [];
209
+ const down = [];
210
+ // Split SQL by statement boundaries (semicolons followed by newline) rather than
211
+ // just newlines, to preserve multiline statements like view definitions.
212
+ // Blank lines (from double newlines) are preserved as empty strings for grouping.
213
+ // Splits inside single-quoted string literals are re-merged (GH #7185).
214
+ const splitStatements = sql => {
215
+ const result = [];
216
+ let buf = '';
217
+ for (const chunk of sql.split(/;\n/)) {
218
+ buf += (buf ? ';\n' : '') + chunk;
219
+ // odd number of single quotes means we're inside a string literal
220
+ if (buf.split(`'`).length % 2 === 0) {
221
+ continue;
236
222
  }
237
- else if (initial) {
238
- const dump = await this.#schemaGenerator.getCreateSchemaSQL({ wrap: false });
239
- up.push(...splitStatements(dump));
223
+ // A chunk starting with \n indicates there was a blank line (grouping separator)
224
+ if (buf.startsWith('\n')) {
225
+ result.push('');
240
226
  }
241
- else {
242
- const diff = await this.#schemaGenerator.getUpdateSchemaMigrationSQL({
243
- wrap: false,
244
- safe: this.options.safe,
245
- dropTables: this.options.dropTables,
246
- fromSchema: await this.getSchemaFromSnapshot(),
247
- });
248
- up.push(...splitStatements(diff.up));
249
- down.push(...splitStatements(diff.down));
227
+ const trimmed = buf.trim();
228
+ if (trimmed) {
229
+ result.push(trimmed.endsWith(';') ? trimmed : trimmed + ';');
250
230
  }
251
- const cleanUp = (diff) => {
252
- for (let i = diff.length - 1; i >= 0; i--) {
253
- if (diff[i]) {
254
- break;
255
- }
256
- /* v8 ignore next */
257
- diff.splice(i, 1);
258
- }
259
- };
260
- cleanUp(up);
261
- cleanUp(down);
262
- return { up, down };
231
+ buf = '';
232
+ }
233
+ return result;
234
+ };
235
+ if (blank) {
236
+ up.push('select 1');
237
+ down.push('select 1');
238
+ } else if (initial) {
239
+ const dump = await this.#schemaGenerator.getCreateSchemaSQL({ wrap: false });
240
+ up.push(...splitStatements(dump));
241
+ } else {
242
+ const diff = await this.#schemaGenerator.getUpdateSchemaMigrationSQL({
243
+ wrap: false,
244
+ safe: this.options.safe,
245
+ dropTables: this.options.dropTables,
246
+ fromSchema: await this.getSchemaFromSnapshot(),
247
+ });
248
+ up.push(...splitStatements(diff.up));
249
+ down.push(...splitStatements(diff.down));
263
250
  }
251
+ const cleanUp = diff => {
252
+ for (let i = diff.length - 1; i >= 0; i--) {
253
+ if (diff[i]) {
254
+ break;
255
+ }
256
+ /* v8 ignore next */
257
+ diff.splice(i, 1);
258
+ }
259
+ };
260
+ cleanUp(up);
261
+ cleanUp(down);
262
+ return { up, down };
263
+ }
264
264
  }