blob: 79b8174be8a33bf4aaa610a4bab01dbd7bee9d80 [file] [log] [blame]
Fatih Degirmencic2a46012019-09-30 12:07:45 +02001from __future__ import with_statement
2
3import logging
4from logging.config import fileConfig
5
6from sqlalchemy import engine_from_config
7from sqlalchemy import pool
8
9from alembic import context
10
11# this is the Alembic Config object, which provides
12# access to the values within the .ini file in use.
13config = context.config
14
15# Interpret the config file for Python logging.
16# This line sets up loggers basically.
17fileConfig(config.config_file_name)
18logger = logging.getLogger('alembic.env')
19
20# add your model's MetaData object here
21# for 'autogenerate' support
22# from myapp import mymodel
23# target_metadata = mymodel.Base.metadata
24from flask import current_app
25config.set_main_option(
26 'sqlalchemy.url', current_app.config.get(
27 'SQLALCHEMY_DATABASE_URI').replace('%', '%%'))
28target_metadata = current_app.extensions['migrate'].db.metadata
29
30# other values from the config, defined by the needs of env.py,
31# can be acquired:
32# my_important_option = config.get_main_option("my_important_option")
33# ... etc.
34
35
36def run_migrations_offline():
37 """Run migrations in 'offline' mode.
38
39 This configures the context with just a URL
40 and not an Engine, though an Engine is acceptable
41 here as well. By skipping the Engine creation
42 we don't even need a DBAPI to be available.
43
44 Calls to context.execute() here emit the given string to the
45 script output.
46
47 """
48 url = config.get_main_option("sqlalchemy.url")
49 context.configure(
50 url=url, target_metadata=target_metadata, literal_binds=True
51 )
52
53 with context.begin_transaction():
54 context.run_migrations()
55
56
57def run_migrations_online():
58 """Run migrations in 'online' mode.
59
60 In this scenario we need to create an Engine
61 and associate a connection with the context.
62
63 """
64
65 # this callback is used to prevent an auto-migration from being generated
66 # when there are no changes to the schema
67 # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
68 def process_revision_directives(context, revision, directives):
69 if getattr(config.cmd_opts, 'autogenerate', False):
70 script = directives[0]
71 if script.upgrade_ops.is_empty():
72 directives[:] = []
73 logger.info('No changes in schema detected.')
74
75 connectable = engine_from_config(
76 config.get_section(config.config_ini_section),
77 prefix='sqlalchemy.',
78 poolclass=pool.NullPool,
79 )
80
81 with connectable.connect() as connection:
82 context.configure(
83 connection=connection,
84 target_metadata=target_metadata,
85 process_revision_directives=process_revision_directives,
86 **current_app.extensions['migrate'].configure_args
87 )
88
89 with context.begin_transaction():
90 context.run_migrations()
91
92
93if context.is_offline_mode():
94 run_migrations_offline()
95else:
96 run_migrations_online()