-
Notifications
You must be signed in to change notification settings - Fork 9k
Expand file tree
/
Copy patharraySort.cpp
More file actions
416 lines (362 loc) · 15.8 KB
/
Copy patharraySort.cpp
File metadata and controls
416 lines (362 loc) · 15.8 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
#include <Columns/ColumnDecimal.h>
#include <Columns/ColumnFixedString.h>
#include <Columns/ColumnString.h>
#include <Columns/ColumnsDateTime.h>
#include <DataTypes/IDataType.h>
#include <Functions/FunctionFactory.h>
#include <Functions/array/arraySort.h>
#include <Common/NaNUtils.h>
#include <Common/iota.h>
#include <base/extended_types.h>
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
}
namespace
{
template <bool positive, typename ColumnType>
struct Less
{
const ColumnType & column;
explicit Less(const IColumn & column_)
: column(assert_cast<const ColumnType &>(column_))
{
}
bool operator()(size_t lhs, size_t rhs) const
{
if constexpr (positive)
return column.compareAt(lhs, rhs, column, 1) < 0;
else
return column.compareAt(lhs, rhs, column, -1) > 0;
}
};
template <bool positive, typename ColumnType>
struct NullableLess
{
const ColumnType & nested_column;
const NullMap & null_map;
explicit NullableLess(const IColumn & nested_column_, const NullMap & null_map_)
: nested_column(assert_cast<const ColumnType &>(nested_column_))
, null_map(null_map_)
{
}
bool operator()(size_t lhs, size_t rhs) const
{
bool lhs_is_null = null_map[lhs];
bool rhs_is_null = null_map[rhs];
if (lhs_is_null) [[unlikely]]
return false;
if (rhs_is_null) [[unlikely]]
return true;
if constexpr (positive)
return nested_column.compareAt(lhs, rhs, nested_column, 1) < 0;
else
return nested_column.compareAt(lhs, rhs, nested_column, -1) > 0;
}
};
template <bool positive>
struct GenericLess
{
const IColumn & column;
explicit GenericLess(const IColumn & column_) : column(column_) { }
bool operator()(size_t lhs, size_t rhs) const
{
if constexpr (positive)
return column.compareAt(lhs, rhs, column, 1) < 0;
else
return column.compareAt(lhs, rhs, column, -1) > 0;
}
};
template <bool positive, typename ColumnType>
ColumnPtr sortNumericValues(const ColumnType & column, const ColumnArray & array)
{
using T = typename ColumnType::ValueType;
typename ColumnType::MutablePtr res_nested;
if constexpr (is_decimal<T>)
res_nested = ColumnType::create(0, column.getScale());
else
res_nested = ColumnType::create();
typename ColumnType::Container & data = res_nested->getData();
data.assign(column.getData());
auto sort_range = [](T * from, T * to)
{
if constexpr (positive)
::sort(from, to);
else
::sort(from, to, std::greater<T>());
};
const ColumnArray::Offsets & offsets = array.getOffsets();
T * base = data.data();
ColumnArray::Offset current_offset = 0;
for (auto next_offset : offsets)
{
T * begin = base + current_offset;
T * end = base + next_offset;
if constexpr (is_floating_point<T>)
{
/// All NaNs go last in both directions, matching the `nan_direction_hint` that the
/// generic path passes to `compareAt`.
T * nan_begin = std::partition(begin, end, [](T x) { return !isNaN(x); });
sort_range(begin, nan_begin);
}
else
{
sort_range(begin, end);
}
current_offset = next_offset;
}
return ColumnArray::create(std::move(res_nested), array.getOffsetsPtr());
}
template <bool positive>
ColumnPtr trySortNumericValues(const ColumnArray & array)
{
// NOLINTBEGIN(bugprone-macro-parentheses)
#define DISPATCH_FOR_NUMERIC_TYPE(TYPE) \
if (const auto * column = checkAndGetColumn<ColumnVector<TYPE>>(&array.getData())) \
return sortNumericValues<positive>(*column, array);
#define DISPATCH_FOR_DECIMAL_TYPE(TYPE) \
if (const auto * column = checkAndGetColumn<ColumnDecimal<TYPE>>(&array.getData())) \
return sortNumericValues<positive>(*column, array);
// NOLINTEND(bugprone-macro-parentheses)
FOR_NUMERIC_TYPES(DISPATCH_FOR_NUMERIC_TYPE)
DISPATCH_FOR_DECIMAL_TYPE(Decimal32)
DISPATCH_FOR_DECIMAL_TYPE(Decimal64)
DISPATCH_FOR_DECIMAL_TYPE(Decimal128)
DISPATCH_FOR_DECIMAL_TYPE(Decimal256)
DISPATCH_FOR_DECIMAL_TYPE(DateTime64)
#undef DISPATCH_FOR_NUMERIC_TYPE
#undef DISPATCH_FOR_DECIMAL_TYPE
return nullptr;
}
}
template <bool positive, bool is_partial>
ColumnPtr ArraySortImpl<positive, is_partial>::execute(
const ColumnArray & array,
ColumnPtr mapped,
const ColumnWithTypeAndName * fixed_arguments)
{
/// The limit (how many elements to partially sort) may differ from row to row when it is passed
/// as a non-constant column, so it is read per-row inside the loop below.
[[maybe_unused]] const IColumn * limit_column = nullptr;
if constexpr (is_partial)
{
if (!fixed_arguments)
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Expected fixed arguments to get the limit for partial array sort");
limit_column = fixed_arguments[0].column.get();
}
if constexpr (!is_partial)
{
/// `mapped` is the array's own data when there is no lambda (and when an identity lambda
/// returns its input column unchanged), so sorting a permutation by `mapped` and permuting
/// the data is equivalent to sorting the values themselves.
if (mapped.get() == &array.getData())
{
if (ColumnPtr res = trySortNumericValues<positive>(array))
return res;
}
}
const ColumnArray::Offsets & offsets = array.getOffsets();
size_t size = offsets.size();
size_t nested_size = array.getData().size();
IColumn::Permutation permutation(nested_size);
iota(permutation.data(), nested_size, IColumn::Permutation::value_type(0));
ColumnArray::Offset current_offset = 0;
#define APPLY_COMPARATOR(CMP) \
for (size_t i = 0; i < size; ++i) \
{ \
auto next_offset = offsets[i]; \
if constexpr (is_partial) \
{ \
const size_t limit = limit_column->getUInt(i); \
if (limit) \
{ \
const auto effective_limit = std::min<size_t>(limit, next_offset - current_offset); \
::partial_sort(&permutation[current_offset], &permutation[current_offset + effective_limit], &permutation[next_offset], CMP); \
} \
else \
::sort(&permutation[current_offset], &permutation[next_offset], CMP); \
} \
else \
::sort(&permutation[current_offset], &permutation[next_offset], CMP); \
current_offset = next_offset; \
}
#define DISPATCH_FOR_NONNULLABLE_COLUMN(TYPE) \
else if (checkAndGetColumn<TYPE>(mapped.get())) \
{ \
Less<positive, TYPE> cmp(*mapped); \
APPLY_COMPARATOR(cmp) \
}
if (false)
;
DISPATCH_FOR_NONNULLABLE_COLUMN(ColumnUInt8)
DISPATCH_FOR_NONNULLABLE_COLUMN(ColumnUInt16)
DISPATCH_FOR_NONNULLABLE_COLUMN(ColumnUInt32)
DISPATCH_FOR_NONNULLABLE_COLUMN(ColumnUInt64)
DISPATCH_FOR_NONNULLABLE_COLUMN(ColumnInt8)
DISPATCH_FOR_NONNULLABLE_COLUMN(ColumnInt16)
DISPATCH_FOR_NONNULLABLE_COLUMN(ColumnInt32)
DISPATCH_FOR_NONNULLABLE_COLUMN(ColumnInt64)
DISPATCH_FOR_NONNULLABLE_COLUMN(ColumnFloat32)
DISPATCH_FOR_NONNULLABLE_COLUMN(ColumnFloat64)
DISPATCH_FOR_NONNULLABLE_COLUMN(ColumnDateTime64)
DISPATCH_FOR_NONNULLABLE_COLUMN(ColumnDecimal<Decimal32>)
DISPATCH_FOR_NONNULLABLE_COLUMN(ColumnDecimal<Decimal64>)
DISPATCH_FOR_NONNULLABLE_COLUMN(ColumnDecimal<Decimal128>)
DISPATCH_FOR_NONNULLABLE_COLUMN(ColumnDecimal<Decimal256>)
DISPATCH_FOR_NONNULLABLE_COLUMN(ColumnString)
DISPATCH_FOR_NONNULLABLE_COLUMN(ColumnFixedString)
#undef DISPATCH_FOR_NONNULLABLE_COLUMN
else if (const auto * nullable = checkAndGetColumn<ColumnNullable>(mapped.get()))
{
const auto & null_map = nullable->getNullMapData();
#define DISPATCH_FOR_NULLABLE_COLUMN(TYPE) \
else if (checkAndGetColumn<TYPE>(&nullable->getNestedColumn())) \
{ \
NullableLess<positive, TYPE> cmp(nullable->getNestedColumn(), null_map); \
APPLY_COMPARATOR(cmp) \
}
if (false)
;
DISPATCH_FOR_NULLABLE_COLUMN(ColumnUInt8)
DISPATCH_FOR_NULLABLE_COLUMN(ColumnUInt16)
DISPATCH_FOR_NULLABLE_COLUMN(ColumnUInt32)
DISPATCH_FOR_NULLABLE_COLUMN(ColumnUInt64)
DISPATCH_FOR_NULLABLE_COLUMN(ColumnInt8)
DISPATCH_FOR_NULLABLE_COLUMN(ColumnInt16)
DISPATCH_FOR_NULLABLE_COLUMN(ColumnInt32)
DISPATCH_FOR_NULLABLE_COLUMN(ColumnInt64)
DISPATCH_FOR_NULLABLE_COLUMN(ColumnFloat32)
DISPATCH_FOR_NULLABLE_COLUMN(ColumnFloat64)
DISPATCH_FOR_NULLABLE_COLUMN(ColumnDateTime64)
DISPATCH_FOR_NULLABLE_COLUMN(ColumnDecimal<Decimal32>)
DISPATCH_FOR_NULLABLE_COLUMN(ColumnDecimal<Decimal64>)
DISPATCH_FOR_NULLABLE_COLUMN(ColumnDecimal<Decimal128>)
DISPATCH_FOR_NULLABLE_COLUMN(ColumnDecimal<Decimal256>)
DISPATCH_FOR_NULLABLE_COLUMN(ColumnString)
DISPATCH_FOR_NULLABLE_COLUMN(ColumnFixedString)
else
{
GenericLess<positive> cmp(*mapped);
APPLY_COMPARATOR(cmp)
}
#undef DISPATCH_FOR_NULLABLE_COLUMN
}
else
{
GenericLess<positive> cmp(*mapped);
APPLY_COMPARATOR(cmp)
}
#undef APPLY_COMPARATOR
return ColumnArray::create(array.getData().permute(permutation, 0), array.getOffsetsPtr());
}
REGISTER_FUNCTION(ArraySort)
{
FunctionDocumentation::Description description = R"(
Sorts the elements of the provided array in ascending order.
If a lambda function `f` is specified, sorting order is determined by the result of
the lambda applied to each element of the array.
If the lambda accepts multiple arguments, the `arraySort` function is passed several
arrays that the arguments of `f` will correspond to.
If the array to sort contains `-Inf`, `NULL`, `NaN`, or `Inf` they will be sorted in the following order:
1. `-Inf`
2. `Inf`
3. `NaN`
4. `NULL`
`arraySort` is a [higher-order function](/reference/functions/regular-functions/overview#higher-order-functions).
)";
FunctionDocumentation::Syntax syntax = "arraySort([f,] arr [, arr1, ... ,arrN])";
FunctionDocumentation::Arguments arguments = {
{"f(y1[, y2 ... yN])", "The lambda function to apply to elements of array `x`."},
{"arr", "An array to be sorted. [`Array(T)`](/reference/data-types/array)"},
{"arr1, ..., arrN", "Optional. N additional arrays, in the case when `f` accepts multiple arguments."}
};
FunctionDocumentation::ReturnedValue returned_value = {R"(
Returns the array `arr` sorted in ascending order if no lambda function is provided, otherwise
it returns an array sorted according to the logic of the provided lambda function. [`Array(T)`](/reference/data-types/array).
)"};
FunctionDocumentation::Examples examples = {
{"Example 1", "SELECT arraySort([1, 3, 3, 0]);", "[0,1,3,3]"},
{"Example 2", "SELECT arraySort(['hello', 'world', '!']);", "['!','hello','world']"},
{"Example 3", "SELECT arraySort([1, nan, 2, NULL, 3, nan, -4, NULL, inf, -inf]);", "[-inf,-4,1,2,3,inf,nan,nan,NULL,NULL]"}
};
FunctionDocumentation::IntroducedIn introduced_in = {1, 1};
FunctionDocumentation::Category category = FunctionDocumentation::Category::Array;
FunctionDocumentation documentation = {description, syntax, arguments, {}, returned_value, examples, introduced_in, category};
factory.registerFunction<FunctionArraySort>(documentation);
description = R"(
Sorts the elements of an array in descending order.
If a function `f` is specified, the provided array is sorted according to the result
of the function applied to the elements of the array, and then the sorted array is reversed.
If `f` accepts multiple arguments, the `arrayReverseSort` function is passed several arrays that
the arguments of `func` will correspond to.
If the array to sort contains `-Inf`, `NULL`, `NaN`, or `Inf` they will be sorted in the following order:
1. `-Inf`
2. `Inf`
3. `NaN`
4. `NULL`
`arrayReverseSort` is a [higher-order function](/reference/functions/regular-functions/overview#higher-order-functions).
)";
syntax = "arrayReverseSort([f,] arr [, arr1, ... ,arrN])";
returned_value = {R"(
Returns the array `x` sorted in descending order if no lambda function is provided, otherwise
it returns an array sorted according to the logic of the provided lambda function, and then reversed. [`Array(T)`](/reference/data-types/array).
)"};
examples = {
{"Example 1", "SELECT arrayReverseSort((x, y) -> y, [4, 3, 5], ['a', 'b', 'c']) AS res;", "[5,3,4]"},
{"Example 2", "SELECT arrayReverseSort((x, y) -> -y, [4, 3, 5], [1, 2, 3]) AS res;", "[4,3,5]"},
};
documentation = {description, syntax, arguments, {}, returned_value, examples, introduced_in, category};
factory.registerFunction<FunctionArrayReverseSort>(documentation);
description = R"(
This function is the same as `arraySort` but with an additional `limit` argument allowing partial sorting.
<Tip>
To retain only the sorted elements use `arrayResize`.
</Tip>
)";
syntax = "arrayPartialSort([f,] limit, arr [, arr1, ... ,arrN])";
arguments = {
{"f(arr[, arr1, ... ,arrN])", "The lambda function to apply to elements of array `x`.", {"Lambda function"}},
{"limit", "Index value up until which sorting will occur.", {"(U)Int*"}},
{"arr", "Array to be sorted.", {"Array(T)"}},
{"arr1, ... ,arrN", "N additional arrays, in the case when `f` accepts multiple arguments.", {"Array(T)"}}
};
returned_value = {R"(
Returns an array of the same size as the original array where elements in the range `[1..limit]` are sorted
in ascending order. The remaining elements `(limit..N]` are in an unspecified order.
)"};
examples = {
{"simple_int", "SELECT arrayPartialSort(2, [5, 9, 1, 3])", "[1,3,5,9]"},
{"simple_string", "SELECT arrayPartialSort(2, ['expenses', 'lasso', 'embolism', 'gladly'])", "['embolism','expenses','gladly','lasso']"},
{"retain_sorted", "SELECT arrayResize(arrayPartialSort(2, [5, 9, 1, 3]), 2)", "[1,3]"},
{"lambda_simple", "SELECT arrayPartialSort((x) -> -x, 2, [5, 9, 1, 3])", "[9,5,1,3]"},
{"lambda_complex", "SELECT arrayPartialSort((x, y) -> -y, 1, [0, 1, 2], [1, 2, 3]) as res", "[2,1,0]"}
};
introduced_in = {23, 2};
documentation = {description, syntax, arguments, {}, returned_value, examples, introduced_in, category};
factory.registerFunction<FunctionArrayPartialSort>(documentation);
description = R"(
This function is the same as `arrayReverseSort` but with an additional `limit` argument allowing partial sorting.
<Tip>
To retain only the sorted elements use `arrayResize`.
</Tip>
)";
syntax = "arrayPartialReverseSort([f,] limit, arr [, arr1, ... ,arrN])";
returned_value = {R"(
Returns an array of the same size as the original array where elements in the range `[1..limit]` are sorted
in descending order. The remaining elements `(limit..N]` are in an unspecified order.
)"};
examples = {
{"simple_int", "SELECT arrayPartialReverseSort(2, [5, 9, 1, 3])", "[9,5,1,3]"},
{"simple_string", "SELECT arrayPartialReverseSort(2, ['expenses','lasso','embolism','gladly'])", "['lasso','gladly','expenses','embolism']"},
{"retain_sorted", "SELECT arrayResize(arrayPartialReverseSort(2, [5, 9, 1, 3]), 2)", "[9,5]"},
{"lambda_simple", "SELECT arrayPartialReverseSort((x) -> -x, 2, [5, 9, 1, 3])", "[1,3,5,9]"},
{"lambda_complex", "SELECT arrayPartialReverseSort((x, y) -> -y, 1, [0, 1, 2], [1, 2, 3]) as res", "[0,1,2]"}
};
documentation = {description, syntax, arguments, {}, returned_value, examples, introduced_in, category};
factory.registerFunction<FunctionArrayPartialReverseSort>(documentation);
}
}