Cache model existence to support insert + update in the same transaction

This commit is contained in:
Alice Gaudon 2020-08-26 14:18:02 +02:00
parent cf4827933f
commit 72c4f972a0

View File

@ -43,6 +43,7 @@ export default abstract class Model {
protected readonly _factory: ModelFactory<any>; protected readonly _factory: ModelFactory<any>;
private readonly _components: ModelComponent<any>[] = []; private readonly _components: ModelComponent<any>[] = [];
private readonly _validators: { [key: string]: Validator<any> } = {}; private readonly _validators: { [key: string]: Validator<any> } = {};
private _cached_exists?: boolean = undefined;
[key: string]: any; [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); 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; if (this.hasOwnProperty('id')) this.id = result.other.insertId;
this._cached_exists = true;
} }
return needs_full_update; return needs_full_update;
@ -168,14 +170,19 @@ export default abstract class Model {
query = query.where(indexField, this[indexField]); query = query.where(indexField, this[indexField]);
} }
await query.execute(); await query.execute();
this._cached_exists = false;
} }
public async exists(): Promise<boolean> { public async exists(): Promise<boolean> {
let query = this._factory.select('1'); if (this._cached_exists === undefined) {
for (const indexField of this._factory.getPrimaryKeyFields()) { const query = this._factory.select('1');
query = query.where(indexField, this[indexField]); 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<void[]> { public async validate(onlyFormat: boolean = false, connection?: Connection): Promise<void[]> {