1 import * as path from 'path'
2 import * as Promise from 'bluebird'
4 import { database as db } from './database'
5 import { LAST_MIGRATION_VERSION } from './constants'
6 import { logger, readdirPromise } from '../helpers'
9 const p = db.sequelize.getQueryInterface().showAllTables()
11 // No tables, we don't need to migrate anything
12 // The installer will do that
13 if (tables.length === 0) throw null
16 return db.Application.loadMigrationVersion()
18 .then(actualVersion => {
19 if (actualVersion === null) {
20 return db.Application.create({ migrationVersion: 0 }).then(() => 0)
25 .then(actualVersion => {
26 // No need migrations, abort
27 if (actualVersion >= LAST_MIGRATION_VERSION) throw null
31 .then(actualVersion => {
32 // If there are a new migration scripts
33 logger.info('Begin migrations.')
35 return getMigrationScripts().then(migrationScripts => ({ actualVersion, migrationScripts }))
37 .then(({ actualVersion, migrationScripts }) => {
38 return Promise.each(migrationScripts, entity => executeMigration(actualVersion, entity))
41 logger.info('Migrations finished. New migration version schema: %s', LAST_MIGRATION_VERSION)
44 if (err === null) return undefined
52 // ---------------------------------------------------------------------------
58 // ---------------------------------------------------------------------------
60 function getMigrationScripts () {
61 return readdirPromise(path.join(__dirname, 'migrations')).then(files => {
62 const filesToMigrate: {
67 files.forEach(function (file) {
68 // Filename is something like 'version-blabla.js'
69 const version = file.split('-')[0]
80 function executeMigration (actualVersion: number, entity: { version: string, script: string }) {
81 const versionScript = parseInt(entity.version, 10)
83 // Do not execute old migration scripts
84 if (versionScript <= actualVersion) return undefined
86 // Load the migration module and run it
87 const migrationScriptName = entity.script
88 logger.info('Executing %s migration script.', migrationScriptName)
90 const migrationScript = require(path.join(__dirname, 'migrations', migrationScriptName))
92 return db.sequelize.transaction(t => {
95 queryInterface: db.sequelize.getQueryInterface(),
96 sequelize: db.sequelize
99 migrationScript.up(options)
101 // Update the new migration version
102 db.Application.updateMigrationVersion(versionScript, t)