@mikro-orm/cli 7.0.4-dev.9 → 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,213 +1,214 @@
1
- import { colors, Utils, } from '@mikro-orm/core';
1
+ import { colors, Utils } from '@mikro-orm/core';
2
2
  import { CLIHelper } from '../CLIHelper.js';
3
3
  export class MigrationCommandFactory {
4
- static DESCRIPTIONS = {
5
- create: 'Create new migration with current schema diff',
6
- up: 'Migrate up to the latest version',
7
- down: 'Migrate one step down',
8
- list: 'List all executed migrations',
9
- check: 'Check if migrations are needed. Useful for bash scripts.',
10
- pending: 'List all pending migrations',
11
- fresh: 'Clear the database and rerun all migrations',
12
- };
13
- static create(command) {
14
- // oxfmt-ignore
15
- return {
4
+ static DESCRIPTIONS = {
5
+ create: 'Create new migration with current schema diff',
6
+ up: 'Migrate up to the latest version',
7
+ down: 'Migrate one step down',
8
+ list: 'List all executed migrations',
9
+ check: 'Check if migrations are needed. Useful for bash scripts.',
10
+ pending: 'List all pending migrations',
11
+ fresh: 'Clear the database and rerun all migrations',
12
+ };
13
+ static create(command) {
14
+ // oxfmt-ignore
15
+ return {
16
16
  command: `migration:${command}`,
17
17
  describe: MigrationCommandFactory.DESCRIPTIONS[command],
18
18
  builder: (args) => MigrationCommandFactory.configureMigrationCommand(args, command),
19
19
  handler: (args) => MigrationCommandFactory.handleMigrationCommand(args, command),
20
20
  };
21
+ }
22
+ static configureMigrationCommand(args, method) {
23
+ if (method === 'create') {
24
+ return this.configureCreateCommand(args);
21
25
  }
22
- static configureMigrationCommand(args, method) {
23
- if (method === 'create') {
24
- return this.configureCreateCommand(args);
25
- }
26
- if (method === 'up' || method === 'down') {
27
- return this.configureUpDownCommand(args, method);
28
- }
29
- if (method === 'fresh') {
30
- return this.configureFreshCommand(args);
31
- }
32
- return args;
26
+ if (method === 'up' || method === 'down') {
27
+ return this.configureUpDownCommand(args, method);
33
28
  }
34
- static configureUpDownCommand(args, method) {
35
- args.option('t', {
36
- alias: 'to',
37
- type: 'string',
38
- desc: `Migrate ${method} to specific version`,
39
- });
40
- args.option('f', {
41
- alias: 'from',
42
- type: 'string',
43
- desc: 'Start migration from specific version',
44
- });
45
- args.option('o', {
46
- alias: 'only',
47
- type: 'string',
48
- desc: 'Migrate only specified versions',
49
- });
50
- return args;
29
+ if (method === 'fresh') {
30
+ return this.configureFreshCommand(args);
51
31
  }
52
- static configureCreateCommand(args) {
53
- args.option('b', {
54
- alias: 'blank',
55
- type: 'boolean',
56
- desc: 'Create blank migration',
57
- });
58
- args.option('i', {
59
- alias: 'initial',
60
- type: 'boolean',
61
- desc: 'Create initial migration',
62
- });
63
- args.option('d', {
64
- alias: 'dump',
65
- type: 'boolean',
66
- desc: 'Dumps all queries to console',
67
- });
68
- args.option('p', {
69
- alias: 'path',
70
- type: 'string',
71
- desc: 'Sets path to directory where to save entities',
72
- });
73
- args.option('n', {
74
- alias: 'name',
75
- type: 'string',
76
- desc: 'Specify custom name for the file',
77
- });
78
- return args;
32
+ return args;
33
+ }
34
+ static configureUpDownCommand(args, method) {
35
+ args.option('t', {
36
+ alias: 'to',
37
+ type: 'string',
38
+ desc: `Migrate ${method} to specific version`,
39
+ });
40
+ args.option('f', {
41
+ alias: 'from',
42
+ type: 'string',
43
+ desc: 'Start migration from specific version',
44
+ });
45
+ args.option('o', {
46
+ alias: 'only',
47
+ type: 'string',
48
+ desc: 'Migrate only specified versions',
49
+ });
50
+ return args;
51
+ }
52
+ static configureCreateCommand(args) {
53
+ args.option('b', {
54
+ alias: 'blank',
55
+ type: 'boolean',
56
+ desc: 'Create blank migration',
57
+ });
58
+ args.option('i', {
59
+ alias: 'initial',
60
+ type: 'boolean',
61
+ desc: 'Create initial migration',
62
+ });
63
+ args.option('d', {
64
+ alias: 'dump',
65
+ type: 'boolean',
66
+ desc: 'Dumps all queries to console',
67
+ });
68
+ args.option('p', {
69
+ alias: 'path',
70
+ type: 'string',
71
+ desc: 'Sets path to directory where to save entities',
72
+ });
73
+ args.option('n', {
74
+ alias: 'name',
75
+ type: 'string',
76
+ desc: 'Specify custom name for the file',
77
+ });
78
+ return args;
79
+ }
80
+ static async handleMigrationCommand(args, method) {
81
+ // to be able to run have a master transaction, but run marked migrations outside of it, we need a second connection
82
+ const options = { pool: { min: 1, max: 2 } };
83
+ const orm = await CLIHelper.getORM(args.contextName, args.config, options);
84
+ switch (method) {
85
+ case 'create':
86
+ await this.handleCreateCommand(orm.migrator, args, orm.config);
87
+ break;
88
+ case 'check':
89
+ await this.handleCheckCommand(orm.migrator, orm);
90
+ break;
91
+ case 'list':
92
+ await this.handleListCommand(orm.migrator);
93
+ break;
94
+ case 'pending':
95
+ await this.handlePendingCommand(orm.migrator);
96
+ break;
97
+ case 'up':
98
+ case 'down':
99
+ await this.handleUpDownCommand(args, orm.migrator, method);
100
+ break;
101
+ case 'fresh':
102
+ await this.handleFreshCommand(args, orm.migrator, orm);
79
103
  }
80
- static async handleMigrationCommand(args, method) {
81
- // to be able to run have a master transaction, but run marked migrations outside of it, we need a second connection
82
- const options = { pool: { min: 1, max: 2 } };
83
- const orm = await CLIHelper.getORM(args.contextName, args.config, options);
84
- switch (method) {
85
- case 'create':
86
- await this.handleCreateCommand(orm.migrator, args, orm.config);
87
- break;
88
- case 'check':
89
- await this.handleCheckCommand(orm.migrator, orm);
90
- break;
91
- case 'list':
92
- await this.handleListCommand(orm.migrator);
93
- break;
94
- case 'pending':
95
- await this.handlePendingCommand(orm.migrator);
96
- break;
97
- case 'up':
98
- case 'down':
99
- await this.handleUpDownCommand(args, orm.migrator, method);
100
- break;
101
- case 'fresh':
102
- await this.handleFreshCommand(args, orm.migrator, orm);
103
- }
104
- await orm.close(true);
104
+ await orm.close(true);
105
+ }
106
+ static configureFreshCommand(args) {
107
+ args.option('seed', {
108
+ type: 'string',
109
+ desc: 'Allows to seed the database after dropping it and rerunning all migrations',
110
+ });
111
+ args.option('drop-db', {
112
+ type: 'boolean',
113
+ desc: 'Drop the whole database',
114
+ });
115
+ return args;
116
+ }
117
+ static async handleUpDownCommand(args, migrator, method) {
118
+ const opts = MigrationCommandFactory.getUpDownOptions(args);
119
+ await migrator[method](opts);
120
+ const message = this.getUpDownSuccessMessage(method, opts);
121
+ CLIHelper.dump(colors.green(message));
122
+ }
123
+ static async handlePendingCommand(migrator) {
124
+ const pending = await migrator.getPending();
125
+ CLIHelper.dumpTable({
126
+ columns: ['Name'],
127
+ rows: pending.map(row => [row.name]),
128
+ empty: 'No pending migrations',
129
+ });
130
+ }
131
+ static async handleListCommand(migrator) {
132
+ const executed = await migrator.getExecuted();
133
+ CLIHelper.dumpTable({
134
+ columns: ['Name', 'Executed at'],
135
+ rows: executed.map(row => {
136
+ /* v8 ignore next */
137
+ const executedAt = (row.executed_at ?? row.created_at)?.toISOString() ?? '';
138
+ return [row.name.replace(/\.[jt]s$/, ''), executedAt];
139
+ }),
140
+ empty: 'No migrations executed yet',
141
+ });
142
+ }
143
+ static async handleCreateCommand(migrator, args, config) {
144
+ const ret = await migrator.create(args.path, args.blank, args.initial, args.name);
145
+ if (ret.diff.up.length === 0) {
146
+ return CLIHelper.dump(colors.green(`No changes required, schema is up-to-date`));
105
147
  }
106
- static configureFreshCommand(args) {
107
- args.option('seed', {
108
- type: 'string',
109
- desc: 'Allows to seed the database after dropping it and rerunning all migrations',
110
- });
111
- args.option('drop-db', {
112
- type: 'boolean',
113
- desc: 'Drop the whole database',
114
- });
115
- return args;
148
+ if (args.dump) {
149
+ CLIHelper.dump(colors.green('Creating migration with following queries:'));
150
+ CLIHelper.dump(colors.green('up:'));
151
+ CLIHelper.dump(ret.diff.up.map(sql => ' ' + sql).join('\n'), config);
152
+ /* v8 ignore if */
153
+ if (config.getDriver().getPlatform().supportsDownMigrations()) {
154
+ CLIHelper.dump(colors.green('down:'));
155
+ CLIHelper.dump(ret.diff.down.map(sql => ' ' + sql).join('\n'), config);
156
+ } else {
157
+ /* v8 ignore next */
158
+ CLIHelper.dump(
159
+ colors.yellow(`(${config.getDriver().constructor.name} does not support automatic down migrations)`),
160
+ );
161
+ }
116
162
  }
117
- static async handleUpDownCommand(args, migrator, method) {
118
- const opts = MigrationCommandFactory.getUpDownOptions(args);
119
- await migrator[method](opts);
120
- const message = this.getUpDownSuccessMessage(method, opts);
121
- CLIHelper.dump(colors.green(message));
163
+ CLIHelper.dump(colors.green(`${ret.fileName} successfully created`));
164
+ }
165
+ static async handleCheckCommand(migrator, orm) {
166
+ if (!(await migrator.checkSchema())) {
167
+ return CLIHelper.dump(colors.green(`No changes required, schema is up-to-date`));
122
168
  }
123
- static async handlePendingCommand(migrator) {
124
- const pending = await migrator.getPending();
125
- CLIHelper.dumpTable({
126
- columns: ['Name'],
127
- rows: pending.map(row => [row.name]),
128
- empty: 'No pending migrations',
129
- });
169
+ await orm.close(true);
170
+ CLIHelper.dump(colors.yellow(`Changes detected. Please create migration to update schema.`));
171
+ process.exit(1);
172
+ }
173
+ static async handleFreshCommand(args, migrator, orm) {
174
+ await orm.schema.drop({ dropMigrationsTable: true, dropDb: args.dropDb });
175
+ CLIHelper.dump(colors.green('Dropped schema successfully'));
176
+ const opts = MigrationCommandFactory.getUpDownOptions(args);
177
+ await migrator.up(opts);
178
+ const message = this.getUpDownSuccessMessage('up', opts);
179
+ CLIHelper.dump(colors.green(message));
180
+ if (args.seed !== undefined) {
181
+ const seederClass = args.seed || orm.config.get('seeder').defaultSeeder;
182
+ await orm.seeder.seedString(seederClass);
183
+ CLIHelper.dump(colors.green(`Database seeded successfully with seeder class ${seederClass}`));
130
184
  }
131
- static async handleListCommand(migrator) {
132
- const executed = await migrator.getExecuted();
133
- CLIHelper.dumpTable({
134
- columns: ['Name', 'Executed at'],
135
- rows: executed.map(row => {
136
- /* v8 ignore next */
137
- const executedAt = (row.executed_at ?? row.created_at)?.toISOString() ?? '';
138
- return [row.name.replace(/\.[jt]s$/, ''), executedAt];
139
- }),
140
- empty: 'No migrations executed yet',
141
- });
185
+ }
186
+ static getUpDownOptions(flags) {
187
+ if (!flags.to && !flags.from && flags.only) {
188
+ return { migrations: flags.only.split(/[, ]+/) };
142
189
  }
143
- static async handleCreateCommand(migrator, args, config) {
144
- const ret = await migrator.create(args.path, args.blank, args.initial, args.name);
145
- if (ret.diff.up.length === 0) {
146
- return CLIHelper.dump(colors.green(`No changes required, schema is up-to-date`));
147
- }
148
- if (args.dump) {
149
- CLIHelper.dump(colors.green('Creating migration with following queries:'));
150
- CLIHelper.dump(colors.green('up:'));
151
- CLIHelper.dump(ret.diff.up.map(sql => ' ' + sql).join('\n'), config);
152
- /* v8 ignore if */
153
- if (config.getDriver().getPlatform().supportsDownMigrations()) {
154
- CLIHelper.dump(colors.green('down:'));
155
- CLIHelper.dump(ret.diff.down.map(sql => ' ' + sql).join('\n'), config);
156
- }
157
- else {
158
- /* v8 ignore next */
159
- CLIHelper.dump(colors.yellow(`(${config.getDriver().constructor.name} does not support automatic down migrations)`));
160
- }
161
- }
162
- CLIHelper.dump(colors.green(`${ret.fileName} successfully created`));
190
+ const ret = {};
191
+ ['from', 'to'].filter(k => flags[k]).forEach(k => (ret[k] = flags[k] === '0' ? 0 : flags[k]));
192
+ return ret;
193
+ }
194
+ static getUpDownSuccessMessage(method, options) {
195
+ const msg = `Successfully migrated ${method}`;
196
+ if (method === 'down' && Utils.isEmpty(options)) {
197
+ return msg + ' to previous version';
163
198
  }
164
- static async handleCheckCommand(migrator, orm) {
165
- if (!(await migrator.checkSchema())) {
166
- return CLIHelper.dump(colors.green(`No changes required, schema is up-to-date`));
167
- }
168
- await orm.close(true);
169
- CLIHelper.dump(colors.yellow(`Changes detected. Please create migration to update schema.`));
170
- process.exit(1);
199
+ if (options.to === 0) {
200
+ const v = { down: 'first', up: 'latest' }[method];
201
+ return `${msg} to the ${v} version`;
171
202
  }
172
- static async handleFreshCommand(args, migrator, orm) {
173
- await orm.schema.drop({ dropMigrationsTable: true, dropDb: args.dropDb });
174
- CLIHelper.dump(colors.green('Dropped schema successfully'));
175
- const opts = MigrationCommandFactory.getUpDownOptions(args);
176
- await migrator.up(opts);
177
- const message = this.getUpDownSuccessMessage('up', opts);
178
- CLIHelper.dump(colors.green(message));
179
- if (args.seed !== undefined) {
180
- const seederClass = args.seed || orm.config.get('seeder').defaultSeeder;
181
- await orm.seeder.seedString(seederClass);
182
- CLIHelper.dump(colors.green(`Database seeded successfully with seeder class ${seederClass}`));
183
- }
203
+ if (method === 'up' && Utils.isEmpty(options)) {
204
+ return msg + ' to the latest version';
184
205
  }
185
- static getUpDownOptions(flags) {
186
- if (!flags.to && !flags.from && flags.only) {
187
- return { migrations: flags.only.split(/[, ]+/) };
188
- }
189
- const ret = {};
190
- ['from', 'to'].filter(k => flags[k]).forEach(k => (ret[k] = flags[k] === '0' ? 0 : flags[k]));
191
- return ret;
206
+ if (typeof options.to === 'string') {
207
+ return msg + ' to version ' + options.to;
192
208
  }
193
- static getUpDownSuccessMessage(method, options) {
194
- const msg = `Successfully migrated ${method}`;
195
- if (method === 'down' && Utils.isEmpty(options)) {
196
- return msg + ' to previous version';
197
- }
198
- if (options.to === 0) {
199
- const v = { down: 'first', up: 'latest' }[method];
200
- return `${msg} to the ${v} version`;
201
- }
202
- if (method === 'up' && Utils.isEmpty(options)) {
203
- return msg + ' to the latest version';
204
- }
205
- if (typeof options.to === 'string') {
206
- return msg + ' to version ' + options.to;
207
- }
208
- if (options.migrations?.length === 1) {
209
- return msg + ' to version ' + options.migrations[0];
210
- }
211
- return msg;
209
+ if (options.migrations?.length === 1) {
210
+ return msg + ' to version ' + options.migrations[0];
212
211
  }
212
+ return msg;
213
+ }
213
214
  }
@@ -1,51 +1,61 @@
1
1
  import type { ArgumentsCamelCase, Argv } from 'yargs';
2
2
  import type { BaseArgs } from '../CLIConfigurator.js';
3
3
  export declare class SchemaCommandFactory {
4
- static readonly DESCRIPTIONS: {
5
- readonly create: "Create database schema based on current metadata";
6
- readonly update: "Update database schema based on current metadata";
7
- readonly drop: "Drop database schema based on current metadata";
8
- readonly fresh: "Drop and recreate database schema based on current metadata";
9
- };
10
- static readonly SUCCESS_MESSAGES: {
11
- readonly create: "Schema successfully created";
12
- readonly update: "Schema successfully updated";
13
- readonly drop: "Schema successfully dropped";
14
- readonly fresh: "Schema successfully dropped and recreated";
15
- };
16
- static create<const T extends SchemaMethod>(command: T): {
17
- command: string;
18
- describe: "Create database schema based on current metadata" | "Update database schema based on current metadata" | "Drop database schema based on current metadata" | "Drop and recreate database schema based on current metadata";
19
- builder: (args: Argv<BaseArgs>) => Argv<OptionsMap[T]>;
20
- handler: (args: ArgumentsCamelCase<OptionsMap[T]>) => Promise<void>;
21
- };
22
- static configureSchemaCommand<const T extends SchemaMethod>(args: Argv<BaseArgs>, command: T): Argv<OptionsMap[T]>;
23
- static handleSchemaCommand(args: ArgumentsCamelCase<Options>, method: SchemaMethod, successMessage: string): Promise<void>;
4
+ static readonly DESCRIPTIONS: {
5
+ readonly create: 'Create database schema based on current metadata';
6
+ readonly update: 'Update database schema based on current metadata';
7
+ readonly drop: 'Drop database schema based on current metadata';
8
+ readonly fresh: 'Drop and recreate database schema based on current metadata';
9
+ };
10
+ static readonly SUCCESS_MESSAGES: {
11
+ readonly create: 'Schema successfully created';
12
+ readonly update: 'Schema successfully updated';
13
+ readonly drop: 'Schema successfully dropped';
14
+ readonly fresh: 'Schema successfully dropped and recreated';
15
+ };
16
+ static create<const T extends SchemaMethod>(
17
+ command: T,
18
+ ): {
19
+ command: string;
20
+ describe:
21
+ | 'Create database schema based on current metadata'
22
+ | 'Update database schema based on current metadata'
23
+ | 'Drop database schema based on current metadata'
24
+ | 'Drop and recreate database schema based on current metadata';
25
+ builder: (args: Argv<BaseArgs>) => Argv<OptionsMap[T]>;
26
+ handler: (args: ArgumentsCamelCase<OptionsMap[T]>) => Promise<void>;
27
+ };
28
+ static configureSchemaCommand<const T extends SchemaMethod>(args: Argv<BaseArgs>, command: T): Argv<OptionsMap[T]>;
29
+ static handleSchemaCommand(
30
+ args: ArgumentsCamelCase<Options>,
31
+ method: SchemaMethod,
32
+ successMessage: string,
33
+ ): Promise<void>;
24
34
  }
25
35
  type SchemaOptions = BaseArgs & {
26
- run?: boolean;
27
- schema?: string;
36
+ run?: boolean;
37
+ schema?: string;
28
38
  };
29
39
  type NonFreshOptions = SchemaOptions & {
30
- dump?: boolean;
31
- fkChecks?: boolean;
40
+ dump?: boolean;
41
+ fkChecks?: boolean;
32
42
  };
33
43
  export type SchemaCreateOptions = NonFreshOptions & {
34
- seed?: string;
44
+ seed?: string;
35
45
  };
36
46
  export type SchemaUpdateOptions = NonFreshOptions & {
37
- safe?: boolean;
38
- dropTables?: boolean;
47
+ safe?: boolean;
48
+ dropTables?: boolean;
39
49
  };
40
50
  export type SchemaDropOptions = NonFreshOptions & {
41
- dropDb?: boolean;
51
+ dropDb?: boolean;
42
52
  };
43
53
  export type SchemaFreshOptions = SchemaOptions & Omit<SchemaCreateOptions & SchemaDropOptions, keyof NonFreshOptions>;
44
54
  type OptionsMap = {
45
- create: SchemaCreateOptions;
46
- update: SchemaUpdateOptions;
47
- drop: SchemaDropOptions;
48
- fresh: SchemaFreshOptions;
55
+ create: SchemaCreateOptions;
56
+ update: SchemaUpdateOptions;
57
+ drop: SchemaDropOptions;
58
+ fresh: SchemaFreshOptions;
49
59
  };
50
60
  type SchemaMethod = keyof OptionsMap;
51
61
  export type Options = SchemaCreateOptions & SchemaUpdateOptions & SchemaDropOptions & SchemaFreshOptions;