Coverage Report

Created: 2026-07-14 18:09

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