Kysely TypeSafe Query Builder
Build fully typed SQL with Kysely, from typed table definitions through dynamic where clauses to exactly shaped result row types.
Code
import { Kysely, PostgresDialect, Generated, sql } from 'kysely';
import { Pool } from 'pg';
interface Database {
articles: {
id: Generated<number>;
title: string;
authorId: number;
published: boolean;
};
authors: {
id: Generated<number>;
name: string;
};
}
const db = new Kysely<Database>({
dialect: new PostgresDialect({
pool: new Pool({ connectionString: process.env.DATABASE_URL }),
}),
});
type Filter = { author?: string; onlyPublished?: boolean };
async function searchArticles(filter: Filter) {
let query = db
.selectFrom('articles')
.innerJoin('authors', 'authors.id', 'articles.authorId')
.select(['articles.id', 'articles.title', 'authors.name as author']);
if (filter.author !== undefined) {
query = query.where('authors.name', '=', filter.author);
}
if (filter.onlyPublished) {
query = query.where('articles.published', '=', true);
}
const rows = await query
.orderBy('articles.id', 'desc')
.limit(25)
.execute();
return rows;
}
const fresh = await searchArticles({ onlyPublished: true });
console.log('typed author column:', fresh[0]?.author.length ?? 0);
await db.destroy();How it works
Kysely TypeSafe Query Builder is built around the function searchArticles.
Await points sequence the asynchronous work; a rejection lands at the awaiting line. The import line is the dependency contract: Kysely, PostgresDialect, Generated, sql, Pool come from kysely and nothing else.
Configuration comes from the environment — it reads DATABASE_URL, so the same code switches behavior between environments without edits.
Caveats
- Dependency check:
kyselyandpg— not built-in, must be present in the project.
Putting it to use
The primary signature is async function searchArticles(filter: Filter)
The demo output is labeled (typed author column:), so every printed line ties back to the operation behind it.
Core lines
const fresh = await searchArticles({ onlyPublished: true });
await db.destroy();
const rows = await query
.orderBy('articles.id', 'desc')
.limit(25)
.execute();
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- `kysely` and `pg` — install them with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.