ddtully/dotfiles/python-sqlalchemy

Claude Code and agent skill by ddtully/dotfiles

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

SQLAlchemy ORM patterns for Python database access. Use when defining models, writing queries, implementing upserts, working with JSON columns, or managing database sessions.

Install

npx vskill@latest install ddtully/dotfiles/python-sqlalchemy

SKILL.md

The same SKILL.md was published earlier as ddtully/dotfiles/python-sqlalchemy.

Quick Reference

TaskSQLAlchemy 2.0 Pattern
Define modelclass User(Base): ... with Mapped[...] + mapped_column(...)
Open sessionSessionLocal = sessionmaker(bind=engine)
Query rowssession.scalars(select(User).where(...)).all()
Query onesession.scalar(select(User).where(...))
Get by PKsession.get(User, user_id)
Insert/updatesession.add(obj) then session.commit()
Deletesession.delete(obj) then session.commit()
Eager loadingselect(User).options(selectinload(User.posts))
Pagination.order_by(...).limit(limit).offset(offset)
Upsert (Postgres)insert(...).on_conflict_do_update(...)
Session RuleWhy
One session per request/unit of workPrevent state leaks
Always rollback on exceptionsKeep transaction clean
Commit explicitlyAvoid accidental writes
Refresh after commit when neededEnsure DB-generated fields loaded

When to Use This Skill

Use for SQLAlchemy ORM and query design:

  • Defining typed models with SQLAlchemy 2.0 APIs
  • Building CRUD and filtering queries
  • Managing sync or async sessions and transactions
  • Solving N+1 issues with relationship loading strategies
  • Implementing Postgres upserts and JSONB queries

Related skills:

  • For Python fundamentals: see python-fundamentals
  • For async patterns: see python-asyncio
  • For backend architecture: see python-backend

SQLAlchemy 2.0 Practical Guide

Base Setup

Sync Engine and Session
python
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, sessionmaker
class Base(DeclarativeBase):
pass
engine = create_engine(
"postgresql+psycopg://user:pass@localhost:5432/app",
pool_pre_ping=True,
)
SessionLocal = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False)
Async Engine and Session
python
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
pass
engine = create_async_engine(
"postgresql+asyncpg://user:pass@localhost:5432/app",
pool_pre_ping=True,
)
AsyncSessionLocal = async_sessionmaker(
bind=engine,
class_=AsyncSession,
autoflush=False,
expire_on_commit=False,
)

Model Patterns

Typed Model Example
python
from datetime import datetime
from typing import Any
from sqlalchemy import DateTime, ForeignKey, String, func
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
email: Mapped[str] = mapped_column(String(320), unique=True, index=True)
profile: Mapped[dict[str, Any]] = mapped_column(JSONB, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
posts: Mapped[list["Post"]] = relationship(back_populates="author", cascade="all, delete-orphan")
class Post(Base):
__tablename__ = "posts"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(String(200), index=True)
author_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
author: Mapped[User] = relationship(back_populates="posts")
Modeling Guidelines
  • Use Mapped[T] and mapped_column(...) for all mapped fields
  • Add DB-level constraints (unique, index, foreign keys) instead of app-only checks
  • Keep relationship names explicit (author/posts) and mirrored with back_populates
  • Prefer server timestamps (server_default=func.now()) for write consistency

Query Patterns

Select and Filter
python
from sqlalchemy import select
def list_active_users(session, limit: int = 50):
stmt = (
select(User)
.where(User.profile["active"].as_boolean().is_(True))
.order_by(User.created_at.desc())
.limit(limit)
)
return session.scalars(stmt).all()
Single Row and Existence
python
from sqlalchemy import exists, select
def get_user_by_email(session, email: str) -> User | None:
return session.scalar(select(User).where(User.email == email))
def user_exists(session, email: str) -> bool:
return bool(session.scalar(select(exists().where(User.email == email))))
Relationship Loading
python
from sqlalchemy import select
from sqlalchemy.orm import selectinload
def list_users_with_posts(session):
stmt = select(User).options(selectinload(User.posts))
return session.scalars(stmt).all()
  • Use selectinload for one-to-many collections in list pages
  • Use joinedload for many-to-one or when row explosion is acceptable
  • Avoid lazy loading in response serialization paths

Transactions and Session Lifecycle

Sync Unit of Work
python
def create_user(session, email: str) -> User:
user = User(email=email)
session.add(user)
session.commit()
session.refresh(user)
return user
Safe Session Scope
python
from collections.abc import Generator
def get_db() -> Generator:
db = SessionLocal()
try:
yield db
db.commit()
except Exception:
db.rollback()
raise
finally:
db.close()
Async Session Scope
python
from collections.abc import AsyncGenerator
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with AsyncSessionLocal() as db:
try:
yield db
await db.commit()
except Exception:
await db.rollback()
raise

Upserts (PostgreSQL)

python
from sqlalchemy.dialects.postgresql import insert
def upsert_user(session, email: str, profile: dict) -> None:
stmt = insert(User).values(email=email, profile=profile)
stmt = stmt.on_conflict_do_update(
index_elements=[User.email],
set_={"profile": stmt.excluded.profile},
)
session.execute(stmt)
session.commit()
  • Prefer conflict target by unique index/constraint
  • Keep upserts idempotent and explicit about updated columns

Performance Checklist

  • Select only needed columns for large list endpoints
  • Add indexes for common filters and sort keys
  • Use eager loading to avoid N+1 query bursts
  • Paginate unbounded list queries
  • Inspect generated SQL and query plans for hot paths

Common Pitfalls

  • Mixing sync session usage in async code paths
  • Reusing one session across unrelated requests
  • Forgetting rollback after exceptions
  • Returning ORM objects after session close with lazy attributes unresolved
  • Using query(...) patterns in new code instead of select(...)

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
0

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
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/ddtully/dotfiles/python-sqlalchemy/badge)](https://verified-skill.com/skills/ddtully/dotfiles/python-sqlalchemy)

Something wrong with this skill or its page? Tell us.