kysforge
v0.1.5
Published
Migration CLI, schema helpers, and codegen for Kysely + PostgreSQL projects.
Maintainers
Readme
kysforge
Migration CLI, schema helpers, and codegen for Kysely + PostgreSQL projects.
Features
- Migration CLI -
up,down,status,to <target>,create-migration - Column helpers - UUID PKs, timestamps, foreign keys via
.$call()chaining - Index helpers - single, composite, trigram (GIN) indexes
- Trigger helpers -
updated_atauto-update trigger - Enum helpers - create PostgreSQL enum types
- Codegen - introspect your database and generate fully-typed Kysely interfaces
Installation
npm install kysforge
# peer deps (skip if already installed)
npm install kysely pgQuick start
1. Environment variables
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_DB=my_db
POSTGRES_USER=dev
POSTGRES_PASSWORD=passwordUse a .env file - the CLI loads it automatically via dotenv.
2. Add scripts to package.json
{
"scripts": {
"migrate": "kysforge migrate",
"migration:create": "kysforge create-migration",
"codegen": "kysforge codegen"
}
}3. Create your first migration
npm run migration:create add-users-table
# -> migrations/20260316120000-add-users-table.tsMigration files are written to ./migrations/ by default.
Override with MIGRATIONS_DIR env var or --migrations-dir CLI flag.
4. Run migrations
npm run migrate up # apply all pending
npm run migrate down # roll back one
npm run migrate down 3 # roll back three
npm run migrate status # show applied / pending
npm run migrate to none # roll back everything
npm run migrate to 20260316120000-add-users-table # migrate to specific nameTypeScript migrations: The CLI runs compiled JavaScript. If your migration files are
.tsyou need to compile them first.
Codegen
Introspect your live database and generate TypeScript types for Kysely.
1. Create kysforge.config.js in your project root
// kysforge.config.js
/** @type {import('kysforge').KyselyPgConfig} */
export default {
output: {
database: "./src/database.generated.ts",
// Optional: write enums to a separate file
enums: "./src/enums.generated.ts",
// Optional: module specifier used to import enums inside the database file
// If omitted, a relative path is derived automatically.
enumsImportPath: "@my-app/shared",
},
overrides: {
columns: {
// Override inferred TypeScript type for specific columns
"books.type": '"book"',
"movies.type": '"movie"',
},
},
};2. Run codegen
npm run codegen
# or with a custom config path:
kysforge codegen --config ./config/kysforge.config.js
# or via env var:
KYSELY_PG_CONFIG=./config/kysforge.config.js kysforge codegenGenerated output (example)
// database.generated.ts
import type {
ColumnType,
Generated,
Insertable,
Selectable,
Updateable,
} from "kysely";
export interface UsersTable {
id: Generated<string>;
email: string;
created_at: ColumnType<Date, string | Date | undefined, never>;
updated_at: ColumnType<Date, string | Date | undefined, string | Date>;
}
export type User = Selectable<UsersTable>;
export type NewUser = Insertable<UsersTable>;
export type UserUpdate = Updateable<UsersTable>;
export interface Database {
users: UsersTable;
}Library API
Import utilities directly for use inside migration files.
import {
createKyselyInstance,
postgresConfigFromEnv,
withUuidPrimaryKey,
withTimestampColumns,
setupTimestampIndexesAndTrigger,
createSingleIndex,
createMultiIndex,
createTrigramIndex,
setupUpdatedAtTrigger,
createEnum,
} from "kysforge";createKyselyInstance<T>(config)
Creates a typed Kysely instance backed by a pg connection pool.
const db = createKyselyInstance<Database>({
host: "localhost",
port: 5432,
database: "my_db",
user: "dev",
password: "password",
});postgresConfigFromEnv()
Reads POSTGRES_HOST/PORT/DB/USER/PASSWORD from process.env.
Column helpers
All helpers are used with Kysely's .$call() pattern inside createTable.
withUuidPrimaryKey(columnName?)
Adds a UUID primary key with uuid_generate_v4() as its default.
Prerequisite: CREATE EXTENSION IF NOT EXISTS "uuid-ossp" (add in your
init migration).
await db.schema
.createTable("users")
.$call(withUuidPrimaryKey()) // default column name: 'id'
.$call(withUuidPrimaryKey("uid")) // custom name
.execute();withTimestampColumns()
Adds created_at and updated_at (timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP).
await db.schema
.createTable("posts")
.$call(withUuidPrimaryKey())
.$call(withTimestampColumns())
.execute();
// Wire up indexes + auto-update trigger (see prerequisites below)
await setupTimestampIndexesAndTrigger(db, "posts");Prerequisite: The update_updated_at_column() PL/pgSQL function must exist
in the database. Add it in your first/init migration:
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ language 'plpgsql';Index helpers
createSingleIndex(db, table, column, options?)
await createSingleIndex(db, "users", "email", { unique: true });
await createSingleIndex(db, "posts", "deleted_at", { notNull: true }); // partial indexcreateMultiIndex(db, table, columns[], options?)
await createMultiIndex(db, "orders", ["user_id", "status"]);
await createMultiIndex(db, "posts", ["author_id", "published_at"], {
unique: true,
});createTrigramIndex(db, table, column, options?)
Creates a GIN trigram index for fast ILIKE / similarity queries.
Installs pg_trgm automatically.
await createTrigramIndex(db, "products", "name");
await createTrigramIndex(db, "articles", "body", { notNull: true });Enum helpers
await createEnum(db, 'status_type', ['active', 'inactive', 'pending']);
// Use in a table:
.addColumn('status', sql`status_type`, (col) => col.notNull())
// Drop in down migration (after dropping the table):
await db.schema.dropType('status_type').execute();Complete migration example
import type { Kysely } from "kysely";
import { sql } from "kysely";
import {
withUuidPrimaryKey,
withTimestampColumns,
setupTimestampIndexesAndTrigger,
createSingleIndex,
createMultiIndex,
createEnum,
} from "kysforge";
export async function up(db: Kysely<any>): Promise<void> {
await createEnum(db, "post_status", ["draft", "published", "archived"]);
await db.schema
.createTable("posts")
.$call(withUuidPrimaryKey())
.$call(withTimestampColumns())
.addColumn("user_id", "uuid", (col) => col.notNull().references("users").onDelete("cascade"))
.addColumn("title", "varchar(255)", (col) => col.notNull())
.addColumn("body", "text")
.addColumn("status", sql`post_status`, (col) => col.notNull())
.addColumn("published_at", "timestamptz")
.execute();
await setupTimestampIndexesAndTrigger(db, "posts");
await createSingleIndex(db, "posts", "user_id");
await createSingleIndex(db, "posts", "status");
await createMultiIndex(db, "posts", ["user_id", "status"]);
}
export async function down(db: Kysely<any>): Promise<void> {
await db.schema.dropTable("posts").execute();
await db.schema.dropType("post_status").execute();
}