SummingSortedAlgorithm.cpp 22.9 KB
Newer Older
1 2 3 4 5 6
#include <Processors/Merges/Algorithms/SummingSortedAlgorithm.h>

#include <AggregateFunctions/AggregateFunctionFactory.h>
#include <Columns/ColumnAggregateFunction.h>
#include <Columns/ColumnTuple.h>
#include <Common/AlignedBuffer.h>
N
Nikolai Kochetov 已提交
7
#include <Common/FieldVisitors.h>
8
#include <Common/StringUtils/StringUtils.h>
N
Nikolai Kochetov 已提交
9 10 11 12 13 14 15 16 17 18 19 20 21
#include <DataTypes/DataTypeArray.h>
#include <DataTypes/NestedUtils.h>
#include <IO/WriteHelpers.h>

namespace DB
{

namespace ErrorCodes
{
    extern const int LOGICAL_ERROR;
    extern const int CORRUPTED_DATA;
}

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
SummingSortedAlgorithm::ColumnsDefinition::ColumnsDefinition() = default;
SummingSortedAlgorithm::ColumnsDefinition::ColumnsDefinition(ColumnsDefinition &&) noexcept = default;
SummingSortedAlgorithm::ColumnsDefinition::~ColumnsDefinition() = default;

/// Stores numbers of key-columns and value-columns.
struct SummingSortedAlgorithm::MapDescription
{
    std::vector<size_t> key_col_nums;
    std::vector<size_t> val_col_nums;
};

/// Stores aggregation function, state, and columns to be used as function arguments.
struct SummingSortedAlgorithm::AggregateDescription
{
    /// An aggregate function 'sumWithOverflow' or 'sumMapWithOverflow' for summing.
    AggregateFunctionPtr function;
    IAggregateFunction::AddFunc add_function = nullptr;
    std::vector<size_t> column_numbers;
    IColumn * merged_column = nullptr;
    AlignedBuffer state;
    bool created = false;

N
Nikolai Kochetov 已提交
44 45
    /// In case when column has type AggregateFunction:
    /// use the aggregate function from itself instead of 'function' above.
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
    bool is_agg_func_type = false;

    void init(const char * function_name, const DataTypes & argument_types)
    {
        function = AggregateFunctionFactory::instance().get(function_name, argument_types);
        add_function = function->getAddressOfAddFunction();
        state.reset(function->sizeOfData(), function->alignOfData());
    }

    void createState()
    {
        if (created)
            return;
        if (is_agg_func_type)
            merged_column->insertDefault();
        else
            function->create(state.data());
        created = true;
    }

    void destroyState()
    {
        if (!created)
            return;
        if (!is_agg_func_type)
            function->destroy(state.data());
        created = false;
    }

    /// Explicitly destroy aggregation state if the stream is terminated
    ~AggregateDescription()
    {
        destroyState();
    }

    AggregateDescription() = default;
    AggregateDescription(AggregateDescription &&) = default;
    AggregateDescription(const AggregateDescription &) = delete;
};


N
Nikolai Kochetov 已提交
87 88
static bool isInPrimaryKey(const SortDescription & description, const std::string & name, const size_t number)
{
A
Alexey Milovidov 已提交
89
    for (const auto & desc : description)
N
Nikolai Kochetov 已提交
90 91 92 93 94 95 96
        if (desc.column_name == name || (desc.column_name.empty() && desc.column_number == number))
            return true;

    return false;
}

/// Returns true if merge result is not empty
97
static bool mergeMap(const SummingSortedAlgorithm::MapDescription & desc,
N
Nikolai Kochetov 已提交
98
                     Row & row, const ColumnRawPtrs & raw_columns, size_t row_number)
N
Nikolai Kochetov 已提交
99 100 101 102 103 104 105
{
    /// Strongly non-optimal.

    Row & left = row;
    Row right(left.size());

    for (size_t col_num : desc.key_col_nums)
N
Nikolai Kochetov 已提交
106
        right[col_num] = (*raw_columns[col_num])[row_number].template get<Array>();
N
Nikolai Kochetov 已提交
107 108

    for (size_t col_num : desc.val_col_nums)
N
Nikolai Kochetov 已提交
109
        right[col_num] = (*raw_columns[col_num])[row_number].template get<Array>();
N
Nikolai Kochetov 已提交
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

    auto at_ith_column_jth_row = [&](const Row & matrix, size_t i, size_t j) -> const Field &
    {
        return matrix[i].get<Array>()[j];
    };

    auto tuple_of_nth_columns_at_jth_row = [&](const Row & matrix, const ColumnNumbers & col_nums, size_t j) -> Array
    {
        size_t size = col_nums.size();
        Array res(size);
        for (size_t col_num_index = 0; col_num_index < size; ++col_num_index)
            res[col_num_index] = at_ith_column_jth_row(matrix, col_nums[col_num_index], j);
        return res;
    };

    std::map<Array, Array> merged;

    auto accumulate = [](Array & dst, const Array & src)
    {
        bool has_non_zero = false;
        size_t size = dst.size();
        for (size_t i = 0; i < size; ++i)
            if (applyVisitor(FieldVisitorSum(src[i]), dst[i]))
                has_non_zero = true;
        return has_non_zero;
    };

    auto merge = [&](const Row & matrix)
    {
        size_t rows = matrix[desc.key_col_nums[0]].get<Array>().size();

        for (size_t j = 0; j < rows; ++j)
        {
            Array key = tuple_of_nth_columns_at_jth_row(matrix, desc.key_col_nums, j);
            Array value = tuple_of_nth_columns_at_jth_row(matrix, desc.val_col_nums, j);

            auto it = merged.find(key);
            if (merged.end() == it)
                merged.emplace(std::move(key), std::move(value));
            else
            {
                if (!accumulate(it->second, value))
                    merged.erase(it);
            }
        }
    };

    merge(left);
    merge(right);

    for (size_t col_num : desc.key_col_nums)
        row[col_num] = Array(merged.size());
    for (size_t col_num : desc.val_col_nums)
        row[col_num] = Array(merged.size());

N
Nikolai Kochetov 已提交
165
    size_t row_num = 0;
N
Nikolai Kochetov 已提交
166 167 168
    for (const auto & key_value : merged)
    {
        for (size_t col_num_index = 0, size = desc.key_col_nums.size(); col_num_index < size; ++col_num_index)
N
Nikolai Kochetov 已提交
169
            row[desc.key_col_nums[col_num_index]].get<Array>()[row_num] = key_value.first[col_num_index];
N
Nikolai Kochetov 已提交
170 171

        for (size_t col_num_index = 0, size = desc.val_col_nums.size(); col_num_index < size; ++col_num_index)
N
Nikolai Kochetov 已提交
172
            row[desc.val_col_nums[col_num_index]].get<Array>()[row_num] = key_value.second[col_num_index];
N
Nikolai Kochetov 已提交
173

N
Nikolai Kochetov 已提交
174
        ++row_num;
N
Nikolai Kochetov 已提交
175 176
    }

N
Nikolai Kochetov 已提交
177
    return row_num != 0;
N
Nikolai Kochetov 已提交
178 179 180 181 182 183 184 185 186
}

static SummingSortedAlgorithm::ColumnsDefinition defineColumns(
    const Block & header,
    const SortDescription & description,
    const Names & column_names_to_sum)
{
    size_t num_columns = header.columns();
    SummingSortedAlgorithm::ColumnsDefinition def;
187
    def.column_names = header.getNames();
N
Nikolai Kochetov 已提交
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

    /// name of nested structure -> the column numbers that refer to it.
    std::unordered_map<std::string, std::vector<size_t>> discovered_maps;

    /** Fill in the column numbers, which must be summed.
        * This can only be numeric columns that are not part of the sort key.
        * If a non-empty column_names_to_sum is specified, then we only take these columns.
        * Some columns from column_names_to_sum may not be found. This is ignored.
        */
    for (size_t i = 0; i < num_columns; ++i)
    {
        const ColumnWithTypeAndName & column = header.safeGetByPosition(i);

        /// Discover nested Maps and find columns for summation
        if (typeid_cast<const DataTypeArray *>(column.type.get()))
        {
            const auto map_name = Nested::extractTableName(column.name);
            /// if nested table name ends with `Map` it is a possible candidate for special handling
            if (map_name == column.name || !endsWith(map_name, "Map"))
            {
                def.column_numbers_not_to_aggregate.push_back(i);
                continue;
            }

            discovered_maps[map_name].emplace_back(i);
        }
        else
        {
            bool is_agg_func = WhichDataType(column.type).isAggregateFunction();

            /// There are special const columns for example after prewhere sections.
            if ((!column.type->isSummable() && !is_agg_func) || isColumnConst(*column.column))
            {
                def.column_numbers_not_to_aggregate.push_back(i);
                continue;
            }

            /// Are they inside the PK?
            if (isInPrimaryKey(description, column.name, i))
            {
                def.column_numbers_not_to_aggregate.push_back(i);
                continue;
            }

            if (column_names_to_sum.empty()
                || column_names_to_sum.end() !=
                   std::find(column_names_to_sum.begin(), column_names_to_sum.end(), column.name))
            {
                // Create aggregator to sum this column
                SummingSortedAlgorithm::AggregateDescription desc;
                desc.is_agg_func_type = is_agg_func;
                desc.column_numbers = {i};

                if (!is_agg_func)
                {
                    desc.init("sumWithOverflow", {column.type});
                }

                def.columns_to_aggregate.emplace_back(std::move(desc));
            }
            else
            {
                // Column is not going to be summed, use last value
                def.column_numbers_not_to_aggregate.push_back(i);
            }
        }
    }

    /// select actual nested Maps from list of candidates
    for (const auto & map : discovered_maps)
    {
        /// map should contain at least two elements (key -> value)
        if (map.second.size() < 2)
        {
            for (auto col : map.second)
                def.column_numbers_not_to_aggregate.push_back(col);
            continue;
        }

        /// no elements of map could be in primary key
        auto column_num_it = map.second.begin();
        for (; column_num_it != map.second.end(); ++column_num_it)
            if (isInPrimaryKey(description, header.safeGetByPosition(*column_num_it).name, *column_num_it))
                break;
        if (column_num_it != map.second.end())
        {
            for (auto col : map.second)
                def.column_numbers_not_to_aggregate.push_back(col);
            continue;
        }

        DataTypes argument_types;
        SummingSortedAlgorithm::AggregateDescription desc;
        SummingSortedAlgorithm::MapDescription map_desc;

        column_num_it = map.second.begin();
        for (; column_num_it != map.second.end(); ++column_num_it)
        {
            const ColumnWithTypeAndName & key_col = header.safeGetByPosition(*column_num_it);
            const String & name = key_col.name;
            const IDataType & nested_type = *assert_cast<const DataTypeArray &>(*key_col.type).getNestedType();

            if (column_num_it == map.second.begin()
                || endsWith(name, "ID")
                || endsWith(name, "Key")
                || endsWith(name, "Type"))
            {
                if (!nested_type.isValueRepresentedByInteger() && !isStringOrFixedString(nested_type))
                    break;

                map_desc.key_col_nums.push_back(*column_num_it);
            }
            else
            {
                if (!nested_type.isSummable())
                    break;

                map_desc.val_col_nums.push_back(*column_num_it);
            }

            // Add column to function arguments
            desc.column_numbers.push_back(*column_num_it);
            argument_types.push_back(key_col.type);
        }

        if (column_num_it != map.second.end())
        {
            for (auto col : map.second)
                def.column_numbers_not_to_aggregate.push_back(col);
            continue;
        }

        if (map_desc.key_col_nums.size() == 1)
        {
            // Create summation for all value columns in the map
            desc.init("sumMapWithOverflow", argument_types);
            def.columns_to_aggregate.emplace_back(std::move(desc));
        }
        else
        {
            // Fall back to legacy mergeMaps for composite keys
            for (auto col : map.second)
                def.column_numbers_not_to_aggregate.push_back(col);
            def.maps_to_sum.emplace_back(std::move(map_desc));
        }
    }

    return def;
}

static MutableColumns getMergedDataColumns(
    const Block & header,
N
Nikolai Kochetov 已提交
340
    const SummingSortedAlgorithm::ColumnsDefinition & def)
N
Nikolai Kochetov 已提交
341 342
{
    MutableColumns columns;
N
Nikolai Kochetov 已提交
343 344
    size_t num_columns = def.column_numbers_not_to_aggregate.size() + def.columns_to_aggregate.size();
    columns.reserve(num_columns);
N
Nikolai Kochetov 已提交
345

A
Alexey Milovidov 已提交
346
    for (const auto & desc : def.columns_to_aggregate)
N
Nikolai Kochetov 已提交
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    {
        // Wrap aggregated columns in a tuple to match function signature
        if (!desc.is_agg_func_type && isTuple(desc.function->getReturnType()))
        {
            size_t tuple_size = desc.column_numbers.size();
            MutableColumns tuple_columns(tuple_size);
            for (size_t i = 0; i < tuple_size; ++i)
                tuple_columns[i] = header.safeGetByPosition(desc.column_numbers[i]).column->cloneEmpty();

            columns.emplace_back(ColumnTuple::create(std::move(tuple_columns)));
        }
        else
            columns.emplace_back(header.safeGetByPosition(desc.column_numbers[0]).column->cloneEmpty());
    }

A
Alexey Milovidov 已提交
362
    for (const auto & column_number : def.column_numbers_not_to_aggregate)
N
Nikolai Kochetov 已提交
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
        columns.emplace_back(header.safeGetByPosition(column_number).type->createColumn());

    return columns;
}

static void preprocessChunk(Chunk & chunk)
{
    auto num_rows = chunk.getNumRows();
    auto columns = chunk.detachColumns();

    for (auto & column : columns)
        column = column->convertToFullColumnIfConst();

    chunk.setColumns(std::move(columns), num_rows);
}

static void postprocessChunk(
    Chunk & chunk, size_t num_result_columns,
    const SummingSortedAlgorithm::ColumnsDefinition & def)
{
    size_t num_rows = chunk.getNumRows();
    auto columns = chunk.detachColumns();

    Columns res_columns(num_result_columns);
    size_t next_column = 0;

A
Alexey Milovidov 已提交
389
    for (const auto & desc : def.columns_to_aggregate)
N
Nikolai Kochetov 已提交
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
    {
        auto column = std::move(columns[next_column]);
        ++next_column;

        if (!desc.is_agg_func_type && isTuple(desc.function->getReturnType()))
        {
            /// Unpack tuple into block.
            size_t tuple_size = desc.column_numbers.size();
            for (size_t i = 0; i < tuple_size; ++i)
                res_columns[desc.column_numbers[i]] = assert_cast<const ColumnTuple &>(*column).getColumnPtr(i);
        }
        else
            res_columns[desc.column_numbers[0]] = std::move(column);
    }

    for (auto column_number : def.column_numbers_not_to_aggregate)
    {
        auto column = std::move(columns[next_column]);
        ++next_column;

        res_columns[column_number] = std::move(column);
    }

    chunk.setColumns(std::move(res_columns), num_rows);
}

416
static void setRow(Row & row, const ColumnRawPtrs & raw_columns, size_t row_num, const Names & column_names)
N
Nikolai Kochetov 已提交
417 418 419 420 421 422
{
    size_t num_columns = row.size();
    for (size_t i = 0; i < num_columns; ++i)
    {
        try
        {
423
            raw_columns[i]->get(row_num, row[i]);
N
Nikolai Kochetov 已提交
424 425 426 427 428 429 430 431 432 433 434
        }
        catch (...)
        {
            tryLogCurrentException(__PRETTY_FUNCTION__);

            /// Find out the name of the column and throw more informative exception.

            String column_name;
            if (i < column_names.size())
                column_name = column_names[i];

435
            throw Exception("MergingSortedBlockInputStream failed to read row " + toString(row_num)
N
Nikolai Kochetov 已提交
436 437 438 439 440 441 442
                            + " of column " + toString(i) + (column_name.empty() ? "" : " (" + column_name + ")"),
                            ErrorCodes::CORRUPTED_DATA);
        }
    }
}


443 444 445 446
SummingSortedAlgorithm::SummingMergedData::SummingMergedData(
    MutableColumns columns_, UInt64 max_block_size_, ColumnsDefinition & def_)
    : MergedData(std::move(columns_), false, max_block_size_)
    , def(def_)
N
Nikolai Kochetov 已提交
447
{
448 449
    current_row.resize(def.column_names.size());
    initAggregateDescription();
N
Nikolai Kochetov 已提交
450 451
}

452
void SummingSortedAlgorithm::SummingMergedData::startGroup(ColumnRawPtrs & raw_columns, size_t row)
N
Nikolai Kochetov 已提交
453
{
N
Nikolai Kochetov 已提交
454 455
    is_group_started = true;

456
    setRow(current_row, raw_columns, row, def.column_names);
N
Nikolai Kochetov 已提交
457

458 459 460
    /// Reset aggregation states for next row
    for (auto & desc : def.columns_to_aggregate)
        desc.createState();
N
Nikolai Kochetov 已提交
461

462 463 464 465 466 467 468 469 470 471 472 473 474
    if (def.maps_to_sum.empty())
    {
        /// We have only columns_to_aggregate. The status of current row will be determined
        /// in 'insertCurrentRowIfNeeded' method on the values of aggregate functions.
        current_row_is_zero = true; // NOLINT
    }
    else
    {
        /// We have complex maps that will be summed with 'mergeMap' method.
        /// The single row is considered non zero, and the status after merging with other rows
        /// will be determined in the branch below (when key_differs == false).
        current_row_is_zero = false; // NOLINT
    }
N
Nikolai Kochetov 已提交
475

476
    addRowImpl(raw_columns, row);
N
Nikolai Kochetov 已提交
477 478
}

479
void SummingSortedAlgorithm::SummingMergedData::finishGroup()
N
Nikolai Kochetov 已提交
480
{
481 482
    is_group_started = false;

N
Nikolai Kochetov 已提交
483
    /// We have nothing to aggregate. It means that it could be non-zero, because we have columns_not_to_aggregate.
484
    if (def.columns_to_aggregate.empty())
N
Nikolai Kochetov 已提交
485 486
        current_row_is_zero = false;

487
    for (auto & desc : def.columns_to_aggregate)
N
Nikolai Kochetov 已提交
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
    {
        // Do not insert if the aggregation state hasn't been created
        if (desc.created)
        {
            if (desc.is_agg_func_type)
            {
                current_row_is_zero = false;
            }
            else
            {
                try
                {
                    desc.function->insertResultInto(desc.state.data(), *desc.merged_column);

                    /// Update zero status of current row
                    if (desc.column_numbers.size() == 1)
                    {
                        // Flag row as non-empty if at least one column number if non-zero
N
Nikolai Kochetov 已提交
506 507
                        current_row_is_zero = current_row_is_zero
                                              && desc.merged_column->isDefaultAt(desc.merged_column->size() - 1);
N
Nikolai Kochetov 已提交
508 509 510 511
                    }
                    else
                    {
                        /// It is sumMapWithOverflow aggregate function.
N
Nikolai Kochetov 已提交
512 513
                        /// Assume that the row isn't empty in this case
                        ///   (just because it is compatible with previous version)
N
Nikolai Kochetov 已提交
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
                        current_row_is_zero = false;
                    }
                }
                catch (...)
                {
                    desc.destroyState();
                    throw;
                }
            }
            desc.destroyState();
        }
        else
            desc.merged_column->insertDefault();
    }

    /// If it is "zero" row, then rollback the insertion
    /// (at this moment we need rollback only cols from columns_to_aggregate)
    if (current_row_is_zero)
    {
533
        for (auto & desc : def.columns_to_aggregate)
N
Nikolai Kochetov 已提交
534 535 536 537 538
            desc.merged_column->popBack(1);

        return;
    }

539 540 541 542 543 544 545 546 547 548
    size_t next_column = columns.size() - def.column_numbers_not_to_aggregate.size();
    for (auto column_number : def.column_numbers_not_to_aggregate)
    {
        columns[next_column]->insert(current_row[column_number]);
        ++next_column;
    }

    ++total_merged_rows;
    ++merged_rows;
    /// TODO: sum_blocks_granularity += block_size;
N
Nikolai Kochetov 已提交
549 550
}

551
void SummingSortedAlgorithm::SummingMergedData::addRow(ColumnRawPtrs & raw_columns, size_t row)
N
Nikolai Kochetov 已提交
552
{
553 554 555 556 557 558 559 560 561 562 563
    // Merge maps only for same rows
    for (const auto & desc : def.maps_to_sum)
        if (mergeMap(desc, current_row, raw_columns, row))
            current_row_is_zero = false;

    addRowImpl(raw_columns, row);
}

void SummingSortedAlgorithm::SummingMergedData::addRowImpl(ColumnRawPtrs & raw_columns, size_t row)
{
    for (auto & desc : def.columns_to_aggregate)
N
Nikolai Kochetov 已提交
564 565
    {
        if (!desc.created)
566 567
            throw Exception("Logical error in SummingSortedBlockInputStream, there are no description",
                            ErrorCodes::LOGICAL_ERROR);
N
Nikolai Kochetov 已提交
568 569 570 571

        if (desc.is_agg_func_type)
        {
            // desc.state is not used for AggregateFunction types
572 573
            auto & col = raw_columns[desc.column_numbers[0]];
            assert_cast<ColumnAggregateFunction &>(*desc.merged_column).insertMergeFrom(*col, row);
N
Nikolai Kochetov 已提交
574 575 576 577 578 579
        }
        else
        {
            // Specialized case for unary functions
            if (desc.column_numbers.size() == 1)
            {
580 581
                auto & col = raw_columns[desc.column_numbers[0]];
                desc.add_function(desc.function.get(), desc.state.data(), &col, row, nullptr);
N
Nikolai Kochetov 已提交
582 583 584 585
            }
            else
            {
                // Gather all source columns into a vector
N
Nikolai Kochetov 已提交
586
                ColumnRawPtrs column_ptrs(desc.column_numbers.size());
N
Nikolai Kochetov 已提交
587
                for (size_t i = 0; i < desc.column_numbers.size(); ++i)
N
Nikolai Kochetov 已提交
588
                    column_ptrs[i] = raw_columns[desc.column_numbers[i]];
N
Nikolai Kochetov 已提交
589

N
Nikolai Kochetov 已提交
590
                desc.add_function(desc.function.get(), desc.state.data(), column_ptrs.data(), row, nullptr);
N
Nikolai Kochetov 已提交
591 592 593 594 595
            }
        }
    }
}

596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
void SummingSortedAlgorithm::SummingMergedData::initAggregateDescription()
{
    size_t num_columns = def.columns_to_aggregate.size();
    for (size_t column_number = 0; column_number < num_columns; ++column_number)
        def.columns_to_aggregate[column_number].merged_column = columns[column_number].get();
}


Chunk SummingSortedAlgorithm::SummingMergedData::pull()
{
    auto chunk = MergedData::pull();
    postprocessChunk(chunk, def.column_names.size(), def);

    initAggregateDescription();

    return chunk;
}


SummingSortedAlgorithm::SummingSortedAlgorithm(
    const Block & header, size_t num_inputs,
    SortDescription description_,
    const Names & column_names_to_sum,
    size_t max_block_size)
    : IMergingAlgorithmWithDelayedChunk(num_inputs, std::move(description_))
    , columns_definition(defineColumns(header, description, column_names_to_sum))
    , merged_data(getMergedDataColumns(header, columns_definition), max_block_size, columns_definition)
{
}

void SummingSortedAlgorithm::initialize(Chunks chunks)
{
    for (auto & chunk : chunks)
        if (chunk)
            preprocessChunk(chunk);

    initializeQueue(std::move(chunks));
}

N
Nikolai Kochetov 已提交
635
void SummingSortedAlgorithm::consume(Chunk & chunk, size_t source_num)
636 637
{
    preprocessChunk(chunk);
N
Nikolai Kochetov 已提交
638
    updateCursor(chunk, source_num);
639 640
}

N
Nikolai Kochetov 已提交
641 642 643 644 645 646 647 648 649 650 651 652 653
IMergingAlgorithm::Status SummingSortedAlgorithm::merge()
{
    /// Take the rows in needed order and put them in `merged_columns` until rows no more than `max_block_size`
    while (queue.isValid())
    {
        bool key_differs;

        SortCursor current = queue.current();

        {
            detail::RowRef current_key;
            current_key.set(current);

654
            key_differs = last_key.empty() || !last_key.hasEqualSortColumnsWith(current_key);
N
Nikolai Kochetov 已提交
655 656 657 658 659 660 661

            last_key = current_key;
            last_chunk_sort_columns.clear();
        }

        if (key_differs)
        {
662
            if (merged_data.isGroupStarted())
N
Nikolai Kochetov 已提交
663
                /// Write the data for the previous group.
664
                merged_data.finishGroup();
N
Nikolai Kochetov 已提交
665 666 667 668 669

            if (merged_data.hasEnoughRows())
            {
                /// The block is now full and the last row is calculated completely.
                last_key.reset();
670
                return Status(merged_data.pull());
N
Nikolai Kochetov 已提交
671 672
            }

673
            merged_data.startGroup(current->all_columns, current->pos);
N
Nikolai Kochetov 已提交
674 675
        }
        else
676
            merged_data.addRow(current->all_columns, current->pos);
N
Nikolai Kochetov 已提交
677 678 679 680 681 682 683 684 685 686 687 688 689 690

        if (!current->isLast())
        {
            queue.next();
        }
        else
        {
            /// We get the next block from the corresponding source, if there is one.
            queue.removeTop();
            return Status(current.impl->order);
        }
    }

    /// We will write the data for the last group, if it is non-zero.
691 692 693
    if (merged_data.isGroupStarted())
        merged_data.finishGroup();

N
Nikolai Kochetov 已提交
694
    last_chunk_sort_columns.clear();
695
    return Status(merged_data.pull(), true);
N
Nikolai Kochetov 已提交
696 697 698
}

}