Skip to content

Commit

Permalink
feat: crud time queries (#6895)
Browse files Browse the repository at this point in the history
## About the changes
Add time metrics to relevant queries:
- get
- getAll
- bulkInsert
- count
- exists
- get

Ignored because might not be that relevant:
- insert
- delete
- deleteAll
- update
  • Loading branch information
gastonfournier committed Apr 22, 2024
1 parent 126b788 commit ef91a5a
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/lib/db/crud/crud-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,13 @@ export abstract class CRUDStore<
}

async getAll(query?: Partial<InputModel>): Promise<OutputModel[]> {
const endTimer = this.timer('getAll');
let allQuery = this.db(this.tableName);
if (query) {
allQuery = allQuery.where(this.toRow(query) as Record<string, any>);
}
const items = await allQuery;
endTimer();
return items.map(this.fromRow) as OutputModel[];
}

Expand All @@ -80,9 +82,11 @@ export abstract class CRUDStore<
if (!items || items.length === 0) {
return [];
}
const endTimer = this.timer('bulkInsert');
const rows = await this.db(this.tableName)
.insert(items.map(this.toRow))
.returning('*');
endTimer();
return rows.map(this.fromRow) as OutputModel[];
}

Expand All @@ -105,27 +109,33 @@ export abstract class CRUDStore<
destroy(): void {}

async exists(id: IdType): Promise<boolean> {
const endTimer = this.timer('exists');
const result = await this.db.raw(
`SELECT EXISTS(SELECT 1 FROM ${this.tableName} WHERE id = ?) AS present`,
[id],
);
const { present } = result.rows[0];
endTimer();
return present;
}

async count(query?: Partial<InputModel>): Promise<number> {
const endTimer = this.timer('count');
let countQuery = this.db(this.tableName).count('*');
if (query) {
countQuery = countQuery.where(
this.toRow(query) as Record<string, any>,
);
}
const { count } = (await countQuery.first()) ?? { count: 0 };
endTimer();
return Number(count);
}

async get(id: IdType): Promise<OutputModel> {
const endTimer = this.timer('get');
const row = await this.db(this.tableName).where({ id }).first();
endTimer();
if (!row) {
throw new NotFoundError(`No item with id ${id}`);
}
Expand Down

0 comments on commit ef91a5a

Please sign in to comment.