Skip to content

Commit

Permalink
feat: add force index in query
Browse files Browse the repository at this point in the history
  • Loading branch information
XadillaX committed Sep 30, 2016
1 parent 7def8a0 commit 87a6882
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
30 changes: 28 additions & 2 deletions lib/adapters/mysql.js
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,11 @@ class MySQLAdapter extends Adapter {
return limit.map(l => parseInt(l) || 0).join(", ");
}

makeIndex(model, index) {
if(!index) return "";
return `FORCE INDEX(\`${index}\`)`;
}

makeSet(model, update) {
let pattern = "";
let params = [];
Expand Down Expand Up @@ -422,6 +427,13 @@ class MySQLAdapter extends Adapter {
"*";
sql += ` FROM \`${model.name}\``;

if(options.index) {
const index = this.makeIndex(model, options.index);
if(index) {
sql += ` ${index}`;
}
}

if(options.where && Object.keys(options.where).length) {
const where = this.makeWhere(model, options.where);
if(where) {
Expand Down Expand Up @@ -450,7 +462,16 @@ class MySQLAdapter extends Adapter {
options = options || {};
const set = this.makeSet(model, options.update);
if(!set) throw new Error("no set data.");
let sql = `UPDATE \`${model.name}\` SET ${set}`;
let sql = `UPDATE \`${model.name}\``;

if(options.index) {
const index = this.makeIndex(model, options.index);
if(index) {
sql += ` ${index}`;
}
}

sql += ` SET ${set}`;

if(options.where && Object.keys(options.where).length) {
const where = this.makeWhere(model, options.where);
Expand Down Expand Up @@ -480,6 +501,10 @@ class MySQLAdapter extends Adapter {
options = options || {};
let sql = `DELETE FROM \`${model.name}\``;

// http://stackoverflow.com/questions/2924671/mysql-delete-and-index-hint#answer-2924738
//
// `FORCE INDEX` is not for deletes

if(options.where && Object.keys(options.where).length) {
const where = this.makeWhere(model, options.where);
if(where) {
Expand Down Expand Up @@ -637,7 +662,8 @@ class MySQLAdapter extends Adapter {
where: query._where,
order: query._order,
limit: query._limit,
update: query._updateData
update: query._updateData,
index: query._index
}, options || {});

if(_options.single) {
Expand Down
6 changes: 6 additions & 0 deletions lib/query.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class ToshihikoQuery {
this._order = [];
this._updateData = {};
this._where = {};
this._index = "";

Object.defineProperties(this, {
// alias for fields, to be compatible
Expand All @@ -36,6 +37,11 @@ class ToshihikoQuery {
});
}

index(idx) {
this._index = idx;
return this;
}

where(condition) {
if(typeof condition !== "object") {
throw new Error(`query condition expected to be an object but got ${typeof condition} ${condition}.`);
Expand Down

0 comments on commit 87a6882

Please sign in to comment.