/claude-kit:alembic-migrationsfrom Claude Kit SDLC
Alembic migration patterns for async SQLAlchemy (asyncpg) — async engine setup, autogenerate, RLS/multi-tenant migrations, and debugging migration errors.
Ships in Claude Kit SDLC. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Alembic migration patterns for async SQLAlchemy (asyncpg) from production FastAPI services.
alembic.ini and env.py for async engines (asyncpg, postgresql+asyncpg)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)
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)
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)
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 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)
# 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()
# 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")
# 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")
# 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,
)
async_engine_from_config + connection.run_sync.sqlalchemy.url dynamically from settings in env.py to support multiple environments.compare_type=True in context.configure().downgrade() for reversibility; use reversed() for loop-based migrations.poolclass=pool.NullPool to avoid connection pool overhead.# 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>
README.md (opens in a new tab)references/alembic-setup-and-env.md (opens in a new tab)references/async-and-multitenant-migrations.md (opens in a new tab)references/repo-evidence.md (opens in a new tab)references/troubleshooting-and-debugging.md (opens in a new tab)references/writing-migrations.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
alembic, database-migrations, async-sqlalchemy, asyncpg, rls
npx claudepluginhub ajyadav013/claude-kit --plugin claude-kit127 skills in this plugin
/accessibility-reviewUI accessibility (WCAG) review — keyboard operability, focus, ARIA semantics, color contrast, touch targets. Returns prioritized fixes. Distinct from performance/visual review./anthropic-vertex-integrationClaude on Vertex AI via the AnthropicVertex SDK — lazy ADC client init, env-based project/region resolution, async helpers, backoff retry. Use when calling Claude via GCP Vertex AI (not direct Anthropic API)./api-and-interface-designStable API and interface design patterns. Use when designing REST/GraphQL endpoints, module boundaries, type contracts between modules or frontend/backend, or changing public interfaces.Other plugins' skills for the same job