0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-02-10 23:36:14 -05:00
ghost/core/server/data/migration/populate.js
Katharina Irrgang 1867e1a75e 🎨 run database population in transaction (#7448)
* 🎨  run database population in transaction

refs #6574, refs #7432

- create transaction for creating tables
- if an error occurs or a container get's destroyed before population finishes, transaction is rolled back

* 🎨  simplify transaction creation and test
2016-09-30 14:05:17 +01:00

56 lines
1.7 KiB
JavaScript

// # Populate
// Create a brand new database for a new install of ghost
var Promise = require('bluebird'),
_ = require('lodash'),
commands = require('../schema').commands,
fixtures = require('./fixtures'),
errors = require('../../errors'),
db = require('../../data/db'),
schema = require('../schema').tables,
schemaTables = Object.keys(schema),
populate, logger;
// @TODO: remove me asap!
logger = {
info: function info(message) {
errors.logComponentInfo('Migrations', message);
},
warn: function warn(message) {
errors.logComponentWarn('Skipping Migrations', message);
}
};
/**
* ## Populate
* Uses the schema to determine table structures, and automatically creates each table in order
*/
populate = function populate(options) {
options = options || {};
var tablesOnly = options.tablesOnly,
modelOptions = {
context: {
internal: true
}
};
logger.info('Creating tables...');
return db.knex.transaction(function populateDatabaseInTransaction(transaction) {
return Promise.mapSeries(schemaTables, function createTable(table) {
logger.info('Creating table: ' + table);
return commands.createTable(table, transaction);
}).then(function populateFixtures() {
if (tablesOnly) {
return;
}
return fixtures.populate(logger, _.merge({}, {transacting: transaction}, modelOptions));
});
}).catch(function populateDatabaseError(err) {
logger.warn('rolling back...');
return Promise.reject(new errors.InternalServerError('Unable to populate database: ' + err.message));
});
};
module.exports = populate;