Provide a better manager API for Alembic.

This commit is contained in:
Berker Peksag 2014-08-15 15:39:45 +03:00
parent 65f20ca435
commit de51eca53f

View File

@ -16,16 +16,21 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import logging
import os import os
from alembic import command from alembic import command
from alembic.config import Config from alembic.config import Config
from alembic.migration import MigrationContext
from mediagoblin.db.base import Base from mediagoblin.db.base import Base
from mediagoblin.tools.common import simple_printer from mediagoblin.tools.common import simple_printer
from sqlalchemy import Table from sqlalchemy import Table
from sqlalchemy.sql import select from sqlalchemy.sql import select
log = logging.getLogger(__name__)
class TableAlreadyExists(Exception): class TableAlreadyExists(Exception):
pass pass
@ -39,18 +44,34 @@ class AlembicMigrationManager(object):
self.alembic_cfg = Config(alembic_cfg_path) self.alembic_cfg = Config(alembic_cfg_path)
self.session = session self.session = session
def get_current_revision(self):
context = MigrationContext.configure(self.session.bind)
return context.get_current_revision()
def upgrade(self, version):
return command.upgrade(self.alembic_cfg, version or 'head')
def downgrade(self, version):
if isinstance(version, int) or version is None or version.isdigit():
version = 'base'
return command.downgrade(self.alembic_cfg, version)
def stamp(self, revision):
return command.stamp(self.alembic_cfg, revision=revision)
def init_tables(self): def init_tables(self):
Base.metadata.create_all(self.session.bind) Base.metadata.create_all(self.session.bind)
# load the Alembic configuration and generate the # load the Alembic configuration and generate the
# version table, "stamping" it with the most recent rev: # version table, "stamping" it with the most recent rev:
command.stamp(self.alembic_cfg, 'head') command.stamp(self.alembic_cfg, 'head')
def init_or_migrate(self, version='head'): def init_or_migrate(self, version=None):
# TODO(berker): Check this if self.get_current_revision() is None:
# http://alembic.readthedocs.org/en/latest/api.html#alembic.migration.MigrationContext log.info('Initializing tables and stamping it with '
# current_rev = context.get_current_revision() 'the most recent migration...')
# Call self.init_tables() first if current_rev is None? self.init_tables()
command.upgrade(self.alembic_cfg, version) else:
self.upgrade(version)
class MigrationManager(object): class MigrationManager(object):