Skip to content

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

Closed

Description

@hunseonglee

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.

Activity

  1. added
    type: bug
    and removed
    status: waiting-for-triage
    on Sep 21, 2026
  2. christophstrobl commented on Sep 22, 2026

    @christophstrobl
    Member

    @harrisleesh thanks for reporting!

  3. added this to the 4.0.8 (2025.1.8) milestone on Oct 15, 2026
  4. added 2 commits that reference this issue on Oct 15, 2026
    ff0cd02
    e1461a5
  5. added a commit that references this issue on Oct 15, 2026
    493c22a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

type: bug

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions