Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
## v1.3.0 (Unreleased)

- Removed support for Python 3.9. ([PR #171](https://github.com/drivendataorg/erdantic/pull/171))
- Added Mermaid ER diagram output via `EntityRelationshipDiagram.to_mermaid()` and the CLI
`--mermaid` option. ([Issue #163](https://github.com/drivendataorg/erdantic/issues/163))

### Documentation

Expand Down
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,15 @@ list(diagram.models.keys())
diagram.draw("diagram.png")
```

To generate Mermaid ER diagram source instead of an image, use the `--mermaid` CLI option or
the diagram object's `to_mermaid()` method:

```bash
erdantic erdantic.examples.pydantic.Party --mermaid > diagram.mmd
```

```python
mermaid = diagram.to_mermaid()
```

Check out the "Usage Examples" section of our [docs](https://erdantic.drivendata.org/) to see more.
Binary file added diagram.mmd
Binary file not shown.
26 changes: 24 additions & 2 deletions erdantic/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,15 @@ def d2_callback(ctx: typer.Context, d2: bool):
return d2


def mermaid_callback(ctx: typer.Context, mermaid: bool):
"""Set --out to not be required for Mermaid output since it prints to console."""
if mermaid:
for param in ctx.command.params:
if param.name == "out":
param.required = False
return mermaid


def list_plugins_callback(list_plugins: bool):
if list_plugins:
active_plugins = erdantic.plugins.list_plugins()
Expand Down Expand Up @@ -152,6 +161,17 @@ def main(
),
),
] = False,
mermaid: Annotated[
bool,
typer.Option(
"--mermaid",
callback=mermaid_callback,
help=(
"Print out Mermaid ER diagram representation to console instead of rendering an "
"image. The --out option will be ignored."
),
),
] = False,
no_overwrite: Annotated[
bool,
typer.Option("--no-overwrite", help="Prevent overwriting an existing file."),
Expand Down Expand Up @@ -200,8 +220,8 @@ def main(
attrs, and standard library dataclasses.
"""

if dot and d2:
logger.error("The --dot and --d2 options are mutually exclusive.")
if sum([dot, d2, mermaid]) > 1:
logger.error("The --dot, --d2, and --mermaid options are mutually exclusive.")
raise typer.Exit(code=1)
# Set up logger
log_level = logging.INFO + 10 * quiet - 10 * verbose
Expand Down Expand Up @@ -237,6 +257,8 @@ def main(
typer.echo(diagram.to_dot())
elif d2:
typer.echo(diagram.to_d2())
elif mermaid:
typer.echo(diagram.to_mermaid())
else:
if out.exists() and no_overwrite:
logger.error(f"{out} already exists, and you specified --no-overwrite.")
Expand Down
10 changes: 10 additions & 0 deletions erdantic/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,16 @@ def to_d2(self) -> str:

return render_d2(self)

def to_mermaid(self) -> str:
"""Generate Mermaid ER diagram representation of the entity relationship diagram.

Returns:
str: Mermaid diagram source
"""
from erdantic.mermaid import render_mermaid

return render_mermaid(self)

def _repr_pretty_(self, p, cycle):
"""IPython special method to pretty-print an object."""
try:
Expand Down
53 changes: 53 additions & 0 deletions erdantic/mermaid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
from __future__ import annotations

import re

from erdantic.core import Cardinality, EntityRelationshipDiagram, Modality


_CARDINALITY_MARKERS = {
(Cardinality.ONE, Modality.ONE): "||",
(Cardinality.ONE, Modality.ZERO): "o|",
(Cardinality.MANY, Modality.ONE): "|{",
(Cardinality.MANY, Modality.ZERO): "o{",
}


def _identifier(name: str) -> str:
"""Return a Mermaid-safe identifier while preserving ordinary Python names."""
identifier = re.sub(r"[^A-Za-z0-9_]", "_", name)
return identifier or "unnamed"


def _attribute_type(type_name: str) -> str:
"""Keep type annotations readable while limiting them to Mermaid type characters."""
return re.sub(r"[^A-Za-z0-9_.-]", "_", type_name)


def _target_marker(cardinality: Cardinality, modality: Modality) -> str:
if cardinality == Cardinality.UNSPECIFIED:
cardinality = Cardinality.ONE
if modality == Modality.UNSPECIFIED:
modality = Modality.ZERO
return _CARDINALITY_MARKERS[(cardinality, modality)]


def render_mermaid(diagram: EntityRelationshipDiagram) -> str:
"""Render an EntityRelationshipDiagram as a Mermaid ER diagram."""
lines = ["erDiagram"]

for model in diagram.models.values():
lines.append(f" {_identifier(model.name)} {{")
for field in model.fields.values():
lines.append(
f" {_attribute_type(field.type_name)} {_identifier(field.name)}"
)
lines.append(" }")

for edge in diagram.edges.values():
source = _identifier(edge.source_model_full_name.qual_name.split(".")[-1])
target = _identifier(edge.target_model_full_name.qual_name.split(".")[-1])
target_marker = _target_marker(edge.target_cardinality, edge.target_modality)
lines.append(f" {source} ||--{target_marker} {target} : {edge.source_field_name}")

return "\n".join(lines) + "\n"
19 changes: 19 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,3 +260,22 @@ def test_d2(tmp_path):
# Test that --dot and --d2 are mutually exclusive
result = runner.invoke(app, ["erdantic.examples.pydantic.Party", "--dot", "--d2"])
assert result.exit_code == 1


def test_mermaid(tmp_path):
result = runner.invoke(app, ["erdantic.examples.pydantic.Party", "--mermaid"])
assert result.exit_code == 0
expected_out = erd.create(erd.examples.pydantic.Party).to_mermaid()
assert result.stdout.strip() == expected_out.strip()

path = tmp_path / "diagram.mmd"
result = runner.invoke(
app, ["erdantic.examples.pydantic.Party", "--mermaid", "-o", str(path)]
)
assert result.exit_code == 0
assert not path.exists()

result = runner.invoke(
app, ["erdantic.examples.pydantic.Party", "--dot", "--mermaid"]
)
assert result.exit_code == 1
33 changes: 33 additions & 0 deletions tests/test_mermaid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import erdantic as erd
from erdantic.core import Cardinality, Modality
from erdantic.examples import pydantic
from erdantic.mermaid import _target_marker, render_mermaid


def test_render_mermaid():
diagram = erd.create(pydantic.Party)
output = render_mermaid(diagram)

assert output.startswith("erDiagram\n")
assert " Party {" in output
assert " list_Adventurer_ members" in output
assert " Optional_Quest_ active_quest" in output
assert " Party ||--o{ Adventurer : members" in output
assert " Party ||--o| Quest : active_quest" in output
assert " Quest ||--|| QuestGiver : giver" in output


def test_target_marker():
assert _target_marker(Cardinality.ONE, Modality.ONE) == "||"
assert _target_marker(Cardinality.ONE, Modality.ZERO) == "o|"
assert _target_marker(Cardinality.MANY, Modality.ONE) == "|{"
assert _target_marker(Cardinality.MANY, Modality.ZERO) == "o{"
assert _target_marker(Cardinality.UNSPECIFIED, Modality.UNSPECIFIED) == "o|"


def test_mermaid_names_are_sanitized():
diagram = erd.create(pydantic.Party)
model = next(iter(diagram.models.values()))
model.name = "Party With Spaces"
output = render_mermaid(diagram)
assert " Party_With_Spaces {" in output