1#include <DataTypes/DataTypesNumber.h>
2#include <Columns/ColumnsNumber.h>
3#include "FunctionArrayMapped.h"
4#include <Functions/FunctionFactory.h>
5
6
7namespace DB
8{
9
10/** arrayCount(x1,...,xn -> expression, array1,...,arrayn) - for how many elements of the array the expression is true.
11 * An overload of the form f(array) is available, which works in the same way as f(x -> x, array).
12 */
13struct ArrayCountImpl
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<DataTypeUInt32>();
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 = ColumnUInt32::create(offsets.size());
39 ColumnUInt32::Container & out_counts = out_column->getData();
40
41 size_t pos = 0;
42 for (size_t i = 0; i < offsets.size(); ++i)
43 {
44 out_counts[i] = offsets[i] - pos;
45 pos = offsets[i];
46 }
47
48 return out_column;
49 }
50 else
51 return DataTypeUInt32().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 = ColumnUInt32::create(offsets.size());
57 ColumnUInt32::Container & out_counts = out_column->getData();
58
59 size_t pos = 0;
60 for (size_t i = 0; i < offsets.size(); ++i)
61 {
62 size_t count = 0;
63 for (; pos < offsets[i]; ++pos)
64 {
65 if (filter[pos])
66 ++count;
67 }
68 out_counts[i] = count;
69 }
70
71 return out_column;
72 }
73};
74
75struct NameArrayCount { static constexpr auto name = "arrayCount"; };
76using FunctionArrayCount = FunctionArrayMapped<ArrayCountImpl, NameArrayCount>;
77
78void registerFunctionArrayCount(FunctionFactory & factory)
79{
80 factory.registerFunction<FunctionArrayCount>();
81}
82
83}
84
85
86