Coverage Report

Created: 2026-07-17 04:10

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
12.8M
bool column_has_name(const ColumnDefinition& column, const std::string& name) {
73
12.8M
    if (to_lower(column.name) == to_lower(name)) {
74
298k
        return true;
75
298k
    }
76
12.6M
    if (column.has_identifier_name() && to_lower(column.get_identifier_name()) == to_lower(name)) {
77
0
        return true;
78
0
    }
79
12.5M
    return std::ranges::any_of(column.name_mapping, [&](const std::string& alias) {
80
146
        return to_lower(alias) == to_lower(name);
81
146
    });
82
12.5M
}
83
84
6.71M
bool column_names_match(const ColumnDefinition& lhs, const ColumnDefinition& rhs) {
85
6.71M
    if (column_has_name(rhs, lhs.name)) {
86
298k
        return true;
87
298k
    }
88
6.41M
    if (lhs.has_identifier_name() && column_has_name(rhs, lhs.get_identifier_name())) {
89
1
        return true;
90
1
    }
91
6.41M
    return std::ranges::any_of(lhs.name_mapping, [&](const std::string& alias) {
92
25
        return column_has_name(rhs, alias);
93
25
    });
94
6.41M
}
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
112k
                                 const std::vector<ColumnDefinition>& file_schema) const override {
108
112k
        if (!table_column.has_identifier_field_id()) {
109
7
            return nullptr;
110
7
        }
111
112k
        const auto field_id = table_column.get_identifier_field_id();
112
763k
        const auto field_it = std::ranges::find_if(file_schema, [&](const ColumnDefinition& field) {
113
763k
            return field.has_identifier_field_id() && field.get_identifier_field_id() == field_id;
114
763k
        });
115
112k
        return field_it == file_schema.end() ? nullptr : &*field_it;
116
112k
    }
117
};
118
119
class NameMatcher final : public ColumnMatcher {
120
public:
121
    const ColumnDefinition* find(const ColumnDefinition& table_column,
122
299k
                                 const std::vector<ColumnDefinition>& file_schema) const override {
123
6.71M
        const auto field_it = std::ranges::find_if(file_schema, [&](const ColumnDefinition& field) {
124
6.71M
            return column_names_match(table_column, field);
125
6.71M
        });
126
299k
        return field_it == file_schema.end() ? nullptr : &*field_it;
127
299k
    }
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
411k
const ColumnMatcher& matcher_for_mode(TableColumnMappingMode mode) {
146
411k
    static const FieldIdMatcher field_id_matcher;
147
411k
    static const NameMatcher name_matcher;
148
411k
    static const PositionMatcher position_matcher;
149
411k
    switch (mode) {
150
112k
    case TableColumnMappingMode::BY_FIELD_ID:
151
112k
        return field_id_matcher;
152
299k
    case TableColumnMappingMode::BY_NAME:
153
299k
        return name_matcher;
154
2
    case TableColumnMappingMode::BY_INDEX:
155
2
        return position_matcher;
156
411k
    }
157
0
    return field_id_matcher;
158
411k
}
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
397k
                                  const std::map<std::string, Field>& partition_values) {
241
654k
    const auto find_by_name = [&](const std::string& name) -> const Field* {
242
654k
        const auto value_it = partition_values.find(name);
243
654k
        return value_it == partition_values.end() ? nullptr : &value_it->second;
244
654k
    };
245
397k
    if (const auto* value = find_by_name(table_column.name); value != nullptr) {
246
18.3k
        return value;
247
18.3k
    }
248
378k
    if (table_column.has_identifier_name()) {
249
258k
        if (const auto* value = find_by_name(table_column.get_identifier_name());
250
258k
            value != nullptr) {
251
0
            return value;
252
0
        }
253
258k
    }
254
378k
    for (const auto& alias : table_column.name_mapping) {
255
23
        if (const auto* value = find_by_name(alias); value != nullptr) {
256
1
            return value;
257
1
        }
258
23
    }
259
378k
    return nullptr;
260
378k
}
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
50.0k
    void add_created_expr(VExprSPtr expr) { created_exprs.push_back(std::move(expr)); }
274
275
32.7k
    Status prepare_created_exprs(VExprContext* context) const {
276
32.7k
        DORIS_CHECK(context != nullptr);
277
32.7k
        RowDescriptor row_desc;
278
49.3k
        for (const auto& expr : created_exprs) {
279
49.3k
            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
49.3k
            RETURN_IF_ERROR(expr->prepare(runtime_state, row_desc, context));
285
49.3k
        }
286
32.7k
        return Status::OK();
287
32.7k
    }
288
};
289
290
static VExprSPtr create_file_slot_ref(const VSlotRef& slot_ref,
291
                                      const FileSlotRewriteInfo& rewrite_info,
292
34.0k
                                      RewriteContext* rewrite_context) {
293
34.0k
    auto ref =
294
34.0k
            VSlotRef::create_shared(slot_ref.slot_id(), cast_set<int>(rewrite_info.block_position),
295
34.0k
                                    -1, rewrite_info.file_type, rewrite_info.file_column_name);
296
34.0k
    rewrite_context->add_created_expr(ref);
297
34.0k
    return ref;
298
34.0k
}
299
300
93.5k
static bool is_cast_expr(const VExprSPtr& expr) {
301
93.5k
    return dynamic_cast<const Cast*>(expr.get()) != nullptr;
302
93.5k
}
303
304
79.1k
static bool is_binary_comparison_predicate(const VExprSPtr& expr) {
305
79.1k
    if (expr == nullptr || expr->get_num_children() != 2 ||
306
79.1k
        (expr->node_type() != TExprNodeType::BINARY_PRED &&
307
62.0k
         expr->node_type() != TExprNodeType::NULL_AWARE_BINARY_PRED)) {
308
62.0k
        return false;
309
62.0k
    }
310
17.0k
    switch (expr->op()) {
311
7.85k
    case TExprOpcode::EQ:
312
7.85k
    case TExprOpcode::EQ_FOR_NULL:
313
9.16k
    case TExprOpcode::NE:
314
11.2k
    case TExprOpcode::GE:
315
14.2k
    case TExprOpcode::GT:
316
15.9k
    case TExprOpcode::LE:
317
17.0k
    case TExprOpcode::LT:
318
17.0k
        return true;
319
0
    default:
320
0
        return false;
321
17.0k
    }
322
17.0k
}
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
25.0k
        const VSlotRef** slot_ref) {
401
25.0k
    if (expr == nullptr) {
402
0
        return nullptr;
403
0
    }
404
25.0k
    VExprSPtr slot_expr = expr;
405
25.0k
    const bool input_is_cast = is_cast_expr(expr) && expr->get_num_children() == 1;
406
25.0k
    if (is_cast_expr(expr) && expr->get_num_children() == 1) {
407
462
        slot_expr = expr->children()[0];
408
462
    }
409
25.0k
    if (!slot_expr->is_slot_ref()) {
410
12.0k
        return nullptr;
411
12.0k
    }
412
13.0k
    const auto* candidate_slot_ref = assert_cast<const VSlotRef*>(slot_expr.get());
413
13.0k
    const auto rewrite_it = global_to_file_slot.find(slot_ref_global_index(*candidate_slot_ref));
414
13.0k
    if (rewrite_it == global_to_file_slot.end()) {
415
0
        return nullptr;
416
0
    }
417
13.0k
    if (input_is_cast && !expr->data_type()->equals(*rewrite_it->second.table_type)) {
418
426
        return nullptr;
419
426
    }
420
12.5k
    if (slot_ref != nullptr) {
421
12.5k
        *slot_ref = candidate_slot_ref;
422
12.5k
    }
423
12.5k
    return &rewrite_it->second;
424
13.0k
}
425
426
470k
static bool filter_conversion_has_local_source(FilterConversionType conversion) {
427
470k
    switch (conversion) {
428
432k
    case FilterConversionType::COPY_DIRECTLY:
429
455k
    case FilterConversionType::CAST_FILTER:
430
469k
    case FilterConversionType::READER_EXPRESSION:
431
469k
        return true;
432
1.03k
    case FilterConversionType::FINALIZE_ONLY:
433
1.03k
    case FilterConversionType::CONSTANT:
434
1.03k
        return false;
435
470k
    }
436
0
    return false;
437
470k
}
438
439
static bool table_filter_has_only_local_entries(
440
39.9k
        const TableFilter& table_filter, const std::map<GlobalIndex, FilterEntry>& filter_entries) {
441
40.7k
    for (const auto global_index : table_filter.global_indices) {
442
40.7k
        const auto entry_it = filter_entries.find(global_index);
443
40.7k
        if (entry_it == filter_entries.end() || !entry_it->second.is_local()) {
444
4.90k
            return false;
445
4.90k
        }
446
40.7k
    }
447
35.0k
    return true;
448
39.9k
}
449
450
static VExprSPtr unwrap_literal_for_file_cast(const VExprSPtr& expr,
451
15.1k
                                              const DataTypePtr& table_type) {
452
15.1k
    if (expr == nullptr) {
453
0
        return nullptr;
454
0
    }
455
15.1k
    if (expr->is_literal()) {
456
15.1k
        return expr;
457
15.1k
    }
458
10
    if (is_cast_expr(expr) && expr->get_num_children() == 1 && expr->children()[0]->is_literal() &&
459
10
        expr->children()[0]->data_type()->equals(*table_type)) {
460
0
        return expr->children()[0];
461
0
    }
462
10
    return nullptr;
463
10
}
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
544k
static Status clone_table_expr_node(const VExpr& expr, VExprSPtr* cloned_expr) {
478
544k
    DORIS_CHECK(cloned_expr != nullptr);
479
544k
    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
544k
    } else if (const auto* vcast_expr = dynamic_cast<const VCastExpr*>(&expr);
484
544k
               vcast_expr != nullptr && vcast_expr->node_type() == TExprNodeType::CAST_EXPR) {
485
6.81k
        *cloned_expr = Cast::create_shared(vcast_expr->data_type());
486
6.81k
    }
487
544k
    return Status::OK();
488
544k
}
489
490
180k
Status clone_table_expr_tree(const VExprSPtr& expr, VExprSPtr* cloned_expr) {
491
180k
    DORIS_CHECK(cloned_expr != nullptr);
492
180k
    if (expr == nullptr) {
493
0
        *cloned_expr = nullptr;
494
0
        return Status::OK();
495
0
    }
496
180k
    return expr->deep_clone(cloned_expr, clone_table_expr_node);
497
180k
}
498
499
static VExprSPtr original_table_literal(const VExprSPtr& literal_expr,
500
16.2k
                                        RewriteContext* rewrite_context = nullptr) {
501
16.2k
    DORIS_CHECK(literal_expr != nullptr);
502
16.2k
    DORIS_CHECK(literal_expr->is_literal());
503
16.2k
    const auto* rewritten_literal = dynamic_cast<const SplitLocalFileLiteral*>(literal_expr.get());
504
16.2k
    if (rewritten_literal == nullptr) {
505
16.2k
        return literal_expr;
506
16.2k
    }
507
0
    auto literal = VLiteral::create_shared(rewritten_literal->original_type(),
508
0
                                           rewritten_literal->original_field());
509
0
    if (rewrite_context != nullptr) {
510
0
        rewrite_context->add_created_expr(literal);
511
0
    }
512
0
    return literal;
513
16.2k
}
514
515
41.1k
static ColumnDefinition hidden_column_from_slot_ref(const VSlotRef& slot_ref) {
516
41.1k
    ColumnDefinition column;
517
41.1k
    column.name = slot_ref.column_name();
518
41.1k
    column.identifier = Field::create_field<TYPE_STRING>(column.name);
519
41.1k
    column.type = slot_ref.data_type();
520
41.1k
    return column;
521
41.1k
}
522
523
static void collect_top_level_slot_columns(const VExprSPtr& expr,
524
129k
                                           std::map<GlobalIndex, ColumnDefinition>* columns) {
525
129k
    DORIS_CHECK(columns != nullptr);
526
129k
    if (expr == nullptr) {
527
0
        return;
528
0
    }
529
129k
    if (expr->is_slot_ref()) {
530
41.1k
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr.get());
531
41.1k
        columns->try_emplace(slot_ref_global_index(*slot_ref),
532
41.1k
                             hidden_column_from_slot_ref(*slot_ref));
533
41.1k
        return;
534
41.1k
    }
535
89.9k
    for (const auto& child : expr->children()) {
536
89.9k
        collect_top_level_slot_columns(child, columns);
537
89.9k
    }
538
88.6k
}
539
540
230
static std::optional<uint8_t> signed_integer_width(PrimitiveType type) {
541
230
    switch (type) {
542
0
    case TYPE_TINYINT:
543
0
        return 8;
544
4
    case TYPE_SMALLINT:
545
4
        return 16;
546
60
    case TYPE_INT:
547
60
        return 32;
548
39
    case TYPE_BIGINT:
549
39
        return 64;
550
0
    case TYPE_LARGEINT:
551
0
        return 128;
552
127
    default:
553
127
        return std::nullopt;
554
230
    }
555
230
}
556
557
111
static std::optional<uint8_t> floating_width(PrimitiveType type) {
558
111
    switch (type) {
559
0
    case TYPE_FLOAT:
560
0
        return 32;
561
1
    case TYPE_DOUBLE:
562
1
        return 64;
563
110
    default:
564
110
        return std::nullopt;
565
111
    }
566
111
}
567
568
17
static std::optional<uint8_t> floating_exact_integer_width(PrimitiveType type) {
569
17
    switch (type) {
570
0
    case TYPE_FLOAT:
571
0
        return 24;
572
3
    case TYPE_DOUBLE:
573
3
        return 53;
574
14
    default:
575
14
        return std::nullopt;
576
17
    }
577
17
}
578
579
static bool is_lossless_file_to_table_numeric_cast(const DataTypePtr& file_type,
580
12.3k
                                                   const DataTypePtr& table_type) {
581
12.3k
    const auto file_nested_type = remove_nullable(file_type);
582
12.3k
    const auto table_nested_type = remove_nullable(table_type);
583
12.3k
    if (file_nested_type->equals(*table_nested_type)) {
584
12.1k
        return true;
585
12.1k
    }
586
587
170
    const auto file_primitive_type = file_nested_type->get_primitive_type();
588
170
    const auto table_primitive_type = table_nested_type->get_primitive_type();
589
170
    if (const auto file_width = signed_integer_width(file_primitive_type)) {
590
60
        if (const auto table_width = signed_integer_width(table_primitive_type)) {
591
43
            return *table_width >= *file_width;
592
43
        }
593
17
        if (const auto table_width = floating_exact_integer_width(table_primitive_type)) {
594
3
            return *table_width >= *file_width;
595
3
        }
596
14
        return false;
597
17
    }
598
110
    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
109
    return false;
603
110
}
604
605
static VExprSPtr rewrite_literal_to_file_type(const VExprSPtr& literal_expr,
606
                                              const FileSlotRewriteInfo& rewrite_info,
607
15.0k
                                              RewriteContext* rewrite_context) {
608
15.0k
    DORIS_CHECK(literal_expr != nullptr);
609
15.0k
    DORIS_CHECK(literal_expr->is_literal());
610
15.0k
    const auto original_literal = original_table_literal(literal_expr, rewrite_context);
611
15.0k
    const Field original_field = literal_field(original_literal);
612
15.0k
    if (rewrite_info.file_type->equals(*original_literal->data_type())) {
613
2.72k
        return original_literal;
614
2.72k
    }
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
12.3k
    if (!is_lossless_file_to_table_numeric_cast(rewrite_info.file_type,
622
12.3k
                                                original_literal->data_type())) {
623
148
        return nullptr;
624
148
    }
625
12.1k
    Field file_field;
626
12.1k
    try {
627
12.1k
        convert_field_to_type(original_field, *rewrite_info.file_type, &file_field,
628
12.1k
                              original_literal->data_type().get());
629
12.1k
    } catch (const Exception&) {
630
0
        return nullptr;
631
0
    }
632
12.1k
    if (file_field.is_null()) {
633
0
        return nullptr;
634
0
    }
635
12.1k
    if (file_field.get_type() != remove_nullable(rewrite_info.file_type)->get_primitive_type()) {
636
38
        return nullptr;
637
38
    }
638
12.1k
    Field round_trip_field;
639
12.1k
    try {
640
12.1k
        convert_field_to_type(file_field, *original_literal->data_type(), &round_trip_field,
641
12.1k
                              rewrite_info.file_type.get());
642
12.1k
    } catch (const Exception&) {
643
968
        return nullptr;
644
968
    }
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
11.1k
    if (round_trip_field != original_field) {
648
2
        return nullptr;
649
2
    }
650
11.1k
    auto literal = std::make_shared<SplitLocalFileLiteral>(
651
11.1k
            rewrite_info.file_type, file_field, original_literal->data_type(), original_field);
652
11.1k
    rewrite_context->add_created_expr(literal);
653
11.1k
    return literal;
654
11.1k
}
655
656
static bool rewrite_binary_slot_literal_predicate(
657
        const VExprSPtr& expr,
658
        const std::map<GlobalIndex, FileSlotRewriteInfo>& global_to_file_slot,
659
79.1k
        RewriteContext* rewrite_context) {
660
79.1k
    if (!is_binary_comparison_predicate(expr)) {
661
62.0k
        return false;
662
62.0k
    }
663
17.1k
    auto children = expr->children();
664
17.1k
    const VSlotRef* slot_ref = nullptr;
665
17.1k
    const FileSlotRewriteInfo* rewrite_info =
666
17.1k
            find_slot_rewrite_info(children[0], global_to_file_slot, &slot_ref);
667
17.1k
    int slot_child_idx = 0;
668
17.1k
    int literal_child_idx = 1;
669
17.1k
    if (rewrite_info == nullptr) {
670
6.20k
        rewrite_info = find_slot_rewrite_info(children[1], global_to_file_slot, &slot_ref);
671
6.20k
        slot_child_idx = 1;
672
6.20k
        literal_child_idx = 0;
673
6.20k
    }
674
17.1k
    if (rewrite_info == nullptr || slot_ref == nullptr) {
675
6.20k
        return false;
676
6.20k
    }
677
10.8k
    auto literal_expr =
678
10.8k
            unwrap_literal_for_file_cast(children[literal_child_idx], rewrite_info->table_type);
679
10.8k
    if (literal_expr == nullptr) {
680
12
        return false;
681
12
    }
682
683
10.8k
    auto rewritten_literal =
684
10.8k
            rewrite_literal_to_file_type(literal_expr, *rewrite_info, rewrite_context);
685
10.8k
    if (rewritten_literal == nullptr) {
686
1.10k
        children[literal_child_idx] = original_table_literal(literal_expr, rewrite_context);
687
1.10k
        expr->set_children(std::move(children));
688
1.10k
        return false;
689
1.10k
    }
690
691
9.77k
    children[slot_child_idx] = create_file_slot_ref(*slot_ref, *rewrite_info, rewrite_context);
692
9.77k
    children[literal_child_idx] = std::move(rewritten_literal);
693
9.77k
    expr->set_children(std::move(children));
694
9.77k
    return true;
695
10.8k
}
696
697
static bool rewrite_in_slot_literal_predicate(
698
        const VExprSPtr& expr,
699
        const std::map<GlobalIndex, FileSlotRewriteInfo>& global_to_file_slot,
700
69.3k
        RewriteContext* rewrite_context) {
701
69.3k
    if (expr->node_type() != TExprNodeType::IN_PRED || expr->get_num_children() < 2) {
702
67.6k
        return false;
703
67.6k
    }
704
1.77k
    auto children = expr->children();
705
1.77k
    const VSlotRef* slot_ref = nullptr;
706
1.77k
    const FileSlotRewriteInfo* rewrite_info =
707
1.77k
            find_slot_rewrite_info(children[0], global_to_file_slot, &slot_ref);
708
1.77k
    if (rewrite_info == nullptr || slot_ref == nullptr) {
709
74
        return false;
710
74
    }
711
712
1.70k
    VExprSPtrs rewritten_literals;
713
1.70k
    rewritten_literals.reserve(children.size() - 1);
714
5.82k
    for (size_t child_idx = 1; child_idx < children.size(); ++child_idx) {
715
4.17k
        auto literal_expr =
716
4.17k
                unwrap_literal_for_file_cast(children[child_idx], rewrite_info->table_type);
717
4.17k
        if (literal_expr == nullptr) {
718
0
            return false;
719
0
        }
720
4.17k
        auto rewritten_literal =
721
4.17k
                rewrite_literal_to_file_type(literal_expr, *rewrite_info, rewrite_context);
722
4.17k
        if (rewritten_literal == nullptr) {
723
150
            for (size_t restore_idx = 1; restore_idx < children.size(); ++restore_idx) {
724
100
                auto restore_literal = unwrap_literal_for_file_cast(children[restore_idx],
725
100
                                                                    rewrite_info->table_type);
726
100
                if (restore_literal != nullptr) {
727
100
                    children[restore_idx] =
728
100
                            original_table_literal(restore_literal, rewrite_context);
729
100
                }
730
100
            }
731
50
            expr->set_children(std::move(children));
732
50
            return false;
733
50
        }
734
4.12k
        rewritten_literals.push_back(std::move(rewritten_literal));
735
4.12k
    }
736
737
1.65k
    children[0] = create_file_slot_ref(*slot_ref, *rewrite_info, rewrite_context);
738
5.77k
    for (size_t literal_idx = 0; literal_idx < rewritten_literals.size(); ++literal_idx) {
739
4.12k
        children[literal_idx + 1] = std::move(rewritten_literals[literal_idx]);
740
4.12k
    }
741
1.65k
    expr->set_children(std::move(children));
742
1.65k
    return true;
743
1.70k
}
744
745
static VExprSPtr create_file_struct_child_name_literal(const std::string& file_child_name,
746
799
                                                       RewriteContext* rewrite_context) {
747
799
    auto literal = VLiteral::create_shared(std::make_shared<DataTypeString>(),
748
799
                                           Field::create_field<TYPE_STRING>(file_child_name));
749
799
    rewrite_context->add_created_expr(literal);
750
799
    return literal;
751
799
}
752
753
static bool needs_complex_file_slot_cast(const DataTypePtr& file_type,
754
4.46k
                                         const DataTypePtr& table_type) {
755
4.46k
    if (file_type == nullptr || table_type == nullptr || file_type->equals(*table_type)) {
756
0
        return false;
757
0
    }
758
4.46k
    const auto file_nested_type = remove_nullable(file_type);
759
4.46k
    const auto table_nested_type = remove_nullable(table_type);
760
4.46k
    if (file_nested_type->equals(*table_nested_type)) {
761
0
        return false;
762
0
    }
763
4.46k
    return is_complex_type(file_nested_type->get_primitive_type()) ||
764
4.46k
           is_complex_type(table_nested_type->get_primitive_type());
765
4.46k
}
766
767
799
static bool collect_struct_element_chain(const VExprSPtr& expr, std::vector<VExprSPtr>* chain) {
768
799
    DORIS_CHECK(chain != nullptr);
769
799
    if (!is_struct_element_expr(expr)) {
770
0
        return false;
771
0
    }
772
799
    const auto& parent = expr->children()[0];
773
799
    if (is_struct_element_expr(parent)) {
774
101
        if (!collect_struct_element_chain(parent, chain)) {
775
0
            return false;
776
0
        }
777
698
    } 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
799
    chain->push_back(expr);
790
799
    return true;
791
799
}
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
2.39k
        RewriteContext* rewrite_context) {
797
2.39k
    ResolvedNestedStructPath resolved;
798
2.39k
    if (!resolve_nested_struct_expr_for_file(expr, mappings, &resolved)) {
799
1.69k
        return false;
800
1.69k
    }
801
802
698
    std::vector<VExprSPtr> struct_element_chain;
803
698
    if (!collect_struct_element_chain(expr, &struct_element_chain) ||
804
698
        struct_element_chain.size() != resolved.file_child_names.size() ||
805
698
        struct_element_chain.size() != resolved.file_child_types.size()) {
806
0
        return false;
807
0
    }
808
809
698
    auto root_children = struct_element_chain.front()->children();
810
698
    if (!root_children[0]->is_slot_ref()) {
811
0
        return false;
812
0
    }
813
698
    const auto* slot_ref = assert_cast<const VSlotRef*>(root_children[0].get());
814
698
    const auto rewrite_it = global_to_file_slot.find(slot_ref_global_index(*slot_ref));
815
698
    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
698
    root_children[0] = create_file_slot_ref(*slot_ref, rewrite_it->second, rewrite_context);
828
698
    struct_element_chain.front()->set_children(std::move(root_children));
829
1.49k
    for (size_t idx = 0; idx < struct_element_chain.size(); ++idx) {
830
799
        auto children = struct_element_chain[idx]->children();
831
799
        children[1] = create_file_struct_child_name_literal(resolved.file_child_names[idx],
832
799
                                                            rewrite_context);
833
799
        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
799
        struct_element_chain[idx]->data_type() = resolved.file_child_types[idx];
843
799
    }
844
698
    return true;
845
698
}
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
83.1k
        bool* can_localize) {
852
83.1k
    if (expr == nullptr) {
853
0
        return nullptr;
854
0
    }
855
83.1k
    DORIS_CHECK(rewrite_context != nullptr);
856
83.1k
    DORIS_CHECK(can_localize != nullptr);
857
83.1k
    if (auto* runtime_filter = dynamic_cast<RuntimeFilterExpr*>(expr.get());
858
83.1k
        runtime_filter != nullptr) {
859
4.04k
        auto impl = runtime_filter->get_impl();
860
4.04k
        if (impl == nullptr) {
861
0
            *can_localize = false;
862
0
            return expr;
863
0
        }
864
4.04k
        auto localized_impl = rewrite_table_expr_to_file_expr(
865
4.04k
                impl, global_to_file_slot, filter_mappings, rewrite_context, can_localize);
866
4.04k
        if (!*can_localize) {
867
0
            return expr;
868
0
        }
869
4.04k
        runtime_filter->set_impl(std::move(localized_impl));
870
4.04k
        return expr;
871
4.04k
    }
872
79.1k
    if (rewrite_binary_slot_literal_predicate(expr, global_to_file_slot, rewrite_context)) {
873
9.76k
        return expr;
874
9.76k
    }
875
69.3k
    if (rewrite_in_slot_literal_predicate(expr, global_to_file_slot, rewrite_context)) {
876
1.65k
        return expr;
877
1.65k
    }
878
67.7k
    if (is_struct_element_expr(expr)) {
879
2.39k
        if (!rewrite_struct_element_path_to_file_expr(expr, filter_mappings, global_to_file_slot,
880
2.39k
                                                      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
1.69k
            *can_localize = false;
888
1.69k
        }
889
2.39k
        return expr;
890
2.39k
    }
891
65.3k
    if (expr->is_slot_ref()) {
892
21.9k
        const auto* slot_ref = assert_cast<const VSlotRef*>(expr.get());
893
21.9k
        const auto rewrite_it = global_to_file_slot.find(slot_ref_global_index(*slot_ref));
894
21.9k
        if (rewrite_it != global_to_file_slot.end()) {
895
21.9k
            const auto& rewrite_info = rewrite_it->second;
896
21.9k
            auto file_slot = create_file_slot_ref(*slot_ref, rewrite_info, rewrite_context);
897
21.9k
            if (rewrite_info.file_type->equals(*rewrite_info.table_type)) {
898
17.5k
                return file_slot;
899
17.5k
            }
900
4.47k
            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
566
                *can_localize = false;
915
566
                return expr;
916
566
            }
917
3.91k
            auto cast_expr = Cast::create_shared(rewrite_info.table_type);
918
3.91k
            cast_expr->add_child(std::move(file_slot));
919
3.91k
            rewrite_context->add_created_expr(cast_expr);
920
3.91k
            return cast_expr;
921
4.47k
        }
922
18.4E
        return expr;
923
21.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
43.3k
    if (is_cast_expr(expr) && expr->get_num_children() == 1) {
928
1.66k
        const auto& child = expr->children()[0];
929
1.66k
        if (child->is_slot_ref()) {
930
1.60k
            const auto* slot_ref = assert_cast<const VSlotRef*>(child.get());
931
1.60k
            const auto rewrite_it = global_to_file_slot.find(slot_ref_global_index(*slot_ref));
932
1.60k
            if (rewrite_it != global_to_file_slot.end() &&
933
1.60k
                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
1.60k
        }
948
1.66k
    }
949
950
43.3k
    VExprSPtrs rewritten_children;
951
43.3k
    rewritten_children.reserve(expr->children().size());
952
44.1k
    for (const auto& child : expr->children()) {
953
44.1k
        rewritten_children.push_back(rewrite_table_expr_to_file_expr(
954
44.1k
                child, global_to_file_slot, filter_mappings, rewrite_context, can_localize));
955
44.1k
    }
956
43.3k
    expr->set_children(std::move(rewritten_children));
957
43.3k
    return expr;
958
43.3k
}
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
303k
static TableVirtualColumnType row_lineage_virtual_column_type(const std::string& column_name) {
966
303k
    if (column_name == ROW_LINEAGE_ROW_ID) {
967
2
        return TableVirtualColumnType::ROW_ID;
968
2
    }
969
303k
    if (column_name == ROW_LINEAGE_LAST_UPDATED_SEQ_NUMBER) {
970
2
        return TableVirtualColumnType::LAST_UPDATED_SEQUENCE_NUMBER;
971
2
    }
972
303k
    return TableVirtualColumnType::INVALID;
973
303k
}
974
975
static TableVirtualColumnType row_lineage_virtual_column_type_by_field_id(
976
88.0k
        const ColumnDefinition& column) {
977
88.0k
    if (!column.has_identifier_field_id()) {
978
545
        return TableVirtualColumnType::INVALID;
979
545
    }
980
87.4k
    switch (column.get_identifier_field_id()) {
981
482
    case ROW_LINEAGE_ROW_ID_FIELD_ID:
982
482
        return TableVirtualColumnType::ROW_ID;
983
395
    case ROW_LINEAGE_LAST_UPDATED_SEQ_NUMBER_FIELD_ID:
984
395
        return TableVirtualColumnType::LAST_UPDATED_SEQUENCE_NUMBER;
985
86.4k
    default:
986
86.4k
        return TableVirtualColumnType::INVALID;
987
87.4k
    }
988
87.4k
}
989
990
static TableVirtualColumnType row_lineage_virtual_column_type(const ColumnDefinition& column,
991
391k
                                                              TableColumnMappingMode mode) {
992
391k
    switch (mode) {
993
88.0k
    case TableColumnMappingMode::BY_FIELD_ID:
994
88.0k
        return row_lineage_virtual_column_type_by_field_id(column);
995
258k
    case TableColumnMappingMode::BY_NAME:
996
303k
    case TableColumnMappingMode::BY_INDEX:
997
303k
        return row_lineage_virtual_column_type(column.name);
998
391k
    }
999
0
    return TableVirtualColumnType::INVALID;
1000
391k
}
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
492k
static bool needs_projected_file_type_rebuild(const ColumnMapping& mapping) {
1006
492k
    if (!is_complex_type(mapping.file_type->get_primitive_type())) {
1007
275k
        return false;
1008
275k
    }
1009
216k
    if (mapping.child_mappings.empty()) {
1010
0
        return false;
1011
0
    }
1012
216k
    DORIS_CHECK(mapping.file_type != nullptr);
1013
216k
    DORIS_CHECK(mapping.table_type != nullptr);
1014
216k
    if (remove_nullable(mapping.file_type)->get_primitive_type() !=
1015
216k
        remove_nullable(mapping.table_type)->get_primitive_type()) {
1016
0
        return true;
1017
0
    }
1018
216k
    if (!mapping.table_type->equals(*mapping.file_type)) {
1019
16.6k
        return true;
1020
16.6k
    }
1021
303k
    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
303k
        if (!child_mapping.file_local_id.has_value() ||
1026
303k
            needs_projected_file_type_rebuild(child_mapping)) {
1027
661
            return true;
1028
661
        }
1029
303k
    }
1030
199k
    return false;
1031
200k
}
1032
1033
static std::optional<size_t> file_child_ordinal_in_scan_type(const ColumnMapping& mapping,
1034
276k
                                                             const ColumnMapping& child_mapping) {
1035
276k
    if (!child_mapping.file_local_id.has_value()) {
1036
241
        return std::nullopt;
1037
241
    }
1038
276k
    const auto& file_children = !mapping.projected_file_children.empty()
1039
276k
                                        ? mapping.projected_file_children
1040
18.4E
                                        : mapping.original_file_children;
1041
383k
    const auto child_it = std::ranges::find_if(file_children, [&](const ColumnDefinition& child) {
1042
383k
        return child.file_local_id() == *child_mapping.file_local_id;
1043
383k
    });
1044
276k
    if (child_it == file_children.end()) {
1045
0
        return std::nullopt;
1046
0
    }
1047
276k
    return static_cast<size_t>(std::distance(file_children.begin(), child_it));
1048
276k
}
1049
1050
1.07M
static bool needs_complex_rematerialize(const ColumnMapping& mapping) {
1051
1.07M
    if (mapping.child_mappings.empty()) {
1052
886k
        return false;
1053
886k
    }
1054
193k
    if (mapping.table_type == nullptr || mapping.file_type == nullptr ||
1055
193k
        !mapping.table_type->equals(*mapping.file_type)) {
1056
10.2k
        return true;
1057
10.2k
    }
1058
457k
    for (size_t table_child_idx = 0; table_child_idx < mapping.child_mappings.size();
1059
276k
         ++table_child_idx) {
1060
276k
        const auto& child_mapping = mapping.child_mappings[table_child_idx];
1061
276k
        const auto file_child_idx = file_child_ordinal_in_scan_type(mapping, child_mapping);
1062
276k
        if (!file_child_idx.has_value() || *file_child_idx != table_child_idx ||
1063
276k
            needs_complex_rematerialize(child_mapping) ||
1064
276k
            (child_mapping.table_type != nullptr && child_mapping.file_type != nullptr &&
1065
274k
             !child_mapping.table_type->equals(*child_mapping.file_type))) {
1066
1.96k
            return true;
1067
1.96k
        }
1068
276k
    }
1069
181k
    return false;
1070
183k
}
1071
1072
841k
static bool mapping_can_use_file_column_directly(const ColumnMapping& mapping) {
1073
841k
    if (mapping.table_type == nullptr || mapping.file_type == nullptr) {
1074
0
        return false;
1075
0
    }
1076
841k
    const auto table_type = remove_nullable(mapping.table_type);
1077
841k
    const auto file_type = remove_nullable(mapping.file_type);
1078
841k
    const bool same_timestamptz_with_different_scale =
1079
841k
            table_type->get_primitive_type() == TYPE_TIMESTAMPTZ &&
1080
841k
            file_type->get_primitive_type() == TYPE_TIMESTAMPTZ;
1081
841k
    if (!mapping.table_type->equals(*mapping.file_type) && !same_timestamptz_with_different_scale) {
1082
61.7k
        return false;
1083
61.7k
    }
1084
779k
    return !needs_complex_rematerialize(mapping);
1085
841k
}
1086
1087
1.05M
static bool type_contains_varbinary(const DataTypePtr& type) {
1088
1.05M
    DORIS_CHECK(type != nullptr);
1089
1.05M
    const auto nested_type = remove_nullable(type);
1090
1.05M
    switch (nested_type->get_primitive_type()) {
1091
619
    case TYPE_VARBINARY:
1092
619
        return true;
1093
99.9k
    case TYPE_ARRAY:
1094
99.9k
        return type_contains_varbinary(
1095
99.9k
                assert_cast<const DataTypeArray&>(*nested_type).get_nested_type());
1096
72.2k
    case TYPE_MAP: {
1097
72.2k
        const auto& map_type = assert_cast<const DataTypeMap&>(*nested_type);
1098
72.2k
        return type_contains_varbinary(map_type.get_key_type()) ||
1099
72.2k
               type_contains_varbinary(map_type.get_value_type());
1100
0
    }
1101
71.2k
    case TYPE_STRUCT:
1102
71.2k
        return std::ranges::any_of(
1103
71.2k
                assert_cast<const DataTypeStruct&>(*nested_type).get_elements(),
1104
134k
                [](const DataTypePtr& child_type) { return type_contains_varbinary(child_type); });
1105
813k
    default:
1106
813k
        return false;
1107
1.05M
    }
1108
1.05M
}
1109
1110
676k
static FilterConversionType direct_filter_conversion(const ColumnMapping& mapping) {
1111
676k
    DORIS_CHECK(mapping.table_type != nullptr);
1112
676k
    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
676k
    if (type_contains_varbinary(mapping.table_type)) {
1119
619
        return FilterConversionType::FINALIZE_ONLY;
1120
619
    }
1121
676k
    const auto table_type = remove_nullable(mapping.table_type);
1122
676k
    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
676k
    if (table_type->get_primitive_type() == TYPE_TIMESTAMPTZ &&
1127
676k
        file_type->get_primitive_type() == TYPE_TIMESTAMPTZ &&
1128
676k
        !mapping.table_type->equals(*mapping.file_type)) {
1129
1
        return FilterConversionType::FINALIZE_ONLY;
1130
1
    }
1131
676k
    return mapping.is_trivial ? FilterConversionType::COPY_DIRECTLY
1132
676k
                              : FilterConversionType::CAST_FILTER;
1133
676k
}
1134
1135
16.9k
static FilterConversionType projected_filter_conversion(const ColumnMapping& mapping) {
1136
16.9k
    const auto conversion = direct_filter_conversion(mapping);
1137
16.9k
    return !mapping.is_trivial && conversion != FilterConversionType::FINALIZE_ONLY
1138
16.9k
                   ? FilterConversionType::READER_EXPRESSION
1139
16.9k
                   : conversion;
1140
16.9k
}
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
293k
                                                           bool allow_ordinal_fallback) {
1147
293k
    const auto file_parent_type = remove_nullable(file_parent.type)->get_primitive_type();
1148
293k
    switch (file_parent_type) {
1149
83.8k
    case TYPE_ARRAY:
1150
83.8k
        DORIS_CHECK(file_parent.children.size() == 1);
1151
83.8k
        return &file_parent.children[0];
1152
132k
    case TYPE_MAP:
1153
132k
        DORIS_CHECK(file_parent.children.size() == 2);
1154
132k
        if (table_child.name == "key") {
1155
66.1k
            return &file_parent.children[0];
1156
66.1k
        }
1157
66.1k
        if (table_child.name == "value") {
1158
66.1k
            return &file_parent.children[1];
1159
66.1k
        }
1160
18
        if (table_child.local_id == 0 || table_child.local_id == 1) {
1161
0
            return &file_parent.children[table_child.local_id];
1162
0
        }
1163
18
        return nullptr;
1164
77.6k
    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
77.6k
        const auto nested_mode =
1169
77.6k
                mode == TableColumnMappingMode::BY_INDEX ? TableColumnMappingMode::BY_NAME : mode;
1170
77.6k
        if (const auto* file_child =
1171
77.6k
                    matcher_for_mode(nested_mode).find(table_child, file_parent.children);
1172
77.6k
            file_child != nullptr) {
1173
73.1k
            return file_child;
1174
73.1k
        }
1175
4.48k
        if (allow_ordinal_fallback && mode == TableColumnMappingMode::BY_FIELD_ID &&
1176
4.48k
            !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
4.48k
        if (allow_ordinal_fallback && table_child_idx < file_parent.children.size()) {
1195
3
            return &file_parent.children[table_child_idx];
1196
3
        }
1197
4.48k
        return nullptr;
1198
293k
    }
1199
293k
}
1200
1201
static ColumnDefinition synthetic_child_definition(const std::string& name, DataTypePtr type,
1202
77.6k
                                                   int32_t local_id) {
1203
77.6k
    ColumnDefinition child;
1204
77.6k
    child.identifier = Field::create_field<TYPE_STRING>(name);
1205
77.6k
    child.local_id = local_id;
1206
77.6k
    child.name = name;
1207
77.6k
    child.type = std::move(type);
1208
77.6k
    return child;
1209
77.6k
}
1210
1211
static std::vector<ColumnDefinition> synthesize_complex_children_from_type(
1212
40.3k
        const DataTypePtr& type) {
1213
40.3k
    std::vector<ColumnDefinition> children;
1214
40.3k
    if (type == nullptr) {
1215
0
        return children;
1216
0
    }
1217
40.3k
    const auto nested_type = remove_nullable(type);
1218
40.3k
    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
40.3k
    case TYPE_STRUCT: {
1231
40.3k
        const auto* struct_type = assert_cast<const DataTypeStruct*>(nested_type.get());
1232
40.3k
        children.reserve(struct_type->get_elements().size());
1233
117k
        for (size_t idx = 0; idx < struct_type->get_elements().size(); ++idx) {
1234
77.6k
            children.push_back(synthetic_child_definition(struct_type->get_element_name(idx),
1235
77.6k
                                                          struct_type->get_element(idx),
1236
77.6k
                                                          cast_set<int32_t>(idx)));
1237
77.6k
        }
1238
40.3k
        break;
1239
0
    }
1240
0
    default:
1241
0
        break;
1242
40.3k
    }
1243
40.3k
    return children;
1244
40.3k
}
1245
1246
static void align_struct_child_types_with_parent(const DataTypePtr& parent_type,
1247
40.3k
                                                 std::vector<ColumnDefinition>& children) {
1248
40.3k
    const auto nested_parent_type = remove_nullable(parent_type);
1249
40.3k
    DORIS_CHECK(nested_parent_type->get_primitive_type() == TYPE_STRUCT);
1250
40.3k
    const auto type_children = synthesize_complex_children_from_type(parent_type);
1251
77.6k
    for (auto& child : children) {
1252
77.6k
        const auto type_child = std::ranges::find_if(
1253
130k
                type_children, [&](const auto& candidate) { return candidate.name == child.name; });
1254
77.6k
        DORIS_CHECK(type_child != type_children.end())
1255
4
                << "Complex child '" << child.name
1256
4
                << "' 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
77.6k
        child.type = type_child->type;
1263
77.6k
    }
1264
40.3k
}
1265
1266
static bool has_table_child_named(const std::vector<ColumnDefinition>& children,
1267
8.97k
                                  std::string_view name) {
1268
13.4k
    return std::ranges::any_of(children, [&](const ColumnDefinition& child) {
1269
13.4k
        return std::string_view(child.name) == name;
1270
13.4k
    });
1271
8.97k
}
1272
1273
static void complete_required_complex_children_from_type(const DataTypePtr& type,
1274
16.3k
                                                         std::vector<ColumnDefinition>& children) {
1275
16.3k
    if (type == nullptr) {
1276
0
        return;
1277
0
    }
1278
16.3k
    const auto nested_type = remove_nullable(type);
1279
16.3k
    switch (nested_type->get_primitive_type()) {
1280
4.48k
    case TYPE_MAP: {
1281
4.48k
        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
4.48k
        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
4.48k
        break;
1293
0
    }
1294
4.99k
    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
4.99k
        break;
1298
6.89k
    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
6.89k
        break;
1302
0
    default:
1303
0
        break;
1304
16.3k
    }
1305
16.3k
}
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
659k
        const ColumnDefinition& table_column, const DataTypePtr& file_type) {
1314
659k
    PreparedTableChildren prepared {.children = table_column.children};
1315
659k
    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
659k
    prepared.synthesized_from_type = prepared.children.empty() &&
1321
659k
                                     is_complex_type(nested_table_type->get_primitive_type()) &&
1322
659k
                                     !table_column.type->equals(*file_type);
1323
659k
    if (prepared.synthesized_from_type) {
1324
4
        prepared.children = synthesize_complex_children_from_type(table_column.type);
1325
659k
    } else if (!prepared.children.empty() && !table_column.type->equals(*file_type)) {
1326
16.3k
        complete_required_complex_children_from_type(table_column.type, prepared.children);
1327
16.3k
    }
1328
1329
659k
    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
40.3k
        align_struct_child_types_with_parent(table_column.type, prepared.children);
1334
40.3k
    }
1335
659k
    return prepared;
1336
659k
}
1337
1338
190k
static Status validate_file_schema_children(const ColumnDefinition& file_field) {
1339
190k
    if (file_field.type == nullptr) {
1340
0
        return Status::InternalError("File column '{}' has null type", file_field.name);
1341
0
    }
1342
190k
    const auto nested_type = remove_nullable(file_field.type);
1343
190k
    size_t expected_children = 0;
1344
190k
    bool complex_with_fixed_children = true;
1345
190k
    switch (nested_type->get_primitive_type()) {
1346
83.8k
    case TYPE_ARRAY:
1347
83.8k
        expected_children = 1;
1348
83.8k
        break;
1349
66.1k
    case TYPE_MAP:
1350
66.1k
        expected_children = 2;
1351
66.1k
        break;
1352
40.3k
    case TYPE_STRUCT:
1353
40.3k
        expected_children =
1354
40.3k
                assert_cast<const DataTypeStruct*>(nested_type.get())->get_elements().size();
1355
40.3k
        break;
1356
0
    default:
1357
0
        complex_with_fixed_children = false;
1358
0
        break;
1359
190k
    }
1360
190k
    if (!complex_with_fixed_children || file_field.children.size() == expected_children) {
1361
190k
        return Status::OK();
1362
190k
    }
1363
21
    return Status::InternalError(
1364
21
            "Malformed complex file schema for column '{}': type={}, expected_children={}, "
1365
21
            "actual_children={}",
1366
21
            file_field.name, file_field.type->get_name(), expected_children,
1367
21
            file_field.children.size());
1368
190k
}
1369
1370
289k
static bool has_projected_file_children(const ColumnMapping& mapping) {
1371
289k
    if (mapping.original_file_children.empty() || mapping.projected_file_children.empty()) {
1372
223k
        return false;
1373
223k
    }
1374
65.6k
    if (mapping.original_file_children.size() != mapping.projected_file_children.size()) {
1375
4.80k
        return true;
1376
4.80k
    }
1377
159k
    for (size_t idx = 0; idx < mapping.original_file_children.size(); ++idx) {
1378
98.3k
        if (mapping.original_file_children[idx].file_local_id() !=
1379
98.3k
            mapping.projected_file_children[idx].file_local_id()) {
1380
0
            return true;
1381
0
        }
1382
98.3k
    }
1383
60.8k
    return false;
1384
60.8k
}
1385
1386
289k
static bool needs_nested_file_projection(const ColumnMapping& mapping) {
1387
289k
    if (has_projected_file_children(mapping)) {
1388
        // Return True if the projected child column is missing / re-ordered
1389
4.79k
        return true;
1390
4.79k
    }
1391
284k
    return std::ranges::any_of(mapping.child_mappings, [](const ColumnMapping& child_mapping) {
1392
99.8k
        return needs_nested_file_projection(child_mapping);
1393
99.8k
    });
1394
289k
}
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
16.9k
        std::vector<ColumnDefinition>* projected_file_children, DataTypePtr* projected_type) {
1405
16.9k
    DORIS_CHECK(file_type != nullptr);
1406
16.9k
    DORIS_CHECK(projected_file_children != nullptr);
1407
16.9k
    DORIS_CHECK(projected_type != nullptr);
1408
16.9k
    ColumnDefinition field;
1409
16.9k
    field.type = file_type;
1410
16.9k
    field.children = original_file_children;
1411
16.9k
    LocalColumnIndex projection = LocalColumnIndex::partial_local(-1);
1412
16.9k
    projection.children.reserve(child_mappings.size());
1413
24.5k
    for (const auto* child_mapping : present_child_mappings_in_file_order(child_mappings)) {
1414
24.5k
        DORIS_CHECK(child_mapping->file_local_id.has_value());
1415
24.5k
        LocalColumnIndex child_projection;
1416
24.5k
        RETURN_IF_ERROR(build_complex_projection(*child_mapping, &child_projection));
1417
24.5k
        projection.children.push_back(std::move(child_projection));
1418
24.5k
    }
1419
1420
16.9k
    ColumnDefinition projected_field;
1421
16.9k
    RETURN_IF_ERROR(project_column_definition(field, projection, &projected_field));
1422
16.9k
    *projected_file_children = std::move(projected_field.children);
1423
16.9k
    *projected_type = std::move(projected_field.type);
1424
16.9k
    return Status::OK();
1425
16.9k
}
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
45.4k
static Status build_complex_projection(const ColumnMapping& mapping, LocalColumnIndex* projection) {
1435
45.4k
    if (projection == nullptr) {
1436
0
        return Status::InvalidArgument("projection is null");
1437
0
    }
1438
45.4k
    DORIS_CHECK(mapping.file_local_id.has_value());
1439
45.4k
    *projection = LocalColumnIndex::local(*mapping.file_local_id);
1440
45.4k
    projection->project_all_children = mapping.child_mappings.empty();
1441
45.4k
    projection->children.clear();
1442
45.4k
    const auto present_children = present_child_mappings_in_file_order(mapping.child_mappings);
1443
45.4k
    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
236
        projection->project_all_children = true;
1448
236
        return Status::OK();
1449
236
    }
1450
45.1k
    for (const auto* child_mapping : present_children) {
1451
16.0k
        LocalColumnIndex child_projection;
1452
16.0k
        RETURN_IF_ERROR(build_complex_projection(*child_mapping, &child_projection));
1453
16.0k
        projection->children.push_back(std::move(child_projection));
1454
16.0k
    }
1455
45.1k
    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
45.1k
    return Status::OK();
1460
45.1k
}
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
371k
                                                    ColumnMapping* mapping) {
1469
371k
    DORIS_CHECK(mapping != nullptr);
1470
371k
    if (mapping->original_file_type == nullptr) {
1471
0
        mapping->original_file_type = mapping->file_type;
1472
0
    }
1473
371k
    if (mapping->original_file_type == nullptr ||
1474
371k
        !is_complex_type(remove_nullable(mapping->original_file_type)->get_primitive_type())) {
1475
207k
        return Status::OK();
1476
207k
    }
1477
164k
    ColumnDefinition field;
1478
164k
    field.type = mapping->original_file_type;
1479
164k
    field.children = mapping->original_file_children;
1480
164k
    ColumnDefinition projected_field;
1481
164k
    RETURN_IF_ERROR(project_column_definition(field, projection, &projected_field));
1482
164k
    mapping->file_type = std::move(projected_field.type);
1483
164k
    mapping->projected_file_children = std::move(projected_field.children);
1484
164k
    mapping->is_trivial = mapping_can_use_file_column_directly(*mapping);
1485
164k
    return Status::OK();
1486
164k
}
1487
1488
static Status merge_filter_projection(const FilterProjectionMap* filter_projections,
1489
35.6k
                                      LocalColumnIndex* projection) {
1490
35.6k
    DORIS_CHECK(projection != nullptr);
1491
35.6k
    if (filter_projections == nullptr) {
1492
0
        return Status::OK();
1493
0
    }
1494
35.6k
    const auto filter_projection_it = filter_projections->find(projection->column_id());
1495
35.6k
    if (filter_projection_it == filter_projections->end()) {
1496
34.8k
        return Status::OK();
1497
34.8k
    }
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
723
    RETURN_IF_ERROR(merge_local_column_index(projection, filter_projection_it->second));
1503
723
    return Status::OK();
1504
723
}
1505
1506
86
static bool table_root_is_map(const ColumnMapping& mapping) {
1507
86
    if (mapping.table_type == nullptr) {
1508
0
        return false;
1509
0
    }
1510
86
    return remove_nullable(mapping.table_type)->get_primitive_type() == TYPE_MAP;
1511
86
}
1512
1513
static Status add_scan_column(FileScanRequest* file_request, ColumnMapping* mapping,
1514
                              bool is_predicate_column, bool force_full_complex_scan_projection,
1515
378k
                              const FilterProjectionMap* filter_projections = nullptr) {
1516
378k
    const auto file_column_id = LocalColumnId(mapping->file_local_id.value());
1517
378k
    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
378k
    if (!force_full_complex_scan_projection && needs_nested_file_projection(*mapping)) {
1522
4.79k
        RETURN_IF_ERROR(build_complex_projection(*mapping, &projection));
1523
4.79k
    }
1524
378k
    if (is_predicate_column && !force_full_complex_scan_projection) {
1525
35.6k
        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
35.6k
        RETURN_IF_ERROR(merge_filter_projection(filter_projections, &projection));
1531
35.6k
    }
1532
378k
    FileScanRequestBuilder builder(file_request);
1533
378k
    if (is_predicate_column) {
1534
35.5k
        return builder.add_predicate_column(std::move(projection));
1535
35.5k
    }
1536
343k
    return builder.add_non_predicate_column(std::move(projection));
1537
378k
}
1538
1539
static const LocalColumnIndex* find_scan_projection(
1540
714k
        const std::vector<LocalColumnIndex>& scan_columns, LocalColumnId file_column_id) {
1541
714k
    const auto projection_it =
1542
7.74M
            std::ranges::find_if(scan_columns, [&](const LocalColumnIndex& projection) {
1543
7.74M
                return projection.column_id() == file_column_id;
1544
7.74M
            });
1545
714k
    return projection_it == scan_columns.end() ? nullptr : &*projection_it;
1546
714k
}
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
371k
                                                         ColumnMapping* mapping) {
1558
371k
    DORIS_CHECK(mapping != nullptr);
1559
371k
    DORIS_CHECK(mapping->file_local_id.has_value());
1560
371k
    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
371k
    const auto* projection = find_scan_projection(file_request.predicate_columns, file_column_id);
1564
371k
    if (projection == nullptr) {
1565
343k
        projection = find_scan_projection(file_request.non_predicate_columns, file_column_id);
1566
343k
    }
1567
371k
    DORIS_CHECK(projection != nullptr);
1568
371k
    return apply_projection_to_mapping_file_type(*projection, mapping);
1569
371k
}
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
59.9k
        FilterProjectionMap* filter_projections) {
1587
59.9k
    DORIS_CHECK(filter_projections != nullptr);
1588
59.9k
    filter_projections->clear();
1589
59.9k
    for (const auto& table_filter : table_filters) {
1590
39.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
39.9k
        std::vector<NestedStructPath> paths;
1597
39.9k
        collect_nested_struct_paths(table_filter.conjunct->root(), &paths);
1598
39.9k
        for (const auto& path : paths) {
1599
3.48k
            auto mapping_it = std::ranges::find_if(mappings, [&](const ColumnMapping& mapping) {
1600
3.48k
                return mapping.global_index == path.root_global_index;
1601
3.48k
            });
1602
1.16k
            if (mapping_it == mappings.end() || !mapping_it->file_local_id.has_value() ||
1603
1.16k
                path.selectors.empty()) {
1604
384
                continue;
1605
384
            }
1606
1607
784
            ResolvedNestedStructPath resolved;
1608
784
            LocalColumnIndex root_projection;
1609
784
            if (!resolve_nested_struct_path_for_file(path, mappings, &resolved)) {
1610
86
                if (!table_root_is_map(*mapping_it)) {
1611
85
                    continue;
1612
85
                }
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
698
            } else {
1626
698
                root_projection = std::move(resolved.file_projection);
1627
698
            }
1628
699
            auto filter_projection_it = filter_projections->find(root_projection.column_id());
1629
699
            if (filter_projection_it == filter_projections->end()) {
1630
631
                filter_projections->emplace(root_projection.column_id(),
1631
631
                                            std::move(root_projection));
1632
631
                continue;
1633
631
            }
1634
68
            RETURN_IF_ERROR(
1635
68
                    merge_local_column_index(&filter_projection_it->second, root_projection));
1636
68
        }
1637
39.9k
    }
1638
59.9k
    return Status::OK();
1639
59.9k
}
1640
1641
371k
static void rebuild_projection(ColumnMapping* mapping, LocalIndex block_position) {
1642
371k
    DORIS_CHECK(mapping->file_local_id.has_value());
1643
371k
    if (mapping->is_trivial || needs_complex_rematerialize(*mapping)) {
1644
358k
        mapping->projection = VExprContext::create_shared(VSlotRef::create_shared(
1645
358k
                cast_set<int>(block_position.value()), cast_set<int>(block_position.value()), -1,
1646
358k
                mapping->file_type, mapping->file_column_name));
1647
358k
        return;
1648
358k
    }
1649
1650
13.5k
    auto expr = Cast::create_shared(mapping->table_type);
1651
13.5k
    expr->add_child(VSlotRef::create_shared(cast_set<int>(block_position.value()),
1652
13.5k
                                            cast_set<int>(block_position.value()), -1,
1653
13.5k
                                            mapping->file_type, mapping->file_column_name));
1654
13.5k
    mapping->projection = VExprContext::create_shared(expr);
1655
13.5k
}
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
59.9k
        const std::map<GlobalIndex, FilterEntry>& filter_entries) {
1662
59.9k
    std::map<GlobalIndex, FileSlotRewriteInfo> global_to_file_slot;
1663
391k
    for (const auto& mapping : mappings) {
1664
391k
        const auto entry_it = filter_entries.find(mapping.global_index);
1665
391k
        if (entry_it == filter_entries.end() || !entry_it->second.is_local()) {
1666
20.3k
            continue;
1667
20.3k
        }
1668
371k
        DORIS_CHECK(mapping.file_local_id.has_value());
1669
371k
        global_to_file_slot.emplace(
1670
371k
                mapping.global_index,
1671
371k
                FileSlotRewriteInfo {.block_position = entry_it->second.local_index().value(),
1672
371k
                                     .file_type = mapping.file_type,
1673
371k
                                     .table_type = mapping.table_type,
1674
371k
                                     .file_column_name = mapping.file_column_name});
1675
371k
    }
1676
59.9k
    return global_to_file_slot;
1677
59.9k
}
1678
1679
Status TableColumnMapper::_create_by_index_mapping(const ColumnDefinition& table_column,
1680
                                                   const std::vector<ColumnDefinition>& file_schema,
1681
37.1k
                                                   ColumnMapping* mapping) {
1682
37.1k
    DORIS_CHECK(mapping != nullptr);
1683
37.1k
    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
37.1k
    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
37.1k
    if (file_index >= 0 && static_cast<size_t>(file_index) < file_schema.size()) {
1698
36.5k
        return _create_direct_mapping(table_column, file_schema[static_cast<size_t>(file_index)],
1699
36.5k
                                      mapping);
1700
36.5k
    }
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
553
    if (table_column.default_expr != nullptr) {
1705
531
        _set_constant_mapping(mapping, table_column.default_expr);
1706
531
        return Status::OK();
1707
531
    }
1708
    // Keep the mapping empty (`file_local_id` remains `nullopt`) and let the upper finalize
1709
    // stage fill NULL/default values.
1710
22
    return Status::OK();
1711
553
}
1712
1713
18.7k
void TableColumnMapper::_set_constant_mapping(ColumnMapping* mapping, VExprContextSPtr expr) {
1714
18.7k
    DORIS_CHECK(mapping != nullptr);
1715
18.7k
    DORIS_CHECK(expr != nullptr);
1716
18.7k
    mapping->default_expr = std::move(expr);
1717
18.7k
    mapping->constant_index = _constant_map.add(ConstantEntry {
1718
18.7k
            .global_index = mapping->global_index,
1719
18.7k
            .expr = mapping->default_expr,
1720
18.7k
            .type = mapping->table_type,
1721
18.7k
    });
1722
18.7k
    mapping->filter_conversion = FilterConversionType::CONSTANT;
1723
18.7k
}
1724
1725
Status TableColumnMapper::_create_mapping_for_column(const ColumnDefinition& table_column,
1726
                                                     GlobalIndex global_index,
1727
391k
                                                     ColumnMapping* mapping) {
1728
391k
    DORIS_CHECK(mapping != nullptr);
1729
391k
    *mapping = ColumnMapping {};
1730
391k
    mapping->global_index = global_index;
1731
391k
    mapping->table_column_name = table_column.name;
1732
391k
    mapping->table_type = table_column.type;
1733
391k
    const auto row_lineage_type = row_lineage_virtual_column_type(table_column, _options.mode);
1734
391k
    if (const auto* partition_value = find_partition_value(table_column, _partition_values);
1735
391k
        table_column.is_partition_key && partition_value != nullptr) {
1736
        // Partition values are split constants and must take precedence over defaults.
1737
12.7k
        _set_constant_mapping(mapping, VExprContext::create_shared(VLiteral::create_shared(
1738
12.7k
                                               mapping->table_type, *partition_value)));
1739
378k
    } else if (_options.mode == TableColumnMappingMode::BY_INDEX &&
1740
378k
               !table_column.is_partition_key && table_column.has_identifier_field_id()) {
1741
        // BY_INDEX interprets ColumnDefinition::identifier as physical file position.
1742
37.1k
        RETURN_IF_ERROR(_create_by_index_mapping(table_column, _file_schema, mapping));
1743
341k
    } else if (const auto* file_field = _find_file_field(table_column, _file_schema)) {
1744
        // Normal physical file column mapping.
1745
335k
        RETURN_IF_ERROR(_create_direct_mapping(table_column, *file_field, mapping));
1746
335k
        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
134
            mapping->virtual_column_type = row_lineage_type;
1752
134
            mapping->filter_conversion = FilterConversionType::FINALIZE_ONLY;
1753
134
        }
1754
335k
    } 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
749
        mapping->virtual_column_type = row_lineage_type;
1761
5.26k
    } 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
194
        mapping->virtual_column_type = TableVirtualColumnType::ICEBERG_ROWID;
1765
5.44k
    } else if (table_column.default_expr != nullptr) {
1766
        // Missing schema-evolution column with an explicit default expression.
1767
5.44k
        _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
391k
    return Status::OK();
1776
391k
}
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
59.8k
        const std::vector<TableFilter>& table_filters) {
1809
59.8k
    _hidden_mappings.clear();
1810
1811
59.8k
    std::map<GlobalIndex, ColumnDefinition> filter_columns;
1812
59.8k
    for (const auto& table_filter : table_filters) {
1813
39.9k
        if (table_filter.conjunct != nullptr) {
1814
39.9k
            collect_top_level_slot_columns(table_filter.conjunct->root(), &filter_columns);
1815
39.9k
        }
1816
39.8k
    }
1817
1818
59.8k
    for (const auto& [global_index, table_column] : filter_columns) {
1819
33.2k
        if (_find_mapping(global_index) != nullptr) {
1820
            // Ignore columns that are already mapped by the projected columns
1821
33.2k
            continue;
1822
33.2k
        }
1823
6
        ColumnMapping mapping;
1824
6
        RETURN_IF_ERROR(_create_hidden_filter_mapping(table_column, global_index, &mapping));
1825
6
        if (mapping.file_local_id.has_value() || mapping.constant_index.has_value() ||
1826
6
            mapping.virtual_column_type != TableVirtualColumnType::INVALID) {
1827
2
            _hidden_mappings.push_back(std::move(mapping));
1828
2
        }
1829
6
    }
1830
59.8k
    return Status::OK();
1831
59.8k
}
1832
1833
Status TableColumnMapper::create_mapping(const std::vector<ColumnDefinition>& projected_columns,
1834
                                         const std::map<std::string, Field>& partition_values,
1835
59.8k
                                         const std::vector<ColumnDefinition>& file_schema) {
1836
59.8k
    clear();
1837
59.8k
    _partition_values = partition_values;
1838
59.8k
    _file_schema = file_schema;
1839
451k
    for (size_t column_idx = 0; column_idx < projected_columns.size(); ++column_idx) {
1840
391k
        ColumnMapping mapping;
1841
391k
        RETURN_IF_ERROR(_create_mapping_for_column(projected_columns[column_idx],
1842
391k
                                                   GlobalIndex(column_idx), &mapping));
1843
391k
        _mappings.push_back(std::move(mapping));
1844
391k
    }
1845
59.8k
    return Status::OK();
1846
59.8k
}
1847
1848
179k
std::vector<ColumnMapping> TableColumnMapper::_filter_visible_mappings() const {
1849
179k
    std::vector<ColumnMapping> mappings;
1850
179k
    mappings.reserve(_mappings.size() + _hidden_mappings.size());
1851
179k
    mappings.insert(mappings.end(), _mappings.begin(), _mappings.end());
1852
179k
    mappings.insert(mappings.end(), _hidden_mappings.begin(), _hidden_mappings.end());
1853
179k
    return mappings;
1854
179k
}
1855
1856
59.8k
Status TableColumnMapper::_build_filter_entries(const FileScanRequest& file_request) {
1857
59.8k
    _filter_entries.clear();
1858
59.8k
    const auto mappings = _filter_visible_mappings();
1859
391k
    for (const auto& mapping : mappings) {
1860
391k
        FilterEntry entry;
1861
391k
        if (mapping.constant_index.has_value()) {
1862
18.7k
            entry = FilterEntry::constant(*mapping.constant_index);
1863
372k
        } else if (mapping.file_local_id.has_value() &&
1864
372k
                   filter_conversion_has_local_source(mapping.filter_conversion)) {
1865
371k
            const auto local_position_it =
1866
371k
                    file_request.local_positions.find(LocalColumnId(*mapping.file_local_id));
1867
371k
            if (local_position_it != file_request.local_positions.end()) {
1868
371k
                entry = FilterEntry::local(local_position_it->second);
1869
371k
            }
1870
371k
        }
1871
391k
        _filter_entries.emplace(mapping.global_index, entry);
1872
391k
    }
1873
59.8k
    return Status::OK();
1874
59.8k
}
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
59.8k
        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
59.8k
    file_request->predicate_columns.clear();
1883
59.8k
    file_request->non_predicate_columns.clear();
1884
59.8k
    file_request->local_positions.clear();
1885
59.8k
    file_request->conjuncts.clear();
1886
59.8k
    file_request->delete_conjuncts.clear();
1887
59.8k
    _filter_entries.clear();
1888
    // 1. Build referenced non-predicate columns
1889
451k
    for (size_t column_idx = 0; column_idx < projected_columns.size(); ++column_idx) {
1890
391k
        const auto global_index = GlobalIndex(column_idx);
1891
391k
        auto* mapping = _find_mapping(global_index);
1892
391k
        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
371k
            bool used_by_filter = false;
1896
371k
            for (const auto& table_filter : table_filters) {
1897
89.2k
                const auto& global_indices = table_filter.global_indices;
1898
89.2k
                if (std::find(global_indices.begin(), global_indices.end(), global_index) !=
1899
89.2k
                            global_indices.end() &&
1900
89.2k
                    filter_conversion_has_local_source(mapping->filter_conversion)) {
1901
28.8k
                    used_by_filter = true;
1902
28.8k
                    break;
1903
28.8k
                }
1904
89.2k
            }
1905
371k
            if (!used_by_filter || !enable_lazy_materialization()) {
1906
343k
                RETURN_IF_ERROR(add_scan_column(file_request, mapping, false,
1907
343k
                                                force_full_complex_scan_projection()));
1908
343k
            }
1909
371k
        }
1910
391k
    }
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
59.8k
    RETURN_IF_ERROR(_build_hidden_filter_mappings(table_filters));
1914
59.8k
    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
391k
    for (auto& mapping : _mappings) {
1919
391k
        if (!mapping.file_local_id.has_value()) {
1920
19.6k
            continue;
1921
19.6k
        }
1922
371k
        auto position_it =
1923
371k
                file_request->local_positions.find(LocalColumnId(*mapping.file_local_id));
1924
371k
        DORIS_CHECK(position_it != file_request->local_positions.end())
1925
35
                << file_request->local_positions.size() << " " << *mapping.file_local_id << " "
1926
35
                << mapping.file_column_name;
1927
371k
        rebuild_projection(&mapping, position_it->second);
1928
371k
    }
1929
59.8k
    return Status::OK();
1930
59.8k
}
1931
1932
498k
ColumnMapping* TableColumnMapper::_find_mapping(GlobalIndex global_index) {
1933
8.05M
    for (auto& mapping : _mappings) {
1934
8.05M
        if (mapping.global_index == global_index) {
1935
498k
            return &mapping;
1936
498k
        }
1937
8.05M
    }
1938
82
    return nullptr;
1939
498k
}
1940
1941
74.3k
ColumnMapping* TableColumnMapper::_find_filter_mapping(GlobalIndex global_index) {
1942
74.4k
    if (auto* mapping = _find_mapping(global_index); mapping != nullptr) {
1943
74.4k
        return mapping;
1944
74.4k
    }
1945
18.4E
    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
18.4E
}
1952
1953
Status TableColumnMapper::localize_filters(const std::vector<TableFilter>& table_filters,
1954
                                           FileScanRequest* file_request,
1955
59.8k
                                           RuntimeState* runtime_state) {
1956
59.8k
    std::set<LocalColumnId> localized_predicate_columns;
1957
59.8k
    FilterProjectionMap filter_projections;
1958
59.8k
    auto filter_mappings = _filter_visible_mappings();
1959
59.8k
    RETURN_IF_ERROR(build_nested_struct_filter_projection_map(table_filters, filter_mappings,
1960
59.8k
                                                              &filter_projections));
1961
59.8k
    for (const auto& table_filter : table_filters) {
1962
41.0k
        for (const auto& global_index : table_filter.global_indices) {
1963
41.0k
            auto* mapping = _find_filter_mapping(global_index);
1964
41.0k
            if (mapping == nullptr || !mapping->file_local_id.has_value() ||
1965
41.0k
                !filter_conversion_has_local_source(mapping->filter_conversion)) {
1966
5.15k
                continue;
1967
5.15k
            }
1968
35.8k
            RETURN_IF_ERROR(add_scan_column(file_request, mapping, enable_lazy_materialization(),
1969
35.8k
                                            force_full_complex_scan_projection(),
1970
35.8k
                                            &filter_projections));
1971
35.8k
        }
1972
39.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
391k
    for (auto& mapping : _mappings) {
1976
391k
        if (mapping.file_local_id.has_value() &&
1977
391k
            file_request->local_positions.contains(LocalColumnId(*mapping.file_local_id))) {
1978
371k
            RETURN_IF_ERROR(apply_scan_projection_to_mapping_file_type(*file_request, &mapping));
1979
371k
        }
1980
391k
    }
1981
59.8k
    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
59.8k
    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
59.8k
    filter_mappings = _filter_visible_mappings();
1992
59.8k
    const auto global_to_file_slot = build_file_slot_rewrite_map(filter_mappings, _filter_entries);
1993
59.8k
    for (const auto& table_filter : table_filters) {
1994
39.9k
        if (table_filter.conjunct != nullptr &&
1995
39.9k
            table_filter_has_only_local_entries(table_filter, _filter_entries)) {
1996
35.0k
            RewriteContext rewrite_context {.runtime_state = runtime_state};
1997
35.0k
            VExprSPtr rewrite_root;
1998
35.0k
            Status clone_status;
1999
35.0k
            try {
2000
35.0k
                clone_status = clone_table_expr_tree(table_filter.conjunct->root(), &rewrite_root);
2001
35.0k
            } 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
35.0k
            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
35.0k
            bool can_localize = true;
2034
35.0k
            auto localized_root = rewrite_table_expr_to_file_expr(rewrite_root, global_to_file_slot,
2035
35.0k
                                                                  filter_mappings, &rewrite_context,
2036
35.0k
                                                                  &can_localize);
2037
35.0k
            if (!can_localize) {
2038
2.26k
                continue;
2039
2.26k
            }
2040
32.8k
            auto localized_conjunct = VExprContext::create_shared(std::move(localized_root));
2041
32.8k
            RETURN_IF_ERROR(rewrite_context.prepare_created_exprs(localized_conjunct.get()));
2042
32.8k
            file_request->conjuncts.push_back(std::move(localized_conjunct));
2043
33.4k
            for (const auto global_index : table_filter.global_indices) {
2044
33.4k
                const auto* mapping = _find_filter_mapping(global_index);
2045
33.4k
                if (mapping != nullptr && mapping->file_local_id.has_value() &&
2046
33.4k
                    filter_conversion_has_local_source(mapping->filter_conversion)) {
2047
33.3k
                    localized_predicate_columns.emplace(*mapping->file_local_id);
2048
33.3k
                }
2049
33.4k
            }
2050
32.8k
        }
2051
39.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
391k
    for (auto& mapping : _mappings) {
2058
391k
        if (!mapping.file_local_id.has_value()) {
2059
19.6k
            continue;
2060
19.6k
        }
2061
371k
        const auto local_id = LocalColumnId(*mapping.file_local_id);
2062
371k
        if (localized_predicate_columns.contains(local_id)) {
2063
26.4k
            continue;
2064
26.4k
        }
2065
345k
        const auto predicate_it = std::ranges::find_if(
2066
345k
                file_request->predicate_columns, [local_id](const LocalColumnIndex& projection) {
2067
45.2k
                    return projection.column_id() == local_id;
2068
45.2k
                });
2069
345k
        if (predicate_it == file_request->predicate_columns.end()) {
2070
342k
            continue;
2071
342k
        }
2072
2.46k
        file_request->non_predicate_columns.push_back(std::move(*predicate_it));
2073
2.46k
        file_request->predicate_columns.erase(predicate_it);
2074
2.46k
    }
2075
59.9k
    return Status::OK();
2076
59.8k
}
2077
2078
const ColumnDefinition* TableColumnMapper::_find_file_field(
2079
        const ColumnDefinition& table_column,
2080
341k
        const std::vector<ColumnDefinition>& file_schema) const {
2081
341k
    if (table_column.name.starts_with(BeConsts::GLOBAL_ROWID_COL)) {
2082
1.04M
        const auto field_it = std::ranges::find_if(file_schema, [](const ColumnDefinition& field) {
2083
1.04M
            return field.column_type == ColumnType::GLOBAL_ROWID;
2084
1.04M
        });
2085
7.52k
        return field_it == file_schema.end() ? nullptr : &*field_it;
2086
7.52k
    }
2087
334k
    return matcher_for_mode(_options.mode).find(table_column, file_schema);
2088
341k
}
2089
2090
Status TableColumnMapper::_create_direct_mapping(const ColumnDefinition& table_column,
2091
                                                 const ColumnDefinition& file_field,
2092
660k
                                                 ColumnMapping* mapping) const {
2093
660k
    DORIS_CHECK(mapping != nullptr);
2094
660k
    DORIS_CHECK(file_field.local_id >= 0 || file_field.local_id == GLOBAL_ROWID_COLUMN_ID);
2095
660k
    mapping->file_local_id = file_field.local_id;
2096
660k
    mapping->table_column_name = table_column.name;
2097
660k
    mapping->file_column_name = file_field.name;
2098
660k
    mapping->original_file_type = file_field.type;
2099
660k
    mapping->original_file_children = file_field.children;
2100
660k
    mapping->projected_file_children = file_field.children;
2101
660k
    mapping->file_type = file_field.type;
2102
660k
    mapping->is_trivial = mapping_can_use_file_column_directly(*mapping);
2103
660k
    mapping->filter_conversion = direct_filter_conversion(*mapping);
2104
660k
    mapping->child_mappings.clear();
2105
2106
660k
    auto [table_children, synthesized_table_children] =
2107
660k
            prepare_table_children_for_mapping(table_column, mapping->file_type);
2108
2109
660k
    if (!table_children.empty()) {
2110
190k
        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
190k
        RETURN_IF_ERROR(validate_file_schema_children(file_field));
2118
190k
        std::vector<int32_t> synthesized_used_file_child_ids;
2119
483k
        for (size_t table_child_idx = 0; table_child_idx < table_children.size();
2120
293k
             ++table_child_idx) {
2121
293k
            const auto& table_child = table_children[table_child_idx];
2122
293k
            const auto* file_child =
2123
293k
                    find_file_child_for_mapping(table_child, file_field, _options.mode,
2124
293k
                                                table_child_idx, synthesized_table_children);
2125
293k
            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
293k
            if (file_child == nullptr) {
2144
4.46k
                ColumnMapping child_mapping;
2145
4.46k
                child_mapping.table_column_name = table_child.name;
2146
4.46k
                child_mapping.file_column_name = table_child.name;
2147
4.46k
                child_mapping.table_type = table_child.type;
2148
4.46k
                child_mapping.file_type = table_child.type;
2149
4.46k
                child_mapping.filter_conversion = FilterConversionType::FINALIZE_ONLY;
2150
4.46k
                mapping->child_mappings.push_back(std::move(child_mapping));
2151
4.46k
                continue;
2152
4.46k
            }
2153
289k
            ColumnMapping child_mapping;
2154
289k
            child_mapping.table_column_name = table_child.name;
2155
289k
            child_mapping.table_type = table_child.type;
2156
289k
            RETURN_IF_ERROR(_create_direct_mapping(table_child, *file_child, &child_mapping));
2157
289k
            mapping->child_mappings.push_back(std::move(child_mapping));
2158
289k
        }
2159
190k
        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
16.9k
            RETURN_IF_ERROR(rebuild_projected_file_children_and_type(
2162
16.9k
                    mapping->file_type, mapping->original_file_children, mapping->child_mappings,
2163
16.9k
                    &mapping->projected_file_children, &mapping->file_type));
2164
16.9k
            DCHECK(mapping->table_type != nullptr);
2165
16.9k
            mapping->is_trivial = mapping_can_use_file_column_directly(*mapping);
2166
16.9k
            mapping->filter_conversion = projected_filter_conversion(*mapping);
2167
16.9k
        }
2168
190k
    }
2169
660k
    return Status::OK();
2170
660k
}
2171
2172
} // namespace doris::format