Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Migration script for mysql."""
- import sys
- import MySQLdb as mysql
- from string import Template
- import json, os, datetime
- from string import Template
- class Dialect(object):
- def __init__(self,command,args):
- """ map methods """
- self.methods = {
- 'add_column' : self.add_column,
- 'drop_column' : self.drop_column,
- 'rename_column' : self.rename_column,
- 'add_index' : self.add_index,
- 'drop_index' : self.drop_index }
- self.command = command
- self.args = args
- def ddl(self):
- return self.methods[self.command](self.args)
- def add_column(self,args):
- template = Template("alter table $table_name add column $col_name $col_type;")
- return template.substitute(table_name=args[0],col_name=args[1],col_type=args[2])
- def drop_column(self,args):
- template = Template("alter table $table_name drop column $col_name;")
- return template.substitute(table_name=args[0],col_name=args[1])
- def rename_column(self,args):
- template = Template("alter table $table_name change column $old_col_name $new_col_name $col_type;")
- return template.substitute(table_name=args[0],old_col_name=args[1],new_col_name=args[2],col_type=args[3])
- def add_index(self,args):
- template = Template("alter table $table_name add index ($col_name);")
- return template.substitute(table_name=args[0],col_name=args[2])
- def drop_index(self,args):
- template = Template("alter table $table_name drop index ($col_name);")
- return template.substitute(table_name=args[0],col_name=args[2])
- class Migrate(object):
- def __init__(self,host,user,password,db):
- self.connection = mysql.connect(host=host,user=user,passwd=password,db=db)
- def execute(self,statements):
- """ execute the satements """
- cursor = self.connection.cursor()
- for statement in statements:
- try:
- cursor.execute(statement["statement"])
- except Exception as e:
- print "========================================="
- print e
- print "Migration aborted"
- print "========================================="
- else:
- self.save(statement["statement"],statement["version"])
- def save(self,statement,version):
- """ save completed migrations in database file """
- template = Template("insert into migrations values ('$version', '$statement', '$time')")
- stmt = template.substitute(version=version,statement=statement,time=datetime.datetime.now())
- cursor = self.connection.cursor()
- try:
- cursor.execute(stmt)
- print stmt
- except Exception as e:
- print e
- def add(self,statement):
- """ add migrations to migrations file """
- with open("migrations.txt","a+") as f:
- try:
- version = os.urandom(5).encode('hex')
- stt = json.dumps({"version":version,'statement':statement})
- f.write(stt+"\n")
- except Exception as e:
- print e
- finally:
- f.close()
- def run(self):
- """ run the migrations """
- flist = self.compare()
- self.execute(flist)
- def compare(self):
- """ compare the added ones with completed ones and make final list """
- added = self.added()
- completed = self.completed()
- flist = []
- if len(completed) == 0:
- flist = added
- else:
- for i in added:
- if i["version"] not udaycodein completed:
- flist.append(i)
- return flist
- def completed(self):
- """ get the list of completed migrations """
- mig = []
- s = "select version from migrations"
- cur = self.connection.cursor()
- try:
- cur.execute(s)
- rows = cur.fetchall()
- except Exception as e:
- if e[0] == 1146:
- print "migrations table does not exist! Created one"
- stmt = "create table migrations (version varchar(255), \
- statement varchar(300), created DATETIME);"
- cursr = self.connection.cursor()
- cursr.execute(stmt)
- else:
- print e
- else:
- mig = [i[0] for i in rows]
- return mig
- def added(self):
- """ get the list of added migrations """
- mig = []
- with open("migrations.txt","r") as f:
- for line in f:
- mig.append(json.loads(line))
- f.close()
- return mig
- def command(self,args):
- """ add command """
- self.add(Dialect(command=args[1:][0],args=args[2:]).ddl())
- if __name__ == '__main__':
- m = Migrate(host='localhost',user='root',password="password",db='test')
- if 'run' in sys.argv:
- m.run()
- elif 'added' in sys.argv:
- for i in m.compare():
- print i
- else:
- m.command(sys.argv)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement