跳至主要内容

GitHub Copilot

GitHub Copilot 是一款 AI 编码助手,可加快您的 Prisma ORM 工作流程,让您减少编写样板代码的时间,将更多时间用于数据建模、查询和协作。在编辑器中安装 GitHub Copilot 扩展后,您可以:

  • 在编辑 schema 或调用客户端时,获取与 Prisma 相关的代码建议。
  • 与 Copilot 讨论建模模式、排除查询故障或探索迁移策略。
  • 通过 Copilot 的命令面板界面运行常见的 Prisma CLI 命令(例如 prisma migrate devprisma db push)。
  • 直接从 Copilot 聊天界面搭建 Prisma schema 模型、生成 Prisma 客户端代码并运行迁移。

GitHub Copilot 允许您通过 Prisma for GitHub Copilot 扩展 查询官方文档,还可以通过 VS Code 代理模式执行自动化操作,例如搭建 Prisma schema、运行 seed 脚本以及创建生产就绪的 Prisma Postgres 数据库。

使用 Prisma for GitHub Copilot 扩展查询 Prisma 文档

Prisma for GitHub Copilot 扩展 允许您直接在 GitHub Copilot Chat 中获取 Prisma 文档。您可以从编辑器中查找 schema 语法、客户端方法、迁移命令等。

如何启用扩展

  1. 从 GitHub Marketplace 安装 Prisma for Copilot
  2. 确保 GitHub Copilot Chat 已安装 并在您的代码编辑器中处于活动状态。
  3. 在工作区中打开一个文件并启动 Copilot Chat。
  4. 在聊天中,在您的问题前加上 @prisma-for-copilot 关键字。
@prisma-for-copilot How do I define a one-to-many relation?
  1. 安装 Prisma for GitHub Copilot 扩展。
  2. 打开您的 IDE。
  3. 安装 GitHub Copilot Chat 扩展
  4. 打开 Copilot Chat 并切换到 Ask 模式
  5. 提问:“@prisma-for-github-copilot 如何定义一对多关系?”(如果几秒钟后没有出现 @prisma-for-github-copilot 命名空间,请重新加载聊天。)
  6. 出现提示时,在浏览器中授权 Prisma 应用,然后返回聊天。
  7. 返回聊天后,重新发送问题。
  8. Copilot 将直接从 Prisma 文档中提取答案并返回。

使用 GitHub Copilot 的代理功能

GitHub Copilot Chat 在 VS Code 中提供 Agent 模式,可以运行 Prisma 命令。您可以使用代理聊天来:

  • 运行和检查迁移。
  • 生成 Prisma 客户端代码。
  • 创建新的 Prisma Postgres 数据库并更新您的 .env 文件。

您可以在 Copilot 聊天中输入 Create a database named test-db and add its connection string to the .env file.,它将自动创建一个名为 test-db 的新数据库,并将连接字符串添加到您的 .env 文件中。要了解更多信息,请访问我们的 VS Code 代理模式文档

使用 copilot-instructions.md 自定义 GitHub Copilot

您可以通过 添加 .github/copilot-instructions.md 文件 来定制 Copilot Chat 在您的仓库中的行为。此文件会将您的指南注入到每个 Copilot Chat 会话中。

Prisma 的 .github/copilot-instructions.md 示例
# GitHub Copilot Instructions for Prisma Workspace

## General Guidelines

1. **Language**: English only.
2. **Types**: Declare explicit types; avoid `any`.
3. **Comments**: Use JSDoc for public methods and classes.
4. **Exports**: One export per file.
5. **Naming**:

* **Classes/interfaces** → `PascalCase`
* **Variables/functions** → `camelCase`
* **Files/directories** → `kebab-case`
* **Constants** → `UPPERCASE`
* **Boolean flags** → verb-based (e.g., `isLoading`)

---

## Prisma-Specific Guidelines

### 1. Data Modeling

* **Domain-driven model names**: keep them singular (e.g. `User`, `OrderItem`).
* **Field naming**: use `camelCase` for fields (e.g. `createdAt`, `deletedAt`).
* **IDs & keys**:

```prisma
model Post {
id Int @id @default(autoincrement())
uuid String @unique @default(uuid())
}
/```
* **Composite keys & uniques**:

```prisma
@@id([userId, role])
@@unique([email, tenantId])
/```
* **Enums & constrained values**: leverage `enum` for fixed domains.
* **Soft deletes & audit**:

```prisma
model Base {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deletedAt DateTime?
}
/```

### 2. Indexing & Constraints

* **Single-column indexes** for frequent lookups:

```prisma
@@index([email])
/```
* **Compound indexes** for multi-field filters/sorts:

```prisma
@@index([status, createdAt])
/```
* **Full-text search** (Postgres-only):

```prisma
@@index([title, content], type: Brin) // or Gin for JSONB
/```

### 3. Migrations

* **Descriptive names**: `npx prisma migrate dev --name add-order-totals`
* **Idempotent steps**: avoid imperative SQL in migrations.
* **Shadow database**: enable in CI to catch drift.
* **Never edit** migration SQL after it’s applied to any environment.

### 4. Client Instantiation & Connection Management

* **Singleton pattern**

```ts
// prisma.ts
import { PrismaClient } from '../prisma/generated/client';
export const prisma = global.prisma || new PrismaClient();
if (process.env.NODE_ENV !== 'production') global.prisma = prisma;
/```

### 5. Transactions & Batch Operations

* **Multi-step atomicity**:

```ts
const result = await prisma.$transaction([
prisma.user.create({ data: { /*…*/ } }),
prisma.order.create({ data: { /*…*/ } }),
]);
/```
* **Interactive transactions** for long-running flows.
* **Bulk writes**: chunk large inserts/updates to avoid timeouts.

### 6. Precise Queries & Performance

* **Select only needed fields**:

```ts
await prisma.user.findUnique({
where: { id },
select: { id: true, email: true },
});
/```
* **Avoid N+1**: use `include` or batch `findMany` with `where: { id: { in: [...] } }` or use database joins in prisma.
* Use **Cursor-based pagination**

### 7. Raw Queries & Client Extensions

* **Raw SQL** when necessary, safely:

```ts
const users = await prisma.$queryRaw`SELECT * FROM "User" WHERE email = ${email}`;
/```
* **Sanitize inputs** with `Prisma.sql` for complex interpolations.
* **Client extensions**: use preview feature `clientExtensions` to add common helper methods.

### 8. Error Handling

* **Catch specific errors**:

```ts
try {
// …
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
// P2002: Unique constraint
}
}
/```
* **Wrap in service-level errors** to add context before bubbling up.

### 9. Testing

* **In-memory DB** (SQLite) or **Testcontainers** for integration tests.
* **Mock Prisma Client** for pure unit tests via `jest.mock()` or similar.

### 10. Logging, Monitoring & Metrics

* **Enable query logging** in dev:

```ts
new PrismaClient({ log: ['query', 'warn', 'error'] });
/```
* **APM integration** (Datadog, Sentry) – capture latency, errors.

### 11. Security & Best Practices

* **Never expose** raw Prisma client in HTTP controllers—wrap in a service layer.
* **Validate inputs** (e.g. with Zod) before any DB operation.
* **Least privilege** DB users: use separate roles for migrations vs. runtime.
* **Rotate credentials** and load from secure vault (AWS Secrets Manager, etc.).

### 12. Environment & Configuration

* **Centralize `DATABASE_URL`** and connection settings in `.env`.
* **Pin preview features** in `schema.prisma`:

```prisma
generator client {
previewFeatures = ["clientExtensions", "interactiveTransactions"]
}
/```
* **Version pinning**: match CLI and client versions in `package.json`.

将此文件放置在您的仓库根目录下的 .github/ 文件夹中。Copilot Chat 会自动将这些规则应用于您项目中的每次对话。

© . This site is unofficial and not affiliated with Prisma Data, Inc.