Django Database Migration Management Script

  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
import MySQLdb
import CommandLineApp # Doug Hellmann's CommandLineApp http://snurl.com/2tela
import os
import sys
import re
from datetime import datetime
import hashlib
from subprocess import Popen, PIPE

DB_NAME = ''
DB_HOST = ''
DB_USER = ''
DB_PASS = ''

reSQL = re.compile(";\s*$", re.MULTILINE)

db_connection = MySQLdb.connect(host=DB_HOST, 
                                db=DB_NAME, 
                                user=DB_USER, 
                                passwd=DB_PASS)


def get_version_list():
    c = db_connection.cursor()
    query = """select distinct version, svn_version 
                 from versions
             order by version;"""
    count = c.execute(query)
    versions = []
    if count > 0:
        versions = [version for version in c.fetchall()]
    return versions
    

class upgrade(CommandLineApp.CommandLineApp):
    """Upgrades the website database."""
    
    EXAMPLES_DESCRIPTION = """
To execute all scripts within a directory:

  $ upgrade --execute --dir /path/to/sqlscripts
  
To execute only some scripts within a directory:

  $ upgrade --execute --dir /path/to/sqlscripts 2008*
  
To just print out script, but don't execute:

  $ upgrade --dir /path/to/sqlscripts 2008*

To just print out scripts in the current working directory, 
but don't execute:

  $ upgrade

To execute all scripts in the current working directory:

  $ upgrade --execute
"""
    def __init__(self, commandLineOptions=sys.argv[1:]):
        super(upgrade, self).__init__(commandLineOptions=sys.argv[1:])
        
    execute = False
    def optionHandler_execute(self):
        """Turn on the excution option.  Defaults to False."""
        self.execute = True
        return
    
    dir = os.getcwd()
    def optionHandler_dir(self, name):
        """Set the directory that contains the scripts to execute.  
		Defaults to current working directory."""
        self.dir = name
        return
        
    def filter_down(self, *cherries):
        already_applied = get_version_list()
        print "# ALREADY APPLIED:"
        for x in already_applied:
            print '#\t%s\tr%s' % (x[0], x[1])
        in_directory = os.listdir(self.dir)
        in_directory.sort()
        sql_in_directory = []
        for sql in in_directory:
            if os.path.splitext(sql)[-1] == '.sql':
                sql_in_directory.append(sql)
        to_execute = []
        if cherries:
            for cherry in cherries:
                if cherry not in already_applied:
                    if cherry[0] in sql_in_directory:
                        to_execute.append(cherry[0])
        else:
            for sql in sql_in_directory:
                if sql not in [info[0] for info in already_applied]:
                    to_execute.append(sql)
        print '# TO EXECUTE:'
        for x in to_execute:
            print '#\t%s' % x
        return to_execute
        
    def get_rev(self, sql):
        svninfo = Popen(["svn", "info", sql], stdout=PIPE).stdout.readlines()
        for info in svninfo:
            tokens = info.split(':')
            if tokens[0].strip() == 'Last Changed Rev':
                return tokens[1].strip()
        return 0
        
    def split_file(self, sql):
        full_path = os.path.join(self.dir, sql)
        contents = open(full_path, 'r').read()
        size = os.stat(full_path).st_size
        sha1 = hashlib.sha1(contents).hexdigest()
        rev = self.get_rev(full_path)
        print "## Processing %s, %s bytes, sha1 %s, svn rev %s" % \
                (sql, size, sha1, rev)
        return {
			'statements':reSQL.split(contents), 
			'full_path':full_path, 
			'contents':contents, 
			'size':size, 
			'sha1':sha1, 
			'rev':rev
		}
        
    def execute_sql(self, statement, segment_number):
        segment = (
            segment_number, 
            len(statement), 
            hashlib.sha1(statement).hexdigest()
        )
        if not self.execute:
            print "### printing segment %s, %s bytes, sha1 %s" % segment
            print "%s;" % statement
        if self.execute:
            print "### executing segment %s, %s bytes, sha1 %s" % segment
            print "%s;" % statement
            c = db_connection.cursor()
            count = c.execute(statement)
            print "### SUCCESS, %s rows affected." % count
            return True
        return True
        
    def stamp_database(self, sql, statements, svn):
        print "## DB status updated: %s" % sql
        if self.execute:
            c = db_connection.cursor()
            count = c.execute("""
INSERT INTO versions (version, date_created, sql_executed, svn_version) 
VALUES (%(sql)s, %(date)s, %(statements)s, %(revision)s);""", {
    'sql':sql, 
    'date':datetime.now(), 
    'statements':';\n'.join(statements)+';', 
    'revision':svn
            })       
    
    def main(self, *args):
        print "# Script began %s" % datetime.now()
        to_execute = self.filter_down(*args)
        for sql in to_execute:
            split_data = self.split_file(sql)
            statements = split_data['statements']
            executed_stmts = []
            segment_num = 0
            for statement in  statements:
                stmt = statement.strip()
                if stmt and stmt not in ('BEGIN', 'COMMIT',) and \
                    "UPDATE `version` SET `serial_number`" not in stmt:
                    if self.execute_sql(stmt, segment_num):
                        executed_stmts.append(stmt)
                segment_num += 1
            # for each file update the database version
            self.stamp_database(sql, executed_stmts, split_data['rev'])
            print "-"*70
        print "# Script ended %s" % datetime.now()
        
        
if __name__ == "__main__":
    up = upgrade()
    up.run()

More like this

  1. Transparently encrypt ORM fields using OpenSSL (via M2Crypto) by ncoghlan 2 years, 9 months ago
  2. Database migration and dump/load script by akaihola 7 years ago
  3. Simple Plone Migration by msm-art 6 years, 2 months ago
  4. Manager for multiple database connections by rix 4 years, 8 months ago
  5. Diagram of your database structure by vnbang2003 2 years, 8 months ago

Comments

(Forgotten your password?)