Skip to content

Commit

Permalink
Wrap Criteria is and regex comparison if necessary.
Browse files Browse the repository at this point in the history
This commit wraps simple values and Patterns if to avoid creating invalid query objects.
  • Loading branch information
christophstrobl committed Dec 20, 2024
1 parent d77786d commit cb40b69
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -945,8 +945,17 @@ protected Document getSingleCriteriaObject() {
Document queryCriteria = new Document();

if (!NOT_SET.equals(isValue)) {
queryCriteria.put(this.key, this.isValue);
queryCriteria.putAll(document);
if(document.isEmpty()) {
queryCriteria.put(this.key, this.isValue);
}
else {
if(isValue instanceof Pattern || isValue instanceof BsonRegularExpression) {
document.put("$regex", isValue);
} else {
document.put("$eq", isValue);
}
queryCriteria.put(this.key, document);
}
} else {
queryCriteria.put(this.key, document);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.regex.Pattern;

import org.bson.BsonRegularExpression;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.geo.Point;
Expand Down Expand Up @@ -50,6 +52,44 @@ public void testSimpleCriteria() {
assertThat(c.getCriteriaObject()).isEqualTo("{ \"name\" : \"Bubba\"}");
}

@Test // GH-4850
public void testCombiningSimpleCriteria() {

Document expected = Document.parse("{ name : { $eq : 123, $type : ['long'] } }");

Criteria c = Criteria.where("name") //
.is(123) //
.type(Type.INT_64);

assertThat(c.getCriteriaObject()).isEqualTo(expected);

c = Criteria.where("name") //
.type(Type.INT_64)
.is(123);

assertThat(c.getCriteriaObject()).isEqualTo(expected);
}

@Test // GH-4850
public void testCombiningBsonRegexCriteria() {

Criteria c = Criteria.where("name")
.regex(new BsonRegularExpression("^spring$"))
.type(Type.INT_64);

assertThat(c.getCriteriaObject()).isEqualTo(Document.parse("{ name : { $regex : RegExp('^spring$'), $type : ['long'] } }"));
}

@Test // GH-4850
public void testCombiningRegexCriteria() {

Criteria c = Criteria.where("name")
.regex("^spring$")
.type(Type.INT_64);

assertThat(c.getCriteriaObject()).hasEntrySatisfying("name.$regex", it -> assertThat(it).isInstanceOf(Pattern.class));
}

@Test
public void testNotEqualCriteria() {
Criteria c = new Criteria("name").ne("Bubba");
Expand Down

0 comments on commit cb40b69

Please sign in to comment.