Creating a Migration Tool
The user wants a Python tool for database migrations using Alembic, but it’s open-ended. I should clarify if they use SQLAlchemy models or what type of database they have. I’ll aim for a general solution that includes a simple script, alembic.ini, and env.py. It might involve building a custom script that uses a Python API instead of CLI commands. I think I should propose a small CLI with Typer or argparse to wrap the Alembic API.Structuring the Migration Tool
I want to include multi-database support and keep explanations clear. I need to ensure compatibility with the knowledge cutoff of October 2024, but since Alembic is stable, that helps.
For the project layout, I'll set it up with dedicated folders for app, migrations, and configurations. I'll import necessary Alembic components in the db_tool.py and use environment variables for the database URL.
I think I should implement the upgrade, downgrade, and autogenerate revision features using argparse for a neat CLI. I also need to configure env.py to import models. Let's start with that!Installing Dependencies and CLI Setup
To get started, I'd show how to install the necessary dependencies with pip install alembic sqlalchemy. Next, I need to provide a sample models/db.py and outline the content for alembic/env.py, which links to the models' Base.
For the db_tool.py, I can set up a CLI wrapper with argparse. I'll create functions for upgrading and downgrading migrations, configuring the database URL, and managing revisions. I should also ensure to include how to run the script with usage examples for clarity, since the user is looking for both code and instructions.Creating the Migration Tool
I should focus on producing the script content and providing a clear explanation of how it works. Since the user might need to handle concurrency, I’ll keep that in mind as we go.
Let’s design a tool called "migrate.py" or use a "manage.py db" style. Although they didn't request env.py code, it’s essential for migrations, so I'll include a minimal version for autogenerate purposes.
I'll specify how to initialize Alembic using alembic init migrations, which they might run first. Then, I'll provide clean steps: Step 1 is initializing Alembic, and Step 2 is implementing the Python tool to wrap alembic.command.Designing a Python Migration Tool
I want to create a fully in-Python migration tool using Alembic. To accommodate users who might want to avoid the CLI, I’ll show how to check if the migrations directory exists and call command.init(config, "migrations") if it doesn't.
However, I'll assume they might use the CLI once to initialize Alembic, so I will guide them through the steps:
- Install libraries.
- Set up SQLAlchemy and provide a snippet.
- Run
alembic init migrations to create necessary files.
- Configure
env.py by importing the Base and assigning target_metadata.
- Build the
db_tool.py script.
This script will load the Alembic Config, set the database URL, and offer CLI commands for revisions or upgrades. I’ll provide example commands and ensure the tool is self-contained. For the autogeneration, I'll include a snippet that uses target_metadata. Also, I'll explain where to obtain the database URL from environment variables or the Alembic config.
This way, they can easily copy the script, and it should work seamlessly with the standard Alembic initialization. Below is a minimal but practical way to build a Python-based migration tool around Alembic.
The idea:
- Use Alembic under the hood (its normal migration system).
- Wrap it in a Python CLI (
db_tool.py) so you can run python db_tool.py upgrade head, revision, downgrade, etc.
- Keep it configurable via environment variables (e.g.,
DATABASE_URL).
1. Install dependencies
pip install alembic sqlalchemy
(If you already have them, you can skip this.)
2. Set up SQLAlchemy models (if you don’t already have them)
Example layout:
your_project/
app/
__init__.py
db.py
models.py
migrations/ # will be created by Alembic
alembic.ini # will be created by Alembic
db_tool.py # the tool we’re building
app/db.py:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
import os
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///app.db")
engine = create_engine(DATABASE_URL, future=True)
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, future=True)
Base = declarative_base()
app/models.py (example):
from sqlalchemy import Column, Integer, String
from .db import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
email = Column(String, unique=True, nullable=False)
3. Initialize Alembic
From the project root (your_project/):
alembic init migrations
This creates:
alembic.ini
migrations/
env.py
script.py.mako
versions/ (empty)
We’ll wire this to your SQLAlchemy models next.
4. Configure migrations/env.py for autogeneration
Edit migrations/env.py to import your Base and set target_metadata.
Near the top, add imports:
import os
import sys
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# Make sure 'app' package is importable
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from app.db import Base # <-- your Base
# Optionally import models so they’re registered
from app import models # noqa
config = context.config
fileConfig(config.config_file_name)
target_metadata = Base.metadata
Make sure target_metadata = Base.metadata is set (this is what autogenerate uses).
Leave the rest of env.py as Alembic generated it, except maybe this part in run_migrations_online and run_migrations_offline where it uses config.get_main_option("sqlalchemy.url"). We’ll set that from our Python tool.
5. Build the Python migration tool (db_tool.py)
Create db_tool.py in the project root:
import os
import argparse
from pathlib import Path
from alembic import command
from alembic.config import Config
BASE_DIR = Path(__file__).resolve().parent
ALEMBIC_INI_PATH = BASE_DIR / "alembic.ini"
MIGRATIONS_DIR = BASE_DIR / "migrations"
def get_alembic_config(database_url: str | None = None) -> Config:
"""
Create and return an Alembic Config object, wired to our project paths
and database URL.
"""
if not ALEMBIC_INI_PATH.exists():
raise RuntimeError(f"alembic.ini not found at {ALEMBIC_INI_PATH}")
cfg = Config(str(ALEMBIC_INI_PATH))
# Explicitly set script_location to the migrations directory
cfg.set_main_option("script_location", str(MIGRATIONS_DIR))
# Allow overriding DB URL via argument or env var
db_url = (
database_url
or os.getenv("DATABASE_URL")
or cfg.get_main_option("sqlalchemy.url") # fallback to ini
)
if not db_url:
raise RuntimeError("No database URL set. Use DATABASE_URL env or alembic.ini.")
cfg.set_main_option("sqlalchemy.url", db_url)
# Make sure Alembic treats project root as current working dir
# (so imports in env.py work as expected)
os.chdir(BASE_DIR)
return cfg
def cmd_upgrade(args: argparse.Namespace) -> None:
cfg = get_alembic_config(args.database_url)
command.upgrade(cfg, args.revision)
def cmd_downgrade(args: argparse.Namespace) -> None:
cfg = get_alembic_config(args.database_url)
command.downgrade(cfg, args.revision)
def cmd_revision(args: argparse.Namespace) -> None:
cfg = get_alembic_config(args.database_url)
command.revision(
cfg,
message=args.message,
autogenerate=args.autogenerate,
head=args.head,
branch_label=args.branch_label,
version_path=None,
)
def cmd_current(args: argparse.Namespace) -> None:
cfg = get_alembic_config(args.database_url)
command.current(cfg, verbose=not args.quiet)
def cmd_history(args: argparse.Namespace) -> None:
cfg = get_alembic_config(args.database_url)
command.history(cfg, rev_range=args.rev_range, verbose=not args.quiet)
def cmd_stamp(args: argparse.Namespace) -> None:
cfg = get_alembic_config(args.database_url)
command.stamp(cfg, args.revision)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Database migration tool powered by Alembic."
)
parser.add_argument(
"--database-url", "-d",
help="Database URL (overrides DATABASE_URL env and alembic.ini).",
)
subparsers = parser.add_subparsers(dest="command", required=True)
# upgrade
p_up = subparsers.add_parser("upgrade", help="Upgrade to a later version.")
p_up.add_argument("revision", nargs="?", default="head",
help="Revision to upgrade to (default: head).")
p_up.set_defaults(func=cmd_upgrade)
# downgrade
p_down = subparsers.add_parser("downgrade", help="Revert to a previous version.")
p_down.add_argument("revision", help="Revision identifier (e.g., -1, base, <rev>).")
p_down.set_defaults(func=cmd_downgrade)
# revision
p_rev = subparsers.add_parser("revision", help="Create a new migration script.")
p_rev.add_argument("-m", "--message", required=True, help="Revision message.")
p_rev.add_argument(
"--autogenerate",
action="store_true",
help="Autogenerate script from SQLAlchemy models.",
)
p_rev.add_argument(
"--head",
default="head",
help="Head to base the new revision on (default: head).",
)
p_rev.add_argument(
"--branch-label",
help="Branch label for this revision.",
)
p_rev.set_defaults(func=cmd_revision)
# current
p_current = subparsers.add_parser("current", help="Show current revision.")
p_current.add_argument(
"-q", "--quiet", action="store_true", help="Less verbose output."
)
p_current.set_defaults(func=cmd_current)
# history
p_hist = subparsers.add_parser("history", help="Show revision history.")
p_hist.add_argument(
"rev_range",
nargs="?",
default=None,
help="Optional revision range (e.g., base:head, -5:head).",
)
p_hist.add_argument(
"-q", "--quiet", action="store_true", help="Less verbose output."
)
p_hist.set_defaults(func=cmd_history)
# stamp
p_stamp = subparsers.add_parser(
"stamp", help="Stamp the database with a specific revision without running migrations."
)
p_stamp.add_argument("revision", help="Revision to stamp (e.g., head, base, <rev>).")
p_stamp.set_defaults(func=cmd_stamp)
return parser
def main() -> None:
parser = build_parser()
args = parser.parse_args()
args.func(args)
if __name__ == "__main__":
main()
6. Usage examples
Set your database URL (optional if you put it in alembic.ini):
export DATABASE_URL="postgresql+psycopg2://user:pass@localhost:5432/mydb"
Then run:
# Create a new migration (autogenerate from models)
python db_tool.py revision -m "create users table" --autogenerate
# Apply all pending migrations
python db_tool.py upgrade head
# Downgrade one revision
python db_tool.py downgrade -1
# Show current database revision
python db_tool.py current
# Show migration history
python db_tool.py history
# Stamp the DB as up-to-date without applying migrations (dangerous, use carefully)
python db_tool.py stamp head
# Override DB URL just for this command
python db_tool.py --database-url sqlite:///tmp.db upgrade head
If you share how your project is structured (especially where your models and Base live), I can tailor the env.py and db_tool.py snippets exactly to your setup.