27/03/2008

Graphing SQLAlchemy Models

Here is a little function to draw a nice graph of your SQLAlchemy tables and foreign keys. Just pass it a MetaInfo instance.

import pydot

def graph_meta(meta, filename="dbgraph.jpeg"):
    d = pydot.Dot()
    nodes = {}

    for table in meta.tables.itervalues():
        n = nodes[table.name] = pydot.Node(table.name)
        d.add_node(n)

    for table in meta.tables.itervalues():
        for c in table.c:
            for fk in c.foreign_keys:
                e = pydot.Edge(nodes[table.name], nodes[fk.column.table.name])
                d.add_edge(e)

    d.write_jpeg(filename)

No comments: