aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Analyzer/Passes/AutoFinalOnQueryPass.cpp
blob: 2c89ec9dc202e96f1b9502fc22357598ddc293d1 (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
#include "AutoFinalOnQueryPass.h"

#include <Storages/IStorage.h>

#include <Analyzer/Utils.h>
#include <Analyzer/TableNode.h>
#include <Analyzer/TableFunctionNode.h>
#include <Analyzer/TableExpressionModifiers.h>
#include <Analyzer/InDepthQueryTreeVisitor.h>

namespace DB
{

namespace
{

class AutoFinalOnQueryPassVisitor : public InDepthQueryTreeVisitorWithContext<AutoFinalOnQueryPassVisitor>
{
public:
    using Base = InDepthQueryTreeVisitorWithContext<AutoFinalOnQueryPassVisitor>;
    using Base::Base;

    void enterImpl(QueryTreeNodePtr & node)
    {
        if (!getSettings().final)
            return;

        const auto * query_node = node->as<QueryNode>();
        if (!query_node)
            return;

        auto table_expressions = extractTableExpressions(query_node->getJoinTree());
        for (auto & table_expression : table_expressions)
            applyFinalIfNeeded(table_expression);
    }
private:
    static void applyFinalIfNeeded(QueryTreeNodePtr & node)
    {
        auto * table_node = node->as<TableNode>();
        auto * table_function_node = node->as<TableFunctionNode>();
        if (!table_node && !table_function_node)
            return;

        const auto & storage = table_node ? table_node->getStorage() : table_function_node->getStorage();
        bool is_final_supported = storage && storage->supportsFinal();
        if (!is_final_supported)
            return;

        TableExpressionModifiers table_expression_modifiers_with_final(true /*has_final*/, {}, {});

        if (table_node)
        {
            if (table_node->hasTableExpressionModifiers())
                table_node->getTableExpressionModifiers()->setHasFinal(true);
            else
                table_node->setTableExpressionModifiers(table_expression_modifiers_with_final);
        }
        else if (table_function_node)
        {
            if (table_function_node->hasTableExpressionModifiers())
                table_function_node->getTableExpressionModifiers()->setHasFinal(true);
            else
                table_function_node->setTableExpressionModifiers(table_expression_modifiers_with_final);
        }
    }
};

}

void AutoFinalOnQueryPass::run(QueryTreeNodePtr query_tree_node, ContextPtr context)
{
    auto visitor = AutoFinalOnQueryPassVisitor(std::move(context));
    visitor.visit(query_tree_node);
}

}