Skip to content

DATAMONGO-2149 - Fix $slice in fields projection when pointing to array of DBRefs. #623

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

Closed
wants to merge 2 commits into from
Closed
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
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.0.DATAMONGO-2149-SNAPSHOT</version>
<packaging>pom</packaging>

<name>Spring Data MongoDB</name>
Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb-benchmarks/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.0.DATAMONGO-2149-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
4 changes: 2 additions & 2 deletions spring-data-mongodb-cross-store/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.0.DATAMONGO-2149-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down Expand Up @@ -50,7 +50,7 @@
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.0.DATAMONGO-2149-SNAPSHOT</version>
</dependency>

<!-- reactive -->
Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb-distribution/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.0.DATAMONGO-2149-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.0.DATAMONGO-2149-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
Expand Down Expand Up @@ -299,7 +300,7 @@ protected Document getMappedKeyword(Keyword keyword, @Nullable MongoPersistentEn
*/
protected Document getMappedKeyword(Field property, Keyword keyword) {

boolean needsAssociationConversion = property.isAssociation() && !keyword.isExists();
boolean needsAssociationConversion = property.isAssociation() && !keyword.isExists() && keyword.mayHoldDbRef();
Object value = keyword.getValue();

Object convertedValue = needsAssociationConversion ? convertAssociation(value, property)
Expand Down Expand Up @@ -634,10 +635,12 @@ protected boolean isKeyword(String candidate) {
static class Keyword {

private static final String N_OR_PATTERN = "\\$.*or";
private static final Set<String> NON_DBREF_CONVERTING_KEYWORDS = new HashSet<>(Arrays.asList("$", "$size", "$slice", "$gt", "$lt"));

private final String key;
private final Object value;


public Keyword(Bson source, String key) {
this.key = key;
this.value = BsonUtils.get(source, key);
Expand Down Expand Up @@ -698,6 +701,15 @@ public <T> T getValue() {
return (T) value;
}

/**
*
* @return {@literal true} if key may hold a DbRef.
* @since 2.0.13
*/
public boolean mayHoldDbRef() {
return !NON_DBREF_CONVERTING_KEYWORDS.contains(key);
}

/**
* Returns whether the current keyword indicates a {@literal $jsonSchema} object.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,16 @@
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
Expand All @@ -60,6 +63,7 @@
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.repository.Person.Sex;
import org.springframework.data.mongodb.repository.SampleEvaluationContextExtension.SampleSecurityContextHolder;
import org.springframework.data.querydsl.QSort;
Expand Down Expand Up @@ -1231,4 +1235,71 @@ public void findByRegexWithPatternAndOptions() {
assertThat(repository.findByFirstnameRegex(Pattern.compile(fn))).hasSize(0);
assertThat(repository.findByFirstnameRegex(Pattern.compile(fn, Pattern.CASE_INSENSITIVE))).hasSize(1);
}

@Test // DATAMONGO-2149
public void annotatedQueryShouldAllowSliceInFieldsProjectionWithDbRef() {

operations.remove(new Query(), User.class);

List<User> users = IntStream.range(0, 10).mapToObj(it -> {

User user = new User();
user.id = "id" + it;
user.username = "user" + it;

return user;
}).collect(Collectors.toList());

users.forEach(operations::save);

alicia.fans = new ArrayList<>(users);
operations.save(alicia);

Person target = repository.findWithSliceInProjection(alicia.getId(), 0, 5);
assertThat(target.getFans().size()).isEqualTo(5);
}

@Test // DATAMONGO-2149
public void annotatedQueryShouldAllowPositionalParameterInFieldsProjection() {

Set<Address> addressList = IntStream.range(0, 10).mapToObj(it -> new Address("street-" + it, "zip", "lnz"))
.collect(Collectors.toSet());

alicia.setShippingAddresses(addressList);
operations.save(alicia);

Person target = repository.findWithArrayPositionInProjection(1);

assertThat(target).isNotNull();
assertThat(target.getShippingAddresses()).hasSize(1);
}

@Test // DATAMONGO-2149
@Ignore("This one fails due to Json parse exception within MongoDB")
public void annotatedQueryShouldAllowPositionalParameterInFieldsProjectionWithDbRef() {

// the following needs to be added to PersonRepository.

// @Query(value = "{ 'fans' : { '$elemMatch' : { '$ref' : 'user' } } }", fields = "{ 'fans.$': ?0 }")
// Person findWithArrayPositionInProjectionWithDbRef(int position);

List<User> userList = IntStream.range(0, 10).mapToObj(it -> {

User user = new User();
user.id = "" + it;
user.username = "user" + it;

return user;
}).collect(Collectors.toList());

userList.forEach(operations::save);

alicia.setFans(userList);
operations.save(alicia);

// Person target = repository.findWithArrayPositionInProjectionWithDbRef(1);
//
// assertThat(target).isNotNull();
// assertThat(target.getShippingAddresses()).hasSize(1);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -356,4 +356,10 @@ Page<Person> findByCustomQueryLastnameAndAddressStreetInList(String lastname, Li
List<Person> findByAgeGreaterThan(int age, Sort sort);

List<Person> findByFirstnameRegex(Pattern pattern);

@Query(value = "{ 'id' : ?0 }", fields = "{ 'fans': { '$slice': [ ?1, ?2 ] } }")
Person findWithSliceInProjection(String id, int skip, int limit);

@Query(value = "{ 'shippingAddresses' : { '$elemMatch' : { 'city' : { '$eq' : 'lnz' } } } }", fields = "{ 'shippingAddresses.$': ?0 }")
Person findWithArrayPositionInProjection(int position);
}
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,18 @@ public void spelShouldIgnoreJsonParseErrorsForRegex() {
is(new BasicQuery("{lastname: {$regex: 'Chandler'}}").getQueryObject().toJson()));
}

@Test // DATAMONGO-2149
public void shouldParseFieldsProjectionWithSliceCorrectly() {

StringBasedMongoQuery mongoQuery = createQueryForMethod("findWithSliceInProjection", String.class, int.class,
int.class);
ConvertingParameterAccessor accessor = StubParameterAccessor.getAccessor(converter, "Bruce Banner", 0, 5);

org.springframework.data.mongodb.core.query.Query query = mongoQuery.createQuery(accessor);

assertThat(query.getFieldsObject(), is(equalTo(Document.parse("{ \"fans\" : { \"$slice\" : [0, 5] } }"))));
}

private StringBasedMongoQuery createQueryForMethod(String name, Class<?>... parameters) {

try {
Expand Down Expand Up @@ -718,6 +730,9 @@ private interface SampleRepository extends Repository<Person, Long> {

@Query("{ 'lastname' : { '$regex' : ?#{[0].lastname} } }")
Person findByPersonLastnameRegex(Person key);

@Query(value = "{ 'id' : ?0 }", fields = "{ 'fans': { '$slice': [ ?1, ?2 ] } }")
Person findWithSliceInProjection(String id, int skip, int limit);
}

}