Coverage Report

Created: 2026-07-17 15:05

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