924060929 commented on code in PR #11802: URL: https://github.com/apache/doris/pull/11802#discussion_r949863988
########## fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/literal/LargeIntLiteral.java: ########## @@ -0,0 +1,59 @@ +// 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.doris.nereids.trees.expressions.literal; + +import org.apache.doris.analysis.LiteralExpr; +import org.apache.doris.common.AnalysisException; +import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor; +import org.apache.doris.nereids.types.SmallIntType; + +import java.math.BigInteger; +import java.util.Objects; + +/** + * large int type literal + */ +public class LargeIntLiteral extends Literal { + + private final BigInteger value; + + public LargeIntLiteral(BigInteger value) { + super(SmallIntType.INSTANCE); Review Comment: shoud be LargeIntType.INSTANCE? ########## fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/BinaryArithmetic.java: ########## @@ -0,0 +1,54 @@ +// 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.doris.nereids.trees.expressions; + +import org.apache.doris.analysis.ArithmeticExpr.Operator; +import org.apache.doris.nereids.exceptions.UnboundException; +import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor; +import org.apache.doris.nereids.types.DataType; + +/** + * binary arithmetic operator. Such as +, -, *, /. + */ +public abstract class BinaryArithmetic extends BinaryOperator { + + private final Operator staleOperator; + + public BinaryArithmetic(Expression left, Expression right, String symbol, Operator staleOperator) { + super(left, right, symbol); + this.staleOperator = staleOperator; + } + + public Operator getStaleOperator() { Review Comment: we should keep the namely consistent ```suggestion public Operator getLegacyOperator() { ``` ########## fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/Mod.java: ########## @@ -26,15 +29,10 @@ /** * Mod Expression. */ -public class Mod extends Arithmetic implements BinaryExpression { - public Mod(Expression left, Expression right) { - super(ArithmeticOperator.MOD, left, right); - } +public class Mod extends BinaryArithmetic { - @Override - public String toSql() { - return left().toSql() + ' ' + getArithmeticOperator().toString() - + ' ' + right().toSql(); + public Mod(Expression left, Expression right) { + super(left, right, "%", Operator.MOD); Review Comment: you can move the '%' to the Operator ```java enum Operator { ADD("+"), SUBTRACT("-"), ..., MOD("%") } ``` ########## fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rewrite/rules/TypeCoercion.java: ########## @@ -0,0 +1,180 @@ +// 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.doris.nereids.rules.expression.rewrite.rules; + +import org.apache.doris.nereids.annotation.Developing; +import org.apache.doris.nereids.rules.expression.rewrite.AbstractExpressionRewriteRule; +import org.apache.doris.nereids.rules.expression.rewrite.ExpressionRewriteContext; +import org.apache.doris.nereids.trees.expressions.BinaryOperator; +import org.apache.doris.nereids.trees.expressions.CaseWhen; +import org.apache.doris.nereids.trees.expressions.Cast; +import org.apache.doris.nereids.trees.expressions.Expression; +import org.apache.doris.nereids.trees.expressions.InPredicate; +import org.apache.doris.nereids.trees.expressions.typecoercion.ImplicitCastInputTypes; +import org.apache.doris.nereids.types.DataType; +import org.apache.doris.nereids.types.coercion.AbstractDataType; +import org.apache.doris.nereids.util.TypeCoercionUtils; + +import com.google.common.collect.Lists; + +import java.util.List; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; + +/** + * a rule to add implicit cast for expressions. + * This class is inspired by spark's TypeCoercion. + */ +@Developing +public class TypeCoercion extends AbstractExpressionRewriteRule { + + // TODO: + // 1. DecimalPrecision Process + // 2. Divide process + // 3. String promote with numeric in binary arithmetic + // 4. Date and DateTime process + + public static final TypeCoercion INSTANCE = new TypeCoercion(); + + @Override + public Expression rewrite(Expression expr, ExpressionRewriteContext ctx) { + if (expr instanceof ImplicitCastInputTypes) { + return visitImplicitCastInputTypes(expr, ctx); + } else { + return super.rewrite(expr, ctx); + } + } + + // TODO: add other expression visitor function to do type coercion if necessary. + + @Override + public Expression visitBinaryOperator(BinaryOperator binaryOperator, ExpressionRewriteContext context) { + Expression left = rewrite(binaryOperator.left(), context); + Expression right = rewrite(binaryOperator.right(), context); + + return Optional.of(TypeCoercionUtils.canHandleTypeCoercion(left.getDataType(), right.getDataType())) + .filter(Boolean::booleanValue) + .map(b -> TypeCoercionUtils.findTightestCommonType(left.getDataType(), right.getDataType())) + .filter(Optional::isPresent) + .map(Optional::get) + .filter(ct -> binaryOperator.inputType().acceptsType(ct)) + .filter(ct -> !left.getDataType().equals(ct) || !right.getDataType().equals(ct)) + .map(commonType -> { + Expression newLeft = TypeCoercionUtils.castIfNotSameType(left, commonType); + Expression newRight = TypeCoercionUtils.castIfNotSameType(right, commonType); + return binaryOperator.withChildren(newLeft, newRight); + }) + .orElse(binaryOperator.withChildren(left, right)); + } + + @Override + public Expression visitCaseWhen(CaseWhen caseWhen, ExpressionRewriteContext context) { + List<Expression> rewrittenChildren = caseWhen.children().stream() + .map(e -> rewrite(e, context)).collect(Collectors.toList()); + CaseWhen newCaseWhen = caseWhen.withChildren(rewrittenChildren); + List<DataType> dataTypesForCoercion = newCaseWhen.dataTypesForCoercion(); + if (dataTypesForCoercion.size() <= 1) { + return newCaseWhen; + } + DataType first = dataTypesForCoercion.get(0); + if (dataTypesForCoercion.stream().allMatch(dataType -> dataType.equals(first))) { + return newCaseWhen; + } + Optional<DataType> optionalCommonType = TypeCoercionUtils.findWiderCommonType(dataTypesForCoercion); + return optionalCommonType + .map(commonType -> { + List<Expression> newChildren + = newCaseWhen.getWhenClauses().stream() + .map(wc -> wc.withChildren(wc.getOperand(), + TypeCoercionUtils.castIfNotSameType(wc.getResult(), commonType))) + .collect(Collectors.toList()); + newCaseWhen.getDefaultValue() + .map(dv -> TypeCoercionUtils.castIfNotSameType(dv, commonType)) + .ifPresent(newChildren::add); + return newCaseWhen.withChildren(newChildren); + }) + .orElse(newCaseWhen); + } + + @Override + public Expression visitInPredicate(InPredicate inPredicate, ExpressionRewriteContext context) { + List<Expression> rewrittenChildren = inPredicate.children().stream() + .map(e -> rewrite(e, context)).collect(Collectors.toList()); + InPredicate newInPredicate = inPredicate.withChildren(rewrittenChildren); + + if (newInPredicate.getOptions().stream().map(Expression::getDataType) + .allMatch(dt -> dt.equals(newInPredicate.getCompareExpr().getDataType()))) { + return newInPredicate; + } + Optional<DataType> optionalCommonType = TypeCoercionUtils.findWiderCommonType(newInPredicate.children() + .stream().map(Expression::getDataType).collect(Collectors.toList())); + + return optionalCommonType + .map(commonType -> { + List<Expression> newChildren = newInPredicate.children().stream() + .map(e -> TypeCoercionUtils.castIfNotSameType(e, commonType)) + .collect(Collectors.toList()); + return newInPredicate.withChildren(newChildren); + }) + .orElse(newInPredicate); + } + + /** + * Do implicit cast for expression's children. + */ + private Expression visitImplicitCastInputTypes(Expression expr, ExpressionRewriteContext ctx) { + ImplicitCastInputTypes implicitCastInputTypes = (ImplicitCastInputTypes) expr; + List<Expression> newChildren = Lists.newArrayListWithCapacity(expr.arity()); + AtomicInteger changed = new AtomicInteger(0); + for (int i = 0; i < implicitCastInputTypes.expectedInputTypes().size(); i++) { + newChildren.add(implicitCast(expr.child(i), implicitCastInputTypes.expectedInputTypes().get(i), ctx) + .map(e -> { + changed.incrementAndGet(); + return e; + }) + .orElse(expr.child(0)) + ); + } + if (changed.get() != 0) { + return expr.withChildren(newChildren); + } else { + return expr; + } + } + + /** + * Return Optional.empty() if we cannot do or do not need to do implicit cast. + */ + @Developing + private Optional<Expression> implicitCast(Expression input, AbstractDataType expected, + ExpressionRewriteContext ctx) { + Expression rewrittenInput = rewrite(input, ctx); + Optional<DataType> castDataType = TypeCoercionUtils.implicitCast(rewrittenInput.getDataType(), expected); + if (castDataType.isPresent() && !castDataType.get().equals(rewrittenInput.getDataType())) { + return Optional.of(new Cast(rewrittenInput, castDataType.get())); + } else { + // TODO: there maybe has performance problem, we need use ctx to save whether children is changed. Review Comment: I think we can check by `rewrittenInput == input`, and every rewrite method return origin expression if not changed ########## fe/fe-core/src/main/java/org/apache/doris/nereids/NereidsPlanner.java: ########## @@ -138,6 +142,10 @@ private void analyze() { cascadesContext.newAnalyzer().analyze(); } + private void checkAnalyze() { + new CheckAnalysisJob(cascadesContext).execute(); Review Comment: this job is along to the analysis stage, we should move to NereidsAnalyzer so we can check analysis at any place we use the NereidsAnalyzer, such as analyze view and analyze subquery which use a different NereidsAnalyzer ########## fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/CheckAnalysis.java: ########## @@ -0,0 +1,48 @@ +// 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.doris.nereids.rules.analysis; + +import org.apache.doris.nereids.rules.Rule; +import org.apache.doris.nereids.rules.RuleType; +import org.apache.doris.nereids.trees.expressions.Expression; +import org.apache.doris.nereids.trees.expressions.typecoercion.TypeCheckResult; +import org.apache.doris.nereids.trees.plans.Plan; + +import java.util.Optional; + +/** + * Check analysis rule to check semantic correct after analysis by Nereids. + */ +public class CheckAnalysis extends OneAnalysisRuleFactory { + @Override + public Rule build() { + return any().then(this::checkExpressionInputTypes).toRule(RuleType.CHECK_ANALYSIS); + } + + private Plan checkExpressionInputTypes(Plan plan) { + final Optional<TypeCheckResult> firstFailed = plan.getExpressions().stream() + .map(Expression::checkInputDataTypes) + .filter(TypeCheckResult::failed) + .findFirst(); + + if (firstFailed.isPresent()) { + throw new RuntimeException(firstFailed.get().getMessage()); Review Comment: ```suggestion throw new AnalysisException(firstFailed.get().getMessage()); ``` ########## fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/And.java: ########## @@ -62,4 +65,9 @@ public CompoundPredicate flip(Expression left, Expression right) { public Class<? extends CompoundPredicate> flipType() { return Or.class; } + + @Override + public AbstractDataType inputType() { Review Comment: we can move inputType method to CompoundPredicate ########## fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/ComparisonPredicate.java: ########## @@ -39,45 +37,21 @@ public abstract class ComparisonPredicate extends Expression implements BinaryEx * @param right right child of comparison predicate */ public ComparisonPredicate(Expression left, Expression right, String symbol) { - super(left, right); - this.symbol = symbol; + super(left, right, symbol); } @Override public DataType getDataType() throws UnboundException { return BooleanType.INSTANCE; } - @Override - public boolean nullable() throws UnboundException { - return left().nullable() || right().nullable(); - } - - @Override - public String toSql() { - return "(" + left().toSql() + ' ' + symbol + ' ' + right().toSql() + ")"; - } - public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) { return visitor.visitComparisonPredicate(this, context); } @Override - public int hashCode() { - return Objects.hash(symbol, left(), right()); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ComparisonPredicate other = (ComparisonPredicate) o; - return Objects.equals(left(), other.left()) - && Objects.equals(right(), other.right()); + public AbstractDataType inputType() { + return AnyDataType.INSTANCE; Review Comment: BooleanType.INSTANCE? -- 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-unsubscr...@doris.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: commits-unsubscr...@doris.apache.org For additional commands, e-mail: commits-h...@doris.apache.org