Last active
February 16, 2025 12:04
-
-
Save jul/e255d76590930545d383 to your computer and use it in GitHub Desktop.
building entitty relation ship diagram from a db by using introspection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
from sqlsoup import SQLSoup as sql | |
from sys import argv | |
DIGRAPH = """digraph structs { | |
graph [ | |
rankdir= "LR" | |
bgcolor=white | |
] | |
node [ | |
fontsize=12 | |
shape=record | |
] | |
%s | |
} | |
""" | |
db=sql(argv[1]) | |
print "introspecting %s" % argv[1] | |
to_scan = db.engine.table_names() | |
vertices = [] | |
nodes = dict() | |
interesting = set([]) | |
fk_count = 0 | |
field_count = 0 | |
while to_scan: | |
node_str = '' | |
try: | |
table_name = to_scan.pop() | |
table = getattr(db,table_name) | |
node_str += """ | |
%s [ | |
label="%s""" % (table_name, table_name) | |
has_fk=False | |
for c in table._table.c: | |
node_str += "|<%s>%s" % (c.name, c.name) | |
field_count += 1 | |
#print "adding %s" % c.name | |
if c.foreign_keys: | |
for fk in c.foreign_keys: | |
interesting |= { table_name, fk.column.table.name, } | |
fk_count+=1 | |
# if you want to make a progressive scan around a table vicinity | |
#to_scan += [ fk.column.table.name ] | |
vertices += [ ( | |
":".join([table_name, c.name]), | |
":".join([ fk.column.table.name, fk.column.name]), | |
fk.name or '""'), | |
] | |
nodes[table_name] = """%s" | |
color=%%s | |
bgcolor=%%s | |
]""" % node_str | |
except Exception as e: | |
print "problem with %r" % table_name | |
print repr(e) | |
to_print = "" | |
for node in nodes: | |
#to_print += node % (("grey","grey"), ("black", "white"))[node in interesting] | |
to_print += nodes[node] % (("grey","grey"), ("black", "white"))[node in interesting] | |
for v in vertices: | |
to_print+=""" | |
%s -> %s [ label=%s ] | |
""" % v | |
to_print = DIGRAPH % to_print | |
print "nb col = %r" % field_count | |
print "nb fk = %r" % fk_count | |
with open("out.dot", "w") as f: f.write(to_print) |
merci @Trujillo
Tx a lot for this program!
Can I use this program in my project which is AGPLv3? cf. https://github.com/amirouche/socialite
TIA!
@amirouche sorry for the lag, the permission is hereby officially granted, eventually send me an email so you have the explicit verbatim auhtoàrization
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
very nice script!
just a little patch on line 68: