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

Fix issue 488 handle union where on connections #540

Merged
merged 10 commits into from
Oct 26, 2021
191 changes: 101 additions & 90 deletions packages/graphql/src/translate/create-where-and-params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,58 +141,63 @@ function createWhereAndParams({
}

if (connectionField) {
const refNode = context.neoSchema.nodes.find(
(x) => x.name === connectionField.relationship.typeMeta.name
) as Node;
const relationship = context.neoSchema.relationships.find(
(x) => x.name === connectionField.relationshipTypeName
) as Relationship;

const relationshipVariable = `${param}_${connectionField.relationshipTypeName}`;

const inStr = connectionField.relationship.direction === "IN" ? "<-" : "-";
const outStr = connectionField.relationship.direction === "OUT" ? "->" : "-";

const labels = refNode.labelString;
let nodeEntries: any = value;
danstarns marked this conversation as resolved.
Show resolved Hide resolved

if (value === null) {
res.clauses.push(
`EXISTS((${varName})${inStr}[:${connectionField.relationship.type}]${outStr}(${labels}))`
);
return res;
if (!connectionField?.relationship.union) {
nodeEntries = { [connectionField.relationship.typeMeta.name]: value };
}

const collectedMap = `${param}_map`;

let resultStr = [
`EXISTS((${varName})${inStr}[:${connectionField.relationship.type}]${outStr}(${labels}))`,
`AND NONE(${collectedMap} IN [(${varName})${inStr}[${relationshipVariable}:${connectionField.relationship.type}]${outStr}(${param}${labels})`,
` | { node: ${param}, relationship: ${relationshipVariable} } ] INNER_WHERE `,
].join(" ");

const connectionWhere = createConnectionWhereAndParams({
whereInput: value,
context,
node: refNode,
nodeVariable: `${collectedMap}.node`,
relationship,
relationshipVariable: `${collectedMap}.relationship`,
parameterPrefix: `${varName}_${context.resolveTree.name}.where.${key}`,
Object.entries(nodeEntries).forEach((entry) => {
const refNode = context.neoSchema.nodes.find((x) => x.name === entry[0]) as Node;
const relationship = context.neoSchema.relationships.find(
(x) => x.name === connectionField.relationshipTypeName
) as Relationship;

const thisParam = `${param}_${refNode.name}`;
const relationshipVariable = `${thisParam}_${connectionField.relationshipTypeName}`;
const inStr = connectionField.relationship.direction === "IN" ? "<-" : "-";
const outStr = connectionField.relationship.direction === "OUT" ? "->" : "-";
const labels = refNode.labelString;
const collectedMap = `${thisParam}_map`;

if (value === null) {
res.clauses.push(
`EXISTS((${varName})${inStr}[:${connectionField.relationship.type}]${outStr}(${labels}))`
);
return res;
}

let resultStr = [
`EXISTS((${varName})${inStr}[:${connectionField.relationship.type}]${outStr}(${labels}))`,
`AND NONE(${collectedMap} IN [(${varName})${inStr}[${relationshipVariable}:${connectionField.relationship.type}]${outStr}(${thisParam}${labels})`,
` | { node: ${thisParam}, relationship: ${relationshipVariable} } ] INNER_WHERE `,
].join(" ");

const connectionWhere = createConnectionWhereAndParams({
whereInput: entry[1] as any,
context,
node: refNode,
nodeVariable: `${collectedMap}.node`,
relationship,
relationshipVariable: `${collectedMap}.relationship`,
parameterPrefix: `${varName}_${context.resolveTree.name}.where.${key}`,
});

resultStr += connectionWhere[0];
resultStr += ")"; // close ALL
res.clauses.push(resultStr);
res.params = {
...res.params,
...(recursing
? {
[`${varName}_${context.resolveTree.name}`]: {
danstarns marked this conversation as resolved.
Show resolved Hide resolved
where: { [`${connectionField.fieldName}_NOT`]: connectionWhere[1] },
},
}
: { [`${varName}_${context.resolveTree.name}`]: context.resolveTree.args }),
};
});

resultStr += connectionWhere[0];
resultStr += ")"; // close ALL
res.clauses.push(resultStr);
res.params = {
...res.params,
...(recursing
? {
[`${varName}_${context.resolveTree.name}`]: {
where: { [`${connectionField.fieldName}_NOT`]: connectionWhere[1] },
},
}
: { [`${varName}_${context.resolveTree.name}`]: context.resolveTree.args }),
};
return res;
}

Expand Down Expand Up @@ -348,58 +353,64 @@ function createWhereAndParams({

const equalityConnection = node.connectionFields?.find((x) => key === x.fieldName);
if (equalityConnection) {
const refNode = context.neoSchema.nodes.find(
(x) => x.name === equalityConnection.relationship.typeMeta.name
) as Node;
const relationship = context.neoSchema.relationships.find(
(x) => x.name === equalityConnection.relationshipTypeName
) as Relationship;
let nodeEntries: any = value;
danstarns marked this conversation as resolved.
Show resolved Hide resolved

if (!equalityConnection?.relationship.union) {
nodeEntries = { [equalityConnection.relationship.typeMeta.name]: value };
}

const relationshipVariable = `${param}_${equalityConnection.relationshipTypeName}`;
Object.entries(nodeEntries).forEach((entry) => {
const refNode = context.neoSchema.nodes.find((x) => x.name === entry[0]) as Node;
const relationship = context.neoSchema.relationships.find(
(x) => x.name === equalityConnection.relationshipTypeName
) as Relationship;

const inStr = equalityConnection.relationship.direction === "IN" ? "<-" : "-";
const outStr = equalityConnection.relationship.direction === "OUT" ? "->" : "-";
const thisParam = `${param}_${refNode.name}`;
const relationshipVariable = `${thisParam}_${equalityConnection.relationshipTypeName}`;
const inStr = equalityConnection.relationship.direction === "IN" ? "<-" : "-";
const outStr = equalityConnection.relationship.direction === "OUT" ? "->" : "-";
const labels = refNode.labelString;
const collectedMap = `${thisParam}_map`;

const labels = refNode.labelString;
if (value === null) {
res.clauses.push(
`NOT EXISTS((${varName})${inStr}[:${equalityConnection.relationship.type}]${outStr}(${labels}))`
);

if (value === null) {
res.clauses.push(
`NOT EXISTS((${varName})${inStr}[:${equalityConnection.relationship.type}]${outStr}(${labels}))`
);
return res;
}
return res;
}

const collectedMap = `${param}_map`;
let resultStr = [
`EXISTS((${varName})${inStr}[:${equalityConnection.relationship.type}]${outStr}(${labels}))`,
`AND ANY(${collectedMap} IN [(${varName})${inStr}[${relationshipVariable}:${equalityConnection.relationship.type}]${outStr}(${thisParam}${labels})`,
` | { node: ${thisParam}, relationship: ${relationshipVariable} } ] INNER_WHERE `,
].join(" ");

let resultStr = [
`EXISTS((${varName})${inStr}[:${equalityConnection.relationship.type}]${outStr}(${labels}))`,
`AND ANY(${collectedMap} IN [(${varName})${inStr}[${relationshipVariable}:${equalityConnection.relationship.type}]${outStr}(${param}${labels})`,
` | { node: ${param}, relationship: ${relationshipVariable} } ] INNER_WHERE `,
].join(" ");
const connectionWhere = createConnectionWhereAndParams({
whereInput: entry[1] as any,
context,
node: refNode,
nodeVariable: `${collectedMap}.node`,
relationship,
relationshipVariable: `${collectedMap}.relationship`,
parameterPrefix: `${varName}_${context.resolveTree.name}.where.${key}`,
});

const connectionWhere = createConnectionWhereAndParams({
whereInput: value,
context,
node: refNode,
nodeVariable: `${collectedMap}.node`,
relationship,
relationshipVariable: `${collectedMap}.relationship`,
parameterPrefix: `${varName}_${context.resolveTree.name}.where.${key}`,
resultStr += connectionWhere[0];
resultStr += ")"; // close ALL
res.clauses.push(resultStr);
res.params = {
...res.params,
...(recursing
? {
[`${varName}_${context.resolveTree.name}`]: {
where: { [equalityConnection.fieldName]: connectionWhere[1] },
},
}
: { [`${varName}_${context.resolveTree.name}`]: context.resolveTree.args }),
};
});

resultStr += connectionWhere[0];
resultStr += ")"; // close ALL
res.clauses.push(resultStr);
res.params = {
...res.params,
...(recursing
? {
[`${varName}_${context.resolveTree.name}`]: {
where: { [equalityConnection.fieldName]: connectionWhere[1] },
},
}
: { [`${varName}_${context.resolveTree.name}`]: context.resolveTree.args }),
};
return res;
}

Expand Down
139 changes: 139 additions & 0 deletions packages/graphql/tests/integration/issues/488.int.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
/*
* 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 { Driver } from "neo4j-driver";
import { graphql } from "graphql";
import { gql } from "apollo-server";
import { generate } from "randomstring";
import neo4j from "../neo4j";
import { Neo4jGraphQL } from "../../../src/classes";

describe("https://github.com/neo4j/graphql/issues/488", () => {
let driver: Driver;

beforeAll(async () => {
driver = await neo4j();
});

afterAll(async () => {
await driver.close();
});

test("should return correct data based on issue", async () => {
const session = driver.session();

const typeDefs = gql`
type Journalist {
id: ID!
keywords: [Keyword]! @relationship(type: "HAS_KEYWORD", direction: OUT)
}

union Keyword = Emoji | Hashtag | Text

type Emoji {
id: ID! @id
type: String!
}

type Hashtag {
id: ID! @id
type: String!
}

type Text {
id: ID! @id
type: String!
}
`;

const neoSchema = new Neo4jGraphQL({ typeDefs });

const journalistId = generate({
charset: "alphabetic",
});

const emojiId = generate({
charset: "alphabetic",
});

const emojiType = "Smile";

const query = `
query Query($journalistsWhere: JournalistWhere) {
journalists(where: $journalistsWhere) {
id
keywords {
... on Emoji {
id
type
}
}
}
}
`;

const variableValues = {
journalistsWhere: {
id: journalistId,
keywordsConnection: {
Emoji: {
node: {
type: emojiType,
},
},
},
},
};

try {
await session.run(`
CREATE (j:Journalist { id: "${journalistId}" })-[:HAS_KEYWORD]->(:Emoji { id: "${emojiId}", type: "${emojiType}" })
danstarns marked this conversation as resolved.
Show resolved Hide resolved
`);

const result = await graphql({
schema: neoSchema.schema,
source: query,
contextValue: { driver },
variableValues,
});

if (result.errors) {
console.log(JSON.stringify(result.errors, null, 2));
}

expect(result.errors).toBeFalsy();

expect(result.data as any).toEqual({
journalists: [
{
id: journalistId,
keywords: [
{
id: emojiId,
type: emojiType,
},
],
},
],
});
} finally {
await session.close();
}
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -666,9 +666,7 @@ RETURN this { .actorCount } as this

```cypher
MATCH (this:Movie)
WHERE EXISTS((this)-[:IN_GENRE]->(:Genre))
AND ANY(this_genresConnection_map IN [(this)-[this_genresConnection_MovieGenresRelationship:IN_GENRE]->(this_genresConnection:Genre) | { node: this_genresConnection, relationship: this_genresConnection_MovieGenresRelationship } ]
WHERE this_genresConnection_map.node.name = $this_movies.where.genresConnection.node.name)
WHERE EXISTS((this)-[:IN_GENRE]->(:Genre)) AND ANY(this_genresConnection_Genre_map IN [(this)-[this_genresConnection_Genre_MovieGenresRelationship:IN_GENRE]->(this_genresConnection_Genre:Genre) | { node: this_genresConnection_Genre, relationship: this_genresConnection_Genre_MovieGenresRelationship } ] WHERE this_genresConnection_Genre_map.node.name = $this_movies.where.genresConnection.node.name)
RETURN this { .actorCount } as this
```

Expand Down Expand Up @@ -706,9 +704,7 @@ RETURN this { .actorCount } as this

```cypher
MATCH (this:Movie)
WHERE EXISTS((this)-[:IN_GENRE]->(:Genre))
AND NONE(this_genresConnection_NOT_map IN [(this)-[this_genresConnection_NOT_MovieGenresRelationship:IN_GENRE]->(this_genresConnection_NOT:Genre) | { node: this_genresConnection_NOT, relationship: this_genresConnection_NOT_MovieGenresRelationship } ]
WHERE this_genresConnection_NOT_map.node.name = $this_movies.where.genresConnection_NOT.node.name)
WHERE EXISTS((this)-[:IN_GENRE]->(:Genre)) AND NONE(this_genresConnection_NOT_Genre_map IN [(this)-[this_genresConnection_NOT_Genre_MovieGenresRelationship:IN_GENRE]->(this_genresConnection_NOT_Genre:Genre) | { node: this_genresConnection_NOT_Genre, relationship: this_genresConnection_NOT_Genre_MovieGenresRelationship } ] WHERE this_genresConnection_NOT_Genre_map.node.name = $this_movies.where.genresConnection_NOT.node.name)
RETURN this { .actorCount } as this
```

Expand Down
Loading