ModelQuery: fix backticks on ORDER BY and remove extra useless spaces

This commit is contained in:
Alice Gaudon 2020-09-05 16:09:30 +02:00
parent e403dfa863
commit 27bd7400e2
3 changed files with 24 additions and 16 deletions

View File

@ -1,6 +1,6 @@
{
"name": "wms-core",
"version": "0.21.13-rc.2",
"version": "0.21.13-rc.3",
"description": "Node web application framework and toolbelt.",
"repository": "https://gitlab.com/ArisuOngaku/wms-core",
"author": "Alice Gaudon <alice@gaudon.pro>",

View File

@ -95,7 +95,7 @@ export default class ModelQuery<M extends Model> implements WhereFieldConsumer<M
}
public sortBy(field: string, direction: 'ASC' | 'DESC' = 'ASC'): this {
this._sortBy = field;
this._sortBy = field.split('.').map(v => v.startsWith('`') ? v : `\`${v}\``).join('.');
this._sortDirection = direction;
return this;
}
@ -140,8 +140,9 @@ export default class ModelQuery<M extends Model> implements WhereFieldConsumer<M
let join = '';
if (this._leftJoin) {
const alias = this._leftJoinAlias ? ` AS \`${this._leftJoinAlias}\`` : '';
join = `LEFT JOIN \`${this._leftJoin}\`${alias} ON ${this._leftJoinOn[0]}`;
join = ` LEFT JOIN \`${this._leftJoin}\``
+ (this._leftJoinAlias ? ` AS \`${this._leftJoinAlias}\`` : '')
+ ` ON ${this._leftJoinOn[0]}`;
for (let i = 1; i < this._leftJoinOn.length; i++) {
join += this._leftJoinOn[i].toString(false);
}
@ -165,7 +166,8 @@ export default class ModelQuery<M extends Model> implements WhereFieldConsumer<M
let orderBy = '';
if (typeof this._sortBy === 'string') {
orderBy = `ORDER BY \`${this._sortBy}\` ${this._sortDirection}`;
orderBy = ` ORDER BY ${this._sortBy}`
+ (this._sortDirection ? ' ' + this._sortDirection : '');
}
const table = `\`${this.table}\``;

View File

@ -3,6 +3,12 @@ import ModelFactory from "../src/db/ModelFactory";
import Model from "../src/db/Model";
describe('Test ModelQuery', () => {
test('order by', () => {
const query = ModelQuery.select({table: 'model'} as unknown as ModelFactory<Model>)
.sortBy('model.f2', 'ASC');
expect(query.toString(true)).toBe('SELECT `model`.* FROM `model` ORDER BY `model`.`f2` ASC');
});
test('update', () => {
const query = ModelQuery.update({table: 'model'} as unknown as ModelFactory<Model>, {
'f1': 'v1',