ajyadav013/claude-kit/alembic-migrations
Claude Code and agent skill by ajyadav013/claude-kit
- community
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-migrationsSKILL.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.iniandenv.pyfor 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
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.urldynamically from settings inenv.pyto support multiple environments. - Missing compare_type flag — Column type changes won't be detected without
compare_type=Trueincontext.configure(). - Forgetting downgrade implementations — Always implement
downgrade()for reversibility; usereversed()for loop-based migrations. - Using pooled connections in migrations — Migrations are one-shot; use
poolclass=pool.NullPoolto 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
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
- SKILL.md in the repositoryCheckingskills/alembic-migrations/SKILL.md
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
[](https://verified-skill.com/skills/ajyadav013/claude-kit/alembic-migrations)