Coverage Report

Created: 2026-06-05 04:37

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
11.8M
size_t columns_byte_size(const std::vector<MutableColumnPtr>& columns) {
71
11.8M
    size_t bytes = 0;
72
186M
    for (const auto& column : columns) {
73
186M
        DCHECK(column.get() != nullptr);
74
186M
        bytes += column->byte_size();
75
186M
    }
76
11.8M
    return bytes;
77
11.8M
}
78
79
} // namespace
80
81
712
void EncloseCsvTextFieldSplitter::do_split(const Slice& line, std::vector<Slice>* splitted_values) {
82
712
    const char* data = line.data;
83
712
    const auto& column_sep_positions = _text_line_reader_ctx->column_sep_positions();
84
712
    size_t value_start_offset = 0;
85
2.59k
    for (auto idx : column_sep_positions) {
86
2.59k
        process_value_func(data, value_start_offset, idx - value_start_offset, _trimming_char,
87
2.59k
                           splitted_values);
88
2.59k
        value_start_offset = idx + _value_sep_len;
89
2.59k
    }
90
712
    if (line.size >= value_start_offset) {
91
        // process the last column
92
710
        process_value_func(data, value_start_offset, line.size - value_start_offset, _trimming_char,
93
710
                           splitted_values);
94
710
    }
95
712
}
96
97
void PlainCsvTextFieldSplitter::_split_field_single_char(const Slice& line,
98
11.9M
                                                         std::vector<Slice>* splitted_values) {
99
11.9M
    const char* data = line.data;
100
11.9M
    const size_t size = line.size;
101
11.9M
    size_t value_start = 0;
102
1.52G
    for (size_t i = 0; i < size; ++i) {
103
1.51G
        if (data[i] == _value_sep[0]) {
104
185M
            process_value_func(data, value_start, i - value_start, _trimming_char, splitted_values);
105
185M
            value_start = i + _value_sep_len;
106
185M
        }
107
1.51G
    }
108
11.9M
    process_value_func(data, value_start, size - value_start, _trimming_char, splitted_values);
109
11.9M
}
110
111
void PlainCsvTextFieldSplitter::_split_field_multi_char(const Slice& line,
112
162
                                                        std::vector<Slice>* splitted_values) {
113
162
    size_t start = 0;  // point to the start pos of next col value.
114
162
    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
162
    std::vector<int> next(_value_sep_len);
128
162
    next[0] = -1;
129
403
    for (int i = 1, j = -1; i < _value_sep_len; i++) {
130
261
        while (j > -1 && _value_sep[i] != _value_sep[j + 1]) {
131
20
            j = next[j];
132
20
        }
133
241
        if (_value_sep[i] == _value_sep[j + 1]) {
134
130
            j++;
135
130
        }
136
241
        next[i] = j;
137
241
    }
138
139
6.96k
    for (int i = 0, j = -1; i < line.size; i++) {
140
        // i : line
141
        // j : _value_sep
142
7.09k
        while (j > -1 && line[i] != _value_sep[j + 1]) {
143
290
            j = next[j];
144
290
        }
145
6.80k
        if (line[i] == _value_sep[j + 1]) {
146
2.17k
            j++;
147
2.17k
        }
148
6.80k
        if (j == _value_sep_len - 1) {
149
832
            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
832
            if (curpos >= start) {
167
803
                process_value_func(line.data, start, curpos - start, _trimming_char,
168
803
                                   splitted_values);
169
803
                start = i + 1;
170
803
            }
171
172
832
            j = next[j];
173
832
        }
174
6.80k
    }
175
162
    process_value_func(line.data, start, line.size - start, _trimming_char, splitted_values);
176
162
}
177
178
11.9M
void PlainCsvTextFieldSplitter::do_split(const Slice& line, std::vector<Slice>* splitted_values) {
179
11.9M
    if (is_single_char_delim) {
180
11.9M
        _split_field_single_char(line, splitted_values);
181
18.4E
    } else {
182
18.4E
        _split_field_multi_char(line, splitted_values);
183
18.4E
    }
184
11.9M
}
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
2.40k
        : _profile(profile),
191
2.40k
          _params(params),
192
2.40k
          _file_reader(nullptr),
193
2.40k
          _line_reader(nullptr),
194
2.40k
          _decompressor(nullptr),
195
2.40k
          _state(state),
196
2.40k
          _counter(counter),
197
2.40k
          _range(range),
198
2.40k
          _file_slot_descs(file_slot_descs),
199
2.40k
          _line_reader_eof(false),
200
2.40k
          _skip_lines(0),
201
2.40k
          _io_ctx(io_ctx),
202
2.40k
          _io_ctx_holder(std::move(io_ctx_holder)),
203
2.40k
          _batch_size(std::max(batch_size, 1UL)) {
204
2.40k
    if (_io_ctx == nullptr && _io_ctx_holder) {
205
2.00k
        _io_ctx = _io_ctx_holder.get();
206
2.00k
    }
207
2.40k
    _file_format_type = _params.format_type;
208
2.40k
    _is_proto_format = _file_format_type == TFileFormatType::FORMAT_PROTO;
209
2.40k
    if (_range.__isset.compress_type) {
210
        // for compatibility
211
622
        _file_compress_type = _range.compress_type;
212
1.78k
    } else {
213
1.78k
        _file_compress_type = _params.compress_type;
214
1.78k
    }
215
2.40k
    _size = _range.size;
216
217
2.40k
    _split_values.reserve(_file_slot_descs.size());
218
2.40k
    _init_system_properties();
219
2.40k
    _init_file_description();
220
2.40k
    _serdes = create_data_type_serdes(_file_slot_descs);
221
2.40k
}
222
223
2.40k
void CsvReader::_init_system_properties() {
224
2.40k
    if (_range.__isset.file_type) {
225
        // for compatibility
226
601
        _system_properties.system_type = _range.file_type;
227
1.80k
    } else {
228
1.80k
        _system_properties.system_type = _params.file_type;
229
1.80k
    }
230
2.40k
    _system_properties.properties = _params.properties;
231
2.40k
    _system_properties.hdfs_params = _params.hdfs_params;
232
2.40k
    if (_params.__isset.broker_addresses) {
233
1.67k
        _system_properties.broker_addresses.assign(_params.broker_addresses.begin(),
234
1.67k
                                                   _params.broker_addresses.end());
235
1.67k
    }
236
2.40k
}
237
238
2.40k
void CsvReader::_init_file_description() {
239
2.40k
    _file_description.path = _range.path;
240
2.40k
    _file_description.file_size = _range.__isset.file_size ? _range.file_size : -1;
241
2.40k
    if (_range.__isset.fs_name) {
242
0
        _file_description.fs_name = _range.fs_name;
243
0
    }
244
2.40k
    if (_range.__isset.file_cache_admission) {
245
224
        _file_description.file_cache_admission = _range.file_cache_admission;
246
224
    }
247
2.40k
}
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
2.00k
Status CsvReader::_open_file_reader(ReaderInitContext* base_ctx) {
328
2.00k
    _start_offset = _range.start_offset;
329
2.00k
    if (_start_offset == 0) {
330
2.00k
        if (_params.__isset.file_attributes && _params.file_attributes.__isset.header_type &&
331
2.00k
            !_params.file_attributes.header_type.empty()) {
332
44
            std::string header_type = to_lower(_params.file_attributes.header_type);
333
44
            if (header_type == BeConsts::CSV_WITH_NAMES) {
334
24
                _skip_lines = 1;
335
24
            } else if (header_type == BeConsts::CSV_WITH_NAMES_AND_TYPES) {
336
20
                _skip_lines = 2;
337
20
            }
338
1.95k
        } else if (_params.file_attributes.__isset.skip_lines) {
339
1.95k
            _skip_lines = _params.file_attributes.skip_lines;
340
1.95k
        }
341
2.00k
    } else if (_start_offset != 0) {
342
4
        if ((_file_compress_type != TFileCompressType::PLAIN) ||
343
4
            (_file_compress_type == TFileCompressType::UNKNOWN &&
344
4
             _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
4
        int64_t pre_read_len = std::min(
348
4
                static_cast<int64_t>(_params.file_attributes.text_params.line_delimiter.size()),
349
4
                _start_offset);
350
4
        _start_offset -= pre_read_len;
351
4
        _size += pre_read_len;
352
4
        _skip_lines = 1;
353
4
    }
354
355
2.00k
    RETURN_IF_ERROR(_init_options());
356
2.00k
    RETURN_IF_ERROR(_create_file_reader(false));
357
2.00k
    return Status::OK();
358
2.00k
}
359
360
2.00k
Status CsvReader::_do_init_reader(ReaderInitContext* base_ctx) {
361
2.00k
    auto* ctx = checked_context_cast<CsvInitContext>(base_ctx);
362
2.00k
    _is_load = ctx->is_load;
363
364
2.00k
    _use_nullable_string_opt.resize(_file_slot_descs.size());
365
17.3k
    for (int i = 0; i < _file_slot_descs.size(); ++i) {
366
15.3k
        auto data_type_ptr = _file_slot_descs[i]->get_data_type_ptr();
367
15.3k
        if (data_type_ptr->is_nullable() && is_string_type(data_type_ptr->get_primitive_type())) {
368
15.3k
            _use_nullable_string_opt[i] = 1;
369
15.3k
        }
370
15.3k
    }
371
372
2.00k
    RETURN_IF_ERROR(_create_decompressor());
373
2.00k
    RETURN_IF_ERROR(_create_line_reader());
374
375
2.00k
    if (!_is_load) {
376
332
        DCHECK(_params.__isset.column_idxs);
377
332
        _col_idxs = _params.column_idxs;
378
332
        int idx = 0;
379
2.30k
        for (const auto& slot_info : _params.required_slots) {
380
2.30k
            if (slot_info.is_file_slot) {
381
2.30k
                _file_slot_idx_map.push_back(idx);
382
2.30k
            }
383
2.30k
            idx++;
384
2.30k
        }
385
1.67k
    } else {
386
1.67k
        int i = 0;
387
13.0k
        for (const auto& desc [[maybe_unused]] : _file_slot_descs) {
388
13.0k
            _col_idxs.push_back(i++);
389
13.0k
        }
390
1.67k
    }
391
2.00k
    _line_reader_eof = false;
392
2.00k
    return Status::OK();
393
2.00k
}
394
395
7.13k
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
7.13k
    _batch_size = std::max(batch_size, 1UL);
401
7.13k
}
402
403
// !FIXME: Here we should use MutableBlock
404
7.14k
Status CsvReader::_do_get_next_block(Block* block, size_t* read_rows, bool* eof) {
405
7.14k
    if (_line_reader_eof) {
406
1.95k
        *eof = true;
407
1.95k
        return Status::OK();
408
1.95k
    }
409
410
5.18k
    const size_t batch_size = _batch_size;
411
5.18k
    const auto max_block_bytes = _state->preferred_block_size_bytes();
412
5.18k
    size_t rows = 0;
413
414
5.18k
    bool success = false;
415
5.18k
    bool is_remove_bom = false;
416
5.18k
    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
5.18k
    } else {
452
5.18k
        auto columns_guard = block->mutate_columns_scoped();
453
5.18k
        auto& columns = columns_guard.mutable_columns();
454
11.8M
        while (rows < batch_size && !_line_reader_eof &&
455
11.8M
               (columns_byte_size(columns) < max_block_bytes)) {
456
11.8M
            const uint8_t* ptr = nullptr;
457
11.8M
            size_t size = 0;
458
11.8M
            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
11.8M
            if (!is_remove_bom && _skip_lines == 0) {
463
5.11k
                ptr = _remove_bom(ptr, size);
464
5.11k
                is_remove_bom = true;
465
5.11k
            }
466
467
            // _skip_lines > 0 means we do not remove bom
468
11.8M
            if (_skip_lines > 0) {
469
123
                _skip_lines--;
470
123
                is_remove_bom = true;
471
123
                continue;
472
123
            }
473
11.8M
            if (size == 0) {
474
2.01k
                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
2.01k
                continue;
479
2.01k
            }
480
481
11.8M
            RETURN_IF_ERROR(_validate_line(Slice(ptr, size), &success));
482
11.8M
            if (!success) {
483
128
                continue;
484
128
            }
485
11.8M
            RETURN_IF_ERROR(_fill_dest_columns(Slice(ptr, size), columns, &rows));
486
11.8M
        }
487
5.18k
    }
488
489
5.17k
    *eof = (rows == 0);
490
5.17k
    *read_rows = rows;
491
492
5.17k
    return Status::OK();
493
5.18k
}
494
495
2.00k
Status CsvReader::_get_columns_impl(std::unordered_map<std::string, DataTypePtr>* name_to_type) {
496
15.3k
    for (const auto& slot : _file_slot_descs) {
497
15.3k
        name_to_type->emplace(slot->col_name(), slot->type());
498
15.3k
    }
499
2.00k
    return Status::OK();
500
2.00k
}
501
502
// init decompressor, file reader and line reader for parsing schema
503
398
Status CsvReader::init_schema_reader() {
504
398
    _start_offset = _range.start_offset;
505
398
    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
398
    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
398
    _read_line = 1;
517
398
    _is_parse_name = false;
518
519
398
    if (_params.__isset.file_attributes && _params.file_attributes.__isset.header_type &&
520
398
        !_params.file_attributes.header_type.empty()) {
521
48
        std::string header_type = to_lower(_params.file_attributes.header_type);
522
48
        if (header_type == BeConsts::CSV_WITH_NAMES) {
523
25
            _is_parse_name = true;
524
25
        } else if (header_type == BeConsts::CSV_WITH_NAMES_AND_TYPES) {
525
23
            _read_line = 2;
526
23
            _is_parse_name = true;
527
23
        }
528
48
    }
529
530
398
    RETURN_IF_ERROR(_init_options());
531
398
    RETURN_IF_ERROR(_create_file_reader(true));
532
398
    RETURN_IF_ERROR(_create_decompressor());
533
398
    RETURN_IF_ERROR(_create_line_reader());
534
398
    return Status::OK();
535
398
}
536
537
Status CsvReader::get_parsed_schema(std::vector<std::string>* col_names,
538
398
                                    std::vector<DataTypePtr>* col_types) {
539
398
    if (_read_line == 1) {
540
375
        if (!_is_parse_name) { //parse csv file without names and types
541
350
            size_t col_nums = 0;
542
350
            RETURN_IF_ERROR(_parse_col_nums(&col_nums));
543
2.92k
            for (size_t i = 0; i < col_nums; ++i) {
544
2.57k
                col_names->emplace_back("c" + std::to_string(i + 1));
545
2.57k
            }
546
349
        } else { // parse csv file with names
547
25
            RETURN_IF_ERROR(_parse_col_names(col_names));
548
25
        }
549
550
3.05k
        for (size_t j = 0; j < col_names->size(); ++j) {
551
2.67k
            col_types->emplace_back(
552
2.67k
                    DataTypeFactory::instance().create_data_type(PrimitiveType::TYPE_STRING, true));
553
2.67k
        }
554
374
    } else { // parse csv file with names and types
555
23
        RETURN_IF_ERROR(_parse_col_names(col_names));
556
23
        RETURN_IF_ERROR(_parse_col_types(col_names->size(), col_types));
557
23
    }
558
397
    return Status::OK();
559
398
}
560
561
193M
Status CsvReader::_deserialize_nullable_string(IColumn& column, Slice& slice) {
562
193M
    auto& null_column = assert_cast<ColumnNullable&>(column);
563
193M
    if (_empty_field_as_null) {
564
60
        if (slice.size == 0) {
565
5
            null_column.insert_data(nullptr, 0);
566
5
            return Status::OK();
567
5
        }
568
60
    }
569
193M
    if (_options.null_len > 0 && !(_options.converted_from_string && slice.trim_double_quotes())) {
570
193M
        if (slice.compare(Slice(_options.null_format, _options.null_len)) == 0) {
571
30.6k
            null_column.insert_data(nullptr, 0);
572
30.6k
            return Status::OK();
573
30.6k
        }
574
193M
    }
575
193M
    static DataTypeStringSerDe stringSerDe(TYPE_STRING);
576
193M
    auto st = stringSerDe.deserialize_one_cell_from_csv(null_column.get_nested_column(), slice,
577
193M
                                                        _options);
578
193M
    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
193M
    null_column.get_null_map_data().push_back(0);
585
193M
    return Status::OK();
586
193M
}
587
588
2.40k
Status CsvReader::_init_options() {
589
    // get column_separator and line_delimiter
590
2.40k
    _value_separator = _params.file_attributes.text_params.column_separator;
591
2.40k
    _value_separator_length = _value_separator.size();
592
2.40k
    _line_delimiter = _params.file_attributes.text_params.line_delimiter;
593
2.40k
    _line_delimiter_length = _line_delimiter.size();
594
2.40k
    if (_params.file_attributes.text_params.__isset.enclose) {
595
2.40k
        _enclose = _params.file_attributes.text_params.enclose;
596
2.40k
    }
597
2.40k
    if (_params.file_attributes.text_params.__isset.escape) {
598
2.40k
        _escape = _params.file_attributes.text_params.escape;
599
2.40k
    }
600
601
2.40k
    _trim_tailing_spaces =
602
2.40k
            (_state != nullptr && _state->trim_tailing_spaces_for_external_table_query());
603
604
2.40k
    _options.escape_char = _escape;
605
2.40k
    _options.quote_char = _enclose;
606
607
2.40k
    if (_params.file_attributes.text_params.collection_delimiter.empty()) {
608
2.40k
        _options.collection_delim = ',';
609
2.40k
    } else {
610
0
        _options.collection_delim = _params.file_attributes.text_params.collection_delimiter[0];
611
0
    }
612
2.40k
    if (_params.file_attributes.text_params.mapkv_delimiter.empty()) {
613
2.39k
        _options.map_key_delim = ':';
614
2.39k
    } else {
615
2
        _options.map_key_delim = _params.file_attributes.text_params.mapkv_delimiter[0];
616
2
    }
617
618
2.40k
    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
2.40k
    if (_params.file_attributes.__isset.trim_double_quotes) {
624
2.40k
        _trim_double_quotes = _params.file_attributes.trim_double_quotes;
625
2.40k
    }
626
2.40k
    _options.converted_from_string = _trim_double_quotes;
627
628
2.40k
    if (_state != nullptr) {
629
2.00k
        _keep_cr = _state->query_options().keep_carriage_return;
630
2.00k
    }
631
632
2.40k
    if (_params.file_attributes.text_params.__isset.empty_field_as_null) {
633
2.40k
        _empty_field_as_null = _params.file_attributes.text_params.empty_field_as_null;
634
2.40k
    }
635
2.40k
    return Status::OK();
636
2.40k
}
637
638
2.40k
Status CsvReader::_create_decompressor() {
639
2.40k
    if (_file_compress_type != TFileCompressType::UNKNOWN) {
640
2.31k
        RETURN_IF_ERROR(Decompressor::create_decompressor(_file_compress_type, &_decompressor));
641
2.31k
    } else {
642
86
        RETURN_IF_ERROR(Decompressor::create_decompressor(_file_format_type, &_decompressor));
643
86
    }
644
645
2.40k
    return Status::OK();
646
2.40k
}
647
648
2.40k
Status CsvReader::_create_file_reader(bool need_schema) {
649
2.40k
    if (_params.file_type == TFileType::FILE_STREAM) {
650
1.82k
        RETURN_IF_ERROR(FileFactory::create_pipe_reader(_range.load_id, &_file_reader, _state,
651
1.82k
                                                        need_schema));
652
1.82k
    } else {
653
577
        _file_description.mtime = _range.__isset.modification_time ? _range.modification_time : 0;
654
577
        io::FileReaderOptions reader_options =
655
577
                FileFactory::get_reader_options(_state, _file_description);
656
577
        io::FileReaderSPtr file_reader;
657
577
        if (_io_ctx_holder) {
658
577
            file_reader = DORIS_TRY(io::DelegateReader::create_file_reader(
659
577
                    _profile, _system_properties, _file_description, reader_options,
660
577
                    io::DelegateReader::AccessMode::SEQUENTIAL,
661
577
                    std::static_pointer_cast<const io::IOContext>(_io_ctx_holder),
662
577
                    io::PrefetchRange(_range.start_offset, _range.start_offset + _range.size)));
663
577
        } 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
577
        _file_reader = _io_ctx && _io_ctx->file_reader_stats
670
577
                               ? std::make_shared<io::TracingFileReader>(std::move(file_reader),
671
576
                                                                         _io_ctx->file_reader_stats)
672
577
                               : file_reader;
673
577
    }
674
2.40k
    if (_file_reader->size() == 0 && _params.file_type != TFileType::FILE_STREAM &&
675
2.40k
        _params.file_type != TFileType::FILE_BROKER) {
676
0
        return Status::EndOfFile("init reader failed, empty csv file: " + _range.path);
677
0
    }
678
2.40k
    return Status::OK();
679
2.40k
}
680
681
2.40k
Status CsvReader::_create_line_reader() {
682
2.40k
    std::shared_ptr<TextLineReaderContextIf> text_line_reader_ctx;
683
2.40k
    if (_enclose == 0) {
684
2.30k
        text_line_reader_ctx = std::make_shared<PlainTextLineReaderCtx>(
685
2.30k
                _line_delimiter, _line_delimiter_length, _keep_cr);
686
2.30k
        _fields_splitter = std::make_unique<PlainCsvTextFieldSplitter>(
687
2.30k
                _trim_tailing_spaces, false, _value_separator, _value_separator_length, -1);
688
689
2.30k
    } else {
690
        // in load task, the _file_slot_descs is empty vector, so we need to set col_sep_num to 0
691
97
        size_t col_sep_num = _file_slot_descs.size() > 1 ? _file_slot_descs.size() - 1 : 0;
692
97
        _enclose_reader_ctx = std::make_shared<EncloseCsvLineReaderCtx>(
693
97
                _line_delimiter, _line_delimiter_length, _value_separator, _value_separator_length,
694
97
                col_sep_num, _enclose, _escape, _keep_cr);
695
97
        text_line_reader_ctx = _enclose_reader_ctx;
696
697
97
        _fields_splitter = std::make_unique<EncloseCsvTextFieldSplitter>(
698
97
                _trim_tailing_spaces, true, _enclose_reader_ctx, _value_separator_length, _enclose);
699
97
    }
700
2.40k
    switch (_file_format_type) {
701
2.32k
    case TFileFormatType::FORMAT_CSV_PLAIN:
702
2.32k
        [[fallthrough]];
703
2.32k
    case TFileFormatType::FORMAT_CSV_GZ:
704
2.32k
        [[fallthrough]];
705
2.32k
    case TFileFormatType::FORMAT_CSV_BZ2:
706
2.32k
        [[fallthrough]];
707
2.32k
    case TFileFormatType::FORMAT_CSV_LZ4FRAME:
708
2.32k
        [[fallthrough]];
709
2.32k
    case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
710
2.32k
        [[fallthrough]];
711
2.32k
    case TFileFormatType::FORMAT_CSV_LZOP:
712
2.32k
        [[fallthrough]];
713
2.32k
    case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
714
2.32k
        [[fallthrough]];
715
2.32k
    case TFileFormatType::FORMAT_CSV_DEFLATE:
716
2.32k
        _line_reader =
717
2.32k
                NewPlainTextLineReader::create_unique(_profile, _file_reader, _decompressor.get(),
718
2.32k
                                                      text_line_reader_ctx, _size, _start_offset);
719
720
2.32k
        break;
721
77
    case TFileFormatType::FORMAT_PROTO:
722
77
        _fields_splitter = std::make_unique<CsvProtoFieldSplitter>();
723
77
        _line_reader = NewPlainBinaryLineReader::create_unique(_file_reader);
724
77
        break;
725
0
    default:
726
0
        return Status::InternalError<false>(
727
0
                "Unknown format type, cannot init line reader in csv reader, type={}",
728
0
                _file_format_type);
729
2.40k
    }
730
2.40k
    return Status::OK();
731
2.40k
}
732
733
300
Status CsvReader::_deserialize_one_cell(DataTypeSerDeSPtr serde, IColumn& column, Slice& slice) {
734
300
    return serde->deserialize_one_cell_from_csv(column, slice, _options);
735
300
}
736
737
Status CsvReader::_fill_dest_columns(const Slice& line, std::vector<MutableColumnPtr>& columns,
738
11.9M
                                     size_t* rows) {
739
11.9M
    bool is_success = false;
740
741
11.9M
    RETURN_IF_ERROR(_line_split_to_values(line, &is_success));
742
11.9M
    if (UNLIKELY(!is_success)) {
743
        // If not success, which means we met an invalid row, filter this row and return.
744
539
        return Status::OK();
745
539
    }
746
747
199M
    for (int i = 0; i < _file_slot_descs.size(); ++i) {
748
187M
        int col_idx = _col_idxs[i];
749
        // col idx is out of range, fill with null format
750
187M
        auto value = col_idx < _split_values.size()
751
188M
                             ? _split_values[col_idx]
752
18.4E
                             : Slice(_options.null_format, _options.null_len);
753
754
187M
        IColumn* col_ptr = columns[i].get();
755
187M
        if (!_is_load) {
756
20.6M
            col_ptr = columns[_file_slot_idx_map[i]].get();
757
20.6M
        }
758
759
195M
        if (_use_nullable_string_opt[i]) {
760
            // For load task, we always read "string" from file.
761
            // So serdes[i] here must be DataTypeNullableSerDe, and DataTypeNullableSerDe -> nested_serde must be DataTypeStringSerDe.
762
            // So we use deserialize_nullable_string and stringSerDe to reduce virtual function calls.
763
195M
            RETURN_IF_ERROR(_deserialize_nullable_string(*col_ptr, value));
764
18.4E
        } else {
765
18.4E
            RETURN_IF_ERROR(_deserialize_one_cell(_serdes[i], *col_ptr, value));
766
18.4E
        }
767
187M
    }
768
11.9M
    ++(*rows);
769
770
11.9M
    return Status::OK();
771
11.9M
}
772
773
0
Status CsvReader::_fill_empty_line(std::vector<MutableColumnPtr>& columns, size_t* rows) {
774
0
    for (int i = 0; i < _file_slot_descs.size(); ++i) {
775
0
        IColumn* col_ptr = columns[i].get();
776
0
        if (!_is_load) {
777
0
            col_ptr = columns[_file_slot_idx_map[i]].get();
778
0
        }
779
0
        auto& null_column = assert_cast<ColumnNullable&>(*col_ptr);
780
0
        null_column.insert_data(nullptr, 0);
781
0
    }
782
0
    ++(*rows);
783
0
    return Status::OK();
784
0
}
785
786
11.9M
Status CsvReader::_validate_line(const Slice& line, bool* success) {
787
11.9M
    if (!_is_proto_format && !validate_utf8(_params, line.data, line.size)) {
788
128
        if (!_is_load) {
789
0
            return Status::InternalError<false>("Only support csv data in utf8 codec");
790
128
        } else {
791
128
            _counter->num_rows_filtered++;
792
128
            *success = false;
793
128
            RETURN_IF_ERROR(_state->append_error_msg_to_file(
794
128
                    [&]() -> std::string { return std::string(line.data, line.size); },
795
128
                    [&]() -> std::string {
796
128
                        return "Invalid file encoding: all CSV files must be UTF-8 encoded";
797
128
                    }));
798
128
            return Status::OK();
799
128
        }
800
128
    }
801
11.9M
    *success = true;
802
11.9M
    return Status::OK();
803
11.9M
}
804
805
11.9M
Status CsvReader::_line_split_to_values(const Slice& line, bool* success) {
806
11.9M
    _split_line(line);
807
808
11.9M
    if (_is_load) {
809
        // Only check for load task. For query task, the non exist column will be filled "null".
810
        // if actual column number in csv file is not equal to _file_slot_descs.size()
811
        // then filter this line.
812
10.6M
        bool ignore_col = false;
813
10.6M
        ignore_col = _params.__isset.file_attributes &&
814
10.6M
                     _params.file_attributes.__isset.ignore_csv_redundant_col &&
815
10.6M
                     _params.file_attributes.ignore_csv_redundant_col;
816
817
10.6M
        if ((!ignore_col && _split_values.size() != _file_slot_descs.size()) ||
818
10.6M
            (ignore_col && _split_values.size() < _file_slot_descs.size())) {
819
544
            _counter->num_rows_filtered++;
820
544
            *success = false;
821
544
            RETURN_IF_ERROR(_state->append_error_msg_to_file(
822
544
                    [&]() -> std::string { return std::string(line.data, line.size); },
823
544
                    [&]() -> std::string {
824
544
                        fmt::memory_buffer error_msg;
825
544
                        fmt::format_to(error_msg,
826
544
                                       "Column count mismatch: expected {}, but found {}",
827
544
                                       _file_slot_descs.size(), _split_values.size());
828
544
                        std::string escaped_separator =
829
544
                                std::regex_replace(_value_separator, std::regex("\t"), "\\t");
830
544
                        std::string escaped_delimiter =
831
544
                                std::regex_replace(_line_delimiter, std::regex("\n"), "\\n");
832
544
                        fmt::format_to(error_msg, " (sep:{} delim:{}", escaped_separator,
833
544
                                       escaped_delimiter);
834
544
                        if (_enclose != 0) {
835
544
                            fmt::format_to(error_msg, " encl:{}", _enclose);
836
544
                        }
837
544
                        if (_escape != 0) {
838
544
                            fmt::format_to(error_msg, " esc:{}", _escape);
839
544
                        }
840
544
                        fmt::format_to(error_msg, ")");
841
544
                        return fmt::to_string(error_msg);
842
544
                    }));
843
539
            return Status::OK();
844
544
        }
845
10.6M
    }
846
847
11.9M
    *success = true;
848
11.9M
    return Status::OK();
849
11.9M
}
850
851
11.9M
void CsvReader::_split_line(const Slice& line) {
852
11.9M
    _split_values.clear();
853
11.9M
    _fields_splitter->split_line(line, &_split_values);
854
11.9M
}
855
856
350
Status CsvReader::_parse_col_nums(size_t* col_nums) {
857
350
    const uint8_t* ptr = nullptr;
858
350
    size_t size = 0;
859
350
    RETURN_IF_ERROR(_line_reader->read_line(&ptr, &size, &_line_reader_eof, _io_ctx));
860
350
    if (size == 0) {
861
0
        return Status::InternalError<false>(
862
0
                "The first line is empty, can not parse column numbers");
863
0
    }
864
350
    if (!validate_utf8(_params, reinterpret_cast<const char*>(ptr), size)) {
865
1
        return Status::InternalError<false>("Only support csv data in utf8 codec");
866
1
    }
867
349
    ptr = _remove_bom(ptr, size);
868
349
    _split_line(Slice(ptr, size));
869
349
    *col_nums = _split_values.size();
870
349
    return Status::OK();
871
350
}
872
873
48
Status CsvReader::_parse_col_names(std::vector<std::string>* col_names) {
874
48
    const uint8_t* ptr = nullptr;
875
48
    size_t size = 0;
876
    // no use of _line_reader_eof
877
48
    RETURN_IF_ERROR(_line_reader->read_line(&ptr, &size, &_line_reader_eof, _io_ctx));
878
48
    if (size == 0) {
879
0
        return Status::InternalError<false>("The first line is empty, can not parse column names");
880
0
    }
881
48
    if (!validate_utf8(_params, reinterpret_cast<const char*>(ptr), size)) {
882
0
        return Status::InternalError<false>("Only support csv data in utf8 codec");
883
0
    }
884
48
    ptr = _remove_bom(ptr, size);
885
48
    _split_line(Slice(ptr, size));
886
187
    for (auto _split_value : _split_values) {
887
187
        col_names->emplace_back(_split_value.to_string());
888
187
    }
889
48
    return Status::OK();
890
48
}
891
892
// TODO(ftw): parse type
893
23
Status CsvReader::_parse_col_types(size_t col_nums, std::vector<DataTypePtr>* col_types) {
894
    // delete after.
895
113
    for (size_t i = 0; i < col_nums; ++i) {
896
90
        col_types->emplace_back(make_nullable(std::make_shared<DataTypeString>()));
897
90
    }
898
899
    // 1. check _line_reader_eof
900
    // 2. read line
901
    // 3. check utf8
902
    // 4. check size
903
    // 5. check _split_values.size must equal to col_nums.
904
    // 6. fill col_types
905
23
    return Status::OK();
906
23
}
907
908
5.50k
const uint8_t* CsvReader::_remove_bom(const uint8_t* ptr, size_t& size) {
909
5.50k
    if (size >= 3 && ptr[0] == 0xEF && ptr[1] == 0xBB && ptr[2] == 0xBF) {
910
7
        LOG(INFO) << "remove bom";
911
7
        constexpr size_t bom_size = 3;
912
7
        size -= bom_size;
913
        // In enclose mode, column_sep_positions were computed on the original line
914
        // (including BOM). After shifting the pointer, we must adjust those positions
915
        // so they remain correct relative to the new start.
916
7
        if (_enclose_reader_ctx) {
917
1
            _enclose_reader_ctx->adjust_column_sep_positions(bom_size);
918
1
        }
919
7
        return ptr + bom_size;
920
7
    }
921
5.49k
    return ptr;
922
5.50k
}
923
924
2.00k
Status CsvReader::close() {
925
2.00k
    if (_line_reader) {
926
2.00k
        _line_reader->close();
927
2.00k
    }
928
929
2.00k
    if (_file_reader) {
930
2.00k
        RETURN_IF_ERROR(_file_reader->close());
931
2.00k
    }
932
933
2.00k
    return Status::OK();
934
2.00k
}
935
936
} // namespace doris