Cursor
Cursor 是一个 AI 驱动的代码编辑器,旨在通过自动执行重复的编码任务来提高工作效率。当与 Prisma(一种用于数据库工作流的强大且类型安全的工具包)搭配使用时,它将成为管理和优化数据库模式、查询和数据播种的强大解决方案。
¥Cursor is an AI-powered code editor designed to boost productivity by automating repetitive coding tasks. When paired with Prisma, a robust and type-safe toolkit for database workflows, it becomes a powerful solution for managing and optimizing database schemas, queries, and data seeding.
本指南提供了有效使用 Prisma 和 Cursor 的详细说明:
¥This guide provides detailed instructions for effectively using Prisma with Cursor to:
-
使用
.cursorrules
定义特定于项目的最佳实践。¥Define project-specific best practices with
.cursorrules
. -
使用 Cursor 的上下文感知功能。
¥Using Cursor's context-aware capabilities.
-
生成适合你数据库的模式、查询和种子数据。
¥Generate schemas, queries, and seed data tailored to your database.
虽然本指南重点介绍 Cursor,但这些模式应该适用于任何 AI 编辑器。在 X 上让我们知道 如果你希望我们为你首选的工具创建指南!
¥While this guide is focused on Cursor, these patterns should work with any AI editor. Let us know on X if you'd like us to create guides for your preferred tool!
Prisma MCP 服务器
¥Prisma MCP server
Prisma 提供自己的 模型上下文协议 (MCP) 服务器,可让你管理 Prisma Postgres 数据库、建模数据库模式并通过迁移进行聊天。了解更多关于如何将其添加到 Cursor 此处 的信息。你也可以通过点击以下链接,使用 一键安装 将 Prisma MCP 服务器添加到 Cursor:
¥Prisma provides its own Model Context Protocol (MCP) server that lets you manage Prisma Postgres databases, model database schemas and chat through migrations. Learn more about how you can add it to Cursor here. You can also add the Prisma MCP server to Cursor using the one-click installation by clicking on the following link:
这将提示你在浏览器中打开 Cursor 应用。打开后,系统将引导你将 Prisma MCP 服务器直接安装到你的 Cursor 配置中。
¥This will prompt you to open the Cursor app in your browser. Once opened, you'll be guided to install the Prisma MCP server directly into your Cursor configuration.
使用 .cursorrules
定义项目特定规则
¥Defining project-specific rules with .cursorrules
Cursor 中的 .cursorrules
文件 允许你实现针对你的 Prisma 项目的最佳实践和开发标准。通过定义清晰一致的规则,你可以确保 Cursor 以最少的手动调整生成干净、可维护且特定于项目的代码。
¥The .cursorrules
file in Cursor allows you to enforce best practices and development standards tailored to your Prisma projects. By defining clear and consistent rules, you can ensure that Cursor generates clean, maintainable, and project-specific code with minimal manual adjustments.
要实现这些规则,请在项目的根目录中创建一个 .cursorrules
文件。以下是示例配置:
¥To implement these rules, create a .cursorrules
file in the root of your project. Below is an example configuration:
示例 .cursorrules
文件
¥Example .cursorrules
file
.cursorrules
文件.cursorrules
fileYou 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.
此文件确保一致且可维护的代码生成,减少人工干预,同时提高项目质量。
¥This file ensures consistent and maintainable code generation, reducing manual intervention while improving project quality.
使用 Cursor 的上下文感知功能
¥Using Cursor's context-aware capabilities
Cursor 的 context-aware 功能可让你添加特定的网站、文件、文件夹或文档,以增强其对你项目的理解。通过添加 schema.prisma
文件作为上下文,你可以启用 Cursor 根据数据库模式生成更准确的查询、测试和种子数据。
¥Cursor's context-aware capabilities let you add specific websites, files, folders or documentation to enhance its understanding of your project. By adding your schema.prisma
file as context, you enable Cursor to generate more accurate queries, tests, and seed data based on your database schema.
将 Prisma docs llm.txt
文件添加为 @Docs
上下文
¥Add Prisma docs llm.txt
file as @Docs
context
为了提高 Cursor 对项目中与 Prisma 相关的建议的理解,请将 /llms.txt
markdown 文件作为上下文包含在内。此文件提供简明的概述、有用的指导以及指向详细 Prisma 文档的链接 - 所有这些都针对 LLM 处理进行了优化。只需导航到 url 并将其作为 @Docs
资源添加到你的 Cursor 配置中。
¥To improve Cursor's understanding of Prisma-related suggestions in your project, include the /llms.txt
markdown file as context. This file offers a concise overview, useful guidance, and links to detailed Prisma documentation—all optimized for LLM processing. Simply navigate to the url and add it as a @Docs
resource in your Cursor configuration.
添加其他 Prisma 文档
¥Adding additional Prisma documentation
Cursor 已经包含来自 Prisma 文档的内置上下文,因此你无需添加任何内容即可使用我们的文档!
¥Cursor already includes built-in context from Prisma documentation, so you don't need to add anything to make us of our docs!
要了解最新更改或合并其他上下文,请将这些资源添加为 @Docs
上下文:
¥To stay updated with the latest changes or incorporate additional context, add these resources as @Docs
context:
-
Prisma 变更日志 用于更新和新功能。
¥Prisma Changelog for updates and new features.
-
Prisma 博客 用于实用指南和最佳实践。
¥Prisma Blog for practical guides and best practices.
要了解如何添加和管理文档上下文,请访问 光标文档。
¥To learn how to add and manage documentation context, visit the Cursor documentation.
使用模式作为上下文
¥Using schema as context
在请求查询、测试或种子脚本之前,使用 @Files
语法将你的 schema.prisma
文件(或整个代码库)添加为上下文。这允许 Cursor 生成精确的、模式驱动的输出,例如查询、测试和种子数据。例如,在 光标聊天 中,你可以通过键入 @Files
然后添加 schema.prisma
文件来包含你的架构。
¥Add your schema.prisma
file (or the entire codebase) as context using the @Files
syntax before requesting queries, tests, or seed scripts. This allows Cursor to generate precise, schema-driven outputs such as queries, tests, and seed data. For example, in Cursor Chat, you can include your schema by typing @Files
followed by adding your schema.prisma
file.
生成 Prisma 模式
¥Generating Prisma Schema
Cursor 可以从高级描述中生成 Prisma 模式,使你能够快速为数据库模式建立坚实的基础。通过提供清晰详细的提示,Cursor 可以根据你的要求创建 Prisma 模式。无论你需要通用的基础模式还是针对详细用例的高度特定的模式,Cursor 都可以精确地提供。这是一个示例提示及其相应的结果:
¥Cursor can generate Prisma schemas from high-level descriptions, enabling you to quickly establish a solid foundation for your database schema. By providing a clear and detailed prompt, Cursor creates Prisma schemas tailored to your requirements. Whether you need a general foundational schema or a highly specific one for detailed use cases, Cursor can deliver with precision. Here's an example prompt and its corresponding result:
如果你运行以下提示,你可能会收到不同的输出,因为 LLM 会产生非确定性响应。
¥If you run the prompts below, you may receive a different outputs because LLMs produce non-deterministic responses.
- Prompt to generate Prisma schema
- Result
"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 查询
¥Generating Prisma queries
Cursor 可以帮助你创建针对你的 Prisma 模式定制的查询,无论是用于基本数据检索还是复杂的优化操作。为了获得最佳结果,请专注于编写清晰、具体的提示来定义你的要求,例如要包含的字段、要应用的条件和要遍历的关系。这确保 Cursor 生成准确、高性能和类型安全的查询。这是一个示例提示及其结果查询:
¥Cursor can help you create queries tailored to your Prisma schema, whether for basic data retrieval or complex, optimized operations. To get the best results, focus on writing clear, specific prompts that define your requirements, such as the fields to include, conditions to apply, and relationships to traverse. This ensures Cursor generates accurate, performant, and type-safe queries. Here's an example prompt and its resulting query:
- Prompt to generate a database query
- Result
"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 创建种子文件
¥Creating seed files with Cursor
编写种子脚本可能是一个繁琐的过程,但 Cursor 通过快速生成结构化和有组织的种子代码简化了它。通过提供清晰的说明,你可以指导 Cursor 创建脚本,用真实数据填充数据库,包括处理模式中定义的关系和复杂结构。这是一个示例提示及其结果种子脚本:
¥Writing seed scripts can be a tedious process, but Cursor simplifies it by quickly generating structured and organized seed code. By providing clear instructions, you can guide Cursor to create scripts that populate your database with realistic data, including handling relationships and complex structures defined in your schema. Here's an example prompt and its resulting seed script:
- Prompt to seed the database
- Result
"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();
});
使用 Prisma VS Code 扩展管理数据库
¥Using the Prisma VS Code extension to manage your database
Prisma VS Code 扩展 是使用 Prisma Postgres 构建应用的强大工具。你也可以通过安装扩展程序在 Cursor 中使用它。它提供专用 UI 用于管理本地和远程 Prisma Postgres 实例,让你可以轻松查看、创建和删除实例,将本地数据库推送到云端,并可视化你的数据库架构。
¥The Prisma VS Code extension is a powerful tool for building applications with Prisma Postgres. You can also use it in Cursor by installing the extension. It provides a dedicated UI for managing Prisma Postgres instances, both local and remote, making it easy to view, create, and delete instances, push local databases to the cloud, and visualize your schema.
数据库管理界面
¥Database management UI
Prisma VS Code 扩展 内置数据库管理界面,让你可以轻松地在编辑器内部使用本地和远程 Prisma Postgres 实例。
¥With its built-in database management interface, the Prisma VS Code extension lets you easily work with local and remote Prisma Postgres instances from inside your editor.
工作流程
¥Workflows
UI 支持以下工作流程:
¥The UI enables the following workflows:
-
使用 进行身份验证
¥Authenticate with the
-
查看、创建和删除 Prisma Postgres 实例(本地和远程)
¥View, create and delete Prisma Postgres instances (local & remote)
-
"推送到云端":轻松部署本地 Prisma Postgres 实例
¥"Push to cloud": Easily deploy a local Prisma Postgres instance
-
通过嵌入式 Prisma Studio 查看和编辑数据
¥View and edit data via an embedded Prisma Studio
-
可视化你的数据库模式
¥Visualize your database schema
用法
¥Usage
要通过 Prisma VS Code 扩展中的 UI 管理 Prisma Postgres 实例:
¥To manage Prisma Postgres instances via the UI in the Prisma VS Code extension:
-
确保你已安装最新版本的 Prisma VS Code 扩展
¥Ensure you have the latest version of the Prisma VS Code extension installed
-
在活动栏中找到 Prisma 徽标
¥Find the Prisma logo in the Activity Bar
-
点击“登录开始”按钮
¥Click the Sign in to get started button
-
使用登录提示符对 进行身份验证,然后选择目标 workspace
¥Authenticate with the using the sign-in prompt, then select a target workspace
内置 Prisma Studio
¥Prisma Studio built-in
除了管理数据库实例之外,Prisma VS Code 扩展还将 Prisma Studio 直接嵌入到你的编辑器中,让你可以轻松地在 Windsurf 中对数据库执行创建、更新和删除操作。按照 简单步骤 开始操作。
¥Beyond managing your database instances, the Prisma VS Code extension embeds Prisma Studio directly in your editor, making it easy to perform create, update, and delete operations on your database right inside Windsurf. Follow these easy steps to get started.
破坏性命令的 AI 安全防护
¥AI Safety guardrails for destructive commands
Prisma ORM 包含内置安全检查,以防止通过 AI 编程助手运行时意外执行破坏性命令。这些防护措施旨在使在 AI 辅助开发环境中使用数据库更加安全。
¥Prisma ORM includes built-in safety checks to prevent accidental destructive commands when run through AI coding assistants. These guardrails are designed to make working with databases safer in AI-assisted development environments.
除了 Cursor 之外,Prisma CLI 还可以检测其他流行的 AI 编码代理(例如 Claude Code、Gemini CLI、Qwen Code、Aider 和 Replit)何时调用它。
¥Including Cursor, the Prisma CLI can also detect when it is being invoked by other popular AI coding agents such as Claude Code, Gemini CLI, Qwen Code, Aider, and Replit.
当其中一个代理尝试执行破坏性操作(例如 prisma migrate reset --force
)时,Prisma ORM 会阻止执行并显示保护性错误消息:
¥When one of these agents attempts a destructive action such as prisma migrate reset --force
, Prisma ORM blocks execution and shows a protective error message:
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
环境变量,然后重新运行该命令。
¥To proceed with the dangerous action, the AI agent will ask you for explicit consent, remind you that the action irreversibly destroys all data, and confirm that the command is being run against a development database. Once you clearly confirm, the AI will set the PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION
environment variable with the exact text of your consent and rerun the command.
其他资源
¥Additional resources
总之,将 Cursor 与 Prisma 结合使用可简化你的工作流程,从生成架构和查询到编写种子脚本。通过遵循本指南,你可以节省时间、减少错误并专注于构建应用。
¥In summary, using Cursor with Prisma simplifies your workflow, from generating schemas and queries to writing seed scripts. By following this guide, you can save time, reduce errors, and focus on building your application.
了解有关其 官方文档 中的 Cursor 的更多信息。
¥Learn more about Cursor in their official documentation.
Stay connected with Prisma
Continue your Prisma journey by connecting with our active community. Stay informed, get involved, and collaborate with other developers:
- Follow us on X for announcements, live events and useful tips.
- Join our Discord to ask questions, talk to the community, and get active support through conversations.
- Subscribe on YouTube for tutorials, demos, and streams.
- Engage on GitHub by starring the repository, reporting issues, or contributing to an issue.