Mailspring/scripts/migrate-db.es6
Karim Hamidou e55c36a79a [cloud-api] Add support for database migrations
Summary:
This diff adds support for database migration to our cloud API. It's partially inspired by Halla's local-sync migration diff (D3809). You can run a migration by calling "node-babel scripts/migrate-db up|down" or by calling "npm script upgrade-db|downgrade-db".

Note that for simplicity reasons we assume that we're only writing migrations for our MySQL database – people developing locally may have to blow up there dbs whenever there's a schema change, though in practice `ALTER TABLE ADD COLUMN`statements work the same on both dbs.

Test Plan: Tested locally. Will run the metadata migration on staging.

Reviewers: evan, spang, halla

Reviewed By: halla

Differential Revision: https://phab.nylas.com/D3840
2017-02-06 13:38:59 -08:00

55 lines
1.2 KiB
JavaScript

import Umzug from 'umzug'
import {DatabaseConnector} from '../packages/cloud-core'
async function activate() {
// Perform migrations before starting sync
const db = await DatabaseConnector.forShared();
const umzug = new Umzug({
storage: 'sequelize',
storageOptions: {
sequelize: db.sequelize,
modelName: 'migration',
tableName: 'migrations',
},
migrations: {
path: `migrations`,
params: [db.sequelize.getQueryInterface(), db.sequelize],
pattern: /^\d+[\w-]+\.es6$/,
},
logging: console.log,
});
return umzug;
}
async function upgrade() {
const umzug = await activate();
const pending = await umzug.pending();
if (pending.length > 0) {
console.log(`Running ${pending.length} migration(s).`)
} else {
console.log(`No new migrations to run.`)
}
return umzug.up() // run all pending migrations
}
async function downgrade() {
const umzug = await activate();
console.log(`Running 1 down migration.`)
return umzug.down()
}
async function main() {
if (process.argv.length !== 3) {
console.log("usage: migrate-db up|down")
} else if (process.argv[2] === 'up') {
await upgrade();
} else if (process.argv[2] === 'down') {
await downgrade();
}
}
main();