1- from __future__ import with_statement
2-
31import logging
42from logging .config import fileConfig
53
1614fileConfig (config .config_file_name )
1715logger = logging .getLogger ('alembic.env' )
1816
17+
18+ def get_engine ():
19+ try :
20+ # this works with Flask-SQLAlchemy<3 and Alchemical
21+ return current_app .extensions ['migrate' ].db .get_engine ()
22+ except (TypeError , AttributeError ):
23+ # this works with Flask-SQLAlchemy>=3
24+ return current_app .extensions ['migrate' ].db .engine
25+
26+
27+ def get_engine_url ():
28+ try :
29+ return get_engine ().url .render_as_string (hide_password = False ).replace (
30+ '%' , '%%' )
31+ except AttributeError :
32+ return str (get_engine ().url ).replace ('%' , '%%' )
33+
34+
1935# add your model's MetaData object here
2036# for 'autogenerate' support
2137# from myapp import mymodel
2238# target_metadata = mymodel.Base.metadata
23- config .set_main_option (
24- 'sqlalchemy.url' ,
25- str (current_app .extensions ['migrate' ].db .get_engine ().url ).replace (
26- '%' , '%%' ))
27- target_metadata = current_app .extensions ['migrate' ].db .metadata
39+ config .set_main_option ('sqlalchemy.url' , get_engine_url ())
40+ target_db = current_app .extensions ['migrate' ].db
2841
2942# other values from the config, defined by the needs of env.py,
3043# can be acquired:
3144# my_important_option = config.get_main_option("my_important_option")
3245# ... etc.
3346
3447
48+ def get_metadata ():
49+ if hasattr (target_db , 'metadatas' ):
50+ return target_db .metadatas [None ]
51+ return target_db .metadata
52+
53+
3554def run_migrations_offline ():
3655 """Run migrations in 'offline' mode.
3756
@@ -46,7 +65,7 @@ def run_migrations_offline():
4665 """
4766 url = config .get_main_option ("sqlalchemy.url" )
4867 context .configure (
49- url = url , target_metadata = target_metadata , literal_binds = True
68+ url = url , target_metadata = get_metadata () , literal_binds = True
5069 )
5170
5271 with context .begin_transaction ():
@@ -71,14 +90,17 @@ def process_revision_directives(context, revision, directives):
7190 directives [:] = []
7291 logger .info ('No changes in schema detected.' )
7392
74- connectable = current_app .extensions ['migrate' ].db .get_engine ()
93+ conf_args = current_app .extensions ['migrate' ].configure_args
94+ if conf_args .get ("process_revision_directives" ) is None :
95+ conf_args ["process_revision_directives" ] = process_revision_directives
96+
97+ connectable = get_engine ()
7598
7699 with connectable .connect () as connection :
77100 context .configure (
78101 connection = connection ,
79- target_metadata = target_metadata ,
80- process_revision_directives = process_revision_directives ,
81- ** current_app .extensions ['migrate' ].configure_args
102+ target_metadata = get_metadata (),
103+ ** conf_args
82104 )
83105
84106 with context .begin_transaction ():
0 commit comments