1#include <Functions/IFunctionImpl.h>
2#include <Functions/FunctionHelpers.h>
3#include <Functions/FunctionFactory.h>
4#include <DataTypes/DataTypesNumber.h>
5#include <DataTypes/DataTypeNullable.h>
6#include <DataTypes/DataTypeNothing.h>
7#include <DataTypes/getLeastSupertype.h>
8#include <Core/ColumnNumbers.h>
9#include <Columns/ColumnNullable.h>
10#include <Columns/ColumnLowCardinality.h>
11
12
13namespace DB
14{
15
16/// Implements the function coalesce which takes a set of arguments and
17/// returns the value of the leftmost non-null argument. If no such value is
18/// found, coalesce() returns NULL.
19class FunctionCoalesce : public IFunction
20{
21public:
22 static constexpr auto name = "coalesce";
23
24 static FunctionPtr create(const Context & context)
25 {
26 return std::make_shared<FunctionCoalesce>(context);
27 }
28
29 FunctionCoalesce(const Context & context_) : context(context_) {}
30
31 std::string getName() const override
32 {
33 return name;
34 }
35
36 bool useDefaultImplementationForNulls() const override { return false; }
37 bool isVariadic() const override { return true; }
38 size_t getNumberOfArguments() const override { return 0; }
39 ColumnNumbers getArgumentsThatDontImplyNullableReturnType(size_t number_of_arguments) const override
40 {
41 ColumnNumbers args;
42 for (size_t i = 0; i + 1 < number_of_arguments; ++i)
43 args.push_back(i);
44 return args;
45 }
46
47 DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override
48 {
49 /// Skip all NULL arguments. If any argument is non-Nullable, skip all next arguments.
50 DataTypes filtered_args;
51 filtered_args.reserve(arguments.size());
52 for (const auto & arg : arguments)
53 {
54 if (arg->onlyNull())
55 continue;
56
57 filtered_args.push_back(arg);
58
59 if (!arg->isNullable())
60 break;
61 }
62
63 DataTypes new_args;
64 for (size_t i = 0; i < filtered_args.size(); ++i)
65 {
66 bool is_last = i + 1 == filtered_args.size();
67
68 if (is_last)
69 new_args.push_back(filtered_args[i]);
70 else
71 new_args.push_back(removeNullable(filtered_args[i]));
72 }
73
74 if (new_args.empty())
75 return std::make_shared<DataTypeNullable>(std::make_shared<DataTypeNothing>());
76 if (new_args.size() == 1)
77 return new_args.front();
78
79 auto res = getLeastSupertype(new_args);
80
81 /// if last argument is not nullable, result should be also not nullable
82 if (!new_args.back()->isNullable() && res->isNullable())
83 res = removeNullable(res);
84
85 return res;
86 }
87
88 void executeImpl(Block & block, const ColumnNumbers & arguments, size_t result, size_t input_rows_count) override
89 {
90 /// coalesce(arg0, arg1, ..., argN) is essentially
91 /// multiIf(isNotNull(arg0), assumeNotNull(arg0), isNotNull(arg1), assumeNotNull(arg1), ..., argN)
92 /// with constant NULL arguments removed.
93
94 ColumnNumbers filtered_args;
95 filtered_args.reserve(arguments.size());
96 for (const auto & arg : arguments)
97 {
98 const auto & type = block.getByPosition(arg).type;
99
100 if (type->onlyNull())
101 continue;
102
103 filtered_args.push_back(arg);
104
105 if (!type->isNullable())
106 break;
107 }
108
109 auto is_not_null = FunctionFactory::instance().get("isNotNull", context);
110 auto assume_not_null = FunctionFactory::instance().get("assumeNotNull", context);
111 auto multi_if = FunctionFactory::instance().get("multiIf", context);
112
113 ColumnNumbers multi_if_args;
114
115 Block temp_block = block;
116
117 for (size_t i = 0; i < filtered_args.size(); ++i)
118 {
119 size_t res_pos = temp_block.columns();
120 bool is_last = i + 1 == filtered_args.size();
121
122 if (is_last)
123 {
124 multi_if_args.push_back(filtered_args[i]);
125 }
126 else
127 {
128 temp_block.insert({nullptr, std::make_shared<DataTypeUInt8>(), ""});
129 is_not_null->build({temp_block.getByPosition(filtered_args[i])})->execute(temp_block, {filtered_args[i]}, res_pos, input_rows_count);
130 temp_block.insert({nullptr, removeNullable(block.getByPosition(filtered_args[i]).type), ""});
131 assume_not_null->build({temp_block.getByPosition(filtered_args[i])})->execute(temp_block, {filtered_args[i]}, res_pos + 1, input_rows_count);
132
133 multi_if_args.push_back(res_pos);
134 multi_if_args.push_back(res_pos + 1);
135 }
136 }
137
138 /// If all arguments appeared to be NULL.
139 if (multi_if_args.empty())
140 {
141 block.getByPosition(result).column = block.getByPosition(result).type->createColumnConstWithDefaultValue(input_rows_count);
142 return;
143 }
144
145 if (multi_if_args.size() == 1)
146 {
147 block.getByPosition(result).column = block.getByPosition(multi_if_args.front()).column;
148 return;
149 }
150
151 ColumnsWithTypeAndName multi_if_args_elems;
152 multi_if_args_elems.reserve(multi_if_args.size());
153 for (auto column_num : multi_if_args)
154 multi_if_args_elems.emplace_back(temp_block.getByPosition(column_num));
155
156 multi_if->build(multi_if_args_elems)->execute(temp_block, multi_if_args, result, input_rows_count);
157
158 ColumnPtr res = std::move(temp_block.getByPosition(result).column);
159
160 /// if last argument is not nullable, result should be also not nullable
161 if (!block.getByPosition(multi_if_args.back()).column->isNullable() && res->isNullable())
162 {
163 if (auto * column_lc = checkAndGetColumn<ColumnLowCardinality>(*res))
164 res = checkAndGetColumn<ColumnNullable>(*column_lc->convertToFullColumn())->getNestedColumnPtr();
165 else if (auto * column_const = checkAndGetColumn<ColumnConst>(*res))
166 res = checkAndGetColumn<ColumnNullable>(column_const->getDataColumn())->getNestedColumnPtr();
167 else
168 res = checkAndGetColumn<ColumnNullable>(*res)->getNestedColumnPtr();
169 }
170
171 block.getByPosition(result).column = std::move(res);
172 }
173
174private:
175 const Context & context;
176};
177
178
179void registerFunctionCoalesce(FunctionFactory & factory)
180{
181 factory.registerFunction<FunctionCoalesce>(FunctionFactory::CaseInsensitive);
182}
183
184}
185