Skip to content

Commit

Permalink
Add db:create and db:drop for MySQL/Postgres 🎊
Browse files Browse the repository at this point in the history
  • Loading branch information
aledalgrande committed Aug 11, 2017
1 parent b6404d0 commit 4fb3b07
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
var
test
81 changes: 81 additions & 0 deletions lib/tasks/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,34 @@ var Umzug = require('umzug');
var clc = require('cli-color');

module.exports = {
'db:create': {
descriptions: {
'short': 'Creates the configured database.',
'long': [
'The command creates the configured database.'
]
},

task: function () {
var config = helpers.config.readConfig();
var database = config.database;
runQueryOnDefaultDatabase('CREATE DATABASE ' + database, config);
}
},
'db:drop': {
descriptions: {
'short': 'Drops the configured database.',
'long': [
'The command drops the configured database.'
]
},

task: function () {
var config = helpers.config.readConfig();
var database = config.database;
runQueryOnDefaultDatabase('DROP DATABASE ' + database, config);
}
},
'db:migrate': {
descriptions: {
'short': 'Run pending migrations.',
Expand Down Expand Up @@ -437,6 +465,59 @@ function getMigrator (type) {
}
}

function runQueryOnDefaultDatabase(query, config) {
var dialect = config.dialect;

return new Bluebird(function () {
if (dialect.match('mysql')) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host: config.host,
user: config.username,
password: config.password,
port: config.port
});

connection.query(query, function (error) {
if (error) {
console.error(error);
process.exit(1);
}
else {
process.exit(0);
}
});
}
else if (dialect.match('postgres')) {
var Postgres = require('pg').Client;
var client = new Postgres({
user: config.username,
host: config.host,
database: 'postgres',
password: config.password,
port: config.port
});
client.connect();
client.query(query, function (error) {
if (error) {
console.error(error);
process.exit(1);
}

client.end();
process.exit(0);
});
}
else {
console.log('This command is not supported for this dialect.');
process.exit(1);
}
}).catch(function (err) {
console.error(err);
process.exit(1);
});
}

/**
* tryToMigrateFromOldSchema - migrates from old schema
*
Expand Down

0 comments on commit 4fb3b07

Please sign in to comment.