Fix webfinger validator
[oweals/peertube.git] / server / initializers / migrator.ts
1 import * as path from 'path'
2 import { logger, readdirPromise } from '../helpers'
3 import { LAST_MIGRATION_VERSION } from './constants'
4 import { sequelizeTypescript } from './database'
5
6 async function migrate () {
7   const tables = await sequelizeTypescript.getQueryInterface().showAllTables()
8
9   // No tables, we don't need to migrate anything
10   // The installer will do that
11   if (tables.length === 0) return
12
13   let actualVersion: number = null
14
15   // Search in "Applications" or "application" tables
16   try {
17     const [ rows ] = await sequelizeTypescript.query('SELECT "migrationVersion" FROM "Applications"')
18     if (rows && rows[ 0 ] && rows[ 0 ].migrationVersion) {
19       actualVersion = rows[ 0 ].migrationVersion
20     }
21   } catch {
22     const [ rows ] = await sequelizeTypescript.query('SELECT "migrationVersion" FROM "application"')
23     if (rows && rows[0] && rows[0].migrationVersion) {
24       actualVersion = rows[0].migrationVersion
25     }
26   }
27
28   if (actualVersion === null) {
29     await sequelizeTypescript.query('INSERT INTO "application" ("migrationVersion") VALUES (0)')
30     actualVersion = 0
31   }
32
33   // No need migrations, abort
34   if (actualVersion >= LAST_MIGRATION_VERSION) return
35
36   // If there are a new migration scripts
37   logger.info('Begin migrations.')
38
39   const migrationScripts = await getMigrationScripts()
40
41   for (const migrationScript of migrationScripts) {
42     try {
43       await executeMigration(actualVersion, migrationScript)
44     } catch (err) {
45       logger.error('Cannot execute migration %s.', migrationScript.version, err)
46       process.exit(0)
47     }
48   }
49
50   logger.info('Migrations finished. New migration version schema: %s', LAST_MIGRATION_VERSION)
51 }
52
53 // ---------------------------------------------------------------------------
54
55 export {
56   migrate
57 }
58
59 // ---------------------------------------------------------------------------
60
61 async function getMigrationScripts () {
62   const files = await readdirPromise(path.join(__dirname, 'migrations'))
63   const filesToMigrate: {
64     version: string,
65     script: string
66   }[] = []
67
68   files
69     .filter(file => file.endsWith('.js.map') === false)
70     .forEach(file => {
71       // Filename is something like 'version-blabla.js'
72       const version = file.split('-')[0]
73       filesToMigrate.push({
74         version,
75         script: file
76       })
77     })
78
79   return filesToMigrate
80 }
81
82 async function executeMigration (actualVersion: number, entity: { version: string, script: string }) {
83   const versionScript = parseInt(entity.version, 10)
84
85   // Do not execute old migration scripts
86   if (versionScript <= actualVersion) return undefined
87
88   // Load the migration module and run it
89   const migrationScriptName = entity.script
90   logger.info('Executing %s migration script.', migrationScriptName)
91
92   const migrationScript = require(path.join(__dirname, 'migrations', migrationScriptName))
93
94   await sequelizeTypescript.transaction(async t => {
95     const options = {
96       transaction: t,
97       queryInterface: sequelizeTypescript.getQueryInterface(),
98       sequelize: sequelizeTypescript
99     }
100
101     await migrationScript.up(options)
102
103     // Update the new migration version
104     await sequelizeTypescript.query('UPDATE "application" SET "migrationVersion" = ' + versionScript, { transaction: t })
105   })
106 }