跳到主要内容

GitHub Copilot

GitHub Copilot 是一款 AI 编码助手,可加速您的 Prisma ORM 工作流程,让您减少编写样板代码的时间,将更多精力投入到数据建模、查询和协作中。借助编辑器中的 GitHub Copilot 扩展,您可以

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

GitHub Copilot 允许您通过适用于 GitHub Copilot 的 Prisma 扩展查询官方文档,并执行 VS Code 代理模式下的操作,例如搭建 Prisma schema、运行种子脚本以及创建生产就绪的 Prisma Postgres 数据库。

使用适用于 GitHub Copilot 的 Prisma 扩展查询 Prisma 文档

适用于 GitHub Copilot 的 Prisma 扩展让您可以直接在 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. 安装 适用于 GitHub Copilot 的 Prisma 扩展。
  2. 打开您的 IDE。
  3. 安装 GitHub Copilot Chat 扩展
  4. 打开 Copilot Chat 并切换到 提问模式
  5. 提问:"@prisma-for-github-copilot 如何定义一对多关系?" (如果几秒钟后没有显示 @prisma-for-github-copilot 命名空间,请重新加载聊天。)
  6. 出现提示时,在浏览器中授权 Prisma 应用,然后返回聊天界面。
  7. 返回聊天界面后,重新发送问题。
  8. Copilot 直接从 Prisma 文档中提取并返回答案。

使用 GitHub Copilot 的代理功能

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

  • 运行和检查迁移。
  • 生成 Prisma Client 代码。
  • 创建一个新的 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/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.
* **Client extensions** for metrics: create extensions that wrap calls to emit timing and telemetry instead of middleware.

### 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 会自动将这些规则应用于您项目中的每个对话。

© . All rights reserved.