Skip to content

Commit 86b43d6

Browse files
authored
Wrap strings in literal if contains $ (#1144)
JAVA-4884
1 parent c5370c3 commit 86b43d6

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

driver-core/src/main/com/mongodb/client/model/mql/MqlValues.java

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ public static MqlArray<MqlDate> ofDateArray(final Instant... array) {
233233
*/
234234
public static MqlString of(final String of) {
235235
Assertions.notNull("String", of);
236-
return new MqlExpression<>((codecRegistry) -> new AstPlaceholder(new BsonString(of)));
236+
return new MqlExpression<>((codecRegistry) -> new AstPlaceholder(wrapString(of)));
237237
}
238238

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

257+
private static BsonValue wrapString(final String s) {
258+
BsonString bson = new BsonString(s);
259+
if (s.contains("$")) {
260+
return new BsonDocument("$literal", bson);
261+
} else {
262+
return bson;
263+
}
264+
}
265+
257266
/**
258267
* Returns a reference to the "current"
259268
* {@linkplain MqlDocument document} value.

driver-core/src/test/functional/com/mongodb/client/model/mql/ArrayMqlValuesFunctionalTest.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,12 @@ public void literalsTest() {
7777
Arrays.asList("a", "b", "c"),
7878
ofStringArray("a", "b", "c"),
7979
"['a', 'b', 'c']");
80+
// must escape:
81+
assertExpression(
82+
Arrays.asList("$a", "b", "$c.d"),
83+
ofStringArray("$a", "b", "$c.d"),
84+
"[{'$literal': '$a'}, 'b', {'$literal': '$c.d'}]");
85+
8086
// Date
8187
assertExpression(
8288
Arrays.asList(Instant.parse("2007-12-03T10:15:30.00Z")),

driver-core/src/test/functional/com/mongodb/client/model/mql/StringMqlValuesFunctionalTest.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,12 @@ public void literalsTest() {
3838
assertExpression("abc", of("abc"), "'abc'");
3939
assertThrows(IllegalArgumentException.class, () -> of((String) null));
4040
assertExpression(fish, of(fish), "'" + fish + "'");
41+
42+
// must escape:
43+
assertExpression(
44+
"$abc",
45+
of("$abc"),
46+
"{'$literal': '$abc'}");
4147
}
4248

4349
@Test

0 commit comments

Comments
 (0)