Coverage Report

Created: 2026-03-20 06:04

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
712
void EncloseCsvTextFieldSplitter::do_split(const Slice& line, std::vector<Slice>* splitted_values) {
68
712
    const char* data = line.data;
69
712
    const auto& column_sep_positions = _text_line_reader_ctx->column_sep_positions();
70
712
    size_t value_start_offset = 0;
71
2.59k
    for (auto idx : column_sep_positions) {
72
2.59k
        process_value_func(data, value_start_offset, idx - value_start_offset, _trimming_char,
73
2.59k
                           splitted_values);
74
2.59k
        value_start_offset = idx + _value_sep_len;
75
2.59k
    }
76
712
    if (line.size >= value_start_offset) {
77
        // process the last column
78
710
        process_value_func(data, value_start_offset, line.size - value_start_offset, _trimming_char,
79
710
                           splitted_values);
80
710
    }
81
712
}
82
83
void PlainCsvTextFieldSplitter::_split_field_single_char(const Slice& line,
84
12.2M
                                                         std::vector<Slice>* splitted_values) {
85
12.2M
    const char* data = line.data;
86
12.2M
    const size_t size = line.size;
87
12.2M
    size_t value_start = 0;
88
1.55G
    for (size_t i = 0; i < size; ++i) {
89
1.54G
        if (data[i] == _value_sep[0]) {
90
189M
            process_value_func(data, value_start, i - value_start, _trimming_char, splitted_values);
91
189M
            value_start = i + _value_sep_len;
92
189M
        }
93
1.54G
    }
94
12.2M
    process_value_func(data, value_start, size - value_start, _trimming_char, splitted_values);
95
12.2M
}
96
97
void PlainCsvTextFieldSplitter::_split_field_multi_char(const Slice& line,
98
162
                                                        std::vector<Slice>* splitted_values) {
99
162
    size_t start = 0;  // point to the start pos of next col value.
100
162
    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
162
    std::vector<int> next(_value_sep_len);
114
162
    next[0] = -1;
115
403
    for (int i = 1, j = -1; i < _value_sep_len; i++) {
116
261
        while (j > -1 && _value_sep[i] != _value_sep[j + 1]) {
117
20
            j = next[j];
118
20
        }
119
241
        if (_value_sep[i] == _value_sep[j + 1]) {
120
130
            j++;
121
130
        }
122
241
        next[i] = j;
123
241
    }
124
125
6.96k
    for (int i = 0, j = -1; i < line.size; i++) {
126
        // i : line
127
        // j : _value_sep
128
7.09k
        while (j > -1 && line[i] != _value_sep[j + 1]) {
129
290
            j = next[j];
130
290
        }
131
6.80k
        if (line[i] == _value_sep[j + 1]) {
132
2.17k
            j++;
133
2.17k
        }
134
6.80k
        if (j == _value_sep_len - 1) {
135
832
            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
832
            if (curpos >= start) {
153
803
                process_value_func(line.data, start, curpos - start, _trimming_char,
154
803
                                   splitted_values);
155
803
                start = i + 1;
156
803
            }
157
158
832
            j = next[j];
159
832
        }
160
6.80k
    }
161
162
    process_value_func(line.data, start, line.size - start, _trimming_char, splitted_values);
162
162
}
163
164
12.2M
void PlainCsvTextFieldSplitter::do_split(const Slice& line, std::vector<Slice>* splitted_values) {
165
12.2M
    if (is_single_char_delim) {
166
12.2M
        _split_field_single_char(line, splitted_values);
167
18.4E
    } else {
168
18.4E
        _split_field_multi_char(line, splitted_values);
169
18.4E
    }
170
12.2M
}
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
2.41k
        : _profile(profile),
177
2.41k
          _params(params),
178
2.41k
          _file_reader(nullptr),
179
2.41k
          _line_reader(nullptr),
180
2.41k
          _decompressor(nullptr),
181
2.41k
          _state(state),
182
2.41k
          _counter(counter),
183
2.41k
          _range(range),
184
2.41k
          _file_slot_descs(file_slot_descs),
185
2.41k
          _line_reader_eof(false),
186
2.41k
          _skip_lines(0),
187
2.41k
          _io_ctx(io_ctx),
188
2.41k
          _io_ctx_holder(std::move(io_ctx_holder)) {
189
2.41k
    if (_io_ctx == nullptr && _io_ctx_holder) {
190
0
        _io_ctx = _io_ctx_holder.get();
191
0
    }
192
2.41k
    _file_format_type = _params.format_type;
193
2.41k
    _is_proto_format = _file_format_type == TFileFormatType::FORMAT_PROTO;
194
2.41k
    if (_range.__isset.compress_type) {
195
        // for compatibility
196
593
        _file_compress_type = _range.compress_type;
197
1.81k
    } else {
198
1.81k
        _file_compress_type = _params.compress_type;
199
1.81k
    }
200
2.41k
    _size = _range.size;
201
202
2.41k
    _split_values.reserve(_file_slot_descs.size());
203
2.41k
    _init_system_properties();
204
2.41k
    _init_file_description();
205
2.41k
    _serdes = create_data_type_serdes(_file_slot_descs);
206
2.41k
}
207
208
2.41k
void CsvReader::_init_system_properties() {
209
2.41k
    if (_range.__isset.file_type) {
210
        // for compatibility
211
573
        _system_properties.system_type = _range.file_type;
212
1.83k
    } else {
213
1.83k
        _system_properties.system_type = _params.file_type;
214
1.83k
    }
215
2.41k
    _system_properties.properties = _params.properties;
216
2.41k
    _system_properties.hdfs_params = _params.hdfs_params;
217
2.41k
    if (_params.__isset.broker_addresses) {
218
1.70k
        _system_properties.broker_addresses.assign(_params.broker_addresses.begin(),
219
1.70k
                                                   _params.broker_addresses.end());
220
1.70k
    }
221
2.41k
}
222
223
2.41k
void CsvReader::_init_file_description() {
224
2.41k
    _file_description.path = _range.path;
225
2.41k
    _file_description.file_size = _range.__isset.file_size ? _range.file_size : -1;
226
2.41k
    if (_range.__isset.fs_name) {
227
0
        _file_description.fs_name = _range.fs_name;
228
0
    }
229
2.41k
    if (_range.__isset.file_cache_admission) {
230
        _file_description.file_cache_admission = _range.file_cache_admission;
231
2.02k
    }
232
}
233
2.02k
234
2.02k
Status CsvReader::init_reader(bool is_load) {
235
    // set the skip lines and start offset
236
2.02k
    _start_offset = _range.start_offset;
237
2.02k
    if (_start_offset == 0) {
238
44
        // check header typer first
239
44
        if (_params.__isset.file_attributes && _params.file_attributes.__isset.header_type &&
240
24
            !_params.file_attributes.header_type.empty()) {
241
24
            std::string header_type = to_lower(_params.file_attributes.header_type);
242
20
            if (header_type == BeConsts::CSV_WITH_NAMES) {
243
20
                _skip_lines = 1;
244
1.98k
            } else if (header_type == BeConsts::CSV_WITH_NAMES_AND_TYPES) {
245
1.98k
                _skip_lines = 2;
246
1.98k
            }
247
2.02k
        } 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
             _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
0
        // 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
                _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
2.02k
        _skip_lines = 1;
264
17.7k
    }
265
15.6k
266
15.6k
    _use_nullable_string_opt.resize(_file_slot_descs.size());
267
15.6k
    for (int i = 0; i < _file_slot_descs.size(); ++i) {
268
15.6k
        auto data_type_ptr = _file_slot_descs[i]->get_data_type_ptr();
269
15.6k
        if (data_type_ptr->is_nullable() && is_string_type(data_type_ptr->get_primitive_type())) {
270
            _use_nullable_string_opt[i] = 1;
271
2.02k
        }
272
2.02k
    }
273
2.02k
274
2.02k
    RETURN_IF_ERROR(_init_options());
275
    RETURN_IF_ERROR(_create_file_reader(false));
276
2.02k
    RETURN_IF_ERROR(_create_decompressor());
277
2.02k
    RETURN_IF_ERROR(_create_line_reader());
278
279
    _is_load = is_load;
280
    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
320
        //      eg, the file_slot_descs is k1, k3, k5, and columns in block are p1, k1, k3, k5
287
320
        //      where "p1" is the partition col which does not exist in file
288
320
        //      the _file_slot_idx_map will save: 1, 2, 3
289
2.23k
        DCHECK(_params.__isset.column_idxs);
290
2.23k
        _col_idxs = _params.column_idxs;
291
2.23k
        int idx = 0;
292
2.23k
        for (const auto& slot_info : _params.required_slots) {
293
2.23k
            if (slot_info.is_file_slot) {
294
2.23k
                _file_slot_idx_map.push_back(idx);
295
1.70k
            }
296
            idx++;
297
1.70k
        }
298
13.4k
    } else {
299
13.4k
        // For load task, the column order is same as file column order
300
13.4k
        int i = 0;
301
1.70k
        for (const auto& desc [[maybe_unused]] : _file_slot_descs) {
302
            _col_idxs.push_back(i++);
303
2.02k
        }
304
2.02k
    }
305
2.02k
306
    _line_reader_eof = false;
307
    return Status::OK();
308
6.71k
}
309
6.71k
310
1.98k
// !FIXME: Here we should use MutableBlock
311
1.98k
Status CsvReader::get_next_block(Block* block, size_t* read_rows, bool* eof) {
312
1.98k
    if (_line_reader_eof) {
313
        *eof = true;
314
4.73k
        return Status::OK();
315
4.73k
    }
316
317
4.73k
    const int batch_size = std::max(_state->batch_size(), (int)_MIN_BATCH_SIZE);
318
4.73k
    size_t rows = 0;
319
4.73k
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
            const uint8_t* ptr = nullptr;
325
            size_t size = 0;
326
            RETURN_IF_ERROR(_line_reader->read_line(&ptr, &size, &_line_reader_eof, _io_ctx));
327
0
328
0
            // _skip_lines == 0 means this line is the actual data beginning line for the entire file
329
0
            // is_remove_bom means _remove_bom should only execute once
330
0
            if (_skip_lines == 0 && !is_remove_bom) {
331
                ptr = _remove_bom(ptr, size);
332
                is_remove_bom = true;
333
0
            }
334
0
335
0
            // _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
                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
0
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
4.73k
            col->resize(rows);
355
4.73k
        }
356
12.1M
        block->set_columns(std::move(mutate_columns));
357
12.1M
    } else {
358
12.1M
        auto columns = block->mutate_columns();
359
12.1M
        while (rows < batch_size && !_line_reader_eof) {
360
            const uint8_t* ptr = nullptr;
361
            size_t size = 0;
362
            RETURN_IF_ERROR(_line_reader->read_line(&ptr, &size, &_line_reader_eof, _io_ctx));
363
12.1M
364
4.66k
            // _skip_lines == 0 means this line is the actual data beginning line for the entire file
365
4.66k
            // is_remove_bom means _remove_bom should only execute once
366
4.66k
            if (!is_remove_bom && _skip_lines == 0) {
367
                ptr = _remove_bom(ptr, size);
368
                is_remove_bom = true;
369
12.1M
            }
370
119
371
119
            // _skip_lines > 0 means we do not remove bom
372
119
            if (_skip_lines > 0) {
373
119
                _skip_lines--;
374
12.1M
                is_remove_bom = true;
375
2.04k
                continue;
376
0
            }
377
0
            if (size == 0) {
378
                if (!_line_reader_eof && _state->is_read_csv_empty_line_as_null()) {
379
2.04k
                    RETURN_IF_ERROR(_fill_empty_line(block, columns, &rows));
380
2.04k
                }
381
                // Read empty line, continue
382
12.1M
                continue;
383
12.1M
            }
384
128
385
128
            RETURN_IF_ERROR(_validate_line(Slice(ptr, size), &success));
386
12.1M
            if (!success) {
387
12.1M
                continue;
388
4.72k
            }
389
4.72k
            RETURN_IF_ERROR(_fill_dest_columns(Slice(ptr, size), block, columns, &rows));
390
        }
391
4.72k
        block->set_columns(std::move(columns));
392
4.72k
    }
393
394
4.72k
    *eof = (rows == 0);
395
4.73k
    *read_rows = rows;
396
397
    return Status::OK();
398
2.02k
}
399
15.6k
400
15.6k
Status CsvReader::get_columns(std::unordered_map<std::string, DataTypePtr>* name_to_type,
401
15.6k
                              std::unordered_set<std::string>* missing_cols) {
402
2.02k
    for (const auto& slot : _file_slot_descs) {
403
2.02k
        name_to_type->emplace(slot->col_name(), slot->type());
404
    }
405
    return Status::OK();
406
381
}
407
381
408
381
// 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
381
        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
                "Getting parsered schema from csv file do not support stream load and broker "
418
                "load.");
419
381
    }
420
381
421
    // csv file without names line and types line.
422
381
    _read_line = 1;
423
381
    _is_parse_name = false;
424
48
425
48
    if (_params.__isset.file_attributes && _params.file_attributes.__isset.header_type &&
426
25
        !_params.file_attributes.header_type.empty()) {
427
25
        std::string header_type = to_lower(_params.file_attributes.header_type);
428
23
        if (header_type == BeConsts::CSV_WITH_NAMES) {
429
23
            _is_parse_name = true;
430
23
        } else if (header_type == BeConsts::CSV_WITH_NAMES_AND_TYPES) {
431
48
            _read_line = 2;
432
            _is_parse_name = true;
433
381
        }
434
381
    }
435
381
436
381
    RETURN_IF_ERROR(_init_options());
437
381
    RETURN_IF_ERROR(_create_file_reader(true));
438
381
    RETURN_IF_ERROR(_create_decompressor());
439
    RETURN_IF_ERROR(_create_line_reader());
440
    return Status::OK();
441
381
}
442
381
443
358
Status CsvReader::get_parsed_schema(std::vector<std::string>* col_names,
444
333
                                    std::vector<DataTypePtr>* col_types) {
445
333
    if (_read_line == 1) {
446
2.83k
        if (!_is_parse_name) { //parse csv file without names and types
447
2.49k
            size_t col_nums = 0;
448
2.49k
            RETURN_IF_ERROR(_parse_col_nums(&col_nums));
449
332
            for (size_t i = 0; i < col_nums; ++i) {
450
25
                col_names->emplace_back("c" + std::to_string(i + 1));
451
25
            }
452
        } else { // parse csv file with names
453
2.95k
            RETURN_IF_ERROR(_parse_col_names(col_names));
454
2.59k
        }
455
2.59k
456
2.59k
        for (size_t j = 0; j < col_names->size(); ++j) {
457
357
            col_types->emplace_back(
458
23
                    DataTypeFactory::instance().create_data_type(PrimitiveType::TYPE_STRING, true));
459
23
        }
460
23
    } else { // parse csv file with names and types
461
380
        RETURN_IF_ERROR(_parse_col_names(col_names));
462
381
        RETURN_IF_ERROR(_parse_col_types(col_names->size(), col_types));
463
    }
464
196M
    return Status::OK();
465
196M
}
466
196M
467
60
Status CsvReader::_deserialize_nullable_string(IColumn& column, Slice& slice) {
468
5
    auto& null_column = assert_cast<ColumnNullable&>(column);
469
5
    if (_empty_field_as_null) {
470
5
        if (slice.size == 0) {
471
60
            null_column.insert_data(nullptr, 0);
472
196M
            return Status::OK();
473
194M
        }
474
30.8k
    }
475
30.8k
    if (_options.null_len > 0 && !(_options.converted_from_string && slice.trim_double_quotes())) {
476
30.8k
        if (slice.compare(Slice(_options.null_format, _options.null_len)) == 0) {
477
194M
            null_column.insert_data(nullptr, 0);
478
196M
            return Status::OK();
479
196M
        }
480
196M
    }
481
196M
    static DataTypeStringSerDe stringSerDe(TYPE_STRING);
482
    auto st = stringSerDe.deserialize_one_cell_from_csv(null_column.get_nested_column(), slice,
483
0
                                                        _options);
484
0
    if (!st.ok()) {
485
0
        // fill null if fail
486
        null_column.insert_data(nullptr, 0); // 0 is meaningless here
487
196M
        return Status::OK();
488
196M
    }
489
196M
    // fill not null if success
490
    null_column.get_null_map_data().push_back(0);
491
2.40k
    return Status::OK();
492
}
493
2.40k
494
2.40k
Status CsvReader::_init_options() {
495
2.40k
    // get column_separator and line_delimiter
496
2.40k
    _value_separator = _params.file_attributes.text_params.column_separator;
497
2.40k
    _value_separator_length = _value_separator.size();
498
2.40k
    _line_delimiter = _params.file_attributes.text_params.line_delimiter;
499
2.40k
    _line_delimiter_length = _line_delimiter.size();
500
2.40k
    if (_params.file_attributes.text_params.__isset.enclose) {
501
2.40k
        _enclose = _params.file_attributes.text_params.enclose;
502
2.40k
    }
503
    if (_params.file_attributes.text_params.__isset.escape) {
504
2.40k
        _escape = _params.file_attributes.text_params.escape;
505
2.40k
    }
506
507
2.40k
    _trim_tailing_spaces =
508
2.40k
            (_state != nullptr && _state->trim_tailing_spaces_for_external_table_query());
509
510
2.40k
    _options.escape_char = _escape;
511
2.40k
    _options.quote_char = _enclose;
512
2.40k
513
2
    if (_params.file_attributes.text_params.collection_delimiter.empty()) {
514
2
        _options.collection_delim = ',';
515
2.40k
    } else {
516
2.40k
        _options.collection_delim = _params.file_attributes.text_params.collection_delimiter[0];
517
2.40k
    }
518
1
    if (_params.file_attributes.text_params.mapkv_delimiter.empty()) {
519
1
        _options.map_key_delim = ':';
520
    } else {
521
2.40k
        _options.map_key_delim = _params.file_attributes.text_params.mapkv_delimiter[0];
522
0
    }
523
0
524
0
    if (_params.file_attributes.text_params.__isset.null_format) {
525
        _options.null_format = _params.file_attributes.text_params.null_format.data();
526
2.40k
        _options.null_len = _params.file_attributes.text_params.null_format.length();
527
2.40k
    }
528
2.40k
529
2.40k
    if (_params.file_attributes.__isset.trim_double_quotes) {
530
        _trim_double_quotes = _params.file_attributes.trim_double_quotes;
531
2.40k
    }
532
2.02k
    _options.converted_from_string = _trim_double_quotes;
533
2.02k
534
    if (_state != nullptr) {
535
2.40k
        _keep_cr = _state->query_options().keep_carriage_return;
536
2.40k
    }
537
2.40k
538
2.40k
    if (_params.file_attributes.text_params.__isset.empty_field_as_null) {
539
2.40k
        _empty_field_as_null = _params.file_attributes.text_params.empty_field_as_null;
540
    }
541
2.41k
    return Status::OK();
542
2.41k
}
543
2.32k
544
2.32k
Status CsvReader::_create_decompressor() {
545
86
    if (_file_compress_type != TFileCompressType::UNKNOWN) {
546
86
        RETURN_IF_ERROR(Decompressor::create_decompressor(_file_compress_type, &_decompressor));
547
    } else {
548
2.41k
        RETURN_IF_ERROR(Decompressor::create_decompressor(_file_format_type, &_decompressor));
549
2.41k
    }
550
551
2.41k
    return Status::OK();
552
2.41k
}
553
1.86k
554
1.86k
Status CsvReader::_create_file_reader(bool need_schema) {
555
1.86k
    if (_params.file_type == TFileType::FILE_STREAM) {
556
548
        RETURN_IF_ERROR(FileFactory::create_pipe_reader(_range.load_id, &_file_reader, _state,
557
548
                                                        need_schema));
558
548
    } else {
559
548
        _file_description.mtime = _range.__isset.modification_time ? _range.modification_time : 0;
560
548
        io::FileReaderOptions reader_options =
561
261
                FileFactory::get_reader_options(_state, _file_description);
562
261
        io::FileReaderSPtr file_reader;
563
261
        if (_io_ctx_holder) {
564
261
            file_reader = DORIS_TRY(io::DelegateReader::create_file_reader(
565
261
                    _profile, _system_properties, _file_description, reader_options,
566
287
                    io::DelegateReader::AccessMode::SEQUENTIAL,
567
287
                    std::static_pointer_cast<const io::IOContext>(_io_ctx_holder),
568
287
                    io::PrefetchRange(_range.start_offset, _range.start_offset + _range.size)));
569
287
        } else {
570
287
            file_reader = DORIS_TRY(io::DelegateReader::create_file_reader(
571
287
                    _profile, _system_properties, _file_description, reader_options,
572
548
                    io::DelegateReader::AccessMode::SEQUENTIAL, _io_ctx,
573
548
                    io::PrefetchRange(_range.start_offset, _range.start_offset + _range.size)));
574
548
        }
575
548
        _file_reader = _io_ctx ? std::make_shared<io::TracingFileReader>(std::move(file_reader),
576
2.41k
                                                                         _io_ctx->file_reader_stats)
577
2.41k
                               : file_reader;
578
0
    }
579
0
    if (_file_reader->size() == 0 && _params.file_type != TFileType::FILE_STREAM &&
580
2.41k
        _params.file_type != TFileType::FILE_BROKER) {
581
2.41k
        return Status::EndOfFile("init reader failed, empty csv file: " + _range.path);
582
    }
583
2.40k
    return Status::OK();
584
2.40k
}
585
2.40k
586
2.30k
Status CsvReader::_create_line_reader() {
587
2.30k
    std::shared_ptr<TextLineReaderContextIf> text_line_reader_ctx;
588
2.30k
    if (_enclose == 0) {
589
2.30k
        text_line_reader_ctx = std::make_shared<PlainTextLineReaderCtx>(
590
                _line_delimiter, _line_delimiter_length, _keep_cr);
591
2.30k
        _fields_splitter = std::make_unique<PlainCsvTextFieldSplitter>(
592
                _trim_tailing_spaces, false, _value_separator, _value_separator_length, -1);
593
97
594
97
    } else {
595
97
        // in load task, the _file_slot_descs is empty vector, so we need to set col_sep_num to 0
596
97
        size_t col_sep_num = _file_slot_descs.size() > 1 ? _file_slot_descs.size() - 1 : 0;
597
97
        _enclose_reader_ctx = std::make_shared<EncloseCsvLineReaderCtx>(
598
                _line_delimiter, _line_delimiter_length, _value_separator, _value_separator_length,
599
97
                col_sep_num, _enclose, _escape, _keep_cr);
600
97
        text_line_reader_ctx = _enclose_reader_ctx;
601
97
602
2.40k
        _fields_splitter = std::make_unique<EncloseCsvTextFieldSplitter>(
603
2.32k
                _trim_tailing_spaces, true, _enclose_reader_ctx, _value_separator_length, _enclose);
604
2.32k
    }
605
2.32k
    switch (_file_format_type) {
606
2.32k
    case TFileFormatType::FORMAT_CSV_PLAIN:
607
2.32k
        [[fallthrough]];
608
2.32k
    case TFileFormatType::FORMAT_CSV_GZ:
609
2.32k
        [[fallthrough]];
610
2.32k
    case TFileFormatType::FORMAT_CSV_BZ2:
611
2.32k
        [[fallthrough]];
612
2.32k
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
613
2.32k
        [[fallthrough]];
614
2.32k
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
615
2.32k
        [[fallthrough]];
616
2.32k
    case TFileFormatType::FORMAT_CSV_LZOP:
617
2.32k
        [[fallthrough]];
618
2.32k
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
619
2.32k
        [[fallthrough]];
620
2.32k
    case TFileFormatType::FORMAT_CSV_DEFLATE:
621
        _line_reader =
622
2.32k
                NewPlainTextLineReader::create_unique(_profile, _file_reader, _decompressor.get(),
623
77
                                                      text_line_reader_ctx, _size, _start_offset);
624
77
625
77
        break;
626
77
    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
2.40k
        return Status::InternalError<false>(
632
2.40k
                "Unknown format type, cannot init line reader in csv reader, type={}",
633
2.40k
                _file_format_type);
634
    }
635
300
    return Status::OK();
636
300
}
637
300
638
Status CsvReader::_deserialize_one_cell(DataTypeSerDeSPtr serde, IColumn& column, Slice& slice) {
639
    return serde->deserialize_one_cell_from_csv(column, slice, _options);
640
12.2M
}
641
12.2M
642
Status CsvReader::_fill_dest_columns(const Slice& line, Block* block,
643
12.2M
                                     std::vector<MutableColumnPtr>& columns, size_t* rows) {
644
12.2M
    bool is_success = false;
645
646
539
    RETURN_IF_ERROR(_line_split_to_values(line, &is_success));
647
539
    if (UNLIKELY(!is_success)) {
648
        // If not success, which means we met an invalid row, filter this row and return.
649
203M
        return Status::OK();
650
191M
    }
651
652
191M
    for (int i = 0; i < _file_slot_descs.size(); ++i) {
653
191M
        int col_idx = _col_idxs[i];
654
191M
        // col idx is out of range, fill with null format
655
        auto value = col_idx < _split_values.size()
656
191M
                             ? _split_values[col_idx]
657
191M
                             : Slice(_options.null_format, _options.null_len);
658
659
        IColumn* col_ptr = columns[i].get();
660
20.5M
        if (!_is_load) {
661
20.5M
            // block is a Block*, and get_by_position returns a ColumnPtr,
662
20.5M
            // which is a const pointer. Therefore, using const_cast is permissible.
663
            col_ptr = const_cast<IColumn*>(
664
198M
                    block->get_by_position(_file_slot_idx_map[i]).column.get());
665
        }
666
667
        if (_use_nullable_string_opt[i]) {
668
198M
            // For load task, we always read "string" from file.
669
18.4E
            // So serdes[i] here must be DataTypeNullableSerDe, and DataTypeNullableSerDe -> nested_serde must be DataTypeStringSerDe.
670
18.4E
            // So we use deserialize_nullable_string and stringSerDe to reduce virtual function calls.
671
18.4E
            RETURN_IF_ERROR(_deserialize_nullable_string(*col_ptr, value));
672
191M
        } else {
673
12.2M
            RETURN_IF_ERROR(_deserialize_one_cell(_serdes[i], *col_ptr, value));
674
        }
675
12.2M
    }
676
12.2M
    ++(*rows);
677
678
    return Status::OK();
679
0
}
680
0
681
0
Status CsvReader::_fill_empty_line(Block* block, std::vector<MutableColumnPtr>& columns,
682
0
                                   size_t* rows) {
683
    for (int i = 0; i < _file_slot_descs.size(); ++i) {
684
        IColumn* col_ptr = columns[i].get();
685
0
        if (!_is_load) {
686
0
            // block is a Block*, and get_by_position returns a ColumnPtr,
687
0
            // 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
    ++(*rows);
695
12.2M
    return Status::OK();
696
12.2M
}
697
128
698
0
Status CsvReader::_validate_line(const Slice& line, bool* success) {
699
128
    if (!_is_proto_format && !validate_utf8(_params, line.data, line.size)) {
700
128
        if (!_is_load) {
701
128
            return Status::InternalError<false>("Only support csv data in utf8 codec");
702
128
        } else {
703
128
            _counter->num_rows_filtered++;
704
128
            *success = false;
705
128
            RETURN_IF_ERROR(_state->append_error_msg_to_file(
706
128
                    [&]() -> std::string { return std::string(line.data, line.size); },
707
128
                    [&]() -> std::string {
708
128
                        return "Invalid file encoding: all CSV files must be UTF-8 encoded";
709
128
                    }));
710
12.2M
            return Status::OK();
711
12.2M
        }
712
12.2M
    }
713
    *success = true;
714
12.2M
    return Status::OK();
715
12.2M
}
716
717
12.2M
Status CsvReader::_line_split_to_values(const Slice& line, bool* success) {
718
    _split_line(line);
719
720
    if (_is_load) {
721
10.9M
        // Only check for load task. For query task, the non exist column will be filled "null".
722
10.9M
        // if actual column number in csv file is not equal to _file_slot_descs.size()
723
10.9M
        // then filter this line.
724
10.9M
        bool ignore_col = false;
725
        ignore_col = _params.__isset.file_attributes &&
726
10.9M
                     _params.file_attributes.__isset.ignore_csv_redundant_col &&
727
10.9M
                     _params.file_attributes.ignore_csv_redundant_col;
728
544
729
544
        if ((!ignore_col && _split_values.size() != _file_slot_descs.size()) ||
730
544
            (ignore_col && _split_values.size() < _file_slot_descs.size())) {
731
544
            _counter->num_rows_filtered++;
732
544
            *success = false;
733
544
            RETURN_IF_ERROR(_state->append_error_msg_to_file(
734
544
                    [&]() -> std::string { return std::string(line.data, line.size); },
735
544
                    [&]() -> std::string {
736
544
                        fmt::memory_buffer error_msg;
737
544
                        fmt::format_to(error_msg,
738
544
                                       "Column count mismatch: expected {}, but found {}",
739
544
                                       _file_slot_descs.size(), _split_values.size());
740
544
                        std::string escaped_separator =
741
544
                                std::regex_replace(_value_separator, std::regex("\t"), "\\t");
742
544
                        std::string escaped_delimiter =
743
544
                                std::regex_replace(_line_delimiter, std::regex("\n"), "\\n");
744
544
                        fmt::format_to(error_msg, " (sep:{} delim:{}", escaped_separator,
745
544
                                       escaped_delimiter);
746
544
                        if (_enclose != 0) {
747
544
                            fmt::format_to(error_msg, " encl:{}", _enclose);
748
544
                        }
749
544
                        if (_escape != 0) {
750
544
                            fmt::format_to(error_msg, " esc:{}", _escape);
751
544
                        }
752
539
                        fmt::format_to(error_msg, ")");
753
544
                        return fmt::to_string(error_msg);
754
10.9M
                    }));
755
            return Status::OK();
756
12.2M
        }
757
12.2M
    }
758
12.2M
759
    *success = true;
760
12.2M
    return Status::OK();
761
12.2M
}
762
12.2M
763
12.2M
void CsvReader::_split_line(const Slice& line) {
764
    _split_values.clear();
765
333
    _fields_splitter->split_line(line, &_split_values);
766
333
}
767
333
768
333
Status CsvReader::_parse_col_nums(size_t* col_nums) {
769
333
    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
333
        return Status::InternalError<false>(
774
1
                "The first line is empty, can not parse column numbers");
775
1
    }
776
332
    if (!validate_utf8(_params, reinterpret_cast<const char*>(ptr), size)) {
777
332
        return Status::InternalError<false>("Only support csv data in utf8 codec");
778
332
    }
779
332
    ptr = _remove_bom(ptr, size);
780
333
    _split_line(Slice(ptr, size));
781
    *col_nums = _split_values.size();
782
48
    return Status::OK();
783
48
}
784
48
785
Status CsvReader::_parse_col_names(std::vector<std::string>* col_names) {
786
48
    const uint8_t* ptr = nullptr;
787
48
    size_t size = 0;
788
0
    // no use of _line_reader_eof
789
0
    RETURN_IF_ERROR(_line_reader->read_line(&ptr, &size, &_line_reader_eof, _io_ctx));
790
48
    if (size == 0) {
791
0
        return Status::InternalError<false>("The first line is empty, can not parse column names");
792
0
    }
793
48
    if (!validate_utf8(_params, reinterpret_cast<const char*>(ptr), size)) {
794
48
        return Status::InternalError<false>("Only support csv data in utf8 codec");
795
187
    }
796
187
    ptr = _remove_bom(ptr, size);
797
187
    _split_line(Slice(ptr, size));
798
48
    for (auto _split_value : _split_values) {
799
48
        col_names->emplace_back(_split_value.to_string());
800
    }
801
    return Status::OK();
802
23
}
803
804
113
// TODO(ftw): parse type
805
90
Status CsvReader::_parse_col_types(size_t col_nums, std::vector<DataTypePtr>* col_types) {
806
90
    // delete after.
807
    for (size_t i = 0; i < col_nums; ++i) {
808
        col_types->emplace_back(make_nullable(std::make_shared<DataTypeString>()));
809
    }
810
811
    // 1. check _line_reader_eof
812
    // 2. read line
813
    // 3. check utf8
814
23
    // 4. check size
815
23
    // 5. check _split_values.size must equal to col_nums.
816
    // 6. fill col_types
817
5.04k
    return Status::OK();
818
5.04k
}
819
7
820
7
const uint8_t* CsvReader::_remove_bom(const uint8_t* ptr, size_t& size) {
821
7
    if (size >= 3 && ptr[0] == 0xEF && ptr[1] == 0xBB && ptr[2] == 0xBF) {
822
        LOG(INFO) << "remove bom";
823
        constexpr size_t bom_size = 3;
824
        size -= bom_size;
825
7
        // In enclose mode, column_sep_positions were computed on the original line
826
1
        // (including BOM). After shifting the pointer, we must adjust those positions
827
1
        // so they remain correct relative to the new start.
828
7
        if (_enclose_reader_ctx) {
829
7
            _enclose_reader_ctx->adjust_column_sep_positions(bom_size);
830
5.03k
        }
831
5.04k
        return ptr + bom_size;
832
    }
833
2.02k
    return ptr;
834
2.02k
}
835
2.02k
836
2.02k
Status CsvReader::close() {
837
    if (_line_reader) {
838
2.02k
        _line_reader->close();
839
2.02k
    }
840
2.02k
841
    if (_file_reader) {
842
2.02k
        RETURN_IF_ERROR(_file_reader->close());
843
2.02k
    }
844
845
    return Status::OK();
846
}
847
848
#include "common/compile_check_end.h"
849
} // namespace doris