from __future__ import with_statement
from alembic import context
from logging.config import fileConfig
from sqlalchemy import engine_from_config, pool

from app import create_app
from app.extensions import db

config = context.config
fileConfig(config.config_file_name)
app = create_app()

target_metadata = db.metadata

with app.app_context():
    def run_migrations_offline():
        context.configure(url=app.config['SQLALCHEMY_DATABASE_URI'], target_metadata=target_metadata, literal_binds=True)
        with context.begin_transaction():
            context.run_migrations()

    def run_migrations_online():
        connectable = engine_from_config(config.get_section(config.config_ini_section), prefix='sqlalchemy.')
        with connectable.connect() as connection:
            context.configure(connection=connection, target_metadata=target_metadata)
            with context.begin_transaction():
                context.run_migrations()

    if context.is_offline_mode():
        run_migrations_offline()
    else:
        run_migrations_online()
