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
codecop/discover/arms.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""One statement per arm of an if / else (or match) that appends to a query string.
|
|
2
|
+
|
|
3
|
+
The Java and Rust extractors replay what happens to a string variable. Until now the arm that was not followed
|
|
4
|
+
was written into the statement as a run-time part (`... AND tenant = ? «or: AND tenant IS NULL» ...`). `Arms`
|
|
5
|
+
keeps, beside that text, the whole statement of every arm: appends in the then-arm go to the variants that
|
|
6
|
+
existed before the `if`, appends in an else-arm go to copies taken before the then-arm, and whatever follows
|
|
7
|
+
goes to all of them. The number of variants is capped by `[discover] max_variants`; past the cap (or when the
|
|
8
|
+
string is rebuilt in a way that cannot be followed per arm) the extractor falls back to the single statement
|
|
9
|
+
with the «or: ...» part, so nothing is dropped silently.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from tree_sitter import Node
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def max_variants() -> int:
|
|
18
|
+
from . import go as go_mod
|
|
19
|
+
return go_mod.MAX_VARIANTS
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Arms:
|
|
23
|
+
def __init__(self, join, limit: int | None = None):
|
|
24
|
+
self.join = join # join([value, piece]) -> value
|
|
25
|
+
self.limit = limit if limit is not None else max_variants()
|
|
26
|
+
self.vs: list | None = None
|
|
27
|
+
self.snaps: dict[int, list] = {}
|
|
28
|
+
self.arm_of: dict[tuple[int, int], list[int]] = {}
|
|
29
|
+
self.dead = False
|
|
30
|
+
|
|
31
|
+
def reset(self, value) -> None:
|
|
32
|
+
self.vs = [value] if value is not None else None
|
|
33
|
+
self.snaps.clear()
|
|
34
|
+
self.arm_of.clear()
|
|
35
|
+
|
|
36
|
+
def kill(self) -> None:
|
|
37
|
+
self.dead = True
|
|
38
|
+
|
|
39
|
+
def then(self, keys: list[int]) -> None:
|
|
40
|
+
"""Before an append inside the first arm of the constructs `keys`: remember the variants as they were."""
|
|
41
|
+
if self.vs is None:
|
|
42
|
+
return
|
|
43
|
+
for k in keys:
|
|
44
|
+
self.snaps.setdefault(k, list(self.vs))
|
|
45
|
+
|
|
46
|
+
def append(self, piece, front: bool = False) -> None:
|
|
47
|
+
if self.vs is not None:
|
|
48
|
+
self.vs = [self.join([piece, v] if front else [v, piece]) for v in self.vs]
|
|
49
|
+
|
|
50
|
+
def append_else(self, key: tuple[int, int] | None, piece) -> None:
|
|
51
|
+
"""An append inside another arm: it extends that arm's own variants, made from the snapshot."""
|
|
52
|
+
if self.vs is None or self.dead:
|
|
53
|
+
return
|
|
54
|
+
if key is None:
|
|
55
|
+
self.dead = True
|
|
56
|
+
return
|
|
57
|
+
idx = self.arm_of.get(key)
|
|
58
|
+
if idx is None:
|
|
59
|
+
base = self.snaps.get(key[0])
|
|
60
|
+
if base is None or len(self.vs) + len(base) > self.limit:
|
|
61
|
+
self.dead = True
|
|
62
|
+
return
|
|
63
|
+
start = len(self.vs)
|
|
64
|
+
self.vs.extend(self.join([b, piece]) for b in base)
|
|
65
|
+
self.arm_of[key] = list(range(start, len(self.vs)))
|
|
66
|
+
else:
|
|
67
|
+
for i in idx:
|
|
68
|
+
self.vs[i] = self.join([self.vs[i], piece])
|
|
69
|
+
|
|
70
|
+
def result(self) -> list:
|
|
71
|
+
if self.dead or self.vs is None or len(self.vs) < 2:
|
|
72
|
+
return []
|
|
73
|
+
return list(self.vs)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _if_parts(n: Node) -> tuple[Node | None, Node | None]:
|
|
77
|
+
"""(first arm, the rest) of an `if`, for Java (`if_statement`) and Rust (`if_expression`)."""
|
|
78
|
+
cons, alt = n.child_by_field_name("consequence"), n.child_by_field_name("alternative")
|
|
79
|
+
if alt is not None and alt.type == "else_clause": # Rust wraps the else part
|
|
80
|
+
inner = [c for c in alt.named_children]
|
|
81
|
+
alt = inner[-1] if inner else None
|
|
82
|
+
return cons, alt
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _within(node: Node, outer: Node | None) -> bool:
|
|
86
|
+
return outer is not None and outer.start_byte <= node.start_byte and node.end_byte <= outer.end_byte
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
IF_TYPES = ("if_statement", "if_expression")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _constructs(node: Node, stop: Node | None, anchor: int):
|
|
93
|
+
"""The if and match constructs around `node`, outermost first, that do not contain the use at `anchor`."""
|
|
94
|
+
out = []
|
|
95
|
+
n = node.parent
|
|
96
|
+
while n is not None and (stop is None or n.id != stop.id) and n.type not in ("function_item", "method_declaration",
|
|
97
|
+
"constructor_declaration", "class_declaration"):
|
|
98
|
+
if n.type in IF_TYPES or n.type == "match_expression":
|
|
99
|
+
if not (n.start_byte <= anchor < n.end_byte):
|
|
100
|
+
out.append(n)
|
|
101
|
+
n = n.parent
|
|
102
|
+
out.reverse()
|
|
103
|
+
return out
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _is_chain_root(n: Node) -> bool:
|
|
107
|
+
p = n.parent
|
|
108
|
+
if p is None:
|
|
109
|
+
return True
|
|
110
|
+
if p.type == "else_clause":
|
|
111
|
+
return False
|
|
112
|
+
return not (p.type in IF_TYPES and p.child_by_field_name("alternative") is not None and p.child_by_field_name("alternative").id == n.id)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _match_arms(n: Node) -> list[Node]:
|
|
116
|
+
body = n.child_by_field_name("body")
|
|
117
|
+
return [c for c in (body.named_children if body is not None else []) if c.type == "match_arm"]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def then_keys(node: Node, stop: Node | None, anchor: int) -> list[int]:
|
|
121
|
+
"""Constructs in whose first arm `node` sits."""
|
|
122
|
+
keys = []
|
|
123
|
+
for n in _constructs(node, stop, anchor):
|
|
124
|
+
if n.type == "match_expression":
|
|
125
|
+
arms = _match_arms(n)
|
|
126
|
+
if arms and _within(node, arms[0]):
|
|
127
|
+
keys.append(n.id)
|
|
128
|
+
elif _is_chain_root(n):
|
|
129
|
+
cons, _alt = _if_parts(n)
|
|
130
|
+
if _within(node, cons):
|
|
131
|
+
keys.append(n.id)
|
|
132
|
+
return keys
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def arm_key(node: Node, stop: Node | None, anchor: int) -> tuple[int, int] | None:
|
|
136
|
+
"""(construct, arm) when `node` sits in an arm other than the first of the outermost such construct."""
|
|
137
|
+
for n in _constructs(node, stop, anchor):
|
|
138
|
+
if n.type == "match_expression":
|
|
139
|
+
arms = _match_arms(n)
|
|
140
|
+
for a in arms[1:]:
|
|
141
|
+
if _within(node, a):
|
|
142
|
+
return n.id, a.id
|
|
143
|
+
continue
|
|
144
|
+
if not _is_chain_root(n):
|
|
145
|
+
continue
|
|
146
|
+
cons, alt = _if_parts(n)
|
|
147
|
+
if not _within(node, alt):
|
|
148
|
+
continue
|
|
149
|
+
arm = alt
|
|
150
|
+
while arm is not None and arm.type in IF_TYPES: # else if ... else if ... else
|
|
151
|
+
c2, a2 = _if_parts(arm)
|
|
152
|
+
if _within(node, c2):
|
|
153
|
+
arm = c2
|
|
154
|
+
break
|
|
155
|
+
if _within(node, a2):
|
|
156
|
+
arm = a2
|
|
157
|
+
continue
|
|
158
|
+
break
|
|
159
|
+
return (n.id, arm.id) if arm is not None else None
|
|
160
|
+
return None
|
codecop/discover/base.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""Shared types for discovery.
|
|
2
|
+
|
|
3
|
+
A language extractor turns source files into RawSite records. It does no SQL
|
|
4
|
+
analysis: it only finds where SQL reaches a driver and resolves the SQL text as
|
|
5
|
+
far as it can statically.
|
|
6
|
+
|
|
7
|
+
SQL templates use «expr» for a part that is only known at run time, where expr
|
|
8
|
+
is the source expression (for example «table» or «", ".join(cols)»).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
import tomllib
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from importlib import resources
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
PLACEHOLDER = re.compile(r"«[^»]*»")
|
|
20
|
+
|
|
21
|
+
# A string that starts like a full statement. Case-sensitive on purpose: prose such
|
|
22
|
+
# as "Select a file from the list" must not match. Lower-case SQL is still found
|
|
23
|
+
# when it is the argument of a known sink.
|
|
24
|
+
SQL_START = re.compile(
|
|
25
|
+
r"^\s*(?:--[^\n]*\n\s*|/\*.*?\*/\s*)*\(?\s*(?:"
|
|
26
|
+
r"SELECT\b[\s\S]+?\bFROM\b|SELECT\s+[\w(*]|WITH\s+[\s\S]+?\bAS\b\s*\(?|INSERT\s+(?:OR\s+\w+\s+)?INTO\b|"
|
|
27
|
+
r"CREATE\s+(?:OR\s+REPLACE\s+)?(?:TEMPORARY\s+)?(?:TABLE|MATERIALIZED|VIEW|DICTIONARY|INDEX|UNIQUE)\b|"
|
|
28
|
+
r"ALTER\s+TABLE\b|DELETE\s+FROM\b|UPDATE\s+[\w.«»\"`]+\s+SET\b|DROP\s+(?:TABLE|VIEW|INDEX)\b|"
|
|
29
|
+
r"OPTIMIZE\s+TABLE\b|TRUNCATE\s+TABLE\b|SHOW\s+(?:CREATE|TABLES|DATABASES)\b|EXPLAIN\s|"
|
|
30
|
+
r"DESCRIBE\s+TABLE\b|SYSTEM\s+[A-Z]+|PRAGMA\s+\w+|EXISTS\s+TABLE\b)"
|
|
31
|
+
)
|
|
32
|
+
SQL_START_ANYCASE = re.compile(SQL_START.pattern, re.IGNORECASE)
|
|
33
|
+
# The words of a DDL statement with nothing after them ("ALTER TABLE ", "CREATE VIEW"): a fragment that code
|
|
34
|
+
# appends a name to, or a keyword in a list. A statement names the thing it changes. Checked on the text a
|
|
35
|
+
# site ends up with, not in looks_like_sql: the extractors use that on the first literal of a concatenation
|
|
36
|
+
# (`"ALTER TABLE " + name + " ADD ..."`), where the words alone are how a real statement starts.
|
|
37
|
+
BARE_DDL = re.compile(
|
|
38
|
+
r"^\s*(?:CREATE(?:\s+OR\s+REPLACE)?(?:\s+TEMPORARY)?(?:\s+UNIQUE)?(?:\s+MATERIALIZED)?|ALTER|DROP|TRUNCATE|OPTIMIZE|RENAME)"
|
|
39
|
+
r"(?:\s+(?:TABLE|VIEW|INDEX|DICTIONARY|DATABASE|SCHEMA|SEQUENCE|TYPE|FUNCTION|TRIGGER))?"
|
|
40
|
+
r"(?:\s+IF\s+(?:NOT\s+)?EXISTS)?\s*;?\s*$", re.I)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def looks_like_sql(text: str, *, any_case: bool = False) -> bool:
|
|
44
|
+
if not text or len(text) < 12:
|
|
45
|
+
return False
|
|
46
|
+
return bool((SQL_START_ANYCASE if any_case else SQL_START).match(text))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class RawSite:
|
|
51
|
+
file: str # path relative to the repo root
|
|
52
|
+
line: int # 1-based line of the call (or of the string for sql_string)
|
|
53
|
+
end_line: int
|
|
54
|
+
language: str # python | rust | go | java | sql
|
|
55
|
+
kind: str # call | sql_string | sql_file
|
|
56
|
+
sink: str # callee text, e.g. "client.query"; "" when not attached to a call
|
|
57
|
+
symbol: str # enclosing function, e.g. "UserStore.fetch_page"; "" at module level
|
|
58
|
+
sql: str | None # resolved template, or None when unresolved
|
|
59
|
+
resolution: str # literal | constant | template | file | unresolved
|
|
60
|
+
expr: str = "" # source text of the SQL argument, trimmed
|
|
61
|
+
in_loop: bool = False
|
|
62
|
+
engine_hint: str = "" # from the sink rule or the file's imports; "" when unknown
|
|
63
|
+
is_test: bool = False
|
|
64
|
+
known_sink: bool = True # False when the callee is not in the sink rules (a likely wrapper)
|
|
65
|
+
orm: dict | None = None # resolution "orm": {library, model_or_table, operation, confidence, notes?}
|
|
66
|
+
# where engine_hint came from when it was not the file's own imports: {basis: handle | package, detail?},
|
|
67
|
+
# {unsure: why no engine was given} when the evidence names two, {binds: "qmark"} for `?` placeholders (Go)
|
|
68
|
+
engine_evidence: dict | None = None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class Sink:
|
|
73
|
+
names: set[str]
|
|
74
|
+
engine: str
|
|
75
|
+
args: list[int]
|
|
76
|
+
kwargs: set[str]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class LangRules:
|
|
81
|
+
sinks: list[Sink] = field(default_factory=list)
|
|
82
|
+
imports: dict[str, str] = field(default_factory=dict)
|
|
83
|
+
|
|
84
|
+
def sink_for(self, name: str) -> Sink | None:
|
|
85
|
+
for s in self.sinks:
|
|
86
|
+
if name in s.names:
|
|
87
|
+
return s
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def load_rules(language: str, extra_wrappers: list[dict] | None = None) -> LangRules:
|
|
92
|
+
"""Load the packaged sink rules for a language, plus wrappers from codecop.toml."""
|
|
93
|
+
text = resources.files("codecop.rules").joinpath("sinks.toml").read_text()
|
|
94
|
+
data = tomllib.loads(text).get(language, {})
|
|
95
|
+
rules = LangRules(imports=dict(data.get("imports", {})))
|
|
96
|
+
for raw in list(data.get("sink", [])) + [w for w in (extra_wrappers or []) if w.get("language", language) == language]:
|
|
97
|
+
names = raw.get("names") or [raw["name"]]
|
|
98
|
+
rules.sinks.append(
|
|
99
|
+
Sink(set(names), raw.get("engine", ""), list(raw.get("args", [0])), set(raw.get("kwargs", [])))
|
|
100
|
+
)
|
|
101
|
+
return rules
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def walk_tree(node, stop: tuple[str, ...] = ()):
|
|
105
|
+
"""Depth-first over a tree-sitter node's descendants in document order, not descending into node types in
|
|
106
|
+
`stop`. A cursor does the walking: asking each node for `.children` instead makes the binding keep a list of
|
|
107
|
+
child objects on every node visited, so one node held afterwards (a file's root, a call kept for later) keeps
|
|
108
|
+
an object for every node of its subtree alive, several times the size of the tree itself."""
|
|
109
|
+
cursor = node.walk()
|
|
110
|
+
if not cursor.goto_first_child():
|
|
111
|
+
return
|
|
112
|
+
depth = 1
|
|
113
|
+
while True:
|
|
114
|
+
n = cursor.node
|
|
115
|
+
yield n
|
|
116
|
+
if n.type not in stop and cursor.goto_first_child():
|
|
117
|
+
depth += 1
|
|
118
|
+
continue
|
|
119
|
+
while not cursor.goto_next_sibling():
|
|
120
|
+
cursor.goto_parent()
|
|
121
|
+
depth -= 1
|
|
122
|
+
if depth == 0:
|
|
123
|
+
return
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
TEST_PATH = re.compile(r"(^|/)(tests?|testdata|__tests__|page_tests|fixtures|testutils?|test_utils?|testhelpers?|test_helpers?|testing)(/|$)|(^|/)test_[^/]*$|_test\.[a-z]+$|(^|/)conftest\.py$|(^|/)tests\.rs$|_tests\.rs$|"
|
|
127
|
+
r"[.-](?:test|spec|e2e|integration-test|integration|smoke|mock|mocks|fixture|fixtures)\.[cm]?[jt]sx?$|_spec\.rb$")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def is_test_path(rel: str) -> bool:
|
|
131
|
+
return bool(TEST_PATH.search(rel))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def trim(text: str, n: int = 300) -> str:
|
|
135
|
+
text = " ".join(text.split())
|
|
136
|
+
return text if len(text) <= n else text[: n - 1] + "…"
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
# The largest file discovery reads, in bytes. A setting, not a constant: `[discover] max_file_bytes` in
|
|
140
|
+
# codecop.toml or `codecop discover --max-file-bytes`. Generated query code (sqlc) runs to several megabytes, so the
|
|
141
|
+
# default is generous; a file over the limit is never dropped silently, it is listed in the inventory.
|
|
142
|
+
DEFAULT_MAX_FILE_BYTES = 64_000_000
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class ReadState:
|
|
146
|
+
"""The file-size limit of the current run and every file it kept out, with its size."""
|
|
147
|
+
|
|
148
|
+
def __init__(self) -> None:
|
|
149
|
+
self.max_file_bytes = DEFAULT_MAX_FILE_BYTES
|
|
150
|
+
self.skipped: dict[str, int] = {} # absolute path -> size in bytes
|
|
151
|
+
|
|
152
|
+
def begin(self, max_file_bytes: int | None = None) -> None:
|
|
153
|
+
self.max_file_bytes = int(max_file_bytes) if max_file_bytes else DEFAULT_MAX_FILE_BYTES
|
|
154
|
+
self.skipped = {}
|
|
155
|
+
|
|
156
|
+
def too_large(self, path: Path, size: int | None = None) -> bool:
|
|
157
|
+
"""True (and noted) when the file is over the limit. Every reader of repository files asks here."""
|
|
158
|
+
if size is None:
|
|
159
|
+
size = path.stat().st_size
|
|
160
|
+
if size > self.max_file_bytes:
|
|
161
|
+
self.skipped[str(path)] = size
|
|
162
|
+
return True
|
|
163
|
+
return False
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
READ = ReadState()
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def read_text(path: Path, limit: int | None = None) -> str | None:
|
|
170
|
+
"""The file's text, or None when it cannot be read or is over the size limit (noted in READ.skipped).
|
|
171
|
+
`limit` is accepted for old callers and ignored: there is one limit, the run's setting."""
|
|
172
|
+
try:
|
|
173
|
+
if READ.too_large(path):
|
|
174
|
+
return None
|
|
175
|
+
return path.read_text(encoding="utf-8", errors="replace")
|
|
176
|
+
except OSError:
|
|
177
|
+
return None
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
# ---- engine evidence outside the SQL text ------------------------------------------------------------------
|
|
181
|
+
_ENGINE_WORDS = {
|
|
182
|
+
"clickhouse": "clickhouse", "click_house": "clickhouse", "chconn": "clickhouse", "chclient": "clickhouse",
|
|
183
|
+
"chdb": "clickhouse", "chpool": "clickhouse",
|
|
184
|
+
"postgres": "postgres", "postgresql": "postgres", "pgsql": "postgres", "psql": "postgres", "pg": "postgres",
|
|
185
|
+
"pgx": "postgres", "pgpool": "postgres", "pgconn": "postgres", "pgdb": "postgres", "pgclient": "postgres",
|
|
186
|
+
"mysql": "mysql", "mariadb": "mysql",
|
|
187
|
+
"sqlite": "sqlite", "sqlite3": "sqlite",
|
|
188
|
+
"mssql": "mssql", "sqlserver": "mssql",
|
|
189
|
+
}
|
|
190
|
+
_WORD_SPLIT = re.compile(r"[^A-Za-z0-9]+|(?<=[a-z0-9])(?=[A-Z])")
|
|
191
|
+
DURABLE_OBJECT_SQL = re.compile(r"(?:^|\.)storage\.sql$")
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _engine_words(text: str) -> list[str]:
|
|
195
|
+
found = []
|
|
196
|
+
for part in re.split(r"[^A-Za-z0-9_]+", text):
|
|
197
|
+
low = part.lower().strip("_")
|
|
198
|
+
if low in _ENGINE_WORDS:
|
|
199
|
+
found.append(_ENGINE_WORDS[low])
|
|
200
|
+
continue
|
|
201
|
+
for word in _WORD_SPLIT.split(part):
|
|
202
|
+
eng = _ENGINE_WORDS.get(word.lower())
|
|
203
|
+
if eng:
|
|
204
|
+
found.append(eng)
|
|
205
|
+
return found
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def receiver_engine(sink: str) -> str:
|
|
209
|
+
"""The engine a call's receiver names: `s.chConn.Select` -> clickhouse, `self.pg_pool.fetch` -> postgres.
|
|
210
|
+
Empty when the receiver names no engine or more than one. A Cloudflare Durable Object's own storage
|
|
211
|
+
(`this.ctx.storage.sql.exec`, `state.storage.sql.exec`) is SQLite, whatever the project's other database is."""
|
|
212
|
+
receiver = sink.rsplit(".", 1)[0] if "." in sink else ""
|
|
213
|
+
if DURABLE_OBJECT_SQL.search(receiver):
|
|
214
|
+
return "sqlite"
|
|
215
|
+
found = set(_engine_words(receiver))
|
|
216
|
+
return next(iter(found)) if len(found) == 1 else ""
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def path_engine(rel: str) -> str:
|
|
220
|
+
"""The engine a directory stands for: `sqlplugin/sqlite/admin.go`, `migrations/postgres/001.sql`,
|
|
221
|
+
`jdbc-mysql/src/...`. The deepest directory that names one wins; a name that says two says nothing.
|
|
222
|
+
A file counts only when its whole name is the engine (`postgres.go`): `clickhouse_cache.py` may
|
|
223
|
+
be a SQLite cache in front of ClickHouse."""
|
|
224
|
+
parts = rel.split("/")
|
|
225
|
+
stem = parts.pop().rsplit(".", 1)[0].lower()
|
|
226
|
+
if stem in _ENGINE_WORDS:
|
|
227
|
+
return _ENGINE_WORDS[stem]
|
|
228
|
+
for part in reversed(parts):
|
|
229
|
+
found = set(_engine_words(part))
|
|
230
|
+
if len(found) == 1:
|
|
231
|
+
return next(iter(found))
|
|
232
|
+
if found:
|
|
233
|
+
return ""
|
|
234
|
+
return ""
|