ClickHouse
103 строки · 3.0 Кб
1#include "config.h"
2
3#if USE_H3
4
5#include <Columns/ColumnsNumber.h>
6#include <DataTypes/DataTypesNumber.h>
7#include <Functions/FunctionFactory.h>
8#include <Functions/IFunction.h>
9#include <IO/WriteHelpers.h>
10#include <Common/typeid_cast.h>
11#include <base/range.h>
12
13#include <constants.h>
14#include <h3api.h>
15
16
17namespace DB
18{
19namespace ErrorCodes
20{
21extern const int ILLEGAL_TYPE_OF_ARGUMENT;
22extern const int ARGUMENT_OUT_OF_BOUND;
23extern const int ILLEGAL_COLUMN;
24}
25
26namespace
27{
28
29class FunctionH3HexAreaKm2 final : public IFunction
30{
31public:
32static constexpr auto name = "h3HexAreaKm2";
33
34static FunctionPtr create(ContextPtr) { return std::make_shared<FunctionH3HexAreaKm2>(); }
35
36std::string getName() const override { return name; }
37
38size_t getNumberOfArguments() const override { return 1; }
39bool useDefaultImplementationForConstants() const override { return true; }
40bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return false; }
41
42DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override
43{
44const auto * arg = arguments[0].get();
45if (!WhichDataType(arg).isUInt8())
46throw Exception(
47ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
48"Illegal type {} of argument {} of function {}. Must be UInt8",
49arg->getName(), 1, getName());
50
51return std::make_shared<DataTypeFloat64>();
52}
53
54ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override
55{
56auto non_const_arguments = arguments;
57for (auto & argument : non_const_arguments)
58argument.column = argument.column->convertToFullColumnIfConst();
59
60const auto * column = checkAndGetColumn<ColumnUInt8>(non_const_arguments[0].column.get());
61if (!column)
62throw Exception(
63ErrorCodes::ILLEGAL_COLUMN,
64"Illegal type {} of argument {} of function {}. Must be UInt8",
65arguments[0].column->getName(),
661,
67getName());
68
69const auto & data = column->getData();
70
71auto dst = ColumnVector<Float64>::create();
72auto & dst_data = dst->getData();
73dst_data.resize(input_rows_count);
74
75for (size_t row = 0; row < input_rows_count; ++row)
76{
77const UInt8 resolution = data[row];
78if (resolution > MAX_H3_RES)
79throw Exception(
80ErrorCodes::ARGUMENT_OUT_OF_BOUND,
81"The argument 'resolution' ({}) of function {} is out of bounds because the maximum resolution in H3 library is {}",
82toString(resolution),
83getName(),
84MAX_H3_RES);
85
86Float64 res = getHexagonAreaAvgKm2(resolution);
87dst_data[row] = res;
88}
89
90return dst;
91}
92};
93
94}
95
96REGISTER_FUNCTION(H3HexAreaKm2)
97{
98factory.registerFunction<FunctionH3HexAreaKm2>();
99}
100
101}
102
103#endif
104