prisma-postgres-setup

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Prisma 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.,
ask
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.
向用户展示选择项(如区域选择、项目删除等)时,请使用你所在平台的交互式选择机制(例如Claude Code中的
ask
工具,其他Agent中的结构化提示)。不要输出静态表格然后要求用户手动输入值,而是提供可选择的选项,让用户可以轻松选择。

Workflow

操作流程

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
PRISMA_SERVICE_TOKEN
in the environment or
.env
file.
1c. 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
references/auth.md
for details on service token creation.
Once you have a token, store it in a shell variable (
PRISMA_SERVICE_TOKEN
) and use it for all subsequent API calls.
你需要一个服务令牌,请按顺序尝试以下获取方式:
1a. 用户提示中的令牌
检查用户初始消息中是否包含服务令牌(例如「使用令牌eyJ...搭建Prisma Postgres」)。如果有,请完全按提供的内容使用——不要截断、重新编码,也不要通过文件中转。将其存储在shell变量中供后续调用使用。
1b. 环境中的令牌
检查环境或
.env
文件中是否存在
PRISMA_SERVICE_TOKEN
1c. 要求用户创建令牌
如果没有可用的令牌,告知用户:
请在Prisma控制台 → 工作区设置 → 服务令牌中创建服务令牌。 复制令牌并粘贴到此处。
更多服务令牌创建的详情请查看
references/auth.md
获取令牌后,将其存储在shell变量(
PRISMA_SERVICE_TOKEN
)中,所有后续API调用都需要使用该令牌。

Step 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/postgres
The response contains an array of regions with
id
,
name
, and
status
. Only present regions where
status
is
available
.
Present the regions as an interactive menu — let the user pick from options rather than typing a region ID manually.
Read
references/endpoints.md
for the full response shape.
获取可用的Prisma Postgres区域列表,让用户选择部署位置。
bash
curl -s -H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
  https://api.prisma.io/v1/regions/postgres
响应包含区域数组,字段有
id
name
status
。仅展示
status
available
的区域。
将区域以交互式菜单的形式展示——让用户从选项中选择,而不是手动输入区域ID。
完整响应结构请查看
references/endpoints.md

Step 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
{ "data": { ... } }
. Extract:
  • data.id
    — the project ID (prefixed with
    proj_
    )
  • data.database.id
    — the database ID (prefixed with
    db_
    )
  • data.database.connections[0].endpoints.direct.connectionString
    — the direct PostgreSQL connection string
Use the direct connection string (
endpoints.direct.connectionString
). Do not use the pooled or accelerate endpoints — those are for legacy Accelerate setups and not needed for new projects.
If the response status is
provisioning
, wait a few seconds and poll
GET /v1/databases/<database-id>
until
status
is
ready
.
If 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
references/endpoints.md
for the full request/response shapes.
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
  }'
默认使用当前目录名称作为项目名。
响应封装在
{ "data": { ... } }
中,提取:
  • data.id
    —— 项目ID(前缀为
    proj_
  • data.database.id
    —— 数据库ID(前缀为
    db_
  • data.database.connections[0].endpoints.direct.connectionString
    —— 直连PostgreSQL连接字符串
请使用直连连接字符串(
endpoints.direct.connectionString
)。不要使用连接池或accelerate端点——这些是旧版Accelerate设置使用的,新项目不需要。
如果响应状态为
provisioning
,等待几秒后轮询
GET /v1/databases/<database-id>
,直到
status
变为
ready
如果因数据库配额不足创建失败,列出用户的现有项目,以交互式菜单形式供用户选择删除。用户选择后删除对应项目并重试。
完整请求/响应结构请查看
references/endpoints.md

Step 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.connectionString
中提取直连连接字符串。

Step 5: Configure the local project

步骤5:配置本地项目

  1. Install dependencies:
bash
npm install prisma @prisma/client @prisma/adapter-pg pg dotenv
All five packages are required:
  • prisma
    — CLI for migrations, schema push, client generation
  • @prisma/client
    — the generated query client
  • @prisma/adapter-pg
    — Prisma 7 driver adapter for direct PostgreSQL connections
  • pg
    — Node.js PostgreSQL driver (used by the adapter)
  • dotenv
    — loads
    .env
    variables for
    prisma.config.ts
  1. Write the direct connection string to
    .env
    . Append to the file if it already exists — do not overwrite existing entries:
DATABASE_URL="<direct-connection-string>"
  1. Verify
    .gitignore
    includes
    .env
    . Create
    .gitignore
    if it does not exist. Warn the user if
    .env
    is not gitignored.
  2. Ensure
    package.json
    has
    "type": "module"
    set (Prisma 7 generates ESM output).
  3. If
    prisma/schema.prisma
    does not exist, run
    npx prisma init
    to scaffold the project. This creates both
    prisma/schema.prisma
    and
    prisma.config.ts
    .
  4. Ensure
    schema.prisma
    has the
    postgresql
    provider and no
    url
    or
    directUrl
    in the datasource block (Prisma 7 manages connection URLs in
    prisma.config.ts
    , not in the schema):
prisma
datasource db {
  provider = "postgresql"
}
  1. Ensure
    prisma.config.ts
    loads the connection URL from the environment:
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
    prisma.config.ts
    , never in
    schema.prisma
  • The provider in
    schema.prisma
    must be
    "postgresql"
    (not
    "prismaPostgres"
    )
  • dotenv/config
    must be imported in
    prisma.config.ts
    to load
    .env
    variables
  1. 安装依赖:
bash
npm install prisma @prisma/client @prisma/adapter-pg pg dotenv
所有五个包都是必须的:
  • prisma
    —— 用于迁移、schema推送、客户端生成的CLI
  • @prisma/client
    —— 生成的查询客户端
  • @prisma/adapter-pg
    —— 用于直连PostgreSQL的Prisma 7驱动适配器
  • pg
    —— Node.js PostgreSQL驱动(供适配器使用)
  • dotenv
    —— 为
    prisma.config.ts
    加载
    .env
    变量
  1. 将直连连接字符串写入
    .env
    。如果文件已存在则追加内容——不要覆盖现有条目:
DATABASE_URL="<direct-connection-string>"
  1. 确认
    .gitignore
    包含
    .env
    。如果
    .gitignore
    不存在则创建。如果
    .env
    没有被git忽略,要警告用户。
  2. 确认
    package.json
    中设置了
    "type": "module"
    (Prisma 7生成ESM输出)。
  3. 如果
    prisma/schema.prisma
    不存在,运行
    npx prisma init
    生成项目框架。这会同时创建
    prisma/schema.prisma
    prisma.config.ts
  4. 确认
    schema.prisma
    使用
    postgresql
    provider,且数据源块中没有
    url
    directUrl
    (Prisma 7在
    prisma.config.ts
    中管理连接URL,而不是在schema中):
prisma
datasource db {
  provider = "postgresql"
}
  1. 确认
    prisma.config.ts
    从环境中加载连接URL:
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
  • schema.prisma
    中的provider必须是
    "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:
  1. "I'll define my schema manually" — Tell the user to edit
    prisma/schema.prisma
    and come back when ready. Wait for them before proceeding.
  2. "Give me a starter schema" — Add a Blog starter schema (User, Post, Comment with relations) to
    prisma/schema.prisma
    . Show the user what was added and ask if they want to adjust it before pushing.
  3. "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 init
This creates migration files in
prisma/migrations/
and generates the client in one step. Migration history is essential for CI/CD workflows (
prisma migrate deploy
) and production deployments.
Only use
npx prisma db push
if the user explicitly asks for prototyping-only mode (no migration history). In that case, follow it with
npx prisma generate
.
如果schema中已经有模型,跳过推送步骤。否则,将以下选项以交互式菜单形式展示
  1. 「我要手动定义schema」 —— 告知用户编辑
    prisma/schema.prisma
    ,准备好后再继续。等待用户操作完成后再执行下一步。
  2. 「给我一个入门schema」 —— 向
    prisma/schema.prisma
    中添加博客入门schema(带关联关系的User、Post、Comment模型)。向用户展示添加的内容,推送前询问是否需要调整。
  3. 「我要描述我的需求」 —— 让用户用自然语言描述他们的数据模型(例如「我要做一个任务管理器,包含项目、任务和团队成员」)。根据描述生成schema,展示给用户,推送前请求确认。
当schema中已有模型且用户确认就绪后,创建迁移并生成客户端:
bash
npx prisma migrate dev --name init
这一步会在
prisma/migrations/
中创建迁移文件,同时生成客户端。迁移历史对CI/CD工作流(
prisma migrate deploy
)和生产部署至关重要。
仅当用户明确要求仅用于原型模式(不需要迁移历史)时才使用
npx prisma db push
。这种情况下,执行完后需要接着运行
npx prisma generate

Step 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.ts
:
typescript
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.ts
Prisma 7 client instantiation rules:
  • Import from
    ./generated/prisma/client.js
    (not
    ./generated/prisma
    )
  • Create a
    pg.Pool
    with the
    DATABASE_URL
    connection string
  • Wrap it in a
    PrismaPg
    adapter
  • Pass
    { adapter }
    to the
    PrismaClient
    constructor
  • Do not use
    datasourceUrl
    — that option does not exist in Prisma 7
  • Do not use
    new PrismaClient()
    with no arguments — it will throw
After verification succeeds, delete
test-connection.ts
.
Then share links for the user to explore their database:
  • Prisma Studio (CLI):
    npx prisma studio
    — opens a visual data browser locally
  • Console:
    https://console.prisma.io/<workspaceId>/<projectId>/<databaseId>/dashboard
    — strip the prefixes (
    wksp_
    ,
    proj_
    ,
    db_
    ) from the IDs returned in Step 3 to build this URL
Read
references/prisma7-client.md
for the full client instantiation reference.
生成客户端后,创建并运行一个快速验证脚本,确认端到端流程正常运行。这一步至关重要——不要跳过。
创建名为
test-connection.ts
的文件:
typescript
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.ts
Prisma 7客户端实例化规则:
  • ./generated/prisma/client.js
    导入(不是
    ./generated/prisma
  • 使用
    DATABASE_URL
    连接字符串创建
    pg.Pool
  • 将其封装在
    PrismaPg
    适配器中
  • { adapter }
    传入
    PrismaClient
    构造函数
  • 不要使用
    datasourceUrl
    ——Prisma 7中没有这个选项
  • 不要不带参数使用
    new PrismaClient()
    ——会抛出异常
验证成功后,删除
test-connection.ts
然后分享链接供用户查看自己的数据库:
  • Prisma Studio(CLI):
    npx prisma studio
    —— 本地打开可视化数据浏览器
  • 控制台:
    https://console.prisma.io/<workspaceId>/<projectId>/<databaseId>/dashboard
    —— 去掉步骤3返回的ID前缀(
    wksp_
    proj_
    db_
    )来构建这个URL
完整的客户端实例化参考请查看
references/prisma7-client.md

Error Handling

错误处理

Read
references/api-basics.md
for the full error reference. Key self-correction patterns:
HTTP StatusError CodeAction
401
authentication-failed
Service token is invalid or expired. Ask the user to create a new one in Console → Workspace Settings → Service Tokens.
404
resource-not-found
Check that the resource ID includes the correct prefix (
proj_
,
db_
,
con_
).
422
validation-error
Check request body against the endpoint schema. Common: missing
name
, invalid
region
.
429
rate-limit-exceeded
Back off and retry after a few seconds.
完整的错误参考请查看
references/api-basics.md
。关键的自动修正规则:
HTTP状态码错误码处理措施
401
authentication-failed
服务令牌无效或已过期。要求用户在控制台 → 工作区设置 → 服务令牌中创建新令牌。
404
resource-not-found
检查资源ID是否包含正确的前缀(
proj_
db_
con_
)。
422
validation-error
对照端点schema检查请求体。常见问题:缺少
name
region
无效。
429
rate-limit-exceeded
退避几秒后重试。

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客户端实例化和使用模式