Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
aiskillstore avatar

Python Database Patterns

  • 1 installs
  • 404 repo stars
  • Updated August 5, 2026
  • aiskillstore/marketplace

python-database-patterns is a skill that gives SQLAlchemy 2.0 ORM and async database patterns for Python and FastAPI backends.

About

This skill teaches SQLAlchemy 2.0 and database best practices for Python. It covers declarative models, sync and async engines, query patterns, relationships, and FastAPI dependency injection for DB sessions. A developer loads it when writing ORM code, tuning connection pools, or setting up Alembic migrations.

  • SQLAlchemy 2.0 ORM and async database patterns
  • Query, relationship, and eager-loading recipes
  • Alembic migration and connection-pooling references

Python Database Patterns by the numbers

  • 1 all-time installs (skills.sh)
  • Ranked #765 of 911 Databases skills by installs in the Skillselion catalog
  • Data as of Aug 5, 2026 (Skillselion catalog sync)
At a glance

python-database-patterns capabilities & compatibility

Capabilities
database · api development
Works with
postgres
Use cases
database · api development
Pricing
Free
From the docs

What python-database-patterns says it does

SQLAlchemy and database patterns for Python. Triggers on: sqlalchemy, database, orm, migration, alembic, async database, connection pool, repository pattern, unit of work.
SKILL.md
SQLAlchemy 2.0 and database best practices.
SKILL.md
npx skills add https://github.com/aiskillstore/marketplace --skill python-database-patterns

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs1
repo stars404
Last updatedAugust 5, 2026
Repositoryaiskillstore/marketplace

What it does

Write SQLAlchemy 2.0 models, queries, and async sessions in a Python backend or FastAPI app.

Who is it for?

Python developers writing SQLAlchemy 2.0 models, queries, and async database sessions.

Skip if: Non-SQLAlchemy ORMs or non-Python stacks.

When should I use this skill?

Writing SQLAlchemy models, async sessions, Alembic migrations, or FastAPI database dependencies.

What you get

Produces SQLAlchemy 2.0 models, typed queries, async sessions, and migration setup.

  • SQLAlchemy 2.0 models
  • async session setup
  • Alembic migration config

By the numbers

  • 7-row SQLAlchemy 2.0 quick-reference table
  • 4 reference docs plus 1 alembic.ini template asset

Files

SKILL.mdMarkdownGitHub ↗

Python Database Patterns

SQLAlchemy 2.0 and database best practices.

SQLAlchemy 2.0 Basics

from sqlalchemy import create_engine, select
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session

class Base(DeclarativeBase):
    pass

class User(Base):
    __tablename__ = "users"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(100))
    email: Mapped[str] = mapped_column(String(255), unique=True)
    is_active: Mapped[bool] = mapped_column(default=True)

# Create engine and tables
engine = create_engine("postgresql://user:pass@localhost/db")
Base.metadata.create_all(engine)

# Query with 2.0 style
with Session(engine) as session:
    stmt = select(User).where(User.is_active == True)
    users = session.execute(stmt).scalars().all()

Async SQLAlchemy

from sqlalchemy.ext.asyncio import (
    AsyncSession,
    async_sessionmaker,
    create_async_engine,
)
from sqlalchemy import select

# Async engine
engine = create_async_engine(
    "postgresql+asyncpg://user:pass@localhost/db",
    echo=False,
    pool_size=5,
    max_overflow=10,
)

# Session factory
async_session = async_sessionmaker(engine, expire_on_commit=False)

# Usage
async with async_session() as session:
    result = await session.execute(select(User).where(User.id == 1))
    user = result.scalar_one_or_none()

Model Relationships

from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship, Mapped, mapped_column

class User(Base):
    __tablename__ = "users"

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

    # One-to-many
    posts: Mapped[list["Post"]] = relationship(back_populates="author")

class Post(Base):
    __tablename__ = "posts"

    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str]
    author_id: Mapped[int] = mapped_column(ForeignKey("users.id"))

    # Many-to-one
    author: Mapped["User"] = relationship(back_populates="posts")

Common Query Patterns

from sqlalchemy import select, and_, or_, func

# Basic select
stmt = select(User).where(User.is_active == True)

# Multiple conditions
stmt = select(User).where(
    and_(
        User.is_active == True,
        User.age >= 18
    )
)

# OR conditions
stmt = select(User).where(
    or_(User.role == "admin", User.role == "moderator")
)

# Ordering and limiting
stmt = select(User).order_by(User.created_at.desc()).limit(10)

# Aggregates
stmt = select(func.count(User.id)).where(User.is_active == True)

# Joins
stmt = select(User, Post).join(Post, User.id == Post.author_id)

# Eager loading
from sqlalchemy.orm import selectinload
stmt = select(User).options(selectinload(User.posts))

FastAPI Integration

from fastapi import Depends, FastAPI
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Annotated

async def get_db() -> AsyncGenerator[AsyncSession, None]:
    async with async_session() as session:
        yield session

DB = Annotated[AsyncSession, Depends(get_db)]

@app.get("/users/{user_id}")
async def get_user(user_id: int, db: DB):
    result = await db.execute(select(User).where(User.id == user_id))
    user = result.scalar_one_or_none()
    if not user:
        raise HTTPException(status_code=404)
    return user

Quick Reference

OperationSQLAlchemy 2.0 Style
Select allselect(User)
Filter.where(User.id == 1)
First.scalar_one_or_none()
All.scalars().all()
Countselect(func.count(User.id))
Join.join(Post)
Eager load.options(selectinload(User.posts))

Additional Resources

  • ./references/sqlalchemy-async.md - Async patterns, session management
  • ./references/connection-pooling.md - Pool configuration, health checks
  • ./references/transactions.md - Transaction patterns, isolation levels
  • ./references/migrations.md - Alembic setup, migration strategies

Assets

  • ./assets/alembic.ini.template - Alembic configuration template

---

See Also

Prerequisites:

  • python-typing-patterns - Mapped types and annotations
  • python-async-patterns - Async database sessions

Related Skills:

  • python-fastapi-patterns - Dependency injection for DB sessions
  • python-pytest-patterns - Database fixtures and testing

Related skills

FAQ

Which SQLAlchemy version does this cover?

SQLAlchemy 2.0 with the modern select() and Mapped[] declarative style.

Does it support async?

Yes, it covers async engines and sessions using asyncpg for PostgreSQL or aiosqlite.

Databasesdatabases

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.