Skip to content

Commit

Permalink
Add 'count' function
Browse files Browse the repository at this point in the history
  • Loading branch information
manelcecs committed Jul 23, 2024
1 parent 79db661 commit f3bfe69
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/db/util/raw-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,20 @@ export type DestroyFn<F extends FieldDefinition> = (args: {

export type TruncateFn = (trx?: Knex.Transaction<any, any>) => Promise<void>;

export type CountFn<F extends FieldDefinition, AdditionalArgs = {}> = (
args?: {
where?: WhereCond<F>;
trx?: Knex.Transaction<any, any>;
/**
* Will produce `SELECT COUNT(DISTINCT "columnName")` and if there
* is an expression in `COUNT`, it will compute the number of input
* rows in which the input value is **not null**. So, besides selecting
* unique values of "columnName", it will also filter out `NULL` values
*/
distinct?: Array<keyof InstanceDataOf<F>>;
} & AdditionalArgs
) => Promise<bigint>;

export type ModelInternals<F extends FieldDefinition> = {
readonly type: 'single-table';
readonly tableName: string;
Expand All @@ -102,6 +116,7 @@ export type Model<F extends FieldDefinition, AdditionalFindArgs = {}> = {
readonly update: UpdateFn<F>;
readonly destroy: DestroyFn<F>;
readonly truncate: TruncateFn;
readonly count: CountFn<F, AdditionalFindArgs>;
};

export type InstanceDataOfModel<M extends Model<any>> = M extends Model<infer F>
Expand Down Expand Up @@ -252,6 +267,25 @@ export const defineRawModel =
await builder.truncate();
};

const count: CountFn<F> = async ({ where, trx, distinct } = {}) => {
const builder = trx ? masterTable().transacting(trx) : replicaTable();
const query = builder.where(prepareCondition(where ?? {}));

if (distinct !== undefined) {
query.countDistinct(distinct);
} else {
query.count('*');
}

const res = (await query) as unknown as [{ count: string }];

if (res.length !== 1) {
throw new Error('Count result must be an array of single element');
}

return BigInt(res[0].count);
};

return {
_internals: {
type: 'single-table',
Expand All @@ -266,5 +300,6 @@ export const defineRawModel =
update,
destroy,
truncate,
count,
};
};

0 comments on commit f3bfe69

Please sign in to comment.