2016-09-26 15:36:36 -05:00
|
|
|
'use strict'
|
|
|
|
|
|
|
|
const eachSeries = require('async/eachSeries')
|
|
|
|
const path = require('path')
|
|
|
|
|
|
|
|
const constants = require('./constants')
|
2016-12-11 14:50:51 -06:00
|
|
|
const db = require('./database')
|
2016-09-26 15:36:36 -05:00
|
|
|
const logger = require('../helpers/logger')
|
|
|
|
|
|
|
|
const migrator = {
|
|
|
|
migrate: migrate
|
|
|
|
}
|
|
|
|
|
|
|
|
function migrate (callback) {
|
2016-12-11 14:50:51 -06:00
|
|
|
db.Application.loadSqlSchemaVersion(function (err, actualVersion) {
|
2016-09-26 15:36:36 -05:00
|
|
|
if (err) return callback(err)
|
|
|
|
|
|
|
|
// If there are a new mongo schemas
|
2016-12-11 14:50:51 -06:00
|
|
|
if (!actualVersion || actualVersion < constants.LAST_SQL_SCHEMA_VERSION) {
|
2016-09-26 15:36:36 -05:00
|
|
|
logger.info('Begin migrations.')
|
|
|
|
|
|
|
|
eachSeries(constants.MONGO_MIGRATION_SCRIPTS, function (entity, callbackEach) {
|
|
|
|
const versionScript = entity.version
|
|
|
|
|
|
|
|
// Do not execute old migration scripts
|
|
|
|
if (versionScript <= actualVersion) return callbackEach(null)
|
|
|
|
|
|
|
|
// Load the migration module and run it
|
|
|
|
const migrationScriptName = entity.script
|
|
|
|
logger.info('Executing %s migration script.', migrationScriptName)
|
|
|
|
|
|
|
|
const migrationScript = require(path.join(__dirname, 'migrations', migrationScriptName))
|
|
|
|
migrationScript.up(function (err) {
|
|
|
|
if (err) return callbackEach(err)
|
|
|
|
|
|
|
|
// Update the new mongo version schema
|
2016-12-11 14:50:51 -06:00
|
|
|
db.Application.updateSqlSchemaVersion(versionScript, callbackEach)
|
2016-09-26 15:36:36 -05:00
|
|
|
})
|
|
|
|
}, function (err) {
|
|
|
|
if (err) return callback(err)
|
|
|
|
|
2016-12-11 14:50:51 -06:00
|
|
|
logger.info('Migrations finished. New SQL version schema: %s', constants.LAST_SQL_SCHEMA_VERSION)
|
2016-09-26 15:36:36 -05:00
|
|
|
return callback(null)
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
return callback(null)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
module.exports = migrator
|
|
|
|
|