GitHub Copilot
GitHub Copilot 是一款 AI 編碼助手,可加速您的 Prisma ORM 工作流程,讓您減少編寫樣板程式碼的時間,將更多精力投入到資料建模、查詢和協作中。藉助編輯器中的 GitHub Copilot 擴充套件,您可以
- 在編輯 schema 或呼叫客戶端時,獲取 Prisma 感知的程式碼建議。
- 與 Copilot 聊天討論建模模式、排查查詢問題或探索遷移策略。
- 透過 Copilot 的命令面板介面執行常見的 Prisma CLI 命令(例如
prisma migrate dev、prisma 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 語法、客戶端方法、遷移命令等。
如何啟用擴充套件
- 從 GitHub Marketplace 安裝 **Prisma for Copilot**。
- 確保 GitHub Copilot Chat 已安裝 並在您的程式碼編輯器中處於活動狀態。
- 在您的工作區中開啟一個檔案並啟動 Copilot Chat。
- 在聊天中,在您的問題前加上
@prisma-for-copilot關鍵詞
@prisma-for-copilot How do I define a one-to-many relation?
- 安裝 適用於 GitHub Copilot 的 Prisma 擴充套件。
- 開啟您的 IDE。
- 安裝 GitHub Copilot Chat 擴充套件。
- 開啟 Copilot Chat 並切換到 提問模式。
- 提問:"
@prisma-for-github-copilot如何定義一對多關係?" (如果幾秒鐘後沒有顯示@prisma-for-github-copilot名稱空間,請重新載入聊天。) - 出現提示時,在瀏覽器中授權 Prisma 應用,然後返回聊天介面。
- 返回聊天介面後,重新發送問題。
- 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 會自動將這些規則應用於您專案中的每個對話。