Skip to content

createDrizzleKeyset

function createDrizzleKeyset(input): DrizzleKeyset;

Defined in: filters/drizzle/pagination.ts:93

Build a keyset (cursor) helper from a sort spec + the Drizzle columns each logical key maps to. The last sort column MUST be unique (a tiebreaker like id) so the cursor is stable.

orderBy(direction) gives the ORDER BY for a fetch ("backward" flips every column) and where(cursor, direction) the lexicographic seek after (or before) the cursor row, or undefined for a null cursor (the first page). Sort keys without a column in columns are skipped.

Parameter Type
input { columns: Record<string, AnyColumn>; sort: KeysetSortColumn[]; }
input.columns Record<string, AnyColumn>
input.sort KeysetSortColumn[]

DrizzleKeyset

import { PgDialect, pgTable, text, timestamp } from "drizzle-orm/pg-core";
import { createDrizzleKeyset } from "@xtandard/lib/filters/drizzle";
const posts = pgTable("posts", { id: text("id").primaryKey(), createdAt: timestamp("created_at", { mode: "date" }) });
const keyset = createDrizzleKeyset({
sort: [{ key: "createdAt", order: "desc" }, { key: "id", order: "desc" }], // unique tiebreaker last
columns: { createdAt: posts.createdAt, id: posts.id },
});
const dialect = new PgDialect();
keyset.orderBy().map((o) => dialect.sqlToQuery(o).sql); // → ['"posts"."created_at" desc', '"posts"."id" desc']
keyset.where(null); // → undefined (first page)
const seek = keyset.where({ createdAt: new Date("2026-06-18T00:00:00Z"), id: "p_9" });
dialect.sqlToQuery(seek!).sql;
// → '("posts"."created_at" < $1 or ("posts"."created_at" = $2 and "posts"."id" < $3))'
// in an app: db.select().from(posts).where(seek).orderBy(...keyset.orderBy()).limit(21)