Skip to content

Instantly share code, notes, and snippets.

@ancho85
Last active July 18, 2016 13:36
Show Gist options
  • Save ancho85/ecc97dead6563aacd01f50d83f1768ca to your computer and use it in GitHub Desktop.
Save ancho85/ecc97dead6563aacd01f50d83f1768ca to your computer and use it in GitHub Desktop.
Command line MySQL backup fixer
import cPickle
import sys
import re
import os.path
try:
recinfofile = file("recinfodic.txt","r")
except:
print "File 'recinfodic.txt' not found. Generate it with a python procedure found at devTools with the name 'PythonProcWriteRecInfo'"
sys.exit()
recinfodic = cPickle.loads(recinfofile.read())
tablenames = {}
for recinfo in recinfodic:
tablenames[recinfodic[recinfo]["TableName"].lower()] = recinfodic[recinfo]["TableName"]
if len(sys.argv) != 3:
print "USAGE: python fixMySqlBackup.py origen destino"
sys.exit()
sourcename = sys.argv[1]
destname = sys.argv[2]
try:
source = open(sourcename, "rbu")
dest = open(destname, "wb")
l = 0
m1 = re.compile("DROP TABLE IF EXISTS `(.*)`;")
m2 = re.compile("CREATE TABLE `(.*)`")
m3 = re.compile("/\*!40000 ALTER TABLE `(.*)`")
m4 = re.compile("LOCK TABLES `(.*)` WRITE;")
m5 = re.compile("INSERT INTO `([^ ]*)`")
for line in source:
if line.startswith("DROP TABLE"):
result = m1.search(line)
tn = tablenames.get(result.group(1), None)
if tn:
line = "DROP TABLE IF EXISTS `(%s)`;" % tn
elif line.startswith("CREATE TABLE"):
result = m2.search(line)
tn = tablenames.get(result.group(1), None)
if tn:
line = "CREATE TABLE `%s` (" % tn
elif line.strip().endswith("DISABLE KEYS */;"):
result = m3.search(line)
tn = tablenames.get(result.group(1), None)
if tn:
line = "/*!40000 ALTER TABLE `%s` DISABLE KEYS */;" % tn
elif line.strip().endswith("ENABLE KEYS */;"):
result = m3.search(line)
tn = tablenames.get(result.group(1), None)
if tn:
line = "/*!40000 ALTER TABLE `%s` ENABLE KEYS */;" % tn
elif line.startswith("LOCK TABLES"):
result = m4.search(line)
tn = tablenames.get(result.group(1), None)
if tn:
line = "LOCK TABLES `%s` WRITE;" % tn
elif line.startswith("INSERT INTO"):
result = m5.search(line)
tn = tablenames.get(result.group(1), None)
if tn:
ln = "INSERT INTO `%s`" % tn
line = ln + line[len(ln):]
dest.write(line)
dest.write("\n")
l += 1
def cls():
os.system(['clear','cls'][os.name == 'nt'])
cls()
print "Procesado %0.1f MB de %0.1f MB" % ((os.path.getsize(destname)/(1024*1024.0)), (os.path.getsize(sourcename)/(1024*1024.0)))
print "Correccion Finalizada. Script hecho por Carlos Angel Gomez Honig"
except Exception, e:
print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment