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

Make use of sub-queries, to get rid of most apoc calls. #222

Merged
merged 6 commits into from
Nov 11, 2021
Merged
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
4 changes: 4 additions & 0 deletions core/src/main/kotlin/org/neo4j/graphql/ExtensionFunctions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package org.neo4j.graphql

import graphql.language.Description
import graphql.language.VariableReference
import graphql.schema.GraphQLOutputType
import org.neo4j.cypherdsl.core.*
import java.util.*

Expand All @@ -17,6 +18,9 @@ fun queryParameter(value: Any?, vararg parts: String?): Parameter<*> {
return org.neo4j.cypherdsl.core.Cypher.parameter(name).withValue(value?.toJavaValue())
}

fun Expression.collect(type: GraphQLOutputType) = if (type.isList()) Functions.collect(this) else this
fun StatementBuilder.OngoingReading.withSubQueries(subQueries: List<Statement>) = subQueries.fold(this, { it, sub -> it.call(sub) })

fun normalizeName(vararg parts: String?) = parts.mapNotNull { it?.capitalize() }.filter { it.isNotBlank() }.joinToString("").decapitalize()
//fun normalizeName(vararg parts: String?) = parts.filterNot { it.isNullOrBlank() }.joinToString("_")

Expand Down
17 changes: 12 additions & 5 deletions core/src/main/kotlin/org/neo4j/graphql/GraphQLExtensions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import org.neo4j.graphql.DirectiveConstants.Companion.PROPERTY_NAME
import org.neo4j.graphql.DirectiveConstants.Companion.RELATION_NAME
import org.neo4j.graphql.DirectiveConstants.Companion.RELATION_TO
import org.neo4j.graphql.handler.projection.ProjectionBase
import org.slf4j.LoggerFactory
import java.math.BigDecimal
import java.math.BigInteger

Expand Down Expand Up @@ -157,11 +158,17 @@ fun <T> GraphQLDirective.getArgument(argumentName: String, defaultValue: T? = nu
}

fun GraphQLFieldDefinition.cypherDirective(): CypherDirective? = getDirective(CYPHER)?.let {
CypherDirective(
it.getMandatoryArgument(CYPHER_STATEMENT),
it.getMandatoryArgument(CYPHER_PASS_THROUGH, false)
)
}
val originalStatement = it.getMandatoryArgument<String>(CYPHER_STATEMENT)
// Arguments on the field are passed to the Cypher statement and can be used by name.
// They must not be prefixed by $ since they are no longer parameters. Just use the same name as the fields' argument.
val rewrittenStatement = originalStatement.replace(Regex("\\\$([_a-zA-Z]\\w*)"), "$1")
jexp marked this conversation as resolved.
Show resolved Hide resolved
if (originalStatement != rewrittenStatement) {
LoggerFactory.getLogger(CypherDirective::class.java)
jexp marked this conversation as resolved.
Show resolved Hide resolved
.warn("The field arguments used in the directives statement must not contain parameters. The statement was replaced. Please adjust your GraphQl Schema.\n\tGot : {}\n\tReplaced by: {}\n\tField : {} ({})",
originalStatement, rewrittenStatement, this.name, this.definition?.sourceLocation)
}
CypherDirective(rewrittenStatement, it.getMandatoryArgument(CYPHER_PASS_THROUGH, false))
}

data class CypherDirective(val statement: String, val passThrough: Boolean)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import graphql.schema.DataFetchingEnvironment
import graphql.schema.GraphQLObjectType
import graphql.schema.idl.TypeDefinitionRegistry
import org.neo4j.cypherdsl.core.Statement
import org.neo4j.cypherdsl.core.StatementBuilder
import org.neo4j.graphql.*

/**
Expand Down Expand Up @@ -86,11 +85,11 @@ class CreateTypeHandler private constructor(schemaConfig: SchemaConfig) : BaseDa
val node = org.neo4j.cypherdsl.core.Cypher.node(type.name, *additionalTypes.toTypedArray()).named(variable)

val properties = properties(variable, field.arguments)
val mapProjection = projectFields(node, field, type, env)
val (mapProjection, subQueries) = projectFields(node, field, type, env)

val update: StatementBuilder.OngoingUpdate = org.neo4j.cypherdsl.core.Cypher.create(node.withProperties(*properties))
return update
return org.neo4j.cypherdsl.core.Cypher.create(node.withProperties(*properties))
.with(node)
.withSubQueries(subQueries)
.returning(node.project(mapProjection).`as`(field.aliasOrName()))
.build()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@ import graphql.schema.DataFetcher
import graphql.schema.DataFetchingEnvironment
import graphql.schema.GraphQLFieldsContainer
import graphql.schema.idl.TypeDefinitionRegistry
import org.neo4j.cypherdsl.core.Functions
import org.neo4j.cypherdsl.core.Statement
import org.neo4j.graphql.*

/**
* This class handles all logic related to custom Cypher queries declared by fields with a @cypher directive
*/
class CypherDirectiveHandler(private val isQuery: Boolean, schemaConfig: SchemaConfig) : BaseDataFetcher(schemaConfig) {
class CypherDirectiveHandler(schemaConfig: SchemaConfig) : BaseDataFetcher(schemaConfig) {

class Factory(schemaConfig: SchemaConfig,
typeDefinitionRegistry: TypeDefinitionRegistry,
Expand All @@ -22,8 +21,7 @@ class CypherDirectiveHandler(private val isQuery: Boolean, schemaConfig: SchemaC

override fun createDataFetcher(operationType: OperationType, fieldDefinition: FieldDefinition): DataFetcher<Cypher>? {
fieldDefinition.cypherDirective() ?: return null
val isQuery = operationType == OperationType.QUERY
return CypherDirectiveHandler(isQuery, schemaConfig)
return CypherDirectiveHandler(schemaConfig)
}
}

Expand All @@ -33,31 +31,21 @@ class CypherDirectiveHandler(private val isQuery: Boolean, schemaConfig: SchemaC
val cypherDirective = fieldDefinition.cypherDirective()
?: throw IllegalStateException("Expect field ${env.logField()} to have @cypher directive present")

val query = if (isQuery) {
val nestedQuery = cypherDirective(variable, fieldDefinition, field, cypherDirective)
org.neo4j.cypherdsl.core.Cypher.unwind(nestedQuery).`as`(variable)
} else {
val args = cypherDirectiveQuery(variable, fieldDefinition, field, cypherDirective)

val value = org.neo4j.cypherdsl.core.Cypher.name("value")
org.neo4j.cypherdsl.core.Cypher.call("apoc.cypher.doIt")
.withArgs(*args)
.yield(value)
.with(org.neo4j.cypherdsl.core.Cypher.property(value, Functions.head(org.neo4j.cypherdsl.core.Cypher.call("keys").withArgs(value).asFunction())).`as`(variable))
}
val node = org.neo4j.cypherdsl.core.Cypher.anyNode(variable)
val readingWithWhere = if (type != null && !cypherDirective.passThrough) {
val projectionEntries = projectFields(node, field, type, env)
query.returning(node.project(projectionEntries).`as`(field.aliasOrName()))
} else {
query.returning(node.`as`(field.aliasOrName()))
}
val ordering = orderBy(node, field.arguments, fieldDefinition, env.variables)
val skipLimit = SkipLimit(variable, field.arguments, fieldDefinition)

val resultWithSkipLimit = readingWithWhere
.let { if (ordering != null) skipLimit.format(it.orderBy(*ordering.toTypedArray())) else skipLimit.format(it) }

return resultWithSkipLimit.build()
val ctxVariable = node.requiredSymbolicName
val nestedQuery = cypherDirective(ctxVariable, fieldDefinition, field, cypherDirective, null, env)

return org.neo4j.cypherdsl.core.Cypher.call(nestedQuery)
.let { reading ->
if (type == null || cypherDirective.passThrough) {
reading.returning(ctxVariable.`as`(field.aliasOrName()))
} else {
val (fieldProjection, nestedSubQueries) = projectFields(node, field, type, env)
reading
.withSubQueries(nestedSubQueries)
.returning(ctxVariable.project(fieldProjection).`as`(field.aliasOrName()))
}
}
.build()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import graphql.schema.idl.TypeDefinitionRegistry
import org.neo4j.cypherdsl.core.Node
import org.neo4j.cypherdsl.core.Relationship
import org.neo4j.cypherdsl.core.Statement
import org.neo4j.cypherdsl.core.StatementBuilder.OngoingUpdate
import org.neo4j.graphql.*

/**
Expand Down Expand Up @@ -91,12 +90,13 @@ class DeleteHandler private constructor(schemaConfig: SchemaConfig) : BaseDataFe
.where(where)
}
val deletedElement = propertyContainer.requiredSymbolicName.`as`("toDelete")
val mapProjection = projectFields(propertyContainer, field, type, env)
val (mapProjection, subQueries) = projectFields(propertyContainer, field, type, env)

val projection = propertyContainer.project(mapProjection).`as`(variable)
val update: OngoingUpdate = select.with(deletedElement, projection)
return select
.withSubQueries(subQueries)
.with(deletedElement, projection)
.detachDelete(deletedElement)
return update
.returning(projection.asName().`as`(field.aliasOrName()))
.build()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import graphql.schema.idl.TypeDefinitionRegistry
import org.neo4j.cypherdsl.core.Node
import org.neo4j.cypherdsl.core.Relationship
import org.neo4j.cypherdsl.core.Statement
import org.neo4j.cypherdsl.core.StatementBuilder.OngoingMatchAndUpdate
import org.neo4j.graphql.*

/**
Expand Down Expand Up @@ -114,12 +113,12 @@ class MergeOrUpdateHandler private constructor(private val merge: Boolean, schem
}
}
val properties = properties(variable, field.arguments)
val mapProjection = projectFields(propertyContainer, field, type, env)
val update: OngoingMatchAndUpdate = select
.mutate(propertyContainer, org.neo4j.cypherdsl.core.Cypher.mapOf(*properties))
val (mapProjection, subQueries) = projectFields(propertyContainer, field, type, env)

return update
return select
.mutate(propertyContainer, org.neo4j.cypherdsl.core.Cypher.mapOf(*properties))
.with(propertyContainer)
.withSubQueries(subQueries)
.returning(propertyContainer.project(mapProjection).`as`(field.aliasOrName()))
.build()
}
Expand Down
17 changes: 6 additions & 11 deletions core/src/main/kotlin/org/neo4j/graphql/handler/QueryHandler.kt
Original file line number Diff line number Diff line change
Expand Up @@ -121,17 +121,12 @@ class QueryHandler private constructor(schemaConfig: SchemaConfig) : BaseDataFet
match.where(where)
}

val ordering = orderBy(propertyContainer, field.arguments, fieldDefinition, env.variables)
val skipLimit = SkipLimit(variable, field.arguments, fieldDefinition)

val projectionEntries = projectFields(propertyContainer, field, type, env)
val (projectionEntries, subQueries) = projectFields(propertyContainer, field, type, env)
val mapProjection = propertyContainer.project(projectionEntries).`as`(field.aliasOrName())
val resultWithSkipLimit = ongoingReading.returning(mapProjection)
.let {
val orderedResult = ordering?.let { o -> it.orderBy(*o.toTypedArray()) } ?: it
skipLimit.format(orderedResult)
}

return resultWithSkipLimit.build()
return ongoingReading
.withSubQueries(subQueries)
.returning(mapProjection)
.skipLimitOrder(propertyContainer.requiredSymbolicName, fieldDefinition, field, env)
.build()
}
}
Loading