Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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<WsaReading> aboveAverageQuery() {
WsaReading.where { qty > avg(qty) }
}

static DetachedCriteria<WsaReading> atLeastAverageQuery() {
WsaReading.where { qty >= avg(qty) }
}

static DetachedCriteria<WsaReading> maximumQuery() {
WsaReading.where { qty == max(qty) }
}

static DetachedCriteria<WsaReading> minimumQuery() {
WsaReading.where { qty == min(qty) }
}

private static List<WsaReading> listOf(DetachedCriteria<WsaReading> query) {
WsaReading.withNewTransaction { query.list() } as List<WsaReading>
}

private static List<Integer> found(List<WsaReading> readings) {
readings*.qty.sort()
}
}

@Entity
class WsaReading {

Integer qty
}

@Service(WsaReading)
interface WsaReadingService {

@Where({ qty > avg(qty) })
List<WsaReading> aboveAverage()

@Where({ qty >= avg(qty) })
List<WsaReading> atLeastAverage()

@Where({ qty == max(qty) })
List<WsaReading> theMaximum()

@Where({ qty == min(qty) })
List<WsaReading> theMinimum()
}
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@ public class DetachedCriteriaTransformer extends ClassCodeVisitorSupport {
protected Map<String, ClassNode> staticDetachedCriteriaVariables = new HashMap<>();
protected Set<Expression> 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<String> embeddedPath = new java.util.ArrayDeque<>();

public DetachedCriteriaTransformer(SourceUnit sourceUnit) {
this.sourceUnit = sourceUnit;
Expand Down Expand Up @@ -813,6 +815,7 @@ private void handleAssociationMethodCallExpression(BlockStatement newCode, Metho

List<String> 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
Expand All @@ -821,21 +824,30 @@ private void handleAssociationMethodCallExpression(BlockStatement newCode, Metho
if (associationTypeFromGenerics != null) {
type = associationTypeFromGenerics;
associationPropertyNames = getPropertyNamesForAssociation(associationTypeFromGenerics);
} else {
embeddedBlock = true;
}
}
if (associationPropertyNames == null) {
associationPropertyNames = AstPropertyResolveUtils.getPropertyNames(type);
}

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();
}
}
}
}
Expand Down Expand Up @@ -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()) {
Expand All @@ -1278,10 +1295,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))),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

"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));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
4 changes: 4 additions & 0 deletions grails-doc/src/en/guide/upgrading/upgrading80x.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -5033,6 +5033,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 `<g:textField>`, `<g:hiddenField>` and the other field tags when a `RequestDataValueProcessor` returns it unchanged, nor in an option of `<g:select>`, with or without a processor. `<g:paginate>` and `<g:sortableColumn>` 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.

==== 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.
Expand Down