You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pinot.apache.org by "Jackie-Jiang (via GitHub)" <gi...@apache.org> on 2023/09/02 06:53:55 UTC
[GitHub] [pinot] Jackie-Jiang commented on a diff in pull request #11438: [multistage] Evaluate literal expression during query parsing
Jackie-Jiang commented on code in PR #11438:
URL: https://github.com/apache/pinot/pull/11438#discussion_r1313732891
##########
pinot-common/src/main/java/org/apache/pinot/common/request/context/LiteralContext.java:
##########
@@ -136,6 +137,16 @@ public LiteralContext(Literal literal) {
}
_value = literal.getFieldValue().toString();
break;
+ case BIG_DECIMAL_VALUE:
+ _type = FieldSpec.DataType.BIG_DECIMAL;
+ _value = literal.getBigDecimalValue();
Review Comment:
I think we should also store `_value` as `BigDecimal`. `byte[]` is just the on-the-wire type, but real type
##########
pinot-query-planner/src/test/resources/queries/LiteralEvaluationPlans.json:
##########
@@ -0,0 +1,161 @@
+{
+ "literal_evaluation_tests": {
+ "queries": [
+ {
+ "description": "Select arithmetic expression",
+ "sql": "EXPLAIN PLAN FOR SELECT 5*6,5+6 FROM d",
+ "output": [
+ "Execution Plan",
+ "\nLogicalProject(EXPR$0=[30.0], EXPR$1=[11.0])",
+ "\n LogicalTableScan(table=[[d]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "Select fromdatetime function",
+ "sql": "EXPLAIN PLAN FOR SELECT FROMDATETIME( '1997-02-01 00:00:00', 'yyyy-MM-dd HH:mm:ss') FROM d",
+ "output": [
+ "Execution Plan",
+ "\nLogicalProject(EXPR$0=[1997-02-01 00:00:00])",
+ "\n LogicalTableScan(table=[[d]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "Select two level function to one literal",
+ "sql": "EXPLAIN PLAN FOR SELECT dateTrunc('MONTH', FROMDATETIME( '1997-02-01 00:00:00', 'yyyy-MM-dd HH:mm:ss')) FROM d",
+ "output": [
+ "Execution Plan",
+ "\nLogicalProject(EXPR$0=[CAST(854755200000:BIGINT):BIGINT])",
+ "\n LogicalTableScan(table=[[d]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "Eval inner function to literal",
+ "sql": "EXPLAIN PLAN FOR SELECT timestampDiff(DAY, CAST(ts as TIMESTAMP), CAST(dateTrunc('MONTH', FROMDATETIME('1997-02-01 00:00:00', 'yyyy-MM-dd HH:mm:ss')) as TIMESTAMP)) FROM d",
+ "output": [
+ "Execution Plan",
+ "\nLogicalProject(EXPR$0=[TIMESTAMPDIFF(FLAG(DAY), CAST($6):TIMESTAMP(0) NOT NULL, CAST(854755200000:BIGINT):TIMESTAMP(0))])",
+ "\n LogicalTableScan(table=[[d]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "Select fromdatetime function in where clause",
+ "sql": "EXPLAIN PLAN FOR SELECT * FROM d WHERE CAST(ts AS TIMESTAMP) = FROMDATETIME('2019-01-01 00:00:00', 'yyyy-MM-dd HH:mm:ss')",
+ "output": [
+ "Execution Plan",
+ "\nLogicalFilter(condition=[=(CAST($6):TIMESTAMP(0) NOT NULL, 2019-01-01 00:00:00)])",
+ "\n LogicalTableScan(table=[[d]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "Select with dateTrunc literal function",
+ "sql": "EXPLAIN PLAN FOR SELECT dateTrunc('MONTH', 854755200000) AS day FROM a",
+ "output": [
+ "Execution Plan",
+ "\nLogicalProject(day=[CAST(854755200000:BIGINT):BIGINT])",
+ "\n LogicalTableScan(table=[[a]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "Eval Filter literal function",
+ "sql": "EXPLAIN PLAN FOR SELECT * FROM a WHERE dateTrunc('MONTH', ts) = dateTrunc('MONTH', FROMDATETIME('2019-01-01 00:00:00', 'yyyy-MM-dd HH:mm:ss'))",
+ "output": [
+ "Execution Plan",
+ "\nLogicalFilter(condition=[=(DATETRUNC('MONTH', $6), 1546300800000)])",
+ "\n LogicalTableScan(table=[[a]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "upper case literal function",
+ "sql": "EXPLAIN PLAN FOR SELECT upper('month') FROM a",
+ "output": [
+ "Execution Plan",
+ "\nLogicalProject(EXPR$0=['MONTH'])",
+ "\n LogicalTableScan(table=[[a]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "concat literal function",
+ "sql": "EXPLAIN PLAN FOR SELECT concat('month', ' 1') FROM a",
+ "output": [
+ "Execution Plan",
+ "\nLogicalProject(EXPR$0=[CAST('month 1':VARCHAR):VARCHAR])",
+ "\n LogicalTableScan(table=[[a]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "substr literal function",
+ "sql": "EXPLAIN PLAN FOR SELECT substr('month',2) FROM a",
+ "output": [
+ "Execution Plan",
+ "\nLogicalProject(EXPR$0=[CAST('nth':VARCHAR):VARCHAR])",
+ "\n LogicalTableScan(table=[[a]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "chained string functions on literal",
+ "sql": "EXPLAIN PLAN FOR SELECT upper(lower(upper(substr('month',2)))) FROM a",
+ "output": [
+ "Execution Plan",
+ "\nLogicalProject(EXPR$0=[CAST('NTH':VARCHAR):VARCHAR])",
+ "\n LogicalTableScan(table=[[a]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "geoToH3 functions",
+ "sql": "EXPLAIN PLAN FOR Select geoToH3(ST_point(20,102),5) FROM a",
+ "output": [
+ "Execution Plan",
+ "\nLogicalProject(EXPR$0=[599041711439609855:BIGINT])",
+ "\n LogicalTableScan(table=[[a]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "geoToH3 functions",
+ "sql": "EXPLAIN PLAN FOR Select ST_Point(20, 10, 1) FROM a",
+ "output": [
+ "Execution Plan",
+ "\nLogicalProject(EXPR$0=[X'8040340000000000004024000000000000':VARBINARY])",
+ "\n LogicalTableScan(table=[[a]])",
+ "\n"
+ ]
+ },
+ {
+ "description": "St distance with two bytes literals",
+ "sql": "EXPLAIN PLAN FOR Select ST_Distance(X'8040340000000000004024000000000000', ST_Point(-122, 37.5, 1)) FROM a",
Review Comment:
This is not PostgreSQL format. Does the current parser support PostgreSQL format? https://www.postgresql.org/docs/current/datatype-binary.html
##########
pinot-query-planner/src/main/java/org/apache/calcite/rel/rules/PinotEvaluateLiteralRule.java:
##########
@@ -0,0 +1,249 @@
+/**
+ * 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.calcite.rel.rules;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Collectors;
+import org.apache.calcite.avatica.util.ByteString;
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.Filter;
+import org.apache.calcite.rel.core.Project;
+import org.apache.calcite.rel.logical.LogicalFilter;
+import org.apache.calcite.rel.logical.LogicalProject;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexShuttle;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.calcite.util.NlsString;
+import org.apache.calcite.util.TimestampString;
+import org.apache.pinot.common.function.FunctionInfo;
+import org.apache.pinot.common.function.FunctionInvoker;
+import org.apache.pinot.common.function.FunctionRegistry;
+import org.apache.pinot.spi.utils.TimestampUtils;
+import org.apache.pinot.sql.parsers.SqlCompilationException;
+
+
+/**
+ * SingleValueAggregateRemoveRule that matches an Aggregate function SINGLE_VALUE and remove it
+ *
+ */
+public class PinotEvaluateLiteralRule extends RelOptRule {
+ public static final PinotEvaluateLiteralRule INSTANCE =
+ new PinotEvaluateLiteralRule(PinotRuleUtils.PINOT_REL_FACTORY);
+
+ public PinotEvaluateLiteralRule(RelBuilderFactory factory) {
+ super(operand(RelNode.class, any()), factory, null);
+ }
+
+ @Override
+ public boolean matches(RelOptRuleCall call) {
+ // Traverse the relational expression using a RexShuttle visitor
+ AtomicBoolean hasLiteralOnlyCall = new AtomicBoolean(false);
+ call.rel(0).accept(new RexShuttle() {
+ @Override
+ public RexNode visitCall(RexCall call) {
+ // Check if all operands are RexLiteral
+ if (call.operands.stream().allMatch(operand -> (operand instanceof RexLiteral))) {
+ // If all operands are literals, this call can be evaluated
+ hasLiteralOnlyCall.set(true);
+ // early terminate if we found one evaluate call
+ return call;
+ }
+ call.operands.forEach(operand -> {
+ if (hasLiteralOnlyCall.get()) {
+ // Early terminate if we already found one evaluate call
+ return;
+ }
+ // Recursively call visitCall on all RexCall operands
+ if (operand instanceof RexCall) {
+ visitCall((RexCall) operand);
+ }
+ });
+ // Return the call to continue traversal
+ return call;
+ }
+ });
+ return hasLiteralOnlyCall.get();
+ }
+
+ @Override
+ public void onMatch(RelOptRuleCall call) {
+ RelNode rootRelNode = call.rel(0);
+ RexBuilder rexBuilder = rootRelNode.getCluster().getRexBuilder();
+ Map<RexNode, RexNode> evaluatedResults = new HashMap<>();
+
+ // Recursively evaluate all the calls with Literal only operands from bottom up
+ // Traverse the relational expression using a RexShuttle visitor
+ rootRelNode.accept(new RexShuttle() {
+ @Override
+ public RexNode visitCall(RexCall call) {
+ call.operands.forEach(operand -> {
+ if (operand instanceof RexCall) {
+ visitCall((RexCall) operand);
+ }
+ });
+ // Check if all operands are RexLiteral
+ if (call.operands.stream().allMatch(operand -> operand instanceof RexLiteral)) {
+ // If all operands are literals or already evaluated, this call can be evaluated
+ return evaluateLiteralOnlyFunction(rexBuilder, call, evaluatedResults);
+ }
+ // Return the call to continue traversal
+ return call;
+ }
+ });
+
+ RelNode newRelNode = null;
+ if (rootRelNode instanceof Project) {
+ newRelNode = constructNewRelNode(rexBuilder, evaluatedResults, (Project) rootRelNode);
+ }
+ if (rootRelNode instanceof Filter) {
+ newRelNode = constructNewRelNode(evaluatedResults, (Filter) rootRelNode);
+ }
Review Comment:
Do we need to do this? I think the result of the visit is the new node
```suggestion
RelNode newRelNode = rootRelNode.accept(new RexShuttle() {
@Override
public RexNode visitCall(RexCall call) {
call.operands.forEach(operand -> {
if (operand instanceof RexCall) {
visitCall((RexCall) operand);
}
});
// Check if all operands are RexLiteral
if (call.operands.stream().allMatch(operand -> operand instanceof RexLiteral)) {
// If all operands are literals or already evaluated, this call can be evaluated
return evaluateLiteralOnlyFunction(rexBuilder, call, evaluatedResults);
}
// Return the call to continue traversal
return call;
}
});
```
##########
pinot-common/src/main/java/org/apache/pinot/common/utils/request/RequestUtils.java:
##########
@@ -174,10 +176,23 @@ public static Expression getLiteralExpression(String value) {
public static Expression getLiteralExpression(byte[] value) {
Expression expression = createNewLiteralExpression();
+ // TODO: Set the binary value directly instead of converting it to hex string.
Review Comment:
(minor) Add comment stating this is for backward compatibility, and we can switch one release after server side can directly use binary
##########
pinot-common/src/main/java/org/apache/pinot/common/utils/request/RequestUtils.java:
##########
@@ -178,6 +178,12 @@ public static Expression getLiteralExpression(byte[] value) {
return expression;
}
+ public static Expression getLiteralExpression(com.google.protobuf.ByteString value) {
Review Comment:
I see. Should we import it, or is it intentional to keep the full class path?
##########
pinot-query-planner/src/main/java/org/apache/calcite/rel/rules/PinotEvaluateLiteralRule.java:
##########
@@ -0,0 +1,249 @@
+/**
+ * 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.calcite.rel.rules;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Collectors;
+import org.apache.calcite.avatica.util.ByteString;
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.Filter;
+import org.apache.calcite.rel.core.Project;
+import org.apache.calcite.rel.logical.LogicalFilter;
+import org.apache.calcite.rel.logical.LogicalProject;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexShuttle;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.calcite.util.NlsString;
+import org.apache.calcite.util.TimestampString;
+import org.apache.pinot.common.function.FunctionInfo;
+import org.apache.pinot.common.function.FunctionInvoker;
+import org.apache.pinot.common.function.FunctionRegistry;
+import org.apache.pinot.spi.utils.TimestampUtils;
+import org.apache.pinot.sql.parsers.SqlCompilationException;
+
+
+/**
+ * SingleValueAggregateRemoveRule that matches an Aggregate function SINGLE_VALUE and remove it
+ *
+ */
+public class PinotEvaluateLiteralRule extends RelOptRule {
+ public static final PinotEvaluateLiteralRule INSTANCE =
+ new PinotEvaluateLiteralRule(PinotRuleUtils.PINOT_REL_FACTORY);
+
+ public PinotEvaluateLiteralRule(RelBuilderFactory factory) {
+ super(operand(RelNode.class, any()), factory, null);
+ }
+
+ @Override
+ public boolean matches(RelOptRuleCall call) {
+ // Traverse the relational expression using a RexShuttle visitor
+ AtomicBoolean hasLiteralOnlyCall = new AtomicBoolean(false);
+ call.rel(0).accept(new RexShuttle() {
+ @Override
+ public RexNode visitCall(RexCall call) {
+ // Check if all operands are RexLiteral
+ if (call.operands.stream().allMatch(operand -> (operand instanceof RexLiteral))) {
+ // If all operands are literals, this call can be evaluated
+ hasLiteralOnlyCall.set(true);
+ // early terminate if we found one evaluate call
+ return call;
+ }
+ call.operands.forEach(operand -> {
+ if (hasLiteralOnlyCall.get()) {
+ // Early terminate if we already found one evaluate call
+ return;
+ }
+ // Recursively call visitCall on all RexCall operands
+ if (operand instanceof RexCall) {
+ visitCall((RexCall) operand);
+ }
+ });
+ // Return the call to continue traversal
+ return call;
+ }
+ });
+ return hasLiteralOnlyCall.get();
+ }
+
+ @Override
+ public void onMatch(RelOptRuleCall call) {
+ RelNode rootRelNode = call.rel(0);
+ RexBuilder rexBuilder = rootRelNode.getCluster().getRexBuilder();
+ Map<RexNode, RexNode> evaluatedResults = new HashMap<>();
+
+ // Recursively evaluate all the calls with Literal only operands from bottom up
+ // Traverse the relational expression using a RexShuttle visitor
+ rootRelNode.accept(new RexShuttle() {
+ @Override
+ public RexNode visitCall(RexCall call) {
+ call.operands.forEach(operand -> {
+ if (operand instanceof RexCall) {
+ visitCall((RexCall) operand);
+ }
+ });
+ // Check if all operands are RexLiteral
+ if (call.operands.stream().allMatch(operand -> operand instanceof RexLiteral)) {
+ // If all operands are literals or already evaluated, this call can be evaluated
+ return evaluateLiteralOnlyFunction(rexBuilder, call, evaluatedResults);
+ }
+ // Return the call to continue traversal
+ return call;
+ }
+ });
+
+ RelNode newRelNode = null;
+ if (rootRelNode instanceof Project) {
+ newRelNode = constructNewRelNode(rexBuilder, evaluatedResults, (Project) rootRelNode);
+ }
+ if (rootRelNode instanceof Filter) {
+ newRelNode = constructNewRelNode(evaluatedResults, (Filter) rootRelNode);
+ }
+ call.transformTo(newRelNode);
+ }
+
+ private RelNode constructNewRelNode(RexBuilder rexBuilder, Map<RexNode, RexNode> evaluatedResults, Project project) {
+ List<RexNode> oldProjects = project.getProjects();
+ List<RexNode> newProjects = new ArrayList<>();
+ for (RexNode oldProject : oldProjects) {
+ RelDataType relDataType = oldProject.getType();
+ RexNode rexNode = replaceRexNodeWithLiteral(oldProject, evaluatedResults);
+
+ // Need to cast the result to the original type if the literal type is changed, e.g. VARCHAR literal is typed as
+ // CHAR(STRING_LENGTH) in Calcite, but we need to cast it back to VARCHAR.
+ rexNode = (rexNode.getType() == relDataType) ? rexNode : rexBuilder.makeCast(relDataType, rexNode, true);
+ newProjects.add(rexNode);
+ }
+ return LogicalProject.create(project.getInput(), project.getHints(), newProjects, project.getRowType());
+ }
+
+ private RelNode constructNewRelNode(Map<RexNode, RexNode> evaluatedResults, Filter filter) {
+ RexNode oldConditions = filter.getCondition();
+ RexNode newConditions = replaceRexNodeWithLiteral(oldConditions, evaluatedResults);
+ return LogicalFilter.create(filter.getInput(), newConditions);
+ }
+
+ private RexNode replaceRexNodeWithLiteral(RexNode rexNode, Map<RexNode, RexNode> rexNodeToLiteralMapping) {
+ if (rexNodeToLiteralMapping.containsKey(rexNode)) {
+ return rexNodeToLiteralMapping.get(rexNode);
+ }
+ // Recursively check any match and replace.
+ if (rexNode instanceof RexCall) {
+ RexCall rexCall = (RexCall) rexNode;
+ List<RexNode> newOperands = rexCall.getOperands().stream()
+ .map(operand -> replaceRexNodeWithLiteral(operand, rexNodeToLiteralMapping))
+ .collect(Collectors.toList());
+ return rexCall.clone(rexCall.getType(), newOperands);
+ }
+ return rexNode;
+ }
+
+ /**
+ * Evaluates the literal only function and returns the result as a RexLiteral, null if the function cannot be
+ * evaluated.
+ */
+ protected static RexNode evaluateLiteralOnlyFunction(RexBuilder rexBuilder, RexNode rexNode,
+ Map<RexNode, RexNode> evaluatedResults) {
+ if (rexNode instanceof RexLiteral) {
+ return rexNode;
+ }
+ Preconditions.checkArgument(rexNode instanceof RexCall, "Expected RexCall, got: " + rexNode);
+ if (evaluatedResults.containsKey(rexNode)) {
+ return evaluatedResults.get(rexNode);
+ }
Review Comment:
(minor)
```suggestion
RexNode resultRexNode = evaluatedResults.get(rexNode);
if (resultRexNode != null) {
return resultRexNode;
}
```
##########
pinot-query-planner/src/main/java/org/apache/calcite/rel/rules/PinotEvaluateLiteralRule.java:
##########
@@ -0,0 +1,272 @@
+/**
+ * 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.calcite.rel.rules;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.calcite.avatica.util.ByteString;
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.Filter;
+import org.apache.calcite.rel.core.Project;
+import org.apache.calcite.rel.logical.LogicalFilter;
+import org.apache.calcite.rel.logical.LogicalProject;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexShuttle;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.calcite.util.NlsString;
+import org.apache.calcite.util.TimestampString;
+import org.apache.pinot.common.function.FunctionInfo;
+import org.apache.pinot.common.function.FunctionInvoker;
+import org.apache.pinot.common.function.FunctionRegistry;
+import org.apache.pinot.spi.utils.TimestampUtils;
+import org.apache.pinot.sql.parsers.SqlCompilationException;
+
+
+/**
+ * SingleValueAggregateRemoveRule that matches an Aggregate function SINGLE_VALUE and remove it
+ *
+ */
+public class PinotEvaluateLiteralRule extends RelOptRule {
+ public static final PinotEvaluateLiteralRule INSTANCE =
+ new PinotEvaluateLiteralRule(PinotRuleUtils.PINOT_REL_FACTORY);
+
+ public PinotEvaluateLiteralRule(RelBuilderFactory factory) {
+ super(operand(RelNode.class, any()), factory, null);
+ }
+
+ @Override
+ public boolean matches(RelOptRuleCall call) {
+ // Traverse the relational expression using a RexShuttle visitor
+ AtomicBoolean hasEvaluateCall = new AtomicBoolean(false);
+ call.rel(0).accept(new RexShuttle() {
+ @Override
+ public RexNode visitCall(RexCall call) {
Review Comment:
Wouldn't this always traverse the whole tree? Notice that `RexShuttle` has all the default visit method that are not cheap (it might clone the node to check if it is changed)
##########
pinot-query-planner/src/main/java/org/apache/calcite/rel/rules/PinotEvaluateLiteralRule.java:
##########
@@ -0,0 +1,249 @@
+/**
+ * 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.calcite.rel.rules;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Collectors;
+import org.apache.calcite.avatica.util.ByteString;
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.Filter;
+import org.apache.calcite.rel.core.Project;
+import org.apache.calcite.rel.logical.LogicalFilter;
+import org.apache.calcite.rel.logical.LogicalProject;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexShuttle;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.calcite.util.NlsString;
+import org.apache.calcite.util.TimestampString;
+import org.apache.pinot.common.function.FunctionInfo;
+import org.apache.pinot.common.function.FunctionInvoker;
+import org.apache.pinot.common.function.FunctionRegistry;
+import org.apache.pinot.spi.utils.TimestampUtils;
+import org.apache.pinot.sql.parsers.SqlCompilationException;
+
+
+/**
+ * SingleValueAggregateRemoveRule that matches an Aggregate function SINGLE_VALUE and remove it
+ *
+ */
+public class PinotEvaluateLiteralRule extends RelOptRule {
+ public static final PinotEvaluateLiteralRule INSTANCE =
+ new PinotEvaluateLiteralRule(PinotRuleUtils.PINOT_REL_FACTORY);
+
+ public PinotEvaluateLiteralRule(RelBuilderFactory factory) {
+ super(operand(RelNode.class, any()), factory, null);
+ }
+
+ @Override
+ public boolean matches(RelOptRuleCall call) {
+ // Traverse the relational expression using a RexShuttle visitor
+ AtomicBoolean hasLiteralOnlyCall = new AtomicBoolean(false);
+ call.rel(0).accept(new RexShuttle() {
+ @Override
+ public RexNode visitCall(RexCall call) {
+ // Check if all operands are RexLiteral
+ if (call.operands.stream().allMatch(operand -> (operand instanceof RexLiteral))) {
+ // If all operands are literals, this call can be evaluated
+ hasLiteralOnlyCall.set(true);
+ // early terminate if we found one evaluate call
+ return call;
+ }
+ call.operands.forEach(operand -> {
+ if (hasLiteralOnlyCall.get()) {
+ // Early terminate if we already found one evaluate call
+ return;
+ }
+ // Recursively call visitCall on all RexCall operands
+ if (operand instanceof RexCall) {
+ visitCall((RexCall) operand);
+ }
+ });
+ // Return the call to continue traversal
+ return call;
+ }
+ });
+ return hasLiteralOnlyCall.get();
+ }
+
+ @Override
+ public void onMatch(RelOptRuleCall call) {
+ RelNode rootRelNode = call.rel(0);
+ RexBuilder rexBuilder = rootRelNode.getCluster().getRexBuilder();
+ Map<RexNode, RexNode> evaluatedResults = new HashMap<>();
+
+ // Recursively evaluate all the calls with Literal only operands from bottom up
+ // Traverse the relational expression using a RexShuttle visitor
+ rootRelNode.accept(new RexShuttle() {
+ @Override
+ public RexNode visitCall(RexCall call) {
+ call.operands.forEach(operand -> {
+ if (operand instanceof RexCall) {
+ visitCall((RexCall) operand);
+ }
+ });
+ // Check if all operands are RexLiteral
+ if (call.operands.stream().allMatch(operand -> operand instanceof RexLiteral)) {
+ // If all operands are literals or already evaluated, this call can be evaluated
+ return evaluateLiteralOnlyFunction(rexBuilder, call, evaluatedResults);
+ }
+ // Return the call to continue traversal
+ return call;
+ }
+ });
+
+ RelNode newRelNode = null;
+ if (rootRelNode instanceof Project) {
+ newRelNode = constructNewRelNode(rexBuilder, evaluatedResults, (Project) rootRelNode);
+ }
+ if (rootRelNode instanceof Filter) {
+ newRelNode = constructNewRelNode(evaluatedResults, (Filter) rootRelNode);
+ }
+ call.transformTo(newRelNode);
+ }
+
+ private RelNode constructNewRelNode(RexBuilder rexBuilder, Map<RexNode, RexNode> evaluatedResults, Project project) {
+ List<RexNode> oldProjects = project.getProjects();
+ List<RexNode> newProjects = new ArrayList<>();
+ for (RexNode oldProject : oldProjects) {
+ RelDataType relDataType = oldProject.getType();
+ RexNode rexNode = replaceRexNodeWithLiteral(oldProject, evaluatedResults);
+
+ // Need to cast the result to the original type if the literal type is changed, e.g. VARCHAR literal is typed as
+ // CHAR(STRING_LENGTH) in Calcite, but we need to cast it back to VARCHAR.
+ rexNode = (rexNode.getType() == relDataType) ? rexNode : rexBuilder.makeCast(relDataType, rexNode, true);
+ newProjects.add(rexNode);
+ }
+ return LogicalProject.create(project.getInput(), project.getHints(), newProjects, project.getRowType());
+ }
+
+ private RelNode constructNewRelNode(Map<RexNode, RexNode> evaluatedResults, Filter filter) {
+ RexNode oldConditions = filter.getCondition();
+ RexNode newConditions = replaceRexNodeWithLiteral(oldConditions, evaluatedResults);
+ return LogicalFilter.create(filter.getInput(), newConditions);
+ }
+
+ private RexNode replaceRexNodeWithLiteral(RexNode rexNode, Map<RexNode, RexNode> rexNodeToLiteralMapping) {
+ if (rexNodeToLiteralMapping.containsKey(rexNode)) {
+ return rexNodeToLiteralMapping.get(rexNode);
+ }
+ // Recursively check any match and replace.
+ if (rexNode instanceof RexCall) {
+ RexCall rexCall = (RexCall) rexNode;
+ List<RexNode> newOperands = rexCall.getOperands().stream()
+ .map(operand -> replaceRexNodeWithLiteral(operand, rexNodeToLiteralMapping))
+ .collect(Collectors.toList());
+ return rexCall.clone(rexCall.getType(), newOperands);
+ }
+ return rexNode;
+ }
+
+ /**
+ * Evaluates the literal only function and returns the result as a RexLiteral, null if the function cannot be
+ * evaluated.
+ */
+ protected static RexNode evaluateLiteralOnlyFunction(RexBuilder rexBuilder, RexNode rexNode,
+ Map<RexNode, RexNode> evaluatedResults) {
+ if (rexNode instanceof RexLiteral) {
+ return rexNode;
+ }
+ Preconditions.checkArgument(rexNode instanceof RexCall, "Expected RexCall, got: " + rexNode);
+ if (evaluatedResults.containsKey(rexNode)) {
+ return evaluatedResults.get(rexNode);
+ }
+ RexCall function = (RexCall) rexNode;
+ List<RexNode> operands = new ArrayList<>(function.getOperands());
+ int numOperands = operands.size();
+ for (int i = 0; i < numOperands; i++) {
+ // The RexCall is guaranteed to have all operands as RexLiteral or evaluated as RexLiteral.
+ // So recursively call evaluateLiteralOnlyFunction on all operands.
+ RexNode operand = evaluateLiteralOnlyFunction(rexBuilder, operands.get(i), evaluatedResults);
+ operands.set(i, operand);
+ }
+
+ String functionName = PinotRuleUtils.extractFunctionName(function);
+ FunctionInfo functionInfo = FunctionRegistry.getFunctionInfo(functionName, numOperands);
+ RexNode resultRexNode = rexNode;
+ if (functionInfo != null) {
+ Object[] arguments = new Object[numOperands];
+ for (int i = 0; i < numOperands; i++) {
+ RexNode operand = function.getOperands().get(i);
+ Preconditions.checkArgument(operand instanceof RexLiteral, "Expected all the operands to be RexLiteral");
+ Object value = ((RexLiteral) operand).getValue();
+ if (value instanceof NlsString) {
+ arguments[i] = ((NlsString) value).getValue();
+ } else if (value instanceof GregorianCalendar) {
+ arguments[i] = ((GregorianCalendar) value).getTimeInMillis();
+ } else if (value instanceof ByteString) {
+ arguments[i] = ((ByteString) value).getBytes();
+ } else {
+ arguments[i] = value;
+ }
+ }
+ RelDataType rexNodeType = rexNode.getType();
+ Object functionResult;
+ try {
+ FunctionInvoker invoker = new FunctionInvoker(functionInfo);
+ invoker.convertTypes(arguments);
+ functionResult = invoker.invoke(arguments);
+ } catch (Exception e) {
+ throw new SqlCompilationException(
+ "Caught exception while invoking method: " + functionInfo.getMethod() + " with arguments: "
+ + Arrays.toString(arguments), e);
+ }
+ if (functionResult == null) {
+ resultRexNode = rexBuilder.makeNullLiteral(rexNodeType);
+ } else if (rexNodeType.getSqlTypeName() == SqlTypeName.TIMESTAMP) {
+ long millis = (functionResult instanceof Number) ? ((Number) functionResult).longValue()
+ : TimestampUtils.toMillisSinceEpoch(functionResult.toString());
+ resultRexNode =
+ rexBuilder.makeTimestampLiteral(TimestampString.fromMillisSinceEpoch(millis), rexNodeType.getPrecision());
+ } else if (functionResult instanceof Byte || functionResult instanceof Short || functionResult instanceof Integer
+ || functionResult instanceof Long) {
+ resultRexNode =
+ rexBuilder.makeExactLiteral(BigDecimal.valueOf(((Number) functionResult).longValue()), rexNodeType);
+ } else if (functionResult instanceof Float || functionResult instanceof Double) {
+ resultRexNode =
+ rexBuilder.makeExactLiteral(BigDecimal.valueOf(((Number) functionResult).doubleValue()), rexNodeType);
Review Comment:
This is incorrect. We cannot always convert to double. @zhtaoxiang is fixing this issue in other places
```suggestion
resultRexNode =
rexBuilder.makeExactLiteral(new BigDecimal(functionResult.toString()), rexNodeType);
```
##########
pinot-query-planner/src/main/java/org/apache/calcite/rel/rules/PinotEvaluateLiteralRule.java:
##########
@@ -0,0 +1,249 @@
+/**
+ * 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.calcite.rel.rules;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Collectors;
+import org.apache.calcite.avatica.util.ByteString;
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.Filter;
+import org.apache.calcite.rel.core.Project;
+import org.apache.calcite.rel.logical.LogicalFilter;
+import org.apache.calcite.rel.logical.LogicalProject;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexShuttle;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.tools.RelBuilderFactory;
+import org.apache.calcite.util.NlsString;
+import org.apache.calcite.util.TimestampString;
+import org.apache.pinot.common.function.FunctionInfo;
+import org.apache.pinot.common.function.FunctionInvoker;
+import org.apache.pinot.common.function.FunctionRegistry;
+import org.apache.pinot.spi.utils.TimestampUtils;
+import org.apache.pinot.sql.parsers.SqlCompilationException;
+
+
+/**
+ * SingleValueAggregateRemoveRule that matches an Aggregate function SINGLE_VALUE and remove it
+ *
+ */
+public class PinotEvaluateLiteralRule extends RelOptRule {
+ public static final PinotEvaluateLiteralRule INSTANCE =
+ new PinotEvaluateLiteralRule(PinotRuleUtils.PINOT_REL_FACTORY);
+
+ public PinotEvaluateLiteralRule(RelBuilderFactory factory) {
+ super(operand(RelNode.class, any()), factory, null);
+ }
+
+ @Override
+ public boolean matches(RelOptRuleCall call) {
+ // Traverse the relational expression using a RexShuttle visitor
+ AtomicBoolean hasLiteralOnlyCall = new AtomicBoolean(false);
+ call.rel(0).accept(new RexShuttle() {
+ @Override
+ public RexNode visitCall(RexCall call) {
+ // Check if all operands are RexLiteral
+ if (call.operands.stream().allMatch(operand -> (operand instanceof RexLiteral))) {
+ // If all operands are literals, this call can be evaluated
+ hasLiteralOnlyCall.set(true);
+ // early terminate if we found one evaluate call
+ return call;
+ }
+ call.operands.forEach(operand -> {
+ if (hasLiteralOnlyCall.get()) {
+ // Early terminate if we already found one evaluate call
+ return;
+ }
+ // Recursively call visitCall on all RexCall operands
+ if (operand instanceof RexCall) {
+ visitCall((RexCall) operand);
+ }
+ });
+ // Return the call to continue traversal
+ return call;
+ }
+ });
+ return hasLiteralOnlyCall.get();
+ }
+
+ @Override
+ public void onMatch(RelOptRuleCall call) {
+ RelNode rootRelNode = call.rel(0);
+ RexBuilder rexBuilder = rootRelNode.getCluster().getRexBuilder();
+ Map<RexNode, RexNode> evaluatedResults = new HashMap<>();
+
+ // Recursively evaluate all the calls with Literal only operands from bottom up
+ // Traverse the relational expression using a RexShuttle visitor
+ rootRelNode.accept(new RexShuttle() {
+ @Override
+ public RexNode visitCall(RexCall call) {
+ call.operands.forEach(operand -> {
+ if (operand instanceof RexCall) {
+ visitCall((RexCall) operand);
+ }
+ });
+ // Check if all operands are RexLiteral
+ if (call.operands.stream().allMatch(operand -> operand instanceof RexLiteral)) {
+ // If all operands are literals or already evaluated, this call can be evaluated
+ return evaluateLiteralOnlyFunction(rexBuilder, call, evaluatedResults);
+ }
+ // Return the call to continue traversal
+ return call;
+ }
+ });
+
+ RelNode newRelNode = null;
+ if (rootRelNode instanceof Project) {
+ newRelNode = constructNewRelNode(rexBuilder, evaluatedResults, (Project) rootRelNode);
+ }
+ if (rootRelNode instanceof Filter) {
+ newRelNode = constructNewRelNode(evaluatedResults, (Filter) rootRelNode);
+ }
+ call.transformTo(newRelNode);
+ }
+
+ private RelNode constructNewRelNode(RexBuilder rexBuilder, Map<RexNode, RexNode> evaluatedResults, Project project) {
+ List<RexNode> oldProjects = project.getProjects();
+ List<RexNode> newProjects = new ArrayList<>();
+ for (RexNode oldProject : oldProjects) {
+ RelDataType relDataType = oldProject.getType();
+ RexNode rexNode = replaceRexNodeWithLiteral(oldProject, evaluatedResults);
+
+ // Need to cast the result to the original type if the literal type is changed, e.g. VARCHAR literal is typed as
+ // CHAR(STRING_LENGTH) in Calcite, but we need to cast it back to VARCHAR.
+ rexNode = (rexNode.getType() == relDataType) ? rexNode : rexBuilder.makeCast(relDataType, rexNode, true);
+ newProjects.add(rexNode);
+ }
+ return LogicalProject.create(project.getInput(), project.getHints(), newProjects, project.getRowType());
+ }
+
+ private RelNode constructNewRelNode(Map<RexNode, RexNode> evaluatedResults, Filter filter) {
+ RexNode oldConditions = filter.getCondition();
+ RexNode newConditions = replaceRexNodeWithLiteral(oldConditions, evaluatedResults);
+ return LogicalFilter.create(filter.getInput(), newConditions);
+ }
+
+ private RexNode replaceRexNodeWithLiteral(RexNode rexNode, Map<RexNode, RexNode> rexNodeToLiteralMapping) {
+ if (rexNodeToLiteralMapping.containsKey(rexNode)) {
+ return rexNodeToLiteralMapping.get(rexNode);
+ }
+ // Recursively check any match and replace.
+ if (rexNode instanceof RexCall) {
+ RexCall rexCall = (RexCall) rexNode;
+ List<RexNode> newOperands = rexCall.getOperands().stream()
+ .map(operand -> replaceRexNodeWithLiteral(operand, rexNodeToLiteralMapping))
+ .collect(Collectors.toList());
+ return rexCall.clone(rexCall.getType(), newOperands);
+ }
+ return rexNode;
+ }
+
+ /**
+ * Evaluates the literal only function and returns the result as a RexLiteral, null if the function cannot be
+ * evaluated.
+ */
+ protected static RexNode evaluateLiteralOnlyFunction(RexBuilder rexBuilder, RexNode rexNode,
+ Map<RexNode, RexNode> evaluatedResults) {
+ if (rexNode instanceof RexLiteral) {
+ return rexNode;
+ }
+ Preconditions.checkArgument(rexNode instanceof RexCall, "Expected RexCall, got: " + rexNode);
+ if (evaluatedResults.containsKey(rexNode)) {
+ return evaluatedResults.get(rexNode);
+ }
+ RexCall function = (RexCall) rexNode;
+ List<RexNode> operands = new ArrayList<>(function.getOperands());
+ int numOperands = operands.size();
+ for (int i = 0; i < numOperands; i++) {
+ // The RexCall is guaranteed to have all operands as RexLiteral or evaluated as RexLiteral.
+ // So recursively call evaluateLiteralOnlyFunction on all operands.
+ RexNode operand = evaluateLiteralOnlyFunction(rexBuilder, operands.get(i), evaluatedResults);
+ operands.set(i, operand);
+ }
+
+ String functionName = PinotRuleUtils.extractFunctionName(function);
+ FunctionInfo functionInfo = FunctionRegistry.getFunctionInfo(functionName, numOperands);
+ RexNode resultRexNode = rexNode;
+ if (functionInfo != null) {
+ Object[] arguments = new Object[numOperands];
+ for (int i = 0; i < numOperands; i++) {
+ RexNode operand = function.getOperands().get(i);
+ Preconditions.checkArgument(operand instanceof RexLiteral, "Expected all the operands to be RexLiteral");
+ Object value = ((RexLiteral) operand).getValue();
+ if (value instanceof NlsString) {
+ arguments[i] = ((NlsString) value).getValue();
+ } else if (value instanceof GregorianCalendar) {
+ arguments[i] = ((GregorianCalendar) value).getTimeInMillis();
+ } else if (value instanceof ByteString) {
+ arguments[i] = ((ByteString) value).getBytes();
+ } else {
+ arguments[i] = value;
+ }
+ }
+ RelDataType rexNodeType = rexNode.getType();
+ Object functionResult;
+ try {
+ FunctionInvoker invoker = new FunctionInvoker(functionInfo);
+ invoker.convertTypes(arguments);
+ functionResult = invoker.invoke(arguments);
+ } catch (Exception e) {
+ throw new SqlCompilationException(
+ "Caught exception while invoking method: " + functionInfo.getMethod() + " with arguments: "
+ + Arrays.toString(arguments), e);
+ }
+ if (functionResult == null) {
+ resultRexNode = rexBuilder.makeNullLiteral(rexNodeType);
+ } else if (rexNodeType.getSqlTypeName() == SqlTypeName.TIMESTAMP) {
+ long millis = (functionResult instanceof Number) ? ((Number) functionResult).longValue()
Review Comment:
Also handle `Timestamp` type explicitly. It should be the most common case
```suggestion
long millis;
if (functionResult instanceof Timestamp) {
millis = ((Timestamp) functionResult).getTime();
} else if (functionResult instanceof Number) {
millis = ((Number) functionResult).longValue();
} else {
millis = TimestampUtils.toMillisSinceEpoch(functionResult.toString());
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org