SQLAlchemy SchemaDisplay
SQLAlchemy SchemaDisplay is a Python library (version 2.0) for generating visual diagrams from SQLAlchemy ORM models or directly from a database schema. It leverages the Graphviz engine to produce high-quality visualizations of database structures, showing tables, columns, relationships, and data types. Releases are primarily driven by feature additions and compatibility updates with SQLAlchemy.
Common errors
-
FileNotFoundError: [Errno 2] No such file or directory: 'dot'
cause The Graphviz command-line executable (`dot`) is not installed on your system or is not accessible in your system's PATH.fixInstall the Graphviz software package for your operating system. For example, `sudo apt-get install graphviz` on Debian/Ubuntu, or `brew install graphviz` on macOS. Verify installation by running `dot -V` in your terminal. -
ModuleNotFoundError: No module named 'graphviz'
cause The Python `graphviz` package, which is a dependency of `sqlalchemy-schemadisplay`, has not been installed.fixInstall the Python `graphviz` package using pip: `pip install graphviz`. -
AttributeError: 'DeclarativeBase' object has no attribute 'metadata'
cause You are passing an instance of `Base` or the `Base` class itself to `create_schema_graph` instead of its `metadata` attribute.fixEnsure you are passing `Base.metadata` (for declarative models) or an existing `MetaData` object to the `metadata` argument of `create_schema_graph`.
Warnings
- breaking The `create_schema_graph` function requires the external Graphviz executable (`dot` command) to be installed on your system and available in your PATH. Without it, the diagram generation will fail with a `FileNotFoundError`.
- gotcha Forgetting to install the Python `graphviz` package alongside `sqlalchemy-schemadisplay` will result in a `ModuleNotFoundError` when `create_schema_graph` attempts to import it.
- gotcha When using `declarative_base`, you must pass `Base.metadata` to `create_schema_graph`, not the `Base` object itself. Passing `Base` directly will likely result in an `AttributeError`.
- gotcha Outputting the diagram requires specifying the `filename` for methods like `write_png`, `write_svg`, etc. Also, ensure the directory has write permissions. If no filename is given, the graph object is returned but not saved.
Install
-
pip install sqlalchemy-schemadisplay graphviz -
sudo apt-get install graphviz # On Debian/Ubuntu brew install graphviz # On macOS
Imports
- create_schema_graph
from sqlalchemy_schemadisplay import create_schema_graph
Quickstart
import os
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base
from sqlalchemy_schemadisplay import create_schema_graph
# 1. Define your SQLAlchemy models
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50), nullable=False)
email = Column(String(100), unique=True)
class Product(Base):
__tablename__ = 'products'
id = Column(Integer, primary_key=True)
name = Column(String(50), nullable=False)
price = Column(Integer)
# 2. Create the graph and save it to a file
try:
# Using Base.metadata directly
graph = create_schema_graph(
metadata=Base.metadata,
show_datatypes=True,
show_labels=True,
rankdir='LR', # Left-to-right layout
orientation='portrait'
)
output_file = 'schema.png'
graph.write_png(output_file)
print(f"Schema diagram saved to {output_file}")
except Exception as e:
print(f"An error occurred: {e}")
print("Make sure Graphviz is installed on your system PATH and 'graphviz' Python package is installed.")
# Optional: Clean up (if you created a temporary database for reflection)
# os.remove('test.db') if os.path.exists('test.db') else None