Skip to content

Instantly share code, notes, and snippets.

@markrwilliams
Created October 8, 2013 08:29
Show Gist options
  • Save markrwilliams/6881472 to your computer and use it in GitHub Desktop.
Save markrwilliams/6881472 to your computer and use it in GitHub Desktop.
import csv
from parsley import makeGrammar
import sys
raw = r'''
squote = '\''
escaped_squote = '\\' squote
float = <digit+ '.' digit*>:f -> float(f)
int = <digit+>:i -> int(i)
string = squote <(escaped_squote | ~squote anything)*>:s squote -> s
value = int | float | string
values = value:head (ws ',' ws value)*:tail -> [head] + tail
tuple = '(' ws values:v ws ')' -> writer.writerow(v)
tuples = tuple:head (ws ',' ws tuple)*:tail -> [head] + tail
table_name = <(letter | '_' | '.')+>:t
table = ('`' table_name:t '`' -> t) | table_name
insert = token('INSERT') ws token('INTO') ws table:t ws token('VALUES') ws tuples:ts ws ';' ws
'''
def parse(fn):
g = makeGrammar(raw, {'writer': csv.writer(sys.stdout)})
with open(fn) as f:
for line in f:
if not line.startswith('INSERT'):
continue
try:
g(line).insert()
except Exception as e:
a = repr(line[e.position-100:e.position])
b = repr(line[e.position])
c = repr(line[e.position+1:e.position+100])
print '%s\033[91m%s\033[0m%s' % (a, b, c)
print e.formatReason()
if __name__ == '__main__':
import argparse
ap = argparse.ArgumentParser(description='pick through a mysqldump')
ap.add_argument('file',
help='mysqldump file that contains INSERTS')
args = ap.parse_args()
parse(args.file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment