将 Prisma Postgres 与 Kysely 结合使用
Kysely 是一个类型安全的 TypeScript SQL 查询构建器,提供 TypeScript 支持和流畅的 API,用于构建 SQL 查询。在本指南中,你将学习如何将 Kysely 连接到 Prisma Postgres,并开始以完全类型安全的方式查询你的数据库。
¥Kysely is a type-safe TypeScript SQL query builder that provides TypeScript support and a fluent API for building SQL queries. In this guide, you'll learn how to connect Kysely to Prisma Postgres and start querying your database with full type safety.
先决条件
¥Prerequisites
-
Node.js 版本 14 或更高版本
¥Node.js version 14 or higher
-
TypeScript 版本 4.6 或更高版本(建议使用 5.4+ 以获得更好的类型推断,使用 5.9+ 以获得更好的编译性能)
¥TypeScript version 4.6 or higher (5.4+ recommended for improved type inference, 5.9+ for better compilation performance)
-
在
tsconfig.json中启用严格模式,以确保 Kysely 的类型安全¥Strict mode enabled in your
tsconfig.jsonfor Kysely's type safety
1. 创建一个新项目
¥ Create a new project
为你的项目创建一个新目录,并使用 npm 进行初始化:
¥Create a new directory for your project and initialize it with npm:
mkdir kysely-quickstart
cd kysely-quickstart
npm init -y
安装 TypeScript 并进行初始化:
¥Install TypeScript and initialize it:
npm install --save-dev typescript
npx tsc --init
2. 配置 TypeScript
¥ Configure TypeScript
Kysely 需要 TypeScript 的严格模式才能确保类型安全。更新你的 tsconfig.json 文件:
¥Kysely requires TypeScript's strict mode for proper type safety. Update your tsconfig.json file:
{
// ...
"compilerOptions": {
// ...
"strict": true,
"allowImportingTsExtensions": true,
"noEmit": true
// ...
}
// ...
}
要使 Kysely 的类型安全正常工作,必须设置 strict: true。
¥The strict: true setting is required for Kysely's type safety to work correctly.
在 package.json 文件中,将 type 设置为 module:
¥In your package.json, set the type to module:
{
// ...
"type": "module"
// ...
}
3. 创建 Prisma Postgres 数据库
¥ Create a Prisma Postgres database
你可以使用 create-db CLI 工具创建 Prisma Postgres 数据库。按照以下步骤创建你的 Prisma Postgres 数据库:
¥You can create a Prisma Postgres database using the create-db CLI tool. Follow these steps to create your Prisma Postgres database:
npx create-db
然后 CLI 工具应输出:
¥Then the CLI tool should output:
┌ 🚀 Creating a Prisma Postgres database
│
│ Provisioning a temporary database in us-east-1...
│
│ It will be automatically deleted in 24 hours, but you can claim it.
│
◇ Database created successfully!
│
│
● Database Connection
│
│
│ Connection String:
│
│ postgresql://hostname:password@db.prisma.io:5432/postgres?sslmode=require
│
│
◆ Claim Your Database
│
│ Keep your database for free:
│
│ https://create-db.prisma.io/claim?CLAIM_CODE
│
│ Database will be deleted on 11/18/2025, 1:55:39 AM if not claimed.
│
└
创建 .env 文件,并添加输出中的连接字符串:
¥Create a .env file and add the connection string from the output:
DATABASE_URL="postgresql://hostname:password@db.prisma.io:5432/postgres?sslmode=require"
切勿将 .env 文件提交到版本控制系统。将 .env 添加到 .gitignore 文件以确保凭据安全。
¥Never commit .env files to version control. Add .env to your .gitignore file to keep credentials secure.
创建的数据库是临时的,除非被认领,否则将在 24 小时后删除。认领操作会将数据库移动到你的 账户。访问输出中的声明 URL 以保留你的数据库。
¥The database created is temporary and will be deleted in 24 hours unless claimed. Claiming moves the database into your account. Visit the claim URL from the output to keep your database.
要了解有关 create-db CLI 工具的更多信息,请参阅 create-db 文档。
¥To learn more about the create-db CLI tool, see the create-db documentation.
4. 安装依赖
¥ Install dependencies
安装 Kysely 和 PostgreSQL 驱动程序:
¥Install Kysely and the PostgreSQL driver:
npm install kysely pg dotenv
npm install --save-dev @types/pg tsx
软件包明细:
¥Package breakdown:
-
kysely:类型安全的 SQL 查询构建器¥
kysely: The type-safe SQL query builder -
pg:适用于 Node.js 的 PostgreSQL 驱动程序(Kysely 的 PostgresDialect 需要此驱动程序)¥
pg: PostgreSQL driver for Node.js (required by Kysely's PostgresDialect) -
dotenv:从.env文件加载环境变量¥
dotenv: Loads environment variables from.envfile -
@types/pg:pg 驱动程序的 TypeScript 类型定义¥
@types/pg: TypeScript type definitions for the pg driver -
tsx:用于直接运行.ts文件的 TypeScript 执行引擎¥
tsx: TypeScript execution engine for running.tsfiles directly
5. 定义数据库类型
¥ Define database types
创建 src/types.ts 文件以定义数据库模式类型:
¥Create a src/types.ts file to define your database schema types:
import type { Generated } from "kysely";
export interface Database {
users: UsersTable;
}
export interface UsersTable {
id: Generated<number>;
email: string;
name: string | null;
}
6. 配置数据库连接
¥ Configure database connection
创建 src/database.ts 文件以使用 Prisma Postgres 连接实例化 Kysely:
¥Create a src/database.ts file to instantiate Kysely with your Prisma Postgres connection:
import 'dotenv/config'
import type { Database } from './types.ts'
import { Pool } from 'pg'
import { Kysely, PostgresDialect } from 'kysely'
// Parse DATABASE_URL into connection parameters
function parseConnectionString(url: string) {
const parsed = new URL(url)
return {
host: parsed.hostname,
port: parseInt(parsed.port),
user: parsed.username,
password: parsed.password,
database: parsed.pathname.slice(1), // Remove leading '/'
}
}
const connectionParams = parseConnectionString(process.env.DATABASE_URL!)
const dialect = new PostgresDialect({
pool: new Pool({
...connectionParams,
ssl: true,
max: 10,
})
})
// Database interface is passed to Kysely's constructor, and from now on, Kysely
// knows your database structure.
// Dialect is passed to Kysely's constructor, and from now on, Kysely knows how
// to communicate with your database.
export const db = new Kysely<Database>({
dialect,
})
7. 运行查询
¥ Run queries
创建 src/script.ts 文件:
¥Create a src/script.ts file:
import { db } from './database.ts'
async function main() {
// Create the users table
await db.schema
.createTable('users')
.ifNotExists()
.addColumn('id', 'serial', (col) => col.primaryKey())
.addColumn('email', 'varchar(255)', (col) => col.notNull().unique())
.addColumn('name', 'varchar(255)')
.execute()
// Insert a user
const user = await db
.insertInto('users')
.values({
email: 'alice@prisma.io',
name: 'Alice',
})
.returningAll()
.executeTakeFirstOrThrow()
console.log('Created user:', user)
// Query all users
const users = await db
.selectFrom('users')
.selectAll()
.execute()
console.log('All users:', users)
}
main()
.then(async () => {
await db.destroy()
})
.catch(async (error) => {
console.error('Error:', error)
await db.destroy()
process.exit(1)
})
运行脚本:
¥Run the script:
npx tsx src/script.ts
你应该收到以下输出:
¥You should receive the following output:
Created user: { id: 1, email: 'alice@prisma.io', name: 'Alice' }
All users: [ { id: 1, email: 'alice@prisma.io', name: 'Alice' } ]
下一步
¥Next steps
你已成功将 Kysely 连接到 Prisma Postgres!对于模式、迁移和复杂查询等更高级的功能,请参阅 Kysely 文档。
¥You've successfully connected Kysely to Prisma Postgres! For more advanced features like schemas, migrations, and complex queries, see the Kysely documentation.