erdify 1.5.2__tar.gz → 1.5.4__tar.gz

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.
Files changed (30) hide show
  1. {erdify-1.5.2 → erdify-1.5.4}/PKG-INFO +1 -1
  2. {erdify-1.5.2 → erdify-1.5.4}/pyproject.toml +1 -1
  3. {erdify-1.5.2 → erdify-1.5.4}/pyproject.toml.orig +1 -1
  4. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/parser/annotations.py +30 -1
  5. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/parser/dialects/annotated.py +9 -2
  6. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/parser/dialects/base.py +6 -2
  7. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/parser/dialects/django.py +11 -9
  8. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/parser/dialects/django_apps.py +2 -2
  9. erdify-1.5.4/src/erdify/parser/dialects/keyless.py +310 -0
  10. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/parser/inheritance.py +4 -2
  11. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/sql_parser.py +44 -2
  12. erdify-1.5.2/src/erdify/parser/dialects/keyless.py +0 -201
  13. {erdify-1.5.2 → erdify-1.5.4}/LICENSE +0 -0
  14. {erdify-1.5.2 → erdify-1.5.4}/README.md +0 -0
  15. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/__init__.py +0 -0
  16. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/__main__.py +0 -0
  17. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/cli.py +0 -0
  18. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/config.py +0 -0
  19. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/generator.py +0 -0
  20. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/inject.py +0 -0
  21. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/parser/__init__.py +0 -0
  22. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/parser/aliases.py +0 -0
  23. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/parser/common.py +0 -0
  24. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/parser/core.py +0 -0
  25. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/parser/dialects/__init__.py +0 -0
  26. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/parser/dialects/django_contrib.py +0 -0
  27. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/parser/dialects/sqlalchemy.py +0 -0
  28. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/parser/discovery.py +0 -0
  29. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/py.typed +0 -0
  30. {erdify-1.5.2 → erdify-1.5.4}/src/erdify/pyproject.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: erdify
3
- Version: 1.5.2
3
+ Version: 1.5.4
4
4
  Summary: A zero-dependency ERD generator for your Python models — pure AST, no database required.
5
5
  Keywords: sqlmodel,sqlalchemy,django,pydantic,dataclass,erd,plantuml,diagram,database,erdify,sql,ddl
6
6
  Author: devsuit GmbH, Fabian Clemenz
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "erdify"
3
- version = "1.5.2"
3
+ version = "1.5.4"
4
4
  description = "A zero-dependency ERD generator for your Python models — pure AST, no database required."
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "erdify"
3
- version = "1.5.2"
3
+ version = "1.5.4"
4
4
  description = "A zero-dependency ERD generator for your Python models — pure AST, no database required."
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -30,7 +30,11 @@ MANY_WRAPPERS = frozenset({"WriteOnlyMapped", "DynamicMapped"})
30
30
  MAPPED_WRAPPERS = frozenset({"Mapped"}) | MANY_WRAPPERS
31
31
  #: Type qualifiers: they say how a field is declared, not what it holds, so a
32
32
  #: column's type and nullability are those of the qualified type.
33
- QUALIFIERS = frozenset({"Final", "InitVar", "Required", "NotRequired", "ReadOnly"})
33
+ QUALIFIERS = frozenset({"Final", "Required", "NotRequired", "ReadOnly"})
34
+ #: Annotations that declare no field: a class variable or a dataclass
35
+ #: ``__init__``-only parameter. ``dataclasses.fields()`` leaves both out, and
36
+ #: redeclaring an inherited field as one hides it.
37
+ NON_FIELDS = frozenset({"ClassVar", "InitVar"})
34
38
  #: Single-argument collections of a model: a "many" reference.
35
39
  MANY_CONTAINERS = frozenset(
36
40
  {
@@ -63,6 +67,31 @@ def expr_name(node: ast.expr) -> str | None:
63
67
  return None
64
68
 
65
69
 
70
+ def is_non_field(node: ast.expr) -> bool:
71
+ """``ClassVar`` / ``InitVar``, bare, subscripted, qualified or quoted.
72
+
73
+ Neither makes a field: dataclasses leave them out of ``fields()``,
74
+ Pydantic and SQLModel skip a ``ClassVar`` (and reject an ``InitVar``),
75
+ and SQLAlchemy maps no column for them.
76
+ """
77
+ return _annotation_name(node) in NON_FIELDS
78
+
79
+
80
+ def is_kw_only(node: ast.expr) -> bool:
81
+ """The dataclass ``KW_ONLY`` sentinel: no field, and it hides no inherited one."""
82
+ return _annotation_name(node) == "KW_ONLY"
83
+
84
+
85
+ def _annotation_name(node: ast.expr) -> str | None:
86
+ """The name of an annotation's outermost type, also subscripted, qualified or quoted."""
87
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
88
+ parsed = parse_quoted(node)
89
+ return _annotation_name(parsed) if parsed is not None else None
90
+ if isinstance(node, ast.Subscript):
91
+ node = node.value
92
+ return expr_name(node)
93
+
94
+
66
95
  def is_call_to(value: ast.expr, func_name: str) -> TypeGuard[ast.Call]:
67
96
  """Check whether an expression is a call to ``func_name`` (Name or attribute)."""
68
97
  if not isinstance(value, ast.Call):
@@ -18,6 +18,8 @@ from ..annotations import (
18
18
  expand_aliases,
19
19
  expr_name,
20
20
  is_call_to,
21
+ is_kw_only,
22
+ is_non_field,
21
23
  )
22
24
  from ..common import _Rel, is_enum_class
23
25
  from .base import Dialect
@@ -44,8 +46,13 @@ class AnnotatedDialect(Dialect):
44
46
  if self.reads_annotated_columns:
45
47
  node = self._with_aliases_expanded(node, class_node)
46
48
 
47
- # Skip special attributes
48
- if field_name.startswith("_"):
49
+ # Skip special attributes, class variables and InitVar parameters
50
+ # (the name still shadows an inherited field: declared_names).
51
+ if (
52
+ field_name.startswith("_")
53
+ or is_non_field(node.annotation)
54
+ or is_kw_only(node.annotation)
55
+ ):
49
56
  continue
50
57
 
51
58
  # Check for an explicit relationship call (SQLModel/SQLAlchemy)
@@ -6,7 +6,7 @@ from pathlib import Path
6
6
  from typing import Callable, ClassVar, Dict, Iterable, List, Mapping, Set, Tuple
7
7
 
8
8
  from ...config import EntityInfo, FieldInfo
9
- from ..annotations import is_call_to
9
+ from ..annotations import is_call_to, is_kw_only
10
10
  from ..common import _ClassMembers, _Rel, to_snake_case
11
11
  from ..inheritance import ClassIndex, merge_members, reorder
12
12
 
@@ -167,7 +167,11 @@ class Dialect:
167
167
  return [
168
168
  node.target.id
169
169
  for node in self.member_nodes(class_node)
170
- if isinstance(node.target, ast.Name) and not node.target.id.startswith("_")
170
+ if isinstance(node.target, ast.Name)
171
+ and not node.target.id.startswith("_")
172
+ # The dataclass KW_ONLY sentinel declares nothing (not even in
173
+ # __dataclass_fields__), so it hides no inherited field.
174
+ and not is_kw_only(node.annotation)
171
175
  ]
172
176
 
173
177
  def member_nodes(self, class_node: ast.ClassDef) -> List[ast.AnnAssign]:
@@ -616,9 +616,10 @@ class DjangoDialect(Dialect):
616
616
  """The model a Django ``"self"`` relation declared in class ``name`` points at.
617
617
 
618
618
  A concrete model's own fields point at that model (a multi-table child
619
- does not copy them, #233). An abstract base's or a plain
620
- mixin's fields are copied into the first concrete model that inherits
621
- it, so ``"self"`` points there (#226).
619
+ does not copy them, #233). An abstract base's fields (or those of a
620
+ base not known to be plain, see :meth:`_own_declarations`) are copied
621
+ into the first concrete model that inherits it, so ``"self"`` points
622
+ there (#226).
622
623
  """
623
624
  if self._is_concrete_django_model(name):
624
625
  return name
@@ -634,8 +635,8 @@ class DjangoDialect(Dialect):
634
635
  def _is_concrete_django_model(self, name: str) -> bool:
635
636
  """A Django model with its own table: a ``models.Model`` subclass, not abstract.
636
637
 
637
- A plain mixin or an abstract base has no table, so a ``"self"``
638
- relation declared there belongs to the concrete model that copies it.
638
+ An abstract base has no table, so a ``"self"`` relation declared there
639
+ belongs to the concrete model that copies it.
639
640
  """
640
641
  node = self.classes.all[name]
641
642
  return self._inherits_django_model(node) and not self._meta_flag(node, "abstract")
@@ -792,10 +793,11 @@ class DjangoDialect(Dialect):
792
793
 
793
794
  Django's ``ModelBase`` (#272, #280): the class body's fields, then,
794
795
  along the MRO, each *direct* base that is an abstract model adds the
795
- fields it has itself (its own and those it copied) unless the name is
796
- already taken. Every other class in the MRO only takes names: a
797
- concrete parent its fields (they stay in its table, #233), a plain
798
- mixin or an indirect ancestor every name its body binds. So a field on
796
+ fields it has itself (its own and those it copied) unless the body or
797
+ a class earlier in the MRO already took the name. Every other class in
798
+ the MRO only takes names: a concrete parent its fields (they stay in
799
+ its table, #233), a plain mixin or an indirect ancestor every name its
800
+ body binds. So a field on
799
801
  a plain mixin is no column, and a diamond keeps the first copy. A base
800
802
  that is not known to be plain (it extends a class outside the scanned
801
803
  files) is read like an abstract model.
@@ -19,8 +19,8 @@ with an ``__init__.py``) from the model file: the nearest directory with an
19
19
  file. The walk never leaves the package chain, so an unrelated ``models``
20
20
  directory above the project can't be picked up.
21
21
 
22
- ``Meta.app_label`` inherited from an abstract base's ``Meta`` is not read yet
23
- (the same gap as an inherited ``db_table``, #279).
22
+ A ``Meta.app_label``, also one inherited from an abstract base's ``Meta``
23
+ (#279), takes precedence; the dialect reads it before asking this module.
24
24
 
25
25
  An ``AppConfig`` chosen explicitly in ``INSTALLED_APPS`` (``"shop.apps.Custom"``)
26
26
  is not known to erdify; the app's default config is used instead.
@@ -0,0 +1,310 @@
1
+ """Keyless sources: Pydantic models and dataclasses.
2
+
3
+ They describe objects, not tables: no keys unless ``--infer-keys``, and a
4
+ field typed as another model is a relationship.
5
+ """
6
+
7
+ import ast
8
+ from dataclasses import replace
9
+ from typing import Dict, FrozenSet, List, Set, Tuple
10
+
11
+ from ...config import FieldInfo
12
+ from ..annotations import is_non_field
13
+ from ..common import _ClassMembers, _Rel
14
+ from ..inheritance import merge_members
15
+ from .annotated import AnnotatedDialect
16
+ from .base import ParseContext
17
+
18
+ #: A class's fields, relationships, and names bound to a ClassVar / InitVar.
19
+ _Effective = Tuple[Dict[str, FieldInfo], Dict[str, _Rel], Set[str]]
20
+
21
+
22
+ class _FieldMergeDialect(AnnotatedDialect):
23
+ """A keyless dialect whose classes merge inherited fields like ``dataclasses.fields()``.
24
+
25
+ A model class (:meth:`owns_fields`) merges each base's fields in reversed
26
+ MRO, then its own annotations. So in ``Child(Left, Middle)`` an attribute
27
+ ``Left`` merely inherits still overrides one ``Middle`` redeclares, unlike
28
+ Python's attribute lookup. A plain class has no fields of its own: it
29
+ exposes those of the first model class in its MRO. ``mixin_fields``: the
30
+ annotations of plain classes in the hierarchy also become fields, where no
31
+ model class declares the attribute (the first such class in the MRO wins),
32
+ and the first annotation in the MRO where a plain class gives the name a
33
+ default (:meth:`_with_mixin_fields`).
34
+
35
+ A ``ClassVar`` / ``InitVar`` redeclaring a field hides it: in a dataclass
36
+ in every subclass (a pseudo-field passed down), with ``mixin_fields``
37
+ (Pydantic) only where it is the first annotation of the name in the MRO.
38
+ """
39
+
40
+ #: Whether a plain (non-model) base's annotations become fields.
41
+ mixin_fields: bool = False
42
+
43
+ def __init__(self, ctx: ParseContext):
44
+ super().__init__(ctx)
45
+ self._fields_cache: Dict[str, _Effective] = {}
46
+ self._owns_cache: Dict[str, bool] = {}
47
+ self._body_cache: Dict[str, Tuple[Set[str], Set[str], Set[str]]] = {}
48
+
49
+ def owns_fields(self, class_node: ast.ClassDef) -> bool:
50
+ """Whether the class is a model class with fields of its own.
51
+
52
+ A class named in ``--base-classes`` is one too, also when its own base
53
+ is not recognised (it is a model base by declaration).
54
+ """
55
+ name = class_node.name
56
+ if name not in self._owns_cache: # detect() walks the ancestors: memoize
57
+ self._owns_cache[name] = self.detect(class_node) or name in self.ctx.base_classes
58
+ return self._owns_cache[name]
59
+
60
+ def _body(self, name: str) -> Tuple[Set[str], Set[str], Set[str]]:
61
+ """A class body's declared names, ``ClassVar`` / ``InitVar`` names and
62
+ names bound to a value; memoized (the MRO scans repeat them)."""
63
+ if name not in self._body_cache:
64
+ node = self.classes.all[name]
65
+ non_fields = {
66
+ member.target.id
67
+ for member in self.member_nodes(node)
68
+ if isinstance(member.target, ast.Name) and is_non_field(member.annotation)
69
+ }
70
+ self._body_cache[name] = (
71
+ set(self.declared_names(node)),
72
+ non_fields,
73
+ _value_bindings(node),
74
+ )
75
+ return self._body_cache[name]
76
+
77
+ def merge(
78
+ self,
79
+ class_node: ast.ClassDef,
80
+ merge_order: List[str],
81
+ members: Dict[str, _ClassMembers],
82
+ ) -> Tuple[Dict[str, FieldInfo], Dict[str, _Rel]]:
83
+ if self.classes.mro(class_node.name) is None:
84
+ return super().merge(class_node, merge_order, members)
85
+ fields, rels, _ = self._effective_fields(class_node.name, members)
86
+ # The cache is shared across entities, and building an entity mutates
87
+ # fields (e.g. is_unique), so each entity gets its own copies.
88
+ return {attr: replace(f) for attr, f in fields.items()}, dict(rels)
89
+
90
+ def _non_fields(self, name: str) -> FrozenSet[str]:
91
+ """Names a class body binds to a ``ClassVar`` / ``InitVar``."""
92
+ return frozenset(self._body(name)[1])
93
+
94
+ def _effective_fields(self, name: str, members: Dict[str, _ClassMembers]) -> _Effective:
95
+ """A class's fields as the framework computes them; cached per parse.
96
+
97
+ Also the names its merged view binds to a ``ClassVar`` / ``InitVar``
98
+ pseudo-field: like ``__dataclass_fields__``, they hide a field of an
99
+ earlier base in a subclass too. A class's own members do not depend
100
+ on the entity being built.
101
+ """
102
+ memo = self._fields_cache
103
+ if name in memo:
104
+ return memo[name]
105
+ mro = self.classes.mro(name) or [name]
106
+ if not self.owns_fields(self.classes.all[name]):
107
+ owner = next((c for c in mro if self.owns_fields(self.classes.all[c])), None)
108
+ result = (
109
+ self._effective_fields(owner, members) if owner is not None else ({}, {}, set())
110
+ )
111
+ memo[name] = result
112
+ return result
113
+ synthetic: Dict[str, _ClassMembers] = {}
114
+ hidden = set(self._non_fields(name)) # a copy: the body cache is shared
115
+ for base in mro[:0:-1]:
116
+ base_fields, base_rels, base_hidden = self._effective_fields(base, members)
117
+ # Dataclasses carry ClassVar / InitVar pseudo-fields down to every
118
+ # subclass; Pydantic has none (its first annotation decides, below).
119
+ passed_down = [] if self.mixin_fields else [*base_hidden]
120
+ synthetic[base] = (base_fields, base_rels, [*base_fields, *base_rels, *passed_down])
121
+ hidden |= base_hidden
122
+ synthetic[name] = members[name]
123
+ fields, rels = merge_members([*mro[:0:-1], name], synthetic, self)
124
+ if self.mixin_fields:
125
+ fields, rels = self._with_mixin_fields(mro, members, fields, rels)
126
+ hidden |= {n for base in mro for n in self._non_fields(base)}
127
+ hidden -= {*fields, *rels}
128
+ memo[name] = (fields, rels, hidden)
129
+ return memo[name]
130
+
131
+ def _with_mixin_fields(
132
+ self,
133
+ mro: List[str],
134
+ members: Dict[str, _ClassMembers],
135
+ fields: Dict[str, FieldInfo],
136
+ rels: Dict[str, _Rel],
137
+ ) -> Tuple[Dict[str, FieldInfo], Dict[str, _Rel]]:
138
+ """Add plain bases' annotations, then apply the first annotation where Pydantic does.
139
+
140
+ As in Pydantic: the annotation found first along the MRO decides
141
+ whether a name is a class variable, whichever class declares the field.
142
+ It is also the field when a plain base binds the name to a value (a
143
+ default Pydantic finds on the class); otherwise an inherited field
144
+ comes from the model bases, as merged.
145
+ """
146
+ fields, rels = dict(fields), dict(rels)
147
+ for base in mro:
148
+ if self.owns_fields(self.classes.all[base]):
149
+ continue
150
+ base_fields, base_rels, _ = members[base]
151
+ for attr, field in base_fields.items():
152
+ if attr not in fields and attr not in rels:
153
+ fields[attr] = field
154
+ for attr, rel in base_rels.items():
155
+ if attr not in fields and attr not in rels:
156
+ rels[attr] = rel
157
+ for attr in [*fields, *rels]:
158
+ first = next((b for b in mro if attr in self._body(b)[0]), None)
159
+ if first is None:
160
+ continue
161
+ if attr in self._non_fields(first):
162
+ fields.pop(attr, None)
163
+ rels.pop(attr, None)
164
+ elif any(
165
+ attr in self._body(b)[2] and not self.owns_fields(self.classes.all[b]) for b in mro
166
+ ):
167
+ first_fields, first_rels, _ = members[first]
168
+ fields.pop(attr, None)
169
+ rels.pop(attr, None)
170
+ if attr in first_fields:
171
+ fields[attr] = first_fields[attr]
172
+ elif attr in first_rels:
173
+ rels[attr] = first_rels[attr]
174
+ return fields, rels
175
+
176
+
177
+ def _value_bindings(class_node: ast.ClassDef) -> Set[str]:
178
+ """Names a class body assigns a value to (``x: T = v`` or ``x = v``)."""
179
+ names: Set[str] = set()
180
+ for node in class_node.body:
181
+ if isinstance(node, ast.AnnAssign) and node.value is not None:
182
+ targets: List[ast.expr] = [node.target]
183
+ elif isinstance(node, ast.Assign):
184
+ targets = list(node.targets)
185
+ else:
186
+ continue
187
+ names.update(t.id for t in targets if isinstance(t, ast.Name))
188
+ return names
189
+
190
+
191
+ class DataclassDialect(_FieldMergeDialect):
192
+ """A class decorated with ``@dataclass`` (bare or called).
193
+
194
+ Its members merge like ``dataclasses.fields()``: an undecorated base adds
195
+ no fields, not even annotations of its own.
196
+ """
197
+
198
+ kind = "dataclass"
199
+ keyless = True
200
+
201
+ def detect(self, class_node: ast.ClassDef) -> bool:
202
+ return self._is_dataclass(class_node)
203
+
204
+ @staticmethod
205
+ def _is_dataclass(class_node: ast.ClassDef) -> bool:
206
+ """Check if a class is decorated with @dataclass (bare or called)."""
207
+ for dec in class_node.decorator_list:
208
+ if isinstance(dec, ast.Name) and dec.id == "dataclass":
209
+ return True
210
+ if isinstance(dec, ast.Attribute) and dec.attr == "dataclass":
211
+ return True
212
+ if isinstance(dec, ast.Call):
213
+ func = dec.func
214
+ if isinstance(func, ast.Name) and func.id == "dataclass":
215
+ return True
216
+ if isinstance(func, ast.Attribute) and func.attr == "dataclass":
217
+ return True
218
+ return False
219
+
220
+
221
+ class PydanticDialect(_FieldMergeDialect):
222
+ """A ``BaseModel`` subclass (directly or transitively), or of ``ctx.base_classes``.
223
+
224
+ Pydantic copies inherited fields from the bases' ``model_fields`` (the
225
+ first base wins), which matches the ``dataclasses.fields()`` merge; a plain
226
+ mixin's annotations become fields too, and the first annotation of a name
227
+ in the MRO decides whether it is a class variable.
228
+ """
229
+
230
+ kind = "pydantic"
231
+ keyless = True
232
+ mixin_fields = True
233
+
234
+ def detect(self, class_node: ast.ClassDef) -> bool:
235
+ return self._inherits_basemodel(class_node)
236
+
237
+ def skip_reason(self, class_node: ast.ClassDef) -> str | None:
238
+ """Skip a ninja-style ``ModelSchema``, whose fields come from a Django model."""
239
+ derived = model_derived_schema(class_node)
240
+ if derived is None:
241
+ return None
242
+ holder, target = derived
243
+ return (
244
+ f"Warning: skipped {class_node.name} - its fields come from "
245
+ f"{holder}.model ({target}), which erdify does not resolve. "
246
+ "Drawing it would add an entity with no fields. "
247
+ "See https://github.com/devsuit-berlin/erdify/issues/171"
248
+ )
249
+
250
+ def _inherits_basemodel(
251
+ self, class_node: ast.ClassDef, visited: set[str] | None = None
252
+ ) -> bool:
253
+ """Check if a class inherits from Pydantic's BaseModel, directly or via ancestors.
254
+
255
+ Any name in ``ctx.base_classes`` counts as well, which is how a base
256
+ defined outside the scanned files (``ninja.Schema``, a shared internal
257
+ ``BaseSchema``) can be recognised at all.
258
+ """
259
+ visited = visited if visited is not None else set()
260
+ if class_node.name in visited:
261
+ return False
262
+ visited.add(class_node.name)
263
+
264
+ for base in class_node.bases:
265
+ if isinstance(base, ast.Name):
266
+ if base.id == "BaseModel" or base.id in self.ctx.base_classes:
267
+ return True
268
+ ancestor = self.classes.all.get(base.id)
269
+ if ancestor is not None and self._inherits_basemodel(ancestor, visited):
270
+ return True
271
+ elif isinstance(base, ast.Attribute):
272
+ if base.attr == "BaseModel" or base.attr in self.ctx.base_classes:
273
+ return True
274
+ return False
275
+
276
+
277
+ def model_derived_schema(class_node: ast.ClassDef) -> Tuple[str, str] | None:
278
+ """Detect a ninja-style ``ModelSchema`` and report where its fields come from.
279
+
280
+ django-ninja's ``ModelSchema`` (inner ``Meta``) and ninja-schema's
281
+ (inner ``Config``) take their fields from a Django model named in that
282
+ inner class rather than from the class body. erdify cannot resolve the
283
+ reference, so the entity would be drawn with no fields at all — worse
284
+ than not drawing it. Detection is deliberately narrow: only an inner
285
+ ``Meta``/``Config`` that assigns ``model`` counts, so an ordinary
286
+ Pydantic model with a nested config class is untouched.
287
+
288
+ Returns:
289
+ ``(holder, target)`` where *holder* is ``"Meta"`` or ``"Config"``
290
+ and *target* is the referenced model's name, or ``None`` when the
291
+ class is not a model-derived schema.
292
+ """
293
+ for node in class_node.body:
294
+ if not isinstance(node, ast.ClassDef) or node.name not in ("Meta", "Config"):
295
+ continue
296
+ for inner in node.body:
297
+ if not isinstance(inner, ast.Assign):
298
+ continue
299
+ for target in inner.targets:
300
+ if not (isinstance(target, ast.Name) and target.id == "model"):
301
+ continue
302
+ value = inner.value
303
+ if isinstance(value, ast.Name):
304
+ return node.name, value.id
305
+ if isinstance(value, ast.Attribute):
306
+ return node.name, value.attr
307
+ if isinstance(value, ast.Call):
308
+ return node.name, "unresolved"
309
+ return node.name, "unresolved"
310
+ return None
@@ -1,8 +1,10 @@
1
1
  """Class hierarchy of the parsed files: MRO, merge order and member merging.
2
2
 
3
3
  Shared by every dialect. A model's fields come from its own body and its
4
- bases; which declaration wins follows Python's MRO (#228), and the order they
5
- are listed in follows the pre-MRO recursive merge.
4
+ bases; which declaration wins follows Python's MRO (#228) unless a dialect
5
+ resolves it its own way (Django follows ``ModelBase``, #272; Pydantic and
6
+ dataclasses merge the bases' fields like ``dataclasses.fields()``, #267), and the order
7
+ they are listed in follows the pre-MRO recursive merge.
6
8
  """
7
9
 
8
10
  import ast
@@ -157,6 +157,11 @@ class SqlSchemaParser:
157
157
  #: for tables and, per table, for columns.
158
158
  self._table_keys: dict[str, str] = {}
159
159
  self._column_keys: dict[str, dict[str, str]] = {}
160
+ #: Enum type name keys -> declared names.
161
+ self._enum_keys: dict[str, str] = {}
162
+ #: Columns of a user-defined type: (field, schema prefix, type name key),
163
+ #: matched to the enums in _finalize().
164
+ self._typed_fields: list[tuple[FieldInfo, str, str]] = []
160
165
  self._dialect: Any = None
161
166
 
162
167
  def parse(self) -> tuple[dict[str, EntityInfo], dict[str, EnumInfo]]:
@@ -335,6 +340,7 @@ class SqlSchemaParser:
335
340
  values.append(lit.this)
336
341
  if name and values:
337
342
  self._enums[name] = EnumInfo(name=name, values=values)
343
+ self._enum_keys[self._key(name_node)] = name
338
344
 
339
345
  def _column(
340
346
  self,
@@ -348,6 +354,11 @@ class SqlSchemaParser:
348
354
  name = coldef.name # type: ignore[attr-defined]
349
355
  kind = coldef.args.get("kind") # type: ignore[attr-defined]
350
356
  type_str = kind.sql().lower() if kind is not None else ""
357
+ type_ref = self._user_defined_type(kind, exp)
358
+ if type_ref is not None:
359
+ prefix, ident = type_ref
360
+ # Unquoted like the CREATE TYPE name: a quoted name keeps its case (#328).
361
+ type_str = prefix + (ident.name if ident.quoted else ident.name.lower())
351
362
  constraints = coldef.constraints # type: ignore[attr-defined] # list[exp.ColumnConstraint]
352
363
  is_pk = name in pk_cols or self._has_constraint(
353
364
  constraints,
@@ -366,7 +377,7 @@ class SqlSchemaParser:
366
377
  constraints,
367
378
  exp.UniqueColumnConstraint, # type: ignore[attr-defined]
368
379
  )
369
- return FieldInfo(
380
+ field = FieldInfo(
370
381
  name=name,
371
382
  type_str=type_str,
372
383
  is_primary_key=is_pk,
@@ -375,6 +386,31 @@ class SqlSchemaParser:
375
386
  default_value=default,
376
387
  is_unique=is_unique,
377
388
  )
389
+ if type_ref is not None:
390
+ self._typed_fields.append((field, type_ref[0], self._key(type_ref[1])))
391
+ return field
392
+
393
+ @staticmethod
394
+ def _user_defined_type(kind: Any, exp: Any) -> tuple[str, Any] | None:
395
+ """A user-defined column type (e.g. an enum) as (schema prefix, name
396
+ identifier), or ``None`` for a built-in type.
397
+
398
+ Only a dialect that reads quoted type names (PostgreSQL) has the
399
+ identifier; the generic dialect keeps the name as plain text.
400
+ """
401
+ if not isinstance(kind, exp.DataType) or kind.this != exp.DataType.Type.USERDEFINED:
402
+ return None
403
+ ref = kind.args.get("kind")
404
+ if isinstance(ref, exp.Identifier):
405
+ return "", ref
406
+ if isinstance(ref, exp.Dot) and isinstance(ref.expression, exp.Identifier):
407
+ # Each schema part follows the type name's rule: quoted keeps its case.
408
+ schema = ".".join(
409
+ part.name if part.quoted else part.name.lower()
410
+ for part in ref.this.find_all(exp.Identifier, bfs=False)
411
+ )
412
+ return schema + ".", ref.expression
413
+ return None
378
414
 
379
415
  @staticmethod
380
416
  def _has_constraint(constraints: list[object], kind: "type") -> bool:
@@ -559,7 +595,13 @@ class SqlSchemaParser:
559
595
  return part
560
596
 
561
597
  def _finalize(self) -> None:
562
- """Detect link tables, then apply ``exclude_patterns``."""
598
+ """Name enum-typed columns' types as their enum, detect link tables,
599
+ then apply ``exclude_patterns``."""
600
+ # Type names fold like table names: `mood` is the enum `Mood` (#328).
601
+ for field, prefix, key in self._typed_fields:
602
+ enum_name = self._enum_keys.get(key)
603
+ if enum_name is not None:
604
+ field.type_str = prefix + enum_name
563
605
  for entity in self._entities.values():
564
606
  normalize_key_uniqueness(entity.fields)
565
607
  entity.is_link_table = is_structural_link_table(entity.fields)
@@ -1,201 +0,0 @@
1
- """Keyless sources: Pydantic models and dataclasses.
2
-
3
- They describe objects, not tables: no keys unless ``--infer-keys``, and a
4
- field typed as another model is a relationship.
5
- """
6
-
7
- import ast
8
- from dataclasses import replace
9
- from typing import Dict, List, Tuple
10
-
11
- from ...config import FieldInfo
12
- from ..common import _ClassMembers, _Rel
13
- from ..inheritance import merge_members
14
- from .annotated import AnnotatedDialect
15
- from .base import ParseContext
16
-
17
-
18
- class DataclassDialect(AnnotatedDialect):
19
- """A class decorated with ``@dataclass`` (bare or called).
20
-
21
- Its members merge like ``dataclasses.fields()`` (:meth:`_dataclass_fields`).
22
- """
23
-
24
- kind = "dataclass"
25
- keyless = True
26
-
27
- def __init__(self, ctx: ParseContext):
28
- super().__init__(ctx)
29
- self._dataclass_cache: Dict[str, Tuple[Dict[str, FieldInfo], Dict[str, _Rel]]] = {}
30
-
31
- def detect(self, class_node: ast.ClassDef) -> bool:
32
- return self._is_dataclass(class_node)
33
-
34
- def merge(
35
- self,
36
- class_node: ast.ClassDef,
37
- merge_order: List[str],
38
- members: Dict[str, _ClassMembers],
39
- ) -> Tuple[Dict[str, FieldInfo], Dict[str, _Rel]]:
40
- if self.classes.mro(class_node.name) is not None:
41
- return self._dataclass_fields(class_node.name, members)
42
- return super().merge(class_node, merge_order, members)
43
-
44
- @staticmethod
45
- def _is_dataclass(class_node: ast.ClassDef) -> bool:
46
- """Check if a class is decorated with @dataclass (bare or called)."""
47
- for dec in class_node.decorator_list:
48
- if isinstance(dec, ast.Name) and dec.id == "dataclass":
49
- return True
50
- if isinstance(dec, ast.Attribute) and dec.attr == "dataclass":
51
- return True
52
- if isinstance(dec, ast.Call):
53
- func = dec.func
54
- if isinstance(func, ast.Name) and func.id == "dataclass":
55
- return True
56
- if isinstance(func, ast.Attribute) and func.attr == "dataclass":
57
- return True
58
- return False
59
-
60
- def _dataclass_fields(
61
- self, name: str, members: Dict[str, _ClassMembers]
62
- ) -> Tuple[Dict[str, FieldInfo], Dict[str, _Rel]]:
63
- """The members of a dataclass entity: ``dataclasses.fields()`` plus mixins.
64
-
65
- First the stdlib result (:meth:`_effective_dataclass_fields`). Then
66
- annotations of undecorated mixins in the hierarchy, which the stdlib
67
- ignores but erdify has always shown, fill in only attributes no
68
- dataclass declares (the first such mixin in the MRO wins).
69
- """
70
- fields, rels = self._effective_dataclass_fields(name, members)
71
- # The cache is shared across entities, and building an entity mutates
72
- # fields (e.g. is_unique), so each entity gets its own copies.
73
- fields, rels = {attr: replace(f) for attr, f in fields.items()}, dict(rels)
74
- for base in self.classes.mro(name) or [name]:
75
- if self._is_dataclass(self.classes.all[base]):
76
- continue
77
- base_fields, base_rels, _ = members[base]
78
- for attr, field in base_fields.items():
79
- if attr not in fields and attr not in rels:
80
- fields[attr] = replace(field)
81
- for attr, rel in base_rels.items():
82
- if attr not in fields and attr not in rels:
83
- rels[attr] = rel
84
- return fields, rels
85
-
86
- def _effective_dataclass_fields(
87
- self, name: str, members: Dict[str, _ClassMembers]
88
- ) -> Tuple[Dict[str, FieldInfo], Dict[str, _Rel]]:
89
- """A class's ``__dataclass_fields__``, as the stdlib computes it.
90
-
91
- A decorated class merges each base's ``__dataclass_fields__`` in
92
- reversed MRO, then its own annotations. So in ``Child(Left, Middle)``
93
- an attribute ``Left`` merely inherits still overrides one ``Middle``
94
- redeclares. An undecorated class has no fields of its own: it exposes
95
- those of the first decorated class in its MRO. Cached per parse; a
96
- class's own members do not depend on the entity being built.
97
- """
98
- memo = self._dataclass_cache
99
- if name in memo:
100
- return memo[name]
101
- mro = self.classes.mro(name) or [name]
102
- if not self._is_dataclass(self.classes.all[name]):
103
- owner = next((c for c in mro if self._is_dataclass(self.classes.all[c])), None)
104
- result = (
105
- self._effective_dataclass_fields(owner, members) if owner is not None else ({}, {})
106
- )
107
- memo[name] = result
108
- return result
109
- synthetic: Dict[str, _ClassMembers] = {}
110
- for base in mro[:0:-1]:
111
- base_fields, base_rels = self._effective_dataclass_fields(base, members)
112
- synthetic[base] = (base_fields, base_rels, [*base_fields, *base_rels])
113
- synthetic[name] = members[name]
114
- result = merge_members([*mro[:0:-1], name], synthetic, self)
115
- memo[name] = result
116
- return result
117
-
118
-
119
- class PydanticDialect(AnnotatedDialect):
120
- """A ``BaseModel`` subclass (directly or transitively), or of ``ctx.base_classes``."""
121
-
122
- kind = "pydantic"
123
- keyless = True
124
-
125
- def detect(self, class_node: ast.ClassDef) -> bool:
126
- return self._inherits_basemodel(class_node)
127
-
128
- def skip_reason(self, class_node: ast.ClassDef) -> str | None:
129
- """Skip a ninja-style ``ModelSchema``, whose fields come from a Django model."""
130
- derived = model_derived_schema(class_node)
131
- if derived is None:
132
- return None
133
- holder, target = derived
134
- return (
135
- f"Warning: skipped {class_node.name} - its fields come from "
136
- f"{holder}.model ({target}), which erdify does not resolve. "
137
- "Drawing it would add an entity with no fields. "
138
- "See https://github.com/devsuit-berlin/erdify/issues/171"
139
- )
140
-
141
- def _inherits_basemodel(
142
- self, class_node: ast.ClassDef, visited: set[str] | None = None
143
- ) -> bool:
144
- """Check if a class inherits from Pydantic's BaseModel, directly or via ancestors.
145
-
146
- Any name in ``ctx.base_classes`` counts as well, which is how a base
147
- defined outside the scanned files (``ninja.Schema``, a shared internal
148
- ``BaseSchema``) can be recognised at all.
149
- """
150
- visited = visited if visited is not None else set()
151
- if class_node.name in visited:
152
- return False
153
- visited.add(class_node.name)
154
-
155
- for base in class_node.bases:
156
- if isinstance(base, ast.Name):
157
- if base.id == "BaseModel" or base.id in self.ctx.base_classes:
158
- return True
159
- ancestor = self.classes.all.get(base.id)
160
- if ancestor is not None and self._inherits_basemodel(ancestor, visited):
161
- return True
162
- elif isinstance(base, ast.Attribute):
163
- if base.attr == "BaseModel" or base.attr in self.ctx.base_classes:
164
- return True
165
- return False
166
-
167
-
168
- def model_derived_schema(class_node: ast.ClassDef) -> Tuple[str, str] | None:
169
- """Detect a ninja-style ``ModelSchema`` and report where its fields come from.
170
-
171
- django-ninja's ``ModelSchema`` (inner ``Meta``) and ninja-schema's
172
- (inner ``Config``) take their fields from a Django model named in that
173
- inner class rather than from the class body. erdify cannot resolve the
174
- reference, so the entity would be drawn with no fields at all — worse
175
- than not drawing it. Detection is deliberately narrow: only an inner
176
- ``Meta``/``Config`` that assigns ``model`` counts, so an ordinary
177
- Pydantic model with a nested config class is untouched.
178
-
179
- Returns:
180
- ``(holder, target)`` where *holder* is ``"Meta"`` or ``"Config"``
181
- and *target* is the referenced model's name, or ``None`` when the
182
- class is not a model-derived schema.
183
- """
184
- for node in class_node.body:
185
- if not isinstance(node, ast.ClassDef) or node.name not in ("Meta", "Config"):
186
- continue
187
- for inner in node.body:
188
- if not isinstance(inner, ast.Assign):
189
- continue
190
- for target in inner.targets:
191
- if not (isinstance(target, ast.Name) and target.id == "model"):
192
- continue
193
- value = inner.value
194
- if isinstance(value, ast.Name):
195
- return node.name, value.id
196
- if isinstance(value, ast.Attribute):
197
- return node.name, value.attr
198
- if isinstance(value, ast.Call):
199
- return node.name, "unresolved"
200
- return node.name, "unresolved"
201
- return None
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes