Skip to content

Commit

Permalink
skip empty SafeQuery from a List
Browse files Browse the repository at this point in the history
  • Loading branch information
fluentfuture committed Dec 28, 2024
1 parent 879be0e commit 3fb6796
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
6 changes: 5 additions & 1 deletion mug-guava/src/main/java/com/google/mu/safesql/SafeQuery.java
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,10 @@ private SafeQuery guardDashExpression(Substring.Match placeholder) {
return query.startsWith("-") && !placeholder.isImmediatelyBetween("(", ")") ? parenthesized() : this;
}

private static Iterable<?> skipEmptySubqueries(Iterable<?> iterable) {
return Iterables.filter(iterable, v -> !(v instanceof SafeQuery && v.toString().isEmpty()));
}

/**
* An SPI class for subclasses to provide additional translation from
* placeholder values to safe query strings.
Expand Down Expand Up @@ -411,7 +415,7 @@ protected SafeQuery translateLiteral(Substring.Match placeholder, Object value)
private String fillInPlaceholder(Substring.Match placeholder, Object value) {
validatePlaceholder(placeholder);
if (value instanceof Iterable) {
Iterable<?> iterable = (Iterable<?>) value;
Iterable<?> iterable = skipEmptySubqueries((Iterable<?>) value);
if (placeholder.isImmediatelyBetween("`", "`")) { // If backquoted, it's a list of symbols
return String.join("`, `", Iterables.transform(iterable, v -> backquoted(placeholder, v)));
}
Expand Down
22 changes: 20 additions & 2 deletions mug-guava/src/test/java/com/google/mu/safesql/SafeQueryTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -246,15 +246,33 @@ public void listOfUnquotedEnumsPlaceholder() {
}

@Test
public void listOfSafeBigQueriesPlaceholder() {
public void listOfSafeQueriesPlaceholder() {
assertThat(
template("SELECT foo FROM {tbls}")
.with(/* tbls */ asList(SafeQuery.of("a"), SafeQuery.of("b"))))
.isEqualTo(SafeQuery.of("SELECT foo FROM a, b"));
}

@Test
public void listOfSafeBigQueries_disallowed() {
public void listOfSubqueries() {
assertThat(
SafeQuery.of(
"SELECT {exprs} FROM tbl", /* exprs */
asList(SafeQuery.of("123"), SafeQuery.of("foo"))))
.isEqualTo(SafeQuery.of("SELECT 123, foo FROM tbl"));
}

@Test
public void listOfSubqueries_emptySubqueryIgnored() {
assertThat(
SafeQuery.of(
"SELECT {exprs} FROM tbl", /* exprs */
asList(SafeQuery.of("123"), SafeQuery.EMPTY)))
.isEqualTo(SafeQuery.of("SELECT 123 FROM tbl"));
}

@Test
public void listOfSafeQueries_disallowed() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
Expand Down

0 comments on commit 3fb6796

Please sign in to comment.