alembic
БесплатноБез исполняемых скриптовНе проверенDatabase migration management for SQLAlchemy projects using Alembic
от diegosouzapw★ 68 звёзд на GitHubОб этом скилле
Alembic Database Migrations
Alembic is a database migration tool for SQLAlchemy projects that provides version control for your database schema.
Quick Start
Create Migration (Autogenerate)
# Generate migration from model changes
alembic revision --autogenerate -m "Add user table"
# Check if there are pending changes
alembic check
Apply Migrations
# Upgrade to latest version
alembic upgrade head
# Upgrade to specific revision
alembic upgrade ae1027a6acf
# Downgrade one revision
alembic downgrade -1
# Downgrade to base (empty schema)
alembic downgrade base
Check Status
# Show current database revision
alembic current
# Show all revision history
alembic history
# Show revision details
alembic show ae1027a6acf
Common Patterns
Autogenerate Configuration
env.py setup for async SQLAlchemy:
import asyncio
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
# Import your models
from app.models import Base
from app.config import get_settings
config = context.config
settings = get_settings()
# Configure database URL for async
database_url = settings.database_url.replace("postgresql://", "postgresql+asyncpg://")
config.set_main_option("sqlalchemy.url", database_url)
target_metadata = Base.metadata
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 do_run_migrations(connection):
context.configure(
connection=connection,
target_metadata=target_metadata,
compare_type=True,
compare_server_default=True,
render_as_batch=False, # Set to True for SQLite
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
asyncio.run(run_async_migrations())
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
Manual Migration Operations
Common schema changes:
from alembic import op
import sqlalchemy as sa
def upgrade():
# Add column
op.add_column('users', sa.Column('email', sa.String(255), nullable=True))
# Rename table
op.rename_table('old_table', 'new_table')
# Create index
op.create_index('ix_users_email', 'users', ['email'])
# Add constraint
op.create_check_constraint('ck_age_positive', 'users', 'age > 0')
def downgrade():
# Reverse operations
op.drop_constraint('ck_age_positive', 'users')
op.drop_index('ix_users_email')
op.rename_table('new_table', 'old_table')
op.drop_column('users', 'email')
Batch Mode (for SQLite)
Configure batch mode in env.py:
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=True # Required for SQLite migrations
)
Generated batch migration:
def upgrade():
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('email', sa.String(length=255), nullable=True))
batch_op.create_index('ix_users_email', ['email'], unique=False)
Filtering Objects
Skip certain objects in autogenerate:
def include_object(object, name, type_, reflected, compare_to):
# Skip temporary tables
if type_ == "table" and name.startswith("temp_"):
return False
# Skip columns with skip_autogenerate flag
if type_ == "column" and not reflected:
if object.info.get("skip_autogenerate", False):
return False
return True
context.configure(
connection=connection,
target_metadata=target_metadata,
include_object=include_object
)
Filter by schema:
def include_name(name, type_, parent_names):
if type_ == "schema":
return name in [None, "public", "auth"] # Include default + specific schemas
elif type_ == "table":
return parent_names["schema_qualified_table_name"] in target_metadata.tables
return True
context.configure(
connection=connection,
target_metadata=target_metadata,
include_name=include_name,
include_schemas=True
)
Custom Migration Processing
Modify generated migrations:
def process_revision_directives(context, revision, directives):
script = directives[0]
# Skip empty migrations
if config.cmd_opts.autogenerate and script.upgrade_ops.is_empty():
directives[:] = []
return
# Remove downgrade operations for one-way migrations
script.downgrade_ops.ops[:] = []
context.configure(
connection=connection,
target_metadata=target_metadata,
process_revision_directives=process_revisi
Установить alembic в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл alembic?
Database migration management for SQLAlchemy projects using Alembic
Как установить скилл alembic?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл alembic запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic