ajyadav013/claude-kit/alembic-migrations

Claude Code and agent skill by ajyadav013/claude-kit

Trust tier 3
  • community
Source check pending

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

Alembic migration setup and patterns for async SQLAlchemy — async engine + run_sync in env.py, autogenerate, RLS/multi-tenant migrations. Use for alembic init, writing migrations, or debugging migration errors.

Install

npx vskill@latest install ajyadav013/claude-kit/alembic-migrations

SKILL.md

The same SKILL.md was published earlier as ajyadav013/claude-kit/alembic-migrations.

Alembic Migrations

Alembic migration patterns for async SQLAlchemy (asyncpg) from production FastAPI services.

When to use

  • Setting up Alembic in a new async SQLAlchemy project (initial migration setup, alembic init)
  • Writing database migrations (table creation, column changes, constraints, indexes, foreign keys)
  • Configuring alembic.ini and env.py for async engines (asyncpg, postgresql+asyncpg)
  • Implementing autogenerate workflow for model changes (alembic revision --autogenerate)
  • Adding Row-Level Security (RLS) policies in migrations (multi-tenant isolation, tenant_id filtering)
  • Filtering out internal/heartbeat tables from autogenerate (include_object callback)
  • Debugging migration issues (compare_type, down_revision chains, "can't locate revision", "multiple heads", "target database not up to date")
  • Converting sync migrations to async (async_engine_from_config, connection.run_sync)
  • Handling migration conflicts in large teams (timestamp-hash revision naming)
  • Creating data migrations (seed data, backfill columns, complex transformations)

Core conventions

Alembic Setup (async SQLAlchemy)

alembic.ini location and URL: Place alembic.ini at project root; leave sqlalchemy.url empty (set dynamically in env.py from settings). _(observed across multiple production services)_

env.py async pattern: Use async_engine_from_config + connection.run_sync(do_run_migrations) + asyncio.run(run_async_migrations()) in run_migrations_online(). _(async FastAPI services)_

postgresql+asyncpg URL: Replace postgresql:// with postgresql+asyncpg:// for async drivers. _(async services with asyncpg)_

target_metadata from Base: Import all model files at the top of env.py (explicit imports, not wildcard in production code, but wildcards acceptable here); set target_metadata = Base.metadata. _(all services)_

NullPool for migrations: Use poolclass=pool.NullPool in async_engine_from_config to avoid connection pooling during migrations (migrations are one-shot operations). _(standard pattern)_

Migration File Patterns

Revision naming conventions: Use sequential numbers (0001, 0002, ...) for core schema migrations _(small teams)_, or timestamp-hash format (202407301751-ad610b2bab70_description.py) for large teams to avoid conflicts _(large production service)_, or alembic-generated hashes (554395de0772_description.py) for standard workflow _(standard pattern)_.

script.py.mako template: Standard template includes revision, down_revision, branch_labels, depends_on variables + upgrade() and downgrade() functions. _(all services)_

Explicit imports in migrations: Import sqlalchemy types explicitly (from sqlalchemy.dialects.postgresql import UUID, JSONB); avoid relative imports. _(best practice)_

Descriptive docstrings: Add a migration summary docstring at the top (autogenerated by alembic revision -m). _(all services)_

Autogenerate Workflow

Basic autogenerate command: alembic revision --autogenerate -m "description" detects model changes and generates migration. _(implied in all repos)_

Review before applying: Always review autogenerated migrations; alembic can't detect all changes (renamed columns, custom types, RLS policies). _(best practice)_

compare_type flag: Add compare_type=True in context.configure() to detect column type changes (off by default). _(multiple services)_

include_object filtering: Define an include_object(object, name, type_, reflected, compare_to) callback to exclude internal tables (like heartbeat/monitoring tables) from autogenerate. _(large production service)_

Multi-Tenant and RLS Migrations

Enabling RLS: Use op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY") in upgrade; loop over TENANT_SCOPED_TABLES list. _(multi-tenant service)_

RLS policy pattern: Create policy with USING (tenant_id = NULLIF(current_setting('app.tenant_id', TRUE), '')::uuid OR current_setting('app.bypass_rls', TRUE) = 'true') to support session variables + admin bypass. _(multi-tenant service)_

RLS downgrade: Drop policies in reversed order; use DROP POLICY IF EXISTS and DISABLE ROW LEVEL SECURITY. _(multi-tenant service)_

Cross-schema migrations: If using multi-schema tenancy, migrations apply to the default schema; tenant-specific schemas may require custom op.execute() loops or separate migration paths (not observed in sampled repos).

Offline vs Online Modes

Offline mode: Generates SQL script to stdout without connecting to DB; context.configure(url=url, target_metadata=target_metadata, literal_binds=True). _(all services)_

Online mode: Connects to DB and applies migrations directly; async services use run_migrations_online() → run_async_migrations() → connection.run_sync(do_run_migrations). _(all services)_

Check mode: if context.is_offline_mode() determines which path to run. _(all services)_

Skeleton / example

python
# alembic/env.py (async SQLAlchemy pattern)
import asyncio
from logging.config import fileConfig
from alembic import context
from sqlalchemy import pool
from sqlalchemy.ext.asyncio import async_engine_from_config
from app.database import Base
from config.settings import settings
# Import all models so Alembic can see them
from myapp.users.models import User
from myapp.tenants.models import Tenant
from myapp.products.models import Product
config = context.config
config.set_main_option("sqlalchemy.url", settings.DATABASE_URL)
if config.config_file_name is not None:
fileConfig(config.config_file_name)
target_metadata = Base.metadata
def run_migrations_offline() -> None:
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection):
context.configure(
connection=connection,
target_metadata=target_metadata,
compare_type=True, # Detect column type changes
)
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations():
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
def run_migrations_online() -> None:
asyncio.run(run_async_migrations())
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
python
# alembic/versions/0001_create_users_table.py
"""create users table
Revision ID: 0001
Revises:
Create Date: 2026-04-22
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID, JSONB
revision: str = "0001"
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"users",
sa.Column("id", UUID(as_uuid=True), primary_key=True, server_default=sa.text("gen_random_uuid()")),
sa.Column("email", sa.String(255), nullable=False, unique=True),
sa.Column("password_hash", sa.String(512), nullable=False),
sa.Column("first_name", sa.String(100), nullable=False),
sa.Column("last_name", sa.String(100), nullable=False),
sa.Column("active", sa.Boolean, nullable=False, server_default=sa.text("true")),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP")),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP")),
)
op.create_index("ix_users_email", "users", ["email"])
def downgrade() -> None:
op.drop_table("users")
python
# alembic/versions/0010_add_rls_policies.py (multi-tenant pattern)
"""Enable Row-Level Security on tenant-scoped tables
Revision ID: 0010
Revises: 0009
Create Date: 2026-04-25
"""
from alembic import op
revision: str = "0010"
down_revision: str = "0009"
TENANT_SCOPED_TABLES = [
"tenant_configs",
"user_tenant_mappings",
"tenant_audit_logs",
]
def upgrade() -> None:
for table in TENANT_SCOPED_TABLES:
op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")
op.execute(f"""
CREATE POLICY tenant_isolation_{table}
ON {table}
FOR ALL
USING (
tenant_id = NULLIF(current_setting('app.tenant_id', TRUE), '')::uuid
OR current_setting('app.bypass_rls', TRUE) = 'true'
)
""")
def downgrade() -> None:
for table in reversed(TENANT_SCOPED_TABLES):
op.execute(f"DROP POLICY IF EXISTS tenant_isolation_{table} ON {table}")
op.execute(f"ALTER TABLE {table} DISABLE ROW LEVEL SECURITY")
python
# include_object filtering (exclude internal tables from autogenerate)
def include_object(object, name, type_, reflected, compare_to):
if type_ == "table" and object.name == "__monitoring_heartbeat":
return False
return True
# In run_migrations_offline() and run_migrations_online():
context.configure(
...,
target_metadata=target_metadata,
include_object=include_object,
)

Anti-patterns to avoid

  • Forgetting to import models in env.py — Alembic can't see models not imported; autogenerate will miss them.
  • Using sync engine for async projects — Async SQLAlchemy requires async_engine_from_config + connection.run_sync.
  • Skipping migration review — Autogenerate doesn't catch renamed columns, data migrations, or custom SQL; always review before applying.
  • Hard-coding database URL in alembic.ini — Set sqlalchemy.url dynamically from settings in env.py to support multiple environments.
  • Missing compare_type flag — Column type changes won't be detected without compare_type=True in context.configure().
  • Forgetting downgrade implementations — Always implement downgrade() for reversibility; use reversed() for loop-based migrations.
  • Using pooled connections in migrations — Migrations are one-shot; use poolclass=pool.NullPool to avoid connection pool overhead.
  • Applying RLS to all tables — Only tenant-scoped tables need RLS; avoid overhead on platform/shared tables.
  • Editing applied migrations — Never modify a migration after it's been applied to any environment; create a new migration to fix issues instead.

Quick command reference

bash
# Initialize Alembic (first time setup)
alembic init alembic
# Create empty migration
alembic revision -m "description"
# Create autogenerated migration
alembic revision --autogenerate -m "description"
# Apply all pending migrations
alembic upgrade head
# Revert last migration
alembic downgrade -1
# Show current revision
alembic current
# Show migration history
alembic history --verbose
# Generate SQL without applying (dry run)
alembic upgrade head --sql
# Merge diverged branches
alembic merge -m "merge heads" head1_id head2_id
# Mark migration as applied without running it
alembic stamp <revision_id>

References

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

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

Source

Popularity

7-day trend score
5

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/ajyadav013/claude-kit/alembic-migrations/badge)](https://verified-skill.com/skills/ajyadav013/claude-kit/alembic-migrations)

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