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

Flatten result lists as late as possible. #826

Merged
merged 1 commit into from
Aug 26, 2020
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
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@
*/
package org.neo4j.ogm.result.adapter;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import org.neo4j.ogm.response.model.NodeModel;
import org.neo4j.ogm.response.model.RelationshipModel;
Expand All @@ -43,12 +44,7 @@ public Map<String, Object> adapt(Map<String, Object> result) {
for (Map.Entry<String, Object> entry : result.entrySet()) {
Object value = entry.getValue();
if (value instanceof Collection) {
Collection<Object> adaptedValues = new ArrayList<>();
Collection<Object> values = (List) value;
for (Object element : values) {
handleAdaptedValue(adaptedValues, processData(element));
}
adaptedResults.put(entry.getKey(), adaptedValues);
adaptedResults.put(entry.getKey(), ((Collection) value).stream().map(this::processData).collect(Collectors.toList()));
} else {
adaptedResults.put(entry.getKey(), processData(value));
}
Expand All @@ -57,20 +53,6 @@ public Map<String, Object> adapt(Map<String, Object> result) {
return adaptedResults;
}

/**
* Not public API, for internal use only.
* @param adaptedValues already prepared values
* @param newValue new value to prepare
*/
public static void handleAdaptedValue(Collection<Object> adaptedValues, Object newValue) {

if (newValue instanceof Collection) {
adaptedValues.addAll((Collection<?>) newValue);
} else {
adaptedValues.add(newValue);
}
}

/**
* Not public API, for internal use only.
* @param element Element that maybe is a collection
Expand All @@ -80,12 +62,7 @@ public static void handleAdaptedValue(Collection<Object> adaptedValues, Object n
public static Object handlePossibleCollections(Object element, Function<Object, Object> mappingFunction) {

if (element instanceof Iterable) {
List<Object> adaptedValues = new ArrayList<>();
Iterable collection = (Iterable) element;
for (Object nestedElement : collection) {
handleAdaptedValue(adaptedValues, mappingFunction.apply(nestedElement));
}
return adaptedValues;
return StreamSupport.stream(((Iterable) element).spliterator(), false).map(mappingFunction).collect(Collectors.toList());
}
return element;
}
Expand Down
45 changes: 29 additions & 16 deletions core/src/main/java/org/neo4j/ogm/context/RestModelMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -179,13 +179,23 @@ void handle(String alias, Object resultObject) {
} else if (resultObject instanceof List) {
// Mark that result object as list, as it needs to be reconstructed later
this.aliasesOfListResults.add(alias);
((List) resultObject).forEach(item -> this.addToGraphModel(alias, item));
this.recursivelyAddToGraphModel(alias, (List<Object>) resultObject);
} else {
// Just add the model as is to the graph model
this.addToGraphModel(alias, resultObject);
}
}

private void recursivelyAddToGraphModel(String alias, List<Object> current) {
for (Object o : current) {
if (o instanceof List) {
recursivelyAddToGraphModel(alias, (List<Object>) o);
} else {
addToGraphModel(alias, o);
}
}
}

/**
* Adds an individual result object to the nodes and relationship of the graph model being build
*
Expand Down Expand Up @@ -265,13 +275,15 @@ private static boolean canBeMapped(Object resultObject) {
Predicate<Object> isNodeModel = NodeModel.class::isInstance;
Predicate<Object> isRelationshipModel = RelationshipModel.class::isInstance;
Predicate<Object> isNodeOrRelationshipModel = isNodeModel.or(isRelationshipModel);
Predicate<Object> isListAndEachMemberCanBeMapped = o -> o instanceof List && ((List) o).stream()
.allMatch(isNodeOrRelationshipModel);

if (isNodeOrRelationshipModel.test(resultObject)) {
return true;
} else if (resultObject instanceof List) {
List listOfResultObjects = (List) resultObject;
return listOfResultObjects.size() > 0 && listOfResultObjects.stream()
.allMatch(isNodeOrRelationshipModel);
.allMatch(isNodeOrRelationshipModel.or(isListAndEachMemberCanBeMapped));
} else {
return false;
}
Expand All @@ -282,35 +294,36 @@ private static boolean canBeMapped(Object resultObject) {
* otherwise returns an {@link Object} array if result object is a list containing a mixed set of things,
* otherwise an array of the one elements class.
*
* @param resultObject The object to convert
* @param in The object to convert
* @return The original object or an array.
*/
private static Object convertToTargetContainer(Object resultObject) {
private static Object convertToTargetContainer(Object in) {

if (!(resultObject instanceof List)) {
return resultObject;
if (!(in instanceof List)) {
return in;
}

List entityList = (List) resultObject;
Class arrayClass = Void.class;
List hlp = new ArrayList();
for (Object element : ((List) in)) {
Object convertedElement = convertToTargetContainer(element);
hlp.add(convertedElement);

Class arrayClass = null;
for (Object element : entityList) {
Class clazz = element.getClass();
if (arrayClass == null) {
Class clazz = convertedElement.getClass();
if (arrayClass == Void.class) {
arrayClass = clazz;
} else if (arrayClass != clazz) {
arrayClass = null;
break;
}
}

Object array;
if (arrayClass == null) {
array = entityList.toArray();
array = hlp.toArray();
} else {
array = Array.newInstance(arrayClass, entityList.size());
for (int j = 0; j < entityList.size(); j++) {
Array.set(array, j, Utils.coerceTypes(arrayClass, entityList.get(j)));
array = Array.newInstance(arrayClass, hlp.size());
for (int i = 0; i < hlp.size(); i++) {
Array.set(array, i, Utils.coerceTypes(arrayClass, hlp.get(i)));
}
}
return array;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@

import static org.neo4j.ogm.result.adapter.RestModelAdapter.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.neo4j.ogm.response.model.NodeModel;
import org.neo4j.ogm.response.model.RelationshipModel;
Expand All @@ -47,12 +47,8 @@ public Map<String, Object> adapt(Object[] result) {
String column = columns[i];
Object value = result[i];
if (value instanceof Collection) {
List<Object> adaptedValues = new ArrayList<>();
List<Object> values = (List) value;
for (Object element : values) {
handleAdaptedValue(adaptedValues, processData(element));
}
adaptedResults.put(column, adaptedValues);
adaptedResults.put(column, ((Collection) value).stream().map(this::processData).collect(
Collectors.toList()));
} else {
adaptedResults.put(column, processData(value));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.neo4j.ogm.context.EntityGraphMapper;
import org.neo4j.ogm.context.EntityMapper;
Expand All @@ -49,6 +48,7 @@
import org.neo4j.ogm.domain.types.EntityWithUnmanagedFieldType;
import org.neo4j.ogm.exception.core.InvalidRelationshipTargetException;
import org.neo4j.ogm.metadata.MetaData;
import org.neo4j.ogm.model.Result;
import org.neo4j.ogm.request.Statements;
import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;
Expand Down Expand Up @@ -712,11 +712,11 @@ public void testAppendReferenceFromIncomingSide() {
// Statements cypher = new Statements(this.mapper.map(immigration, 2).getCompiler().getAllStatements());
session.clear();
assertThat(session.query("MATCH (j:Person:DomainObject { name :'jim' }), " +
"(h:Policy:DomainObject { name: 'health' }), " +
"(i:Policy:DomainObject { name: 'immigration' }) " +
"WHERE (j)-[:WRITES_POLICY]->(h) and" +
"(j)-[:WRITES_POLICY]->(i) return j, h, i", emptyMap()).queryResults())
.hasSize(1);
"(h:Policy:DomainObject { name: 'health' }), " +
"(i:Policy:DomainObject { name: 'immigration' }) " +
"WHERE (j)-[:WRITES_POLICY]->(h) and" +
"(j)-[:WRITES_POLICY]->(i) return j, h, i", emptyMap()).queryResults())
.hasSize(1);
}

@Test(expected = IllegalArgumentException.class)
Expand All @@ -735,7 +735,8 @@ public void shouldThrowInvalidRelationshipTargetExceptionOnNullElements() {

assertThatExceptionOfType(InvalidRelationshipTargetException.class)
.isThrownBy(() -> session.save(course))
.withMessage("The relationship 'STUDENTS' from 'org.neo4j.ogm.domain.education.Course' to 'org.neo4j.ogm.domain.education.Student' stored on '#students' contains 'null', which is an invalid target for this relationship.'");
.withMessage(
"The relationship 'STUDENTS' from 'org.neo4j.ogm.domain.education.Course' to 'org.neo4j.ogm.domain.education.Student' stored on '#students' contains 'null', which is an invalid target for this relationship.'");

}

Expand All @@ -751,4 +752,69 @@ public void shouldNotThrowNpeOnUnknownEntityFieldType() {
assertThat(loaded).isNotNull();
}

@Test
public void shouldNotMessUpNestedLists() {

Result result = session.query("RETURN [[0,1,2], [3], [4], [5,6]] as nested_list", Collections.emptyMap());
assertThat(result).hasSize(1).first().satisfies(row -> {
Object nestedLists = row.get("nested_list");
assertThat(nestedLists).isInstanceOf(Long[][].class);

Long[][] columns = (Long[][]) nestedLists;
assertThat(columns).hasSize(4);
assertThat(columns[0]).isInstanceOf(Long[].class)
.satisfies(c -> assertThat(((Long[]) c)).containsExactly(0L, 1L, 2L));
assertThat(columns[1]).isInstanceOf(Long[].class)
.satisfies(c -> assertThat(((Long[]) c)).containsExactly(3L));
});
}

@Test
public void shouldNotMessUpMixedNestedLists() {

Result result = session.query("RETURN [[0,1,2], [[23,42]], [4], [5,6]] as nested_list", Collections.emptyMap());
assertThat(result).hasSize(1).first().satisfies(row -> {
Object nestedLists = row.get("nested_list");
assertThat(nestedLists).isInstanceOf(Object[].class);

Object[] columns = (Object[]) nestedLists;
assertThat(columns).hasSize(4);
assertThat(columns[0]).isInstanceOf(Long[].class)
.satisfies(c -> assertThat(((Long[]) c)).containsExactly(0L, 1L, 2L));
assertThat(columns[1]).isInstanceOf(Long[][].class)
.satisfies(c -> assertThat(((Long[][]) c)[0]).containsExactly(23L, 42L));
});
}

@Test
public void shouldNotMessUpMixedTypedLists() {

Teacher jim = new Teacher("Jim");
sessionFactory.openSession().save(jim);

Result result = session
.query("MATCH (n:Teacher) RETURN n, [[0,1,2], [[\"a\",\"b\"]], [\"c\"], \"d\"] as nested_list",
Collections.emptyMap());
assertThat(result).hasSize(1).first().satisfies(row -> {
Object nestedLists = row.get("nested_list");
assertThat(nestedLists).isInstanceOf(Object[].class);

Object[] columns = (Object[]) nestedLists;
assertThat(columns).hasSize(4);
assertThat(columns[0]).isInstanceOf(Long[].class)
.satisfies(c -> assertThat(((Long[]) c)).containsExactly(0L, 1L, 2L));
assertThat(columns[1]).isInstanceOf(String[][].class)
.satisfies(c -> assertThat(((String[][]) c)[0]).containsExactly("a", "b"));

assertThat(columns[2]).isInstanceOf(String[].class)
.satisfies(c -> assertThat(((String[]) c)).containsExactly("c"));

assertThat(columns[3]).isInstanceOf(String.class)
.isEqualTo("d");

assertThat(row.get("n"))
.isInstanceOf(Teacher.class)
.extracting("name").first().isEqualTo("Jim");
});
}
}