Skip to content

Commit

Permalink
Add 'distinct' clause
Browse files Browse the repository at this point in the history
  • Loading branch information
manelcecs committed Jul 11, 2024
1 parent 0c59cd7 commit ef4a0c8
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/db/util/raw-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export type FindFn<F extends FieldDefinition, AdditionalArgs = {}> = (
skipValidation?: boolean;
trx?: Knex.Transaction<any, any>;
orderByNullsLast?: boolean;
distinct?: Array<keyof InstanceDataOf<F>>;
} & AdditionalArgs
) => Promise<Array<InstanceDataOf<F>>>;

Expand Down Expand Up @@ -162,6 +163,7 @@ export const defineRawModel =
skipValidation = false,
trx,
orderByNullsLast,
distinct,
} = {}) => {
const builder = trx ? masterTable().transacting(trx) : replicaTable();
const query = builder.where(prepareCondition(where ?? {})).select('*');
Expand All @@ -188,6 +190,20 @@ export const defineRawModel =
}
}

if (distinct !== undefined) {
if (orderBy !== undefined) {
// We need to add both the columns in the order by clause and the distinct clause
// Merge the list of columns and keep only unique values
const distinctColumns = [
...new Set([...distinct, ...orderBy.map((order) => order.column)]),
];
query.distinctOn(distinctColumns);
} else {
// If there is no order by clause, we can directly use the distinct clause
query.distinctOn(distinct);
}
}

const res = await query;

if (skipValidation) {
Expand Down

0 comments on commit ef4a0c8

Please sign in to comment.