48 lines
1.7 KiB
Python
48 lines
1.7 KiB
Python
import re
|
|
|
|
def mysql_to_sqlite( mysql_sql_code ):
|
|
"""
|
|
converts a mysql-compatible sql code into a sqlite-ompatible sql code
|
|
|
|
note: the original code was found on internet, then tweaked
|
|
"""
|
|
content = mysql_sql_code
|
|
|
|
# unused commands
|
|
COMMAND_RE = re.compile(r'^(SET).*?;\n$', re.I | re.M | re.S)
|
|
content = COMMAND_RE.sub('', content)
|
|
|
|
# table constraints
|
|
TCONS_RE = re.compile(r'\)(\s*(CHARSET|DEFAULT|ENGINE)(=.*?)?\s*)+;', re.I | re.M | re.S)
|
|
content = TCONS_RE.sub(');', content)
|
|
|
|
# remove comments
|
|
# content = re.sub(r'^-- Tab[.]', 'toto', content, flags=re.I | re.M | re.S)
|
|
|
|
# sqlite doesn't like 'unsigned' as in `ip_address_3` tinyint(3) unsigned NOT NULL default '27',
|
|
content = re.sub(r' unsigned ', ' ', content)
|
|
|
|
# sqlite doesn't like 'enum' as in `type` enum('normal','light_out_management') NOT NULL default 'normal',,
|
|
content = re.sub(r' enum\([^\)]*\) ', ' varchar(255) ', content)
|
|
|
|
# insert multiple values
|
|
# INSERTVALS_RE = re.compile(r'^(INSERT INTO.*?VALUES)\s*\((.*)\*;', re.I | re.M | re.S)
|
|
INSERTVALS_RE = re.compile(r'^(INSERT INTO.*?VALUES)\s*([^;]*);', re.I | re.M | re.S)
|
|
#INSERTVALS_RE = re.compile(r'^(INSERT INTO.*?VALUES)\s*((\[^\)](\)));$', re.I | re.M | re.S)
|
|
INSERTVALS_SPLIT_RE = re.compile(r'\)\s*,\s*\(', re.I | re.M | re.S)
|
|
|
|
def insertvals_replacer(match):
|
|
insert, values = match.groups()
|
|
# print("insert=%s"%insert)
|
|
# print("values=%s"%values)
|
|
values = re.sub('^\s*\(' ,'', values)
|
|
values = re.sub('\)\s*$' ,'', values)
|
|
replacement = ''
|
|
for vals in INSERTVALS_SPLIT_RE.split(values):
|
|
#print("vals=%s"%vals)
|
|
replacement = '%s\n%s (%s);' % (replacement, insert, vals)
|
|
return replacement
|
|
|
|
content = INSERTVALS_RE.sub(insertvals_replacer, content)
|
|
return content
|