Coverage Report

Created: 2026-07-14 17:43

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