erdify-studio 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.
- erdify_studio/__init__.py +63 -0
- erdify_studio/__main__.py +7 -0
- erdify_studio/_check.py +215 -0
- erdify_studio/_config.py +95 -0
- erdify_studio/_diagrams.py +433 -0
- erdify_studio/_entities.py +101 -0
- erdify_studio/_errors.py +48 -0
- erdify_studio/_export.py +353 -0
- erdify_studio/_geometry.py +181 -0
- erdify_studio/_layout.py +334 -0
- erdify_studio/_place.py +351 -0
- erdify_studio/_server.py +536 -0
- erdify_studio/_static/THIRD_PARTY_LICENSES.txt +552 -0
- erdify_studio/_static/assets/Toast-DKNikwgv.js +15 -0
- erdify_studio/_static/assets/index-BwaNC2Tp.css +1 -0
- erdify_studio/_static/assets/index-DCr6Tq0B.js +15 -0
- erdify_studio/_static/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
- erdify_studio/_static/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
- erdify_studio/_static/assets/jetbrains-mono-cyrillic-700-normal-BWTpRfYl.woff2 +0 -0
- erdify_studio/_static/assets/jetbrains-mono-cyrillic-700-normal-CEoEElIJ.woff +0 -0
- erdify_studio/_static/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
- erdify_studio/_static/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
- erdify_studio/_static/assets/jetbrains-mono-greek-700-normal-C6CZE3T8.woff2 +0 -0
- erdify_studio/_static/assets/jetbrains-mono-greek-700-normal-DEigVDxa.woff +0 -0
- erdify_studio/_static/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
- erdify_studio/_static/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- erdify_studio/_static/assets/jetbrains-mono-latin-700-normal-BYuf6tUa.woff2 +0 -0
- erdify_studio/_static/assets/jetbrains-mono-latin-700-normal-D3wTyLJW.woff +0 -0
- erdify_studio/_static/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- erdify_studio/_static/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
- erdify_studio/_static/assets/jetbrains-mono-latin-ext-700-normal-CZipNAKV.woff2 +0 -0
- erdify_studio/_static/assets/jetbrains-mono-latin-ext-700-normal-CxPITLHs.woff +0 -0
- erdify_studio/_static/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
- erdify_studio/_static/assets/jetbrains-mono-vietnamese-700-normal-BDLVIk2r.woff +0 -0
- erdify_studio/_static/index.html +13 -0
- erdify_studio/_svg.py +250 -0
- erdify_studio/cli.py +272 -0
- erdify_studio/py.typed +0 -0
- erdify_studio-0.1.0.dist-info/METADATA +224 -0
- erdify_studio-0.1.0.dist-info/RECORD +43 -0
- erdify_studio-0.1.0.dist-info/WHEEL +4 -0
- erdify_studio-0.1.0.dist-info/entry_points.txt +2 -0
- erdify_studio-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
"""Every diagram as the canvas draws it, as JSON-ready dicts.
|
|
2
|
+
|
|
3
|
+
Python owns everything the canvas shows: the boxes with their sizes (from
|
|
4
|
+
``_place``, so the canvas and ``place --auto`` agree), positions including the
|
|
5
|
+
ones ``place --auto`` would give unplaced boxes, erdify's edges, and the
|
|
6
|
+
revision of the layout file the positions were read from.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
from collections.abc import Mapping
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Literal, TypedDict
|
|
16
|
+
|
|
17
|
+
from erdify import EdgeEnd, Project, diagram_edges
|
|
18
|
+
|
|
19
|
+
from erdify_studio._check import DiagramContent, drawn_enums, project_diagrams
|
|
20
|
+
from erdify_studio._config import StudioConfig
|
|
21
|
+
from erdify_studio._entities import entity_groups, entity_ids, entity_keys, enum_key
|
|
22
|
+
from erdify_studio._errors import LayoutConflictError, LayoutError, PositionsError
|
|
23
|
+
from erdify_studio._layout import (
|
|
24
|
+
DEFAULT_GROUP,
|
|
25
|
+
OVERVIEW,
|
|
26
|
+
Layout,
|
|
27
|
+
load_existing_layout,
|
|
28
|
+
save_layout,
|
|
29
|
+
)
|
|
30
|
+
from erdify_studio._place import METRICS, PlaceResult, name_box_size, place_inputs, place_layout
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class FieldRow(TypedDict):
|
|
34
|
+
"""One field of an entity box."""
|
|
35
|
+
|
|
36
|
+
name: str
|
|
37
|
+
type: str
|
|
38
|
+
pk: bool
|
|
39
|
+
fk: bool
|
|
40
|
+
uk: bool
|
|
41
|
+
nullable: bool
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ValueRow(TypedDict):
|
|
45
|
+
"""One value of an enum box."""
|
|
46
|
+
|
|
47
|
+
name: str
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class BoxDef(TypedDict):
|
|
51
|
+
"""An entity or enum box, sent once for every diagram that shows it.
|
|
52
|
+
|
|
53
|
+
``group`` is the entity's group diagram; None for enums and without groups.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
kind: Literal["entity", "enum"]
|
|
57
|
+
title: str
|
|
58
|
+
group: str | None
|
|
59
|
+
width: int
|
|
60
|
+
height: int
|
|
61
|
+
rows: list[FieldRow] | list[ValueRow]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class EdgeEndJson(TypedDict):
|
|
65
|
+
"""One end of an edge: optional (zero allowed) and many (more than one)."""
|
|
66
|
+
|
|
67
|
+
optional: bool
|
|
68
|
+
many: bool
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
EdgeJson = TypedDict(
|
|
72
|
+
"EdgeJson",
|
|
73
|
+
{
|
|
74
|
+
"from": str,
|
|
75
|
+
"to": str,
|
|
76
|
+
"fromEnd": EdgeEndJson,
|
|
77
|
+
"toEnd": EdgeEndJson,
|
|
78
|
+
"kind": str,
|
|
79
|
+
"label": str,
|
|
80
|
+
},
|
|
81
|
+
)
|
|
82
|
+
"""An edge of ``erdify.diagram_edges`` between two layout keys."""
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class EnumLink(TypedDict):
|
|
86
|
+
"""An enum and an entity using it."""
|
|
87
|
+
|
|
88
|
+
enum: str
|
|
89
|
+
entity: str
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class Pending(TypedDict):
|
|
93
|
+
"""What Save would change before anything is dragged.
|
|
94
|
+
|
|
95
|
+
``placed``: boxes placed automatically, over all diagrams. ``diagrams``: how many
|
|
96
|
+
diagrams have such boxes. ``dropped``: stale entries plus stale diagrams.
|
|
97
|
+
``created``: there is no layout file yet. ``svgs``: exported SVGs that are missing,
|
|
98
|
+
out of date or stale (``_export.build_studio`` fills it; 0 here).
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
placed: int
|
|
102
|
+
diagrams: int
|
|
103
|
+
dropped: int
|
|
104
|
+
created: bool
|
|
105
|
+
svgs: int
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class DiagramJson(TypedDict):
|
|
109
|
+
"""One diagram: the keys it shows, where, and what it draws between them.
|
|
110
|
+
|
|
111
|
+
``own``: its entities and enums; ``foreign``: name-only boxes of other groups,
|
|
112
|
+
sized by ``foreignSizes``; ``positions``: every shown key (top-left, canvas
|
|
113
|
+
units); ``new``: keys placed automatically, not yet in the layout file.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
name: str
|
|
117
|
+
label: str
|
|
118
|
+
own: list[str]
|
|
119
|
+
foreign: list[str]
|
|
120
|
+
foreignSizes: dict[str, list[int]]
|
|
121
|
+
positions: dict[str, list[int]]
|
|
122
|
+
new: list[str]
|
|
123
|
+
edges: list[EdgeJson]
|
|
124
|
+
enumLinks: list[EnumLink]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class Diagrams(TypedDict):
|
|
128
|
+
"""The JSON of ``GET /api/diagrams``."""
|
|
129
|
+
|
|
130
|
+
metrics: dict[str, int]
|
|
131
|
+
boxes: dict[str, BoxDef]
|
|
132
|
+
diagrams: list[DiagramJson]
|
|
133
|
+
revision: str | None
|
|
134
|
+
pending: Pending
|
|
135
|
+
layoutPath: str
|
|
136
|
+
projectPath: str
|
|
137
|
+
exportPath: str | None
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
#: Labels of the diagrams that aren't named after a group.
|
|
141
|
+
_LABELS = {OVERVIEW: "Overview", DEFAULT_GROUP: "Ungrouped"}
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _label(name: str) -> str:
|
|
145
|
+
"""The diagram's name as the UI lists it; a group never looks like a built-in one."""
|
|
146
|
+
if name in _LABELS:
|
|
147
|
+
return _LABELS[name]
|
|
148
|
+
return f"{name} (group)" if name in _LABELS.values() else name
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def layout_revision(path: Path) -> str | None:
|
|
152
|
+
"""The sha256 hex digest of the file at ``path``; None when there is none.
|
|
153
|
+
|
|
154
|
+
Raises:
|
|
155
|
+
OSError: The file exists but cannot be read.
|
|
156
|
+
"""
|
|
157
|
+
try:
|
|
158
|
+
return hashlib.sha256(path.read_bytes()).hexdigest()
|
|
159
|
+
except FileNotFoundError:
|
|
160
|
+
return None
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def build_diagrams(project: Project, config: StudioConfig, *, shown_path: str) -> Diagrams:
|
|
164
|
+
"""Every diagram of ``project`` with the positions of its layout file.
|
|
165
|
+
|
|
166
|
+
Boxes without a position get the one ``place --auto`` would give them and are
|
|
167
|
+
listed as ``new``. Nothing is written. Order: the overview, the groups by name,
|
|
168
|
+
``DEFAULT_GROUP`` last.
|
|
169
|
+
|
|
170
|
+
Args:
|
|
171
|
+
project: The project as ``erdify.load_project(..., strict=True)`` returns it.
|
|
172
|
+
config: Its studio settings.
|
|
173
|
+
shown_path: The layout file's path as the UI shows it.
|
|
174
|
+
|
|
175
|
+
Raises:
|
|
176
|
+
ProjectError: The project has no entities and erdify's ``allow_empty`` is off.
|
|
177
|
+
DuplicateKeyError: An entity keyed by its erdify name has another entity's key.
|
|
178
|
+
LayoutVersionError: The layout file is of another version.
|
|
179
|
+
LayoutError: A reserved group name, or a layout file that cannot be read.
|
|
180
|
+
OSError: The layout file cannot be read.
|
|
181
|
+
"""
|
|
182
|
+
revision = layout_revision(config.layout)
|
|
183
|
+
existing = load_existing_layout(config.layout)
|
|
184
|
+
payload = build_from(project, config, existing or Layout(), created=existing is None)
|
|
185
|
+
payload["revision"] = revision
|
|
186
|
+
payload["layoutPath"] = shown_path
|
|
187
|
+
return payload
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def model_fingerprint(project: Project, config: StudioConfig) -> str:
|
|
191
|
+
"""A digest of what the canvas draws, positions aside; changes with the models.
|
|
192
|
+
|
|
193
|
+
Built without the layout file, so a broken or edited layout file never looks like
|
|
194
|
+
a model change. Comments and formatting in the model files don't change it.
|
|
195
|
+
"""
|
|
196
|
+
payload = build_from(project, config, Layout(), created=True)
|
|
197
|
+
shape = {
|
|
198
|
+
"metrics": payload["metrics"],
|
|
199
|
+
"boxes": payload["boxes"],
|
|
200
|
+
"diagrams": [
|
|
201
|
+
{k: v for k, v in d.items() if k not in ("positions", "new")}
|
|
202
|
+
for d in payload["diagrams"]
|
|
203
|
+
],
|
|
204
|
+
"exportDir": None if config.export_dir is None else str(config.export_dir),
|
|
205
|
+
}
|
|
206
|
+
text = json.dumps(shape, sort_keys=True, separators=(",", ":"))
|
|
207
|
+
return hashlib.sha256(text.encode()).hexdigest()
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def build_from(project: Project, config: StudioConfig, start: Layout, *, created: bool) -> Diagrams:
|
|
211
|
+
"""The payload of ``project`` with every box placed, starting from ``start``.
|
|
212
|
+
|
|
213
|
+
``revision`` and ``layoutPath`` are left empty; ``pending`` is relative to
|
|
214
|
+
``start``, ``new`` lists the boxes placed here.
|
|
215
|
+
"""
|
|
216
|
+
contents = project_diagrams(project, config)
|
|
217
|
+
sizes, edges = place_inputs(project)
|
|
218
|
+
result = place_layout(start, contents, sizes=sizes, edges=edges, created=created)
|
|
219
|
+
all_edges = _edges(project)
|
|
220
|
+
all_links = _enum_links(project)
|
|
221
|
+
new: dict[str, list[str]] = {}
|
|
222
|
+
for diagram, key in result.placed:
|
|
223
|
+
new.setdefault(diagram, []).append(key)
|
|
224
|
+
|
|
225
|
+
def order(name: str) -> tuple[int, str]:
|
|
226
|
+
return (0 if name == OVERVIEW else 2 if name == DEFAULT_GROUP else 1, name)
|
|
227
|
+
|
|
228
|
+
diagrams: list[DiagramJson] = []
|
|
229
|
+
for name in sorted(contents, key=order):
|
|
230
|
+
content = contents[name]
|
|
231
|
+
foreign = sorted(content.foreign - content.entities)
|
|
232
|
+
diagrams.append(
|
|
233
|
+
{
|
|
234
|
+
"name": name,
|
|
235
|
+
"label": _label(name),
|
|
236
|
+
"own": sorted(content.entities | content.enums),
|
|
237
|
+
"foreign": foreign,
|
|
238
|
+
"foreignSizes": {key: list(name_box_size(key)) for key in foreign},
|
|
239
|
+
"positions": {
|
|
240
|
+
key: [x, y] for key, (x, y) in sorted(result.layout.diagrams[name].items())
|
|
241
|
+
},
|
|
242
|
+
"new": sorted(new.get(name, [])),
|
|
243
|
+
"edges": [e for e in all_edges if content.shows_edge(e["from"], e["to"])],
|
|
244
|
+
"enumLinks": [
|
|
245
|
+
link
|
|
246
|
+
for link in all_links
|
|
247
|
+
if content.shows_enum_link(link["enum"], link["entity"])
|
|
248
|
+
],
|
|
249
|
+
}
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
return {
|
|
253
|
+
"metrics": dict(METRICS),
|
|
254
|
+
"boxes": _boxes(project, config, sizes, contents[OVERVIEW]),
|
|
255
|
+
"diagrams": diagrams,
|
|
256
|
+
"revision": None,
|
|
257
|
+
"pending": _pending(result),
|
|
258
|
+
"layoutPath": "",
|
|
259
|
+
"projectPath": str(project.settings.input),
|
|
260
|
+
"exportPath": None,
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def save_diagrams(
|
|
265
|
+
project: Project, config: StudioConfig, diagrams: object, revision: str | None
|
|
266
|
+
) -> str | None:
|
|
267
|
+
"""Save the positions of every diagram and return the layout file's new revision.
|
|
268
|
+
|
|
269
|
+
Writes exactly these positions, then what ``place --auto`` would add (nothing for
|
|
270
|
+
a complete body), so ``check_project`` passes afterwards.
|
|
271
|
+
|
|
272
|
+
Args:
|
|
273
|
+
project: The project as ``erdify.load_project(..., strict=True)`` returns it.
|
|
274
|
+
config: Its studio settings.
|
|
275
|
+
diagrams: Diagram name -> layout key -> ``[x, y]`` for every box of every
|
|
276
|
+
diagram, as decoded from JSON (validated here).
|
|
277
|
+
revision: ``layout_revision`` of the file the positions were based on.
|
|
278
|
+
|
|
279
|
+
Raises:
|
|
280
|
+
LayoutConflictError: The file's revision is not ``revision`` any more.
|
|
281
|
+
LayoutConflictError: Other diagrams or boxes than the project has: the models
|
|
282
|
+
changed since the page loaded.
|
|
283
|
+
PositionsError: ``diagrams`` or a diagram is not an object, or a position is
|
|
284
|
+
not a pair of finite numbers within the coordinate limit.
|
|
285
|
+
LayoutError: The layout file cannot be read or written (see ``save_layout``).
|
|
286
|
+
"""
|
|
287
|
+
current = layout_revision(config.layout)
|
|
288
|
+
if current != revision:
|
|
289
|
+
raise LayoutConflictError(
|
|
290
|
+
f"{str(config.layout)!r} changed since the positions were read from it"
|
|
291
|
+
)
|
|
292
|
+
if not isinstance(diagrams, Mapping):
|
|
293
|
+
raise PositionsError(f"diagrams must be an object, got {type(diagrams).__name__!r}")
|
|
294
|
+
contents = project_diagrams(project, config)
|
|
295
|
+
missing = sorted(contents.keys() - diagrams.keys())
|
|
296
|
+
unknown = sorted(diagrams.keys() - contents.keys())
|
|
297
|
+
if missing or unknown:
|
|
298
|
+
first = f"no diagram {unknown[0]!r} any more" if unknown else f"new diagram {missing[0]!r}"
|
|
299
|
+
raise LayoutConflictError(
|
|
300
|
+
f"the models changed since the page loaded ({first}); reload the page",
|
|
301
|
+
reason="models",
|
|
302
|
+
)
|
|
303
|
+
layout = Layout()
|
|
304
|
+
for name, content in contents.items():
|
|
305
|
+
layout.add_diagram(name)
|
|
306
|
+
for key, (x, y) in checked_positions(diagrams[name], content.shown).items():
|
|
307
|
+
try:
|
|
308
|
+
layout.set_position(name, key, x, y)
|
|
309
|
+
except LayoutError as e:
|
|
310
|
+
raise PositionsError(str(e)) from None
|
|
311
|
+
sizes, edges = place_inputs(project)
|
|
312
|
+
result = place_layout(layout, contents, sizes=sizes, edges=edges)
|
|
313
|
+
save_layout(result.layout, config.layout)
|
|
314
|
+
return layout_revision(config.layout)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def checked_positions(positions: object, shown: frozenset[str]) -> dict[str, tuple[float, float]]:
|
|
318
|
+
"""``positions`` narrowed to key -> ``(x, y)`` numbers, with exactly the ``shown`` keys."""
|
|
319
|
+
if not isinstance(positions, Mapping):
|
|
320
|
+
raise PositionsError(f"positions must be an object, got {type(positions).__name__!r}")
|
|
321
|
+
# Other boxes than the diagram shows: the page was loaded before the models
|
|
322
|
+
# changed (e.g. a `git checkout`). Saving would drop the positions it lacks.
|
|
323
|
+
missing = sorted(shown - positions.keys())
|
|
324
|
+
unknown = sorted(positions.keys() - shown)
|
|
325
|
+
if missing or unknown:
|
|
326
|
+
first = f"no box {unknown[0]!r} any more" if unknown else f"new box {missing[0]!r}"
|
|
327
|
+
raise LayoutConflictError(
|
|
328
|
+
f"the models changed since the page loaded ({first}); reload the page",
|
|
329
|
+
reason="models",
|
|
330
|
+
)
|
|
331
|
+
checked: dict[str, tuple[float, float]] = {}
|
|
332
|
+
for key, value in positions.items():
|
|
333
|
+
if (
|
|
334
|
+
not isinstance(value, list)
|
|
335
|
+
or len(value) != 2
|
|
336
|
+
or not all(isinstance(v, int | float) and not isinstance(v, bool) for v in value)
|
|
337
|
+
):
|
|
338
|
+
raise PositionsError(f"position of {key!r} must be [x, y] numbers, got {value!r}")
|
|
339
|
+
checked[key] = (value[0], value[1])
|
|
340
|
+
return checked
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _boxes(
|
|
344
|
+
project: Project,
|
|
345
|
+
config: StudioConfig,
|
|
346
|
+
sizes: Mapping[str, tuple[int, int]],
|
|
347
|
+
overview: DiagramContent,
|
|
348
|
+
) -> dict[str, BoxDef]:
|
|
349
|
+
"""Every entity and drawn enum, by layout key, sorted."""
|
|
350
|
+
keys = entity_keys(project.entities)
|
|
351
|
+
groups = entity_groups(project.entities, config.group_by)
|
|
352
|
+
boxes: dict[str, BoxDef] = {}
|
|
353
|
+
for name, entity in project.entities.items():
|
|
354
|
+
key = keys[name]
|
|
355
|
+
rows: list[FieldRow] = [
|
|
356
|
+
{
|
|
357
|
+
"name": f.name,
|
|
358
|
+
"type": f.type_str,
|
|
359
|
+
"pk": f.is_primary_key,
|
|
360
|
+
"fk": f.is_foreign_key,
|
|
361
|
+
"uk": f.is_unique,
|
|
362
|
+
"nullable": f.is_nullable,
|
|
363
|
+
}
|
|
364
|
+
for f in entity.fields
|
|
365
|
+
]
|
|
366
|
+
width, height = sizes[key]
|
|
367
|
+
boxes[key] = {
|
|
368
|
+
"kind": "entity",
|
|
369
|
+
"title": key,
|
|
370
|
+
"group": groups.get(name),
|
|
371
|
+
"width": width,
|
|
372
|
+
"height": height,
|
|
373
|
+
"rows": rows,
|
|
374
|
+
}
|
|
375
|
+
for enum in project.enums.values():
|
|
376
|
+
key = enum_key(enum)
|
|
377
|
+
if key in overview.enums:
|
|
378
|
+
values: list[ValueRow] = [{"name": str(value)} for value in enum.values]
|
|
379
|
+
width, height = sizes[key]
|
|
380
|
+
boxes[key] = {
|
|
381
|
+
"kind": "enum",
|
|
382
|
+
"title": enum.name,
|
|
383
|
+
"group": None,
|
|
384
|
+
"width": width,
|
|
385
|
+
"height": height,
|
|
386
|
+
"rows": values,
|
|
387
|
+
}
|
|
388
|
+
return dict(sorted(boxes.items()))
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _end(end: EdgeEnd) -> EdgeEndJson:
|
|
392
|
+
return {"optional": end.optional, "many": end.many}
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _edges(project: Project) -> list[EdgeJson]:
|
|
396
|
+
if project.settings.no_relationships:
|
|
397
|
+
return []
|
|
398
|
+
keys = entity_keys(project.entities)
|
|
399
|
+
ids = entity_ids(project.entities)
|
|
400
|
+
return [
|
|
401
|
+
{
|
|
402
|
+
"from": keys[ids[edge.from_entity]],
|
|
403
|
+
"to": keys[ids[edge.to_entity]],
|
|
404
|
+
"fromEnd": _end(edge.from_end),
|
|
405
|
+
"toEnd": _end(edge.to_end),
|
|
406
|
+
"kind": str(edge.kind),
|
|
407
|
+
"label": edge.label,
|
|
408
|
+
}
|
|
409
|
+
for edge in diagram_edges(project.entities)
|
|
410
|
+
]
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _enum_links(project: Project) -> list[EnumLink]:
|
|
414
|
+
keys = entity_keys(project.entities)
|
|
415
|
+
ids = entity_ids(project.entities)
|
|
416
|
+
return sorted(
|
|
417
|
+
(
|
|
418
|
+
{"enum": enum, "entity": keys[ids[name]]}
|
|
419
|
+
for enum, users in drawn_enums(project).items()
|
|
420
|
+
for name in users
|
|
421
|
+
),
|
|
422
|
+
key=lambda link: (link["enum"], link["entity"]),
|
|
423
|
+
)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _pending(result: PlaceResult) -> Pending:
|
|
427
|
+
return {
|
|
428
|
+
"placed": len(result.placed),
|
|
429
|
+
"diagrams": len({diagram for diagram, _ in result.placed}),
|
|
430
|
+
"dropped": len(result.removed) + len(result.removed_diagrams),
|
|
431
|
+
"created": result.created,
|
|
432
|
+
"svgs": 0,
|
|
433
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Layout keys and diagram groups of erdify's entities."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import Counter
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
|
|
8
|
+
from erdify import EntityInfo, EnumInfo
|
|
9
|
+
|
|
10
|
+
from erdify_studio._config import GroupBy
|
|
11
|
+
from erdify_studio._errors import DuplicateKeyError, LayoutError
|
|
12
|
+
from erdify_studio._layout import DEFAULT_GROUP, OVERVIEW
|
|
13
|
+
|
|
14
|
+
_RESERVED = (OVERVIEW, DEFAULT_GROUP)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def entity_key(entity: EntityInfo) -> str:
|
|
18
|
+
"""Return the layout key of ``entity``: ``schema.table``, or ``table`` without a schema.
|
|
19
|
+
|
|
20
|
+
The key is the table, not the class, so a renamed class keeps its position.
|
|
21
|
+
"""
|
|
22
|
+
if entity.schema:
|
|
23
|
+
return f"{entity.schema}.{entity.table_name}"
|
|
24
|
+
return entity.table_name
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def enum_key(enum: EnumInfo) -> str:
|
|
28
|
+
"""Return the layout key of ``enum``: ``enum:<name>``."""
|
|
29
|
+
return f"enum:{enum.name}"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def entity_keys(entities: Mapping[str, EntityInfo]) -> dict[str, str]:
|
|
33
|
+
"""Map every entity name (erdify's key) to its layout key.
|
|
34
|
+
|
|
35
|
+
The layout key is ``entity_key`` while no other entity has it. Entities that
|
|
36
|
+
share one (same-name classes in different modules, which erdify names
|
|
37
|
+
``module.Class``; or several classes of one table) are keyed by their erdify
|
|
38
|
+
name instead, so only they change key when a namesake appears.
|
|
39
|
+
|
|
40
|
+
Raises:
|
|
41
|
+
DuplicateKeyError: An erdify name used as a key equals another entity's key.
|
|
42
|
+
"""
|
|
43
|
+
base = {name: entity_key(entity) for name, entity in entities.items()}
|
|
44
|
+
shared = Counter(base.values())
|
|
45
|
+
keys = {name: name if shared[key] > 1 else key for name, key in base.items()}
|
|
46
|
+
owners: dict[str, str] = {}
|
|
47
|
+
for name, key in keys.items():
|
|
48
|
+
if key in owners:
|
|
49
|
+
first, second = sorted((owners[key], name))
|
|
50
|
+
raise DuplicateKeyError(
|
|
51
|
+
f"entities {first!r} and {second!r} have the same layout key {key!r}"
|
|
52
|
+
)
|
|
53
|
+
owners[key] = name
|
|
54
|
+
return keys
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def entity_ids(entities: Mapping[str, EntityInfo]) -> dict[str, str]:
|
|
58
|
+
"""Map every entity name (``EntityInfo.name``) to its key in ``entities``.
|
|
59
|
+
|
|
60
|
+
erdify's edges and ``enum_users`` name entities by ``EntityInfo.name``, which
|
|
61
|
+
may differ from the dict key; a key equal to the name wins over another entity
|
|
62
|
+
of that name.
|
|
63
|
+
"""
|
|
64
|
+
ids = {name: name for name, entity in entities.items() if entity.name == name}
|
|
65
|
+
for name, entity in sorted(entities.items()):
|
|
66
|
+
ids.setdefault(entity.name, name)
|
|
67
|
+
return ids
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def entity_groups(entities: Mapping[str, EntityInfo], group_by: GroupBy) -> dict[str, str]:
|
|
71
|
+
"""Map every entity name to the group diagram it belongs to.
|
|
72
|
+
|
|
73
|
+
``auto`` decides per entity: its schema, else its Django app, else its module.
|
|
74
|
+
An entity without a value goes to ``DEFAULT_GROUP``. ``none`` gives no groups
|
|
75
|
+
(an empty mapping): the overview is the only diagram.
|
|
76
|
+
|
|
77
|
+
Raises:
|
|
78
|
+
LayoutError: A group value is a reserved diagram name.
|
|
79
|
+
"""
|
|
80
|
+
if group_by == "none":
|
|
81
|
+
return {}
|
|
82
|
+
groups: dict[str, str] = {}
|
|
83
|
+
for name, entity in entities.items():
|
|
84
|
+
group = _group_value(entity, group_by)
|
|
85
|
+
if group in _RESERVED:
|
|
86
|
+
raise LayoutError(
|
|
87
|
+
f"group {group!r} is a reserved diagram name (entity {name!r}); "
|
|
88
|
+
f"set [tool.erdify-studio] group_by to another value"
|
|
89
|
+
)
|
|
90
|
+
groups[name] = group or DEFAULT_GROUP
|
|
91
|
+
return groups
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _group_value(entity: EntityInfo, group_by: GroupBy) -> str | None:
|
|
95
|
+
if group_by == "schema":
|
|
96
|
+
return entity.schema
|
|
97
|
+
if group_by == "app":
|
|
98
|
+
return entity.app
|
|
99
|
+
if group_by == "module":
|
|
100
|
+
return entity.module
|
|
101
|
+
return entity.schema or entity.app or entity.module
|
erdify_studio/_errors.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Exceptions raised by erdify-studio."""
|
|
2
|
+
|
|
3
|
+
from typing import Literal
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class StudioError(Exception):
|
|
7
|
+
"""Base for all errors raised by erdify-studio."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ConfigError(StudioError):
|
|
11
|
+
"""An invalid ``[tool.erdify-studio]`` table or value."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class LayoutError(StudioError):
|
|
15
|
+
"""A layout file that cannot be read, or entities that cannot be laid out."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class LayoutVersionError(LayoutError):
|
|
19
|
+
"""A layout file of a version this erdify-studio does not support."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class DuplicateKeyError(LayoutError):
|
|
23
|
+
"""An entity keyed by its erdify name (its own key was shared) has another entity's key."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ProjectError(StudioError):
|
|
27
|
+
"""A project studio cannot lay out, e.g. one without entities."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class PositionsError(StudioError):
|
|
31
|
+
"""Positions sent to save that do not match the diagram's boxes."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class LayoutConflictError(LayoutError):
|
|
35
|
+
"""The positions to save no longer fit: the layout file or the models changed.
|
|
36
|
+
|
|
37
|
+
Attributes:
|
|
38
|
+
reason: ``"layout"`` when the layout file changed since the positions were
|
|
39
|
+
read from it, ``"models"`` when the project now has other boxes or diagrams.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def __init__(self, message: str, reason: Literal["layout", "models"] = "layout") -> None:
|
|
43
|
+
super().__init__(message)
|
|
44
|
+
self.reason = reason
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ExportError(StudioError):
|
|
48
|
+
"""SVGs that cannot be exported: no ``export_dir``, or two groups sharing a file name."""
|