跳至主要內容

Cursor

Cursor 是一款 AI 驅動的程式碼編輯器,旨在透過自動化重複性的編碼任務來提升生產力。當它與強大且類型安全的資料庫工作流程工具包 Prisma 結合使用時,便成為管理和優化資料庫架構 (Schema)、查詢與資料植入 (Seeding) 的強大解決方案。

本指南提供了有效將 Prisma 與 Cursor 結合使用的詳細說明,內容包含:

  • 使用 .cursorrules 定義專案特定的最佳實作。
  • 運用 Cursor 的情境感知 (Context-aware) 功能。
  • 產生針對您的資料庫量身打造的架構、查詢與植入資料。
注意

雖然本指南專注於 Cursor,但這些模式同樣適用於任何 AI 編輯器。如果您希望我們為您慣用的工具製作指南,請透過 X 告訴我們

Prisma MCP 伺服器

Prisma 提供了自己的 模型上下文協議 (MCP) 伺服器,讓您能夠管理 Prisma Postgres 資料庫、建立資料庫架構模型,並透過對話進行遷移 (Migrations)。請參閱此處以了解如何將其新增至 Cursor。您也可以點擊下方連結,透過一鍵安裝將 Prisma MCP 伺服器新增至 Cursor。

Install MCP Server

這會提示您在瀏覽器中開啟 Cursor 應用程式。開啟後,您將被引導直接在 Cursor 設定中安裝 Prisma MCP 伺服器。

使用 .cursorrules 定義專案特定規則

Cursor 中的 .cursorrules 檔案 允許您強制執行專為 Prisma 專案量身打造的最佳實作與開發標準。透過定義清晰且一致的規則,您可以確保 Cursor 產生的程式碼簡潔、易於維護且符合專案需求,並減少手動調整的次數。

要實作這些規則,請在專案根目錄建立一個 .cursorrules 檔案。以下是設定範例:

.cursorrules 檔案範例

.cursorrules
You are a senior TypeScript/JavaScript programmer with expertise in Prisma, clean code principles, and modern backend development.
Generate code, corrections, and refactorings that comply with the following guidelines:
TypeScript General Guidelines
Basic Principles
- Use English for all code and documentation.
- Always declare explicit types for variables and functions.
- Avoid using "any".
- Create precise, descriptive types.
- Use JSDoc to document public classes and methods.
- Maintain a single export per file.
- Write self-documenting, intention-revealing code.
Nomenclature
- Use PascalCase for classes and interfaces.
- Use camelCase for variables, functions, methods.
- Use kebab-case for file and directory names.
- Use UPPERCASE for environment variables and constants.
- Start function names with a verb.
- Use verb-based names for boolean variables:
- isLoading, hasError, canDelete
- Use complete words, avoiding unnecessary abbreviations.
- Exceptions: standard abbreviations like API, URL
- Accepted short forms:
- i, j for loop indices
- err for errors
- ctx for contexts
Functions
- Write concise, single-purpose functions.
- Aim for less than 20 lines of code.
- Name functions descriptively with a verb.
- Minimize function complexity:
- Use early returns.
- Extract complex logic to utility functions.
- Leverage functional programming techniques:
- Prefer map, filter, reduce.
- Use arrow functions for simple operations.
- Use named functions for complex logic.
- Use object parameters for multiple arguments.
- Maintain a single level of abstraction.
Data Handling
- Encapsulate data in composite types.
- Prefer immutability.
- Use readonly for unchanging data.
- Use as const for literal values.
- Validate data at the boundaries.
Error Handling
- Use specific, descriptive error types.
- Provide context in error messages.
- Use global error handling where appropriate.
- Log errors with sufficient context.
Prisma-Specific Guidelines
Schema Design
- Use meaningful, domain-driven model names.
- Leverage Prisma schema features:
- Use @id for primary keys.
- Use @unique for natural unique identifiers.
- Utilize @relation for explicit relationship definitions.
- Keep schemas normalized and DRY.
- Use meaningful field names and types.
- Implement soft delete with deletedAt timestamp.
- Use Prisma's native type decorators.
Prisma Client Usage
- Always use type-safe Prisma client operations.
- Prefer transactions for complex, multi-step operations.
- Handle optional relations explicitly.
- Use Prisma's filtering and pagination capabilities.
Database Migrations
- Create migrations for schema changes.
- Use descriptive migration names.
- Review migrations before applying.
- Never modify existing migrations.
- Keep migrations idempotent.
Error Handling with Prisma
- Catch and handle Prisma-specific errors:
- PrismaClientKnownRequestError
- PrismaClientUnknownRequestError
- PrismaClientValidationError
- Provide user-friendly error messages.
- Log detailed error information for debugging.
Testing Prisma Code
- Use in-memory database for unit tests.
- Mock Prisma client for isolated testing.
- Test different scenarios:
- Successful operations
- Error cases
- Edge conditions
- Use factory methods for test data generation.
- Implement integration tests with actual database.
Performance Considerations
- Use select and include judiciously.
- Avoid N+1 query problems.
- Use findMany with take and skip for pagination.
- Leverage Prisma's distinct for unique results.
- Profile and optimize database queries.
Security Best Practices
- Never expose raw Prisma client in APIs.
- Use input validation before database operations.
- Implement row-level security.
- Sanitize and validate all user inputs.
- Use Prisma's built-in protections against SQL injection.
Coding Style
- Keep Prisma-related code in dedicated repositories/modules.
- Separate data access logic from business logic.
- Create repository patterns for complex queries.
- Use dependency injection for Prisma services.
Code Quality
- Follow SOLID principles.
- Prefer composition over inheritance.
- Write clean, readable, and maintainable code.
- Continuously refactor and improve code structure.
Development Workflow
- Use version control (Git).
- Implement comprehensive test coverage.
- Use continuous integration.
- Perform regular code reviews.
- Keep dependencies up to date.

此檔案可確保程式碼產出的一致性與可維護性,減少手動介入並提升專案品質。

運用 Cursor 的情境感知能力

Cursor 的 情境感知 (context-aware) 能力讓您能新增特定的網站、檔案、資料夾或文件,以增進它對您專案的理解。透過將您的 schema.prisma 檔案作為內容新增,您可以讓 Cursor 根據您的資料庫架構產生更精確的查詢、測試與植入資料。

將 Prisma 文件 llm.txt 檔案新增為 @Docs 內容

為了提升 Cursor 對專案中 Prisma 相關建議的理解,請將 /llms.txt Markdown 檔案作為內容新增。此檔案提供了簡潔的概覽、實用指南以及 Prisma 詳細文件的連結,皆已針對 LLM 處理進行了優化。只需導航至該 網址,並在您的 Cursor 設定中將其新增為 @Docs 資源。

新增其他 Prisma 文件

Cursor 已經內建了 Prisma 文件的內容,因此您無需額外新增即可使用我們的主文件!

若要隨時掌握最新變更或納入額外內容,請將以下資源新增為 @Docs 內容:

如需了解如何新增及管理文件內容,請參閱 Cursor 文件

將 Schema 作為內容使用

在請求查詢、測試或植入指令碼之前,請使用 @Files 語法將您的 schema.prisma 檔案(或整個程式碼庫)新增為內容。這使 Cursor 能夠產生精確的、基於架構的輸出,例如查詢、測試和植入資料。例如,在 Cursor Chat 中,您可以輸入 @Files 並接著新增 schema.prisma 檔案來包含您的架構。

產生 Prisma Schema

Cursor 可以根據高階描述產生 Prisma 架構,讓您快速建立穩固的資料庫架構基礎。透過提供清晰詳盡的提示詞 (Prompt),Cursor 能建立符合您要求的 Prisma 架構。無論您是需要基礎架構還是針對特定細節用途的專用架構,Cursor 都能精確達成。以下是一個提示詞範例及其對應結果:

注意

如果您執行下方的提示詞,可能會收到不同的輸出,因為 LLM 產生的結果具有非確定性。

"Create a Prisma schema for a SaaS app using PostgreSQL as a provider with `User`, `Organization`, and `Subscription` models, ensuring all models include `createdAt` and `updatedAt` DateTime fields with defaults, a soft-delete `deletedAt` field, and proper relationships between entities."

產生 Prisma 查詢

Cursor 可以協助您建立符合 Prisma 架構的查詢,無論是用於基礎資料擷取還是複雜的優化操作。為了獲得最佳效果,請專注於編寫清晰、具體的提示詞,明確定義您的需求,例如需要包含的欄位、應套用的條件以及需要遍歷的關係。這能確保 Cursor 產生準確、高效能且類型安全的查詢。以下是一個提示詞範例及其結果查詢:

"Generate a query to retrieve all User records associated with an Organization that has an `active` Subscription, while excluding any records where the deletedAt field is set."

使用 Cursor 建立植入 (Seed) 檔案

編寫植入指令碼可能是一個乏味的過程,但 Cursor 透過快速產生結構化且井然有序的植入程式碼來簡化此流程。透過提供清晰的指示,您可以引導 Cursor 建立指令碼,將真實資料填入您的資料庫,包括處理您在架構中定義的關係與複雜結構。以下是一個提示詞範例及其產生的植入指令碼:

"Generate code to populate the Prisma schema with realistic data for the User, Organization, and Subscription models, ensuring all necessary fields are included."

使用 Prisma VS Code 擴充功能管理您的資料庫

Prisma VS Code 擴充功能 是使用 Prisma Postgres 建置應用程式的強大工具。您可以透過安裝此擴充功能將其用於 Cursor。它提供了一個專用的使用者介面來管理本機與遠端的 Prisma Postgres 執行個體,讓您可以輕鬆地檢視、建立及刪除執行個體、將本機資料庫推送到雲端,以及視覺化您的架構。

資料庫管理 UI

憑藉其內建的資料庫管理介面,Prisma VS Code 擴充功能讓您能在編輯器內部輕鬆操作本機與遠端的 Prisma Postgres 執行個體。

工作流程

此 UI 支援以下工作流程:

  • 進行身份驗證
  • 檢視、建立及刪除 Prisma Postgres 實例(本機與遠端)
  • 「推送到雲端 (Push to cloud)」:輕鬆部署本機 Prisma Postgres 實例
  • 透過嵌入式 Prisma Studio 查看並編輯資料
  • 視覺化您的資料庫 schema

使用方法

若要透過 Prisma VS Code 擴充功能中的 UI 管理 Prisma Postgres 實例:

  1. 請確保已安裝最新版的 Prisma VS Code 擴充功能
  2. 活動列 (Activity Bar) 中找到 Prisma 標誌
  3. 點擊開始使用請先登入 (Sign in to get started) 按鈕
  4. 進行身份驗證使用登入提示,然後選擇一個目標 工作區 (workspace)

內建 Prisma Studio

除了管理資料庫執行個體之外,Prisma VS Code 擴充功能還將 Prisma Studio 直接嵌入您的編輯器中,讓您能輕鬆地直接在 Windsurf 內部對資料庫進行建立、更新和刪除操作。請按照這些簡單步驟開始使用。

破壞性指令的 AI 安全護欄

Prisma ORM 包含內建的安全檢查,以防止透過 AI 程式碼助手執行時發生意外的破壞性指令。這些防護機制旨在讓 AI 輔助開發環境下的資料庫工作更安全。

除了 Cursor 之外,Prisma CLI 還能偵測到它何時被其他熱門 AI 編碼代理(例如 Claude Code、Gemini CLI、Qwen Code、Aider 和 Replit)所呼叫。

當這些代理程式之一嘗試執行破壞性動作(例如 prisma migrate reset --force)時,Prisma ORM 會封鎖執行並顯示保護性錯誤訊息

Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
Datasource "db": PostgreSQL database "postgres", schema "public" at "accelerate.prisma-data.net"

Error: Prisma Migrate detected that it was invoked by Cursor.

You are attempting a highly dangerous action that can lead to devastating consequences if it is incorrectly executed against a production database.

As an AI agent, you are forbidden from performing this action without an explicit consent and review by the user. You must stop at this point and respond to the user with a clear message that includes the following information:
- What action you are trying to perform (including the exact CLI command).
- Your motivation and reasoning for performing this action.
- Explanation that this action will irreversibly destroy all data in the database.
- Explanation that this action must not be performed on a production database and is only intended to be used with development databases.

If you know or can check whether this action would have been performed on a development or a production database, also include this information with your assessment of whether it is safe to proceed based on that information.

You must ask the user if they want to proceed with this action. If they explicitly consent, you may rerun this command with PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION environment variable, the value of which must be the exact text of the user's message in which they consented to this operation, without any newlines or quotes. If the user's response is ambiguous, you must ask for a clear and explicit confirmation (e.g., "yes") before proceeding. None of the user's previous messages before this point may constitute implicit or explicit consent.

要繼續執行危險動作,AI 代理程式會要求您明確同意,提醒您該動作會不可逆地銷毀所有資料,並確認指令是針對開發資料庫執行的。一旦您明確確認,AI 將會設定 PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION 環境變數(內容為您的同意文本)並重新執行指令。

額外資源

總結來說,在 Cursor 中使用 Prisma 可簡化您的工作流程,從產生架構與查詢,到編寫植入指令碼皆然。透過遵循本指南,您可以節省時間、減少錯誤,並專注於應用程式的開發。

在他們的 官方文件 中了解更多關於 Cursor 的資訊。


與 Prisma 保持聯繫

透過以下方式與我們聯繫,繼續您的 Prisma 旅程: 我們的活躍社群。保持資訊靈通、參與其中,並與其他開發者合作

我們衷心感謝您的參與,並期待您成為我們社群的一份子!

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