kysely-pgschema
v0.3.0
Published
Generate Kysely type definitions from PostgreSQL schema files — offline, no DB required
Readme
kysely-pgschema
Generate Kysely type definitions from PostgreSQL schema files — no database connection required.
Parses .sql files offline using the official PostgreSQL parser (libpg-query, compiled to WASM).
Installation
npm install --save-dev kysely-pgschemaUsage
kysely-pgschema --schema ./db/schema.sql --out-file ./src/db/types.d.tsGiven this schema:
CREATE TYPE user_role AS ENUM ('admin', 'member');
CREATE TABLE users (
id serial PRIMARY KEY,
email text NOT NULL,
role user_role NOT NULL DEFAULT 'member',
created_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz
);Generates:
import type { ColumnType } from 'kysely';
export type Generated<T> = ...;
export type Timestamp = ColumnType<Date, Date | string, Date | string>;
export type UserRole = 'admin' | 'member';
export interface Users {
id: Generated<number>;
email: string;
role: Generated<UserRole>;
created_at: Generated<Timestamp>;
deleted_at: Timestamp | null;
}
export interface DB {
users: Users;
}Then use it with Kysely:
import { Kysely, PostgresDialect } from 'kysely';
import { DB } from './types.d.ts';
const db = new Kysely<DB>({ dialect: ... });\i includes
Schema files that use \i (e.g. from pgschema.com or pg_dump splits) are resolved recursively:
-- schema.sql
\i ./tables/users.sql
\i ./tables/posts.sqlCLI options
| Flag | Default | Description |
|---|---|---|
| --schema | required | Path to SQL schema file |
| --out-file | kysely-pgschema.d.ts | Output file path |
| --camel-case | false | Convert snake_case columns to camelCase |
| --default-schema | public | Schema used as root in the DB interface |
| --include-pattern | — | Glob to include only matching schema.table |
| --exclude-pattern | — | Glob to exclude matching schema.table |
| --date-parser | timestamp | timestamp or string for date/time columns |
| --numeric-parser | string | string, number, or number-or-string |
| --runtime-enums | false | Also emit const objects for enum types |
| --nullability | null | null (T \| null), optional (field?: T), or undefined (T \| undefined) |
| --config-file | auto | Path to config file |
Config file
Options can also be set in .kysely-pgschemarc.json:
{
"schema": "./db/schema.sql",
"outFile": "./src/db/types.d.ts",
"camelCase": true,
"runtimeEnums": true,
"nullability": "optional"
}Supported SQL statements
CREATE TABLECREATE TYPE ... AS ENUMALTER TABLE ... ADD COLUMNALTER TABLE ... ALTER COLUMN SET NOT NULL / DROP NOT NULL / SET DEFAULT
Development
npm test # run tests (node:test)
npm run typecheck # tsc --noEmit
npm run build # compile to dist/