/
MigrationExecutor.ts
404 lines (340 loc) · 18.3 KB
/
MigrationExecutor.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import {Table} from "../schema-builder/table/Table";
import {Connection} from "../connection/Connection";
import {Migration} from "./Migration";
import {ObjectLiteral} from "../common/ObjectLiteral";
import {PromiseUtils} from "../util/PromiseUtils";
import {QueryRunner} from "../query-runner/QueryRunner";
import {SqlServerDriver} from "../driver/sqlserver/SqlServerDriver";
import {MssqlParameter} from "../driver/sqlserver/MssqlParameter";
import {SqlServerConnectionOptions} from "../driver/sqlserver/SqlServerConnectionOptions";
import {PostgresConnectionOptions} from "../driver/postgres/PostgresConnectionOptions";
import { MongoDriver } from "../driver/mongodb/MongoDriver";
import { MongoQueryRunner } from "../driver/mongodb/MongoQueryRunner";
/**
* Executes migrations: runs pending and reverts previously executed migrations.
*/
export class MigrationExecutor {
// -------------------------------------------------------------------------
// Public Properties
// -------------------------------------------------------------------------
/**
* Indicates if migrations must be executed in a transaction.
*/
transaction: boolean = true;
// -------------------------------------------------------------------------
// Private Properties
// -------------------------------------------------------------------------
private readonly migrationsTable: string;
private readonly migrationsTableName: string;
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor(protected connection: Connection,
protected queryRunner?: QueryRunner) {
const options = <SqlServerConnectionOptions|PostgresConnectionOptions>this.connection.driver.options;
this.migrationsTableName = connection.options.migrationsTableName || "migrations";
this.migrationsTable = this.connection.driver.buildTableName(this.migrationsTableName, options.schema, options.database);
}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Lists all migrations and whether they have been executed or not
* returns true if there are unapplied migrations
*/
async showMigrations(): Promise<boolean> {
let hasUnappliedMigrations = false;
const queryRunner = this.queryRunner || this.connection.createQueryRunner("master");
// create migrations table if its not created yet
await this.createMigrationsTableIfNotExist(queryRunner);
// get all migrations that are executed and saved in the database
const executedMigrations = await this.loadExecutedMigrations(queryRunner);
// get all user's migrations in the source code
const allMigrations = this.getMigrations();
for (const migration of allMigrations) {
const executedMigration = executedMigrations.find(executedMigration => executedMigration.name === migration.name);
if (executedMigration) {
this.connection.logger.logSchemaBuild(` [X] ${migration.name}`);
} else {
hasUnappliedMigrations = true;
this.connection.logger.logSchemaBuild(` [ ] ${migration.name}`);
}
}
// if query runner was created by us then release it
if (!this.queryRunner) {
await queryRunner.release();
}
return hasUnappliedMigrations;
}
/**
* Executes all pending migrations. Pending migrations are migrations that are not yet executed,
* thus not saved in the database.
*/
async executePendingMigrations(): Promise<Migration[]> {
const queryRunner = this.queryRunner || this.connection.createQueryRunner("master");
// create migrations table if its not created yet
await this.createMigrationsTableIfNotExist(queryRunner);
// get all migrations that are executed and saved in the database
const executedMigrations = await this.loadExecutedMigrations(queryRunner);
// get the time when last migration was executed
let lastTimeExecutedMigration = this.getLatestTimestampMigration(executedMigrations);
// get all user's migrations in the source code
const allMigrations = this.getMigrations();
// variable to store all migrations we did successefuly
const successMigrations: Migration[] = [];
// find all migrations that needs to be executed
const pendingMigrations = allMigrations.filter(migration => {
// check if we already have executed migration
const executedMigration = executedMigrations.find(executedMigration => executedMigration.name === migration.name);
if (executedMigration)
return false;
// migration is new and not executed. now check if its timestamp is correct
// if (lastTimeExecutedMigration && migration.timestamp < lastTimeExecutedMigration.timestamp)
// throw new Error(`New migration found: ${migration.name}, however this migration's timestamp is not valid. Migration's timestamp should not be older then migrations already executed in the database.`);
// every check is passed means that migration was not run yet and we need to run it
return true;
});
// if no migrations are pending then nothing to do here
if (!pendingMigrations.length) {
this.connection.logger.logSchemaBuild(`No migrations are pending`);
// if query runner was created by us then release it
if (!this.queryRunner)
await queryRunner.release();
return [];
}
// log information about migration execution
this.connection.logger.logSchemaBuild(`${executedMigrations.length} migrations are already loaded in the database.`);
this.connection.logger.logSchemaBuild(`${allMigrations.length} migrations were found in the source code.`);
if (lastTimeExecutedMigration)
this.connection.logger.logSchemaBuild(`${lastTimeExecutedMigration.name} is the last executed migration. It was executed on ${new Date(lastTimeExecutedMigration.timestamp).toString()}.`);
this.connection.logger.logSchemaBuild(`${pendingMigrations.length} migrations are new migrations that needs to be executed.`);
// start transaction if its not started yet
let transactionStartedByUs = false;
if (this.transaction && !queryRunner.isTransactionActive) {
await queryRunner.startTransaction();
transactionStartedByUs = true;
}
// run all pending migrations in a sequence
try {
await PromiseUtils.runInSequence(pendingMigrations, migration => {
return migration.instance!.up(queryRunner)
.then(() => { // now when migration is executed we need to insert record about it into the database
return this.insertExecutedMigration(queryRunner, migration);
})
.then(() => { // informative log about migration success
successMigrations.push(migration);
this.connection.logger.logSchemaBuild(`Migration ${migration.name} has been executed successfully.`);
});
});
// commit transaction if we started it
if (transactionStartedByUs)
await queryRunner.commitTransaction();
} catch (err) { // rollback transaction if we started it
if (transactionStartedByUs) {
try { // we throw original error even if rollback thrown an error
await queryRunner.rollbackTransaction();
} catch (rollbackError) { }
}
throw err;
} finally {
// if query runner was created by us then release it
if (!this.queryRunner)
await queryRunner.release();
}
return successMigrations;
}
/**
* Reverts last migration that were run.
*/
async undoLastMigration(): Promise<void> {
const queryRunner = this.queryRunner || this.connection.createQueryRunner("master");
// create migrations table if its not created yet
await this.createMigrationsTableIfNotExist(queryRunner);
// get all migrations that are executed and saved in the database
const executedMigrations = await this.loadExecutedMigrations(queryRunner);
// get the time when last migration was executed
let lastTimeExecutedMigration = this.getLatestExecutedMigration(executedMigrations);
// if no migrations found in the database then nothing to revert
if (!lastTimeExecutedMigration) {
this.connection.logger.logSchemaBuild(`No migrations was found in the database. Nothing to revert!`);
return;
}
// get all user's migrations in the source code
const allMigrations = this.getMigrations();
// find the instance of the migration we need to remove
const migrationToRevert = allMigrations.find(migration => migration.name === lastTimeExecutedMigration!.name);
// if no migrations found in the database then nothing to revert
if (!migrationToRevert)
throw new Error(`No migration ${lastTimeExecutedMigration.name} was found in the source code. Make sure you have this migration in your codebase and its included in the connection options.`);
// log information about migration execution
this.connection.logger.logSchemaBuild(`${executedMigrations.length} migrations are already loaded in the database.`);
this.connection.logger.logSchemaBuild(`${lastTimeExecutedMigration.name} is the last executed migration. It was executed on ${new Date(lastTimeExecutedMigration.timestamp).toString()}.`);
this.connection.logger.logSchemaBuild(`Now reverting it...`);
// start transaction if its not started yet
let transactionStartedByUs = false;
if (this.transaction && !queryRunner.isTransactionActive) {
await queryRunner.startTransaction();
transactionStartedByUs = true;
}
try {
await migrationToRevert.instance!.down(queryRunner);
await this.deleteExecutedMigration(queryRunner, migrationToRevert);
this.connection.logger.logSchemaBuild(`Migration ${migrationToRevert.name} has been reverted successfully.`);
// commit transaction if we started it
if (transactionStartedByUs)
await queryRunner.commitTransaction();
} catch (err) { // rollback transaction if we started it
if (transactionStartedByUs) {
try { // we throw original error even if rollback thrown an error
await queryRunner.rollbackTransaction();
} catch (rollbackError) { }
}
throw err;
} finally {
// if query runner was created by us then release it
if (!this.queryRunner)
await queryRunner.release();
}
}
// -------------------------------------------------------------------------
// Protected Methods
// -------------------------------------------------------------------------
/**
* Creates table "migrations" that will store information about executed migrations.
*/
protected async createMigrationsTableIfNotExist(queryRunner: QueryRunner): Promise<void> {
// If driver is mongo no need to create
if (this.connection.driver instanceof MongoDriver) {
return;
}
const tableExist = await queryRunner.hasTable(this.migrationsTable); // todo: table name should be configurable
if (!tableExist) {
await queryRunner.createTable(new Table(
{
name: this.migrationsTable,
columns: [
{
name: "id",
type: this.connection.driver.normalizeType({type: this.connection.driver.mappedDataTypes.migrationId}),
isGenerated: true,
generationStrategy: "increment",
isPrimary: true,
isNullable: false
},
{
name: "timestamp",
type: this.connection.driver.normalizeType({type: this.connection.driver.mappedDataTypes.migrationTimestamp}),
isPrimary: false,
isNullable: false
},
{
name: "name",
type: this.connection.driver.normalizeType({type: this.connection.driver.mappedDataTypes.migrationName}),
isNullable: false
},
]
},
));
}
}
/**
* Loads all migrations that were executed and saved into the database (sorts by id).
*/
protected async loadExecutedMigrations(queryRunner: QueryRunner): Promise<Migration[]> {
if (this.connection.driver instanceof MongoDriver) {
const mongoRunner = queryRunner as MongoQueryRunner;
return await mongoRunner.databaseConnection
.db(this.connection.driver.database!)
.collection(this.migrationsTableName)
.find<Migration>()
.sort("_id", -1)
.toArray();
} else {
const migrationsRaw: ObjectLiteral[] = await this.connection.manager
.createQueryBuilder(queryRunner)
.select()
.orderBy("id", "DESC")
.from(this.migrationsTable, this.migrationsTableName)
.getRawMany();
return migrationsRaw.map(migrationRaw => {
return new Migration(parseInt(migrationRaw["id"]), parseInt(migrationRaw["timestamp"]), migrationRaw["name"]);
});
}
}
/**
* Gets all migrations that setup for this connection.
*/
protected getMigrations(): Migration[] {
const migrations = this.connection.migrations.map(migration => {
const migrationClassName = migration.name || (migration.constructor as any).name;
const migrationTimestamp = parseInt(migrationClassName.substr(-13));
if (!migrationTimestamp)
throw new Error(`${migrationClassName} migration name is wrong. Migration class name should have a JavaScript timestamp appended.`);
return new Migration(undefined, migrationTimestamp, migrationClassName, migration);
});
// sort them by timestamp
return migrations.sort((a, b) => a.timestamp - b.timestamp);
}
/**
* Finds the latest migration (sorts by timestamp) in the given array of migrations.
*/
protected getLatestTimestampMigration(migrations: Migration[]): Migration|undefined {
const sortedMigrations = migrations.map(migration => migration).sort((a, b) => (a.timestamp - b.timestamp) * -1);
return sortedMigrations.length > 0 ? sortedMigrations[0] : undefined;
}
/**
* Finds the latest migration in the given array of migrations.
* PRE: Migration array must be sorted by descending id.
*/
protected getLatestExecutedMigration(sortedMigrations: Migration[]): Migration|undefined {
return sortedMigrations.length > 0 ? sortedMigrations[0] : undefined;
}
/**
* Inserts new executed migration's data into migrations table.
*/
protected async insertExecutedMigration(queryRunner: QueryRunner, migration: Migration): Promise<void> {
const values: ObjectLiteral = {};
if (this.connection.driver instanceof SqlServerDriver) {
values["timestamp"] = new MssqlParameter(migration.timestamp, this.connection.driver.normalizeType({ type: this.connection.driver.mappedDataTypes.migrationTimestamp }) as any);
values["name"] = new MssqlParameter(migration.name, this.connection.driver.normalizeType({ type: this.connection.driver.mappedDataTypes.migrationName }) as any);
} else {
values["timestamp"] = migration.timestamp;
values["name"] = migration.name;
}
if (this.connection.driver instanceof MongoDriver) {
const mongoRunner = queryRunner as MongoQueryRunner;
await mongoRunner.databaseConnection.db(this.connection.driver.database!).collection(this.migrationsTableName).insert(values);
} else {
const qb = queryRunner.manager.createQueryBuilder();
await qb.insert()
.into(this.migrationsTable)
.values(values)
.execute();
}
}
/**
* Delete previously executed migration's data from the migrations table.
*/
protected async deleteExecutedMigration(queryRunner: QueryRunner, migration: Migration): Promise<void> {
const conditions: ObjectLiteral = {};
if (this.connection.driver instanceof SqlServerDriver) {
conditions["timestamp"] = new MssqlParameter(migration.timestamp, this.connection.driver.normalizeType({ type: this.connection.driver.mappedDataTypes.migrationTimestamp }) as any);
conditions["name"] = new MssqlParameter(migration.name, this.connection.driver.normalizeType({ type: this.connection.driver.mappedDataTypes.migrationName }) as any);
} else {
conditions["timestamp"] = migration.timestamp;
conditions["name"] = migration.name;
}
if (this.connection.driver instanceof MongoDriver) {
const mongoRunner = queryRunner as MongoQueryRunner;
await mongoRunner.databaseConnection.db(this.connection.driver.database!).collection(this.migrationsTableName).deleteOne(conditions);
} else {
const qb = queryRunner.manager.createQueryBuilder();
await qb.delete()
.from(this.migrationsTable)
.where(`${qb.escape("timestamp")} = :timestamp`)
.andWhere(`${qb.escape("name")} = :name`)
.setParameters(conditions)
.execute();
}
}
}