Skip to content

Instantly share code, notes, and snippets.

@seanknox
Created November 23, 2015 21:35
Show Gist options
  • Save seanknox/ea7006640465b4a59107 to your computer and use it in GitHub Desktop.
Save seanknox/ea7006640465b4a59107 to your computer and use it in GitHub Desktop.
First attempt at tool to create/delete/reset DB using Sequelize and MySQL SQL dumps
'use strict';
const _ = require('lodash');
const Promise = require('bluebird');
const fs = require('fs');
const mysql = require('mysql');
const Sequelize = require('sequelize');
const config = require('config');
const database = config.get('database');
Promise.promisifyAll(mysql);
class DatabaseSetup {
constructor() {
this.mysqlConnection = mysql.createConnection({
host: database.options.host,
user: database.username,
port: database.options.port
});
this.databaseName = database.database;
Promise.promisifyAll(this.mysqlConnection);
}
create() {
const sql = `CREATE DATABASE ${this.databaseName}`;
this.mysqlConnection.queryAsync(sql).then(() => {
console.log(`*** Creating ${this.databaseName}...`);
this.loadSchema();
});
}
destroy() {
const sql = `DROP DATABASE ${this.databaseName}`;
this.mysqlConnection.queryAsync(sql)
.catch((e) => {
console.log(`${this.databaseName} doesn't exist. Moving on...`);
});
}
reset() {
return Promise
.resolve()
.then(() => {
this.destroy();
})
.then(() => {
this.create();
});
}
loadSchema() {
const allowMultipleQueries = {
'dialectOptions': {
'multipleStatements': true
}
};
const sequelize = new Sequelize(
database.database,
database.username,
database.password,
_.merge(database.options, allowMultipleQueries)
);
return Promise
.resolve()
.then(() => {
return fs.readFileSync(__dirname + '/schema.sql', 'utf-8');
})
.then(schema => {
return sequelize.query(schema);
});
}
}
module.exports = new DatabaseSetup();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment