Skip to content

Run an aggregate on the right of a data service @Where comparison as a subquery - #17153

Open
borinquenkid wants to merge 10 commits into
8.0.xfrom
fix/service-where-aggregate-8.0.x
Open

borinquenkid wants to merge 10 commits into
8.0.xfrom
fix/service-where-aggregate-8.0.x

Conversation

@borinquenkid

Copy link
Copy Markdown
Member

Fixes #16807.

Replaces #16835, whose base was the branch of a closed pull request and so carried 68 commits that are not part of this change. This is the one commit of it that belongs on 8.0.x, on a clean branch.

Problem

amount > avg(amount) in the @Where closure of a data service was translated into a bare closure, which the enclosing criteria resolved its projections call against. The aggregate then landed on the outer query and the subquery lost it, so every such method failed with SQLGrammarException on Hibernate 5.

Change

DetachedCriteriaTransformer builds the aggregate as an explicit DetachedCriteria subquery, as the .of { } form already was. No public API is added.

Tests

WhereServiceAggregateSpec runs the comparisons with avg, >= avg, max and min through a data service and through the same where query, and compares the rows. All four fail without the change and pass with it. grails-datamapping-core (1831 tests) and the Hibernate 5 module (1221) pass, and so does codeStyle.

Not in this change

https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

 comparison as a subquery

amount > avg(amount) in a @where closure of a data service was translated into a bare closure that the
enclosing criteria resolved its projections calls against, so the aggregate landed on the outer query and the
subquery lost it. The aggregate is now built as an explicit DetachedCriteria subquery, as the .of { } form
already was. WhereServiceAggregateSpec runs the comparisons with avg, max and min on Hibernate 5 and checks them
against the same where queries.

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 24, 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

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 average inside an embedded block throws instead of comparing the values.

// declared in a service (@Where), and the aggregate then lands on the outer query.
rightExpression = 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.

stats { qty > avg(qty) } should return the reading whose quantity is above the average. It throws, because the average is built against the embedded type as if it were its own class. Build the average against the reading.

@borinquenkid
borinquenkid requested review from jamesfredley, lhotari and sdelamo and removed request for lhotari and sdelamo November 25, 2026 04:39
@borinquenkid

Copy link
Copy Markdown
Member Author

Pushed d862d7f. You are right that stats { qty > avg(qty) } threw: the subquery was built over the class of the block, and the class of an embedded value is not an entity. I tried to build it over the owner of the value and found that it cannot be done here, so the shape is refused when the query is compiled instead of failing when it runs.

What I found, in a throwaway spec with the owner as the subquery's entity and the path stats.qty as the projection:

  • On Hibernate 5 the transformer then built the query, and it failed one step later: a subquery used as the value of a comparison inside the block of an embedded value is bound as a plain parameter, ClassCastException: DetachedCriteria cannot be cast to Integer. That is in how the Hibernate 5 query builder translates the block, not in the transformer, and Hibernate 5 is the frozen store.
  • On Hibernate 7 the data service @Where with an aggregate fails even for a plain property of the entity (Cannot coerce value 'grails.gorm.DetachedCriteria'), so the embedded case cannot be tested there until that is fixed; the spec of this pull request runs on Hibernate 5 only.

So DetachedCriteriaTransformer, line 1268 now adds a compile error, naming the function and the embedded property, for an aggregate inside the block of an embedded property (the tracking of the block, line 840); an aggregate outside such a block is as it was. The test: WhereQueryAggregateSubqueryErrorSpec line 132, the refusal with the message, and line 162, an aggregate beside an embedded property that still compiles; the refusal row fails without the change. The upgrade note is upgrading80x.adoc line 5036. grails-datamapping-core, grails-data-hibernate5-core, grails-data-mongodb-core and grails-data-hibernate7-core (they compile where closures) pass and codeStyle is clean.

If you want it to work and not be refused, the two stores need their own changes first; I can open an issue for each with the failing query. Nothing in the guide describes an aggregate inside an embedded block; the upgrade note is the only text.

@github-actions
github-actions Bot dismissed sbglasius’s stale review November 25, 2026 15:22

Dismissed automatically: the pull request changed after this approval, from d908a35 to d862d7f.

@borinquenkid

Copy link
Copy Markdown
Member Author

Pushed aaba3bc, which merges 8.0.x into the branch: the pull request conflicted with it in upgrading80x.adoc only, where this note and the cache-manager note landed at the same place. Both are kept, this one first. No other change.

@jdaugherty jdaugherty 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.

Thanks for adding the embedded-block diagnostic and regression coverage. The previously reported embedded aggregate failure is now caught during compilation. Two remaining regressions need attention.

P2: Preserve the criteria's runtime target. DetachedCriteriaTransformer.java:1305–1308 constructs the aggregate criteria with the compile-time class. For a helper taking DetachedCriteria<Reading> and returning criteria.where { qty > avg(qty) }, passing new DetachedCriteria<Reading>(SpecialReading) aggregates Reading instead of SpecialReading. With base-only quantity 100 and subclass quantities 1 and 9, the subclass average should select 9; the base-class average selects neither. The previous closure path uses the receiver's runtime target. Please preserve that behavior and add a subclass-criteria regression; #17275 already covers this shape.

P2: Restrict the embedded guard to DSL aggregates. Lines 1268–1275 reject aggregate-named calls before checking their receiver. This ordinary value comparison now fails compilation:

def limits = [1, 2]
Reading.where { stats { qty > limits.max() } }

Here stats is embedded, and limits.max() computes a value from a captured list. It is not a query aggregate. Please check the receiver before applying the prohibition, and cover both this accepted helper call and the rejected avg(qty) DSL form.

These findings are source-traced against this head. I have not run the 8.0.x module suites or a database reproducer for them.

… from the criteria it runs on, and refuse only the aggregates of the query DSL in an embedded block

The subquery of an aggregate on the right of a comparison was built over the class named where the query is written,
so a helper that takes a DetachedCriteria of a base class and is called with the criteria of a subclass aggregated the
base class. The closure now takes the subquery as its parameter and calls the projection on it, as the earlier closure
did through its receiver, and the name of that parameter never repeats a declared one. The guard against an aggregate in
the block of an embedded property looked only at the name of the call, so a value such as limits.max() failed to compile;
it now applies to the calls of the query DSL, which have no receiver of their own.

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

Copy link
Copy Markdown
Member Author

Both points are fixed in 7c2129f.

Runtime target. The subquery of an aggregate on the right of a comparison is no longer built over the class named where the query is written. The generated closure takes the subquery as its parameter and calls the aggregate on that criteria's projection list, so the subquery is built when the query runs, over the target of the criteria it is passed to, as the closure path did through its receiver. Your shape, a helper that takes DetachedCriteria<Reading> and returns criteria.where { qty > avg(qty) }, called with new DetachedCriteria<Reading>(SpecialReading), now aggregates SpecialReading. This is the mechanism of #17275, and its rows are in WhereServiceAggregateSpec: subclass quantities 1, 2 and 4 against base quantities -50, 0 and 10, for avg, max, min, sum and count, each against the three subclass rows and not the six rows of the base. The name of the generated parameter never repeats a variable of an enclosing scope or a parameter of the data service method, and there is a row for a parameter of the same name. With the earlier transformer put back, the five subclass rows fail.

Embedded guard. The refusal now applies to the calls of the query DSL, which have no receiver of their own. Reading.where { stats { qty > limits.max() } } with a captured list compiles, and stats { qty > avg(qty) } is still refused, both in WhereQueryAggregateSubqueryErrorSpec. With the guard as it was, the limits.max() row fails. grails-datamapping-core (1834 tests), grails-datamapping-core-test and the Hibernate 5 module pass, and codeStyle passes.

sbglasius
sbglasius previously approved these changes Dec 4, 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.

Re-reviewed after the latest pushes. The subquery is now built from the criteria it runs on, through the closure parameter, so a DetachedCriteria<Reading> built for SpecialReading aggregates the subclass, and the embedded-block refusal only fires for DSL calls, so limits.max() compiles again. Both of jdaugherty's points look addressed and are covered by tests.

Before merge, please remove the no ci label so the full suite runs. This changes the code generated for every where { x > avg(x) } in every datastore, and nothing has run in CI on this branch yet.

One wording point on the upgrade note: it says an aggregate inside an embedded block is refused when the query is compiled, but the .of { } form is handled before that check (DetachedCriteriaTransformer line 1281), so stats { qty > avg(qty).of { } } still compiles. Either narrow the note to the plain form or extend the check to .of.

Approving on that basis.

@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. A helper call inside an embedded block no longer compiles, and a local name in the query body can collide with the generated parameter.

}
}
}
} else if (aggregateFunctionName != null && !embeddedPath.isEmpty() &&

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.

Reading.where { stats { qty > this.max() } } no longer compiles when stats is embedded and max() is a zero-argument helper that returns a number. The guard matches the method name and does not look at the argument count, so it rejects a value that used to be the comparison. Keep the rejection for an aggregate call, and let an explicit helper through.

*/
private String subqueryParameterName(VariableScope variableScope) {
String name = SUBQUERY_PARAMETER_NAME;
while (reservedParameterNames.contains(name) || isDeclaredInScope(variableScope, name)) {

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 data-service method with @where({ def $subquery = 4; qty > avg(qty); qty > $subquery }) fails to compile with a duplicate parameter. The name check misses a local declared in the query body, so the generated closure parameter reuses $subquery.

… an embedded block, and keep the generated subquery parameter off every name the query declares

An embedded block refused every call of avg, max, min, sum, count or property on this, so a helper that takes no argument, or several,
no longer compiled although the base branch compiles it. Only the call that takes the one property, which is the aggregate of the
query DSL, is refused, as it is outside an embedded block.

The generated closure parameter was kept off the names of the scopes the compiler had resolved, which do not hold a local variable
declared in the body of a data service @where. The transformation now reads the names of the whole query body first, so the parameter
takes none of them. The table covers the names a body declares or reads as locals, closure parameters, loop, catch and pattern variables,
and method parameters; the local variable is the form that failed before.
@borinquenkid

Copy link
Copy Markdown
Member Author

Pushed the next commit, which answers both of the 12-04 findings. Both come from code this pull request adds: the base branch compiles the zero-argument helper and has no generated parameter.

The helper call in an embedded block. The refusal matched the name and not the number of arguments, so stats { qty > this.max() } no longer compiled. It now refuses only the call that takes the one property, which is the aggregate of the query DSL, and the same call is an aggregate outside an embedded block. A call of the same name with no argument or with several, or on another receiver, is a value and compiles as before. The upgrade note says so.

A local name that collides with the generated parameter. The name was kept off the scopes the compiler had resolved, and those do not hold a variable declared in the body of the query. The transformation now reads every name the query declares or reads, and the method's parameters, before it picks the name, so @Where({ def $subquery = 4; qty > avg(qty); qty > $subquery }) compiles and runs: the average is 4 and the local is the other bound.

The class, not the two samples. WhereAggregateCallFormsSpec generates 564 rows:

  • the call forms: six function names, three receivers, four argument forms and two embedded depths (144 rows);
  • the names a query declares or reads, in a where query and in the @Where of a data service: a local variable, the parameter of a closure, the variable of a loop, a catch clause or an instanceof pattern, a parameter of the method and a local of the enclosing method, before and after the aggregate, for five functions.

With the change reverted 53 rows fail, the call forms and the local variable of the data service. The loop, catch and pattern rows pass on the base as well, so they are controls. Try-with-resources is not valid in a query block on any branch, so it has no row. The H5 spec has two new runtime rows for the local variable.

grails-datamapping-core, grails-datamapping-core-test and grails-data-hibernate5-core pass, and codeStyle is clean. An independent reader of the diff, who had not seen my reasoning, found no regression against the base.

One case I left alone because it behaves the same on the base: stats { qty > max(qty).of { ... } } takes the .of form, which is built over the class of the block before the refusal is reached. It is optional here; I can open an issue for it.

@github-actions
github-actions Bot dismissed sbglasius’s stale review December 4, 2026 22:01

Dismissed automatically: the pull request changed after this approval, from 7c2129f to 11de137.

@borinquenkid borinquenkid added run ci and removed no ci labels Dec 5, 2026
@borinquenkid

Copy link
Copy Markdown
Member Author

Thanks for the approval, @sbglasius. Two things from it are in:

  • The upgrade note. It now says that the refusal is of the plain form, a call that takes the one property (avg(qty)), and that avg(qty).of { ... } is not covered: that form is built before the check is reached and fails when the query runs, as it did before. I narrowed the note and left the check alone, as the .of form behaves the same on the base branch.
  • CI. I removed the no ci label and added run ci, so the full suite runs on this push.

The push dismissed your approval, because it changes the upgrade note and a pull request is dismissed on any new commit. The code is that of the head you reviewed (11de1371fc): this commit changes only upgrading80x.adoc.

@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. The helper call and the local-name collision are addressed. An aggregate inside an entity association that sits in an embedded block is still rejected.

}
}
}
} else if (aggregateFunctionName != null && !embeddedPath.isEmpty() &&

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.

Reading.where { stats { category { qty > avg(qty) } } } no longer compiles when stats is embedded and category is a mapped entity. The guard still treats the aggregate as inside the embedded block after the association has been entered. Allow the aggregate once the current path is the entity.

…lock of an embedded value is built over the entity

The refusal of an aggregate inside the block of an embedded value kept the embedded property on its path after the block of an entity was entered
inside it, so where { stats { category { qty > avg(qty) } } } with stats embedded and category an entity no longer compiled, though the aggregate is built
over the entity there as it is anywhere else. The embedded properties are now set aside while the block of an entity is walked and put back after it,
so the innermost block decides, and the message names the innermost embedded property. WhereAggregateCallFormsSpec gains a table over five shapes of
nested blocks, four functions, the receiver and the arguments, 80 rows; 8 of them fail with the previous transformer.
…collection of a class that is no entity inside an embedded value

The embedded properties were set aside for every block that was not an embedded value, which included the block of a collection whose elements are not
entities, so where { stats { tags { qty > avg(qty) } } } with a List of a plain class compiled and built the aggregate over that class, as the refusal exists
to prevent. They are now set aside only when the block is of a domain class, the class of an association or the element of a collection of entities. The table
of WhereAggregateCallFormsSpec gains the collection of a class that is no entity and the collection of entities in an embedded value, 112 rows over seven
shapes; 4 of them fail with the previous commit.
@borinquenkid

Copy link
Copy Markdown
Member Author

Pushed the next commits, which answer the review of 12-05 at e3e727a: d6f94b85e3 for the finding and 35fc51e893 for a regression that an independent read of the first one found.

The finding. Reading.where { stats { category { qty > avg(qty) } } } with stats embedded and category a mapped entity did not compile: the refusal of an aggregate kept stats on its path after the walk entered the block of an entity. The embedded properties are now set aside while the block of an entity is walked and put back after it, so the innermost block decides: the block of an entity takes the aggregate, built over that entity as anywhere else, and the block of an embedded value inside it refuses it, naming the innermost embedded property.

What the independent read found, and the fix. I first set the path aside for every block that was not an embedded value. A collection of a class that is no entity (List<Tag> with a plain class) is not an embedded value either, so stats { tags { qty > avg(qty) } }, refused on 8.0.x, compiled. I reproduced it as 4 failing rows and narrowed the condition to a block of a domain class: the class of an association, or the element of a collection of entities.

The table. WhereAggregateCallFormsSpec has the 112 rows of seven shapes of nested blocks (an embedded value; an entity in one; an embedded value in an entity in one; an entity; an embedded value in an entity; a collection of a class that is no entity in an embedded value; a collection of entities in one), four functions, the receiver and the arguments, 112 rows in all. The expectation is computed in the spec from one rule (refused only when the innermost block is an embedded value and the call has the form of the aggregate), not by the transformer. With the transformer of 8.0.x 8 rows fail, and with the first of the two commits 4 do.

One limit that I did not change. The read also found this: a nested embedded component whose class carries @Entity, or sits in a domain path, is taken for an entity by AstUtils.isDomainClass, which is also what the first property-type check of this method does on 8.0.x for an embedded value of that kind. So stats { detail { qty > avg(qty) } } where stats is embedded and detail is an embedded component of such a class was refused on 8.0.x by the path of stats, and now compiles; the aggregate is then built over the component and fails when the query runs. Telling the two apart needs the static embedded list of the enclosing class read from the AST, which is new machinery in a method that has had a review round for each case so far, so I left it. Do you want it in this pull request, or as a follow-up? The Mongo mapping makes this layout common, so I would lean towards doing it here if you say so.

grails-datamapping-core (2512 tests), grails-datamapping-core-test (697), grails-data-hibernate5-core (3855), grails-data-mongodb-core (1042) and grails-data-hibernate7-core (5408) pass and codeStyle is clean.

@testlens-app

testlens-app Bot commented Dec 5, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: 35fc51e
▶️ Tests: 116298 executed
⚪️ Checks: 97/97 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.

Requested changes. An aggregate inside an explicit association block is no longer rejected. The same aggregate written as a dotted path still is.

}
}
}
} else if (aggregateFunctionName != null && !embeddedPath.isEmpty() &&

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.

Root.where { stats { category.qty > avg('qty') } } no longer compiles when stats is embedded and category is an entity. The dotted path leaves the embedded marker set, so the guard rejects an aggregate that belongs to the entity. The block form category { qty > avg(qty) } is accepted. Treat the dotted path the same way.

This branch has not been deployed

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

Labels

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

Data Services: Fix @Where aggregate subquery translation generating invalid SQL

5 participants