ClickHouse
79 строк · 2.4 Кб
1#include <Functions/IFunction.h>
2#include <Functions/FunctionFactory.h>
3#include <Functions/FunctionHelpers.h>
4#include <DataTypes/DataTypeAggregateFunction.h>
5#include <Columns/ColumnAggregateFunction.h>
6#include <Common/typeid_cast.h>
7
8
9namespace DB
10{
11namespace ErrorCodes
12{
13extern const int ILLEGAL_COLUMN;
14extern const int ILLEGAL_TYPE_OF_ARGUMENT;
15}
16
17namespace
18{
19
20/** finalizeAggregation(agg_state) - get the result from the aggregation state.
21* Takes state of aggregate function. Returns result of aggregation (finalized state).
22*/
23class FunctionFinalizeAggregation : public IFunction
24{
25public:
26static constexpr auto name = "finalizeAggregation";
27static FunctionPtr create(ContextPtr)
28{
29return std::make_shared<FunctionFinalizeAggregation>();
30}
31
32String getName() const override
33{
34return name;
35}
36
37size_t getNumberOfArguments() const override
38{
39return 1;
40}
41
42bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return true; }
43
44bool useDefaultImplementationForConstants() const override { return true; }
45
46DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override
47{
48const DataTypeAggregateFunction * type = checkAndGetDataType<DataTypeAggregateFunction>(arguments[0].get());
49if (!type)
50{
51throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
52"Argument for function '{}' must have type AggregateFunction - state of aggregate function."
53" Got '{}' instead", getName(), arguments[0]->getName());
54}
55
56return type->getReturnType();
57}
58
59ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t /*input_rows_count*/) const override
60{
61auto column = arguments.at(0).column;
62if (!typeid_cast<const ColumnAggregateFunction *>(column.get()))
63throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}",
64arguments.at(0).column->getName(), getName());
65
66/// Column is copied here, because there is no guarantee that we own it.
67auto mut_column = IColumn::mutate(std::move(column));
68return ColumnAggregateFunction::convertToValues(std::move(mut_column));
69}
70};
71
72}
73
74REGISTER_FUNCTION(FinalizeAggregation)
75{
76factory.registerFunction<FunctionFinalizeAggregation>();
77}
78
79}
80