Advertisement
gregwa

MySQL2SQLite.py

Nov 7th, 2011
851
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.74 KB | None | 0 0
  1. #!/usr/bin/env python
  2. #====================================
  3. # MySQL2SQLite.py
  4. #====================================
  5. #            IMPORTS
  6. import sys
  7. #====================================
  8.  
  9. #====================================
  10. #     BEGIN CLASS MySQL2SQLite
  11. #====================================
  12. class MySQL2SQLite:
  13.     def __init__(self):
  14.         self.InputFile = ""
  15.         self.OutputFile = ""
  16.         self.WriteFile = 0
  17.         self.DebugMode = 0
  18.         self.SchemaOnly = 0
  19.         self.DirectMode = False
  20.  
  21.     def SetUp(self, In, Out = '', Debug = False, Schema = 0):
  22.         self.InputFile = In
  23.         if Out == '':
  24.             self.writeFile = 0
  25.         else:
  26.             self.WriteFile = 1
  27.             self.OutputFile = Out
  28.         if Debug == True:
  29.             self.DebugMode = 1
  30.         if Schema == 1:
  31.             self.SchemaOnly = 1
  32.            
  33.     def DoWork(self):
  34.         f = open(self.InputFile)
  35.         print "Starting Process"
  36.         cntr = 0
  37.         insertmode = 0
  38.         CreateTableMode = 0
  39.         InsertStart = "INSERT INTO "
  40.         AI = "auto_increment"
  41.         PK = "PRIMARY KEY "
  42.         IPK = " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL"
  43.         CT = "CREATE TABLE "
  44.         # Begin
  45.         if self.WriteFile == 1:
  46.             OutFile = open(self.OutputFile,'w')
  47.         while 1:
  48.             line = f.readline()
  49.             cntr += 1
  50.             if not line:
  51.                 break
  52.             # Ignore blank lines, lines that start with "--" or comments (/*!)
  53.             if line.startswith("--"): #Comments
  54.                 pass
  55.             elif len(line) == 1: # Blank Lines
  56.                 pass
  57.             elif line.startswith("/*!"): # Comments
  58.                 pass
  59.             elif line.startswith("USE"):
  60.                 #Ignore USE lines
  61.                 pass
  62.             elif line.startswith("CREATE DATABASE "):
  63.                 pass            
  64.             elif line.startswith(CT):
  65.                 CreateTableMode = 1
  66.                 l1 = len(line)
  67.                 line = line[:l1-1]
  68.                 if self.DebugMode == 1:
  69.                     print "Starting Create Table"
  70.                     print line
  71.                 if self.WriteFile == 1:
  72.                     OutFile.write(line)            
  73.             elif CreateTableMode == 1:
  74.                 # Parse the line...
  75.                 if self.DebugMode == 1:
  76.                     print "Line to process - {0}".format(line)
  77.                 p1 = line.find(AI)
  78.                 if line.startswith(") "):
  79.                     CreateTableMode = 0
  80.                     if self.DebugMode == 1:
  81.                         print "Finished Table Create"
  82.                     newline = ");\n"
  83.                     if self.WriteFile == 1:
  84.                         OutFile.write(newline)
  85.                         if self.DebugMode == 1:
  86.                             print "Writing Line {0}".format(newline)
  87.                 elif p1 != -1:
  88.                     # Line is primary key line
  89.                     l = line.strip()
  90.                     fnpos = l.find(" int(")
  91.                     if fnpos != -1:
  92.                         fn = l[:fnpos]
  93.                     newline = fn + IPK #+ ",\n"
  94.                     if self.WriteFile == 1:
  95.                         OutFile.write(newline)
  96.                         if self.DebugMode == 1:
  97.                             print "Writing Line {0}".format(newline)
  98.                 elif line.strip().startswith(PK):
  99.                     pass
  100.                 elif line.find(" unsigned ") != -1:
  101.                     line = line.replace(" unsigned "," ")
  102.                     line = line.strip()
  103.                     l1 = len(line)
  104.                     line = line[:l1-1]
  105.                     if self.WriteFile == 1:
  106.                         OutFile.write("," + line)
  107.                         if self.DebugMode == 1:
  108.                             print "Writing Line {0}".format(line)
  109.                 else:
  110.                     l1 = len(line)
  111.                     line = line.strip()
  112.                     line = line[:l1-4]
  113.                     if self.DebugMode == 1:
  114.                         print "," + line
  115.                     if self.WriteFile == 1:
  116.                         OutFile.write("," + line)
  117.             elif line.startswith(InsertStart):
  118.                 if insertmode == 0:
  119.                     insertmode = 1
  120.                     # Get tablename and field list here
  121.                     istatement = line
  122.                     # Strip CR/LF from istatement line
  123.                     l = len(istatement)
  124.                     istatement = istatement[:l-2]
  125.             elif self.SchemaOnly == 0:
  126.                 if insertmode == 1:
  127.                     posx = line.find("');")
  128.                     pos1 = line.find("'),")
  129.                     l1 = line[:pos1]
  130.                     line = line.replace("\\'","''")
  131.                     if posx != -1:
  132.                         l1 = line[:posx+3]
  133.                         insertmode = 0
  134.                         if self.DebugMode == 1:
  135.                             print istatement + l1
  136.                             print "------------------------------"
  137.                         if self.WriteFile == 1:
  138.                             OutFile.write(istatement + l1+"\n")
  139.                     elif pos1 != -1:
  140.                         l1 = line[:pos1+2]
  141.                         if self.DebugMode == 1:
  142.                             print istatement + l1 + ";"
  143.                         if self.WriteFile == 1:
  144.                             OutFile.write(istatement + l1 + ";\n")
  145.                     else:
  146.                         if self.DebugMode == 1:
  147.                             print "Testing line {0}".format(line)
  148.                         pos1 = line.find("),")
  149.                         posx = line.find(");")
  150.                         if self.DebugMode == 1:
  151.                             print "pos1 = {0}, posx = {1}".format(pos1,posx)
  152.                         if pos1 != -1:
  153.                             l1 = line[:pos1+1]
  154.                             if self.DebugMode == 1:
  155.                                 print istatement + l1 + ";"
  156.                             if self.WriteFile == 1:
  157.                                 OutFile.write(istatement + l1 + ";\n")
  158.                         else:
  159.                             insertmode = 0
  160.                             l1 = line[:posx+1]
  161.                             if self.DebugMode == 1:
  162.                                 print istatement + l1 + ";"
  163.                             if self.WriteFile == 1:
  164.                                 OutFile.write(istatement + l1 + ";\n")
  165.         f.close()
  166.         if self.WriteFile == 1:
  167.             OutFile.close()                        
  168.                        
  169.        
  170. def error(message):
  171.     print >> sys.stderr, str(message)    
  172.        
  173. def DoIt():
  174.     #=======================================
  175.     #            Setup Variables
  176.     #=======================================
  177.     SourceFile = ''
  178.     OutputFile = ''
  179.     Debug = False
  180.     Help = False
  181.     SchemaOnly = False
  182.     #=======================================
  183.     if len(sys.argv) == 1:
  184.         usage()
  185.     else:
  186.         for a in sys.argv:
  187.             print a
  188.             if a.startswith("Infile="):
  189.                 pos = a.find("=")
  190.                 SourceFile = a[pos+1:]
  191.             elif a.startswith("Outfile="):
  192.                 pos = a.find("=")
  193.                 OutputFile = a[pos+1:]
  194.             elif a == 'Debug':
  195.                 Debug = True
  196.             elif a == 'SchemaOnly':
  197.                 SchemaOnly = True
  198.             elif a == '-Help' or a == '-H' or a == '-?':
  199.                 Help = True      
  200.         if Help == True:
  201.             usage()
  202.         r = MySQL2SQLite()
  203.         r.SetUp(SourceFile,OutputFile,Debug,SchemaOnly)
  204.         r.DoWork()    
  205.    
  206. def usage():
  207.     message = (
  208.        '=======================================================================\n'
  209.         'MySQL2SQLite - A database converter\n'
  210.         'Author: Greg Walters\n'
  211.         'USAGE:\n'
  212.         'MySQL2SQLite Infile=filename [Outfile=filename] [SchemaOnly] [Debug] [-H-Help-?\n'
  213.         '   where\n'
  214.         '         Infile is the MySQL dump file\n'
  215.         '         Outfile (optional) is the output filename\n'
  216.         '            (if Outfile is omitted, assumed direct to SQLite\n'
  217.         '         SchemaOnly (optional) Create Tables, DO NOT IMPORT DATA\n'
  218.         '         Debug (optional) - Turn on debugging messages\n'
  219.         '         -H or -Help or -? - Show this message\n'
  220.         'Copyright (C) 2011 by G.D. Walters\n'
  221.         '=======================================================================\n'
  222.         )
  223.     error(message)
  224.     sys.exit(1)        
  225.  
  226. if __name__ == "__main__":
  227.     DoIt()
  228.  
  229.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement