ModelQuery: fix count() queries

This commit is contained in:
Alice Gaudon 2020-09-04 18:51:41 +02:00
parent 6a4898cbda
commit 823f5d0d26
2 changed files with 7 additions and 6 deletions

View File

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

View File

@ -92,7 +92,8 @@ export default class ModelQuery<M extends Model> {
// Prevent wildcard and fields from conflicting
if (this._leftJoin) {
this.fields = this.fields.map(f => f.toString().split('.').length === 1 ? `\`${this.table}\`.${f}` : f);
this.fields = this.fields
.map(f => !f.toString().startsWith('(') && f.toString().split('.').length === 1 ? `\`${this.table}\`.${f}` : f);
}
if (this._pivot) this.fields.push(...this._pivot);
@ -231,9 +232,9 @@ export default class ModelQuery<M extends Model> {
this._sortDirection = undefined;
this.fields.splice(0, this.fields.length);
this.fields.push('COUNT(*)');
this.fields.push(new SelectFieldValue('_count', 'COUNT(*)', true));
let queryResult = await this.execute(connection);
return queryResult.results[0]['COUNT(*)'];
return queryResult.results[0]['_count'];
}
}
@ -275,7 +276,7 @@ class FieldValue {
}
public toString(first: boolean = true): string {
const valueStr = this.raw || this.value === null || this.value instanceof ModelQuery ? this.value :
const valueStr = (this.raw || this.value === null || this.value instanceof ModelQuery) ? this.value :
(Array.isArray(this.value) ? `(${'?'.repeat(this.value.length).split('').join(',')})` : '?');
let field = this.field.split('.').map(p => `\`${p}\``).join('.');
return `${first ? '' : ','}${field}${this.test}${valueStr}`;
@ -295,7 +296,7 @@ class FieldValue {
class SelectFieldValue extends FieldValue {
public toString(first: boolean = true): string {
return `(${this.value instanceof ModelQuery ? this.value : '?'}) AS \`${this.field}\``;
return `(${this.value instanceof ModelQuery ? this.value : (this.raw ? this.value : '?')}) AS \`${this.field}\``;
}
}