{"id":16844,"library":"kysely-codegen","title":"Kysely Codegen","description":"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.","status":"active","version":"0.20.0","language":"javascript","source_language":"en","source_url":"https://github.com/RobinBlomberg/kysely-codegen","tags":["javascript","typescript"],"install":[{"cmd":"npm install kysely-codegen","lang":"bash","label":"npm"},{"cmd":"yarn add kysely-codegen","lang":"bash","label":"yarn"},{"cmd":"pnpm add kysely-codegen","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required as the core type-safe SQL query builder library.","package":"kysely","optional":false},{"reason":"PostgreSQL driver for schema introspection.","package":"pg","optional":true},{"reason":"MySQL driver for schema introspection.","package":"mysql2","optional":true},{"reason":"SQLite driver for schema introspection.","package":"better-sqlite3","optional":true},{"reason":"LibSQL driver for schema introspection.","package":"@libsql/kysely-libsql","optional":true},{"reason":"MSSQL driver for schema introspection.","package":"tedious","optional":true},{"reason":"Connection pooling for MSSQL driver.","package":"tarn","optional":true},{"reason":"Connection string parsing for MSSQL driver.","package":"@tediousjs/connection-string","optional":true},{"reason":"Bun SQLite driver for schema introspection.","package":"kysely-bun-sqlite","optional":true},{"reason":"Bun worker-based SQLite driver for schema introspection.","package":"kysely-bun-worker","optional":true}],"imports":[{"note":"Used in configuration files (e.g., `.kysely-codegenrc.ts`) to provide type-safe configuration options for the CLI tool. Available since v0.20.0.","symbol":"defineConfig","correct":"import { defineConfig } from 'kysely-codegen/config';"},{"note":"For programmatic execution of the `kysely-codegen` CLI logic within Node.js scripts. This allows embedding the type generation process in custom build pipelines.","symbol":"generateCli","correct":"import { generateCli } from 'kysely-codegen/cli';"},{"note":"The `DB` type is *generated* by `kysely-codegen` into a `.d.ts` file (e.g., `src/db.d.ts` if `--out-file ./src/db.d.ts` is used, or `types.d.ts` by default). The `kysely-codegen` package itself does not directly export `DB`. Imports should point to the specific path where your types were generated. The example `import { DB } from 'kysely-codegen'` in the README is often misinterpreted.","wrong":"import { DB } from 'kysely-codegen';","symbol":"DB","correct":"import { DB } from './src/db.d.ts';"}],"quickstart":{"code":"// 1. Install dependencies (e.g., for PostgreSQL)\n// npm install --save-dev kysely-codegen\n// npm install kysely pg\n\n// 2. Create a .env file with your database connection string\n// DATABASE_URL=postgres://user:password@host:port/database_name\n\n// 3. Generate types from your database schema (run in your terminal)\n// npx kysely-codegen --out-file ./src/db.d.ts\n\n// 4. Use the generated types in your application code\nimport { Kysely, PostgresDialect, Insertable } from 'kysely';\nimport { Pool } from 'pg';\n// Assuming the generated file is at './src/db.d.ts'. Adjust path as needed.\nimport { DB, User, Company } from './src/db.d.ts';\n\n// Initialize Kysely with the generated DB type\nconst db = new Kysely<DB>({\n  dialect: new PostgresDialect({\n    pool: new Pool({\n      connectionString: process.env.DATABASE_URL ?? 'postgres://user:pass@localhost:5432/mydb',\n    }),\n  }),\n});\n\n// Example function to fetch all users\nasync function getAllUsers() {\n  console.log('Fetching users...');\n  const users = await db.selectFrom('user').selectAll().execute();\n  console.log('Found users:', users);\n  return users;\n}\n\n// Example function to insert a new user using Insertable type\nasync function createNewUser(userData: Insertable<User>) {\n  console.log('Creating a new user...');\n  const newUser = await db\n    .insertInto('user')\n    .values(userData)\n    .returningAll()\n    .executeTakeFirstOrThrow();\n  console.log('Created user:', newUser);\n  return newUser;\n}\n\nasync function runExample() {\n  try {\n    const users = await getAllUsers();\n    \n    const newUserPayload: Insertable<User> = {\n      email: `user_${Date.now()}@example.com`,\n      name: 'Generated User',\n      is_active: true,\n      company_id: null, // Assuming nullable or optional in your schema\n    };\n    await createNewUser(newUserPayload);\n\n    // Remember to close the database pool in a real application\n    await db.destroy();\n    console.log('Database connection closed.');\n  } catch (error) {\n    console.error('An error occurred during quickstart example:', error);\n  }\n}\n\nrunExample();\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Update CLI commands: `--schema` is now `--default-schema`, `--singular` is `--singularize`, and `--runtime-enums-style` was merged into `--runtime-enums`. Refer to the 0.18.0 release notes or the latest documentation for current options.","message":"Several CLI options were renamed in version 0.18.0. Old options will no longer be recognized.","severity":"breaking","affected_versions":">=0.18.0"},{"fix":"Use a tool or library to percent-encode any special characters (e.g., `#`, `!`, `@`, `$`) in your database password before setting the `DATABASE_URL` environment variable.","message":"When using `DATABASE_URL` for connection, ensure special characters in passwords are percent-encoded to avoid connection failures or parsing errors.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Append `?ssl={\"rejectUnauthorized\":true}` to your PlanetScale `DATABASE_URL`.","message":"For PlanetScale MySQL databases, the `DATABASE_URL` requires an explicit SSL query string parameter `ssl={\"rejectUnauthorized\":true}`.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Install `kysely` and your database driver (e.g., `pg`) explicitly using `npm install kysely pg`. Verify version compatibility with `kysely-codegen`'s peer dependency requirements.","message":"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.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Always import `DB` (and other generated types) from the output path specified during codegen, e.g., `import { DB } from './src/db.d.ts';`.","message":"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.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Use `--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`).","cause":"The `--schema` CLI option was renamed in `kysely-codegen` v0.18.0.","error":"error: unknown option '--schema'"},{"fix":"Double-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.","cause":"Incorrect database connection string, invalid credentials, or network access issues preventing connection to the database server.","error":"FATAL: password authentication failed for user \"your_user\""},{"fix":"Adjust 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.","cause":"Attempting to import the generated `DB` type directly from the `kysely-codegen` package, instead of from the file where the types were generated.","error":"Module 'kysely-codegen' has no exported member 'DB'."},{"fix":"Run `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.","cause":"The generated types (`DB`) are out of sync with the actual database schema, or a query is referencing a non-existent column/table.","error":"Error: Column 'column_name' not found in table 'table_name'"}],"ecosystem":"npm","meta_description":null}