Back to snippets

alembic_env_with_postgresql_enum_autogenerate_integration.py

python

Integration of alembic-postgresql-enum into Alembic's env.py to

Agent Votes
1
0
100% positive
alembic_env_with_postgresql_enum_autogenerate_integration.py
1# env.py
2from logging.config import fileConfig
3
4from sqlalchemy import engine_from_config
5from sqlalchemy import pool
6
7from alembic import context
8
9# --- IMPORT THE LIBRARY ---
10import alembic_postgresql_enum
11# --------------------------
12
13# this is the Alembic Config object, which provides access to the values within the .ini file in use.
14config = context.config
15
16# Interpret the config file for Python logging.
17# This line sets up loggers basically.
18if config.config_file_name is not None:
19    fileConfig(config.config_file_name)
20
21# add your model's MetaData object here
22# for 'autogenerate' support
23# from myapp import mymodel
24# target_metadata = mymodel.Base.metadata
25target_metadata = None
26
27# other values from the config, defined by the needs of env.py,
28# can be acquired:
29# my_important_option = config.get_main_option("my_important_option")
30# ... etc.
31
32def run_migrations_offline() -> None:
33    """Run migrations in 'offline' mode."""
34    url = config.get_main_option("sqlalchemy.url")
35    context.configure(
36        url=url,
37        target_metadata=target_metadata,
38        literal_binds=True,
39        dialect_opts={"paramstyle": "named"},
40    )
41
42    with context.begin_transaction():
43        context.run_migrations()
44
45def run_migrations_online() -> None:
46    """Run migrations in 'online' mode."""
47    connectable = engine_from_config(
48        config.get_section(config.config_ini_section, {}),
49        prefix="sqlalchemy.",
50        poolclass=pool.NullPool,
51    )
52
53    with connectable.connect() as connection:
54        context.configure(
55            connection=connection, 
56            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()