7 # This prevents prematurely closed pipes from raising
8 # an exception in Python
9 from signal import signal, SIGPIPE, SIG_DFL
10 signal(SIGPIPE, SIG_DFL)
14 Returns true if the line begins a SQL insert statement.
16 return line.startswith('INSERT INTO') or False
21 Returns the portion of an INSERT statement containing values
23 return line.partition('` VALUES ')[2].strip()
26 def values_sanity_check(values):
28 Ensures that values from the INSERT statement meet basic checks.
31 assert values[0] == '('
32 assert values[-2:] == ');'
33 # Assertions have not been raised
36 def clean_quotes_for_fread(col):
37 col = re.sub('\t', ' ', col)
38 if col.startswith('"'):
39 return('"' + col + '"')
43 def parse_values(values, outfile):
45 Given a file handle and the raw values from a MySQL INSERT
46 statement, write the equivalent CSV to the file
48 values = values.rstrip(");")
49 values = values.lstrip("(")
51 reader = csv.reader(values.split("),("), delimiter=',',
57 for reader_row in reader:
58 print("\t".join([clean_quotes_for_fread(col) for col in reader_row]))
62 Parse arguments and start the program
64 # Iterate over all lines in all files
65 # listed in sys.argv[1:]
66 # or stdin if no args given.
68 for line in fileinput.input():
69 # Look for an INSERT statement and parse it.
71 values = get_values(line.strip().rstrip())
72 if values_sanity_check(values):
73 parse_values(values, sys.stdout)
74 except KeyboardInterrupt:
77 if __name__ == "__main__":