zclllyybb commented on code in PR #57941:
URL: https://github.com/apache/doris/pull/57941#discussion_r2606727875
##########
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/executable/DateTimeExtractAndTransform.java:
##########
@@ -1334,4 +1338,81 @@ private static long convertMonthToPeriod(long month) {
}
return year * 100 + month % 12 + 1;
}
+
+ /**
+ * date extract function hour_from_unixtime
+ */
+ @ExecFunction(name = "hour_from_unixtime")
+ public static Expression hourFromUnixtime(BigIntLiteral unixTime) {
+ long epochSecond = unixTime.getValue();
+ if (epochSecond < 0 || epochSecond > TIMESTAMP_VALID_MAX) {
+ return new NullLiteral(IntegerType.INSTANCE);
Review Comment:
from_unixtime 遇到越界应该是报错行为才对?
##########
fe/fe-core/src/test/java/org/apache/doris/nereids/rules/expression/SimplifyTimeFieldFromUnixtimeTest.java:
##########
@@ -0,0 +1,74 @@
+// 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;
+
+import
org.apache.doris.nereids.rules.expression.rules.SimplifyTimeFieldFromUnixtime;
+import org.apache.doris.nereids.trees.expressions.Expression;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Maps;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.Map;
+
+/**
+ * Tests for {@link SimplifyTimeFieldFromUnixtime}.
+ */
+public class SimplifyTimeFieldFromUnixtimeTest extends
ExpressionRewriteTestHelper {
+ public SimplifyTimeFieldFromUnixtimeTest() {
+ executor = new ExpressionRuleExecutor(ImmutableList.of(
+ bottomUp(SimplifyTimeFieldFromUnixtime.INSTANCE)));
+ }
+
+ @Test
+ public void testRewriteSimple() {
+ assertRewriteAfterTypeCoercion("hour(from_unixtime(IA))",
"cast(hour_from_unixtime(IA) as TINYINT)");
+ assertRewriteAfterTypeCoercion("minute(from_unixtime(IA))",
"cast(minute_from_unixtime(IA) as TINYINT)");
Review Comment:
why the result is wrapped with a `cast`?
##########
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/MicrosecondFromUnixtime.java:
##########
@@ -0,0 +1,88 @@
+// 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.functions.scalar;
+
+import org.apache.doris.catalog.FunctionSignature;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.functions.AlwaysNullable;
+import
org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
+import org.apache.doris.nereids.trees.expressions.shape.UnaryExpression;
+import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
+import org.apache.doris.nereids.types.DecimalV3Type;
+import org.apache.doris.nereids.types.IntegerType;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/**
+ * Scalar Function 'microsecond_from_unixtime'
+ * Optimized version of `MICROSECOND(FROM_UNIXTIME(ts))`
+ */
+public class MicrosecondFromUnixtime extends ScalarFunction
+ implements UnaryExpression, ExplicitlyCastableSignature,
AlwaysNullable {
+ public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
+
FunctionSignature.ret(IntegerType.INSTANCE).args(DecimalV3Type.createDecimalV3Type(18,
6))
+ );
+
+ /**
+ * constructor with 1 argument.
+ */
+ public MicrosecondFromUnixtime(Expression arg) {
+ super("microsecond_from_unixtime", arg);
+ }
+
+ /** constructor for withChildren and reuse signature */
+ private MicrosecondFromUnixtime(ScalarFunctionParams functionParams) {
+ super(functionParams);
+ }
+
+ @Override
+ public FunctionSignature computeSignature(FunctionSignature signature) {
+ // skip super.computeSignature() to avoid changing the decimal
precision
+ // manually set decimal argument's type to always decimal(18, 6)
Review Comment:
means for any decimal type input, cast it to specific scale and precision?
what's this for?
##########
be/src/vec/functions/date_time_transforms.h:
##########
@@ -427,6 +431,134 @@ struct FromUnixTimeDecimalImpl {
}
};
+// Base template for optimized time field(HOUR, MINUTE, SECOND, MS) extraction
from Unix timestamp
+// Uses lookup_offset to avoid expensive civil_second construction
+template <typename Impl>
+class FunctionTimeFieldFromUnixtime : public IFunction {
+public:
+ static constexpr auto name = Impl::name;
+ static FunctionPtr create() { return
std::make_shared<FunctionTimeFieldFromUnixtime<Impl>>(); }
+
+ String get_name() const override { return name; }
+
+ size_t get_number_of_arguments() const override { return 1; }
+
+ DataTypePtr get_return_type_impl(const ColumnsWithTypeAndName& arguments)
const override {
+ return make_nullable(std::make_shared<DataTypeInt32>());
+ }
+
+ // Align with FROM_UNIXTIME upper bound (3001-01-19 00:00:00)
+ static const int64_t TIMESTAMP_VALID_MAX = 32536771199L;
Review Comment:
in this version you dont need to consider the bound of `3001 year` anymore.
that's for compatible logic
##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rules/SimplifyTimeFieldFromUnixtime.java:
##########
@@ -0,0 +1,151 @@
+// 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.rules;
+
+import org.apache.doris.nereids.rules.expression.ExpressionMatchingContext;
+import org.apache.doris.nereids.rules.expression.ExpressionPatternMatcher;
+import org.apache.doris.nereids.rules.expression.ExpressionPatternRuleFactory;
+import org.apache.doris.nereids.rules.expression.ExpressionRuleType;
+import org.apache.doris.nereids.trees.expressions.Cast;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import
org.apache.doris.nereids.trees.expressions.functions.scalar.FromUnixtime;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.Hour;
+import
org.apache.doris.nereids.trees.expressions.functions.scalar.HourFromUnixtime;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.Microsecond;
+import
org.apache.doris.nereids.trees.expressions.functions.scalar.MicrosecondFromUnixtime;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.Minute;
+import
org.apache.doris.nereids.trees.expressions.functions.scalar.MinuteFromUnixtime;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.Second;
+import
org.apache.doris.nereids.trees.expressions.functions.scalar.SecondFromUnixtime;
+import org.apache.doris.nereids.types.BigIntType;
+import org.apache.doris.nereids.types.DataType;
+import org.apache.doris.nereids.types.DecimalV3Type;
+import org.apache.doris.nereids.util.TypeCoercionUtils;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/**
+ * Simplify time extraction functions with from_unixtime():
+ * - hour(from_unixtime(ts)) -> hour_from_unixtime(ts)
+ * - minute(from_unixtime(ts)) -> minute_from_unixtime(ts)
+ * - second(from_unixtime(ts)) -> second_from_unixtime(ts)
+ * - microsecond(from_unixtime(ts)) -> microsecond_from_unixtime(ts)
+ */
+public class SimplifyTimeFieldFromUnixtime implements
ExpressionPatternRuleFactory {
+ public static final SimplifyTimeFieldFromUnixtime INSTANCE = new
SimplifyTimeFieldFromUnixtime();
+
+ @Override
+ public List<ExpressionPatternMatcher<? extends Expression>> buildRules() {
+ return ImmutableList.of(
+ matchesType(Hour.class)
+ .thenApply(SimplifyTimeFieldFromUnixtime::rewriteHour)
+ .toRule(ExpressionRuleType.SIMPLIFY_ARITHMETIC),
+ matchesType(Minute.class)
+
.thenApply(SimplifyTimeFieldFromUnixtime::rewriteMinute)
+ .toRule(ExpressionRuleType.SIMPLIFY_ARITHMETIC),
+ matchesType(Second.class)
+
.thenApply(SimplifyTimeFieldFromUnixtime::rewriteSecond)
+ .toRule(ExpressionRuleType.SIMPLIFY_ARITHMETIC),
+ matchesType(Microsecond.class)
+
.thenApply(SimplifyTimeFieldFromUnixtime::rewriteMicrosecond)
+ .toRule(ExpressionRuleType.SIMPLIFY_ARITHMETIC)
+ );
+ }
+
+ private static Expression rewriteHour(ExpressionMatchingContext<Hour> ctx)
{
+ Hour hour = ctx.expr;
+ Expression nestedChild = removeCast(hour.child());
+ if (!(nestedChild instanceof FromUnixtime && nestedChild.arity() ==
1)) {
+ return hour;
+ }
+
+ FromUnixtime fromUnixtime = (FromUnixtime) nestedChild;
+ Expression tsArg = fromUnixtime.child(0);
+ if (!tsArg.getDataType().isNumericType() && !tsArg.isNullLiteral()) {
+ return hour;
+ }
+ Expression bigintArg = TypeCoercionUtils.castIfNotSameType(tsArg,
BigIntType.INSTANCE);
+ Expression rewritten = new HourFromUnixtime(bigintArg);
+ return TypeCoercionUtils.ensureSameResultType(hour, rewritten,
ctx.rewriteContext);
+ }
+
+ private static Expression rewriteMinute(ExpressionMatchingContext<Minute>
ctx) {
+ Minute minute = ctx.expr;
+ Expression nestedChild = removeCast(minute.child());
+ if (!(nestedChild instanceof FromUnixtime && nestedChild.arity() ==
1)) {
+ return minute;
+ }
+
+ FromUnixtime fromUnixtime = (FromUnixtime) nestedChild;
+ Expression tsArg = fromUnixtime.child(0);
+ if (!tsArg.getDataType().isNumericType() && !tsArg.isNullLiteral()) {
+ return minute;
+ }
+ Expression bigintArg = TypeCoercionUtils.castIfNotSameType(tsArg,
BigIntType.INSTANCE);
+ Expression rewritten = new MinuteFromUnixtime(bigintArg);
+ return TypeCoercionUtils.ensureSameResultType(minute, rewritten,
ctx.rewriteContext);
+ }
+
+ private static Expression rewriteSecond(ExpressionMatchingContext<Second>
ctx) {
+ Second second = ctx.expr;
+ Expression nestedChild = removeCast(second.child());
+ if (!(nestedChild instanceof FromUnixtime && nestedChild.arity() ==
1)) {
+ return second;
+ }
+
+ FromUnixtime fromUnixtime = (FromUnixtime) nestedChild;
+ Expression tsArg = fromUnixtime.child(0);
+ if (!tsArg.getDataType().isNumericType() && !tsArg.isNullLiteral()) {
+ return second;
+ }
+ Expression bigintArg = TypeCoercionUtils.castIfNotSameType(tsArg,
BigIntType.INSTANCE);
+ Expression rewritten = new SecondFromUnixtime(bigintArg);
+ return TypeCoercionUtils.ensureSameResultType(second, rewritten,
ctx.rewriteContext);
+ }
+
+ private static Expression
rewriteMicrosecond(ExpressionMatchingContext<Microsecond> ctx) {
+ Microsecond microsecond = ctx.expr;
+ Expression nestedChild = removeCast(microsecond.child());
+ if (!(nestedChild instanceof FromUnixtime && nestedChild.arity() ==
1)) {
+ return microsecond;
+ }
+
+ FromUnixtime fromUnixtime = (FromUnixtime) nestedChild;
+ Expression tsArg = fromUnixtime.child(0);
+ if (!tsArg.getDataType().isNumericType() && !tsArg.isNullLiteral()) {
+ return microsecond;
+ }
+ Expression decimalArg = TypeCoercionUtils.castIfNotSameType(tsArg,
+ DecimalV3Type.createDecimalV3Type(18,
6));
+ Expression rewritten = new MicrosecondFromUnixtime(decimalArg);
+ return TypeCoercionUtils.ensureSameResultType(microsecond, rewritten,
ctx.rewriteContext);
+ }
+
+ private static Expression removeCast(Expression expr) {
+ Expression current = expr;
+ if (current instanceof Cast) {
+ DataType nestedType = current.getDataType();
+ if (nestedType.isDateTimeType() || nestedType.isDateTimeV2Type()) {
Review Comment:
means should apply to `hour(cast(from_unixtime(...) as datetime))`? have you
add test about this?
##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rules/SimplifyTimeFieldFromUnixtime.java:
##########
@@ -0,0 +1,151 @@
+// 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.rules;
+
+import org.apache.doris.nereids.rules.expression.ExpressionMatchingContext;
+import org.apache.doris.nereids.rules.expression.ExpressionPatternMatcher;
+import org.apache.doris.nereids.rules.expression.ExpressionPatternRuleFactory;
+import org.apache.doris.nereids.rules.expression.ExpressionRuleType;
+import org.apache.doris.nereids.trees.expressions.Cast;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import
org.apache.doris.nereids.trees.expressions.functions.scalar.FromUnixtime;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.Hour;
+import
org.apache.doris.nereids.trees.expressions.functions.scalar.HourFromUnixtime;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.Microsecond;
+import
org.apache.doris.nereids.trees.expressions.functions.scalar.MicrosecondFromUnixtime;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.Minute;
+import
org.apache.doris.nereids.trees.expressions.functions.scalar.MinuteFromUnixtime;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.Second;
+import
org.apache.doris.nereids.trees.expressions.functions.scalar.SecondFromUnixtime;
+import org.apache.doris.nereids.types.BigIntType;
+import org.apache.doris.nereids.types.DataType;
+import org.apache.doris.nereids.types.DecimalV3Type;
+import org.apache.doris.nereids.util.TypeCoercionUtils;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/**
+ * Simplify time extraction functions with from_unixtime():
+ * - hour(from_unixtime(ts)) -> hour_from_unixtime(ts)
+ * - minute(from_unixtime(ts)) -> minute_from_unixtime(ts)
+ * - second(from_unixtime(ts)) -> second_from_unixtime(ts)
+ * - microsecond(from_unixtime(ts)) -> microsecond_from_unixtime(ts)
+ */
+public class SimplifyTimeFieldFromUnixtime implements
ExpressionPatternRuleFactory {
+ public static final SimplifyTimeFieldFromUnixtime INSTANCE = new
SimplifyTimeFieldFromUnixtime();
+
+ @Override
+ public List<ExpressionPatternMatcher<? extends Expression>> buildRules() {
+ return ImmutableList.of(
+ matchesType(Hour.class)
+ .thenApply(SimplifyTimeFieldFromUnixtime::rewriteHour)
+ .toRule(ExpressionRuleType.SIMPLIFY_ARITHMETIC),
Review Comment:
should add a new `ExpressionRuleType`
##########
be/src/vec/functions/date_time_transforms.h:
##########
@@ -427,6 +431,134 @@ struct FromUnixTimeDecimalImpl {
}
};
+// Base template for optimized time field(HOUR, MINUTE, SECOND, MS) extraction
from Unix timestamp
+// Uses lookup_offset to avoid expensive civil_second construction
+template <typename Impl>
+class FunctionTimeFieldFromUnixtime : public IFunction {
+public:
+ static constexpr auto name = Impl::name;
+ static FunctionPtr create() { return
std::make_shared<FunctionTimeFieldFromUnixtime<Impl>>(); }
+
+ String get_name() const override { return name; }
+
+ size_t get_number_of_arguments() const override { return 1; }
+
+ DataTypePtr get_return_type_impl(const ColumnsWithTypeAndName& arguments)
const override {
+ return make_nullable(std::make_shared<DataTypeInt32>());
+ }
+
+ // Align with FROM_UNIXTIME upper bound (3001-01-19 00:00:00)
+ static const int64_t TIMESTAMP_VALID_MAX = 32536771199L;
+
+ Status execute_impl(FunctionContext* context, Block& block, const
ColumnNumbers& arguments,
+ uint32_t result, size_t input_rows_count) const
override {
+ using ArgColType = PrimitiveTypeTraits<Impl::ArgType>::ColumnType;
+ auto res = ColumnInt32::create();
+ auto null_map = ColumnUInt8::create(input_rows_count, 0);
+ auto& null_data = null_map->get_data();
+
+ const auto* ts_col =
+ assert_cast<const
ArgColType*>(block.get_by_position(arguments[0]).column.get());
+ if constexpr (Impl::ArgType == PrimitiveType::TYPE_DECIMAL64) {
+ // microsecond_from_unixtime only
+ const auto scale = static_cast<int32_t>(ts_col->get_scale());
+
+ for (int i = 0; i < input_rows_count; ++i) {
+ const auto seconds = ts_col->get_intergral_part(i);
+ const auto fraction = ts_col->get_fractional_part(i);
+
+ if (seconds < 0 || seconds > TIMESTAMP_VALID_MAX) {
+ res->insert_default();
+ null_data[i] = 1;
Review Comment:
why return null? in nowadays behaviour we throw exception for
`from_unixtime`'s wrong.
--
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: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]