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