codecop 0.1.0__py3-none-any.whl
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.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,814 @@
|
|
|
1
|
+
"""Django models read statically: tables, columns, relations, indexes, managers.
|
|
2
|
+
|
|
3
|
+
What Django derives at import time is derived here from the class bodies: `db_table` or `<app label>_<model>`,
|
|
4
|
+
`db_column` or the field name (`<name>_id` for a foreign key), the implicit `id` key, fields of abstract bases,
|
|
5
|
+
the parent link of multi-table inheritance, automatic many-to-many tables, reverse accessors and query names.
|
|
6
|
+
A model whose table name cannot be determined (a computed `db_table`) is kept out, and counted.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import ast
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
|
|
15
|
+
from .orm_py import Cls, Mod, Project, dotted, kwarg, const, str_const
|
|
16
|
+
from .schema import Table
|
|
17
|
+
|
|
18
|
+
FIELD_NAME = re.compile(r"(Field|Key|ManyToMany\w*|OneToOne\w*|ForeignObject)$")
|
|
19
|
+
NOT_FIELDS = {"GenericForeignKey", "GenericRelation", "GenericRel"}
|
|
20
|
+
DENY_PKGS = ("pydantic", "sqlalchemy", "sqlmodel", "flask_sqlalchemy", "marshmallow", "msgspec", "attrs", "attr",
|
|
21
|
+
"typing", "peewee", "tortoise", "mongoengine", "pynamodb", "ormar", "piccolo", "beanie", "odmantic",
|
|
22
|
+
"tensorflow", "torch", "keras", "sklearn", "transformers", "openai", "anthropic", "rest_framework", "graphene")
|
|
23
|
+
DJANGO_ROOTS = {"Model", "AbstractUser", "AbstractBaseUser", "PermissionsMixin", "AbstractBaseSession"}
|
|
24
|
+
OTHER_ROOTS = {"MPTTModel", "MP_Node", "NS_Node", "AL_Node", "TimeStampedModel", "PolymorphicModel", "SoftDeletableModel",
|
|
25
|
+
"StatusModel", "TimeFramedModel", "UUIDModel", "SingletonModel", "TranslatableModel", "ClusterableModel",
|
|
26
|
+
"SafeDeleteModel", "LifecycleModel", "DirtyFieldsMixin", "OrderedModel", "ParanoidModel"}
|
|
27
|
+
JSON_TYPES = {"JSONField", "HStoreField", "JSONBField", "NullableJSONField", "LegacyTextJSONField"}
|
|
28
|
+
ARRAY_TYPES = {"ArrayField"}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class Field:
|
|
33
|
+
name: str
|
|
34
|
+
column: str
|
|
35
|
+
kind: str = "col" # col | fk | o2o | m2m
|
|
36
|
+
type_name: str = ""
|
|
37
|
+
null: bool = False
|
|
38
|
+
pk: bool = False
|
|
39
|
+
unique: bool = False
|
|
40
|
+
db_index: bool = False
|
|
41
|
+
target_ref: object = None # how the target was written, until resolved
|
|
42
|
+
target: "Model | None" = None
|
|
43
|
+
to_field: str = ""
|
|
44
|
+
related_name: str | None = None
|
|
45
|
+
related_query_name: str | None = None
|
|
46
|
+
through_ref: object = None
|
|
47
|
+
through: "Model | None" = None
|
|
48
|
+
auto_through: "Model | None" = None # the model Django makes for an automatic many-to-many table
|
|
49
|
+
m2m_table: str = ""
|
|
50
|
+
m2m_from: str = ""
|
|
51
|
+
m2m_to: str = ""
|
|
52
|
+
owner: "Model | None" = None # the model whose table holds the column
|
|
53
|
+
parent_link: bool = False
|
|
54
|
+
line: int = 0
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def is_rel(self) -> bool:
|
|
58
|
+
return self.kind in ("fk", "o2o", "m2m")
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def is_json(self) -> bool:
|
|
62
|
+
return self.type_name in JSON_TYPES or self.type_name.endswith("JSONField")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass
|
|
66
|
+
class Rel:
|
|
67
|
+
"""A relation seen from the other side: `kind` is rev_fk | rev_o2o | rev_m2m."""
|
|
68
|
+
kind: str
|
|
69
|
+
model: "Model" # the model on the far side (where the field is declared)
|
|
70
|
+
field: Field
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class Manager:
|
|
75
|
+
name: str
|
|
76
|
+
cls: Cls | None = None # the manager class, when it is the project's
|
|
77
|
+
qs_cls: Cls | None = None # its queryset class, when one is attached
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass
|
|
81
|
+
class Model:
|
|
82
|
+
cls: Cls | None
|
|
83
|
+
name: str
|
|
84
|
+
app_label: str
|
|
85
|
+
table: str = ""
|
|
86
|
+
abstract: bool = False
|
|
87
|
+
proxy: bool = False
|
|
88
|
+
managed: bool = True
|
|
89
|
+
fields: dict[str, Field] = field(default_factory=dict)
|
|
90
|
+
pk: Field | None = None
|
|
91
|
+
parents: list["Model"] = field(default_factory=list) # concrete parents (multi-table inheritance)
|
|
92
|
+
ordering: list = field(default_factory=list)
|
|
93
|
+
indexes: list[dict] = field(default_factory=list)
|
|
94
|
+
managers: dict[str, Manager] = field(default_factory=dict)
|
|
95
|
+
reverse: dict[str, Rel] = field(default_factory=dict) # accessor name -> relation
|
|
96
|
+
reverse_query: dict[str, Rel] = field(default_factory=dict) # name used in lookups -> relation
|
|
97
|
+
where: str = "" # file:line
|
|
98
|
+
builtin: bool = False
|
|
99
|
+
table_basis: str = "meta"
|
|
100
|
+
|
|
101
|
+
def __hash__(self) -> int:
|
|
102
|
+
return id(self)
|
|
103
|
+
|
|
104
|
+
def __eq__(self, other) -> bool:
|
|
105
|
+
return self is other
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def label(self) -> str:
|
|
109
|
+
return f"{self.app_label}.{self.name}"
|
|
110
|
+
|
|
111
|
+
def field_by_attname(self, name: str) -> Field | None:
|
|
112
|
+
f = self.fields.get(name)
|
|
113
|
+
if f is not None:
|
|
114
|
+
return f
|
|
115
|
+
if name.endswith("_id"):
|
|
116
|
+
f = self.fields.get(name[:-3])
|
|
117
|
+
if f is not None and f.kind in ("fk", "o2o"):
|
|
118
|
+
return f
|
|
119
|
+
return None
|
|
120
|
+
|
|
121
|
+
def columns(self) -> list[Field]:
|
|
122
|
+
"""Fields with a column in this model's own table."""
|
|
123
|
+
return [f for f in self.fields.values() if f.kind != "m2m" and (f.owner is None or f.owner is self)]
|
|
124
|
+
|
|
125
|
+
def all_columns(self) -> list[Field]:
|
|
126
|
+
return [f for f in self.fields.values() if f.kind != "m2m"]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
BUILTIN = {
|
|
130
|
+
# the documented schema of Django's own apps: enough to translate queries that touch them
|
|
131
|
+
("auth", "User"): ("auth_user", ["id", "password", "last_login", "is_superuser", "username", "first_name", "last_name",
|
|
132
|
+
"email", "is_staff", "is_active", "date_joined"]),
|
|
133
|
+
("auth", "Group"): ("auth_group", ["id", "name"]),
|
|
134
|
+
("auth", "Permission"): ("auth_permission", ["id", "name", "content_type_id", "codename"]),
|
|
135
|
+
("contenttypes", "ContentType"): ("django_content_type", ["id", "app_label", "model"]),
|
|
136
|
+
("sessions", "Session"): ("django_session", ["session_key", "session_data", "expire_date"]),
|
|
137
|
+
("sites", "Site"): ("django_site", ["id", "domain", "name"]),
|
|
138
|
+
("admin", "LogEntry"): ("django_admin_log", ["id", "action_time", "user_id", "content_type_id", "object_id", "object_repr",
|
|
139
|
+
"action_flag", "change_message"]),
|
|
140
|
+
}
|
|
141
|
+
BUILTIN_PATHS = {
|
|
142
|
+
"django.contrib.auth.models.User": ("auth", "User"), "django.contrib.auth.models.Group": ("auth", "Group"),
|
|
143
|
+
"django.contrib.auth.models.Permission": ("auth", "Permission"),
|
|
144
|
+
"django.contrib.contenttypes.models.ContentType": ("contenttypes", "ContentType"),
|
|
145
|
+
"django.contrib.sessions.models.Session": ("sessions", "Session"),
|
|
146
|
+
"django.contrib.sites.models.Site": ("sites", "Site"), "django.contrib.admin.models.LogEntry": ("admin", "LogEntry"),
|
|
147
|
+
}
|
|
148
|
+
ABSTRACT_USER_FIELDS = ["password", "last_login", "is_superuser", "username", "first_name", "last_name", "email", "is_staff",
|
|
149
|
+
"is_active", "date_joined"]
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class DjangoIndex:
|
|
153
|
+
def __init__(self, project: Project):
|
|
154
|
+
self.project = project
|
|
155
|
+
self.by_cls: dict[int, Model] = {}
|
|
156
|
+
self.models: list[Model] = []
|
|
157
|
+
self.by_label: dict[tuple[str, str], Model] = {}
|
|
158
|
+
self.by_name: dict[str, list[Model]] = {}
|
|
159
|
+
self.auth_user: Model | None = None
|
|
160
|
+
self.skipped: dict[str, int] = {}
|
|
161
|
+
self.manager_models: dict[int, list[tuple[Model, Manager]]] = {} # manager class id -> models using it
|
|
162
|
+
self.qs_models: dict[int, list[Model]] = {} # queryset class id -> models using it
|
|
163
|
+
self._is_model: dict[int, bool] = {}
|
|
164
|
+
self._app_labels: dict[str, str] = {}
|
|
165
|
+
self._building: set[int] = set()
|
|
166
|
+
self._build()
|
|
167
|
+
|
|
168
|
+
# ---- which classes are models ----------------------------------------------------------------------------
|
|
169
|
+
def is_model_cls(self, cls: Cls) -> bool:
|
|
170
|
+
got = self._is_model.get(id(cls))
|
|
171
|
+
if got is None:
|
|
172
|
+
got = False
|
|
173
|
+
for ext in self.project.external_bases(cls):
|
|
174
|
+
if self._model_root(ext):
|
|
175
|
+
# outside `django.` itself a base named ...Model proves nothing unless the project uses Django here
|
|
176
|
+
if ext.startswith("django.") or any(m.startswith("django") for _, m, _ in cls.mod.imports.values()) \
|
|
177
|
+
or any(any(m.startswith("django") for _, m, _ in c.mod.imports.values()) for c in self.project.mro(cls)[1:]):
|
|
178
|
+
got = True
|
|
179
|
+
break
|
|
180
|
+
self._is_model[id(cls)] = got
|
|
181
|
+
return got
|
|
182
|
+
|
|
183
|
+
@staticmethod
|
|
184
|
+
def _model_root(ext: str) -> bool:
|
|
185
|
+
parts = ext.split(".")
|
|
186
|
+
last = parts[-1]
|
|
187
|
+
if parts[0] in DENY_PKGS:
|
|
188
|
+
return False
|
|
189
|
+
if parts[0] == "django":
|
|
190
|
+
return last in DJANGO_ROOTS
|
|
191
|
+
if last in OTHER_ROOTS:
|
|
192
|
+
return True
|
|
193
|
+
if ext in ("models.Model",): # `models` not imported in a way we could follow
|
|
194
|
+
return True
|
|
195
|
+
return len(parts) > 1 and "models" in parts[:-1] and last.endswith("Model")
|
|
196
|
+
|
|
197
|
+
# ---- build -----------------------------------------------------------------------------------------------
|
|
198
|
+
def _build(self) -> None:
|
|
199
|
+
p = self.project
|
|
200
|
+
for (app, name), (table, cols) in BUILTIN.items():
|
|
201
|
+
m = Model(cls=None, name=name, app_label=app, table=table, builtin=True, where="django")
|
|
202
|
+
for c in cols:
|
|
203
|
+
if c.endswith("_id") and c != "object_id":
|
|
204
|
+
m.fields[c[:-3]] = Field(c[:-3], c, kind="fk", owner=m)
|
|
205
|
+
else:
|
|
206
|
+
m.fields[c] = Field(c, c, pk=c in ("id", "session_key"), owner=m)
|
|
207
|
+
m.pk = m.fields.get("id") or m.fields.get("session_key")
|
|
208
|
+
self.by_label[(app, name.lower())] = m
|
|
209
|
+
self.by_label[("auth", "permission")].fields["content_type"].target = self.by_label[("contenttypes", "contenttype")]
|
|
210
|
+
self.by_label[("admin", "logentry")].fields["content_type"].target = self.by_label[("contenttypes", "contenttype")]
|
|
211
|
+
self.by_label[("admin", "logentry")].fields["user"].target_ref = "AUTH_USER"
|
|
212
|
+
|
|
213
|
+
candidates = [c for mod in p.mods.values() for c in mod.classes.values() if self.is_model_cls(c)]
|
|
214
|
+
for cls in candidates:
|
|
215
|
+
self._model_for(cls)
|
|
216
|
+
for m in list(self.models):
|
|
217
|
+
self._resolve_relations(m)
|
|
218
|
+
for m in list(self.models):
|
|
219
|
+
self._reverse(m)
|
|
220
|
+
for m in self.models:
|
|
221
|
+
self._indexes(m)
|
|
222
|
+
self._find_auth_user()
|
|
223
|
+
for m in list(self.models) + [b for b in self.by_label.values() if b.builtin]:
|
|
224
|
+
for f in m.fields.values():
|
|
225
|
+
if f.target_ref == "AUTH_USER" and f.target is None:
|
|
226
|
+
f.target = self.auth_user
|
|
227
|
+
|
|
228
|
+
def _app_label(self, mod: Mod) -> str:
|
|
229
|
+
"""The package that holds the `models` module (Django's default label), or the `label` of its AppConfig."""
|
|
230
|
+
parts = mod.rel.split("/")
|
|
231
|
+
key = "/".join(parts[:-1])
|
|
232
|
+
got = self._app_labels.get(key)
|
|
233
|
+
if got is not None:
|
|
234
|
+
return got
|
|
235
|
+
app_dir = parts[:-1]
|
|
236
|
+
names = [x[:-3] if x.endswith(".py") else x for x in parts]
|
|
237
|
+
if "models" in names:
|
|
238
|
+
app_dir = parts[: names.index("models")]
|
|
239
|
+
label = app_dir[-1] if app_dir else (parts[-1][:-3])
|
|
240
|
+
# an AppConfig may rename it: `label = "x"` in apps.py (or __init__.py) of the app's package
|
|
241
|
+
for depth in range(len(app_dir), max(len(app_dir) - 2, 0), -1):
|
|
242
|
+
found = None
|
|
243
|
+
for fname in ("apps.py", "__init__.py"):
|
|
244
|
+
am = self.project.mods.get("/".join(app_dir[:depth] + [fname]))
|
|
245
|
+
if am is None:
|
|
246
|
+
continue
|
|
247
|
+
for c in am.classes.values():
|
|
248
|
+
if any((b or "").endswith("AppConfig") for b in c.bases):
|
|
249
|
+
lab = str_const(c.assigns.get("label"))
|
|
250
|
+
nm = str_const(c.assigns.get("name"))
|
|
251
|
+
found = lab or (nm.split(".")[-1] if nm else None)
|
|
252
|
+
if found:
|
|
253
|
+
break
|
|
254
|
+
if found:
|
|
255
|
+
break
|
|
256
|
+
if found:
|
|
257
|
+
label = found
|
|
258
|
+
break
|
|
259
|
+
self._app_labels[key] = label
|
|
260
|
+
return label
|
|
261
|
+
|
|
262
|
+
def _meta(self, cls: Cls) -> dict[str, ast.AST]:
|
|
263
|
+
meta = cls.inner.get("Meta")
|
|
264
|
+
return dict(meta.assigns) if meta is not None else {}
|
|
265
|
+
|
|
266
|
+
def _model_for(self, cls: Cls) -> Model | None:
|
|
267
|
+
got = self.by_cls.get(id(cls))
|
|
268
|
+
if got is not None or id(cls) in self._building:
|
|
269
|
+
return got
|
|
270
|
+
self._building.add(id(cls))
|
|
271
|
+
p = self.project
|
|
272
|
+
meta = self._meta(cls)
|
|
273
|
+
ok, abstract = const(meta.get("abstract"))
|
|
274
|
+
ok2, proxy = const(meta.get("proxy"))
|
|
275
|
+
app = str_const(meta.get("app_label")) or self._app_label(cls.mod)
|
|
276
|
+
m = Model(cls=cls, name=cls.name, app_label=app, abstract=bool(ok and abstract), proxy=bool(ok2 and proxy),
|
|
277
|
+
where=f"{cls.mod.rel}:{cls.node.lineno}")
|
|
278
|
+
okm, managed = const(meta.get("managed"))
|
|
279
|
+
m.managed = not (okm and managed is False)
|
|
280
|
+
self.by_cls[id(cls)] = m
|
|
281
|
+
is_abstract = m.abstract
|
|
282
|
+
|
|
283
|
+
# bases, nearest last so that nearer definitions override
|
|
284
|
+
direct = []
|
|
285
|
+
for expr, name in zip(cls.base_exprs, cls.bases):
|
|
286
|
+
base = p.resolve_class(cls.mod, name) if name else None
|
|
287
|
+
if base is not None and self.is_model_cls(base):
|
|
288
|
+
bm = self._model_for(base)
|
|
289
|
+
if bm is not None:
|
|
290
|
+
direct.append(bm)
|
|
291
|
+
elif base is not None:
|
|
292
|
+
# a plain mixin class may still declare fields (they are collected by Django's metaclass only on
|
|
293
|
+
# abstract models, so nothing to add)
|
|
294
|
+
continue
|
|
295
|
+
elif name:
|
|
296
|
+
ext = p.external(cls.mod, name) or name
|
|
297
|
+
last = ext.split(".")[-1]
|
|
298
|
+
if last == "AbstractUser":
|
|
299
|
+
for c in ABSTRACT_USER_FIELDS:
|
|
300
|
+
m.fields.setdefault(c, Field(c, c, owner=m))
|
|
301
|
+
self._perm_fields(m)
|
|
302
|
+
elif last == "AbstractBaseUser":
|
|
303
|
+
for c in ("password", "last_login"):
|
|
304
|
+
m.fields.setdefault(c, Field(c, c, owner=m))
|
|
305
|
+
elif last == "PermissionsMixin":
|
|
306
|
+
m.fields.setdefault("is_superuser", Field("is_superuser", "is_superuser", owner=m))
|
|
307
|
+
self._perm_fields(m)
|
|
308
|
+
elif last == "MPTTModel":
|
|
309
|
+
for c in ("lft", "rght", "tree_id", "level"):
|
|
310
|
+
m.fields.setdefault(c, Field(c, c, owner=m, db_index=True))
|
|
311
|
+
elif last == "TimeStampedModel":
|
|
312
|
+
for c in ("created", "modified"):
|
|
313
|
+
m.fields.setdefault(c, Field(c, c, owner=m))
|
|
314
|
+
concrete_parent = None
|
|
315
|
+
for bm in reversed(direct):
|
|
316
|
+
if bm.abstract:
|
|
317
|
+
for f in bm.fields.values():
|
|
318
|
+
nf = Field(**{**f.__dict__})
|
|
319
|
+
nf.owner = m
|
|
320
|
+
nf.target = None # resolved again for this model (related_name templates differ)
|
|
321
|
+
m.fields[f.name] = nf
|
|
322
|
+
for k, v in bm.managers.items():
|
|
323
|
+
m.managers.setdefault(k, v)
|
|
324
|
+
if not m.ordering and bm.ordering:
|
|
325
|
+
m.ordering = list(bm.ordering)
|
|
326
|
+
else:
|
|
327
|
+
concrete_parent = bm
|
|
328
|
+
if concrete_parent is not None:
|
|
329
|
+
m.parents.append(concrete_parent)
|
|
330
|
+
for f in concrete_parent.fields.values():
|
|
331
|
+
if f.name not in m.fields:
|
|
332
|
+
m.fields[f.name] = f # same Field object: its owner is the parent table
|
|
333
|
+
for k, v in concrete_parent.managers.items():
|
|
334
|
+
m.managers.setdefault(k, v)
|
|
335
|
+
if m.proxy:
|
|
336
|
+
m.table = concrete_parent.table
|
|
337
|
+
if not m.ordering:
|
|
338
|
+
m.ordering = list(concrete_parent.ordering)
|
|
339
|
+
|
|
340
|
+
# own fields, in source order
|
|
341
|
+
for st in cls.node.body:
|
|
342
|
+
target = value = None
|
|
343
|
+
if isinstance(st, ast.Assign) and len(st.targets) == 1 and isinstance(st.targets[0], ast.Name):
|
|
344
|
+
target, value = st.targets[0].id, st.value
|
|
345
|
+
elif isinstance(st, ast.AnnAssign) and isinstance(st.target, ast.Name) and st.value is not None:
|
|
346
|
+
target, value = st.target.id, st.value
|
|
347
|
+
if target is None or not isinstance(value, ast.Call):
|
|
348
|
+
continue
|
|
349
|
+
f = self._field(cls, m, target, value)
|
|
350
|
+
if f is not None:
|
|
351
|
+
m.fields[target] = f
|
|
352
|
+
else:
|
|
353
|
+
mg = self._manager(cls, target, value)
|
|
354
|
+
if mg is not None:
|
|
355
|
+
m.managers[target] = mg
|
|
356
|
+
|
|
357
|
+
# primary key
|
|
358
|
+
pk = next((f for f in m.fields.values() if f.pk), None)
|
|
359
|
+
if pk is None and concrete_parent is not None and not m.proxy:
|
|
360
|
+
link = next((f for f in m.fields.values() if f.parent_link and f.owner is m), None)
|
|
361
|
+
if link is None:
|
|
362
|
+
nm = concrete_parent.name.lower() + "_ptr"
|
|
363
|
+
link = Field(nm, nm + "_id", kind="o2o", pk=True, unique=True, target=concrete_parent, owner=m, parent_link=True)
|
|
364
|
+
m.fields = {nm: link, **m.fields}
|
|
365
|
+
link.pk = True
|
|
366
|
+
pk = link
|
|
367
|
+
if pk is None:
|
|
368
|
+
pk = Field("id", "id", type_name="AutoField", pk=True, unique=True, owner=m)
|
|
369
|
+
m.fields = {"id": pk, **m.fields}
|
|
370
|
+
m.pk = pk
|
|
371
|
+
|
|
372
|
+
# table name
|
|
373
|
+
if not m.proxy or not m.table:
|
|
374
|
+
if "db_table" in meta:
|
|
375
|
+
name = str_const(meta["db_table"])
|
|
376
|
+
if name is None:
|
|
377
|
+
inner = dotted(meta["db_table"])
|
|
378
|
+
got_v = p.resolve(cls.mod, inner) if inner else None
|
|
379
|
+
if got_v is not None and got_v[0] == "value":
|
|
380
|
+
name = str_const(got_v[2])
|
|
381
|
+
if name is None:
|
|
382
|
+
self.skipped["db_table is computed"] = self.skipped.get("db_table is computed", 0) + 1
|
|
383
|
+
m.table = ""
|
|
384
|
+
else:
|
|
385
|
+
m.table = name.strip('"')
|
|
386
|
+
else:
|
|
387
|
+
m.table = f"{app}_{cls.name.lower()}"
|
|
388
|
+
m.table_basis = "default"
|
|
389
|
+
if is_abstract:
|
|
390
|
+
m.table = "" # an abstract model has no table
|
|
391
|
+
ordering = meta.get("ordering")
|
|
392
|
+
oko, ov = const(ordering)
|
|
393
|
+
if oko and isinstance(ov, list):
|
|
394
|
+
m.ordering = [x for x in ov if isinstance(x, str)]
|
|
395
|
+
elif oko and isinstance(ov, str):
|
|
396
|
+
m.ordering = [ov]
|
|
397
|
+
if "objects" not in m.managers and not any(True for _ in m.managers):
|
|
398
|
+
m.managers["objects"] = Manager("objects")
|
|
399
|
+
m.managers.setdefault("_default_manager", next(iter(m.managers.values())))
|
|
400
|
+
m.managers.setdefault("_base_manager", Manager("_base_manager"))
|
|
401
|
+
|
|
402
|
+
self._building.discard(id(cls))
|
|
403
|
+
if not m.abstract and m.table:
|
|
404
|
+
self.models.append(m)
|
|
405
|
+
self.by_label[(m.app_label.lower(), m.name.lower())] = m
|
|
406
|
+
self.by_name.setdefault(m.name, []).append(m)
|
|
407
|
+
for mg in m.managers.values():
|
|
408
|
+
if mg.cls is not None:
|
|
409
|
+
self.manager_models.setdefault(id(mg.cls), []).append((m, mg))
|
|
410
|
+
for c in p.mro(mg.cls):
|
|
411
|
+
if c is not mg.cls:
|
|
412
|
+
self.manager_models.setdefault(id(c), []).append((m, mg))
|
|
413
|
+
if mg.qs_cls is not None:
|
|
414
|
+
for c in p.mro(mg.qs_cls):
|
|
415
|
+
self.qs_models.setdefault(id(c), []).append(m)
|
|
416
|
+
return m
|
|
417
|
+
|
|
418
|
+
def _perm_fields(self, m: Model) -> None:
|
|
419
|
+
for name, target in (("groups", ("auth", "group")), ("user_permissions", ("auth", "permission"))):
|
|
420
|
+
if name not in m.fields:
|
|
421
|
+
f = Field(name, "", kind="m2m", owner=m, target=self.by_label.get(target))
|
|
422
|
+
f.related_name = "user_set"
|
|
423
|
+
f.related_query_name = "user"
|
|
424
|
+
m.fields[name] = f
|
|
425
|
+
|
|
426
|
+
def _field_kind(self, cls: Cls, call: ast.Call) -> tuple[str, str] | None:
|
|
427
|
+
name = dotted(call.func)
|
|
428
|
+
if not name:
|
|
429
|
+
return None
|
|
430
|
+
last = name.split(".")[-1]
|
|
431
|
+
if last in NOT_FIELDS or not FIELD_NAME.search(last):
|
|
432
|
+
return None
|
|
433
|
+
chain = [last]
|
|
434
|
+
target = self.project.resolve_class(cls.mod, name)
|
|
435
|
+
if target is not None:
|
|
436
|
+
chain = [c.name for c in self.project.mro(target)] + [e.split(".")[-1] for e in self.project.external_bases(target)]
|
|
437
|
+
if not any(FIELD_NAME.search(x) for x in chain[1:]) and len(chain) > 1:
|
|
438
|
+
return None
|
|
439
|
+
kind = "col"
|
|
440
|
+
for x in chain:
|
|
441
|
+
if "ManyToMany" in x:
|
|
442
|
+
kind = "m2m"
|
|
443
|
+
break
|
|
444
|
+
if "OneToOne" in x:
|
|
445
|
+
kind = "o2o"
|
|
446
|
+
break
|
|
447
|
+
if x.endswith("ForeignKey") or x in ("ParentalKey", "ForeignObject"):
|
|
448
|
+
kind = "fk"
|
|
449
|
+
break
|
|
450
|
+
if kind != "col" and target is not None:
|
|
451
|
+
# a project class named like a relation that is really a plain column (an integer id to another silo)
|
|
452
|
+
ext = [e.split(".")[-1] for e in self.project.external_bases(target)]
|
|
453
|
+
if ext and not any(("ForeignKey" in e or "OneToOne" in e or "ManyToMany" in e or e in ("ForeignObject", "ParentalKey"))
|
|
454
|
+
for e in ext + [c.name for c in self.project.mro(target)[1:]]):
|
|
455
|
+
kind = "col"
|
|
456
|
+
base_type = next((x for x in chain if x in JSON_TYPES or x in ARRAY_TYPES or x.endswith("JSONField")), last)
|
|
457
|
+
return kind, base_type
|
|
458
|
+
|
|
459
|
+
def _field(self, cls: Cls, m: Model, name: str, call: ast.Call) -> Field | None:
|
|
460
|
+
fk = self._field_kind(cls, call)
|
|
461
|
+
if fk is None:
|
|
462
|
+
return None
|
|
463
|
+
kind, type_name = fk
|
|
464
|
+
|
|
465
|
+
def flag(key: str, default: bool = False) -> bool:
|
|
466
|
+
ok, v = const(kwarg(call, key))
|
|
467
|
+
return bool(v) if ok else default
|
|
468
|
+
|
|
469
|
+
col = str_const(kwarg(call, "db_column"))
|
|
470
|
+
f = Field(name, col or (name + "_id" if kind in ("fk", "o2o") else name), kind=kind, type_name=type_name,
|
|
471
|
+
null=flag("null"), pk=flag("primary_key"), unique=flag("unique") or flag("primary_key") or kind == "o2o",
|
|
472
|
+
db_index=flag("db_index", kind in ("fk", "o2o")), owner=m, line=call.lineno)
|
|
473
|
+
if kind == "m2m":
|
|
474
|
+
f.column = ""
|
|
475
|
+
f.m2m_table = str_const(kwarg(call, "db_table")) or ""
|
|
476
|
+
f.through_ref = (cls, kwarg(call, "through")) if kwarg(call, "through") is not None else None
|
|
477
|
+
if kind != "col":
|
|
478
|
+
ref = kwarg(call, "to") or (call.args[0] if call.args else None)
|
|
479
|
+
f.target_ref = (cls, ref)
|
|
480
|
+
f.related_name = str_const(kwarg(call, "related_name"))
|
|
481
|
+
f.related_query_name = str_const(kwarg(call, "related_query_name"))
|
|
482
|
+
f.to_field = str_const(kwarg(call, "to_field")) or ""
|
|
483
|
+
f.parent_link = flag("parent_link")
|
|
484
|
+
return f
|
|
485
|
+
|
|
486
|
+
def _manager(self, cls: Cls, name: str, call: ast.Call) -> Manager | None:
|
|
487
|
+
"""`objects = Manager()`, `objects = SomeManager.from_queryset(QS)()`, `objects = QS.as_manager()`."""
|
|
488
|
+
p = self.project
|
|
489
|
+
fn = call.func
|
|
490
|
+
seen = 0
|
|
491
|
+
mod = cls.mod
|
|
492
|
+
# an alias: `FooManager = BaseManager.from_queryset(FooQuerySet)` (here or in another module), then
|
|
493
|
+
# `objects = FooManager()` / `objects = managers.FooManager()`
|
|
494
|
+
while seen < 4:
|
|
495
|
+
dn = dotted(fn)
|
|
496
|
+
got = p.resolve(mod, dn) if dn else None
|
|
497
|
+
if got is not None and got[0] == "value" and isinstance(got[2], ast.Call):
|
|
498
|
+
inner = got[2]
|
|
499
|
+
if isinstance(inner.func, ast.Attribute) and inner.func.attr == "from_queryset":
|
|
500
|
+
return self._from_queryset(got[1], name, inner)
|
|
501
|
+
fn, mod = inner.func, got[1]
|
|
502
|
+
seen += 1
|
|
503
|
+
continue
|
|
504
|
+
break
|
|
505
|
+
if isinstance(fn, ast.Attribute) and fn.attr == "as_manager":
|
|
506
|
+
qs = p.resolve_class(mod, dotted(fn.value))
|
|
507
|
+
if qs is not None or (dotted(fn.value) or "").endswith("QuerySet"):
|
|
508
|
+
return Manager(name, None, qs)
|
|
509
|
+
return None
|
|
510
|
+
if isinstance(fn, ast.Call) and isinstance(fn.func, ast.Attribute) and fn.func.attr == "from_queryset":
|
|
511
|
+
return self._from_queryset(mod, name, fn)
|
|
512
|
+
dn = dotted(fn)
|
|
513
|
+
if not dn:
|
|
514
|
+
return None
|
|
515
|
+
target = p.resolve_class(mod, dn)
|
|
516
|
+
if target is not None:
|
|
517
|
+
names = [c.name for c in p.mro(target)] + p.external_bases(target)
|
|
518
|
+
if any(n.split(".")[-1].endswith("Manager") for n in names):
|
|
519
|
+
return Manager(name, target, self._qs_of_manager(target))
|
|
520
|
+
return None
|
|
521
|
+
return Manager(name) if dn.split(".")[-1].endswith("Manager") else None
|
|
522
|
+
|
|
523
|
+
def _from_queryset(self, mod: Mod, name: str, call: ast.Call) -> Manager | None:
|
|
524
|
+
p = self.project
|
|
525
|
+
qs = p.resolve_class(mod, dotted(call.args[0])) if call.args else None
|
|
526
|
+
base = p.resolve_class(mod, dotted(call.func.value))
|
|
527
|
+
return Manager(name, base, qs or (self._qs_of_manager(base) if base else None))
|
|
528
|
+
|
|
529
|
+
def _qs_of_manager(self, mgr: Cls) -> Cls | None:
|
|
530
|
+
"""The queryset class behind a manager class: a `from_queryset(...)` base, or what `get_queryset` builds."""
|
|
531
|
+
p = self.project
|
|
532
|
+
for c in p.mro(mgr):
|
|
533
|
+
for expr in c.base_exprs:
|
|
534
|
+
if isinstance(expr, ast.Call) and isinstance(expr.func, ast.Attribute) and expr.func.attr == "from_queryset" and expr.args:
|
|
535
|
+
qs = p.resolve_class(c.mod, dotted(expr.args[0]))
|
|
536
|
+
if qs is not None:
|
|
537
|
+
return qs
|
|
538
|
+
gq = c.methods.get("get_queryset")
|
|
539
|
+
if gq is not None:
|
|
540
|
+
for node in ast.walk(gq):
|
|
541
|
+
if isinstance(node, ast.Call):
|
|
542
|
+
dn = dotted(node.func)
|
|
543
|
+
if dn and dn.split(".")[-1].endswith(("QuerySet", "Queryset", "Query")) and node.keywords + node.args:
|
|
544
|
+
qs = p.resolve_class(c.mod, dn)
|
|
545
|
+
if qs is not None:
|
|
546
|
+
return qs
|
|
547
|
+
return None
|
|
548
|
+
|
|
549
|
+
# ---- relations -------------------------------------------------------------------------------------------
|
|
550
|
+
def model_ref(self, cls: Cls | None, ref, owner: Model | None = None) -> Model | None | str:
|
|
551
|
+
"""A relation target as written: a class name, "app.Model", "Model", "self", settings.AUTH_USER_MODEL."""
|
|
552
|
+
if ref is None:
|
|
553
|
+
return None
|
|
554
|
+
s = str_const(ref)
|
|
555
|
+
if s is None:
|
|
556
|
+
dn = dotted(ref)
|
|
557
|
+
if isinstance(ref, ast.Call) and dotted(ref.func) in ("get_user_model",):
|
|
558
|
+
return "AUTH_USER"
|
|
559
|
+
if dn is None:
|
|
560
|
+
return None
|
|
561
|
+
if dn.endswith("AUTH_USER_MODEL"):
|
|
562
|
+
return "AUTH_USER"
|
|
563
|
+
if cls is not None:
|
|
564
|
+
target = self.project.resolve_class(cls.mod, dn)
|
|
565
|
+
if target is not None:
|
|
566
|
+
return self.by_cls.get(id(target)) or self._model_for(target)
|
|
567
|
+
ext = self.project.external(cls.mod, dn)
|
|
568
|
+
if ext in BUILTIN_PATHS:
|
|
569
|
+
return self.by_label.get((BUILTIN_PATHS[ext][0], BUILTIN_PATHS[ext][1].lower()))
|
|
570
|
+
got = self.project.resolve(cls.mod, dn)
|
|
571
|
+
if got is not None and got[0] == "value":
|
|
572
|
+
return self.model_ref(self.project_cls_stub(got[1]), got[2], owner)
|
|
573
|
+
return self.unique(dn.split(".")[-1])
|
|
574
|
+
if s == "self":
|
|
575
|
+
return owner
|
|
576
|
+
if "." in s:
|
|
577
|
+
app, _, name = s.rpartition(".")
|
|
578
|
+
return self.by_label.get((app.split(".")[-1].lower(), name.lower()))
|
|
579
|
+
if owner is not None:
|
|
580
|
+
same = self.by_label.get((owner.app_label.lower(), s.lower()))
|
|
581
|
+
if same is not None:
|
|
582
|
+
return same
|
|
583
|
+
return self.unique(s)
|
|
584
|
+
|
|
585
|
+
@staticmethod
|
|
586
|
+
def project_cls_stub(mod: Mod):
|
|
587
|
+
class _S: # just enough of a Cls to resolve names in that module
|
|
588
|
+
pass
|
|
589
|
+
s = _S()
|
|
590
|
+
s.mod = mod
|
|
591
|
+
return s
|
|
592
|
+
|
|
593
|
+
def unique(self, name: str) -> Model | None:
|
|
594
|
+
found = [m for m in self.by_name.get(name, []) if not (m.cls and m.cls.mod.is_test)] or self.by_name.get(name, [])
|
|
595
|
+
return found[0] if len(found) == 1 else None
|
|
596
|
+
|
|
597
|
+
def _resolve_relations(self, m: Model) -> None:
|
|
598
|
+
for f in m.fields.values():
|
|
599
|
+
if not f.is_rel or f.target is not None or (f.owner is not None and f.owner is not m):
|
|
600
|
+
continue
|
|
601
|
+
if isinstance(f.target_ref, tuple):
|
|
602
|
+
cls, ref = f.target_ref
|
|
603
|
+
got = self.model_ref(cls, ref, m)
|
|
604
|
+
if got == "AUTH_USER":
|
|
605
|
+
f.target_ref = "AUTH_USER"
|
|
606
|
+
elif isinstance(got, Model):
|
|
607
|
+
f.target = got
|
|
608
|
+
if f.kind == "m2m":
|
|
609
|
+
if isinstance(f.through_ref, tuple):
|
|
610
|
+
cls, ref = f.through_ref
|
|
611
|
+
got = self.model_ref(cls, ref, m)
|
|
612
|
+
f.through = got if isinstance(got, Model) else None
|
|
613
|
+
|
|
614
|
+
def _m2m_shape(self, m: Model, f: Field) -> None:
|
|
615
|
+
"""Table and the two columns of a many-to-many: the `through` model's, or Django's automatic table."""
|
|
616
|
+
if f.m2m_from or f.target is None:
|
|
617
|
+
return
|
|
618
|
+
if f.through is not None:
|
|
619
|
+
t = f.through
|
|
620
|
+
f.m2m_table = t.table
|
|
621
|
+
src = next((x for x in t.fields.values() if x.kind == "fk" and x.target is m), None)
|
|
622
|
+
dst = next((x for x in t.fields.values() if x.kind == "fk" and x.target is f.target and x is not src), None)
|
|
623
|
+
if src is None or dst is None:
|
|
624
|
+
# the far side may be a parent of the declared target (or the reverse): fall back on names
|
|
625
|
+
src = src or next((x for x in t.fields.values() if x.kind == "fk" and x.target in m.parents), None)
|
|
626
|
+
f.m2m_from, f.m2m_to = (src.column if src else ""), (dst.column if dst else "")
|
|
627
|
+
return
|
|
628
|
+
if isinstance(f.through_ref, tuple):
|
|
629
|
+
return # an explicit through model we could not resolve: no guess
|
|
630
|
+
if not f.m2m_table:
|
|
631
|
+
f.m2m_table = f"{m.table}_{f.name}"
|
|
632
|
+
a, b = m.name.lower(), f.target.name.lower()
|
|
633
|
+
f.m2m_from, f.m2m_to = (f"from_{a}_id", f"to_{b}_id") if f.target is m else (f"{a}_id", f"{b}_id")
|
|
634
|
+
t = Model(cls=None, name=f"{m.name}_{f.name}", app_label=m.app_label, table=f.m2m_table, where=m.where)
|
|
635
|
+
t.fields["id"] = Field("id", "id", type_name="AutoField", pk=True, unique=True, owner=t)
|
|
636
|
+
t.fields[f.m2m_from[:-3]] = Field(f.m2m_from[:-3], f.m2m_from, kind="fk", target=m, owner=t, db_index=True)
|
|
637
|
+
t.fields[f.m2m_to[:-3]] = Field(f.m2m_to[:-3], f.m2m_to, kind="fk", target=f.target, owner=t, db_index=True)
|
|
638
|
+
t.pk = t.fields["id"]
|
|
639
|
+
t.managers["objects"] = Manager("objects")
|
|
640
|
+
t.managers["_default_manager"] = t.managers["objects"]
|
|
641
|
+
f.auto_through = t
|
|
642
|
+
|
|
643
|
+
def _reverse(self, m: Model) -> None:
|
|
644
|
+
for f in list(m.fields.values()):
|
|
645
|
+
if not f.is_rel or (f.owner is not None and f.owner is not m):
|
|
646
|
+
continue
|
|
647
|
+
if f.target is None and f.target_ref == "AUTH_USER":
|
|
648
|
+
continue # filled in once the user model is known
|
|
649
|
+
if f.target is None:
|
|
650
|
+
continue
|
|
651
|
+
if f.kind == "m2m":
|
|
652
|
+
self._m2m_shape(m, f)
|
|
653
|
+
self._add_reverse(m, f)
|
|
654
|
+
|
|
655
|
+
def _add_reverse(self, m: Model, f: Field) -> None:
|
|
656
|
+
target = f.target
|
|
657
|
+
if target is None:
|
|
658
|
+
return
|
|
659
|
+
subst = {"class": m.name.lower(), "app_label": m.app_label.lower(), "model_name": m.name.lower()}
|
|
660
|
+
rn = f.related_name
|
|
661
|
+
if rn:
|
|
662
|
+
try:
|
|
663
|
+
rn = rn % subst
|
|
664
|
+
except (KeyError, ValueError, TypeError):
|
|
665
|
+
pass
|
|
666
|
+
kind = {"fk": "rev_fk", "o2o": "rev_o2o", "m2m": "rev_m2m"}[f.kind]
|
|
667
|
+
rel = Rel(kind, m, f)
|
|
668
|
+
hidden = bool(rn) and rn.endswith("+")
|
|
669
|
+
if not hidden:
|
|
670
|
+
accessor = rn or (m.name.lower() if f.kind == "o2o" else m.name.lower() + "_set")
|
|
671
|
+
target.reverse.setdefault(accessor, rel)
|
|
672
|
+
qn = f.related_query_name
|
|
673
|
+
if qn:
|
|
674
|
+
try:
|
|
675
|
+
qn = qn % subst
|
|
676
|
+
except (KeyError, ValueError, TypeError):
|
|
677
|
+
pass
|
|
678
|
+
qn = qn or (rn if rn and not hidden else m.name.lower())
|
|
679
|
+
target.reverse_query.setdefault(qn, rel)
|
|
680
|
+
|
|
681
|
+
def _find_auth_user(self) -> None:
|
|
682
|
+
"""AUTH_USER_MODEL = "app.Model" in a settings module; else the one model built on AbstractBaseUser/AbstractUser."""
|
|
683
|
+
label = None
|
|
684
|
+
for mod in self.project.mods.values():
|
|
685
|
+
if mod.is_test:
|
|
686
|
+
continue
|
|
687
|
+
v = mod.assigns.get("AUTH_USER_MODEL")
|
|
688
|
+
s = str_const(v) if v is not None else None
|
|
689
|
+
if s and "." in s:
|
|
690
|
+
label = s
|
|
691
|
+
break
|
|
692
|
+
user = None
|
|
693
|
+
if label:
|
|
694
|
+
app, _, name = label.rpartition(".")
|
|
695
|
+
user = self.by_label.get((app.lower(), name.lower()))
|
|
696
|
+
if user is None:
|
|
697
|
+
cands = [m for m in self.models if m.cls is not None and not m.cls.mod.is_test and any(
|
|
698
|
+
e.split(".")[-1] in ("AbstractUser", "AbstractBaseUser") for e in self.project.external_bases(m.cls))]
|
|
699
|
+
if len(cands) == 1:
|
|
700
|
+
user = cands[0]
|
|
701
|
+
if user is None and not label:
|
|
702
|
+
user = self.by_label.get(("auth", "user"))
|
|
703
|
+
self.auth_user = user
|
|
704
|
+
if user is None:
|
|
705
|
+
return
|
|
706
|
+
for m in list(self.models) + [b for b in self.by_label.values() if b.builtin]:
|
|
707
|
+
for f in m.fields.values():
|
|
708
|
+
if f.target_ref == "AUTH_USER" and f.target is None and (f.owner is None or f.owner is m):
|
|
709
|
+
f.target = user
|
|
710
|
+
if f.kind == "m2m":
|
|
711
|
+
self._m2m_shape(m, f)
|
|
712
|
+
self._add_reverse(m, f)
|
|
713
|
+
|
|
714
|
+
# ---- indexes and tables ----------------------------------------------------------------------------------
|
|
715
|
+
def _cols(self, m: Model, names) -> list[str]:
|
|
716
|
+
out = []
|
|
717
|
+
for n in names or []:
|
|
718
|
+
if not isinstance(n, str):
|
|
719
|
+
return []
|
|
720
|
+
f = m.field_by_attname(n.lstrip("-"))
|
|
721
|
+
if f is None or f.kind == "m2m":
|
|
722
|
+
return []
|
|
723
|
+
out.append(f.column)
|
|
724
|
+
return out
|
|
725
|
+
|
|
726
|
+
def _indexes(self, m: Model) -> None:
|
|
727
|
+
if m.cls is None or m.proxy:
|
|
728
|
+
return
|
|
729
|
+
idx: list[dict] = []
|
|
730
|
+
for f in m.columns():
|
|
731
|
+
if f.pk:
|
|
732
|
+
idx.append({"name": "", "columns": [f.column], "unique": True, "primary": True})
|
|
733
|
+
elif f.unique:
|
|
734
|
+
idx.append({"name": "", "columns": [f.column], "unique": True})
|
|
735
|
+
elif f.db_index:
|
|
736
|
+
idx.append({"name": "", "columns": [f.column], "unique": False})
|
|
737
|
+
metas = [self._meta(m.cls)]
|
|
738
|
+
if not metas[0]:
|
|
739
|
+
for c in self.project.mro(m.cls)[1:]:
|
|
740
|
+
bm = self.by_cls.get(id(c))
|
|
741
|
+
if bm is not None and bm.abstract and self._meta(c):
|
|
742
|
+
metas = [self._meta(c)]
|
|
743
|
+
break
|
|
744
|
+
meta = metas[0]
|
|
745
|
+
for key, unique in (("unique_together", True), ("index_together", False)):
|
|
746
|
+
ok, v = const(meta.get(key))
|
|
747
|
+
if ok and isinstance(v, list) and v:
|
|
748
|
+
groups = v if isinstance(v[0], list) else [v]
|
|
749
|
+
for g in groups:
|
|
750
|
+
cols = self._cols(m, g)
|
|
751
|
+
if cols:
|
|
752
|
+
idx.append({"name": "", "columns": cols, "unique": unique})
|
|
753
|
+
for key in ("indexes", "constraints"):
|
|
754
|
+
node = meta.get(key)
|
|
755
|
+
if isinstance(node, ast.BinOp): # `Parent.Meta.indexes + [...]`
|
|
756
|
+
node = node.right
|
|
757
|
+
if not isinstance(node, (ast.List, ast.Tuple)):
|
|
758
|
+
continue
|
|
759
|
+
for el in node.elts:
|
|
760
|
+
if not isinstance(el, ast.Call):
|
|
761
|
+
continue
|
|
762
|
+
kind = (dotted(el.func) or "").split(".")[-1]
|
|
763
|
+
ok, fields = const(kwarg(el, "fields"))
|
|
764
|
+
cols = self._cols(m, fields) if ok and isinstance(fields, list) else []
|
|
765
|
+
if not cols:
|
|
766
|
+
continue
|
|
767
|
+
if key == "constraints" and "Unique" not in kind:
|
|
768
|
+
continue
|
|
769
|
+
entry = {"name": str_const(kwarg(el, "name")) or "", "columns": cols,
|
|
770
|
+
"unique": key == "constraints" or kind == "UniqueConstraint"}
|
|
771
|
+
if kwarg(el, "condition") is not None:
|
|
772
|
+
entry["partial"] = True
|
|
773
|
+
if kind not in ("Index", "UniqueConstraint"):
|
|
774
|
+
entry["method"] = kind
|
|
775
|
+
idx.append(entry)
|
|
776
|
+
m.indexes = idx
|
|
777
|
+
|
|
778
|
+
def tables(self) -> list:
|
|
779
|
+
out = []
|
|
780
|
+
seen: set[str] = set()
|
|
781
|
+
for m in self.models:
|
|
782
|
+
if m.cls is None or m.proxy or not m.table or m.table in seen:
|
|
783
|
+
continue
|
|
784
|
+
seen.add(m.table)
|
|
785
|
+
t = OrmTable(name=m.table, defined_at=[m.where], name_basis="orm")
|
|
786
|
+
t.columns = [{"name": f.column, "type": f.type_name or ("ForeignKey" if f.kind != "col" else "")} for f in m.columns()]
|
|
787
|
+
t.indexes = list(m.indexes)
|
|
788
|
+
t.primary_key = m.pk.column if m.pk is not None and (m.pk.owner is None or m.pk.owner is m) else ""
|
|
789
|
+
t.orm = {"library": "django", "model": m.label}
|
|
790
|
+
out.append(t)
|
|
791
|
+
for m in self.models:
|
|
792
|
+
if m.cls is None:
|
|
793
|
+
continue
|
|
794
|
+
for f in m.fields.values():
|
|
795
|
+
if f.kind == "m2m" and f.through is None and f.m2m_table and f.m2m_from and f.m2m_table not in seen \
|
|
796
|
+
and (f.owner is None or f.owner is m) and not isinstance(f.through_ref, tuple):
|
|
797
|
+
seen.add(f.m2m_table)
|
|
798
|
+
t = OrmTable(name=f.m2m_table, defined_at=[f"{m.cls.mod.rel}:{f.line or m.cls.node.lineno}"], name_basis="orm")
|
|
799
|
+
t.columns = [{"name": "id", "type": "AutoField"}, {"name": f.m2m_from, "type": "ForeignKey"},
|
|
800
|
+
{"name": f.m2m_to, "type": "ForeignKey"}]
|
|
801
|
+
t.indexes = [{"name": "", "columns": ["id"], "unique": True, "primary": True},
|
|
802
|
+
{"name": "", "columns": [f.m2m_from, f.m2m_to], "unique": True},
|
|
803
|
+
{"name": "", "columns": [f.m2m_from], "unique": False},
|
|
804
|
+
{"name": "", "columns": [f.m2m_to], "unique": False}]
|
|
805
|
+
t.primary_key = "id"
|
|
806
|
+
t.orm = {"library": "django", "model": f"{m.label}.{f.name} (automatic many-to-many table)"}
|
|
807
|
+
out.append(t)
|
|
808
|
+
return out
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
@dataclass
|
|
812
|
+
class OrmTable(Table):
|
|
813
|
+
indexes: list[dict] = field(default_factory=list)
|
|
814
|
+
orm: dict = field(default_factory=dict)
|