1 import * as path from 'path'
2 import { logger } from '../helpers/logger'
3 import { LAST_MIGRATION_VERSION } from './constants'
4 import { sequelizeTypescript } from './database'
5 import { readdir } from 'fs-extra'
7 async function migrate () {
8 const tables = await sequelizeTypescript.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: number | null = null
16 const [ rows ] = await sequelizeTypescript.query('SELECT "migrationVersion" FROM "application"')
17 if (rows && rows[0] && rows[0].migrationVersion) {
18 actualVersion = rows[0].migrationVersion
21 if (actualVersion === null) {
22 await sequelizeTypescript.query('INSERT INTO "application" ("migrationVersion") VALUES (0)')
26 // No need migrations, abort
27 if (actualVersion >= LAST_MIGRATION_VERSION) return
29 // If there are a new migration scripts
30 logger.info('Begin migrations.')
32 const migrationScripts = await getMigrationScripts()
34 for (const migrationScript of migrationScripts) {
36 await executeMigration(actualVersion, migrationScript)
38 logger.error('Cannot execute migration %s.', migrationScript.version, { err })
43 logger.info('Migrations finished. New migration version schema: %s', LAST_MIGRATION_VERSION)
46 // ---------------------------------------------------------------------------
52 // ---------------------------------------------------------------------------
54 async function getMigrationScripts () {
55 const files = await readdir(path.join(__dirname, 'migrations'))
56 const filesToMigrate: {
62 .filter(file => file.endsWith('.js.map') === false)
64 // Filename is something like 'version-blabla.js'
65 const version = file.split('-')[0]
75 async function executeMigration (actualVersion: number, entity: { version: string, script: string }) {
76 const versionScript = parseInt(entity.version, 10)
78 // Do not execute old migration scripts
79 if (versionScript <= actualVersion) return undefined
81 // Load the migration module and run it
82 const migrationScriptName = entity.script
83 logger.info('Executing %s migration script.', migrationScriptName)
85 const migrationScript = require(path.join(__dirname, 'migrations', migrationScriptName))
87 return sequelizeTypescript.transaction(async t => {
90 queryInterface: sequelizeTypescript.getQueryInterface(),
91 sequelize: sequelizeTypescript
94 await migrationScript.up(options)
96 // Update the new migration version
97 await sequelizeTypescript.query('UPDATE "application" SET "migrationVersion" = ' + versionScript, { transaction: t })