Created
July 20, 2015 03:41
-
-
Save ThomasHambach/012372cf76f622213d66 to your computer and use it in GitHub Desktop.
Node ODBC upsert module
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 wodbc = require("./wodbc")(); | |
var data = { | |
UserName: 'Jane Doe' | |
} | |
wodbc.upsert('User', 'UserId', data, function (err, insertId) { ... |
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
'use strict'; | |
var config = require('../config/environment'), | |
db = require("odbc")(); | |
/** | |
* Perform insert or update. | |
* | |
* @param table string | |
* @param primaryKey string|null | |
* @param values obj | |
* @param cb | |
*/ | |
db.upsert = function (table, primaryKey, values, cb) { | |
if(primaryKey) { | |
var pk = values[primaryKey] || 0; | |
pk = pk.toString(); | |
delete values[primaryKey]; | |
} else { | |
primaryKey = '0'; | |
pk = '1'; | |
} | |
var query = "SELECT * FROM " + table + " WHERE " + primaryKey + " = ?"; | |
this.query(query, new Array(pk), function (err, data) { | |
if (err) { | |
console.log('failed finder partner') | |
return cb(err, []); | |
} | |
var keys = [], | |
valuesArray = [], | |
valuesDynamic = []; | |
for (var o in values) { | |
keys.push(o); | |
valuesArray.push(values[o]); | |
valuesDynamic.push('?') | |
} | |
var query = ""; | |
if (data.length == 0) { | |
// No matching record was found, create a new one. | |
query = "INSERT INTO " + table + " (" + keys.join(', ') + ') VALUES (' + valuesDynamic.join(', ') + '); SELECT SCOPE_IDENTITY() as insertId'; | |
} else { | |
valuesArray.push(pk); | |
query = "UPDATE " + table + " SET " + keys.join('=?, ') + '=? WHERE ' + primaryKey + ' = ?'; | |
} | |
db.query(query, valuesArray, function (err, data) { | |
if (err) { | |
return cb(err, []); | |
} else { | |
var insertId = null; | |
if(data[0] && data[0].insertId) { | |
insertId = data[0].insertId; | |
} | |
return cb(null, insertId); | |
} | |
}); | |
}); | |
}; | |
db.open(config.mssql.uri, function (err) { | |
if (err) { | |
console.error('DATABASE CONNECTION ERROR'); | |
console.error(err); | |
} | |
}); | |
module.exports = function () { | |
return db; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment