Coverage Report

Created: 2026-03-21 15:29

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format/csv/csv_reader.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/csv/csv_reader.h"
19
20
#include <fmt/format.h>
21
#include <gen_cpp/PlanNodes_types.h>
22
#include <gen_cpp/Types_types.h>
23
#include <glog/logging.h>
24
25
#include <algorithm>
26
#include <cstddef>
27
#include <map>
28
#include <memory>
29
#include <ostream>
30
#include <regex>
31
#include <utility>
32
33
#include "common/compiler_util.h" // IWYU pragma: keep
34
#include "common/consts.h"
35
#include "common/status.h"
36
#include "core/block/block.h"
37
#include "core/block/column_with_type_and_name.h"
38
#include "core/data_type/data_type_factory.hpp"
39
#include "exec/scan/scanner.h"
40
#include "format/file_reader/new_plain_binary_line_reader.h"
41
#include "format/file_reader/new_plain_text_line_reader.h"
42
#include "format/line_reader.h"
43
#include "io/file_factory.h"
44
#include "io/fs/broker_file_reader.h"
45
#include "io/fs/buffered_reader.h"
46
#include "io/fs/file_reader.h"
47
#include "io/fs/s3_file_reader.h"
48
#include "io/fs/tracing_file_reader.h"
49
#include "runtime/descriptors.h"
50
#include "runtime/runtime_state.h"
51
#include "util/decompressor.h"
52
#include "util/string_util.h"
53
#include "util/utf8_check.h"
54
55
namespace doris {
56
class RuntimeProfile;
57
class IColumn;
58
namespace io {
59
struct IOContext;
60
enum class FileCachePolicy : uint8_t;
61
} // namespace io
62
} // namespace doris
63
64
namespace doris {
65
#include "common/compile_check_begin.h"
66
67
0
void EncloseCsvTextFieldSplitter::do_split(const Slice& line, std::vector<Slice>* splitted_values) {
68
0
    const char* data = line.data;
69
0
    const auto& column_sep_positions = _text_line_reader_ctx->column_sep_positions();
70
0
    size_t value_start_offset = 0;
71
0
    for (auto idx : column_sep_positions) {
72
0
        process_value_func(data, value_start_offset, idx - value_start_offset, _trimming_char,
73
0
                           splitted_values);
74
0
        value_start_offset = idx + _value_sep_len;
75
0
    }
76
0
    if (line.size >= value_start_offset) {
77
        // process the last column
78
0
        process_value_func(data, value_start_offset, line.size - value_start_offset, _trimming_char,
79
0
                           splitted_values);
80
0
    }
81
0
}
82
83
void PlainCsvTextFieldSplitter::_split_field_single_char(const Slice& line,
84
0
                                                         std::vector<Slice>* splitted_values) {
85
0
    const char* data = line.data;
86
0
    const size_t size = line.size;
87
0
    size_t value_start = 0;
88
0
    for (size_t i = 0; i < size; ++i) {
89
0
        if (data[i] == _value_sep[0]) {
90
0
            process_value_func(data, value_start, i - value_start, _trimming_char, splitted_values);
91
0
            value_start = i + _value_sep_len;
92
0
        }
93
0
    }
94
0
    process_value_func(data, value_start, size - value_start, _trimming_char, splitted_values);
95
0
}
96
97
void PlainCsvTextFieldSplitter::_split_field_multi_char(const Slice& line,
98
0
                                                        std::vector<Slice>* splitted_values) {
99
0
    size_t start = 0;  // point to the start pos of next col value.
100
0
    size_t curpos = 0; // point to the start pos of separator matching sequence.
101
102
    // value_sep : AAAA
103
    // line.data : 1234AAAA5678
104
    // -> 1234,5678
105
106
    //    start   start
107
    //      ▼       ▼
108
    //      1234AAAA5678\0
109
    //          ▲       ▲
110
    //      curpos     curpos
111
112
    //kmp
113
0
    std::vector<int> next(_value_sep_len);
114
0
    next[0] = -1;
115
0
    for (int i = 1, j = -1; i < _value_sep_len; i++) {
116
0
        while (j > -1 && _value_sep[i] != _value_sep[j + 1]) {
117
0
            j = next[j];
118
0
        }
119
0
        if (_value_sep[i] == _value_sep[j + 1]) {
120
0
            j++;
121
0
        }
122
0
        next[i] = j;
123
0
    }
124
125
0
    for (int i = 0, j = -1; i < line.size; i++) {
126
        // i : line
127
        // j : _value_sep
128
0
        while (j > -1 && line[i] != _value_sep[j + 1]) {
129
0
            j = next[j];
130
0
        }
131
0
        if (line[i] == _value_sep[j + 1]) {
132
0
            j++;
133
0
        }
134
0
        if (j == _value_sep_len - 1) {
135
0
            curpos = i - _value_sep_len + 1;
136
137
            /*
138
             * column_separator : "xx"
139
             * data.csv :  data1xxxxdata2
140
             *
141
             * Parse incorrectly:
142
             *      data1[xx]xxdata2
143
             *      data1x[xx]xdata2
144
             *      data1xx[xx]data2
145
             * The string "xxxx" is parsed into three "xx" delimiters.
146
             *
147
             * Parse correctly:
148
             *      data1[xx]xxdata2
149
             *      data1xx[xx]data2
150
             */
151
152
0
            if (curpos >= start) {
153
0
                process_value_func(line.data, start, curpos - start, _trimming_char,
154
0
                                   splitted_values);
155
0
                start = i + 1;
156
0
            }
157
158
0
            j = next[j];
159
0
        }
160
0
    }
161
0
    process_value_func(line.data, start, line.size - start, _trimming_char, splitted_values);
162
0
}
163
164
0
void PlainCsvTextFieldSplitter::do_split(const Slice& line, std::vector<Slice>* splitted_values) {
165
0
    if (is_single_char_delim) {
166
0
        _split_field_single_char(line, splitted_values);
167
0
    } else {
168
0
        _split_field_multi_char(line, splitted_values);
169
0
    }
170
0
}
171
172
CsvReader::CsvReader(RuntimeState* state, RuntimeProfile* profile, ScannerCounter* counter,
173
                     const TFileScanRangeParams& params, const TFileRangeDesc& range,
174
                     const std::vector<SlotDescriptor*>& file_slot_descs, io::IOContext* io_ctx,
175
                     std::shared_ptr<io::IOContext> io_ctx_holder)
176
0
        : _profile(profile),
177
0
          _params(params),
178
0
          _file_reader(nullptr),
179
0
          _line_reader(nullptr),
180
0
          _decompressor(nullptr),
181
0
          _state(state),
182
0
          _counter(counter),
183
0
          _range(range),
184
0
          _file_slot_descs(file_slot_descs),
185
0
          _line_reader_eof(false),
186
0
          _skip_lines(0),
187
0
          _io_ctx(io_ctx),
188
0
          _io_ctx_holder(std::move(io_ctx_holder)) {
189
0
    if (_io_ctx == nullptr && _io_ctx_holder) {
190
0
        _io_ctx = _io_ctx_holder.get();
191
0
    }
192
0
    _file_format_type = _params.format_type;
193
0
    _is_proto_format = _file_format_type == TFileFormatType::FORMAT_PROTO;
194
0
    if (_range.__isset.compress_type) {
195
        // for compatibility
196
0
        _file_compress_type = _range.compress_type;
197
0
    } else {
198
0
        _file_compress_type = _params.compress_type;
199
0
    }
200
0
    _size = _range.size;
201
202
0
    _split_values.reserve(_file_slot_descs.size());
203
0
    _init_system_properties();
204
0
    _init_file_description();
205
0
    _serdes = create_data_type_serdes(_file_slot_descs);
206
0
}
207
208
0
void CsvReader::_init_system_properties() {
209
0
    if (_range.__isset.file_type) {
210
        // for compatibility
211
0
        _system_properties.system_type = _range.file_type;
212
0
    } else {
213
0
        _system_properties.system_type = _params.file_type;
214
0
    }
215
0
    _system_properties.properties = _params.properties;
216
0
    _system_properties.hdfs_params = _params.hdfs_params;
217
0
    if (_params.__isset.broker_addresses) {
218
0
        _system_properties.broker_addresses.assign(_params.broker_addresses.begin(),
219
0
                                                   _params.broker_addresses.end());
220
0
    }
221
0
}
222
223
0
void CsvReader::_init_file_description() {
224
0
    _file_description.path = _range.path;
225
0
    _file_description.file_size = _range.__isset.file_size ? _range.file_size : -1;
226
0
    if (_range.__isset.fs_name) {
227
0
        _file_description.fs_name = _range.fs_name;
228
0
    }
229
0
    if (_range.__isset.file_cache_admission) {
230
0
        _file_description.file_cache_admission = _range.file_cache_admission;
231
0
    }
232
0
}
233
234
0
Status CsvReader::init_reader(bool is_load) {
235
    // set the skip lines and start offset
236
0
    _start_offset = _range.start_offset;
237
0
    if (_start_offset == 0) {
238
        // check header typer first
239
0
        if (_params.__isset.file_attributes && _params.file_attributes.__isset.header_type &&
240
0
            !_params.file_attributes.header_type.empty()) {
241
0
            std::string header_type = to_lower(_params.file_attributes.header_type);
242
0
            if (header_type == BeConsts::CSV_WITH_NAMES) {
243
0
                _skip_lines = 1;
244
0
            } else if (header_type == BeConsts::CSV_WITH_NAMES_AND_TYPES) {
245
0
                _skip_lines = 2;
246
0
            }
247
0
        } else if (_params.file_attributes.__isset.skip_lines) {
248
0
            _skip_lines = _params.file_attributes.skip_lines;
249
0
        }
250
0
    } else if (_start_offset != 0) {
251
0
        if ((_file_compress_type != TFileCompressType::PLAIN) ||
252
0
            (_file_compress_type == TFileCompressType::UNKNOWN &&
253
0
             _file_format_type != TFileFormatType::FORMAT_CSV_PLAIN)) {
254
0
            return Status::InternalError<false>("For now we do not support split compressed file");
255
0
        }
256
        // pre-read to promise first line skipped always read
257
0
        int64_t pre_read_len = std::min(
258
0
                static_cast<int64_t>(_params.file_attributes.text_params.line_delimiter.size()),
259
0
                _start_offset);
260
0
        _start_offset -= pre_read_len;
261
0
        _size += pre_read_len;
262
        // not first range will always skip one line
263
0
        _skip_lines = 1;
264
0
    }
265
266
0
    _use_nullable_string_opt.resize(_file_slot_descs.size());
267
0
    for (int i = 0; i < _file_slot_descs.size(); ++i) {
268
0
        auto data_type_ptr = _file_slot_descs[i]->get_data_type_ptr();
269
0
        if (data_type_ptr->is_nullable() && is_string_type(data_type_ptr->get_primitive_type())) {
270
0
            _use_nullable_string_opt[i] = 1;
271
0
        }
272
0
    }
273
274
0
    RETURN_IF_ERROR(_init_options());
275
0
    RETURN_IF_ERROR(_create_file_reader(false));
276
0
    RETURN_IF_ERROR(_create_decompressor());
277
0
    RETURN_IF_ERROR(_create_line_reader());
278
279
0
    _is_load = is_load;
280
0
    if (!_is_load) {
281
        // For query task, there are 2 slot mapping.
282
        // One is from file slot to values in line.
283
        //      eg, the file_slot_descs is k1, k3, k5, and values in line are k1, k2, k3, k4, k5
284
        //      the _col_idxs will save: 0, 2, 4
285
        // The other is from file slot to columns in output block
286
        //      eg, the file_slot_descs is k1, k3, k5, and columns in block are p1, k1, k3, k5
287
        //      where "p1" is the partition col which does not exist in file
288
        //      the _file_slot_idx_map will save: 1, 2, 3
289
0
        DCHECK(_params.__isset.column_idxs);
290
0
        _col_idxs = _params.column_idxs;
291
0
        int idx = 0;
292
0
        for (const auto& slot_info : _params.required_slots) {
293
0
            if (slot_info.is_file_slot) {
294
0
                _file_slot_idx_map.push_back(idx);
295
0
            }
296
0
            idx++;
297
0
        }
298
0
    } else {
299
        // For load task, the column order is same as file column order
300
0
        int i = 0;
301
0
        for (const auto& desc [[maybe_unused]] : _file_slot_descs) {
302
0
            _col_idxs.push_back(i++);
303
0
        }
304
0
    }
305
306
0
    _line_reader_eof = false;
307
0
    return Status::OK();
308
0
}
309
310
// !FIXME: Here we should use MutableBlock
311
0
Status CsvReader::get_next_block(Block* block, size_t* read_rows, bool* eof) {
312
0
    if (_line_reader_eof) {
313
0
        *eof = true;
314
0
        return Status::OK();
315
0
    }
316
317
0
    const int batch_size = std::max(_state->batch_size(), (int)_MIN_BATCH_SIZE);
318
0
    size_t rows = 0;
319
320
0
    bool success = false;
321
0
    bool is_remove_bom = false;
322
0
    if (_push_down_agg_type == TPushAggOp::type::COUNT) {
323
0
        while (rows < batch_size && !_line_reader_eof) {
324
0
            const uint8_t* ptr = nullptr;
325
0
            size_t size = 0;
326
0
            RETURN_IF_ERROR(_line_reader->read_line(&ptr, &size, &_line_reader_eof, _io_ctx));
327
328
            // _skip_lines == 0 means this line is the actual data beginning line for the entire file
329
            // is_remove_bom means _remove_bom should only execute once
330
0
            if (_skip_lines == 0 && !is_remove_bom) {
331
0
                ptr = _remove_bom(ptr, size);
332
0
                is_remove_bom = true;
333
0
            }
334
335
            // _skip_lines > 0 means we do not need to remove bom
336
0
            if (_skip_lines > 0) {
337
0
                _skip_lines--;
338
0
                is_remove_bom = true;
339
0
                continue;
340
0
            }
341
0
            if (size == 0) {
342
0
                if (!_line_reader_eof && _state->is_read_csv_empty_line_as_null()) {
343
0
                    ++rows;
344
0
                }
345
                // Read empty line, continue
346
0
                continue;
347
0
            }
348
349
0
            RETURN_IF_ERROR(_validate_line(Slice(ptr, size), &success));
350
0
            ++rows;
351
0
        }
352
0
        auto mutate_columns = block->mutate_columns();
353
0
        for (auto& col : mutate_columns) {
354
0
            col->resize(rows);
355
0
        }
356
0
        block->set_columns(std::move(mutate_columns));
357
0
    } else {
358
0
        auto columns = block->mutate_columns();
359
0
        while (rows < batch_size && !_line_reader_eof) {
360
0
            const uint8_t* ptr = nullptr;
361
0
            size_t size = 0;
362
0
            RETURN_IF_ERROR(_line_reader->read_line(&ptr, &size, &_line_reader_eof, _io_ctx));
363
364
            // _skip_lines == 0 means this line is the actual data beginning line for the entire file
365
            // is_remove_bom means _remove_bom should only execute once
366
0
            if (!is_remove_bom && _skip_lines == 0) {
367
0
                ptr = _remove_bom(ptr, size);
368
0
                is_remove_bom = true;
369
0
            }
370
371
            // _skip_lines > 0 means we do not remove bom
372
0
            if (_skip_lines > 0) {
373
0
                _skip_lines--;
374
0
                is_remove_bom = true;
375
0
                continue;
376
0
            }
377
0
            if (size == 0) {
378
0
                if (!_line_reader_eof && _state->is_read_csv_empty_line_as_null()) {
379
0
                    RETURN_IF_ERROR(_fill_empty_line(block, columns, &rows));
380
0
                }
381
                // Read empty line, continue
382
0
                continue;
383
0
            }
384
385
0
            RETURN_IF_ERROR(_validate_line(Slice(ptr, size), &success));
386
0
            if (!success) {
387
0
                continue;
388
0
            }
389
0
            RETURN_IF_ERROR(_fill_dest_columns(Slice(ptr, size), block, columns, &rows));
390
0
        }
391
0
        block->set_columns(std::move(columns));
392
0
    }
393
394
0
    *eof = (rows == 0);
395
0
    *read_rows = rows;
396
397
0
    return Status::OK();
398
0
}
399
400
Status CsvReader::get_columns(std::unordered_map<std::string, DataTypePtr>* name_to_type,
401
0
                              std::unordered_set<std::string>* missing_cols) {
402
0
    for (const auto& slot : _file_slot_descs) {
403
0
        name_to_type->emplace(slot->col_name(), slot->type());
404
0
    }
405
0
    return Status::OK();
406
0
}
407
408
// init decompressor, file reader and line reader for parsing schema
409
0
Status CsvReader::init_schema_reader() {
410
0
    _start_offset = _range.start_offset;
411
0
    if (_start_offset != 0) {
412
0
        return Status::InvalidArgument(
413
0
                "start offset of TFileRangeDesc must be zero in get parsered schema");
414
0
    }
415
0
    if (_params.file_type == TFileType::FILE_BROKER) {
416
0
        return Status::InternalError<false>(
417
0
                "Getting parsered schema from csv file do not support stream load and broker "
418
0
                "load.");
419
0
    }
420
421
    // csv file without names line and types line.
422
0
    _read_line = 1;
423
0
    _is_parse_name = false;
424
425
0
    if (_params.__isset.file_attributes && _params.file_attributes.__isset.header_type &&
426
0
        !_params.file_attributes.header_type.empty()) {
427
0
        std::string header_type = to_lower(_params.file_attributes.header_type);
428
0
        if (header_type == BeConsts::CSV_WITH_NAMES) {
429
0
            _is_parse_name = true;
430
0
        } else if (header_type == BeConsts::CSV_WITH_NAMES_AND_TYPES) {
431
0
            _read_line = 2;
432
0
            _is_parse_name = true;
433
0
        }
434
0
    }
435
436
0
    RETURN_IF_ERROR(_init_options());
437
0
    RETURN_IF_ERROR(_create_file_reader(true));
438
0
    RETURN_IF_ERROR(_create_decompressor());
439
0
    RETURN_IF_ERROR(_create_line_reader());
440
0
    return Status::OK();
441
0
}
442
443
Status CsvReader::get_parsed_schema(std::vector<std::string>* col_names,
444
0
                                    std::vector<DataTypePtr>* col_types) {
445
0
    if (_read_line == 1) {
446
0
        if (!_is_parse_name) { //parse csv file without names and types
447
0
            size_t col_nums = 0;
448
0
            RETURN_IF_ERROR(_parse_col_nums(&col_nums));
449
0
            for (size_t i = 0; i < col_nums; ++i) {
450
0
                col_names->emplace_back("c" + std::to_string(i + 1));
451
0
            }
452
0
        } else { // parse csv file with names
453
0
            RETURN_IF_ERROR(_parse_col_names(col_names));
454
0
        }
455
456
0
        for (size_t j = 0; j < col_names->size(); ++j) {
457
0
            col_types->emplace_back(
458
0
                    DataTypeFactory::instance().create_data_type(PrimitiveType::TYPE_STRING, true));
459
0
        }
460
0
    } else { // parse csv file with names and types
461
0
        RETURN_IF_ERROR(_parse_col_names(col_names));
462
0
        RETURN_IF_ERROR(_parse_col_types(col_names->size(), col_types));
463
0
    }
464
0
    return Status::OK();
465
0
}
466
467
0
Status CsvReader::_deserialize_nullable_string(IColumn& column, Slice& slice) {
468
0
    auto& null_column = assert_cast<ColumnNullable&>(column);
469
0
    if (_empty_field_as_null) {
470
0
        if (slice.size == 0) {
471
0
            null_column.insert_data(nullptr, 0);
472
0
            return Status::OK();
473
0
        }
474
0
    }
475
0
    if (_options.null_len > 0 && !(_options.converted_from_string && slice.trim_double_quotes())) {
476
0
        if (slice.compare(Slice(_options.null_format, _options.null_len)) == 0) {
477
0
            null_column.insert_data(nullptr, 0);
478
0
            return Status::OK();
479
0
        }
480
0
    }
481
0
    static DataTypeStringSerDe stringSerDe(TYPE_STRING);
482
0
    auto st = stringSerDe.deserialize_one_cell_from_csv(null_column.get_nested_column(), slice,
483
0
                                                        _options);
484
0
    if (!st.ok()) {
485
        // fill null if fail
486
0
        null_column.insert_data(nullptr, 0); // 0 is meaningless here
487
0
        return Status::OK();
488
0
    }
489
    // fill not null if success
490
0
    null_column.get_null_map_data().push_back(0);
491
0
    return Status::OK();
492
0
}
493
494
0
Status CsvReader::_init_options() {
495
    // get column_separator and line_delimiter
496
0
    _value_separator = _params.file_attributes.text_params.column_separator;
497
0
    _value_separator_length = _value_separator.size();
498
0
    _line_delimiter = _params.file_attributes.text_params.line_delimiter;
499
0
    _line_delimiter_length = _line_delimiter.size();
500
0
    if (_params.file_attributes.text_params.__isset.enclose) {
501
0
        _enclose = _params.file_attributes.text_params.enclose;
502
0
    }
503
0
    if (_params.file_attributes.text_params.__isset.escape) {
504
0
        _escape = _params.file_attributes.text_params.escape;
505
0
    }
506
507
0
    _trim_tailing_spaces =
508
0
            (_state != nullptr && _state->trim_tailing_spaces_for_external_table_query());
509
510
0
    _options.escape_char = _escape;
511
0
    _options.quote_char = _enclose;
512
513
0
    if (_params.file_attributes.text_params.collection_delimiter.empty()) {
514
0
        _options.collection_delim = ',';
515
0
    } else {
516
0
        _options.collection_delim = _params.file_attributes.text_params.collection_delimiter[0];
517
0
    }
518
0
    if (_params.file_attributes.text_params.mapkv_delimiter.empty()) {
519
0
        _options.map_key_delim = ':';
520
0
    } else {
521
0
        _options.map_key_delim = _params.file_attributes.text_params.mapkv_delimiter[0];
522
0
    }
523
524
0
    if (_params.file_attributes.text_params.__isset.null_format) {
525
0
        _options.null_format = _params.file_attributes.text_params.null_format.data();
526
0
        _options.null_len = _params.file_attributes.text_params.null_format.length();
527
0
    }
528
529
0
    if (_params.file_attributes.__isset.trim_double_quotes) {
530
0
        _trim_double_quotes = _params.file_attributes.trim_double_quotes;
531
0
    }
532
0
    _options.converted_from_string = _trim_double_quotes;
533
534
0
    if (_state != nullptr) {
535
0
        _keep_cr = _state->query_options().keep_carriage_return;
536
0
    }
537
538
0
    if (_params.file_attributes.text_params.__isset.empty_field_as_null) {
539
0
        _empty_field_as_null = _params.file_attributes.text_params.empty_field_as_null;
540
0
    }
541
0
    return Status::OK();
542
0
}
543
544
0
Status CsvReader::_create_decompressor() {
545
0
    if (_file_compress_type != TFileCompressType::UNKNOWN) {
546
0
        RETURN_IF_ERROR(Decompressor::create_decompressor(_file_compress_type, &_decompressor));
547
0
    } else {
548
0
        RETURN_IF_ERROR(Decompressor::create_decompressor(_file_format_type, &_decompressor));
549
0
    }
550
551
0
    return Status::OK();
552
0
}
553
554
0
Status CsvReader::_create_file_reader(bool need_schema) {
555
0
    if (_params.file_type == TFileType::FILE_STREAM) {
556
0
        RETURN_IF_ERROR(FileFactory::create_pipe_reader(_range.load_id, &_file_reader, _state,
557
0
                                                        need_schema));
558
0
    } else {
559
0
        _file_description.mtime = _range.__isset.modification_time ? _range.modification_time : 0;
560
0
        io::FileReaderOptions reader_options =
561
0
                FileFactory::get_reader_options(_state, _file_description);
562
0
        io::FileReaderSPtr file_reader;
563
0
        if (_io_ctx_holder) {
564
0
            file_reader = DORIS_TRY(io::DelegateReader::create_file_reader(
565
0
                    _profile, _system_properties, _file_description, reader_options,
566
0
                    io::DelegateReader::AccessMode::SEQUENTIAL,
567
0
                    std::static_pointer_cast<const io::IOContext>(_io_ctx_holder),
568
0
                    io::PrefetchRange(_range.start_offset, _range.start_offset + _range.size)));
569
0
        } else {
570
0
            file_reader = DORIS_TRY(io::DelegateReader::create_file_reader(
571
0
                    _profile, _system_properties, _file_description, reader_options,
572
0
                    io::DelegateReader::AccessMode::SEQUENTIAL, _io_ctx,
573
0
                    io::PrefetchRange(_range.start_offset, _range.start_offset + _range.size)));
574
0
        }
575
0
        _file_reader = _io_ctx ? std::make_shared<io::TracingFileReader>(std::move(file_reader),
576
0
                                                                         _io_ctx->file_reader_stats)
577
0
                               : file_reader;
578
0
    }
579
0
    if (_file_reader->size() == 0 && _params.file_type != TFileType::FILE_STREAM &&
580
0
        _params.file_type != TFileType::FILE_BROKER) {
581
0
        return Status::EndOfFile("init reader failed, empty csv file: " + _range.path);
582
0
    }
583
0
    return Status::OK();
584
0
}
585
586
0
Status CsvReader::_create_line_reader() {
587
0
    std::shared_ptr<TextLineReaderContextIf> text_line_reader_ctx;
588
0
    if (_enclose == 0) {
589
0
        text_line_reader_ctx = std::make_shared<PlainTextLineReaderCtx>(
590
0
                _line_delimiter, _line_delimiter_length, _keep_cr);
591
0
        _fields_splitter = std::make_unique<PlainCsvTextFieldSplitter>(
592
0
                _trim_tailing_spaces, false, _value_separator, _value_separator_length, -1);
593
594
0
    } else {
595
        // in load task, the _file_slot_descs is empty vector, so we need to set col_sep_num to 0
596
0
        size_t col_sep_num = _file_slot_descs.size() > 1 ? _file_slot_descs.size() - 1 : 0;
597
0
        _enclose_reader_ctx = std::make_shared<EncloseCsvLineReaderCtx>(
598
0
                _line_delimiter, _line_delimiter_length, _value_separator, _value_separator_length,
599
0
                col_sep_num, _enclose, _escape, _keep_cr);
600
0
        text_line_reader_ctx = _enclose_reader_ctx;
601
602
0
        _fields_splitter = std::make_unique<EncloseCsvTextFieldSplitter>(
603
0
                _trim_tailing_spaces, true, _enclose_reader_ctx, _value_separator_length, _enclose);
604
0
    }
605
0
    switch (_file_format_type) {
606
0
    case TFileFormatType::FORMAT_CSV_PLAIN:
607
0
        [[fallthrough]];
608
0
    case TFileFormatType::FORMAT_CSV_GZ:
609
0
        [[fallthrough]];
610
0
    case TFileFormatType::FORMAT_CSV_BZ2:
611
0
        [[fallthrough]];
612
0
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
613
0
        [[fallthrough]];
614
0
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
615
0
        [[fallthrough]];
616
0
    case TFileFormatType::FORMAT_CSV_LZOP:
617
0
        [[fallthrough]];
618
0
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
619
0
        [[fallthrough]];
620
0
    case TFileFormatType::FORMAT_CSV_DEFLATE:
621
0
        _line_reader =
622
0
                NewPlainTextLineReader::create_unique(_profile, _file_reader, _decompressor.get(),
623
0
                                                      text_line_reader_ctx, _size, _start_offset);
624
625
0
        break;
626
0
    case TFileFormatType::FORMAT_PROTO:
627
0
        _fields_splitter = std::make_unique<CsvProtoFieldSplitter>();
628
0
        _line_reader = NewPlainBinaryLineReader::create_unique(_file_reader);
629
0
        break;
630
0
    default:
631
0
        return Status::InternalError<false>(
632
0
                "Unknown format type, cannot init line reader in csv reader, type={}",
633
0
                _file_format_type);
634
0
    }
635
0
    return Status::OK();
636
0
}
637
638
0
Status CsvReader::_deserialize_one_cell(DataTypeSerDeSPtr serde, IColumn& column, Slice& slice) {
639
0
    return serde->deserialize_one_cell_from_csv(column, slice, _options);
640
0
}
641
642
Status CsvReader::_fill_dest_columns(const Slice& line, Block* block,
643
0
                                     std::vector<MutableColumnPtr>& columns, size_t* rows) {
644
0
    bool is_success = false;
645
646
0
    RETURN_IF_ERROR(_line_split_to_values(line, &is_success));
647
0
    if (UNLIKELY(!is_success)) {
648
        // If not success, which means we met an invalid row, filter this row and return.
649
0
        return Status::OK();
650
0
    }
651
652
0
    for (int i = 0; i < _file_slot_descs.size(); ++i) {
653
0
        int col_idx = _col_idxs[i];
654
        // col idx is out of range, fill with null format
655
0
        auto value = col_idx < _split_values.size()
656
0
                             ? _split_values[col_idx]
657
0
                             : Slice(_options.null_format, _options.null_len);
658
659
0
        IColumn* col_ptr = columns[i].get();
660
0
        if (!_is_load) {
661
            // block is a Block*, and get_by_position returns a ColumnPtr,
662
            // which is a const pointer. Therefore, using const_cast is permissible.
663
0
            col_ptr = const_cast<IColumn*>(
664
0
                    block->get_by_position(_file_slot_idx_map[i]).column.get());
665
0
        }
666
667
0
        if (_use_nullable_string_opt[i]) {
668
            // For load task, we always read "string" from file.
669
            // So serdes[i] here must be DataTypeNullableSerDe, and DataTypeNullableSerDe -> nested_serde must be DataTypeStringSerDe.
670
            // So we use deserialize_nullable_string and stringSerDe to reduce virtual function calls.
671
0
            RETURN_IF_ERROR(_deserialize_nullable_string(*col_ptr, value));
672
0
        } else {
673
0
            RETURN_IF_ERROR(_deserialize_one_cell(_serdes[i], *col_ptr, value));
674
0
        }
675
0
    }
676
0
    ++(*rows);
677
678
0
    return Status::OK();
679
0
}
680
681
Status CsvReader::_fill_empty_line(Block* block, std::vector<MutableColumnPtr>& columns,
682
0
                                   size_t* rows) {
683
0
    for (int i = 0; i < _file_slot_descs.size(); ++i) {
684
0
        IColumn* col_ptr = columns[i].get();
685
0
        if (!_is_load) {
686
            // block is a Block*, and get_by_position returns a ColumnPtr,
687
            // which is a const pointer. Therefore, using const_cast is permissible.
688
0
            col_ptr = const_cast<IColumn*>(
689
0
                    block->get_by_position(_file_slot_idx_map[i]).column.get());
690
0
        }
691
0
        auto& null_column = assert_cast<ColumnNullable&>(*col_ptr);
692
0
        null_column.insert_data(nullptr, 0);
693
0
    }
694
0
    ++(*rows);
695
0
    return Status::OK();
696
0
}
697
698
0
Status CsvReader::_validate_line(const Slice& line, bool* success) {
699
0
    if (!_is_proto_format && !validate_utf8(_params, line.data, line.size)) {
700
0
        if (!_is_load) {
701
0
            return Status::InternalError<false>("Only support csv data in utf8 codec");
702
0
        } else {
703
0
            _counter->num_rows_filtered++;
704
0
            *success = false;
705
0
            RETURN_IF_ERROR(_state->append_error_msg_to_file(
706
0
                    [&]() -> std::string { return std::string(line.data, line.size); },
707
0
                    [&]() -> std::string {
708
0
                        return "Invalid file encoding: all CSV files must be UTF-8 encoded";
709
0
                    }));
710
0
            return Status::OK();
711
0
        }
712
0
    }
713
0
    *success = true;
714
0
    return Status::OK();
715
0
}
716
717
0
Status CsvReader::_line_split_to_values(const Slice& line, bool* success) {
718
0
    _split_line(line);
719
720
0
    if (_is_load) {
721
        // Only check for load task. For query task, the non exist column will be filled "null".
722
        // if actual column number in csv file is not equal to _file_slot_descs.size()
723
        // then filter this line.
724
0
        bool ignore_col = false;
725
0
        ignore_col = _params.__isset.file_attributes &&
726
0
                     _params.file_attributes.__isset.ignore_csv_redundant_col &&
727
0
                     _params.file_attributes.ignore_csv_redundant_col;
728
729
0
        if ((!ignore_col && _split_values.size() != _file_slot_descs.size()) ||
730
0
            (ignore_col && _split_values.size() < _file_slot_descs.size())) {
731
0
            _counter->num_rows_filtered++;
732
0
            *success = false;
733
0
            RETURN_IF_ERROR(_state->append_error_msg_to_file(
734
0
                    [&]() -> std::string { return std::string(line.data, line.size); },
735
0
                    [&]() -> std::string {
736
0
                        fmt::memory_buffer error_msg;
737
0
                        fmt::format_to(error_msg,
738
0
                                       "Column count mismatch: expected {}, but found {}",
739
0
                                       _file_slot_descs.size(), _split_values.size());
740
0
                        std::string escaped_separator =
741
0
                                std::regex_replace(_value_separator, std::regex("\t"), "\\t");
742
0
                        std::string escaped_delimiter =
743
0
                                std::regex_replace(_line_delimiter, std::regex("\n"), "\\n");
744
0
                        fmt::format_to(error_msg, " (sep:{} delim:{}", escaped_separator,
745
0
                                       escaped_delimiter);
746
0
                        if (_enclose != 0) {
747
0
                            fmt::format_to(error_msg, " encl:{}", _enclose);
748
0
                        }
749
0
                        if (_escape != 0) {
750
0
                            fmt::format_to(error_msg, " esc:{}", _escape);
751
0
                        }
752
0
                        fmt::format_to(error_msg, ")");
753
0
                        return fmt::to_string(error_msg);
754
0
                    }));
755
0
            return Status::OK();
756
0
        }
757
0
    }
758
759
0
    *success = true;
760
0
    return Status::OK();
761
0
}
762
763
0
void CsvReader::_split_line(const Slice& line) {
764
0
    _split_values.clear();
765
0
    _fields_splitter->split_line(line, &_split_values);
766
0
}
767
768
0
Status CsvReader::_parse_col_nums(size_t* col_nums) {
769
0
    const uint8_t* ptr = nullptr;
770
0
    size_t size = 0;
771
0
    RETURN_IF_ERROR(_line_reader->read_line(&ptr, &size, &_line_reader_eof, _io_ctx));
772
0
    if (size == 0) {
773
0
        return Status::InternalError<false>(
774
0
                "The first line is empty, can not parse column numbers");
775
0
    }
776
0
    if (!validate_utf8(_params, reinterpret_cast<const char*>(ptr), size)) {
777
0
        return Status::InternalError<false>("Only support csv data in utf8 codec");
778
0
    }
779
0
    ptr = _remove_bom(ptr, size);
780
0
    _split_line(Slice(ptr, size));
781
0
    *col_nums = _split_values.size();
782
0
    return Status::OK();
783
0
}
784
785
0
Status CsvReader::_parse_col_names(std::vector<std::string>* col_names) {
786
0
    const uint8_t* ptr = nullptr;
787
0
    size_t size = 0;
788
    // no use of _line_reader_eof
789
0
    RETURN_IF_ERROR(_line_reader->read_line(&ptr, &size, &_line_reader_eof, _io_ctx));
790
0
    if (size == 0) {
791
0
        return Status::InternalError<false>("The first line is empty, can not parse column names");
792
0
    }
793
0
    if (!validate_utf8(_params, reinterpret_cast<const char*>(ptr), size)) {
794
0
        return Status::InternalError<false>("Only support csv data in utf8 codec");
795
0
    }
796
0
    ptr = _remove_bom(ptr, size);
797
0
    _split_line(Slice(ptr, size));
798
0
    for (auto _split_value : _split_values) {
799
0
        col_names->emplace_back(_split_value.to_string());
800
0
    }
801
0
    return Status::OK();
802
0
}
803
804
// TODO(ftw): parse type
805
0
Status CsvReader::_parse_col_types(size_t col_nums, std::vector<DataTypePtr>* col_types) {
806
    // delete after.
807
0
    for (size_t i = 0; i < col_nums; ++i) {
808
0
        col_types->emplace_back(make_nullable(std::make_shared<DataTypeString>()));
809
0
    }
810
811
    // 1. check _line_reader_eof
812
    // 2. read line
813
    // 3. check utf8
814
    // 4. check size
815
    // 5. check _split_values.size must equal to col_nums.
816
    // 6. fill col_types
817
0
    return Status::OK();
818
0
}
819
820
0
const uint8_t* CsvReader::_remove_bom(const uint8_t* ptr, size_t& size) {
821
0
    if (size >= 3 && ptr[0] == 0xEF && ptr[1] == 0xBB && ptr[2] == 0xBF) {
822
0
        LOG(INFO) << "remove bom";
823
0
        constexpr size_t bom_size = 3;
824
0
        size -= bom_size;
825
        // In enclose mode, column_sep_positions were computed on the original line
826
        // (including BOM). After shifting the pointer, we must adjust those positions
827
        // so they remain correct relative to the new start.
828
0
        if (_enclose_reader_ctx) {
829
0
            _enclose_reader_ctx->adjust_column_sep_positions(bom_size);
830
0
        }
831
0
        return ptr + bom_size;
832
0
    }
833
0
    return ptr;
834
0
}
835
836
0
Status CsvReader::close() {
837
0
    if (_line_reader) {
838
0
        _line_reader->close();
839
0
    }
840
841
0
    if (_file_reader) {
842
0
        RETURN_IF_ERROR(_file_reader->close());
843
0
    }
844
845
0
    return Status::OK();
846
0
}
847
848
#include "common/compile_check_end.h"
849
} // namespace doris