Skip to content

Instantly share code, notes, and snippets.

@jul
Last active October 2, 2025 13:23
Show Gist options
  • Save jul/e255d76590930545d383 to your computer and use it in GitHub Desktop.
Save jul/e255d76590930545d383 to your computer and use it in GitHub Desktop.
building entitty relation ship diagram from a db by using introspection
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sqlramen import SQLRamen 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 = list(db.base.classes)
vertices = []
nodes = dict()
interesting = set([])
fk_count = 0
field_count = 0
while to_scan:
node_str = ''
try:
table = to_scan.pop()
table_name = table.__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 )
print("outputing diagram in out.dot")
with open("out.dot", "w") as f: f.write(to_print)
@truijllo
Copy link

very nice script!
just a little patch on line 68:

 to_print += nodes[node] % (("grey","grey"), ("black", "white"))[node in interesting]

@jul
Copy link
Author

jul commented Apr 17, 2016

merci @Trujillo

@amirouche
Copy link

amirouche commented Jul 16, 2017

Tx a lot for this program!

@amirouche
Copy link

Can I use this program in my project which is AGPLv3? cf. https://github.com/amirouche/socialite

TIA!

@jul
Copy link
Author

jul commented Apr 10, 2018

@amirouche sorry for the lag, the permission is hereby officially granted, eventually send me an email so you have the explicit verbatim auhtoàrization

@jul
Copy link
Author

jul commented Oct 2, 2025

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment