sqlalchemy-patterns

sqlalchemy-patterns is a skill for Claude Code from AratKruglik/claude-sdlc. It costs 226 tokens per session (1,559 once invoked), scanned A, original, MIT.

A set of database patterns for using SQLAlchemy with FastAPI, where SQLAlchemy connects Python code to a database. It focuses on asynchronous database engines, sessions, dependencies, relationship loading, and Alembic migration setup.

In plain words
What is it for?
Use it to configure async database sessions, write database models and queries, control relationship loading, and connect SQLAlchemy metadata to Alembic, a tool for tracking database schema changes.
Why use it?
It removes uncertainty around safely opening, committing, rolling back, and closing database sessions in asynchronous web requests. It also gives the FastAPI-specific part of a shared SQLAlchemy setup.

Skill for Claude Code

Written for Claude Code: shipped in a Claude Code plugin.

Part of the fastapi-plugin plugin — 2 skills, 2 agents shipped together

Good fit Use it to configure async database sessions, write database models and queries, control relationship loading, and connect SQLAlchemy metadata to Alembic, a tool for tracking database schema changes.

Compare 6 skills from other repositories ↓
Install with agentmods
npx agentmods add skills/aratkruglik/claude-sdlc/sqlalchemy-patterns
Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Any agent
npx skills add AratKruglik/claude-sdlc --skill sqlalchemy-patterns
Clone the repo
git clone --depth 1 https://github.com/AratKruglik/claude-sdlc

Made for: Claude Code.

Or install fastapi-plugin, the plugin that ships this one along with the rest of its 2 skills, 2 agents.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for sqlalchemy-patterns

README.md
[![agentmods](https://agentmods.dev/badge/skills/aratkruglik/claude-sdlc/sqlalchemy-patterns.svg)](https://agentmods.dev/skills/aratkruglik/claude-sdlc/sqlalchemy-patterns)
Your own site
<a href="https://agentmods.dev/skills/aratkruglik/claude-sdlc/sqlalchemy-patterns"><img src="https://agentmods.dev/badge/skills/aratkruglik/claude-sdlc/sqlalchemy-patterns.svg" alt="Measured on agentmods" height="20"></a>
Per session 226 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 1,559 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe. Third-party audits
  • NVIDIA SkillSpector pass 7 Sept 2026
How audits are shown
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00226 $0.01559
Opus 5 $0.00113 $0.00779
Sonnet 5 $0.00045 $0.00312
Haiku 4.5 $0.00023 $0.00156

Measured 8d ago against content hash ba17c02db2ff, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-07, from the pricing page.

Security

Grade A, and why

sqlalchemy-patterns scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 8d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

plugins/fastapi-plugin/skills/sqlalchemy-patterns/SKILL.md · 199 lines

How it starts

The opening of the file, as written. The whole thing — 199 lines — stays where its author put it; the contents beside it link to each section on GitHub.

SQLAlchemy Patterns for FastAPI (async delta)

Load python-foundation:sqlalchemy-patterns via the Skill tool FIRST. It contains the shared SQLAlchemy 2.0 core: detection, Mapped/mapped_column model definition, column type guidance, select() querying, relationship structure, lazy-strategy overview, and migration metadata rules. This skill covers only the async/FastAPI delta.


Async session setup

# app/db/session.py
from collections.abc import AsyncGenerator

from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine

from app.core.config import settings

engine = create_async_engine(
    settings.DATABASE_URL,
    echo=False,
    pool_pre_ping=True,
    pool_size=10,
    max_overflow=20,
)

AsyncSessionLocal = async_sessionmaker(
    engine,
    class_=AsyncSession,
    expire_on_commit=False,
)


async def get_db() -> AsyncGenerator[AsyncSession, None]:
    async with AsyncSessionLocal() as session:
        try:
            yield session
            await session.commit()
        except Exception:
            await session.rollback()
            raise

Use expire_on_commit=False so that model attributes remain accessible after a commit without triggering lazy loads — important in async contexts where implicit IO is not allowed.

Use pool_pre_ping=True to detect stale connections before use.

The get_db() dependency owns the transaction boundary: it commits on successful yield exit and rolls back on exception. Never call session.commit() in a router handler.


Async querying

Every execution is awaited; statement construction follows the foundation skill.

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from app.users.models import User


async def get_user_by_id(db: AsyncSession, user_id: int) -> User | None:
    result = await db.execute(select(User).where(User.id == user_id))
    return result.scalar_one_or_none()


async def get_user_with_orders(db: AsyncSession, user_id: int) -> User | None:
    result = await db.execute(
        select(User)
        .options(selectinload(User.orders))
        .where(User.id == user_id)
    )
    return result.scalar_one_or_none()


async def create_user(db: AsyncSession, email: str, hashed_password: str, display_name: str) -> User:
    user = User(email=email, hashed_password=hashed_password, display_name=display_name)
    db.add(user)
    await db.flush()  # assigns id without committing; session.commit() happens in get_db()
    return user

Read the full file on GitHub · 199 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 8d ago First seen · 199 lines · 226 tokens per session scan A ba17c02db2ff

Subscribe to this mod's changes

sqlalchemy-patterns is a skill published in the GitHub repository AratKruglik/claude-sdlc (33 stars, last pushed 3d ago), licensed MIT. It adds 226 tokens to every session and 1,559 once invoked, about $0.0011 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.

Related

Other skills, from other repositories

event-store-design

Design and implement event stores for event-sourced systems. Use when building event sourcing infrastructure, choosing event store technologies, or implementing event persistence patterns.

wshobson/agents · 33 tokens

convex-explain-app

Explain an existing Convex app — data model + relationships, public vs internal functions, auth/ownership model, components, a request→data flow — read from the schema and function surface. Read-only.

openclaw/clawhub · 47 tokens

platform-custom-field-generate

Use this skill when users need to create, generate, or validate Salesforce Custom Field metadata. Trigger when users mention custom fields, field types, Roll-up Summary fields, Master-Detail relationships, Lookup relationships, formula fields, picklists, dependent (controlling) picklists, referencing a value set from…

forcedotcom/sf-skills · 194 tokens

openloomi-api

OpenLoomi ships a local-first HTTP API served from the desktop app (port 3414, fallback 3515). All auth, Memory, AI, RAG, Loop, and Audit data live in a local SQLite database — your data stays on your machine and the OpenLoomi app is the source of truth. The only externally-routed auth path is the Composio OAuth…

melandlabs/openloomi · 106 tokens

nornicdb-grpc

Drive NornicDB over gRPC — the Qdrant-compatible surface (Collections, Points, Snapshots) plus the additive NornicSearch service. Use when ingesting via Qdrant SDKs, migrating from Qdrant, or running hybrid text+vector search from a non-Bolt client. Covers connection, RPC catalog, collection→database mapping…

orneryd/NornicDB · 98 tokens

field-service-sobject-create-configure

Headless 360 REST API deployment step for creating sObject records. Handles describe-based field discovery, required-field derivation, entity-relationship ordering, and composite graph transactions. Use this skill when a designer skill (or a user directly) needs to create sObject records after design confirmation…

forcedotcom/sf-skills · 74 tokens