Permalink
Browse files

feat: add delete by query

  • Loading branch information...
XadillaX committed Sep 27, 2016
1 parent 8141d80 commit 8d6d522dd6f894572b414ea3af2dcebe3be5c278
Showing with 89 additions and 0 deletions.
  1. +82 −0 lib/adapters/mysql.js
  2. +7 −0 lib/query.js
@@ -459,13 +459,56 @@ class MySQLAdapter extends Adapter {
}
}

if(options.order && options.order.length) {
const order = this.makeOrder(model, options.order);
if(order) {
sql += ` ORDER BY ${order}`;
}
}

if(options.limit && options.limit.length) {
const limit = this.makeLimit(model, options.limit);
if(limit) {
sql += ` LIMIT ${limit}`;
}
}

return sql;
}

makeDelete(model, options) {
options = options || {};
let sql = `DELETE FROM ${model.name}`;

if(options.where && Object.keys(options.where).length) {
const where = this.makeWhere(model, options.where);
if(where) {
sql += ` WHERE ${where}`;
}
}

if(options.order && options.order.length) {
const order = this.makeOrder(model, options.order);
if(order) {
sql += ` ORDER BY ${order}`;
}
}

if(options.limit && options.limit.length) {
const limit = this.makeLimit(model, options.limit);
if(limit) {
sql += ` LIMIT ${limit}`;
}
}

return sql;
}

makeSql(type, model, options) {
switch(type) {
case "find": return this.makeFind(model, options);
case "update": return this.makeUpdate(model, options);
case "delete": return this.makeDelete(model, options);
default: return this.makeFind(model, options);
}
}
@@ -658,6 +701,45 @@ class MySQLAdapter extends Adapter {
});
}

deleteByQuery(query, callback) {
const self = this;
const options = this.queryToOptions(query);
const sql = this.makeSql("delete", query.model, options);
const model = query.model;

let primaryKeys;
async.waterfall([
function(callback) {
if(!model.cache) {
return callback();
}

// delete related rows if using cache
const tempFields = options.fields;
primaryKeys = model.primaryKeys.map(key => key.name);
options.fields = primaryKeys;

const relatedSql = self.makeSql("find", query.model, options);
debug("find related rows when deleting", relatedSql);
self.execute(relatedSql, function(err, result) {
if(err) return callback(err);
model.cache.deleteKeys(self.getDBName(), model.name, result, function(err) {
options.fields = tempFields;
callback(err);
});
});
},

function(callback) {
debug("delete data by query", sql);
self.execute(sql, callback);
}
], function(err, result) {
if(err === null) err = undefined;
callback(err, result, sql);
});
}

insert(model, _data, callback) {
// let it be
// [ { field: foo, value: bar }, ... ]
@@ -193,6 +193,13 @@ class ToshihikoQuery {
return callback(err, result, extra);
});
}

delete(callback) {
if(undefined === callback) callback = emptyFunc;
this.adapter.deleteByQuery(this, function(err, result, extra) {
return callback(err, result, extra);
});
}
}

module.exports = ToshihikoQuery;

0 comments on commit 8d6d522

Please sign in to comment.