Skip to content

Kysely

This content is not available in your language yet.

Kysely is a type-safe and autocompletion-friendly TypeScript SQL query builder.

It lets developers build SQL queries with a fluent API. It also helps to detect errors in queries by leveraging TypeScript.

A Little Case

In the following example, we use the Kysely query builder to fetch a user from the database:

import { Kysely, PostgresDialect } from 'kysely';
interface User {
id: number;
name: string;
email: string;
}
interface Post {
id: number;
title: string;
content: string;
authorId: number;
}
interface DB {
users: User;
posts: Post;
}
const db = new Kysely < DB > ({
dialect: new PostgresDialect({
pool: new Pool({
host: process.env.DATABASE_HOST,
database: process.env.DATABASE_DB,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
port: Number(process.env.DATABASE_PORT),
}),
}),
});
const user = db
.selectFrom('users')
.where('id', 1)
.select(['id', 'name', 'email'])
.executeTakeFirst();

Kysely uses the DB interface to type the result of the query. As a consequence, TypeScript infers the user variable as User | undefined (because the query may return an empty result).

Kysely helps to type the query result, and also the query itself. For example, if we try to select a column foo that does not exist in the user type, we will have a TypeScript error:

const user = db
.selectFrom('users')
.where('id', 1)
// Type Error: Argument of type 'string[]' is not assignable to parameter of type 'SelectExpression<DB, "users">'.
.select(['id', 'name', 'email', 'foo'])
.executeTakeFirst();

The error message is not very clear, but it helps to detect the bug and prevent runtime errors.

More Features In The Video

Useful Resources