2017-10-23 08:22:09 +08:00
|
|
|
const backup = require('./backup');
|
|
|
|
const sql = require('./sql');
|
|
|
|
const fs = require('fs-extra');
|
2017-10-25 10:17:48 +08:00
|
|
|
const log = require('./log');
|
2017-10-23 08:22:09 +08:00
|
|
|
|
2017-11-03 07:23:52 +08:00
|
|
|
const APP_DB_VERSION = 23;
|
2017-10-23 08:22:09 +08:00
|
|
|
const MIGRATIONS_DIR = "./migrations";
|
|
|
|
|
|
|
|
async function migrate() {
|
|
|
|
const migrations = [];
|
|
|
|
|
2017-10-25 10:17:48 +08:00
|
|
|
// backup before attempting migration
|
2017-10-23 08:22:09 +08:00
|
|
|
await backup.backupNow();
|
|
|
|
|
|
|
|
const currentDbVersion = parseInt(await sql.getOption('db_version'));
|
|
|
|
|
|
|
|
fs.readdirSync(MIGRATIONS_DIR).forEach(file => {
|
|
|
|
const match = file.match(/([0-9]{4})__([a-zA-Z0-9_ ]+)\.sql/);
|
|
|
|
|
|
|
|
if (match) {
|
|
|
|
const dbVersion = parseInt(match[1]);
|
|
|
|
|
|
|
|
if (dbVersion > currentDbVersion) {
|
|
|
|
const name = match[2];
|
|
|
|
|
|
|
|
const migrationRecord = {
|
2017-10-23 08:29:31 +08:00
|
|
|
dbVersion: dbVersion,
|
|
|
|
name: name,
|
|
|
|
file: file
|
2017-10-23 08:22:09 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
migrations.push(migrationRecord);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
migrations.sort((a, b) => a.db_version - b.db_version);
|
|
|
|
|
|
|
|
for (const mig of migrations) {
|
|
|
|
const migrationSql = fs.readFileSync(MIGRATIONS_DIR + "/" + mig.file).toString('utf8');
|
|
|
|
|
|
|
|
try {
|
2017-10-25 10:17:48 +08:00
|
|
|
log.info("Attempting migration to version " + mig.dbVersion + " with script: " + migrationSql);
|
2017-10-23 08:22:09 +08:00
|
|
|
|
2017-10-30 06:50:28 +08:00
|
|
|
await sql.doInTransaction(async () => {
|
|
|
|
await sql.executeScript(migrationSql);
|
2017-10-23 08:22:09 +08:00
|
|
|
|
2017-10-30 06:50:28 +08:00
|
|
|
await sql.setOption("db_version", mig.dbVersion);
|
|
|
|
});
|
2017-10-23 08:22:09 +08:00
|
|
|
|
2017-10-25 10:17:48 +08:00
|
|
|
log.info("Migration to version " + mig.dbVersion + " has been successful.");
|
|
|
|
|
2017-10-23 08:22:09 +08:00
|
|
|
mig['success'] = true;
|
|
|
|
}
|
|
|
|
catch (e) {
|
|
|
|
mig['success'] = false;
|
|
|
|
mig['error'] = e.stack;
|
|
|
|
|
2017-10-25 10:17:48 +08:00
|
|
|
log.error("error during migration to version " + mig.dbVersion + ": " + e.stack);
|
2017-10-23 08:22:09 +08:00
|
|
|
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
2017-10-25 10:17:48 +08:00
|
|
|
|
2017-10-23 08:22:09 +08:00
|
|
|
return migrations;
|
|
|
|
}
|
|
|
|
|
2017-10-26 10:39:21 +08:00
|
|
|
async function isDbUpToDate() {
|
|
|
|
const dbVersion = parseInt(await sql.getOption('db_version'));
|
|
|
|
|
|
|
|
return dbVersion >= APP_DB_VERSION;
|
|
|
|
}
|
|
|
|
|
2017-10-23 08:22:09 +08:00
|
|
|
module.exports = {
|
|
|
|
migrate,
|
2017-10-26 10:39:21 +08:00
|
|
|
isDbUpToDate,
|
2017-10-23 08:22:09 +08:00
|
|
|
APP_DB_VERSION
|
|
|
|
};
|