Cursor
Cursor は、反復的なコーディングタスクを自動化することで生産性を向上させるように設計された、AI搭載のコードエディタです。データベースワークフローのための堅牢でタイプセーフなツールキットであるPrismaと組み合わせることで、データベーススキーマ、クエリ、およびデータシードを管理および最適化するための強力なソリューションになります。
このガイドでは、CursorとPrismaを効果的に使用するための詳細な手順を説明します。
.cursorrules
を使用してプロジェクト固有のベストプラクティスを定義する。- Cursorのコンテキスト認識機能を活用する。
- データベースに合わせて調整されたスキーマ、クエリ、およびシードデータを生成する。
このガイドはCursorに焦点を当てていますが、これらのパターンはどのAIエディタでも機能するはずです。ご希望のツール用のガイドを作成してほしい場合は、X でお知らせください。
Prisma MCPサーバー
Prismaは、Prisma Postgresデータベースの管理、データベーススキーマのモデル化、および移行を通じたチャットを可能にする独自のモデルコンテキストプロトコル(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
コンテキストとして追加する
プロジェクトにおけるPrisma関連の提案に対するCursorの理解を向上させるには、/llms.txt
マークダウンファイルをコンテキストとして含めます。このファイルは、簡潔な概要、役立つガイダンス、および詳細なPrismaドキュメントへのリンクを提供します。これらはすべてLLM処理用に最適化されています。url に移動して、Cursor構成で @Docs
リソースとして追加するだけです。
追加のPrismaドキュメントを追加する
CursorにはPrismaドキュメントからの組み込みコンテキストがすでに含まれているため、ドキュメントを利用するために何かを追加する必要はありません! Cursorが使用している既存のリソースはこちらで確認できます。
最新の変更に常に追従したり、追加のコンテキストを組み込んだりするには、これらのリソースを @Docs
コンテキストとして追加します。
- 更新と新機能については、Prisma Changelogを参照してください。
- 実践的なガイドとベストプラクティスについては、Prisma Blogを参照してください。
ドキュメントコンテキストを追加および管理する方法については、Cursorドキュメントをご覧ください。
スキーマをコンテキストとして使用する
クエリ、テスト、またはシードスクリプトをリクエストする前に、@Files
構文を使用して、schema.prisma
ファイル(またはコードベース全体)をコンテキストとして追加します。これにより、Cursorはクエリ、テスト、およびシードデータなどの正確なスキーマ駆動型出力を生成できます。たとえば、Cursor Chat では、@Files
と入力し、その後に schema.prisma
ファイルを追加することで、スキーマを含めることができます。
Prismaスキーマの生成
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の詳細については、公式ドキュメントをご覧ください。
Prismaとのつながりを保つ
以下と連携してPrismaの旅を続けましょう。 活発なコミュニティ。常に情報を入手し、参加し、他の開発者と協力しましょう。
- Xでフォローしてください お知らせ、ライブイベント、および役立つヒントについて。
- Discordに参加する 質問をしたり、コミュニティと話したり、会話を通じて積極的なサポートを受けたりできます。
- YouTubeでチャンネル登録する チュートリアル、デモ、およびストリームについては。
- GitHubで参加する リポジトリにスターを付けたり、問題を報告したり、問題に貢献したりします。