Skip to content

Commit

Permalink
Wrap strings in literal if contains $ (#1144)
Browse files Browse the repository at this point in the history
  • Loading branch information
katcharov authored Jun 20, 2023
1 parent c5370c3 commit 86b43d6
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
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;
}
}

/**
* 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

0 comments on commit 86b43d6

Please sign in to comment.