Coverage Report

Created: 2026-09-30 17:30

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