Getting Started
Introduction
Kysely is a type-safe and autocompletion-friendly TypeScript SQL query builder.
Prerequisites
Before getting started with Kysely, make sure you have:
-
TypeScript version 4.6 or later installed
-
TypeScript's strict mode enabled in your
tsconfig.json
Installation
Types
To enable Kysely's type-safety and autocompletion features, you need to define your database structure using TypeScript interfaces. The main Database interface maps table names to their corresponding schema interfaces.
Here's how to define your first database interface:
Codegen
For production applications, it's highly recommended to automatically generate your Database
interface by introspecting your database schema or Prisma schema. This ensures your TypeScript types stay in sync with your actual database structure.
You can learn more about the available code generation options in the Generate Types guide.
Dialects
Kysely needs a Dialect to work with your database. A Dialect tells Kysely:
- How to compile SQL queries for your specific database
- How to connect and communicate with your database
Kysely comes with built-in support for 4 popular databases:
- PostgreSQL
- MySQL
- Microsoft SQL Server (MSSQL)
- SQLite
The community has also created dialects for other databases. Check out Dialects to learn more.
Dialect Driver Installation
Kysely's built-in PostgreSQL dialect uses the "pg" driver library under the hood. Please refer to its official documentation for configuration options.
Let's create a Kysely instance using the built-in PostgresDialect
dialect:
Building Your First Query Repository
Now that we have our database connection set up, let's explore how to build type-safe queries by implementing a repository pattern for managing person records. This example will demonstrate common CRUD operations using Kysely's expressive API: