aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Interpreters/RewriteCountVariantsVisitor.cpp
blob: f207bc51527a6136beb6fe6db4e83a3538034678 (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
#include <Interpreters/RewriteCountVariantsVisitor.h>
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTLiteral.h>
#include <Parsers/ASTSubquery.h>
#include <Parsers/ASTTablesInSelectQuery.h>
#include <Poco/String.h>
#include <Common/typeid_cast.h>
#include <Common/checkStackSize.h>
#include <Interpreters/Context.h>


namespace DB
{

void RewriteCountVariantsVisitor::visit(ASTPtr & node)
{
    checkStackSize();

    if (node->as<ASTSubquery>() || node->as<ASTTableExpression>() || node->as<ASTArrayJoin>())
        return;

    for (auto & child : node->children)
        visit(child);

    if (auto * func = node->as<ASTFunction>())
        visit(*func);
}

void RewriteCountVariantsVisitor::visit(ASTFunction & func)
{
    if (!func.arguments || func.arguments->children.empty() || func.arguments->children.size() > 1 || !func.arguments->children[0])
        return;

    auto name = Poco::toLower(func.name);

    if (name != "sum" && name != "count")
        return;

    auto & func_arguments = func.arguments->children;

    const auto * first_arg_literal = func_arguments[0]->as<ASTLiteral>();
    if (!first_arg_literal)
        return;

    bool transform = false;
    if (name == "count")
    {
        if (first_arg_literal->value.getType() != Field::Types::Null)
            transform = true;
    }
    else if (name == "sum")
    {
        if (first_arg_literal->value.getType() == Field::Types::UInt64)
        {
            auto constant = first_arg_literal->value.get<UInt64>();
            if (constant == 1 && !context->getSettingsRef().aggregate_functions_null_for_empty)
                transform = true;
        }
    }
    if (!transform)
        return;

    func.name = "count";
    func.arguments->children.clear();
}

}