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,743 @@
|
|
|
1
|
+
"""JDBI, StringTemplate and SQL kept outside Java code.
|
|
2
|
+
|
|
3
|
+
* StringTemplate text in SQL (`<if(x)> ... <endif>`, `<name>`, `<items:{i | ...}>`): rendered so the statement
|
|
4
|
+
parses. An attribute becomes a «run-time part»; an optional block becomes one «if(cond): ...» run-time part; an
|
|
5
|
+
if / else chain, where exactly one arm is always taken, yields one statement per arm (chains on the same
|
|
6
|
+
conditions vary together), capped by `[discover] max_variants`; past the cap the first arm is kept and the
|
|
7
|
+
others are named in an «or: ...» part.
|
|
8
|
+
* StringTemplate group files (`Dao.sql.stg`) of DAO interfaces that use a template locator
|
|
9
|
+
(`@UseStringTemplateSqlLocator`, `@UseStringTemplate3StatementLocator`, Kill Bill's
|
|
10
|
+
`@KillBillSqlDaoStringTemplate`): each `@SqlQuery` / `@SqlUpdate` / `@SqlBatch` method is linked to the template
|
|
11
|
+
it names, rendered through the group and its imports, so the site has SQL and a caller. A method inherited from
|
|
12
|
+
a generic base DAO is rendered once per concrete DAO, with that DAO's templates.
|
|
13
|
+
* `handle.createQuery(...)` in a file that uses JDBI is SQL, not JPQL.
|
|
14
|
+
* JDO queries and MyBatis XML mapper statements are counted, not translated.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import os
|
|
20
|
+
import re
|
|
21
|
+
from itertools import product
|
|
22
|
+
|
|
23
|
+
from tree_sitter import Node
|
|
24
|
+
|
|
25
|
+
from .base import PLACEHOLDER, RawSite, is_test_path, read_text, trim
|
|
26
|
+
|
|
27
|
+
# The longest text kept inside one «if(...): ...» run-time part. A setting: `[discover] orm_template_marker_chars`.
|
|
28
|
+
DEFAULT_MARKER_CHARS = 4000
|
|
29
|
+
MARKER_CHARS = DEFAULT_MARKER_CHARS
|
|
30
|
+
# How deep template calls are followed in a group file. A setting: `[discover] orm_template_depth`.
|
|
31
|
+
DEFAULT_TEMPLATE_DEPTH = 24
|
|
32
|
+
TEMPLATE_DEPTH = DEFAULT_TEMPLATE_DEPTH
|
|
33
|
+
|
|
34
|
+
LOCATOR_ANNOS = {"UseStringTemplateSqlLocator", "UseStringTemplate3StatementLocator", "UseStringTemplateEngine",
|
|
35
|
+
"KillBillSqlDaoStringTemplate", "UseST4StatementLocator", "UseStringTemplateStatementLocator",
|
|
36
|
+
"ExternalizedSqlViaStringTemplate3"}
|
|
37
|
+
SQL_ANNOS = {"SqlQuery", "SqlUpdate", "SqlBatch", "SqlCall", "SqlScript"}
|
|
38
|
+
ST_HINT = re.compile(r"<(?:if\(|else>|endif>|elseif\()")
|
|
39
|
+
ST_ATTR = re.compile(r"<[A-Za-z_][\w.]*(?:\([^<>]*\))?(?:\s*;[^<>]*)?>|<[A-Za-z_]\w*\s*:\s*\{")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _txt(node: Node | None) -> str:
|
|
43
|
+
return node.text.decode("utf-8", "replace") if node is not None else ""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _max_variants() -> int:
|
|
47
|
+
from . import go as go_mod
|
|
48
|
+
return go_mod.MAX_VARIANTS
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# ------------------------------------------------------------------------------------ StringTemplate text
|
|
52
|
+
class TNode:
|
|
53
|
+
__slots__ = ("kind", "text", "args", "arms", "other", "body", "var")
|
|
54
|
+
|
|
55
|
+
def __init__(self, kind: str, text: str = "", args: str = "", arms=None, other=None, body=None, var: str = ""):
|
|
56
|
+
self.kind = kind # text | attr | call | if | iter
|
|
57
|
+
self.text = text # text; attribute or template name
|
|
58
|
+
self.args = args
|
|
59
|
+
self.arms = arms or [] # [(condition, [TNode])]
|
|
60
|
+
self.other = other # the else arm, or None
|
|
61
|
+
self.body = body or []
|
|
62
|
+
self.var = var
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
_SIMPLE = re.compile(r"([A-Za-z_][\w.]*)(\((?:[^()<>]|\([^()]*\))*\))?(\s*;[^<>]*)?$")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _find_close(text: str, start: int, opener: str, closer: str) -> int:
|
|
69
|
+
"""Index of the delimiter that closes the expression opened just before `start`."""
|
|
70
|
+
depth, i, n = 0, start, len(text)
|
|
71
|
+
quote = ""
|
|
72
|
+
while i < n:
|
|
73
|
+
c = text[i]
|
|
74
|
+
if quote:
|
|
75
|
+
if c == "\\":
|
|
76
|
+
i += 1
|
|
77
|
+
elif c == quote:
|
|
78
|
+
quote = ""
|
|
79
|
+
elif c == '"':
|
|
80
|
+
quote = c
|
|
81
|
+
elif c == "{":
|
|
82
|
+
depth += 1
|
|
83
|
+
elif c == "}":
|
|
84
|
+
depth -= 1
|
|
85
|
+
elif text.startswith(closer, i) and depth <= 0:
|
|
86
|
+
return i
|
|
87
|
+
i += 1
|
|
88
|
+
return -1
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def parse_template(text: str, left: str = "<", right: str = ">") -> list[TNode]:
|
|
92
|
+
"""A template body as a tree. Anything that is not StringTemplate syntax stays text (`a < b`, `<=`)."""
|
|
93
|
+
root: list[TNode] = []
|
|
94
|
+
stack: list[tuple[list[TNode], TNode | None]] = [(root, None)]
|
|
95
|
+
cur = root
|
|
96
|
+
i, n = 0, len(text)
|
|
97
|
+
buf: list[str] = []
|
|
98
|
+
|
|
99
|
+
def flush() -> None:
|
|
100
|
+
if buf:
|
|
101
|
+
cur.append(TNode("text", "".join(buf)))
|
|
102
|
+
buf.clear()
|
|
103
|
+
|
|
104
|
+
while i < n:
|
|
105
|
+
c = text[i]
|
|
106
|
+
if c == "\\" and text.startswith(left, i + 1):
|
|
107
|
+
buf.append(left)
|
|
108
|
+
i += 1 + len(left)
|
|
109
|
+
continue
|
|
110
|
+
if not text.startswith(left, i):
|
|
111
|
+
buf.append(c)
|
|
112
|
+
i += 1
|
|
113
|
+
continue
|
|
114
|
+
j = i + len(left)
|
|
115
|
+
if text.startswith("!", j): # <! comment !>
|
|
116
|
+
end = text.find("!" + right, j)
|
|
117
|
+
if end >= 0:
|
|
118
|
+
i = end + 1 + len(right)
|
|
119
|
+
continue
|
|
120
|
+
if text.startswith("\\", j): # <\n>, <\\>: an escape, no output
|
|
121
|
+
end = text.find(right, j)
|
|
122
|
+
if end >= 0 and end - j <= 4:
|
|
123
|
+
i = end + len(right)
|
|
124
|
+
continue
|
|
125
|
+
end = _find_close(text, j, left, right)
|
|
126
|
+
inner = text[j:end] if end >= 0 else ""
|
|
127
|
+
m = re.match(r"(if|elseif)\s*\((.*)\)\s*$", inner, re.S)
|
|
128
|
+
if m and "\n" not in inner:
|
|
129
|
+
flush()
|
|
130
|
+
if m.group(1) == "if":
|
|
131
|
+
node = TNode("if", arms=[(m.group(2).strip(), [])])
|
|
132
|
+
cur.append(node)
|
|
133
|
+
stack.append((cur, node))
|
|
134
|
+
cur = node.arms[-1][1]
|
|
135
|
+
elif stack[-1][1] is not None:
|
|
136
|
+
node = stack[-1][1]
|
|
137
|
+
node.arms.append((m.group(2).strip(), []))
|
|
138
|
+
cur = node.arms[-1][1]
|
|
139
|
+
i = end + len(right)
|
|
140
|
+
continue
|
|
141
|
+
if inner.strip() == "else" and stack[-1][1] is not None:
|
|
142
|
+
flush()
|
|
143
|
+
node = stack[-1][1]
|
|
144
|
+
node.other = []
|
|
145
|
+
cur = node.other
|
|
146
|
+
i = end + len(right)
|
|
147
|
+
continue
|
|
148
|
+
if inner.strip() == "endif" and stack[-1][1] is not None:
|
|
149
|
+
flush()
|
|
150
|
+
cur = stack.pop()[0]
|
|
151
|
+
i = end + len(right)
|
|
152
|
+
continue
|
|
153
|
+
it = re.match(r"([A-Za-z_][\w.]*)\s*:\s*\{\s*(?:(\w+)\s*\|)?(.*)\}\s*(?:;.*)?$", inner, re.S)
|
|
154
|
+
if it:
|
|
155
|
+
flush()
|
|
156
|
+
cur.append(TNode("iter", it.group(1), var=it.group(2) or "it", body=parse_template(it.group(3), left, right)))
|
|
157
|
+
i = end + len(right)
|
|
158
|
+
continue
|
|
159
|
+
sm = _SIMPLE.match(inner.strip()) if end >= 0 and "\n" not in inner else None
|
|
160
|
+
if sm:
|
|
161
|
+
flush()
|
|
162
|
+
if sm.group(2) is not None:
|
|
163
|
+
cur.append(TNode("call", sm.group(1), sm.group(2)[1:-1]))
|
|
164
|
+
else:
|
|
165
|
+
cur.append(TNode("attr", sm.group(1)))
|
|
166
|
+
i = end + len(right)
|
|
167
|
+
continue
|
|
168
|
+
buf.append(c)
|
|
169
|
+
i += 1
|
|
170
|
+
flush()
|
|
171
|
+
return root
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _chains(nodes: list[TNode], out: list[tuple]) -> None:
|
|
175
|
+
for n in nodes:
|
|
176
|
+
if n.kind == "if":
|
|
177
|
+
if n.other is not None:
|
|
178
|
+
sig = tuple(c for c, _ in n.arms)
|
|
179
|
+
if sig not in [s for s, _ in out]:
|
|
180
|
+
out.append((sig, len(n.arms) + 1))
|
|
181
|
+
for _, body in n.arms:
|
|
182
|
+
_chains(body, out)
|
|
183
|
+
if n.other is not None:
|
|
184
|
+
_chains(n.other, out)
|
|
185
|
+
elif n.kind == "iter":
|
|
186
|
+
_chains(n.body, out)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _flat(text: str) -> str:
|
|
190
|
+
return " ".join(text.replace("«", "<").replace("»", ">").split())
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class Group:
|
|
194
|
+
"""A StringTemplate group file: named templates, and the groups it imports."""
|
|
195
|
+
|
|
196
|
+
def __init__(self, path: str = ""):
|
|
197
|
+
self.path = path
|
|
198
|
+
self.templates: dict[str, tuple[list[str], str]] = {} # name -> (parameter names, body)
|
|
199
|
+
self.imports: list["Group"] = []
|
|
200
|
+
self.left, self.right = "<", ">"
|
|
201
|
+
self._parsed: dict[str, list[TNode]] = {}
|
|
202
|
+
|
|
203
|
+
def lookup(self, name: str, seen: set | None = None) -> tuple["Group", list[str], str] | None:
|
|
204
|
+
seen = seen or set()
|
|
205
|
+
if id(self) in seen:
|
|
206
|
+
return None
|
|
207
|
+
seen.add(id(self))
|
|
208
|
+
if name in self.templates:
|
|
209
|
+
params, body = self.templates[name]
|
|
210
|
+
return self, params, body
|
|
211
|
+
for g in self.imports:
|
|
212
|
+
hit = g.lookup(name, seen)
|
|
213
|
+
if hit is not None:
|
|
214
|
+
return hit
|
|
215
|
+
return None
|
|
216
|
+
|
|
217
|
+
def tree(self, name: str, body: str) -> list[TNode]:
|
|
218
|
+
t = self._parsed.get(name)
|
|
219
|
+
if t is None:
|
|
220
|
+
t = parse_template(body, self.left, self.right)
|
|
221
|
+
self._parsed[name] = t
|
|
222
|
+
return t
|
|
223
|
+
|
|
224
|
+
def names(self) -> list[str]:
|
|
225
|
+
return list(self.templates)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
_GROUP_DEF = re.compile(r"(?m)^[ \t]*([A-Za-z_]\w*)\s*\(([^()]*)\)\s*::=\s*")
|
|
229
|
+
_GROUP_IMPORT = re.compile(r'(?m)^\s*import\s+"([^"]+)"')
|
|
230
|
+
_GROUP_DELIMS = re.compile(r'(?m)^\s*delimiters\s+"([^"]+)"\s*,\s*"([^"]+)"')
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def parse_group(text: str, path: str = "") -> tuple[Group, list[str]]:
|
|
234
|
+
g = Group(path)
|
|
235
|
+
dm = _GROUP_DELIMS.search(text)
|
|
236
|
+
if dm:
|
|
237
|
+
g.left, g.right = dm.group(1), dm.group(2)
|
|
238
|
+
imports = _GROUP_IMPORT.findall(text)
|
|
239
|
+
pos = 0
|
|
240
|
+
while True:
|
|
241
|
+
m = _GROUP_DEF.search(text, pos)
|
|
242
|
+
if m is None:
|
|
243
|
+
break
|
|
244
|
+
i = m.end()
|
|
245
|
+
body = None
|
|
246
|
+
for opener, closer in (("<<", ">>"), ("<%", "%>")):
|
|
247
|
+
if text.startswith(opener, i):
|
|
248
|
+
end = text.find(closer + "\n", i)
|
|
249
|
+
if end < 0:
|
|
250
|
+
end = text.rfind(closer, i) if text.rstrip().endswith(closer) else text.find(closer, i)
|
|
251
|
+
if end >= 0:
|
|
252
|
+
body, pos = text[i + 2:end], end + 2
|
|
253
|
+
break
|
|
254
|
+
else:
|
|
255
|
+
if text.startswith('"', i):
|
|
256
|
+
sm = re.compile(r'"((?:[^"\\]|\\.)*)"').match(text, i)
|
|
257
|
+
if sm:
|
|
258
|
+
body, pos = re.sub(r"\\(.)", r"\1", sm.group(1)), sm.end()
|
|
259
|
+
if body is None:
|
|
260
|
+
pos = m.end()
|
|
261
|
+
continue
|
|
262
|
+
params = [p.split("=")[0].strip() for p in m.group(2).split(",") if p.strip()]
|
|
263
|
+
g.templates[m.group(1)] = (params, body.strip("\n"))
|
|
264
|
+
return g, imports
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
class Renderer:
|
|
268
|
+
def __init__(self, group: Group | None = None, defines: bool = True):
|
|
269
|
+
self.group = group
|
|
270
|
+
self.defines = defines
|
|
271
|
+
self.over_cap = False
|
|
272
|
+
self._depth = 0
|
|
273
|
+
|
|
274
|
+
def render(self, nodes: list[TNode], scope: dict[str, str | None], decisions: dict[tuple, int], depth: int = 0) -> str:
|
|
275
|
+
out: list[str] = []
|
|
276
|
+
for n in nodes:
|
|
277
|
+
if n.kind == "text":
|
|
278
|
+
out.append(n.text)
|
|
279
|
+
elif n.kind == "attr":
|
|
280
|
+
out.append(self._attr(n.text, scope))
|
|
281
|
+
elif n.kind == "call":
|
|
282
|
+
out.append(self._call(n, scope, decisions, depth))
|
|
283
|
+
elif n.kind == "iter":
|
|
284
|
+
inner = dict(scope)
|
|
285
|
+
inner[n.var] = None
|
|
286
|
+
inner["\0loop"] = n.var
|
|
287
|
+
out.append(self.render(n.body, inner, decisions, depth))
|
|
288
|
+
elif n.kind == "if":
|
|
289
|
+
out.append(self._if(n, scope, decisions, depth))
|
|
290
|
+
return "".join(out)
|
|
291
|
+
|
|
292
|
+
def _attr(self, name: str, scope: dict) -> str:
|
|
293
|
+
head = name.split(".")[0]
|
|
294
|
+
if head in scope:
|
|
295
|
+
value = scope[head]
|
|
296
|
+
if value is None: # a loop variable: its counters print nothing, its fields are run-time values
|
|
297
|
+
prop = name.split(".", 1)[1] if "." in name else ""
|
|
298
|
+
return "" if prop in ("index", "i", "i0", "hasNext", "first", "last") else "«" + name + "»"
|
|
299
|
+
return value if "." not in name else "«" + name + "»"
|
|
300
|
+
return "«" + name + "»"
|
|
301
|
+
|
|
302
|
+
def _args(self, text: str, scope: dict, decisions: dict, depth: int) -> list[str]:
|
|
303
|
+
out, cur, d, quote = [], [], 0, ""
|
|
304
|
+
for c in text:
|
|
305
|
+
if quote:
|
|
306
|
+
cur.append(c)
|
|
307
|
+
if c == quote:
|
|
308
|
+
quote = ""
|
|
309
|
+
elif c == '"':
|
|
310
|
+
quote = c
|
|
311
|
+
cur.append(c)
|
|
312
|
+
elif c == "(":
|
|
313
|
+
d += 1
|
|
314
|
+
cur.append(c)
|
|
315
|
+
elif c == ")":
|
|
316
|
+
d -= 1
|
|
317
|
+
cur.append(c)
|
|
318
|
+
elif c == "," and d == 0:
|
|
319
|
+
out.append("".join(cur).strip())
|
|
320
|
+
cur = []
|
|
321
|
+
else:
|
|
322
|
+
cur.append(c)
|
|
323
|
+
if "".join(cur).strip():
|
|
324
|
+
out.append("".join(cur).strip())
|
|
325
|
+
values = []
|
|
326
|
+
for a in out:
|
|
327
|
+
a = re.sub(r"^\w+\s*=\s*", "", a)
|
|
328
|
+
while a.startswith("(") and a.endswith(")"):
|
|
329
|
+
a = a[1:-1].strip()
|
|
330
|
+
if a.startswith('"') and a.endswith('"'):
|
|
331
|
+
values.append(a[1:-1])
|
|
332
|
+
else:
|
|
333
|
+
sub = parse_template("<" + a + ">")
|
|
334
|
+
values.append(self.render(sub, scope, decisions, depth + 1))
|
|
335
|
+
return values
|
|
336
|
+
|
|
337
|
+
def _call(self, n: TNode, scope: dict, decisions: dict, depth: int) -> str:
|
|
338
|
+
hit = self.group.lookup(n.text) if self.group is not None else None
|
|
339
|
+
if hit is None or depth > TEMPLATE_DEPTH:
|
|
340
|
+
return "«" + n.text + "(" + _flat(n.args) + ")»"
|
|
341
|
+
owner, params, body = hit
|
|
342
|
+
values = self._args(n.args, scope, decisions, depth)
|
|
343
|
+
inner: dict[str, str | None] = {p: (values[k] if k < len(values) else "") for k, p in enumerate(params)}
|
|
344
|
+
return self.render(owner.tree(n.text, body), inner, decisions, depth + 1)
|
|
345
|
+
|
|
346
|
+
def _truth(self, cond: str, scope: dict) -> bool | None:
|
|
347
|
+
"""A condition on a template parameter bound to a literal is decided here; anything else at run time."""
|
|
348
|
+
neg = cond.startswith("!")
|
|
349
|
+
name = cond.lstrip("!").strip()
|
|
350
|
+
head, _, prop = name.partition(".")
|
|
351
|
+
if head in scope and scope[head] is None and prop in ("hasNext", "first", "last", "index", "i", "i0"):
|
|
352
|
+
return neg # the body of an iteration is rendered once, as its only item
|
|
353
|
+
if re.fullmatch(r"\w+", name) and name in scope and scope[name] is not None and "«" not in scope[name]:
|
|
354
|
+
return bool(scope[name]) != neg
|
|
355
|
+
call = re.fullmatch(r"(\w+)\((.*)\)", name, re.S)
|
|
356
|
+
if call and self.group is not None and self.group.lookup(call.group(1)) is not None and self._depth < TEMPLATE_DEPTH:
|
|
357
|
+
self._depth += 1
|
|
358
|
+
try:
|
|
359
|
+
text = self._call(TNode("call", call.group(1), call.group(2)), scope, {}, 1)
|
|
360
|
+
finally:
|
|
361
|
+
self._depth -= 1
|
|
362
|
+
if "«" not in text:
|
|
363
|
+
return bool(text.strip()) != neg
|
|
364
|
+
return None
|
|
365
|
+
|
|
366
|
+
def _if(self, n: TNode, scope: dict, decisions: dict, depth: int) -> str:
|
|
367
|
+
for k, (cond, body) in enumerate(n.arms):
|
|
368
|
+
known = self._truth(cond, scope)
|
|
369
|
+
if known is True:
|
|
370
|
+
return self.render(body, scope, decisions, depth)
|
|
371
|
+
if known is None:
|
|
372
|
+
break
|
|
373
|
+
else:
|
|
374
|
+
return self.render(n.other, scope, decisions, depth) if n.other is not None else ""
|
|
375
|
+
arms = [(c, b) for c, b in n.arms if self._truth(c, scope) is not False]
|
|
376
|
+
if n.other is None:
|
|
377
|
+
parts = []
|
|
378
|
+
for i, (cond, body) in enumerate(arms):
|
|
379
|
+
text = _flat(self.render(body, scope, decisions, depth))
|
|
380
|
+
parts.append(("if" if i == 0 else "elseif") + f"({_flat(cond)}): {text}")
|
|
381
|
+
marker = "; ".join(parts)
|
|
382
|
+
if len(marker) > MARKER_CHARS:
|
|
383
|
+
marker = marker[: MARKER_CHARS - 1] + "…"
|
|
384
|
+
return " «" + marker + "» "
|
|
385
|
+
sig = tuple(c for c, _ in n.arms)
|
|
386
|
+
bodies = [b for _, b in arms] + [n.other]
|
|
387
|
+
if self.over_cap:
|
|
388
|
+
first = self.render(bodies[0], scope, decisions, depth)
|
|
389
|
+
rest = " ".join("«or: " + trim(_flat(self.render(b, scope, decisions, depth)), MARKER_CHARS) + "»" for b in bodies[1:])
|
|
390
|
+
return first + " " + rest + " "
|
|
391
|
+
pick = min(decisions.get(sig, 0), len(bodies) - 1)
|
|
392
|
+
return self.render(bodies[pick], scope, decisions, depth)
|
|
393
|
+
|
|
394
|
+
def variants(self, nodes: list[TNode], scope: dict | None = None) -> list[str]:
|
|
395
|
+
"""Every statement the template can produce through its if / else chains, up to the variant limit."""
|
|
396
|
+
chains: list[tuple] = []
|
|
397
|
+
_chains(nodes, chains)
|
|
398
|
+
total = 1
|
|
399
|
+
for _, count in chains:
|
|
400
|
+
total *= count
|
|
401
|
+
limit = _max_variants()
|
|
402
|
+
if total > limit:
|
|
403
|
+
self.over_cap = True
|
|
404
|
+
return [self.render(nodes, dict(scope or {}), {})]
|
|
405
|
+
out: list[str] = []
|
|
406
|
+
for combo in product(*[range(count) for _, count in chains]):
|
|
407
|
+
text = self.render(nodes, dict(scope or {}), {sig: pick for (sig, _), pick in zip(chains, combo)})
|
|
408
|
+
if text not in out:
|
|
409
|
+
out.append(text)
|
|
410
|
+
return out
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def has_template_syntax(sql: str, defines: bool) -> bool:
|
|
414
|
+
return bool(ST_HINT.search(sql)) or (defines and bool(ST_ATTR.search(sql)))
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def render_sql(sql: str, defines: bool = True) -> list[str]:
|
|
418
|
+
"""SQL with StringTemplate syntax as one or more statements with run-time parts. `defines`: a bare
|
|
419
|
+
`<name>` is an attribute (JDBI @Define, a StringTemplate attribute)."""
|
|
420
|
+
held: list[str] = []
|
|
421
|
+
|
|
422
|
+
def hold(m: re.Match) -> str:
|
|
423
|
+
held.append(m.group(0))
|
|
424
|
+
return f"\x00{len(held) - 1}\x00"
|
|
425
|
+
|
|
426
|
+
text = PLACEHOLDER.sub(hold, sql)
|
|
427
|
+
nodes = parse_template(text)
|
|
428
|
+
if not defines:
|
|
429
|
+
_plain_attrs(nodes)
|
|
430
|
+
out = []
|
|
431
|
+
for v in Renderer().variants(nodes):
|
|
432
|
+
v = re.sub(r"\x00(\d+)\x00", lambda m: held[int(m.group(1))], v)
|
|
433
|
+
out.append(_tidy(v))
|
|
434
|
+
return out
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _plain_attrs(nodes: list[TNode]) -> None:
|
|
438
|
+
for n in nodes:
|
|
439
|
+
if n.kind in ("attr", "call"):
|
|
440
|
+
n.kind, n.text = "text", "<" + n.text + ("(" + n.args + ")" if n.kind == "call" else "") + ">"
|
|
441
|
+
for _, body in n.arms:
|
|
442
|
+
_plain_attrs(body)
|
|
443
|
+
if n.other:
|
|
444
|
+
_plain_attrs(n.other)
|
|
445
|
+
_plain_attrs(n.body)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _tidy(text: str) -> str:
|
|
449
|
+
text = re.sub(r"[ \t]+\n", "\n", text)
|
|
450
|
+
text = re.sub(r"\n\s*\n+", "\n", text)
|
|
451
|
+
return text.strip().rstrip(";").strip()
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
# ----------------------------------------------------------------------------------------- group files
|
|
455
|
+
def _load_groups(ctx, files: list[str]) -> dict[str, Group]:
|
|
456
|
+
"""Every `.stg` group file of the repository, with imports linked, by path."""
|
|
457
|
+
groups: dict[str, Group] = {}
|
|
458
|
+
wanted: dict[str, list[str]] = {}
|
|
459
|
+
for rel in files:
|
|
460
|
+
if not rel.endswith(".stg"):
|
|
461
|
+
continue
|
|
462
|
+
text = read_text(ctx.root / rel)
|
|
463
|
+
if text is None:
|
|
464
|
+
continue
|
|
465
|
+
g, imports = parse_group(text, rel)
|
|
466
|
+
groups[rel] = g
|
|
467
|
+
wanted[rel] = imports
|
|
468
|
+
for rel, imports in wanted.items():
|
|
469
|
+
for imp in imports:
|
|
470
|
+
target = next((p for p in groups if p.endswith("/" + imp) or p == imp), None)
|
|
471
|
+
if target is None:
|
|
472
|
+
base = os.path.basename(imp)
|
|
473
|
+
cands = [p for p in groups if os.path.basename(p) == base]
|
|
474
|
+
target = cands[0] if len(cands) == 1 else None
|
|
475
|
+
if target is not None and target != rel:
|
|
476
|
+
groups[rel].imports.append(groups[target])
|
|
477
|
+
return groups
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def _annos(node: Node) -> dict[str, dict[str, Node]]:
|
|
481
|
+
out: dict[str, dict[str, Node]] = {}
|
|
482
|
+
mods = next((c for c in node.children if c.type == "modifiers"), None)
|
|
483
|
+
if mods is None:
|
|
484
|
+
return out
|
|
485
|
+
for a in mods.children:
|
|
486
|
+
if a.type in ("annotation", "marker_annotation"):
|
|
487
|
+
args: dict[str, Node] = {}
|
|
488
|
+
al = a.child_by_field_name("arguments")
|
|
489
|
+
for x in (al.named_children if al is not None else ()):
|
|
490
|
+
if x.type == "element_value_pair":
|
|
491
|
+
args[_txt(x.child_by_field_name("key"))] = x.child_by_field_name("value")
|
|
492
|
+
elif x.type not in ("line_comment", "block_comment"):
|
|
493
|
+
args["value"] = x
|
|
494
|
+
out[_txt(a.child_by_field_name("name")).split(".")[-1]] = args
|
|
495
|
+
return out
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def _dao_methods(jf, iface: Node) -> list[tuple[Node, str, str]]:
|
|
499
|
+
"""(method, annotation, template name) for the SQL-object methods an interface declares."""
|
|
500
|
+
out = []
|
|
501
|
+
body = iface.child_by_field_name("body")
|
|
502
|
+
for meth in (body.named_children if body is not None else ()):
|
|
503
|
+
if meth.type != "method_declaration":
|
|
504
|
+
continue
|
|
505
|
+
an = _annos(meth)
|
|
506
|
+
kind = next((a for a in SQL_ANNOS if a in an), "")
|
|
507
|
+
if not kind:
|
|
508
|
+
continue
|
|
509
|
+
value = an[kind].get("value")
|
|
510
|
+
name = _txt(meth.child_by_field_name("name"))
|
|
511
|
+
template = name
|
|
512
|
+
if value is not None:
|
|
513
|
+
r = None
|
|
514
|
+
try:
|
|
515
|
+
r = jf.resolve(value, value, 0)
|
|
516
|
+
except Exception:
|
|
517
|
+
r = None
|
|
518
|
+
if r is None or r.dynamic:
|
|
519
|
+
continue
|
|
520
|
+
if re.search(r"\s", r.text.strip()):
|
|
521
|
+
continue # literal SQL: reported by the annotation sink
|
|
522
|
+
template = r.text.strip()
|
|
523
|
+
out.append((meth, kind, template))
|
|
524
|
+
return out
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def link_groups(ctx, stats, files: list[str]) -> None:
|
|
528
|
+
repo = ctx.repo
|
|
529
|
+
daos: list[tuple[object, Node, str]] = []
|
|
530
|
+
for jf in repo.files:
|
|
531
|
+
for name, nodes in jf.classes.items():
|
|
532
|
+
for node in nodes:
|
|
533
|
+
if node.type not in ("interface_declaration", "class_declaration"):
|
|
534
|
+
continue
|
|
535
|
+
if set(_annos(node)) & LOCATOR_ANNOS:
|
|
536
|
+
daos.append((jf, node, name))
|
|
537
|
+
if not daos:
|
|
538
|
+
return
|
|
539
|
+
groups = _load_groups(ctx, files)
|
|
540
|
+
by_base: dict[str, list[str]] = {}
|
|
541
|
+
for rel in groups:
|
|
542
|
+
by_base.setdefault(os.path.basename(rel), []).append(rel)
|
|
543
|
+
|
|
544
|
+
def group_for(jf, name: str) -> Group | None:
|
|
545
|
+
cands = by_base.get(name + ".sql.stg", []) + by_base.get(name + ".stg", [])
|
|
546
|
+
if len(cands) > 1:
|
|
547
|
+
pkg = next((_txt(c).replace("package", "").strip(" ;\n") for c in jf.root.children if c.type == "package_declaration"), "")
|
|
548
|
+
path = pkg.replace(".", "/")
|
|
549
|
+
narrowed = [c for c in cands if path and path in c]
|
|
550
|
+
cands = narrowed or cands
|
|
551
|
+
return groups[cands[0]] if cands else None
|
|
552
|
+
|
|
553
|
+
def inherited(jf, node: Node, depth: int = 0) -> list[tuple[object, Node, str]]:
|
|
554
|
+
out = []
|
|
555
|
+
if depth > 6:
|
|
556
|
+
return out
|
|
557
|
+
for sup in jf.supers(node):
|
|
558
|
+
for sjf, snode in repo.classes.get(sup, ()):
|
|
559
|
+
if snode.type == "interface_declaration":
|
|
560
|
+
out.append((sjf, snode, sup))
|
|
561
|
+
out.extend(inherited(sjf, snode, depth + 1))
|
|
562
|
+
return out
|
|
563
|
+
|
|
564
|
+
bases = {sname for jf, node, _name in daos for _sjf, _snode, sname in inherited(jf, node)}
|
|
565
|
+
seen_sites: set[tuple] = set()
|
|
566
|
+
for jf, node, name in daos:
|
|
567
|
+
if name in bases and node.child_by_field_name("type_parameters") is not None:
|
|
568
|
+
continue # rendered once per concrete DAO that extends it
|
|
569
|
+
g = group_for(jf, name)
|
|
570
|
+
test = is_test_path(jf.rel) or "/src/test/" in "/" + jf.rel
|
|
571
|
+
own = [(jf, node, name)]
|
|
572
|
+
sources = own + inherited(jf, node) if g is not None else own
|
|
573
|
+
done: set[int] = set()
|
|
574
|
+
for sjf, snode, sname in sources:
|
|
575
|
+
if snode.id in done:
|
|
576
|
+
continue
|
|
577
|
+
done.add(snode.id)
|
|
578
|
+
for meth, kind, template in _dao_methods(sjf, snode):
|
|
579
|
+
is_own = sjf is jf and snode.id == node.id
|
|
580
|
+
if is_own:
|
|
581
|
+
stats.seen("jdbi-stringtemplate", test)
|
|
582
|
+
line = meth.start_point[0] + 1
|
|
583
|
+
if g is None:
|
|
584
|
+
if is_own:
|
|
585
|
+
stats.miss("jdbi-stringtemplate", "template group file of the DAO not found", sjf.rel, line, test)
|
|
586
|
+
continue
|
|
587
|
+
hit = g.lookup(template)
|
|
588
|
+
if hit is None:
|
|
589
|
+
if is_own:
|
|
590
|
+
stats.miss("jdbi-stringtemplate", "template not found in the group or its imports", sjf.rel, line, test)
|
|
591
|
+
continue
|
|
592
|
+
owner, params, body = hit
|
|
593
|
+
r = Renderer(g)
|
|
594
|
+
try:
|
|
595
|
+
texts = r.variants(owner.tree(template, body), {p: "«" + p + "»" for p in params})
|
|
596
|
+
except RecursionError:
|
|
597
|
+
if is_own:
|
|
598
|
+
stats.miss("jdbi-stringtemplate", "template nested too deeply", sjf.rel, line, test)
|
|
599
|
+
continue
|
|
600
|
+
texts = [t for t in (_tidy(x) for x in texts) if t]
|
|
601
|
+
name_node = meth.child_by_field_name("name")
|
|
602
|
+
n = 0
|
|
603
|
+
for text in texts:
|
|
604
|
+
key = (sjf.rel, line, text)
|
|
605
|
+
if key in seen_sites:
|
|
606
|
+
continue
|
|
607
|
+
seen_sites.add(key)
|
|
608
|
+
dynamic = bool(PLACEHOLDER.search(text))
|
|
609
|
+
s = RawSite(
|
|
610
|
+
file=sjf.rel, line=name_node.start_point[0] + 1, end_line=meth.end_point[0] + 1, language="java",
|
|
611
|
+
kind="call", sink="@" + kind, symbol=sjf.symbol(name_node), sql=text,
|
|
612
|
+
resolution="template" if dynamic else "file", expr=template, in_loop=False, engine_hint="",
|
|
613
|
+
is_test=is_test_path(sjf.rel) or "/src/test/" in "/" + sjf.rel, known_sink=True)
|
|
614
|
+
note = f"template {template} of {owner.path}"
|
|
615
|
+
if not is_own:
|
|
616
|
+
note += f", rendered with the templates of {name} ({g.path}): the method is inherited from {sname}"
|
|
617
|
+
s.orm = {"library": "jdbi-stringtemplate", "model_or_table": g.path, "operation": template,
|
|
618
|
+
"confidence": "high", "notes": note}
|
|
619
|
+
ctx.out.append(s)
|
|
620
|
+
n += 1
|
|
621
|
+
if is_own:
|
|
622
|
+
if n:
|
|
623
|
+
stats.hit("jdbi-stringtemplate", n, test)
|
|
624
|
+
else:
|
|
625
|
+
stats.miss("jdbi-stringtemplate", "template renders to nothing", sjf.rel, line, test)
|
|
626
|
+
elif n and not test:
|
|
627
|
+
stats.sites["jdbi-stringtemplate"] += n
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
# ---------------------------------------------------------------------------------- sites found already
|
|
631
|
+
JDBI_IMPORT = ("org.jdbi", "org.skife.jdbi")
|
|
632
|
+
JPA_IMPORT = ("jakarta.persistence", "javax.persistence", "org.hibernate")
|
|
633
|
+
JDO_IMPORT = ("javax.jdo", "org.datanucleus")
|
|
634
|
+
ST_IMPORT = ("org.stringtemplate", "org.antlr.stringtemplate")
|
|
635
|
+
SQLISH = re.compile(r"^\s*(?:--[^\n]*\n\s*|/\*.*?\*/\s*)*\(?\s*(SELECT|INSERT|UPDATE|DELETE|WITH|CREATE|ALTER|DROP|TRUNCATE|MERGE|CALL|EXPLAIN|SET|LOCK|ANALYZE|VACUUM|REFRESH|COPY|GRANT|COMMENT)\b", re.I | re.S)
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def prepare(ctx, sites: list[RawSite], stats) -> set[int]:
|
|
639
|
+
"""Before the JPA pass: `createQuery` text in a JDBI file is SQL; in a JDO file it is JDOQL (counted).
|
|
640
|
+
Returns the sites that are not JPQL although the sink rule said so."""
|
|
641
|
+
by_rel = {jf.rel: jf for jf in ctx.repo.files}
|
|
642
|
+
not_jpql: set[int] = set()
|
|
643
|
+
for s in sites:
|
|
644
|
+
if s.language != "java" or s.engine_hint != "jpql":
|
|
645
|
+
continue
|
|
646
|
+
jf = by_rel.get(s.file)
|
|
647
|
+
imports = jf.imports if jf is not None else []
|
|
648
|
+
if any(i.startswith(JPA_IMPORT) for i in imports):
|
|
649
|
+
continue
|
|
650
|
+
if any(i.startswith(JDBI_IMPORT) for i in imports) and (s.sql is None or SQLISH.match(s.sql)):
|
|
651
|
+
if s.sql is not None:
|
|
652
|
+
s.orm = {"id_from": [s.sql, "jpql"]}
|
|
653
|
+
s.engine_hint = "" # handle.createQuery(...) of JDBI takes SQL
|
|
654
|
+
not_jpql.add(id(s))
|
|
655
|
+
elif any(i.startswith(JDO_IMPORT) for i in imports):
|
|
656
|
+
stats.seen("jdo", s.is_test)
|
|
657
|
+
stats.miss("jdo", "JDOQL is not translated", s.file, s.line, s.is_test)
|
|
658
|
+
not_jpql.add(id(s))
|
|
659
|
+
return not_jpql
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
def rewrite_sites(ctx, sites: list[RawSite], stats) -> list[RawSite]:
|
|
663
|
+
by_rel = {jf.rel: jf for jf in ctx.repo.files}
|
|
664
|
+
st_project = any(any(i.startswith(ST_IMPORT) for i in jf.imports) for jf in ctx.repo.files)
|
|
665
|
+
out: list[RawSite] = []
|
|
666
|
+
for s in sites:
|
|
667
|
+
if s.language != "java" or s.sql is None:
|
|
668
|
+
out.append(s)
|
|
669
|
+
continue
|
|
670
|
+
jf = by_rel.get(s.file)
|
|
671
|
+
imports = jf.imports if jf is not None else []
|
|
672
|
+
jdbi = any(i.startswith(JDBI_IMPORT) for i in imports)
|
|
673
|
+
if s.engine_hint in ("jpql", "cypher"):
|
|
674
|
+
out.append(s)
|
|
675
|
+
continue
|
|
676
|
+
defines = jdbi or st_project or any(i.startswith(ST_IMPORT) for i in imports)
|
|
677
|
+
if not has_template_syntax(s.sql, defines) or (not ST_HINT.search(s.sql) and not defines):
|
|
678
|
+
out.append(s)
|
|
679
|
+
continue
|
|
680
|
+
stats.seen("stringtemplate", s.is_test)
|
|
681
|
+
try:
|
|
682
|
+
texts = [t for t in render_sql(s.sql, defines) if t]
|
|
683
|
+
except RecursionError:
|
|
684
|
+
texts = []
|
|
685
|
+
if not texts or texts == [s.sql.strip()]:
|
|
686
|
+
stats.miss("stringtemplate", "template syntax not recognised", s.file, s.line, s.is_test)
|
|
687
|
+
out.append(s)
|
|
688
|
+
continue
|
|
689
|
+
original = s.sql
|
|
690
|
+
for k, text in enumerate(texts):
|
|
691
|
+
if k == 0:
|
|
692
|
+
t = s
|
|
693
|
+
else:
|
|
694
|
+
t = RawSite(**{f: getattr(s, f) for f in s.__dataclass_fields__})
|
|
695
|
+
t.orm = None
|
|
696
|
+
t.sql = text
|
|
697
|
+
if t.resolution in ("literal", "constant") and PLACEHOLDER.search(text):
|
|
698
|
+
t.resolution = "template"
|
|
699
|
+
if k == 0 and not (t.orm and "library" in t.orm):
|
|
700
|
+
t.orm = {"id_from": (s.orm or {}).get("id_from") or [original, s.engine_hint]}
|
|
701
|
+
out.append(t)
|
|
702
|
+
stats.hit("stringtemplate", len(texts), s.is_test)
|
|
703
|
+
return out
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
MAPPER_XML = re.compile(r"<mapper\s+namespace\s*=")
|
|
707
|
+
MAPPER_STMT = re.compile(r"<(select|insert|update|delete)\s+[^>]*\bid\s*=")
|
|
708
|
+
|
|
709
|
+
|
|
710
|
+
def count_mybatis(ctx, stats, files: list[str]) -> None:
|
|
711
|
+
for rel in files:
|
|
712
|
+
if not rel.endswith(".xml") or "apper" not in os.path.basename(rel):
|
|
713
|
+
continue
|
|
714
|
+
text = read_text(ctx.root / rel)
|
|
715
|
+
if text is None or not MAPPER_XML.search(text):
|
|
716
|
+
continue
|
|
717
|
+
test = is_test_path(rel)
|
|
718
|
+
for m in MAPPER_STMT.finditer(text):
|
|
719
|
+
stats.seen("mybatis-xml", test)
|
|
720
|
+
stats.miss("mybatis-xml", "MyBatis XML mapper statements are counted, not linked to mapper methods", rel,
|
|
721
|
+
text.count("\n", 0, m.start()) + 1, test)
|
|
722
|
+
|
|
723
|
+
|
|
724
|
+
def apply_settings(settings: dict | None) -> None:
|
|
725
|
+
global MARKER_CHARS, TEMPLATE_DEPTH
|
|
726
|
+
settings = settings or {}
|
|
727
|
+
MARKER_CHARS = int(settings.get("orm_template_marker_chars", DEFAULT_MARKER_CHARS))
|
|
728
|
+
TEMPLATE_DEPTH = int(settings.get("orm_template_depth", DEFAULT_TEMPLATE_DEPTH))
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
def extend(ctx, sites: list[RawSite], stats) -> list[RawSite]:
|
|
732
|
+
sites = rewrite_sites(ctx, sites, stats)
|
|
733
|
+
needs_files = any(
|
|
734
|
+
any(i.startswith(JDBI_IMPORT + ("org.apache.ibatis", "org.mybatis")) or "StringTemplate" in i for i in jf.imports)
|
|
735
|
+
for jf in ctx.repo.files)
|
|
736
|
+
if needs_files:
|
|
737
|
+
from . import list_files
|
|
738
|
+
try:
|
|
739
|
+
files = list_files(ctx.root)
|
|
740
|
+
except Exception:
|
|
741
|
+
files = []
|
|
742
|
+
link_groups(ctx, stats, files) # MyBatis mapper XML is read by xml_mapper (and linked by orm_mybatis)
|
|
743
|
+
return sites
|