Skip to content

Commit

Permalink
Escape \r
Browse files Browse the repository at this point in the history
  • Loading branch information
xingyutangyuan committed Dec 1, 2023
1 parent 529c74f commit b30a5dd
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
9 changes: 4 additions & 5 deletions mug-guava/src/main/java/com/google/mu/safesql/SafeQuery.java
Original file line number Diff line number Diff line change
Expand Up @@ -232,16 +232,15 @@ private static String quotedBy(char quoteChar, Substring.Match placeholder, Obje
quoteChar,
placeholder,
quoteChar);
return first(CharPredicate.is('\\').or(quoteChar).or('\n'))
return first(CharPredicate.is('\\').or(quoteChar).or('\n').or('\r'))
.repeatedly()
.replaceAllFrom(
value.toString(),
c -> {
switch (c.charAt(0)) {
case '\n':
return "\\n";
default:
return "\\" + c;
case '\r': return "\\r";
case '\n': return "\\n";
default: return "\\" + c;
}
});
}
Expand Down
24 changes: 24 additions & 0 deletions mug-guava/src/test/java/com/google/mu/safesql/SafeQueryTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,30 @@ public void newLineDisallowedWithinBackticks() {
assertThrows(IllegalArgumentException.class, () -> template.with(/* tbl */ "a\nb"));
}

@Test
public void carriageReturnEscapedWithinSingleQuote() {
assertThat(template("SELECT * FROM tbl WHERE id = '{id}'").with("\r"))
.isEqualTo(SafeQuery.of("SELECT * FROM tbl WHERE id = '\\r'"));
}

@Test
public void carriageReturnEscapedWithinDoubleQuote() {
assertThat(template("SELECT * FROM tbl WHERE id = \"{id}\"").with("\r"))
.isEqualTo(SafeQuery.of("SELECT * FROM tbl WHERE id = \"\\r\""));
}

@Test
public void carriageReturnDisallowedWithinBackticks() {
StringFormat.To<SafeQuery> template = template("SELECT * FROM `{tbl}`");
assertThrows(IllegalArgumentException.class, () -> template.with(/* tbl */ "a\rb"));
}

@Test
public void carriageReturnAndLineFeedEscapedWithinDoubleQuote() {
assertThat(template("SELECT * FROM tbl WHERE id = \"{id}\"").with("a\r\nb"))
.isEqualTo(SafeQuery.of("SELECT * FROM tbl WHERE id = \"a\\r\\nb\""));
}

@Test
public void singleQuoteNotEscapedWithinDoubleQuote() {
assertThat(template("SELECT * FROM tbl WHERE id = \"{id}\"").with("'v'"))
Expand Down

0 comments on commit b30a5dd

Please sign in to comment.