sqlalchemylisted
Install: claude install-skill lgzarturo/codeconductor
## When to Use
- Defining new SQLAlchemy models
- Writing query logic in services
- Implementing bulk operations
- Setting up or modifying Alembic migrations
- Debugging N+1 queries or session issues
## Engine and Session Setup
```python
# db.py
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from src.config import settings
engine = create_async_engine(
settings.database_url, # postgresql+asyncpg://user:pass@host/db
echo=settings.debug,
pool_size=10,
max_overflow=20,
)
async_session_factory = async_sessionmaker(
engine,
class_=AsyncSession,
expire_on_commit=False, # required for async — objects usable after commit
)
```
`expire_on_commit=False` is mandatory in async SQLAlchemy. Without it, accessing
attributes after commit triggers lazy load → `MissingGreenlet` error.
## Model Base
```python
# models/base.py
from datetime import datetime
from sqlalchemy import func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
class TimestampMixin:
created_at: Mapped[datetime] = mapped_column(
server_default=func.now(), nullable=False
)
updated_at: Mapped[datetime] = mapped_column(
server_default=func.now(), onupdate=func.now(), nullable=False
)
```
All models inherit from `Base`. All persistent entities include
`TimestampMixin`.
## Model Definition (SQLAlchemy 2.x style)
```python
# models/product.py
f