aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Interpreters/RedundantFunctionsInOrderByVisitor.h
blob: 60c9fcf2a24e06348af7726abb097d86d5d6baef (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
#pragma once

#include <Interpreters/InDepthNodeVisitor.h>
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTOrderByElement.h>
#include <Parsers/ASTExpressionList.h>
#include <Parsers/ASTIdentifier.h>
#include <Functions/FunctionFactory.h>

namespace DB
{

class ASTIdentifier;

class RedundantFunctionsInOrderByMatcher
{
public:
    struct Data
    {
        std::unordered_set<String> & keys;
        ContextPtr context;
        bool redundant = true;
        bool done = false;

        void preventErase()
        {
            redundant = false;
            done = true;
        }
    };

    static void visit(const ASTPtr & ast, Data & data)
    {
        if (const auto * func = ast->as<ASTFunction>())
            visit(*func, data);
    }

    static void visit(const ASTFunction & ast_function, Data & data)
    {
        if (data.done)
            return;

        bool is_lambda = (ast_function.name == "lambda");

        const auto & arguments = ast_function.arguments;
        bool has_arguments = arguments && !arguments->children.empty();

        if (is_lambda || !has_arguments)
        {
            data.preventErase();
            return;
        }

        /// If we meet function as argument then we have already checked
        /// arguments of it and if it can be erased
        for (const auto & arg : arguments->children)
        {
            /// Allow functions: visit them later
            if (arg->as<ASTFunction>())
                continue;

            /// Allow known identifiers: they are present in ORDER BY before current item
            if (auto * identifier = arg->as<ASTIdentifier>())
                if (data.keys.count(getIdentifierName(identifier)))
                    continue;

            /// Reject erase others
            data.preventErase();
            return;
        }

        const auto function = FunctionFactory::instance().tryGet(ast_function.name, data.context);
        if (!function || !function->isDeterministicInScopeOfQuery())
        {
            data.preventErase();
        }
    }

    static bool needChildVisit(const ASTPtr & node, const ASTPtr &)
    {
        /// Visit functions and their arguments, that are stored in ASTExpressionList.
        return node->as<ASTFunction>() || node->as<ASTExpressionList>();
    }
};

using RedundantFunctionsInOrderByVisitor = ConstInDepthNodeVisitor<RedundantFunctionsInOrderByMatcher, true>;

}