Switch to unified view

a b/pyforge/flyway/migrate.py
1
import logging
2
3
log = logging.getLogger(__name__)
4
5
class MigrationMeta(type):
6
    '''Metaclass providing a registry of migrations.
7
8
    If the class-level variable _current_migrations_module is
9
    defined, then migrations will be registered according to that
10
    module and their declared version.  (The migrate command
11
    sets this module according to the migration's entry point name.)
12
    '''
13
14
    def __init__(cls, name, bases, dct):
15
        if cls._current_migrations_module is None: return
16
        cls.migrations_registry[
17
            cls._current_migrations_module, cls.version] = cls
18
        cls.module = cls._current_migrations_module
19
20
    def get(cls, module, version):
21
        '''Load a Migration class from the registry'''
22
        return cls.migrations_registry[module, version]
23
24
    def latest_versions(cls):
25
        result = {}
26
        for k,v in cls.migrations_registry:
27
            if result.get(k, -1) < v:
28
                result[k] = v
29
        return result
30
31
class Migration(object):
32
    __metaclass__ = MigrationMeta
33
    version = 0
34
    module = None # filled in automatically by Metaclass
35
    migrations_registry = {}
36
    _current_migrations_module = None
37
38
39
    def __init__(self, session):
40
        self.session = session
41
42
    def requires(self):
43
        '''Returns a list of requirements that must be met before upgrading to
44
        this migration.  By default, returns the previous-versioned migration'''
45
        return [ (self.module, self.version-1) ]
46
47
    def up(self):
48
        '''Upgrade to a new schema version'''
49
        raise NotImplementedError, 'up'
50
51
    def down(self):
52
        '''Downgrade from this schema version (undo an 'up') '''
53
        raise NotImplementedError, 'down'
54
55
    def ensure_index(self, cls, fields, **kwargs):
56
        '''Ensures that a particular index has been created in the DB'''
57
        self.session.ensure_index(cls, fields, **kwargs)
58
59
    def drop_index(self, cls, fields):
60
        '''Ensures that a particular index has been dropped from  the DB'''
61
        self.session.drop_index(cls, fields)
62
63
    def set_indexes(self, cls):
64
        '''Ensures that a the only indexes on a class are those defined in its
65
        __mongometa__ attribute.'''
66
        self.session.drop_indexes(cls)
67
        self.session.ensure_indexes(cls)
68