Autonomy Software C++ 24.5.1
Welcome to the Autonomy Software repository of the Mars Rover Design Team (MRDT) at Missouri University of Science and Technology (Missouri S&T)! API reference contains the source code and other resources for the development of the autonomy software for our Mars rover. The Autonomy Software project aims to compete in the University Rover Challenge (URC) by demonstrating advanced autonomous capabilities and robust navigation algorithms.
Loading...
Searching...
No Matches
duckdb::StringValueScanner Class Reference

Our dialect scanner basically goes over the CSV and actually parses the values to a DuckDB vector of string_t. More...

Inheritance diagram for duckdb::StringValueScanner:
Collaboration diagram for duckdb::StringValueScanner:

Public Member Functions

 StringValueScanner (idx_t scanner_idx, const shared_ptr< CSVBufferManager > &buffer_manager, const shared_ptr< CSVStateMachine > &state_machine, const shared_ptr< CSVErrorHandler > &error_handler, const shared_ptr< CSVFileScan > &csv_file_scan, bool sniffing=false, const CSVIterator &boundary={}, idx_t result_size=STANDARD_VECTOR_SIZE)
 StringValueScanner (const shared_ptr< CSVBufferManager > &buffer_manager, const shared_ptr< CSVStateMachine > &state_machine, const shared_ptr< CSVErrorHandler > &error_handler, idx_t result_size=STANDARD_VECTOR_SIZE, const CSVIterator &boundary={})
StringValueResult & ParseChunk () override
 Parses data into an output_chunk.
void Flush (DataChunk &insert_chunk)
 Flushes the result to the insert_chunk.
bool FinishedIterator () const
ValidatorLine GetValidationLine ()
 Gets validation line information.
Public Member Functions inherited from duckdb::BaseScanner
 BaseScanner (shared_ptr< CSVBufferManager > buffer_manager, shared_ptr< CSVStateMachine > state_machine, shared_ptr< CSVErrorHandler > error_handler, bool sniffing=false, shared_ptr< CSVFileScan > csv_file_scan=nullptr, const CSVIterator &iterator={})
void Print () const
bool FinishedFile () const
 Returns true if the scanner is finished.
virtual ScannerResult & GetResult ()
 Returns the result from the last Parse call. Shouts at you if you call it wrong.
CSVIterator & GetIterator ()
void SetIterator (const CSVIterator &it)
idx_t GetBoundaryIndex () const
idx_t GetLinesRead () const
CSVPosition GetIteratorPosition () const
CSVStateMachine & GetStateMachine () const

Static Public Member Functions

static unique_ptr< StringValueScanner > GetCSVScanner (ClientContext &context, CSVReaderOptions &options, const MultiFileOptions &file_options)
 Function that creates and returns a non-boundary CSV Scanner, can be used for internal csv reading.
static string_t RemoveEscape (const char *str_ptr, idx_t end, char escape, char quote, bool strict_mode, Vector &vector)
 Creates a new string with all escaped values removed.
static bool CanDirectlyCast (const LogicalType &type, bool icu_loaded)
 If we can directly cast the type when consuming the CSV file, or we have to do it later.
Static Public Member Functions inherited from duckdb::BaseScanner
static string RemoveSeparator (const char *value_ptr, const idx_t size, char thousands_separator)
 Removes thousands separator.
static CSVIterator SkipCSVRows (shared_ptr< CSVBufferManager > buffer_manager, const shared_ptr< CSVStateMachine > &state_machine, idx_t rows_to_skip)
static bool ContainsZeroByte (uint64_t v)

Public Attributes

const idx_t scanner_idx
shared_ptr< CSVBufferUsage > buffer_tracker
 Variable that manages buffer tracking.
Public Attributes inherited from duckdb::BaseScanner
shared_ptr< CSVFileScan > csv_file_scan
bool sniffing = false
 If this scanner is being used for sniffing.
shared_ptr< CSVErrorHandler > error_handler
 The guy that handles errors.
shared_ptr< CSVStateMachine > state_machine
 Shared pointer to the state machine, this is used across multiple scanners.
CSVStates states
 States.
bool ever_quoted = false
 If the scanner ever entered a quoted state.
bool ever_escaped = false
 If the scanner ever entered an escaped state.
bool used_unstrictness = false
 If the scanner ever used advantage of the non-strict mode.
shared_ptr< CSVBufferManager > buffer_manager
 Shared pointer to the buffer_manager, this is shared across multiple scanners.

Static Public Attributes

static constexpr idx_t LINE_FINDER_ID = NumericLimits<idx_t>::Maximum()
 We use the max of idx_t to signify this is a line finder scanner.

Private Member Functions

void Initialize () override
void FinalizeChunkProcess () override
 Finalizes the process of the chunk.
void ProcessOverBufferValue ()
 Function used to process values that go over the first buffer, extra allocation might be necessary.
void ProcessExtraRow ()
bool MoveToNextBuffer ()
 Function used to move from one buffer to the other, if necessary.
void SetStart ()
bool SkipUntilState (CSVState initial_state, CSVState until_state, CSVIterator &current_iterator, bool &quoted) const
 From a given initial state, it skips until we reach the until_state.
bool IsRowValid (CSVIterator &current_iterator) const
 If the current row we found is valid.
ValidRowInfo TryRow (CSVState state, idx_t start_pos, idx_t end_pos) const
bool FirstValueEndsOnQuote (CSVIterator iterator) const

Private Attributes

StringValueResult result
vector< LogicalType > types
idx_t start_pos
 True Position where this scanner started scanning(i.e., after figuring out where the first line starts).
shared_ptr< CSVBufferHandle > previous_buffer_handle
 Pointer to the previous buffer handle, necessary for over-buffer values.
shared_ptr< CSVStateMachine > state_machine_strict
 Strict state machine is basically a state machine with rfc 4180 set to true, used to figure out a new line.

Additional Inherited Members

Protected Member Functions inherited from duckdb::BaseScanner
template<class T>
void Process (T &result)
 Process one chunk.
template<class T>
void ParseChunkInternal (T &result)
 Internal function for parse chunk.
Protected Attributes inherited from duckdb::BaseScanner
CSVIterator iterator
 Boundaries of this scanner.
shared_ptr< CSVBufferHandle > cur_buffer_handle
char * buffer_handle_ptr = nullptr
 Hold the current buffer ptr.
bool initialized = false
 If this scanner has been initialized.
idx_t lines_read = 0
 How many lines were read by this scanner.
idx_t bytes_read = 0

Detailed Description

Our dialect scanner basically goes over the CSV and actually parses the values to a DuckDB vector of string_t.

Constructor & Destructor Documentation

◆ StringValueScanner() [1/2]

duckdb::StringValueScanner::StringValueScanner ( idx_t scanner_idx,
const shared_ptr< CSVBufferManager > & buffer_manager,
const shared_ptr< CSVStateMachine > & state_machine,
const shared_ptr< CSVErrorHandler > & error_handler,
const shared_ptr< CSVFileScan > & csv_file_scan,
bool sniffing = false,
const CSVIterator & boundary = {},
idx_t result_size = STANDARD_VECTOR_SIZE )
170281 : BaseScanner(buffer_manager, state_machine, error_handler, sniffing, csv_file_scan, boundary),
170282 scanner_idx(scanner_idx_p),
170283 result(states, *state_machine, cur_buffer_handle, BufferAllocator::Get(buffer_manager->context), result_size,
170284 iterator.pos.buffer_pos, *error_handler, iterator,
170285 buffer_manager->context.client_data->debug_set_max_line_length, csv_file_scan, lines_read, sniffing,
170286 buffer_manager->GetFilePath(), scanner_idx_p, used_unstrictness),
170287 start_pos(0) {
170288 if (scanner_idx == 0 && csv_file_scan) {
170289 lines_read += csv_file_scan->skipped_rows;
170290 }
170291 iterator.buffer_size = state_machine->options.buffer_size_option.GetValue();
170292 result.try_row = scanner_idx == LINE_FINDER_ID;
170293}
shared_ptr< CSVStateMachine > state_machine
Shared pointer to the state machine, this is used across multiple scanners.
Definition duckdb.cpp:167295
bool sniffing
If this scanner is being used for sniffing.
Definition duckdb.cpp:167290
CSVIterator iterator
Boundaries of this scanner.
Definition duckdb.cpp:167323
CSVStates states
States.
Definition duckdb.cpp:167298
shared_ptr< CSVBufferManager > buffer_manager
Shared pointer to the buffer_manager, this is shared across multiple scanners.
Definition duckdb.cpp:167310
shared_ptr< CSVErrorHandler > error_handler
The guy that handles errors.
Definition duckdb.cpp:167292
shared_ptr< CSVBufferHandle > cur_buffer_handle
Definition duckdb.cpp:167327
bool used_unstrictness
If the scanner ever used advantage of the non-strict mode.
Definition duckdb.cpp:167307
idx_t lines_read
How many lines were read by this scanner.
Definition duckdb.cpp:167335
static constexpr idx_t LINE_FINDER_ID
We use the max of idx_t to signify this is a line finder scanner.
Definition duckdb.cpp:167938
idx_t start_pos
True Position where this scanner started scanning(i.e., after figuring out where the first line start...
Definition duckdb.cpp:167969

◆ StringValueScanner() [2/2]

duckdb::StringValueScanner::StringValueScanner ( const shared_ptr< CSVBufferManager > & buffer_manager,
const shared_ptr< CSVStateMachine > & state_machine,
const shared_ptr< CSVErrorHandler > & error_handler,
idx_t result_size = STANDARD_VECTOR_SIZE,
const CSVIterator & boundary = {} )
170299 : BaseScanner(buffer_manager, state_machine, error_handler, false, nullptr, boundary), scanner_idx(0),
170300 result(states, *state_machine, cur_buffer_handle, Allocator::DefaultAllocator(), result_size,
170301 iterator.pos.buffer_pos, *error_handler, iterator,
170302 buffer_manager->context.client_data->debug_set_max_line_length, csv_file_scan, lines_read, sniffing,
170303 buffer_manager->GetFilePath(), 0, used_unstrictness),
170304 start_pos(0) {
170305 if (scanner_idx == 0 && csv_file_scan) {
170306 lines_read += csv_file_scan->skipped_rows;
170307 }
170308 iterator.buffer_size = state_machine->options.buffer_size_option.GetValue();
170309}

Member Function Documentation

◆ ParseChunk()

StringValueResult & duckdb::StringValueScanner::ParseChunk ( )
overridevirtual

Parses data into an output_chunk.

Reimplemented from duckdb::BaseScanner.

170334 {
170335 result.Reset();
170336 ParseChunkInternal(result);
170337 return result;
170338}
void ParseChunkInternal(T &result)
Internal function for parse chunk.
Definition duckdb.cpp:167542
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Flush()

void duckdb::StringValueScanner::Flush ( DataChunk & insert_chunk)

Flushes the result to the insert_chunk.

170340 {
170341 bool continue_processing;
170342 do {
170343 continue_processing = false;
170344 auto &process_result = ParseChunk();
170345 // First Get Parsed Chunk
170346 auto &parse_chunk = process_result.ToChunk();
170347 insert_chunk.Reset();
170348 // We have to check if we got to error
170349 error_handler->ErrorIfNeeded();
170350 if (parse_chunk.size() == 0) {
170351 return;
170352 }
170353 // convert the columns in the parsed chunk to the types of the table
170354 insert_chunk.SetCardinality(parse_chunk);
170355
170356 // We keep track of the borked lines, in case we are ignoring errors
170357 D_ASSERT(csv_file_scan);
170358
170359 auto &names = csv_file_scan->GetNames();
170360 // Now Do the cast-aroo
170361 for (idx_t i = 0; i < csv_file_scan->column_ids.size(); i++) {
170362 idx_t result_idx = i;
170363 if (!csv_file_scan->projection_ids.empty()) {
170364 result_idx = csv_file_scan->projection_ids[i].second;
170365 }
170366 if (i >= parse_chunk.ColumnCount()) {
170367 throw InvalidInputException("Mismatch between the schema of different files");
170368 }
170369 auto &parse_vector = parse_chunk.data[i];
170370 auto &result_vector = insert_chunk.data[result_idx];
170371 auto &type = result_vector.GetType();
170372 auto &parse_type = parse_vector.GetType();
170373 if (!type.IsJSONType() && (type == LogicalType::VARCHAR ||
170374 (type != LogicalType::VARCHAR && parse_type != LogicalType::VARCHAR))) {
170375 // reinterpret rather than reference
170376 result_vector.Reinterpret(parse_vector);
170377 } else {
170378 string error_message;
170379 idx_t line_error = 0;
170380 if (VectorOperations::TryCast(buffer_manager->context, parse_vector, result_vector, parse_chunk.size(),
170381 &error_message, false, true)) {
170382 continue;
170383 }
170384 // An error happened, to propagate it we need to figure out the exact line where the casting failed.
170385 UnifiedVectorFormat inserted_column_data;
170386 result_vector.ToUnifiedFormat(parse_chunk.size(), inserted_column_data);
170387 UnifiedVectorFormat parse_column_data;
170388 parse_vector.ToUnifiedFormat(parse_chunk.size(), parse_column_data);
170389
170390 for (; line_error < parse_chunk.size(); line_error++) {
170391 if (!inserted_column_data.validity.RowIsValid(line_error) &&
170392 parse_column_data.validity.RowIsValid(line_error)) {
170393 break;
170394 }
170395 }
170396 {
170397 if (state_machine->options.ignore_errors.GetValue()) {
170398 vector<Value> row;
170399 for (idx_t col = 0; col < parse_chunk.ColumnCount(); col++) {
170400 row.push_back(parse_chunk.GetValue(col, line_error));
170401 }
170402 }
170403 if (!state_machine->options.IgnoreErrors()) {
170404 LinesPerBoundary lines_per_batch(iterator.GetBoundaryIdx(),
170405 lines_read - parse_chunk.size() + line_error);
170406 bool first_nl = false;
170407 auto borked_line = result.line_positions_per_row[line_error].ReconstructCurrentLine(
170408 first_nl, result.buffer_handles, result.PrintErrorLine());
170409 std::ostringstream error;
170410 error << "Could not convert string \"" << parse_vector.GetValue(line_error) << "\" to \'"
170411 << type.ToString() << "\'";
170412 string error_msg = error.str();
170413 FullLinePosition::SanitizeError(error_msg);
170414 idx_t row_byte_pos = 0;
170415 if (!(result.line_positions_per_row[line_error].begin ==
170416 result.line_positions_per_row[line_error].end)) {
170417 row_byte_pos = result.line_positions_per_row[line_error].begin.GetGlobalPosition(
170418 result.result_size, first_nl);
170419 }
170420 auto csv_error = CSVError::CastError(
170421 state_machine->options, names[i], error_msg, i, borked_line, lines_per_batch, row_byte_pos,
170422 optional_idx::Invalid(), result_vector.GetType().id(), result.path);
170423 error_handler->Error(csv_error);
170424 }
170425 }
170426 result.borked_rows.insert(line_error++);
170427 D_ASSERT(state_machine->options.ignore_errors.GetValue());
170428 // We are ignoring errors. We must continue but ignoring borked-rows
170429 for (; line_error < parse_chunk.size(); line_error++) {
170430 if (!inserted_column_data.validity.RowIsValid(line_error) &&
170431 parse_column_data.validity.RowIsValid(line_error)) {
170432 result.borked_rows.insert(line_error);
170433 vector<Value> row;
170434 for (idx_t col = 0; col < parse_chunk.ColumnCount(); col++) {
170435 row.push_back(parse_chunk.GetValue(col, line_error));
170436 }
170437 if (!state_machine->options.IgnoreErrors()) {
170438 LinesPerBoundary lines_per_batch(iterator.GetBoundaryIdx(),
170439 lines_read - parse_chunk.size() + line_error);
170440 bool first_nl = false;
170441 auto borked_line = result.line_positions_per_row[line_error].ReconstructCurrentLine(
170442 first_nl, result.buffer_handles, result.PrintErrorLine());
170443 std::ostringstream error;
170444 // Casting Error Message
170445 error << "Could not convert string \"" << parse_vector.GetValue(line_error) << "\" to \'"
170446 << LogicalTypeIdToString(type.id()) << "\'";
170447 string error_msg = error.str();
170448 FullLinePosition::SanitizeError(error_msg);
170449 auto csv_error = CSVError::CastError(
170450 state_machine->options, names[i], error_msg, i, borked_line, lines_per_batch,
170451 result.line_positions_per_row[line_error].begin.GetGlobalPosition(result.result_size,
170452 first_nl),
170453 optional_idx::Invalid(), result_vector.GetType().id(), result.path);
170454 error_handler->Error(csv_error);
170455 }
170456 }
170457 }
170458 }
170459 }
170460 if (!result.borked_rows.empty()) {
170461 // We must remove the borked lines from our chunk
170462 SelectionVector successful_rows(parse_chunk.size());
170463 idx_t sel_idx = 0;
170464 for (idx_t row_idx = 0; row_idx < parse_chunk.size(); row_idx++) {
170465 if (result.borked_rows.find(row_idx) == result.borked_rows.end()) {
170466 successful_rows.set_index(sel_idx++, row_idx);
170467 }
170468 }
170469 // Now we slice the result
170470 insert_chunk.Slice(successful_rows, sel_idx);
170471 result.borked_rows.clear();
170472 }
170473 if (insert_chunk.size() == 0 && cur_buffer_handle) {
170474 idx_t to_pos;
170475 if (iterator.IsBoundarySet()) {
170476 to_pos = iterator.GetEndPos();
170477 if (to_pos > cur_buffer_handle->actual_size) {
170478 to_pos = cur_buffer_handle->actual_size;
170479 }
170480 } else {
170481 to_pos = cur_buffer_handle->actual_size;
170482 }
170483 if (iterator.pos.buffer_pos < to_pos) {
170484 // If a chunk is complete with errors, we might get to this situation where we must proceed with the
170485 // scanning
170486 continue_processing = true;
170487 }
170488 }
170489 } while (continue_processing);
170490}
static CSVError CastError(const CSVReaderOptions &options, const string &column_name, string &cast_error, idx_t column_idx, string &csv_row, LinesPerBoundary error_info, idx_t row_byte_position, optional_idx byte_position, LogicalTypeId type, const String &current_path)
Produces error messages for casting errors.
Definition duckdb.cpp:175857
DUCKDB_API void Reset()
Definition duckdb.cpp:116840
vector< Vector > data
The vectors owned by the DataChunk.
Definition duckdb.hpp:11445
StringValueResult & ParseChunk() override
Parses data into an output_chunk.
Definition duckdb.cpp:170334
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237
static DUCKDB_API bool TryCast(CastFunctionSet &set, GetCastFunctionInput &input, Vector &source, Vector &result, idx_t count, string *error_message, bool strict=false, const bool nullify_parent=false)
Definition duckdb.cpp:143445
Here is the call graph for this function:

◆ GetCSVScanner()

unique_ptr< StringValueScanner > duckdb::StringValueScanner::GetCSVScanner ( ClientContext & context,
CSVReaderOptions & options,
const MultiFileOptions & file_options )
static

Function that creates and returns a non-boundary CSV Scanner, can be used for internal csv reading.

170312 {
170313 auto state_machine = make_shared_ptr<CSVStateMachine>(options, options.dialect_options.state_machine_options,
170314 CSVStateMachineCache::Get(context));
170315
170316 state_machine->dialect_options.num_cols = options.dialect_options.num_cols;
170317 state_machine->dialect_options.header = options.dialect_options.header;
170318 auto buffer_manager = make_shared_ptr<CSVBufferManager>(context, options, options.file_path, 0);
170319 idx_t rows_to_skip = state_machine->options.GetSkipRows() + state_machine->options.GetHeader();
170320 rows_to_skip = std::max(rows_to_skip, state_machine->dialect_options.rows_until_header +
170321 state_machine->dialect_options.header.GetValue());
170322 auto it = BaseScanner::SkipCSVRows(buffer_manager, state_machine, rows_to_skip);
170323 auto scanner = make_uniq<StringValueScanner>(buffer_manager, state_machine, make_shared_ptr<CSVErrorHandler>(),
170324 STANDARD_VECTOR_SIZE, it);
170325 scanner->csv_file_scan = make_shared_ptr<CSVFileScan>(context, options.file_path, options, file_options);
170326 scanner->csv_file_scan->InitializeProjection();
170327 return scanner;
170328}
static CSVIterator SkipCSVRows(shared_ptr< CSVBufferManager > buffer_manager, const shared_ptr< CSVStateMachine > &state_machine, idx_t rows_to_skip)
Definition duckdb.cpp:168396
static CSVStateMachineCache & Get(ClientContext &context)
Definition duckdb.cpp:174537
Here is the call graph for this function:

◆ FinishedIterator()

bool duckdb::StringValueScanner::FinishedIterator ( ) const
170330 {
170331 return iterator.done;
170332}

◆ RemoveEscape()

string_t duckdb::StringValueScanner::RemoveEscape ( const char * str_ptr,
idx_t end,
char escape,
char quote,
bool strict_mode,
Vector & vector )
static

Creates a new string with all escaped values removed.

170610 {
170611 // Figure out the exact size
170612 idx_t str_pos = 0;
170613 bool just_escaped = false;
170614 for (idx_t cur_pos = 0; cur_pos < end; cur_pos++) {
170615 if (str_ptr[cur_pos] == escape && !just_escaped) {
170616 just_escaped = true;
170617 } else if (str_ptr[cur_pos] == quote) {
170618 if (just_escaped || !strict_mode) {
170619 str_pos++;
170620 }
170621 just_escaped = false;
170622 } else {
170623 just_escaped = false;
170624 str_pos++;
170625 }
170626 }
170627
170628 auto removed_escapes = StringVector::EmptyString(vector, str_pos);
170629 auto removed_escapes_ptr = removed_escapes.GetDataWriteable();
170630 // Allocate string and copy it
170631 str_pos = 0;
170632 just_escaped = false;
170633 for (idx_t cur_pos = 0; cur_pos < end; cur_pos++) {
170634 const char c = str_ptr[cur_pos];
170635 if (c == escape && !just_escaped) {
170636 just_escaped = true;
170637 } else if (str_ptr[cur_pos] == quote) {
170638 if (just_escaped || !strict_mode) {
170639 removed_escapes_ptr[str_pos++] = c;
170640 }
170641 just_escaped = false;
170642 } else {
170643 just_escaped = false;
170644 removed_escapes_ptr[str_pos++] = c;
170645 }
170646 }
170647 removed_escapes.Finalize();
170648 return removed_escapes;
170649}
static DUCKDB_API string_t EmptyString(Vector &vector, idx_t len)
Definition duckdb.cpp:137942
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CanDirectlyCast()

bool duckdb::StringValueScanner::CanDirectlyCast ( const LogicalType & type,
bool icu_loaded )
static

If we can directly cast the type when consuming the CSV file, or we have to do it later.

171040 {
171041 switch (type.id()) {
171042 case LogicalTypeId::TINYINT:
171043 case LogicalTypeId::SMALLINT:
171044 case LogicalTypeId::INTEGER:
171045 case LogicalTypeId::BIGINT:
171046 case LogicalTypeId::UTINYINT:
171047 case LogicalTypeId::USMALLINT:
171048 case LogicalTypeId::UINTEGER:
171049 case LogicalTypeId::UBIGINT:
171050 case LogicalTypeId::DOUBLE:
171051 case LogicalTypeId::FLOAT:
171052 case LogicalTypeId::DATE:
171053 case LogicalTypeId::TIMESTAMP:
171054 case LogicalTypeId::TIME:
171055 case LogicalTypeId::DECIMAL:
171056 case LogicalType::BOOLEAN:
171057 return true;
171058 case LogicalType::TIMESTAMP_TZ:
171059 // We only try to do direct cast of timestamp tz if the ICU extension is not loaded, otherwise, it needs to go
171060 // through string -> timestamp_tz casting
171061 return !icu_loaded;
171062 case LogicalType::VARCHAR:
171063 return !type.IsJSONType();
171064 default:
171065 return false;
171066 }
171067}

◆ GetValidationLine()

ValidatorLine duckdb::StringValueScanner::GetValidationLine ( )

Gets validation line information.

171290 {
171291 return {start_pos, result.iterator.GetGlobalCurrentPos()};
171292}

◆ Initialize()

void duckdb::StringValueScanner::Initialize ( )
overrideprivatevirtual

Internal Functions used to perform the parsing Initializes the scanner

Reimplemented from duckdb::BaseScanner.

170492 {
170493 states.Initialize();
170494
170495 if (result.result_size != 1 && !(sniffing && state_machine->options.null_padding &&
170496 !state_machine->options.dialect_options.skip_rows.IsSetByUser())) {
170497 SetStart();
170498 } else {
170499 start_pos = iterator.GetGlobalCurrentPos();
170500 }
170501
170502 result.last_position = {iterator.pos.buffer_idx, iterator.pos.buffer_pos, cur_buffer_handle->actual_size};
170503 result.current_line_position.begin = result.last_position;
170504 result.current_line_position.end = result.current_line_position.begin;
170505}
void SetStart()
Definition duckdb.cpp:171114
Here is the call graph for this function:

◆ FinalizeChunkProcess()

void duckdb::StringValueScanner::FinalizeChunkProcess ( )
overrideprivatevirtual

Finalizes the process of the chunk.

Reimplemented from duckdb::BaseScanner.

171195 {
171196 if (static_cast<idx_t>(result.number_of_rows) >= result.result_size || iterator.done) {
171197 // We are done
171198 if (!sniffing) {
171199 if (csv_file_scan) {
171200 csv_file_scan->bytes_read += bytes_read;
171201 bytes_read = 0;
171202 }
171203 }
171204 return;
171205 }
171206 // If we are not done we have two options.
171207 // 1) If a boundary is set.
171208 if (iterator.IsBoundarySet()) {
171209 bool found_error = false;
171210 CSVErrorType type;
171211 if (!result.current_errors.HasErrorType(UNTERMINATED_QUOTES) &&
171212 !result.current_errors.HasErrorType(INVALID_STATE)) {
171213 iterator.done = true;
171214 } else {
171215 found_error = true;
171216 if (result.current_errors.HasErrorType(UNTERMINATED_QUOTES)) {
171217 type = UNTERMINATED_QUOTES;
171218 } else {
171219 type = INVALID_STATE;
171220 }
171221 }
171222 // We read until the next line or until we have nothing else to read.
171223 // Move to next buffer
171224 if (!cur_buffer_handle) {
171225 return;
171226 }
171227 bool moved = MoveToNextBuffer();
171228 if (cur_buffer_handle) {
171229 if (moved && result.cur_col_id > 0) {
171230 ProcessExtraRow();
171231 } else if (!moved) {
171232 ProcessExtraRow();
171233 }
171234 if (cur_buffer_handle->is_last_buffer && iterator.pos.buffer_pos >= cur_buffer_handle->actual_size) {
171236 }
171237 }
171238 if (result.current_errors.HasErrorType(UNTERMINATED_QUOTES)) {
171239 found_error = true;
171240 type = UNTERMINATED_QUOTES;
171241 } else if (result.current_errors.HasErrorType(INVALID_STATE)) {
171242 found_error = true;
171243 type = INVALID_STATE;
171244 }
171245 if (result.current_errors.HandleErrors(result)) {
171246 result.number_of_rows++;
171247 }
171248 if (states.IsQuotedCurrent() && !found_error) {
171249 if (state_machine->dialect_options.state_machine_options.strict_mode.GetValue()) {
171250 type = UNTERMINATED_QUOTES;
171251 // If we finish the execution of a buffer, and we end in a quoted state, it means we have unterminated
171252 // quotes
171253 result.current_errors.Insert(type, result.cur_col_id, result.chunk_col_id, result.last_position);
171254 if (result.current_errors.HandleErrors(result)) {
171255 result.number_of_rows++;
171256 }
171257 } else {
171258 used_unstrictness = true;
171259 }
171260 }
171261 if (!iterator.done) {
171262 if (iterator.pos.buffer_pos >= iterator.GetEndPos() || iterator.pos.buffer_idx > iterator.GetBufferIdx() ||
171263 FinishedFile()) {
171264 iterator.done = true;
171265 }
171266 }
171267 } else {
171268 // 2) If a boundary is not set
171269 // We read until the chunk is complete, or we have nothing else to read.
171270 while (!FinishedFile() && static_cast<idx_t>(result.number_of_rows) < result.result_size) {
171272 if (static_cast<idx_t>(result.number_of_rows) >= result.result_size) {
171273 return;
171274 }
171275 if (cur_buffer_handle) {
171276 Process(result);
171277 }
171278 }
171279 iterator.done = FinishedFile();
171280 if (result.null_padding && result.number_of_rows < STANDARD_VECTOR_SIZE && result.chunk_col_id > 0) {
171281 while (result.chunk_col_id < result.parse_chunk.ColumnCount()) {
171282 result.validity_mask[result.chunk_col_id++]->SetInvalid(static_cast<idx_t>(result.number_of_rows));
171283 result.cur_col_id++;
171284 }
171285 result.number_of_rows++;
171286 }
171287 }
171288}
void Process(T &result)
Process one chunk.
Definition duckdb.cpp:167343
bool FinishedFile() const
Returns true if the scanner is finished.
Definition duckdb.cpp:168380
bool MoveToNextBuffer()
Function used to move from one buffer to the other, if necessary.
Definition duckdb.cpp:170875
CSVErrorType
Definition duckdb.cpp:166184
@ UNTERMINATED_QUOTES
If the CSV has too many column.
Definition duckdb.cpp:166189
@ INVALID_STATE
If we have invalid UTF-8 encoded values.
Definition duckdb.cpp:166194
Here is the call graph for this function:

◆ ProcessOverBufferValue()

void duckdb::StringValueScanner::ProcessOverBufferValue ( )
private

Function used to process values that go over the first buffer, extra allocation might be necessary.

170651 {
170652 // Process first string
170653 if (result.last_position.buffer_pos != previous_buffer_handle->actual_size) {
170654 states.Initialize();
170655 }
170656
170657 string over_buffer_string;
170658 auto previous_buffer = previous_buffer_handle->Ptr();
170659 idx_t j = 0;
170660 result.quoted = false;
170661 for (idx_t i = result.last_position.buffer_pos; i < previous_buffer_handle->actual_size; i++) {
170662 state_machine->Transition(states, previous_buffer[i]);
170663 if (states.EmptyLine() || states.IsCurrentNewRow()) {
170664 continue;
170665 }
170666 if (states.NewRow() || states.NewValue()) {
170667 break;
170668 } else if (!result.comment) {
170669 over_buffer_string += previous_buffer[i];
170670 }
170671 if (states.IsQuoted()) {
170672 result.SetQuoted(result, j);
170673 }
170674 if (states.IsUnquoted()) {
170675 result.SetUnquoted(result);
170676 }
170677 if (states.IsEscaped() && result.state_machine.dialect_options.state_machine_options.escape != '\0') {
170678 result.escaped = true;
170679 }
170680 if (states.IsComment()) {
170681 result.SetComment(result, j);
170682 }
170683 if (states.IsInvalid()) {
170684 result.InvalidState(result);
170685 }
170686 j++;
170687 }
170688 if (over_buffer_string.empty() &&
170689 state_machine->dialect_options.state_machine_options.new_line == NewLineIdentifier::CARRY_ON) {
170690 if (!iterator.IsBoundarySet()) {
170691 if (buffer_handle_ptr[iterator.pos.buffer_pos] == '\n') {
170692 iterator.pos.buffer_pos++;
170693 }
170694 } else {
170695 while (iterator.pos.buffer_pos < cur_buffer_handle->actual_size &&
170696 (buffer_handle_ptr[iterator.pos.buffer_pos] == '\n' ||
170697 buffer_handle_ptr[iterator.pos.buffer_pos] == '\r')) {
170698 if (buffer_handle_ptr[iterator.pos.buffer_pos] == '\r') {
170699 if (result.last_position.buffer_pos <= previous_buffer_handle->actual_size) {
170700 // we add the value
170701 result.AddValue(result, previous_buffer_handle->actual_size);
170702 if (result.IsCommentSet(result)) {
170703 result.UnsetComment(result, iterator.pos.buffer_pos);
170704 } else {
170705 result.AddRow(result, previous_buffer_handle->actual_size);
170706 }
170707 state_machine->Transition(states, buffer_handle_ptr[iterator.pos.buffer_pos++]);
170708 while (iterator.pos.buffer_pos < cur_buffer_handle->actual_size &&
170709 (buffer_handle_ptr[iterator.pos.buffer_pos] == '\r' ||
170710 buffer_handle_ptr[iterator.pos.buffer_pos] == '\n')) {
170711 state_machine->Transition(states, buffer_handle_ptr[iterator.pos.buffer_pos++]);
170712 }
170713 return;
170714 }
170715 } else {
170716 if (iterator.pos.buffer_pos + 1 == cur_buffer_handle->actual_size) {
170717 return;
170718 }
170719 }
170720 state_machine->Transition(states, buffer_handle_ptr[iterator.pos.buffer_pos]);
170721 iterator.pos.buffer_pos++;
170722 }
170723 }
170724 }
170725 // second buffer
170726 for (; iterator.pos.buffer_pos < cur_buffer_handle->actual_size; iterator.pos.buffer_pos++) {
170727 state_machine->Transition(states, buffer_handle_ptr[iterator.pos.buffer_pos]);
170728 if (states.EmptyLine()) {
170729 if (state_machine->dialect_options.num_cols == 1) {
170730 break;
170731 }
170732 continue;
170733 }
170734 if (states.NewRow() || states.NewValue()) {
170735 break;
170736 } else if (!result.comment && !states.IsComment()) {
170737 over_buffer_string += buffer_handle_ptr[iterator.pos.buffer_pos];
170738 }
170739 if (states.IsQuoted()) {
170740 result.SetQuoted(result, j);
170741 }
170742 if (states.IsComment()) {
170743 result.SetComment(result, j);
170744 }
170745 if (states.IsEscaped() && result.state_machine.dialect_options.state_machine_options.escape != '\0') {
170746 result.escaped = true;
170747 }
170748 if (states.IsInvalid()) {
170749 result.InvalidState(result);
170750 }
170751 j++;
170752 }
170753 bool skip_value = false;
170754 if (result.projecting_columns) {
170755 if (!result.projected_columns[result.cur_col_id] && result.cur_col_id != result.number_of_columns) {
170756 result.cur_col_id++;
170757 skip_value = true;
170758 }
170759 }
170760 if (!skip_value) {
170761 string_t value;
170762 if (result.quoted && !result.comment) {
170763 idx_t length = over_buffer_string.size() - 1 - result.quoted_position;
170764 while (length > 0 && result.ignore_empty_values &&
170765 over_buffer_string.c_str()[result.quoted_position + length] == ' ') {
170766 length--;
170767 }
170768 value = string_t(over_buffer_string.c_str() + result.quoted_position, UnsafeNumericCast<uint32_t>(length));
170769 if (result.escaped) {
170770 if (!result.HandleTooManyColumnsError(over_buffer_string.c_str(), over_buffer_string.size())) {
170771 const auto str_ptr = over_buffer_string.c_str() + result.quoted_position;
170772 if (result.parse_chunk.data[result.chunk_col_id].GetType() != LogicalType::VARCHAR) {
170773 // We cant have escapes on non varchar columns
170774 result.current_errors.Insert(CAST_ERROR, result.cur_col_id, result.chunk_col_id,
170775 result.last_position);
170776 if (!result.state_machine.options.IgnoreErrors()) {
170777 // We have to write the cast error message.
170778 std::ostringstream error;
170779 // Casting Error Message
170780 error << "Could not convert string \""
170781 << std::string(over_buffer_string.c_str(), over_buffer_string.size()) << "\" to \'"
170782 << LogicalTypeIdToString(result.parse_types[result.chunk_col_id].type_id) << "\'";
170783 auto error_string = error.str();
170784 FullLinePosition::SanitizeError(error_string);
170785 result.current_errors.ModifyErrorMessageOfLastError(error_string);
170786 }
170787 return;
170788 }
170789 value =
170790 RemoveEscape(str_ptr, over_buffer_string.size() - 2,
170791 state_machine->dialect_options.state_machine_options.escape.GetValue(),
170792 state_machine->dialect_options.state_machine_options.quote.GetValue(),
170793 result.state_machine.dialect_options.state_machine_options.strict_mode.GetValue(),
170794 result.parse_chunk.data[result.chunk_col_id]);
170795 }
170796 }
170797 } else {
170798 value = string_t(over_buffer_string.c_str(), UnsafeNumericCast<uint32_t>(over_buffer_string.size()));
170799 if (result.escaped) {
170800 if (result.cur_col_id >= result.number_of_columns &&
170801 !result.state_machine.state_machine_options.strict_mode.GetValue()) {
170802 result.used_unstrictness = true;
170803 } else if (!result.HandleTooManyColumnsError(over_buffer_string.c_str(), over_buffer_string.size())) {
170804 if (result.parse_chunk.data[result.chunk_col_id].GetType() != LogicalType::VARCHAR) {
170805 // We cant have escapes on non varchar columns
170806 result.current_errors.Insert(CAST_ERROR, result.cur_col_id, result.chunk_col_id,
170807 result.last_position);
170808 if (!result.state_machine.options.IgnoreErrors()) {
170809 // We have to write the cast error message.
170810 std::ostringstream error;
170811 // Casting Error Message
170812 error << "Could not convert string \""
170813 << std::string(over_buffer_string.c_str(), over_buffer_string.size()) << "\" to \'"
170814 << LogicalTypeIdToString(result.parse_types[result.chunk_col_id].type_id) << "\'";
170815 auto error_string = error.str();
170816 FullLinePosition::SanitizeError(error_string);
170817 result.current_errors.ModifyErrorMessageOfLastError(error_string);
170818 }
170819 return;
170820 }
170821 value =
170822 RemoveEscape(over_buffer_string.c_str(), over_buffer_string.size(),
170823 state_machine->dialect_options.state_machine_options.escape.GetValue(),
170824 state_machine->dialect_options.state_machine_options.quote.GetValue(),
170825 result.state_machine.dialect_options.state_machine_options.strict_mode.GetValue(),
170826 result.parse_chunk.data[result.chunk_col_id]);
170827 }
170828 }
170829 }
170830 if (states.EmptyLine() && state_machine->dialect_options.num_cols == 1) {
170831 result.EmptyLine(result, iterator.pos.buffer_pos);
170832 } else if (!states.IsNotSet() && (!result.comment || !value.Empty())) {
170833 idx_t value_size = value.GetSize();
170834 if (states.IsDelimiter() &&
170835 !result.state_machine.dialect_options.state_machine_options.delimiter.GetValue().empty()) {
170836 idx_t extra_delimiter_bytes =
170837 result.state_machine.dialect_options.state_machine_options.delimiter.GetValue().size() - 1;
170838 if (extra_delimiter_bytes > value_size) {
170839 throw InternalException(
170840 "Value size is lower than the number of extra delimiter bytes in the ProcessOverBufferValue()");
170841 }
170842 value_size -= extra_delimiter_bytes;
170843 }
170844 result.AddValueToVector(value.GetData(), value_size, true);
170845 }
170846 } else {
170847 if (states.EmptyLine() && state_machine->dialect_options.num_cols == 1) {
170848 result.EmptyLine(result, iterator.pos.buffer_pos);
170849 }
170850 }
170851
170852 if (states.NewRow() && !states.IsNotSet()) {
170853 if (result.IsCommentSet(result)) {
170854 result.UnsetComment(result, iterator.pos.buffer_pos);
170855 } else {
170856 result.AddRowInternal();
170857 }
170858 lines_read++;
170859 }
170860
170861 if (iterator.pos.buffer_pos >= cur_buffer_handle->actual_size && cur_buffer_handle->is_last_buffer) {
170862 result.added_last_line = true;
170863 }
170864 if (states.IsCarriageReturn() &&
170865 state_machine->dialect_options.state_machine_options.new_line == NewLineIdentifier::CARRY_ON) {
170866 result.last_position = {iterator.pos.buffer_idx, ++iterator.pos.buffer_pos + 1, result.buffer_size};
170867 } else {
170868 result.last_position = {iterator.pos.buffer_idx, ++iterator.pos.buffer_pos, result.buffer_size};
170869 }
170870 // Be sure to reset the quoted and escaped variables
170871 result.quoted = false;
170872 result.escaped = false;
170873}
char * buffer_handle_ptr
Hold the current buffer ptr.
Definition duckdb.cpp:167330
shared_ptr< CSVBufferHandle > previous_buffer_handle
Pointer to the previous buffer handle, necessary for over-buffer values.
Definition duckdb.cpp:167971
static string_t RemoveEscape(const char *str_ptr, idx_t end, char escape, char quote, bool strict_mode, Vector &vector)
Creates a new string with all escaped values removed.
Definition duckdb.cpp:170609
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ProcessExtraRow()

void duckdb::StringValueScanner::ProcessExtraRow ( )
private
170507 {
170508 result.NullPaddingQuotedNewlineCheck();
170509 idx_t to_pos = cur_buffer_handle->actual_size;
170510 while (iterator.pos.buffer_pos < to_pos) {
170511 state_machine->Transition(states, buffer_handle_ptr[iterator.pos.buffer_pos]);
170512 switch (states.states[1]) {
170513 case CSVState::INVALID:
170514 result.InvalidState(result);
170515 iterator.pos.buffer_pos++;
170516 return;
170518 if (states.states[0] == CSVState::RECORD_SEPARATOR) {
170519 result.EmptyLine(result, iterator.pos.buffer_pos);
170520 iterator.pos.buffer_pos++;
170521 lines_read++;
170522 return;
170523 } else if (states.states[0] != CSVState::CARRIAGE_RETURN) {
170524 if (result.IsCommentSet(result)) {
170525 result.UnsetComment(result, iterator.pos.buffer_pos);
170526 } else {
170527 result.AddRow(result, iterator.pos.buffer_pos);
170528 }
170529 iterator.pos.buffer_pos++;
170530 lines_read++;
170531 return;
170532 }
170533 lines_read++;
170534 iterator.pos.buffer_pos++;
170535 break;
170537 if (states.states[0] != CSVState::RECORD_SEPARATOR) {
170538 if (result.IsCommentSet(result)) {
170539 result.UnsetComment(result, iterator.pos.buffer_pos);
170540 } else {
170541 result.AddRow(result, iterator.pos.buffer_pos);
170542 }
170543 iterator.pos.buffer_pos++;
170544 lines_read++;
170545 return;
170546 } else {
170547 result.EmptyLine(result, iterator.pos.buffer_pos);
170548 iterator.pos.buffer_pos++;
170549 lines_read++;
170550 return;
170551 }
170552 break;
170553 case CSVState::DELIMITER:
170554 result.AddValue(result, iterator.pos.buffer_pos);
170555 iterator.pos.buffer_pos++;
170556 break;
170557 case CSVState::QUOTED:
170558 if (states.states[0] == CSVState::UNQUOTED) {
170559 result.SetEscaped(result);
170560 }
170561 result.SetQuoted(result, iterator.pos.buffer_pos);
170562 iterator.pos.buffer_pos++;
170563 while (state_machine->transition_array
170564 .skip_quoted[static_cast<uint8_t>(buffer_handle_ptr[iterator.pos.buffer_pos])] &&
170565 iterator.pos.buffer_pos < to_pos - 1) {
170566 iterator.pos.buffer_pos++;
170567 }
170568 break;
170569 case CSVState::ESCAPE:
170572 result.SetEscaped(result);
170573 iterator.pos.buffer_pos++;
170574 break;
170575 case CSVState::STANDARD:
170576 iterator.pos.buffer_pos++;
170577 while (state_machine->transition_array
170578 .skip_standard[static_cast<uint8_t>(buffer_handle_ptr[iterator.pos.buffer_pos])] &&
170579 iterator.pos.buffer_pos < to_pos - 1) {
170580 iterator.pos.buffer_pos++;
170581 }
170582 break;
170583 case CSVState::UNQUOTED: {
170584 result.SetUnquoted(result);
170585 iterator.pos.buffer_pos++;
170586 break;
170587 }
170588 case CSVState::COMMENT:
170589 result.SetComment(result, iterator.pos.buffer_pos);
170590 iterator.pos.buffer_pos++;
170591 while (state_machine->transition_array
170592 .skip_comment[static_cast<uint8_t>(buffer_handle_ptr[iterator.pos.buffer_pos])] &&
170593 iterator.pos.buffer_pos < to_pos - 1) {
170594 iterator.pos.buffer_pos++;
170595 }
170596 break;
170598 result.quoted_new_line = true;
170599 result.NullPaddingQuotedNewlineCheck();
170600 iterator.pos.buffer_pos++;
170601 break;
170602 default:
170603 iterator.pos.buffer_pos++;
170604 break;
170605 }
170606 }
170607}
::uint8_t uint8_t
@ UNQUOTED_ESCAPE
State used for figuring out a new line.
Definition duckdb.cpp:59192
@ QUOTED
State after encountering a carriage return(i.e., \r).
Definition duckdb.cpp:59183
@ CARRIAGE_RETURN
State after encountering a record separator (i.e., ).
Definition duckdb.cpp:59182
@ DELIMITER
Regular unquoted field state.
Definition duckdb.cpp:59175
@ UNQUOTED
State when inside a quoted field.
Definition duckdb.cpp:59184
@ INVALID
State when encountering an escape character (e.g., ).
Definition duckdb.cpp:59186
@ QUOTED_NEW_LINE
If the state is not set, usually the first state before getting the first character.
Definition duckdb.cpp:59188
@ ESCAPE
State when leaving a quoted field.
Definition duckdb.cpp:59185
@ ESCAPED_RETURN
State when encountering an escape character (e.g., ) in an unquoted field.
Definition duckdb.cpp:59193
@ RECORD_SEPARATOR
-----------------------------------------------------------------------------------------------------...
Definition duckdb.cpp:59181
@ COMMENT
If we have empty spaces in the beginning and end of value.
Definition duckdb.cpp:59190

◆ MoveToNextBuffer()

bool duckdb::StringValueScanner::MoveToNextBuffer ( )
private

Function used to move from one buffer to the other, if necessary.

170875 {
170876 if (iterator.pos.buffer_pos >= cur_buffer_handle->actual_size) {
170878 cur_buffer_handle = buffer_manager->GetBuffer(++iterator.pos.buffer_idx);
170879 if (!cur_buffer_handle) {
170880 iterator.pos.buffer_idx--;
170881 buffer_handle_ptr = nullptr;
170882 // We do not care if it's a quoted new line on the last row of our file.
170883 result.quoted_new_line = false;
170884 // This means we reached the end of the file, we must add a last line if there is any to be added
170885 if (states.EmptyLine() || states.NewRow() || result.added_last_line || states.IsCurrentNewRow() ||
170886 states.IsNotSet()) {
170887 if (result.cur_col_id == result.number_of_columns && !result.IsStateCurrent(CSVState::INVALID)) {
170888 result.number_of_rows++;
170889 }
170890 result.cur_col_id = 0;
170891 result.chunk_col_id = 0;
170892 return false;
170893 } else if (states.NewValue()) {
170894 // we add the value
170895 result.AddValue(result, previous_buffer_handle->actual_size);
170896 // And an extra empty value to represent what comes after the delimiter
170897 if (result.IsCommentSet(result)) {
170898 result.UnsetComment(result, iterator.pos.buffer_pos);
170899 } else {
170900 result.AddRow(result, previous_buffer_handle->actual_size);
170901 }
170902 lines_read++;
170903 } else if (states.IsQuotedCurrent() &&
170904 state_machine->dialect_options.state_machine_options.strict_mode.GetValue()) {
170905 // Unterminated quote
170906 LinePosition current_line_start = {iterator.pos.buffer_idx, iterator.pos.buffer_pos,
170907 result.buffer_size};
170908 result.current_line_position.begin = result.current_line_position.end;
170909 result.current_line_position.end = current_line_start;
170910 result.InvalidState(result);
170911 } else {
170912 if (result.IsCommentSet(result)) {
170913 result.UnsetComment(result, iterator.pos.buffer_pos);
170914 } else {
170915 if (result.quoted && states.IsDelimiterBytes() &&
170916 state_machine->dialect_options.state_machine_options.strict_mode.GetValue()) {
170917 result.current_errors.Insert(UNTERMINATED_QUOTES, result.cur_col_id, result.chunk_col_id,
170918 result.last_position);
170919 }
170920 result.AddRow(result, previous_buffer_handle->actual_size);
170921 }
170922 lines_read++;
170923 }
170924 return false;
170925 }
170926 result.buffer_handles[cur_buffer_handle->buffer_idx] = cur_buffer_handle;
170927
170928 iterator.pos.buffer_pos = 0;
170930 // Handle over-buffer value
170932 result.buffer_ptr = buffer_handle_ptr;
170933 result.buffer_size = cur_buffer_handle->actual_size;
170934 return true;
170935 }
170936 return false;
170937}
void ProcessOverBufferValue()
Function used to process values that go over the first buffer, extra allocation might be necessary.
Definition duckdb.cpp:170651
Here is the call graph for this function:
Here is the caller graph for this function:

◆ SetStart()

void duckdb::StringValueScanner::SetStart ( )
private

-----— Functions used to figure out where lines start ------—!// Main function, sets the correct start

171114 {
171115 start_pos = iterator.GetGlobalCurrentPos();
171116 if (iterator.first_one) {
171117 if (result.store_line_size) {
171118 result.error_handler.NewMaxLineSize(iterator.pos.buffer_pos);
171119 }
171120 return;
171121 }
171122 if (iterator.GetEndPos() > cur_buffer_handle->actual_size) {
171123 iterator.SetEnd(cur_buffer_handle->actual_size);
171124 }
171125 if (!state_machine_strict) {
171126 // We need to initialize our strict state machine
171127 auto &state_machine_cache = CSVStateMachineCache::Get(buffer_manager->context);
171128 auto state_options = state_machine->state_machine_options;
171129 // To set the state machine to be strict we ensure that strict_mode is set to true
171130 if (!state_options.strict_mode.IsSetByUser()) {
171131 state_options.strict_mode = true;
171132 }
171134 make_shared_ptr<CSVStateMachine>(state_machine_cache.Get(state_options), state_machine->options);
171135 }
171136 // At this point we have 3 options:
171137 // 1. We are at the start of a valid line
171138 ValidRowInfo best_row = TryRow(CSVState::STANDARD_NEWLINE, iterator.pos.buffer_pos, iterator.GetEndPos());
171139 // 2. We are in the middle of a quoted value
171140 if (state_machine->dialect_options.state_machine_options.quote.GetValue() != '\0') {
171141 idx_t end_pos = iterator.GetEndPos();
171142 if (best_row.is_valid && best_row.end_buffer_idx == iterator.pos.buffer_idx) {
171143 // If we got a valid row from the standard state, we limit our search up to that.
171144 end_pos = best_row.end_pos;
171145 }
171146 auto quoted_row = TryRow(CSVState::QUOTED, iterator.pos.buffer_pos, end_pos);
171147 if (quoted_row.is_valid && (!best_row.is_valid || best_row.last_state_quote)) {
171148 best_row = quoted_row;
171149 }
171150 if (!best_row.is_valid && !quoted_row.is_valid && best_row.start_pos < quoted_row.start_pos) {
171151 best_row = quoted_row;
171152 }
171153 if (quoted_row.is_valid && quoted_row.start_pos < best_row.start_pos) {
171154 best_row = quoted_row;
171155 }
171156 }
171157 // 3. We are in an escaped value
171158 if (!best_row.is_valid && state_machine->dialect_options.state_machine_options.quote.GetValue() != '\0') {
171159 auto escape_row = TryRow(CSVState::ESCAPE, iterator.pos.buffer_pos, iterator.GetEndPos());
171160 if (escape_row.is_valid) {
171161 best_row = escape_row;
171162 } else {
171163 if (best_row.start_pos < escape_row.start_pos) {
171164 best_row = escape_row;
171165 }
171166 }
171167 }
171168 if (!best_row.is_valid) {
171169 bool is_this_the_end =
171170 best_row.start_pos >= cur_buffer_handle->actual_size && cur_buffer_handle->is_last_buffer;
171171 if (is_this_the_end) {
171172 iterator.pos.buffer_pos = best_row.start_pos;
171173 iterator.done = true;
171174 } else {
171175 bool mock;
171177 iterator.CheckIfDone();
171178 }
171179 }
171180 } else {
171181 iterator.pos.buffer_pos = best_row.start_pos;
171182 bool is_this_the_end =
171183 best_row.start_pos >= cur_buffer_handle->actual_size && cur_buffer_handle->is_last_buffer;
171184 if (is_this_the_end) {
171185 iterator.done = true;
171186 }
171187 }
171188
171189 // 4. We have an error, if we have an error, we let life go on, the scanner will either ignore it
171190 // or throw.
171191 result.last_position = {iterator.pos.buffer_idx, iterator.pos.buffer_pos, result.buffer_size};
171192 start_pos = iterator.GetGlobalCurrentPos();
171193}
shared_ptr< CSVStateMachine > state_machine_strict
Strict state machine is basically a state machine with rfc 4180 set to true, used to figure out a new...
Definition duckdb.cpp:167973
bool SkipUntilState(CSVState initial_state, CSVState until_state, CSVIterator &current_iterator, bool &quoted) const
From a given initial state, it skips until we reach the until_state.
Definition duckdb.cpp:170976
@ STANDARD_NEWLINE
If we are in a comment state, and hence have to skip the whole line.
Definition duckdb.cpp:59191
Here is the call graph for this function:
Here is the caller graph for this function:

◆ SkipUntilState()

bool duckdb::StringValueScanner::SkipUntilState ( CSVState initial_state,
CSVState until_state,
CSVIterator & current_iterator,
bool & quoted ) const
private

From a given initial state, it skips until we reach the until_state.

170977 {
170978 CSVStates current_state;
170979 current_state.Initialize(initial_state);
170980 bool first_column = true;
170981 const idx_t to_pos = current_iterator.GetEndPos();
170982 while (current_iterator.pos.buffer_pos < to_pos) {
170983 state_machine_strict->Transition(current_state, buffer_handle_ptr[current_iterator.pos.buffer_pos++]);
170984 if (current_state.IsState(CSVState::STANDARD) || current_state.IsState(CSVState::STANDARD_NEWLINE)) {
170985 while (current_iterator.pos.buffer_pos + 8 < to_pos) {
170986 uint64_t value = Load<uint64_t>(
170987 reinterpret_cast<const_data_ptr_t>(&buffer_handle_ptr[current_iterator.pos.buffer_pos]));
170988 if (ContainsZeroByte((value ^ state_machine_strict->transition_array.delimiter) &
170989 (value ^ state_machine_strict->transition_array.new_line) &
170990 (value ^ state_machine_strict->transition_array.carriage_return) &
170991 (value ^ state_machine_strict->transition_array.comment))) {
170992 break;
170993 }
170994 current_iterator.pos.buffer_pos += 8;
170995 }
170996 while (state_machine_strict->transition_array
170997 .skip_standard[static_cast<uint8_t>(buffer_handle_ptr[current_iterator.pos.buffer_pos])] &&
170998 current_iterator.pos.buffer_pos < to_pos - 1) {
170999 current_iterator.pos.buffer_pos++;
171000 }
171001 }
171002 if (current_state.IsState(CSVState::QUOTED)) {
171003 while (current_iterator.pos.buffer_pos + 8 < to_pos) {
171004 uint64_t value = Load<uint64_t>(
171005 reinterpret_cast<const_data_ptr_t>(&buffer_handle_ptr[current_iterator.pos.buffer_pos]));
171006 if (ContainsZeroByte((value ^ state_machine_strict->transition_array.quote) &
171007 (value ^ state_machine_strict->transition_array.escape))) {
171008 break;
171009 }
171010 current_iterator.pos.buffer_pos += 8;
171011 }
171012
171013 while (state_machine_strict->transition_array
171014 .skip_quoted[static_cast<uint8_t>(buffer_handle_ptr[current_iterator.pos.buffer_pos])] &&
171015 current_iterator.pos.buffer_pos < to_pos - 1) {
171016 current_iterator.pos.buffer_pos++;
171017 }
171018 }
171019 if ((current_state.IsState(CSVState::DELIMITER) || current_state.IsState(CSVState::CARRIAGE_RETURN) ||
171020 current_state.IsState(CSVState::RECORD_SEPARATOR)) &&
171021 first_column) {
171022 if (buffer_handle_ptr[current_iterator.pos.buffer_pos - 1] ==
171023 state_machine_strict->dialect_options.state_machine_options.quote.GetValue()) {
171024 quoted = true;
171025 }
171026 }
171027 if (current_state.WasState(CSVState::DELIMITER)) {
171028 first_column = false;
171029 }
171030 if (current_state.IsState(until_state)) {
171031 return true;
171032 }
171033 if (current_state.IsState(CSVState::INVALID)) {
171034 return false;
171035 }
171036 }
171037 return false;
171038}
::uint64_t uint64_t
Here is the call graph for this function:
Here is the caller graph for this function:

◆ IsRowValid()

bool duckdb::StringValueScanner::IsRowValid ( CSVIterator & current_iterator) const
private

If the current row we found is valid.

171069 {
171070 if (iterator.pos.buffer_pos == cur_buffer_handle->actual_size) {
171071 return false;
171072 }
171073 constexpr idx_t result_size = 1;
171074 auto scan_finder = make_uniq<StringValueScanner>(LINE_FINDER_ID, buffer_manager, state_machine_strict,
171075 make_shared_ptr<CSVErrorHandler>(), csv_file_scan, false,
171076 current_iterator, result_size);
171077 try {
171078 auto &tuples = scan_finder->ParseChunk();
171079 current_iterator.pos = scan_finder->GetIteratorPosition();
171080 bool has_error = false;
171081 if (tuples.current_errors.HasError()) {
171082 if (tuples.current_errors.Size() != 1 || !tuples.current_errors.HasErrorType(MAXIMUM_LINE_SIZE)) {
171083 // We ignore maximum line size errors
171084 has_error = true;
171085 }
171086 }
171087 return (tuples.number_of_rows == 1 || tuples.first_line_is_comment) && !has_error && tuples.borked_rows.empty();
171088 } catch (const Exception &e) {
171089 return false;
171090 }
171091 return true;
171092}
@ MAXIMUM_LINE_SIZE
If something went wrong during sniffing and was not possible to find suitable candidates.
Definition duckdb.cpp:166191

◆ TryRow()

ValidRowInfo duckdb::StringValueScanner::TryRow ( CSVState state,
idx_t start_pos,
idx_t end_pos ) const
private
171094 {
171095 auto current_iterator = iterator;
171096 current_iterator.SetStart(start_pos);
171097 current_iterator.SetEnd(end_pos);
171098 bool quoted = false;
171099 if (SkipUntilState(state, CSVState::RECORD_SEPARATOR, current_iterator, quoted)) {
171100 auto iterator_start = current_iterator;
171101 idx_t current_pos = current_iterator.pos.buffer_pos;
171102 current_iterator.SetEnd(iterator.GetEndPos());
171103 if (IsRowValid(current_iterator)) {
171104 if (!quoted) {
171105 quoted = FirstValueEndsOnQuote(iterator_start);
171106 }
171107 return {true, current_pos, current_iterator.pos.buffer_idx, current_iterator.pos.buffer_pos, quoted};
171108 }
171109 }
171110 return {false, current_iterator.pos.buffer_pos, current_iterator.pos.buffer_idx, current_iterator.pos.buffer_pos,
171111 quoted};
171112}
bool IsRowValid(CSVIterator &current_iterator) const
If the current row we found is valid.
Definition duckdb.cpp:171069

◆ FirstValueEndsOnQuote()

bool duckdb::StringValueScanner::FirstValueEndsOnQuote ( CSVIterator iterator) const
private
170961 {
170962 CSVStates current_state;
170963 current_state.Initialize(CSVState::STANDARD);
170964 const idx_t to_pos = iterator.GetEndPos();
170965 while (iterator.pos.buffer_pos < to_pos) {
170966 state_machine->Transition(current_state, buffer_handle_ptr[iterator.pos.buffer_pos++]);
170967 if (current_state.IsState(CSVState::DELIMITER) || current_state.IsState(CSVState::CARRIAGE_RETURN) ||
170968 current_state.IsState(CSVState::RECORD_SEPARATOR)) {
170969 return buffer_handle_ptr[iterator.pos.buffer_pos - 2] ==
170970 state_machine->dialect_options.state_machine_options.quote.GetValue();
170971 }
170972 }
170973 return false;
170974}

The documentation for this class was generated from the following file: