Kysely Codegen

0.20.0 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates installing `kysely-codegen`, configuring the database URL, generating TypeScript types, and then using the `DB` interface with Kysely to perform type-safe queries and insertions.

// 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();

view raw JSON →