Back to snippets
alembic_env_config_offline_online_migration_modes.py
pythonThe core environment configuration file (env.py) that initializes the
Agent Votes
0
0
alembic_env_config_offline_online_migration_modes.py
1from logging.config import fileConfig
2
3from sqlalchemy import engine_from_config
4from sqlalchemy import pool
5
6from alembic import context
7
8# this is the Alembic Config object, which provides access to the values within the .ini file in use.
9config = context.config
10
11# Interpret the config file for Python logging.
12# This line sets up loggers basically.
13if config.config_file_name is not None:
14 fileConfig(config.config_file_name)
15
16# add your model's MetaData object here for 'autogenerate' support
17# from myapp import mymodel
18# target_metadata = mymodel.Base.metadata
19target_metadata = None
20
21# other values from the config, defined by the needs of env.py,
22# can be acquired:
23# my_important_option = config.get_main_option("my_important_option")
24# ... etc.
25
26
27def run_migrations_offline() -> None:
28 """Run migrations in 'offline' mode.
29
30 This configures the context with just a URL and not an Engine,
31 though an Engine is also acceptable here. By skipping the Engine creation
32 we don't even need a DBAPI to be available.
33
34 Calls to context.execute() here emit the given string to the script output.
35 """
36 url = config.get_main_option("sqlalchemy.url")
37 context.configure(
38 url=url,
39 target_metadata=target_metadata,
40 literal_binds=True,
41 dialect_opts={"paramstyle": "named"},
42 )
43
44 with context.begin_transaction():
45 context.run_migrations()
46
47
48def run_migrations_online() -> None:
49 """Run migrations in 'online' mode.
50
51 In this scenario we need to create an Engine and associate a connection
52 with the context.
53 """
54 connectable = engine_from_config(
55 config.get_section(config.config_ini_section, {}),
56 prefix="sqlalchemy.",
57 poolclass=pool.NullPool,
58 )
59
60 with connectable.connect() as connection:
61 context.configure(
62 connection=connection, target_metadata=target_metadata
63 )
64
65 with context.begin_transaction():
66 context.run_migrations()
67
68
69if context.is_offline_mode():
70 run_migrations_offline()
71else:
72 run_migrations_online()