Permalink
Browse files

feat: makeOrder in mysql adapter

  • Loading branch information...
XadillaX committed Aug 22, 2016
1 parent bf33649 commit c998ca4157f32bd4f163ae88163b6dbbc91cec02
Showing with 79 additions and 1 deletion.
  1. +27 −1 lib/adapters/mysql.js
  2. +52 −0 test/adapters/mysql.js
@@ -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) {
@@ -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;
@@ -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.