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 ONLYinto 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
LIMITclause (SelectQueryBuilder.limit(n)) as an alternative forFETCH FIRST n ROWS ONLYdepending 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
visitLimitmethod to change the behavior oflimit().Then extends a
Dialectclass and overridecreateQueryCompiler()method to use theQueryCompiler.Pass it to
Kyselyconstructor to use it.PostgresQueryCompilerandPostgresDialectare just examples. You can override any dialect you want.Full example: