generalized update sql templating for create

This commit is contained in:
AJ ONeal 2015-09-22 02:08:58 -06:00
parent a3fabc87d2
commit 26311eba3b
1 changed files with 76 additions and 47 deletions

View File

@ -186,13 +186,19 @@ function wrap(db, dir) {
return new PromiseA(function (resolve, reject) {
var json = JSON.stringify(obj);
var data = JSON.parse(json);
delete data[idnameCased];
json = JSON.stringify(data);
var sql = "INSERT INTO " + tablename + " (" + idname + ", json) VALUES (?, ?)";
var values = [id, json];
var sql;
db.run(sql, values, function (err) {
// removes known fields from data
sql = strainUpdate(id, data, function sqlTpl(fieldable) {
return "INSERT INTO " + tablename + " (" + fieldable.join(', ') + ", " + idname + ")"
//+ " VALUES ('" + vals.join("', '") + "')"
+ " VALUES (" + fieldable.map(function () { return '?'; }).join(", ") + ", ?)"
;
});
console.log('[debug] DB.create() sql:', sql);
db.run(sql, [], function (err) {
if (err) {
reject(err);
return;
@ -215,13 +221,11 @@ function wrap(db, dir) {
});
};
DB.set = function (id, obj) {
var json = JSON.stringify(obj);
var data = JSON.parse(json);
return new PromiseA(function (resolve, reject) {
var sql;
// pull indices from object
function strainUpdate(id, data/*, vals*/, cb) {
var fieldable = [];
var json;
var sql;
var vals = [];
(opts.indices || []).forEach(function (col) {
@ -242,28 +246,53 @@ function wrap(db, dir) {
+ " = '" + db.escape(val) + "'"
);
*/
fieldable.push(db.escape(snakeCase(col.name)) + " = ?");
fieldable.push(db.escape(snakeCase(col.name)));
vals.push(val);
}
delete data[col.name];
delete data[camelCase(col.name)];
});
delete data[idnameCased];
if (!fieldable.length || Object.keys(data).length) {
json = JSON.stringify(data);
fieldable.push("json = ?");
fieldable.push("json");
//fieldable.push("json = '" + db.escape(json) + "'");
vals.push(json);
}
vals.push(id);
sql = "UPDATE " + tablename + " SET " + fieldable.join(', ') + " WHERE " + idname + " = ?";
sql = cb(fieldable);
while (vals.length) {
sql = sql.replace(/\?/, "'" + db.escape(vals.shift()) + "'");
}
console.log('[debug] sql:', sql);
db.run(sql, vals, function (err) {
return sql;
}
DB.set = function (id, obj) {
var json = JSON.stringify(obj);
var data = JSON.parse(json);
return new PromiseA(function (resolve, reject) {
function sqlTpl(fieldable) {
// this will always at least have one fieldable value: json
return "UPDATE " + tablename + " SET "
+ (fieldable.join(' = ?, ') + " = ?")
+ " WHERE " + idname + " = ?"
;
}
//var vals = [];
// removes known fields from data
var sql = strainUpdate(id, data/*, vals*/, sqlTpl);
console.log('[debug] DB.set() sql:', sql);
db.run(sql, /*vals*/[], function (err) {
if (err) {
reject(err);
return;