Repository navigation
Run an aggregate on the right of a data service @Where comparison as a subquery - #17153
borinquenkid wants to merge 10 commits into
Conversation
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
sbglasius
left a comment
There was a problem hiding this comment.
This is an AI assisted review
LGTM.
jamesfredley
left a comment
There was a problem hiding this comment.
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))), |
There was a problem hiding this comment.
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.
…ed property is refused when the query is compiled Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…d property is refused Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
Pushed d862d7f. You are right that What I found, in a throwaway spec with the owner as the subquery's entity and the path
So 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. |
|
Pushed aaba3bc, which merges |
jdaugherty
left a comment
There was a problem hiding this comment.
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
|
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 Embedded guard. The refusal now applies to the calls of the query DSL, which have no receiver of their own. |
sbglasius
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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() && |
There was a problem hiding this comment.
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)) { |
There was a problem hiding this comment.
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.
…gregate-clean-8.0.x
… 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.
|
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 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 The class, not the two samples.
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.
One case I left alone because it behaves the same on the base: |
…of the plain form, not of the .of form
|
Thanks for the approval, @sbglasius. Two things from it are in:
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 ( |
jamesfredley
left a comment
There was a problem hiding this comment.
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() && |
There was a problem hiding this comment.
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.
|
Pushed the next commits, which answer the review of 12-05 at e3e727a: The finding. 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 ( The table. One limit that I did not change. The read also found this: a nested embedded component whose class carries
|
✅ All tests passed ✅🏷️ Commit: 35fc51e Learn more about TestLens at testlens.app/docs. |
jamesfredley
left a comment
There was a problem hiding this comment.
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() && |
There was a problem hiding this comment.
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.
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@Whereclosure of a data service was translated into a bare closure, which the enclosing criteria resolved itsprojectionscall against. The aggregate then landed on the outer query and the subquery lost it, so every such method failed withSQLGrammarExceptionon Hibernate 5.Change
DetachedCriteriaTransformerbuilds the aggregate as an explicitDetachedCriteriasubquery, as the.of { }form already was. No public API is added.Tests
WhereServiceAggregateSpecruns the comparisons withavg,>= avg,maxandminthrough a data service and through the samewherequery, 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 doescodeStyle.Not in this change
GroovyCastException, because 7.0.x lacks the scope recompute of Nested criteria subqueries bind to the outer criteria under @CompileStatic (Groovy 4) #16425 andDELEGATE_FIRSTinprojections. Porting those is a larger change; on 7.0.x the workaround is the.of { }form.getTargetClass()it needed: that is public API and waits for the 8.1.x pull request after fix(hibernate7): support where-query functions and refactor PredicateGenerator #16816.gt('qty', { projections { avg('qty') } }), fails the same way with or without this change: it does not run itsprojectionscall on its own subquery.https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL