Coverage Report

Created: 2026-04-27 07:43

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