My favorite DB toolkit for use with TypeScrypt-based projects is Prisma. However, one of the projects is using Kysely type-safe DB query builder.
I am trying to prepare a query that would handle keyset pagination using Kysely query builder, but I can't figure out how to add FETCH FIRST n ROWS ONLY
into the query if that is even possible.
Kysely docs: https://kysely.dev/docs/category/select
Any ideas or suggestions?
import { Kysely, sql } from "kysely";
const DB = new Kysely<Database>({...});
const query = DB
.selectFrom("cl")
.selectAll()
.where(sql`(created_at, id)`, '>', `('${keyFromCreatedAt}', '${keyFromId}')`)
// ¿¿¿ Something to insert FETCH FIRST n ROWS ONLY? ???
;
const res = query.execute();
First of all, you can use
LIMIT
clause (SelectQueryBuilder.limit(n)
) as an alternative forFETCH FIRST n ROWS ONLY
depending on the dialect you are using. If you have to useFETCH FIRST n ROWS ONLY
, you should implement you ownQueryCompiler
.It doesn't take a lot of time. Everything is already implemented in DefaultQueryCompiler. All you should do is extend it and override a single method. For example, PostgresQueryCompiler overrides single method from DefaultQueryCompiler.
Defined your custom QueryCompiler and override
visitLimit
method to change the behavior oflimit()
.Then extends a
Dialect
class and overridecreateQueryCompiler()
method to use theQueryCompiler
.Pass it to
Kysely
constructor to use it.PostgresQueryCompiler
andPostgresDialect
are just examples. You can override any dialect you want.Full example: