Skip to content

Commit

Permalink
Fix custom quoting in SQLQuery
Browse files Browse the repository at this point in the history
Signed-off-by: Benjamin Rögner <[email protected]>
  • Loading branch information
roegi committed Oct 15, 2024
1 parent 29056d8 commit 16e0b28
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions xyz-util/src/main/java/com/here/xyz/util/db/SQLQuery.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public class SQLQuery {
private static final String FRAGMENT_PREFIX = "${{";
private static final String FRAGMENT_SUFFIX = "}}";
public static final String QUERY_ID = "queryId";
public static final String TEXT_QUOTE = "\\$a\\$";
public static final String TEXT_QUOTE = "$a$";
private String statement = "";
@JsonProperty
private List<Object> parameters = new ArrayList<>();
Expand Down Expand Up @@ -231,7 +231,7 @@ private String paramValueToString(Object paramValue) {
if (paramValue == null)
return "NULL";
if (paramValue instanceof String stringParam)
return TEXT_QUOTE + escapeDollarSigns(escapeCustomQuotes(stringParam, TEXT_QUOTE)) + TEXT_QUOTE;
return escapeDollarSigns(customQuote(stringParam));
if (paramValue instanceof Long)
return paramValue + "::BIGINT";
if (paramValue instanceof Number)
Expand All @@ -245,6 +245,11 @@ private String paramValueToString(Object paramValue) {
return paramValue.toString();
}

private static String customQuote(String stringToQuote) {
String quote = getEscapedCustomQuoteFor(stringToQuote, TEXT_QUOTE);
return quote + stringToQuote + quote;
}

/**
* Internal helper method that escapes $-signs, because they're treated as special chars when using the containing string as value
* in a string / pattern-matching replacement.
Expand All @@ -266,17 +271,12 @@ private static String escapeDollarSigns(String containingString) {
* @param customQuoteToEscape
* @return
*/
private static String escapeCustomQuotes(String containingString, String customQuoteToEscape) {
if (!containingString.contains(customQuoteToEscape))
return containingString;

String escapedCustomQuote = getEscapedCustomQuoteFor(customQuoteToEscape);

private static String getEscapedCustomQuoteFor(String containingString, String customQuoteToEscape) {
//Further escape the custom quote until finding one that is not in use yet
while (containingString.contains(escapedCustomQuote))
escapedCustomQuote = getEscapedCustomQuoteFor(escapedCustomQuote);
while (containingString.contains(customQuoteToEscape))
customQuoteToEscape = getEscapedCustomQuoteFor(customQuoteToEscape);

return containingString.replaceAll(Pattern.quote(customQuoteToEscape), escapeDollarSigns(escapedCustomQuote));
return customQuoteToEscape;
}

private static String getEscapedCustomQuoteFor(String customQuoteToEscape) {
Expand Down

0 comments on commit 16e0b28

Please sign in to comment.