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
Expand Up @@ -182,29 +182,45 @@ class Neo4jQuery extends Query {
}
] as Map<Class<? extends Query.Projection>, ProjectionHandler<? extends Projection>>

/**
* A junction with no criteria is true wherever it stands, as it is on Hibernate 5: it adds no restriction in an and,
* makes the or it stands in true, and makes a negation false.
*/
private static final CypherExpression EMPTY_JUNCTION = new CypherExpression('true')

public static Map<Class<? extends Query.Criterion>, CriterionHandler<? extends Criterion>> CRITERION_HANDLERS = [
(Query.Conjunction): new CriterionHandler<Query.Conjunction>() {

@Override
@CompileStatic
CypherExpression handle(CriterionScope scope, Query.Conjunction criterion) {
if (((Query.Junction) criterion).criteria.isEmpty()) {
return EMPTY_JUNCTION
}
def inner = ((Query.Junction) criterion).criteria
.collect { Query.Criterion it -> dispatchCriterion(it, scope).toString() }
.findAll { String expression -> expression }
.join(CriterionHandler.OPERATOR_AND)
return new CypherExpression(inner ? "( $inner )" : inner)
// a junction whose children add no expression, as one that holds only an empty block, is true like one without children
return inner ? new CypherExpression("( $inner )") : EMPTY_JUNCTION
}
},
(Query.Disjunction): new CriterionHandler<Query.Disjunction>() {

@Override
@CompileStatic
CypherExpression handle(CriterionScope scope, Query.Disjunction criterion) {
if (((Query.Junction) criterion).criteria.isEmpty()) {
return EMPTY_JUNCTION
}
scope.builder.enterDisjunction()
try {
def inner = ((Query.Junction) criterion).criteria
.collect { Query.Criterion it -> dispatchCriterion(it, scope).toString() }
.findAll { String expression -> expression }

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.

or { or { child {} }; eq('name', 'orphan') } should return the orphan, because the inner junction is true. It returns nothing. The empty association is filtered out, and the junction then adds nothing, so the required child match removes the name branch. An empty junction is true. Keep that when its children add no expression.

.join(CriterionHandler.OPERATOR_OR)
return new CypherExpression(inner ? "( $inner )" : inner)
// a junction whose children add no expression, as one that holds only an empty block, is true like one without children
return inner ? new CypherExpression("( $inner )") : EMPTY_JUNCTION
} finally {
scope.builder.leaveDisjunction()
}
Expand All @@ -216,8 +232,52 @@ class Neo4jQuery extends Query {
@CompileStatic
CypherExpression handle(CriterionScope scope, Query.Negation criterion) {
List<Query.Criterion> criteria = criterion.criteria
def disjunction = new Query.Disjunction(criteria)
new CypherExpression("NOT (${dispatchCriterion(disjunction, scope)})")
if (criteria.isEmpty()) {
throw new IllegalArgumentException('Logical expression [not] must contain at least 1 expression')
}
// a block with criteria asks for a neighbour, as a join does, so its negation is a neighbour that fails them: a node
// without a neighbour is not in it. The other criteria are negated together
List<Query.Criterion> others = []
List<String> negatedBlocks = []
for (Query.Criterion child : criteria) {
if (negatesAsExistence(scope, child)) {
negatedBlocks << negatedBlock(scope, (AssociationQuery) child)
}
else {
others << child
}
}
List<String> parts = []
// a disjunction whose children add no expression is the shared true value: there is nothing to negate
CypherExpression disjunction = others.isEmpty() ? null : dispatchCriterion(new Query.Disjunction(others), scope)
String negated = disjunction == null || disjunction.is(EMPTY_JUNCTION) ? '' : disjunction.toString()
if (negated) {
parts << "NOT ($negated)".toString()
}
parts.addAll(negatedBlocks)
if (parts.isEmpty()) {
// nothing is left to negate, as in a negation of a block without criteria: Hibernate 5 refuses it
throw new IllegalArgumentException('Logical expression [not] must contain at least 1 expression')
}
new CypherExpression(parts.size() == 1 ? parts[0] : "( ${parts.join(CriterionHandler.OPERATOR_AND)} )".toString())
}

private boolean negatesAsExistence(CriterionScope scope, Query.Criterion child) {
child instanceof AssociationQuery && !((AssociationQuery) child).criteria.getCriteria().isEmpty() &&
!(((AssociationQuery) child).association instanceof Embedded) && !scope.entity.isRelationshipEntity()
}

private String negatedBlock(CriterionScope scope, AssociationQuery block) {
CriterionScope.Existence existence = scope.intoExistence(block)
scope.builder.enterDisjunction()
String conditions
try {
conditions = dispatchCriterion(block.criteria, existence.scope).toString()
}
finally {
scope.builder.leaveDisjunction()
}
"size([${existence.pattern} WHERE NOT (${conditions ?: 'true'}) | 1]) > 0".toString()
}
},
(Query.Equals): new CriterionHandler<Query.Equals>() {
Expand Down Expand Up @@ -759,14 +819,17 @@ class Neo4jQuery extends Query {
if (scope.entity.isRelationshipEntity()) {
return dispatchCriterion(criterion.criteria, scope.forEnd(association))
}
if (scope.builder.inDisjunction) {
if (scope.builder.inDisjunction && !criterion.criteria.getCriteria().isEmpty()) {

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.

Other has no parent. or { parent { and {} }; eq('name', 'Other') } should match nothing, the same as parent {}. It returns Root and Other, because the empty and is treated as a branch. not { parent {} } used to find folders without a parent and now fails to parse. An empty junction adds nothing. A negated empty association still asks for the neighbour.

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.

not { parent {} } used to find folders without a parent. It now fails to parse, because the association adds a match and then an empty expression, and the negation wraps that as NOT (). not { child { or {} } } returns the orphan instead of nothing. An empty junction is true. A negated empty association still asks for the neighbour, and the query has to parse.

// a block in a disjunction is true for a node that has a matching neighbour, and false for one that
// has none, so the other branches still see the nodes without; a match would drop them first
// has none, so the other branches still see the nodes without; a match would drop them first.
// A block without criteria is no branch: it keeps the match, so it still asks for a neighbour.
CriterionScope.Existence existence = scope.intoExistence(criterion)
String conditions = dispatchCriterion(criterion.criteria, existence.scope).toString()
return new CypherExpression("size([${existence.pattern}${conditions ? ' WHERE ' + conditions : ''} | 1]) > 0".toString())
}
return dispatchCriterion(criterion.criteria, scope.into(criterion))
CypherExpression conditions = dispatchCriterion(criterion.criteria, scope.into(criterion))
// a block without criteria keeps the match but adds no condition: its empty conjunction is not a branch
return criterion.criteria.getCriteria().isEmpty() ? new CypherExpression('') : conditions
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* 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.apache.grails.data.neo4j.core.Neo4jGormDatastoreSpec
import spock.lang.Issue

/**
* A junction without criteria adds nothing to the Cypher, and a block without criteria inside an or still asks for an
* associated node, as it does on the datastores that join.
*/
@Issue('14635')
class EmptyJunctionSpec extends Neo4jGormDatastoreSpec {

void setupSpec() {
manager.registerDomainClasses(NullTestFolder)
}

private void seed() {
NullTestFolder other = new NullTestFolder(name: 'Other').save(flush: true, failOnError: true)
new NullTestFolder(name: 'Root', parent: other).save(flush: true, failOnError: true)
NullTestFolder.withSession { it.clear() }
}

void "an empty or beside a property adds nothing"() {
given:
seed()

when:
List<NullTestFolder> folders = NullTestFolder.createCriteria().list {
or {}
eq('name', 'Root')
}

then:
folders*.name == ['Root']
}

void "an empty and beside a property adds nothing"() {
given:
seed()

when:
List<NullTestFolder> folders = NullTestFolder.createCriteria().list {
and {}
eq('name', 'Root')
}

then:
folders*.name == ['Root']
}

void "an empty or alone matches every node"() {
given:
seed()

when:
List<NullTestFolder> folders = NullTestFolder.createCriteria().list { or {} }

then:
folders*.name.sort() == ['Other', 'Root']
}

void "an empty association block in an or still requires an associated node"() {
given:
seed()

when:
List<NullTestFolder> folders = NullTestFolder.createCriteria().list {
or {
parent {}
eq('name', 'Other')
}
}

then: 'the block adds no branch, and the node without a parent is left out'
folders.isEmpty()
}
}
Loading