skb3002/agenthub/sqlalchemy-expert
Claude Code and agent skill by skb3002/agenthub
Trust tier 3
- community
Source check pending
Checking that the SKILL.md file is still in the repository.
SQLAlchemy 2.0 async patterns, session management, query optimization, and Alembic migrations. Use when designing Python data access layers with SQLAlchemy.
Install
npx vskill@latest install skb3002/agenthub/sqlalchemy-expertSKILL.md
SQLAlchemy 2.0 Expert
Modern async-first SQLAlchemy patterns for production Python services.Learn to THINK about the session lifecycle, not copy query strings.
⚠️ How to Use This Skill
- ASK whether the service is async or sync before choosing the API
- Default to SQLAlchemy 2.0 style (
select(),Mapped[], typed) — NOT the legacy 1.4 Query API - If raw SQL fits better, use it — an ORM isn't mandatory
1. When to Use SQLAlchemy vs Raw SQL
Decision Matrix
| Use SQLAlchemy when… | Use Raw SQL when… | |
|---|---|---|
| Multi-table ORM relationships | Complex analytics / window functions | |
| Migrations via Alembic | Bulk ETL / data pipelines | |
| Schema-driven app | Single known query, perf critical | |
| Team wants type safety | DB-specific features (CTE, LATERAL) |
Hybrid Pattern (Recommended)
2. Async Setup (SQLAlchemy 2.0)
Engine & Session
Driver Matrix
| DB | Sync Driver | Async Driver | Dialect | |
|---|---|---|---|---|
| PostgreSQL | psycopg2 / psycopg3 | asyncpg | postgresql+asyncpg | |
| MySQL | PyMySQL | aiomysql | mysql+aiomysql | |
| SQLite | sqlite3 | aiosqlite | sqlite+aiosqlite | |
| SQL Server | pyodbc | aioodbc | mssql+aioodbc |
3. Session Management
The Golden Rule
One session per request, one transaction per logical unit of work.
FastAPI Dependency
Transactions
| Pattern | Use | |
|---|---|---|
async with session.begin(): | Explicit transaction block | |
async with session.begin_nested(): | Savepoint (nested transaction) | |
| Auto-commit on dep yield | Default request lifecycle |
4. Modern Model Style (SQLAlchemy 2.0)
Typed Mapped[] Syntax
Benefits Over 1.4 Style
mypycatches type errors at declaration- No more
Column(Integer, primary_key=True)— types come from annotations - Relationship types flow through queries
5. Querying (2.0 API)
SELECT — always use select()
INSERT / UPDATE / DELETE
Eager Loading — the N+1 Fix
| Pattern | When | |
|---|---|---|
selectinload(User.posts) | Many-to-many, one-to-many (issues 2nd query) | |
joinedload(User.profile) | One-to-one, one-to-few (single JOIN) | |
.options(contains_eager(...)) | Manual JOIN with explicit load |
6. Relationships
Cardinality Map
| Relationship | Pattern | |
|---|---|---|
| One-to-one | relationship(..., uselist=False) + unique FK | |
| One-to-many | FK on child, relationship on parent | |
| Many-to-many | Association table with two FKs | |
| Self-referential | remote_side=[id] for tree structures |
Cascades — Be Explicit
7. Alembic Migrations
Setup
Common Flow
Migration Hygiene
| Rule | Why | |
|---|---|---|
Number sequentially (001_, 002_, …) | Predictable ordering in teams | |
| Small migrations | Easier to review + roll back | |
| Never edit a merged migration | Write a new one | |
| Review autogenerated output | Autogen is a draft, not truth | |
| Test rollback | alembic downgrade -1 should work |
Zero-Downtime Strategy
8. Performance
Connection Pool Tuning
| Setting | Default | Typical Prod | |
|---|---|---|---|
pool_size | 5 | 10–20 | |
max_overflow | 10 | 20 | |
pool_timeout | 30 | 30 | |
pool_recycle | -1 | 1800 (30 min) | |
pool_pre_ping | False | True |
Query Optimization
Batching
9. Testing
Transactional Fixtures
Every test starts from a clean DB state without re-creating the schema.
Don't Mock the ORM
Use a real SQLite (sqlite+aiosqlite:///:memory:) or Postgres test container. Mocking the session is fragile and hides bugs.
10. Anti-Patterns
❌ DON'T
- Mix sync and async drivers in the same app
- Use
session.query()(legacy 1.4 API) - Rely on
autocommit=True(removed in 2.0) - Share a session across threads or async tasks
- Use
expire_on_commit=True(default) with long-lived objects - Skip
pool_pre_pingin production - Forget to review Alembic autogenerated migrations
✅ DO
- Use
select(),insert(),update(),delete()functions - One session per request, commit once at boundary
- Eager-load relationships with
selectinload/joinedload - Keep migrations small and reversible
- Test with real DB, not mocks
- Type models with
Mapped[]
11. SQLAlchemy vs Alternatives
| Library | Best For | Why pick it | |
|---|---|---|---|
| SQLAlchemy 2.0 | Production apps, complex schemas | Mature, typed, async, any DB | |
| SQLModel | FastAPI-heavy, Pydantic-first | Wraps SQLAlchemy with Pydantic models | |
| Tortoise ORM | Async-native, Django-like API | Simpler API, smaller ecosystem | |
| Piccolo | Async + ORM + admin UI | Built-in admin, smaller scope | |
| asyncpg direct | Hot paths, known queries | No ORM overhead, raw speed |
Remember: SQLAlchemy is a tool for managing sessions and transactions, not just queries. Master the session lifecycle and the rest follows.
Security
- Security scanPassed, 100 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/sqlalchemy-expert/SKILL.md
Popularity
- Repository stars
- 3
- 7-day trend score
- 7
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/skb3002/agenthub/sqlalchemy-expert)