Kysely Codegen
Kysely Codegen is a utility that generates TypeScript type definitions, specifically the `DB` interface, directly from your database schema for use with the Kysely type-safe SQL query builder. The current stable version is 0.20.0, with frequent minor releases introducing new features, bug fixes, and expanding dialect support. It offers broad compatibility across various SQL databases including PostgreSQL, MySQL, SQLite, MSSQL, and LibSQL. Key differentiators include its declarative configuration options, custom type mapping, the ability to process introspected metadata before code generation via `postprocess()`, and the newly introduced `defineConfig()` for type-safe configuration, ensuring developers have up-to-date and accurate type information without manual schema synchronization. It is primarily used as a CLI tool during development workflows.
Common errors
-
error: unknown option '--schema'
cause The `--schema` CLI option was renamed in `kysely-codegen` v0.18.0.fixUse `--default-schema` instead of `--schema`. For other renames, refer to the v0.18.0 changelog (e.g., `--singular` to `--singularize`, `--runtime-enums-style` merged into `--runtime-enums`). -
FATAL: password authentication failed for user "your_user"
cause Incorrect database connection string, invalid credentials, or network access issues preventing connection to the database server.fixDouble-check your `DATABASE_URL` environment variable for correct username, password, host, port, and database name. Ensure the database server is running and accessible from where `kysely-codegen` is executed. Consider percent-encoding special characters in your password. -
Module 'kysely-codegen' has no exported member 'DB'.
cause Attempting to import the generated `DB` type directly from the `kysely-codegen` package, instead of from the file where the types were generated.fixAdjust your import statement to point to the actual generated file, for example: `import { DB } from './path/to/your/db.d.ts';`. Ensure `kysely-codegen` has been run and the output file exists. -
Error: Column 'column_name' not found in table 'table_name'
cause The generated types (`DB`) are out of sync with the actual database schema, or a query is referencing a non-existent column/table.fixRun `npx kysely-codegen` again to regenerate the type definitions from your current database schema. Verify the column and table names in your Kysely query match the database.
Warnings
- breaking Several CLI options were renamed in version 0.18.0. Old options will no longer be recognized.
- gotcha When using `DATABASE_URL` for connection, ensure special characters in passwords are percent-encoded to avoid connection failures or parsing errors.
- gotcha For PlanetScale MySQL databases, the `DATABASE_URL` requires an explicit SSL query string parameter `ssl={"rejectUnauthorized":true}`.
- gotcha The `kysely` package (and specific database drivers like `pg`, `mysql2`, etc.) are peer dependencies. Ensure `kysely` is installed within the compatible version range (`>=0.27.0 <1.0.0`) along with your chosen database driver to prevent runtime issues or type mismatches.
- gotcha The `DB` type is generated into a file and must be imported from that file's path, not directly from the `kysely-codegen` package. Misinterpreting README examples can lead to `Module 'kysely-codegen' has no exported member 'DB'` errors.
Install
-
npm install kysely-codegen -
yarn add kysely-codegen -
pnpm add kysely-codegen
Imports
- defineConfig
import { defineConfig } from 'kysely-codegen/config'; - generateCli
import { generateCli } from 'kysely-codegen/cli'; - DB
import { DB } from 'kysely-codegen';import { DB } from './src/db.d.ts';
Quickstart
// 1. Install dependencies (e.g., for PostgreSQL)
// npm install --save-dev kysely-codegen
// npm install kysely pg
// 2. Create a .env file with your database connection string
// DATABASE_URL=postgres://user:password@host:port/database_name
// 3. Generate types from your database schema (run in your terminal)
// npx kysely-codegen --out-file ./src/db.d.ts
// 4. Use the generated types in your application code
import { Kysely, PostgresDialect, Insertable } from 'kysely';
import { Pool } from 'pg';
// Assuming the generated file is at './src/db.d.ts'. Adjust path as needed.
import { DB, User, Company } from './src/db.d.ts';
// Initialize Kysely with the generated DB type
const db = new Kysely<DB>({
dialect: new PostgresDialect({
pool: new Pool({
connectionString: process.env.DATABASE_URL ?? 'postgres://user:pass@localhost:5432/mydb',
}),
}),
});
// Example function to fetch all users
async function getAllUsers() {
console.log('Fetching users...');
const users = await db.selectFrom('user').selectAll().execute();
console.log('Found users:', users);
return users;
}
// Example function to insert a new user using Insertable type
async function createNewUser(userData: Insertable<User>) {
console.log('Creating a new user...');
const newUser = await db
.insertInto('user')
.values(userData)
.returningAll()
.executeTakeFirstOrThrow();
console.log('Created user:', newUser);
return newUser;
}
async function runExample() {
try {
const users = await getAllUsers();
const newUserPayload: Insertable<User> = {
email: `user_${Date.now()}@example.com`,
name: 'Generated User',
is_active: true,
company_id: null, // Assuming nullable or optional in your schema
};
await createNewUser(newUserPayload);
// Remember to close the database pool in a real application
await db.destroy();
console.log('Database connection closed.');
} catch (error) {
console.error('An error occurred during quickstart example:', error);
}
}
runExample();