ClickHouse
87 строк · 2.6 Кб
1#include <Functions/IFunction.h>
2#include <Functions/FunctionFactory.h>
3#include <Functions/FunctionHelpers.h>
4#include <DataTypes/DataTypeString.h>
5#include <Columns/ColumnString.h>
6#include <Interpreters/Context.h>
7#include <Common/Macros.h>
8#include <Core/Field.h>
9
10
11namespace DB
12{
13namespace ErrorCodes
14{
15extern const int ILLEGAL_TYPE_OF_ARGUMENT;
16extern const int ILLEGAL_COLUMN;
17}
18
19namespace
20{
21
22/** Get the value of macro from configuration file.
23* For example, it may be used as a sophisticated replacement for the function 'hostName' if servers have complicated hostnames
24* but you still need to distinguish them by some convenient names.
25*/
26class FunctionGetMacro : public IFunction
27{
28private:
29MultiVersion<Macros>::Version macros;
30bool is_distributed;
31
32public:
33static constexpr auto name = "getMacro";
34static FunctionPtr create(ContextPtr context)
35{
36return std::make_shared<FunctionGetMacro>(context->getMacros(), context->isDistributed());
37}
38
39explicit FunctionGetMacro(MultiVersion<Macros>::Version macros_, bool is_distributed_)
40: macros(std::move(macros_)), is_distributed(is_distributed_)
41{
42}
43
44String getName() const override
45{
46return name;
47}
48
49bool isDeterministic() const override { return false; }
50
51bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return false; }
52
53/// getMacro may return different values on different shards/replicas, so it's not constant for distributed query
54bool isSuitableForConstantFolding() const override { return !is_distributed; }
55
56size_t getNumberOfArguments() const override
57{
58return 1;
59}
60
61DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override
62{
63if (!isString(arguments[0]))
64throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "The argument of function {} must have String type", getName());
65return std::make_shared<DataTypeString>();
66}
67
68ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const override
69{
70const IColumn * arg_column = arguments[0].column.get();
71const ColumnString * arg_string = checkAndGetColumnConstData<ColumnString>(arg_column);
72
73if (!arg_string)
74throw Exception(ErrorCodes::ILLEGAL_COLUMN, "The argument of function {} must be constant String", getName());
75
76return result_type->createColumnConst(input_rows_count, macros->getValue(arg_string->getDataAt(0).toString()));
77}
78};
79
80}
81
82REGISTER_FUNCTION(GetMacro)
83{
84factory.registerFunction<FunctionGetMacro>();
85}
86
87}
88