Python + SQLAlchemy Rules for Cursor
Cursor coding rules for Python + SQLAlchemy projects. Best practices, patterns, and conventions.
# Python + SQLAlchemy Rules for Cursor
# Python + SQLAlchemy 2.0 Rules
## Modern SQLAlchemy
- Use SQLAlchemy 2.0+ syntax — not 1.x legacy patterns
- Declarative mapped classes with `mapped_column`
- Type annotations on all column mappings
- Async engine with asyncpg for async applications
```python
from sqlalchemy.orm import Mapped, mapped_column, DeclarativeBase
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
email: Mapped[str] = mapped_column(unique=True, index=True)
name: Mapped[str | None]
```
## Session Management
- One session per request — use dependency injection
- Context managers for session lifecycle
- Async sessions for async applications
## Query Patterns
- `select()` function — not `session.query()`
- Explicit `joinedload` / `selectinload` to avoid N+1
- Paginate with `offset` / `limit` or keyset pagination
## Migrations
- Alembic for all schema changes
- Never modify existing migration files
- Autogenerate migrations then review before applyingHow to use with Cursor
Create a `.cursorrules` file in your project root and paste these rules. Cursor reads this automatically on every AI interaction.
Related Rules
Python Cursor Rules
Best Cursor AI coding rules for Python development. Enforce type hints, PEP 8, Pythonic patterns, and modern Python best practices in your .cursorrules file.
TypeScript Cursor Rules
Cursor rules for TypeScript: enforce strict mode, eliminate any types, and write type-safe code with these .cursorrules configurations.
React Cursor Rules
Cursor rules for React: component patterns, hooks best practices, performance optimization, and clean state management conventions.
Next.js Cursor Rules
Cursor rules for Next.js App Router: server components, data fetching, routing, and deployment best practices.