1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
#include <Functions/IFunction.h>
#include <Functions/FunctionHelpers.h>
#include <Functions/FunctionFactory.h>
#include <DataTypes/DataTypeArray.h>
#include <DataTypes/DataTypesNumber.h>
#include <Columns/ColumnArray.h>
namespace DB
{
namespace ErrorCodes
{
extern const int ILLEGAL_TYPE_OF_ARGUMENT;
extern const int TOO_LARGE_ARRAY_SIZE;
}
/// Reasonable threshold.
static constexpr size_t max_arrays_size_in_columns = 1000000000;
/* arrayWithConstant(num, const) - make array of constants with length num.
* arrayWithConstant(3, 'hello') = ['hello', 'hello', 'hello']
* arrayWithConstant(1, 'hello') = ['hello']
* arrayWithConstant(0, 'hello') = []
*/
class FunctionArrayWithConstant : public IFunction
{
public:
static constexpr auto name = "arrayWithConstant";
static FunctionPtr create(ContextPtr) { return std::make_shared<FunctionArrayWithConstant>(); }
String getName() const override { return name; }
size_t getNumberOfArguments() const override { return 2; }
bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return true; }
DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override
{
if (!isNativeNumber(arguments[0]))
throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal type {} of argument of function {}, expected Integer",
arguments[0]->getName(), getName());
return std::make_shared<DataTypeArray>(arguments[1]);
}
bool useDefaultImplementationForConstants() const override { return true; }
bool useDefaultImplementationForNulls() const override { return false; }
ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t num_rows) const override
{
const auto * col_num = arguments[0].column.get();
const auto * col_value = arguments[1].column.get();
auto offsets_col = ColumnArray::ColumnOffsets::create();
ColumnArray::Offsets & offsets = offsets_col->getData();
offsets.reserve(num_rows);
ColumnArray::Offset offset = 0;
for (size_t i = 0; i < num_rows; ++i)
{
auto array_size = col_num->getInt(i);
if (unlikely(array_size < 0))
throw Exception(ErrorCodes::TOO_LARGE_ARRAY_SIZE, "Array size cannot be negative: while executing function {}", getName());
offset += array_size;
if (unlikely(offset > max_arrays_size_in_columns))
throw Exception(ErrorCodes::TOO_LARGE_ARRAY_SIZE, "Too large array size while executing function {}", getName());
offsets.push_back(offset);
}
return ColumnArray::create(col_value->replicate(offsets)->convertToFullColumnIfConst(), std::move(offsets_col));
}
};
REGISTER_FUNCTION(ArrayWithConstant)
{
factory.registerFunction<FunctionArrayWithConstant>();
}
}
|