Coverage Report

Created: 2026-07-12 22:20

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
387
bool column_has_name(const ColumnDefinition& column, const std::string& name) {
72
387
    if (to_lower(column.name) == to_lower(name)) {
73
164
        return true;
74
164
    }
75
223
    if (column.has_identifier_name() && to_lower(column.get_identifier_name()) == to_lower(name)) {
76
0
        return true;
77
0
    }
78
223
    return std::ranges::any_of(column.name_mapping, [&](const std::string& alias) {
79
10
        return to_lower(alias) == to_lower(name);
80
10
    });
81
223
}
82
83
264
bool column_names_match(const ColumnDefinition& lhs, const ColumnDefinition& rhs) {
84
264
    if (column_has_name(rhs, lhs.name)) {
85
155
        return true;
86
155
    }
87
109
    if (lhs.has_identifier_name() && column_has_name(rhs, lhs.get_identifier_name())) {
88
1
        return true;
89
1
    }
90
108
    return std::ranges::any_of(lhs.name_mapping, [&](const std::string& alias) {
91
18
        return column_has_name(rhs, alias);
92
18
    });
93
109
}
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
109
                                 const std::vector<ColumnDefinition>& file_schema) const override {
107
109
        if (!table_column.has_identifier_field_id()) {
108
7
            return nullptr;
109
7
        }
110
102
        const auto field_id = table_column.get_identifier_field_id();
111
166
        const auto field_it = std::ranges::find_if(file_schema, [&](const ColumnDefinition& field) {
112
166
            return field.has_identifier_field_id() && field.get_identifier_field_id() == field_id;
113
166
        });
114
102
        return field_it == file_schema.end() ? nullptr : &*field_it;
115
109
    }
116
};
117
118
class NameMatcher final : public ColumnMatcher {
119
public:
120
    const ColumnDefinition* find(const ColumnDefinition& table_column,
121
192
                                 const std::vector<ColumnDefinition>& file_schema) const override {
122
264
        const auto field_it = std::ranges::find_if(file_schema, [&](const ColumnDefinition& field) {
123
264
            return column_names_match(table_column, field);
124
264
        });
125
192
        return field_it == file_schema.end() ? nullptr : &*field_it;
126
192
    }
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
300
const ColumnMatcher& matcher_for_mode(TableColumnMappingMode mode) {
145
300
    static const FieldIdMatcher field_id_matcher;
146
300
    static const NameMatcher name_matcher;
147
300
    static const PositionMatcher position_matcher;
148
300
    switch (mode) {
149
109
    case TableColumnMappingMode::BY_FIELD_ID:
150
109
        return field_id_matcher;
151
189
    case TableColumnMappingMode::BY_NAME:
152
189
        return name_matcher;
153
2
    case TableColumnMappingMode::BY_INDEX:
154
2
        return position_matcher;
155
300
    }
156
0
    return field_id_matcher;
157
300
}
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
244
                                  const std::map<std::string, Field>& partition_values) {
235
388
    const auto find_by_name = [&](const std::string& name) -> const Field* {
236
388
        const auto value_it = partition_values.find(name);
237
388
        return value_it == partition_values.end() ? nullptr : &value_it->second;
238
388
    };
239
244
    if (const auto* value = find_by_name(table_column.name); value != nullptr) {
240
15
        return value;
241
15
    }
242
229
    if (table_column.has_identifier_name()) {
243
137
        if (const auto* value = find_by_name(table_column.get_identifier_name());
244
137
            value != nullptr) {
245
0
            return value;
246
0
        }
247
137
    }
248
229
    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
228
    return nullptr;
254
229
}
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
132
    void add_created_expr(VExprSPtr expr) { created_exprs.push_back(std::move(expr)); }
268
269
63
    Status prepare_created_exprs(VExprContext* context) const {
270
63
        DORIS_CHECK(context != nullptr);
271
63
        RowDescriptor row_desc;
272
130
        for (const auto& expr : created_exprs) {
273
130
            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
130
            RETURN_IF_ERROR(expr->prepare(runtime_state, row_desc, context));
279
130
        }
280
63
        return Status::OK();
281
63
    }
282
};
283
284
static VExprSPtr create_file_slot_ref(const VSlotRef& slot_ref,
285
                                      const FileSlotRewriteInfo& rewrite_info,
286
70
                                      RewriteContext* rewrite_context) {
287
70
    auto ref =
288
70
            VSlotRef::create_shared(slot_ref.slot_id(), cast_set<int>(rewrite_info.block_position),
289
70
                                    -1, rewrite_info.file_type, rewrite_info.file_column_name);
290
70
    rewrite_context->add_created_expr(ref);
291
70
    return ref;
292
70
}
293
294
237
static bool is_cast_expr(const VExprSPtr& expr) {
295
237
    return dynamic_cast<const Cast*>(expr.get()) != nullptr;
296
237
}
297
298
155
static bool is_binary_comparison_predicate(const VExprSPtr& expr) {
299
155
    if (expr == nullptr || expr->get_num_children() != 2 ||
300
155
        (expr->node_type() != TExprNodeType::BINARY_PRED &&
301
105
         expr->node_type() != TExprNodeType::NULL_AWARE_BINARY_PRED)) {
302
105
        return false;
303
105
    }
304
50
    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
46
    case TExprOpcode::GT:
310
46
    case TExprOpcode::LE:
311
50
    case TExprOpcode::LT:
312
50
        return true;
313
0
    default:
314
0
        return false;
315
50
    }
316
50
}
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
77
        const VSlotRef** slot_ref) {
395
77
    if (expr == nullptr) {
396
0
        return nullptr;
397
0
    }
398
77
    VExprSPtr slot_expr = expr;
399
77
    const bool input_is_cast = is_cast_expr(expr) && expr->get_num_children() == 1;
400
77
    if (is_cast_expr(expr) && expr->get_num_children() == 1) {
401
3
        slot_expr = expr->children()[0];
402
3
    }
403
77
    if (!slot_expr->is_slot_ref()) {
404
40
        return nullptr;
405
40
    }
406
37
    const auto* candidate_slot_ref = assert_cast<const VSlotRef*>(slot_expr.get());
407
37
    const auto rewrite_it = global_to_file_slot.find(slot_ref_global_index(*candidate_slot_ref));
408
37
    if (rewrite_it == global_to_file_slot.end()) {
409
0
        return nullptr;
410
0
    }
411
37
    if (input_is_cast && !expr->data_type()->equals(*rewrite_it->second.table_type)) {
412
1
        return nullptr;
413
1
    }
414
36
    if (slot_ref != nullptr) {
415
36
        *slot_ref = candidate_slot_ref;
416
36
    }
417
36
    return &rewrite_it->second;
418
37
}
419
420
300
static bool filter_conversion_has_local_source(FilterConversionType conversion) {
421
300
    switch (conversion) {
422
213
    case FilterConversionType::COPY_DIRECTLY:
423
264
    case FilterConversionType::CAST_FILTER:
424
282
    case FilterConversionType::READER_EXPRESSION:
425
282
        return true;
426
18
    case FilterConversionType::FINALIZE_ONLY:
427
18
    case FilterConversionType::CONSTANT:
428
18
        return false;
429
300
    }
430
0
    return false;
431
300
}
432
433
static bool table_filter_has_only_local_entries(
434
82
        const TableFilter& table_filter, const std::map<GlobalIndex, FilterEntry>& filter_entries) {
435
83
    for (const auto global_index : table_filter.global_indices) {
436
83
        const auto entry_it = filter_entries.find(global_index);
437
83
        if (entry_it == filter_entries.end() || !entry_it->second.is_local()) {
438
14
            return false;
439
14
        }
440
83
    }
441
68
    return true;
442
82
}
443
444
static VExprSPtr unwrap_literal_for_file_cast(const VExprSPtr& expr,
445
44
                                              const DataTypePtr& table_type) {
446
44
    if (expr == nullptr) {
447
0
        return nullptr;
448
0
    }
449
44
    if (expr->is_literal()) {
450
44
        return expr;
451
44
    }
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
396
static Status clone_table_expr_node(const VExpr& expr, VExprSPtr* cloned_expr) {
472
396
    DORIS_CHECK(cloned_expr != nullptr);
473
396
    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
396
    } else if (const auto* vcast_expr = dynamic_cast<const VCastExpr*>(&expr);
478
396
               vcast_expr != nullptr && vcast_expr->node_type() == TExprNodeType::CAST_EXPR) {
479
0
        *cloned_expr = Cast::create_shared(vcast_expr->data_type());
480
0
    }
481
396
    return Status::OK();
482
396
}
483
484
105
Status clone_table_expr_tree(const VExprSPtr& expr, VExprSPtr* cloned_expr) {
485
105
    DORIS_CHECK(cloned_expr != nullptr);
486
105
    if (expr == nullptr) {
487
0
        *cloned_expr = nullptr;
488
0
        return Status::OK();
489
0
    }
490
105
    return expr->deep_clone(cloned_expr, clone_table_expr_node);
491
105
}
492
493
static VExprSPtr original_table_literal(const VExprSPtr& literal_expr,
494
48
                                        RewriteContext* rewrite_context = nullptr) {
495
48
    DORIS_CHECK(literal_expr != nullptr);
496
48
    DORIS_CHECK(literal_expr->is_literal());
497
48
    const auto* rewritten_literal = dynamic_cast<const SplitLocalFileLiteral*>(literal_expr.get());
498
48
    if (rewritten_literal == nullptr) {
499
48
        return literal_expr;
500
48
    }
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
48
}
508
509
81
static ColumnDefinition hidden_column_from_slot_ref(const VSlotRef& slot_ref) {
510
81
    ColumnDefinition column;
511
81
    column.name = slot_ref.column_name();
512
81
    column.identifier = Field::create_field<TYPE_STRING>(column.name);
513
81
    column.type = slot_ref.data_type();
514
81
    return column;
515
81
}
516
517
static void collect_top_level_slot_columns(const VExprSPtr& expr,
518
305
                                           std::map<GlobalIndex, ColumnDefinition>* columns) {
519
305
    DORIS_CHECK(columns != nullptr);
520
305
    if (expr == nullptr) {
521
0
        return;
522
0
    }
523
305
    if (expr->is_slot_ref()) {
524
81
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr.get());
525
81
        columns->try_emplace(slot_ref_global_index(*slot_ref),
526
81
                             hidden_column_from_slot_ref(*slot_ref));
527
81
        return;
528
81
    }
529
229
    for (const auto& child : expr->children()) {
530
229
        collect_top_level_slot_columns(child, columns);
531
229
    }
532
224
}
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
35
                                                   const DataTypePtr& table_type) {
575
35
    const auto file_nested_type = remove_nullable(file_type);
576
35
    const auto table_nested_type = remove_nullable(table_type);
577
35
    if (file_nested_type->equals(*table_nested_type)) {
578
21
        return true;
579
21
    }
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
40
                                              RewriteContext* rewrite_context) {
602
40
    DORIS_CHECK(literal_expr != nullptr);
603
40
    DORIS_CHECK(literal_expr->is_literal());
604
40
    const auto original_literal = original_table_literal(literal_expr, rewrite_context);
605
40
    const Field original_field = literal_field(original_literal);
606
40
    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
35
    if (!is_lossless_file_to_table_numeric_cast(rewrite_info.file_type,
616
35
                                                original_literal->data_type())) {
617
4
        return nullptr;
618
4
    }
619
31
    Field file_field;
620
31
    try {
621
31
        convert_field_to_type(original_field, *rewrite_info.file_type, &file_field,
622
31
                              original_literal->data_type().get());
623
31
    } catch (const Exception&) {
624
0
        return nullptr;
625
0
    }
626
31
    if (file_field.is_null()) {
627
0
        return nullptr;
628
0
    }
629
31
    if (file_field.get_type() != remove_nullable(rewrite_info.file_type)->get_primitive_type()) {
630
0
        return nullptr;
631
0
    }
632
31
    Field round_trip_field;
633
31
    try {
634
31
        convert_field_to_type(file_field, *original_literal->data_type(), &round_trip_field,
635
31
                              rewrite_info.file_type.get());
636
31
    } 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
31
    if (round_trip_field != original_field) {
642
2
        return nullptr;
643
2
    }
644
29
    auto literal = std::make_shared<SplitLocalFileLiteral>(
645
29
            rewrite_info.file_type, file_field, original_literal->data_type(), original_field);
646
29
    rewrite_context->add_created_expr(literal);
647
29
    return literal;
648
31
}
649
650
static bool rewrite_binary_slot_literal_predicate(
651
        const VExprSPtr& expr,
652
        const std::map<GlobalIndex, FileSlotRewriteInfo>& global_to_file_slot,
653
155
        RewriteContext* rewrite_context) {
654
155
    if (!is_binary_comparison_predicate(expr)) {
655
105
        return false;
656
105
    }
657
50
    auto children = expr->children();
658
50
    const VSlotRef* slot_ref = nullptr;
659
50
    const FileSlotRewriteInfo* rewrite_info =
660
50
            find_slot_rewrite_info(children[0], global_to_file_slot, &slot_ref);
661
50
    int slot_child_idx = 0;
662
50
    int literal_child_idx = 1;
663
50
    if (rewrite_info == nullptr) {
664
20
        rewrite_info = find_slot_rewrite_info(children[1], global_to_file_slot, &slot_ref);
665
20
        slot_child_idx = 1;
666
20
        literal_child_idx = 0;
667
20
    }
668
50
    if (rewrite_info == nullptr || slot_ref == nullptr) {
669
19
        return false;
670
19
    }
671
31
    auto literal_expr =
672
31
            unwrap_literal_for_file_cast(children[literal_child_idx], rewrite_info->table_type);
673
31
    if (literal_expr == nullptr) {
674
0
        return false;
675
0
    }
676
677
31
    auto rewritten_literal =
678
31
            rewrite_literal_to_file_type(literal_expr, *rewrite_info, rewrite_context);
679
31
    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
27
    children[slot_child_idx] = create_file_slot_ref(*slot_ref, *rewrite_info, rewrite_context);
686
27
    children[literal_child_idx] = std::move(rewritten_literal);
687
27
    expr->set_children(std::move(children));
688
27
    return true;
689
31
}
690
691
static bool rewrite_in_slot_literal_predicate(
692
        const VExprSPtr& expr,
693
        const std::map<GlobalIndex, FileSlotRewriteInfo>& global_to_file_slot,
694
128
        RewriteContext* rewrite_context) {
695
128
    if (expr->node_type() != TExprNodeType::IN_PRED || expr->get_num_children() < 2) {
696
121
        return false;
697
121
    }
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
23
                                                       RewriteContext* rewrite_context) {
741
23
    auto literal = VLiteral::create_shared(std::make_shared<DataTypeString>(),
742
23
                                           Field::create_field<TYPE_STRING>(file_child_name));
743
23
    rewrite_context->add_created_expr(literal);
744
23
    return literal;
745
23
}
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
23
static bool collect_struct_element_chain(const VExprSPtr& expr, std::vector<VExprSPtr>* chain) {
762
23
    DORIS_CHECK(chain != nullptr);
763
23
    if (!is_struct_element_expr(expr)) {
764
0
        return false;
765
0
    }
766
23
    const auto& parent = expr->children()[0];
767
23
    if (is_struct_element_expr(parent)) {
768
3
        if (!collect_struct_element_chain(parent, chain)) {
769
0
            return false;
770
0
        }
771
20
    } 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
23
    chain->push_back(expr);
784
23
    return true;
785
23
}
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
23
        RewriteContext* rewrite_context) {
791
23
    ResolvedNestedStructPath resolved;
792
23
    if (!resolve_nested_struct_expr_for_file(expr, mappings, &resolved)) {
793
3
        return false;
794
3
    }
795
796
20
    std::vector<VExprSPtr> struct_element_chain;
797
20
    if (!collect_struct_element_chain(expr, &struct_element_chain) ||
798
20
        struct_element_chain.size() != resolved.file_child_names.size() ||
799
20
        struct_element_chain.size() != resolved.file_child_types.size()) {
800
0
        return false;
801
0
    }
802
803
20
    auto root_children = struct_element_chain.front()->children();
804
20
    if (!root_children[0]->is_slot_ref()) {
805
0
        return false;
806
0
    }
807
20
    const auto* slot_ref = assert_cast<const VSlotRef*>(root_children[0].get());
808
20
    const auto rewrite_it = global_to_file_slot.find(slot_ref_global_index(*slot_ref));
809
20
    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
20
    root_children[0] = create_file_slot_ref(*slot_ref, rewrite_it->second, rewrite_context);
822
20
    struct_element_chain.front()->set_children(std::move(root_children));
823
43
    for (size_t idx = 0; idx < struct_element_chain.size(); ++idx) {
824
23
        auto children = struct_element_chain[idx]->children();
825
23
        children[1] = create_file_struct_child_name_literal(resolved.file_child_names[idx],
826
23
                                                            rewrite_context);
827
23
        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
23
        struct_element_chain[idx]->data_type() = resolved.file_child_types[idx];
837
23
    }
838
20
    return true;
839
20
}
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
156
        bool* can_localize) {
846
156
    if (expr == nullptr) {
847
0
        return nullptr;
848
0
    }
849
156
    DORIS_CHECK(rewrite_context != nullptr);
850
156
    DORIS_CHECK(can_localize != nullptr);
851
156
    if (auto* runtime_filter = dynamic_cast<RuntimeFilterExpr*>(expr.get());
852
156
        runtime_filter != nullptr) {
853
1
        auto impl = runtime_filter->get_impl();
854
1
        if (impl == nullptr) {
855
0
            *can_localize = false;
856
0
            return expr;
857
0
        }
858
1
        auto localized_impl = rewrite_table_expr_to_file_expr(
859
1
                impl, global_to_file_slot, filter_mappings, rewrite_context, can_localize);
860
1
        if (!*can_localize) {
861
0
            return expr;
862
0
        }
863
1
        runtime_filter->set_impl(std::move(localized_impl));
864
1
        return expr;
865
1
    }
866
155
    if (rewrite_binary_slot_literal_predicate(expr, global_to_file_slot, rewrite_context)) {
867
27
        return expr;
868
27
    }
869
128
    if (rewrite_in_slot_literal_predicate(expr, global_to_file_slot, rewrite_context)) {
870
3
        return expr;
871
3
    }
872
125
    if (is_struct_element_expr(expr)) {
873
23
        if (!rewrite_struct_element_path_to_file_expr(expr, filter_mappings, global_to_file_slot,
874
23
                                                      rewrite_context)) {
875
            // The scanner still evaluates the original table-level conjunct after TableReader
876
            // finalizes the output block. Skipping an unlocalizable file conjunct is therefore
877
            // safer than preparing a partially rewritten expression against the wrong struct
878
            // layout. In particular, do not generate file-local conjuncts for computed complex
879
            // parents such as `element_at(element_at(map_values(m), 1), 'field')`; only direct
880
            // slot-rooted struct chains are supported here.
881
3
            *can_localize = false;
882
3
        }
883
23
        return expr;
884
23
    }
885
102
    if (expr->is_slot_ref()) {
886
19
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr.get());
887
19
        const auto rewrite_it = global_to_file_slot.find(slot_ref_global_index(*slot_ref));
888
19
        if (rewrite_it != global_to_file_slot.end()) {
889
19
            const auto& rewrite_info = rewrite_it->second;
890
19
            auto file_slot = create_file_slot_ref(*slot_ref, rewrite_info, rewrite_context);
891
19
            if (rewrite_info.file_type->equals(*rewrite_info.table_type)) {
892
7
                return file_slot;
893
7
            }
894
12
            if (needs_complex_file_slot_cast(rewrite_info.file_type, rewrite_info.table_type)) {
895
                // Generic file-local expressions cannot safely cast an evolved complex file slot
896
                // back to the table type. Example:
897
                //
898
                //   table filter: ARRAY_CONTAINS(MAP_KEYS(m), 'person5')
899
                //   old file:     m MAP<STRING, STRUCT<name, age>>
900
                //   table:        m MAP<STRING, STRUCT<age, full_name, gender>>
901
                //
902
                // Although MAP_KEYS only reads the key column, wrapping the file slot as
903
                // `CAST(file_m AS table_m)` forces the value struct cast first and fails because
904
                // the old and new value structs have different fields. Keep such filters at the
905
                // table level, where TableReader materializes the evolved complex value before
906
                // Scanner evaluates the original conjunct. Direct slot-rooted struct child paths
907
                // are handled by rewrite_struct_element_path_to_file_expr() above.
908
2
                *can_localize = false;
909
2
                return expr;
910
2
            }
911
10
            auto cast_expr = Cast::create_shared(rewrite_info.table_type);
912
10
            cast_expr->add_child(std::move(file_slot));
913
10
            rewrite_context->add_created_expr(cast_expr);
914
10
            return cast_expr;
915
12
        }
916
0
        return expr;
917
19
    }
918
    // The input is a split-local cloned tree. A previous split-local clone may already have
919
    // inserted Cast(slot). Keep that rewrite idempotent: rewrite the cast child from table slot to
920
    // the current split's file slot, and drop the cast when the current split no longer needs it.
921
83
    if (is_cast_expr(expr) && expr->get_num_children() == 1) {
922
4
        const auto& child = expr->children()[0];
923
4
        if (child->is_slot_ref()) {
924
2
            const auto* slot_ref = assert_cast<const VSlotRef*>(child.get());
925
2
            const auto rewrite_it = global_to_file_slot.find(slot_ref_global_index(*slot_ref));
926
2
            if (rewrite_it != global_to_file_slot.end() &&
927
2
                expr->data_type()->equals(*rewrite_it->second.table_type)) {
928
1
                auto rewritten_child =
929
1
                        create_file_slot_ref(*slot_ref, rewrite_it->second, rewrite_context);
930
1
                if (rewrite_it->second.file_type->equals(*rewrite_it->second.table_type)) {
931
0
                    return rewritten_child;
932
0
                }
933
1
                if (needs_complex_file_slot_cast(rewrite_it->second.file_type,
934
1
                                                 rewrite_it->second.table_type)) {
935
0
                    *can_localize = false;
936
0
                    return expr;
937
0
                }
938
1
                expr->set_children({std::move(rewritten_child)});
939
1
                return expr;
940
1
            }
941
2
        }
942
4
    }
943
944
82
    VExprSPtrs rewritten_children;
945
82
    rewritten_children.reserve(expr->children().size());
946
87
    for (const auto& child : expr->children()) {
947
87
        rewritten_children.push_back(rewrite_table_expr_to_file_expr(
948
87
                child, global_to_file_slot, filter_mappings, rewrite_context, can_localize));
949
87
    }
950
82
    expr->set_children(std::move(rewritten_children));
951
82
    return expr;
952
83
}
953
954
static constexpr const char* ROW_LINEAGE_ROW_ID = "_row_id";
955
static constexpr const char* ROW_LINEAGE_LAST_UPDATED_SEQ_NUMBER = "_last_updated_sequence_number";
956
static constexpr int32_t ROW_LINEAGE_ROW_ID_FIELD_ID = 2147483540;
957
static constexpr int32_t ROW_LINEAGE_LAST_UPDATED_SEQ_NUMBER_FIELD_ID = 2147483539;
958
959
164
static TableVirtualColumnType row_lineage_virtual_column_type(const std::string& column_name) {
960
164
    if (column_name == ROW_LINEAGE_ROW_ID) {
961
2
        return TableVirtualColumnType::ROW_ID;
962
2
    }
963
162
    if (column_name == ROW_LINEAGE_LAST_UPDATED_SEQ_NUMBER) {
964
2
        return TableVirtualColumnType::LAST_UPDATED_SEQUENCE_NUMBER;
965
2
    }
966
160
    return TableVirtualColumnType::INVALID;
967
162
}
968
969
static TableVirtualColumnType row_lineage_virtual_column_type_by_field_id(
970
76
        const ColumnDefinition& column) {
971
76
    if (!column.has_identifier_field_id()) {
972
5
        return TableVirtualColumnType::INVALID;
973
5
    }
974
71
    switch (column.get_identifier_field_id()) {
975
10
    case ROW_LINEAGE_ROW_ID_FIELD_ID:
976
10
        return TableVirtualColumnType::ROW_ID;
977
9
    case ROW_LINEAGE_LAST_UPDATED_SEQ_NUMBER_FIELD_ID:
978
9
        return TableVirtualColumnType::LAST_UPDATED_SEQUENCE_NUMBER;
979
52
    default:
980
52
        return TableVirtualColumnType::INVALID;
981
71
    }
982
71
}
983
984
static TableVirtualColumnType row_lineage_virtual_column_type(const ColumnDefinition& column,
985
240
                                                              TableColumnMappingMode mode) {
986
240
    switch (mode) {
987
76
    case TableColumnMappingMode::BY_FIELD_ID:
988
76
        return row_lineage_virtual_column_type_by_field_id(column);
989
142
    case TableColumnMappingMode::BY_NAME:
990
164
    case TableColumnMappingMode::BY_INDEX:
991
164
        return row_lineage_virtual_column_type(column.name);
992
240
    }
993
0
    return TableVirtualColumnType::INVALID;
994
240
}
995
996
// Returns true when the current file type is not the exact nested type the scan should expose.
997
// This is about building the projected file-side type/projection, not about whether TableReader
998
// later needs to rematerialize the complex value back to table layout.
999
105
static bool needs_projected_file_type_rebuild(const ColumnMapping& mapping) {
1000
105
    if (!is_complex_type(mapping.file_type->get_primitive_type())) {
1001
26
        return false;
1002
26
    }
1003
79
    if (mapping.child_mappings.empty()) {
1004
0
        return false;
1005
0
    }
1006
79
    DORIS_CHECK(mapping.file_type != nullptr);
1007
79
    DORIS_CHECK(mapping.table_type != nullptr);
1008
79
    if (remove_nullable(mapping.file_type)->get_primitive_type() !=
1009
79
        remove_nullable(mapping.table_type)->get_primitive_type()) {
1010
0
        return true;
1011
0
    }
1012
79
    if (!mapping.table_type->equals(*mapping.file_type)) {
1013
62
        return true;
1014
62
    }
1015
30
    for (const auto& child_mapping : mapping.child_mappings) {
1016
        // Rename-only child mappings do not change the file-side projected shape. If field-id
1017
        // matching maps table child `renamed_b` to file child `b`, the file reader can still expose
1018
        // the original file type as long as child count/order/types are unchanged.
1019
30
        if (!child_mapping.file_local_id.has_value() ||
1020
30
            needs_projected_file_type_rebuild(child_mapping)) {
1021
1
            return true;
1022
1
        }
1023
30
    }
1024
16
    return false;
1025
17
}
1026
1027
static std::optional<size_t> file_child_ordinal_in_scan_type(const ColumnMapping& mapping,
1028
76
                                                             const ColumnMapping& child_mapping) {
1029
76
    if (!child_mapping.file_local_id.has_value()) {
1030
1
        return std::nullopt;
1031
1
    }
1032
75
    const auto& file_children = !mapping.projected_file_children.empty()
1033
75
                                        ? mapping.projected_file_children
1034
75
                                        : mapping.original_file_children;
1035
90
    const auto child_it = std::ranges::find_if(file_children, [&](const ColumnDefinition& child) {
1036
90
        return child.file_local_id() == *child_mapping.file_local_id;
1037
90
    });
1038
75
    if (child_it == file_children.end()) {
1039
0
        return std::nullopt;
1040
0
    }
1041
75
    return static_cast<size_t>(std::distance(file_children.begin(), child_it));
1042
75
}
1043
1044
386
static bool needs_complex_rematerialize(const ColumnMapping& mapping) {
1045
386
    if (mapping.child_mappings.empty()) {
1046
296
        return false;
1047
296
    }
1048
90
    if (mapping.table_type == nullptr || mapping.file_type == nullptr ||
1049
90
        !mapping.table_type->equals(*mapping.file_type)) {
1050
25
        return true;
1051
25
    }
1052
133
    for (size_t table_child_idx = 0; table_child_idx < mapping.child_mappings.size();
1053
76
         ++table_child_idx) {
1054
76
        const auto& child_mapping = mapping.child_mappings[table_child_idx];
1055
76
        const auto file_child_idx = file_child_ordinal_in_scan_type(mapping, child_mapping);
1056
76
        if (!file_child_idx.has_value() || *file_child_idx != table_child_idx ||
1057
76
            needs_complex_rematerialize(child_mapping) ||
1058
76
            (child_mapping.table_type != nullptr && child_mapping.file_type != nullptr &&
1059
68
             !child_mapping.table_type->equals(*child_mapping.file_type))) {
1060
8
            return true;
1061
8
        }
1062
76
    }
1063
57
    return false;
1064
65
}
1065
1066
408
static bool mapping_can_use_file_column_directly(const ColumnMapping& mapping) {
1067
408
    if (mapping.table_type == nullptr || mapping.file_type == nullptr) {
1068
0
        return false;
1069
0
    }
1070
408
    const auto table_type = remove_nullable(mapping.table_type);
1071
408
    const auto file_type = remove_nullable(mapping.file_type);
1072
408
    const bool same_timestamptz_with_different_scale =
1073
408
            table_type->get_primitive_type() == TYPE_TIMESTAMPTZ &&
1074
408
            file_type->get_primitive_type() == TYPE_TIMESTAMPTZ;
1075
408
    if (!mapping.table_type->equals(*mapping.file_type) && !same_timestamptz_with_different_scale) {
1076
138
        return false;
1077
138
    }
1078
270
    return !needs_complex_rematerialize(mapping);
1079
408
}
1080
1081
static const ColumnDefinition* find_file_child_for_mapping(const ColumnDefinition& table_child,
1082
                                                           const ColumnDefinition& file_parent,
1083
                                                           TableColumnMappingMode mode,
1084
                                                           size_t table_child_idx,
1085
119
                                                           bool allow_ordinal_fallback) {
1086
119
    const auto file_parent_type = remove_nullable(file_parent.type)->get_primitive_type();
1087
119
    switch (file_parent_type) {
1088
10
    case TYPE_ARRAY:
1089
10
        DORIS_CHECK(file_parent.children.size() == 1);
1090
10
        return &file_parent.children[0];
1091
19
    case TYPE_MAP:
1092
19
        DORIS_CHECK(file_parent.children.size() == 2);
1093
19
        if (table_child.name == "key") {
1094
6
            return &file_parent.children[0];
1095
6
        }
1096
13
        if (table_child.name == "value") {
1097
13
            return &file_parent.children[1];
1098
13
        }
1099
0
        if (table_child.local_id == 0 || table_child.local_id == 1) {
1100
0
            return &file_parent.children[table_child.local_id];
1101
0
        }
1102
0
        return nullptr;
1103
90
    default:
1104
        // Hive BY_INDEX is a top-level column matching rule. Once a complex root is selected by
1105
        // file position, nested struct children follow Hive reader's historical name matching
1106
        // semantics; their integer identifiers can be field ids, not file positions.
1107
90
        const auto nested_mode =
1108
90
                mode == TableColumnMappingMode::BY_INDEX ? TableColumnMappingMode::BY_NAME : mode;
1109
90
        if (const auto* file_child =
1110
90
                    matcher_for_mode(nested_mode).find(table_child, file_parent.children);
1111
90
            file_child != nullptr) {
1112
71
            return file_child;
1113
71
        }
1114
19
        if (allow_ordinal_fallback && mode == TableColumnMappingMode::BY_FIELD_ID &&
1115
19
            !table_child.has_identifier_field_id()) {
1116
            // Synthetic children are derived from the table DataType when nested ColumnDefinition
1117
            // metadata has been pruned away. They do not carry Iceberg field ids, so try a name
1118
            // match before falling back to ordinal order. Example:
1119
            //   table value type: Struct(age, full_name, gender)
1120
            //   old file value:   Struct(name, age)
1121
            // Name matching keeps `age -> age`; the later unused-child fallback can then map the
1122
            // renamed `full_name -> name` instead of consuming `age` twice.
1123
3
            if (const auto* file_child = NameMatcher().find(table_child, file_parent.children);
1124
3
                file_child != nullptr) {
1125
1
                return file_child;
1126
1
            }
1127
3
        }
1128
        // Some callers only carry the full complex DataType for a projected table column, without
1129
        // expanded nested ColumnDefinitions. In that case we can still preserve full materialization
1130
        // by walking table/file struct fields by ordinal. This is a fallback only: explicit
1131
        // ColumnDefinition children keep using the requested table-format matching rule, which is
1132
        // required for precise schema evolution.
1133
18
        if (allow_ordinal_fallback && table_child_idx < file_parent.children.size()) {
1134
3
            return &file_parent.children[table_child_idx];
1135
3
        }
1136
15
        return nullptr;
1137
119
    }
1138
119
}
1139
1140
static ColumnDefinition synthetic_child_definition(const std::string& name, DataTypePtr type,
1141
13
                                                   int32_t local_id) {
1142
13
    ColumnDefinition child;
1143
13
    child.identifier = Field::create_field<TYPE_STRING>(name);
1144
13
    child.local_id = local_id;
1145
13
    child.name = name;
1146
13
    child.type = std::move(type);
1147
13
    return child;
1148
13
}
1149
1150
static std::vector<ColumnDefinition> synthesize_complex_children_from_type(
1151
4
        const DataTypePtr& type) {
1152
4
    std::vector<ColumnDefinition> children;
1153
4
    if (type == nullptr) {
1154
0
        return children;
1155
0
    }
1156
4
    const auto nested_type = remove_nullable(type);
1157
4
    switch (nested_type->get_primitive_type()) {
1158
0
    case TYPE_ARRAY: {
1159
0
        const auto* array_type = assert_cast<const DataTypeArray*>(nested_type.get());
1160
0
        children.push_back(synthetic_child_definition("element", array_type->get_nested_type(), 0));
1161
0
        break;
1162
0
    }
1163
1
    case TYPE_MAP: {
1164
1
        const auto* map_type = assert_cast<const DataTypeMap*>(nested_type.get());
1165
1
        children.push_back(synthetic_child_definition("key", map_type->get_key_type(), 0));
1166
1
        children.push_back(synthetic_child_definition("value", map_type->get_value_type(), 1));
1167
1
        break;
1168
0
    }
1169
3
    case TYPE_STRUCT: {
1170
3
        const auto* struct_type = assert_cast<const DataTypeStruct*>(nested_type.get());
1171
3
        children.reserve(struct_type->get_elements().size());
1172
12
        for (size_t idx = 0; idx < struct_type->get_elements().size(); ++idx) {
1173
9
            children.push_back(synthetic_child_definition(struct_type->get_element_name(idx),
1174
9
                                                          struct_type->get_element(idx),
1175
9
                                                          cast_set<int32_t>(idx)));
1176
9
        }
1177
3
        break;
1178
0
    }
1179
0
    default:
1180
0
        break;
1181
4
    }
1182
4
    return children;
1183
4
}
1184
1185
static bool has_table_child_named(const std::vector<ColumnDefinition>& children,
1186
15
                                  std::string_view name) {
1187
17
    return std::ranges::any_of(children, [&](const ColumnDefinition& child) {
1188
17
        return std::string_view(child.name) == name;
1189
17
    });
1190
15
}
1191
1192
static void complete_required_complex_children_from_type(const DataTypePtr& type,
1193
58
                                                         std::vector<ColumnDefinition>* children) {
1194
58
    DORIS_CHECK(children != nullptr);
1195
58
    if (type == nullptr) {
1196
0
        return;
1197
0
    }
1198
58
    const auto nested_type = remove_nullable(type);
1199
58
    switch (nested_type->get_primitive_type()) {
1200
11
    case TYPE_MAP: {
1201
11
        const auto* map_type = assert_cast<const DataTypeMap*>(nested_type.get());
1202
        // MAP key/value are structural children, not independently materializable table fields.
1203
        // A key-only projection can still be attached to a whole-map output root, for example:
1204
        //   SELECT * FROM t WHERE ARRAY_CONTAINS(MAP_KEYS(new_map_column), 'person5')
1205
        //
1206
        // In that shape the scanner keeps the value stream readable, but the table projection can
1207
        // carry only the key child. Add the missing value child so recursive mapping can evolve the
1208
        // value type instead of letting TableReader cast old/new value structs directly.
1209
11
        if (has_table_child_named(*children, "key") && !has_table_child_named(*children, "value")) {
1210
2
            children->push_back(synthetic_child_definition("value", map_type->get_value_type(), 1));
1211
2
        }
1212
11
        break;
1213
0
    }
1214
9
    case TYPE_ARRAY:
1215
        // ARRAY has only one required structural child (`element`), so a non-empty projection is
1216
        // already rooted at the element path.
1217
9
        break;
1218
38
    case TYPE_STRUCT:
1219
        // STRUCT children are real fields and must remain prunable. Completing missing struct
1220
        // fields here would turn `SELECT s.a` into a full-struct read and undo nested projection.
1221
38
        break;
1222
0
    default:
1223
0
        break;
1224
58
    }
1225
58
}
1226
1227
77
static Status validate_file_schema_children(const ColumnDefinition& file_field) {
1228
77
    if (file_field.type == nullptr) {
1229
0
        return Status::InternalError("File column '{}' has null type", file_field.name);
1230
0
    }
1231
77
    const auto nested_type = remove_nullable(file_field.type);
1232
77
    size_t expected_children = 0;
1233
77
    bool complex_with_fixed_children = true;
1234
77
    switch (nested_type->get_primitive_type()) {
1235
10
    case TYPE_ARRAY:
1236
10
        expected_children = 1;
1237
10
        break;
1238
13
    case TYPE_MAP:
1239
13
        expected_children = 2;
1240
13
        break;
1241
54
    case TYPE_STRUCT:
1242
54
        expected_children =
1243
54
                assert_cast<const DataTypeStruct*>(nested_type.get())->get_elements().size();
1244
54
        break;
1245
0
    default:
1246
0
        complex_with_fixed_children = false;
1247
0
        break;
1248
77
    }
1249
77
    if (!complex_with_fixed_children || file_field.children.size() == expected_children) {
1250
76
        return Status::OK();
1251
76
    }
1252
1
    return Status::InternalError(
1253
1
            "Malformed complex file schema for column '{}': type={}, expected_children={}, "
1254
1
            "actual_children={}",
1255
1
            file_field.name, file_field.type->get_name(), expected_children,
1256
1
            file_field.children.size());
1257
77
}
1258
1259
190
static bool has_projected_file_children(const ColumnMapping& mapping) {
1260
190
    if (mapping.original_file_children.empty() || mapping.projected_file_children.empty()) {
1261
143
        return false;
1262
143
    }
1263
47
    if (mapping.original_file_children.size() != mapping.projected_file_children.size()) {
1264
21
        return true;
1265
21
    }
1266
67
    for (size_t idx = 0; idx < mapping.original_file_children.size(); ++idx) {
1267
41
        if (mapping.original_file_children[idx].file_local_id() !=
1268
41
            mapping.projected_file_children[idx].file_local_id()) {
1269
0
            return true;
1270
0
        }
1271
41
    }
1272
26
    return false;
1273
26
}
1274
1275
190
static bool needs_nested_file_projection(const ColumnMapping& mapping) {
1276
190
    if (has_projected_file_children(mapping)) {
1277
        // Return True if the projected child column is missing / re-ordered
1278
21
        return true;
1279
21
    }
1280
169
    return std::ranges::any_of(mapping.child_mappings, [](const ColumnMapping& child_mapping) {
1281
41
        return needs_nested_file_projection(child_mapping);
1282
41
    });
1283
190
}
1284
1285
static Status build_complex_projection(const ColumnMapping& mapping, LocalColumnIndex* projection);
1286
1287
// Build the projected file children/type according to the pruned complex projection. For example,
1288
// if we have a struct column `s` with children `id` and `name`, and the projection only keeps
1289
// `s.name`, then the file reader should expose `STRUCT<name ...>`.
1290
static Status rebuild_projected_file_children_and_type(
1291
        const DataTypePtr& file_type, const std::vector<ColumnDefinition>& original_file_children,
1292
        const std::vector<ColumnMapping>& child_mappings,
1293
63
        std::vector<ColumnDefinition>* projected_file_children, DataTypePtr* projected_type) {
1294
63
    DORIS_CHECK(file_type != nullptr);
1295
63
    DORIS_CHECK(projected_file_children != nullptr);
1296
63
    DORIS_CHECK(projected_type != nullptr);
1297
63
    ColumnDefinition field;
1298
63
    field.type = file_type;
1299
63
    field.children = original_file_children;
1300
63
    LocalColumnIndex projection = LocalColumnIndex::partial_local(-1);
1301
63
    projection.children.reserve(child_mappings.size());
1302
81
    for (const auto* child_mapping : present_child_mappings_in_file_order(child_mappings)) {
1303
81
        DORIS_CHECK(child_mapping->file_local_id.has_value());
1304
81
        LocalColumnIndex child_projection;
1305
81
        RETURN_IF_ERROR(build_complex_projection(*child_mapping, &child_projection));
1306
81
        projection.children.push_back(std::move(child_projection));
1307
81
    }
1308
1309
63
    ColumnDefinition projected_field;
1310
63
    RETURN_IF_ERROR(project_column_definition(field, projection, &projected_field));
1311
63
    *projected_file_children = std::move(projected_field.children);
1312
63
    *projected_type = std::move(projected_field.type);
1313
63
    return Status::OK();
1314
63
}
1315
1316
// Build the complex column projection according to the ColumnMapping which is re-ordered by the
1317
// file-schema's order.
1318
//
1319
// For MAP, a partial projection represents value-subtree pruning only. The key child is not a
1320
// projected output shape; file readers still read full keys to construct ColumnMap offsets and keep
1321
// key semantics unchanged. If a caller tries to project only/prune the key child, the common schema
1322
// projection helper rejects it.
1323
161
static Status build_complex_projection(const ColumnMapping& mapping, LocalColumnIndex* projection) {
1324
161
    if (projection == nullptr) {
1325
0
        return Status::InvalidArgument("projection is null");
1326
0
    }
1327
161
    DORIS_CHECK(mapping.file_local_id.has_value());
1328
161
    *projection = LocalColumnIndex::local(*mapping.file_local_id);
1329
161
    projection->project_all_children = mapping.child_mappings.empty();
1330
161
    projection->children.clear();
1331
161
    const auto present_children = present_child_mappings_in_file_order(mapping.child_mappings);
1332
161
    if (!projection->project_all_children && present_children.empty()) {
1333
        // All requested table children under this complex node are missing/default-only. The file
1334
        // reader cannot expose an empty complex projection, but TableReader can still rematerialize
1335
        // the table shape from a full file subtree and fill the missing children with defaults.
1336
4
        projection->project_all_children = true;
1337
4
        return Status::OK();
1338
4
    }
1339
157
    for (const auto* child_mapping : present_children) {
1340
59
        LocalColumnIndex child_projection;
1341
59
        RETURN_IF_ERROR(build_complex_projection(*child_mapping, &child_projection));
1342
59
        projection->children.push_back(std::move(child_projection));
1343
59
    }
1344
157
    if (!projection->project_all_children && projection->children.empty()) {
1345
0
        return Status::NotSupported("Projection for complex column {} contains no file children",
1346
0
                                    mapping.file_column_name);
1347
0
    }
1348
157
    return Status::OK();
1349
157
}
1350
1351
using FilterProjectionMap = std::map<LocalColumnId, LocalColumnIndex>;
1352
1353
// Update the mapping's file type according to the projection, and determine whether the projection
1354
// is trivial (i.e. the projected file type is the same as the table type, so no need to
1355
// rematerialize the complex value back to table layout after reading from file).
1356
static Status apply_projection_to_mapping_file_type(const LocalColumnIndex& projection,
1357
154
                                                    ColumnMapping* mapping) {
1358
154
    DORIS_CHECK(mapping != nullptr);
1359
154
    if (mapping->original_file_type == nullptr) {
1360
0
        mapping->original_file_type = mapping->file_type;
1361
0
    }
1362
154
    if (mapping->original_file_type == nullptr ||
1363
154
        !is_complex_type(remove_nullable(mapping->original_file_type)->get_primitive_type())) {
1364
110
        return Status::OK();
1365
110
    }
1366
44
    ColumnDefinition field;
1367
44
    field.type = mapping->original_file_type;
1368
44
    field.children = mapping->original_file_children;
1369
44
    ColumnDefinition projected_field;
1370
44
    RETURN_IF_ERROR(project_column_definition(field, projection, &projected_field));
1371
44
    mapping->file_type = std::move(projected_field.type);
1372
44
    mapping->projected_file_children = std::move(projected_field.children);
1373
44
    mapping->is_trivial = mapping_can_use_file_column_directly(*mapping);
1374
44
    return Status::OK();
1375
44
}
1376
1377
static Status merge_filter_projection(const FilterProjectionMap* filter_projections,
1378
71
                                      LocalColumnIndex* projection) {
1379
71
    DORIS_CHECK(projection != nullptr);
1380
71
    if (filter_projections == nullptr) {
1381
0
        return Status::OK();
1382
0
    }
1383
71
    const auto filter_projection_it = filter_projections->find(projection->column_id());
1384
71
    if (filter_projection_it == filter_projections->end()) {
1385
56
        return Status::OK();
1386
56
    }
1387
    // Merge predicate-only nested paths into the root projection that is about to be scanned.
1388
    // Example: `SELECT s.a WHERE s.b > 1` first builds the output projection `s -> a` from
1389
    // ColumnMapping, while build_nested_struct_filter_projection_map() records `s -> b`. This merge
1390
    // produces one file scan projection `s -> a,b`.
1391
15
    RETURN_IF_ERROR(merge_local_column_index(projection, filter_projection_it->second));
1392
15
    return Status::OK();
1393
15
}
1394
1395
2
static bool table_root_is_map(const ColumnMapping& mapping) {
1396
2
    if (mapping.table_type == nullptr) {
1397
0
        return false;
1398
0
    }
1399
2
    return remove_nullable(mapping.table_type)->get_primitive_type() == TYPE_MAP;
1400
2
}
1401
1402
static Status add_scan_column(FileScanRequest* file_request, ColumnMapping* mapping,
1403
                              bool is_predicate_column, bool force_full_complex_scan_projection,
1404
156
                              const FilterProjectionMap* filter_projections = nullptr) {
1405
156
    const auto file_column_id = LocalColumnId(mapping->file_local_id.value());
1406
156
    LocalColumnIndex projection = LocalColumnIndex::top_level(file_column_id);
1407
    // Columnar readers can turn a complex mapping into a nested file projection, but
1408
    // row-oriented readers must scan the full top-level complex field because all children are
1409
    // encoded in the same text cell.
1410
156
    if (!force_full_complex_scan_projection && needs_nested_file_projection(*mapping)) {
1411
21
        RETURN_IF_ERROR(build_complex_projection(*mapping, &projection));
1412
21
    }
1413
156
    if (is_predicate_column && !force_full_complex_scan_projection) {
1414
71
        DCHECK(filter_projections != nullptr);
1415
        // If a projected complex root is also used by a predicate, rebuild the predicate scan
1416
        // projection from the output mapping before merging predicate-only children. For
1417
        // `SELECT s.a WHERE s.b > 1`, build_complex_projection() produces `s -> a` and
1418
        // merge_filter_projection() adds `s -> b`, so the predicate column reads both children.
1419
71
        RETURN_IF_ERROR(merge_filter_projection(filter_projections, &projection));
1420
71
    }
1421
156
    FileScanRequestBuilder builder(file_request);
1422
156
    if (is_predicate_column) {
1423
71
        return builder.add_predicate_column(std::move(projection));
1424
71
    }
1425
85
    return builder.add_non_predicate_column(std::move(projection));
1426
156
}
1427
1428
static const LocalColumnIndex* find_scan_projection(
1429
238
        const std::vector<LocalColumnIndex>& scan_columns, LocalColumnId file_column_id) {
1430
238
    const auto projection_it =
1431
238
            std::ranges::find_if(scan_columns, [&](const LocalColumnIndex& projection) {
1432
193
                return projection.column_id() == file_column_id;
1433
193
            });
1434
238
    return projection_it == scan_columns.end() ? nullptr : &*projection_it;
1435
238
}
1436
1437
// Apply the final scan projection of one root file column back to its ColumnMapping. This updates
1438
// mapping.file_type/projected_file_children from the original file schema to the exact shape that
1439
// FileReader will return.
1440
//
1441
// Example: for `SELECT s.a WHERE s.b > 1`, add_scan_column() keeps only one predicate scan
1442
// projection `s -> a,b`. Applying that projection changes the mapping's file type from the full
1443
// file struct `s<a,b,c>` to the projected file struct `s<a,b>`, so later filter rewrite and
1444
// TableReader final materialization use the same column shape as the file-local block.
1445
static Status apply_scan_projection_to_mapping_file_type(const FileScanRequest& file_request,
1446
154
                                                         ColumnMapping* mapping) {
1447
154
    DORIS_CHECK(mapping != nullptr);
1448
154
    DORIS_CHECK(mapping->file_local_id.has_value());
1449
154
    const auto file_column_id = LocalColumnId(*mapping->file_local_id);
1450
    // Predicate columns are the actual scan projection when a column is used by row-level filters:
1451
    // add_scan_column() removes the duplicate non-predicate projection in that case.
1452
154
    const auto* projection = find_scan_projection(file_request.predicate_columns, file_column_id);
1453
154
    if (projection == nullptr) {
1454
84
        projection = find_scan_projection(file_request.non_predicate_columns, file_column_id);
1455
84
    }
1456
154
    DORIS_CHECK(projection != nullptr);
1457
154
    return apply_projection_to_mapping_file_type(*projection, mapping);
1458
154
}
1459
1460
// Build extra scan projections required only by row-level filters on nested struct children.
1461
//
1462
// Example: for `SELECT s.a FROM t WHERE s.b.c > 1`, the output projection may only contain `s.a`,
1463
// but the file reader must also read `s.b.c` to evaluate the predicate. This function collects the
1464
// table-side filter path, resolves it through ColumnMapping first, and records the corresponding
1465
// file-side projection in filter_projections. This keeps renamed fields consistent between the scan
1466
// projection and row-level conjunct rewrite. Example:
1467
//   table filter path: s -> renamed_b -> c
1468
//   old file path:     s -> b -> c
1469
//   recorded path:     s -> b -> c
1470
// When add_scan_column() adds the same root as a predicate column, it rebuilds that root from the
1471
// output mapping, merges this filter-only projection into it, and removes the duplicate
1472
// non-predicate root entry.
1473
static Status build_nested_struct_filter_projection_map(
1474
        const std::vector<TableFilter>& table_filters, const std::vector<ColumnMapping>& mappings,
1475
137
        FilterProjectionMap* filter_projections) {
1476
137
    DORIS_CHECK(filter_projections != nullptr);
1477
137
    filter_projections->clear();
1478
137
    for (const auto& table_filter : table_filters) {
1479
84
        if (table_filter.conjunct == nullptr) {
1480
2
            continue;
1481
2
        }
1482
        // Collect all nested struct paths in the table filter. For example, for
1483
        // `s.id > 5 AND element_at(s, 'renamed_name') = 'abc'`, collect the table paths
1484
        // `s -> id` and `s -> renamed_name`, then resolve each one to its file-side projection.
1485
82
        std::vector<NestedStructPath> paths;
1486
82
        collect_nested_struct_paths(table_filter.conjunct->root(), &paths);
1487
82
        for (const auto& path : paths) {
1488
23
            auto mapping_it = std::ranges::find_if(mappings, [&](const ColumnMapping& mapping) {
1489
23
                return mapping.global_index == path.root_global_index;
1490
23
            });
1491
22
            if (mapping_it == mappings.end() || !mapping_it->file_local_id.has_value() ||
1492
22
                path.selectors.empty()) {
1493
0
                continue;
1494
0
            }
1495
1496
22
            ResolvedNestedStructPath resolved;
1497
22
            LocalColumnIndex root_projection;
1498
22
            if (!resolve_nested_struct_path_for_file(path, mappings, &resolved)) {
1499
2
                if (!table_root_is_map(*mapping_it)) {
1500
1
                    continue;
1501
1
                }
1502
                // Direct map value filters such as `m.value.a > 1` need the value leaf for row
1503
                // evaluation even when the query only projects another value child. This is only a
1504
                // scan projection fallback; complex map/array expressions are still not rewritten
1505
                // into file-local conjuncts.
1506
1
                LocalColumnIndex child_projection;
1507
1
                RETURN_IF_ERROR(build_file_child_projection_from_schema(
1508
1
                        mapping_it->original_file_children, path.selectors, &child_projection));
1509
1
                if (child_projection.local_id() < 0) {
1510
0
                    continue;
1511
0
                }
1512
1
                root_projection = LocalColumnIndex::partial_local(*mapping_it->file_local_id);
1513
1
                root_projection.children.push_back(std::move(child_projection));
1514
20
            } else {
1515
20
                root_projection = std::move(resolved.file_projection);
1516
20
            }
1517
21
            auto filter_projection_it = filter_projections->find(root_projection.column_id());
1518
21
            if (filter_projection_it == filter_projections->end()) {
1519
17
                filter_projections->emplace(root_projection.column_id(),
1520
17
                                            std::move(root_projection));
1521
17
                continue;
1522
17
            }
1523
4
            RETURN_IF_ERROR(
1524
4
                    merge_local_column_index(&filter_projection_it->second, root_projection));
1525
4
        }
1526
82
    }
1527
137
    return Status::OK();
1528
137
}
1529
1530
146
static void rebuild_projection(ColumnMapping* mapping, LocalIndex block_position) {
1531
146
    DORIS_CHECK(mapping->file_local_id.has_value());
1532
146
    if (mapping->is_trivial || needs_complex_rematerialize(*mapping)) {
1533
127
        mapping->projection = VExprContext::create_shared(VSlotRef::create_shared(
1534
127
                cast_set<int>(block_position.value()), cast_set<int>(block_position.value()), -1,
1535
127
                mapping->file_type, mapping->file_column_name));
1536
127
        return;
1537
127
    }
1538
1539
19
    auto expr = Cast::create_shared(mapping->table_type);
1540
19
    expr->add_child(VSlotRef::create_shared(cast_set<int>(block_position.value()),
1541
19
                                            cast_set<int>(block_position.value()), -1,
1542
19
                                            mapping->file_type, mapping->file_column_name));
1543
19
    mapping->projection = VExprContext::create_shared(expr);
1544
19
}
1545
1546
// Build file slot rewrite info from the localized filter targets. Only local targets can enter
1547
// file-reader expressions; constant and unset targets stay above the file reader.
1548
static std::map<GlobalIndex, FileSlotRewriteInfo> build_file_slot_rewrite_map(
1549
        const std::vector<ColumnMapping>& mappings,
1550
137
        const std::map<GlobalIndex, FilterEntry>& filter_entries) {
1551
137
    std::map<GlobalIndex, FileSlotRewriteInfo> global_to_file_slot;
1552
179
    for (const auto& mapping : mappings) {
1553
179
        const auto entry_it = filter_entries.find(mapping.global_index);
1554
179
        if (entry_it == filter_entries.end() || !entry_it->second.is_local()) {
1555
35
            continue;
1556
35
        }
1557
144
        DORIS_CHECK(mapping.file_local_id.has_value());
1558
144
        global_to_file_slot.emplace(
1559
144
                mapping.global_index,
1560
144
                FileSlotRewriteInfo {.block_position = entry_it->second.local_index().value(),
1561
144
                                     .file_type = mapping.file_type,
1562
144
                                     .table_type = mapping.table_type,
1563
144
                                     .file_column_name = mapping.file_column_name});
1564
144
    }
1565
137
    return global_to_file_slot;
1566
137
}
1567
1568
Status TableColumnMapper::_create_by_index_mapping(const ColumnDefinition& table_column,
1569
                                                   const std::vector<ColumnDefinition>& file_schema,
1570
19
                                                   ColumnMapping* mapping) {
1571
19
    DORIS_CHECK(mapping != nullptr);
1572
19
    DORIS_CHECK(!table_column.is_partition_key);
1573
1574
    // Key contract: in BY_INDEX mode, `ColumnDefinition::identifier` TYPE_INT is interpreted as the
1575
    // 0-based position of this column inside `file_schema`. FE writes the physical file position
1576
    // of each non-partition projected column into that identifier. This interpretation allows:
1577
    //   - sparse projection: read only a subset of file columns (for example only `_col2`
1578
    //     and `_col4`);
1579
    //   - column reordering: table column order differs from file column order;
1580
    //   - no many-to-one mapping: FE must guarantee that each file position is referenced by at
1581
    //     most one table column.
1582
19
    const auto file_index = table_column.get_identifier_position();
1583
1584
    // Case A: file_index is in range, so build a direct positional mapping.
1585
    // The file column name (for example `_col0`) is intentionally ignored here.
1586
19
    if (file_index >= 0 && static_cast<size_t>(file_index) < file_schema.size()) {
1587
16
        return _create_direct_mapping(table_column, file_schema[static_cast<size_t>(file_index)],
1588
16
                                      mapping);
1589
16
    }
1590
1591
    // Case B: file_index is out of range, which means the file does not contain this column.
1592
    // Route it through the missing-column path used by schema evolution.
1593
3
    if (table_column.default_expr != nullptr) {
1594
1
        _set_constant_mapping(mapping, table_column.default_expr);
1595
1
        return Status::OK();
1596
1
    }
1597
    // Keep the mapping empty (`file_local_id` remains `nullopt`) and let the upper finalize
1598
    // stage fill NULL/default values.
1599
2
    return Status::OK();
1600
3
}
1601
1602
19
void TableColumnMapper::_set_constant_mapping(ColumnMapping* mapping, VExprContextSPtr expr) {
1603
19
    DORIS_CHECK(mapping != nullptr);
1604
19
    DORIS_CHECK(expr != nullptr);
1605
19
    mapping->default_expr = std::move(expr);
1606
19
    mapping->constant_index = _constant_map.add(ConstantEntry {
1607
19
            .global_index = mapping->global_index,
1608
19
            .expr = mapping->default_expr,
1609
19
            .type = mapping->table_type,
1610
19
    });
1611
19
    mapping->filter_conversion = FilterConversionType::CONSTANT;
1612
19
}
1613
1614
Status TableColumnMapper::_create_mapping_for_column(const ColumnDefinition& table_column,
1615
                                                     GlobalIndex global_index,
1616
240
                                                     ColumnMapping* mapping) {
1617
240
    DORIS_CHECK(mapping != nullptr);
1618
240
    *mapping = ColumnMapping {};
1619
240
    mapping->global_index = global_index;
1620
240
    mapping->table_column_name = table_column.name;
1621
240
    mapping->table_type = table_column.type;
1622
240
    const auto row_lineage_type = row_lineage_virtual_column_type(table_column, _options.mode);
1623
240
    if (const auto* partition_value = find_partition_value(table_column, _partition_values);
1624
240
        table_column.is_partition_key && partition_value != nullptr) {
1625
        // Partition values are split constants and must take precedence over defaults.
1626
12
        _set_constant_mapping(mapping, VExprContext::create_shared(VLiteral::create_shared(
1627
12
                                               mapping->table_type, *partition_value)));
1628
228
    } else if (_options.mode == TableColumnMappingMode::BY_INDEX &&
1629
228
               !table_column.is_partition_key && table_column.has_identifier_field_id()) {
1630
        // BY_INDEX interprets ColumnDefinition::identifier as physical file position.
1631
19
        RETURN_IF_ERROR(_create_by_index_mapping(table_column, _file_schema, mapping));
1632
209
    } else if (const auto* file_field = _find_file_field(table_column, _file_schema)) {
1633
        // Normal physical file column mapping.
1634
179
        RETURN_IF_ERROR(_create_direct_mapping(table_column, *file_field, mapping));
1635
178
        if (row_lineage_type != TableVirtualColumnType::INVALID) {
1636
            // Iceberg v3 rewritten files may physically contain row lineage metadata fields.
1637
            // File non-null values must be preserved, while file NULLs still inherit from data file
1638
            // metadata in IcebergTableReader. Therefore the mapping has a real file source plus a
1639
            // virtual post-materialization step, and filters must wait for finalize output.
1640
10
            mapping->virtual_column_type = row_lineage_type;
1641
10
            mapping->filter_conversion = FilterConversionType::FINALIZE_ONLY;
1642
10
        }
1643
178
    } else if (row_lineage_type != TableVirtualColumnType::INVALID) {
1644
        // Iceberg row lineage metadata fields are optional in data files. Missing fields are exposed
1645
        // as all-NULL table columns first; IcebergTableReader fills inherited values only when the
1646
        // split carries first_row_id / last_updated_sequence_number metadata.
1647
        // FE may attach a default_expr to these hidden metadata columns, but the Iceberg v3
1648
        // inheritance rule must take precedence over the generic missing-column default path.
1649
13
        mapping->virtual_column_type = row_lineage_type;
1650
17
    } else if (table_column.name == BeConsts::ICEBERG_ROWID_COL) {
1651
        // Doris internal Iceberg row locator is never a physical Iceberg data column. It is built
1652
        // from file path, row position and partition metadata for delete/update/merge.
1653
2
        mapping->virtual_column_type = TableVirtualColumnType::ICEBERG_ROWID;
1654
15
    } else if (table_column.default_expr != nullptr) {
1655
        // Missing schema-evolution column with an explicit default expression.
1656
6
        _set_constant_mapping(mapping, table_column.default_expr);
1657
9
    } else {
1658
9
        if (table_column.is_partition_key) {
1659
0
            return Status::InvalidArgument(
1660
0
                    "Table column '{}' (global_index={}) does not have a matching partition value",
1661
0
                    table_column.name, mapping->global_index.value());
1662
0
        }
1663
9
    }
1664
239
    return Status::OK();
1665
240
}
1666
1667
Status TableColumnMapper::_create_hidden_filter_mapping(const ColumnDefinition& table_column,
1668
                                                        GlobalIndex global_index,
1669
2
                                                        ColumnMapping* mapping) {
1670
2
    auto status = _create_mapping_for_column(table_column, global_index, mapping);
1671
2
    if (mapping->file_local_id.has_value() || mapping->constant_index.has_value() ||
1672
2
        mapping->virtual_column_type != TableVirtualColumnType::INVALID) {
1673
0
        return Status::OK();
1674
0
    }
1675
2
    if (_options.mode == TableColumnMappingMode::BY_NAME) {
1676
0
        return status;
1677
0
    }
1678
1679
    // Predicate-only slot refs carry the table name/type but do not carry the table-format field
1680
    // id used by BY_FIELD_ID or the file position used by BY_INDEX. Use a name fallback only for
1681
    // hidden filter localization; projected columns still obey the requested mapping mode.
1682
2
    const auto* file_field =
1683
2
            matcher_for_mode(TableColumnMappingMode::BY_NAME).find(table_column, _file_schema);
1684
2
    if (file_field == nullptr) {
1685
0
        return status;
1686
0
    }
1687
2
    ColumnMapping fallback_mapping;
1688
2
    fallback_mapping.global_index = global_index;
1689
2
    fallback_mapping.table_column_name = table_column.name;
1690
2
    fallback_mapping.table_type = table_column.type;
1691
2
    RETURN_IF_ERROR(_create_direct_mapping(table_column, *file_field, &fallback_mapping));
1692
2
    *mapping = std::move(fallback_mapping);
1693
2
    return Status::OK();
1694
2
}
1695
1696
Status TableColumnMapper::_build_hidden_filter_mappings(
1697
131
        const std::vector<TableFilter>& table_filters) {
1698
131
    _hidden_mappings.clear();
1699
1700
131
    std::map<GlobalIndex, ColumnDefinition> filter_columns;
1701
131
    for (const auto& table_filter : table_filters) {
1702
78
        if (table_filter.conjunct != nullptr) {
1703
76
            collect_top_level_slot_columns(table_filter.conjunct->root(), &filter_columns);
1704
76
        }
1705
78
    }
1706
1707
131
    for (const auto& [global_index, table_column] : filter_columns) {
1708
76
        if (_find_mapping(global_index) != nullptr) {
1709
            // Ignore columns that are already mapped by the projected columns
1710
74
            continue;
1711
74
        }
1712
2
        ColumnMapping mapping;
1713
2
        RETURN_IF_ERROR(_create_hidden_filter_mapping(table_column, global_index, &mapping));
1714
2
        if (mapping.file_local_id.has_value() || mapping.constant_index.has_value() ||
1715
2
            mapping.virtual_column_type != TableVirtualColumnType::INVALID) {
1716
2
            _hidden_mappings.push_back(std::move(mapping));
1717
2
        }
1718
2
    }
1719
131
    return Status::OK();
1720
131
}
1721
1722
Status TableColumnMapper::create_mapping(const std::vector<ColumnDefinition>& projected_columns,
1723
                                         const std::map<std::string, Field>& partition_values,
1724
169
                                         const std::vector<ColumnDefinition>& file_schema) {
1725
169
    clear();
1726
169
    _partition_values = partition_values;
1727
169
    _file_schema = file_schema;
1728
406
    for (size_t column_idx = 0; column_idx < projected_columns.size(); ++column_idx) {
1729
238
        ColumnMapping mapping;
1730
238
        RETURN_IF_ERROR(_create_mapping_for_column(projected_columns[column_idx],
1731
238
                                                   GlobalIndex(column_idx), &mapping));
1732
237
        _mappings.push_back(std::move(mapping));
1733
237
    }
1734
168
    return Status::OK();
1735
169
}
1736
1737
411
std::vector<ColumnMapping> TableColumnMapper::_filter_visible_mappings() const {
1738
411
    std::vector<ColumnMapping> mappings;
1739
411
    mappings.reserve(_mappings.size() + _hidden_mappings.size());
1740
411
    mappings.insert(mappings.end(), _mappings.begin(), _mappings.end());
1741
411
    mappings.insert(mappings.end(), _hidden_mappings.begin(), _hidden_mappings.end());
1742
411
    return mappings;
1743
411
}
1744
1745
137
Status TableColumnMapper::_build_filter_entries(const FileScanRequest& file_request) {
1746
137
    _filter_entries.clear();
1747
137
    const auto mappings = _filter_visible_mappings();
1748
179
    for (const auto& mapping : mappings) {
1749
179
        FilterEntry entry;
1750
179
        if (mapping.constant_index.has_value()) {
1751
12
            entry = FilterEntry::constant(*mapping.constant_index);
1752
167
        } else if (mapping.file_local_id.has_value() &&
1753
167
                   filter_conversion_has_local_source(mapping.filter_conversion)) {
1754
144
            const auto local_position_it =
1755
144
                    file_request.local_positions.find(LocalColumnId(*mapping.file_local_id));
1756
144
            if (local_position_it != file_request.local_positions.end()) {
1757
144
                entry = FilterEntry::local(local_position_it->second);
1758
144
            }
1759
144
        }
1760
179
        _filter_entries.emplace(mapping.global_index, entry);
1761
179
    }
1762
137
    return Status::OK();
1763
137
}
1764
1765
Status TableColumnMapper::create_scan_request(
1766
        const std::vector<TableFilter>& table_filters,
1767
        const std::vector<ColumnDefinition>& projected_columns, FileScanRequest* file_request,
1768
131
        RuntimeState* runtime_state) {
1769
    // FileReader evaluates expressions against a file-local block. This mapper owns the
1770
    // table-column to file-column conversion, so it also owns the file-local block positions.
1771
131
    file_request->predicate_columns.clear();
1772
131
    file_request->non_predicate_columns.clear();
1773
131
    file_request->local_positions.clear();
1774
131
    file_request->conjuncts.clear();
1775
131
    file_request->delete_conjuncts.clear();
1776
131
    _filter_entries.clear();
1777
    // 1. Build referenced non-predicate columns
1778
301
    for (size_t column_idx = 0; column_idx < projected_columns.size(); ++column_idx) {
1779
170
        const auto global_index = GlobalIndex(column_idx);
1780
170
        auto* mapping = _find_mapping(global_index);
1781
170
        if (mapping != nullptr && mapping->file_local_id.has_value()) {
1782
            // A file column can be read lazily as a non-predicate column only when it is not used
1783
            // by row-level expression filters.
1784
146
            bool used_by_filter = false;
1785
146
            for (const auto& table_filter : table_filters) {
1786
91
                const auto& global_indices = table_filter.global_indices;
1787
91
                if (std::find(global_indices.begin(), global_indices.end(), global_index) !=
1788
91
                            global_indices.end() &&
1789
91
                    filter_conversion_has_local_source(mapping->filter_conversion)) {
1790
65
                    used_by_filter = true;
1791
65
                    break;
1792
65
                }
1793
91
            }
1794
146
            if (!used_by_filter || !enable_lazy_materialization()) {
1795
83
                RETURN_IF_ERROR(add_scan_column(file_request, mapping, false,
1796
83
                                                force_full_complex_scan_projection()));
1797
83
            }
1798
146
        }
1799
170
    }
1800
    // 2. Build referenced predicate columns
1801
    // 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.
1802
131
    RETURN_IF_ERROR(_build_hidden_filter_mappings(table_filters));
1803
131
    RETURN_IF_ERROR(localize_filters(table_filters, file_request, runtime_state));
1804
    // 3. Rebuild output projection expressions for projected columns. localize_filters() has
1805
    // already applied the final scan projection to mapping.file_type/projected_file_children before
1806
    // rewriting filter expressions.
1807
170
    for (auto& mapping : _mappings) {
1808
170
        if (!mapping.file_local_id.has_value()) {
1809
24
            continue;
1810
24
        }
1811
146
        auto position_it =
1812
146
                file_request->local_positions.find(LocalColumnId(*mapping.file_local_id));
1813
146
        DORIS_CHECK(position_it != file_request->local_positions.end())
1814
0
                << file_request->local_positions.size() << " " << *mapping.file_local_id << " "
1815
0
                << mapping.file_column_name;
1816
146
        rebuild_projection(&mapping, position_it->second);
1817
146
    }
1818
131
    return Status::OK();
1819
131
}
1820
1821
333
ColumnMapping* TableColumnMapper::_find_mapping(GlobalIndex global_index) {
1822
425
    for (auto& mapping : _mappings) {
1823
425
        if (mapping.global_index == global_index) {
1824
329
            return &mapping;
1825
329
        }
1826
425
    }
1827
4
    return nullptr;
1828
333
}
1829
1830
87
ColumnMapping* TableColumnMapper::_find_filter_mapping(GlobalIndex global_index) {
1831
87
    if (auto* mapping = _find_mapping(global_index); mapping != nullptr) {
1832
85
        return mapping;
1833
85
    }
1834
2
    for (auto& mapping : _hidden_mappings) {
1835
2
        if (mapping.global_index == global_index) {
1836
2
            return &mapping;
1837
2
        }
1838
2
    }
1839
0
    return nullptr;
1840
2
}
1841
1842
Status TableColumnMapper::localize_filters(const std::vector<TableFilter>& table_filters,
1843
                                           FileScanRequest* file_request,
1844
137
                                           RuntimeState* runtime_state) {
1845
137
    FilterProjectionMap filter_projections;
1846
137
    auto filter_mappings = _filter_visible_mappings();
1847
137
    RETURN_IF_ERROR(build_nested_struct_filter_projection_map(table_filters, filter_mappings,
1848
137
                                                              &filter_projections));
1849
137
    for (const auto& table_filter : table_filters) {
1850
87
        for (const auto& global_index : table_filter.global_indices) {
1851
87
            auto* mapping = _find_filter_mapping(global_index);
1852
87
            if (mapping == nullptr || !mapping->file_local_id.has_value() ||
1853
87
                !filter_conversion_has_local_source(mapping->filter_conversion)) {
1854
14
                continue;
1855
14
            }
1856
73
            RETURN_IF_ERROR(add_scan_column(file_request, mapping, enable_lazy_materialization(),
1857
73
                                            force_full_complex_scan_projection(),
1858
73
                                            &filter_projections));
1859
73
        }
1860
84
    }
1861
    // Rebuild the file type for every scan-local mapping before expression rewrite. Predicate-only
1862
    // hidden mappings must see the same projected file type as the file reader will produce.
1863
177
    for (auto& mapping : _mappings) {
1864
177
        if (mapping.file_local_id.has_value() &&
1865
177
            file_request->local_positions.contains(LocalColumnId(*mapping.file_local_id))) {
1866
152
            RETURN_IF_ERROR(apply_scan_projection_to_mapping_file_type(*file_request, &mapping));
1867
152
        }
1868
177
    }
1869
137
    for (auto& mapping : _hidden_mappings) {
1870
2
        if (mapping.file_local_id.has_value() &&
1871
2
            file_request->local_positions.contains(LocalColumnId(*mapping.file_local_id))) {
1872
2
            RETURN_IF_ERROR(apply_scan_projection_to_mapping_file_type(*file_request, &mapping));
1873
2
        }
1874
2
    }
1875
137
    RETURN_IF_ERROR(_build_filter_entries(*file_request));
1876
1877
    // Build the complete table-slot rewrite map after all predicate columns have been assigned.
1878
    // This keeps expression localization independent from filter iteration order.
1879
137
    filter_mappings = _filter_visible_mappings();
1880
137
    const auto global_to_file_slot = build_file_slot_rewrite_map(filter_mappings, _filter_entries);
1881
137
    for (const auto& table_filter : table_filters) {
1882
84
        if (table_filter.conjunct != nullptr &&
1883
84
            table_filter_has_only_local_entries(table_filter, _filter_entries)) {
1884
68
            RewriteContext rewrite_context {.runtime_state = runtime_state};
1885
68
            VExprSPtr rewrite_root;
1886
68
            Status clone_status;
1887
68
            try {
1888
68
                clone_status = clone_table_expr_tree(table_filter.conjunct->root(), &rewrite_root);
1889
68
            } catch ([[maybe_unused]] const Exception& e) {
1890
                // Some table filters contain complex intermediate values, for example
1891
                // `element_at(MAP_VALUES(m)[1], 'age') > 30`. The current file-local rewrite only
1892
                // understands top-level slots and struct-element paths rooted at top-level slots;
1893
                // cloning such expressions can hit the generic TExpr complex-type limitation.
1894
                // Leave them above TableReader, where Scanner evaluates the original table-level
1895
                // conjunct after final materialization.
1896
0
#ifndef NDEBUG
1897
0
                return Status::InternalError(
1898
0
                        "Failed to clone table filter for file-local rewrite: {}, expr={}",
1899
0
                        e.to_string(), table_filter.conjunct->root()->debug_string());
1900
#else
1901
                continue;
1902
#endif
1903
0
            } catch ([[maybe_unused]] const std::exception& e) {
1904
0
#ifndef NDEBUG
1905
0
                return Status::InternalError(
1906
0
                        "Failed to clone table filter for file-local rewrite: {}, expr={}",
1907
0
                        e.what(), table_filter.conjunct->root()->debug_string());
1908
#else
1909
                continue;
1910
#endif
1911
0
            }
1912
68
            if (!clone_status.ok()) {
1913
0
#ifndef NDEBUG
1914
0
                return Status::InternalError(
1915
0
                        "Failed to clone table filter for file-local rewrite: {}, expr={}",
1916
0
                        clone_status.to_string(), table_filter.conjunct->root()->debug_string());
1917
#else
1918
                continue;
1919
#endif
1920
0
            }
1921
68
            bool can_localize = true;
1922
68
            auto localized_root = rewrite_table_expr_to_file_expr(rewrite_root, global_to_file_slot,
1923
68
                                                                  filter_mappings, &rewrite_context,
1924
68
                                                                  &can_localize);
1925
68
            if (!can_localize) {
1926
5
                continue;
1927
5
            }
1928
63
            auto localized_conjunct = VExprContext::create_shared(std::move(localized_root));
1929
63
            RETURN_IF_ERROR(rewrite_context.prepare_created_exprs(localized_conjunct.get()));
1930
63
            file_request->conjuncts.push_back(std::move(localized_conjunct));
1931
63
        }
1932
84
    }
1933
137
    return Status::OK();
1934
137
}
1935
1936
const ColumnDefinition* TableColumnMapper::_find_file_field(
1937
        const ColumnDefinition& table_column,
1938
209
        const std::vector<ColumnDefinition>& file_schema) const {
1939
209
    if (table_column.name.starts_with(BeConsts::GLOBAL_ROWID_COL)) {
1940
2
        const auto field_it = std::ranges::find_if(file_schema, [](const ColumnDefinition& field) {
1941
2
            return field.column_type == ColumnType::GLOBAL_ROWID;
1942
2
        });
1943
1
        return field_it == file_schema.end() ? nullptr : &*field_it;
1944
1
    }
1945
208
    return matcher_for_mode(_options.mode).find(table_column, file_schema);
1946
209
}
1947
1948
Status TableColumnMapper::_create_direct_mapping(const ColumnDefinition& table_column,
1949
                                                 const ColumnDefinition& file_field,
1950
301
                                                 ColumnMapping* mapping) const {
1951
301
    DORIS_CHECK(mapping != nullptr);
1952
301
    DORIS_CHECK(file_field.local_id >= 0 || file_field.local_id == GLOBAL_ROWID_COLUMN_ID);
1953
301
    mapping->file_local_id = file_field.local_id;
1954
301
    mapping->table_column_name = table_column.name;
1955
301
    mapping->file_column_name = file_field.name;
1956
301
    mapping->original_file_type = file_field.type;
1957
301
    mapping->original_file_children = file_field.children;
1958
301
    mapping->projected_file_children = file_field.children;
1959
301
    mapping->file_type = file_field.type;
1960
301
    mapping->is_trivial = mapping_can_use_file_column_directly(*mapping);
1961
301
    mapping->filter_conversion = mapping->is_trivial ? FilterConversionType::COPY_DIRECTLY
1962
301
                                                     : FilterConversionType::CAST_FILTER;
1963
301
    mapping->child_mappings.clear();
1964
1965
301
    auto table_children = table_column.children;
1966
301
    const auto nested_table_type = remove_nullable(mapping->table_type);
1967
    // Some scan paths, especially SELECT *, only carry the complete complex DataType for a table
1968
    // column and leave ColumnDefinition::children empty. If the file type is an older complex
1969
    // schema, treating this as a leaf mapping would make TableReader fall back to a plain CAST.
1970
    // That is invalid for evolved structs with different field counts.
1971
    //
1972
    // Example:
1973
    //   table column type: Map(String, Struct(age, full_name, gender))
1974
    //   old file type:    Map(String, Struct(age, name))
1975
    //   table children:   empty
1976
    //
1977
    // Synthesize key/value/struct-field children from the table type so the normal recursive
1978
    // mapping path can rematerialize `name -> full_name` and fill missing `gender` with defaults,
1979
    // instead of trying to CAST Struct(age, name) to Struct(age, full_name, gender).
1980
301
    const bool synthesized_table_children =
1981
301
            table_children.empty() && is_complex_type(nested_table_type->get_primitive_type()) &&
1982
301
            !mapping->table_type->equals(*mapping->file_type);
1983
301
    if (synthesized_table_children) {
1984
4
        table_children = synthesize_complex_children_from_type(mapping->table_type);
1985
297
    } else if (!table_children.empty() && !mapping->table_type->equals(*mapping->file_type)) {
1986
58
        complete_required_complex_children_from_type(mapping->table_type, &table_children);
1987
58
    }
1988
1989
301
    if (!table_children.empty()) {
1990
77
        if (!is_complex_type(remove_nullable(mapping->file_type)->get_primitive_type())) {
1991
0
            return Status::NotSupported(
1992
0
                    "Cannot map complex table column '{}' to scalar parquet column '{}', table "
1993
0
                    "type={}, file type={}",
1994
0
                    table_column.name, file_field.name, mapping->table_type->get_name(),
1995
0
                    mapping->file_type->get_name());
1996
0
        }
1997
77
        RETURN_IF_ERROR(validate_file_schema_children(file_field));
1998
76
        std::vector<int32_t> synthesized_used_file_child_ids;
1999
195
        for (size_t table_child_idx = 0; table_child_idx < table_children.size();
2000
119
             ++table_child_idx) {
2001
119
            const auto& table_child = table_children[table_child_idx];
2002
119
            const auto* file_child =
2003
119
                    find_file_child_for_mapping(table_child, file_field, _options.mode,
2004
119
                                                table_child_idx, synthesized_table_children);
2005
119
            if (synthesized_table_children && file_child != nullptr) {
2006
8
                const auto file_child_id = file_child->file_local_id();
2007
8
                if (std::ranges::find(synthesized_used_file_child_ids, file_child_id) !=
2008
8
                    synthesized_used_file_child_ids.end()) {
2009
2
                    file_child = nullptr;
2010
2
                    for (const auto& candidate : file_field.children) {
2011
2
                        const auto candidate_id = candidate.file_local_id();
2012
2
                        if (std::ranges::find(synthesized_used_file_child_ids, candidate_id) ==
2013
2
                            synthesized_used_file_child_ids.end()) {
2014
2
                            file_child = &candidate;
2015
2
                            break;
2016
2
                        }
2017
2
                    }
2018
2
                }
2019
8
                if (file_child != nullptr) {
2020
8
                    synthesized_used_file_child_ids.push_back(file_child->file_local_id());
2021
8
                }
2022
8
            }
2023
119
            if (file_child == nullptr) {
2024
15
                ColumnMapping child_mapping;
2025
15
                child_mapping.table_column_name = table_child.name;
2026
15
                child_mapping.file_column_name = table_child.name;
2027
15
                child_mapping.table_type = table_child.type;
2028
15
                child_mapping.file_type = table_child.type;
2029
15
                child_mapping.filter_conversion = FilterConversionType::FINALIZE_ONLY;
2030
15
                mapping->child_mappings.push_back(std::move(child_mapping));
2031
15
                continue;
2032
15
            }
2033
104
            ColumnMapping child_mapping;
2034
104
            child_mapping.table_column_name = table_child.name;
2035
104
            child_mapping.table_type = table_child.type;
2036
104
            RETURN_IF_ERROR(_create_direct_mapping(table_child, *file_child, &child_mapping));
2037
104
            mapping->child_mappings.push_back(std::move(child_mapping));
2038
104
        }
2039
76
        if (needs_projected_file_type_rebuild(*mapping)) {
2040
            // 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.
2041
63
            RETURN_IF_ERROR(rebuild_projected_file_children_and_type(
2042
63
                    mapping->file_type, mapping->original_file_children, mapping->child_mappings,
2043
63
                    &mapping->projected_file_children, &mapping->file_type));
2044
63
            DCHECK(mapping->table_type != nullptr);
2045
63
            mapping->is_trivial = mapping_can_use_file_column_directly(*mapping);
2046
            // TODO: ? READER_EXPRESSION
2047
63
            mapping->filter_conversion = mapping->is_trivial
2048
63
                                                 ? FilterConversionType::COPY_DIRECTLY
2049
63
                                                 : FilterConversionType::READER_EXPRESSION;
2050
63
        }
2051
76
    }
2052
300
    return Status::OK();
2053
301
}
2054
2055
} // namespace doris::format