From 19aafc76bf512b75eab1c2fc060ecc7e34c76a82 Mon Sep 17 00:00:00 2001 From: Alice Gaudon Date: Fri, 4 Sep 2020 15:07:31 +0200 Subject: [PATCH] mysql queries: wrap field names in "`" to avoid conflict with reserved words also do not add table name to field in select if it is already present --- src/db/Model.ts | 3 ++- src/db/ModelQuery.ts | 9 ++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/db/Model.ts b/src/db/Model.ts index 148fbf2..94ba992 100644 --- a/src/db/Model.ts +++ b/src/db/Model.ts @@ -164,7 +164,8 @@ export default abstract class Model { needs_full_update = true; } } - const result = await query(`INSERT INTO ${this.table} (${properties.join(', ')}) VALUES(${props_holders.join(', ')})`, values, connection); + const fieldNames = properties.map(f => `\`${f}\``).join(', '); + const result = await query(`INSERT INTO ${this.table} (${fieldNames}) VALUES(${props_holders.join(', ')})`, values, connection); if (this.hasOwnProperty('id')) this.id = result.other.insertId; this._cached_exists = true; diff --git a/src/db/ModelQuery.ts b/src/db/ModelQuery.ts index 76f863f..8843d6c 100644 --- a/src/db/ModelQuery.ts +++ b/src/db/ModelQuery.ts @@ -91,7 +91,9 @@ export default class ModelQuery { let query = ''; // Prevent wildcard and fields from conflicting - if (this._leftJoin) this.fields = this.fields.map(f => this.table + '.' + f); + if (this._leftJoin) { + this.fields = this.fields.map(f => f.toString().split('.').length === 1 ? `\`${this.table}\`.${f}` : f); + } if (this._pivot) this.fields.push(...this._pivot); @@ -275,7 +277,8 @@ class FieldValue { public toString(first: boolean = true): string { const valueStr = this.raw || this.value === null || this.value instanceof ModelQuery ? this.value : (Array.isArray(this.value) ? `(${'?'.repeat(this.value.length).split('').join(',')})` : '?'); - return `${!first ? ',' : ''}${this.field}${this.test}${valueStr}`; + let field = this.field.split('.').map(p => `\`${p}\``).join('.'); + return `${first ? '' : ','}${field}${this.test}${valueStr}`; } protected get test(): string { @@ -292,7 +295,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 : '?'}) AS \`${this.field}\``; } }