ERAlchemy: Entity-Relation Diagram Generator

1.6.0 · maintenance · verified Thu Apr 09

ERAlchemy is a Python library for generating Entity-Relation (ER) diagrams from SQLAlchemy models, declarative database metadata, or a simple text file format. It leverages the external Graphviz engine to visualize the relationships and can output diagrams in various formats such as PNG, SVG, and PDF. The current stable version is 1.6.0, with development activity having slowed in recent years, but it remains a functional tool for its primary purpose.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to generate an ER diagram from SQLAlchemy models using `eralchemy`. It creates a simple SQLite database with two related tables (`User` and `Email`) and then uses `render_er` to generate a PNG file. Crucially, the external Graphviz program must be installed on your system for rendering to succeed.

from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from eralchemy import render_er
import os

# 1. Define SQLAlchemy models
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(50), nullable=False)
    emails = relationship('Email', back_populates='user')

class Email(Base):
    __tablename__ = 'emails'
    id = Column(Integer, primary_key=True)
    address = Column(String(100), nullable=False, unique=True)
    user_id = Column(Integer, ForeignKey('users.id'))
    user = relationship('User', back_populates='emails')

# 2. Create a dummy database and tables
db_url = "sqlite:///./er_example.db"
engine = create_engine(db_url)
Base.metadata.create_all(engine)

# 3. Generate the ER diagram
output_file = "er_diagram.png"

# IMPORTANT: Graphviz must be installed on your system for this to work.
# Instructions for common OS:
#   - Debian/Ubuntu: sudo apt-get install graphviz
#   - macOS: brew install graphviz
#   - Windows: Download and install from graphviz.org, then add to PATH.

try:
    render_er(db_url, output_file)
    print(f"ER diagram generated to {output_file}")
    print(f"To view it, ensure Graphviz is installed and open {output_file}")
except Exception as e:
    print(f"Failed to generate ER diagram. Ensure Graphviz is correctly installed and in your system's PATH. Error: {e}")
finally:
    # Clean up the dummy database file if it was created
    if os.path.exists("./er_example.db"):
        pass # os.remove("./er_example.db") # Uncomment to remove DB file after run

view raw JSON →