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", "name": "wms-core",
"version": "0.21.13-rc.2", "version": "0.21.13-rc.3",
"description": "Node web application framework and toolbelt.", "description": "Node web application framework and toolbelt.",
"repository": "https://gitlab.com/ArisuOngaku/wms-core", "repository": "https://gitlab.com/ArisuOngaku/wms-core",
"author": "Alice Gaudon <alice@gaudon.pro>", "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 { 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; this._sortDirection = direction;
return this; return this;
} }
@ -140,8 +140,9 @@ export default class ModelQuery<M extends Model> implements WhereFieldConsumer<M
let join = ''; let join = '';
if (this._leftJoin) { if (this._leftJoin) {
const alias = this._leftJoinAlias ? ` AS \`${this._leftJoinAlias}\`` : ''; join = ` LEFT JOIN \`${this._leftJoin}\``
join = `LEFT JOIN \`${this._leftJoin}\`${alias} ON ${this._leftJoinOn[0]}`; + (this._leftJoinAlias ? ` AS \`${this._leftJoinAlias}\`` : '')
+ ` ON ${this._leftJoinOn[0]}`;
for (let i = 1; i < this._leftJoinOn.length; i++) { for (let i = 1; i < this._leftJoinOn.length; i++) {
join += this._leftJoinOn[i].toString(false); join += this._leftJoinOn[i].toString(false);
} }
@ -165,7 +166,8 @@ export default class ModelQuery<M extends Model> implements WhereFieldConsumer<M
let orderBy = ''; let orderBy = '';
if (typeof this._sortBy === 'string') { 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}\``; const table = `\`${this.table}\``;

View File

@ -3,6 +3,12 @@ import ModelFactory from "../src/db/ModelFactory";
import Model from "../src/db/Model"; import Model from "../src/db/Model";
describe('Test ModelQuery', () => { 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', () => { test('update', () => {
const query = ModelQuery.update({table: 'model'} as unknown as ModelFactory<Model>, { const query = ModelQuery.update({table: 'model'} as unknown as ModelFactory<Model>, {
'f1': 'v1', 'f1': 'v1',