erdify 1.4.2__tar.gz → 1.4.3__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.
- {erdify-1.4.2 → erdify-1.4.3}/PKG-INFO +2 -2
- {erdify-1.4.2 → erdify-1.4.3}/README.md +1 -1
- {erdify-1.4.2 → erdify-1.4.3}/pyproject.toml +3 -1
- {erdify-1.4.2 → erdify-1.4.3}/pyproject.toml.orig +14 -2
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/inject.py +3 -1
- erdify-1.4.3/src/erdify/parser/common.py +73 -0
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/parser/core.py +26 -4
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/parser/dialects/annotated.py +38 -3
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/parser/dialects/base.py +53 -15
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/parser/dialects/django.py +235 -33
- erdify-1.4.3/src/erdify/parser/dialects/django_apps.py +159 -0
- erdify-1.4.3/src/erdify/parser/dialects/django_contrib.py +168 -0
- erdify-1.4.3/src/erdify/parser/dialects/sqlalchemy.py +280 -0
- erdify-1.4.2/src/erdify/parser/common.py +0 -48
- erdify-1.4.2/src/erdify/parser/dialects/sqlalchemy.py +0 -148
- {erdify-1.4.2 → erdify-1.4.3}/LICENSE +0 -0
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/__init__.py +0 -0
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/__main__.py +0 -0
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/cli.py +0 -0
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/config.py +0 -0
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/generator.py +0 -0
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/parser/__init__.py +0 -0
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/parser/aliases.py +0 -0
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/parser/annotations.py +0 -0
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/parser/dialects/__init__.py +0 -0
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/parser/dialects/keyless.py +0 -0
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/parser/discovery.py +0 -0
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/parser/inheritance.py +0 -0
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/py.typed +0 -0
- {erdify-1.4.2 → erdify-1.4.3}/src/erdify/pyproject.py +0 -0
- {erdify-1.4.2 → erdify-1.4.3}/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.
|
|
3
|
+
Version: 1.4.3
|
|
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.
|
|
3
|
+
version = "1.4.3"
|
|
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.
|
|
3
|
+
version = "1.4.3"
|
|
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 = [
|
|
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
|
|
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)
|
|
@@ -173,6 +181,12 @@ class ASTDatabaseParser:
|
|
|
173
181
|
if entity.name not in self._entities:
|
|
174
182
|
self._entities[entity.name] = entity
|
|
175
183
|
|
|
184
|
+
# Cross-entity adjustments, once every entity is built, Core tables
|
|
185
|
+
# included (e.g. renamed columns that foreign keys elsewhere point at,
|
|
186
|
+
# #275, #292).
|
|
187
|
+
for dialect in self._ctx.all_dialects():
|
|
188
|
+
dialect.finalize(self._entities)
|
|
189
|
+
|
|
176
190
|
# Third pass: apply exclude patterns
|
|
177
191
|
self._apply_exclude_patterns()
|
|
178
192
|
|
|
@@ -247,8 +261,16 @@ class ASTDatabaseParser:
|
|
|
247
261
|
django_raw_types=self.django_raw_types,
|
|
248
262
|
base_classes=self.base_classes,
|
|
249
263
|
aliases_for=self._alias_lookup(),
|
|
264
|
+
file_of=lambda class_node: self._class_files.get(id(class_node)),
|
|
265
|
+
trees=list(self._file_trees.values()),
|
|
266
|
+
tree_of=self._tree_of,
|
|
250
267
|
)
|
|
251
268
|
|
|
269
|
+
def _tree_of(self, class_node: ast.ClassDef) -> ast.Module | None:
|
|
270
|
+
"""The syntax tree of the file ``class_node`` is defined in, if scanned."""
|
|
271
|
+
model_file = self._class_files.get(id(class_node))
|
|
272
|
+
return self._file_trees.get(model_file) if model_file is not None else None
|
|
273
|
+
|
|
252
274
|
def _alias_lookup(self) -> "Callable[[ast.ClassDef], Mapping[str, ast.expr]]":
|
|
253
275
|
"""Class -> the column type aliases visible where it is defined (#249, #250)."""
|
|
254
276
|
resolver = AliasResolver(self._file_trees, self._all_classes)
|
|
@@ -270,7 +292,7 @@ class ASTDatabaseParser:
|
|
|
270
292
|
def _parse_table_class(self, class_node: ast.ClassDef, source: str) -> None:
|
|
271
293
|
"""Parse a table class and all its inherited fields."""
|
|
272
294
|
dialect = self._ctx.dialect(source)
|
|
273
|
-
table_name = dialect.table_name(class_node) or
|
|
295
|
+
table_name = dialect.table_name(class_node) or dialect.default_table_name(class_node)
|
|
274
296
|
|
|
275
297
|
# Get base classes
|
|
276
298
|
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
|
-
|
|
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 #
|
|
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
|
|
248
|
-
without an explicit name maps to itself, so a
|
|
249
|
-
overrides an inherited name. Bases resolve in
|
|
250
|
-
fields (:meth:`ClassIndex.merge_order`), so the
|
|
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
|
|
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"})``.
|
|
267
|
-
|
|
268
|
-
the name, so an
|
|
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
|
-
|
|
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
|