Skip to content

Instantly share code, notes, and snippets.

@stevenctl
Last active July 16, 2019 20:34
Show Gist options
  • Save stevenctl/29bc0954afeae0aad6c2d9a96c2948c7 to your computer and use it in GitHub Desktop.
Save stevenctl/29bc0954afeae0aad6c2d9a96c2948c7 to your computer and use it in GitHub Desktop.
Quick script for generating a CSV from SQL DDL. Supports simple foreign keys and assumes sql file has formatting as you would get when exporting from datagrip.
#/usr/bin/env python
import re
def parse_fk(fk_str):
res = re.search("foreign key \(([^\)]+)\) references ([^ ]+) \(([^\)]+)\)", fk_str)
return res.group(1), res.group(2), res.group(3)
def wrap_quotes(str_arr):
return ['"%s"' % s for s in str_arr]
class Table:
name = None
columns = {}
def __init__(self, name):
self.name = name
self.columns = {}
def add_column(self, column):
self.columns[column] = self.columns[column] if column in self.columns else []
def add_relationship(self, column, ftable, fcolumn):
col = self.columns[column] if column in self.columns else []
col.append("%s.%s" % (ftable, fcolumn))
self.columns[column] = col
def print_csv(self):
for column, rels in self.columns.items():
print(','.join(wrap_quotes([self.name, column] + rels)))
with open('./ddl.sql') as sql_file:
lines = sql_file.readlines()
tables = []
current_table = None
i = -1
while i < len(lines):
line = lines[i].strip()
if not current_table:
if line.startswith("create table"):
current_table = Table(line.split(" ")[2])
else:
if line.startswith("foreign key"):
current_table.add_relationship(*parse_fk(line))
elif line.endswith("null,") or line.endswith("null"):
current_table.add_column(line.split(" ")[0])
elif line == ")" or line == ");":
tables.append(current_table)
current_table = None
i += 1
for t in tables:
t.print_csv()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment