Coverage Report

Created: 2026-10-09 23:10

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