Sqlalchemy patterns

From AratKruglik/claude-sdlc · View interactive version

Sqlalchemy patterns is an AI agent skill from the GitHub repository AratKruglik/claude-sdlc. Framework-agnostic SQLAlchemy 2.0 core shared by fastapi-plugin and flask-plugin: declarative mapped classes with Mapped/mapped_column, column type selection, relationships with explicit lazy loading and cascades, 2.0-style select() querying, transaction/flush discipline, and Alembic-agnostic migrat

How to use this skill

Skill file

SQLAlchemy 2.0 Patterns (framework-agnostic core)

Detection

Read pyproject.toml or requirements.txt before writing any model code:

grep -E "sqlalchemy" pyproject.toml requirements.txt

Always prefer 2.0 style for new code. When working in an existing project using 1.x style throughout, match the existing style. Never mix 1.x Column() and 2.0 mapped_column() in the same model.


Declarative base and mapped classes

Define one Base class per project. All models inherit from it. (Framework plugins may supply the base for you — e.g., Flask-SQLAlchemy's db.Model — but the mapped-column rules below are identical.)

from datetime import datetime
from decimal import Decimal
from typing import Optional

from sqlalchemy import DateTime, ForeignKey, Numeric, String, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship


class Base(DeclarativeBase):
    pass


class User(Base):
    __tablename__ = "users"

    id: Mapped[int] = mapped_column(primary_key=True)
    email: Mapped[str] = mapped_column(String(255), unique=True, index=True)
    display_name: Mapped[str] = mapped_column(String(100))
    hashed_password: Mapped[str] = mapped_column(String(255))
    is_active: Mapped[bool] = mapped_column(default=True)
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )

    orders: Mapped[list["Order"]] = relationship(
        "Order", back_populates="user", lazy="selectin"
    )

    def __repr__(self) -> str:
        return f"<User id={self.id} email={self.email!r}>"

Key rules:


Column type guidance

| Python type | SQLAlchemy column type | Notes |

|---|---|---|

| str | String(N) | Always set length; never bare String |

| Decimal | Numeric(precision, scale) | Never Float for money or precise values |

| datetime | DateTime(timezone=True) | Always set timezone=True |

| int | Integer or BigInteger | Use BigInteger for large tables (users, events) |

| bool | Boolean | |

| UUID | Uuid (SA 2.0+) or String(36) | Uuid stores as native UUID on PostgreSQL |

| enum | Enum(MyEnum, native_enum=False) | native_enum=False for DB portability |

| float | Float | Only for non-monetary approximations (lat/lon, scores) |


Querying patterns (2.0 style)

Always use 2.0-style select() statements executed through the session. The session/execution style (sync db.session vs async AsyncSession) comes from the framework delta skill; the statement construction is identical.

from sqlalchemy import select
from sqlalchemy.orm import selectinload

select(User).where(User.id == user_id)                      # single row by predicate
select(User).where(User.email == email)                     # lookup by unique column
select(User).offset(skip).limit(limit)                      # pagination
select(User).options(selectinload(User.orders)).where(...)  # explicit eager load

Result handling rules:

Transaction/flush discipline:


Relationships

Define relationships with explicit lazy and cascade settings. Never rely on defaults.

from sqlalchemy.orm import Mapped, mapped_column, relationship


class User(Base):
    __tablename__ = "users"

    id: Mapped[int] = mapped_column(primary_key=True)

    orders: Mapped[list["Order"]] = relationship(
        "Order",
        back_populates="user",
        lazy="selectin",
        cascade="all, delete-orphan",
    )

    profile: Mapped[Optional["UserProfile"]] = relationship(
        "UserProfile",
        back_populates="user",
        lazy="selectin",
        uselist=False,
        cascade="all, delete-orphan",
    )


class Order(Base):
    __tablename__ = "orders"

    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))

    user: Mapped["User"] = relationship("User", back_populates="orders", lazy="selectin")
    lines: Mapped[list["OrderLine"]] = relationship(
        "OrderLine",
        back_populates="order",
        lazy="selectin",
        cascade="all, delete-orphan",
    )

Structural rules:

Lazy loading strategy guide:

Which strategies are permitted per framework is refined by the framework delta skill (async contexts forbid select/subquery).

To prevent N+1 queries on list endpoints, apply eager-load options at query time:

from sqlalchemy.orm import joinedload, selectinload

select(User).options(selectinload(User.orders))

Migration metadata rules (Alembic-agnostic)

Both FastAPI (raw Alembic) and Flask (Flask-Migrate, which wraps Alembic) rely on --autogenerate reading the metadata object (Base.metadata / db.metadata).

Framework-specific wiring (async env.py for FastAPI, flask db init scaffolding for Flask) lives in the respective delta skill.


Anti-patterns (shared)

| Anti-pattern | Problem | Correct approach |

|---|---|---|

| String without length | Alembic autogenerate produces VARCHAR with no length; some databases use TEXT or reject it | Always String(N) |

| Float for monetary values | IEEE 754 rounding errors on financial calculations | Numeric(precision, scale) |

| lazy="dynamic" | Legacy loader superseded in SQLAlchemy 2.0; returns a legacy Query, not asyncio-compatible | lazy="write_only" for large collections; otherwise lazy="selectin"/lazy="select" (per framework) or explicit selectinload() |

| default=datetime.utcnow | Python-side default — not reflected in DB schema; utcnow is deprecated | server_default=func.now() with DateTime(timezone=True) |

| Importing models only in routers | Migration tooling never sees them; --autogenerate misses tables | Import all models in the central metadata module |

| Mixing Column() and mapped_column() | Produces inconsistent metadata; confuses tooling | One style per project; prefer mapped_column() for new code |

| Scattered commit() calls in helpers | Makes unit testing harder; unclear transaction boundaries | Commit once per unit of work at the framework-defined boundary; flush() for PKs |

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.