From d908a35de6c9de9f8f201f028d7085d2729d17a7 Mon Sep 17 00:00:00 2001 From: Walter Duque de Estrada Date: Mon, 23 Nov 2026 10:05:35 -0600 Subject: [PATCH 1/3] fix(datamapping): run an aggregate on the right of a data service @Where 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 --- .../services/WhereServiceAggregateSpec.groovy | 123 ++++++++++++++++++ .../DetachedCriteriaTransformer.java | 11 +- 2 files changed, 132 insertions(+), 2 deletions(-) create mode 100644 grails-data-hibernate5/core/src/test/groovy/org/grails/orm/hibernate/services/WhereServiceAggregateSpec.groovy diff --git a/grails-data-hibernate5/core/src/test/groovy/org/grails/orm/hibernate/services/WhereServiceAggregateSpec.groovy b/grails-data-hibernate5/core/src/test/groovy/org/grails/orm/hibernate/services/WhereServiceAggregateSpec.groovy new file mode 100644 index 00000000000..b2034a56f26 --- /dev/null +++ b/grails-data-hibernate5/core/src/test/groovy/org/grails/orm/hibernate/services/WhereServiceAggregateSpec.groovy @@ -0,0 +1,123 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.orm.hibernate.services + +import spock.lang.AutoCleanup +import spock.lang.Shared +import spock.lang.Specification + +import grails.gorm.DetachedCriteria +import grails.gorm.annotation.Entity +import grails.gorm.services.Service +import grails.gorm.services.Where + +import org.grails.orm.hibernate.HibernateDatastore + +/** + * An aggregate on the right of a comparison in the {@code @Where} of a data service is run as a subquery over the + * entity of the service, as it is in a {@code where} query: the comparisons with the average, the maximum and the + * minimum give the same rows as the query written with {@code where}. + */ +class WhereServiceAggregateSpec extends Specification { + + @Shared @AutoCleanup HibernateDatastore datastore = new HibernateDatastore(WsaReading) + + @Shared WsaReadingService service + + void setupSpec() { + service = datastore.getService(WsaReadingService) + } + + void setup() { + WsaReading.withNewTransaction { + WsaReading.executeUpdate('delete from WsaReading') + [1, 2, 3, 4, 10].each { new WsaReading(qty: it).save(failOnError: true, flush: true) } + } + } + + void "a data service @Where compares with the average of the entity like the same where query"() { + expect: 'the quantities are 1, 2, 3, 4 and 10, so the average is 4' + found(service.aboveAverage()) == [10] + found(listOf(aboveAverageQuery())) == [10] + } + + void "a data service @Where compares with the average of the entity or equal to it like the same where query"() { + expect: + found(service.atLeastAverage()) == [4, 10] + found(listOf(atLeastAverageQuery())) == [4, 10] + } + + void "a data service @Where compares with the maximum of the entity like the same where query"() { + expect: + found(service.theMaximum()) == [10] + found(listOf(maximumQuery())) == [10] + } + + void "a data service @Where compares with the minimum of the entity like the same where query"() { + expect: + found(service.theMinimum()) == [1] + found(listOf(minimumQuery())) == [1] + } + + static DetachedCriteria aboveAverageQuery() { + WsaReading.where { qty > avg(qty) } + } + + static DetachedCriteria atLeastAverageQuery() { + WsaReading.where { qty >= avg(qty) } + } + + static DetachedCriteria maximumQuery() { + WsaReading.where { qty == max(qty) } + } + + static DetachedCriteria minimumQuery() { + WsaReading.where { qty == min(qty) } + } + + private static List listOf(DetachedCriteria query) { + WsaReading.withNewTransaction { query.list() } as List + } + + private static List found(List readings) { + readings*.qty.sort() + } +} + +@Entity +class WsaReading { + + Integer qty +} + +@Service(WsaReading) +interface WsaReadingService { + + @Where({ qty > avg(qty) }) + List aboveAverage() + + @Where({ qty >= avg(qty) }) + List atLeastAverage() + + @Where({ qty == max(qty) }) + List theMaximum() + + @Where({ qty == min(qty) }) + List theMinimum() +} diff --git a/grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/query/transform/DetachedCriteriaTransformer.java b/grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/query/transform/DetachedCriteriaTransformer.java index 89e09a0a571..f03a32efe1b 100644 --- a/grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/query/transform/DetachedCriteriaTransformer.java +++ b/grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/query/transform/DetachedCriteriaTransformer.java @@ -1278,10 +1278,17 @@ private void addCriteriaCall(BlockStatement newCode, String operator, Expression addProjectionToCurrentBody(currentBody, aggregateFunctionName, aggregatePropertyName, variableScope); - rightExpression = closureAndArguments.getClosureExpression(); - if ("property".equals(aggregateFunctionName) && METHOD_TO_SUBQUERY_MAP.containsKey(methodToCall)) { + rightExpression = closureAndArguments.getClosureExpression(); methodToCall = methodToCall + "All"; + } else { + // Built explicitly so the subquery's own criteria receives the projection: a bare + // closure resolves its calls against the enclosing criteria when the query is + // 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))), + "build", new ArgumentListExpression(closureAndArguments.getClosureExpression())); } } else { sourceUnit.getErrorCollector().addError(new LocatedMessage("Cannot use aggregate function " + aggregateFunctionName + " on property \"" + aggregatePropertyName + "\" - no such property on class " + this.currentClassNode.getName() + " exists.", Token.newString(propertyName, aggregateMethodCall.getLineNumber(), aggregateMethodCall.getColumnNumber()), sourceUnit)); From 8301b0ab0a0c6e16d1c76db54e938e4de40acf5e Mon Sep 17 00:00:00 2001 From: Walter Duque de Estrada Date: Wed, 25 Nov 2026 00:57:33 -0600 Subject: [PATCH 2/3] fix(datamapping): an aggregate function inside the block of an embedded property is refused when the query is compiled Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL --- .../DetachedCriteriaTransformer.java | 17 ++++++ ...hereQueryAggregateSubqueryErrorSpec.groovy | 60 +++++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/query/transform/DetachedCriteriaTransformer.java b/grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/query/transform/DetachedCriteriaTransformer.java index f03a32efe1b..c4866291d79 100644 --- a/grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/query/transform/DetachedCriteriaTransformer.java +++ b/grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/query/transform/DetachedCriteriaTransformer.java @@ -167,6 +167,8 @@ public class DetachedCriteriaTransformer extends ClassCodeVisitorSupport { protected Map staticDetachedCriteriaVariables = new HashMap<>(); protected Set aliasExpressions = new HashSet<>(); protected ClassNode currentClassNode; + /** the embedded properties a block is inside of, outermost first: an aggregate cannot be built there */ + private final java.util.ArrayDeque embeddedPath = new java.util.ArrayDeque<>(); public DetachedCriteriaTransformer(SourceUnit sourceUnit) { this.sourceUnit = sourceUnit; @@ -813,6 +815,7 @@ private void handleAssociationMethodCallExpression(BlockStatement newCode, Metho List associationPropertyNames = null; ClassNode type = getPropertyType(methodName); + boolean embeddedBlock = false; if (!AstUtils.isDomainClass(type)) { // A collection association carries its element type in its generics; an // embedded component does not, so keep its own type rather than @@ -821,6 +824,8 @@ private void handleAssociationMethodCallExpression(BlockStatement newCode, Metho if (associationTypeFromGenerics != null) { type = associationTypeFromGenerics; associationPropertyNames = getPropertyNamesForAssociation(associationTypeFromGenerics); + } else { + embeddedBlock = true; } } if (associationPropertyNames == null) { @@ -828,14 +833,21 @@ private void handleAssociationMethodCallExpression(BlockStatement newCode, Metho } ClassNode existing = currentClassNode; + boolean enteredEmbedded = embeddedBlock && type != null; try { if (type != null) { + if (enteredEmbedded) { + embeddedPath.addLast(methodName); + } currentClassNode = type; addBlockStatementToNewQuery((BlockStatement) associationCode, currentBody, associationPropertyNames.isEmpty(), associationPropertyNames, variableScope); } } finally { currentClassNode = existing; + if (enteredEmbedded) { + embeddedPath.removeLast(); + } } } } @@ -1253,6 +1265,11 @@ private void addCriteriaCall(BlockStatement newCode, String operator, Expression } } } + } else if (aggregateFunctionName != null && !embeddedPath.isEmpty()) { + // the subquery of an aggregate is built over an entity, and the class of the block of an embedded value is not + // one: the aggregate would be built over the embedded class and fail when the query runs + sourceUnit.getErrorCollector().addError(new LocatedMessage("Cannot use aggregate function " + aggregateFunctionName + " inside the block of the embedded property \"" + String.join(".", embeddedPath) + "\": an aggregate of the properties of an embedded value is not supported.", Token.newString(propertyName, aggregateMethodCall.getLineNumber(), aggregateMethodCall.getColumnNumber()), sourceUnit)); + return; } else if (aggregateFunctionName != null) { if ((methodTarget instanceof VariableExpression) && ((VariableExpression) methodTarget).isThisExpression()) { diff --git a/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/query/transform/WhereQueryAggregateSubqueryErrorSpec.groovy b/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/query/transform/WhereQueryAggregateSubqueryErrorSpec.groovy index e80e12e7580..07e634ed9f7 100644 --- a/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/query/transform/WhereQueryAggregateSubqueryErrorSpec.groovy +++ b/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/query/transform/WhereQueryAggregateSubqueryErrorSpec.groovy @@ -128,4 +128,64 @@ class AggUnknownPropertyBook { e.message.contains('Cannot use aggregate function avg on property "nonExistentProperty"') e.message.contains('no such property on class') } + + void "an aggregate function inside the block of an embedded property is refused when the query is compiled"() { + when: + new GroovyClassLoader().parseClass(''' +import grails.gorm.annotation.Entity +import org.grails.datastore.gorm.query.transform.ApplyDetachedCriteriaTransform + +class AggEmbeddedStats { + Integer qty +} + +@ApplyDetachedCriteriaTransform +@Entity +class AggEmbeddedReading { + AggEmbeddedStats stats + + static embedded = ['stats'] + + static findInvalid() { + AggEmbeddedReading.where { + stats { qty > avg(qty) } + } + } +} +''') + + then: 'the message names the function and the embedded property' + MultipleCompilationErrorsException e = thrown() + e.message.contains('Cannot use aggregate function avg inside the block of the embedded property "stats"') + } + + void "an aggregate function outside the block of an embedded property is still accepted next to one"() { + when: + Class compiled = new GroovyClassLoader().parseClass(''' +import grails.gorm.annotation.Entity +import org.grails.datastore.gorm.query.transform.ApplyDetachedCriteriaTransform + +class AggEmbeddedOkStats { + Integer qty +} + +@ApplyDetachedCriteriaTransform +@Entity +class AggEmbeddedOkReading { + Integer total + AggEmbeddedOkStats stats + + static embedded = ['stats'] + + static ok() { + AggEmbeddedOkReading.where { + total > avg(total) + } + } +} +''') + + then: 'it compiles, and an embedded block that holds no aggregate beside it does not change that' + compiled != null + } } From d862d7ffcf409b0da60c8de0abd0b70b24e51946 Mon Sep 17 00:00:00 2001 From: Walter Duque de Estrada Date: Wed, 25 Nov 2026 00:58:06 -0600 Subject: [PATCH 3/3] docs(upgrading): an aggregate function inside the block of an embedded property is refused Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL --- grails-doc/src/en/guide/upgrading/upgrading80x.adoc | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc index 3359f409eab..37ab6bca1a2 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc @@ -5032,3 +5032,7 @@ A value marked with `raw()` is still written as given by the tags that wrote it `` now encodes its `value` once. It encoded it twice, so a value with `&`, `<`, `>`, `"` or `'` was submitted with character references in it, such as `+R&D+` for `R&D`. A value encoded beforehand is no longer encoded twice in the `value` of ``, `` and the other field tags when a `RequestDataValueProcessor` returns it unchanged, nor in an option of ``, with or without a processor. `` and `` write a `class` that was encoded beforehand once next to the classes they add, such as `step` and `sortable`; they encoded it twice. + +==== An aggregate function inside the block of an embedded property is refused + +An aggregate on the right of a comparison, such as `stats { qty > avg(qty) }` in a `where` query or in the `@Where` of a data service, where `stats` is an embedded property, is refused when the query is compiled, with a message that names the function and the embedded property. The subquery of an aggregate is built over an entity, and the class of an embedded value is not one, so the query failed when it ran, with an error that did not say why. Compare with a value that is computed before the query, or write the aggregate on a property of the entity itself. No working query changes.