Coverage Report

Created: 2026-04-01 13:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/sink/vrow_distribution.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
18
#include "exec/sink/vrow_distribution.h"
19
20
#include <gen_cpp/FrontendService.h>
21
#include <gen_cpp/FrontendService_types.h>
22
#include <glog/logging.h>
23
24
#include <cstdint>
25
#include <memory>
26
#include <string>
27
28
#include "common/cast_set.h"
29
#include "common/logging.h"
30
#include "common/metrics/doris_metrics.h"
31
#include "common/status.h"
32
#include "core/assert_cast.h"
33
#include "core/column/column.h"
34
#include "core/column/column_const.h"
35
#include "core/column/column_nullable.h"
36
#include "core/column/column_vector.h"
37
#include "core/data_type/data_type.h"
38
#include "exec/sink/writer/vtablet_writer.h"
39
#include "runtime/exec_env.h"
40
#include "runtime/query_context.h"
41
#include "runtime/runtime_state.h"
42
#include "service/backend_options.h"
43
#include "util/client_cache.h"
44
#include "util/debug_points.h"
45
#include "util/thrift_rpc_helper.h"
46
47
namespace doris {
48
#include "common/compile_check_begin.h"
49
50
26
std::pair<VExprContextSPtrs, VExprSPtrs> VRowDistribution::_get_partition_function() {
51
26
    return {_vpartition->get_part_func_ctx(), _vpartition->get_partition_function()};
52
26
}
53
54
Status VRowDistribution::_save_missing_values(
55
        const Block& input_block,
56
        std::vector<std::vector<std::string>>& col_strs, // non-const ref for move
57
        int col_size, Block* block, const std::vector<uint32_t>& filter,
58
4
        const std::vector<const NullMap*>& col_null_maps) {
59
    // de-duplication for new partitions but save all rows.
60
4
    RETURN_IF_ERROR(
61
4
            _batching_block->add_rows(&input_block, filter.data(), filter.data() + filter.size()));
62
4
    std::vector<TNullableStringLiteral> cur_row_values;
63
12
    for (int row = 0; row < col_strs[0].size(); ++row) {
64
8
        cur_row_values.clear();
65
16
        for (int col = 0; col < col_size; ++col) {
66
8
            TNullableStringLiteral node;
67
8
            const auto* null_map = col_null_maps[col]; // null map for this col
68
8
            node.__set_is_null((null_map && (*null_map)[filter[row]])
69
8
                                       ? true
70
8
                                       : node.is_null); // if not, dont change(default false)
71
8
            if (!node.is_null) {
72
8
                node.__set_value(col_strs[col][row]);
73
8
            }
74
8
            cur_row_values.push_back(node);
75
8
        }
76
8
        if (!_deduper.contains(cur_row_values)) {
77
4
            _deduper.insert(cur_row_values);
78
4
            _partitions_need_create.emplace_back(cur_row_values);
79
4
        }
80
8
    }
81
82
    // to avoid too large mem use
83
4
    if (_batching_block->rows() > _batch_size) {
84
0
        _deal_batched = true;
85
0
    }
86
4
    _batching_rows = _batching_block->rows();
87
4
    VLOG_NOTICE << "pushed some batching lines, now numbers = " << _batching_rows;
88
89
4
    return Status::OK();
90
4
}
91
92
4
void VRowDistribution::clear_batching_stats() {
93
4
    _partitions_need_create.clear();
94
4
    _batching_rows = 0;
95
4
    _batching_bytes = 0;
96
4
}
97
98
4
Status VRowDistribution::automatic_create_partition() {
99
4
    MonotonicStopWatch timer;
100
4
    if (_state->enable_profile() && _state->profile_level() >= 2) {
101
0
        timer.start();
102
0
    }
103
104
4
    SCOPED_TIMER(_add_partition_request_timer);
105
4
    TCreatePartitionRequest request;
106
4
    TCreatePartitionResult result;
107
4
    bool injected = false;
108
4
    std::string be_endpoint = BackendOptions::get_be_endpoint();
109
4
    request.__set_txn_id(_txn_id);
110
4
    request.__set_db_id(_vpartition->db_id());
111
4
    request.__set_table_id(_vpartition->table_id());
112
4
    request.__set_partitionValues(_partitions_need_create);
113
4
    request.__set_be_endpoint(be_endpoint);
114
4
    request.__set_write_single_replica(_write_single_replica);
115
4
    if (_state && _state->get_query_ctx()) {
116
        // Pass query_id to FE so it can determine if this is a multi-instance load by checking Coordinator
117
4
        request.__set_query_id(_state->get_query_ctx()->query_id());
118
4
    }
119
120
4
    DBUG_EXECUTE_IF("VRowDistribution.automatic_create_partition.inject_result", {
121
4
        DBUG_RUN_CALLBACK(&request, &result);
122
4
        injected = true;
123
4
    });
124
125
4
    VLOG_NOTICE << "automatic partition rpc begin request " << request;
126
4
    if (!injected) {
127
0
        std::shared_ptr<TNetworkAddress> master_addr;
128
0
        if (_vpartition->get_master_address() == nullptr) {
129
0
            auto* cluster_info = ExecEnv::GetInstance()->cluster_info();
130
0
            if (cluster_info == nullptr) {
131
0
                return Status::InternalError("cluster_info is null");
132
0
            }
133
0
            master_addr = std::make_shared<TNetworkAddress>(cluster_info->master_fe_addr);
134
0
        } else {
135
0
            master_addr = _vpartition->get_master_address();
136
0
        }
137
0
        int time_out = _state->execution_timeout() * 1000;
138
0
        RETURN_IF_ERROR(ThriftRpcHelper::rpc<FrontendServiceClient>(
139
0
                master_addr->hostname, master_addr->port,
140
0
                [&request, &result](FrontendServiceConnection& client) {
141
0
                    client->createPartition(result, request);
142
0
                },
143
0
                time_out));
144
0
    }
145
146
4
    Status status(Status::create(result.status));
147
4
    VLOG_NOTICE << "automatic partition rpc end response " << result;
148
4
    if (result.status.status_code == TStatusCode::OK) {
149
        // add new created partitions
150
4
        RETURN_IF_ERROR(_vpartition->add_partitions(result.partitions));
151
4
        for (const auto& part : result.partitions) {
152
4
            _new_partition_ids.insert(part.id);
153
4
            VLOG_TRACE << "record new id: " << part.id;
154
4
        }
155
4
        RETURN_IF_ERROR(_create_partition_callback(_caller, &result));
156
4
    }
157
158
    // Record this request's elapsed time
159
4
    if (_state->enable_profile() && _state->profile_level() >= 2) {
160
0
        int64_t elapsed_ns = timer.elapsed_time();
161
0
        _add_partition_request_times.push_back(elapsed_ns);
162
0
    }
163
4
    return status;
164
4
}
165
166
// for reuse the same create callback of create-partition
167
2
static TCreatePartitionResult cast_as_create_result(TReplacePartitionResult& arg) {
168
2
    TCreatePartitionResult result;
169
2
    result.status = arg.status;
170
2
    result.nodes = std::move(arg.nodes);
171
2
    result.partitions = std::move(arg.partitions);
172
2
    result.tablets = std::move(arg.tablets);
173
2
    result.slave_tablets = std::move(arg.slave_tablets);
174
2
    return result;
175
2
}
176
177
// use _partitions and replace them
178
4
Status VRowDistribution::_replace_overwriting_partition() {
179
4
    SCOPED_TIMER(_add_partition_request_timer); // also for replace_partition
180
4
    TReplacePartitionRequest request;
181
4
    TReplacePartitionResult result;
182
4
    bool injected = false;
183
4
    request.__set_overwrite_group_id(_vpartition->get_overwrite_group_id());
184
4
    request.__set_db_id(_vpartition->db_id());
185
4
    request.__set_table_id(_vpartition->table_id());
186
4
    request.__set_write_single_replica(_write_single_replica);
187
188
    // only request for partitions not recorded for replacement
189
4
    std::set<int64_t> id_deduper;
190
6
    for (const auto* part : _partitions) {
191
6
        if (part != nullptr) {
192
6
            if (_new_partition_ids.contains(part->id)) {
193
                // this is a new partition. dont replace again.
194
2
                VLOG_TRACE << "skip new partition: " << part->id;
195
4
            } else {
196
                // request for replacement
197
4
                id_deduper.insert(part->id);
198
4
            }
199
6
        } else if (_missing_map.empty()) {
200
            // no origin partition. and not allow to create.
201
0
            return Status::InvalidArgument(
202
0
                    "Cannot found origin partitions in auto detect overwriting, stop "
203
0
                    "processing");
204
0
        } // else: part is null and _missing_map is not empty. dealed outside using auto-partition way. nothing to do here.
205
6
    }
206
4
    if (id_deduper.empty()) {
207
2
        return Status::OK(); // no need to request
208
2
    }
209
    // de-duplicate. there's no check in FE
210
2
    std::vector<int64_t> request_part_ids(id_deduper.begin(), id_deduper.end());
211
212
2
    request.__set_partition_ids(request_part_ids);
213
214
2
    std::string be_endpoint = BackendOptions::get_be_endpoint();
215
2
    request.__set_be_endpoint(be_endpoint);
216
2
    if (_state && _state->get_query_ctx()) {
217
        // Pass query_id to FE so it can determine if this is a multi-instance load by checking Coordinator
218
2
        request.__set_query_id(_state->get_query_ctx()->query_id());
219
2
    }
220
221
2
    DBUG_EXECUTE_IF("VRowDistribution.replace_overwriting_partition.inject_result", {
222
2
        DBUG_RUN_CALLBACK(&request, &result);
223
2
        injected = true;
224
2
    });
225
226
2
    VLOG_NOTICE << "auto detect replace partition request: " << request;
227
2
    if (!injected) {
228
0
        std::shared_ptr<TNetworkAddress> master_addr;
229
0
        if (_vpartition->get_master_address() == nullptr) {
230
0
            auto* cluster_info = ExecEnv::GetInstance()->cluster_info();
231
0
            if (cluster_info == nullptr) {
232
0
                return Status::InternalError("cluster_info is null");
233
0
            }
234
0
            master_addr = std::make_shared<TNetworkAddress>(cluster_info->master_fe_addr);
235
0
        } else {
236
0
            master_addr = _vpartition->get_master_address();
237
0
        }
238
0
        int time_out = _state->execution_timeout() * 1000;
239
0
        RETURN_IF_ERROR(ThriftRpcHelper::rpc<FrontendServiceClient>(
240
0
                master_addr->hostname, master_addr->port,
241
0
                [&request, &result](FrontendServiceConnection& client) {
242
0
                    client->replacePartition(result, request);
243
0
                },
244
0
                time_out));
245
0
    }
246
247
2
    Status status(Status::create(result.status));
248
2
    VLOG_NOTICE << "auto detect replace partition result: " << result;
249
2
    if (result.status.status_code == TStatusCode::OK) {
250
        // record new partitions
251
4
        for (const auto& part : result.partitions) {
252
4
            _new_partition_ids.insert(part.id);
253
4
            VLOG_TRACE << "record new id: " << part.id;
254
4
        }
255
        // replace data in _partitions
256
2
        RETURN_IF_ERROR(_vpartition->replace_partitions(request_part_ids, result.partitions));
257
        // reuse the function as the args' structure are same. it add nodes/locations and incremental_open
258
2
        auto result_as_create = cast_as_create_result(result);
259
2
        RETURN_IF_ERROR(_create_partition_callback(_caller, &result_as_create));
260
2
    }
261
262
2
    return status;
263
2
}
264
265
void VRowDistribution::_get_tablet_ids(Block* block, int32_t index_idx,
266
18
                                       std::vector<int64_t>& tablet_ids) {
267
18
    tablet_ids.resize(block->rows());
268
52
    for (int row_idx = 0; row_idx < block->rows(); row_idx++) {
269
34
        if (_skip[row_idx]) {
270
12
            continue;
271
12
        }
272
22
        auto& partition = _partitions[row_idx];
273
22
        auto& tablet_index = _tablet_indexes[row_idx];
274
22
        auto& index = partition->indexes[index_idx];
275
276
22
        auto tablet_id = index.tablets[tablet_index];
277
22
        tablet_ids[row_idx] = tablet_id;
278
22
    }
279
18
}
280
281
14
void VRowDistribution::_filter_block_by_skip(Block* block, RowPartTabletIds& row_part_tablet_id) {
282
14
    auto& row_ids = row_part_tablet_id.row_ids;
283
14
    auto& partition_ids = row_part_tablet_id.partition_ids;
284
14
    auto& tablet_ids = row_part_tablet_id.tablet_ids;
285
286
14
    auto rows = block->rows();
287
    // row count of a block should not exceed UINT32_MAX
288
14
    auto rows_uint32 = cast_set<uint32_t>(rows);
289
38
    for (uint32_t i = 0; i < rows_uint32; i++) {
290
24
        if (!_skip[i]) {
291
12
            row_ids.emplace_back(i);
292
12
            partition_ids.emplace_back(_partitions[i]->id);
293
12
            tablet_ids.emplace_back(_tablet_ids[i]);
294
12
        }
295
24
    }
296
14
}
297
298
Status VRowDistribution::_filter_block_by_skip_and_where_clause(
299
4
        Block* block, const VExprContextSPtr& where_clause, RowPartTabletIds& row_part_tablet_id) {
300
    // TODO
301
    //SCOPED_RAW_TIMER(&_stat.where_clause_ns);
302
4
    ColumnPtr filter_column;
303
4
    RETURN_IF_ERROR(where_clause->execute(block, filter_column));
304
305
4
    auto& row_ids = row_part_tablet_id.row_ids;
306
4
    auto& partition_ids = row_part_tablet_id.partition_ids;
307
4
    auto& tablet_ids = row_part_tablet_id.tablet_ids;
308
4
    if (const auto* nullable_column = check_and_get_column<ColumnNullable>(*filter_column)) {
309
0
        auto rows = block->rows();
310
        // row count of a block should not exceed UINT32_MAX
311
0
        auto rows_uint32 = cast_set<uint32_t>(rows);
312
0
        for (uint32_t i = 0; i < rows_uint32; i++) {
313
0
            if (nullable_column->get_bool_inline(i) && !_skip[i]) {
314
0
                row_ids.emplace_back(i);
315
0
                partition_ids.emplace_back(_partitions[i]->id);
316
0
                tablet_ids.emplace_back(_tablet_ids[i]);
317
0
            }
318
0
        }
319
4
    } else if (const auto* const_column = check_and_get_column<ColumnConst>(*filter_column)) {
320
2
        bool ret = const_column->get_bool(0);
321
2
        if (!ret) {
322
2
            return Status::OK();
323
2
        }
324
        // should we optimize?
325
0
        _filter_block_by_skip(block, row_part_tablet_id);
326
2
    } else {
327
2
        const auto& filter = assert_cast<const ColumnUInt8&>(*filter_column).get_data();
328
2
        auto rows = block->rows();
329
        // row count of a block should not exceed UINT32_MAX
330
2
        auto rows_uint32 = cast_set<uint32_t>(rows);
331
8
        for (uint32_t i = 0; i < rows_uint32; i++) {
332
6
            if (filter[i] != 0 && !_skip[i]) {
333
4
                row_ids.emplace_back(i);
334
4
                partition_ids.emplace_back(_partitions[i]->id);
335
4
                tablet_ids.emplace_back(_tablet_ids[i]);
336
4
            }
337
6
        }
338
2
    }
339
340
2
    return Status::OK();
341
4
}
342
343
Status VRowDistribution::_filter_block(Block* block,
344
18
                                       std::vector<RowPartTabletIds>& row_part_tablet_ids) {
345
36
    for (int i = 0; i < _schema->indexes().size(); i++) {
346
18
        _get_tablet_ids(block, i, _tablet_ids);
347
18
        auto& where_clause = _schema->indexes()[i]->where_clause;
348
18
        if (where_clause != nullptr) {
349
4
            RETURN_IF_ERROR(_filter_block_by_skip_and_where_clause(block, where_clause,
350
4
                                                                   row_part_tablet_ids[i]));
351
14
        } else {
352
14
            _filter_block_by_skip(block, row_part_tablet_ids[i]);
353
14
        }
354
18
    }
355
18
    return Status::OK();
356
18
}
357
358
Status VRowDistribution::_generate_rows_distribution_for_non_auto_partition(
359
10
        Block* block, bool has_filtered_rows, std::vector<RowPartTabletIds>& row_part_tablet_ids) {
360
10
    int num_rows = cast_set<int>(block->rows());
361
362
10
    RETURN_IF_ERROR(_tablet_finder->find_tablets(_state, block, num_rows, _partitions,
363
10
                                                 _tablet_indexes, _skip));
364
10
    if (has_filtered_rows) {
365
0
        for (int i = 0; i < num_rows; i++) {
366
0
            _skip[i] = _skip[i] || _block_convertor->filter_map()[i];
367
0
        }
368
0
    }
369
10
    RETURN_IF_ERROR(_filter_block(block, row_part_tablet_ids));
370
10
    return Status::OK();
371
10
}
372
373
Status VRowDistribution::_deal_missing_map(const Block& input_block, Block* block,
374
                                           const std::vector<uint16_t>& partition_cols_idx,
375
4
                                           int64_t& rows_stat_val) {
376
    // for missing partition keys, calc the missing partition and save in _partitions_need_create
377
4
    auto [part_ctxs, part_exprs] = _get_partition_function();
378
4
    int part_col_num = cast_set<int>(part_exprs.size());
379
    // the two vectors are in column-first-order
380
4
    std::vector<std::vector<std::string>> col_strs;
381
4
    std::vector<const NullMap*> col_null_maps;
382
4
    col_strs.resize(part_col_num);
383
4
    col_null_maps.reserve(part_col_num);
384
385
4
    auto format_options = DataTypeSerDe::get_default_format_options();
386
4
    format_options.timezone = &_state->timezone_obj();
387
388
8
    for (int i = 0; i < part_col_num; ++i) {
389
4
        auto return_type = part_exprs[i]->data_type();
390
        // expose the data column. the return type would be nullable
391
4
        const auto& [range_left_col, col_const] =
392
4
                unpack_if_const(block->get_by_position(partition_cols_idx[i]).column);
393
4
        if (range_left_col->is_nullable()) {
394
0
            col_null_maps.push_back(&(
395
0
                    assert_cast<const ColumnNullable*>(range_left_col.get())->get_null_map_data()));
396
4
        } else {
397
4
            col_null_maps.push_back(nullptr);
398
4
        }
399
8
        for (auto row : _missing_map) {
400
8
            col_strs[i].push_back(return_type->to_string(
401
8
                    *range_left_col, index_check_const(row, col_const), format_options));
402
8
        }
403
4
    }
404
405
    // calc the end value and save them. in the end of sending, we will create partitions for them and deal them.
406
    // NOTE: must save old batching stats before calling _save_missing_values(),
407
    // because _save_missing_values() will update _batching_rows internally.
408
4
    size_t old_bt_rows = _batching_rows;
409
4
    size_t old_bt_bytes = _batching_bytes;
410
411
4
    RETURN_IF_ERROR(_save_missing_values(input_block, col_strs, part_col_num, block, _missing_map,
412
4
                                         col_null_maps));
413
414
4
    size_t new_bt_rows = _batching_block->rows();
415
4
    size_t new_bt_bytes = _batching_block->bytes();
416
4
    rows_stat_val -= new_bt_rows - old_bt_rows;
417
4
    _state->update_num_rows_load_total(old_bt_rows - new_bt_rows);
418
4
    _state->update_num_bytes_load_total(old_bt_bytes - new_bt_bytes);
419
4
    DorisMetrics::instance()->load_rows->increment(old_bt_rows - new_bt_rows);
420
4
    DorisMetrics::instance()->load_bytes->increment(old_bt_bytes - new_bt_bytes);
421
422
4
    return Status::OK();
423
4
}
424
425
Status VRowDistribution::_generate_rows_distribution_for_auto_partition(
426
        const Block& input_block, Block* block, const std::vector<uint16_t>& partition_cols_idx,
427
        bool has_filtered_rows, std::vector<RowPartTabletIds>& row_part_tablet_ids,
428
4
        int64_t& rows_stat_val) {
429
4
    int num_rows = cast_set<int>(block->rows());
430
4
    std::vector<uint16_t> partition_keys = _vpartition->get_partition_keys();
431
432
4
    auto& partition_col = block->get_by_position(partition_keys[0]);
433
4
    _missing_map.clear();
434
4
    _missing_map.reserve(partition_col.column->size());
435
436
4
    RETURN_IF_ERROR(_tablet_finder->find_tablets(_state, block, num_rows, _partitions,
437
4
                                                 _tablet_indexes, _skip, &_missing_map));
438
439
    // the missing vals for auto partition are also skipped.
440
4
    if (has_filtered_rows) {
441
0
        for (int i = 0; i < num_rows; i++) {
442
0
            _skip[i] = _skip[i] || _block_convertor->filter_map()[i];
443
0
        }
444
0
    }
445
4
    RETURN_IF_ERROR(_filter_block(block, row_part_tablet_ids));
446
447
4
    if (!_missing_map.empty()) {
448
4
        RETURN_IF_ERROR(_deal_missing_map(input_block, block, partition_cols_idx,
449
4
                                          rows_stat_val)); // send input block to save
450
4
    }
451
4
    return Status::OK();
452
4
}
453
454
Status VRowDistribution::_generate_rows_distribution_for_auto_overwrite(
455
        const Block& input_block, Block* block, const std::vector<uint16_t>& partition_cols_idx,
456
        bool has_filtered_rows, std::vector<RowPartTabletIds>& row_part_tablet_ids,
457
4
        int64_t& rows_stat_val) {
458
4
    int num_rows = cast_set<int>(block->rows());
459
460
    // for non-auto-partition situation, goes into two 'else' branch. just find the origin partitions, replace them by rpc,
461
    //  and find the new partitions to use.
462
    // for auto-partition's, find and save origins in _partitions and replace them. at meanwhile save the missing values for auto
463
    //  partition. then we find partition again to get replaced partitions in _partitions. this time _missing_map is ignored cuz
464
    //  we already saved missing values.
465
4
    if (_vpartition->is_auto_partition() &&
466
4
        _state->query_options().enable_auto_create_when_overwrite) {
467
        // allow auto create partition for missing rows.
468
0
        std::vector<uint16_t> partition_keys = _vpartition->get_partition_keys();
469
0
        auto partition_col = block->get_by_position(partition_keys[0]);
470
0
        _missing_map.clear();
471
0
        _missing_map.reserve(partition_col.column->size());
472
473
0
        RETURN_IF_ERROR(_tablet_finder->find_tablets(_state, block, num_rows, _partitions,
474
0
                                                     _tablet_indexes, _skip, &_missing_map));
475
476
        // allow and really need to create during auto-detect-overwriting.
477
0
        if (!_missing_map.empty()) {
478
0
            RETURN_IF_ERROR(
479
0
                    _deal_missing_map(input_block, block, partition_cols_idx, rows_stat_val));
480
0
        }
481
4
    } else {
482
4
        RETURN_IF_ERROR(_tablet_finder->find_tablets(_state, block, num_rows, _partitions,
483
4
                                                     _tablet_indexes, _skip));
484
4
    }
485
4
    RETURN_IF_ERROR(_replace_overwriting_partition());
486
487
    // regenerate locations for new partitions & tablets
488
4
    _reset_find_tablets(num_rows);
489
4
    if (_vpartition->is_auto_partition() &&
490
4
        _state->query_options().enable_auto_create_when_overwrite) {
491
        // here _missing_map is just a placeholder
492
0
        RETURN_IF_ERROR(_tablet_finder->find_tablets(_state, block, num_rows, _partitions,
493
0
                                                     _tablet_indexes, _skip, &_missing_map));
494
0
        if (VLOG_TRACE_IS_ON) {
495
0
            std::string tmp;
496
0
            for (auto v : _missing_map) {
497
0
                tmp += std::to_string(v).append(", ");
498
0
            }
499
0
            VLOG_TRACE << "Trace missing map of " << this << ':' << tmp;
500
0
        }
501
4
    } else {
502
4
        RETURN_IF_ERROR(_tablet_finder->find_tablets(_state, block, num_rows, _partitions,
503
4
                                                     _tablet_indexes, _skip));
504
4
    }
505
4
    if (has_filtered_rows) {
506
0
        for (int i = 0; i < num_rows; i++) {
507
0
            _skip[i] = _skip[i] || _block_convertor->filter_map()[i];
508
0
        }
509
0
    }
510
4
    RETURN_IF_ERROR(_filter_block(block, row_part_tablet_ids));
511
4
    return Status::OK();
512
4
}
513
514
void VRowDistribution::_reset_row_part_tablet_ids(
515
18
        std::vector<RowPartTabletIds>& row_part_tablet_ids, int64_t rows) {
516
18
    row_part_tablet_ids.resize(_schema->indexes().size());
517
18
    for (auto& row_part_tablet_id : row_part_tablet_ids) {
518
18
        auto& row_ids = row_part_tablet_id.row_ids;
519
18
        auto& partition_ids = row_part_tablet_id.partition_ids;
520
18
        auto& tablet_ids = row_part_tablet_id.tablet_ids;
521
522
18
        row_ids.clear();
523
18
        partition_ids.clear();
524
18
        tablet_ids.clear();
525
        // This is important for performance.
526
18
        row_ids.reserve(rows);
527
18
        partition_ids.reserve(rows);
528
18
        tablet_ids.reserve(rows);
529
18
    }
530
18
}
531
532
Status VRowDistribution::generate_rows_distribution(
533
        Block& input_block, std::shared_ptr<Block>& block,
534
18
        std::vector<RowPartTabletIds>& row_part_tablet_ids, int64_t& rows_stat_val) {
535
18
    auto input_rows = input_block.rows();
536
18
    _reset_row_part_tablet_ids(row_part_tablet_ids, input_rows);
537
538
    // we store the batching block with value of `input_block`. so just do all of these again.
539
18
    bool has_filtered_rows = false;
540
18
    RETURN_IF_ERROR(_block_convertor->validate_and_convert_block(
541
18
            _state, &input_block, block, *_vec_output_expr_ctxs, input_rows, has_filtered_rows));
542
543
    // batching block rows which need new partitions. deal together at finish.
544
18
    if (!_batching_block) [[unlikely]] {
545
16
        std::unique_ptr<Block> tmp_block = input_block.create_same_struct_block(0);
546
16
        _batching_block = MutableBlock::create_unique(std::move(*tmp_block));
547
16
    }
548
549
18
    auto num_rows = block->rows();
550
18
    _reset_find_tablets(num_rows);
551
552
    // if there's projection of partition calc, we need to calc it first.
553
18
    auto [part_ctxs, part_funcs] = _get_partition_function();
554
18
    std::vector<uint16_t> partition_cols_idx;
555
18
    if (_vpartition->is_projection_partition()) {
556
        // calc the start value of missing partition ranges.
557
4
        auto func_size = part_funcs.size();
558
8
        for (int i = 0; i < func_size; ++i) {
559
4
            int result_idx = -1;
560
            // we just calc left range here. leave right to FE to avoid dup calc.
561
4
            RETURN_IF_ERROR(part_funcs[i]->execute(part_ctxs[i].get(), block.get(), &result_idx));
562
563
4
            VLOG_DEBUG << "Partition-calculated block:\n" << block->dump_data(0, 1);
564
4
            DCHECK(result_idx != -1);
565
566
4
            partition_cols_idx.push_back(cast_set<uint16_t>(result_idx));
567
4
        }
568
569
        // change the column to compare to transformed.
570
4
        _vpartition->set_transformed_slots(partition_cols_idx);
571
4
    }
572
573
18
    Status st = Status::OK();
574
18
    if (_vpartition->is_auto_detect_overwrite() && !_deal_batched) {
575
        // when overwrite, no auto create partition allowed.
576
4
        st = _generate_rows_distribution_for_auto_overwrite(input_block, block.get(),
577
4
                                                            partition_cols_idx, has_filtered_rows,
578
4
                                                            row_part_tablet_ids, rows_stat_val);
579
14
    } else if (_vpartition->is_auto_partition() && !_deal_batched) {
580
4
        st = _generate_rows_distribution_for_auto_partition(input_block, block.get(),
581
4
                                                            partition_cols_idx, has_filtered_rows,
582
4
                                                            row_part_tablet_ids, rows_stat_val);
583
10
    } else { // not auto partition
584
10
        st = _generate_rows_distribution_for_non_auto_partition(block.get(), has_filtered_rows,
585
10
                                                                row_part_tablet_ids);
586
10
    }
587
588
18
    return st;
589
18
}
590
591
// reuse vars for find_tablets
592
22
void VRowDistribution::_reset_find_tablets(int64_t rows) {
593
22
    _tablet_finder->filter_bitmap().Reset(rows);
594
22
    _partitions.assign(rows, nullptr);
595
22
    _skip.assign(rows, false);
596
22
    _tablet_indexes.assign(rows, 0);
597
22
}
598
599
} // namespace doris