From 7a1773c52205c6dfd98ade07b1c9d9da7fb39670 Mon Sep 17 00:00:00 2001 From: Michael Bromley Date: Wed, 11 Nov 2020 17:32:34 +0100 Subject: [PATCH] feat(core): Improve feedback & error handling in migration functions --- packages/core/src/migrate.ts | 36 ++++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/packages/core/src/migrate.ts b/packages/core/src/migrate.ts index f2e2ea070c..f92c12a0b1 100644 --- a/packages/core/src/migrate.ts +++ b/packages/core/src/migrate.ts @@ -39,8 +39,20 @@ export interface MigrationOptions { export async function runMigrations(userConfig: Partial) { const config = await preBootstrapConfig(userConfig); const connection = await createConnection(createConnectionOptions(config)); - await disableForeignKeysForSqLite(connection, () => connection.runMigrations({ transaction: 'each' })); - await connection.close(); + try { + const migrations = await disableForeignKeysForSqLite(connection, () => + connection.runMigrations({ transaction: 'each' }), + ); + for (const migration of migrations) { + console.log(chalk.green(`Successfully ran migration: ${migration.name}`)); + } + } catch (e) { + console.log(chalk.red(`An error occurred when running migrations:`)); + console.log(e.message); + process.exitCode = 1; + } finally { + await connection.close(); + } } /** @@ -53,10 +65,17 @@ export async function runMigrations(userConfig: Partial) { export async function revertLastMigration(userConfig: Partial) { const config = await preBootstrapConfig(userConfig); const connection = await createConnection(createConnectionOptions(config)); - await disableForeignKeysForSqLite(connection, () => - connection.undoLastMigration({ transaction: 'each' }), - ); - await connection.close(); + try { + await disableForeignKeysForSqLite(connection, () => + connection.undoLastMigration({ transaction: 'each' }), + ); + } catch (e) { + console.log(chalk.red(`An error occurred when reverting migration:`)); + console.log(e.message); + process.exitCode = 1; + } finally { + await connection.close(); + } } /** @@ -154,15 +173,16 @@ function createConnectionOptions(userConfig: Partial): Connection * is a work-around for the issue. * See https://github.com/typeorm/typeorm/issues/2576#issuecomment-499506647 */ -async function disableForeignKeysForSqLite(connection: Connection, work: () => Promise) { +async function disableForeignKeysForSqLite(connection: Connection, work: () => Promise): Promise { const isSqLite = connection.options.type === 'sqlite'; if (isSqLite) { await connection.query('PRAGMA foreign_keys=OFF'); } - await work(); + const result = await work(); if (isSqLite) { await connection.query('PRAGMA foreign_keys=ON'); } + return result; } /**