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,557 @@
|
|
|
1
|
+
"""Python ORM discovery: the shared part.
|
|
2
|
+
|
|
3
|
+
Database access through an ORM never shows up as SQL text, so the string-based extractor in python.py cannot see
|
|
4
|
+
it. This module indexes a project's Python modules once (imports, classes, functions) with the standard `ast`
|
|
5
|
+
parser, hands that index to the per-library translators (orm_django.py, orm_sqlalchemy.py) and returns their
|
|
6
|
+
sites: RawSite records with `resolution = "orm"` and an `orm` object, whose SQL is synthesised from the call and
|
|
7
|
+
the library's model metadata.
|
|
8
|
+
|
|
9
|
+
Rules every translator follows: real tables and columns only (never a guess), a «run-time part» marker for
|
|
10
|
+
anything decided when the program runs, one site per statement the ORM sends, and a count of every call seen
|
|
11
|
+
and every call not translated with the reason, reported in `summary.orm_calls`.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import ast
|
|
17
|
+
import re
|
|
18
|
+
import warnings
|
|
19
|
+
from collections import Counter
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
from .base import RawSite, is_test_path, trim
|
|
23
|
+
|
|
24
|
+
# ---- settings (every limit is a setting: `[discover]` in codecop.toml) ------------------------------------------
|
|
25
|
+
DEFAULTS = {
|
|
26
|
+
"orm": True, # translate ORM calls at all
|
|
27
|
+
"orm_helper_depth": 6, # helper functions followed when a queryset or statement is built through calls
|
|
28
|
+
"orm_marker_chars": 80, # longest source expression kept inside one «run-time part»
|
|
29
|
+
"orm_max_sql_chars": 60_000, # a synthesised statement longer than this is not emitted (counted instead)
|
|
30
|
+
"orm_max_relation_depth": 12, # relation hops followed in one lookup path (a__b__c ...)
|
|
31
|
+
"orm_lazy_loads": True, # emit sites for lazy relation access (the N+1 shape)
|
|
32
|
+
"orm_reexport_depth": 12, # `from x import y` hops followed to find where a name is defined
|
|
33
|
+
"orm_tests": False, # also read test files (several times the work and memory; the rank stage skips test sites)
|
|
34
|
+
}
|
|
35
|
+
SETTINGS = dict(DEFAULTS)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def apply_settings(settings: dict | None) -> None:
|
|
39
|
+
SETTINGS.clear()
|
|
40
|
+
SETTINGS.update(DEFAULTS)
|
|
41
|
+
for k in DEFAULTS:
|
|
42
|
+
if settings and k in settings:
|
|
43
|
+
SETTINGS[k] = type(DEFAULTS[k])(settings[k])
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# ---- small helpers ---------------------------------------------------------------------------------------------
|
|
47
|
+
def dotted(node: ast.AST | None) -> str | None:
|
|
48
|
+
"""`a.b.c` for a Name / Attribute chain, else None."""
|
|
49
|
+
parts = []
|
|
50
|
+
while isinstance(node, ast.Attribute):
|
|
51
|
+
parts.append(node.attr)
|
|
52
|
+
node = node.value
|
|
53
|
+
if isinstance(node, ast.Name):
|
|
54
|
+
parts.append(node.id)
|
|
55
|
+
return ".".join(reversed(parts))
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
_SRC: dict[int, tuple] = {} # node id -> (node, text): the node is held so its id is never reused
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def src(node: ast.AST) -> str:
|
|
63
|
+
hit = _SRC.get(id(node))
|
|
64
|
+
if hit is not None and hit[0] is node:
|
|
65
|
+
return hit[1]
|
|
66
|
+
try:
|
|
67
|
+
text = ast.unparse(node)
|
|
68
|
+
except Exception: # a node the unparser cannot write is simply not shown
|
|
69
|
+
text = "?"
|
|
70
|
+
_SRC[id(node)] = (node, text)
|
|
71
|
+
return text
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def marker(text: str) -> str:
|
|
75
|
+
"""A «run-time part». The text is the source expression, whitespace-normalised so formatting never moves an id."""
|
|
76
|
+
text = " ".join(str(text).split()).replace("«", "<").replace("»", ">")
|
|
77
|
+
# Python source inside a run-time part must not read as SQL of some engine: `{name: Type}` is a ClickHouse
|
|
78
|
+
# parameter and `::` a Postgres cast to the engine guess, which looks at the whole text
|
|
79
|
+
text = text.replace("{", "(").replace("}", ")").replace("::", ": :")
|
|
80
|
+
n = SETTINGS["orm_marker_chars"]
|
|
81
|
+
if len(text) > n:
|
|
82
|
+
text = text[: n - 1] + "…"
|
|
83
|
+
return "«" + text + "»"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def unmark(sql: str) -> str:
|
|
87
|
+
"""The same text with its run-time parts written bare, for use inside another run-time part."""
|
|
88
|
+
return sql.replace("«", "").replace("»", "")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def sql_literal(value) -> str | None:
|
|
92
|
+
if value is None:
|
|
93
|
+
return "NULL"
|
|
94
|
+
if value is True:
|
|
95
|
+
return "TRUE"
|
|
96
|
+
if value is False:
|
|
97
|
+
return "FALSE"
|
|
98
|
+
if isinstance(value, (int, float)):
|
|
99
|
+
return repr(value)
|
|
100
|
+
if isinstance(value, str):
|
|
101
|
+
return "'" + value.replace("'", "''") + "'"
|
|
102
|
+
return None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def const(node: ast.AST | None):
|
|
106
|
+
"""(True, value) for a literal constant (including negative numbers and tuples/lists of constants)."""
|
|
107
|
+
if isinstance(node, ast.Constant) and not isinstance(node.value, (bytes, type(Ellipsis))):
|
|
108
|
+
return True, node.value
|
|
109
|
+
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub) and isinstance(node.operand, ast.Constant) \
|
|
110
|
+
and isinstance(node.operand.value, (int, float)):
|
|
111
|
+
return True, -node.operand.value
|
|
112
|
+
if isinstance(node, (ast.Tuple, ast.List, ast.Set)):
|
|
113
|
+
vals = [const(e) for e in node.elts]
|
|
114
|
+
if all(ok for ok, _ in vals):
|
|
115
|
+
return True, [v for _, v in vals]
|
|
116
|
+
return False, None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def str_const(node: ast.AST | None) -> str | None:
|
|
120
|
+
return node.value if isinstance(node, ast.Constant) and isinstance(node.value, str) else None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def kwarg(call: ast.Call, name: str) -> ast.AST | None:
|
|
124
|
+
for k in call.keywords:
|
|
125
|
+
if k.arg == name:
|
|
126
|
+
return k.value
|
|
127
|
+
return None
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# ---- the project index -----------------------------------------------------------------------------------------
|
|
131
|
+
class Cls:
|
|
132
|
+
__slots__ = ("mod", "name", "node", "bases", "base_exprs", "assigns", "annots", "methods", "inner", "outer", "qual")
|
|
133
|
+
|
|
134
|
+
def __init__(self, mod: "Mod", node: ast.ClassDef, outer: "Cls | None" = None):
|
|
135
|
+
self.mod, self.name, self.node, self.outer = mod, node.name, node, outer
|
|
136
|
+
self.qual = (outer.qual + "." if outer else "") + node.name
|
|
137
|
+
self.base_exprs = list(node.bases)
|
|
138
|
+
self.bases = [dotted(b) or dotted(b.value) if isinstance(b, ast.Subscript) else dotted(b) for b in node.bases]
|
|
139
|
+
self.assigns: dict[str, ast.AST] = {}
|
|
140
|
+
self.annots: dict[str, ast.AST] = {}
|
|
141
|
+
self.methods: dict[str, ast.FunctionDef] = {}
|
|
142
|
+
self.inner: dict[str, Cls] = {}
|
|
143
|
+
for st in node.body:
|
|
144
|
+
if isinstance(st, ast.Assign):
|
|
145
|
+
for t in st.targets:
|
|
146
|
+
if isinstance(t, ast.Name):
|
|
147
|
+
self.assigns[t.id] = st.value
|
|
148
|
+
elif isinstance(st, ast.AnnAssign) and isinstance(st.target, ast.Name):
|
|
149
|
+
self.annots[st.target.id] = st.annotation
|
|
150
|
+
if st.value is not None:
|
|
151
|
+
self.assigns[st.target.id] = st.value
|
|
152
|
+
elif isinstance(st, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
153
|
+
self.methods.setdefault(st.name, st)
|
|
154
|
+
elif isinstance(st, ast.ClassDef):
|
|
155
|
+
self.inner[st.name] = Cls(mod, st, self)
|
|
156
|
+
|
|
157
|
+
def __repr__(self) -> str:
|
|
158
|
+
return f"<Cls {self.mod.rel}:{self.qual}>"
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class Mod:
|
|
162
|
+
__slots__ = ("rel", "parts", "tree", "imports", "stars", "classes", "funcs", "assigns", "is_test", "is_pkg", "text")
|
|
163
|
+
|
|
164
|
+
def __init__(self, rel: str, tree: ast.Module, text: str):
|
|
165
|
+
self.rel, self.tree, self.text = rel, tree, text
|
|
166
|
+
p = rel[:-3].split("/")
|
|
167
|
+
self.is_pkg = p[-1] == "__init__"
|
|
168
|
+
if self.is_pkg:
|
|
169
|
+
p = p[:-1]
|
|
170
|
+
self.parts = tuple(p)
|
|
171
|
+
self.imports: dict[str, tuple[int, str, str | None]] = {} # local name -> (relative level, module, attribute)
|
|
172
|
+
self.stars: list[tuple[int, str]] = []
|
|
173
|
+
self.classes: dict[str, Cls] = {}
|
|
174
|
+
self.funcs: dict[str, ast.FunctionDef] = {}
|
|
175
|
+
self.assigns: dict[str, ast.AST] = {}
|
|
176
|
+
self.is_test = is_test_path(rel)
|
|
177
|
+
self._index()
|
|
178
|
+
|
|
179
|
+
def _index(self) -> None:
|
|
180
|
+
for st in self.tree.body:
|
|
181
|
+
self._top(st)
|
|
182
|
+
# imports inside functions and `if TYPE_CHECKING:` blocks name the same things
|
|
183
|
+
for node in _statements(self.tree.body):
|
|
184
|
+
if isinstance(node, ast.Import):
|
|
185
|
+
for a in node.names:
|
|
186
|
+
if a.asname:
|
|
187
|
+
self.imports.setdefault(a.asname, (0, a.name, None))
|
|
188
|
+
else:
|
|
189
|
+
self.imports.setdefault(a.name.split(".")[0], (0, a.name.split(".")[0], None))
|
|
190
|
+
elif isinstance(node, ast.ImportFrom):
|
|
191
|
+
for a in node.names:
|
|
192
|
+
if a.name == "*":
|
|
193
|
+
self.stars.append((node.level, node.module or ""))
|
|
194
|
+
else:
|
|
195
|
+
self.imports.setdefault(a.asname or a.name, (node.level, node.module or "", a.name))
|
|
196
|
+
|
|
197
|
+
def _top(self, st: ast.stmt) -> None:
|
|
198
|
+
if isinstance(st, ast.ClassDef):
|
|
199
|
+
self.classes.setdefault(st.name, Cls(self, st))
|
|
200
|
+
elif isinstance(st, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
201
|
+
self.funcs.setdefault(st.name, st)
|
|
202
|
+
elif isinstance(st, ast.Assign):
|
|
203
|
+
for t in st.targets:
|
|
204
|
+
if isinstance(t, ast.Name):
|
|
205
|
+
self.assigns[t.id] = st.value
|
|
206
|
+
elif isinstance(st, ast.AnnAssign) and isinstance(st.target, ast.Name) and st.value is not None:
|
|
207
|
+
self.assigns[st.target.id] = st.value
|
|
208
|
+
elif isinstance(st, (ast.If, ast.Try)):
|
|
209
|
+
for sub in list(st.body) + list(getattr(st, "orelse", [])):
|
|
210
|
+
self._top(sub)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _statements(body: list):
|
|
214
|
+
"""Every statement of a module, at any depth (function and class bodies, branches), without visiting expressions."""
|
|
215
|
+
stack = list(reversed(body))
|
|
216
|
+
while stack:
|
|
217
|
+
st = stack.pop()
|
|
218
|
+
yield st
|
|
219
|
+
for name in ("body", "orelse", "finalbody"):
|
|
220
|
+
sub = getattr(st, name, None)
|
|
221
|
+
if isinstance(sub, list):
|
|
222
|
+
stack.extend(reversed(sub))
|
|
223
|
+
for h in getattr(st, "handlers", ()):
|
|
224
|
+
stack.extend(reversed(h.body))
|
|
225
|
+
for c in getattr(st, "cases", ()):
|
|
226
|
+
stack.extend(reversed(c.body))
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class Project:
|
|
230
|
+
"""Every parsed module, and name resolution across them."""
|
|
231
|
+
|
|
232
|
+
def __init__(self) -> None:
|
|
233
|
+
self.mods: dict[str, Mod] = {}
|
|
234
|
+
self.by_suffix: dict[tuple[str, ...], list[Mod]] = {}
|
|
235
|
+
self.unparsed: list[str] = []
|
|
236
|
+
self._mro: dict[int, list[Cls]] = {}
|
|
237
|
+
self._ext: dict[int, list[str]] = {}
|
|
238
|
+
|
|
239
|
+
def add(self, rel: str, text: str) -> None:
|
|
240
|
+
try:
|
|
241
|
+
with warnings.catch_warnings():
|
|
242
|
+
warnings.simplefilter("ignore")
|
|
243
|
+
tree = ast.parse(text)
|
|
244
|
+
except (SyntaxError, ValueError, RecursionError, MemoryError):
|
|
245
|
+
self.unparsed.append(rel)
|
|
246
|
+
return
|
|
247
|
+
mod = Mod(rel, tree, text)
|
|
248
|
+
self.mods[rel] = mod
|
|
249
|
+
for i in range(len(mod.parts)):
|
|
250
|
+
self.by_suffix.setdefault(mod.parts[i:], []).append(mod)
|
|
251
|
+
|
|
252
|
+
def module(self, name: str | tuple, near: Mod | None = None) -> Mod | None:
|
|
253
|
+
parts = tuple(name.split(".")) if isinstance(name, str) else tuple(name)
|
|
254
|
+
if not parts or parts == ("",):
|
|
255
|
+
return None
|
|
256
|
+
found = self.by_suffix.get(parts)
|
|
257
|
+
if not found:
|
|
258
|
+
return None
|
|
259
|
+
# `import sqlalchemy` is not the project's `utils/sqlalchemy.py`: a module answers to a dotted name only
|
|
260
|
+
# from a source root, that is when the directory above the name is not itself a package
|
|
261
|
+
found = [m for m in found if m.parts == parts or not self._is_package(m.parts[: len(m.parts) - len(parts)])]
|
|
262
|
+
if not found:
|
|
263
|
+
return None
|
|
264
|
+
if len(found) == 1:
|
|
265
|
+
return found[0]
|
|
266
|
+
# several roots hold a module by this name: the one that is the whole path, then the one nearest
|
|
267
|
+
exact = [m for m in found if m.parts == parts]
|
|
268
|
+
if len(exact) == 1:
|
|
269
|
+
return exact[0]
|
|
270
|
+
if near is not None:
|
|
271
|
+
def shared(m: Mod) -> int:
|
|
272
|
+
n = 0
|
|
273
|
+
for a, b in zip(m.rel.split("/"), near.rel.split("/")):
|
|
274
|
+
if a != b:
|
|
275
|
+
break
|
|
276
|
+
n += 1
|
|
277
|
+
return n
|
|
278
|
+
best = sorted(found, key=lambda m: (-shared(m), len(m.parts), m.rel))
|
|
279
|
+
if shared(best[0]) > shared(best[1]):
|
|
280
|
+
return best[0]
|
|
281
|
+
apps = [m for m in found if not m.is_test]
|
|
282
|
+
if len(apps) == 1:
|
|
283
|
+
return apps[0]
|
|
284
|
+
shortest = sorted(found, key=lambda m: (len(m.parts), m.rel))
|
|
285
|
+
return shortest[0] if len(shortest[0].parts) < len(shortest[1].parts) else None
|
|
286
|
+
|
|
287
|
+
def _is_package(self, parts: tuple) -> bool:
|
|
288
|
+
return bool(parts) and "/".join(parts) + "/__init__.py" in self.mods
|
|
289
|
+
|
|
290
|
+
def _import_target(self, mod: Mod, level: int, module: str) -> tuple[str, ...] | None:
|
|
291
|
+
if level == 0:
|
|
292
|
+
return tuple(module.split(".")) if module else None
|
|
293
|
+
base = mod.parts if mod.is_pkg else mod.parts[:-1]
|
|
294
|
+
if level > 1:
|
|
295
|
+
base = base[: len(base) - (level - 1)] if level - 1 <= len(base) else ()
|
|
296
|
+
return base + (tuple(module.split(".")) if module else ())
|
|
297
|
+
|
|
298
|
+
def resolve(self, mod: Mod, name: str, depth: int = 0):
|
|
299
|
+
"""What a dotted name means in a module: ("class", Cls) | ("func", Mod, def) | ("module", Mod) |
|
|
300
|
+
("value", Mod, expr) | ("external", "pkg.mod.Name") | None."""
|
|
301
|
+
if depth > SETTINGS["orm_reexport_depth"] or not name:
|
|
302
|
+
return None
|
|
303
|
+
head, _, rest = name.partition(".")
|
|
304
|
+
got = None
|
|
305
|
+
if head in mod.classes:
|
|
306
|
+
got = ("class", mod.classes[head])
|
|
307
|
+
elif head in mod.funcs:
|
|
308
|
+
got = ("func", mod, mod.funcs[head])
|
|
309
|
+
elif head in mod.imports:
|
|
310
|
+
level, module, attr = mod.imports[head]
|
|
311
|
+
target = self._import_target(mod, level, module)
|
|
312
|
+
if attr is None:
|
|
313
|
+
m = self.module(target, mod) if target else None
|
|
314
|
+
got = ("module", m) if m is not None else ("external", module)
|
|
315
|
+
else:
|
|
316
|
+
sub = self.module(target + (attr,), mod) if target else None
|
|
317
|
+
m = self.module(target, mod) if target else None
|
|
318
|
+
if m is not None and (attr in m.classes or attr in m.funcs or attr in m.imports or attr in m.assigns):
|
|
319
|
+
got = self.resolve(m, attr, depth + 1)
|
|
320
|
+
elif sub is not None:
|
|
321
|
+
got = ("module", sub)
|
|
322
|
+
elif m is not None:
|
|
323
|
+
got = self._star(m, attr, depth + 1)
|
|
324
|
+
else:
|
|
325
|
+
got = ("external", ".".join(target or ()) + "." + attr if level == 0 else None) if level == 0 else None
|
|
326
|
+
elif head in mod.assigns:
|
|
327
|
+
got = ("value", mod, mod.assigns[head])
|
|
328
|
+
else:
|
|
329
|
+
got = self._star(mod, head, depth + 1)
|
|
330
|
+
if not rest or got is None:
|
|
331
|
+
return got
|
|
332
|
+
if got[0] == "module":
|
|
333
|
+
m = got[1]
|
|
334
|
+
sub = self.module(m.parts + (rest.split(".")[0],), m)
|
|
335
|
+
if rest.split(".")[0] not in m.classes and rest.split(".")[0] not in m.imports and sub is not None:
|
|
336
|
+
tail = rest.partition(".")[2]
|
|
337
|
+
return self.resolve_in(sub, tail, depth + 1) if tail else ("module", sub)
|
|
338
|
+
return self.resolve(m, rest, depth + 1)
|
|
339
|
+
if got[0] == "class":
|
|
340
|
+
cls = got[1]
|
|
341
|
+
for part in rest.split("."):
|
|
342
|
+
cls = cls.inner.get(part) if cls is not None else None
|
|
343
|
+
return ("class", cls) if cls is not None else None
|
|
344
|
+
if got[0] == "external":
|
|
345
|
+
return ("external", (got[1] or "") + "." + rest)
|
|
346
|
+
if got[0] == "value":
|
|
347
|
+
# `X = SomeClass` aliases, then the attribute
|
|
348
|
+
inner = dotted(got[2])
|
|
349
|
+
if inner and inner != name:
|
|
350
|
+
return self.resolve(got[1], inner + "." + rest, depth + 1)
|
|
351
|
+
return None
|
|
352
|
+
|
|
353
|
+
def resolve_in(self, mod: Mod, name: str, depth: int = 0):
|
|
354
|
+
return self.resolve(mod, name, depth)
|
|
355
|
+
|
|
356
|
+
def _star(self, mod: Mod, name: str, depth: int):
|
|
357
|
+
for level, module in mod.stars:
|
|
358
|
+
target = self._import_target(mod, level, module)
|
|
359
|
+
m = self.module(target, mod) if target else None
|
|
360
|
+
if m is not None and m is not mod and depth <= SETTINGS["orm_reexport_depth"]:
|
|
361
|
+
if name in m.classes or name in m.funcs or name in m.imports or name in m.assigns or m.stars:
|
|
362
|
+
got = self.resolve(m, name, depth + 1)
|
|
363
|
+
if got is not None:
|
|
364
|
+
return got
|
|
365
|
+
return None
|
|
366
|
+
|
|
367
|
+
def resolve_class(self, mod: Mod, name: str | None) -> Cls | None:
|
|
368
|
+
got = self.resolve(mod, name) if name else None
|
|
369
|
+
seen = 0
|
|
370
|
+
while got is not None and got[0] == "value" and seen < 5: # `Base = Other` aliases
|
|
371
|
+
inner = dotted(got[2])
|
|
372
|
+
if not inner:
|
|
373
|
+
return None
|
|
374
|
+
got = self.resolve(got[1], inner)
|
|
375
|
+
seen += 1
|
|
376
|
+
return got[1] if got is not None and got[0] == "class" else None
|
|
377
|
+
|
|
378
|
+
def external(self, mod: Mod, name: str | None) -> str | None:
|
|
379
|
+
"""The full outside name (`django.db.models.Model`) a dotted name stands for, when it is not the project's."""
|
|
380
|
+
got = self.resolve(mod, name) if name else None
|
|
381
|
+
if got is not None and got[0] == "external":
|
|
382
|
+
return got[1]
|
|
383
|
+
return None
|
|
384
|
+
|
|
385
|
+
def mro(self, cls: Cls) -> list[Cls]:
|
|
386
|
+
"""The class and its project bases, nearest first (depth-first, left to right: close enough to the C3 order
|
|
387
|
+
for looking up attributes)."""
|
|
388
|
+
cached = self._mro.get(id(cls))
|
|
389
|
+
if cached is not None:
|
|
390
|
+
return cached
|
|
391
|
+
out: list[Cls] = []
|
|
392
|
+
ext: list[str] = []
|
|
393
|
+
self._mro[id(cls)] = out # a cycle sees the partial list and stops
|
|
394
|
+
stack = [cls]
|
|
395
|
+
seen: set[int] = set()
|
|
396
|
+
while stack:
|
|
397
|
+
c = stack.pop(0)
|
|
398
|
+
if id(c) in seen:
|
|
399
|
+
continue
|
|
400
|
+
seen.add(id(c))
|
|
401
|
+
out.append(c)
|
|
402
|
+
nxt = []
|
|
403
|
+
for expr, name in zip(c.base_exprs, c.bases):
|
|
404
|
+
target = expr
|
|
405
|
+
# `Base.from_queryset(QS)` / `Generic[T]` / `with_metaclass(Meta, Base)`: the class inside
|
|
406
|
+
while isinstance(target, ast.Call) and isinstance(target.func, ast.Attribute):
|
|
407
|
+
target = target.func.value
|
|
408
|
+
if isinstance(target, ast.Subscript):
|
|
409
|
+
target = target.value
|
|
410
|
+
nm = dotted(target) or name
|
|
411
|
+
base = self.resolve_class(c.mod, nm) if nm else None
|
|
412
|
+
if base is not None:
|
|
413
|
+
nxt.append(base)
|
|
414
|
+
elif nm:
|
|
415
|
+
ext.append(self.external(c.mod, nm) or nm)
|
|
416
|
+
stack = nxt + stack
|
|
417
|
+
self._ext[id(cls)] = ext
|
|
418
|
+
return out
|
|
419
|
+
|
|
420
|
+
def external_bases(self, cls: Cls) -> list[str]:
|
|
421
|
+
self.mro(cls)
|
|
422
|
+
return self._ext.get(id(cls), [])
|
|
423
|
+
|
|
424
|
+
def find_method(self, cls: Cls, name: str) -> tuple[Cls, ast.FunctionDef] | None:
|
|
425
|
+
for c in self.mro(cls):
|
|
426
|
+
if name in c.methods:
|
|
427
|
+
return c, c.methods[name]
|
|
428
|
+
return None
|
|
429
|
+
|
|
430
|
+
def find_attr(self, cls: Cls, name: str) -> tuple[Cls, ast.AST] | None:
|
|
431
|
+
for c in self.mro(cls):
|
|
432
|
+
if name in c.assigns:
|
|
433
|
+
return c, c.assigns[name]
|
|
434
|
+
return None
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
# ---- counting ---------------------------------------------------------------------------------------------------
|
|
438
|
+
class Stats:
|
|
439
|
+
"""Per library: calls seen, sites emitted, calls not translated and why."""
|
|
440
|
+
|
|
441
|
+
def __init__(self, library: str):
|
|
442
|
+
self.library = library
|
|
443
|
+
self.seen = 0
|
|
444
|
+
self.translated = 0
|
|
445
|
+
self.sites = 0
|
|
446
|
+
self.by_operation: Counter = Counter()
|
|
447
|
+
self.reasons: Counter = Counter()
|
|
448
|
+
self.examples: dict[str, list[str]] = {}
|
|
449
|
+
self.extra: dict = {}
|
|
450
|
+
|
|
451
|
+
def miss(self, reason: str, where: str = "") -> None:
|
|
452
|
+
self.reasons[reason] += 1
|
|
453
|
+
if where:
|
|
454
|
+
ex = self.examples.setdefault(reason, [])
|
|
455
|
+
ex.append(where) # every one is kept in memory for sampling; the summary lists the first few
|
|
456
|
+
|
|
457
|
+
def to_dict(self) -> dict:
|
|
458
|
+
missed = sum(self.reasons.values())
|
|
459
|
+
return {
|
|
460
|
+
"calls_seen": self.seen, "calls_translated": self.translated, "calls_not_translated": missed,
|
|
461
|
+
"share_translated": round(self.translated / self.seen, 3) if self.seen else None,
|
|
462
|
+
"sites_emitted": self.sites,
|
|
463
|
+
"sites_by_operation": dict(self.by_operation.most_common()),
|
|
464
|
+
"not_translated_reasons": dict(self.reasons.most_common()),
|
|
465
|
+
"not_translated_examples": {k: v[:5] for k, v in sorted(self.examples.items(), key=lambda kv: -len(kv[1]))},
|
|
466
|
+
**self.extra,
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
class Emitter:
|
|
471
|
+
"""Collects RawSite records for one library."""
|
|
472
|
+
|
|
473
|
+
def __init__(self, stats: Stats):
|
|
474
|
+
self.stats = stats
|
|
475
|
+
self.sites: list[RawSite] = []
|
|
476
|
+
self._seen: set[tuple] = set()
|
|
477
|
+
|
|
478
|
+
def emit(self, mod: Mod, node: ast.AST, symbol: str, sql: str, *, sink: str, in_loop: bool, model: str,
|
|
479
|
+
operation: str, confidence: str, notes: str = "", engine: str = "", is_test: bool | None = None) -> bool:
|
|
480
|
+
if len(sql) > SETTINGS["orm_max_sql_chars"]:
|
|
481
|
+
self.stats.miss("statement longer than orm_max_sql_chars", f"{mod.rel}:{node.lineno}")
|
|
482
|
+
return False
|
|
483
|
+
line = getattr(node, "lineno", 1)
|
|
484
|
+
key = (mod.rel, line, getattr(node, "col_offset", 0), sql, operation)
|
|
485
|
+
if key in self._seen:
|
|
486
|
+
return False
|
|
487
|
+
self._seen.add(key)
|
|
488
|
+
orm = {"library": self.stats.library, "model_or_table": model, "operation": operation, "confidence": confidence}
|
|
489
|
+
if notes:
|
|
490
|
+
orm["notes"] = notes
|
|
491
|
+
self.sites.append(RawSite(
|
|
492
|
+
file=mod.rel, line=line, end_line=getattr(node, "end_lineno", line) or line, language="python", kind="call",
|
|
493
|
+
sink=trim(sink, 80), symbol=symbol, sql=sql, resolution="orm", expr=trim(src(node)), in_loop=in_loop,
|
|
494
|
+
engine_hint=engine, is_test=mod.is_test if is_test is None else is_test, known_sink=True, orm=orm))
|
|
495
|
+
self.stats.sites += 1
|
|
496
|
+
self.stats.by_operation[operation] += 1
|
|
497
|
+
return True
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
# ---- driver -----------------------------------------------------------------------------------------------------
|
|
501
|
+
LAST_SUMMARY: dict = {}
|
|
502
|
+
LAST_TABLES: list = []
|
|
503
|
+
# cheap test that a project uses one of the ORMs at all: without it nothing is parsed
|
|
504
|
+
_ANY_ORM = re.compile(rb"\bdjango\b|\bsqlalchemy\b|\bsqlmodel\b|\balembic\b|\bprisma|\bpeewee\b|\bplayhouse\b")
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def extract(root: Path, sources: dict[str, bytes], settings: dict | None = None, *, consume: bool = False) -> list[RawSite]:
|
|
508
|
+
"""Called by python.extract with the sources it already read. Returns the ORM sites of the project.
|
|
509
|
+
`consume`: the caller has no further use for `sources`; each file's bytes are let go as its module is
|
|
510
|
+
built, so the bytes and the syntax trees are not all held at once."""
|
|
511
|
+
global LAST_SUMMARY, LAST_TABLES
|
|
512
|
+
LAST_SUMMARY, LAST_TABLES = {}, []
|
|
513
|
+
_SRC.clear()
|
|
514
|
+
if not SETTINGS["orm"]:
|
|
515
|
+
return []
|
|
516
|
+
if not any(_ANY_ORM.search(data) for data in sources.values()):
|
|
517
|
+
return []
|
|
518
|
+
project = Project()
|
|
519
|
+
tests_skipped = 0
|
|
520
|
+
for rel in list(sources):
|
|
521
|
+
data = sources.pop(rel) if consume else sources[rel]
|
|
522
|
+
if not rel.endswith(".py"):
|
|
523
|
+
continue
|
|
524
|
+
if not SETTINGS["orm_tests"] and is_test_path(rel):
|
|
525
|
+
tests_skipped += 1
|
|
526
|
+
continue
|
|
527
|
+
project.add(rel, data.decode("utf-8", "replace"))
|
|
528
|
+
from . import orm_django, orm_py_peewee, orm_py_prisma, orm_sqlalchemy
|
|
529
|
+
|
|
530
|
+
sites: list[RawSite] = []
|
|
531
|
+
calls: dict = {}
|
|
532
|
+
tables: list = []
|
|
533
|
+
for lib in (orm_django, orm_sqlalchemy, orm_py_prisma, orm_py_peewee):
|
|
534
|
+
got, stats, tabs = lib.run(root, project)
|
|
535
|
+
sites.extend(got)
|
|
536
|
+
tables.extend(tabs)
|
|
537
|
+
if stats.seen or stats.sites or tabs:
|
|
538
|
+
calls[stats.library] = stats.to_dict()
|
|
539
|
+
calls[stats.library]["tables_from_models"] = len(tabs)
|
|
540
|
+
calls[stats.library]["files_read"] = len(project.mods)
|
|
541
|
+
calls[stats.library]["files_not_parsed"] = len(project.unparsed)
|
|
542
|
+
# test files are left out unless `orm_tests = true` under [discover]: said here so it is never silent
|
|
543
|
+
calls[stats.library]["test_files_not_read"] = tests_skipped
|
|
544
|
+
if calls:
|
|
545
|
+
LAST_SUMMARY = {"orm_calls": calls}
|
|
546
|
+
LAST_TABLES = tables
|
|
547
|
+
_SRC.clear()
|
|
548
|
+
return sites
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def summary_extras() -> dict:
|
|
552
|
+
return dict(LAST_SUMMARY)
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def tables() -> list:
|
|
556
|
+
"""Table definitions read from ORM models and migrations during the last `extract`."""
|
|
557
|
+
return list(LAST_TABLES)
|