| 1 | #include <Functions/FunctionFactory.h> |
|---|---|
| 2 | #include <Functions/FunctionUnaryArithmetic.h> |
| 3 | #include <DataTypes/NumberTraits.h> |
| 4 | #include <Common/FieldVisitors.h> |
| 5 | |
| 6 | namespace DB |
| 7 | { |
| 8 | |
| 9 | template <typename A> |
| 10 | struct AbsImpl |
| 11 | { |
| 12 | using ResultType = std::conditional_t<IsDecimalNumber<A>, A, typename NumberTraits::ResultOfAbs<A>::Type>; |
| 13 | |
| 14 | static inline NO_SANITIZE_UNDEFINED ResultType apply(A a) |
| 15 | { |
| 16 | if constexpr (IsDecimalNumber<A>) |
| 17 | return a < 0 ? A(-a) : a; |
| 18 | else if constexpr (is_integral_v<A> && is_signed_v<A>) |
| 19 | return a < 0 ? static_cast<ResultType>(~a) + 1 : a; |
| 20 | else if constexpr (is_integral_v<A> && is_unsigned_v<A>) |
| 21 | return static_cast<ResultType>(a); |
| 22 | else if constexpr (std::is_floating_point_v<A>) |
| 23 | return static_cast<ResultType>(std::abs(a)); |
| 24 | } |
| 25 | |
| 26 | #if USE_EMBEDDED_COMPILER |
| 27 | static constexpr bool compilable = false; /// special type handling, some other time |
| 28 | #endif |
| 29 | }; |
| 30 | |
| 31 | struct NameAbs { static constexpr auto name = "abs"; }; |
| 32 | using FunctionAbs = FunctionUnaryArithmetic<AbsImpl, NameAbs, false>; |
| 33 | |
| 34 | template <> struct FunctionUnaryArithmeticMonotonicity<NameAbs> |
| 35 | { |
| 36 | static bool has() { return true; } |
| 37 | static IFunction::Monotonicity get(const Field & left, const Field & right) |
| 38 | { |
| 39 | Float64 left_float = left.isNull() ? -std::numeric_limits<Float64>::infinity() : applyVisitor(FieldVisitorConvertToNumber<Float64>(), left); |
| 40 | Float64 right_float = right.isNull() ? std::numeric_limits<Float64>::infinity() : applyVisitor(FieldVisitorConvertToNumber<Float64>(), right); |
| 41 | |
| 42 | if ((left_float < 0 && right_float > 0) || (left_float > 0 && right_float < 0)) |
| 43 | return {}; |
| 44 | |
| 45 | return { true, (left_float > 0) }; |
| 46 | } |
| 47 | }; |
| 48 | |
| 49 | void registerFunctionAbs(FunctionFactory & factory) |
| 50 | { |
| 51 | factory.registerFunction<FunctionAbs>(FunctionFactory::CaseInsensitive); |
| 52 | } |
| 53 | |
| 54 | } |
| 55 |