Skip to content

Commit

Permalink
feat: makeOrder in mysql adapter
Browse files Browse the repository at this point in the history
  • Loading branch information
XadillaX committed Aug 22, 2016
1 parent bf33649 commit c998ca4
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 1 deletion.
28 changes: 27 additions & 1 deletion lib/adapters/mysql.js
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,22 @@ class MySQLAdapter extends Adapter {
return `(${fragments.join(` ${logic} `)})`;
}

makeOrder(model, order) {
order = _.compact(order.map(o => {
const key = Object.keys(o)[0];
if(!key) return null;
const field = model.fieldNamesMap[key];
if(!field) {
throw new Error(`no field named "${key}" in model "${model.name}"`);
}

return `\`${field.column}\` ${o[key] > 0 ? "ASC" : "DESC"}`;
}));
if(!order.length) return "";

return order.join(", ");
}

makeFind(model, options) {
let fields = options.fields;
if(!fields || !fields.length) {
Expand All @@ -356,7 +372,17 @@ class MySQLAdapter extends Adapter {
sql += ` FROM \`${model.name}\``;

if(options.where && Object.keys(options.where)) {
sql += ` WHERE ${this.makeWhere(model, options.where)}`;
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}`;
}
}

return sql;
Expand Down
52 changes: 52 additions & 0 deletions test/adapters/mysql.js
Original file line number Diff line number Diff line change
Expand Up @@ -279,5 +279,57 @@ describe("🐣 adapters/mysql", function() {
}
});
});

describe(`${name} makeOrder`, function() {
const toshihiko = new Toshihiko("mysql", {
username: "root",
password: "",
database: "toshihiko",
charset: "utf8mb4_general_ci"
});
const adapter = toshihiko.adapter;
const model = toshihiko.define("test", common.COMMON_SCHEMA);

after(function() {
adapter.mysql.end();
});


it("should generate - 1", function() {
let sql;

sql = adapter.makeOrder(model, [ { key1: -1 } ]);
sql.should.equal("`id` DESC");

sql = adapter.makeOrder(model, []);
sql.should.equal("");

sql = adapter.makeOrder(model, [{
key1: -1
}, {
key2: 1
}, {
key3: 2
}, {
key4: -1
}, {
key5: "123"
}]);
sql.should.equal("`id` DESC, `key2` ASC, `key3` ASC, `key4` DESC, `key5` ASC");
});

it("should generate - 2", function() {
let sql;

sql = adapter.makeOrder(model, [ {} ]);
sql.should.equal("");

try {
sql = adapter.makeOrder(model, [ { id: -1 } ]);
} catch(e) {
e.message.indexOf("no field").should.above(-1);
}
});
});
});
});

0 comments on commit c998ca4

Please sign in to comment.