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,730 @@
|
|
|
1
|
+
"""MyBatis and MyBatis-Plus from the Java side: the calls of mapper interfaces, with the statement each one sends.
|
|
2
|
+
|
|
3
|
+
Called by `orm_java.extend` with every parsed Java file. It
|
|
4
|
+
|
|
5
|
+
* finds the mapper interfaces: the ones a mapper XML's namespace names, the ones annotated `@Mapper`, and the ones
|
|
6
|
+
that extend MyBatis-Plus `BaseMapper<Entity>`;
|
|
7
|
+
* renders `<script>` dynamic SQL in `@Select` / `@Insert` / `@Update` / `@Delete` with the mapper XML engine
|
|
8
|
+
(xml_mapper), one site per variant;
|
|
9
|
+
* gives every call of a mapper method (`userMapper.queryByName(name)`) the statement it sends: the mapper XML
|
|
10
|
+
statement with that id, the method's SQL annotation, or, for the methods MyBatis-Plus `BaseMapper` provides
|
|
11
|
+
(`selectById`, `insert`, `selectList(wrapper)` ...), the statement MyBatis-Plus writes from the entity's
|
|
12
|
+
`@TableName` / `@TableId` / `@TableField` mapping and the `QueryWrapper` / `LambdaQueryWrapper` conditions;
|
|
13
|
+
* counts what it cannot tell (a `@SelectProvider` method, a generic base mapper, a wrapper built elsewhere) with the
|
|
14
|
+
reason.
|
|
15
|
+
|
|
16
|
+
Sites: `resolution = "orm"`, orm {library: "mybatis" | "mybatis-plus", model_or_table, operation, confidence,
|
|
17
|
+
notes, mechanism}. A wrapper condition decided at run time is a «run-time part»; a condition guarded by a run-time
|
|
18
|
+
boolean (`eq(name != null, User::getName, name)`) gives a variant without it and one with it.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import re
|
|
24
|
+
|
|
25
|
+
from tree_sitter import Node
|
|
26
|
+
|
|
27
|
+
from . import xml_mapper
|
|
28
|
+
from .base import RawSite, trim
|
|
29
|
+
|
|
30
|
+
SQL_ANNOS = ("Select", "Insert", "Update", "Delete")
|
|
31
|
+
PROVIDER_ANNOS = ("SelectProvider", "InsertProvider", "UpdateProvider", "DeleteProvider")
|
|
32
|
+
BASE_MAPPERS = {"BaseMapper", "Mapper", "MPJBaseMapper"}
|
|
33
|
+
WRAPPER_TYPES = re.compile(r"\b(?:Lambda)?(?:Query|Update)(?:Chain)?Wrapper\b|\bWrapper\b|\bMPJLambdaWrapper\b")
|
|
34
|
+
OPS = {"eq": "=", "ne": "<>", "gt": ">", "ge": ">=", "lt": "<", "le": "<="}
|
|
35
|
+
LIKES = {"like": "LIKE", "notLike": "NOT LIKE", "likeLeft": "LIKE", "likeRight": "LIKE", "notLikeLeft": "NOT LIKE",
|
|
36
|
+
"notLikeRight": "NOT LIKE"}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _txt(node: Node | None) -> str:
|
|
40
|
+
return node.text.decode("utf-8", "replace") if node is not None else ""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _named(node: Node | None) -> list[Node]:
|
|
44
|
+
return [c for c in node.named_children if c.type not in ("line_comment", "block_comment")] if node is not None else []
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _snake(name: str) -> str:
|
|
48
|
+
s = re.sub(r"(?<=[a-z0-9])([A-Z])", r"_\1", name)
|
|
49
|
+
s = re.sub(r"(?<=[A-Z])([A-Z][a-z])", r"_\1", s)
|
|
50
|
+
return s.lower()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _mark(text: str) -> str:
|
|
54
|
+
return "«" + trim(" ".join(text.split()), 80).replace("»", ">").replace("«", "<") + "»"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _string(node: Node | None) -> str | None:
|
|
58
|
+
if node is None or node.type != "string_literal":
|
|
59
|
+
return None
|
|
60
|
+
t = _txt(node)
|
|
61
|
+
if t.startswith('"""'):
|
|
62
|
+
return t[3:-3]
|
|
63
|
+
return t[1:-1].replace('\\"', '"')
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# ---- the model ----------------------------------------------------------------------------------------------------
|
|
67
|
+
class Entity:
|
|
68
|
+
def __init__(self, name: str, table: str, explicit: bool):
|
|
69
|
+
self.name, self.table, self.explicit = name, table, explicit
|
|
70
|
+
self.columns: list[tuple[str, str]] = [] # (field, column)
|
|
71
|
+
self.id_field, self.id_column = "id", "id"
|
|
72
|
+
self.logic: tuple[str, str, str] | None = None # (column, live value, deleted value)
|
|
73
|
+
|
|
74
|
+
def column(self, field: str) -> str:
|
|
75
|
+
for f, c in self.columns:
|
|
76
|
+
if f == field:
|
|
77
|
+
return c
|
|
78
|
+
return _snake(field)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class Iface:
|
|
82
|
+
def __init__(self, jf, node: Node, fqn: str):
|
|
83
|
+
self.jf, self.node, self.fqn = jf, node, fqn
|
|
84
|
+
self.name = fqn.rsplit(".", 1)[-1]
|
|
85
|
+
self.entity: str = "" # BaseMapper<Entity>
|
|
86
|
+
self.plus = False
|
|
87
|
+
self.annotated: dict[str, list[str]] = {} # method -> SQL texts of its annotation sites
|
|
88
|
+
self.methods: set[str] = set()
|
|
89
|
+
self.providers: set[str] = set()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class Pass:
|
|
93
|
+
def __init__(self, ctx, sites: list[RawSite], stats):
|
|
94
|
+
self.ctx, self.sites, self.stats = ctx, sites, stats
|
|
95
|
+
self.mappers: dict[str, list] = {}
|
|
96
|
+
self.ifaces: dict[str, Iface] = {} # simple name -> interface
|
|
97
|
+
self.entities: dict[str, Entity | None] = {}
|
|
98
|
+
self.engine_hint = ""
|
|
99
|
+
|
|
100
|
+
# ---- setup
|
|
101
|
+
def load_xml(self) -> None:
|
|
102
|
+
if not any(any(i.startswith(("org.apache.ibatis", "org.mybatis", "com.baomidou", "tk.mybatis")) for i in jf.imports)
|
|
103
|
+
for jf in self.ctx.repo.files):
|
|
104
|
+
return
|
|
105
|
+
from . import list_files
|
|
106
|
+
try:
|
|
107
|
+
files = [f for f in list_files(self.ctx.root) if f.endswith(".xml")]
|
|
108
|
+
except Exception:
|
|
109
|
+
files = []
|
|
110
|
+
self.mappers = xml_mapper.load(self.ctx.root, files) if files else {}
|
|
111
|
+
|
|
112
|
+
def find_ifaces(self) -> None:
|
|
113
|
+
for jf in self.ctx.repo.files:
|
|
114
|
+
pkg = ""
|
|
115
|
+
for c in jf.root.children:
|
|
116
|
+
if c.type == "package_declaration":
|
|
117
|
+
pkg = re.sub(r"^package\s+|\s*;\s*$", "", _txt(c)).strip()
|
|
118
|
+
for name, nodes in jf.classes.items():
|
|
119
|
+
for node in nodes:
|
|
120
|
+
if node.type != "interface_declaration":
|
|
121
|
+
continue
|
|
122
|
+
fqn = f"{pkg}.{name}" if pkg else name
|
|
123
|
+
supers_text = "".join(_txt(c) for c in node.children if c.type in ("extends_interfaces", "super_interfaces"))
|
|
124
|
+
plus = re.search(r"\b(?:BaseMapper|MPJBaseMapper)\s*<\s*([\w.]+)", supers_text)
|
|
125
|
+
annotated = "@Mapper" in _txt(next((c for c in node.children if c.type == "modifiers"), None))
|
|
126
|
+
if fqn not in self.mappers and not plus and not annotated:
|
|
127
|
+
continue
|
|
128
|
+
f = Iface(jf, node, fqn)
|
|
129
|
+
if plus:
|
|
130
|
+
f.plus, f.entity = True, plus.group(1).rsplit(".", 1)[-1]
|
|
131
|
+
self._methods(f)
|
|
132
|
+
self.ifaces.setdefault(name, f)
|
|
133
|
+
# a mapper that extends another mapper interface of the repository inherits its entity
|
|
134
|
+
for f in self.ifaces.values():
|
|
135
|
+
if not f.entity:
|
|
136
|
+
for sup in f.jf.supers(f.node):
|
|
137
|
+
g = self.ifaces.get(sup)
|
|
138
|
+
if g is not None and g.entity:
|
|
139
|
+
f.entity, f.plus = g.entity, g.plus
|
|
140
|
+
|
|
141
|
+
def _methods(self, f: Iface) -> None:
|
|
142
|
+
body = f.node.child_by_field_name("body")
|
|
143
|
+
for m in _named(body):
|
|
144
|
+
if m.type != "method_declaration":
|
|
145
|
+
continue
|
|
146
|
+
name = _txt(m.child_by_field_name("name"))
|
|
147
|
+
f.methods.add(name)
|
|
148
|
+
mods = next((c for c in m.children if c.type == "modifiers"), None)
|
|
149
|
+
for a in (mods.children if mods is not None else ()):
|
|
150
|
+
if a.type not in ("annotation", "marker_annotation"):
|
|
151
|
+
continue
|
|
152
|
+
an = _txt(a.child_by_field_name("name")).split(".")[-1]
|
|
153
|
+
if an in PROVIDER_ANNOS:
|
|
154
|
+
f.providers.add(name)
|
|
155
|
+
elif an in SQL_ANNOS:
|
|
156
|
+
lo, hi = m.start_point[0] + 1, m.end_point[0] + 1
|
|
157
|
+
texts = [s.sql for s in self.sites if s.file == f.jf.rel and lo <= s.line <= hi and s.sql
|
|
158
|
+
and s.sink.lstrip("@") in SQL_ANNOS]
|
|
159
|
+
f.annotated.setdefault(name, []).extend(texts)
|
|
160
|
+
|
|
161
|
+
# ---- <script> in annotations
|
|
162
|
+
def render_scripts(self) -> list[RawSite]:
|
|
163
|
+
out: list[RawSite] = []
|
|
164
|
+
for s in self.sites:
|
|
165
|
+
if s.language != "java" or not s.sql or s.sink.lstrip("@") not in SQL_ANNOS or "<script>" not in s.sql:
|
|
166
|
+
out.append(s)
|
|
167
|
+
continue
|
|
168
|
+
self.stats.seen("mybatis", s.is_test)
|
|
169
|
+
variants, more, dollar = self.script(s.sql, s.file)
|
|
170
|
+
if not variants:
|
|
171
|
+
self.stats.miss("mybatis", "<script> dynamic SQL that does not render", s.file, s.line, s.is_test)
|
|
172
|
+
out.append(s)
|
|
173
|
+
continue
|
|
174
|
+
original = s.sql
|
|
175
|
+
for k, (sql, cond) in enumerate(variants):
|
|
176
|
+
t = s if k == 0 else RawSite(**{f: getattr(s, f) for f in s.__dataclass_fields__})
|
|
177
|
+
t.sql, t.resolution = sql, "orm"
|
|
178
|
+
notes = [f"variant: {trim(cond, 200)}"] if len(variants) > 1 else []
|
|
179
|
+
if more:
|
|
180
|
+
notes.append(f"{more} more variants past [discover] max_variants")
|
|
181
|
+
t.orm = {"library": "mybatis", "model_or_table": _table(sql), "operation": s.sink.lstrip("@").lower(),
|
|
182
|
+
"confidence": "high" if len(variants) == 1 else "medium",
|
|
183
|
+
"mechanism": "orm_raw_fragment" if dollar else "orm_api"}
|
|
184
|
+
if notes:
|
|
185
|
+
t.orm["notes"] = "; ".join(notes)
|
|
186
|
+
if k == 0:
|
|
187
|
+
t.orm["id_from"] = [original, s.engine_hint]
|
|
188
|
+
out.append(t)
|
|
189
|
+
self.stats.hit("mybatis", len(variants), s.is_test)
|
|
190
|
+
# the annotation's texts as the calls of its method see them
|
|
191
|
+
for f in self.ifaces.values():
|
|
192
|
+
if f.jf.rel == s.file:
|
|
193
|
+
for name, texts in f.annotated.items():
|
|
194
|
+
if original in texts:
|
|
195
|
+
f.annotated[name] = [v for v, _ in variants] + [x for x in texts if x != original]
|
|
196
|
+
return out
|
|
197
|
+
|
|
198
|
+
def script(self, text: str, rel: str) -> tuple[list, int, bool]:
|
|
199
|
+
body = re.sub(r"^\s*<script>|</script>\s*$", "", text.strip())
|
|
200
|
+
doc = xml_mapper.parse("<script>" + body.replace("&&", "&&") + "</script>")
|
|
201
|
+
if doc is None:
|
|
202
|
+
return [], 0, False
|
|
203
|
+
el = doc.children[0] if doc.children and isinstance(doc.children[0], xml_mapper.El) else None
|
|
204
|
+
if el is None:
|
|
205
|
+
return [], 0, False
|
|
206
|
+
fake = xml_mapper.Mapper(rel, "", el)
|
|
207
|
+
nodes = xml_mapper._inline(el, self.mappers, fake, {})
|
|
208
|
+
return xml_mapper.render_family(nodes)
|
|
209
|
+
|
|
210
|
+
# ---- entities
|
|
211
|
+
def entity(self, name: str) -> Entity | None:
|
|
212
|
+
if name in self.entities:
|
|
213
|
+
return self.entities[name]
|
|
214
|
+
self.entities[name] = None
|
|
215
|
+
for jf, node in self.ctx.repo.classes.get(name, ()):
|
|
216
|
+
if node.type not in ("class_declaration", "record_declaration"):
|
|
217
|
+
continue
|
|
218
|
+
e = self._read_entity(jf, node, name)
|
|
219
|
+
self.entities[name] = e
|
|
220
|
+
return e
|
|
221
|
+
return None
|
|
222
|
+
|
|
223
|
+
def _read_entity(self, jf, node: Node, name: str) -> Entity:
|
|
224
|
+
table, explicit = _snake(name), False
|
|
225
|
+
for a in _annotations(node):
|
|
226
|
+
an = _txt(a.child_by_field_name("name")).split(".")[-1]
|
|
227
|
+
if an == "TableName":
|
|
228
|
+
v = _anno_value(a, "value")
|
|
229
|
+
if v:
|
|
230
|
+
table, explicit = v, True
|
|
231
|
+
e = Entity(name, table, explicit)
|
|
232
|
+
body = node.child_by_field_name("body")
|
|
233
|
+
for fd in _named(body):
|
|
234
|
+
if fd.type != "field_declaration":
|
|
235
|
+
continue
|
|
236
|
+
mods = next((c for c in fd.children if c.type == "modifiers"), None)
|
|
237
|
+
mtext = _txt(mods)
|
|
238
|
+
if re.search(r"\bstatic\b|\btransient\b", mtext):
|
|
239
|
+
continue
|
|
240
|
+
col = ""
|
|
241
|
+
skip = is_id = False
|
|
242
|
+
logic = None
|
|
243
|
+
for a in _annotations(fd):
|
|
244
|
+
an = _txt(a.child_by_field_name("name")).split(".")[-1]
|
|
245
|
+
if an == "TableField":
|
|
246
|
+
if re.search(r"\bexist\s*=\s*false", _txt(a)):
|
|
247
|
+
skip = True
|
|
248
|
+
col = _anno_value(a, "value") or col
|
|
249
|
+
elif an == "TableId":
|
|
250
|
+
is_id = True
|
|
251
|
+
col = _anno_value(a, "value") or col
|
|
252
|
+
elif an == "TableLogic":
|
|
253
|
+
logic = (_anno_value(a, "value") or "0", _anno_value(a, "delval") or "1")
|
|
254
|
+
if skip:
|
|
255
|
+
continue
|
|
256
|
+
for d in fd.children:
|
|
257
|
+
if d.type == "variable_declarator":
|
|
258
|
+
fname = _txt(d.child_by_field_name("name"))
|
|
259
|
+
c = (col or _snake(fname)).strip("`\"")
|
|
260
|
+
e.columns.append((fname, c))
|
|
261
|
+
if is_id:
|
|
262
|
+
e.id_field, e.id_column = fname, c
|
|
263
|
+
if logic:
|
|
264
|
+
e.logic = (c, logic[0], logic[1])
|
|
265
|
+
if not any(f == e.id_field for f, _ in e.columns) and any(f == "id" for f, _ in e.columns):
|
|
266
|
+
e.id_field, e.id_column = "id", e.column("id")
|
|
267
|
+
return e
|
|
268
|
+
|
|
269
|
+
# ---- calls
|
|
270
|
+
def receiver(self, jf, obj: Node, call: Node) -> Iface | None:
|
|
271
|
+
from .orm_java import _decl_type, _outer_type
|
|
272
|
+
if obj.type == "identifier":
|
|
273
|
+
name = _txt(obj)
|
|
274
|
+
elif obj.type == "field_access" and _txt(obj.child_by_field_name("object")) == "this":
|
|
275
|
+
name = _txt(obj.child_by_field_name("field"))
|
|
276
|
+
else:
|
|
277
|
+
return None
|
|
278
|
+
t = _outer_type(_decl_type(self.ctx, jf, name, call))
|
|
279
|
+
if t in self.ifaces:
|
|
280
|
+
return self.ifaces[t]
|
|
281
|
+
if t and not re.fullmatch(r"[A-Z][A-Z0-9_]*", t):
|
|
282
|
+
return None # a declared type that is not a mapper of the repository
|
|
283
|
+
# undeclared here, or a type variable: a subclass names the mapper in its superclass's type arguments
|
|
284
|
+
cls = jf._enclosing(call, ("class_declaration",))
|
|
285
|
+
sup = next((c for c in cls.children if c.type == "superclass"), None) if cls is not None else None
|
|
286
|
+
hits = [w for w in re.findall(r"\b([A-Z]\w*)\b", _txt(sup)) if w in self.ifaces] if sup is not None else []
|
|
287
|
+
if len(set(hits)) == 1:
|
|
288
|
+
return self.ifaces[hits[0]]
|
|
289
|
+
if t:
|
|
290
|
+
return None
|
|
291
|
+
return self.ifaces.get(name[:1].upper() + name[1:])
|
|
292
|
+
|
|
293
|
+
def calls(self) -> None:
|
|
294
|
+
from .orm_java import _is_test
|
|
295
|
+
if not self.ifaces:
|
|
296
|
+
return
|
|
297
|
+
names = set()
|
|
298
|
+
for f in self.ifaces.values():
|
|
299
|
+
names |= f.methods
|
|
300
|
+
if f.plus:
|
|
301
|
+
names |= PLUS_METHODS
|
|
302
|
+
for jf in self.ctx.repo.files:
|
|
303
|
+
test = _is_test(jf.rel)
|
|
304
|
+
for call in jf.calls:
|
|
305
|
+
mname = _txt(call.child_by_field_name("name"))
|
|
306
|
+
if mname not in names:
|
|
307
|
+
continue
|
|
308
|
+
obj = call.child_by_field_name("object")
|
|
309
|
+
if obj is None:
|
|
310
|
+
continue
|
|
311
|
+
f = self.receiver(jf, obj, call)
|
|
312
|
+
if f is None:
|
|
313
|
+
continue
|
|
314
|
+
if f.node.start_byte <= call.start_byte < f.node.end_byte and f.jf is jf:
|
|
315
|
+
continue
|
|
316
|
+
self.stats.seen("mybatis", test)
|
|
317
|
+
n, why = self.call_site(jf, call, f, mname, test)
|
|
318
|
+
if n:
|
|
319
|
+
self.stats.hit("mybatis", n, test)
|
|
320
|
+
else:
|
|
321
|
+
self.stats.miss("mybatis", why, jf.rel, call.start_point[0] + 1, test)
|
|
322
|
+
|
|
323
|
+
def call_site(self, jf, call: Node, f: Iface, mname: str, test: bool) -> tuple[int, str]:
|
|
324
|
+
sink = f"{_txt(call.child_by_field_name('object'))}.{mname}"
|
|
325
|
+
stmts = [s for m in self.mappers.get(f.fqn, ()) for s in m.by_id.get(mname, ())]
|
|
326
|
+
if not stmts: # a namespace that is not the interface's own: matched by simple name when unique
|
|
327
|
+
alt = [s for ns, ms in self.mappers.items() if ns.rsplit(".", 1)[-1] == f.name for m in ms for s in m.by_id.get(mname, ())]
|
|
328
|
+
if len({s.mapper.namespace for s in alt}) == 1:
|
|
329
|
+
stmts = alt
|
|
330
|
+
if stmts:
|
|
331
|
+
n = 0
|
|
332
|
+
for s in stmts:
|
|
333
|
+
for sql, cond in s.variants:
|
|
334
|
+
notes = [f"statement {s.mapper.rel}:{s.line}"] + xml_mapper.notes(s, cond, len(s.variants))
|
|
335
|
+
self.add(jf, call, sink, sql, "mybatis", s.table or s.model, s.op,
|
|
336
|
+
"high" if len(s.variants) == 1 and not s.dollar else "medium", notes, xml_mapper.mechanism(s),
|
|
337
|
+
xml_mapper.engine_of(s.database_id))
|
|
338
|
+
n += 1
|
|
339
|
+
return n, "mapper statement renders to no complete SQL"
|
|
340
|
+
if mname in f.annotated and f.annotated[mname]:
|
|
341
|
+
texts = f.annotated[mname]
|
|
342
|
+
for sql in texts:
|
|
343
|
+
notes = ["statement in the method's annotation"] + ([f"one of {len(texts)} variants"] if len(texts) > 1 else [])
|
|
344
|
+
self.add(jf, call, sink, sql, "mybatis", _table(sql) or f.entity, _op(sql), "high" if len(texts) == 1 else "medium",
|
|
345
|
+
notes, "orm_api")
|
|
346
|
+
return len(texts), ""
|
|
347
|
+
if mname in f.providers:
|
|
348
|
+
return 0, "@SelectProvider / @InsertProvider ...: the SQL is built by a provider class at run time"
|
|
349
|
+
if f.plus and mname in PLUS_METHODS and mname not in f.methods:
|
|
350
|
+
e = self.entity(f.entity) if f.entity else None
|
|
351
|
+
if e is None:
|
|
352
|
+
return 0, "BaseMapper entity class not found in the repository"
|
|
353
|
+
return self.plus_call(jf, call, sink, e, mname)
|
|
354
|
+
if mname in f.methods:
|
|
355
|
+
return 0, "mapper method with no statement (no XML statement or SQL annotation found)"
|
|
356
|
+
return 0, "generic or unknown mapper method"
|
|
357
|
+
|
|
358
|
+
def add(self, jf, call: Node, sink: str, sql: str, library: str, table: str, op: str, confidence: str,
|
|
359
|
+
notes: list[str], mechanism: str, engine: str = "") -> None:
|
|
360
|
+
s = self.ctx.site(jf, call, sql, library, table, op, confidence, notes, sink=sink,
|
|
361
|
+
line_node=call.child_by_field_name("name"))
|
|
362
|
+
s.orm["mechanism"] = "orm_api_in_loop" if s.in_loop and mechanism == "orm_api" else mechanism
|
|
363
|
+
s.engine_hint = engine
|
|
364
|
+
|
|
365
|
+
# ---- MyBatis-Plus
|
|
366
|
+
def plus_call(self, jf, call: Node, sink: str, e: Entity, mname: str) -> tuple[int, str]:
|
|
367
|
+
args = _named(call.child_by_field_name("arguments"))
|
|
368
|
+
cols = ", ".join(c for _, c in e.columns) or "*"
|
|
369
|
+
t, idc = e.table, e.id_column
|
|
370
|
+
live = f" AND {e.logic[0]} = {e.logic[1]}" if e.logic else ""
|
|
371
|
+
notes = [] if e.explicit else [f"table {t} from the class name (no @TableName)"]
|
|
372
|
+
conf = "high" if e.explicit else "medium"
|
|
373
|
+
a0 = _txt(args[0]) if args else ""
|
|
374
|
+
|
|
375
|
+
def emit(sqls: list[tuple[str, str]], op: str, extra: list[str] = ()) -> tuple[int, str]:
|
|
376
|
+
for sql, cond in sqls:
|
|
377
|
+
ns = notes + list(extra) + ([f"variant: {cond}"] if len(sqls) > 1 else [])
|
|
378
|
+
self.add(jf, call, sink, sql, "mybatis-plus", t, op, conf if len(sqls) == 1 else "medium", ns, "orm_api")
|
|
379
|
+
return len(sqls), ""
|
|
380
|
+
|
|
381
|
+
if mname in ("selectById",):
|
|
382
|
+
return emit([(f"SELECT {cols} FROM {t} WHERE {idc} = {_mark(a0)}{live}", "")], "select")
|
|
383
|
+
if mname in ("selectBatchIds", "selectByIds"):
|
|
384
|
+
return emit([(f"SELECT {cols} FROM {t} WHERE {idc} IN ({_mark(a0)}){live}", "")], "select")
|
|
385
|
+
if mname in ("deleteById", "deleteBatchIds", "deleteByIds"):
|
|
386
|
+
where = f"{idc} = {_mark(a0)}" if mname == "deleteById" else f"{idc} IN ({_mark(a0)})"
|
|
387
|
+
if e.logic:
|
|
388
|
+
return emit([(f"UPDATE {t} SET {e.logic[0]} = {e.logic[2]} WHERE {where}{live}", "")], "update", ["logical delete (@TableLogic)"])
|
|
389
|
+
return emit([(f"DELETE FROM {t} WHERE {where}", "")], "delete")
|
|
390
|
+
if mname == "insert":
|
|
391
|
+
fields = [(f, c) for f, c in e.columns]
|
|
392
|
+
if not fields:
|
|
393
|
+
return 0, "entity with no mapped fields"
|
|
394
|
+
return emit([(f"INSERT INTO {t} ({', '.join(c for _, c in fields)}) VALUES ("
|
|
395
|
+
+ ", ".join(_mark(f"{a0}.{f}") for f, _ in fields) + ")", "")], "insert",
|
|
396
|
+
["MyBatis-Plus leaves out the fields that are null at run time"])
|
|
397
|
+
if mname == "updateById":
|
|
398
|
+
fields = [(f, c) for f, c in e.columns if f != e.id_field]
|
|
399
|
+
if not fields:
|
|
400
|
+
return 0, "entity with no mapped fields"
|
|
401
|
+
return emit([(f"UPDATE {t} SET " + ", ".join(f"{c} = {_mark(f'{a0}.{f}')}" for f, c in fields)
|
|
402
|
+
+ f" WHERE {idc} = {_mark(a0 + '.' + e.id_field)}{live}", "")], "update",
|
|
403
|
+
["MyBatis-Plus sets only the fields that are not null at run time"])
|
|
404
|
+
# the wrapper methods
|
|
405
|
+
wi = {"selectList": 0, "selectOne": 0, "selectCount": 0, "selectMaps": 0, "selectObjs": 0, "exists": 0,
|
|
406
|
+
"delete": 0, "selectPage": 1, "selectMapsPage": 1, "update": 1}.get(mname)
|
|
407
|
+
if wi is None:
|
|
408
|
+
return 0, f"BaseMapper.{mname} is not translated"
|
|
409
|
+
w = args[wi] if wi < len(args) else None
|
|
410
|
+
cond = self.wrapper(jf, w, call, e) if w is not None and _txt(w) != "null" else Cond()
|
|
411
|
+
if cond is None:
|
|
412
|
+
return 0, "wrapper built outside this method (or of a form not read): its conditions are not known"
|
|
413
|
+
out: list[tuple[str, str]] = []
|
|
414
|
+
for preds, label in cond.variants():
|
|
415
|
+
where = " AND ".join(preds + ([f"{e.logic[0]} = {e.logic[1]}"] if e.logic else []))
|
|
416
|
+
wsql = f" WHERE {where}" if where else ""
|
|
417
|
+
tail = (" " + cond.tail) if cond.tail else ""
|
|
418
|
+
order = f" ORDER BY {', '.join(cond.order)}" if cond.order else ""
|
|
419
|
+
group = f" GROUP BY {', '.join(cond.group)}" if cond.group else ""
|
|
420
|
+
select = ", ".join(cond.select) if cond.select else cols
|
|
421
|
+
if mname == "selectCount":
|
|
422
|
+
sql = f"SELECT COUNT(*) FROM {t}{wsql}"
|
|
423
|
+
elif mname == "exists":
|
|
424
|
+
sql = f"SELECT COUNT(*) FROM {t}{wsql}"
|
|
425
|
+
elif mname == "delete":
|
|
426
|
+
sql = (f"UPDATE {t} SET {e.logic[0]} = {e.logic[2]}{wsql}" if e.logic else f"DELETE FROM {t}{wsql}")
|
|
427
|
+
elif mname == "update":
|
|
428
|
+
sets = cond.sets or [f"{c} = {_mark(_txt(args[0]) + '.' + f)}" for f, c in e.columns if f != e.id_field]
|
|
429
|
+
if not sets:
|
|
430
|
+
return 0, "update with nothing to set"
|
|
431
|
+
sql = f"UPDATE {t} SET {', '.join(sets)}{wsql}"
|
|
432
|
+
else:
|
|
433
|
+
sql = f"SELECT {select} FROM {t}{wsql}{group}{order}{tail}"
|
|
434
|
+
if mname in ("selectPage", "selectMapsPage"):
|
|
435
|
+
sql += f" LIMIT {_mark(a0 + '.size')} OFFSET {_mark(a0 + '.offset')}"
|
|
436
|
+
out.append((sql, label))
|
|
437
|
+
op = "delete" if mname == "delete" and not e.logic else ("update" if mname in ("update", "delete") else "select")
|
|
438
|
+
return emit(out, op, cond.notes)
|
|
439
|
+
|
|
440
|
+
def wrapper(self, jf, w: Node, at: Node, e: Entity) -> "Cond | None":
|
|
441
|
+
chain = _chain(w)
|
|
442
|
+
if chain is None:
|
|
443
|
+
return None
|
|
444
|
+
head, calls = chain
|
|
445
|
+
cond = Cond()
|
|
446
|
+
if head.type == "identifier":
|
|
447
|
+
got = self._var_calls(jf, _txt(head), at)
|
|
448
|
+
if got is None:
|
|
449
|
+
return None
|
|
450
|
+
for c, conditional in got:
|
|
451
|
+
if not cond.add(c, e, conditional):
|
|
452
|
+
return None
|
|
453
|
+
elif not _is_wrapper_start(head):
|
|
454
|
+
return None
|
|
455
|
+
for c in calls:
|
|
456
|
+
if not cond.add(c, e, False):
|
|
457
|
+
return None
|
|
458
|
+
return cond
|
|
459
|
+
|
|
460
|
+
def _var_calls(self, jf, name: str, at: Node) -> list[tuple[Node, bool]] | None:
|
|
461
|
+
"""The wrapper calls made on a local variable before `at`: its initializer's chain, then `name.eq(...)`
|
|
462
|
+
statements of the same method (marked conditional when under an if / loop / switch the call is not in)."""
|
|
463
|
+
method = jf._enclosing(at, ("method_declaration", "constructor_declaration", "lambda_expression"))
|
|
464
|
+
if method is None:
|
|
465
|
+
return None
|
|
466
|
+
decl = None
|
|
467
|
+
for n in _walk(method):
|
|
468
|
+
if n.start_byte >= at.start_byte:
|
|
469
|
+
break
|
|
470
|
+
if n.type == "variable_declarator" and _txt(n.child_by_field_name("name")) == name:
|
|
471
|
+
decl = n
|
|
472
|
+
if decl is None:
|
|
473
|
+
return None
|
|
474
|
+
init = decl.child_by_field_name("value")
|
|
475
|
+
ch = _chain(init) if init is not None else None
|
|
476
|
+
if ch is None or not _is_wrapper_start(ch[0]):
|
|
477
|
+
return None
|
|
478
|
+
out = [(c, False) for c in ch[1]]
|
|
479
|
+
for n in _walk(method):
|
|
480
|
+
if n.start_byte <= decl.end_byte:
|
|
481
|
+
continue
|
|
482
|
+
if n.start_byte >= at.start_byte:
|
|
483
|
+
break
|
|
484
|
+
if n.type == "expression_statement" and n.named_children:
|
|
485
|
+
x = n.named_children[0]
|
|
486
|
+
if x.type == "assignment_expression":
|
|
487
|
+
x = x.child_by_field_name("right")
|
|
488
|
+
ch2 = _chain(x)
|
|
489
|
+
if ch2 is not None and ch2[0].type == "identifier" and _txt(ch2[0]) == name and ch2[1]:
|
|
490
|
+
conditional = _guarded(n, at)
|
|
491
|
+
out.extend((c, conditional) for c in ch2[1])
|
|
492
|
+
elif n.type == "argument_list" and any(_txt(a) == name for a in n.named_children) and n.parent is not None \
|
|
493
|
+
and n.parent.start_byte < at.start_byte and n.parent is not at:
|
|
494
|
+
return None # handed to another method, which may add conditions
|
|
495
|
+
return out
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
PLUS_METHODS = {"selectById", "selectBatchIds", "selectByIds", "selectList", "selectOne", "selectCount", "selectMaps",
|
|
499
|
+
"selectObjs", "selectPage", "selectMapsPage", "exists", "insert", "updateById", "update", "deleteById",
|
|
500
|
+
"deleteBatchIds", "deleteByIds", "delete"}
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
class Cond:
|
|
504
|
+
def __init__(self):
|
|
505
|
+
self.preds: list[tuple[str, bool, str]] = [] # (predicate, conditional, condition text)
|
|
506
|
+
self.order: list[str] = []
|
|
507
|
+
self.group: list[str] = []
|
|
508
|
+
self.select: list[str] = []
|
|
509
|
+
self.sets: list[str] = []
|
|
510
|
+
self.tail = ""
|
|
511
|
+
self.notes: list[str] = []
|
|
512
|
+
|
|
513
|
+
def variants(self) -> list[tuple[list[str], str]]:
|
|
514
|
+
sure = [p for p, c, _ in self.preds if not c]
|
|
515
|
+
maybe = [(p, why) for p, c, why in self.preds if c]
|
|
516
|
+
if not maybe:
|
|
517
|
+
return [(sure, "")]
|
|
518
|
+
out = [(sure, "every guarded condition false"), (sure + [p for p, _ in maybe], "every guarded condition true")]
|
|
519
|
+
return out
|
|
520
|
+
|
|
521
|
+
def add(self, call: Node, e: Entity, conditional: bool) -> bool:
|
|
522
|
+
name = _txt(call.child_by_field_name("name"))
|
|
523
|
+
args = _named(call.child_by_field_name("arguments"))
|
|
524
|
+
guard = ""
|
|
525
|
+
if name in ("lambda", "getWrapper", "func"):
|
|
526
|
+
return True
|
|
527
|
+
if args and name not in ("select", "last", "apply", "orderByAsc", "orderByDesc", "groupBy", "in", "notIn") \
|
|
528
|
+
and args[0].type in ("binary_expression", "true", "false", "method_invocation", "unary_expression", "identifier") \
|
|
529
|
+
and len(args) >= (2 if name in ("isNull", "isNotNull") else 3) and not _is_col(args[0]):
|
|
530
|
+
guard, args = _txt(args[0]), args[1:]
|
|
531
|
+
if guard == "true":
|
|
532
|
+
guard = ""
|
|
533
|
+
elif guard == "false":
|
|
534
|
+
return True
|
|
535
|
+
elif name in ("orderBy",) and len(args) >= 3:
|
|
536
|
+
guard, args = _txt(args[0]), args[1:]
|
|
537
|
+
cond = conditional or bool(guard)
|
|
538
|
+
why = guard or "an if around the call"
|
|
539
|
+
|
|
540
|
+
def col(n: Node) -> str | None:
|
|
541
|
+
return _column(n, e)
|
|
542
|
+
|
|
543
|
+
if name in OPS and len(args) == 2:
|
|
544
|
+
c = col(args[0])
|
|
545
|
+
if c is None:
|
|
546
|
+
return False
|
|
547
|
+
self.preds.append((f"{c} {OPS[name]} {_value(args[1])}", cond, why))
|
|
548
|
+
elif name in LIKES and len(args) == 2:
|
|
549
|
+
c = col(args[0])
|
|
550
|
+
if c is None:
|
|
551
|
+
return False
|
|
552
|
+
self.preds.append((f"{c} {LIKES[name]} {_value(args[1])}", cond, why))
|
|
553
|
+
elif name in ("in", "notIn") and len(args) >= 2:
|
|
554
|
+
if len(args) == 3:
|
|
555
|
+
guard, args = _txt(args[0]), args[1:]
|
|
556
|
+
cond, why = True, guard
|
|
557
|
+
c = col(args[0])
|
|
558
|
+
if c is None:
|
|
559
|
+
return False
|
|
560
|
+
vals = args[1:]
|
|
561
|
+
inside = _value(vals[0]) if len(vals) == 1 else ", ".join(_value(v) for v in vals)
|
|
562
|
+
self.preds.append((f"{c} {'IN' if name == 'in' else 'NOT IN'} ({inside})", cond, why))
|
|
563
|
+
elif name in ("isNull", "isNotNull") and len(args) == 1:
|
|
564
|
+
c = col(args[0])
|
|
565
|
+
if c is None:
|
|
566
|
+
return False
|
|
567
|
+
self.preds.append((f"{c} IS {'NULL' if name == 'isNull' else 'NOT NULL'}", cond, why))
|
|
568
|
+
elif name in ("between", "notBetween") and len(args) == 3:
|
|
569
|
+
c = col(args[0])
|
|
570
|
+
if c is None:
|
|
571
|
+
return False
|
|
572
|
+
self.preds.append((f"{c} {'BETWEEN' if name == 'between' else 'NOT BETWEEN'} {_value(args[1])} AND {_value(args[2])}", cond, why))
|
|
573
|
+
elif name in ("orderByAsc", "orderByDesc", "orderBy"):
|
|
574
|
+
asc = name == "orderByAsc"
|
|
575
|
+
if name == "orderBy":
|
|
576
|
+
asc_node, args = args[0], args[1:]
|
|
577
|
+
asc = _txt(asc_node) == "true"
|
|
578
|
+
cs = [col(a) for a in args]
|
|
579
|
+
if any(c is None for c in cs):
|
|
580
|
+
return False
|
|
581
|
+
if cond:
|
|
582
|
+
self.notes.append(f"order by {', '.join(cs)} only when {why}")
|
|
583
|
+
self.order.extend(f"{c} {'ASC' if asc else 'DESC'}" for c in cs)
|
|
584
|
+
elif name == "groupBy":
|
|
585
|
+
cs = [col(a) for a in args]
|
|
586
|
+
if any(c is None for c in cs):
|
|
587
|
+
return False
|
|
588
|
+
self.group.extend(cs)
|
|
589
|
+
elif name == "select":
|
|
590
|
+
cs = [col(a) for a in args if a.type != "class_literal"]
|
|
591
|
+
if not cs or any(c is None for c in cs):
|
|
592
|
+
return False
|
|
593
|
+
self.select.extend(cs)
|
|
594
|
+
elif name == "set" and len(args) == 2:
|
|
595
|
+
c = col(args[0])
|
|
596
|
+
if c is None:
|
|
597
|
+
return False
|
|
598
|
+
self.sets.append(f"{c} = {_value(args[1])}")
|
|
599
|
+
elif name == "last" and len(args) == 1:
|
|
600
|
+
s = _string(args[0])
|
|
601
|
+
self.tail = s if s is not None else _mark(_txt(args[0]))
|
|
602
|
+
elif name == "apply" and args:
|
|
603
|
+
s = _string(args[0])
|
|
604
|
+
if s is None:
|
|
605
|
+
return False
|
|
606
|
+
self.preds.append((re.sub(r"\{\d+\}", lambda m: "«" + m.group(0)[1:-1] + "»", s), cond, why))
|
|
607
|
+
elif name in ("and", "or", "nested", "not", "exists", "notExists", "inSql", "notInSql", "having") and args:
|
|
608
|
+
self.preds.append((_mark(name + "(...)"), cond, why))
|
|
609
|
+
self.notes.append(f".{name}(...) is a run-time part")
|
|
610
|
+
else:
|
|
611
|
+
return False
|
|
612
|
+
return True
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def _is_col(n: Node) -> bool:
|
|
616
|
+
return n.type == "method_reference" or n.type == "string_literal"
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def _column(n: Node, e: Entity) -> str | None:
|
|
620
|
+
if n.type == "method_reference":
|
|
621
|
+
t = _txt(n)
|
|
622
|
+
m = re.search(r"::\s*(?:get|is)?(\w+)$", t)
|
|
623
|
+
if not m:
|
|
624
|
+
return None
|
|
625
|
+
field = m.group(1)[:1].lower() + m.group(1)[1:]
|
|
626
|
+
return e.column(field)
|
|
627
|
+
s = _string(n)
|
|
628
|
+
if s is not None and re.fullmatch(r"[\w.`\"]+", s):
|
|
629
|
+
return s
|
|
630
|
+
if n.type in ("identifier", "field_access") and re.search(r"[A-Z_]{3,}$", _txt(n)):
|
|
631
|
+
return _mark(_txt(n))
|
|
632
|
+
return None
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
def _value(n: Node) -> str:
|
|
636
|
+
t = n.type
|
|
637
|
+
if t == "string_literal":
|
|
638
|
+
s = _string(n) or ""
|
|
639
|
+
return "'" + s.replace("'", "''") + "'"
|
|
640
|
+
if t in ("decimal_integer_literal", "decimal_floating_point_literal"):
|
|
641
|
+
return _txt(n).rstrip("lLfFdD")
|
|
642
|
+
if t in ("true", "false", "null_literal"):
|
|
643
|
+
return {"true": "TRUE", "false": "FALSE", "null_literal": "NULL"}[t]
|
|
644
|
+
return _mark(_txt(n))
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def _chain(node: Node | None) -> tuple[Node, list[Node]] | None:
|
|
648
|
+
"""`a.b(..).c(..)` -> (head `a`, [b-call, c-call]); `new X<>().b()` -> (the creation, [b-call])."""
|
|
649
|
+
calls: list[Node] = []
|
|
650
|
+
while node is not None and node.type == "method_invocation":
|
|
651
|
+
calls.append(node)
|
|
652
|
+
node = node.child_by_field_name("object")
|
|
653
|
+
if node is None:
|
|
654
|
+
if calls: # `Wrappers.lambdaQuery()` written without an object is not a chain we read
|
|
655
|
+
return None
|
|
656
|
+
return None
|
|
657
|
+
calls.reverse()
|
|
658
|
+
# `Wrappers.<E>lambdaQuery()` / `Wrappers.query()`: the first call starts the wrapper
|
|
659
|
+
if node.type == "identifier" and _txt(node) in ("Wrappers", "new_QueryWrapper") and calls:
|
|
660
|
+
return calls[0], calls[1:]
|
|
661
|
+
return node, calls
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
def _is_wrapper_start(n: Node) -> bool:
|
|
665
|
+
if n.type == "object_creation_expression":
|
|
666
|
+
return bool(WRAPPER_TYPES.search(_txt(n.child_by_field_name("type"))))
|
|
667
|
+
if n.type == "method_invocation":
|
|
668
|
+
return _txt(n.child_by_field_name("object")) == "Wrappers" and not _named(n.child_by_field_name("arguments")) \
|
|
669
|
+
or (_txt(n.child_by_field_name("object")) == "Wrappers" and all(a.type == "class_literal" for a in _named(n.child_by_field_name("arguments"))))
|
|
670
|
+
return False
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def _guarded(stmt: Node, at: Node) -> bool:
|
|
674
|
+
n = stmt.parent
|
|
675
|
+
while n is not None:
|
|
676
|
+
if n.type in ("if_statement", "for_statement", "enhanced_for_statement", "while_statement", "switch_expression",
|
|
677
|
+
"switch_block_statement_group", "catch_clause", "ternary_expression", "lambda_expression"):
|
|
678
|
+
return not (n.start_byte <= at.start_byte < n.end_byte)
|
|
679
|
+
if n.type in ("method_declaration", "constructor_declaration"):
|
|
680
|
+
return False
|
|
681
|
+
n = n.parent
|
|
682
|
+
return False
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
def _walk(node: Node):
|
|
686
|
+
from .base import walk_tree
|
|
687
|
+
yield node
|
|
688
|
+
yield from walk_tree(node)
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
def _annotations(node: Node) -> list[Node]:
|
|
692
|
+
mods = next((c for c in node.children if c.type == "modifiers"), None)
|
|
693
|
+
return [a for a in (mods.children if mods is not None else ()) if a.type in ("annotation", "marker_annotation")]
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def _anno_value(a: Node, key: str) -> str:
|
|
697
|
+
for x in _named(a.child_by_field_name("arguments")):
|
|
698
|
+
if x.type == "element_value_pair":
|
|
699
|
+
if _txt(x.child_by_field_name("key")) == key:
|
|
700
|
+
return _string(x.child_by_field_name("value")) or ""
|
|
701
|
+
elif key == "value":
|
|
702
|
+
return _string(x) or ""
|
|
703
|
+
return ""
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def _table(sql: str) -> str:
|
|
707
|
+
m = re.search(r"(?is)\b(?:from|into|update)\s+([`\"\w.]+)", sql)
|
|
708
|
+
return m.group(1).strip("`\"") if m else ""
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
def _op(sql: str) -> str:
|
|
712
|
+
m = re.match(r"\s*(\w+)", sql)
|
|
713
|
+
return m.group(1).lower() if m else ""
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
def extend(ctx, sites: list[RawSite], stats) -> list[RawSite]:
|
|
717
|
+
import os
|
|
718
|
+
p = Pass(ctx, sites, stats)
|
|
719
|
+
try:
|
|
720
|
+
p.load_xml()
|
|
721
|
+
p.find_ifaces()
|
|
722
|
+
if not p.ifaces and not p.mappers:
|
|
723
|
+
return sites
|
|
724
|
+
sites = p.render_scripts()
|
|
725
|
+
p.sites = sites
|
|
726
|
+
p.calls()
|
|
727
|
+
except Exception: # one odd mapper must not stop the inventory
|
|
728
|
+
if os.environ.get("CODECOP_ORM_DEBUG"):
|
|
729
|
+
raise
|
|
730
|
+
return sites
|