@wofflos/kysely-utils
v0.4.2
Published
Utilities for Kysely
Readme
@wofflos/kysely-utils
Personal package, published for convenience. No stability guarantees or support.
Utilities for Kysely. Requires Node >= 22.5.0.
Install
pnpm add @wofflos/kysely-utils kyselyFeatures
SerializerPlugin
Handles camelCase ↔ snake_case column name conversion and value serialization automatically.
- Query: camelCase → snake_case column names
- Result: snake_case → camelCase column names
- Serializes
boolean→"true"/"false",Date→ Unix timestamp, objects → JSON - Deserializes columns ending in
_at/_date→Date,"true"/"false"→boolean
import { createSerializerPlugin } from "@wofflos/kysely-utils";
const db = new Kysely<DB>({
dialect,
plugins: [createSerializerPlugin()],
});SerializerPlugin, QueryTransformer, and ResultTransformer are also exported for building custom plugins.
NodeSqliteDialect
A Kysely dialect for Node's built-in node:sqlite module (Node 22.5+).
import { DatabaseSync } from "node:sqlite";
import { NodeSqliteDialect } from "@wofflos/kysely-utils";
const db = new Kysely<DB>({
dialect: new NodeSqliteDialect({
database: new DatabaseSync("./app.db"),
// or a factory function, opened lazily on first query:
// database: () => new DatabaseSync("./app.db"),
}),
});MigrationRunner
A wrapper around Kysely's Migrator with optional logging.
import { MigrationRunner } from "@wofflos/kysely-utils";
const runner = new MigrationRunner({
db,
migrations: [
{
name: "2024_01_create_users",
async up(db) {
/* ... */
},
async down(db) {
/* ... */
},
},
],
// optional: provide a logger for migration status messages
logger: { log: console.log, error: console.error },
});
await runner.migrateToLatest(); // run all pending migrations
await runner.migrateUp(); // run one migration
await runner.migrateTo("name"); // migrate to a specific migration
await runner.migrateDown(); // roll back one migration
await runner.reset(); // roll back all migrations
await runner.status(); // log migration status
runner.close(); // destroy the db connectionMigrationsProvider is also exported for use directly with Kysely's Migrator.
Logger
Functions that return a Kysely Logger for SQL query logging.
import { consoleLogger, noopLogger } from "@wofflos/kysely-utils";
// Logs queries with duration and colorized SQL
const db = new Kysely<DB>({ dialect, log: consoleLogger() });
// Silences all SQL logs
const db = new Kysely<DB>({ dialect, log: noopLogger() });Schema Introspector
Introspects a SQLite database and generates Kysely-compatible TypeScript types.
Generated output:
export interface Users { ... }per table, with camelCase property namesexport interface Database { ... }mapping table names to interfacesexport type User = Selectable<Users>+NewUser+UserUpdatealiases (skippable with--no-aliases)Generated<number>for single-columnINTEGER PRIMARY KEYDatefor columns ending in_ator_date
CLI
Installed as kysely-utils, uses a config file by default.
# Introspect (flags override config)
kysely-utils introspect --db ./app.db --out ./src/schema.ts
# Migrate
kysely-utils migrate up
kysely-utils migrate down
kysely-utils migrate reset
kysely-utils migrate status
# Custom config file
kysely-utils migrate up --config ./my.config.tsintrospect flags:
| Flag | Default | Description |
| ----------------- | ------------- | --------------------------------------------------- |
| --db <path> | from config | Path to the SQLite .db file |
| --out <path> | schema.ts | Output file path |
| --tables <csv> | all tables | Tables to include |
| --no-aliases | off | Skip Selectable/Insertable/Updateable aliases |
| --config <path> | auto-detected | Config file path |
Config file
kysely-utils.config.ts (or .js) in your project root. Also looks for kysely.config.ts / kysely.config.js as fallbacks.
import { defineConfig, NodeSqliteDialect, consoleLogger } from "@wofflos/kysely-utils";
import { DatabaseSync } from "node:sqlite";
import { migrations } from "./dist/migrations.js";
export default defineConfig({
dialect: new NodeSqliteDialect({ database: new DatabaseSync("./app.db") }),
migrations,
dbLogger: consoleLogger(), // SQL query logging (optional)
migrationLogger: { log: console.log, error: console.error }, // migration status (optional)
introspect: {
db: "./app.db",
out: "./src/schema.ts",
},
});On Node 22,
.tsconfig files require--experimental-strip-typesor a loader liketsx. Node 24 loads them natively.
Programmatic API
import { introspect } from "@wofflos/kysely-utils";
// Pass a file path (opened read-only, closed automatically)
const { code } = introspect("./app.db");
await fs.writeFile("schema.ts", code);
// Or pass an existing DatabaseSync instance
import { DatabaseSync } from "node:sqlite";
const db = new DatabaseSync("./app.db");
const { code, tables } = introspect(db, {
tables: ["users", "posts"], // optional filter
generateTypeAliases: false, // skip Selectable/Insertable/Updateable
locale: "es", // BCP 47 tag for pluralization rules
});License
MIT
