This is an automated email from the ASF dual-hosted git repository.
xiangfu0 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git
The following commit(s) were added to refs/heads/master by this push:
new 92468bf3d12 Extract SQL query options without parsing the executable
statement (#20319)
92468bf3d12 is described below
commit 92468bf3d12b53fa50205346bd029b0d1f1840bd
Author: Xiang Fu <[email protected]>
AuthorDate: Fri Nov 20 13:54:13 2026 -0800
Extract SQL query options without parsing the executable statement (#20319)
`CalciteSqlParser.extractQueryOptions` reads SQL options without building
an AST for the executable statement. Callers that need only the options can
reuse Pinot's lexer, `SET` grammar, and trailing `OPTION(...)` handling. `SET`
takes precedence and option names are normalized the same way as in a full
parse. The broker still validates and executes the query.
```java
Map<String, String> options = CalciteSqlParser.extractQueryOptions(
"SET timeoutMs = 300000; SELECT COUNT(*) FROM events");
String timeoutMs = options.get("timeoutMs"); // "300000"
```
HTTP callers can use `RequestUtils.extractQueryOptions(sql, requestJson)`
to include JSON `queryOptions` and `trace` with the same `sqlOptionsMode`
policy as the broker parser.
Use the existing full parser when you need the statement AST, such as for
table routing. The options-only API supports `SET` both before and after the
query.
Local JDK 25 comparison for a leading `SET` and a large `IN` list, with
medians of five measured rounds after three warmups:
| SQL size | Full parse | Options only |
| --- | ---: | ---: |
| 150 characters | 39.8 µs | 11.5 µs |
| 12 KB | 1.64 ms | 0.10 ms |
| 269 KB | 32.49 ms | 2.14 ms |
The legacy `OPTION(...)` matcher also avoids quadratic scanning on long
runs of whitespace. In review, matching a query with 200,000 internal spaces
took about 104 seconds on `master` and 0.5 milliseconds with this change. This
measurement covers the matcher only.
All 114 tests across `CalciteSqlCompilerTest` and `SqlOptionsModeTest`
passed. New tests compare option results with the full parser across syntax and
precedence cases and exercise extraction from a lexically valid query the full
parser rejects. Formatting, license, and Checkstyle checks passed for
`pinot-common`.
---
.../pinot/common/utils/request/RequestUtils.java | 28 ++++-
.../apache/pinot/sql/parsers/CalciteSqlParser.java | 122 +++++++++++++++++++--
.../pinot/sql/parsers/CalciteSqlCompilerTest.java | 31 ++++++
.../pinot/sql/parsers/SqlOptionsModeTest.java | 28 +++++
4 files changed, 198 insertions(+), 11 deletions(-)
diff --git
a/pinot-common/src/main/java/org/apache/pinot/common/utils/request/RequestUtils.java
b/pinot-common/src/main/java/org/apache/pinot/common/utils/request/RequestUtils.java
index 6f8623cc952..6eedf81e9a4 100644
---
a/pinot-common/src/main/java/org/apache/pinot/common/utils/request/RequestUtils.java
+++
b/pinot-common/src/main/java/org/apache/pinot/common/utils/request/RequestUtils.java
@@ -101,12 +101,28 @@ public class RequestUtils {
return sqlNodeAndOptions;
}
+ /// Extracts and merges SQL and request payload options without parsing the
executable SQL statement.
+ /// Callers can pass null when they only need the payload options. The
broker still validates the statement,
+ /// including policies that depend on the statement type.
+ public static Map<String, String> extractQueryOptions(@Nullable String
query, JsonNode request) {
+ Map<String, String> sqlOptions = query != null ?
CalciteSqlParser.extractQueryOptions(query) : new HashMap<>();
+ mergeOptions(sqlOptions, getRequestOptions(request), false);
+ return sqlOptions;
+ }
+
/// Merges the request payload options (`queryOptions` and `trace`) into the
options parsed from the SQL. The SQL
/// options take precedence, unless the request sets
[Request.QueryOptionKey#SQL_OPTIONS_MODE] to `IGNORE` (the SQL
/// options are dropped, or a DELETE statement fails when it carries any) or
`REJECT` (the query fails when it
/// carries any).
@VisibleForTesting
public static void setOptions(SqlNodeAndOptions sqlNodeAndOptions, JsonNode
jsonRequest) {
+ Map<String, String> requestOptions = getRequestOptions(jsonRequest);
+ if (!requestOptions.isEmpty()) {
+ setOptions(sqlNodeAndOptions, requestOptions);
+ }
+ }
+
+ private static Map<String, String> getRequestOptions(JsonNode jsonRequest) {
Map<String, String> requestOptions = new HashMap<>();
if (jsonRequest.has(Request.QUERY_OPTIONS)) {
requestOptions.putAll(getOptionsFromString(jsonRequest.get(Request.QUERY_OPTIONS).asText()));
@@ -115,25 +131,29 @@ public class RequestUtils {
requestOptions.put(Request.TRACE, "true");
}
if (requestOptions.isEmpty()) {
- return;
+ return requestOptions;
}
LOGGER.debug("Query options are set to: {}", requestOptions);
- setOptions(sqlNodeAndOptions,
QueryOptionsUtils.resolveCaseInsensitiveOptions(requestOptions));
+ return QueryOptionsUtils.resolveCaseInsensitiveOptions(requestOptions);
}
/// Merges the given options into the options parsed from the SQL, like
[#setOptions(SqlNodeAndOptions, JsonNode)]
/// does with the options of the request payload. The keys of the given
options must be resolved, see
/// [QueryOptionsUtils#resolveCaseInsensitiveOptions(Map)].
public static void setOptions(SqlNodeAndOptions sqlNodeAndOptions,
Map<String, String> requestOptions) {
+ mergeOptions(sqlNodeAndOptions.getOptions(), requestOptions,
sqlNodeAndOptions.getSqlNode() instanceof SqlDelete);
+ }
+
+ private static void mergeOptions(Map<String, String> sqlOptions, Map<String,
String> requestOptions,
+ boolean isDelete) {
SqlOptionsMode sqlOptionsMode =
QueryOptionsUtils.getSqlOptionsMode(requestOptions);
- Map<String, String> sqlOptions = sqlNodeAndOptions.getOptions();
if (sqlOptionsMode != SqlOptionsMode.ALLOW && !sqlOptions.isEmpty()) {
if (sqlOptionsMode == SqlOptionsMode.REJECT) {
throw QueryErrorCode.QUERY_VALIDATION.asException(
"Query options are not allowed in the SQL for this request, found:
" + sqlOptions.keySet());
}
// Dropping a DELETE option (e.g. dryRun) would change its effect
- if (sqlNodeAndOptions.getSqlNode() instanceof SqlDelete) {
+ if (isDelete) {
throw QueryErrorCode.QUERY_VALIDATION.asException(
"SQL options cannot be ignored for DELETE, found: " +
sqlOptions.keySet());
}
diff --git
a/pinot-common/src/main/java/org/apache/pinot/sql/parsers/CalciteSqlParser.java
b/pinot-common/src/main/java/org/apache/pinot/sql/parsers/CalciteSqlParser.java
index 1312b2ac3a1..720453c3eff 100644
---
a/pinot-common/src/main/java/org/apache/pinot/sql/parsers/CalciteSqlParser.java
+++
b/pinot-common/src/main/java/org/apache/pinot/sql/parsers/CalciteSqlParser.java
@@ -55,6 +55,7 @@ import org.apache.calcite.sql.fun.SqlBetweenOperator;
import org.apache.calcite.sql.fun.SqlCase;
import org.apache.calcite.sql.fun.SqlLikeOperator;
import org.apache.calcite.sql.parser.SqlAbstractParserImpl;
+import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.sql.validate.SqlConformanceEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.pinot.common.function.scalar.arithmetic.NegateScalarFunction;
@@ -75,6 +76,7 @@ import org.apache.pinot.sql.FilterKind;
import org.apache.pinot.sql.parsers.parser.GrowingCharStream;
import org.apache.pinot.sql.parsers.parser.SqlInsertFromFile;
import org.apache.pinot.sql.parsers.parser.SqlParserImpl;
+import org.apache.pinot.sql.parsers.parser.SqlParserImplConstants;
import org.apache.pinot.sql.parsers.parser.SqlPinotCreateMaterializedView;
import org.apache.pinot.sql.parsers.parser.SqlPinotCreateTable;
import org.apache.pinot.sql.parsers.parser.SqlPinotDropMaterializedView;
@@ -83,6 +85,7 @@ import
org.apache.pinot.sql.parsers.parser.SqlPinotShowCreateMaterializedView;
import org.apache.pinot.sql.parsers.parser.SqlPinotShowCreateTable;
import org.apache.pinot.sql.parsers.parser.SqlPinotShowMaterializedViews;
import org.apache.pinot.sql.parsers.parser.SqlPinotShowTables;
+import org.apache.pinot.sql.parsers.parser.Token;
import org.apache.pinot.sql.parsers.rewriter.QueryRewriter;
import org.apache.pinot.sql.parsers.rewriter.QueryRewriterFactory;
import org.slf4j.Logger;
@@ -113,8 +116,9 @@ public class CalciteSqlParser {
//
// Multiple OPTIONs is also supported by:
// `OPTION (<k1> = <v1>, <k2> = <v2>, <k3> = <v3>)`
+ // Start at OPTION itself so the unanchored search does not rescan leading
whitespace.
private static final Pattern OPTIONS_REGEX_PATTEN =
- Pattern.compile("\\s*option\\s*\\(([^)]+)\\)\\s*;?\\s*\\Z",
Pattern.CASE_INSENSITIVE);
+ Pattern.compile("option\\s*+\\(([^)]++)\\)\\s*+;?\\s*+\\Z",
Pattern.CASE_INSENSITIVE);
public static SqlNodeAndOptions compileToSqlNodeAndOptions(String sql)
throws SqlCompilationException {
@@ -138,7 +142,7 @@ public class CalciteSqlParser {
if (matcher.find()) {
ignoredOptionsStart = matcher.start(1);
ignoredOptionsEnd = matcher.end(1);
- sql = sql.substring(0, matcher.start());
+ sql = stripLegacyOptionSuffix(sql, matcher.start());
}
} else {
options = extractOptionsFromSql(sql);
@@ -180,6 +184,101 @@ public class CalciteSqlParser {
}
}
+ /// Extracts SQL `SET` statements and the legacy `OPTION(...)` suffix
without building the executable statement's AST.
+ /// Uses the same lexer and option parser as
[#compileToSqlNodeAndOptions(String)], including quoted identifiers,
+ /// literals, comments, and scoped `ALTER SESSION/SYSTEM SET` statements.
`SET` options take precedence over `OPTION`.
+ ///
+ /// This is not SQL validation: executable statements and broker
query-option policies must still be validated by the
+ /// broker. In particular, successfully extracting options does not mean the
SQL is executable.
+ public static Map<String, String> extractQueryOptions(String sql) {
+ sql = ParserUtils.sanitizeSql(sql);
+ List<String> legacyOptions = List.of();
+ Matcher matcher = OPTIONS_REGEX_PATTEN.matcher(sql);
+ if (matcher.find()) {
+ SqlOptionsMode legacyOptionSyntaxMode =
QueryOptionsUtils.getLegacyOptionSyntaxMode();
+ if (legacyOptionSyntaxMode != SqlOptionsMode.IGNORE) {
+ legacyOptions = List.of(matcher.group(1));
+ if (legacyOptionSyntaxMode == SqlOptionsMode.REJECT) {
+ throw new SqlCompilationException("Legacy OPTION(...) query options
are not allowed on this cluster, use "
+ + "'SET <key> = <value>;' statements instead: " + legacyOptions);
+ }
+ }
+ sql = stripLegacyOptionSuffix(sql, matcher.start());
+ }
+ try {
+ Map<String, String> options = new HashMap<>();
+ SqlParserImpl sqlParser = newSqlParser(sql);
+ SqlParserPos lastSeparator = findLastInternalSeparator(sql);
+ Token token = sqlParser.getToken(1);
+ while (token.kind != SqlParserImplConstants.EOF) {
+ if (token.kind == SqlParserImplConstants.SET || token.kind ==
SqlParserImplConstants.RESET
+ || (token.kind == SqlParserImplConstants.ALTER
+ && (sqlParser.getToken(2).kind ==
SqlParserImplConstants.SESSION
+ || sqlParser.getToken(2).kind ==
SqlParserImplConstants.SYSTEM)
+ && (sqlParser.getToken(3).kind == SqlParserImplConstants.SET
+ || sqlParser.getToken(3).kind ==
SqlParserImplConstants.RESET))) {
+ extractSetOption((SqlSetOption) sqlParser.SqlStmt(), options);
+ token = sqlParser.getToken(1);
+ if (token.kind != SqlParserImplConstants.EOF && token.kind !=
SqlParserImplConstants.SEMICOLON) {
+ throw new SqlCompilationException("Expected ';' after SET query
option");
+ }
+ } else {
+ // Skip the body if no later SET can follow. Otherwise use the lexer
to distinguish statement separators
+ // from semicolons in literals and comments.
+ if (token.beginLine > lastSeparator.getLineNum()
+ || (token.beginLine == lastSeparator.getLineNum()
+ && token.beginColumn > lastSeparator.getColumnNum())) {
+ break;
+ }
+ while (token.kind != SqlParserImplConstants.EOF && token.kind !=
SqlParserImplConstants.SEMICOLON) {
+ sqlParser.getNextToken();
+ token = sqlParser.getToken(1);
+ }
+ }
+ if (token.kind == SqlParserImplConstants.EOF) {
+ break;
+ }
+ sqlParser.getNextToken();
+ token = sqlParser.getToken(1);
+ }
+ Map<String, String> resolvedOptions =
QueryOptionsUtils.resolveCaseInsensitiveOptions(options);
+ if (!legacyOptions.isEmpty()) {
+
QueryOptionsUtils.resolveCaseInsensitiveOptions(extractOptionsMap(legacyOptions))
+ .forEach(resolvedOptions::putIfAbsent);
+ }
+ return resolvedOptions;
+ } catch (Throwable e) {
+ throw new SqlCompilationException(
+ "Caught exception while extracting query options: " + sql + ": " +
e.getMessage(), e);
+ }
+ }
+
+ private static SqlParserPos findLastInternalSeparator(String sql) {
+ // A terminal semicolon cannot introduce another statement.
+ int offset = sql.lastIndexOf(';', sql.length() - 2);
+ if (offset < 0) {
+ return SqlParserPos.ZERO;
+ }
+ // Match JavaCC's CR, LF and CRLF line endings. newSqlParser sets the tab
size to one.
+ int line = 1;
+ int lineStart = 0;
+ for (int i = 0; i < offset; i++) {
+ char c = sql.charAt(i);
+ if (c == '\n' || (c == '\r' && sql.charAt(i + 1) != '\n')) {
+ line++;
+ lineStart = i + 1;
+ }
+ }
+ return new SqlParserPos(line, offset - lineStart + 1);
+ }
+
+ private static void extractSetOption(SqlSetOption sqlNode, Map<String,
String> options) {
+ List<SqlNode> operandList = sqlNode.getOperandList();
+ SqlIdentifier key = (SqlIdentifier) operandList.get(1);
+ SqlLiteral value = (SqlLiteral) operandList.get(2);
+ options.put(key.getSimple(), value.toValue());
+ }
+
private static SqlNodeAndOptions extractSqlNodeAndOptions(SqlNodeList
sqlNodeList) {
PinotSqlType sqlType = null;
SqlNode statementNode = null;
@@ -216,10 +315,7 @@ public class CalciteSqlParser {
}
} else if (sqlNode instanceof SqlSetOption) {
// extract options, these are non-execution statements
- List<SqlNode> operandList = ((SqlSetOption) sqlNode).getOperandList();
- SqlIdentifier key = (SqlIdentifier) operandList.get(1);
- SqlLiteral value = (SqlLiteral) operandList.get(2);
- options.put(key.getSimple(), value.toValue());
+ extractSetOption((SqlSetOption) sqlNode, options);
} else {
// default extract query statement (execution statement)
if (sqlType == null) {
@@ -907,7 +1003,19 @@ public class CalciteSqlParser {
@Deprecated
private static String removeOptionsFromSql(String sql) {
Matcher matcher = OPTIONS_REGEX_PATTEN.matcher(sql);
- return matcher.replaceAll("");
+ return matcher.find() ? stripLegacyOptionSuffix(sql, matcher.start()) :
sql;
+ }
+
+ private static String stripLegacyOptionSuffix(String sql, int optionStart) {
+ // Preserve the same ASCII whitespace removal as the old leading \s* in
the suffix matcher.
+ while (optionStart > 0) {
+ char c = sql.charAt(optionStart - 1);
+ if (c != ' ' && (c < '\t' || c > '\r')) {
+ break;
+ }
+ optionStart--;
+ }
+ return sql.substring(0, optionStart);
}
@Deprecated
diff --git
a/pinot-common/src/test/java/org/apache/pinot/sql/parsers/CalciteSqlCompilerTest.java
b/pinot-common/src/test/java/org/apache/pinot/sql/parsers/CalciteSqlCompilerTest.java
index 1a4ef105d56..869bc9a7a8f 100644
---
a/pinot-common/src/test/java/org/apache/pinot/sql/parsers/CalciteSqlCompilerTest.java
+++
b/pinot-common/src/test/java/org/apache/pinot/sql/parsers/CalciteSqlCompilerTest.java
@@ -23,6 +23,7 @@ import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.calcite.sql.SqlDelete;
import org.apache.calcite.sql.SqlIdentifier;
@@ -47,6 +48,7 @@ import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.expectThrows;
/// Some tests for the SQL compiler.
@@ -972,6 +974,35 @@ public class CalciteSqlCompilerTest {
}
}
+ @Test
+ public void testExtractQueryOptionsMatchesFullParser() {
+ for (String sql : List.of(
+ "SELECT * FROM foo",
+ "sEt \"TiMeOuTmS\" = '120000'; SELECT * FROM foo",
+ "SET timeoutMs=120000; SELECT * FROM foo; SET timeoutMs=240000;",
+ "SET a=1;" + "\t".repeat(8) + "SELECT 'x;y' FROM t; SET b=2",
+ "SELECT * FROM foo OPTION(timeoutMs=300000, trace=true); -- trailing
comment",
+ "SELECT * FROM foo\u000BOPTION(timeoutMs=300000)",
+ "SET timeoutMs=120000; SELECT * FROM foo OPTION(timeoutMs=300000,
trace=true)",
+ "SET \"custom:key\"='a:b;''c'; SELECT \"col:;\"\"name\", 'it''s; SET
timeoutMs=7;' FROM foo; "
+ + "/* SET timeoutMs=8; */ SET /* comment */ timeoutMs=120000; --
SET timeoutMs=9;",
+ "ALTER SESSION SET timeoutMs=120000; ALTER SYSTEM SET trace=true;
SELECT * FROM foo")) {
+ assertEquals(CalciteSqlParser.extractQueryOptions(sql),
+ CalciteSqlParser.compileToSqlNodeAndOptions(sql).getOptions(), sql);
+ }
+ }
+
+ @Test
+ public void testExtractQueryOptionsWithoutParsingQueryBody() {
+ String sql = "SET timeoutMs=120000; SELECT FROM WHERE
OPTION(timeoutMs=300000, trace=true)";
+
+ expectThrows(SqlCompilationException.class, () ->
CalciteSqlParser.compileToSqlNodeAndOptions(sql));
+ assertEquals(CalciteSqlParser.extractQueryOptions(sql),
Map.of("timeoutMs", "120000", "trace", "true"));
+
+ String multiSet = "SET timeoutMs=120000;\r\nSET trace=true;\r\tSELECT /*
unterminated comment";
+ assertEquals(CalciteSqlParser.extractQueryOptions(multiSet),
Map.of("timeoutMs", "120000", "trace", "true"));
+ }
+
@Test
public void testRemoveComments() {
testRemoveComments("select * from myTable", "select * from myTable");
diff --git
a/pinot-common/src/test/java/org/apache/pinot/sql/parsers/SqlOptionsModeTest.java
b/pinot-common/src/test/java/org/apache/pinot/sql/parsers/SqlOptionsModeTest.java
index b0f67f20949..385e58a14d8 100644
---
a/pinot-common/src/test/java/org/apache/pinot/sql/parsers/SqlOptionsModeTest.java
+++
b/pinot-common/src/test/java/org/apache/pinot/sql/parsers/SqlOptionsModeTest.java
@@ -56,6 +56,7 @@ public class SqlOptionsModeTest {
public void testIgnoredLegacyOptionSyntaxIsStrippedAndDropped() {
QueryOptionsUtils.setLegacyOptionSyntaxMode(SqlOptionsMode.IGNORE);
assertEquals(sqlOptionsOf("select * from vegetables
OPTION(timeoutMs=1000)"), Map.of());
+ assertEquals(CalciteSqlParser.extractQueryOptions("select * from
vegetables OPTION(timeoutMs=1000)"), Map.of());
// INSERT is unaffected: its suffix is dropped silently, as always
assertEquals(sqlOptionsOf("INSERT INTO db.tbl FROM FILE
'file:///tmp/file1' OPTION(taskName=myTask-1)"), Map.of());
// SET statements are unaffected
@@ -86,6 +87,8 @@ public class SqlOptionsModeTest {
for (String sql : List.of("select * from vegetables
OPTION(timeoutMs=1000)",
"INSERT INTO db.tbl FROM FILE 'file:///tmp/file1'
OPTION(taskName=myTask-1)")) {
SqlCompilationException e = expectThrows(SqlCompilationException.class,
() -> sqlOptionsOf(sql));
+ assertEquals(expectThrows(SqlCompilationException.class,
+ () -> CalciteSqlParser.extractQueryOptions(sql)).getMessage(),
e.getMessage());
assertTrue(e.getMessage().contains("OPTION(...)"), e.getMessage());
assertTrue(e.getMessage().contains("SET"), e.getMessage());
}
@@ -161,6 +164,31 @@ public class SqlOptionsModeTest {
assertTrue(e.getMessage().contains("bogus"), e.getMessage());
}
+ @Test
+ public void testExtractQueryOptionsHonorsRequestMode() {
+ String sql = "SET timeoutMs=1000; SELECT * FROM vegetables
OPTION(skipUpsert=true)";
+ for (String queryOptions : List.of("timeoutMs=2000",
"timeoutMs=2000;sqlOptionsMode=allow",
+ "timeoutMs=2000;SQLOPTIONSMODE=IgNoRe")) {
+ ObjectNode request =
JsonUtils.newObjectNode().put(Request.QUERY_OPTIONS,
queryOptions).put(Request.TRACE, true);
+ assertEquals(RequestUtils.extractQueryOptions(sql, request),
RequestUtils.parseQuery(sql, request).getOptions(),
+ queryOptions);
+ }
+ ObjectNode request = JsonUtils.newObjectNode().put(Request.QUERY_OPTIONS,
"timeoutMs=2000");
+ assertEquals(RequestUtils.extractQueryOptions(null, request),
Map.of("timeoutMs", "2000"));
+ }
+
+ @Test
+ public void testExtractQueryOptionsRejectsForbiddenOptionsAndInvalidModes() {
+ String sql = "SET timeoutMs=1000; SELECT * FROM vegetables";
+ for (String mode : List.of("reject", "bogus")) {
+ ObjectNode request =
+ JsonUtils.newObjectNode().put(Request.QUERY_OPTIONS,
"timeoutMs=2000;sqlOptionsMode=" + mode);
+ QueryException expected = expectThrows(QueryException.class, () ->
RequestUtils.parseQuery(sql, request));
+ QueryException actual = expectThrows(QueryException.class, () ->
RequestUtils.extractQueryOptions(sql, request));
+ assertEquals(actual.getErrorCode(), expected.getErrorCode());
+ }
+ }
+
private static Map<String, String> sqlOptionsOf(String sql) {
return CalciteSqlParser.compileToSqlNodeAndOptions(sql).getOptions();
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]