Coverage Report

Created: 2026-06-26 01:40

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/core/block/block.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
// This file is copied from
18
// https://github.com/ClickHouse/ClickHouse/blob/master/src/Core/Block.cpp
19
// and modified by Doris
20
21
#include "core/block/block.h"
22
23
#include <fmt/format.h>
24
#include <gen_cpp/data.pb.h>
25
#include <glog/logging.h>
26
#include <snappy.h>
27
#include <streamvbyte.h>
28
29
#include <algorithm>
30
#include <cassert>
31
#include <iomanip>
32
#include <limits>
33
#include <ranges>
34
35
#include "agent/be_exec_version_manager.h"
36
#include "common/compiler_util.h" // IWYU pragma: keep
37
#include "common/logging.h"
38
#include "common/status.h"
39
#include "core/assert_cast.h"
40
#include "core/column/column.h"
41
#include "core/column/column_const.h"
42
#include "core/column/column_nothing.h"
43
#include "core/column/column_nullable.h"
44
#include "core/column/column_vector.h"
45
#include "core/data_type/data_type_factory.hpp"
46
#include "core/data_type/data_type_nullable.h"
47
#include "core/data_type_serde/data_type_serde.h"
48
#include "runtime/descriptors.h"
49
#include "runtime/runtime_profile.h"
50
#include "runtime/thread_context.h"
51
#include "util/block_compression.h"
52
#include "util/faststring.h"
53
#include "util/simd/bits.h"
54
#include "util/slice.h"
55
56
class SipHash;
57
58
namespace doris::segment_v2 {
59
enum CompressionTypePB : int;
60
} // namespace doris::segment_v2
61
namespace doris {
62
template <typename T>
63
void clear_blocks(moodycamel::ConcurrentQueue<T>& blocks,
64
2
                  RuntimeProfile::Counter* memory_used_counter = nullptr) {
65
2
    T block;
66
6
    while (blocks.try_dequeue(block)) {
67
4
        if (memory_used_counter) {
68
4
            if constexpr (std::is_same_v<T, Block>) {
69
2
                memory_used_counter->update(-block.allocated_bytes());
70
2
            } else {
71
2
                memory_used_counter->update(-block->allocated_bytes());
72
2
            }
73
4
        }
74
4
    }
75
2
}
_ZN5doris12clear_blocksINS_5BlockEEEvRN10moodycamel15ConcurrentQueueIT_NS2_28ConcurrentQueueDefaultTraitsEEEPNS_14RuntimeProfile7CounterE
Line
Count
Source
64
1
                  RuntimeProfile::Counter* memory_used_counter = nullptr) {
65
1
    T block;
66
3
    while (blocks.try_dequeue(block)) {
67
2
        if (memory_used_counter) {
68
2
            if constexpr (std::is_same_v<T, Block>) {
69
2
                memory_used_counter->update(-block.allocated_bytes());
70
            } else {
71
                memory_used_counter->update(-block->allocated_bytes());
72
            }
73
2
        }
74
2
    }
75
1
}
_ZN5doris12clear_blocksISt10unique_ptrINS_5BlockESt14default_deleteIS2_EEEEvRN10moodycamel15ConcurrentQueueIT_NS6_28ConcurrentQueueDefaultTraitsEEEPNS_14RuntimeProfile7CounterE
Line
Count
Source
64
1
                  RuntimeProfile::Counter* memory_used_counter = nullptr) {
65
1
    T block;
66
3
    while (blocks.try_dequeue(block)) {
67
2
        if (memory_used_counter) {
68
            if constexpr (std::is_same_v<T, Block>) {
69
                memory_used_counter->update(-block.allocated_bytes());
70
2
            } else {
71
2
                memory_used_counter->update(-block->allocated_bytes());
72
2
            }
73
2
        }
74
2
    }
75
1
}
76
77
template void clear_blocks<Block>(moodycamel::ConcurrentQueue<Block>&,
78
                                  RuntimeProfile::Counter* memory_used_counter);
79
template void clear_blocks<BlockUPtr>(moodycamel::ConcurrentQueue<BlockUPtr>&,
80
                                      RuntimeProfile::Counter* memory_used_counter);
81
82
namespace {
83
84
// The no-clone fast path is only safe when the whole column tree is uniquely
85
// owned. A composite column with shared children still needs COW detachment.
86
32.5k
bool is_recursively_exclusive(const IColumn& column) {
87
32.5k
    if (!column.is_exclusive()) {
88
13
        return false;
89
13
    }
90
91
32.5k
    bool exclusive = true;
92
32.5k
    IColumn::ColumnCallback callback = [&](const IColumn& subcolumn) {
93
27.7k
        if (!exclusive) {
94
0
            return;
95
0
        }
96
27.7k
        exclusive = is_recursively_exclusive(subcolumn);
97
27.7k
    };
98
32.5k
    column.for_each_subcolumn(callback);
99
32.5k
    return exclusive;
100
32.5k
}
101
102
// Acquire one live Block slot transactionally. Shared columns are detached while
103
// the original slot is still intact, so a clone failure cannot leave Block with
104
// a moved-from/null column. Exclusive column trees keep the stealing fast path.
105
4.80k
MutableColumnPtr scoped_mutate_column(ColumnPtr& column, const DataTypePtr& type) {
106
4.80k
    DCHECK(type);
107
4.80k
    if (!column) {
108
1
        return type->create_column();
109
1
    }
110
111
4.80k
    MutableColumnPtr mutable_column;
112
4.80k
    if (is_recursively_exclusive(*column)) {
113
4.78k
        mutable_column = std::move(*column).mutate();
114
4.78k
    } else {
115
13
        mutable_column = IColumn::mutate(column);
116
13
    }
117
4.80k
    column = nullptr;
118
4.80k
    return mutable_column;
119
4.80k
}
120
121
} // namespace
122
123
4.38k
Block::Block(std::initializer_list<ColumnWithTypeAndName> il) : data {il} {}
124
125
258k
Block::Block(ColumnsWithTypeAndName data_) : data {std::move(data_)} {}
126
127
56.0k
Block::Block(const std::vector<SlotDescriptor*>& slots, size_t block_size) {
128
271k
    for (auto* const slot_desc : slots) {
129
271k
        auto column_ptr = slot_desc->get_empty_mutable_column();
130
271k
        column_ptr->reserve(block_size);
131
271k
        insert(ColumnWithTypeAndName(std::move(column_ptr), slot_desc->get_data_type_ptr(),
132
271k
                                     slot_desc->col_name()));
133
271k
    }
134
56.0k
}
135
136
1
Block::Block(const std::vector<SlotDescriptor>& slots, size_t block_size) {
137
1
    std::vector<SlotDescriptor*> slot_ptrs(slots.size());
138
3
    for (size_t i = 0; i < slots.size(); ++i) {
139
        // Slots remain unmodified and are used to read column information; const_cast can be employed.
140
        // used in src/exec/rowid_fetcher.cpp
141
2
        slot_ptrs[i] = const_cast<SlotDescriptor*>(&slots[i]);
142
2
    }
143
1
    *this = Block(slot_ptrs, block_size);
144
1
}
145
146
Status Block::deserialize(const PBlock& pblock, size_t* uncompressed_bytes,
147
992
                          int64_t* decompress_time) {
148
992
    swap(Block());
149
992
    int be_exec_version = pblock.has_be_exec_version() ? pblock.be_exec_version() : 0;
150
992
    RETURN_IF_ERROR(BeExecVersionManager::check_be_exec_version(be_exec_version));
151
152
992
    const char* buf = nullptr;
153
992
    std::string compression_scratch;
154
992
    if (pblock.compressed()) {
155
        // Decompress
156
481
        SCOPED_RAW_TIMER(decompress_time);
157
481
        const char* compressed_data = pblock.column_values().c_str();
158
481
        size_t compressed_size = pblock.column_values().size();
159
481
        size_t uncompressed_size = 0;
160
481
        if (pblock.has_compression_type() && pblock.has_uncompressed_size()) {
161
481
            BlockCompressionCodec* codec;
162
481
            RETURN_IF_ERROR(get_block_compression_codec(pblock.compression_type(), &codec));
163
481
            uncompressed_size = pblock.uncompressed_size();
164
            // Should also use allocator to allocate memory here.
165
481
            compression_scratch.resize(uncompressed_size);
166
481
            Slice decompressed_slice(compression_scratch);
167
481
            RETURN_IF_ERROR(codec->decompress(Slice(compressed_data, compressed_size),
168
481
                                              &decompressed_slice));
169
481
            DCHECK(uncompressed_size == decompressed_slice.size);
170
481
        } else {
171
0
            bool success = snappy::GetUncompressedLength(compressed_data, compressed_size,
172
0
                                                         &uncompressed_size);
173
0
            DCHECK(success) << "snappy::GetUncompressedLength failed";
174
0
            compression_scratch.resize(uncompressed_size);
175
0
            success = snappy::RawUncompress(compressed_data, compressed_size,
176
0
                                            compression_scratch.data());
177
0
            DCHECK(success) << "snappy::RawUncompress failed";
178
0
        }
179
481
        *uncompressed_bytes = uncompressed_size;
180
481
        buf = compression_scratch.data();
181
511
    } else {
182
511
        buf = pblock.column_values().data();
183
511
    }
184
185
1.57k
    for (const auto& pcol_meta : pblock.column_metas()) {
186
1.57k
        DataTypePtr type = DataTypeFactory::instance().create_data_type(pcol_meta);
187
1.57k
        MutableColumnPtr data_column = type->create_column();
188
        // Here will try to allocate large memory, should return error if failed.
189
1.57k
        RETURN_IF_CATCH_EXCEPTION(
190
1.57k
                buf = type->deserialize(buf, &data_column, pblock.be_exec_version()));
191
1.57k
        data.emplace_back(data_column->get_ptr(), type, pcol_meta.name());
192
1.57k
    }
193
194
992
    return Status::OK();
195
992
}
196
197
13.4k
void Block::reserve(size_t count) {
198
13.4k
    data.reserve(count);
199
13.4k
}
200
201
4
void Block::insert(size_t position, const ColumnWithTypeAndName& elem) {
202
4
    if (position > data.size()) {
203
1
        throw Exception(ErrorCode::INTERNAL_ERROR,
204
1
                        "invalid input position, position={}, data.size={}, names={}", position,
205
1
                        data.size(), dump_names());
206
1
    }
207
208
3
    data.emplace(data.begin() + position, elem);
209
3
}
210
211
3
void Block::insert(size_t position, ColumnWithTypeAndName&& elem) {
212
3
    if (position > data.size()) {
213
1
        throw Exception(ErrorCode::INTERNAL_ERROR,
214
1
                        "invalid input position, position={}, data.size={}, names={}", position,
215
1
                        data.size(), dump_names());
216
1
    }
217
218
2
    data.emplace(data.begin() + position, std::move(elem));
219
2
}
220
221
8.09k
void Block::clear_names() {
222
178k
    for (auto& entry : data) {
223
178k
        entry.name.clear();
224
178k
    }
225
8.09k
}
226
227
14.5k
void Block::insert(const ColumnWithTypeAndName& elem) {
228
14.5k
    data.emplace_back(elem);
229
14.5k
}
230
231
1.00M
void Block::insert(ColumnWithTypeAndName&& elem) {
232
1.00M
    data.emplace_back(std::move(elem));
233
1.00M
}
234
235
3
void Block::erase(const std::set<size_t>& positions) {
236
3
    for (unsigned long position : std::ranges::reverse_view(positions)) {
237
2
        erase(position);
238
2
    }
239
3
}
240
241
718
void Block::erase_tail(size_t start) {
242
718
    DCHECK(start <= data.size()) << fmt::format(
243
0
            "Position out of bound in Block::erase(), max position = {}", data.size());
244
718
    data.erase(data.begin() + start, data.end());
245
718
}
246
247
124k
void Block::erase(size_t position) {
248
124k
    DCHECK(!data.empty()) << "Block is empty";
249
124k
    DCHECK_LT(position, data.size()) << fmt::format(
250
0
            "Position out of bound in Block::erase(), max position = {}", data.size() - 1);
251
252
124k
    erase_impl(position);
253
124k
}
254
255
124k
void Block::erase_impl(size_t position) {
256
124k
    data.erase(data.begin() + position);
257
124k
}
258
259
76.0k
ColumnWithTypeAndName& Block::safe_get_by_position(size_t position) {
260
76.0k
    if (position >= data.size()) {
261
0
        throw Exception(ErrorCode::INTERNAL_ERROR,
262
0
                        "invalid input position, position={}, data.size={}, names={}", position,
263
0
                        data.size(), dump_names());
264
0
    }
265
76.0k
    return data[position];
266
76.0k
}
267
268
109
const ColumnWithTypeAndName& Block::safe_get_by_position(size_t position) const {
269
109
    if (position >= data.size()) {
270
0
        throw Exception(ErrorCode::INTERNAL_ERROR,
271
0
                        "invalid input position, position={}, data.size={}, names={}", position,
272
0
                        data.size(), dump_names());
273
0
    }
274
109
    return data[position];
275
109
}
276
277
89
int Block::get_position_by_name(const std::string& name) const {
278
1.04k
    for (int i = 0; i < data.size(); i++) {
279
1.04k
        if (data[i].name == name) {
280
86
            return i;
281
86
        }
282
1.04k
    }
283
3
    return -1;
284
89
}
285
286
5
void Block::check_number_of_rows(bool allow_null_columns) const {
287
5
    ssize_t rows = -1;
288
9
    for (const auto& elem : data) {
289
9
        if (!elem.column && allow_null_columns) {
290
2
            continue;
291
2
        }
292
293
7
        if (!elem.column) {
294
1
            throw Exception(ErrorCode::INTERNAL_ERROR,
295
1
                            "Column {} in block is nullptr, in method check_number_of_rows.",
296
1
                            elem.name);
297
1
        }
298
299
6
        ssize_t size = elem.column->size();
300
301
6
        if (rows == -1) {
302
5
            rows = size;
303
5
        } else if (rows != size) {
304
1
            throw Exception(ErrorCode::INTERNAL_ERROR, "Sizes of columns doesn't match, block={}",
305
1
                            dump_structure());
306
1
        }
307
6
    }
308
5
}
309
310
3.04M
Status Block::check_type_and_column() const {
311
3.04M
#ifndef NDEBUG
312
3.04M
    for (const auto& elem : data) {
313
211k
        if (!elem.column) {
314
0
            continue;
315
0
        }
316
211k
        if (!elem.type) {
317
0
            continue;
318
0
        }
319
320
        // ColumnNothing is a special column type, it is used to represent a column that
321
        // is not materialized, so we don't need to check it.
322
211k
        if (check_and_get_column<ColumnNothing>(elem.column.get())) {
323
0
            continue;
324
0
        }
325
326
211k
        const auto& type = elem.type;
327
211k
        const auto& column = elem.column;
328
329
211k
        RETURN_IF_ERROR(column->column_self_check());
330
211k
        auto st = type->check_column(*column);
331
211k
        if (!st.ok()) {
332
1
            return Status::InternalError(
333
1
                    "Column {} in block is not compatible with its column type :{}, data type :{}, "
334
1
                    "error: {}",
335
1
                    elem.name, column->get_name(), type->get_name(), st.msg());
336
1
        }
337
211k
    }
338
3.04M
#endif
339
3.04M
    return Status::OK();
340
3.04M
}
341
342
1.56M
Status Block::check_column_and_type_not_null() const {
343
1.75M
    for (size_t i = 0; i != data.size(); ++i) {
344
190k
        const auto& elem = data[i];
345
190k
        if (!elem.column) {
346
1
            return Status::InternalError("Column in block is nullptr, column index: {}, name: {}",
347
1
                                         i, elem.name);
348
1
        }
349
190k
        if (!elem.type) {
350
1
            return Status::InternalError("Type in block is nullptr, column index: {}, name: {}", i,
351
1
                                         elem.name);
352
1
        }
353
190k
    }
354
1.56M
    return Status::OK();
355
1.56M
}
356
357
50.8M
size_t Block::rows() const {
358
50.8M
    for (const auto& elem : data) {
359
46.4M
        if (elem.column) {
360
46.4M
            return elem.column->size();
361
46.4M
        }
362
46.4M
    }
363
364
4.40M
    return 0;
365
50.8M
}
366
367
6
void Block::set_num_rows(size_t length) {
368
6
    if (rows() > length) {
369
4
        for (auto& elem : data) {
370
4
            if (elem.column) {
371
4
                elem.column = elem.column->shrink(length);
372
4
            }
373
4
        }
374
4
    }
375
6
}
376
377
1
void Block::skip_num_rows(int64_t& length) {
378
1
    auto origin_rows = rows();
379
1
    if (origin_rows <= length) {
380
0
        clear();
381
0
        length -= origin_rows;
382
1
    } else {
383
1
        for (auto& elem : data) {
384
1
            if (elem.column) {
385
1
                elem.column = elem.column->cut(length, origin_rows - length);
386
1
            }
387
1
        }
388
1
    }
389
1
}
390
391
13.1k
size_t Block::bytes() const {
392
13.1k
    size_t res = 0;
393
27.8k
    for (const auto& elem : data) {
394
27.8k
        if (!elem.column) {
395
0
            std::stringstream ss;
396
0
            for (const auto& e : data) {
397
0
                ss << e.name + " ";
398
0
            }
399
0
            throw Exception(ErrorCode::INTERNAL_ERROR,
400
0
                            "Column {} in block is nullptr, in method bytes. All Columns are {}",
401
0
                            elem.name, ss.str());
402
0
        }
403
27.8k
        res += elem.column->byte_size();
404
27.8k
    }
405
406
13.1k
    return res;
407
13.1k
}
408
409
194k
size_t Block::allocated_bytes() const {
410
194k
    size_t res = 0;
411
381k
    for (const auto& elem : data) {
412
381k
        if (!elem.column) {
413
            // Sometimes if expr failed, then there will be a nullptr
414
            // column left in the block.
415
1
            continue;
416
1
        }
417
381k
        res += elem.column->allocated_bytes();
418
381k
    }
419
420
194k
    return res;
421
194k
}
422
423
8
std::string Block::dump_names() const {
424
8
    std::string out;
425
23
    for (auto it = data.begin(); it != data.end(); ++it) {
426
15
        if (it != data.begin()) {
427
7
            out += ", ";
428
7
        }
429
15
        out += it->name;
430
15
    }
431
8
    return out;
432
8
}
433
434
7
std::string Block::dump_types() const {
435
7
    std::string out;
436
21
    for (auto it = data.begin(); it != data.end(); ++it) {
437
14
        if (it != data.begin()) {
438
7
            out += ", ";
439
7
        }
440
14
        out += it->type->get_name();
441
14
    }
442
7
    return out;
443
7
}
444
445
31
std::string Block::dump_data_json(size_t begin, size_t row_limit, bool allow_null_mismatch) const {
446
31
    std::stringstream ss;
447
448
31
    std::vector<std::string> headers;
449
31
    headers.reserve(columns());
450
46
    for (const auto& it : data) {
451
        // fmt::format is from the {fmt} library, you might be using std::format in C++20
452
        // If not, you can build the string with a stringstream as a fallback.
453
46
        headers.push_back(fmt::format("{}({})", it.name, it.type->get_name()));
454
46
    }
455
456
31
    size_t start_row = std::min(begin, rows());
457
31
    size_t end_row = std::min(rows(), begin + row_limit);
458
459
31
    auto format_options = DataTypeSerDe::get_default_format_options();
460
31
    auto time_zone = cctz::utc_time_zone();
461
31
    format_options.timezone = &time_zone;
462
463
31
    ss << "[";
464
3.59k
    for (size_t row_num = start_row; row_num < end_row; ++row_num) {
465
3.56k
        if (row_num > start_row) {
466
3.53k
            ss << ",";
467
3.53k
        }
468
3.56k
        ss << "{";
469
8.33k
        for (size_t i = 0; i < columns(); ++i) {
470
4.77k
            if (i > 0) {
471
1.21k
                ss << ",";
472
1.21k
            }
473
4.77k
            ss << "\"" << headers[i] << "\":";
474
4.77k
            std::string s;
475
476
            // This value-extraction logic is preserved from your original function
477
            // to maintain consistency, especially for handling nullability mismatches.
478
4.77k
            if (data[i].column && data[i].type->is_nullable() && !data[i].column->is_nullable()) {
479
                // This branch handles a specific internal representation of nullable columns.
480
                // The original code would assert here if allow_null_mismatch is false.
481
0
                assert(allow_null_mismatch);
482
0
                s = assert_cast<const DataTypeNullable*>(data[i].type.get())
483
0
                            ->get_nested_type()
484
0
                            ->to_string(*data[i].column, row_num, format_options);
485
4.77k
            } else {
486
                // This is the standard path. The to_string method is expected to correctly
487
                // handle all cases, including when the column is null (e.g., by returning "NULL").
488
4.77k
                s = data[i].to_string(row_num, format_options);
489
4.77k
            }
490
4.77k
            ss << "\"" << s << "\"";
491
4.77k
        }
492
3.56k
        ss << "}";
493
3.56k
    }
494
31
    ss << "]";
495
31
    return ss.str();
496
31
}
497
498
858
std::string Block::dump_data(size_t begin, size_t row_limit, bool allow_null_mismatch) const {
499
858
    std::vector<std::string> headers;
500
858
    std::vector<int> headers_size;
501
2.10k
    for (const auto& it : data) {
502
2.10k
        std::string s = fmt::format("{}({})", it.name, it.type->get_name());
503
2.10k
        headers_size.push_back(s.size() > 15 ? (int)s.size() : 15);
504
2.10k
        headers.emplace_back(s);
505
2.10k
    }
506
507
858
    std::stringstream out;
508
    // header upper line
509
2.16k
    auto line = [&]() {
510
8.07k
        for (size_t i = 0; i < columns(); ++i) {
511
5.91k
            out << std::setfill('-') << std::setw(1) << "+" << std::setw(headers_size[i]) << "-";
512
5.91k
        }
513
2.16k
        out << std::setw(1) << "+" << std::endl;
514
2.16k
    };
515
858
    line();
516
    // header text
517
2.96k
    for (size_t i = 0; i < columns(); ++i) {
518
2.10k
        out << std::setfill(' ') << std::setw(1) << "|" << std::left << std::setw(headers_size[i])
519
2.10k
            << headers[i];
520
2.10k
    }
521
858
    out << std::setw(1) << "|" << std::endl;
522
    // header bottom line
523
858
    line();
524
858
    if (rows() == 0) {
525
414
        return out.str();
526
414
    }
527
528
444
    auto format_options = DataTypeSerDe::get_default_format_options();
529
444
    auto time_zone = cctz::utc_time_zone();
530
444
    format_options.timezone = &time_zone;
531
532
    // content
533
12.2k
    for (size_t row_num = begin; row_num < rows() && row_num < row_limit + begin; ++row_num) {
534
32.4k
        for (size_t i = 0; i < columns(); ++i) {
535
20.6k
            if (!data[i].column || data[i].column->empty()) {
536
0
                out << std::setfill(' ') << std::setw(1) << "|" << std::setw(headers_size[i])
537
0
                    << std::right;
538
0
                continue;
539
0
            }
540
20.6k
            std::string s;
541
20.6k
            if (data[i].column) { // column may be const
542
                // for code inside `default_implementation_for_nulls`, there's could have: type = null, col != null
543
20.6k
                if (data[i].type->is_nullable() && !data[i].column->is_nullable()) {
544
0
                    assert(allow_null_mismatch);
545
0
                    s = assert_cast<const DataTypeNullable*>(data[i].type.get())
546
0
                                ->get_nested_type()
547
0
                                ->to_string(*data[i].column, row_num, format_options);
548
20.6k
                } else {
549
20.6k
                    s = data[i].to_string(row_num, format_options);
550
20.6k
                }
551
20.6k
            }
552
20.6k
            if (s.length() > headers_size[i]) {
553
2.12k
                s = s.substr(0, headers_size[i] - 3) + "...";
554
2.12k
            }
555
20.6k
            out << std::setfill(' ') << std::setw(1) << "|" << std::setw(headers_size[i])
556
20.6k
                << std::right << s;
557
20.6k
        }
558
11.7k
        out << std::setw(1) << "|" << std::endl;
559
11.7k
    }
560
    // bottom line
561
444
    line();
562
444
    if (row_limit < rows()) {
563
112
        out << rows() << " rows in block, only show first " << row_limit << " rows." << std::endl;
564
112
    }
565
444
    return out.str();
566
444
}
567
568
1
std::string Block::dump_one_line(size_t row, int column_end) const {
569
1
    assert(column_end <= columns());
570
1
    fmt::memory_buffer line;
571
572
1
    auto format_options = DataTypeSerDe::get_default_format_options();
573
1
    auto time_zone = cctz::utc_time_zone();
574
1
    format_options.timezone = &time_zone;
575
576
3
    for (int i = 0; i < column_end; ++i) {
577
2
        if (LIKELY(i != 0)) {
578
            // TODO: need more effective function of to string. now the impl is slow
579
1
            fmt::format_to(line, " {}", data[i].to_string(row, format_options));
580
1
        } else {
581
1
            fmt::format_to(line, "{}", data[i].to_string(row, format_options));
582
1
        }
583
2
    }
584
1
    return fmt::to_string(line);
585
1
}
586
587
47
std::string Block::dump_structure() const {
588
47
    std::string out;
589
382
    for (auto it = data.begin(); it != data.end(); ++it) {
590
335
        if (it != data.begin()) {
591
288
            out += ", \n";
592
288
        }
593
335
        out += it->dump_structure();
594
335
    }
595
47
    return out;
596
47
}
597
598
48.9k
Block Block::clone_empty() const {
599
48.9k
    Block res;
600
95.8k
    for (const auto& elem : data) {
601
95.8k
        res.insert(elem.clone_empty());
602
95.8k
    }
603
48.9k
    return res;
604
48.9k
}
605
606
32
MutableColumns Block::clone_empty_columns() const {
607
32
    size_t num_columns = data.size();
608
32
    MutableColumns columns(num_columns);
609
142
    for (size_t i = 0; i < num_columns; ++i) {
610
110
        columns[i] = data[i].column ? data[i].column->clone_empty() : data[i].type->create_column();
611
110
    }
612
32
    return columns;
613
32
}
614
615
26.1k
Columns Block::get_columns() const {
616
26.1k
    size_t num_columns = data.size();
617
26.1k
    Columns columns(num_columns);
618
113k
    for (size_t i = 0; i < num_columns; ++i) {
619
87.7k
        columns[i] = data[i].column->convert_to_full_column_if_const();
620
87.7k
    }
621
26.1k
    return columns;
622
26.1k
}
623
624
559
Columns Block::get_columns_and_convert() {
625
559
    size_t num_columns = data.size();
626
559
    Columns columns(num_columns);
627
1.18k
    for (size_t i = 0; i < num_columns; ++i) {
628
622
        data[i].column = data[i].column->convert_to_full_column_if_const();
629
622
        columns[i] = data[i].column;
630
622
    }
631
559
    return columns;
632
559
}
633
634
2.48k
Block::ScopedMutableColumns::ScopedMutableColumns(Block& block) : _block(&block) {
635
2.48k
    const size_t num_columns = block.data.size();
636
2.48k
    _columns.resize(num_columns);
637
2.48k
    size_t acquired_columns = 0;
638
2.48k
    try {
639
7.18k
        for (; acquired_columns < num_columns; ++acquired_columns) {
640
4.70k
            auto& column_with_type_and_name = block.data[acquired_columns];
641
4.70k
            _columns[acquired_columns] = scoped_mutate_column(column_with_type_and_name.column,
642
4.70k
                                                              column_with_type_and_name.type);
643
4.70k
        }
644
2.48k
    } catch (...) {
645
4
        for (size_t i = 0; i < acquired_columns; ++i) {
646
2
            block.data[i].column = std::move(_columns[i]);
647
2
        }
648
2
        _block = nullptr;
649
2
        throw;
650
2
    }
651
2.48k
}
652
653
2.47k
Block::ScopedMutableColumns::~ScopedMutableColumns() {
654
2.47k
    restore();
655
2.47k
}
656
657
Block::ScopedMutableColumns::ScopedMutableColumns(ScopedMutableColumns&& other) noexcept
658
0
        : _block(std::exchange(other._block, nullptr)), _columns(std::move(other._columns)) {}
659
660
Block::ScopedMutableColumns& Block::ScopedMutableColumns::operator=(
661
0
        ScopedMutableColumns&& other) noexcept {
662
0
    if (this != &other) {
663
0
        restore();
664
0
        _block = std::exchange(other._block, nullptr);
665
0
        _columns = std::move(other._columns);
666
0
    }
667
0
    return *this;
668
0
}
669
670
2
const DataTypePtr& Block::ScopedMutableColumns::get_datatype_by_position(size_t position) const {
671
2
    DCHECK(_block != nullptr);
672
2
    return _block->get_by_position(position).type;
673
2
}
674
675
2
const std::string& Block::ScopedMutableColumns::get_name_by_position(size_t position) const {
676
2
    DCHECK(_block != nullptr);
677
2
    return _block->get_by_position(position).name;
678
2
}
679
680
816
MutableColumns Block::ScopedMutableColumns::release() {
681
816
    DCHECK(_block != nullptr);
682
816
    _block = nullptr;
683
816
    return std::move(_columns);
684
816
}
685
686
2.96k
void Block::ScopedMutableColumns::restore() {
687
2.96k
    if (_block != nullptr) {
688
1.66k
        _block->set_columns(std::move(_columns));
689
1.66k
        _block = nullptr;
690
1.66k
    }
691
2.96k
}
692
693
Block::ScopedMutableColumn::ScopedMutableColumn(Block& block, size_t position)
694
98
        : _block(&block), _position(position) {
695
98
    DCHECK_LT(_position, _block->data.size());
696
98
    auto& column_with_type_and_name = _block->data[_position];
697
98
    DCHECK(column_with_type_and_name.type);
698
98
    _column =
699
98
            scoped_mutate_column(column_with_type_and_name.column, column_with_type_and_name.type);
700
98
}
701
702
97
Block::ScopedMutableColumn::~ScopedMutableColumn() {
703
97
    restore();
704
97
}
705
706
Block::ScopedMutableColumn::ScopedMutableColumn(ScopedMutableColumn&& other) noexcept
707
0
        : _block(std::exchange(other._block, nullptr)),
708
0
          _position(other._position),
709
0
          _column(std::move(other._column)) {}
710
711
Block::ScopedMutableColumn& Block::ScopedMutableColumn::operator=(
712
0
        ScopedMutableColumn&& other) noexcept {
713
0
    if (this != &other) {
714
0
        restore();
715
0
        _block = std::exchange(other._block, nullptr);
716
0
        _position = other._position;
717
0
        _column = std::move(other._column);
718
0
    }
719
0
    return *this;
720
0
}
721
722
97
void Block::ScopedMutableColumn::restore() {
723
97
    if (_block != nullptr) {
724
97
        DCHECK_LT(_position, _block->data.size());
725
97
        _block->data[_position].column = std::move(_column);
726
97
        _block = nullptr;
727
97
    }
728
97
}
729
730
2.48k
Block::ScopedMutableColumns Block::mutate_columns_scoped() & {
731
2.48k
    return ScopedMutableColumns(*this);
732
2.48k
}
733
734
98
Block::ScopedMutableColumn Block::mutate_column_scoped(size_t position) & {
735
98
    return ScopedMutableColumn(*this, position);
736
98
}
737
738
817
ScopedMutableBlock::ScopedMutableBlock(Block* block) {
739
817
    DCHECK(block != nullptr);
740
817
    DataTypes data_types = block->get_data_types();
741
817
    std::vector<std::string> names = block->get_names();
742
817
    auto columns_guard = block->mutate_columns_scoped();
743
817
    _mutable_block.data_types() = std::move(data_types);
744
817
    _mutable_block.get_names() = std::move(names);
745
817
    _mutable_block.set_mutable_columns(columns_guard.release());
746
817
    _block = block;
747
817
}
748
749
146k
MutableColumns Block::mutate_columns() && {
750
146k
    size_t num_columns = data.size();
751
146k
    MutableColumns columns(num_columns);
752
433k
    for (size_t i = 0; i < num_columns; ++i) {
753
287k
        DCHECK(data[i].type);
754
287k
        columns[i] = data[i].column ? IColumn::mutate(std::move(data[i].column))
755
287k
                                    : data[i].type->create_column();
756
287k
    }
757
146k
    return columns;
758
146k
}
759
760
3.46k
void Block::set_columns(MutableColumns&& columns) {
761
3.46k
    DCHECK_GE(columns.size(), data.size())
762
0
            << fmt::format("Invalid size of columns, columns size: {}, data size: {}",
763
0
                           columns.size(), data.size());
764
3.46k
    size_t num_columns = data.size();
765
11.8k
    for (size_t i = 0; i < num_columns; ++i) {
766
8.41k
        data[i].column = std::move(columns[i]);
767
8.41k
    }
768
3.46k
}
769
770
51
Block Block::clone_without_columns(const std::vector<int>* column_offset) const {
771
51
    Block res;
772
773
51
    if (column_offset != nullptr) {
774
32
        size_t num_columns = column_offset->size();
775
174
        for (size_t i = 0; i < num_columns; ++i) {
776
142
            res.insert({nullptr, data[(*column_offset)[i]].type, data[(*column_offset)[i]].name});
777
142
        }
778
32
    } else {
779
19
        size_t num_columns = data.size();
780
53
        for (size_t i = 0; i < num_columns; ++i) {
781
34
            res.insert({nullptr, data[i].type, data[i].name});
782
34
        }
783
19
    }
784
51
    return res;
785
51
}
786
787
55.8k
const ColumnsWithTypeAndName& Block::get_columns_with_type_and_name() const {
788
55.8k
    return data;
789
55.8k
}
790
791
145k
std::vector<std::string> Block::get_names() const {
792
145k
    std::vector<std::string> res;
793
145k
    res.reserve(columns());
794
795
285k
    for (const auto& elem : data) {
796
285k
        res.push_back(elem.name);
797
285k
    }
798
799
145k
    return res;
800
145k
}
801
802
145k
DataTypes Block::get_data_types() const {
803
145k
    DataTypes res;
804
145k
    res.reserve(columns());
805
806
285k
    for (const auto& elem : data) {
807
285k
        res.push_back(elem.type);
808
285k
    }
809
810
145k
    return res;
811
145k
}
812
813
52.7k
void Block::clear() {
814
52.7k
    data.clear();
815
52.7k
}
816
817
1.49M
void Block::clear_column_data(int64_t column_size) {
818
1.49M
    SCOPED_SKIP_MEMORY_CHECK();
819
    // data.size() greater than column_size, means here have some
820
    // function exec result in block, need erase it here
821
1.49M
    if (column_size != -1 and data.size() > column_size) {
822
2.20k
        for (int64_t i = data.size() - 1; i >= column_size; --i) {
823
1.10k
            erase(i);
824
1.10k
        }
825
1.10k
    }
826
1.49M
    for (auto& d : data) {
827
53.0k
        if (d.column) {
828
53.0k
            if (d.column->is_exclusive()) {
829
52.8k
                d.column->assert_mutable()->clear();
830
52.8k
            } else {
831
245
                d.column = d.column->clone_empty();
832
245
            }
833
53.0k
        }
834
53.0k
    }
835
1.49M
}
836
837
46
void Block::clear_column_data(const std::vector<uint32_t>& columns_to_clear) {
838
46
    SCOPED_SKIP_MEMORY_CHECK();
839
79
    for (auto col : columns_to_clear) {
840
79
        DCHECK_LT(col, data.size());
841
79
        auto& column = data[col].column;
842
79
        if (column) {
843
79
            if (column->is_exclusive()) {
844
77
                column->assert_mutable()->clear();
845
77
            } else {
846
2
                column = column->clone_empty();
847
2
            }
848
79
        }
849
79
    }
850
46
}
851
852
void Block::clear_column_mem_not_keep(const std::vector<bool>& column_keep_flags,
853
48.0k
                                      bool need_keep_first) {
854
48.0k
    if (data.size() >= column_keep_flags.size()) {
855
48.0k
        auto origin_rows = rows();
856
142k
        for (size_t i = 0; i < column_keep_flags.size(); ++i) {
857
94.1k
            if (!column_keep_flags[i]) {
858
36.8k
                data[i].column = data[i].column->clone_empty();
859
36.8k
            }
860
94.1k
        }
861
862
48.0k
        if (need_keep_first && !column_keep_flags[0]) {
863
1
            auto first_column = data[0].column->clone_empty();
864
1
            first_column->resize(origin_rows);
865
1
            data[0].column = std::move(first_column);
866
1
        }
867
48.0k
    }
868
48.0k
}
869
870
1.32k
void Block::swap(Block& other) noexcept {
871
1.32k
    SCOPED_SKIP_MEMORY_CHECK();
872
1.32k
    data.swap(other.data);
873
1.32k
}
874
875
1.70k
void Block::swap(Block&& other) noexcept {
876
1.70k
    SCOPED_SKIP_MEMORY_CHECK();
877
1.70k
    data = std::move(other.data);
878
1.70k
}
879
880
3
void Block::shuffle_columns(const std::vector<int>& result_column_ids) {
881
3
    Container tmp_data;
882
3
    tmp_data.reserve(result_column_ids.size());
883
5
    for (const int result_column_id : result_column_ids) {
884
5
        tmp_data.push_back(data[result_column_id]);
885
5
    }
886
3
    data = std::move(tmp_data);
887
3
}
888
889
2
void Block::update_hash(SipHash& hash) const {
890
8
    for (size_t row_no = 0, num_rows = rows(); row_no < num_rows; ++row_no) {
891
12
        for (const auto& col : data) {
892
12
            col.column->update_hash_with_value(row_no, hash);
893
12
        }
894
6
    }
895
2
}
896
897
void Block::filter_block_internal(Block* block, const std::vector<uint32_t>& columns_to_filter,
898
525
                                  const IColumn::Filter& filter) {
899
525
    size_t count = filter.size() - simd::count_zero_num((int8_t*)filter.data(), filter.size());
900
1.34k
    for (const auto& col : columns_to_filter) {
901
1.34k
        auto& column = block->get_by_position(col).column;
902
1.34k
        if (column->size() == count) {
903
1.29k
            continue;
904
1.29k
        }
905
49
        if (count == 0) {
906
2
            if (column->is_exclusive()) {
907
0
                column->assert_mutable()->clear();
908
2
            } else {
909
2
                column = column->clone_empty();
910
2
            }
911
2
            continue;
912
2
        }
913
47
        if (column->is_exclusive()) {
914
            // COW: safe to mutate in-place since we have exclusive ownership
915
47
            const auto result_size = column->assert_mutable()->filter(filter);
916
47
            if (result_size != count) [[unlikely]] {
917
0
                throw Exception(ErrorCode::INTERNAL_ERROR,
918
0
                                "result_size not equal with filter_size, result_size={}, "
919
0
                                "filter_size={}",
920
0
                                result_size, count);
921
0
            }
922
47
        } else {
923
            // COW: must create a copy since column is shared
924
0
            column = column->filter(filter, count);
925
0
        }
926
47
    }
927
525
}
928
929
void Block::filter_block_internal(Block* block, const IColumn::Filter& filter,
930
1
                                  uint32_t column_to_keep) {
931
1
    std::vector<uint32_t> columns_to_filter;
932
1
    columns_to_filter.resize(column_to_keep);
933
3
    for (uint32_t i = 0; i < column_to_keep; ++i) {
934
2
        columns_to_filter[i] = i;
935
2
    }
936
1
    filter_block_internal(block, columns_to_filter, filter);
937
1
}
938
939
8
void Block::filter_block_internal(Block* block, const IColumn::Filter& filter) {
940
8
    const size_t count =
941
8
            filter.size() - simd::count_zero_num((int8_t*)filter.data(), filter.size());
942
24
    for (int i = 0; i < block->columns(); ++i) {
943
16
        auto& column = block->get_by_position(i).column;
944
16
        if (column->is_exclusive()) {
945
16
            column->assert_mutable()->filter(filter);
946
16
        } else {
947
0
            column = column->filter(filter, count);
948
0
        }
949
16
    }
950
8
}
951
952
Status Block::append_to_block_by_selector(MutableBlock* dst,
953
1
                                          const IColumn::Selector& selector) const {
954
1
    RETURN_IF_CATCH_EXCEPTION({
955
1
        DCHECK_EQ(data.size(), dst->mutable_columns().size());
956
1
        for (size_t i = 0; i < data.size(); i++) {
957
            // FIXME: this is a quickfix. we assume that only partition functions make there some
958
1
            if (!is_column_const(*data[i].column)) {
959
1
                data[i].column->append_data_by_selector(dst->mutable_columns()[i], selector);
960
1
            }
961
1
        }
962
1
    });
963
1
    return Status::OK();
964
1
}
965
966
Status Block::filter_block(Block* block, const std::vector<uint32_t>& columns_to_filter,
967
496
                           size_t filter_column_id, size_t column_to_keep) {
968
496
    const auto& filter_column = block->get_by_position(filter_column_id).column;
969
496
    if (const auto* nullable_column = check_and_get_column<ColumnNullable>(*filter_column)) {
970
1
        const auto& nested_column = nullable_column->get_nested_column_ptr();
971
972
1
        MutableColumnPtr mutable_holder =
973
1
                nested_column->use_count() == 1
974
1
                        ? nested_column->assert_mutable()
975
1
                        : nested_column->clone_resized(nested_column->size());
976
977
1
        auto* concrete_column = assert_cast<ColumnUInt8*>(mutable_holder.get());
978
1
        const auto* __restrict null_map = nullable_column->get_null_map_data().data();
979
1
        IColumn::Filter& filter = concrete_column->get_data();
980
1
        auto* __restrict filter_data = filter.data();
981
982
1
        const size_t size = filter.size();
983
4
        for (size_t i = 0; i < size; ++i) {
984
3
            filter_data[i] &= !null_map[i];
985
3
        }
986
1
        RETURN_IF_CATCH_EXCEPTION(filter_block_internal(block, columns_to_filter, filter));
987
495
    } else if (const auto* const_column = check_and_get_column<ColumnConst>(*filter_column)) {
988
2
        bool ret = const_column->get_bool(0);
989
2
        if (!ret) {
990
2
            for (const auto& col : columns_to_filter) {
991
2
                auto& column = block->get_by_position(col).column;
992
2
                if (column->is_exclusive()) {
993
2
                    column->assert_mutable()->clear();
994
2
                } else {
995
0
                    column = column->clone_empty();
996
0
                }
997
2
            }
998
1
        }
999
493
    } else {
1000
493
        const IColumn::Filter& filter =
1001
493
                assert_cast<const doris::ColumnUInt8&>(*filter_column).get_data();
1002
493
        RETURN_IF_CATCH_EXCEPTION(filter_block_internal(block, columns_to_filter, filter));
1003
493
    }
1004
1005
496
    erase_useless_column(block, column_to_keep);
1006
496
    return Status::OK();
1007
496
}
1008
1009
490
Status Block::filter_block(Block* block, size_t filter_column_id, size_t column_to_keep) {
1010
490
    std::vector<uint32_t> columns_to_filter;
1011
490
    columns_to_filter.resize(column_to_keep);
1012
1.77k
    for (uint32_t i = 0; i < column_to_keep; ++i) {
1013
1.28k
        columns_to_filter[i] = i;
1014
1.28k
    }
1015
490
    return filter_block(block, columns_to_filter, filter_column_id, column_to_keep);
1016
490
}
1017
1018
Status Block::serialize(int be_exec_version, PBlock* pblock,
1019
                        /*std::string* compressed_buffer,*/ size_t* uncompressed_bytes,
1020
                        size_t* compressed_bytes, int64_t* compress_time,
1021
                        segment_v2::CompressionTypePB compression_type,
1022
2.72k
                        bool allow_transfer_large_data) const {
1023
2.72k
    RETURN_IF_ERROR(BeExecVersionManager::check_be_exec_version(be_exec_version));
1024
2.72k
    pblock->set_be_exec_version(be_exec_version);
1025
1026
    // calc uncompressed size for allocation
1027
2.72k
    size_t content_uncompressed_size = 0;
1028
3.41k
    for (const auto& c : *this) {
1029
3.41k
        PColumnMeta* pcm = pblock->add_column_metas();
1030
3.41k
        c.to_pb_column_meta(pcm);
1031
18.4E
        DCHECK(pcm->type() != PGenericType::UNKNOWN) << " forget to set pb type";
1032
        // get serialized size
1033
3.41k
        content_uncompressed_size +=
1034
3.41k
                c.type->get_uncompressed_serialized_bytes(*(c.column), pblock->be_exec_version());
1035
3.41k
    }
1036
1037
    // serialize data values
1038
    // when data type is HLL, content_uncompressed_size maybe larger than real size.
1039
2.72k
    std::string column_values;
1040
2.72k
    try {
1041
        // TODO: After support c++23, we should use resize_and_overwrite to replace resize
1042
2.72k
        column_values.resize(content_uncompressed_size);
1043
2.72k
    } catch (...) {
1044
0
        std::string msg = fmt::format("Try to alloc {} bytes for pblock column values failed.",
1045
0
                                      content_uncompressed_size);
1046
0
        LOG(WARNING) << msg;
1047
0
        return Status::BufferAllocFailed(msg);
1048
0
    }
1049
2.73k
    char* buf = column_values.data();
1050
1051
3.42k
    for (const auto& c : *this) {
1052
3.42k
        buf = c.type->serialize(*(c.column), buf, pblock->be_exec_version());
1053
3.42k
    }
1054
2.73k
    *uncompressed_bytes = content_uncompressed_size;
1055
2.73k
    const size_t serialize_bytes = buf - column_values.data() + STREAMVBYTE_PADDING;
1056
2.73k
    *compressed_bytes = serialize_bytes;
1057
2.73k
    column_values.resize(serialize_bytes);
1058
1059
    // compress
1060
2.73k
    if (compression_type != segment_v2::NO_COMPRESSION && content_uncompressed_size > 0) {
1061
625
        SCOPED_RAW_TIMER(compress_time);
1062
625
        pblock->set_compression_type(compression_type);
1063
625
        pblock->set_uncompressed_size(serialize_bytes);
1064
1065
625
        BlockCompressionCodec* codec;
1066
625
        RETURN_IF_ERROR(get_block_compression_codec(compression_type, &codec));
1067
1068
625
        faststring buf_compressed;
1069
625
        RETURN_IF_ERROR_OR_CATCH_EXCEPTION(
1070
625
                codec->compress(Slice(column_values.data(), serialize_bytes), &buf_compressed));
1071
625
        size_t compressed_size = buf_compressed.size();
1072
625
        if (LIKELY(compressed_size < serialize_bytes)) {
1073
            // TODO: rethink the logic here may copy again ?
1074
625
            pblock->set_column_values(buf_compressed.data(), buf_compressed.size());
1075
625
            pblock->set_compressed(true);
1076
625
            *compressed_bytes = compressed_size;
1077
625
        } else {
1078
0
            pblock->set_column_values(std::move(column_values));
1079
0
        }
1080
1081
625
        VLOG_ROW << "uncompressed size: " << content_uncompressed_size
1082
0
                 << ", compressed size: " << compressed_size;
1083
2.10k
    } else {
1084
2.10k
        pblock->set_column_values(std::move(column_values));
1085
2.10k
    }
1086
2.73k
    if (!allow_transfer_large_data && *compressed_bytes >= std::numeric_limits<int32_t>::max()) {
1087
0
        return Status::InternalError("The block is large than 2GB({}), can not send by Protobuf.",
1088
0
                                     *compressed_bytes);
1089
0
    }
1090
2.73k
    return Status::OK();
1091
2.73k
}
1092
1093
240k
size_t MutableBlock::rows() const {
1094
240k
    for (const auto& column : _columns) {
1095
144k
        if (column) {
1096
144k
            return column->size();
1097
144k
        }
1098
144k
    }
1099
1100
96.0k
    return 0;
1101
240k
}
1102
1103
0
void MutableBlock::swap(MutableBlock& another) noexcept {
1104
0
    SCOPED_SKIP_MEMORY_CHECK();
1105
0
    _columns.swap(another._columns);
1106
0
    _data_types.swap(another._data_types);
1107
0
    _names.swap(another._names);
1108
0
}
1109
1110
0
void MutableBlock::add_row(const Block* block, int row) {
1111
0
    const auto& block_data = block->get_columns_with_type_and_name();
1112
0
    for (size_t i = 0; i < _columns.size(); ++i) {
1113
0
        _columns[i]->insert_from(*block_data[i].column.get(), row);
1114
0
    }
1115
0
}
1116
1117
Status MutableBlock::add_rows(const Block* block, const uint32_t* row_begin,
1118
163
                              const uint32_t* row_end, const std::vector<int>* column_offset) {
1119
163
    RETURN_IF_CATCH_EXCEPTION({
1120
163
        DCHECK_LE(columns(), block->columns());
1121
163
        if (column_offset != nullptr) {
1122
163
            DCHECK_EQ(columns(), column_offset->size());
1123
163
        }
1124
163
        const auto& block_data = block->get_columns_with_type_and_name();
1125
163
        for (size_t i = 0; i < _columns.size(); ++i) {
1126
163
            const auto& src_col = column_offset ? block_data[(*column_offset)[i]] : block_data[i];
1127
163
            DCHECK_EQ(_data_types[i]->get_name(), src_col.type->get_name());
1128
163
            auto& dst = _columns[i];
1129
163
            const auto& src = *src_col.column.get();
1130
163
            DCHECK_GE(src.size(), row_end - row_begin);
1131
163
            dst->insert_indices_from(src, row_begin, row_end);
1132
163
        }
1133
163
    });
1134
162
    return Status::OK();
1135
163
}
1136
1137
126
Status MutableBlock::add_rows(const Block* block, size_t row_begin, size_t length) {
1138
126
    RETURN_IF_CATCH_EXCEPTION({
1139
126
        DCHECK_LE(columns(), block->columns());
1140
126
        const auto& block_data = block->get_columns_with_type_and_name();
1141
126
        for (size_t i = 0; i < _columns.size(); ++i) {
1142
126
            DCHECK_EQ(_data_types[i]->get_name(), block_data[i].type->get_name());
1143
126
            auto& dst = _columns[i];
1144
126
            const auto& src = *block_data[i].column.get();
1145
126
            dst->insert_range_from(src, row_begin, length);
1146
126
        }
1147
126
    });
1148
126
    return Status::OK();
1149
126
}
1150
1151
144k
Block MutableBlock::to_block(int start_column) {
1152
144k
    return to_block(start_column, (int)_columns.size());
1153
144k
}
1154
1155
144k
Block MutableBlock::to_block(int start_column, int end_column) {
1156
144k
    ColumnsWithTypeAndName columns_with_schema;
1157
144k
    columns_with_schema.reserve(end_column - start_column);
1158
428k
    for (size_t i = start_column; i < end_column; ++i) {
1159
283k
        columns_with_schema.emplace_back(std::move(_columns[i]), _data_types[i], _names[i]);
1160
283k
    }
1161
144k
    return {columns_with_schema};
1162
144k
}
1163
1164
1
std::string MutableBlock::dump_data_json(size_t row_limit) const {
1165
1
    std::stringstream ss;
1166
1
    std::vector<std::string> headers;
1167
1168
1
    headers.reserve(columns());
1169
2
    for (size_t i = 0; i < columns(); ++i) {
1170
1
        headers.push_back(_data_types[i]->get_name());
1171
1
    }
1172
1
    size_t num_rows_to_dump = std::min(rows(), row_limit);
1173
1
    ss << "[";
1174
1175
1
    auto format_options = DataTypeSerDe::get_default_format_options();
1176
1
    auto time_zone = cctz::utc_time_zone();
1177
1
    format_options.timezone = &time_zone;
1178
1179
4
    for (size_t row_num = 0; row_num < num_rows_to_dump; ++row_num) {
1180
3
        if (row_num > 0) {
1181
2
            ss << ",";
1182
2
        }
1183
3
        ss << "{";
1184
6
        for (size_t i = 0; i < columns(); ++i) {
1185
3
            if (i > 0) {
1186
0
                ss << ",";
1187
0
            }
1188
3
            ss << "\"" << headers[i] << "\":";
1189
3
            std::string s = _data_types[i]->to_string(*_columns[i].get(), row_num, format_options);
1190
3
            ss << "\"" << s << "\"";
1191
3
        }
1192
3
        ss << "}";
1193
3
    }
1194
1
    ss << "]";
1195
1
    return ss.str();
1196
1
}
1197
1198
1
std::string MutableBlock::dump_data(size_t row_limit) const {
1199
1
    std::vector<std::string> headers;
1200
1
    std::vector<int> headers_size;
1201
2
    for (size_t i = 0; i < columns(); ++i) {
1202
1
        std::string s = _data_types[i]->get_name();
1203
1
        headers_size.push_back(s.size() > 15 ? (int)s.size() : 15);
1204
1
        headers.emplace_back(s);
1205
1
    }
1206
1207
1
    std::stringstream out;
1208
    // header upper line
1209
3
    auto line = [&]() {
1210
6
        for (size_t i = 0; i < columns(); ++i) {
1211
3
            out << std::setfill('-') << std::setw(1) << "+" << std::setw(headers_size[i]) << "-";
1212
3
        }
1213
3
        out << std::setw(1) << "+" << std::endl;
1214
3
    };
1215
1
    line();
1216
    // header text
1217
2
    for (size_t i = 0; i < columns(); ++i) {
1218
1
        out << std::setfill(' ') << std::setw(1) << "|" << std::left << std::setw(headers_size[i])
1219
1
            << headers[i];
1220
1
    }
1221
1
    out << std::setw(1) << "|" << std::endl;
1222
    // header bottom line
1223
1
    line();
1224
1
    if (rows() == 0) {
1225
0
        return out.str();
1226
0
    }
1227
1228
1
    auto format_options = DataTypeSerDe::get_default_format_options();
1229
1
    auto time_zone = cctz::utc_time_zone();
1230
1
    format_options.timezone = &time_zone;
1231
1232
    // content
1233
4
    for (size_t row_num = 0; row_num < rows() && row_num < row_limit; ++row_num) {
1234
6
        for (size_t i = 0; i < columns(); ++i) {
1235
3
            if (_columns[i].get()->empty()) {
1236
0
                out << std::setfill(' ') << std::setw(1) << "|" << std::setw(headers_size[i])
1237
0
                    << std::right;
1238
0
                continue;
1239
0
            }
1240
3
            std::string s = _data_types[i]->to_string(*_columns[i].get(), row_num, format_options);
1241
3
            if (s.length() > headers_size[i]) {
1242
0
                s = s.substr(0, headers_size[i] - 3) + "...";
1243
0
            }
1244
3
            out << std::setfill(' ') << std::setw(1) << "|" << std::setw(headers_size[i])
1245
3
                << std::right << s;
1246
3
        }
1247
3
        out << std::setw(1) << "|" << std::endl;
1248
3
    }
1249
    // bottom line
1250
1
    line();
1251
1
    if (row_limit < rows()) {
1252
0
        out << rows() << " rows in block, only show first " << row_limit << " rows." << std::endl;
1253
0
    }
1254
1
    return out.str();
1255
1
}
1256
1257
48.0k
std::unique_ptr<Block> Block::create_same_struct_block(size_t size, bool is_reserve) const {
1258
48.0k
    auto temp_block = Block::create_unique();
1259
94.1k
    for (const auto& d : data) {
1260
94.1k
        auto column = d.type->create_column();
1261
94.1k
        if (is_reserve) {
1262
0
            column->reserve(size);
1263
94.1k
        } else {
1264
94.1k
            column->insert_many_defaults(size);
1265
94.1k
        }
1266
94.1k
        temp_block->insert({std::move(column), d.type, d.name});
1267
94.1k
    }
1268
48.0k
    return temp_block;
1269
48.0k
}
1270
1271
96.1k
size_t MutableBlock::allocated_bytes() const {
1272
96.1k
    size_t res = 0;
1273
188k
    for (const auto& col : _columns) {
1274
188k
        if (col) {
1275
188k
            res += col->allocated_bytes();
1276
188k
        }
1277
188k
    }
1278
1279
96.1k
    return res;
1280
96.1k
}
1281
1282
1
void MutableBlock::clear_column_data() noexcept {
1283
1
    SCOPED_SKIP_MEMORY_CHECK();
1284
1
    for (auto& col : _columns) {
1285
1
        if (col) {
1286
1
            col->clear();
1287
1
        }
1288
1
    }
1289
1
}
1290
1291
5
std::string MutableBlock::dump_names() const {
1292
5
    std::string out;
1293
16
    for (auto it = _names.begin(); it != _names.end(); ++it) {
1294
11
        if (it != _names.begin()) {
1295
6
            out += ", ";
1296
6
        }
1297
11
        out += *it;
1298
11
    }
1299
5
    return out;
1300
5
}
1301
} // namespace doris