Commit 5f463a94 authored by Hugo Kerstens's avatar Hugo Kerstens

Implement alembic for migration

parent 3ac65d05
# A generic, single database configuration.
[alembic]
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
from __future__ import with_statement
import logging
import sys
import os
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
from flask import current_app
sys.path.append(os.getcwd())
from zesje.database import db # noqa: E402
config = context.config
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')
config.set_main_option('sqlalchemy.url',
current_app.config.get('SQLALCHEMY_DATABASE_URI'))
target_metadata = db.metadata
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(url=url)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
def process_revision_directives(context, revision, directives):
if getattr(config.cmd_opts, 'autogenerate', False):
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
logger.info('No changes in schema detected.')
engine = engine_from_config(config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool)
connection = engine.connect()
context.configure(connection=connection,
target_metadata=target_metadata,
process_revision_directives=process_revision_directives,
**current_app.extensions['migrate'].configure_args)
try:
with context.begin_transaction():
context.run_migrations()
except Exception as exception:
logger.error(exception)
raise exception
finally:
connection.close()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
""" ${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}
This diff is collapsed.
......@@ -13,7 +13,9 @@
"lint:py": "flake8",
"test:py": "python3 -m pytest -v -W error::RuntimeWarning",
"start": "ZESJE_SETTINGS=$(pwd)/zesje.dev.cfg python3 zesje",
"analyze": "webpack --config webpack.prod.js --profile --json > stats.json; webpack-bundle-analyzer stats.json zesje/static"
"analyze": "webpack --config webpack.prod.js --profile --json > stats.json; webpack-bundle-analyzer stats.json zesje/static",
"migrate:dev": "ZESJE_SETTINGS=$(pwd)/zesje.dev.cfg flask db upgrade",
"migrate": "flask db upgrade"
},
"standard": {
"parser": "babel-eslint",
......
......@@ -4,6 +4,7 @@ import os
from os.path import abspath, dirname
from flask import Flask
from flask_migrate import Migrate
from werkzeug.exceptions import NotFound
from .api import api_bp
......@@ -31,7 +32,7 @@ app.config.update(
# These reference DATA_DIRECTORY, so they need to be in a separate update
app.config.update(
SCAN_DIRECTORY=os.path.join(app.config['DATA_DIRECTORY'], 'scans'),
DB_PATH=os.path.join(app.config['DATA_DIRECTORY'], 'database.sqlite'),
DB_PATH=os.path.join(app.config['DATA_DIRECTORY'], 'course.sqlite'),
)
app.config.update(
......@@ -39,15 +40,11 @@ app.config.update(
SQLALCHEMY_TRACK_MODIFICATIONS=False # Suppress future deprecation warning
)
os.makedirs(app.config['DATA_DIRECTORY'], exist_ok=True)
os.makedirs(app.config['SCAN_DIRECTORY'], exist_ok=True)
@app.before_first_request
def setup():
os.makedirs(app.config['DATA_DIRECTORY'], exist_ok=True)
os.makedirs(app.config['SCAN_DIRECTORY'], exist_ok=True)
db.init_app(app)
db.create_all()
db.session.commit()
db.init_app(app)
migrate = Migrate(app, db)
@app.route('/')
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment