Regenerate all MDC rules with fresh Exa data and December 2025 best practices

- Refreshed all 241 library rules with current best practices
- Updated Exa search results for all libraries with 2025 content
- Fixed --regenerate-all flag logic to properly process all libraries
- Removed duplicate astro entry in rules.json (merged tags)
- Added missing docker.mdc and vim.mdc files
- All rules now include modern patterns and anti-patterns
- Updated with framework-specific recommendations for 2025

Technical improvements:
- Fixed retry_failed_only logic in generate_mdc_files.py
- Improved progress tracking for regeneration scenarios
- Ensured proper handling of --refresh-exa flag
This commit is contained in:
sanjeed5
2025-12-17 22:40:28 +05:30
parent 331fb6ffac
commit 8fbf269085
244 changed files with 66701 additions and 52708 deletions
+202 -194
View File
@@ -1,261 +1,269 @@
---
description: Enforces best practices for SQLAlchemy, covering code organization, performance, security, testing, and common pitfalls to ensure maintainable, efficient, and secure database interactions.
globs: *.py
description: This guide enforces modern SQLAlchemy 2.x best practices for Python applications, ensuring type-safe, performant, and maintainable database interactions.
globs: **/*.py
---
# SQLAlchemy Best Practices and Coding Standards
This document outlines the best practices and coding standards for using SQLAlchemy in Python projects. Following these guidelines will help you write maintainable, efficient, and secure code.
## 1. Code Organization and Structure
### 1.1 Directory Structure
A well-organized directory structure improves code readability and maintainability. Here's a recommended structure for SQLAlchemy-based projects:
project_name/
├── app/
│ ├── __init__.py
│ ├── models/
│ │ ├── __init__.py
│ │ ├── user.py
│ │ ├── product.py
│ │ └── ...
│ ├── database.py # SQLAlchemy engine and session setup
│ ├── routes/
│ │ ├── __init__.py
│ │ ├── user_routes.py
│ │ ├── product_routes.py
│ │ └── ...
│ ├── schemas/
│ │ ├── __init__.py
│ │ ├── user_schema.py
│ │ ├── product_schema.py
│ │ └── ...
│ ├── utils.py
│ └── main.py # Entry point for the application
├── tests/
│ ├── __init__.py
│ ├── conftest.py # Fixtures for testing
│ ├── test_models.py
│ ├── test_routes.py
│ └── ...
├── migrations/
│ ├── versions/
│ │ ├── ... (Alembic migration scripts)
│ ├── alembic.ini
│ └── env.py
├── .env # Environment variables
├── requirements.txt
├── pyproject.toml # Define project dependencies
└── README.md
# SQLAlchemy Best Practices (2.x Style)
This document outlines the definitive best practices for using SQLAlchemy 2.x in our projects. We exclusively adopt the "2-style" API, leveraging its fully typed, declarative features for robust and maintainable code.
### 1.2 File Naming Conventions
## 1. Code Organization and Data Modeling
* **Models:** Use descriptive names for model files (e.g., `user.py`, `product.py`).
* **Schemas:** Use `_schema.py` suffix for schema files (e.g., `user_schema.py`).
* **Routes/Controllers:** Use `_routes.py` or `_controllers.py` suffix (e.g., `user_routes.py`).
* **Database:** A central `database.py` or `db.py` file is standard.
* **Migrations:** Alembic manages migration script names automatically.
Always define your ORM models using the modern `DeclarativeBase` and `Mapped` annotations. Keep model definitions in a dedicated `models.py` or `orm_models/` directory.
### 1.3 Module Organization
### 1.1 Declarative Models with Type Annotations
* **Models:** Group related models into separate modules for clarity.
* **Schemas:** Define schemas in separate modules for serialization/deserialization.
* **Routes/Controllers:** Organize API endpoints into logical modules.
Use `DeclarativeBase` as your base class and `Mapped` for all ORM-mapped attributes. This enables static type checking and clear schema definition.
### 1.4 Component Architecture
❌ BAD: Legacy `declarative_base()` function and untyped `Column`.
```python
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
* **Data Access Layer (DAL):** Abstract database interactions into a separate layer using the Repository Pattern to decouple the application logic from the database implementation.
* **Service Layer:** Implement business logic in a service layer that utilizes the DAL.
* **Presentation Layer:** (Routes/Controllers) Handle request processing and response generation.
Base = declarative_base()
### 1.5 Code Splitting
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
name = Column(String) # No type hint
```
* **Model Definition:** Split large models into smaller, manageable classes.
* **Query Logic:** Move complex query logic into reusable functions or methods.
* **Configuration:** Externalize configuration settings using environment variables.
✅ GOOD: Modern `DeclarativeBase` and `Mapped` for explicit typing.
```python
from typing import List, Optional
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
from sqlalchemy import String, ForeignKey, func, DateTime
## 2. Common Patterns and Anti-patterns
class Base(DeclarativeBase):
pass
### 2.1 Design Patterns
class User(Base):
__tablename__ = "user_account"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(30))
fullname: Mapped[Optional[str]]
created_at: Mapped[DateTime] = mapped_column(DateTime, insert_default=func.now())
* **Repository Pattern:** Centralizes data access logic, improving testability and maintainability. Example:
addresses: Mapped[List["Address"]] = relationship(back_populates="user", cascade="all, delete-orphan")
python
class UserRepository:
def __init__(self, session: Session):
self.session = session
class Address(Base):
__tablename__ = "address"
id: Mapped[int] = mapped_column(primary_key=True)
email_address: Mapped[str]
user_id: Mapped[int] = mapped_column(ForeignKey("user_account.id"))
def get_user_by_id(self, user_id: int) -> User | None:
return self.session.get(User, user_id)
* **Unit of Work Pattern:** Tracks changes to multiple entities and commits them as a single transaction, ensuring data consistency.
* **Data Mapper Pattern:** Provides a layer of indirection between the database and domain objects, allowing for independent evolution.
user: Mapped["User"] = relationship(back_populates="addresses")
```
### 2.2 Recommended Approaches
### 1.2 Mixins for Common Fields
* **Declarative Base:** Use `declarative_base()` to define models.
* **Context Managers:** Use context managers for session management to ensure sessions are properly closed.
* **Parameterized Queries:** Always use parameterized queries to prevent SQL injection.
* **Eager Loading:** Use `joinedload()`, `subqueryload()`, or `selectinload()` to optimize query performance and avoid the N+1 problem.
* **Alembic:** Use Alembic for database migrations.
Implement common fields like timestamps, soft-delete flags, or version counters using mixins.
### 2.3 Anti-patterns and Code Smells
```python
from datetime import datetime
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy import DateTime, func
* **Raw SQL:** Avoid writing raw SQL queries whenever possible; leverage SQLAlchemy's ORM or Core features.
* **Global Sessions:** Avoid using global session objects; create sessions within request/transaction scopes.
* **Long-Lived Sessions:** Keep sessions short-lived to prevent stale data and concurrency issues.
* **Over-Fetching:** Avoid retrieving more data than necessary; use targeted queries.
* **N+1 Query Problem:** Identify and address the N+1 query problem using eager loading.
class TimestampMixin:
created_at: Mapped[datetime] = mapped_column(DateTime, insert_default=func.now())
updated_at: Mapped[datetime] = mapped_column(DateTime, insert_default=func.now(), onupdate=func.now())
### 2.4 State Management
class SoftDeleteMixin:
deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, default=None)
* **Session Scope:** Manage the SQLAlchemy session within the scope of a request or transaction.
* **Thread Safety:** Ensure thread safety when using SQLAlchemy in multi-threaded environments.
* **Asynchronous Sessions:** Use asynchronous sessions for non-blocking database operations in asynchronous applications.
class User(Base, TimestampMixin, SoftDeleteMixin):
__tablename__ = "user_account"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
# ... other fields
```
### 2.5 Error Handling
## 2. Session Management
* **Exception Handling:** Implement robust exception handling to catch database errors and prevent application crashes.
* **Rollbacks:** Use `session.rollback()` to revert changes in case of errors.
* **Logging:** Log database errors and queries for debugging and monitoring purposes.
The `Session` is your unit of work. Always use it as a context manager to ensure proper transaction handling and resource cleanup.
## 3. Performance Considerations
### 2.1 Context Manager for Sessions
### 3.1 Optimization Techniques
Wrap all database operations within a `with Session(engine) as session:` block. This guarantees `commit()` on success and `rollback()` on error, followed by `close()`.
* **Indexing:** Add indexes to frequently queried columns to improve query performance.
* **Query Optimization:** Analyze query execution plans and optimize queries accordingly.
* **Connection Pooling:** Configure connection pooling to reuse database connections and reduce overhead.
* **Caching:** Implement caching strategies to reduce database load.
* **Batch Operations:** Use batch operations for bulk inserts, updates, and deletes.
❌ BAD: Manual session handling, prone to leaks and uncommitted transactions.
```python
session = Session(engine)
try:
user = User(name="Alice")
session.add(user)
session.commit()
except Exception:
session.rollback()
finally:
session.close()
```
### 3.2 Memory Management
✅ GOOD: `Session` as a context manager.
```python
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
* **Session Management:** Close sessions promptly to release resources.
* **Result Set Size:** Limit the size of result sets to prevent memory exhaustion.
* **Streaming Results:** Use streaming results for large datasets to reduce memory usage.
engine = create_engine("sqlite:///./test.db")
Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
### 3.3 Lazy Loading Strategies
def create_user(name: str):
with Session() as session:
user = User(name=name)
session.add(user)
session.commit() # Flushes changes and commits transaction
session.refresh(user) # Refresh to get auto-generated IDs
return user
```
### 2.2 Explicit Transaction Blocks
For complex operations requiring multiple steps within a single transaction, use `session.begin()`.
```python
def transfer_funds(from_account_id: int, to_account_id: int, amount: float):
with Session() as session:
with session.begin(): # Explicit transaction block
from_account = session.get(Account, from_account_id)
to_account = session.get(Account, to_account_id)
if not from_account or not to_account:
raise ValueError("Account not found")
if from_account.balance < amount:
raise ValueError("Insufficient funds")
* **Joined Loading**: Load related entities in a single query using a JOIN.
* **Subquery Loading**: Load related entities using a subquery, suitable for complex relationships.
* **Selectin Loading**: Load related entities using a separate SELECT IN query, efficient for collections.
from_account.balance -= amount
to_account.balance += amount
# Transaction commits here if no exceptions, or rolls back if an error occurs
print(f"Transferred {amount} from {from_account_id} to {to_account_id}")
```
## 3. Querying and Optimization
## 4. Security Best Practices
Always use the `select()` construct for queries and prioritize eager loading for relationships to avoid N+1 problems.
### 4.1 Common Vulnerabilities
### 3.1 Use `select()` for All Queries
* **SQL Injection:** Prevent SQL injection by using parameterized queries and avoiding string concatenation.
* **Data Exposure:** Protect sensitive data by encrypting it at rest and in transit.
* **Authentication Bypass:** Implement robust authentication and authorization mechanisms to prevent unauthorized access.
The `Query` object is deprecated in 2.x. Use `select()` for all ORM and Core queries.
### 4.2 Input Validation
❌ BAD: Using the legacy `session.query()` API.
```python
users = session.query(User).filter(User.name == "Alice").all()
```
* **Schema Validation:** Use schemas to validate input data and ensure it conforms to the expected format.
* **Sanitization:** Sanitize input data to remove malicious characters and prevent cross-site scripting (XSS) attacks.
✅ GOOD: Using `select()` with `session.execute()`.
```python
from sqlalchemy import select
### 4.3 Authentication and Authorization
def get_user_by_name(session: Session, name: str) -> Optional[User]:
stmt = select(User).where(User.name == name)
return session.scalar(stmt) # Use scalar for single result, one_or_none for one, all for list
```
* **Authentication:** Use secure authentication protocols such as OAuth 2.0 or JWT (JSON Web Tokens).
* **Authorization:** Implement role-based access control (RBAC) or attribute-based access control (ABAC) to restrict access to resources.
### 3.2 Eager Loading Relationships
### 4.4 Data Protection
Prevent N+1 query issues by eagerly loading related objects using `selectinload` or `joinedload`. `selectinload` is generally preferred for collections.
* **Encryption:** Encrypt sensitive data at rest and in transit using strong encryption algorithms.
* **Hashing:** Hash passwords and other sensitive data using strong hashing algorithms.
* **Data Masking:** Mask sensitive data in non-production environments to prevent data breaches.
❌ BAD: Lazy loading in a loop, leading to N+1 queries.
```python
users = session.scalars(select(User)).all()
for user in users:
print(f"{user.name} has {len(user.addresses)} addresses") # Each access triggers a new query
```
### 4.5 Secure API Communication
✅ GOOD: Eager loading with `selectinload`.
```python
from sqlalchemy.orm import selectinload
* **HTTPS:** Use HTTPS to encrypt communication between the client and the server.
* **API Keys:** Use API keys to authenticate API requests.
* **Rate Limiting:** Implement rate limiting to prevent denial-of-service (DoS) attacks.
def get_users_with_addresses(session: Session) -> List[User]:
stmt = select(User).options(selectinload(User.addresses))
return session.scalars(stmt).all()
## 5. Testing Approaches
# Now, accessing user.addresses won't trigger additional queries
users = get_users_with_addresses(session)
for user in users:
print(f"{user.name} has {len(user.addresses)} addresses")
```
### 5.1 Unit Testing
## 4. Data Manipulation
* **Model Testing:** Test model methods and properties.
* **Repository Testing:** Test repository methods in isolation.
* **Service Testing:** Test service layer logic.
The ORM Unit of Work pattern handles inserts, updates, and deletes efficiently.
### 5.2 Integration Testing
### 4.1 Adding and Updating Objects
* **Database Integration:** Test database interactions and ensure data integrity.
* **API Integration:** Test API endpoints and ensure they function correctly.
Add new objects with `session.add()`. Modifications to existing objects are tracked automatically.
### 5.3 End-to-End Testing
```python
def update_user_name(session: Session, user_id: int, new_name: str):
user = session.get(User, user_id) # Efficiently get by primary key
if user:
user.name = new_name # Change is tracked
session.commit()
return user
* **Full Application Testing:** Test the entire application workflow to ensure all components work together seamlessly.
def add_new_user_with_address(session: Session, name: str, email: str):
user = User(name=name, fullname=name)
address = Address(email_address=email, user=user) # Relationship automatically links
session.add(user) # Adding user also adds address due to cascade
session.commit()
return user
```
### 5.4 Test Organization
### 4.2 Deleting Objects
* **Test Directory:** Organize tests into a separate `tests` directory.
* **Test Modules:** Create separate test modules for each component.
* **Test Fixtures:** Use test fixtures to set up test data and dependencies.
Delete objects using `session.delete()`.
### 5.5 Mocking and Stubbing
```python
def delete_user(session: Session, user_id: int):
user = session.get(User, user_id)
if user:
session.delete(user)
session.commit()
print(f"User {user_id} deleted.")
else:
print(f"User {user_id} not found.")
```
* **Mocking Databases**: Use `unittest.mock` or `pytest-mock` to mock the SQLAlchemy engine and session during testing.
* **Patching External Dependencies**: Patch external dependencies to isolate the component under test.
### 4.3 Bulk Operations (Use Sparingly)
## 6. Common Pitfalls and Gotchas
Only use bulk operations (`session.bulk_insert_mappings`, `session.execute(insert/update/delete)`) when performance is paramount and ORM event handling (e.g., `onupdate` hooks) is not required.
### 6.1 Frequent Mistakes
```python
from sqlalchemy import insert
* **Forgetting to Commit:** Always commit changes to the database after making modifications.
* **Incorrect Relationship Configuration:** Ensure relationships are configured correctly to avoid data integrity issues.
* **Not Handling Exceptions:** Always handle exceptions to prevent application crashes.
* **Lack of Query Optimization:** Neglecting to optimize queries can lead to performance bottlenecks.
def bulk_insert_users(session: Session, user_data: List[dict]):
# This bypasses ORM object creation and event hooks.
# Use when you have raw data and need speed.
session.execute(insert(User), user_data)
session.commit()
### 6.2 Edge Cases
# Example user_data: [{"name": "Charlie", "fullname": "Charlie Brown"}, ...]
```
* **Concurrency Issues:** Be aware of concurrency issues when multiple users access the database simultaneously.
* **Data Type Mismatches:** Ensure data types in the application and the database are compatible.
* **Large Result Sets:** Handle large result sets efficiently to avoid memory issues.
## 5. Migrations and Type Checking
### 6.3 Version-Specific Issues
Integrate Alembic for schema migrations and ensure static type checking with Mypy or Ruff.
* **API Changes:** Be aware of API changes between different SQLAlchemy versions.
* **Compatibility Issues:** Ensure compatibility between SQLAlchemy and other libraries.
### 5.1 Alembic for Schema Evolution
### 6.4 Debugging Strategies
Always use Alembic to manage database schema changes. Never manually alter the database schema.
* **Logging:** Use logging to track database queries and errors.
* **Debugging Tools:** Use debugging tools to step through code and inspect variables.
* **Query Analysis:** Analyze query execution plans to identify performance bottlenecks.
```bash
# Initialize Alembic (once per project)
alembic init -t async migrations
## 7. Tooling and Environment
# Generate a new migration script
alembic revision --autogenerate -m "Add new_column to user_account"
### 7.1 Recommended Development Tools
# Apply migrations
alembic upgrade head
```
* **IDE:** Use a good IDE such as VS Code, PyCharm, or Spyder.
* **Database Client:** Use a database client such as pgAdmin, Dbeaver, or MySQL Workbench.
* **SQLAlchemy Profiler:** Use an SQLAlchemy profiler to analyze query performance.
### 5.2 Static Type Checking
### 7.2 Build Configuration
Leverage Python's `typing` and SQLAlchemy's `Mapped` for comprehensive type checking with tools like Mypy or Ruff. This catches schema mismatches and API misuses early.
* **Dependencies:** Use `requirements.txt` or `pyproject.toml` to manage dependencies.
* **Environment Variables:** Use environment variables to configure the application.
### 7.3 Linting and Formatting
* **Linting:** Use linters such as pylint or flake8 to enforce code style.
* **Formatting:** Use formatters such as black or autopep8 to automatically format code.
### 7.4 Deployment Best Practices
* **Database Configuration:** Configure the database connection settings correctly.
* **Security Hardening:** Harden the server and database to prevent security breaches.
* **Monitoring:** Implement monitoring to track application performance and errors.
### 7.5 CI/CD Integration
* **Automated Testing:** Run automated tests during the CI/CD pipeline.
* **Database Migrations:** Apply database migrations during deployment.
* **Rollbacks:** Implement rollbacks in case of deployment failures.
By adhering to these best practices, you can build robust, scalable, and maintainable applications with SQLAlchemy. Remember to adapt these guidelines to your specific project requirements and context.
```python
# mypy.ini or pyproject.toml configuration for mypy
[mypy]
plugins = sqlalchemy.ext.mypy.plugin
```