Coverage Report

Created: 2026-04-10 18:35

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