Coverage Report

Created: 2026-07-13 21:07

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