Skip to content
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
13 changes: 11 additions & 2 deletions driver-core/src/main/com/mongodb/client/model/mql/MqlValues.java
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ public static MqlArray<MqlDate> ofDateArray(final Instant... array) {
*/
public static MqlString of(final String of) {
Assertions.notNull("String", of);
return new MqlExpression<>((codecRegistry) -> new AstPlaceholder(new BsonString(of)));
return new MqlExpression<>((codecRegistry) -> new AstPlaceholder(wrapString(of)));
}

/**
Expand All @@ -249,11 +249,20 @@ public static MqlArray<MqlString> ofStringArray(final String... array) {
List<BsonValue> result = new ArrayList<>();
for (String e : array) {
Assertions.notNull("elements of array", e);
result.add(new BsonString(e));
result.add(wrapString(e));
}
return new MqlExpression<>((cr) -> new AstPlaceholder(new BsonArray(result)));
}

private static BsonValue wrapString(final String s) {
BsonString bson = new BsonString(s);
if (s.contains("$")) {
return new BsonDocument("$literal", bson);
} else {
return bson;
}
}
Comment on lines +257 to +264
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe "$" is the only character that would cause a string to need to be wrapped.


/**
* Returns a reference to the "current"
* {@linkplain MqlDocument document} value.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ public void literalsTest() {
Arrays.asList("a", "b", "c"),
ofStringArray("a", "b", "c"),
"['a', 'b', 'c']");
// must escape:
assertExpression(
Arrays.asList("$a", "b", "$c.d"),
ofStringArray("$a", "b", "$c.d"),
"[{'$literal': '$a'}, 'b', {'$literal': '$c.d'}]");

// Date
assertExpression(
Arrays.asList(Instant.parse("2007-12-03T10:15:30.00Z")),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ public void literalsTest() {
assertExpression("abc", of("abc"), "'abc'");
assertThrows(IllegalArgumentException.class, () -> of((String) null));
assertExpression(fish, of(fish), "'" + fish + "'");

// must escape:
assertExpression(
"$abc",
of("$abc"),
"{'$literal': '$abc'}");
}

@Test
Expand Down