1 | #include <DataTypes/DataTypesNumber.h> |
2 | #include <Columns/ColumnsNumber.h> |
3 | #include "FunctionArrayMapped.h" |
4 | #include <Functions/FunctionFactory.h> |
5 | |
6 | |
7 | namespace DB |
8 | { |
9 | |
10 | /** arrayExists(x1,...,xn -> expression, array1,...,arrayn) - is the expression true for at least one array element. |
11 | * An overload of the form f(array) is available, which works in the same way as f(x -> x, array). |
12 | */ |
13 | struct ArrayExistsImpl |
14 | { |
15 | static bool needBoolean() { return true; } |
16 | static bool needExpression() { return false; } |
17 | static bool needOneArray() { return false; } |
18 | |
19 | static DataTypePtr getReturnType(const DataTypePtr & /*expression_return*/, const DataTypePtr & /*array_element*/) |
20 | { |
21 | return std::make_shared<DataTypeUInt8>(); |
22 | } |
23 | |
24 | static ColumnPtr execute(const ColumnArray & array, ColumnPtr mapped) |
25 | { |
26 | const ColumnUInt8 * column_filter = typeid_cast<const ColumnUInt8 *>(&*mapped); |
27 | |
28 | if (!column_filter) |
29 | { |
30 | auto column_filter_const = checkAndGetColumnConst<ColumnUInt8>(&*mapped); |
31 | |
32 | if (!column_filter_const) |
33 | throw Exception("Unexpected type of filter column" , ErrorCodes::ILLEGAL_COLUMN); |
34 | |
35 | if (column_filter_const->getValue<UInt8>()) |
36 | { |
37 | const IColumn::Offsets & offsets = array.getOffsets(); |
38 | auto out_column = ColumnUInt8::create(offsets.size()); |
39 | ColumnUInt8::Container & out_exists = out_column->getData(); |
40 | |
41 | size_t pos = 0; |
42 | for (size_t i = 0; i < offsets.size(); ++i) |
43 | { |
44 | out_exists[i] = offsets[i] - pos > 0; |
45 | pos = offsets[i]; |
46 | } |
47 | |
48 | return out_column; |
49 | } |
50 | else |
51 | return DataTypeUInt8().createColumnConst(array.size(), 0u); |
52 | } |
53 | |
54 | const IColumn::Filter & filter = column_filter->getData(); |
55 | const IColumn::Offsets & offsets = array.getOffsets(); |
56 | auto out_column = ColumnUInt8::create(offsets.size()); |
57 | ColumnUInt8::Container & out_exists = out_column->getData(); |
58 | |
59 | size_t pos = 0; |
60 | for (size_t i = 0; i < offsets.size(); ++i) |
61 | { |
62 | UInt8 exists = 0; |
63 | for (; pos < offsets[i]; ++pos) |
64 | { |
65 | if (filter[pos]) |
66 | { |
67 | exists = 1; |
68 | pos = offsets[i]; |
69 | break; |
70 | } |
71 | } |
72 | out_exists[i] = exists; |
73 | } |
74 | |
75 | return out_column; |
76 | } |
77 | }; |
78 | |
79 | struct NameArrayExists { static constexpr auto name = "arrayExists" ; }; |
80 | using FunctionArrayExists = FunctionArrayMapped<ArrayExistsImpl, NameArrayExists>; |
81 | |
82 | void registerFunctionArrayExists(FunctionFactory & factory) |
83 | { |
84 | factory.registerFunction<FunctionArrayExists>(); |
85 | } |
86 | |
87 | } |
88 | |
89 | |
90 | |