Coverage Report

Created: 2026-07-13 20:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format_v2/column_mapper.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 "format_v2/column_mapper.h"
19
20
#include <algorithm>
21
#include <cstddef>
22
#include <memory>
23
#include <optional>
24
#include <sstream>
25
#include <string_view>
26
#include <utility>
27
#include <vector>
28
29
#include "common/consts.h"
30
#include "common/exception.h"
31
#include "common/status.h"
32
#include "core/data_type/convert_field_to_type.h"
33
#include "core/data_type/data_type_array.h"
34
#include "core/data_type/data_type_map.h"
35
#include "core/data_type/data_type_nullable.h"
36
#include "core/data_type/data_type_string.h"
37
#include "core/data_type/data_type_struct.h"
38
#include "core/data_type/primitive_type.h"
39
#include "exprs/runtime_filter_expr.h"
40
#include "exprs/short_circuit_evaluation_expr.h"
41
#include "exprs/vcase_expr.h"
42
#include "exprs/vcast_expr.h"
43
#include "exprs/vcondition_expr.h"
44
#include "exprs/vectorized_fn_call.h"
45
#include "exprs/vexpr_context.h"
46
#include "exprs/vin_predicate.h"
47
#include "exprs/vliteral.h"
48
#include "format_v2/column_mapper_nested.h"
49
#include "format_v2/expr/cast.h"
50
#include "format_v2/file_reader.h"
51
#include "format_v2/schema_projection.h"
52
#include "format_v2/table_reader.h"
53
#include "gen_cpp/Exprs_types.h"
54
55
namespace doris::format {
56
57
namespace {
58
59
16
std::string mapping_mode_to_string(TableColumnMappingMode mode) {
60
16
    switch (mode) {
61
1
    case TableColumnMappingMode::BY_FIELD_ID:
62
1
        return "BY_FIELD_ID";
63
14
    case TableColumnMappingMode::BY_NAME:
64
14
        return "BY_NAME";
65
1
    case TableColumnMappingMode::BY_INDEX:
66
1
        return "BY_INDEX";
67
16
    }
68
0
    return "UNKNOWN";
69
16
}
70
71
402
bool column_has_name(const ColumnDefinition& column, const std::string& name) {
72
402
    if (to_lower(column.name) == to_lower(name)) {
73
175
        return true;
74
175
    }
75
227
    if (column.has_identifier_name() && to_lower(column.get_identifier_name()) == to_lower(name)) {
76
0
        return true;
77
0
    }
78
227
    return std::ranges::any_of(column.name_mapping, [&](const std::string& alias) {
79
10
        return to_lower(alias) == to_lower(name);
80
10
    });
81
227
}
82
83
277
bool column_names_match(const ColumnDefinition& lhs, const ColumnDefinition& rhs) {
84
277
    if (column_has_name(rhs, lhs.name)) {
85
166
        return true;
86
166
    }
87
111
    if (lhs.has_identifier_name() && column_has_name(rhs, lhs.get_identifier_name())) {
88
1
        return true;
89
1
    }
90
110
    return std::ranges::any_of(lhs.name_mapping, [&](const std::string& alias) {
91
18
        return column_has_name(rhs, alias);
92
18
    });
93
111
}
94
95
class ColumnMatcher {
96
public:
97
3
    virtual ~ColumnMatcher() = default;
98
    virtual const ColumnDefinition* find(
99
            const ColumnDefinition& table_column,
100
            const std::vector<ColumnDefinition>& file_schema) const = 0;
101
};
102
103
class FieldIdMatcher final : public ColumnMatcher {
104
public:
105
    const ColumnDefinition* find(const ColumnDefinition& table_column,
106
111
                                 const std::vector<ColumnDefinition>& file_schema) const override {
107
111
        if (!table_column.has_identifier_field_id()) {
108
7
            return nullptr;
109
7
        }
110
104
        const auto field_id = table_column.get_identifier_field_id();
111
168
        const auto field_it = std::ranges::find_if(file_schema, [&](const ColumnDefinition& field) {
112
168
            return field.has_identifier_field_id() && field.get_identifier_field_id() == field_id;
113
168
        });
114
104
        return field_it == file_schema.end() ? nullptr : &*field_it;
115
111
    }
116
};
117
118
class NameMatcher final : public ColumnMatcher {
119
public:
120
    const ColumnDefinition* find(const ColumnDefinition& table_column,
121
203
                                 const std::vector<ColumnDefinition>& file_schema) const override {
122
277
        const auto field_it = std::ranges::find_if(file_schema, [&](const ColumnDefinition& field) {
123
277
            return column_names_match(table_column, field);
124
277
        });
125
203
        return field_it == file_schema.end() ? nullptr : &*field_it;
126
203
    }
127
};
128
129
class PositionMatcher final : public ColumnMatcher {
130
public:
131
    const ColumnDefinition* find(const ColumnDefinition& table_column,
132
2
                                 const std::vector<ColumnDefinition>& file_schema) const override {
133
2
        if (!table_column.has_identifier_field_id()) {
134
2
            return nullptr;
135
2
        }
136
0
        const auto position = table_column.get_identifier_position();
137
0
        if (position < 0 || static_cast<size_t>(position) >= file_schema.size()) {
138
0
            return nullptr;
139
0
        }
140
0
        return &file_schema[static_cast<size_t>(position)];
141
0
    }
142
};
143
144
313
const ColumnMatcher& matcher_for_mode(TableColumnMappingMode mode) {
145
313
    static const FieldIdMatcher field_id_matcher;
146
313
    static const NameMatcher name_matcher;
147
313
    static const PositionMatcher position_matcher;
148
313
    switch (mode) {
149
111
    case TableColumnMappingMode::BY_FIELD_ID:
150
111
        return field_id_matcher;
151
200
    case TableColumnMappingMode::BY_NAME:
152
200
        return name_matcher;
153
2
    case TableColumnMappingMode::BY_INDEX:
154
2
        return position_matcher;
155
313
    }
156
0
    return field_id_matcher;
157
313
}
158
159
12
std::string virtual_column_type_to_string(TableVirtualColumnType type) {
160
12
    switch (type) {
161
9
    case TableVirtualColumnType::INVALID:
162
9
        return "INVALID";
163
1
    case TableVirtualColumnType::ROW_ID:
164
1
        return "ROW_ID";
165
1
    case TableVirtualColumnType::LAST_UPDATED_SEQUENCE_NUMBER:
166
1
        return "LAST_UPDATED_SEQUENCE_NUMBER";
167
1
    case TableVirtualColumnType::ICEBERG_ROWID:
168
1
        return "ICEBERG_ROWID";
169
12
    }
170
0
    return "UNKNOWN";
171
12
}
172
173
12
std::string filter_conversion_type_to_string(FilterConversionType type) {
174
12
    switch (type) {
175
3
    case FilterConversionType::COPY_DIRECTLY:
176
3
        return "COPY_DIRECTLY";
177
1
    case FilterConversionType::CAST_FILTER:
178
1
        return "CAST_FILTER";
179
1
    case FilterConversionType::READER_EXPRESSION:
180
1
        return "READER_EXPRESSION";
181
6
    case FilterConversionType::FINALIZE_ONLY:
182
6
        return "FINALIZE_ONLY";
183
1
    case FilterConversionType::CONSTANT:
184
1
        return "CONSTANT";
185
12
    }
186
0
    return "UNKNOWN";
187
12
}
188
189
47
std::string data_type_debug_string(const DataTypePtr& type) {
190
47
    return type == nullptr ? "null" : type->get_name();
191
47
}
192
193
11
std::string field_debug_string(const Field& field) {
194
11
    std::ostringstream out;
195
11
    out << "Field{type=" << type_to_string(field.get_type()) << ", value=";
196
11
    switch (field.get_type()) {
197
0
    case TYPE_NULL:
198
0
        out << "null";
199
0
        break;
200
9
    case TYPE_INT:
201
9
        out << field.get<TYPE_INT>();
202
9
        break;
203
0
    case TYPE_BIGINT:
204
0
        out << field.get<TYPE_BIGINT>();
205
0
        break;
206
2
    case TYPE_STRING:
207
2
        out << field.get<TYPE_STRING>();
208
2
        break;
209
0
    default:
210
0
        out << field.to_debug_string(0);
211
0
        break;
212
11
    }
213
11
    out << "}";
214
11
    return out.str();
215
11
}
216
217
template <typename T, typename Formatter>
218
50
std::string join_debug_strings(const std::vector<T>& values, Formatter formatter) {
219
50
    std::ostringstream out;
220
50
    out << "[";
221
72
    for (size_t i = 0; i < values.size(); ++i) {
222
22
        if (i > 0) {
223
1
            out << ", ";
224
1
        }
225
22
        out << formatter(values[i]);
226
22
    }
227
50
    out << "]";
228
50
    return out.str();
229
50
}
column_mapper.cpp:_ZN5doris6format12_GLOBAL__N_118join_debug_stringsINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEZNKS0_16ColumnDefinition12debug_stringEvE3$_0EES8_RKSt6vectorIT_SaISC_EET0_
Line
Count
Source
218
11
std::string join_debug_strings(const std::vector<T>& values, Formatter formatter) {
219
11
    std::ostringstream out;
220
11
    out << "[";
221
19
    for (size_t i = 0; i < values.size(); ++i) {
222
8
        if (i > 0) {
223
0
            out << ", ";
224
0
        }
225
8
        out << formatter(values[i]);
226
8
    }
227
11
    out << "]";
228
11
    return out.str();
229
11
}
column_mapper.cpp:_ZN5doris6format12_GLOBAL__N_118join_debug_stringsINS0_16ColumnDefinitionEZNKS3_12debug_stringB5cxx11EvE3$_1EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISC_EET0_
Line
Count
Source
218
11
std::string join_debug_strings(const std::vector<T>& values, Formatter formatter) {
219
11
    std::ostringstream out;
220
11
    out << "[";
221
12
    for (size_t i = 0; i < values.size(); ++i) {
222
1
        if (i > 0) {
223
0
            out << ", ";
224
0
        }
225
1
        out << formatter(values[i]);
226
1
    }
227
11
    out << "]";
228
11
    return out.str();
229
11
}
column_mapper.cpp:_ZN5doris6format12_GLOBAL__N_118join_debug_stringsINS0_16LocalColumnIndexEZNKS3_12debug_stringB5cxx11EvE3$_0EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISC_EET0_
Line
Count
Source
218
2
std::string join_debug_strings(const std::vector<T>& values, Formatter formatter) {
219
2
    std::ostringstream out;
220
2
    out << "[";
221
3
    for (size_t i = 0; i < values.size(); ++i) {
222
1
        if (i > 0) {
223
0
            out << ", ";
224
0
        }
225
1
        out << formatter(values[i]);
226
1
    }
227
2
    out << "]";
228
2
    return out.str();
229
2
}
column_mapper.cpp:_ZN5doris6format12_GLOBAL__N_118join_debug_stringsINS0_16ColumnDefinitionEZNKS0_13ColumnMapping12debug_stringB5cxx11EvE3$_0EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISD_EET0_
Line
Count
Source
218
12
std::string join_debug_strings(const std::vector<T>& values, Formatter formatter) {
219
12
    std::ostringstream out;
220
12
    out << "[";
221
17
    for (size_t i = 0; i < values.size(); ++i) {
222
5
        if (i > 0) {
223
0
            out << ", ";
224
0
        }
225
5
        out << formatter(values[i]);
226
5
    }
227
12
    out << "]";
228
12
    return out.str();
229
12
}
column_mapper.cpp:_ZN5doris6format12_GLOBAL__N_118join_debug_stringsINS0_13ColumnMappingEZNKS3_12debug_stringB5cxx11EvE3$_1EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISC_EET0_
Line
Count
Source
218
12
std::string join_debug_strings(const std::vector<T>& values, Formatter formatter) {
219
12
    std::ostringstream out;
220
12
    out << "[";
221
17
    for (size_t i = 0; i < values.size(); ++i) {
222
5
        if (i > 0) {
223
0
            out << ", ";
224
0
        }
225
5
        out << formatter(values[i]);
226
5
    }
227
12
    out << "]";
228
12
    return out.str();
229
12
}
column_mapper.cpp:_ZN5doris6format12_GLOBAL__N_118join_debug_stringsINS0_13ColumnMappingEZNKS0_17TableColumnMapper12debug_stringB5cxx11EvE3$_0EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISD_EET0_
Line
Count
Source
218
1
std::string join_debug_strings(const std::vector<T>& values, Formatter formatter) {
219
1
    std::ostringstream out;
220
1
    out << "[";
221
3
    for (size_t i = 0; i < values.size(); ++i) {
222
2
        if (i > 0) {
223
1
            out << ", ";
224
1
        }
225
2
        out << formatter(values[i]);
226
2
    }
227
1
    out << "]";
228
1
    return out.str();
229
1
}
column_mapper.cpp:_ZN5doris6format12_GLOBAL__N_118join_debug_stringsINS0_13ColumnMappingEZNKS0_17TableColumnMapper12debug_stringB5cxx11EvE3$_1EENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorIT_SaISD_EET0_
Line
Count
Source
218
1
std::string join_debug_strings(const std::vector<T>& values, Formatter formatter) {
219
1
    std::ostringstream out;
220
1
    out << "[";
221
1
    for (size_t i = 0; i < values.size(); ++i) {
222
0
        if (i > 0) {
223
0
            out << ", ";
224
0
        }
225
0
        out << formatter(values[i]);
226
0
    }
227
1
    out << "]";
228
1
    return out.str();
229
1
}
230
231
} // namespace
232
233
const Field* find_partition_value(const ColumnDefinition& table_column,
234
254
                                  const std::map<std::string, Field>& partition_values) {
235
407
    const auto find_by_name = [&](const std::string& name) -> const Field* {
236
407
        const auto value_it = partition_values.find(name);
237
407
        return value_it == partition_values.end() ? nullptr : &value_it->second;
238
407
    };
239
254
    if (const auto* value = find_by_name(table_column.name); value != nullptr) {
240
15
        return value;
241
15
    }
242
239
    if (table_column.has_identifier_name()) {
243
146
        if (const auto* value = find_by_name(table_column.get_identifier_name());
244
146
            value != nullptr) {
245
0
            return value;
246
0
        }
247
146
    }
248
239
    for (const auto& alias : table_column.name_mapping) {
249
7
        if (const auto* value = find_by_name(alias); value != nullptr) {
250
1
            return value;
251
1
        }
252
7
    }
253
238
    return nullptr;
254
239
}
255
256
struct FileSlotRewriteInfo {
257
    size_t block_position = 0;
258
    DataTypePtr file_type;
259
    DataTypePtr table_type;
260
    std::string file_column_name;
261
};
262
263
struct RewriteContext {
264
    RuntimeState* runtime_state = nullptr;
265
    std::vector<VExprSPtr> created_exprs {};
266
267
141
    void add_created_expr(VExprSPtr expr) { created_exprs.push_back(std::move(expr)); }
268
269
67
    Status prepare_created_exprs(VExprContext* context) const {
270
67
        DORIS_CHECK(context != nullptr);
271
67
        RowDescriptor row_desc;
272
139
        for (const auto& expr : created_exprs) {
273
139
            if (dynamic_cast<const Cast*>(expr.get()) != nullptr && runtime_state == nullptr) {
274
0
                return Status::InvalidArgument(
275
0
                        "RuntimeState is required to prepare rewritten cast expression {}",
276
0
                        expr->expr_name());
277
0
            }
278
139
            RETURN_IF_ERROR(expr->prepare(runtime_state, row_desc, context));
279
139
        }
280
67
        return Status::OK();
281
67
    }
282
};
283
284
static VExprSPtr create_file_slot_ref(const VSlotRef& slot_ref,
285
                                      const FileSlotRewriteInfo& rewrite_info,
286
74
                                      RewriteContext* rewrite_context) {
287
74
    auto ref =
288
74
            VSlotRef::create_shared(slot_ref.slot_id(), cast_set<int>(rewrite_info.block_position),
289
74
                                    -1, rewrite_info.file_type, rewrite_info.file_column_name);
290
74
    rewrite_context->add_created_expr(ref);
291
74
    return ref;
292
74
}
293
294
249
static bool is_cast_expr(const VExprSPtr& expr) {
295
249
    return dynamic_cast<const Cast*>(expr.get()) != nullptr;
296
249
}
297
298
161
static bool is_binary_comparison_predicate(const VExprSPtr& expr) {
299
161
    if (expr == nullptr || expr->get_num_children() != 2 ||
300
161
        (expr->node_type() != TExprNodeType::BINARY_PRED &&
301
107
         expr->node_type() != TExprNodeType::NULL_AWARE_BINARY_PRED)) {
302
107
        return false;
303
107
    }
304
54
    switch (expr->op()) {
305
3
    case TExprOpcode::EQ:
306
3
    case TExprOpcode::EQ_FOR_NULL:
307
3
    case TExprOpcode::NE:
308
3
    case TExprOpcode::GE:
309
50
    case TExprOpcode::GT:
310
50
    case TExprOpcode::LE:
311
54
    case TExprOpcode::LT:
312
54
        return true;
313
0
    default:
314
0
        return false;
315
54
    }
316
54
}
317
318
16
std::string TableColumnMapperOptions::debug_string() const {
319
16
    std::ostringstream out;
320
16
    out << "TableColumnMapperOptions{mode=" << mapping_mode_to_string(mode) << "}";
321
16
    return out.str();
322
16
}
323
324
11
std::string ColumnDefinition::debug_string() const {
325
11
    std::ostringstream out;
326
11
    out << "ColumnDefinition{name=" << name << ", identifier=" << field_debug_string(identifier)
327
11
        << ", name_mapping="
328
11
        << join_debug_strings(name_mapping, [](const std::string& name) { return name; })
329
11
        << ", local_id=" << local_id << ", type=" << data_type_debug_string(type) << ", children="
330
11
        << join_debug_strings(children,
331
11
                              [](const ColumnDefinition& child) { return child.debug_string(); })
332
11
        << ", has_default_expr=" << (default_expr != nullptr)
333
11
        << ", is_partition_key=" << is_partition_key << "}";
334
11
    return out.str();
335
11
}
336
337
2
std::string LocalColumnIndex::debug_string() const {
338
2
    std::ostringstream out;
339
2
    out << "LocalColumnIndex{index=" << index << ", project_all_children=" << project_all_children
340
2
        << ", children="
341
2
        << join_debug_strings(children,
342
2
                              [](const LocalColumnIndex& child) { return child.debug_string(); })
343
2
        << "}";
344
2
    return out.str();
345
2
}
346
347
12
std::string ColumnMapping::debug_string() const {
348
12
    std::ostringstream out;
349
12
    out << "ColumnMapping{global_index=" << global_index
350
12
        << ", table_column_name=" << table_column_name << ", file_local_id=";
351
12
    if (file_local_id.has_value()) {
352
7
        out << *file_local_id;
353
7
    } else {
354
5
        out << "null";
355
5
    }
356
12
    out << ", constant_index=";
357
12
    if (constant_index.has_value()) {
358
5
        out << *constant_index;
359
7
    } else {
360
7
        out << "null";
361
7
    }
362
12
    out << ", file_column_name=" << file_column_name
363
12
        << ", original_file_type=" << data_type_debug_string(original_file_type)
364
12
        << ", original_file_children="
365
12
        << join_debug_strings(original_file_children,
366
12
                              [](const ColumnDefinition& child) { return child.debug_string(); })
367
12
        << ", file_type=" << data_type_debug_string(file_type)
368
12
        << ", table_type=" << data_type_debug_string(table_type)
369
12
        << ", has_projection=" << (projection != nullptr) << ", child_mappings="
370
12
        << join_debug_strings(child_mappings,
371
12
                              [](const ColumnMapping& child) { return child.debug_string(); })
372
12
        << ", is_trivial=" << is_trivial << ", is_constant=" << constant_index.has_value()
373
12
        << ", filter_conversion=" << filter_conversion_type_to_string(filter_conversion)
374
12
        << ", virtual_column_type=" << virtual_column_type_to_string(virtual_column_type)
375
12
        << ", has_default_expr=" << (default_expr != nullptr) << "}";
376
12
    return out.str();
377
12
}
378
379
1
std::string TableColumnMapper::debug_string() const {
380
1
    std::ostringstream out;
381
1
    out << "TableColumnMapper{options=" << _options.debug_string() << ", mappings="
382
1
        << join_debug_strings(_mappings,
383
2
                              [](const ColumnMapping& mapping) { return mapping.debug_string(); })
384
1
        << ", hidden_mappings="
385
1
        << join_debug_strings(_hidden_mappings,
386
1
                              [](const ColumnMapping& mapping) { return mapping.debug_string(); })
387
1
        << ", constant_count=" << _constant_map.size() << "}";
388
1
    return out.str();
389
1
}
390
391
static const FileSlotRewriteInfo* find_slot_rewrite_info(
392
        const VExprSPtr& expr,
393
        const std::map<GlobalIndex, FileSlotRewriteInfo>& global_to_file_slot,
394
82
        const VSlotRef** slot_ref) {
395
82
    if (expr == nullptr) {
396
0
        return nullptr;
397
0
    }
398
82
    VExprSPtr slot_expr = expr;
399
82
    const bool input_is_cast = is_cast_expr(expr) && expr->get_num_children() == 1;
400
82
    if (is_cast_expr(expr) && expr->get_num_children() == 1) {
401
3
        slot_expr = expr->children()[0];
402
3
    }
403
82
    if (!slot_expr->is_slot_ref()) {
404
42
        return nullptr;
405
42
    }
406
40
    const auto* candidate_slot_ref = assert_cast<const VSlotRef*>(slot_expr.get());
407
40
    const auto rewrite_it = global_to_file_slot.find(slot_ref_global_index(*candidate_slot_ref));
408
40
    if (rewrite_it == global_to_file_slot.end()) {
409
0
        return nullptr;
410
0
    }
411
40
    if (input_is_cast && !expr->data_type()->equals(*rewrite_it->second.table_type)) {
412
1
        return nullptr;
413
1
    }
414
39
    if (slot_ref != nullptr) {
415
39
        *slot_ref = candidate_slot_ref;
416
39
    }
417
39
    return &rewrite_it->second;
418
40
}
419
420
325
static bool filter_conversion_has_local_source(FilterConversionType conversion) {
421
325
    switch (conversion) {
422
226
    case FilterConversionType::COPY_DIRECTLY:
423
277
    case FilterConversionType::CAST_FILTER:
424
298
    case FilterConversionType::READER_EXPRESSION:
425
298
        return true;
426
27
    case FilterConversionType::FINALIZE_ONLY:
427
27
    case FilterConversionType::CONSTANT:
428
27
        return false;
429
325
    }
430
0
    return false;
431
325
}
432
433
static bool table_filter_has_only_local_entries(
434
86
        const TableFilter& table_filter, const std::map<GlobalIndex, FilterEntry>& filter_entries) {
435
87
    for (const auto global_index : table_filter.global_indices) {
436
87
        const auto entry_it = filter_entries.find(global_index);
437
87
        if (entry_it == filter_entries.end() || !entry_it->second.is_local()) {
438
14
            return false;
439
14
        }
440
87
    }
441
72
    return true;
442
86
}
443
444
static VExprSPtr unwrap_literal_for_file_cast(const VExprSPtr& expr,
445
47
                                              const DataTypePtr& table_type) {
446
47
    if (expr == nullptr) {
447
0
        return nullptr;
448
0
    }
449
47
    if (expr->is_literal()) {
450
47
        return expr;
451
47
    }
452
0
    if (is_cast_expr(expr) && expr->get_num_children() == 1 && expr->children()[0]->is_literal() &&
453
0
        expr->children()[0]->data_type()->equals(*table_type)) {
454
0
        return expr->children()[0];
455
0
    }
456
0
    return nullptr;
457
0
}
458
459
0
static Field literal_field_from_expr(const VExpr& literal_expr) {
460
0
    DORIS_CHECK(literal_expr.is_literal());
461
0
    const auto* literal = dynamic_cast<const VLiteral*>(&literal_expr);
462
0
    DORIS_CHECK(literal != nullptr);
463
0
    Field field;
464
0
    literal->get_column_ptr()->get(0, field);
465
0
    return field;
466
0
}
467
468
// Table filter localization clones an already-prepared table expr and then rewrites it to file
469
// slots. Only split-local literals and BE cast nodes need table-reader-specific clone behavior;
470
// plain slot refs and literals use their own VExpr::clone_node().
471
403
static Status clone_table_expr_node(const VExpr& expr, VExprSPtr* cloned_expr) {
472
403
    DORIS_CHECK(cloned_expr != nullptr);
473
403
    if (const auto* split_literal = dynamic_cast<const SplitLocalFileLiteral*>(&expr)) {
474
0
        *cloned_expr = std::make_shared<SplitLocalFileLiteral>(
475
0
                split_literal->data_type(), literal_field_from_expr(expr),
476
0
                split_literal->original_type(), split_literal->original_field());
477
403
    } else if (const auto* vcast_expr = dynamic_cast<const VCastExpr*>(&expr);
478
403
               vcast_expr != nullptr && vcast_expr->node_type() == TExprNodeType::CAST_EXPR) {
479
0
        *cloned_expr = Cast::create_shared(vcast_expr->data_type());
480
0
    }
481
403
    return Status::OK();
482
403
}
483
484
109
Status clone_table_expr_tree(const VExprSPtr& expr, VExprSPtr* cloned_expr) {
485
109
    DORIS_CHECK(cloned_expr != nullptr);
486
109
    if (expr == nullptr) {
487
0
        *cloned_expr = nullptr;
488
0
        return Status::OK();
489
0
    }
490
109
    return expr->deep_clone(cloned_expr, clone_table_expr_node);
491
109
}
492
493
static VExprSPtr original_table_literal(const VExprSPtr& literal_expr,
494
51
                                        RewriteContext* rewrite_context = nullptr) {
495
51
    DORIS_CHECK(literal_expr != nullptr);
496
51
    DORIS_CHECK(literal_expr->is_literal());
497
51
    const auto* rewritten_literal = dynamic_cast<const SplitLocalFileLiteral*>(literal_expr.get());
498
51
    if (rewritten_literal == nullptr) {
499
51
        return literal_expr;
500
51
    }
501
0
    auto literal = VLiteral::create_shared(rewritten_literal->original_type(),
502
0
                                           rewritten_literal->original_field());
503
0
    if (rewrite_context != nullptr) {
504
0
        rewrite_context->add_created_expr(literal);
505
0
    }
506
0
    return literal;
507
51
}
508
509
85
static ColumnDefinition hidden_column_from_slot_ref(const VSlotRef& slot_ref) {
510
85
    ColumnDefinition column;
511
85
    column.name = slot_ref.column_name();
512
85
    column.identifier = Field::create_field<TYPE_STRING>(column.name);
513
85
    column.type = slot_ref.data_type();
514
85
    return column;
515
85
}
516
517
static void collect_top_level_slot_columns(const VExprSPtr& expr,
518
316
                                           std::map<GlobalIndex, ColumnDefinition>* columns) {
519
316
    DORIS_CHECK(columns != nullptr);
520
316
    if (expr == nullptr) {
521
0
        return;
522
0
    }
523
316
    if (expr->is_slot_ref()) {
524
85
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr.get());
525
85
        columns->try_emplace(slot_ref_global_index(*slot_ref),
526
85
                             hidden_column_from_slot_ref(*slot_ref));
527
85
        return;
528
85
    }
529
236
    for (const auto& child : expr->children()) {
530
236
        collect_top_level_slot_columns(child, columns);
531
236
    }
532
231
}
533
534
26
static std::optional<uint8_t> signed_integer_width(PrimitiveType type) {
535
26
    switch (type) {
536
0
    case TYPE_TINYINT:
537
0
        return 8;
538
0
    case TYPE_SMALLINT:
539
0
        return 16;
540
12
    case TYPE_INT:
541
12
        return 32;
542
7
    case TYPE_BIGINT:
543
7
        return 64;
544
0
    case TYPE_LARGEINT:
545
0
        return 128;
546
7
    default:
547
7
        return std::nullopt;
548
26
    }
549
26
}
550
551
3
static std::optional<uint8_t> floating_width(PrimitiveType type) {
552
3
    switch (type) {
553
0
    case TYPE_FLOAT:
554
0
        return 32;
555
1
    case TYPE_DOUBLE:
556
1
        return 64;
557
2
    default:
558
2
        return std::nullopt;
559
3
    }
560
3
}
561
562
5
static std::optional<uint8_t> floating_exact_integer_width(PrimitiveType type) {
563
5
    switch (type) {
564
0
    case TYPE_FLOAT:
565
0
        return 24;
566
3
    case TYPE_DOUBLE:
567
3
        return 53;
568
2
    default:
569
2
        return std::nullopt;
570
5
    }
571
5
}
572
573
static bool is_lossless_file_to_table_numeric_cast(const DataTypePtr& file_type,
574
38
                                                   const DataTypePtr& table_type) {
575
38
    const auto file_nested_type = remove_nullable(file_type);
576
38
    const auto table_nested_type = remove_nullable(table_type);
577
38
    if (file_nested_type->equals(*table_nested_type)) {
578
24
        return true;
579
24
    }
580
581
14
    const auto file_primitive_type = file_nested_type->get_primitive_type();
582
14
    const auto table_primitive_type = table_nested_type->get_primitive_type();
583
14
    if (const auto file_width = signed_integer_width(file_primitive_type)) {
584
12
        if (const auto table_width = signed_integer_width(table_primitive_type)) {
585
7
            return *table_width >= *file_width;
586
7
        }
587
5
        if (const auto table_width = floating_exact_integer_width(table_primitive_type)) {
588
3
            return *table_width >= *file_width;
589
3
        }
590
2
        return false;
591
5
    }
592
2
    if (const auto file_width = floating_width(file_primitive_type)) {
593
1
        const auto table_width = floating_width(table_primitive_type);
594
1
        return table_width.has_value() && *table_width >= *file_width;
595
1
    }
596
1
    return false;
597
2
}
598
599
static VExprSPtr rewrite_literal_to_file_type(const VExprSPtr& literal_expr,
600
                                              const FileSlotRewriteInfo& rewrite_info,
601
43
                                              RewriteContext* rewrite_context) {
602
43
    DORIS_CHECK(literal_expr != nullptr);
603
43
    DORIS_CHECK(literal_expr->is_literal());
604
43
    const auto original_literal = original_table_literal(literal_expr, rewrite_context);
605
43
    const Field original_field = literal_field(original_literal);
606
43
    if (rewrite_info.file_type->equals(*original_literal->data_type())) {
607
5
        return original_literal;
608
5
    }
609
    // A literal round trip alone cannot prove that file-local evaluation is safe: the file slot
610
    // itself may lose information when materialized as the table type. For example, DOUBLE 1.5
611
    // becomes BIGINT 1, so table predicate `value = 1` is true while file predicate
612
    // `value = 1.0` is false. Complex Field equality also does not compare nested contents.
613
    // Restrict localization to scalar numeric casts that preserve every file value; unsupported
614
    // and complex casts keep the table predicate and evaluate after materialization.
615
38
    if (!is_lossless_file_to_table_numeric_cast(rewrite_info.file_type,
616
38
                                                original_literal->data_type())) {
617
4
        return nullptr;
618
4
    }
619
34
    Field file_field;
620
34
    try {
621
34
        convert_field_to_type(original_field, *rewrite_info.file_type, &file_field,
622
34
                              original_literal->data_type().get());
623
34
    } catch (const Exception&) {
624
0
        return nullptr;
625
0
    }
626
34
    if (file_field.is_null()) {
627
0
        return nullptr;
628
0
    }
629
34
    if (file_field.get_type() != remove_nullable(rewrite_info.file_type)->get_primitive_type()) {
630
0
        return nullptr;
631
0
    }
632
34
    Field round_trip_field;
633
34
    try {
634
34
        convert_field_to_type(file_field, *original_literal->data_type(), &round_trip_field,
635
34
                              rewrite_info.file_type.get());
636
34
    } catch (const Exception&) {
637
0
        return nullptr;
638
0
    }
639
    // The file-to-table type check protects every possible file value. This round trip separately
640
    // proves that the specific predicate boundary is exactly representable in the file type.
641
34
    if (round_trip_field != original_field) {
642
2
        return nullptr;
643
2
    }
644
32
    auto literal = std::make_shared<SplitLocalFileLiteral>(
645
32
            rewrite_info.file_type, file_field, original_literal->data_type(), original_field);
646
32
    rewrite_context->add_created_expr(literal);
647
32
    return literal;
648
34
}
649
650
static bool rewrite_binary_slot_literal_predicate(
651
        const VExprSPtr& expr,
652
        const std::map<GlobalIndex, FileSlotRewriteInfo>& global_to_file_slot,
653
161
        RewriteContext* rewrite_context) {
654
161
    if (!is_binary_comparison_predicate(expr)) {
655
107
        return false;
656
107
    }
657
54
    auto children = expr->children();
658
54
    const VSlotRef* slot_ref = nullptr;
659
54
    const FileSlotRewriteInfo* rewrite_info =
660
54
            find_slot_rewrite_info(children[0], global_to_file_slot, &slot_ref);
661
54
    int slot_child_idx = 0;
662
54
    int literal_child_idx = 1;
663
54
    if (rewrite_info == nullptr) {
664
21
        rewrite_info = find_slot_rewrite_info(children[1], global_to_file_slot, &slot_ref);
665
21
        slot_child_idx = 1;
666
21
        literal_child_idx = 0;
667
21
    }
668
54
    if (rewrite_info == nullptr || slot_ref == nullptr) {
669
20
        return false;
670
20
    }
671
34
    auto literal_expr =
672
34
            unwrap_literal_for_file_cast(children[literal_child_idx], rewrite_info->table_type);
673
34
    if (literal_expr == nullptr) {
674
0
        return false;
675
0
    }
676
677
34
    auto rewritten_literal =
678
34
            rewrite_literal_to_file_type(literal_expr, *rewrite_info, rewrite_context);
679
34
    if (rewritten_literal == nullptr) {
680
4
        children[literal_child_idx] = original_table_literal(literal_expr, rewrite_context);
681
4
        expr->set_children(std::move(children));
682
4
        return false;
683
4
    }
684
685
30
    children[slot_child_idx] = create_file_slot_ref(*slot_ref, *rewrite_info, rewrite_context);
686
30
    children[literal_child_idx] = std::move(rewritten_literal);
687
30
    expr->set_children(std::move(children));
688
30
    return true;
689
34
}
690
691
static bool rewrite_in_slot_literal_predicate(
692
        const VExprSPtr& expr,
693
        const std::map<GlobalIndex, FileSlotRewriteInfo>& global_to_file_slot,
694
131
        RewriteContext* rewrite_context) {
695
131
    if (expr->node_type() != TExprNodeType::IN_PRED || expr->get_num_children() < 2) {
696
124
        return false;
697
124
    }
698
7
    auto children = expr->children();
699
7
    const VSlotRef* slot_ref = nullptr;
700
7
    const FileSlotRewriteInfo* rewrite_info =
701
7
            find_slot_rewrite_info(children[0], global_to_file_slot, &slot_ref);
702
7
    if (rewrite_info == nullptr || slot_ref == nullptr) {
703
2
        return false;
704
2
    }
705
706
5
    VExprSPtrs rewritten_literals;
707
5
    rewritten_literals.reserve(children.size() - 1);
708
12
    for (size_t child_idx = 1; child_idx < children.size(); ++child_idx) {
709
9
        auto literal_expr =
710
9
                unwrap_literal_for_file_cast(children[child_idx], rewrite_info->table_type);
711
9
        if (literal_expr == nullptr) {
712
0
            return false;
713
0
        }
714
9
        auto rewritten_literal =
715
9
                rewrite_literal_to_file_type(literal_expr, *rewrite_info, rewrite_context);
716
9
        if (rewritten_literal == nullptr) {
717
6
            for (size_t restore_idx = 1; restore_idx < children.size(); ++restore_idx) {
718
4
                auto restore_literal = unwrap_literal_for_file_cast(children[restore_idx],
719
4
                                                                    rewrite_info->table_type);
720
4
                if (restore_literal != nullptr) {
721
4
                    children[restore_idx] =
722
4
                            original_table_literal(restore_literal, rewrite_context);
723
4
                }
724
4
            }
725
2
            expr->set_children(std::move(children));
726
2
            return false;
727
2
        }
728
7
        rewritten_literals.push_back(std::move(rewritten_literal));
729
7
    }
730
731
3
    children[0] = create_file_slot_ref(*slot_ref, *rewrite_info, rewrite_context);
732
9
    for (size_t literal_idx = 0; literal_idx < rewritten_literals.size(); ++literal_idx) {
733
6
        children[literal_idx + 1] = std::move(rewritten_literals[literal_idx]);
734
6
    }
735
3
    expr->set_children(std::move(children));
736
3
    return true;
737
5
}
738
739
static VExprSPtr create_file_struct_child_name_literal(const std::string& file_child_name,
740
24
                                                       RewriteContext* rewrite_context) {
741
24
    auto literal = VLiteral::create_shared(std::make_shared<DataTypeString>(),
742
24
                                           Field::create_field<TYPE_STRING>(file_child_name));
743
24
    rewrite_context->add_created_expr(literal);
744
24
    return literal;
745
24
}
746
747
static bool needs_complex_file_slot_cast(const DataTypePtr& file_type,
748
13
                                         const DataTypePtr& table_type) {
749
13
    if (file_type == nullptr || table_type == nullptr || file_type->equals(*table_type)) {
750
0
        return false;
751
0
    }
752
13
    const auto file_nested_type = remove_nullable(file_type);
753
13
    const auto table_nested_type = remove_nullable(table_type);
754
13
    if (file_nested_type->equals(*table_nested_type)) {
755
0
        return false;
756
0
    }
757
13
    return is_complex_type(file_nested_type->get_primitive_type()) ||
758
13
           is_complex_type(table_nested_type->get_primitive_type());
759
13
}
760
761
24
static bool collect_struct_element_chain(const VExprSPtr& expr, std::vector<VExprSPtr>* chain) {
762
24
    DORIS_CHECK(chain != nullptr);
763
24
    if (!is_struct_element_expr(expr)) {
764
0
        return false;
765
0
    }
766
24
    const auto& parent = expr->children()[0];
767
24
    if (is_struct_element_expr(parent)) {
768
3
        if (!collect_struct_element_chain(parent, chain)) {
769
0
            return false;
770
0
        }
771
21
    } else if (!parent->is_slot_ref()) {
772
        // Only support file-local rewrite for struct child chains rooted directly at a top-level
773
        // slot, for example `element_at(s, 'a')` or `element_at(element_at(s, 'a'), 'b')`.
774
        //
775
        // Do not localize computed complex parents such as
776
        // `element_at(element_at(map_values(m), 1), 'full_name')`. The intermediate map/array
777
        // result has already been reshaped by scan projection and may have a different child order
778
        // from the table expression. Partially rewriting that expression against the file block can
779
        // silently evaluate the wrong struct child and filter out valid rows. Those predicates must
780
        // remain as table-level conjuncts and be evaluated after TableReader materialization.
781
0
        return false;
782
0
    }
783
24
    chain->push_back(expr);
784
24
    return true;
785
24
}
786
787
static bool rewrite_struct_element_path_to_file_expr(
788
        const VExprSPtr& expr, const std::vector<ColumnMapping>& mappings,
789
        const std::map<GlobalIndex, FileSlotRewriteInfo>& global_to_file_slot,
790
24
        RewriteContext* rewrite_context) {
791
24
    ResolvedNestedStructPath resolved;
792
24
    if (!resolve_nested_struct_expr_for_file(expr, mappings, &resolved)) {
793
3
        return false;
794
3
    }
795
796
21
    std::vector<VExprSPtr> struct_element_chain;
797
21
    if (!collect_struct_element_chain(expr, &struct_element_chain) ||
798
21
        struct_element_chain.size() != resolved.file_child_names.size() ||
799
21
        struct_element_chain.size() != resolved.file_child_types.size()) {
800
0
        return false;
801
0
    }
802
803
21
    auto root_children = struct_element_chain.front()->children();
804
21
    if (!root_children[0]->is_slot_ref()) {
805
0
        return false;
806
0
    }
807
21
    const auto* slot_ref = assert_cast<const VSlotRef*>(root_children[0].get());
808
21
    const auto rewrite_it = global_to_file_slot.find(slot_ref_global_index(*slot_ref));
809
21
    if (rewrite_it == global_to_file_slot.end()) {
810
0
        return false;
811
0
    }
812
813
    // File-local conjuncts are prepared against the file-reader Block, so both the root slot and
814
    // every struct selector must be expressed in file schema terms. For a renamed Iceberg field,
815
    // keeping the table selector would prepare `element_at(file_struct<rename>, 'renamed')` and
816
    // fail before any rows are read. Rewrite the whole chain while ColumnMapping still preserves
817
    // the table-to-file relationship. Example:
818
    //   table filter: element_at(element_at(s, 'renamed_parent'), 'renamed_leaf')
819
    //   old file:     s<parent<leaf>>
820
    //   file filter:  element_at(element_at(s, 'parent'), 'leaf')
821
21
    root_children[0] = create_file_slot_ref(*slot_ref, rewrite_it->second, rewrite_context);
822
21
    struct_element_chain.front()->set_children(std::move(root_children));
823
45
    for (size_t idx = 0; idx < struct_element_chain.size(); ++idx) {
824
24
        auto children = struct_element_chain[idx]->children();
825
24
        children[1] = create_file_struct_child_name_literal(resolved.file_child_names[idx],
826
24
                                                            rewrite_context);
827
24
        struct_element_chain[idx]->set_children(std::move(children));
828
        // The selector name and the expression return type must be moved to file schema together.
829
        // Example:
830
        //   table filter: element_at(element_at(s, 'new_a'), 'new_aa') = 50
831
        //   old file:     s.new_a STRUCT<aa, bb>
832
        //   file filter:  element_at(element_at(s, 'new_a'), 'aa') = 50
833
        //
834
        // If the inner element_at keeps the table return type STRUCT<new_aa, bb>, preparing the
835
        // outer element_at(..., 'aa') fails before scanning because `aa` is not a table field.
836
24
        struct_element_chain[idx]->data_type() = resolved.file_child_types[idx];
837
24
    }
838
21
    return true;
839
21
}
840
841
static VExprSPtr rewrite_table_expr_to_file_expr(
842
        const VExprSPtr& expr,
843
        const std::map<GlobalIndex, FileSlotRewriteInfo>& global_to_file_slot,
844
        const std::vector<ColumnMapping>& filter_mappings, RewriteContext* rewrite_context,
845
164
        bool* can_localize) {
846
164
    if (expr == nullptr) {
847
0
        return nullptr;
848
0
    }
849
164
    DORIS_CHECK(rewrite_context != nullptr);
850
164
    DORIS_CHECK(can_localize != nullptr);
851
164
    if (auto* runtime_filter = dynamic_cast<RuntimeFilterExpr*>(expr.get());
852
164
        runtime_filter != nullptr) {
853
3
        auto impl = runtime_filter->get_impl();
854
3
        if (impl == nullptr) {
855
0
            *can_localize = false;
856
0
            return expr;
857
0
        }
858
3
        auto localized_impl = rewrite_table_expr_to_file_expr(
859
3
                impl, global_to_file_slot, filter_mappings, rewrite_context, can_localize);
860
3
        if (!*can_localize) {
861
0
            return expr;
862
0
        }
863
3
        runtime_filter->set_impl(std::move(localized_impl));
864
3
        return expr;
865
3
    }
866
161
    if (rewrite_binary_slot_literal_predicate(expr, global_to_file_slot, rewrite_context)) {
867
30
        return expr;
868
30
    }
869
131
    if (rewrite_in_slot_literal_predicate(expr, global_to_file_slot, rewrite_context)) {
870
3
        return expr;
871
3
    }
872
128
    if (is_struct_element_expr(expr)) {
873
24
        const auto table_leaf_type = expr->data_type();
874
24
        if (!rewrite_struct_element_path_to_file_expr(expr, filter_mappings, global_to_file_slot,
875
24
                                                      rewrite_context)) {
876
            // The scanner still evaluates the original table-level conjunct after TableReader
877
            // finalizes the output block. Skipping an unlocalizable file conjunct is therefore
878
            // safer than preparing a partially rewritten expression against the wrong struct
879
            // layout. In particular, do not generate file-local conjuncts for computed complex
880
            // parents such as `element_at(element_at(map_values(m), 1), 'field')`; only direct
881
            // slot-rooted struct chains are supported here.
882
3
            *can_localize = false;
883
3
            return expr;
884
3
        }
885
21
        DORIS_CHECK(table_leaf_type != nullptr);
886
21
        DORIS_CHECK(expr->data_type() != nullptr);
887
21
        if (!expr->data_type()->equals(*table_leaf_type)) {
888
            // Path localization changes the leaf to the physical file type. For example, after an
889
            // Iceberg evolution from STRUCT<a: INT> to STRUCT<a: BIGINT>, the localized old-file
890
            // predicate is initially `element_at(file_col, 'a')::INT = 10::BIGINT`. Cast only the
891
            // leaf back to BIGINT so the comparison has matching operands without forcing a cast
892
            // of the entire evolved struct (whose children may also have been added or reordered).
893
1
            auto cast_expr = Cast::create_shared(table_leaf_type);
894
1
            cast_expr->add_child(expr);
895
1
            rewrite_context->add_created_expr(cast_expr);
896
1
            return cast_expr;
897
1
        }
898
20
        return expr;
899
21
    }
900
104
    if (expr->is_slot_ref()) {
901
19
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr.get());
902
19
        const auto rewrite_it = global_to_file_slot.find(slot_ref_global_index(*slot_ref));
903
19
        if (rewrite_it != global_to_file_slot.end()) {
904
19
            const auto& rewrite_info = rewrite_it->second;
905
19
            auto file_slot = create_file_slot_ref(*slot_ref, rewrite_info, rewrite_context);
906
19
            if (rewrite_info.file_type->equals(*rewrite_info.table_type)) {
907
7
                return file_slot;
908
7
            }
909
12
            if (needs_complex_file_slot_cast(rewrite_info.file_type, rewrite_info.table_type)) {
910
                // Generic file-local expressions cannot safely cast an evolved complex file slot
911
                // back to the table type. Example:
912
                //
913
                //   table filter: ARRAY_CONTAINS(MAP_KEYS(m), 'person5')
914
                //   old file:     m MAP<STRING, STRUCT<name, age>>
915
                //   table:        m MAP<STRING, STRUCT<age, full_name, gender>>
916
                //
917
                // Although MAP_KEYS only reads the key column, wrapping the file slot as
918
                // `CAST(file_m AS table_m)` forces the value struct cast first and fails because
919
                // the old and new value structs have different fields. Keep such filters at the
920
                // table level, where TableReader materializes the evolved complex value before
921
                // Scanner evaluates the original conjunct. Direct slot-rooted struct child paths
922
                // are handled by rewrite_struct_element_path_to_file_expr() above.
923
2
                *can_localize = false;
924
2
                return expr;
925
2
            }
926
10
            auto cast_expr = Cast::create_shared(rewrite_info.table_type);
927
10
            cast_expr->add_child(std::move(file_slot));
928
10
            rewrite_context->add_created_expr(cast_expr);
929
10
            return cast_expr;
930
12
        }
931
0
        return expr;
932
19
    }
933
    // The input is a split-local cloned tree. A previous split-local clone may already have
934
    // inserted Cast(slot). Keep that rewrite idempotent: rewrite the cast child from table slot to
935
    // the current split's file slot, and drop the cast when the current split no longer needs it.
936
85
    if (is_cast_expr(expr) && expr->get_num_children() == 1) {
937
4
        const auto& child = expr->children()[0];
938
4
        if (child->is_slot_ref()) {
939
2
            const auto* slot_ref = assert_cast<const VSlotRef*>(child.get());
940
2
            const auto rewrite_it = global_to_file_slot.find(slot_ref_global_index(*slot_ref));
941
2
            if (rewrite_it != global_to_file_slot.end() &&
942
2
                expr->data_type()->equals(*rewrite_it->second.table_type)) {
943
1
                auto rewritten_child =
944
1
                        create_file_slot_ref(*slot_ref, rewrite_it->second, rewrite_context);
945
1
                if (rewrite_it->second.file_type->equals(*rewrite_it->second.table_type)) {
946
0
                    return rewritten_child;
947
0
                }
948
1
                if (needs_complex_file_slot_cast(rewrite_it->second.file_type,
949
1
                                                 rewrite_it->second.table_type)) {
950
0
                    *can_localize = false;
951
0
                    return expr;
952
0
                }
953
1
                expr->set_children({std::move(rewritten_child)});
954
1
                return expr;
955
1
            }
956
2
        }
957
4
    }
958
959
84
    VExprSPtrs rewritten_children;
960
84
    rewritten_children.reserve(expr->children().size());
961
89
    for (const auto& child : expr->children()) {
962
89
        rewritten_children.push_back(rewrite_table_expr_to_file_expr(
963
89
                child, global_to_file_slot, filter_mappings, rewrite_context, can_localize));
964
89
    }
965
84
    expr->set_children(std::move(rewritten_children));
966
84
    return expr;
967
85
}
968
969
static constexpr const char* ROW_LINEAGE_ROW_ID = "_row_id";
970
static constexpr const char* ROW_LINEAGE_LAST_UPDATED_SEQ_NUMBER = "_last_updated_sequence_number";
971
static constexpr int32_t ROW_LINEAGE_ROW_ID_FIELD_ID = 2147483540;
972
static constexpr int32_t ROW_LINEAGE_LAST_UPDATED_SEQ_NUMBER_FIELD_ID = 2147483539;
973
974
173
static TableVirtualColumnType row_lineage_virtual_column_type(const std::string& column_name) {
975
173
    if (column_name == ROW_LINEAGE_ROW_ID) {
976
2
        return TableVirtualColumnType::ROW_ID;
977
2
    }
978
171
    if (column_name == ROW_LINEAGE_LAST_UPDATED_SEQ_NUMBER) {
979
2
        return TableVirtualColumnType::LAST_UPDATED_SEQUENCE_NUMBER;
980
2
    }
981
169
    return TableVirtualColumnType::INVALID;
982
171
}
983
984
static TableVirtualColumnType row_lineage_virtual_column_type_by_field_id(
985
77
        const ColumnDefinition& column) {
986
77
    if (!column.has_identifier_field_id()) {
987
5
        return TableVirtualColumnType::INVALID;
988
5
    }
989
72
    switch (column.get_identifier_field_id()) {
990
10
    case ROW_LINEAGE_ROW_ID_FIELD_ID:
991
10
        return TableVirtualColumnType::ROW_ID;
992
9
    case ROW_LINEAGE_LAST_UPDATED_SEQ_NUMBER_FIELD_ID:
993
9
        return TableVirtualColumnType::LAST_UPDATED_SEQUENCE_NUMBER;
994
53
    default:
995
53
        return TableVirtualColumnType::INVALID;
996
72
    }
997
72
}
998
999
static TableVirtualColumnType row_lineage_virtual_column_type(const ColumnDefinition& column,
1000
250
                                                              TableColumnMappingMode mode) {
1001
250
    switch (mode) {
1002
77
    case TableColumnMappingMode::BY_FIELD_ID:
1003
77
        return row_lineage_virtual_column_type_by_field_id(column);
1004
151
    case TableColumnMappingMode::BY_NAME:
1005
173
    case TableColumnMappingMode::BY_INDEX:
1006
173
        return row_lineage_virtual_column_type(column.name);
1007
250
    }
1008
0
    return TableVirtualColumnType::INVALID;
1009
250
}
1010
1011
// Returns true when the current file type is not the exact nested type the scan should expose.
1012
// This is about building the projected file-side type/projection, not about whether TableReader
1013
// later needs to rematerialize the complex value back to table layout.
1014
109
static bool needs_projected_file_type_rebuild(const ColumnMapping& mapping) {
1015
109
    if (!is_complex_type(mapping.file_type->get_primitive_type())) {
1016
28
        return false;
1017
28
    }
1018
81
    if (mapping.child_mappings.empty()) {
1019
0
        return false;
1020
0
    }
1021
81
    DORIS_CHECK(mapping.file_type != nullptr);
1022
81
    DORIS_CHECK(mapping.table_type != nullptr);
1023
81
    if (remove_nullable(mapping.file_type)->get_primitive_type() !=
1024
81
        remove_nullable(mapping.table_type)->get_primitive_type()) {
1025
0
        return true;
1026
0
    }
1027
81
    if (!mapping.table_type->equals(*mapping.file_type)) {
1028
63
        return true;
1029
63
    }
1030
32
    for (const auto& child_mapping : mapping.child_mappings) {
1031
        // Rename-only child mappings do not change the file-side projected shape. If field-id
1032
        // matching maps table child `renamed_b` to file child `b`, the file reader can still expose
1033
        // the original file type as long as child count/order/types are unchanged.
1034
32
        if (!child_mapping.file_local_id.has_value() ||
1035
32
            needs_projected_file_type_rebuild(child_mapping)) {
1036
1
            return true;
1037
1
        }
1038
32
    }
1039
17
    return false;
1040
18
}
1041
1042
static std::optional<size_t> file_child_ordinal_in_scan_type(const ColumnMapping& mapping,
1043
78
                                                             const ColumnMapping& child_mapping) {
1044
78
    if (!child_mapping.file_local_id.has_value()) {
1045
1
        return std::nullopt;
1046
1
    }
1047
77
    const auto& file_children = !mapping.projected_file_children.empty()
1048
77
                                        ? mapping.projected_file_children
1049
77
                                        : mapping.original_file_children;
1050
93
    const auto child_it = std::ranges::find_if(file_children, [&](const ColumnDefinition& child) {
1051
93
        return child.file_local_id() == *child_mapping.file_local_id;
1052
93
    });
1053
77
    if (child_it == file_children.end()) {
1054
0
        return std::nullopt;
1055
0
    }
1056
77
    return static_cast<size_t>(std::distance(file_children.begin(), child_it));
1057
77
}
1058
1059
401
static bool needs_complex_rematerialize(const ColumnMapping& mapping) {
1060
401
    if (mapping.child_mappings.empty()) {
1061
309
        return false;
1062
309
    }
1063
92
    if (mapping.table_type == nullptr || mapping.file_type == nullptr ||
1064
92
        !mapping.table_type->equals(*mapping.file_type)) {
1065
26
        return true;
1066
26
    }
1067
136
    for (size_t table_child_idx = 0; table_child_idx < mapping.child_mappings.size();
1068
78
         ++table_child_idx) {
1069
78
        const auto& child_mapping = mapping.child_mappings[table_child_idx];
1070
78
        const auto file_child_idx = file_child_ordinal_in_scan_type(mapping, child_mapping);
1071
78
        if (!file_child_idx.has_value() || *file_child_idx != table_child_idx ||
1072
78
            needs_complex_rematerialize(child_mapping) ||
1073
78
            (child_mapping.table_type != nullptr && child_mapping.file_type != nullptr &&
1074
70
             !child_mapping.table_type->equals(*child_mapping.file_type))) {
1075
8
            return true;
1076
8
        }
1077
78
    }
1078
58
    return false;
1079
66
}
1080
1081
424
static bool mapping_can_use_file_column_directly(const ColumnMapping& mapping) {
1082
424
    if (mapping.table_type == nullptr || mapping.file_type == nullptr) {
1083
0
        return false;
1084
0
    }
1085
424
    const auto table_type = remove_nullable(mapping.table_type);
1086
424
    const auto file_type = remove_nullable(mapping.file_type);
1087
424
    const bool same_timestamptz_with_different_scale =
1088
424
            table_type->get_primitive_type() == TYPE_TIMESTAMPTZ &&
1089
424
            file_type->get_primitive_type() == TYPE_TIMESTAMPTZ;
1090
424
    if (!mapping.table_type->equals(*mapping.file_type) && !same_timestamptz_with_different_scale) {
1091
142
        return false;
1092
142
    }
1093
282
    return !needs_complex_rematerialize(mapping);
1094
424
}
1095
1096
695
static bool type_contains_varbinary(const DataTypePtr& type) {
1097
695
    DORIS_CHECK(type != nullptr);
1098
695
    const auto nested_type = remove_nullable(type);
1099
695
    switch (nested_type->get_primitive_type()) {
1100
3
    case TYPE_VARBINARY:
1101
3
        return true;
1102
20
    case TYPE_ARRAY:
1103
20
        return type_contains_varbinary(
1104
20
                assert_cast<const DataTypeArray&>(*nested_type).get_nested_type());
1105
25
    case TYPE_MAP: {
1106
25
        const auto& map_type = assert_cast<const DataTypeMap&>(*nested_type);
1107
25
        return type_contains_varbinary(map_type.get_key_type()) ||
1108
25
               type_contains_varbinary(map_type.get_value_type());
1109
0
    }
1110
144
    case TYPE_STRUCT:
1111
144
        return std::ranges::any_of(
1112
144
                assert_cast<const DataTypeStruct&>(*nested_type).get_elements(),
1113
247
                [](const DataTypePtr& child_type) { return type_contains_varbinary(child_type); });
1114
503
    default:
1115
503
        return false;
1116
695
    }
1117
695
}
1118
1119
378
static FilterConversionType direct_filter_conversion(const ColumnMapping& mapping) {
1120
378
    DORIS_CHECK(mapping.table_type != nullptr);
1121
378
    DORIS_CHECK(mapping.file_type != nullptr);
1122
    // FileScanOperator deliberately keeps VARBINARY predicates above external readers. Their
1123
    // physical binary representations are not uniformly supported by reader-side expression and
1124
    // metadata filtering, so localizing a late runtime filter here can incorrectly reject rows.
1125
    // Apply the same rule to a complex root because generic array/map/struct expressions rewrite
1126
    // the root slot and can otherwise expose a nested VARBINARY child to the reader.
1127
378
    if (type_contains_varbinary(mapping.table_type)) {
1128
3
        return FilterConversionType::FINALIZE_ONLY;
1129
3
    }
1130
375
    const auto table_type = remove_nullable(mapping.table_type);
1131
375
    const auto file_type = remove_nullable(mapping.file_type);
1132
    // TIMESTAMPTZ scale mismatch is intentionally materialized as pass-through: a SQL cast rounds
1133
    // fractional seconds. A file-local cast would therefore filter different instants from the
1134
    // scanner-level predicate evaluated on the pass-through value.
1135
375
    if (table_type->get_primitive_type() == TYPE_TIMESTAMPTZ &&
1136
375
        file_type->get_primitive_type() == TYPE_TIMESTAMPTZ &&
1137
375
        !mapping.table_type->equals(*mapping.file_type)) {
1138
1
        return FilterConversionType::FINALIZE_ONLY;
1139
1
    }
1140
374
    return mapping.is_trivial ? FilterConversionType::COPY_DIRECTLY
1141
374
                              : FilterConversionType::CAST_FILTER;
1142
375
}
1143
1144
64
static FilterConversionType projected_filter_conversion(const ColumnMapping& mapping) {
1145
64
    const auto conversion = direct_filter_conversion(mapping);
1146
64
    return !mapping.is_trivial && conversion != FilterConversionType::FINALIZE_ONLY
1147
64
                   ? FilterConversionType::READER_EXPRESSION
1148
64
                   : conversion;
1149
64
}
1150
1151
static const ColumnDefinition* find_file_child_for_mapping(const ColumnDefinition& table_child,
1152
                                                           const ColumnDefinition& file_parent,
1153
                                                           TableColumnMappingMode mode,
1154
                                                           size_t table_child_idx,
1155
122
                                                           bool allow_ordinal_fallback) {
1156
122
    const auto file_parent_type = remove_nullable(file_parent.type)->get_primitive_type();
1157
122
    switch (file_parent_type) {
1158
10
    case TYPE_ARRAY:
1159
10
        DORIS_CHECK(file_parent.children.size() == 1);
1160
10
        return &file_parent.children[0];
1161
19
    case TYPE_MAP:
1162
19
        DORIS_CHECK(file_parent.children.size() == 2);
1163
19
        if (table_child.name == "key") {
1164
6
            return &file_parent.children[0];
1165
6
        }
1166
13
        if (table_child.name == "value") {
1167
13
            return &file_parent.children[1];
1168
13
        }
1169
0
        if (table_child.local_id == 0 || table_child.local_id == 1) {
1170
0
            return &file_parent.children[table_child.local_id];
1171
0
        }
1172
0
        return nullptr;
1173
93
    default:
1174
        // Hive BY_INDEX is a top-level column matching rule. Once a complex root is selected by
1175
        // file position, nested struct children follow Hive reader's historical name matching
1176
        // semantics; their integer identifiers can be field ids, not file positions.
1177
93
        const auto nested_mode =
1178
93
                mode == TableColumnMappingMode::BY_INDEX ? TableColumnMappingMode::BY_NAME : mode;
1179
93
        if (const auto* file_child =
1180
93
                    matcher_for_mode(nested_mode).find(table_child, file_parent.children);
1181
93
            file_child != nullptr) {
1182
74
            return file_child;
1183
74
        }
1184
19
        if (allow_ordinal_fallback && mode == TableColumnMappingMode::BY_FIELD_ID &&
1185
19
            !table_child.has_identifier_field_id()) {
1186
            // Synthetic children are derived from the table DataType when nested ColumnDefinition
1187
            // metadata has been pruned away. They do not carry Iceberg field ids, so try a name
1188
            // match before falling back to ordinal order. Example:
1189
            //   table value type: Struct(age, full_name, gender)
1190
            //   old file value:   Struct(name, age)
1191
            // Name matching keeps `age -> age`; the later unused-child fallback can then map the
1192
            // renamed `full_name -> name` instead of consuming `age` twice.
1193
3
            if (const auto* file_child = NameMatcher().find(table_child, file_parent.children);
1194
3
                file_child != nullptr) {
1195
1
                return file_child;
1196
1
            }
1197
3
        }
1198
        // Some callers only carry the full complex DataType for a projected table column, without
1199
        // expanded nested ColumnDefinitions. In that case we can still preserve full materialization
1200
        // by walking table/file struct fields by ordinal. This is a fallback only: explicit
1201
        // ColumnDefinition children keep using the requested table-format matching rule, which is
1202
        // required for precise schema evolution.
1203
18
        if (allow_ordinal_fallback && table_child_idx < file_parent.children.size()) {
1204
3
            return &file_parent.children[table_child_idx];
1205
3
        }
1206
15
        return nullptr;
1207
122
    }
1208
122
}
1209
1210
static ColumnDefinition synthetic_child_definition(const std::string& name, DataTypePtr type,
1211
13
                                                   int32_t local_id) {
1212
13
    ColumnDefinition child;
1213
13
    child.identifier = Field::create_field<TYPE_STRING>(name);
1214
13
    child.local_id = local_id;
1215
13
    child.name = name;
1216
13
    child.type = std::move(type);
1217
13
    return child;
1218
13
}
1219
1220
static std::vector<ColumnDefinition> synthesize_complex_children_from_type(
1221
4
        const DataTypePtr& type) {
1222
4
    std::vector<ColumnDefinition> children;
1223
4
    if (type == nullptr) {
1224
0
        return children;
1225
0
    }
1226
4
    const auto nested_type = remove_nullable(type);
1227
4
    switch (nested_type->get_primitive_type()) {
1228
0
    case TYPE_ARRAY: {
1229
0
        const auto* array_type = assert_cast<const DataTypeArray*>(nested_type.get());
1230
0
        children.push_back(synthetic_child_definition("element", array_type->get_nested_type(), 0));
1231
0
        break;
1232
0
    }
1233
1
    case TYPE_MAP: {
1234
1
        const auto* map_type = assert_cast<const DataTypeMap*>(nested_type.get());
1235
1
        children.push_back(synthetic_child_definition("key", map_type->get_key_type(), 0));
1236
1
        children.push_back(synthetic_child_definition("value", map_type->get_value_type(), 1));
1237
1
        break;
1238
0
    }
1239
3
    case TYPE_STRUCT: {
1240
3
        const auto* struct_type = assert_cast<const DataTypeStruct*>(nested_type.get());
1241
3
        children.reserve(struct_type->get_elements().size());
1242
12
        for (size_t idx = 0; idx < struct_type->get_elements().size(); ++idx) {
1243
9
            children.push_back(synthetic_child_definition(struct_type->get_element_name(idx),
1244
9
                                                          struct_type->get_element(idx),
1245
9
                                                          cast_set<int32_t>(idx)));
1246
9
        }
1247
3
        break;
1248
0
    }
1249
0
    default:
1250
0
        break;
1251
4
    }
1252
4
    return children;
1253
4
}
1254
1255
static bool has_table_child_named(const std::vector<ColumnDefinition>& children,
1256
15
                                  std::string_view name) {
1257
17
    return std::ranges::any_of(children, [&](const ColumnDefinition& child) {
1258
17
        return std::string_view(child.name) == name;
1259
17
    });
1260
15
}
1261
1262
static void complete_required_complex_children_from_type(const DataTypePtr& type,
1263
59
                                                         std::vector<ColumnDefinition>* children) {
1264
59
    DORIS_CHECK(children != nullptr);
1265
59
    if (type == nullptr) {
1266
0
        return;
1267
0
    }
1268
59
    const auto nested_type = remove_nullable(type);
1269
59
    switch (nested_type->get_primitive_type()) {
1270
11
    case TYPE_MAP: {
1271
11
        const auto* map_type = assert_cast<const DataTypeMap*>(nested_type.get());
1272
        // MAP key/value are structural children, not independently materializable table fields.
1273
        // A key-only projection can still be attached to a whole-map output root, for example:
1274
        //   SELECT * FROM t WHERE ARRAY_CONTAINS(MAP_KEYS(new_map_column), 'person5')
1275
        //
1276
        // In that shape the scanner keeps the value stream readable, but the table projection can
1277
        // carry only the key child. Add the missing value child so recursive mapping can evolve the
1278
        // value type instead of letting TableReader cast old/new value structs directly.
1279
11
        if (has_table_child_named(*children, "key") && !has_table_child_named(*children, "value")) {
1280
2
            children->push_back(synthetic_child_definition("value", map_type->get_value_type(), 1));
1281
2
        }
1282
11
        break;
1283
0
    }
1284
9
    case TYPE_ARRAY:
1285
        // ARRAY has only one required structural child (`element`), so a non-empty projection is
1286
        // already rooted at the element path.
1287
9
        break;
1288
39
    case TYPE_STRUCT:
1289
        // STRUCT children are real fields and must remain prunable. Completing missing struct
1290
        // fields here would turn `SELECT s.a` into a full-struct read and undo nested projection.
1291
39
        break;
1292
0
    default:
1293
0
        break;
1294
59
    }
1295
59
}
1296
1297
79
static Status validate_file_schema_children(const ColumnDefinition& file_field) {
1298
79
    if (file_field.type == nullptr) {
1299
0
        return Status::InternalError("File column '{}' has null type", file_field.name);
1300
0
    }
1301
79
    const auto nested_type = remove_nullable(file_field.type);
1302
79
    size_t expected_children = 0;
1303
79
    bool complex_with_fixed_children = true;
1304
79
    switch (nested_type->get_primitive_type()) {
1305
10
    case TYPE_ARRAY:
1306
10
        expected_children = 1;
1307
10
        break;
1308
13
    case TYPE_MAP:
1309
13
        expected_children = 2;
1310
13
        break;
1311
56
    case TYPE_STRUCT:
1312
56
        expected_children =
1313
56
                assert_cast<const DataTypeStruct*>(nested_type.get())->get_elements().size();
1314
56
        break;
1315
0
    default:
1316
0
        complex_with_fixed_children = false;
1317
0
        break;
1318
79
    }
1319
79
    if (!complex_with_fixed_children || file_field.children.size() == expected_children) {
1320
78
        return Status::OK();
1321
78
    }
1322
1
    return Status::InternalError(
1323
1
            "Malformed complex file schema for column '{}': type={}, expected_children={}, "
1324
1
            "actual_children={}",
1325
1
            file_field.name, file_field.type->get_name(), expected_children,
1326
1
            file_field.children.size());
1327
79
}
1328
1329
204
static bool has_projected_file_children(const ColumnMapping& mapping) {
1330
204
    if (mapping.original_file_children.empty() || mapping.projected_file_children.empty()) {
1331
155
        return false;
1332
155
    }
1333
49
    if (mapping.original_file_children.size() != mapping.projected_file_children.size()) {
1334
21
        return true;
1335
21
    }
1336
72
    for (size_t idx = 0; idx < mapping.original_file_children.size(); ++idx) {
1337
44
        if (mapping.original_file_children[idx].file_local_id() !=
1338
44
            mapping.projected_file_children[idx].file_local_id()) {
1339
0
            return true;
1340
0
        }
1341
44
    }
1342
28
    return false;
1343
28
}
1344
1345
204
static bool needs_nested_file_projection(const ColumnMapping& mapping) {
1346
204
    if (has_projected_file_children(mapping)) {
1347
        // Return True if the projected child column is missing / re-ordered
1348
21
        return true;
1349
21
    }
1350
183
    return std::ranges::any_of(mapping.child_mappings, [](const ColumnMapping& child_mapping) {
1351
44
        return needs_nested_file_projection(child_mapping);
1352
44
    });
1353
204
}
1354
1355
static Status build_complex_projection(const ColumnMapping& mapping, LocalColumnIndex* projection);
1356
1357
// Build the projected file children/type according to the pruned complex projection. For example,
1358
// if we have a struct column `s` with children `id` and `name`, and the projection only keeps
1359
// `s.name`, then the file reader should expose `STRUCT<name ...>`.
1360
static Status rebuild_projected_file_children_and_type(
1361
        const DataTypePtr& file_type, const std::vector<ColumnDefinition>& original_file_children,
1362
        const std::vector<ColumnMapping>& child_mappings,
1363
64
        std::vector<ColumnDefinition>* projected_file_children, DataTypePtr* projected_type) {
1364
64
    DORIS_CHECK(file_type != nullptr);
1365
64
    DORIS_CHECK(projected_file_children != nullptr);
1366
64
    DORIS_CHECK(projected_type != nullptr);
1367
64
    ColumnDefinition field;
1368
64
    field.type = file_type;
1369
64
    field.children = original_file_children;
1370
64
    LocalColumnIndex projection = LocalColumnIndex::partial_local(-1);
1371
64
    projection.children.reserve(child_mappings.size());
1372
82
    for (const auto* child_mapping : present_child_mappings_in_file_order(child_mappings)) {
1373
82
        DORIS_CHECK(child_mapping->file_local_id.has_value());
1374
82
        LocalColumnIndex child_projection;
1375
82
        RETURN_IF_ERROR(build_complex_projection(*child_mapping, &child_projection));
1376
82
        projection.children.push_back(std::move(child_projection));
1377
82
    }
1378
1379
64
    ColumnDefinition projected_field;
1380
64
    RETURN_IF_ERROR(project_column_definition(field, projection, &projected_field));
1381
64
    *projected_file_children = std::move(projected_field.children);
1382
64
    *projected_type = std::move(projected_field.type);
1383
64
    return Status::OK();
1384
64
}
1385
1386
// Build the complex column projection according to the ColumnMapping which is re-ordered by the
1387
// file-schema's order.
1388
//
1389
// For MAP, a partial projection represents value-subtree pruning only. The key child is not a
1390
// projected output shape; file readers still read full keys to construct ColumnMap offsets and keep
1391
// key semantics unchanged. If a caller tries to project only/prune the key child, the common schema
1392
// projection helper rejects it.
1393
162
static Status build_complex_projection(const ColumnMapping& mapping, LocalColumnIndex* projection) {
1394
162
    if (projection == nullptr) {
1395
0
        return Status::InvalidArgument("projection is null");
1396
0
    }
1397
162
    DORIS_CHECK(mapping.file_local_id.has_value());
1398
162
    *projection = LocalColumnIndex::local(*mapping.file_local_id);
1399
162
    projection->project_all_children = mapping.child_mappings.empty();
1400
162
    projection->children.clear();
1401
162
    const auto present_children = present_child_mappings_in_file_order(mapping.child_mappings);
1402
162
    if (!projection->project_all_children && present_children.empty()) {
1403
        // All requested table children under this complex node are missing/default-only. The file
1404
        // reader cannot expose an empty complex projection, but TableReader can still rematerialize
1405
        // the table shape from a full file subtree and fill the missing children with defaults.
1406
4
        projection->project_all_children = true;
1407
4
        return Status::OK();
1408
4
    }
1409
158
    for (const auto* child_mapping : present_children) {
1410
59
        LocalColumnIndex child_projection;
1411
59
        RETURN_IF_ERROR(build_complex_projection(*child_mapping, &child_projection));
1412
59
        projection->children.push_back(std::move(child_projection));
1413
59
    }
1414
158
    if (!projection->project_all_children && projection->children.empty()) {
1415
0
        return Status::NotSupported("Projection for complex column {} contains no file children",
1416
0
                                    mapping.file_column_name);
1417
0
    }
1418
158
    return Status::OK();
1419
158
}
1420
1421
using FilterProjectionMap = std::map<LocalColumnId, LocalColumnIndex>;
1422
1423
// Update the mapping's file type according to the projection, and determine whether the projection
1424
// is trivial (i.e. the projected file type is the same as the table type, so no need to
1425
// rematerialize the complex value back to table layout after reading from file).
1426
static Status apply_projection_to_mapping_file_type(const LocalColumnIndex& projection,
1427
165
                                                    ColumnMapping* mapping) {
1428
165
    DORIS_CHECK(mapping != nullptr);
1429
165
    if (mapping->original_file_type == nullptr) {
1430
0
        mapping->original_file_type = mapping->file_type;
1431
0
    }
1432
165
    if (mapping->original_file_type == nullptr ||
1433
165
        !is_complex_type(remove_nullable(mapping->original_file_type)->get_primitive_type())) {
1434
119
        return Status::OK();
1435
119
    }
1436
46
    ColumnDefinition field;
1437
46
    field.type = mapping->original_file_type;
1438
46
    field.children = mapping->original_file_children;
1439
46
    ColumnDefinition projected_field;
1440
46
    RETURN_IF_ERROR(project_column_definition(field, projection, &projected_field));
1441
46
    mapping->file_type = std::move(projected_field.type);
1442
46
    mapping->projected_file_children = std::move(projected_field.children);
1443
46
    mapping->is_trivial = mapping_can_use_file_column_directly(*mapping);
1444
46
    return Status::OK();
1445
46
}
1446
1447
static Status merge_filter_projection(const FilterProjectionMap* filter_projections,
1448
75
                                      LocalColumnIndex* projection) {
1449
75
    DORIS_CHECK(projection != nullptr);
1450
75
    if (filter_projections == nullptr) {
1451
0
        return Status::OK();
1452
0
    }
1453
75
    const auto filter_projection_it = filter_projections->find(projection->column_id());
1454
75
    if (filter_projection_it == filter_projections->end()) {
1455
59
        return Status::OK();
1456
59
    }
1457
    // Merge predicate-only nested paths into the root projection that is about to be scanned.
1458
    // Example: `SELECT s.a WHERE s.b > 1` first builds the output projection `s -> a` from
1459
    // ColumnMapping, while build_nested_struct_filter_projection_map() records `s -> b`. This merge
1460
    // produces one file scan projection `s -> a,b`.
1461
16
    RETURN_IF_ERROR(merge_local_column_index(projection, filter_projection_it->second));
1462
16
    return Status::OK();
1463
16
}
1464
1465
2
static bool table_root_is_map(const ColumnMapping& mapping) {
1466
2
    if (mapping.table_type == nullptr) {
1467
0
        return false;
1468
0
    }
1469
2
    return remove_nullable(mapping.table_type)->get_primitive_type() == TYPE_MAP;
1470
2
}
1471
1472
static Status add_scan_column(FileScanRequest* file_request, ColumnMapping* mapping,
1473
                              bool is_predicate_column, bool force_full_complex_scan_projection,
1474
167
                              const FilterProjectionMap* filter_projections = nullptr) {
1475
167
    const auto file_column_id = LocalColumnId(mapping->file_local_id.value());
1476
167
    LocalColumnIndex projection = LocalColumnIndex::top_level(file_column_id);
1477
    // Columnar readers can turn a complex mapping into a nested file projection, but
1478
    // row-oriented readers must scan the full top-level complex field because all children are
1479
    // encoded in the same text cell.
1480
167
    if (!force_full_complex_scan_projection && needs_nested_file_projection(*mapping)) {
1481
21
        RETURN_IF_ERROR(build_complex_projection(*mapping, &projection));
1482
21
    }
1483
167
    if (is_predicate_column && !force_full_complex_scan_projection) {
1484
75
        DCHECK(filter_projections != nullptr);
1485
        // If a projected complex root is also used by a predicate, rebuild the predicate scan
1486
        // projection from the output mapping before merging predicate-only children. For
1487
        // `SELECT s.a WHERE s.b > 1`, build_complex_projection() produces `s -> a` and
1488
        // merge_filter_projection() adds `s -> b`, so the predicate column reads both children.
1489
75
        RETURN_IF_ERROR(merge_filter_projection(filter_projections, &projection));
1490
75
    }
1491
167
    FileScanRequestBuilder builder(file_request);
1492
167
    if (is_predicate_column) {
1493
75
        return builder.add_predicate_column(std::move(projection));
1494
75
    }
1495
92
    return builder.add_non_predicate_column(std::move(projection));
1496
167
}
1497
1498
static const LocalColumnIndex* find_scan_projection(
1499
256
        const std::vector<LocalColumnIndex>& scan_columns, LocalColumnId file_column_id) {
1500
256
    const auto projection_it =
1501
256
            std::ranges::find_if(scan_columns, [&](const LocalColumnIndex& projection) {
1502
205
                return projection.column_id() == file_column_id;
1503
205
            });
1504
256
    return projection_it == scan_columns.end() ? nullptr : &*projection_it;
1505
256
}
1506
1507
// Apply the final scan projection of one root file column back to its ColumnMapping. This updates
1508
// mapping.file_type/projected_file_children from the original file schema to the exact shape that
1509
// FileReader will return.
1510
//
1511
// Example: for `SELECT s.a WHERE s.b > 1`, add_scan_column() keeps only one predicate scan
1512
// projection `s -> a,b`. Applying that projection changes the mapping's file type from the full
1513
// file struct `s<a,b,c>` to the projected file struct `s<a,b>`, so later filter rewrite and
1514
// TableReader final materialization use the same column shape as the file-local block.
1515
static Status apply_scan_projection_to_mapping_file_type(const FileScanRequest& file_request,
1516
165
                                                         ColumnMapping* mapping) {
1517
165
    DORIS_CHECK(mapping != nullptr);
1518
165
    DORIS_CHECK(mapping->file_local_id.has_value());
1519
165
    const auto file_column_id = LocalColumnId(*mapping->file_local_id);
1520
    // Predicate columns are the actual scan projection when a column is used by row-level filters:
1521
    // add_scan_column() removes the duplicate non-predicate projection in that case.
1522
165
    const auto* projection = find_scan_projection(file_request.predicate_columns, file_column_id);
1523
165
    if (projection == nullptr) {
1524
91
        projection = find_scan_projection(file_request.non_predicate_columns, file_column_id);
1525
91
    }
1526
165
    DORIS_CHECK(projection != nullptr);
1527
165
    return apply_projection_to_mapping_file_type(*projection, mapping);
1528
165
}
1529
1530
// Build extra scan projections required only by row-level filters on nested struct children.
1531
//
1532
// Example: for `SELECT s.a FROM t WHERE s.b.c > 1`, the output projection may only contain `s.a`,
1533
// but the file reader must also read `s.b.c` to evaluate the predicate. This function collects the
1534
// table-side filter path, resolves it through ColumnMapping first, and records the corresponding
1535
// file-side projection in filter_projections. This keeps renamed fields consistent between the scan
1536
// projection and row-level conjunct rewrite. Example:
1537
//   table filter path: s -> renamed_b -> c
1538
//   old file path:     s -> b -> c
1539
//   recorded path:     s -> b -> c
1540
// When add_scan_column() adds the same root as a predicate column, it rebuilds that root from the
1541
// output mapping, merges this filter-only projection into it, and removes the duplicate
1542
// non-predicate root entry.
1543
static Status build_nested_struct_filter_projection_map(
1544
        const std::vector<TableFilter>& table_filters, const std::vector<ColumnMapping>& mappings,
1545
147
        FilterProjectionMap* filter_projections) {
1546
147
    DORIS_CHECK(filter_projections != nullptr);
1547
147
    filter_projections->clear();
1548
147
    for (const auto& table_filter : table_filters) {
1549
88
        if (table_filter.conjunct == nullptr) {
1550
2
            continue;
1551
2
        }
1552
        // Collect all nested struct paths in the table filter. For example, for
1553
        // `s.id > 5 AND element_at(s, 'renamed_name') = 'abc'`, collect the table paths
1554
        // `s -> id` and `s -> renamed_name`, then resolve each one to its file-side projection.
1555
86
        std::vector<NestedStructPath> paths;
1556
86
        collect_nested_struct_paths(table_filter.conjunct->root(), &paths);
1557
86
        for (const auto& path : paths) {
1558
24
            auto mapping_it = std::ranges::find_if(mappings, [&](const ColumnMapping& mapping) {
1559
24
                return mapping.global_index == path.root_global_index;
1560
24
            });
1561
23
            if (mapping_it == mappings.end() || !mapping_it->file_local_id.has_value() ||
1562
23
                path.selectors.empty()) {
1563
0
                continue;
1564
0
            }
1565
1566
23
            ResolvedNestedStructPath resolved;
1567
23
            LocalColumnIndex root_projection;
1568
23
            if (!resolve_nested_struct_path_for_file(path, mappings, &resolved)) {
1569
2
                if (!table_root_is_map(*mapping_it)) {
1570
1
                    continue;
1571
1
                }
1572
                // Direct map value filters such as `m.value.a > 1` need the value leaf for row
1573
                // evaluation even when the query only projects another value child. This is only a
1574
                // scan projection fallback; complex map/array expressions are still not rewritten
1575
                // into file-local conjuncts.
1576
1
                LocalColumnIndex child_projection;
1577
1
                RETURN_IF_ERROR(build_file_child_projection_from_schema(
1578
1
                        mapping_it->original_file_children, path.selectors, &child_projection));
1579
1
                if (child_projection.local_id() < 0) {
1580
0
                    continue;
1581
0
                }
1582
1
                root_projection = LocalColumnIndex::partial_local(*mapping_it->file_local_id);
1583
1
                root_projection.children.push_back(std::move(child_projection));
1584
21
            } else {
1585
21
                root_projection = std::move(resolved.file_projection);
1586
21
            }
1587
22
            auto filter_projection_it = filter_projections->find(root_projection.column_id());
1588
22
            if (filter_projection_it == filter_projections->end()) {
1589
18
                filter_projections->emplace(root_projection.column_id(),
1590
18
                                            std::move(root_projection));
1591
18
                continue;
1592
18
            }
1593
4
            RETURN_IF_ERROR(
1594
4
                    merge_local_column_index(&filter_projection_it->second, root_projection));
1595
4
        }
1596
86
    }
1597
147
    return Status::OK();
1598
147
}
1599
1600
157
static void rebuild_projection(ColumnMapping* mapping, LocalIndex block_position) {
1601
157
    DORIS_CHECK(mapping->file_local_id.has_value());
1602
157
    if (mapping->is_trivial || needs_complex_rematerialize(*mapping)) {
1603
138
        mapping->projection = VExprContext::create_shared(VSlotRef::create_shared(
1604
138
                cast_set<int>(block_position.value()), cast_set<int>(block_position.value()), -1,
1605
138
                mapping->file_type, mapping->file_column_name));
1606
138
        return;
1607
138
    }
1608
1609
19
    auto expr = Cast::create_shared(mapping->table_type);
1610
19
    expr->add_child(VSlotRef::create_shared(cast_set<int>(block_position.value()),
1611
19
                                            cast_set<int>(block_position.value()), -1,
1612
19
                                            mapping->file_type, mapping->file_column_name));
1613
19
    mapping->projection = VExprContext::create_shared(expr);
1614
19
}
1615
1616
// Build file slot rewrite info from the localized filter targets. Only local targets can enter
1617
// file-reader expressions; constant and unset targets stay above the file reader.
1618
static std::map<GlobalIndex, FileSlotRewriteInfo> build_file_slot_rewrite_map(
1619
        const std::vector<ColumnMapping>& mappings,
1620
147
        const std::map<GlobalIndex, FilterEntry>& filter_entries) {
1621
147
    std::map<GlobalIndex, FileSlotRewriteInfo> global_to_file_slot;
1622
190
    for (const auto& mapping : mappings) {
1623
190
        const auto entry_it = filter_entries.find(mapping.global_index);
1624
190
        if (entry_it == filter_entries.end() || !entry_it->second.is_local()) {
1625
38
            continue;
1626
38
        }
1627
152
        DORIS_CHECK(mapping.file_local_id.has_value());
1628
152
        global_to_file_slot.emplace(
1629
152
                mapping.global_index,
1630
152
                FileSlotRewriteInfo {.block_position = entry_it->second.local_index().value(),
1631
152
                                     .file_type = mapping.file_type,
1632
152
                                     .table_type = mapping.table_type,
1633
152
                                     .file_column_name = mapping.file_column_name});
1634
152
    }
1635
147
    return global_to_file_slot;
1636
147
}
1637
1638
Status TableColumnMapper::_create_by_index_mapping(const ColumnDefinition& table_column,
1639
                                                   const std::vector<ColumnDefinition>& file_schema,
1640
19
                                                   ColumnMapping* mapping) {
1641
19
    DORIS_CHECK(mapping != nullptr);
1642
19
    DORIS_CHECK(!table_column.is_partition_key);
1643
1644
    // Key contract: in BY_INDEX mode, `ColumnDefinition::identifier` TYPE_INT is interpreted as the
1645
    // 0-based position of this column inside `file_schema`. FE writes the physical file position
1646
    // of each non-partition projected column into that identifier. This interpretation allows:
1647
    //   - sparse projection: read only a subset of file columns (for example only `_col2`
1648
    //     and `_col4`);
1649
    //   - column reordering: table column order differs from file column order;
1650
    //   - no many-to-one mapping: FE must guarantee that each file position is referenced by at
1651
    //     most one table column.
1652
19
    const auto file_index = table_column.get_identifier_position();
1653
1654
    // Case A: file_index is in range, so build a direct positional mapping.
1655
    // The file column name (for example `_col0`) is intentionally ignored here.
1656
19
    if (file_index >= 0 && static_cast<size_t>(file_index) < file_schema.size()) {
1657
16
        return _create_direct_mapping(table_column, file_schema[static_cast<size_t>(file_index)],
1658
16
                                      mapping);
1659
16
    }
1660
1661
    // Case B: file_index is out of range, which means the file does not contain this column.
1662
    // Route it through the missing-column path used by schema evolution.
1663
3
    if (table_column.default_expr != nullptr) {
1664
1
        _set_constant_mapping(mapping, table_column.default_expr);
1665
1
        return Status::OK();
1666
1
    }
1667
    // Keep the mapping empty (`file_local_id` remains `nullopt`) and let the upper finalize
1668
    // stage fill NULL/default values.
1669
2
    return Status::OK();
1670
3
}
1671
1672
19
void TableColumnMapper::_set_constant_mapping(ColumnMapping* mapping, VExprContextSPtr expr) {
1673
19
    DORIS_CHECK(mapping != nullptr);
1674
19
    DORIS_CHECK(expr != nullptr);
1675
19
    mapping->default_expr = std::move(expr);
1676
19
    mapping->constant_index = _constant_map.add(ConstantEntry {
1677
19
            .global_index = mapping->global_index,
1678
19
            .expr = mapping->default_expr,
1679
19
            .type = mapping->table_type,
1680
19
    });
1681
19
    mapping->filter_conversion = FilterConversionType::CONSTANT;
1682
19
}
1683
1684
Status TableColumnMapper::_create_mapping_for_column(const ColumnDefinition& table_column,
1685
                                                     GlobalIndex global_index,
1686
250
                                                     ColumnMapping* mapping) {
1687
250
    DORIS_CHECK(mapping != nullptr);
1688
250
    *mapping = ColumnMapping {};
1689
250
    mapping->global_index = global_index;
1690
250
    mapping->table_column_name = table_column.name;
1691
250
    mapping->table_type = table_column.type;
1692
250
    const auto row_lineage_type = row_lineage_virtual_column_type(table_column, _options.mode);
1693
250
    if (const auto* partition_value = find_partition_value(table_column, _partition_values);
1694
250
        table_column.is_partition_key && partition_value != nullptr) {
1695
        // Partition values are split constants and must take precedence over defaults.
1696
12
        _set_constant_mapping(mapping, VExprContext::create_shared(VLiteral::create_shared(
1697
12
                                               mapping->table_type, *partition_value)));
1698
238
    } else if (_options.mode == TableColumnMappingMode::BY_INDEX &&
1699
238
               !table_column.is_partition_key && table_column.has_identifier_field_id()) {
1700
        // BY_INDEX interprets ColumnDefinition::identifier as physical file position.
1701
19
        RETURN_IF_ERROR(_create_by_index_mapping(table_column, _file_schema, mapping));
1702
219
    } else if (const auto* file_field = _find_file_field(table_column, _file_schema)) {
1703
        // Normal physical file column mapping.
1704
189
        RETURN_IF_ERROR(_create_direct_mapping(table_column, *file_field, mapping));
1705
188
        if (row_lineage_type != TableVirtualColumnType::INVALID) {
1706
            // Iceberg v3 rewritten files may physically contain row lineage metadata fields.
1707
            // File non-null values must be preserved, while file NULLs still inherit from data file
1708
            // metadata in IcebergTableReader. Therefore the mapping has a real file source plus a
1709
            // virtual post-materialization step, and filters must wait for finalize output.
1710
10
            mapping->virtual_column_type = row_lineage_type;
1711
10
            mapping->filter_conversion = FilterConversionType::FINALIZE_ONLY;
1712
10
        }
1713
188
    } else if (row_lineage_type != TableVirtualColumnType::INVALID) {
1714
        // Iceberg row lineage metadata fields are optional in data files. Missing fields are exposed
1715
        // as all-NULL table columns first; IcebergTableReader fills inherited values only when the
1716
        // split carries first_row_id / last_updated_sequence_number metadata.
1717
        // FE may attach a default_expr to these hidden metadata columns, but the Iceberg v3
1718
        // inheritance rule must take precedence over the generic missing-column default path.
1719
13
        mapping->virtual_column_type = row_lineage_type;
1720
17
    } else if (table_column.name == BeConsts::ICEBERG_ROWID_COL) {
1721
        // Doris internal Iceberg row locator is never a physical Iceberg data column. It is built
1722
        // from file path, row position and partition metadata for delete/update/merge.
1723
2
        mapping->virtual_column_type = TableVirtualColumnType::ICEBERG_ROWID;
1724
15
    } else if (table_column.default_expr != nullptr) {
1725
        // Missing schema-evolution column with an explicit default expression.
1726
6
        _set_constant_mapping(mapping, table_column.default_expr);
1727
9
    } else {
1728
9
        if (table_column.is_partition_key) {
1729
0
            return Status::InvalidArgument(
1730
0
                    "Table column '{}' (global_index={}) does not have a matching partition value",
1731
0
                    table_column.name, mapping->global_index.value());
1732
0
        }
1733
9
    }
1734
249
    return Status::OK();
1735
250
}
1736
1737
Status TableColumnMapper::_create_hidden_filter_mapping(const ColumnDefinition& table_column,
1738
                                                        GlobalIndex global_index,
1739
2
                                                        ColumnMapping* mapping) {
1740
2
    auto status = _create_mapping_for_column(table_column, global_index, mapping);
1741
2
    if (mapping->file_local_id.has_value() || mapping->constant_index.has_value() ||
1742
2
        mapping->virtual_column_type != TableVirtualColumnType::INVALID) {
1743
0
        return Status::OK();
1744
0
    }
1745
2
    if (_options.mode == TableColumnMappingMode::BY_NAME) {
1746
0
        return status;
1747
0
    }
1748
1749
    // Predicate-only slot refs carry the table name/type but do not carry the table-format field
1750
    // id used by BY_FIELD_ID or the file position used by BY_INDEX. Use a name fallback only for
1751
    // hidden filter localization; projected columns still obey the requested mapping mode.
1752
2
    const auto* file_field =
1753
2
            matcher_for_mode(TableColumnMappingMode::BY_NAME).find(table_column, _file_schema);
1754
2
    if (file_field == nullptr) {
1755
0
        return status;
1756
0
    }
1757
2
    ColumnMapping fallback_mapping;
1758
2
    fallback_mapping.global_index = global_index;
1759
2
    fallback_mapping.table_column_name = table_column.name;
1760
2
    fallback_mapping.table_type = table_column.type;
1761
2
    RETURN_IF_ERROR(_create_direct_mapping(table_column, *file_field, &fallback_mapping));
1762
2
    *mapping = std::move(fallback_mapping);
1763
2
    return Status::OK();
1764
2
}
1765
1766
Status TableColumnMapper::_build_hidden_filter_mappings(
1767
141
        const std::vector<TableFilter>& table_filters) {
1768
141
    _hidden_mappings.clear();
1769
1770
141
    std::map<GlobalIndex, ColumnDefinition> filter_columns;
1771
141
    for (const auto& table_filter : table_filters) {
1772
82
        if (table_filter.conjunct != nullptr) {
1773
80
            collect_top_level_slot_columns(table_filter.conjunct->root(), &filter_columns);
1774
80
        }
1775
82
    }
1776
1777
141
    for (const auto& [global_index, table_column] : filter_columns) {
1778
81
        if (_find_mapping(global_index) != nullptr) {
1779
            // Ignore columns that are already mapped by the projected columns
1780
79
            continue;
1781
79
        }
1782
2
        ColumnMapping mapping;
1783
2
        RETURN_IF_ERROR(_create_hidden_filter_mapping(table_column, global_index, &mapping));
1784
2
        if (mapping.file_local_id.has_value() || mapping.constant_index.has_value() ||
1785
2
            mapping.virtual_column_type != TableVirtualColumnType::INVALID) {
1786
2
            _hidden_mappings.push_back(std::move(mapping));
1787
2
        }
1788
2
    }
1789
141
    return Status::OK();
1790
141
}
1791
1792
Status TableColumnMapper::create_mapping(const std::vector<ColumnDefinition>& projected_columns,
1793
                                         const std::map<std::string, Field>& partition_values,
1794
178
                                         const std::vector<ColumnDefinition>& file_schema) {
1795
178
    clear();
1796
178
    _partition_values = partition_values;
1797
178
    _file_schema = file_schema;
1798
425
    for (size_t column_idx = 0; column_idx < projected_columns.size(); ++column_idx) {
1799
248
        ColumnMapping mapping;
1800
248
        RETURN_IF_ERROR(_create_mapping_for_column(projected_columns[column_idx],
1801
248
                                                   GlobalIndex(column_idx), &mapping));
1802
247
        _mappings.push_back(std::move(mapping));
1803
247
    }
1804
177
    return Status::OK();
1805
178
}
1806
1807
441
std::vector<ColumnMapping> TableColumnMapper::_filter_visible_mappings() const {
1808
441
    std::vector<ColumnMapping> mappings;
1809
441
    mappings.reserve(_mappings.size() + _hidden_mappings.size());
1810
441
    mappings.insert(mappings.end(), _mappings.begin(), _mappings.end());
1811
441
    mappings.insert(mappings.end(), _hidden_mappings.begin(), _hidden_mappings.end());
1812
441
    return mappings;
1813
441
}
1814
1815
147
Status TableColumnMapper::_build_filter_entries(const FileScanRequest& file_request) {
1816
147
    _filter_entries.clear();
1817
147
    const auto mappings = _filter_visible_mappings();
1818
190
    for (const auto& mapping : mappings) {
1819
190
        FilterEntry entry;
1820
190
        if (mapping.constant_index.has_value()) {
1821
12
            entry = FilterEntry::constant(*mapping.constant_index);
1822
178
        } else if (mapping.file_local_id.has_value() &&
1823
178
                   filter_conversion_has_local_source(mapping.filter_conversion)) {
1824
152
            const auto local_position_it =
1825
152
                    file_request.local_positions.find(LocalColumnId(*mapping.file_local_id));
1826
152
            if (local_position_it != file_request.local_positions.end()) {
1827
152
                entry = FilterEntry::local(local_position_it->second);
1828
152
            }
1829
152
        }
1830
190
        _filter_entries.emplace(mapping.global_index, entry);
1831
190
    }
1832
147
    return Status::OK();
1833
147
}
1834
1835
Status TableColumnMapper::create_scan_request(
1836
        const std::vector<TableFilter>& table_filters,
1837
        const std::vector<ColumnDefinition>& projected_columns, FileScanRequest* file_request,
1838
141
        RuntimeState* runtime_state) {
1839
    // FileReader evaluates expressions against a file-local block. This mapper owns the
1840
    // table-column to file-column conversion, so it also owns the file-local block positions.
1841
141
    file_request->predicate_columns.clear();
1842
141
    file_request->non_predicate_columns.clear();
1843
141
    file_request->local_positions.clear();
1844
141
    file_request->conjuncts.clear();
1845
141
    file_request->delete_conjuncts.clear();
1846
141
    _filter_entries.clear();
1847
    // 1. Build referenced non-predicate columns
1848
322
    for (size_t column_idx = 0; column_idx < projected_columns.size(); ++column_idx) {
1849
181
        const auto global_index = GlobalIndex(column_idx);
1850
181
        auto* mapping = _find_mapping(global_index);
1851
181
        if (mapping != nullptr && mapping->file_local_id.has_value()) {
1852
            // A file column can be read lazily as a non-predicate column only when it is not used
1853
            // by row-level expression filters.
1854
157
            bool used_by_filter = false;
1855
157
            for (const auto& table_filter : table_filters) {
1856
98
                const auto& global_indices = table_filter.global_indices;
1857
98
                if (std::find(global_indices.begin(), global_indices.end(), global_index) !=
1858
98
                            global_indices.end() &&
1859
98
                    filter_conversion_has_local_source(mapping->filter_conversion)) {
1860
69
                    used_by_filter = true;
1861
69
                    break;
1862
69
                }
1863
98
            }
1864
157
            if (!used_by_filter || !enable_lazy_materialization()) {
1865
90
                RETURN_IF_ERROR(add_scan_column(file_request, mapping, false,
1866
90
                                                force_full_complex_scan_projection()));
1867
90
            }
1868
157
        }
1869
181
    }
1870
    // 2. Build referenced predicate columns
1871
    // Hidden filter mappings must be built before localizing filters, so that they can be localized together with visible mappings and referenced by localized filter expressions.
1872
141
    RETURN_IF_ERROR(_build_hidden_filter_mappings(table_filters));
1873
141
    RETURN_IF_ERROR(localize_filters(table_filters, file_request, runtime_state));
1874
    // 3. Rebuild output projection expressions for projected columns. localize_filters() has
1875
    // already applied the final scan projection to mapping.file_type/projected_file_children before
1876
    // rewriting filter expressions.
1877
181
    for (auto& mapping : _mappings) {
1878
181
        if (!mapping.file_local_id.has_value()) {
1879
24
            continue;
1880
24
        }
1881
157
        auto position_it =
1882
157
                file_request->local_positions.find(LocalColumnId(*mapping.file_local_id));
1883
157
        DORIS_CHECK(position_it != file_request->local_positions.end())
1884
0
                << file_request->local_positions.size() << " " << *mapping.file_local_id << " "
1885
0
                << mapping.file_column_name;
1886
157
        rebuild_projection(&mapping, position_it->second);
1887
157
    }
1888
141
    return Status::OK();
1889
141
}
1890
1891
353
ColumnMapping* TableColumnMapper::_find_mapping(GlobalIndex global_index) {
1892
446
    for (auto& mapping : _mappings) {
1893
446
        if (mapping.global_index == global_index) {
1894
349
            return &mapping;
1895
349
        }
1896
446
    }
1897
4
    return nullptr;
1898
353
}
1899
1900
91
ColumnMapping* TableColumnMapper::_find_filter_mapping(GlobalIndex global_index) {
1901
91
    if (auto* mapping = _find_mapping(global_index); mapping != nullptr) {
1902
89
        return mapping;
1903
89
    }
1904
2
    for (auto& mapping : _hidden_mappings) {
1905
2
        if (mapping.global_index == global_index) {
1906
2
            return &mapping;
1907
2
        }
1908
2
    }
1909
0
    return nullptr;
1910
2
}
1911
1912
Status TableColumnMapper::localize_filters(const std::vector<TableFilter>& table_filters,
1913
                                           FileScanRequest* file_request,
1914
147
                                           RuntimeState* runtime_state) {
1915
147
    FilterProjectionMap filter_projections;
1916
147
    auto filter_mappings = _filter_visible_mappings();
1917
147
    RETURN_IF_ERROR(build_nested_struct_filter_projection_map(table_filters, filter_mappings,
1918
147
                                                              &filter_projections));
1919
147
    for (const auto& table_filter : table_filters) {
1920
91
        for (const auto& global_index : table_filter.global_indices) {
1921
91
            auto* mapping = _find_filter_mapping(global_index);
1922
91
            if (mapping == nullptr || !mapping->file_local_id.has_value() ||
1923
91
                !filter_conversion_has_local_source(mapping->filter_conversion)) {
1924
14
                continue;
1925
14
            }
1926
77
            RETURN_IF_ERROR(add_scan_column(file_request, mapping, enable_lazy_materialization(),
1927
77
                                            force_full_complex_scan_projection(),
1928
77
                                            &filter_projections));
1929
77
        }
1930
88
    }
1931
    // Rebuild the file type for every scan-local mapping before expression rewrite. Predicate-only
1932
    // hidden mappings must see the same projected file type as the file reader will produce.
1933
188
    for (auto& mapping : _mappings) {
1934
188
        if (mapping.file_local_id.has_value() &&
1935
188
            file_request->local_positions.contains(LocalColumnId(*mapping.file_local_id))) {
1936
163
            RETURN_IF_ERROR(apply_scan_projection_to_mapping_file_type(*file_request, &mapping));
1937
163
        }
1938
188
    }
1939
147
    for (auto& mapping : _hidden_mappings) {
1940
2
        if (mapping.file_local_id.has_value() &&
1941
2
            file_request->local_positions.contains(LocalColumnId(*mapping.file_local_id))) {
1942
2
            RETURN_IF_ERROR(apply_scan_projection_to_mapping_file_type(*file_request, &mapping));
1943
2
        }
1944
2
    }
1945
147
    RETURN_IF_ERROR(_build_filter_entries(*file_request));
1946
1947
    // Build the complete table-slot rewrite map after all predicate columns have been assigned.
1948
    // This keeps expression localization independent from filter iteration order.
1949
147
    filter_mappings = _filter_visible_mappings();
1950
147
    const auto global_to_file_slot = build_file_slot_rewrite_map(filter_mappings, _filter_entries);
1951
147
    for (const auto& table_filter : table_filters) {
1952
88
        if (table_filter.conjunct != nullptr &&
1953
88
            table_filter_has_only_local_entries(table_filter, _filter_entries)) {
1954
72
            RewriteContext rewrite_context {.runtime_state = runtime_state};
1955
72
            VExprSPtr rewrite_root;
1956
72
            Status clone_status;
1957
72
            try {
1958
72
                clone_status = clone_table_expr_tree(table_filter.conjunct->root(), &rewrite_root);
1959
72
            } catch ([[maybe_unused]] const Exception& e) {
1960
                // Some table filters contain complex intermediate values, for example
1961
                // `element_at(MAP_VALUES(m)[1], 'age') > 30`. The current file-local rewrite only
1962
                // understands top-level slots and struct-element paths rooted at top-level slots;
1963
                // cloning such expressions can hit the generic TExpr complex-type limitation.
1964
                // Leave them above TableReader, where Scanner evaluates the original table-level
1965
                // conjunct after final materialization.
1966
0
#ifndef NDEBUG
1967
0
                return Status::InternalError(
1968
0
                        "Failed to clone table filter for file-local rewrite: {}, expr={}",
1969
0
                        e.to_string(), table_filter.conjunct->root()->debug_string());
1970
#else
1971
                continue;
1972
#endif
1973
0
            } catch ([[maybe_unused]] const std::exception& e) {
1974
0
#ifndef NDEBUG
1975
0
                return Status::InternalError(
1976
0
                        "Failed to clone table filter for file-local rewrite: {}, expr={}",
1977
0
                        e.what(), table_filter.conjunct->root()->debug_string());
1978
#else
1979
                continue;
1980
#endif
1981
0
            }
1982
72
            if (!clone_status.ok()) {
1983
0
#ifndef NDEBUG
1984
0
                return Status::InternalError(
1985
0
                        "Failed to clone table filter for file-local rewrite: {}, expr={}",
1986
0
                        clone_status.to_string(), table_filter.conjunct->root()->debug_string());
1987
#else
1988
                continue;
1989
#endif
1990
0
            }
1991
72
            bool can_localize = true;
1992
72
            auto localized_root = rewrite_table_expr_to_file_expr(rewrite_root, global_to_file_slot,
1993
72
                                                                  filter_mappings, &rewrite_context,
1994
72
                                                                  &can_localize);
1995
72
            if (!can_localize) {
1996
5
                continue;
1997
5
            }
1998
67
            auto localized_conjunct = VExprContext::create_shared(std::move(localized_root));
1999
67
            RETURN_IF_ERROR(rewrite_context.prepare_created_exprs(localized_conjunct.get()));
2000
67
            file_request->conjuncts.push_back(std::move(localized_conjunct));
2001
67
        }
2002
88
    }
2003
147
    return Status::OK();
2004
147
}
2005
2006
const ColumnDefinition* TableColumnMapper::_find_file_field(
2007
        const ColumnDefinition& table_column,
2008
219
        const std::vector<ColumnDefinition>& file_schema) const {
2009
219
    if (table_column.name.starts_with(BeConsts::GLOBAL_ROWID_COL)) {
2010
2
        const auto field_it = std::ranges::find_if(file_schema, [](const ColumnDefinition& field) {
2011
2
            return field.column_type == ColumnType::GLOBAL_ROWID;
2012
2
        });
2013
1
        return field_it == file_schema.end() ? nullptr : &*field_it;
2014
1
    }
2015
218
    return matcher_for_mode(_options.mode).find(table_column, file_schema);
2016
219
}
2017
2018
Status TableColumnMapper::_create_direct_mapping(const ColumnDefinition& table_column,
2019
                                                 const ColumnDefinition& file_field,
2020
314
                                                 ColumnMapping* mapping) const {
2021
314
    DORIS_CHECK(mapping != nullptr);
2022
314
    DORIS_CHECK(file_field.local_id >= 0 || file_field.local_id == GLOBAL_ROWID_COLUMN_ID);
2023
314
    mapping->file_local_id = file_field.local_id;
2024
314
    mapping->table_column_name = table_column.name;
2025
314
    mapping->file_column_name = file_field.name;
2026
314
    mapping->original_file_type = file_field.type;
2027
314
    mapping->original_file_children = file_field.children;
2028
314
    mapping->projected_file_children = file_field.children;
2029
314
    mapping->file_type = file_field.type;
2030
314
    mapping->is_trivial = mapping_can_use_file_column_directly(*mapping);
2031
314
    mapping->filter_conversion = direct_filter_conversion(*mapping);
2032
314
    mapping->child_mappings.clear();
2033
2034
314
    auto table_children = table_column.children;
2035
314
    const auto nested_table_type = remove_nullable(mapping->table_type);
2036
    // Some scan paths, especially SELECT *, only carry the complete complex DataType for a table
2037
    // column and leave ColumnDefinition::children empty. If the file type is an older complex
2038
    // schema, treating this as a leaf mapping would make TableReader fall back to a plain CAST.
2039
    // That is invalid for evolved structs with different field counts.
2040
    //
2041
    // Example:
2042
    //   table column type: Map(String, Struct(age, full_name, gender))
2043
    //   old file type:    Map(String, Struct(age, name))
2044
    //   table children:   empty
2045
    //
2046
    // Synthesize key/value/struct-field children from the table type so the normal recursive
2047
    // mapping path can rematerialize `name -> full_name` and fill missing `gender` with defaults,
2048
    // instead of trying to CAST Struct(age, name) to Struct(age, full_name, gender).
2049
314
    const bool synthesized_table_children =
2050
314
            table_children.empty() && is_complex_type(nested_table_type->get_primitive_type()) &&
2051
314
            !mapping->table_type->equals(*mapping->file_type);
2052
314
    if (synthesized_table_children) {
2053
4
        table_children = synthesize_complex_children_from_type(mapping->table_type);
2054
310
    } else if (!table_children.empty() && !mapping->table_type->equals(*mapping->file_type)) {
2055
59
        complete_required_complex_children_from_type(mapping->table_type, &table_children);
2056
59
    }
2057
2058
314
    if (!table_children.empty()) {
2059
79
        if (!is_complex_type(remove_nullable(mapping->file_type)->get_primitive_type())) {
2060
0
            return Status::NotSupported(
2061
0
                    "Cannot map complex table column '{}' to scalar parquet column '{}', table "
2062
0
                    "type={}, file type={}",
2063
0
                    table_column.name, file_field.name, mapping->table_type->get_name(),
2064
0
                    mapping->file_type->get_name());
2065
0
        }
2066
79
        RETURN_IF_ERROR(validate_file_schema_children(file_field));
2067
78
        std::vector<int32_t> synthesized_used_file_child_ids;
2068
200
        for (size_t table_child_idx = 0; table_child_idx < table_children.size();
2069
122
             ++table_child_idx) {
2070
122
            const auto& table_child = table_children[table_child_idx];
2071
122
            const auto* file_child =
2072
122
                    find_file_child_for_mapping(table_child, file_field, _options.mode,
2073
122
                                                table_child_idx, synthesized_table_children);
2074
122
            if (synthesized_table_children && file_child != nullptr) {
2075
8
                const auto file_child_id = file_child->file_local_id();
2076
8
                if (std::ranges::find(synthesized_used_file_child_ids, file_child_id) !=
2077
8
                    synthesized_used_file_child_ids.end()) {
2078
2
                    file_child = nullptr;
2079
2
                    for (const auto& candidate : file_field.children) {
2080
2
                        const auto candidate_id = candidate.file_local_id();
2081
2
                        if (std::ranges::find(synthesized_used_file_child_ids, candidate_id) ==
2082
2
                            synthesized_used_file_child_ids.end()) {
2083
2
                            file_child = &candidate;
2084
2
                            break;
2085
2
                        }
2086
2
                    }
2087
2
                }
2088
8
                if (file_child != nullptr) {
2089
8
                    synthesized_used_file_child_ids.push_back(file_child->file_local_id());
2090
8
                }
2091
8
            }
2092
122
            if (file_child == nullptr) {
2093
15
                ColumnMapping child_mapping;
2094
15
                child_mapping.table_column_name = table_child.name;
2095
15
                child_mapping.file_column_name = table_child.name;
2096
15
                child_mapping.table_type = table_child.type;
2097
15
                child_mapping.file_type = table_child.type;
2098
15
                child_mapping.filter_conversion = FilterConversionType::FINALIZE_ONLY;
2099
15
                mapping->child_mappings.push_back(std::move(child_mapping));
2100
15
                continue;
2101
15
            }
2102
107
            ColumnMapping child_mapping;
2103
107
            child_mapping.table_column_name = table_child.name;
2104
107
            child_mapping.table_type = table_child.type;
2105
107
            RETURN_IF_ERROR(_create_direct_mapping(table_child, *file_child, &child_mapping));
2106
107
            mapping->child_mappings.push_back(std::move(child_mapping));
2107
107
        }
2108
78
        if (needs_projected_file_type_rebuild(*mapping)) {
2109
            // If complex projection prunes some children, we have to rebuild the projected file type to make sure the reader expression can find the correct child types by name.
2110
64
            RETURN_IF_ERROR(rebuild_projected_file_children_and_type(
2111
64
                    mapping->file_type, mapping->original_file_children, mapping->child_mappings,
2112
64
                    &mapping->projected_file_children, &mapping->file_type));
2113
64
            DCHECK(mapping->table_type != nullptr);
2114
64
            mapping->is_trivial = mapping_can_use_file_column_directly(*mapping);
2115
64
            mapping->filter_conversion = projected_filter_conversion(*mapping);
2116
64
        }
2117
78
    }
2118
313
    return Status::OK();
2119
314
}
2120
2121
} // namespace doris::format