Coverage Report

Created: 2026-05-25 21:25

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