Coverage Report

Created: 2026-05-17 20:45

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