refactor(rdsdata,redshiftdata): deduplicate sql parameter parsing logic (#3570) (#3577)

* refactor(rdsdata,redshiftdata): deduplicate sql parameter parsing logic (#3570)

* refactor(rdsdata,redshiftdata): preserve dialect quoting rules in sql parameter parser (#3570)
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-14 12:12:22 -04:00
1 parent 95079965a8
commit 5ae3ed8976
8 files changed
+420 -312

No files matched your search

@@ -0,0 +1,221 @@
package io.github.hectorvent.floci.core.common;
import java.util.ArrayList;
import java.util.List;
/**
* Translates SQL statements containing named placeholders ({@code :name}) into
* JDBC-compatible positional placeholders ({@code ?}), recording placeholder order.
*
* <p>Handles comments (line {@code --} and block {@code /* ... *\/}), single- and
* double-quoted string literals, MySQL backtick identifiers, PostgreSQL dollar-quoted
* strings ({@code $tag$...$tag$}), PostgreSQL cast operators ({@code ::}), and
* PostgreSQL escape strings ({@code E'...'}).
*
* <p>Shared across RDS Data API and Redshift Data API implementations.
*/
public final class SqlParameterParser {
private SqlParameterParser() {
}
/**
* Dialect-specific quoting and escape rules for SQL parameter parsing.
*
* @param allowBackticks whether backticks ({@code `}) delimit identifiers (e.g. MySQL / RDS Data)
* @param backslashEscapes whether backslash escapes characters in string literals (e.g. MySQL)
* @param escapeStrings whether PostgreSQL escape strings ({@code E'...'}/{@code e'...'})
* honor backslash escapes (e.g. Redshift Data API)
*/
public record Options(boolean allowBackticks, boolean backslashEscapes, boolean escapeStrings) {
public static final Options REDSHIFT = new Options(false, false, true);
public static final Options RDS_MYSQL = new Options(true, true, false);
public static final Options RDS_POSTGRESQL = new Options(true, false, false);
}
/**
* SQL rewritten with positional {@code ?} placeholders, plus the ordered
* list of parameter names each placeholder was derived from.
* A name repeats once per occurrence in the original SQL.
*/
public record ParsedSql(String sql, List<String> parameterOrder) {
}
/**
* Rewrites {@code :name} placeholders to positional {@code ?}, skipping over
* string literals, quoted/backtick identifiers, line and block comments,
* PostgreSQL {@code ::} casts, and PostgreSQL dollar-quoted strings according
* to {@code options}.
*/
public static ParsedSql parse(String sql, Options options) {
StringBuilder out = new StringBuilder(sql.length());
List<String> order = new ArrayList<>();
int len = sql.length();
int i = 0;
while (i < len) {
char c = sql.charAt(i);
if (c == '-' && i + 1 < len && sql.charAt(i + 1) == '-') {
int end = sql.indexOf('\n', i);
end = end < 0 ? len : end;
out.append(sql, i, end);
i = end;
continue;
}
if (c == '/' && i + 1 < len && sql.charAt(i + 1) == '*') {
int end = sql.indexOf("*/", i + 2);
end = end < 0 ? len : end + 2;
out.append(sql, i, end);
i = end;
continue;
}
if (c == '\'' || c == '"' || (options.allowBackticks() && c == '`')) {
int end = skipQuoted(sql, i, c, options);
out.append(sql, i, end);
i = end;
continue;
}
if (c == '$') {
int consumed = skipDollarQuoted(sql, i);
if (consumed > i) {
out.append(sql, i, consumed);
i = consumed;
continue;
}
out.append(c);
i++;
continue;
}
if (c == ':') {
if (i + 1 < len && sql.charAt(i + 1) == ':') {
out.append("::");
i += 2;
continue;
}
if (i + 1 < len && isNameStart(sql.charAt(i + 1))) {
int j = i + 1;
while (j < len && isNamePart(sql.charAt(j))) {
j++;
}
order.add(sql.substring(i + 1, j));
out.append('?');
i = j;
continue;
}
}
out.append(c);
i++;
}
return new ParsedSql(out.toString(), order);
}
/**
* Whether {@code sql} holds more than one statement, applying the same
* literal, identifier, comment, and dollar-quote skipping as {@link #parse}
* so a {@code ;} inside any of those is not counted. Trailing {@code ;}
* characters (with only whitespace after) are permitted.
*/
public static boolean isMultiStatement(String sql, Options options) {
int len = sql.length();
int i = 0;
boolean sawSemicolon = false;
while (i < len) {
char c = sql.charAt(i);
if (c == '-' && i + 1 < len && sql.charAt(i + 1) == '-') {
int end = sql.indexOf('\n', i);
i = end < 0 ? len : end;
continue;
}
if (c == '/' && i + 1 < len && sql.charAt(i + 1) == '*') {
int end = sql.indexOf("*/", i + 2);
i = end < 0 ? len : end + 2;
continue;
}
if (c == '\'' || c == '"' || (options.allowBackticks() && c == '`')) {
i = skipQuoted(sql, i, c, options);
continue;
}
if (c == '$') {
int consumed = skipDollarQuoted(sql, i);
if (consumed > i) {
i = consumed;
continue;
}
}
if (c == ';') {
sawSemicolon = true;
} else if (sawSemicolon && !Character.isWhitespace(c)) {
return true;
}
i++;
}
return false;
}
private static int skipQuoted(String sql, int start, char quote, Options options) {
int len = sql.length();
boolean escapable = (options.backslashEscapes() && quote != '`')
|| (options.escapeStrings() && isEscapeStringStart(sql, start, quote));
int i = start + 1;
while (i < len) {
char c = sql.charAt(i);
if (escapable && c == '\\' && i + 1 < len) {
i += 2;
continue;
}
if (c == quote) {
if (i + 1 < len && sql.charAt(i + 1) == quote) {
i += 2;
continue;
}
return i + 1;
}
i++;
}
return i;
}
private static int skipDollarQuoted(String sql, int start) {
int len = sql.length();
int tagEnd = start + 1;
while (tagEnd < len && isNamePart(sql.charAt(tagEnd))) {
tagEnd++;
}
if (tagEnd >= len || sql.charAt(tagEnd) != '$') {
return start;
}
String tag = sql.substring(start, tagEnd + 1);
int close = sql.indexOf(tag, tagEnd + 1);
return close < 0 ? len : close + tag.length();
}
private static boolean isEscapeStringStart(String sql, int quotePos, char quote) {
if (quote != '\'' || quotePos == 0) {
return false;
}
char prefix = sql.charAt(quotePos - 1);
if (prefix != 'e' && prefix != 'E') {
return false;
}
return quotePos - 1 == 0 || !isNamePart(sql.charAt(quotePos - 2));
}
private static boolean isNameStart(char c) {
return Character.isLetter(c) || c == '_';
}
private static boolean isNamePart(char c) {
return Character.isLetterOrDigit(c) || c == '_';
}
}
@@ -6,10 +6,11 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.common.SqlParameterParser.ParsedSql;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
import io.github.hectorvent.floci.core.common.Resettable;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
@@ -243,7 +244,7 @@ public class RdsDataService implements Resettable {
private ObjectNode executeOnConnection(Connection connection, DatabaseEngine engine, String sql,
Map<String, JsonNode> parameters, boolean includeMetadata)
throws SQLException {
RdsDataSqlParameters.ParsedSql parsed = RdsDataSqlParameters.parse(sql, usesBackslashEscapes(engine));
ParsedSql parsed = RdsDataSqlParameters.parse(sql, usesBackslashEscapes(engine));
try (PreparedStatement statement = prepare(connection, engine, parsed.sql())) {
RdsDataSqlParameters.bind(statement, parsed.parameterOrder(), parameters);
return buildResponse(statement, statement.execute(), includeMetadata, engine);
@@ -274,7 +275,7 @@ public class RdsDataService implements Resettable {
if (parameterSets.isEmpty()) {
return batchResponse(updateResults);
}
RdsDataSqlParameters.ParsedSql parsed = RdsDataSqlParameters.parse(sql, usesBackslashEscapes(engine));
ParsedSql parsed = RdsDataSqlParameters.parse(sql, usesBackslashEscapes(engine));
try (PreparedStatement statement = prepare(connection, engine, parsed.sql())) {
rejectStatementReturningRows(statement, parsed.sql());
if (returnsGeneratedKeys(engine)) {
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.rdsdata;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.SqlParameterParser;
import io.github.hectorvent.floci.core.common.SqlParameterParser.ParsedSql;
import java.io.IOException;
import java.math.BigDecimal;
@@ -11,7 +13,6 @@ import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -33,14 +34,6 @@ final class RdsDataSqlParameters {
private RdsDataSqlParameters() {
}
/**
* SQL rewritten with positional {@code ?} placeholders, plus the ordered
* list of the Data API parameter names each placeholder was derived from.
* A name repeats once per occurrence in the original SQL.
*/
record ParsedSql(String sql, List<String> parameterOrder) {
}
/**
* Rewrites {@code :name} placeholders to positional {@code ?} without
* treating backslash as a string-literal escape (the PostgreSQL default
@@ -55,76 +48,11 @@ final class RdsDataSqlParameters {
* string literals, quoted/backtick identifiers, line and block comments,
* PostgreSQL {@code ::} casts, and PostgreSQL dollar-quoted strings so a
* colon inside any of those is left untouched.
*
* @param backslashEscapes when {@code true}, a backslash inside a single- or
* double-quoted string escapes the next character (MySQL/MariaDB
* default, i.e. {@code NO_BACKSLASH_ESCAPES} disabled). Backtick
* identifiers never honor backslash escaping.
*/
static ParsedSql parse(String sql, boolean backslashEscapes) {
StringBuilder out = new StringBuilder(sql.length());
List<String> order = new ArrayList<>();
int len = sql.length();
int i = 0;
while (i < len) {
char c = sql.charAt(i);
if (c == '-' && i + 1 < len && sql.charAt(i + 1) == '-') {
int end = sql.indexOf('\n', i);
if (end < 0) {
end = len;
}
out.append(sql, i, end);
i = end;
continue;
}
if (c == '/' && i + 1 < len && sql.charAt(i + 1) == '*') {
int end = sql.indexOf("*/", i + 2);
end = end < 0 ? len : end + 2;
out.append(sql, i, end);
i = end;
continue;
}
if (c == '\'' || c == '"' || c == '`') {
i = copyQuoted(sql, i, c, out, backslashEscapes);
continue;
}
if (c == '$') {
int consumed = copyDollarQuoted(sql, i, out);
if (consumed > i) {
i = consumed;
continue;
}
out.append(c);
i++;
continue;
}
if (c == ':') {
if (i + 1 < len && sql.charAt(i + 1) == ':') {
out.append("::");
i += 2;
continue;
}
if (i + 1 < len && isNameStart(sql.charAt(i + 1))) {
int j = i + 1;
while (j < len && isNamePart(sql.charAt(j))) {
j++;
}
order.add(sql.substring(i + 1, j));
out.append('?');
i = j;
continue;
}
}
out.append(c);
i++;
}
return new ParsedSql(out.toString(), order);
return SqlParameterParser.parse(sql, backslashEscapes
? SqlParameterParser.Options.RDS_MYSQL
: SqlParameterParser.Options.RDS_POSTGRESQL);
}
/**
@@ -216,56 +144,6 @@ final class RdsDataSqlParameters {
}
}
private static int copyQuoted(String sql, int start, char quote, StringBuilder out, boolean backslashEscapes) {
int len = sql.length();
boolean escapable = backslashEscapes && quote != '`';
out.append(quote);
int i = start + 1;
while (i < len) {
char c = sql.charAt(i);
out.append(c);
if (escapable && c == '\\' && i + 1 < len) {
out.append(sql.charAt(i + 1));
i += 2;
continue;
}
if (c == quote) {
if (i + 1 < len && sql.charAt(i + 1) == quote) {
out.append(quote);
i += 2;
continue;
}
return i + 1;
}
i++;
}
return i;
}
private static int copyDollarQuoted(String sql, int start, StringBuilder out) {
int len = sql.length();
int tagEnd = start + 1;
while (tagEnd < len && isNamePart(sql.charAt(tagEnd))) {
tagEnd++;
}
if (tagEnd >= len || sql.charAt(tagEnd) != '$') {
return start;
}
String tag = sql.substring(start, tagEnd + 1);
int close = sql.indexOf(tag, tagEnd + 1);
int end = close < 0 ? len : close + tag.length();
out.append(sql, start, end);
return end;
}
private static boolean isNameStart(char c) {
return Character.isLetter(c) || c == '_';
}
private static boolean isNamePart(char c) {
return Character.isLetterOrDigit(c) || c == '_';
}
private static String text(JsonNode node, String field) {
JsonNode value = node.get(field);
return value == null || value.isNull() ? null : value.asText();
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.common.SqlParameterParser.ParsedSql;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -104,7 +105,7 @@ public class RedshiftDataService implements Resettable {
private void runOnConnection(RedshiftDataStatementStore.StoredStatement stored,
Connection connection, String sql, Map<String, String> parameters)
throws SQLException {
RedshiftDataSqlParameters.ParsedSql parsed = RedshiftDataSqlParameters.parse(sql);
ParsedSql parsed = RedshiftDataSqlParameters.parse(sql);
long t0 = System.nanoTime();
try (PreparedStatement statement = connection.prepareStatement(parsed.sql())) {
RedshiftDataSqlParameters.bind(statement, parsed.parameterOrder(), parameters);
@@ -2,11 +2,12 @@ package io.github.hectorvent.floci.services.redshiftdata;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.SqlParameterParser;
import io.github.hectorvent.floci.core.common.SqlParameterParser.ParsedSql;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -26,9 +27,6 @@ final class RedshiftDataSqlParameters {
private RedshiftDataSqlParameters() {
}
record ParsedSql(String sql, List<String> parameterOrder) {
}
/**
* Rewrites {@code :name} placeholders to positional {@code ?}, skipping over
* string literals, quoted identifiers, line and block comments, PostgreSQL
@@ -37,61 +35,7 @@ final class RedshiftDataSqlParameters {
* (the PostgreSQL default with {@code standard_conforming_strings} on).
*/
static ParsedSql parse(String sql) {
StringBuilder out = new StringBuilder(sql.length());
List<String> order = new ArrayList<>();
int len = sql.length();
int i = 0;
while (i < len) {
char c = sql.charAt(i);
if (c == '-' && i + 1 < len && sql.charAt(i + 1) == '-') {
int end = sql.indexOf('\n', i);
end = end < 0 ? len : end;
out.append(sql, i, end);
i = end;
continue;
}
if (c == '/' && i + 1 < len && sql.charAt(i + 1) == '*') {
int end = sql.indexOf("*/", i + 2);
end = end < 0 ? len : end + 2;
out.append(sql, i, end);
i = end;
continue;
}
if (c == '\'' || c == '"') {
i = copyQuoted(sql, i, c, out);
continue;
}
if (c == '$') {
int consumed = copyDollarQuoted(sql, i, out);
if (consumed > i) {
i = consumed;
continue;
}
out.append(c);
i++;
continue;
}
if (c == ':') {
if (i + 1 < len && sql.charAt(i + 1) == ':') {
out.append("::");
i += 2;
continue;
}
if (i + 1 < len && isNameStart(sql.charAt(i + 1))) {
int j = i + 1;
while (j < len && isNamePart(sql.charAt(j))) {
j++;
}
order.add(sql.substring(i + 1, j));
out.append('?');
i = j;
continue;
}
}
out.append(c);
i++;
}
return new ParsedSql(out.toString(), order);
return SqlParameterParser.parse(sql, SqlParameterParser.Options.REDSHIFT);
}
/**
@@ -150,113 +94,6 @@ final class RedshiftDataSqlParameters {
* characters (with only whitespace after) are permitted.
*/
static boolean isMultiStatement(String sql) {
int len = sql.length();
int i = 0;
boolean sawSemicolon = false;
while (i < len) {
char c = sql.charAt(i);
if (c == '-' && i + 1 < len && sql.charAt(i + 1) == '-') {
int end = sql.indexOf('\n', i);
i = end < 0 ? len : end;
continue;
}
if (c == '/' && i + 1 < len && sql.charAt(i + 1) == '*') {
int end = sql.indexOf("*/", i + 2);
i = end < 0 ? len : end + 2;
continue;
}
if (c == '\'' || c == '"') {
i = skipQuoted(sql, i, c, isEscapeStringStart(sql, i, c));
continue;
}
if (c == '$') {
int consumed = skipDollarQuoted(sql, i);
if (consumed > i) {
i = consumed;
continue;
}
}
if (c == ';') {
sawSemicolon = true;
} else if (sawSemicolon && !Character.isWhitespace(c)) {
return true;
}
i++;
}
return false;
}
/**
* Whether the quote at {@code quotePos} opens a PostgreSQL escape string
* ({@code E'...'} / {@code e'...'}), inside which a backslash escapes the
* next character. Plain {@code '...'} literals do not process backslashes
* under {@code standard_conforming_strings}.
*/
private static boolean isEscapeStringStart(String sql, int quotePos, char quote) {
if (quote != '\'' || quotePos == 0) {
return false;
}
char prefix = sql.charAt(quotePos - 1);
if (prefix != 'e' && prefix != 'E') {
return false;
}
return quotePos - 1 == 0 || !isNamePart(sql.charAt(quotePos - 2));
}
private static int skipQuoted(String sql, int start, char quote, boolean backslashEscapes) {
int len = sql.length();
int i = start + 1;
while (i < len) {
char c = sql.charAt(i);
if (backslashEscapes && c == '\\' && i + 1 < len) {
i += 2;
continue;
}
if (c == quote) {
if (i + 1 < len && sql.charAt(i + 1) == quote) {
i += 2;
continue;
}
return i + 1;
}
i++;
}
return i;
}
private static int skipDollarQuoted(String sql, int start) {
int len = sql.length();
int tagEnd = start + 1;
while (tagEnd < len && isNamePart(sql.charAt(tagEnd))) {
tagEnd++;
}
if (tagEnd >= len || sql.charAt(tagEnd) != '$') {
return start;
}
String tag = sql.substring(start, tagEnd + 1);
int close = sql.indexOf(tag, tagEnd + 1);
return close < 0 ? len : close + tag.length();
}
private static int copyQuoted(String sql, int start, char quote, StringBuilder out) {
int end = skipQuoted(sql, start, quote, isEscapeStringStart(sql, start, quote));
out.append(sql, start, end);
return end;
}
private static int copyDollarQuoted(String sql, int start, StringBuilder out) {
int end = skipDollarQuoted(sql, start);
if (end > start) {
out.append(sql, start, end);
}
return end;
}
private static boolean isNameStart(char c) {
return Character.isLetter(c) || c == '_';
}
private static boolean isNamePart(char c) {
return Character.isLetterOrDigit(c) || c == '_';
return SqlParameterParser.isMultiStatement(sql, SqlParameterParser.Options.REDSHIFT);
}
}