GitHub Copilot
GitHub Copilot 是一款 AI 程式碼助手,能加速您的 Prisma ORM 工作流程,讓您減少處理樣板程式碼的時間,將更多心力投入在資料建模、查詢與協作上。透過編輯器中的 GitHub Copilot 擴充功能,您可以:
- 在編輯結構描述(Schema)或呼叫用戶端(Client)時,獲得具備 Prisma 認知的程式碼建議。
- 與 Copilot 討論建模模式、排解查詢問題或探索遷移策略。
- 透過 Copilot 的命令選擇介面執行常見的 Prisma CLI 指令(例如
prisma migrate dev、prisma db push)。 - 直接從 Copilot 對話介面建立 Prisma 結構描述模型、產生 Prisma Client 程式碼並執行遷移。
GitHub Copilot 允許您透過 Prisma for GitHub Copilot 擴充功能 查詢官方文件,並在 VS Code 代理模式 (agent mode) 下執行自動化操作,例如建立 Prisma 結構描述、執行種子腳本 (seed scripts) 以及建立適用於正式環境的 Prisma Postgres 資料庫。
使用 Prisma for GitHub Copilot 擴充功能查詢 Prisma 文件
Prisma for GitHub Copilot 擴充功能 讓您可以直接在 GitHub Copilot Chat 中獲取 Prisma 文件。您可以從編輯器中查詢結構描述語法、用戶端方法、遷移指令等資訊。
如何啟用該擴充功能
- 從 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?
- 安裝 Prisma for GitHub Copilot 擴充功能。
- 開啟您的 IDE。
- 安裝 GitHub Copilot Chat 擴充功能。
- 開啟 Copilot Chat 並切換至 Ask 模式。
- 詢問:「
@prisma-for-github-copilot如何定義一對多關係?」(如果幾秒鐘後沒有出現@prisma-for-github-copilot命名空間,請重新載入對話。) - 出現提示時,請在瀏覽器中授權 Prisma 應用程式,然後回到對話視窗。
- 回到對話後,重新發送該問題。
- Copilot 會直接從 Prisma 文件中提取並回覆答案。
使用 GitHub Copilot 的代理功能
GitHub Copilot Chat 在 VS Code 中提供了一種代理 (Agent) 模式,可以執行 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 檔案),它會自動建立一個名為 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 會自動將這些規則套用到您專案中的每次對話。