prisma-postgres-setup
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePrisma Postgres Setup
Prisma Postgres 搭建指南
Procedural skill that guides you through provisioning a new Prisma Postgres database via the Management API and connecting it to a local project.
这是一份流程化操作指南,可指导你通过Management API预配新的Prisma Postgres数据库并将其连接到本地项目。
When to Apply
适用场景
Use this skill when:
- Setting up a new Prisma Postgres database for a project
- Creating a Prisma Postgres project and connecting it locally
- Obtaining a connection string for Prisma Postgres
- Provisioning a database via the Management API (not the Console UI)
Do not use this skill when:
- Setting up CI/CD preview databases — use
prisma-postgres-cicd - Building multi-tenant database provisioning into an app — use
prisma-postgres-integrator - Working with a database that already exists and is connected (schema/migration tasks are standard Prisma CLI)
请在以下场景使用本指南:
- 为项目搭建新的Prisma Postgres数据库
- 创建Prisma Postgres项目并连接到本地环境
- 获取Prisma Postgres的连接字符串
- 通过Management API(而非控制台UI)预配数据库
请勿在以下场景使用本指南:
- 搭建CI/CD预览数据库 —— 请使用
prisma-postgres-cicd - 在应用中内置多租户数据库预配功能 —— 请使用
prisma-postgres-integrator - 处理已存在且已连接的数据库(schema/迁移任务属于标准Prisma CLI功能)
Prerequisites
前置要求
- Node.js 18+
- A Prisma Postgres workspace (create one at https://console.prisma.io if needed)
- A workspace service token (see )
references/auth.md
- Node.js 18+
- Prisma Postgres工作区(如有需要可在https://console.prisma.io 创建)
- 工作区服务令牌(参考)
references/auth.md
UX Guidelines
交互体验指南
When presenting choices to the user (region selection, project deletion, etc.), use your platform's interactive selection mechanism (e.g., tool in Claude Code, structured prompts in other agents). Do not print static tables and ask the user to type a value — present selectable options so the user can pick with minimal effort.
ask向用户展示选择项(如区域选择、项目删除等)时,请使用你所在平台的交互式选择机制(例如Claude Code中的工具,其他Agent中的结构化提示)。不要输出静态表格然后要求用户手动输入值,而是提供可选择的选项,让用户可以轻松选择。
askWorkflow
操作流程
Follow these steps in order. Each step includes the API call to make and how to handle the response.
请按顺序执行以下步骤,每个步骤都包含对应的API调用方法和响应处理方式。
Step 1: Authenticate
步骤1:身份验证
You need a service token. Try these methods in order:
1a. Token in the user's prompt
Check if the user included a service token in their initial message (e.g., "Set up Prisma Postgres with token eyJ..."). If so, use it exactly as provided — do not truncate, re-encode, or round-trip it through a file. Store it in a shell variable for subsequent calls.
1b. Token in the environment
Check for in the environment or file.
PRISMA_SERVICE_TOKEN.env1c. Ask the user to create one
If no token is available, instruct the user:
Create a service token in Prisma Console → Workspace Settings → Service Tokens. Copy the token and paste it here.
Read for details on service token creation.
references/auth.mdOnce you have a token, store it in a shell variable () and use it for all subsequent API calls.
PRISMA_SERVICE_TOKEN你需要一个服务令牌,请按顺序尝试以下获取方式:
1a. 用户提示中的令牌
检查用户初始消息中是否包含服务令牌(例如「使用令牌eyJ...搭建Prisma Postgres」)。如果有,请完全按提供的内容使用——不要截断、重新编码,也不要通过文件中转。将其存储在shell变量中供后续调用使用。
1b. 环境中的令牌
检查环境或文件中是否存在。
.envPRISMA_SERVICE_TOKEN1c. 要求用户创建令牌
如果没有可用的令牌,告知用户:
请在Prisma控制台 → 工作区设置 → 服务令牌中创建服务令牌。 复制令牌并粘贴到此处。
更多服务令牌创建的详情请查看。
references/auth.md获取令牌后,将其存储在shell变量()中,所有后续API调用都需要使用该令牌。
PRISMA_SERVICE_TOKENStep 2: List available regions
步骤2:列出可用区域
Fetch the list of available Prisma Postgres regions to let the user choose where to deploy.
bash
curl -s -H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
https://api.prisma.io/v1/regions/postgresThe response contains an array of regions with , , and . Only present regions where is .
idnamestatusstatusavailablePresent the regions as an interactive menu — let the user pick from options rather than typing a region ID manually.
Read for the full response shape.
references/endpoints.md获取可用的Prisma Postgres区域列表,让用户选择部署位置。
bash
curl -s -H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
https://api.prisma.io/v1/regions/postgres响应包含区域数组,字段有、和。仅展示为的区域。
idnamestatusstatusavailable将区域以交互式菜单的形式展示——让用户从选项中选择,而不是手动输入区域ID。
完整响应结构请查看。
references/endpoints.mdStep 3: Create a project with a database
步骤3:创建带数据库的项目
bash
curl -s -X POST https://api.prisma.io/v1/projects \
-H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "<project-name>",
"region": "<region-id>",
"createDatabase": true
}'Use the current directory name as the project name by default.
The response is wrapped in . Extract:
{ "data": { ... } }- — the project ID (prefixed with
data.id)proj_ - — the database ID (prefixed with
data.database.id)db_ - — the direct PostgreSQL connection string
data.database.connections[0].endpoints.direct.connectionString
Use the direct connection string (). Do not use the pooled or accelerate endpoints — those are for legacy Accelerate setups and not needed for new projects.
endpoints.direct.connectionStringIf the response status is , wait a few seconds and poll until is .
provisioningGET /v1/databases/<database-id>statusreadyIf creation fails due to a database limit, list the user's existing projects and present them as an interactive menu for deletion. After the user picks one, delete it and retry.
Read for the full request/response shapes.
references/endpoints.mdbash
curl -s -X POST https://api.prisma.io/v1/projects \
-H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "<project-name>",
"region": "<region-id>",
"createDatabase": true
}'默认使用当前目录名称作为项目名。
响应封装在中,提取:
{ "data": { ... } }- —— 项目ID(前缀为
data.id)proj_ - —— 数据库ID(前缀为
data.database.id)db_ - —— 直连PostgreSQL连接字符串
data.database.connections[0].endpoints.direct.connectionString
请使用直连连接字符串()。不要使用连接池或accelerate端点——这些是旧版Accelerate设置使用的,新项目不需要。
endpoints.direct.connectionString如果响应状态为,等待几秒后轮询,直到变为。
provisioningGET /v1/databases/<database-id>statusready如果因数据库配额不足创建失败,列出用户的现有项目,以交互式菜单形式供用户选择删除。用户选择后删除对应项目并重试。
完整请求/响应结构请查看。
references/endpoints.mdStep 4: Create a named connection (optional)
步骤4:创建命名连接(可选)
If you need a dedicated connection (e.g., per-developer or per-environment), create one:
bash
curl -s -X POST https://api.prisma.io/v1/databases/<database-id>/connections \
-H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
-H "Content-Type: application/json" \
-d '{ "name": "dev" }'Extract the direct connection string from .
data.endpoints.direct.connectionString如果需要专用连接(例如每个开发者/每个环境一个连接),可创建:
bash
curl -s -X POST https://api.prisma.io/v1/databases/<database-id>/connections \
-H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
-H "Content-Type: application/json" \
-d '{ "name": "dev" }'从中提取直连连接字符串。
data.endpoints.direct.connectionStringStep 5: Configure the local project
步骤5:配置本地项目
- Install dependencies:
bash
npm install prisma @prisma/client @prisma/adapter-pg pg dotenvAll five packages are required:
- — CLI for migrations, schema push, client generation
prisma - — the generated query client
@prisma/client - — Prisma 7 driver adapter for direct PostgreSQL connections
@prisma/adapter-pg - — Node.js PostgreSQL driver (used by the adapter)
pg - — loads
dotenvvariables for.envprisma.config.ts
- Write the direct connection string to . Append to the file if it already exists — do not overwrite existing entries:
.env
DATABASE_URL="<direct-connection-string>"-
Verifyincludes
.gitignore. Create.envif it does not exist. Warn the user if.gitignoreis not gitignored..env -
Ensurehas
package.jsonset (Prisma 7 generates ESM output)."type": "module" -
Ifdoes not exist, run
prisma/schema.prismato scaffold the project. This creates bothnpx prisma initandprisma/schema.prisma.prisma.config.ts -
Ensurehas the
schema.prismaprovider and nopostgresqlorurlin the datasource block (Prisma 7 manages connection URLs indirectUrl, not in the schema):prisma.config.ts
prisma
datasource db {
provider = "postgresql"
}- Ensure loads the connection URL from the environment:
prisma.config.ts
typescript
import path from 'node:path'
import { defineConfig } from 'prisma/config'
import 'dotenv/config'
export default defineConfig({
earlyAccess: true,
schema: path.join(import.meta.dirname, 'prisma', 'schema.prisma'),
datasource: {
url: process.env.DATABASE_URL!,
},
})Important Prisma 7 notes:
- Connection URLs go in , never in
prisma.config.tsschema.prisma - The provider in must be
schema.prisma(not"postgresql")"prismaPostgres" - must be imported in
dotenv/configto loadprisma.config.tsvariables.env
- 安装依赖:
bash
npm install prisma @prisma/client @prisma/adapter-pg pg dotenv所有五个包都是必须的:
- —— 用于迁移、schema推送、客户端生成的CLI
prisma - —— 生成的查询客户端
@prisma/client - —— 用于直连PostgreSQL的Prisma 7驱动适配器
@prisma/adapter-pg - —— Node.js PostgreSQL驱动(供适配器使用)
pg - —— 为
dotenv加载prisma.config.ts变量.env
- 将直连连接字符串写入。如果文件已存在则追加内容——不要覆盖现有条目:
.env
DATABASE_URL="<direct-connection-string>"-
确认包含
.gitignore。如果.env不存在则创建。如果.gitignore没有被git忽略,要警告用户。.env -
确认中设置了
package.json(Prisma 7生成ESM输出)。"type": "module" -
如果不存在,运行
prisma/schema.prisma生成项目框架。这会同时创建npx prisma init和prisma/schema.prisma。prisma.config.ts -
确认使用
schema.prismaprovider,且数据源块中没有postgresql或url(Prisma 7在directUrl中管理连接URL,而不是在schema中):prisma.config.ts
prisma
datasource db {
provider = "postgresql"
}- 确认从环境中加载连接URL:
prisma.config.ts
typescript
import path from 'node:path'
import { defineConfig } from 'prisma/config'
import 'dotenv/config'
export default defineConfig({
earlyAccess: true,
schema: path.join(import.meta.dirname, 'prisma', 'schema.prisma'),
datasource: {
url: process.env.DATABASE_URL!,
},
})Prisma 7重要注意事项:
- 连接URL存放在中,永远不要放在
prisma.config.ts里schema.prisma - 中的provider必须是
schema.prisma(不是"postgresql")"prismaPostgres" - 必须在中导入
prisma.config.ts来加载dotenv/config变量.env
Step 6: Define schema and push
步骤6:定义schema并推送
If the schema already has models, skip to pushing. Otherwise, present these options as an interactive menu:
- "I'll define my schema manually" — Tell the user to edit and come back when ready. Wait for them before proceeding.
prisma/schema.prisma - "Give me a starter schema" — Add a Blog starter schema (User, Post, Comment with relations) to . Show the user what was added and ask if they want to adjust it before pushing.
prisma/schema.prisma - "I'll describe what I need" — Ask the user to describe their data model in natural language (e.g., "I'm building a task manager with projects, tasks, and team members"). Generate a schema from the description, show it, and ask for confirmation before pushing.
Once the schema has models and the user is ready, create a migration and generate the client:
bash
npx prisma migrate dev --name initThis creates migration files in and generates the client in one step. Migration history is essential for CI/CD workflows () and production deployments.
prisma/migrations/prisma migrate deployOnly use if the user explicitly asks for prototyping-only mode (no migration history). In that case, follow it with .
npx prisma db pushnpx prisma generate如果schema中已经有模型,跳过推送步骤。否则,将以下选项以交互式菜单形式展示:
- 「我要手动定义schema」 —— 告知用户编辑,准备好后再继续。等待用户操作完成后再执行下一步。
prisma/schema.prisma - 「给我一个入门schema」 —— 向中添加博客入门schema(带关联关系的User、Post、Comment模型)。向用户展示添加的内容,推送前询问是否需要调整。
prisma/schema.prisma - 「我要描述我的需求」 —— 让用户用自然语言描述他们的数据模型(例如「我要做一个任务管理器,包含项目、任务和团队成员」)。根据描述生成schema,展示给用户,推送前请求确认。
当schema中已有模型且用户确认就绪后,创建迁移并生成客户端:
bash
npx prisma migrate dev --name init这一步会在中创建迁移文件,同时生成客户端。迁移历史对CI/CD工作流()和生产部署至关重要。
prisma/migrations/prisma migrate deploy仅当用户明确要求仅用于原型模式(不需要迁移历史)时才使用。这种情况下,执行完后需要接着运行。
npx prisma db pushnpx prisma generateStep 7: Verify the connection
步骤7:验证连接
After generating the client, create and run a quick verification script to confirm everything works end-to-end. This is critical — do not skip this step.
Create a file named :
test-connection.tstypescript
import 'dotenv/config'
import pg from 'pg'
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from './generated/prisma/client.js'
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
const adapter = new PrismaPg(pool)
const prisma = new PrismaClient({ adapter })
const result = await prisma.$queryRawUnsafe('SELECT 1 as connected')
console.log('Connected to Prisma Postgres:', result)
await prisma.$disconnect()
await pool.end()Run it:
bash
npx tsx test-connection.tsPrisma 7 client instantiation rules:
- Import from (not
./generated/prisma/client.js)./generated/prisma - Create a with the
pg.Poolconnection stringDATABASE_URL - Wrap it in a adapter
PrismaPg - Pass to the
{ adapter }constructorPrismaClient - Do not use — that option does not exist in Prisma 7
datasourceUrl - Do not use with no arguments — it will throw
new PrismaClient()
After verification succeeds, delete .
test-connection.tsThen share links for the user to explore their database:
- Prisma Studio (CLI): — opens a visual data browser locally
npx prisma studio - Console: — strip the prefixes (
https://console.prisma.io/<workspaceId>/<projectId>/<databaseId>/dashboard,wksp_,proj_) from the IDs returned in Step 3 to build this URLdb_
Read for the full client instantiation reference.
references/prisma7-client.md生成客户端后,创建并运行一个快速验证脚本,确认端到端流程正常运行。这一步至关重要——不要跳过。
创建名为的文件:
test-connection.tstypescript
import 'dotenv/config'
import pg from 'pg'
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from './generated/prisma/client.js'
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
const adapter = new PrismaPg(pool)
const prisma = new PrismaClient({ adapter })
const result = await prisma.$queryRawUnsafe('SELECT 1 as connected')
console.log('Connected to Prisma Postgres:', result)
await prisma.$disconnect()
await pool.end()运行:
bash
npx tsx test-connection.tsPrisma 7客户端实例化规则:
- 从导入(不是
./generated/prisma/client.js)./generated/prisma - 使用连接字符串创建
DATABASE_URLpg.Pool - 将其封装在适配器中
PrismaPg - 将传入
{ adapter }构造函数PrismaClient - 不要使用——Prisma 7中没有这个选项
datasourceUrl - 不要不带参数使用——会抛出异常
new PrismaClient()
验证成功后,删除。
test-connection.ts然后分享链接供用户查看自己的数据库:
- Prisma Studio(CLI): —— 本地打开可视化数据浏览器
npx prisma studio - 控制台: —— 去掉步骤3返回的ID前缀(
https://console.prisma.io/<workspaceId>/<projectId>/<databaseId>/dashboard、wksp_、proj_)来构建这个URLdb_
完整的客户端实例化参考请查看。
references/prisma7-client.mdError Handling
错误处理
Read for the full error reference. Key self-correction patterns:
references/api-basics.md| HTTP Status | Error Code | Action |
|---|---|---|
| 401 | | Service token is invalid or expired. Ask the user to create a new one in Console → Workspace Settings → Service Tokens. |
| 404 | | Check that the resource ID includes the correct prefix ( |
| 422 | | Check request body against the endpoint schema. Common: missing |
| 429 | | Back off and retry after a few seconds. |
完整的错误参考请查看。关键的自动修正规则:
references/api-basics.md| HTTP状态码 | 错误码 | 处理措施 |
|---|---|---|
| 401 | | 服务令牌无效或已过期。要求用户在控制台 → 工作区设置 → 服务令牌中创建新令牌。 |
| 404 | | 检查资源ID是否包含正确的前缀( |
| 422 | | 对照端点schema检查请求体。常见问题:缺少 |
| 429 | | 退避几秒后重试。 |
Reference Files
参考文件
Detailed API and usage information is in:
references/auth.md — Service token creation and usage
references/api-basics.md — Base URL, envelope, IDs, errors, pagination
references/endpoints.md — Endpoint details for projects, databases, connections, regions
references/prisma7-client.md — Prisma 7 client instantiation and usage patterns详细的API和使用信息存放在:
references/auth.md — 服务令牌创建和使用
references/api-basics.md — 基础URL、封装结构、ID、错误、分页
references/endpoints.md — 项目、数据库、连接、区域的端点详情
references/prisma7-client.md — Prisma 7客户端实例化和使用模式