aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Interpreters/RewriteOrderByVisitor.cpp
blob: 694dec84b7a07e6393718990c10bdf826b6dc487 (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
#include <Interpreters/RewriteOrderByVisitor.hpp>
#include <Parsers/ASTExpressionList.h>
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTOrderByElement.h>
#include <Parsers/ASTSelectQuery.h>

namespace DB
{

void RewriteOrderBy::visit(ASTPtr & ast, Data &)
{
    auto * query = ast->as<ASTSelectQuery>();
    if (!query)
        return;

    const ASTPtr & order_by = query->orderBy();
    if (!order_by)
        return;

    const auto * expr_list = order_by->as<ASTExpressionList>();
    if (!expr_list)
        return;

    if (expr_list->children.size() != 1)
        return;

    const auto * order_by_elem = expr_list->children.front()->as<ASTOrderByElement>();
    if (!order_by_elem)
        return;

    const auto * func = order_by_elem->children.front()->as<ASTFunction>();
    if (!func || func->name != "tuple")
        return;

    if (const auto * inner_list = func->children.front()->as<ASTExpressionList>())
    {
        auto new_order_by = std::make_shared<ASTExpressionList>();
        for (const auto & identifier : inner_list->children)
        {
            // clone w/o children
            auto clone = std::make_shared<ASTOrderByElement>(*order_by_elem);
            clone->children.clear();

            clone->children.emplace_back(identifier);
            new_order_by->children.emplace_back(clone);
        }
        if (!new_order_by->children.empty())
            query->setExpression(ASTSelectQuery::Expression::ORDER_BY, std::move(new_order_by));
    }
}

}