skills/sqlmodel-orm-dbhelper/SKILL.md
Design and implement production-grade database layers using SQLModel with SQLAlchemy 2.0 patterns. This skill should be used when users need to create database models, configure engines/sessions, design schemas, implement relationships, or optimize database performance in Python FastAPI projects.
npx skillsauth add alijilani-dev/claude sqlmodel-orm-dbhelperInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
A comprehensive skill for designing robust, high-performance database management layers using SQLModel.
Gather context to ensure successful implementation:
| Source | Gather |
|--------|--------|
| Codebase | Existing models, database.py, project structure, FastAPI app setup |
| Conversation | Project domain, entities, relationships, performance requirements |
| Skill References | SQLModel patterns from references/ (models, relationships, engine config) |
| User Guidelines | Naming conventions, project standards, database choice (SQLite/PostgreSQL/MySQL) |
Ensure all required context is gathered before implementing. Only ask user for THEIR specific requirements (domain expertise is in this skill).
Ask about USER's context before designing:
1. Understand Domain → 2. Design Schema → 3. Create Models → 4. Configure Engine → 5. Implement Session → 6. Add Relationships → 7. Optimize
| Normal Form | When to Use | |-------------|-------------| | 1NF | Always - atomic values, no repeating groups | | 2NF | Always - remove partial dependencies | | 3NF | Default - remove transitive dependencies | | Denormalize | Only for proven performance needs |
| Data Type | SQLModel Type | Use Case |
|-----------|---------------|----------|
| Primary Key | int | None = Field(default=None, primary_key=True) | Auto-increment ID |
| UUID PK | uuid.UUID = Field(default_factory=uuid4, primary_key=True) | Distributed systems |
| String | str = Field(max_length=255) | Text with limit |
| Text | str = Field(sa_type=Text) | Unlimited text |
| DateTime | datetime = Field(default_factory=datetime.utcnow) | Timestamps |
| DateTime TZ | datetime = Field(sa_type=DateTime(timezone=True)) | Timezone-aware |
| Decimal | Decimal = Field(max_digits=10, decimal_places=2) | Financial data |
| JSON | dict = Field(sa_type=JSON) | Flexible schemas |
| JSONB | dict = Field(sa_type=JSONB) | PostgreSQL queryable JSON |
from datetime import datetime
from typing import Optional
from sqlmodel import Field, SQLModel
class TimestampMixin(SQLModel):
created_at: datetime = Field(default_factory=datetime.utcnow, nullable=False)
updated_at: datetime = Field(
default_factory=datetime.utcnow,
sa_column_kwargs={"onupdate": datetime.utcnow},
nullable=False
)
class BaseModel(TimestampMixin):
id: Optional[int] = Field(default=None, primary_key=True)
See references/relationships.md for complete relationship patterns.
from sqlmodel import create_engine, Session
from sqlalchemy.pool import QueuePool
DATABASE_URL = "postgresql://user:pass@localhost/dbname"
engine = create_engine(
DATABASE_URL,
poolclass=QueuePool,
pool_size=5, # Persistent connections
max_overflow=10, # Additional connections under load
pool_timeout=30, # Wait time for connection
pool_recycle=1800, # Recycle connections every 30 min
pool_pre_ping=True, # Verify connection health
echo=False, # Disable SQL logging in production
)
from typing import Generator
from fastapi import Depends
from sqlmodel import Session
def get_session() -> Generator[Session, None, None]:
with Session(engine) as session:
yield session
# Usage in FastAPI endpoint
@app.get("/items")
def get_items(session: Session = Depends(get_session)):
return session.exec(select(Item)).all()
See references/engine-config.md for database-specific configurations.
class User(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
email: str = Field(unique=True, index=True) # Unique + indexed
username: str = Field(index=True) # Frequently queried
status: str = Field(index=True) # Filter field
from sqlmodel import select
from sqlalchemy.orm import selectinload, joinedload
# Eager load related objects
statement = select(User).options(selectinload(User.orders))
users = session.exec(statement).all()
# Use joinedload for single related object
statement = select(Order).options(joinedload(Order.user))
| Strategy | Use When |
|----------|----------|
| lazy="select" (default) | Related data rarely needed |
| lazy="selectin" | Loading multiple parents with children |
| lazy="joined" | Always need related data, single object |
| lazy="subquery" | Complex queries with collections |
See references/performance.md for advanced optimization patterns.
| Anti-Pattern | Problem | Solution | |--------------|---------|----------| | Session per operation | Connection overhead | One session per request | | Missing indexes | Slow queries | Index frequently filtered columns | | N+1 queries | Performance killer | Use eager loading | | No connection pooling | Resource exhaustion | Use QueuePool | | Committing in loops | Transaction overhead | Batch operations | | No pool_pre_ping | Stale connections | Enable pre-ping | | Hardcoded credentials | Security risk | Use environment variables |
When implementing, deliver:
Before delivering, verify:
| File | When to Read |
|------|--------------|
| references/relationships.md | Implementing One-to-One, One-to-Many, Many-to-Many |
| references/engine-config.md | Database-specific engine configuration |
| references/performance.md | Advanced optimization, query tuning |
| references/field-types.md | Complete field type reference |
| references/migrations.md | Alembic migration guidance |
data-ai
Orchestrate complex tasks by delegating work to parallel subagent teams, preserving the main context window and preventing auto-compact. This skill should be used when users ask to apply subagent-teams, when performing complex multi-step tasks, when context window is getting large, or when independent subtasks can run in parallel.
development
Generate new Claude Code skills with proper structure and standards. Use when the user requests skill creation, wants to generate a new skill, or mentions creating custom Claude Code functionality. Activated by phrases like "create a skill", "generate a skill", "make a new skill", or "build a skill for".
testing
Generate comprehensive educational quizzes based on Bloom's Taxonomy methodology (Remember, Understand, Apply, Analyze, Evaluate, Create). Creates structured True/False quizzes with detailed answer keys and explanations. Use when user requests quiz generation, assessment creation, test materials, practice questions, mentions Bloom's Taxonomy, or provides educational topics for quiz creation. Activates for study topics, course materials, reference files (.md, .txt, .pdf), or educational content requiring systematic assessment.
content-media
Generate comprehensive educational notes using Bloom's Taxonomy methodology. Creates structured learning materials with summaries, practice questions, and visual diagrams. Use when user requests notes generation, study materials, learning resources, mentions Bloom's Taxonomy, or provides topics for educational note-taking. Activates for .md files, study topics, course materials, or educational content creation.