@mikro-orm/migrations 7.0.0-dev.9 → 7.0.0-dev.91

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.
@@ -11,7 +11,7 @@ export class JSMigrationGenerator extends MigrationGenerator {
11
11
  ret += ` async up() {\n`;
12
12
  diff.up.forEach(sql => ret += this.createStatement(sql, 4));
13
13
  ret += ` }\n\n`;
14
- /* v8 ignore next 5 */
14
+ /* v8 ignore next */
15
15
  if (diff.down.length > 0) {
16
16
  ret += ` async down() {\n`;
17
17
  diff.down.forEach(sql => ret += this.createStatement(sql, 4));
@@ -1,4 +1,5 @@
1
1
  import { Utils, } from '@mikro-orm/core';
2
+ import { fs } from '@mikro-orm/core/fs-utils';
2
3
  import { writeFile } from 'node:fs/promises';
3
4
  export class MigrationGenerator {
4
5
  driver;
@@ -16,7 +17,7 @@ export class MigrationGenerator {
16
17
  /* v8 ignore next */
17
18
  const defaultPath = this.options.emit === 'ts' && this.options.pathTs ? this.options.pathTs : this.options.path;
18
19
  path = Utils.normalizePath(this.driver.config.get('baseDir'), path ?? defaultPath);
19
- Utils.ensureDir(path);
20
+ fs.ensureDir(path);
20
21
  const timestamp = new Date().toISOString().replace(/[-T:]|\.\d{3}z$/ig, '');
21
22
  const className = this.namingStrategy.classToMigrationName(timestamp, name);
22
23
  const fileName = `${this.options.fileName(timestamp, name)}.${this.options.emit}`;
@@ -39,7 +39,7 @@ export class MigrationRunner {
39
39
  let queries = migration.getQueries();
40
40
  queries.unshift(...this.helper.getSchemaBeginning(charset, this.options.disableForeignKeys).split('\n'));
41
41
  queries.push(...this.helper.getSchemaEnd(this.options.disableForeignKeys).split('\n'));
42
- queries = queries.filter(sql => !Utils.isString(sql) || sql.trim().length > 0);
42
+ queries = queries.filter(sql => typeof sql !== 'string' || sql.trim().length > 0);
43
43
  return queries;
44
44
  }
45
45
  }
@@ -75,7 +75,7 @@ export class MigrationStorage {
75
75
  length,
76
76
  });
77
77
  const sql = this.helper.createTable(table);
78
- await this.connection.execute(sql.join(';\n'));
78
+ await this.connection.execute(sql.join(';\n'), [], 'run', this.masterTransaction);
79
79
  }
80
80
  setMasterMigration(trx) {
81
81
  this.masterTransaction = trx;
package/Migrator.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type MigrationParams, type RunnableMigration } from 'umzug';
2
- import { type Constructor, type IMigrator, type MikroORM, type MigratorEvent, type MaybePromise } from '@mikro-orm/core';
2
+ import { type Constructor, type IMigrator, type MaybePromise, type MigratorEvent, type MikroORM } from '@mikro-orm/core';
3
3
  import { DatabaseSchema, type EntityManager } from '@mikro-orm/knex';
4
4
  import type { Migration } from './Migration.js';
5
5
  import { MigrationStorage } from './MigrationStorage.js';
@@ -17,16 +17,25 @@ export declare class Migrator implements IMigrator {
17
17
  private readonly absolutePath;
18
18
  private readonly snapshotPath;
19
19
  constructor(em: EntityManager);
20
+ /**
21
+ * Checks if `src` folder exists, it so, tries to adjust the migrations and seeders paths automatically to use it.
22
+ * If there is a `dist` or `build` folder, it will be used for the JS variant (`path` option), while the `src` folder will be
23
+ * used for the TS variant (`pathTs` option).
24
+ *
25
+ * If the default folder exists (e.g. `/migrations`), the config will respect that, so this auto-detection should not
26
+ * break existing projects, only help with the new ones.
27
+ */
28
+ private detectSourceFolder;
20
29
  static register(orm: MikroORM): void;
21
30
  /**
22
31
  * @inheritDoc
23
32
  */
24
- createMigration(path?: string, blank?: boolean, initial?: boolean, name?: string): Promise<MigrationResult>;
25
- checkMigrationNeeded(): Promise<boolean>;
33
+ create(path?: string, blank?: boolean, initial?: boolean, name?: string): Promise<MigrationResult>;
34
+ checkSchema(): Promise<boolean>;
26
35
  /**
27
36
  * @inheritDoc
28
37
  */
29
- createInitialMigration(path?: string, name?: string, blank?: boolean): Promise<MigrationResult>;
38
+ createInitial(path?: string, name?: string, blank?: boolean): Promise<MigrationResult>;
30
39
  /**
31
40
  * @inheritDoc
32
41
  */
@@ -48,12 +57,12 @@ export declare class Migrator implements IMigrator {
48
57
  /**
49
58
  * @inheritDoc
50
59
  */
51
- getExecutedMigrations(): Promise<MigrationRow[]>;
60
+ getExecuted(): Promise<MigrationRow[]>;
52
61
  private ensureDatabase;
53
62
  /**
54
63
  * @inheritDoc
55
64
  */
56
- getPendingMigrations(): Promise<UmzugMigration[]>;
65
+ getPending(): Promise<UmzugMigration[]>;
57
66
  /**
58
67
  * @inheritDoc
59
68
  */
package/Migrator.js CHANGED
@@ -1,8 +1,9 @@
1
- import { Umzug } from 'umzug';
1
+ import { Umzug, } from 'umzug';
2
2
  import { basename, join } from 'node:path';
3
3
  import { existsSync, writeFileSync } from 'node:fs';
4
4
  import { t, Type, UnknownType, Utils, } from '@mikro-orm/core';
5
- import { DatabaseSchema, DatabaseTable, SqlSchemaGenerator, } from '@mikro-orm/knex';
5
+ import { fs } from '@mikro-orm/core/fs-utils';
6
+ import { DatabaseSchema, DatabaseTable, } from '@mikro-orm/knex';
6
7
  import { MigrationRunner } from './MigrationRunner.js';
7
8
  import { MigrationStorage } from './MigrationStorage.js';
8
9
  import { TSMigrationGenerator } from './TSMigrationGenerator.js';
@@ -22,9 +23,10 @@ export class Migrator {
22
23
  constructor(em) {
23
24
  this.em = em;
24
25
  this.driver = this.em.getDriver();
25
- this.schemaGenerator = new SqlSchemaGenerator(this.em);
26
26
  this.config = this.em.config;
27
27
  this.options = this.config.get('migrations');
28
+ this.schemaGenerator = this.config.getExtension('@mikro-orm/schema-generator');
29
+ this.detectSourceFolder();
28
30
  /* v8 ignore next */
29
31
  const key = (this.config.get('preferTs', Utils.detectTypeScriptSupport()) && this.options.pathTs) ? 'pathTs' : 'path';
30
32
  this.absolutePath = Utils.absolutePath(this.options[key], this.config.get('baseDir'));
@@ -37,15 +39,42 @@ export class Migrator {
37
39
  this.snapshotPath = Utils.normalizePath(absoluteSnapshotPath, `${snapshotName}.json`);
38
40
  this.createUmzug();
39
41
  }
42
+ /**
43
+ * Checks if `src` folder exists, it so, tries to adjust the migrations and seeders paths automatically to use it.
44
+ * If there is a `dist` or `build` folder, it will be used for the JS variant (`path` option), while the `src` folder will be
45
+ * used for the TS variant (`pathTs` option).
46
+ *
47
+ * If the default folder exists (e.g. `/migrations`), the config will respect that, so this auto-detection should not
48
+ * break existing projects, only help with the new ones.
49
+ */
50
+ detectSourceFolder() {
51
+ const baseDir = this.config.get('baseDir');
52
+ const defaultPath = './migrations';
53
+ if (!fs.pathExists(baseDir + '/src')) {
54
+ this.options.path ??= defaultPath;
55
+ return;
56
+ }
57
+ const exists = fs.pathExists(`${baseDir}/${defaultPath}`);
58
+ const distDir = fs.pathExists(baseDir + '/dist');
59
+ const buildDir = fs.pathExists(baseDir + '/build');
60
+ // if neither `dist` nor `build` exist, we use the `src` folder as it might be a JS project without building, but with `src` folder
61
+ /* v8 ignore next */
62
+ const path = distDir ? './dist' : (buildDir ? './build' : './src');
63
+ // only if the user did not provide any values and if the default path does not exist
64
+ if (!this.options.path && !this.options.pathTs && !exists) {
65
+ this.options.path = `${path}/migrations`;
66
+ this.options.pathTs = './src/migrations';
67
+ }
68
+ }
40
69
  static register(orm) {
41
70
  orm.config.registerExtension('@mikro-orm/migrator', () => new Migrator(orm.em));
42
71
  }
43
72
  /**
44
73
  * @inheritDoc
45
74
  */
46
- async createMigration(path, blank = false, initial = false, name) {
75
+ async create(path, blank = false, initial = false, name) {
47
76
  if (initial) {
48
- return this.createInitialMigration(path, name, blank);
77
+ return this.createInitial(path, name, blank);
49
78
  }
50
79
  this.ensureMigrationsDirExists();
51
80
  const diff = await this.getSchemaDiff(blank, initial);
@@ -60,7 +89,7 @@ export class Migrator {
60
89
  diff,
61
90
  };
62
91
  }
63
- async checkMigrationNeeded() {
92
+ async checkSchema() {
64
93
  this.ensureMigrationsDirExists();
65
94
  const diff = await this.getSchemaDiff(false, false);
66
95
  return diff.up.length > 0;
@@ -68,7 +97,7 @@ export class Migrator {
68
97
  /**
69
98
  * @inheritDoc
70
99
  */
71
- async createInitialMigration(path, name, blank = false) {
100
+ async createInitial(path, name, blank = false) {
72
101
  this.ensureMigrationsDirExists();
73
102
  const schemaExists = await this.validateInitialMigration(blank);
74
103
  const diff = await this.getSchemaDiff(blank, true);
@@ -117,6 +146,7 @@ export class Migrator {
117
146
  logger: undefined,
118
147
  migrations,
119
148
  });
149
+ /* v8 ignore else */
120
150
  if (!this.options.silent) {
121
151
  const logger = this.config.getLogger();
122
152
  this.umzug.on('migrating', event => logger.log('migrator', `Processing '${event.name}'`, { enabled: true }));
@@ -143,8 +173,8 @@ export class Migrator {
143
173
  * If only some of the tables are present, exception is thrown.
144
174
  */
145
175
  async validateInitialMigration(blank) {
146
- const executed = await this.getExecutedMigrations();
147
- const pending = await this.getPendingMigrations();
176
+ const executed = await this.getExecuted();
177
+ const pending = await this.getPending();
148
178
  if (executed.length > 0 || pending.length > 0) {
149
179
  throw new Error('Initial migration cannot be created, as some migrations already exist');
150
180
  }
@@ -175,14 +205,14 @@ export class Migrator {
175
205
  /**
176
206
  * @inheritDoc
177
207
  */
178
- async getExecutedMigrations() {
208
+ async getExecuted() {
179
209
  await this.ensureDatabase();
180
210
  return this.storage.getExecutedMigrations();
181
211
  }
182
212
  async ensureDatabase() {
183
213
  this.ensureMigrationsDirExists();
184
214
  const created = await this.schemaGenerator.ensureDatabase();
185
- /* v8 ignore next 3 */
215
+ /* v8 ignore next */
186
216
  if (created) {
187
217
  this.createUmzug();
188
218
  }
@@ -191,7 +221,7 @@ export class Migrator {
191
221
  /**
192
222
  * @inheritDoc
193
223
  */
194
- async getPendingMigrations() {
224
+ async getPending() {
195
225
  await this.ensureDatabase();
196
226
  return this.umzug.pending();
197
227
  }
@@ -213,7 +243,7 @@ export class Migrator {
213
243
  resolve(params) {
214
244
  const createMigrationHandler = async (method) => {
215
245
  const migration = await Utils.dynamicImport(params.path);
216
- const MigrationClass = Object.values(migration)[0];
246
+ const MigrationClass = Object.values(migration).find(cls => typeof cls === 'function' && typeof cls.constructor === 'function');
217
247
  const instance = new MigrationClass(this.driver, this.config);
218
248
  await this.runner.run(instance, method);
219
249
  };
@@ -227,7 +257,7 @@ export class Migrator {
227
257
  if (!this.options.snapshot || !existsSync(this.snapshotPath)) {
228
258
  return undefined;
229
259
  }
230
- const data = Utils.readJSONSync(this.snapshotPath);
260
+ const data = fs.readJSONSync(this.snapshotPath);
231
261
  const schema = new DatabaseSchema(this.driver.getPlatform(), this.config.get('schema'));
232
262
  const { tables, namespaces, ...rest } = data;
233
263
  const tableInstances = tables.map((tbl) => {
@@ -298,7 +328,7 @@ export class Migrator {
298
328
  return name.match(/^\d{14}$/) ? this.options.fileName(name) : name;
299
329
  }
300
330
  prefix(options) {
301
- if (Utils.isString(options) || Array.isArray(options)) {
331
+ if (typeof options === 'string' || Array.isArray(options)) {
302
332
  return { migrations: Utils.asArray(options).map(name => this.getMigrationFilename(name)) };
303
333
  }
304
334
  if (!options) {
@@ -333,7 +363,7 @@ export class Migrator {
333
363
  }
334
364
  ensureMigrationsDirExists() {
335
365
  if (!this.options.migrationsList) {
336
- Utils.ensureDir(this.absolutePath);
366
+ fs.ensureDir(this.absolutePath);
337
367
  }
338
368
  }
339
369
  }
package/README.md CHANGED
@@ -11,7 +11,6 @@ TypeScript ORM for Node.js based on Data Mapper, [Unit of Work](https://mikro-or
11
11
  [![Chat on discord](https://img.shields.io/discord/1214904142443839538?label=discord&color=blue)](https://discord.gg/w8bjxFHS7X)
12
12
  [![Downloads](https://img.shields.io/npm/dm/@mikro-orm/core.svg)](https://www.npmjs.com/package/@mikro-orm/core)
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
- [![Maintainability](https://api.codeclimate.com/v1/badges/27999651d3adc47cfa40/maintainability)](https://codeclimate.com/github/mikro-orm/mikro-orm/maintainability)
15
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)
16
15
 
17
16
  ## 🤔 Unit of What?
@@ -141,7 +140,7 @@ There is also auto-generated [CHANGELOG.md](CHANGELOG.md) file based on commit m
141
140
  - [Composite and Foreign Keys as Primary Key](https://mikro-orm.io/docs/composite-keys)
142
141
  - [Filters](https://mikro-orm.io/docs/filters)
143
142
  - [Using `QueryBuilder`](https://mikro-orm.io/docs/query-builder)
144
- - [Preloading Deeply Nested Structures via populate](https://mikro-orm.io/docs/nested-populate)
143
+ - [Populating relations](https://mikro-orm.io/docs/populating-relations)
145
144
  - [Property Validation](https://mikro-orm.io/docs/property-validation)
146
145
  - [Lifecycle Hooks](https://mikro-orm.io/docs/events#hooks)
147
146
  - [Vanilla JS Support](https://mikro-orm.io/docs/usage-with-js)
@@ -382,6 +381,8 @@ See also the list of contributors who [participated](https://github.com/mikro-or
382
381
 
383
382
  Please ⭐️ this repository if this project helped you!
384
383
 
384
+ > If you'd like to support my open-source work, consider sponsoring me directly at [github.com/sponsors/b4nan](https://github.com/sponsors/b4nan).
385
+
385
386
  ## 📝 License
386
387
 
387
388
  Copyright © 2018 [Martin Adámek](https://github.com/b4nan).
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mikro-orm/migrations",
3
3
  "type": "module",
4
- "version": "7.0.0-dev.9",
4
+ "version": "7.0.0-dev.91",
5
5
  "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.",
6
6
  "exports": {
7
7
  "./package.json": "./package.json",
@@ -38,7 +38,7 @@
38
38
  },
39
39
  "homepage": "https://mikro-orm.io",
40
40
  "engines": {
41
- "node": ">= 22.11.0"
41
+ "node": ">= 22.17.0"
42
42
  },
43
43
  "scripts": {
44
44
  "build": "yarn clean && yarn compile && yarn copy",
@@ -50,13 +50,13 @@
50
50
  "access": "public"
51
51
  },
52
52
  "dependencies": {
53
- "@mikro-orm/knex": "7.0.0-dev.9",
53
+ "@mikro-orm/knex": "7.0.0-dev.91",
54
54
  "umzug": "3.8.2"
55
55
  },
56
56
  "devDependencies": {
57
- "@mikro-orm/core": "^6.4.13"
57
+ "@mikro-orm/core": "^6.6.2"
58
58
  },
59
59
  "peerDependencies": {
60
- "@mikro-orm/core": "7.0.0-dev.9"
60
+ "@mikro-orm/core": "7.0.0-dev.91"
61
61
  }
62
62
  }
package/typings.d.ts CHANGED
@@ -1 +1 @@
1
- export { UmzugMigration, MigrateOptions, MigrationResult, MigrationRow } from '@mikro-orm/core';
1
+ export type { UmzugMigration, MigrateOptions, MigrationResult, MigrationRow } from '@mikro-orm/core';