fix snakecasing, add order by

This commit is contained in:
AJ ONeal 2015-09-21 20:14:07 -06:00
parent 9a25ad99a1
commit 75089a9f54
1 changed files with 38 additions and 10 deletions

View File

@ -38,6 +38,7 @@ function wrap(db, dir) {
var DB = {};
var tablename = db.escape(snakeCase(opts.tablename) || 'data');
var idname = db.escape(snakeCase(opts.idname) || 'id');
var idnameCased = (camelCase(opts.idname) || 'id');
db = PromiseA.promisifyAll(db);
@ -65,7 +66,7 @@ function wrap(db, dir) {
obj = {};
}
obj[idname] = row[idname];
obj[idnameCased] = row[idname];
return obj;
}
@ -87,7 +88,7 @@ function wrap(db, dir) {
obj = {};
}
obj[idname] = row[idname];
obj[idnameCased] = row[idname];
});
// set up for garbage collection
rows.length = 0;
@ -96,7 +97,7 @@ function wrap(db, dir) {
return results;
}
DB.find = function (opts) {
DB.find = function (opts, params) {
var sql = 'SELECT * FROM ' + tablename + ' WHERE ';
Object.keys(opts).forEach(function (key, i) {
@ -106,6 +107,15 @@ function wrap(db, dir) {
sql += db.escape(snakeCase(key)) + ' ' + db.escape(opts[key]);
});
if (params) {
if (params.orderBy) {
sql += ' ORDER BY ' + db.escape(snakeCase(params.orderBy));
if (params.orderByDesc) {
sql += ' DESC';
}
}
}
return db.allAsync("SELECT * FROM " + tablename + " " + sql, []).then(simpleMap);
};
@ -139,29 +149,46 @@ function wrap(db, dir) {
};
DB.save = function (data) {
if (!data[idname]) {
if (!data[idnameCased]) {
// NOTE saving the id both in the object and the id for now
var UUID = require('node-uuid');
data[idname] = UUID.v4();
return DB.create(data[idname], data).then(function (/*stats*/) {
data[idnameCased] = UUID.v4();
return DB.create(data[idnameCased], data).then(function (/*stats*/) {
//data._rowid = stats.id;
return data;
});
}
return DB.set(data[idname], data).then(function (result) {
return DB.set(data[idnameCased], data).then(function (result) {
var success = result.changes >= 1;
if (success) {
return result;
} else {
console.log('[debug result of set]', result.sql);
delete result.sql;
console.log(result);
}
return null;
});
};
DB.create = function (id, data) {
var json = JSON.stringify(data);
DB.create = function (id, obj) {
if (!obj) {
obj = id;
id = obj[idnameCased];
}
if (!id) {
return PromiseA.reject(new Error("no id supplied"));
}
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];
@ -221,6 +248,7 @@ function wrap(db, dir) {
delete data[col.name];
});
delete data[idnameCased];
json = JSON.stringify(data);
fieldable.push("json = ?");
@ -258,7 +286,7 @@ function wrap(db, dir) {
DB.destroy = function (id) {
if ('object' === typeof id) {
id = id[idname];
id = id[idnameCased];
}
return new PromiseA(function (resolve, reject) {