aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Analyzer/QueryTreePassManager.cpp
blob: cd3abd9593e7ec18af05c53e1e07236c02d35b01 (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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#include <Analyzer/QueryTreePassManager.h>

#include <memory>

#include <Common/Exception.h>

#include <IO/WriteHelpers.h>
#include <IO/Operators.h>

#include <DataTypes/IDataType.h>
#include <DataTypes/DataTypeLowCardinality.h>

#include <Interpreters/Context.h>

#include <Analyzer/ColumnNode.h>
#include <Analyzer/FunctionNode.h>
#include <Analyzer/InDepthQueryTreeVisitor.h>
#include <Analyzer/Utils.h>
#include <Analyzer/Passes/QueryAnalysisPass.h>
#include <Analyzer/Passes/CountDistinctPass.h>
#include <Analyzer/Passes/FunctionToSubcolumnsPass.h>
#include <Analyzer/Passes/RewriteAggregateFunctionWithIfPass.h>
#include <Analyzer/Passes/SumIfToCountIfPass.h>
#include <Analyzer/Passes/MultiIfToIfPass.h>
#include <Analyzer/Passes/IfConstantConditionPass.h>
#include <Analyzer/Passes/IfChainToMultiIfPass.h>
#include <Analyzer/Passes/OrderByTupleEliminationPass.h>
#include <Analyzer/Passes/NormalizeCountVariantsPass.h>
#include <Analyzer/Passes/AggregateFunctionsArithmericOperationsPass.h>
#include <Analyzer/Passes/UniqInjectiveFunctionsEliminationPass.h>
#include <Analyzer/Passes/OrderByLimitByDuplicateEliminationPass.h>
#include <Analyzer/Passes/FuseFunctionsPass.h>
#include <Analyzer/Passes/OptimizeGroupByFunctionKeysPass.h>
#include <Analyzer/Passes/IfTransformStringsToEnumPass.h>
#include <Analyzer/Passes/ConvertOrLikeChainPass.h>
#include <Analyzer/Passes/OptimizeRedundantFunctionsInOrderByPass.h>
#include <Analyzer/Passes/GroupingFunctionsResolvePass.h>
#include <Analyzer/Passes/AutoFinalOnQueryPass.h>
#include <Analyzer/Passes/ArrayExistsToHasPass.h>
#include <Analyzer/Passes/ComparisonTupleEliminationPass.h>
#include <Analyzer/Passes/LogicalExpressionOptimizerPass.h>
#include <Analyzer/Passes/CrossToInnerJoinPass.h>
#include <Analyzer/Passes/ShardNumColumnToFunctionPass.h>
#include <Analyzer/Passes/ConvertQueryToCNFPass.h>
#include <Analyzer/Passes/OptimizeDateOrDateTimeConverterWithPreimagePass.h>

namespace DB
{

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

namespace
{

#ifndef NDEBUG

/** This visitor checks if Query Tree structure is valid after each pass
  * in debug build.
  */
class ValidationChecker : public InDepthQueryTreeVisitor<ValidationChecker>
{
public:
    explicit ValidationChecker(String pass_name_)
        : pass_name(std::move(pass_name_))
    {}

    static bool needChildVisit(VisitQueryTreeNodeType & parent, VisitQueryTreeNodeType &)
    {
        if (parent->getNodeType() == QueryTreeNodeType::TABLE_FUNCTION)
            return false;

        return true;
    }

    void visitImpl(QueryTreeNodePtr & node) const
    {
        if (auto * column = node->as<ColumnNode>())
            return visitColumn(column);
        else if (auto * function = node->as<FunctionNode>())
            return visitFunction(function);
    }
private:
    void visitColumn(ColumnNode * column) const
    {
        if (column->getColumnSourceOrNull() == nullptr && column->getColumnName() != "__grouping_set")
            throw Exception(ErrorCodes::LOGICAL_ERROR,
                "Column {} {} query tree node does not have valid source node after running {} pass",
                column->getColumnName(), column->getColumnType(), pass_name);
    }

    void visitFunction(FunctionNode * function) const
    {
        if (!function->isResolved())
            throw Exception(ErrorCodes::LOGICAL_ERROR,
                "Function {} is not resolved after running {} pass",
                function->toAST()->formatForErrorMessage(), pass_name);

        if (isNameOfInFunction(function->getFunctionName()))
            return;

        const auto & expected_argument_types = function->getArgumentTypes();
        size_t expected_argument_types_size = expected_argument_types.size();
        auto actual_argument_columns = function->getArgumentColumns();

        if (expected_argument_types_size != actual_argument_columns.size())
            throw Exception(ErrorCodes::LOGICAL_ERROR,
                "Function {} expects {} arguments but has {} after running {} pass",
                function->toAST()->formatForErrorMessage(),
                expected_argument_types_size,
                actual_argument_columns.size(),
                pass_name);

        for (size_t i = 0; i < expected_argument_types_size; ++i)
        {
            const auto & expected_argument_type = expected_argument_types[i];
            const auto & actual_argument_type = actual_argument_columns[i].type;

            if (!expected_argument_type)
                throw Exception(ErrorCodes::LOGICAL_ERROR,
                    "Function {} expected argument {} type is not set after running {} pass",
                    function->toAST()->formatForErrorMessage(),
                    i + 1,
                    pass_name);

            if (!actual_argument_type)
                throw Exception(ErrorCodes::LOGICAL_ERROR,
                    "Function {} actual argument {} type is not set after running {} pass",
                    function->toAST()->formatForErrorMessage(),
                    i + 1,
                    pass_name);

            if (!expected_argument_type->equals(*actual_argument_type))
            {
                /// Aggregate functions remove low cardinality for their argument types
                if ((function->isAggregateFunction() || function->isWindowFunction()) &&
                    expected_argument_type->equals(*recursiveRemoveLowCardinality(actual_argument_type)))
                    continue;

                throw Exception(ErrorCodes::LOGICAL_ERROR,
                    "Function {} expects {} argument to have {} type but receives {} after running {} pass",
                    function->toAST()->formatForErrorMessage(),
                    i + 1,
                    expected_argument_type->getName(),
                    actual_argument_type->getName(),
                    pass_name);
            }
        }
    }

    String pass_name;
};
#endif

}

/** ClickHouse query tree pass manager.
  *
  * TODO: Support setting optimize_substitute_columns.
  * TODO: Support GROUP BY injective function elimination.
  * TODO: Support setting optimize_move_functions_out_of_any.
  * TODO: Support setting optimize_aggregators_of_group_by_keys.
  * TODO: Support setting optimize_duplicate_order_by_and_distinct.
  * TODO: Support setting optimize_monotonous_functions_in_order_by.
  * TODO: Add optimizations based on function semantics. Example: SELECT * FROM test_table WHERE id != id. (id is not nullable column).
  */

QueryTreePassManager::QueryTreePassManager(ContextPtr context_) : WithContext(context_) {}

void QueryTreePassManager::addPass(QueryTreePassPtr pass)
{
    passes.push_back(std::move(pass));
}

void QueryTreePassManager::run(QueryTreeNodePtr query_tree_node)
{
    auto current_context = getContext();
    size_t passes_size = passes.size();

    for (size_t i = 0; i < passes_size; ++i)
    {
        passes[i]->run(query_tree_node, current_context);
#ifndef NDEBUG
        ValidationChecker(passes[i]->getName()).visit(query_tree_node);
#endif
    }
}

void QueryTreePassManager::run(QueryTreeNodePtr query_tree_node, size_t up_to_pass_index)
{
    size_t passes_size = passes.size();
    if (up_to_pass_index > passes_size)
        throw Exception(ErrorCodes::BAD_ARGUMENTS,
            "Requested to run passes up to {} pass. There are only {} passes",
            up_to_pass_index,
            passes_size);

    auto current_context = getContext();
    for (size_t i = 0; i < up_to_pass_index; ++i)
    {
        passes[i]->run(query_tree_node, current_context);
#ifndef NDEBUG
        ValidationChecker(passes[i]->getName()).visit(query_tree_node);
#endif
    }
}

void QueryTreePassManager::dump(WriteBuffer & buffer)
{
    size_t passes_size = passes.size();

    for (size_t i = 0; i < passes_size; ++i)
    {
        auto & pass = passes[i];
        buffer << "Pass " << (i + 1) << ' ' << pass->getName() << " - " << pass->getDescription();
        if (i + 1 != passes_size)
            buffer << '\n';
    }
}

void QueryTreePassManager::dump(WriteBuffer & buffer, size_t up_to_pass_index)
{
    size_t passes_size = passes.size();
    if (up_to_pass_index > passes_size)
        throw Exception(ErrorCodes::BAD_ARGUMENTS,
            "Requested to dump passes up to {} pass. There are only {} passes",
            up_to_pass_index,
            passes_size);

    for (size_t i = 0; i < up_to_pass_index; ++i)
    {
        auto & pass = passes[i];
        buffer << "Pass " << (i + 1) << " " << pass->getName() << " - " << pass->getDescription();
        if (i + 1 != up_to_pass_index)
            buffer << '\n';
    }
}

void addQueryTreePasses(QueryTreePassManager & manager)
{
    manager.addPass(std::make_unique<QueryAnalysisPass>());
    manager.addPass(std::make_unique<FunctionToSubcolumnsPass>());

    manager.addPass(std::make_unique<ConvertLogicalExpressionToCNFPass>());

    manager.addPass(std::make_unique<CountDistinctPass>());
    manager.addPass(std::make_unique<RewriteAggregateFunctionWithIfPass>());
    manager.addPass(std::make_unique<SumIfToCountIfPass>());
    manager.addPass(std::make_unique<RewriteArrayExistsToHasPass>());
    manager.addPass(std::make_unique<NormalizeCountVariantsPass>());

    manager.addPass(std::make_unique<AggregateFunctionsArithmericOperationsPass>());
    manager.addPass(std::make_unique<UniqInjectiveFunctionsEliminationPass>());
    manager.addPass(std::make_unique<OptimizeGroupByFunctionKeysPass>());

    manager.addPass(std::make_unique<MultiIfToIfPass>());
    manager.addPass(std::make_unique<IfConstantConditionPass>());
    manager.addPass(std::make_unique<IfChainToMultiIfPass>());

    manager.addPass(std::make_unique<ComparisonTupleEliminationPass>());

    manager.addPass(std::make_unique<OptimizeRedundantFunctionsInOrderByPass>());

    manager.addPass(std::make_unique<OrderByTupleEliminationPass>());
    manager.addPass(std::make_unique<OrderByLimitByDuplicateEliminationPass>());

    manager.addPass(std::make_unique<FuseFunctionsPass>());

    manager.addPass(std::make_unique<IfTransformStringsToEnumPass>());

    manager.addPass(std::make_unique<ConvertOrLikeChainPass>());

    manager.addPass(std::make_unique<LogicalExpressionOptimizerPass>());

    manager.addPass(std::make_unique<GroupingFunctionsResolvePass>());
    manager.addPass(std::make_unique<AutoFinalOnQueryPass>());
    manager.addPass(std::make_unique<CrossToInnerJoinPass>());
    manager.addPass(std::make_unique<ShardNumColumnToFunctionPass>());
    manager.addPass(std::make_unique<OptimizeDateOrDateTimeConverterWithPreimagePass>());
}

}