Permalink
Browse files

feat: add force index in query

  • Loading branch information...
XadillaX committed Sep 30, 2016
1 parent 7def8a0 commit 87a6882cbcc65cda206c554af4f08b093cbbd702
Showing with 34 additions and 2 deletions.
  1. +28 −2 lib/adapters/mysql.js
  2. +6 −0 lib/query.js
@@ -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 = [];
@@ -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) {
@@ -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);
@@ -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) {
@@ -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) {
@@ -26,6 +26,7 @@ class ToshihikoQuery {
this._order = [];
this._updateData = {};
this._where = {};
this._index = "";

Object.defineProperties(this, {
// alias for fields, to be compatible
@@ -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}.`);

0 comments on commit 87a6882

Please sign in to comment.