aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Analyzer/Passes/GroupingFunctionsResolvePass.cpp
blob: 577bca8d1ae1fac7a6f539f3e4b53bb6b036ad2e (plain) (blame)
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
#include <Analyzer/Passes/GroupingFunctionsResolvePass.h>

#include <Core/ColumnNumbers.h>

#include <Functions/grouping.h>

#include <Interpreters/Context.h>

#include <Analyzer/InDepthQueryTreeVisitor.h>
#include <Analyzer/QueryNode.h>
#include <Analyzer/HashUtils.h>
#include <Analyzer/FunctionNode.h>
#include <Analyzer/ColumnNode.h>

namespace DB
{

namespace ErrorCodes
{
    extern const int BAD_ARGUMENTS;
    extern const int LOGICAL_ERROR;
}

namespace
{

enum class GroupByKind
{
    ORDINARY,
    ROLLUP,
    CUBE,
    GROUPING_SETS
};

class GroupingFunctionResolveVisitor : public InDepthQueryTreeVisitorWithContext<GroupingFunctionResolveVisitor>
{
public:
    GroupingFunctionResolveVisitor(GroupByKind group_by_kind_,
        QueryTreeNodePtrWithHashMap<size_t> aggregation_key_to_index_,
        ColumnNumbersList grouping_sets_keys_indices_,
        ContextPtr context_)
        : InDepthQueryTreeVisitorWithContext(std::move(context_))
        , group_by_kind(group_by_kind_)
        , aggregation_key_to_index(std::move(aggregation_key_to_index_))
        , grouping_sets_keys_indexes(std::move(grouping_sets_keys_indices_))
    {
    }

    void enterImpl(const QueryTreeNodePtr & node)
    {
        auto * function_node = node->as<FunctionNode>();
        if (!function_node || function_node->getFunctionName() != "grouping")
            return;

        auto & function_arguments = function_node->getArguments().getNodes();

        ColumnNumbers arguments_indexes;
        arguments_indexes.reserve(function_arguments.size());

        for (const auto & argument : function_arguments)
        {
            auto it = aggregation_key_to_index.find(argument);
            if (it == aggregation_key_to_index.end())
                throw Exception(ErrorCodes::BAD_ARGUMENTS,
                    "Argument {} of GROUPING function is not a part of GROUP BY clause",
                    argument->formatASTForErrorMessage());

            arguments_indexes.push_back(it->second);
        }

        FunctionOverloadResolverPtr grouping_function_resolver;
        bool add_grouping_set_column = false;

        bool force_grouping_standard_compatibility = getSettings().force_grouping_standard_compatibility;
        size_t aggregation_keys_size = aggregation_key_to_index.size();

        switch (group_by_kind)
        {
            case GroupByKind::ORDINARY:
            {
                auto grouping_ordinary_function = std::make_shared<FunctionGroupingOrdinary>(arguments_indexes,
                    force_grouping_standard_compatibility);
                grouping_function_resolver = std::make_shared<FunctionToOverloadResolverAdaptor>(std::move(grouping_ordinary_function));
                break;
            }
            case GroupByKind::ROLLUP:
            {
                auto grouping_rollup_function = std::make_shared<FunctionGroupingForRollup>(arguments_indexes,
                    aggregation_keys_size,
                    force_grouping_standard_compatibility);
                grouping_function_resolver = std::make_shared<FunctionToOverloadResolverAdaptor>(std::move(grouping_rollup_function));
                add_grouping_set_column = true;
                break;
            }
            case GroupByKind::CUBE:
            {
                auto grouping_cube_function = std::make_shared<FunctionGroupingForCube>(arguments_indexes,
                    aggregation_keys_size,
                    force_grouping_standard_compatibility);
                grouping_function_resolver = std::make_shared<FunctionToOverloadResolverAdaptor>(std::move(grouping_cube_function));
                add_grouping_set_column = true;
                break;
            }
            case GroupByKind::GROUPING_SETS:
            {
                auto grouping_grouping_sets_function = std::make_shared<FunctionGroupingForGroupingSets>(arguments_indexes,
                    grouping_sets_keys_indexes,
                    force_grouping_standard_compatibility);
                grouping_function_resolver = std::make_shared<FunctionToOverloadResolverAdaptor>(std::move(grouping_grouping_sets_function));
                add_grouping_set_column = true;
                break;
            }
        }

        if (add_grouping_set_column)
        {
            QueryTreeNodeWeakPtr column_source;
            auto grouping_set_column = NameAndTypePair{"__grouping_set", std::make_shared<DataTypeUInt64>()};
            auto grouping_set_argument_column = std::make_shared<ColumnNode>(std::move(grouping_set_column), std::move(column_source));
            function_arguments.insert(function_arguments.begin(), std::move(grouping_set_argument_column));
        }

        function_node->resolveAsFunction(grouping_function_resolver->build(function_node->getArgumentColumns()));
    }

    static bool needChildVisit(const QueryTreeNodePtr &, const QueryTreeNodePtr & child_node)
    {
        return !(child_node->getNodeType() == QueryTreeNodeType::QUERY || child_node->getNodeType() == QueryTreeNodeType::UNION);
    }

private:
    GroupByKind group_by_kind;
    QueryTreeNodePtrWithHashMap<size_t> aggregation_key_to_index;
    ColumnNumbersList grouping_sets_keys_indexes;
};

void resolveGroupingFunctions(QueryTreeNodePtr & query_node, ContextPtr context)
{
    auto & query_node_typed = query_node->as<QueryNode &>();

    size_t aggregation_node_index = 0;
    QueryTreeNodePtrWithHashMap<size_t> aggregation_key_to_index;

    std::vector<QueryTreeNodes> grouping_sets_used_aggregation_keys_list;

    if (query_node_typed.hasGroupBy())
    {
        /// It is expected by execution layer that if there are only 1 grouping set it will be removed
        if (query_node_typed.isGroupByWithGroupingSets() && query_node_typed.getGroupBy().getNodes().size() == 1)
        {
            auto grouping_set_list_node = query_node_typed.getGroupBy().getNodes().front();
            auto & grouping_set_list_node_typed = grouping_set_list_node->as<ListNode &>();
            query_node_typed.getGroupBy().getNodes() = std::move(grouping_set_list_node_typed.getNodes());
            query_node_typed.setIsGroupByWithGroupingSets(false);
        }

        if (query_node_typed.isGroupByWithGroupingSets())
        {
            for (const auto & grouping_set_keys_list_node : query_node_typed.getGroupBy().getNodes())
            {
                auto & grouping_set_keys_list_node_typed = grouping_set_keys_list_node->as<ListNode &>();

                grouping_sets_used_aggregation_keys_list.emplace_back();
                auto & grouping_sets_used_aggregation_keys = grouping_sets_used_aggregation_keys_list.back();

                QueryTreeNodePtrWithHashSet used_keys_in_set;

                for (auto & grouping_set_key_node : grouping_set_keys_list_node_typed.getNodes())
                {
                    if (used_keys_in_set.contains(grouping_set_key_node))
                        continue;
                    used_keys_in_set.insert(grouping_set_key_node);
                    grouping_sets_used_aggregation_keys.push_back(grouping_set_key_node);

                    if (aggregation_key_to_index.contains(grouping_set_key_node))
                        continue;
                    aggregation_key_to_index.emplace(grouping_set_key_node, aggregation_node_index);
                    ++aggregation_node_index;
                }
            }
        }
        else
        {
            for (auto & group_by_key_node : query_node_typed.getGroupBy().getNodes())
            {
                if (aggregation_key_to_index.contains(group_by_key_node))
                    continue;

                aggregation_key_to_index.emplace(group_by_key_node, aggregation_node_index);
                ++aggregation_node_index;
            }
        }
    }

    /// Indexes of aggregation keys used in each grouping set (only for GROUP BY GROUPING SETS)
    ColumnNumbersList grouping_sets_keys_indexes;

    for (const auto & grouping_set_used_aggregation_keys : grouping_sets_used_aggregation_keys_list)
    {
        grouping_sets_keys_indexes.emplace_back();
        auto & grouping_set_keys_indexes = grouping_sets_keys_indexes.back();

        for (const auto & used_aggregation_key : grouping_set_used_aggregation_keys)
        {
            auto aggregation_node_index_it = aggregation_key_to_index.find(used_aggregation_key);
            if (aggregation_node_index_it == aggregation_key_to_index.end())
                throw Exception(ErrorCodes::LOGICAL_ERROR,
                    "Aggregation key {} in GROUPING SETS is not found in GROUP BY keys",
                    used_aggregation_key->formatASTForErrorMessage());

            grouping_set_keys_indexes.push_back(aggregation_node_index_it->second);
        }
    }

    GroupByKind group_by_kind = GroupByKind::ORDINARY;
    if (query_node_typed.isGroupByWithRollup())
        group_by_kind = GroupByKind::ROLLUP;
    else if (query_node_typed.isGroupByWithCube())
        group_by_kind = GroupByKind::CUBE;
    else if (query_node_typed.isGroupByWithGroupingSets())
        group_by_kind = GroupByKind::GROUPING_SETS;

    GroupingFunctionResolveVisitor visitor(group_by_kind,
        std::move(aggregation_key_to_index),
        std::move(grouping_sets_keys_indexes),
        std::move(context));
    visitor.visit(query_node);
}

class GroupingFunctionsResolveVisitor : public InDepthQueryTreeVisitor<GroupingFunctionsResolveVisitor>
{
public:
    explicit GroupingFunctionsResolveVisitor(ContextPtr context_)
        : context(std::move(context_))
    {}

    void visitImpl(QueryTreeNodePtr & node)
    {
        if (node->getNodeType() != QueryTreeNodeType::QUERY)
            return;

        resolveGroupingFunctions(node, context);
    }

private:
    ContextPtr context;
};

}

void GroupingFunctionsResolvePass::run(QueryTreeNodePtr query_tree_node, ContextPtr context)
{
    GroupingFunctionsResolveVisitor visitor(std::move(context));
    visitor.visit(query_tree_node);
}

}