Coverage Report

Created: 2026-03-17 18:28

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
1
        : Scanner(state, local_state, limit, profile),
104
1
          _split_source(split_source),
105
1
          _cur_reader(nullptr),
106
1
          _cur_reader_eof(false),
107
1
          _kv_cache(kv_cache),
108
1
          _strict_mode(false),
109
1
          _col_name_to_slot_id(colname_to_slot_id) {
110
1
    if (state->get_query_ctx() != nullptr &&
111
1
        state->get_query_ctx()->file_scan_range_params_map.count(local_state->parent_id()) > 0) {
112
0
        _params = &(state->get_query_ctx()->file_scan_range_params_map[local_state->parent_id()]);
113
1
    } else {
114
        // old fe thrift protocol
115
1
        _params = _split_source->get_params();
116
1
    }
117
1
    if (_params->__isset.strict_mode) {
118
0
        _strict_mode = _params->strict_mode;
119
0
    }
120
121
    // For load scanner, there are input and output tuple.
122
    // For query scanner, there is only output tuple
123
1
    _input_tuple_desc = state->desc_tbl().get_tuple_descriptor(_params->src_tuple_id);
124
1
    _real_tuple_desc = _input_tuple_desc == nullptr ? _output_tuple_desc : _input_tuple_desc;
125
1
    _is_load = (_input_tuple_desc != nullptr);
126
1
}
127
128
1
Status FileScanner::init(RuntimeState* state, const VExprContextSPtrs& conjuncts) {
129
1
    RETURN_IF_ERROR(Scanner::init(state, conjuncts));
130
1
    _get_block_timer =
131
1
            ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(), "FileScannerGetBlockTime", 1);
132
1
    _cast_to_input_block_timer = ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(),
133
1
                                                      "FileScannerCastInputBlockTime", 1);
134
1
    _fill_missing_columns_timer = ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(),
135
1
                                                       "FileScannerFillMissingColumnTime", 1);
136
1
    _pre_filter_timer =
137
1
            ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(), "FileScannerPreFilterTimer", 1);
138
1
    _convert_to_output_block_timer = ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(),
139
1
                                                          "FileScannerConvertOuputBlockTime", 1);
140
1
    _runtime_filter_partition_prune_timer = ADD_TIMER_WITH_LEVEL(
141
1
            _local_state->scanner_profile(), "FileScannerRuntimeFilterPartitionPruningTime", 1);
142
1
    _empty_file_counter =
143
1
            ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(), "EmptyFileNum", TUnit::UNIT, 1);
144
1
    _not_found_file_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
145
1
                                                     "NotFoundFileNum", TUnit::UNIT, 1);
146
1
    _fully_skipped_file_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
147
1
                                                         "FullySkippedFileNum", TUnit::UNIT, 1);
148
1
    _file_counter =
149
1
            ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(), "FileNumber", TUnit::UNIT, 1);
150
151
1
    _file_read_bytes_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
152
1
                                                      FileReadBytesProfile, TUnit::BYTES, 1);
153
1
    _file_read_calls_counter = ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
154
1
                                                      "FileReadCalls", TUnit::UNIT, 1);
155
1
    _file_read_time_counter =
156
1
            ADD_TIMER_WITH_LEVEL(_local_state->scanner_profile(), FileReadTimeProfile, 1);
157
158
1
    _runtime_filter_partition_pruned_range_counter =
159
1
            ADD_COUNTER_WITH_LEVEL(_local_state->scanner_profile(),
160
1
                                   "RuntimeFilterPartitionPrunedRangeNum", TUnit::UNIT, 1);
161
162
1
    _file_cache_statistics.reset(new io::FileCacheStatistics());
163
1
    _file_reader_stats.reset(new io::FileReaderStats());
164
165
1
    RETURN_IF_ERROR(_init_io_ctx());
166
1
    _io_ctx->file_cache_stats = _file_cache_statistics.get();
167
1
    _io_ctx->file_reader_stats = _file_reader_stats.get();
168
1
    _io_ctx->is_disposable = _state->query_options().disable_file_cache;
169
170
1
    if (_is_load) {
171
0
        _src_row_desc.reset(new RowDescriptor(_state->desc_tbl(),
172
0
                                              std::vector<TupleId>({_input_tuple_desc->id()})));
173
        // prepare pre filters
174
0
        if (_params->__isset.pre_filter_exprs_list) {
175
0
            RETURN_IF_ERROR(doris::VExpr::create_expr_trees(_params->pre_filter_exprs_list,
176
0
                                                            _pre_conjunct_ctxs));
177
0
        } 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
0
        for (auto& conjunct : _pre_conjunct_ctxs) {
184
0
            RETURN_IF_ERROR(conjunct->prepare(_state, *_src_row_desc));
185
0
            RETURN_IF_ERROR(conjunct->open(_state));
186
0
        }
187
188
0
        _dest_row_desc.reset(new RowDescriptor(_state->desc_tbl(),
189
0
                                               std::vector<TupleId>({_output_tuple_desc->id()})));
190
0
    }
191
192
1
    _default_val_row_desc.reset(
193
1
            new RowDescriptor(_state->desc_tbl(), std::vector<TupleId>({_real_tuple_desc->id()})));
194
195
1
    return Status::OK();
196
1
}
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
0
void FileScanner::_init_runtime_filter_partition_prune_ctxs() {
214
0
    _runtime_filter_partition_prune_ctxs.clear();
215
0
    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
0
}
224
225
0
void FileScanner::_init_runtime_filter_partition_prune_block() {
226
    // init block with empty column
227
0
    for (auto const* slot_desc : _real_tuple_desc->slots()) {
228
0
        _runtime_filter_partition_prune_block.insert(
229
0
                ColumnWithTypeAndName(slot_desc->get_empty_mutable_column(),
230
0
                                      slot_desc->get_data_type_ptr(), slot_desc->col_name()));
231
0
    }
232
0
}
233
234
0
Status FileScanner::_process_runtime_filters_partition_prune(bool& can_filter_all) {
235
0
    SCOPED_TIMER(_runtime_filter_partition_prune_timer);
236
0
    if (_runtime_filter_partition_prune_ctxs.empty() || _partition_col_descs.empty()) {
237
0
        return Status::OK();
238
0
    }
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
0
Status FileScanner::_process_conjuncts() {
320
0
    _slot_id_to_filter_conjuncts.clear();
321
0
    _not_single_slot_filter_conjuncts.clear();
322
0
    for (auto& conjunct : _push_down_conjuncts) {
323
0
        auto impl = conjunct->root()->get_impl();
324
        // If impl is not null, which means this a conjuncts from runtime filter.
325
0
        auto cur_expr = impl ? impl : conjunct->root();
326
327
0
        std::vector<int> slot_ids;
328
0
        _get_slot_ids(cur_expr.get(), &slot_ids);
329
0
        if (slot_ids.empty()) {
330
0
            _not_single_slot_filter_conjuncts.emplace_back(conjunct);
331
0
            continue;
332
0
        }
333
0
        bool single_slot = true;
334
0
        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
0
        if (single_slot) {
341
0
            SlotId slot_id = slot_ids[0];
342
0
            _slot_id_to_filter_conjuncts[slot_id].emplace_back(conjunct);
343
0
        } else {
344
0
            _not_single_slot_filter_conjuncts.emplace_back(conjunct);
345
0
        }
346
0
    }
347
0
    return Status::OK();
348
0
}
349
350
0
Status FileScanner::_process_late_arrival_conjuncts() {
351
0
    if (_push_down_conjuncts.size() < _conjuncts.size()) {
352
0
        _push_down_conjuncts = _conjuncts;
353
0
        _conjuncts.clear();
354
0
        RETURN_IF_ERROR(_process_conjuncts());
355
0
    }
356
0
    if (_applied_rf_num == _total_rf_num) {
357
0
        _local_state->scanner_profile()->add_info_string("ApplyAllRuntimeFilters", "True");
358
0
    }
359
0
    return Status::OK();
360
0
}
361
362
0
void FileScanner::_get_slot_ids(VExpr* expr, std::vector<int>* slot_ids) {
363
0
    for (auto& child_expr : expr->children()) {
364
0
        if (child_expr->is_slot_ref()) {
365
0
            VSlotRef* slot_ref = reinterpret_cast<VSlotRef*>(child_expr.get());
366
0
            SlotDescriptor* slot_desc = _state->desc_tbl().get_slot_descriptor(slot_ref->slot_id());
367
0
            slot_desc->set_is_predicate(true);
368
0
            slot_ids->emplace_back(slot_ref->slot_id());
369
0
        } else {
370
0
            _get_slot_ids(child_expr.get(), slot_ids);
371
0
        }
372
0
    }
373
0
}
374
375
0
Status FileScanner::_open_impl(RuntimeState* state) {
376
0
    RETURN_IF_CANCELLED(state);
377
0
    RETURN_IF_ERROR(Scanner::_open_impl(state));
378
0
    if (_local_state) {
379
0
        _condition_cache_digest = _local_state->get_condition_cache_digest();
380
0
    }
381
0
    RETURN_IF_ERROR(_split_source->get_next(&_first_scan_range, &_current_range));
382
0
    if (_first_scan_range) {
383
0
        RETURN_IF_ERROR(_init_expr_ctxes());
384
0
        if (_state->query_options().enable_runtime_filter_partition_prune &&
385
0
            !_partition_slot_index_map.empty()) {
386
0
            _init_runtime_filter_partition_prune_ctxs();
387
0
            _init_runtime_filter_partition_prune_block();
388
0
        }
389
0
    } else {
390
        // there's no scan range in split source. stop scanner directly.
391
0
        _scanner_eof = true;
392
0
    }
393
394
0
    return Status::OK();
395
0
}
396
397
35
Status FileScanner::_get_block_impl(RuntimeState* state, Block* block, bool* eof) {
398
35
    Status st = _get_block_wrapped(state, block, eof);
399
400
35
    if (!st.ok()) {
401
        // add cur path in error msg for easy debugging
402
1
        return std::move(st.append(". cur path: " + get_current_scan_range_name()));
403
1
    }
404
34
    return st;
405
35
}
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
35
Status FileScanner::_get_block_wrapped(RuntimeState* state, Block* block, bool* eof) {
427
35
    do {
428
35
        RETURN_IF_CANCELLED(state);
429
35
        if (_cur_reader == nullptr || _cur_reader_eof) {
430
1
            _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
1
            Status st = _get_next_reader();
435
1
            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
1
            } 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
1
            } else if (!st) {
444
1
                return st;
445
1
            }
446
0
            _init_reader_condition_cache();
447
0
        }
448
449
34
        if (_scanner_eof) {
450
0
            *eof = true;
451
0
            return Status::OK();
452
0
        }
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
34
        size_t read_rows = 0;
457
34
        RETURN_IF_ERROR(_init_src_block(block));
458
34
        {
459
34
            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
34
            RETURN_IF_ERROR(
464
34
                    _cur_reader->get_next_block(_src_block_ptr, &read_rows, &_cur_reader_eof));
465
34
        }
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
34
        if (read_rows > 0) {
469
24
            if ((!_cur_reader->count_read_rows()) && _io_ctx) {
470
0
                _io_ctx->file_reader_stats->read_rows += read_rows;
471
0
            }
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
24
            if (_get_push_down_agg_type() != TPushAggOp::type::COUNT) {
475
                // Convert the src block columns type to string in-place.
476
24
                RETURN_IF_ERROR(_cast_to_input_block(block));
477
                // FileReader can fill partition and missing columns itself
478
24
                if (!_cur_reader->fill_all_columns()) {
479
                    // Fill rows in src block with partition columns from path. (e.g. Hive partition columns)
480
0
                    RETURN_IF_ERROR(_fill_columns_from_path(read_rows));
481
                    // Fill columns not exist in file with null or default value
482
0
                    RETURN_IF_ERROR(_fill_missing_columns(read_rows));
483
0
                }
484
                // Apply _pre_conjunct_ctxs to filter src block.
485
24
                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
24
                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
24
                RETURN_IF_ERROR(_truncate_char_or_varchar_columns(block));
492
24
            }
493
24
        }
494
34
        break;
495
34
    } 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
34
    return Status::OK();
504
35
}
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
0
Status FileScanner::_check_output_block_types() {
512
0
    if (_is_load) {
513
0
        TFileFormatType::type format_type = _params->format_type;
514
0
        if (format_type == TFileFormatType::FORMAT_PARQUET ||
515
0
            format_type == TFileFormatType::FORMAT_ORC) {
516
0
            for (auto slot : _output_tuple_desc->slots()) {
517
0
                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
0
            }
523
0
        }
524
0
    }
525
0
    return Status::OK();
526
0
}
527
528
34
Status FileScanner::_init_src_block(Block* block) {
529
34
    if (!_is_load) {
530
34
        _src_block_ptr = block;
531
532
        // Build name to index map only once on first call
533
34
        if (_src_block_name_to_idx.empty()) {
534
15
            _src_block_name_to_idx = block->get_name_to_pos_map();
535
15
        }
536
34
        return Status::OK();
537
34
    }
538
0
    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
0
    _src_block.clear();
547
0
    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
0
    for (auto& slot : _input_tuple_desc->slots()) {
554
0
        DataTypePtr data_type;
555
0
        auto it = _slot_lower_name_to_col_type.find(slot->col_name());
556
0
        if (slot->is_skip_bitmap_col()) {
557
0
            _skip_bitmap_col_idx = idx;
558
0
        }
559
0
        if (_params->__isset.sequence_map_col) {
560
0
            if (_params->sequence_map_col == slot->col_name()) {
561
0
                _sequence_map_col_uid = slot->col_unique_id();
562
0
            }
563
0
        }
564
0
        data_type =
565
0
                it == _slot_lower_name_to_col_type.end() ? slot->type() : make_nullable(it->second);
566
0
        MutableColumnPtr data_column = data_type->create_column();
567
0
        _src_block.insert(
568
0
                ColumnWithTypeAndName(std::move(data_column), data_type, slot->col_name()));
569
0
        _src_block_name_to_idx.emplace(slot->col_name(), idx++);
570
0
    }
571
0
    if (_params->__isset.sequence_map_col) {
572
0
        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
0
            if (slot->is_sequence_col()) {
576
0
                _sequence_col_uid = slot->col_unique_id();
577
0
            }
578
0
        }
579
0
    }
580
0
    _src_block_ptr = &_src_block;
581
0
    _src_block_init = true;
582
0
    return Status::OK();
583
0
}
584
585
24
Status FileScanner::_cast_to_input_block(Block* block) {
586
24
    if (!_is_load) {
587
24
        return Status::OK();
588
24
    }
589
0
    SCOPED_TIMER(_cast_to_input_block_timer);
590
    // cast primitive type(PT0) to primitive type(PT1)
591
0
    uint32_t idx = 0;
592
0
    for (auto& slot_desc : _input_tuple_desc->slots()) {
593
0
        if (_slot_lower_name_to_col_type.find(slot_desc->col_name()) ==
594
0
            _slot_lower_name_to_col_type.end()) {
595
            // skip columns which does not exist in file
596
0
            continue;
597
0
        }
598
0
        auto& arg = _src_block_ptr->get_by_position(_src_block_name_to_idx[slot_desc->col_name()]);
599
0
        auto return_type = slot_desc->get_data_type_ptr();
600
        // remove nullable here, let the get_function decide whether nullable
601
0
        auto data_type = get_data_type_with_default_argument(remove_nullable(return_type));
602
0
        ColumnsWithTypeAndName arguments {
603
0
                arg, {data_type->create_column(), data_type, slot_desc->col_name()}};
604
0
        auto func_cast =
605
0
                SimpleFunctionFactory::instance().get_function("CAST", arguments, return_type, {});
606
0
        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
0
        idx = _src_block_name_to_idx[slot_desc->col_name()];
612
0
        DCHECK(_state != nullptr);
613
0
        auto ctx = FunctionContext::create_context(_state, {}, {});
614
0
        RETURN_IF_ERROR(
615
0
                func_cast->execute(ctx.get(), *_src_block_ptr, {idx}, idx, arg.column->size()));
616
0
        _src_block_ptr->get_by_position(idx).type = std::move(return_type);
617
0
    }
618
0
    return Status::OK();
619
0
}
620
621
0
Status FileScanner::_fill_columns_from_path(size_t rows) {
622
0
    if (!_fill_partition_from_path) {
623
0
        return Status::OK();
624
0
    }
625
0
    DataTypeSerDe::FormatOptions _text_formatOptions;
626
0
    for (auto& kv : _partition_col_descs) {
627
0
        auto doris_column =
628
0
                _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
0
        IColumn* col_ptr = const_cast<IColumn*>(doris_column.get());
631
0
        auto& [value, slot_desc] = kv.second;
632
0
        auto _text_serde = slot_desc->get_data_type_ptr()->get_serde();
633
0
        Slice slice(value.data(), value.size());
634
0
        uint64_t num_deserialized = 0;
635
0
        if (_text_serde->deserialize_column_from_fixed_json(*col_ptr, slice, rows,
636
0
                                                            &num_deserialized,
637
0
                                                            _text_formatOptions) != Status::OK()) {
638
0
            return Status::InternalError("Failed to fill partition column: {}={}",
639
0
                                         slot_desc->col_name(), value);
640
0
        }
641
0
        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
0
    }
649
0
    return Status::OK();
650
0
}
651
652
0
Status FileScanner::_fill_missing_columns(size_t rows) {
653
0
    if (_missing_cols.empty()) {
654
0
        return Status::OK();
655
0
    }
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
24
Status FileScanner::_pre_filter_src_block() {
696
24
    if (!_is_load) {
697
24
        return Status::OK();
698
24
    }
699
0
    if (!_pre_conjunct_ctxs.empty()) {
700
0
        SCOPED_TIMER(_pre_filter_timer);
701
0
        auto origin_column_num = _src_block_ptr->columns();
702
0
        auto old_rows = _src_block_ptr->rows();
703
0
        RETURN_IF_ERROR(
704
0
                VExprContext::filter_block(_pre_conjunct_ctxs, _src_block_ptr, origin_column_num));
705
0
        _counter.num_rows_unselected += old_rows - _src_block_ptr->rows();
706
0
    }
707
0
    return Status::OK();
708
0
}
709
710
24
Status FileScanner::_convert_to_output_block(Block* block) {
711
24
    if (!_is_load) {
712
24
        return Status::OK();
713
24
    }
714
0
    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
0
    int ctx_idx = 0;
721
0
    size_t rows = _src_block_ptr->rows();
722
0
    auto filter_column = ColumnUInt8::create(rows, 1);
723
0
    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
0
    MutableBlock mutable_output_block =
728
0
            VectorizedUtils::build_mutable_mem_reuse_block(block, *_dest_row_desc);
729
0
    auto& mutable_output_columns = mutable_output_block.mutable_columns();
730
731
0
    std::vector<BitmapValue>* skip_bitmaps {nullptr};
732
0
    if (_should_process_skip_bitmap_col()) {
733
0
        auto* skip_bitmap_nullable_col_ptr =
734
0
                assert_cast<ColumnNullable*>(_src_block_ptr->get_by_position(_skip_bitmap_col_idx)
735
0
                                                     .column->assume_mutable()
736
0
                                                     .get());
737
0
        skip_bitmaps = &(assert_cast<ColumnBitmap*>(
738
0
                                 skip_bitmap_nullable_col_ptr->get_nested_column_ptr().get())
739
0
                                 ->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
0
        if (_sequence_map_col_uid != -1) {
747
0
            for (int j = 0; j < rows; ++j) {
748
0
                if ((*skip_bitmaps)[j].contains(_sequence_map_col_uid)) {
749
0
                    (*skip_bitmaps)[j].add(_sequence_col_uid);
750
0
                }
751
0
            }
752
0
        }
753
0
    }
754
755
    // for (auto slot_desc : _output_tuple_desc->slots()) {
756
0
    for (int j = 0; j < mutable_output_columns.size(); ++j) {
757
0
        auto* slot_desc = _output_tuple_desc->slots()[j];
758
0
        int dest_index = ctx_idx;
759
0
        ColumnPtr column_ptr;
760
761
0
        auto& ctx = _dest_vexpr_ctx[dest_index];
762
        // PT1 => dest primitive type
763
0
        RETURN_IF_ERROR(ctx->execute(_src_block_ptr, column_ptr));
764
        // column_ptr maybe a ColumnConst, convert it to a normal column
765
0
        column_ptr = column_ptr->convert_to_full_column_if_const();
766
0
        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
0
        if (LIKELY(column_ptr->is_nullable())) {
771
0
            const auto* nullable_column = reinterpret_cast<const ColumnNullable*>(column_ptr.get());
772
0
            for (int i = 0; i < rows; ++i) {
773
0
                if (filter_map[i] && nullable_column->is_null_at(i)) {
774
                    // skip checks for non-mentioned columns in flexible partial update
775
0
                    if (skip_bitmaps == nullptr ||
776
0
                        !skip_bitmaps->at(i).contains(slot_desc->col_unique_id())) {
777
                        // clang-format off
778
0
                        if (_strict_mode && (_src_slot_descs_order_by_dest[dest_index]) &&
779
0
                            !_src_block_ptr->get_by_position(_dest_slot_to_src_slot_index[dest_index]).column->is_null_at(i)) {
780
0
                            filter_map[i] = false;
781
0
                            RETURN_IF_ERROR(_state->append_error_msg_to_file(
782
0
                                [&]() -> std::string {
783
0
                                    return _src_block_ptr->dump_one_line(i, _num_of_columns_from_file);
784
0
                                },
785
0
                                [&]() -> std::string {
786
0
                                    auto raw_value =
787
0
                                            _src_block_ptr->get_by_position(_dest_slot_to_src_slot_index[dest_index]).column->get_data_at(i);
788
0
                                    std::string raw_string = raw_value.to_string();
789
0
                                    fmt::memory_buffer error_msg;
790
0
                                    fmt::format_to(error_msg,"column({}) value is incorrect while strict mode is {}, src value is {}",
791
0
                                            slot_desc->col_name(), _strict_mode, raw_string);
792
0
                                    return fmt::to_string(error_msg);
793
0
                                }));
794
0
                        } else if (!slot_desc->is_nullable()) {
795
0
                            filter_map[i] = false;
796
0
                            RETURN_IF_ERROR(_state->append_error_msg_to_file(
797
0
                                [&]() -> std::string {
798
0
                                    return _src_block_ptr->dump_one_line(i, _num_of_columns_from_file);
799
0
                                },
800
0
                                [&]() -> std::string {
801
0
                                    fmt::memory_buffer error_msg;
802
0
                                    fmt::format_to(error_msg, "column({}) values is null while columns is not nullable", slot_desc->col_name());
803
0
                                    return fmt::to_string(error_msg);
804
0
                                }));
805
0
                        }
806
                        // clang-format on
807
0
                    }
808
0
                }
809
0
            }
810
0
            if (!slot_desc->is_nullable()) {
811
0
                column_ptr = remove_nullable(column_ptr);
812
0
            }
813
0
        } else if (slot_desc->is_nullable()) {
814
0
            column_ptr = make_nullable(column_ptr);
815
0
        }
816
0
        mutable_output_columns[j]->insert_range_from(*column_ptr, 0, rows);
817
0
        ctx_idx++;
818
0
    }
819
820
    // after do the dest block insert operation, clear _src_block to remove the reference of origin column
821
0
    _src_block_ptr->clear();
822
823
0
    size_t dest_size = block->columns();
824
    // do filter
825
0
    block->insert(ColumnWithTypeAndName(std::move(filter_column), std::make_shared<DataTypeUInt8>(),
826
0
                                        "filter column"));
827
0
    RETURN_IF_ERROR(Block::filter_block(block, dest_size, dest_size));
828
829
0
    _counter.num_rows_filtered += rows - block->rows();
830
0
    return Status::OK();
831
0
}
832
833
24
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
24
    if (!_state->query_options().truncate_char_or_varchar_columns) {
837
24
        return Status::OK();
838
24
    }
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
24
}
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
0
Status FileScanner::_create_row_id_column_iterator() {
899
0
    auto& id_file_map = _state->get_id_file_map();
900
0
    auto file_id = id_file_map->get_file_mapping_id(
901
0
            std::make_shared<FileMapping>(((FileScanLocalState*)_local_state)->parent_id(),
902
0
                                          _current_range, _should_enable_file_meta_cache()));
903
0
    _row_id_column_iterator_pair.first = std::make_shared<RowIdColumnIteratorV2>(
904
0
            IdManager::ID_VERSION, BackendOptions::get_backend_id(), file_id);
905
0
    return Status::OK();
906
0
}
907
908
1
Status FileScanner::_get_next_reader() {
909
1
    while (true) {
910
1
        if (_cur_reader) {
911
0
            _cur_reader->collect_profile_before_close();
912
0
            RETURN_IF_ERROR(_cur_reader->close());
913
0
            _state->update_num_finished_scan_range(1);
914
0
        }
915
1
        _cur_reader.reset(nullptr);
916
1
        _src_block_init = false;
917
1
        bool has_next = _first_scan_range;
918
1
        if (!_first_scan_range) {
919
1
            RETURN_IF_ERROR(_split_source->get_next(&has_next, &_current_range));
920
1
        }
921
1
        _first_scan_range = false;
922
1
        if (!has_next || _should_stop) {
923
0
            _scanner_eof = true;
924
0
            return Status::OK();
925
0
        }
926
927
1
        const TFileRangeDesc& range = _current_range;
928
1
        _current_range_path = range.path;
929
930
1
        if (!_partition_slot_descs.empty()) {
931
            // we need get partition columns first for runtime filter partition pruning
932
0
            RETURN_IF_ERROR(_generate_partition_columns());
933
934
0
            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
0
                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
0
                bool can_filter_all = false;
943
0
                RETURN_IF_ERROR(_process_runtime_filters_partition_prune(can_filter_all));
944
0
                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
0
            }
951
0
        }
952
953
        // create reader for specific format
954
1
        Status init_status = Status::OK();
955
1
        TFileFormatType::type format_type = _get_current_format_type();
956
        // for compatibility, this logic is deprecated in 3.1
957
1
        if (format_type == TFileFormatType::FORMAT_JNI && range.__isset.table_format_params) {
958
0
            if (range.table_format_params.table_format_type == "paimon" &&
959
0
                !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
0
        }
971
972
        // JNI reader can only push down column value range
973
1
        bool push_down_predicates = !_is_load && format_type != TFileFormatType::FORMAT_JNI;
974
1
        bool need_to_get_parsed_schema = false;
975
1
        switch (format_type) {
976
1
        case TFileFormatType::FORMAT_JNI: {
977
1
            if (range.__isset.table_format_params &&
978
1
                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
1
            } else if (range.__isset.table_format_params &&
990
1
                       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
1
            } else if (range.__isset.table_format_params &&
1011
1
                       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
1
            } else if (range.__isset.table_format_params &&
1018
1
                       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
1
            } else if (range.__isset.table_format_params &&
1023
1
                       range.table_format_params.table_format_type == "jdbc") {
1024
                // Extract jdbc params from table_format_params
1025
0
                std::map<std::string, std::string> jdbc_params(
1026
0
                        range.table_format_params.jdbc_params.begin(),
1027
0
                        range.table_format_params.jdbc_params.end());
1028
0
                _cur_reader = JdbcJniReader::create_unique(_file_slot_descs, _state, _profile,
1029
0
                                                           jdbc_params);
1030
0
                init_status = ((JdbcJniReader*)(_cur_reader.get()))->init_reader();
1031
0
            }
1032
            // Set col_name_to_block_idx for JNI readers to avoid repeated map creation
1033
1
            if (_cur_reader) {
1034
0
                if (auto* jni_reader = dynamic_cast<JniReader*>(_cur_reader.get())) {
1035
0
                    jni_reader->set_col_name_to_block_idx(&_src_block_name_to_idx);
1036
0
                }
1037
0
            }
1038
1
            break;
1039
1
        }
1040
0
        case TFileFormatType::FORMAT_PARQUET: {
1041
0
            auto file_meta_cache_ptr = _should_enable_file_meta_cache()
1042
0
                                               ? ExecEnv::GetInstance()->file_meta_cache()
1043
0
                                               : nullptr;
1044
0
            std::unique_ptr<ParquetReader> parquet_reader = ParquetReader::create_unique(
1045
0
                    _profile, *_params, range, _state->query_options().batch_size,
1046
0
                    &_state->timezone_obj(), _io_ctx.get(), _state, file_meta_cache_ptr,
1047
0
                    _state->query_options().enable_parquet_lazy_mat);
1048
1049
0
            if (_row_id_column_iterator_pair.second != -1) {
1050
0
                RETURN_IF_ERROR(_create_row_id_column_iterator());
1051
0
                parquet_reader->set_row_id_column_iterator(_row_id_column_iterator_pair);
1052
0
            }
1053
1054
            // ATTN: the push down agg type may be set back to NONE,
1055
            // see IcebergTableReader::init_row_filters for example.
1056
0
            parquet_reader->set_push_down_agg_type(_get_push_down_agg_type());
1057
0
            if (push_down_predicates) {
1058
0
                RETURN_IF_ERROR(_process_late_arrival_conjuncts());
1059
0
            }
1060
0
            RETURN_IF_ERROR(_init_parquet_reader(std::move(parquet_reader), file_meta_cache_ptr));
1061
1062
0
            need_to_get_parsed_schema = true;
1063
0
            break;
1064
0
        }
1065
0
        case TFileFormatType::FORMAT_ORC: {
1066
0
            auto file_meta_cache_ptr = _should_enable_file_meta_cache()
1067
0
                                               ? ExecEnv::GetInstance()->file_meta_cache()
1068
0
                                               : nullptr;
1069
0
            std::unique_ptr<OrcReader> orc_reader = OrcReader::create_unique(
1070
0
                    _profile, _state, *_params, range, _state->query_options().batch_size,
1071
0
                    _state->timezone(), _io_ctx.get(), file_meta_cache_ptr,
1072
0
                    _state->query_options().enable_orc_lazy_mat);
1073
0
            if (_row_id_column_iterator_pair.second != -1) {
1074
0
                RETURN_IF_ERROR(_create_row_id_column_iterator());
1075
0
                orc_reader->set_row_id_column_iterator(_row_id_column_iterator_pair);
1076
0
            }
1077
1078
0
            orc_reader->set_push_down_agg_type(_get_push_down_agg_type());
1079
0
            if (push_down_predicates) {
1080
0
                RETURN_IF_ERROR(_process_late_arrival_conjuncts());
1081
0
            }
1082
0
            RETURN_IF_ERROR(_init_orc_reader(std::move(orc_reader), file_meta_cache_ptr));
1083
1084
0
            need_to_get_parsed_schema = true;
1085
0
            break;
1086
0
        }
1087
0
        case TFileFormatType::FORMAT_CSV_PLAIN:
1088
0
        case TFileFormatType::FORMAT_CSV_GZ:
1089
0
        case TFileFormatType::FORMAT_CSV_BZ2:
1090
0
        case TFileFormatType::FORMAT_CSV_LZ4FRAME:
1091
0
        case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
1092
0
        case TFileFormatType::FORMAT_CSV_LZOP:
1093
0
        case TFileFormatType::FORMAT_CSV_DEFLATE:
1094
0
        case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
1095
0
        case TFileFormatType::FORMAT_PROTO: {
1096
0
            auto reader = CsvReader::create_unique(_state, _profile, &_counter, *_params, range,
1097
0
                                                   _file_slot_descs, _io_ctx.get());
1098
1099
0
            init_status = reader->init_reader(_is_load);
1100
0
            _cur_reader = std::move(reader);
1101
0
            break;
1102
0
        }
1103
0
        case TFileFormatType::FORMAT_TEXT: {
1104
0
            auto reader = TextReader::create_unique(_state, _profile, &_counter, *_params, range,
1105
0
                                                    _file_slot_descs, _io_ctx.get());
1106
0
            init_status = reader->init_reader(_is_load);
1107
0
            _cur_reader = std::move(reader);
1108
0
            break;
1109
0
        }
1110
0
        case TFileFormatType::FORMAT_JSON: {
1111
0
            _cur_reader =
1112
0
                    NewJsonReader::create_unique(_state, _profile, &_counter, *_params, range,
1113
0
                                                 _file_slot_descs, &_scanner_eof, _io_ctx.get());
1114
0
            init_status = ((NewJsonReader*)(_cur_reader.get()))
1115
0
                                  ->init_reader(_col_default_value_ctx, _is_load);
1116
0
            break;
1117
0
        }
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
0
        }
1124
0
        case TFileFormatType::FORMAT_NATIVE: {
1125
0
            auto reader =
1126
0
                    NativeReader::create_unique(_profile, *_params, range, _io_ctx.get(), _state);
1127
0
            init_status = reader->init_reader();
1128
0
            _cur_reader = std::move(reader);
1129
0
            need_to_get_parsed_schema = false;
1130
0
            break;
1131
0
        }
1132
0
        case TFileFormatType::FORMAT_ARROW: {
1133
0
            if (range.__isset.table_format_params &&
1134
0
                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
0
            } else {
1143
0
                _cur_reader =
1144
0
                        ArrowStreamReader::create_unique(_state, _profile, &_counter, *_params,
1145
0
                                                         range, _file_slot_descs, _io_ctx.get());
1146
0
                init_status = ((ArrowStreamReader*)(_cur_reader.get()))->init_reader();
1147
0
            }
1148
0
            break;
1149
0
        }
1150
0
        default:
1151
0
            return Status::NotSupported("Not supported create reader for file format: {}.",
1152
0
                                        to_string(_params->format_type));
1153
1
        }
1154
1155
1
        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
0
        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
0
        if (init_status.is<END_OF_FILE>()) {
1168
0
            COUNTER_UPDATE(_empty_file_counter, 1);
1169
0
            continue;
1170
0
        } 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
0
        } else if (!init_status.ok()) {
1177
0
            return Status::InternalError("failed to init reader, err: {}", init_status.to_string());
1178
0
        }
1179
1180
0
        _cur_reader->set_push_down_agg_type(_get_push_down_agg_type());
1181
0
        if (_get_push_down_agg_type() == TPushAggOp::type::COUNT &&
1182
0
            range.__isset.table_format_params &&
1183
0
            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
0
        } else {
1190
0
            Status status = _set_fill_or_truncate_columns(need_to_get_parsed_schema);
1191
0
            if (status.is<END_OF_FILE>()) { // all parquet row groups are filtered
1192
0
                continue;
1193
0
            } 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
0
        }
1198
0
        _cur_reader_eof = false;
1199
0
        break;
1200
0
    }
1201
0
    return Status::OK();
1202
1
}
1203
1204
Status FileScanner::_init_parquet_reader(std::unique_ptr<ParquetReader>&& parquet_reader,
1205
14
                                         FileMetaCache* file_meta_cache_ptr) {
1206
14
    const TFileRangeDesc& range = _current_range;
1207
14
    Status init_status = Status::OK();
1208
1209
14
    phmap::flat_hash_map<int, std::vector<std::shared_ptr<ColumnPredicate>>> slot_id_to_predicates =
1210
14
            _local_state
1211
14
                    ? _local_state->cast<FileScanLocalState>()._slot_id_to_predicates
1212
14
                    : phmap::flat_hash_map<int, std::vector<std::shared_ptr<ColumnPredicate>>> {};
1213
14
    if (range.__isset.table_format_params &&
1214
14
        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
14
    } else if (range.__isset.table_format_params &&
1225
14
               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
14
    } else if (range.__isset.table_format_params &&
1237
14
               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
14
    } 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
14
    } else if (range.table_format_params.table_format_type == "tvf") {
1258
0
        const FieldDescriptor* parquet_meta = nullptr;
1259
0
        RETURN_IF_ERROR(parquet_reader->get_file_metadata_schema(&parquet_meta));
1260
0
        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
0
        std::shared_ptr<TableSchemaChangeHelper::Node> tvf_info_node = nullptr;
1266
0
        RETURN_IF_ERROR(TableSchemaChangeHelper::BuildTableInfoUtil::by_parquet_name(
1267
0
                _real_tuple_desc, *parquet_meta, tvf_info_node));
1268
0
        init_status = parquet_reader->init_reader(
1269
0
                _file_col_names, &_src_block_name_to_idx, _push_down_conjuncts,
1270
0
                slot_id_to_predicates, _real_tuple_desc, _default_val_row_desc.get(),
1271
0
                _col_name_to_slot_id, &_not_single_slot_filter_conjuncts,
1272
0
                &_slot_id_to_filter_conjuncts, tvf_info_node);
1273
0
        _cur_reader = std::move(parquet_reader);
1274
0
    } else if (_is_load) {
1275
0
        const FieldDescriptor* parquet_meta = nullptr;
1276
0
        RETURN_IF_ERROR(parquet_reader->get_file_metadata_schema(&parquet_meta));
1277
0
        DCHECK(parquet_meta != nullptr);
1278
1279
        // Load is case-insensitive, so you to match the columns in the file.
1280
0
        std::map<std::string, std::string> file_lower_name_to_native;
1281
0
        for (const auto& parquet_field : parquet_meta->get_fields_schema()) {
1282
0
            file_lower_name_to_native.emplace(doris::to_lower(parquet_field.name),
1283
0
                                              parquet_field.name);
1284
0
        }
1285
0
        auto load_info_node = std::make_shared<TableSchemaChangeHelper::StructNode>();
1286
0
        for (const auto slot : _real_tuple_desc->slots()) {
1287
0
            if (file_lower_name_to_native.contains(slot->col_name())) {
1288
0
                load_info_node->add_children(slot->col_name(),
1289
0
                                             file_lower_name_to_native[slot->col_name()],
1290
0
                                             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
0
            } else {
1295
0
                load_info_node->add_not_exist_children(slot->col_name());
1296
0
            }
1297
0
        }
1298
1299
0
        init_status = parquet_reader->init_reader(
1300
0
                _file_col_names, &_src_block_name_to_idx, _push_down_conjuncts,
1301
0
                slot_id_to_predicates, _real_tuple_desc, _default_val_row_desc.get(),
1302
0
                _col_name_to_slot_id, &_not_single_slot_filter_conjuncts,
1303
0
                &_slot_id_to_filter_conjuncts, load_info_node);
1304
0
        _cur_reader = std::move(parquet_reader);
1305
0
    }
1306
1307
14
    return init_status;
1308
14
}
1309
1310
Status FileScanner::_init_orc_reader(std::unique_ptr<OrcReader>&& orc_reader,
1311
10
                                     FileMetaCache* file_meta_cache_ptr) {
1312
10
    const TFileRangeDesc& range = _current_range;
1313
10
    Status init_status = Status::OK();
1314
1315
10
    if (range.__isset.table_format_params &&
1316
10
        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
10
    } else if (range.__isset.table_format_params &&
1328
10
               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
10
    } else if (range.__isset.table_format_params &&
1339
10
               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
10
    } else if (range.__isset.table_format_params &&
1351
10
               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
10
    } else if (range.__isset.table_format_params &&
1362
10
               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
10
    } else if (range.__isset.table_format_params &&
1373
0
               range.table_format_params.table_format_type == "tvf") {
1374
0
        const orc::Type* orc_type_ptr = nullptr;
1375
0
        RETURN_IF_ERROR(orc_reader->get_file_type(&orc_type_ptr));
1376
1377
0
        std::shared_ptr<TableSchemaChangeHelper::Node> tvf_info_node = nullptr;
1378
0
        RETURN_IF_ERROR(TableSchemaChangeHelper::BuildTableInfoUtil::by_orc_name(
1379
0
                _real_tuple_desc, orc_type_ptr, tvf_info_node));
1380
0
        init_status = orc_reader->init_reader(
1381
0
                &_file_col_names, &_src_block_name_to_idx, _push_down_conjuncts, false,
1382
0
                _real_tuple_desc, _default_val_row_desc.get(), &_not_single_slot_filter_conjuncts,
1383
0
                &_slot_id_to_filter_conjuncts, tvf_info_node);
1384
0
        _cur_reader = std::move(orc_reader);
1385
0
    } else if (_is_load) {
1386
0
        const orc::Type* orc_type_ptr = nullptr;
1387
0
        RETURN_IF_ERROR(orc_reader->get_file_type(&orc_type_ptr));
1388
1389
0
        std::map<std::string, std::string> file_lower_name_to_native;
1390
0
        for (uint64_t idx = 0; idx < orc_type_ptr->getSubtypeCount(); idx++) {
1391
0
            file_lower_name_to_native.emplace(doris::to_lower(orc_type_ptr->getFieldName(idx)),
1392
0
                                              orc_type_ptr->getFieldName(idx));
1393
0
        }
1394
1395
0
        auto load_info_node = std::make_shared<TableSchemaChangeHelper::StructNode>();
1396
0
        for (const auto slot : _real_tuple_desc->slots()) {
1397
0
            if (file_lower_name_to_native.contains(slot->col_name())) {
1398
0
                load_info_node->add_children(slot->col_name(),
1399
0
                                             file_lower_name_to_native[slot->col_name()],
1400
0
                                             TableSchemaChangeHelper::ConstNode::get_instance());
1401
0
            } else {
1402
0
                load_info_node->add_not_exist_children(slot->col_name());
1403
0
            }
1404
0
        }
1405
0
        init_status = orc_reader->init_reader(
1406
0
                &_file_col_names, &_src_block_name_to_idx, _push_down_conjuncts, false,
1407
0
                _real_tuple_desc, _default_val_row_desc.get(), &_not_single_slot_filter_conjuncts,
1408
0
                &_slot_id_to_filter_conjuncts, load_info_node);
1409
0
        _cur_reader = std::move(orc_reader);
1410
0
    }
1411
1412
10
    return init_status;
1413
10
}
1414
1415
24
Status FileScanner::_set_fill_or_truncate_columns(bool need_to_get_parsed_schema) {
1416
24
    _missing_cols.clear();
1417
24
    _slot_lower_name_to_col_type.clear();
1418
24
    std::unordered_map<std::string, DataTypePtr> name_to_col_type;
1419
24
    RETURN_IF_ERROR(_cur_reader->get_columns(&name_to_col_type, &_missing_cols));
1420
300
    for (const auto& [col_name, col_type] : name_to_col_type) {
1421
300
        auto col_name_lower = to_lower(col_name);
1422
300
        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
0
            continue;
1434
0
        }
1435
300
        _slot_lower_name_to_col_type.emplace(col_name_lower, col_type);
1436
300
    }
1437
1438
24
    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
24
    RETURN_IF_ERROR(_generate_missing_columns());
1450
24
    if (_fill_partition_from_path) {
1451
24
        RETURN_IF_ERROR(_cur_reader->set_fill_columns(_partition_col_descs, _missing_col_descs));
1452
24
    } else {
1453
        // If the partition columns are not from path, we only fill the missing columns.
1454
0
        RETURN_IF_ERROR(_cur_reader->set_fill_columns({}, _missing_col_descs));
1455
0
    }
1456
24
    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
24
    RETURN_IF_ERROR(_generate_truncate_columns(need_to_get_parsed_schema));
1466
24
    return Status::OK();
1467
24
}
1468
1469
24
Status FileScanner::_generate_truncate_columns(bool need_to_get_parsed_schema) {
1470
24
    _source_file_col_name_types.clear();
1471
    //  The col names and types of source file, such as parquet, orc files.
1472
24
    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
24
    return Status::OK();
1487
24
}
1488
1489
15
Status FileScanner::prepare_for_read_lines(const TFileRangeDesc& range) {
1490
15
    _current_range = range;
1491
1492
15
    _file_cache_statistics.reset(new io::FileCacheStatistics());
1493
15
    _file_reader_stats.reset(new io::FileReaderStats());
1494
1495
15
    _file_read_bytes_counter =
1496
15
            ADD_COUNTER_WITH_LEVEL(_profile, FileReadBytesProfile, TUnit::BYTES, 1);
1497
15
    _file_read_time_counter = ADD_TIMER_WITH_LEVEL(_profile, FileReadTimeProfile, 1);
1498
1499
15
    RETURN_IF_ERROR(_init_io_ctx());
1500
15
    _io_ctx->file_cache_stats = _file_cache_statistics.get();
1501
15
    _io_ctx->file_reader_stats = _file_reader_stats.get();
1502
15
    _default_val_row_desc.reset(new RowDescriptor((TupleDescriptor*)_real_tuple_desc));
1503
15
    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
15
    _push_down_conjuncts.clear();
1507
15
    _not_single_slot_filter_conjuncts.clear();
1508
15
    _slot_id_to_filter_conjuncts.clear();
1509
15
    _kv_cache = nullptr;
1510
15
    return Status::OK();
1511
15
}
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
24
                                          int64_t* init_reader_ms, int64_t* get_block_ms) {
1517
24
    _current_range = range;
1518
24
    RETURN_IF_ERROR(_generate_partition_columns());
1519
1520
24
    TFileFormatType::type format_type = _get_current_format_type();
1521
24
    Status init_status = Status::OK();
1522
1523
24
    auto file_meta_cache_ptr = external_info.enable_file_meta_cache
1524
24
                                       ? ExecEnv::GetInstance()->file_meta_cache()
1525
24
                                       : nullptr;
1526
1527
24
    RETURN_IF_ERROR(scope_timer_run(
1528
24
            [&]() -> Status {
1529
24
                switch (format_type) {
1530
24
                case TFileFormatType::FORMAT_PARQUET: {
1531
24
                    std::unique_ptr<ParquetReader> parquet_reader = ParquetReader::create_unique(
1532
24
                            _profile, *_params, range, 1, &_state->timezone_obj(), _io_ctx.get(),
1533
24
                            _state, file_meta_cache_ptr, false);
1534
1535
24
                    RETURN_IF_ERROR(parquet_reader->read_by_rows(row_ids));
1536
24
                    RETURN_IF_ERROR(
1537
24
                            _init_parquet_reader(std::move(parquet_reader), file_meta_cache_ptr));
1538
24
                    break;
1539
24
                }
1540
24
                case TFileFormatType::FORMAT_ORC: {
1541
24
                    std::unique_ptr<OrcReader> orc_reader = OrcReader::create_unique(
1542
24
                            _profile, _state, *_params, range, 1, _state->timezone(), _io_ctx.get(),
1543
24
                            file_meta_cache_ptr, false);
1544
1545
24
                    RETURN_IF_ERROR(orc_reader->read_by_rows(row_ids));
1546
24
                    RETURN_IF_ERROR(_init_orc_reader(std::move(orc_reader), file_meta_cache_ptr));
1547
24
                    break;
1548
24
                }
1549
24
                default: {
1550
24
                    return Status::NotSupported(
1551
24
                            "Not support create lines reader for file format: {},"
1552
24
                            "only support parquet and orc.",
1553
24
                            to_string(_params->format_type));
1554
24
                }
1555
24
                }
1556
24
                return Status::OK();
1557
24
            },
1558
24
            init_reader_ms));
1559
1560
24
    RETURN_IF_ERROR(_set_fill_or_truncate_columns(true));
1561
24
    _cur_reader_eof = false;
1562
1563
24
    RETURN_IF_ERROR(scope_timer_run(
1564
24
            [&]() -> Status {
1565
24
                while (!_cur_reader_eof) {
1566
24
                    bool eof = false;
1567
24
                    RETURN_IF_ERROR(_get_block_impl(_state, result_block, &eof));
1568
24
                }
1569
24
                return Status::OK();
1570
24
            },
1571
24
            get_block_ms));
1572
1573
24
    _cur_reader->collect_profile_before_close();
1574
24
    RETURN_IF_ERROR(_cur_reader->close());
1575
1576
24
    COUNTER_UPDATE(_file_read_bytes_counter, _file_reader_stats->read_bytes);
1577
24
    COUNTER_UPDATE(_file_read_time_counter, _file_reader_stats->read_time_ns);
1578
24
    return Status::OK();
1579
24
}
1580
1581
24
Status FileScanner::_generate_partition_columns() {
1582
24
    _partition_col_descs.clear();
1583
24
    _partition_value_is_null.clear();
1584
24
    const TFileRangeDesc& range = _current_range;
1585
24
    if (range.__isset.columns_from_path && !_partition_slot_descs.empty()) {
1586
0
        for (const auto& slot_desc : _partition_slot_descs) {
1587
0
            if (slot_desc) {
1588
0
                auto it = _partition_slot_index_map.find(slot_desc->id());
1589
0
                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
0
                const std::string& column_from_path = range.columns_from_path[it->second];
1594
0
                _partition_col_descs.emplace(slot_desc->col_name(),
1595
0
                                             std::make_tuple(column_from_path, slot_desc));
1596
0
                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
0
            }
1601
0
        }
1602
0
    }
1603
24
    return Status::OK();
1604
24
}
1605
1606
24
Status FileScanner::_generate_missing_columns() {
1607
24
    _missing_col_descs.clear();
1608
24
    if (!_missing_cols.empty()) {
1609
0
        for (auto* slot_desc : _real_tuple_desc->slots()) {
1610
0
            if (!_missing_cols.contains(slot_desc->col_name())) {
1611
0
                continue;
1612
0
            }
1613
1614
0
            auto it = _col_default_value_ctx.find(slot_desc->col_name());
1615
0
            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
0
            _missing_col_descs.emplace(slot_desc->col_name(), it->second);
1620
0
        }
1621
0
    }
1622
24
    return Status::OK();
1623
24
}
1624
1625
15
Status FileScanner::_init_expr_ctxes() {
1626
15
    std::map<SlotId, int> full_src_index_map;
1627
15
    std::map<SlotId, SlotDescriptor*> full_src_slot_map;
1628
15
    std::map<std::string, int> partition_name_to_key_index_map;
1629
15
    int index = 0;
1630
108
    for (const auto& slot_desc : _real_tuple_desc->slots()) {
1631
108
        full_src_slot_map.emplace(slot_desc->id(), slot_desc);
1632
108
        full_src_index_map.emplace(slot_desc->id(), index++);
1633
108
    }
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
15
    if (_current_range.__isset.columns_from_path_keys) {
1642
0
        std::vector<std::string> key_map = _current_range.columns_from_path_keys;
1643
0
        if (!key_map.empty()) {
1644
0
            for (size_t i = 0; i < key_map.size(); i++) {
1645
0
                partition_name_to_key_index_map.emplace(key_map[i], i);
1646
0
            }
1647
0
        }
1648
0
    }
1649
1650
15
    _num_of_columns_from_file = _params->num_of_columns_from_file;
1651
1652
108
    for (const auto& slot_info : _params->required_slots) {
1653
108
        auto slot_id = slot_info.slot_id;
1654
108
        auto it = full_src_slot_map.find(slot_id);
1655
108
        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
108
        if (it->second->col_name().starts_with(BeConsts::GLOBAL_ROWID_COL)) {
1660
0
            _row_id_column_iterator_pair.second = _default_val_row_desc->get_column_id(slot_id);
1661
0
            continue;
1662
0
        }
1663
1664
108
        if (slot_info.is_file_slot) {
1665
108
            _is_file_slot.emplace(slot_id);
1666
108
            _file_slot_descs.emplace_back(it->second);
1667
108
            _file_col_names.push_back(it->second->col_name());
1668
108
        }
1669
1670
108
        if (partition_name_to_key_index_map.contains(it->second->col_name())) {
1671
0
            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
0
            } 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
0
            _partition_slot_descs.emplace_back(it->second);
1683
0
            if (_is_load) {
1684
0
                auto iti = full_src_index_map.find(slot_id);
1685
0
                _partition_slot_index_map.emplace(slot_id, iti->second - _num_of_columns_from_file);
1686
0
            } 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
0
        }
1691
108
    }
1692
1693
    // set column name to default value expr map
1694
108
    for (auto* slot_desc : _real_tuple_desc->slots()) {
1695
108
        VExprContextSPtr ctx;
1696
108
        auto it = _params->default_value_of_src_slot.find(slot_desc->id());
1697
108
        if (it != std::end(_params->default_value_of_src_slot)) {
1698
0
            if (!it->second.nodes.empty()) {
1699
0
                RETURN_IF_ERROR(VExpr::create_expr_tree(it->second, ctx));
1700
0
                RETURN_IF_ERROR(ctx->prepare(_state, *_default_val_row_desc));
1701
0
                RETURN_IF_ERROR(ctx->open(_state));
1702
0
            }
1703
            // if expr is empty, the default value will be null
1704
0
            _col_default_value_ctx.emplace(slot_desc->col_name(), ctx);
1705
0
        }
1706
108
    }
1707
1708
15
    if (_is_load) {
1709
        // follow desc expr map is only for load task.
1710
0
        bool has_slot_id_map = _params->__isset.dest_sid_to_src_sid_without_trans;
1711
0
        int idx = 0;
1712
0
        for (auto* slot_desc : _output_tuple_desc->slots()) {
1713
0
            auto it = _params->expr_of_dest_slot.find(slot_desc->id());
1714
0
            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
0
            VExprContextSPtr ctx;
1720
0
            if (!it->second.nodes.empty()) {
1721
0
                RETURN_IF_ERROR(VExpr::create_expr_tree(it->second, ctx));
1722
0
                RETURN_IF_ERROR(ctx->prepare(_state, *_src_row_desc));
1723
0
                RETURN_IF_ERROR(ctx->open(_state));
1724
0
            }
1725
0
            _dest_vexpr_ctx.emplace_back(ctx);
1726
0
            _dest_slot_name_to_idx[slot_desc->col_name()] = idx++;
1727
1728
0
            if (has_slot_id_map) {
1729
0
                auto it1 = _params->dest_sid_to_src_sid_without_trans.find(slot_desc->id());
1730
0
                if (it1 == std::end(_params->dest_sid_to_src_sid_without_trans)) {
1731
0
                    _src_slot_descs_order_by_dest.emplace_back(nullptr);
1732
0
                } else {
1733
0
                    auto _src_slot_it = full_src_slot_map.find(it1->second);
1734
0
                    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
0
                    _dest_slot_to_src_slot_index.emplace(_src_slot_descs_order_by_dest.size(),
1739
0
                                                         full_src_index_map[_src_slot_it->first]);
1740
0
                    _src_slot_descs_order_by_dest.emplace_back(_src_slot_it->second);
1741
0
                }
1742
0
            }
1743
0
        }
1744
0
    }
1745
15
    return Status::OK();
1746
15
}
1747
1748
2
bool FileScanner::_should_enable_condition_cache() {
1749
2
    return _condition_cache_digest != 0 && !_is_load &&
1750
2
           (!_conjuncts.empty() || !_push_down_conjuncts.empty());
1751
2
}
1752
1753
0
void FileScanner::_init_reader_condition_cache() {
1754
0
    _condition_cache = nullptr;
1755
0
    _condition_cache_ctx = nullptr;
1756
1757
0
    if (!_should_enable_condition_cache() || !_cur_reader) {
1758
0
        return;
1759
0
    }
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
0
    if (_cur_reader->has_delete_operations()) {
1765
0
        return;
1766
0
    }
1767
1768
0
    auto* cache = segment_v2::ConditionCache::instance();
1769
0
    _condition_cache_key = segment_v2::ConditionCache::ExternalCacheKey(
1770
0
            _current_range.path,
1771
0
            _current_range.__isset.modification_time ? _current_range.modification_time : 0,
1772
0
            _current_range.__isset.file_size ? _current_range.file_size : -1,
1773
0
            _condition_cache_digest,
1774
0
            _current_range.__isset.start_offset ? _current_range.start_offset : 0,
1775
0
            _current_range.__isset.size ? _current_range.size : -1);
1776
1777
0
    segment_v2::ConditionCacheHandle handle;
1778
0
    auto condition_cache_hit = cache->lookup(_condition_cache_key, &handle);
1779
0
    if (condition_cache_hit) {
1780
0
        _condition_cache = handle.get_filter_result();
1781
0
        _condition_cache_hit_count++;
1782
0
    } 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
0
        int64_t total_rows = _cur_reader->get_total_rows();
1790
0
        if (total_rows > 0) {
1791
0
            size_t num_granules = (total_rows + ConditionCacheContext::GRANULE_SIZE - 1) /
1792
0
                                  ConditionCacheContext::GRANULE_SIZE;
1793
0
            _condition_cache = std::make_shared<std::vector<bool>>(num_granules + 1, false);
1794
0
        }
1795
0
    }
1796
1797
0
    if (_condition_cache) {
1798
        // Create context to pass to readers (native readers use it; non-native readers ignore it)
1799
0
        _condition_cache_ctx = std::make_shared<ConditionCacheContext>();
1800
0
        _condition_cache_ctx->is_hit = condition_cache_hit;
1801
0
        _condition_cache_ctx->filter_result = _condition_cache;
1802
0
        _cur_reader->set_condition_cache_context(_condition_cache_ctx);
1803
0
    }
1804
0
}
1805
1806
2
void FileScanner::_finalize_reader_condition_cache() {
1807
2
    if (!_should_enable_condition_cache() || !_condition_cache_ctx ||
1808
2
        _condition_cache_ctx->is_hit) {
1809
2
        _condition_cache = nullptr;
1810
2
        _condition_cache_ctx = nullptr;
1811
2
        return;
1812
2
    }
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
0
    if (!_cur_reader_eof) {
1817
0
        _condition_cache = nullptr;
1818
0
        _condition_cache_ctx = nullptr;
1819
0
        return;
1820
0
    }
1821
1822
0
    auto* cache = segment_v2::ConditionCache::instance();
1823
0
    cache->insert(_condition_cache_key, std::move(_condition_cache));
1824
0
    _condition_cache = nullptr;
1825
0
    _condition_cache_ctx = nullptr;
1826
0
}
1827
1828
1
Status FileScanner::close(RuntimeState* state) {
1829
1
    if (!_try_close()) {
1830
0
        return Status::OK();
1831
0
    }
1832
1833
1
    _finalize_reader_condition_cache();
1834
1835
1
    if (_cur_reader) {
1836
0
        RETURN_IF_ERROR(_cur_reader->close());
1837
0
    }
1838
1839
1
    RETURN_IF_ERROR(Scanner::close(state));
1840
1
    return Status::OK();
1841
1
}
1842
1843
0
void FileScanner::try_stop() {
1844
0
    Scanner::try_stop();
1845
0
    if (_io_ctx) {
1846
0
        _io_ctx->should_stop = true;
1847
0
    }
1848
0
}
1849
1850
0
void FileScanner::update_realtime_counters() {
1851
0
    FileScanLocalState* local_state = static_cast<FileScanLocalState*>(_local_state);
1852
1853
0
    COUNTER_UPDATE(local_state->_scan_bytes, _file_reader_stats->read_bytes);
1854
0
    COUNTER_UPDATE(local_state->_scan_rows, _file_reader_stats->read_rows);
1855
1856
0
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_rows(
1857
0
            _file_reader_stats->read_rows);
1858
0
    _state->get_query_ctx()->resource_ctx()->io_context()->update_scan_bytes(
1859
0
            _file_reader_stats->read_bytes);
1860
1861
0
    int64_t delta_bytes_read_from_local =
1862
0
            _file_cache_statistics->bytes_read_from_local - _last_bytes_read_from_local;
1863
0
    int64_t delta_bytes_read_from_remote =
1864
0
            _file_cache_statistics->bytes_read_from_remote - _last_bytes_read_from_remote;
1865
0
    if (_file_cache_statistics->bytes_read_from_local == 0 &&
1866
0
        _file_cache_statistics->bytes_read_from_remote == 0) {
1867
0
        _state->get_query_ctx()
1868
0
                ->resource_ctx()
1869
0
                ->io_context()
1870
0
                ->update_scan_bytes_from_remote_storage(_file_reader_stats->read_bytes);
1871
0
        DorisMetrics::instance()->query_scan_bytes_from_local->increment(
1872
0
                _file_reader_stats->read_bytes);
1873
0
    } 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
0
    COUNTER_UPDATE(_file_read_bytes_counter, _file_reader_stats->read_bytes);
1887
1888
0
    DorisMetrics::instance()->query_scan_bytes->increment(_file_reader_stats->read_bytes);
1889
0
    DorisMetrics::instance()->query_scan_rows->increment(_file_reader_stats->read_rows);
1890
1891
0
    _file_reader_stats->read_bytes = 0;
1892
0
    _file_reader_stats->read_rows = 0;
1893
1894
0
    _last_bytes_read_from_local = _file_cache_statistics->bytes_read_from_local;
1895
0
    _last_bytes_read_from_remote = _file_cache_statistics->bytes_read_from_remote;
1896
0
}
1897
1898
0
void FileScanner::_collect_profile_before_close() {
1899
0
    Scanner::_collect_profile_before_close();
1900
0
    if (config::enable_file_cache && _state->query_options().enable_file_cache &&
1901
0
        _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
0
    if (_cur_reader != nullptr) {
1909
0
        _cur_reader->collect_profile_before_close();
1910
0
    }
1911
1912
0
    FileScanLocalState* local_state = static_cast<FileScanLocalState*>(_local_state);
1913
0
    COUNTER_UPDATE(local_state->_scan_bytes, _file_reader_stats->read_bytes);
1914
0
    COUNTER_UPDATE(local_state->_scan_rows, _file_reader_stats->read_rows);
1915
1916
0
    COUNTER_UPDATE(_file_read_bytes_counter, _file_reader_stats->read_bytes);
1917
0
    COUNTER_UPDATE(_file_read_calls_counter, _file_reader_stats->read_calls);
1918
0
    COUNTER_UPDATE(_file_read_time_counter, _file_reader_stats->read_time_ns);
1919
0
    COUNTER_UPDATE(local_state->_condition_cache_hit_counter, _condition_cache_hit_count);
1920
0
    if (_io_ctx) {
1921
0
        COUNTER_UPDATE(local_state->_condition_cache_filtered_rows_counter,
1922
0
                       _io_ctx->condition_cache_filtered_rows);
1923
0
    }
1924
1925
0
    DorisMetrics::instance()->query_scan_bytes->increment(_file_reader_stats->read_bytes);
1926
0
    DorisMetrics::instance()->query_scan_rows->increment(_file_reader_stats->read_rows);
1927
0
}
1928
1929
} // namespace doris