fschulze / sqlalchemy_schemadisplay

Other
138 stars 37 forks source link

sqlalchemy_schemadisplay

Turn SQLAlchemy DB Model into a graph.

.. image:: https://img.shields.io/pypi/v/sqlalchemy_schemadisplay :alt: PyPI :target: https://pypi.org/project/sqlalchemy_schemadisplay

See SQLAlchemy wiki <https://github.com/sqlalchemy/sqlalchemy/wiki/SchemaDisplay>_ for the previous version of this doc.

Usage

You will need atleast SQLAlchemy and pydot along with graphviz for this. Graphviz-cairo is highly recommended to get tolerable image quality. If PIL and an image viewer are available then there are functions to automatically show the image. Some of the stuff, specifically loading list of tables from a database via a mapper and reflecting indexes currently only work on postgres.

This is an example of database entity diagram generation:

.. code-block:: python

from sqlalchemy import MetaData, create_engine
from sqlalchemy_schemadisplay import create_schema_graph

# create the pydot graph object by autoloading all tables via a bound metadata object
graph = create_schema_graph(
   engine=create_engine('postgresql+psycopg2://user:pwd@host/database'),
   metadata=MetaData('postgres://user:pwd@host/database'),
   show_datatypes=False, # The image would get nasty big if we'd show the datatypes
   show_indexes=False, # ditto for indexes
   rankdir='LR', # From left to right (instead of top to bottom)
   concentrate=False # Don't try to join the relation lines together
)
graph.write_png('dbschema.png') # write out the file

And an UML class diagram from a model:

.. code-block:: python

from myapp import model
from sqlalchemy_schemadisplay import create_uml_graph
from sqlalchemy.orm import class_mapper

# lets find all the mappers in our model
mappers = [model.__mapper__]
for attr in dir(model):
    if attr[0] == '_': continue
    try:
        cls = getattr(model, attr)
        mappers.append(cls.property.entity)
    except:
        pass

# pass them to the function and set some formatting options
graph = create_uml_graph(mappers,
    show_operations=False, # not necessary in this case
    show_multiplicity_one=False # some people like to see the ones, some don't
)
graph.write_png('schema.png') # write out the file

Changelog

2.0 - 2024-02-15

1.4 - 2024-02-15

Last release to support Python 2.

1.3 - 2016-01-27

1.2 - 2014-03-02

1.1 - 2011-10-12

1.0 - 2011-01-07