#!/usr/bin/env python3
"""
Alembic Migration Tool
======================
A simple Click-based CLI wrapper around Alembic for managing database migrations.
Requirements:
- pip install alembic sqlalchemy click
Usage:
python migrate.py init # Initialize Alembic
python migrate.py revision -m "init" --autogenerate
python migrate.py upgrade head
python migrate.py current
...
After `init`:
1. Edit `alembic/env.py`: Set `target_metadata = YourAppBase.metadata` (import your SQLAlchemy Base).
2. Edit `alembic.ini`: Set `sqlalchemy.url = your_database_url`.
"""
import os
import sys
import subprocess
import click
from pathlib import Path
from alembic.config import Config
from alembic import command
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
@click.version_option("1.0")
def cli():
"""Alembic-powered database migration tool."""
def _get_config(config_file, url=None):
if config_file:
config_path = Path(config_file)
if not config_path.exists():
raise click.BadParameter(f"Config file '{config_file}' not found.")
cfg = Config(str(config_path))
else:
# Auto-detect alembic.ini or pyproject.toml (Alembic supports it)
for fname in ("alembic.ini", "pyproject.toml"):
if os.path.exists(fname):
cfg = Config(fname)
break
else:
raise click.UsageError(
"No Alembic config found. Run 'init' first or use --config."
)
if url:
cfg.set_main_option("sqlalchemy.url", url)
return cfg
@cli.command()
@click.argument("directory", nargs=1, required=False, default="alembic")
def init(directory):
"""Initialize Alembic migrations in DIRECTORY (default: alembic)."""
directory = Path(directory)
if directory.exists():
if not click.confirm(f"Directory '{directory}' exists. Overwrite?", abort=True):
return
import shutil
shutil.rmtree(directory)
try:
subprocess.check_call(
[sys.executable, "-m", "alembic", "init", str(directory)]
)
click.echo(click.style(f"✓ Alembic initialized in {directory}", fg="green"))
click.echo(
click.style(
"""
Next steps:
1. Edit alembic/env.py:
- Import your SQLAlchemy models: from yourapp.models import Base
- Set: target_metadata = Base.metadata
2. Edit alembic.ini:
- Set: sqlalchemy.url = postgresql://user:pass@localhost/dbname
(or sqlite:///./app.db, etc.)
3. Generate first migration: python migrate.py revision -m "create initial tables" --autogenerate
""",
fg="yellow",
)
)
except subprocess.CalledProcessError:
click.echo(
click.style(
"✗ Failed to initialize. Ensure Alembic is installed:\n"
"pip install alembic",
fg="red",
)
)
sys.exit(1)
@cli.command()
@click.option(
"-c",
"--config",
"config_file",
type=click.Path(exists=True),
metavar="FILE",
help="Alembic config file (default: alembic.ini)",
)
@click.option("--url", "-u", metavar="URL", help="Database URL (overrides config)")
def current(config_file, url):
"""Display the current revision."""
cfg = _get_config(config_file, url)
command.current(cfg)
@cli.command()
@click.option(
"-c",
"--config",
"config_file",
type=click.Path(exists=True),
metavar="FILE",
)
@click.option("--url", "-u", metavar="URL")
@click.option("--verbose", "-v", is_flag=True)
def status(config_file, url, verbose):
"""Display the current migration status."""
cfg = _get_config(config_file, url)
command.status(cfg, verbose=verbose)
@cli.command()
@click.option(
"-c",
"--config",
"config_file",
type=click.Path(exists=True),
metavar="FILE",
)
@click.option("--url", "-u", metavar="URL")
@click.option("--verbose", "-v", is_flag=True)
def history(config_file, url, verbose):
"""List changeset history."""
cfg = _get_config(config_file, url)
command.history(cfg, verbose=verbose)
@cli.command()
@click.option(
"-c",
"--config",
"config_file",
type=click.Path(exists=True),
metavar="FILE",
)
@click.option("--url", "-u", metavar="URL")
def heads(config_file, url):
"""Show current heads."""
cfg = _get_config(config_file, url)
command.heads(cfg)
@cli.command()
@click.argument("revision")
@click.option(
"-c",
"--config",
"config_file",
type=click.Path(exists=True),
metavar="FILE",
)
@click.option("--url", "-u", metavar="URL")
def show(revision, config_file, url):
"""Show the revision for REVISION."""
cfg = _get_config(config_file, url)
command.show(cfg, revision)
@cli.command()
@click.argument("revision", nargs=1, required=False, default="head")
@click.option("--sql", is_flag=True, help="Don't emit SQL to DB; dump to stdout/file.")
@click.option(
"-c",
"--config",
"config_file",
type=click.Path(exists=True),
metavar="FILE",
)
@click.option("--url", "-u", metavar="URL")
def upgrade(revision, sql, config_file, url):
"""Upgrade to REVISION (default: head)."""
cfg = _get_config(config_file, url)
command.upgrade(cfg, revision, sql=sql)
@cli.command()
@click.argument("revision", nargs=1, required=False, default="base")
@click.option("--sql", is_flag=True, help="Don't emit SQL to DB; dump to stdout/file.")
@click.option(
"-c",
"--config",
"config_file",
type=click.Path(exists=True),
metavar="FILE",
)
@click.option("--url", "-u", metavar="URL")
def downgrade(revision, sql, config_file, url):
"""Downgrade to REVISION (default: base)."""
cfg = _get_config(config_file, url)
command.downgrade(cfg, revision, sql=sql)
@cli.command()
@click.option("-m", "--message", "message", required=True, help="Revision message.")
@click.option(
"--autogenerate",
"-a",
"autogenerate",
is_flag=True,
help="Auto-generate based on schema changes.",
)
@click.option(
"--sql",
is_flag=True,
help="SQL mode; generate SQL scripts but don't run.",
)
@click.option(
"-c",
"--config",
"config_file",
type=click.Path(exists=True),
metavar="FILE",
)
@click.option("--url", "-u", metavar="URL")
def revision(message, autogenerate, sql, config_file, url):
"""Create a new revision file."""
cfg = _get_config(config_file, url)
command.revision(cfg, autogenerate=autogenerate, sql=sql, message=message)
if __name__ == "__main__":
cli()
Usage Examples
-
Install dependencies:
pip install alembic sqlalchemy click
-
Save the script as migrate.py and make executable (chmod +x migrate.py).
-
Initialize:
./migrate.py init
-
Configure (edit alembic.ini and alembic/env.py as instructed).
-
Create migration:
./migrate.py revision -m "Create users table" --autogenerate
-
Apply migration:
./migrate.py upgrade head
-
Check status:
./migrate.py status
./migrate.py current
-
Override DB URL (without editing config):
./migrate.py upgrade head --url "sqlite:///./test.db"
This tool provides a clean, self-contained CLI for Alembic operations, with auto-detection of config files and helpful error messages. Extend it by adding more @cli.command() for advanced features like merge or batch.