Coverage Report

Created: 2026-07-14 17:43

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.7k
bool is_recursively_exclusive(const IColumn& column) {
87
32.7k
    if (!column.is_exclusive()) {
88
13
        return false;
89
13
    }
90
91
32.6k
    bool exclusive = true;
92
32.6k
    IColumn::ColumnCallback callback = [&](const IColumn& subcolumn) {
93
27.8k
        if (!exclusive) {
94
0
            return;
95
0
        }
96
27.8k
        exclusive = is_recursively_exclusive(subcolumn);
97
27.8k
    };
98
32.6k
    column.for_each_subcolumn(callback);
99
32.6k
    return exclusive;
100
32.7k
}
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.84k
MutableColumnPtr scoped_mutate_column(ColumnPtr& column, const DataTypePtr& type) {
106
4.84k
    DCHECK(type);
107
4.84k
    if (!column) {
108
1
        return type->create_column();
109
1
    }
110
111
4.84k
    MutableColumnPtr mutable_column;
112
4.84k
    if (is_recursively_exclusive(*column)) {
113
4.83k
        mutable_column = std::move(*column).mutate();
114
4.83k
    } else {
115
13
        mutable_column = IColumn::mutate(column);
116
13
    }
117
4.84k
    column = nullptr;
118
4.84k
    return mutable_column;
119
4.84k
}
120
121
} // namespace
122
123
4.40k
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
997
                          int64_t* decompress_time) {
148
997
    swap(Block());
149
997
    int be_exec_version = pblock.has_be_exec_version() ? pblock.be_exec_version() : 0;
150
997
    RETURN_IF_ERROR(BeExecVersionManager::check_be_exec_version(be_exec_version));
151
152
997
    const char* buf = nullptr;
153
997
    std::string compression_scratch;
154
997
    if (pblock.compressed()) {
155
        // Decompress
156
486
        SCOPED_RAW_TIMER(decompress_time);
157
486
        const char* compressed_data = pblock.column_values().c_str();
158
486
        size_t compressed_size = pblock.column_values().size();
159
486
        size_t uncompressed_size = 0;
160
486
        if (pblock.has_compression_type() && pblock.has_uncompressed_size()) {
161
486
            BlockCompressionCodec* codec;
162
486
            RETURN_IF_ERROR(get_block_compression_codec(pblock.compression_type(), &codec));
163
486
            uncompressed_size = pblock.uncompressed_size();
164
            // Should also use allocator to allocate memory here.
165
486
            compression_scratch.resize(uncompressed_size);
166
486
            Slice decompressed_slice(compression_scratch);
167
486
            RETURN_IF_ERROR(codec->decompress(Slice(compressed_data, compressed_size),
168
486
                                              &decompressed_slice));
169
486
            DCHECK(uncompressed_size == decompressed_slice.size);
170
486
        } 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
486
        *uncompressed_bytes = uncompressed_size;
180
486
        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
997
    return Status::OK();
195
997
}
196
197
13.6k
void Block::reserve(size_t count) {
198
13.6k
    data.reserve(count);
199
13.6k
}
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
177k
    for (auto& entry : data) {
223
177k
        entry.name.clear();
224
177k
    }
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
6
void Block::erase(const std::set<size_t>& positions) {
236
6
    for (unsigned long position : std::ranges::reverse_view(positions)) {
237
5
        erase(position);
238
5
    }
239
6
}
240
241
710
void Block::erase_tail(size_t start) {
242
710
    DCHECK(start <= data.size()) << fmt::format(
243
0
            "Position out of bound in Block::erase(), max position = {}", data.size());
244
710
    data.erase(data.begin() + start, data.end());
245
710
}
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
1.56M
Status Block::check_no_column_string64() const {
358
1.75M
    for (size_t i = 0; i != data.size(); ++i) {
359
190k
        const auto& elem = data[i];
360
190k
        DCHECK(elem.column);
361
190k
        if (elem.column->contains_column_string64()) {
362
2
            return Status::InternalError(
363
2
                    "ColumnString64 is not allowed at operator boundaries, column index: {}, "
364
2
                    "name: {}, structure: {}",
365
2
                    i, elem.name, elem.column->dump_structure());
366
2
        }
367
190k
    }
368
1.56M
    return Status::OK();
369
1.56M
}
370
371
50.8M
size_t Block::rows() const {
372
50.8M
    for (const auto& elem : data) {
373
46.4M
        if (elem.column) {
374
46.4M
            return elem.column->size();
375
46.4M
        }
376
46.4M
    }
377
378
4.40M
    return 0;
379
50.8M
}
380
381
6
void Block::set_num_rows(size_t length) {
382
6
    if (rows() > length) {
383
4
        for (auto& elem : data) {
384
4
            if (elem.column) {
385
4
                elem.column = elem.column->shrink(length);
386
4
            }
387
4
        }
388
4
    }
389
6
}
390
391
1
void Block::skip_num_rows(int64_t& length) {
392
1
    auto origin_rows = rows();
393
1
    if (origin_rows <= length) {
394
0
        clear();
395
0
        length -= origin_rows;
396
1
    } else {
397
1
        for (auto& elem : data) {
398
1
            if (elem.column) {
399
1
                elem.column = elem.column->cut(length, origin_rows - length);
400
1
            }
401
1
        }
402
1
    }
403
1
}
404
405
13.2k
size_t Block::bytes() const {
406
13.2k
    size_t res = 0;
407
27.9k
    for (const auto& elem : data) {
408
27.9k
        if (!elem.column) {
409
0
            std::stringstream ss;
410
0
            for (const auto& e : data) {
411
0
                ss << e.name + " ";
412
0
            }
413
0
            throw Exception(ErrorCode::INTERNAL_ERROR,
414
0
                            "Column {} in block is nullptr, in method bytes. All Columns are {}",
415
0
                            elem.name, ss.str());
416
0
        }
417
27.9k
        res += elem.column->byte_size();
418
27.9k
    }
419
420
13.2k
    return res;
421
13.2k
}
422
423
194k
size_t Block::allocated_bytes() const {
424
194k
    size_t res = 0;
425
381k
    for (const auto& elem : data) {
426
381k
        if (!elem.column) {
427
            // Sometimes if expr failed, then there will be a nullptr
428
            // column left in the block.
429
1
            continue;
430
1
        }
431
381k
        res += elem.column->allocated_bytes();
432
381k
    }
433
434
194k
    return res;
435
194k
}
436
437
8
std::string Block::dump_names() const {
438
8
    std::string out;
439
23
    for (auto it = data.begin(); it != data.end(); ++it) {
440
15
        if (it != data.begin()) {
441
7
            out += ", ";
442
7
        }
443
15
        out += it->name;
444
15
    }
445
8
    return out;
446
8
}
447
448
7
std::string Block::dump_types() const {
449
7
    std::string out;
450
21
    for (auto it = data.begin(); it != data.end(); ++it) {
451
14
        if (it != data.begin()) {
452
7
            out += ", ";
453
7
        }
454
14
        out += it->type->get_name();
455
14
    }
456
7
    return out;
457
7
}
458
459
31
std::string Block::dump_data_json(size_t begin, size_t row_limit, bool allow_null_mismatch) const {
460
31
    std::stringstream ss;
461
462
31
    std::vector<std::string> headers;
463
31
    headers.reserve(columns());
464
46
    for (const auto& it : data) {
465
        // fmt::format is from the {fmt} library, you might be using std::format in C++20
466
        // If not, you can build the string with a stringstream as a fallback.
467
46
        headers.push_back(fmt::format("{}({})", it.name, it.type->get_name()));
468
46
    }
469
470
31
    size_t start_row = std::min(begin, rows());
471
31
    size_t end_row = std::min(rows(), begin + row_limit);
472
473
31
    auto format_options = DataTypeSerDe::get_default_format_options();
474
31
    auto time_zone = cctz::utc_time_zone();
475
31
    format_options.timezone = &time_zone;
476
477
31
    ss << "[";
478
3.59k
    for (size_t row_num = start_row; row_num < end_row; ++row_num) {
479
3.56k
        if (row_num > start_row) {
480
3.53k
            ss << ",";
481
3.53k
        }
482
3.56k
        ss << "{";
483
8.33k
        for (size_t i = 0; i < columns(); ++i) {
484
4.77k
            if (i > 0) {
485
1.21k
                ss << ",";
486
1.21k
            }
487
4.77k
            ss << "\"" << headers[i] << "\":";
488
4.77k
            std::string s;
489
490
            // This value-extraction logic is preserved from your original function
491
            // to maintain consistency, especially for handling nullability mismatches.
492
4.77k
            if (data[i].column && data[i].type->is_nullable() && !data[i].column->is_nullable()) {
493
                // This branch handles a specific internal representation of nullable columns.
494
                // The original code would assert here if allow_null_mismatch is false.
495
0
                assert(allow_null_mismatch);
496
0
                s = assert_cast<const DataTypeNullable*>(data[i].type.get())
497
0
                            ->get_nested_type()
498
0
                            ->to_string(*data[i].column, row_num, format_options);
499
4.77k
            } else {
500
                // This is the standard path. The to_string method is expected to correctly
501
                // handle all cases, including when the column is null (e.g., by returning "NULL").
502
4.77k
                s = data[i].to_string(row_num, format_options);
503
4.77k
            }
504
4.77k
            ss << "\"" << s << "\"";
505
4.77k
        }
506
3.56k
        ss << "}";
507
3.56k
    }
508
31
    ss << "]";
509
31
    return ss.str();
510
31
}
511
512
858
std::string Block::dump_data(size_t begin, size_t row_limit, bool allow_null_mismatch) const {
513
858
    std::vector<std::string> headers;
514
858
    std::vector<int> headers_size;
515
2.10k
    for (const auto& it : data) {
516
2.10k
        std::string s = fmt::format("{}({})", it.name, it.type->get_name());
517
2.10k
        headers_size.push_back(s.size() > 15 ? (int)s.size() : 15);
518
2.10k
        headers.emplace_back(s);
519
2.10k
    }
520
521
858
    std::stringstream out;
522
    // header upper line
523
2.16k
    auto line = [&]() {
524
8.07k
        for (size_t i = 0; i < columns(); ++i) {
525
5.91k
            out << std::setfill('-') << std::setw(1) << "+" << std::setw(headers_size[i]) << "-";
526
5.91k
        }
527
2.16k
        out << std::setw(1) << "+" << std::endl;
528
2.16k
    };
529
858
    line();
530
    // header text
531
2.96k
    for (size_t i = 0; i < columns(); ++i) {
532
2.10k
        out << std::setfill(' ') << std::setw(1) << "|" << std::left << std::setw(headers_size[i])
533
2.10k
            << headers[i];
534
2.10k
    }
535
858
    out << std::setw(1) << "|" << std::endl;
536
    // header bottom line
537
858
    line();
538
858
    if (rows() == 0) {
539
414
        return out.str();
540
414
    }
541
542
444
    auto format_options = DataTypeSerDe::get_default_format_options();
543
444
    auto time_zone = cctz::utc_time_zone();
544
444
    format_options.timezone = &time_zone;
545
546
    // content
547
12.2k
    for (size_t row_num = begin; row_num < rows() && row_num < row_limit + begin; ++row_num) {
548
32.4k
        for (size_t i = 0; i < columns(); ++i) {
549
20.6k
            if (!data[i].column || data[i].column->empty()) {
550
0
                out << std::setfill(' ') << std::setw(1) << "|" << std::setw(headers_size[i])
551
0
                    << std::right;
552
0
                continue;
553
0
            }
554
20.6k
            std::string s;
555
20.6k
            if (data[i].column) { // column may be const
556
                // for code inside `default_implementation_for_nulls`, there's could have: type = null, col != null
557
20.6k
                if (data[i].type->is_nullable() && !data[i].column->is_nullable()) {
558
0
                    assert(allow_null_mismatch);
559
0
                    s = assert_cast<const DataTypeNullable*>(data[i].type.get())
560
0
                                ->get_nested_type()
561
0
                                ->to_string(*data[i].column, row_num, format_options);
562
20.6k
                } else {
563
20.6k
                    s = data[i].to_string(row_num, format_options);
564
20.6k
                }
565
20.6k
            }
566
20.6k
            if (s.length() > headers_size[i]) {
567
2.12k
                s = s.substr(0, headers_size[i] - 3) + "...";
568
2.12k
            }
569
20.6k
            out << std::setfill(' ') << std::setw(1) << "|" << std::setw(headers_size[i])
570
20.6k
                << std::right << s;
571
20.6k
        }
572
11.7k
        out << std::setw(1) << "|" << std::endl;
573
11.7k
    }
574
    // bottom line
575
444
    line();
576
444
    if (row_limit < rows()) {
577
112
        out << rows() << " rows in block, only show first " << row_limit << " rows." << std::endl;
578
112
    }
579
444
    return out.str();
580
444
}
581
582
1
std::string Block::dump_one_line(size_t row, int column_end) const {
583
1
    assert(column_end <= columns());
584
1
    fmt::memory_buffer line;
585
586
1
    auto format_options = DataTypeSerDe::get_default_format_options();
587
1
    auto time_zone = cctz::utc_time_zone();
588
1
    format_options.timezone = &time_zone;
589
590
3
    for (int i = 0; i < column_end; ++i) {
591
2
        if (LIKELY(i != 0)) {
592
            // TODO: need more effective function of to string. now the impl is slow
593
1
            fmt::format_to(line, " {}", data[i].to_string(row, format_options));
594
1
        } else {
595
1
            fmt::format_to(line, "{}", data[i].to_string(row, format_options));
596
1
        }
597
2
    }
598
1
    return fmt::to_string(line);
599
1
}
600
601
47
std::string Block::dump_structure() const {
602
47
    std::string out;
603
382
    for (auto it = data.begin(); it != data.end(); ++it) {
604
335
        if (it != data.begin()) {
605
288
            out += ", \n";
606
288
        }
607
335
        out += it->dump_structure();
608
335
    }
609
47
    return out;
610
47
}
611
612
48.9k
Block Block::clone_empty() const {
613
48.9k
    Block res;
614
95.8k
    for (const auto& elem : data) {
615
95.8k
        res.insert(elem.clone_empty());
616
95.8k
    }
617
48.9k
    return res;
618
48.9k
}
619
620
32
MutableColumns Block::clone_empty_columns() const {
621
32
    size_t num_columns = data.size();
622
32
    MutableColumns columns(num_columns);
623
142
    for (size_t i = 0; i < num_columns; ++i) {
624
110
        columns[i] = data[i].column ? data[i].column->clone_empty() : data[i].type->create_column();
625
110
    }
626
32
    return columns;
627
32
}
628
629
26.2k
Columns Block::get_columns() const {
630
26.2k
    size_t num_columns = data.size();
631
26.2k
    Columns columns(num_columns);
632
114k
    for (size_t i = 0; i < num_columns; ++i) {
633
87.9k
        columns[i] = data[i].column->convert_to_full_column_if_const();
634
87.9k
    }
635
26.2k
    return columns;
636
26.2k
}
637
638
570
Columns Block::get_columns_and_convert() {
639
570
    size_t num_columns = data.size();
640
570
    Columns columns(num_columns);
641
1.20k
    for (size_t i = 0; i < num_columns; ++i) {
642
636
        data[i].column = data[i].column->convert_to_full_column_if_const();
643
636
        columns[i] = data[i].column;
644
636
    }
645
570
    return columns;
646
570
}
647
648
2.53k
Block::ScopedMutableColumns::ScopedMutableColumns(Block& block) : _block(&block) {
649
2.53k
    const size_t num_columns = block.data.size();
650
2.53k
    _columns.resize(num_columns);
651
2.53k
    size_t acquired_columns = 0;
652
2.53k
    try {
653
7.31k
        for (; acquired_columns < num_columns; ++acquired_columns) {
654
4.77k
            auto& column_with_type_and_name = block.data[acquired_columns];
655
4.77k
            _columns[acquired_columns] = scoped_mutate_column(column_with_type_and_name.column,
656
4.77k
                                                              column_with_type_and_name.type);
657
4.77k
        }
658
2.53k
    } catch (...) {
659
4
        for (size_t i = 0; i < acquired_columns; ++i) {
660
2
            block.data[i].column = std::move(_columns[i]);
661
2
        }
662
2
        _block = nullptr;
663
2
        throw;
664
2
    }
665
2.53k
}
666
667
2.53k
Block::ScopedMutableColumns::~ScopedMutableColumns() {
668
2.53k
    restore();
669
2.53k
}
670
671
Block::ScopedMutableColumns::ScopedMutableColumns(ScopedMutableColumns&& other) noexcept
672
0
        : _block(std::exchange(other._block, nullptr)), _columns(std::move(other._columns)) {}
673
674
Block::ScopedMutableColumns& Block::ScopedMutableColumns::operator=(
675
0
        ScopedMutableColumns&& other) noexcept {
676
0
    if (this != &other) {
677
0
        restore();
678
0
        _block = std::exchange(other._block, nullptr);
679
0
        _columns = std::move(other._columns);
680
0
    }
681
0
    return *this;
682
0
}
683
684
7
const DataTypePtr& Block::ScopedMutableColumns::get_datatype_by_position(size_t position) const {
685
7
    DCHECK(_block != nullptr);
686
7
    return _block->get_by_position(position).type;
687
7
}
688
689
2
const std::string& Block::ScopedMutableColumns::get_name_by_position(size_t position) const {
690
2
    DCHECK(_block != nullptr);
691
2
    return _block->get_by_position(position).name;
692
2
}
693
694
823
MutableColumns Block::ScopedMutableColumns::release() {
695
823
    DCHECK(_block != nullptr);
696
823
    _block = nullptr;
697
823
    return std::move(_columns);
698
823
}
699
700
3.01k
void Block::ScopedMutableColumns::restore() {
701
3.01k
    if (_block != nullptr) {
702
1.71k
        _block->set_columns(std::move(_columns));
703
1.71k
        _block = nullptr;
704
1.71k
    }
705
3.01k
}
706
707
Block::ScopedMutableColumn::ScopedMutableColumn(Block& block, size_t position)
708
65
        : _block(&block), _position(position) {
709
65
    DCHECK_LT(_position, _block->data.size());
710
65
    auto& column_with_type_and_name = _block->data[_position];
711
65
    DCHECK(column_with_type_and_name.type);
712
65
    _column =
713
65
            scoped_mutate_column(column_with_type_and_name.column, column_with_type_and_name.type);
714
65
}
715
716
64
Block::ScopedMutableColumn::~ScopedMutableColumn() {
717
64
    restore();
718
64
}
719
720
Block::ScopedMutableColumn::ScopedMutableColumn(ScopedMutableColumn&& other) noexcept
721
0
        : _block(std::exchange(other._block, nullptr)),
722
0
          _position(other._position),
723
0
          _column(std::move(other._column)) {}
724
725
Block::ScopedMutableColumn& Block::ScopedMutableColumn::operator=(
726
0
        ScopedMutableColumn&& other) noexcept {
727
0
    if (this != &other) {
728
0
        restore();
729
0
        _block = std::exchange(other._block, nullptr);
730
0
        _position = other._position;
731
0
        _column = std::move(other._column);
732
0
    }
733
0
    return *this;
734
0
}
735
736
64
void Block::ScopedMutableColumn::restore() {
737
64
    if (_block != nullptr) {
738
64
        DCHECK_LT(_position, _block->data.size());
739
64
        _block->data[_position].column = std::move(_column);
740
64
        _block = nullptr;
741
64
    }
742
64
}
743
744
2.53k
Block::ScopedMutableColumns Block::mutate_columns_scoped() & {
745
2.53k
    return ScopedMutableColumns(*this);
746
2.53k
}
747
748
65
Block::ScopedMutableColumn Block::mutate_column_scoped(size_t position) & {
749
65
    return ScopedMutableColumn(*this, position);
750
65
}
751
752
824
ScopedMutableBlock::ScopedMutableBlock(Block* block) {
753
824
    DCHECK(block != nullptr);
754
824
    DataTypes data_types = block->get_data_types();
755
824
    std::vector<std::string> names = block->get_names();
756
824
    auto columns_guard = block->mutate_columns_scoped();
757
824
    _mutable_block.data_types() = std::move(data_types);
758
824
    _mutable_block.get_names() = std::move(names);
759
824
    _mutable_block.set_mutable_columns(columns_guard.release());
760
824
    _block = block;
761
824
}
762
763
146k
MutableColumns Block::mutate_columns() && {
764
146k
    size_t num_columns = data.size();
765
146k
    MutableColumns columns(num_columns);
766
433k
    for (size_t i = 0; i < num_columns; ++i) {
767
287k
        DCHECK(data[i].type);
768
287k
        columns[i] = data[i].column ? IColumn::mutate(std::move(data[i].column))
769
287k
                                    : data[i].type->create_column();
770
287k
    }
771
146k
    return columns;
772
146k
}
773
774
3.52k
void Block::set_columns(MutableColumns&& columns) {
775
3.52k
    DCHECK_GE(columns.size(), data.size())
776
0
            << fmt::format("Invalid size of columns, columns size: {}, data size: {}",
777
0
                           columns.size(), data.size());
778
3.52k
    size_t num_columns = data.size();
779
12.0k
    for (size_t i = 0; i < num_columns; ++i) {
780
8.50k
        data[i].column = std::move(columns[i]);
781
8.50k
    }
782
3.52k
}
783
784
51
Block Block::clone_without_columns(const std::vector<int>* column_offset) const {
785
51
    Block res;
786
787
51
    if (column_offset != nullptr) {
788
32
        size_t num_columns = column_offset->size();
789
174
        for (size_t i = 0; i < num_columns; ++i) {
790
142
            res.insert({nullptr, data[(*column_offset)[i]].type, data[(*column_offset)[i]].name});
791
142
        }
792
32
    } else {
793
19
        size_t num_columns = data.size();
794
53
        for (size_t i = 0; i < num_columns; ++i) {
795
34
            res.insert({nullptr, data[i].type, data[i].name});
796
34
        }
797
19
    }
798
51
    return res;
799
51
}
800
801
55.8k
const ColumnsWithTypeAndName& Block::get_columns_with_type_and_name() const {
802
55.8k
    return data;
803
55.8k
}
804
805
145k
std::vector<std::string> Block::get_names() const {
806
145k
    std::vector<std::string> res;
807
145k
    res.reserve(columns());
808
809
285k
    for (const auto& elem : data) {
810
285k
        res.push_back(elem.name);
811
285k
    }
812
813
145k
    return res;
814
145k
}
815
816
145k
DataTypes Block::get_data_types() const {
817
145k
    DataTypes res;
818
145k
    res.reserve(columns());
819
820
285k
    for (const auto& elem : data) {
821
285k
        res.push_back(elem.type);
822
285k
    }
823
824
145k
    return res;
825
145k
}
826
827
52.9k
void Block::clear() {
828
52.9k
    data.clear();
829
52.9k
}
830
831
1.49M
void Block::clear_column_data(int64_t column_size) {
832
1.49M
    SCOPED_SKIP_MEMORY_CHECK();
833
    // data.size() greater than column_size, means here have some
834
    // function exec result in block, need erase it here
835
1.49M
    if (column_size != -1 and data.size() > column_size) {
836
2.20k
        for (int64_t i = data.size() - 1; i >= column_size; --i) {
837
1.10k
            erase(i);
838
1.10k
        }
839
1.10k
    }
840
1.49M
    for (auto& d : data) {
841
53.8k
        if (d.column) {
842
53.8k
            if (d.column->is_exclusive()) {
843
53.6k
                d.column->assert_mutable()->clear();
844
53.6k
            } else {
845
241
                d.column = d.column->clone_empty();
846
241
            }
847
53.8k
        }
848
53.8k
    }
849
1.49M
}
850
851
13
void Block::clear_column_data(const std::vector<uint32_t>& columns_to_clear) {
852
13
    SCOPED_SKIP_MEMORY_CHECK();
853
13
    for (auto col : columns_to_clear) {
854
13
        DCHECK_LT(col, data.size());
855
13
        auto& column = data[col].column;
856
13
        if (column) {
857
13
            if (column->is_exclusive()) {
858
11
                column->assert_mutable()->clear();
859
11
            } else {
860
2
                column = column->clone_empty();
861
2
            }
862
13
        }
863
13
    }
864
13
}
865
866
void Block::clear_column_mem_not_keep(const std::vector<bool>& column_keep_flags,
867
48.0k
                                      bool need_keep_first) {
868
48.0k
    if (data.size() >= column_keep_flags.size()) {
869
48.0k
        auto origin_rows = rows();
870
142k
        for (size_t i = 0; i < column_keep_flags.size(); ++i) {
871
94.1k
            if (!column_keep_flags[i]) {
872
36.8k
                data[i].column = data[i].column->clone_empty();
873
36.8k
            }
874
94.1k
        }
875
876
48.0k
        if (need_keep_first && !column_keep_flags[0]) {
877
1
            auto first_column = data[0].column->clone_empty();
878
1
            first_column->resize(origin_rows);
879
1
            data[0].column = std::move(first_column);
880
1
        }
881
48.0k
    }
882
48.0k
}
883
884
1.33k
void Block::swap(Block& other) noexcept {
885
1.33k
    SCOPED_SKIP_MEMORY_CHECK();
886
1.33k
    data.swap(other.data);
887
1.33k
}
888
889
1.71k
void Block::swap(Block&& other) noexcept {
890
1.71k
    SCOPED_SKIP_MEMORY_CHECK();
891
1.71k
    data = std::move(other.data);
892
1.71k
}
893
894
3
void Block::shuffle_columns(const std::vector<int>& result_column_ids) {
895
3
    Container tmp_data;
896
3
    tmp_data.reserve(result_column_ids.size());
897
5
    for (const int result_column_id : result_column_ids) {
898
5
        tmp_data.push_back(data[result_column_id]);
899
5
    }
900
3
    data = std::move(tmp_data);
901
3
}
902
903
2
void Block::update_hash(SipHash& hash) const {
904
8
    for (size_t row_no = 0, num_rows = rows(); row_no < num_rows; ++row_no) {
905
12
        for (const auto& col : data) {
906
12
            col.column->update_hash_with_value(row_no, hash);
907
12
        }
908
6
    }
909
2
}
910
911
void Block::filter_block_internal(Block* block, const std::vector<uint32_t>& columns_to_filter,
912
557
                                  const IColumn::Filter& filter) {
913
557
    size_t count = filter.size() - simd::count_zero_num((int8_t*)filter.data(), filter.size());
914
1.39k
    for (const auto& col : columns_to_filter) {
915
1.39k
        auto& column = block->get_by_position(col).column;
916
1.39k
        if (column->size() == count) {
917
1.29k
            continue;
918
1.29k
        }
919
95
        if (count == 0) {
920
8
            if (column->is_exclusive()) {
921
6
                column->assert_mutable()->clear();
922
6
            } else {
923
2
                column = column->clone_empty();
924
2
            }
925
8
            continue;
926
8
        }
927
87
        if (column->is_exclusive()) {
928
            // COW: safe to mutate in-place since we have exclusive ownership
929
87
            const auto result_size = column->assert_mutable()->filter(filter);
930
87
            if (result_size != count) [[unlikely]] {
931
0
                throw Exception(ErrorCode::INTERNAL_ERROR,
932
0
                                "result_size not equal with filter_size, result_size={}, "
933
0
                                "filter_size={}",
934
0
                                result_size, count);
935
0
            }
936
87
        } else {
937
            // COW: must create a copy since column is shared
938
0
            column = column->filter(filter, count);
939
0
        }
940
87
    }
941
557
}
942
943
void Block::filter_block_internal(Block* block, const IColumn::Filter& filter,
944
4
                                  uint32_t column_to_keep) {
945
4
    std::vector<uint32_t> columns_to_filter;
946
4
    columns_to_filter.resize(column_to_keep);
947
12
    for (uint32_t i = 0; i < column_to_keep; ++i) {
948
8
        columns_to_filter[i] = i;
949
8
    }
950
4
    filter_block_internal(block, columns_to_filter, filter);
951
4
}
952
953
9
void Block::filter_block_internal(Block* block, const IColumn::Filter& filter) {
954
9
    const size_t count =
955
9
            filter.size() - simd::count_zero_num((int8_t*)filter.data(), filter.size());
956
27
    for (int i = 0; i < block->columns(); ++i) {
957
18
        auto& column = block->get_by_position(i).column;
958
18
        if (column->is_exclusive()) {
959
18
            column->assert_mutable()->filter(filter);
960
18
        } else {
961
0
            column = column->filter(filter, count);
962
0
        }
963
18
    }
964
9
}
965
966
Status Block::append_to_block_by_selector(MutableBlock* dst,
967
1
                                          const IColumn::Selector& selector) const {
968
1
    RETURN_IF_CATCH_EXCEPTION({
969
1
        DCHECK_EQ(data.size(), dst->mutable_columns().size());
970
1
        for (size_t i = 0; i < data.size(); i++) {
971
            // FIXME: this is a quickfix. we assume that only partition functions make there some
972
1
            if (!is_column_const(*data[i].column)) {
973
1
                data[i].column->append_data_by_selector(dst->mutable_columns()[i], selector);
974
1
            }
975
1
        }
976
1
    });
977
1
    return Status::OK();
978
1
}
979
980
Status Block::filter_block(Block* block, const std::vector<uint32_t>& columns_to_filter,
981
496
                           size_t filter_column_id, size_t column_to_keep) {
982
496
    const auto& filter_column = block->get_by_position(filter_column_id).column;
983
496
    if (const auto* nullable_column = check_and_get_column<ColumnNullable>(*filter_column)) {
984
1
        const auto& nested_column = nullable_column->get_nested_column_ptr();
985
986
1
        MutableColumnPtr mutable_holder =
987
1
                nested_column->use_count() == 1
988
1
                        ? nested_column->assert_mutable()
989
1
                        : nested_column->clone_resized(nested_column->size());
990
991
1
        auto* concrete_column = assert_cast<ColumnUInt8*>(mutable_holder.get());
992
1
        const auto* __restrict null_map = nullable_column->get_null_map_data().data();
993
1
        IColumn::Filter& filter = concrete_column->get_data();
994
1
        auto* __restrict filter_data = filter.data();
995
996
1
        const size_t size = filter.size();
997
4
        for (size_t i = 0; i < size; ++i) {
998
3
            filter_data[i] &= !null_map[i];
999
3
        }
1000
1
        RETURN_IF_CATCH_EXCEPTION(filter_block_internal(block, columns_to_filter, filter));
1001
495
    } else if (const auto* const_column = check_and_get_column<ColumnConst>(*filter_column)) {
1002
2
        bool ret = const_column->get_bool(0);
1003
2
        if (!ret) {
1004
2
            for (const auto& col : columns_to_filter) {
1005
2
                auto& column = block->get_by_position(col).column;
1006
2
                if (column->is_exclusive()) {
1007
2
                    column->assert_mutable()->clear();
1008
2
                } else {
1009
0
                    column = column->clone_empty();
1010
0
                }
1011
2
            }
1012
1
        }
1013
493
    } else {
1014
493
        const IColumn::Filter& filter =
1015
493
                assert_cast<const doris::ColumnUInt8&>(*filter_column).get_data();
1016
493
        RETURN_IF_CATCH_EXCEPTION(filter_block_internal(block, columns_to_filter, filter));
1017
493
    }
1018
1019
496
    erase_useless_column(block, column_to_keep);
1020
496
    return Status::OK();
1021
496
}
1022
1023
490
Status Block::filter_block(Block* block, size_t filter_column_id, size_t column_to_keep) {
1024
490
    std::vector<uint32_t> columns_to_filter;
1025
490
    columns_to_filter.resize(column_to_keep);
1026
1.77k
    for (uint32_t i = 0; i < column_to_keep; ++i) {
1027
1.28k
        columns_to_filter[i] = i;
1028
1.28k
    }
1029
490
    return filter_block(block, columns_to_filter, filter_column_id, column_to_keep);
1030
490
}
1031
1032
Status Block::serialize(int be_exec_version, PBlock* pblock,
1033
                        /*std::string* compressed_buffer,*/ size_t* uncompressed_bytes,
1034
                        size_t* compressed_bytes, int64_t* compress_time,
1035
                        segment_v2::CompressionTypePB compression_type,
1036
2.72k
                        bool allow_transfer_large_data) const {
1037
2.72k
    RETURN_IF_ERROR(BeExecVersionManager::check_be_exec_version(be_exec_version));
1038
2.72k
    pblock->set_be_exec_version(be_exec_version);
1039
1040
    // calc uncompressed size for allocation
1041
2.72k
    size_t content_uncompressed_size = 0;
1042
2.72k
    RETURN_IF_CATCH_EXCEPTION({
1043
2.72k
        for (const auto& c : *this) {
1044
2.72k
            PColumnMeta* pcm = pblock->add_column_metas();
1045
2.72k
            c.to_pb_column_meta(pcm);
1046
2.72k
            DCHECK(pcm->type() != PGenericType::UNKNOWN) << " forget to set pb type";
1047
            // get serialized size
1048
2.72k
            content_uncompressed_size += c.type->get_uncompressed_serialized_bytes(
1049
2.72k
                    *(c.column), pblock->be_exec_version());
1050
2.72k
        }
1051
2.72k
    });
1052
1053
    // serialize data values
1054
    // when data type is HLL, content_uncompressed_size maybe larger than real size.
1055
2.72k
    std::string column_values;
1056
2.72k
    try {
1057
        // TODO: After support c++23, we should use resize_and_overwrite to replace resize
1058
2.72k
        column_values.resize(content_uncompressed_size);
1059
2.72k
    } catch (...) {
1060
0
        std::string msg = fmt::format("Try to alloc {} bytes for pblock column values failed.",
1061
0
                                      content_uncompressed_size);
1062
0
        LOG(WARNING) << msg;
1063
0
        return Status::BufferAllocFailed(msg);
1064
0
    }
1065
2.73k
    char* buf = column_values.data();
1066
1067
2.73k
    RETURN_IF_CATCH_EXCEPTION({
1068
2.73k
        for (const auto& c : *this) {
1069
2.73k
            buf = c.type->serialize(*(c.column), buf, pblock->be_exec_version());
1070
2.73k
        }
1071
2.73k
    });
1072
2.73k
    *uncompressed_bytes = content_uncompressed_size;
1073
2.73k
    const size_t serialize_bytes = buf - column_values.data() + STREAMVBYTE_PADDING;
1074
2.73k
    *compressed_bytes = serialize_bytes;
1075
2.73k
    column_values.resize(serialize_bytes);
1076
1077
    // compress
1078
2.73k
    if (compression_type != segment_v2::NO_COMPRESSION && content_uncompressed_size > 0) {
1079
629
        SCOPED_RAW_TIMER(compress_time);
1080
629
        pblock->set_compression_type(compression_type);
1081
629
        pblock->set_uncompressed_size(serialize_bytes);
1082
1083
629
        BlockCompressionCodec* codec;
1084
629
        RETURN_IF_ERROR(get_block_compression_codec(compression_type, &codec));
1085
1086
629
        faststring buf_compressed;
1087
629
        RETURN_IF_ERROR_OR_CATCH_EXCEPTION(
1088
629
                codec->compress(Slice(column_values.data(), serialize_bytes), &buf_compressed));
1089
629
        size_t compressed_size = buf_compressed.size();
1090
629
        if (LIKELY(compressed_size < serialize_bytes)) {
1091
            // TODO: rethink the logic here may copy again ?
1092
629
            pblock->set_column_values(buf_compressed.data(), buf_compressed.size());
1093
629
            pblock->set_compressed(true);
1094
629
            *compressed_bytes = compressed_size;
1095
629
        } else {
1096
0
            pblock->set_column_values(std::move(column_values));
1097
0
        }
1098
1099
629
        VLOG_ROW << "uncompressed size: " << content_uncompressed_size
1100
0
                 << ", compressed size: " << compressed_size;
1101
2.10k
    } else {
1102
2.10k
        pblock->set_column_values(std::move(column_values));
1103
2.10k
    }
1104
2.73k
    if (!allow_transfer_large_data && *compressed_bytes >= std::numeric_limits<int32_t>::max()) {
1105
0
        return Status::InternalError("The block is large than 2GB({}), can not send by Protobuf.",
1106
0
                                     *compressed_bytes);
1107
0
    }
1108
2.73k
    return Status::OK();
1109
2.73k
}
1110
1111
240k
size_t MutableBlock::rows() const {
1112
240k
    for (const auto& column : _columns) {
1113
144k
        if (column) {
1114
144k
            return column->size();
1115
144k
        }
1116
144k
    }
1117
1118
96.0k
    return 0;
1119
240k
}
1120
1121
0
void MutableBlock::swap(MutableBlock& another) noexcept {
1122
0
    SCOPED_SKIP_MEMORY_CHECK();
1123
0
    _columns.swap(another._columns);
1124
0
    _data_types.swap(another._data_types);
1125
0
    _names.swap(another._names);
1126
0
}
1127
1128
0
void MutableBlock::add_row(const Block* block, int row) {
1129
0
    const auto& block_data = block->get_columns_with_type_and_name();
1130
0
    for (size_t i = 0; i < _columns.size(); ++i) {
1131
0
        _columns[i]->insert_from(*block_data[i].column.get(), row);
1132
0
    }
1133
0
}
1134
1135
Status MutableBlock::add_rows(const Block* block, const uint32_t* row_begin,
1136
165
                              const uint32_t* row_end, const std::vector<int>* column_offset) {
1137
165
    RETURN_IF_CATCH_EXCEPTION({
1138
165
        DCHECK_LE(columns(), block->columns());
1139
165
        if (column_offset != nullptr) {
1140
165
            DCHECK_EQ(columns(), column_offset->size());
1141
165
        }
1142
165
        const auto& block_data = block->get_columns_with_type_and_name();
1143
165
        for (size_t i = 0; i < _columns.size(); ++i) {
1144
165
            const auto& src_col = column_offset ? block_data[(*column_offset)[i]] : block_data[i];
1145
165
            DCHECK_EQ(_data_types[i]->get_name(), src_col.type->get_name());
1146
165
            auto& dst = _columns[i];
1147
165
            const auto& src = *src_col.column.get();
1148
165
            DCHECK_GE(src.size(), row_end - row_begin);
1149
165
            dst->insert_indices_from(src, row_begin, row_end);
1150
165
        }
1151
165
    });
1152
164
    return Status::OK();
1153
165
}
1154
1155
126
Status MutableBlock::add_rows(const Block* block, size_t row_begin, size_t length) {
1156
126
    RETURN_IF_CATCH_EXCEPTION({
1157
126
        DCHECK_LE(columns(), block->columns());
1158
126
        const auto& block_data = block->get_columns_with_type_and_name();
1159
126
        for (size_t i = 0; i < _columns.size(); ++i) {
1160
126
            DCHECK_EQ(_data_types[i]->get_name(), block_data[i].type->get_name());
1161
126
            auto& dst = _columns[i];
1162
126
            const auto& src = *block_data[i].column.get();
1163
126
            dst->insert_range_from(src, row_begin, length);
1164
126
        }
1165
126
    });
1166
126
    return Status::OK();
1167
126
}
1168
1169
144k
Block MutableBlock::to_block(int start_column) {
1170
144k
    return to_block(start_column, (int)_columns.size());
1171
144k
}
1172
1173
144k
Block MutableBlock::to_block(int start_column, int end_column) {
1174
144k
    ColumnsWithTypeAndName columns_with_schema;
1175
144k
    columns_with_schema.reserve(end_column - start_column);
1176
428k
    for (size_t i = start_column; i < end_column; ++i) {
1177
283k
        columns_with_schema.emplace_back(std::move(_columns[i]), _data_types[i], _names[i]);
1178
283k
    }
1179
144k
    return {columns_with_schema};
1180
144k
}
1181
1182
1
std::string MutableBlock::dump_data_json(size_t row_limit) const {
1183
1
    std::stringstream ss;
1184
1
    std::vector<std::string> headers;
1185
1186
1
    headers.reserve(columns());
1187
2
    for (size_t i = 0; i < columns(); ++i) {
1188
1
        headers.push_back(_data_types[i]->get_name());
1189
1
    }
1190
1
    size_t num_rows_to_dump = std::min(rows(), row_limit);
1191
1
    ss << "[";
1192
1193
1
    auto format_options = DataTypeSerDe::get_default_format_options();
1194
1
    auto time_zone = cctz::utc_time_zone();
1195
1
    format_options.timezone = &time_zone;
1196
1197
4
    for (size_t row_num = 0; row_num < num_rows_to_dump; ++row_num) {
1198
3
        if (row_num > 0) {
1199
2
            ss << ",";
1200
2
        }
1201
3
        ss << "{";
1202
6
        for (size_t i = 0; i < columns(); ++i) {
1203
3
            if (i > 0) {
1204
0
                ss << ",";
1205
0
            }
1206
3
            ss << "\"" << headers[i] << "\":";
1207
3
            std::string s = _data_types[i]->to_string(*_columns[i].get(), row_num, format_options);
1208
3
            ss << "\"" << s << "\"";
1209
3
        }
1210
3
        ss << "}";
1211
3
    }
1212
1
    ss << "]";
1213
1
    return ss.str();
1214
1
}
1215
1216
1
std::string MutableBlock::dump_data(size_t row_limit) const {
1217
1
    std::vector<std::string> headers;
1218
1
    std::vector<int> headers_size;
1219
2
    for (size_t i = 0; i < columns(); ++i) {
1220
1
        std::string s = _data_types[i]->get_name();
1221
1
        headers_size.push_back(s.size() > 15 ? (int)s.size() : 15);
1222
1
        headers.emplace_back(s);
1223
1
    }
1224
1225
1
    std::stringstream out;
1226
    // header upper line
1227
3
    auto line = [&]() {
1228
6
        for (size_t i = 0; i < columns(); ++i) {
1229
3
            out << std::setfill('-') << std::setw(1) << "+" << std::setw(headers_size[i]) << "-";
1230
3
        }
1231
3
        out << std::setw(1) << "+" << std::endl;
1232
3
    };
1233
1
    line();
1234
    // header text
1235
2
    for (size_t i = 0; i < columns(); ++i) {
1236
1
        out << std::setfill(' ') << std::setw(1) << "|" << std::left << std::setw(headers_size[i])
1237
1
            << headers[i];
1238
1
    }
1239
1
    out << std::setw(1) << "|" << std::endl;
1240
    // header bottom line
1241
1
    line();
1242
1
    if (rows() == 0) {
1243
0
        return out.str();
1244
0
    }
1245
1246
1
    auto format_options = DataTypeSerDe::get_default_format_options();
1247
1
    auto time_zone = cctz::utc_time_zone();
1248
1
    format_options.timezone = &time_zone;
1249
1250
    // content
1251
4
    for (size_t row_num = 0; row_num < rows() && row_num < row_limit; ++row_num) {
1252
6
        for (size_t i = 0; i < columns(); ++i) {
1253
3
            if (_columns[i].get()->empty()) {
1254
0
                out << std::setfill(' ') << std::setw(1) << "|" << std::setw(headers_size[i])
1255
0
                    << std::right;
1256
0
                continue;
1257
0
            }
1258
3
            std::string s = _data_types[i]->to_string(*_columns[i].get(), row_num, format_options);
1259
3
            if (s.length() > headers_size[i]) {
1260
0
                s = s.substr(0, headers_size[i] - 3) + "...";
1261
0
            }
1262
3
            out << std::setfill(' ') << std::setw(1) << "|" << std::setw(headers_size[i])
1263
3
                << std::right << s;
1264
3
        }
1265
3
        out << std::setw(1) << "|" << std::endl;
1266
3
    }
1267
    // bottom line
1268
1
    line();
1269
1
    if (row_limit < rows()) {
1270
0
        out << rows() << " rows in block, only show first " << row_limit << " rows." << std::endl;
1271
0
    }
1272
1
    return out.str();
1273
1
}
1274
1275
48.0k
std::unique_ptr<Block> Block::create_same_struct_block(size_t size, bool is_reserve) const {
1276
48.0k
    auto temp_block = Block::create_unique();
1277
94.1k
    for (const auto& d : data) {
1278
94.1k
        auto column = d.type->create_column();
1279
94.1k
        if (is_reserve) {
1280
0
            column->reserve(size);
1281
94.1k
        } else {
1282
94.1k
            column->insert_many_defaults(size);
1283
94.1k
        }
1284
94.1k
        temp_block->insert({std::move(column), d.type, d.name});
1285
94.1k
    }
1286
48.0k
    return temp_block;
1287
48.0k
}
1288
1289
96.1k
size_t MutableBlock::allocated_bytes() const {
1290
96.1k
    size_t res = 0;
1291
188k
    for (const auto& col : _columns) {
1292
188k
        if (col) {
1293
188k
            res += col->allocated_bytes();
1294
188k
        }
1295
188k
    }
1296
1297
96.1k
    return res;
1298
96.1k
}
1299
1300
1
void MutableBlock::clear_column_data() noexcept {
1301
1
    SCOPED_SKIP_MEMORY_CHECK();
1302
1
    for (auto& col : _columns) {
1303
1
        if (col) {
1304
1
            col->clear();
1305
1
        }
1306
1
    }
1307
1
}
1308
1309
5
std::string MutableBlock::dump_names() const {
1310
5
    std::string out;
1311
16
    for (auto it = _names.begin(); it != _names.end(); ++it) {
1312
11
        if (it != _names.begin()) {
1313
6
            out += ", ";
1314
6
        }
1315
11
        out += *it;
1316
11
    }
1317
5
    return out;
1318
5
}
1319
} // namespace doris