Coverage Report

Created: 2026-04-03 04:27

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