关于 kysely
面向 Kysely、TypeScript 和 SQL 数据库设计的开发指导技能,涵盖类型安全的查询构建、迁移、插件和性能实践。
主要功能
- 01类型安全的 SQL 查询构建
- 02查询、连接与子查询模式
- 03事务与迁移
- 04生成数据库类型
- 05插件与查询组合
适用场景
- 01构建类型化数据库查询
- 02通过迁移管理架构变更
- 03优化应用的数据库访问
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ mindrally/ skills --skill kysely安装后在 Claude Code 中输入/kysely确认已加载。
详细介绍
Kysely 开发指南
你是 Kysely、TypeScript 和 SQL 数据库设计方面的专家,专注于类型安全和查询优化。
核心原则
- Kysely 是 SQL 之上的轻量级抽象层,由热爱 SQL 的开发者为热爱 SQL 的开发者设计
- 提供完整的类型安全,为表、列和查询结果提供自动补全
- 可预测地将代码 1:1 编译为 SQL:写什么就得到什么
- 没有魔法或隐藏行为:查询构建明确且透明
- 支持 Node.js、Deno、Bun、Cloudflare Workers 和浏览器
数据库接口定义
定义数据库架构
import { Generated, ColumnType, Selectable, Insertable, Updateable } from "kysely";
// Define table interfaces
interface UserTable {
id: Generated<number>;
email: string;
name: string | null;
is_active: boolean;
created_at: Generated<Date>;
updated_at: ColumnType<Date, Date | undefined, Date>;
}
interface PostTable {
id: Generated<number>;
title: string;
content: string | null;
author_id: number;
published_at: Date | null;
created_at: Generated<Date>;
}
// Define the database interface
interface Database {
users: UserTable;
posts: PostTable;
}
// Export helper types for each table
export type User = Selectable<UserTable>;
export type NewUser = Insertable<UserTable>;
export type UserUpdate = Updateable<UserTable>;
export type Post = Selectable<PostTable>;
export type NewPost = Insertable<PostTable>;
export type PostUpdate = Updateable<PostTable>;
Generated 与 ColumnType
Generated<T>- 由数据库自动生成的列(自增、默认值)ColumnType<SelectType, InsertType, UpdateType>- 为不同操作指定不同类型
数据库连接
PostgreSQL 设置
import { Kysely, PostgresDialect } from "kysely";
import { Pool } from "pg";
const db = new Kysely<Database>({
dialect: new PostgresDialect({
pool: new Pool({
connectionString: process.env.DATABASE_URL,
}),
}),
});
export { db };
MySQL 设置
import { Kysely, MysqlDialect } from "kysely";
import { createPool } from "mysql2";
const db = new Kysely<Database>({
dialect: new MysqlDialect({
pool: createPool({
uri: process.env.DATABASE_URL,
}),
}),
});
SQLite 设置
import { Kysely, SqliteDialect } from "kysely";
import Database from "better-sqlite3";
const db = new Kysely<Database>({
dialect: new SqliteDialect({
database: new Database("database.db"),
}),
});
查询模式
Select 查询
// Select all columns from a table
const users = await db.selectFrom("users").selectAll().execute();
// Select specific columns
const userEmails = await db
.selectFrom("users")
.select(["id", "email", "name"])
.execute();
// With WHERE conditions
const activeUsers = await db
.selectFrom("users")
.selectAll()
.where("is_active", "=", true)
.execute();
// Multiple conditions
const filteredUsers = await db
.selectFrom("users")
.selectAll()
.where("is_active", "=", true)
.where("email", "like", "%@example.com")
.execute();
// OR conditions
const users = await db
.selectFrom("users")
.selectAll()
.where((eb) =>
eb.or([
eb("name", "=", "John"),
eb("name", "=", "Jane"),
])
)
.execute();
列别名
// Kysely automatically infers alias types
const result = await db
.selectFrom("users")
.select([
"id",
"email",
"name as userName", // Alias parsed and typed correctly
])
.executeTakeFirst();
// result.userName is typed correctly
联接
// Inner join
const postsWithAuthors = await db
.selectFrom("posts")
.innerJoin("users", "users.id", "posts.author_id")
.select([
"posts.id",
"posts.title",
"users.name as authorName",
])
.execute();
// Left join
const usersWithPosts = await db
.selectFrom("users")
.leftJoin("posts", "posts.author_id", "users.id")
.select([
"users.id",
"users.name",
"posts.title as postTitle",
])
.execute();
子查询
// Subquery in select
const usersWithPostCount = await db
.selectFrom("users")
.select([
"users.id",
"users.name",
(eb) =>
eb
.selectFrom("posts")
.select(eb.fn.count<number>("posts.id").as("count"))
.whereRef("posts.author_id", "=", "users.id")
.as("postCount"),
])
.execute();
// Subquery in where
const usersWithPosts = await db
.selectFrom("users")
.selectAll()
.where("id", "in", (eb) =>
eb.selectFrom("posts").select("author_id").distinct()
)
.execute();
插入操作
// Single insert
const result = await db
.insertInto("users")
.values({
email: "[email protected]",
name: "John Doe",
is_active: true,
})
.returning(["id", "email", "created_at"])
.executeTakeFirstOrThrow();
// Bulk insert
await db
.insertInto("users")
.values([
{ email: "[email protected]", name: "User 1", is_active: true },
{ email: "[email protected]", name: "User 2", is_active: true },
])
.execute();
// Insert with on conflict (upsert)
await db
.insertInto("users")
.values({
email: "[email protected]",
name: "John",
is_active: true,
})
.onConflict((oc) =>
oc.column("email").doUpdateSet({
name: "John Updated",
updated_at: new Date(),
})
)
.execute();
更新操作
const result = await db
.updateTable("users")
.set({
name: "Jane Doe",
updated_at: new Date(),
})
.where("id", "=", 1)
.returning(["id", "name", "updated_at"])
.executeTakeFirst();
删除操作
const result = await db
.deleteFrom("users")
.where("id", "=", 1)
.returning(["id", "email"])
.executeTakeFirst();
事务
await db.transaction().execute(async (trx) => {
const user = await trx
.insertInto("users")
.values({
email: "[email protected]",
name: "User",
is_active: true,
})
.returning(["id"])
.executeTakeFirstOrThrow();
await trx
.insertInto("posts")
.values({
title: "First Post",
author_id: user.id,
})
.execute();
});
使用 kysely-codegen 生成类型
使用 kysely-codegen 从现有数据库生成类型:
# Install
npm install -D kysely-codegen
# Generate types (reads from DATABASE_URL environment variable)
npx kysely-codegen
# Specify output file
npx kysely-codegen --out-file src/db/types.ts
每当数据库架构发生变化时,都要重新生成类型。
插件
CamelCase 插件
将 snake_case 列名转换为 camelCase:
import { Kysely, PostgresDialect, CamelCasePlugin } from "kysely";
const db = new Kysely<Database>({
dialect: new PostgresDialect({ pool }),
plugins: [new CamelCasePlugin()],
});
自定义插件
import { KyselyPlugin, PluginTransformQueryArgs, PluginTransformResultArgs } from "kysely";
class LoggingPlugin implements KyselyPlugin {
transformQuery(args: PluginTransformQueryArgs): RootOperationNode {
console.log("Query:", args.node);
return args.node;
}
async transformResult(args: PluginTransformResultArgs): Promise<QueryResult<unknown>> {
console.log("Result:", args.result);
return args.result;
}
}
高级模式
动态构建查询
function findUsers(filters: {
email?: string;
isActive?: boolean;
name?: string;
}) {
let query = db.selectFrom("users").selectAll();
if (filters.email) {
query = query.where("email", "=", filters.email);
}
if (filters.isActive !== undefined) {
query = query.where("is_active", "=", filters.isActive);
}
if (filters.name) {
query = query.where("name", "like", `%${filters.name}%`);
}
return query.execute();
}
原始 SQL
import { sql } from "kysely";
// Raw expression in select
const result = await db
.selectFrom("users")
.select([
"id",
sql<string>`CONCAT(first_name, ' ', last_name)`.as("fullName"),
])
.execute();
// Raw expression in where
const users = await db
.selectFrom("users")
.selectAll()
.where(sql`LOWER(email)`, "=", "[email protected]")
.execute();
公用表表达式(CTE)
const result = await db
.with("active_users", (db) =>
db.selectFrom("users").selectAll().where("is_active", "=", true)
)
.selectFrom("active_users")
.selectAll()
.execute();
最佳实践
TypeScript 配置
在 tsconfig.json 中启用严格模式:
{
"compilerOptions": {
"strict": true,
"strictNullChecks": true,
"target": "ES2020"
}
}
为获得最佳类型推断,请使用 TypeScript 5.4 或更高版本。
性能提示
- 仅选择所需的列 - 只需要特定字段时,避免使用
selectAll() - 使用适当的索引 - 确保数据库为 WHERE 和 JOIN 列建立了索引
- 批量操作 - 插入多条记录时使用批量插入
- 连接池 - 生产环境中始终使用连接池
- 预处理语句 - Kysely 会自动使用预处理语句
错误处理
import { NoResultError } from "kysely";
try {
const user = await db
.selectFrom("users")
.selectAll()
.where("id", "=", 999)
.executeTakeFirstOrThrow();
} catch (error) {
if (error instanceof NoResultError) {
// Handle not found
}
throw error;
}
查询组合
// Create reusable query parts
function withActiveUsers(db: Kysely<Database>) {
return db.selectFrom("users").where("is_active", "=", true);
}
// Use in queries
const activeUsers = await withActiveUsers(db).selectAll().execute();
迁移管理
Kysely 提供了简单的迁移系统:
import { Migrator, FileMigrationProvider } from "kysely";
import path from "path";
import { promises as fs } from "fs";
const migrator = new Migrator({
db,
provider: new FileMigrationProvider({
fs,
path,
migrationFolder: path.join(__dirname, "migrations"),
}),
});
// Run migrations
await migrator.migrateToLatest();
迁移文件示例:
// migrations/001_create_users.ts
import { Kysely, sql } from "kysely";
export async function up(db: Kysely<any>): Promise<void> {
await db.schema
.createTable("users")
.addColumn("id", "serial", (col) => col.primaryKey())
.addColumn("email", "varchar(255)", (col) => col.notNull().unique())
.addColumn("name", "varchar(255)")
.addColumn("is_active", "boolean", (col) => col.defaultTo(true))
.addColumn("created_at", "timestamp", (col) =>
col.defaultTo(sql`now()`).notNull()
)
.execute();
}
export async function down(db: Kysely<any>): Promise<void> {
await db.schema.dropTable("users").execute();
}
评论
支持 Markdown