- PostgreSQL materialized view support (introspects materialized views alongside tables). - MySQL dateStrings-aware typing for DATE/DATETIME/TIMESTAMP. - Added esm rather than just cjs build output. - Now uses tsdown to build both cjs and esm outputs.
npm install kysely-generate- PostgreSQL materialized view support (introspects materialized views alongside tables).
- MySQL dateStrings-aware typing for DATE/DATETIME/TIMESTAMP.
- Added esm rather than just cjs build output.
- Now uses tsdown to build both cjs and esm outputs.
- Uses oxlint and tsgo
- Fixed custom import detection for override/type-mapping expressions with generics, unions, and arrays.
- Improved MSSQL connection string parsing with @tediousjs/connection-string@^1.0.0 support, including NTLM authentication.
- Fixed a Windows-specific singularization cache path issue.
kysely-generate generates Kysely type definitions from your database. That's it.
- Installation
- Generating type definitions
- Using the type definitions
- CLI arguments
- Basic example
- Named imports with aliasing
- Configuration file
``sh`
npm install --save-dev kysely-generate
You will also need to install Kysely with your driver of choice:
`shPostgreSQL
npm install kysely pg
Generating type definitions
The most convenient way to get started is to create an
.env file with your database connection string:`sh
PostgreSQL
DATABASE_URL=postgres://username:password@yourdomain.com/databaseMySQL
DATABASE_URL=mysql://username:password@yourdomain.com/databaseSQLite
DATABASE_URL=C:/Program Files/sqlite3/dbMSSQL
DATABASE_URL=Server=mssql;Database=database;User Id=user;Password=password
or using ntlm auth
DATABASE_URL=Server=mssql;Database=database;User Id=user;Password=password;Domain=domain;authentication=ntlmLibSQL
DATABASE_URL=libsql://token@host:port/database
`> If your URL contains a password with special characters, those characters may need to be percent-encoded.
>
> If you are using _PlanetScale_, make sure your URL contains this SSL query string parameter:
ssl={"rejectUnauthorized":true}Then run the following command, or add it to the scripts section in your package.json file:
`sh
kysely-generate
`This command will generate a
.d.ts file from your database, for example:
`ts
import { ColumnType } from 'kysely';export type Generated = T extends ColumnType
? ColumnType
: ColumnType;
export type Timestamp = ColumnType;
export interface Company {
id: Generated;
name: string;
}
export interface User {
company_id: number | null;
created_at: Generated;
email: string;
id: Generated;
is_active: boolean;
name: string;
updated_at: Timestamp;
}
export interface DB {
company: Company;
user: User;
}
`To specify a different output file:
`sh
kysely-generate --out-file ./src/db/db.d.ts
`Using the type definitions
Import
DB into new Kysely, and you're done!`ts
import { Kysely, PostgresDialect } from 'kysely';
import { DB } from 'kysely-generate';
import { Pool } from 'pg';const db = new Kysely({
dialect: new PostgresDialect({
pool: new Pool({
connectionString: process.env.DATABASE_URL,
}),
}),
});
const rows = await db.selectFrom('users').selectAll().execute();
// ^ { created_at: Date; 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.`ts
import { Insertable, Updateable } from 'kysely';
import { DB } from 'kysely-generate';
import { db } from './db';async function insertUser(user: Insertable) {
return await db
.insertInto('users')
.values(user)
.returningAll()
.executeTakeFirstOrThrow();
// ^ Selectable
}
async function updateUser(id: number, user: Updateable) {
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:
`ts
export interface User {
companyId: number | null;
createdAt: Generated;
email: string;
id: Generated;
isActive: boolean;
name: string;
updatedAt: Timestamp;
}
`#### --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
`sh
kysely-generate --custom-imports='{"InstantRange":"./custom-types","MyCustomType":"@my-org/custom-types"}'
`##### Named imports with aliasing
You can import specific named exports and optionally alias them using the
# syntax:`sh
kysely-generate --custom-imports='{"MyType":"./types#OriginalType","DateRange":"@org/utils#CustomDateRange"}'
`This generates:
`ts
import type { OriginalType as MyType } from './types';
import type { CustomDateRange as DateRange } from '@org/utils';
`Then you can use these imported types in your overrides:
`sh
kysely-generate --overrides='{"columns":{"events.date_range":"ColumnType"}}'
`#### --date-parser
Specify which parser to use for PostgreSQL date values. (values:
string/timestamp, default: timestamp)#### --date-strings
Treat MySQL DATE/DATETIME/TIMESTAMP columns as
string in generated types to match mysql2 dateStrings. Use --date-strings for all, or repeat with --date-strings=date, --date-strings=datetime, --date-strings=timestamp.#### --default-schema [value]
Set the default schema(s) for the database connection.
Multiple schemas can be specified:
`sh
kysely-generate --default-schema=public --default-schema=hidden
`#### --dialect [value]
Set the SQL dialect. (values:
postgres/mysql/sqlite/mssql/libsql/bun-sqlite/kysely-bun-sqlite/worker-bun-sqlite)#### --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 your public tables:`sh
kysely-generate --include-pattern="public.*"
`You can also include only certain tables within a schema:
`sh
kysely-generate --include-pattern="public.+(user|post)"
`Or exclude an entire class of tables:
`sh
kysely-generate --exclude-pattern="documents.*"
`#### --log-level [value]
Set the terminal log level. (values:
debug/info/warn/error/silent, default: warn)#### --no-domains
Skip generating types for PostgreSQL domains. (default:
false)#### --numeric-parser
Specify which parser to use for PostgreSQL numeric values. (values:
string/number/number-or-string, default: string)#### --overrides
Specify type overrides for specific table columns in JSON format.
Example:
`sh
kysely-generate --overrides='{"columns":{"table_name.column_name":"{foo:\"bar\"}"}}'
`#### --out-file [value]
Set the file build path. (default:
./node_modules/kysely-generate/dist/db.d.ts)#### --partitions
Include partitions of PostgreSQL tables in the generated code.
#### --print
Print the generated output to the terminal instead of a file.
#### --runtime-enums
The PostgreSQL
--runtime-enums option generates runtime enums instead of string unions. You can optionally specify which naming convention to use for runtime enum keys. (values: [pascal-case, screaming-snake-case], default: screaming-snake-case)Examples:
--runtime-enums=false`ts
export type Status = 'CONFIRMED' | 'UNCONFIRMED';
`--runtime-enums or --runtime-enums=screaming-snake-case`ts
export enum Status {
CONFIRMED = 'CONFIRMED',
UNCONFIRMED = 'UNCONFIRMED',
}
`--runtime-enums=pascal-case`ts
export enum Status {
Confirmed = 'CONFIRMED',
Unconfirmed = 'UNCONFIRMED',
}
`#### --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:
`sh
kysely-generate --type-mapping='{"timestamptz":"Temporal.Instant","tstzrange":"InstantRange"}' --custom-imports='{"Temporal":"@js-temporal/polyfill","InstantRange":"./custom-types"}'
`This is especially useful when you want to use modern JavaScript types like Temporal API instead of Date objects:
`json
{
"typeMapping": {
"date": "Temporal.PlainDate",
"daterange": "DateRange",
"interval": "Temporal.Duration",
"time": "Temporal.PlainTime",
"timestamp": "Temporal.Instant",
"timestamptz": "Temporal.Instant",
"tsrange": "InstantRange",
"tstzrange": "InstantRange"
}
}
`Type mappings are automatically applied to all columns of the specified database type, eliminating the need to override each column individually. This feature works with all supported databases, though some types (like PostgreSQL range types) are database-specific.
#### --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
.kysely-generaterc.json (or .js, .ts, .yaml etc.) file or the kysely-generate property in package.json. See Cosmiconfig for all available configuration file formats.The default configuration:
`json
{
"camelCase": false,
"customImports": {},
"dateParser": "timestamp",
"dateStrings": false,
"defaultSchemas": [], // ["public"] for PostgreSQL.
"dialect": null,
"domains": true,
"envFile": null,
"excludePattern": null,
"includePattern": null,
"logLevel": "warn",
"numericParser": "string",
"outFile": "./node_modules/kysely-generate/dist/db.d.ts",
"overrides": {},
"partitions": false,
"print": false,
"runtimeEnums": false,
"singularize": false,
"typeMapping": {},
"typeOnlyImports": true,
"url": "env(DATABASE_URL)",
"verify": false
}
`The configuration object adds support for more advanced options:
`json
{
"camelCase": true,
"customImports": {
"InstantRange": "./custom-types",
"MyCustomType": "@my-org/custom-types",
"AliasedType": "./types#OriginalType"
},
"overrides": {
"columns": {
"events.date_range": "ColumnType",
"posts.author_type": "AliasedType",
"users.settings": "{ theme: 'dark' }"
}
},
"singularize": {
"/^(.*?)s?$/": "$1_model",
"/(bacch)(?:us|i)$/i": "$1us"
},
"typeMapping": {
"date": "Temporal.PlainDate",
"interval": "Temporal.Duration",
"timestamptz": "Temporal.Instant"
}
}
`The generated output:
`ts
import type { InstantRange } from './custom-types';
import type { MyCustomType } from '@my-org/custom-types';
import type { OriginalType as AliasedType } from './types';
import type { Temporal } from '@js-temporal/polyfill';export interface EventModel {
createdAt: Temporal.Instant;
dateRange: ColumnType;
eventDate: Temporal.PlainDate;
}
export interface UserModel {
settings: { theme: 'dark' };
}
// ...
export interface DB {
bacchi: Bacchus;
events: EventModel;
users: UserModel;
}
``