mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(redshift): tokenize streaming view JOIN and aggregate checks with SqlParameterParser (#8977)
The JOIN and aggregate checks on a streaming materialized view blanked string literals with their own regex, which paired the quotes of an escape string such as E'\'' wrongly: a JOIN or an aggregate after it could hide inside a bogus literal, and a keyword inside E'it\'s a join' was refused. The checks now run on the query as SqlParameterParser tokenizes it, through a new blankQuoted that empties quoted strings, quoted identifiers and dollar-quoted bodies and drops comments. The Redshift DDL rewrite masks its string literals through the same tokenizer's literalSpans instead of a second regex.
This commit is contained in:
1 parent
9ea2f038f7
commit
8db9542226
6 files changed
+120
-12
No files matched your search
@@ -246,6 +246,55 @@ public final class SqlParameterParser {
|
||||
* inside any of those is kept. A line comment's terminating newline is kept.
|
||||
*/
|
||||
public static String stripComments(String sql, Options options) {
|
||||
return rewrite(sql, options, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code sql} with each comment replaced by a single space and each quoted string, quoted
|
||||
* identifier, or dollar-quoted body replaced by an empty {@code ''}, tokenized as {@link #parse}
|
||||
* does, so a keyword inside any of them is not seen by a caller that scans the rest.
|
||||
*/
|
||||
public static String blankQuoted(String sql, Options options) {
|
||||
return rewrite(sql, options, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@code [start, end)} span of each string literal and dollar-quoted body in {@code sql}, in
|
||||
* order, tokenized as {@link #parse} does. Quoted identifiers and comments are skipped, not returned.
|
||||
*/
|
||||
public static List<int[]> literalSpans(String sql, Options options) {
|
||||
List<int[]> spans = new ArrayList<>();
|
||||
int len = sql.length();
|
||||
int i = 0;
|
||||
while (i < len) {
|
||||
char c = sql.charAt(i);
|
||||
if (startsLineComment(sql, i, options)) {
|
||||
int end = sql.indexOf('\n', i);
|
||||
i = end < 0 ? len : end;
|
||||
} else if (c == '/' && i + 1 < len && sql.charAt(i + 1) == '*') {
|
||||
i = skipBlockComment(sql, i, !options.mysqlComments());
|
||||
} else if (c == '\'' || c == '"' || (options.allowBackticks() && c == '`')) {
|
||||
int end = skipQuoted(sql, i, c, options);
|
||||
if (c == '\'') {
|
||||
spans.add(new int[] {i, end});
|
||||
}
|
||||
i = end;
|
||||
} else if (c == '$') {
|
||||
int end = skipDollarQuoted(sql, i);
|
||||
if (end > i) {
|
||||
spans.add(new int[] {i, end});
|
||||
i = end;
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return spans;
|
||||
}
|
||||
|
||||
private static String rewrite(String sql, Options options, boolean blankQuoted) {
|
||||
StringBuilder out = new StringBuilder(sql.length());
|
||||
int len = sql.length();
|
||||
int i = 0;
|
||||
@@ -272,7 +321,11 @@ public final class SqlParameterParser {
|
||||
end = skipDollarQuoted(sql, i);
|
||||
}
|
||||
if (end > i) {
|
||||
out.append(sql, i, end);
|
||||
if (blankQuoted) {
|
||||
out.append("''");
|
||||
} else {
|
||||
out.append(sql, i, end);
|
||||
}
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package io.floci.aws.services.redshift.proxy;
|
||||
|
||||
import io.floci.aws.core.common.SqlParameterParser;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
@@ -45,10 +47,6 @@ public final class RedshiftSqlInterceptor {
|
||||
"(?is)^\\s*(?:(?:--[^\\n]*\\n)|(?:/\\*.*?\\*/)|\\s)*(?:CREATE|ALTER)\\s+(?:(?:GLOBAL|LOCAL)\\s+)?"
|
||||
+ "(?:(?:TEMP|TEMPORARY|UNLOGGED)\\s+)?TABLE\\b");
|
||||
|
||||
/** Single-quoted string literal (doubled '' is escaped quote) and PostgreSQL dollar-quoted string literal ($tag$...$tag$). */
|
||||
private static final Pattern STRING_LITERAL_PATTERN = Pattern.compile(
|
||||
"'(?:[^']|'')*'|(?s)\\$([^$\\s]*)\\$.*?\\$\\1\\$");
|
||||
|
||||
private static final Pattern DISTSTYLE_PATTERN = Pattern.compile("(?i)\\bDISTSTYLE\\s+(ALL|EVEN|KEY|AUTO)\\b");
|
||||
private static final Pattern DISTKEY_PAREN_PATTERN = Pattern.compile("(?i)\\bDISTKEY\\s*\\([^)]*\\)");
|
||||
private static final Pattern SORTKEY_PAREN_PATTERN = Pattern.compile("(?i)\\b(?:COMPOUND|INTERLEAVED)?\\s*SORTKEY\\s*\\([^)]*\\)");
|
||||
@@ -137,13 +135,15 @@ public final class RedshiftSqlInterceptor {
|
||||
}
|
||||
|
||||
private static String maskStringLiterals(String sql, List<String> out) {
|
||||
Matcher m = STRING_LITERAL_PATTERN.matcher(sql);
|
||||
StringBuilder sb = new StringBuilder(sql.length());
|
||||
while (m.find()) {
|
||||
out.add(m.group());
|
||||
m.appendReplacement(sb, Matcher.quoteReplacement(MASK_SENTINEL + (out.size() - 1) + MASK_SENTINEL));
|
||||
int copied = 0;
|
||||
for (int[] span : SqlParameterParser.literalSpans(sql, SqlParameterParser.Options.REDSHIFT)) {
|
||||
sb.append(sql, copied, span[0]);
|
||||
out.add(sql.substring(span[0], span[1]));
|
||||
sb.append(MASK_SENTINEL).append(out.size() - 1).append(MASK_SENTINEL);
|
||||
copied = span[1];
|
||||
}
|
||||
m.appendTail(sb);
|
||||
sb.append(sql, copied, sql.length());
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.floci.aws.services.redshift.spectrum;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.PostgresWire;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.common.SqlParameterParser;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.services.glue.GlueService;
|
||||
import io.floci.aws.services.glue.model.Database;
|
||||
@@ -37,7 +38,6 @@ public class SpectrumQueryPreparation {
|
||||
"\\b(?:GROUP\\s+BY|HAVING|DISTINCT)\\b|\\b(?:COUNT|SUM|AVG|MIN|MAX|MEDIAN|LISTAGG|STDDEV\\w*|VAR_\\w+|VARIANCE"
|
||||
+ "|BOOL_AND|BOOL_OR|ARRAY_AGG|APPROXIMATE|PERCENTILE_\\w+)\\s*\\(",
|
||||
Pattern.CASE_INSENSITIVE);
|
||||
private static final Pattern STRING_LITERAL = Pattern.compile("'(?:[^']|'')*'|\"(?:[^\"]|\"\")*\"");
|
||||
private final ExternalCatalogRegistry registry;
|
||||
private final KinesisSchemaRegistry kinesisSchemas;
|
||||
private final KinesisStreamingViews views;
|
||||
@@ -540,7 +540,7 @@ public class SpectrumQueryPreparation {
|
||||
throw new SpectrumSqlException("0A000",
|
||||
"AUTO REFRESH YES is not supported; refresh the view with REFRESH MATERIALIZED VIEW");
|
||||
}
|
||||
String unquoted = STRING_LITERAL.matcher(view.select()).replaceAll("''");
|
||||
String unquoted = SqlParameterParser.blankQuoted(view.select(), SqlParameterParser.Options.REDSHIFT);
|
||||
if (JOIN.matcher(unquoted).find()) {
|
||||
throw new SpectrumSqlException("0A000", "A streaming materialized view cannot contain a JOIN");
|
||||
}
|
||||
|
||||
@@ -12,6 +12,31 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class SqlParameterParserTest {
|
||||
|
||||
@Test
|
||||
void blankQuotedEmptiesLiteralsIdentifiersAndDollarBodiesAndDropsComments() {
|
||||
assertEquals("select '', '' from t where a = ''",
|
||||
SqlParameterParser.blankQuoted(
|
||||
"select 'a join b', \"group by\" from t where a = $$ x $$", Options.REDSHIFT));
|
||||
assertEquals("select 1 from t",
|
||||
SqlParameterParser.blankQuoted("select 1 /* join */ from t", Options.REDSHIFT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankQuotedReadsABackslashQuoteInAnEscapeStringAsPartOfTheLiteral() {
|
||||
assertEquals("select E'' from t join u",
|
||||
SqlParameterParser.blankQuoted("select E'\\' x' from t join u", Options.REDSHIFT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void literalSpansCoverStringsAndDollarBodiesButNotIdentifiersOrComments() {
|
||||
String sql = "select E'\\'' , \"a'b\", $t$ x $t$ /* 'c' */ -- 'd'\n, 'e''f'";
|
||||
|
||||
List<String> literals = SqlParameterParser.literalSpans(sql, Options.REDSHIFT).stream()
|
||||
.map(span -> sql.substring(span[0], span[1])).toList();
|
||||
|
||||
assertEquals(List.of("'\\''", "$t$ x $t$", "'e''f'"), literals);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rewritesNamedPlaceholdersToPositional() {
|
||||
ParsedSql parsed = SqlParameterParser.parse(
|
||||
|
||||
@@ -353,6 +353,17 @@ class RedshiftSqlInterceptorTest {
|
||||
assertSame(sql, RedshiftSqlInterceptor.rewrite(sql));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReadABackslashQuoteInAnEscapeStringAsPartOfTheLiteral() {
|
||||
String sql = "CREATE TABLE t (a VARCHAR(20) DEFAULT E'\\'', b INT DISTKEY, c VARCHAR(20) DEFAULT ' DISTKEY ');";
|
||||
|
||||
String rewritten = RedshiftSqlInterceptor.rewrite(sql);
|
||||
|
||||
assertTrue(!rewritten.contains("b INT DISTKEY"), "Should remove column-level DISTKEY: " + rewritten);
|
||||
assertTrue(rewritten.contains("DEFAULT E'\\''"), "Should keep the escape string: " + rewritten);
|
||||
assertTrue(rewritten.contains("' DISTKEY '"), "Should keep DISTKEY inside the literal: " + rewritten);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotTouchABinaryTypeOutsideTableDdl() {
|
||||
String sql = "SELECT CAST(x AS VARBYTE(10)) FROM t";
|
||||
|
||||
+19
@@ -136,6 +136,25 @@ class SpectrumKinesisViewPreparationTest {
|
||||
SESSION, backend);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEscapedQuoteInAnEscapeStringDoesNotHideAJoinOrAnAggregateFromTheChecks() {
|
||||
SpectrumSqlException join = assertThrows(SpectrumSqlException.class, () -> preparation.prepare(
|
||||
"CREATE MATERIALIZED VIEW v AS SELECT E'\\'' AS q FROM kds.events e JOIN public.t ON e.shard_id = 'a'",
|
||||
SESSION, backend));
|
||||
SpectrumSqlException aggregate = assertThrows(SpectrumSqlException.class, () -> preparation.prepare(
|
||||
"CREATE MATERIALIZED VIEW v AS SELECT E'\\'' AS q, count(*) FROM kds.events WHERE shard_id = 'a'",
|
||||
SESSION, backend));
|
||||
|
||||
assertThat(join.getMessage(), containsString("JOIN"));
|
||||
assertThat(aggregate.getMessage(), containsString("aggregate"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeywordInsideAnEscapeStringWithAnEscapedQuoteIsNotTakenForAJoin() {
|
||||
preparation.prepare("CREATE MATERIALIZED VIEW v AS SELECT E'it\\'s a join' AS c FROM kds.events",
|
||||
SESSION, backend);
|
||||
}
|
||||
|
||||
@Test
|
||||
void droppingTheLastViewAlsoDropsTheStagingTable() {
|
||||
preparation.prepare(CREATE_VIEW, SESSION, backend);
|
||||
|
||||
Reference in new issue
Block a user