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/8] 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/8] 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/8] 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. From 7c2129f7225bc450e205340dd970f68625dd83dd Mon Sep 17 00:00:00 2001 From: Walter Duque de Estrada Date: Thu, 3 Dec 2026 18:16:36 -0600 Subject: [PATCH 4/8] fix(datamapping): build the aggregate subquery of a data service @Where 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 --- .../services/WhereServiceAggregateSpec.groovy | 123 +++++++++++++++++- .../DetachedCriteriaTransformer.java | 100 +++++++++++--- .../AbstractWhereImplementer.groovy | 2 +- ...hereQueryAggregateSubqueryErrorSpec.groovy | 30 +++++ 4 files changed, 237 insertions(+), 18 deletions(-) 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 index b2034a56f26..3a68f20e57d 100644 --- 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 @@ -18,6 +18,8 @@ */ package org.grails.orm.hibernate.services +import groovy.transform.CompileStatic + import spock.lang.AutoCleanup import spock.lang.Shared import spock.lang.Specification @@ -26,6 +28,7 @@ import grails.gorm.DetachedCriteria import grails.gorm.annotation.Entity import grails.gorm.services.Service import grails.gorm.services.Where +import grails.gorm.transactions.Transactional import org.grails.orm.hibernate.HibernateDatastore @@ -36,7 +39,7 @@ import org.grails.orm.hibernate.HibernateDatastore */ class WhereServiceAggregateSpec extends Specification { - @Shared @AutoCleanup HibernateDatastore datastore = new HibernateDatastore(WsaReading) + @Shared @AutoCleanup HibernateDatastore datastore = new HibernateDatastore(WsaReading, WsaBase, WsaSub) @Shared WsaReadingService service @@ -69,12 +72,90 @@ class WhereServiceAggregateSpec extends Specification { found(listOf(maximumQuery())) == [10] } + void "a data service @Where compares with the sum of the entity like the same where query"() { + expect: 'the sum is 20, above every quantity' + found(service.belowTheSum()) == [1, 2, 3, 4, 10] + found(listOf(belowTheSumQuery())) == [1, 2, 3, 4, 10] + } + + void "a data service @Where compares with the count of the entity like the same where query"() { + expect: 'five distinct quantities' + found(service.atMostTheCount()) == [1, 2, 3, 4] + found(listOf(countQuery())) == [1, 2, 3, 4] + } + 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] } + void "an aggregate in a where query of a method that names the base class is of the criteria passed to it: #function"() { + given: 'subclass quantities 1, 2 and 4, and base class quantities -50, 0 and 10' + WsaBase.withNewTransaction { + WsaBase.executeUpdate('delete from WsaBase') + [-50, 0, 10].each { new WsaBase(qty: it).save(failOnError: true, flush: true) } + [1, 2, 4].each { new WsaSub(qty: it).save(failOnError: true, flush: true) } + } + + expect: 'the aggregate is of the three subclass rows, not of the six rows of the base class' + WsaBase.withNewTransaction { query(new DetachedCriteria(WsaSub)).list() }*.qty.sort() == expected + + where: + function | query || expected + 'avg' | WhereServiceAggregateSpec.&aboveAverageOf || [4] + 'max' | WhereServiceAggregateSpec.&maximumOf || [4] + 'min' | WhereServiceAggregateSpec.&minimumOf || [1] + 'sum' | WhereServiceAggregateSpec.&belowTheSumOf || [1, 2, 4] + 'count' | WhereServiceAggregateSpec.&atMostCountOf || [1, 2] + } + + void "an aggregate in a where query of a transactional method runs when the method has a #variable named delegate"() { + expect: 'the variable of the method does not take the place of anything the query is compiled to' + found(query(new WsaReadingFinder())) == [10] + + where: + variable | query + 'parameter' | { WsaReadingFinder finder -> finder.aboveAverageWithParameter('x') } + 'local variable' | { WsaReadingFinder finder -> finder.aboveAverageWithLocalVariable() } + } + + void "an aggregate in a data service @Where runs when a parameter of the service method is named like the generated one"() { + expect: 'the quantities are 1, 2, 3, 4 and 10, so the average is 4 and the parameter is the other bound' + found(service.aboveAverageAndParameter(9)) == [10] + found(service.aboveAverageAndParameter(10)) == [] + } + + void "an aggregate in a statically compiled where query is run as a subquery"() { + expect: + found(listOf(staticallyCompiledQuery())) == [10] + } + + @CompileStatic + static DetachedCriteria staticallyCompiledQuery() { + WsaReading.where { qty > avg(qty) } + } + + static DetachedCriteria aboveAverageOf(DetachedCriteria criteria) { + criteria.where { qty > avg(qty) } + } + + static DetachedCriteria maximumOf(DetachedCriteria criteria) { + criteria.where { qty == max(qty) } + } + + static DetachedCriteria minimumOf(DetachedCriteria criteria) { + criteria.where { qty == min(qty) } + } + + static DetachedCriteria belowTheSumOf(DetachedCriteria criteria) { + criteria.where { qty < sum(qty) } + } + + static DetachedCriteria atMostCountOf(DetachedCriteria criteria) { + criteria.where { qty <= count(qty) } + } + static DetachedCriteria aboveAverageQuery() { WsaReading.where { qty > avg(qty) } } @@ -91,6 +172,14 @@ class WhereServiceAggregateSpec extends Specification { WsaReading.where { qty == min(qty) } } + static DetachedCriteria belowTheSumQuery() { + WsaReading.where { qty < sum(qty) } + } + + static DetachedCriteria countQuery() { + WsaReading.where { qty <= count(qty) } + } + private static List listOf(DetachedCriteria query) { WsaReading.withNewTransaction { query.list() } as List } @@ -106,6 +195,29 @@ class WsaReading { Integer qty } +@Entity +class WsaBase { + + Integer qty +} + +@Entity +class WsaSub extends WsaBase { +} + +@Transactional +class WsaReadingFinder { + + List aboveAverageWithParameter(Object delegate) { + WsaReading.where { qty > avg(qty) }.list() + } + + List aboveAverageWithLocalVariable() { + def delegate = 'x' + WsaReading.where { qty > avg(qty) }.list() + } +} + @Service(WsaReading) interface WsaReadingService { @@ -120,4 +232,13 @@ interface WsaReadingService { @Where({ qty == min(qty) }) List theMinimum() + + @Where({ qty < sum(qty) }) + List belowTheSum() + + @Where({ qty <= count(qty) }) + List atMostTheCount() + + @Where({ qty > avg(qty) && qty > $subquery }) + List aboveAverageAndParameter(Integer $subquery) } 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 c4866291d79..07d38973fe7 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 @@ -22,6 +22,7 @@ import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -169,6 +170,7 @@ public class DetachedCriteriaTransformer extends ClassCodeVisitorSupport { 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<>(); + private Set reservedParameterNames = Collections.emptySet(); public DetachedCriteriaTransformer(SourceUnit sourceUnit) { this.sourceUnit = sourceUnit; @@ -626,6 +628,21 @@ public void visitStaticMethodCallExpression(StaticMethodCallExpression call) { super.visitStaticMethodCallExpression(call); } + /** + * Transforms the closure of a data service method, whose parameters become variables of the closure after the transformation. + * + * @param reservedNames The names of the parameters of the method, which the transformation does not use for a variable of its own + */ + public void transformClosureExpression(ClassNode classNode, ClosureExpression closureExpression, Collection reservedNames) { + Set previous = this.reservedParameterNames; + try { + this.reservedParameterNames = new HashSet<>(reservedNames); + transformClosureExpression(classNode, closureExpression); + } finally { + this.reservedParameterNames = previous; + } + } + public void transformClosureExpression(ClassNode classNode, ClosureExpression closureExpression) { if (closureExpression.getNodeMetaData(TRANSFORMED_MARKER) != null) return; ClassNode previousClassNode = this.currentClassNode; @@ -1265,8 +1282,10 @@ 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 + } else if (aggregateFunctionName != null && !embeddedPath.isEmpty() && + (methodTarget instanceof VariableExpression) && ((VariableExpression) methodTarget).isThisExpression()) { + // a call of the query DSL, with no receiver of its own, as a call such as list.max() is a value, not an aggregate. + // 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; @@ -1290,22 +1309,22 @@ private void addCriteriaCall(BlockStatement newCode, String operator, Expression boolean validProperty = aggregatePropertyName != null && propertyNames.contains(aggregatePropertyName); if (validProperty) { - ClosureAndArguments closureAndArguments = new ClosureAndArguments(variableScope); - BlockStatement currentBody = closureAndArguments.getCurrentBody(); - - addProjectionToCurrentBody(currentBody, aggregateFunctionName, aggregatePropertyName, variableScope); - - if ("property".equals(aggregateFunctionName) && METHOD_TO_SUBQUERY_MAP.containsKey(methodToCall)) { + if ("property".equals(aggregateFunctionName)) { + ClosureAndArguments closureAndArguments = new ClosureAndArguments(variableScope); + addProjectionToCurrentBody(closureAndArguments.getCurrentBody(), aggregateFunctionName, aggregatePropertyName, variableScope); rightExpression = closureAndArguments.getClosureExpression(); - methodToCall = methodToCall + "All"; + + if (METHOD_TO_SUBQUERY_MAP.containsKey(methodToCall)) { + 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())); + // The closure takes the subquery as its parameter and calls projections on it. The + // @Where of a data service is compiled statically, and there the calls of a closure + // without that parameter resolve to the enclosing criteria, so the aggregate was + // added to the outer query. The criteria the closure is passed to builds the + // subquery when the query runs, of its own class, which can be a subclass of the + // class named where the query is written. + rightExpression = projectionsOnParameter(aggregateFunctionName, aggregatePropertyName, variableScope); } } 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)); @@ -1425,6 +1444,55 @@ private void addProjectionToCurrentBody(BlockStatement currentBody, String funct currentBody.addStatement(new ExpressionStatement(new MethodCallExpression(thisExpression, "projections", projectionsBody.getArguments()))); } + /** + * The name of the parameter of the generated closure, to which {@code $} is added for as long as the application declares it: + * as a variable of an enclosing scope, or as a parameter of the data service method that the closure is moved into, which + * {@link #transformClosureExpression(ClassNode, ClosureExpression, Collection)} is given. The compiler refuses to see the + * name declared twice. + */ + private static final String SUBQUERY_PARAMETER_NAME = "$subquery"; + + /** + * A closure that adds the aggregate to the criteria it is called with: + * {@code { DetachedCriteria c -> c.getProjectionList().fn(property) }}. The call names its receiver: in a statically + * compiled closure, such as the {@code @Where} of a data service, a call without a receiver is not sent to the + * delegate, and the subquery is left without a projection. The receiver is the parameter of the closure, which no + * variable of the application can hide. + */ + private String subqueryParameterName(VariableScope variableScope) { + String name = SUBQUERY_PARAMETER_NAME; + while (reservedParameterNames.contains(name) || isDeclaredInScope(variableScope, name)) { + name = name + '$'; + } + return name; + } + + private static boolean isDeclaredInScope(VariableScope variableScope, String name) { + for (VariableScope scope = variableScope; scope != null; scope = scope.getParent()) { + if (scope.getDeclaredVariable(name) != null) { + return true; + } + } + return false; + } + + private ClosureExpression projectionsOnParameter(String functionName, String aggregatePropertyName, VariableScope variableScope) { + Parameter criteria = new Parameter(getParameterizedDetachedCriteriaClassNode(null), subqueryParameterName(variableScope)); + VariableScope scope = new VariableScope(variableScope); + scope.putDeclaredVariable(criteria); + MethodCallExpression projectionList = new MethodCallExpression(new VariableExpression(criteria), "getProjectionList", + new ArgumentListExpression()); + projectionList.setImplicitThis(false); + MethodCallExpression aggregate = new MethodCallExpression(projectionList, functionName, + new ArgumentListExpression(new ConstantExpression(aggregatePropertyName))); + aggregate.setImplicitThis(false); + BlockStatement body = new BlockStatement(); + body.addStatement(new ExpressionStatement(aggregate)); + ClosureExpression closure = new ClosureExpression(new Parameter[]{criteria}, body); + closure.setVariableScope(scope); + return closure; + } + @Override protected SourceUnit getSourceUnit() { return this.sourceUnit; diff --git a/grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/services/implementers/AbstractWhereImplementer.groovy b/grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/services/implementers/AbstractWhereImplementer.groovy index 0c737719d64..f5ec04ab070 100644 --- a/grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/services/implementers/AbstractWhereImplementer.groovy +++ b/grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/services/implementers/AbstractWhereImplementer.groovy @@ -86,7 +86,7 @@ abstract class AbstractWhereImplementer extends AbstractReadOperationImplementer ClosureExpression originalClosureExpression = (ClosureExpression) expr ClosureExpression closureExpression = AstUtils.makeClosureAwareOfArguments(newMethodNode, originalClosureExpression) DetachedCriteriaTransformer transformer = new DetachedCriteriaTransformer(sourceUnit) - transformer.transformClosureExpression(domainClassNode, closureExpression) + transformer.transformClosureExpression(domainClassNode, closureExpression, newMethodNode.parameters*.name) BlockStatement body = (BlockStatement) newMethodNode.getCode() 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 07e634ed9f7..1e8bf52c08d 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 @@ -159,6 +159,36 @@ class AggEmbeddedReading { e.message.contains('Cannot use aggregate function avg inside the block of the embedded property "stats"') } + void "a value computed by a call of the same name inside the block of an embedded property is not an aggregate and compiles"() { + when: + Class compiled = new GroovyClassLoader().parseClass(''' +import grails.gorm.annotation.Entity +import org.grails.datastore.gorm.query.transform.ApplyDetachedCriteriaTransform + +class AggEmbeddedValueStats { + Integer qty +} + +@ApplyDetachedCriteriaTransform +@Entity +class AggEmbeddedValueReading { + AggEmbeddedValueStats stats + + static embedded = ['stats'] + + static ok() { + def limits = [1, 2] + AggEmbeddedValueReading.where { + stats { qty > limits.max() } + } + } +} +''') + + then: 'the receiver is a list of the application, not the query DSL, so the call is a value like any other' + compiled != null + } + void "an aggregate function outside the block of an embedded property is still accepted next to one"() { when: Class compiled = new GroovyClassLoader().parseClass(''' From 11de1371fccdb3ab73cd3fb403c3c262cbd720a0 Mon Sep 17 00:00:00 2001 From: Walter Duque de Estrada Date: Fri, 4 Dec 2026 15:25:22 -0600 Subject: [PATCH 5/8] fix(datamapping): let a helper call of an aggregate's name through in 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. --- .../services/WhereServiceAggregateSpec.groovy | 19 ++ .../DetachedCriteriaTransformer.java | 64 +++++- .../WhereAggregateCallFormsSpec.groovy | 205 ++++++++++++++++++ .../src/en/guide/upgrading/upgrading80x.adoc | 2 +- 4 files changed, 286 insertions(+), 4 deletions(-) create mode 100644 grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/query/transform/WhereAggregateCallFormsSpec.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 index 3a68f20e57d..d22fb45fdb6 100644 --- 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 @@ -126,6 +126,12 @@ class WhereServiceAggregateSpec extends Specification { found(service.aboveAverageAndParameter(10)) == [] } + void "an aggregate in a data service @Where runs when the query declares a variable named like the generated parameter"() { + expect: 'the average is 4 and the variable of the query, also 4, is the other bound' + found(service.aboveAverageAndLocal()) == [10] + found(service.aboveAverageAndTwoLocals()) == [10] + } + void "an aggregate in a statically compiled where query is run as a subquery"() { expect: found(listOf(staticallyCompiledQuery())) == [10] @@ -239,6 +245,19 @@ interface WsaReadingService { @Where({ qty <= count(qty) }) List atMostTheCount() + @Where({ + def $subquery = 4 + qty > avg(qty) && qty > $subquery + }) + List aboveAverageAndLocal() + + @Where({ + def $subquery = 4 + def $subquery$ = 3 + qty > avg(qty) && qty > $subquery && qty > $subquery$ + }) + List aboveAverageAndTwoLocals() + @Where({ qty > avg(qty) && qty > $subquery }) List aboveAverageAndParameter(Integer $subquery) } 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 07d38973fe7..5d31008ab6c 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 @@ -35,6 +35,7 @@ import org.codehaus.groovy.ast.ClassCodeVisitorSupport; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; +import org.codehaus.groovy.ast.CodeVisitorSupport; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.GenericsType; import org.codehaus.groovy.ast.MethodNode; @@ -171,6 +172,8 @@ public class DetachedCriteriaTransformer extends ClassCodeVisitorSupport { /** 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<>(); private Set reservedParameterNames = Collections.emptySet(); + /** every name the query being transformed declares or reads: a variable of the generated closure takes none of them */ + private Set namesOfTheQuery = Collections.emptySet(); public DetachedCriteriaTransformer(SourceUnit sourceUnit) { this.sourceUnit = sourceUnit; @@ -646,8 +649,10 @@ public void transformClosureExpression(ClassNode classNode, ClosureExpression cl public void transformClosureExpression(ClassNode classNode, ClosureExpression closureExpression) { if (closureExpression.getNodeMetaData(TRANSFORMED_MARKER) != null) return; ClassNode previousClassNode = this.currentClassNode; + Set previousNames = this.namesOfTheQuery; try { this.currentClassNode = classNode; + this.namesOfTheQuery = namesIn(closureExpression, previousNames); List propertyNames = AstPropertyResolveUtils.getPropertyNames(classNode); Statement code = closureExpression.getCode(); BlockStatement newCode = new BlockStatement(); @@ -667,9 +672,54 @@ public void transformClosureExpression(ClassNode classNode, ClosureExpression cl } } finally { this.currentClassNode = previousClassNode; + this.namesOfTheQuery = previousNames; } } + /** + * The names that a closure declares or reads, wherever it does: a local variable of the body, a parameter of a closure + * inside it, the variable of a loop or of a catch clause, and every variable it reads. The transformation runs before the + * compiler has resolved the scopes of the closure, so the scope cannot say which names the application declared. + */ + private static Set namesIn(ClosureExpression closure, Set outer) { + Set names = new HashSet<>(outer); + CodeVisitorSupport collector = new CodeVisitorSupport() { + @Override + public void visitVariableExpression(VariableExpression expression) { + names.add(expression.getName()); + super.visitVariableExpression(expression); + } + + @Override + public void visitClosureExpression(ClosureExpression expression) { + addParameters(expression.getParameters()); + super.visitClosureExpression(expression); + } + + @Override + public void visitForLoop(ForStatement forLoop) { + names.add(forLoop.getVariable().getName()); + super.visitForLoop(forLoop); + } + + @Override + public void visitCatchStatement(CatchStatement statement) { + names.add(statement.getVariable().getName()); + super.visitCatchStatement(statement); + } + + private void addParameters(Parameter[] parameters) { + if (parameters != null) { + for (Parameter parameter : parameters) { + names.add(parameter.getName()); + } + } + } + }; + collector.visitClosureExpression(closure); + return names; + } + private void addBlockStatementToNewQuery(BlockStatement blockStatement, BlockStatement newCode, boolean addAll, List propertyNames, VariableScope variableScope) { List statements = blockStatement.getStatements(); for (Statement statement : statements) { @@ -1283,8 +1333,11 @@ private void addCriteriaCall(BlockStatement newCode, String operator, Expression } } } else if (aggregateFunctionName != null && !embeddedPath.isEmpty() && - (methodTarget instanceof VariableExpression) && ((VariableExpression) methodTarget).isThisExpression()) { - // a call of the query DSL, with no receiver of its own, as a call such as list.max() is a value, not an aggregate. + (methodTarget instanceof VariableExpression) && ((VariableExpression) methodTarget).isThisExpression() && + isCallOfOneArgument(aggregateMethodCall)) { + // a call of the query DSL, with no receiver of its own, as a call such as list.max() is a value, not an aggregate, + // and neither is a call of the same name that takes no argument or several, which outside an embedded block is left + // as the value it is: the aggregate of the query DSL takes the one property it is computed over. // 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)); @@ -1461,12 +1514,17 @@ private void addProjectionToCurrentBody(BlockStatement currentBody, String funct */ private String subqueryParameterName(VariableScope variableScope) { String name = SUBQUERY_PARAMETER_NAME; - while (reservedParameterNames.contains(name) || isDeclaredInScope(variableScope, name)) { + while (reservedParameterNames.contains(name) || namesOfTheQuery.contains(name) || isDeclaredInScope(variableScope, name)) { name = name + '$'; } return name; } + private static boolean isCallOfOneArgument(MethodCallExpression call) { + Expression arguments = call.getArguments(); + return arguments instanceof ArgumentListExpression && ((ArgumentListExpression) arguments).getExpressions().size() == 1; + } + private static boolean isDeclaredInScope(VariableScope variableScope, String name) { for (VariableScope scope = variableScope; scope != null; scope = scope.getParent()) { if (scope.getDeclaredVariable(name) != null) { diff --git a/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/query/transform/WhereAggregateCallFormsSpec.groovy b/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/query/transform/WhereAggregateCallFormsSpec.groovy new file mode 100644 index 00000000000..ccb802a5426 --- /dev/null +++ b/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/query/transform/WhereAggregateCallFormsSpec.groovy @@ -0,0 +1,205 @@ +/* + * 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.datastore.gorm.query.transform + +import java.util.concurrent.atomic.AtomicInteger + +import org.codehaus.groovy.control.MultipleCompilationErrorsException + +import spock.lang.Specification + +/** + * The calls of an aggregate function name, and the names a query declares, are generated as tables, because each form is one + * sample of a class: + *
    + *
  • Inside the block of an embedded property the aggregates of the query DSL are refused: a call with no receiver of its + * own, or on {@code this}, that takes one argument, as it does outside the block. A call of the same name with no argument or + * with several is a value the application computes, as it was before the refusal, and so is a call on another receiver.
  • + *
  • The closure generated for an aggregate takes a parameter of its own, whose name is not one the query declares or reads: + * a local variable, a parameter of a closure, the variable of a loop or of a catch clause, or a variable of the method, and + * not one that is declared before the aggregate or after it.
  • + *
+ */ +class WhereAggregateCallFormsSpec extends Specification { + + private static final AtomicInteger COUNTER = new AtomicInteger() + + private static final List FUNCTIONS = ['avg', 'max', 'min', 'sum', 'count', 'property'] + + // The class name is unique across the test JVM because AstPropertyResolveUtils caches resolved properties by class name + private static String nextName() { + 'AggForms' + COUNTER.incrementAndGet() + } + + private static Class compileEmbedded(String body) { + String name = nextName() + new GroovyClassLoader().parseClass(""" +import grails.gorm.annotation.Entity +import org.grails.datastore.gorm.query.transform.ApplyDetachedCriteriaTransform + +class ${name}Inner { + Integer qty +} + +class ${name}Middle { + Integer qty + ${name}Inner inner + static embedded = ['inner'] +} + +@ApplyDetachedCriteriaTransform +@Entity +class ${name} { + Integer qty + ${name}Middle stats + static embedded = ['stats'] + + static query() { + def helpers = [1, 2] + ${name}.where { + ${body} + } + } +} +""") + } + + void "the call #receiver#function(#arguments) at depth #depth inside the block of an embedded property is #outcome"() { + given: + String call = "${receiver}${function}(${arguments})" + String body = depth == 1 ? "stats { qty > ${call} }" : "stats { inner { qty > ${call} } }" + + when: + MultipleCompilationErrorsException error = null + try { + compileEmbedded(body) + } catch (MultipleCompilationErrorsException e) { + error = e + } + + then: + (error != null) == refused + !refused || error.message.contains('Cannot use aggregate function') + !refused || error.message.contains('inside the block of the embedded property') + + where: + [function, receiver, arguments, depth] << [FUNCTIONS, ['this.', '', 'helpers.'], ['', 'qty', 'qty, 1', '1'], [1, 2]].combinations() + refused = receiver != 'helpers.' && arguments in ['qty', '1'] + outcome = refused ? 'refused' : 'a value' + } + + void "a name the query declares or reads is not taken for the parameter of the generated closure: #kind #variable #position #function"() { + given: + String name = nextName() + String aggregate = "qty > ${function}(qty)" + String declare = declaration.declare.replace("N", variable) + String use = "qty > ${variable}" + String body = position == 'before' ? "${declare}\n${aggregate}\n${use}" : "${aggregate}\n${declare}\n${use}" + String prefix = declaration.enclosing ? "def ${variable} = 4" : '' + + when: + Class compiled = new GroovyClassLoader().parseClass(""" +import grails.gorm.annotation.Entity +import org.grails.datastore.gorm.query.transform.ApplyDetachedCriteriaTransform + +@ApplyDetachedCriteriaTransform +@Entity +class ${name} { + Integer qty + + static query() { + ${prefix} + ${name}.where { + ${declaration.enclosing ? aggregate + '\n' + use : body} + } + } +} +""") + + then: 'the query compiles: the generated parameter has a name of its own' + compiled != null + + where: + [declaration, variable, position, function] << [ + [ + [declare: 'def N = 4', enclosing: false], + [declare: 'def f = { N -> N }', enclosing: false], + [declare: 'def f = { x -> def N = 1 }', enclosing: false], + [declare: 'for (N in [1]) { }', enclosing: false], + [declare: 'try { } catch (Exception N) { }', enclosing: false], + [declare: "def b = 'x' instanceof String N", enclosing: false], + [declare: '', enclosing: true], + ], + ['$subquery', '$subquery$', 'subquery'], + ['before', 'after'], + ['avg', 'max', 'min', 'sum', 'count'] + ].combinations() + kind = declaration.enclosing ? 'enclosing' : declaration.declare.startsWith('def N') ? 'local' : declaration.declare.take(8) + } + + void "a name the @Where of a data service declares or reads is not taken for the generated parameter: #kind #variable #position #function"() { + given: + String name = nextName() + String declare = declaration.declare.replace('N', variable) + String aggregate = "qty > ${function}(qty)" + String use = "qty > ${variable}" + String body = declaration.parameter ? "${aggregate} && ${use}" : (position == 'before' ? "${declare}\n${aggregate}\n${use}" : "${aggregate}\n${declare}\n${use}") + String parameter = declaration.parameter ? "Integer ${variable}" : '' + when: + Class service = new GroovyClassLoader().parseClass(""" +import grails.gorm.services.Service +import grails.gorm.services.Where +import grails.gorm.annotation.Entity + +@Service(${name}) +interface ${name}Service { + + @Where({ + ${body} + }) + List<${name}> find(${parameter}) +} + +@Entity +class ${name} { + Integer qty +} +""") + + then: 'the service compiles: the generated parameter has a name of its own' + service.isInterface() + + where: + [declaration, variable, position, function] << [ + [ + [declare: 'def N = 4', parameter: false], + [declare: 'def f = { N -> N }', parameter: false], + [declare: 'def f = { x -> def N = 1 }', parameter: false], + [declare: 'for (N in [1]) { }', parameter: false], + [declare: 'try { } catch (Exception N) { }', parameter: false], + [declare: "def b = 'x' instanceof String N", parameter: false], + [declare: '', parameter: true], + ], + ['$subquery', '$subquery$', 'subquery'], + ['before', 'after'], + ['avg', 'max', 'min', 'sum', 'count'] + ].combinations() + kind = declaration.parameter ? 'parameter' : declaration.declare.startsWith('def N') ? 'local' : declaration.declare.take(8) + } +} diff --git a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc index 73801837f34..959e33fdcbf 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc @@ -5097,7 +5097,7 @@ A value encoded beforehand is no longer encoded twice in the `value` of ` 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. +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. Only the aggregates of the query DSL are refused, which take the one property they are computed over; a call of the same name with no argument or with several, or on another receiver, is a value, and compiles as it did before. No working query changes. ==== A Second Cache Manager No Longer Stops a Cached Application From Starting From e3e727ac32328bf18c3dd52306da812662d939bf Mon Sep 17 00:00:00 2001 From: Walter Duque de Estrada Date: Fri, 4 Dec 2026 18:31:12 -0600 Subject: [PATCH 6/8] docs(upgrading): the refusal of an aggregate in an embedded block is of the plain form, not of the .of form --- grails-doc/src/en/guide/upgrading/upgrading80x.adoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc index 959e33fdcbf..7075ce179d6 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc @@ -5097,7 +5097,7 @@ A value encoded beforehand is no longer encoded twice in the `value` of ` 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. Only the aggregates of the query DSL are refused, which take the one property they are computed over; a call of the same name with no argument or with several, or on another receiver, is a value, and compiles as it did before. No working query changes. +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. Only the plain form of the aggregates of the query DSL is refused, a call that takes the one property it is computed over, as `avg(qty)`; a call of the same name with no argument or with several, or on another receiver, is a value, and compiles as it did before. The form `avg(qty).of { ... }` is not covered by this check: it is built before the check is reached, and fails when the query runs, as it did before. No working query changes. ==== A Second Cache Manager No Longer Stops a Cached Application From Starting From d6f94b85e3c08cf2c17bc980dc30e3972c8fc1f9 Mon Sep 17 00:00:00 2001 From: Walter Duque de Estrada Date: Sat, 5 Dec 2026 00:43:14 -0600 Subject: [PATCH 7/8] fix(datamapping): an aggregate in the block of an entity inside the block 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. --- .../DetachedCriteriaTransformer.java | 10 +++ .../WhereAggregateCallFormsSpec.groovy | 75 +++++++++++++++++++ 2 files changed, 85 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 5d31008ab6c..2680eae3378 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 @@ -901,8 +901,15 @@ private void handleAssociationMethodCallExpression(BlockStatement newCode, Metho ClassNode existing = currentClassNode; boolean enteredEmbedded = embeddedBlock && type != null; + // the block of an entity inside the block of an embedded value is built over the entity, so an aggregate in it is + // built over an entity as it is anywhere else: the embedded properties it is inside of are set aside until it ends + java.util.ArrayDeque outerEmbedded = !embeddedBlock && type != null && !embeddedPath.isEmpty() ? + new java.util.ArrayDeque<>(embeddedPath) : null; try { if (type != null) { + if (outerEmbedded != null) { + embeddedPath.clear(); + } if (enteredEmbedded) { embeddedPath.addLast(methodName); } @@ -915,6 +922,9 @@ private void handleAssociationMethodCallExpression(BlockStatement newCode, Metho if (enteredEmbedded) { embeddedPath.removeLast(); } + if (outerEmbedded != null) { + embeddedPath.addAll(outerEmbedded); + } } } } diff --git a/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/query/transform/WhereAggregateCallFormsSpec.groovy b/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/query/transform/WhereAggregateCallFormsSpec.groovy index ccb802a5426..8fc2ff02268 100644 --- a/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/query/transform/WhereAggregateCallFormsSpec.groovy +++ b/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/query/transform/WhereAggregateCallFormsSpec.groovy @@ -104,6 +104,81 @@ class ${name} { outcome = refused ? 'refused' : 'a value' } + private static Class compileEntityInEmbedded(String body) { + String name = nextName() + new GroovyClassLoader().parseClass(""" +import grails.gorm.annotation.Entity +import org.grails.datastore.gorm.query.transform.ApplyDetachedCriteriaTransform + +class ${name}Inner { + Integer qty +} + +@Entity +class ${name}Category { + Integer qty + ${name}Inner inner + static embedded = ['inner'] +} + +class ${name}Middle { + Integer qty + ${name}Category category +} + +@ApplyDetachedCriteriaTransform +@Entity +class ${name} { + Integer qty + ${name}Middle stats + ${name}Category direct + static embedded = ['stats'] + + static query() { + def helpers = [1, 2] + ${name}.where { + ${body} + } + } +} +""") + } + + // the innermost block decides: the block of an embedded value refuses the aggregate, the block of an entity, also when it is + // inside the block of an embedded value, takes it as it does anywhere else + private static final Map BLOCK_PATHS = [ + 'an embedded value' : 'stats { QUERY }', + 'an entity in an embedded value' : 'stats { category { QUERY } }', + 'an embedded value in an entity in one' : 'stats { category { inner { QUERY } } }', + 'an entity outside any embedded value' : 'direct { QUERY }', + 'an embedded value in an entity' : 'direct { inner { QUERY } }', + ].asImmutable() + + void "the call #receiver#function(#arguments) inside the block of #path is #outcome"() { + given: + String body = BLOCK_PATHS[path].replace('QUERY', "qty > ${receiver}${function}(${arguments})") + + when: + MultipleCompilationErrorsException error = null + try { + compileEntityInEmbedded(body) + } catch (MultipleCompilationErrorsException e) { + error = e + } + + then: + (error != null) == refused + !refused || error.message.contains('inside the block of the embedded property') + !refused || error.message.contains("\"${innermostEmbedded}\"") + + where: + [path, function, receiver, arguments] << [BLOCK_PATHS.keySet().toList(), ['avg', 'max', 'sum', 'count'], ['', 'helpers.'], ['qty', '']].combinations() + refused = path in ['an embedded value', 'an embedded value in an entity in one', 'an embedded value in an entity'] && + receiver == '' && arguments == 'qty' + innermostEmbedded = path == 'an embedded value' ? 'stats' : 'inner' + outcome = refused ? 'refused' : 'compiled' + } + void "a name the query declares or reads is not taken for the parameter of the generated closure: #kind #variable #position #function"() { given: String name = nextName() From 35fc51e8935ece1ce958569f17c334fc25109890 Mon Sep 17 00:00:00 2001 From: Walter Duque de Estrada Date: Sat, 5 Dec 2026 00:46:48 -0600 Subject: [PATCH 8/8] fix(datamapping): keep the refusal of an aggregate in the block of a 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. --- .../transform/DetachedCriteriaTransformer.java | 7 ++++--- .../transform/WhereAggregateCallFormsSpec.groovy | 14 +++++++++++--- 2 files changed, 15 insertions(+), 6 deletions(-) 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 2680eae3378..a39f4078f4c 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 @@ -901,9 +901,10 @@ private void handleAssociationMethodCallExpression(BlockStatement newCode, Metho ClassNode existing = currentClassNode; boolean enteredEmbedded = embeddedBlock && type != null; - // the block of an entity inside the block of an embedded value is built over the entity, so an aggregate in it is - // built over an entity as it is anywhere else: the embedded properties it is inside of are set aside until it ends - java.util.ArrayDeque outerEmbedded = !embeddedBlock && type != null && !embeddedPath.isEmpty() ? + // the block of an entity inside the block of an embedded value, or of a collection of entities, is built over the entity, so + // an aggregate in it is built over an entity as it is anywhere else: the embedded properties it is inside of are set aside + // until it ends. The block of a collection of another class, one that is no entity, keeps them + java.util.ArrayDeque outerEmbedded = type != null && AstUtils.isDomainClass(type) && !embeddedPath.isEmpty() ? new java.util.ArrayDeque<>(embeddedPath) : null; try { if (type != null) { diff --git a/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/query/transform/WhereAggregateCallFormsSpec.groovy b/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/query/transform/WhereAggregateCallFormsSpec.groovy index 8fc2ff02268..1264826a1ad 100644 --- a/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/query/transform/WhereAggregateCallFormsSpec.groovy +++ b/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/query/transform/WhereAggregateCallFormsSpec.groovy @@ -121,9 +121,15 @@ class ${name}Category { static embedded = ['inner'] } +class ${name}Tag { + Integer qty +} + class ${name}Middle { Integer qty ${name}Category category + List<${name}Tag> tags + List<${name}Category> categories } @ApplyDetachedCriteriaTransform @@ -152,6 +158,8 @@ class ${name} { 'an embedded value in an entity in one' : 'stats { category { inner { QUERY } } }', 'an entity outside any embedded value' : 'direct { QUERY }', 'an embedded value in an entity' : 'direct { inner { QUERY } }', + 'a collection of a class that is no entity in an embedded value': 'stats { tags { QUERY } }', + 'a collection of entities in an embedded value' : 'stats { categories { QUERY } }', ].asImmutable() void "the call #receiver#function(#arguments) inside the block of #path is #outcome"() { @@ -173,9 +181,9 @@ class ${name} { where: [path, function, receiver, arguments] << [BLOCK_PATHS.keySet().toList(), ['avg', 'max', 'sum', 'count'], ['', 'helpers.'], ['qty', '']].combinations() - refused = path in ['an embedded value', 'an embedded value in an entity in one', 'an embedded value in an entity'] && - receiver == '' && arguments == 'qty' - innermostEmbedded = path == 'an embedded value' ? 'stats' : 'inner' + refused = path in ['an embedded value', 'an embedded value in an entity in one', 'an embedded value in an entity', + 'a collection of a class that is no entity in an embedded value'] && receiver == '' && arguments == 'qty' + innermostEmbedded = path in ['an embedded value', 'a collection of a class that is no entity in an embedded value'] ? 'stats' : 'inner' outcome = refused ? 'refused' : 'compiled' }