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.
Files changed (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1450 @@
1
+ """Java database access that goes through an ORM or a query builder instead of a SQL string.
2
+
3
+ Called once by `java.extract` with every parsed file and the sites found so far. It
4
+
5
+ * reads the JPA mapping (orm_jpa.Model) and hands the tables to discovery,
6
+ * rewrites every JPQL / HQL site (`@Query`, `@NamedQuery`, `createQuery`) as SQL over the mapped tables,
7
+ * adds sites for Spring Data derived query methods, the repository's inherited methods (`findById`, `save`,
8
+ ...), `EntityManager.find / persist / merge / remove`, eager associations, and lazy associations read inside
9
+ a loop (the JPA N+1),
10
+ * counts what it does not translate (Criteria API, Specifications, JDO) with the reason,
11
+ * and runs the jOOQ and JDBI / StringTemplate / MyBatis extractors (orm_jooq, orm_jdbi).
12
+
13
+ A synthesised site has `resolution = "orm"` and an `orm` object {library, model_or_table, operation,
14
+ confidence, notes}. Nothing is invented: when the entity, table or operation is not certain the call is counted.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ from pathlib import Path
21
+
22
+ from tree_sitter import Node
23
+
24
+ from . import orm_jpa
25
+ from .base import PLACEHOLDER, RawSite, is_test_path, trim
26
+ from .orm_jpa import Attr, Entity, Model, Untranslatable
27
+ from .orm_stats import Stats
28
+
29
+ STATS = Stats()
30
+ TABLES: list = []
31
+
32
+ # The most extra statements one call site gets for eager associations. A setting: `[discover] orm_max_eager`.
33
+ DEFAULT_MAX_EAGER = 16
34
+ MAX_EAGER = DEFAULT_MAX_EAGER
35
+ # How many lazy-association reads inside loops are reported per method. A setting: `[discover] orm_max_lazy_per_method`.
36
+ DEFAULT_MAX_LAZY = 50
37
+ MAX_LAZY = DEFAULT_MAX_LAZY
38
+
39
+ MAPPING_ANNOS = {"Column", "Id", "EmbeddedId", "Embedded", "JoinColumn", "JoinColumns", "ManyToOne", "OneToOne", "OneToMany",
40
+ "ManyToMany", "ElementCollection", "Transient", "Version", "Basic", "Enumerated", "Lob", "Temporal",
41
+ "Convert", "JoinTable", "CollectionTable", "Formula", "MapsId", "GeneratedValue", "MapKeyColumn"}
42
+ REPO_BASES = {"JpaRepository", "CrudRepository", "PagingAndSortingRepository", "ListCrudRepository",
43
+ "ListPagingAndSortingRepository", "Repository", "JpaSpecificationExecutor", "QuerydslPredicateExecutor",
44
+ "ReactiveCrudRepository", "R2dbcRepository", "ReactiveSortingRepository", "RevisionRepository",
45
+ "JpaRepositoryImplementation", "PanacheRepository", "PanacheRepositoryBase"}
46
+ NOT_SQL_REPOS = re.compile(r"\b(Mongo|Cassandra|Elasticsearch|Redis|Neo4j|Couchbase|Solr|Ldap|KeyValue|DynamoDB|Cosmos)\w*Repository\b")
47
+ PAGING_TYPES = ("Pageable", "PageRequest")
48
+ TEST_FILE = re.compile(r"(^|/)src/(test|it|integration-?test)/|(Test|Tests|IT|TestCase)\.java$")
49
+
50
+
51
+ def _txt(node: Node | None) -> str:
52
+ return node.text.decode("utf-8", "replace") if node is not None else ""
53
+
54
+
55
+ def _named(node: Node | None) -> list[Node]:
56
+ return [c for c in node.named_children if c.type not in ("line_comment", "block_comment")] if node is not None else []
57
+
58
+
59
+ def _is_test(rel: str) -> bool:
60
+ return is_test_path(rel) or bool(TEST_FILE.search(rel))
61
+
62
+
63
+ def _annos(node: Node) -> dict[str, list[dict[str, Node]]]:
64
+ """Annotations on a declaration: name -> one {element -> value node} per use ("value" for the single element)."""
65
+ out: dict[str, list[dict[str, Node]]] = {}
66
+ mods = next((c for c in node.children if c.type == "modifiers"), None)
67
+ if mods is None:
68
+ return out
69
+ for a in mods.children:
70
+ if a.type in ("annotation", "marker_annotation"):
71
+ out.setdefault(_txt(a.child_by_field_name("name")).split(".")[-1], []).append(_anno_args(a))
72
+ return out
73
+
74
+
75
+ def _anno_args(a: Node) -> dict[str, Node]:
76
+ args: dict[str, Node] = {}
77
+ for x in _named(a.child_by_field_name("arguments")):
78
+ if x.type == "element_value_pair":
79
+ key, value = x.child_by_field_name("key"), x.child_by_field_name("value")
80
+ if key is not None and value is not None:
81
+ args[_txt(key)] = value
82
+ else:
83
+ args["value"] = x
84
+ return args
85
+
86
+
87
+ def _items(node: Node | None) -> list[Node]:
88
+ if node is None:
89
+ return []
90
+ if node.type == "element_value_array_initializer":
91
+ return _named(node)
92
+ return [node]
93
+
94
+
95
+ def _modifiers(node: Node) -> str:
96
+ mods = next((c for c in node.children if c.type == "modifiers"), None)
97
+ return " ".join(_txt(c) for c in mods.children if c.type not in ("annotation", "marker_annotation")) if mods is not None else ""
98
+
99
+
100
+ def _simple_type(text: str) -> str:
101
+ """`java.util.List<org.x.Foo>` -> Foo (the element type of a collection, the value type of a map)."""
102
+ text = text.strip()
103
+ m = re.search(r"<(.*)>\s*$", text, re.S)
104
+ if m:
105
+ inner = m.group(1)
106
+ depth, last, start = 0, inner, 0
107
+ for i, c in enumerate(inner):
108
+ if c == "<":
109
+ depth += 1
110
+ elif c == ">":
111
+ depth -= 1
112
+ elif c == "," and depth == 0:
113
+ start = i + 1
114
+ return _simple_type(inner[start:])
115
+ return re.sub(r"\[\]$", "", text.split(".")[-1].strip()).strip("? ").replace("extends ", "").strip()
116
+
117
+
118
+ def _outer_type(text: str) -> str:
119
+ return re.sub(r"<.*", "", text, flags=re.S).split(".")[-1].strip()
120
+
121
+
122
+ def _decap(name: str) -> str:
123
+ if len(name) > 1 and name[0].isupper() and name[1].isupper():
124
+ return name
125
+ return name[:1].lower() + name[1:]
126
+
127
+
128
+ class Ctx:
129
+ """Everything the Java ORM passes share: the parsed files, the mapping, the counters."""
130
+
131
+ def __init__(self, root: Path, repo, rules):
132
+ self.root = root
133
+ self.repo = repo
134
+ self.rules = rules
135
+ self.model = Model()
136
+ self.repos: dict[str, tuple[Entity, object, Node]] = {} # repository interface -> (entity, file, node)
137
+ self.repo_misses: dict[str, str] = {} # repository interface -> why its entity is unknown
138
+ self.out: list[RawSite] = []
139
+
140
+ # ---- values in annotations ------------------------------------------------------------------
141
+ def sval(self, jf, node: Node | None) -> str:
142
+ if node is None:
143
+ return ""
144
+ try:
145
+ r = jf.resolve(node, None, 0)
146
+ except Exception:
147
+ r = None
148
+ if r is None or r.dynamic or PLACEHOLDER.search(r.text):
149
+ return ""
150
+ return r.text
151
+
152
+ def site(self, jf, node: Node, sql: str, library: str, table: str, operation: str, confidence: str,
153
+ notes: list[str] | str = "", sink: str = "", line_node: Node | None = None, in_loop: bool | None = None,
154
+ symbol: str | None = None, expr: str | None = None) -> RawSite:
155
+ notes_text = "; ".join(notes) if isinstance(notes, list) else notes
156
+ orm = {"library": library, "model_or_table": table, "operation": operation, "confidence": confidence}
157
+ if notes_text:
158
+ orm["notes"] = notes_text
159
+ ln = line_node or node
160
+ s = RawSite(
161
+ file=jf.rel, line=ln.start_point[0] + 1, end_line=node.end_point[0] + 1, language="java", kind="call",
162
+ sink=trim(sink, 80), symbol=jf.symbol(ln) if symbol is None else symbol, sql=sql, resolution="orm",
163
+ expr=trim(_txt(node) if expr is None else expr), in_loop=jf.in_loop(node) if in_loop is None else in_loop,
164
+ engine_hint="", is_test=_is_test(jf.rel), known_sink=True)
165
+ s.orm = orm
166
+ self.out.append(s)
167
+ return s
168
+
169
+
170
+ # ------------------------------------------------------------------------------------------ the mapping
171
+ def _join_col_names(ctx: Ctx, jf, nodes: list[Node]) -> list[str]:
172
+ out = []
173
+ for n in nodes:
174
+ if n.type in ("annotation", "marker_annotation"):
175
+ name = ctx.sval(jf, _anno_args(n).get("name"))
176
+ if name:
177
+ out.append(ctx.model.name(name, True))
178
+ return out
179
+
180
+
181
+ def _read_attr(ctx: Ctx, jf, name: str, jtype: str, an: dict[str, list[dict[str, Node]]], line: int) -> Attr | None:
182
+ m = ctx.model
183
+ if "Transient" in an:
184
+ return None
185
+ a = Attr(name=name, type=_simple_type(jtype), java_type=jtype, line=line)
186
+ col = an.get("Column", [{}])[0]
187
+ cname = ctx.sval(jf, col.get("name"))
188
+ if cname:
189
+ a.column, a.explicit = m.name(cname, True), True
190
+ if _txt(col.get("unique")) == "true":
191
+ a.unique = True
192
+ rel = next((r for r in ("ManyToOne", "OneToOne", "OneToMany", "ManyToMany") if r in an), "")
193
+ if rel:
194
+ args = an[rel][0]
195
+ a.relation = rel
196
+ a.kind = "to_one" if rel in ("ManyToOne", "OneToOne") else "to_many"
197
+ a.mapped_by = ctx.sval(jf, args.get("mappedBy"))
198
+ fetch = _txt(args.get("fetch")).rsplit(".", 1)[-1]
199
+ a.fetch = fetch.lower() if fetch in ("LAZY", "EAGER") else ("eager" if a.kind == "to_one" else "lazy")
200
+ target = _txt(args.get("targetEntity"))
201
+ if target.endswith(".class"):
202
+ a.type = target[:-6].split(".")[-1]
203
+ jcs = [x for use in an.get("JoinColumn", []) for x in [use]]
204
+ if jcs:
205
+ jname = ctx.sval(jf, jcs[0].get("name"))
206
+ if jname:
207
+ if a.kind == "to_one":
208
+ a.column, a.explicit = m.name(jname, True), True
209
+ else:
210
+ a.join_columns = [m.name(jname, True)]
211
+ elif a.kind == "to_one" and not a.column:
212
+ a.explicit = False
213
+ if "JoinTable" in an:
214
+ jt = an["JoinTable"][0]
215
+ a.join_table = m.name(ctx.sval(jf, jt.get("name")), True) if ctx.sval(jf, jt.get("name")) else ""
216
+ a.join_columns = _join_col_names(ctx, jf, _items(jt.get("joinColumns")))
217
+ a.inverse_columns = _join_col_names(ctx, jf, _items(jt.get("inverseJoinColumns")))
218
+ elif "ElementCollection" in an:
219
+ a.kind = "elements"
220
+ fetch = _txt(an["ElementCollection"][0].get("fetch")).rsplit(".", 1)[-1]
221
+ a.fetch = fetch.lower() if fetch in ("LAZY", "EAGER") else "lazy"
222
+ if "MapKeyColumn" in an:
223
+ a.key_column = m.name(ctx.sval(jf, an["MapKeyColumn"][0].get("name")) or "", True)
224
+ if "CollectionTable" in an:
225
+ ct = an["CollectionTable"][0]
226
+ a.join_table = m.name(ctx.sval(jf, ct.get("name")), True) if ctx.sval(jf, ct.get("name")) else ""
227
+ a.join_columns = _join_col_names(ctx, jf, _items(ct.get("joinColumns")))
228
+ elif "EmbeddedId" in an:
229
+ a.kind = "embedded_id"
230
+ elif "Embedded" in an:
231
+ a.kind = "embedded"
232
+ elif "Formula" in an:
233
+ a.kind = "formula"
234
+ elif "Id" in an:
235
+ a.kind = "id"
236
+ if "Id" in an and a.kind == "to_one":
237
+ a.id_part = True # a derived identity: the foreign key is part of the key
238
+ if "BatchSize" in an:
239
+ try:
240
+ a.batch_size = int(_txt(an["BatchSize"][0].get("size") or an["BatchSize"][0].get("value")) or 0)
241
+ except ValueError:
242
+ a.batch_size = 0
243
+ for use in an.get("AttributeOverride", []) + [
244
+ _anno_args(x) for o in an.get("AttributeOverrides", []) for x in _items(o.get("value")) if x.type == "annotation"]:
245
+ oname = ctx.sval(jf, use.get("name"))
246
+ ocol = use.get("column")
247
+ if oname and ocol is not None and ocol.type == "annotation":
248
+ cn = ctx.sval(jf, _anno_args(ocol).get("name"))
249
+ if cn:
250
+ a.overrides[oname] = m.name(cn, True)
251
+ return a
252
+
253
+
254
+ def _read_class(ctx: Ctx, jf, cls: Node) -> Entity | None:
255
+ an = _annos(cls)
256
+ kind = "entity" if "Entity" in an else "mapped" if "MappedSuperclass" in an else "embeddable" if "Embeddable" in an else ""
257
+ name_node = cls.child_by_field_name("name")
258
+ if name_node is None:
259
+ return None
260
+ cname = _txt(name_node)
261
+ supers = [s for s in jf.supers(cls)]
262
+ ctx.model.supers.setdefault(cname, supers)
263
+ if not kind and "Table" in an and any("springframework.data" in i for i in jf.imports):
264
+ kind = "entity" # Spring Data JDBC / R2DBC: @Table without @Entity
265
+ if not kind:
266
+ return None
267
+ m = ctx.model
268
+ e = Entity(cls=cname, name=cname, kind=kind, supers=supers, file=jf.rel, line=cls.start_point[0] + 1)
269
+ if "Entity" in an:
270
+ e.name = ctx.sval(jf, an["Entity"][0].get("name")) or cname
271
+ table = an.get("Table", [{}])[0]
272
+ tname = ctx.sval(jf, table.get("name") or table.get("value"))
273
+ if tname:
274
+ schema = ctx.sval(jf, table.get("schema"))
275
+ e.table, e.table_explicit = (schema + "." if schema else "") + m.name(tname, True), True
276
+ elif "Table" in an and (table.get("name") is not None):
277
+ e.table = "" # a name that could not be resolved: the entity is unusable
278
+ e.kind = "unresolved"
279
+ if "Inheritance" in an:
280
+ e.inheritance = _txt(an["Inheritance"][0].get("strategy")).rsplit(".", 1)[-1] or "SINGLE_TABLE"
281
+ for ix in _items(table.get("indexes")):
282
+ if ix.type == "annotation":
283
+ args = _anno_args(ix)
284
+ cols = [c.strip().split()[0] for c in ctx.sval(jf, args.get("columnList")).split(",") if c.strip()]
285
+ if cols:
286
+ e.indexes.append({"name": ctx.sval(jf, args.get("name")), "columns": [m.name(c, True) for c in cols],
287
+ "unique": _txt(args.get("unique")) == "true"})
288
+ for uc in _items(table.get("uniqueConstraints")):
289
+ if uc.type == "annotation":
290
+ args = _anno_args(uc)
291
+ cols = [ctx.sval(jf, c) for c in _items(args.get("columnNames"))]
292
+ if cols and all(cols):
293
+ e.indexes.append({"name": ctx.sval(jf, args.get("name")), "columns": [m.name(c, True) for c in cols], "unique": True})
294
+ body = cls.child_by_field_name("body")
295
+ members = _named(body)
296
+ fields: list[tuple[str, str, dict, int]] = []
297
+ getters: list[tuple[str, str, dict, int]] = []
298
+ for mem in members:
299
+ if mem.type == "field_declaration":
300
+ mods = _modifiers(mem)
301
+ if re.search(r"\b(static|transient)\b", mods):
302
+ continue
303
+ ftype = _txt(mem.child_by_field_name("type"))
304
+ fan = _annos(mem)
305
+ for d in mem.named_children:
306
+ if d.type == "variable_declarator" and d.child_by_field_name("name") is not None:
307
+ fields.append((_txt(d.child_by_field_name("name")), ftype, fan, mem.start_point[0] + 1))
308
+ elif mem.type == "method_declaration":
309
+ nm = _txt(mem.child_by_field_name("name"))
310
+ g = re.match(r"^(?:get|is)([A-Z]\w*)$", nm)
311
+ if g and not _named(mem.child_by_field_name("parameters")) and "static" not in _modifiers(mem):
312
+ getters.append((_decap(g.group(1)), _txt(mem.child_by_field_name("type")), _annos(mem), mem.start_point[0] + 1))
313
+ field_mapped = any(set(fan) & MAPPING_ANNOS for _, _, fan, _ in fields)
314
+ getter_mapped = any(set(gan) & MAPPING_ANNOS for _, _, gan, _ in getters)
315
+ source = getters if getter_mapped and not field_mapped else fields
316
+ for aname, jtype, aan, line in source:
317
+ a = _read_attr(ctx, jf, aname, jtype, aan, line)
318
+ if a is not None:
319
+ e.attrs[aname] = a
320
+ if getter_mapped and field_mapped: # mixed access: an annotated getter still defines its property
321
+ for aname, jtype, aan, line in getters:
322
+ if set(aan) & MAPPING_ANNOS and aname not in e.attrs:
323
+ a = _read_attr(ctx, jf, aname, jtype, aan, line)
324
+ if a is not None:
325
+ e.attrs[aname] = a
326
+ return e
327
+
328
+
329
+ _MODULE = re.compile(r"^(.*?)(?:^|/)src/")
330
+
331
+
332
+ def _module(rel: str) -> str:
333
+ """The build module a file belongs to: the path before its `src/` directory."""
334
+ m = _MODULE.match(rel)
335
+ return m.group(1) if m else rel.rsplit("/", 1)[0] if "/" in rel else ""
336
+
337
+
338
+ def _snake_closure(m: Model, e: Entity) -> None:
339
+ """Spring Boot naming for an entity, the mapped classes it inherits from and the embeddables it uses."""
340
+ for anc in m.chain(e):
341
+ m.make_snake(anc)
342
+ for a in anc.attrs.values():
343
+ emb = m.entities.get(a.type)
344
+ if a.kind in ("embedded", "embedded_id", "elements") and emb is not None and emb.kind == "embeddable":
345
+ m.make_snake(emb)
346
+
347
+
348
+ def build_model(ctx: Ctx) -> None:
349
+ m = ctx.model
350
+ m.snake = False
351
+ ctx.spring_modules = {_module(jf.rel) for jf in ctx.repo.files
352
+ if any(i.startswith(("org.springframework.boot", "org.springframework.data")) for i in jf.imports)}
353
+
354
+ def constant(path: str):
355
+ cls, name = path.split(".")[-2], path.split(".")[-1]
356
+ owners = ctx.repo.classes.get(cls, ())
357
+ if not owners:
358
+ return None
359
+ if any(node.type == "enum_declaration" for _jf, node in owners):
360
+ return "enum"
361
+ try:
362
+ r = ctx.repo.field(cls, name)
363
+ except Exception:
364
+ r = None
365
+ return ("value", r.text) if r is not None and not r.dynamic else None
366
+ m.constant = constant
367
+ for jf in ctx.repo.files:
368
+ for nodes in jf.classes.values():
369
+ for cls in nodes:
370
+ try:
371
+ e = _read_class(ctx, jf, cls)
372
+ except Exception:
373
+ e = None
374
+ if e is not None and e.kind != "unresolved":
375
+ if _is_test(jf.rel) and e.cls in m.entities and not _is_test(m.entities[e.cls].file):
376
+ continue
377
+ m.add(e)
378
+ # an attribute whose type is an @Embeddable class is embedded even without @Embedded
379
+ for e in m.entities.values():
380
+ for a in e.attrs.values():
381
+ if a.kind == "basic":
382
+ target = m.entities.get(a.type)
383
+ if target is not None and target.kind == "embeddable" and a.java_type.split("<")[0].split(".")[-1] == a.type:
384
+ a.kind = "embedded"
385
+ # Spring Boot's naming strategy applies to the entities of a module that uses Spring Boot or Spring Data
386
+ for e in list(m.entities.values()):
387
+ if _module(e.file) in ctx.spring_modules:
388
+ _snake_closure(m, e)
389
+
390
+
391
+ # ------------------------------------------------------------------------------------- SQL from the model
392
+ def select_by(model: Model, e: Entity, where: str = "", alias: str = "e", tail: str = "") -> str:
393
+ cols = ", ".join(f"{alias}.{c}" for c in model.columns(e))
394
+ return f"SELECT {cols} FROM {model.table(e)} {alias}" + (f" WHERE {where}" if where else "") + tail
395
+
396
+
397
+ def pk_predicate(model: Model, e: Entity, alias: str = "e", param: str = ":id") -> str | None:
398
+ pk = model.pk(e)
399
+ if not pk:
400
+ return None
401
+ q = alias + "." if alias else ""
402
+ if len(pk) == 1:
403
+ return f"{q}{pk[0]} = {param}"
404
+ return " AND ".join(f"{q}{c} = :{c}" for c in pk)
405
+
406
+
407
+ def _explicit(model: Model, e: Entity) -> bool:
408
+ return model.root(e).table_explicit and all(
409
+ a.explicit for a in model.attrs(e).values() if a.kind in ("basic", "id") or (a.kind == "to_one" and not a.mapped_by))
410
+
411
+
412
+ def _explicit_table(model: Model, e: Entity) -> bool:
413
+ return model.root(e).table_explicit
414
+
415
+
416
+ def eager_statements(ctx: Ctx, jf, node: Node, e: Entity, skip: set[str], sink: str, line_node: Node | None = None,
417
+ symbol: str | None = None, in_loop: bool | None = None) -> int:
418
+ """After a query returns entities, Hibernate loads each EAGER association it did not join with one more
419
+ SELECT per distinct referenced row. One site per such association."""
420
+ m = ctx.model
421
+ n = 0
422
+ for a in m.attrs(e).values():
423
+ if n >= MAX_EAGER:
424
+ break
425
+ if a.fetch != "eager" or a.kind not in ("to_one", "to_many", "elements") or a.type in skip:
426
+ continue
427
+ target = m.entities.get(a.type)
428
+ try:
429
+ if a.kind == "to_one":
430
+ if target is None or target.kind != "entity":
431
+ continue
432
+ if a.mapped_by:
433
+ inv = m.inverse(e, a)
434
+ if inv is None:
435
+ continue
436
+ sql = select_by(m, target, f"e.{m.fk(inv[1])} = ?")
437
+ else:
438
+ where = pk_predicate(m, target, "e", "?")
439
+ if where is None:
440
+ continue
441
+ sql = select_by(m, target, where)
442
+ note = (f"eager {a.relation} {e.name}.{a.name}: after a query, one more SELECT per distinct referenced row "
443
+ "unless it is join-fetched or already in the persistence context")
444
+ else:
445
+ sql = collection_select(m, e, a)
446
+ if sql is None:
447
+ continue
448
+ note = f"eager collection {e.name}.{a.name}: one more SELECT per returned {e.name}"
449
+ except Untranslatable:
450
+ continue
451
+ ctx.site(jf, node, sql, "jpa", m.table(target) if target is not None and target.kind == "entity" else m.table(e),
452
+ "eager load", "medium", note, sink=sink, line_node=line_node, symbol=symbol, in_loop=in_loop)
453
+ n += 1
454
+ return n
455
+
456
+
457
+ def collection_select(m: Model, owner: Entity, a: Attr) -> str | None:
458
+ """The SELECT Hibernate runs to initialise the collection `owner.a` of one owner."""
459
+ target = m.entities.get(a.type)
460
+ inv = m.inverse(owner, a) if a.mapped_by else None
461
+ if a.kind == "to_many" and target is not None and target.kind == "entity":
462
+ if inv is not None and inv[1].kind == "to_one":
463
+ return select_by(m, target, f"e.{m.fk(inv[1])} = ?")
464
+ if a.relation == "OneToMany" and not a.mapped_by and not a.join_table and a.join_columns:
465
+ return select_by(m, target, f"e.{a.join_columns[0]} = ?")
466
+ jt, back, to = m.collection_table(owner, a)
467
+ tpk = m.pk(target)
468
+ if len(tpk) != 1:
469
+ return None
470
+ cols = ", ".join(f"e.{c}" for c in m.columns(target))
471
+ return f"SELECT {cols} FROM {jt} j JOIN {m.table(target)} e ON e.{tpk[0]} = j.{to} WHERE j.{back} = ?"
472
+ if a.kind == "elements":
473
+ jt, back, value = m.collection_table(owner, a)
474
+ emb = m.embeddable(a.type)
475
+ cols = [m.column(x) for x in m.attrs(emb).values() if x.kind == "basic"] if emb is not None and emb.kind == "embeddable" else \
476
+ ([a.key_column] if a.key_column else []) + [value]
477
+ return f"SELECT {', '.join('c.' + c for c in cols)} FROM {jt} c WHERE c.{back} = ?"
478
+ return None
479
+
480
+
481
+ # ----------------------------------------------------------------------------------- JPQL sites to SQL
482
+ def _query_annotation_context(ctx: Ctx) -> dict[tuple[str, int], tuple[object, Node, Node]]:
483
+ """(file, line of the annotation) -> (file, annotation, method) for @Query on a method."""
484
+ out = {}
485
+ for jf in ctx.repo.files:
486
+ for ann in jf.annotations:
487
+ if _txt(ann.child_by_field_name("name")).split(".")[-1] != "Query":
488
+ continue
489
+ method = ann.parent.parent if ann.parent is not None else None
490
+ if method is not None and method.type == "method_declaration":
491
+ out[(jf.rel, ann.start_point[0] + 1)] = (jf, ann, method)
492
+ return out
493
+
494
+
495
+ def _method_params(method: Node) -> list[tuple[str, str]]:
496
+ out = []
497
+ for p in _named(method.child_by_field_name("parameters")):
498
+ nm = p.child_by_field_name("name")
499
+ if nm is not None:
500
+ out.append((_txt(nm), _txt(p.child_by_field_name("type"))))
501
+ return out
502
+
503
+
504
+ def _paging_tail(params: list[tuple[str, str]], sql: str) -> tuple[str, bool]:
505
+ """Pageable and Sort parameters add ordering and paging at run time."""
506
+ pageable = next((n for n, t in params if _outer_type(t) in PAGING_TYPES), "")
507
+ sort = next((n for n, t in params if _outer_type(t) == "Sort"), "")
508
+ limit = next((n for n, t in params if _outer_type(t) == "Limit"), "")
509
+ has_order = bool(re.search(r"\bORDER\s+BY\b(?![^()]*\))", sql, re.I))
510
+ tail = ""
511
+ if pageable:
512
+ tail += (", " if has_order else " ORDER BY ") + f"«{pageable}.sort»" + f" LIMIT «{pageable}.pageSize» OFFSET «{pageable}.offset»"
513
+ elif sort:
514
+ tail += (", " if has_order else " ORDER BY ") + f"«{sort}»"
515
+ if limit and not pageable:
516
+ tail += f" LIMIT «{limit}»"
517
+ return tail, bool(pageable)
518
+
519
+
520
+ def _returns_page(method: Node) -> bool:
521
+ return _outer_type(_txt(method.child_by_field_name("type"))) in ("Page", "PageData", "PagedModel")
522
+
523
+
524
+ def _count_jpql(jpql: str) -> str | None:
525
+ """The count query Spring Data derives from a JPQL query for a Page result."""
526
+ m = re.match(r"(?is)^\s*(select\s+(distinct\s+)?(.*?)\s+)?from\s+([\w.]+)(?:\s+as)?\s+(\w+)\b(.*)$", jpql)
527
+ if not m or re.search(r"(?i)\bgroup\s+by\b", jpql):
528
+ return None
529
+ alias, rest = m.group(5), m.group(6)
530
+ if alias.upper() in ("WHERE", "JOIN", "LEFT", "INNER", "ORDER", "GROUP"):
531
+ return None
532
+ rest = re.sub(r"(?is)\border\s+by\b(?![^()]*\)).*$", "", rest)
533
+ rest = re.sub(r"(?i)\bjoin\s+fetch\b", "join", rest)
534
+ return f"select count({'distinct ' if m.group(2) else ''}{alias}) from {m.group(4)} {alias}{rest}"
535
+
536
+
537
+ def translate_jpql_sites(ctx: Ctx, sites: list[RawSite]) -> None:
538
+ m = ctx.model
539
+ qctx = None
540
+ for s in sites:
541
+ if s.engine_hint != "jpql" or s.sql is None or s.language != "java" or id(s) in ctx.not_jpql:
542
+ continue
543
+ STATS.seen("jpa", s.is_test)
544
+ if not m.by_name:
545
+ STATS.miss("jpa", "no entity mapping in the repository", s.file, s.line, s.is_test)
546
+ continue
547
+ if qctx is None:
548
+ qctx = _query_annotation_context(ctx)
549
+ hit = qctx.get((s.file, s.line)) if s.sink.endswith("Query") and s.sink.startswith("@") else None
550
+ entity_name = ""
551
+ params: list[tuple[str, str]] = []
552
+ if hit is not None:
553
+ jf, ann, method = hit
554
+ params = _method_params(method)
555
+ iface = jf._enclosing(method, ("interface_declaration", "class_declaration"))
556
+ rname = _txt(iface.child_by_field_name("name")) if iface is not None else ""
557
+ if rname in ctx.repos:
558
+ entity_name = ctx.repos[rname][0].name
559
+ try:
560
+ res = orm_jpa.translate(s.sql, m, entity_name)
561
+ except Untranslatable as exc:
562
+ STATS.miss("jpa", str(exc), s.file, s.line, s.is_test)
563
+ continue
564
+ except RecursionError:
565
+ STATS.miss("jpa", "statement nested too deeply", s.file, s.line, s.is_test)
566
+ continue
567
+ original = s.sql
568
+ sql = res.sql
569
+ notes = list(res.notes)
570
+ is_count = "countQuery" in s.expr or bool(re.search(r"countQuery\s*=", s.expr))
571
+ paged = False
572
+ if hit is not None and res.kind == "select":
573
+ jf, ann, method = hit
574
+ args = _anno_args(ann)
575
+ this_is_count = "countQuery" in args and _same_text(ctx, jf, args["countQuery"], original)
576
+ if not this_is_count:
577
+ tail, paged = _paging_tail(params, sql)
578
+ sql += tail
579
+ table = m.table(res.root) if res.root is not None else ""
580
+ s.orm = {"library": "jpa", "model_or_table": table, "operation": "jpql " + res.kind,
581
+ "confidence": "medium" if res.assumed or notes else "high", "source": trim(original, 2000),
582
+ "id_from": [original, "jpql"]}
583
+ if res.assumed:
584
+ notes.append("a table or column name comes from the naming strategy, not from an explicit name in the mapping")
585
+ if notes:
586
+ s.orm["notes"] = "; ".join(notes)
587
+ s.sql, s.resolution, s.engine_hint = sql, "orm", ""
588
+ n = 1
589
+ if hit is not None and res.kind == "select":
590
+ jf, ann, method = hit
591
+ args = _anno_args(ann)
592
+ if paged and _returns_page(method) and "countQuery" not in args:
593
+ cj = _count_jpql(original)
594
+ if cj:
595
+ try:
596
+ cres = orm_jpa.translate(cj, m, entity_name)
597
+ ctx.site(jf, ann, cres.sql, "jpa", table, "count for Page", "medium",
598
+ "the count query Spring Data derives for a Page result", sink=s.sink, symbol=s.symbol,
599
+ in_loop=False, expr=s.expr)
600
+ n += 1
601
+ except (Untranslatable, RecursionError):
602
+ pass
603
+ fetched = {c for c, _ in res.fetched}
604
+ for e in res.selected[:1]:
605
+ n += eager_statements(ctx, jf, ann, e, fetched, s.sink, symbol=s.symbol, in_loop=s.in_loop)
606
+ STATS.hit("jpa", n, s.is_test)
607
+
608
+
609
+ def _same_text(ctx: Ctx, jf, node: Node, text: str) -> bool:
610
+ try:
611
+ r = jf.resolve(node, node, 0)
612
+ except Exception:
613
+ return False
614
+ return r is not None and " ".join(r.text.split()) == " ".join(text.split())
615
+
616
+
617
+ # ------------------------------------------------------------------------------- Spring Data repositories
618
+ def find_repositories(ctx: Ctx) -> None:
619
+ m = ctx.model
620
+ pending: list[tuple[str, object, Node, str]] = []
621
+ for jf in ctx.repo.files:
622
+ for name, nodes in jf.classes.items():
623
+ for node in nodes:
624
+ if node.type != "interface_declaration":
625
+ continue
626
+ ext = next((c for c in node.children if c.type == "extends_interfaces"), None)
627
+ text = _txt(ext)
628
+ if not text:
629
+ continue
630
+ if NOT_SQL_REPOS.search(text):
631
+ continue
632
+ pending.append((name, jf, node, text))
633
+ known_bases = set(REPO_BASES)
634
+ generic_bases: set[str] = set()
635
+ for _ in range(4):
636
+ grew = False
637
+ for name, jf, node, text in pending:
638
+ if name in ctx.repos or name in generic_bases:
639
+ continue
640
+ mt = re.search(r"\b(" + "|".join(sorted(known_bases | generic_bases, key=len, reverse=True)) + r")\s*<\s*([\w.]+)\s*[,>]", text)
641
+ if mt is None:
642
+ if any(re.search(r"\b" + re.escape(b) + r"\b", text) for b in known_bases) and name not in known_bases:
643
+ # `interface Base<T, ID> extends JpaRepository<T, ID>`: a base other repositories extend
644
+ pass
645
+ continue
646
+ arg = mt.group(2).split(".")[-1]
647
+ e = m.entities.get(arg)
648
+ if e is not None and e.kind == "entity":
649
+ ctx.repos[name] = (e, jf, node)
650
+ grew = True
651
+ else:
652
+ tparams = _txt(node.child_by_field_name("type_parameters"))
653
+ if re.search(r"\b" + re.escape(arg) + r"\b", tparams):
654
+ generic_bases.add(name)
655
+ grew = True
656
+ else:
657
+ ctx.repo_misses[name] = "entity class of the repository is not a mapped entity in the repository"
658
+ if not grew:
659
+ break
660
+ # an entity of a plain module that a Spring Data repository manages is named by Spring's strategy too
661
+ for e, jf, _node in ctx.repos.values():
662
+ if _module(jf.rel) in getattr(ctx, "spring_modules", ()):
663
+ _snake_closure(m, e)
664
+
665
+
666
+ SUBJECT = re.compile(r"^(find|read|get|query|search|stream|count|exists|delete|remove)([A-Z]\w*?)??By([A-Z]\w*)?$")
667
+ PART_KEYWORDS = [
668
+ ("IsNotNull", "notnull", 0), ("NotNull", "notnull", 0), ("IsNull", "null", 0), ("Null", "null", 0),
669
+ ("IsBetween", "between", 2), ("Between", "between", 2),
670
+ ("IsLessThanEqual", "<=", 1), ("LessThanEqual", "<=", 1), ("IsLessThan", "<", 1), ("LessThan", "<", 1),
671
+ ("IsGreaterThanEqual", ">=", 1), ("GreaterThanEqual", ">=", 1), ("IsGreaterThan", ">", 1), ("GreaterThan", ">", 1),
672
+ ("IsAfter", ">", 1), ("After", ">", 1), ("IsBefore", "<", 1), ("Before", "<", 1),
673
+ ("IsNotLike", "notlike", 1), ("NotLike", "notlike", 1), ("IsLike", "like", 1), ("Like", "like", 1),
674
+ ("IsStartingWith", "starts", 1), ("StartingWith", "starts", 1), ("StartsWith", "starts", 1),
675
+ ("IsEndingWith", "ends", 1), ("EndingWith", "ends", 1), ("EndsWith", "ends", 1),
676
+ ("IsNotContaining", "notcontains", 1), ("NotContaining", "notcontains", 1), ("NotContains", "notcontains", 1),
677
+ ("IsContaining", "contains", 1), ("Containing", "contains", 1), ("Contains", "contains", 1),
678
+ ("IsNotIn", "notin", 1), ("NotIn", "notin", 1), ("IsIn", "in", 1), ("In", "in", 1),
679
+ ("IsTrue", "true", 0), ("True", "true", 0), ("IsFalse", "false", 0), ("False", "false", 0),
680
+ ("IsNotEmpty", "notempty", 0), ("NotEmpty", "notempty", 0), ("IsEmpty", "empty", 0), ("Empty", "empty", 0),
681
+ ("MatchesRegex", "regex", 1), ("Matches", "regex", 1), ("Regex", "regex", 1),
682
+ ("IsNot", "<>", 1), ("Not", "<>", 1), ("Equals", "=", 1), ("Is", "=", 1),
683
+ ]
684
+ CRUD_METHODS = {"findById", "findAll", "findAllById", "existsById", "count", "save", "saveAll", "saveAndFlush",
685
+ "saveAllAndFlush", "deleteById", "delete", "deleteAll", "deleteAllById", "deleteAllInBatch",
686
+ "deleteAllByIdInBatch", "deleteInBatch", "getReferenceById", "getById", "getOne", "findOne", "exists",
687
+ "flush"}
688
+
689
+
690
+ def _property_path(m: Model, e: Entity, prop: str) -> str | None:
691
+ """`AddressZipCode` -> address.zipCode, the way Spring Data walks a property expression."""
692
+ def walk(owner: Entity, rest: str) -> list[str] | None:
693
+ if "_" in rest:
694
+ head, tail = rest.split("_", 1)
695
+ a = m.attr(owner, _decap(head))
696
+ if a is None or not tail:
697
+ return None
698
+ nxt = m.entities.get(a.type)
699
+ sub = walk(nxt, tail) if nxt is not None and a.kind in ("to_one", "embedded", "embedded_id", "to_many") else None
700
+ return [a.name] + sub if sub else None
701
+ a = owner.attrs.get(_decap(rest)) or m.attrs(owner).get(_decap(rest))
702
+ if a is not None:
703
+ return [a.name]
704
+ cuts = [i for i in range(len(rest) - 1, 0, -1) if rest[i].isupper()]
705
+ for i in cuts:
706
+ a = m.attrs(owner).get(_decap(rest[:i]))
707
+ if a is None or a.kind not in ("to_one", "embedded", "embedded_id", "to_many"):
708
+ continue
709
+ nxt = m.entities.get(a.type)
710
+ sub = walk(nxt, rest[i:]) if nxt is not None else None
711
+ if sub:
712
+ return [a.name] + sub
713
+ return None
714
+ path = walk(e, prop)
715
+ return ".".join(path) if path else None
716
+
717
+
718
+ def derived_jpql(m: Model, e: Entity, name: str, params: list[tuple[str, str]]) -> tuple[str, str, int | None, list[str]] | None:
719
+ """(operation, JPQL, limit, notes) for a Spring Data derived query method name, or None when it is not one.
720
+ Raises Untranslatable when it is one and a property cannot be resolved."""
721
+ mt = SUBJECT.match(name)
722
+ if mt is None:
723
+ return None
724
+ verb, subject, rest = mt.group(1), mt.group(2) or "", mt.group(3) or ""
725
+ op = {"count": "count", "exists": "exists", "delete": "delete", "remove": "delete"}.get(verb, "find")
726
+ distinct = "Distinct" in subject
727
+ limit = None
728
+ lm = re.search(r"(First|Top)(\d*)", subject)
729
+ if lm:
730
+ limit = int(lm.group(2) or 1)
731
+ pred, _, order = rest.partition("OrderBy") if not rest.startswith("OrderBy") else ("", "", rest[len("OrderBy"):])
732
+ values = [n for n, t in params if _outer_type(t) not in PAGING_TYPES + ("Sort", "Limit", "Class", "ScrollPosition")]
733
+ vi = 0
734
+ notes: list[str] = []
735
+
736
+ def take() -> str:
737
+ nonlocal vi
738
+ vi += 1
739
+ return ":" + values[vi - 1] if vi <= len(values) else "?"
740
+
741
+ ors = []
742
+ all_ignore = False
743
+ if pred.endswith("AllIgnoreCase") or pred.endswith("AllIgnoringCase"):
744
+ all_ignore = True
745
+ pred = re.sub(r"AllIgnor(e|ing)Case$", "", pred)
746
+ for or_part in (re.split(r"Or(?=[A-Z])", pred) if pred else []):
747
+ ands = []
748
+ for part in re.split(r"And(?=[A-Z])", or_part):
749
+ if not part:
750
+ continue
751
+ ignore = all_ignore
752
+ g = re.search(r"(IgnoreCase|IgnoringCase)$", part)
753
+ if g:
754
+ ignore = True
755
+ part = part[: g.start()]
756
+ kw, nargs, prop = "=", 1, part
757
+ for suffix, k, n in PART_KEYWORDS:
758
+ if part.endswith(suffix) and len(part) > len(suffix) and _property_path(m, e, part[: -len(suffix)]) is not None:
759
+ kw, nargs, prop = k, n, part[: -len(suffix)]
760
+ break
761
+ path = _property_path(m, e, prop)
762
+ if path is None:
763
+ raise Untranslatable("derived query: property not found on the entity")
764
+ lhs = f"e.{path}"
765
+ wrap = (lambda x: f"upper({x})") if ignore else (lambda x: x)
766
+ if kw in ("=", "<>", "<", "<=", ">", ">="):
767
+ ands.append(f"{wrap(lhs)} {kw} {wrap(take())}")
768
+ elif kw == "null":
769
+ ands.append(f"{lhs} is null")
770
+ elif kw == "notnull":
771
+ ands.append(f"{lhs} is not null")
772
+ elif kw == "between":
773
+ ands.append(f"{lhs} between {take()} and {take()}")
774
+ elif kw in ("like", "notlike"):
775
+ ands.append(f"{wrap(lhs)} {'not ' if kw == 'notlike' else ''}like {wrap(take())}")
776
+ elif kw == "starts":
777
+ ands.append(f"{wrap(lhs)} like {wrap('concat(' + take() + ', ' + chr(39) + '%' + chr(39) + ')')}")
778
+ elif kw == "ends":
779
+ ands.append(f"{wrap(lhs)} like {wrap('concat(' + chr(39) + '%' + chr(39) + ', ' + take() + ')')}")
780
+ elif kw in ("contains", "notcontains"):
781
+ ands.append(f"{wrap(lhs)} {'not ' if kw == 'notcontains' else ''}like "
782
+ f"{wrap('concat(' + chr(39) + '%' + chr(39) + ', ' + take() + ', ' + chr(39) + '%' + chr(39) + ')')}")
783
+ elif kw in ("in", "notin"):
784
+ ands.append(f"{lhs} {'not ' if kw == 'notin' else ''}in ({take()})")
785
+ elif kw in ("true", "false"):
786
+ ands.append(f"{lhs} = {kw}")
787
+ elif kw in ("empty", "notempty"):
788
+ ands.append(f"{lhs} is {'not ' if kw == 'notempty' else ''}empty")
789
+ else:
790
+ raise Untranslatable("derived query: regular-expression keyword")
791
+ if ands:
792
+ ors.append(" and ".join(ands))
793
+ where = ""
794
+ if ors:
795
+ where = " where " + (" or ".join(ors) if len(ors) > 1 else ors[0])
796
+ order_sql = ""
797
+ if order:
798
+ items = []
799
+ for om in re.finditer(r"(.+?)(Asc|Desc)(?=[A-Z]|$)|(.+)$", order):
800
+ prop, direction = (om.group(1), om.group(2)) if om.group(1) else (om.group(3), "Asc")
801
+ path = _property_path(m, e, prop)
802
+ if path is None:
803
+ raise Untranslatable("derived query: ORDER BY property not found on the entity")
804
+ items.append(f"e.{path} {direction.lower()}")
805
+ order_sql = " order by " + ", ".join(items)
806
+ if op == "count":
807
+ jpql = f"select count({'distinct ' if distinct else ''}e) from {e.name} e{where}"
808
+ elif op == "exists":
809
+ jpql = f"select 1 from {e.name} e{where}"
810
+ limit = 1
811
+ else:
812
+ jpql = f"select {'distinct ' if distinct else ''}e from {e.name} e{where}{order_sql}"
813
+ return op, jpql, limit, notes
814
+
815
+
816
+ def repository_methods(ctx: Ctx) -> None:
817
+ m = ctx.model
818
+ for rname, (e, jf, node) in ctx.repos.items():
819
+ body = node.child_by_field_name("body")
820
+ test = _is_test(jf.rel)
821
+ for meth in _named(body):
822
+ if meth.type != "method_declaration" or meth.child_by_field_name("body") is not None:
823
+ continue
824
+ an = _annos(meth)
825
+ if "Query" in an or "Procedure" in an:
826
+ continue # reported as a JPQL or native query site
827
+ name_node = meth.child_by_field_name("name")
828
+ name = _txt(name_node)
829
+ params = _method_params(meth)
830
+ STATS.seen("spring-data", test)
831
+ sink = f"{rname}.{name}"
832
+ if name in CRUD_METHODS:
833
+ n = crud_sites(ctx, jf, meth, e, name, [t for _, t in params], [n for n, _ in params], sink, line_node=name_node)
834
+ if n:
835
+ STATS.hit("spring-data", n, test)
836
+ else:
837
+ STATS.miss("spring-data", "repository method without a fixed statement", jf.rel, meth.start_point[0] + 1, test)
838
+ continue
839
+ if any(_outer_type(t) in ("Specification", "Example", "Predicate") for _, t in params):
840
+ STATS.miss("spring-data", "Specification / Example / Querydsl predicate: built at run time", jf.rel, meth.start_point[0] + 1, test)
841
+ continue
842
+ try:
843
+ d = derived_jpql(m, e, name, params)
844
+ if d is None:
845
+ STATS.miss("spring-data", "method name is not a derived query (custom implementation or named query)",
846
+ jf.rel, meth.start_point[0] + 1, test)
847
+ continue
848
+ op, jpql, limit, notes = d
849
+ res = orm_jpa.translate(jpql, m)
850
+ except Untranslatable as exc:
851
+ STATS.miss("spring-data", str(exc), jf.rel, meth.start_point[0] + 1, test)
852
+ continue
853
+ sql = res.sql
854
+ notes = notes + list(res.notes)
855
+ graph = entity_graph(ctx, jf, an, e)
856
+ if graph:
857
+ sql, gnote = graph_joins(m, e, sql, graph)
858
+ notes.append(gnote)
859
+ paged = False
860
+ if op == "find":
861
+ if limit is not None:
862
+ sql += f" LIMIT {limit}"
863
+ tail, paged = _paging_tail(params, sql)
864
+ if not (limit is not None and "LIMIT" in tail):
865
+ sql += tail
866
+ elif op == "exists":
867
+ sql += " LIMIT 1"
868
+ conf = "medium" if res.assumed or res.notes else "high"
869
+ if res.assumed:
870
+ notes.append("a table or column name comes from the naming strategy, not from an explicit name in the mapping")
871
+ table = m.table(e)
872
+ ctx.site(jf, meth, sql, "spring-data", table, "derived " + op, conf, notes, sink=sink, line_node=name_node,
873
+ in_loop=False, expr=name)
874
+ n = 1
875
+ if op == "delete":
876
+ where = pk_predicate(m, e, "", "?")
877
+ if where:
878
+ ctx.site(jf, meth, f"DELETE FROM {table} WHERE {where}", "spring-data", table, "derived delete", "medium",
879
+ "a derived delete loads the matching entities, then deletes each one by its id: one DELETE per row",
880
+ sink=sink, line_node=name_node, in_loop=False, expr=name)
881
+ n += 1
882
+ if op == "find":
883
+ if paged and _returns_page(meth):
884
+ try:
885
+ cres = orm_jpa.translate(_count_jpql(jpql) or "", m)
886
+ ctx.site(jf, meth, cres.sql, "spring-data", table, "count for Page", conf,
887
+ "the count query Spring Data runs for a Page result", sink=sink, line_node=name_node,
888
+ in_loop=False, expr=name)
889
+ n += 1
890
+ except Untranslatable:
891
+ pass
892
+ n += eager_statements(ctx, jf, meth, e, {m.attr(e, g.split(".")[0]).type for g in graph if m.attr(e, g.split(".")[0])},
893
+ sink, line_node=name_node, in_loop=False)
894
+ STATS.hit("spring-data", n, test)
895
+
896
+
897
+ def entity_graph(ctx: Ctx, jf, an: dict, e: Entity) -> list[str]:
898
+ if "EntityGraph" not in an:
899
+ return []
900
+ args = an["EntityGraph"][0]
901
+ return [p for p in (ctx.sval(jf, x) for x in _items(args.get("attributePaths"))) if p]
902
+
903
+
904
+ def graph_joins(m: Model, e: Entity, sql: str, paths: list[str]) -> tuple[str, str]:
905
+ """@EntityGraph(attributePaths): the named associations are fetched in the same SELECT with LEFT JOINs."""
906
+ joins, cols, done = [], [], []
907
+ for k, p in enumerate(paths):
908
+ a = m.attr(e, p.split(".")[0])
909
+ target = m.entities.get(a.type) if a is not None else None
910
+ if a is None or target is None or target.kind != "entity" or "." in p:
911
+ continue
912
+ q = f"g{k}"
913
+ tpk, opk = m.pk(target), m.pk(e)
914
+ if a.kind == "to_one" and not a.mapped_by and len(tpk) == 1:
915
+ joins.append(f"LEFT JOIN {m.table(target)} {q} ON {q}.{tpk[0]} = e.{m.fk(a)}")
916
+ elif a.kind == "to_many" and a.mapped_by and len(opk) == 1 and m.inverse(e, a) is not None and m.inverse(e, a)[1].kind == "to_one":
917
+ joins.append(f"LEFT JOIN {m.table(target)} {q} ON {q}.{m.fk(m.inverse(e, a)[1])} = e.{opk[0]}")
918
+ else:
919
+ continue
920
+ cols.extend(f"{q}.{c}" for c in m.columns(target))
921
+ done.append(p)
922
+ if not joins:
923
+ return sql, "@EntityGraph: the named paths could not be resolved to joins"
924
+ mt = re.match(r"(?s)^(SELECT .*?)( FROM \S+ e)(.*)$", sql)
925
+ if mt is None:
926
+ return sql, "@EntityGraph: not applied"
927
+ return (mt.group(1) + ", " + ", ".join(cols) + mt.group(2) + " " + " ".join(joins) + mt.group(3),
928
+ "@EntityGraph: " + ", ".join(done) + " fetched with LEFT JOIN in the same statement")
929
+
930
+
931
+ def crud_sites(ctx: Ctx, jf, node: Node, e: Entity, name: str, arg_types: list[str], arg_names: list[str], sink: str,
932
+ line_node: Node | None = None, in_loop: bool | None = None, library: str = "spring-data") -> int:
933
+ """Sites for one of the methods every Spring Data repository inherits. Returns how many were added."""
934
+ m = ctx.model
935
+ table = m.table(e)
936
+ conf = "high" if _explicit(m, e) else "medium"
937
+ base_note = "" if conf == "high" else "a table or column name comes from the naming strategy, not from an explicit name in the mapping"
938
+ pkp = pk_predicate(m, e, "e", ":id")
939
+ pkp_bare = pk_predicate(m, e, "", ":id")
940
+ cols = m.columns(e)
941
+ outer = [_outer_type(t) for t in arg_types]
942
+
943
+ def add(sql: str, op: str, note: str = "", confidence: str = conf) -> None:
944
+ ctx.site(jf, node, sql, library, table, op, confidence, "; ".join(x for x in (note, base_note) if x), sink=sink,
945
+ line_node=line_node, in_loop=in_loop)
946
+
947
+ n = 0
948
+ if name in ("findById", "findOne", "getById", "getOne", "getReferenceById") and pkp:
949
+ if any(t in ("Specification", "Example", "Predicate") for t in outer):
950
+ return 0
951
+ note = "returns a lazy reference; the SELECT runs on first access" if name in ("getById", "getOne", "getReferenceById") else ""
952
+ add(_find_sql(m, e, pkp), "find by id", note)
953
+ n = 1
954
+ elif name == "findAll":
955
+ if any(t in ("Specification", "Example", "Predicate") for t in outer):
956
+ return 0
957
+ sql = select_by(m, e)
958
+ tail, paged = _paging_tail(list(zip(arg_names, arg_types)), sql)
959
+ add(sql + tail, "find all")
960
+ n = 1
961
+ if paged:
962
+ add(f"SELECT COUNT({'e.' + m.pk(e)[0] if len(m.pk(e)) == 1 else '*'}) FROM {table} e", "count for Page",
963
+ "the count query Spring Data runs for a Page result")
964
+ n += 1
965
+ n += eager_statements(ctx, jf, node, e, set(), sink, line_node=line_node, in_loop=in_loop)
966
+ elif name == "findAllById" and len(m.pk(e)) == 1:
967
+ add(select_by(m, e, f"e.{m.pk(e)[0]} IN (:ids)"), "find by ids")
968
+ n = 1 + eager_statements(ctx, jf, node, e, set(), sink, line_node=line_node, in_loop=in_loop)
969
+ elif name in ("existsById",) and pkp:
970
+ add(f"SELECT COUNT(*) FROM {table} e WHERE {pkp}", "exists by id")
971
+ n = 1
972
+ elif name == "count" and not arg_types:
973
+ add(f"SELECT COUNT(*) FROM {table} e", "count")
974
+ n = 1
975
+ elif name in ("save", "saveAndFlush", "saveAll", "saveAllAndFlush") and cols:
976
+ many = " (one statement per entity)" if "All" in name else ""
977
+ add(f"INSERT INTO {table} ({', '.join(cols)}) VALUES ({', '.join('?' for _ in cols)})", "save",
978
+ "save: INSERT for a new entity; for an existing one a SELECT by id (when detached) and an UPDATE at flush" + many,
979
+ "medium")
980
+ n = 1
981
+ elif name in ("deleteById", "delete") and pkp_bare:
982
+ add(f"DELETE FROM {table} WHERE {pk_predicate(m, e, '', '?')}", "delete",
983
+ "deleteById loads the entity first (SELECT by id), then deletes it" if name == "deleteById" else "runs at flush", "medium")
984
+ n = 1
985
+ elif name in ("deleteAll", "deleteAllById") and pkp_bare:
986
+ add(f"DELETE FROM {table} WHERE {pk_predicate(m, e, '', '?')}", "delete",
987
+ "loads the entities, then one DELETE per entity", "medium")
988
+ n = 1
989
+ elif name in ("deleteAllInBatch", "deleteInBatch", "deleteAllByIdInBatch"):
990
+ if not arg_types:
991
+ add(f"DELETE FROM {table}", "delete all in batch")
992
+ elif len(m.pk(e)) == 1:
993
+ add(f"DELETE FROM {table} WHERE {m.pk(e)[0]} IN (:ids)", "delete in batch")
994
+ else:
995
+ return 0
996
+ n = 1
997
+ return n
998
+
999
+
1000
+ def _find_sql(m: Model, e: Entity, where: str) -> str:
1001
+ """`find` by id: Hibernate joins the EAGER to-one associations in the same SELECT."""
1002
+ cols = [f"e.{c}" for c in m.columns(e)]
1003
+ joins = []
1004
+ k = 0
1005
+ for a in m.attrs(e).values():
1006
+ if a.kind == "to_one" and a.fetch == "eager" and not a.mapped_by:
1007
+ target = m.entities.get(a.type)
1008
+ tpk = m.pk(target) if target is not None and target.kind == "entity" else []
1009
+ if len(tpk) != 1 or k >= MAX_EAGER:
1010
+ continue
1011
+ q = f"j{k}"
1012
+ k += 1
1013
+ joins.append(f" LEFT JOIN {m.table(target)} {q} ON {q}.{tpk[0]} = e.{m.fk(a)}")
1014
+ cols.extend(f"{q}.{c}" for c in m.columns(target))
1015
+ return f"SELECT {', '.join(cols)} FROM {m.table(e)} e" + "".join(joins) + f" WHERE {where}"
1016
+
1017
+
1018
+ # ------------------------------------------------------------------- calls: repositories, EntityManager
1019
+ def _decl_type(ctx: Ctx, jf, name: str, at: Node) -> str:
1020
+ """The declared type of a local variable, parameter, loop variable or field, as written."""
1021
+ n = at.parent
1022
+ while n is not None:
1023
+ if n.type == "enhanced_for_statement":
1024
+ nm = n.child_by_field_name("name")
1025
+ if nm is not None and _txt(nm) == name:
1026
+ return _txt(n.child_by_field_name("type"))
1027
+ elif n.type == "lambda_expression":
1028
+ params = n.child_by_field_name("parameters")
1029
+ if params is not None and params.type == "formal_parameters":
1030
+ for p in _named(params):
1031
+ if _txt(p.child_by_field_name("name")) == name:
1032
+ return _txt(p.child_by_field_name("type"))
1033
+ n = n.parent
1034
+ for func in jf._scopes(at):
1035
+ t = jf.scope(func).types.get(name, "")
1036
+ if t:
1037
+ return t
1038
+ t = jf.field_types.get(name, "")
1039
+ if t:
1040
+ return t
1041
+ cls = jf._enclosing(at, ("class_declaration",))
1042
+ seen: set[str] = set()
1043
+ queue = list(jf.supers(cls)) if cls is not None else []
1044
+ while queue:
1045
+ sup = queue.pop(0)
1046
+ if sup in seen:
1047
+ continue
1048
+ seen.add(sup)
1049
+ for sjf, snode in ctx.repo.classes.get(sup, ()):
1050
+ t = sjf.field_types.get(name, "")
1051
+ if t:
1052
+ return t
1053
+ queue.extend(sjf.supers(snode))
1054
+ return ""
1055
+
1056
+
1057
+ def _receiver_type(ctx: Ctx, jf, obj: Node | None, at: Node) -> str:
1058
+ if obj is None:
1059
+ return ""
1060
+ if obj.type == "identifier":
1061
+ return _decl_type(ctx, jf, _txt(obj), at)
1062
+ if obj.type == "field_access" and _txt(obj.child_by_field_name("object")) == "this":
1063
+ return jf.field_types.get(_txt(obj.child_by_field_name("field")), "")
1064
+ return ""
1065
+
1066
+
1067
+ def _expr_entity(ctx: Ctx, jf, arg: Node, at: Node) -> Entity | None:
1068
+ """The entity class of an argument: a typed variable, `new X(...)`, or a cast."""
1069
+ m = ctx.model
1070
+ t = ""
1071
+ if arg.type == "identifier":
1072
+ t = _decl_type(ctx, jf, _txt(arg), at)
1073
+ if t == "var" or not t:
1074
+ for func in jf._scopes(at):
1075
+ for kind, _node, payload in jf.scope(func).events.get(_txt(arg), ()):
1076
+ if kind == "set" and payload.type == "object_creation_expression":
1077
+ t = _txt(payload.child_by_field_name("type"))
1078
+ elif arg.type == "object_creation_expression":
1079
+ t = _txt(arg.child_by_field_name("type"))
1080
+ elif arg.type == "cast_expression":
1081
+ t = _txt(arg.child_by_field_name("type"))
1082
+ e = m.entities.get(_outer_type(t)) if t else None
1083
+ return e if e is not None and e.kind == "entity" else None
1084
+
1085
+
1086
+ EM_METHODS = {"find", "persist", "merge", "remove", "getReference", "refresh"}
1087
+ EM_TYPES = {"EntityManager", "Session", "StatelessSession", "TestEntityManager"}
1088
+ EM_NAMES = re.compile(r"^(em|entityManager|session|manager|entityMgr)$", re.I)
1089
+ REPO_NAMES = re.compile(r"(repo|repository|dao)$", re.I)
1090
+ CRITERIA_CALLS = {"getCriteriaBuilder"}
1091
+
1092
+
1093
+ def call_sites(ctx: Ctx) -> None:
1094
+ m = ctx.model
1095
+ for jf in ctx.repo.files:
1096
+ test = _is_test(jf.rel)
1097
+ for call in jf.calls:
1098
+ name = _txt(call.child_by_field_name("name"))
1099
+ if name in CRITERIA_CALLS:
1100
+ STATS.seen("jpa-criteria", test)
1101
+ STATS.miss("jpa-criteria", "Criteria API: the query is assembled from objects at run time", jf.rel, call.start_point[0] + 1, test)
1102
+ continue
1103
+ if name not in CRUD_METHODS and name not in EM_METHODS:
1104
+ continue
1105
+ obj = call.child_by_field_name("object")
1106
+ if obj is None:
1107
+ continue
1108
+ args = _named(call.child_by_field_name("arguments"))
1109
+ rtype = _outer_type(_receiver_type(ctx, jf, obj, call))
1110
+ obj_text = _txt(obj)
1111
+ if name in EM_METHODS and (rtype in EM_TYPES or (not rtype and EM_NAMES.match(obj_text.split(".")[-1]))):
1112
+ if not m.by_name:
1113
+ continue
1114
+ STATS.seen("jpa-entitymanager", test)
1115
+ n, why = _em_site(ctx, jf, call, name, args, obj_text)
1116
+ if n:
1117
+ STATS.hit("jpa-entitymanager", n, test)
1118
+ else:
1119
+ STATS.miss("jpa-entitymanager", why, jf.rel, call.start_point[0] + 1, test)
1120
+ continue
1121
+ if name not in CRUD_METHODS or name == "flush":
1122
+ continue
1123
+ if rtype in ctx.repos:
1124
+ e = ctx.repos[rtype][0]
1125
+ STATS.seen("spring-data", test)
1126
+ if any(a.type == "identifier" and _outer_type(_decl_type(ctx, jf, _txt(a), call)) in ("Specification", "Example", "Predicate")
1127
+ for a in args) and name in ("findAll", "findOne", "count", "exists", "delete"):
1128
+ STATS.miss("spring-data", "Specification / Example / Querydsl predicate: built at run time", jf.rel, call.start_point[0] + 1, test)
1129
+ continue
1130
+ types, names = [], []
1131
+ for a in args:
1132
+ t = _decl_type(ctx, jf, _txt(a), call) if a.type == "identifier" else ""
1133
+ if not t and a.type == "method_invocation" and _txt(a.child_by_field_name("object")) in ("PageRequest", "Pageable"):
1134
+ t = "Pageable"
1135
+ if not t and a.type == "method_invocation" and _txt(a.child_by_field_name("object")) == "Sort":
1136
+ t = "Sort"
1137
+ types.append(t)
1138
+ names.append(trim(_txt(a), 40))
1139
+ if name == "count" and args:
1140
+ STATS.miss("spring-data", "Specification / Example / Querydsl predicate: built at run time", jf.rel, call.start_point[0] + 1, test)
1141
+ continue
1142
+ n = crud_sites(ctx, jf, call, e, name, types, names, f"{obj_text}.{name}", line_node=call.child_by_field_name("name"))
1143
+ if n:
1144
+ STATS.hit("spring-data", n, test)
1145
+ else:
1146
+ STATS.miss("spring-data", "repository method without a fixed statement", jf.rel, call.start_point[0] + 1, test)
1147
+ elif (rtype in ctx.repo_misses or (rtype in ("JpaRepository", "CrudRepository", "PagingAndSortingRepository"))
1148
+ or (not rtype and obj.type == "method_invocation" and REPO_NAMES.search(_txt(obj.child_by_field_name("name"))))):
1149
+ STATS.seen("spring-data", test)
1150
+ STATS.miss("spring-data", ctx.repo_misses.get(rtype, "repository of a generic or unknown entity type: the table is decided by a subclass"),
1151
+ jf.rel, call.start_point[0] + 1, test)
1152
+
1153
+
1154
+ def _em_site(ctx: Ctx, jf, call: Node, name: str, args: list[Node], obj_text: str) -> tuple[int, str]:
1155
+ m = ctx.model
1156
+ sink = f"{obj_text}.{name}"
1157
+ if name in ("find", "getReference"):
1158
+ if not args:
1159
+ return 0, "no entity class argument"
1160
+ t = _txt(args[0])
1161
+ if not t.endswith(".class"):
1162
+ return 0, "entity class passed as a variable"
1163
+ e = m.entities.get(t[:-6].split(".")[-1])
1164
+ if e is None or e.kind != "entity":
1165
+ return 0, "entity not found: mapping not in the repository"
1166
+ where = pk_predicate(m, e, "e", ":id")
1167
+ if where is None:
1168
+ return 0, "entity without a mapped @Id"
1169
+ conf = "high" if _explicit(m, e) else "medium"
1170
+ note = "returns a lazy reference; the SELECT runs on first access" if name == "getReference" else \
1171
+ "served from the persistence context when the entity is already loaded"
1172
+ lock = " ".join(_txt(a) for a in args[2:])
1173
+ tail = " FOR UPDATE" if re.search(r"PESSIMISTIC_(WRITE|FORCE_INCREMENT)", lock) else " FOR SHARE" if "PESSIMISTIC_READ" in lock else ""
1174
+ ctx.site(jf, call, _find_sql(m, e, where) + tail, "jpa", m.table(e), "find by id", conf, note, sink=sink,
1175
+ line_node=call.child_by_field_name("name"))
1176
+ return 1, ""
1177
+ if not args:
1178
+ return 0, "no entity argument"
1179
+ e = _expr_entity(ctx, jf, args[0], call)
1180
+ if e is None:
1181
+ return 0, "entity type of the argument is not known statically"
1182
+ table, cols = m.table(e), m.columns(e)
1183
+ if not cols:
1184
+ return 0, "entity without mapped columns"
1185
+ conf = "medium"
1186
+ line_node = call.child_by_field_name("name")
1187
+ if name == "persist":
1188
+ ctx.site(jf, call, f"INSERT INTO {table} ({', '.join(cols)}) VALUES ({', '.join('?' for _ in cols)})", "jpa", table,
1189
+ "persist", conf, "runs at flush; cascaded associations add their own statements", sink=sink, line_node=line_node)
1190
+ elif name == "merge":
1191
+ pk = set(m.pk(e))
1192
+ where = pk_predicate(m, e, "", "?")
1193
+ if where is None:
1194
+ return 0, "entity without a mapped @Id"
1195
+ ctx.site(jf, call, f"UPDATE {table} SET {', '.join(c + ' = ?' for c in cols if c not in pk)} WHERE {where}", "jpa", table,
1196
+ "merge", conf, "merge: SELECT by id when the entity is detached, then INSERT or UPDATE at flush", sink=sink, line_node=line_node)
1197
+ elif name == "remove":
1198
+ where = pk_predicate(m, e, "", "?")
1199
+ if where is None:
1200
+ return 0, "entity without a mapped @Id"
1201
+ ctx.site(jf, call, f"DELETE FROM {table} WHERE {where}", "jpa", table, "remove", conf,
1202
+ "runs at flush; cascaded associations add their own statements", sink=sink, line_node=line_node)
1203
+ elif name == "refresh":
1204
+ where = pk_predicate(m, e, "e", "?")
1205
+ if where is None:
1206
+ return 0, "entity without a mapped @Id"
1207
+ ctx.site(jf, call, select_by(m, e, where), "jpa", table, "refresh", conf, "", sink=sink, line_node=line_node)
1208
+ return 1, ""
1209
+
1210
+
1211
+ # ----------------------------------------------------------------------------- lazy associations in loops
1212
+ def lazy_in_loops(ctx: Ctx) -> None:
1213
+ """Reads of a LAZY association: `owner.getChildren()` on a variable whose declared type is a mapped entity.
1214
+ Each owner's association is loaded by its own SELECT on first access, so the read inside a loop over owners is
1215
+ the JPA N+1 (`in_loop`); outside a loop it is still one query, and a loop in a caller makes it N.
1216
+ Proven: the receiver's declared type is an entity and the getter belongs to a lazy association of it.
1217
+ Assumed: the entity is managed and the query that loaded it did not fetch the association."""
1218
+ m = ctx.model
1219
+ getters: dict[str, list[tuple[Entity, Attr]]] = {}
1220
+ entity_classes: set[str] = set()
1221
+ for e in m.entities.values():
1222
+ entity_classes.add(e.cls)
1223
+ if e.kind != "entity":
1224
+ continue
1225
+ for a in m.attrs(e).values():
1226
+ if a.fetch == "lazy" and a.kind in ("to_many", "elements", "to_one"):
1227
+ getters.setdefault("get" + a.name[:1].upper() + a.name[1:], []).append((e, a))
1228
+ if not getters:
1229
+ return
1230
+ for jf in ctx.repo.files:
1231
+ test = _is_test(jf.rel)
1232
+ per_method: dict[int, int] = {}
1233
+ seen: set[tuple[int, str, str, str]] = set()
1234
+ for call in jf.calls:
1235
+ name = _txt(call.child_by_field_name("name"))
1236
+ if name not in getters or _named(call.child_by_field_name("arguments")):
1237
+ continue
1238
+ obj = call.child_by_field_name("object")
1239
+ if obj is None:
1240
+ continue
1241
+ if obj.type == "field_access" and _txt(obj.child_by_field_name("object")) == "this":
1242
+ var = _txt(obj.child_by_field_name("field"))
1243
+ elif obj.type == "identifier":
1244
+ var = _txt(obj)
1245
+ else:
1246
+ continue
1247
+ cls = jf._enclosing(call, ("class_declaration",))
1248
+ if cls is not None and _txt(cls.child_by_field_name("name")) in entity_classes:
1249
+ continue # the mapping class itself
1250
+ vtype = _decl_type(ctx, jf, var, call)
1251
+ typed = bool(vtype) and vtype != "var"
1252
+ if not typed:
1253
+ loop = _loop_binding(jf, call, var)
1254
+ vtype = _infer_loop_type(ctx, jf, loop[0], var) if loop is not None else ""
1255
+ if not vtype:
1256
+ if loop is not None:
1257
+ STATS.seen("jpa-lazy", test)
1258
+ STATS.miss("jpa-lazy", "type of the loop variable is not known statically", jf.rel, call.start_point[0] + 1, test)
1259
+ continue
1260
+ e = m.entities.get(_outer_type(vtype))
1261
+ if e is None or e.kind != "entity":
1262
+ continue # not an entity: not database access
1263
+ a = m.attr(e, _decap(name[3:]))
1264
+ if a is None or a.fetch != "lazy" or a.kind not in ("to_many", "elements", "to_one"):
1265
+ continue
1266
+ STATS.seen("jpa-lazy", test)
1267
+ line = call.start_point[0] + 1
1268
+ top = jf._enclosing(call, ("method_declaration", "constructor_declaration"))
1269
+ key = (top.id if top is not None else 0, var, e.cls, a.name)
1270
+ if key in seen:
1271
+ STATS.miss("jpa-lazy", "same association of the same variable read again (loaded once)", jf.rel, line, test)
1272
+ continue
1273
+ target = m.entities.get(a.type)
1274
+ in_loop = jf.in_loop(call)
1275
+ what = a.relation or "collection"
1276
+ notes = [f"lazy {what} {e.name}.{a.name}: loaded by its own SELECT on first access, once per {e.name}"
1277
+ + ("; here inside a loop (N+1)" if in_loop else "; a loop in a caller makes it one query per item"),
1278
+ "assumed: the entity is managed and the loading query did not fetch this association"]
1279
+ conf = "medium" if typed else "low"
1280
+ try:
1281
+ if a.kind == "to_one":
1282
+ parent = call.parent
1283
+ used = parent is not None and parent.type == "method_invocation" and parent.child_by_field_name("object") is not None \
1284
+ and parent.child_by_field_name("object").id == call.id
1285
+ tid = m.pk_attr(target) if target is not None else None
1286
+ if not used or target is None or target.kind != "entity":
1287
+ STATS.miss("jpa-lazy", "lazy to-one read without touching its state (no query)", jf.rel, line, test)
1288
+ continue
1289
+ next_name = _txt(parent.child_by_field_name("name"))
1290
+ if tid is not None and next_name == "get" + tid.name[:1].upper() + tid.name[1:]:
1291
+ STATS.miss("jpa-lazy", "lazy to-one read without touching its state (no query)", jf.rel, line, test)
1292
+ continue
1293
+ where = pk_predicate(m, target, "e", "?")
1294
+ if where is None:
1295
+ STATS.miss("jpa-lazy", "entity without a mapped @Id", jf.rel, line, test)
1296
+ continue
1297
+ sql = select_by(m, target, where)
1298
+ notes.append("an entity already in the persistence context is not loaded again")
1299
+ else:
1300
+ sql = collection_select(m, e, a)
1301
+ if sql is None:
1302
+ STATS.miss("jpa-lazy", "collection mapping not resolved", jf.rel, line, test)
1303
+ continue
1304
+ except Untranslatable as exc:
1305
+ STATS.miss("jpa-lazy", str(exc), jf.rel, line, test)
1306
+ continue
1307
+ if a.batch_size:
1308
+ notes.append(f"@BatchSize({a.batch_size}): Hibernate loads up to {a.batch_size} owners' collections per SELECT, so about N/{a.batch_size} queries")
1309
+ conf = "low"
1310
+ if top is not None:
1311
+ per_method[top.id] = per_method.get(top.id, 0) + 1
1312
+ if per_method[top.id] > MAX_LAZY:
1313
+ STATS.miss("jpa-lazy", "over the per-method limit (orm_max_lazy_per_method)", jf.rel, line, test)
1314
+ continue
1315
+ seen.add(key)
1316
+ ctx.site(jf, call, sql, "jpa", m.table(target) if target is not None and target.kind == "entity" else m.table(e),
1317
+ "lazy load", conf, notes, sink=f"{var}.{name}", line_node=call.child_by_field_name("name"), in_loop=in_loop)
1318
+ STATS.hit("jpa-lazy", 1, test)
1319
+
1320
+
1321
+ LOOP_LAMBDAS = {"forEach", "forEachOrdered", "map", "flatMap", "filter", "peek", "anyMatch", "allMatch", "noneMatch",
1322
+ "mapToInt", "mapToLong", "mapToObj", "collect", "sorted", "removeIf", "takeWhile", "dropWhile"}
1323
+
1324
+
1325
+ def _loop_binding(jf, call: Node, var: str) -> tuple[Node, str, bool] | None:
1326
+ """The loop that binds `var`, when `call` is inside its body: (loop node, declared type or "", typed)."""
1327
+ n = call.parent
1328
+ while n is not None and n.type not in ("method_declaration", "constructor_declaration", "class_declaration"):
1329
+ if n.type == "enhanced_for_statement":
1330
+ nm = n.child_by_field_name("name")
1331
+ if nm is not None and _txt(nm) == var:
1332
+ t = _txt(n.child_by_field_name("type"))
1333
+ return n, ("" if t == "var" else t), t != "var"
1334
+ elif n.type == "lambda_expression":
1335
+ params = n.child_by_field_name("parameters")
1336
+ names: list[tuple[str, str]] = []
1337
+ if params is not None and params.type == "identifier":
1338
+ names = [(_txt(params), "")]
1339
+ elif params is not None and params.type == "inferred_parameters":
1340
+ names = [(_txt(c), "") for c in params.named_children]
1341
+ elif params is not None:
1342
+ names = [(_txt(p.child_by_field_name("name")), _txt(p.child_by_field_name("type"))) for p in _named(params)]
1343
+ hit = next((t for nme, t in names if nme == var), None)
1344
+ if hit is not None:
1345
+ p = n.parent
1346
+ if p is not None and p.type == "argument_list" and p.parent is not None and p.parent.type == "method_invocation" \
1347
+ and _txt(p.parent.child_by_field_name("name")) in LOOP_LAMBDAS:
1348
+ return n, hit, bool(hit)
1349
+ return None
1350
+ n = n.parent
1351
+ return None
1352
+
1353
+
1354
+ def _infer_loop_type(ctx: Ctx, jf, loop: Node, var: str) -> str:
1355
+ """Element type of what the loop iterates: `for (var x : list)` or `list.forEach(x -> ...)` with a declared
1356
+ `List<Entity> list`, also through `.stream()`."""
1357
+ src: Node | None = None
1358
+ if loop.type == "enhanced_for_statement":
1359
+ src = loop.child_by_field_name("value")
1360
+ else:
1361
+ inv = loop.parent.parent if loop.parent is not None else None
1362
+ src = inv.child_by_field_name("object") if inv is not None else None
1363
+ hops = 0
1364
+ while src is not None and src.type == "method_invocation" and hops < 6:
1365
+ nm = _txt(src.child_by_field_name("name"))
1366
+ if nm in ("stream", "parallelStream", "filter", "sorted", "distinct", "limit", "skip", "peek", "iterator", "values"):
1367
+ src = src.child_by_field_name("object")
1368
+ hops += 1
1369
+ continue
1370
+ if nm.startswith("get") and not _named(src.child_by_field_name("arguments")):
1371
+ # owner.getChildren(): the element type of a mapped collection
1372
+ obj = src.child_by_field_name("object")
1373
+ if obj is not None and obj.type == "identifier":
1374
+ owner = ctx.model.entities.get(_outer_type(_decl_type(ctx, jf, _txt(obj), loop)))
1375
+ a = ctx.model.attr(owner, _decap(nm[3:])) if owner is not None else None
1376
+ if a is not None and a.kind == "to_many":
1377
+ return a.type
1378
+ return ""
1379
+ if src is not None and src.type == "identifier":
1380
+ t = _decl_type(ctx, jf, _txt(src), loop)
1381
+ if "<" in t:
1382
+ return _simple_type(t)
1383
+ return ""
1384
+
1385
+
1386
+ # ------------------------------------------------------------------------------------------------ driver
1387
+ def apply_settings(settings: dict | None) -> None:
1388
+ global MAX_EAGER, MAX_LAZY
1389
+ from . import orm_stats
1390
+ settings = settings or {}
1391
+ MAX_EAGER = int(settings.get("orm_max_eager", DEFAULT_MAX_EAGER))
1392
+ MAX_LAZY = int(settings.get("orm_max_lazy_per_method", DEFAULT_MAX_LAZY))
1393
+ orm_stats.TOP_REASONS = int(settings.get("orm_top_reasons", orm_stats.DEFAULT_TOP_REASONS))
1394
+ orm_stats.REASON_EXAMPLES = int(settings.get("orm_reason_examples", orm_stats.DEFAULT_REASON_EXAMPLES))
1395
+
1396
+
1397
+ def extend(root: Path, repo, rules, sites: list[RawSite], files: list[str] | None = None) -> list[RawSite]:
1398
+ """Called at the end of java.extract. Returns the sites, with JPQL translated and the ORM sites added."""
1399
+ STATS.clear()
1400
+ TABLES.clear()
1401
+ ctx = Ctx(root, repo, rules)
1402
+ not_jpql: set[int] = set()
1403
+ try:
1404
+ from . import orm_jdbi
1405
+ not_jpql = orm_jdbi.prepare(ctx, sites, STATS)
1406
+ except Exception:
1407
+ pass
1408
+ ctx.not_jpql = not_jpql
1409
+ steps = [("mapping", lambda: build_model(ctx)), ("repositories", lambda: find_repositories(ctx))]
1410
+ for _name, step in steps:
1411
+ try:
1412
+ step()
1413
+ except Exception:
1414
+ pass
1415
+ if ctx.model.by_name:
1416
+ for step in (lambda: translate_jpql_sites(ctx, sites), lambda: repository_methods(ctx), lambda: call_sites(ctx),
1417
+ lambda: lazy_in_loops(ctx)):
1418
+ try:
1419
+ step()
1420
+ except RecursionError:
1421
+ continue
1422
+ try:
1423
+ TABLES.extend(ctx.model.tables())
1424
+ except Exception:
1425
+ pass
1426
+ else:
1427
+ for s in sites:
1428
+ if s.engine_hint == "jpql" and s.sql is not None and id(s) not in not_jpql:
1429
+ STATS.seen("jpa", s.is_test)
1430
+ STATS.miss("jpa", "no entity mapping in the repository", s.file, s.line, s.is_test)
1431
+ for modname in ("orm_jooq", "orm_jdbi", "orm_mybatis"):
1432
+ try:
1433
+ mod = __import__(f"codecop.discover.{modname}", fromlist=["extend"])
1434
+ except ImportError:
1435
+ continue
1436
+ try:
1437
+ sites = mod.extend(ctx, sites, STATS)
1438
+ except RecursionError:
1439
+ continue
1440
+ return sites + ctx.out
1441
+
1442
+
1443
+ def summary_extras() -> dict:
1444
+ return STATS.summary()
1445
+
1446
+
1447
+ def tables() -> list:
1448
+ out = list(TABLES)
1449
+ TABLES.clear()
1450
+ return out