メインコンテンツにスキップ

Cursor

Cursorは、反復的なコーディングタスクを自動化することで生産性を向上させるように設計されたAI搭載コードエディタです。堅牢で型安全なデータベースワークフロー用ツールキットであるPrismaと組み合わせることで、データベーススキーマ、クエリ、データシーディングの管理と最適化のための強力なソリューションとなります。

このガイドでは、PrismaをCursorと効果的に使用するための詳細な手順を説明します。

  • .cursorrulesを使用してプロジェクト固有のベストプラクティスを定義します。
  • Cursorのコンテキスト認識機能を使用します。
  • データベースに合わせたスキーマ、クエリ、シードデータを生成します。

このガイドはCursorに焦点を当てていますが、これらのパターンはどのAIエディタでも機能するはずです。お気に入りのツール用のガイドを作成してほしい場合は、Xでお知らせください

Prisma MCPサーバー

Prismaは、Prisma Postgresデータベースの管理、データベーススキーマのモデリング、およびマイグレーションに関するチャットを可能にする独自のモデルコンテキストプロトコル (MCP) サーバーを提供しています。これをCursorに追加する方法についてはこちらで詳しく知ることができます。また、以下のリンクをクリックすることで、ワンクリックインストールを使用してPrisma MCPサーバーをCursorに追加することもできます。

Install MCP Server

これにより、ブラウザで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 docs llm.txtファイルを@Docsコンテキストとして追加

プロジェクトにおけるPrisma関連の提案に関するCursorの理解度を向上させるには、/llms.txtマークダウンファイルをコンテキストとして含めます。このファイルは、簡潔な概要、役立つガイダンス、詳細なPrismaドキュメントへのリンクを提供し、すべてLLM処理に最適化されています。単にURLに移動し、Cursorの設定で@Docsリソースとして追加するだけです。

追加のPrismaドキュメントの追加

CursorにはPrismaドキュメントからの組み込みコンテキストがすでに含まれているため、弊社のドキュメントを利用するために何かを追加する必要はありません!Cursorが使用する既存のリソースはこちらで確認できます。

最新の変更に追いついたり、追加のコンテキストを組み込んだりするには、これらのリソースを@Docsコンテキストとして追加します。

  • アップデートと新機能についてはPrismaチェンジログを参照してください。
  • 実践的なガイドとベストプラクティスについてはPrismaブログを参照してください。

ドキュメントコンテキストの追加と管理方法については、Cursorドキュメントを参照してください。

スキーマをコンテキストとして使用

クエリ、テスト、またはシードスクリプトをリクエストする前に、@Files構文を使用してschema.prismaファイル(またはコードベース全体)をコンテキストとして追加します。これにより、Cursorはクエリ、テスト、シードデータなどの正確なスキーマ駆動型出力を生成できます。例えば、Cursor Chatでは、@Filesと入力し、続けてschema.prismaファイルを追加することでスキーマを含めることができます。

Prismaスキーマの生成

Cursorは高レベルな記述からPrismaスキーマを生成でき、データベーススキーマの強固な基盤を迅速に確立できます。明確で詳細なプロンプトを提供することで、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でシードファイルを作成

シードスクリプトの作成は面倒なプロセスですが、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."

追加リソース

要するに、CursorをPrismaと一緒に使用することで、スキーマやクエリの生成からシードスクリプトの作成まで、ワークフローが簡素化されます。このガイドに従うことで、時間を節約し、エラーを減らし、アプリケーションの構築に集中できます。

Cursorの詳細については、公式ドキュメントでご確認ください。


Prismaとつながる

Prismaの旅を続けるには、以下とつながりましょう 活発なコミュニティに参加しましょう。情報収集し、関わりを持ち、他の開発者と協力しましょう。

  • Xでフォローする アナウンス、ライブイベント、役立つヒントについて。
  • Discordに参加する 質問したり、コミュニティと話したり、会話を通じて積極的なサポートを受けたりできます。
  • YouTubeで購読する チュートリアル、デモ、ストリームについて。
  • GitHubで関わる リポジトリにスターを付けたり、問題を報告したり、問題に貢献したりすることで。
皆様のご参加を心から歓迎し、コミュニティの一員となることを楽しみにしています!

© . All rights reserved.