Created
October 19, 2015 18:06
-
-
Save mrosenberg/2ccade3d380062162f7b to your computer and use it in GitHub Desktop.
Script to do a one time update to a database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var config = require(''); // Config file containing DB credentials | |
var mysql = require('mysql'); | |
var Promise = require('bluebird'); | |
Promise.promisifyAll(require("mysql/lib/Connection").prototype); | |
Promise.promisifyAll(require("mysql/lib/Pool").prototype); | |
var pool = mysql.createPool(config.dbConfig); | |
pool.on('error', function(err) { | |
console.log('Database Error %s', err) | |
}); | |
pool.on('enqueue', function () { | |
console.log('Database connection pool queued.'); | |
}); | |
function getClients() { | |
return pool.getConnectionAsync() | |
.then(function(connection) { | |
return connection.queryAsync('select * from your_table;') | |
.spread(function(rows, columns) { | |
connection.release(); | |
return rows; | |
}); | |
}); | |
}; | |
function ErrDupField(e) { | |
return (e.cause.errno === 1060); | |
} | |
function addClientIdField(table) { | |
console.log(table); | |
return pool.getConnectionAsync() | |
.then(function(connection) { | |
return connection.queryAsync('ALTER TABLE '+table.name+' ADD clientID VARCHAR(50) NOT NULL;').then(function() { | |
return connection.release(); | |
}).catch(ErrDupField, function(e) { | |
console.log('%s already has clientID', table.name); | |
}); | |
}); | |
}; | |
function addClientID(client, table) { | |
return pool.getConnectionAsync() | |
.then(function(connection) { | |
return connection.queryAsync('Update '+table.name+' SET clientID = "'+client.id+'" WHERE '+table.accountField+' = "'+client[table.clientField]+'";') | |
.then(function() { | |
return connection.release(); | |
}); | |
}); | |
}; | |
getClients() | |
.then(function(clients) { | |
var tables = [ | |
{ | |
"name": "", // name of the table to update | |
"accountField": "", // table field to update | |
"clientField": "" // Field of another table to update data from | |
} | |
]; | |
Promise.map(tables, function(table) { | |
return addClientIdField(table).return(table); | |
}) | |
.each(function(table) { | |
return Promise.map(clients, function(client) { | |
return addClientID(client, table).return(client.name); | |
}, {concurrency: 5}) | |
.tap(console.log); | |
}) | |
.finally(function() { | |
console.log('All Clients Udpated'); | |
process.exit(0); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment