Skip to main content

GitHub Copilot

GitHub Copilot 是一款 AI 编码助手,可加速你的 Prisma ORM 工作流程,让你减少在样板代码上花费的时间,而将更多时间用于数据建模、查询和协作。使用编辑器中的 GitHub Copilot 扩展程序,你可以:

¥GitHub Copilot is an AI coding assistant that speeds up your Prisma ORM workflows, so you spend less time on boilerplate and more on data modeling, querying, and collaboration. With the GitHub Copilot extension in your editor, you can:

  • 在编辑模式或调用客户端时获取 Prisma 感知的代码建议。

    ¥Get Prisma-aware code suggestions as you edit your schema or invoke the client.

  • 与 Copilot 讨论建模模式、排除查询故障或探索迁移策略。

    ¥Chat with Copilot about modeling patterns, troubleshoot queries, or explore migration strategies.

  • 通过 Copilot 的命令面板界面运行常用的 Prisma CLI 命令(例如 prisma migrate devprisma db push)。

    ¥Run common Prisma CLI commands (e.g. prisma migrate dev, prisma db push) via Copilot's command-palette interface.

  • 搭建 Prisma 模式模型,生成 Prisma 客户端代码,并直接从 Copilot 聊天界面运行迁移。

    ¥Scaffold Prisma schema models and generate Prisma Client code and run migrations directly from the Copilot chat interface.

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

¥GitHub Copilot allows you to query the official docs via the Prisma for GitHub Copilot extension and also perform automated actions in VS Code Agent mode, such as scaffolding a Prisma schema, running seeds scripts, and creating a production-ready Prisma Postgres database.

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

¥Query Prisma docs with the Prisma for GitHub Copilot extension

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

¥The Prisma for GitHub Copilot extension lets you fetch Prisma documentation directly in GitHub Copilot Chat. You can look up schema syntax, client methods, migration commands, and more from your editor.

如何启用扩展

¥How to enable the extension

  1. 从 GitHub Marketplace 安装 Copilot 的 Prisma。

    ¥Install the Prisma for Copilot from the GitHub Marketplace.

  2. 确保 GitHub Copilot Chat 已安装 在代码编辑器中处于活动状态。

    ¥Ensure GitHub Copilot Chat is installed and active in your code editor.

  3. 在你的工作区中打开一个文件并启动 Copilot Chat。

    ¥Open a file in your workspace and launch Copilot Chat.

  4. 在聊天中,请在你的问题前添加 @prisma-for-copilot 关键字:

    ¥In chat, prefix your question with the @prisma-for-copilot keyword:

@prisma-for-copilot How do I define a one-to-many relation?
  1. 安装 Prisma for GitHub Copilot 扩展。

    ¥Install the Prisma for GitHub Copilot extension.

  2. 打开你的 IDE。

    ¥Open your IDE.

  3. 安装 GitHub Copilot Chat 扩展

    ¥Install the GitHub Copilot Chat extension.

  4. 打开 Copilot Chat 并切换到 提问模式

    ¥Open Copilot Chat and switch to Ask mode.

  5. 提问:“@prisma-for-github-copilot 我该如何定义一对多关系?”(如果 @prisma-for-github-copilot 命名空间几秒钟后仍未显示,请刷新聊天。)

    ¥Ask: "@prisma-for-github-copilot How do I define a one-to-many relation?" (If the @prisma-for-github-copilot namespace doesn't show up after a few seconds, reload the chat.)

  6. 出现提示时,请在浏览器中授权 Prisma 应用,然后返回聊天室。

    ¥When prompted, authorize the Prisma app in your browser, then return to the chat.

  7. 返回聊天后,重新发送问题。

    ¥After returning to the chat, resend the question.

  8. Copilot 返回直接从 Prisma 文档中提取的答案。

    ¥Copilot returns the answer pulled straight from the Prisma docs.

使用 GitHub Copilot 的代理功能

¥Use GitHub Copilot's agent features

GitHub Copilot Chat 在 VS Code 中提供可运行 Prisma 命令的代理模式。你可以使用代理聊天执行以下操作:

¥GitHub Copilot Chat offers an Agent mode in VS Code that can run Prisma commands. You can use the agent chat to:

  • 运行并检查迁移。

    ¥Run and inspect migrations.

  • 生成 Prisma 客户端代码。

    ¥Generate Prisma Client code.

  • 创建一个新的 Prisma Postgres 数据库并更新你的 .env 文件。

    ¥Create a new Prisma Postgres database and update your .env file.

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

¥You can type Create a database named test-db and add its connection string to the .env file. in the Copilot chat, and it will automatically create a new database named test-db and add the connection string to your .env file. To learn more about this, visit our VS Code agent mode documentation.

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

¥Customize GitHub Copilot with copilot-instructions.md

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

¥You can tailor Copilot Chat's behavior in your repository by adding a .github/copilot-instructions.md file. This file injects your guidelines into every Copilot Chat session.

Example .github/copilot-instructions.md for Prisma
# 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 会自动将这些规则应用于你项目中的每个对话。

¥Place this file at the root of your repository under .github/. Copilot Chat automatically applies these rules to every conversation in your project.