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
116 changes: 116 additions & 0 deletions be/src/exprs/function/function_utility.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,13 @@
// IWYU pragma: no_include <bits/chrono.h>
#include <algorithm>
#include <chrono> // IWYU pragma: keep
#include <cmath>
#include <limits>
#include <memory>
#include <string>
#include <thread>
#include <utility>
#include <vector>

#include "common/status.h"
#include "core/assert_cast.h"
Expand Down Expand Up @@ -138,11 +141,124 @@ 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->convert_to_full_column_if_const();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no need to do this. the outer framework did.

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();
for (size_t i = 0; i < input_rows_count; ++i) {
auto value = data_column->get_element(i);
auto text = _to_human_readable(value);
result_column->insert_data(text.data(), text.size());
}

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

private:
static std::string _append_unit(int64_t value, const char* singular, const char* plural) {
return std::to_string(value) + " " + (value == 1 ? singular : plural);
}

static std::string _to_human_readable(double seconds) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dont pass string as result. directly write to result column

if (std::isnan(seconds)) {
return "nan";
}
if (std::isinf(seconds)) {
return seconds > 0 ? "inf" : "-inf";
}

bool negative = seconds < 0;
double abs_seconds = std::fabs(seconds);
if (abs_seconds >= static_cast<double>(std::numeric_limits<int64_t>::max())) {
abs_seconds = static_cast<double>(std::numeric_limits<int64_t>::max());
}

double integral_part = 0;
double fractional_part = std::modf(abs_seconds, &integral_part);
int64_t remain = static_cast<int64_t>(integral_part);
int64_t millis = static_cast<int64_t>(std::llround(fractional_part * 1000.0));
if (millis == 1000) {
++remain;
millis = 0;
}
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;

std::vector<std::string> parts;
parts.reserve(5);
if (weeks > 0) {
parts.emplace_back(_append_unit(weeks, "week", "weeks"));
}
if (days > 0) {
parts.emplace_back(_append_unit(days, "day", "days"));
}
if (hours > 0) {
parts.emplace_back(_append_unit(hours, "hour", "hours"));
}
if (minutes > 0) {
parts.emplace_back(_append_unit(minutes, "minute", "minutes"));
}
if (secs > 0 || (parts.empty() && millis == 0)) {
parts.emplace_back(_append_unit(secs, "second", "seconds"));
}
if (millis > 0) {
parts.emplace_back(_append_unit(millis, "millisecond", "milliseconds"));
}

std::string result;
if (negative &&
(weeks > 0 || days > 0 || hours > 0 || minutes > 0 || secs > 0 || millis > 0)) {
result.push_back('-');
}
for (size_t i = 0; i < parts.size(); ++i) {
if (i != 0) {
result += ", ";
}
result += parts[i];
}
return result;
}
};

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
53 changes: 53 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,53 @@
// 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 <limits>
#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};

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")},
{{-96.0}, std::string("-1 minute, 36 seconds")},
{{0.9}, std::string("900 milliseconds")},
{{0.001}, std::string("1 millisecond")},
{{1.001}, std::string("1 second, 1 millisecond")},
{{475.33}, std::string("7 minutes, 55 seconds, 330 milliseconds")},
{{-0.5}, std::string("-500 milliseconds")},
{{1.2}, std::string("1 second")},
{{std::numeric_limits<double>::infinity()}, std::string("inf")},
{{-std::numeric_limits<double>::infinity()}, std::string("-inf")},
{{std::numeric_limits<double>::quiet_NaN()}, std::string("nan")},
{{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 @@ -250,6 +250,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 @@ -802,6 +803,7 @@ public class BuiltinScalarFunctions implements FunctionHelper {
scalar(HllFromBase64.class, "hll_from_base64"),
scalar(HllHash.class, "hll_hash"),
scalar(HllToBase64.class, "hll_to_base64"),
scalar(HumanReadableSeconds.class, "human_readable_seconds"),
scalar(Hour.class, "hour"),
scalar(HourCeil.class, "hour_ceil"),
scalar(HourFloor.class, "hour_floor"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import org.apache.doris.nereids.trees.expressions.literal.DoubleLiteral;
import org.apache.doris.nereids.trees.expressions.literal.IntegerLiteral;
import org.apache.doris.nereids.trees.expressions.literal.NullLiteral;
import org.apache.doris.nereids.trees.expressions.literal.NumericLiteral;
import org.apache.doris.nereids.trees.expressions.literal.SmallIntLiteral;
import org.apache.doris.nereids.trees.expressions.literal.StringLikeLiteral;
import org.apache.doris.nereids.trees.expressions.literal.StringLiteral;
Expand Down Expand Up @@ -67,7 +68,9 @@
import java.time.format.TextStyle;
import java.time.temporal.ChronoUnit;
import java.time.temporal.WeekFields;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

/**
Expand Down Expand Up @@ -1340,6 +1343,85 @@ 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(NumericLiteral sec) {
return new VarcharLiteral(formatHumanReadableSeconds(sec.getDouble()));
}

private static String formatHumanReadableSeconds(double seconds) {
if (Double.isNaN(seconds)) {
return "nan";
}
if (Double.isInfinite(seconds)) {
return seconds > 0 ? "inf" : "-inf";
}

boolean negative = seconds < 0;
double absSeconds = Math.abs(seconds);
if (absSeconds >= (double) Long.MAX_VALUE) {
absSeconds = (double) Long.MAX_VALUE;
}

long remain = (long) absSeconds;
long millis = Math.round((absSeconds - remain) * 1000.0d);
if (millis == 1000) {
remain++;
millis = 0;
}
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;

List<String> parts = new ArrayList<>(5);
if (weeks > 0) {
parts.add(formatUnit(weeks, "week", "weeks"));
}
if (days > 0) {
parts.add(formatUnit(days, "day", "days"));
}
if (hours > 0) {
parts.add(formatUnit(hours, "hour", "hours"));
}
if (minutes > 0) {
parts.add(formatUnit(minutes, "minute", "minutes"));
}
if (secs > 0 || (parts.isEmpty() && millis == 0)) {
parts.add(formatUnit(secs, "second", "seconds"));
}
if (millis > 0) {
parts.add(formatUnit(millis, "millisecond", "milliseconds"));
}

StringBuilder result = new StringBuilder();
if (negative && (weeks > 0 || days > 0 || hours > 0 || minutes > 0 || secs > 0 || millis > 0)) {
result.append('-');
}
for (int i = 0; i < parts.size(); i++) {
if (i > 0) {
result.append(", ");
}
result.append(parts.get(i));
}
return result.toString();
}

private static String formatUnit(long value, String singular, String plural) {
return value + " " + (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);
}
}
Loading
Loading