Skip to content

Run an aggregate on the right of a data service @Where comparison as a subquery (7.2.x) - #17176

Closed
borinquenkid wants to merge 2 commits into
7.2.xfrom
fix/service-where-aggregate-7.2.x
Closed

borinquenkid wants to merge 2 commits into
7.2.xfrom
fix/service-where-aggregate-7.2.x

Conversation

@borinquenkid

Copy link
Copy Markdown
Member

Fixes #16807 on 7.2.x. The 8.0.x fix is #17153.

Problem

qty > avg(qty) in the @Where closure of a data service failed on 7.x: with an SQLGrammarException (select from wsa_reading, the subquery lost its projection), and with the obvious repair, with a GroovyCastException. A data service is compiled statically, and two things went wrong there:

  1. The aggregate was added in a closure, { projections { avg('qty') } }. Under @CompileStatic, the calls of a criteria closure nested in another one resolve to the enclosing criteria, so the projection landed on the outer query. 8.0.x fixed that with DELEGATE_FIRST on the @DelegatesTo of the criteria API (Nested criteria subqueries bind to the outer criteria under @CompileStatic (Groovy 4) #16425), which changes public signatures and the compile-time resolution of user code, so it is not ported to a minor 7.x line.
  2. A MethodCallExpression is implicitly on this when created. The dynamic compiler still calls it on its object expression, but the static compiler, in a closure, calls an implicit-this method on the closure's owner. A generated new DetachedCriteria(Entity).build(...) was therefore compiled as ((DetachedCriteria) this).build(...), which is the GroovyCastException.

Change

DetachedCriteriaTransformer builds the subquery with no criteria closure for the static compiler to misresolve, and marks the generated call as not on this:

  • avg, max, min, sum: new DetachedCriteria(Entity).avg('qty'), the criteria's own projection methods.
  • count (countDistinct, which has no such method): new DetachedCriteria(Entity).build { DetachedCriteria c -> c.projections { countDistinct('qty') } }. build calls the closure with the new criteria, so projections is called on it explicitly.
  • property keeps its closure and its ...All subquery methods.

No public API changes. A where query takes the same path in its subquery (gt(String, DetachedCriteria) instead of gt(String, Closure), which builds that criteria) and gives the same rows.

Tests

WhereServiceAggregateSpec (Hibernate 5) runs > avg, >= avg, == max, == min, < sum and <= count through a data service and through the same where query, and compares the rows. With the transformer of 7.2.x, the four cases of #17153 fail (4 of 4); with this change all six pass. grails-datamapping-core, grails-datamapping-core-test (which holds the where aggregate cases of WhereMethodSpec), the Hibernate 5 module and the MongoDB module pass, and so does codeStyle. The upgrade note is in the Grails 7.2.6 section.

Not in this change

https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

 comparison as a subquery

A data service is compiled statically. There the aggregate subquery of
`qty > avg(qty)` lost its projection: the closure that added it resolved
`projections` to the enclosing criteria, and the generated call on the new
criteria, implicitly on `this`, was compiled as a call on the closure's owner.

The transformer now adds avg, max, min and sum through the criteria's own
methods, adds countDistinct in a closure that calls projections on the
criteria it is given, and marks those calls as not on `this`. No public
API changes.

Fixes #16807

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

sbglasius
sbglasius previously approved these changes Nov 26, 2026

@sbglasius sbglasius left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an AI assisted review

Building the subquery on a new criteria avoids the static-compile delegation issue without porting #16425. The spec covers every aggregate. LGTM.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requested changes. An aggregate built from a method that names the base class is run against the base class, not the subclass that was passed.

private MethodCallExpression newSubquery(String methodName, ArgumentListExpression arguments) {
MethodCallExpression call = new MethodCallExpression(
new ConstructorCallExpression(getParameterizedDetachedCriteriaClassNode(null),
new ArgumentListExpression(new ClassExpression(this.currentClassNode))),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A method takes a criteria of the base class and compares a value with the average. A subclass criteria is passed in. The average should be of the subclass. It is of the base class, so a subclass row that is above its own average is left out. Build the average against the criteria that was passed.

…the criteria it runs on

The previous commit built the subquery of avg, max, min and sum as a new
criteria of the class named where the query is written. A method that takes a
criteria of the base class and is passed a subclass criteria then compared
with the aggregate of the base class (review on #17176).

Every aggregate is now a closure that takes the subquery as its parameter,
as count already was. The criteria it is passed to builds the subquery when
the query runs, of its own class. The aggregate is called on the projection
list by name, because a statically compiled closure, such as the @where of a
data service, does not send a call without a receiver to its delegate.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
@borinquenkid

Copy link
Copy Markdown
Member Author

@jamesfredley You're right, thanks. My first commit built the subquery as a new criteria of the class named where the query is written, so a criteria of the subclass got the base class aggregate. Fixed in 2b3a170.

  • The change: every aggregate is now a closure that takes the subquery as its parameter (DetachedCriteriaTransformer.java#L1278). The criteria that receives the comparison builds the subquery when the query runs, from its own class (DetachedCriteria.groovy#L750), as it did before this PR.
  • Data services: the aggregate is called on the projection list by name (L1410), because a statically compiled closure does not send a call without a receiver to its delegate. That was the Data Services: Fix @Where aggregate subquery translation generating invalid SQL #16807 failure.
  • Test: your case for all five functions, with methods that take a DetachedCriteria<WsaBase> and are passed a WsaSub criteria (WhereServiceAggregateSpec.groovy#L90). The rows are chosen so that the base class and the subclass give a different answer for each function. All five fail without the change, and the six data service features still pass.
  • Suites: grails-datamapping-core, grails-datamapping-core-test, the Hibernate 5 module, the MongoDB module and codeStyle pass.

@github-actions
github-actions Bot dismissed sbglasius’s stale review November 26, 2026 20:08

Dismissed automatically: the pull request changed after this approval, from c42bd2c to 2b3a170.

@testlens-app

testlens-app Bot commented Nov 26, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: 2b3a170
▶️ Tests: 67906 executed
⚪️ Checks: 62/62 completed


Learn more about TestLens at testlens.app/docs.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The items this review found have been addressed. The average is built against the criteria that was passed.

@borinquenkid

Copy link
Copy Markdown
Member Author

Moved to 7.0.x as #17275: the bug is also on 7.0.x, the oldest branch with it. The change is rebuilt there on a new branch. It also fixes two things this branch still has: a where query in a @transactional method with a variable named delegate throws a GroovyCastException, and with the in-memory datastore a data service method with avg throws on an entity with no instances. The review here does not carry over. Closing this one; its review history stays here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants