Coverage for app / documents / visuals / mermaid / er.py: 89%
195 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""``erDiagram``.
3Read: entities with attribute blocks (``NAME { type name PK, FK "comment" }``),
4aliases (``p[Person]``, ``p["A person"]``), quoted names, and relationships
5``A ||--o{ B : label`` — cardinalities as symbols (``|o`` ``||`` ``}o`` ``}|``
6and their mirrors) or Mermaid's words (``one or zero``, ``zero or more``,
7``1+`` …), ``--`` identifying and ``..`` not, or ``to`` / ``optionally to``.
8"""
10from __future__ import annotations
12import re
13from dataclasses import dataclass, field
15from ..registry import Layout
16from ..text import ellipsize, measure
17from ..theme import Theme
18from . import look
19from .base import Diagram, MermaidSyntaxError, Statement, register_diagram
20from .canvas import Canvas, block_size
21from .compound import (
22 MAX_EDGES,
23 MAX_NODES,
24 Box,
25 Direction,
26 Edge,
27 Graph,
28 Node,
29 layout,
30 rect_boundary,
31)
32from .flowchart import _DIRECTIONS, label_box
33from .labels import clean, fit
34from .layered import Spacing
35from .markers import draw_edge
37_LEFT = {
38 "|o": "zero_or_one",
39 "||": "only_one",
40 "}o": "zero_or_more",
41 "}|": "one_or_more",
42}
43_RIGHT = {
44 "o|": "zero_or_one",
45 "||": "only_one",
46 "o{": "zero_or_more",
47 "|{": "one_or_more",
48}
49_WORDS = {
50 "one or zero": "zero_or_one", "zero or one": "zero_or_one",
51 "one or more": "one_or_more", "one or many": "one_or_more", "many(1)": "one_or_more", "1+": "one_or_more",
52 "zero or more": "zero_or_more", "zero or many": "zero_or_more", "many(0)": "zero_or_more", "0+": "zero_or_more",
53 "only one": "only_one", "1": "only_one",
54} # fmt: skip
55_ENTITY = r'(?:"[^"]+"|[\w-]+)(?:\[(?:"[^"]*"|[^\]]*)\])?'
56_SYMBOLS = re.compile(
57 rf"^(?P<a>{_ENTITY})\s*(?P<left>\|o|\|\||\}}o|\}}\|)(?P<line>--|\.\.)(?P<right>o\||\|\||o\{{|\|\{{)\s*(?P<b>{_ENTITY})\s*(?::\s*(?P<label>.*))?$"
58)
59_WORD_FORM = re.compile(
60 rf"^(?P<a>{_ENTITY})\s+(?P<left>{'|'.join(re.escape(w) for w in sorted(_WORDS, key=len, reverse=True))})\s+"
61 rf"(?P<line>optionally to|to)\s+(?P<right>{'|'.join(re.escape(w) for w in sorted(_WORDS, key=len, reverse=True))})\s+"
62 rf"(?P<b>{_ENTITY})\s*(?::\s*(?P<label>.*))?$"
63)
64_BLOCK = re.compile(rf"^(?P<name>{_ENTITY})\s*\{{\s*(?P<rest>.*)$")
65_ATTRIBUTE = re.compile(
66 r'^(?P<type>[^\s"]+)\s+(?P<name>[^\s"]+)(?:\s+(?P<keys>(?:PK|FK|UK)(?:\s*,\s*(?:PK|FK|UK))*))?(?:\s+"(?P<comment>[^"]*)")?\s*$'
67)
68#: The widest a cell runs before it is cut.
69CELL_WIDTH = 140.0
72@dataclass
73class Attribute:
74 type: str
75 name: str
76 keys: str
77 comment: str
80@dataclass
81class Entity:
82 id: str
83 label: str
84 attributes: list[Attribute] = field(default_factory=list)
87@dataclass
88class Relationship:
89 source: str
90 target: str
91 start: str
92 end: str
93 identifying: bool
94 label: str | None
97def _entity_name(text: str) -> tuple[str, str | None]:
98 """An entity's id and the alias it is shown by."""
99 m = re.fullmatch(
100 r'(?P<id>"[^"]+"|[\w-]+)(?:\[(?P<alias>"[^"]*"|[^\]]*)\])?', text.strip()
101 )
102 if not m:
103 return text.strip(), None
104 alias = m.group("alias")
105 return m.group("id").strip('"'), alias.strip('"') if alias else None
108@register_diagram
109class ERDiagram(Diagram):
110 keywords = ("erDiagram",)
111 noun = "an entity relationship diagram"
113 def __init__(self) -> None:
114 self.direction: Direction = "TB"
115 self.entities: dict[str, Entity] = {}
116 self.relationships: list[Relationship] = []
118 @classmethod
119 def parse(cls, header: Statement, statements: list[Statement]) -> ERDiagram:
120 diagram = cls()
121 lines = iter(statements)
122 for statement in lines:
123 text, line = statement.text, statement.line
124 first, _, rest = text.partition(" ")
125 if first == "direction":
126 found = _DIRECTIONS.get(rest.strip())
127 if found is None:
128 raise MermaidSyntaxError(
129 line, "the direction is not one Mermaid knows"
130 )
131 diagram.direction = found
132 continue
133 if first.startswith(("accTitle", "accDescr")):
134 continue
135 block = _BLOCK.match(text)
136 if block:
137 entity = diagram._entity(block.group("name"))
138 body = block.group("rest").strip()
139 if body.endswith("}"):
140 for part in body[:-1].split("\n"):
141 diagram._attribute(entity, part.strip(), line)
142 continue
143 if body:
144 diagram._attribute(entity, body, line)
145 for later in lines:
146 if later.text == "}":
147 break
148 if later.text.endswith("}"):
149 diagram._attribute(entity, later.text[:-1].strip(), later.line)
150 break
151 diagram._attribute(entity, later.text, later.line)
152 else:
153 raise MermaidSyntaxError(
154 line, "an entity's attributes have no closing '}'"
155 )
156 continue
157 m = _SYMBOLS.match(text)
158 if m:
159 diagram._relationship(
160 m,
161 _LEFT[m.group("left")],
162 _RIGHT[m.group("right")],
163 m.group("line") == "--",
164 )
165 continue
166 m = _WORD_FORM.match(text)
167 if m:
168 diagram._relationship(
169 m,
170 _WORDS[m.group("left")],
171 _WORDS[m.group("right")],
172 m.group("line") == "to",
173 )
174 continue
175 if re.fullmatch(_ENTITY, text):
176 diagram._entity(text)
177 continue
178 raise MermaidSyntaxError(
179 line, "this line is not an entity or a relationship"
180 )
181 return diagram
183 def _entity(self, text: str) -> Entity:
184 eid, alias = _entity_name(text)
185 entity = self.entities.get(eid)
186 if entity is None:
187 entity = self.entities[eid] = Entity(eid, alias or eid)
188 if len(self.entities) > MAX_NODES:
189 raise MermaidSyntaxError(None, f"it has more than {MAX_NODES} entities")
190 elif alias:
191 entity.label = alias
192 return entity
194 def _attribute(self, entity: Entity, text: str, line: int) -> None:
195 if not text:
196 return
197 m = _ATTRIBUTE.match(text)
198 if not m:
199 raise MermaidSyntaxError(
200 line,
201 "an attribute is written 'type name', then any keys and a quoted comment",
202 )
203 keys = ", ".join(
204 k.strip() for k in (m.group("keys") or "").split(",") if k.strip()
205 )
206 entity.attributes.append(
207 Attribute(m.group("type"), m.group("name"), keys, m.group("comment") or "")
208 )
210 def _relationship(
211 self, m: re.Match[str], start: str, end: str, identifying: bool
212 ) -> None:
213 a = self._entity(m.group("a"))
214 b = self._entity(m.group("b"))
215 label = (m.group("label") or "").strip().strip('"') or None
216 self.relationships.append(
217 Relationship(a.id, b.id, start, end, identifying, label)
218 )
219 if len(self.relationships) > MAX_EDGES:
220 raise MermaidSyntaxError(
221 None, f"it has more than {MAX_EDGES} relationships"
222 )
224 def _cells(self, entity: Entity, theme: Theme) -> list[list[str]]:
225 font, size = theme.regular, look.FONT_SIZE
226 rows = []
227 for attribute in entity.attributes:
228 rows.append(
229 [
230 ellipsize(" ".join(clean(value)), font, size, CELL_WIDTH)
231 if value
232 else ""
233 for value in (
234 attribute.type,
235 attribute.name,
236 attribute.keys,
237 attribute.comment,
238 )
239 ]
240 )
241 return rows
243 def layout(self, theme: Theme) -> Layout:
244 font, bold, size = theme.regular, theme.bold, look.FONT_SIZE
245 step = size * look.LINE_HEIGHT + 4.0
246 tables: dict[str, tuple[list[str], list[list[str]], list[float]]] = {}
247 nodes = []
248 for entity in self.entities.values():
249 title = fit(entity.label, bold, size, look.MAX_LINE_WIDTH, 2)
250 rows = self._cells(entity, theme)
251 columns = [
252 max((measure(row[c], font, size) for row in rows), default=0.0)
253 for c in range(4)
254 ]
255 widths = [w + 2 * look.PAD_X if w else 0.0 for w in columns]
256 tw, th = block_size(title, bold, size)
257 width = max(sum(widths), tw + 2 * look.PAD_X, 80.0)
258 spare = width - sum(widths)
259 if rows and spare > 0:
260 used = [i for i, w in enumerate(widths) if w] or [1]
261 for i in used:
262 widths[i] += spare / len(used)
263 height = th + 2 * look.PAD_Y + step * len(rows)
264 tables[entity.id] = (title, rows, widths)
265 nodes.append(Node(entity.id, width, max(height, 30.0)))
266 edges = []
267 edge_lines: list[list[str] | None] = []
268 for relationship in self.relationships:
269 lines = (
270 fit(relationship.label, font, size, 140.0, 3)
271 if relationship.label
272 else None
273 )
274 edge_lines.append(lines)
275 label = None
276 if lines:
277 tw, th = block_size(lines, font, size)
278 label = (tw + 6.0, th + 2.0)
279 edges.append(Edge(relationship.source, relationship.target, 1, label))
280 placed = layout(
281 Graph(
282 self.direction,
283 nodes,
284 edges,
285 [],
286 Spacing(look.NODE_SEP * 1.5, look.RANK_SEP * 1.6, look.EDGE_SEP),
287 ),
288 lambda _id, b, toward: rect_boundary(b, toward),
289 )
290 canvas = Canvas(placed.width, placed.height)
291 for relationship, route in zip(self.relationships, placed.routes):
292 if route is None:
293 continue
294 draw_edge(
295 canvas, route.points, color=look.LINE, width=look.EDGE_WIDTH,
296 dash=None if relationship.identifying else (3.0, 3.0),
297 start=relationship.start, end=relationship.end,
298 ) # fmt: skip
299 for route, lines in zip(placed.routes, edge_lines):
300 if route is not None and lines and route.label is not None:
301 label_box(
302 canvas, route.label, lines, font, size, look.TEXT, fill=look.WHITE
303 )
304 for entity in self.entities.values():
305 self._table(canvas, placed.nodes[entity.id], tables[entity.id], theme, step)
306 return Layout(
307 canvas.drawing(), placed.width, placed.height, breaks=placed.breaks
308 )
310 @staticmethod
311 def _table(
312 canvas: Canvas,
313 box: Box,
314 table: tuple[list[str], list[list[str]], list[float]],
315 theme: Theme,
316 step: float,
317 ) -> None:
318 font, bold, size = theme.regular, theme.bold, look.FONT_SIZE
319 title, rows, widths = table
320 _, th = block_size(title, bold, size)
321 head = th + 2 * look.PAD_Y
322 canvas.rect(
323 box.x,
324 box.y,
325 box.width,
326 box.height,
327 fill=look.NODE_FILL,
328 stroke=look.NODE_STROKE,
329 width=look.NODE_STROKE_WIDTH,
330 )
331 canvas.lines(
332 box.cx,
333 box.y + head / 2 if rows else box.cy,
334 title,
335 font=bold,
336 size=size,
337 color=look.TEXT,
338 )
339 y = box.y + head
340 for i, row in enumerate(rows):
341 canvas.rect(
342 box.x, y, box.width, step,
343 fill=look.ROW_ODD if i % 2 == 0 else look.ROW_EVEN, stroke=look.NODE_STROKE, width=0.5,
344 ) # fmt: skip
345 x = box.x
346 for text, width in zip(row, widths):
347 if width and text:
348 canvas.text(
349 x + look.PAD_X,
350 y + step / 2 + size * 0.35,
351 text,
352 font=font,
353 size=size,
354 color=look.TEXT,
355 anchor="start",
356 )
357 x += width
358 y += step
359 if rows:
360 canvas.rect(
361 box.x,
362 box.y,
363 box.width,
364 box.height,
365 fill=None,
366 stroke=look.NODE_STROKE,
367 width=look.NODE_STROKE_WIDTH,
368 )