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

#include <duckdb.hpp>

Classes

struct  EnumStringLiteral

Static Public Member Functions

static string GenerateRandomName (idx_t length=16)
static uint8_t GetHexValue (char c)
static uint8_t GetBinaryValue (char c)
static bool CharacterIsSpace (char c)
static bool CharacterIsNewline (char c)
static bool CharacterIsDigit (char c)
static bool CharacterIsHex (char c)
static char CharacterToUpper (char c)
static char CharacterToLower (char c)
static bool CharacterIsAlpha (char c)
static bool CharacterIsAlphaNumeric (char c)
static bool CharacterIsOperator (char c)
template<class TO>
static vector< TO > ConvertStrings (const vector< string > &strings)
static vector< SQLIdentifier > ConvertToSQLIdentifiers (const vector< string > &strings)
static vector< SQLString > ConvertToSQLStrings (const vector< string > &strings)
static DUCKDB_API bool Contains (const string &haystack, const string &needle)
 Returns true if the needle string exists in the haystack.
static DUCKDB_API bool Contains (const string &haystack, const char &needle_char)
static DUCKDB_API optional_idx Find (const string &haystack, const string &needle)
 Returns the position of needle string within the haystack.
static DUCKDB_API bool StartsWith (string str, string prefix)
 Returns true if the target string starts with the given prefix.
static DUCKDB_API bool EndsWith (const string &str, const string &suffix)
 Returns true if the target string ends with the given suffix.
static DUCKDB_API string Repeat (const string &str, const idx_t n)
 Repeat a string multiple times.
static DUCKDB_API vector< string > Split (const string &str, char delimiter)
 Split the input string based on newline char.
static DUCKDB_API vector< string > SplitWithParentheses (const string &str, char delimiter=',', char par_open='(', char par_close=')')
 Split the input string, ignore delimiters within parentheses. Note: leading/trailing spaces are NOT stripped.
static DUCKDB_API vector< string > SplitWithQuote (const string &str, char delimiter=',', char quote='"')
 Split the input string allong a quote. Note that any escaping is NOT supported.
static DUCKDB_API string Join (const vector< string > &input, const string &separator)
 Join multiple strings into one string. Components are concatenated by the given separator.
static DUCKDB_API string Join (const set< string > &input, const string &separator)
static DUCKDB_API string URLEncode (const string &str, bool encode_slash=true)
 Encode special URL characters in a string.
static DUCKDB_API idx_t URLEncodeSize (const char *input, idx_t input_size, bool encode_slash=true)
static DUCKDB_API void URLEncodeBuffer (const char *input, idx_t input_size, char *output, bool encode_slash=true)
static DUCKDB_API string URLDecode (const string &str, bool plus_to_space=false)
 Decode URL escape sequences (e.g. %20) in a string.
static DUCKDB_API idx_t URLDecodeSize (const char *input, idx_t input_size, bool plus_to_space=false)
static DUCKDB_API void URLDecodeBuffer (const char *input, idx_t input_size, char *output, bool plus_to_space=false)
static DUCKDB_API void SkipBOM (const char *buffer_ptr, const idx_t &buffer_size, idx_t &buffer_pos)
 BOM skipping (https://en.wikipedia.org/wiki/Byte_order_mark).
static DUCKDB_API idx_t ToUnsigned (const string &str)
static DUCKDB_API int64_t ToSigned (const string &str)
static DUCKDB_API double ToDouble (const string &str)
template<class T>
static string ToString (const vector< T > &input, const string &separator)
template<typename C, typename S, typename FUNC>
static string Join (const C &input, S count, const string &separator, FUNC f)
static DUCKDB_API string BytesToHumanReadableString (idx_t bytes, idx_t multiplier=1024)
 Return a string that formats the give number of bytes.
static DUCKDB_API string TryParseFormattedBytes (const string &arg, idx_t &result)
static DUCKDB_API idx_t ParseFormattedBytes (const string &arg)
static DUCKDB_API string Upper (const string &str)
 Convert a string to UPPERCASE.
static DUCKDB_API string Lower (const string &str)
 Convert a string to lowercase.
static DUCKDB_API string Title (const string &str)
 Convert a string to Title Case.
static DUCKDB_API bool IsLower (const string &str)
static DUCKDB_API bool IsUpper (const string &str)
static DUCKDB_API uint64_t CIHash (const string &str)
 Case insensitive hash.
static DUCKDB_API uint64_t CIHash (const char *str, idx_t size)
static DUCKDB_API bool CIEquals (const string &l1, const string &l2)
 Case insensitive equals.
static DUCKDB_API bool CIEquals (const char *l1, idx_t l1_size, const char *l2, idx_t l2_size)
 Case insensitive equals (null-terminated strings).
static DUCKDB_API bool CIStartsWith (const string &str, const string &prefix)
 Case insensitive starts-with.
static DUCKDB_API bool CILessThan (const string &l1, const string &l2)
 Case insensitive compare.
static DUCKDB_API idx_t CIFind (vector< string > &vec, const string &str)
 Case insensitive find, returns DConstants::INVALID_INDEX if not found.
template<typename... ARGS>
static string Format (const string fmt_str, ARGS... params)
 Format a string using printf semantics.
static DUCKDB_API vector< string > Split (const string &input, const string &split)
 Split the input string into a vector of strings based on the split string.
static DUCKDB_API void LTrim (string &str)
 Remove the whitespace char in the left end of the string.
static DUCKDB_API void RTrim (string &str)
 Remove the whitespace char in the right end of the string.
static DUCKDB_API void RTrim (string &str, const string &chars_to_trim)
 Remove the all chars from chars_to_trim char in the right end of the string.
static DUCKDB_API void Trim (string &str)
 Remove the whitespace char in the left and right end of the string.
static DUCKDB_API string Replace (string source, const string &from, const string &to)
static DUCKDB_API idx_t LevenshteinDistance (const string &s1, const string &s2, idx_t not_equal_penalty=1)
static DUCKDB_API idx_t SimilarityScore (const string &s1, const string &s2)
 Returns the similarity score between two strings (edit distance metric - lower is more similar).
static DUCKDB_API double SimilarityRating (const string &s1, const string &s2)
 Returns a normalized similarity rating between 0.0 - 1.0 (higher is more similar).
static DUCKDB_API vector< string > TopNStrings (vector< pair< string, double > > scores, idx_t n=5, double threshold=0.5)
static DUCKDB_API vector< string > TopNStrings (const vector< pair< string, idx_t > > &scores, idx_t n=5, idx_t threshold=5)
static DUCKDB_API vector< string > TopNLevenshtein (const vector< string > &strings, const string &target, idx_t n=5, idx_t threshold=5)
static DUCKDB_API vector< string > TopNJaroWinkler (const vector< string > &strings, const string &target, idx_t n=5, double threshold=0.5)
static DUCKDB_API string CandidatesMessage (const vector< string > &candidates, const string &candidate="Candidate bindings")
static DUCKDB_API string CandidatesErrorMessage (const vector< string > &strings, const string &target, const string &message_prefix, idx_t n=5)
static bool Equals (const char *s1, const char *s2)
static bool Equals (const string &s1, const char *s2)
static bool Equals (const char *s1, const string &s2)
static bool Equals (const string &s1, const string &s2)
static bool Equals (const string_t &s1, const char *s2)
static bool Equals (const char *s1, const string_t &s2)
static DUCKDB_API unique_ptr< ComplexJSON > ParseJSONMap (const string &json, bool ignore_errors=false)
static DUCKDB_API string ExceptionToJSONMap (ExceptionType type, const string &message, const unordered_map< string, string > &map)
static DUCKDB_API string ToJSONMap (const unordered_map< string, string > &map)
 Transforms an unordered map to a JSON string.
static DUCKDB_API string ToComplexJSONMap (const ComplexJSON &complex_json)
 Transforms an complex JSON to a JSON string.
static DUCKDB_API string ValidateJSON (const char *data, const idx_t &len)
static DUCKDB_API string GetFileName (const string &file_path)
static DUCKDB_API string GetFileExtension (const string &file_name)
static DUCKDB_API string GetFileStem (const string &file_name)
static DUCKDB_API string GetFilePath (const string &file_path)
static DUCKDB_API uint32_t StringToEnum (const EnumStringLiteral enum_list[], idx_t enum_count, const char *enum_name, const char *str_value)
static DUCKDB_API const char * EnumToString (const EnumStringLiteral enum_list[], idx_t enum_count, const char *enum_name, uint32_t enum_value)

Static Public Attributes

static DUCKDB_API const uint8_t ASCII_TO_LOWER_MAP []
static DUCKDB_API const uint8_t ASCII_TO_UPPER_MAP []

Detailed Description

String Utility Functions Note that these are not the most efficient implementations (i.e., they copy memory) and therefore they should only be used for debug messages and other such things.

Member Function Documentation

◆ GenerateRandomName()

string duckdb::StringUtil::GenerateRandomName ( idx_t length = 16)
static
109293 {
109294 RandomEngine engine;
109295 duckdb::stringstream ss;
109296 for (idx_t i = 0; i < length; i++) {
109297 ss << "0123456789abcdef"[engine.NextRandomInteger(0, 15)];
109298 }
109299 return ss.str();
109300}
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237

◆ GetHexValue()

uint8_t duckdb::StringUtil::GetHexValue ( char c)
inlinestatic
3800 {
3801 if (c >= '0' && c <= '9') {
3802 return UnsafeNumericCast<uint8_t>(c - '0');
3803 }
3804 if (c >= 'a' && c <= 'f') {
3805 return UnsafeNumericCast<uint8_t>(c - 'a' + 10);
3806 }
3807 if (c >= 'A' && c <= 'F') {
3808 return UnsafeNumericCast<uint8_t>(c - 'A' + 10);
3809 }
3810 throw InvalidInputException("Invalid input for hex digit: %s", string(1, c));
3811 }

◆ GetBinaryValue()

uint8_t duckdb::StringUtil::GetBinaryValue ( char c)
inlinestatic
3812 {
3813 if (c >= '0' && c <= '1') {
3814 return UnsafeNumericCast<uint8_t>(c - '0');
3815 }
3816 throw InvalidInputException("Invalid input for binary digit: %s", string(1, c));
3817 }

◆ CharacterIsSpace()

bool duckdb::StringUtil::CharacterIsSpace ( char c)
inlinestatic
3819 {
3820 return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r';
3821 }

◆ CharacterIsNewline()

bool duckdb::StringUtil::CharacterIsNewline ( char c)
inlinestatic
3822 {
3823 return c == '\n' || c == '\r';
3824 }

◆ CharacterIsDigit()

bool duckdb::StringUtil::CharacterIsDigit ( char c)
inlinestatic
3825 {
3826 return c >= '0' && c <= '9';
3827 }

◆ CharacterIsHex()

bool duckdb::StringUtil::CharacterIsHex ( char c)
inlinestatic
3828 {
3829 return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
3830 }

◆ CharacterToUpper()

char duckdb::StringUtil::CharacterToUpper ( char c)
inlinestatic
3831 {
3832 if (c >= 'a' && c <= 'z') {
3833 return UnsafeNumericCast<char>(c - ('a' - 'A'));
3834 }
3835 return c;
3836 }

◆ CharacterToLower()

char duckdb::StringUtil::CharacterToLower ( char c)
inlinestatic
3837 {
3838 if (c >= 'A' && c <= 'Z') {
3839 return UnsafeNumericCast<char>(c + ('a' - 'A'));
3840 }
3841 return c;
3842 }

◆ CharacterIsAlpha()

bool duckdb::StringUtil::CharacterIsAlpha ( char c)
inlinestatic
3843 {
3844 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
3845 }

◆ CharacterIsAlphaNumeric()

bool duckdb::StringUtil::CharacterIsAlphaNumeric ( char c)
inlinestatic
3846 {
3847 return CharacterIsAlpha(c) || CharacterIsDigit(c);
3848 }

◆ CharacterIsOperator()

bool duckdb::StringUtil::CharacterIsOperator ( char c)
inlinestatic
3849 {
3850 if (c == '_') {
3851 return false;
3852 }
3853 if (c >= '!' && c <= '/') {
3854 return true;
3855 }
3856 if (c >= ':' && c <= '@') {
3857 return true;
3858 }
3859 if (c >= '[' && c <= '`') {
3860 return true;
3861 }
3862 if (c >= '{' && c <= '~') {
3863 return true;
3864 }
3865 return false;
3866 }

◆ ConvertStrings()

template<class TO>
vector< TO > duckdb::StringUtil::ConvertStrings ( const vector< string > & strings)
inlinestatic
3869 {
3870 vector<TO> result;
3871 for (auto &string : strings) {
3872 result.emplace_back(string);
3873 }
3874 return result;
3875 }

◆ ConvertToSQLIdentifiers()

vector< SQLIdentifier > duckdb::StringUtil::ConvertToSQLIdentifiers ( const vector< string > & strings)
inlinestatic
3877 {
3878 return ConvertStrings<SQLIdentifier>(strings);
3879 }

◆ ConvertToSQLStrings()

vector< SQLString > duckdb::StringUtil::ConvertToSQLStrings ( const vector< string > & strings)
inlinestatic
3881 {
3882 return ConvertStrings<SQLString>(strings);
3883 }

◆ Contains() [1/2]

bool duckdb::StringUtil::Contains ( const string & haystack,
const string & needle )
static

Returns true if the needle string exists in the haystack.

109323 {
109324 return Find(haystack, needle).IsValid();
109325}
static DUCKDB_API optional_idx Find(const string &haystack, const string &needle)
Returns the position of needle string within the haystack.
Definition duckdb.cpp:109327
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Contains() [2/2]

bool duckdb::StringUtil::Contains ( const string & haystack,
const char & needle_char )
static
109335 {
109336 return (haystack.find(needle_char) != string::npos);
109337}

◆ Find()

optional_idx duckdb::StringUtil::Find ( const string & haystack,
const string & needle )
static

Returns the position of needle string within the haystack.

109327 {
109328 auto index = haystack.find(needle);
109329 if (index == string::npos) {
109330 return optional_idx();
109331 }
109332 return optional_idx(index);
109333}
index
Here is the caller graph for this function:

◆ StartsWith()

bool duckdb::StringUtil::StartsWith ( string str,
string prefix )
static

Returns true if the target string starts with the given prefix.

109377 {
109378 if (prefix.size() > str.size()) {
109379 return false;
109380 }
109381 return equal(prefix.begin(), prefix.end(), str.begin());
109382}
Here is the caller graph for this function:

◆ EndsWith()

bool duckdb::StringUtil::EndsWith ( const string & str,
const string & suffix )
static

Returns true if the target string ends with the given suffix.

109384 {
109385 if (suffix.size() > str.size()) {
109386 return false;
109387 }
109388 return equal(suffix.rbegin(), suffix.rend(), str.rbegin());
109389}
Here is the caller graph for this function:

◆ Repeat()

string duckdb::StringUtil::Repeat ( const string & str,
const idx_t n )
static

Repeat a string multiple times.

109391 {
109392 std::ostringstream os;
109393 for (idx_t i = 0; i < n; i++) {
109394 os << str;
109395 }
109396 return (os.str());
109397}

◆ Split() [1/2]

vector< string > duckdb::StringUtil::Split ( const string & str,
char delimiter )
static

Split the input string based on newline char.

109734 {
109735 duckdb::stringstream ss(str);
109736 vector<string> lines;
109737 string temp;
109738 while (getline(ss, temp, delimiter)) {
109739 lines.push_back(temp);
109740 }
109741 return (lines);
109742}
Here is the caller graph for this function:

◆ SplitWithParentheses()

vector< string > duckdb::StringUtil::SplitWithParentheses ( const string & str,
char delimiter = ',',
char par_open = '(',
char par_close = ')' )
static

Split the input string, ignore delimiters within parentheses. Note: leading/trailing spaces are NOT stripped.

109460 {
109461 vector<string> result;
109462 string current;
109463 stack<char> parentheses;
109464
109465 for (size_t i = 0; i < str.size(); ++i) {
109466 char ch = str[i];
109467
109468 // stack to keep track if we are within parentheses
109469 if (ch == par_open) {
109470 parentheses.push(ch);
109471 }
109472 if (ch == par_close) {
109473 if (!parentheses.empty()) {
109474 parentheses.pop();
109475 } else {
109476 throw InvalidInputException("Incongruent parentheses in string: '%s'", str);
109477 }
109478 }
109479 // split if not within parentheses
109480 if (parentheses.empty() && ch == delimiter) {
109481 result.push_back(current);
109482 current.clear();
109483 } else {
109484 current += ch;
109485 }
109486 }
109487 // Add the last segment
109488 if (!current.empty()) {
109489 result.push_back(current);
109490 }
109491 if (!parentheses.empty()) {
109492 throw InvalidInputException("Incongruent parentheses in string: '%s'", str);
109493 }
109494 return result;
109495}

◆ SplitWithQuote()

vector< string > duckdb::StringUtil::SplitWithQuote ( const string & str,
char delimiter = ',',
char quote = '"' )
static

Split the input string allong a quote. Note that any escaping is NOT supported.

109443 {
109444 vector<string> entries;
109445 idx_t i = 0;
109446
109447 string_util_internal::SkipSpaces(str, i);
109448 while (i < str.size()) {
109449 if (!entries.empty()) {
109450 string_util_internal::ConsumeLetter(str, i, delimiter);
109451 }
109452
109453 entries.emplace_back(string_util_internal::TakePossiblyQuotedItem(str, i, delimiter, quote));
109454 string_util_internal::SkipSpaces(str, i);
109455 }
109456
109457 return entries;
109458}

◆ Join() [1/3]

string duckdb::StringUtil::Join ( const vector< string > & input,
const string & separator )
static

Join multiple strings into one string. Components are concatenated by the given separator.

109497 {
109498 return StringUtil::Join(input, input.size(), separator, [](const string &s) { return s; });
109499}
static DUCKDB_API string Join(const vector< string > &input, const string &separator)
Join multiple strings into one string. Components are concatenated by the given separator.
Definition duckdb.cpp:109497
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Join() [2/3]

string duckdb::StringUtil::Join ( const set< string > & input,
const string & separator )
static
109501 {
109502 // The result
109503 std::string result;
109504
109505 auto it = input.begin();
109506 while (it != input.end()) {
109507 result += *it;
109508 it++;
109509 if (it == input.end()) {
109510 break;
109511 }
109512 result += separator;
109513 }
109514 return result;
109515}

◆ URLEncode()

string duckdb::StringUtil::URLEncode ( const string & str,
bool encode_slash = true )
static

Encode special URL characters in a string.

110249 {
110250 idx_t result_size = URLEncodeSize(input.c_str(), input.size(), encode_slash);
110251 auto result_data = make_uniq_array<char>(result_size);
110252 URLEncodeBuffer(input.c_str(), input.size(), result_data.get(), encode_slash);
110253 return string(result_data.get(), result_size);
110254}
Here is the caller graph for this function:

◆ URLEncodeSize()

idx_t duckdb::StringUtil::URLEncodeSize ( const char * input,
idx_t input_size,
bool encode_slash = true )
static
110239 {
110240 idx_t result_length = 0;
110241 URLEncodeInternal<URLEncodeLength>(input, input_size, result_length, encode_slash);
110242 return result_length;
110243}

◆ URLEncodeBuffer()

void duckdb::StringUtil::URLEncodeBuffer ( const char * input,
idx_t input_size,
char * output,
bool encode_slash = true )
static
110245 {
110246 URLEncodeInternal<URLEncodeWrite>(input, input_size, output, encode_slash);
110247}

◆ URLDecode()

string duckdb::StringUtil::URLDecode ( const string & str,
bool plus_to_space = false )
static

Decode URL escape sequences (e.g. %20) in a string.

110294 {
110295 idx_t result_size = URLDecodeSize(input.c_str(), input.size(), plus_to_space);
110296 auto result_data = make_uniq_array<char>(result_size);
110297 URLDecodeBuffer(input.c_str(), input.size(), result_data.get(), plus_to_space);
110298 return string(result_data.get(), result_size);
110299}
Here is the caller graph for this function:

◆ URLDecodeSize()

idx_t duckdb::StringUtil::URLDecodeSize ( const char * input,
idx_t input_size,
bool plus_to_space = false )
static
110272 {
110273 idx_t result_length = 0;
110274 URLDecodeInternal<URLEncodeLength>(input, input_size, result_length, plus_to_space);
110275 return result_length;
110276}

◆ URLDecodeBuffer()

void duckdb::StringUtil::URLDecodeBuffer ( const char * input,
idx_t input_size,
char * output,
bool plus_to_space = false )
static
110278 {
110279 char *output_start = output;
110280 URLDecodeInternal<URLEncodeWrite>(input, input_size, output, plus_to_space);
110281 if (!Utf8Proc::IsValid(output_start, NumericCast<idx_t>(output - output_start))) {
110282 throw InvalidInputException("Failed to decode string \"%s\" using URL decoding - decoded value is invalid UTF8",
110283 string(input, input_size));
110284 }
110285}
static bool IsValid(const char *s, size_t len)
Returns whether or not the UTF8 string is valid.
Definition duckdb.cpp:507383

◆ SkipBOM()

void duckdb::StringUtil::SkipBOM ( const char * buffer_ptr,
const idx_t & buffer_size,
idx_t & buffer_pos )
static

BOM skipping (https://en.wikipedia.org/wiki/Byte_order_mark).

110287 {
110288 if (buffer_size >= 3 && buffer_ptr[0] == '\xEF' && buffer_ptr[1] == '\xBB' && buffer_ptr[2] == '\xBF' &&
110289 buffer_pos == 0) {
110290 buffer_pos = 3;
110291 }
110292}
shared_ptr< T > buffer_ptr
FIXME: this should be a single_thread_ptr.
Definition duckdb.hpp:2709
Here is the caller graph for this function:

◆ ToUnsigned()

idx_t duckdb::StringUtil::ToUnsigned ( const string & str)
static
109339 {
109340 return std::stoull(str);
109341}

◆ ToSigned()

int64_t duckdb::StringUtil::ToSigned ( const string & str)
static
109343 {
109344 return std::stoll(str);
109345}

◆ ToDouble()

double duckdb::StringUtil::ToDouble ( const string & str)
static
109347 {
109348 return std::stod(str);
109349}

◆ ToString()

template<class T>
string duckdb::StringUtil::ToString ( const vector< T > & input,
const string & separator )
inlinestatic
3933 {
3934 vector<string> input_list;
3935 for (auto &i : input) {
3936 input_list.push_back(i.ToString());
3937 }
3938 return StringUtil::Join(input_list, separator);
3939 }

◆ Join() [3/3]

template<typename C, typename S, typename FUNC>
string duckdb::StringUtil::Join ( const C & input,
S count,
const string & separator,
FUNC f )
inlinestatic

Join multiple items of container with given size, transformed to string using function, into one string using the given separator

3944 {
3945 // The result
3946 std::string result;
3947
3948 // If the input isn't empty, append the first element. We do this so we
3949 // don't need to introduce an if into the loop.
3950 if (count > 0) {
3951 result += f(input[0]);
3952 }
3953
3954 // Append the remaining input components, after the first
3955 for (size_t i = 1; i < count; i++) {
3956 result += separator + f(input[i]);
3957 }
3958
3959 return result;
3960 }

◆ BytesToHumanReadableString()

string duckdb::StringUtil::BytesToHumanReadableString ( idx_t bytes,
idx_t multiplier = 1024 )
static

Return a string that formats the give number of bytes.

109517 {
109518 D_ASSERT(multiplier == 1000 || multiplier == 1024);
109519 idx_t array[6] = {};
109520 const char *unit[2][6] = {{"bytes", "KiB", "MiB", "GiB", "TiB", "PiB"}, {"bytes", "kB", "MB", "GB", "TB", "PB"}};
109521
109522 const int sel = (multiplier == 1000);
109523
109524 array[0] = bytes;
109525 for (idx_t i = 1; i < 6; i++) {
109526 array[i] = array[i - 1] / multiplier;
109527 array[i - 1] %= multiplier;
109528 }
109529
109530 for (idx_t i = 5; i >= 1; i--) {
109531 if (array[i]) {
109532 // Map 0 -> 0 and (multiplier-1) -> 9
109533 idx_t fractional_part = (array[i - 1] * 10) / multiplier;
109534 return to_string(array[i]) + "." + to_string(fractional_part) + " " + unit[sel][i];
109535 }
109536 }
109537
109538 return to_string(array[0]) + (bytes == 1 ? " byte" : " bytes");
109539}
std::string to_string(const T &value)
Definition duckdb.cpp:19425
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TryParseFormattedBytes()

string duckdb::StringUtil::TryParseFormattedBytes ( const string & arg,
idx_t & result )
static
109541 {
109542 // split based on the number/non-number
109543 idx_t idx = 0;
109544 while (StringUtil::CharacterIsSpace(arg[idx])) {
109545 idx++;
109546 }
109547 idx_t num_start = idx;
109548 while ((arg[idx] >= '0' && arg[idx] <= '9') || arg[idx] == '.' || arg[idx] == 'e' || arg[idx] == 'E' ||
109549 arg[idx] == '-') {
109550 idx++;
109551 }
109552 if (idx == num_start) {
109553 return "Memory must have a number (e.g. 1GB)";
109554 }
109555 string number = arg.substr(num_start, idx - num_start);
109556
109557 // try to parse the number
109558 double limit;
109559 bool success = TryCast::Operation<string_t, double>(string_t(number), limit);
109560 if (!success) {
109561 return StringUtil::Format("Invalid memory limit: '%s'", number);
109562 }
109563
109564 // now parse the memory limit unit (e.g. bytes, gb, etc)
109565 while (StringUtil::CharacterIsSpace(arg[idx])) {
109566 idx++;
109567 }
109568 idx_t start = idx;
109569 while (idx < arg.size() && !StringUtil::CharacterIsSpace(arg[idx])) {
109570 idx++;
109571 }
109572
109573 if (limit < 0) {
109574 return "Memory cannot be negative";
109575 }
109576
109577 string unit = StringUtil::Lower(arg.substr(start, idx - start));
109578 idx_t multiplier;
109579 if (unit == "byte" || unit == "bytes" || unit == "b") {
109580 multiplier = 1;
109581 } else if (unit == "kilobyte" || unit == "kilobytes" || unit == "kb" || unit == "k") {
109582 multiplier = 1000LL;
109583 } else if (unit == "megabyte" || unit == "megabytes" || unit == "mb" || unit == "m") {
109584 multiplier = 1000LL * 1000LL;
109585 } else if (unit == "gigabyte" || unit == "gigabytes" || unit == "gb" || unit == "g") {
109586 multiplier = 1000LL * 1000LL * 1000LL;
109587 } else if (unit == "terabyte" || unit == "terabytes" || unit == "tb" || unit == "t") {
109588 multiplier = 1000LL * 1000LL * 1000LL * 1000LL;
109589 } else if (unit == "kib") {
109590 multiplier = 1024LL;
109591 } else if (unit == "mib") {
109592 multiplier = 1024LL * 1024LL;
109593 } else if (unit == "gib") {
109594 multiplier = 1024LL * 1024LL * 1024LL;
109595 } else if (unit == "tib") {
109596 multiplier = 1024LL * 1024LL * 1024LL * 1024LL;
109597 } else {
109598 return StringUtil::Format("Unknown unit for memory: '%s' (expected: KB, MB, GB, TB for 1000^i units or KiB, "
109599 "MiB, GiB, TiB for 1024^i units)",
109600 unit);
109601 }
109602
109603 // Make sure the result is not greater than `idx_t` max value
109604 constexpr double max_value = static_cast<double>(NumericLimits<idx_t>::Maximum());
109605 const double double_multiplier = static_cast<double>(multiplier);
109606
109607 if (limit > (max_value / double_multiplier)) {
109608 return "Memory value out of range: value is too large";
109609 }
109610
109611 result = LossyNumericCast<idx_t>(static_cast<double>(multiplier) * limit);
109612 return string();
109613}
static DUCKDB_API string Lower(const string &str)
Convert a string to lowercase.
Definition duckdb.cpp:109630
static string Format(const string fmt_str, ARGS... params)
Format a string using printf semantics.
Definition duckdb.hpp:4002
internal::named_arg< T, Char > arg(const S &name, const T &arg)
Definition duckdb.cpp:16242

◆ ParseFormattedBytes()

idx_t duckdb::StringUtil::ParseFormattedBytes ( const string & arg)
static
109615 {
109616 idx_t result;
109617 const string error = TryParseFormattedBytes(arg, result);
109618 if (!error.empty()) {
109619 throw InvalidInputException(error);
109620 }
109621 return result;
109622}

◆ Upper()

string duckdb::StringUtil::Upper ( const string & str)
static

Convert a string to UPPERCASE.

109624 {
109625 string copy(str);
109626 transform(copy.begin(), copy.end(), copy.begin(), [](unsigned char c) { return std::toupper(c); });
109627 return (copy);
109628}
void transform(InputArray src, OutputArray dst, InputArray m)
Here is the caller graph for this function:

◆ Lower()

string duckdb::StringUtil::Lower ( const string & str)
static

Convert a string to lowercase.

109630 {
109631 string copy(str);
109632 transform(copy.begin(), copy.end(), copy.begin(),
109633 [](unsigned char c) { return StringUtil::CharacterToLower(static_cast<char>(c)); });
109634 return (copy);
109635}
Here is the caller graph for this function:

◆ Title()

string duckdb::StringUtil::Title ( const string & str)
static

Convert a string to Title Case.

109637 {
109638 string copy;
109639 bool first_character = true;
109640 for (auto c : str) {
109641 bool is_alpha = StringUtil::CharacterIsAlpha(c);
109642 if (is_alpha) {
109643 if (first_character) {
109644 copy += StringUtil::CharacterToUpper(c);
109645 first_character = false;
109646 } else {
109647 copy += StringUtil::CharacterToLower(c);
109648 }
109649 } else {
109650 first_character = true;
109651 copy += c;
109652 }
109653 }
109654 return copy;
109655}

◆ IsLower()

bool duckdb::StringUtil::IsLower ( const string & str)
static
109657 {
109658 return str == Lower(str);
109659}

◆ IsUpper()

bool duckdb::StringUtil::IsUpper ( const string & str)
static
109661 {
109662 return str == Upper(str);
109663}
static DUCKDB_API string Upper(const string &str)
Convert a string to UPPERCASE.
Definition duckdb.cpp:109624

◆ CIHash() [1/2]

uint64_t duckdb::StringUtil::CIHash ( const string & str)
static

Case insensitive hash.

109666 {
109667 return StringUtil::CIHash(str.c_str(), str.size());
109668}
static DUCKDB_API uint64_t CIHash(const string &str)
Case insensitive hash.
Definition duckdb.cpp:109666
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CIHash() [2/2]

uint64_t duckdb::StringUtil::CIHash ( const char * str,
idx_t size )
static
109670 {
109671 uint32_t hash = 0;
109672 for (idx_t i = 0; i < size; i++) {
109673 hash += static_cast<uint32_t>(StringUtil::CharacterToLower(static_cast<char>(str[i])));
109674 hash += hash << 10;
109675 hash ^= hash >> 6;
109676 }
109677 hash += hash << 3;
109678 hash ^= hash >> 11;
109679 hash += hash << 15;
109680 return hash;
109681}
GOpaque< Size > size(const GMat &src)
::uint32_t uint32_t

◆ CIEquals() [1/2]

bool duckdb::StringUtil::CIEquals ( const string & l1,
const string & l2 )
static

Case insensitive equals.

109696 {
109697 return CIEquals(l1.c_str(), l1.size(), l2.c_str(), l2.size());
109698}
static DUCKDB_API bool CIEquals(const string &l1, const string &l2)
Case insensitive equals.
Definition duckdb.cpp:109696
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CIEquals() [2/2]

bool duckdb::StringUtil::CIEquals ( const char * l1,
idx_t l1_size,
const char * l2,
idx_t l2_size )
static

Case insensitive equals (null-terminated strings).

109683 {
109684 if (l1_size != l2_size) {
109685 return false;
109686 }
109687 const auto charmap = ASCII_TO_LOWER_MAP;
109688 for (idx_t c = 0; c < l1_size; c++) {
109689 if (charmap[(uint8_t)l1[c]] != charmap[(uint8_t)l2[c]]) {
109690 return false;
109691 }
109692 }
109693 return true;
109694}

◆ CIStartsWith()

bool duckdb::StringUtil::CIStartsWith ( const string & str,
const string & prefix )
static

Case insensitive starts-with.

109700 {
109701 if (prefix.size() > str.size()) {
109702 return false;
109703 }
109704 return CIEquals(str.c_str(), prefix.size(), prefix.c_str(), prefix.size());
109705}
Here is the call graph for this function:

◆ CILessThan()

bool duckdb::StringUtil::CILessThan ( const string & l1,
const string & l2 )
static

Case insensitive compare.

109707 {
109708 const auto charmap = ASCII_TO_UPPER_MAP;
109709
109710 unsigned char u1 {}, u2 {};
109711
109712 idx_t length = MinValue<idx_t>(s1.length(), s2.length());
109713 length += s1.length() != s2.length();
109714 for (idx_t i = 0; i < length; i++) {
109715 u1 = (unsigned char)s1[i];
109716 u2 = (unsigned char)s2[i];
109717 if (charmap[u1] != charmap[u2]) {
109718 break;
109719 }
109720 }
109721 return (charmap[u1] - charmap[u2]) < 0;
109722}
Here is the caller graph for this function:

◆ CIFind()

idx_t duckdb::StringUtil::CIFind ( vector< string > & vec,
const string & str )
static

Case insensitive find, returns DConstants::INVALID_INDEX if not found.

109724 {
109725 for (idx_t i = 0; i < vector.size(); i++) {
109726 const auto &string = vector[i];
109727 if (CIEquals(string, search_string)) {
109728 return i;
109729 }
109730 }
109732}
static constexpr const idx_t INVALID_INDEX
The value used to signify an invalid index entry.
Definition duckdb.hpp:1117
Here is the call graph for this function:

◆ Format()

template<typename... ARGS>
string duckdb::StringUtil::Format ( const string fmt_str,
ARGS... params )
inlinestatic

Format a string using printf semantics.

4002 {
4003 return Exception::ConstructMessage(fmt_str, params...);
4004 }
PyParams params(const std::string &tag, const std::string &model, const std::string &weights, const std::string &device)
Here is the caller graph for this function:

◆ Split() [2/2]

vector< string > duckdb::StringUtil::Split ( const string & input,
const string & split )
static

Split the input string into a vector of strings based on the split string.

109744 {
109745 vector<string> splits;
109746
109747 idx_t last = 0;
109748 idx_t input_len = input.size();
109749 idx_t split_len = split.size();
109750 while (last <= input_len) {
109751 idx_t next = input.find(split, last);
109752 if (next == string::npos) {
109753 next = input_len;
109754 }
109755
109756 // Push the substring [last, next) on to splits
109757 string substr = input.substr(last, next - last);
109758 if (!substr.empty()) {
109759 splits.push_back(substr);
109760 }
109761 last = next + split_len;
109762 }
109763 if (splits.empty()) {
109764 splits.push_back(input);
109765 }
109766 return splits;
109767}
void split(const Mat &src, Mat *mvbegin)

◆ LTrim()

void duckdb::StringUtil::LTrim ( string & str)
static

Remove the whitespace char in the left end of the string.

109351 {
109352 auto it = str.begin();
109353 while (it != str.end() && CharacterIsSpace(*it)) {
109354 it++;
109355 }
109356 str.erase(str.begin(), it);
109357}
Here is the caller graph for this function:

◆ RTrim() [1/2]

void duckdb::StringUtil::RTrim ( string & str)
static

Remove the whitespace char in the right end of the string.

109360 {
109361 str.erase(find_if(str.rbegin(), str.rend(), [](char ch) { return ch > 0 && !CharacterIsSpace(ch); }).base(),
109362 str.end());
109363}
Here is the caller graph for this function:

◆ RTrim() [2/2]

void duckdb::StringUtil::RTrim ( string & str,
const string & chars_to_trim )
static

Remove the all chars from chars_to_trim char in the right end of the string.

109365 {
109366 str.erase(find_if(str.rbegin(), str.rend(),
109367 [&chars_to_trim](char ch) { return ch > 0 && chars_to_trim.find(ch) == string::npos; })
109368 .base(),
109369 str.end());
109370}

◆ Trim()

void duckdb::StringUtil::Trim ( string & str)
static

Remove the whitespace char in the left and right end of the string.

109372 {
109373 StringUtil::LTrim(str);
109374 StringUtil::RTrim(str);
109375}
static DUCKDB_API void RTrim(string &str)
Remove the whitespace char in the right end of the string.
Definition duckdb.cpp:109360
static DUCKDB_API void LTrim(string &str)
Remove the whitespace char in the left end of the string.
Definition duckdb.cpp:109351
Here is the call graph for this function:

◆ Replace()

string duckdb::StringUtil::Replace ( string source,
const string & from,
const string & to )
static
109769 {
109770 if (from.empty()) {
109771 throw InternalException("Invalid argument to StringUtil::Replace - empty FROM");
109772 }
109773 idx_t start_pos = 0;
109774 while ((start_pos = source.find(from, start_pos)) != string::npos) {
109775 source.replace(start_pos, from.length(), to);
109776 start_pos += to.length(); // In case 'to' contains 'from', like
109777 // replacing 'x' with 'yx'
109778 }
109779 return source;
109780}

◆ LevenshteinDistance()

idx_t duckdb::StringUtil::LevenshteinDistance ( const string & s1,
const string & s2,
idx_t not_equal_penalty = 1 )
static

Get the levenshtein distance from two strings The not_equal_penalty is the penalty given when two characters in a string are not equal The regular levenshtein distance has a not equal penalty of 1, which means changing a character is as expensive as adding or removing one For similarity searches we often want to give extra weight to changing a character For example: with an equal penalty of 1, "pg_am" is closer to "depdelay" than "depdelay_minutes" with an equal penalty of 3, "depdelay_minutes" is closer to "depdelay" than to "pg_am"

109843 {
109844 auto s1 = StringUtil::Lower(s1_p);
109845 auto s2 = StringUtil::Lower(s2_p);
109846 idx_t len1 = s1.size();
109847 idx_t len2 = s2.size();
109848 if (len1 == 0) {
109849 return len2;
109850 }
109851 if (len2 == 0) {
109852 return len1;
109853 }
109854 LevenshteinArray array(len1 + 1, len2 + 1);
109855 array.Score(0, 0) = 0;
109856 for (idx_t i = 0; i <= len1; i++) {
109857 array.Score(i, 0) = i;
109858 }
109859 for (idx_t j = 0; j <= len2; j++) {
109860 array.Score(0, j) = j;
109861 }
109862 for (idx_t i = 1; i <= len1; i++) {
109863 for (idx_t j = 1; j <= len2; j++) {
109864 // d[i][j] = std::min({ d[i - 1][j] + 1,
109865 // d[i][j - 1] + 1,
109866 // d[i - 1][j - 1] + (s1[i - 1] == s2[j - 1] ? 0 : 1) });
109867 auto equal = s1[i - 1] == s2[j - 1] ? 0 : not_equal_penalty;
109868 idx_t adjacent_score1 = array.Score(i - 1, j) + 1;
109869 idx_t adjacent_score2 = array.Score(i, j - 1) + 1;
109870 idx_t adjacent_score3 = array.Score(i - 1, j - 1) + equal;
109871
109872 idx_t t = MinValue<idx_t>(adjacent_score1, adjacent_score2);
109873 array.Score(i, j) = MinValue<idx_t>(t, adjacent_score3);
109874 }
109875 }
109876 return array.Score(len1, len2);
109877}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ SimilarityScore()

idx_t duckdb::StringUtil::SimilarityScore ( const string & s1,
const string & s2 )
static

Returns the similarity score between two strings (edit distance metric - lower is more similar).

109879 {
109880 return LevenshteinDistance(s1, s2, 3);
109881}
static DUCKDB_API idx_t LevenshteinDistance(const string &s1, const string &s2, idx_t not_equal_penalty=1)
Definition duckdb.cpp:109843
Here is the call graph for this function:
Here is the caller graph for this function:

◆ SimilarityRating()

double duckdb::StringUtil::SimilarityRating ( const string & s1,
const string & s2 )
static

Returns a normalized similarity rating between 0.0 - 1.0 (higher is more similar).

109883 {
109884 return duckdb_jaro_winkler::jaro_winkler_similarity(s1.data(), s1.data() + s1.size(), s2.data(),
109885 s2.data() + s2.size());
109886}
std::enable_if< common::is_iterator< InputIt1 >::value &&common::is_iterator< InputIt2 >::value, double >::type jaro_winkler_similarity(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, double prefix_weight=0.1, double score_cutoff=0.0)
Calculates the jaro winkler similarity.
Definition duckdb.cpp:109127
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TopNStrings() [1/2]

vector< string > duckdb::StringUtil::TopNStrings ( vector< pair< string, double > > scores,
idx_t n = 5,
double threshold = 0.5 )
static

Get the top-n strings (sorted by the given score distance) from a set of scores. The scores should be normalized between 0.0 and 1.0, where 1.0 is the highest score At least one entry is returned (if there is one). Strings are only returned if they have a score higher than the threshold.

109782 {
109783 if (scores.empty()) {
109784 return vector<string>();
109785 }
109786 sort(scores.begin(), scores.end(), [](const pair<string, double> &a, const pair<string, double> &b) -> bool {
109787 if (a.second != b.second) {
109788 return a.second > b.second;
109789 }
109790 return StringUtil::CILessThan(a.first, b.first);
109791 });
109792 vector<string> result;
109793 result.push_back(scores[0].first);
109794 for (idx_t i = 1; i < MinValue<idx_t>(scores.size(), n); i++) {
109795 if (scores[i].second < threshold) {
109796 break;
109797 }
109798 result.push_back(scores[i].first);
109799 }
109800 return result;
109801}
static DUCKDB_API bool CILessThan(const string &l1, const string &l2)
Case insensitive compare.
Definition duckdb.cpp:109707
void sort(InputArray src, OutputArray dst, int flags)
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TopNStrings() [2/2]

vector< string > duckdb::StringUtil::TopNStrings ( const vector< pair< string, idx_t > > & scores,
idx_t n = 5,
idx_t threshold = 5 )
static

DEPRECATED: old TopNStrings method that uses the levenshtein distance metric instead of the normalized 0.0 - 1.0 rating

109807 {
109808 // obtain the max score to normalize
109809 idx_t max_score = threshold;
109810 for (auto &score : scores) {
109811 if (score.second > max_score) {
109812 max_score = score.second;
109813 }
109814 }
109815
109816 // normalize
109817 vector<pair<string, double>> normalized_scores;
109818 for (auto &score : scores) {
109819 normalized_scores.push_back(make_pair(score.first, NormalizeScore(score.second, max_score)));
109820 }
109821 return TopNStrings(std::move(normalized_scores), n, NormalizeScore(threshold, max_score));
109822}
static DUCKDB_API vector< string > TopNStrings(vector< pair< string, double > > scores, idx_t n=5, double threshold=0.5)
Definition duckdb.cpp:109782
GMat threshold(const GMat &src, const GScalar &thresh, const GScalar &maxval, int type)
Here is the call graph for this function:

◆ TopNLevenshtein()

vector< string > duckdb::StringUtil::TopNLevenshtein ( const vector< string > & strings,
const string & target,
idx_t n = 5,
idx_t threshold = 5 )
static

Computes the levenshtein distance of each string in strings, and compares it to target, then returns TopNStrings with the given params.

109889 {
109890 vector<pair<string, idx_t>> scores;
109891 scores.reserve(strings.size());
109892 for (auto &str : strings) {
109893 if (target.size() < str.size()) {
109894 scores.emplace_back(str, SimilarityScore(str.substr(0, target.size()), target));
109895 } else {
109896 scores.emplace_back(str, SimilarityScore(str, target));
109897 }
109898 }
109899 return TopNStrings(scores, n, threshold);
109900}
static DUCKDB_API idx_t SimilarityScore(const string &s1, const string &s2)
Returns the similarity score between two strings (edit distance metric - lower is more similar).
Definition duckdb.cpp:109879
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TopNJaroWinkler()

vector< string > duckdb::StringUtil::TopNJaroWinkler ( const vector< string > & strings,
const string & target,
idx_t n = 5,
double threshold = 0.5 )
static

Computes the jaro winkler distance of each string in strings, and compares it to target, then returns TopNStrings with the given params.

109903 {
109904 vector<pair<string, double>> scores;
109905 scores.reserve(strings.size());
109906 for (auto &str : strings) {
109907 scores.emplace_back(str, SimilarityRating(str, target));
109908 }
109909 return TopNStrings(scores, n, threshold);
109910}
static DUCKDB_API double SimilarityRating(const string &s1, const string &s2)
Returns a normalized similarity rating between 0.0 - 1.0 (higher is more similar).
Definition duckdb.cpp:109883
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CandidatesMessage()

string duckdb::StringUtil::CandidatesMessage ( const vector< string > & candidates,
const string & candidate = "Candidate bindings" )
static
109912 {
109913 string result_str;
109914 if (!candidates.empty()) {
109915 result_str = "\n" + candidate + ": ";
109916 for (idx_t i = 0; i < candidates.size(); i++) {
109917 if (i > 0) {
109918 result_str += ", ";
109919 }
109920 result_str += "\"" + candidates[i] + "\"";
109921 }
109922 }
109923 return result_str;
109924}

◆ CandidatesErrorMessage()

string duckdb::StringUtil::CandidatesErrorMessage ( const vector< string > & strings,
const string & target,
const string & message_prefix,
idx_t n = 5 )
static

Generate an error message in the form of "{message_prefix}: nearest_string, nearest_string2, ... Equivalent to calling TopNLevenshtein followed by CandidatesMessage

109927 {
109928 auto closest_strings = StringUtil::TopNLevenshtein(strings, target, n);
109929 return StringUtil::CandidatesMessage(closest_strings, message_prefix);
109930}
static DUCKDB_API vector< string > TopNLevenshtein(const vector< string > &strings, const string &target, idx_t n=5, idx_t threshold=5)
Definition duckdb.cpp:109888
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Equals() [1/6]

bool duckdb::StringUtil::Equals ( const char * s1,
const char * s2 )
inlinestatic

Returns true if two null-terminated strings are equal or point to the same address. Returns false if only one of the strings is nullptr

4060 {
4061 if (s1 == s2) {
4062 return true;
4063 }
4064 if (s1 == nullptr || s2 == nullptr) {
4065 return false;
4066 }
4067 return strcmp(s1, s2) == 0;
4068 }

◆ Equals() [2/6]

bool duckdb::StringUtil::Equals ( const string & s1,
const char * s2 )
inlinestatic
4069 {
4070 return Equals(s1.c_str(), s2);
4071 }
static bool Equals(const char *s1, const char *s2)
Definition duckdb.hpp:4060

◆ Equals() [3/6]

bool duckdb::StringUtil::Equals ( const char * s1,
const string & s2 )
inlinestatic
4072 {
4073 return Equals(s1, s2.c_str());
4074 }

◆ Equals() [4/6]

bool duckdb::StringUtil::Equals ( const string & s1,
const string & s2 )
inlinestatic
4075 {
4076 return s1 == s2;
4077 }

◆ Equals() [5/6]

bool duckdb::StringUtil::Equals ( const string_t & s1,
const char * s2 )
static
109302 {
109303 auto s1_data = s1.GetData();
109304 for (idx_t i = 0; i < s1.GetSize(); i++) {
109305 if (s1_data[i] != s2[i]) {
109306 return false;
109307 }
109308 if (s2[i] == '\0') {
109309 return false;
109310 }
109311 }
109312 if (s2[s1.GetSize()] != '\0') {
109313 // not equal
109314 return false;
109315 }
109316 return true;
109317}

◆ Equals() [6/6]

bool duckdb::StringUtil::Equals ( const char * s1,
const string_t & s2 )
static
109319 {
109320 return StringUtil::Equals(s2, s1);
109321}

◆ ParseJSONMap()

unique_ptr< ComplexJSON > duckdb::StringUtil::ParseJSONMap ( const string & json,
bool ignore_errors = false )
static

JSON method that parses a { string: value } JSON blob NOTE: this method is not efficient NOTE: this method is used in Exception construction - as such it does NOT throw on invalid JSON, instead an empty map is returned Parses complex (i.e., nested) Json maps, it also parses invalid JSONs, as a pure string.

109981 {
109982 auto result = make_uniq<ComplexJSON>(json);
109983 if (json.empty()) {
109984 return result;
109985 }
109987 yyjson_doc *doc = yyjson_read(json.c_str(), json.size(), flags);
109988 if (!doc) {
109989 if (ignore_errors) {
109990 return result;
109991 }
109992 throw SerializationException("Failed to parse JSON string: %s", json);
109993 }
109994 yyjson_val *root = yyjson_doc_get_root(doc);
109995 if (!root || yyjson_get_type(root) != YYJSON_TYPE_OBJ) {
109996 yyjson_doc_free(doc);
109997 if (ignore_errors) {
109998 return result;
109999 }
110000 throw SerializationException("Failed to parse JSON string: %s", json);
110001 }
110002
110003 result = ParseJSON(json, doc, root, ignore_errors);
110004 yyjson_doc_free(doc);
110005 return result;
110006}
static const yyjson_read_flag YYJSON_READ_ALLOW_INVALID_UNICODE
Definition duckdb.cpp:37826
uint32_t yyjson_read_flag
Definition duckdb.cpp:37778
struct yyjson_doc yyjson_doc
Definition duckdb.cpp:37748
#define YYJSON_TYPE_OBJ
Definition duckdb.cpp:37614
struct yyjson_val yyjson_val
Definition duckdb.cpp:37755
yyjson_api_inline yyjson_type yyjson_get_type(yyjson_val *val)
Definition duckdb.cpp:41957
yyjson_api_inline void yyjson_doc_free(yyjson_doc *doc)
Definition duckdb.cpp:41880
yyjson_api_inline yyjson_doc * yyjson_read(const char *dat, size_t len, yyjson_read_flag flg)
Definition duckdb.cpp:37983
yyjson_api_inline yyjson_val * yyjson_doc_get_root(yyjson_doc *doc)
Definition duckdb.cpp:41868
Here is the caller graph for this function:

◆ ExceptionToJSONMap()

string duckdb::StringUtil::ExceptionToJSONMap ( ExceptionType type,
const string & message,
const unordered_map< string, string > & map )
static

JSON method that constructs a { string: value } JSON map This is the inverse of ParseJSONMap NOTE: this method is not efficient

110112 {
110113 D_ASSERT(map.find("exception_type") == map.end());
110114 D_ASSERT(map.find("exception_message") == map.end());
110115
110116 yyjson_mut_doc *doc = yyjson_mut_doc_new(nullptr);
110117 yyjson_mut_val *root = yyjson_mut_obj(doc);
110118 yyjson_mut_doc_set_root(doc, root);
110119
110120 auto except_str = Exception::ExceptionTypeToString(type);
110121 yyjson_mut_obj_add_strncpy(doc, root, "exception_type", except_str.c_str(), except_str.size());
110122 yyjson_mut_obj_add_strncpy(doc, root, "exception_message", message.c_str(), message.size());
110123
110124 return ToJsonMapInternal(map, doc, root);
110125}
yyjson_api_inline void yyjson_mut_doc_set_root(yyjson_mut_doc *doc, yyjson_mut_val *root)
Definition duckdb.cpp:42425
yyjson_api yyjson_mut_doc * yyjson_mut_doc_new(const yyjson_alc *alc)
Definition duckdb.cpp:599384
yyjson_api_inline bool yyjson_mut_obj_add_strncpy(yyjson_mut_doc *doc, yyjson_mut_val *obj, const char *key, const char *val, size_t len)
Definition duckdb.cpp:44013
struct yyjson_mut_doc yyjson_mut_doc
Definition duckdb.cpp:37762
yyjson_api_inline yyjson_mut_val * yyjson_mut_obj(yyjson_mut_doc *doc)
Definition duckdb.cpp:43608
struct yyjson_mut_val yyjson_mut_val
Definition duckdb.cpp:37769

◆ ToJSONMap()

string duckdb::StringUtil::ToJSONMap ( const unordered_map< string, string > & map)
static

Transforms an unordered map to a JSON string.

110036 {
110037 yyjson_mut_doc *doc = yyjson_mut_doc_new(nullptr);
110038 yyjson_mut_val *root = yyjson_mut_obj(doc);
110039 yyjson_mut_doc_set_root(doc, root);
110040
110041 return ToJsonMapInternal(map, doc, root);
110042}

◆ ToComplexJSONMap()

string duckdb::StringUtil::ToComplexJSONMap ( const ComplexJSON & complex_json)
static

Transforms an complex JSON to a JSON string.

110092 {
110093 return ComplexJSON::GetValueRecursive(complex_json);
110094}
static string GetValueRecursive(const ComplexJSON &child)
Recursive function for GetValue.
Definition duckdb.cpp:110064
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ValidateJSON()

string duckdb::StringUtil::ValidateJSON ( const char * data,
const idx_t & len )
static
110096 {
110097 // Same flags as in JSON extension
110098 static constexpr auto READ_FLAG =
110100 yyjson_read_err error;
110101 yyjson_doc *doc = yyjson_read_opts((char *)data, len, READ_FLAG, nullptr, &error); // NOLINT: for yyjson
110102 if (error.code != YYJSON_READ_SUCCESS) {
110103 return StringUtil::Format("Malformed JSON at byte %lld of input: %s. Input: \"%s\"", error.pos, error.msg,
110104 string(data, len));
110105 }
110106
110107 yyjson_doc_free(doc);
110108 return string();
110109}
static const yyjson_read_flag YYJSON_READ_BIGNUM_AS_RAW
Definition duckdb.cpp:37832
yyjson_api yyjson_doc * yyjson_read_opts(char *dat, size_t len, yyjson_read_flag flg, const yyjson_alc *alc, yyjson_read_err *err)
Definition duckdb.cpp:604595
static const yyjson_read_flag YYJSON_READ_ALLOW_TRAILING_COMMAS
Definition duckdb.cpp:37805
static const yyjson_read_flag YYJSON_READ_ALLOW_INF_AND_NAN
Definition duckdb.cpp:37812
struct duckdb_yyjson::yyjson_read_err yyjson_read_err

◆ GetFileName()

string duckdb::StringUtil::GetFileName ( const string & file_path)
static
110127 {
110128 idx_t pos = file_path.find_last_of("/\\");
110129 if (pos == string::npos) {
110130 return file_path;
110131 }
110132 auto end = file_path.size() - 1;
110133
110134 // If the rest of the string is just slashes or dots, trim them
110135 if (file_path.find_first_not_of("/\\.", pos) == string::npos) {
110136 // Trim the trailing slashes and dots
110137 while (end > 0 && (file_path[end] == '/' || file_path[end] == '.' || file_path[end] == '\\')) {
110138 end--;
110139 }
110140
110141 // Now find the next slash
110142 pos = file_path.find_last_of("/\\", end);
110143 if (pos == string::npos) {
110144 return file_path.substr(0, end + 1);
110145 }
110146 }
110147
110148 return file_path.substr(pos + 1, end - pos);
110149}

◆ GetFileExtension()

string duckdb::StringUtil::GetFileExtension ( const string & file_name)
static
110151 {
110152 auto name = GetFileName(file_name);
110153 idx_t pos = name.find_last_of('.');
110154 // We dont consider e.g. `.gitignore` to have an extension
110155 if (pos == string::npos || pos == 0) {
110156 return "";
110157 }
110158 return name.substr(pos + 1);
110159}

◆ GetFileStem()

string duckdb::StringUtil::GetFileStem ( const string & file_name)
static
110161 {
110162 auto name = GetFileName(file_name);
110163 if (name.size() > 1 && name[0] == '.') {
110164 return name;
110165 }
110166 idx_t pos = name.find_last_of('.');
110167 if (pos == string::npos) {
110168 return name;
110169 }
110170 return name.substr(0, pos);
110171}

◆ GetFilePath()

string duckdb::StringUtil::GetFilePath ( const string & file_path)
static
110173 {
110174 // Trim the trailing slashes
110175 auto end = file_path.size() - 1;
110176 while (end > 0 && (file_path[end] == '/' || file_path[end] == '\\')) {
110177 end--;
110178 }
110179
110180 auto pos = file_path.find_last_of("/\\", end);
110181 if (pos == string::npos) {
110182 return "";
110183 }
110184
110185 while (pos > 0 && (file_path[pos] == '/' || file_path[pos] == '\\')) {
110186 pos--;
110187 }
110188
110189 return file_path.substr(0, pos + 1);
110190}

◆ StringToEnum()

uint32_t duckdb::StringUtil::StringToEnum ( const EnumStringLiteral enum_list[],
idx_t enum_count,
const char * enum_name,
const char * str_value )
static
110302 {
110303 for (idx_t i = 0; i < enum_count; i++) {
110304 if (CIEquals(enum_list[i].string, str_value)) {
110305 return enum_list[i].number;
110306 }
110307 }
110308 // string to enum conversion failed - generate candidates
110309 vector<string> candidates;
110310 for (idx_t i = 0; i < enum_count; i++) {
110311 candidates.push_back(enum_list[i].string);
110312 }
110313 auto closest_values = TopNJaroWinkler(candidates, str_value);
110314 auto message = CandidatesMessage(closest_values, "Candidates");
110315 throw NotImplementedException("Enum value: unrecognized value \"%s\" for enum \"%s\"\n%s", str_value, enum_name,
110316 message);
110317}
static DUCKDB_API vector< string > TopNJaroWinkler(const vector< string > &strings, const string &target, idx_t n=5, double threshold=0.5)
Definition duckdb.cpp:109902

◆ EnumToString()

const char * duckdb::StringUtil::EnumToString ( const EnumStringLiteral enum_list[],
idx_t enum_count,
const char * enum_name,
uint32_t enum_value )
static
110320 {
110321 for (idx_t i = 0; i < enum_count; i++) {
110322 if (enum_list[i].number == enum_value) {
110323 return enum_list[i].string;
110324 }
110325 }
110326 throw NotImplementedException("Enum value: unrecognized enum value \"%d\" for enum \"%s\"", enum_value, enum_name);
110327}

Member Data Documentation

◆ ASCII_TO_LOWER_MAP

const uint8_t duckdb::StringUtil::ASCII_TO_LOWER_MAP
static
Initial value:
= {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97,
98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
120, 121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109,
110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131,
132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153,
154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197,
198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219,
220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255}

◆ ASCII_TO_UPPER_MAP

const uint8_t duckdb::StringUtil::ASCII_TO_UPPER_MAP
static
Initial value:
= {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65,
66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87,
88, 89, 90, 91, 92, 93, 94, 95, 96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123, 124, 125, 126, 127, 128, 129, 130, 131,
132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153,
154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197,
198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219,
220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255}

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