spring-projects / spring-projects/spring-data-jpa

Derived count query for `SELECT DISTINCT` mangles select expressions into invalid JPQL

Open
#4,341 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

status: waiting-for-triage
Dominant language
Java
Stars
3.3k
Forks
1.6k
PR merge metrics
No merged PRs in 30d

Description

Deriving a count query from a SELECT DISTINCT query whose selection contains expressions produces invalid JPQL in QueryTransformers.CountSelectionTokenStream:

  1. Flattening the selection tokens drops all whitespace of multi-token expressions.
  2. AS (plus the following token) is stripped at any parenthesis nesting level, breaking cast(x as string).
  3. withoutConstructorExpression() removes all parentheses rather than just the constructor wrapper, breaking function calls inside constructor arguments.

Examples on main (also affects JPQL and EQL; HQL is affected for the constructor case):

select distinct coalesce(u.name, u.lastname) from User u where u.foo = ?1
→ count query: select count(distinct coalescename, lastname) from User where foo = ?1

select distinct case when u.age > 18 then 'adult' else 'minor' end from User u
→ count query: select count(distinct casewhenu.age>18then'adult'else'minor'end) from User u

Both derived count queries are rejected by the project's own query parsers (BadJpqlGrammarException: no viable alternative), so any paged repository query of this shape fails at count-query execution.

Expected: the derived count query preserves the expression's spacing, keeps AS inside function calls, and retains nested parentheses when unwrapping a constructor expression. I will submit a PR with a fix and tests for all three dialects.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in QueryTransformers.CountSelectionTokenStream and use the supplied DISTINCT expression examples as parser inputs across JPQL, EQL, and HQL. Confirm completion when derived count queries retain expression whitespace, preserve AS inside function calls, and unwrap only the constructor wrapper while keeping nested function parentheses; add coverage for all three dialects.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
backend, databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Clearly specified
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.