mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 06:42:54 +08:00
Add comprehensive MDC files for various technologies and frameworks
Generate a large set of Markdown Configuration (MDC) files covering best practices across multiple domains, including: - AI/ML libraries (PyTorch, TensorFlow, scikit-learn) - Backend frameworks (Django, FastAPI, Express, Spring Boot) - Frontend frameworks (React, Vue, Angular) - Cloud platforms (AWS, Azure, GCP) - Development tools (Docker, Kubernetes, Terraform) - State management libraries - UI component libraries - Web technologies and APIs Enhance project documentation with detailed, standardized best practice guidelines for different technologies and frameworks
This commit is contained in:
@@ -0,0 +1,285 @@
|
||||
---
|
||||
description: This rule file outlines best practices for developing with DuckDB, covering code organization, performance optimization, security considerations, and testing strategies. It aims to improve code quality, maintainability, and overall project health when using DuckDB.
|
||||
globs: **/*.{sql,ddl,md,duckdb}
|
||||
---
|
||||
# DuckDB Best Practices and Coding Standards
|
||||
|
||||
This document provides guidelines and best practices for developing with DuckDB. Following these recommendations will lead to more maintainable, performant, and secure DuckDB projects.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1. Directory Structure Best Practices
|
||||
|
||||
* **Project Root:**
|
||||
* `.cursor/`: Contains Cursor rule files.
|
||||
* `data/`: Stores data files (CSV, Parquet, etc.). Consider subdirectories based on data source or type.
|
||||
* `sql/`: Contains SQL scripts (DDL, DML, queries).
|
||||
* `scripts/`: Python, Bash, or other scripts for data processing and automation.
|
||||
* `docs/`: Project documentation.
|
||||
* `tests/`: Test scripts and data.
|
||||
* `venv/` (or `.venv/`): Virtual environment for Python dependencies (if applicable).
|
||||
* `Makefile`: Automation of common tasks (e.g., data loading, testing).
|
||||
* `README.md`: Project overview and instructions.
|
||||
* `.gitignore`: Specifies intentionally untracked files that Git should ignore.
|
||||
|
||||
* **Example:**
|
||||
|
||||
|
||||
my_duckdb_project/
|
||||
├── .cursor/
|
||||
│ └── rules.mdc
|
||||
├── data/
|
||||
│ ├── raw/
|
||||
│ │ └── sales_data.csv
|
||||
│ └── processed/
|
||||
│ └── sales_summary.parquet
|
||||
├── sql/
|
||||
│ ├── create_tables.sql
|
||||
│ ├── queries/
|
||||
│ │ ├── monthly_sales.sql
|
||||
│ │ └── top_customers.sql
|
||||
│ └── data_validation.sql
|
||||
├── scripts/
|
||||
│ └── process_data.py
|
||||
├── docs/
|
||||
│ └── user_guide.md
|
||||
├── tests/
|
||||
│ ├── unit/
|
||||
│ │ └── test_queries.py
|
||||
│ └── integration/
|
||||
│ └── test_data_pipeline.py
|
||||
├── venv/
|
||||
├── Makefile
|
||||
├── README.md
|
||||
└── .gitignore
|
||||
|
||||
|
||||
### 1.2. File Naming Conventions
|
||||
|
||||
* **SQL Scripts:** Use descriptive names with underscores (e.g., `create_tables.sql`, `monthly_sales_report.sql`).
|
||||
* **Data Files:** Use names reflecting the data content (e.g., `customer_data.csv`, `product_catalog.parquet`). Prefix with dates if versioning is needed (e.g., `2024-01-01_customer_data.csv`).
|
||||
* **Scripts:** Use names indicating the script's purpose (e.g., `load_data.py`, `run_tests.sh`).
|
||||
* **DDL Files:** `schema.sql`, `tables.sql` etc. for defining database structures
|
||||
|
||||
### 1.3. Module Organization (if using a scripting language like Python)
|
||||
|
||||
* **Separate Modules:** Divide code into logical modules (e.g., `data_loading.py`, `query_execution.py`, `utils.py`).
|
||||
* **Clear Interfaces:** Define clear functions and classes with well-defined inputs and outputs.
|
||||
* **Avoid Global State:** Minimize the use of global variables to improve code testability and maintainability.
|
||||
|
||||
### 1.4. Component Architecture
|
||||
|
||||
* **Data Layer:** Handles data loading, transformation, and storage using DuckDB.
|
||||
* **Logic Layer:** Encapsulates business logic and data processing routines.
|
||||
* **Presentation Layer:** (If applicable) Presents data to users (e.g., through a web application).
|
||||
* **Configuration Layer:** Loads external configurations (e.g., environment variables) that the script needs to run properly.
|
||||
|
||||
### 1.5. Code Splitting Strategies
|
||||
|
||||
* **Split Large SQL Scripts:** Break down complex SQL scripts into smaller, more manageable files.
|
||||
* **Modularize Python Code:** Use functions and classes to create reusable components.
|
||||
* **Separate Configuration:** Store configuration settings (database paths, API keys) in separate files.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1. Design Patterns Specific to DuckDB
|
||||
|
||||
* **Embedded Database:** Use DuckDB as an embedded database for lightweight data analysis and prototyping.
|
||||
* **Data Pipeline:** Build data pipelines with DuckDB for ETL (Extract, Transform, Load) processes.
|
||||
* **Analytical Queries:** Leverage DuckDB's columnar storage and vectorized execution for efficient analytical queries.
|
||||
* **Federated Querying:** Utilize DuckDB's ability to query data from various sources (CSV, Parquet, JSON, HTTP) using a unified SQL interface.
|
||||
|
||||
### 2.2. Recommended Approaches for Common Tasks
|
||||
|
||||
* **Data Loading:**
|
||||
* Use `COPY` command for efficient bulk loading of data from files.
|
||||
* Consider Parquet format for optimal storage and query performance.
|
||||
* Use `read_csv_auto` or `read_parquet` functions.
|
||||
* **Querying:**
|
||||
* Write clear and concise SQL queries.
|
||||
* Use parameterized queries to prevent SQL injection.
|
||||
* Utilize window functions for complex aggregations and ranking.
|
||||
* **Data Transformation:**
|
||||
* Use SQL functions for data cleaning and transformation.
|
||||
* Create views for commonly used data transformations.
|
||||
* **Joining Tables:**
|
||||
* Understand different join types (INNER, LEFT, RIGHT, FULL) and choose the appropriate one.
|
||||
* Ensure join columns are properly indexed for performance.
|
||||
* Use explicit `JOIN` syntax for readability.
|
||||
* **Error Handling:** Implement robust error handling to prevent unexpected crashes.
|
||||
* Utilize `TRY/CATCH` blocks in SQL scripts.
|
||||
* Log errors to files or databases for debugging and monitoring.
|
||||
|
||||
### 2.3. Anti-patterns and Code Smells to Avoid
|
||||
|
||||
* `SELECT *`: Avoid selecting all columns unless necessary. Specify only the columns you need to improve performance.
|
||||
* Nested Subqueries: Excessive use of nested subqueries can impact performance. Consider using `WITH` clauses (Common Table Expressions - CTEs) to improve readability and performance.
|
||||
* Lack of Indexing: Missing indexes on frequently queried columns can lead to slow query performance. Add indexes where appropriate.
|
||||
* Hardcoded Values: Avoid hardcoding values in SQL queries or scripts. Use parameters or configuration files instead.
|
||||
* Ignoring Error Handling: Failing to handle errors gracefully can lead to unexpected application behavior.
|
||||
* Over-complicating Queries: Strive for clarity and simplicity in SQL queries. Break down complex logic into smaller, more manageable steps.
|
||||
* Not closing database connections after usage.
|
||||
|
||||
### 2.4. State Management Best Practices
|
||||
|
||||
* **Minimize State:** Keep the amount of mutable state in your application to a minimum.
|
||||
* **Centralized State:** If state is necessary, manage it in a centralized location (e.g., a configuration file or dedicated state management module).
|
||||
* **Immutable Data:** Prefer immutable data structures whenever possible to avoid unintended side effects.
|
||||
|
||||
### 2.5. Error Handling Patterns
|
||||
|
||||
* **Try-Catch Blocks:** Use `TRY/CATCH` blocks in SQL scripts to handle potential errors.
|
||||
* **Logging:** Log errors to files or databases for debugging and monitoring.
|
||||
* **Custom Error Messages:** Provide informative error messages to help users understand and resolve issues.
|
||||
* **Graceful Degradation:** Design your application to handle errors gracefully and continue functioning (albeit with reduced functionality) if possible.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1. Optimization Techniques
|
||||
|
||||
* **Column Selection:** Use specific column selections instead of `SELECT *` to improve performance.
|
||||
* **Filtering Before Joining:** Optimize queries by filtering data before joining tables.
|
||||
* **Prepared Statements:** Utilize prepared statements for repeated queries to enhance execution speed.
|
||||
* **Indexing:** Create indexes on frequently queried columns to speed up data retrieval.
|
||||
* **Query Plan Analysis:** Use `EXPLAIN ANALYZE` to understand query execution plans and identify bottlenecks.
|
||||
* **Chunking:** Implement chunking for large datasets to manage memory better.
|
||||
* **Data Types:** Use appropriate data types to minimize storage space and improve query performance. Avoid using TEXT for numerical data. Use INTEGER or BIGINT where possible.
|
||||
* **Compression:** DuckDB supports lightweight compression. Consider using persistent databases to take advantage of this.
|
||||
* **Parallelism:** DuckDB parallelizes workload based on row groups. Ensure your data is large enough to benefit from multi-core processing. Manually limit the number of threads if necessary using `SET threads = X`.
|
||||
|
||||
### 3.2. Memory Management
|
||||
|
||||
* **Memory Limits:** Monitor memory usage and set appropriate memory limits.
|
||||
* **Spilling to Disk:** Larger-than-memory workloads are supported by spilling to disk. Configure the temporary directory using `SET temp_directory = '/path/to/temp_dir.tmp/'`.
|
||||
* **Avoid Large Intermediate Results:** Optimize queries to minimize the size of intermediate results.
|
||||
* **`preserve_insertion_order`:** Disable `preserve_insertion_order` for large imports/exports if order is not important (`SET preserve_insertion_order = false`).
|
||||
|
||||
### 3.3. Avoiding Reading Unnecessary Data (Remote Files)
|
||||
|
||||
* **Column Selection:** Avoid `SELECT *`. Only select columns that are actually used.
|
||||
* **Filter Pushdown:** Apply filters on remote parquet files when possible. DuckDB can use these filters to reduce the amount of data that is scanned.
|
||||
* **Sorting/Partitioning:** Either sort or partition data by columns that are regularly used for filters: this increases the effectiveness of the filters in reducing IO.
|
||||
* **Avoid Reading Data More Than Once:** If data needs to be accessed multiple times, store it locally.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1. Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
* **SQL Injection:** Prevent SQL injection by using parameterized queries and avoiding string concatenation in SQL statements.
|
||||
* **Data Exposure:** Protect sensitive data by encrypting it at rest and in transit. Use appropriate access controls to restrict access to sensitive data.
|
||||
* **Denial of Service (DoS):** Limit resource consumption (memory, CPU) to prevent DoS attacks.
|
||||
* **Unauthorized Access:** Implement strong authentication and authorization mechanisms to prevent unauthorized access to the database.
|
||||
|
||||
### 4.2. Input Validation
|
||||
|
||||
* **Validate User Inputs:** Validate all user inputs to prevent malicious data from entering the database. Check data types, ranges, and formats.
|
||||
* **Sanitize Inputs:** Sanitize user inputs to remove potentially harmful characters or code.
|
||||
|
||||
### 4.3. Authentication and Authorization Patterns
|
||||
|
||||
* **Role-Based Access Control (RBAC):** Implement RBAC to grant users only the necessary permissions to access data.
|
||||
* **Least Privilege Principle:** Grant users the minimum level of access required to perform their tasks.
|
||||
* **Secure Connection:** Ensure that connections to the database are encrypted using TLS/SSL.
|
||||
|
||||
### 4.4. Data Protection Strategies
|
||||
|
||||
* **Encryption:** Encrypt sensitive data at rest and in transit.
|
||||
* **Data Masking:** Mask sensitive data in non-production environments to protect user privacy.
|
||||
* **Data Auditing:** Track all data access and modification activities for auditing purposes.
|
||||
* **Regular Backups:** Regularly back up the database to prevent data loss in case of failures.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1. Unit Testing Strategies
|
||||
|
||||
* **Test Individual Components:** Write unit tests to verify the functionality of individual SQL functions, Python modules, or other components.
|
||||
* **Mock Database Connections:** Mock database connections to isolate the code being tested from the actual database.
|
||||
* **Assertion Frameworks:** Use assertion frameworks (e.g., `pytest`, `unittest`) to verify expected results.
|
||||
|
||||
### 5.2. Integration Testing
|
||||
|
||||
* **Test Interactions:** Write integration tests to verify the interactions between different components of the system.
|
||||
* **Real Database:** Use a real DuckDB database for integration tests (preferably a test database).
|
||||
* **Data Validation:** Verify that data is correctly loaded, transformed, and stored in the database.
|
||||
|
||||
### 5.3. End-to-End Testing
|
||||
|
||||
* **Test Complete Workflows:** Write end-to-end tests to verify the functionality of complete workflows from start to finish.
|
||||
* **Simulate User Actions:** Simulate user actions to test the system's behavior under realistic conditions.
|
||||
|
||||
### 5.4. Test Organization
|
||||
|
||||
* **Separate Test Directory:** Create a separate `tests/` directory to store test scripts.
|
||||
* **Organize Tests:** Organize tests into subdirectories based on the component or feature being tested.
|
||||
* **Descriptive Names:** Use descriptive names for test files and functions.
|
||||
|
||||
### 5.5. Mocking and Stubbing
|
||||
|
||||
* **Mock External Dependencies:** Mock external dependencies (e.g., file systems, network connections) to isolate the code being tested.
|
||||
* **Stub Database Interactions:** Stub database interactions to control the behavior of the database during testing.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1. Frequent Mistakes Developers Make
|
||||
|
||||
* **Not Using Indexes:** Forgetting to create indexes on frequently queried columns.
|
||||
* **Incorrect Join Types:** Using the wrong join type (e.g., INNER instead of LEFT).
|
||||
* **SQL Injection Vulnerabilities:** Failing to prevent SQL injection attacks.
|
||||
* **Memory Leaks:** Not properly closing database connections or releasing resources.
|
||||
* **Lack of Error Handling:** Ignoring potential errors in SQL scripts or Python code.
|
||||
|
||||
### 6.2. Edge Cases to Be Aware Of
|
||||
|
||||
* **Null Values:** Handle null values correctly in SQL queries and data transformations.
|
||||
* **Empty Datasets:** Test the system's behavior with empty datasets.
|
||||
* **Large Datasets:** Test the system's behavior with large datasets to ensure performance.
|
||||
* **Concurrency:** Consider potential concurrency issues when multiple users or processes access the database simultaneously.
|
||||
|
||||
### 6.3. Version-Specific Issues
|
||||
|
||||
* **Check Release Notes:** Review the release notes for each new version of DuckDB to identify any breaking changes or known issues.
|
||||
* **Compatibility Testing:** Perform compatibility testing to ensure that the application works correctly with different versions of DuckDB.
|
||||
|
||||
### 6.4. Compatibility Concerns
|
||||
|
||||
* **Operating System:** Ensure that the application is compatible with the target operating system (Windows, macOS, Linux).
|
||||
* **Programming Language:** Ensure that the application is compatible with the programming language being used (Python, Java, etc.).
|
||||
* **Database Drivers:** Use compatible database drivers.
|
||||
|
||||
### 6.5. Debugging Strategies
|
||||
|
||||
* **Logging:** Add logging statements to the code to track execution flow and variable values.
|
||||
* **Print Statements:** Use print statements to display intermediate results and debug issues.
|
||||
* **Debuggers:** Use debuggers (e.g., `pdb` in Python) to step through the code and inspect variables.
|
||||
* **Query Plan Analysis:** Use `EXPLAIN ANALYZE` to understand query execution plans and identify bottlenecks.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1. Recommended Development Tools
|
||||
|
||||
* **Text Editor/IDE:** VSCode, Sublime Text, IntelliJ IDEA, etc.
|
||||
* **Database Client:** DBeaver, DataGrip, SQL Developer, DuckDB CLI.
|
||||
* **Version Control:** Git.
|
||||
* **Virtual Environment Manager:** `venv` (Python), Conda.
|
||||
* **Task Runner:** Make, Invoke (Python).
|
||||
|
||||
### 7.2. Build Configuration
|
||||
|
||||
* **Dependency Management:** Use a dependency management tool (e.g., `pip` for Python) to manage project dependencies.
|
||||
* **Configuration Files:** Use configuration files (e.g., `config.ini`, `settings.json`) to store project settings and parameters.
|
||||
|
||||
### 7.3. Linting and Formatting
|
||||
|
||||
* **Linters:** Use linters (e.g., `flake8`, `pylint` for Python, `sqlfluff` for SQL) to enforce code style and identify potential errors.
|
||||
* **Formatters:** Use formatters (e.g., `black` for Python, `sqlformat` for SQL) to automatically format code according to a defined style.
|
||||
|
||||
### 7.4. Deployment Best Practices
|
||||
|
||||
* **Containerization:** Use containerization (e.g., Docker) to package the application and its dependencies into a single unit.
|
||||
* **Infrastructure as Code (IaC):** Use IaC tools (e.g., Terraform, CloudFormation) to automate the provisioning and management of infrastructure.
|
||||
* **Configuration Management:** Use configuration management tools (e.g., Ansible, Chef, Puppet) to automate the configuration of servers and applications.
|
||||
|
||||
### 7.5. CI/CD Integration
|
||||
|
||||
* **Continuous Integration (CI):** Integrate automated testing into the CI pipeline to ensure code quality.
|
||||
* **Continuous Delivery (CD):** Automate the deployment process to ensure frequent and reliable releases.
|
||||
@@ -0,0 +1,148 @@
|
||||
---
|
||||
description: Comprehensive best practices for developing with MongoDB, covering schema design, code organization, performance optimization, security considerations, and testing strategies. This rule provides actionable guidance to help developers build robust and scalable MongoDB applications.
|
||||
globs: **/*.{js,ts,mongodb}
|
||||
---
|
||||
- **Understand Schema Differences Between Relational and Document-based Databases:** Recognize that MongoDB's document-oriented model differs significantly from relational databases. Design schemas that reflect the relationships within the data itself, rather than relying on joins.
|
||||
- **Embed Your Data Instead of Relying on Joins:** Favor embedding related data within a single document to minimize the need for costly join operations. This approach can significantly improve read performance.
|
||||
- **Use Indexes For Frequent Operations:** Create indexes on fields that are frequently queried to optimize performance. Carefully consider the types of queries your application will perform and create indexes accordingly. Compound indexes are beneficial for queries involving multiple fields.
|
||||
- **Properly Size Your Servers:** Ensure that your MongoDB server resources are adequately sized for your workload. Monitor resource utilization and scale as needed to maintain optimal performance. Consider CPU, memory, and disk I/O.
|
||||
- **Use Replication or Sharding:** Implement replication or sharding to enhance scalability and reliability. Replication provides data redundancy and high availability, while sharding distributes data across multiple servers to handle larger datasets and higher traffic volumes.
|
||||
|
||||
### 1. Code Organization and Structure:
|
||||
|
||||
- **Directory Structure Best Practices:**
|
||||
- `config/`: Contains configuration files for database connections, authentication, and other settings.
|
||||
- `models/`: Defines data models using Mongoose or other ODM libraries. Each model represents a MongoDB collection.
|
||||
- `routes/`: Handles API endpoints and routes for interacting with the database.
|
||||
- `controllers/`: Implements the logic for handling requests, interacting with models, and returning responses.
|
||||
- `services/`: Contains reusable business logic related to data access and manipulation.
|
||||
- `utils/`: Provides utility functions for common tasks such as validation, formatting, and error handling.
|
||||
- `tests/`: Includes unit, integration, and end-to-end tests.
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive names that reflect the purpose of the file (e.g., `user.model.js`, `auth.controller.ts`, `product.service.js`).
|
||||
- Follow a consistent naming convention across the project (e.g., camelCase or snake_case).
|
||||
- **Module Organization:**
|
||||
- Organize code into modules based on functionality or domain (e.g., `user` module, `product` module).
|
||||
- Use ES modules or CommonJS modules to encapsulate code and manage dependencies.
|
||||
- **Component Architecture:**
|
||||
- Design reusable components for common tasks such as data validation, error handling, and authentication.
|
||||
- Follow the principles of separation of concerns and single responsibility.
|
||||
- **Code Splitting Strategies:**
|
||||
- Implement lazy loading of modules or components to improve initial load time.
|
||||
- Use code splitting to break down large bundles into smaller chunks.
|
||||
|
||||
### 2. Common Patterns and Anti-patterns:
|
||||
|
||||
- **Design Patterns Specific to MongoDB:**
|
||||
- **Embedded Document Pattern:** Embed related data within a single document to minimize the need for joins.
|
||||
- **Polymorphic Pattern:** Store different types of documents in the same collection using a common base schema and discriminator fields.
|
||||
- **Bucket Pattern:** Group data into buckets based on time or other criteria for efficient querying and aggregation.
|
||||
- **Recommended Approaches for Common Tasks:**
|
||||
- Use Mongoose or other ODM libraries to simplify data modeling and validation.
|
||||
- Implement pagination for large result sets.
|
||||
- Use aggregation pipelines for complex queries and data transformations.
|
||||
- **Anti-patterns and Code Smells to Avoid:**
|
||||
- **Over-indexing:** Creating too many indexes can degrade write performance.
|
||||
- **Ignoring Performance:** Neglecting to analyze query performance can lead to slow response times.
|
||||
- **Schema Violations:** Allowing inconsistent data to be stored in collections can cause unexpected errors.
|
||||
- **State Management Best Practices:**
|
||||
- Use a state management library such as Redux or Zustand to manage application state.
|
||||
- Store state in a centralized store to ensure consistency and predictability.
|
||||
- **Error Handling Patterns:**
|
||||
- Implement robust error handling to catch and handle exceptions gracefully.
|
||||
- Use try-catch blocks to handle potential errors.
|
||||
- Log errors for debugging and monitoring.
|
||||
|
||||
### 3. Performance Considerations:
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- Use indexes to optimize query performance.
|
||||
- Avoid using `$where` operator, as it can be slow.
|
||||
- Use projection to retrieve only the necessary fields.
|
||||
- **Memory Management:**
|
||||
- Monitor memory usage and identify potential memory leaks.
|
||||
- Use connection pooling to reuse database connections.
|
||||
- **Rendering Optimization:** (If applicable for UI-based apps using MongoDB data)
|
||||
- Implement virtualization for large lists.
|
||||
- Use memoization to avoid unnecessary re-renders.
|
||||
- **Bundle Size Optimization:** (If applicable)
|
||||
- Minify and compress JavaScript and CSS files.
|
||||
- Remove unused code.
|
||||
- **Lazy Loading Strategies:** (If applicable)
|
||||
- Lazy load images and other resources.
|
||||
- Use code splitting to load modules on demand.
|
||||
|
||||
### 4. Security Best Practices:
|
||||
|
||||
- **Common Vulnerabilities and How to Prevent Them:**
|
||||
- **NoSQL Injection:** Sanitize user inputs to prevent injection attacks.
|
||||
- **Authentication Bypass:** Implement strong authentication and authorization mechanisms.
|
||||
- **Data Exposure:** Protect sensitive data by encrypting it and controlling access.
|
||||
- **Input Validation:**
|
||||
- Validate all user inputs to prevent malicious data from being stored in the database.
|
||||
- Use a validation library such as Joi or Yup to define validation schemas.
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- Use a secure authentication protocol such as OAuth 2.0 or JWT.
|
||||
- Implement role-based access control (RBAC) to restrict access to sensitive data and functionality.
|
||||
- **Data Protection Strategies:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use data masking to protect personally identifiable information (PII).
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS to encrypt communication between the client and server.
|
||||
- Implement rate limiting to prevent abuse.
|
||||
|
||||
### 5. Testing Approaches:
|
||||
|
||||
- **Unit Testing Strategies:**
|
||||
- Write unit tests to verify the functionality of individual modules and components.
|
||||
- Use a testing framework such as Jest or Mocha.
|
||||
- **Integration Testing:**
|
||||
- Write integration tests to verify the interaction between different modules and components.
|
||||
- Test the integration between the application and the database.
|
||||
- **End-to-End Testing:**
|
||||
- Write end-to-end tests to verify the functionality of the entire application.
|
||||
- Use a testing framework such as Cypress or Playwright.
|
||||
- **Test Organization:**
|
||||
- Organize tests into separate directories based on functionality or module.
|
||||
- Use descriptive names for test files and test cases.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking and stubbing to isolate units of code during testing.
|
||||
- Use a mocking library such as Sinon or Jest's built-in mocking.
|
||||
|
||||
### 6. Common Pitfalls and Gotchas:
|
||||
|
||||
- **Frequent Mistakes Developers Make:**
|
||||
- **Not Understanding MongoDB's Query Language:** Failing to grasp the nuances of MongoDB's query language can lead to inefficient queries.
|
||||
- **Ignoring Indexes:** Neglecting to create indexes on frequently queried fields can significantly impact performance.
|
||||
- **Not Handling Errors Properly:** Failing to handle errors gracefully can lead to unexpected application behavior.
|
||||
- **Edge Cases to Be Aware Of:**
|
||||
- **Data Type Mismatches:** Ensure that data types are consistent across the application and the database.
|
||||
- **Concurrency Issues:** Handle concurrency issues carefully to prevent data corruption.
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of compatibility issues between different versions of MongoDB and related libraries.
|
||||
- Consult the documentation for the specific version you are using.
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure that the application is compatible with different operating systems and browsers.
|
||||
- Test the application on different devices and screen sizes.
|
||||
- **Debugging Strategies:**
|
||||
- Use logging to track the execution flow and identify potential issues.
|
||||
- Use a debugger to step through the code and inspect variables.
|
||||
|
||||
### 7. Tooling and Environment:
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- **MongoDB Compass:** A GUI tool for exploring and managing MongoDB databases.
|
||||
- **MongoDB Shell:** A command-line interface for interacting with MongoDB.
|
||||
- **VS Code Extension for MongoDB:** Provides syntax highlighting, code completion, and other features for MongoDB development.
|
||||
- **Build Configuration:**
|
||||
- Use a build tool such as Webpack or Parcel to bundle and optimize the application.
|
||||
- Configure the build tool to minify and compress JavaScript and CSS files.
|
||||
- **Linting and Formatting:**
|
||||
- Use a linter such as ESLint to enforce coding standards.
|
||||
- Use a formatter such as Prettier to automatically format code.
|
||||
- **Deployment Best Practices:**
|
||||
- Use a containerization technology such as Docker to package the application and its dependencies.
|
||||
- Deploy the application to a cloud platform such as AWS, Azure, or Google Cloud.
|
||||
- **CI/CD Integration:**
|
||||
- Integrate the application with a CI/CD pipeline to automate the build, test, and deployment process.
|
||||
- Use a CI/CD tool such as Jenkins, Travis CI, or CircleCI.
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
description: This rule provides best practices for working with Redis, covering code organization, performance, security, testing, and common pitfalls to ensure efficient and reliable usage. It applies to any language file interacting with Redis.
|
||||
globs: **/*.{py,js,go,java,c,cpp,rb,php,ts,rs,kt,scala}
|
||||
---
|
||||
- **General Best Practices**
|
||||
- Follow official Redis documentation and community best practices.
|
||||
- Use the most recent stable version of the Redis client library for your language.
|
||||
- Regularly update the Redis server and client libraries to benefit from bug fixes, performance improvements, and security patches.
|
||||
|
||||
- **Connection Management**
|
||||
- **Connection Pooling:** Use connection pooling to reduce the overhead of creating new connections for each operation. This significantly improves performance, especially in high-traffic scenarios.
|
||||
- **Connection Timeout:** Configure appropriate connection timeouts to prevent indefinite blocking in case of network issues.
|
||||
- **Retry Logic:** Implement retry logic with exponential backoff for transient connection errors.
|
||||
- **Secure Connections:** When connecting to a remote Redis instance, always use TLS/SSL encryption (redis+ssl://) to protect data in transit, especially when dealing with sensitive information. Ensure proper certificate validation.
|
||||
|
||||
- **Data Modeling and Serialization**
|
||||
- **Key Naming:** Use consistent and meaningful key naming conventions. Consider using namespaces or prefixes to organize keys and avoid collisions.
|
||||
- **Data Serialization:** Choose an efficient serialization format (e.g., JSON, Protocol Buffers, MessagePack) and use it consistently. Consider the trade-offs between human readability, storage space, and serialization/deserialization performance.
|
||||
- **Smaller Values:** Redis works best with smaller values. Break larger data structures into smaller chunks and distribute them across multiple keys. This improves memory utilization and performance.
|
||||
- **Data Types:** Leverage Redis's rich data types (strings, lists, sets, sorted sets, hashes, streams) effectively to optimize data storage and operations. Choose the data type that best suits the use case.
|
||||
|
||||
- **Command Usage**
|
||||
- **Transactions:** Use transactions (`MULTI`, `EXEC`, `DISCARD`, `WATCH`) to ensure atomicity when performing multiple operations. Be aware of the limitations of Redis transactions (no rollback on individual command failure).
|
||||
- **Pipelines:** Use pipelines to batch multiple commands together and reduce network round-trip time. This dramatically improves performance for bulk operations.
|
||||
- **Lua Scripting:** Use Lua scripting for complex operations that require atomicity and server-side processing. This reduces network traffic and improves performance compared to executing multiple individual commands.
|
||||
- **Avoid Blocking Commands:** Avoid using blocking commands like `KEYS`, `FLUSHALL`, `FLUSHDB`, `SORT` without `LIMIT` in production environments. These commands can block the Redis server and degrade performance.
|
||||
- **Use SCAN:** Instead of `KEYS`, use the `SCAN` command for iterating over keys in a non-blocking manner. This allows the Redis server to continue serving other requests while iterating.
|
||||
- **Efficient Deletion:** Instead of `FLUSHALL` or `FLUSHDB`, use `SCAN` with `DEL` to delete keys in batches, minimizing disruption to the server.
|
||||
- **TTL Management:** Set appropriate Time-To-Live (TTL) values for keys to automatically expire data that is no longer needed. This helps manage memory usage and prevent data from becoming stale.
|
||||
|
||||
- **Memory Management**
|
||||
- **Maxmemory:** Configure the `maxmemory` directive to limit the amount of memory Redis can use. When the limit is reached, Redis will evict keys based on the configured eviction policy.
|
||||
- **Eviction Policies:** Choose an appropriate eviction policy (e.g., `LRU`, `LFU`, `volatile-ttl`) based on your application's needs. Understand the trade-offs between different eviction policies.
|
||||
- **Memory Fragmentation:** Monitor memory fragmentation and consider restarting Redis periodically to defragment memory. The `INFO memory` command provides information about memory usage and fragmentation.
|
||||
|
||||
- **Performance Monitoring and Tuning**
|
||||
- **Redis Monitor:** Use the `MONITOR` command (with caution in production) to observe real-time commands being executed on the server. This can help identify performance bottlenecks.
|
||||
- **Redis Slow Log:** Configure the Redis slow log to record commands that take longer than a specified amount of time to execute. Analyze the slow log to identify performance issues.
|
||||
- **INFO Command:** Use the `INFO` command to gather information about the Redis server, including memory usage, CPU usage, and client connections. This information can be used to monitor performance and identify potential problems.
|
||||
- **Latency Monitoring:** Monitor Redis latency using tools like `redis-cli --latency` or dedicated monitoring solutions. High latency can indicate performance issues.
|
||||
|
||||
- **Security Considerations**
|
||||
- **Authentication:** Enable authentication using the `requirepass` directive to protect the Redis server from unauthorized access. Use a strong password.
|
||||
- **Access Control Lists (ACLs):** Use ACLs to restrict access to specific commands and keys for different users. This provides fine-grained control over access to Redis data.
|
||||
- **Network Security:** Restrict network access to the Redis server using firewalls or other network security measures. Only allow connections from trusted sources.
|
||||
- **Disable Unsafe Commands:** Disable or rename potentially dangerous commands like `FLUSHALL`, `FLUSHDB`, `KEYS`, `EVAL` using the `rename-command` directive. This reduces the risk of accidental or malicious misuse.
|
||||
- **Regular Audits:** Conduct regular security audits of the Redis configuration and usage patterns to identify and address potential vulnerabilities.
|
||||
- **Input Validation:** Always validate and sanitize any data being stored in Redis to prevent injection attacks.
|
||||
|
||||
- **Testing Strategies**
|
||||
- **Unit Tests:** Write unit tests to verify the functionality of your code that interacts with Redis. Use mocking or stubbing to isolate the Redis interactions from the rest of the code.
|
||||
- **Integration Tests:** Write integration tests to verify the interaction between your code and the Redis server. Use a dedicated test Redis instance for integration tests.
|
||||
- **End-to-End Tests:** Write end-to-end tests to verify the entire application flow, including the interaction with Redis. This ensures that the application works correctly in a realistic environment.
|
||||
- **Data Population:** When testing, consider populating your redis database with a representative set of data.
|
||||
- **Test Organization:** Organize tests logically, separating unit, integration, and end-to-end tests into different directories or modules.
|
||||
- **Mocking and Stubbing:** Use mocking and stubbing frameworks to simulate Redis behavior during unit tests.
|
||||
|
||||
- **Code Organization and Structure**
|
||||
- **Dedicated Module:** Create a dedicated module or class to encapsulate all Redis-related operations. This promotes code reuse and maintainability.
|
||||
- **Configuration Management:** Store Redis connection parameters (host, port, password) in a configuration file or environment variables. This makes it easy to change the Redis configuration without modifying code.
|
||||
- **Abstraction Layer:** Consider creating an abstraction layer on top of the Redis client library to provide a higher-level API for your application. This can improve code readability and make it easier to switch to a different Redis client library in the future.
|
||||
|
||||
- **Common Pitfalls and Gotchas**
|
||||
- **N+1 Problem:** Avoid the N+1 problem when retrieving data from Redis. Instead of making multiple individual requests, use pipelining or Lua scripting to retrieve the data in a single request.
|
||||
- **Race Conditions:** Be aware of potential race conditions when updating data in Redis. Use transactions or Lua scripting to ensure atomicity.
|
||||
- **Large Values:** Avoid storing extremely large values in Redis. This can lead to performance issues and memory exhaustion.
|
||||
- **Key Expiration:** Be careful when using key expiration (TTL). If keys expire unexpectedly, it can lead to data loss or inconsistent application behavior.
|
||||
- **Blocking Operations in Event Loops:** Do not perform blocking Redis operations directly in event loops or GUI threads. Use asynchronous operations instead to avoid blocking the main thread.
|
||||
|
||||
- **Tooling and Environment**
|
||||
- **Redis CLI:** Use the Redis CLI (`redis-cli`) for interacting with the Redis server, executing commands, and monitoring performance.
|
||||
- **Redis Desktop Manager:** Use a Redis desktop manager (e.g., RedisInsight, Medis) for visualizing data, managing keys, and monitoring the Redis server.
|
||||
- **Linting and Formatting:** Configure linters and formatters to enforce consistent code style and best practices in your Redis-related code.
|
||||
- **CI/CD Integration:** Integrate Redis testing and deployment into your CI/CD pipeline to automate the testing and deployment process.
|
||||
- **Monitoring Tools:** Utilize monitoring tools like Prometheus, Grafana, or Datadog to monitor Redis performance and health in production environments.
|
||||
@@ -0,0 +1,107 @@
|
||||
---
|
||||
description: Enforces PostgreSQL coding standards, best practices, and performance optimization techniques to ensure maintainable, efficient, and secure database interactions. This rule covers code formatting, data integrity, security, and performance considerations.
|
||||
globs: **/*.{sql,plpgsql,c,h}
|
||||
---
|
||||
- **Code Formatting and Comments:**
|
||||
- Maintain consistent code formatting using a tool like `pgformatter` or similar.
|
||||
- Use clear and concise comments to explain complex logic and intentions. Update comments regularly to avoid confusion.
|
||||
- Use inline comments sparingly; prefer block comments for detailed explanations.
|
||||
- Write comments in plain, easy-to-follow English.
|
||||
- Add a space after line comments (`-- a comment`); do not add a space for commented-out code (`--raise notice`).
|
||||
- Keep comments up-to-date; incorrect comments are worse than no comments.
|
||||
|
||||
- **Naming Conventions:**
|
||||
- Use `snake_case` for identifiers (e.g., `user_id`, `customer_name`).
|
||||
- Use plural nouns for table names (e.g., `customers`, `products`).
|
||||
- Use consistent naming conventions for functions, procedures, and triggers.
|
||||
- Choose descriptive and meaningful names for all database objects.
|
||||
|
||||
- **Data Integrity and Data Types:**
|
||||
- Use appropriate data types for columns to ensure data integrity (e.g., `INTEGER`, `VARCHAR`, `TIMESTAMP`).
|
||||
- Use constraints (e.g., `NOT NULL`, `UNIQUE`, `CHECK`, `FOREIGN KEY`) to enforce data integrity.
|
||||
- Define primary keys for all tables.
|
||||
- Use foreign keys to establish relationships between tables.
|
||||
- Utilize domains to enforce data type constraints reusable across multiple columns.
|
||||
|
||||
- **SQL Injection Prevention:**
|
||||
- Always use parameterized queries or prepared statements to prevent SQL injection attacks.
|
||||
- Sanitize user inputs before using them in SQL queries.
|
||||
- Avoid constructing SQL queries by concatenating strings directly.
|
||||
- Use the `quote_literal()` and `quote_ident()` functions to properly escape strings and identifiers.
|
||||
|
||||
- **Transaction Management:**
|
||||
- Use explicit transactions to ensure data consistency and atomicity.
|
||||
- Start transactions with `BEGIN;` and end them with `COMMIT;` or `ROLLBACK;`.
|
||||
- Handle transaction errors properly to prevent data corruption.
|
||||
- Use savepoints to allow partial rollbacks within a transaction.
|
||||
|
||||
- **Indexing:**
|
||||
- Create indexes on columns frequently used in `WHERE` clauses and `JOIN` conditions.
|
||||
- Avoid over-indexing, as it can slow down write operations.
|
||||
- Consider using partial indexes for specific query patterns.
|
||||
- Use appropriate index types (e.g., `B-tree`, `Hash`, `GIN`, `GiST`) based on the data and query requirements.
|
||||
- Regularly analyze and maintain indexes using `ANALYZE` and `VACUUM`.
|
||||
|
||||
- **Query Optimization:**
|
||||
- Use `EXPLAIN ANALYZE` to analyze query execution plans and identify performance bottlenecks.
|
||||
- Avoid using `SELECT *` and specify only the necessary columns.
|
||||
- Use `JOIN` operations instead of subqueries where possible.
|
||||
- Optimize `WHERE` clauses to reduce the number of rows processed.
|
||||
- Consider using materialized views for frequently executed, complex queries.
|
||||
- Rewrite slow performing queries with more efficient alternatives.
|
||||
|
||||
- **PL/pgSQL Best Practices:**
|
||||
- Keep PL/pgSQL functions and procedures short and focused.
|
||||
- Use exception handling to gracefully handle errors.
|
||||
- Use `RAISE NOTICE`, `RAISE WARNING`, and `RAISE EXCEPTION` for logging and error reporting.
|
||||
- Avoid using cursors unless absolutely necessary; prefer set-based operations.
|
||||
- Use the `STRICT` attribute to ensure that a function returns a value.
|
||||
|
||||
- **Security Best Practices:**
|
||||
- Grant the least privileges necessary to database users.
|
||||
- Use roles to manage permissions.
|
||||
- Regularly audit database activity.
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use the `SECURITY DEFINER` attribute for functions that require elevated privileges.
|
||||
- Configure appropriate authentication mechanisms (e.g., `SCRAM-SHA-256`).
|
||||
|
||||
- **Connection Management:**
|
||||
- Use connection pooling to reduce the overhead of establishing new connections.
|
||||
- Close connections when they are no longer needed.
|
||||
- Configure connection timeouts to prevent idle connections from consuming resources.
|
||||
|
||||
- **Backup and Recovery:**
|
||||
- Implement a robust backup and recovery strategy.
|
||||
- Regularly back up the database.
|
||||
- Test the recovery process to ensure it works as expected.
|
||||
- Consider using replication for high availability.
|
||||
|
||||
- **Code Organization and Structure:**
|
||||
- Organize database objects into schemas based on functionality or application modules.
|
||||
- Use version control for database scripts and migrations.
|
||||
- Follow a consistent directory structure for database-related files.
|
||||
|
||||
- **Common Pitfalls and Gotchas:**
|
||||
- Avoid using reserved keywords as identifiers.
|
||||
- Be aware of the limitations of data types (e.g., maximum length of `VARCHAR` columns).
|
||||
- Handle null values carefully.
|
||||
- Test database changes thoroughly before deploying them to production.
|
||||
|
||||
- **Tooling and Environment:**
|
||||
- Use a code editor with SQL syntax highlighting and autocompletion.
|
||||
- Use a database client tool for querying and managing the database (e.g., `pgAdmin`, `DBeaver`, `psql`).
|
||||
- Use a version control system (e.g., Git) to manage database scripts and migrations.
|
||||
- Use a CI/CD pipeline to automate database deployments.
|
||||
|
||||
- **C Coding Standards (When Extending PostgreSQL):**
|
||||
- Adhere to the C99 standard. Only use language features available in the C99 standard.
|
||||
- Follow PostgreSQL's source code conventions ([PostgreSQL Documentation](https://www.postgresql.org/docs/current/source-conventions.html)).
|
||||
- Manage memory carefully; avoid memory leaks.
|
||||
- Properly handle errors and exceptions.
|
||||
- Document code thoroughly.
|
||||
|
||||
- **Use Case specific optimizations:**
|
||||
- Time series data: Consider timescaledb extension
|
||||
- Geospatial data: Consider postgis extension
|
||||
|
||||
@file ./rules/postgresql_security_rules.mdc
|
||||
@@ -0,0 +1,190 @@
|
||||
---
|
||||
description: Enforces Prisma best practices for schema design, data access, and application security. Provides guidelines for writing efficient, secure, and maintainable Prisma applications.
|
||||
globs: **/*.prisma
|
||||
---
|
||||
- **General Principles:**
|
||||
- **Never expose the raw Prisma client directly in APIs.** Instead, create abstraction layers (e.g., repositories or services) to handle data access logic. This protects you from accidentally exposing sensitive database details and allows you to easily change your data access implementation in the future.
|
||||
- **Always use input validation** before performing any database operations. Use a validation library like Zod or Yup to ensure that user input conforms to your expected schema and data types. This helps prevent injection attacks and data corruption.
|
||||
- **Implement row-level security (RLS) where applicable.** If your application handles sensitive data, use Prisma policies or database-level RLS to restrict data access based on user roles or permissions. Carefully design your policies to prevent unauthorized data access.
|
||||
- **Sanitize and validate all user inputs** to prevent injection attacks, such as SQL injection. Use Prisma's built-in features to escape user input and prevent it from being interpreted as code.
|
||||
|
||||
- **Code Organization and Structure:**
|
||||
- **Directory Structure:**
|
||||
- `prisma/`: Contains the `schema.prisma` file and any seed scripts or migrations.
|
||||
- `src/`: Contains the main application code.
|
||||
- `src/lib/prisma.ts`: A single module that exports an instance of the Prisma client. This promotes reuse and simplifies dependency injection.
|
||||
- `src/models/`: Database model definitions as classes, abstracting Prisma calls.
|
||||
- `src/repositories/`: Contains data access logic, abstracting Prisma queries.
|
||||
- `src/services/`: Contains business logic, orchestrating data access through repositories.
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive names for files and directories that reflect their purpose.
|
||||
- Use consistent naming conventions (e.g., camelCase for variables, PascalCase for components).
|
||||
- **Module Organization:**
|
||||
- Organize code into logical modules with clear responsibilities.
|
||||
- Use dependency injection to decouple modules and improve testability.
|
||||
- **Component Architecture:**
|
||||
- Design components that are reusable, testable, and maintainable.
|
||||
- Follow the single responsibility principle for each component.
|
||||
- **Code Splitting Strategies:**
|
||||
- Use dynamic imports to load code on demand and reduce initial bundle size.
|
||||
- Split code based on routes, features, or user roles.
|
||||
|
||||
- **Common Patterns and Anti-patterns:**
|
||||
- **Design Patterns:**
|
||||
- **Repository Pattern:** Abstract data access logic behind repositories.
|
||||
- **Service Layer Pattern:** Encapsulate business logic in service classes.
|
||||
- **Unit of Work Pattern:** Manage transactions across multiple repositories.
|
||||
- **Recommended Approaches:**
|
||||
- Use Prisma's relation features to model complex relationships between entities.
|
||||
- Use Prisma's transaction features to ensure data consistency.
|
||||
- Use Prisma's filtering and sorting options to optimize queries.
|
||||
- **Anti-patterns:**
|
||||
- **Exposing the Prisma client directly to the client-side.** This is a major security risk.
|
||||
- **Writing complex queries directly in components.** Move query logic to repositories or services.
|
||||
- **Ignoring error handling.** Always handle potential errors when interacting with the database.
|
||||
- **State Management:**
|
||||
- Consider using a state management library like Redux, Zustand, or Jotai for complex applications.
|
||||
- Use server-side data fetching for initial data loading and hydration.
|
||||
- **Error Handling:**
|
||||
- Use try-catch blocks to handle potential errors when interacting with the database.
|
||||
- Log errors to a centralized logging system for monitoring and debugging.
|
||||
- Return meaningful error messages to the client-side.
|
||||
|
||||
- **Performance Considerations:**
|
||||
- **Optimization Techniques:**
|
||||
- Use Prisma's connection pooling to reduce database connection overhead.
|
||||
- Use Prisma's batching features to reduce the number of database roundtrips.
|
||||
- Optimize database queries by using indexes and filtering data on the server-side.
|
||||
- **Memory Management:**
|
||||
- Avoid loading large amounts of data into memory at once. Use pagination or streaming to process data in smaller chunks.
|
||||
- Clean up resources after use, such as database connections and file handles.
|
||||
- **Rendering Optimization:**
|
||||
- Use virtualization for large lists or tables.
|
||||
- Optimize images and other assets.
|
||||
- **Bundle Size Optimization:**
|
||||
- Use code splitting to reduce the initial bundle size.
|
||||
- Remove unused code and dependencies.
|
||||
- **Lazy Loading Strategies:**
|
||||
- Load data on demand when it is needed.
|
||||
- Use placeholders or skeletons to improve the user experience during loading.
|
||||
|
||||
- **Security Best Practices:**
|
||||
- **Common Vulnerabilities:**
|
||||
- SQL injection: Prevented by using Prisma's prepared statements and escaping user input.
|
||||
- Cross-site scripting (XSS): Prevented by sanitizing user input and output.
|
||||
- Cross-site request forgery (CSRF): Prevented by using CSRF tokens.
|
||||
- **Input Validation:**
|
||||
- Use a validation library to validate all user input.
|
||||
- Validate data types, lengths, and formats.
|
||||
- **Authentication and Authorization:**
|
||||
- Use a secure authentication library like NextAuth.js or Clerk.
|
||||
- Implement role-based access control (RBAC) to restrict access to sensitive data and functionality.
|
||||
- **Data Protection:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use HTTPS to secure communication between the client and server.
|
||||
- **Secure API Communication:**
|
||||
- Use API keys or tokens to authenticate API requests.
|
||||
- Rate limit API requests to prevent abuse.
|
||||
|
||||
- **Testing Approaches:**
|
||||
- **Unit Testing:**
|
||||
- Test individual components and functions in isolation.
|
||||
- Use mocking and stubbing to isolate components from external dependencies.
|
||||
- **Integration Testing:**
|
||||
- Test the interaction between different components and modules.
|
||||
- Test database interactions using a test database.
|
||||
- **End-to-End Testing:**
|
||||
- Test the entire application from end to end.
|
||||
- Use a testing framework like Cypress or Playwright.
|
||||
- **Test Organization:**
|
||||
- Organize tests into logical suites based on functionality.
|
||||
- Use descriptive names for tests.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking to replace external dependencies with test doubles.
|
||||
- Use stubbing to control the behavior of dependencies.
|
||||
|
||||
- **Common Pitfalls and Gotchas:**
|
||||
- **Frequent Mistakes:**
|
||||
- Forgetting to handle errors when interacting with the database.
|
||||
- Exposing the Prisma client directly to the client-side.
|
||||
- Writing complex queries directly in components.
|
||||
- **Edge Cases:**
|
||||
- Handling large datasets.
|
||||
- Dealing with concurrency issues.
|
||||
- Managing database migrations.
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of breaking changes between Prisma versions.
|
||||
- Use version control to manage dependencies.
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure that your code is compatible with different browsers and devices.
|
||||
- Test your application on different environments.
|
||||
- **Debugging Strategies:**
|
||||
- Use logging to track down errors.
|
||||
- Use a debugger to step through code.
|
||||
- Use Prisma's query logging feature to inspect database queries.
|
||||
|
||||
- **Tooling and Environment:**
|
||||
- **Recommended Development Tools:**
|
||||
- VS Code with the Prisma extension.
|
||||
- Prisma Studio for visualizing and managing data.
|
||||
- Docker for containerizing the application.
|
||||
- **Build Configuration:**
|
||||
- Use a build tool like Webpack, Parcel, or esbuild to bundle and optimize code.
|
||||
- Configure the build tool to generate production-ready code.
|
||||
- **Linting and Formatting:**
|
||||
- Use ESLint and Prettier to enforce code style and prevent errors.
|
||||
- Configure the linter and formatter to use consistent settings across the project.
|
||||
- **Deployment Best Practices:**
|
||||
- Use a CI/CD pipeline to automate deployments.
|
||||
- Deploy to a cloud platform like Vercel, Netlify, or AWS.
|
||||
- **CI/CD Integration:**
|
||||
- Integrate with CI/CD tools like GitHub Actions, GitLab CI, or CircleCI.
|
||||
- Run tests and linters as part of the CI/CD pipeline.
|
||||
|
||||
- **Specific Prisma Configuration:**
|
||||
- **Schema Design:**
|
||||
- Use clear and concise names for models and fields.
|
||||
- Define relationships between models using Prisma's relation features.
|
||||
- Use indexes to optimize query performance.
|
||||
- Consider using enums for fields with a limited set of values.
|
||||
- Properly use `@id`, `@unique`, and `@relation` directives for optimal schema design.
|
||||
- **Data Types:**
|
||||
- Use the appropriate data types for each field.
|
||||
- Use `DateTime` for storing timestamps.
|
||||
- Use `Json` for storing complex data structures.
|
||||
- **Prisma Client Generation:**
|
||||
- Ensure your `.env` file is correctly configured for database connection.
|
||||
- Regularly update the Prisma client to the latest version.
|
||||
- Use `prisma generate` to generate the client after schema changes.
|
||||
|
||||
- **Query Optimization:**
|
||||
- **Select only the necessary fields** to reduce the amount of data transferred from the database.
|
||||
- **Use `include` and `select` carefully** to optimize the query shape.
|
||||
- **Avoid N+1 queries** by using Prisma's `include` or `join` features.
|
||||
- **Use pagination** to limit the number of results returned by a query.
|
||||
- **Use `take` and `skip`** for efficient pagination.
|
||||
|
||||
- **Transaction Management:**
|
||||
- **Use Prisma's `prisma.$transaction` method** to ensure atomicity of database operations.
|
||||
- **Handle potential errors** within the transaction to prevent data inconsistency.
|
||||
- **Keep transactions short** to minimize the impact on database performance.
|
||||
|
||||
- **Seed Data Management:**
|
||||
- **Create a seed script** to populate the database with initial data.
|
||||
- **Use Prisma's `prisma.create` method** to create seed data.
|
||||
- **Use environment variables** to configure seed data for different environments.
|
||||
|
||||
- **Migration Management:**
|
||||
- **Use Prisma Migrate** to manage database schema changes.
|
||||
- **Create migrations** for each schema change.
|
||||
- **Apply migrations** to the database using `prisma migrate deploy`.
|
||||
- **Use shadow database** to test migrations before deploying them to production.
|
||||
|
||||
- **Monitoring and Logging:**
|
||||
- **Use Prisma's query logging feature** to monitor database queries.
|
||||
- **Log errors and warnings** to a centralized logging system.
|
||||
- **Monitor database performance** using tools like Prometheus or Grafana.
|
||||
|
||||
- **Further Study:**
|
||||
- Always refer to the [official Prisma documentation](https://www.prisma.io/docs/) for the most up-to-date information.
|
||||
- Consider taking an [official Prisma course](https://www.prisma.io/learn/).
|
||||
@@ -0,0 +1,283 @@
|
||||
---
|
||||
description: Comprehensive best practices for developing with Supabase, covering code organization, performance, security, testing, and common pitfalls. This rule provides actionable guidance for developers to build robust and scalable applications using Supabase.
|
||||
globs: **/*.{js,jsx,ts,tsx,sql}
|
||||
---
|
||||
# Supabase Best Practices: A Comprehensive Guide
|
||||
|
||||
This document outlines best practices for developing with Supabase, covering various aspects from code organization to security and performance.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
A well-organized codebase is crucial for maintainability and scalability. Here's how to structure your Supabase project:
|
||||
|
||||
### 1.1. Directory Structure Best Practices
|
||||
|
||||
Adopt a modular structure that separates concerns:
|
||||
|
||||
|
||||
project-root/
|
||||
├── src/
|
||||
│ ├── components/ # Reusable UI components
|
||||
│ ├── pages/ # Page-level components (routes)
|
||||
│ ├── services/ # Supabase client initialization and data fetching
|
||||
│ │ ├── supabase.ts # Supabase client initialization
|
||||
│ │ ├── auth.ts # Authentication-related functions
|
||||
│ │ ├── database.ts # Database interaction functions
|
||||
│ ├── utils/ # Utility functions (e.g., date formatting)
|
||||
│ ├── types/ # TypeScript types and interfaces
|
||||
│ ├── hooks/ # Custom React hooks
|
||||
│ ├── styles/ # Global styles and theme
|
||||
│ └── App.tsx # Main application component
|
||||
├── migrations/ # Database migrations
|
||||
├── tests/ # Unit and integration tests
|
||||
├── .env # Environment variables
|
||||
└── package.json # Project dependencies
|
||||
|
||||
|
||||
### 1.2. File Naming Conventions
|
||||
|
||||
* **Components:** Use PascalCase (e.g., `UserProfile.tsx`).
|
||||
* **Functions:** Use camelCase (e.g., `fetchUserData`).
|
||||
* **Variables:** Use camelCase (e.g., `userName`).
|
||||
* **Files:** Use kebab-case (e.g., `user-profile.tsx`).
|
||||
|
||||
### 1.3. Module Organization
|
||||
|
||||
* Group related functionalities into modules.
|
||||
* Use clear and descriptive module names.
|
||||
* Export only what is necessary from each module to minimize the API surface.
|
||||
|
||||
### 1.4. Component Architecture
|
||||
|
||||
* Favor small, reusable components.
|
||||
* Use a component-based approach (e.g., React, Vue.js) to build UIs.
|
||||
* Separate presentational components from container components to improve reusability and testability.
|
||||
|
||||
### 1.5. Code Splitting Strategies
|
||||
|
||||
* Use dynamic imports to lazy-load modules.
|
||||
* Split large components into smaller chunks.
|
||||
* Implement route-based code splitting to load only the necessary code for each route.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1. Design Patterns Specific to Supabase
|
||||
|
||||
* **Repository Pattern:** Abstract database interactions behind a repository interface for better testability and maintainability.
|
||||
* **Observer Pattern:** Utilize Supabase's real-time capabilities to implement reactive UIs.
|
||||
|
||||
### 2.2. Recommended Approaches for Common Tasks
|
||||
|
||||
* **Data Fetching:** Create reusable functions for fetching data from Supabase tables.
|
||||
* **Authentication:** Use Supabase Auth for user authentication and authorization.
|
||||
* **Real-time Updates:** Leverage Supabase Realtime for real-time data synchronization.
|
||||
* **File Storage:** Utilize Supabase Storage for managing file uploads and downloads.
|
||||
|
||||
### 2.3. Anti-patterns and Code Smells to Avoid
|
||||
|
||||
* **Direct Database Access from UI Components:** This tightly couples the UI to the database and makes testing difficult. Use a service layer to abstract database interactions.
|
||||
* **Overusing Supabase Functions and Policies:** Keep business logic in your application code whenever possible to avoid vendor lock-in and improve testability.
|
||||
* **Manually Creating Tables Without an ORM:** Always use an ORM to manage your database schema and migrations.
|
||||
* **Ignoring Error Handling:** Implement proper error handling to prevent unexpected crashes and provide informative error messages to users.
|
||||
* **Storing Sensitive Data in Plain Text:** Never store sensitive data like passwords or API keys in plain text. Use encryption and secure storage mechanisms.
|
||||
|
||||
### 2.4. State Management Best Practices
|
||||
|
||||
* Choose a state management library (e.g., Redux, Zustand, Recoil) based on your project's complexity.
|
||||
* Use local component state for simple UI state.
|
||||
* Centralize application state in a global store for complex data dependencies.
|
||||
* Use asynchronous actions to handle data fetching and updates.
|
||||
|
||||
### 2.5. Error Handling Patterns
|
||||
|
||||
* Use try-catch blocks to handle exceptions.
|
||||
* Implement a global error handler to catch unhandled exceptions.
|
||||
* Log errors to a monitoring service for tracking and analysis.
|
||||
* Display user-friendly error messages to the user.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1. Optimization Techniques
|
||||
|
||||
* **Indexing:** Add indexes to frequently queried columns to improve query performance.
|
||||
* **Query Optimization:** Use efficient SQL queries and avoid N+1 query problems.
|
||||
* **Caching:** Implement caching strategies to reduce database load.
|
||||
* **Connection Pooling:** Use connection pooling to reuse database connections and reduce overhead.
|
||||
|
||||
### 3.2. Memory Management
|
||||
|
||||
* Avoid memory leaks by properly cleaning up resources.
|
||||
* Use garbage collection to reclaim unused memory.
|
||||
* Optimize data structures to reduce memory usage.
|
||||
|
||||
### 3.3. Rendering Optimization
|
||||
|
||||
* Use memoization techniques to prevent unnecessary re-renders.
|
||||
* Virtualize long lists to improve rendering performance.
|
||||
* Optimize images and other assets to reduce file sizes.
|
||||
|
||||
### 3.4. Bundle Size Optimization
|
||||
|
||||
* Use tree shaking to remove unused code.
|
||||
* Minify code to reduce file sizes.
|
||||
* Compress assets to reduce transfer times.
|
||||
|
||||
### 3.5. Lazy Loading Strategies
|
||||
|
||||
* Lazy load images and other assets that are not immediately visible.
|
||||
* Implement infinite scrolling to load data in chunks as the user scrolls.
|
||||
* Use code splitting to load only the necessary code for each route.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1. Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
* **SQL Injection:** Prevent SQL injection by using parameterized queries and prepared statements.
|
||||
* **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks.
|
||||
* **Cross-Site Request Forgery (CSRF):** Implement CSRF protection to prevent unauthorized requests.
|
||||
* **Authentication and Authorization Issues:** Secure your authentication and authorization mechanisms to prevent unauthorized access.
|
||||
|
||||
### 4.2. Input Validation
|
||||
|
||||
* Validate all user input to prevent malicious data from entering your system.
|
||||
* Use server-side validation in addition to client-side validation.
|
||||
* Sanitize user input to remove potentially harmful characters.
|
||||
|
||||
### 4.3. Authentication and Authorization Patterns
|
||||
|
||||
* Use Supabase Auth for user authentication and authorization.
|
||||
* Implement role-based access control (RBAC) to manage user permissions.
|
||||
* Use row-level security (RLS) to control data access at the row level.
|
||||
|
||||
### 4.4. Data Protection Strategies
|
||||
|
||||
* Encrypt sensitive data at rest and in transit.
|
||||
* Use secure storage mechanisms to store API keys and other secrets.
|
||||
* Implement data masking to protect sensitive data from unauthorized access.
|
||||
|
||||
### 4.5. Secure API Communication
|
||||
|
||||
* Use HTTPS to encrypt API traffic.
|
||||
* Implement API rate limiting to prevent abuse.
|
||||
* Validate API requests to prevent malicious input.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1. Unit Testing Strategies
|
||||
|
||||
* Write unit tests for individual functions and components.
|
||||
* Use mocking and stubbing to isolate units of code.
|
||||
* Aim for high code coverage.
|
||||
|
||||
### 5.2. Integration Testing
|
||||
|
||||
* Write integration tests to verify the interaction between different parts of your system.
|
||||
* Test the integration between your application and Supabase.
|
||||
|
||||
### 5.3. End-to-end Testing
|
||||
|
||||
* Write end-to-end tests to simulate user interactions and verify the overall functionality of your application.
|
||||
* Use tools like Cypress or Playwright to automate end-to-end tests.
|
||||
|
||||
### 5.4. Test Organization
|
||||
|
||||
* Organize tests into separate directories based on functionality.
|
||||
* Use descriptive test names.
|
||||
* Keep tests concise and focused.
|
||||
|
||||
### 5.5. Mocking and Stubbing
|
||||
|
||||
* Use mocking to replace external dependencies with controlled substitutes.
|
||||
* Use stubbing to replace specific method calls with predefined values.
|
||||
* Avoid over-mocking, as it can make tests less reliable.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1. Frequent Mistakes Developers Make
|
||||
|
||||
* Not using an ORM for database schema management.
|
||||
* Over-relying on Supabase functions and policies for business logic.
|
||||
* Using Supabase-only features without considering open-source alternatives.
|
||||
* Ignoring error handling and security best practices.
|
||||
|
||||
### 6.2. Edge Cases to Be Aware Of
|
||||
|
||||
* Handling large datasets efficiently.
|
||||
* Dealing with real-time data synchronization conflicts.
|
||||
* Managing user sessions and authentication tokens securely.
|
||||
|
||||
### 6.3. Version-Specific Issues
|
||||
|
||||
* Be aware of breaking changes in Supabase and its dependencies.
|
||||
* Test your application thoroughly after upgrading Supabase or its dependencies.
|
||||
* Refer to the Supabase documentation for migration guides.
|
||||
|
||||
### 6.4. Compatibility Concerns
|
||||
|
||||
* Ensure compatibility between your application and the Supabase client library.
|
||||
* Test your application on different browsers and devices.
|
||||
|
||||
### 6.5. Debugging Strategies
|
||||
|
||||
* Use browser developer tools to debug client-side code.
|
||||
* Use server-side logging to track errors and performance issues.
|
||||
* Use the Supabase dashboard to monitor database activity.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1. Recommended Development Tools
|
||||
|
||||
* Supabase CLI: For local development and database management.
|
||||
* VS Code: For code editing and debugging.
|
||||
* Drizzle ORM: For database schema management.
|
||||
* Postman/Insomnia: For testing API endpoints.
|
||||
|
||||
### 7.2. Build Configuration
|
||||
|
||||
* Use a build tool like Webpack or Parcel to bundle your code.
|
||||
* Configure your build tool to optimize for production.
|
||||
* Use environment variables to configure your application.
|
||||
|
||||
### 7.3. Linting and Formatting
|
||||
|
||||
* Use ESLint to enforce code style and prevent errors.
|
||||
* Use Prettier to format your code automatically.
|
||||
* Integrate linting and formatting into your development workflow.
|
||||
|
||||
### 7.4. Deployment Best Practices
|
||||
|
||||
* Use a CI/CD pipeline to automate deployments.
|
||||
* Deploy your application to a production-ready environment.
|
||||
* Monitor your application for errors and performance issues.
|
||||
|
||||
### 7.5. CI/CD Integration
|
||||
|
||||
* Use a CI/CD tool like GitHub Actions or GitLab CI to automate your build, test, and deployment processes.
|
||||
* Configure your CI/CD pipeline to run tests and linting before deployment.
|
||||
* Use environment variables to configure your application in the CI/CD environment.
|
||||
|
||||
## 8. Database Workflow Design
|
||||
|
||||
* **Avoid Direct Changes in Production**: Once your application is live, refrain from making database changes using the Supabase Dashboard. Instead, utilize migration tools and enforce access control to prevent unauthorized modifications.
|
||||
* **Multiple Environments**: Adopt a multi-stage development workflow (`local -> staging -> prod`). This approach allows for thorough testing and validation at each stage before changes are deployed to production.
|
||||
* **Point-in-Time Recovery**: As your database grows, consider moving to Point-in-Time Recovery (PITR) to minimize the impact on database performance during maintenance and ensure data safety.
|
||||
* **Database Migrations**: Use database migration tools to manage schema changes. This practice helps maintain consistency across different environments and simplifies version control.
|
||||
* **Access Control**: Be mindful of who has access to your production environment. Limit access to experienced team members and set clear internal workflows to mitigate risks.
|
||||
* **Security**: Regularly review and update your security measures. Ensure that tables with sensitive data have appropriate access levels and that database secrets and API keys are stored securely.
|
||||
* **Performance Monitoring**: Utilize Supabase's observability tooling to monitor database performance and optimize queries, indexes, and connection management.
|
||||
|
||||
## 9. Additional Best Practices
|
||||
|
||||
* **Understand Shared Responsibilities:** When using Supabase, be aware of the shared responsibilities model. Supabase manages infrastructure, but you are responsible for application architecture, security, and data management.
|
||||
* **Proper Indexing:** Essential for query optimization. Indices should be created based on common query patterns to reduce search time.
|
||||
* **Load Testing**: Before deploying changes to production, perform load testing in a staging environment. Tools such as `k6` can simulate traffic and help identify potential bottlenecks.
|
||||
* **Resource Upgrades**: Monitor resource usage and upgrade your database when necessary. For significant traffic surges, contact support in advance for assistance.
|
||||
* **Database Optimization**: Regularly optimize your database by adding filters on large queries, using caching strategies, and managing connections efficiently.
|
||||
* **Regular Backups:** Schedule regular backups of your database to protect against data loss.
|
||||
* **Use of Postgres Features**: As Supabase is built around Postgres, understand and leverage Postgres features for performance and scalability.
|
||||
|
||||
## 10. Conclusion
|
||||
|
||||
By following these best practices, you can build robust, scalable, and secure applications with Supabase. Remember to stay up-to-date with the latest Supabase documentation and community resources to continuously improve your development practices.
|
||||
|
||||
@file ./supabase_code_examples.mdc
|
||||
Reference in New Issue
Block a user