erdify 1.4.2__tar.gz → 1.4.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 (31) hide show
  1. {erdify-1.4.2 → erdify-1.4.4}/PKG-INFO +2 -2
  2. {erdify-1.4.2 → erdify-1.4.4}/README.md +1 -1
  3. {erdify-1.4.2 → erdify-1.4.4}/pyproject.toml +3 -1
  4. {erdify-1.4.2 → erdify-1.4.4}/pyproject.toml.orig +14 -2
  5. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/inject.py +3 -1
  6. erdify-1.4.4/src/erdify/parser/common.py +73 -0
  7. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/parser/core.py +27 -6
  8. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/parser/dialects/annotated.py +38 -3
  9. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/parser/dialects/base.py +105 -47
  10. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/parser/dialects/django.py +235 -33
  11. erdify-1.4.4/src/erdify/parser/dialects/django_apps.py +159 -0
  12. erdify-1.4.4/src/erdify/parser/dialects/django_contrib.py +168 -0
  13. erdify-1.4.4/src/erdify/parser/dialects/sqlalchemy.py +764 -0
  14. erdify-1.4.2/src/erdify/parser/common.py +0 -48
  15. erdify-1.4.2/src/erdify/parser/dialects/sqlalchemy.py +0 -148
  16. {erdify-1.4.2 → erdify-1.4.4}/LICENSE +0 -0
  17. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/__init__.py +0 -0
  18. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/__main__.py +0 -0
  19. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/cli.py +0 -0
  20. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/config.py +0 -0
  21. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/generator.py +0 -0
  22. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/parser/__init__.py +0 -0
  23. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/parser/aliases.py +0 -0
  24. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/parser/annotations.py +0 -0
  25. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/parser/dialects/__init__.py +0 -0
  26. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/parser/dialects/keyless.py +0 -0
  27. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/parser/discovery.py +0 -0
  28. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/parser/inheritance.py +0 -0
  29. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/py.typed +0 -0
  30. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/pyproject.py +0 -0
  31. {erdify-1.4.2 → erdify-1.4.4}/src/erdify/sql_parser.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: erdify
3
- Version: 1.4.2
3
+ Version: 1.4.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
@@ -127,7 +127,7 @@ The runnable sources live in [`docs/examples/`](https://github.com/devsuit-berli
127
127
 
128
128
  ## 📚 Documentation
129
129
 
130
- - [Installation](https://erdify.devsuit.io/installation/) — pip, uv, pipx, or run with uvx
130
+ - [Installation](https://erdify.devsuit.io/installation/) — pip, uv, pipx, or run with uvx; [supported Python and framework versions](https://erdify.devsuit.io/installation/#supported-framework-versions)
131
131
  - [CLI & Python API](https://erdify.devsuit.io/usage/cli/) — all CLI options, running as a module, and the Python API
132
132
  - [Output Formats](https://erdify.devsuit.io/usage/output-formats/) — PlantUML & Mermaid, `--format`, `--inject` into Markdown, output naming
133
133
  - [Filtering & Key Inference](https://erdify.devsuit.io/usage/filtering/) — `--exclude`, `--exclude-paths`, `--include`, `--sources`, `--infer-keys`
@@ -98,7 +98,7 @@ The runnable sources live in [`docs/examples/`](https://github.com/devsuit-berli
98
98
 
99
99
  ## 📚 Documentation
100
100
 
101
- - [Installation](https://erdify.devsuit.io/installation/) — pip, uv, pipx, or run with uvx
101
+ - [Installation](https://erdify.devsuit.io/installation/) — pip, uv, pipx, or run with uvx; [supported Python and framework versions](https://erdify.devsuit.io/installation/#supported-framework-versions)
102
102
  - [CLI & Python API](https://erdify.devsuit.io/usage/cli/) — all CLI options, running as a module, and the Python API
103
103
  - [Output Formats](https://erdify.devsuit.io/usage/output-formats/) — PlantUML & Mermaid, `--format`, `--inject` into Markdown, output naming
104
104
  - [Filtering & Key Inference](https://erdify.devsuit.io/usage/filtering/) — `--exclude`, `--exclude-paths`, `--include`, `--sources`, `--infer-keys`
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "erdify"
3
- version = "1.4.2"
3
+ version = "1.4.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"
@@ -66,6 +66,8 @@ dev = [
66
66
  "pydantic",
67
67
  "django",
68
68
  "sqlglot",
69
+ "pyyaml>=6.0.3",
70
+ "packaging>=26.2",
69
71
  ]
70
72
  docs = ["mkdocs-material[imaging]"]
71
73
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "erdify"
3
- version = "1.4.2"
3
+ version = "1.4.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"
@@ -42,7 +42,19 @@ dependencies = [] # No runtime dependencies - uses stdlib ast module
42
42
  sql = ["sqlglot>=25"]
43
43
 
44
44
  [dependency-groups]
45
- dev = ["pytest", "pytest-cov", "ruff", "mypy", "sqlmodel", "sqlalchemy", "pydantic", "django", "sqlglot"]
45
+ dev = [
46
+ "pytest",
47
+ "pytest-cov",
48
+ "ruff",
49
+ "mypy",
50
+ "sqlmodel",
51
+ "sqlalchemy",
52
+ "pydantic",
53
+ "django",
54
+ "sqlglot",
55
+ "pyyaml>=6.0.3",
56
+ "packaging>=26.2",
57
+ ]
46
58
  docs = ["mkdocs-material[imaging]"]
47
59
 
48
60
  [project.scripts]
@@ -2,7 +2,9 @@
2
2
 
3
3
  Only the text between the markers is replaced; every other byte of the file is
4
4
  preserved. Matching is lenient (tolerates whitespace and future attributes) so
5
- the single-region format stays forward-compatible.
5
+ the single-region format stays forward-compatible: keep accepting attributes
6
+ inside the markers, so that named regions (``<!-- erdify:start id=auth -->``,
7
+ considered in #90) could be added later without breaking existing files.
6
8
  """
7
9
 
8
10
  import re
@@ -0,0 +1,73 @@
1
+ """Types and small helpers shared by the parser modules."""
2
+
3
+ import ast
4
+ import re
5
+ from typing import Dict, List, Mapping, NamedTuple, Set, Tuple, TypeVar
6
+
7
+ from ..config import FieldInfo
8
+
9
+ _V = TypeVar("_V")
10
+
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
+
27
+
28
+ # A class body's (fields, relationships, declared attribute names).
29
+ _ClassMembers = Tuple[Dict[str, FieldInfo], Dict[str, _Rel], List[str]]
30
+
31
+ #: Enum base class names recognized by erdify: the stdlib ``enum`` bases and
32
+ #: Django's choices (#296).
33
+ ENUM_BASES = frozenset(
34
+ {"Enum", "IntEnum", "StrEnum", "Flag", "IntFlag", "TextChoices", "IntegerChoices"}
35
+ )
36
+
37
+
38
+ def is_enum_class(
39
+ class_node: ast.ClassDef, classes: Mapping[str, ast.ClassDef] | None = None
40
+ ) -> bool:
41
+ """Check if a class is an enum: based on one of ``ENUM_BASES``, directly or
42
+ through scanned classes in ``classes`` (a project's own enum base, #296)."""
43
+ seen: Set[int] = set()
44
+ pending = [class_node]
45
+ while pending:
46
+ node = pending.pop()
47
+ if id(node) in seen:
48
+ continue
49
+ seen.add(id(node))
50
+ for base in node.bases:
51
+ if isinstance(base, ast.Attribute):
52
+ if isinstance(base.value, ast.Name) and base.value.id == "enum":
53
+ if base.attr in ENUM_BASES:
54
+ return True
55
+ name = base.attr # models.Flag: a scanned model, or Django's choices
56
+ elif isinstance(base, ast.Name):
57
+ name = base.id
58
+ else:
59
+ continue
60
+ # A scanned class of that name (a model called `Flag`) is
61
+ # followed, not taken for the enum base it shares a name with.
62
+ scanned = classes.get(name) if classes is not None else None
63
+ if scanned is not None and scanned is not node:
64
+ pending.append(scanned)
65
+ elif name in ENUM_BASES:
66
+ return True
67
+ return False
68
+
69
+
70
+ def to_snake_case(name: str) -> str:
71
+ """Convert CamelCase to snake_case."""
72
+ s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
73
+ return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
@@ -9,8 +9,8 @@ from typing import Callable, Dict, List, Mapping, Tuple
9
9
 
10
10
  from ..config import EntityInfo, EnumInfo, is_structural_link_table
11
11
  from .aliases import AliasResolver
12
- from .common import is_enum_class, to_snake_case
13
- from .dialects import ParseContext
12
+ from .common import is_enum_class
13
+ from .dialects import DIALECTS, ParseContext
14
14
  from .discovery import discover_model_files
15
15
  from .inheritance import ClassIndex
16
16
 
@@ -149,11 +149,19 @@ class ASTDatabaseParser:
149
149
  if self.strict and self._parse_errors:
150
150
  raise ModelParseError(self._parse_errors)
151
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
+
152
160
  # Second pass: process enum and model classes. Dialects (and their
153
161
  # caches) are fresh for each run.
154
162
  self._ctx = self._new_context()
155
163
  for class_node in self._all_classes.values():
156
- if is_enum_class(class_node):
164
+ if is_enum_class(class_node, self._all_classes):
157
165
  self._parse_enum_class(class_node)
158
166
  continue
159
167
  source = self._classify_source(class_node)
@@ -164,8 +172,7 @@ class ASTDatabaseParser:
164
172
  continue
165
173
  self._parse_table_class(class_node, source)
166
174
 
167
- # Entities that are not classes, e.g. SQLAlchemy Core association
168
- # tables referenced by relationship(secondary=...) (#34).
175
+ # Entities that are not classes, e.g. SQLAlchemy Core tables (#34, #305).
169
176
  for dialect in self._ctx.all_dialects():
170
177
  if self.sources is not None and dialect.kind not in self.sources:
171
178
  continue
@@ -173,6 +180,12 @@ class ASTDatabaseParser:
173
180
  if entity.name not in self._entities:
174
181
  self._entities[entity.name] = entity
175
182
 
183
+ # Cross-entity adjustments, once every entity is built, Core tables
184
+ # included (e.g. renamed columns that foreign keys elsewhere point at,
185
+ # #275, #292).
186
+ for dialect in self._ctx.all_dialects():
187
+ dialect.finalize(self._entities)
188
+
176
189
  # Third pass: apply exclude patterns
177
190
  self._apply_exclude_patterns()
178
191
 
@@ -247,8 +260,16 @@ class ASTDatabaseParser:
247
260
  django_raw_types=self.django_raw_types,
248
261
  base_classes=self.base_classes,
249
262
  aliases_for=self._alias_lookup(),
263
+ file_of=lambda class_node: self._class_files.get(id(class_node)),
264
+ trees=list(self._file_trees.values()),
265
+ tree_of=self._tree_of,
250
266
  )
251
267
 
268
+ def _tree_of(self, class_node: ast.ClassDef) -> ast.Module | None:
269
+ """The syntax tree of the file ``class_node`` is defined in, if scanned."""
270
+ model_file = self._class_files.get(id(class_node))
271
+ return self._file_trees.get(model_file) if model_file is not None else None
272
+
252
273
  def _alias_lookup(self) -> "Callable[[ast.ClassDef], Mapping[str, ast.expr]]":
253
274
  """Class -> the column type aliases visible where it is defined (#249, #250)."""
254
275
  resolver = AliasResolver(self._file_trees, self._all_classes)
@@ -270,7 +291,7 @@ class ASTDatabaseParser:
270
291
  def _parse_table_class(self, class_node: ast.ClassDef, source: str) -> None:
271
292
  """Parse a table class and all its inherited fields."""
272
293
  dialect = self._ctx.dialect(source)
273
- table_name = dialect.table_name(class_node) or to_snake_case(class_node.name)
294
+ table_name = dialect.table_name(class_node) or dialect.default_table_name(class_node)
274
295
 
275
296
  # Get base classes
276
297
  base_classes: List[str] = []
@@ -16,9 +16,10 @@ from ..annotations import (
16
16
  column_metadata,
17
17
  column_type,
18
18
  expand_aliases,
19
+ expr_name,
19
20
  is_call_to,
20
21
  )
21
- from ..common import _Rel
22
+ from ..common import _Rel, is_enum_class
22
23
  from .base import Dialect
23
24
 
24
25
 
@@ -68,19 +69,53 @@ class AnnotatedDialect(Dialect):
68
69
  relationships[field_name] = rel
69
70
  continue
70
71
 
72
+ # SQLAlchemy maps no column for `x: Mapped[T] = <plain value>`,
73
+ # not even with MappedAsDataclass: a default goes through
74
+ # mapped_column(default=...) (#294). `= None` counts as unset.
75
+ if not self.plain_value_is_column and not self._may_map_column(node):
76
+ continue
77
+
71
78
  field = self._parse_field(node)
72
79
  if field:
73
80
  fields[field_name] = field
74
81
 
75
82
  return fields, relationships
76
83
 
84
+ def _may_map_column(self, node: ast.AnnAssign) -> bool:
85
+ """Whether SQLAlchemy may map a column for this ``Mapped`` attribute.
86
+
87
+ Nothing, ``None``, a call, a name or a subscript may: a project helper
88
+ may return ``mapped_column()``, and a module-level
89
+ ``fk = mapped_column(...)`` may be assigned (also qualified,
90
+ ``columns.fk``, or looked up, ``COLUMNS["fk"]``). A constant (``= "a"``,
91
+ ``= 3``) is a plain class attribute, and so is a member of the
92
+ column's own type (``Mapped[Status] = Status.NEW``, scanned or not) or
93
+ of a scanned enum. A plain-value call such as
94
+ ``= datetime(2020, 1, 1)`` is therefore still drawn as a column.
95
+ """
96
+ value = node.value
97
+ if value is None or isinstance(value, (ast.Call, ast.Name, ast.Subscript)):
98
+ return True
99
+ if isinstance(value, ast.Constant):
100
+ return value.value is None
101
+ if isinstance(value, ast.Attribute):
102
+ owner = expr_name(value.value)
103
+ if owner is None:
104
+ return True
105
+ if owner == column_type(node.annotation)[0].rpartition(".")[2]:
106
+ return False
107
+ enum_class = self.classes.all.get(owner)
108
+ return enum_class is None or not is_enum_class(enum_class, self.classes.all)
109
+ return False
110
+
77
111
  @staticmethod
78
112
  def _declares_default(value: ast.expr | None) -> bool:
79
113
  """Whether the assigned value sets a default, even one that cannot be shown."""
80
- if value is None:
114
+ # `= None` is unset in SQLAlchemy: a default in the Annotated metadata applies.
115
+ if value is None or (isinstance(value, ast.Constant) and value.value is None):
81
116
  return False
82
117
  if not is_call_to(value, "mapped_column"):
83
- return True # `x: Mapped[str] = "a"` (MappedAsDataclass)
118
+ return True # another call (e.g. column_property()) is taken as setting its own
84
119
  return any(
85
120
  kw.arg in ("default", "default_factory", "insert_default") for kw in value.keywords
86
121
  )
@@ -2,11 +2,12 @@
2
2
 
3
3
  import ast
4
4
  from dataclasses import dataclass, field
5
+ from pathlib import Path
5
6
  from typing import Callable, ClassVar, Dict, Iterable, List, Mapping, Set, Tuple
6
7
 
7
8
  from ...config import EntityInfo, FieldInfo
8
9
  from ..annotations import is_call_to
9
- from ..common import _ClassMembers, _Rel
10
+ from ..common import _ClassMembers, _Rel, to_snake_case
10
11
  from ..inheritance import ClassIndex, merge_members, reorder
11
12
 
12
13
 
@@ -24,6 +25,9 @@ class ParseContext:
24
25
  aliases_for: Column type aliases visible where a class is defined
25
26
  (``intpk = Annotated[int, mapped_column(primary_key=True)]``,
26
27
  #241, #249, #250).
28
+ file_of: The file a class is defined in, or None if unknown.
29
+ trees: The syntax trees of every scanned file.
30
+ tree_of: The syntax tree of the file a class is defined in, or None.
27
31
  """
28
32
 
29
33
  classes: ClassIndex = field(default_factory=lambda: ClassIndex({}))
@@ -32,6 +36,9 @@ class ParseContext:
32
36
  base_classes: Set[str] = field(default_factory=set)
33
37
  dialects: List["Dialect"] = field(default_factory=list)
34
38
  aliases_for: Callable[[ast.ClassDef], Mapping[str, ast.expr]] = lambda _class_node: {}
39
+ file_of: Callable[[ast.ClassDef], Path | None] = lambda _class_node: None
40
+ trees: List[ast.Module] = field(default_factory=list)
41
+ tree_of: Callable[[ast.ClassDef], ast.Module | None] = lambda _class_node: None
35
42
 
36
43
  def all_dialects(self) -> List["Dialect"]:
37
44
  """Every dialect, in classification order, bound to this context."""
@@ -80,6 +87,9 @@ class Dialect:
80
87
  #: Reads SQLAlchemy column settings from ``Annotated`` metadata and column
81
88
  #: type aliases (#241); only SQLAlchemy itself does.
82
89
  reads_annotated_columns: ClassVar[bool] = False
90
+ #: Whether ``x: T = <plain value>`` declares a column with that default.
91
+ #: SQLAlchemy maps no column for it (#294).
92
+ plain_value_is_column: ClassVar[bool] = True
83
93
 
84
94
  def __init__(self, ctx: ParseContext):
85
95
  self.ctx = ctx
@@ -87,6 +97,19 @@ class Dialect:
87
97
 
88
98
  # -- detection --------------------------------------------------------
89
99
 
100
+ @classmethod
101
+ def builtin_classes(
102
+ cls, trees: Iterable[ast.Module], defined: Set[str]
103
+ ) -> Dict[str, ast.ClassDef]:
104
+ """Framework classes to add to the scanned ones, by name.
105
+
106
+ For base classes that ship with the framework and that models build
107
+ on (Django's ``AbstractUser``), so their members are inherited even
108
+ though their source isn't scanned. ``defined`` holds the names the
109
+ scanned files define; those are never replaced. None by default.
110
+ """
111
+ return {}
112
+
90
113
  def detect(self, class_node: ast.ClassDef) -> bool:
91
114
  """Whether the class belongs to this framework."""
92
115
  raise NotImplementedError
@@ -121,6 +144,10 @@ class Dialect:
121
144
  table_name = str(node.value.value)
122
145
  return table_name
123
146
 
147
+ def default_table_name(self, class_node: ast.ClassDef) -> str:
148
+ """The table name of a class that declares none; the snake_case class name."""
149
+ return to_snake_case(class_node.name)
150
+
124
151
  def class_fields(
125
152
  self, class_node: ast.ClassDef, concrete: str
126
153
  ) -> Tuple[Dict[str, FieldInfo], Dict[str, _Rel]]:
@@ -227,6 +254,13 @@ class Dialect:
227
254
 
228
255
  # -- finishing the entity -------------------------------------------------
229
256
 
257
+ def finalize(self, entities: Mapping[str, EntityInfo]) -> None:
258
+ """Adjust the dialect's entities once all entities are built. Nothing by default.
259
+
260
+ For changes that cross entities, e.g. renaming a column that other
261
+ entities' foreign keys reference.
262
+ """
263
+
230
264
  def finish(self, entity: EntityInfo, class_node: ast.ClassDef) -> None:
231
265
  """Adjust the built entity: mark columns made unique by ``__table_args__``."""
232
266
  # Single-column UniqueConstraint / unique Index in __table_args__ (#218).
@@ -241,38 +275,42 @@ class Dialect:
241
275
  if db_names.get(f.name, f.name) in unique_cols or f.name in unique_refs:
242
276
  f.is_unique = True
243
277
 
244
- def _db_column_names(self, class_node: ast.ClassDef) -> Dict[str, str]:
278
+ def _db_column_names(self, class_node: ast.ClassDef, use_key: bool = True) -> Dict[str, str]:
245
279
  """Map attribute name -> explicit DB column name for a class and its bases.
246
280
 
247
- See :meth:`_explicit_column_name` for the recognized forms. A column
248
- without an explicit name maps to itself, so a redeclaration without one
249
- overrides an inherited name. Bases resolve in the same order as the
250
- fields (:meth:`ClassIndex.merge_order`), so the name matches the winning column.
281
+ See :meth:`_explicit_column_name` for the recognized forms and
282
+ ``use_key``. A column without an explicit name maps to itself, so a
283
+ redeclaration without one overrides an inherited name. Bases resolve in
284
+ the same order as the fields (:meth:`ClassIndex.merge_order`), so the
285
+ name matches the winning column.
251
286
  """
252
287
  names: Dict[str, str] = {}
253
288
  for class_name in self.classes.merge_order(class_node):
254
289
  for node in self.classes.all[class_name].body:
255
290
  if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
256
- db_name = self._explicit_column_name(node.value)
291
+ db_name = self._explicit_column_name(node.value, use_key)
257
292
  names[node.target.id] = db_name if db_name is not None else node.target.id
258
293
  return names
259
294
 
260
295
  @classmethod
261
- def _explicit_column_name(cls, value: ast.expr | None) -> str | None:
262
- """Return the name a string constraint uses for this column, if explicit.
296
+ def _explicit_column_name(cls, value: ast.expr | None, use_key: bool = True) -> str | None:
297
+ """Return the explicit name of this column, if any.
263
298
 
264
299
  Recognizes ``mapped_column("name", ...)`` / ``mapped_column(name="name")``,
265
300
  and SQLModel's ``Field(sa_column=Column("name", ...))`` /
266
- ``Field(sa_column_kwargs={"name": "name"})``. SQLAlchemy resolves a
267
- constraint's string column through the column *key*, which defaults to
268
- the name, so an explicit ``key=`` takes precedence.
301
+ ``Field(sa_column_kwargs={"name": "name"})``. With ``use_key``, it is the
302
+ name a string constraint uses: SQLAlchemy resolves a constraint's string
303
+ column through the column *key*, which defaults to the name, so an
304
+ explicit ``key=`` takes precedence. Without it, it is the database
305
+ column's name.
269
306
  """
270
307
  if value is None:
271
308
  return None
272
309
  if is_call_to(value, "mapped_column") or is_call_to(value, "Column"):
273
310
  for kw in value.keywords:
274
311
  if (
275
- kw.arg == "key"
312
+ use_key
313
+ and kw.arg == "key"
276
314
  and isinstance(kw.value, ast.Constant)
277
315
  and isinstance(kw.value.value, str)
278
316
  ):
@@ -294,7 +332,7 @@ class Dialect:
294
332
  if is_call_to(value, "Field"):
295
333
  for kw in value.keywords:
296
334
  if kw.arg == "sa_column":
297
- return cls._explicit_column_name(kw.value)
335
+ return cls._explicit_column_name(kw.value, use_key)
298
336
  if kw.arg == "sa_column_kwargs" and isinstance(kw.value, ast.Dict):
299
337
  opts = {
300
338
  key.value: val.value
@@ -304,7 +342,7 @@ class Dialect:
304
342
  and isinstance(val.value, str)
305
343
  }
306
344
  # As above: an explicit key wins over the name.
307
- found = opts.get("key", opts.get("name"))
345
+ found = opts.get("key", opts.get("name")) if use_key else opts.get("name")
308
346
  if isinstance(found, str):
309
347
  return found
310
348
  return None
@@ -333,37 +371,57 @@ class Dialect:
333
371
  and node.target.id == "__table_args__"
334
372
  ):
335
373
  value = node.value
336
- columns: set[str] = set()
337
- refs: set[str] = set()
338
374
  if not isinstance(value, (ast.Tuple, ast.List)):
339
- return columns, refs
340
-
341
- for item in value.elts:
342
- if is_call_to(item, "UniqueConstraint"):
343
- cols = item.args
344
- elif is_call_to(item, "Index"):
345
- if not any(
346
- kw.arg == "unique" and isinstance(kw.value, ast.Constant) and kw.value.value
347
- for kw in item.keywords
348
- ):
349
- continue
350
- # A partial index (postgresql_where=, sqlite_where=, ...) is only
351
- # unique over a subset of rows, so it does not imply a 1:1. A
352
- # literal `*_where=None` is "no predicate", i.e. not partial.
353
- if any(
354
- kw.arg
355
- and kw.arg.endswith("_where")
356
- and not (isinstance(kw.value, ast.Constant) and kw.value.value is None)
357
- for kw in item.keywords
358
- ):
359
- continue
360
- cols = item.args[1:] # first positional arg is the index name
361
- else:
375
+ return set(), set()
376
+ return single_column_uniques(value.elts)
377
+
378
+
379
+ def explicit_column_name(value: ast.expr | None, use_key: bool = True) -> str | None:
380
+ """The explicit name (or, with ``use_key``, key) of a column declaration, if any.
381
+
382
+ See :meth:`Dialect._explicit_column_name`; also reads a Core ``Column(...)``.
383
+ """
384
+ return Dialect._explicit_column_name(value, use_key)
385
+
386
+
387
+ def single_column_uniques(items: Iterable[ast.expr]) -> Tuple[Set[str], Set[str]]:
388
+ """Columns made unique on their own by ``UniqueConstraint`` / unique ``Index`` items.
389
+
390
+ The items of a ``__table_args__`` tuple or the arguments of a Core
391
+ ``Table(...)``. Only constraints and indexes over exactly one column
392
+ count; a partial index (``*_where=``) does not make a column unique.
393
+
394
+ Returns ``(db_columns, attribute_refs)``: a string names the database
395
+ column, a bare name an attribute declared earlier in the class body.
396
+ """
397
+ columns: Set[str] = set()
398
+ refs: Set[str] = set()
399
+ for item in items:
400
+ if is_call_to(item, "UniqueConstraint"):
401
+ cols = item.args
402
+ elif is_call_to(item, "Index"):
403
+ if not any(
404
+ kw.arg == "unique" and isinstance(kw.value, ast.Constant) and kw.value.value
405
+ for kw in item.keywords
406
+ ):
362
407
  continue
363
- if len(cols) == 1:
364
- col = cols[0]
365
- if isinstance(col, ast.Constant) and isinstance(col.value, str):
366
- columns.add(col.value)
367
- elif isinstance(col, ast.Name):
368
- refs.add(col.id)
369
- return columns, refs
408
+ # A partial index (postgresql_where=, sqlite_where=, ...) is only
409
+ # unique over a subset of rows, so it does not imply a 1:1. A
410
+ # literal `*_where=None` is "no predicate", i.e. not partial.
411
+ if any(
412
+ kw.arg
413
+ and kw.arg.endswith("_where")
414
+ and not (isinstance(kw.value, ast.Constant) and kw.value.value is None)
415
+ for kw in item.keywords
416
+ ):
417
+ continue
418
+ cols = item.args[1:] # first positional arg is the index name
419
+ else:
420
+ continue
421
+ if len(cols) == 1:
422
+ col = cols[0]
423
+ if isinstance(col, ast.Constant) and isinstance(col.value, str):
424
+ columns.add(col.value)
425
+ elif isinstance(col, ast.Name):
426
+ refs.add(col.id)
427
+ return columns, refs