Coverage Report

Created: 2026-03-16 19:50

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