erdify 1.3.0__tar.gz → 1.4.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 (26) hide show
  1. {erdify-1.3.0 → erdify-1.4.0}/PKG-INFO +1 -1
  2. {erdify-1.3.0 → erdify-1.4.0}/pyproject.toml +1 -1
  3. {erdify-1.3.0 → erdify-1.4.0}/pyproject.toml.orig +1 -1
  4. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/config.py +6 -1
  5. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/generator.py +184 -50
  6. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/parser/annotations.py +105 -2
  7. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/parser/common.py +17 -5
  8. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/parser/core.py +88 -4
  9. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/parser/dialects/annotated.py +113 -33
  10. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/parser/dialects/base.py +6 -0
  11. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/parser/dialects/django.py +1 -1
  12. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/parser/dialects/sqlalchemy.py +1 -0
  13. {erdify-1.3.0 → erdify-1.4.0}/LICENSE +0 -0
  14. {erdify-1.3.0 → erdify-1.4.0}/README.md +0 -0
  15. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/__init__.py +0 -0
  16. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/__main__.py +0 -0
  17. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/cli.py +0 -0
  18. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/inject.py +0 -0
  19. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/parser/__init__.py +0 -0
  20. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/parser/dialects/__init__.py +0 -0
  21. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/parser/dialects/keyless.py +0 -0
  22. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/parser/discovery.py +0 -0
  23. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/parser/inheritance.py +0 -0
  24. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/py.typed +0 -0
  25. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/pyproject.py +0 -0
  26. {erdify-1.3.0 → erdify-1.4.0}/src/erdify/sql_parser.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: erdify
3
- Version: 1.3.0
3
+ Version: 1.4.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
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "erdify"
3
- version = "1.3.0"
3
+ version = "1.4.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"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "erdify"
3
- version = "1.3.0"
3
+ version = "1.4.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"
@@ -1,7 +1,7 @@
1
1
  """Data classes for erdify."""
2
2
 
3
3
  from dataclasses import dataclass, field
4
- from typing import List, Tuple
4
+ from typing import Dict, List, Tuple
5
5
 
6
6
 
7
7
  @dataclass
@@ -67,6 +67,10 @@ class EntityInfo:
67
67
  reference is optional (e.g. ``user: User | None``); drawn as
68
68
  zero-or-one on the target side. Foreign-key columns carry their own
69
69
  ``FieldInfo.is_nullable`` instead.
70
+ inverse_relationships: Relationship attribute -> the attribute of the
71
+ other side's relationship it pairs with, when the source names it
72
+ (SQLAlchemy / SQLModel ``back_populates=``). Both sides are then
73
+ drawn as one edge.
70
74
  """
71
75
 
72
76
  name: str
@@ -79,6 +83,7 @@ class EntityInfo:
79
83
  base_classes: List[str] = field(default_factory=list)
80
84
  source: str = "sqlmodel"
81
85
  nullable_relationships: List[str] = field(default_factory=list)
86
+ inverse_relationships: Dict[str, str] = field(default_factory=dict)
82
87
 
83
88
 
84
89
  def is_structural_link_table(fields: List[FieldInfo]) -> bool:
@@ -3,7 +3,7 @@
3
3
  import html
4
4
  import json
5
5
  import re
6
- from typing import Dict, List, Tuple
6
+ from typing import Dict, Iterable, List, Tuple
7
7
 
8
8
  from .config import EntityInfo, EnumInfo, FieldInfo
9
9
 
@@ -186,18 +186,34 @@ class _ERGenerator:
186
186
  """
187
187
  return re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "_", name).lower()
188
188
 
189
+ #: Crow's-foot end at the target for what a relationship declares about
190
+ #: it: (kind, nullable) -> token, written on the target's side.
191
+ _TARGET_END = {
192
+ ("one", False): "||",
193
+ ("one", True): "o|",
194
+ ("many", False): "o{",
195
+ ("one_to_one", False): "||",
196
+ ("many_to_many", False): "o{",
197
+ }
198
+ #: The source end when only one side is declared: kind -> token.
199
+ _DEFAULT_SOURCE_END = {"one": "}o", "many": "||", "one_to_one": "||", "many_to_many": "}o"}
200
+
189
201
  @staticmethod
190
- def _declared_line(entity: EntityInfo, target: str, rel_type: str, attr: str) -> str:
191
- """The edge for one declared relationship of ``entity``."""
192
- if rel_type == "many":
193
- return f'{entity.name} ||--o{{ {target} : "{attr}"'
194
- if rel_type == "one_to_one":
195
- return f'{entity.name} ||--|| {target} : "{attr}"'
196
- if rel_type == "many_to_many":
197
- return f'{entity.name} }}o--o{{ {target} : "{attr}"'
198
- if attr in entity.nullable_relationships: # optional "one" (#223)
199
- return f'{entity.name} }}o--o| {target} : "{attr}"'
200
- return f'{entity.name} }}o--|| {target} : "{attr}"' # "one"
202
+ def _mirror(token: str) -> str:
203
+ """The same end written on the other side of ``--`` (``o{`` -> ``}o``)."""
204
+ return token[::-1].replace("{", "}")
205
+
206
+ def _end(self, entity: EntityInfo, kind: str, attr: str) -> str:
207
+ """The target end of ``entity.attr``; only a ``one`` reference can be optional."""
208
+ if kind not in self._DEFAULT_SOURCE_END:
209
+ kind = "one"
210
+ nullable = kind == "one" and attr in entity.nullable_relationships # #223
211
+ return self._TARGET_END[(kind, nullable)]
212
+
213
+ def _declared_line(self, entity: EntityInfo, target: str, rel_type: str, attr: str) -> str:
214
+ """The edge for one declared relationship of ``entity``, other side undeclared."""
215
+ source = self._DEFAULT_SOURCE_END.get(rel_type, self._DEFAULT_SOURCE_END["one"])
216
+ return f'{entity.name} {source}--{self._end(entity, rel_type, attr)} {target} : "{attr}"'
201
217
 
202
218
  def _declared_relationship_lines(
203
219
  self, fk_pairs: "set[frozenset[str]]", link_pairs: "set[frozenset[str]]"
@@ -210,18 +226,12 @@ class _ERGenerator:
210
226
  foreign-key column, so only a link table suppresses it: e.g. a Django
211
227
  ``ManyToManyField`` to the parent of a multi-table child (#233).
212
228
 
213
- Every declared attribute gets its own edge (#230), except the inverse
214
- side of a bidirectional relationship (e.g. ``User.posts`` and
215
- ``Post.user``), which describes the same edge and is collapsed into the
216
- side declared first. The IR does not record ``back_populates``, so each
217
- edge of the first side absorbs at most one relationship declared back
218
- from the other side: the first one with the inverse cardinality
219
- (``many`` for ``one`` and vice versa), preferring an attribute named
220
- after the class it points at (``Post.user`` for ``User``), else the
221
- first one left. A self-reference has no "other side", so there only an
222
- N:1 / 1:N inverse (``parent`` / ``children``) is absorbed; two references
223
- of the same cardinality (``friends`` / ``blocked``, both M:N) stay two
224
- edges.
229
+ Every declared attribute gets its own edge (#230), except that the two
230
+ sides of a bidirectional relationship (e.g. ``User.posts`` and
231
+ ``Post.user``) describe one edge (:meth:`_pair_sides`). That edge is
232
+ drawn from the side whose entity name sorts first, so it does not
233
+ depend on file order, and each end shows what its own side declares
234
+ (#239): ``list[B]`` on ``A`` and ``list[A]`` on ``B`` give ``}o--o{``.
225
235
  """
226
236
  connected = fk_pairs | link_pairs
227
237
  rels = [
@@ -232,34 +242,156 @@ class _ERGenerator:
232
242
  and frozenset((entity.name, target))
233
243
  not in (link_pairs if rel_type == "many_to_many" else connected)
234
244
  ]
235
- by_direction: Dict[Tuple[str, str], List[int]] = {}
245
+ by_pair: Dict[frozenset[str], List[int]] = {}
236
246
  for i, (entity, target, _, _) in enumerate(rels):
237
- by_direction.setdefault((entity.name, target), []).append(i)
238
- first_side: Dict[frozenset[str], str] = {}
239
- absorbed: set[int] = set()
240
- for i, (entity, target, rel_type, _) in enumerate(rels):
241
- if i in absorbed:
247
+ by_pair.setdefault(frozenset((entity.name, target)), []).append(i)
248
+ partner: Dict[int, int] = {}
249
+ for indices in by_pair.values():
250
+ partner.update(self._pair_sides(rels, indices))
251
+ folded = set(partner.values())
252
+ lines: List[str] = []
253
+ for i, (entity, target, rel_type, attr) in enumerate(rels):
254
+ if i in folded:
242
255
  continue
243
- if first_side.setdefault(frozenset((entity.name, target)), entity.name) != entity.name:
244
- continue # the other side's leftovers: drawn as they are
245
- if target == entity.name and self._INVERSE_KIND[rel_type] == rel_type:
246
- continue # two M:N / 1:1 self-references are two relationships
247
- inverse = [
248
- j
249
- for j in by_direction.get((target, entity.name), ())
250
- if j > i and j not in absorbed
251
- ]
252
- exact = [j for j in inverse if rels[j][2] == self._INVERSE_KIND[rel_type]]
253
- named = [j for j in exact if rels[j][3] == self._snake_case(entity.name)]
254
- if exact:
255
- absorbed.add((named or exact)[0])
256
- elif inverse and target != entity.name:
257
- absorbed.add(inverse[0])
258
- return [
259
- self._declared_line(entity, target, rel_type, attr)
260
- for i, (entity, target, rel_type, attr) in enumerate(rels)
261
- if i not in absorbed
256
+ if i in partner:
257
+ lines.append(self._merged_line(rels[i], rels[partner[i]]))
258
+ else:
259
+ lines.append(self._declared_line(entity, target, rel_type, attr))
260
+ return lines
261
+
262
+ def _pair_sides(
263
+ self, rels: "List[Tuple[EntityInfo, str, str, str]]", indices: List[int]
264
+ ) -> Dict[int, int]:
265
+ """Pair the relationships between one pair of entities: kept index -> folded index.
266
+
267
+ 1. **Explicit** (#240): a side naming its inverse (``back_populates=``)
268
+ pairs with that attribute of the other side, mutual declarations
269
+ first. One naming an attribute the other side does not declare is
270
+ guessed like the rest.
271
+ 2. **Guessed**: each relationship of the first side (the entity whose
272
+ name sorts first) folds at most one relationship declared back
273
+ from the other side, best candidates first: the inverse
274
+ cardinality (``many`` for ``one`` and vice versa) with attributes
275
+ named after the class they point at on both sides (``Post.user`` /
276
+ ``User.posts``), then on one side, then any inverse cardinality,
277
+ then (not for a self-reference) anything left.
278
+
279
+ Equal candidates are tried in declaration order within each entity, the
280
+ first side before the other, so the file (entity) order never changes
281
+ the result. The kept side is the first side's relationship; for a
282
+ self-reference, the attribute whose name sorts first. A self-reference
283
+ only folds an N:1 / 1:N inverse (``parent`` / ``children``): two
284
+ references of the same cardinality
285
+ (``friends`` / ``blocked``, both M:N) stay two edges.
286
+ """
287
+
288
+ def attr(i: int) -> str:
289
+ return rels[i][3]
290
+
291
+ def inverse_of(i: int) -> str | None:
292
+ return rels[i][0].inverse_relationships.get(attr(i))
293
+
294
+ def by_attr(idx: Iterable[int]) -> List[int]:
295
+ return sorted(idx, key=attr)
296
+
297
+ names = sorted({rels[i][0].name for i in indices} | {rels[i][1] for i in indices})
298
+ first = names[0]
299
+ self_ref = len(names) == 1
300
+ side_a = {i for i in indices if rels[i][0].name == first}
301
+ side_b = side_a if self_ref else set(indices) - side_a
302
+ pairs: Dict[int, int] = {}
303
+ used: set[int] = set()
304
+
305
+ def other_side(i: int) -> "set[int]":
306
+ return side_b if i in side_a else side_a
307
+
308
+ def pair(i: int, j: int) -> None:
309
+ if self_ref:
310
+ keep, fold = by_attr((i, j))
311
+ else:
312
+ keep, fold = (i, j) if i in side_a else (j, i)
313
+ pairs[keep] = fold
314
+ used.update((i, j))
315
+
316
+ # 1. Explicit: mutual back_populates first, then one-sided ones.
317
+ for mutual in (True, False):
318
+ for i in [*sorted(side_a), *sorted(side_b - side_a)]:
319
+ inverse = inverse_of(i)
320
+ if i in used or inverse is None:
321
+ continue
322
+ j = next(
323
+ (
324
+ j
325
+ for j in sorted(other_side(i))
326
+ if j != i
327
+ and j not in used
328
+ and attr(j) == inverse
329
+ and (inverse_of(j) == attr(i) if mutual else inverse_of(j) is None)
330
+ ),
331
+ None,
332
+ )
333
+ if j is not None:
334
+ pair(i, j)
335
+
336
+ # 2. Guessed: everything not paired whose inverse (if named) does not exist.
337
+ def guessable(i: int) -> bool:
338
+ inverse = inverse_of(i)
339
+ return i not in used and (
340
+ inverse is None or not any(attr(j) == inverse for j in other_side(i))
341
+ )
342
+
343
+ plural_names = {name: self._class_attr_names(name) for name in names}
344
+
345
+ def exact(i: int, j: int) -> bool:
346
+ return rels[j][2] == self._INVERSE_KIND[rels[i][2]]
347
+
348
+ def named(i: int, j: int) -> int:
349
+ entity_i, target_i, _, attr_i = rels[i]
350
+ return int(attr_i in plural_names[target_i]) + int(
351
+ attr(j) in plural_names[entity_i.name]
352
+ )
353
+
354
+ tiers = [
355
+ lambda i, j: exact(i, j) and named(i, j) == 2,
356
+ lambda i, j: exact(i, j) and named(i, j) == 1,
357
+ exact,
262
358
  ]
359
+ if not self_ref:
360
+ tiers.append(lambda i, j: True)
361
+ free_a = [i for i in sorted(side_a) if guessable(i)]
362
+ free_b = [j for j in sorted(side_b) if guessable(j)]
363
+ for fits in tiers:
364
+ for i in free_a:
365
+ if i in used:
366
+ continue
367
+ if self_ref and self._INVERSE_KIND[rels[i][2]] == rels[i][2]:
368
+ continue # two M:N / 1:1 self-references are two relationships
369
+ j = next((j for j in free_b if j not in used and j != i and fits(i, j)), None)
370
+ if j is not None:
371
+ pair(i, j)
372
+ return pairs
373
+
374
+ def _class_attr_names(self, name: str) -> "set[str]":
375
+ """Attribute names that refer to class ``name``: ``user``, ``users``, ``categories``."""
376
+ snake = self._snake_case(name)
377
+ names = {snake, snake + "s"}
378
+ if snake.endswith("y") and snake[-2:-1] not in ("a", "e", "i", "o", "u", ""):
379
+ names.add(snake[:-1] + "ies")
380
+ elif snake.endswith(("s", "x", "z", "ch", "sh")):
381
+ names.add(snake + "es")
382
+ return names
383
+
384
+ def _merged_line(
385
+ self,
386
+ kept: "Tuple[EntityInfo, str, str, str]",
387
+ folded: "Tuple[EntityInfo, str, str, str]",
388
+ ) -> str:
389
+ """One edge for both sides of a relationship; each end from its own side (#239)."""
390
+ entity, target, kind, attr = kept
391
+ other, _, other_kind, other_attr = folded
392
+ left = self._mirror(self._end(other, other_kind, other_attr))
393
+ right = self._end(entity, kind, attr)
394
+ return f'{entity.name} {left}--{right} {target} : "{attr}"'
263
395
 
264
396
  def _relationship_lines(self) -> List[str]:
265
397
  """Resolve every relationship line, de-duplicated and ordered.
@@ -587,7 +719,8 @@ def generate_json(
587
719
 
588
720
  Shape: ``{schema_version, title, entities: [{name, table_name, source, is_link_table,
589
721
  fields: [{name, type, primary_key, foreign_key, nullable, foreign_table,
590
- index, unique, default}], relationships: [{target, type, attribute, nullable}]}],
722
+ index, unique, default}], relationships: [{target, type, attribute, nullable,
723
+ inverse}]}],
591
724
  enums:
592
725
  [{name, values}]}``. Downstream tools can consume this without re-parsing.
593
726
  ``schema_version`` is :data:`JSON_SCHEMA_VERSION`; consumers should ignore
@@ -635,6 +768,7 @@ def generate_json(
635
768
  "type": rel_type,
636
769
  "attribute": attr,
637
770
  "nullable": rel_type == "one" and attr in entity.nullable_relationships,
771
+ "inverse": entity.inverse_relationships.get(attr),
638
772
  }
639
773
  for target, rel_type, attr in entity.relationships
640
774
  ]
@@ -5,7 +5,7 @@ nullability (#236), and call / wrapper recognition.
5
5
  """
6
6
 
7
7
  import ast
8
- from typing import Callable, List, NamedTuple, Tuple, TypeGuard
8
+ from typing import Callable, List, Mapping, NamedTuple, Tuple, TypeGuard
9
9
 
10
10
  from .common import _Rel
11
11
 
@@ -152,6 +152,109 @@ def column_type(node: ast.expr) -> Tuple[str, bool]:
152
152
  return ast.unparse(node), False
153
153
 
154
154
 
155
+ def expand_aliases(
156
+ node: ast.expr, aliases: Mapping[str, ast.expr], stack: Tuple[str, ...] = ()
157
+ ) -> ast.expr:
158
+ """``node`` with each column type alias replaced by its definition (#241).
159
+
160
+ ``id: Mapped[intpk]`` with ``intpk = Annotated[int, mapped_column(...)]``
161
+ reads as ``Mapped[Annotated[int, mapped_column(...)]]``, also when quoted
162
+ (``Mapped["intpk"]``). Only type positions are expanded: ``Annotated``
163
+ metadata, ``Literal`` values and call arguments (``ForeignKey("user.id")``)
164
+ are left alone, and so is a subscripted (generic) alias such as
165
+ ``Pk[int]``. An alias referring to itself is left as is. ``node`` itself
166
+ is never modified.
167
+ """
168
+ if not aliases or not _mentions_alias(node, aliases):
169
+ return node
170
+ if isinstance(node, ast.Name):
171
+ if node.id in aliases and node.id not in stack:
172
+ return expand_aliases(aliases[node.id], aliases, stack + (node.id,))
173
+ return node
174
+ if isinstance(node, ast.Constant):
175
+ parsed = parse_quoted(node)
176
+ if parsed is None:
177
+ return node
178
+ expanded = expand_aliases(parsed, aliases, stack)
179
+ return expanded if expanded is not parsed else node
180
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.BitOr):
181
+ return ast.BinOp(
182
+ left=expand_aliases(node.left, aliases, stack),
183
+ op=node.op,
184
+ right=expand_aliases(node.right, aliases, stack),
185
+ )
186
+ if isinstance(node, ast.Subscript):
187
+ name, args = subscript_parts(node)
188
+ if (
189
+ not args
190
+ or name == "Literal"
191
+ or (isinstance(node.value, ast.Name) and node.value.id in aliases)
192
+ ):
193
+ return node
194
+ # Annotated: only the type is a type position, not the metadata.
195
+ parts: List[ast.expr] = [expand_aliases(args[0], aliases, stack)] + (
196
+ args[1:]
197
+ if name == "Annotated"
198
+ else [expand_aliases(a, aliases, stack) for a in args[1:]]
199
+ )
200
+ slice_: ast.expr = (
201
+ ast.Tuple(elts=parts, ctx=ast.Load()) if isinstance(node.slice, ast.Tuple) else parts[0]
202
+ )
203
+ return ast.Subscript(value=node.value, slice=slice_, ctx=node.ctx)
204
+ return node
205
+
206
+
207
+ def _mentions_alias(node: ast.expr, aliases: Mapping[str, ast.expr]) -> bool:
208
+ """Whether an alias name, or any string (a possible quoted alias), occurs in ``node``."""
209
+ return any(
210
+ (isinstance(sub, ast.Name) and sub.id in aliases)
211
+ or (isinstance(sub, ast.Constant) and isinstance(sub.value, str))
212
+ for sub in ast.walk(node)
213
+ )
214
+
215
+
216
+ def defines_column_alias(value: ast.expr) -> bool:
217
+ """``Annotated[X, ..., mapped_column(...), ...]``: an alias carrying column settings.
218
+
219
+ Other ``Annotated`` aliases (e.g. Pydantic's ``PositiveInt = Annotated[int,
220
+ Gt(0)]``) keep their name as the displayed type.
221
+ """
222
+ if not isinstance(value, ast.Subscript) or subscript_parts(value)[0] != "Annotated":
223
+ return False
224
+ # column_metadata flattens nested Annotated, as typing does.
225
+ return any(is_call_to(arg, "mapped_column") for arg in column_metadata(value))
226
+
227
+
228
+ def column_metadata(node: ast.expr) -> List[ast.expr]:
229
+ """The ``Annotated`` metadata that applies to a column, innermost first (#241).
230
+
231
+ Follows the same wrappers as :func:`column_type`: ``Mapped`` and its
232
+ variants, type qualifiers, quotes, and an optional type (``Optional[X]``,
233
+ ``X | None``), but not a union of several types.
234
+ """
235
+ if isinstance(node, ast.Constant):
236
+ parsed = parse_quoted(node)
237
+ return column_metadata(parsed) if parsed is not None else []
238
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.BitOr):
239
+ rest = [option for option in union_operands(node) if not is_none(option)]
240
+ return column_metadata(rest[0]) if len(rest) == 1 else []
241
+ if not isinstance(node, ast.Subscript):
242
+ return []
243
+ name, args = subscript_parts(node)
244
+ if not args:
245
+ return []
246
+ if name == "Annotated":
247
+ return [*column_metadata(args[0]), *args[1:]]
248
+ if name in TRANSPARENT_WRAPPERS | MANY_WRAPPERS | QUALIFIERS:
249
+ return column_metadata(args[0])
250
+ if name == "Optional" and len(args) == 1:
251
+ return column_metadata(args[0])
252
+ if name == "Union":
253
+ rest = [option for option in args if not is_none(option)]
254
+ return column_metadata(rest[0]) if len(rest) == 1 else []
255
+ return []
256
+
257
+
155
258
  def literal_admits_none(args: List[ast.expr]) -> bool:
156
259
  """``Literal[..., None]``, also nested (``Literal[Literal[None], "a"]``).
157
260
 
@@ -267,4 +370,4 @@ def is_mapped_annotation(annotation: ast.expr) -> bool:
267
370
 
268
371
  def as_rel(ref: _AnnotationRef, attr: str) -> _Rel:
269
372
  """A relationship tuple; only a ``one`` reference can be optional (#223)."""
270
- return (ref.target, "many" if ref.many else "one", attr, ref.nullable and not ref.many)
373
+ return _Rel(ref.target, "many" if ref.many else "one", attr, ref.nullable and not ref.many)
@@ -2,16 +2,28 @@
2
2
 
3
3
  import ast
4
4
  import re
5
- from typing import Dict, List, Tuple, TypeVar
5
+ from typing import Dict, List, NamedTuple, Tuple, TypeVar
6
6
 
7
7
  from ..config import FieldInfo
8
8
 
9
9
  _V = TypeVar("_V")
10
10
 
11
- # A relationship while parsing: (target, type, attribute, nullable). The
12
- # public EntityInfo.relationships keeps (target, type, attribute); the flag
13
- # goes to EntityInfo.nullable_relationships.
14
- _Rel = Tuple[str, str, str, bool]
11
+
12
+ class _Rel(NamedTuple):
13
+ """A relationship while parsing.
14
+
15
+ The public ``EntityInfo.relationships`` keeps ``(target, kind, attr)``;
16
+ ``nullable`` goes to ``EntityInfo.nullable_relationships`` and
17
+ ``inverse`` to ``EntityInfo.inverse_relationships``.
18
+ """
19
+
20
+ target: str
21
+ kind: str
22
+ attr: str
23
+ nullable: bool
24
+ #: The other side's attribute, when named explicitly (``back_populates=``).
25
+ inverse: str | None = None
26
+
15
27
 
16
28
  # A class body's (fields, relationships, declared attribute names).
17
29
  _ClassMembers = Tuple[Dict[str, FieldInfo], Dict[str, _Rel], List[str]]
@@ -8,6 +8,7 @@ from pathlib import Path
8
8
  from typing import Dict, List, Tuple
9
9
 
10
10
  from ..config import EntityInfo, EnumInfo, is_structural_link_table
11
+ from .annotations import defines_column_alias
11
12
  from .common import is_enum_class, to_snake_case
12
13
  from .dialects import ParseContext
13
14
  from .discovery import discover_model_files
@@ -217,6 +218,11 @@ class ASTDatabaseParser:
217
218
  entity.nullable_relationships = [
218
219
  attr for attr in entity.nullable_relationships if attr in kept
219
220
  ]
221
+ entity.inverse_relationships = {
222
+ attr: inverse
223
+ for attr, inverse in entity.inverse_relationships.items()
224
+ if attr in kept
225
+ }
220
226
 
221
227
  def _parse_enum_class(self, class_node: ast.ClassDef) -> None:
222
228
  """Parse an enum class and extract its values."""
@@ -237,8 +243,86 @@ class ASTDatabaseParser:
237
243
  infer_keys=self.infer_keys,
238
244
  django_raw_types=self.django_raw_types,
239
245
  base_classes=self.base_classes,
246
+ aliases=self._annotated_aliases(),
240
247
  )
241
248
 
249
+ def _annotated_aliases(self) -> Dict[str, ast.expr]:
250
+ """Module-level column type aliases of every scanned file, by name (#241).
251
+
252
+ ``X = Annotated[..., mapped_column(...)]`` and ``X: TypeAlias = ...``.
253
+ A class of the same name wins. A name defined differently in two
254
+ places, or also bound to something else at module level (another
255
+ assignment, a chained or unpacking one, or an import under that name
256
+ other than of the alias itself, or any import of that name in the
257
+ module defining the alias), is ambiguous and not used. A PEP 695
258
+ ``type X = ...`` alias is not read: SQLAlchemy does not take a
259
+ ``mapped_column()`` from it.
260
+ """
261
+ found: Dict[str, ast.expr] = {}
262
+ ambiguous: set[str] = set()
263
+ for tree in self._file_trees.values():
264
+ # An import of the alias's own name in the module defining it
265
+ # replaces it (`UUID = Annotated[...]` then `from uuid import UUID`).
266
+ defined = {
267
+ target.id
268
+ for node in tree.body
269
+ if isinstance(node, (ast.Assign, ast.AnnAssign))
270
+ for target in (node.targets if isinstance(node, ast.Assign) else [node.target])
271
+ if isinstance(target, ast.Name)
272
+ }
273
+ imported = {
274
+ alias.asname or alias.name.split(".")[0]
275
+ for node in tree.body
276
+ if isinstance(node, (ast.Import, ast.ImportFrom))
277
+ for alias in node.names
278
+ }
279
+ ambiguous.update(defined & imported)
280
+ for node in tree.body:
281
+ ambiguous.update(self._other_module_bindings(node))
282
+ name, value = None, None
283
+ if (
284
+ isinstance(node, ast.Assign)
285
+ and len(node.targets) == 1
286
+ and isinstance(node.targets[0], ast.Name)
287
+ ):
288
+ name, value = node.targets[0].id, node.value
289
+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
290
+ name, value = node.target.id, node.value
291
+ if name is None or name in self._all_classes:
292
+ continue
293
+ if value is None or not defines_column_alias(value):
294
+ ambiguous.add(name) # also bound to something else
295
+ continue
296
+ if name in found and ast.dump(found[name]) != ast.dump(value):
297
+ ambiguous.add(name)
298
+ found[name] = value
299
+ return {name: value for name, value in found.items() if name not in ambiguous}
300
+
301
+ @staticmethod
302
+ def _other_module_bindings(node: ast.stmt) -> List[str]:
303
+ """Names a module-level statement binds other than as a plain ``X = ...``.
304
+
305
+ Chained (``a = b = ...``) and unpacking (``a, b = ...``) assignments,
306
+ and imports under a different name (``import UUID as intpk``). An
307
+ import of the alias itself (``from .types import intpk``) keeps it.
308
+ """
309
+ if isinstance(node, ast.Assign) and not (
310
+ len(node.targets) == 1 and isinstance(node.targets[0], ast.Name)
311
+ ):
312
+ return [
313
+ sub.id
314
+ for target in node.targets
315
+ for sub in ast.walk(target)
316
+ if isinstance(sub, ast.Name) and isinstance(sub.ctx, ast.Store)
317
+ ]
318
+ if isinstance(node, (ast.Import, ast.ImportFrom)):
319
+ return [
320
+ alias.asname
321
+ for alias in node.names
322
+ if alias.asname is not None and alias.asname != alias.name.split(".")[-1]
323
+ ]
324
+ return []
325
+
242
326
  def _classify_source(self, class_node: ast.ClassDef) -> str | None:
243
327
  """Classify which model framework a class belongs to (:meth:`ParseContext.classify`).
244
328
 
@@ -269,10 +353,10 @@ class ASTDatabaseParser:
269
353
  fields_dict, relationships_dict = dialect.collect(class_node)
270
354
 
271
355
  entity.fields = list(fields_dict.values())
272
- entity.relationships = [(t, kind, attr) for t, kind, attr, _ in relationships_dict.values()]
273
- entity.nullable_relationships = [
274
- attr for _, _, attr, nullable in relationships_dict.values() if nullable
275
- ]
356
+ rels = list(relationships_dict.values())
357
+ entity.relationships = [(r.target, r.kind, r.attr) for r in rels]
358
+ entity.nullable_relationships = [r.attr for r in rels if r.nullable]
359
+ entity.inverse_relationships = {r.attr: r.inverse for r in rels if r.inverse}
276
360
 
277
361
  dialect.finish(entity, class_node)
278
362
 
@@ -7,10 +7,17 @@ and in which of these member kinds they accept.
7
7
  """
8
8
 
9
9
  import ast
10
- from typing import Dict, Tuple
10
+ from typing import Dict, List, Tuple
11
11
 
12
12
  from ...config import FieldInfo
13
- from ..annotations import annotation_reference, as_rel, column_type, is_call_to
13
+ from ..annotations import (
14
+ annotation_reference,
15
+ as_rel,
16
+ column_metadata,
17
+ column_type,
18
+ expand_aliases,
19
+ is_call_to,
20
+ )
14
21
  from ..common import _Rel
15
22
  from .base import Dialect
16
23
 
@@ -33,6 +40,8 @@ class AnnotatedDialect(Dialect):
33
40
  for node in class_node.body:
34
41
  if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
35
42
  field_name = node.target.id
43
+ if self.reads_annotated_columns:
44
+ node = self._with_aliases_expanded(node)
36
45
 
37
46
  # Skip special attributes
38
47
  if field_name.startswith("_"):
@@ -65,6 +74,27 @@ class AnnotatedDialect(Dialect):
65
74
 
66
75
  return fields, relationships
67
76
 
77
+ @staticmethod
78
+ def _declares_default(value: ast.expr | None) -> bool:
79
+ """Whether the assigned value sets a default, even one that cannot be shown."""
80
+ if value is None:
81
+ return False
82
+ if not is_call_to(value, "mapped_column"):
83
+ return True # `x: Mapped[str] = "a"` (MappedAsDataclass)
84
+ return any(
85
+ kw.arg in ("default", "default_factory", "insert_default") for kw in value.keywords
86
+ )
87
+
88
+ def _with_aliases_expanded(self, node: ast.AnnAssign) -> ast.AnnAssign:
89
+ """``node`` with column type aliases in its annotation expanded (#241)."""
90
+ annotation = expand_aliases(node.annotation, self.ctx.aliases)
91
+ if annotation is node.annotation:
92
+ return node
93
+ expanded = ast.AnnAssign(
94
+ target=node.target, annotation=annotation, value=node.value, simple=node.simple
95
+ )
96
+ return ast.copy_location(expanded, node)
97
+
68
98
  def _parse_field(self, node: ast.AnnAssign) -> FieldInfo | None:
69
99
  """Parse a field from an annotated assignment."""
70
100
  if not isinstance(node.target, ast.Name):
@@ -73,42 +103,59 @@ class AnnotatedDialect(Dialect):
73
103
  field_name = node.target.id
74
104
  type_str, is_nullable = column_type(node.annotation)
75
105
 
76
- # Parse Field() / mapped_column() parameters
106
+ # As in SQLAlchemy, the first mapped_column() in the Annotated metadata
107
+ # (#241) is merged with the assigned Field() (SQLModel) / mapped_column()
108
+ # (SQLAlchemy), bare or qualified (e.g. orm.mapped_column): what the
109
+ # assigned call sets wins, except that primary_key=True from either
110
+ # sticks. SQLModel ignores Field() keys in Annotated metadata.
111
+ metadata_calls = (
112
+ [
113
+ call
114
+ for call in column_metadata(node.annotation)
115
+ if is_call_to(call, "mapped_column")
116
+ ][:1]
117
+ if self.reads_annotated_columns
118
+ else []
119
+ )
120
+ calls: List[ast.Call] = list(metadata_calls)
121
+ if node.value is not None and (
122
+ is_call_to(node.value, "Field") or is_call_to(node.value, "mapped_column")
123
+ ):
124
+ calls.append(node.value)
125
+
77
126
  is_primary_key = False
78
127
  is_foreign_key = False
79
128
  foreign_table = None
80
129
  index = False
81
130
  is_unique = False
82
-
83
- if node.value and isinstance(node.value, ast.Call):
84
- # Field() (SQLModel) / mapped_column() (SQLAlchemy), bare or qualified
85
- # (e.g. orm.mapped_column).
86
- if is_call_to(node.value, "Field") or is_call_to(node.value, "mapped_column"):
87
- for keyword in node.value.keywords:
88
- if keyword.arg == "primary_key" and isinstance(keyword.value, ast.Constant):
89
- is_primary_key = bool(keyword.value.value)
90
- elif keyword.arg == "foreign_key" and isinstance(keyword.value, ast.Constant):
91
- is_foreign_key = True
92
- foreign_table = str(keyword.value.value)
93
- elif keyword.arg == "index" and isinstance(keyword.value, ast.Constant):
94
- index = bool(keyword.value.value)
95
- elif keyword.arg == "unique" and isinstance(keyword.value, ast.Constant):
96
- is_unique = bool(keyword.value.value)
97
- elif (
98
- keyword.arg == "nullable"
99
- and isinstance(keyword.value, ast.Constant)
100
- and isinstance(keyword.value.value, bool)
101
- ):
102
- # An explicit nullable=True/False is what the database gets
103
- # and overrides the annotation; nullable=None means
104
- # "unspecified", so the annotation still decides.
105
- is_nullable = keyword.value.value
106
-
107
- # SQLAlchemy: ForeignKey("table.col") passed to mapped_column()
108
- fk_target = extract_foreign_key_arg(node.value)
109
- if fk_target is not None:
131
+ for call in calls:
132
+ for keyword in call.keywords:
133
+ if isinstance(keyword.value, ast.Constant) and keyword.value.value is None:
134
+ continue # `index=None` etc. means "unspecified" in SQLAlchemy
135
+ if keyword.arg == "primary_key" and isinstance(keyword.value, ast.Constant):
136
+ is_primary_key = is_primary_key or bool(keyword.value.value)
137
+ elif keyword.arg == "foreign_key" and isinstance(keyword.value, ast.Constant):
110
138
  is_foreign_key = True
111
- foreign_table = fk_target
139
+ foreign_table = str(keyword.value.value)
140
+ elif keyword.arg == "index" and isinstance(keyword.value, ast.Constant):
141
+ index = bool(keyword.value.value)
142
+ elif keyword.arg == "unique" and isinstance(keyword.value, ast.Constant):
143
+ is_unique = bool(keyword.value.value)
144
+ elif (
145
+ keyword.arg == "nullable"
146
+ and isinstance(keyword.value, ast.Constant)
147
+ and isinstance(keyword.value.value, bool)
148
+ ):
149
+ # An explicit nullable=True/False is what the database gets
150
+ # and overrides the annotation; nullable=None means
151
+ # "unspecified", so the annotation still decides.
152
+ is_nullable = keyword.value.value
153
+
154
+ # SQLAlchemy: ForeignKey("table.col") passed to mapped_column()
155
+ fk_target = extract_foreign_key_arg(call)
156
+ if fk_target is not None:
157
+ is_foreign_key = True
158
+ foreign_table = fk_target
112
159
 
113
160
  # Optional name-based key inference for keyless sources (Pydantic/dataclass).
114
161
  # Never overrides explicitly declared keys above.
@@ -121,6 +168,12 @@ class AnnotatedDialect(Dialect):
121
168
 
122
169
  # Extract default value
123
170
  default_value = self._extract_default_value(node)
171
+ for call in metadata_calls: # only when nothing assigned declares a default
172
+ if self._declares_default(node.value):
173
+ break
174
+ default_value = self._extract_default_value(
175
+ ast.AnnAssign(target=node.target, annotation=node.annotation, value=call, simple=1)
176
+ )
124
177
 
125
178
  # A primary key is never NULL in the database. SQLModel's idiomatic
126
179
  # `id: int | None = Field(default=None, primary_key=True)` only means
@@ -205,7 +258,34 @@ class AnnotatedDialect(Dialect):
205
258
  ref = annotation_reference(node.annotation)
206
259
  if ref is None: # names no single class (e.g. Mapped[A | B]): nothing to draw
207
260
  return None
208
- return as_rel(ref, node.target.id)
261
+ rel = as_rel(ref, node.target.id)
262
+ # back_populates= names the other side's attribute, so the two sides
263
+ # can be paired exactly (#240). backref= creates that side implicitly,
264
+ # so there is no second declaration to pair with.
265
+ if isinstance(node.value, ast.Call):
266
+ inverse = self._back_populates(node.value)
267
+ if inverse is not None:
268
+ rel = rel._replace(inverse=inverse)
269
+ return rel
270
+
271
+ @staticmethod
272
+ def _back_populates(call: ast.Call) -> str | None:
273
+ """``back_populates="x"``, also SQLModel's ``sa_relationship_kwargs={...}`` form."""
274
+ for kw in call.keywords:
275
+ value = kw.value
276
+ if kw.arg == "back_populates":
277
+ if isinstance(value, ast.Constant) and isinstance(value.value, str):
278
+ return value.value
279
+ elif kw.arg == "sa_relationship_kwargs" and isinstance(value, ast.Dict):
280
+ for key, item in zip(value.keys, value.values):
281
+ if (
282
+ isinstance(key, ast.Constant)
283
+ and key.value == "back_populates"
284
+ and isinstance(item, ast.Constant)
285
+ and isinstance(item.value, str)
286
+ ):
287
+ return item.value
288
+ return None
209
289
 
210
290
  def _parse_model_reference(self, node: ast.AnnAssign) -> _Rel | None:
211
291
  """Treat a field typed as another known model as a relationship.
@@ -21,6 +21,8 @@ class ParseContext:
21
21
  base_classes: Extra base-class names treated as Pydantic models.
22
22
  dialects: One instance of every dialect, in ``MODEL_SOURCES`` order;
23
23
  created on first use.
24
+ aliases: Module-level ``Annotated`` type aliases by name
25
+ (``intpk = Annotated[int, mapped_column(primary_key=True)]``, #241).
24
26
  """
25
27
 
26
28
  classes: ClassIndex = field(default_factory=lambda: ClassIndex({}))
@@ -28,6 +30,7 @@ class ParseContext:
28
30
  django_raw_types: bool = False
29
31
  base_classes: Set[str] = field(default_factory=set)
30
32
  dialects: List["Dialect"] = field(default_factory=list)
33
+ aliases: Dict[str, ast.expr] = field(default_factory=dict)
31
34
 
32
35
  def all_dialects(self) -> List["Dialect"]:
33
36
  """Every dialect, in classification order, bound to this context."""
@@ -73,6 +76,9 @@ class Dialect:
73
76
  #: typed as another model is a relationship, and an optional primary key
74
77
  #: really is optional.
75
78
  keyless: ClassVar[bool] = False
79
+ #: Reads SQLAlchemy column settings from ``Annotated`` metadata and column
80
+ #: type aliases (#241); only SQLAlchemy itself does.
81
+ reads_annotated_columns: ClassVar[bool] = False
76
82
 
77
83
  def __init__(self, ctx: ParseContext):
78
84
  self.ctx = ctx
@@ -728,7 +728,7 @@ class DjangoDialect(Dialect):
728
728
  return None
729
729
  if any(keyword.arg == "through" for keyword in call.keywords):
730
730
  return None
731
- return (target, "many_to_many", name, False)
731
+ return _Rel(target, "many_to_many", name, False)
732
732
 
733
733
  def _resolve_django_relationship_target(self, call: ast.Call, current_class: str) -> str | None:
734
734
  """Resolve a relationship field's target from its first positional or ``to=`` arg.
@@ -30,6 +30,7 @@ class SQLAlchemyDialect(AnnotatedDialect):
30
30
  """
31
31
 
32
32
  kind = "sqlalchemy"
33
+ reads_annotated_columns = True
33
34
 
34
35
  def detect(self, class_node: ast.ClassDef) -> bool:
35
36
  return has_tablename(class_node) and has_mapped_field(class_node)
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