Prisma ORM 与 CockroachDB 快速入门
CockroachDB 是一个专为云应用构建的分布式 SQL 数据库。在本指南中,你将学习如何从头开始设置一个新的 TypeScript 项目,使用 Prisma ORM 将其连接到 CockroachDB,并生成 Prisma Client,以便轻松、类型安全地访问数据库。
¥CockroachDB is a distributed SQL database built for cloud applications. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to CockroachDB using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database.
先决条件
¥Prerequisites
你需要:
¥You need:
-
你的机器上已安装 Node.js v20.19+、v22.12+ 或 v24.0+ 版本
¥Node.js v20.19+, v22.12+, or v24.0+ installed on your machine
-
具备 JavaScript 或 TypeScript 的基础知识
¥Basic knowledge of JavaScript or TypeScript
你还需要:
¥You also need:
-
CockroachDB 数据库
¥A CockroachDB database
-
来自 CockroachDB 的数据库连接字符串
¥Database connection string from CockroachDB
1. 创建一个新项目
¥ Create a new project
创建一个项目目录并导航到它:
¥Create a project directory and navigate into it:
mkdir hello-prisma
cd hello-prisma
初始化 TypeScript 项目:
¥Initialize a TypeScript project:
npm init -y
npm install typescript tsx @types/node --save-dev
npx tsc --init
2. 安装所需依赖
¥ Install required dependencies
安装此快速入门所需的软件包:
¥Install the packages needed for this quickstart:
npm install prisma @types/node @types/pg --save-dev
npm install @prisma/client @prisma/adapter-pg pg dotenv
以下是每个包的功能:
¥Here's what each package does:
-
prisma- 用于运行prisma init、prisma migrate和prisma generate等命令的 Prisma CLI¥
prisma- The Prisma CLI for running commands likeprisma init,prisma migrate, andprisma generate -
@prisma/client- 用于查询数据库的 Prisma 客户端库¥
@prisma/client- The Prisma Client library for querying your database -
@prisma/adapter-pg- 将 Prisma Client 连接到数据库的node-postgres驱动程序适配器(CockroachDB 与 PostgreSQL 兼容)¥
@prisma/adapter-pg- Thenode-postgresdriver adapter that connects Prisma Client to your database (CockroachDB is PostgreSQL-compatible) -
pg- node-postgres 数据库驱动程序¥
pg- The node-postgres database driver -
@types/pg- node-postgres 的 TypeScript 类型定义¥
@types/pg- TypeScript type definitions for node-postgres -
dotenv- 从你的.env文件加载环境变量¥
dotenv- Loads environment variables from your.envfile
3. 配置 ESM 支持
¥ Configure ESM support
更新 tsconfig.json 以兼容 ESM:
¥Update tsconfig.json for ESM compatibility:
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "node",
"target": "ES2023",
"strict": true,
"esModuleInterop": true,
"ignoreDeprecations": "6.0"
}
}
更新 package.json 以启用 ESM:
¥Update package.json to enable ESM:
{
"type": "module",
}
4. 初始化 Prisma ORM
¥ Initialize Prisma ORM
你现在可以通过添加 npx 前缀来调用 Prisma CLI:
¥You can now invoke the Prisma CLI by prefixing it with npx:
npx prisma
接下来,使用以下命令创建 Prisma 模式 文件来设置 Prisma ORM 项目:
¥Next, set up your Prisma ORM project by creating your Prisma Schema file with the following command:
npx prisma init --datasource-provider cockroachdb --output ../generated/prisma
此命令执行以下几项操作:
¥This command does a few things:
-
创建一个名为
prisma/的目录,其中包含一个schema.prisma文件,该文件包含数据库连接和模式模型¥Creates a
prisma/directory with aschema.prismafile containing your database connection and schema models -
在根目录中创建一个用于环境变量的
.env文件¥Creates a
.envfile in the root directory for environment variables -
创建一个用于 Prisma 配置的
prisma.config.ts文件¥Creates a
prisma.config.tsfile for Prisma configuration
生成的 prisma.config.ts 文件如下所示:
¥The generated prisma.config.ts file looks like this:
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
})
生成的 schema 使用带有自定义输出路径的 ESM 优先的 prisma-client 生成器:
¥The generated schema uses the ESM-first prisma-client generator with a custom output path:
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
datasource db {
provider = "cockroachdb"
}
使用 CockroachDB 连接字符串更新 .env 文件:
¥Update your .env file with your CockroachDB connection string:
DATABASE_URL="postgresql://username:password@host:26257/mydb?sslmode=require"
替换为你集群控制面板中显示的实际 CockroachDB 连接字符串。
¥Replace with your actual CockroachDB connection string from your cluster dashboard.
5. 定义你的数据模型
¥ Define your data model
打开 prisma/schema.prisma 文件并添加以下模型:
¥Open prisma/schema.prisma and add the following models:
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
datasource db {
provider = "cockroachdb"
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
}
6. 创建并应用你的第一个迁移
¥ Create and apply your first migration
创建第一个迁移以设置数据库表:
¥Create your first migration to set up the database tables:
npx prisma migrate dev --name init
此命令根据你的架构创建数据库表。
¥This command creates the database tables based on your schema.
现在运行以下命令来生成 Prisma 客户端:
¥Now run the following command to generate the Prisma Client:
npx prisma generate
7. 实例化 Prisma 客户端
¥ Instantiate Prisma Client
现在你已安装所有依赖,可以实例化 Prisma Client 了。你需要将 Prisma ORM 的驱动程序适配器实例传递给 PrismaClient 构造函数:
¥Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the PrismaClient constructor:
import "dotenv/config";
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from '../generated/prisma/client'
const connectionString = `${process.env.DATABASE_URL}`
const adapter = new PrismaPg({ connectionString })
const prisma = new PrismaClient({ adapter })
export { prisma }
8. 编写你的第一个查询
¥ Write your first query
创建 script.ts 文件以测试你的设置:
¥Create a script.ts file to test your setup:
import { prisma } from './lib/prisma'
async function main() {
// Create a new user with a post
const user = await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
posts: {
create: {
title: 'Hello World',
content: 'This is my first post!',
published: true,
},
},
},
include: {
posts: true,
},
})
console.log('Created user:', user)
// Fetch all users with their posts
const allUsers = await prisma.user.findMany({
include: {
posts: true,
},
})
console.log('All users:', JSON.stringify(allUsers, null, 2))
}
main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})
运行脚本:
¥Run the script:
npx tsx script.ts
你应该在控制台中看到已创建的用户以及所有用户!
¥You should see the created user and all users printed to the console!
9. 探索你的数据
¥ Explore your data
探索 CockroachDB 建议的选项,以查看和管理你的数据。
¥Explore the options suggested by CockroachDB to view and manage your data.
Prisma 工作室 目前不支持 CockroachDB。未来版本可能会添加此功能。请参阅 Prisma 支持的数据库 Studio 了解更多信息。
¥Prisma Studio does not currently support CockroachDB. Support may be added in a future release. See Databases supported by Prisma Studio for more information.
下一步
¥Next steps
你已成功设置 Prisma ORM。接下来你可以探索以下内容:
¥You've successfully set up Prisma ORM. Here's what you can explore next:
-
了解更多关于 Prisma 客户端的信息:探索 Prisma 客户端 API 的高级查询、筛选和关联功能
¥Learn more about Prisma Client: Explore the Prisma Client API for advanced querying, filtering, and relations
-
数据库迁移:了解 Prisma 迁移,以便演进你的数据库模式
¥Database migrations: Learn about Prisma Migrate for evolving your database schema
-
性能优化:Discover 查询优化技巧
¥Performance optimization: Discover query optimization techniques
-
构建完整应用:查看我们的 框架指南,了解如何将 Prisma ORM 与 Next.js、Express 等集成。
¥Build a full application: Check out our framework guides to integrate Prisma ORM with Next.js, Express, and more
-
加入社区:通过 Discord 与其他开发者连接
¥Join the community: Connect with other developers on Discord
更多信息
¥More info