Added migration utils for dropping tables

refs https://github.com/TryGhost/Ghost/issues/12565

- Dropping tables happens sporadicaly, usually during major version releases. It made sense to create a utility based on previous migrations of this type (e.g.:  3.0/03-drop-client-auth-tables.js migration) to avoid code duplication in the future
This commit is contained in:
Naz 2021-02-02 14:12:07 +13:00 committed by Daniel Lockyer
parent 73f6fd8c51
commit bf1fcd25ce
No known key found for this signature in database
GPG Key ID: FFBC6FA2A6F6ABC1

View File

@ -1,6 +1,7 @@
const ObjectId = require('bson-objectid').default;
const logging = require('../../../shared/logging');
const commands = require('../schema').commands;
const Promise = require('bluebird');
const MIGRATION_USER = 1;
@ -32,6 +33,28 @@ function addTable(name) {
);
}
/**
* Creates migration which will drop a table
*
* @param {[string]} names - names of the tables to drop
*/
function dropTables(names) {
return createTransactionalMigration(
async function up(connection) {
for (const name of names) {
const exists = await connection.schema.hasTable(name);
if (!exists) {
logging.warn(`Failed dropping table: ${name}. Table does not exits`);
} else {
logging.info(`Dropping table: ${name}`);
await commands.deleteTable(name, connection);
}
}
}
);
}
/**
* Creates a migration which will add a permission to the database
*
@ -221,6 +244,25 @@ function createNonTransactionalMigration(up, down) {
};
}
/**
* @param {(connection: import('knex')) => Promise<void>} up
*
* @returns {Migration}
*/
function createIrreversibleMigration(up) {
return {
config: {
irreversible: true
},
async up(config) {
await up(config.connection);
},
async down() {
return Promise.reject();
}
};
}
/**
* @param {(connection: import('knex')) => Promise<void>} up
* @param {(connection: import('knex')) => Promise<void>} down
@ -351,11 +393,13 @@ function createDropColumnMigration(table, column, columnDefinition) {
module.exports = {
addTable,
dropTables,
addPermission,
addPermissionToRole,
addPermissionWithRoles,
createTransactionalMigration,
createNonTransactionalMigration,
createIrreversibleMigration,
combineTransactionalMigrations,
combineNonTransactionalMigrations,
createAddColumnMigration,