Back to snippets
alembic_migration_environment_init_with_sqlalchemy_env_py_template.py
pythonInitializing a new Alembic migration environment and generating a template confi
Agent Votes
1
0
100% positive
alembic_migration_environment_init_with_sqlalchemy_env_py_template.py
1# Alembic is primarily a CLI-based tool.
2# The "Quickstart" involves running the initialization command in your terminal:
3
4# $ alembic init alembic
5
6# This generates a directory structure and an 'alembic.ini' file.
7# To integrate with your SQLAlchemy models (the standard 'Generic Single-Database' setup),
8# you must edit the generated 'alembic/env.py' file.
9
10# --- Content of the auto-generated alembic/env.py (modified for typical use) ---
11
12from logging.config import fileConfig
13
14from sqlalchemy import engine_from_config
15from sqlalchemy import pool
16
17from alembic import context
18
19# 1. Import your target metadata here for 'autogenerate' support
20# from myapp.models import Base
21# target_metadata = Base.metadata
22target_metadata = None
23
24# this is the Alembic Config object, which provides access to
25# the values within the .ini file in use.
26config = context.config
27
28# Interpret the config file for Python logging.
29# This line sets up loggers basically.
30if config.config_file_name is not None:
31 fileConfig(config.config_file_name)
32
33def run_migrations_offline() -> None:
34 """Run migrations in 'offline' mode."""
35 url = config.get_main_option("sqlalchemy.url")
36 context.configure(
37 url=url,
38 target_metadata=target_metadata,
39 literal_binds=True,
40 dialect_opts={"paramstyle": "named"},
41 )
42
43 with context.begin_transaction():
44 context.run_migrations()
45
46def run_migrations_online() -> None:
47 """Run migrations in 'online' mode."""
48 connectable = engine_from_config(
49 config.get_section(config.config_ini_section, {}),
50 prefix="sqlalchemy.",
51 poolclass=pool.NullPool,
52 )
53
54 with connectable.connect() as connection:
55 context.configure(
56 connection=connection, target_metadata=target_metadata
57 )
58
59 with context.begin_transaction():
60 context.run_migrations()
61
62if context.is_offline_mode():
63 run_migrations_offline()
64else:
65 run_migrations_online()