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,595 @@
|
|
|
1
|
+
"""Python call-site extractor.
|
|
2
|
+
|
|
3
|
+
Finds calls whose argument is SQL and resolves that argument statically:
|
|
4
|
+
string literals, f-strings, implicit and `+` concatenation, `.format()`, `%`
|
|
5
|
+
formatting, local variables (including `sql += ...`), module and class
|
|
6
|
+
constants, and constants imported from other files.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from bisect import bisect_right
|
|
13
|
+
from collections import defaultdict
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
import tree_sitter_python
|
|
17
|
+
from tree_sitter import Language, Node, Parser, Query, QueryCursor
|
|
18
|
+
|
|
19
|
+
from .base import LangRules, RawSite, Sink, is_test_path, looks_like_sql, read_text, trim
|
|
20
|
+
from .base import walk_tree
|
|
21
|
+
|
|
22
|
+
LANG = Language(tree_sitter_python.language())
|
|
23
|
+
CONST_NAME = re.compile(r"^_{0,2}[A-Z][A-Z0-9_]*$")
|
|
24
|
+
# How many steps of indirection one SQL argument is followed through. A setting: `[discover] python_resolve_depth`.
|
|
25
|
+
DEFAULT_MAX_DEPTH = 6
|
|
26
|
+
MAX_DEPTH = DEFAULT_MAX_DEPTH
|
|
27
|
+
# The most complete statements one call site is split into when its SQL is assembled in mutually exclusive
|
|
28
|
+
# branches (if / elif / else). Past it the branches become one run-time part. A setting: `[discover] max_variants`.
|
|
29
|
+
DEFAULT_MAX_VARIANTS = 12
|
|
30
|
+
MAX_VARIANTS = DEFAULT_MAX_VARIANTS
|
|
31
|
+
FUNC_TYPES = ("function_definition", "lambda")
|
|
32
|
+
LOOP_TYPES = ("for_statement", "while_statement", "list_comprehension", "generator_expression",
|
|
33
|
+
"set_comprehension", "dictionary_comprehension")
|
|
34
|
+
ESCAPES = {"\\n": "\n", "\\t": "\t", "\\\\": "\\", '\\"': '"', "\\'": "'", "\\\n": ""}
|
|
35
|
+
ESCAPE_RE = re.compile(r"\\(?:n|t|\\|\"|'|\n)")
|
|
36
|
+
# Every node a file's passes look for, found by one query instead of one walk of the whole tree per pass.
|
|
37
|
+
INDEX_QUERY = Query(LANG, "(call) @call (string) @string (function_definition) @func (lambda) @lambda "
|
|
38
|
+
"(assignment) @assign (import_statement) @import (import_from_statement) @import")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _doc_order(nodes: list[Node]) -> list[Node]:
|
|
42
|
+
"""Nodes in the order a depth-first walk meets them: by start, an enclosing node before what it encloses."""
|
|
43
|
+
return sorted(nodes, key=lambda n: (n.start_byte, -n.end_byte))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Res:
|
|
47
|
+
"""A resolved string: text with «expr» placeholders, and how it was reached."""
|
|
48
|
+
|
|
49
|
+
__slots__ = ("text", "dynamic", "via_name", "alts")
|
|
50
|
+
|
|
51
|
+
def __init__(self, text: str, dynamic: bool = False, via_name: bool = False, alts: list[str] | None = None):
|
|
52
|
+
self.text = text
|
|
53
|
+
self.dynamic = dynamic
|
|
54
|
+
self.via_name = via_name
|
|
55
|
+
# complete alternative texts of this value, one per mutually exclusive branch; `text` then has a
|
|
56
|
+
# run-time part where they differ
|
|
57
|
+
self.alts = alts
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def resolution(self) -> str:
|
|
61
|
+
if self.dynamic:
|
|
62
|
+
return "template"
|
|
63
|
+
return "constant" if self.via_name else "literal"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _txt(node: Node) -> str:
|
|
67
|
+
return node.text.decode("utf-8", "replace")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _ph(node: Node) -> Res:
|
|
71
|
+
return Res("«" + trim(_txt(node), 60).replace("»", ">") + "»", dynamic=True)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _walk(node: Node, stop: tuple[str, ...] = ()):
|
|
75
|
+
"""Depth-first over descendants, not descending into node types in `stop`."""
|
|
76
|
+
return walk_tree(node, stop)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class PyFile:
|
|
80
|
+
def __init__(self, rel: str, src: bytes, global_consts: dict[str, set[str]]):
|
|
81
|
+
self.rel = rel
|
|
82
|
+
self.tree = Parser(LANG).parse(src)
|
|
83
|
+
self.root = self.tree.root_node
|
|
84
|
+
self.global_consts = global_consts
|
|
85
|
+
self.module_assigns: dict[str, Node] = {}
|
|
86
|
+
self.imports: set[str] = set()
|
|
87
|
+
self.funcs: dict[str, Node] = {}
|
|
88
|
+
self.consumed: set[int] = set() # string nodes already attached to a reported site
|
|
89
|
+
self.used_globals: set[str] = set() # values of constants taken from other files
|
|
90
|
+
self._resolving: set[int] = set()
|
|
91
|
+
self._scope_cache: dict[int, dict[str, list[Node]]] = {}
|
|
92
|
+
self._index_module()
|
|
93
|
+
|
|
94
|
+
# ---- indexing -------------------------------------------------------
|
|
95
|
+
def _index_module(self) -> None:
|
|
96
|
+
caps = QueryCursor(INDEX_QUERY).captures(self.root)
|
|
97
|
+
# every call and every string of the file in document order, for `wrappers` and `sites`
|
|
98
|
+
self.calls: list[Node] = _doc_order(caps.get("call", []))
|
|
99
|
+
self.strings: list[Node] = _doc_order(caps.get("string", []))
|
|
100
|
+
funcs = _doc_order(caps.get("func", []))
|
|
101
|
+
for n in funcs:
|
|
102
|
+
nm = n.child_by_field_name("name")
|
|
103
|
+
if nm is not None:
|
|
104
|
+
self.funcs.setdefault(_txt(nm), n)
|
|
105
|
+
# assignments and imports outside every function and lambda: spans of the outermost ones, then a lookup
|
|
106
|
+
spans: list[tuple[int, int]] = []
|
|
107
|
+
for n in _doc_order(funcs + caps.get("lambda", [])):
|
|
108
|
+
if not spans or n.start_byte >= spans[-1][1]:
|
|
109
|
+
spans.append((n.start_byte, n.end_byte))
|
|
110
|
+
starts = [a for a, _ in spans]
|
|
111
|
+
|
|
112
|
+
def at_module_level(n: Node) -> bool:
|
|
113
|
+
i = bisect_right(starts, n.start_byte) - 1
|
|
114
|
+
return i < 0 or n.start_byte >= spans[i][1]
|
|
115
|
+
|
|
116
|
+
for n in _doc_order(caps.get("assign", [])):
|
|
117
|
+
if at_module_level(n):
|
|
118
|
+
left = n.child_by_field_name("left")
|
|
119
|
+
right = n.child_by_field_name("right")
|
|
120
|
+
if left is not None and right is not None and left.type == "identifier":
|
|
121
|
+
self.module_assigns.setdefault(_txt(left), right)
|
|
122
|
+
for n in caps.get("import", []):
|
|
123
|
+
if at_module_level(n):
|
|
124
|
+
for name in re.findall(r"[A-Za-z_][\w.]*", _txt(n)):
|
|
125
|
+
self.imports.add(name.split(".")[0])
|
|
126
|
+
|
|
127
|
+
def module_constants(self) -> dict[str, str]:
|
|
128
|
+
"""Module- and class-level NAME = "..." values that resolve fully."""
|
|
129
|
+
out = {}
|
|
130
|
+
for name, node in self.module_assigns.items():
|
|
131
|
+
if not CONST_NAME.match(name):
|
|
132
|
+
continue
|
|
133
|
+
r = self.resolve(node, None, 0)
|
|
134
|
+
if r is not None and not r.dynamic and r.text:
|
|
135
|
+
out[name] = r.text
|
|
136
|
+
return out
|
|
137
|
+
|
|
138
|
+
def _scope_assigns(self, func: Node) -> dict[str, list[Node]]:
|
|
139
|
+
cached = self._scope_cache.get(func.id)
|
|
140
|
+
if cached is None:
|
|
141
|
+
cached = defaultdict(list)
|
|
142
|
+
body = func.child_by_field_name("body") or func
|
|
143
|
+
for n in _walk(body, stop=FUNC_TYPES):
|
|
144
|
+
if n.type in ("assignment", "augmented_assignment"):
|
|
145
|
+
left = n.child_by_field_name("left")
|
|
146
|
+
if left is not None and left.type == "identifier":
|
|
147
|
+
cached[_txt(left)].append(n)
|
|
148
|
+
self._scope_cache[func.id] = cached
|
|
149
|
+
return cached
|
|
150
|
+
|
|
151
|
+
# ---- resolution -----------------------------------------------------
|
|
152
|
+
def resolve(self, node: Node | None, at: Node | None, depth: int) -> Res | None:
|
|
153
|
+
"""Resolve an expression to SQL text. `at` is the call it feeds, used to
|
|
154
|
+
pick the assignments that precede it. Returns None when nothing is known."""
|
|
155
|
+
if node is None or depth > MAX_DEPTH:
|
|
156
|
+
return None
|
|
157
|
+
t = node.type
|
|
158
|
+
if t == "string":
|
|
159
|
+
return self._string(node, at, depth)
|
|
160
|
+
if t == "concatenated_string":
|
|
161
|
+
return self._join([self.resolve(c, at, depth) or _ph(c) for c in node.named_children if c.type == "string"])
|
|
162
|
+
if t == "parenthesized_expression":
|
|
163
|
+
return self.resolve(node.named_children[0], at, depth) if node.named_children else None
|
|
164
|
+
if t == "binary_operator":
|
|
165
|
+
op = node.child_by_field_name("operator")
|
|
166
|
+
left, right = node.child_by_field_name("left"), node.child_by_field_name("right")
|
|
167
|
+
if op is not None and _txt(op) == "+":
|
|
168
|
+
l, r = self.resolve(left, at, depth), self.resolve(right, at, depth)
|
|
169
|
+
if l is None and r is None:
|
|
170
|
+
return None
|
|
171
|
+
return self._join([l or _ph(left), r or _ph(right)])
|
|
172
|
+
if op is not None and _txt(op) == "%":
|
|
173
|
+
l = self.resolve(left, at, depth)
|
|
174
|
+
if l is None:
|
|
175
|
+
return None
|
|
176
|
+
# %s / %d with a tuple on the right is Python formatting; %(name)s stays (driver params)
|
|
177
|
+
return Res(re.sub(r"%[sdr]", "«%»", l.text), True, l.via_name) if re.search(r"%[sdr]", l.text) else l
|
|
178
|
+
return None
|
|
179
|
+
if t == "identifier":
|
|
180
|
+
return self._name(node, at, depth)
|
|
181
|
+
if t == "attribute":
|
|
182
|
+
attr = node.child_by_field_name("attribute")
|
|
183
|
+
if attr is not None and CONST_NAME.match(_txt(attr)):
|
|
184
|
+
return self._global(_txt(attr))
|
|
185
|
+
return None
|
|
186
|
+
if t == "conditional_expression":
|
|
187
|
+
for c in node.named_children:
|
|
188
|
+
r = self.resolve(c, at, depth)
|
|
189
|
+
if r is not None and len(r.text) > 8:
|
|
190
|
+
return Res(r.text, True, r.via_name)
|
|
191
|
+
return None
|
|
192
|
+
if t == "await":
|
|
193
|
+
return self.resolve(node.named_children[0], at, depth) if node.named_children else None
|
|
194
|
+
if t == "call":
|
|
195
|
+
fn = node.child_by_field_name("function")
|
|
196
|
+
if fn is not None and fn.type == "attribute":
|
|
197
|
+
method = _txt(fn.child_by_field_name("attribute"))
|
|
198
|
+
obj = fn.child_by_field_name("object")
|
|
199
|
+
if method == "format":
|
|
200
|
+
base = self.resolve(obj, at, depth)
|
|
201
|
+
if base is None:
|
|
202
|
+
return None
|
|
203
|
+
text = re.sub(r"(?<!\{)\{(\w*)\}(?!\})", lambda m: "«" + (m.group(1) or "arg") + "»", base.text)
|
|
204
|
+
return Res(text.replace("{{", "{").replace("}}", "}"), True, base.via_name)
|
|
205
|
+
if method in ("strip", "lstrip", "rstrip", "replace", "dedent", "lower", "upper"):
|
|
206
|
+
base = self.resolve(obj, at, depth)
|
|
207
|
+
if base is not None and method == "replace":
|
|
208
|
+
return Res(base.text, True, base.via_name)
|
|
209
|
+
return base
|
|
210
|
+
# a helper defined in this file that returns the SQL: resolve its return value
|
|
211
|
+
callee = _txt(fn) if fn is not None and fn.type == "identifier" else (
|
|
212
|
+
_txt(fn.child_by_field_name("attribute")) if fn is not None and fn.type == "attribute"
|
|
213
|
+
and _txt(fn.child_by_field_name("object")) in ("self", "cls") else "")
|
|
214
|
+
target = self.funcs.get(callee) if callee else None
|
|
215
|
+
if target is not None and target.id not in self._resolving:
|
|
216
|
+
self._resolving.add(target.id)
|
|
217
|
+
try:
|
|
218
|
+
found = []
|
|
219
|
+
body = target.child_by_field_name("body")
|
|
220
|
+
for n in (_walk(body, stop=FUNC_TYPES) if body is not None else ()):
|
|
221
|
+
if n.type == "return_statement" and n.named_children:
|
|
222
|
+
r = self.resolve(n.named_children[0], n, depth + 1)
|
|
223
|
+
if r is not None and looks_like_sql(r.text, any_case=True):
|
|
224
|
+
found.append(r)
|
|
225
|
+
if found:
|
|
226
|
+
return Res(found[-1].text, True, True)
|
|
227
|
+
finally:
|
|
228
|
+
self._resolving.discard(target.id)
|
|
229
|
+
# textwrap.dedent("..."), text("..."), wrap_sql(sql): unwrap a single SQL argument
|
|
230
|
+
args = node.child_by_field_name("arguments")
|
|
231
|
+
if args is not None and len(args.named_children) == 1:
|
|
232
|
+
inner = self.resolve(args.named_children[0], at, depth + 1)
|
|
233
|
+
if inner is not None and looks_like_sql(inner.text, any_case=True):
|
|
234
|
+
return inner
|
|
235
|
+
return None
|
|
236
|
+
|
|
237
|
+
def _join(self, parts: list[Res]) -> Res:
|
|
238
|
+
return Res("".join(p.text for p in parts), any(p.dynamic for p in parts), any(p.via_name for p in parts))
|
|
239
|
+
|
|
240
|
+
def _string(self, node: Node, at: Node | None, depth: int) -> Res:
|
|
241
|
+
prefix = ""
|
|
242
|
+
for c in node.children:
|
|
243
|
+
if c.type == "string_start":
|
|
244
|
+
prefix = _txt(c).rstrip("'\"").lower()
|
|
245
|
+
is_f, is_raw = "f" in prefix, "r" in prefix
|
|
246
|
+
parts: list[Res] = []
|
|
247
|
+
for c in node.children:
|
|
248
|
+
if c.type == "string_content":
|
|
249
|
+
s = _txt(c)
|
|
250
|
+
if not is_raw:
|
|
251
|
+
s = ESCAPE_RE.sub(lambda m: ESCAPES[m.group(0)], s)
|
|
252
|
+
if is_f:
|
|
253
|
+
s = s.replace("{{", "{").replace("}}", "}")
|
|
254
|
+
parts.append(Res(s))
|
|
255
|
+
elif c.type == "interpolation":
|
|
256
|
+
expr = c.child_by_field_name("expression") or (c.named_children[0] if c.named_children else None)
|
|
257
|
+
r = None
|
|
258
|
+
if expr is not None and expr.type in ("identifier", "attribute"):
|
|
259
|
+
r = self.resolve(expr, at, depth + 1)
|
|
260
|
+
if r is not None:
|
|
261
|
+
r = Res(r.text, r.dynamic, True)
|
|
262
|
+
parts.append(r or _ph(expr or c))
|
|
263
|
+
return self._join(parts) if parts else Res("")
|
|
264
|
+
|
|
265
|
+
def _name(self, node: Node, at: Node | None, depth: int) -> Res | None:
|
|
266
|
+
name = _txt(node)
|
|
267
|
+
anchor = at or node
|
|
268
|
+
func = self._enclosing(anchor, FUNC_TYPES)
|
|
269
|
+
if func is not None:
|
|
270
|
+
assigns = [a for a in self._scope_assigns(func).get(name, []) if a.end_byte <= anchor.start_byte]
|
|
271
|
+
if assigns:
|
|
272
|
+
last_plain = max((i for i, a in enumerate(assigns) if a.type == "assignment"), default=None)
|
|
273
|
+
if last_plain is None:
|
|
274
|
+
return None
|
|
275
|
+
key = assigns[last_plain].id
|
|
276
|
+
if key in self._resolving:
|
|
277
|
+
return None
|
|
278
|
+
self._resolving.add(key)
|
|
279
|
+
try:
|
|
280
|
+
base = self.resolve(assigns[last_plain].child_by_field_name("right"), assigns[last_plain], depth + 1)
|
|
281
|
+
if base is None:
|
|
282
|
+
return None
|
|
283
|
+
# (append, its piece, its arm): `+=` in different arms of one if / elif / else are
|
|
284
|
+
# alternatives, never one text
|
|
285
|
+
pieces: list[tuple[Node, Res, tuple[int, int] | None]] = []
|
|
286
|
+
for a in assigns[last_plain + 1:]:
|
|
287
|
+
op = a.child_by_field_name("operator")
|
|
288
|
+
if a.type == "augmented_assignment" and op is not None and _txt(op) == "+=":
|
|
289
|
+
right = a.child_by_field_name("right")
|
|
290
|
+
pieces.append((a, self.resolve(right, a, depth + 1) or _ph(right), self._arm(a, anchor, func)))
|
|
291
|
+
groups: dict[int, list[int]] = {}
|
|
292
|
+
for _, _, arm in pieces:
|
|
293
|
+
if arm is not None and arm[1] not in groups.setdefault(arm[0], []):
|
|
294
|
+
groups[arm[0]].append(arm[1])
|
|
295
|
+
groups = {g: arms for g, arms in groups.items() if len(arms) > 1}
|
|
296
|
+
|
|
297
|
+
def read(choice: dict[int, int]) -> Res:
|
|
298
|
+
parts, held = [base], set()
|
|
299
|
+
for a, piece, arm in pieces:
|
|
300
|
+
if arm is not None and arm[0] in choice:
|
|
301
|
+
if choice[arm[0]] == -1:
|
|
302
|
+
if arm[0] not in held:
|
|
303
|
+
held.add(arm[0])
|
|
304
|
+
gap = "" if not parts[-1].text or parts[-1].text[-1].isspace() else " "
|
|
305
|
+
parts.append(Res(gap + "«one of the branches at line %d»" % (a.start_point[0] + 1), True))
|
|
306
|
+
continue
|
|
307
|
+
if choice[arm[0]] != arm[1]:
|
|
308
|
+
continue
|
|
309
|
+
parts.append(piece)
|
|
310
|
+
return self._join(parts)
|
|
311
|
+
|
|
312
|
+
# other assignments to the same name before the last one mean branches we did not follow
|
|
313
|
+
branched = last_plain > 0
|
|
314
|
+
r = read({g: -1 for g in groups})
|
|
315
|
+
alts: list[str] | None = None
|
|
316
|
+
total = 1
|
|
317
|
+
for arms in groups.values():
|
|
318
|
+
total *= len(arms)
|
|
319
|
+
if groups and total <= MAX_VARIANTS:
|
|
320
|
+
choices: list[dict[int, int]] = [{}]
|
|
321
|
+
for g, arms in groups.items():
|
|
322
|
+
choices = [{**c, g: arm} for c in choices for arm in arms]
|
|
323
|
+
alts = list(dict.fromkeys(read(c).text for c in choices))
|
|
324
|
+
alts = alts if len(alts) > 1 else None
|
|
325
|
+
for a in assigns[last_plain:]:
|
|
326
|
+
self._consume(a)
|
|
327
|
+
return Res(r.text, r.dynamic or branched or bool(groups), True, alts)
|
|
328
|
+
finally:
|
|
329
|
+
self._resolving.discard(key)
|
|
330
|
+
if self._is_param(func, name):
|
|
331
|
+
return None
|
|
332
|
+
target = self.module_assigns.get(name)
|
|
333
|
+
if target is not None:
|
|
334
|
+
if target.id in self._resolving:
|
|
335
|
+
return None
|
|
336
|
+
self._resolving.add(target.id)
|
|
337
|
+
try:
|
|
338
|
+
r = self.resolve(target, None, depth + 1)
|
|
339
|
+
finally:
|
|
340
|
+
self._resolving.discard(target.id)
|
|
341
|
+
if r is not None:
|
|
342
|
+
self._consume(target)
|
|
343
|
+
return Res(r.text, r.dynamic, True) if r is not None else None
|
|
344
|
+
return self._global(name)
|
|
345
|
+
|
|
346
|
+
@staticmethod
|
|
347
|
+
def _arm(node: Node, anchor: Node, func: Node) -> tuple[int, int] | None:
|
|
348
|
+
"""(if statement, arm) when `node` sits in one arm of an if / elif / else that `anchor` is outside of."""
|
|
349
|
+
n = node.parent
|
|
350
|
+
while n is not None and n.id != func.id:
|
|
351
|
+
if n.type in LOOP_TYPES:
|
|
352
|
+
return None
|
|
353
|
+
if n.type == "block" and n.parent is not None and n.parent.type in ("if_statement", "elif_clause", "else_clause"):
|
|
354
|
+
root = n.parent if n.parent.type == "if_statement" else n.parent.parent
|
|
355
|
+
if root is not None and not (root.start_byte <= anchor.start_byte and anchor.end_byte <= root.end_byte):
|
|
356
|
+
return root.id, n.id
|
|
357
|
+
return None
|
|
358
|
+
n = n.parent
|
|
359
|
+
return None
|
|
360
|
+
|
|
361
|
+
def _consume(self, node: Node) -> None:
|
|
362
|
+
if node.type == "string":
|
|
363
|
+
self.consumed.add(node.id)
|
|
364
|
+
for s in _walk(node):
|
|
365
|
+
if s.type == "string":
|
|
366
|
+
self.consumed.add(s.id)
|
|
367
|
+
|
|
368
|
+
def _global(self, name: str) -> Res | None:
|
|
369
|
+
values = self.global_consts.get(name)
|
|
370
|
+
if values and len(values) == 1:
|
|
371
|
+
value = next(iter(values))
|
|
372
|
+
self.used_globals.add(value)
|
|
373
|
+
return Res(value, False, True)
|
|
374
|
+
return None
|
|
375
|
+
|
|
376
|
+
@staticmethod
|
|
377
|
+
def _is_param(func: Node, name: str) -> bool:
|
|
378
|
+
params = func.child_by_field_name("parameters")
|
|
379
|
+
return params is not None and bool(re.search(rf"(?<![\w.]){re.escape(name)}(?!\w)", _txt(params)))
|
|
380
|
+
|
|
381
|
+
@staticmethod
|
|
382
|
+
def _enclosing(node: Node, types: tuple[str, ...]) -> Node | None:
|
|
383
|
+
n = node.parent
|
|
384
|
+
while n is not None:
|
|
385
|
+
if n.type in types:
|
|
386
|
+
return n
|
|
387
|
+
n = n.parent
|
|
388
|
+
return None
|
|
389
|
+
|
|
390
|
+
# ---- call sites -----------------------------------------------------
|
|
391
|
+
def symbol(self, node: Node) -> str:
|
|
392
|
+
names = []
|
|
393
|
+
n = node.parent
|
|
394
|
+
while n is not None:
|
|
395
|
+
if n.type in ("function_definition", "class_definition"):
|
|
396
|
+
nm = n.child_by_field_name("name")
|
|
397
|
+
if nm is not None:
|
|
398
|
+
names.append(_txt(nm))
|
|
399
|
+
n = n.parent
|
|
400
|
+
return ".".join(reversed(names))
|
|
401
|
+
|
|
402
|
+
def in_loop(self, node: Node) -> bool:
|
|
403
|
+
n = node.parent
|
|
404
|
+
while n is not None and n.type not in ("function_definition", "module"):
|
|
405
|
+
if n.type in LOOP_TYPES:
|
|
406
|
+
return True
|
|
407
|
+
n = n.parent
|
|
408
|
+
return False
|
|
409
|
+
|
|
410
|
+
def file_engine(self, rules: LangRules) -> str:
|
|
411
|
+
engines = {rules.imports[m] for m in self.imports if m in rules.imports}
|
|
412
|
+
return next(iter(engines)) if len(engines) == 1 else ""
|
|
413
|
+
|
|
414
|
+
def sites(self, rules: LangRules) -> list[RawSite]:
|
|
415
|
+
out: list[RawSite] = []
|
|
416
|
+
consumed = self.consumed
|
|
417
|
+
consumed.clear()
|
|
418
|
+
file_engine = self.file_engine(rules)
|
|
419
|
+
test = is_test_path(self.rel)
|
|
420
|
+
|
|
421
|
+
def site(call: Node, arg: Node, sink_text: str, engine: str, known: bool, res: Res | None) -> None:
|
|
422
|
+
variants = [a for a in (res.alts or ()) if looks_like_sql(a, any_case=True)] if res is not None else []
|
|
423
|
+
for text in (variants if len(variants) > 1 else [res.text if res is not None else None]):
|
|
424
|
+
out.append(RawSite(
|
|
425
|
+
file=self.rel, line=call.start_point[0] + 1, end_line=call.end_point[0] + 1, language="python",
|
|
426
|
+
kind="call", sink=trim(sink_text, 80), symbol=self.symbol(call),
|
|
427
|
+
sql=text,
|
|
428
|
+
resolution=res.resolution if res is not None else ("parameter" if self._param_of(call, arg) else "unresolved"),
|
|
429
|
+
expr=trim(_txt(arg)), in_loop=self.in_loop(call), engine_hint=engine or file_engine,
|
|
430
|
+
is_test=test, known_sink=known,
|
|
431
|
+
))
|
|
432
|
+
|
|
433
|
+
for call in self.calls:
|
|
434
|
+
fn = call.child_by_field_name("function")
|
|
435
|
+
args = call.child_by_field_name("arguments")
|
|
436
|
+
if fn is None or args is None or args.type != "argument_list":
|
|
437
|
+
continue
|
|
438
|
+
name = _txt(fn.child_by_field_name("attribute")) if fn.type == "attribute" else _txt(fn) if fn.type == "identifier" else ""
|
|
439
|
+
sink = rules.sink_for(name) if name else None
|
|
440
|
+
if sink is None:
|
|
441
|
+
continue
|
|
442
|
+
positional = [a for a in args.named_children if a.type not in ("keyword_argument", "comment")]
|
|
443
|
+
candidates = [positional[i] for i in sink.args if i < len(positional)]
|
|
444
|
+
for a in args.named_children:
|
|
445
|
+
if a.type == "keyword_argument" and _txt(a.child_by_field_name("name")) in sink.kwargs:
|
|
446
|
+
candidates.append(a.child_by_field_name("value"))
|
|
447
|
+
for arg in candidates:
|
|
448
|
+
res = self.resolve(arg, call, 0)
|
|
449
|
+
if res is not None and not looks_like_sql(res.text, any_case=True):
|
|
450
|
+
continue # resolved, and it is not SQL (dict.get("query"), requests, ...)
|
|
451
|
+
if res is None and not self._param_of(call, arg) and not self._plausible_unresolved(fn, arg, file_engine):
|
|
452
|
+
continue
|
|
453
|
+
if res is None and fn.type == "attribute" and _txt(fn.child_by_field_name("object")).replace(" ", "").startswith("super("):
|
|
454
|
+
continue # `super().execute(context)` hands its argument to the parent's method: no SQL is sent here
|
|
455
|
+
site(call, arg, _txt(fn), sink.engine, True, res)
|
|
456
|
+
self._consume(arg)
|
|
457
|
+
break
|
|
458
|
+
|
|
459
|
+
# SQL strings not attached to a known sink: wrapper calls, fragments, constants.
|
|
460
|
+
orphans: list[tuple[Node, Node, Res]] = []
|
|
461
|
+
for s in self.strings:
|
|
462
|
+
if s.id in consumed:
|
|
463
|
+
continue
|
|
464
|
+
if s.parent is not None and s.parent.type == "concatenated_string" and s.parent.named_children[0].id != s.id:
|
|
465
|
+
continue
|
|
466
|
+
node = s.parent if s.parent is not None and s.parent.type == "concatenated_string" else s
|
|
467
|
+
if node.parent is not None and node.parent.type == "expression_statement":
|
|
468
|
+
continue # docstring
|
|
469
|
+
res = self.resolve(node, node, 0)
|
|
470
|
+
if res is None or not looks_like_sql(res.text):
|
|
471
|
+
continue
|
|
472
|
+
orphans.append((s, node, res))
|
|
473
|
+
for s, node, res in orphans:
|
|
474
|
+
if s.id in consumed:
|
|
475
|
+
continue # a larger SQL string was built from this one
|
|
476
|
+
call, kw = self._owning_call(node)
|
|
477
|
+
sink_text = _txt(call.child_by_field_name("function")) if call is not None else ""
|
|
478
|
+
out.append(RawSite(
|
|
479
|
+
file=self.rel, line=node.start_point[0] + 1, end_line=node.end_point[0] + 1, language="python",
|
|
480
|
+
kind="call" if call is not None else "sql_string", sink=trim(sink_text, 80), symbol=self.symbol(node),
|
|
481
|
+
sql=res.text, resolution=res.resolution, expr=trim(_txt(node)), in_loop=self.in_loop(node),
|
|
482
|
+
engine_hint=file_engine, is_test=test, known_sink=False,
|
|
483
|
+
))
|
|
484
|
+
return out
|
|
485
|
+
|
|
486
|
+
def _param_of(self, call: Node, arg: Node) -> tuple[str, int] | None:
|
|
487
|
+
"""When `arg` is a parameter of the enclosing function, that function is a
|
|
488
|
+
wrapper around the driver. Returns (function name, positional index)."""
|
|
489
|
+
if arg.type != "identifier":
|
|
490
|
+
return None
|
|
491
|
+
func = self._enclosing(call, ("function_definition",))
|
|
492
|
+
if func is None:
|
|
493
|
+
return None
|
|
494
|
+
name = _txt(arg)
|
|
495
|
+
if self._scope_assigns(func).get(name):
|
|
496
|
+
return None
|
|
497
|
+
params = func.child_by_field_name("parameters")
|
|
498
|
+
fname = func.child_by_field_name("name")
|
|
499
|
+
if params is None or fname is None:
|
|
500
|
+
return None
|
|
501
|
+
names = []
|
|
502
|
+
for p in params.named_children:
|
|
503
|
+
ident = p if p.type == "identifier" else (p.child_by_field_name("name") or (p.named_children[0] if p.named_children else None))
|
|
504
|
+
names.append(_txt(ident) if ident is not None else "")
|
|
505
|
+
if names and names[0] in ("self", "cls"):
|
|
506
|
+
names = names[1:]
|
|
507
|
+
return (_txt(fname), names.index(name)) if name in names else None
|
|
508
|
+
|
|
509
|
+
def wrappers(self, rules: LangRules) -> list[tuple[str, int, str, str]]:
|
|
510
|
+
"""Functions in this file that pass one of their own parameters to a sink:
|
|
511
|
+
(function name, positional index, parameter name, engine)."""
|
|
512
|
+
out = []
|
|
513
|
+
for call in self.calls:
|
|
514
|
+
fn, args = call.child_by_field_name("function"), call.child_by_field_name("arguments")
|
|
515
|
+
if fn is None or args is None or args.type != "argument_list":
|
|
516
|
+
continue
|
|
517
|
+
name = _txt(fn.child_by_field_name("attribute")) if fn.type == "attribute" else _txt(fn) if fn.type == "identifier" else ""
|
|
518
|
+
sink = rules.sink_for(name) if name else None
|
|
519
|
+
if sink is None:
|
|
520
|
+
continue
|
|
521
|
+
positional = [a for a in args.named_children if a.type not in ("keyword_argument", "comment")]
|
|
522
|
+
for i in sink.args:
|
|
523
|
+
if i < len(positional):
|
|
524
|
+
hit = self._param_of(call, positional[i])
|
|
525
|
+
if hit and self.SQLISH_NAME.search(_txt(positional[i])):
|
|
526
|
+
out.append((hit[0], hit[1], _txt(positional[i]), sink.engine or self.file_engine(rules)))
|
|
527
|
+
return out
|
|
528
|
+
|
|
529
|
+
@staticmethod
|
|
530
|
+
def _owning_call(node: Node) -> tuple[Node | None, str]:
|
|
531
|
+
"""The call this string is a direct argument of, if any."""
|
|
532
|
+
n = node.parent
|
|
533
|
+
kw = ""
|
|
534
|
+
while n is not None and n.type in ("parenthesized_expression", "keyword_argument", "binary_operator", "concatenated_string"):
|
|
535
|
+
if n.type == "keyword_argument":
|
|
536
|
+
kw = _txt(n.child_by_field_name("name"))
|
|
537
|
+
n = n.parent
|
|
538
|
+
if n is not None and n.type == "argument_list" and n.parent is not None and n.parent.type == "call":
|
|
539
|
+
return n.parent, kw
|
|
540
|
+
return None, kw
|
|
541
|
+
|
|
542
|
+
RECEIVER = re.compile(r"(client|ch|conn|cursor|cur|db|pool|session|clickhouse)", re.I)
|
|
543
|
+
SQLISH_NAME = re.compile(r"(sql|query|stmt|statement|ddl)", re.I)
|
|
544
|
+
|
|
545
|
+
def _plausible_unresolved(self, fn: Node, arg: Node, file_engine: str) -> bool:
|
|
546
|
+
"""Keep an unresolved call only when it plausibly is a database call."""
|
|
547
|
+
if arg.type in ("dictionary", "list", "integer", "true", "false", "none", "lambda"):
|
|
548
|
+
return False
|
|
549
|
+
obj = fn.child_by_field_name("object") if fn.type == "attribute" else None
|
|
550
|
+
receiver_ok = obj is not None and bool(self.RECEIVER.search(_txt(obj)[-40:]))
|
|
551
|
+
arg_ok = bool(self.SQLISH_NAME.search(_txt(arg)[:80]))
|
|
552
|
+
return (receiver_ok and (arg_ok or bool(file_engine))) or (arg_ok and bool(file_engine))
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def extract(root: Path, files: list[str], rules: LangRules) -> list[RawSite]:
|
|
556
|
+
"""Two passes: collect constants and wrapper functions from every file, then find call sites."""
|
|
557
|
+
found_wrappers: dict[str, tuple[int, str, str]] = {}
|
|
558
|
+
global_consts: dict[str, set[str]] = defaultdict(set)
|
|
559
|
+
sources: dict[str, bytes] = {}
|
|
560
|
+
for rel in files:
|
|
561
|
+
text = read_text(root / rel)
|
|
562
|
+
if text is None:
|
|
563
|
+
continue
|
|
564
|
+
src = text.encode("utf-8")
|
|
565
|
+
sources[rel] = src
|
|
566
|
+
try:
|
|
567
|
+
pf = PyFile(rel, src, {})
|
|
568
|
+
for name, value in pf.module_constants().items():
|
|
569
|
+
if len(value) < 20_000:
|
|
570
|
+
global_consts[name].add(value)
|
|
571
|
+
for fname, index, param, engine in pf.wrappers(rules):
|
|
572
|
+
if rules.sink_for(fname) is None and not fname.startswith("__"):
|
|
573
|
+
found_wrappers.setdefault(fname, (index, param, engine))
|
|
574
|
+
except RecursionError:
|
|
575
|
+
continue
|
|
576
|
+
for fname, (index, param, engine) in found_wrappers.items():
|
|
577
|
+
rules.sinks.append(Sink({fname}, engine, [index], {param}))
|
|
578
|
+
out: list[RawSite] = []
|
|
579
|
+
used_globals: set[str] = set()
|
|
580
|
+
for rel, src in sources.items():
|
|
581
|
+
try:
|
|
582
|
+
pf = PyFile(rel, src, global_consts)
|
|
583
|
+
out.extend(pf.sites(rules))
|
|
584
|
+
used_globals |= pf.used_globals
|
|
585
|
+
except RecursionError:
|
|
586
|
+
continue
|
|
587
|
+
# a constant used from another file is reported at its use sites, not again at its definition
|
|
588
|
+
out = [s for s in out if not (s.kind == "sql_string" and s.sql in used_globals)]
|
|
589
|
+
from . import orm_py # ORM calls (Django, SQLAlchemy): sites whose SQL is synthesised from the call
|
|
590
|
+
return out + orm_py.extract(root, sources, consume=True)
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def summary_extras() -> dict:
|
|
594
|
+
from . import orm_py
|
|
595
|
+
return orm_py.summary_extras()
|