Skip to content

Update API to latest version of neo4j-graphql #329

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

Merged
merged 2 commits into from
Jan 14, 2025
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
4 changes: 2 additions & 2 deletions .run/AsciidocReformater.run.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="org.neo4j.graphql.tools.AsciidocReformater" type="JetRunConfigurationType" nameIsGenerated="true">
<configuration default="false" name="AsciidocReformater" type="JetRunConfigurationType" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="org.neo4j.graphql.tools.AsciidocReformater" />
<module name="neo4j-graphql-java" />
<shortenClasspath name="NONE" />
Expand All @@ -8,4 +8,4 @@
<option name="Make" enabled="true" />
</method>
</configuration>
</component>
</component>
11 changes: 11 additions & 0 deletions .run/JsTemplateDeleter.run.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="JsTemplateDeleter" type="JetRunConfigurationType" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="org.neo4j.graphql.tools.JsTemplateDeleter" />
<module name="neo4j-graphql-java" />
<shortenClasspath name="NONE" />
<option name="WORKING_DIRECTORY" value="$MODULE_WORKING_DIR$" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
</component>
4 changes: 2 additions & 2 deletions .run/JsTestCaseSync.run.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="org.neo4j.graphql.tools.JsTestCaseSync" type="JetRunConfigurationType" nameIsGenerated="true">
<configuration default="false" name="JsTestCaseSync" type="JetRunConfigurationType" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="org.neo4j.graphql.tools.JsTestCaseSync" />
<module name="neo4j-graphql-java" />
<shortenClasspath name="NONE" />
Expand All @@ -8,4 +8,4 @@
<option name="Make" enabled="true" />
</method>
</configuration>
</component>
</component>
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ object EnglischInflector : English() {
workaround_irregular("person", "people")
// TODO
workaround_irregular("two", "twos")
workaround_irregular("aircraft", "aircraft")
}

private fun workaround_irregular(singular: String, plural: String) {
Expand Down
4 changes: 1 addition & 3 deletions core/src/main/kotlin/org/neo4j/graphql/Constants.kt
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ object Constants {
const val CURSOR_FIELD = "cursor"
const val NODE_FIELD = "node"
const val RELATIONSHIP_FIELD = "relationship"
const val TYPENAME_IN = "typename_IN"
const val TYPENAME_IN = "typename"

const val RESOLVE_TYPE = TYPE_NAME
const val RESOLVE_ID = "__id"
Expand Down Expand Up @@ -60,7 +60,6 @@ object Constants {
RelationshipDirective.NAME,
)

const val OPTIONS = "options"
const val WHERE = "where"

object Types {
Expand All @@ -71,7 +70,6 @@ object Constants {
val Boolean = TypeName("Boolean")

val PageInfo = TypeName("PageInfo")
val QueryOptions = TypeName("QueryOptions")
val SortDirection = TypeName("SortDirection")
val PointDistance = TypeName("PointDistance")
val CartesianPointDistance = TypeName("CartesianPointDistance")
Expand Down
30 changes: 19 additions & 11 deletions core/src/main/kotlin/org/neo4j/graphql/QueryContext.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,27 @@ data class QueryContext @JvmOverloads constructor(
private var paramKeysPerValues = mutableMapOf<String, MutableMap<Any?, Parameter<*>>>()

fun resolve(string: String): String {
return contextParams?.let { params ->
CONTEXT_VARIABLE_PATTERN.replace(string) {
val path = it.groups[1] ?: it.groups[2] ?: throw IllegalStateException("expected a group")
val parts = path.value.split(".")
var o: Any = params
for (part in parts) {
if (o is Map<*, *>) {
o = o[part] ?: return@replace ""
return CONTEXT_VARIABLE_PATTERN.replace(string) {
val path = it.groups[1] ?: it.groups[2] ?: throw IllegalStateException("expected a group")
val parts = path.value.split(".")
var o: Any? = null
for ((index, part) in parts.withIndex()) {
if (index == 0) {
if (part == "context") {
o = contextParams
continue
} else {
TODO("only maps are currently supported")
TODO("query context does not provide a `$part`")
}
}
return@replace o.toString()
if (o is Map<*, *>) {
o = o[part] ?: return@replace ""
} else {
TODO("only maps are currently supported")
}
}
} ?: string
return@replace o.toString()
}
}

fun getNextVariable(relationField: RelationField) = getNextVariable(
Expand Down Expand Up @@ -61,6 +67,8 @@ data class QueryContext @JvmOverloads constructor(
const val KEY = "Neo4jGraphQLQueryContext"

private const val PATH_PATTERN = "([a-zA-Z_][a-zA-Z_0-9]*(?:.[a-zA-Z_][a-zA-Z_0-9]*)*)"

// matches ${path} or $path
private val CONTEXT_VARIABLE_PATTERN = Regex("\\\$(?:\\{$PATH_PATTERN}|$PATH_PATTERN)")
}
}
4 changes: 2 additions & 2 deletions core/src/main/kotlin/org/neo4j/graphql/domain/Node.kt
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,15 @@ class Node(
}

fun asCypherNode(queryContext: QueryContext?, name: String? = null) =
Cypher.node(mainLabel, additionalLabels(queryContext)).let {
Cypher.node(mapLabelWithContext(mainLabel, queryContext), additionalLabels(queryContext)).let {
when {
name != null -> it.named(name)
else -> it
}
}

fun asCypherNode(queryContext: QueryContext?, name: SymbolicName) =
Cypher.node(mainLabel, additionalLabels(queryContext)).named(name)
Cypher.node(mapLabelWithContext(mainLabel, queryContext), additionalLabels(queryContext)).named(name)

}

Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ object NodeFactory {
val schemeDirectives =
typeDefinitionRegistry.schemaExtensionDefinitions?.map { it.directives }?.flatten() ?: emptyList()
val annotations = Annotations(schemeDirectives + definition.directives, typeDefinitionRegistry, definition.name)
if (annotations.relationshipProperties != null) {
if (annotations.node == null || annotations.relationshipProperties != null) {
return null
}
val interfaces = definition.implements.mapNotNull { interfaceFactory(it.name()) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class RelationshipDirective private constructor(

val queryDirection =
directive.readArgument(RelationshipDirective::queryDirection) { RelationField.QueryDirection.valueOf((it as EnumValue).name) }
?: RelationField.QueryDirection.DEFAULT_DIRECTED
?: RelationField.QueryDirection.DIRECTED

return RelationshipDirective(direction, type, properties, queryDirection)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,13 @@ class PointField(
override val predicateDefinitions: Map<String, ScalarPredicateDefinition> = initPredicates()
override val whereType
get() = when (coordinateType) {
CoordinateType.GEOGRAPHIC -> POINT_INPUT_TYPE.asType()
CoordinateType.CARTESIAN -> CARTESIAN_POINT_INPUT_TYPE.asType()
CoordinateType.GEOGRAPHIC -> TypeName(POINT_INPUT_TYPE)
CoordinateType.CARTESIAN -> TypeName(CARTESIAN_POINT_INPUT_TYPE)
}

private fun initPredicates(): Map<String, ScalarPredicateDefinition> {
val result = mutableMapOf<String, ScalarPredicateDefinition>()
.add(FieldOperator.IMPLICIT_EQUAL, deprecated = "Please use the explicit _EQ version")
.add(FieldOperator.EQUAL)
if (isList()) {
result.addIncludesResolver(FieldOperator.INCLUDES)
Expand Down Expand Up @@ -77,7 +78,7 @@ class PointField(
val paramPointArray = Cypher.listWith(p).`in`(parameter).returning(Cypher.point(p))
op.conditionCreator(property, paramPointArray)
},
type = whereType.NonNull.List
type = whereType.makeRequired(type.isRequired()).List
)
}

Expand All @@ -88,7 +89,7 @@ class PointField(
val paramPoint = Cypher.point(parameter)
op.conditionCreator(property, paramPoint)
},
type = whereType.inner()
type = whereType
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,39 +41,22 @@ class RelationField(
}

enum class QueryDirection {
DEFAULT_DIRECTED,
DEFAULT_UNDIRECTED,
DIRECTED_ONLY,
UNDIRECTED_ONLY,
DIRECTED,
UNDIRECTED,
}

fun createQueryDslRelation(
start: Node,
end: Node,
directed: Boolean?,
): Relationship {
val useDirected = when (queryDirection) {
QueryDirection.DEFAULT_DIRECTED -> directed ?: true
QueryDirection.DEFAULT_UNDIRECTED -> directed ?: false
QueryDirection.DIRECTED_ONLY -> {
check(directed == null || directed == true, { "Invalid direction in 'DIRECTED_ONLY' relationship" })
true
return when (queryDirection) {
QueryDirection.DIRECTED -> when (direction) {
Direction.IN -> end.relationshipTo(start, relationType)
Direction.OUT -> start.relationshipTo(end, relationType)
}

QueryDirection.UNDIRECTED_ONLY -> {
check(directed == null || directed == false, { "Invalid direction in 'UNDIRECTED_ONLY' relationship" })
false
}
}
if (useDirected) {
return createDslRelation(start, end)
QueryDirection.UNDIRECTED -> start.relationshipBetween(end, relationType)
}
return start.relationshipBetween(end, relationType)
}

fun createDslRelation(start: Node, end: Node, name: String? = null): Relationship = when (direction) {
Direction.IN -> end.relationshipTo(start, relationType)
Direction.OUT -> start.relationshipTo(end, relationType)
}.let { if (name != null) it.named(name) else it }

}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ abstract class ScalarField(
}

val result = mutableMapOf<String, ScalarPredicateDefinition>()
.add(FieldOperator.IMPLICIT_EQUAL, resolver, deprecated = "Please use the explicit _EQ version")
.add(FieldOperator.EQUAL, resolver)
if (fieldType == Constants.BOOLEAN) {
return result
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ sealed class ImplementingTypeNames(
) : EntityNames(name, annotations) {

val connectOrCreateWhereInputTypeName get() = "${name}ConnectOrCreateWhere"
val optionsInputTypeName get() = "${name}Options"
val sortInputTypeName get() = "${name}Sort"
override val rootTypeFieldNames get() = ImplementingTypeRootTypeFieldNames()
val rootTypeSelection get() = ImplementingTypeRootTypeSelection()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ enum class FieldOperator(
val conditionCreator: (Expression, Expression) -> Condition,
val conditionEvaluator: (Any?, Any?) -> Boolean,
) {
EQUAL("",
IMPLICIT_EQUAL("",
{ lhs, rhs -> if (rhs == Cypher.literalNull()) lhs.isNull else lhs.eq(rhs) },
{ lhs, rhs -> lhs == rhs }
),
EQUAL("EQ",
{ lhs, rhs -> if (rhs == Cypher.literalNull()) lhs.isNull else lhs.eq(rhs) },
{ lhs, rhs -> lhs == rhs }
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ enum class RelationOperator(
NONE("NONE", list = true, wrapInNotIfNeeded = { it.not() }),
SINGLE("SINGLE", list = true),
SOME("SOME", list = true),
NOT_EQUAL("NOT", list = false, wrapInNotIfNeeded = { it.not() }),
EQUAL(null, list = false);

fun createRelationCondition(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ internal abstract class BaseDataFetcher(protected val schemaConfig: SchemaConfig
}

val result = neo4jAdapter.executeQuery(query, params)
return mapResult(env, result)
}

protected abstract fun generateCypher(env: DataFetchingEnvironment): Statement

protected open fun mapResult(env: DataFetchingEnvironment, result: List<Map<String, Any?>>): Any {
return if (env.fieldDefinition.type?.isList() == true) {
result.map { it[RESULT_VARIABLE] }
} else {
Expand All @@ -47,8 +53,6 @@ internal abstract class BaseDataFetcher(protected val schemaConfig: SchemaConfig
}
}

protected abstract fun generateCypher(env: DataFetchingEnvironment): Statement

companion object {
const val RESULT_VARIABLE = "this"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import org.neo4j.graphql.schema.model.inputs.options.SortInput
import org.neo4j.graphql.schema.model.outputs.root_connection.RootNodeConnectionSelection
import org.neo4j.graphql.translate.ProjectionTranslator
import org.neo4j.graphql.translate.TopLevelMatchTranslator
import org.neo4j.graphql.utils.PagingUtils
import org.neo4j.graphql.utils.ResolveTree

/**
Expand Down Expand Up @@ -75,7 +76,7 @@ internal class ConnectionResolver private constructor(

SortInput.Companion.Augmentation
.generateSortIT(implementingType, ctx)
?.let { args += inputValue(Constants.SORT, it.List) }
?.let { args += inputValue(Constants.SORT, it.NonNull.List) }

args += inputValue(Constants.FIRST, Constants.Types.Int)
args += inputValue(Constants.AFTER, Constants.Types.String)
Expand Down Expand Up @@ -119,10 +120,6 @@ internal class ConnectionResolver private constructor(

val alias = queryContext.getNextVariable(edgesSelection.aliasOrName)


edgeSelection?.forEachField(Constants.CURSOR_FIELD) {
TODO()
}
val subQueriesBeforeSort = mutableListOf<Statement>()
val subQueriesAfterSort = mutableListOf<Statement>()

Expand Down Expand Up @@ -187,4 +184,34 @@ internal class ConnectionResolver private constructor(
.returning(Cypher.mapOf(*topProjection.toTypedArray()).`as`(RESULT_VARIABLE))
.build()
}

override fun mapResult(env: DataFetchingEnvironment, result: List<Map<String, Any?>>): Any {
val data = result.map { it[RESULT_VARIABLE] }.firstOrNull() ?: return emptyMap<String, Any>()

val resolveTree = ResolveTree.resolve(env)

val mutableData = (data as? Map<*, *>)?.toMutableMap() ?: return data

val connectionSelection = resolveTree.fieldsByTypeName[implementingType.namings.rootTypeSelection.connection]
connectionSelection?.forEachField(Constants.EDGES_FIELD) { edgesSelection ->
val edgeSelection = edgesSelection.fieldsByTypeName[implementingType.namings.rootTypeSelection.edge]

mutableData[edgesSelection.aliasOrName] = mutableData[edgesSelection.aliasOrName]?.let {
if (it !is List<*>) {
return@forEachField
}
val input = InputArguments(implementingType, resolveTree.args)
val sliceStart = (input.options.offset ?: -1) + 1

it.mapIndexed{ index, edge ->
val mutableEdge = (edge as? Map<*, *>)?.toMutableMap() ?: return@mapIndexed edge
edgeSelection?.forEachField(Constants.CURSOR_FIELD) {
mutableEdge[it.aliasOrName] = PagingUtils.createCursor(sliceStart + index)
}
mutableEdge
}
}
}
return mutableData
}
}
Loading
Loading