Advertisement
Guest User

Untitled

a guest
Mar 8th, 2016
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.41 KB | None | 0 0
  1. """Migration script for mysql."""
  2. import sys
  3. import MySQLdb as mysql
  4. from string import Template
  5. import json, os, datetime
  6. from string import Template
  7.  
  8.  
  9. class Dialect(object):
  10. def __init__(self,command,args):
  11. """ map methods """
  12. self.methods = {
  13. 'add_column' : self.add_column,
  14. 'drop_column' : self.drop_column,
  15. 'rename_column' : self.rename_column,
  16. 'add_index' : self.add_index,
  17. 'drop_index' : self.drop_index }
  18. self.command = command
  19. self.args = args
  20.  
  21. def ddl(self):
  22. return self.methods[self.command](self.args)
  23.  
  24. def add_column(self,args):
  25. template = Template("alter table $table_name add column $col_name $col_type;")
  26. return template.substitute(table_name=args[0],col_name=args[1],col_type=args[2])
  27.  
  28. def drop_column(self,args):
  29. template = Template("alter table $table_name drop column $col_name;")
  30. return template.substitute(table_name=args[0],col_name=args[1])
  31.  
  32. def rename_column(self,args):
  33. template = Template("alter table $table_name change column $old_col_name $new_col_name $col_type;")
  34. return template.substitute(table_name=args[0],old_col_name=args[1],new_col_name=args[2],col_type=args[3])
  35.  
  36. def add_index(self,args):
  37. template = Template("alter table $table_name add index ($col_name);")
  38. return template.substitute(table_name=args[0],col_name=args[2])
  39.  
  40. def drop_index(self,args):
  41. template = Template("alter table $table_name drop index ($col_name);")
  42. return template.substitute(table_name=args[0],col_name=args[2])
  43.  
  44. class Migrate(object):
  45. def __init__(self,host,user,password,db):
  46. self.connection = mysql.connect(host=host,user=user,passwd=password,db=db)
  47.  
  48. def execute(self,statements):
  49. """ execute the satements """
  50. cursor = self.connection.cursor()
  51. for statement in statements:
  52. try:
  53. cursor.execute(statement["statement"])
  54. except Exception as e:
  55. print "========================================="
  56. print e
  57. print "Migration aborted"
  58. print "========================================="
  59. else:
  60. self.save(statement["statement"],statement["version"])
  61.  
  62. def save(self,statement,version):
  63. """ save completed migrations in database file """
  64. template = Template("insert into migrations values ('$version', '$statement', '$time')")
  65. stmt = template.substitute(version=version,statement=statement,time=datetime.datetime.now())
  66. cursor = self.connection.cursor()
  67. try:
  68. cursor.execute(stmt)
  69. print stmt
  70. except Exception as e:
  71. print e
  72.  
  73. def add(self,statement):
  74. """ add migrations to migrations file """
  75. with open("migrations.txt","a+") as f:
  76. try:
  77. version = os.urandom(5).encode('hex')
  78. stt = json.dumps({"version":version,'statement':statement})
  79. f.write(stt+"\n")
  80. except Exception as e:
  81. print e
  82. finally:
  83. f.close()
  84.  
  85. def run(self):
  86. """ run the migrations """
  87. flist = self.compare()
  88. self.execute(flist)
  89.  
  90. def compare(self):
  91. """ compare the added ones with completed ones and make final list """
  92. added = self.added()
  93. completed = self.completed()
  94. flist = []
  95. if len(completed) == 0:
  96. flist = added
  97. else:
  98. for i in added:
  99. if i["version"] not udaycodein completed:
  100. flist.append(i)
  101. return flist
  102.  
  103. def completed(self):
  104. """ get the list of completed migrations """
  105. mig = []
  106. s = "select version from migrations"
  107. cur = self.connection.cursor()
  108. try:
  109. cur.execute(s)
  110. rows = cur.fetchall()
  111. except Exception as e:
  112. if e[0] == 1146:
  113. print "migrations table does not exist! Created one"
  114. stmt = "create table migrations (version varchar(255), \
  115. statement varchar(300), created DATETIME);"
  116. cursr = self.connection.cursor()
  117. cursr.execute(stmt)
  118. else:
  119. print e
  120. else:
  121. mig = [i[0] for i in rows]
  122. return mig
  123.  
  124.  
  125. def added(self):
  126. """ get the list of added migrations """
  127. mig = []
  128. with open("migrations.txt","r") as f:
  129. for line in f:
  130. mig.append(json.loads(line))
  131. f.close()
  132. return mig
  133.  
  134. def command(self,args):
  135. """ add command """
  136. self.add(Dialect(command=args[1:][0],args=args[2:]).ddl())
  137.  
  138.  
  139. if __name__ == '__main__':
  140. m = Migrate(host='localhost',user='root',password="password",db='test')
  141. if 'run' in sys.argv:
  142. m.run()
  143. elif 'added' in sys.argv:
  144. for i in m.compare():
  145. print i
  146. else:
  147. m.command(sys.argv)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement