Coverage Report

Created: 2026-04-10 12:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/load/delta_writer/push_handler.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 "load/delta_writer/push_handler.h"
19
20
#include <fmt/core.h>
21
#include <gen_cpp/AgentService_types.h>
22
#include <gen_cpp/Descriptors_types.h>
23
#include <gen_cpp/MasterService_types.h>
24
#include <gen_cpp/PaloInternalService_types.h>
25
#include <gen_cpp/PlanNodes_types.h>
26
#include <gen_cpp/Types_types.h>
27
#include <gen_cpp/olap_file.pb.h>
28
#include <gen_cpp/types.pb.h>
29
#include <glog/logging.h>
30
31
#include <algorithm>
32
#include <iostream>
33
#include <mutex>
34
#include <new>
35
#include <queue>
36
#include <shared_mutex>
37
#include <type_traits>
38
39
#include "common/compiler_util.h" // IWYU pragma: keep
40
#include "common/config.h"
41
#include "common/logging.h"
42
#include "common/status.h"
43
#include "core/block/block.h"
44
#include "core/block/column_with_type_and_name.h"
45
#include "core/data_type/data_type_bitmap.h"
46
#include "core/data_type/data_type_factory.hpp"
47
#include "core/data_type/data_type_nullable.h"
48
#include "exprs/function/function_helpers.h"
49
#include "exprs/function/simple_function_factory.h"
50
#include "exprs/vexpr_context.h"
51
#include "format/parquet/vparquet_reader.h"
52
#include "io/hdfs_builder.h"
53
#include "runtime/descriptors.h"
54
#include "runtime/exec_env.h"
55
#include "storage/compaction/cumulative_compaction_time_series_policy.h"
56
#include "storage/delete/delete_handler.h"
57
#include "storage/olap_define.h"
58
#include "storage/rowset/pending_rowset_helper.h"
59
#include "storage/rowset/rowset_writer.h"
60
#include "storage/rowset/rowset_writer_context.h"
61
#include "storage/storage_engine.h"
62
#include "storage/tablet/tablet.h"
63
#include "storage/tablet/tablet_manager.h"
64
#include "storage/tablet/tablet_schema.h"
65
#include "storage/txn/txn_manager.h"
66
#include "util/time.h"
67
68
namespace doris {
69
using namespace ErrorCode;
70
71
// Process push command, the main logical is as follows:
72
//    a. related tablets not exist:
73
//        current table isn't in schemachange state, only push for current
74
//        tablet
75
//    b. related tablets exist
76
//       I.  current tablet is old table (cur.creation_time <
77
//       related.creation_time):
78
//           push for current table and than convert data for related tables
79
//       II. current table is new table:
80
//           this usually means schema change is over,
81
//           clear schema change info in both current tablet and related
82
//           tablets, finally we will only push for current tablets. this is
83
//           very useful in rollup action.
84
Status PushHandler::process_streaming_ingestion(TabletSharedPtr tablet, const TPushReq& request,
85
                                                PushType push_type,
86
22
                                                std::vector<TTabletInfo>* tablet_info_vec) {
87
22
    LOG(INFO) << "begin to realtime push. tablet=" << tablet->tablet_id()
88
22
              << ", transaction_id=" << request.transaction_id;
89
90
22
    Status res = Status::OK();
91
22
    _request = request;
92
93
22
    RETURN_IF_ERROR(DescriptorTbl::create(&_pool, _request.desc_tbl, &_desc_tbl));
94
95
22
    res = _do_streaming_ingestion(tablet, request, push_type, tablet_info_vec);
96
97
22
    if (res.ok()) {
98
22
        if (tablet_info_vec != nullptr) {
99
22
            TTabletInfo tablet_info;
100
22
            tablet_info.tablet_id = tablet->tablet_id();
101
22
            tablet_info.schema_hash = tablet->schema_hash();
102
22
            RETURN_IF_ERROR(_engine.tablet_manager()->report_tablet_info(&tablet_info));
103
22
            tablet_info_vec->push_back(tablet_info);
104
22
        }
105
22
        LOG(INFO) << "process realtime push successfully. "
106
22
                  << "tablet=" << tablet->tablet_id() << ", partition_id=" << request.partition_id
107
22
                  << ", transaction_id=" << request.transaction_id;
108
22
    }
109
110
22
    return res;
111
22
}
112
113
Status PushHandler::_do_streaming_ingestion(TabletSharedPtr tablet, const TPushReq& request,
114
                                            PushType push_type,
115
22
                                            std::vector<TTabletInfo>* tablet_info_vec) {
116
    // add transaction in engine, then check sc status
117
    // lock, prevent sc handler checking transaction concurrently
118
22
    if (tablet == nullptr) {
119
0
        return Status::Error<TABLE_NOT_FOUND>(
120
0
                "PushHandler::_do_streaming_ingestion input tablet is nullptr");
121
0
    }
122
123
22
    PUniqueId load_id;
124
22
    load_id.set_hi(0);
125
22
    load_id.set_lo(0);
126
127
22
    RETURN_IF_ERROR(
128
22
            tablet->prepare_txn(request.partition_id, request.transaction_id, load_id, false));
129
130
    // not call validate request here, because realtime load does not
131
    // contain version info
132
133
22
    Status res;
134
    // check delete condition if push for delete
135
22
    std::queue<DeletePredicatePB> del_preds;
136
22
    if (push_type == PushType::PUSH_FOR_DELETE) {
137
22
        DeletePredicatePB del_pred;
138
22
        TabletSchema tablet_schema;
139
22
        tablet_schema.copy_from(*tablet->tablet_schema());
140
22
        if (!request.columns_desc.empty() && request.columns_desc[0].col_unique_id >= 0) {
141
22
            tablet_schema.clear_columns();
142
64
            for (const auto& column_desc : request.columns_desc) {
143
64
                tablet_schema.append_column(TabletColumn(column_desc));
144
64
            }
145
22
        }
146
22
        res = DeleteHandler::generate_delete_predicate(tablet_schema, request.delete_conditions,
147
22
                                                       &del_pred);
148
22
        del_preds.push(del_pred);
149
22
        if (!res.ok()) {
150
0
            LOG(WARNING) << "fail to generate delete condition. res=" << res
151
0
                         << ", tablet=" << tablet->tablet_id();
152
0
            return res;
153
0
        }
154
22
    }
155
156
22
    int32_t max_version_config = tablet->max_version_config();
157
    // check if version number exceed limit
158
22
    if (tablet->exceed_version_limit(max_version_config)) {
159
0
        return Status::Status::Error<TOO_MANY_VERSION>(
160
0
                "failed to push data. version count: {}, exceed limit: {}, tablet: {}. Please "
161
0
                "reduce the frequency of loading data or adjust the max_tablet_version_num or "
162
0
                "time_series_max_tablet_version_num in "
163
0
                "be.conf to a larger value.",
164
0
                tablet->version_count(), max_version_config, tablet->tablet_id());
165
0
    }
166
167
22
    auto version_count = tablet->version_count() + tablet->stale_version_count();
168
22
    if (tablet->avg_rs_meta_serialize_size() * version_count >
169
22
        config::tablet_meta_serialize_size_limit) {
170
0
        return Status::Error<TOO_MANY_VERSION>(
171
0
                "failed to init rowset builder. meta serialize size : {}, exceed limit: {}, "
172
0
                "tablet: {}. Please reduce the frequency of loading data or adjust the "
173
0
                "max_tablet_version_num in be.conf to a larger value.",
174
0
                tablet->avg_rs_meta_serialize_size() * version_count,
175
0
                config::tablet_meta_serialize_size_limit, tablet->tablet_id());
176
0
    }
177
178
22
    auto tablet_schema = std::make_shared<TabletSchema>();
179
22
    tablet_schema->copy_from(*tablet->tablet_schema());
180
22
    if (!request.columns_desc.empty() && request.columns_desc[0].col_unique_id >= 0) {
181
22
        tablet_schema->clear_columns();
182
        // TODO(lhy) handle variant
183
64
        for (const auto& column_desc : request.columns_desc) {
184
64
            tablet_schema->append_column(TabletColumn(column_desc));
185
64
        }
186
22
    }
187
22
    RowsetSharedPtr rowset_to_add;
188
    // writes
189
22
    res = _convert_v2(tablet, &rowset_to_add, tablet_schema, push_type);
190
22
    if (!res.ok()) {
191
0
        LOG(WARNING) << "fail to convert tmp file when realtime push. res=" << res
192
0
                     << ", failed to process realtime push."
193
0
                     << ", tablet=" << tablet->tablet_id()
194
0
                     << ", transaction_id=" << request.transaction_id;
195
196
0
        Status rollback_status = _engine.txn_manager()->rollback_txn(request.partition_id, *tablet,
197
0
                                                                     request.transaction_id);
198
        // has to check rollback status to ensure not delete a committed rowset
199
0
        if (rollback_status.ok()) {
200
0
            _engine.add_unused_rowset(rowset_to_add);
201
0
        }
202
0
        return res;
203
0
    }
204
205
    // add pending data to tablet
206
207
22
    if (push_type == PushType::PUSH_FOR_DELETE) {
208
22
        rowset_to_add->rowset_meta()->set_delete_predicate(std::move(del_preds.front()));
209
22
        del_preds.pop();
210
22
    }
211
    // Transfer ownership of `PendingRowsetGuard` to `TxnManager`
212
22
    Status commit_status = _engine.txn_manager()->commit_txn(
213
22
            request.partition_id, *tablet, request.transaction_id, load_id, rowset_to_add,
214
22
            std::move(_pending_rs_guard), false);
215
22
    if (!commit_status.ok() && !commit_status.is<PUSH_TRANSACTION_ALREADY_EXIST>()) {
216
0
        res = std::move(commit_status);
217
0
    }
218
22
    return res;
219
22
}
220
221
Status PushHandler::_convert_v2(TabletSharedPtr cur_tablet, RowsetSharedPtr* cur_rowset,
222
22
                                TabletSchemaSPtr tablet_schema, PushType push_type) {
223
22
    Status st = Status::OK();
224
22
    uint32_t num_rows = 0;
225
22
    PUniqueId load_id;
226
22
    load_id.set_hi(0);
227
22
    load_id.set_lo(0);
228
229
22
    do {
230
22
        VLOG_NOTICE << "start to convert delta file.";
231
232
        // 1. init RowsetBuilder of cur_tablet for current push
233
22
        VLOG_NOTICE << "init rowset builder. tablet=" << cur_tablet->tablet_id()
234
0
                    << ", block_row_size=" << tablet_schema->num_rows_per_row_block();
235
        // although the spark load output files are fully sorted,
236
        // but it depends on thirparty implementation, so we conservatively
237
        // set this value to OVERLAP_UNKNOWN
238
22
        RowsetWriterContext context;
239
22
        context.txn_id = _request.transaction_id;
240
22
        context.load_id = load_id;
241
22
        context.rowset_state = PREPARED;
242
22
        context.segments_overlap = OVERLAP_UNKNOWN;
243
22
        context.tablet_schema = tablet_schema;
244
22
        context.newest_write_timestamp = UnixSeconds();
245
22
        auto rowset_writer = DORIS_TRY(cur_tablet->create_rowset_writer(context, false));
246
22
        _pending_rs_guard = _engine.pending_local_rowsets().add(context.rowset_id);
247
248
        // 2. Init PushBrokerReader to read broker file if exist,
249
        //    in case of empty push this will be skipped.
250
22
        std::string path;
251
        // If it is push delete, the broker_scan_range is not set.
252
22
        if (push_type == PushType::PUSH_NORMAL_V2) {
253
0
            path = _request.broker_scan_range.ranges[0].path;
254
0
            LOG(INFO) << "tablet=" << cur_tablet->tablet_id() << ", file path=" << path
255
0
                      << ", file size=" << _request.broker_scan_range.ranges[0].file_size;
256
0
        }
257
        // For push load, this tablet maybe not need push data, so that the path maybe empty
258
22
        if (!path.empty()) {
259
            // init Reader
260
0
            std::unique_ptr<PushBrokerReader> reader =
261
0
                    PushBrokerReader::create_unique(_request.broker_scan_range, _request.desc_tbl);
262
0
            st = reader->init();
263
0
            if (reader == nullptr || !st.ok()) {
264
0
                st = Status::Error<PUSH_INIT_ERROR>("fail to init reader. st={}, tablet={}", st,
265
0
                                                    cur_tablet->tablet_id());
266
0
                break;
267
0
            }
268
269
            // 3. Init Block
270
0
            Block block;
271
272
            // 4. Read data from broker and write into cur_tablet
273
0
            VLOG_NOTICE << "start to convert etl file to delta.";
274
0
            while (!reader->eof()) {
275
0
                st = reader->next(&block);
276
0
                if (!st.ok()) {
277
0
                    LOG(WARNING) << "read next row failed."
278
0
                                 << " st=" << st << " read_rows=" << num_rows;
279
0
                    break;
280
0
                } else {
281
0
                    if (reader->eof()) {
282
0
                        break;
283
0
                    }
284
0
                    if (!(st = rowset_writer->add_block(&block)).ok()) {
285
0
                        LOG(WARNING) << "fail to attach block to rowset_writer. "
286
0
                                     << "st=" << st << ", tablet=" << cur_tablet->tablet_id()
287
0
                                     << ", read_rows=" << num_rows;
288
0
                        break;
289
0
                    }
290
0
                    num_rows++;
291
0
                }
292
0
            }
293
294
0
            reader->print_profile();
295
0
            RETURN_IF_ERROR(reader->close());
296
0
        }
297
298
22
        if (!st.ok()) {
299
0
            break;
300
0
        }
301
302
22
        if (!(st = rowset_writer->flush()).ok()) {
303
0
            LOG(WARNING) << "failed to finalize writer";
304
0
            break;
305
0
        }
306
307
22
        if (!(st = rowset_writer->build(*cur_rowset)).ok()) {
308
0
            LOG(WARNING) << "failed to build rowset";
309
0
            break;
310
0
        }
311
312
22
        _write_bytes += (*cur_rowset)->data_disk_size();
313
22
        _write_rows += (*cur_rowset)->num_rows();
314
22
    } while (false);
315
316
22
    VLOG_TRACE << "convert delta file end. st=" << st << ", tablet=" << cur_tablet->tablet_id()
317
0
               << ", processed_rows" << num_rows;
318
22
    return st;
319
22
}
320
321
PushBrokerReader::PushBrokerReader(const TBrokerScanRange& t_scan_range,
322
                                   const TDescriptorTable& t_desc_tbl)
323
0
        : _ready(false),
324
0
          _eof(false),
325
0
          _next_range(0),
326
0
          _t_desc_tbl(t_desc_tbl),
327
0
          _cur_reader_eof(false),
328
0
          _params(t_scan_range.params),
329
0
          _ranges(t_scan_range.ranges) {
330
    // change broker params to file params
331
0
    if (_ranges.empty()) {
332
0
        return;
333
0
    }
334
0
    _file_params.format_type = _ranges[0].format_type;
335
0
    _file_params.src_tuple_id = _params.src_tuple_id;
336
0
    _file_params.dest_tuple_id = _params.dest_tuple_id;
337
0
    _file_params.num_of_columns_from_file = _ranges[0].num_of_columns_from_file;
338
0
    _file_params.properties = _params.properties;
339
0
    _file_params.expr_of_dest_slot = _params.expr_of_dest_slot;
340
0
    _file_params.dest_sid_to_src_sid_without_trans = _params.dest_sid_to_src_sid_without_trans;
341
0
    _file_params.strict_mode = _params.strict_mode;
342
0
    if (_ranges[0].file_type == TFileType::FILE_HDFS) {
343
0
        _file_params.hdfs_params = parse_properties(_params.properties);
344
0
    } else {
345
0
        _file_params.__isset.broker_addresses = true;
346
0
        _file_params.broker_addresses = t_scan_range.broker_addresses;
347
0
    }
348
349
0
    for (const auto& range : _ranges) {
350
0
        TFileRangeDesc file_range;
351
        // TODO(cmy): in previous implementation, the file_type is set in _file_params
352
        // and it use _ranges[0].file_type.
353
        // Later, this field is moved to TFileRangeDesc, but here we still only use _ranges[0]'s
354
        // file_type.
355
        // Because I don't know if other range has this field, so just keep it same as before.
356
0
        file_range.__set_file_type(_ranges[0].file_type);
357
0
        file_range.__set_load_id(range.load_id);
358
0
        file_range.__set_path(range.path);
359
0
        file_range.__set_start_offset(range.start_offset);
360
0
        file_range.__set_size(range.size);
361
0
        file_range.__set_file_size(range.file_size);
362
0
        file_range.__set_columns_from_path(range.columns_from_path);
363
364
0
        _file_ranges.push_back(file_range);
365
0
    }
366
0
}
367
368
0
Status PushBrokerReader::init() {
369
    // init runtime state, runtime profile, counter
370
0
    TUniqueId dummy_id;
371
0
    dummy_id.hi = 0;
372
0
    dummy_id.lo = 0;
373
0
    TPlanFragmentExecParams params;
374
0
    params.fragment_instance_id = dummy_id;
375
0
    params.query_id = dummy_id;
376
0
    TQueryOptions query_options;
377
0
    TQueryGlobals query_globals;
378
0
    std::shared_ptr<MemTrackerLimiter> tracker = MemTrackerLimiter::create_shared(
379
0
            MemTrackerLimiter::Type::LOAD,
380
0
            fmt::format("PushBrokerReader:dummy_id={}", print_id(dummy_id)));
381
0
    _runtime_state = RuntimeState::create_unique(params, query_options, query_globals,
382
0
                                                 ExecEnv::GetInstance(), nullptr, tracker);
383
0
    DescriptorTbl* desc_tbl = nullptr;
384
0
    Status status = DescriptorTbl::create(_runtime_state->obj_pool(), _t_desc_tbl, &desc_tbl);
385
0
    if (UNLIKELY(!status.ok())) {
386
0
        return Status::Error<PUSH_INIT_ERROR>("Failed to create descriptor table, msg: {}", status);
387
0
    }
388
0
    _runtime_state->set_desc_tbl(desc_tbl);
389
0
    _runtime_profile = _runtime_state->runtime_profile();
390
0
    _runtime_profile->set_name("PushBrokerReader");
391
392
0
    _file_cache_statistics.reset(new io::FileCacheStatistics());
393
0
    _file_reader_stats.reset(new io::FileReaderStats());
394
0
    _io_ctx.reset(new io::IOContext());
395
0
    _io_ctx->file_cache_stats = _file_cache_statistics.get();
396
0
    _io_ctx->file_reader_stats = _file_reader_stats.get();
397
0
    _io_ctx->query_id = &_runtime_state->query_id();
398
399
0
    auto slot_descs = desc_tbl->get_tuple_descriptor(0)->slots();
400
0
    uint32_t idx = 0;
401
0
    for (auto& slot_desc : slot_descs) {
402
0
        _all_col_names.push_back(to_lower((slot_desc->col_name())));
403
0
        _col_name_to_block_idx.insert({to_lower(slot_desc->col_name()), idx++});
404
0
    }
405
406
0
    RETURN_IF_ERROR(_init_expr_ctxes());
407
408
0
    _ready = true;
409
0
    return Status::OK();
410
0
}
411
412
0
Status PushBrokerReader::next(Block* block) {
413
0
    if (!_ready || block == nullptr) {
414
0
        return Status::Error<INVALID_ARGUMENT>("PushBrokerReader not ready or block is nullptr");
415
0
    }
416
0
    if (_cur_reader == nullptr || _cur_reader_eof) {
417
0
        RETURN_IF_ERROR(_get_next_reader());
418
0
        if (_eof) {
419
0
            return Status::OK();
420
0
        }
421
0
    }
422
0
    RETURN_IF_ERROR(_init_src_block());
423
0
    size_t read_rows = 0;
424
0
    RETURN_IF_ERROR(_cur_reader->get_next_block(_src_block_ptr, &read_rows, &_cur_reader_eof));
425
0
    if (read_rows > 0) {
426
0
        RETURN_IF_ERROR(_cast_to_input_block());
427
0
        RETURN_IF_ERROR(_convert_to_output_block(block));
428
0
    }
429
0
    return Status::OK();
430
0
}
431
432
0
Status PushBrokerReader::close() {
433
0
    _ready = false;
434
0
    return Status::OK();
435
0
}
436
437
0
Status PushBrokerReader::_init_src_block() {
438
0
    _src_block.clear();
439
0
    int idx = 0;
440
0
    for (auto& slot : _src_slot_descs) {
441
0
        DataTypePtr data_type;
442
0
        auto it = _name_to_col_type.find(slot->col_name());
443
0
        if (it == _name_to_col_type.end()) {
444
            // not exist in file, using type from _input_tuple_desc
445
0
            data_type = slot->get_data_type_ptr();
446
0
        } else {
447
0
            data_type = it->second;
448
0
        }
449
0
        if (data_type == nullptr) {
450
0
            return Status::NotSupported("Not support data type {} for column {}",
451
0
                                        it == _name_to_col_type.end() ? slot->type()->get_name()
452
0
                                                                      : it->second->get_name(),
453
0
                                        slot->col_name());
454
0
        }
455
0
        MutableColumnPtr data_column = data_type->create_column();
456
0
        _src_block.insert(
457
0
                ColumnWithTypeAndName(std::move(data_column), data_type, slot->col_name()));
458
0
        _src_block_name_to_idx.emplace(slot->col_name(), idx++);
459
0
    }
460
0
    _src_block_ptr = &_src_block;
461
0
    return Status::OK();
462
0
}
463
464
0
Status PushBrokerReader::_cast_to_input_block() {
465
0
    uint32_t idx = 0;
466
0
    for (auto& slot_desc : _src_slot_descs) {
467
0
        if (_name_to_col_type.find(slot_desc->col_name()) == _name_to_col_type.end()) {
468
0
            continue;
469
0
        }
470
0
        if (slot_desc->type()->get_primitive_type() == PrimitiveType::TYPE_VARIANT) {
471
0
            continue;
472
0
        }
473
        // remove nullable here, let the get_function decide whether nullable
474
0
        auto return_type = slot_desc->get_data_type_ptr();
475
0
        idx = _src_block_name_to_idx[slot_desc->col_name()];
476
0
        auto& arg = _src_block_ptr->get_by_position(idx);
477
        // bitmap convert:src -> to_base64 -> bitmap_from_base64
478
0
        if (slot_desc->type()->get_primitive_type() == TYPE_BITMAP) {
479
0
            auto base64_return_type = DataTypeFactory::instance().create_data_type(
480
0
                    PrimitiveType::TYPE_STRING, slot_desc->is_nullable());
481
0
            auto func_to_base64 = SimpleFunctionFactory::instance().get_function(
482
0
                    "to_base64", {arg}, base64_return_type);
483
0
            RETURN_IF_ERROR(func_to_base64->execute(nullptr, *_src_block_ptr, {idx}, idx,
484
0
                                                    arg.column->size()));
485
0
            _src_block_ptr->get_by_position(idx).type = std::move(base64_return_type);
486
0
            auto& arg_base64 = _src_block_ptr->get_by_position(idx);
487
0
            auto func_bitmap_from_base64 = SimpleFunctionFactory::instance().get_function(
488
0
                    "bitmap_from_base64", {arg_base64}, return_type);
489
0
            RETURN_IF_ERROR(func_bitmap_from_base64->execute(nullptr, *_src_block_ptr, {idx}, idx,
490
0
                                                             arg_base64.column->size()));
491
0
            _src_block_ptr->get_by_position(idx).type = std::move(return_type);
492
0
        } else {
493
0
            ColumnsWithTypeAndName arguments {
494
0
                    arg,
495
0
                    {DataTypeString().create_column_const(
496
0
                             arg.column->size(),
497
0
                             Field::create_field<TYPE_STRING>(
498
0
                                     is_decimal(return_type->get_primitive_type())
499
0
                                             ? "Decimal"
500
0
                                             : remove_nullable(return_type)->get_family_name())),
501
0
                     std::make_shared<DataTypeString>(), ""}};
502
0
            auto func_cast =
503
0
                    SimpleFunctionFactory::instance().get_function("CAST", arguments, return_type);
504
0
            RETURN_IF_ERROR(
505
0
                    func_cast->execute(nullptr, *_src_block_ptr, {idx}, idx, arg.column->size()));
506
0
            _src_block_ptr->get_by_position(idx).type = std::move(return_type);
507
0
        }
508
0
    }
509
0
    return Status::OK();
510
0
}
511
512
0
Status PushBrokerReader::_convert_to_output_block(Block* block) {
513
0
    block->clear();
514
515
0
    int ctx_idx = 0;
516
0
    size_t rows = _src_block.rows();
517
0
    auto filter_column = ColumnUInt8::create(rows, 1);
518
519
0
    for (auto* slot_desc : _dest_tuple_desc->slots()) {
520
0
        int dest_index = ctx_idx++;
521
0
        ColumnPtr column_ptr;
522
523
0
        auto& ctx = _dest_expr_ctxs[dest_index];
524
        // PT1 => dest primitive type
525
0
        RETURN_IF_ERROR(ctx->execute(&_src_block, column_ptr));
526
        // column_ptr maybe a ColumnConst, convert it to a normal column
527
0
        column_ptr = column_ptr->convert_to_full_column_if_const();
528
0
        DCHECK(column_ptr);
529
530
        // because of src_slot_desc is always be nullable, so the column_ptr after do dest_expr
531
        // is likely to be nullable
532
0
        if (LIKELY(column_ptr->is_nullable())) {
533
0
            if (!slot_desc->is_nullable()) {
534
0
                column_ptr = remove_nullable(column_ptr);
535
0
            }
536
0
        } else if (slot_desc->is_nullable()) {
537
0
            column_ptr = make_nullable(column_ptr);
538
0
        }
539
0
        block->insert(dest_index, ColumnWithTypeAndName(column_ptr, slot_desc->get_data_type_ptr(),
540
0
                                                        slot_desc->col_name()));
541
0
    }
542
0
    _src_block.clear();
543
544
0
    size_t dest_size = block->columns();
545
0
    block->insert(ColumnWithTypeAndName(std::move(filter_column), std::make_shared<DataTypeUInt8>(),
546
0
                                        "filter column"));
547
0
    RETURN_IF_ERROR(Block::filter_block(block, dest_size, dest_size));
548
0
    return Status::OK();
549
0
}
550
551
0
void PushBrokerReader::print_profile() {
552
0
    std::stringstream ss;
553
0
    _runtime_profile->pretty_print(&ss);
554
0
    LOG(INFO) << ss.str();
555
0
}
556
557
0
Status PushBrokerReader::_init_expr_ctxes() {
558
    // Construct _src_slot_descs
559
0
    const TupleDescriptor* src_tuple_desc =
560
0
            _runtime_state->desc_tbl().get_tuple_descriptor(_params.src_tuple_id);
561
0
    if (src_tuple_desc == nullptr) {
562
0
        return Status::InternalError("Unknown source tuple descriptor, tuple_id={}",
563
0
                                     _params.src_tuple_id);
564
0
    }
565
566
0
    std::map<SlotId, SlotDescriptor*> src_slot_desc_map;
567
0
    std::unordered_map<SlotDescriptor*, int> src_slot_desc_to_index {};
568
0
    for (size_t i = 0, len = src_tuple_desc->slots().size(); i < len; ++i) {
569
0
        auto* slot_desc = src_tuple_desc->slots()[i];
570
0
        src_slot_desc_to_index.emplace(slot_desc, i);
571
0
        src_slot_desc_map.emplace(slot_desc->id(), slot_desc);
572
0
    }
573
0
    for (auto slot_id : _params.src_slot_ids) {
574
0
        auto it = src_slot_desc_map.find(slot_id);
575
0
        if (it == std::end(src_slot_desc_map)) {
576
0
            return Status::InternalError("Unknown source slot descriptor, slot_id={}", slot_id);
577
0
        }
578
0
        _src_slot_descs.emplace_back(it->second);
579
0
    }
580
0
    _row_desc.reset(new RowDescriptor(_runtime_state->desc_tbl(),
581
0
                                      std::vector<TupleId>({_params.src_tuple_id})));
582
583
0
    if (!_pre_filter_texprs.empty()) {
584
0
        DCHECK(_pre_filter_texprs.size() == 1);
585
0
        RETURN_IF_ERROR(VExpr::create_expr_tree(_pre_filter_texprs[0], _pre_filter_ctx_ptr));
586
0
        RETURN_IF_ERROR(_pre_filter_ctx_ptr->prepare(_runtime_state.get(), *_row_desc));
587
0
        RETURN_IF_ERROR(_pre_filter_ctx_ptr->open(_runtime_state.get()));
588
0
    }
589
590
0
    _dest_tuple_desc = _runtime_state->desc_tbl().get_tuple_descriptor(_params.dest_tuple_id);
591
0
    if (_dest_tuple_desc == nullptr) {
592
0
        return Status::InternalError("Unknown dest tuple descriptor, tuple_id={}",
593
0
                                     _params.dest_tuple_id);
594
0
    }
595
0
    bool has_slot_id_map = _params.__isset.dest_sid_to_src_sid_without_trans;
596
0
    for (auto slot_desc : _dest_tuple_desc->slots()) {
597
0
        auto it = _params.expr_of_dest_slot.find(slot_desc->id());
598
0
        if (it == std::end(_params.expr_of_dest_slot)) {
599
0
            return Status::InternalError("No expr for dest slot, id={}, name={}", slot_desc->id(),
600
0
                                         slot_desc->col_name());
601
0
        }
602
603
0
        VExprContextSPtr ctx;
604
0
        RETURN_IF_ERROR(VExpr::create_expr_tree(it->second, ctx));
605
0
        RETURN_IF_ERROR(ctx->prepare(_runtime_state.get(), *_row_desc.get()));
606
0
        RETURN_IF_ERROR(ctx->open(_runtime_state.get()));
607
0
        _dest_expr_ctxs.emplace_back(ctx);
608
0
        if (has_slot_id_map) {
609
0
            auto it1 = _params.dest_sid_to_src_sid_without_trans.find(slot_desc->id());
610
0
            if (it1 == std::end(_params.dest_sid_to_src_sid_without_trans)) {
611
0
                _src_slot_descs_order_by_dest.emplace_back(nullptr);
612
0
            } else {
613
0
                auto _src_slot_it = src_slot_desc_map.find(it1->second);
614
0
                if (_src_slot_it == std::end(src_slot_desc_map)) {
615
0
                    return Status::InternalError("No src slot {} in src slot descs", it1->second);
616
0
                }
617
0
                _dest_slot_to_src_slot_index.emplace(_src_slot_descs_order_by_dest.size(),
618
0
                                                     src_slot_desc_to_index[_src_slot_it->second]);
619
0
                _src_slot_descs_order_by_dest.emplace_back(_src_slot_it->second);
620
0
            }
621
0
        }
622
0
    }
623
0
    return Status::OK();
624
0
}
625
626
0
Status PushBrokerReader::_get_next_reader() {
627
0
    _cur_reader.reset(nullptr);
628
0
    if (_next_range >= _file_ranges.size()) {
629
0
        _eof = true;
630
0
        return Status::OK();
631
0
    }
632
0
    const TFileRangeDesc& range = _file_ranges[_next_range++];
633
0
    Status init_status;
634
0
    switch (_file_params.format_type) {
635
0
    case TFileFormatType::FORMAT_PARQUET: {
636
0
        std::unique_ptr<ParquetReader> parquet_reader = ParquetReader::create_unique(
637
0
                _runtime_profile, _file_params, range, _runtime_state->query_options().batch_size,
638
0
                &_runtime_state->timezone_obj(), _io_ctx.get(), _runtime_state.get());
639
640
0
        init_status = parquet_reader->init_reader(
641
0
                _all_col_names, &_col_name_to_block_idx, _push_down_exprs, _slot_id_to_predicates,
642
0
                _real_tuple_desc, _default_val_row_desc.get(), _col_name_to_slot_id,
643
0
                &_not_single_slot_filter_conjuncts, &_slot_id_to_filter_conjuncts,
644
0
                TableSchemaChangeHelper::ConstNode::get_instance(), false);
645
0
        _cur_reader = std::move(parquet_reader);
646
0
        if (!init_status.ok()) {
647
0
            return Status::InternalError("failed to init reader for file {}, err: {}", range.path,
648
0
                                         init_status.to_string());
649
0
        }
650
0
        std::unordered_map<std::string, std::tuple<std::string, const SlotDescriptor*>>
651
0
                partition_columns;
652
0
        std::unordered_map<std::string, VExprContextSPtr> missing_columns;
653
0
        RETURN_IF_ERROR(_cur_reader->get_columns(&_name_to_col_type, &_missing_cols));
654
0
        RETURN_IF_ERROR(_cur_reader->set_fill_columns(partition_columns, missing_columns));
655
0
        break;
656
0
    }
657
0
    default:
658
0
        return Status::Error<PUSH_INIT_ERROR>("Unsupported file format type: {}",
659
0
                                              _file_params.format_type);
660
0
    }
661
0
    _cur_reader_eof = false;
662
663
0
    return Status::OK();
664
0
}
665
666
} // namespace doris