1 import * as path from 'path'
3 import { database as db } from './database'
4 import { LAST_MIGRATION_VERSION } from './constants'
5 import { logger, readdirPromise } from '../helpers'
7 async function migrate () {
8 const tables = await db.sequelize.getQueryInterface().showAllTables()
10 // No tables, we don't need to migrate anything
11 // The installer will do that
12 if (tables.length === 0) return
14 let actualVersion = await db.Application.loadMigrationVersion()
15 if (actualVersion === null) {
16 await db.Application.create({ migrationVersion: 0 })
20 // No need migrations, abort
21 if (actualVersion >= LAST_MIGRATION_VERSION) return
23 // If there are a new migration scripts
24 logger.info('Begin migrations.')
26 const migrationScripts = await getMigrationScripts()
28 for (const migrationScript of migrationScripts) {
29 await executeMigration(actualVersion, migrationScript)
32 logger.info('Migrations finished. New migration version schema: %s', LAST_MIGRATION_VERSION)
35 // ---------------------------------------------------------------------------
41 // ---------------------------------------------------------------------------
43 async function getMigrationScripts () {
44 const files = await readdirPromise(path.join(__dirname, 'migrations'))
45 const filesToMigrate: {
51 .filter(file => file.endsWith('.js.map') === false)
53 // Filename is something like 'version-blabla.js'
54 const version = file.split('-')[0]
64 async function executeMigration (actualVersion: number, entity: { version: string, script: string }) {
65 const versionScript = parseInt(entity.version, 10)
67 // Do not execute old migration scripts
68 if (versionScript <= actualVersion) return undefined
70 // Load the migration module and run it
71 const migrationScriptName = entity.script
72 logger.info('Executing %s migration script.', migrationScriptName)
74 const migrationScript = require(path.join(__dirname, 'migrations', migrationScriptName))
76 await db.sequelize.transaction(async t => {
79 queryInterface: db.sequelize.getQueryInterface(),
80 sequelize: db.sequelize,
84 await migrationScript.up(options)
86 // Update the new migration version
87 await db.Application.updateMigrationVersion(versionScript, t)