SQLAlchemy SchemaDisplay

2.0 · active · verified Fri Apr 17

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define simple SQLAlchemy models using `declarative_base` and then use `create_schema_graph` to generate a PNG diagram representing their structure. It outputs a file named `schema.png` in the current directory. Remember that the Graphviz executable must be installed on your system for this to work.

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

view raw JSON →