Skip to content

Commit

Permalink
Merge pull request #5856 from mjfwebb/6x-cypher-filtering-relationships
Browse files Browse the repository at this point in the history
(6.x) Cypher filtering many to many relationships
  • Loading branch information
mjfwebb authored Nov 29, 2024
2 parents 3ba3c35 + 2425b21 commit 7411910
Show file tree
Hide file tree
Showing 13 changed files with 3,527 additions and 19 deletions.
5 changes: 5 additions & 0 deletions .changeset/red-hairs-decide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@neo4j/graphql": minor
---

Add filtering on many to many relationship custom cypher fields
34 changes: 23 additions & 11 deletions packages/graphql/src/schema-model/generate-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ import type { Operations } from "./Neo4jGraphQLSchemaModel";
import { Neo4jGraphQLSchemaModel } from "./Neo4jGraphQLSchemaModel";
import { Operation } from "./Operation";
import type { Attribute } from "./attribute/Attribute";
import { ObjectType } from "./attribute/AttributeType";
import type { AttributeType } from "./attribute/AttributeType";
import { ListType, ObjectType } from "./attribute/AttributeType";
import type { CompositeEntity } from "./entity/CompositeEntity";
import { ConcreteEntity } from "./entity/ConcreteEntity";
import type { Entity } from "./entity/Entity";
Expand Down Expand Up @@ -131,20 +132,31 @@ function addCompositeEntitiesToConcreteEntity(compositeEntities: CompositeEntity
});
}

function getCypherTarget(schema: Neo4jGraphQLSchemaModel, attributeType: AttributeType): ConcreteEntity | undefined {
if (attributeType instanceof ListType) {
return getCypherTarget(schema, attributeType.ofType);
}
if (attributeType instanceof ObjectType) {
const foundConcreteEntity = schema.getConcreteEntity(attributeType.name);
if (!foundConcreteEntity) {
throw new Neo4jGraphQLSchemaValidationError(
`@cypher field must target type annotated with the @node directive${attributeType.name}, `
);
}
return schema.getConcreteEntity(attributeType.name);
}
if (attributeType instanceof InterfaceEntity || attributeType instanceof UnionEntity) {
throw new Error("@cypher field target cannot be an interface or an union");
}
}

// TODO: currently the below is used only for Filtering purposes, and therefore the target is set only for ObjectTypes but in the future we might want to use it for other types as well
function hydrateCypherAnnotations(schema: Neo4jGraphQLSchemaModel, concreteEntities: ConcreteEntity[]) {
for (const concreteEntity of concreteEntities) {
for (const attributeField of concreteEntity.attributes.values()) {
if (attributeField.annotations.cypher) {
if (attributeField.type instanceof ObjectType) {
const foundConcreteEntity = schema.getConcreteEntity(attributeField.type.name);
if (!foundConcreteEntity) {
throw new Neo4jGraphQLSchemaValidationError(
`Could not find concrete entity with name ${attributeField.type.name}`
);
}

attributeField.annotations.cypher.targetEntity = foundConcreteEntity;
}
const target = getCypherTarget(schema, attributeField.type);
attributeField.annotations.cypher.targetEntity = target;
}
}
}
Expand Down
54 changes: 53 additions & 1 deletion packages/graphql/src/schema/get-where-fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,44 @@ import { DEPRECATE_IMPLICIT_EQUAL_FILTERS } from "./constants";
import { shouldAddDeprecatedFields } from "./generation/utils";
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 @@ -73,10 +111,24 @@ export function getWhereFieldsForAttributes({

if (field.annotations.cypher.targetEntity) {
const targetEntityAdapter = new ConcreteEntityAdapter(field.annotations.cypher.targetEntity);
const type = targetEntityAdapter.operations.whereInputTypeName;

// Always add base where field filter (e.g. name)
result[field.name] = {
type: targetEntityAdapter.operations.whereInputTypeName,
type,
directives: deprecatedDirectives,
};

// Add list where field filters (e.g. name_ALL, name_NONE, name_SINGLE, name_SOME)
if (field.typeHelper.isList()) {
addCypherListFieldFilters({
field,
type,
result,
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

0 comments on commit 7411910

Please sign in to comment.