Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(workspace): skip JPQL entity queries in Java and Kotlin (#4533)
Little Fedyab1ddeb077765
diff --git a/packages/core/src/repowise/core/workspace/extractors/data/sql_strings.py b/packages/core/src/repowise/core/workspace/extractors/data/sql_strings.pyindex 4a16463f7..2c6c74ad4 100644--- a/packages/core/src/repowise/core/workspace/extractors/data/sql_strings.py+++ b/packages/core/src/repowise/core/workspace/extractors/data/sql_strings.py@@ -11,10 +11,17 @@ Precision rules (this is where the false links would come from):3. A table token that is itself interpolated (``FROM {table}`` /``FROM ${table}`` / ``FROM " + name``) is skipped: normalization rejectsnon-identifier tokens, so an interpolated target emits nothing.+4. In Java and Kotlin, JPQL queries (ORM entity-class queries in+ ``@Query(...)`` without ``nativeQuery = true``, in ``@NamedQuery`` /+ ``@NamedQueries``, and the first argument of ``createQuery(``) are skipped+ so that entity names are not extracted as tables. Native queries (e.g.+ ``@Query(..., nativeQuery = true)`` and ``createNativeQuery(``) continue+ to emit their table targets."""from __future__ import annotations+import bisectimport refrom typing import TYPE_CHECKING@@ -119,6 +126,128 @@ def _verb_for_statement(stmt: object) -> str:return kind if kind in ("insert", "update", "delete", "merge") else "select"+_JVM_EXTENSIONS = JAVA | KOTLIN++_JPQL_QUERY_RE = re.compile(r"(?<![A-Za-z0-9_])(?:@|\.)?Query\b")+_JPQL_NAMED_QUERY_RE = re.compile(r"@(NamedNativeQuery|NamedQuery)\b")+_JPQL_NATIVE_FLAG_RE = re.compile(r"\bnativeQuery\s*=\s*true\b")+_CREATE_QUERY_RE = re.compile(r"(?<![A-Za-z0-9_])createQuery\s*\($")+++def _is_enclosing_open(content: str, opener_pos: int, target_pos: int) -> bool:+ """True when *target_pos* lies inside the parentheses opened at *opener_pos*."""+ paren_idx = content.find("(", opener_pos, target_pos)+ if paren_idx == -1:+ return False+ depth = 0+ in_str = False+ quote = ""+ i = paren_idx+ while i < target_pos:+ ch = content[i]+ if in_str:+ if ch == "\\" and i + 1 < target_pos:+ i += 2+ continue+ if content.startswith(quote, i):+ in_str = False+ i += len(quote)+ continue+ else:+ if content.startswith(('"""', "'''"), i):+ in_str = True+ quote = content[i : i + 3]+ i += 3+ continue+ if ch in ('"', "'", "`"):+ in_str = True+ quote = ch+ elif ch == "(":+ depth += 1+ elif ch == ")":+ depth -= 1+ if depth == 0:+ return False+ i += 1+ return depth > 0+++def _find_enclosing_block(content: str, opener_pos: int) -> str | None:+ """The span from *opener_pos* to matching ``)``, or None if unparenthesized."""+ paren_idx = content.find("(", opener_pos)+ if paren_idx == -1:+ return None+ depth = 0+ in_str = False+ quote = ""+ i = paren_idx+ n = len(content)+ while i < n:+ ch = content[i]+ if in_str:+ if ch == "\\" and i + 1 < n:+ i += 2+ continue+ if content.startswith(quote, i):+ in_str = False+ i += len(quote)+ continue+ else:+ if content.startswith(('"""', "'''"), i):+ in_str = True+ quote = content[i : i + 3]+ i += 3+ continue+ if ch in ('"', "'", "`"):+ in_str = True+ quote = ch+ elif ch == "(":+ depth += 1+ elif ch == ")":+ depth -= 1+ if depth == 0:+ return content[opener_pos : i + 1]+ i += 1+ return content[opener_pos:]+++def _is_jpql(+ content: str,+ start: int,+ named_positions: list[int] | None = None,+ query_positions: list[int] | None = None,+) -> bool:+ """True when string literal at *start* is a Java/Kotlin JPQL query."""+ window = content[max(0, start - 200) : start]+ prefix = re.sub(r"(?:\s|//[^\n]*\n|/\*.*?\*/)+$", "", window)+ if _CREATE_QUERY_RE.search(prefix):+ return True++ if named_positions is None:+ named_positions = [+ m.start()+ for m in _JPQL_NAMED_QUERY_RE.finditer(content[:start])+ if m.group(1) == "NamedQuery"+ ]+ idx = bisect.bisect_right(named_positions, start) - 1+ if idx >= 0:+ pos = named_positions[idx]+ if _is_enclosing_open(content, pos, start):+ return True++ if query_positions is None:+ query_positions = [m.start() for m in _JPQL_QUERY_RE.finditer(content[:start])]+ idx = bisect.bisect_right(query_positions, start) - 1+ if idx >= 0:+ pos = query_positions[idx]+ if _is_enclosing_open(content, pos, start):+ block = _find_enclosing_block(content, pos)+ if block is not None and not _JPQL_NATIVE_FLAG_RE.search(block):+ return True++ return False++class SqlStringsDialect:"""Consumers from SQL literals in app code (all supported app languages)."""@@ -134,7 +263,7 @@ class SqlStringsDialect:def extract(self, ctx: ScanContext) -> list[Contract]:out: list[Contract] = []seen: set[str] = set()- for literal, line in self._sql_literals(ctx.content):+ for literal, line in self._sql_literals(ctx.content, ctx.suffix):for table_raw, verb in self._tables_in(literal):if table_raw.lower().strip('"`[]') in _SQL_KEYWORDS:continue@@ -154,10 +283,20 @@ class SqlStringsDialect:out.append(contract)return out- @staticmethod- def _sql_literals(content: str) -> list[tuple[str, int]]:+ @classmethod+ def _sql_literals(cls, content: str, suffix: str = "") -> list[tuple[str, int]]:"""``(literal, line)`` for each SQL-looking string literal in *content*."""literals: list[tuple[str, int]] = []+ is_jvm = suffix in _JVM_EXTENSIONS+ named_positions: list[int] | None = None+ query_positions: list[int] | None = None+ if is_jvm:+ named_positions = [+ m.start()+ for m in _JPQL_NAMED_QUERY_RE.finditer(content)+ if m.group(1) == "NamedQuery"+ ]+ query_positions = [m.start() for m in _JPQL_QUERY_RE.finditer(content)]for m in _STRING_RE.finditer(content):s = next(g for g in m.groups() if g is not None)if (@@ -166,6 +305,8 @@ class SqlStringsDialect:and _SQL_VERB_RE.search(s)and (_UPPER_VERB_RE.search(s) or _SQL_PUNCT_RE.search(s))):+ if is_jvm and _is_jpql(content, m.start(), named_positions, query_positions):+ continueliterals.append((s, line_at(content, m.start())))return literals@@ -205,9 +346,7 @@ class SqlStringsDialect:# reads. sqlglot models a reference to one as exp.Table all the# same, so ``WITH ranked AS (...) ... FROM ranked`` reported a# table named ``ranked``. Only unqualified references shadow.- cte_names = {- cte.alias.lower() for cte in stmt.find_all(exp.CTE) if cte.alias- }+ cte_names = {cte.alias.lower() for cte in stmt.find_all(exp.CTE) if cte.alias}for table in stmt.find_all(exp.Table):name = table.nameif not name:diff --git a/tests/unit/workspace/test_data_contracts.py b/tests/unit/workspace/test_data_contracts.pyindex 41affb70f..66dd56507 100644--- a/tests/unit/workspace/test_data_contracts.py+++ b/tests/unit/workspace/test_data_contracts.py@@ -383,6 +383,65 @@ class TestSqlStringConsumers:contracts = DataExtractor().extract(tmp_path, "api", make_exclude_predicate())assert contracts == []+ def test_jpql_skipped_in_java_and_kotlin(self, tmp_path: Path) -> None:+ # JPQL queries (@Query without nativeQuery = true, @NamedQuery, and+ # createQuery) target entity classes rather than database tables. They+ # must emit no consumers, while native queries (@Query with+ # nativeQuery = true, and createNativeQuery) still emit table targets.+ _write(+ tmp_path,+ "shipping/CityRepository.java",+ '@Query("select c from City c where c.active = true")\n'+ "List<City> findActive();\n"+ '@NamedQuery(name = "findAll", query = "SELECT c FROM City c")\n'+ "class CityRepo {\n"+ " void find(EntityManager em) {\n"+ ' em.createQuery("SELECT c FROM City c", City.class);\n'+ " }\n"+ "}\n",+ )+ _write(+ tmp_path,+ "catalog/ProductRepository.java",+ '@Query(value = "SELECT * FROM products WHERE sku = ?1", nativeQuery = true)\n'+ "Product findBySku(String sku);\n"+ "class ProductRepo {\n"+ " void find(EntityManager em) {\n"+ ' em.createNativeQuery("SELECT * FROM products", Product.class);\n'+ " }\n"+ "}\n",+ )+ _write(+ tmp_path,+ "shipping/CityRepository.kt",+ '@Query("SELECT c FROM City c")\nfun findCities(): List<City>\n',+ )+ contracts = DataExtractor().extract(tmp_path, "service")+ consumers = [c for c in contracts if c.role == "consumer"]+ assert {c.contract_id for c in consumers} == {"data::products"}++ def test_native_query_variations_and_jdbc_preserved(self, tmp_path: Path) -> None:+ _write(+ tmp_path,+ "app/NativeRepo.java",+ '@Query(nativeQuery = true, value = "SELECT id FROM orders WHERE active = true")\n'+ "List<Order> findActive();\n"+ '@Query("SELECT * FROM customers WHERE id = ?1", nativeQuery = true)\n'+ "Customer findCust(Long id);\n"+ "class JdbcWork {\n"+ " void run(JdbcTemplate jdbc) {\n"+ ' jdbc.query("SELECT * FROM audit_log", mapper);\n'+ " }\n"+ "}\n",+ )+ contracts = DataExtractor().extract(tmp_path, "app")+ consumers = [c for c in contracts if c.role == "consumer"]+ assert {c.contract_id for c in consumers} == {+ "data::orders",+ "data::customers",+ "data::audit_log",+ }+def test_system_catalogs_and_alembic_version_skipped(self, tmp_path: Path) -> None:_write(tmp_path,