aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Analyzer/Passes/OptimizeDateOrDateTimeConverterWithPreimagePass.cpp
blob: 774c07ef1d46a76382d709fef82cda79e7bda242 (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
#include <Analyzer/Passes/OptimizeDateOrDateTimeConverterWithPreimagePass.h>

#include <Functions/FunctionFactory.h>

#include <Analyzer/InDepthQueryTreeVisitor.h>
#include <Analyzer/ColumnNode.h>
#include <Analyzer/ConstantNode.h>
#include <Analyzer/FunctionNode.h>
#include <Common/DateLUT.h>
#include <Common/DateLUTImpl.h>

namespace DB
{

namespace ErrorCodes
{
    extern const int LOGICAL_ERROR;
}

namespace
{

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

    explicit OptimizeDateOrDateTimeConverterWithPreimageVisitor(ContextPtr context)
        : Base(std::move(context))
    {}

    static bool needChildVisit(QueryTreeNodePtr & node, QueryTreeNodePtr & /*child*/)
    {
        const static std::unordered_set<String> relations = {
            "equals",
            "notEquals",
            "less",
            "greater",
            "lessOrEquals",
            "greaterOrEquals",
        };

        if (const auto * function = node->as<FunctionNode>())
        {
            return !relations.contains(function->getFunctionName());
        }

        return true;
    }

    void enterImpl(QueryTreeNodePtr & node) const
    {
        const static std::unordered_map<String, String> swap_relations = {
            {"equals", "equals"},
            {"notEquals", "notEquals"},
            {"less", "greater"},
            {"greater", "less"},
            {"lessOrEquals", "greaterOrEquals"},
            {"greaterOrEquals", "lessOrEquals"},
        };

        const auto * function = node->as<FunctionNode>();

        if (!function || !swap_relations.contains(function->getFunctionName())) return;

        if (function->getArguments().getNodes().size() != 2) return;

        size_t func_id = function->getArguments().getNodes().size();

        for (size_t i = 0; i < function->getArguments().getNodes().size(); i++)
        {
            if (const auto * func = function->getArguments().getNodes()[i]->as<FunctionNode>())
            {
                func_id = i;
            }
        }

        if (func_id == function->getArguments().getNodes().size()) return;

        size_t literal_id = 1 - func_id;
        const auto * literal = function->getArguments().getNodes()[literal_id]->as<ConstantNode>();

        if (!literal || literal->getValue().getType() != Field::Types::UInt64) return;

        String comparator = literal_id > func_id ? function->getFunctionName(): swap_relations.at(function->getFunctionName());

        const auto * func_node = function->getArguments().getNodes()[func_id]->as<FunctionNode>();
        /// Currently we only handle single-argument functions.
        if (!func_node || func_node->getArguments().getNodes().size() != 1) return;

        const auto * column_id = func_node->getArguments().getNodes()[0]->as<ColumnNode>();
        if (!column_id) return;

        const auto * column_type = column_id->getColumnType().get();
        if (!isDateOrDate32(column_type) && !isDateTime(column_type) && !isDateTime64(column_type)) return;

        const auto & converter = FunctionFactory::instance().tryGet(func_node->getFunctionName(), getContext());
        if (!converter) return;

        ColumnsWithTypeAndName args;
        args.emplace_back(column_id->getColumnType(), "tmp");
        auto converter_base = converter->build(args);
        if (!converter_base || !converter_base->hasInformationAboutPreimage()) return;

        auto preimage_range = converter_base->getPreimage(*(column_id->getColumnType()), literal->getValue());
        if (!preimage_range) return;

        const auto new_node = generateOptimizedDateFilter(comparator, *column_id, *preimage_range);

        if (!new_node) return;

        node = new_node;
    }

private:
    QueryTreeNodePtr generateOptimizedDateFilter(const String & comparator, const ColumnNode & column_node, const std::pair<Field, Field>& range) const
    {
        const DateLUTImpl & date_lut = DateLUT::instance("UTC");

        String start_date_or_date_time;
        String end_date_or_date_time;

        if (isDateOrDate32(column_node.getColumnType().get()))
        {
            start_date_or_date_time = date_lut.dateToString(range.first.get<DateLUTImpl::Time>());
            end_date_or_date_time = date_lut.dateToString(range.second.get<DateLUTImpl::Time>());
        }
        else if (isDateTime(column_node.getColumnType().get()) || isDateTime64(column_node.getColumnType().get()))
        {
            start_date_or_date_time = date_lut.timeToString(range.first.get<DateLUTImpl::Time>());
            end_date_or_date_time = date_lut.timeToString(range.second.get<DateLUTImpl::Time>());
        }
        else [[unlikely]] return {};

        if (comparator == "equals")
        {
            const auto lhs = std::make_shared<FunctionNode>("greaterOrEquals");
            lhs->getArguments().getNodes().push_back(std::make_shared<ColumnNode>(column_node.getColumn(), column_node.getColumnSource()));
            lhs->getArguments().getNodes().push_back(std::make_shared<ConstantNode>(start_date_or_date_time));
            resolveOrdinaryFunctionNode(*lhs, lhs->getFunctionName());

            const auto rhs = std::make_shared<FunctionNode>("less");
            rhs->getArguments().getNodes().push_back(std::make_shared<ColumnNode>(column_node.getColumn(), column_node.getColumnSource()));
            rhs->getArguments().getNodes().push_back(std::make_shared<ConstantNode>(end_date_or_date_time));
            resolveOrdinaryFunctionNode(*rhs, rhs->getFunctionName());

            const auto new_date_filter = std::make_shared<FunctionNode>("and");
            new_date_filter->getArguments().getNodes() = {lhs, rhs};
            resolveOrdinaryFunctionNode(*new_date_filter, new_date_filter->getFunctionName());

            return new_date_filter;
        }
        else if (comparator == "notEquals")
        {
            const auto lhs = std::make_shared<FunctionNode>("less");
            lhs->getArguments().getNodes().push_back(std::make_shared<ColumnNode>(column_node.getColumn(), column_node.getColumnSource()));
            lhs->getArguments().getNodes().push_back(std::make_shared<ConstantNode>(start_date_or_date_time));
            resolveOrdinaryFunctionNode(*lhs, lhs->getFunctionName());

            const auto rhs = std::make_shared<FunctionNode>("greaterOrEquals");
            rhs->getArguments().getNodes().push_back(std::make_shared<ColumnNode>(column_node.getColumn(), column_node.getColumnSource()));
            rhs->getArguments().getNodes().push_back(std::make_shared<ConstantNode>(end_date_or_date_time));
            resolveOrdinaryFunctionNode(*rhs, rhs->getFunctionName());

            const auto new_date_filter = std::make_shared<FunctionNode>("or");
            new_date_filter->getArguments().getNodes() = {lhs, rhs};
            resolveOrdinaryFunctionNode(*new_date_filter, new_date_filter->getFunctionName());

            return new_date_filter;
        }
        else if (comparator == "greater")
        {
            const auto new_date_filter = std::make_shared<FunctionNode>("greaterOrEquals");
            new_date_filter->getArguments().getNodes().push_back(std::make_shared<ColumnNode>(column_node.getColumn(), column_node.getColumnSource()));
            new_date_filter->getArguments().getNodes().push_back(std::make_shared<ConstantNode>(end_date_or_date_time));
            resolveOrdinaryFunctionNode(*new_date_filter, new_date_filter->getFunctionName());

            return new_date_filter;
        }
        else if (comparator == "lessOrEquals")
        {
            const auto new_date_filter = std::make_shared<FunctionNode>("less");
            new_date_filter->getArguments().getNodes().push_back(std::make_shared<ColumnNode>(column_node.getColumn(), column_node.getColumnSource()));
            new_date_filter->getArguments().getNodes().push_back(std::make_shared<ConstantNode>(end_date_or_date_time));
            resolveOrdinaryFunctionNode(*new_date_filter, new_date_filter->getFunctionName());

            return new_date_filter;
        }
        else if (comparator == "less" || comparator == "greaterOrEquals")
        {
            const auto new_date_filter = std::make_shared<FunctionNode>(comparator);
            new_date_filter->getArguments().getNodes().push_back(std::make_shared<ColumnNode>(column_node.getColumn(), column_node.getColumnSource()));
            new_date_filter->getArguments().getNodes().push_back(std::make_shared<ConstantNode>(start_date_or_date_time));
            resolveOrdinaryFunctionNode(*new_date_filter, new_date_filter->getFunctionName());

            return new_date_filter;
        }
        else [[unlikely]]
        {
            throw Exception(ErrorCodes::LOGICAL_ERROR,
                "Expected equals, notEquals, less, lessOrEquals, greater, greaterOrEquals. Actual {}",
                comparator);
        }
    }

    void resolveOrdinaryFunctionNode(FunctionNode & function_node, const String & function_name) const
    {
        auto function = FunctionFactory::instance().get(function_name, getContext());
        function_node.resolveAsFunction(function->build(function_node.getArgumentColumns()));
    }
};

}

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

}