diff --git a/src/db/Model.ts b/src/db/Model.ts index b1a291a..e1dcf29 100644 --- a/src/db/Model.ts +++ b/src/db/Model.ts @@ -43,6 +43,7 @@ export default abstract class Model { protected readonly _factory: ModelFactory; private readonly _components: ModelComponent[] = []; private readonly _validators: { [key: string]: Validator } = {}; + private _cached_exists?: boolean = undefined; [key: string]: any; @@ -155,6 +156,7 @@ export default abstract class Model { const result = await query(`INSERT INTO ${this.table} (${properties.join(', ')}) VALUES(${props_holders.join(', ')})`, values, connection); if (this.hasOwnProperty('id')) this.id = result.other.insertId; + this._cached_exists = true; } return needs_full_update; @@ -168,14 +170,19 @@ export default abstract class Model { query = query.where(indexField, this[indexField]); } await query.execute(); + this._cached_exists = false; } public async exists(): Promise { - let query = this._factory.select('1'); - for (const indexField of this._factory.getPrimaryKeyFields()) { - query = query.where(indexField, this[indexField]); + if (this._cached_exists === undefined) { + const query = this._factory.select('1'); + for (const indexField of this._factory.getPrimaryKeyFields()) { + query.where(indexField, this[indexField]); + } + this._cached_exists = (await query.limit(1).execute()).results.length > 0; } - return (await query.limit(1).execute()).results.length > 0; + + return this._cached_exists; } public async validate(onlyFormat: boolean = false, connection?: Connection): Promise {