Cursor
Cursor 是一個 AI 驅動的程式碼編輯器,旨在透過自動化重複編碼任務來提高生產力。當與 Prisma(一個用於資料庫工作流的強大且型別安全的工具包)結合使用時,它成為管理和最佳化資料庫模式、查詢和資料填充的強大解決方案。
本指南提供了將 Prisma 與 Cursor 有效結合使用的詳細說明,以實現以下目標:
- 使用
.cursorrules定義專案特定的最佳實踐。 - 利用 Cursor 的上下文感知能力。
- 生成適合您資料庫的模式、查詢和填充資料。
雖然本指南側重於 Cursor,但這些模式應適用於任何 AI 編輯器。如果您希望我們為您首選的工具建立指南,請透過 X 告訴我們!
Prisma MCP 伺服器
Prisma 提供了自己的 模型上下文協議 (MCP) 伺服器,讓您能夠管理 Prisma Postgres 資料庫、建模資料庫模式以及透過遷移進行聊天。在此處瞭解如何將其新增到 Cursor 。您還可以使用 一鍵安裝 將 Prisma MCP 伺服器新增到 Cursor,方法是點選以下連結
這將提示您在瀏覽器中開啟 Cursor 應用。一旦開啟,您將獲得指導,將 Prisma MCP 伺服器直接安裝到您的 Cursor 配置中。
使用 .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.
- Use Prisma middleware for cross-cutting concerns:
- Logging
- Soft delete
- Auditing
- 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 的 上下文感知 能力讓您能夠新增特定網站、檔案、資料夾或文件,以增強其對您專案的理解。透過將您的 schema.prisma 檔案新增為上下文,您可以使 Cursor 根據您的資料庫模式生成更準確的查詢、測試和填充資料。
將 Prisma 文件 llm.txt 檔案新增為 @Docs 上下文
為了提高 Cursor 對專案中 Prisma 相關建議的理解,請將 /llms.txt Markdown 檔案作為上下文包含進來。此檔案提供了簡潔的概述、有用的指導以及指向詳細 Prisma 文件的連結——所有這些都經過了 LLM 處理的最佳化。只需導航到 URL,並將其新增為 Cursor 配置中的 @Docs 資源。
新增額外的 Prisma 文件
Cursor 已經包含了 Prisma 文件的內建上下文,所以您無需新增任何內容即可使用我們的文件!您可以 此處 檢視 Cursor 使用的現有資源。
要及時瞭解最新更改或整合額外上下文,請將這些資源新增為 @Docs 上下文
- Prisma 變更日誌,用於瞭解更新和新功能。
- Prisma 部落格,用於獲取實用指南和最佳實踐。
要了解如何新增和管理文件上下文,請訪問 Cursor 文件。
使用模式作為上下文
在請求查詢、測試或填充指令碼之前,使用 @Files 語法將您的 schema.prisma 檔案(或整個程式碼庫)新增為上下文。這使得 Cursor 能夠生成精確的、模式驅動的輸出,例如查詢、測試和填充資料。例如,在 Cursor Chat 中,您可以透過輸入 @Files 後新增您的 schema.prisma 檔案來包含您的模式。
生成 Prisma Schema
Cursor 可以從高層描述中生成 Prisma 模式,使您能夠快速為資料庫模式奠定堅實的基礎。透過提供清晰詳細的提示,Cursor 會生成符合您要求的 Prisma 模式。無論您需要通用的基礎模式還是針對特定用例的高度特定模式,Cursor 都能精確交付。以下是示例提示及其相應結果:
如果您執行以下提示,可能會收到不同的輸出,因為 LLM 會產生非確定性響應。
- 生成 Prisma 模式的提示
- 結果
"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."
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String
password String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deletedAt DateTime?
organization Organization @relation(fields: [organizationId], references: [id])
organizationId Int
role UserRole @default(MEMBER)
}
model Organization {
id Int @id @default(autoincrement())
name String
slug String @unique
subscription Subscription?
users User[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deletedAt DateTime?
}
model Subscription {
id Int @id @default(autoincrement())
organization Organization @relation(fields: [organizationId], references: [id])
organizationId Int @unique
plan SubscriptionPlan
status SubscriptionStatus @default(ACTIVE)
startDate DateTime
endDate DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deletedAt DateTime?
}
enum UserRole {
ADMIN
MEMBER
}
enum SubscriptionPlan {
FREE
BASIC
PREMIUM
ENTERPRISE
}
enum SubscriptionStatus {
ACTIVE
CANCELED
EXPIRED
PAST_DUE
}
生成 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."
const activeUsers = await prisma.user.findMany({
where: {
deletedAt: null,
organization: {
deletedAt: null,
subscription: {
deletedAt: null,
status: 'ACTIVE'
}
}
},
include: {
organization: {
include: {
subscription: true
}
}
},
orderBy: {
createdAt: 'desc'
},
skip: 0,
take: 10
});
使用 Cursor 建立填充檔案
編寫填充指令碼可能是一個繁瑣的過程,但 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."
import {
PrismaClient,
UserRole,
SubscriptionPlan,
SubscriptionStatus,
} from "@prisma/client";
const prisma = new PrismaClient();
async function main() {
// Clear existing data
await prisma.user.deleteMany();
await prisma.subscription.deleteMany();
await prisma.organization.deleteMany();
const organizations = [
{
name: "Tech Innovators",
slug: "tech-innovators",
subscription: {
plan: SubscriptionPlan.ENTERPRISE,
status: SubscriptionStatus.ACTIVE,
startDate: new Date("2024-01-01"),
},
users: [
{
name: "Emma Thompson",
email: "emma@techinnovators.com",
role: UserRole.ADMIN,
password: "password123",
},
{
name: "Michael Chen",
email: "michael@techinnovators.com",
role: UserRole.MEMBER,
password: "password123",
},
],
},
{
name: "Digital Solutions",
slug: "digital-solutions",
subscription: {
plan: SubscriptionPlan.PREMIUM,
status: SubscriptionStatus.ACTIVE,
startDate: new Date("2024-01-15"),
},
users: [
{
name: "Sarah Wilson",
email: "sarah@digitalsolutions.com",
role: UserRole.ADMIN,
password: "password123",
},
{
name: "James Miller",
email: "james@digitalsolutions.com",
role: UserRole.MEMBER,
password: "password123",
},
],
},
{
name: "Cloud Systems",
slug: "cloud-systems",
subscription: {
plan: SubscriptionPlan.BASIC,
status: SubscriptionStatus.ACTIVE,
startDate: new Date("2024-02-01"),
},
users: [
{
name: "David Garcia",
email: "david@cloudsystems.com",
role: UserRole.ADMIN,
password: "password123",
},
{
name: "Lisa Wang",
email: "lisa@cloudsystems.com",
role: UserRole.MEMBER,
password: "password123",
},
],
},
{
name: "Data Analytics Co",
slug: "data-analytics",
subscription: {
plan: SubscriptionPlan.PREMIUM,
status: SubscriptionStatus.ACTIVE,
startDate: new Date("2024-01-10"),
},
users: [
{
name: "Alex Johnson",
email: "alex@dataanalytics.com",
role: UserRole.ADMIN,
password: "password123",
},
{
name: "Rachel Kim",
email: "rachel@dataanalytics.com",
role: UserRole.MEMBER,
password: "password123",
},
],
},
{
name: "Smart Solutions",
slug: "smart-solutions",
subscription: {
plan: SubscriptionPlan.FREE,
status: SubscriptionStatus.ACTIVE,
startDate: new Date("2024-02-15"),
},
users: [
{
name: "Daniel Brown",
email: "daniel@smartsolutions.com",
role: UserRole.ADMIN,
password: "password123",
},
{
name: "Maria Rodriguez",
email: "maria@smartsolutions.com",
role: UserRole.MEMBER,
password: "password123",
},
],
},
];
for (const org of organizations) {
const createdOrg = await prisma.organization.create({
data: {
name: org.name,
slug: org.slug,
subscription: {
create: {
plan: org.subscription.plan,
status: org.subscription.status,
startDate: org.subscription.startDate,
},
},
},
});
for (const user of org.users) {
await prisma.user.create({
data: {
name: user.name,
email: user.email,
password: user.password,
role: user.role,
organizationId: createdOrg.id,
},
});
}
}
console.log("Seed data created successfully");
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
附加資源
總而言之,將 Cursor 與 Prisma 結合使用可簡化您的工作流程,從生成模式和查詢到編寫填充指令碼。透過遵循本指南,您可以節省時間、減少錯誤,並專注於構建應用程式。
在 Cursor 官方文件 中瞭解更多關於 Cursor 的資訊。
與 Prisma 保持聯絡
透過與以下方面建立聯絡,繼續您的 Prisma 之旅: 我們的活躍社群。隨時瞭解資訊、參與其中並與其他開發者協作
- 在 X 上關注我們 獲取公告、現場活動和實用技巧。
- 加入我們的 Discord 提問、與社群交流並獲得積極的對話支援。
- 訂閱 YouTube 觀看教程、演示和直播。
- 在 GitHub 上參與 透過標星儲存庫、報告問題或為問題貢獻力量。