First version with PostgreSQL
[oweals/peertube.git] / server / initializers / migrator.js
1 'use strict'
2
3 const eachSeries = require('async/eachSeries')
4 const path = require('path')
5
6 const constants = require('./constants')
7 const db = require('./database')
8 const logger = require('../helpers/logger')
9
10 const migrator = {
11   migrate: migrate
12 }
13
14 function migrate (callback) {
15   db.Application.loadSqlSchemaVersion(function (err, actualVersion) {
16     if (err) return callback(err)
17
18     // If there are a new mongo schemas
19     if (!actualVersion || actualVersion < constants.LAST_SQL_SCHEMA_VERSION) {
20       logger.info('Begin migrations.')
21
22       eachSeries(constants.MONGO_MIGRATION_SCRIPTS, function (entity, callbackEach) {
23         const versionScript = entity.version
24
25         // Do not execute old migration scripts
26         if (versionScript <= actualVersion) return callbackEach(null)
27
28         // Load the migration module and run it
29         const migrationScriptName = entity.script
30         logger.info('Executing %s migration script.', migrationScriptName)
31
32         const migrationScript = require(path.join(__dirname, 'migrations', migrationScriptName))
33         migrationScript.up(function (err) {
34           if (err) return callbackEach(err)
35
36           // Update the new mongo version schema
37           db.Application.updateSqlSchemaVersion(versionScript, callbackEach)
38         })
39       }, function (err) {
40         if (err) return callback(err)
41
42         logger.info('Migrations finished. New SQL version schema: %s', constants.LAST_SQL_SCHEMA_VERSION)
43         return callback(null)
44       })
45     } else {
46       return callback(null)
47     }
48   })
49 }
50
51 // ---------------------------------------------------------------------------
52
53 module.exports = migrator
54