Coverage Report

Created: 2026-03-20 11:11

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
940
void EncloseCsvTextFieldSplitter::do_split(const Slice& line, std::vector<Slice>* splitted_values) {
68
940
    const char* data = line.data;
69
940
    const auto& column_sep_positions = _text_line_reader_ctx->column_sep_positions();
70
940
    size_t value_start_offset = 0;
71
3.08k
    for (auto idx : column_sep_positions) {
72
3.08k
        process_value_func(data, value_start_offset, idx - value_start_offset, _trimming_char,
73
3.08k
                           splitted_values);
74
3.08k
        value_start_offset = idx + _value_sep_len;
75
3.08k
    }
76
940
    if (line.size >= value_start_offset) {
77
        // process the last column
78
938
        process_value_func(data, value_start_offset, line.size - value_start_offset, _trimming_char,
79
938
                           splitted_values);
80
938
    }
81
940
}
82
83
void PlainCsvTextFieldSplitter::_split_field_single_char(const Slice& line,
84
15.0M
                                                         std::vector<Slice>* splitted_values) {
85
15.0M
    const char* data = line.data;
86
15.0M
    const size_t size = line.size;
87
15.0M
    size_t value_start = 0;
88
3.57G
    for (size_t i = 0; i < size; ++i) {
89
3.56G
        if (data[i] == _value_sep[0]) {
90
446M
            process_value_func(data, value_start, i - value_start, _trimming_char, splitted_values);
91
446M
            value_start = i + _value_sep_len;
92
446M
        }
93
3.56G
    }
94
15.0M
    process_value_func(data, value_start, size - value_start, _trimming_char, splitted_values);
95
15.0M
}
96
97
void PlainCsvTextFieldSplitter::_split_field_multi_char(const Slice& line,
98
2.38k
                                                        std::vector<Slice>* splitted_values) {
99
2.38k
    size_t start = 0;  // point to the start pos of next col value.
100
2.38k
    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.38k
    std::vector<int> next(_value_sep_len);
114
2.38k
    next[0] = -1;
115
4.96k
    for (int i = 1, j = -1; i < _value_sep_len; i++) {
116
2.60k
        while (j > -1 && _value_sep[i] != _value_sep[j + 1]) {
117
20
            j = next[j];
118
20
        }
119
2.58k
        if (_value_sep[i] == _value_sep[j + 1]) {
120
2.44k
            j++;
121
2.44k
        }
122
2.58k
        next[i] = j;
123
2.58k
    }
124
125
42.1k
    for (int i = 0, j = -1; i < line.size; i++) {
126
        // i : line
127
        // j : _value_sep
128
42.4k
        while (j > -1 && line[i] != _value_sep[j + 1]) {
129
2.66k
            j = next[j];
130
2.66k
        }
131
39.7k
        if (line[i] == _value_sep[j + 1]) {
132
7.02k
            j++;
133
7.02k
        }
134
39.7k
        if (j == _value_sep_len - 1) {
135
3.19k
            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
3.19k
            if (curpos >= start) {
153
3.13k
                process_value_func(line.data, start, curpos - start, _trimming_char,
154
3.13k
                                   splitted_values);
155
3.13k
                start = i + 1;
156
3.13k
            }
157
158
3.19k
            j = next[j];
159
3.19k
        }
160
39.7k
    }
161
2.38k
    process_value_func(line.data, start, line.size - start, _trimming_char, splitted_values);
162
2.38k
}
163
164
15.0M
void PlainCsvTextFieldSplitter::do_split(const Slice& line, std::vector<Slice>* splitted_values) {
165
15.0M
    if (is_single_char_delim) {
166
15.0M
        _split_field_single_char(line, splitted_values);
167
15.0M
    } else {
168
2.09k
        _split_field_multi_char(line, splitted_values);
169
2.09k
    }
170
15.0M
}
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
8.76k
        : _profile(profile),
177
8.76k
          _params(params),
178
8.76k
          _file_reader(nullptr),
179
8.76k
          _line_reader(nullptr),
180
8.76k
          _decompressor(nullptr),
181
8.76k
          _state(state),
182
8.76k
          _counter(counter),
183
8.76k
          _range(range),
184
8.76k
          _file_slot_descs(file_slot_descs),
185
8.76k
          _line_reader_eof(false),
186
8.76k
          _skip_lines(0),
187
8.76k
          _io_ctx(io_ctx),
188
8.76k
          _io_ctx_holder(std::move(io_ctx_holder)) {
189
8.76k
    if (_io_ctx == nullptr && _io_ctx_holder) {
190
0
        _io_ctx = _io_ctx_holder.get();
191
0
    }
192
8.76k
    _file_format_type = _params.format_type;
193
8.76k
    _is_proto_format = _file_format_type == TFileFormatType::FORMAT_PROTO;
194
8.76k
    if (_range.__isset.compress_type) {
195
        // for compatibility
196
6.76k
        _file_compress_type = _range.compress_type;
197
6.76k
    } else {
198
2.00k
        _file_compress_type = _params.compress_type;
199
2.00k
    }
200
8.76k
    _size = _range.size;
201
202
8.76k
    _split_values.reserve(_file_slot_descs.size());
203
8.76k
    _init_system_properties();
204
8.76k
    _init_file_description();
205
8.76k
    _serdes = create_data_type_serdes(_file_slot_descs);
206
8.76k
}
207
208
8.76k
void CsvReader::_init_system_properties() {
209
8.76k
    if (_range.__isset.file_type) {
210
        // for compatibility
211
6.60k
        _system_properties.system_type = _range.file_type;
212
6.60k
    } else {
213
2.16k
        _system_properties.system_type = _params.file_type;
214
2.16k
    }
215
8.76k
    _system_properties.properties = _params.properties;
216
8.76k
    _system_properties.hdfs_params = _params.hdfs_params;
217
8.76k
    if (_params.__isset.broker_addresses) {
218
1.89k
        _system_properties.broker_addresses.assign(_params.broker_addresses.begin(),
219
1.89k
                                                   _params.broker_addresses.end());
220
1.89k
    }
221
8.76k
}
222
223
8.76k
void CsvReader::_init_file_description() {
224
8.76k
    _file_description.path = _range.path;
225
8.76k
    _file_description.file_size = _range.__isset.file_size ? _range.file_size : -1;
226
8.76k
    if (_range.__isset.fs_name) {
227
5.46k
        _file_description.fs_name = _range.fs_name;
228
5.46k
    }
229
8.76k
    if (_range.__isset.file_cache_admission) {
230
5.96k
        _file_description.file_cache_admission = _range.file_cache_admission;
231
5.96k
    }
232
8.76k
}
233
234
7.96k
Status CsvReader::init_reader(bool is_load) {
235
    // set the skip lines and start offset
236
7.96k
    _start_offset = _range.start_offset;
237
7.96k
    if (_start_offset == 0) {
238
        // check header typer first
239
7.83k
        if (_params.__isset.file_attributes && _params.file_attributes.__isset.header_type &&
240
7.83k
            !_params.file_attributes.header_type.empty()) {
241
92
            std::string header_type = to_lower(_params.file_attributes.header_type);
242
92
            if (header_type == BeConsts::CSV_WITH_NAMES) {
243
64
                _skip_lines = 1;
244
64
            } else if (header_type == BeConsts::CSV_WITH_NAMES_AND_TYPES) {
245
28
                _skip_lines = 2;
246
28
            }
247
7.74k
        } else if (_params.file_attributes.__isset.skip_lines) {
248
7.74k
            _skip_lines = _params.file_attributes.skip_lines;
249
7.74k
        }
250
7.83k
    } 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
7.96k
    _use_nullable_string_opt.resize(_file_slot_descs.size());
267
219k
    for (int i = 0; i < _file_slot_descs.size(); ++i) {
268
211k
        auto data_type_ptr = _file_slot_descs[i]->get_data_type_ptr();
269
211k
        if (data_type_ptr->is_nullable() && is_string_type(data_type_ptr->get_primitive_type())) {
270
47.5k
            _use_nullable_string_opt[i] = 1;
271
47.5k
        }
272
211k
    }
273
274
7.96k
    RETURN_IF_ERROR(_init_options());
275
7.96k
    RETURN_IF_ERROR(_create_file_reader(false));
276
7.96k
    RETURN_IF_ERROR(_create_decompressor());
277
7.96k
    RETURN_IF_ERROR(_create_line_reader());
278
279
7.96k
    _is_load = is_load;
280
7.96k
    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
6.07k
        DCHECK(_params.__isset.column_idxs);
290
6.07k
        _col_idxs = _params.column_idxs;
291
6.07k
        int idx = 0;
292
196k
        for (const auto& slot_info : _params.required_slots) {
293
196k
            if (slot_info.is_file_slot) {
294
194k
                _file_slot_idx_map.push_back(idx);
295
194k
            }
296
196k
            idx++;
297
196k
        }
298
6.07k
    } else {
299
        // For load task, the column order is same as file column order
300
1.89k
        int i = 0;
301
17.4k
        for (const auto& desc [[maybe_unused]] : _file_slot_descs) {
302
17.4k
            _col_idxs.push_back(i++);
303
17.4k
        }
304
1.89k
    }
305
306
7.96k
    _line_reader_eof = false;
307
7.96k
    return Status::OK();
308
7.96k
}
309
310
// !FIXME: Here we should use MutableBlock
311
18.8k
Status CsvReader::get_next_block(Block* block, size_t* read_rows, bool* eof) {
312
18.8k
    if (_line_reader_eof) {
313
7.87k
        *eof = true;
314
7.87k
        return Status::OK();
315
7.87k
    }
316
317
10.9k
    const int batch_size = std::max(_state->batch_size(), (int)_MIN_BATCH_SIZE);
318
10.9k
    size_t rows = 0;
319
320
10.9k
    bool success = false;
321
10.9k
    bool is_remove_bom = false;
322
10.9k
    if (_push_down_agg_type == TPushAggOp::type::COUNT) {
323
159k
        while (rows < batch_size && !_line_reader_eof) {
324
158k
            const uint8_t* ptr = nullptr;
325
158k
            size_t size = 0;
326
158k
            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
159k
            if (_skip_lines == 0 && !is_remove_bom) {
331
604
                ptr = _remove_bom(ptr, size);
332
604
                is_remove_bom = true;
333
604
            }
334
335
            // _skip_lines > 0 means we do not need to remove bom
336
158k
            if (_skip_lines > 0) {
337
0
                _skip_lines--;
338
0
                is_remove_bom = true;
339
0
                continue;
340
0
            }
341
158k
            if (size == 0) {
342
604
                if (!_line_reader_eof && _state->is_read_csv_empty_line_as_null()) {
343
0
                    ++rows;
344
0
                }
345
                // Read empty line, continue
346
604
                continue;
347
604
            }
348
349
157k
            RETURN_IF_ERROR(_validate_line(Slice(ptr, size), &success));
350
157k
            ++rows;
351
157k
        }
352
604
        auto mutate_columns = block->mutate_columns();
353
604
        for (auto& col : mutate_columns) {
354
604
            col->resize(rows);
355
604
        }
356
604
        block->set_columns(std::move(mutate_columns));
357
10.3k
    } else {
358
10.3k
        auto columns = block->mutate_columns();
359
15.3M
        while (rows < batch_size && !_line_reader_eof) {
360
15.3M
            const uint8_t* ptr = nullptr;
361
15.3M
            size_t size = 0;
362
15.3M
            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
15.3M
            if (!is_remove_bom && _skip_lines == 0) {
367
10.0k
                ptr = _remove_bom(ptr, size);
368
10.0k
                is_remove_bom = true;
369
10.0k
            }
370
371
            // _skip_lines > 0 means we do not remove bom
372
15.3M
            if (_skip_lines > 0) {
373
329
                _skip_lines--;
374
329
                is_remove_bom = true;
375
329
                continue;
376
329
            }
377
15.3M
            if (size == 0) {
378
7.39k
                if (!_line_reader_eof && _state->is_read_csv_empty_line_as_null()) {
379
12
                    RETURN_IF_ERROR(_fill_empty_line(block, columns, &rows));
380
12
                }
381
                // Read empty line, continue
382
7.39k
                continue;
383
7.39k
            }
384
385
15.3M
            RETURN_IF_ERROR(_validate_line(Slice(ptr, size), &success));
386
15.3M
            if (!success) {
387
128
                continue;
388
128
            }
389
15.3M
            RETURN_IF_ERROR(_fill_dest_columns(Slice(ptr, size), block, columns, &rows));
390
15.3M
        }
391
10.3k
        block->set_columns(std::move(columns));
392
10.3k
    }
393
394
10.9k
    *eof = (rows == 0);
395
10.9k
    *read_rows = rows;
396
397
10.9k
    return Status::OK();
398
10.9k
}
399
400
Status CsvReader::get_columns(std::unordered_map<std::string, DataTypePtr>* name_to_type,
401
7.96k
                              std::unordered_set<std::string>* missing_cols) {
402
211k
    for (const auto& slot : _file_slot_descs) {
403
211k
        name_to_type->emplace(slot->col_name(), slot->type());
404
211k
    }
405
7.96k
    return Status::OK();
406
7.96k
}
407
408
// init decompressor, file reader and line reader for parsing schema
409
805
Status CsvReader::init_schema_reader() {
410
805
    _start_offset = _range.start_offset;
411
805
    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
805
    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
805
    _read_line = 1;
423
805
    _is_parse_name = false;
424
425
805
    if (_params.__isset.file_attributes && _params.file_attributes.__isset.header_type &&
426
805
        !_params.file_attributes.header_type.empty()) {
427
92
        std::string header_type = to_lower(_params.file_attributes.header_type);
428
92
        if (header_type == BeConsts::CSV_WITH_NAMES) {
429
63
            _is_parse_name = true;
430
63
        } else if (header_type == BeConsts::CSV_WITH_NAMES_AND_TYPES) {
431
29
            _read_line = 2;
432
29
            _is_parse_name = true;
433
29
        }
434
92
    }
435
436
805
    RETURN_IF_ERROR(_init_options());
437
805
    RETURN_IF_ERROR(_create_file_reader(true));
438
805
    RETURN_IF_ERROR(_create_decompressor());
439
805
    RETURN_IF_ERROR(_create_line_reader());
440
805
    return Status::OK();
441
805
}
442
443
Status CsvReader::get_parsed_schema(std::vector<std::string>* col_names,
444
804
                                    std::vector<DataTypePtr>* col_types) {
445
804
    if (_read_line == 1) {
446
776
        if (!_is_parse_name) { //parse csv file without names and types
447
713
            size_t col_nums = 0;
448
713
            RETURN_IF_ERROR(_parse_col_nums(&col_nums));
449
7.93k
            for (size_t i = 0; i < col_nums; ++i) {
450
7.22k
                col_names->emplace_back("c" + std::to_string(i + 1));
451
7.22k
            }
452
702
        } else { // parse csv file with names
453
63
            RETURN_IF_ERROR(_parse_col_names(col_names));
454
63
        }
455
456
8.21k
        for (size_t j = 0; j < col_names->size(); ++j) {
457
7.44k
            col_types->emplace_back(
458
7.44k
                    DataTypeFactory::instance().create_data_type(PrimitiveType::TYPE_STRING, true));
459
7.44k
        }
460
765
    } else { // parse csv file with names and types
461
28
        RETURN_IF_ERROR(_parse_col_names(col_names));
462
28
        RETURN_IF_ERROR(_parse_col_types(col_names->size(), col_types));
463
28
    }
464
793
    return Status::OK();
465
804
}
466
467
214M
Status CsvReader::_deserialize_nullable_string(IColumn& column, Slice& slice) {
468
214M
    auto& null_column = assert_cast<ColumnNullable&>(column);
469
214M
    if (_empty_field_as_null) {
470
60
        if (slice.size == 0) {
471
5
            null_column.insert_data(nullptr, 0);
472
5
            return Status::OK();
473
5
        }
474
60
    }
475
214M
    if (_options.null_len > 0 && !(_options.converted_from_string && slice.trim_double_quotes())) {
476
214M
        if (slice.compare(Slice(_options.null_format, _options.null_len)) == 0) {
477
31.2k
            null_column.insert_data(nullptr, 0);
478
31.2k
            return Status::OK();
479
31.2k
        }
480
214M
    }
481
214M
    static DataTypeStringSerDe stringSerDe(TYPE_STRING);
482
214M
    auto st = stringSerDe.deserialize_one_cell_from_csv(null_column.get_nested_column(), slice,
483
214M
                                                        _options);
484
214M
    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
214M
    null_column.get_null_map_data().push_back(0);
491
214M
    return Status::OK();
492
214M
}
493
494
3.64k
Status CsvReader::_init_options() {
495
    // get column_separator and line_delimiter
496
3.64k
    _value_separator = _params.file_attributes.text_params.column_separator;
497
3.64k
    _value_separator_length = _value_separator.size();
498
3.64k
    _line_delimiter = _params.file_attributes.text_params.line_delimiter;
499
3.64k
    _line_delimiter_length = _line_delimiter.size();
500
3.64k
    if (_params.file_attributes.text_params.__isset.enclose) {
501
3.63k
        _enclose = _params.file_attributes.text_params.enclose;
502
3.63k
    }
503
3.64k
    if (_params.file_attributes.text_params.__isset.escape) {
504
3.63k
        _escape = _params.file_attributes.text_params.escape;
505
3.63k
    }
506
507
3.64k
    _trim_tailing_spaces =
508
3.64k
            (_state != nullptr && _state->trim_tailing_spaces_for_external_table_query());
509
510
3.64k
    _options.escape_char = _escape;
511
3.64k
    _options.quote_char = _enclose;
512
513
3.64k
    if (_params.file_attributes.text_params.collection_delimiter.empty()) {
514
3.63k
        _options.collection_delim = ',';
515
3.63k
    } else {
516
2
        _options.collection_delim = _params.file_attributes.text_params.collection_delimiter[0];
517
2
    }
518
3.64k
    if (_params.file_attributes.text_params.mapkv_delimiter.empty()) {
519
3.63k
        _options.map_key_delim = ':';
520
3.63k
    } else {
521
1
        _options.map_key_delim = _params.file_attributes.text_params.mapkv_delimiter[0];
522
1
    }
523
524
3.64k
    if (_params.file_attributes.text_params.__isset.null_format) {
525
52
        _options.null_format = _params.file_attributes.text_params.null_format.data();
526
52
        _options.null_len = _params.file_attributes.text_params.null_format.length();
527
52
    }
528
529
3.64k
    if (_params.file_attributes.__isset.trim_double_quotes) {
530
3.63k
        _trim_double_quotes = _params.file_attributes.trim_double_quotes;
531
3.63k
    }
532
3.64k
    _options.converted_from_string = _trim_double_quotes;
533
534
3.64k
    if (_state != nullptr) {
535
2.83k
        _keep_cr = _state->query_options().keep_carriage_return;
536
2.83k
    }
537
538
3.64k
    if (_params.file_attributes.text_params.__isset.empty_field_as_null) {
539
3.58k
        _empty_field_as_null = _params.file_attributes.text_params.empty_field_as_null;
540
3.58k
    }
541
3.64k
    return Status::OK();
542
3.64k
}
543
544
8.76k
Status CsvReader::_create_decompressor() {
545
8.76k
    if (_file_compress_type != TFileCompressType::UNKNOWN) {
546
8.67k
        RETURN_IF_ERROR(Decompressor::create_decompressor(_file_compress_type, &_decompressor));
547
8.67k
    } else {
548
84
        RETURN_IF_ERROR(Decompressor::create_decompressor(_file_format_type, &_decompressor));
549
84
    }
550
551
8.76k
    return Status::OK();
552
8.76k
}
553
554
8.76k
Status CsvReader::_create_file_reader(bool need_schema) {
555
8.76k
    if (_params.file_type == TFileType::FILE_STREAM) {
556
1.97k
        RETURN_IF_ERROR(FileFactory::create_pipe_reader(_range.load_id, &_file_reader, _state,
557
1.97k
                                                        need_schema));
558
6.79k
    } else {
559
18.4E
        _file_description.mtime = _range.__isset.modification_time ? _range.modification_time : 0;
560
6.79k
        io::FileReaderOptions reader_options =
561
6.79k
                FileFactory::get_reader_options(_state, _file_description);
562
6.79k
        io::FileReaderSPtr file_reader;
563
6.79k
        if (_io_ctx_holder) {
564
681
            file_reader = DORIS_TRY(io::DelegateReader::create_file_reader(
565
681
                    _profile, _system_properties, _file_description, reader_options,
566
681
                    io::DelegateReader::AccessMode::SEQUENTIAL,
567
681
                    std::static_pointer_cast<const io::IOContext>(_io_ctx_holder),
568
681
                    io::PrefetchRange(_range.start_offset, _range.start_offset + _range.size)));
569
6.10k
        } else {
570
6.10k
            file_reader = DORIS_TRY(io::DelegateReader::create_file_reader(
571
6.10k
                    _profile, _system_properties, _file_description, reader_options,
572
6.10k
                    io::DelegateReader::AccessMode::SEQUENTIAL, _io_ctx,
573
6.10k
                    io::PrefetchRange(_range.start_offset, _range.start_offset + _range.size)));
574
6.10k
        }
575
6.79k
        _file_reader = _io_ctx ? std::make_shared<io::TracingFileReader>(std::move(file_reader),
576
6.79k
                                                                         _io_ctx->file_reader_stats)
577
18.4E
                               : file_reader;
578
6.79k
    }
579
8.76k
    if (_file_reader->size() == 0 && _params.file_type != TFileType::FILE_STREAM &&
580
8.76k
        _params.file_type != TFileType::FILE_BROKER) {
581
0
        return Status::EndOfFile("init reader failed, empty csv file: " + _range.path);
582
0
    }
583
8.76k
    return Status::OK();
584
8.76k
}
585
586
3.63k
Status CsvReader::_create_line_reader() {
587
3.63k
    std::shared_ptr<TextLineReaderContextIf> text_line_reader_ctx;
588
3.63k
    if (_enclose == 0) {
589
3.46k
        text_line_reader_ctx = std::make_shared<PlainTextLineReaderCtx>(
590
3.46k
                _line_delimiter, _line_delimiter_length, _keep_cr);
591
3.46k
        _fields_splitter = std::make_unique<PlainCsvTextFieldSplitter>(
592
3.46k
                _trim_tailing_spaces, false, _value_separator, _value_separator_length, -1);
593
594
3.46k
    } else {
595
        // in load task, the _file_slot_descs is empty vector, so we need to set col_sep_num to 0
596
171
        size_t col_sep_num = _file_slot_descs.size() > 1 ? _file_slot_descs.size() - 1 : 0;
597
171
        _enclose_reader_ctx = std::make_shared<EncloseCsvLineReaderCtx>(
598
171
                _line_delimiter, _line_delimiter_length, _value_separator, _value_separator_length,
599
171
                col_sep_num, _enclose, _escape, _keep_cr);
600
171
        text_line_reader_ctx = _enclose_reader_ctx;
601
602
171
        _fields_splitter = std::make_unique<EncloseCsvTextFieldSplitter>(
603
171
                _trim_tailing_spaces, true, _enclose_reader_ctx, _value_separator_length, _enclose);
604
171
    }
605
3.63k
    switch (_file_format_type) {
606
3.56k
    case TFileFormatType::FORMAT_CSV_PLAIN:
607
3.56k
        [[fallthrough]];
608
3.56k
    case TFileFormatType::FORMAT_CSV_GZ:
609
3.56k
        [[fallthrough]];
610
3.56k
    case TFileFormatType::FORMAT_CSV_BZ2:
611
3.56k
        [[fallthrough]];
612
3.56k
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
613
3.56k
        [[fallthrough]];
614
3.56k
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
615
3.56k
        [[fallthrough]];
616
3.56k
    case TFileFormatType::FORMAT_CSV_LZOP:
617
3.56k
        [[fallthrough]];
618
3.56k
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
619
3.56k
        [[fallthrough]];
620
3.56k
    case TFileFormatType::FORMAT_CSV_DEFLATE:
621
3.56k
        _line_reader =
622
3.56k
                NewPlainTextLineReader::create_unique(_profile, _file_reader, _decompressor.get(),
623
3.56k
                                                      text_line_reader_ctx, _size, _start_offset);
624
625
3.56k
        break;
626
77
    case TFileFormatType::FORMAT_PROTO:
627
77
        _fields_splitter = std::make_unique<CsvProtoFieldSplitter>();
628
77
        _line_reader = NewPlainBinaryLineReader::create_unique(_file_reader);
629
77
        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
3.63k
    }
635
3.64k
    return Status::OK();
636
3.63k
}
637
638
5.24k
Status CsvReader::_deserialize_one_cell(DataTypeSerDeSPtr serde, IColumn& column, Slice& slice) {
639
5.24k
    return serde->deserialize_one_cell_from_csv(column, slice, _options);
640
5.24k
}
641
642
Status CsvReader::_fill_dest_columns(const Slice& line, Block* block,
643
15.3M
                                     std::vector<MutableColumnPtr>& columns, size_t* rows) {
644
15.3M
    bool is_success = false;
645
646
15.3M
    RETURN_IF_ERROR(_line_split_to_values(line, &is_success));
647
15.3M
    if (UNLIKELY(!is_success)) {
648
        // If not success, which means we met an invalid row, filter this row and return.
649
539
        return Status::OK();
650
539
    }
651
652
238M
    for (int i = 0; i < _file_slot_descs.size(); ++i) {
653
222M
        int col_idx = _col_idxs[i];
654
        // col idx is out of range, fill with null format
655
222M
        auto value = col_idx < _split_values.size()
656
224M
                             ? _split_values[col_idx]
657
18.4E
                             : Slice(_options.null_format, _options.null_len);
658
659
222M
        IColumn* col_ptr = columns[i].get();
660
222M
        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
41.8M
            col_ptr = const_cast<IColumn*>(
664
41.8M
                    block->get_by_position(_file_slot_idx_map[i]).column.get());
665
41.8M
        }
666
667
222M
        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
218M
            RETURN_IF_ERROR(_deserialize_nullable_string(*col_ptr, value));
672
218M
        } else {
673
4.52M
            RETURN_IF_ERROR(_deserialize_one_cell(_serdes[i], *col_ptr, value));
674
4.52M
        }
675
222M
    }
676
15.3M
    ++(*rows);
677
678
15.3M
    return Status::OK();
679
15.3M
}
680
681
Status CsvReader::_fill_empty_line(Block* block, std::vector<MutableColumnPtr>& columns,
682
12
                                   size_t* rows) {
683
48
    for (int i = 0; i < _file_slot_descs.size(); ++i) {
684
36
        IColumn* col_ptr = columns[i].get();
685
36
        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
36
            col_ptr = const_cast<IColumn*>(
689
36
                    block->get_by_position(_file_slot_idx_map[i]).column.get());
690
36
        }
691
36
        auto& null_column = assert_cast<ColumnNullable&>(*col_ptr);
692
36
        null_column.insert_data(nullptr, 0);
693
36
    }
694
12
    ++(*rows);
695
12
    return Status::OK();
696
12
}
697
698
15.0M
Status CsvReader::_validate_line(const Slice& line, bool* success) {
699
15.0M
    if (!_is_proto_format && !validate_utf8(_params, line.data, line.size)) {
700
132
        if (!_is_load) {
701
4
            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
128
            return Status::OK();
711
128
        }
712
132
    }
713
15.0M
    *success = true;
714
15.0M
    return Status::OK();
715
15.0M
}
716
717
15.3M
Status CsvReader::_line_split_to_values(const Slice& line, bool* success) {
718
15.3M
    _split_line(line);
719
720
15.3M
    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
11.0M
        bool ignore_col = false;
725
11.0M
        ignore_col = _params.__isset.file_attributes &&
726
11.0M
                     _params.file_attributes.__isset.ignore_csv_redundant_col &&
727
11.0M
                     _params.file_attributes.ignore_csv_redundant_col;
728
729
11.0M
        if ((!ignore_col && _split_values.size() != _file_slot_descs.size()) ||
730
11.0M
            (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
544
                        fmt::format_to(error_msg, ")");
753
544
                        return fmt::to_string(error_msg);
754
544
                    }));
755
539
            return Status::OK();
756
544
        }
757
11.0M
    }
758
759
15.3M
    *success = true;
760
15.3M
    return Status::OK();
761
15.3M
}
762
763
15.3M
void CsvReader::_split_line(const Slice& line) {
764
15.3M
    _split_values.clear();
765
15.3M
    _fields_splitter->split_line(line, &_split_values);
766
15.3M
}
767
768
713
Status CsvReader::_parse_col_nums(size_t* col_nums) {
769
713
    const uint8_t* ptr = nullptr;
770
713
    size_t size = 0;
771
713
    RETURN_IF_ERROR(_line_reader->read_line(&ptr, &size, &_line_reader_eof, _io_ctx));
772
713
    if (size == 0) {
773
2
        return Status::InternalError<false>(
774
2
                "The first line is empty, can not parse column numbers");
775
2
    }
776
711
    if (!validate_utf8(_params, reinterpret_cast<const char*>(ptr), size)) {
777
9
        return Status::InternalError<false>("Only support csv data in utf8 codec");
778
9
    }
779
702
    ptr = _remove_bom(ptr, size);
780
702
    _split_line(Slice(ptr, size));
781
702
    *col_nums = _split_values.size();
782
702
    return Status::OK();
783
711
}
784
785
92
Status CsvReader::_parse_col_names(std::vector<std::string>* col_names) {
786
92
    const uint8_t* ptr = nullptr;
787
92
    size_t size = 0;
788
    // no use of _line_reader_eof
789
92
    RETURN_IF_ERROR(_line_reader->read_line(&ptr, &size, &_line_reader_eof, _io_ctx));
790
92
    if (size == 0) {
791
0
        return Status::InternalError<false>("The first line is empty, can not parse column names");
792
0
    }
793
92
    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
92
    ptr = _remove_bom(ptr, size);
797
92
    _split_line(Slice(ptr, size));
798
345
    for (auto _split_value : _split_values) {
799
345
        col_names->emplace_back(_split_value.to_string());
800
345
    }
801
92
    return Status::OK();
802
92
}
803
804
// TODO(ftw): parse type
805
29
Status CsvReader::_parse_col_types(size_t col_nums, std::vector<DataTypePtr>* col_types) {
806
    // delete after.
807
155
    for (size_t i = 0; i < col_nums; ++i) {
808
126
        col_types->emplace_back(make_nullable(std::make_shared<DataTypeString>()));
809
126
    }
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
29
    return Status::OK();
818
29
}
819
820
11.4k
const uint8_t* CsvReader::_remove_bom(const uint8_t* ptr, size_t& size) {
821
11.4k
    if (size >= 3 && ptr[0] == 0xEF && ptr[1] == 0xBB && ptr[2] == 0xBF) {
822
7
        LOG(INFO) << "remove bom";
823
7
        constexpr size_t bom_size = 3;
824
7
        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
7
        if (_enclose_reader_ctx) {
829
1
            _enclose_reader_ctx->adjust_column_sep_positions(bom_size);
830
1
        }
831
7
        return ptr + bom_size;
832
7
    }
833
11.4k
    return ptr;
834
11.4k
}
835
836
7.96k
Status CsvReader::close() {
837
7.96k
    if (_line_reader) {
838
7.96k
        _line_reader->close();
839
7.96k
    }
840
841
7.96k
    if (_file_reader) {
842
7.96k
        RETURN_IF_ERROR(_file_reader->close());
843
7.96k
    }
844
845
7.96k
    return Status::OK();
846
7.96k
}
847
848
#include "common/compile_check_end.h"
849
} // namespace doris