Coverage Report

Created: 2026-06-25 13:16

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