Skip to content

Instantly share code, notes, and snippets.

@pixelchai
Last active January 17, 2020 22:15
Show Gist options
  • Save pixelchai/ad9d6b3cc343f70c93e76f461ddea109 to your computer and use it in GitHub Desktop.
Save pixelchai/ad9d6b3cc343f70c93e76f461ddea109 to your computer and use it in GitHub Desktop.
converts an input sqlite sql file into the format used by https://dbdiagram.io/
import re
text = ""
output = ""
with open("input.sql") as f:
text = f.read()
text = re.sub(r"--.*", "", text)
for m_table in re.finditer(r"CREATE\s+TABLE\s+IF\s+NOT\s+EXISTS\s+"\
"(\w+)\s+\(([\s\S]+?)\);", text):
output += "Table {} ".format(m_table.group(1)) + "{\n"
for m_attr in re.finditer(r"(\w+)\s+(INTEGER|REAL|TEXT|BLOB)"\
"((?:\s*(?:PRIMARY KEY|NOT NULL|UNIQUE))*)",
m_table.group(2)):
output += " "*4 + m_attr.group(1) + " " + m_attr.group(2)
modifiers = m_attr.group(3).strip()
if len(modifiers)>0:
output += " [" + re.sub(r"PRIMARY KEY|NOT NULL|UNIQUE",
"\g<0>,", modifiers)[:-1] + "]"
output += "\n"
output += "}\n"
for m_fk in re.finditer(r"FOREIGN KEY\s*\((\w+)\)"\
"\s*REFERENCES\s+(\w+)\s*\((\w+)\)",
m_table.group(2)):
output += "Ref: {}.{} > {}.{}\n".format(m_table.group(1),
m_fk.group(1),
m_fk.group(2),
m_fk.group(3))
output += "\n"
print(output)
with open("output.sql", "w") as f:
f.write(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment