-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Support PostgreSQL hex bytea literals #19263
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
xiangfu0
merged 2 commits into
apache:master
from
xiangfu0:xiangfu0/postgresql-bytea-literals
Sep 22, 2026
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
201 changes: 201 additions & 0 deletions
201
pinot-common/src/main/java/org/apache/pinot/sql/parsers/PostgreSqlCastRewriter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,201 @@ | ||
| /** | ||
| * Licensed to the Apache Software Foundation (ASF) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. The ASF licenses this file | ||
| * to you under the Apache License, Version 2.0 (the | ||
| * "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, | ||
| * software distributed under the License is distributed on an | ||
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| * KIND, either express or implied. See the License for the | ||
| * specific language governing permissions and limitations | ||
| * under the License. | ||
| */ | ||
| package org.apache.pinot.sql.parsers; | ||
|
|
||
| import java.util.List; | ||
| import org.apache.calcite.sql.SqlBinaryStringLiteral; | ||
| import org.apache.calcite.sql.SqlCall; | ||
| import org.apache.calcite.sql.SqlCharStringLiteral; | ||
| import org.apache.calcite.sql.SqlDataTypeSpec; | ||
| import org.apache.calcite.sql.SqlKind; | ||
| import org.apache.calcite.sql.SqlNode; | ||
| import org.apache.calcite.sql.SqlNodeList; | ||
| import org.apache.calcite.sql.fun.SqlLibraryOperators; | ||
| import org.apache.calcite.sql.util.SqlShuttle; | ||
|
|
||
|
|
||
| /// Normalizes PostgreSQL hex-format BYTEA constants (`'\x0102'::bytea` and `CAST('\x0102' AS BYTEA)`) to Calcite | ||
| /// binary literals, so both query engines see the same representation they would get from SQL `X'0102'`. Only quoted | ||
| /// constants are normalized: a dynamic `STRING`-to-`BYTES` conversion would have to be implemented per row in each | ||
| /// engine, and the two would be easy to drift apart. | ||
| /// | ||
| /// Every other use of the PostgreSQL `::` operator is rejected here. That is a deliberate scope limit, not a | ||
| /// technical one — `SqlLibraryOperators.INFIX_CAST` is an ordinary `SqlCastOperator` of kind | ||
| /// [org.apache.calcite.sql.SqlKind#CAST], so `intCol::double` would in fact plan and run like `CAST(intCol AS | ||
| /// DOUBLE)`. Supporting the full operator means committing to `::` type-name semantics across both engines and is | ||
| /// tracked in https://github.com/apache/pinot/issues/19628; until then the grammar accepts `::` only so that this | ||
| /// rewriter can give a clear error instead of a parse failure. Rejecting now keeps that open: relaxing a rejection | ||
| /// later is backward compatible, while narrowing an accepted type would not be. | ||
| /// | ||
| /// The tree is rewritten in place. A plain [SqlShuttle] is copy-on-write: it rebuilds every ancestor of a replaced | ||
| /// node through `SqlOperator.createCall`, and that does not preserve Pinot's own statement classes. A | ||
| /// `SqlPhysicalExplain` comes back as a plain `SqlExplain` and a `SqlPinotCreateMaterializedView` as a `SqlBasicCall`, | ||
| /// which silently changes how the statement is planned or classified. Here only a constant's direct parent is | ||
| /// modified, through `SqlCall.setOperand` or `SqlNodeList.set`, so every other node keeps its identity and class. | ||
| /// Every node under which Pinot's grammar accepts an arbitrary expression supports that. The exceptions are positions | ||
| /// the grammar restricts: `SqlOrderBy` holds its offset and fetch directly, but they must be numeric, and Pinot's own | ||
| /// statement nodes hold queries, identifiers and literals rather than bare expressions. A parent that cannot be | ||
| /// updated in place is rejected with a clear error rather than rebuilt. | ||
| /// | ||
| /// Stateless and safe to share across threads. It mutates only the tree passed to `rewrite`, which must be owned by | ||
| /// the caller, such as a freshly parsed statement. | ||
| final class PostgreSqlCastRewriter extends SqlShuttle { | ||
| private static final PostgreSqlCastRewriter INSTANCE = new PostgreSqlCastRewriter(); | ||
| private static final String HEX_PREFIX = "\\x"; | ||
| private static final String BYTEA_TYPE_NAME = "BYTEA"; | ||
|
|
||
| private PostgreSqlCastRewriter() { | ||
| } | ||
|
|
||
| /// Rewrites `sqlNode` in place and returns it, or returns the replacement literal when `sqlNode` is itself a bytea | ||
| /// constant, as for an expression parsed on its own. | ||
| static SqlNode rewrite(SqlNode sqlNode) { | ||
| return sqlNode.accept(INSTANCE); | ||
| } | ||
|
|
||
| @Override | ||
| public SqlNode visit(SqlNodeList nodeList) { | ||
| for (int i = 0; i < nodeList.size(); i++) { | ||
| SqlNode node = nodeList.get(i); | ||
| if (node != null) { | ||
| SqlNode rewritten = node.accept(this); | ||
| if (rewritten != node) { | ||
| try { | ||
| nodeList.set(i, rewritten); | ||
| } catch (UnsupportedOperationException e) { | ||
| throw unsupportedParent("an immutable node list", e); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| return nodeList; | ||
| } | ||
|
|
||
| @Override | ||
| public SqlNode visit(SqlCall call) { | ||
| List<SqlNode> operands = call.getOperandList(); | ||
| for (int i = 0; i < operands.size(); i++) { | ||
| SqlNode operand = operands.get(i); | ||
| if (operand != null) { | ||
| SqlNode rewritten = operand.accept(this); | ||
| if (rewritten != operand) { | ||
| setOperand(call, i, rewritten); | ||
| } | ||
| } | ||
| } | ||
| return rewriteCast(call); | ||
| } | ||
|
|
||
| private static void setOperand(SqlCall parent, int index, SqlNode replacement) { | ||
| try { | ||
| parent.setOperand(index, replacement); | ||
| } catch (UnsupportedOperationException e) { | ||
| throw unsupportedParent(parent.getKind().toString(), e); | ||
| } | ||
| } | ||
|
|
||
| /// Not reachable from Pinot's grammar today. Fails with a clear error if a future node holds a bytea constant where | ||
| /// it cannot be replaced in place, rather than falling back to rebuilding the node. | ||
| private static SqlCompilationException unsupportedParent(String parent, UnsupportedOperationException cause) { | ||
| return new SqlCompilationException( | ||
| "PostgreSQL BYTEA constants are not supported inside " + parent + "; use X'...' instead", cause); | ||
| } | ||
|
|
||
| /// Returns the binary literal that a supported bytea constant normalizes to, or `call` itself when it is not a cast | ||
| /// this rewriter handles. Throws for every other use of the PostgreSQL `::` operator. | ||
| private static SqlNode rewriteCast(SqlCall call) { | ||
| List<SqlNode> operands = call.getOperandList(); | ||
| boolean infixCast = call.getOperator() == SqlLibraryOperators.INFIX_CAST; | ||
| if (call.getKind() != SqlKind.CAST || operands.size() != 2 || !(operands.get(1) instanceof SqlDataTypeSpec)) { | ||
| if (infixCast) { | ||
| // The target type did not survive as a type spec, e.g. `col::bytea[1]`, where the item accessor binds | ||
| // tighter than `::`. Reject it here rather than letting the malformed call reach the planner. | ||
| throw new SqlCompilationException("Unsupported PostgreSQL :: cast target in '" + call | ||
| + "'. Note that [] binds tighter than ::, so write CAST(<expr> AS <type>) instead"); | ||
| } | ||
| return call; | ||
| } | ||
|
|
||
| SqlDataTypeSpec targetType = (SqlDataTypeSpec) operands.get(1); | ||
| boolean bytea = targetType.getTypeName().isSimple() | ||
| && targetType.getTypeName().getSimple().equalsIgnoreCase(BYTEA_TYPE_NAME); | ||
| if (!bytea) { | ||
| if (infixCast) { | ||
| throw new SqlCompilationException("PostgreSQL-style :: casts are supported only for BYTEA hex constants, " | ||
| + "not for target type '" + targetType.getTypeName() + "'. Use CAST(<expr> AS <type>) instead"); | ||
| } | ||
| return call; | ||
| } | ||
|
|
||
| SqlNode source = operands.get(0); | ||
| if (source instanceof SqlBinaryStringLiteral) { | ||
| return source; | ||
| } | ||
| if (!(source instanceof SqlCharStringLiteral)) { | ||
| throw new SqlCompilationException("BYTEA casts are supported only for quoted hex constants such as " | ||
| + "'\\x0102', not for the expression '" + source + "'. To convert hex strings per row, use " | ||
| + "hexToBytes(<expr>), which takes plain hexadecimal digits without the \\x prefix"); | ||
| } | ||
| String value = ((SqlCharStringLiteral) source).getValueAs(String.class); | ||
| if (!value.startsWith(HEX_PREFIX)) { | ||
| throw invalidByteaLiteral(value); | ||
| } | ||
| return SqlBinaryStringLiteral.createBinaryString(normalizeHex(value), call.getParserPosition()); | ||
| } | ||
|
|
||
| /// Decodes the digits after the leading `\x`. PostgreSQL allows whitespace between byte pairs but not inside one. | ||
| private static String normalizeHex(String literal) { | ||
| String value = literal.substring(HEX_PREFIX.length()); | ||
| StringBuilder hex = new StringBuilder(value.length()); | ||
| for (int i = 0; i < value.length(); i++) { | ||
| char c = value.charAt(i); | ||
| if (isAsciiWhitespace(c)) { | ||
| if ((hex.length() & 1) != 0) { | ||
| throw invalidByteaLiteral(literal); | ||
| } | ||
| } else if (isAsciiHexDigit(c)) { | ||
| hex.append(c); | ||
| } else { | ||
| throw invalidByteaLiteral(literal); | ||
| } | ||
| } | ||
| if ((hex.length() & 1) != 0) { | ||
| throw invalidByteaLiteral(literal); | ||
| } | ||
| return hex.toString(); | ||
| } | ||
|
|
||
| /// Deliberately not `Character.digit(c, 16)`: that also accepts full-width and non-Latin digits such as `A` and | ||
| /// `١`, which PostgreSQL rejects. | ||
| private static boolean isAsciiHexDigit(char c) { | ||
| return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); | ||
| } | ||
|
|
||
| /// Deliberately not `Character.isWhitespace(c)`, for the same reason as [#isAsciiHexDigit]: PostgreSQL only skips | ||
| /// ASCII whitespace between byte pairs, so a non-ASCII space such as U+205F between them is an error. | ||
| private static boolean isAsciiWhitespace(char c) { | ||
| return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == 0x0B; | ||
| } | ||
|
|
||
| private static SqlCompilationException invalidByteaLiteral(String value) { | ||
| return new SqlCompilationException("Invalid PostgreSQL BYTEA constant '" + value + "': only the hex format is " | ||
| + "supported, so it must begin with \\x and contain complete hexadecimal byte pairs, optionally separated by " | ||
| + "ASCII whitespace"); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This runs the shuttle over the whole statement list, so it also walks Pinot's own statement nodes.
SqlShuttlerebuilds every ancestor of a changed node withoperator.createCall(...), and that call returns the operator's own node type.SqlPhysicalExplaininheritsSqlExplain.OPERATOR, whosecreateCallhardcodesnew SqlExplain(...).SqlPinotCreateMaterializedViewuses a bareSqlSpecialOperatorwith nocreateCalloverride, so it rebuilds asSqlBasicCall. One bytea literal anywhere inside such a statement replaces the statement node with a different class.I ran both cases against this branch:
QueryEnvironment:967picks the physical plan withexplain instanceof SqlPhysicalExplain. After the downgrade that test is false, so the broker returns the logical plan. The user gets no error.extractSqlNodeAndOptionsmatches on the node class, so the statement becomes DQL and the DDL path never runs.CAST('\x01' AS BYTEA)reproduces both, so::is not needed to hit this. A bytea literal in a nested subquery of the view body triggers it too.Two ways to correct this:
SqlExplain, rewrite operand 0 in place withsetOperand.createCalloverride that rebuilds the concrete class, and giveSqlPhysicalExplainits ownOPERATOR.Option 1 is smaller. Option 2 also protects these nodes from the next shuttle someone adds.
Please add regression tests that assert the node class and
PinotSqlTypeforEXPLAIN IMPLEMENTATION PLAN FORand forCREATE MATERIALIZED VIEWwith a bytea literal. The current tests cover only a plainSELECT, so both defects pass CI.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks. This was a real bug, and your repro matched what I saw:
SqlPhysicalExplain→SqlExplain, andSqlPinotCreateMaterializedView/DDL →SqlBasicCall/DQL, including with a nested subquery in the view body.Fixed in 6e2b49b with a variant of option 1 that doesn't need to know the statement types. The rewriter no longer rebuilds anything: it replaces only the constant's direct parent in place (
SqlCall.setOperand/SqlNodeList.set), so every other node keeps its identity and class. I preferred this to classifying first because 13 Pinot node types subclassSqlCall, and any of them that holds a query would have hit the same bug. It is also smaller than option 2.For it to be safe, every node that can directly hold a bytea constant has to support
setOperand. I checked Calcite 1.42 and the grammar:SqlBasicCall,SqlNodeList,SqlSelect,SqlCase,SqlJoin,SqlWindow,SqlExplain,SqlWith, and the rest.SqlOrderByoffset/fetch (numeric only),SqlHint,SqlTableRef, and starEXCLUDE/REPLACE(disabled).SqlPinotColumnDeclaration'sDEFAULT, only acceptsLiteral().If a future node does hold a constant somewhere it can't be replaced, the rewriter throws a
SqlCompilationExceptionnaming the node instead of rebuilding it.Regression tests, each of which fails against the previous copy-on-write rewriter:
CalciteSqlParserTest.testPostgreSqlByteaLiteralPreservesStatementNodechecks the node class andPinotSqlTypeforEXPLAIN IMPLEMENTATION PLAN FOR,EXPLAIN PLAN FOR, andCREATE MATERIALIZED VIEW, with the constant both directly in the body and in a nested subquery. Each case runs with'\x01'::bytea,CAST('\x01' AS BYTEA)andX'01', and asserts the constant was still normalized.QueryCompilationTest.testPostgreSqlByteaLiteralKeepsPhysicalExplainchecks the user-visible symptom: theEXPLAIN IMPLEMENTATION PLANoutput must equal theX'01'physical plan. Against the old code it gets the logical plan back.DdlCompilerMaterializedViewTest.definedSqlWithPostgreSqlByteaConstantcompiles a real materialized view end to end and asserts the storeddefinedSQL. Against the old code, the DDL compiler rejects it as an unsupported statement.