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..d22fb45fdb6 --- /dev/null +++ b/grails-data-hibernate5/core/src/test/groovy/org/grails/orm/hibernate/services/WhereServiceAggregateSpec.groovy @@ -0,0 +1,263 @@ +/* + * 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 groovy.transform.CompileStatic + +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 grails.gorm.transactions.Transactional + +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, WsaBase, WsaSub) + + @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 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 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] + } + + @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) } + } + + static DetachedCriteria atLeastAverageQuery() { + WsaReading.where { qty >= avg(qty) } + } + + static DetachedCriteria maximumQuery() { + WsaReading.where { qty == max(qty) } + } + + static DetachedCriteria minimumQuery() { + 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 + } + + private static List found(List readings) { + readings*.qty.sort() + } +} + +@Entity +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 { + + @Where({ qty > avg(qty) }) + List aboveAverage() + + @Where({ qty >= avg(qty) }) + List atLeastAverage() + + @Where({ qty == max(qty) }) + List theMaximum() + + @Where({ qty == min(qty) }) + List theMinimum() + + @Where({ qty < sum(qty) }) + List belowTheSum() + + @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 89e09a0a571..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 @@ -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; @@ -34,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; @@ -167,6 +169,11 @@ 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<>(); + 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; @@ -624,11 +631,28 @@ 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; + 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(); @@ -648,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) { @@ -813,6 +882,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 +891,8 @@ private void handleAssociationMethodCallExpression(BlockStatement newCode, Metho if (associationTypeFromGenerics != null) { type = associationTypeFromGenerics; associationPropertyNames = getPropertyNamesForAssociation(associationTypeFromGenerics); + } else { + embeddedBlock = true; } } if (associationPropertyNames == null) { @@ -828,14 +900,32 @@ 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, 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) { + if (outerEmbedded != null) { + embeddedPath.clear(); + } + if (enteredEmbedded) { + embeddedPath.addLast(methodName); + } currentClassNode = type; addBlockStatementToNewQuery((BlockStatement) associationCode, currentBody, associationPropertyNames.isEmpty(), associationPropertyNames, variableScope); } } finally { currentClassNode = existing; + if (enteredEmbedded) { + embeddedPath.removeLast(); + } + if (outerEmbedded != null) { + embeddedPath.addAll(outerEmbedded); + } } } } @@ -1253,6 +1343,16 @@ private void addCriteriaCall(BlockStatement newCode, String operator, Expression } } } + } else if (aggregateFunctionName != null && !embeddedPath.isEmpty() && + (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)); + return; } else if (aggregateFunctionName != null) { if ((methodTarget instanceof VariableExpression) && ((VariableExpression) methodTarget).isThisExpression()) { @@ -1273,15 +1373,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); - - rightExpression = closureAndArguments.getClosureExpression(); + if ("property".equals(aggregateFunctionName)) { + ClosureAndArguments closureAndArguments = new ClosureAndArguments(variableScope); + addProjectionToCurrentBody(closureAndArguments.getCurrentBody(), aggregateFunctionName, aggregatePropertyName, variableScope); + rightExpression = closureAndArguments.getClosureExpression(); - if ("property".equals(aggregateFunctionName) && METHOD_TO_SUBQUERY_MAP.containsKey(methodToCall)) { - methodToCall = methodToCall + "All"; + if (METHOD_TO_SUBQUERY_MAP.containsKey(methodToCall)) { + methodToCall = methodToCall + "All"; + } + } else { + // 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)); @@ -1401,6 +1508,60 @@ 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) || 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) { + 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/WhereAggregateCallFormsSpec.groovy b/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/query/transform/WhereAggregateCallFormsSpec.groovy new file mode 100644 index 00000000000..1264826a1ad --- /dev/null +++ b/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/query/transform/WhereAggregateCallFormsSpec.groovy @@ -0,0 +1,288 @@ +/* + * 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' + } + + 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}Tag { + Integer qty +} + +class ${name}Middle { + Integer qty + ${name}Category category + List<${name}Tag> tags + List<${name}Category> categories +} + +@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 } }', + '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"() { + 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', + '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' + } + + 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-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..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 @@ -128,4 +128,94 @@ 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 "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(''' +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 + } } diff --git a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc index c0dae236d15..7075ce179d6 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc @@ -5095,6 +5095,10 @@ A value marked with `raw()` is still written as given by the tags that wrote it 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. 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 The cache annotations are given their cache manager by type. Grails 8.0.0 failed to start when the application context had a second `CacheManager` beside the plugin's `grailsCacheManager` and Spring could not choose between them, as when neither is marked primary or has a `@Priority`, which is what happens when the Spring Security plugin's `cacheUsers` is set. The annotations now use `grailsCacheManager` there. Two cache managers both marked primary, or sharing the highest `@Priority`, still fail to start, as Spring rejects them before it looks further; mark only one primary, or give one the higher priority. A cache manager whose `@Priority` is only on the object its factory method or `FactoryBean` returns, with the declared type a plain `CacheManager`, is not seen as preferred beside `grailsCacheManager`, which the annotations then use; mark it primary to keep it. Wherever Spring can choose, such as a cache manager marked primary or with a `@Priority`, it chooses as before, and with caching turned off (`grails.cache.enabled: false`) nothing changes. This applies to classes compiled against Grails 8.0.0 too, so plugins need not be recompiled. The cache tags use `grailsCacheManager` by name, as before.