Skip to content

Instantly share code, notes, and snippets.

@cesarandreu
Created November 23, 2014 23:53
Show Gist options
  • Select an option

  • Save cesarandreu/407f429384c5b4600827 to your computer and use it in GitHub Desktop.

Select an option

Save cesarandreu/407f429384c5b4600827 to your computer and use it in GitHub Desktop.
create or drop PG database
'use strict';
var pg = require('co-pg')(require('pg')),
co = require('co');
var env = process.env.NODE_ENV || 'development',
config = require('../config/database')[env],
database = config.database;
delete config.database;
co(function* createDatabase () {
var client;
try {
client = new pg.Client(config);
yield client.connect_();
let query = 'SELECT 1 FROM pg_database WHERE datname=\'' + database + '\'';
let result = yield client.query_(query);
if (result.rowCount) {
console.log('Database', database, 'already exists');
} else {
yield client.query_('CREATE DATABASE ' + database);
console.log('Database', database, 'created');
}
} catch (ex) {
console.error(ex.toString());
} finally {
client.end();
}
})();
'use strict';
var pg = require('co-pg')(require('pg')),
co = require('co');
var env = process.env.NODE_ENV || 'development',
config = require('../config/database')[env],
database = config.database;
delete config.database;
if (env.indexOf('production') !== -1 && process.env.FORCE !== 'true') {
console.warn('You were about to drop a production database');
console.warn('To drop a production database you must pass FORCE=true');
console.warn('For example: NODE_ENV=production FORCE=true node script/drop_database.js');
return;
}
co(function* dropDatabase () {
var client;
try {
client = new pg.Client(config);
yield client.connect_();
let query = 'SELECT 1 FROM pg_database WHERE datname=\'' + database + '\'';
let result = yield client.query_(query);
if (!result.rowCount) {
console.log('Database', database, 'doesn\'t exists');
} else {
yield client.query_('DROP DATABASE ' + database);
console.log('Database', database, 'dropped');
}
} catch (ex) {
console.error(ex.toString());
} finally {
client.end();
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment