Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(7.x) Cypher filtering many to many relationships #5858

Merged
merged 4 commits into from
Nov 29, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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 @@ -126,7 +126,7 @@ export class AttributeAdapter {
(this.typeHelper.isEnum() ||
this.typeHelper.isSpatial() ||
this.typeHelper.isScalar() ||
(this.isCypherRelationshipField() && !this.typeHelper.isList())) &&
this.isCypherRelationshipField()) &&
this.isFilterable() &&
!this.isCustomResolvable()
);
Expand Down
60 changes: 56 additions & 4 deletions packages/graphql/src/schema/get-where-fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,44 @@ import { ConcreteEntityAdapter } from "../schema-model/entity/model-adapters/Con
import type { Neo4jFeaturesSettings } from "../types";
import { graphqlDirectivesToCompose } from "./to-compose";

function addCypherListFieldFilters({
field,
type,
result,
deprecatedDirectives,
}: {
field: AttributeAdapter;
type: string;
result: Record<
string,
{
type: string;
directives: Directive[];
}
>;
deprecatedDirectives: Directive[];
}) {
result[`${field.name}_ALL`] = {
type,
directives: deprecatedDirectives,
};

result[`${field.name}_NONE`] = {
type,
directives: deprecatedDirectives,
};

result[`${field.name}_SINGLE`] = {
type,
directives: deprecatedDirectives,
};

result[`${field.name}_SOME`] = {
type,
directives: deprecatedDirectives,
};
}

// TODO: refactoring needed!
// isWhereField, isFilterable, ... extracted out into attributes category
export function getWhereFieldsForAttributes({
Expand Down Expand Up @@ -71,10 +109,24 @@ export function getWhereFieldsForAttributes({

if (field.annotations.cypher.targetEntity) {
const targetEntityAdapter = new ConcreteEntityAdapter(field.annotations.cypher.targetEntity);
result[field.name] = {
type: targetEntityAdapter.operations.whereInputTypeName,
directives: deprecatedDirectives,
};
const type = targetEntityAdapter.operations.whereInputTypeName;

// Add list where field filters (e.g. name_ALL, name_NONE, name_SINGLE, name_SOME)
if (field.typeHelper.isList()) {
addCypherListFieldFilters({
field,
type,
result,
deprecatedDirectives,
});
} else {
// Add base where field filter (e.g. name)
result[field.name] = {
type,
directives: deprecatedDirectives,
};
}

continue;
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed 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
*
* http://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.
*/

import Cypher from "@neo4j/cypher-builder";
import type { AttributeAdapter } from "../../../../schema-model/attribute/model-adapters/AttributeAdapter";
import type { QueryASTContext } from "../QueryASTContext";
import type { QueryASTNode } from "../QueryASTNode";
import type { CustomCypherSelection } from "../selection/CustomCypherSelection";
import type { FilterOperator, RelationshipWhereOperator } from "./Filter";
import { Filter } from "./Filter";

export class CypherRelationshipFilter extends Filter {
private returnVariable: Cypher.Node;
private attribute: AttributeAdapter;
private selection: CustomCypherSelection;
private operator: FilterOperator;
private targetNodeFilters: Filter[] = [];
private isNot: boolean;

constructor({
selection,
attribute,
operator,
isNot,
returnVariable,
}: {
selection: CustomCypherSelection;
attribute: AttributeAdapter;
operator: RelationshipWhereOperator;
isNot: boolean;
returnVariable: Cypher.Node;
}) {
super();
this.selection = selection;
this.attribute = attribute;
this.isNot = isNot;
this.operator = operator;
this.returnVariable = returnVariable;
}

public getChildren(): QueryASTNode[] {
return [...this.targetNodeFilters, this.selection];
}

public addTargetNodeFilter(...filter: Filter[]): void {
this.targetNodeFilters.push(...filter);
}

public print(): string {
return `${super.print()} [${this.attribute.name}] <${this.isNot ? "NOT " : ""}${this.operator}>`;
}

public getSubqueries(context: QueryASTContext): Cypher.Clause[] {
const { selection, nestedContext } = this.selection.apply(context);

const cypherSubquery = selection.return([Cypher.collect(nestedContext.returnVariable), this.returnVariable]);

return [cypherSubquery];
}

public getPredicate(queryASTContext: QueryASTContext): Cypher.Predicate | undefined {
const context = queryASTContext.setTarget(this.returnVariable);

const predicate = this.createRelationshipOperation(context);
if (predicate) {
return this.wrapInNotIfNeeded(predicate);
}
}

private createRelationshipOperation(queryASTContext: QueryASTContext): Cypher.Predicate | undefined {
const x = new Cypher.Node();
const context = queryASTContext.setTarget(x);
const targetNodePredicates = this.targetNodeFilters.map((c) => c.getPredicate(context));
const innerPredicate = Cypher.and(...targetNodePredicates);

if (!innerPredicate) {
return;
}

switch (this.operator) {
case "ALL": {
return Cypher.all(x, this.returnVariable, innerPredicate);
}
case "SINGLE": {
return Cypher.single(x, this.returnVariable, innerPredicate);
}
case "NONE": {
return Cypher.none(x, this.returnVariable, innerPredicate);
}
case "SOME": {
return Cypher.any(x, this.returnVariable, innerPredicate);
}
}
}

private wrapInNotIfNeeded(predicate: Cypher.Predicate): Cypher.Predicate {
// TODO: Remove check for NONE when isNot is removed
if (this.isNot && this.operator !== "NONE") {
return Cypher.not(predicate);
}

return predicate;
}
}
30 changes: 24 additions & 6 deletions packages/graphql/src/translate/queryAST/factory/FilterFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { asArray, filterTruthy } from "../../../utils/utils";
import { isLogicalOperator } from "../../utils/logical-operators";
import { ConnectionFilter } from "../ast/filters/ConnectionFilter";
import { CypherOneToOneRelationshipFilter } from "../ast/filters/CypherOneToOneRelationshipFilter";
import { CypherRelationshipFilter } from "../ast/filters/CypherRelationshipFilter";
import type { Filter, FilterOperator, RelationshipWhereOperator } from "../ast/filters/Filter";
import { isRelationshipOperator } from "../ast/filters/Filter";
import { LogicalFilter } from "../ast/filters/LogicalFilter";
Expand Down Expand Up @@ -333,28 +334,33 @@ export class FilterFactory {
}

const filteredEntities = getConcreteEntities(target, where);
const cypherOneToOneRelationshipFilters: CypherOneToOneRelationshipFilter[] = [];
const filters: (CypherOneToOneRelationshipFilter | CypherRelationshipFilter)[] = [];
for (const concreteEntity of filteredEntities) {
const returnVariable = new Cypher.Node();
const cypherOneToOneRelationshipFilter = this.createCypherOneToOneRelationshipFilterTreeNode({

const options = {
selection,
isNot: filterOps.isNot,
isNull,
operator: filterOps.operator || "SOME",
attribute,
returnVariable,
});
};

const filter = attribute.typeHelper.isList()
? this.createCypherRelationshipFilterTreeNode(options)
: this.createCypherOneToOneRelationshipFilterTreeNode(options);

if (!isNull) {
const entityWhere = where[concreteEntity.name] ?? where;
const targetNodeFilters = this.createNodeFilters(concreteEntity, entityWhere);
cypherOneToOneRelationshipFilter.addTargetNodeFilter(...targetNodeFilters);
filter.addTargetNodeFilter(...targetNodeFilters);
}

cypherOneToOneRelationshipFilters.push(cypherOneToOneRelationshipFilter);
filters.push(filter);
}
const logicalOp = this.getLogicalOperatorForRelatedNodeFilters(target, filterOps.operator);
return this.wrapMultipleFiltersInLogical(cypherOneToOneRelationshipFilters, logicalOp);
return this.wrapMultipleFiltersInLogical(filters, logicalOp);
}

// This allows to override this creation in AuthFilterFactory
Expand All @@ -369,6 +375,18 @@ export class FilterFactory {
return new CypherOneToOneRelationshipFilter(options);
}

// This allows to override this creation in AuthFilterFactory
protected createCypherRelationshipFilterTreeNode(options: {
selection: CustomCypherSelection;
attribute: AttributeAdapter;
isNot: boolean;
isNull: boolean;
operator: RelationshipWhereOperator;
returnVariable: Cypher.Node;
}): CypherRelationshipFilter {
return new CypherRelationshipFilter(options);
}

// This allows to override this creation in AuthFilterFactory
protected createRelationshipFilterTreeNode(options: {
relationship: RelationshipAdapter;
Expand Down
Loading
Loading