· 8 years ago · Aug 04, 2018, 09:36 PM
1#!/usr/bin/env python
2
3import re
4import fileinput
5
6def this_line_is_useless(line):
7 useless_es = [
8 'BEGIN TRANSACTION',
9 'COMMIT',
10 'sqlite_sequence',
11 'CREATE UNIQUE INDEX',
12 'PRAGMA foreign_keys=OFF',
13 ]
14 for useless in useless_es:
15 if re.search(useless, line):
16 return True
17
18def has_primary_key(line):
19 return bool(re.search(r'PRIMARY KEY', line))
20
21searching_for_end = False
22for line in fileinput.input():
23 if this_line_is_useless(line):
24 continue
25
26 # this line was necessary because '');
27 # would be converted to \'); which isn't appropriate
28 if re.match(r".*, ''\);", line):
29 line = re.sub(r"''\);", r'``);', line)
30
31 if re.match(r'^CREATE TABLE.*', line):
32 searching_for_end = True
33
34 m = re.search('CREATE TABLE "?(\w*)"?(.*)', line)
35 if m:
36 name, sub = m.groups()
37 line = "DROP TABLE IF EXISTS %(name)s;\nCREATE TABLE IF NOT EXISTS `%(name)s`%(sub)s\n"
38 line = line % dict(name=name, sub=sub)
39 else:
40 m = re.search('INSERT INTO "(\w*)"(.*)', line)
41 if m:
42 line = 'INSERT INTO %s%s\n' % m.groups()
43 line = line.replace('"', r'\"')
44 line = line.replace('"', "'")
45 line = re.sub(r"([^'])'t'(.)", "\1THIS_IS_TRUE\2", line)
46 line = line.replace('THIS_IS_TRUE', '1')
47 line = re.sub(r"([^'])'f'(.)", "\1THIS_IS_FALSE\2", line)
48 line = line.replace('THIS_IS_FALSE', '0')
49
50 # Add auto_increment if it is not there since sqlite auto_increments ALL
51 # primary keys
52 if searching_for_end:
53 if re.search(r"integer(?:\s+\w+)*\s*PRIMARY KEY(?:\s+\w+)*\s*,", line):
54 line = line.replace("PRIMARY KEY", "PRIMARY KEY AUTO_INCREMENT")
55 # replace " and ' with ` because mysql doesn't like quotes in CREATE commands
56 if line.find('DEFAULT') == -1:
57 line = line.replace(r'"', r'`').replace(r"'", r'`')
58 else:
59 parts = line.split('DEFAULT')
60 parts[0] = parts[0].replace(r'"', r'`').replace(r"'", r'`')
61 line = 'DEFAULT'.join(parts)
62
63 # And now we convert it back (see above)
64 if re.match(r".*, ``\);", line):
65 line = re.sub(r'``\);', r"'');", line)
66
67 if searching_for_end and re.match(r'.*\);', line):
68 searching_for_end = False
69
70 if re.match(r"CREATE INDEX", line):
71 line = re.sub('"', '`', line)
72
73 if re.match(r"AUTOINCREMENT", line):
74 line = re.sub("AUTOINCREMENT", "AUTO_INCREMENT", line)
75
76 print line,