erdify 1.4.4__tar.gz → 1.5.0__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.4.4 → erdify-1.5.0}/PKG-INFO +2 -2
  2. {erdify-1.4.4 → erdify-1.5.0}/pyproject.toml +2 -2
  3. {erdify-1.4.4 → erdify-1.5.0}/pyproject.toml.orig +2 -2
  4. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/parser/core.py +171 -14
  5. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/parser/dialects/annotated.py +4 -3
  6. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/parser/dialects/base.py +17 -6
  7. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/parser/dialects/sqlalchemy.py +474 -8
  8. erdify-1.5.0/src/erdify/sql_parser.py +580 -0
  9. erdify-1.4.4/src/erdify/sql_parser.py +0 -384
  10. {erdify-1.4.4 → erdify-1.5.0}/LICENSE +0 -0
  11. {erdify-1.4.4 → erdify-1.5.0}/README.md +0 -0
  12. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/__init__.py +0 -0
  13. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/__main__.py +0 -0
  14. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/cli.py +0 -0
  15. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/config.py +0 -0
  16. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/generator.py +0 -0
  17. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/inject.py +0 -0
  18. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/parser/__init__.py +0 -0
  19. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/parser/aliases.py +0 -0
  20. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/parser/annotations.py +0 -0
  21. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/parser/common.py +0 -0
  22. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/parser/dialects/__init__.py +0 -0
  23. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/parser/dialects/django.py +0 -0
  24. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/parser/dialects/django_apps.py +0 -0
  25. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/parser/dialects/django_contrib.py +0 -0
  26. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/parser/dialects/keyless.py +0 -0
  27. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/parser/discovery.py +0 -0
  28. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/parser/inheritance.py +0 -0
  29. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/py.typed +0 -0
  30. {erdify-1.4.4 → erdify-1.5.0}/src/erdify/pyproject.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: erdify
3
- Version: 1.4.4
3
+ Version: 1.5.0
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
@@ -17,7 +17,7 @@ Classifier: Programming Language :: Python :: 3.14
17
17
  Classifier: Programming Language :: Python :: 3.15
18
18
  Classifier: Topic :: Database
19
19
  Classifier: Topic :: Software Development :: Code Generators
20
- Requires-Dist: sqlglot>=25 ; extra == 'sql'
20
+ Requires-Dist: sqlglot>=30.8 ; extra == 'sql'
21
21
  Requires-Python: >=3.11
22
22
  Project-URL: Homepage, https://github.com/devsuit-berlin/erdify
23
23
  Project-URL: Repository, https://github.com/devsuit-berlin/erdify
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "erdify"
3
- version = "1.4.4"
3
+ version = "1.5.0"
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"
@@ -43,7 +43,7 @@ name = "Fabian Clemenz"
43
43
  email = "fabian.clemenz@devsuit.de"
44
44
 
45
45
  [project.optional-dependencies]
46
- sql = ["sqlglot>=25"]
46
+ sql = ["sqlglot>=30.8"]
47
47
 
48
48
  [project.scripts]
49
49
  erdify = "erdify.cli:main"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "erdify"
3
- version = "1.4.4"
3
+ version = "1.5.0"
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"
@@ -39,7 +39,7 @@ classifiers = [
39
39
  dependencies = [] # No runtime dependencies - uses stdlib ast module
40
40
 
41
41
  [project.optional-dependencies]
42
- sql = ["sqlglot>=25"]
42
+ sql = ["sqlglot>=30.8"]
43
43
 
44
44
  [dependency-groups]
45
45
  dev = [
@@ -1,6 +1,7 @@
1
1
  """The parser entry points: :class:`ASTDatabaseParser` and :func:`parse_models_directory`."""
2
2
 
3
3
  import ast
4
+ import copy
4
5
  import sys
5
6
  from dataclasses import dataclass
6
7
  from fnmatch import fnmatchcase
@@ -19,13 +20,16 @@ class ModelParseError(Exception):
19
20
  """Raised in strict mode when one or more input files could not be parsed.
20
21
 
21
22
  Attributes:
22
- errors: ``(file, message)`` for every file that failed, in scan order.
23
+ errors: ``(file, message)`` for every failure, in scan order: one per
24
+ file, or one per statement of a ``.sql`` file.
23
25
  """
24
26
 
25
27
  def __init__(self, errors: List[Tuple[Path, str]]):
26
28
  self.errors = errors
27
- files = ", ".join(str(path) for path, _ in errors)
28
- super().__init__(f"{len(errors)} file(s) could not be parsed (strict mode): {files}")
29
+ paths = list(dict.fromkeys(str(path) for path, _ in errors))
30
+ super().__init__(
31
+ f"{len(paths)} file(s) could not be parsed (strict mode): {', '.join(paths)}"
32
+ )
29
33
 
30
34
 
31
35
  class ASTDatabaseParser:
@@ -113,6 +117,10 @@ class ASTDatabaseParser:
113
117
  self._file_trees: Dict[Path, ast.Module] = {}
114
118
  #: The file each class definition (by ``id`` of its node) was read from.
115
119
  self._class_files: Dict[int, Path] = {}
120
+ #: Names given to the definitions a namesake extends -> their own name (#300).
121
+ self._shadowed: Dict[str, str] = {}
122
+ #: id() of such a definition -> the name it is kept under.
123
+ self._renamed: Dict[int, str] = {}
116
124
  #: Classes and dialects (with their caches); renewed for each parse run.
117
125
  self._ctx = self._new_context()
118
126
 
@@ -130,6 +138,7 @@ class ASTDatabaseParser:
130
138
  self._parse_errors = []
131
139
 
132
140
  # First pass: parse all files and collect class definitions
141
+ definitions: List[Tuple[ast.ClassDef, Path]] = []
133
142
  for model_file in model_files:
134
143
  try:
135
144
  with open(model_file, encoding="utf-8") as f: # PEP 3120 default
@@ -140,27 +149,21 @@ class ASTDatabaseParser:
140
149
  # Collect all class definitions
141
150
  for node in ast.walk(tree):
142
151
  if isinstance(node, ast.ClassDef):
143
- self._all_classes[node.name] = node
144
- self._class_files[id(node)] = model_file
152
+ definitions.append((node, model_file))
145
153
  except Exception as e:
146
154
  print(f"Error parsing {model_file}: {e}", file=sys.stderr)
147
155
  self._parse_errors.append((model_file, str(e)))
148
156
 
149
157
  if self.strict and self._parse_errors:
150
158
  raise ModelParseError(self._parse_errors)
151
-
152
- # Framework base classes the scanned models build on but whose source
153
- # isn't scanned (e.g. Django's AbstractUser, #277). They have no file.
154
- defined = set(self._all_classes)
155
- for dialect_class in DIALECTS:
156
- builtins = dialect_class.builtin_classes(self._file_trees.values(), defined)
157
- for name, node in builtins.items():
158
- self._all_classes.setdefault(name, node)
159
+ self._collect_classes(definitions)
159
160
 
160
161
  # Second pass: process enum and model classes. Dialects (and their
161
162
  # caches) are fresh for each run.
162
163
  self._ctx = self._new_context()
163
164
  for class_node in self._all_classes.values():
165
+ if class_node.name in self._shadowed:
166
+ continue
164
167
  if is_enum_class(class_node, self._all_classes):
165
168
  self._parse_enum_class(class_node)
166
169
  continue
@@ -191,6 +194,141 @@ class ASTDatabaseParser:
191
194
 
192
195
  return self._entities, self._enums
193
196
 
197
+ def _collect_classes(self, definitions: List[Tuple[ast.ClassDef, Path]]) -> None:
198
+ """Index every class by name; a later definition replaces an earlier one.
199
+
200
+ ``class Item(Item)`` extends another definition of ``Item`` (#300): a
201
+ class cannot extend itself. Its base is the latest ``Item`` before it
202
+ in the same file or, in another file, the ``Item`` its ``from ...
203
+ import Item`` names. That base is kept under a name of its own,
204
+ ``Item@<line>``, which a copy of the extending class names as its base
205
+ instead; it is not drawn, as the extending definition replaces it. A
206
+ base that is a table model of its own (a Django model, a mapped
207
+ SQLAlchemy class, a SQLModel table) would need drawing as a separate
208
+ table, so it is not linked: the classes are indexed as before.
209
+ """
210
+ links: Dict[int, ast.ClassDef] = {} # id() of an extending class -> its base
211
+ for index, (node, model_file) in enumerate(definitions):
212
+ if not _extends_namesake(node):
213
+ continue
214
+ base = next(
215
+ (
216
+ earlier
217
+ for earlier, earlier_file in reversed(definitions[:index])
218
+ if earlier.name == node.name and earlier_file == model_file
219
+ ),
220
+ None,
221
+ )
222
+ if base is None:
223
+ base = self._imported_namesake(node, model_file)
224
+ if base is not None:
225
+ links[id(node)] = base
226
+ while True:
227
+ self._index_classes(definitions, links)
228
+ if not links:
229
+ return
230
+ ctx = self._new_context()
231
+ tables = [
232
+ extending
233
+ for extending, base in links.items()
234
+ for kind in [ctx.classify(self._all_classes[self._renamed[id(base)]])]
235
+ if kind is not None and not ctx.dialect(kind).keyless
236
+ ]
237
+ if not tables:
238
+ return
239
+ for extending in tables:
240
+ del links[extending]
241
+
242
+ def _index_classes(
243
+ self, definitions: List[Tuple[ast.ClassDef, Path]], links: Mapping[int, ast.ClassDef]
244
+ ) -> None:
245
+ """Fill the class index from ``definitions``, applying the namesake ``links``."""
246
+ self._all_classes = {}
247
+ self._class_files = {}
248
+ self._shadowed = {}
249
+ self._renamed = {}
250
+ files = {id(node): model_file for node, model_file in definitions}
251
+ bases = {id(base) for base in links.values()}
252
+ for node, model_file in definitions:
253
+ self._class_files[id(node)] = model_file
254
+ for node, model_file in definitions:
255
+ if id(node) in bases:
256
+ continue
257
+ if id(node) in links:
258
+ node = self._extend(node, links, files)
259
+ self._class_files[id(node)] = model_file
260
+ self._all_classes[node.name] = node
261
+ # Framework base classes the scanned models build on but whose source
262
+ # isn't scanned (e.g. Django's AbstractUser, #277). They have no file.
263
+ defined = set(self._all_classes)
264
+ for dialect_class in DIALECTS:
265
+ builtins = dialect_class.builtin_classes(self._file_trees.values(), defined)
266
+ for name, builtin in builtins.items():
267
+ self._all_classes.setdefault(name, builtin)
268
+
269
+ def _extend(
270
+ self, node: ast.ClassDef, links: Mapping[int, ast.ClassDef], files: Mapping[int, Path]
271
+ ) -> ast.ClassDef:
272
+ """A copy of ``node`` whose base of its own name is its linked base, renamed.
273
+
274
+ The base is kept under a new name; one that extends a namesake itself
275
+ is linked the same way first.
276
+ """
277
+ base = links[id(node)]
278
+ name = self._renamed.get(id(base))
279
+ if name is None:
280
+ name = f"{node.name}@{base.lineno}"
281
+ while name in self._shadowed:
282
+ name += "'"
283
+ self._renamed[id(base)] = name
284
+ self._shadowed[name] = node.name
285
+ renamed = copy.copy(self._extend(base, links, files) if id(base) in links else base)
286
+ renamed.name = name
287
+ self._all_classes[name] = renamed
288
+ self._class_files[id(renamed)] = files[id(base)]
289
+ extending = copy.copy(node)
290
+ extending.bases = [
291
+ ast.copy_location(ast.Name(id=name, ctx=ast.Load()), b)
292
+ if isinstance(b, ast.Name) and b.id == node.name
293
+ else b
294
+ for b in node.bases
295
+ ]
296
+ return extending
297
+
298
+ def _imported_namesake(self, node: ast.ClassDef, model_file: Path) -> ast.ClassDef | None:
299
+ """The class ``from <module> import <name>`` binds, when exactly one scanned file is it.
300
+
301
+ That is the module's last top-level definition of the name; several
302
+ files matching the module path leave it unresolved.
303
+ """
304
+ imported = self._import_source(model_file, node.name)
305
+ if imported is None:
306
+ return None
307
+ found: List[ast.ClassDef] = []
308
+ for other_file, tree in self._file_trees.items():
309
+ if other_file == model_file or not _is_module_file(other_file, model_file, imported):
310
+ continue
311
+ top = [
312
+ stmt
313
+ for stmt in tree.body
314
+ if isinstance(stmt, ast.ClassDef) and stmt.name == node.name
315
+ ]
316
+ if top:
317
+ found.append(top[-1])
318
+ return found[0] if len(found) == 1 else None
319
+
320
+ def _import_source(self, model_file: Path, name: str) -> Tuple[int, str] | None:
321
+ """``(level, module)`` of the ``from <module> import <name>`` in a file, if any."""
322
+ tree = self._file_trees.get(model_file)
323
+ if tree is None:
324
+ return None
325
+ for stmt in tree.body:
326
+ if isinstance(stmt, ast.ImportFrom) and any(
327
+ alias.name == name and alias.asname in (None, name) for alias in stmt.names
328
+ ):
329
+ return stmt.level, stmt.module or ""
330
+ return None
331
+
194
332
  def _discover_model_files(self) -> List[Path]:
195
333
  """Find model files (see :func:`discover_model_files`) and record the walk."""
196
334
  found = discover_model_files(
@@ -297,7 +435,7 @@ class ASTDatabaseParser:
297
435
  base_classes: List[str] = []
298
436
  for base in class_node.bases:
299
437
  if isinstance(base, ast.Name):
300
- base_classes.append(base.id)
438
+ base_classes.append(self._shadowed.get(base.id, base.id))
301
439
 
302
440
  entity = EntityInfo(
303
441
  name=class_node.name,
@@ -325,6 +463,25 @@ class ASTDatabaseParser:
325
463
  self._entities[class_node.name] = entity
326
464
 
327
465
 
466
+ def _is_module_file(path: Path, importer: Path, source: Tuple[int, str]) -> bool:
467
+ """Whether ``path`` is the module ``source`` (``(level, module)``) names from ``importer``."""
468
+ level, module = source
469
+ parts = [part for part in module.split(".") if part]
470
+ stem = path.with_suffix("")
471
+ own = list(stem.parent.parts) if path.name == "__init__.py" else list(stem.parts)
472
+ if level == 0:
473
+ return bool(parts) and own[-len(parts) :] == parts
474
+ package = importer.parent
475
+ for _ in range(level - 1):
476
+ package = package.parent
477
+ return own == list(package.joinpath(*parts).parts)
478
+
479
+
480
+ def _extends_namesake(node: ast.ClassDef) -> bool:
481
+ """Whether a class names a base of its own name (``class Item(Item)``)."""
482
+ return any(isinstance(base, ast.Name) and base.id == node.name for base in node.bases)
483
+
484
+
328
485
  def parse_models_directory(
329
486
  path: Path,
330
487
  *,
@@ -38,8 +38,8 @@ class AnnotatedDialect(Dialect):
38
38
  fields: Dict[str, FieldInfo] = {}
39
39
  relationships: Dict[str, _Rel] = {}
40
40
 
41
- for node in class_node.body:
42
- if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
41
+ for node in self.member_nodes(class_node):
42
+ if isinstance(node.target, ast.Name):
43
43
  field_name = node.target.id
44
44
  if self.reads_annotated_columns:
45
45
  node = self._with_aliases_expanded(node, class_node)
@@ -144,7 +144,8 @@ class AnnotatedDialect(Dialect):
144
144
  # (#241) is merged with the assigned Field() (SQLModel) / mapped_column()
145
145
  # (SQLAlchemy), bare or qualified (e.g. orm.mapped_column): what the
146
146
  # assigned call sets wins, except that primary_key=True from either
147
- # sticks. SQLModel ignores Field() keys in Annotated metadata.
147
+ # sticks. A SQLModel Field() in the metadata is applied before this
148
+ # (SQLModelDialect.member_nodes, #295).
148
149
  metadata_calls = (
149
150
  [
150
151
  call
@@ -166,10 +166,20 @@ class Dialect:
166
166
  """
167
167
  return [
168
168
  node.target.id
169
+ for node in self.member_nodes(class_node)
170
+ if isinstance(node.target, ast.Name) and not node.target.id.startswith("_")
171
+ ]
172
+
173
+ def member_nodes(self, class_node: ast.ClassDef) -> List[ast.AnnAssign]:
174
+ """The annotated attribute declarations of a class body, in body order.
175
+
176
+ A dialect may add members that are spelled differently, e.g.
177
+ SQLAlchemy's ``@declared_attr`` methods (#298).
178
+ """
179
+ return [
180
+ node
169
181
  for node in class_node.body
170
- if isinstance(node, ast.AnnAssign)
171
- and isinstance(node.target, ast.Name)
172
- and not node.target.id.startswith("_")
182
+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name)
173
183
  ]
174
184
 
175
185
  def class_members(self, class_node: ast.ClassDef, concrete: str) -> _ClassMembers:
@@ -187,7 +197,8 @@ class Dialect:
187
197
  """Which of ``names`` (the class and its ancestors) store columns in its table.
188
198
 
189
199
  All of them by default: a base's members are copied into the model.
190
- Django's multi-table inheritance keeps a concrete parent's in its own table.
200
+ Django's multi-table inheritance and SQLAlchemy's mapped-class
201
+ inheritance keep a concrete parent's in its own table.
191
202
  """
192
203
  return set(names)
193
204
 
@@ -286,8 +297,8 @@ class Dialect:
286
297
  """
287
298
  names: Dict[str, str] = {}
288
299
  for class_name in self.classes.merge_order(class_node):
289
- for node in self.classes.all[class_name].body:
290
- if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
300
+ for node in self.member_nodes(self.classes.all[class_name]):
301
+ if isinstance(node.target, ast.Name):
291
302
  db_name = self._explicit_column_name(node.value, use_key)
292
303
  names[node.target.id] = db_name if db_name is not None else node.target.id
293
304
  return names