Skip to content
Open
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
Expand Down Expand Up @@ -137,6 +139,8 @@ public abstract class AbstractHibernateCriteriaBuilder extends GroovyObjectSuppo
protected List<String> aliasStack = new ArrayList<>();
protected List<Criteria> aliasInstanceStack = new ArrayList<>();
protected Map<String, String> aliasMap = new HashMap<>();
/** The aliases of association blocks that are branches of an "or", which join the association with a left join. */
protected Set<String> leftBlockAliases = new HashSet<>();
protected static final String ALIAS = "_alias";
protected ResultTransformer resultTransformer;
protected int aliasCount;
Expand Down Expand Up @@ -1863,7 +1867,7 @@ else if (paginationEnabledList) {
// Property type is a managed entity - treat as association
Class oldTargetClass = targetClass;
targetClass = propertyType;
if (targetClass.equals(oldTargetClass) && !hasMoreThanOneArg) {
if ((targetClass.equals(oldTargetClass) || isInDisjunction()) && !hasMoreThanOneArg) {
joinType = org.hibernate.sql.JoinType.LEFT_OUTER_JOIN.getJoinTypeValue();
}
associationStack.add(name);
Expand Down Expand Up @@ -1892,12 +1896,28 @@ else if (paginationEnabledList) {
if (attribute.isAssociation()) {
Class oldTargetClass = targetClass;
targetClass = getClassForAssociationType(attribute);
if (targetClass.equals(oldTargetClass) && !hasMoreThanOneArg) {
joinType = org.hibernate.sql.JoinType.LEFT_OUTER_JOIN.getJoinTypeValue(); // default to left join if joining on the same table
final boolean branchOfOr = isInDisjunction() && !hasMoreThanOneArg;
if ((targetClass.equals(oldTargetClass) || branchOfOr) && !hasMoreThanOneArg) {
Comment thread
jamesfredley marked this conversation as resolved.
Resolved
// default to left join if joining on the same table, or when the block is a branch of an
// "or": the entities without the association are still found by the other branches
joinType = org.hibernate.sql.JoinType.LEFT_OUTER_JOIN.getJoinTypeValue();
}
associationStack.add(name);
final String associationPath = getAssociationPath();
final boolean aliasExisted = aliasMap.containsKey(associationPath);
createAliasIfNeccessary(name, associationPath, joinType);
final String blockAlias = getLastAlias();
if (branchOfOr && !aliasExisted) {
leftBlockAliases.add(blockAlias);
}
// a block that is a branch of an "or" asks for an associated entity, and so does a block that
// reuses the left join of one, as a block outside an "or" always did; a block that names an inner
// join asks for it as well, as the join it reuses is not the inner join the caller asked for.
// (A left join the caller named is kept as the caller named it.)
final boolean explicitInnerJoin = hasMoreThanOneArg &&
joinType == org.hibernate.sql.JoinType.INNER_JOIN.getJoinTypeValue();
final boolean requiresAssociated = branchOfOr ||
(leftBlockAliases.contains(blockAlias) && (!hasMoreThanOneArg || explicitInnerJoin));
// the criteria within an association node are grouped with an implicit AND
logicalExpressionStack.add(new LogicalExpression(AND));
invokeClosureNode(callable);
Expand All @@ -1906,6 +1926,15 @@ else if (paginationEnabledList) {
aliasInstanceStack.remove(aliasInstanceStack.size() - 1);
}
LogicalExpression logicalExpression = logicalExpressionStack.remove(logicalExpressionStack.size() - 1);
if (logicalExpression.args.isEmpty() && requiresAssociated) {
// a block without criteria is not a branch of the "or": it asks for an associated entity of
// the entity as a whole, as the inner join it was always given did
criteria.add(Restrictions.isNotNull(blockAlias + ".id"));
}
else if (requiresAssociated) {
// a missing associated entity is a null that a null test in the block would match
logicalExpression.args.add(0, Restrictions.isNotNull(blockAlias + ".id"));

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.

with has a child named kid. orphan has no child. An or that asks for the child, then a second or with child(0), should return only with. It returns with and orphan. The existence check sits inside the second or, so the name branch bypasses it. Keep that check on the whole query.

}
if (!logicalExpression.args.isEmpty()) {
addToCriteria(logicalExpression.toCriterion());
}
Expand Down Expand Up @@ -1984,6 +2013,15 @@ private boolean isAssociationQueryWithJoinSpecificationMethod(Object[] args) {
return args.length == 2 && (args[0] instanceof Number) && (args[1] instanceof Closure);
}

private boolean isInDisjunction() {
for (LogicalExpression expression : logicalExpressionStack) {
if (OR.equals(expression.name)) {
return true;
}
}
return false;
}

private void createAliasIfNeccessary(String associationName, String associationPath, int joinType) {
String newAlias;
if (aliasMap.containsKey(associationPath)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,21 +188,37 @@ protected void addAssociationQueryCriterionAdapters() {
@Override
public Criterion toHibernateCriterion(AbstractHibernateQuery hibernateQuery, Query.Criterion criterion, String alias) {
DetachedAssociationCriteria<?> existing = (DetachedAssociationCriteria<?>) criterion;
if (existing.getAlias() == null) {
alias = hibernateQuery.handleAssociationQuery(existing.getAssociation(), existing.getCriteria());
final boolean branchOfOr = existing.getAlias() == null && hibernateQuery.isInDisjunction();
if (existing.getAlias() != null) {
alias = hibernateQuery.handleAssociationQuery(existing.getAssociation(), existing.getCriteria(), existing.getAlias());
}
else if (branchOfOr) {
alias = hibernateQuery.handleOrBranchAssociationQuery(existing.getAssociation());
}
else {
alias = hibernateQuery.handleAssociationQuery(existing.getAssociation(), existing.getCriteria(), existing.getAlias());
alias = hibernateQuery.handleAssociationQuery(existing.getAssociation(), existing.getCriteria());
}
// a block that is a branch of an or asks for an associated entity, and so does a block that reuses the left
// join of one: a missing associated entity is a null that a null test in the block would match
final boolean requiresAssociated = existing.getAlias() == null && (branchOfOr || hibernateQuery.isLeftBlockAlias(alias));
final boolean emptyBlock = existing.getCriteria().isEmpty();
Association association = existing.getAssociation();
hibernateQuery.associationStack.add(association);
Junction conjunction = Restrictions.conjunction();
if (requiresAssociated && !emptyBlock) {
conjunction.add(Restrictions.isNotNull(alias + ".id"));
}
try {
applySubCriteriaToJunction(association.getAssociatedEntity(), hibernateQuery, existing.getCriteria(), conjunction, alias);
return conjunction;
} finally {
hibernateQuery.associationStack.removeLast();
}
if (requiresAssociated && emptyBlock) {
// a block without criteria is not a branch of the or: it asks for an associated entity of the entity as a whole
hibernateQuery.addToRootCriteria(Restrictions.isNotNull(alias + ".id"));
return null;
}
return conjunction;
}
});
criterionAdaptors.put(AssociationQuery.class, new CriterionAdaptor() {
Expand Down Expand Up @@ -236,15 +252,23 @@ public Criterion toHibernateCriterion(AbstractHibernateQuery hibernateQuery, Que
@Override
public Criterion toHibernateCriterion(AbstractHibernateQuery hibernateQuery, Query.Disjunction criterion, String alias) {
Disjunction disjunction = Restrictions.disjunction();
applySubCriteriaToJunction(hibernateQuery.getEntity(), hibernateQuery, criterion.getCriteria(), disjunction, alias);
hibernateQuery.disjunctionDepth++;
try {
applySubCriteriaToJunction(hibernateQuery.getEntity(), hibernateQuery, criterion.getCriteria(), disjunction, alias);
}
finally {
hibernateQuery.disjunctionDepth--;
}
return disjunction;
}
});
criterionAdaptors.put(Query.Negation.class, new CriterionAdaptor<Query.Negation>() {
@Override
public Criterion toHibernateCriterion(AbstractHibernateQuery hibernateQuery, Query.Negation criterion, String alias) {
CriterionAdaptor<Query.Disjunction> adapter = (CriterionAdaptor<Query.Disjunction>) criterionAdaptors.get(Query.Disjunction.class);
return Restrictions.not(adapter.toHibernateCriterion(hibernateQuery, new Query.Disjunction(criterion.getCriteria()), alias));
// the criteria of a negation are joined with or, but they are not branches of an or: a block in one keeps its join
Disjunction disjunction = Restrictions.disjunction();
applySubCriteriaToJunction(hibernateQuery.getEntity(), hibernateQuery, criterion.getCriteria(), disjunction, alias);
return Restrictions.not(disjunction);
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ public abstract class AbstractHibernateQuery extends Query {
protected String alias;
protected int aliasCount;
protected Map<String, CriteriaAndAlias> createdAssociationPaths = new HashMap<>();
/** how many disjunctions the criterion being added is inside; a block in one is a branch of an or */
protected int disjunctionDepth;
/** the aliases of the joins made for a block that is a branch of an or: left joins, so an entity without the association is kept */
protected final java.util.Set<String> leftBlockAliases = new java.util.HashSet<>();
protected LinkedList<String> aliasStack = new LinkedList<>();
protected LinkedList<PersistentEntity> entityStack = new LinkedList<>();
protected LinkedList<Association> associationStack = new LinkedList<>();
Expand Down Expand Up @@ -212,6 +216,11 @@ else if (criterion instanceof PropertyCriterion) {

CriteriaAndAlias criteriaAndAlias = getCriteriaAndAlias(associationCriteria);

if (associationCriteria.getAlias() == null && leftBlockAliases.contains(criteriaAndAlias.alias)) {
// the join is the left join of a block in an or: a block outside it asks for an associated entity, as
// it always did
addToRootCriteria(Restrictions.isNotNull(criteriaAndAlias.alias + ".id"));
}
if (criteriaAndAlias.criteria != null) {
aliasInstanceStack.add(criteriaAndAlias.criteria);
}
Expand Down Expand Up @@ -504,6 +513,14 @@ protected CriteriaAndAlias getCriteriaAndAlias(DetachedAssociationCriteria assoc
}

protected CriteriaAndAlias getOrCreateAlias(String associationName, String alias) {
return getOrCreateAlias(associationName, alias, null);
}

/**
* @param defaultJoinType the join type to make the join with when the caller has not named one for the association,
* or null for an inner join
*/
protected CriteriaAndAlias getOrCreateAlias(String associationName, String alias, JoinType defaultJoinType) {
CriteriaAndAlias subCriteria = null;
String associationPath = getAssociationPath(associationName);
Criteria parentCriteria = criteria;
Expand All @@ -525,7 +542,7 @@ protected CriteriaAndAlias getOrCreateAlias(String associationName, String alias
subCriteria = createdAssociationPaths.get(associationName);
}
else {
JoinType joinType = joinTypes.get(associationName);
JoinType joinType = joinTypes.containsKey(associationName) ? joinTypes.get(associationName) : defaultJoinType;
if (parentCriteria != null) {
Criteria sc = parentCriteria.createAlias(associationPath, alias, resolveJoinType(joinType));
subCriteria = new CriteriaAndAlias(sc, alias, associationPath);
Expand Down Expand Up @@ -924,6 +941,38 @@ protected List executeQuery(PersistentEntity entity, Junction criteria) {
return list();
}

/**
* The join of an association block that is a branch of an or: a left join, so that an entity without the association
* is still found by the other branches. A join that already exists for the path is reused, and stays what it was.
*/
String handleOrBranchAssociationQuery(Association<?> association) {
String associationName = calculatePropertyName(association.getName());
boolean existed = createdAssociationPaths.containsKey(getAssociationPath(associationName));
CriteriaAndAlias block = getOrCreateAlias(associationName, generateAlias(associationName), JoinType.LEFT);
if (!existed) {
leftBlockAliases.add(block.alias);
}
return block.alias;
}

boolean isInDisjunction() {
return disjunctionDepth > 0;
}

boolean isLeftBlockAlias(String alias) {
return leftBlockAliases.contains(alias);
}

/** Adds a criterion to the query itself, whatever junction or association block is being added. */
void addToRootCriteria(org.hibernate.criterion.Criterion criterion) {
if (criteria != null) {
criteria.add(criterion);
}
else if (detachedCriteria != null) {
detachedCriteria.add(criterion);
}
}

String handleAssociationQuery(Association<?> association, List<Criterion> criteriaList) {
return getCriteriaAndAlias(association).alias;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
* 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 grails.gorm.tests

import org.hibernate.criterion.CriteriaSpecification
import spock.lang.AutoCleanup
import spock.lang.Shared
import spock.lang.Specification

import grails.gorm.annotation.Entity
import grails.gorm.transactions.Rollback
import org.grails.orm.hibernate.HibernateDatastore

/**
* An association block that names its join type keeps it: a block that asks for a left join finds the entities without
* the association, whether it is a branch of an {@code or}, or follows a block in one that joined it with a left join
* because it is a branch of the {@code or}.
*/
@Rollback
class CriteriaOrAssociationJoinTypeSpec extends Specification {

@Shared
@AutoCleanup
HibernateDatastore datastore = new HibernateDatastore(JoinParent, JoinChild)

private void createParents() {
new JoinParent(name: 'with', child: new JoinChild(name: 'kid')).save(flush: true)
new JoinParent(name: 'other', child: new JoinChild(name: 'stranger')).save(flush: true)
new JoinParent(name: 'orphan').save(flush: true)
}

void 'a block that asks for a left join and is a branch of or keeps the entities without the association'() {
given:
createParents()

when:
def found = JoinParent.createCriteria().list {
or {
child(CriteriaSpecification.LEFT_JOIN) { isNull('name') }
eq('name', 'nobody')
}
}

then:
found*.name == ['orphan']
}

void 'a later block that asks for a left join keeps the entities without the association'() {
given:
createParents()

when:
def found = JoinParent.createCriteria().list {
or {
child { eq('name', 'kid') }
eq('name', 'orphan')
}
child(CriteriaSpecification.LEFT_JOIN) { isNull('name') }
}

then:
found*.name == ['orphan']
}
}

@Entity
class JoinParent {

String name
JoinChild child

static constraints = {
child(nullable: true)
}
}

@Entity
class JoinChild {

String name
}
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ def results = c.list {

Here we find all accounts that have either performed transactions in the last 10 days OR have been recently created in the last 10 days.

An account that was recently created and has no transactions is found: an association block that restricts the association is a branch of the `or`, so it does not remove the entities without the association. A block outside an `or`, a block without criteria, and the only branch of an `or` still require the association.


==== Querying with Projections

Expand Down
Loading