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::CSVSniffer Class Reference

Sniffer that detects Header, Dialect and Types of CSV Files. More...

Collaboration diagram for duckdb::CSVSniffer:

Public Member Functions

 CSVSniffer (CSVReaderOptions &options_p, const MultiFileOptions &file_options, shared_ptr< CSVBufferManager > buffer_manager_p, CSVStateMachineCache &state_machine_cache, bool default_null_to_varchar=true)
SnifferResult SniffCSV (bool force_match=false)
SnifferResult AdaptiveSniff (const CSVSchema &file_schema)
AdaptiveSnifferResult MinimalSniff ()
 Function that only sniffs the first two rows, to verify if a header exists and what are the data types.
idx_t LinesSniffed () const
bool EmptyOrOnlyHeader () const

Static Public Member Functions

static NewLineIdentifier DetectNewLineDelimiter (CSVBufferManager &buffer_manager)
static bool CanYouCastIt (ClientContext &context, const string_t value, const LogicalType &type, const DialectOptions &dialect_options, const bool is_null, const char decimal_separator, const char thousands_separator)
 If a string_t value can be cast to a type.

Private Member Functions

void SetResultOptions () const
 Sets the result options.
void DetectDialect ()
void GenerateStateMachineSearchSpace (vector< unique_ptr< ColumnCountScanner > > &column_count_scanners, const DialectCandidates &dialect_candidates)
void AnalyzeDialectCandidate (unique_ptr< ColumnCountScanner >, CandidateStats &stats, vector< unique_ptr< ColumnCountScanner > > &successful_candidates)
void RefineCandidates ()
bool RefineCandidateNextChunk (ColumnCountScanner &candidate) const
 Checks if candidate still produces good values for the next chunk.
void DetectTypes ()
void InitializeDateAndTimeStampDetection (CSVStateMachine &candidate, const string &separator, const LogicalType &sql_type)
 Function that initialized the necessary variables used for date and timestamp detection.
void SetUserDefinedDateTimeFormat (CSVStateMachine &candidate) const
 Sets user defined date and time formats (if any).
void DetectDateAndTimeStampFormats (CSVStateMachine &candidate, const LogicalType &sql_type, const string &separator, const string_t &dummy_val)
 Functions that performs detection for date and timestamp formats.
void SniffTypes (DataChunk &data_chunk, CSVStateMachine &state_machine, unordered_map< idx_t, vector< LogicalType > > &info_sql_types_candidates, idx_t start_idx_detection)
 Sniffs the types from a data chunk.
void RefineTypes ()
bool TryCastVector (Vector &parse_chunk_col, idx_t size, const LogicalType &sql_type) const
void DetectHeader ()
void ReplaceTypes ()

Static Private Member Functions

static void SetDateFormat (CSVStateMachine &candidate, const string &format_specifier, const LogicalTypeId &sql_type)
static bool DetectHeaderWithSetColumn (ClientContext &context, vector< HeaderValue > &best_header_row, const SetColumns &set_columns, CSVReaderOptions &options)
static vector< string > DetectHeaderInternal (ClientContext &context, vector< HeaderValue > &best_header_row, CSVStateMachine &state_machine, const SetColumns &set_columns, unordered_map< idx_t, vector< LogicalType > > &best_sql_types_candidates_per_column_idx, CSVReaderOptions &options, const MultiFileOptions &file_options, CSVErrorHandler &error_handler)

Private Attributes

bool all_fail_max_line_size = true
 If all our candidates failed due to lines being bigger than the max line size.
CSVError line_error
CSVStateMachineCache & state_machine_cache
 CSV State Machine Cache.
idx_t max_columns_found = 0
 Highest number of columns found.
idx_t max_columns_found_error = 0
bool best_candidate_is_strict = false
vector< unique_ptr< ColumnCountScanner > > candidates
 Current Candidates being considered.
CSVReaderOptions & options
 Reference to original CSV Options, it will be modified as a result of the sniffer.
const MultiFileOptions & file_options
 The multi-file reader options.
shared_ptr< CSVBufferManager > buffer_manager
 Buffer being used on sniffer.
SetColumns set_columns
 Information regarding columns that were set by user/query.
shared_ptr< CSVErrorHandler > error_handler
shared_ptr< CSVErrorHandler > detection_error_handler
idx_t lines_sniffed
 Number of lines sniffed in this sniffer.
const map< LogicalTypeId, vector< const char * > > format_template_candidates
unordered_map< idx_t, vector< LogicalType > > best_sql_types_candidates_per_column_idx
map< LogicalTypeId, vector< string > > best_format_candidates
unique_ptr< StringValueScanner > best_candidate
vector< HeaderValue > best_header_row
map< LogicalTypeId, DateTimestampSniffing > format_candidates
 Variable used for sniffing date and timestamp.
map< LogicalTypeId, DateTimestampSniffing > original_format_candidates
vector< LogicalType > detected_types
const bool default_null_to_varchar
 If when finding a SQLNULL type in type detection we default it to varchar.
vector< string > names
bool single_row_file = false
 If the file only has a header.
vector< bool > manually_set

Detailed Description

Sniffer that detects Header, Dialect and Types of CSV Files.

Constructor & Destructor Documentation

◆ CSVSniffer()

duckdb::CSVSniffer::CSVSniffer ( CSVReaderOptions & options_p,
const MultiFileOptions & file_options,
shared_ptr< CSVBufferManager > buffer_manager_p,
CSVStateMachineCache & state_machine_cache,
bool default_null_to_varchar = true )
explicit
171303 : state_machine_cache(state_machine_cache_p), options(options_p), file_options(file_options),
171304 buffer_manager(std::move(buffer_manager_p)), lines_sniffed(0),
171305 default_null_to_varchar(default_null_to_varchar_p) {
171306 // Initialize Format Candidates
171307 for (const auto &format_template : format_template_candidates) {
171308 auto &logical_type = format_template.first;
171309 best_format_candidates[logical_type].clear();
171310 }
171311 // Initialize max columns found to either 0, or however many were set
171313 error_handler = make_shared_ptr<CSVErrorHandler>(options.ignore_errors.GetValue());
171314 detection_error_handler = make_shared_ptr<CSVErrorHandler>(true);
171315 if (options.columns_set) {
171316 set_columns = SetColumns(&options.sql_type_list, &options.name_list);
171317 }
171318}
idx_t max_columns_found
Highest number of columns found.
Definition duckdb.cpp:168167
idx_t lines_sniffed
Number of lines sniffed in this sniffer.
Definition duckdb.cpp:168183
CSVStateMachineCache & state_machine_cache
CSV State Machine Cache.
Definition duckdb.cpp:168165
shared_ptr< CSVBufferManager > buffer_manager
Buffer being used on sniffer.
Definition duckdb.cpp:168177
const bool default_null_to_varchar
If when finding a SQLNULL type in type detection we default it to varchar.
Definition duckdb.cpp:168252
SetColumns set_columns
Information regarding columns that were set by user/query.
Definition duckdb.cpp:168179
const MultiFileOptions & file_options
The multi-file reader options.
Definition duckdb.cpp:168175
CSVReaderOptions & options
Reference to original CSV Options, it will be modified as a result of the sniffer.
Definition duckdb.cpp:168173
const map< LogicalTypeId, vector< const char * > > format_template_candidates
Definition duckdb.cpp:168231

Member Function Documentation

◆ SniffCSV()

SnifferResult duckdb::CSVSniffer::SniffCSV ( bool force_match = false)

Main method that sniffs the CSV file, returns the types, names and options as a result CSV Sniffing consists of five steps:

  1. Dialect Detection: Generate the CSV Options (delimiter, quote, escape, etc.)
  2. Type Detection: Figures out the types of the columns (For one chunk)
  3. Type Refinement: Refines the types of the columns for the remaining chunks
  4. Header Detection: Figures out if the CSV file has a header and produces the names of the columns
  5. Type Replacement: Replaces the types of the columns if the user specified them
171466 {
171467 buffer_manager->sniffing = true;
171468 // 1. Dialect Detection
171469 DetectDialect();
171470 if (buffer_manager->file_handle->compression_type != FileCompressionType::UNCOMPRESSED &&
171471 buffer_manager->IsBlockUnloaded(0)) {
171472 buffer_manager->ResetBufferManager();
171473 }
171474 // 2. Type Detection
171475 DetectTypes();
171476 // 3. Type Refinement
171477 RefineTypes();
171478 // 4. Header Detection
171479 DetectHeader();
171480 // 5. Type Replacement
171481 ReplaceTypes();
171482
171483 // We reset the buffer for compressed files
171484 // This is done because we can't easily seek on compressed files, if a buffer goes out of scope we must read from
171485 // the start
171486 if (buffer_manager->file_handle->compression_type != FileCompressionType::UNCOMPRESSED) {
171487 buffer_manager->ResetBufferManager();
171488 }
171489 buffer_manager->sniffing = false;
171490 if (best_candidate->error_handler->AnyErrors() && !options.ignore_errors.GetValue() &&
171491 best_candidate->state_machine->dialect_options.state_machine_options.strict_mode.GetValue()) {
171492 best_candidate->error_handler->ErrorIfTypeExists(MAXIMUM_LINE_SIZE);
171493 }
171494 D_ASSERT(best_sql_types_candidates_per_column_idx.size() == names.size());
171495 // We are done, Set the CSV Options in the reference. Construct and return the result.
171497 options.auto_detect = true;
171498 // Check if everything matches
171499 auto &error = options.sniffer_user_mismatch_error;
171500 if (set_columns.IsSet()) {
171501 bool match = true;
171502 // Columns and their types were set, let's validate they match
171503 if (options.dialect_options.header.GetValue()) {
171504 // If the header exists it should match
171505 string header_error = "The Column names set by the user do not match the ones found by the sniffer. \n";
171506 auto &set_names = *set_columns.names;
171507 if (set_names.size() == names.size()) {
171508 for (idx_t i = 0; i < set_columns.Size(); i++) {
171509 if (set_names[i] != names[i]) {
171510 header_error += "Column at position: " + to_string(i) + ", Set name: " + set_names[i] +
171511 ", Sniffed Name: " + names[i] + "\n";
171512 match = false;
171513 }
171514 }
171515 }
171516
171517 if (!match) {
171518 error += header_error;
171519 }
171520 }
171521 match = true;
171522 string type_error = "The Column types set by the user do not match the ones found by the sniffer. \n";
171523 auto &set_types = *set_columns.types;
171524 if (detected_types.size() == set_columns.Size()) {
171525 for (idx_t i = 0; i < set_columns.Size(); i++) {
171526 if (set_types[i] != detected_types[i]) {
171527 type_error += "Column at position: " + to_string(i) + " Set type: " + set_types[i].ToString() +
171528 " Sniffed type: " + detected_types[i].ToString() + "\n";
171529 detected_types[i] = set_types[i];
171530 manually_set[i] = true;
171531 match = false;
171532 }
171533 }
171534 }
171535
171536 if (!match) {
171537 error += type_error;
171538 }
171539
171540 if (!error.empty() && force_match) {
171541 throw InvalidInputException(error);
171542 }
171543 options.was_type_manually_set = manually_set;
171544 }
171545 if (!error.empty() && force_match) {
171546 throw InvalidInputException(error);
171547 }
171548 options.was_type_manually_set = manually_set;
171549 if (set_columns.IsSet()) {
171550 return SnifferResult(*set_columns.types, *set_columns.names);
171551 }
171552 return SnifferResult(detected_types, names);
171553}
void RefineTypes()
Definition duckdb.cpp:173919
void ReplaceTypes()
Definition duckdb.cpp:173981
void DetectHeader()
Definition duckdb.cpp:173271
void DetectTypes()
Definition duckdb.cpp:173779
void DetectDialect()
Definition duckdb.cpp:172160
void SetResultOptions() const
Sets the result options.
Definition duckdb.cpp:171358
std::string to_string(const T &value)
Definition duckdb.cpp:19425
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237
@ MAXIMUM_LINE_SIZE
If something went wrong during sniffing and was not possible to find suitable candidates.
Definition duckdb.cpp:166191
Here is the call graph for this function:
Here is the caller graph for this function:

◆ AdaptiveSniff()

SnifferResult duckdb::CSVSniffer::AdaptiveSniff ( const CSVSchema & file_schema)

I call it adaptive, since that's a sexier term. In practice this Function that only sniffs the first two rows, to verify if a header exists and what are the data types It does this considering a priorly set CSV schema. If there is a mismatch of the schema it runs the full on blazing all guns sniffer, if that still fails it tells the user to union_by_name. It returns the projection order.

171440 {
171441 auto min_sniff_res = MinimalSniff();
171442 bool run_full = error_handler->AnyErrors() || detection_error_handler->AnyErrors();
171443 // Check if we are happy with the result or if we need to do more sniffing
171444 if (!error_handler->AnyErrors() && !detection_error_handler->AnyErrors()) {
171445 // If we got no errors, we also run full if schemas do not match.
171446 if (!set_columns.IsSet() && !file_options.AnySet()) {
171447 string error;
171448 run_full = !file_schema.SchemasMatch(error, min_sniff_res, options.file_path, true);
171449 }
171450 }
171451 if (run_full) {
171452 // We run full sniffer
171453 auto full_sniffer = SniffCSV();
171454 if (!set_columns.IsSet() && !file_options.AnySet()) {
171455 string error;
171456 if (!file_schema.SchemasMatch(error, full_sniffer, options.file_path, false) &&
171457 !options.ignore_errors.GetValue()) {
171458 throw InvalidInputException(error);
171459 }
171460 }
171461 return full_sniffer;
171462 }
171463 return min_sniff_res.ToSnifferResult();
171464}
AdaptiveSnifferResult MinimalSniff()
Function that only sniffs the first two rows, to verify if a header exists and what are the data type...
Definition duckdb.cpp:171374
SnifferResult SniffCSV(bool force_match=false)
Definition duckdb.cpp:171466
Here is the call graph for this function:
Here is the caller graph for this function:

◆ MinimalSniff()

AdaptiveSnifferResult duckdb::CSVSniffer::MinimalSniff ( )

Function that only sniffs the first two rows, to verify if a header exists and what are the data types.

171374 {
171375 if (set_columns.IsSet()) {
171376 // Nothing to see here
171377 return AdaptiveSnifferResult(*set_columns.types, *set_columns.names, true);
171378 }
171379 // Return Types detected
171380 vector<LogicalType> return_types;
171381 // Column Names detected
171382 buffer_manager->sniffing = true;
171383 constexpr idx_t result_size = STANDARD_VECTOR_SIZE;
171384
171385 auto state_machine =
171386 make_shared_ptr<CSVStateMachine>(options, options.dialect_options.state_machine_options, state_machine_cache);
171387 ColumnCountScanner count_scanner(buffer_manager, state_machine, error_handler, result_size);
171388 auto &sniffed_column_counts = count_scanner.ParseChunk();
171389 if (sniffed_column_counts.result_position == 0) {
171390 // The file is an empty file, we just return
171391 return {{}, {}, false};
171392 }
171393
171394 state_machine->dialect_options.num_cols = sniffed_column_counts[0].number_of_columns;
171395 options.dialect_options.num_cols = sniffed_column_counts[0].number_of_columns;
171396
171397 // First figure out the number of columns on this configuration
171398 auto scanner = count_scanner.UpgradeToStringValueScanner();
171399 scanner->error_handler->SetIgnoreErrors(true);
171400 // Parse chunk and read csv with info candidate
171401 auto &data_chunk = scanner->ParseChunk().ToChunk();
171402 idx_t start_row = 0;
171403 if (sniffed_column_counts.result_position == 2) {
171404 // If equal to two, we will only use the second row for type checking
171405 start_row = 1;
171406 }
171407
171408 // Gather Types
171409 for (idx_t i = 0; i < state_machine->dialect_options.num_cols; i++) {
171410 best_sql_types_candidates_per_column_idx[i] = state_machine->options.auto_type_candidates;
171411 }
171412 SniffTypes(data_chunk, *state_machine, best_sql_types_candidates_per_column_idx, start_row);
171413
171414 // Possibly Gather Header
171415 vector<HeaderValue> potential_header;
171416 for (idx_t col_idx = 0; col_idx < data_chunk.ColumnCount(); col_idx++) {
171417 auto &cur_vector = data_chunk.data[col_idx];
171418 const auto vector_data = FlatVector::GetData<string_t>(cur_vector);
171419 auto &validity = FlatVector::Validity(cur_vector);
171420 HeaderValue val;
171421 if (validity.RowIsValid(0)) {
171422 val = HeaderValue(vector_data[0]);
171423 }
171424 potential_header.emplace_back(val);
171425 }
171426
171427 auto names = DetectHeaderInternal(buffer_manager->context, potential_header, *state_machine, set_columns,
171428 best_sql_types_candidates_per_column_idx, options, file_options, *error_handler);
171429
171430 for (idx_t column_idx = 0; column_idx < best_sql_types_candidates_per_column_idx.size(); column_idx++) {
171431 LogicalType d_type = best_sql_types_candidates_per_column_idx[column_idx].back();
171432 if (best_sql_types_candidates_per_column_idx[column_idx].size() == options.auto_type_candidates.size()) {
171433 d_type = LogicalType::VARCHAR;
171434 }
171435 detected_types.push_back(d_type);
171436 }
171437 return {detected_types, names, sniffed_column_counts.result_position > 1};
171438}
void SniffTypes(DataChunk &data_chunk, CSVStateMachine &state_machine, unordered_map< idx_t, vector< LogicalType > > &info_sql_types_candidates, idx_t start_idx_detection)
Sniffs the types from a data chunk.
Definition duckdb.cpp:173703
GOpaque< Size > size(const GMat &src)
Here is the call graph for this function:
Here is the caller graph for this function:

◆ DetectNewLineDelimiter()

NewLineIdentifier duckdb::CSVSniffer::DetectNewLineDelimiter ( CSVBufferManager & buffer_manager)
static
172130 {
172131 // Get first buffer
172132 auto buffer = buffer_manager.GetBuffer(0);
172133 auto buffer_ptr = buffer->Ptr();
172134 bool carriage_return = false;
172135 bool n = false;
172136 for (idx_t i = 0; i < buffer->actual_size; i++) {
172137 if (buffer_ptr[i] == '\r') {
172138 carriage_return = true;
172139 } else if (buffer_ptr[i] == '\n') {
172140 n = true;
172141 break;
172142 } else if (carriage_return) {
172143 break;
172144 }
172145 }
172146 if (carriage_return && n) {
172147 return NewLineIdentifier::CARRY_ON;
172148 }
172149 if (carriage_return) {
172150 return NewLineIdentifier::SINGLE_R;
172151 }
172152 return NewLineIdentifier::SINGLE_N;
172153}
shared_ptr< T > buffer_ptr
FIXME: this should be a single_thread_ptr.
Definition duckdb.hpp:2709

◆ CanYouCastIt()

bool duckdb::CSVSniffer::CanYouCastIt ( ClientContext & context,
const string_t value,
const LogicalType & type,
const DialectOptions & dialect_options,
const bool is_null,
const char decimal_separator,
const char thousands_separator )
static

If a string_t value can be cast to a type.

173463 {
173464 if (is_null) {
173465 return true;
173466 }
173467 auto value_ptr = value.GetData();
173468 auto value_size = value.GetSize();
173469 string strip_thousands;
173470 if (type.IsNumeric() && thousands_separator != '\0') {
173471 // If we have a thousands separator we should try to use that
173472 strip_thousands = BaseScanner::RemoveSeparator(value_ptr, value_size, thousands_separator);
173473 value_ptr = strip_thousands.c_str();
173474 value_size = strip_thousands.size();
173475 }
173476 switch (type.id()) {
173477 case LogicalTypeId::BOOLEAN: {
173478 bool dummy_value;
173479 return TryCastStringBool(value_ptr, value_size, dummy_value, true);
173480 }
173481 case LogicalTypeId::TINYINT: {
173482 int8_t dummy_value;
173483 return TrySimpleIntegerCast(value_ptr, value_size, dummy_value, false);
173484 }
173485 case LogicalTypeId::SMALLINT: {
173486 int16_t dummy_value;
173487 return TrySimpleIntegerCast(value_ptr, value_size, dummy_value, true);
173488 }
173489 case LogicalTypeId::INTEGER: {
173490 int32_t dummy_value;
173491 return TrySimpleIntegerCast(value_ptr, value_size, dummy_value, true);
173492 }
173493 case LogicalTypeId::BIGINT: {
173494 int64_t dummy_value;
173495 return TrySimpleIntegerCast(value_ptr, value_size, dummy_value, true);
173496 }
173497 case LogicalTypeId::UTINYINT: {
173498 uint8_t dummy_value;
173499 return TrySimpleIntegerCast(value_ptr, value_size, dummy_value, true);
173500 }
173501 case LogicalTypeId::USMALLINT: {
173502 uint16_t dummy_value;
173503 return TrySimpleIntegerCast(value_ptr, value_size, dummy_value, true);
173504 }
173505 case LogicalTypeId::UINTEGER: {
173506 uint32_t dummy_value;
173507 return TrySimpleIntegerCast(value_ptr, value_size, dummy_value, true);
173508 }
173509 case LogicalTypeId::UBIGINT: {
173510 uint64_t dummy_value;
173511 return TrySimpleIntegerCast(value_ptr, value_size, dummy_value, true);
173512 }
173513 case LogicalTypeId::DOUBLE: {
173514 double dummy_value;
173515 return TryDoubleCast<double>(value_ptr, value_size, dummy_value, true, decimal_separator);
173516 }
173517 case LogicalTypeId::FLOAT: {
173518 float dummy_value;
173519 return TryDoubleCast<float>(value_ptr, value_size, dummy_value, true, decimal_separator);
173520 }
173521 case LogicalTypeId::DATE: {
173522 if (!dialect_options.date_format.find(LogicalTypeId::DATE)->second.GetValue().Empty()) {
173523 date_t result;
173524 string error_message;
173525 return dialect_options.date_format.find(LogicalTypeId::DATE)
173526 ->second.GetValue()
173527 .TryParseDate(value, result, error_message);
173528 }
173529 idx_t pos;
173530 bool special;
173531 date_t dummy_value;
173532 return Date::TryConvertDate(value_ptr, value_size, pos, dummy_value, special, true) == DateCastResult::SUCCESS;
173533 }
173534 case LogicalTypeId::TIMESTAMP: {
173535 timestamp_t dummy_value;
173536 if (!dialect_options.date_format.find(LogicalTypeId::TIMESTAMP)->second.GetValue().Empty()) {
173537 string error_message;
173538 return dialect_options.date_format.find(LogicalTypeId::TIMESTAMP)
173539 ->second.GetValue()
173540 .TryParseTimestamp(value, dummy_value, error_message);
173541 }
173542 return Timestamp::TryConvertTimestamp(value_ptr, value_size, dummy_value, false, nullptr, true) ==
173543 TimestampCastResult::SUCCESS;
173544 }
173545 case LogicalTypeId::TIME: {
173546 idx_t pos;
173547 dtime_t dummy_value;
173548 return Time::TryConvertTime(value_ptr, value_size, pos, dummy_value, true);
173549 }
173550 case LogicalTypeId::DECIMAL: {
173551 uint8_t width, scale;
173552 type.GetDecimalProperties(width, scale);
173553 if (decimal_separator == ',') {
173554 switch (type.InternalType()) {
173555 case PhysicalType::INT16: {
173556 int16_t dummy_value;
173557 return TryDecimalStringCast<int16_t, ','>(value_ptr, value_size, dummy_value, width, scale);
173558 }
173559
173560 case PhysicalType::INT32: {
173561 int32_t dummy_value;
173562 return TryDecimalStringCast<int32_t, ','>(value_ptr, value_size, dummy_value, width, scale);
173563 }
173564
173565 case PhysicalType::INT64: {
173566 int64_t dummy_value;
173567 return TryDecimalStringCast<int64_t, ','>(value_ptr, value_size, dummy_value, width, scale);
173568 }
173569
173570 case PhysicalType::INT128: {
173571 hugeint_t dummy_value;
173572 return TryDecimalStringCast<hugeint_t, ','>(value_ptr, value_size, dummy_value, width, scale);
173573 }
173574
173575 default:
173576 throw InternalException("Invalid Physical Type for Decimal Value. Physical Type: " +
173577 TypeIdToString(type.InternalType()));
173578 }
173579
173580 } else if (decimal_separator == '.') {
173581 switch (type.InternalType()) {
173582 case PhysicalType::INT16: {
173583 int16_t dummy_value;
173584 return TryDecimalStringCast(value_ptr, value_size, dummy_value, width, scale);
173585 }
173586
173587 case PhysicalType::INT32: {
173588 int32_t dummy_value;
173589 return TryDecimalStringCast(value_ptr, value_size, dummy_value, width, scale);
173590 }
173591
173592 case PhysicalType::INT64: {
173593 int64_t dummy_value;
173594 return TryDecimalStringCast(value_ptr, value_size, dummy_value, width, scale);
173595 }
173596
173597 case PhysicalType::INT128: {
173598 hugeint_t dummy_value;
173599 return TryDecimalStringCast(value_ptr, value_size, dummy_value, width, scale);
173600 }
173601
173602 default:
173603 throw InternalException("Invalid Physical Type for Decimal Value. Physical Type: " +
173604 TypeIdToString(type.InternalType()));
173605 }
173606 }
173607 throw InvalidInputException("Decimals can only have ',' and '.' as decimal separators");
173608 }
173609 case LogicalTypeId::VARCHAR:
173610 return true;
173611 default: {
173612 // We do Value Try Cast for non-basic types.
173613 Value new_value;
173614 string error_message;
173615 Value str_value(value);
173616 bool success = str_value.TryCastAs(context, type, new_value, &error_message, true);
173617 return success && error_message.empty();
173618 }
173619 }
173620}
static string RemoveSeparator(const char *value_ptr, const idx_t size, char thousands_separator)
Removes thousands separator.
Definition duckdb.cpp:168369
static DUCKDB_API DateCastResult TryConvertDate(const char *buf, idx_t len, idx_t &pos, date_t &result, bool &special, bool strict=false)
Definition duckdb.cpp:117363
static DUCKDB_API TimestampCastResult TryConvertTimestamp(const char *str, idx_t len, timestamp_t &result, const bool use_offset, optional_ptr< int32_t > nanos=nullptr, bool strict=false)
Strict Timestamp does not accept offsets.
Definition duckdb.cpp:129558
void scale(cv::Mat &mat, const cv::Mat &range, const T min, const T max)
::int64_t int64_t
::int8_t int8_t
::uint32_t uint32_t
::uint8_t uint8_t
::uint64_t uint64_t
::uint16_t uint16_t
::int32_t int32_t
::int16_t int16_t
@ INT64
Signed 64-bit little-endian integer.
Definition duckdb.hpp:2767
@ INT16
Signed 16-bit little-endian integer.
Definition duckdb.hpp:2755
@ INT32
Signed 32-bit little-endian integer.
Definition duckdb.hpp:2761
Here is the call graph for this function:
Here is the caller graph for this function:

◆ LinesSniffed()

idx_t duckdb::CSVSniffer::LinesSniffed ( ) const
173453 {
173454 return lines_sniffed;
173455}

◆ EmptyOrOnlyHeader()

bool duckdb::CSVSniffer::EmptyOrOnlyHeader ( ) const
173457 {
173458 return (single_row_file && best_candidate->state_machine->dialect_options.header.GetValue()) || lines_sniffed == 0;
173459}
bool single_row_file
If the file only has a header.
Definition duckdb.cpp:168267

◆ SetResultOptions()

void duckdb::CSVSniffer::SetResultOptions ( ) const
private

Sets the result options.

171358 {
171359 bool found_date = false;
171360 bool found_timestamp = false;
171361 for (auto &type : detected_types) {
171362 if (type == LogicalType::DATE) {
171363 found_date = true;
171364 } else if (type == LogicalType::TIMESTAMP) {
171365 found_timestamp = true;
171366 }
171367 }
171368 MatchAndReplaceUserSetVariables(options.dialect_options, best_candidate->GetStateMachine().dialect_options,
171369 options.sniffer_user_mismatch_error, found_date, found_timestamp);
171370 options.dialect_options.num_cols = best_candidate->GetStateMachine().dialect_options.num_cols;
171371 options.dialect_options.rows_until_header = best_candidate->GetStateMachine().dialect_options.rows_until_header;
171372}
Here is the caller graph for this function:

◆ DetectDialect()

void duckdb::CSVSniffer::DetectDialect ( )
private

---------------------------------------------------—// --------------— Dialect Detection --------------— // ---------------------------------------------------—// First phase of auto detection: detect CSV dialect (i.e. delimiter, quote rules, etc)

172160 {
172161 // Variables for Dialect Detection
172162 DialectCandidates dialect_candidates(options.dialect_options.state_machine_options);
172163 CandidateStats stats;
172164 // Vector of CSV State Machines
172165 vector<unique_ptr<ColumnCountScanner>> csv_state_machines;
172166 // Step 1: Generate state machines
172167 GenerateStateMachineSearchSpace(csv_state_machines, dialect_candidates);
172168 // Step 2: Analyze all candidates on the first chunk
172169 for (auto &state_machine : csv_state_machines) {
172170 AnalyzeDialectCandidate(std::move(state_machine), stats, candidates);
172171 }
172172 // Step 3: Loop over candidates and find if they can still produce good results for the remaining chunks
172174
172175 // if no dialect candidate was found, we throw an exception
172176 if (candidates.empty()) {
172177 CSVError error;
172179 error = line_error;
172180 } else {
172181 error = CSVError::SniffingError(options, dialect_candidates.Print(), max_columns_found_error, set_columns,
172182 false);
172183 }
172184 error_handler->Error(error, true);
172185 }
172186}
static CSVError SniffingError(const CSVReaderOptions &options, const string &search_space, idx_t max_columns_found, SetColumns &set_columns, bool type_detection)
Produces an error message for a dialect sniffing error.
Definition duckdb.cpp:175977
void GenerateStateMachineSearchSpace(vector< unique_ptr< ColumnCountScanner > > &column_count_scanners, const DialectCandidates &dialect_candidates)
Definition duckdb.cpp:171690
bool all_fail_max_line_size
If all our candidates failed due to lines being bigger than the max line size.
Definition duckdb.cpp:168162
void RefineCandidates()
Definition duckdb.cpp:172056
vector< unique_ptr< ColumnCountScanner > > candidates
Current Candidates being considered.
Definition duckdb.cpp:168171
void AnalyzeDialectCandidate(unique_ptr< ColumnCountScanner >, CandidateStats &stats, vector< unique_ptr< ColumnCountScanner > > &successful_candidates)
Definition duckdb.cpp:171771
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GenerateStateMachineSearchSpace()

void duckdb::CSVSniffer::GenerateStateMachineSearchSpace ( vector< unique_ptr< ColumnCountScanner > > & column_count_scanners,
const DialectCandidates & dialect_candidates )
private

Functions called in the main DetectDialect(); function

  1. Generates the search space candidates for the state machines
171691 {
171692 // Generate state machines for all option combinations
171693 NewLineIdentifier new_line_id;
171694 if (options.dialect_options.state_machine_options.new_line.IsSetByUser()) {
171695 new_line_id = options.dialect_options.state_machine_options.new_line.GetValue();
171696 } else {
171697 new_line_id = DetectNewLineDelimiter(*buffer_manager);
171698 }
171699 CSVIterator first_iterator;
171700 bool iterator_set = false;
171701 for (const auto &comment : dialect_candidates.comment_candidates) {
171702 for (const auto quote_escape_candidate : dialect_candidates.quote_escape_candidates) {
171703 for (const auto &delimiter : dialect_candidates.delim_candidates) {
171704 D_ASSERT(buffer_manager);
171705 CSVStateMachineOptions state_machine_options(
171706 delimiter, quote_escape_candidate.quote, quote_escape_candidate.escape, comment, new_line_id,
171707 options.dialect_options.state_machine_options.strict_mode.GetValue());
171708 auto sniffing_state_machine =
171709 make_shared_ptr<CSVStateMachine>(options, state_machine_options, state_machine_cache);
171710 if (options.dialect_options.skip_rows.IsSetByUser()) {
171711 if (!iterator_set) {
171712 first_iterator = BaseScanner::SkipCSVRows(buffer_manager, sniffing_state_machine,
171713 options.dialect_options.skip_rows.GetValue());
171714 iterator_set = true;
171715 }
171716 column_count_scanners.emplace_back(make_uniq<ColumnCountScanner>(
171717 buffer_manager, std::move(sniffing_state_machine), detection_error_handler,
171718 CSVReaderOptions::sniff_size, first_iterator));
171719 continue;
171720 }
171721 column_count_scanners.emplace_back(
171722 make_uniq<ColumnCountScanner>(buffer_manager, std::move(sniffing_state_machine),
171723 detection_error_handler, CSVReaderOptions::sniff_size));
171724 }
171725 }
171726 }
171727}
static CSVIterator SkipCSVRows(shared_ptr< CSVBufferManager > buffer_manager, const shared_ptr< CSVStateMachine > &state_machine, idx_t rows_to_skip)
Definition duckdb.cpp:168396
static constexpr idx_t sniff_size
Result size of sniffing phases.
Definition duckdb.hpp:51785
Here is the call graph for this function:
Here is the caller graph for this function:

◆ AnalyzeDialectCandidate()

void duckdb::CSVSniffer::AnalyzeDialectCandidate ( unique_ptr< ColumnCountScanner > scanner,
CandidateStats & stats,
vector< unique_ptr< ColumnCountScanner > > & successful_candidates )
private
  1. Analyzes if a dialect candidate is a good candidate to be considered, if so, it adds it to the candidates
171772 {
171773 // The sniffed_column_counts variable keeps track of the number of columns found for each row
171774 auto &sniffed_column_counts = scanner->ParseChunk();
171775 idx_t dirty_notes = 0;
171776 idx_t dirty_notes_minus_comments = 0;
171777 idx_t empty_lines = 0;
171778 if (sniffed_column_counts.error) {
171779 if (!scanner->error_handler->HasError(MAXIMUM_LINE_SIZE)) {
171780 all_fail_max_line_size = false;
171781 } else {
171782 line_error = scanner->error_handler->GetFirstError(MAXIMUM_LINE_SIZE);
171783 }
171784 // This candidate has an error (i.e., over maximum line size or never unquoting quoted values)
171785 return;
171786 }
171787 all_fail_max_line_size = false;
171788 idx_t consistent_rows = 0;
171789 idx_t num_cols = sniffed_column_counts.result_position == 0 ? 1 : sniffed_column_counts[0].number_of_columns;
171790 const bool ignore_errors = options.ignore_errors.GetValue();
171791 // If we are ignoring errors and not null_padding, we pick the most frequent number of columns as the right one
171792 const bool use_most_frequent_columns = ignore_errors && !options.null_padding;
171793 if (use_most_frequent_columns) {
171794 num_cols = sniffed_column_counts.GetMostFrequentColumnCount();
171795 }
171796 idx_t padding_count = 0;
171797 idx_t comment_rows = 0;
171798 idx_t ignored_rows = 0;
171799 const bool allow_padding = options.null_padding;
171800 bool first_valid = false;
171801 if (sniffed_column_counts.result_position > stats.rows_read) {
171802 stats.rows_read = sniffed_column_counts.result_position;
171803 }
171804 if (set_columns.IsCandidateUnacceptable(num_cols, options.null_padding, ignore_errors,
171805 sniffed_column_counts[0].last_value_always_empty)) {
171806 max_columns_found_error = num_cols > max_columns_found_error ? num_cols : max_columns_found_error;
171807 // Not acceptable
171808 return;
171809 }
171810 idx_t header_idx = 0;
171811 for (idx_t row = 0; row < sniffed_column_counts.result_position; row++) {
171812 if (set_columns.IsCandidateUnacceptable(sniffed_column_counts[row].number_of_columns, options.null_padding,
171813 ignore_errors, sniffed_column_counts[row].last_value_always_empty)) {
171814 max_columns_found_error = sniffed_column_counts[row].number_of_columns > max_columns_found_error
171815 ? sniffed_column_counts[row].number_of_columns
171816 : max_columns_found_error;
171817 // Not acceptable
171818 return;
171819 }
171820 if (sniffed_column_counts[row].is_comment) {
171821 comment_rows++;
171822 } else if (sniffed_column_counts[row].last_value_always_empty &&
171823 sniffed_column_counts[row].number_of_columns ==
171824 sniffed_column_counts[header_idx].number_of_columns + 1) {
171825 // we allow for the first row to miss one column IF last_value_always_empty is true
171826 // This is so we can sniff files that have an extra delimiter on the data part.
171827 // e.g., C1|C2\n1|2|\n3|4|
171828 consistent_rows++;
171829 } else if (num_cols < sniffed_column_counts[row].number_of_columns &&
171830 (!options.dialect_options.skip_rows.IsSetByUser() || comment_rows > 0) &&
171831 (!set_columns.IsSet() || options.null_padding) && (!first_valid || (!use_most_frequent_columns))) {
171832 // all rows up to this point will need padding
171833 if (!first_valid) {
171834 first_valid = true;
171835 sniffed_column_counts.state_machine.dialect_options.rows_until_header = row;
171836 }
171837 padding_count = 0;
171838 // we use the maximum number of num_cols that we find
171839 num_cols = sniffed_column_counts[row].number_of_columns;
171840 dirty_notes = row + sniffed_column_counts[row].empty_lines;
171841 empty_lines = sniffed_column_counts[row].empty_lines;
171842 dirty_notes_minus_comments = dirty_notes - comment_rows;
171843 header_idx = row;
171844 consistent_rows = 1;
171845 } else if (sniffed_column_counts[row].number_of_columns == num_cols || (use_most_frequent_columns)) {
171846 if (!first_valid) {
171847 first_valid = true;
171848 sniffed_column_counts.state_machine.dialect_options.rows_until_header = row;
171849 dirty_notes = row + sniffed_column_counts[row].empty_lines;
171850 empty_lines = sniffed_column_counts[row].empty_lines;
171851 dirty_notes_minus_comments = dirty_notes - comment_rows;
171852 num_cols = sniffed_column_counts[row].number_of_columns;
171853 }
171854 if (sniffed_column_counts[row].number_of_columns != num_cols) {
171855 ignored_rows++;
171856 }
171857 consistent_rows++;
171858 } else if (num_cols >= sniffed_column_counts[row].number_of_columns) {
171859 // we are missing some columns, we can parse this as long as we add padding
171860 padding_count++;
171861 }
171862 }
171863
171864 if (sniffed_column_counts.state_machine.options.dialect_options.skip_rows.IsSetByUser()) {
171865 sniffed_column_counts.state_machine.dialect_options.rows_until_header +=
171866 sniffed_column_counts.state_machine.options.dialect_options.skip_rows.GetValue();
171867 }
171868 // Calculate the total number of consistent rows after adding padding.
171869 consistent_rows += padding_count;
171870
171871 // Whether there are more values (rows) available that are consistent, exceeding the current best.
171872 const bool more_values = consistent_rows > stats.best_consistent_rows && num_cols >= max_columns_found;
171873
171874 const bool more_columns = consistent_rows == stats.best_consistent_rows && num_cols > max_columns_found;
171875
171876 // If additional padding is required when compared to the previous padding count.
171877 const bool require_more_padding = padding_count > stats.prev_padding_count;
171878
171879 // If less padding is now required when compared to the previous padding count.
171880 const bool require_less_padding = padding_count < stats.prev_padding_count;
171881
171882 // If there was only a single column before, and the new number of columns exceeds that.
171883 const bool single_column_before =
171884 max_columns_found < 2 && num_cols > max_columns_found * successful_candidates.size();
171885
171886 // If the number of rows is consistent with the calculated value after accounting for skipped rows and the
171887 // start row.
171888 const bool rows_consistent = consistent_rows +
171889 (dirty_notes_minus_comments - options.dialect_options.skip_rows.GetValue()) +
171890 comment_rows - empty_lines ==
171891 sniffed_column_counts.result_position - options.dialect_options.skip_rows.GetValue();
171892 // If there are more than one consistent row.
171893 const bool more_than_one_row = consistent_rows > 1;
171894
171895 // If there are more than one column.
171896 const bool more_than_one_column = num_cols > 1;
171897
171898 // If the start position is valid.
171899 const bool start_good =
171900 !successful_candidates.empty() &&
171901 dirty_notes <= successful_candidates.front()->GetStateMachine().dialect_options.skip_rows.GetValue();
171902
171903 // If padding happened but it is not allowed.
171904 const bool invalid_padding = !allow_padding && padding_count > 0;
171905
171906 const bool comments_are_acceptable = AreCommentsAcceptable(sniffed_column_counts, num_cols, options);
171907
171908 const bool quoted =
171909 scanner->ever_quoted &&
171910 sniffed_column_counts.state_machine.dialect_options.state_machine_options.quote.GetValue() != '\0';
171911
171912 // For our columns to match, we either don't have them manually set, or they match in value with the sniffed value
171913 const bool columns_match_set =
171914 num_cols == set_columns.Size() ||
171915 (num_cols == set_columns.Size() + 1 && sniffed_column_counts[0].last_value_always_empty) ||
171916 !set_columns.IsSet();
171917
171918 max_columns_found_error = num_cols > max_columns_found_error ? num_cols : max_columns_found_error;
171919
171920 // If rows are consistent and no invalid padding happens, this is the best suitable candidate if one of the
171921 // following is valid:
171922 // - There's a single column before.
171923 // - There are more values, and no additional padding is required.
171924 // - There's more than one column and less padding is required.
171925 if (columns_match_set && (rows_consistent || (set_columns.IsSet() && ignore_errors)) &&
171926 (single_column_before || ((more_values || more_columns) && !require_more_padding) ||
171927 (more_than_one_column && require_less_padding) || (quoted && comment_rows == 0)) &&
171928 !invalid_padding && comments_are_acceptable) {
171929 if (!successful_candidates.empty() && set_columns.IsSet() && max_columns_found == set_columns.Size() &&
171930 consistent_rows <= stats.best_consistent_rows) {
171931 // We have a candidate that fits our requirements better
171932 if (successful_candidates.front()->ever_quoted || !scanner->ever_quoted) {
171933 return;
171934 }
171935 }
171936 auto &sniffing_state_machine = scanner->GetStateMachine();
171937
171938 if (!successful_candidates.empty() && successful_candidates.front()->ever_quoted) {
171939 // Give preference to quoted boys.
171940 if (!scanner->ever_quoted) {
171941 return;
171942 } else {
171943 // Give preference to one that got escaped
171944 if (!scanner->ever_escaped && successful_candidates.front()->ever_escaped &&
171945 sniffing_state_machine.dialect_options.state_machine_options.strict_mode.GetValue()) {
171946 return;
171947 }
171948 if (stats.best_consistent_rows == consistent_rows && num_cols >= max_columns_found) {
171949 // If both have not been escaped, this might get solved later on.
171950 sniffing_state_machine.dialect_options.num_cols = num_cols;
171951 if (options.dialect_options.skip_rows.IsSetByUser()) {
171952 // If skip rows are set by the user, and we found dirty notes, we only accept it if either
171953 // null_padding or ignore_errors is set
171954 if (dirty_notes != 0 && !options.null_padding && !options.ignore_errors.GetValue()) {
171955 return;
171956 }
171957 sniffing_state_machine.dialect_options.skip_rows = options.dialect_options.skip_rows.GetValue();
171958 } else if (!options.null_padding) {
171959 sniffing_state_machine.dialect_options.skip_rows = dirty_notes;
171960 }
171961 sniffing_state_machine.dialect_options.num_cols = num_cols;
171962 lines_sniffed = sniffed_column_counts.result_position;
171963 successful_candidates.emplace_back(std::move(scanner));
171964 max_columns_found = num_cols;
171965 return;
171966 }
171967 }
171968 }
171969 if (max_columns_found == num_cols && (ignored_rows > stats.min_ignored_rows)) {
171970 return;
171971 }
171972 if (max_columns_found > 1 && num_cols > max_columns_found && consistent_rows < stats.best_consistent_rows / 2 &&
171973 (options.null_padding || ignore_errors)) {
171974 // When null_padding is true, we only give preference to a max number of columns if null padding is at least
171975 // 50% as consistent as the best case scenario
171976 return;
171977 }
171978 if (quoted && num_cols < max_columns_found) {
171979 if (scanner->ever_escaped &&
171980 sniffing_state_machine.dialect_options.state_machine_options.strict_mode.GetValue()) {
171981 for (auto &candidate : successful_candidates) {
171982 if (candidate->ever_quoted && candidate->ever_escaped) {
171983 return;
171984 }
171985 }
171986
171987 } else {
171988 for (auto &candidate : successful_candidates) {
171989 if (candidate->ever_quoted) {
171990 return;
171991 }
171992 }
171993 }
171994 }
171995 stats.best_consistent_rows = consistent_rows;
171996 max_columns_found = num_cols;
171997 stats.prev_padding_count = padding_count;
171998 stats.min_ignored_rows = ignored_rows;
171999
172000 if (options.dialect_options.skip_rows.IsSetByUser()) {
172001 // If skip rows are set by the user, and we found dirty notes, we only accept it if either null_padding or
172002 // ignore_errors is set we have comments
172003 if (dirty_notes - empty_lines != 0 && !options.null_padding && !options.ignore_errors.GetValue() &&
172004 comment_rows == 0) {
172005 return;
172006 }
172007 sniffing_state_machine.dialect_options.skip_rows = options.dialect_options.skip_rows.GetValue();
172008 } else if (!options.null_padding) {
172009 sniffing_state_machine.dialect_options.skip_rows = dirty_notes_minus_comments;
172010 }
172011 successful_candidates.clear();
172012 sniffing_state_machine.dialect_options.num_cols = num_cols;
172013 lines_sniffed = sniffed_column_counts.result_position;
172014 successful_candidates.emplace_back(std::move(scanner));
172015 return;
172016 }
172017 // If there's more than one row and column, the start is good, rows are consistent,
172018 // no additional padding is required, and there is no invalid padding, and there is not yet a candidate
172019 // with the same quote, we add this state_machine as a suitable candidate.
172020 if (columns_match_set && more_than_one_row && more_than_one_column && start_good && rows_consistent &&
172021 !require_more_padding && !invalid_padding && num_cols == max_columns_found && comments_are_acceptable) {
172022 auto &sniffing_state_machine = scanner->GetStateMachine();
172023
172024 if (options.dialect_options.skip_rows.IsSetByUser()) {
172025 // If skip rows are set by the user, and we found dirty notes, we only accept it if either null_padding or
172026 // ignore_errors is set
172027 if (dirty_notes != 0 && !options.null_padding && !options.ignore_errors.GetValue()) {
172028 return;
172029 }
172030 sniffing_state_machine.dialect_options.skip_rows = options.dialect_options.skip_rows.GetValue();
172031 } else if (!options.null_padding) {
172032 sniffing_state_machine.dialect_options.skip_rows = dirty_notes;
172033 }
172034 sniffing_state_machine.dialect_options.num_cols = num_cols;
172035 lines_sniffed = sniffed_column_counts.result_position;
172036 successful_candidates.emplace_back(std::move(scanner));
172037 }
172038}
Here is the caller graph for this function:

◆ RefineCandidates()

void duckdb::CSVSniffer::RefineCandidates ( )
private
  1. Refine Candidates over remaining chunks
172056 {
172057 // It's very frequent that more than one dialect can parse a csv file; hence here we run one state machine
172058 // fully on the whole sample dataset, when/if it fails, we go to the next one.
172059 if (candidates.empty()) {
172060 // No candidates to refine
172061 return;
172062 }
172063 if (candidates.size() == 1 || candidates[0]->FinishedFile()) {
172064 // Only one candidate nothing to refine, or all candidates already checked
172065 return;
172066 }
172067
172068 for (idx_t i = 1; i <= options.sample_size_chunks; i++) {
172069 vector<unique_ptr<ColumnCountScanner>> successful_candidates;
172070 bool done = candidates.empty();
172071 for (auto &cur_candidate : candidates) {
172072 const bool finished_file = cur_candidate->FinishedFile();
172073 if (successful_candidates.empty()) {
172074 lines_sniffed += cur_candidate->GetResult().result_position;
172075 }
172076 if (finished_file || i == options.sample_size_chunks) {
172077 // we finished the file or our chunk sample successfully
172078 if (!cur_candidate->GetResult().error) {
172079 successful_candidates.push_back(std::move(cur_candidate));
172080 }
172081 done = true;
172082 continue;
172083 }
172084 if (RefineCandidateNextChunk(*cur_candidate) && !cur_candidate->GetResult().error) {
172085 successful_candidates.push_back(std::move(cur_candidate));
172086 }
172087 }
172088 candidates = std::move(successful_candidates);
172089 if (done) {
172090 break;
172091 }
172092 }
172093 // If we have multiple candidates with quotes set, we will give the preference to ones
172094 // that have actually quoted values, otherwise we will choose quotes = \0
172095 vector<unique_ptr<ColumnCountScanner>> successful_candidates = std::move(candidates);
172096 if (!successful_candidates.empty()) {
172097 bool ever_quoted = false;
172098 for (idx_t i = 0; i < successful_candidates.size(); i++) {
172099 unique_ptr<ColumnCountScanner> cc_best_candidate = std::move(successful_candidates[i]);
172100 if (cc_best_candidate->ever_quoted) {
172101 if (cc_best_candidate->ever_escaped) {
172102 // It can't be better than this
172103 candidates.clear();
172104 candidates.push_back(std::move(cc_best_candidate));
172105 return;
172106 }
172107 if (!ever_quoted) {
172108 ever_quoted = true;
172109 candidates.clear();
172110 }
172111 candidates.push_back(std::move(cc_best_candidate));
172112 } else if (!ever_quoted) {
172113 candidates.push_back(std::move(cc_best_candidate));
172114 }
172115 }
172116 }
172117 if (candidates.size() > 1) {
172118 successful_candidates = std::move(candidates);
172119 for (idx_t i = 0; i < successful_candidates.size(); i++) {
172120 if (successful_candidates[i]->state_machine->state_machine_options.quote ==
172121 successful_candidates[i]->state_machine->state_machine_options.escape) {
172122 candidates.push_back(std::move(std::move(successful_candidates[i])));
172123 return;
172124 }
172125 }
172126 candidates.push_back(std::move(std::move(successful_candidates[0])));
172127 }
172128}
bool RefineCandidateNextChunk(ColumnCountScanner &candidate) const
Checks if candidate still produces good values for the next chunk.
Definition duckdb.cpp:172040
Here is the call graph for this function:
Here is the caller graph for this function:

◆ RefineCandidateNextChunk()

bool duckdb::CSVSniffer::RefineCandidateNextChunk ( ColumnCountScanner & candidate) const
private

Checks if candidate still produces good values for the next chunk.

172040 {
172041 auto &sniffed_column_counts = candidate.ParseChunk();
172042 for (idx_t i = 0; i < sniffed_column_counts.result_position; i++) {
172043 if (set_columns.IsSet()) {
172044 return !set_columns.IsCandidateUnacceptable(sniffed_column_counts[i].number_of_columns,
172045 options.null_padding, options.ignore_errors.GetValue(),
172046 sniffed_column_counts[i].last_value_always_empty);
172047 }
172048 if (max_columns_found != sniffed_column_counts[i].number_of_columns &&
172049 (!options.null_padding && !options.ignore_errors.GetValue() && !sniffed_column_counts[i].is_comment)) {
172050 return false;
172051 }
172052 }
172053 return true;
172054}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ DetectTypes()

void duckdb::CSVSniffer::DetectTypes ( )
private

---------------------------------------------------—// ----------------— Type Detection ---------------— // ---------------------------------------------------—// Second phase of auto-detection: detect types, format template candidates ordered by descending specificity (~ from high to low)

173779 {
173780 idx_t min_varchar_cols = max_columns_found + 1;
173781 idx_t min_errors = NumericLimits<idx_t>::Maximum();
173782 vector<LogicalType> return_types;
173783 // check which info candidate leads to the minimum number of non-varchar columns...
173784 for (auto &candidate_cc : candidates) {
173785 auto &sniffing_state_machine = candidate_cc->GetStateMachine();
173786 unordered_map<idx_t, vector<LogicalType>> info_sql_types_candidates;
173787 for (idx_t i = 0; i < max_columns_found; i++) {
173788 info_sql_types_candidates[i] = sniffing_state_machine.options.auto_type_candidates;
173789 }
173790 D_ASSERT(max_columns_found > 0);
173791
173792 // Set all return_types to VARCHAR, so we can do datatype detection based on VARCHAR values
173793 return_types.clear();
173794 return_types.assign(max_columns_found, LogicalType::VARCHAR);
173795
173796 // Reset candidate for parsing
173797 auto candidate = candidate_cc->UpgradeToStringValueScanner();
173798 SetUserDefinedDateTimeFormat(*candidate->state_machine);
173799 // Parse chunk and read csv with info-candidate
173800 auto &data_chunk = candidate->ParseChunk().ToChunk();
173801 if (candidate->error_handler->AnyErrors() && !candidate->error_handler->HasError(MAXIMUM_LINE_SIZE) &&
173802 !candidate->state_machine->options.ignore_errors.GetValue()) {
173803 continue;
173804 }
173805 idx_t start_idx_detection = 0;
173806 idx_t chunk_size = data_chunk.size();
173807 if (chunk_size > 1 &&
173808 (!options.dialect_options.header.IsSetByUser() ||
173809 (options.dialect_options.header.IsSetByUser() && options.dialect_options.header.GetValue()))) {
173810 // This means we have more than one row, hence we can use the first row to detect if we have a header
173811 start_idx_detection = 1;
173812 }
173813 // First line where we start our type detection
173814 SniffTypes(data_chunk, sniffing_state_machine, info_sql_types_candidates, start_idx_detection);
173815
173816 // Count the number of varchar columns
173817 idx_t varchar_cols = 0;
173818 for (idx_t col = 0; col < info_sql_types_candidates.size(); col++) {
173819 auto &col_type_candidates = info_sql_types_candidates[col];
173820 // check the number of varchar columns
173821 const auto &col_type = col_type_candidates.back();
173822 if (col_type == LogicalType::VARCHAR) {
173823 varchar_cols++;
173824 }
173825 }
173826
173827 // it's good if the dialect creates more non-varchar columns
173828 const bool has_less_varchar_cols = varchar_cols < min_varchar_cols;
173829 // but only if we sacrifice < 30% of best_num_cols.
173830 const bool acceptable_best_num_cols =
173831 static_cast<double>(info_sql_types_candidates.size()) > static_cast<double>(max_columns_found) * 0.7;
173832 const idx_t number_of_errors = candidate->error_handler->GetSize();
173833 const bool better_strictness = best_candidate_is_strict ? !candidate->used_unstrictness : true;
173834 const bool acceptable_candidate = has_less_varchar_cols && acceptable_best_num_cols && better_strictness;
173835 // If we escaped an unquoted character when strict is false.
173836 if (!best_candidate ||
173837 (acceptable_candidate && (!options.ignore_errors.GetValue() || number_of_errors < min_errors))) {
173838 min_errors = number_of_errors;
173839 best_header_row.clear();
173840 // we have a new best_options candidate
173841 best_candidate = std::move(candidate);
173842 min_varchar_cols = varchar_cols;
173843 best_candidate_is_strict = !best_candidate->used_unstrictness;
173844 best_sql_types_candidates_per_column_idx = info_sql_types_candidates;
173845 for (auto &format_candidate : format_candidates) {
173846 best_format_candidates[format_candidate.first] = format_candidate.second.format;
173847 }
173848 if (chunk_size > 0) {
173849 single_row_file = chunk_size == 1;
173850 for (idx_t col_idx = 0; col_idx < data_chunk.ColumnCount(); col_idx++) {
173851 auto &cur_vector = data_chunk.data[col_idx];
173852 auto vector_data = FlatVector::GetData<string_t>(cur_vector);
173853 auto null_mask = FlatVector::Validity(cur_vector);
173854 if (null_mask.RowIsValid(0)) {
173855 auto value = HeaderValue(vector_data[0]);
173856 best_header_row.push_back(value);
173857 } else {
173858 best_header_row.push_back({});
173859 }
173860 }
173861 }
173862 }
173863 }
173864 if (!best_candidate) {
173865 DialectCandidates dialect_candidates(options.dialect_options.state_machine_options);
173866 auto error = CSVError::SniffingError(options, dialect_candidates.Print(), max_columns_found, set_columns, true);
173867 error_handler->Error(error, true);
173868 }
173869 // Assert that it's all good at this point.
173870 D_ASSERT(best_candidate && !best_format_candidates.empty());
173871}
map< LogicalTypeId, DateTimestampSniffing > format_candidates
Variable used for sniffing date and timestamp.
Definition duckdb.cpp:168242
void SetUserDefinedDateTimeFormat(CSVStateMachine &candidate) const
Sets user defined date and time formats (if any).
Definition duckdb.cpp:173770
Here is the call graph for this function:
Here is the caller graph for this function:

◆ SetDateFormat()

void duckdb::CSVSniffer::SetDateFormat ( CSVStateMachine & candidate,
const string & format_specifier,
const LogicalTypeId & sql_type )
staticprivate

Change the date format for the type to the string Try to cast a string value to the specified sql type

173447 {
173448 StrpTimeFormat strpformat;
173449 StrTimeFormat::ParseFormatSpecifier(format_specifier, strpformat);
173450 candidate.dialect_options.date_format[sql_type].Set(strpformat, false);
173451}
Here is the caller graph for this function:

◆ InitializeDateAndTimeStampDetection()

void duckdb::CSVSniffer::InitializeDateAndTimeStampDetection ( CSVStateMachine & candidate,
const string & separator,
const LogicalType & sql_type )
private

Function that initialized the necessary variables used for date and timestamp detection.

173623 {
173624 auto &format_candidate = format_candidates[sql_type.id()];
173625 if (!format_candidate.initialized) {
173626 format_candidate.initialized = true;
173627 // if user set a format, we add that as well
173628 auto user_format = options.dialect_options.date_format.find(sql_type.id());
173629 if (user_format->second.IsSetByUser()) {
173630 format_candidate.format.emplace_back(user_format->second.GetValue().format_specifier);
173631 } else {
173632 auto entry = format_template_candidates.find(sql_type.id());
173633 if (entry != format_template_candidates.end()) {
173634 const auto &format_template_list = entry->second;
173635 for (const auto &t : format_template_list) {
173636 const auto format_string = GenerateDateFormat(separator, t);
173637 // don't parse ISO 8601
173638 if (format_string.find("%Y-%m-%d") == string::npos) {
173639 format_candidate.format.emplace_back(format_string);
173640 }
173641 }
173642 }
173643 }
173644 // order by preference
173645 original_format_candidates = format_candidates;
173646 }
173647 // initialise the first candidate
173648 // all formats are constructed to be valid
173649 SetDateFormat(candidate, format_candidate.format.back(), sql_type.id());
173650}
static void SetDateFormat(CSVStateMachine &candidate, const string &format_specifier, const LogicalTypeId &sql_type)
Definition duckdb.cpp:173446
Here is the call graph for this function:
Here is the caller graph for this function:

◆ SetUserDefinedDateTimeFormat()

void duckdb::CSVSniffer::SetUserDefinedDateTimeFormat ( CSVStateMachine & candidate) const
private

Sets user defined date and time formats (if any).

173770 {
173771 const vector<LogicalTypeId> data_time_formats {LogicalTypeId::DATE, LogicalTypeId::TIMESTAMP};
173772 for (auto &date_time_format : data_time_formats) {
173773 auto &user_option = options.dialect_options.date_format.at(date_time_format);
173774 if (user_option.IsSetByUser()) {
173775 SetDateFormat(candidate, user_option.GetValue().format_specifier, date_time_format);
173776 }
173777 }
173778}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ DetectDateAndTimeStampFormats()

void duckdb::CSVSniffer::DetectDateAndTimeStampFormats ( CSVStateMachine & candidate,
const LogicalType & sql_type,
const string & separator,
const string_t & dummy_val )
private

Functions that performs detection for date and timestamp formats.

173657 {
173658 if (!ValidSeparator(separator)) {
173659 return;
173660 }
173661 // If it is the first time running date/timestamp detection we must initialize the format variables
173662 InitializeDateAndTimeStampDetection(candidate, separator, sql_type);
173663 // generate date format candidates the first time through
173664 auto &type_format_candidates = format_candidates[sql_type.id()].format;
173665 // check all formats and keep the first one that works
173666 StrpTimeFormat::ParseResult result;
173667 auto save_format_candidates = type_format_candidates;
173668 const bool had_format_candidates = !save_format_candidates.empty();
173669 const bool initial_format_candidates =
173670 save_format_candidates.size() == original_format_candidates.at(sql_type.id()).format.size();
173671 const bool is_set_by_user = options.dialect_options.date_format.find(sql_type.id())->second.IsSetByUser();
173672 while (!type_format_candidates.empty() && !is_set_by_user) {
173673 // avoid using exceptions for flow control...
173674 auto &current_format = candidate.dialect_options.date_format[sql_type.id()].GetValue();
173675 if (current_format.Parse(dummy_val, result, true)) {
173676 format_candidates[sql_type.id()].had_match = true;
173677 break;
173678 }
173679 // doesn't work - move to the next one
173680 type_format_candidates.pop_back();
173681 if (!type_format_candidates.empty()) {
173682 SetDateFormat(candidate, type_format_candidates.back(), sql_type.id());
173683 }
173684 }
173685 // if none match, then this is not a value of type sql_type,
173686 if (type_format_candidates.empty()) {
173687 // so restore the candidates that did work.
173688 // or throw them out if they were generated by this value.
173689 if (had_format_candidates) {
173690 if (initial_format_candidates && !format_candidates[sql_type.id()].had_match) {
173691 // we reset the whole thing because we tried to sniff the wrong type.
173692 format_candidates[sql_type.id()].initialized = false;
173693 format_candidates[sql_type.id()].format.clear();
173694 SetDateFormat(candidate, "", sql_type.id());
173695 return;
173696 }
173697 type_format_candidates.swap(save_format_candidates);
173698 SetDateFormat(candidate, type_format_candidates.back(), sql_type.id());
173699 }
173700 }
173701}
void InitializeDateAndTimeStampDetection(CSVStateMachine &candidate, const string &separator, const LogicalType &sql_type)
Function that initialized the necessary variables used for date and timestamp detection.
Definition duckdb.cpp:173622
Here is the call graph for this function:
Here is the caller graph for this function:

◆ SniffTypes()

void duckdb::CSVSniffer::SniffTypes ( DataChunk & data_chunk,
CSVStateMachine & state_machine,
unordered_map< idx_t, vector< LogicalType > > & info_sql_types_candidates,
idx_t start_idx_detection )
private

Sniffs the types from a data chunk.

173705 {
173706 const idx_t chunk_size = data_chunk.size();
173707 HasType has_type;
173708 for (idx_t col_idx = 0; col_idx < data_chunk.ColumnCount(); col_idx++) {
173709 auto &cur_vector = data_chunk.data[col_idx];
173710 D_ASSERT(cur_vector.GetVectorType() == VectorType::FLAT_VECTOR);
173711 D_ASSERT(cur_vector.GetType() == LogicalType::VARCHAR);
173712 auto vector_data = FlatVector::GetData<string_t>(cur_vector);
173713 auto null_mask = FlatVector::Validity(cur_vector);
173714 auto &col_type_candidates = info_sql_types_candidates[col_idx];
173715 for (idx_t row_idx = start_idx_detection; row_idx < chunk_size; row_idx++) {
173716 // col_type_candidates can't be empty since anything in a CSV file should at least be a string
173717 // and we validate utf-8 compatibility when creating the type
173718 D_ASSERT(!col_type_candidates.empty());
173719 auto cur_top_candidate = col_type_candidates.back();
173720 // try cast from string to sql_type
173721 while (col_type_candidates.size() > 1) {
173722 const auto &sql_type = col_type_candidates.back();
173723 // try formatting for date types if the user did not specify one, and it starts with numeric
173724 // values.
173725 string separator;
173726 // If Value is not Null, Has a numeric date format, and the current investigated candidate is
173727 // either a timestamp or a date
173728 if (null_mask.RowIsValid(row_idx) && StartsWithNumericDate(separator, vector_data[row_idx]) &&
173729 ((col_type_candidates.back().id() == LogicalTypeId::TIMESTAMP && !has_type.timestamp) ||
173730 (col_type_candidates.back().id() == LogicalTypeId::DATE && !has_type.date))) {
173731 DetectDateAndTimeStampFormats(state_machine, sql_type, separator, vector_data[row_idx]);
173732 }
173733 // try cast from string to sql_type
173734 if (sql_type == LogicalType::VARCHAR) {
173735 // Nothing to convert it to
173736 continue;
173737 }
173738 if (CanYouCastIt(buffer_manager->context, vector_data[row_idx], sql_type, state_machine.dialect_options,
173739 !null_mask.RowIsValid(row_idx), state_machine.options.decimal_separator[0],
173740 state_machine.options.thousands_separator)) {
173741 break;
173742 }
173743 D_ASSERT(cur_top_candidate.id() == LogicalTypeId::VARCHAR || col_type_candidates.size() > 1);
173744 if (row_idx != start_idx_detection &&
173745 (cur_top_candidate == LogicalType::BOOLEAN || cur_top_candidate == LogicalType::DATE ||
173746 cur_top_candidate == LogicalType::TIME ||
173747 (cur_top_candidate == LogicalType::TIMESTAMP &&
173748 col_type_candidates[col_type_candidates.size() - 2] != LogicalType::TIMESTAMP_TZ) ||
173749 cur_top_candidate == LogicalType::TIMESTAMP_TZ)) {
173750 // If we thought this was a boolean value (i.e., T,F, True, False) and it is not, we
173751 // immediately pop to varchar.
173752 while (col_type_candidates.back() != LogicalType::VARCHAR) {
173753 col_type_candidates.pop_back();
173754 }
173755 break;
173756 }
173757 col_type_candidates.pop_back();
173758 }
173759 }
173760 if (col_type_candidates.back().id() == LogicalTypeId::DATE) {
173761 has_type.date = true;
173762 }
173763 if (col_type_candidates.back().id() == LogicalTypeId::TIMESTAMP) {
173764 has_type.timestamp = true;
173765 }
173766 }
173767}
void DetectDateAndTimeStampFormats(CSVStateMachine &candidate, const LogicalType &sql_type, const string &separator, const string_t &dummy_val)
Functions that performs detection for date and timestamp formats.
Definition duckdb.cpp:173656
static bool CanYouCastIt(ClientContext &context, const string_t value, const LogicalType &type, const DialectOptions &dialect_options, const bool is_null, const char decimal_separator, const char thousands_separator)
If a string_t value can be cast to a type.
Definition duckdb.cpp:173461
vector< Vector > data
The vectors owned by the DataChunk.
Definition duckdb.hpp:11445
Here is the call graph for this function:
Here is the caller graph for this function:

◆ RefineTypes()

void duckdb::CSVSniffer::RefineTypes ( )
private

---------------------------------------------------—// ---------------— Type Refinement ---------------— // ---------------------------------------------------—//

173919 {
173920 auto &sniffing_state_machine = best_candidate->GetStateMachine();
173921 // if data types were provided, exit here if the number of columns does not match
173922 detected_types.assign(sniffing_state_machine.dialect_options.num_cols, LogicalType::VARCHAR);
173923 if (sniffing_state_machine.options.all_varchar) {
173924 // return all types varchar
173925 return;
173926 }
173927 for (idx_t i = 1; i < sniffing_state_machine.options.sample_size_chunks; i++) {
173928 bool finished_file = best_candidate->FinishedFile();
173929 if (finished_file) {
173930 // we finished the file: stop
173931 // set sql types
173932 detected_types.clear();
173933 for (idx_t column_idx = 0; column_idx < best_sql_types_candidates_per_column_idx.size(); column_idx++) {
173934 LogicalType d_type = best_sql_types_candidates_per_column_idx[column_idx].back();
173935 detected_types.push_back(d_type);
173936 }
173937 return;
173938 }
173939 auto &parse_chunk = best_candidate->ParseChunk().ToChunk();
173940
173941 for (idx_t col = 0; col < parse_chunk.ColumnCount(); col++) {
173942 vector<LogicalType> &col_type_candidates = best_sql_types_candidates_per_column_idx[col];
173943 bool is_bool_type = col_type_candidates.back() == LogicalType::BOOLEAN;
173944 while (col_type_candidates.size() > 1) {
173945 const auto &sql_type = col_type_candidates.back();
173946 if (TryCastVector(parse_chunk.data[col], parse_chunk.size(), sql_type)) {
173947 break;
173948 }
173949 if (col_type_candidates.back() == LogicalType::BOOLEAN && is_bool_type) {
173950 // If we thought this was a boolean value (i.e., T,F, True, False) and it is not, we
173951 // immediately pop to varchar.
173952 while (col_type_candidates.back() != LogicalType::VARCHAR) {
173953 col_type_candidates.pop_back();
173954 }
173955 break;
173956 }
173957 col_type_candidates.pop_back();
173958 }
173959 }
173960 // reset parse chunk for the next iteration
173961 parse_chunk.Reset();
173962 parse_chunk.SetCapacity(CSVReaderOptions::sniff_size);
173963 }
173964 detected_types.clear();
173965 // set sql types
173966 for (idx_t column_idx = 0; column_idx < best_sql_types_candidates_per_column_idx.size(); column_idx++) {
173967 LogicalType d_type = best_sql_types_candidates_per_column_idx[column_idx].back();
173968 if (best_sql_types_candidates_per_column_idx[column_idx].size() ==
173969 best_candidate->GetStateMachine().options.auto_type_candidates.size() &&
173970 default_null_to_varchar && !best_candidate->FinishedFile()) {
173971 // We only default SQLNull to Varchar if we haven't finished the file yet.
173972 d_type = LogicalType::VARCHAR;
173973 }
173974 detected_types.push_back(d_type);
173975 }
173976}
Here is the caller graph for this function:

◆ TryCastVector()

bool duckdb::CSVSniffer::TryCastVector ( Vector & parse_chunk_col,
idx_t size,
const LogicalType & sql_type ) const
private
173878 {
173879 auto &sniffing_state_machine = best_candidate->GetStateMachine();
173880 // try vector-cast from string to sql_type
173881 Vector dummy_result(sql_type, size);
173882 if (!sniffing_state_machine.dialect_options.date_format[LogicalTypeId::DATE].GetValue().Empty() &&
173883 sql_type.id() == LogicalTypeId::DATE) {
173884 // use the date format to cast the chunk
173885 string error_message;
173886 CastParameters parameters(false, &error_message);
173887 idx_t line_error;
173888 return CSVCast::TryCastDateVector(sniffing_state_machine.dialect_options.date_format, parse_chunk_col,
173889 dummy_result, size, parameters, line_error);
173890 }
173891 if (!sniffing_state_machine.dialect_options.date_format[LogicalTypeId::TIMESTAMP].GetValue().Empty() &&
173892 sql_type.id() == LogicalTypeId::TIMESTAMP) {
173893 // use the timestamp format to cast the chunk
173894 string error_message;
173895 CastParameters parameters(false, &error_message);
173896 return CSVCast::TryCastTimestampVector(sniffing_state_machine.dialect_options.date_format, parse_chunk_col,
173897 dummy_result, size, parameters);
173898 }
173899 if ((sql_type.id() == LogicalTypeId::DOUBLE || sql_type.id() == LogicalTypeId::FLOAT) &&
173900 options.decimal_separator == ",") {
173901 string error_message;
173902 CastParameters parameters(false, &error_message);
173903 idx_t line_error;
173904 return CSVCast::TryCastFloatingVectorCommaSeparated(options, parse_chunk_col, dummy_result, size, parameters,
173905 sql_type, line_error);
173906 }
173907 if (sql_type.id() == LogicalTypeId::DECIMAL && options.decimal_separator == ",") {
173908 string error_message;
173909 CastParameters parameters(false, &error_message);
173910 idx_t line_error;
173911 return CSVCast::TryCastDecimalVectorCommaSeparated(options, parse_chunk_col, dummy_result, size, parameters,
173912 sql_type, line_error);
173913 }
173914 // target type is not varchar: perform a cast
173915 string error_message;
173916 return VectorOperations::DefaultTryCast(parse_chunk_col, dummy_result, size, &error_message, true);
173917}

◆ DetectHeader()

void duckdb::CSVSniffer::DetectHeader ( )
private

---------------------------------------------------—// ---------------— Header Detection --------------— // ---------------------------------------------------—//

173271 {
173272 auto &sniffer_state_machine = best_candidate->GetStateMachine();
173273 names = DetectHeaderInternal(buffer_manager->context, best_header_row, sniffer_state_machine, set_columns,
173274 best_sql_types_candidates_per_column_idx, options, file_options, *error_handler);
173275 if (EmptyOrOnlyHeader()) {
173276 // This file only contains a header, lets default to the lowest type of all.
173277 detected_types.clear();
173278 for (idx_t i = 0; i < names.size(); i++) {
173279 detected_types.push_back(LogicalType::SQLNULL);
173280 }
173281 }
173282 for (idx_t i = detected_types.size(); i < names.size(); i++) {
173283 detected_types.push_back(LogicalType::VARCHAR);
173284 }
173285 max_columns_found = names.size();
173286}
Here is the caller graph for this function:

◆ DetectHeaderWithSetColumn()

bool duckdb::CSVSniffer::DetectHeaderWithSetColumn ( ClientContext & context,
vector< HeaderValue > & best_header_row,
const SetColumns & set_columns,
CSVReaderOptions & options )
staticprivate
173075 {
173076 bool has_header = true;
173077
173078 std::ostringstream error;
173079 // User set the names, we must check if they match the first row
173080 // We do a +1 to check for situations where the csv file has an extra all null column
173081 if (set_columns.Size() != best_header_row.size() && set_columns.Size() + 1 != best_header_row.size()) {
173082 return false;
173083 }
173084
173085 // Let's do a match-aroo
173086 for (idx_t i = 0; i < set_columns.Size(); i++) {
173087 if (best_header_row[i].IsNull()) {
173088 return false;
173089 }
173090 if (best_header_row[i].value != (*set_columns.names)[i]) {
173091 error << "Header mismatch at position: " << i << "\n";
173092 error << "Expected name: \"" << (*set_columns.names)[i] << "\", ";
173093 error << "Actual name: \"" << best_header_row[i].value << "\"."
173094 << "\n";
173095 has_header = false;
173096 break;
173097 }
173098 }
173099
173100 if (!has_header) {
173101 bool all_varchar = true;
173102 bool first_row_consistent = true;
173103 // We verify if the types are consistent
173104 for (idx_t col = 0; col < set_columns.Size(); col++) {
173105 // try cast to sql_type of column
173106 const auto &sql_type = (*set_columns.types)[col];
173107 if (sql_type != LogicalType::VARCHAR) {
173108 all_varchar = false;
173109 if (!CSVSniffer::CanYouCastIt(context, best_header_row[col].value, sql_type, options.dialect_options,
173110 best_header_row[col].IsNull(), options.decimal_separator[0],
173111 options.thousands_separator)) {
173112 first_row_consistent = false;
173113 }
173114 }
173115 }
173116 if (!first_row_consistent) {
173117 options.sniffer_user_mismatch_error += error.str();
173118 }
173119 if (all_varchar) {
173120 return true;
173121 }
173122 return !first_row_consistent;
173123 }
173124 return has_header;
173125}

◆ DetectHeaderInternal()

vector< string > duckdb::CSVSniffer::DetectHeaderInternal ( ClientContext & context,
vector< HeaderValue > & best_header_row,
CSVStateMachine & state_machine,
const SetColumns & set_columns,
unordered_map< idx_t, vector< LogicalType > > & best_sql_types_candidates_per_column_idx,
CSVReaderOptions & options,
const MultiFileOptions & file_options,
CSVErrorHandler & error_handler )
staticprivate
173148 {
173149 vector<string> detected_names;
173150 auto &dialect_options = state_machine.dialect_options;
173151 dialect_options.num_cols = best_sql_types_candidates_per_column_idx.size();
173152 if (best_header_row.empty()) {
173153 dialect_options.header = false;
173154 for (idx_t col = 0; col < dialect_options.num_cols; col++) {
173155 detected_names.push_back(GenerateColumnName(dialect_options.num_cols, col));
173156 }
173157 // If the user provided names, we must replace our header with the user provided names
173158 ReplaceNames(detected_names, state_machine, best_sql_types_candidates_per_column_idx, options, file_options,
173159 best_header_row, error_handler);
173160 return detected_names;
173161 }
173162 // information for header detection
173163 // check if header row is all null and/or consistent with detected column data types
173164 // If null-padding is not allowed and there is a mismatch between our header candidate and the number of columns
173165 // We can't detect the dialect/type options properly
173166 if (!options.null_padding && best_sql_types_candidates_per_column_idx.size() != best_header_row.size()) {
173167 if (options.ignore_errors.GetValue()) {
173168 dialect_options.header = false;
173169 for (idx_t col = 0; col < dialect_options.num_cols; col++) {
173170 detected_names.push_back(GenerateColumnName(dialect_options.num_cols, col));
173171 }
173172 dialect_options.rows_until_header += 1;
173173 ReplaceNames(detected_names, state_machine, best_sql_types_candidates_per_column_idx, options, file_options,
173174 best_header_row, error_handler);
173175 return detected_names;
173176 }
173177 auto error =
173178 CSVError::HeaderSniffingError(options, best_header_row, best_sql_types_candidates_per_column_idx.size(),
173179 state_machine.dialect_options.state_machine_options.delimiter.GetValue());
173180 error_handler.Error(error);
173181 }
173182 bool has_header;
173183
173184 if (set_columns.IsSet()) {
173185 has_header = DetectHeaderWithSetColumn(context, best_header_row, set_columns, options);
173186 } else {
173187 bool first_row_consistent = true;
173188 bool all_varchar = true;
173189 bool first_row_nulls = true;
173190 for (idx_t col = 0; col < best_header_row.size(); col++) {
173191 if (!best_header_row[col].IsNull()) {
173192 first_row_nulls = false;
173193 }
173194 // try cast to sql_type of column
173195 const auto &sql_type = best_sql_types_candidates_per_column_idx[col].back();
173196 if (sql_type != LogicalType::VARCHAR) {
173197 all_varchar = false;
173198 if (!CanYouCastIt(context, best_header_row[col].value, sql_type, dialect_options,
173199 best_header_row[col].IsNull(), options.decimal_separator[0],
173200 options.thousands_separator)) {
173201 first_row_consistent = false;
173202 }
173203 }
173204 }
173205 // Our header is only false if types are not all varchar, and rows are consistent
173206 if (all_varchar || first_row_nulls) {
173207 has_header = true;
173208 } else {
173209 has_header = !first_row_consistent;
173210 }
173211 }
173212
173213 if (options.dialect_options.header.IsSetByUser()) {
173214 // Header is defined by user, use that.
173215 has_header = options.dialect_options.header.GetValue();
173216 }
173217 // update parser info, and read, generate & set col_names based on previous findings
173218 if (has_header) {
173219 dialect_options.header = true;
173220 if (options.null_padding && !options.dialect_options.skip_rows.IsSetByUser()) {
173221 if (dialect_options.skip_rows.GetValue() > 0) {
173222 dialect_options.skip_rows = dialect_options.skip_rows.GetValue() - 1;
173223 }
173224 }
173225 case_insensitive_map_t<idx_t> name_collision_count;
173226
173227 // get header names from CSV
173228 for (idx_t col = 0; col < best_header_row.size(); col++) {
173229 string &col_name = best_header_row[col].value;
173230
173231 // generate name if field is empty
173232 if (EmptyHeader(col_name, best_header_row[col].is_null, options.normalize_names)) {
173233 col_name = GenerateColumnName(dialect_options.num_cols, col);
173234 }
173235
173236 // normalize names or at least trim whitespace
173237 if (options.normalize_names) {
173238 col_name = NormalizeColumnName(col_name);
173239 } else {
173240 col_name = TrimWhitespace(col_name);
173241 }
173242
173243 // avoid duplicate header names
173244 while (name_collision_count.find(col_name) != name_collision_count.end()) {
173245 name_collision_count[col_name] += 1;
173246 col_name = col_name + "_" + to_string(name_collision_count[col_name]);
173247 }
173248 detected_names.push_back(col_name);
173249 name_collision_count[col_name] = 0;
173250 }
173251 if (best_header_row.size() < dialect_options.num_cols && options.null_padding) {
173252 for (idx_t col = best_header_row.size(); col < dialect_options.num_cols; col++) {
173253 detected_names.push_back(GenerateColumnName(dialect_options.num_cols, col));
173254 }
173255 } else if (best_header_row.size() < dialect_options.num_cols) {
173256 throw InternalException("Detected header has number of columns inferior to dialect detection");
173257 }
173258
173259 } else {
173260 dialect_options.header = false;
173261 for (idx_t col = 0; col < dialect_options.num_cols; col++) {
173262 detected_names.push_back(GenerateColumnName(dialect_options.num_cols, col));
173263 }
173264 }
173265
173266 // If the user provided names, we must replace our header with the user provided names
173267 ReplaceNames(detected_names, state_machine, best_sql_types_candidates_per_column_idx, options, file_options,
173268 best_header_row, error_handler);
173269 return detected_names;
173270}
static CSVError HeaderSniffingError(const CSVReaderOptions &options, const vector< HeaderValue > &best_header_row, idx_t column_count, const string &delimiter)
Produces an error message for a header sniffing error.
Definition duckdb.cpp:175919

◆ ReplaceTypes()

void duckdb::CSVSniffer::ReplaceTypes ( )
private

---------------------------------------------------—// ---------------— Type Replacement --------------— // ---------------------------------------------------—//

173981 {
173982 auto &sniffing_state_machine = best_candidate->GetStateMachine();
173983 manually_set = vector<bool>(detected_types.size(), false);
173984 if (sniffing_state_machine.options.sql_type_list.empty() || sniffing_state_machine.options.columns_set) {
173985 return;
173986 }
173987 // user-defined types were supplied for certain columns
173988 // override the types
173989 if (!sniffing_state_machine.options.sql_types_per_column.empty()) {
173990 // types supplied as name -> value map
173991 idx_t found = 0;
173992 for (idx_t i = 0; i < names.size(); i++) {
173993 auto it = sniffing_state_machine.options.sql_types_per_column.find(names[i]);
173994 if (it != sniffing_state_machine.options.sql_types_per_column.end()) {
173995 best_sql_types_candidates_per_column_idx[i] = {
173996 sniffing_state_machine.options.sql_type_list[it->second]};
173997 detected_types[i] = sniffing_state_machine.options.sql_type_list[it->second];
173998 manually_set[i] = true;
173999 found++;
174000 }
174001 }
174002 if (!file_options.union_by_name && found < sniffing_state_machine.options.sql_types_per_column.size()) {
174003 auto error_msg = CSVError::ColumnTypesError(options.sql_types_per_column, names);
174004 error_handler->Error(error_msg);
174005 }
174006 return;
174007 }
174008 // types supplied as list
174009 if (names.size() < sniffing_state_machine.options.sql_type_list.size()) {
174010 throw BinderException("read_csv: %d types were provided, but CSV file only has %d columns",
174011 sniffing_state_machine.options.sql_type_list.size(), names.size());
174012 }
174013 for (idx_t i = 0; i < sniffing_state_machine.options.sql_type_list.size(); i++) {
174014 detected_types[i] = sniffing_state_machine.options.sql_type_list[i];
174015 manually_set[i] = true;
174016 }
174017}
static CSVError ColumnTypesError(case_insensitive_map_t< idx_t > sql_types_per_column, const vector< string > &names)
Produces error messages for column name -> type mismatch.
Definition duckdb.cpp:175834
Here is the call graph for this function:
Here is the caller graph for this function:

Member Data Documentation

◆ format_template_candidates

const map<LogicalTypeId, vector<const char *> > duckdb::CSVSniffer::format_template_candidates
private
Initial value:
= {
{LogicalTypeId::DATE, {"%m-%d-%Y", "%m-%d-%y", "%d-%m-%Y", "%d-%m-%y", "%Y-%m-%d", "%y-%m-%d"}},
{LogicalTypeId::TIMESTAMP,
{"%Y-%m-%d %H:%M:%S.%f", "%m-%d-%Y %I:%M:%S %p", "%m-%d-%y %I:%M:%S %p", "%d-%m-%Y %H:%M:%S",
"%d-%m-%y %H:%M:%S", "%Y-%m-%d %H:%M:%S", "%y-%m-%d %H:%M:%S"}},
}

Variables for Type Detection Format Candidates for Date and Timestamp Types

168231 {
168232 {LogicalTypeId::DATE, {"%m-%d-%Y", "%m-%d-%y", "%d-%m-%Y", "%d-%m-%y", "%Y-%m-%d", "%y-%m-%d"}},
168233 {LogicalTypeId::TIMESTAMP,
168234 {"%Y-%m-%d %H:%M:%S.%f", "%m-%d-%Y %I:%M:%S %p", "%m-%d-%y %I:%M:%S %p", "%d-%m-%Y %H:%M:%S",
168235 "%d-%m-%y %H:%M:%S", "%Y-%m-%d %H:%M:%S", "%y-%m-%d %H:%M:%S"}},
168236 };

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