Coverage Report

Created: 2026-03-20 04:39

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/scan/file_scanner.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/scan/file_scanner.h"
19
20
#include <fmt/format.h>
21
#include <gen_cpp/Exprs_types.h>
22
#include <gen_cpp/Metrics_types.h>
23
#include <gen_cpp/Opcodes_types.h>
24
#include <gen_cpp/PaloInternalService_types.h>
25
#include <gen_cpp/PlanNodes_types.h>
26
#include <glog/logging.h>
27
28
#include <algorithm>
29
#include <boost/iterator/iterator_facade.hpp>
30
#include <map>
31
#include <ranges>
32
#include <tuple>
33
#include <unordered_map>
34
#include <utility>
35
36
#include "common/compiler_util.h" // IWYU pragma: keep
37
#include "common/config.h"
38
#include "common/consts.h"
39
#include "common/logging.h"
40
#include "common/status.h"
41
#include "core/block/column_with_type_and_name.h"
42
#include "core/block/columns_with_type_and_name.h"
43
#include "core/column/column.h"
44
#include "core/column/column_nullable.h"
45
#include "core/column/column_vector.h"
46
#include "core/data_type/data_type.h"
47
#include "core/data_type/data_type_nullable.h"
48
#include "core/data_type/data_type_string.h"
49
#include "core/string_ref.h"
50
#include "exec/common/stringop_substring.h"
51
#include "exec/rowid_fetcher.h"
52
#include "exec/scan/scan_node.h"
53
#include "exprs/aggregate/aggregate_function.h"
54
#include "exprs/function/function.h"
55
#include "exprs/function/simple_function_factory.h"
56
#include "exprs/vexpr.h"
57
#include "exprs/vexpr_context.h"
58
#include "exprs/vexpr_fwd.h"
59
#include "exprs/vslot_ref.h"
60
#include "format/arrow/arrow_stream_reader.h"
61
#include "format/csv/csv_reader.h"
62
#include "format/json/new_json_reader.h"
63
#include "format/native/native_reader.h"
64
#include "format/orc/vorc_reader.h"
65
#include "format/parquet/vparquet_reader.h"
66
#include "format/table/hive_reader.h"
67
#include "format/table/hudi_jni_reader.h"
68
#include "format/table/hudi_reader.h"
69
#include "format/table/iceberg_reader.h"
70
#include "format/table/jdbc_jni_reader.h"
71
#include "format/table/max_compute_jni_reader.h"
72
#include "format/table/paimon_cpp_reader.h"
73
#include "format/table/paimon_jni_reader.h"
74
#include "format/table/paimon_predicate_converter.h"
75
#include "format/table/paimon_reader.h"
76
#include "format/table/remote_doris_reader.h"
77
#include "format/table/transactional_hive_reader.h"
78
#include "format/table/trino_connector_jni_reader.h"
79
#include "format/text/text_reader.h"
80
#include "io/cache/block_file_cache_profile.h"
81
#include "load/group_commit/wal/wal_reader.h"
82
#include "runtime/descriptors.h"
83
#include "runtime/runtime_profile.h"
84
#include "runtime/runtime_state.h"
85
86
namespace cctz {
87
class time_zone;
88
} // namespace cctz
89
namespace doris {
90
class ShardedKVCache;
91
} // namespace doris
92
93
namespace doris {
94
#include "common/compile_check_begin.h"
95
using namespace ErrorCode;
96
97
const std::string FileScanner::FileReadBytesProfile = "FileReadBytes";
98
const std::string FileScanner::FileReadTimeProfile = "FileReadTime";
99
100
FileScanner::FileScanner(RuntimeState* state, FileScanLocalState* local_state, int64_t limit,
101
                         std::shared_ptr<SplitSourceConnector> split_source,
102
                         RuntimeProfile* profile, ShardedKVCache* kv_cache,
103
                         const std::unordered_map<std::string, int>* colname_to_slot_id)
104
2.67k
        : Scanner(state, local_state, limit, profile),
105
2.67k
          _split_source(split_source),
106
2.67k
          _cur_reader(nullptr),
107
2.67k
          _cur_reader_eof(false),
108
2.67k
          _kv_cache(kv_cache),
109
2.67k
          _strict_mode(false),
110
2.67k
          _col_name_to_slot_id(colname_to_slot_id) {
111
2.67k
    if (state->get_query_ctx() != nullptr &&
112
2.67k
        state->get_query_ctx()->file_scan_range_params_map.count(local_state->parent_id()) > 0) {
113
522
        _params = &(state->get_query_ctx()->file_scan_range_params_map[local_state->parent_id()]);
114
2.15k
    } else {
115
        // old fe thrift protocol
116
2.15k
        _params = _split_source->get_params();
117
2.15k
    }
118
2.67k
    if (_params->__isset.strict_mode) {
119
2.15k
        _strict_mode = _params->strict_mode;
120
2.15k
    }
121
122
    // For load scanner, there are input and output tuple.
123
    // For query scanner, there is only output tuple
124
2.67k
    _input_tuple_desc = state->desc_tbl().get_tuple_descriptor(_params->src_tuple_id);
125
2.67k
    _real_tuple_desc = _input_tuple_desc == nullptr ? _output_tuple_desc : _input_tuple_desc;
126
2.67k
    _is_load = (_input_tuple_desc != nullptr);
127
2.67k
}
128
129
2.67k
Status FileScanner::init(RuntimeState* state, const VExprContextSPtrs& conjuncts) {
130
2.67k
    RETURN_IF_ERROR(Scanner::init(state, conjuncts));
131
2.67k
    _get_block_timer =
132
2.67k
            ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(), "FileScannerGetBlockTime", 1);
133
2.67k
    _cast_to_input_block_timer = ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(),
134
2.67k
                                                      "FileScannerCastInputBlockTime", 1);
135
2.67k
    _fill_missing_columns_timer = ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(),
136
2.67k
                                                       "FileScannerFillMissingColumnTime", 1);
137
2.67k
    _pre_filter_timer =
138
2.67k
            ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(), "FileScannerPreFilterTimer", 1);
139
2.67k
    _convert_to_output_block_timer = ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(),
140
2.67k
                                                          "FileScannerConvertOuputBlockTime", 1);
141
2.67k
    _runtime_filter_partition_prune_timer = ADD_TIMER_WITH_LEVEL(
142
2.67k
            _local_state->scanner_profile(), "FileScannerRuntimeFilterPartitionPruningTime", 1);
143
2.67k
    _empty_file_counter =
144
2.67k
            ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(), "EmptyFileNum", TUnit::UNIT, 1);
145
2.67k
    _not_found_file_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
146
2.67k
                                                     "NotFoundFileNum", TUnit::UNIT, 1);
147
2.67k
    _fully_skipped_file_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
148
2.67k
                                                         "FullySkippedFileNum", TUnit::UNIT, 1);
149
2.67k
    _file_counter =
150
2.67k
            ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(), "FileNumber", TUnit::UNIT, 1);
151
152
2.67k
    _file_read_bytes_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
153
2.67k
                                                      FileReadBytesProfile, TUnit::BYTES, 1);
154
2.67k
    _file_read_calls_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
155
2.67k
                                                      "FileReadCalls", TUnit::UNIT, 1);
156
2.67k
    _file_read_time_counter =
157
2.67k
            ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(), FileReadTimeProfile, 1);
158
159
2.67k
    _runtime_filter_partition_pruned_range_counter =
160
2.67k
            ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
161
2.67k
                                   "RuntimeFilterPartitionPrunedRangeNum", TUnit::UNIT, 1);
162
163
2.67k
    _file_cache_statistics.reset(new io::FileCacheStatistics());
164
2.67k
    _file_reader_stats.reset(new io::FileReaderStats());
165
166
2.67k
    RETURN_IF_ERROR(_init_io_ctx());
167
2.67k
    _io_ctx->file_cache_stats = _file_cache_statistics.get();
168
2.67k
    _io_ctx->file_reader_stats = _file_reader_stats.get();
169
2.67k
    _io_ctx->is_disposable = _state->query_options().disable_file_cache;
170
171
2.67k
    if (_is_load) {
172
2.15k
        _src_row_desc.reset(new RowDescriptor(_state->desc_tbl(),
173
2.15k
                                              std::vector<TupleId>({_input_tuple_desc->id()})));
174
        // prepare pre filters
175
2.15k
        if (_params->__isset.pre_filter_exprs_list) {
176
4
            RETURN_IF_ERROR(doris::VExpr::create_expr_trees(_params->pre_filter_exprs_list,
177
4
                                                            _pre_conjunct_ctxs));
178
2.14k
        } else if (_params->__isset.pre_filter_exprs) {
179
0
            VExprContextSPtr context;
180
0
            RETURN_IF_ERROR(doris::VExpr::create_expr_tree(_params->pre_filter_exprs, context));
181
0
            _pre_conjunct_ctxs.emplace_back(context);
182
0
        }
183
184
2.15k
        for (auto& conjunct : _pre_conjunct_ctxs) {
185
5
            RETURN_IF_ERROR(conjunct->prepare(_state, *_src_row_desc));
186
5
            RETURN_IF_ERROR(conjunct->open(_state));
187
5
        }
188
189
2.15k
        _dest_row_desc.reset(new RowDescriptor(_state->desc_tbl(),
190
2.15k
                                               std::vector<TupleId>({_output_tuple_desc->id()})));
191
2.15k
    }
192
193
2.67k
    _default_val_row_desc.reset(
194
2.67k
            new RowDescriptor(_state->desc_tbl(), std::vector<TupleId>({_real_tuple_desc->id()})));
195
196
2.67k
    return Status::OK();
197
2.67k
}
198
199
// check if the expr is a partition pruning expr
200
0
bool FileScanner::_check_partition_prune_expr(const VExprSPtr& expr) {
201
0
    if (expr->is_slot_ref()) {
202
0
        auto* slot_ref = static_cast<VSlotRef*>(expr.get());
203
0
        return _partition_slot_index_map.find(slot_ref->slot_id()) !=
204
0
               _partition_slot_index_map.end();
205
0
    }
206
0
    if (expr->is_literal()) {
207
0
        return true;
208
0
    }
209
0
    return std::ranges::all_of(expr->children(), [this](const auto& child) {
210
0
        return _check_partition_prune_expr(child);
211
0
    });
212
0
}
213
214
6
void FileScanner::_init_runtime_filter_partition_prune_ctxs() {
215
6
    _runtime_filter_partition_prune_ctxs.clear();
216
6
    for (auto& conjunct : _conjuncts) {
217
0
        auto impl = conjunct->root()->get_impl();
218
        // If impl is not null, which means this a conjuncts from runtime filter.
219
0
        auto expr = impl ? impl : conjunct->root();
220
0
        if (_check_partition_prune_expr(expr)) {
221
0
            _runtime_filter_partition_prune_ctxs.emplace_back(conjunct);
222
0
        }
223
0
    }
224
6
}
225
226
6
void FileScanner::_init_runtime_filter_partition_prune_block() {
227
    // init block with empty column
228
22
    for (auto const* slot_desc : _real_tuple_desc->slots()) {
229
22
        _runtime_filter_partition_prune_block.insert(
230
22
                ColumnWithTypeAndName(slot_desc->get_empty_mutable_column(),
231
22
                                      slot_desc->get_data_type_ptr(), slot_desc->col_name()));
232
22
    }
233
6
}
234
235
6
Status FileScanner::_process_runtime_filters_partition_prune(bool& can_filter_all) {
236
6
    SCOPED_TIMER(_runtime_filter_partition_prune_timer);
237
6
    if (_runtime_filter_partition_prune_ctxs.empty() || _partition_col_descs.empty()) {
238
6
        return Status::OK();
239
6
    }
240
0
    size_t partition_value_column_size = 1;
241
242
    // 1. Get partition key values to string columns.
243
0
    std::unordered_map<SlotId, MutableColumnPtr> partition_slot_id_to_column;
244
0
    for (auto const& partition_col_desc : _partition_col_descs) {
245
0
        const auto& [partition_value, partition_slot_desc] = partition_col_desc.second;
246
0
        auto data_type = partition_slot_desc->get_data_type_ptr();
247
0
        auto test_serde = data_type->get_serde();
248
0
        auto partition_value_column = data_type->create_column();
249
0
        auto* col_ptr = static_cast<IColumn*>(partition_value_column.get());
250
0
        Slice slice(partition_value.data(), partition_value.size());
251
0
        uint64_t num_deserialized = 0;
252
0
        DataTypeSerDe::FormatOptions options {};
253
0
        if (_partition_value_is_null.contains(partition_slot_desc->col_name())) {
254
            // for iceberg/paimon table
255
            // NOTICE: column is always be nullable for iceberg/paimon table now
256
0
            DCHECK(data_type->is_nullable());
257
0
            test_serde = test_serde->get_nested_serdes()[0];
258
0
            auto* null_column = assert_cast<ColumnNullable*>(col_ptr);
259
0
            if (_partition_value_is_null[partition_slot_desc->col_name()]) {
260
0
                null_column->insert_many_defaults(partition_value_column_size);
261
0
            } else {
262
                // If the partition value is not null, we set null map to 0 and deserialize it normally.
263
0
                null_column->get_null_map_column().insert_many_vals(0, partition_value_column_size);
264
0
                RETURN_IF_ERROR(test_serde->deserialize_column_from_fixed_json(
265
0
                        null_column->get_nested_column(), slice, partition_value_column_size,
266
0
                        &num_deserialized, options));
267
0
            }
268
0
        } else {
269
            // for hive/hudi table, the null value is set as "\\N"
270
            // TODO: this will be unified as iceberg/paimon table in the future
271
0
            RETURN_IF_ERROR(test_serde->deserialize_column_from_fixed_json(
272
0
                    *col_ptr, slice, partition_value_column_size, &num_deserialized, options));
273
0
        }
274
275
0
        partition_slot_id_to_column[partition_slot_desc->id()] = std::move(partition_value_column);
276
0
    }
277
278
    // 2. Fill _runtime_filter_partition_prune_block from the partition column, then execute conjuncts and filter block.
279
    // 2.1 Fill _runtime_filter_partition_prune_block from the partition column to match the conjuncts executing.
280
0
    size_t index = 0;
281
0
    bool first_column_filled = false;
282
0
    for (auto const* slot_desc : _real_tuple_desc->slots()) {
283
0
        if (partition_slot_id_to_column.find(slot_desc->id()) !=
284
0
            partition_slot_id_to_column.end()) {
285
0
            auto data_type = slot_desc->get_data_type_ptr();
286
0
            auto partition_value_column = std::move(partition_slot_id_to_column[slot_desc->id()]);
287
0
            if (data_type->is_nullable()) {
288
0
                _runtime_filter_partition_prune_block.insert(
289
0
                        index, ColumnWithTypeAndName(
290
0
                                       ColumnNullable::create(
291
0
                                               std::move(partition_value_column),
292
0
                                               ColumnUInt8::create(partition_value_column_size, 0)),
293
0
                                       data_type, slot_desc->col_name()));
294
0
            } else {
295
0
                _runtime_filter_partition_prune_block.insert(
296
0
                        index, ColumnWithTypeAndName(std::move(partition_value_column), data_type,
297
0
                                                     slot_desc->col_name()));
298
0
            }
299
0
            if (index == 0) {
300
0
                first_column_filled = true;
301
0
            }
302
0
        }
303
0
        index++;
304
0
    }
305
306
    // 2.2 Execute conjuncts.
307
0
    if (!first_column_filled) {
308
        // VExprContext.execute has an optimization, the filtering is executed when block->rows() > 0
309
        // The following process may be tricky and time-consuming, but we have no other way.
310
0
        _runtime_filter_partition_prune_block.get_by_position(0).column->assume_mutable()->resize(
311
0
                partition_value_column_size);
312
0
    }
313
0
    IColumn::Filter result_filter(_runtime_filter_partition_prune_block.rows(), 1);
314
0
    RETURN_IF_ERROR(VExprContext::execute_conjuncts(_runtime_filter_partition_prune_ctxs, nullptr,
315
0
                                                    &_runtime_filter_partition_prune_block,
316
0
                                                    &result_filter, &can_filter_all));
317
0
    return Status::OK();
318
0
}
319
320
1
Status FileScanner::_process_conjuncts() {
321
1
    _slot_id_to_filter_conjuncts.clear();
322
1
    _not_single_slot_filter_conjuncts.clear();
323
1
    for (auto& conjunct : _push_down_conjuncts) {
324
1
        auto impl = conjunct->root()->get_impl();
325
        // If impl is not null, which means this a conjuncts from runtime filter.
326
1
        auto cur_expr = impl ? impl : conjunct->root();
327
328
1
        std::vector<int> slot_ids;
329
1
        _get_slot_ids(cur_expr.get(), &slot_ids);
330
1
        if (slot_ids.empty()) {
331
0
            _not_single_slot_filter_conjuncts.emplace_back(conjunct);
332
0
            continue;
333
0
        }
334
1
        bool single_slot = true;
335
1
        for (int i = 1; i < slot_ids.size(); i++) {
336
0
            if (slot_ids[i] != slot_ids[0]) {
337
0
                single_slot = false;
338
0
                break;
339
0
            }
340
0
        }
341
1
        if (single_slot) {
342
1
            SlotId slot_id = slot_ids[0];
343
1
            _slot_id_to_filter_conjuncts[slot_id].emplace_back(conjunct);
344
1
        } else {
345
0
            _not_single_slot_filter_conjuncts.emplace_back(conjunct);
346
0
        }
347
1
    }
348
1
    return Status::OK();
349
1
}
350
351
178
Status FileScanner::_process_late_arrival_conjuncts() {
352
178
    if (_push_down_conjuncts.size() < _conjuncts.size()) {
353
1
        _push_down_conjuncts = _conjuncts;
354
1
        _conjuncts.clear();
355
1
        RETURN_IF_ERROR(_process_conjuncts());
356
1
    }
357
178
    if (_applied_rf_num == _total_rf_num) {
358
178
        _local_state->scanner_profile()->add_info_string("ApplyAllRuntimeFilters", "True");
359
178
    }
360
178
    return Status::OK();
361
178
}
362
363
1
void FileScanner::_get_slot_ids(VExpr* expr, std::vector<int>* slot_ids) {
364
1
    for (auto& child_expr : expr->children()) {
365
1
        if (child_expr->is_slot_ref()) {
366
1
            VSlotRef* slot_ref = reinterpret_cast<VSlotRef*>(child_expr.get());
367
1
            SlotDescriptor* slot_desc = _state->desc_tbl().get_slot_descriptor(slot_ref->slot_id());
368
1
            slot_desc->set_is_predicate(true);
369
1
            slot_ids->emplace_back(slot_ref->slot_id());
370
1
        } else {
371
0
            _get_slot_ids(child_expr.get(), slot_ids);
372
0
        }
373
1
    }
374
1
}
375
376
2.67k
Status FileScanner::_open_impl(RuntimeState* state) {
377
2.67k
    RETURN_IF_CANCELLED(state);
378
2.67k
    RETURN_IF_ERROR(Scanner::_open_impl(state));
379
2.67k
    if (_local_state) {
380
2.67k
        _condition_cache_digest = _local_state->get_condition_cache_digest();
381
2.67k
    }
382
2.67k
    RETURN_IF_ERROR(_split_source->get_next(&_first_scan_range, &_current_range));
383
2.67k
    if (_first_scan_range) {
384
2.67k
        RETURN_IF_ERROR(_init_expr_ctxes());
385
2.67k
        if (_state->query_options().enable_runtime_filter_partition_prune &&
386
2.67k
            !_partition_slot_index_map.empty()) {
387
6
            _init_runtime_filter_partition_prune_ctxs();
388
6
            _init_runtime_filter_partition_prune_block();
389
6
        }
390
2.67k
    } else {
391
        // there's no scan range in split source. stop scanner directly.
392
0
        _scanner_eof = true;
393
0
    }
394
395
2.67k
    return Status::OK();
396
2.67k
}
397
398
11.1k
Status FileScanner::_get_block_impl(RuntimeState* state, Block* block, bool* eof) {
399
11.1k
    Status st = _get_block_wrapped(state, block, eof);
400
401
11.1k
    if (!st.ok()) {
402
        // add cur path in error msg for easy debugging
403
14
        return std::move(st.append(". cur path: " + get_current_scan_range_name()));
404
14
    }
405
11.1k
    return st;
406
11.1k
}
407
408
// For query:
409
//                              [exist cols]  [non-exist cols]  [col from path]  input  output
410
//                              A     B    C  D                 E
411
// _init_src_block              x     x    x  x                 x                -      x
412
// get_next_block               x     x    x  -                 -                -      x
413
// _cast_to_input_block         -     -    -  -                 -                -      -
414
// _fill_columns_from_path      -     -    -  -                 x                -      x
415
// _fill_missing_columns        -     -    -  x                 -                -      x
416
// _convert_to_output_block     -     -    -  -                 -                -      -
417
//
418
// For load:
419
//                              [exist cols]  [non-exist cols]  [col from path]  input  output
420
//                              A     B    C  D                 E
421
// _init_src_block              x     x    x  x                 x                x      -
422
// get_next_block               x     x    x  -                 -                x      -
423
// _cast_to_input_block         x     x    x  -                 -                x      -
424
// _fill_columns_from_path      -     -    -  -                 x                x      -
425
// _fill_missing_columns        -     -    -  x                 -                x      -
426
// _convert_to_output_block     -     -    -  -                 -                -      x
427
11.1k
Status FileScanner::_get_block_wrapped(RuntimeState* state, Block* block, bool* eof) {
428
11.1k
    do {
429
11.1k
        RETURN_IF_CANCELLED(state);
430
11.1k
        if (_cur_reader == nullptr || _cur_reader_eof) {
431
5.34k
            _finalize_reader_condition_cache();
432
            // The file may not exist because the file list is got from meta cache,
433
            // And the file may already be removed from storage.
434
            // Just ignore not found files.
435
5.34k
            Status st = _get_next_reader();
436
5.34k
            if (st.is<ErrorCode::NOT_FOUND>() && config::ignore_not_found_file_in_external_table) {
437
0
                _cur_reader_eof = true;
438
0
                COUNTER_UPDATE(_not_found_file_counter, 1);
439
0
                continue;
440
5.34k
            } else if (st.is<ErrorCode::END_OF_FILE>()) {
441
0
                _cur_reader_eof = true;
442
0
                COUNTER_UPDATE(_fully_skipped_file_counter, 1);
443
0
                continue;
444
5.34k
            } else if (!st) {
445
2
                return st;
446
2
            }
447
5.33k
            _init_reader_condition_cache();
448
5.33k
        }
449
450
11.1k
        if (_scanner_eof) {
451
2.66k
            *eof = true;
452
2.66k
            return Status::OK();
453
2.66k
        }
454
455
        // Init src block for load job based on the data file schema (e.g. parquet)
456
        // For query job, simply set _src_block_ptr to block.
457
8.47k
        size_t read_rows = 0;
458
8.47k
        RETURN_IF_ERROR(_init_src_block(block));
459
8.47k
        if (_need_iceberg_rowid_column && _current_range.__isset.table_format_params &&
460
8.47k
            _current_range.table_format_params.table_format_type == "iceberg") {
461
0
            if (auto* iceberg_reader = dynamic_cast<IcebergTableReader*>(_cur_reader.get())) {
462
0
                iceberg_reader->set_row_id_column_position(_iceberg_rowid_column_pos);
463
0
            }
464
0
        }
465
8.47k
        {
466
8.47k
            SCOPED_TIMER(_get_block_timer);
467
468
            // Read next block.
469
            // Some of column in block may not be filled (column not exist in file)
470
8.47k
            RETURN_IF_ERROR(
471
8.47k
                    _cur_reader->get_next_block(_src_block_ptr, &read_rows, &_cur_reader_eof));
472
8.47k
        }
473
        // use read_rows instead of _src_block_ptr->rows(), because the first column of _src_block_ptr
474
        // may not be filled after calling `get_next_block()`, so _src_block_ptr->rows() may return wrong result.
475
8.46k
        if (read_rows > 0) {
476
5.88k
            if ((!_cur_reader->count_read_rows()) && _io_ctx) {
477
5.55k
                _io_ctx->file_reader_stats->read_rows += read_rows;
478
5.55k
            }
479
            // If the push_down_agg_type is COUNT, no need to do the rest,
480
            // because we only save a number in block.
481
5.88k
            if (_get_push_down_agg_type() != TPushAggOp::type::COUNT) {
482
                // Convert the src block columns type to string in-place.
483
5.88k
                RETURN_IF_ERROR(_cast_to_input_block(block));
484
                // FileReader can fill partition and missing columns itself
485
5.88k
                if (!_cur_reader->fill_all_columns()) {
486
                    // Fill rows in src block with partition columns from path. (e.g. Hive partition columns)
487
5.58k
                    RETURN_IF_ERROR(_fill_columns_from_path(read_rows));
488
                    // Fill columns not exist in file with null or default value
489
5.58k
                    RETURN_IF_ERROR(_fill_missing_columns(read_rows));
490
5.58k
                }
491
                // Apply _pre_conjunct_ctxs to filter src block.
492
5.88k
                RETURN_IF_ERROR(_pre_filter_src_block());
493
494
                // Convert src block to output block (dest block), string to dest data type and apply filters.
495
5.88k
                RETURN_IF_ERROR(_convert_to_output_block(block));
496
                // Truncate char columns or varchar columns if size is smaller than file columns
497
                // or not found in the file column schema.
498
5.88k
                RETURN_IF_ERROR(_truncate_char_or_varchar_columns(block));
499
5.88k
            }
500
5.88k
        }
501
8.46k
        break;
502
8.46k
    } while (true);
503
504
    // Update filtered rows and unselected rows for load, reset counter.
505
    // {
506
    //     state->update_num_rows_load_filtered(_counter.num_rows_filtered);
507
    //     state->update_num_rows_load_unselected(_counter.num_rows_unselected);
508
    //     _reset_counter();
509
    // }
510
8.46k
    return Status::OK();
511
11.1k
}
512
513
/**
514
 * Check whether there are complex types in parquet/orc reader in broker/stream load.
515
 * Broker/stream load will cast any type as string type, and complex types will be casted wrong.
516
 * This is a temporary method, and will be replaced by tvf.
517
 */
518
7.29k
Status FileScanner::_check_output_block_types() {
519
7.29k
    if (_is_load) {
520
7.29k
        TFileFormatType::type format_type = _params->format_type;
521
7.29k
        if (format_type == TFileFormatType::FORMAT_PARQUET ||
522
7.29k
            format_type == TFileFormatType::FORMAT_ORC) {
523
1.63k
            for (auto slot : _output_tuple_desc->slots()) {
524
1.63k
                if (is_complex_type(slot->type()->get_primitive_type())) {
525
0
                    return Status::InternalError(
526
0
                            "Parquet/orc doesn't support complex types in broker/stream load, "
527
0
                            "please use tvf(table value function) to insert complex types.");
528
0
                }
529
1.63k
            }
530
88
        }
531
7.29k
    }
532
7.29k
    return Status::OK();
533
7.29k
}
534
535
8.47k
Status FileScanner::_init_src_block(Block* block) {
536
8.47k
    if (!_is_load) {
537
1.18k
        _src_block_ptr = block;
538
539
1.18k
        bool update_name_to_idx = _src_block_name_to_idx.empty();
540
1.18k
        _iceberg_rowid_column_pos = -1;
541
1.18k
        if (_need_iceberg_rowid_column && _current_range.__isset.table_format_params &&
542
1.18k
            _current_range.table_format_params.table_format_type == "iceberg") {
543
0
            int row_id_idx = block->get_position_by_name(BeConsts::ICEBERG_ROWID_COL);
544
0
            if (row_id_idx >= 0) {
545
0
                _iceberg_rowid_column_pos = row_id_idx;
546
0
                if (!update_name_to_idx &&
547
0
                    !_src_block_name_to_idx.contains(BeConsts::ICEBERG_ROWID_COL)) {
548
0
                    update_name_to_idx = true;
549
0
                }
550
0
            }
551
0
        }
552
553
        // Build name to index map only once on first call
554
1.18k
        if (update_name_to_idx) {
555
551
            _src_block_name_to_idx = block->get_name_to_pos_map();
556
551
        }
557
1.18k
        return Status::OK();
558
1.18k
    }
559
7.28k
    RETURN_IF_ERROR(_check_output_block_types());
560
561
    // if (_src_block_init) {
562
    //     _src_block.clear_column_data();
563
    //     _src_block_ptr = &_src_block;
564
    //     return Status::OK();
565
    // }
566
567
7.28k
    _src_block.clear();
568
7.28k
    uint32_t idx = 0;
569
    // slots in _input_tuple_desc contains all slots describe in load statement, eg:
570
    // -H "columns: k1, k2, tmp1, k3 = tmp1 + 1"
571
    // _input_tuple_desc will contains: k1, k2, tmp1
572
    // and some of them are from file, such as k1 and k2, and some of them may not exist in file, such as tmp1
573
    // _input_tuple_desc also contains columns from path
574
80.5k
    for (auto& slot : _input_tuple_desc->slots()) {
575
80.5k
        DataTypePtr data_type;
576
80.5k
        auto it = _slot_lower_name_to_col_type.find(slot->col_name());
577
80.5k
        if (slot->is_skip_bitmap_col()) {
578
314
            _skip_bitmap_col_idx = idx;
579
314
        }
580
80.5k
        if (_params->__isset.sequence_map_col) {
581
1.25k
            if (_params->sequence_map_col == slot->col_name()) {
582
198
                _sequence_map_col_uid = slot->col_unique_id();
583
198
            }
584
1.25k
        }
585
80.5k
        data_type =
586
80.5k
                it == _slot_lower_name_to_col_type.end() ? slot->type() : make_nullable(it->second);
587
80.5k
        MutableColumnPtr data_column = data_type->create_column();
588
80.5k
        _src_block.insert(
589
80.5k
                ColumnWithTypeAndName(std::move(data_column), data_type, slot->col_name()));
590
80.5k
        _src_block_name_to_idx.emplace(slot->col_name(), idx++);
591
80.5k
    }
592
7.28k
    if (_params->__isset.sequence_map_col) {
593
1.76k
        for (const auto& slot : _output_tuple_desc->slots()) {
594
            // When the target table has seqeunce map column, _input_tuple_desc will not contains __DORIS_SEQUENCE_COL__,
595
            // so we should get its column unique id from _output_tuple_desc
596
1.76k
            if (slot->is_sequence_col()) {
597
206
                _sequence_col_uid = slot->col_unique_id();
598
206
            }
599
1.76k
        }
600
242
    }
601
7.28k
    _src_block_ptr = &_src_block;
602
7.28k
    _src_block_init = true;
603
7.28k
    return Status::OK();
604
7.28k
}
605
606
5.88k
Status FileScanner::_cast_to_input_block(Block* block) {
607
5.88k
    if (!_is_load) {
608
733
        return Status::OK();
609
733
    }
610
5.15k
    SCOPED_TIMER(_cast_to_input_block_timer);
611
    // cast primitive type(PT0) to primitive type(PT1)
612
5.15k
    uint32_t idx = 0;
613
62.6k
    for (auto& slot_desc : _input_tuple_desc->slots()) {
614
62.6k
        if (_slot_lower_name_to_col_type.find(slot_desc->col_name()) ==
615
62.6k
            _slot_lower_name_to_col_type.end()) {
616
            // skip columns which does not exist in file
617
336
            continue;
618
336
        }
619
62.3k
        auto& arg = _src_block_ptr->get_by_position(_src_block_name_to_idx[slot_desc->col_name()]);
620
62.3k
        auto return_type = slot_desc->get_data_type_ptr();
621
        // remove nullable here, let the get_function decide whether nullable
622
62.3k
        auto data_type = get_data_type_with_default_argument(remove_nullable(return_type));
623
62.3k
        ColumnsWithTypeAndName arguments {
624
62.3k
                arg, {data_type->create_column(), data_type, slot_desc->col_name()}};
625
62.3k
        auto func_cast =
626
62.3k
                SimpleFunctionFactory::instance().get_function("CAST", arguments, return_type, {});
627
62.3k
        if (!func_cast) {
628
0
            return Status::InternalError("Function CAST[arg={}, col name={}, return={}] not found!",
629
0
                                         arg.type->get_name(), slot_desc->col_name(),
630
0
                                         return_type->get_name());
631
0
        }
632
62.3k
        idx = _src_block_name_to_idx[slot_desc->col_name()];
633
62.3k
        DCHECK(_state != nullptr);
634
62.3k
        auto ctx = FunctionContext::create_context(_state, {}, {});
635
62.3k
        RETURN_IF_ERROR(
636
62.3k
                func_cast->execute(ctx.get(), *_src_block_ptr, {idx}, idx, arg.column->size()));
637
62.3k
        _src_block_ptr->get_by_position(idx).type = std::move(return_type);
638
62.3k
    }
639
5.15k
    return Status::OK();
640
5.15k
}
641
642
5.58k
Status FileScanner::_fill_columns_from_path(size_t rows) {
643
5.58k
    if (!_fill_partition_from_path) {
644
0
        return Status::OK();
645
0
    }
646
5.58k
    DataTypeSerDe::FormatOptions _text_formatOptions;
647
5.58k
    for (auto& kv : _partition_col_descs) {
648
7
        auto doris_column =
649
7
                _src_block_ptr->get_by_position(_src_block_name_to_idx[kv.first]).column;
650
        // _src_block_ptr points to a mutable block created by this class itself, so const_cast can be used here.
651
7
        IColumn* col_ptr = const_cast<IColumn*>(doris_column.get());
652
7
        auto& [value, slot_desc] = kv.second;
653
7
        auto _text_serde = slot_desc->get_data_type_ptr()->get_serde();
654
7
        Slice slice(value.data(), value.size());
655
7
        uint64_t num_deserialized = 0;
656
7
        if (_text_serde->deserialize_column_from_fixed_json(*col_ptr, slice, rows,
657
7
                                                            &num_deserialized,
658
7
                                                            _text_formatOptions) != Status::OK()) {
659
0
            return Status::InternalError("Failed to fill partition column: {}={}",
660
0
                                         slot_desc->col_name(), value);
661
0
        }
662
7
        if (num_deserialized != rows) {
663
0
            return Status::InternalError(
664
0
                    "Failed to fill partition column: {}={} ."
665
0
                    "Number of rows expected to be written : {}, number of rows actually written : "
666
0
                    "{}",
667
0
                    slot_desc->col_name(), value, num_deserialized, rows);
668
0
        }
669
7
    }
670
5.58k
    return Status::OK();
671
5.58k
}
672
673
5.58k
Status FileScanner::_fill_missing_columns(size_t rows) {
674
5.58k
    if (_missing_cols.empty()) {
675
5.58k
        return Status::OK();
676
5.58k
    }
677
678
0
    SCOPED_TIMER(_fill_missing_columns_timer);
679
0
    for (auto& kv : _missing_col_descs) {
680
0
        if (kv.second == nullptr) {
681
            // no default column, fill with null
682
0
            auto mutable_column = _src_block_ptr->get_by_position(_src_block_name_to_idx[kv.first])
683
0
                                          .column->assume_mutable();
684
0
            auto* nullable_column = static_cast<ColumnNullable*>(mutable_column.get());
685
0
            nullable_column->insert_many_defaults(rows);
686
0
        } else {
687
            // fill with default value
688
0
            auto& ctx = kv.second;
689
0
            ColumnPtr result_column_ptr;
690
            // PT1 => dest primitive type
691
0
            RETURN_IF_ERROR(ctx->execute(_src_block_ptr, result_column_ptr));
692
0
            if (result_column_ptr->use_count() == 1) {
693
                // call resize because the first column of _src_block_ptr may not be filled by reader,
694
                // so _src_block_ptr->rows() may return wrong result, cause the column created by `ctx->execute()`
695
                // has only one row.
696
0
                auto mutable_column = result_column_ptr->assume_mutable();
697
0
                mutable_column->resize(rows);
698
                // result_column_ptr maybe a ColumnConst, convert it to a normal column
699
0
                result_column_ptr = result_column_ptr->convert_to_full_column_if_const();
700
0
                auto origin_column_type =
701
0
                        _src_block_ptr->get_by_position(_src_block_name_to_idx[kv.first]).type;
702
0
                bool is_nullable = origin_column_type->is_nullable();
703
0
                if (!_src_block_name_to_idx.contains(kv.first)) {
704
0
                    return Status::InternalError("Column {} not found in src block {}", kv.first,
705
0
                                                 _src_block_ptr->dump_structure());
706
0
                }
707
0
                _src_block_ptr->replace_by_position(
708
0
                        _src_block_name_to_idx[kv.first],
709
0
                        is_nullable ? make_nullable(result_column_ptr) : result_column_ptr);
710
0
            }
711
0
        }
712
0
    }
713
0
    return Status::OK();
714
0
}
715
716
5.88k
Status FileScanner::_pre_filter_src_block() {
717
5.88k
    if (!_is_load) {
718
733
        return Status::OK();
719
733
    }
720
5.15k
    if (!_pre_conjunct_ctxs.empty()) {
721
28
        SCOPED_TIMER(_pre_filter_timer);
722
28
        auto origin_column_num = _src_block_ptr->columns();
723
28
        auto old_rows = _src_block_ptr->rows();
724
28
        RETURN_IF_ERROR(
725
28
                VExprContext::filter_block(_pre_conjunct_ctxs, _src_block_ptr, origin_column_num));
726
28
        _counter.num_rows_unselected += old_rows - _src_block_ptr->rows();
727
28
    }
728
5.15k
    return Status::OK();
729
5.15k
}
730
731
5.88k
Status FileScanner::_convert_to_output_block(Block* block) {
732
5.88k
    if (!_is_load) {
733
733
        return Status::OK();
734
733
    }
735
5.15k
    SCOPED_TIMER(_convert_to_output_block_timer);
736
    // The block is passed from scanner context's free blocks,
737
    // which is initialized by output columns
738
    // so no need to clear it
739
    // block->clear();
740
741
5.15k
    int ctx_idx = 0;
742
5.15k
    size_t rows = _src_block_ptr->rows();
743
5.15k
    auto filter_column = ColumnUInt8::create(rows, 1);
744
5.15k
    auto& filter_map = filter_column->get_data();
745
746
    // After convert, the column_ptr should be copied into output block.
747
    // Can not use block->insert() because it may cause use_count() non-zero bug
748
5.15k
    MutableBlock mutable_output_block =
749
5.15k
            VectorizedUtils::build_mutable_mem_reuse_block(block, *_dest_row_desc);
750
5.15k
    auto& mutable_output_columns = mutable_output_block.mutable_columns();
751
752
5.15k
    std::vector<BitmapValue>* skip_bitmaps {nullptr};
753
5.15k
    if (_should_process_skip_bitmap_col()) {
754
157
        auto* skip_bitmap_nullable_col_ptr =
755
157
                assert_cast<ColumnNullable*>(_src_block_ptr->get_by_position(_skip_bitmap_col_idx)
756
157
                                                     .column->assume_mutable()
757
157
                                                     .get());
758
157
        skip_bitmaps = &(assert_cast<ColumnBitmap*>(
759
157
                                 skip_bitmap_nullable_col_ptr->get_nested_column_ptr().get())
760
157
                                 ->get_data());
761
        // NOTE:
762
        // - If the table has sequence type column, __DORIS_SEQUENCE_COL__ will be put in _input_tuple_desc, so whether
763
        //   __DORIS_SEQUENCE_COL__ will be marked in skip bitmap depends on whether it's specified in that row
764
        // - If the table has sequence map column, __DORIS_SEQUENCE_COL__ will not be put in _input_tuple_desc,
765
        //   so __DORIS_SEQUENCE_COL__ will be ommited if it't specified in a row and will not be marked in skip bitmap.
766
        //   So we should mark __DORIS_SEQUENCE_COL__ in skip bitmap here if the corresponding sequence map column us marked
767
157
        if (_sequence_map_col_uid != -1) {
768
347
            for (int j = 0; j < rows; ++j) {
769
328
                if ((*skip_bitmaps)[j].contains(_sequence_map_col_uid)) {
770
137
                    (*skip_bitmaps)[j].add(_sequence_col_uid);
771
137
                }
772
328
            }
773
19
        }
774
157
    }
775
776
    // for (auto slot_desc : _output_tuple_desc->slots()) {
777
73.3k
    for (int j = 0; j < mutable_output_columns.size(); ++j) {
778
68.2k
        auto* slot_desc = _output_tuple_desc->slots()[j];
779
68.2k
        int dest_index = ctx_idx;
780
68.2k
        ColumnPtr column_ptr;
781
782
68.2k
        auto& ctx = _dest_vexpr_ctx[dest_index];
783
        // PT1 => dest primitive type
784
68.2k
        RETURN_IF_ERROR(ctx->execute(_src_block_ptr, column_ptr));
785
        // column_ptr maybe a ColumnConst, convert it to a normal column
786
68.2k
        column_ptr = column_ptr->convert_to_full_column_if_const();
787
68.2k
        DCHECK(column_ptr);
788
789
        // because of src_slot_desc is always be nullable, so the column_ptr after do dest_expr
790
        // is likely to be nullable
791
68.2k
        if (LIKELY(column_ptr->is_nullable())) {
792
63.2k
            const auto* nullable_column = reinterpret_cast<const ColumnNullable*>(column_ptr.get());
793
175M
            for (int i = 0; i < rows; ++i) {
794
175M
                if (filter_map[i] && nullable_column->is_null_at(i)) {
795
                    // skip checks for non-mentioned columns in flexible partial update
796
1.79M
                    if (skip_bitmaps == nullptr ||
797
1.79M
                        !skip_bitmaps->at(i).contains(slot_desc->col_unique_id())) {
798
                        // clang-format off
799
1.74M
                        if (_strict_mode && (_src_slot_descs_order_by_dest[dest_index]) &&
800
1.74M
                            !_src_block_ptr->get_by_position(_dest_slot_to_src_slot_index[dest_index]).column->is_null_at(i)) {
801
5.48k
                            filter_map[i] = false;
802
5.48k
                            RETURN_IF_ERROR(_state->append_error_msg_to_file(
803
5.48k
                                [&]() -> std::string {
804
5.48k
                                    return _src_block_ptr->dump_one_line(i, _num_of_columns_from_file);
805
5.48k
                                },
806
5.48k
                                [&]() -> std::string {
807
5.48k
                                    auto raw_value =
808
5.48k
                                            _src_block_ptr->get_by_position(_dest_slot_to_src_slot_index[dest_index]).column->get_data_at(i);
809
5.48k
                                    std::string raw_string = raw_value.to_string();
810
5.48k
                                    fmt::memory_buffer error_msg;
811
5.48k
                                    fmt::format_to(error_msg,"column({}) value is incorrect while strict mode is {}, src value is {}",
812
5.48k
                                            slot_desc->col_name(), _strict_mode, raw_string);
813
5.48k
                                    return fmt::to_string(error_msg);
814
5.48k
                                }));
815
1.73M
                        } else if (!slot_desc->is_nullable()) {
816
638
                            filter_map[i] = false;
817
638
                            RETURN_IF_ERROR(_state->append_error_msg_to_file(
818
638
                                [&]() -> std::string {
819
638
                                    return _src_block_ptr->dump_one_line(i, _num_of_columns_from_file);
820
638
                                },
821
638
                                [&]() -> std::string {
822
638
                                    fmt::memory_buffer error_msg;
823
638
                                    fmt::format_to(error_msg, "column({}) values is null while columns is not nullable", slot_desc->col_name());
824
638
                                    return fmt::to_string(error_msg);
825
638
                                }));
826
638
                        }
827
                        // clang-format on
828
1.74M
                    }
829
1.79M
                }
830
175M
            }
831
63.2k
            if (!slot_desc->is_nullable()) {
832
41.9k
                column_ptr = remove_nullable(column_ptr);
833
41.9k
            }
834
63.2k
        } else if (slot_desc->is_nullable()) {
835
115
            column_ptr = make_nullable(column_ptr);
836
115
        }
837
68.2k
        mutable_output_columns[j]->insert_range_from(*column_ptr, 0, rows);
838
68.2k
        ctx_idx++;
839
68.2k
    }
840
841
    // after do the dest block insert operation, clear _src_block to remove the reference of origin column
842
5.15k
    _src_block_ptr->clear();
843
844
5.15k
    size_t dest_size = block->columns();
845
    // do filter
846
5.15k
    block->insert(ColumnWithTypeAndName(std::move(filter_column), std::make_shared<DataTypeUInt8>(),
847
5.15k
                                        "filter column"));
848
5.15k
    RETURN_IF_ERROR(Block::filter_block(block, dest_size, dest_size));
849
850
5.15k
    _counter.num_rows_filtered += rows - block->rows();
851
5.15k
    return Status::OK();
852
5.15k
}
853
854
5.88k
Status FileScanner::_truncate_char_or_varchar_columns(Block* block) {
855
    // Truncate char columns or varchar columns if size is smaller than file columns
856
    // or not found in the file column schema.
857
5.88k
    if (!_state->query_options().truncate_char_or_varchar_columns) {
858
5.88k
        return Status::OK();
859
5.88k
    }
860
0
    int idx = 0;
861
0
    for (auto* slot_desc : _real_tuple_desc->slots()) {
862
0
        const auto& type = slot_desc->type();
863
0
        if (type->get_primitive_type() != TYPE_VARCHAR && type->get_primitive_type() != TYPE_CHAR) {
864
0
            ++idx;
865
0
            continue;
866
0
        }
867
0
        auto iter = _source_file_col_name_types.find(slot_desc->col_name());
868
0
        if (iter != _source_file_col_name_types.end()) {
869
0
            const auto file_type_desc = _source_file_col_name_types[slot_desc->col_name()];
870
0
            int l = -1;
871
0
            if (auto* ftype = check_and_get_data_type<DataTypeString>(
872
0
                        remove_nullable(file_type_desc).get())) {
873
0
                l = ftype->len();
874
0
            }
875
0
            if ((assert_cast<const DataTypeString*>(remove_nullable(type).get())->len() > 0) &&
876
0
                (assert_cast<const DataTypeString*>(remove_nullable(type).get())->len() < l ||
877
0
                 l < 0)) {
878
0
                _truncate_char_or_varchar_column(
879
0
                        block, idx,
880
0
                        assert_cast<const DataTypeString*>(remove_nullable(type).get())->len());
881
0
            }
882
0
        } else {
883
0
            _truncate_char_or_varchar_column(
884
0
                    block, idx,
885
0
                    assert_cast<const DataTypeString*>(remove_nullable(type).get())->len());
886
0
        }
887
0
        ++idx;
888
0
    }
889
0
    return Status::OK();
890
5.88k
}
891
892
// VARCHAR substring(VARCHAR str, INT pos[, INT len])
893
0
void FileScanner::_truncate_char_or_varchar_column(Block* block, int idx, int len) {
894
0
    auto int_type = std::make_shared<DataTypeInt32>();
895
0
    uint32_t num_columns_without_result = block->columns();
896
0
    const ColumnNullable* col_nullable =
897
0
            assert_cast<const ColumnNullable*>(block->get_by_position(idx).column.get());
898
0
    const ColumnPtr& string_column_ptr = col_nullable->get_nested_column_ptr();
899
0
    ColumnPtr null_map_column_ptr = col_nullable->get_null_map_column_ptr();
900
0
    block->replace_by_position(idx, std::move(string_column_ptr));
901
0
    block->insert({int_type->create_column_const(block->rows(), to_field<TYPE_INT>(1)), int_type,
902
0
                   "const 1"}); // pos is 1
903
0
    block->insert({int_type->create_column_const(block->rows(), to_field<TYPE_INT>(len)), int_type,
904
0
                   fmt::format("const {}", len)});                          // len
905
0
    block->insert({nullptr, std::make_shared<DataTypeString>(), "result"}); // result column
906
0
    ColumnNumbers temp_arguments(3);
907
0
    temp_arguments[0] = idx;                            // str column
908
0
    temp_arguments[1] = num_columns_without_result;     // pos
909
0
    temp_arguments[2] = num_columns_without_result + 1; // len
910
0
    uint32_t result_column_id = num_columns_without_result + 2;
911
912
0
    SubstringUtil::substring_execute(*block, temp_arguments, result_column_id, block->rows());
913
0
    auto res = ColumnNullable::create(block->get_by_position(result_column_id).column,
914
0
                                      null_map_column_ptr);
915
0
    block->replace_by_position(idx, std::move(res));
916
0
    Block::erase_useless_column(block, num_columns_without_result);
917
0
}
918
919
13
Status FileScanner::_create_row_id_column_iterator() {
920
13
    auto& id_file_map = _state->get_id_file_map();
921
13
    auto file_id = id_file_map->get_file_mapping_id(
922
13
            std::make_shared<FileMapping>(((FileScanLocalState*)_local_state)->parent_id(),
923
13
                                          _current_range, _should_enable_file_meta_cache()));
924
13
    _row_id_column_iterator_pair.first = std::make_shared<RowIdColumnIteratorV2>(
925
13
            IdManager::ID_VERSION, BackendOptions::get_backend_id(), file_id);
926
13
    return Status::OK();
927
13
}
928
929
5.34k
Status FileScanner::_get_next_reader() {
930
5.34k
    while (true) {
931
5.34k
        if (_cur_reader) {
932
2.66k
            _cur_reader->collect_profile_before_close();
933
2.66k
            RETURN_IF_ERROR(_cur_reader->close());
934
2.66k
            _state->update_num_finished_scan_range(1);
935
2.66k
        }
936
5.34k
        _cur_reader.reset(nullptr);
937
5.34k
        _src_block_init = false;
938
5.34k
        bool has_next = _first_scan_range;
939
5.34k
        if (!_first_scan_range) {
940
2.66k
            RETURN_IF_ERROR(_split_source->get_next(&has_next, &_current_range));
941
2.66k
        }
942
5.34k
        _first_scan_range = false;
943
5.34k
        if (!has_next || _should_stop) {
944
2.66k
            _scanner_eof = true;
945
2.66k
            return Status::OK();
946
2.66k
        }
947
948
2.67k
        const TFileRangeDesc& range = _current_range;
949
2.67k
        _current_range_path = range.path;
950
951
2.67k
        if (!_partition_slot_descs.empty()) {
952
            // we need get partition columns first for runtime filter partition pruning
953
6
            RETURN_IF_ERROR(_generate_partition_columns());
954
955
6
            if (_state->query_options().enable_runtime_filter_partition_prune) {
956
                // if enable_runtime_filter_partition_prune is true, we need to check whether this range can be filtered out
957
                // by runtime filter partition prune
958
6
                if (_push_down_conjuncts.size() < _conjuncts.size()) {
959
                    // there are new runtime filters, need to re-init runtime filter partition pruning ctxs
960
0
                    _init_runtime_filter_partition_prune_ctxs();
961
0
                }
962
963
6
                bool can_filter_all = false;
964
6
                RETURN_IF_ERROR(_process_runtime_filters_partition_prune(can_filter_all));
965
6
                if (can_filter_all) {
966
                    // this range can be filtered out by runtime filter partition pruning
967
                    // so we need to skip this range
968
0
                    COUNTER_UPDATE(_runtime_filter_partition_pruned_range_counter, 1);
969
0
                    continue;
970
0
                }
971
6
            }
972
6
        }
973
974
        // create reader for specific format
975
2.67k
        Status init_status = Status::OK();
976
2.67k
        TFileFormatType::type format_type = _get_current_format_type();
977
        // for compatibility, this logic is deprecated in 3.1
978
2.67k
        if (format_type == TFileFormatType::FORMAT_JNI && range.__isset.table_format_params) {
979
4
            if (range.table_format_params.table_format_type == "paimon" &&
980
4
                !range.table_format_params.paimon_params.__isset.paimon_split) {
981
                // use native reader
982
0
                auto format = range.table_format_params.paimon_params.file_format;
983
0
                if (format == "orc") {
984
0
                    format_type = TFileFormatType::FORMAT_ORC;
985
0
                } else if (format == "parquet") {
986
0
                    format_type = TFileFormatType::FORMAT_PARQUET;
987
0
                } else {
988
0
                    return Status::InternalError("Not supported paimon file format: {}", format);
989
0
                }
990
0
            }
991
4
        }
992
993
        // JNI reader can only push down column value range
994
2.67k
        bool push_down_predicates = !_is_load && format_type != TFileFormatType::FORMAT_JNI;
995
2.67k
        bool need_to_get_parsed_schema = false;
996
2.67k
        switch (format_type) {
997
5
        case TFileFormatType::FORMAT_JNI: {
998
5
            if (range.__isset.table_format_params &&
999
5
                range.table_format_params.table_format_type == "max_compute") {
1000
0
                const auto* mc_desc = static_cast<const MaxComputeTableDescriptor*>(
1001
0
                        _real_tuple_desc->table_desc());
1002
0
                if (!mc_desc->init_status()) {
1003
0
                    return mc_desc->init_status();
1004
0
                }
1005
0
                std::unique_ptr<MaxComputeJniReader> mc_reader = MaxComputeJniReader::create_unique(
1006
0
                        mc_desc, range.table_format_params.max_compute_params, _file_slot_descs,
1007
0
                        range, _state, _profile);
1008
0
                init_status = mc_reader->init_reader();
1009
0
                _cur_reader = std::move(mc_reader);
1010
5
            } else if (range.__isset.table_format_params &&
1011
5
                       range.table_format_params.table_format_type == "paimon") {
1012
0
                if (_state->query_options().__isset.enable_paimon_cpp_reader &&
1013
0
                    _state->query_options().enable_paimon_cpp_reader) {
1014
0
                    auto cpp_reader = PaimonCppReader::create_unique(_file_slot_descs, _state,
1015
0
                                                                     _profile, range, _params);
1016
0
                    cpp_reader->set_push_down_agg_type(_get_push_down_agg_type());
1017
0
                    if (!_is_load && !_push_down_conjuncts.empty()) {
1018
0
                        PaimonPredicateConverter predicate_converter(_file_slot_descs, _state);
1019
0
                        auto predicate = predicate_converter.build(_push_down_conjuncts);
1020
0
                        if (predicate) {
1021
0
                            cpp_reader->set_predicate(std::move(predicate));
1022
0
                        }
1023
0
                    }
1024
0
                    init_status = cpp_reader->init_reader();
1025
0
                    _cur_reader = std::move(cpp_reader);
1026
0
                } else {
1027
0
                    _cur_reader = PaimonJniReader::create_unique(_file_slot_descs, _state, _profile,
1028
0
                                                                 range, _params);
1029
0
                    init_status = ((PaimonJniReader*)(_cur_reader.get()))->init_reader();
1030
0
                }
1031
5
            } else if (range.__isset.table_format_params &&
1032
5
                       range.table_format_params.table_format_type == "hudi") {
1033
0
                _cur_reader = HudiJniReader::create_unique(*_params,
1034
0
                                                           range.table_format_params.hudi_params,
1035
0
                                                           _file_slot_descs, _state, _profile);
1036
0
                init_status = ((HudiJniReader*)_cur_reader.get())->init_reader();
1037
1038
5
            } else if (range.__isset.table_format_params &&
1039
5
                       range.table_format_params.table_format_type == "trino_connector") {
1040
0
                _cur_reader = TrinoConnectorJniReader::create_unique(_file_slot_descs, _state,
1041
0
                                                                     _profile, range);
1042
0
                init_status = ((TrinoConnectorJniReader*)(_cur_reader.get()))->init_reader();
1043
5
            } else if (range.__isset.table_format_params &&
1044
5
                       range.table_format_params.table_format_type == "jdbc") {
1045
                // Extract jdbc params from table_format_params
1046
4
                std::map<std::string, std::string> jdbc_params(
1047
4
                        range.table_format_params.jdbc_params.begin(),
1048
4
                        range.table_format_params.jdbc_params.end());
1049
4
                _cur_reader = JdbcJniReader::create_unique(_file_slot_descs, _state, _profile,
1050
4
                                                           jdbc_params);
1051
4
                init_status = ((JdbcJniReader*)(_cur_reader.get()))->init_reader();
1052
4
            }
1053
            // Set col_name_to_block_idx for JNI readers to avoid repeated map creation
1054
5
            if (_cur_reader) {
1055
4
                if (auto* jni_reader = dynamic_cast<JniReader*>(_cur_reader.get())) {
1056
4
                    jni_reader->set_col_name_to_block_idx(&_src_block_name_to_idx);
1057
4
                }
1058
4
            }
1059
5
            break;
1060
5
        }
1061
105
        case TFileFormatType::FORMAT_PARQUET: {
1062
105
            auto file_meta_cache_ptr = _should_enable_file_meta_cache()
1063
105
                                               ? ExecEnv::GetInstance()->file_meta_cache()
1064
105
                                               : nullptr;
1065
105
            std::unique_ptr<ParquetReader> parquet_reader = ParquetReader::create_unique(
1066
105
                    _profile, *_params, range, _state->query_options().batch_size,
1067
105
                    &_state->timezone_obj(), _io_ctx.get(), _state, file_meta_cache_ptr,
1068
105
                    _state->query_options().enable_parquet_lazy_mat);
1069
1070
105
            if (_row_id_column_iterator_pair.second != -1) {
1071
8
                RETURN_IF_ERROR(_create_row_id_column_iterator());
1072
8
                parquet_reader->set_row_id_column_iterator(_row_id_column_iterator_pair);
1073
8
            }
1074
1075
            // ATTN: the push down agg type may be set back to NONE,
1076
            // see IcebergTableReader::init_row_filters for example.
1077
105
            parquet_reader->set_push_down_agg_type(_get_push_down_agg_type());
1078
105
            if (push_down_predicates) {
1079
87
                RETURN_IF_ERROR(_process_late_arrival_conjuncts());
1080
87
            }
1081
105
            RETURN_IF_ERROR(_init_parquet_reader(std::move(parquet_reader), file_meta_cache_ptr));
1082
1083
105
            need_to_get_parsed_schema = true;
1084
105
            break;
1085
105
        }
1086
102
        case TFileFormatType::FORMAT_ORC: {
1087
102
            auto file_meta_cache_ptr = _should_enable_file_meta_cache()
1088
102
                                               ? ExecEnv::GetInstance()->file_meta_cache()
1089
102
                                               : nullptr;
1090
102
            std::unique_ptr<OrcReader> orc_reader = OrcReader::create_unique(
1091
102
                    _profile, _state, *_params, range, _state->query_options().batch_size,
1092
102
                    _state->timezone(), _io_ctx.get(), file_meta_cache_ptr,
1093
102
                    _state->query_options().enable_orc_lazy_mat);
1094
102
            if (_row_id_column_iterator_pair.second != -1) {
1095
5
                RETURN_IF_ERROR(_create_row_id_column_iterator());
1096
5
                orc_reader->set_row_id_column_iterator(_row_id_column_iterator_pair);
1097
5
            }
1098
1099
102
            orc_reader->set_push_down_agg_type(_get_push_down_agg_type());
1100
102
            if (push_down_predicates) {
1101
91
                RETURN_IF_ERROR(_process_late_arrival_conjuncts());
1102
91
            }
1103
102
            RETURN_IF_ERROR(_init_orc_reader(std::move(orc_reader), file_meta_cache_ptr));
1104
1105
102
            need_to_get_parsed_schema = true;
1106
102
            break;
1107
102
        }
1108
1.94k
        case TFileFormatType::FORMAT_CSV_PLAIN:
1109
1.94k
        case TFileFormatType::FORMAT_CSV_GZ:
1110
1.94k
        case TFileFormatType::FORMAT_CSV_BZ2:
1111
1.94k
        case TFileFormatType::FORMAT_CSV_LZ4FRAME:
1112
1.94k
        case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
1113
1.94k
        case TFileFormatType::FORMAT_CSV_LZOP:
1114
1.94k
        case TFileFormatType::FORMAT_CSV_DEFLATE:
1115
1.94k
        case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
1116
2.02k
        case TFileFormatType::FORMAT_PROTO: {
1117
2.02k
            auto reader = CsvReader::create_unique(_state, _profile, &_counter, *_params, range,
1118
2.02k
                                                   _file_slot_descs, _io_ctx.get());
1119
1120
2.02k
            init_status = reader->init_reader(_is_load);
1121
2.02k
            _cur_reader = std::move(reader);
1122
2.02k
            break;
1123
1.94k
        }
1124
3
        case TFileFormatType::FORMAT_TEXT: {
1125
3
            auto reader = TextReader::create_unique(_state, _profile, &_counter, *_params, range,
1126
3
                                                    _file_slot_descs, _io_ctx.get());
1127
3
            init_status = reader->init_reader(_is_load);
1128
3
            _cur_reader = std::move(reader);
1129
3
            break;
1130
1.94k
        }
1131
424
        case TFileFormatType::FORMAT_JSON: {
1132
424
            _cur_reader =
1133
424
                    NewJsonReader::create_unique(_state, _profile, &_counter, *_params, range,
1134
424
                                                 _file_slot_descs, &_scanner_eof, _io_ctx.get());
1135
424
            init_status = ((NewJsonReader*)(_cur_reader.get()))
1136
424
                                  ->init_reader(_col_default_value_ctx, _is_load);
1137
424
            break;
1138
1.94k
        }
1139
1140
0
        case TFileFormatType::FORMAT_WAL: {
1141
0
            _cur_reader = WalReader::create_unique(_state);
1142
0
            init_status = ((WalReader*)(_cur_reader.get()))->init_reader(_output_tuple_desc);
1143
0
            break;
1144
1.94k
        }
1145
3
        case TFileFormatType::FORMAT_NATIVE: {
1146
3
            auto reader =
1147
3
                    NativeReader::create_unique(_profile, *_params, range, _io_ctx.get(), _state);
1148
3
            init_status = reader->init_reader();
1149
3
            _cur_reader = std::move(reader);
1150
3
            need_to_get_parsed_schema = false;
1151
3
            break;
1152
1.94k
        }
1153
10
        case TFileFormatType::FORMAT_ARROW: {
1154
10
            if (range.__isset.table_format_params &&
1155
10
                range.table_format_params.table_format_type == "remote_doris") {
1156
0
                _cur_reader =
1157
0
                        RemoteDorisReader::create_unique(_file_slot_descs, _state, _profile, range);
1158
0
                init_status = ((RemoteDorisReader*)(_cur_reader.get()))->init_reader();
1159
0
                if (_cur_reader) {
1160
0
                    static_cast<RemoteDorisReader*>(_cur_reader.get())
1161
0
                            ->set_col_name_to_block_idx(&_src_block_name_to_idx);
1162
0
                }
1163
10
            } else {
1164
10
                _cur_reader =
1165
10
                        ArrowStreamReader::create_unique(_state, _profile, &_counter, *_params,
1166
10
                                                         range, _file_slot_descs, _io_ctx.get());
1167
10
                init_status = ((ArrowStreamReader*)(_cur_reader.get()))->init_reader();
1168
10
            }
1169
10
            break;
1170
1.94k
        }
1171
0
        default:
1172
0
            return Status::NotSupported("Not supported create reader for file format: {}.",
1173
0
                                        to_string(_params->format_type));
1174
2.67k
        }
1175
1176
2.67k
        if (_cur_reader == nullptr) {
1177
1
            return Status::NotSupported(
1178
1
                    "Not supported create reader for table format: {} / file format: {}.",
1179
1
                    range.__isset.table_format_params ? range.table_format_params.table_format_type
1180
1
                                                      : "NotSet",
1181
1
                    to_string(_params->format_type));
1182
1
        }
1183
2.67k
        COUNTER_UPDATE(_file_counter, 1);
1184
        // The FileScanner for external table may try to open not exist files,
1185
        // Because FE file cache for external table may out of date.
1186
        // So, NOT_FOUND for FileScanner is not a fail case.
1187
        // Will remove this after file reader refactor.
1188
2.67k
        if (init_status.is<END_OF_FILE>()) {
1189
0
            COUNTER_UPDATE(_empty_file_counter, 1);
1190
0
            continue;
1191
2.67k
        } else if (init_status.is<ErrorCode::NOT_FOUND>()) {
1192
0
            if (config::ignore_not_found_file_in_external_table) {
1193
0
                COUNTER_UPDATE(_not_found_file_counter, 1);
1194
0
                continue;
1195
0
            }
1196
0
            return Status::InternalError("failed to find reader, err: {}", init_status.to_string());
1197
2.67k
        } else if (!init_status.ok()) {
1198
1
            return Status::InternalError("failed to init reader, err: {}", init_status.to_string());
1199
1
        }
1200
1201
2.67k
        _cur_reader->set_push_down_agg_type(_get_push_down_agg_type());
1202
2.67k
        if (_get_push_down_agg_type() == TPushAggOp::type::COUNT &&
1203
2.67k
            range.__isset.table_format_params &&
1204
2.67k
            range.table_format_params.table_level_row_count >= 0) {
1205
            // This is a table level count push down operation, no need to call
1206
            // _set_fill_or_truncate_columns.
1207
            // in _set_fill_or_truncate_columns, we will use [range.start_offset, end offset]
1208
            // to filter the row group. But if this is count push down, the offset is undefined,
1209
            // causing incorrect row group filter and may return empty result.
1210
2.67k
        } else {
1211
2.67k
            Status status = _set_fill_or_truncate_columns(need_to_get_parsed_schema);
1212
2.67k
            if (status.is<END_OF_FILE>()) { // all parquet row groups are filtered
1213
0
                continue;
1214
2.67k
            } else if (!status.ok()) {
1215
0
                return Status::InternalError("failed to set_fill_or_truncate_columns, err: {}",
1216
0
                                             status.to_string());
1217
0
            }
1218
2.67k
        }
1219
2.67k
        _cur_reader_eof = false;
1220
2.67k
        break;
1221
2.67k
    }
1222
2.67k
    return Status::OK();
1223
5.34k
}
1224
1225
Status FileScanner::_init_parquet_reader(std::unique_ptr<ParquetReader>&& parquet_reader,
1226
127
                                         FileMetaCache* file_meta_cache_ptr) {
1227
127
    const TFileRangeDesc& range = _current_range;
1228
127
    Status init_status = Status::OK();
1229
1230
127
    phmap::flat_hash_map<int, std::vector<std::shared_ptr<ColumnPredicate>>> slot_id_to_predicates =
1231
127
            _local_state
1232
127
                    ? _local_state->cast<FileScanLocalState>()._slot_id_to_predicates
1233
127
                    : phmap::flat_hash_map<int, std::vector<std::shared_ptr<ColumnPredicate>>> {};
1234
127
    if (range.__isset.table_format_params &&
1235
127
        range.table_format_params.table_format_type == "iceberg") {
1236
0
        std::unique_ptr<IcebergParquetReader> iceberg_reader = IcebergParquetReader::create_unique(
1237
0
                std::move(parquet_reader), _profile, _state, *_params, range, _kv_cache,
1238
0
                _io_ctx.get(), file_meta_cache_ptr);
1239
0
        if (_need_iceberg_rowid_column) {
1240
0
            iceberg_reader->set_need_row_id_column(true);
1241
0
        }
1242
0
        init_status = iceberg_reader->init_reader(
1243
0
                _file_col_names, &_src_block_name_to_idx, _push_down_conjuncts,
1244
0
                slot_id_to_predicates, _real_tuple_desc, _default_val_row_desc.get(),
1245
0
                _col_name_to_slot_id, &_not_single_slot_filter_conjuncts,
1246
0
                &_slot_id_to_filter_conjuncts);
1247
0
        _cur_reader = std::move(iceberg_reader);
1248
127
    } else if (range.__isset.table_format_params &&
1249
127
               range.table_format_params.table_format_type == "paimon") {
1250
0
        std::unique_ptr<PaimonParquetReader> paimon_reader = PaimonParquetReader::create_unique(
1251
0
                std::move(parquet_reader), _profile, _state, *_params, range, _kv_cache,
1252
0
                _io_ctx.get(), file_meta_cache_ptr);
1253
0
        init_status = paimon_reader->init_reader(
1254
0
                _file_col_names, &_src_block_name_to_idx, _push_down_conjuncts,
1255
0
                slot_id_to_predicates, _real_tuple_desc, _default_val_row_desc.get(),
1256
0
                _col_name_to_slot_id, &_not_single_slot_filter_conjuncts,
1257
0
                &_slot_id_to_filter_conjuncts);
1258
0
        RETURN_IF_ERROR(paimon_reader->init_row_filters());
1259
0
        _cur_reader = std::move(paimon_reader);
1260
127
    } else if (range.__isset.table_format_params &&
1261
127
               range.table_format_params.table_format_type == "hudi") {
1262
0
        std::unique_ptr<HudiParquetReader> hudi_reader = HudiParquetReader::create_unique(
1263
0
                std::move(parquet_reader), _profile, _state, *_params, range, _io_ctx.get(),
1264
0
                file_meta_cache_ptr);
1265
0
        init_status = hudi_reader->init_reader(
1266
0
                _file_col_names, &_src_block_name_to_idx, _push_down_conjuncts,
1267
0
                slot_id_to_predicates, _real_tuple_desc, _default_val_row_desc.get(),
1268
0
                _col_name_to_slot_id, &_not_single_slot_filter_conjuncts,
1269
0
                &_slot_id_to_filter_conjuncts);
1270
0
        _cur_reader = std::move(hudi_reader);
1271
127
    } else if (range.table_format_params.table_format_type == "hive") {
1272
14
        auto hive_reader = HiveParquetReader::create_unique(std::move(parquet_reader), _profile,
1273
14
                                                            _state, *_params, range, _io_ctx.get(),
1274
14
                                                            &_is_file_slot, file_meta_cache_ptr);
1275
14
        init_status = hive_reader->init_reader(
1276
14
                _file_col_names, &_src_block_name_to_idx, _push_down_conjuncts,
1277
14
                slot_id_to_predicates, _real_tuple_desc, _default_val_row_desc.get(),
1278
14
                _col_name_to_slot_id, &_not_single_slot_filter_conjuncts,
1279
14
                &_slot_id_to_filter_conjuncts);
1280
14
        _cur_reader = std::move(hive_reader);
1281
113
    } else if (range.table_format_params.table_format_type == "tvf") {
1282
95
        const FieldDescriptor* parquet_meta = nullptr;
1283
95
        RETURN_IF_ERROR(parquet_reader->get_file_metadata_schema(&parquet_meta));
1284
95
        DCHECK(parquet_meta != nullptr);
1285
1286
        // TVF will first `get_parsed_schema` to obtain file information from BE, and FE will convert
1287
        // the column names to lowercase (because the query process is case-insensitive),
1288
        // so the lowercase file column names are used here to match the read columns.
1289
95
        std::shared_ptr<TableSchemaChangeHelper::Node> tvf_info_node = nullptr;
1290
95
        RETURN_IF_ERROR(TableSchemaChangeHelper::BuildTableInfoUtil::by_parquet_name(
1291
95
                _real_tuple_desc, *parquet_meta, tvf_info_node));
1292
95
        init_status = parquet_reader->init_reader(
1293
95
                _file_col_names, &_src_block_name_to_idx, _push_down_conjuncts,
1294
95
                slot_id_to_predicates, _real_tuple_desc, _default_val_row_desc.get(),
1295
95
                _col_name_to_slot_id, &_not_single_slot_filter_conjuncts,
1296
95
                &_slot_id_to_filter_conjuncts, tvf_info_node);
1297
95
        _cur_reader = std::move(parquet_reader);
1298
95
    } else if (_is_load) {
1299
18
        const FieldDescriptor* parquet_meta = nullptr;
1300
18
        RETURN_IF_ERROR(parquet_reader->get_file_metadata_schema(&parquet_meta));
1301
18
        DCHECK(parquet_meta != nullptr);
1302
1303
        // Load is case-insensitive, so you to match the columns in the file.
1304
18
        std::map<std::string, std::string> file_lower_name_to_native;
1305
416
        for (const auto& parquet_field : parquet_meta->get_fields_schema()) {
1306
416
            file_lower_name_to_native.emplace(doris::to_lower(parquet_field.name),
1307
416
                                              parquet_field.name);
1308
416
        }
1309
18
        auto load_info_node = std::make_shared<TableSchemaChangeHelper::StructNode>();
1310
405
        for (const auto slot : _real_tuple_desc->slots()) {
1311
405
            if (file_lower_name_to_native.contains(slot->col_name())) {
1312
404
                load_info_node->add_children(slot->col_name(),
1313
404
                                             file_lower_name_to_native[slot->col_name()],
1314
404
                                             TableSchemaChangeHelper::ConstNode::get_instance());
1315
                // For Load, `file_scanner` will create block columns using the file type,
1316
                // there is no schema change when reading inside the struct,
1317
                // so use `TableSchemaChangeHelper::ConstNode`.
1318
404
            } else {
1319
1
                load_info_node->add_not_exist_children(slot->col_name());
1320
1
            }
1321
405
        }
1322
1323
18
        init_status = parquet_reader->init_reader(
1324
18
                _file_col_names, &_src_block_name_to_idx, _push_down_conjuncts,
1325
18
                slot_id_to_predicates, _real_tuple_desc, _default_val_row_desc.get(),
1326
18
                _col_name_to_slot_id, &_not_single_slot_filter_conjuncts,
1327
18
                &_slot_id_to_filter_conjuncts, load_info_node);
1328
18
        _cur_reader = std::move(parquet_reader);
1329
18
    }
1330
1331
127
    return init_status;
1332
127
}
1333
1334
Status FileScanner::_init_orc_reader(std::unique_ptr<OrcReader>&& orc_reader,
1335
118
                                     FileMetaCache* file_meta_cache_ptr) {
1336
118
    const TFileRangeDesc& range = _current_range;
1337
118
    Status init_status = Status::OK();
1338
1339
118
    if (range.__isset.table_format_params &&
1340
118
        range.table_format_params.table_format_type == "transactional_hive") {
1341
0
        std::unique_ptr<TransactionalHiveReader> tran_orc_reader =
1342
0
                TransactionalHiveReader::create_unique(std::move(orc_reader), _profile, _state,
1343
0
                                                       *_params, range, _io_ctx.get(),
1344
0
                                                       file_meta_cache_ptr);
1345
0
        init_status = tran_orc_reader->init_reader(
1346
0
                _file_col_names, &_src_block_name_to_idx, _push_down_conjuncts, _real_tuple_desc,
1347
0
                _default_val_row_desc.get(), &_not_single_slot_filter_conjuncts,
1348
0
                &_slot_id_to_filter_conjuncts);
1349
0
        RETURN_IF_ERROR(tran_orc_reader->init_row_filters());
1350
0
        _cur_reader = std::move(tran_orc_reader);
1351
118
    } else if (range.__isset.table_format_params &&
1352
118
               range.table_format_params.table_format_type == "iceberg") {
1353
0
        std::unique_ptr<IcebergOrcReader> iceberg_reader = IcebergOrcReader::create_unique(
1354
0
                std::move(orc_reader), _profile, _state, *_params, range, _kv_cache, _io_ctx.get(),
1355
0
                file_meta_cache_ptr);
1356
1357
0
        if (_need_iceberg_rowid_column) {
1358
0
            iceberg_reader->set_need_row_id_column(true);
1359
0
        }
1360
0
        init_status = iceberg_reader->init_reader(
1361
0
                _file_col_names, &_src_block_name_to_idx, _push_down_conjuncts, _real_tuple_desc,
1362
0
                _default_val_row_desc.get(), _col_name_to_slot_id,
1363
0
                &_not_single_slot_filter_conjuncts, &_slot_id_to_filter_conjuncts);
1364
0
        _cur_reader = std::move(iceberg_reader);
1365
118
    } else if (range.__isset.table_format_params &&
1366
118
               range.table_format_params.table_format_type == "paimon") {
1367
0
        std::unique_ptr<PaimonOrcReader> paimon_reader = PaimonOrcReader::create_unique(
1368
0
                std::move(orc_reader), _profile, _state, *_params, range, _kv_cache, _io_ctx.get(),
1369
0
                file_meta_cache_ptr);
1370
1371
0
        init_status = paimon_reader->init_reader(
1372
0
                _file_col_names, &_src_block_name_to_idx, _push_down_conjuncts, _real_tuple_desc,
1373
0
                _default_val_row_desc.get(), &_not_single_slot_filter_conjuncts,
1374
0
                &_slot_id_to_filter_conjuncts);
1375
0
        RETURN_IF_ERROR(paimon_reader->init_row_filters());
1376
0
        _cur_reader = std::move(paimon_reader);
1377
118
    } else if (range.__isset.table_format_params &&
1378
118
               range.table_format_params.table_format_type == "hudi") {
1379
0
        std::unique_ptr<HudiOrcReader> hudi_reader =
1380
0
                HudiOrcReader::create_unique(std::move(orc_reader), _profile, _state, *_params,
1381
0
                                             range, _io_ctx.get(), file_meta_cache_ptr);
1382
1383
0
        init_status = hudi_reader->init_reader(
1384
0
                _file_col_names, &_src_block_name_to_idx, _push_down_conjuncts, _real_tuple_desc,
1385
0
                _default_val_row_desc.get(), &_not_single_slot_filter_conjuncts,
1386
0
                &_slot_id_to_filter_conjuncts);
1387
0
        _cur_reader = std::move(hudi_reader);
1388
118
    } else if (range.__isset.table_format_params &&
1389
118
               range.table_format_params.table_format_type == "hive") {
1390
11
        std::unique_ptr<HiveOrcReader> hive_reader = HiveOrcReader::create_unique(
1391
11
                std::move(orc_reader), _profile, _state, *_params, range, _io_ctx.get(),
1392
11
                &_is_file_slot, file_meta_cache_ptr);
1393
1394
11
        init_status = hive_reader->init_reader(
1395
11
                _file_col_names, &_src_block_name_to_idx, _push_down_conjuncts, _real_tuple_desc,
1396
11
                _default_val_row_desc.get(), &_not_single_slot_filter_conjuncts,
1397
11
                &_slot_id_to_filter_conjuncts);
1398
11
        _cur_reader = std::move(hive_reader);
1399
107
    } else if (range.__isset.table_format_params &&
1400
107
               range.table_format_params.table_format_type == "tvf") {
1401
96
        const orc::Type* orc_type_ptr = nullptr;
1402
96
        RETURN_IF_ERROR(orc_reader->get_file_type(&orc_type_ptr));
1403
1404
96
        std::shared_ptr<TableSchemaChangeHelper::Node> tvf_info_node = nullptr;
1405
96
        RETURN_IF_ERROR(TableSchemaChangeHelper::BuildTableInfoUtil::by_orc_name(
1406
96
                _real_tuple_desc, orc_type_ptr, tvf_info_node));
1407
96
        init_status = orc_reader->init_reader(
1408
96
                &_file_col_names, &_src_block_name_to_idx, _push_down_conjuncts, false,
1409
96
                _real_tuple_desc, _default_val_row_desc.get(), &_not_single_slot_filter_conjuncts,
1410
96
                &_slot_id_to_filter_conjuncts, tvf_info_node);
1411
96
        _cur_reader = std::move(orc_reader);
1412
96
    } else if (_is_load) {
1413
11
        const orc::Type* orc_type_ptr = nullptr;
1414
11
        RETURN_IF_ERROR(orc_reader->get_file_type(&orc_type_ptr));
1415
1416
11
        std::map<std::string, std::string> file_lower_name_to_native;
1417
359
        for (uint64_t idx = 0; idx < orc_type_ptr->getSubtypeCount(); idx++) {
1418
348
            file_lower_name_to_native.emplace(doris::to_lower(orc_type_ptr->getFieldName(idx)),
1419
348
                                              orc_type_ptr->getFieldName(idx));
1420
348
        }
1421
1422
11
        auto load_info_node = std::make_shared<TableSchemaChangeHelper::StructNode>();
1423
348
        for (const auto slot : _real_tuple_desc->slots()) {
1424
348
            if (file_lower_name_to_native.contains(slot->col_name())) {
1425
348
                load_info_node->add_children(slot->col_name(),
1426
348
                                             file_lower_name_to_native[slot->col_name()],
1427
348
                                             TableSchemaChangeHelper::ConstNode::get_instance());
1428
348
            } else {
1429
0
                load_info_node->add_not_exist_children(slot->col_name());
1430
0
            }
1431
348
        }
1432
11
        init_status = orc_reader->init_reader(
1433
11
                &_file_col_names, &_src_block_name_to_idx, _push_down_conjuncts, false,
1434
11
                _real_tuple_desc, _default_val_row_desc.get(), &_not_single_slot_filter_conjuncts,
1435
11
                &_slot_id_to_filter_conjuncts, load_info_node);
1436
11
        _cur_reader = std::move(orc_reader);
1437
11
    }
1438
1439
118
    return init_status;
1440
118
}
1441
1442
2.71k
Status FileScanner::_set_fill_or_truncate_columns(bool need_to_get_parsed_schema) {
1443
2.71k
    _missing_cols.clear();
1444
2.71k
    _slot_lower_name_to_col_type.clear();
1445
2.71k
    std::unordered_map<std::string, DataTypePtr> name_to_col_type;
1446
2.71k
    RETURN_IF_ERROR(_cur_reader->get_columns(&name_to_col_type, &_missing_cols));
1447
2.71k
    if (_need_iceberg_rowid_column && _current_range.__isset.table_format_params &&
1448
2.71k
        _current_range.table_format_params.table_format_type == "iceberg") {
1449
0
        _missing_cols.erase(BeConsts::ICEBERG_ROWID_COL);
1450
0
        _missing_cols.erase(to_lower(BeConsts::ICEBERG_ROWID_COL));
1451
0
    }
1452
22.1k
    for (const auto& [col_name, col_type] : name_to_col_type) {
1453
22.1k
        auto col_name_lower = to_lower(col_name);
1454
22.1k
        if (_partition_col_descs.contains(col_name_lower)) {
1455
            /*
1456
             * `_slot_lower_name_to_col_type` is used by `_init_src_block` and `_cast_to_input_block` during LOAD to
1457
             * generate columns of the corresponding type, which records the columns existing in the file.
1458
             *
1459
             * When a column in `COLUMNS FROM PATH` exists in a file column, the column type in the block will
1460
             * not match the slot type in `_output_tuple_desc`, causing an error when
1461
             * Serde `deserialize_one_cell_from_json` fills the partition values.
1462
             *
1463
             * So for partition column not need fill _slot_lower_name_to_col_type.
1464
             */
1465
4
            continue;
1466
4
        }
1467
22.1k
        _slot_lower_name_to_col_type.emplace(col_name_lower, col_type);
1468
22.1k
    }
1469
1470
2.71k
    if (!_fill_partition_from_path && config::enable_iceberg_partition_column_fallback) {
1471
        // check if the cols of _partition_col_descs are in _missing_cols
1472
        // if so, set _fill_partition_from_path to true and remove the col from _missing_cols
1473
0
        for (const auto& [col_name, col_type] : _partition_col_descs) {
1474
0
            if (_missing_cols.contains(col_name)) {
1475
0
                _fill_partition_from_path = true;
1476
0
                _missing_cols.erase(col_name);
1477
0
            }
1478
0
        }
1479
0
    }
1480
1481
2.71k
    RETURN_IF_ERROR(_generate_missing_columns());
1482
2.71k
    if (_fill_partition_from_path) {
1483
2.71k
        RETURN_IF_ERROR(_cur_reader->set_fill_columns(_partition_col_descs, _missing_col_descs));
1484
2.71k
    } else {
1485
        // If the partition columns are not from path, we only fill the missing columns.
1486
1
        RETURN_IF_ERROR(_cur_reader->set_fill_columns({}, _missing_col_descs));
1487
1
    }
1488
2.71k
    if (VLOG_NOTICE_IS_ON && !_missing_cols.empty() && _is_load) {
1489
0
        fmt::memory_buffer col_buf;
1490
0
        for (auto& col : _missing_cols) {
1491
0
            fmt::format_to(col_buf, " {}", col);
1492
0
        }
1493
0
        VLOG_NOTICE << fmt::format("Unknown columns:{} in file {}", fmt::to_string(col_buf),
1494
0
                                   _current_range.path);
1495
0
    }
1496
1497
2.71k
    RETURN_IF_ERROR(_generate_truncate_columns(need_to_get_parsed_schema));
1498
2.71k
    return Status::OK();
1499
2.71k
}
1500
1501
2.71k
Status FileScanner::_generate_truncate_columns(bool need_to_get_parsed_schema) {
1502
2.71k
    _source_file_col_name_types.clear();
1503
    //  The col names and types of source file, such as parquet, orc files.
1504
2.71k
    if (_state->query_options().truncate_char_or_varchar_columns && need_to_get_parsed_schema) {
1505
0
        std::vector<std::string> source_file_col_names;
1506
0
        std::vector<DataTypePtr> source_file_col_types;
1507
0
        Status status =
1508
0
                _cur_reader->get_parsed_schema(&source_file_col_names, &source_file_col_types);
1509
0
        if (!status.ok() && status.code() != TStatusCode::NOT_IMPLEMENTED_ERROR) {
1510
0
            return status;
1511
0
        }
1512
0
        DCHECK_EQ(source_file_col_names.size(), source_file_col_types.size());
1513
0
        for (int i = 0; i < source_file_col_names.size(); ++i) {
1514
0
            _source_file_col_name_types[to_lower(source_file_col_names[i])] =
1515
0
                    source_file_col_types[i];
1516
0
        }
1517
0
    }
1518
2.71k
    return Status::OK();
1519
2.71k
}
1520
1521
29
Status FileScanner::prepare_for_read_lines(const TFileRangeDesc& range) {
1522
29
    _current_range = range;
1523
1524
29
    _file_cache_statistics.reset(new io::FileCacheStatistics());
1525
29
    _file_reader_stats.reset(new io::FileReaderStats());
1526
1527
29
    _file_read_bytes_counter =
1528
29
            ADD_COUNTER_WITH_LEVEL(_profile, FileReadBytesProfile, TUnit::BYTES, 1);
1529
29
    _file_read_time_counter = ADD_TIMER_WITH_LEVEL(_profile, FileReadTimeProfile, 1);
1530
1531
29
    RETURN_IF_ERROR(_init_io_ctx());
1532
29
    _io_ctx->file_cache_stats = _file_cache_statistics.get();
1533
29
    _io_ctx->file_reader_stats = _file_reader_stats.get();
1534
29
    _default_val_row_desc.reset(new RowDescriptor((TupleDescriptor*)_real_tuple_desc));
1535
29
    RETURN_IF_ERROR(_init_expr_ctxes());
1536
1537
    // Since only one column is read from the file, there is no need to filter, so set these variables to empty.
1538
29
    _push_down_conjuncts.clear();
1539
29
    _not_single_slot_filter_conjuncts.clear();
1540
29
    _slot_id_to_filter_conjuncts.clear();
1541
29
    _kv_cache = nullptr;
1542
29
    return Status::OK();
1543
29
}
1544
1545
Status FileScanner::read_lines_from_range(const TFileRangeDesc& range,
1546
                                          const std::list<int64_t>& row_ids, Block* result_block,
1547
                                          const ExternalFileMappingInfo& external_info,
1548
38
                                          int64_t* init_reader_ms, int64_t* get_block_ms) {
1549
38
    _current_range = range;
1550
38
    RETURN_IF_ERROR(_generate_partition_columns());
1551
1552
38
    TFileFormatType::type format_type = _get_current_format_type();
1553
38
    Status init_status = Status::OK();
1554
1555
38
    auto file_meta_cache_ptr = external_info.enable_file_meta_cache
1556
38
                                       ? ExecEnv::GetInstance()->file_meta_cache()
1557
38
                                       : nullptr;
1558
1559
38
    RETURN_IF_ERROR(scope_timer_run(
1560
38
            [&]() -> Status {
1561
38
                switch (format_type) {
1562
38
                case TFileFormatType::FORMAT_PARQUET: {
1563
38
                    std::unique_ptr<ParquetReader> parquet_reader = ParquetReader::create_unique(
1564
38
                            _profile, *_params, range, 1, &_state->timezone_obj(), _io_ctx.get(),
1565
38
                            _state, file_meta_cache_ptr, false);
1566
1567
38
                    RETURN_IF_ERROR(parquet_reader->read_by_rows(row_ids));
1568
38
                    RETURN_IF_ERROR(
1569
38
                            _init_parquet_reader(std::move(parquet_reader), file_meta_cache_ptr));
1570
38
                    break;
1571
38
                }
1572
38
                case TFileFormatType::FORMAT_ORC: {
1573
38
                    std::unique_ptr<OrcReader> orc_reader = OrcReader::create_unique(
1574
38
                            _profile, _state, *_params, range, 1, _state->timezone(), _io_ctx.get(),
1575
38
                            file_meta_cache_ptr, false);
1576
1577
38
                    RETURN_IF_ERROR(orc_reader->read_by_rows(row_ids));
1578
38
                    RETURN_IF_ERROR(_init_orc_reader(std::move(orc_reader), file_meta_cache_ptr));
1579
38
                    break;
1580
38
                }
1581
38
                default: {
1582
38
                    return Status::NotSupported(
1583
38
                            "Not support create lines reader for file format: {},"
1584
38
                            "only support parquet and orc.",
1585
38
                            to_string(_params->format_type));
1586
38
                }
1587
38
                }
1588
38
                return Status::OK();
1589
38
            },
1590
38
            init_reader_ms));
1591
1592
38
    RETURN_IF_ERROR(_set_fill_or_truncate_columns(true));
1593
38
    _cur_reader_eof = false;
1594
1595
38
    RETURN_IF_ERROR(scope_timer_run(
1596
38
            [&]() -> Status {
1597
38
                while (!_cur_reader_eof) {
1598
38
                    bool eof = false;
1599
38
                    RETURN_IF_ERROR(_get_block_impl(_state, result_block, &eof));
1600
38
                }
1601
38
                return Status::OK();
1602
38
            },
1603
38
            get_block_ms));
1604
1605
38
    _cur_reader->collect_profile_before_close();
1606
38
    RETURN_IF_ERROR(_cur_reader->close());
1607
1608
38
    COUNTER_UPDATE(_file_read_bytes_counter, _file_reader_stats->read_bytes);
1609
38
    COUNTER_UPDATE(_file_read_time_counter, _file_reader_stats->read_time_ns);
1610
38
    return Status::OK();
1611
38
}
1612
1613
44
Status FileScanner::_generate_partition_columns() {
1614
44
    _partition_col_descs.clear();
1615
44
    _partition_value_is_null.clear();
1616
44
    const TFileRangeDesc& range = _current_range;
1617
44
    if (range.__isset.columns_from_path && !_partition_slot_descs.empty()) {
1618
11
        for (const auto& slot_desc : _partition_slot_descs) {
1619
11
            if (slot_desc) {
1620
11
                auto it = _partition_slot_index_map.find(slot_desc->id());
1621
11
                if (it == std::end(_partition_slot_index_map)) {
1622
0
                    return Status::InternalError("Unknown source slot descriptor, slot_id={}",
1623
0
                                                 slot_desc->id());
1624
0
                }
1625
11
                const std::string& column_from_path = range.columns_from_path[it->second];
1626
11
                _partition_col_descs.emplace(slot_desc->col_name(),
1627
11
                                             std::make_tuple(column_from_path, slot_desc));
1628
11
                if (range.__isset.columns_from_path_is_null) {
1629
0
                    _partition_value_is_null.emplace(slot_desc->col_name(),
1630
0
                                                     range.columns_from_path_is_null[it->second]);
1631
0
                }
1632
11
            }
1633
11
        }
1634
6
    }
1635
44
    return Status::OK();
1636
44
}
1637
1638
2.71k
Status FileScanner::_generate_missing_columns() {
1639
2.71k
    _missing_col_descs.clear();
1640
2.71k
    if (!_missing_cols.empty()) {
1641
3
        for (auto* slot_desc : _real_tuple_desc->slots()) {
1642
3
            if (!_missing_cols.contains(slot_desc->col_name())) {
1643
2
                continue;
1644
2
            }
1645
1646
1
            auto it = _col_default_value_ctx.find(slot_desc->col_name());
1647
1
            if (it == _col_default_value_ctx.end()) {
1648
0
                return Status::InternalError("failed to find default value expr for slot: {}",
1649
0
                                             slot_desc->col_name());
1650
0
            }
1651
1
            _missing_col_descs.emplace(slot_desc->col_name(), it->second);
1652
1
        }
1653
1
    }
1654
2.71k
    return Status::OK();
1655
2.71k
}
1656
1657
2.70k
Status FileScanner::_init_expr_ctxes() {
1658
2.70k
    std::map<SlotId, int> full_src_index_map;
1659
2.70k
    std::map<SlotId, SlotDescriptor*> full_src_slot_map;
1660
2.70k
    std::map<std::string, int> partition_name_to_key_index_map;
1661
2.70k
    int index = 0;
1662
21.6k
    for (const auto& slot_desc : _real_tuple_desc->slots()) {
1663
21.6k
        full_src_slot_map.emplace(slot_desc->id(), slot_desc);
1664
21.6k
        full_src_index_map.emplace(slot_desc->id(), index++);
1665
21.6k
    }
1666
1667
    // For external table query, find the index of column in path.
1668
    // Because query doesn't always search for all columns in a table
1669
    // and the order of selected columns is random.
1670
    // All ranges in _ranges vector should have identical columns_from_path_keys
1671
    // because they are all file splits for the same external table.
1672
    // So here use the first element of _ranges to fill the partition_name_to_key_index_map
1673
2.70k
    if (_current_range.__isset.columns_from_path_keys) {
1674
428
        std::vector<std::string> key_map = _current_range.columns_from_path_keys;
1675
428
        if (!key_map.empty()) {
1676
17
            for (size_t i = 0; i < key_map.size(); i++) {
1677
11
                partition_name_to_key_index_map.emplace(key_map[i], i);
1678
11
            }
1679
6
        }
1680
428
    }
1681
1682
2.70k
    _num_of_columns_from_file = _params->num_of_columns_from_file;
1683
1684
21.6k
    for (const auto& slot_info : _params->required_slots) {
1685
21.6k
        auto slot_id = slot_info.slot_id;
1686
21.6k
        auto it = full_src_slot_map.find(slot_id);
1687
21.6k
        if (it == std::end(full_src_slot_map)) {
1688
0
            return Status::InternalError(
1689
0
                    fmt::format("Unknown source slot descriptor, slot_id={}", slot_id));
1690
0
        }
1691
21.6k
        if (it->second->col_name().starts_with(BeConsts::GLOBAL_ROWID_COL)) {
1692
13
            _row_id_column_iterator_pair.second = _default_val_row_desc->get_column_id(slot_id);
1693
13
            continue;
1694
13
        }
1695
21.6k
        if (it->second->col_name() == BeConsts::ICEBERG_ROWID_COL) {
1696
0
            _need_iceberg_rowid_column = true;
1697
0
            continue;
1698
0
        }
1699
1700
21.6k
        if (slot_info.is_file_slot) {
1701
21.6k
            _is_file_slot.emplace(slot_id);
1702
21.6k
            _file_slot_descs.emplace_back(it->second);
1703
21.6k
            _file_col_names.push_back(it->second->col_name());
1704
21.6k
        }
1705
1706
21.6k
        if (partition_name_to_key_index_map.contains(it->second->col_name())) {
1707
11
            if (slot_info.is_file_slot) {
1708
                // If there is slot which is both a partition column and a file column,
1709
                // we should not fill the partition column from path.
1710
0
                _fill_partition_from_path = false;
1711
11
            } else if (!_fill_partition_from_path) {
1712
                // This should not happen
1713
0
                return Status::InternalError(
1714
0
                        "Partition column {} is not a file column, but there is already a column "
1715
0
                        "which is both a partition column and a file column.",
1716
0
                        it->second->col_name());
1717
0
            }
1718
11
            _partition_slot_descs.emplace_back(it->second);
1719
11
            if (_is_load) {
1720
11
                auto iti = full_src_index_map.find(slot_id);
1721
11
                _partition_slot_index_map.emplace(slot_id, iti->second - _num_of_columns_from_file);
1722
11
            } else {
1723
0
                auto kit = partition_name_to_key_index_map.find(it->second->col_name());
1724
0
                _partition_slot_index_map.emplace(slot_id, kit->second);
1725
0
            }
1726
11
        }
1727
21.6k
    }
1728
1729
    // set column name to default value expr map
1730
21.6k
    for (auto* slot_desc : _real_tuple_desc->slots()) {
1731
21.6k
        VExprContextSPtr ctx;
1732
21.6k
        auto it = _params->default_value_of_src_slot.find(slot_desc->id());
1733
21.6k
        if (it != std::end(_params->default_value_of_src_slot)) {
1734
21.2k
            if (!it->second.nodes.empty()) {
1735
17.4k
                RETURN_IF_ERROR(VExpr::create_expr_tree(it->second, ctx));
1736
17.4k
                RETURN_IF_ERROR(ctx->prepare(_state, *_default_val_row_desc));
1737
17.4k
                RETURN_IF_ERROR(ctx->open(_state));
1738
17.4k
            }
1739
            // if expr is empty, the default value will be null
1740
21.2k
            _col_default_value_ctx.emplace(slot_desc->col_name(), ctx);
1741
21.2k
        }
1742
21.6k
    }
1743
1744
2.70k
    if (_is_load) {
1745
        // follow desc expr map is only for load task.
1746
2.15k
        bool has_slot_id_map = _params->__isset.dest_sid_to_src_sid_without_trans;
1747
2.15k
        int idx = 0;
1748
23.9k
        for (auto* slot_desc : _output_tuple_desc->slots()) {
1749
23.9k
            auto it = _params->expr_of_dest_slot.find(slot_desc->id());
1750
23.9k
            if (it == std::end(_params->expr_of_dest_slot)) {
1751
0
                return Status::InternalError("No expr for dest slot, id={}, name={}",
1752
0
                                             slot_desc->id(), slot_desc->col_name());
1753
0
            }
1754
1755
23.9k
            VExprContextSPtr ctx;
1756
23.9k
            if (!it->second.nodes.empty()) {
1757
23.9k
                RETURN_IF_ERROR(VExpr::create_expr_tree(it->second, ctx));
1758
23.9k
                RETURN_IF_ERROR(ctx->prepare(_state, *_src_row_desc));
1759
23.9k
                RETURN_IF_ERROR(ctx->open(_state));
1760
23.9k
            }
1761
23.9k
            _dest_vexpr_ctx.emplace_back(ctx);
1762
23.9k
            _dest_slot_name_to_idx[slot_desc->col_name()] = idx++;
1763
1764
23.9k
            if (has_slot_id_map) {
1765
23.8k
                auto it1 = _params->dest_sid_to_src_sid_without_trans.find(slot_desc->id());
1766
23.8k
                if (it1 == std::end(_params->dest_sid_to_src_sid_without_trans)) {
1767
5.88k
                    _src_slot_descs_order_by_dest.emplace_back(nullptr);
1768
17.9k
                } else {
1769
17.9k
                    auto _src_slot_it = full_src_slot_map.find(it1->second);
1770
17.9k
                    if (_src_slot_it == std::end(full_src_slot_map)) {
1771
0
                        return Status::InternalError("No src slot {} in src slot descs",
1772
0
                                                     it1->second);
1773
0
                    }
1774
17.9k
                    _dest_slot_to_src_slot_index.emplace(_src_slot_descs_order_by_dest.size(),
1775
17.9k
                                                         full_src_index_map[_src_slot_it->first]);
1776
17.9k
                    _src_slot_descs_order_by_dest.emplace_back(_src_slot_it->second);
1777
17.9k
                }
1778
23.8k
            }
1779
23.9k
        }
1780
2.15k
    }
1781
2.70k
    return Status::OK();
1782
2.70k
}
1783
1784
13.3k
bool FileScanner::_should_enable_condition_cache() {
1785
13.3k
    return _condition_cache_digest != 0 && !_is_load &&
1786
13.3k
           (!_conjuncts.empty() || !_push_down_conjuncts.empty());
1787
13.3k
}
1788
1789
5.33k
void FileScanner::_init_reader_condition_cache() {
1790
5.33k
    _condition_cache = nullptr;
1791
5.33k
    _condition_cache_ctx = nullptr;
1792
1793
5.33k
    if (!_should_enable_condition_cache() || !_cur_reader) {
1794
5.33k
        return;
1795
5.33k
    }
1796
1797
    // Disable condition cache when delete operations exist (e.g. Iceberg position/equality
1798
    // deletes, Hive ACID deletes). Cached granule results may become stale if delete files
1799
    // change between queries while the data file's cache key remains the same.
1800
3
    if (_cur_reader->has_delete_operations()) {
1801
0
        return;
1802
0
    }
1803
1804
3
    auto* cache = segment_v2::ConditionCache::instance();
1805
3
    _condition_cache_key = segment_v2::ConditionCache::ExternalCacheKey(
1806
3
            _current_range.path,
1807
3
            _current_range.__isset.modification_time ? _current_range.modification_time : 0,
1808
3
            _current_range.__isset.file_size ? _current_range.file_size : -1,
1809
3
            _condition_cache_digest,
1810
3
            _current_range.__isset.start_offset ? _current_range.start_offset : 0,
1811
3
            _current_range.__isset.size ? _current_range.size : -1);
1812
1813
3
    segment_v2::ConditionCacheHandle handle;
1814
3
    auto condition_cache_hit = cache->lookup(_condition_cache_key, &handle);
1815
3
    if (condition_cache_hit) {
1816
0
        _condition_cache = handle.get_filter_result();
1817
0
        _condition_cache_hit_count++;
1818
3
    } else {
1819
        // Allocate cache pre-sized to total number of granules.
1820
        // We add +1 as a safety margin: when a file is split across multiple scanners
1821
        // and the first row of this scanner's range is not aligned to a granule boundary,
1822
        // the data may span one more granule than ceil(total_rows / GRANULE_SIZE).
1823
        // The extra element costs only 1 bit and never affects correctness (an extra
1824
        // false-granule beyond the actual data range won't overlap any real row range).
1825
3
        int64_t total_rows = _cur_reader->get_total_rows();
1826
3
        if (total_rows > 0) {
1827
1
            size_t num_granules = (total_rows + ConditionCacheContext::GRANULE_SIZE - 1) /
1828
1
                                  ConditionCacheContext::GRANULE_SIZE;
1829
1
            _condition_cache = std::make_shared<std::vector<bool>>(num_granules + 1, false);
1830
1
        }
1831
3
    }
1832
1833
3
    if (_condition_cache) {
1834
        // Create context to pass to readers (native readers use it; non-native readers ignore it)
1835
1
        _condition_cache_ctx = std::make_shared<ConditionCacheContext>();
1836
1
        _condition_cache_ctx->is_hit = condition_cache_hit;
1837
1
        _condition_cache_ctx->filter_result = _condition_cache;
1838
1
        _cur_reader->set_condition_cache_context(_condition_cache_ctx);
1839
1
    }
1840
3
}
1841
1842
8.01k
void FileScanner::_finalize_reader_condition_cache() {
1843
8.01k
    if (!_should_enable_condition_cache() || !_condition_cache_ctx ||
1844
8.01k
        _condition_cache_ctx->is_hit) {
1845
8.01k
        _condition_cache = nullptr;
1846
8.01k
        _condition_cache_ctx = nullptr;
1847
8.01k
        return;
1848
8.01k
    }
1849
    // Only store the cache if the reader was fully consumed. If the scan was
1850
    // truncated early (e.g. by LIMIT), the cache is incomplete — unread granules
1851
    // would remain false and cause surviving rows to be incorrectly skipped on HIT.
1852
1
    if (!_cur_reader_eof) {
1853
0
        _condition_cache = nullptr;
1854
0
        _condition_cache_ctx = nullptr;
1855
0
        return;
1856
0
    }
1857
1858
1
    auto* cache = segment_v2::ConditionCache::instance();
1859
1
    cache->insert(_condition_cache_key, std::move(_condition_cache));
1860
1
    _condition_cache = nullptr;
1861
1
    _condition_cache_ctx = nullptr;
1862
1
}
1863
1864
2.67k
Status FileScanner::close(RuntimeState* state) {
1865
2.67k
    if (!_try_close()) {
1866
0
        return Status::OK();
1867
0
    }
1868
1869
2.67k
    _finalize_reader_condition_cache();
1870
1871
2.67k
    if (_cur_reader) {
1872
13
        RETURN_IF_ERROR(_cur_reader->close());
1873
13
    }
1874
1875
2.67k
    RETURN_IF_ERROR(Scanner::close(state));
1876
2.67k
    return Status::OK();
1877
2.67k
}
1878
1879
2.67k
void FileScanner::try_stop() {
1880
2.67k
    Scanner::try_stop();
1881
2.67k
    if (_io_ctx) {
1882
2.67k
        _io_ctx->should_stop = true;
1883
2.67k
    }
1884
2.67k
}
1885
1886
2.67k
void FileScanner::update_realtime_counters() {
1887
2.67k
    FileScanLocalState* local_state = static_cast<FileScanLocalState*>(_local_state);
1888
1889
2.67k
    COUNTER_UPDATE(local_state->_scan_bytes, _file_reader_stats->read_bytes);
1890
2.67k
    COUNTER_UPDATE(local_state->_scan_rows, _file_reader_stats->read_rows);
1891
1892
2.67k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_rows(
1893
2.67k
            _file_reader_stats->read_rows);
1894
2.67k
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes(
1895
2.67k
            _file_reader_stats->read_bytes);
1896
1897
2.67k
    int64_t delta_bytes_read_from_local =
1898
2.67k
            _file_cache_statistics->bytes_read_from_local - _last_bytes_read_from_local;
1899
2.67k
    int64_t delta_bytes_read_from_remote =
1900
2.67k
            _file_cache_statistics->bytes_read_from_remote - _last_bytes_read_from_remote;
1901
2.67k
    if (_file_cache_statistics->bytes_read_from_local == 0 &&
1902
2.67k
        _file_cache_statistics->bytes_read_from_remote == 0) {
1903
2.67k
        _state->get_query_ctx()
1904
2.67k
                ->resource_ctx()
1905
2.67k
                ->io_context()
1906
2.67k
                ->update_scan_bytes_from_remote_storage(_file_reader_stats->read_bytes);
1907
2.67k
        DorisMetrics::instance()->query_scan_bytes_from_local->increment(
1908
2.67k
                _file_reader_stats->read_bytes);
1909
2.67k
    } else {
1910
0
        _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes_from_local_storage(
1911
0
                delta_bytes_read_from_local);
1912
0
        _state->get_query_ctx()
1913
0
                ->resource_ctx()
1914
0
                ->io_context()
1915
0
                ->update_scan_bytes_from_remote_storage(delta_bytes_read_from_remote);
1916
0
        DorisMetrics::instance()->query_scan_bytes_from_local->increment(
1917
0
                delta_bytes_read_from_local);
1918
0
        DorisMetrics::instance()->query_scan_bytes_from_remote->increment(
1919
0
                delta_bytes_read_from_remote);
1920
0
    }
1921
1922
2.67k
    COUNTER_UPDATE(_file_read_bytes_counter, _file_reader_stats->read_bytes);
1923
1924
2.67k
    DorisMetrics::instance()->query_scan_bytes->increment(_file_reader_stats->read_bytes);
1925
2.67k
    DorisMetrics::instance()->query_scan_rows->increment(_file_reader_stats->read_rows);
1926
1927
2.67k
    _file_reader_stats->read_bytes = 0;
1928
2.67k
    _file_reader_stats->read_rows = 0;
1929
1930
2.67k
    _last_bytes_read_from_local = _file_cache_statistics->bytes_read_from_local;
1931
2.67k
    _last_bytes_read_from_remote = _file_cache_statistics->bytes_read_from_remote;
1932
2.67k
}
1933
1934
2.67k
void FileScanner::_collect_profile_before_close() {
1935
2.67k
    Scanner::_collect_profile_before_close();
1936
2.67k
    if (config::enable_file_cache && _state->query_options().enable_file_cache &&
1937
2.67k
        _profile != nullptr) {
1938
0
        io::FileCacheProfileReporter cache_profile(_profile);
1939
0
        cache_profile.update(_file_cache_statistics.get());
1940
0
        _state->get_query_ctx()->resource_ctx()->io_context()->update_bytes_write_into_cache(
1941
0
                _file_cache_statistics->bytes_write_into_cache);
1942
0
    }
1943
1944
2.67k
    if (_cur_reader != nullptr) {
1945
13
        _cur_reader->collect_profile_before_close();
1946
13
    }
1947
1948
2.67k
    FileScanLocalState* local_state = static_cast<FileScanLocalState*>(_local_state);
1949
2.67k
    COUNTER_UPDATE(local_state->_scan_bytes, _file_reader_stats->read_bytes);
1950
2.67k
    COUNTER_UPDATE(local_state->_scan_rows, _file_reader_stats->read_rows);
1951
1952
2.67k
    COUNTER_UPDATE(_file_read_bytes_counter, _file_reader_stats->read_bytes);
1953
2.67k
    COUNTER_UPDATE(_file_read_calls_counter, _file_reader_stats->read_calls);
1954
2.67k
    COUNTER_UPDATE(_file_read_time_counter, _file_reader_stats->read_time_ns);
1955
2.67k
    COUNTER_UPDATE(local_state->_condition_cache_hit_counter, _condition_cache_hit_count);
1956
2.67k
    if (_io_ctx) {
1957
2.67k
        COUNTER_UPDATE(local_state->_condition_cache_filtered_rows_counter,
1958
2.67k
                       _io_ctx->condition_cache_filtered_rows);
1959
2.67k
    }
1960
1961
2.67k
    DorisMetrics::instance()->query_scan_bytes->increment(_file_reader_stats->read_bytes);
1962
2.67k
    DorisMetrics::instance()->query_scan_rows->increment(_file_reader_stats->read_rows);
1963
2.67k
}
1964
1965
} // namespace doris