Skip to main content

Prisma ORM 与 PlanetScale

PlanetScale 是一个无服务器数据库平台。本指南涵盖 PlanetScale MySQL。本指南将教你如何从零开始创建一个新的 TypeScript 项目,使用 Prisma ORM 将其连接到 PlanetScale MySQL,并生成 Prisma 客户端,以便轻松、安全地访问你的数据库。

¥PlanetScale is a serverless database platform. This guide covers PlanetScale MySQL. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to PlanetScale MySQL using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database.

注意

PlanetScale 还提供 PostgreSQL 数据库。如果你使用的是 PlanetScale PostgreSQL,请参考 PostgreSQL 快速入门指南 文件。

¥PlanetScale also offers PostgreSQL databases. If you're using PlanetScale PostgreSQL, follow the PostgreSQL quickstart guide instead.

先决条件

¥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:

  • PlanetScale 数据库

    ¥A PlanetScale database

  • 来自 PlanetScale 的数据库连接字符串

    ¥Database connection string from PlanetScale

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 --save-dev 
npm install @prisma/client @prisma/adapter-planetscale undici dotenv

以下是每个包的功能:

¥Here's what each package does:

  • prisma - 用于运行 prisma initprisma migrateprisma generate 等命令的 Prisma CLI

    ¥prisma - The Prisma CLI for running commands like prisma init, prisma migrate, and prisma generate

  • @prisma/client - 用于查询数据库的 Prisma 客户端库

    ¥@prisma/client - The Prisma Client library for querying your database

  • @prisma/adapter-planetscale - 用于将 Prisma 客户端连接到数据库的 PlanetScale 驱动程序适配器

    ¥@prisma/adapter-planetscale - The PlanetScale driver adapter that connects Prisma Client to your database

  • undici - PlanetScale 适配器所需的快速 HTTP/1.1 客户端

    ¥undici - A fast HTTP/1.1 client required by the PlanetScale adapter

  • dotenv - 从你的 .env 文件加载环境变量

    ¥dotenv - Loads environment variables from your .env file

3. 配置 ESM 支持

¥ Configure ESM support

更新 tsconfig.json 以兼容 ESM:

¥Update tsconfig.json for ESM compatibility:

tsconfig.json
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "node",
"target": "ES2023",
"strict": true,
"esModuleInterop": true,
"ignoreDeprecations": "6.0"
}
}

更新 package.json 以启用 ESM:

¥Update package.json to enable ESM:

package.json
{
"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 mysql --output ../generated/prisma

此命令执行以下几项操作:

¥This command does a few things:

  • 创建一个名为 prisma/ 的目录,其中包含一个 schema.prisma 文件,该文件包含数据库连接和模式模型

    ¥Creates a prisma/ directory with a schema.prisma file containing your database connection and schema models

  • 在根目录中创建一个用于环境变量的 .env 文件

    ¥Creates a .env file in the root directory for environment variables

  • 创建一个用于 Prisma 配置的 prisma.config.ts 文件

    ¥Creates a prisma.config.ts file for Prisma configuration

生成的 prisma.config.ts 文件如下所示:

¥The generated prisma.config.ts file looks like this:

prisma.config.ts
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:

prisma/schema.prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}

datasource db {
provider = "mysql"
}

更新你的架构以包含 PlanetScale 的 relationMode = "prisma"

¥Update your schema to include relationMode = "prisma" for PlanetScale:

prisma/schema.prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}

datasource db {
provider = "mysql"
relationMode = "prisma"
}

使用 PlanetScale 连接字符串更新 .env 文件:

¥Update your .env file with your PlanetScale connection string:

.env
DATABASE_URL="mysql://username:password@host.connect.psdb.cloud/mydb?sslaccept=strict"

替换为你数据库控制面板中显示的实际 PlanetScale 连接字符串。

¥Replace with your actual PlanetScale connection string from your database dashboard.

5. 定义你的数据模型

¥ Define your data model

打开 prisma/schema.prisma 文件并添加以下模型:

¥Open prisma/schema.prisma and add the following models:

prisma/schema.prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}

datasource db {
provider = "mysql"
relationMode = "prisma"
}

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? @db.Text
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int

@@index([authorId])
}
注意

请注意 Post 模型中的 @@index([authorId])。使用 relationMode = "prisma" 时,PlanetScale 要求外键上创建索引。

¥Note the @@index([authorId]) on the Post model. PlanetScale requires indexes on foreign keys when using relationMode = "prisma".

6. 将 schema 推送到 PlanetScale

¥ Push your schema to PlanetScale

PlanetScale 使用分支工作流,而不是传统的迁移方式。直接推送你的 schema:

¥PlanetScale uses a branching workflow instead of traditional migrations. Push your schema directly:

npx prisma db push

此命令根据你的架构创建数据库表。

¥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:

lib/prisma.ts
import "dotenv/config";
import { PrismaPlanetScale } from '@prisma/adapter-planetscale'
import { PrismaClient } from '../generated/prisma/client'
import { fetch as undiciFetch } from 'undici'

const adapter = new PrismaPlanetScale({ url: process.env.DATABASE_URL, fetch: undiciFetch })
const prisma = new PrismaClient({ adapter })

export { prisma }

8. 编写你的第一个查询

¥ Write your first query

创建 script.ts 文件以测试你的设置:

¥Create a script.ts file to test your setup:

script.ts
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. 使用 Prisma Studio 探索你的数据

¥ Explore your data with Prisma Studio

Prisma Studio 是一个用于数据库的可视化编辑器。使用以下命令启动:

¥Prisma Studio is a visual editor for your database. Launch it with:

npx prisma studio --config ./prisma.config.ts

这将打开一个 Web 界面,你可以在其中查看和编辑数据。

¥This opens a web interface where you can view and edit your data.

支持的数据库

Prisma Studio 目前支持 PostgreSQL、MySQL 和 SQLite。详细信息请参见 Prisma 支持的数据库 Studio

¥Prisma Studio currently supports PostgreSQL, MySQL, and SQLite. For more details, see Databases supported by Prisma Studio.

下一步

¥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