erdalchemy 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,153 @@
1
+ Metadata-Version: 2.4
2
+ Name: erdalchemy
3
+ Version: 0.1.0
4
+ Summary: Interactive ERD visualization for SQLAlchemy 2.0 models
5
+ Author: Jose Velazco
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: database,diagram,erd,sqlalchemy,visualization
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Database
17
+ Classifier: Topic :: Software Development :: Documentation
18
+ Requires-Python: >=3.10
19
+ Requires-Dist: sqlalchemy>=2.0
20
+ Provides-Extra: all
21
+ Requires-Dist: cairosvg>=2.7; extra == 'all'
22
+ Provides-Extra: pdf
23
+ Requires-Dist: cairosvg>=2.7; extra == 'pdf'
24
+ Provides-Extra: png
25
+ Requires-Dist: cairosvg>=2.7; extra == 'png'
26
+ Description-Content-Type: text/markdown
27
+
28
+ # sqlalchemy-erd
29
+
30
+ Interactive ERD visualizer for SQLAlchemy 2.0 models. Introspects your `DeclarativeBase` metadata and generates diagram files with no manual configuration required.
31
+
32
+ - Drag-and-drop interactive HTML output
33
+ - Auto-layout via force-directed algorithm
34
+ - Hover highlighting for tables and relationships
35
+ - Export to HTML, SVG, PNG, and PDF
36
+ - Built-in color themes and per-table color overrides
37
+ - Zero dependencies beyond SQLAlchemy
38
+
39
+ ![preview](examples/blog/blog.png)
40
+
41
+ ## Installation
42
+
43
+ ```bash
44
+ pip install sqlalchemy-erd
45
+ ```
46
+
47
+ PNG and PDF export require an optional dependency:
48
+
49
+ ```bash
50
+ pip install "sqlalchemy-erd[all]"
51
+ ```
52
+
53
+ ## Quick start
54
+
55
+ ```python
56
+ from sqlalchemy_erd import generate_erd
57
+ from myapp.models import Base
58
+
59
+ generate_erd(Base, output="erd.html")
60
+ ```
61
+
62
+ ## CLI
63
+
64
+ ```bash
65
+ # Interactive HTML (default)
66
+ sqlalchemy-erd myapp.models:Base
67
+
68
+ # Specific format and output path
69
+ sqlalchemy-erd myapp.models:Base --format svg --output erd.svg
70
+
71
+ # With theme and custom title
72
+ sqlalchemy-erd myapp.models:Base --format png --theme blue --title "My Schema"
73
+
74
+ # Per-table color overrides as JSON
75
+ sqlalchemy-erd myapp.models:Base --colors '{"users": "#1d4ed8", "orders": "#059669"}'
76
+
77
+ # High-resolution PNG
78
+ sqlalchemy-erd myapp.models:Base --format png --scale 3
79
+ ```
80
+
81
+ ## Python API
82
+
83
+ ```python
84
+ from sqlalchemy_erd import generate_erd
85
+ from myapp.models import Base
86
+
87
+ generate_erd(Base, output="erd.html", format="html")
88
+ generate_erd(Base, output="erd.svg", format="svg")
89
+ generate_erd(Base, output="erd.png", format="png", scale=2) # requires cairosvg
90
+ generate_erd(Base, output="erd.pdf", format="pdf") # requires cairosvg
91
+ ```
92
+
93
+ ## Themes
94
+
95
+ Five built-in themes: `default`, `blue`, `green`, `dark`, `rose`.
96
+
97
+ Preview images for each theme are available in [`examples/themes/`](examples/themes/).
98
+
99
+ ```python
100
+ generate_erd(Base, theme="dark")
101
+ ```
102
+
103
+ Per-table color overrides let you assign any hex color to individual tables while keeping the rest of the theme intact:
104
+
105
+ ```python
106
+ generate_erd(
107
+ Base,
108
+ theme="default",
109
+ table_colors={
110
+ "users": "#1e40af",
111
+ "orders": "#065f46",
112
+ "products": "#9f1239",
113
+ },
114
+ )
115
+ ```
116
+
117
+ ## Supported column types
118
+
119
+ | SQLAlchemy type | Badge |
120
+ |---|---|
121
+ | Primary key | `PK` |
122
+ | Foreign key | `FK` |
123
+ | `String` | `string` |
124
+ | `Text` | `text` |
125
+ | `Integer` / `BigInteger` / `SmallInteger` | `int` / `bigint` / `smallint` |
126
+ | `Float` / `Numeric` | `float` / `numeric` |
127
+ | `Date` | `date` |
128
+ | `DateTime` | `datetime` |
129
+ | `Boolean` | `bool` |
130
+ | `JSON` | `json` |
131
+ | `Uuid` | `uuid` |
132
+
133
+ Nullable columns display a `?` suffix (e.g. `text?`, `date?`).
134
+
135
+ ## Relationship types
136
+
137
+ | Cardinality | Line style |
138
+ |---|---|
139
+ | 1:N | Solid with arrow |
140
+ | N:N | Dashed with arrow |
141
+
142
+ ## Examples
143
+
144
+ See the [`examples/`](examples/) directory:
145
+
146
+ - [`examples/blog/`](examples/blog/) - blog schema (User, Post, Comment)
147
+ - [`examples/ecommerce/`](examples/ecommerce/) - 1:N chains (Category, Product, Order, Customer, OrderItem)
148
+ - [`examples/university/`](examples/university/) - N:N via association tables (Student, Course, Professor, Department)
149
+ - [`examples/hr/`](examples/hr/) - 1:1 and 1:N (Employee, EmployeeProfile, Department, Project)
150
+
151
+ ## License
152
+
153
+ MIT
@@ -0,0 +1,13 @@
1
+ sqlalchemy_erd/__init__.py,sha256=9mRod1ez4p9RLjI19Wbo4zcWxW8CZutPngfna9evEoM,1773
2
+ sqlalchemy_erd/cli.py,sha256=uGzOPLQ-COqH1EoUxPBTkwwiD_YaV-c0pdWbh9Z1bW0,3762
3
+ sqlalchemy_erd/export.py,sha256=4GfKLKx9ASERNFbFskyPkl54-Ur7TmLQ8ODlDNNRpio,1912
4
+ sqlalchemy_erd/html_renderer.py,sha256=PJzsVB-tQobTGGjV_hsnv6fG65OmxxtOsqnY1K9l98E,14891
5
+ sqlalchemy_erd/introspect.py,sha256=zw8FohfvcPoCIuN5nfGKFSNzhwF6PapFasoPam-4XQE,4458
6
+ sqlalchemy_erd/layout.py,sha256=jFr-OifD-REwKuDWDyDgS8hG6R-wMyopuM2QUnYNPto,3023
7
+ sqlalchemy_erd/renderer.py,sha256=MP8xGpH9d1aL9I-PDrK_RvmE5Xdd5A2ct7-GFBW1OAk,7808
8
+ sqlalchemy_erd/theme.py,sha256=30cPGZCCr81yn6zsNpCofrEwGqNEp-dhRER4B3mhFLA,2979
9
+ erdalchemy-0.1.0.dist-info/METADATA,sha256=BSx70KrDjEUM0NL41Q-qmipvUhTAMP2gKddBxNVvRMw,4166
10
+ erdalchemy-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
11
+ erdalchemy-0.1.0.dist-info/entry_points.txt,sha256=hHf4RHtS89nkNHpee5w8xWYxVZh-Z4EwkfzNGGAtZW0,59
12
+ erdalchemy-0.1.0.dist-info/licenses/LICENSE,sha256=pCDEr9PXBYS-kebMYd19au89zccgIo88pgRXnNwv618,1069
13
+ erdalchemy-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ sqlalchemy-erd = sqlalchemy_erd.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jose Velazco
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,49 @@
1
+ """sqlalchemy-erd: Interactive ERD visualization for SQLAlchemy 2.0 models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Union
7
+
8
+ from sqlalchemy import MetaData
9
+ from sqlalchemy.orm import DeclarativeBase
10
+
11
+ from sqlalchemy_erd.introspect import introspect_models
12
+ from sqlalchemy_erd.layout import force_directed_layout
13
+ from sqlalchemy_erd.theme import Theme, THEMES, get_theme
14
+ from sqlalchemy_erd.export import to_html, to_svg, to_png, to_pdf
15
+
16
+ __version__ = "0.1.0"
17
+
18
+
19
+ def generate_erd(
20
+ base_or_metadata: Union[type[DeclarativeBase], MetaData],
21
+ output: str = "erd.html",
22
+ format: str = "html",
23
+ theme: Union[str, Theme] = "default",
24
+ table_colors: dict[str, str] | None = None,
25
+ title: str = "ERD",
26
+ scale: int = 2,
27
+ ) -> Union[str, bytes]:
28
+ tables, relationships = introspect_models(base_or_metadata)
29
+ resolved_theme = get_theme(theme, table_colors)
30
+ positions = force_directed_layout(tables, relationships)
31
+
32
+ if format == "html":
33
+ content = to_html(tables, relationships, positions, resolved_theme, title=title)
34
+ Path(output).write_text(content, encoding="utf-8")
35
+ return content
36
+ elif format == "svg":
37
+ content = to_svg(tables, relationships, positions, resolved_theme)
38
+ Path(output).write_text(content, encoding="utf-8")
39
+ return content
40
+ elif format == "png":
41
+ data = to_png(tables, relationships, positions, resolved_theme, scale=scale)
42
+ Path(output).write_bytes(data)
43
+ return data
44
+ elif format == "pdf":
45
+ data = to_pdf(tables, relationships, positions, resolved_theme)
46
+ Path(output).write_bytes(data)
47
+ return data
48
+ else:
49
+ raise ValueError(f"Unknown format '{format}'. Use: html, svg, png, pdf")
sqlalchemy_erd/cli.py ADDED
@@ -0,0 +1,123 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import importlib
5
+ import json
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from sqlalchemy.orm import DeclarativeBase
10
+ from sqlalchemy import MetaData
11
+
12
+ from sqlalchemy_erd.introspect import introspect_models
13
+ from sqlalchemy_erd.layout import force_directed_layout
14
+ from sqlalchemy_erd.theme import get_theme, THEMES
15
+ from sqlalchemy_erd.export import to_svg, to_html, to_png, to_pdf
16
+
17
+
18
+ def _resolve_target(spec: str) -> type[DeclarativeBase] | MetaData:
19
+ if ":" in spec:
20
+ module_path, attr_name = spec.rsplit(":", 1)
21
+ else:
22
+ module_path = spec
23
+ attr_name = None
24
+
25
+ sys.path.insert(0, str(Path.cwd()))
26
+ module = importlib.import_module(module_path)
27
+
28
+ if attr_name:
29
+ obj = getattr(module, attr_name)
30
+ else:
31
+ obj = None
32
+ for name in dir(module):
33
+ val = getattr(module, name)
34
+ if isinstance(val, type) and issubclass(val, DeclarativeBase) and val is not DeclarativeBase:
35
+ obj = val
36
+ break
37
+ if obj is None:
38
+ for name in dir(module):
39
+ val = getattr(module, name)
40
+ if isinstance(val, MetaData):
41
+ obj = val
42
+ break
43
+ if obj is None:
44
+ print(f"Error: no DeclarativeBase subclass or MetaData found in '{module_path}'", file=sys.stderr)
45
+ sys.exit(1)
46
+
47
+ return obj
48
+
49
+
50
+ def main(argv: list[str] | None = None) -> None:
51
+ parser = argparse.ArgumentParser(
52
+ prog="sqlalchemy-erd",
53
+ description="Generate ERD diagrams from SQLAlchemy 2.0 models",
54
+ )
55
+ parser.add_argument(
56
+ "target",
57
+ help="Python import path to Base class (e.g., myapp.models:Base)",
58
+ )
59
+ parser.add_argument(
60
+ "-f", "--format",
61
+ choices=["html", "svg", "png", "pdf"],
62
+ default="html",
63
+ help="Output format (default: html)",
64
+ )
65
+ parser.add_argument(
66
+ "-o", "--output",
67
+ help="Output file path (default: erd.<format>)",
68
+ )
69
+ parser.add_argument(
70
+ "-t", "--theme",
71
+ choices=list(THEMES.keys()),
72
+ default="default",
73
+ help="Color theme (default: default)",
74
+ )
75
+ parser.add_argument(
76
+ "--colors",
77
+ help='Per-table color overrides as JSON: \'{"users": "#1d4ed8"}\'',
78
+ )
79
+ parser.add_argument(
80
+ "--scale",
81
+ type=int,
82
+ default=2,
83
+ help="Scale factor for PNG export (default: 2)",
84
+ )
85
+ parser.add_argument(
86
+ "--title",
87
+ default="ERD",
88
+ help="Title for HTML output (default: ERD)",
89
+ )
90
+
91
+ args = parser.parse_args(argv)
92
+
93
+ target = _resolve_target(args.target)
94
+ tables, relationships = introspect_models(target)
95
+
96
+ if not tables:
97
+ print("No tables found.", file=sys.stderr)
98
+ sys.exit(1)
99
+
100
+ table_colors = json.loads(args.colors) if args.colors else None
101
+ theme = get_theme(args.theme, table_colors)
102
+ positions = force_directed_layout(tables, relationships)
103
+
104
+ output_path = args.output or f"erd.{args.format}"
105
+
106
+ if args.format == "html":
107
+ content = to_html(tables, relationships, positions, theme, title=args.title)
108
+ Path(output_path).write_text(content, encoding="utf-8")
109
+ elif args.format == "svg":
110
+ content = to_svg(tables, relationships, positions, theme)
111
+ Path(output_path).write_text(content, encoding="utf-8")
112
+ elif args.format == "png":
113
+ data = to_png(tables, relationships, positions, theme, scale=args.scale)
114
+ Path(output_path).write_bytes(data)
115
+ elif args.format == "pdf":
116
+ data = to_pdf(tables, relationships, positions, theme)
117
+ Path(output_path).write_bytes(data)
118
+
119
+ print(f"Generated {output_path}")
120
+
121
+
122
+ if __name__ == "__main__":
123
+ main()
@@ -0,0 +1,63 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ from sqlalchemy_erd.introspect import TableInfo, RelationshipInfo
6
+ from sqlalchemy_erd.layout import force_directed_layout
7
+ from sqlalchemy_erd.renderer import render_svg
8
+ from sqlalchemy_erd.html_renderer import render_html
9
+ from sqlalchemy_erd.theme import Theme
10
+
11
+
12
+ def to_svg(
13
+ tables: list[TableInfo],
14
+ relationships: list[RelationshipInfo],
15
+ positions: dict[str, tuple[float, float]],
16
+ theme: Theme,
17
+ ) -> str:
18
+ return render_svg(tables, relationships, positions, theme, include_xml_header=True)
19
+
20
+
21
+ def to_html(
22
+ tables: list[TableInfo],
23
+ relationships: list[RelationshipInfo],
24
+ positions: dict[str, tuple[float, float]],
25
+ theme: Theme,
26
+ title: str = "ERD",
27
+ ) -> str:
28
+ return render_html(tables, relationships, positions, theme, title=title)
29
+
30
+
31
+ def to_png(
32
+ tables: list[TableInfo],
33
+ relationships: list[RelationshipInfo],
34
+ positions: dict[str, tuple[float, float]],
35
+ theme: Theme,
36
+ scale: int = 2,
37
+ ) -> bytes:
38
+ try:
39
+ import cairosvg
40
+ except ImportError:
41
+ raise ImportError(
42
+ "PNG export requires 'cairosvg'. Install it with: "
43
+ "pip install sqlalchemy-erd[png]"
44
+ )
45
+ svg_str = render_svg(tables, relationships, positions, theme, include_xml_header=True)
46
+ return cairosvg.svg2png(bytestring=svg_str.encode("utf-8"), scale=scale)
47
+
48
+
49
+ def to_pdf(
50
+ tables: list[TableInfo],
51
+ relationships: list[RelationshipInfo],
52
+ positions: dict[str, tuple[float, float]],
53
+ theme: Theme,
54
+ ) -> bytes:
55
+ try:
56
+ import cairosvg
57
+ except ImportError:
58
+ raise ImportError(
59
+ "PDF export requires 'cairosvg'. Install it with: "
60
+ "pip install sqlalchemy-erd[pdf]"
61
+ )
62
+ svg_str = render_svg(tables, relationships, positions, theme, include_xml_header=True)
63
+ return cairosvg.svg2pdf(bytestring=svg_str.encode("utf-8"))