Registry / database / kysely-codegen

kysely-codegen

JSON →
library0.20.0jsnpmunverified

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.

npm install kysely-codegen
INSTALL
IMPORT
SIG · KYSELY-CODEGEN
K
kysely-codegen
databasejavascriptv0.20.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

defineConfig
import { defineConfig } from 'kysely-codegen/config';
Used in configuration files (e.g., `.kysely-codegenrc.ts`) to provide type-safe configuration options for the CLI tool. Available since v0.20.0.
generateCli
import { generateCli } from 'kysely-codegen/cli';
For programmatic execution of the `kysely-codegen` CLI logic within Node.js scripts. This allows embedding the type generation process in custom build pipelines.
DB
import { DB } from './src/db.d.ts';
import { DB } from 'kysely-codegen';
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.

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();
kysely-codegen --version
Debug
Known issues
breakingSeveral CLI options were renamed in version 0.18.0. Old options will no longer be recognized.
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.
affects: >=0.18.0
gotchaWhen using `DATABASE_URL` for connection, ensure special characters in passwords are percent-encoded to avoid connection failures or parsing errors.
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.
affects: >=0.1.0
gotchaFor PlanetScale MySQL databases, the `DATABASE_URL` requires an explicit SSL query string parameter `ssl={"rejectUnauthorized":true}`.
fix
Append `?ssl={"rejectUnauthorized":true}` to your PlanetScale `DATABASE_URL`.
affects: >=0.1.0
gotchaThe `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.
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.
affects: >=0.1.0
gotchaThe `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.
fix
Always import `DB` (and other generated types) from the output path specified during codegen, e.g., `import { DB } from './src/db.d.ts';`.
affects: >=0.1.0
Errors
Common errors & fixes
error: unknown option '--schema'
The `--schema` CLI option was renamed in `kysely-codegen` v0.18.0.
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`).
FATAL: password authentication failed for user "your_user"
Incorrect database connection string, invalid credentials, or network access issues preventing connection to the database server.
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.
Module 'kysely-codegen' has no exported member 'DB'.
Attempting to import the generated `DB` type directly from the `kysely-codegen` package, instead of from the file where the types were generated.
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.
Error: Column 'column_name' not found in table 'table_name'
The generated types (`DB`) are out of sync with the actual database schema, or a query is referencing a non-existent column/table.
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.
Upgrade
Version history
0.20.0latest on npm
Audit
Dependencies
kyselyrequiredRequired as the core type-safe SQL query builder library.
pgoptionalPostgreSQL driver for schema introspection.
mysql2optionalMySQL driver for schema introspection.
better-sqlite3optionalSQLite driver for schema introspection.
@libsql/kysely-libsqloptionalLibSQL driver for schema introspection.
tediousoptionalMSSQL driver for schema introspection.
tarnoptionalConnection pooling for MSSQL driver.
@tediousjs/connection-stringoptionalConnection string parsing for MSSQL driver.
kysely-bun-sqliteoptionalBun SQLite driver for schema introspection.
kysely-bun-workeroptionalBun worker-based SQLite driver for schema introspection.
Agent activity
4 hits · last 30 days
node
4
Resources