summaryrefslogtreecommitdiff
path: root/tools/db/schema_diff.py
blob: bb389532f0535adaa9723992983886d2df94e26d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#!/usr/bin/env python
# Copyright 2012 OpenStack Foundation
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""
Utility for diff'ing two versions of the DB schema.

Each release cycle the plan is to compact all of the migrations from that
release into a single file. This is a manual and, unfortunately, error-prone
process. To ensure that the schema doesn't change, this tool can be used to
diff the compacted DB schema to the original, uncompacted form.

The database is specified by providing a SQLAlchemy connection URL WITHOUT the
database-name portion (that will be filled in automatically with a temporary
database name).

The schema versions are specified by providing a git ref (a branch name or
commit hash) and a SQLAlchemy-Migrate version number:

Run like:

    MYSQL:

    ./tools/db/schema_diff.py mysql+pymysql://root@localhost \
                              master:latest my_branch:82

    POSTGRESQL:

    ./tools/db/schema_diff.py postgresql://localhost \
                              master:latest my_branch:82

"""

from __future__ import print_function

import datetime
import glob
import os
import subprocess
import sys

from nova.i18n import _


# Dump


def dump_db(db_driver, db_name, db_url, migration_version, dump_filename):
    if not db_url.endswith('/'):
        db_url += '/'

    db_url += db_name

    db_driver.create(db_name)
    try:
        _migrate(db_url, migration_version)
        db_driver.dump(db_name, dump_filename)
    finally:
        db_driver.drop(db_name)


# Diff


def diff_files(filename1, filename2):
    pipeline = ['diff -U 3 %(filename1)s %(filename2)s'
                % {'filename1': filename1, 'filename2': filename2}]

    # Use colordiff if available
    if subprocess.call(['which', 'colordiff']) == 0:
        pipeline.append('colordiff')

    pipeline.append('less -R')

    cmd = ' | '.join(pipeline)
    subprocess.check_call(cmd, shell=True)


# Database


class Mysql(object):
    def create(self, name):
        subprocess.check_call(['mysqladmin', '-u', 'root', 'create', name])

    def drop(self, name):
        subprocess.check_call(['mysqladmin', '-f', '-u', 'root', 'drop', name])

    def dump(self, name, dump_filename):
        subprocess.check_call(
                'mysqldump -u root %(name)s > %(dump_filename)s'
                % {'name': name, 'dump_filename': dump_filename},
                shell=True)


class Postgresql(object):
    def create(self, name):
        subprocess.check_call(['createdb', name])

    def drop(self, name):
        subprocess.check_call(['dropdb', name])

    def dump(self, name, dump_filename):
        subprocess.check_call(
                'pg_dump %(name)s > %(dump_filename)s'
                % {'name': name, 'dump_filename': dump_filename},
                shell=True)


def _get_db_driver_class(db_url):
    try:
        return globals()[db_url.split('://')[0].capitalize()]
    except KeyError:
        raise Exception(_("database %s not supported") % db_url)


# Migrate


MIGRATE_REPO = os.path.join(os.getcwd(), "nova/db/sqlalchemy/migrate_repo")


def _migrate(db_url, migration_version):
    earliest_version = _migrate_get_earliest_version()

    # NOTE(sirp): sqlalchemy-migrate currently cannot handle the skipping of
    # migration numbers.
    _migrate_cmd(
            db_url, 'version_control', str(earliest_version - 1))

    upgrade_cmd = ['upgrade']
    if migration_version != 'latest':
        upgrade_cmd.append(str(migration_version))

    _migrate_cmd(db_url, *upgrade_cmd)


def _migrate_cmd(db_url, *cmd):
    manage_py = os.path.join(MIGRATE_REPO, 'manage.py')

    args = ['python', manage_py]
    args += cmd
    args += ['--repository=%s' % MIGRATE_REPO,
             '--url=%s' % db_url]

    subprocess.check_call(args)


def _migrate_get_earliest_version():
    versions_glob = os.path.join(MIGRATE_REPO, 'versions', '???_*.py')

    versions = []
    for path in glob.iglob(versions_glob):
        filename = os.path.basename(path)
        prefix = filename.split('_', 1)[0]
        try:
            version = int(prefix)
        except ValueError:
            pass
        versions.append(version)

    versions.sort()
    return versions[0]


# Git


def git_current_branch_name():
    ref_name = git_symbolic_ref('HEAD', quiet=True)
    current_branch_name = ref_name.replace('refs/heads/', '')
    return current_branch_name


def git_symbolic_ref(ref, quiet=False):
    args = ['git', 'symbolic-ref', ref]
    if quiet:
        args.append('-q')
    proc = subprocess.Popen(args, stdout=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    return stdout.strip()


def git_checkout(branch_name):
    subprocess.check_call(['git', 'checkout', branch_name])


def git_has_uncommited_changes():
    return subprocess.call(['git', 'diff', '--quiet', '--exit-code']) == 1


# Command


def die(msg):
    print("ERROR: %s" % msg, file=sys.stderr)
    sys.exit(1)


def usage(msg=None):
    if msg:
        print("ERROR: %s" % msg, file=sys.stderr)

    prog = "schema_diff.py"
    args = ["<db-url>", "<orig-branch:orig-version>",
            "<new-branch:new-version>"]

    print("usage: %s %s" % (prog, ' '.join(args)), file=sys.stderr)
    sys.exit(1)


def parse_options():
    try:
        db_url = sys.argv[1]
    except IndexError:
        usage("must specify DB connection url")

    try:
        orig_branch, orig_version = sys.argv[2].split(':')
    except IndexError:
        usage('original branch and version required (e.g. master:82)')

    try:
        new_branch, new_version = sys.argv[3].split(':')
    except IndexError:
        usage('new branch and version required (e.g. master:82)')

    return db_url, orig_branch, orig_version, new_branch, new_version


def main():
    timestamp = datetime.datetime.utcnow().strftime("%Y%m%d_%H%M%S")

    ORIG_DB = 'orig_db_%s' % timestamp
    NEW_DB = 'new_db_%s' % timestamp

    ORIG_DUMP = ORIG_DB + ".dump"
    NEW_DUMP = NEW_DB + ".dump"

    options = parse_options()
    db_url, orig_branch, orig_version, new_branch, new_version = options

    # Since we're going to be switching branches, ensure user doesn't have any
    # uncommitted changes
    if git_has_uncommited_changes():
        die("You have uncommitted changes. Please commit them before running "
            "this command.")

    db_driver = _get_db_driver_class(db_url)()

    users_branch = git_current_branch_name()
    git_checkout(orig_branch)

    try:
        # Dump Original Schema
        dump_db(db_driver, ORIG_DB, db_url, orig_version, ORIG_DUMP)

        # Dump New Schema
        git_checkout(new_branch)
        dump_db(db_driver, NEW_DB, db_url, new_version, NEW_DUMP)

        diff_files(ORIG_DUMP, NEW_DUMP)
    finally:
        git_checkout(users_branch)

        if os.path.exists(ORIG_DUMP):
            os.unlink(ORIG_DUMP)

        if os.path.exists(NEW_DUMP):
            os.unlink(NEW_DUMP)


if __name__ == "__main__":
    main()