Coverage Report

Created: 2026-03-13 12:42

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