This skill provides expert guidance for building production-ready database layers.
Stack
- SQLAlchemy 2.0 with async support (asyncpg driver)
- Pydantic v2 for validation and serialization
- Alembic for migrations
- PostgreSQL only
Core Principles
1. Separation of Concerns
models/ # SQLAlchemy ORM models (database layer)
schemas/ # Pydantic schemas (API layer)
repositories/ # Data access patterns
services/ # Business logic
2. Type Safety First
Always use SQLAlchemy 2.0 style with Mapped[] type annotations:
from sqlalchemy.orm import Mapped, mapped_column
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100))
3. Async by Default
Use async engine and sessions for FastAPI:
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
engine = create_async_engine("postgresql+asyncpg://...")
4. Pydantic-SQLAlchemy Bridge
Keep models and schemas separate but mappable:
# Schema reads from ORM
class UserRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
5. Repository Pattern
Abstract database operations for testability and clean code.
- Setup database layer - Initialize SQLAlchemy + Pydantic + Alembic from scratch
- Define models - Create SQLAlchemy models with Pydantic schemas
- Create migration - Generate and manage Alembic migrations
- Query patterns - Async CRUD, joins, eager loading, optimization
- Full implementation - Complete database layer for a feature
Auto-detection triggers (use this skill when user mentions):
- database, db, sqlalchemy, postgres, postgresql
- model, migration, alembic
- repository, crud, query
- async session, connection pool
| Reference |
Purpose |
| references/best-practices.md |
Production patterns, security, performance |
| references/patterns.md |
Repository, Unit of Work, common queries |
| references/async-patterns.md |
Async session management, FastAPI integration |
|
|
Essential Imports
# Models
from sqlalchemy import String, Integer, ForeignKey, DateTime
from sqlalchemy.orm import Mapped, mapped_column, relationship, DeclarativeBase
# Async
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
# Pydantic
from pydantic import BaseModel, ConfigDict, Field
Connection String
# PostgreSQL async
DATABASE_URL = "postgresql+asyncpg://user:pass@localhost:5432/dbname"
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: sqlalchemy-postgres3description: Expert guidance for SQLAlchemy 2.0 + Pydantic + PostgreSQL. Use when setting up database layers, defining models, creating migrations, or any database-related work. Automatically activated for DB tasks. Use when this capability is needed.4---56<essential_principles>7## SQLAlchemy 2.0 + Pydantic + PostgreSQL Best Practices89This skill provides expert guidance for building production-ready database layers.1011### Stack12- **SQLAlchemy 2.0** with async support (asyncpg driver)13- **Pydantic v2** for validation and serialization14- **Alembic** for migrations15- **PostgreSQL** only1617### Core Principles1819**1. Separation of Concerns**20```21models/ # SQLAlchemy ORM models (database layer)22schemas/ # Pydantic schemas (API layer)23repositories/ # Data access patterns24services/ # Business logic25```2627**2. Type Safety First**28Always use SQLAlchemy 2.0 style with `Mapped[]` type annotations:29```python30from sqlalchemy.orm import Mapped, mapped_column3132class User(Base):33 __tablename__ = "users"34 id: Mapped[int] = mapped_column(primary_key=True)35 name: Mapped[str] = mapped_column(String(100))36```3738**3. Async by Default**39Use async engine and sessions for FastAPI:40```python41from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession42engine = create_async_engine("postgresql+asyncpg://...")43```4445**4. Pydantic-SQLAlchemy Bridge**46Keep models and schemas separate but mappable:47```python48# Schema reads from ORM49class UserRead(BaseModel):50 model_config = ConfigDict(from_attributes=True)51```5253**5. Repository Pattern**54Abstract database operations for testability and clean code.55</essential_principles>5657<intake>58What do you need help with?59601. **Setup database layer** - Initialize SQLAlchemy + Pydantic + Alembic from scratch612. **Define models** - Create SQLAlchemy models with Pydantic schemas623. **Create migration** - Generate and manage Alembic migrations634. **Query patterns** - Async CRUD, joins, eager loading, optimization645. **Full implementation** - Complete database layer for a feature65</intake>6667<routing>68| Response | Workflow |69|----------|----------|70| 1, "setup", "initialize", "start" | workflows/setup-database.md |71| 2, "model", "define", "create model" | workflows/define-models.md |72| 3, "migration", "alembic", "schema change" | workflows/create-migration.md |73| 4, "query", "crud", "repository" | workflows/query-patterns.md |74| 5, "full", "complete", "feature" | Run setup → define-models → create-migration |7576**Auto-detection triggers (use this skill when user mentions):**77- database, db, sqlalchemy, postgres, postgresql78- model, migration, alembic79- repository, crud, query80- async session, connection pool81</routing>8283<reference_index>84## Domain Knowledge8586| Reference | Purpose |87|-----------|---------|88| references/best-practices.md | Production patterns, security, performance |89| references/patterns.md | Repository, Unit of Work, common queries |90| references/async-patterns.md | Async session management, FastAPI integration |91</reference_index>9293<workflows_index>94| Workflow | Purpose |95|----------|---------|96| workflows/setup-database.md | Initialize complete database layer |97| workflows/define-models.md | Create models + schemas + relationships |98| workflows/create-migration.md | Alembic migration workflow |99| workflows/query-patterns.md | CRUD operations and optimization |100</workflows_index>101102<quick_reference>103## File Structure104```105src/106├── db/107│ ├── __init__.py108│ ├── base.py # DeclarativeBase109│ ├── session.py # Engine + async session factory110│ └── dependencies.py # FastAPI dependency111├── models/112│ ├── __init__.py113│ └── user.py # SQLAlchemy models114├── schemas/115│ ├── __init__.py116│ └── user.py # Pydantic schemas117├── repositories/118│ ├── __init__.py119│ ├── base.py # Generic repository120│ └── user.py # User repository121└── alembic/122 ├── alembic.ini123 ├── env.py124 └── versions/125```126127## Essential Imports128```python129# Models130from sqlalchemy import String, Integer, ForeignKey, DateTime131from sqlalchemy.orm import Mapped, mapped_column, relationship, DeclarativeBase132133# Async134from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker135136# Pydantic137from pydantic import BaseModel, ConfigDict, Field138```139140## Connection String141```python142# PostgreSQL async143DATABASE_URL = "postgresql+asyncpg://user:pass@localhost:5432/dbname"144```145</quick_reference>146147<success_criteria>148Database layer is complete when:149- [ ] Async engine and session factory configured150- [ ] Base model with common fields (id, created_at, updated_at)151- [ ] Models use Mapped[] type annotations152- [ ] Pydantic schemas with from_attributes=True153- [ ] Alembic configured for async154- [ ] Repository pattern implemented155- [ ] FastAPI dependency for session injection156- [ ] Connection pooling configured for production157</success_criteria>158159---160> Converted and distributed by [TomeVault](https://tomevault.io/claim/cfircoo) — claim your Tome and manage your conversions.161<!-- tomevault:4.0:skill_md:2026-04-11 -->