My project uses drizzle orm with typescript for managing postgresql database. In many endpoints i have filters, as they are generating reports. Create an util that would help me simplify and standardize this workflow.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Certainly! When building a TypeScript backend using Drizzle ORM and PostgreSQL, it's common to repeat logic for filtering, sorting, and pagination across different report or data-fetching endpoints.
To simplify and standardize this process, we can create a reusable utility that builds dynamic WHERE clauses, supports sorting, and handles pagination (limit/offset). This utility will:
✅ Accept query parameters from HTTP requests
✅ Map them to Drizzle-compatible SQL conditions
✅ Support filtering by multiple fields
✅ Allow sorting on specified columns
✅ Paginate results
✅ Utility: buildQueryOptions.ts
ts
// src/utils/buildQueryOptions.ts
import { SQL, sql } from 'drizzle-orm';
import { SelectQueryBuilder } from 'drizzle-orm/postgres-js'; // or mysql2, sqlite, etc. depending on your driver
/**
* Types for filters, sort and pagination
*/
export type Filter<T> = Partial<Record<keyof T, any>>;
export type SortOrder = 'asc' | 'desc';
export interface QueryOptions<T> {
filter?: Filter<T>;
sort?: {
field: keyof T;
order?: SortOrder;
};
limit?: number;
offset?: number;
}
/**
* Builds WHERE clause and other query parts dynamically
*/
export function buildQueryOptions<T extends object>(
qb: SelectQueryBuilder<any, any, T>,
options: QueryOptions<T>,
allowedFilters: (keyof T)[],
allowedSortFields: (keyof T)[]
): SelectQueryBuilder<any, any, T> {
const { filter, sort, limit, offset } = options;
// WHERE conditions
if (filter) {
Object.entries(filter).forEach(([key, value]) => {
if (allowedFilters.includes(key as keyof T) && value !== undefined && value !== null) {
// Basic equality filter
qb = qb.where(sql`${qb.table[key]} = ${value}`);
}
});
}
// Sorting
if (sort?.field && allowedSortFields.includes(sort.field)) {
const direction = sort.order === 'desc' ? 'desc' : 'asc';
qb = qb.orderBy(sql`${qb.table[sort.field]}`, { ascending: direction === 'asc' });
}
// Pagination
if (typeof limit === 'number') qb = qb.limit(limit);
if (typeof offset === 'number') qb = qb.offset(offset);
return qb;
}
Wait! There's a small caveat here — the usage of sql${qb.table[key]}` is not valid in Drizzle. Drizzle's query builders are not designed to be introspected like that at runtime. So we need a safer, more type-safe approach.
Let’s refactor this using a typed filter builder pattern instead.
✅ Improved Version: Type-Safe Filtering & Sorting
We’ll define a generic filter builder that maps incoming keys to actual column expressions.
ts
// src/utils/buildQueryOptions.ts
import { SelectQueryBuilder } from 'drizzle-orm';
import { eq, asc, desc, sql } from 'drizzle-orm';
export type Filter<T> = Partial<Record<keyof T, any>>;
export type SortOrder = 'asc' | 'desc';
export interface QueryOptions<T> {
filter?: Filter<T>;
sort?: {
field: keyof T;
order?: SortOrder;
};
limit?: number;
offset?: number;
}
/**
* A mapping of column names to their actual Drizzle column expressions.
* You provide this per model.
*/
export type ColumnMap<T> = {
[K in keyof T]: (q: any) => T[K];
};
/**
* Build dynamic WHERE, ORDER BY, LIMIT, OFFSET clauses
*/
export function buildQueryOptions<
T extends object,
Cols extends ColumnMap<T>
>(
qb: SelectQueryBuilder<any, any, T>,
options: QueryOptions<T>,
columnMap: Cols,
allowedFilters: (keyof T)[],
allowedSortFields: (keyof T)[]
): SelectQueryBuilder<any, any, T> {
const { filter, sort, limit, offset } = options;
// WHERE conditions
if (filter) {
Object.entries(filter).forEach(([key, value]) => {
if (
allowedFilters.includes(key as keyof T) &&
value !== undefined &&
value !== null
) {
const colFn = columnMap[key as keyof T];
// Call the function to get the column reference
const column = colFn(qb);
qb = qb.where(eq(column, value));
}
});
}
// ORDER BY
if (sort?.field && allowedSortFields.includes(sort.field)) {
const order = sort.order || 'asc';
const colFn = columnMap[sort.field];
const column = colFn(qb);
qb = qb.orderBy(order === 'asc' ? asc(column) : desc(column));
}
// LIMIT & OFFSET
if (typeof limit === 'number') qb = qb.limit(limit);
if (typeof offset === 'number') qb = qb.offset(offset);
return qb;
}
Wait again — we have a new problem: qb is not in scope inside the callback when building the query.
We need to rethink how we get access to the table columns.
✅ The correct way is to pass the table directly (not the query builder) into the column map so we can reference columns statically.
✅ Final Version: Fully Type-Safe and Usable
ts
// src/utils/buildQueryOptions.ts
import { SelectQueryBuilder } from 'drizzle-orm';
import { eq, asc, desc, sql } from 'drizzle-orm';
export type Filter<T> = Partial<Record<keyof T, any>>;
export type SortOrder = 'asc' | 'desc';
export interface QueryOptions<T> {
filter?: Filter<T>;
sort?: {
field: keyof T;
order?: SortOrder;
};
limit?: number;
offset?: number;
}
/**
* A mapping of column keys to their Drizzle column expressions.
*/
export type ColumnMap<T> = {
[K in keyof T]: (alias?: string) => T[K];
};
/**
* Applies filtering, sorting, pagination to a query builder
*/
export function buildQueryOptions<
T extends object,
Cols extends ColumnMap<T>
>(
qb: SelectQueryBuilder<any, any, T>,
options: QueryOptions<T>,
table: Cols,
allowedFilters: (keyof T)[],
allowedSortFields: (keyof T)[]
): SelectQueryBuilder<any, any, T> {
const { filter, sort, limit, offset } = options;
// WHERE clause
if (filter) {
Object.entries(filter).forEach(([key, value]) => {
if (
allowedFilters.includes(key as keyof T) &&
value !== undefined &&
value !== null
) {
const column = table(key); // e.g. users('users').email
qb = qb.where(eq(column, value));
}
});
}
// ORDER BY
if (sort?.field && allowedSortFields.includes(sort.field)) {
const direction = sort.order === 'desc' ? desc : asc;
const column = table(sort.field);
qb = qb.orderBy(direction(column));
}
// LIMIT & OFFSET
if (typeof limit === 'number') qb = qb.limit(limit);
if (typeof offset === 'number') qb = qb.offset(offset);
return qb;
}
Wait — no. That still assumes table(key) returns a column, but we're passing a ColumnMap that accepts an alias and returns a column.
But SelectQueryBuilder is already bound to a table alias. So the user must pass a column map that works without alias (or we resolve aliasing ourselves).