NoteApi

Форк
0
90 строк · 2.7 Кб
1
from __future__ import with_statement
2

3
import logging
4
from logging.config import fileConfig
5

6
from flask import current_app
7

8
from alembic import context
9

10
# this is the Alembic Config object, which provides
11
# access to the values within the .ini file in use.
12
config = context.config
13

14
# Interpret the config file for Python logging.
15
# This line sets up loggers basically.
16
fileConfig(config.config_file_name)
17
logger = logging.getLogger('alembic.env')
18

19
# add your model's MetaData object here
20
# for 'autogenerate' support
21
# from myapp import mymodel
22
# target_metadata = mymodel.Base.metadata
23
config.set_main_option(
24
    'sqlalchemy.url',
25
    str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%'))
26
target_metadata = current_app.extensions['migrate'].db.metadata
27

28
# other values from the config, defined by the needs of env.py,
29
# can be acquired:
30
# my_important_option = config.get_main_option("my_important_option")
31
# ... etc.
32

33

34
def run_migrations_offline():
35
    """Run migrations in 'offline' mode.
36

37
    This configures the context with just a URL
38
    and not an Engine, though an Engine is acceptable
39
    here as well.  By skipping the Engine creation
40
    we don't even need a DBAPI to be available.
41

42
    Calls to context.execute() here emit the given string to the
43
    script output.
44

45
    """
46
    url = config.get_main_option("sqlalchemy.url")
47
    context.configure(
48
        url=url, target_metadata=target_metadata, literal_binds=True
49
    )
50

51
    with context.begin_transaction():
52
        context.run_migrations()
53

54

55
def run_migrations_online():
56
    """Run migrations in 'online' mode.
57

58
    In this scenario we need to create an Engine
59
    and associate a connection with the context.
60

61
    """
62

63
    # this callback is used to prevent an auto-migration from being generated
64
    # when there are no changes to the schema
65
    # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
66
    def process_revision_directives(context, revision, directives):
67
        if getattr(config.cmd_opts, 'autogenerate', False):
68
            script = directives[0]
69
            if script.upgrade_ops.is_empty():
70
                directives[:] = []
71
                logger.info('No changes in schema detected.')
72

73
    connectable = current_app.extensions['migrate'].db.engine
74

75
    with connectable.connect() as connection:
76
        context.configure(
77
            connection=connection,
78
            target_metadata=target_metadata,
79
            process_revision_directives=process_revision_directives,
80
            **current_app.extensions['migrate'].configure_args
81
        )
82

83
        with context.begin_transaction():
84
            context.run_migrations()
85

86

87
if context.is_offline_mode():
88
    run_migrations_offline()
89
else:
90
    run_migrations_online()
91

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.