aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Interpreters/getClusterName.cpp
blob: ea053d356d22fe1001346ca7c3e1c498f6247bdb (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
#include <Parsers/IAST.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTLiteral.h>
#include <Parsers/ASTFunction.h>
#include <Storages/checkAndGetLiteralArgument.h>
#include <Common/typeid_cast.h>

#include <Interpreters/getClusterName.h>


namespace DB
{

namespace ErrorCodes
{
    extern const int BAD_ARGUMENTS;
}


std::string getClusterName(const IAST & node)
{
    auto name = tryGetClusterName(node);
    if (!name)
        throw Exception(ErrorCodes::BAD_ARGUMENTS, "Illegal expression instead of cluster name.");
    return std::move(name).value();
}


std::optional<std::string> tryGetClusterName(const IAST & node)
{
    if (const auto * ast_id = node.as<ASTIdentifier>())
        return ast_id->name();

    if (const auto * ast_lit = node.as<ASTLiteral>())
    {
        if (ast_lit->value.getType() != Field::Types::String)
            return {};
        return ast_lit->value.safeGet<String>();
    }

    /// A hack to support hyphens in cluster names.
    if (const auto * ast_func = node.as<ASTFunction>())
    {
        if (ast_func->name != "minus" || !ast_func->arguments || ast_func->arguments->children.size() < 2)
            return {};

        String name;
        for (const auto & arg : ast_func->arguments->children)
        {
            if (name.empty())
                name += getClusterName(*arg);
            else
                name += "-" + getClusterName(*arg);
        }

        return name;
    }

    return {};
}


std::string getClusterNameAndMakeLiteral(ASTPtr & node)
{
    String cluster_name = getClusterName(*node);
    node = std::make_shared<ASTLiteral>(cluster_name);
    return cluster_name;
}

}