Skip to content
Back to skills

Sqlalchemy Alembic

ASecurity

Build typed SQLAlchemy 2.x models, async sessions, and safe Alembic migrations. Prevent async MissingGreenlet lazy loads, enforce constraint naming conventions, and audit autogenerate diffs.

  • 50,717 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 2, 2026
ai-agentspythongosqlexpressfastapitestinggitapidatabasedocumentation

Works with

  • api

Security analysis

A100/100

Pro scans all 2 files and shows the line behind each finding

Scanned December 2, 2026

npx -y skills add sickn33/agentic-awesome-skills --skill sqlalchemy-alembic --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Sqlalchemy Alembic?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Sqlalchemy Alembic
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/sickn33-sqlalchemy-alembic/badge)](https://www.skillsdirectory.com/skills/sickn33-sqlalchemy-alembic)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: sqlalchemy-alembic
description: "Build typed SQLAlchemy 2.x models, async sessions, and safe Alembic migrations. Prevent async MissingGreenlet lazy loads, enforce constraint naming conventions, and audit autogenerate diffs."
category: database
risk: critical
source: self
source_type: self
date_added: "2026-11-30"
author: ShianMike
tags: [sqlalchemy, alembic, python, orm, migrations, asyncio]
---

# SQLAlchemy 2.0 and Alembic

## When to Use

- Define or migrate SQLAlchemy 2.x models using `DeclarativeBase`, `Mapped[]`, and `mapped_column`.
- Debug `MissingGreenlet`, detached-instance errors, or N+1 queries under `AsyncSession`.
- Author, audit, or test Alembic schema migrations (including deterministic constraint names and SQLite batch rebuilds).

## Prerequisites

Identify the SQLAlchemy major/minor version, Alembic version, target database dialect and driver (for example `asyncpg`, `psycopg`, or `aiosqlite`), and whether migrations run online or offline (`--sql`). For async engines, ensure `sqlalchemy[asyncio]` (including `greenlet`) is installed. Inspect `alembic.ini`, `env.py`, `Base.metadata`, and existing revision history before generating new revisions.

## Write SQLAlchemy 2.x models and async queries safely

1. Declare a shared `MetaData(naming_convention=...)` on `DeclarativeBase` before creating migrations so indexes, unique constraints, check constraints, and foreign keys get deterministic names across dialects. Unnamed constraints make future `drop_constraint` migrations fail or drift between environments.
2. Use SQLAlchemy 2.x style consistently: `Mapped[T]` with `mapped_column(...)` and `select(...)` statements instead of legacy 1.x `session.query(...)` and `declarative_base()`.
3. On `AsyncSession`, configure `async_sessionmaker(engine, expire_on_commit=False)` when callers inspect ORM attributes after `commit()`. Never rely on implicit lazy loading in async code: accessing an unloaded relationship triggers `MissingGreenlet` (wrapped in `StatementError` on SQLAlchemy 2.1+). Load required relations explicitly with `selectinload(...)` or `joinedload(...)` (using `.unique()` on joined collection loads), or declare `lazy="raise"` on relationships so accidental lazy loads fail early in tests.

## Author and verify Alembic migrations

- Treat `alembic revision --autogenerate` as a draft, never a finished migration. Autogenerate does not reliably detect table or column renames (it emits drop + add), custom `CHECK` expressions, partial indexes, triggers, or required data backfills.
- For SQLite targets, enable `render_as_batch=True` in `env.py` and use `with op.batch_alter_table(...):` when altering nullability, types, or constraints so Alembic executes SQLite's copy-and-move table rebuild cleanly.
- Keep `downgrade()` tested when rollback is expected, or explicitly raise `NotImplementedError` for irreversible destructive steps rather than leaving a broken auto-generated downgrade.
- Verify every new migration on a disposable database by running `upgrade head`, checking actual reflected schema/constraints, and testing `downgrade` + re-`upgrade` on representative fixture rows.

## Example

> Reproduce an async `MissingGreenlet` lazy-load failure, fix it with `selectinload`, and verify an Alembic `batch_alter_table` upgrade and downgrade with explicit constraint names.

Run the [worked async session and Alembic batch migration test](references/async-and-alembic.md) to confirm both the async eager-loading contract and reversible named-constraint schema migrations.

## Limitations

- SQLite batch migrations exercise Alembic's revision graph and constraint naming locally, not PostgreSQL/MySQL locking semantics (`ALTER TABLE` locks, `CREATE INDEX CONCURRENTLY`, or enum DDL).
- `AsyncSession` examples require `greenlet` (`sqlalchemy[asyncio]`); sync engines do not raise `MissingGreenlet`, though N+1 lazy loading still applies.
- Multi-branch Alembic heads require explicit `alembic merge` coordination against the repository's actual migration history.

## Safety and Side Effects

Always test migrations against an isolated scratch or staging database copy before touching production. Separate destructive column/table drops from application cutovers using expand-contract steps, back up before running irreversible data backfills, and keep database credentials out of `alembic.ini` and source control (inject via environment variables in `env.py`).

## Related Skills and Documentation

- For FastAPI routing, dependency injection, and service architecture, see [FastAPI Pro](https://github.com/sickn33/agentic-awesome-skills/blob/main/skills/fastapi-pro/SKILL.md) and [Python FastAPI Development](https://github.com/sickn33/agentic-awesome-skills/blob/main/skills/python-fastapi-development/SKILL.md).
- For zero-downtime SQL rollout patterns across PostgreSQL, MySQL, and SQL Server, see [SQL Database Migration Strategy](https://github.com/sickn33/agentic-awesome-skills/blob/main/skills/database-migrations-sql-migrations/SKILL.md).
- See the official [SQLAlchemy 2.0 asyncio guide](https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html), [SQLAlchemy constraint naming conventions](https://docs.sqlalchemy.org/en/20/core/constraints.html#constraint-naming-conventions), and [Alembic batch migrations documentation](https://alembic.sqlalchemy.org/en/latest/batch.html).

Files in this skill

  • SKILL.md5.2 KB
  • references/async-and-alembic.md6.4 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.