]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/initializers/migrator.js
Server: retry video abuse requests too
[github/Chocobozzz/PeerTube.git] / server / initializers / migrator.js
CommitLineData
00d6b0dd
C
1'use strict'
2
3const eachSeries = require('async/eachSeries')
b769007f 4const fs = require('fs')
00d6b0dd
C
5const path = require('path')
6
7const constants = require('./constants')
feb4bdfd 8const db = require('./database')
00d6b0dd
C
9const logger = require('../helpers/logger')
10
00d6b0dd
C
11const migrator = {
12 migrate: migrate
13}
14
15function migrate (callback) {
b769007f 16 db.Application.loadMigrationVersion(function (err, actualVersion) {
00d6b0dd
C
17 if (err) return callback(err)
18
b769007f
C
19 // If there are a new migration scripts
20 if (actualVersion < constants.LAST_MIGRATION_VERSION) {
00d6b0dd
C
21 logger.info('Begin migrations.')
22
b769007f
C
23 getMigrationScripts(function (err, migrationScripts) {
24 if (err) return callback(err)
00d6b0dd 25
b769007f
C
26 eachSeries(migrationScripts, function (entity, callbackEach) {
27 executeMigration(actualVersion, entity, callbackEach)
28 }, function (err) {
29 if (err) return callback(err)
00d6b0dd 30
b769007f
C
31 logger.info('Migrations finished. New migration version schema: %s', constants.LAST_MIGRATION_VERSION)
32 return callback(null)
00d6b0dd 33 })
00d6b0dd
C
34 })
35 } else {
36 return callback(null)
37 }
38 })
39}
40
41// ---------------------------------------------------------------------------
42
43module.exports = migrator
44
b769007f
C
45// ---------------------------------------------------------------------------
46
47function getMigrationScripts (callback) {
48 fs.readdir(path.join(__dirname, 'migrations'), function (err, files) {
49 if (err) return callback(err)
50
51 const filesToMigrate = []
52
53 files.forEach(function (file) {
54 // Filename is something like 'version-blabla.js'
55 const version = file.split('-')[0]
56 filesToMigrate.push({
57 version,
58 script: file
59 })
60 })
61
62 return callback(err, filesToMigrate)
63 })
64}
65
66function executeMigration (actualVersion, entity, callback) {
67 const versionScript = entity.version
68
69 // Do not execute old migration scripts
70 if (versionScript <= actualVersion) return callback(null)
71
72 // Load the migration module and run it
73 const migrationScriptName = entity.script
74 logger.info('Executing %s migration script.', migrationScriptName)
75
76 const migrationScript = require(path.join(__dirname, 'migrations', migrationScriptName))
77
78 db.sequelize.transaction().asCallback(function (err, t) {
79 if (err) return callback(err)
80
81 migrationScript.up({ transaction: t }, function (err) {
82 if (err) {
83 t.rollback()
84 return callback(err)
85 }
86
87 // Update the new migration version
88 db.Application.updateMigrationVersion(versionScript, t, function (err) {
89 if (err) {
90 t.rollback()
91 return callback(err)
92 }
93
94 t.commit()
95 })
96 })
97 })
98}