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