npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

kysely-codegen-sqlite

v0.2.0

Published

`kysely-codegen-sqlite` generates Kysely type definitions from your SQLite database. That's it.

Readme

kysely-codegen-sqlite

kysely-codegen-sqlite generates Kysely type definitions from your SQLite database. That's it.

Table of contents

Installation

npm install --save-dev kysely-codegen-sqlite

You will also need to install Kysely with your driver of choice:

npm install kysely better-sqlite3

Generating type definitions

The most convenient way to get started is to create an .env file with your database connection string:

DATABASE_URL=./path/to/database.db

Then run the following command, or add it to the scripts section in your package.json file:

kysely-codegen-sqlite

This command will generate a .d.ts file from your database, for example:

import { ColumnType } from 'kysely';

export type Generated<T> = T extends ColumnType<infer S, infer I, infer U>
  ? ColumnType<S, I | undefined, U>
  : ColumnType<T, T | undefined, T>;

export interface Company {
  id: Generated<number>;
  name: string;
}

export interface User {
  company_id: number | null;
  created_at: Generated<string>;
  email: string;
  id: Generated<number>;
  is_active: number;
  name: string;
  updated_at: string;
}

export interface DB {
  company: Company;
  user: User;
}

To specify a different output file:

kysely-codegen-sqlite --out-file ./src/db/db.d.ts

Using the type definitions

Import DB into new Kysely<DB>, and you're done!

import { Kysely } from 'kysely';
import BetterSqlite3 from 'better-sqlite3';
import { BetterSqlite3Dialect } from 'kysely';
import { DB } from 'kysely-codegen-sqlite';

const db = new Kysely<DB>({
  dialect: new BetterSqlite3Dialect({
    database: new BetterSqlite3('./database.db'),
  }),
});

const rows = await db.selectFrom('users').selectAll().execute();
//    ^ { created_at: string; email: string; id: number; ... }[]

If you need to use the generated types in e.g. function parameters and type definitions, you may need to use the Kysely Insertable, Selectable, Updateable types. Note that you don't need to explicitly annotate query return values, as it's recommended to let Kysely infer the types for you.

import { Insertable, Updateable } from 'kysely';
import { DB } from 'kysely-codegen-sqlite';
import { db } from './db';

async function insertUser(user: Insertable<User>) {
  return await db
    .insertInto('users')
    .values(user)
    .returningAll()
    .executeTakeFirstOrThrow();
  // ^ Selectable<User>
}

async function updateUser(id: number, user: Updateable<User>) {
  return await db
    .updateTable('users')
    .set(user)
    .where('id', '=', id)
    .returning(['email', 'id'])
    .executeTakeFirstOrThrow();
  // ^ { email: string; id: number; }
}

Read the Kysely documentation for more information.

CLI arguments

--camel-case

Use the Kysely CamelCasePlugin for generated table column names.

Example:

export interface User {
  companyId: number | null;
  createdAt: Generated<string>;
  email: string;
  id: Generated<number>;
  isActive: number;
  name: string;
  updatedAt: string;
}

--config-file

Specify the path to the configuration file to use.

--custom-imports

Specify custom type imports to use with type overrides. This is particularly useful when using custom types from external packages or local files.

Basic example
kysely-codegen-sqlite --custom-imports='{"MyCustomType":"./custom-types"}'
Named imports with aliasing

You can import specific named exports and optionally alias them using the # syntax:

kysely-codegen-sqlite --custom-imports='{"MyType":"./types#OriginalType"}'

This generates:

import type { OriginalType as MyType } from './types';

Then you can use these imported types in your overrides:

kysely-codegen-sqlite --overrides='{"columns":{"events.data":"ColumnType<MyCustomType, MyCustomType, never>"}}'

--default-schema [value]

Set the default schema(s) for the database connection.

Multiple schemas can be specified:

kysely-codegen-sqlite --default-schema=main --default-schema=temp

--env-file [value]

Specify the path to an environment file to use.

--help, -h

Print all command line options.

--include-pattern [value], --exclude-pattern [value]

You can choose which tables should be included during code generation by providing a glob pattern to the --include-pattern and --exclude-pattern flags. We use micromatch under the hood, which provides advanced glob support. For instance, if you only want to include certain tables:

kysely-codegen-sqlite --include-pattern="user*"

You can also include only certain tables:

kysely-codegen-sqlite --include-pattern="+(user|post)"

Or exclude certain tables:

kysely-codegen-sqlite --exclude-pattern="_*"

--log-level [value]

Set the terminal log level. (values: debug/info/warn/error/silent, default: warn)

--overrides

Specify type overrides for specific table columns in JSON format.

Example:

kysely-codegen-sqlite --overrides='{"columns":{"table_name.column_name":"{foo:\"bar\"}"}}'

--out-file [value]

Set the file build path. (default: ./node_modules/kysely-codegen-sqlite/dist/db.d.ts)

--print

Print the generated output to the terminal instead of a file.

--singularize

Singularize generated type aliases, e.g. as BlogPost instead of BlogPosts. The codegen uses the pluralize package for singularization.

You can specify custom singularization rules in the configuration file.

--type-mapping

Specify type mappings for database types, in JSON format. This allows you to automatically map database types to custom TypeScript types.

Example:

kysely-codegen-sqlite --type-mapping='{"datetime":"Date"}' --custom-imports='{}'

Type mappings are automatically applied to all columns of the specified database type, eliminating the need to override each column individually.

--type-only-imports

Generate code using the TypeScript 3.8+ import type syntax. (default: true)

--url [value]

Set the database connection string URL. This may point to an environment variable. (default: env(DATABASE_URL))

--verify

Verify that the generated types are up-to-date. (default: false)

Configuration file

All codegen options can also be configured in a configuration file (e.g., .kysely-codegen-sqliterc.json, .js, .ts, .yaml etc.) or the kysely-codegen-sqlite property in package.json. See Cosmiconfig for all available configuration file formats.

The default configuration:

{
  "camelCase": false,
  "customImports": {},
  "defaultSchemas": [],
  "dialect": null,
  "envFile": null,
  "excludePattern": null,
  "includePattern": null,
  "logLevel": "warn",
  "outFile": "./node_modules/kysely-codegen-sqlite/dist/db.d.ts",
  "overrides": {},
  "print": false,
  "singularize": false,
  "typeMapping": {},
  "typeOnlyImports": true,
  "url": "env(DATABASE_URL)",
  "verify": false
}

The configuration object adds support for more advanced options:

{
  "camelCase": true,
  "customImports": {
    "MyCustomType": "@my-org/custom-types",
    "AliasedType": "./types#OriginalType"
  },
  "overrides": {
    "columns": {
      "posts.author_type": "AliasedType",
      "users.settings": "{ theme: 'dark' }"
    }
  },
  "singularize": {
    "/^(.*?)s?$/": "$1_model"
  },
  "typeMapping": {
    "datetime": "Date"
  }
}

The generated output:

import type { MyCustomType } from '@my-org/custom-types';
import type { OriginalType as AliasedType } from './types';

export interface UserModel {
  settings: { theme: 'dark' };
}

// ...

export interface DB {
  users: UserModel;
}

Credits

This project is a fork of kysely-codegen by Robin Blomberg. Thank you to the original author and all contributors for their work on the original project.