Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions be/src/exprs/function/function_utility.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
// IWYU pragma: no_include <bits/chrono.h>
#include <algorithm>
#include <chrono> // IWYU pragma: keep
#include <cmath>
#include <limits>
#include <memory>
#include <string>
#include <thread>
Expand Down Expand Up @@ -138,11 +140,109 @@ class FunctionVersion : public IFunction {
}
};

class FunctionHumanReadableSeconds : public IFunction {
public:
static constexpr auto name = "human_readable_seconds";

static FunctionPtr create() { return std::make_shared<FunctionHumanReadableSeconds>(); }

String get_name() const override { return name; }

size_t get_number_of_arguments() const override { return 1; }

DataTypePtr get_return_type_impl(const DataTypes& /*arguments*/) const override {
return std::make_shared<DataTypeString>();
}

Status execute_impl(FunctionContext* /*context*/, Block& block, const ColumnNumbers& arguments,
uint32_t result, size_t input_rows_count) const override {
const auto& argument_column = block.get_by_position(arguments[0]).column;
const auto* data_column = check_and_get_column<ColumnFloat64>(*argument_column);
if (data_column == nullptr) {
return Status::InvalidArgument("Illegal column {} of first argument of function {}",
argument_column->get_name(), name);
}

auto result_column = ColumnString::create();
result_column->reserve(input_rows_count);
std::string buffer;
for (size_t i = 0; i < input_rows_count; ++i) {
double value = data_column->get_element(i);
if (std::isnan(value) || std::isinf(value)) {
return Status::InvalidArgument("Invalid argument value {} for function {}", value,
name);
}
buffer.clear();
to_human_readable(value, buffer);
result_column->insert_data(buffer.data(), buffer.size());
}

block.replace_by_position(result, std::move(result_column));
return Status::OK();
}

private:
static void append_unit(std::string& out, int64_t value, const char* singular,
const char* plural) {
if (!out.empty()) {
out += ", ";
}
out += std::to_string(value);
out += ' ';
out += (value == 1 ? singular : plural);
}

static void to_human_readable(double seconds, std::string& out) {
// Match Presto/Trino: round to whole seconds and ignore the sign.
Comment thread
prakash-atul marked this conversation as resolved.
// Saturate at int64_t max for very large finite inputs. This both matches the
// FE constant-folding path (Java Math.round saturates to Long.MAX_VALUE) and
// avoids std::llround's domain error when the rounded value exceeds int64_t.
double abs_seconds = std::fabs(seconds);
int64_t remain;
if (abs_seconds >= static_cast<double>(std::numeric_limits<int64_t>::max())) {
remain = std::numeric_limits<int64_t>::max();
} else {
remain = std::llround(abs_seconds);
}

constexpr int64_t WEEK = 7 * 24 * 60 * 60;
constexpr int64_t DAY = 24 * 60 * 60;
constexpr int64_t HOUR = 60 * 60;
constexpr int64_t MINUTE = 60;

const int64_t weeks = remain / WEEK;
remain %= WEEK;
const int64_t days = remain / DAY;
remain %= DAY;
const int64_t hours = remain / HOUR;
remain %= HOUR;
const int64_t minutes = remain / MINUTE;
const int64_t secs = remain % MINUTE;

if (weeks > 0) {
append_unit(out, weeks, "week", "weeks");
}
if (days > 0) {
append_unit(out, days, "day", "days");
}
if (hours > 0) {
append_unit(out, hours, "hour", "hours");
}
if (minutes > 0) {
append_unit(out, minutes, "minute", "minutes");
}
if (secs > 0 || out.empty()) {
append_unit(out, secs, "second", "seconds");
}
}
};

const std::string FunctionVersion::version = "5.7.99";

void register_function_utility(SimpleFunctionFactory& factory) {
factory.register_function<FunctionSleep>();
factory.register_function<FunctionVersion>();
factory.register_function<FunctionHumanReadableSeconds>();
}

} // namespace doris
56 changes: 56 additions & 0 deletions be/test/exprs/function/function_human_readable_seconds_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// 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.

#include <string>

#include "core/data_type/data_type_string.h"
#include "core/types.h"
#include "exprs/function/function_test_util.h"

namespace doris {
using namespace ut_type;

TEST(FunctionHumanReadableSecondsTest, one_arg) {
std::string func_name = "human_readable_seconds";

InputTypeSet input_types = {PrimitiveType::TYPE_DOUBLE};

// Presto/Trino semantics: round to whole seconds, ignore the sign, no milliseconds.
DataSet data_set = {
{{96.0}, std::string("1 minute, 36 seconds")},
{{3762.0}, std::string("1 hour, 2 minutes, 42 seconds")},
{{56363463.0}, std::string("93 weeks, 1 day, 8 hours, 31 minutes, 3 seconds")},
{{0.0}, std::string("0 seconds")},
{{0.4}, std::string("0 seconds")},
{{0.9}, std::string("1 second")},
{{1.2}, std::string("1 second")},
{{1.5}, std::string("2 seconds")},
{{61.0}, std::string("1 minute, 1 second")},
{{3600.0}, std::string("1 hour")},
{{604800.0}, std::string("1 week")},
{{475.33}, std::string("7 minutes, 55 seconds")},
// negative input uses absolute value (no leading '-')
{{-96.0}, std::string("1 minute, 36 seconds")},
{{-0.5}, std::string("1 second")},
{{1e20}, std::string("15250284452471 weeks, 3 days, 15 hours, 30 minutes, 7 seconds")},
{{-1e20}, std::string("15250284452471 weeks, 3 days, 15 hours, 30 minutes, 7 seconds")},
{{Null()}, Null()}};

check_function_all_arg_comb<DataTypeString, true>(func_name, input_types, data_set);
}

} // namespace doris
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@
import org.apache.doris.nereids.trees.expressions.functions.scalar.HoursAdd;
import org.apache.doris.nereids.trees.expressions.functions.scalar.HoursDiff;
import org.apache.doris.nereids.trees.expressions.functions.scalar.HoursSub;
import org.apache.doris.nereids.trees.expressions.functions.scalar.HumanReadableSeconds;
import org.apache.doris.nereids.trees.expressions.functions.scalar.If;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Ignore;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Initcap;
Expand Down Expand Up @@ -823,6 +824,7 @@ public class BuiltinScalarFunctions implements FunctionHelper {
scalar(HoursAdd.class, "hours_add"),
scalar(HoursDiff.class, "hours_diff"),
scalar(HoursSub.class, "hours_sub"),
scalar(HumanReadableSeconds.class, "human_readable_seconds"),
scalar(If.class, "if"),
scalar(Ignore.class, "ignore"),
scalar(Initcap.class, "initcap"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1340,6 +1340,61 @@ public static Expression secToTime(DoubleLiteral sec) {
return new TimeV2Literal(sec.getValue() * 1000000);
}

/**
* human_readable_seconds function for constant folding
*/
@ExecFunction(name = "human_readable_seconds")
public static Expression humanReadableSeconds(DoubleLiteral sec) {
return new VarcharLiteral(formatHumanReadableSeconds(sec.getValue()));
}

private static String formatHumanReadableSeconds(double seconds) {
if (Double.isNaN(seconds) || Double.isInfinite(seconds)) {
throw new AnalysisException("Invalid argument value " + seconds
+ " for function human_readable_seconds");
}

long remain = Math.round(Math.abs(seconds));
final long week = 7L * 24 * 60 * 60;
final long day = 24L * 60 * 60;
final long hour = 60L * 60;
final long minute = 60L;

long weeks = remain / week;
remain %= week;
long days = remain / day;
remain %= day;
long hours = remain / hour;
remain %= hour;
long minutes = remain / minute;
long secs = remain % minute;

StringBuilder result = new StringBuilder();
if (weeks > 0) {
appendUnit(result, weeks, "week", "weeks");
}
if (days > 0) {
appendUnit(result, days, "day", "days");
}
if (hours > 0) {
appendUnit(result, hours, "hour", "hours");
}
if (minutes > 0) {
appendUnit(result, minutes, "minute", "minutes");
}
if (secs > 0 || result.length() == 0) {
appendUnit(result, secs, "second", "seconds");
}
return result.toString();
}

private static void appendUnit(StringBuilder out, long value, String singular, String plural) {
if (out.length() > 0) {
out.append(", ");
}
out.append(value).append(' ').append(value == 1 ? singular : plural);
}

/**
* get_format function for constant folding
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// 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.ExplicitlyCastableSignature;
import org.apache.doris.nereids.trees.expressions.functions.PropagateNullable;
import org.apache.doris.nereids.trees.expressions.shape.UnaryExpression;
import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
import org.apache.doris.nereids.types.DoubleType;
import org.apache.doris.nereids.types.VarcharType;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;

import java.util.List;

/**
* ScalarFunction 'human_readable_seconds'.
*/
public class HumanReadableSeconds extends ScalarFunction
implements UnaryExpression, ExplicitlyCastableSignature, PropagateNullable {

public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
FunctionSignature.ret(VarcharType.SYSTEM_DEFAULT).args(DoubleType.INSTANCE)
);

public HumanReadableSeconds(Expression arg) {
super("human_readable_seconds", arg);
}

/** constructor for withChildren and reuse signature */
private HumanReadableSeconds(ScalarFunctionParams functionParams) {
super(functionParams);
}

@Override
public HumanReadableSeconds withChildren(List<Expression> children) {
Preconditions.checkArgument(children.size() == 1);
return new HumanReadableSeconds(getFunctionParams(children));
}

@Override
public List<FunctionSignature> getSignatures() {
return SIGNATURES;
}

@Override
public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
return visitor.visitHumanReadableSeconds(this, context);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,7 @@
import org.apache.doris.nereids.trees.expressions.functions.scalar.HoursAdd;
import org.apache.doris.nereids.trees.expressions.functions.scalar.HoursDiff;
import org.apache.doris.nereids.trees.expressions.functions.scalar.HoursSub;
import org.apache.doris.nereids.trees.expressions.functions.scalar.HumanReadableSeconds;
import org.apache.doris.nereids.trees.expressions.functions.scalar.If;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Ignore;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Initcap;
Expand Down Expand Up @@ -1292,6 +1293,10 @@ default R visitHoursSub(HoursSub hoursSub, C context) {
return visitScalarFunction(hoursSub, context);
}

default R visitHumanReadableSeconds(HumanReadableSeconds humanReadableSeconds, C context) {
return visitScalarFunction(humanReadableSeconds, context);
}

default R visitHourMinute(HourMinute hourMinute, C context) {
return visitScalarFunction(hourMinute, context);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@
import org.apache.doris.nereids.trees.expressions.literal.BigIntLiteral;
import org.apache.doris.nereids.trees.expressions.literal.DateTimeV2Literal;
import org.apache.doris.nereids.trees.expressions.literal.DecimalV3Literal;
import org.apache.doris.nereids.trees.expressions.literal.DoubleLiteral;
import org.apache.doris.nereids.trees.expressions.literal.SmallIntLiteral;
import org.apache.doris.nereids.trees.expressions.literal.StringLiteral;
import org.apache.doris.nereids.trees.expressions.literal.TinyIntLiteral;
import org.apache.doris.nereids.trees.expressions.literal.VarcharLiteral;
import org.apache.doris.nereids.types.DateTimeV2Type;

import org.junit.jupiter.api.Assertions;
Expand Down Expand Up @@ -166,4 +168,41 @@ public void testFromUnixTimeOutOfRangeThrows() {
Assertions.assertThrows(AnalysisException.class,
() -> DateTimeExtractAndTransform.fromUnixTime(dec));
}

@Test
public void testHumanReadableSeconds() {
// Presto/Trino round to whole seconds, drop the sign, and never emit milliseconds.
Assertions.assertEquals(new VarcharLiteral("1 minute, 36 seconds"),
DateTimeExtractAndTransform.humanReadableSeconds(new DoubleLiteral(96.0)));
Assertions.assertEquals(new VarcharLiteral("1 hour, 2 minutes, 42 seconds"),
DateTimeExtractAndTransform.humanReadableSeconds(new DoubleLiteral(3762.0)));
Assertions.assertEquals(new VarcharLiteral("93 weeks, 1 day, 8 hours, 31 minutes, 3 seconds"),
DateTimeExtractAndTransform.humanReadableSeconds(new DoubleLiteral(56363463.0)));
Assertions.assertEquals(new VarcharLiteral("0 seconds"),
DateTimeExtractAndTransform.humanReadableSeconds(new DoubleLiteral(0.0)));
// fractional input is rounded, not rendered as milliseconds
Assertions.assertEquals(new VarcharLiteral("7 minutes, 55 seconds"),
DateTimeExtractAndTransform.humanReadableSeconds(new DoubleLiteral(475.33)));
Assertions.assertEquals(new VarcharLiteral("1 second"),
DateTimeExtractAndTransform.humanReadableSeconds(new DoubleLiteral(0.9)));
// negative input uses absolute value (no leading '-')
Assertions.assertEquals(new VarcharLiteral("1 minute, 36 seconds"),
DateTimeExtractAndTransform.humanReadableSeconds(new DoubleLiteral(-96.0)));
Assertions.assertEquals(new VarcharLiteral("1 second"),
DateTimeExtractAndTransform.humanReadableSeconds(new DoubleLiteral(-0.5)));
// very large finite inputs saturate at Long.MAX_VALUE (Math.round), and BE matches
Assertions.assertEquals(
new VarcharLiteral("15250284452471 weeks, 3 days, 15 hours, 30 minutes, 7 seconds"),
DateTimeExtractAndTransform.humanReadableSeconds(new DoubleLiteral(1e20)));
Assertions.assertEquals(
new VarcharLiteral("15250284452471 weeks, 3 days, 15 hours, 30 minutes, 7 seconds"),
DateTimeExtractAndTransform.humanReadableSeconds(new DoubleLiteral(-1e20)));
// NaN / Infinity are rejected
Assertions.assertThrows(AnalysisException.class,
() -> DateTimeExtractAndTransform.humanReadableSeconds(
new DoubleLiteral(Double.NaN)));
Assertions.assertThrows(AnalysisException.class,
() -> DateTimeExtractAndTransform.humanReadableSeconds(
new DoubleLiteral(Double.POSITIVE_INFINITY)));
}
}
Loading
Loading