1 import * as path from 'path'
2 import { readdirPromise } from '../helpers/core-utils'
3 import { logger } from '../helpers/logger'
4 import { LAST_MIGRATION_VERSION } from './constants'
5 import { sequelizeTypescript } from './database'
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
16 // Search in "Applications" or "application" tables
18 const [ rows ] = await sequelizeTypescript.query('SELECT "migrationVersion" FROM "Applications"')
19 if (rows && rows[ 0 ] && rows[ 0 ].migrationVersion) {
20 actualVersion = rows[ 0 ].migrationVersion
23 const [ rows ] = await sequelizeTypescript.query('SELECT "migrationVersion" FROM "application"')
24 if (rows && rows[0] && rows[0].migrationVersion) {
25 actualVersion = rows[0].migrationVersion
29 if (actualVersion === null) {
30 await sequelizeTypescript.query('INSERT INTO "application" ("migrationVersion") VALUES (0)')
34 // No need migrations, abort
35 if (actualVersion >= LAST_MIGRATION_VERSION) return
37 // If there are a new migration scripts
38 logger.info('Begin migrations.')
40 const migrationScripts = await getMigrationScripts()
42 for (const migrationScript of migrationScripts) {
44 await executeMigration(actualVersion, migrationScript)
46 logger.error('Cannot execute migration %s.', migrationScript.version, err)
51 logger.info('Migrations finished. New migration version schema: %s', LAST_MIGRATION_VERSION)
54 // ---------------------------------------------------------------------------
60 // ---------------------------------------------------------------------------
62 async function getMigrationScripts () {
63 const files = await readdirPromise(path.join(__dirname, 'migrations'))
64 const filesToMigrate: {
70 .filter(file => file.endsWith('.js.map') === false)
72 // Filename is something like 'version-blabla.js'
73 const version = file.split('-')[0]
83 async function executeMigration (actualVersion: number, entity: { version: string, script: string }) {
84 const versionScript = parseInt(entity.version, 10)
86 // Do not execute old migration scripts
87 if (versionScript <= actualVersion) return undefined
89 // Load the migration module and run it
90 const migrationScriptName = entity.script
91 logger.info('Executing %s migration script.', migrationScriptName)
93 const migrationScript = require(path.join(__dirname, 'migrations', migrationScriptName))
95 return sequelizeTypescript.transaction(async t => {
98 queryInterface: sequelizeTypescript.getQueryInterface(),
99 sequelize: sequelizeTypescript
102 await migrationScript.up(options)
104 // Update the new migration version
105 await sequelizeTypescript.query('UPDATE "application" SET "migrationVersion" = ' + versionScript, { transaction: t })