Coverage Report

Created: 2026-04-20 14:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format/generic_reader.h
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
#pragma once
19
20
#include <gen_cpp/PlanNodes_types.h>
21
22
#include <functional>
23
#include <memory>
24
#include <set>
25
#include <string>
26
#include <tuple>
27
#include <unordered_map>
28
#include <vector>
29
30
#include "common/status.h"
31
#include "core/column/column.h"
32
#include "core/column/column_nullable.h"
33
#include "core/data_type/data_type.h"
34
#include "exprs/vexpr.h"
35
#include "exprs/vexpr_context.h"
36
#include "exprs/vexpr_fwd.h"
37
#include "format/column_descriptor.h"
38
#include "format/table/table_schema_change_helper.h"
39
#include "runtime/descriptors.h"
40
#include "runtime/runtime_state.h"
41
#include "storage/predicate/block_column_predicate.h"
42
#include "storage/segment/common.h"
43
#include "util/profile_collector.h"
44
45
namespace doris {
46
class ColumnPredicate;
47
} // namespace doris
48
49
namespace doris {
50
51
class Block;
52
class VSlotRef;
53
54
// Context passed from FileScanner to readers for condition cache integration.
55
// On MISS: readers populate filter_result per-granule during predicate evaluation.
56
// On HIT: readers skip granules where filter_result[granule] == false.
57
struct ConditionCacheContext {
58
    bool is_hit = false;
59
    std::shared_ptr<std::vector<bool>> filter_result; // per-granule: true = has surviving rows
60
    int64_t base_granule = 0; // global granule index of the first granule in filter_result
61
    static constexpr int GRANULE_SIZE = 2048;
62
};
63
64
/// Base context for the unified init_reader(ReaderInitContext*) template method.
65
/// Contains fields shared by ALL reader types. Format-specific readers define
66
/// subclasses (ParquetInitContext, OrcInitContext, etc.) with extra fields.
67
/// FileScanner allocates the appropriate subclass and populates the shared fields
68
/// before calling init_reader().
69
struct ReaderInitContext {
70
103
    virtual ~ReaderInitContext() = default;
71
72
    // ---- Owned by FileScanner, shared by all readers ----
73
    std::vector<ColumnDescriptor>* column_descs = nullptr;
74
    std::unordered_map<std::string, uint32_t>* col_name_to_block_idx = nullptr;
75
    RuntimeState* state = nullptr;
76
    const TupleDescriptor* tuple_descriptor = nullptr;
77
    const RowDescriptor* row_descriptor = nullptr;
78
    const TFileScanRangeParams* params = nullptr;
79
    const TFileRangeDesc* range = nullptr;
80
    TPushAggOp::type push_down_agg_type = TPushAggOp::type::NONE;
81
82
    // ---- Output slots (populated by on_before_init_reader, consumed by _do_init_reader) ----
83
    // column_names: the list of file columns to read. Populated by on_before_init_reader
84
    // from column_descs (slot→name mapping). _do_init_reader uses this to configure the
85
    // format-specific parsing engine. For standalone readers (column_descs==nullptr),
86
    // callers populate column_names directly before calling init_reader.
87
    std::vector<std::string> column_names;
88
    std::shared_ptr<TableSchemaChangeHelper::Node> table_info_node =
89
            TableSchemaChangeHelper::ConstNode::get_instance();
90
    std::set<uint64_t> column_ids;
91
    std::set<uint64_t> filter_column_ids;
92
};
93
94
/// Safe downcast for ReaderInitContext subclasses.
95
/// Uses dynamic_cast + DORIS_CHECK: crashes on type mismatch (per Doris coding standards).
96
template <typename To, typename From>
97
102
To* checked_context_cast(From* ptr) {
98
102
    auto* result = dynamic_cast<To*>(ptr);
99
102
    DORIS_CHECK(result != nullptr);
100
102
    return result;
101
102
}
_ZN5doris20checked_context_castINS_14OrcInitContextENS_17ReaderInitContextEEEPT_PT0_
Line
Count
Source
97
36
To* checked_context_cast(From* ptr) {
98
36
    auto* result = dynamic_cast<To*>(ptr);
99
36
    DORIS_CHECK(result != nullptr);
100
36
    return result;
101
36
}
Unexecuted instantiation: _ZN5doris20checked_context_castINS_14CsvInitContextENS_17ReaderInitContextEEEPT_PT0_
Unexecuted instantiation: _ZN5doris20checked_context_castINS_15JsonInitContextENS_17ReaderInitContextEEEPT_PT0_
_ZN5doris20checked_context_castINS_18ParquetInitContextENS_17ReaderInitContextEEEPT_PT0_
Line
Count
Source
97
66
To* checked_context_cast(From* ptr) {
98
66
    auto* result = dynamic_cast<To*>(ptr);
99
66
    DORIS_CHECK(result != nullptr);
100
66
    return result;
101
66
}
Unexecuted instantiation: _ZN5doris20checked_context_castINS_14WalInitContextENS_17ReaderInitContextEEEPT_PT0_
102
103
/// Base reader interface for all file readers.
104
/// A GenericReader is responsible for reading a file and returning
105
/// a set of blocks with specified schema.
106
///
107
/// Provides hook virtual methods that implement the Template Method pattern:
108
///   init_reader:      _open_file_reader → on_before_init_reader → _do_init_reader → on_after_init_reader
109
///   get_next_block:   on_before_read_block → _do_get_next_block → on_after_read_block
110
///
111
/// Column-filling logic (partition/missing/synthesized) lives in TableFormatReader.
112
class GenericReader : public ProfileCollector {
113
public:
114
209
    GenericReader() : _push_down_agg_type(TPushAggOp::type::NONE) {}
115
114
    void set_push_down_agg_type(TPushAggOp::type push_down_agg_type) {
116
114
        _push_down_agg_type = push_down_agg_type;
117
114
    }
118
1
    TPushAggOp::type get_push_down_agg_type() const { return _push_down_agg_type; }
119
120
    /// Template method for reading blocks.
121
    /// Calls: on_before_read_block → _do_get_next_block → on_after_read_block
122
194
    Status get_next_block(Block* block, size_t* read_rows, bool* eof) {
123
194
        RETURN_IF_ERROR(on_before_read_block(block));
124
194
        RETURN_IF_ERROR(_do_get_next_block(block, read_rows, eof));
125
194
        RETURN_IF_ERROR(on_after_read_block(block, read_rows));
126
194
        return Status::OK();
127
194
    }
128
129
    // Type is always nullable to process illegal values.
130
    // Results are cached after the first successful call.
131
26
    Status get_columns(std::unordered_map<std::string, DataTypePtr>* name_to_type) {
132
26
        if (_get_columns_cached) {
133
0
            *name_to_type = _cached_name_to_type;
134
0
            return Status::OK();
135
0
        }
136
26
        RETURN_IF_ERROR(_get_columns_impl(name_to_type));
137
26
        _cached_name_to_type = *name_to_type;
138
26
        _get_columns_cached = true;
139
140
26
        return Status::OK();
141
26
    }
142
143
0
    virtual Status _get_columns_impl(std::unordered_map<std::string, DataTypePtr>* name_to_type) {
144
0
        return Status::NotSupported("get_columns is not implemented");
145
0
    }
146
147
    // This method is responsible for initializing the resource for parsing schema.
148
    // It will be called before `get_parsed_schema`.
149
0
    virtual Status init_schema_reader() {
150
0
        return Status::NotSupported("init_schema_reader is not implemented for this reader.");
151
0
    }
152
    // `col_types` is always nullable to process illegal values.
153
    virtual Status get_parsed_schema(std::vector<std::string>* col_names,
154
0
                                     std::vector<DataTypePtr>* col_types) {
155
0
        return Status::NotSupported("get_parsed_schema is not implemented for this reader.");
156
0
    }
157
209
    ~GenericReader() override = default;
158
159
11
    virtual Status close() { return Status::OK(); }
160
161
41
    Status read_by_rows(const std::list<int64_t>& row_ids) {
162
41
        _read_by_rows = true;
163
41
        _row_ids = row_ids;
164
41
        return _set_read_one_line_impl();
165
41
    }
166
167
    /// The reader is responsible for counting the number of rows read,
168
    /// because some readers, such as parquet/orc,
169
    /// can skip some pages/rowgroups through indexes.
170
0
    virtual bool count_read_rows() { return false; }
171
172
    /// Returns true if on_before_init_reader has already set _column_descs.
173
102
    bool has_column_descs() const { return _column_descs != nullptr; }
174
175
    /// Unified initialization entry point (NVI pattern).
176
    /// Enforces the template method sequence for ALL readers:
177
    ///   _open_file_reader → on_before_init_reader → _do_init_reader → on_after_init_reader
178
    /// Subclasses implement _open_file_reader and _do_init_reader(ReaderInitContext*).
179
    /// FileScanner constructs the appropriate ReaderInitContext subclass and calls this.
180
    ///
181
    /// NOTE: During migration, readers not yet ported to this API still use their
182
    /// format-specific init_reader(...) methods. This method is non-virtual so it
183
    /// cannot be accidentally overridden.
184
102
    Status init_reader(ReaderInitContext* ctx) {
185
        // Apply push_down_agg_type early so _open_file_reader and _do_init_reader
186
        // can use it (e.g., PaimonCppReader skips full init on COUNT pushdown).
187
        // on_after_init_reader may reset this (e.g., Iceberg with equality deletes).
188
102
        set_push_down_agg_type(ctx->push_down_agg_type);
189
190
102
        RETURN_IF_ERROR(_open_file_reader(ctx));
191
192
        // Standalone readers (delete file readers, push handler) set column_descs=nullptr
193
        // and pre-populate column_names directly. Skip hooks for them.
194
102
        if (ctx->column_descs != nullptr) {
195
36
            RETURN_IF_ERROR(on_before_init_reader(ctx));
196
36
        }
197
198
102
        RETURN_IF_ERROR(_do_init_reader(ctx));
199
200
102
        if (ctx->column_descs != nullptr) {
201
36
            RETURN_IF_ERROR(on_after_init_reader(ctx));
202
36
        }
203
204
102
        return Status::OK();
205
102
    }
206
207
    /// Hook called before core init. Default just sets _column_descs.
208
    /// TableFormatReader overrides with partition/missing column computation.
209
    /// ORC/Parquet/Hive/Iceberg further override with format-specific schema matching.
210
0
    virtual Status on_before_init_reader(ReaderInitContext* ctx) {
211
0
        _column_descs = ctx->column_descs;
212
0
        return Status::OK();
213
0
    }
214
215
protected:
216
    // ---- Init-time hooks (Template Method for init_reader) ----
217
218
    /// Opens the file and prepares I/O resources before hooks run. Override in
219
    /// subclasses to open files, read metadata, set up decompressors, etc.
220
    /// For Parquet/ORC, opens the file and reads footer metadata.
221
    /// For CSV/JSON, opens the file, creates decompressors, and sets up line readers.
222
    /// Default is no-op (for JNI, Native, Arrow readers).
223
0
    virtual Status _open_file_reader(ReaderInitContext* /*ctx*/) { return Status::OK(); }
224
225
    /// Core initialization (format-specific). Subclasses override to perform
226
    /// their actual parsing engine setup. The context should be downcast to
227
    /// the appropriate subclass using checked_context_cast<T>.
228
    /// Default returns NotSupported — readers not yet migrated to the unified
229
    /// init_reader(ReaderInitContext*) API still use their old init methods.
230
0
    virtual Status _do_init_reader(ReaderInitContext* /*ctx*/) {
231
0
        return Status::NotSupported(
232
0
                "_do_init_reader(ReaderInitContext*) not yet implemented for this reader");
233
0
    }
234
235
    // ---- Existing init-time hooks ----
236
237
    /// Called after core init completes. Subclasses override to process
238
    /// delete files, deletion vectors, etc.
239
36
    virtual Status on_after_init_reader(ReaderInitContext* /*ctx*/) { return Status::OK(); }
240
241
    // ---- Read-time hooks ----
242
243
    /// Called before reading a block. Subclasses override to modify block
244
    /// structure (e.g. add ACID columns, expand for equality delete).
245
192
    virtual Status on_before_read_block(Block* block) { return Status::OK(); }
246
247
    /// Core block reading. Subclasses must override with actual read logic.
248
    virtual Status _do_get_next_block(Block* block, size_t* read_rows, bool* eof) = 0;
249
250
    /// Called after reading a block. Subclasses override to post-process
251
    /// (e.g. remove ACID columns, apply equality delete filter).
252
18
    virtual Status on_after_read_block(Block* block, size_t* read_rows) { return Status::OK(); }
253
254
0
    virtual Status _set_read_one_line_impl() {
255
0
        return Status::NotSupported("read_by_rows is not implemented for this reader.");
256
0
    }
257
258
    const size_t _MIN_BATCH_SIZE = 4064; // 4094 - 32(padding)
259
260
    TPushAggOp::type _push_down_agg_type {};
261
262
public:
263
    // Pass condition cache context to the reader for HIT/MISS tracking.
264
0
    virtual void set_condition_cache_context(std::shared_ptr<ConditionCacheContext> ctx) {}
265
266
    // Returns true if this reader can produce an accurate total row count from metadata
267
    // without reading actual data. Used to determine if CountReader decorator can be applied.
268
    // Only ORC and Parquet readers support this (via file footer metadata).
269
0
    virtual bool supports_count_pushdown() const { return false; }
270
271
    // Returns the total number of rows the reader will produce.
272
    // Used to pre-allocate condition cache with the correct number of granules.
273
0
    virtual int64_t get_total_rows() const { return 0; }
274
275
    // Returns true if this reader has delete operations (e.g. Iceberg position/equality deletes,
276
    // Hive ACID deletes). Used to disable condition cache when deletes are present, since cached
277
    // granule results may become stale if delete files change between queries.
278
0
    virtual bool has_delete_operations() const { return false; }
279
280
protected:
281
    bool _read_by_rows = false;
282
    std::list<int64_t> _row_ids;
283
284
    // Cache to save some common part such as file footer.
285
    // Maybe null if not used
286
    FileMetaCache* _meta_cache = nullptr;
287
288
    // ---- Column descriptors (set by init_reader, owned by FileScanner) ----
289
    const std::vector<ColumnDescriptor>* _column_descs = nullptr;
290
291
    // ---- get_columns cache ----
292
    bool _get_columns_cached = false;
293
    std::unordered_map<std::string, DataTypePtr> _cached_name_to_type;
294
};
295
296
/// Provides an accessor for the current batch's row positions within the file.
297
/// Implemented by RowGroupReader (Parquet) and OrcReader.
298
class RowPositionProvider {
299
public:
300
120
    virtual ~RowPositionProvider() = default;
301
    virtual const std::vector<segment_v2::rowid_t>& current_batch_row_positions() const = 0;
302
};
303
304
} // namespace doris