Coverage Report

Created: 2026-04-08 13:21

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