Agent skill
sqlmodel-mastery
Comprehensive SQLModel skill for Python database operations with SQL databases. Use when working with SQLModel for (1) Designing database models and table schemas, (2) Creating relationships between tables (foreign keys, one-to-many, many-to-many), (3) Integrating SQLModel with FastAPI for CRUD APIs, (4) Writing queries with select, where, joins, and filtering, (5) Implementing best practices for session management, migrations, and performance optimization. Covers the multiple model pattern (Base, Table, Create, Public, Update), dependency injection, pagination, error handling, and production-ready patterns.
Install this agent skill to your Project
npx add-skill https://github.com/majiayu000/claude-skill-registry/tree/main/skills/data/sqlmodel-mastery
SKILL.md
SQLModel Mastery
Overview
Assist users with SQLModel for database operations, model design, FastAPI integration, and production-ready patterns. SQLModel combines Pydantic and SQLAlchemy, enabling type-safe database models that work seamlessly with FastAPI.
Quick Start
When User Needs Help With...
Model Design: Load references/model-patterns.md
Relationships: Load references/relationships.md
Queries: Load references/queries.md
FastAPI Integration: Load references/fastapi-integration.md
Best Practices/Production: Load references/best-practices.md
Common Templates
Complete CRUD API: Use assets/templates/complete-crud-api.py
Model Examples: Use assets/templates/models-example.py
Workflow
Step 1: Understand User's Context
Identify the task type:
- New project setup
- Model design questions
- Relationship configuration
- Query writing
- FastAPI integration
- Troubleshooting errors
- Best practices advice
Gather context:
- Database type (SQLite, PostgreSQL, MySQL)
- Existing codebase or greenfield
- FastAPI integration status
- Specific error messages or issues
Step 2: Load Appropriate References
Progressive disclosure: Only load what's needed.
IF task == "model design" OR "schema design":
READ references/model-patterns.md
FOCUS: Multiple model pattern, field configuration, validation
IF task == "relationships" OR "foreign keys" OR "joins":
READ references/relationships.md
FOCUS: One-to-many, many-to-many, Relationship() configuration
IF task == "queries" OR "select" OR "filtering":
READ references/queries.md
FOCUS: WHERE clauses, joins, pagination, aggregations
IF task == "FastAPI" OR "CRUD" OR "endpoints" OR "dependency injection":
READ references/fastapi-integration.md
FOCUS: Dependency pattern, CRUD endpoints, error handling
IF task == "production" OR "performance" OR "migrations" OR "best practices":
READ references/best-practices.md
FOCUS: Session management, security, optimization
IF task == "complete example" OR "template":
PROVIDE assets/templates/complete-crud-api.py OR models-example.py
Step 3: Provide Targeted Guidance
Be specific and actionable:
- Reference exact code patterns from loaded references
- Explain the "why" behind recommendations
- Highlight common pitfalls
- Provide file:line references where appropriate
For model design:
- Recommend multiple model pattern (Base, Table, Create, Public, Update)
- Show field configuration with validation
- Explain when to use Optional vs required fields
For relationships:
- Identify relationship type (one-to-many, many-to-many)
- Show foreign key and Relationship() setup
- Explain back_populates and loading strategies
For queries:
- Build query incrementally (select → where → join → pagination)
- Show proper session usage
- Recommend eager loading to avoid N+1 queries
For FastAPI integration:
- Recommend dependency injection pattern
- Show proper error handling
- Emphasize using Public models in response_model
For best practices:
- Always recommend session context managers
- Emphasize pagination on list endpoints
- Highlight security considerations
Step 4: Provide Code Examples
Use examples from references:
- Copy relevant code snippets from loaded references
- Adapt to user's specific domain
- Include comments explaining key points
Or provide templates:
- For complete implementations, copy from
assets/templates/ - Customize placeholder names to user's domain
- Highlight sections to modify
Step 5: Address Follow-up Questions
Common follow-ups:
- "How do I handle errors?" → Load
fastapi-integration.mderror handling section - "How do I optimize this query?" → Load
best-practices.mdperformance section - "How do I set up migrations?" → Load
best-practices.mdAlembic section
Reference Files Guide
references/model-patterns.md
When to load: Model design, schema design, validation questions
Key topics:
- Multiple model pattern (Base, Table, Create, Public, Update)
- Field configuration (indexes, constraints, defaults)
- Type hints and Pydantic validation
- Complete e-commerce example
Example prompts:
- "How do I design SQLModel models?"
- "What's the difference between Create and Update models?"
- "How do I add validation to fields?"
references/relationships.md
When to load: Foreign keys, relationships, joins, related data
Key topics:
- Foreign key setup
- One-to-many relationships (Team has many Heroes)
- Many-to-many relationships (link tables)
- Relationship() configuration
- Loading strategies (lazy vs eager)
- Complete blog example with Posts and Comments
Example prompts:
- "How do I create a one-to-many relationship?"
- "How do I set up many-to-many with extra fields?"
- "What is back_populates?"
references/queries.md
When to load: SELECT queries, filtering, pagination, aggregations
Key topics:
- Basic SELECT statements
- WHERE clauses (equality, comparison, LIKE, IN)
- Joins (implicit and explicit)
- Pagination (offset/limit)
- Ordering and sorting
- Aggregations (COUNT, AVG, GROUP BY)
- Complex query patterns
Example prompts:
- "How do I filter Heroes by age?"
- "How do I paginate results?"
- "How do I join two tables?"
- "How do I count records?"
references/fastapi-integration.md
When to load: FastAPI integration, CRUD endpoints, dependency injection
Key topics:
- Database setup and configuration
- Dependency injection pattern
- CRUD endpoints (Create, Read, Update, Delete)
- Error handling (404, IntegrityError)
- Request validation
- Response models
- Advanced patterns (bulk operations, transactions)
Example prompts:
- "How do I integrate SQLModel with FastAPI?"
- "How do I create CRUD endpoints?"
- "What's the dependency injection pattern?"
- "How do I handle database errors in FastAPI?"
references/best-practices.md
When to load: Production readiness, optimization, security, migrations
Key topics:
- Model design best practices (DOs and DON'Ts)
- Session management patterns
- Performance optimization (indexes, eager loading, pagination)
- Security (hiding sensitive fields, password hashing)
- Database migrations with Alembic
- Testing strategies
- Common pitfalls and solutions
- Production checklist
Example prompts:
- "What are SQLModel best practices?"
- "How do I optimize performance?"
- "How do I handle database migrations?"
- "How do I test SQLModel code?"
Asset Templates
assets/templates/complete-crud-api.py
Complete production-ready FastAPI + SQLModel CRUD API
Includes:
- Database configuration
- Multiple model pattern for Team and Hero
- All CRUD endpoints with proper error handling
- Pagination and filtering
- Dependency injection
- Input validation
- OpenAPI documentation
When to provide:
- User needs a complete working example
- Starting a new FastAPI + SQLModel project
- Understanding full CRUD implementation
How to use:
- Copy entire template
- Customize model names and fields
- Update database URL
- Run with
uvicorn main:app --reload
assets/templates/models-example.py
Comprehensive model design examples
Includes:
- Multiple model pattern for Users, Products, Orders
- Relationships (one-to-many, many-to-many)
- Field validation and constraints
- Enums and complex types
- Timestamp and soft delete mixins
- Complete e-commerce schema
When to provide:
- User needs model design inspiration
- Learning relationship patterns
- Understanding complex model hierarchies
Common Scenarios
Scenario 1: New FastAPI + SQLModel Project
User: "I want to build a FastAPI app with SQLModel"
Response:
- Provide
assets/templates/complete-crud-api.py - Explain the multiple model pattern
- Show how to run and test
- Recommend next steps (add more models, migrations)
Scenario 2: Designing Models
User: "How do I create User and Post models with relationship?"
Response:
- Load
references/model-patterns.md - Load
references/relationships.md - Show multiple model pattern for both entities
- Demonstrate one-to-many relationship setup
- Provide code example adapted to their domain
Scenario 3: Query Optimization
User: "My queries are slow"
Response:
- Load
references/queries.md(join/eager loading sections) - Load
references/best-practices.md(performance section) - Diagnose N+1 query problem
- Show selectinload() solution
- Recommend adding indexes
Scenario 4: Error Handling
User: "How do I handle 'Hero not found' errors?"
Response:
- Load
references/fastapi-integration.md(error handling section) - Show HTTPException pattern
- Demonstrate helper function approach
- Provide complete endpoint example
Scenario 5: Many-to-Many Relationship
User: "How do I create a many-to-many relationship?"
Response:
- Load
references/relationships.md(many-to-many section) - Explain link table concept
- Show basic many-to-many example
- If extra fields needed, show link table with additional columns
- Demonstrate usage in FastAPI endpoint
Key Principles
Always Recommend
- Multiple Model Pattern: Base, Table, Create, Public, Update
- Dependency Injection: Use
Depends(get_session)in FastAPI - Pagination: Always limit list endpoints
- Security: Never expose table models or sensitive fields in responses
- Error Handling: Validate and handle database errors
- Type Hints: Use proper type hints for IDE support
- Indexes: Add to frequently queried fields
Common Mistakes to Avoid
- ❌ Exposing Table models in
response_model - ❌ Forgetting
exclude_unset=Truein updates - ❌ Not using pagination on list endpoints
- ❌ Accessing relationships outside session (DetachedInstanceError)
- ❌ Not handling IntegrityError on unique constraints
- ❌ Forgetting to commit and refresh after adding records
Industry Standards
- Use PostgreSQL for production (not SQLite)
- Implement Alembic for database migrations
- Use connection pooling
- Add indexes to foreign keys
- Hash passwords before storing
- Validate all user input
- Use proper HTTP status codes (201, 404, etc.)
Troubleshooting Guide
DetachedInstanceError
Problem: Accessing relationship outside session
Solution: Use eager loading with selectinload() or access within session
Reference: best-practices.md → Common Pitfalls
IntegrityError
Problem: Unique constraint or foreign key violation
Solution: Wrap in try/except and handle gracefully
Reference: fastapi-integration.md → Error Handling
N+1 Query Problem
Problem: Separate query for each relationship access
Solution: Use selectinload() or lazy="selectin"
Reference: best-practices.md → Performance Optimization
Missing ID after commit
Problem: ID is None after session.add() and session.commit()
Solution: Call session.refresh(obj) after commit
Reference: best-practices.md → Session Management
Quick Reference Commands
# Create model instance and save
hero = Hero(name="Spider-Boy")
session.add(hero)
session.commit()
session.refresh(hero) # Load generated fields
# Query
statement = select(Hero).where(Hero.age > 30)
heroes = session.exec(statement).all()
# Update
hero_data = hero_update.model_dump(exclude_unset=True)
db_hero.sqlmodel_update(hero_data)
session.add(db_hero)
session.commit()
# Delete
session.delete(hero)
session.commit()
# FastAPI dependency
def get_session():
with Session(engine) as session:
yield session
SessionDep = Annotated[Session, Depends(get_session)]
Didn't find tool you were looking for?