121851 {
121852using ::std::basic_stringstream;
121853using ::std::stringstream;
121854using ::std::wstringstream;
121855}
121856
121857#include <string>
121858#include <locale>
121859
121860namespace duckdb {
121861using std::string;
121862}
121863
121864namespace duckdb {
121865
121866template <class charT, class traits = std::char_traits<charT>, class Allocator = std::allocator<charT>>
121867class basic_stringstream : public duckdb_base_std::basic_stringstream<charT, traits, Allocator> {
121868public:
121869 using original = duckdb_base_std::basic_stringstream<charT, traits, Allocator>;
121870
121871 explicit basic_stringstream(std::ios_base::openmode which = std::ios_base::out | std::ios_base::in)
121872 : original(which) {
121873 this->imbue(std::locale::classic());
121874 }
121875 explicit basic_stringstream(const std::basic_string<charT, traits, Allocator> &s,
121876 std::ios_base::openmode which = std::ios_base::out | std::ios_base::in)
121877 : original(s, which) {
121878 this->imbue(std::locale::classic());
121879 }
121880 basic_stringstream(const basic_stringstream &) = delete;
121881 basic_stringstream(basic_stringstream &&rhs) noexcept;
121882};
121883
121884typedef basic_stringstream<char> stringstream;
121885}
121886
121887
121888
121889
121890
121891
121892
121893
121894
121895
121896
121897#ifndef DUCKDB_API
121898#if defined(_WIN32) && !defined(__MINGW32__)
121899#ifdef DUCKDB_STATIC_BUILD
121900#define DUCKDB_API
121901#else
121902#if defined(DUCKDB_BUILD_LIBRARY) && !defined(DUCKDB_BUILD_LOADABLE_EXTENSION)
121903#define DUCKDB_API __declspec(dllexport)
121904#else
121905#define DUCKDB_API __declspec(dllimport)
121906#endif
121907#endif
121908#else
121909#define DUCKDB_API
121910#endif
121911#endif
121912
121913#ifndef DUCKDB_EXTENSION_API
121914#ifdef _WIN32
121915#ifdef DUCKDB_STATIC_BUILD
121916#define DUCKDB_EXTENSION_API
121917#else
121918#define DUCKDB_EXTENSION_API __declspec(dllexport)
121919#endif
121920#else
121921#define DUCKDB_EXTENSION_API __attribute__((visibility("default")))
121922#endif
121923#endif
121924
121925
121926
121927
121928
121929
121930
121931
121932
121933
121934
121935
121936
121937
121938
121939
121940
121941
121942
121943
121944
121945
121946
121947
121948
121949
121950
121951#if ( \
121952 \
121953 !defined(DEBUG) && \
121954 \
121955 !defined(DUCKDB_FORCE_ASSERT) && \
121956 \
121957 !defined(__MVS__) \
121958)
121959
121960
121963#include <assert.h>
121964#define D_ASSERT assert
121965namespace duckdb {
121966DUCKDB_API void DuckDBAssertInternal(bool condition, const char *condition_name, const char *file, int linenr);
121967}
121968
121969#else
121970namespace duckdb {
121971DUCKDB_API void DuckDBAssertInternal(bool condition, const char *condition_name, const char *file, int linenr);
121972}
121973
121974#define D_ASSERT(condition) duckdb::DuckDBAssertInternal(bool(condition), #condition, __FILE__, __LINE__)
121975#define D_ASSERT_IS_ENABLED
121976
121977#endif
121978
121980#define ALWAYS_ASSERT(condition) duckdb::DuckDBAssertInternal(bool(condition), #condition, __FILE__, __LINE__)
121981
121982
121983
121984
121985
121986
121987
121988
121989
121990
121991
121992
121993
121994
121995
121996
121997#include <stdint.h>
121998
121999
122000
122001
122002
122003
122004
122005
122006
122007
122008#include <cstdint>
122009
122010namespace duckdb {
122011
122014
122017
122020
122023typedef data_t *data_ptr_t;
122024typedef const data_t *const_data_ptr_t;
122025
122030
122033
122038
122039template <class SRC>
122040data_ptr_t data_ptr_cast(SRC *src) {
122041 return reinterpret_cast<data_ptr_t>(src);
122042}
122043
122044template <class SRC>
122045const_data_ptr_t const_data_ptr_cast(const SRC *src) {
122046 return reinterpret_cast<const_data_ptr_t>(src);
122047}
122048
122049template <class SRC>
122050char *char_ptr_cast(SRC *src) {
122051 return reinterpret_cast<char *>(src);
122052}
122053
122054template <class SRC>
122055const char *const_char_ptr_cast(const SRC *src) {
122056 return reinterpret_cast<const char *>(src);
122057}
122058
122059template <class SRC>
122060const unsigned char *const_uchar_ptr_cast(const SRC *src) {
122061 return reinterpret_cast<const unsigned char *>(src);
122062}
122063
122064template <class SRC>
122065uintptr_t CastPointerToValue(SRC *src) {
122066 return reinterpret_cast<uintptr_t>(src);
122067}
122068
122069template <class SRC>
122070uint64_t cast_pointer_to_uint64(SRC *src) {
122071 return static_cast<uint64_t>(
reinterpret_cast<uintptr_t
>(src));
122072}
122073
122074template <class SRC = data_t>
122075SRC *cast_uint64_to_pointer(uint64_t value) {
122076 return reinterpret_cast<SRC *>(static_cast<uintptr_t>(value));
122077}
122078
122079}
122080
122081
122082namespace duckdb {
122083
122084
122085struct uhugeint_t;
122086
122087struct hugeint_t {
122088public:
122091
122092public:
122093 hugeint_t() = default;
122094 DUCKDB_API hugeint_t(int64_t value);
122095 constexpr hugeint_t(int64_t upper, uint64_t lower) : lower(lower), upper(upper) {
122096 }
122097 constexpr hugeint_t(const hugeint_t &rhs) = default;
122098 constexpr hugeint_t(hugeint_t &&rhs) = default;
122099 hugeint_t &
operator=(
const hugeint_t &rhs) =
default;
122100 hugeint_t &
operator=(hugeint_t &&rhs) =
default;
122101
122102 DUCKDB_API string ToString() const;
122103
122104
122105 DUCKDB_API
bool operator==(
const hugeint_t &rhs)
const;
122106 DUCKDB_API
bool operator!=(
const hugeint_t &rhs)
const;
122107 DUCKDB_API
bool operator<=(
const hugeint_t &rhs)
const;
122108 DUCKDB_API
bool operator<(
const hugeint_t &rhs)
const;
122109 DUCKDB_API
bool operator>(
const hugeint_t &rhs)
const;
122110 DUCKDB_API
bool operator>=(
const hugeint_t &rhs)
const;
122111
122112
122113 DUCKDB_API hugeint_t
operator+(
const hugeint_t &rhs)
const;
122114 DUCKDB_API hugeint_t
operator-(
const hugeint_t &rhs)
const;
122115 DUCKDB_API hugeint_t
operator*(
const hugeint_t &rhs)
const;
122116 DUCKDB_API hugeint_t
operator/(
const hugeint_t &rhs)
const;
122117 DUCKDB_API hugeint_t
operator%(
const hugeint_t &rhs)
const;
122118 DUCKDB_API hugeint_t
operator-()
const;
122119
122120
122121 DUCKDB_API hugeint_t
operator>>(
const hugeint_t &rhs)
const;
122122 DUCKDB_API hugeint_t
operator<<(
const hugeint_t &rhs)
const;
122123 DUCKDB_API hugeint_t
operator&(
const hugeint_t &rhs)
const;
122124 DUCKDB_API hugeint_t
operator|(
const hugeint_t &rhs)
const;
122125 DUCKDB_API hugeint_t
operator^(
const hugeint_t &rhs)
const;
122126 DUCKDB_API hugeint_t
operator~()
const;
122127
122128
122129 DUCKDB_API hugeint_t &
operator+=(
const hugeint_t &rhs);
122130 DUCKDB_API hugeint_t &
operator-=(
const hugeint_t &rhs);
122131 DUCKDB_API hugeint_t &
operator*=(
const hugeint_t &rhs);
122132 DUCKDB_API hugeint_t &
operator/=(
const hugeint_t &rhs);
122133 DUCKDB_API hugeint_t &
operator%=(
const hugeint_t &rhs);
122134 DUCKDB_API hugeint_t &operator>>=(const hugeint_t &rhs);
122135 DUCKDB_API hugeint_t &operator<<=(const hugeint_t &rhs);
122136 DUCKDB_API hugeint_t &
operator&=(
const hugeint_t &rhs);
122137 DUCKDB_API hugeint_t &
operator|=(
const hugeint_t &rhs);
122138 DUCKDB_API hugeint_t &
operator^=(
const hugeint_t &rhs);
122139
122140
122141 DUCKDB_API explicit operator bool() const;
122143
122144
122145 DUCKDB_API
explicit operator uint8_t()
const;
122146 DUCKDB_API
explicit operator uint16_t()
const;
122147 DUCKDB_API
explicit operator uint32_t()
const;
122148 DUCKDB_API
explicit operator uint64_t()
const;
122149 DUCKDB_API
explicit operator int8_t()
const;
122150 DUCKDB_API
explicit operator int16_t()
const;
122151 DUCKDB_API
explicit operator int32_t()
const;
122152 DUCKDB_API
explicit operator int64_t()
const;
122153 DUCKDB_API explicit operator uhugeint_t() const;
122154};
122155
122156}
122157
122158namespace std {
122159template <>
122160struct hash<duckdb::hugeint_t> {
122161 size_t operator()(
const duckdb::hugeint_t &val)
const {
122162 using std::hash;
122163 return hash<int64_t> {}(val.upper) ^ hash<uint64_t> {}(val.lower);
122164 }
122165};
122166}
122167
122168
122169#include <vector>
122170
122171namespace duckdb {
122172
122174
122175
122176
122177class SQLIdentifier {
122178public:
122179 explicit SQLIdentifier(const string &raw_string) : raw_string(raw_string) {
122180 }
122181
122182public:
122183 string raw_string;
122184};
122185
122186
122187
122188class SQLString {
122189public:
122190 explicit SQLString(const string &raw_string) : raw_string(raw_string) {
122191 }
122192
122193public:
122194 string raw_string;
122195};
122196
122198struct LogicalType;
122199
122200enum class ExceptionFormatValueType :
uint8_t {
122201 FORMAT_VALUE_TYPE_DOUBLE,
122202 FORMAT_VALUE_TYPE_INTEGER,
122203 FORMAT_VALUE_TYPE_STRING
122204};
122205
122206struct ExceptionFormatValue {
122207 DUCKDB_API ExceptionFormatValue(double dbl_val);
122208 DUCKDB_API ExceptionFormatValue(int64_t int_val);
122209 DUCKDB_API ExceptionFormatValue(idx_t uint_val);
122210 DUCKDB_API ExceptionFormatValue(string str_val);
122211 DUCKDB_API ExceptionFormatValue(
const String &str_val);
122212 DUCKDB_API ExceptionFormatValue(hugeint_t hg_val);
122213 DUCKDB_API ExceptionFormatValue(uhugeint_t uhg_val);
122214
122215 ExceptionFormatValueType type;
122216
122217 double dbl_val = 0;
122218 hugeint_t int_val = 0;
122219 string str_val;
122220
122221public:
122222 template <class T>
122223 static ExceptionFormatValue CreateFormatValue(const T &value) {
122225 }
122226 static string Format(const string &msg, std::vector<ExceptionFormatValue> &values);
122227};
122228
122229template <>
122230DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const PhysicalType &value);
122231template <>
122232DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const SQLString &value);
122233template <>
122234DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const SQLIdentifier &value);
122235template <>
122236DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const LogicalType &value);
122237template <>
122238DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const float &value);
122239template <>
122240DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const double &value);
122241template <>
122242DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const string &value);
122243template <>
122244DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(
const String &value);
122245template <>
122246DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const char *const &value);
122247template <>
122248DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(char *const &value);
122249template <>
122250DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const idx_t &value);
122251template <>
122252DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const hugeint_t &value);
122253template <>
122254DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const uhugeint_t &value);
122255
122256}
122257
122258
122259
122260
122261
122262
122263
122264
122265
122266
122267
122268#include <unordered_map>
122269
122270namespace duckdb {
122271using std::unordered_map;
122272}
122273
122274
122275
122276#include <vector>
122277#include <stdexcept>
122278
122279namespace duckdb {
122281struct LogicalType;
122282class Expression;
122283class ParsedExpression;
122284class QueryErrorContext;
122285class TableRef;
122286struct hugeint_t;
122287class optional_idx;
122288
122289inline void AssertRestrictFunction(const void *left_start, const void *left_end, const void *right_start,
122290 const void *right_end, const char *fname, int linenr) {
122291
122292#ifdef DEBUG
122293 if (!(left_end <= right_start || right_end <= left_start)) {
122294 printf(
"ASSERT RESTRICT FAILED: %s:%d\n", fname, linenr);
122295 D_ASSERT(0);
122296 }
122297#endif
122298}
122299
122300#define ASSERT_RESTRICT(left_start, left_end, right_start, right_end) \
122301 AssertRestrictFunction(left_start, left_end, right_start, right_end, __FILE__, __LINE__)
122302
122303
122304
122305
122306
122307enum class ExceptionType :
uint8_t {
122308 INVALID = 0,
122309 OUT_OF_RANGE = 1,
122310 CONVERSION = 2,
122311 UNKNOWN_TYPE = 3,
122312 DECIMAL = 4,
122313 MISMATCH_TYPE = 5,
122314 DIVIDE_BY_ZERO = 6,
122315 OBJECT_SIZE = 7,
122316 INVALID_TYPE = 8,
122317 SERIALIZATION = 9,
122318 TRANSACTION = 10,
122319 NOT_IMPLEMENTED = 11,
122320 EXPRESSION = 12,
122321 CATALOG = 13,
122322 PARSER = 14,
122323 PLANNER = 15,
122324 SCHEDULER = 16,
122325 EXECUTOR = 17,
122326 CONSTRAINT = 18,
122327 INDEX = 19,
122328 STAT = 20,
122329 CONNECTION = 21,
122330 SYNTAX = 22,
122331 SETTINGS = 23,
122332 BINDER = 24,
122333 NETWORK = 25,
122334 OPTIMIZER = 26,
122335 NULL_POINTER = 27,
122336 IO = 28,
122337 INTERRUPT = 29,
122338 FATAL = 30,
122339 INTERNAL = 31,
122340 INVALID_INPUT = 32,
122341 OUT_OF_MEMORY = 33,
122342 PERMISSION = 34,
122343 PARAMETER_NOT_RESOLVED = 35,
122344 PARAMETER_NOT_ALLOWED = 36,
122345 DEPENDENCY = 37,
122346 HTTP = 38,
122347 MISSING_EXTENSION = 39,
122348 AUTOLOAD = 40,
122349 SEQUENCE = 41,
122350 INVALID_CONFIGURATION =
122351 42
122352};
122353
122354class Exception : public std::runtime_error {
122355public:
122356 DUCKDB_API Exception(ExceptionType exception_type, const string &message);
122357
122358 DUCKDB_API Exception(const unordered_map<string, string> &extra_info, ExceptionType exception_type,
122359 const string &message);
122360
122361public:
122362 DUCKDB_API static string ExceptionTypeToString(ExceptionType type);
122363 DUCKDB_API static ExceptionType StringToExceptionType(const string &type);
122364
122365 template <typename... ARGS>
122366 static string ConstructMessage(const string &msg, ARGS const &...params) {
122367 const std::size_t num_args = sizeof...(ARGS);
122368 if (num_args == 0) {
122369 return msg;
122370 }
122371 std::vector<ExceptionFormatValue> values;
122372 return ConstructMessageRecursive(msg, values,
params...);
122373 }
122374
122375 DUCKDB_API static unordered_map<string, string> InitializeExtraInfo(const Expression &expr);
122376 DUCKDB_API static unordered_map<string, string> InitializeExtraInfo(const ParsedExpression &expr);
122377 DUCKDB_API static unordered_map<string, string> InitializeExtraInfo(const QueryErrorContext &error_context);
122378 DUCKDB_API static unordered_map<string, string> InitializeExtraInfo(const TableRef &ref);
122379 DUCKDB_API static unordered_map<string, string> InitializeExtraInfo(optional_idx error_location);
122380 DUCKDB_API static unordered_map<string, string> InitializeExtraInfo(const string &subtype,
122381 optional_idx error_location);
122382
122384 DUCKDB_API static bool IsExecutionError(ExceptionType type);
122385 DUCKDB_API static string ToJSON(ExceptionType type, const string &message);
122386
122387 DUCKDB_API static string ToJSON(const unordered_map<string, string> &extra_info, ExceptionType type,
122388 const string &message);
122389
122390 DUCKDB_API static bool InvalidatesTransaction(ExceptionType exception_type);
122391 DUCKDB_API static bool InvalidatesDatabase(ExceptionType exception_type);
122392
122393 DUCKDB_API static string ConstructMessageRecursive(const string &msg, std::vector<ExceptionFormatValue> &values);
122394
122395 template <class T, typename... ARGS>
122396 static string ConstructMessageRecursive(const string &msg, std::vector<ExceptionFormatValue> &values,
122397 const T ¶m, ARGS &&...params) {
122398 values.push_back(ExceptionFormatValue::CreateFormatValue<T>(param));
122399 return ConstructMessageRecursive(msg, values,
params...);
122400 }
122401
122402 DUCKDB_API static bool UncaughtException();
122403
122404 DUCKDB_API static string GetStackTrace(idx_t max_depth = 120);
122405 static string FormatStackTrace(const string &message = "") {
122406 return (message + "\n" + GetStackTrace());
122407 }
122408
122409 DUCKDB_API static void SetQueryLocation(optional_idx error_location, unordered_map<string, string> &extra_info);
122410};
122411
122412
122413
122414
122415class ConnectionException : public Exception {
122416public:
122417 DUCKDB_API explicit ConnectionException(const string &msg);
122418
122419 template <typename... ARGS>
122420 explicit ConnectionException(const string &msg, ARGS &&...params)
122421 : ConnectionException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122422 }
122423};
122424
122425class PermissionException : public Exception {
122426public:
122427 DUCKDB_API explicit PermissionException(const string &msg);
122428
122429 template <typename... ARGS>
122430 explicit PermissionException(const string &msg, ARGS &&...params)
122431 : PermissionException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122432 }
122433};
122434
122435class OutOfRangeException : public Exception {
122436public:
122437 DUCKDB_API explicit OutOfRangeException(const string &msg);
122438
122439 template <typename... ARGS>
122440 explicit OutOfRangeException(const string &msg, ARGS &&...params)
122441 : OutOfRangeException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122442 }
122443 DUCKDB_API OutOfRangeException(const int64_t value, const PhysicalType orig_type, const PhysicalType new_type);
122444 DUCKDB_API OutOfRangeException(const hugeint_t value, const PhysicalType orig_type, const PhysicalType new_type);
122445 DUCKDB_API OutOfRangeException(const double value, const PhysicalType orig_type, const PhysicalType new_type);
122446 DUCKDB_API OutOfRangeException(const PhysicalType var_type, const idx_t length);
122447};
122448
122449class OutOfMemoryException : public Exception {
122450public:
122451 DUCKDB_API explicit OutOfMemoryException(const string &msg);
122452
122453 template <typename... ARGS>
122454 explicit OutOfMemoryException(const string &msg, ARGS &&...params)
122455 : OutOfMemoryException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122456 }
122457
122458private:
122459 string ExtendOutOfMemoryError(const string &msg);
122460};
122461
122462class SyntaxException : public Exception {
122463public:
122464 DUCKDB_API explicit SyntaxException(const string &msg);
122465
122466 template <typename... ARGS>
122467 explicit SyntaxException(const string &msg, ARGS &&...params)
122468 : SyntaxException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122469 }
122470};
122471
122472class ConstraintException : public Exception {
122473public:
122474 DUCKDB_API explicit ConstraintException(const string &msg);
122475
122476 template <typename... ARGS>
122477 explicit ConstraintException(const string &msg, ARGS &&...params)
122478 : ConstraintException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122479 }
122480};
122481
122482class DependencyException : public Exception {
122483public:
122484 DUCKDB_API explicit DependencyException(const string &msg);
122485
122486 template <typename... ARGS>
122487 explicit DependencyException(const string &msg, ARGS &&...params)
122488 : DependencyException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122489 }
122490};
122491
122492class IOException : public Exception {
122493public:
122494 DUCKDB_API explicit IOException(const string &msg);
122495
122496 DUCKDB_API explicit IOException(const unordered_map<string, string> &extra_info, const string &msg);
122497 explicit IOException(ExceptionType exception_type, const string &msg) : Exception(exception_type, msg) {
122498 }
122499
122500 template <typename... ARGS>
122501 explicit IOException(const string &msg, ARGS &&...params)
122502 : IOException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122503 }
122504
122505 template <typename... ARGS>
122506 explicit IOException(const unordered_map<string, string> &extra_info, const string &msg, ARGS &&...params)
122507 : IOException(extra_info, ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122508 }
122509};
122510
122511class MissingExtensionException : public Exception {
122512public:
122513 DUCKDB_API explicit MissingExtensionException(const string &msg);
122514
122515 template <typename... ARGS>
122516 explicit MissingExtensionException(const string &msg, ARGS &&...params)
122517 : MissingExtensionException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122518 }
122519};
122520
122521class NotImplementedException : public Exception {
122522public:
122523 DUCKDB_API explicit NotImplementedException(const string &msg);
122524 explicit NotImplementedException(const unordered_map<string, string> &extra_info, const string &msg);
122525
122526 template <typename... ARGS>
122527 explicit NotImplementedException(const string &msg, ARGS &&...params)
122528 : NotImplementedException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122529 }
122530 template <typename... ARGS>
122531 explicit NotImplementedException(const unordered_map<string, string> &extra_info, const string &msg,
122532 ARGS &&...params)
122533 : NotImplementedException(extra_info, ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122534 }
122535};
122536
122537class AutoloadException : public Exception {
122538public:
122539 DUCKDB_API explicit AutoloadException(const string &extension_name, const string &message);
122540};
122541
122542class SerializationException : public Exception {
122543public:
122544 DUCKDB_API explicit SerializationException(const string &msg);
122545
122546 template <typename... ARGS>
122547 explicit SerializationException(const string &msg, ARGS &&...params)
122548 : SerializationException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122549 }
122550};
122551
122552class SequenceException : public Exception {
122553public:
122554 DUCKDB_API explicit SequenceException(const string &msg);
122555
122556 template <typename... ARGS>
122557 explicit SequenceException(const string &msg, ARGS &&...params)
122558 : SequenceException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122559 }
122560};
122561
122562class InterruptException : public Exception {
122563public:
122564 static constexpr const char *INTERRUPT_MESSAGE = "Interrupted!";
122565 DUCKDB_API InterruptException();
122566};
122567
122568class FatalException : public Exception {
122569public:
122570 explicit FatalException(const string &msg) : FatalException(ExceptionType::FATAL, msg) {
122571 }
122572 template <typename... ARGS>
122573 explicit FatalException(const string &msg, ARGS &&...params)
122574 : FatalException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122575 }
122576
122577protected:
122578 DUCKDB_API explicit FatalException(ExceptionType type, const string &msg);
122579 template <typename... ARGS>
122580 explicit FatalException(ExceptionType type, const string &msg, ARGS &&...params)
122581 : FatalException(type, ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122582 }
122583};
122584
122585class InternalException : public Exception {
122586public:
122587 DUCKDB_API explicit InternalException(const string &msg);
122588 InternalException(const unordered_map<string, string> &extra_info, const string &msg);
122589
122590 template <typename... ARGS>
122591 explicit InternalException(const string &msg, ARGS &&...params)
122592 : InternalException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122593 }
122594
122595 template <typename... ARGS>
122596 explicit InternalException(const unordered_map<string, string> &extra_info, const string &msg, ARGS &&...params)
122597 : InternalException(extra_info, ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122598 }
122599};
122600
122601class InvalidInputException : public Exception {
122602public:
122603 DUCKDB_API explicit InvalidInputException(const string &msg);
122604 DUCKDB_API explicit InvalidInputException(const unordered_map<string, string> &extra_info, const string &msg);
122605
122606 template <typename... ARGS>
122607 explicit InvalidInputException(const string &msg, ARGS &&...params)
122608 : InvalidInputException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122609 }
122610
122611 template <typename... ARGS>
122612 explicit InvalidInputException(const Expression &expr, const string &msg, ARGS &&...params)
122613 : InvalidInputException(Exception::InitializeExtraInfo(expr),
122614 ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122615 }
122616};
122617
122618class ExecutorException : public Exception {
122619public:
122620 DUCKDB_API explicit ExecutorException(const string &msg);
122621
122622 template <typename... ARGS>
122623 explicit ExecutorException(const string &msg, ARGS &&...params)
122624 : ExecutorException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122625 }
122626};
122627
122628class InvalidConfigurationException : public Exception {
122629public:
122630 DUCKDB_API explicit InvalidConfigurationException(const string &msg);
122631
122632 DUCKDB_API explicit InvalidConfigurationException(const unordered_map<string, string> &extra_info,
122633 const string &msg);
122634
122635 template <typename... ARGS>
122636 explicit InvalidConfigurationException(const string &msg, ARGS &&...params)
122637 : InvalidConfigurationException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122638 }
122639 template <typename... ARGS>
122640 explicit InvalidConfigurationException(const Expression &expr, const string &msg, ARGS &&...params)
122641 : InvalidConfigurationException(ConstructMessage(msg, std::forward<ARGS>(
params)...),
122642 Exception::InitializeExtraInfo(expr)) {
122643 }
122644};
122645
122646class InvalidTypeException : public Exception {
122647public:
122648 DUCKDB_API InvalidTypeException(PhysicalType type, const string &msg);
122649 DUCKDB_API InvalidTypeException(const LogicalType &type, const string &msg);
122650 DUCKDB_API explicit InvalidTypeException(const string &msg);
122651};
122652
122653class TypeMismatchException : public Exception {
122654public:
122655 DUCKDB_API TypeMismatchException(const PhysicalType type_1, const PhysicalType type_2, const string &msg);
122656 DUCKDB_API TypeMismatchException(const LogicalType &type_1, const LogicalType &type_2, const string &msg);
122657 DUCKDB_API TypeMismatchException(optional_idx error_location, const LogicalType &type_1, const LogicalType &type_2,
122658 const string &msg);
122659 DUCKDB_API explicit TypeMismatchException(const string &msg);
122660};
122661
122662class ParameterNotAllowedException : public Exception {
122663public:
122664 DUCKDB_API explicit ParameterNotAllowedException(const string &msg);
122665
122666 template <typename... ARGS>
122667 explicit ParameterNotAllowedException(const string &msg, ARGS &&...params)
122668 : ParameterNotAllowedException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
122669 }
122670};
122671
122675class ParameterNotResolvedException : public Exception {
122676public:
122677 DUCKDB_API explicit ParameterNotResolvedException();
122678};
122679
122680}
122681
122682
122683
122684
122685
122686
122687
122688
122689
122690
122691
122692#if __GNUC__
122693#define DUCKDB_BUILTIN_EXPECT(cond, expected_value) (__builtin_expect(cond, expected_value))
122694#else
122695#define DUCKDB_BUILTIN_EXPECT(cond, expected_value) (cond)
122696#endif
122697
122698#define DUCKDB_LIKELY(...) DUCKDB_BUILTIN_EXPECT((__VA_ARGS__), 1)
122699#define DUCKDB_UNLIKELY(...) DUCKDB_BUILTIN_EXPECT((__VA_ARGS__), 0)
122700
122701
122702
122703namespace duckdb {
122704
122705template <bool IS_ENABLED>
122706struct MemorySafety {
122707#ifdef DEBUG
122708
122709 static constexpr bool ENABLED = true;
122710#else
122711 static constexpr bool ENABLED = IS_ENABLED;
122712#endif
122713};
122714
122715}
122716
122717
122718
122719#include <memory>
122720
122721#define DUCKDB_BASE_STD
122722
122723namespace duckdb_base_std {
122724using ::std::make_shared;
122725using ::std::shared_ptr;
122726using ::std::unique_ptr;
122727
122728}
122729
122730
122731#include <type_traits>
122732
122733namespace duckdb {
122734
122735template <class DATA_TYPE, class DELETER = std::default_delete<DATA_TYPE>, bool SAFE = true>
122736class unique_ptr : public duckdb_base_std::unique_ptr<DATA_TYPE, DELETER> {
122737public:
122738 using original = duckdb_base_std::unique_ptr<DATA_TYPE, DELETER>;
122739 using original::original;
122740 using pointer = typename original::pointer;
122741
122742private:
122743 static inline void AssertNotNull(const bool null) {
122744#if defined(DUCKDB_DEBUG_NO_SAFETY) || defined(DUCKDB_CLANG_TIDY)
122745 return;
122746#else
122747 if (DUCKDB_UNLIKELY(null)) {
122748 throw duckdb::InternalException("Attempted to dereference unique_ptr that is NULL!");
122749 }
122750#endif
122751 }
122752
122753public:
122754 typename std::add_lvalue_reference<DATA_TYPE>::type
operator*()
const {
122755 const auto ptr = original::get();
122756 if (MemorySafety<SAFE>::ENABLED) {
122757 AssertNotNull(!ptr);
122758 }
122759 return *ptr;
122760 }
122761
122762 typename original::pointer operator->() const {
122763 const auto ptr = original::get();
122764 if (MemorySafety<SAFE>::ENABLED) {
122765 AssertNotNull(!ptr);
122766 }
122767 return ptr;
122768 }
122769
122770#ifdef DUCKDB_CLANG_TIDY
122771
122772 [[clang::reinitializes]]
122773#endif
122774 inline void
122775 reset(typename original::pointer ptr = typename original::pointer()) noexcept {
122776 original::reset(ptr);
122777 }
122778};
122779
122780template <class DATA_TYPE, class DELETER>
122781class unique_ptr<DATA_TYPE[], DELETER, true> : public duckdb_base_std::unique_ptr<DATA_TYPE[], DELETER> {
122782public:
122783 using original = duckdb_base_std::unique_ptr<DATA_TYPE[], DELETER>;
122784 using original::original;
122785
122786private:
122787 static inline void AssertNotNull(const bool null) {
122788#if defined(DUCKDB_DEBUG_NO_SAFETY) || defined(DUCKDB_CLANG_TIDY)
122789 return;
122790#else
122791 if (DUCKDB_UNLIKELY(null)) {
122792 throw duckdb::InternalException("Attempted to dereference unique_ptr that is NULL!");
122793 }
122794#endif
122795 }
122796
122797public:
122798 typename std::add_lvalue_reference<DATA_TYPE>::type operator[](size_t __i) const {
122799 const auto ptr = original::get();
122800 if (MemorySafety<true>::ENABLED) {
122801 AssertNotNull(!ptr);
122802 }
122803 return ptr[__i];
122804 }
122805};
122806
122807template <class DATA_TYPE, class DELETER, bool SAFE>
122808class unique_ptr<DATA_TYPE[], DELETER, SAFE> : public duckdb_base_std::unique_ptr<DATA_TYPE[], DELETER> {
122809public:
122810 using original = duckdb_base_std::unique_ptr<DATA_TYPE[], DELETER>;
122811 using original::original;
122812
122813private:
122814 static inline void AssertNotNull(const bool null) {
122815#if defined(DUCKDB_DEBUG_NO_SAFETY) || defined(DUCKDB_CLANG_TIDY)
122816 return;
122817#else
122818 if (DUCKDB_UNLIKELY(null)) {
122819 throw duckdb::InternalException("Attempted to dereference unique_ptr that is NULL!");
122820 }
122821#endif
122822 }
122823
122824public:
122825 typename std::add_lvalue_reference<DATA_TYPE>::type operator[](size_t __i) const {
122826 const auto ptr = original::get();
122827 if (MemorySafety<SAFE>::ENABLED) {
122828 AssertNotNull(!ptr);
122829 }
122830 return ptr[__i];
122831 }
122832};
122833
122834template <typename T>
122835using unique_array = unique_ptr<T[], std::default_delete<T[]>, true>;
122836
122837template <typename T>
122838using unsafe_unique_array = unique_ptr<T[], std::default_delete<T[]>, false>;
122839
122840template <typename T>
122841using unsafe_unique_ptr = unique_ptr<T, std::default_delete<T>, false>;
122842
122843}
122844
122845
122846
122847namespace duckdb {
122848class Serializer;
122849class Deserializer;
122850class BinarySerializer;
122851class BinaryDeserializer;
122852class WriteStream;
122853class ReadStream;
122854
122856#ifndef DUCKDB_DEBUG_MOVE
122857using std::move;
122858#endif
122859
122860
122861#define DEFAULT_SCHEMA "main"
122862#define INVALID_SCHEMA ""
122863#define INVALID_CATALOG ""
122864#define SYSTEM_CATALOG "system"
122865#define TEMP_CATALOG "temp"
122866#define IN_MEMORY_PATH ":memory:"
122867
122868DUCKDB_API bool IsInvalidSchema(const string &str);
122869DUCKDB_API bool IsInvalidCatalog(const string &str);
122870
122875DUCKDB_API
extern const column_t VIRTUAL_COLUMN_START;
122876DUCKDB_API bool IsRowIdColumnId(column_t column_id);
122877DUCKDB_API bool IsVirtualColumn(column_t column_id);
122878
122883
122888
122889extern const double PI;
122890
122891struct DConstants {
122893 static constexpr const idx_t INVALID_INDEX =
idx_t(-1);
122895 static constexpr const idx_t MAX_VECTOR_SIZE = 1ULL << 37ULL;
122896};
122897
122898struct LogicalIndex {
122899 explicit LogicalIndex(idx_t index) :
index(
index) {
122900 }
122901
122903
122904 inline bool operator==(
const LogicalIndex &rhs)
const {
122905 return index == rhs.index;
122906 };
122907 inline bool operator!=(
const LogicalIndex &rhs)
const {
122908 return index != rhs.index;
122909 };
122910 inline bool operator<(
const LogicalIndex &rhs)
const {
122911 return index < rhs.index;
122912 };
122913 bool IsValid() {
122914 return index != DConstants::INVALID_INDEX;
122915 }
122916};
122917
122918struct PhysicalIndex {
122919 explicit PhysicalIndex(idx_t index) :
index(
index) {
122920 }
122921
122923
122924 inline bool operator==(
const PhysicalIndex &rhs)
const {
122925 return index == rhs.index;
122926 };
122927 inline bool operator!=(
const PhysicalIndex &rhs)
const {
122928 return index != rhs.index;
122929 };
122930 inline bool operator<(
const PhysicalIndex &rhs)
const {
122931 return index < rhs.index;
122932 };
122933 bool IsValid() {
122934 return index != DConstants::INVALID_INDEX;
122935 }
122936};
122937
122938DUCKDB_API
bool IsPowerOfTwo(uint64_t
v);
122939DUCKDB_API
uint64_t NextPowerOfTwo(uint64_t
v);
122940DUCKDB_API
uint64_t PreviousPowerOfTwo(uint64_t
v);
122941
122942}
122943
122944
122945namespace duckdb {
122946
122947enum class ProfilerPrintFormat :
uint8_t { QUERY_TREE, JSON, QUERY_TREE_OPTIMIZER, NO_OUTPUT, HTML, GRAPHVIZ, MERMAID };
122948
122949}
122950
122951
122952
122953
122954
122955
122956
122957
122958
122959
122960
122961
122962
122963
122964
122965
122966
122967
122968
122969
122970
122971
122972
122973
122974
122975
122976
122977
122978
122979
122980
122981
122982
122983
122984
122985
122986
122987
122988
122989
122990
122991
122992
122993
122994
122995
122996
122997
122998
122999
123000
123001
123002
123003
123004
123005
123006
123007
123008
123009
123010
123011
123012
123013
123014
123015
123016
123017
123018
123019
123020
123021
123022
123023
123024
123025
123026
123027#include <stdint.h>
123028
123029namespace duckdb {
123030
123031
123032struct hugeint_t;
123033
123034struct uhugeint_t {
123035public:
123038
123039public:
123040 uhugeint_t() = default;
123041 DUCKDB_API uhugeint_t(uint64_t value);
123042 constexpr uhugeint_t(uint64_t upper, uint64_t lower) : lower(lower), upper(upper) {
123043 }
123044 constexpr uhugeint_t(const uhugeint_t &rhs) = default;
123045 constexpr uhugeint_t(uhugeint_t &&rhs) = default;
123046 uhugeint_t &
operator=(
const uhugeint_t &rhs) =
default;
123047 uhugeint_t &
operator=(uhugeint_t &&rhs) =
default;
123048
123049 DUCKDB_API string ToString() const;
123050
123051
123052 DUCKDB_API
bool operator==(
const uhugeint_t &rhs)
const;
123053 DUCKDB_API
bool operator!=(
const uhugeint_t &rhs)
const;
123054 DUCKDB_API
bool operator<=(
const uhugeint_t &rhs)
const;
123055 DUCKDB_API
bool operator<(
const uhugeint_t &rhs)
const;
123056 DUCKDB_API
bool operator>(
const uhugeint_t &rhs)
const;
123057 DUCKDB_API
bool operator>=(
const uhugeint_t &rhs)
const;
123058
123059
123060 DUCKDB_API uhugeint_t
operator+(
const uhugeint_t &rhs)
const;
123061 DUCKDB_API uhugeint_t
operator-(
const uhugeint_t &rhs)
const;
123062 DUCKDB_API uhugeint_t
operator*(
const uhugeint_t &rhs)
const;
123063 DUCKDB_API uhugeint_t
operator/(
const uhugeint_t &rhs)
const;
123064 DUCKDB_API uhugeint_t
operator%(
const uhugeint_t &rhs)
const;
123065 DUCKDB_API uhugeint_t
operator-()
const;
123066
123067
123068 DUCKDB_API uhugeint_t
operator>>(
const uhugeint_t &rhs)
const;
123069 DUCKDB_API uhugeint_t
operator<<(
const uhugeint_t &rhs)
const;
123070 DUCKDB_API uhugeint_t
operator&(
const uhugeint_t &rhs)
const;
123071 DUCKDB_API uhugeint_t
operator|(
const uhugeint_t &rhs)
const;
123072 DUCKDB_API uhugeint_t
operator^(
const uhugeint_t &rhs)
const;
123073 DUCKDB_API uhugeint_t
operator~()
const;
123074
123075
123076 DUCKDB_API uhugeint_t &
operator+=(
const uhugeint_t &rhs);
123077 DUCKDB_API uhugeint_t &
operator-=(
const uhugeint_t &rhs);
123078 DUCKDB_API uhugeint_t &
operator*=(
const uhugeint_t &rhs);
123079 DUCKDB_API uhugeint_t &
operator/=(
const uhugeint_t &rhs);
123080 DUCKDB_API uhugeint_t &
operator%=(
const uhugeint_t &rhs);
123081 DUCKDB_API uhugeint_t &operator>>=(const uhugeint_t &rhs);
123082 DUCKDB_API uhugeint_t &operator<<=(const uhugeint_t &rhs);
123083 DUCKDB_API uhugeint_t &
operator&=(
const uhugeint_t &rhs);
123084 DUCKDB_API uhugeint_t &
operator|=(
const uhugeint_t &rhs);
123085 DUCKDB_API uhugeint_t &
operator^=(
const uhugeint_t &rhs);
123086
123087
123088 DUCKDB_API explicit operator bool() const;
123090
123091
123092 DUCKDB_API
explicit operator uint8_t()
const;
123093 DUCKDB_API
explicit operator uint16_t()
const;
123094 DUCKDB_API
explicit operator uint32_t()
const;
123095 DUCKDB_API
explicit operator uint64_t()
const;
123096 DUCKDB_API
explicit operator int8_t()
const;
123097 DUCKDB_API
explicit operator int16_t()
const;
123098 DUCKDB_API
explicit operator int32_t()
const;
123099 DUCKDB_API
explicit operator int64_t()
const;
123100 DUCKDB_API operator hugeint_t() const;
123101};
123102
123103}
123104
123105namespace std {
123106template <>
123107struct hash<duckdb::uhugeint_t> {
123108 size_t operator()(
const duckdb::uhugeint_t &val)
const {
123109 using std::hash;
123110 return hash<uint64_t> {}(val.upper) ^ hash<uint64_t> {}(val.lower);
123111 }
123112};
123113}
123114
123115
123116#include <cstring>
123117
123118namespace duckdb {
123119
123120#ifndef DUCKDB_IS_BIG_ENDIAN
123121#if defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
123122#define DUCKDB_IS_BIG_ENDIAN 1
123123#else
123124#define DUCKDB_IS_BIG_ENDIAN 0
123125#endif
123126#endif
123127
123128#if defined(__clang__) || defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
123129#define BSWAP16(x) __builtin_bswap16(static_cast<uint16_t>(x))
123130#define BSWAP32(x) __builtin_bswap32(static_cast<uint32_t>(x))
123131#define BSWAP64(x) __builtin_bswap64(static_cast<uint64_t>(x))
123132#else
123133#define BSWAP16(x) ((uint16_t)((((uint16_t)(x)&0xff00) >> 8) | (((uint16_t)(x)&0x00ff) << 8)))
123134
123135#define BSWAP32(x) \
123136 ((uint32_t)((((uint32_t)(x)&0xff000000) >> 24) | (((uint32_t)(x)&0x00ff0000) >> 8) | \
123137 (((uint32_t)(x)&0x0000ff00) << 8) | (((uint32_t)(x)&0x000000ff) << 24)))
123138
123139#define BSWAP64(x) \
123140 ((uint64_t)((((uint64_t)(x)&0xff00000000000000ull) >> 56) | (((uint64_t)(x)&0x00ff000000000000ull) >> 40) | \
123141 (((uint64_t)(x)&0x0000ff0000000000ull) >> 24) | (((uint64_t)(x)&0x000000ff00000000ull) >> 8) | \
123142 (((uint64_t)(x)&0x00000000ff000000ull) << 8) | (((uint64_t)(x)&0x0000000000ff0000ull) << 24) | \
123143 (((uint64_t)(x)&0x000000000000ff00ull) << 40) | (((uint64_t)(x)&0x00000000000000ffull) << 56)))
123144#endif
123145
123146static inline int8_t BSwap(
const int8_t &x) {
123147 return x;
123148}
123149
123150static inline uint8_t BSwap(
const uint8_t &x) {
123151 return x;
123152}
123153
123154static inline uint16_t BSwap(
const uint16_t &x) {
123155 return BSWAP16(x);
123156}
123157
123158static inline int16_t BSwap(
const int16_t &x) {
123159 return static_cast<int16_t>(BSWAP16(x));
123160}
123161
123162static inline uint32_t BSwap(
const uint32_t &x) {
123163 return BSWAP32(x);
123164}
123165
123166static inline int32_t BSwap(
const int32_t &x) {
123167 return static_cast<int32_t>(BSWAP32(x));
123168}
123169
123170static inline uint64_t BSwap(
const uint64_t &x) {
123171 return BSWAP64(x);
123172}
123173
123174static inline int64_t BSwap(
const int64_t &x) {
123175 return static_cast<int64_t>(BSWAP64(x));
123176}
123177
123178static inline uhugeint_t BSwap(const uhugeint_t &x) {
123179 return uhugeint_t(BSWAP64(x.upper), BSWAP64(x.lower));
123180}
123181
123182static inline hugeint_t BSwap(const hugeint_t &x) {
123183 return hugeint_t(
static_cast<int64_t>(BSWAP64(x.upper)), BSWAP64(x.lower));
123184}
123185
123186static inline float BSwap(const float &x) {
123188 std::memcpy(&temp, &x, sizeof(temp));
123189 temp = BSWAP32(temp);
123190 float result;
123191 std::memcpy(&result, &temp, sizeof(result));
123192 return result;
123193}
123194
123195static inline double BSwap(const double &x) {
123197 std::memcpy(&temp, &x, sizeof(temp));
123198 temp = BSWAP64(temp);
123199 double result;
123200 std::memcpy(&result, &temp, sizeof(result));
123201 return result;
123202}
123203
123204template <class T>
123205static inline T BSwapIfLE(const T &x) {
123206#if DUCKDB_IS_BIG_ENDIAN
123207 return x;
123208#else
123209 return BSwap(x);
123210#endif
123211}
123212
123213template <class T>
123214static inline T BSwapIfBE(const T &x) {
123215#if DUCKDB_IS_BIG_ENDIAN
123216 return BSwap(x);
123217#else
123218 return x;
123219#endif
123220}
123221
123222}
123223
123224
123225
123226
123227
123228
123229
123230
123231
123232
123233
123234
123235
123236
123237
123238
123239
123240
123241#include <memory>
123242#include <type_traits>
123243
123244namespace duckdb {
123245
123246
123247
123248
123249
123250#if _LIBCPP_STD_VER >= 17
123251template <class U, class T>
123252struct __bounded_convertible_to_unbounded : std::false_type {};
123253
123254template <class _Up, std::size_t _Np, class T>
123255struct __bounded_convertible_to_unbounded<_Up[_Np], T> : std::is_same<std::remove_cv<T>, _Up[]> {};
123256
123257template <class U, class T>
123258struct compatible_with_t : std::_Or<std::is_convertible<U *, T *>, __bounded_convertible_to_unbounded<U, T>> {};
123259#else
123260template <class U, class T>
123261struct compatible_with_t : std::is_convertible<U *, T *> {};
123262#endif
123263
123264}
123265
123266
123267
123268
123269
123270namespace duckdb {
123271
123272template <typename T, bool SAFE = true>
123273class weak_ptr;
123274
123275template <class T>
123276class enable_shared_from_this;
123277
123278template <typename T, bool SAFE = true>
123279class shared_ptr {
123280public:
123281 using original = std::shared_ptr<T>;
123282 using element_type = typename original::element_type;
123283 using weak_type = weak_ptr<T, SAFE>;
123284
123285private:
123286 static inline void AssertNotNull(const bool null) {
123287#if defined(DUCKDB_DEBUG_NO_SAFETY) || defined(DUCKDB_CLANG_TIDY)
123288 return;
123289#else
123290 if (DUCKDB_UNLIKELY(null)) {
123291 throw duckdb::InternalException("Attempted to dereference shared_ptr that is NULL!");
123292 }
123293#endif
123294 }
123295
123296private:
123297 template <class U, bool SAFE_P>
123298 friend class weak_ptr;
123299
123300 template <class U, bool SAFE_P>
123301 friend class shared_ptr;
123302
123303 template <typename U, typename S>
123304 friend shared_ptr<S> shared_ptr_cast(shared_ptr<U> src);
123305
123306private:
123307 original internal;
123308
123309public:
123310
123311 shared_ptr() : internal() {
123312 }
123313 shared_ptr(std::nullptr_t) : internal(nullptr) {
123314 }
123315
123316
123317 template <class U, typename std::enable_if<compatible_with_t<U, T>::value, int>::type = 0>
123318 explicit shared_ptr(U *ptr) : internal(ptr) {
123319 __enable_weak_this(internal.get(), internal.get());
123320 }
123321
123322 template <typename DELETER>
123323 shared_ptr(T *ptr, DELETER deleter) : internal(ptr, deleter) {
123324 __enable_weak_this(internal.get(), internal.get());
123325 }
123326
123327
123328 template <class U>
123329 shared_ptr(const shared_ptr<U> &ref, T *ptr) noexcept : internal(ref.internal, ptr) {
123330 }
123331#if _LIBCPP_STD_VER >= 20
123332 template <class U>
123333 shared_ptr(shared_ptr<U> &&ref, T *ptr) noexcept : internal(std::move(ref.internal), ptr) {
123334 }
123335#endif
123336
123337
123338 template <class U, typename std::enable_if<compatible_with_t<U, T>::value, int>::type = 0>
123339 shared_ptr(const shared_ptr<U> &ref) noexcept : internal(ref.internal) {
123340 }
123341 shared_ptr(const shared_ptr &other) : internal(other.internal) {
123342 }
123343
123344 template <class U, typename std::enable_if<compatible_with_t<U, T>::value, int>::type = 0>
123345#ifdef DUCKDB_CLANG_TIDY
123346 [[clang::reinitializes]]
123347#endif
123348 shared_ptr(shared_ptr<U> &&ref) noexcept
123349 : internal(std::move(ref.internal)) {
123350 }
123351
123352#ifdef DUCKDB_CLANG_TIDY
123353 [[clang::reinitializes]]
123354#endif
123355 shared_ptr(shared_ptr<T, SAFE> &&other) noexcept
123356 : internal(std::move(other.internal)) {
123357 }
123358
123359
123360 explicit shared_ptr(std::shared_ptr<T> other) : internal(other) {
123361
123362
123363 __enable_weak_this(internal.get(), internal.get());
123364 }
123365
123366
123367 template <class U>
123368 explicit shared_ptr(weak_ptr<U> other) : internal(other.internal) {
123369 }
123370
123371
123372 template <class U, class DELETER, bool SAFE_P,
123373 typename std::enable_if<compatible_with_t<U, T>::value &&
123374 std::is_convertible<typename unique_ptr<U, DELETER>::pointer, T *>::value,
123375 int>::type = 0>
123376#ifdef DUCKDB_CLANG_TIDY
123377 [[clang::reinitializes]]
123378#endif
123379 shared_ptr(unique_ptr<U, DELETER, SAFE_P> &&other)
123380 : internal(std::move(other)) {
123381 __enable_weak_this(internal.get(), internal.get());
123382 }
123383
123384
123385 ~shared_ptr() = default;
123386
123387
123388 shared_ptr<T, SAFE> &
operator=(
const shared_ptr<T, SAFE> &other)
noexcept {
123389 if (this == &other) {
123390 return *this;
123391 }
123392
123393 shared_ptr(other).swap(*this);
123394 return *this;
123395 }
123396 template <class U, typename std::enable_if<compatible_with_t<U, T>::value, int>::type = 0>
123397 shared_ptr<T> &
operator=(
const shared_ptr<U> &other) {
123398 shared_ptr(other).swap(*this);
123399 return *this;
123400 }
123401
123402
123403 shared_ptr<T, SAFE> &
operator=(shared_ptr &&other)
noexcept {
123404
123405 shared_ptr(std::move(other)).swap(*this);
123406 return *this;
123407 }
123408 template <class U, typename std::enable_if<compatible_with_t<U, T>::value, int>::type = 0>
123409 shared_ptr<T, SAFE> &
operator=(shared_ptr<U> &&other) {
123410 shared_ptr(std::move(other)).swap(*this);
123411 return *this;
123412 }
123413
123414
123415 template <class U, class DELETER, bool SAFE_P,
123416 typename std::enable_if<compatible_with_t<U, T>::value &&
123417 std::is_convertible<typename unique_ptr<U, DELETER>::pointer, T *>::value,
123418 int>::type = 0>
123419 shared_ptr<T, SAFE> &
operator=(unique_ptr<U, DELETER, SAFE_P> &&ref) {
123420 shared_ptr(std::move(ref)).swap(*this);
123421 return *this;
123422 }
123423
123424#ifdef DUCKDB_CLANG_TIDY
123425 [[clang::reinitializes]]
123426#endif
123427 void
123428 reset() {
123429 internal.reset();
123430 }
123431 template <typename U>
123432#ifdef DUCKDB_CLANG_TIDY
123433 [[clang::reinitializes]]
123434#endif
123435 void
123436 reset(U *ptr) {
123437 internal.reset(ptr);
123438 }
123439 template <typename U, typename DELETER>
123440#ifdef DUCKDB_CLANG_TIDY
123441 [[clang::reinitializes]]
123442#endif
123443 void
123444 reset(U *ptr, DELETER deleter) {
123445 internal.reset(ptr, deleter);
123446 }
123447
123448 void swap(shared_ptr &r)
noexcept {
123449 internal.swap(r.internal);
123450 }
123451
123453 return internal.get();
123454 }
123455
123456 long use_count() const {
123457 return internal.use_count();
123458 }
123459
123460 explicit operator bool() const noexcept {
123461 return internal.operator bool();
123462 }
123463
123464 typename std::add_lvalue_reference<T>::type
operator*()
const {
123465 if (MemorySafety<SAFE>::ENABLED) {
123466 const auto ptr = internal.get();
123467 AssertNotNull(!ptr);
123468 return *ptr;
123469 } else {
123470 return *internal;
123471 }
123472 }
123473
123474 T *operator->() const {
123475 if (MemorySafety<SAFE>::ENABLED) {
123476 const auto ptr = internal.get();
123477 AssertNotNull(!ptr);
123478 return ptr;
123479 } else {
123480 return internal.operator->();
123481 }
123482 }
123483
123484
123485 template <typename U>
123486 bool operator==(
const shared_ptr<U> &other)
const noexcept {
123487 return internal == other.internal;
123488 }
123489 template <typename U>
123490 bool operator!=(
const shared_ptr<U> &other)
const noexcept {
123491 return internal != other.internal;
123492 }
123493
123494 bool operator==(std::nullptr_t)
const noexcept {
123495 return internal == nullptr;
123496 }
123497 bool operator!=(std::nullptr_t)
const noexcept {
123498 return internal != nullptr;
123499 }
123500
123501 template <typename U>
123502 bool operator<(
const shared_ptr<U> &other)
const noexcept {
123503 return internal < other.internal;
123504 }
123505 template <typename U>
123506 bool operator<=(
const shared_ptr<U> &other)
const noexcept {
123507 return internal <= other.internal;
123508 }
123509 template <typename U>
123510 bool operator>(
const shared_ptr<U> &other)
const noexcept {
123511 return internal > other.internal;
123512 }
123513 template <typename U>
123514 bool operator>=(
const shared_ptr<U> &other)
const noexcept {
123515 return internal >= other.internal;
123516 }
123517
123518 shared_ptr<T, SAFE> atomic_load() const {
123519 return shared_ptr<T, SAFE>(std::atomic_load(&internal));
123520 }
123521
123522 shared_ptr<T, SAFE> atomic_load(std::memory_order order) const {
123523 return shared_ptr<T, SAFE>(std::atomic_load_explicit(&internal, order));
123524 }
123525
123526 void atomic_store(const shared_ptr<T, SAFE> &new_ptr) {
123527 std::atomic_store(&internal, new_ptr.internal);
123528 }
123529
123530private:
123531
123532 template <class U, class V,
123533 typename std::enable_if<std::is_convertible<V *, const enable_shared_from_this<U> *>::value,
123534 int>::type = 0>
123535 void __enable_weak_this(const enable_shared_from_this<U> *object,
123536 V *ptr) noexcept {
123537 typedef typename std::remove_cv<U>::type non_const_u_t;
123538 if (object && object->__weak_this_.expired()) {
123539
123540
123541 auto non_const = const_cast<non_const_u_t *>(static_cast<const U *>(ptr));
123542 object->__weak_this_ = shared_ptr<non_const_u_t>(*this, non_const);
123543 }
123544 }
123545
123546 void __enable_weak_this(...) noexcept {
123547 }
123548};
123549
123550template <typename T>
123551using unsafe_shared_ptr = shared_ptr<T, false>;
123552
123553}
123554
123555
123556
123557
123558
123559namespace duckdb {
123560
123561template <typename T, bool SAFE>
123562class weak_ptr {
123563public:
123564 using original = std::weak_ptr<T>;
123565 using element_type = typename original::element_type;
123566
123567private:
123568 template <class U, bool SAFE_P>
123569 friend class shared_ptr;
123570
123571private:
123572 original internal;
123573
123574public:
123575
123576 weak_ptr() : internal() {
123577 }
123578
123579
123580 template <class U, typename std::enable_if<compatible_with_t<U, T>::value, int>::type = 0>
123581 weak_ptr(shared_ptr<U, SAFE> const &ptr) noexcept : internal(ptr.internal) {
123582 }
123583 weak_ptr(weak_ptr const &other) noexcept : internal(other.internal) {
123584 }
123585 template <class U, typename std::enable_if<compatible_with_t<U, T>::value, int>::type = 0>
123586 weak_ptr(weak_ptr<U> const &ptr) noexcept : internal(ptr.internal) {
123587 }
123588#ifdef DUCKDB_CLANG_TIDY
123589 [[clang::reinitializes]]
123590#endif
123591 weak_ptr(weak_ptr &&ptr) noexcept
123592 : internal(std::move(ptr.internal)) {
123593 }
123594 template <class U, typename std::enable_if<compatible_with_t<U, T>::value, int>::type = 0>
123595#ifdef DUCKDB_CLANG_TIDY
123596 [[clang::reinitializes]]
123597#endif
123598 weak_ptr(weak_ptr<U> &&ptr) noexcept
123599 : internal(std::move(ptr.internal)) {
123600 }
123601
123602
123603 ~weak_ptr() = default;
123604
123605
123606 weak_ptr &
operator=(
const weak_ptr &other) {
123607 if (this == &other) {
123608 return *this;
123609 }
123610 internal = other.internal;
123611 return *this;
123612 }
123613
123614 template <class U, typename std::enable_if<compatible_with_t<U, T>::value, int>::type = 0>
123615 weak_ptr &
operator=(
const shared_ptr<U, SAFE> &ptr) {
123616 internal = ptr.internal;
123617 return *this;
123618 }
123619
123620
123621#ifdef DUCKDB_CLANG_TIDY
123622
123623 [[clang::reinitializes]]
123624#endif
123625 void
123626 reset() {
123627 internal.reset();
123628 }
123629
123630
123631 long use_count() const {
123632 return internal.use_count();
123633 }
123634
123635 bool expired() const {
123636 return internal.expired();
123637 }
123638
123639 shared_ptr<T, SAFE> lock() const {
123640 return shared_ptr<T, SAFE>(internal.lock());
123641 }
123642
123643
123644 template <typename U>
123645 bool operator==(
const weak_ptr<U> &other)
const noexcept {
123646 return internal == other.internal;
123647 }
123648
123649 template <typename U>
123650 bool operator!=(
const weak_ptr<U> &other)
const noexcept {
123651 return internal != other.internal;
123652 }
123653
123654 template <typename U>
123655 bool operator<(
const weak_ptr<U> &other)
const noexcept {
123656 return internal < other.internal;
123657 }
123658
123659 template <typename U>
123660 bool operator<=(
const weak_ptr<U> &other)
const noexcept {
123661 return internal <= other.internal;
123662 }
123663
123664 template <typename U>
123665 bool operator>(
const weak_ptr<U> &other)
const noexcept {
123666 return internal > other.internal;
123667 }
123668
123669 template <typename U>
123670 bool operator>=(
const weak_ptr<U> &other)
const noexcept {
123671 return internal >= other.internal;
123672 }
123673};
123674
123675template <typename T>
123676using unsafe_weak_ptr = weak_ptr<T, false>;
123677
123678}
123679
123680
123681
123682
123683
123684
123685namespace duckdb {
123686
123687template <class T>
123688class enable_shared_from_this {
123689public:
123690 template <class U, bool SAFE>
123691 friend class shared_ptr;
123692
123693private:
123694 mutable weak_ptr<T> __weak_this_;
123695
123696protected:
123697 constexpr enable_shared_from_this() noexcept {
123698 }
123699 enable_shared_from_this(enable_shared_from_this const &) noexcept {
123700 }
123701 enable_shared_from_this &
operator=(enable_shared_from_this
const &)
noexcept {
123702 return *this;
123703 }
123704 ~enable_shared_from_this() {
123705 }
123706
123707public:
123708 shared_ptr<T> shared_from_this() {
123709 return shared_ptr<T>(__weak_this_);
123710 }
123711 shared_ptr<T const> shared_from_this() const {
123712 return shared_ptr<const T>(__weak_this_);
123713 }
123714
123715#if _LIBCPP_STD_VER >= 17
123716 weak_ptr<T> weak_from_this() noexcept {
123717 return __weak_this_;
123718 }
123719
123720 weak_ptr<const T> weak_from_this() const noexcept {
123721 return __weak_this_;
123722 }
123723#endif
123724};
123725
123726}
123727
123728
123729#include <string.h>
123730#include <type_traits>
123731
123732#ifdef _MSC_VER
123733#define suint64_t int64_t
123734#endif
123735
123736#if defined(_WIN32) || defined(_WIN64)
123737#define DUCKDB_WINDOWS
123738#elif defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))
123739#define DUCKDB_POSIX
123740#endif
123741
123742namespace duckdb {
123743
123744
123745#ifndef __has_cpp_attribute
123746#define __has_cpp_attribute(x) 0
123747#endif
123748#if __has_cpp_attribute(clang::fallthrough)
123749#define DUCKDB_EXPLICIT_FALLTHROUGH [[clang::fallthrough]]
123750#elif __has_cpp_attribute(gnu::fallthrough)
123751#define DUCKDB_EXPLICIT_FALLTHROUGH [[gnu::fallthrough]]
123752#else
123753#define DUCKDB_EXPLICIT_FALLTHROUGH
123754#endif
123755
123756template <class... T>
123757struct AlwaysFalse {
123758 static constexpr bool VALUE = false;
123759};
123760
123761template<typename T>
123762using reference = std::reference_wrapper<T>;
123763
123764template<class DATA_TYPE, bool SAFE = true>
123765struct TemplatedUniqueIf
123766{
123767 typedef unique_ptr<DATA_TYPE, std::default_delete<DATA_TYPE>, SAFE> templated_unique_single_t;
123768};
123769
123770template<class DATA_TYPE, size_t N>
123771struct TemplatedUniqueIf<DATA_TYPE[N]>
123772{
123773 typedef void TemplatedUniqueArrayKnownBound;
123774};
123775
123776template<class DATA_TYPE, class... ARGS>
123777inline
123778typename TemplatedUniqueIf<DATA_TYPE, true>::templated_unique_single_t
123779make_uniq(ARGS&&... args)
123780{
123781 return unique_ptr<DATA_TYPE, std::default_delete<DATA_TYPE>, true>(new DATA_TYPE(std::forward<ARGS>(args)...));
123782}
123783
123784template<class DATA_TYPE, class... ARGS>
123785inline
123786shared_ptr<DATA_TYPE>
123787make_shared_ptr(ARGS&&... args)
123788{
123789 return shared_ptr<DATA_TYPE>(duckdb_base_std::make_shared<DATA_TYPE>(std::forward<ARGS>(args)...));
123790}
123791
123792template<class DATA_TYPE, class... ARGS>
123793inline
123794typename TemplatedUniqueIf<DATA_TYPE, false>::templated_unique_single_t
123795make_unsafe_uniq(ARGS&&... args)
123796{
123797 return unique_ptr<DATA_TYPE, std::default_delete<DATA_TYPE>, false>(new DATA_TYPE(std::forward<ARGS>(args)...));
123798}
123799
123800template<class DATA_TYPE>
123801inline unique_ptr<DATA_TYPE[], std::default_delete<DATA_TYPE[]>, true>
123802make_uniq_array(size_t n)
123803{
123804 return unique_ptr<DATA_TYPE[], std::default_delete<DATA_TYPE[]>, true>(new DATA_TYPE[n]());
123805}
123806
123807template<class DATA_TYPE>
123808inline unique_ptr<DATA_TYPE[], std::default_delete<DATA_TYPE[]>, true>
123809make_uniq_array_uninitialized(size_t n)
123810{
123811 return unique_ptr<DATA_TYPE[], std::default_delete<DATA_TYPE[]>, true>(new DATA_TYPE[n]);
123812}
123813
123814template<class DATA_TYPE>
123815inline unique_ptr<DATA_TYPE[], std::default_delete<DATA_TYPE[]>, false>
123816make_unsafe_uniq_array(size_t n)
123817{
123818 return unique_ptr<DATA_TYPE[], std::default_delete<DATA_TYPE[]>, false>(new DATA_TYPE[n]());
123819}
123820
123821template<class DATA_TYPE>
123822inline unique_ptr<DATA_TYPE[], std::default_delete<DATA_TYPE[]>, false>
123823make_unsafe_uniq_array_uninitialized(size_t n)
123824{
123825 return unique_ptr<DATA_TYPE[], std::default_delete<DATA_TYPE[]>, false>(new DATA_TYPE[n]);
123826}
123827
123828template<class DATA_TYPE, class... ARGS>
123829 typename TemplatedUniqueIf<DATA_TYPE>::TemplatedUniqueArrayKnownBound
123830 make_uniq(ARGS&&...) = delete;
123831
123832
123833template <typename S, typename T, typename... ARGS>
123834unique_ptr<S> make_uniq_base(ARGS &&... args) {
123835 return unique_ptr<S>(new T(std::forward<ARGS>(args)...));
123836}
123837
123838#ifdef DUCKDB_ENABLE_DEPRECATED_API
123839template <typename S, typename T, typename... Args>
123840unique_ptr<S> make_unique_base(Args &&... args) {
123841 return unique_ptr<S>(new T(std::forward<Args>(args)...));
123842}
123843#endif
123844
123845template <typename SRC, typename TGT>
123846unique_ptr<TGT> unique_ptr_cast(unique_ptr<SRC> src) {
123847 return unique_ptr<TGT>(static_cast<TGT *>(src.release()));
123848}
123849
123850template <typename SRC, typename TGT>
123851shared_ptr<TGT> shared_ptr_cast(shared_ptr<SRC> src) {
123852 return shared_ptr<TGT>(std::static_pointer_cast<TGT, SRC>(src.internal));
123853}
123854
123855#ifdef DUCKDB_DEBUG_MOVE
123856template<class T>
123857typename std::remove_reference<T>::type&& move(T&& t) noexcept {
123858
123859 static_assert(sizeof(T) == 0, "Use std::move instead of unqualified move or duckdb::move");
123860}
123861#endif
123862
123863template <class T, class... ARGS>
123864static duckdb::unique_ptr<T> make_unique(ARGS&&... __args) {
123865#ifndef DUCKDB_ENABLE_DEPRECATED_API
123866 static_assert(sizeof(T) == 0, "Use make_uniq instead of make_unique!");
123867#endif
123868 return unique_ptr<T>(new T(std::forward<ARGS>(__args)...));
123869}
123870
123871template <class T, class... ARGS>
123872static duckdb::shared_ptr<T> make_shared(ARGS&&... __args) {
123873#ifndef DUCKDB_ENABLE_DEPRECATED_API
123874 static_assert(sizeof(T) == 0, "Use make_shared_ptr instead of make_shared!");
123875#endif
123876 return shared_ptr<T>(new T(std::forward<ARGS>(__args)...));
123877}
123878
123879template <typename T>
123880constexpr T MaxValue(T a, T b) {
123881 return a > b ? a : b;
123882}
123883
123884template <typename T>
123885constexpr T MinValue(T a, T b) {
123886 return a < b ? a : b;
123887}
123888
123890template <typename T>
123892 return MinValue(MaxValue(
v,
min),
max);
123893}
123894
123895template <typename T>
123896T AbsValue(T a) {
123897 return a < 0 ? -a : a;
123898}
123899
123901template<class T, T val=8, typename = typename std::enable_if<!std::is_pointer<T>::value>::type>
123903 return ((n + (val - 1)) / val) * val;
123904}
123905
123906template <class T>
123908 return ((n + (val - 1)) / val) * val;
123909}
123910
123911template<uintptr_t alignment, class T>
123912inline T *AlignPointer(T *addr) {
123913 static_assert((alignment & (alignment - 1)) == 0, "'alignment' has to be a power of 2");
123914 return reinterpret_cast<T *>((reinterpret_cast<uintptr_t>(addr) + alignment - 1) & ~(alignment - 1));
123915}
123916
123917template<class T, T val=8>
123918constexpr inline T AlignValueFloor(T n) {
123919 return (n / val) * val;
123920}
123921
123922template<class T, T val=8>
123923static inline bool ValueIsAligned(T n) {
123924 return (n % val) == 0;
123925}
123926
123927template <typename T>
123928T SignValue(T a) {
123929 return a < 0 ? -1 : 1;
123930}
123931
123932template <typename T>
123933const T Load(const_data_ptr_t ptr) {
123934 T ret;
123935 memcpy(&ret, ptr, sizeof(ret));
123936 return ret;
123937}
123938
123939template <typename T>
123940const T LoadLE(const_data_ptr_t ptr) {
123941 return BSwapIfBE(Load<T>(ptr));
123942}
123943
123944template <typename T>
123945void Store(const T &val, data_ptr_t ptr) {
123946 memcpy(ptr, (void *)&val, sizeof(val));
123947}
123948
123955template<class T>
123957 if (target.get() != source.get()) {
123958 target = source;
123959 }
123960}
123961
123962template<typename T>
123963using const_reference = std::reference_wrapper<const T>;
123964
123966template<class T>
123968 return &a.get() == &b.get();
123969}
123970
123971template<class T>
123973 return &a == &b;
123974}
123975
123976template<class T, class SRC>
123977void DynamicCastCheck(const SRC *source) {
123978#ifndef __APPLE__
123979
123980 D_ASSERT(reinterpret_cast<const T *>(source) == dynamic_cast<const T *>(source));
123981#endif
123982}
123983
123985template<typename T>
123986class PostIncrement {
123987public:
123988 explicit PostIncrement(T &t) : t(t) {
123989 }
123990 ~PostIncrement() {
123991 ++t;
123992 }
123993private:
123994 T &t;
123995};
123996
123997}
123998
123999
124000
124001
124002
124003
124004
124005
124006
124007
124008
124009
124010
124011
124012
124013
124014#include <vector>
124015
124016namespace duckdb {
124017
124018template <class DATA_TYPE, bool SAFE = true, class ALLOCATOR = std::allocator<DATA_TYPE>>
124019class vector : public std::vector<DATA_TYPE, ALLOCATOR> {
124020public:
124021 using original = std::vector<DATA_TYPE, ALLOCATOR>;
124022 using original::original;
124023 using value_type =
typename original::value_type;
124024 using allocator_type = typename original::allocator_type;
124025 using size_type = typename original::size_type;
124026 using difference_type = typename original::difference_type;
124027 using reference = typename original::reference;
124028 using const_reference = typename original::const_reference;
124029 using pointer = typename original::pointer;
124030 using const_pointer = typename original::const_pointer;
124031 using iterator = typename original::iterator;
124032 using const_iterator = typename original::const_iterator;
124033 using reverse_iterator = typename original::reverse_iterator;
124034 using const_reverse_iterator = typename original::const_reverse_iterator;
124035
124036private:
124037 static inline void AssertIndexInBounds(idx_t index, idx_t size) {
124038#if defined(DUCKDB_DEBUG_NO_SAFETY) || defined(DUCKDB_CLANG_TIDY)
124039 return;
124040#else
124041 if (DUCKDB_UNLIKELY(index >= size)) {
124042 throw InternalException("Attempted to access index %ld within vector of size %ld", index, size);
124043 }
124044#endif
124045 }
124046
124047public:
124048#ifdef DUCKDB_CLANG_TIDY
124049
124050 [[clang::reinitializes]]
124051#endif
124052 inline void
124053 clear() noexcept {
124054 original::clear();
124055 }
124056
124057
124058
124059 vector() = default;
124060 vector(original &&other) : original(std::move(other)) {
124061 }
124062 template <bool INTERNAL_SAFE>
124063 vector(vector<DATA_TYPE, INTERNAL_SAFE> &&other) : original(std::move(other)) {
124064 }
124065
124066 template <bool INTERNAL_SAFE = false>
124067 inline typename original::reference
get(
typename original::size_type __n) {
124068 if (MemorySafety<INTERNAL_SAFE>::ENABLED) {
124069 AssertIndexInBounds(__n, original::size());
124070 }
124071 return original::operator[](__n);
124072 }
124073
124074 template <bool INTERNAL_SAFE = false>
124075 inline typename original::const_reference
get(
typename original::size_type __n)
const {
124076 if (MemorySafety<INTERNAL_SAFE>::ENABLED) {
124077 AssertIndexInBounds(__n, original::size());
124078 }
124079 return original::operator[](__n);
124080 }
124081
124082 typename original::reference operator[](typename original::size_type __n) {
124084 }
124085 typename original::const_reference operator[](typename original::size_type __n) const {
124087 }
124088
124089 typename original::reference front() {
124091 }
124092
124093 typename original::const_reference front() const {
124095 }
124096
124097 typename original::reference back() {
124098 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
124099 throw InternalException("'back' called on an empty vector!");
124100 }
124101 return get<SAFE>(original::size() - 1);
124102 }
124103
124104 typename original::const_reference back() const {
124105 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
124106 throw InternalException("'back' called on an empty vector!");
124107 }
124108 return get<SAFE>(original::size() - 1);
124109 }
124110
124111 void unsafe_erase_at(idx_t idx) {
124112 original::erase(original::begin() + static_cast<typename original::iterator::difference_type>(idx));
124113 }
124114
124115 void erase_at(idx_t idx) {
124116 if (MemorySafety<SAFE>::ENABLED && idx > original::size()) {
124117 throw InternalException("Can't remove offset %d from vector of size %d", idx, original::size());
124118 }
124119 unsafe_erase_at(idx);
124120 }
124121};
124122
124123template <typename T>
124124using unsafe_vector = vector<T, false>;
124125
124126}
124127
124128
124129
124130
124131
124132
124133
124134
124135
124136
124137
124138
124139
124140
124141namespace duckdb {
124142
124143
124144
124145
124146enum class CatalogType :
uint8_t {
124147 INVALID = 0,
124149 SCHEMA_ENTRY = 2,
124150 VIEW_ENTRY = 3,
124151 INDEX_ENTRY = 4,
124152 PREPARED_STATEMENT = 5,
124153 SEQUENCE_ENTRY = 6,
124154 COLLATION_ENTRY = 7,
124155 TYPE_ENTRY = 8,
124156 DATABASE_ENTRY = 9,
124157 COORDINATE_SYSTEM_ENTRY = 10,
124158
124159
124160 TABLE_FUNCTION_ENTRY = 25,
124161 SCALAR_FUNCTION_ENTRY = 26,
124162 AGGREGATE_FUNCTION_ENTRY = 27,
124163 PRAGMA_FUNCTION_ENTRY = 28,
124164 COPY_FUNCTION_ENTRY = 29,
124165 MACRO_ENTRY = 30,
124166 TABLE_MACRO_ENTRY = 31,
124167
124168
124169 DELETED_ENTRY = 51,
124170 RENAMED_ENTRY = 52,
124171
124172
124173 SECRET_ENTRY = 71,
124174 SECRET_TYPE_ENTRY = 72,
124175 SECRET_FUNCTION_ENTRY = 73,
124176
124177
124178 DEPENDENCY_ENTRY = 100
124179
124180};
124181
124182DUCKDB_API string CatalogTypeToString(CatalogType type);
124183CatalogType CatalogTypeFromString(const string &type);
124184
124185}
124186
124187
124188
124189
124190
124191
124192
124193
124194
124195
124196
124197
124198#include <atomic>
124199
124200namespace duckdb {
124201
124202using std::atomic;
124203
124213
124214}
124215
124216
124217
124218
124219
124220
124221
124222
124223
124224
124225
124226
124227
124228
124229
124230namespace duckdb {
124231
124232template <class T, bool SAFE = true>
124233class optional_ptr {
124234public:
124235 optional_ptr() noexcept : ptr(nullptr) {
124236 }
124237 optional_ptr(T *ptr_p) : ptr(ptr_p) {
124238 }
124239 optional_ptr(T &ref) : ptr(&ref) {
124240 }
124241 optional_ptr(
const unique_ptr<T> &ptr_p) : ptr(ptr_p.
get()) {
124242 }
124243 optional_ptr(
const shared_ptr<T> &ptr_p) : ptr(ptr_p.
get()) {
124244 }
124245
124246 void CheckValid() const {
124247 if (MemorySafety<SAFE>::ENABLED) {
124248 if (!ptr) {
124249 throw InternalException("Attempting to dereference an optional pointer that is not set");
124250 }
124251 }
124252 }
124253
124254 operator bool() const {
124255 return ptr;
124256 }
124258 CheckValid();
124259 return *ptr;
124260 }
124262 CheckValid();
124263 return *ptr;
124264 }
124265 T *operator->() {
124266 CheckValid();
124267 return ptr;
124268 }
124269 const T *operator->() const {
124270 CheckValid();
124271 return ptr;
124272 }
124274
124275 return ptr;
124276 }
124277 const T *
get()
const {
124278
124279 return ptr;
124280 }
124281
124282 T *get_mutable() const {
124283
124284 return ptr;
124285 }
124286
124287 bool operator==(
const optional_ptr<T> &rhs)
const {
124288 return ptr == rhs.ptr;
124289 }
124290
124291 bool operator!=(
const optional_ptr<T> &rhs)
const {
124292 return ptr != rhs.ptr;
124293 }
124294
124295private:
124296 T *ptr;
124297};
124298
124299template <typename T>
124300using unsafe_optional_ptr = optional_ptr<T, false>;
124301
124302}
124303
124304
124305
124306
124307
124308
124309
124310
124311
124312
124313
124314
124315
124316
124317
124318
124319
124320
124321
124322
124323
124324
124325
124326
124327
124328
124329
124330
124331
124332
124333
124334
124335
124336
124337
124338
124339
124340namespace duckdb {
124341
124342class optional_idx {
124343 static constexpr const idx_t INVALID_INDEX =
idx_t(-1);
124344
124345public:
124346 optional_idx() :
index(INVALID_INDEX) {
124347 }
124349 if (index == INVALID_INDEX) {
124350 throw InternalException("optional_idx cannot be initialized with an invalid index");
124351 }
124352 }
124353
124354 static optional_idx Invalid() {
124355 return optional_idx();
124356 }
124357
124358 bool IsValid() const {
124359 return index != INVALID_INDEX;
124360 }
124361
124362 void SetInvalid() {
124363 index = INVALID_INDEX;
124364 }
124365
124366 idx_t GetIndex()
const {
124367 if (index == INVALID_INDEX) {
124368 throw InternalException("Attempting to get the index of an optional_idx that is not set");
124369 }
124371 }
124372
124373 inline bool operator==(
const optional_idx &rhs)
const {
124374 return index == rhs.index;
124375 }
124376
124377 inline bool operator!=(
const optional_idx &rhs)
const {
124378 return index != rhs.index;
124379 }
124380
124381private:
124383};
124384
124385}
124386
124387
124388namespace duckdb {
124389class ParsedExpression;
124390
124391class QueryErrorContext {
124392public:
124393 QueryErrorContext(const ParsedExpression &expr);
124394 explicit QueryErrorContext(optional_idx query_location_p = optional_idx()) : query_location(query_location_p) {
124395 }
124396
124398 optional_idx query_location;
124399
124400public:
124401 static string Format(const string &query, const string &error_message, optional_idx error_loc,
124402 bool add_line_indicator = true);
124403};
124404
124405}
124406
124407
124408
124409namespace duckdb {
124410struct EntryLookupInfo;
124411
124412class CatalogException : public Exception {
124413public:
124414 DUCKDB_API explicit CatalogException(const string &msg);
124415
124416 DUCKDB_API explicit CatalogException(const unordered_map<string, string> &extra_info, const string &msg);
124417
124418 template <typename... ARGS>
124419 explicit CatalogException(const string &msg, ARGS &&...params)
124420 : CatalogException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
124421 }
124422
124423 template <typename... ARGS>
124424 explicit CatalogException(QueryErrorContext error_context, const string &msg, ARGS &&...params)
124425 : CatalogException(Exception::InitializeExtraInfo(error_context),
124426 ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
124427 }
124428
124429 static CatalogException MissingEntry(const EntryLookupInfo &lookup_info, const string &suggestion);
124430 static CatalogException MissingEntry(CatalogType type, const string &name, const string &suggestion,
124431 QueryErrorContext context = QueryErrorContext());
124432 static CatalogException MissingEntry(const string &type, const string &name, const vector<string> &suggestions,
124433 QueryErrorContext context = QueryErrorContext());
124434 static CatalogException EntryAlreadyExists(CatalogType type, const string &name,
124435 QueryErrorContext context = QueryErrorContext());
124436};
124437
124438}
124439
124440
124441
124442
124443
124444
124445
124446
124447
124448
124449
124450
124451
124452
124453
124454
124455
124456
124457
124458
124459
124460
124461
124462
124463
124464
124465
124466
124467
124468namespace duckdb {
124469
124470class Serializer;
124471class Deserializer;
124472class Value;
124473class TypeCatalogEntry;
124474class Vector;
124475class ClientContext;
124476class ParsedExpression;
124477class CoordinateReferenceSystem;
124478
124479struct string_t;
124480
124481template <class T>
124482using child_list_t = vector<std::pair<std::string, T>>;
124484template <class T>
124486
124487template <class T, typename... ARGS>
124488buffer_ptr<T> make_buffer(ARGS &&...args) {
124489 return make_shared_ptr<T>(std::forward<ARGS>(args)...);
124490}
124491
124492struct list_entry_t {
124493 list_entry_t() = default;
124494 list_entry_t(uint64_t offset, uint64_t length) : offset(offset), length(length) {
124495 }
124496 inline constexpr bool operator!=(
const list_entry_t &other)
const {
124497 return !(*this == other);
124498 }
124499 inline constexpr bool operator==(
const list_entry_t &other)
const {
124500 return offset == other.offset && length == other.length;
124501 }
124502
124505};
124506
124508
124509
124510
124511
124512
124513
124516
124517
124520
124523
124526
124529
124532
124535
124538
124541
124544
124546
124547
124550
124553
124555
124556
124558
124559
124561
124562
124564
124565
124567
124568
124571
124572
124575
124576
124579
124580
124582 INTERVAL = 21,
124583
124586
124587
124590
124592 STRUCT = 24,
124593
124595
124596
124601
124602
124604
124605
124607 ARRAY = 29,
124608
124611
124612
124614
124615
124617
124618
124620
124621
124623 VARCHAR = 200,
124624 UINT128 = 203,
124625 INT128 = 204,
124626 UNKNOWN = 205,
124628 BIT = 206,
124629
124630 INVALID = 255
124631};
124632
124633
124634
124635
124637 INVALID = 0,
124638 SQLNULL = 1,
124639 UNKNOWN = 2,
124640 ANY = 3,
124641 UNBOUND = 4,
124642
124643
124644
124645
124646
124647
124648 TEMPLATE = 5,
124649
124651
124653 TINYINT = 11,
124654 SMALLINT = 12,
124655 INTEGER = 13,
124656 BIGINT = 14,
124657 DATE = 15,
124658 TIME = 16,
124659 TIMESTAMP_SEC = 17,
124660 TIMESTAMP_MS = 18,
124661 TIMESTAMP = 19,
124663 DECIMAL = 21,
124666 CHAR = 24,
124667 VARCHAR = 25,
124668 BLOB = 26,
124669 INTERVAL = 27,
124670 UTINYINT = 28,
124671 USMALLINT = 29,
124672 UINTEGER = 30,
124673 UBIGINT = 31,
124674 TIMESTAMP_TZ = 32,
124675 TIME_TZ = 34,
124676 TIME_NS = 35,
124677 BIT = 36,
124678 STRING_LITERAL = 37,
124679 INTEGER_LITERAL = 38,
124680 BIGNUM = 39,
124681 UHUGEINT = 49,
124682 HUGEINT = 50,
124683 POINTER = 51,
124684 VALIDITY = 53,
124685 UUID = 54,
124686
124687 GEOMETRY = 60,
124688
124689 STRUCT = 100,
124691 MAP = 102,
124692 TABLE = 103,
124693 ENUM = 104,
124694 AGGREGATE_STATE = 105,
124695 LAMBDA = 106,
124696 UNION = 107,
124697 ARRAY = 108,
124698 VARIANT = 109
124699};
124700
124701struct ExtraTypeInfo;
124702struct ExtensionTypeInfo;
124703
124704struct aggregate_state_t;
124705
124706struct LogicalType {
124707 DUCKDB_API LogicalType();
124708 DUCKDB_API LogicalType(LogicalTypeId id);
124709 DUCKDB_API LogicalType(LogicalTypeId id, shared_ptr<ExtraTypeInfo> type_info);
124710 DUCKDB_API LogicalType(const LogicalType &other);
124711 DUCKDB_API LogicalType(LogicalType &&other) noexcept;
124712
124713 DUCKDB_API ~LogicalType();
124714
124716 return id_;
124717 }
124719 return physical_type_;
124720 }
124721 inline const optional_ptr<ExtraTypeInfo> AuxInfo() const {
124722 return type_info_.get();
124723 }
124724 inline bool IsNested() const {
124725 auto internal = InternalType();
124726 if (internal == PhysicalType::STRUCT) {
124727 return true;
124728 }
124729 if (internal == PhysicalType::LIST) {
124730 return true;
124731 }
124732 if (internal == PhysicalType::ARRAY) {
124733 return true;
124734 }
124735 return false;
124736 }
124737 inline bool IsUnknown() const {
124738 return id_ == LogicalTypeId::UNKNOWN;
124739 }
124740 inline bool IsUnbound() const {
124741 return id_ == LogicalTypeId::UNBOUND;
124742 }
124743
124744 inline shared_ptr<ExtraTypeInfo> GetAuxInfoShrPtr() const {
124745 return type_info_;
124746 }
124747
124749 LogicalType Copy() const;
124751 LogicalType DeepCopy() const;
124752
124753 inline void CopyAuxInfo(const LogicalType &other) {
124754 type_info_ = other.type_info_;
124755 }
124756 bool EqualTypeInfo(const LogicalType &rhs) const;
124757
124758
124759 inline LogicalType &
operator=(
const LogicalType &other) {
124760 if (this == &other) {
124761 return *this;
124762 }
124763 id_ = other.id_;
124764 physical_type_ = other.physical_type_;
124765 type_info_ = other.type_info_;
124766 return *this;
124767 }
124768
124769 inline LogicalType &
operator=(LogicalType &&other)
noexcept {
124770 id_ = other.id_;
124771 physical_type_ = other.physical_type_;
124772 std::swap(type_info_, other.type_info_);
124773 return *this;
124774 }
124775
124776 DUCKDB_API
bool operator==(
const LogicalType &rhs)
const;
124777 inline bool operator!=(
const LogicalType &rhs)
const {
124778 return !(*this == rhs);
124779 }
124780
124781 DUCKDB_API void Serialize(Serializer &serializer) const;
124782 DUCKDB_API static LogicalType Deserialize(Deserializer &deserializer);
124783
124784 static bool TypeIsTimestamp(LogicalTypeId id) {
124785 return (id == LogicalTypeId::TIMESTAMP || id == LogicalTypeId::TIMESTAMP_MS ||
124786 id == LogicalTypeId::TIMESTAMP_NS || id == LogicalTypeId::TIMESTAMP_SEC ||
124787 id == LogicalTypeId::TIMESTAMP_TZ);
124788 }
124789 static bool TypeIsTimestamp(const LogicalType &type) {
124790 return TypeIsTimestamp(type.id());
124791 }
124792 DUCKDB_API string ToString() const;
124793 DUCKDB_API bool IsIntegral() const;
124794 DUCKDB_API bool IsFloating() const;
124795 DUCKDB_API bool IsNumeric() const;
124796 DUCKDB_API static bool IsNumeric(LogicalTypeId type);
124797 DUCKDB_API bool IsTemporal() const;
124798 DUCKDB_API
hash_t Hash()
const;
124799 DUCKDB_API void SetAlias(string alias);
124800 DUCKDB_API bool HasAlias() const;
124801 DUCKDB_API string GetAlias() const;
124802
124803 DUCKDB_API bool HasExtensionInfo() const;
124804 DUCKDB_API optional_ptr<const ExtensionTypeInfo> GetExtensionInfo() const;
124805 DUCKDB_API optional_ptr<ExtensionTypeInfo> GetExtensionInfo();
124806 DUCKDB_API void SetExtensionInfo(unique_ptr<ExtensionTypeInfo> info);
124807
124809 DUCKDB_API static LogicalType MaxLogicalType(ClientContext &context, const LogicalType &left, const LogicalType &right);
124810 DUCKDB_API static bool TryGetMaxLogicalType(ClientContext &context, const LogicalType &left, const LogicalType &right, LogicalType &result);
124811 DUCKDB_API static bool TryGetMaxLogicalTypeUnchecked(const LogicalType &left, const LogicalType &right, LogicalType &result);
124813 DUCKDB_API static LogicalType ForceMaxLogicalType(const LogicalType &left, const LogicalType &right);
124815 DUCKDB_API static LogicalType NormalizeType(const LogicalType &type);
124816
124817
124819 DUCKDB_API bool GetDecimalProperties(uint8_t &width, uint8_t &scale) const;
124820
124821 DUCKDB_API void Verify() const;
124822
124823 DUCKDB_API bool IsSigned() const;
124824 DUCKDB_API bool IsUnsigned() const;
124825
124826 DUCKDB_API bool IsValid() const;
124827 DUCKDB_API bool IsComplete() const;
124828 DUCKDB_API bool IsTemplated() const;
124829
124831 bool SupportsRegularUpdate() const;
124832
124833
124834private:
124837 shared_ptr<ExtraTypeInfo> type_info_;
124838
124839private:
124841
124842public:
124843 static constexpr const LogicalTypeId SQLNULL = LogicalTypeId::SQLNULL;
124844 static constexpr const LogicalTypeId UNKNOWN = LogicalTypeId::UNKNOWN;
124846 static constexpr const LogicalTypeId TINYINT = LogicalTypeId::TINYINT;
124847 static constexpr const LogicalTypeId UTINYINT = LogicalTypeId::UTINYINT;
124848 static constexpr const LogicalTypeId SMALLINT = LogicalTypeId::SMALLINT;
124849 static constexpr const LogicalTypeId USMALLINT = LogicalTypeId::USMALLINT;
124850 static constexpr const LogicalTypeId INTEGER = LogicalTypeId::INTEGER;
124851 static constexpr const LogicalTypeId UINTEGER = LogicalTypeId::UINTEGER;
124852 static constexpr const LogicalTypeId BIGINT = LogicalTypeId::BIGINT;
124853 static constexpr const LogicalTypeId UBIGINT = LogicalTypeId::UBIGINT;
124856 static constexpr const LogicalTypeId DATE = LogicalTypeId::DATE;
124857 static constexpr const LogicalTypeId TIMESTAMP = LogicalTypeId::TIMESTAMP;
124858 static constexpr const LogicalTypeId TIMESTAMP_S = LogicalTypeId::TIMESTAMP_SEC;
124859 static constexpr const LogicalTypeId TIMESTAMP_MS = LogicalTypeId::TIMESTAMP_MS;
124861 static constexpr const LogicalTypeId TIME = LogicalTypeId::TIME;
124862 static constexpr const LogicalTypeId TIME_NS = LogicalTypeId::TIME_NS;
124863 static constexpr const LogicalTypeId TIMESTAMP_TZ = LogicalTypeId::TIMESTAMP_TZ;
124864 static constexpr const LogicalTypeId TIME_TZ = LogicalTypeId::TIME_TZ;
124865 static constexpr const LogicalTypeId VARCHAR = LogicalTypeId::VARCHAR;
124866 static constexpr const LogicalTypeId ANY = LogicalTypeId::ANY;
124867 static constexpr const LogicalTypeId BLOB = LogicalTypeId::BLOB;
124868 static constexpr const LogicalTypeId BIT = LogicalTypeId::BIT;
124869 static constexpr const LogicalTypeId BIGNUM = LogicalTypeId::BIGNUM;
124870
124871 static constexpr const LogicalTypeId INTERVAL = LogicalTypeId::INTERVAL;
124872 static constexpr const LogicalTypeId HUGEINT = LogicalTypeId::HUGEINT;
124873 static constexpr const LogicalTypeId UHUGEINT = LogicalTypeId::UHUGEINT;
124874 static constexpr const LogicalTypeId UUID = LogicalTypeId::UUID;
124875 static constexpr const LogicalTypeId HASH = LogicalTypeId::UBIGINT;
124876 static constexpr const LogicalTypeId POINTER = LogicalTypeId::POINTER;
124877 static constexpr const LogicalTypeId TABLE = LogicalTypeId::TABLE;
124878 static constexpr const LogicalTypeId LAMBDA = LogicalTypeId::LAMBDA;
124879 static constexpr const LogicalTypeId INVALID = LogicalTypeId::INVALID;
124881
124882
124883 DUCKDB_API static LogicalType DECIMAL(uint8_t width, uint8_t scale);
124884 DUCKDB_API static LogicalType VARCHAR_COLLATION(string collation);
124885 DUCKDB_API
static LogicalType
LIST(
const LogicalType &child);
124886 DUCKDB_API static LogicalType STRUCT(child_list_t<LogicalType> children);
124887 DUCKDB_API static LogicalType AGGREGATE_STATE(aggregate_state_t state_type);
124888 DUCKDB_API static LogicalType MAP(const LogicalType &child);
124889 DUCKDB_API static LogicalType MAP(LogicalType key, LogicalType value);
124890 DUCKDB_API static LogicalType UNION(child_list_t<LogicalType> members);
124891 DUCKDB_API static LogicalType ARRAY(const LogicalType &child, optional_idx index);
124892 DUCKDB_API static LogicalType ENUM(Vector &ordered_data, idx_t size);
124893 DUCKDB_API static LogicalType GEOMETRY();
124894 DUCKDB_API static LogicalType GEOMETRY(const string &crs);
124895 DUCKDB_API static LogicalType GEOMETRY(const CoordinateReferenceSystem &crs);
124896
124897 DUCKDB_API static LogicalType ANY_PARAMS(LogicalType target, idx_t cast_score = 5);
124898 DUCKDB_API static LogicalType TEMPLATE(const string &name);
124899 DUCKDB_API static LogicalType VARIANT();
124901 DUCKDB_API static LogicalType INTEGER_LITERAL(const Value &constant);
124902
124903 DUCKDB_API static LogicalType ENUM(const string &enum_name, Vector &ordered_data, idx_t size);
124904 DUCKDB_API static LogicalType UNBOUND(unique_ptr<ParsedExpression> expr);
124905 DUCKDB_API
static LogicalType
TYPE();
124907 DUCKDB_API static const vector<LogicalType> Numeric();
124909 DUCKDB_API static const vector<LogicalType> Integral();
124911 DUCKDB_API static const vector<LogicalType> Real();
124913 DUCKDB_API static const vector<LogicalType> AllTypes();
124914
124915public:
124917 static constexpr auto JSON_TYPE_NAME = "JSON";
124918 DUCKDB_API static LogicalType JSON();
124919 DUCKDB_API bool IsJSONType() const;
124920};
124921
124922struct DecimalType {
124923 DUCKDB_API
static uint8_t GetWidth(
const LogicalType &type);
124924 DUCKDB_API
static uint8_t GetScale(
const LogicalType &type);
124925 DUCKDB_API
static uint8_t MaxWidth();
124926};
124927
124928struct StringType {
124929 DUCKDB_API static string GetCollation(const LogicalType &type);
124930};
124931
124932struct ListType {
124933 DUCKDB_API static const LogicalType &GetChildType(const LogicalType &type);
124934};
124935
124936
124937struct UnboundType {
124938
124939 DUCKDB_API static LogicalType TryParseAndDefaultBind(const string &type_str);
124940 DUCKDB_API static LogicalType TryDefaultBind(const LogicalType &unbound_type);
124941 DUCKDB_API static const unique_ptr<ParsedExpression> &GetTypeExpression(const LogicalType &type);
124942};
124943
124944struct EnumType {
124945 DUCKDB_API
static int64_t GetPos(
const LogicalType &type,
const string_t &key);
124946 DUCKDB_API static const Vector &GetValuesInsertOrder(const LogicalType &type);
124947 DUCKDB_API
static idx_t GetSize(
const LogicalType &type);
124948 DUCKDB_API static const string GetValue(const Value &val);
124949 DUCKDB_API
static PhysicalType GetPhysicalType(
const LogicalType &type);
124950 DUCKDB_API static string_t GetString(const LogicalType &type, idx_t pos);
124951};
124952
124953struct StructType {
124954 DUCKDB_API static const child_list_t<LogicalType> &GetChildTypes(const LogicalType &type);
124955 DUCKDB_API static const LogicalType &GetChildType(const LogicalType &type, idx_t index);
124956 DUCKDB_API static const string &GetChildName(const LogicalType &type, idx_t index);
124957 DUCKDB_API
static idx_t GetChildIndexUnsafe(
const LogicalType &type,
const string &name);
124958 DUCKDB_API
static idx_t GetChildCount(
const LogicalType &type);
124959 DUCKDB_API static bool IsUnnamed(const LogicalType &type);
124960};
124961
124962struct MapType {
124963 DUCKDB_API
static const LogicalType &
KeyType(
const LogicalType &type);
124964 DUCKDB_API static const LogicalType &ValueType(const LogicalType &type);
124965};
124966
124967struct UnionType {
124968 DUCKDB_API
static const idx_t MAX_UNION_MEMBERS = 256;
124969 DUCKDB_API
static idx_t GetMemberCount(
const LogicalType &type);
124970 DUCKDB_API static const LogicalType &GetMemberType(const LogicalType &type, idx_t index);
124971 DUCKDB_API static const string &GetMemberName(const LogicalType &type, idx_t index);
124972 DUCKDB_API static const child_list_t<LogicalType> CopyMemberTypes(const LogicalType &type);
124973};
124974
124975struct ArrayType {
124976 DUCKDB_API static const LogicalType &GetChildType(const LogicalType &type);
124977 DUCKDB_API
static idx_t GetSize(
const LogicalType &type);
124978 DUCKDB_API static bool IsAnySize(const LogicalType &type);
124979 DUCKDB_API
static constexpr idx_t MAX_ARRAY_SIZE = 100000;
124981 DUCKDB_API static LogicalType ConvertToList(const LogicalType &type);
124982};
124983
124984struct AggregateStateType {
124985 DUCKDB_API static const string GetTypeName(const LogicalType &type);
124986 DUCKDB_API static const aggregate_state_t &GetStateType(const LogicalType &type);
124987};
124988
124989struct AnyType {
124990 DUCKDB_API static LogicalType GetTargetType(const LogicalType &type);
124991 DUCKDB_API
static idx_t GetCastScore(
const LogicalType &type);
124992};
124993
124994struct IntegerLiteral {
124996 DUCKDB_API static LogicalType GetType(const LogicalType &type);
124998 DUCKDB_API static bool FitsInType(const LogicalType &type, const LogicalType &target);
124999};
125000
125001struct TemplateType {
125002
125003 DUCKDB_API static const string &GetName(const LogicalType &type);
125004};
125005
125006struct GeoType {
125007 DUCKDB_API static bool HasCRS(const LogicalType &type);
125008 DUCKDB_API static const CoordinateReferenceSystem &GetCRS(const LogicalType &type);
125009};
125010
125011
125012DUCKDB_API string LogicalTypeIdToString(LogicalTypeId type);
125013
125014DUCKDB_API
LogicalTypeId TransformStringToLogicalTypeId(
const string &str);
125015
125016DUCKDB_API LogicalType TransformStringToLogicalType(const string &str, ClientContext &context);
125017
125020
125021DUCKDB_API string TypeIdToString(PhysicalType type);
125022DUCKDB_API
idx_t GetTypeIdSize(PhysicalType type);
125023DUCKDB_API bool TypeIsConstantSize(PhysicalType type);
125024DUCKDB_API bool TypeIsIntegral(PhysicalType type);
125025DUCKDB_API bool TypeIsNumeric(PhysicalType type);
125026DUCKDB_API bool TypeIsInteger(PhysicalType type);
125027
125028bool ApproxEqual(float l, float r);
125029bool ApproxEqual(double l, double r);
125030
125031struct aggregate_state_t {
125032 aggregate_state_t() {
125033 }
125034
125035 aggregate_state_t(string function_name_p, LogicalType return_type_p, vector<LogicalType> bound_argument_types_p)
125036 : function_name(std::move(function_name_p)), return_type(std::move(return_type_p)),
125037 bound_argument_types(std::move(bound_argument_types_p)) {
125038 }
125039
125040 string function_name;
125041 LogicalType return_type;
125042 vector<LogicalType> bound_argument_types;
125043};
125044
125045
125046
125047}
125048
125049
125050
125051
125052
125053
125054
125055
125056
125057
125058
125059
125060
125061
125062
125063
125064
125065
125066
125067
125068
125069
125070
125071
125072
125073
125074
125075#include <type_traits>
125076
125077
125078#undef max
125079
125080#include <limits>
125081
125082namespace duckdb {
125083
125084template <class T>
125085struct NumericLimits {
125086 static constexpr T Minimum() {
125087 return std::numeric_limits<T>::has_infinity ? -std::numeric_limits<T>::infinity()
125088 : std::numeric_limits<T>::lowest();
125089 }
125090 static constexpr T Maximum() {
125091 return std::numeric_limits<T>::has_infinity ? std::numeric_limits<T>::infinity()
125092 : std::numeric_limits<T>::
max();
125093 }
125094 static constexpr bool IsSigned() {
125095 return std::is_signed<T>::value;
125096 }
125097 static constexpr bool IsIntegral() {
125098 return std::is_integral<T>::value || std::is_enum<T>::value;
125099 }
125100 static constexpr idx_t Digits();
125101};
125102
125103template <>
125104struct NumericLimits<hugeint_t> {
125105 static constexpr hugeint_t Minimum() {
125106 return {std::numeric_limits<int64_t>::lowest(), 0};
125107 };
125108 static constexpr hugeint_t Maximum() {
125109 return {std::numeric_limits<int64_t>::max(), std::numeric_limits<uint64_t>::max()};
125110 };
125111 static constexpr bool IsSigned() {
125112 return true;
125113 }
125114 static constexpr bool IsIntegral() {
125115 return true;
125116 }
125117 static constexpr idx_t Digits() {
125118 return 39;
125119 }
125120};
125121
125122template <>
125123struct NumericLimits<uhugeint_t> {
125124 static constexpr uhugeint_t Minimum() {
125125 return {0, 0};
125126 };
125127 static constexpr uhugeint_t Maximum() {
125128 return {std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::max()};
125129 };
125130 static constexpr bool IsSigned() {
125131 return false;
125132 }
125133 static constexpr bool IsIntegral() {
125134 return true;
125135 }
125136 static constexpr idx_t Digits() {
125137 return 39;
125138 }
125139};
125140
125141template <>
125142constexpr idx_t NumericLimits<int8_t>::Digits() {
125143 return 3;
125144}
125145
125146template <>
125147constexpr idx_t NumericLimits<int16_t>::Digits() {
125148 return 5;
125149}
125150
125151template <>
125152constexpr idx_t NumericLimits<int32_t>::Digits() {
125153 return 10;
125154}
125155
125156template <>
125157constexpr idx_t NumericLimits<int64_t>::Digits() {
125158 return 19;
125159}
125160
125161template <>
125162constexpr idx_t NumericLimits<uint8_t>::Digits() {
125163 return 3;
125164}
125165
125166template <>
125167constexpr idx_t NumericLimits<uint16_t>::Digits() {
125168 return 5;
125169}
125170
125171template <>
125172constexpr idx_t NumericLimits<uint32_t>::Digits() {
125173 return 10;
125174}
125175
125176template <>
125177constexpr idx_t NumericLimits<uint64_t>::Digits() {
125178 return 20;
125179}
125180
125181template <>
125182constexpr idx_t NumericLimits<float>::Digits() {
125183 return 127;
125184}
125185
125186template <>
125187constexpr idx_t NumericLimits<double>::Digits() {
125188 return 250;
125189}
125190
125191}
125192
125193
125194
125195
125196
125197
125198
125199
125200
125201
125202
125203
125204
125205
125206
125207
125208
125209
125210
125211
125212
125213
125214
125215#include <type_traits>
125216
125217
125218
125219
125220namespace duckdb {
125221
125222template <class T>
125223struct MakeSigned {
125224 using type = typename std::make_signed<T>::type;
125225};
125226
125227template <>
125228struct MakeSigned<hugeint_t> {
125229 using type = hugeint_t;
125230};
125231
125232template <>
125233struct MakeSigned<uhugeint_t> {
125234 using type = hugeint_t;
125235};
125236
125237template <class T>
125238struct MakeUnsigned {
125239 using type = typename std::make_unsigned<T>::type;
125240};
125241
125242template <>
125243struct MakeUnsigned<hugeint_t> {
125244 using type = uhugeint_t;
125245};
125246
125247template <>
125248struct MakeUnsigned<uhugeint_t> {
125249 using type = uhugeint_t;
125250};
125251
125252template <class TO, class FROM>
125253static void ThrowNumericCastError(FROM in, TO minval, TO maxval) {
125254 throw InternalException("Information loss on integer cast: value %d outside of target range [%d, %d]", in, minval,
125255 maxval);
125256}
125257
125258template <class TO, class FROM, bool are_same_type>
125259struct NumericCastImpl;
125260
125261template <class TO, class FROM>
125262struct NumericCastImpl<TO, FROM, true> {
125263 static TO Convert(FROM val) {
125264 return static_cast<TO>(val);
125265 }
125266};
125267
125268template <class TO, class FROM>
125269struct NumericCastImpl<TO, FROM, false> {
125270 static TO Convert(FROM val) {
125271
125272 auto minval = NumericLimits<TO>::Minimum();
125273 auto maxval = NumericLimits<TO>::Maximum();
125274 auto unsigned_in = static_cast<typename MakeUnsigned<FROM>::type>(val);
125275 auto unsigned_min = static_cast<typename MakeUnsigned<TO>::type>(minval);
125276 auto unsigned_max = static_cast<typename MakeUnsigned<TO>::type>(maxval);
125277 auto signed_in = static_cast<typename MakeSigned<FROM>::type>(val);
125278 auto signed_min = static_cast<typename MakeSigned<TO>::type>(minval);
125279 auto signed_max = static_cast<typename MakeSigned<TO>::type>(maxval);
125280
125281 if (!NumericLimits<FROM>::IsSigned() && !NumericLimits<TO>::IsSigned() &&
125282 (unsigned_in < unsigned_min || unsigned_in > unsigned_max)) {
125283 ThrowNumericCastError(val, static_cast<TO>(unsigned_min), static_cast<TO>(unsigned_max));
125284 }
125285
125286 if (NumericLimits<FROM>::IsSigned() && NumericLimits<TO>::IsSigned() &&
125287 (signed_in < signed_min || signed_in > signed_max)) {
125288 ThrowNumericCastError(val, static_cast<TO>(signed_min), static_cast<TO>(signed_max));
125289 }
125290
125291 if (NumericLimits<FROM>::IsSigned() != NumericLimits<TO>::IsSigned() &&
125292 (signed_in < signed_min || unsigned_in > unsigned_max)) {
125293 ThrowNumericCastError(val, static_cast<TO>(signed_min), static_cast<TO>(unsigned_max));
125294 }
125295
125296 return static_cast<TO>(val);
125297 }
125298};
125299
125300
125301
125302
125303template <class TO, class FROM,
125304 class = typename std::enable_if<(NumericLimits<TO>::IsIntegral() && NumericLimits<FROM>::IsIntegral()) ||
125305 std::is_same<TO, FROM>::value>::type>
125306TO NumericCast(FROM val) {
125307 return NumericCastImpl<TO, FROM, std::is_same<TO, FROM>::value>::Convert(val);
125308}
125309
125310
125311
125312
125313template <class TO, class FROM,
125314 class = typename std::enable_if<(NumericLimits<TO>::IsIntegral() && NumericLimits<FROM>::IsIntegral()) ||
125315 std::is_same<TO, FROM>::value>::type>
125316TO UnsafeNumericCast(FROM in) {
125317#if defined(DEBUG) || defined(UNSAFE_NUMERIC_CAST)
125318 return NumericCast<TO, FROM>(in);
125319#endif
125320 return static_cast<TO>(in);
125321}
125322
125323
125324
125325
125326template <class TO, class FROM>
125327TO LossyNumericCast(FROM val) {
125328 return static_cast<TO>(val);
125329}
125330
125331
125332
125333
125334
125335template <class TO>
125336TO ExactNumericCast(double val) {
125337 auto res = LossyNumericCast<TO>(val);
125338#if defined(DEBUG) || defined(UNSAFE_NUMERIC_CAST)
125339 if (val != double(res)) {
125340 throw InternalException("Information loss on double cast: value %lf outside of target range [%lf, %lf]", val,
125341 double(res), double(res));
125342 }
125343#endif
125344 return res;
125345}
125346
125347template <class TO>
125348TO ExactNumericCast(float val) {
125349 auto res = LossyNumericCast<TO>(val);
125350#if defined(DEBUG) || defined(UNSAFE_NUMERIC_CAST)
125351 if (val != float(res)) {
125352 throw InternalException("Information loss on float cast: value %f outside of target range [%f, %f]", val,
125353 float(res), float(res));
125354 }
125355#endif
125356 return res;
125357}
125358
125359template <class T>
125360struct NextUnsigned {};
125361
125362template <>
125363struct NextUnsigned<uint8_t> {
125365};
125366
125367template <>
125368struct NextUnsigned<uint16_t> {
125370};
125371
125372template <>
125373struct NextUnsigned<uint32_t> {
125375};
125376
125377template <>
125378struct NextUnsigned<uint64_t> {
125379#if ((__GNUC__ >= 5) || defined(__clang__)) && defined(__SIZEOF_INT128__)
125380 using type = __uint128_t;
125381#else
125382 using type = uhugeint_t;
125383#endif
125384};
125385
125386template <class TYPE>
125387class FastMod {
125388 using NEXT_TYPE = typename NextUnsigned<TYPE>::type;
125389 static_assert(sizeof(NEXT_TYPE) != 0, "NextUnsigned not available for this type");
125390
125391public:
125392 explicit FastMod(TYPE divisor_p) : divisor(divisor_p), multiplier((static_cast<
TYPE>(-1) / divisor) + 1) {
125393 }
125394
125395 TYPE Div(
const TYPE &val)
const {
125396 return static_cast<TYPE>((
static_cast<NEXT_TYPE
>(val) * multiplier) >> (
sizeof(
TYPE) * 8));
125397 }
125398
125399 TYPE Mod(
const TYPE &val,
const TYPE "ient)
const {
125400 return val - quotient * divisor;
125401 }
125402
125403 TYPE Mod(
const TYPE &val)
const {
125404 return Mod(val, Div(val));
125405 }
125406
125407 const TYPE &GetDivisor()
const {
125408 return divisor;
125409 }
125410
125411private:
125412 const TYPE divisor;
125413 const TYPE multiplier;
125414};
125415
125416}
125417
125418
125419
125420
125421
125422
125423
125424
125425
125426
125427
125428#include <utility>
125429
125430namespace duckdb {
125431using std::make_pair;
125432using std::pair;
125433}
125434
125435
125436
125437
125438
125439
125440
125441
125442
125443
125444
125445#include <set>
125446
125447namespace duckdb {
125448using std::multiset;
125449using std::set;
125450}
125451
125452
125453
125454
125455
125456
125457
125458
125459
125460
125461
125462
125463#include <unordered_map>
125464#include <string>
125465
125466
125467
125468
125469namespace duckdb {
125470
125471enum class ComplexJSONType :
uint8_t { VALUE = 0, OBJECT = 1, ARRAY = 2 };
125472
125474struct ComplexJSON {
125476 explicit ComplexJSON(const string &str);
125478 ComplexJSON();
125480 void AddObjectEntry(const string &key, unique_ptr<ComplexJSON> object);
125482 void AddArrayElement(unique_ptr<ComplexJSON> object);
125484 ComplexJSON &GetObject(const string &key);
125486 ComplexJSON &GetArrayElement(const idx_t &index);
125488 string GetValue(const string &key) const;
125490 string GetValue(const idx_t &index) const;
125492 static string GetValueRecursive(const ComplexJSON &child);
125494 unordered_map<string, string> Flatten() const;
125495
125496private:
125498 string str_value;
125500 unordered_map<string, unique_ptr<ComplexJSON>> obj_value;
125502 vector<unique_ptr<ComplexJSON>> arr_value;
125504 ComplexJSONType type;
125505};
125506
125507}
125508
125509
125510
125511
125512
125513
125514
125515
125516
125517
125518
125519
125520
125521
125522
125523namespace duckdb {
125524
125525class ParserException : public Exception {
125526public:
125527 DUCKDB_API explicit ParserException(const string &msg);
125528
125529 DUCKDB_API explicit ParserException(const unordered_map<string, string> &extra_info, const string &msg);
125530
125531 template <typename... ARGS>
125532 explicit ParserException(const string &msg, ARGS &&...params)
125533 : ParserException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
125534 }
125535 template <typename... ARGS>
125536 explicit ParserException(optional_idx error_location, const string &msg, ARGS &&...params)
125537 : ParserException(Exception::InitializeExtraInfo(error_location),
125538 ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
125539 }
125540 template <typename... ARGS>
125541 explicit ParserException(const ParsedExpression &expr, const string &msg, ARGS &&...params)
125542 : ParserException(Exception::InitializeExtraInfo(expr), ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
125543 }
125544
125545 static ParserException SyntaxError(const string &query, const string &error_message, optional_idx error_location);
125546};
125547
125548}
125549
125550
125551#include <cstring>
125552
125553namespace duckdb {
125554
125555#ifndef DUCKDB_QUOTE_DEFINE
125556
125557
125558
125559
125560
125561
125562#define DUCKDB_QUOTE_DEFINE_IMPL(x) #x
125563#define DUCKDB_QUOTE_DEFINE(x) DUCKDB_QUOTE_DEFINE_IMPL(x)
125564#endif
125565
125572class StringUtil {
125573public:
125574 static string GenerateRandomName(idx_t length = 16);
125575
125576 static uint8_t GetHexValue(
char c) {
125577 if (c >= '0' && c <= '9') {
125578 return UnsafeNumericCast<uint8_t>(c - '0');
125579 }
125580 if (c >= 'a' && c <= 'f') {
125581 return UnsafeNumericCast<uint8_t>(c - 'a' + 10);
125582 }
125583 if (c >= 'A' && c <= 'F') {
125584 return UnsafeNumericCast<uint8_t>(c - 'A' + 10);
125585 }
125586 throw InvalidInputException("Invalid input for hex digit: %s", string(1, c));
125587 }
125588 static uint8_t GetBinaryValue(
char c) {
125589 if (c >= '0' && c <= '1') {
125590 return UnsafeNumericCast<uint8_t>(c - '0');
125591 }
125592 throw InvalidInputException("Invalid input for binary digit: %s", string(1, c));
125593 }
125594
125595 static bool CharacterIsSpace(char c) {
125596 return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r';
125597 }
125598 static bool CharacterIsNewline(char c) {
125599 return c == '\n' || c == '\r';
125600 }
125601 static bool CharacterIsDigit(char c) {
125602 return c >= '0' && c <= '9';
125603 }
125604 static bool CharacterIsHex(char c) {
125605 return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
125606 }
125607 static char CharacterToUpper(char c) {
125608 if (c >= 'a' && c <= 'z') {
125609 return UnsafeNumericCast<char>(c - ('a' - 'A'));
125610 }
125611 return c;
125612 }
125613 static char CharacterToLower(char c) {
125614 if (c >= 'A' && c <= 'Z') {
125615 return UnsafeNumericCast<char>(c + ('a' - 'A'));
125616 }
125617 return c;
125618 }
125619 static bool CharacterIsAlpha(char c) {
125620 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
125621 }
125622 static bool CharacterIsAlphaNumeric(char c) {
125623 return CharacterIsAlpha(c) || CharacterIsDigit(c);
125624 }
125625 static bool CharacterIsOperator(char c) {
125626 if (c == '_') {
125627 return false;
125628 }
125629 if (c >= '!' && c <= '/') {
125630 return true;
125631 }
125632 if (c >= ':' && c <= '@') {
125633 return true;
125634 }
125635 if (c >= '[' && c <= '`') {
125636 return true;
125637 }
125638 if (c >= '{' && c <= '~') {
125639 return true;
125640 }
125641 return false;
125642 }
125643
125644 template <class TO>
125645 static vector<TO> ConvertStrings(const vector<string> &strings) {
125646 vector<TO> result;
125647 for (auto &string : strings) {
125648 result.emplace_back(string);
125649 }
125650 return result;
125651 }
125652
125653 static vector<SQLIdentifier> ConvertToSQLIdentifiers(const vector<string> &strings) {
125654 return ConvertStrings<SQLIdentifier>(strings);
125655 }
125656
125657 static vector<SQLString> ConvertToSQLStrings(const vector<string> &strings) {
125658 return ConvertStrings<SQLString>(strings);
125659 }
125660
125662 DUCKDB_API static bool Contains(const string &haystack, const string &needle);
125663 DUCKDB_API static bool Contains(const string &haystack, const char &needle_char);
125664
125666 DUCKDB_API static optional_idx Find(const string &haystack, const string &needle);
125667
125669 DUCKDB_API static bool StartsWith(string str, string prefix);
125670
125672 DUCKDB_API static bool EndsWith(const string &str, const string &suffix);
125673
125675 DUCKDB_API static string Repeat(const string &str, const idx_t n);
125676
125678 DUCKDB_API static vector<string> Split(const string &str, char delimiter);
125679
125681 DUCKDB_API static vector<string> SplitWithParentheses(const string &str, char delimiter = ',', char par_open = '(',
125682 char par_close = ')');
125683
125685 DUCKDB_API static vector<string> SplitWithQuote(const string &str, char delimiter = ',', char quote = '"');
125686
125688 DUCKDB_API static string Join(const vector<string> &input, const string &separator);
125689 DUCKDB_API static string Join(const set<string> &input, const string &separator);
125690
125692 DUCKDB_API static string URLEncode(const string &str, bool encode_slash = true);
125693 DUCKDB_API
static idx_t URLEncodeSize(
const char *input, idx_t input_size,
bool encode_slash =
true);
125694 DUCKDB_API static void URLEncodeBuffer(const char *input, idx_t input_size, char *output, bool encode_slash = true);
125696 DUCKDB_API static string URLDecode(const string &str, bool plus_to_space = false);
125697 DUCKDB_API
static idx_t URLDecodeSize(
const char *input, idx_t input_size,
bool plus_to_space =
false);
125698 DUCKDB_API static void URLDecodeBuffer(const char *input, idx_t input_size, char *output,
125699 bool plus_to_space = false);
125700
125702 DUCKDB_API static void SkipBOM(const char *buffer_ptr, const idx_t &buffer_size, idx_t &buffer_pos);
125703
125704 DUCKDB_API
static idx_t ToUnsigned(
const string &str);
125705 DUCKDB_API
static int64_t ToSigned(
const string &str);
125706 DUCKDB_API static double ToDouble(const string &str);
125707
125708 template <class T>
125709 static string ToString(const vector<T> &input, const string &separator) {
125710 vector<string> input_list;
125711 for (auto &i : input) {
125712 input_list.push_back(i.ToString());
125713 }
125715 }
125716
125719 template <typename C, typename S, typename FUNC>
125720 static string Join(const C &input, S count, const string &separator, FUNC f) {
125721
125722 std::string result;
125723
125724
125725
125726 if (count > 0) {
125727 result += f(input[0]);
125728 }
125729
125730
125731 for (size_t i = 1; i < count; i++) {
125732 result += separator + f(input[i]);
125733 }
125734
125735 return result;
125736 }
125737
125739 DUCKDB_API static string BytesToHumanReadableString(idx_t bytes, idx_t multiplier = 1024);
125740
125741 DUCKDB_API
static string TryParseFormattedBytes(
const string &
arg, idx_t &result);
125742
125743 DUCKDB_API
static idx_t ParseFormattedBytes(
const string &
arg);
125744
125746 DUCKDB_API static string Upper(const string &str);
125747
125749 DUCKDB_API static string Lower(const string &str);
125750
125752 DUCKDB_API static string Title(const string &str);
125753
125754 DUCKDB_API static bool IsLower(const string &str);
125755 DUCKDB_API static bool IsUpper(const string &str);
125756
125758 DUCKDB_API
static uint64_t CIHash(
const string &str);
125759 DUCKDB_API
static uint64_t CIHash(
const char *str, idx_t size);
125760
125762 DUCKDB_API static bool CIEquals(const string &l1, const string &l2);
125763
125765 DUCKDB_API static bool CIEquals(const char *l1, idx_t l1_size, const char *l2, idx_t l2_size);
125766
125768 DUCKDB_API static bool CIStartsWith(const string &str, const string &prefix);
125769
125771 DUCKDB_API static bool CILessThan(const string &l1, const string &l2);
125772
125774 DUCKDB_API
static idx_t CIFind(vector<string> &vec,
const string &str);
125775
125777 template <typename... ARGS>
125778 static string Format(const string fmt_str, ARGS... params) {
125779 return Exception::ConstructMessage(fmt_str,
params...);
125780 }
125781
125783 DUCKDB_API static vector<string> Split(const string &input, const string &split);
125784
125786 DUCKDB_API static void LTrim(string &str);
125788 DUCKDB_API static void RTrim(string &str);
125790 DUCKDB_API static void RTrim(string &str, const string &chars_to_trim);
125792 DUCKDB_API static void Trim(string &str);
125793
125794 DUCKDB_API static string Replace(string source, const string &from, const string &to);
125795
125802 DUCKDB_API
static idx_t LevenshteinDistance(
const string &s1,
const string &s2, idx_t not_equal_penalty = 1);
125803
125805 DUCKDB_API
static idx_t SimilarityScore(
const string &s1,
const string &s2);
125807 DUCKDB_API static double SimilarityRating(const string &s1, const string &s2);
125812 DUCKDB_API static vector<string> TopNStrings(vector<pair<string, double>> scores, idx_t n = 5,
125813 double threshold = 0.5);
125816 DUCKDB_API static vector<string> TopNStrings(const vector<pair<string, idx_t>> &scores, idx_t n = 5,
125817 idx_t threshold = 5);
125820 DUCKDB_API static vector<string> TopNLevenshtein(const vector<string> &strings, const string &target, idx_t n = 5,
125821 idx_t threshold = 5);
125824 DUCKDB_API static vector<string> TopNJaroWinkler(const vector<string> &strings, const string &target, idx_t n = 5,
125825 double threshold = 0.5);
125826 DUCKDB_API static string CandidatesMessage(const vector<string> &candidates,
125827 const string &candidate = "Candidate bindings");
125828
125831 DUCKDB_API static string CandidatesErrorMessage(const vector<string> &strings, const string &target,
125832 const string &message_prefix, idx_t n = 5);
125833
125836 static bool Equals(const char *s1, const char *s2) {
125837 if (s1 == s2) {
125838 return true;
125839 }
125840 if (s1 == nullptr || s2 == nullptr) {
125841 return false;
125842 }
125843 return strcmp(s1, s2) == 0;
125844 }
125845 static bool Equals(const string &s1, const char *s2) {
125846 return Equals(s1.c_str(), s2);
125847 }
125848 static bool Equals(const char *s1, const string &s2) {
125849 return Equals(s1, s2.c_str());
125850 }
125851 static bool Equals(const string &s1, const string &s2) {
125852 return s1 == s2;
125853 }
125854 static bool Equals(const string_t &s1, const char *s2);
125855 static bool Equals(const char *s1, const string_t &s2);
125856
125862 DUCKDB_API static unique_ptr<ComplexJSON> ParseJSONMap(const string &json, bool ignore_errors = false);
125863
125867 DUCKDB_API static string ExceptionToJSONMap(ExceptionType type, const string &message,
125868 const unordered_map<string, string> &map);
125869
125871 DUCKDB_API static string ToJSONMap(const unordered_map<string, string> &map);
125873 DUCKDB_API static string ToComplexJSONMap(const ComplexJSON &complex_json);
125874
125875 DUCKDB_API static string ValidateJSON(const char *data, const idx_t &len);
125876
125877 DUCKDB_API static string GetFileName(const string &file_path);
125878 DUCKDB_API static string GetFileExtension(const string &file_name);
125879 DUCKDB_API static string GetFileStem(const string &file_name);
125880 DUCKDB_API static string GetFilePath(const string &file_path);
125881
125882 struct EnumStringLiteral {
125884 const char *string;
125885 };
125886
125887 DUCKDB_API
static uint32_t StringToEnum(
const EnumStringLiteral enum_list[], idx_t enum_count,
125888 const char *enum_name, const char *str_value);
125889 DUCKDB_API static const char *EnumToString(const EnumStringLiteral enum_list[], idx_t enum_count,
125890 const char *enum_name, uint32_t enum_value);
125891 DUCKDB_API
static const uint8_t ASCII_TO_LOWER_MAP[];
125892 DUCKDB_API
static const uint8_t ASCII_TO_UPPER_MAP[];
125893};
125894}
125895
125896
125897
125898
125899#include <functional>
125900
125901namespace duckdb {
125902
125903struct date_t;
125904struct dtime_t;
125905struct dtime_ns_t;
125906struct dtime_tz_t;
125907
125909struct timestamp_t {
125910
125911
125913
125914 timestamp_t() = default;
125915 explicit inline constexpr timestamp_t(int64_t micros) : value(micros) {
125916 }
125917 inline timestamp_t &
operator=(int64_t micros) {
125918 value = micros;
125919 return *this;
125920 }
125921
125922
125923 explicit inline operator int64_t()
const {
125924 return value;
125925 }
125926
125927
125928 inline bool operator==(
const timestamp_t &rhs)
const {
125929 return value == rhs.value;
125930 };
125931 inline bool operator!=(
const timestamp_t &rhs)
const {
125932 return value != rhs.value;
125933 };
125934 inline bool operator<=(
const timestamp_t &rhs)
const {
125935 return value <= rhs.value;
125936 };
125937 inline bool operator<(
const timestamp_t &rhs)
const {
125938 return value < rhs.value;
125939 };
125940 inline bool operator>(
const timestamp_t &rhs)
const {
125941 return value > rhs.value;
125942 };
125943 inline bool operator>=(
const timestamp_t &rhs)
const {
125944 return value >= rhs.value;
125945 };
125946
125947
125948 timestamp_t
operator+(
const double &value)
const;
125950
125951
125952 timestamp_t &
operator+=(
const int64_t &delta);
125953 timestamp_t &
operator-=(
const int64_t &delta);
125954
125955
125956 static constexpr timestamp_t infinity() {
125957 return timestamp_t(NumericLimits<int64_t>::Maximum());
125958 }
125959 static constexpr timestamp_t ninfinity() {
125960 return timestamp_t(-NumericLimits<int64_t>::Maximum());
125961 }
125962 static constexpr inline timestamp_t epoch() {
125963 return timestamp_t(0);
125964 }
125965};
125966
125968struct timestamp_sec_t : public timestamp_t {
125969 timestamp_sec_t() = default;
125970 explicit inline constexpr timestamp_sec_t(int64_t seconds) : timestamp_t(seconds) {
125971 }
125972};
125973
125975struct timestamp_ms_t : public timestamp_t {
125976 timestamp_ms_t() = default;
125977 explicit inline constexpr timestamp_ms_t(int64_t millis) : timestamp_t(millis) {
125978 }
125979};
125980
125982struct timestamp_ns_t : public timestamp_t {
125983 timestamp_ns_t() = default;
125984 explicit inline constexpr timestamp_ns_t(int64_t nanos) : timestamp_t(nanos) {
125985 }
125986};
125987
125990struct timestamp_tz_t : public timestamp_t {
125991 timestamp_tz_t() = default;
125992 explicit inline constexpr timestamp_tz_t(int64_t micros) : timestamp_t(micros) {
125993 }
125994 explicit inline constexpr timestamp_tz_t(timestamp_t ts) : timestamp_t(ts) {
125995 }
125996};
125997
125998enum class TimestampCastResult :
uint8_t {
125999 SUCCESS,
126000 ERROR_INCORRECT_FORMAT,
126001 ERROR_NON_UTC_TIMEZONE,
126002 ERROR_RANGE,
126003 STRICT_UTC
126004};
126005
126006struct TimestampComponents {
126010
126015};
126016
126018class Timestamp {
126019public:
126020
126021 constexpr static const int32_t MIN_YEAR = -290308;
126022 constexpr static const int32_t MIN_MONTH = 12;
126023 constexpr static const int32_t MIN_DAY = 22;
126024
126025public:
126027 DUCKDB_API static timestamp_t FromString(const string &str, bool use_offset);
126031 DUCKDB_API static TimestampCastResult TryConvertTimestampTZ(const char *str, idx_t len, timestamp_t &result,
126032 const bool use_offset, bool &has_offset, string_t &tz,
126033 optional_ptr<int32_t> nanos = nullptr);
126035 DUCKDB_API static TimestampCastResult TryConvertTimestamp(const char *str, idx_t len, timestamp_t &result,
126036 const bool use_offset,
126037 optional_ptr<int32_t> nanos = nullptr,
126038 bool strict = false);
126039 DUCKDB_API static TimestampCastResult TryConvertTimestamp(const char *str, idx_t len, timestamp_ns_t &result);
126040 DUCKDB_API static timestamp_t FromCString(const char *str, idx_t len, bool use_offset = false,
126041 optional_ptr<int32_t> nanos = nullptr);
126043 DUCKDB_API static string ToString(timestamp_t timestamp);
126044
126045 DUCKDB_API static date_t GetDate(timestamp_t timestamp);
126046
126047 DUCKDB_API static dtime_t GetTime(timestamp_t timestamp);
126048 DUCKDB_API static dtime_ns_t GetTimeNs(timestamp_ns_t timestamp);
126050 DUCKDB_API static timestamp_t FromDatetime(date_t date, dtime_t time);
126051 DUCKDB_API static bool TryFromDatetime(date_t date, dtime_t time, timestamp_t &result);
126052 DUCKDB_API static bool TryFromDatetime(date_t date, dtime_tz_t timetz, timestamp_t &result);
126054 DUCKDB_API static bool TryFromTimestampNanos(timestamp_t ts, int32_t nanos, timestamp_ns_t &result);
126055
126057 static inline bool CharacterIsTimeZone(char c) {
126058 return StringUtil::CharacterIsAlpha(c) || StringUtil::CharacterIsDigit(c) || c == '_' || c == '/' || c == '+' ||
126059 c == '-';
126060 }
126061
126063 static inline bool IsFinite(timestamp_t timestamp) {
126064 return timestamp != timestamp_t::infinity() &&
timestamp != timestamp_t::ninfinity();
126065 }
126066
126068 DUCKDB_API static void Convert(timestamp_t date, date_t &out_date, dtime_t &out_time);
126070 DUCKDB_API static void Convert(timestamp_ns_t date, date_t &out_date, dtime_t &out_time, int32_t &out_nanos);
126072 DUCKDB_API static timestamp_t GetCurrentTimestamp();
126073
126075 DUCKDB_API static timestamp_t FromEpochSecondsPossiblyInfinite(int64_t s);
126076 DUCKDB_API static timestamp_t FromEpochSeconds(int64_t s);
126078 DUCKDB_API static timestamp_t FromEpochMsPossiblyInfinite(int64_t ms);
126079 DUCKDB_API static timestamp_t FromEpochMs(int64_t ms);
126081 DUCKDB_API static timestamp_t FromEpochMicroSeconds(int64_t micros);
126083 DUCKDB_API static timestamp_t FromEpochNanoSecondsPossiblyInfinite(int64_t nanos);
126084 DUCKDB_API static timestamp_t FromEpochNanoSeconds(int64_t nanos);
126085
126087 DUCKDB_API static timestamp_ns_t TimestampNsFromEpochMicros(int64_t micros);
126088 DUCKDB_API static timestamp_ns_t TimestampNsFromEpochMillis(int64_t millis);
126089
126091 DUCKDB_API static bool TryGetEpochNanoSeconds(timestamp_t timestamp, int64_t &result);
126093 DUCKDB_API
static int64_t GetEpochSeconds(timestamp_t timestamp);
126095 DUCKDB_API
static int64_t GetEpochMs(timestamp_t timestamp);
126097 DUCKDB_API
static int64_t GetEpochMicroSeconds(timestamp_t timestamp);
126099 DUCKDB_API
static int64_t GetEpochNanoSeconds(timestamp_t timestamp);
126100 DUCKDB_API
static int64_t GetEpochNanoSeconds(timestamp_ns_t timestamp);
126102 DUCKDB_API
static int64_t GetEpochRounded(timestamp_t timestamp,
const int64_t power_of_ten);
126104 DUCKDB_API static double GetJulianDay(timestamp_t timestamp);
126105
126107 DUCKDB_API static TimestampComponents GetComponents(timestamp_t timestamp);
126108 DUCKDB_API static time_t ToTimeT(timestamp_t);
126109 DUCKDB_API static timestamp_t FromTimeT(time_t);
126110
126111 DUCKDB_API static bool TryParseUTCOffset(const char *str, idx_t &pos, idx_t len, int &hh, int &mm, int &ss);
126112
126113 DUCKDB_API static string FormatError(const string &str);
126114 DUCKDB_API static string FormatError(string_t str);
126115 DUCKDB_API static string UnsupportedTimezoneError(const string &str);
126116 DUCKDB_API static string UnsupportedTimezoneError(string_t str);
126117 DUCKDB_API static string RangeError(const string &str);
126118 DUCKDB_API static string RangeError(string_t str);
126119};
126120
126121}
126122
126123namespace std {
126124
126126template <>
126127struct hash<duckdb::timestamp_t> {
126128 std::size_t
operator()(
const duckdb::timestamp_t &k)
const {
126129 using std::hash;
126130 return hash<int64_t>()((
int64_t)k);
126131 }
126132};
126133template <>
126134struct hash<duckdb::timestamp_ms_t> {
126135 std::size_t
operator()(
const duckdb::timestamp_ms_t &k)
const {
126136 using std::hash;
126137 return hash<int64_t>()((
int64_t)k);
126138 }
126139};
126140template <>
126141struct hash<duckdb::timestamp_ns_t> {
126142 std::size_t
operator()(
const duckdb::timestamp_ns_t &k)
const {
126143 using std::hash;
126144 return hash<int64_t>()((
int64_t)k);
126145 }
126146};
126147template <>
126148struct hash<duckdb::timestamp_sec_t> {
126149 std::size_t
operator()(
const duckdb::timestamp_sec_t &k)
const {
126150 using std::hash;
126151 return hash<int64_t>()((
int64_t)k);
126152 }
126153};
126154template <>
126155struct hash<duckdb::timestamp_tz_t> {
126156 std::size_t
operator()(
const duckdb::timestamp_tz_t &k)
const {
126157 using std::hash;
126158 return hash<int64_t>()((
int64_t)k);
126159 }
126160};
126161}
126162
126163
126164
126165
126166
126167
126168
126169
126170
126171
126172
126173
126174
126175
126176
126177
126178
126179
126180
126181
126182
126183
126184
126185
126186
126187
126188
126189
126190
126191
126192
126193
126194
126195
126196
126197
126198
126199
126200
126201
126202
126203
126204
126205
126206
126207
126208
126209
126210
126211
126212
126213
126214
126215#include <functional>
126216
126217namespace duckdb {
126218
126220struct dtime_t {
126222
126223 dtime_t() = default;
126224 explicit inline constexpr dtime_t(int64_t micros_p) : micros(micros_p) {
126225 }
126226 inline dtime_t &
operator=(int64_t micros_p) {
126227 micros = micros_p;
126228 return *this;
126229 }
126230
126231
126232 explicit inline operator int64_t()
const {
126233 return micros;
126234 }
126235 explicit inline operator double() const {
126236 return static_cast<double>(micros);
126237 }
126238
126239
126240 inline bool operator==(
const dtime_t &rhs)
const {
126241 return micros == rhs.micros;
126242 };
126243 inline bool operator!=(
const dtime_t &rhs)
const {
126244 return micros != rhs.micros;
126245 };
126246 inline bool operator<=(
const dtime_t &rhs)
const {
126247 return micros <= rhs.micros;
126248 };
126249 inline bool operator<(
const dtime_t &rhs)
const {
126250 return micros < rhs.micros;
126251 };
126252 inline bool operator>(
const dtime_t &rhs)
const {
126253 return micros > rhs.micros;
126254 };
126255 inline bool operator>=(
const dtime_t &rhs)
const {
126256 return micros >= rhs.micros;
126257 };
126258
126259
126260 inline dtime_t
operator+(
const int64_t µs)
const {
126261 return dtime_t(this->micros + micros);
126262 };
126263 inline dtime_t
operator+(
const double µs)
const {
126264 return dtime_t(this->micros +
int64_t(micros));
126265 };
126266 inline dtime_t
operator-(
const int64_t µs)
const {
126267 return dtime_t(this->micros - micros);
126268 };
126269 inline dtime_t
operator*(
const idx_t &copies)
const {
126270 return dtime_t(this->micros * UnsafeNumericCast<int64_t>(copies));
126271 };
126272 inline dtime_t
operator/(
const idx_t &copies)
const {
126273 return dtime_t(this->micros / UnsafeNumericCast<int64_t>(copies));
126274 };
126276 return this->micros - other.micros;
126277 };
126278
126279
126280 inline dtime_t &
operator+=(
const int64_t µs) {
126281 this->micros += micros;
126282 return *this;
126283 };
126284 inline dtime_t &
operator-=(
const int64_t µs) {
126285 this->micros -= micros;
126286 return *this;
126287 };
126288 inline dtime_t &
operator+=(
const dtime_t &other) {
126289 this->micros += other.micros;
126290 return *this;
126291 };
126292
126293
126294 static inline dtime_t allballs() {
126295 return dtime_t(0);
126296 }
126297};
126298
126300struct dtime_ns_t : public dtime_t {
126301 dtime_ns_t() = default;
126302 explicit inline constexpr dtime_ns_t(const int64_t nanos) : dtime_t(nanos) {
126303 }
126304 inline dtime_t time() const {
126305 return dtime_t(micros / 1000);
126306 }
126307};
126308
126309struct dtime_tz_t {
126310 static constexpr const int TIME_BITS = 40;
126311 static constexpr const int OFFSET_BITS = 24;
126312 static constexpr const uint64_t OFFSET_MASK = ~uint64_t(0) >> TIME_BITS;
126313 static constexpr const int32_t MAX_OFFSET = 16 * 60 * 60 - 1;
126314 static constexpr const int32_t MIN_OFFSET = -MAX_OFFSET;
126315 static constexpr const uint64_t OFFSET_MICROS = 1000000;
126316
126318
126319
126320
126321
126322 static inline uint64_t encode_offset(int32_t offset) {
126323 return uint64_t(MAX_OFFSET - offset);
126324 }
126325 static inline int32_t decode_offset(uint64_t bits) {
126326 return MAX_OFFSET -
int32_t(bits & OFFSET_MASK);
126327 }
126328
126329 static inline uint64_t encode_micros(int64_t micros) {
126330 return encode_micros(UnsafeNumericCast<uint64_t>(micros));
126331 }
126332 static inline uint64_t encode_micros(uint64_t micros) {
126333 return micros << OFFSET_BITS;
126334 }
126335 static inline int64_t decode_micros(uint64_t bits) {
126336 return int64_t(bits >> OFFSET_BITS);
126337 }
126338
126339 dtime_tz_t() = default;
126340
126341 inline dtime_tz_t(dtime_t t, int32_t offset) : bits(encode_micros(t.micros) | encode_offset(offset)) {
126342 }
126343 explicit inline dtime_tz_t(uint64_t bits_p) : bits(bits_p) {
126344 }
126345
126346 inline dtime_t time() const {
126347 return dtime_t(decode_micros(bits));
126348 }
126349
126350 inline int32_t offset()
const {
126351 return decode_offset(bits);
126352 }
126353
126354
126355
126356
126357 inline uint64_t sort_key()
const {
126358 return bits + encode_micros((bits & OFFSET_MASK) * OFFSET_MICROS);
126359 }
126360
126361
126362 inline bool operator==(
const dtime_tz_t &rhs)
const {
126363 return bits == rhs.bits;
126364 };
126365 inline bool operator!=(
const dtime_tz_t &rhs)
const {
126366 return bits != rhs.bits;
126367 };
126368 inline bool operator<=(
const dtime_tz_t &rhs)
const {
126369 return sort_key() <= rhs.sort_key();
126370 };
126371 inline bool operator<(
const dtime_tz_t &rhs)
const {
126372 return sort_key() < rhs.sort_key();
126373 };
126374 inline bool operator>(
const dtime_tz_t &rhs)
const {
126375 return sort_key() > rhs.sort_key();
126376 };
126377 inline bool operator>=(
const dtime_tz_t &rhs)
const {
126378 return sort_key() >= rhs.sort_key();
126379 };
126380};
126381
126382}
126383
126384namespace std {
126385
126387template <>
126388struct hash<duckdb::dtime_t> {
126389 std::size_t
operator()(
const duckdb::dtime_t &k)
const {
126390 using std::hash;
126391 return hash<int64_t>()((
int64_t)k);
126392 }
126393};
126394
126395template <>
126396struct hash<duckdb::dtime_tz_t> {
126397 std::size_t
operator()(
const duckdb::dtime_tz_t &k)
const {
126398 using std::hash;
126399 return hash<uint64_t>()(k.bits);
126400 }
126401};
126402}
126403
126404
126405namespace duckdb {
126406
126407struct string_t;
126408struct interval_t;
126409
126412 return left ^ right;
126413}
126414
126415#ifdef DUCKDB_HASH_ZERO
126416template <class T>
126418 return 0;
126419}
126420
126421DUCKDB_API
hash_t Hash(
const char *val,
size_t size);
126422DUCKDB_API
hash_t Hash(uint8_t *val,
size_t size);
126423#else
126427 x ^= x >> 32;
126428 x *= 0xd6e8feb86659fd93U;
126429 x ^= x >> 32;
126430 x *= 0xd6e8feb86659fd93U;
126431 x ^= x >> 32;
126432 return x;
126433}
126434
126435inline hash_t MurmurHash32(uint32_t x) {
126437}
126438
126439template <class T>
126441 return MurmurHash32(
static_cast<uint32_t>(value));
126442}
126443
126444template <>
126445DUCKDB_API
inline hash_t Hash(uint64_t val) {
126447}
126448template <>
126449DUCKDB_API
inline hash_t Hash(int64_t val) {
126451}
126452template <>
126453DUCKDB_API
hash_t Hash(hugeint_t val);
126454template <>
126455DUCKDB_API
hash_t Hash(uhugeint_t val);
126456template <>
126457DUCKDB_API
hash_t Hash(
float val);
126458template <>
126459DUCKDB_API
hash_t Hash(
double val);
126460template <>
126461DUCKDB_API
hash_t Hash(
const char *val);
126462template <>
126463DUCKDB_API
hash_t Hash(
char *val);
126464template <>
126465DUCKDB_API
hash_t Hash(string_t val);
126466template <>
126467DUCKDB_API
hash_t Hash(interval_t val);
126468template <>
126469DUCKDB_API
hash_t Hash(dtime_tz_t val);
126470DUCKDB_API
hash_t Hash(
const char *val,
size_t size);
126471DUCKDB_API
hash_t Hash(uint8_t *val,
size_t size);
126472#endif
126473
126474}
126475
126476
126477#include <cstring>
126478#include <algorithm>
126479
126480namespace duckdb {
126481
126482struct string_t {
126483 friend struct StringComparisonOperators;
126484
126485public:
126486 static constexpr idx_t PREFIX_BYTES = 4 *
sizeof(char);
126487 static constexpr idx_t INLINE_BYTES = 12 *
sizeof(char);
126488 static constexpr idx_t HEADER_SIZE =
sizeof(
uint32_t) + PREFIX_BYTES;
126489 static constexpr idx_t MAX_STRING_SIZE = NumericLimits<uint32_t>::Maximum();
126490#ifndef DUCKDB_DEBUG_NO_INLINE
126491 static constexpr idx_t PREFIX_LENGTH = PREFIX_BYTES;
126492 static constexpr idx_t INLINE_LENGTH = INLINE_BYTES;
126493#else
126494 static constexpr idx_t PREFIX_LENGTH = 0;
126495 static constexpr idx_t INLINE_LENGTH = 0;
126496#endif
126497
126498 string_t() = default;
126499 explicit string_t(uint32_t len) {
126500 value.inlined.length = len;
126501 }
126502 string_t(const char *data, uint32_t len) {
126503 value.inlined.length = len;
126504 D_ASSERT(data || GetSize() == 0);
126505 if (IsInlined()) {
126506
126507
126508 memset(value.inlined.inlined, 0, INLINE_BYTES);
126509 if (GetSize() == 0) {
126510 return;
126511 }
126512
126513 memcpy(value.inlined.inlined, data, GetSize());
126514 } else {
126515
126516#ifndef DUCKDB_DEBUG_NO_INLINE
126517 memcpy(value.pointer.prefix, data, PREFIX_LENGTH);
126518#else
126519 memset(value.pointer.prefix, 0, PREFIX_BYTES);
126520#endif
126521 value.pointer.ptr = (char *)data;
126522 }
126523 }
126524
126525 string_t(const char *data)
126526 : string_t(data, UnsafeNumericCast<
uint32_t>(strlen(data))) {
126527 }
126528 string_t(const string &value)
126529 : string_t(value.c_str(), UnsafeNumericCast<
uint32_t>(value.
size())) {
126530 }
126531
126532 bool IsInlined() const {
126533 return GetSize() <= INLINE_LENGTH;
126534 }
126535
126536 const char *GetData() const {
126537 return IsInlined() ? const_char_ptr_cast(value.inlined.inlined) : value.pointer.ptr;
126538 }
126539 const char *GetDataUnsafe() const {
126540 return GetData();
126541 }
126542
126543 char *GetDataWriteable() const {
126544 return IsInlined() ? (char *)value.inlined.inlined : value.pointer.ptr;
126545 }
126546
126547 const char *GetPrefix() const {
126548 return value.inlined.inlined;
126549 }
126550
126551 char *GetPrefixWriteable() {
126552 return value.inlined.inlined;
126553 }
126554
126555 idx_t GetSize()
const {
126556 return value.inlined.length;
126557 }
126558
126559 void SetSizeAndFinalize(uint32_t size, idx_t allocated_size) {
126560 value.inlined.length =
size;
126561 if (allocated_size > INLINE_LENGTH && IsInlined()) {
126563 D_ASSERT(value.pointer.ptr);
126564 auto ptr = value.pointer.ptr;
126565 memcpy(GetDataWriteable(), ptr, size);
126566 }
126567 Finalize();
126568 VerifyCharacters();
126569 }
126570
126571 bool Empty() const {
126572 return value.inlined.length == 0;
126573 }
126574
126575 string GetString() const {
126576 return string(GetData(), GetSize());
126577 }
126578
126579 explicit operator string() const {
126580 return GetString();
126581 }
126582
126583 char *GetPointer() const {
126584 D_ASSERT(!IsInlined());
126585 return value.pointer.ptr;
126586 }
126587
126588 void SetPointer(char *new_ptr) {
126589 D_ASSERT(!IsInlined());
126590 value.pointer.ptr = new_ptr;
126591 }
126592
126593 void Finalize() {
126594
126595 if (GetSize() <= INLINE_LENGTH) {
126596
126597 memset(value.inlined.inlined + GetSize(), 0, INLINE_BYTES - GetSize());
126598 } else {
126599
126600#ifndef DUCKDB_DEBUG_NO_INLINE
126601 auto dataptr = GetData();
126602 memcpy(value.pointer.prefix, dataptr, PREFIX_LENGTH);
126603#else
126604 memset(value.pointer.prefix, 0, PREFIX_BYTES);
126605#endif
126606 }
126607 }
126608
126609 void Verify() const;
126610 void VerifyUTF8() const;
126611 void VerifyCharacters() const;
126612 void VerifyNull() const;
126613
126614 struct StringComparisonOperators {
126615 static inline bool Equals(const string_t &a, const string_t &b) {
126616#ifdef DUCKDB_DEBUG_NO_INLINE
126617 if (a.GetSize() != b.GetSize()) {
126618 return false;
126619 }
126620 return (memcmp(a.GetData(), b.GetData(), a.GetSize()) == 0);
126621#endif
126622 uint64_t a_bulk_comp = Load<uint64_t>(const_data_ptr_cast(&a));
126623 uint64_t b_bulk_comp = Load<uint64_t>(const_data_ptr_cast(&b));
126624 if (a_bulk_comp != b_bulk_comp) {
126625
126626 return false;
126627 }
126628
126629 a_bulk_comp = Load<uint64_t>(const_data_ptr_cast(&a) + 8u);
126630 b_bulk_comp = Load<uint64_t>(const_data_ptr_cast(&b) + 8u);
126631 if (a_bulk_comp == b_bulk_comp) {
126632
126633 return true;
126634 }
126635 if (!a.IsInlined()) {
126636
126637 if (memcmp(a.value.pointer.ptr, b.value.pointer.ptr, a.GetSize()) == 0) {
126638 return true;
126639 }
126640 }
126641
126642
126643
126644 return false;
126645 }
126646
126647 static bool GreaterThan(const string_t &left, const string_t &right) {
126648 const uint32_t left_length = UnsafeNumericCast<uint32_t>(left.GetSize());
126649 const uint32_t right_length = UnsafeNumericCast<uint32_t>(right.GetSize());
126650 const uint32_t min_length = std::min<uint32_t>(left_length, right_length);
126651
126652#ifndef DUCKDB_DEBUG_NO_INLINE
126653 uint32_t a_prefix = Load<uint32_t>(const_data_ptr_cast(left.GetPrefix()));
126654 uint32_t b_prefix = Load<uint32_t>(const_data_ptr_cast(right.GetPrefix()));
126655
126656
126657
126658
126659
126660
126661
126662 if (a_prefix != b_prefix) {
126663 return BSwapIfLE(a_prefix) > BSwapIfLE(b_prefix);
126664 }
126665#endif
126666 auto memcmp_res = memcmp(left.GetData(), right.GetData(), min_length);
126667 return memcmp_res > 0 || (memcmp_res == 0 && left_length > right_length);
126668 }
126669 };
126670
126672 return StringComparisonOperators::Equals(*this, r);
126673 }
126674
126676 return !(*this == r);
126677 }
126678
126679 bool operator>(
const string_t &r)
const {
126680 return StringComparisonOperators::GreaterThan(*this, r);
126681 }
126682 bool operator<(
const string_t &r)
const {
126683 return r > *this;
126684 }
126685
126686private:
126687 union {
126688 struct {
126690 char prefix[4];
126691 char *ptr;
126692 } pointer;
126693 struct {
126695 char inlined[12];
126696 } inlined;
126697 } value;
126698};
126699
126700}
126701
126702namespace std {
126703template <>
126704struct hash<duckdb::string_t> {
126705 size_t operator()(
const duckdb::string_t &val)
const {
126706 return Hash(val);
126707 }
126708};
126709}
126710
126711
126712
126713#include <functional>
126714
126715namespace duckdb {
126716
126717struct timestamp_t;
126718
126720struct date_t {
126722
126723 date_t() = default;
126724 explicit inline date_t(int32_t days_p) : days(days_p) {
126725 }
126726
126727
126728 explicit inline operator int32_t()
const {
126729 return days;
126730 }
126731
126732
126733 inline bool operator==(
const date_t &rhs)
const {
126734 return days == rhs.days;
126735 };
126736 inline bool operator!=(
const date_t &rhs)
const {
126737 return days != rhs.days;
126738 };
126739 inline bool operator<=(
const date_t &rhs)
const {
126740 return days <= rhs.days;
126741 };
126742 inline bool operator<(
const date_t &rhs)
const {
126743 return days < rhs.days;
126744 };
126745 inline bool operator>(
const date_t &rhs)
const {
126746 return days > rhs.days;
126747 };
126748 inline bool operator>=(
const date_t &rhs)
const {
126749 return days >= rhs.days;
126750 };
126751
126752
126753 inline date_t
operator+(
const int32_t &days)
const {
126754 return date_t(this->days + days);
126755 };
126756 inline date_t
operator-(
const int32_t &days)
const {
126757 return date_t(this->days - days);
126758 };
126759
126760
126761 inline date_t &
operator+=(
const int32_t &days) {
126762 this->days += days;
126763 return *this;
126764 };
126765 inline date_t &
operator-=(
const int32_t &days) {
126766 this->days -= days;
126767 return *this;
126768 };
126769
126770
126771 static inline date_t infinity() {
126772 return date_t(NumericLimits<int32_t>::Maximum());
126773 }
126774 static inline date_t ninfinity() {
126775 return date_t(-NumericLimits<int32_t>::Maximum());
126776 }
126777 static inline date_t epoch() {
126778 return date_t(0);
126779 }
126780};
126781
126782enum class DateCastResult :
uint8_t { SUCCESS, ERROR_INCORRECT_FORMAT, ERROR_RANGE };
126783
126784struct DateSpecial {
126785 const char *str;
126787};
126788
126790class Date {
126791public:
126792 static const DateSpecial PINF;
126793 static const DateSpecial NINF;
126794 static const DateSpecial EPOCH;
126795
126796 static const string_t MONTH_NAMES[12];
126797 static const string_t MONTH_NAMES_ABBREVIATED[12];
126798 static const string_t DAY_NAMES[7];
126799 static const string_t DAY_NAMES_ABBREVIATED[7];
126800 static const int32_t NORMAL_DAYS[13];
126801 static const int32_t CUMULATIVE_DAYS[13];
126802 static const int32_t LEAP_DAYS[13];
126803 static const int32_t CUMULATIVE_LEAP_DAYS[13];
126804 static const int32_t CUMULATIVE_YEAR_DAYS[401];
126805 static const int8_t MONTH_PER_DAY_OF_YEAR[365];
126806 static const int8_t LEAP_MONTH_PER_DAY_OF_YEAR[366];
126807
126808
126809 constexpr static const int32_t DATE_MIN_YEAR = -5877641;
126810 constexpr static const int32_t DATE_MIN_MONTH = 6;
126811 constexpr static const int32_t DATE_MIN_DAY = 25;
126812
126813 constexpr static const int32_t DATE_MAX_YEAR = 5881580;
126814 constexpr static const int32_t DATE_MAX_MONTH = 7;
126815 constexpr static const int32_t DATE_MAX_DAY = 10;
126816 constexpr static const int32_t EPOCH_YEAR = 1970;
126817
126818 constexpr static const int32_t YEAR_INTERVAL = 400;
126819 constexpr static const int32_t DAYS_PER_YEAR_INTERVAL = 146097;
126820
126821public:
126823 DUCKDB_API static date_t FromString(const string &str, bool strict = false);
126825 DUCKDB_API static date_t FromCString(const char *str, idx_t len, bool strict = false);
126827 DUCKDB_API static string ToString(date_t date);
126830 DUCKDB_API static bool TryConvertDateSpecial(const char *buf, idx_t len, idx_t &pos, const DateSpecial &special);
126833 DUCKDB_API static DateCastResult TryConvertDate(const char *buf, idx_t len, idx_t &pos, date_t &result,
126834 bool &special, bool strict = false);
126835
126838 DUCKDB_API static string Format(int32_t year, int32_t month, int32_t day);
126839
126841 DUCKDB_API static void Convert(date_t date, int32_t &out_year, int32_t &out_month, int32_t &out_day);
126843 DUCKDB_API static date_t FromDate(int32_t year, int32_t month, int32_t day);
126844 DUCKDB_API static bool TryFromDate(int32_t year, int32_t month, int32_t day, date_t &result);
126845
126847 DUCKDB_API static bool IsLeapYear(int32_t year);
126848
126851 DUCKDB_API static bool IsValid(int32_t year, int32_t month, int32_t day);
126852
126854 static inline bool IsFinite(date_t date) {
126855 return date != date_t::infinity() && date != date_t::ninfinity();
126856 }
126857
126859 DUCKDB_API
static int32_t MonthDays(int32_t year, int32_t month);
126860
126862 DUCKDB_API
static int64_t Epoch(date_t date);
126864 DUCKDB_API
static int64_t EpochNanoseconds(date_t date);
126866 DUCKDB_API
static int64_t EpochMicroseconds(date_t date);
126868 DUCKDB_API
static int64_t EpochMilliseconds(date_t date);
126870 DUCKDB_API static date_t EpochToDate(int64_t epoch);
126871
126873 DUCKDB_API
static int32_t EpochDays(date_t date);
126875 DUCKDB_API static date_t EpochDaysToDate(int32_t epoch);
126876
126878 DUCKDB_API
static int32_t ExtractYear(date_t date);
126880 DUCKDB_API
static int32_t ExtractMonth(date_t date);
126882 DUCKDB_API
static int32_t ExtractDay(date_t date);
126884 DUCKDB_API
static int32_t ExtractISODayOfTheWeek(date_t date);
126886 DUCKDB_API
static int32_t ExtractDayOfTheYear(date_t date);
126888 DUCKDB_API
static int64_t ExtractJulianDay(date_t date);
126894 DUCKDB_API static void ExtractISOYearWeek(date_t date, int32_t &year, int32_t &week);
126895 DUCKDB_API
static int32_t ExtractISOWeekNumber(date_t date);
126896 DUCKDB_API
static int32_t ExtractISOYearNumber(date_t date);
126901 DUCKDB_API
static int32_t ExtractWeekNumberRegular(date_t date,
bool monday_first =
true);
126903 DUCKDB_API static date_t GetMondayOfCurrentWeek(date_t date);
126904
126906 DUCKDB_API static bool ParseDoubleDigit(const char *buf, idx_t len, idx_t &pos, int32_t &result);
126907
126908 DUCKDB_API static string FormatError(const string &str);
126909 DUCKDB_API static string FormatError(string_t str);
126910
126911 DUCKDB_API static string RangeError(const string &str);
126912 DUCKDB_API static string RangeError(string_t str);
126913
126914private:
126915 static void ExtractYearOffset(int32_t &n, int32_t &year, int32_t &year_offset);
126916};
126917
126918}
126919
126920namespace std {
126921
126923template <>
126924struct hash<duckdb::date_t> {
126925 std::size_t
operator()(
const duckdb::date_t &k)
const {
126926 using std::hash;
126927 return hash<int32_t>()((
int32_t)k);
126928 }
126929};
126930}
126931
126932
126933
126934
126935
126936
126937
126938
126939
126940
126941
126942
126943
126944
126945
126946namespace duckdb {
126947
126948struct dtime_t;
126949struct date_t;
126950struct dtime_tz_t;
126951struct timestamp_t;
126952struct TimestampComponents;
126953
126954class Serializer;
126955class Deserializer;
126956
126957struct interval_t {
126961
126962 inline void Normalize(int64_t &months, int64_t &days, int64_t µs) const;
126963
126964
126965 inline static void Borrow(const int64_t msf, int64_t &lsf, int32_t &f, const int64_t scale);
126966 inline interval_t Normalize() const;
126967
126968 inline bool operator==(
const interval_t &right)
const {
126969
126970 const auto &left = *this;
126971 if (left.months == right.months && left.days == right.days && left.micros == right.micros) {
126972 return true;
126973 }
126974
126975 int64_t lmonths, ldays, lmicros;
126976 int64_t rmonths, rdays, rmicros;
126977 left.Normalize(lmonths, ldays, lmicros);
126978 right.Normalize(rmonths, rdays, rmicros);
126979
126980 return lmonths == rmonths && ldays == rdays && lmicros == rmicros;
126981 }
126982 inline bool operator!=(
const interval_t &right)
const {
126983 return !(*this == right);
126984 }
126985
126986 inline bool operator>(
const interval_t &right)
const {
126987 const auto &left = *this;
126988 int64_t lmonths, ldays, lmicros;
126989 int64_t rmonths, rdays, rmicros;
126990 left.Normalize(lmonths, ldays, lmicros);
126991 right.Normalize(rmonths, rdays, rmicros);
126992
126993 if (lmonths > rmonths) {
126994 return true;
126995 } else if (lmonths < rmonths) {
126996 return false;
126997 }
126998 if (ldays > rdays) {
126999 return true;
127000 } else if (ldays < rdays) {
127001 return false;
127002 }
127003 return lmicros > rmicros;
127004 }
127005
127006 inline bool operator<(
const interval_t &right)
const {
127007 return right > *this;
127008 }
127009
127010 inline bool operator<=(
const interval_t &right)
const {
127011 return !(*this > right);
127012 }
127013
127014 inline bool operator>=(
const interval_t &right)
const {
127015 return !(*this < right);
127016 }
127017
127018
127019 void Serialize(Serializer &serializer) const;
127020 static interval_t Deserialize(Deserializer &source);
127021};
127022
127025class Interval {
127026public:
127027 static constexpr const int32_t MONTHS_PER_MILLENIUM = 12000;
127028 static constexpr const int32_t MONTHS_PER_CENTURY = 1200;
127029 static constexpr const int32_t MONTHS_PER_DECADE = 120;
127030 static constexpr const int32_t MONTHS_PER_YEAR = 12;
127031 static constexpr const int32_t MONTHS_PER_QUARTER = 3;
127032 static constexpr const int32_t DAYS_PER_WEEK = 7;
127034 static constexpr const int64_t DAYS_PER_MONTH = 30;
127035 static constexpr const int64_t DAYS_PER_YEAR = 365;
127036 static constexpr const int64_t MSECS_PER_SEC = 1000;
127037 static constexpr const int32_t SECS_PER_MINUTE = 60;
127038 static constexpr const int32_t MINS_PER_HOUR = 60;
127039 static constexpr const int32_t HOURS_PER_DAY = 24;
127040 static constexpr const int32_t SECS_PER_HOUR = SECS_PER_MINUTE * MINS_PER_HOUR;
127041 static constexpr const int32_t SECS_PER_DAY = SECS_PER_HOUR * HOURS_PER_DAY;
127042 static constexpr const int32_t SECS_PER_WEEK = SECS_PER_DAY * DAYS_PER_WEEK;
127043
127044 static constexpr const int64_t MICROS_PER_MSEC = 1000;
127045 static constexpr const int64_t MICROS_PER_SEC = MICROS_PER_MSEC * MSECS_PER_SEC;
127046 static constexpr const int64_t MICROS_PER_MINUTE = MICROS_PER_SEC * SECS_PER_MINUTE;
127047 static constexpr const int64_t MICROS_PER_HOUR = MICROS_PER_MINUTE * MINS_PER_HOUR;
127048 static constexpr const int64_t MICROS_PER_DAY = MICROS_PER_HOUR * HOURS_PER_DAY;
127049 static constexpr const int64_t MICROS_PER_WEEK = MICROS_PER_DAY * DAYS_PER_WEEK;
127050 static constexpr const int64_t MICROS_PER_MONTH = MICROS_PER_DAY * DAYS_PER_MONTH;
127051
127052 static constexpr const int64_t NANOS_PER_MICRO = 1000;
127053 static constexpr const int64_t NANOS_PER_MSEC = NANOS_PER_MICRO * MICROS_PER_MSEC;
127054 static constexpr const int64_t NANOS_PER_SEC = NANOS_PER_MSEC * MSECS_PER_SEC;
127055 static constexpr const int64_t NANOS_PER_MINUTE = NANOS_PER_SEC * SECS_PER_MINUTE;
127056 static constexpr const int64_t NANOS_PER_HOUR = NANOS_PER_MINUTE * MINS_PER_HOUR;
127057 static constexpr const int64_t NANOS_PER_DAY = NANOS_PER_HOUR * HOURS_PER_DAY;
127058 static constexpr const int64_t NANOS_PER_WEEK = NANOS_PER_DAY * DAYS_PER_WEEK;
127059
127060public:
127062 static bool FromString(const string &str, interval_t &result);
127064 static bool FromCString(const char *str, idx_t len, interval_t &result, string *error_message, bool strict);
127066 static string ToString(const interval_t &val);
127067
127069 DUCKDB_API static interval_t FromMicro(int64_t micros);
127070
127072 static int64_t GetMilli(
const interval_t &val);
127073
127075 static bool TryGetMicro(const interval_t &val, int64_t µs);
127076 static int64_t GetMicro(
const interval_t &val);
127077
127079 static int64_t GetNanoseconds(
const interval_t &val);
127080
127082 static interval_t GetAge(timestamp_t timestamp_1, timestamp_t timestamp_2);
127084 static interval_t GetAge(TimestampComponents ts1, TimestampComponents ts2, bool is_negative);
127085
127087 static interval_t GetDifference(timestamp_t timestamp_1, timestamp_t timestamp_2);
127088
127090 static interval_t Invert(interval_t interval);
127091
127093 static date_t Add(date_t left, interval_t right);
127095 static timestamp_t Add(timestamp_t left, interval_t right);
127098 static dtime_t Add(dtime_t left, interval_t right, date_t &date);
127099 static dtime_tz_t Add(dtime_tz_t left, interval_t right, date_t &date);
127100
127102 inline static bool Equals(const interval_t &left, const interval_t &right) {
127103 return left == right;
127104 }
127105 inline static bool GreaterThan(const interval_t &left, const interval_t &right) {
127106 return left > right;
127107 }
127108};
127109
127110void interval_t::Normalize(int64_t &months, int64_t &days, int64_t µs) const {
127111 auto &input = *this;
127112
127113
127114 micros = input.micros;
127115 int64_t carry_days = micros / Interval::MICROS_PER_DAY;
127116 micros -= carry_days * Interval::MICROS_PER_DAY;
127117
127118 days = input.days;
127119 days += carry_days;
127120 int64_t carry_months = days / Interval::DAYS_PER_MONTH;
127121 days -= carry_months * Interval::DAYS_PER_MONTH;
127122
127123 months = input.months;
127124 months += carry_months;
127125}
127126
127127void interval_t::Borrow(const int64_t msf, int64_t &lsf, int32_t &f, const int64_t scale) {
127128 if (msf > NumericLimits<int32_t>::Maximum()) {
127129 f = NumericLimits<int32_t>::Maximum();
127130 lsf += (msf - f) * scale;
127131 } else if (msf < NumericLimits<int32_t>::Minimum()) {
127132 f = NumericLimits<int32_t>::Minimum();
127133 lsf += (msf - f) * scale;
127134 } else {
127135 f = UnsafeNumericCast<int32_t>(msf);
127136 }
127137}
127138
127139interval_t interval_t::Normalize() const {
127140 interval_t result;
127141
127144 Normalize(mm, dd, result.micros);
127145
127146
127147 Borrow(mm, dd, result.months, Interval::DAYS_PER_MONTH);
127148 Borrow(dd, result.micros, result.days, Interval::MICROS_PER_DAY);
127149
127150 return result;
127151}
127152
127153}
127154
127155namespace std {
127156template <>
127157struct hash<duckdb::interval_t> {
127158 size_t operator()(
const duckdb::interval_t &val)
const {
127159 int64_t months, days, micros;
127160 val.Normalize(months, days, micros);
127161 using std::hash;
127162
127163 return hash<int32_t> {}(duckdb::UnsafeNumericCast<int32_t>(days)) ^
127164 hash<int32_t> {}(duckdb::UnsafeNumericCast<int32_t>(months)) ^ hash<int64_t> {}(micros);
127165 }
127166};
127167}
127168
127169
127170
127171
127172
127173
127174
127175
127176
127177
127178
127179
127180
127181
127182
127183
127184
127185
127186
127187
127188
127189
127190
127191
127192
127193
127194
127195
127196
127197
127198
127199
127200
127201#include <unordered_set>
127202
127203namespace duckdb {
127204using std::unordered_set;
127205}
127206
127207
127208
127209
127210
127211
127212
127213
127214
127215
127216
127217
127218
127219
127220#include <map>
127221
127222namespace duckdb {
127223using std::map;
127224using std::multimap;
127225}
127226
127227
127228namespace duckdb {
127229
127230struct CaseInsensitiveStringHashFunction {
127233 }
127234};
127235
127236struct CaseInsensitiveStringEquality {
127237 bool operator()(
const string &a,
const string &b)
const {
127239 }
127240};
127241
127242template <typename T>
127243using case_insensitive_map_t =
127244 unordered_map<string, T, CaseInsensitiveStringHashFunction, CaseInsensitiveStringEquality>;
127245
127246using case_insensitive_set_t = unordered_set<string, CaseInsensitiveStringHashFunction, CaseInsensitiveStringEquality>;
127247
127248struct CaseInsensitiveStringCompare {
127249 bool operator()(
const string &s1,
const string &s2)
const {
127251 }
127252};
127253
127254template <typename T>
127255using case_insensitive_tree_t = map<string, T, CaseInsensitiveStringCompare>;
127256
127257}
127258
127259
127260
127261
127262
127263
127264
127265
127266namespace duckdb {
127267
127268template <typename V>
127269class InsertionOrderPreservingMap {
127270public:
127271 typedef vector<pair<string, V>> VECTOR_TYPE;
127272 typedef string key_type;
127273
127274public:
127275 InsertionOrderPreservingMap() {
127276 }
127277
127278private:
127279 VECTOR_TYPE map;
127280 case_insensitive_map_t<idx_t> map_idx;
127281
127282public:
127283 vector<string> Keys() const {
127284 vector<string> keys;
127285 keys.resize(this->
size());
127286 for (auto &kv : map_idx) {
127287 keys[kv.second] = kv.first;
127288 }
127289
127290 return keys;
127291 }
127292
127293 typename VECTOR_TYPE::iterator begin() {
127294 return map.begin();
127295 }
127296
127297 typename VECTOR_TYPE::iterator end() {
127298 return map.end();
127299 }
127300
127301 typename VECTOR_TYPE::const_iterator begin() const {
127302 return map.begin();
127303 }
127304
127305 typename VECTOR_TYPE::const_iterator end() const {
127306 return map.end();
127307 }
127308
127309 typename VECTOR_TYPE::reverse_iterator rbegin() {
127310 return map.rbegin();
127311 }
127312
127313 typename VECTOR_TYPE::reverse_iterator rend() {
127314 return map.rend();
127315 }
127316
127317 typename VECTOR_TYPE::iterator find(const string &key) {
127318 auto entry = map_idx.find(key);
127319 if (entry == map_idx.end()) {
127320 return map.end();
127321 }
127322 return map.begin() + static_cast<typename VECTOR_TYPE::difference_type>(entry->second);
127323 }
127324
127325 typename VECTOR_TYPE::const_iterator find(const string &key) const {
127326 auto entry = map_idx.find(key);
127327 if (entry == map_idx.end()) {
127328 return map.end();
127329 }
127330 return map.begin() + static_cast<typename VECTOR_TYPE::difference_type>(entry->second);
127331 }
127332
127334 return map_idx.size();
127335 }
127336
127337 bool empty() const {
127338 return map_idx.empty();
127339 }
127340
127341 void resize(idx_t nz) {
127342 map.resize(nz);
127343 }
127344
127345 void clear() {
127346 map.clear();
127347 }
127348
127349 void insert(const string &key, V &&value) {
127350 if (contains(key)) {
127351 return;
127352 }
127353 map.emplace_back(key, std::move(value));
127354 map_idx[key] = map.size() - 1;
127355 }
127356
127357 void insert(const string &key, const V &value) {
127358 if (contains(key)) {
127359 return;
127360 }
127361 map.emplace_back(key, value);
127362 map_idx[key] = map.size() - 1;
127363 }
127364
127365 void insert(pair<string, V> &&value) {
127366 auto &key = value.first;
127367 if (contains(key)) {
127368 return;
127369 }
127370 map_idx[key] = map.size();
127371 map.push_back(std::move(value));
127372 }
127373
127374 void erase(typename VECTOR_TYPE::iterator it) {
127375 auto key = it->first;
127376 auto idx = map_idx[key];
127377 map.erase(it);
127378 map_idx.erase(key);
127379 for (auto &kv : map_idx) {
127380 if (kv.second > idx) {
127381 kv.second--;
127382 }
127383 }
127384 }
127385
127386 bool contains(const string &key) const {
127387 return map_idx.find(key) != map_idx.end();
127388 }
127389
127390 const V &
at(
const string &key)
const {
127391 return map[map_idx.at(key)].second;
127392 }
127393
127394 V &operator[](const string &key) {
127395 if (!contains(key)) {
127397 insert(key, std::move(
v));
127398 }
127399 return map[map_idx[key]].second;
127400 }
127401
127402 bool operator==(
const InsertionOrderPreservingMap &other)
const {
127403 return map == other.map && map_idx == other.map_idx;
127404 }
127405
127406 bool operator!=(
const InsertionOrderPreservingMap &other)
const {
127407 return !(*this == other);
127408 }
127409};
127410
127411}
127412
127413
127414namespace duckdb {
127415
127417class CastFunctionSet;
127418struct GetCastFunctionInput;
127419struct ExtraValueInfo;
127420
127423class Value {
127424 friend struct StringValue;
127425 friend struct StructValue;
127426 friend struct ListValue;
127427 friend struct UnionValue;
127428 friend struct ArrayValue;
127429 friend struct MapValue;
127430 friend struct TypeValue;
127431
127432public:
127434 DUCKDB_API explicit Value(LogicalType type = LogicalType::SQLNULL);
127436 DUCKDB_API Value(int32_t val);
127438 explicit DUCKDB_API Value(bool val);
127440 DUCKDB_API Value(int64_t val);
127442 DUCKDB_API Value(float val);
127444 DUCKDB_API Value(double val);
127446 DUCKDB_API Value(const char *val);
127448 DUCKDB_API Value(std::nullptr_t val);
127450 DUCKDB_API Value(string_t val);
127452 DUCKDB_API Value(string val);
127454 DUCKDB_API Value(
String val);
127456 DUCKDB_API Value(const Value &other);
127458 DUCKDB_API Value(Value &&other) noexcept;
127460 DUCKDB_API ~Value();
127461
127462
127463 DUCKDB_API Value &
operator=(
const Value &other);
127464
127465 DUCKDB_API Value &
operator=(Value &&other)
noexcept;
127466
127467 inline LogicalType &GetTypeMutable() {
127468 return type_;
127469 }
127470 inline const LogicalType &type() const {
127471 return type_;
127472 }
127473 inline bool IsNull() const {
127474 return is_null;
127475 }
127476
127478 DUCKDB_API static Value MinimumValue(const LogicalType &type);
127480 DUCKDB_API static Value MaximumValue(const LogicalType &type);
127482 DUCKDB_API static Value NegativeInfinity(const LogicalType &type);
127484 DUCKDB_API static Value Infinity(const LogicalType &type);
127486 DUCKDB_API static Value Numeric(const LogicalType &type, int64_t value);
127487 DUCKDB_API static Value Numeric(const LogicalType &type, hugeint_t value);
127488 DUCKDB_API static Value Numeric(const LogicalType &type, uhugeint_t value);
127489
127491 DUCKDB_API
static Value
BOOLEAN(
bool value);
127493 DUCKDB_API static Value TINYINT(int8_t value);
127495 DUCKDB_API static Value SMALLINT(int16_t value);
127497 DUCKDB_API static Value INTEGER(int32_t value);
127499 DUCKDB_API static Value BIGINT(int64_t value);
127501 DUCKDB_API static Value UTINYINT(uint8_t value);
127503 DUCKDB_API static Value USMALLINT(uint16_t value);
127505 DUCKDB_API static Value UINTEGER(uint32_t value);
127507 DUCKDB_API static Value UBIGINT(uint64_t value);
127509 DUCKDB_API static Value HUGEINT(hugeint_t value);
127511 DUCKDB_API static Value UHUGEINT(uhugeint_t value);
127513 DUCKDB_API static Value UUID(const string &value);
127515 DUCKDB_API static Value UUID(hugeint_t value);
127517 DUCKDB_API static Value HASH(hash_t value);
127519 DUCKDB_API static Value POINTER(uintptr_t value);
127521 DUCKDB_API static Value DATE(date_t date);
127523 DUCKDB_API static Value DATE(int32_t year, int32_t month, int32_t day);
127525 DUCKDB_API static Value TIME(dtime_t time);
127526 DUCKDB_API static Value TIME_NS(dtime_ns_t time);
127527 DUCKDB_API static Value TIMETZ(dtime_tz_t time);
127529 DUCKDB_API
static Value TIME(int32_t hour, int32_t
min, int32_t sec, int32_t micros);
127531 DUCKDB_API static Value TIMESTAMP(date_t date, dtime_t time);
127533 DUCKDB_API static Value TIMESTAMP(timestamp_t timestamp);
127535 DUCKDB_API static Value TIMESTAMPSEC(timestamp_sec_t timestamp);
127537 DUCKDB_API static Value TIMESTAMPMS(timestamp_ms_t timestamp);
127539 DUCKDB_API static Value TIMESTAMPNS(timestamp_ns_t timestamp);
127541 DUCKDB_API static Value TIMESTAMPTZ(timestamp_tz_t timestamp);
127543 DUCKDB_API
static Value TIMESTAMP(int32_t year, int32_t month, int32_t day, int32_t hour, int32_t
min, int32_t sec,
127544 int32_t micros);
127545 DUCKDB_API static Value INTERVAL(int32_t months, int32_t days, int64_t micros);
127546 DUCKDB_API static Value INTERVAL(interval_t interval);
127547
127548
127549 DUCKDB_API static Value ENUM(uint64_t value, const LogicalType &original_type);
127550
127551
127552 DUCKDB_API static Value DECIMAL(int16_t value, uint8_t width, uint8_t scale);
127553 DUCKDB_API static Value DECIMAL(int32_t value, uint8_t width, uint8_t scale);
127554 DUCKDB_API static Value DECIMAL(int64_t value, uint8_t width, uint8_t scale);
127555 DUCKDB_API static Value DECIMAL(hugeint_t value, uint8_t width, uint8_t scale);
127557 DUCKDB_API
static Value
FLOAT(
float value);
127559 DUCKDB_API
static Value
DOUBLE(
double value);
127561 DUCKDB_API static Value STRUCT(child_list_t<Value> values);
127562 DUCKDB_API static Value STRUCT(const LogicalType &type, vector<Value> struct_values);
127564 DUCKDB_API static Value VARIANT(vector<Value> children);
127566 DUCKDB_API
static Value
LIST(
const LogicalType &child_type, vector<Value> values);
127569 DUCKDB_API
static Value
LIST(vector<Value> values);
127570
127571 DUCKDB_API static Value ARRAY(const LogicalType &type, vector<Value> values);
127573 DUCKDB_API static Value MAP(const LogicalType &child_type, vector<Value> values);
127575 DUCKDB_API
static Value MAP(
const LogicalType &key_type,
const LogicalType &
value_type, vector<Value> keys,
127576 vector<Value> values);
127578 DUCKDB_API static Value MAP(const InsertionOrderPreservingMap<string> &kv_pairs);
127579
127581 DUCKDB_API static Value UNION(child_list_t<LogicalType> members, uint8_t tag, Value value);
127582
127584 DUCKDB_API static Value BLOB(const_data_ptr_t data, idx_t len);
127585 static Value BLOB_RAW(const string &data) {
127586 return Value::BLOB(const_data_ptr_cast(data.c_str()), data.size());
127587 }
127589 DUCKDB_API static Value BLOB(const string &data);
127591 DUCKDB_API static Value BIT(const_data_ptr_t data, idx_t len);
127592 DUCKDB_API static Value BIT(const string &data);
127593 DUCKDB_API static Value BIGNUM(const_data_ptr_t data, idx_t len);
127594 DUCKDB_API static Value BIGNUM(const string &data);
127595
127596 DUCKDB_API static Value GEOMETRY(const_data_ptr_t data, idx_t len);
127597 DUCKDB_API static Value GEOMETRY(const_data_ptr_t data, idx_t len, const CoordinateReferenceSystem &crs);
127598
127599 DUCKDB_API
static Value
TYPE(
const LogicalType &type);
127600 DUCKDB_API
static Value
TYPE(
const string_t &serialized_type);
127601
127603 DUCKDB_API static Value AGGREGATE_STATE(const LogicalType &type, const_data_ptr_t data, idx_t len);
127604
127605 template <class T>
127606 T GetValue() const;
127607 template <class T>
127608 static Value CreateValue(T value) {
127609 static_assert(AlwaysFalse<T>::VALUE, "No specialization exists for this type");
127610 return Value(nullptr);
127611 }
127612
127613
127614 template <class T>
127615 T GetValueUnsafe() const;
127616
127618 Value Copy() const {
127619 return Value(*this);
127620 }
127621
127623 DUCKDB_API
hash_t Hash()
const;
127625 DUCKDB_API string ToString() const;
127627 DUCKDB_API string ToSQLString() const;
127628
127629 DUCKDB_API uintptr_t GetPointer() const;
127630
127632 DUCKDB_API Value CastAs(CastFunctionSet &set, GetCastFunctionInput &get_input, const LogicalType &target_type,
127633 bool strict = false) const;
127634 DUCKDB_API Value CastAs(ClientContext &context, const LogicalType &target_type, bool strict = false) const;
127635 DUCKDB_API Value DefaultCastAs(const LogicalType &target_type, bool strict = false) const;
127637 DUCKDB_API bool TryCastAs(CastFunctionSet &set, GetCastFunctionInput &get_input, const LogicalType &target_type,
127638 Value &new_value, string *error_message, bool strict = false) const;
127639 DUCKDB_API bool TryCastAs(ClientContext &context, const LogicalType &target_type, Value &new_value,
127640 string *error_message, bool strict = false) const;
127641 DUCKDB_API bool DefaultTryCastAs(const LogicalType &target_type, Value &new_value, string *error_message,
127642 bool strict = false) const;
127644 DUCKDB_API bool TryCastAs(CastFunctionSet &set, GetCastFunctionInput &get_input, const LogicalType &target_type,
127645 bool strict = false);
127646 DUCKDB_API bool TryCastAs(ClientContext &context, const LogicalType &target_type, bool strict = false);
127647 DUCKDB_API bool DefaultTryCastAs(const LogicalType &target_type, bool strict = false);
127648
127649 DUCKDB_API void Reinterpret(LogicalType new_type);
127650
127652 DUCKDB_API void Serialize(Serializer &serializer) const;
127654 DUCKDB_API static Value Deserialize(Deserializer &deserializer);
127655
127656
127657
127658
127659 DUCKDB_API
bool operator==(
const Value &rhs)
const;
127660 DUCKDB_API
bool operator!=(
const Value &rhs)
const;
127661 DUCKDB_API
bool operator<(
const Value &rhs)
const;
127662 DUCKDB_API
bool operator>(
const Value &rhs)
const;
127663 DUCKDB_API
bool operator<=(
const Value &rhs)
const;
127664 DUCKDB_API
bool operator>=(
const Value &rhs)
const;
127665
127666 DUCKDB_API
bool operator==(
const int64_t &rhs)
const;
127667 DUCKDB_API
bool operator!=(
const int64_t &rhs)
const;
127668 DUCKDB_API
bool operator<(
const int64_t &rhs)
const;
127669 DUCKDB_API
bool operator>(
const int64_t &rhs)
const;
127670 DUCKDB_API
bool operator<=(
const int64_t &rhs)
const;
127671 DUCKDB_API
bool operator>=(
const int64_t &rhs)
const;
127672
127673 DUCKDB_API static bool FloatIsFinite(float value);
127674 DUCKDB_API static bool DoubleIsFinite(double value);
127675 template <class T>
127676 static bool IsNan(T value) {
127677 throw InternalException("Unimplemented template type for Value::IsNan");
127678 }
127679 template <class T>
127680 static bool IsFinite(T value) {
127681 return true;
127682 }
127683 DUCKDB_API static bool StringIsValid(const char *str, idx_t length);
127684 static bool StringIsValid(const string &str) {
127685 return StringIsValid(str.c_str(), str.size());
127686 }
127687
127690 DUCKDB_API static bool ValuesAreEqual(CastFunctionSet &set, GetCastFunctionInput &get_input,
127691 const Value &result_value, const Value &value);
127692 DUCKDB_API static bool ValuesAreEqual(ClientContext &context, const Value &result_value, const Value &value);
127693 DUCKDB_API static bool DefaultValuesAreEqual(const Value &result_value, const Value &value);
127695 DUCKDB_API static bool NotDistinctFrom(const Value &lvalue, const Value &rvalue);
127696
127697 friend std::ostream &
operator<<(std::ostream &out,
const Value &val) {
127699 return out;
127700 }
127701 DUCKDB_API void Print() const;
127702
127703private:
127704 void SerializeInternal(Serializer &serializer, bool serialize_type) const;
127705 static void SerializeChildren(Serializer &serializer, const vector<Value> &children,
127706 const LogicalType &parent_type);
127707
127708private:
127710 LogicalType type_;
127711
127713 bool is_null;
127714
127716 union Val {
127717 bool boolean;
127726 hugeint_t hugeint;
127727 uhugeint_t uhugeint;
127728 float float_;
127729 double double_;
127730 uintptr_t pointer;
127732 date_t date;
127733 dtime_t time;
127734 dtime_ns_t time_ns;
127735 dtime_tz_t timetz;
127737 timestamp_sec_t timestamp_s;
127738 timestamp_ms_t timestamp_ms;
127739 timestamp_ns_t timestamp_ns;
127740 timestamp_tz_t timestamp_tz;
127741 interval_t interval;
127742 } value_;
127743
127744 shared_ptr<ExtraValueInfo> value_info_;
127745
127746private:
127747 template <class T>
127748 T GetValueInternal() const;
127749};
127750
127751
127752
127753
127754
127755
127756struct BooleanValue {
127757 DUCKDB_API static bool Get(const Value &value);
127758};
127759
127760struct TinyIntValue {
127761 DUCKDB_API
static int8_t Get(
const Value &value);
127762};
127763
127764struct SmallIntValue {
127765 DUCKDB_API
static int16_t Get(
const Value &value);
127766};
127767
127768struct IntegerValue {
127769 DUCKDB_API
static int32_t Get(
const Value &value);
127770};
127771
127772struct BigIntValue {
127773 DUCKDB_API
static int64_t Get(
const Value &value);
127774};
127775
127776struct HugeIntValue {
127777 DUCKDB_API static hugeint_t Get(const Value &value);
127778};
127779
127780struct UTinyIntValue {
127781 DUCKDB_API
static uint8_t Get(
const Value &value);
127782};
127783
127784struct USmallIntValue {
127785 DUCKDB_API
static uint16_t Get(
const Value &value);
127786};
127787
127788struct UIntegerValue {
127789 DUCKDB_API
static uint32_t Get(
const Value &value);
127790};
127791
127792struct UBigIntValue {
127793 DUCKDB_API
static uint64_t Get(
const Value &value);
127794};
127795
127796struct UhugeIntValue {
127797 DUCKDB_API static uhugeint_t Get(const Value &value);
127798};
127799
127800struct FloatValue {
127801 DUCKDB_API static float Get(const Value &value);
127802};
127803
127804struct DoubleValue {
127805 DUCKDB_API static double Get(const Value &value);
127806};
127807
127808struct StringValue {
127809 DUCKDB_API static const string &Get(const Value &value);
127810};
127811
127812struct DateValue {
127813 DUCKDB_API static date_t Get(const Value &value);
127814};
127815
127816struct TimeValue {
127817 DUCKDB_API static dtime_t Get(const Value &value);
127818};
127819
127820struct TimestampValue {
127821 DUCKDB_API static timestamp_t Get(const Value &value);
127822};
127823
127824struct TimestampSValue {
127825 DUCKDB_API static timestamp_sec_t Get(const Value &value);
127826};
127827
127828struct TimestampMSValue {
127829 DUCKDB_API static timestamp_ms_t Get(const Value &value);
127830};
127831
127832struct TimestampNSValue {
127833 DUCKDB_API static timestamp_ns_t Get(const Value &value);
127834};
127835
127836struct TimestampTZValue {
127837 DUCKDB_API static timestamp_tz_t Get(const Value &value);
127838};
127839
127840struct IntervalValue {
127841 DUCKDB_API static interval_t Get(const Value &value);
127842};
127843
127844struct StructValue {
127845 DUCKDB_API static const vector<Value> &GetChildren(const Value &value);
127846};
127847
127848struct MapValue {
127849 DUCKDB_API static const vector<Value> &GetChildren(const Value &value);
127850};
127851
127852struct ListValue {
127853 DUCKDB_API static const vector<Value> &GetChildren(const Value &value);
127854};
127855
127856struct ArrayValue {
127857 DUCKDB_API static const vector<Value> &GetChildren(const Value &value);
127858};
127859
127860struct UnionValue {
127861 DUCKDB_API static const Value &GetValue(const Value &value);
127862 DUCKDB_API
static uint8_t GetTag(
const Value &value);
127863 DUCKDB_API static const LogicalType &GetType(const Value &value);
127864};
127865
127866struct TypeValue {
127867 DUCKDB_API static LogicalType GetType(const Value &value);
127868};
127869
127872struct IntegralValue {
127873 static hugeint_t Get(const Value &value);
127874};
127875
127876template <>
127877Value DUCKDB_API Value::CreateValue(bool value);
127878template <>
127879Value DUCKDB_API Value::CreateValue(uint8_t value);
127880template <>
127881Value DUCKDB_API Value::CreateValue(uint16_t value);
127882template <>
127883Value DUCKDB_API Value::CreateValue(uint32_t value);
127884template <>
127885Value DUCKDB_API Value::CreateValue(uint64_t value);
127886template <>
127887Value DUCKDB_API Value::CreateValue(int8_t value);
127888template <>
127889Value DUCKDB_API Value::CreateValue(int16_t value);
127890template <>
127891Value DUCKDB_API Value::CreateValue(int32_t value);
127892template <>
127893Value DUCKDB_API Value::CreateValue(int64_t value);
127894template <>
127895Value DUCKDB_API Value::CreateValue(hugeint_t value);
127896template <>
127897Value DUCKDB_API Value::CreateValue(uhugeint_t value);
127898template <>
127899Value DUCKDB_API Value::CreateValue(date_t value);
127900template <>
127901Value DUCKDB_API Value::CreateValue(dtime_t value);
127902template <>
127903Value DUCKDB_API Value::CreateValue(dtime_ns_t value);
127904template <>
127905Value DUCKDB_API Value::CreateValue(dtime_tz_t value);
127906template <>
127907Value DUCKDB_API Value::CreateValue(timestamp_t value);
127908template <>
127909Value DUCKDB_API Value::CreateValue(timestamp_sec_t value);
127910template <>
127911Value DUCKDB_API Value::CreateValue(timestamp_ms_t value);
127912template <>
127913Value DUCKDB_API Value::CreateValue(timestamp_ns_t value);
127914template <>
127915Value DUCKDB_API Value::CreateValue(timestamp_tz_t value);
127916template <>
127917Value DUCKDB_API Value::CreateValue(const char *value);
127918template <>
127919Value DUCKDB_API Value::CreateValue(string value);
127920template <>
127921Value DUCKDB_API Value::CreateValue(string_t value);
127922template <>
127923Value DUCKDB_API Value::CreateValue(float value);
127924template <>
127925Value DUCKDB_API Value::CreateValue(double value);
127926template <>
127927Value DUCKDB_API Value::CreateValue(interval_t value);
127928template <>
127929Value DUCKDB_API Value::CreateValue(Value value);
127930
127931template <>
127932DUCKDB_API bool Value::GetValue() const;
127933template <>
127934DUCKDB_API
int8_t Value::GetValue()
const;
127935template <>
127936DUCKDB_API
int16_t Value::GetValue()
const;
127937template <>
127938DUCKDB_API
int32_t Value::GetValue()
const;
127939template <>
127940DUCKDB_API
int64_t Value::GetValue()
const;
127941template <>
127942DUCKDB_API
uint8_t Value::GetValue()
const;
127943template <>
127944DUCKDB_API
uint16_t Value::GetValue()
const;
127945template <>
127946DUCKDB_API
uint32_t Value::GetValue()
const;
127947template <>
127948DUCKDB_API
uint64_t Value::GetValue()
const;
127949template <>
127950DUCKDB_API hugeint_t Value::GetValue() const;
127951template <>
127952DUCKDB_API uhugeint_t Value::GetValue() const;
127953template <>
127954DUCKDB_API string Value::GetValue() const;
127955template <>
127956DUCKDB_API float Value::GetValue() const;
127957template <>
127958DUCKDB_API double Value::GetValue() const;
127959template <>
127960DUCKDB_API date_t Value::GetValue() const;
127961template <>
127962DUCKDB_API dtime_t Value::GetValue() const;
127963template <>
127964DUCKDB_API dtime_ns_t Value::GetValue() const;
127965template <>
127966DUCKDB_API dtime_tz_t Value::GetValue() const;
127967template <>
127968DUCKDB_API timestamp_t Value::GetValue() const;
127969template <>
127970DUCKDB_API timestamp_sec_t Value::GetValue() const;
127971template <>
127972DUCKDB_API timestamp_ms_t Value::GetValue() const;
127973template <>
127974DUCKDB_API timestamp_ns_t Value::GetValue() const;
127975template <>
127976DUCKDB_API timestamp_tz_t Value::GetValue() const;
127977template <>
127978DUCKDB_API interval_t Value::GetValue() const;
127979template <>
127980DUCKDB_API Value Value::GetValue() const;
127981
127982template <>
127983DUCKDB_API bool Value::GetValueUnsafe() const;
127984template <>
127985DUCKDB_API
int8_t Value::GetValueUnsafe()
const;
127986template <>
127987DUCKDB_API
int16_t Value::GetValueUnsafe()
const;
127988template <>
127989DUCKDB_API
int32_t Value::GetValueUnsafe()
const;
127990template <>
127991DUCKDB_API
int64_t Value::GetValueUnsafe()
const;
127992template <>
127993DUCKDB_API hugeint_t Value::GetValueUnsafe() const;
127994template <>
127995DUCKDB_API uhugeint_t Value::GetValueUnsafe() const;
127996template <>
127997DUCKDB_API
uint8_t Value::GetValueUnsafe()
const;
127998template <>
127999DUCKDB_API
uint16_t Value::GetValueUnsafe()
const;
128000template <>
128001DUCKDB_API
uint32_t Value::GetValueUnsafe()
const;
128002template <>
128003DUCKDB_API
uint64_t Value::GetValueUnsafe()
const;
128004template <>
128005DUCKDB_API string Value::GetValueUnsafe() const;
128006template <>
128007DUCKDB_API string_t Value::GetValueUnsafe() const;
128008template <>
128009DUCKDB_API float Value::GetValueUnsafe() const;
128010template <>
128011DUCKDB_API double Value::GetValueUnsafe() const;
128012template <>
128013DUCKDB_API date_t Value::GetValueUnsafe() const;
128014template <>
128015DUCKDB_API dtime_t Value::GetValueUnsafe() const;
128016template <>
128017DUCKDB_API dtime_ns_t Value::GetValueUnsafe() const;
128018template <>
128019DUCKDB_API dtime_tz_t Value::GetValueUnsafe() const;
128020template <>
128021DUCKDB_API timestamp_t Value::GetValueUnsafe() const;
128022template <>
128023DUCKDB_API timestamp_sec_t Value::GetValueUnsafe() const;
128024template <>
128025DUCKDB_API timestamp_ms_t Value::GetValueUnsafe() const;
128026template <>
128027DUCKDB_API timestamp_ns_t Value::GetValueUnsafe() const;
128028template <>
128029DUCKDB_API timestamp_tz_t Value::GetValueUnsafe() const;
128030template <>
128031DUCKDB_API interval_t Value::GetValueUnsafe() const;
128032
128033template <>
128034DUCKDB_API bool Value::IsNan(float input);
128035template <>
128036DUCKDB_API bool Value::IsNan(double input);
128037
128038template <>
128039DUCKDB_API bool Value::IsFinite(float input);
128040template <>
128041DUCKDB_API bool Value::IsFinite(double input);
128042template <>
128043DUCKDB_API bool Value::IsFinite(date_t input);
128044template <>
128045DUCKDB_API bool Value::IsFinite(timestamp_t input);
128046template <>
128047DUCKDB_API bool Value::IsFinite(timestamp_sec_t input);
128048template <>
128049DUCKDB_API bool Value::IsFinite(timestamp_ms_t input);
128050template <>
128051DUCKDB_API bool Value::IsFinite(timestamp_ns_t input);
128052template <>
128053DUCKDB_API bool Value::IsFinite(timestamp_tz_t input);
128054
128055}
128056
128057#include <memory>
128058
128059namespace duckdb {
128060
128061class Catalog;
128062class CatalogSet;
128063class ClientContext;
128064class Deserializer;
128065class SchemaCatalogEntry;
128066class Serializer;
128067class Value;
128068
128069struct AlterInfo;
128070struct CatalogTransaction;
128071struct CreateInfo;
128072
128074class CatalogEntry {
128075public:
128076 CatalogEntry(CatalogType type, Catalog &catalog, string name);
128077 CatalogEntry(CatalogType type, string name, idx_t oid);
128078 virtual ~CatalogEntry();
128079
128083 CatalogType type;
128085 optional_ptr<CatalogSet> set;
128087 string name;
128089 bool deleted;
128091 bool temporary;
128093 bool internal;
128097 Value comment;
128099 InsertionOrderPreservingMap<string> tags;
128100
128101private:
128103 unique_ptr<CatalogEntry> child;
128105 optional_ptr<CatalogEntry> parent;
128106
128107public:
128108 virtual unique_ptr<CatalogEntry> AlterEntry(ClientContext &context, AlterInfo &info);
128109 virtual unique_ptr<CatalogEntry> AlterEntry(CatalogTransaction transaction, AlterInfo &info);
128110 virtual void UndoAlter(ClientContext &context, AlterInfo &info);
128111 virtual void Rollback(CatalogEntry &prev_entry);
128112 virtual void OnDrop();
128113
128114 virtual unique_ptr<CatalogEntry> Copy(ClientContext &context) const;
128115
128116 virtual unique_ptr<CreateInfo> GetInfo() const;
128117
128119
128120 virtual void SetAsRoot();
128121
128123 virtual string ToSQL() const;
128124
128125 virtual Catalog &ParentCatalog();
128126 virtual const Catalog &ParentCatalog() const;
128127 virtual SchemaCatalogEntry &ParentSchema();
128128 virtual const SchemaCatalogEntry &ParentSchema() const;
128129
128130 virtual void Verify(Catalog &catalog);
128131
128132 void Serialize(Serializer &serializer) const;
128133 static unique_ptr<CreateInfo> Deserialize(Deserializer &deserializer);
128134
128135public:
128136 void SetChild(unique_ptr<CatalogEntry> child);
128137 unique_ptr<CatalogEntry> TakeChild();
128138 bool HasChild() const;
128139 bool HasParent() const;
128140 CatalogEntry &Child();
128141 CatalogEntry &Parent();
128142 const CatalogEntry &Parent() const;
128143
128144public:
128145 template <class TARGET>
128146 TARGET &Cast() {
128147 DynamicCastCheck<TARGET>(this);
128148 return reinterpret_cast<TARGET &>(*this);
128149 }
128150 template <class TARGET>
128151 const TARGET &Cast() const {
128152 DynamicCastCheck<TARGET>(this);
128153 return reinterpret_cast<const TARGET &>(*this);
128154 }
128155};
128156
128157class InCatalogEntry : public CatalogEntry {
128158public:
128159 InCatalogEntry(CatalogType type, Catalog &catalog, string name);
128160 ~InCatalogEntry() override;
128161
128163 Catalog &catalog;
128164
128165public:
128166 Catalog &ParentCatalog() override {
128167 return catalog;
128168 }
128169 const Catalog &ParentCatalog() const override {
128170 return catalog;
128171 }
128172
128173 void Verify(Catalog &catalog) override;
128174};
128175
128176}
128177
128178
128179
128180
128181
128182
128183
128184
128185
128186
128187
128188
128189
128190
128191namespace duckdb {
128192class Catalog;
128193class ClientContext;
128194class DatabaseInstance;
128195class Transaction;
128196
128197struct CatalogTransaction {
128198 CatalogTransaction(Catalog &catalog, ClientContext &context);
128199 CatalogTransaction(DatabaseInstance &db, transaction_t transaction_id_p, transaction_t start_time_p);
128200
128201 optional_ptr<DatabaseInstance>
db;
128202 optional_ptr<ClientContext> context;
128203 optional_ptr<Transaction> transaction;
128206
128207 bool HasContext() const {
128208 return context;
128209 }
128210 ClientContext &GetContext();
128211
128212 static CatalogTransaction GetSystemCatalogTransaction(ClientContext &context);
128213 static CatalogTransaction GetSystemTransaction(DatabaseInstance &db);
128214};
128215
128216}
128217
128218
128219
128220
128221
128222
128223
128224
128225
128226
128227
128228
128229
128230
128231namespace duckdb {
128232
128234
128235
128236
128238
128239}
128240
128241
128242
128243
128244
128245
128246
128247
128248
128249
128250
128251
128252
128253namespace duckdb {
128254
128255enum class OnEntryNotFound :
uint8_t { THROW_EXCEPTION = 0, RETURN_NULL = 1 };
128256
128257}
128258
128259
128260
128261
128262
128263
128264
128265
128266
128267
128268
128269
128270
128271
128272namespace duckdb {
128273class ParsedExpression;
128274class TableRef;
128275
128276class ErrorData {
128277public:
128279 DUCKDB_API ErrorData();
128281 DUCKDB_API ErrorData(const std::exception &ex);
128283 DUCKDB_API ErrorData(ExceptionType type, const string &raw_message);
128285 DUCKDB_API explicit ErrorData(const string &raw_message);
128286
128287public:
128289 [[noreturn]] DUCKDB_API void Throw(const string &prepended_message = "") const;
128291 DUCKDB_API const ExceptionType &Type() const;
128293 DUCKDB_API const string &Message() const {
128294 return final_message;
128295 }
128296 DUCKDB_API const string &RawMessage() const {
128297 return raw_message;
128298 }
128299 DUCKDB_API void Merge(const ErrorData &other);
128300 DUCKDB_API
bool operator==(
const ErrorData &other)
const;
128301
128303 inline bool HasError() const {
128304 return initialized;
128305 }
128306 const unordered_map<string, string> &ExtraInfo() const {
128307 return extra_info;
128308 }
128309
128310 DUCKDB_API void FinalizeError();
128311 DUCKDB_API void AddErrorLocation(const string &query);
128312 DUCKDB_API void ConvertErrorToJSON();
128313
128314 DUCKDB_API void AddQueryLocation(optional_idx query_location);
128315 DUCKDB_API void AddQueryLocation(QueryErrorContext error_context);
128316 DUCKDB_API void AddQueryLocation(const ParsedExpression &ref);
128317 DUCKDB_API void AddQueryLocation(const TableRef &ref);
128318
128319private:
128321 bool initialized;
128323 ExceptionType type;
128325 string raw_message;
128327 string final_message;
128329 unordered_map<string, string> extra_info;
128330
128331private:
128332 DUCKDB_API static string SanitizeErrorMessage(string error);
128333 DUCKDB_API string ConstructFinalMessage() const;
128334};
128335
128336}
128337
128338
128339
128340
128341
128342
128343
128344
128345
128346
128347
128348
128349
128350#ifdef __MVS__
128351#include <time.h>
128352#endif
128353#include <mutex>
128354
128355namespace duckdb {
128356using std::lock_guard;
128357using std::mutex;
128358using std::unique_lock;
128359}
128360
128361
128362
128363
128364
128365
128366
128367
128368
128369
128370
128371
128372
128373
128374
128375
128376namespace duckdb {
128377class Expression;
128378
128379template <class T>
128380struct ReferenceHashFunction {
128382 return std::hash<void *>()((void *)&ref.get());
128383 }
128384};
128385
128386template <class T>
128387struct ReferenceEquality {
128388 bool operator()(
const reference<T> &a,
const reference<T> &b)
const {
128389 return &a.get() == &b.get();
128390 }
128391};
128392
128393template <typename T, typename TGT>
128394using reference_map_t = unordered_map<reference<T>, TGT, ReferenceHashFunction<T>, ReferenceEquality<T>>;
128395
128396template <typename T>
128397using reference_set_t = unordered_set<reference<T>, ReferenceHashFunction<T>, ReferenceEquality<T>>;
128398
128399}
128400
128401
128402
128403
128404
128405
128406
128407
128408
128409
128410
128411
128412
128413
128414
128415
128416namespace duckdb {
128417class BoundAtClause;
128418
128419struct EntryLookupInfo {
128420public:
128421 EntryLookupInfo(CatalogType catalog_type, const string &name,
128422 QueryErrorContext error_context = QueryErrorContext());
128423 EntryLookupInfo(CatalogType catalog_type, const string &name, optional_ptr<BoundAtClause> at_clause,
128424 QueryErrorContext error_context);
128425 EntryLookupInfo(const EntryLookupInfo &parent, const string &name);
128426 EntryLookupInfo(const EntryLookupInfo &parent, optional_ptr<BoundAtClause> at_clause);
128427
128428public:
128429 CatalogType GetCatalogType() const;
128430 const string &GetEntryName() const;
128431 const QueryErrorContext &GetErrorContext() const;
128432 const optional_ptr<BoundAtClause> GetAtClause() const;
128433
128434 static EntryLookupInfo SchemaLookup(const EntryLookupInfo &parent, const string &schema_name);
128435
128436private:
128437 CatalogType catalog_type;
128438 const string &name;
128439 optional_ptr<BoundAtClause> at_clause;
128440 QueryErrorContext error_context;
128441};
128442
128444struct CatalogEntryLookup {
128445 optional_ptr<SchemaCatalogEntry> schema;
128446 optional_ptr<CatalogEntry> entry;
128447 ErrorData error;
128448
128449 DUCKDB_API bool Found() const {
128450 return entry;
128451 }
128452};
128453
128454}
128455
128456
128457
128458
128459
128460
128461
128462
128463
128464
128465
128466#include <string>
128467#include <cstring>
128468
128469
128470
128471
128472
128473namespace duckdb {
128474
128476
128477
128478
128479
128480
128481
128482
128483
128484
128485
128486public:
128487
128488 String() : len(0), buf {0} {
128489 }
128490
128491 String(
const std::string &str) {
128492 AssignOwning(str.data(), SafeStrLen(str));
128493 }
128494
128495 String(
const char *str,
const uint32_t size) {
128496 AssignOwning(str, size);
128497 }
128498
128499 String(
const char *str)
128500 :
String(str, str ? SafeStrLen(str) : 0) {
128501 }
128502
128503public:
128504
128507
128508
128510 TransferOwnership(other);
128511 }
128512
128513
128515 if (this != &other) {
128516 Destroy();
128517 TransferOwnership(other);
128518 }
128519 return *this;
128520 }
128521
128522
128523 ~String() {
128524 Destroy();
128525 }
128526
128527public:
128528
128530 if (this == &other) {
128531 return true;
128532 }
128533
128534 if (
size() != other.size()) {
128535 return false;
128536 }
128537
128538 return memcmp(data(), other.data(),
size()) == 0;
128539 }
128540
128541 bool operator==(
const std::string &other)
const {
128542 if (SafeStrLen(other) !=
size()) {
128543 return false;
128544 }
128545 return memcmp(data(), other.data(),
size()) == 0;
128546 }
128547
128549 if (!other || SafeStrLen(other) !=
size()) {
128550 return false;
128551 }
128552
128553 if (this->data() == other) {
128554 return true;
128555 }
128556
128557 return memcmp(data(), other,
size()) == 0;
128558 }
128559
128561 const auto this_size =
size();
128562 const auto other_size = other.size();
128563 const auto min_size = MinValue<idx_t>(this_size, other_size);
128564
128565 auto memcmp_res = memcmp(data(), other.data(), min_size);
128566 return memcmp_res > 0 || (memcmp_res == 0 && this_size > other_size);
128567 }
128568
128570 return !(*this == other);
128571 }
128573 return other > *this;
128574 }
128576 return !(*this < other);
128577 }
128579 return !(*this > other);
128580 }
128581
128582 char operator[](const idx_t pos) const {
128583 D_ASSERT(pos <
size());
128584
128585 if (IsInlined()) {
128586 return buf[pos];
128587 }
128588 return ptr[pos];
128589 }
128590
128591public:
128592
128593
128595 return len & ~NON_OWNING_BIT;
128596 }
128597 bool empty() const {
128598 return len == 0;
128599 }
128600 const char *data() const {
128601 return IsInlined() ? buf : ptr;
128602 }
128603 const char *begin() const {
128604 return data();
128605 }
128606 const char *end() const {
128607 return data() +
size();
128608 }
128609 const char *c_str() const {
128610 return data();
128611 }
128612
128613
128614
128615 bool IsOwning() const {
128616 return (len & NON_OWNING_BIT) == 0;
128617 }
128618
128619 bool IsInlined() const {
128620 return len <= INLINE_MAX;
128621 }
128622
128623 static bool CanBeInlined(uint32_t size) {
128624 return size <= INLINE_MAX;
128625 }
128626
128627
128628 static String Copy(
const char *data, uint32_t size) {
128629 if (data == nullptr) {
128631 }
128632
128634 result.AssignOwning(data, size);
128635 return result;
128636 }
128637
128639 return Copy(other.data(), other.size());
128640 }
128641 static String Copy(
const char *data) {
128642 return Copy(data, data ? SafeStrLen(data) : 0);
128643 }
128644 static String Copy(
const std::string &str) {
128645 return Copy(str.data(), SafeStrLen(str));
128646 }
128648 return String::Copy(data(),
size());
128649 }
128650
128651
128652
128653 static String Reference(
const char *data, uint32_t size) {
128654 if (data == nullptr) {
128656 }
128657
128659
128660 if (size <= INLINE_MAX) {
128661 result.AssignOwning(data, size);
128662 } else {
128663 result.ptr = const_cast<char *>(data);
128664 result.len =
size | NON_OWNING_BIT;
128665 }
128666 return result;
128667 }
128668
128670 return Reference(other.data(), other.size());
128671 }
128672 static String Reference(
const char *data) {
128673 return Reference(data, data ? SafeStrLen(data) : 0);
128674 }
128675 static String Reference(
const std::string &str) {
128676 return Reference(str.data(), SafeStrLen(str));
128677 }
128678 String Reference()
const {
128679 return String::Reference(data(),
size());
128680 }
128681
128682 std::string ToStdString() const {
128683 if (IsInlined()) {
128684 return std::string(buf,
size());
128685 }
128686 return std::string(ptr,
size());
128687 }
128688
128689 static uint32_t SafeStrLen(
const char *data) {
128690 if (!data) {
128691 return 0;
128692 }
128693
128694 const auto len = strlen(data);
128695 D_ASSERT(len < NumericLimits<uint32_t>::Maximum());
128696 return static_cast<uint32_t>(len);
128697 }
128698
128699 static uint32_t SafeStrLen(
const std::string &data) {
128700 const auto len = data.size();
128701 D_ASSERT(len < NumericLimits<uint32_t>::Maximum());
128702 return static_cast<uint32_t>(len);
128703 }
128704
128705public:
128706 static char CharacterToLower(char c) {
128707 if (c >= 'A' && c <= 'Z') {
128708 return UnsafeNumericCast<char>(c + ('a' - 'A'));
128709 }
128710 return c;
128711 }
128712
128714 const auto str_data = data();
128715 const auto str_size =
size();
128716
128717 std::string lowercase_str;
128718 lowercase_str.reserve(str_size);
128719 for (idx_t i = 0; i < str_size; ++i) {
128720 lowercase_str.push_back(CharacterToLower(str_data[i]));
128721 }
128722 return String(lowercase_str);
128723 }
128724
128725private:
128726 static constexpr auto INLINE_CAP = sizeof(char *);
128727 static constexpr auto INLINE_MAX = INLINE_CAP - 1;
128728 static constexpr auto NON_OWNING_BIT = 1UL << (
sizeof(
uint32_t) * 8 - 1);
128729 static constexpr auto LENGTH_MAX = (1UL << (
sizeof(
uint32_t) * 8 - 1)) - 1;
128730
128731 void AssignOwning(const char *new_data, uint32_t new_size) {
128732 len = new_data ? new_size : 0;
128733
128734 if (len == 0) {
128735 buf[len] = '\0';
128736 return;
128737 }
128738
128739 if (len <= INLINE_MAX) {
128740 memcpy(buf, new_data, len);
128741 buf[len] = '\0';
128742 return;
128743 }
128744
128745 auto new_ptr = new char[len + 1];
128746 memcpy(new_ptr, new_data, len);
128747 new_ptr[len] = '\0';
128748
128749 ptr = new_ptr;
128750 }
128751
128752 void Destroy() {
128753 if (IsOwning() && !IsInlined()) {
128754 delete[] ptr;
128755 }
128756 }
128757
128758
128759 void ReleaseOwning() {
128760
128761 if (IsOwning() && !IsInlined()) {
128762 len |= NON_OWNING_BIT;
128763 }
128764 }
128765
128766 void TransferOwnership(
String &other) {
128767 len = other.len;
128768 if (IsInlined()) {
128769 AssignOwning(other.data(), other.size());
128770 } else {
128771 ptr = other.ptr;
128772 len = other.len;
128773 }
128774 other.ReleaseOwning();
128775 }
128776
128777private:
128779 union {
128780 const char *ptr;
128781 char buf[INLINE_CAP];
128782 };
128783};
128784
128786 return rhs == lhs;
128787}
128788
128790 return rhs == lhs;
128791}
128792
128793}
128794
128795
128796#include <functional>
128797
128798namespace duckdb {
128799struct AttachOptions;
128800struct CreateSchemaInfo;
128801struct DropInfo;
128802struct BoundCreateTableInfo;
128803struct AlterTableInfo;
128804struct CreateTableFunctionInfo;
128805struct CreateCopyFunctionInfo;
128806struct CreatePragmaFunctionInfo;
128807struct CreateFunctionInfo;
128808struct CreateViewInfo;
128809struct CreateSequenceInfo;
128810struct CreateCollationInfo;
128811struct CreateCoordinateSystemInfo;
128812struct CreateIndexInfo;
128813struct CreateTypeInfo;
128814struct CreateTableInfo;
128815struct DatabaseSize;
128816struct MetadataBlockInfo;
128817
128818class AttachedDatabase;
128819class ClientContext;
128820class QueryContext;
128821class Transaction;
128822
128823class AggregateFunctionCatalogEntry;
128824class CollateCatalogEntry;
128825class SchemaCatalogEntry;
128826class TableCatalogEntry;
128827class ViewCatalogEntry;
128828class SequenceCatalogEntry;
128829class TableFunctionCatalogEntry;
128830class CopyFunctionCatalogEntry;
128831class PragmaFunctionCatalogEntry;
128832class CatalogSet;
128833class DatabaseInstance;
128834class DependencyManager;
128835
128836struct CatalogLookup;
128837struct CatalogEntryLookup;
128838struct SimilarCatalogEntry;
128839
128840class Binder;
128841class LogicalOperator;
128842class LogicalMergeInto;
128843class PhysicalOperator;
128844class PhysicalPlanGenerator;
128845class LogicalCreateIndex;
128846class LogicalCreateTable;
128847class LogicalInsert;
128848class LogicalDelete;
128849class LogicalUpdate;
128850class CreateStatement;
128851class CatalogEntryRetriever;
128852
128854class Catalog {
128855public:
128856 explicit Catalog(AttachedDatabase &db);
128857 virtual ~Catalog();
128858
128859public:
128861 DUCKDB_API static Catalog &GetSystemCatalog(ClientContext &context);
128863 DUCKDB_API static Catalog &GetSystemCatalog(DatabaseInstance &db);
128865 DUCKDB_API static Catalog &GetCatalog(ClientContext &context, const string &catalog_name);
128867 DUCKDB_API static Catalog &GetCatalog(CatalogEntryRetriever &retriever, const string &catalog_name);
128869 DUCKDB_API static Catalog &GetCatalog(DatabaseInstance &db, const string &catalog_name);
128871 DUCKDB_API static optional_ptr<Catalog> GetCatalogEntry(ClientContext &context, const string &catalog_name);
128873 DUCKDB_API static optional_ptr<Catalog> GetCatalogEntry(CatalogEntryRetriever &retriever,
128874 const string &catalog_name);
128876 DUCKDB_API static Catalog &GetCatalog(AttachedDatabase &db);
128877
128878 DUCKDB_API AttachedDatabase &GetAttached();
128879 DUCKDB_API const AttachedDatabase &GetAttached() const;
128880 DUCKDB_API DatabaseInstance &GetDatabase();
128881
128882 virtual bool IsDuckCatalog() {
128883 return false;
128884 }
128885
128886 virtual void Initialize(bool load_builtin) = 0;
128887 virtual void Initialize(optional_ptr<ClientContext> context, bool load_builtin);
128888 virtual void FinalizeLoad(optional_ptr<ClientContext> context);
128889
128890 bool IsSystemCatalog() const;
128891 bool IsTemporaryCatalog() const;
128892
128897 DUCKDB_API virtual optional_idx GetCatalogVersion(ClientContext &context) {
128898 return {};
128899 }
128900
128902 DUCKDB_API const string &GetName() const;
128903 DUCKDB_API
idx_t GetOid();
128904 DUCKDB_API virtual string GetCatalogType() = 0;
128905
128906 DUCKDB_API CatalogTransaction GetCatalogTransaction(ClientContext &context);
128907
128909 DUCKDB_API virtual optional_ptr<CatalogEntry> CreateSchema(CatalogTransaction transaction,
128910 CreateSchemaInfo &info) = 0;
128911 DUCKDB_API optional_ptr<CatalogEntry> CreateSchema(ClientContext &context, CreateSchemaInfo &info);
128913 DUCKDB_API optional_ptr<CatalogEntry> CreateTable(CatalogTransaction transaction, BoundCreateTableInfo &info);
128914 DUCKDB_API optional_ptr<CatalogEntry> CreateTable(ClientContext &context, BoundCreateTableInfo &info);
128916 DUCKDB_API optional_ptr<CatalogEntry> CreateTable(ClientContext &context, unique_ptr<CreateTableInfo> info);
128918 DUCKDB_API optional_ptr<CatalogEntry> CreateTableFunction(CatalogTransaction transaction,
128919 CreateTableFunctionInfo &info);
128920 DUCKDB_API optional_ptr<CatalogEntry> CreateTableFunction(ClientContext &context, CreateTableFunctionInfo &info);
128921
128922 DUCKDB_API optional_ptr<CatalogEntry> CreateTableFunction(ClientContext &context,
128923 optional_ptr<CreateTableFunctionInfo> info);
128925 DUCKDB_API optional_ptr<CatalogEntry> CreateCopyFunction(CatalogTransaction transaction,
128926 CreateCopyFunctionInfo &info);
128927 DUCKDB_API optional_ptr<CatalogEntry> CreateCopyFunction(ClientContext &context, CreateCopyFunctionInfo &info);
128929 DUCKDB_API optional_ptr<CatalogEntry> CreatePragmaFunction(CatalogTransaction transaction,
128930 CreatePragmaFunctionInfo &info);
128931 DUCKDB_API optional_ptr<CatalogEntry> CreatePragmaFunction(ClientContext &context, CreatePragmaFunctionInfo &info);
128933 DUCKDB_API optional_ptr<CatalogEntry> CreateFunction(CatalogTransaction transaction, CreateFunctionInfo &info);
128934 DUCKDB_API optional_ptr<CatalogEntry> CreateFunction(ClientContext &context, CreateFunctionInfo &info);
128936 DUCKDB_API optional_ptr<CatalogEntry> CreateView(CatalogTransaction transaction, CreateViewInfo &info);
128937 DUCKDB_API optional_ptr<CatalogEntry> CreateView(ClientContext &context, CreateViewInfo &info);
128939 DUCKDB_API optional_ptr<CatalogEntry> CreateSequence(CatalogTransaction transaction, CreateSequenceInfo &info);
128940 DUCKDB_API optional_ptr<CatalogEntry> CreateSequence(ClientContext &context, CreateSequenceInfo &info);
128942 DUCKDB_API optional_ptr<CatalogEntry> CreateType(CatalogTransaction transaction, CreateTypeInfo &info);
128943 DUCKDB_API optional_ptr<CatalogEntry> CreateType(ClientContext &context, CreateTypeInfo &info);
128945 DUCKDB_API optional_ptr<CatalogEntry> CreateCollation(CatalogTransaction transaction, CreateCollationInfo &info);
128946 DUCKDB_API optional_ptr<CatalogEntry> CreateCollation(ClientContext &context, CreateCollationInfo &info);
128948 DUCKDB_API optional_ptr<CatalogEntry> CreateCoordinateSystem(CatalogTransaction transaction,
128949 CreateCoordinateSystemInfo &info);
128950 DUCKDB_API optional_ptr<CatalogEntry> CreateCoordinateSystem(ClientContext &context,
128951 CreateCoordinateSystemInfo &info);
128953 DUCKDB_API optional_ptr<CatalogEntry> CreateIndex(CatalogTransaction transaction, CreateIndexInfo &info);
128954 DUCKDB_API optional_ptr<CatalogEntry> CreateIndex(ClientContext &context, CreateIndexInfo &info);
128955
128957 DUCKDB_API optional_ptr<CatalogEntry> CreateTable(CatalogTransaction transaction, SchemaCatalogEntry &schema,
128958 BoundCreateTableInfo &info);
128960 DUCKDB_API optional_ptr<CatalogEntry>
128961 CreateTableFunction(CatalogTransaction transaction, SchemaCatalogEntry &schema, CreateTableFunctionInfo &info);
128963 DUCKDB_API optional_ptr<CatalogEntry> CreateCopyFunction(CatalogTransaction transaction, SchemaCatalogEntry &schema,
128964 CreateCopyFunctionInfo &info);
128966 DUCKDB_API optional_ptr<CatalogEntry>
128967 CreatePragmaFunction(CatalogTransaction transaction, SchemaCatalogEntry &schema, CreatePragmaFunctionInfo &info);
128969 DUCKDB_API optional_ptr<CatalogEntry> CreateFunction(CatalogTransaction transaction, SchemaCatalogEntry &schema,
128970 CreateFunctionInfo &info);
128972 DUCKDB_API optional_ptr<CatalogEntry> CreateView(CatalogTransaction transaction, SchemaCatalogEntry &schema,
128973 CreateViewInfo &info);
128975 DUCKDB_API optional_ptr<CatalogEntry> CreateSequence(CatalogTransaction transaction, SchemaCatalogEntry &schema,
128976 CreateSequenceInfo &info);
128978 DUCKDB_API optional_ptr<CatalogEntry> CreateType(CatalogTransaction transaction, SchemaCatalogEntry &schema,
128979 CreateTypeInfo &info);
128981 DUCKDB_API static optional_ptr<CatalogEntry> CreateCollation(CatalogTransaction transaction,
128982 SchemaCatalogEntry &schema, CreateCollationInfo &info);
128984 DUCKDB_API static optional_ptr<CatalogEntry> CreateCoordinateSystem(CatalogTransaction transaction,
128985 SchemaCatalogEntry &schema,
128986 CreateCoordinateSystemInfo &info);
128987
128989 DUCKDB_API void DropEntry(ClientContext &context, DropInfo &info);
128990
128991 DUCKDB_API virtual optional_ptr<SchemaCatalogEntry> LookupSchema(CatalogTransaction transaction,
128992 const EntryLookupInfo &schema_lookup,
128993 OnEntryNotFound if_not_found) = 0;
128994
128996 DUCKDB_API SchemaCatalogEntry &GetSchema(ClientContext &context, const EntryLookupInfo &schema_lookup);
128997 DUCKDB_API optional_ptr<SchemaCatalogEntry> GetSchema(ClientContext &context, const EntryLookupInfo &schema_lookup,
128998 OnEntryNotFound if_not_found);
129000 DUCKDB_API virtual bool CheckAmbiguousCatalogOrSchema(ClientContext &context, const string &schema);
129001
129002 DUCKDB_API SchemaCatalogEntry &GetSchema(ClientContext &context, const string &schema);
129003 DUCKDB_API SchemaCatalogEntry &GetSchema(CatalogTransaction transaction, const string &schema);
129004 DUCKDB_API SchemaCatalogEntry &GetSchema(CatalogTransaction transaction, const EntryLookupInfo &schema_lookup);
129005 DUCKDB_API static SchemaCatalogEntry &GetSchema(ClientContext &context, const string &catalog_name,
129006 const EntryLookupInfo &schema_lookup);
129007 DUCKDB_API optional_ptr<SchemaCatalogEntry> GetSchema(ClientContext &context, const string &schema,
129008 OnEntryNotFound if_not_found);
129009 DUCKDB_API optional_ptr<SchemaCatalogEntry> GetSchema(CatalogTransaction transaction, const string &schema,
129010 OnEntryNotFound if_not_found);
129011 DUCKDB_API static optional_ptr<SchemaCatalogEntry> GetSchema(ClientContext &context, const string &catalog_name,
129012 const EntryLookupInfo &schema_lookup,
129013 OnEntryNotFound if_not_found);
129014 DUCKDB_API static SchemaCatalogEntry &GetSchema(ClientContext &context, const string &catalog_name,
129015 const string &schema);
129016 DUCKDB_API static optional_ptr<SchemaCatalogEntry> GetSchema(ClientContext &context, const string &catalog_name,
129017 const string &schema, OnEntryNotFound if_not_found);
129018 DUCKDB_API static optional_ptr<SchemaCatalogEntry> GetSchema(CatalogEntryRetriever &retriever,
129019 const string &catalog_name,
129020 const EntryLookupInfo &schema_lookup,
129021 OnEntryNotFound if_not_found);
129023 DUCKDB_API virtual void ScanSchemas(ClientContext &context, std::function<void(SchemaCatalogEntry &)> callback) = 0;
129024
129026 DUCKDB_API optional_ptr<CatalogEntry> GetEntry(ClientContext &context, const string &schema,
129027 const EntryLookupInfo &lookup_info, OnEntryNotFound if_not_found);
129028 DUCKDB_API optional_ptr<CatalogEntry> GetEntry(ClientContext &context, CatalogType catalog_type,
129029 const string &schema, const string &name,
129030 OnEntryNotFound if_not_found);
129031 DUCKDB_API optional_ptr<CatalogEntry> GetEntry(CatalogEntryRetriever &retriever, const string &schema,
129032 const EntryLookupInfo &lookup_info, OnEntryNotFound if_not_found);
129033 DUCKDB_API CatalogEntry &GetEntry(ClientContext &context, const string &schema, const EntryLookupInfo &lookup_info);
129036 DUCKDB_API static optional_ptr<CatalogEntry> GetEntry(ClientContext &context, const string &catalog,
129037 const string &schema, const EntryLookupInfo &lookup_info,
129038 OnEntryNotFound if_not_found);
129039 DUCKDB_API static optional_ptr<CatalogEntry> GetEntry(CatalogEntryRetriever &retriever, const string &catalog,
129040 const string &schema, const EntryLookupInfo &lookup_info,
129041 OnEntryNotFound if_not_found);
129042 DUCKDB_API static CatalogEntry &GetEntry(ClientContext &context, const string &catalog, const string &schema,
129043 const EntryLookupInfo &lookup_info);
129044
129045 template <class T>
129046 optional_ptr<T> GetEntry(ClientContext &context, const string &schema_name, const string &name,
129047 OnEntryNotFound if_not_found, QueryErrorContext error_context = QueryErrorContext()) {
129048 EntryLookupInfo lookup_info(T::Type, name, error_context);
129049 auto entry = GetEntry(context, schema_name, lookup_info, if_not_found);
129050 if (!entry) {
129051 return nullptr;
129052 }
129053 if (entry->type != T::Type) {
129054 throw CatalogException(error_context, "%s is not an %s", name, T::Name);
129055 }
129056 return &entry->template Cast<T>();
129057 }
129058
129059 template <class T>
129060 T &GetEntry(ClientContext &context, const string &schema_name, const string &name,
129061 QueryErrorContext error_context = QueryErrorContext()) {
129062 auto entry = GetEntry<T>(context, schema_name, name, OnEntryNotFound::THROW_EXCEPTION, error_context);
129063 return *entry;
129064 }
129065
129066 static CatalogEntry &GetEntry(ClientContext &context, CatalogType catalog_type, const string &catalog_name,
129067 const string &schema_name, const string &name);
129068 CatalogEntry &GetEntry(ClientContext &context, CatalogType catalog_type, const string &schema_name,
129069 const string &name);
129070
129072 DUCKDB_API optional_ptr<CatalogEntry> AddFunction(ClientContext &context, CreateFunctionInfo &info);
129073
129075 DUCKDB_API void Alter(CatalogTransaction transaction, AlterInfo &info);
129076 DUCKDB_API void Alter(ClientContext &context, AlterInfo &info);
129077
129078 virtual PhysicalOperator &PlanCreateTableAs(ClientContext &context, PhysicalPlanGenerator &planner,
129079 LogicalCreateTable &op, PhysicalOperator &plan) = 0;
129080 virtual PhysicalOperator &PlanInsert(ClientContext &context, PhysicalPlanGenerator &planner, LogicalInsert &op,
129081 optional_ptr<PhysicalOperator> plan) = 0;
129082 virtual PhysicalOperator &PlanDelete(ClientContext &context, PhysicalPlanGenerator &planner, LogicalDelete &op,
129083 PhysicalOperator &plan) = 0;
129084 virtual PhysicalOperator &PlanDelete(ClientContext &context, PhysicalPlanGenerator &planner, LogicalDelete &op);
129085 virtual PhysicalOperator &PlanUpdate(ClientContext &context, PhysicalPlanGenerator &planner, LogicalUpdate &op,
129086 PhysicalOperator &plan) = 0;
129087 virtual PhysicalOperator &PlanUpdate(ClientContext &context, PhysicalPlanGenerator &planner, LogicalUpdate &op);
129088 virtual PhysicalOperator &PlanMergeInto(ClientContext &context, PhysicalPlanGenerator &planner,
129089 LogicalMergeInto &op, PhysicalOperator &plan);
129090 virtual unique_ptr<LogicalOperator> BindCreateIndex(Binder &binder, CreateStatement &stmt, TableCatalogEntry &table,
129091 unique_ptr<LogicalOperator> plan);
129092 virtual unique_ptr<LogicalOperator> BindAlterAddIndex(Binder &binder, TableCatalogEntry &table_entry,
129093 unique_ptr<LogicalOperator> plan,
129094 unique_ptr<CreateIndexInfo> create_info,
129095 unique_ptr<AlterTableInfo> alter_info);
129096
129097 virtual DatabaseSize GetDatabaseSize(ClientContext &context) = 0;
129098 virtual vector<MetadataBlockInfo> GetMetadataInfo(ClientContext &context);
129099
129100 virtual bool InMemory() = 0;
129101 virtual string GetDBPath() = 0;
129102 virtual bool SupportsTimeTravel() const {
129103 return false;
129104 }
129105 virtual bool IsEncrypted() const {
129106 return false;
129107 }
129108 virtual string GetEncryptionCipher() const {
129109 return string();
129110 }
129111 virtual ErrorData SupportsCreateTable(BoundCreateTableInfo &info);
129112
129115 return CatalogLookupBehavior::STANDARD;
129116 }
129117
129119 virtual string GetDefaultSchema() const;
129120
129123 DUCKDB_API bool HasDefaultTable() const;
129124 DUCKDB_API void SetDefaultTable(const string &schema, const string &name);
129125 DUCKDB_API string GetDefaultTable() const;
129126 DUCKDB_API string GetDefaultTableSchema() const;
129127
129129 virtual optional_ptr<DependencyManager> GetDependencyManager();
129130
129132 virtual bool HasConflictingAttachOptions(const string &path, const AttachOptions &options);
129133
129134public:
129135 template <class T>
129136 static optional_ptr<T> GetEntry(ClientContext &context, const string &catalog_name, const string &schema_name,
129137 const string &name, OnEntryNotFound if_not_found,
129138 QueryErrorContext error_context = QueryErrorContext()) {
129139 EntryLookupInfo lookup_info(T::Type, name, error_context);
129140 auto entry = GetEntry(context, catalog_name, schema_name, lookup_info, if_not_found);
129141 if (!entry) {
129142 return nullptr;
129143 }
129144 if (entry->type != T::Type) {
129145 throw CatalogException(error_context, "%s is not an %s", name, T::Name);
129146 }
129147 return &entry->template Cast<T>();
129148 }
129149 template <class T>
129150 static T &GetEntry(ClientContext &context, const string &catalog_name, const string &schema_name,
129151 const string &name, QueryErrorContext error_context = QueryErrorContext()) {
129152 auto entry =
129153 GetEntry<T>(context, catalog_name, schema_name, name, OnEntryNotFound::THROW_EXCEPTION, error_context);
129154 return *entry;
129155 }
129156
129157 DUCKDB_API vector<reference<SchemaCatalogEntry>> GetSchemas(ClientContext &context);
129158 DUCKDB_API static vector<reference<SchemaCatalogEntry>> GetSchemas(ClientContext &context,
129159 const string &catalog_name);
129160 DUCKDB_API static vector<reference<SchemaCatalogEntry>> GetSchemas(CatalogEntryRetriever &retriever,
129161 const string &catalog_name);
129162 DUCKDB_API static vector<reference<SchemaCatalogEntry>> GetAllSchemas(ClientContext &context);
129163
129164 static vector<reference<CatalogEntry>> GetAllEntries(ClientContext &context, CatalogType catalog_type);
129165
129166 virtual void Verify();
129167
129168 static CatalogException UnrecognizedConfigurationError(ClientContext &context, const string &name);
129169
129171 static String AutoloadExtensionByConfigName(ClientContext &context,
const String &configuration_name);
129173 static bool AutoLoadExtensionByCatalogEntry(DatabaseInstance &db, CatalogType type, const string &entry_name);
129174 DUCKDB_API static bool TryAutoLoad(ClientContext &context, const string &extension_name) noexcept;
129175
129177 DUCKDB_API virtual void OnDetach(ClientContext &context);
129178
129179protected:
129181 AttachedDatabase &
db;
129182
129184 string default_table;
129185 string default_table_schema;
129186
129187public:
129189 CatalogEntryLookup LookupEntry(CatalogEntryRetriever &retriever, const string &schema,
129190 const EntryLookupInfo &lookup_info, OnEntryNotFound if_not_found);
129191
129192private:
129194 virtual CatalogEntryLookup TryLookupEntryInternal(CatalogTransaction transaction, const string &schema,
129195 const EntryLookupInfo &lookup_info);
129198 CatalogEntryLookup TryLookupEntry(CatalogEntryRetriever &retriever, const string &schema,
129199 const EntryLookupInfo &lookup_info, OnEntryNotFound if_not_found);
129200 static CatalogEntryLookup TryLookupEntry(CatalogEntryRetriever &retriever, const vector<CatalogLookup> &lookups,
129201 const EntryLookupInfo &lookup_info, OnEntryNotFound if_not_found,
129202 bool allow_default_table_lookup);
129203 static CatalogEntryLookup TryLookupEntry(CatalogEntryRetriever &retriever, const string &catalog,
129204 const string &schema, const EntryLookupInfo &lookup_info,
129205 OnEntryNotFound if_not_found);
129206
129208 static CatalogEntryLookup TryLookupDefaultTable(CatalogEntryRetriever &retriever,
129209 const EntryLookupInfo &lookup_info,
129210 bool allow_ignore_at_clause = false);
129211
129213 static CatalogException CreateMissingEntryException(CatalogEntryRetriever &retriever,
129214 const EntryLookupInfo &lookup_info,
129215 const reference_set_t<SchemaCatalogEntry> &schemas);
129216
129218 static vector<SimilarCatalogEntry> SimilarEntriesInSchemas(ClientContext &context,
129219 const EntryLookupInfo &lookup_info,
129220 const reference_set_t<SchemaCatalogEntry> &schemas);
129221
129222 virtual void DropSchema(ClientContext &context, DropInfo &info) = 0;
129223
129224public:
129225 template <class TARGET>
129226 TARGET &Cast() {
129227 DynamicCastCheck<TARGET>(this);
129228 return reinterpret_cast<TARGET &>(*this);
129229 }
129230
129231 template <class TARGET>
129232 const TARGET &Cast() const {
129233 DynamicCastCheck<TARGET>(this);
129234 return reinterpret_cast<const TARGET &>(*this);
129235 }
129236};
129237
129238}
129239
129240
129241
129242
129243#include <type_traits>
129244
129245namespace duckdb {
129246
129247class WriteStream {
129248public:
129249
129250 virtual void WriteData(const_data_ptr_t buffer, idx_t write_size) = 0;
129251
129252
129253
129254 template <class T>
129255 void Write(T element) {
129256 static_assert(std::is_standard_layout<T>(), "Write element must be a standard layout data type");
129257 WriteData(const_data_ptr_cast(&element), sizeof(T));
129258 }
129259
129260 virtual ~WriteStream() {
129261 }
129262};
129263
129264}
129265
129266
129267
129268
129269
129270
129271
129272
129273
129274
129275
129276
129277
129278
129279
129280
129281
129282
129283
129284
129285
129286
129287
129288
129289namespace duckdb {
129290
129291enum class FileCompressionType :
uint8_t { AUTO_DETECT = 0, UNCOMPRESSED = 1, GZIP = 2, ZSTD = 3 };
129292
129293FileCompressionType FileCompressionTypeFromString(const string &input);
129294
129295string CompressionExtensionFromType(const FileCompressionType type);
129296
129297bool IsFileCompressed(string path, FileCompressionType type);
129298
129299}
129300
129301
129302
129303
129304
129305
129306
129307
129308
129309
129310
129311
129312
129313namespace duckdb {
129314
129315enum class FileGlobOptions :
uint8_t { DISALLOW_EMPTY = 0, ALLOW_EMPTY = 1, FALLBACK_GLOB = 2 };
129316
129317struct FileGlobInput {
129318 FileGlobInput(FileGlobOptions options)
129319 : behavior(options) {
129320 }
129321 FileGlobInput(FileGlobOptions options, string extension_p) : behavior(options), extension(std::move(extension_p)) {
129322 }
129323
129324 FileGlobOptions behavior;
129325 string extension;
129326};
129327
129328}
129329
129330
129331
129332
129333
129334
129335
129336
129337
129338
129339
129340
129341
129342
129343
129344
129345
129346
129347
129348
129349
129350
129351
129352
129353
129354
129355namespace duckdb {
129356
129357enum class DebugInitialize :
uint8_t { NO_INITIALIZE = 0, DEBUG_ZERO_INITIALIZE = 1, DEBUG_ONE_INITIALIZE = 2 };
129358
129359}
129360
129361
129362namespace duckdb {
129363
129364class BlockAllocator;
129365class BlockManager;
129366class QueryContext;
129367
129368struct FileHandle;
129369
129370enum class FileBufferType :
uint8_t { BLOCK = 1, MANAGED_BUFFER = 2, TINY_BUFFER = 3, EXTERNAL_FILE = 4 };
129371
129372static constexpr idx_t FILE_BUFFER_TYPE_COUNT = 4;
129373
129375class FileBuffer {
129376public:
129381 FileBuffer(BlockAllocator &allocator, FileBufferType type, uint64_t user_size, idx_t block_header_size);
129382 FileBuffer(BlockAllocator &allocator, FileBufferType type, BlockManager &block_manager);
129383 FileBuffer(FileBuffer &source, FileBufferType type, idx_t block_header_size);
129384
129385 virtual ~FileBuffer();
129386
129387 BlockAllocator &allocator;
129389 data_ptr_t buffer;
129393
129394public:
129396 void Read(QueryContext context, FileHandle &handle, uint64_t location);
129398 void Write(QueryContext context, FileHandle &handle, const uint64_t location);
129399
129400 void Clear();
129401
129402 FileBufferType GetBufferType() const {
129403 return type;
129404 }
129405
129406
129407
129408 void Resize(uint64_t user_size, idx_t block_header_size);
129409 void Resize(BlockManager &block_manager);
129410
129411 idx_t GetHeaderSize()
const {
129412 return internal_size -
size;
129413 }
129414
129416 return internal_size;
129417 }
129420 }
129421 data_ptr_t InternalBuffer() {
129422 return internal_buffer;
129423 }
129424
129425 struct MemoryRequirement {
129427 idx_t header_size;
129428 };
129429
129430 MemoryRequirement CalculateMemory(uint64_t user_size, uint64_t block_header_size) const;
129431 void Initialize(DebugInitialize info);
129432
129433protected:
129435 FileBufferType type;
129438 data_ptr_t internal_buffer;
129442
129443 void ReallocBuffer(idx_t new_size);
129444 void Init();
129445
129446private:
129447 void ResizeInternal(uint64_t user_size, uint64_t block_header_size);
129448};
129449
129450}
129451
129452
129453
129454
129455
129456
129457
129458
129459
129460
129461
129462
129463
129464
129465
129466
129467
129468
129469
129470
129471
129472
129473
129474#include <cstdint>
129475
129476namespace duckdb {
129477
129481
129482 ALWAYS_CACHE = 0,
129483
129484 CACHE_REMOTE_ONLY = 1,
129485
129486 NO_CACHING = 2,
129487};
129488
129489}
129490
129491
129492namespace duckdb {
129493
129494enum class FileLockType :
uint8_t { NO_LOCK = 0, READ_LOCK = 1, WRITE_LOCK = 2 };
129495
129496class FileOpenFlags {
129497public:
129498 static constexpr idx_t FILE_FLAGS_READ =
idx_t(1 << 0);
129499 static constexpr idx_t FILE_FLAGS_WRITE =
idx_t(1 << 1);
129500 static constexpr idx_t FILE_FLAGS_DIRECT_IO =
idx_t(1 << 2);
129501 static constexpr idx_t FILE_FLAGS_FILE_CREATE =
idx_t(1 << 3);
129502 static constexpr idx_t FILE_FLAGS_FILE_CREATE_NEW =
idx_t(1 << 4);
129503 static constexpr idx_t FILE_FLAGS_APPEND =
idx_t(1 << 5);
129504 static constexpr idx_t FILE_FLAGS_PRIVATE =
idx_t(1 << 6);
129505 static constexpr idx_t FILE_FLAGS_NULL_IF_NOT_EXISTS =
idx_t(1 << 7);
129506 static constexpr idx_t FILE_FLAGS_PARALLEL_ACCESS =
idx_t(1 << 8);
129507 static constexpr idx_t FILE_FLAGS_EXCLUSIVE_CREATE =
idx_t(1 << 9);
129508 static constexpr idx_t FILE_FLAGS_NULL_IF_EXISTS =
idx_t(1 << 10);
129509 static constexpr idx_t FILE_FLAGS_MULTI_CLIENT_ACCESS =
idx_t(1 << 11);
129510 static constexpr idx_t FILE_FLAGS_DISABLE_LOGGING =
idx_t(1 << 12);
129511 static constexpr idx_t FILE_FLAGS_ENABLE_EXTENSION_INSTALL =
idx_t(1 << 13);
129512
129513public:
129514 FileOpenFlags() = default;
129515 constexpr FileOpenFlags(idx_t flags) : flags(flags) {
129516 }
129517 constexpr FileOpenFlags(FileLockType lock) : lock(lock) {
129518 }
129519 constexpr FileOpenFlags(FileCompressionType compression)
129520 : compression(compression) {
129521 }
129522 constexpr FileOpenFlags(idx_t flags, FileLockType lock, FileCompressionType compression)
129523 : flags(flags), lock(lock), compression(compression) {
129524 }
129525
129526 static constexpr FileLockType MergeLock(FileLockType a, FileLockType b) {
129527 return a == FileLockType::NO_LOCK ? b : a;
129528 }
129529
129530 static constexpr FileCompressionType MergeCompression(FileCompressionType a, FileCompressionType b) {
129531 return a == FileCompressionType::UNCOMPRESSED ? b : a;
129532 }
129533
129534 static constexpr CachingMode MergeCachingMode(CachingMode a, CachingMode b) {
129535 return a == CachingMode::NO_CACHING ? b : a;
129536 }
129537
129538 inline constexpr FileOpenFlags
operator|(FileOpenFlags b)
const {
129539 return FileOpenFlags(flags | b.flags, MergeLock(lock, b.lock), MergeCompression(compression, b.compression));
129540 }
129541 inline FileOpenFlags &
operator|=(FileOpenFlags b) {
129542 flags |= b.flags;
129543 lock = MergeLock(lock, b.lock);
129544 compression = MergeCompression(compression, b.compression);
129545 caching_mode = MergeCachingMode(caching_mode, b.caching_mode);
129546 return *this;
129547 }
129548
129549 FileLockType Lock() {
129550 return lock;
129551 }
129552
129553 FileCompressionType Compression() {
129554 return compression;
129555 }
129556
129557 void SetCompression(FileCompressionType new_compression) {
129558 compression = new_compression;
129559 }
129560
129562 return caching_mode;
129563 }
129564 void SetCachingMode(CachingMode new_caching_mode) {
129565 caching_mode = new_caching_mode;
129566 }
129567
129568 void Verify();
129569
129570 inline bool OpenForReading() const {
129571 return flags & FILE_FLAGS_READ;
129572 }
129573 inline bool OpenForWriting() const {
129574 return flags & FILE_FLAGS_WRITE;
129575 }
129576 inline bool DirectIO() const {
129577 return flags & FILE_FLAGS_DIRECT_IO;
129578 }
129579 inline bool CreateFileIfNotExists() const {
129580 return flags & FILE_FLAGS_FILE_CREATE;
129581 }
129582 inline bool OverwriteExistingFile() const {
129583 return flags & FILE_FLAGS_FILE_CREATE_NEW;
129584 }
129585 inline bool OpenForAppending() const {
129586 return flags & FILE_FLAGS_APPEND;
129587 }
129588 inline bool CreatePrivateFile() const {
129589 return flags & FILE_FLAGS_PRIVATE;
129590 }
129591 inline bool ReturnNullIfNotExists() const {
129592 return flags & FILE_FLAGS_NULL_IF_NOT_EXISTS;
129593 }
129594 inline bool RequireParallelAccess() const {
129595 return flags & FILE_FLAGS_PARALLEL_ACCESS;
129596 }
129597 inline bool ExclusiveCreate() const {
129598 return flags & FILE_FLAGS_EXCLUSIVE_CREATE;
129599 }
129600 inline bool ReturnNullIfExists() const {
129601 return flags & FILE_FLAGS_NULL_IF_EXISTS;
129602 }
129603 inline bool MultiClientAccess() const {
129604 return flags & FILE_FLAGS_MULTI_CLIENT_ACCESS;
129605 }
129606 inline bool DisableLogging() const {
129607 return flags & FILE_FLAGS_DISABLE_LOGGING;
129608 }
129609 inline bool EnableExtensionInstall() const {
129610 return flags & FILE_FLAGS_ENABLE_EXTENSION_INSTALL;
129611 }
129612 inline idx_t GetFlagsInternal()
const {
129613 return flags;
129614 }
129615
129616private:
129618 FileLockType lock = FileLockType::NO_LOCK;
129619 CachingMode caching_mode = CachingMode::NO_CACHING;
129620 FileCompressionType compression = FileCompressionType::UNCOMPRESSED;
129621};
129622
129623class FileFlags {
129624public:
129626 static constexpr FileOpenFlags FILE_FLAGS_READ = FileOpenFlags(FileOpenFlags::FILE_FLAGS_READ);
129628 static constexpr FileOpenFlags FILE_FLAGS_WRITE = FileOpenFlags(FileOpenFlags::FILE_FLAGS_WRITE);
129630 static constexpr FileOpenFlags FILE_FLAGS_DIRECT_IO = FileOpenFlags(FileOpenFlags::FILE_FLAGS_DIRECT_IO);
129632 static constexpr FileOpenFlags FILE_FLAGS_FILE_CREATE = FileOpenFlags(FileOpenFlags::FILE_FLAGS_FILE_CREATE);
129634 static constexpr FileOpenFlags FILE_FLAGS_FILE_CREATE_NEW =
129635 FileOpenFlags(FileOpenFlags::FILE_FLAGS_FILE_CREATE_NEW);
129637 static constexpr FileOpenFlags FILE_FLAGS_APPEND = FileOpenFlags(FileOpenFlags::FILE_FLAGS_APPEND);
129639 static constexpr FileOpenFlags FILE_FLAGS_PRIVATE = FileOpenFlags(FileOpenFlags::FILE_FLAGS_PRIVATE);
129641 static constexpr FileOpenFlags FILE_FLAGS_NULL_IF_NOT_EXISTS =
129642 FileOpenFlags(FileOpenFlags::FILE_FLAGS_NULL_IF_NOT_EXISTS);
129644 static constexpr FileOpenFlags FILE_FLAGS_PARALLEL_ACCESS =
129645 FileOpenFlags(FileOpenFlags::FILE_FLAGS_PARALLEL_ACCESS);
129647 static constexpr FileOpenFlags FILE_FLAGS_EXCLUSIVE_CREATE =
129648 FileOpenFlags(FileOpenFlags::FILE_FLAGS_EXCLUSIVE_CREATE);
129650 static constexpr FileOpenFlags FILE_FLAGS_NULL_IF_EXISTS = FileOpenFlags(FileOpenFlags::FILE_FLAGS_NULL_IF_EXISTS);
129652 static constexpr FileOpenFlags FILE_FLAGS_MULTI_CLIENT_ACCESS =
129653 FileOpenFlags(FileOpenFlags::FILE_FLAGS_MULTI_CLIENT_ACCESS);
129655 static constexpr FileOpenFlags FILE_FLAGS_DISABLE_LOGGING =
129656 FileOpenFlags(FileOpenFlags::FILE_FLAGS_DISABLE_LOGGING);
129658 static constexpr FileOpenFlags FILE_FLAGS_ENABLE_EXTENSION_INSTALL =
129659 FileOpenFlags(FileOpenFlags::FILE_FLAGS_ENABLE_EXTENSION_INSTALL);
129660};
129661
129662}
129663
129664
129665
129666
129667
129668
129669
129670
129671
129672
129673
129674
129675
129676
129677
129678namespace duckdb {
129679
129680struct ExtendedOpenFileInfo {
129681 unordered_map<string, Value> options;
129682};
129683
129684struct OpenFileInfo {
129685 OpenFileInfo() = default;
129686 OpenFileInfo(string path_p)
129687 : path(std::move(path_p)) {
129688 }
129689
129690 string path;
129691 shared_ptr<ExtendedOpenFileInfo> extended_info;
129692
129693public:
129694 bool operator<(
const OpenFileInfo &rhs)
const {
129695 return path < rhs.path;
129696 }
129697};
129698
129699}
129700
129701
129702
129703
129704
129705
129706
129707
129708
129709
129710
129711
129712
129713
129714
129715
129716
129717
129718namespace duckdb {
129719
129720
129721
129722
129723
129724
129725
129726
129727
129728
129729
129730
129731
129732
129733
129734
129735
129736
129737
129738
129739
129740
129741
129742
129743
129744
129745
129746
129747
129748
129749
129750
129751
129752
129753class Path {
129754public:
129755
129756 static Path FromString(const string &raw);
129757
129758 string ToString() const;
129759
129760
129761 string GetBase() const;
129762 string GetPath() const;
129763 string GetTrailingSeparator() const {
129764 return !segments.empty() && has_trailing_separator ? string(1, separator) : "";
129765 }
129766 const string &GetScheme() const {
129767 return scheme;
129768 }
129769 const string &GetAuthority() const {
129770 return authority;
129771 }
129772 const string &GetAnchor() const {
129773 return anchor;
129774 }
129775 char GetSeparator() const {
129776 return separator;
129777 }
129778
129779 bool HasScheme() const {
129780 return !scheme.empty();
129781 }
129782 bool HasAuthority() const {
129783 return !authority.empty();
129784 }
129785 bool HasAnchor() const {
129786 return !anchor.empty();
129787 }
129788
129789 bool HasDrive() const;
129790 char GetDriveChar() const;
129791
129792 bool HasPathSegments() const {
129793 return !segments.empty();
129794 }
129795
129796 bool HasTrailingSeparator() const {
129797 return has_trailing_separator;
129798 }
129799
129800 bool IsAbsolute() const {
129801 return is_absolute;
129802 }
129803
129804
129805 bool IsLocal() const {
129806
129808 }
129809
129810 bool IsRemote() const {
129811 return !IsLocal();
129812 }
129813
129814 const vector<string> &GetPathSegments() const {
129815 return segments;
129816 }
129817
129818
129819 Path Join(const Path &rhs) const;
129820 Path Join(const string &rhs) const;
129821
129822 template <typename... Args>
129823 Path Join(const string &first, const Args &...rest) const {
129824 return Join(first).Join(rest...);
129825 }
129826
129827 Path Join(const vector<string> &paths) const {
129828 Path result = *this;
129829 for (const auto &rhs : paths) {
129830 result = result.Join(rhs);
129831 }
129832 return result;
129833 }
129834
129835 Path Parent(int n = 1) const;
129836
129837
129838 static string Normalize(const string &input) {
129839 return FromString(input).ToString();
129840 }
129841
129842 static string AddSuffixToPath(const string &path, const string &suffix);
129843
129844private:
129845 string scheme;
129846 string authority;
129847 string anchor;
129848 vector<string> segments;
129849
129850 char separator = '/';
129851 bool has_trailing_separator = false;
129852 bool is_absolute = false;
129853
129854 void NormalizeSegments(const string &raw, size_t path_offset);
129855
129856 static size_t ParseURIScheme(const string &input, Path &parsed);
129857 static size_t ParseFilePathTail(const string &input, size_t start, Path &parsed);
129858 static size_t ParseFileSchemes(const string &input, Path &parsed);
129859#if defined(_WIN32)
129860 static size_t ParseUNCScheme(const string &input, Path &parsed);
129861#endif
129862};
129863
129864}
129865
129866
129867
129868
129869#include <functional>
129870
129871#undef CreateDirectory
129872#undef MoveFile
129873#undef RemoveDirectory
129874
129875namespace duckdb {
129876
129877class AttachedDatabase;
129878class DatabaseInstance;
129879class FileOpener;
129880class FileSystem;
129881class Logger;
129882class ClientContext;
129883class QueryContext;
129884class MultiFileList;
129885
129903};
129904
129905struct FileMetadata {
129907 timestamp_t last_modification_time = timestamp_t::ninfinity();
129908 FileType file_type = FileType::FILE_TYPE_INVALID;
129909
129910
129911 unordered_map<string, Value> extended_file_info;
129912};
129913
129914struct FileHandle {
129915public:
129916 DUCKDB_API FileHandle(FileSystem &file_system, string path, FileOpenFlags flags);
129917 FileHandle(const FileHandle &) = delete;
129918 DUCKDB_API virtual ~FileHandle();
129919
129920
129921
129922 DUCKDB_API
int64_t Read(
void *buffer, idx_t nr_bytes);
129923 DUCKDB_API
int64_t Read(QueryContext context,
void *buffer, idx_t nr_bytes);
129924 DUCKDB_API
int64_t Write(
void *buffer, idx_t nr_bytes);
129925 DUCKDB_API
int64_t Write(QueryContext context,
void *buffer, idx_t nr_bytes);
129926
129927
129928 DUCKDB_API void Read(void *buffer, idx_t nr_bytes, idx_t location);
129929 DUCKDB_API void Read(QueryContext context, void *buffer, idx_t nr_bytes, idx_t location);
129930 DUCKDB_API void Write(QueryContext context, void *buffer, idx_t nr_bytes, idx_t location);
129931 DUCKDB_API void Seek(idx_t location);
129932 DUCKDB_API void Reset();
129933 DUCKDB_API
idx_t SeekPosition();
129934 DUCKDB_API
void Sync();
129935 DUCKDB_API void Truncate(int64_t new_size);
129936 DUCKDB_API string ReadLine();
129937 DUCKDB_API string ReadLine(QueryContext context);
129938 DUCKDB_API bool Trim(idx_t offset_bytes, idx_t length_bytes);
129939 DUCKDB_API
virtual idx_t GetProgress();
129940 DUCKDB_API virtual FileCompressionType GetFileCompressionType();
129941
129942 DUCKDB_API bool CanSeek();
129943 DUCKDB_API bool IsPipe();
129944 DUCKDB_API bool OnDiskFile();
129945 DUCKDB_API
idx_t GetFileSize();
129947 DUCKDB_API FileMetadata Stats();
129948
129949 DUCKDB_API void TryAddLogger(FileOpener &opener);
129950
129952 DUCKDB_API virtual void Close() = 0;
129953
129954 string GetPath() const {
129955 return path;
129956 }
129957
129958 FileOpenFlags GetFlags() const {
129959 return flags;
129960 }
129961
129962 template <class TARGET>
129963 TARGET &Cast() {
129964 DynamicCastCheck<TARGET>(this);
129965 return reinterpret_cast<TARGET &>(*this);
129966 }
129967 template <class TARGET>
129968 const TARGET &Cast() const {
129969 DynamicCastCheck<TARGET>(this);
129970 return reinterpret_cast<const TARGET &>(*this);
129971 }
129972
129973public:
129974 FileSystem &file_system;
129975 string path;
129976 FileOpenFlags flags;
129977
129978 shared_ptr<Logger> logger;
129979};
129980
129981class FileSystem {
129982public:
129983 DUCKDB_API virtual ~FileSystem();
129984
129985public:
129986 DUCKDB_API static FileSystem &GetFileSystem(ClientContext &context);
129987 DUCKDB_API static FileSystem &GetFileSystem(DatabaseInstance &db);
129988 DUCKDB_API static FileSystem &Get(AttachedDatabase &db);
129989
129990 DUCKDB_API virtual unique_ptr<FileHandle> OpenFile(const string &path, FileOpenFlags flags,
129991 optional_ptr<FileOpener> opener = nullptr);
129992 DUCKDB_API unique_ptr<FileHandle> OpenFile(const OpenFileInfo &path, FileOpenFlags flags,
129993 optional_ptr<FileOpener> opener = nullptr);
129994
129997 DUCKDB_API virtual void Read(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location);
130000 DUCKDB_API virtual void Write(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location);
130003 DUCKDB_API
virtual int64_t Read(FileHandle &handle,
void *buffer, int64_t nr_bytes);
130005 DUCKDB_API
virtual int64_t Write(FileHandle &handle,
void *buffer, int64_t nr_bytes);
130008 DUCKDB_API virtual bool Trim(FileHandle &handle, idx_t offset_bytes, idx_t length_bytes);
130009
130011 DUCKDB_API
virtual int64_t GetFileSize(FileHandle &handle);
130013 DUCKDB_API virtual timestamp_t GetLastModifiedTime(FileHandle &handle);
130016 DUCKDB_API virtual string GetVersionTag(FileHandle &handle);
130018 DUCKDB_API
virtual FileType GetFileType(FileHandle &handle);
130020 DUCKDB_API virtual FileMetadata Stats(FileHandle &handle);
130023 DUCKDB_API virtual void Truncate(FileHandle &handle, int64_t new_size);
130024
130026 DUCKDB_API virtual bool DirectoryExists(const string &directory, optional_ptr<FileOpener> opener = nullptr);
130028 DUCKDB_API virtual void CreateDirectory(const string &directory, optional_ptr<FileOpener> opener = nullptr);
130030 DUCKDB_API virtual void CreateDirectoriesRecursive(const string &path, optional_ptr<FileOpener> opener = nullptr);
130032 DUCKDB_API virtual void RemoveDirectory(const string &directory, optional_ptr<FileOpener> opener = nullptr);
130033
130035 DUCKDB_API virtual bool ListFiles(const string &directory,
130036 const std::function<void(const string &, bool)> &callback,
130037 FileOpener *opener = nullptr);
130038 DUCKDB_API bool ListFiles(const string &directory, const std::function<void(OpenFileInfo &info)> &callback,
130039 optional_ptr<FileOpener> opener = nullptr);
130040
130043 DUCKDB_API virtual void MoveFile(const string &source, const string &target,
130044 optional_ptr<FileOpener> opener = nullptr);
130046 DUCKDB_API virtual bool FileExists(const string &filename, optional_ptr<FileOpener> opener = nullptr);
130048 DUCKDB_API virtual bool IsPipe(const string &filename, optional_ptr<FileOpener> opener = nullptr);
130050 DUCKDB_API virtual void RemoveFile(const string &filename, optional_ptr<FileOpener> opener = nullptr);
130052 DUCKDB_API virtual bool TryRemoveFile(const string &filename, optional_ptr<FileOpener> opener = nullptr);
130054 DUCKDB_API virtual void RemoveFiles(const vector<string> &filenames, optional_ptr<FileOpener> opener = nullptr);
130056 DUCKDB_API virtual void FileSync(FileHandle &handle);
130058 DUCKDB_API static void SetWorkingDirectory(const string &path);
130060 DUCKDB_API static string GetWorkingDirectory();
130062 DUCKDB_API static string GetHomeDirectory(optional_ptr<FileOpener> opener);
130064 DUCKDB_API virtual string GetHomeDirectory();
130066 DUCKDB_API static string ExpandPath(const string &path, optional_ptr<FileOpener> opener);
130068 DUCKDB_API virtual string ExpandPath(const string &path);
130070 DUCKDB_API static optional_idx GetAvailableMemory();
130072 DUCKDB_API static optional_idx GetAvailableDiskSpace(const string &path);
130074 DUCKDB_API virtual string PathSeparator(const string &path);
130076 DUCKDB_API virtual bool IsPathAbsolute(const string &path);
130078 DUCKDB_API string JoinPath(const string &a, const string &path);
130079
130080 template <typename... ARGS>
130081 string JoinPath(const string &a, const string &b, ARGS... args) {
130082 return JoinPath(JoinPath(a, b), args...);
130083 }
130085 DUCKDB_API string ConvertSeparators(const string &path);
130087 DUCKDB_API string ExtractBaseName(const string &path);
130089 DUCKDB_API string ExtractExtension(const string &path);
130091 DUCKDB_API string ExtractName(const string &path);
130092
130094 DUCKDB_API static string GetEnvVariable(const string &name);
130095
130097 DUCKDB_API static bool HasGlob(const string &str);
130099 DUCKDB_API virtual vector<OpenFileInfo> Glob(const string &path, FileOpener *opener = nullptr);
130100 DUCKDB_API unique_ptr<MultiFileList> Glob(const string &path, const FileGlobInput &input,
130101 optional_ptr<FileOpener> opener);
130102 DUCKDB_API unique_ptr<MultiFileList> GlobFileList(const string &path,
130103 const FileGlobInput &input = FileGlobOptions::DISALLOW_EMPTY);
130104 DUCKDB_API vector<OpenFileInfo> GlobFiles(const string &pattern,
130105 const FileGlobInput &input = FileGlobOptions::DISALLOW_EMPTY);
130106
130108 DUCKDB_API virtual void RegisterSubSystem(unique_ptr<FileSystem> sub_fs);
130109 DUCKDB_API virtual void RegisterSubSystem(FileCompressionType compression_type, unique_ptr<FileSystem> fs);
130110
130112 DUCKDB_API virtual void UnregisterSubSystem(const string &name);
130113
130114
130115
130116 DUCKDB_API virtual unique_ptr<FileSystem> ExtractSubSystem(const string &name);
130117
130119 DUCKDB_API virtual vector<string> ListSubSystems();
130120
130122 DUCKDB_API virtual bool CanHandleFile(const string &fpath);
130123
130125 DUCKDB_API virtual void Seek(FileHandle &handle, idx_t location);
130127 DUCKDB_API virtual void Reset(FileHandle &handle);
130128 DUCKDB_API
virtual idx_t SeekPosition(FileHandle &handle);
130129
130131 DUCKDB_API virtual bool IsManuallySet();
130133 DUCKDB_API virtual bool CanSeek();
130136 DUCKDB_API virtual bool OnDiskFile(FileHandle &handle);
130137
130138 DUCKDB_API virtual unique_ptr<FileHandle> OpenCompressedFile(QueryContext context, unique_ptr<FileHandle> handle,
130139 bool write);
130140
130142 DUCKDB_API static unique_ptr<FileSystem> CreateLocal();
130143
130145 DUCKDB_API virtual std::string GetName() const = 0;
130146
130148 DUCKDB_API static bool IsRemoteFile(const string &path);
130149 DUCKDB_API static bool IsRemoteFile(const string &path, string &extension);
130150
130151 DUCKDB_API virtual void SetDisabledFileSystems(const vector<string> &names);
130152 DUCKDB_API virtual bool SubSystemIsDisabled(const string &name);
130154 DUCKDB_API virtual bool IsDisabledForPath(const string &path);
130155
130156 DUCKDB_API static bool IsDirectory(const OpenFileInfo &info);
130157
130159 DUCKDB_API virtual string CanonicalizePath(const string &path, optional_ptr<FileOpener> opener = nullptr);
130160
130161protected:
130162 DUCKDB_API virtual unique_ptr<FileHandle> OpenFileExtended(const OpenFileInfo &path, FileOpenFlags flags,
130163 optional_ptr<FileOpener> opener);
130164 DUCKDB_API virtual bool SupportsOpenFileExtended() const;
130165
130166 DUCKDB_API virtual bool ListFilesExtended(const string &directory,
130167 const std::function<void(OpenFileInfo &info)> &callback,
130168 optional_ptr<FileOpener> opener);
130169 DUCKDB_API virtual bool SupportsListFilesExtended() const;
130170
130171 DUCKDB_API virtual unique_ptr<MultiFileList> GlobFilesExtended(const string &path, const FileGlobInput &input,
130172 optional_ptr<FileOpener> opener = nullptr);
130173 DUCKDB_API virtual bool SupportsGlobExtended() const;
130174
130175public:
130176 template <class TARGET>
130177 TARGET &Cast() {
130178 DynamicCastCheck<TARGET>(this);
130179 return reinterpret_cast<TARGET &>(*this);
130180 }
130181
130182 template <class TARGET>
130183 const TARGET &Cast() const {
130184 DynamicCastCheck<TARGET>(this);
130185 return reinterpret_cast<const TARGET &>(*this);
130186 }
130187};
130188
130189}
130190
130191
130192namespace duckdb {
130193
130194#define FILE_BUFFER_SIZE 4096
130195
130196class BufferedFileWriter : public WriteStream {
130197public:
130198 static constexpr FileOpenFlags DEFAULT_OPEN_FLAGS = FileFlags::FILE_FLAGS_WRITE | FileFlags::FILE_FLAGS_FILE_CREATE;
130199
130202 DUCKDB_API BufferedFileWriter(FileSystem &fs, const string &path, FileOpenFlags open_flags = DEFAULT_OPEN_FLAGS);
130203
130204 FileSystem &fs;
130205 string path;
130206 unsafe_unique_array<data_t> data;
130208 idx_t total_written;
130209 unique_ptr<FileHandle> handle;
130210
130211public:
130212 DUCKDB_API void WriteData(const_data_ptr_t buffer, idx_t write_size) override;
130214 DUCKDB_API void Close();
130216 DUCKDB_API
void Sync();
130218 DUCKDB_API void Flush();
130220 DUCKDB_API
idx_t GetFileSize();
130222 DUCKDB_API void Truncate(idx_t size);
130223
130224 DUCKDB_API
idx_t GetTotalWritten()
const;
130225};
130226
130227}
130228
130229
130230
130231
130232
130233
130234
130235
130236
130237
130238
130239
130240
130241
130242
130243
130244
130245
130246
130247
130248
130249
130250
130251
130252
130253
130254
130255
130256
130257
130258
130259
130260
130261
130262
130263
130264
130265
130266
130267
130268
130269
130270
130271
130272
130273
130274
130275
130276
130277
130278
130279
130280
130281#include <bitset>
130282
130283namespace duckdb {
130284using std::bitset;
130285}
130286
130287
130288
130289
130290
130291
130292
130293
130294
130295
130296
130297
130298
130299
130300namespace duckdb {
130301
130302enum class VectorType :
uint8_t {
130303 FLAT_VECTOR,
130304 FSST_VECTOR,
130305 CONSTANT_VECTOR,
130306 DICTIONARY_VECTOR,
130307 SEQUENCE_VECTOR
130308};
130309
130310string VectorTypeToString(VectorType type);
130311
130312}
130313
130314
130315
130316
130317
130318
130319
130320
130321
130322
130323
130324
130325
130326
130327
130328
130329
130330
130331
130332
130333
130334
130335
130336
130337
130338
130339
130340
130341namespace duckdb {
130342class Allocator;
130343class AttachedDatabase;
130344class ClientContext;
130345class DatabaseInstance;
130346class ExecutionContext;
130347class ThreadContext;
130348
130349struct AllocatorDebugInfo;
130350
130351enum class AllocatorFreeType { REQUIRES_FREE, DOES_NOT_REQUIRE_FREE };
130352
130353struct PrivateAllocatorData {
130354 PrivateAllocatorData();
130355 virtual ~PrivateAllocatorData();
130356
130357 AllocatorFreeType free_type = AllocatorFreeType::REQUIRES_FREE;
130361 unique_ptr<AllocatorDebugInfo> debug_info;
130362
130363 template <class TARGET>
130364 TARGET &Cast() {
130365 DynamicCastCheck<TARGET>(this);
130366 return reinterpret_cast<TARGET &>(*this);
130367 }
130368 template <class TARGET>
130369 const TARGET &Cast() const {
130370 DynamicCastCheck<TARGET>(this);
130371 return reinterpret_cast<const TARGET &>(*this);
130372 }
130373};
130374
130375typedef data_ptr_t (*allocate_function_ptr_t)(PrivateAllocatorData *private_data,
idx_t size);
130376typedef void (*free_function_ptr_t)(PrivateAllocatorData *private_data, data_ptr_t pointer,
idx_t size);
130377typedef data_ptr_t (*reallocate_function_ptr_t)(PrivateAllocatorData *private_data, data_ptr_t pointer,
idx_t old_size,
130379
130380class AllocatedData {
130381public:
130382 DUCKDB_API AllocatedData();
130383 DUCKDB_API AllocatedData(Allocator &allocator, data_ptr_t pointer, idx_t allocated_size);
130384 DUCKDB_API ~AllocatedData();
130385
130386 AllocatedData(const AllocatedData &other) = delete;
130387 AllocatedData &
operator=(
const AllocatedData &) =
delete;
130389 DUCKDB_API AllocatedData(AllocatedData &&other) noexcept;
130390 DUCKDB_API AllocatedData &
operator=(AllocatedData &&) noexcept;
130391
130392 data_ptr_t
get() {
130393 return pointer;
130394 }
130395 operator bool() const {
130396 return pointer != nullptr;
130397 }
130398 const_data_ptr_t
get()
const {
130399 return pointer;
130400 }
130401 idx_t GetSize()
const {
130402 return allocated_size;
130403 }
130404 bool IsSet() {
130405 return pointer;
130406 }
130407 optional_ptr<Allocator> GetAllocator() const {
130408 return allocator;
130409 }
130410 void Reset();
130411
130412private:
130413 optional_ptr<Allocator> allocator;
130414 data_ptr_t pointer;
130415 idx_t allocated_size;
130416};
130417
130418class Allocator {
130419
130420 static constexpr const idx_t MAXIMUM_ALLOC_SIZE = 281474976710656ULL;
130421
130422public:
130423 DUCKDB_API Allocator();
130424 DUCKDB_API Allocator(allocate_function_ptr_t allocate_function_p, free_function_ptr_t free_function_p,
130425 reallocate_function_ptr_t reallocate_function_p,
130426 unique_ptr<PrivateAllocatorData> private_data);
130427 Allocator &
operator=(Allocator &&allocator)
noexcept =
delete;
130428 DUCKDB_API ~Allocator();
130429
130430 DUCKDB_API data_ptr_t AllocateData(idx_t size);
130431 DUCKDB_API void FreeData(data_ptr_t pointer, idx_t size);
130432 DUCKDB_API data_ptr_t ReallocateData(data_ptr_t pointer, idx_t old_size, idx_t new_size);
130433
130434 AllocatedData Allocate(idx_t size) {
130435 return AllocatedData(*this, AllocateData(size), size);
130436 }
130437 static data_ptr_t DefaultAllocate(PrivateAllocatorData *private_data, idx_t size);
130438 static void DefaultFree(PrivateAllocatorData *private_data, data_ptr_t pointer, idx_t size);
130439 static data_ptr_t DefaultReallocate(PrivateAllocatorData *private_data, data_ptr_t pointer, idx_t old_size,
130440 idx_t size);
130441 static Allocator &Get(ClientContext &context);
130442 static Allocator &Get(DatabaseInstance &db);
130443 static Allocator &Get(AttachedDatabase &db);
130444
130445 PrivateAllocatorData *GetPrivateData() {
130446 return private_data.get();
130447 }
130448
130449 DUCKDB_API static Allocator &DefaultAllocator();
130450 DUCKDB_API static shared_ptr<Allocator> &DefaultAllocatorReference();
130451
130452 static bool SupportsFlush();
130453 static optional_idx DecayDelay();
130454 static void ThreadFlush(bool allocator_background_threads, idx_t threshold, idx_t thread_count);
130455 static void ThreadIdle();
130456 static void FlushAll();
130457 static void SetBackgroundThreads(bool enable);
130458
130459private:
130460 allocate_function_ptr_t allocate_function;
130461 free_function_ptr_t free_function;
130462 reallocate_function_ptr_t reallocate_function;
130463 unique_ptr<PrivateAllocatorData> private_data;
130464
130465 bool ShouldUseDebugInfo() const {
130466 return private_data && private_data->free_type != AllocatorFreeType::DOES_NOT_REQUIRE_FREE &&
130467 private_data->debug_info;
130468 }
130469};
130470
130471template <class T>
130472T *AllocateArray(idx_t size) {
130473 return (T *)Allocator::DefaultAllocator().AllocateData(size * sizeof(T));
130474}
130475
130476template <class T>
130477void DeleteArray(T *ptr, idx_t size) {
130478 Allocator::DefaultAllocator().FreeData(data_ptr_cast(ptr), size * sizeof(T));
130479}
130480
130481template <typename T, typename... ARGS>
130482T *AllocateObject(ARGS &&... args) {
130483 auto data = Allocator::DefaultAllocator().AllocateData(sizeof(T));
130484 return new (data) T(std::forward<ARGS>(args)...);
130485}
130486
130487template <typename T>
130488void DestroyObject(T *ptr) {
130489 ptr->~T();
130490 Allocator::DefaultAllocator().FreeData(data_ptr_cast(ptr), sizeof(T));
130491}
130492
130498struct BufferAllocator {
130499 DUCKDB_API static Allocator &Get(ClientContext &context);
130500 DUCKDB_API static Allocator &Get(DatabaseInstance &db);
130501 DUCKDB_API static Allocator &Get(AttachedDatabase &db);
130502};
130503
130504}
130505
130506
130507
130508
130509
130510
130511
130512
130513
130514
130515
130516
130517
130518
130519
130520
130521namespace duckdb {
130522
130524#define DEFAULT_STANDARD_VECTOR_SIZE 2048U
130525
130527#ifndef STANDARD_VECTOR_SIZE
130528#define STANDARD_VECTOR_SIZE DEFAULT_STANDARD_VECTOR_SIZE
130529#endif
130530
130531#if (STANDARD_VECTOR_SIZE & (STANDARD_VECTOR_SIZE - 1) != 0)
130532#error The vector size must be a power of two
130533#endif
130534
130535}
130536
130537
130538namespace duckdb {
130539class VectorBuffer;
130540
130541struct SelectionData {
130542 DUCKDB_API explicit SelectionData(idx_t count);
130543
130544 AllocatedData owned_data;
130545};
130546
130547struct SelectionVector {
130548 SelectionVector() : sel_vector(nullptr) {
130549 }
130550 explicit SelectionVector(sel_t *sel) {
130551 Initialize(sel);
130552 }
130553 explicit SelectionVector(idx_t count) {
130554 Initialize(count);
130555 }
130556 SelectionVector(idx_t start, idx_t count) {
130557 Initialize(MaxValue<idx_t>(count, STANDARD_VECTOR_SIZE));
130558 for (idx_t i = 0; i < count; i++) {
130559 set_index(i, start + i);
130560 }
130561 }
130562 SelectionVector(const SelectionVector &sel_vector) {
130563 Initialize(sel_vector);
130564 }
130565 explicit SelectionVector(buffer_ptr<SelectionData> data) {
130566 Initialize(std::move(data));
130567 }
130568 SelectionVector &
operator=(SelectionVector &&other)
noexcept {
130569 sel_vector = other.sel_vector;
130570 other.sel_vector = nullptr;
130571 selection_data = std::move(other.selection_data);
130572 return *this;
130573 }
130574
130575public:
130576 static idx_t Inverted(
const SelectionVector &src, SelectionVector &dst, idx_t source_size, idx_t count) {
130577 idx_t src_idx = 0;
130578 idx_t dst_idx = 0;
130579 for (idx_t i = 0; i < count; i++) {
130580 if (src_idx < source_size && src.get_index(src_idx) == i) {
130581 src_idx++;
130582
130583 continue;
130584 }
130585
130586 dst.set_index(dst_idx++, i);
130587 }
130588 return dst_idx;
130589 }
130590
130591 void Initialize(sel_t *sel) {
130592 selection_data.reset();
130593 sel_vector = sel;
130594 }
130595 void Initialize(idx_t count = STANDARD_VECTOR_SIZE) {
130596 selection_data = make_shared_ptr<SelectionData>(count);
130597 sel_vector =
reinterpret_cast<sel_t *
>(selection_data->owned_data.get());
130598 }
130599 void Initialize(buffer_ptr<SelectionData> data) {
130600 selection_data = std::move(data);
130601 sel_vector =
reinterpret_cast<sel_t *
>(selection_data->owned_data.get());
130602 }
130603 void Initialize(const SelectionVector &other) {
130604 selection_data = other.selection_data;
130605 sel_vector = other.sel_vector;
130606 }
130607
130608 inline void set_index(idx_t idx, idx_t loc) {
130609 sel_vector[idx] = UnsafeNumericCast<sel_t>(loc);
130610 }
130611 inline void swap(idx_t i, idx_t j) {
130612 sel_t tmp = sel_vector[i];
130613 sel_vector[i] = sel_vector[j];
130614 sel_vector[j] = tmp;
130615 }
130616 inline idx_t get_index(idx_t idx)
const {
130617 return sel_vector ? get_index_unsafe(idx) : idx;
130618 }
130619 inline idx_t get_index_unsafe(idx_t idx)
const {
130620 return sel_vector[idx];
130621 }
130623 return sel_vector;
130624 }
130625 const sel_t *data()
const {
130626 return sel_vector;
130627 }
130628 buffer_ptr<SelectionData> sel_data() {
130629 return selection_data;
130630 }
130631 buffer_ptr<SelectionData> Slice(const SelectionVector &sel, idx_t count) const;
130632 idx_t SliceInPlace(
const SelectionVector &sel, idx_t count);
130633
130634 string ToString(idx_t count = 0) const;
130635 void Print(idx_t count = 0) const;
130636
130637 inline const sel_t &operator[](idx_t index)
const {
130638 return sel_vector[
index];
130639 }
130640 inline sel_t &operator[](idx_t index) {
130641 return sel_vector[
index];
130642 }
130643 inline bool IsSet() const {
130644 return sel_vector;
130645 }
130646 void Verify(idx_t count, idx_t vector_size) const;
130647 void Sort(idx_t count);
130648
130649private:
130650 sel_t *sel_vector;
130651 buffer_ptr<SelectionData> selection_data;
130652};
130653
130654class OptionalSelection {
130655public:
130656 explicit OptionalSelection(SelectionVector *sel_p) {
130657 Initialize(sel_p);
130658 }
130659 void Initialize(SelectionVector *sel_p) {
130660 sel = sel_p;
130661 if (sel) {
130662 vec.Initialize(sel->data());
130663 sel = &vec;
130664 }
130665 }
130666
130667 inline operator SelectionVector *() {
130668 return sel;
130669 }
130670
130671 inline void Append(idx_t &count, const idx_t idx) {
130672 if (sel) {
130673 sel->set_index(count, idx);
130674 }
130675 ++count;
130676 }
130677
130678 inline void Advance(idx_t completed) {
130679 if (sel) {
130680 sel->Initialize(sel->data() + completed);
130681 }
130682 }
130683
130684private:
130685 SelectionVector *sel;
130686 SelectionVector vec;
130687};
130688
130689}
130690
130691
130692
130693
130694
130695
130696
130697
130698
130699
130700
130701
130702
130703
130704
130705
130706
130707
130708
130709
130710
130711
130712namespace duckdb {
130713using std::to_string;
130714}
130715
130716
130717
130718
130719namespace duckdb {
130720struct SelectionVector;
130721struct ValidityMask;
130722
130723template <typename V>
130724struct TemplatedValidityData {
130725 static constexpr const idx_t BITS_PER_VALUE =
sizeof(V) * 8;
130726 static constexpr const V MAX_ENTRY = V(~V(0));
130727
130728public:
130729 inline explicit TemplatedValidityData(idx_t count) {
130730 auto entry_count = EntryCount(count);
130731 owned_data = make_unsafe_uniq_array_uninitialized<V>(entry_count);
130732 for (idx_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
130733 owned_data[entry_idx] = MAX_ENTRY;
130734 }
130735 }
130736 inline TemplatedValidityData(const V *validity_mask, idx_t count) {
130737 D_ASSERT(validity_mask);
130738 auto entry_count = EntryCount(count);
130739 owned_data = make_unsafe_uniq_array_uninitialized<V>(entry_count);
130740 for (idx_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
130741 owned_data[entry_idx] = validity_mask[entry_idx];
130742 }
130743 }
130744
130745 unsafe_unique_array<V> owned_data;
130746
130747public:
130748 static inline idx_t EntryCount(idx_t count) {
130749 return (count + (BITS_PER_VALUE - 1)) / BITS_PER_VALUE;
130750 }
130751};
130752
130754
130755struct ValidityData : TemplatedValidityData<validity_t> {
130756public:
130757 DUCKDB_API explicit ValidityData(idx_t count);
130758 DUCKDB_API ValidityData(const ValidityMask &original, idx_t count);
130759};
130760
130762template <typename V>
130763struct TemplatedValidityMask {
130764 using ValidityBuffer = TemplatedValidityData<V>;
130765
130766public:
130767 static constexpr const idx_t BITS_PER_VALUE = ValidityBuffer::BITS_PER_VALUE;
130768 static constexpr const idx_t STANDARD_ENTRY_COUNT = (STANDARD_VECTOR_SIZE + (BITS_PER_VALUE - 1)) / BITS_PER_VALUE;
130769 static constexpr const idx_t STANDARD_MASK_SIZE = STANDARD_ENTRY_COUNT *
sizeof(V);
130770
130771public:
130772 inline TemplatedValidityMask() : validity_mask(nullptr), capacity(STANDARD_VECTOR_SIZE) {
130773 }
130774 inline explicit TemplatedValidityMask(idx_t target_count) : validity_mask(nullptr), capacity(target_count) {
130775 }
130776 inline explicit TemplatedValidityMask(V *ptr, idx_t capacity) : validity_mask(ptr), capacity(capacity) {
130777 }
130778 inline TemplatedValidityMask(const TemplatedValidityMask &original, idx_t count) {
130779 Copy(original, count);
130780 }
130781
130782 static inline idx_t ValidityMaskSize(idx_t count = STANDARD_VECTOR_SIZE) {
130783 return ValidityBuffer::EntryCount(count) * sizeof(V);
130784 }
130785 inline bool AllValid() const {
130786 return !validity_mask;
130787 }
130788 inline bool CheckAllValid(idx_t count) const {
130789 return CountValid(count) == count;
130790 }
130791 inline bool CheckAllInvalid(idx_t count) const {
130792 return CountValid(count) == 0;
130793 }
130794
130795 inline bool CheckAllValid(idx_t to, idx_t from) const {
130796 if (AllValid()) {
130797 return true;
130798 }
130799 for (idx_t i = from; i < to; i++) {
130800 if (!RowIsValid(i)) {
130801 return false;
130802 }
130803 }
130804 return true;
130805 }
130806
130807 idx_t CountValid(
const idx_t count)
const {
130808 if (AllValid() || count == 0) {
130809 return count;
130810 }
130811
130813 const auto entry_count = EntryCount(count);
130814 for (idx_t entry_idx = 0; entry_idx < entry_count;) {
130815 auto entry = GetValidityEntry(entry_idx++);
130816
130817 if (entry_idx == entry_count && count % BITS_PER_VALUE != 0) {
130818 const auto shift = BITS_PER_VALUE - (count % BITS_PER_VALUE);
130819 const auto mask = ValidityBuffer::MAX_ENTRY >> shift;
130821 } else if (AllValid(entry)) {
130822
130823 valid += BITS_PER_VALUE;
130824 continue;
130825 }
130826
130827
130828 while (entry) {
130829 entry &= (entry - 1);
130830 ++valid;
130831 }
130832 }
130833
130834 return valid;
130835 }
130836
130837 inline V *GetData() const {
130838 return validity_mask;
130839 }
130840 inline void Reset(idx_t target_count_p = STANDARD_VECTOR_SIZE) {
130841 validity_mask = nullptr;
130842 validity_data.reset();
130843 capacity = target_count_p;
130844 }
130845
130846 static inline idx_t EntryCount(idx_t count) {
130847 return ValidityBuffer::EntryCount(count);
130848 }
130849 inline V GetValidityEntry(idx_t entry_idx) const {
130850 if (!validity_mask) {
130851 return ValidityBuffer::MAX_ENTRY;
130852 }
130853 return GetValidityEntryUnsafe(entry_idx);
130854 }
130855 inline V &GetValidityEntryUnsafe(idx_t entry_idx) const {
130856 return validity_mask[entry_idx];
130857 }
130858 static inline bool AllValid(V entry) {
130859
130860 return entry == ValidityBuffer::MAX_ENTRY;
130861 }
130862 static inline bool NoneValid(V entry) {
130863 return entry == 0;
130864 }
130865 static inline bool RowIsValid(const V &entry, const idx_t &idx_in_entry) {
130866 return entry & (V(1) << V(idx_in_entry));
130867 }
130868 static inline void GetEntryIndex(idx_t row_idx, idx_t &entry_idx, idx_t &idx_in_entry) {
130869 entry_idx = row_idx / BITS_PER_VALUE;
130870 idx_in_entry = row_idx % BITS_PER_VALUE;
130871 }
130873 static inline V EntryWithValidBits(idx_t n) {
130874 if (n == 0) {
130875 return V(0);
130876 }
130877 return ValidityBuffer::MAX_ENTRY >> (BITS_PER_VALUE - n);
130878 }
130879 static inline idx_t SizeInBytes(idx_t n) {
130880 return (n + BITS_PER_VALUE - 1) / BITS_PER_VALUE;
130881 }
130882
130885 inline bool RowIsValidUnsafe(idx_t row_idx) const {
130886 D_ASSERT(validity_mask);
130887 idx_t entry_idx, idx_in_entry;
130888 GetEntryIndex(row_idx, entry_idx, idx_in_entry);
130889 auto entry = GetValidityEntryUnsafe(entry_idx);
130890 return RowIsValid(entry, idx_in_entry);
130891 }
130892
130894 inline bool RowIsValid(idx_t row_idx) const {
130895#ifdef DEBUG
130896 if (row_idx >= capacity) {
130897 throw InternalException("ValidityMask::RowIsValid - row_idx %d is out-of-range for mask with capacity %llu",
130898 row_idx, capacity);
130899 }
130900#endif
130901 if (!validity_mask) {
130902 return true;
130903 }
130904 return RowIsValidUnsafe(row_idx);
130905 }
130906
130908 inline void SetValidUnsafe(idx_t row_idx) {
130909 D_ASSERT(validity_mask);
130910 idx_t entry_idx, idx_in_entry;
130911 GetEntryIndex(row_idx, entry_idx, idx_in_entry);
130912 validity_mask[entry_idx] |= (V(1) << V(idx_in_entry));
130913 }
130914
130916 inline void SetValid(idx_t row_idx) {
130917#ifdef DEBUG
130918 if (row_idx >= capacity) {
130919 throw InternalException("ValidityMask::SetValid - row_idx %d is out-of-range for mask with capacity %llu",
130920 row_idx, capacity);
130921 }
130922#endif
130923 if (!validity_mask) {
130924
130925
130926 return;
130927 }
130928 SetValidUnsafe(row_idx);
130929 }
130930
130932 inline void SetInvalidUnsafe(idx_t entry_idx, idx_t idx_in_entry) {
130933 D_ASSERT(validity_mask);
130934 validity_mask[entry_idx] &= ~(V(1) << V(idx_in_entry));
130935 }
130936
130938 inline void SetInvalidUnsafe(idx_t row_idx) {
130939 idx_t entry_idx, idx_in_entry;
130940 GetEntryIndex(row_idx, entry_idx, idx_in_entry);
130941 SetInvalidUnsafe(entry_idx, idx_in_entry);
130942 }
130943
130945 inline void SetInvalid(idx_t row_idx) {
130946#ifdef DEBUG
130947 if (row_idx >= capacity) {
130948 throw InternalException("ValidityMask::SetInvalid - row_idx %d is out-of-range for mask with capacity %llu",
130949 row_idx, capacity);
130950 }
130951#endif
130952 if (!validity_mask) {
130953 Initialize(capacity);
130954 }
130955 SetInvalidUnsafe(row_idx);
130956 }
130957
130959 inline void Set(idx_t row_idx, bool valid) {
130960 if (valid) {
130961 SetValid(row_idx);
130962 } else {
130963 SetInvalid(row_idx);
130964 }
130965 }
130966
130968 inline void EnsureWritable() {
130969 if (!validity_mask) {
130970 Initialize();
130971 }
130972 }
130973
130976 inline void SetRangeInvalid(const idx_t count, const idx_t begin_entry, const idx_t end_entry) {
130977 EnsureWritable();
130978 if (count == 0) {
130979 return;
130980 }
130981 const auto last_entry_index = ValidityBuffer::EntryCount(count) - 1;
130982 for (idx_t i = begin_entry; i < MinValue(last_entry_index, end_entry); i++) {
130983 validity_mask[i] = 0;
130984 }
130985 if (end_entry <= last_entry_index) {
130986 return;
130987 }
130988 const auto last_entry_bits = count % BITS_PER_VALUE;
130989 validity_mask[last_entry_index] =
130990 (last_entry_bits == 0) ? 0 : static_cast<V>(ValidityBuffer::MAX_ENTRY << (last_entry_bits));
130991 }
130992
130994 inline void SetAllInvalid(idx_t count) {
130995 SetRangeInvalid(count, 0, EntryCount(count));
130996 }
130997
130999 inline void SetAllValid(idx_t count) {
131000 EnsureWritable();
131001 if (count == 0) {
131002 return;
131003 }
131004 auto last_entry_index = ValidityBuffer::EntryCount(count) - 1;
131005 for (idx_t i = 0; i < last_entry_index; i++) {
131006 validity_mask[i] = ValidityBuffer::MAX_ENTRY;
131007 }
131008 auto last_entry_bits = count % BITS_PER_VALUE;
131009 validity_mask[last_entry_index] |= (last_entry_bits == 0)
131010 ? ValidityBuffer::MAX_ENTRY
131011 : ~static_cast<V>(ValidityBuffer::MAX_ENTRY << (last_entry_bits));
131012 }
131013
131014 inline bool IsMaskSet() const {
131015 if (validity_mask) {
131016 return true;
131017 }
131018 return false;
131019 }
131020
131021public:
131022 inline void Initialize(validity_t *validity, idx_t new_capacity) {
131023 validity_data.reset();
131024 validity_mask = validity;
131025 capacity = new_capacity;
131026 }
131027 inline void Initialize(const TemplatedValidityMask &other) {
131028 validity_mask = other.validity_mask;
131029 validity_data = other.validity_data;
131030 capacity = other.capacity;
131031 }
131032 inline void Initialize(idx_t count) {
131033 capacity = count;
131034 validity_data = make_buffer<ValidityBuffer>(count);
131035 validity_mask = validity_data->owned_data.get();
131036 }
131037 inline void Initialize() {
131038 Initialize(capacity);
131039 }
131040 inline void Copy(const TemplatedValidityMask &other, idx_t count) {
131041 capacity = count;
131042 if (other.AllValid()) {
131043 validity_data = nullptr;
131044 validity_mask = nullptr;
131045 } else {
131046 validity_data = make_buffer<ValidityBuffer>(other.validity_mask, count);
131047 validity_mask = validity_data->owned_data.get();
131048 }
131049 }
131050
131051protected:
131052 V *validity_mask;
131053 buffer_ptr<ValidityBuffer> validity_data;
131055};
131056
131057struct ValidityMask : public TemplatedValidityMask<validity_t> {
131058public:
131059 inline ValidityMask() : TemplatedValidityMask(nullptr, STANDARD_VECTOR_SIZE) {
131060 }
131061 inline explicit ValidityMask(idx_t capacity) : TemplatedValidityMask(capacity) {
131062 }
131063 inline explicit ValidityMask(validity_t *ptr, idx_t capacity) : TemplatedValidityMask(ptr, capacity) {
131064 }
131065 inline ValidityMask(const ValidityMask &original, idx_t count) : TemplatedValidityMask(original, count) {
131066 }
131067
131068public:
131069 DUCKDB_API void Resize(idx_t new_size);
131070 DUCKDB_API
idx_t Capacity()
const;
131071 DUCKDB_API void SliceInPlace(const ValidityMask &other, idx_t target_offset, idx_t source_offset, idx_t count);
131072 DUCKDB_API void Slice(const ValidityMask &other, idx_t source_offset, idx_t count);
131073 DUCKDB_API void CopySel(const ValidityMask &other, const SelectionVector &sel, idx_t source_offset,
131074 idx_t target_offset, idx_t count);
131075 DUCKDB_API void Combine(const ValidityMask &other, idx_t count);
131076 DUCKDB_API string ToString(idx_t count) const;
131077 DUCKDB_API string ToString() const;
131078
131079 DUCKDB_API static bool IsAligned(idx_t count);
131080
131081 void Write(WriteStream &writer, idx_t count);
131082 void Read(ReadStream &reader, idx_t count);
131083};
131084
131085
131086
131087
131088struct ValidityArray {
131089 inline ValidityArray() {
131090 }
131091
131092 inline bool AllValid() const {
131093 return !validity_mask;
131094 }
131095
131096 inline void Initialize(idx_t count, bool initial = true) {
131097 capacity = count;
131098 validity_data = make_unsafe_uniq_array<bool>(count);
131099 validity_mask = validity_data.get();
131100 memset(validity_mask, initial, sizeof(bool) * count);
131101 }
131102 inline void InitializeEmpty(idx_t count) {
131103 capacity = count;
131104 }
131105
131106 idx_t Capacity()
const {
131107 return capacity;
131108 }
131109
131112 inline bool RowIsValidUnsafe(idx_t row_idx) const {
131113 D_ASSERT(validity_mask);
131114 return validity_mask[row_idx];
131115 }
131116
131118 inline bool RowIsValid(idx_t row_idx) const {
131119#ifdef DEBUG
131120 if (row_idx >= capacity) {
131121 throw InternalException("ValidityData::RowIsValid - row_idx %d is out-of-range for mask with capacity %llu",
131122 row_idx, capacity);
131123 }
131124#endif
131125 if (!validity_mask) {
131126 return true;
131127 }
131128 return RowIsValidUnsafe(row_idx);
131129 }
131130
131132 inline void SetValidUnsafe(idx_t row_idx) {
131133 D_ASSERT(validity_mask);
131134 validity_mask[row_idx] = true;
131135 }
131136
131138 inline void SetValid(idx_t row_idx) {
131139#ifdef DEBUG
131140 if (row_idx >= capacity) {
131141 throw InternalException("ValidityData::SetValid - row_idx %d is out-of-range for mask with capacity %llu",
131142 row_idx, capacity);
131143 }
131144#endif
131145 if (!validity_mask) {
131146
131147
131148 return;
131149 }
131150
131151 SetValidUnsafe(row_idx);
131152 }
131153
131154 inline void Pack(ValidityMask &mask, const idx_t count) const {
131155 if (AllValid()) {
131156 mask.Reset(count);
131157 return;
131158 }
131159 mask.Initialize(count);
131160
131161 const auto entire_entries = count / ValidityMask::BITS_PER_VALUE;
131162 const auto ragged = count % ValidityMask::BITS_PER_VALUE;
131163 auto bits =
mask.GetData();
131164 idx_t row_idx = 0;
131165 for (idx_t i = 0; i < entire_entries; ++i) {
131166 validity_t entry = 0;
131167 for (idx_t j = 0; j < ValidityMask::BITS_PER_VALUE; ++j) {
131168 if (RowIsValidUnsafe(row_idx++)) {
131169 entry |= validity_t(1) << j;
131170 }
131171 }
131172 *bits++ = entry;
131173 }
131174 if (ragged) {
131175 validity_t entry = 0;
131176 for (idx_t j = 0; j < ragged; ++j) {
131177 if (RowIsValidUnsafe(row_idx++)) {
131178 entry |= validity_t(1) << j;
131179 }
131180 }
131181 *bits++ = entry;
131182 }
131183 }
131184
131185private:
131186 bool *validity_mask = nullptr;
131187 unsafe_unique_array<bool> validity_data;
131188 idx_t capacity = 0;
131189};
131190
131191}
131192
131193
131194
131195
131196
131197
131198
131199
131200
131201
131202
131203
131204
131205
131206
131207
131208
131209
131210
131211
131212
131213
131214
131215
131216
131217
131218
131219
131220
131221
131222
131223
131224
131225
131226
131227
131228
131229
131230
131231
131232
131233
131234
131235
131236
131237
131238
131239
131240
131241
131242
131243namespace duckdb {
131244
131246template <class T>
131247struct arena_deleter {
131249 pointer->~T();
131250 }
131251};
131252
131253template <class T>
131254using arena_ptr = unique_ptr<T, arena_deleter<T>>;
131255
131256template <class T>
131257using unsafe_arena_ptr = unique_ptr<T, arena_deleter<T>, false>;
131258
131259}
131260
131261
131262namespace duckdb {
131263
131264struct ArenaChunk {
131265 ArenaChunk(Allocator &allocator, idx_t size);
131266 ~ArenaChunk();
131267
131268 AllocatedData data;
131269 idx_t current_position;
131270 idx_t maximum_size;
131271 unsafe_unique_ptr<ArenaChunk> next;
131272 ArenaChunk *prev;
131273};
131274
131275class ArenaAllocator {
131276public:
131277 static constexpr const idx_t ARENA_ALLOCATOR_INITIAL_CAPACITY = 2048;
131278 static constexpr const idx_t ARENA_ALLOCATOR_MAX_CAPACITY = 1ULL << 24ULL;
131279
131280public:
131281 DUCKDB_API explicit ArenaAllocator(Allocator &allocator, idx_t initial_capacity = ARENA_ALLOCATOR_INITIAL_CAPACITY);
131282 DUCKDB_API ~ArenaAllocator();
131283
131284 data_ptr_t Allocate(idx_t len) {
131285 D_ASSERT(!head || head->current_position <= head->maximum_size);
131286 if (!head || head->current_position + len > head->maximum_size) {
131287 AllocateNewBlock(len);
131288 }
131289 D_ASSERT(head->current_position + len <= head->maximum_size);
131290 auto result = head->data.get() + head->current_position;
131291 head->current_position += len;
131292 return result;
131293 }
131294 DUCKDB_API data_ptr_t Reallocate(data_ptr_t pointer, idx_t old_size, idx_t size);
131295
131296 DUCKDB_API data_ptr_t AllocateAligned(idx_t size);
131297 DUCKDB_API data_ptr_t ReallocateAligned(data_ptr_t pointer, idx_t old_size, idx_t size);
131298
131300 DUCKDB_API void AlignNext();
131301
131304 DUCKDB_API void ShrinkHead(idx_t shrink_size) const {
131305 D_ASSERT(head && head->current_position >= shrink_size);
131306 head->current_position -= shrink_size;
131307 }
131308
131310 DUCKDB_API void Reset();
131311 DUCKDB_API void Destroy();
131312 DUCKDB_API void Move(ArenaAllocator &allocator);
131313
131314 DUCKDB_API ArenaChunk *GetHead();
131315 DUCKDB_API ArenaChunk *GetTail();
131316
131317 DUCKDB_API bool IsEmpty() const;
131319 DUCKDB_API
idx_t SizeInBytes()
const;
131321 DUCKDB_API
idx_t AllocationSize()
const;
131322
131324 Allocator &GetAllocator() {
131325 return arena_allocator;
131326 }
131327
131328 template <class T, class... ARGS>
131329 T *Make(ARGS &&... args) {
131330 auto mem = AllocateAligned(sizeof(T));
131331 return new (mem) T(std::forward<ARGS>(args)...);
131332 }
131333
131334 template <class T, class... ARGS>
131335 arena_ptr<T> MakePtr(ARGS &&... args) {
131336 return arena_ptr<T>(Make<T>(std::forward<ARGS>(args)...));
131337 }
131338
131339 template <class T, class... ARGS>
131340 unsafe_arena_ptr<T> MakeUnsafePtr(ARGS &&... args) {
131341 return unsafe_arena_ptr<T>(Make<T>(std::forward<ARGS>(args)...));
131342 }
131343
131344 String MakeString(
const char *data,
const size_t len) {
131345 data_ptr_t mem = nullptr;
131346
131347 D_ASSERT(len < NumericLimits<uint32_t>::Maximum());
131349 if (!String::CanBeInlined(size)) {
131350
131351 mem = AllocateAligned(sizeof(char) * size + 1);
131352 memcpy(mem, data, size);
131354 }
131355
131356 return String::Reference(mem ? reinterpret_cast<char *>(mem) : data, size);
131357 }
131358
131359 String MakeString(
const std::string &data) {
131360 return MakeString(data.c_str(), data.size());
131361 }
131362
131363private:
131364 void AllocateNewBlock(idx_t min_size);
131365
131366private:
131368 Allocator &allocator;
131369 idx_t initial_capacity;
131370 unsafe_unique_ptr<ArenaChunk> head;
131371 ArenaChunk *tail;
131373 Allocator arena_allocator;
131375 idx_t allocated_size = 0;
131376};
131377
131378}
131379
131380
131381namespace duckdb {
131385class StringHeap {
131386public:
131387 DUCKDB_API explicit StringHeap(Allocator &allocator = Allocator::DefaultAllocator());
131388
131389 DUCKDB_API void Destroy();
131390 DUCKDB_API void Move(StringHeap &other);
131391
131393 DUCKDB_API string_t AddString(const char *data, idx_t len);
131395 DUCKDB_API string_t AddString(const char *data);
131397 DUCKDB_API string_t AddString(const string &data);
131399 DUCKDB_API string_t AddString(const string_t &data);
131401 DUCKDB_API string_t AddBlob(const string_t &data);
131403 DUCKDB_API string_t AddBlob(const char *data, idx_t len);
131405 DUCKDB_API string_t EmptyString(idx_t len);
131406
131408 DUCKDB_API
idx_t SizeInBytes()
const;
131410 DUCKDB_API
idx_t AllocationSize()
const;
131411
131412 DUCKDB_API ArenaAllocator &GetAllocator() {
131413 return allocator;
131414 }
131415
131416private:
131417 ArenaAllocator allocator;
131418};
131419
131420}
131421
131422
131423
131424
131425
131426
131427
131428
131429
131430
131431
131432
131433
131434
131435
131436
131437
131438
131439
131440
131441
131442
131443
131444
131445
131446
131447
131448namespace duckdb {
131449
131450struct FileHandle;
131451class QueryContext;
131452
131454#define DEFAULT_ROW_GROUP_SIZE 122880ULL
131456#define INVALID_BLOCK (-1)
131458#define MAXIMUM_BLOCK 4611686018427388000LL
131459
131461#define DEFAULT_BLOCK_ALLOC_SIZE 262144ULL
131463#define DEFAULT_BLOCK_HEADER_STORAGE_SIZE 8ULL
131465#define DEFAULT_ENCRYPTION_BLOCK_HEADER_SIZE 40ULL
131467
131468
131469#ifndef DUCKDB_BLOCK_HEADER_STORAGE_SIZE
131470#define DUCKDB_BLOCK_HEADER_STORAGE_SIZE DEFAULT_BLOCK_HEADER_STORAGE_SIZE
131471#endif
131472
131473#ifndef DEFAULT_ENCRYPTED_BUFFER_HEADER_SIZE
131474#define DEFAULT_ENCRYPTED_BUFFER_HEADER_SIZE 32ULL
131475#endif
131476
131478
131479struct Storage {
131481 constexpr static idx_t SECTOR_SIZE = 4096U;
131484 constexpr static idx_t FILE_HEADER_SIZE = 4096U;
131486 constexpr static const idx_t MAX_ROW_GROUP_SIZE = 1ULL << 30ULL;
131488 constexpr static idx_t MIN_BLOCK_ALLOC_SIZE = 16384ULL;
131490 constexpr static idx_t MAX_BLOCK_ALLOC_SIZE = 262144ULL;
131492 constexpr static idx_t DEFAULT_BLOCK_HEADER_SIZE =
sizeof(
idx_t);
131494 constexpr static idx_t MAX_BLOCK_HEADER_SIZE = 128ULL;
131496 constexpr static idx_t DEFAULT_BLOCK_SIZE = DEFAULT_BLOCK_ALLOC_SIZE - DEFAULT_BLOCK_HEADER_SIZE;
131497
131499 static void VerifyBlockAllocSize(const idx_t block_alloc_size);
131500 static void VerifyBlockHeaderSize(const idx_t block_header_size);
131501};
131502
131505extern const uint64_t VERSION_NUMBER_LOWER;
131506extern const uint64_t VERSION_NUMBER_UPPER;
131507string GetDuckDBVersions(const idx_t version_number);
131508optional_idx GetStorageVersion(const char *version_string);
131509string GetStorageVersionName(const idx_t serialization_version, const bool add_suffix);
131510optional_idx GetSerializationVersion(const char *version_string);
131511vector<string> GetSerializationCandidates();
131512
131515class MainHeader {
131516public:
131517 static constexpr idx_t MAX_VERSION_SIZE = 32;
131518 static constexpr idx_t MAGIC_BYTE_SIZE = 4;
131519 static constexpr idx_t MAGIC_BYTE_OFFSET = Storage::DEFAULT_BLOCK_HEADER_SIZE;
131520 static constexpr idx_t FLAG_COUNT = 4;
131521
131523 static constexpr uint64_t ENCRYPTED_DATABASE_FLAG = 1;
131525 static constexpr uint64_t DEFAULT_ENCRYPTION_KEY_LENGTH = 32;
131527 static const char MAGIC_BYTES[];
131529 static const char CANARY[];
131530
131537
131539 static constexpr idx_t DB_IDENTIFIER_LEN = 16;
131541 static constexpr idx_t ENCRYPTION_METADATA_LEN = 8;
131543 static constexpr idx_t CANARY_BYTE_SIZE = 8;
131545 static constexpr uint64_t AES_NONCE_LEN = 12;
131546 static constexpr uint64_t AES_COUNTER_BYTES = 4;
131547 static constexpr uint64_t AES_NONCE_LEN_DEPRECATED = 16;
131548 static constexpr uint64_t AES_IV_LEN = 16;
131549 static constexpr uint64_t AES_TAG_LEN = 16;
131550
131551 static void CheckMagicBytes(QueryContext context, FileHandle &handle);
131552
131553 string LibraryGitDesc() {
131554 return string(char_ptr_cast(library_git_desc), 0, MAX_VERSION_SIZE);
131555 }
131556 string LibraryGitHash() {
131557 return string(char_ptr_cast(library_git_hash), 0, MAX_VERSION_SIZE);
131558 }
131559
131560 bool IsEncrypted() const {
131562 }
131563 void SetEncrypted() {
131565 }
131566 void SetEncryptionVersion(uint8_t version) {
131567 encryption_version = version;
131568 }
131569
131570 void SetEncryptionMetadata(data_ptr_t source) {
131571 memset(encryption_metadata, 0, ENCRYPTION_METADATA_LEN);
131572 memcpy(encryption_metadata, source, ENCRYPTION_METADATA_LEN);
131573 }
131574
131575 uint8_t GetEncryptionCipher()
const {
131576 return encryption_metadata[2];
131577 }
131578
131579 uint8_t GetEncryptionVersion()
const {
131580 return encryption_metadata[3];
131581 }
131582
131583 void SetDBIdentifier(data_ptr_t source) {
131584 memset(db_identifier, 0, DB_IDENTIFIER_LEN);
131585 memcpy(db_identifier, source, DB_IDENTIFIER_LEN);
131586 }
131587
131588 void SetEncryptedCanary(data_ptr_t source) {
131589 memset(encrypted_canary, 0, CANARY_BYTE_SIZE);
131590 memcpy(encrypted_canary, source, CANARY_BYTE_SIZE);
131591 }
131592
131593 void SetCanaryIV(data_ptr_t source) {
131594 memset(canary_iv, 0, AES_NONCE_LEN);
131595 memcpy(canary_iv, source, AES_NONCE_LEN);
131596 }
131597
131598 void SetCanaryTag(data_ptr_t source) {
131599 memset(canary_tag, 0, AES_TAG_LEN);
131600 memcpy(canary_tag, source, AES_TAG_LEN);
131601 }
131602
131603 data_ptr_t GetDBIdentifier() {
131604 return db_identifier;
131605 }
131606
131607 data_ptr_t GetIV() {
131608 return canary_iv;
131609 }
131610
131611 data_ptr_t GetTag() {
131612 return canary_tag;
131613 }
131614
131615 static bool CompareDBIdentifiers(const data_ptr_t db_identifier_1, const data_ptr_t db_identifier_2) {
131616 for (idx_t i = 0; i < DB_IDENTIFIER_LEN; i++) {
131617 if (db_identifier_1[i] != db_identifier_2[i]) {
131618 return false;
131619 }
131620 }
131621 return true;
131622 }
131623
131624 data_ptr_t GetEncryptedCanary() {
131625 return encrypted_canary;
131626 }
131627
131628 void Write(WriteStream &ser);
131629 static MainHeader Read(ReadStream &source);
131630
131631private:
131632 data_t library_git_desc[MAX_VERSION_SIZE];
131633 data_t library_git_hash[MAX_VERSION_SIZE];
131634 data_t encryption_metadata[ENCRYPTION_METADATA_LEN];
131636 data_t db_identifier[DB_IDENTIFIER_LEN];
131637 data_t encrypted_canary[CANARY_BYTE_SIZE];
131638 data_t canary_iv[AES_NONCE_LEN];
131639 data_t canary_tag[AES_TAG_LEN];
131640};
131641
131646struct DatabaseHeader {
131650 idx_t meta_block = 0;
131652 idx_t free_list = 0;
131657 idx_t block_alloc_size = 0;
131659 idx_t vector_size = 0;
131661 idx_t serialization_compatibility = 0;
131662
131663 void Write(WriteStream &ser);
131664 static DatabaseHeader Read(const MainHeader &header, ReadStream &source);
131665};
131666
131668
131669#if (DEFAULT_ROW_GROUP_SIZE % STANDARD_VECTOR_SIZE != 0)
131670#error The row group size must be a multiple of the vector size
131671#endif
131672#if (DEFAULT_ROW_GROUP_SIZE < STANDARD_VECTOR_SIZE)
131673#error Row groups must be able to hold at least one vector
131674#endif
131675#if (DEFAULT_BLOCK_ALLOC_SIZE & (DEFAULT_BLOCK_ALLOC_SIZE - 1) != 0)
131676#error The default block allocation size must be a power of two
131677#endif
131678
131679}
131680
131681
131682
131683namespace duckdb {
131684class BlockHandle;
131685class FileBuffer;
131686
131687class BufferHandle {
131688public:
131689 DUCKDB_API BufferHandle();
131690 DUCKDB_API explicit BufferHandle(shared_ptr<BlockHandle> handle, optional_ptr<FileBuffer> node);
131691 DUCKDB_API ~BufferHandle();
131692
131693 BufferHandle(const BufferHandle &other) = delete;
131694 BufferHandle &
operator=(
const BufferHandle &) =
delete;
131696 DUCKDB_API BufferHandle(BufferHandle &&other) noexcept;
131697 DUCKDB_API BufferHandle &
operator=(BufferHandle &&) noexcept;
131698
131699public:
131701 DUCKDB_API bool IsValid() const;
131703 inline data_ptr_t
Ptr()
const {
131704 D_ASSERT(IsValid());
131705 return node->buffer;
131706 }
131708 inline data_ptr_t
Ptr() {
131709 D_ASSERT(IsValid());
131710 return node->buffer;
131711 }
131713 DUCKDB_API FileBuffer &GetFileBuffer();
131715 DUCKDB_API void Destroy();
131716
131717 const shared_ptr<BlockHandle> &GetBlockHandle() const {
131718 return handle;
131719 }
131720
131721private:
131723 shared_ptr<BlockHandle> handle;
131725 optional_ptr<FileBuffer> node;
131726};
131727
131728}
131729
131730
131731namespace duckdb {
131732
131733class BufferHandle;
131734class VectorBuffer;
131735class Vector;
131736
131737enum class VectorBufferType :
uint8_t {
131738 STANDARD_BUFFER,
131739 DICTIONARY_BUFFER,
131740 VECTOR_CHILD_BUFFER,
131741 STRING_BUFFER,
131742 FSST_BUFFER,
131743 STRUCT_BUFFER,
131744 LIST_BUFFER,
131745 MANAGED_BUFFER,
131746 OPAQUE_BUFFER,
131747 ARRAY_BUFFER
131748};
131749
131750enum class VectorAuxiliaryDataType :
uint8_t {
131751 ARROW_AUXILIARY
131752};
131753
131754struct VectorAuxiliaryData {
131755 explicit VectorAuxiliaryData(VectorAuxiliaryDataType type_p)
131756 : type(type_p) {
131757
131758 };
131759 VectorAuxiliaryDataType type;
131760
131761 virtual ~VectorAuxiliaryData() {
131762 }
131763
131764public:
131765 template <class TARGET>
131766 TARGET &Cast() {
131767 if (type != TARGET::TYPE) {
131768 throw InternalException("Failed to cast vector auxiliary data to type - type mismatch");
131769 }
131770 return reinterpret_cast<TARGET &>(*this);
131771 }
131772
131773 template <class TARGET>
131774 const TARGET &Cast() const {
131775 if (type != TARGET::TYPE) {
131776 throw InternalException("Failed to cast vector auxiliary data to type - type mismatch");
131777 }
131778 return reinterpret_cast<const TARGET &>(*this);
131779 }
131780};
131781
131783class VectorBuffer {
131784public:
131785 explicit VectorBuffer(VectorBufferType type) : buffer_type(type) {
131786 }
131787 explicit VectorBuffer(idx_t data_size) : buffer_type(VectorBufferType::STANDARD_BUFFER) {
131788 if (data_size > 0) {
131789 data = Allocator::DefaultAllocator().Allocate(data_size);
131790 }
131791 }
131792 explicit VectorBuffer(AllocatedData &&data_p)
131793 : buffer_type(VectorBufferType::STANDARD_BUFFER), data(std::move(data_p)) {
131794 }
131795 virtual ~VectorBuffer() {
131796 }
131797 VectorBuffer() {
131798 }
131799
131800public:
131801 data_ptr_t GetData() {
131802 return data.get();
131803 }
131804
131805 void SetData(AllocatedData &&new_data) {
131806 data = std::move(new_data);
131807 }
131808
131809 VectorAuxiliaryData *GetAuxiliaryData() {
131810 return aux_data.get();
131811 }
131812
131813 void SetAuxiliaryData(unique_ptr<VectorAuxiliaryData> aux_data_p) {
131814 aux_data = std::move(aux_data_p);
131815 }
131816
131817 void MoveAuxiliaryData(VectorBuffer &source_buffer) {
131818 SetAuxiliaryData(std::move(source_buffer.aux_data));
131819 }
131820
131821 virtual optional_ptr<Allocator> GetAllocator() const {
131822 return data.GetAllocator();
131823 }
131824
131825 static buffer_ptr<VectorBuffer> CreateStandardVector(PhysicalType type, idx_t capacity = STANDARD_VECTOR_SIZE);
131826 static buffer_ptr<VectorBuffer> CreateConstantVector(PhysicalType type);
131827 static buffer_ptr<VectorBuffer> CreateConstantVector(const LogicalType &logical_type);
131828 static buffer_ptr<VectorBuffer> CreateStandardVector(const LogicalType &logical_type,
131829 idx_t capacity = STANDARD_VECTOR_SIZE);
131830
131831 inline VectorBufferType GetBufferType() const {
131832 return buffer_type;
131833 }
131834
131835 inline VectorAuxiliaryDataType GetAuxiliaryDataType() const {
131836 return aux_data->type;
131837 }
131838
131839protected:
131840 VectorBufferType buffer_type;
131841 unique_ptr<VectorAuxiliaryData> aux_data;
131842 AllocatedData data;
131843
131844public:
131845 template <class TARGET>
131846 TARGET &Cast() {
131847 DynamicCastCheck<TARGET>(this);
131848 return reinterpret_cast<TARGET &>(*this);
131849 }
131850 template <class TARGET>
131851 const TARGET &Cast() const {
131852 DynamicCastCheck<TARGET>(this);
131853 return reinterpret_cast<const TARGET &>(*this);
131854 }
131855};
131856
131858class DictionaryBuffer : public VectorBuffer {
131859public:
131860 explicit DictionaryBuffer(const SelectionVector &sel)
131861 : VectorBuffer(VectorBufferType::DICTIONARY_BUFFER), sel_vector(sel) {
131862 }
131863 explicit DictionaryBuffer(buffer_ptr<SelectionData> data)
131864 : VectorBuffer(VectorBufferType::DICTIONARY_BUFFER), sel_vector(std::move(data)) {
131865 }
131866 explicit DictionaryBuffer(idx_t count = STANDARD_VECTOR_SIZE)
131867 : VectorBuffer(VectorBufferType::DICTIONARY_BUFFER), sel_vector(count) {
131868 }
131869
131870public:
131871 const SelectionVector &GetSelVector() const {
131872 return sel_vector;
131873 }
131874 SelectionVector &GetSelVector() {
131875 return sel_vector;
131876 }
131877 void SetSelVector(const SelectionVector &vector) {
131878 this->sel_vector.Initialize(vector);
131879 }
131880 void SetDictionarySize(idx_t dict_size) {
131881 dictionary_size = dict_size;
131882 }
131883 optional_idx GetDictionarySize() const {
131884 return dictionary_size;
131885 }
131886 void SetDictionaryId(string id) {
131887 dictionary_id = std::move(id);
131888 }
131889 const string &GetDictionaryId() const {
131890 return dictionary_id;
131891 }
131892
131893private:
131894 SelectionVector sel_vector;
131895 optional_idx dictionary_size;
131897 string dictionary_id;
131898};
131899
131900class VectorStringBuffer : public VectorBuffer {
131901public:
131902 VectorStringBuffer();
131903 explicit VectorStringBuffer(Allocator &allocator);
131904 explicit VectorStringBuffer(VectorBufferType type);
131905
131906public:
131907 string_t AddString(const char *data, idx_t len) {
131908 return heap.AddString(data, len);
131909 }
131910 string_t AddString(string_t data) {
131911 return heap.AddString(data);
131912 }
131913 string_t AddBlob(string_t data) {
131914 return heap.AddBlob(data.GetData(), data.GetSize());
131915 }
131916 string_t EmptyString(idx_t len) {
131917 return heap.EmptyString(len);
131918 }
131919
131920 ArenaAllocator &GetStringAllocator() {
131921 return heap.GetAllocator();
131922 }
131926 data_ptr_t AllocateShrinkableBuffer(idx_t alloc_len) {
131927 auto &allocator = heap.GetAllocator();
131928 return allocator.Allocate(alloc_len);
131929 }
131932 string_t FinalizeShrinkableBuffer(data_ptr_t buffer, idx_t alloc_len, idx_t str_len) {
131933 auto &allocator = heap.GetAllocator();
131934 D_ASSERT(str_len <= alloc_len);
131935 D_ASSERT(buffer == allocator.GetHead()->data.get() + allocator.GetHead()->current_position - alloc_len);
131936 bool is_not_inlined = str_len > string_t::INLINE_LENGTH;
131937 idx_t shrink_count = alloc_len - (str_len * is_not_inlined);
131938 allocator.ShrinkHead(shrink_count);
131939 return string_t(const_char_ptr_cast(buffer), UnsafeNumericCast<uint32_t>(str_len));
131940 }
131941
131942 void AddHeapReference(buffer_ptr<VectorBuffer> heap) {
131943 references.push_back(std::move(heap));
131944 }
131945
131946private:
131948 StringHeap heap;
131950 vector<buffer_ptr<VectorBuffer>> references;
131951};
131952
131953class VectorFSSTStringBuffer : public VectorStringBuffer {
131954public:
131955 VectorFSSTStringBuffer();
131956
131957public:
131958 void AddDecoder(buffer_ptr<void> &duckdb_fsst_decoder_p, const idx_t string_block_limit) {
131959 duckdb_fsst_decoder = duckdb_fsst_decoder_p;
131960 decompress_buffer.resize(string_block_limit + 1);
131961 }
131962 void *GetDecoder() {
131963 return duckdb_fsst_decoder.get();
131964 }
131965 vector<unsigned char> &GetDecompressBuffer() {
131966 return decompress_buffer;
131967 }
131968 void SetCount(idx_t count) {
131969 total_string_count = count;
131970 }
131971 idx_t GetCount() {
131972 return total_string_count;
131973 }
131974
131975private:
131976 buffer_ptr<void> duckdb_fsst_decoder;
131977 idx_t total_string_count = 0;
131978 vector<unsigned char> decompress_buffer;
131979};
131980
131981class VectorStructBuffer : public VectorBuffer {
131982public:
131983 VectorStructBuffer();
131984 explicit VectorStructBuffer(const LogicalType &struct_type, idx_t capacity = STANDARD_VECTOR_SIZE);
131985 VectorStructBuffer(Vector &other, const SelectionVector &sel, idx_t count);
131986 ~VectorStructBuffer() override;
131987
131988public:
131989 const vector<unique_ptr<Vector>> &GetChildren() const {
131990 return children;
131991 }
131992 vector<unique_ptr<Vector>> &GetChildren() {
131993 return children;
131994 }
131995
131996private:
131998 vector<unique_ptr<Vector>> children;
131999};
132000
132001class VectorListBuffer : public VectorBuffer {
132002public:
132003 explicit VectorListBuffer(unique_ptr<Vector> vector, idx_t initial_capacity = STANDARD_VECTOR_SIZE);
132004 explicit VectorListBuffer(const LogicalType &list_type, idx_t initial_capacity = STANDARD_VECTOR_SIZE);
132005 ~VectorListBuffer() override;
132006
132007public:
132008 Vector &GetChild() {
132009 return *child;
132010 }
132011 void Reserve(idx_t to_reserve);
132012
132013 void Append(const Vector &to_append, idx_t to_append_size, idx_t source_offset = 0);
132014 void Append(const Vector &to_append, const SelectionVector &sel, idx_t to_append_size, idx_t source_offset = 0);
132015
132016 void PushBack(const Value &insert);
132017
132020 }
132021
132022 idx_t GetCapacity() {
132023 return capacity;
132024 }
132025
132026 void SetCapacity(idx_t new_capacity);
132027 void SetSize(idx_t new_size);
132028
132029private:
132031 unique_ptr<Vector> child;
132032 idx_t capacity = 0;
132034};
132035
132036class VectorArrayBuffer : public VectorBuffer {
132037public:
132038 explicit VectorArrayBuffer(unique_ptr<Vector> child_vector, idx_t array_size, idx_t initial_capacity);
132039 explicit VectorArrayBuffer(const LogicalType &array, idx_t initial = STANDARD_VECTOR_SIZE);
132040 ~VectorArrayBuffer() override;
132041
132042public:
132043 Vector &GetChild();
132044 idx_t GetArraySize();
132045 idx_t GetChildSize();
132046
132047private:
132048 unique_ptr<Vector> child;
132049
132050 idx_t array_size = 0;
132051
132052
132054};
132055
132057class ManagedVectorBuffer : public VectorBuffer {
132058public:
132059 explicit ManagedVectorBuffer(BufferHandle handle);
132060 ~ManagedVectorBuffer() override;
132061
132062private:
132063 BufferHandle handle;
132064};
132065
132066}
132067
132068
132069
132070
132071
132072
132073
132074
132075
132076
132077
132078
132079
132080
132081
132082
132083
132084
132085
132086
132087
132088
132089
132090
132091
132092
132093
132094
132095
132096#include <cmath>
132097
132098namespace duckdb {
132099
132100
132101struct double_na_equal {
132102 double_na_equal() : val(0) {
132103 }
132104 explicit double_na_equal(const double val_p) : val(val_p) {
132105 }
132106
132107 operator double() const {
132108 return val;
132109 }
132110
132111 bool operator==(
const double &right)
const {
132112 if (std::isnan(val) && std::isnan(right)) {
132113 return true;
132114 }
132115 return val == right;
132116 }
132117
132118 bool operator!=(
const double &right)
const {
132119 return !(*this == right);
132120 }
132121
132122 double val;
132123};
132124
132125struct float_na_equal {
132126 float_na_equal() : val(0) {
132127 }
132128 explicit float_na_equal(const float val_p) : val(val_p) {
132129 }
132130
132131 operator float() const {
132132 return val;
132133 }
132134
132135 bool operator==(
const float &right)
const {
132136 if (std::isnan(val) && std::isnan(right)) {
132137 return true;
132138 }
132139 return val == right;
132140 }
132141
132142 bool operator!=(
const float &right)
const {
132143 return !(*this == right);
132144 }
132145
132146 float val;
132147};
132148
132149}
132150
132151
132152namespace duckdb {
132153struct bignum_t;
132154
132156template <class T>
132158 using TYPE =
typename std::remove_cv<T>::type;
132159
132160 if (std::is_same<TYPE, bool>()) {
132161 return PhysicalType::BOOL;
132162 } else if (std::is_same<TYPE, int8_t>()) {
132163 return PhysicalType::INT8;
132164 } else if (std::is_same<TYPE, int16_t>()) {
132165 return PhysicalType::INT16;
132166 } else if (std::is_same<TYPE, int32_t>()) {
132167 return PhysicalType::INT32;
132168 } else if (std::is_same<TYPE, int64_t>()) {
132169 return PhysicalType::INT64;
132170 } else if (std::is_same<TYPE, uint8_t>()) {
132171 return PhysicalType::UINT8;
132172 } else if (std::is_same<TYPE, uint16_t>()) {
132173 return PhysicalType::UINT16;
132174 } else if (std::is_same<TYPE, uint32_t>()) {
132175 return PhysicalType::UINT32;
132176 } else if (std::is_same<TYPE, uint64_t>()) {
132177 return PhysicalType::UINT64;
132178 } else if (std::is_same<TYPE, idx_t>() || std::is_same<TYPE, const idx_t>()) {
132179 return PhysicalType::UINT64;
132180 } else if (std::is_same<TYPE, hugeint_t>()) {
132181 return PhysicalType::INT128;
132182 } else if (std::is_same<TYPE, uhugeint_t>()) {
132183 return PhysicalType::UINT128;
132184 } else if (std::is_same<TYPE, date_t>()) {
132185 return PhysicalType::INT32;
132186 } else if (std::is_same<TYPE, dtime_t>()) {
132187 return PhysicalType::INT64;
132188 } else if (std::is_same<TYPE, dtime_tz_t>()) {
132189 return PhysicalType::INT64;
132190 } else if (std::is_same<TYPE, dtime_ns_t>()) {
132191 return PhysicalType::INT64;
132192 } else if (std::is_same<TYPE, timestamp_t>()) {
132193 return PhysicalType::INT64;
132194 } else if (std::is_same<TYPE, timestamp_sec_t>()) {
132195 return PhysicalType::INT64;
132196 } else if (std::is_same<TYPE, timestamp_ms_t>()) {
132197 return PhysicalType::INT64;
132198 } else if (std::is_same<TYPE, timestamp_ns_t>()) {
132199 return PhysicalType::INT64;
132200 } else if (std::is_same<TYPE, timestamp_tz_t>()) {
132201 return PhysicalType::INT64;
132202 } else if (std::is_same<TYPE, float>() || std::is_same<TYPE, float_na_equal>()) {
132203 return PhysicalType::FLOAT;
132204 } else if (std::is_same<TYPE, double>() || std::is_same<TYPE, double_na_equal>()) {
132205 return PhysicalType::DOUBLE;
132206 } else if (std::is_same<TYPE, const char *>() || std::is_same<TYPE, char *>() || std::is_same<TYPE, string_t>() ||
132207 std::is_same<TYPE, bignum_t>()) {
132208 return PhysicalType::VARCHAR;
132209 } else if (std::is_same<TYPE, interval_t>()) {
132210 return PhysicalType::INTERVAL;
132211 } else if (std::is_same<TYPE, list_entry_t>()) {
132212 return PhysicalType::LIST;
132213 } else if (std::is_pointer<TYPE>() || std::is_same<TYPE, uintptr_t>()) {
132214 if (sizeof(uintptr_t) == sizeof(uint32_t)) {
132215 return PhysicalType::UINT32;
132216 } else if (sizeof(uintptr_t) == sizeof(uint64_t)) {
132217 return PhysicalType::UINT64;
132218 } else {
132219 throw InternalException("Unsupported pointer size in GetTypeId");
132220 }
132221 } else {
132222 throw InternalException("Unsupported type in GetTypeId");
132223 }
132224}
132225
132226template <class T>
132227bool StorageTypeCompatible(PhysicalType type) {
132228 using TYPE =
typename std::remove_cv<T>::type;
132229
132230 if (std::is_same<TYPE, int8_t>()) {
132231 return type == PhysicalType::INT8 || type == PhysicalType::BOOL;
132232 }
132233 if (std::is_same<TYPE, uint8_t>()) {
132234 return type == PhysicalType::UINT8 || type == PhysicalType::BOOL;
132235 }
132236 return type == GetTypeId<T>();
132237}
132238
132239template <class T>
132240bool TypeIsNumber() {
132241 using TYPE =
typename std::remove_cv<T>::type;
132242
132243 return std::is_integral<TYPE>() || std::is_floating_point<TYPE>() || std::is_same<TYPE, hugeint_t>() ||
132244 std::is_same<TYPE, uhugeint_t>();
132245}
132246
132247template <class T>
132248bool IsValidType() {
132249 return GetTypeId<T>() != PhysicalType::INVALID;
132250}
132251
132252template <class T>
132253bool IsIntegerType() {
132254 return TypeIsIntegral(GetTypeId<T>());
132255}
132256
132257}
132258
132259
132260namespace duckdb {
132261
132262class VectorCache;
132263class VectorChildBuffer;
132264class VectorStringBuffer;
132265class VectorStructBuffer;
132266class VectorListBuffer;
132267struct SelCache;
132268
132269struct UnifiedVectorFormat {
132270 DUCKDB_API UnifiedVectorFormat();
132271
132272 UnifiedVectorFormat(const UnifiedVectorFormat &other) = delete;
132273 UnifiedVectorFormat &
operator=(
const UnifiedVectorFormat &) =
delete;
132275 DUCKDB_API UnifiedVectorFormat(UnifiedVectorFormat &&other) noexcept;
132276 DUCKDB_API UnifiedVectorFormat &
operator=(UnifiedVectorFormat &&) noexcept;
132277
132278 const SelectionVector *sel;
132279 data_ptr_t data;
132280 ValidityMask validity;
132281 SelectionVector owned_sel;
132282 PhysicalType physical_type;
132283
132284 template <class T>
132285 void VerifyVectorType() const {
132286#ifdef DUCKDB_DEBUG_NO_SAFETY
132287 D_ASSERT(StorageTypeCompatible<T>(physical_type));
132288#else
132289 if (!StorageTypeCompatible<T>(physical_type)) {
132290 throw InternalException("Expected unified vector format of type %s, but found type %s", GetTypeId<T>(),
132291 physical_type);
132292 }
132293#endif
132294 }
132295
132296 template <class T>
132297 static inline const T *GetDataUnsafe(
const UnifiedVectorFormat &
format) {
132298 return reinterpret_cast<const T *
>(
format.data);
132299 }
132300 template <class T>
132301 static inline const T *GetData(
const UnifiedVectorFormat &
format) {
132302 return format.GetData<T>();
132303 }
132304 template <class T>
132305 inline const T *GetData() const {
132306 VerifyVectorType<T>();
132307 return GetDataUnsafe<T>(*this);
132308 }
132309 template <class T>
132310 static inline T *GetDataNoConst(UnifiedVectorFormat &
format) {
132311 format.VerifyVectorType<T>();
132312 return reinterpret_cast<T *
>(
format.data);
132313 }
132314};
132315
132316struct RecursiveUnifiedVectorFormat {
132317 UnifiedVectorFormat unified;
132318 vector<RecursiveUnifiedVectorFormat> children;
132319 LogicalType logical_type;
132320};
132321
132322struct UnifiedVariantVector {
132324 DUCKDB_API static const UnifiedVectorFormat &GetKeys(const RecursiveUnifiedVectorFormat &vec);
132326 DUCKDB_API static const UnifiedVectorFormat &GetKeysEntry(const RecursiveUnifiedVectorFormat &vec);
132328 DUCKDB_API static const UnifiedVectorFormat &GetChildren(const RecursiveUnifiedVectorFormat &vec);
132330 DUCKDB_API static const UnifiedVectorFormat &GetChildrenKeysIndex(const RecursiveUnifiedVectorFormat &vec);
132332 DUCKDB_API static const UnifiedVectorFormat &GetChildrenValuesIndex(const RecursiveUnifiedVectorFormat &vec);
132334 DUCKDB_API static const UnifiedVectorFormat &GetValues(const RecursiveUnifiedVectorFormat &vec);
132336 DUCKDB_API static const UnifiedVectorFormat &GetValuesTypeId(const RecursiveUnifiedVectorFormat &vec);
132338 DUCKDB_API static const UnifiedVectorFormat &GetValuesByteOffset(const RecursiveUnifiedVectorFormat &vec);
132340 DUCKDB_API static const UnifiedVectorFormat &GetData(const RecursiveUnifiedVectorFormat &vec);
132341};
132342
132344struct ResizeInfo {
132345 ResizeInfo(Vector &vec, data_ptr_t data, optional_ptr<VectorBuffer> buffer, const idx_t multiplier)
132346 : vec(vec), data(data), buffer(buffer), multiplier(multiplier) {
132347 }
132348
132349 Vector &vec;
132350 data_ptr_t data;
132351 optional_ptr<VectorBuffer> buffer;
132353};
132354
132355struct ConsecutiveChildListInfo {
132356 ConsecutiveChildListInfo() : is_constant(true), needs_slicing(false), child_list_info(list_entry_t(0, 0)) {
132357 }
132358 bool is_constant;
132359 bool needs_slicing;
132360 list_entry_t child_list_info;
132361};
132362
132364class Vector {
132365 friend struct ConstantVector;
132366 friend struct DictionaryVector;
132367 friend struct FlatVector;
132368 friend struct ListVector;
132369 friend struct StringVector;
132370 friend struct FSSTVector;
132371 friend struct StructVector;
132372 friend struct UnionVector;
132373 friend struct SequenceVector;
132374 friend struct ArrayVector;
132375
132376 friend class DataChunk;
132377 friend class VectorCacheBuffer;
132378
132379public:
132381 DUCKDB_API Vector(Vector &other);
132383 DUCKDB_API explicit Vector(const Vector &other, const SelectionVector &sel, idx_t count);
132385 DUCKDB_API explicit Vector(const Vector &other, idx_t offset, idx_t end);
132387 DUCKDB_API explicit Vector(const Value &value);
132389 DUCKDB_API explicit Vector(LogicalType type, idx_t capacity = STANDARD_VECTOR_SIZE);
132391 DUCKDB_API explicit Vector(const VectorCache &cache);
132393 DUCKDB_API Vector(LogicalType type, data_ptr_t dataptr);
132395
132400 DUCKDB_API Vector(LogicalType type, bool create_data, bool initialize_to_zero,
132401 idx_t capacity = STANDARD_VECTOR_SIZE);
132402
132403 Vector(const Vector &) = delete;
132404
132405 DUCKDB_API Vector(Vector &&other) noexcept;
132406
132407public:
132409 DUCKDB_API void Reference(const Value &value);
132412 DUCKDB_API void Reference(const Vector &other);
132416 DUCKDB_API void Reinterpret(const Vector &other);
132417
132419 DUCKDB_API void ReferenceAndSetType(const Vector &other);
132420
132424 DUCKDB_API void ResetFromCache(const VectorCache &cache);
132425
132427 DUCKDB_API void Slice(const Vector &other, idx_t offset, idx_t end);
132429 DUCKDB_API void Slice(const Vector &other, const SelectionVector &sel, idx_t count);
132431 DUCKDB_API void Slice(const SelectionVector &sel, idx_t count);
132433 DUCKDB_API void Slice(const SelectionVector &sel, idx_t count, SelCache &cache);
132435 DUCKDB_API void Dictionary(idx_t dictionary_size, const SelectionVector &sel, idx_t count);
132437 DUCKDB_API void Dictionary(Vector &dict, idx_t dictionary_size, const SelectionVector &sel, idx_t count);
132439 DUCKDB_API void Dictionary(buffer_ptr<VectorChildBuffer> reusable_dict, const SelectionVector &sel);
132440
132443 DUCKDB_API void Initialize(bool initialize_to_zero = false, idx_t capacity = STANDARD_VECTOR_SIZE);
132444
132446 DUCKDB_API string ToString(idx_t count) const;
132447 DUCKDB_API void Print(idx_t count) const;
132448
132449 DUCKDB_API string ToString() const;
132450 DUCKDB_API void Print() const;
132451
132453 DUCKDB_API void Flatten(idx_t count);
132454 DUCKDB_API void Flatten(const SelectionVector &sel, idx_t count);
132461 DUCKDB_API void ToUnifiedFormat(idx_t count, UnifiedVectorFormat &data);
132463 static void RecursiveToUnifiedFormat(Vector &input, idx_t count, RecursiveUnifiedVectorFormat &data);
132464
132466 DUCKDB_API void Sequence(int64_t start, int64_t increment, idx_t count);
132467
132470 DUCKDB_API void Verify(idx_t count);
132472 DUCKDB_API static void VerifyMap(Vector &map, const SelectionVector &sel, idx_t count);
132473 DUCKDB_API static void VerifyUnion(Vector &map, const SelectionVector &sel, idx_t count);
132474 DUCKDB_API static void VerifyVariant(Vector &map, const SelectionVector &sel, idx_t count);
132475 DUCKDB_API static void Verify(Vector &vector, const SelectionVector &sel, idx_t count);
132476 DUCKDB_API void UTFVerify(idx_t count);
132477 DUCKDB_API void UTFVerify(const SelectionVector &sel, idx_t count);
132478
132480 DUCKDB_API Value GetValue(idx_t index) const;
132482 DUCKDB_API void SetValue(idx_t index, const Value &val);
132483
132484 inline void SetAuxiliary(buffer_ptr<VectorBuffer> new_buffer) {
132485 auxiliary = std::move(new_buffer);
132486 };
132487
132488 inline void CopyBuffer(Vector &other) {
132489 buffer = other.buffer;
132490 data = other.data;
132491 }
132492
132494 DUCKDB_API void Resize(idx_t cur_size, idx_t new_size);
132496 DUCKDB_API void FindResizeInfos(vector<ResizeInfo> &resize_infos, const idx_t multiplier);
132497
132498 DUCKDB_API void Serialize(Serializer &serializer, idx_t count, bool compressed_serialization = true);
132499 DUCKDB_API void Deserialize(Deserializer &deserializer, idx_t count);
132500
132501 idx_t GetAllocationSize(idx_t cardinality)
const;
132502
132503
132504 inline VectorType GetVectorType() const {
132505 return vector_type;
132506 }
132507 inline const LogicalType &GetType() const {
132508 return type;
132509 }
132510 inline data_ptr_t GetData() const {
132511 return data;
132512 }
132513
132514 inline buffer_ptr<VectorBuffer> GetAuxiliary() {
132515 return auxiliary;
132516 }
132517
132518 inline buffer_ptr<VectorBuffer> GetBuffer() {
132519 return buffer;
132520 }
132521
132522
132523 DUCKDB_API void SetVectorType(VectorType vector_type);
132524
132525
132526 static void DebugTransformToDictionary(Vector &vector, idx_t count);
132527
132528 static void DebugShuffleNestedVector(Vector &vector, idx_t count);
132529
132530private:
132532 static Value GetValue(
const Vector &
v, idx_t index);
132534 static Value GetValueInternal(
const Vector &
v, idx_t index);
132535
132536protected:
132539 VectorType vector_type;
132541 LogicalType type;
132543 data_ptr_t data;
132545 ValidityMask validity;
132547 buffer_ptr<VectorBuffer> buffer;
132550 buffer_ptr<VectorBuffer> auxiliary;
132551};
132552
132554class VectorChildBuffer : public VectorBuffer {
132555public:
132556 explicit VectorChildBuffer(Vector vector)
132557 : VectorBuffer(VectorBufferType::VECTOR_CHILD_BUFFER), data(std::move(vector)),
132558 cached_hashes(LogicalType::HASH, nullptr) {
132559 }
132560
132561public:
132562 Vector data;
132564 optional_idx
size;
132565 string id;
132567 mutex cached_hashes_lock;
132568 Vector cached_hashes;
132569};
132570
132571struct ConstantVector {
132572 template <class T>
132573 static void VerifyVectorType(const Vector &vector) {
132574#ifdef DUCKDB_DEBUG_NO_SAFETY
132575 D_ASSERT(StorageTypeCompatible<T>(vector.GetType().InternalType()));
132576#else
132577 if (!StorageTypeCompatible<T>(vector.GetType().InternalType())) {
132578 throw InternalException("Expected vector of type %s, but found vector of type %s", GetTypeId<T>(),
132579 vector.GetType().InternalType());
132580 }
132581#endif
132582 }
132583
132584 static inline const_data_ptr_t GetData(const Vector &vector) {
132585 D_ASSERT(vector.GetVectorType() == VectorType::CONSTANT_VECTOR ||
132586 vector.GetVectorType() == VectorType::FLAT_VECTOR);
132587 return vector.data;
132588 }
132589 static inline data_ptr_t GetData(Vector &vector) {
132590 D_ASSERT(vector.GetVectorType() == VectorType::CONSTANT_VECTOR ||
132591 vector.GetVectorType() == VectorType::FLAT_VECTOR);
132592 return vector.data;
132593 }
132594 template <class T>
132595 static inline const T *GetDataUnsafe(const Vector &vector) {
132596 return reinterpret_cast<const T *>(GetData(vector));
132597 }
132598 template <class T>
132599 static inline T *GetDataUnsafe(Vector &vector) {
132600 return reinterpret_cast<T *>(GetData(vector));
132601 }
132602 template <class T>
132603 static inline const T *GetData(const Vector &vector) {
132604 VerifyVectorType<T>(vector);
132605 return GetDataUnsafe<T>(vector);
132606 }
132607 template <class T>
132608 static inline T *GetData(Vector &vector) {
132609 VerifyVectorType<T>(vector);
132610 return GetDataUnsafe<T>(vector);
132611 }
132612 static inline bool IsNull(const Vector &vector) {
132613 D_ASSERT(vector.GetVectorType() == VectorType::CONSTANT_VECTOR);
132614 return !vector.validity.RowIsValid(0);
132615 }
132616 DUCKDB_API static void SetNull(Vector &vector, bool is_null);
132617 static inline ValidityMask &Validity(Vector &vector) {
132618 D_ASSERT(vector.GetVectorType() == VectorType::CONSTANT_VECTOR);
132619 return vector.validity;
132620 }
132621 DUCKDB_API static const SelectionVector *ZeroSelectionVector(idx_t count, SelectionVector &owned_sel);
132622 DUCKDB_API static const SelectionVector *ZeroSelectionVector();
132624 DUCKDB_API static void Reference(Vector &vector, Vector &source, idx_t position, idx_t count);
132625
132626 static const sel_t ZERO_VECTOR[STANDARD_VECTOR_SIZE];
132627};
132628
132629struct DictionaryVector {
132630 static void VerifyDictionary(const Vector &vector) {
132631#ifdef DUCKDB_DEBUG_NO_SAFETY
132632 D_ASSERT(vector.GetVectorType() == VectorType::DICTIONARY_VECTOR);
132633#else
132634 if (vector.GetVectorType() != VectorType::DICTIONARY_VECTOR) {
132635 throw InternalException(
132636 "Operation requires a dictionary vector but a non-dictionary vector was encountered");
132637 }
132638#endif
132639 }
132640 static inline const SelectionVector &SelVector(const Vector &vector) {
132641 VerifyDictionary(vector);
132642 return vector.buffer->Cast<DictionaryBuffer>().GetSelVector();
132643 }
132644 static inline SelectionVector &SelVector(Vector &vector) {
132645 VerifyDictionary(vector);
132646 return vector.buffer->Cast<DictionaryBuffer>().GetSelVector();
132647 }
132648 static inline const Vector &Child(const Vector &vector) {
132649 VerifyDictionary(vector);
132650 return vector.auxiliary->Cast<VectorChildBuffer>().data;
132651 }
132652 static inline Vector &Child(Vector &vector) {
132653 VerifyDictionary(vector);
132654 return vector.auxiliary->Cast<VectorChildBuffer>().data;
132655 }
132656 static inline optional_idx DictionarySize(const Vector &vector) {
132657 VerifyDictionary(vector);
132658 const auto &child_buffer = vector.auxiliary->Cast<VectorChildBuffer>();
132659 if (child_buffer.size.IsValid()) {
132660 return child_buffer.size;
132661 }
132662 return vector.buffer->Cast<DictionaryBuffer>().GetDictionarySize();
132663 }
132664 static inline const string &DictionaryId(const Vector &vector) {
132665 VerifyDictionary(vector);
132666 const auto &child_buffer = vector.auxiliary->Cast<VectorChildBuffer>();
132667 if (!child_buffer.id.empty()) {
132668 return child_buffer.id;
132669 }
132670 return vector.buffer->Cast<DictionaryBuffer>().GetDictionaryId();
132671 }
132672 static inline bool CanCacheHashes(const LogicalType &type) {
132673 return type.InternalType() == PhysicalType::VARCHAR;
132674 }
132675 static inline bool CanCacheHashes(const Vector &vector) {
132676 return DictionarySize(vector).IsValid() && CanCacheHashes(vector.GetType());
132677 }
132678 static buffer_ptr<VectorChildBuffer> CreateReusableDictionary(const LogicalType &type, const idx_t &size);
132679 static const Vector &GetCachedHashes(Vector &input);
132680};
132681
132682struct FlatVector {
132683 static void VerifyFlatVector(const Vector &vector) {
132684#ifdef DUCKDB_DEBUG_NO_SAFETY
132685 D_ASSERT(vector.GetVectorType() == VectorType::FLAT_VECTOR);
132686#else
132687 if (vector.GetVectorType() != VectorType::FLAT_VECTOR) {
132688 throw InternalException("Operation requires a flat vector but a non-flat vector was encountered");
132689 }
132690#endif
132691 }
132692
132693 static inline data_ptr_t GetData(Vector &vector) {
132694 return ConstantVector::GetData(vector);
132695 }
132696 template <class T>
132697 static inline const T *GetData(const Vector &vector) {
132698 return ConstantVector::GetData<T>(vector);
132699 }
132700 template <class T>
132701 static inline T *GetData(Vector &vector) {
132702 return ConstantVector::GetData<T>(vector);
132703 }
132704 template <class T>
132705 static inline const T *GetDataUnsafe(const Vector &vector) {
132706 return ConstantVector::GetDataUnsafe<T>(vector);
132707 }
132708 template <class T>
132709 static inline T *GetDataUnsafe(Vector &vector) {
132710 return ConstantVector::GetDataUnsafe<T>(vector);
132711 }
132712 static inline void SetData(Vector &vector, data_ptr_t data) {
132713 D_ASSERT(vector.GetVectorType() == VectorType::FLAT_VECTOR);
132714 vector.data = data;
132715 }
132716 template <class T>
132717 static inline T GetValue(Vector &vector, idx_t idx) {
132718 D_ASSERT(vector.GetVectorType() == VectorType::FLAT_VECTOR);
132719 return FlatVector::GetData<T>(vector)[idx];
132720 }
132721 static inline const ValidityMask &Validity(const Vector &vector) {
132722 VerifyFlatVector(vector);
132723 return vector.validity;
132724 }
132725 static inline ValidityMask &Validity(Vector &vector) {
132726 VerifyFlatVector(vector);
132727 return vector.validity;
132728 }
132729 static inline void SetValidity(Vector &vector, const ValidityMask &new_validity) {
132730 VerifyFlatVector(vector);
132731 vector.validity.Initialize(new_validity);
132732 }
132733 DUCKDB_API static void SetNull(Vector &vector, idx_t idx, bool is_null);
132734 static inline bool IsNull(const Vector &vector, idx_t idx) {
132735 D_ASSERT(vector.GetVectorType() == VectorType::FLAT_VECTOR);
132736 return !vector.validity.RowIsValid(idx);
132737 }
132738 DUCKDB_API static const SelectionVector *IncrementalSelectionVector();
132739};
132740
132741struct ListVector {
132742 static inline const list_entry_t *GetData(
const Vector &
v) {
132743 if (
v.GetVectorType() == VectorType::DICTIONARY_VECTOR) {
132744 auto &child = DictionaryVector::Child(
v);
132745 return GetData(child);
132746 }
132747 return FlatVector::GetData<const list_entry_t>(
v);
132748 }
132749 static inline list_entry_t *GetData(Vector &
v) {
132750 if (
v.GetVectorType() == VectorType::DICTIONARY_VECTOR) {
132751 auto &child = DictionaryVector::Child(
v);
132752 return GetData(child);
132753 }
132754 return FlatVector::GetData<list_entry_t>(
v);
132755 }
132757 DUCKDB_API static const Vector &GetEntry(const Vector &vector);
132759 DUCKDB_API static Vector &GetEntry(Vector &vector);
132761 DUCKDB_API
static idx_t GetListSize(
const Vector &vector);
132763 DUCKDB_API static void SetListSize(Vector &vec, idx_t size);
132765 DUCKDB_API
static idx_t GetListCapacity(
const Vector &vector);
132767 DUCKDB_API static void Reserve(Vector &vec, idx_t required_capacity);
132768 DUCKDB_API static void Append(Vector &target, const Vector &source, idx_t source_size, idx_t source_offset = 0);
132769 DUCKDB_API static void Append(Vector &target, const Vector &source, const SelectionVector &sel, idx_t source_size,
132770 idx_t source_offset = 0);
132771 DUCKDB_API static void PushBack(Vector &target, const Value &insert);
132773 DUCKDB_API
static idx_t GetConsecutiveChildList(Vector &list, Vector &result, idx_t offset, idx_t count);
132775 DUCKDB_API static ConsecutiveChildListInfo GetConsecutiveChildListInfo(Vector &list, idx_t offset, idx_t count);
132777 DUCKDB_API static void GetConsecutiveChildSelVector(Vector &list, SelectionVector &sel, idx_t offset, idx_t count);
132779 DUCKDB_API static void ReferenceEntry(Vector &vector, Vector &other);
132780
132781private:
132782 template <class T>
132783 static T &GetEntryInternal(T &vector);
132784};
132785
132786struct StringVector {
132788 DUCKDB_API static string_t AddString(Vector &vector, const char *data, idx_t len);
132791 DUCKDB_API static string_t AddStringOrBlob(Vector &vector, const char *data, idx_t len);
132793 DUCKDB_API static string_t AddString(Vector &vector, const char *data);
132795 DUCKDB_API static string_t AddString(Vector &vector, string_t data);
132797 DUCKDB_API static string_t AddString(Vector &vector, const string &data);
132800 DUCKDB_API static string_t AddStringOrBlob(Vector &vector, string_t data);
132803 DUCKDB_API static string_t EmptyString(Vector &vector, idx_t len);
132805 DUCKDB_API static VectorStringBuffer &GetStringBuffer(Vector &vector);
132807 DUCKDB_API static void AddHandle(Vector &vector, BufferHandle handle);
132809 DUCKDB_API static void AddBuffer(Vector &vector, buffer_ptr<VectorBuffer> buffer);
132811 DUCKDB_API static void AddHeapReference(Vector &vector, Vector &other);
132812};
132813
132814struct FSSTVector {
132815 static inline const ValidityMask &Validity(const Vector &vector) {
132816 D_ASSERT(vector.GetVectorType() == VectorType::FSST_VECTOR);
132817 return vector.validity;
132818 }
132819 static inline ValidityMask &Validity(Vector &vector) {
132820 D_ASSERT(vector.GetVectorType() == VectorType::FSST_VECTOR);
132821 return vector.validity;
132822 }
132823 static inline void SetValidity(Vector &vector, ValidityMask &new_validity) {
132824 D_ASSERT(vector.GetVectorType() == VectorType::FSST_VECTOR);
132825 vector.validity.Initialize(new_validity);
132826 }
132827 static inline const_data_ptr_t GetCompressedData(const Vector &vector) {
132828 D_ASSERT(vector.GetVectorType() == VectorType::FSST_VECTOR);
132829 return vector.data;
132830 }
132831 static inline data_ptr_t GetCompressedData(Vector &vector) {
132832 D_ASSERT(vector.GetVectorType() == VectorType::FSST_VECTOR);
132833 return vector.data;
132834 }
132835 template <class T>
132836 static inline const T *GetCompressedData(const Vector &vector) {
132837 return (const T *)FSSTVector::GetCompressedData(vector);
132838 }
132839 template <class T>
132840 static inline T *GetCompressedData(Vector &vector) {
132841 return (T *)FSSTVector::GetCompressedData(vector);
132842 }
132844 static void DecompressVector(const Vector &src, Vector &dst, idx_t src_offset, idx_t dst_offset, idx_t copy_count,
132845 const SelectionVector *sel);
132846
132847 DUCKDB_API static string_t AddCompressedString(Vector &vector, string_t data);
132848 DUCKDB_API static string_t AddCompressedString(Vector &vector, const char *data, idx_t len);
132849 DUCKDB_API static void RegisterDecoder(Vector &vector, buffer_ptr<void> &duckdb_fsst_decoder,
132850 const idx_t string_block_limit);
132851 DUCKDB_API static void *GetDecoder(const Vector &vector);
132852 DUCKDB_API static vector<unsigned char> &GetDecompressBuffer(const Vector &vector);
132854 DUCKDB_API static void SetCount(Vector &vector, idx_t count);
132855 DUCKDB_API
static idx_t GetCount(Vector &vector);
132856};
132857
132858enum class MapInvalidReason :
uint8_t { VALID, NULL_KEY, DUPLICATE_KEY, NOT_ALIGNED, INVALID_PARAMS };
132859
132860struct MapVector {
132861 DUCKDB_API static const Vector &GetKeys(const Vector &vector);
132862 DUCKDB_API static const Vector &GetValues(const Vector &vector);
132863 DUCKDB_API static Vector &GetKeys(Vector &vector);
132864 DUCKDB_API static Vector &GetValues(Vector &vector);
132865 DUCKDB_API static MapInvalidReason
132866 CheckMapValidity(Vector &map, idx_t count, const SelectionVector &sel = *FlatVector::IncrementalSelectionVector());
132867 DUCKDB_API static void EvalMapInvalidReason(MapInvalidReason reason);
132868 DUCKDB_API static void MapConversionVerify(Vector &vector, idx_t count);
132869};
132870
132871struct StructVector {
132872 DUCKDB_API static const vector<unique_ptr<Vector>> &GetEntries(const Vector &vector);
132873 DUCKDB_API static vector<unique_ptr<Vector>> &GetEntries(Vector &vector);
132874};
132875
132876struct ArrayVector {
132878 DUCKDB_API static const Vector &GetEntry(const Vector &vector);
132880 DUCKDB_API static Vector &GetEntry(Vector &vector);
132882 DUCKDB_API
static idx_t GetTotalSize(
const Vector &vector);
132883
132884private:
132885 template <class T>
132886 static T &GetEntryInternal(T &vector);
132887};
132888
132889struct VariantVector {
132891 DUCKDB_API static Vector &GetKeys(Vector &vec);
132892 DUCKDB_API static Vector &GetKeys(const Vector &vec);
132894 DUCKDB_API static Vector &GetChildren(Vector &vec);
132895 DUCKDB_API static Vector &GetChildren(const Vector &vec);
132897 DUCKDB_API static Vector &GetChildrenKeysIndex(Vector &vec);
132898 DUCKDB_API static Vector &GetChildrenKeysIndex(const Vector &vec);
132900 DUCKDB_API static Vector &GetChildrenValuesIndex(Vector &vec);
132901 DUCKDB_API static Vector &GetChildrenValuesIndex(const Vector &vec);
132903 DUCKDB_API static Vector &GetValues(Vector &vec);
132904 DUCKDB_API static Vector &GetValues(const Vector &vec);
132906 DUCKDB_API static Vector &GetValuesTypeId(Vector &vec);
132907 DUCKDB_API static Vector &GetValuesTypeId(const Vector &vec);
132909 DUCKDB_API static Vector &GetValuesByteOffset(Vector &vec);
132910 DUCKDB_API static Vector &GetValuesByteOffset(const Vector &vec);
132912 DUCKDB_API static Vector &GetData(Vector &vec);
132913 DUCKDB_API static Vector &GetData(const Vector &vec);
132914};
132915
132916enum class UnionInvalidReason :
uint8_t {
132917 VALID,
132918 TAG_OUT_OF_RANGE,
132919 NO_MEMBERS,
132920 VALIDITY_OVERLAP,
132921 TAG_MISMATCH,
132922 NULL_TAG
132923};
132924
132925struct UnionVector {
132926
132927
132928
132929
132930
132931
132932
132933
132934
132935
132936
132937
132938
132939
132940
132941
132942
132944 DUCKDB_API
static const Vector &GetTags(
const Vector &
v);
132945 DUCKDB_API
static Vector &GetTags(Vector &
v);
132946
132949 DUCKDB_API static bool TryGetTag(const Vector &vector, idx_t index, union_tag_t &tag);
132950
132952 DUCKDB_API static const Vector &GetMember(const Vector &vector, idx_t member_index);
132953 DUCKDB_API static Vector &GetMember(Vector &vector, idx_t member_index);
132954
132962 DUCKDB_API static void SetToMember(Vector &vector, union_tag_t tag, Vector &member_vector, idx_t count,
132963 bool keep_tags_for_null);
132964
132965 DUCKDB_API static UnionInvalidReason
132966 CheckUnionValidity(Vector &vector, idx_t count,
132967 const SelectionVector &sel = *FlatVector::IncrementalSelectionVector());
132968};
132969
132970struct SequenceVector {
132971 static void GetSequence(const Vector &vector, int64_t &start, int64_t &increment, int64_t &sequence_count) {
132972 D_ASSERT(vector.GetVectorType() == VectorType::SEQUENCE_VECTOR);
132973 auto data =
reinterpret_cast<int64_t *
>(vector.buffer->GetData());
132974 start = data[0];
132975 increment = data[1];
132976 sequence_count = data[2];
132977 }
132978 static void GetSequence(const Vector &vector, int64_t &start, int64_t &increment) {
132980 GetSequence(vector, start, increment, sequence_count);
132981 }
132982};
132983
132984}
132985
132986
132987
132988
132989
132990
132991
132992
132993
132994
132995
132996
132997
132998
132999
133000
133001
133002
133003
133004
133005
133006
133007
133008
133009
133010
133011
133012
133013
133014
133015
133016
133017
133018
133019
133020
133021
133022
133023
133024#ifndef ARROW_FLAG_DICTIONARY_ORDERED
133025
133026#include <stdint.h>
133027
133028#ifdef __cplusplus
133029extern "C" {
133030#endif
133031
133032#ifndef ARROW_C_DATA_INTERFACE
133033#define ARROW_C_DATA_INTERFACE
133034
133035#define ARROW_FLAG_DICTIONARY_ORDERED 1
133036#define ARROW_FLAG_NULLABLE 2
133037#define ARROW_FLAG_MAP_KEYS_SORTED 4
133038
133039struct ArrowSchema {
133042 const char *name;
133043 const char *metadata;
133046 struct ArrowSchema **children;
133047 struct ArrowSchema *dictionary;
133048
133050 void (*release)(struct ArrowSchema *);
133052 void *private_data;
133053
133055 void Init() {
133056 flags = 0;
133057 n_children = 0;
133058 release = nullptr;
133059 private_data = nullptr;
133060 }
133061};
133062
133063struct ArrowArray {
133070 const void **buffers;
133071 struct ArrowArray **children;
133072 struct ArrowArray *dictionary;
133073
133075 void (*release)(struct ArrowArray *);
133077 void *private_data;
133078
133080 void Init() {
133081 length = 0;
133082 null_count = 0;
133083 offset = 0;
133084 n_buffers = 0;
133085 n_children = 0;
133086 release = nullptr;
133087 private_data = nullptr;
133088 }
133089};
133090#endif
133091
133092#ifndef ARROW_C_STREAM_INTERFACE
133093#define ARROW_C_STREAM_INTERFACE
133094
133095struct ArrowArrayStream {
133096
133097
133098
133099 int (*get_schema)(struct ArrowArrayStream *, struct ArrowSchema *out);
133100
133101
133102
133103 int (*get_next)(struct ArrowArrayStream *, struct ArrowArray *out);
133104
133105
133106
133107
133108
133109
133110 const char *(*get_last_error)(struct ArrowArrayStream *);
133111
133112
133113
133114 void (*release)(struct ArrowArrayStream *);
133115
133116 void *private_data;
133117};
133118#endif
133119
133120#ifdef __cplusplus
133121}
133122#endif
133123
133124#endif
133125
133126
133127
133129namespace duckdb {
133130
133131class ArrowSchemaWrapper {
133132public:
133133 ArrowSchema arrow_schema;
133134
133135 ArrowSchemaWrapper() {
133136 arrow_schema.
release =
nullptr;
133137 }
133138
133139 ~ArrowSchemaWrapper();
133140};
133141class ArrowArrayWrapper {
133142public:
133143 ArrowArray arrow_array;
133144 ArrowArrayWrapper() {
133145 arrow_array.
length = 0;
133146 arrow_array.
release =
nullptr;
133147 }
133148 ArrowArrayWrapper(ArrowArrayWrapper &&other) noexcept : arrow_array(other.arrow_array) {
133149 other.arrow_array.release = nullptr;
133150 }
133151 ArrowArrayWrapper &
operator=(ArrowArrayWrapper &&other)
noexcept {
133152 if (this != &other) {
133154 arrow_array.
release(&arrow_array);
133155 }
133156 arrow_array = other.arrow_array;
133157 other.arrow_array.release = nullptr;
133158 }
133159 return *this;
133160 }
133161 ~ArrowArrayWrapper();
133162};
133163
133164class ArrowArrayStreamWrapper {
133165public:
133166 ArrowArrayStream arrow_array_stream;
133168
133169public:
133170 void GetSchema(ArrowSchemaWrapper &schema);
133171
133172 virtual shared_ptr<ArrowArrayWrapper> GetNextChunk();
133173
133174 const char *GetError();
133175
133176 virtual ~ArrowArrayStreamWrapper();
133177 ArrowArrayStreamWrapper() {
133178 arrow_array_stream.release = nullptr;
133179 }
133180};
133181
133182}
133183
133184
133185
133186
133187
133188namespace duckdb {
133189class Allocator;
133190class ClientContext;
133191class ExecutionContext;
133192class VectorCache;
133193class Serializer;
133194class Deserializer;
133195
133197
133214class DataChunk {
133215public:
133217 DUCKDB_API DataChunk();
133218 DUCKDB_API ~DataChunk();
133219
133221 vector<Vector> data;
133222
133223public:
133225 return count;
133226 }
133227 inline idx_t ColumnCount()
const {
133228 return data.size();
133229 }
133230 inline void SetCardinality(idx_t count_p) {
133231 D_ASSERT(count_p <= capacity);
133232 this->count = count_p;
133233 }
133234 inline void SetCardinality(const DataChunk &other) {
133235 SetCardinality(other.size());
133236 }
133237 inline idx_t GetCapacity()
const {
133238 return capacity;
133239 }
133240 inline void SetCapacity(idx_t capacity_p) {
133241 this->capacity = capacity_p;
133242 }
133243 inline void SetCapacity(const DataChunk &other) {
133245 }
133246
133247 DUCKDB_API Value GetValue(idx_t col_idx, idx_t index) const;
133248 DUCKDB_API void SetValue(idx_t col_idx, idx_t index, const Value &val);
133249
133250 idx_t GetAllocationSize()
const;
133251
133253 DUCKDB_API bool AllConstant() const;
133254
133256 DUCKDB_API void Reference(DataChunk &chunk);
133258 DUCKDB_API void Move(DataChunk &chunk);
133259
133261 DUCKDB_API void InitializeEmpty(const vector<LogicalType> &types);
133262
133265 DUCKDB_API void Initialize(ClientContext &context, const vector<LogicalType> &types,
133266 idx_t capacity = STANDARD_VECTOR_SIZE);
133267 DUCKDB_API void Initialize(Allocator &allocator, const vector<LogicalType> &types,
133268 idx_t capacity = STANDARD_VECTOR_SIZE);
133269 DUCKDB_API void Initialize(ClientContext &context, const vector<LogicalType> &types, const vector<bool> &initialize,
133270 idx_t capacity = STANDARD_VECTOR_SIZE);
133271 DUCKDB_API void Initialize(Allocator &allocator, const vector<LogicalType> &types, const vector<bool> &initialize,
133272 idx_t capacity = STANDARD_VECTOR_SIZE);
133273
133277 DUCKDB_API void Append(const DataChunk &other, bool resize = false, SelectionVector *sel = nullptr,
133278 idx_t count = 0);
133279
133281 DUCKDB_API void Destroy();
133282
133284 DUCKDB_API void Copy(DataChunk &other, idx_t offset = 0) const;
133285 DUCKDB_API void Copy(DataChunk &other, const SelectionVector &sel, const idx_t source_count,
133286 const idx_t offset = 0) const;
133287
133289 DUCKDB_API void Split(DataChunk &other, idx_t split_idx);
133290
133292 DUCKDB_API void Fuse(DataChunk &other);
133293
133295 DUCKDB_API void ReferenceColumns(DataChunk &other, const vector<column_t> &column_ids);
133296
133298 DUCKDB_API void Flatten();
133299
133300
133301 DUCKDB_API unsafe_unique_array<UnifiedVectorFormat> ToUnifiedFormat();
133302
133303 DUCKDB_API void Slice(const SelectionVector &sel_vector, idx_t count);
133304
133307 DUCKDB_API void Slice(const DataChunk &other, const SelectionVector &sel, idx_t count, idx_t col_offset = 0);
133308
133310 DUCKDB_API void Slice(idx_t offset, idx_t count);
133311
133315 DUCKDB_API void Reset();
133316
133317 DUCKDB_API void Serialize(Serializer &serializer, bool compressed_serialization = true) const;
133318 DUCKDB_API void Deserialize(Deserializer &source);
133319
133321 DUCKDB_API void Hash(Vector &result);
133323 DUCKDB_API void Hash(vector<idx_t> &column_ids, Vector &result);
133324
133326 DUCKDB_API vector<LogicalType> GetTypes() const;
133327
133329 DUCKDB_API string ToString() const;
133330 DUCKDB_API void Print() const;
133331
133332 DataChunk(const DataChunk &) = delete;
133333
133336 DUCKDB_API void Verify();
133337
133338private:
133344 idx_t initial_capacity;
133346 vector<VectorCache> vector_caches;
133347};
133348}
133349
133350
133351
133352#include <functional>
133353
133354namespace duckdb {
133355class CastFunctionSet;
133356struct GetCastFunctionInput;
133357
133358
133359
133360
133361
133362
133363
133364
133365struct VectorOperations {
133366
133367
133368
133370 static void AddInPlace(Vector &left, int64_t delta, idx_t count);
133371
133372
133373
133374
133376 static void IsNotNull(Vector &
arg, Vector &result, idx_t count);
133378 static void IsNull(Vector &input, Vector &result, idx_t count);
133379
133380 static bool HasNull(Vector &input, idx_t count);
133381 static bool HasNotNull(Vector &input, idx_t count);
133383 static idx_t CountNotNull(Vector &input,
const idx_t count);
133384
133385
133386
133387
133388
133389 static void And(Vector &left, Vector &right, Vector &result, idx_t count);
133390
133391 static void Or(Vector &left, Vector &right, Vector &result, idx_t count);
133392
133393 static void Not(Vector &left, Vector &result, idx_t count);
133394
133395
133396
133397
133398
133399 static void Equals(Vector &left, Vector &right, Vector &result, idx_t count);
133400
133401 static void NotEquals(Vector &left, Vector &right, Vector &result, idx_t count);
133402
133403 static void GreaterThan(Vector &left, Vector &right, Vector &result, idx_t count);
133404
133405 static void GreaterThanEquals(Vector &left, Vector &right, Vector &result, idx_t count);
133406
133407 static void LessThan(Vector &left, Vector &right, Vector &result, idx_t count);
133408
133409 static void LessThanEquals(Vector &left, Vector &right, Vector &result, idx_t count);
133410
133411
133412 static void DistinctFrom(Vector &left, Vector &right, Vector &result, idx_t count);
133413
133414 static void NotDistinctFrom(Vector &left, Vector &right, Vector &result, idx_t count);
133415
133416 static void DistinctGreaterThan(Vector &left, Vector &right, Vector &result, idx_t count);
133417
133418 static void DistinctGreaterThanEquals(Vector &left, Vector &right, Vector &result, idx_t count);
133419
133420 static void DistinctLessThan(Vector &left, Vector &right, Vector &result, idx_t count);
133421
133422 static void DistinctLessThanEquals(Vector &left, Vector &right, Vector &result, idx_t count);
133423
133424
133425
133426
133427 static idx_t Equals(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
133428 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
133429 optional_ptr<ValidityMask> null_mask = nullptr);
133430 static idx_t NotEquals(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
133431 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
133432 optional_ptr<ValidityMask> null_mask = nullptr);
133433 static idx_t GreaterThan(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
133434 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
133435 optional_ptr<ValidityMask> null_mask = nullptr);
133436 static idx_t GreaterThanEquals(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
133437 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
133438 optional_ptr<ValidityMask> null_mask = nullptr);
133439 static idx_t LessThan(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
133440 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
133441 optional_ptr<ValidityMask> null_mask = nullptr);
133442 static idx_t LessThanEquals(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
133443 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
133444 optional_ptr<ValidityMask> null_mask = nullptr);
133445
133446
133447 static idx_t DistinctFrom(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
133448 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel);
133449
133450 static idx_t NotDistinctFrom(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
133451 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel);
133452
133453 static idx_t DistinctGreaterThan(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
133454 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
133455 optional_ptr<ValidityMask> null_mask = nullptr);
133456
133457 static idx_t DistinctGreaterThanEquals(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel,
133458 idx_t count, optional_ptr<SelectionVector> true_sel,
133459 optional_ptr<SelectionVector> false_sel,
133460 optional_ptr<ValidityMask> null_mask = nullptr);
133461
133462 static idx_t DistinctLessThan(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
133463 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
133464 optional_ptr<ValidityMask> null_mask = nullptr);
133465
133466 static idx_t DistinctLessThanEquals(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel,
133467 idx_t count, optional_ptr<SelectionVector> true_sel,
133468 optional_ptr<SelectionVector> false_sel,
133469 optional_ptr<ValidityMask> null_mask = nullptr);
133470
133471 static idx_t DistinctGreaterThanNullsFirst(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel,
133472 idx_t count, optional_ptr<SelectionVector> true_sel,
133473 optional_ptr<SelectionVector> false_sel,
133474 optional_ptr<ValidityMask> null_mask = nullptr);
133475
133476 static idx_t DistinctLessThanNullsFirst(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel,
133477 idx_t count, optional_ptr<SelectionVector> true_sel,
133478 optional_ptr<SelectionVector> false_sel,
133479 optional_ptr<ValidityMask> null_mask = nullptr);
133480
133481
133482
133483
133484
133485 static idx_t NestedNotEquals(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
133486 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
133487 optional_ptr<ValidityMask> null_mask = nullptr);
133488
133489 static idx_t NestedEquals(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
133490 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
133491 optional_ptr<ValidityMask> null_mask = nullptr);
133492
133493
133494
133495
133496
133497 static void Hash(Vector &input, Vector &hashes, idx_t count);
133498 static void Hash(Vector &input, Vector &hashes, const SelectionVector &rsel, idx_t count);
133499
133500 static void CombineHash(Vector &hashes, Vector &input, idx_t count);
133501 static void CombineHash(Vector &hashes, Vector &input,
const SelectionVector &rsel, idx_t count);
133502
133503
133504
133505
133506 static void GenerateSequence(Vector &result, idx_t count, int64_t start = 0, int64_t increment = 1);
133507 static void GenerateSequence(Vector &result, idx_t count, const SelectionVector &sel, int64_t start = 0,
133508 int64_t increment = 1);
133509
133510
133511
133515 DUCKDB_API static bool TryCast(CastFunctionSet &set, GetCastFunctionInput &input, Vector &source, Vector &result,
133516 idx_t count, string *error_message, bool strict = false,
133517 const bool nullify_parent = false);
133518 DUCKDB_API static bool DefaultTryCast(Vector &source, Vector &result, idx_t count, string *error_message,
133519 bool strict = false);
133520 DUCKDB_API static bool TryCast(ClientContext &context, Vector &source, Vector &result, idx_t count,
133521 string *error_message, bool strict = false, const bool nullify_parent = false);
133523 DUCKDB_API static void Cast(ClientContext &context, Vector &source, Vector &result, idx_t count,
133524 bool strict = false);
133525 DUCKDB_API static void DefaultCast(Vector &source, Vector &result, idx_t count, bool strict = false);
133526
133527
133528 static void Copy(const Vector &source, Vector &target, idx_t source_count, idx_t source_offset,
133529 idx_t target_offset);
133530 static void Copy(const Vector &source, Vector &target, const SelectionVector &sel, idx_t source_count,
133531 idx_t source_offset, idx_t target_offset);
133532 static void Copy(const Vector &source, Vector &target, const SelectionVector &sel, idx_t source_count,
133533 idx_t source_offset, idx_t target_offset, idx_t copy_count);
133534
133535
133536
133537 static void WriteToStorage(Vector &source, idx_t count, data_ptr_t target);
133538
133539
133540 static void ReadFromStorage(data_ptr_t source, idx_t count, Vector &result);
133541};
133542}
133543
133544
133545#include <functional>
133546
133547namespace duckdb {
133548
133549struct DefaultNullCheckOperator {
133550 template <class LEFT_TYPE, class RIGHT_TYPE>
133551 static inline bool Operation(LEFT_TYPE left, RIGHT_TYPE right) {
133552 return false;
133553 }
133554};
133555
133556struct BinaryStandardOperatorWrapper {
133557 template <class FUNC, class OP, class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE>
133558 static inline RESULT_TYPE Operation(FUNC fun, LEFT_TYPE left, RIGHT_TYPE right, ValidityMask &mask, idx_t idx) {
133559 return OP::template Operation<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE>(left, right);
133560 }
133561
133562 static bool AddsNulls() {
133563 return false;
133564 }
133565};
133566
133567struct BinarySingleArgumentOperatorWrapper {
133568 template <class FUNC, class OP, class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE>
133569 static inline RESULT_TYPE Operation(FUNC fun, LEFT_TYPE left, RIGHT_TYPE right, ValidityMask &mask, idx_t idx) {
133570 return OP::template Operation<LEFT_TYPE>(left, right);
133571 }
133572
133573 static bool AddsNulls() {
133574 return false;
133575 }
133576};
133577
133578struct BinaryLambdaWrapper {
133579 template <class FUNC, class OP, class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE>
133580 static inline RESULT_TYPE Operation(FUNC fun, LEFT_TYPE left, RIGHT_TYPE right, ValidityMask &mask, idx_t idx) {
133581 return fun(left, right);
133582 }
133583
133584 static bool AddsNulls() {
133585 return false;
133586 }
133587};
133588
133589struct BinaryLambdaWrapperWithNulls {
133590 template <class FUNC, class OP, class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE>
133591 static inline RESULT_TYPE Operation(FUNC fun, LEFT_TYPE left, RIGHT_TYPE right, ValidityMask &mask, idx_t idx) {
133592 return fun(left, right, mask, idx);
133593 }
133594
133595 static bool AddsNulls() {
133596 return true;
133597 }
133598};
133599
133600struct BinaryExecutor {
133601#ifndef DUCKDB_SMALLER_BINARY
133602 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE, class OPWRAPPER, class OP, class FUNC,
133603 bool LEFT_CONSTANT, bool RIGHT_CONSTANT>
133604 static void ExecuteFlatLoop(const LEFT_TYPE *__restrict ldata, const RIGHT_TYPE *__restrict rdata,
133605 RESULT_TYPE *__restrict result_data, idx_t count, ValidityMask &mask, FUNC fun) {
133606 if (!LEFT_CONSTANT) {
133607 ASSERT_RESTRICT(ldata, ldata + count, result_data, result_data + count);
133608 }
133609 if (!RIGHT_CONSTANT) {
133610 ASSERT_RESTRICT(rdata, rdata + count, result_data, result_data + count);
133611 }
133612
133613 if (!
mask.AllValid()) {
133614 idx_t base_idx = 0;
133615 auto entry_count = ValidityMask::EntryCount(count);
133616 for (idx_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
133617 auto validity_entry =
mask.GetValidityEntry(entry_idx);
133618 idx_t next = MinValue<idx_t>(base_idx + ValidityMask::BITS_PER_VALUE, count);
133619 if (ValidityMask::AllValid(validity_entry)) {
133620
133621 for (; base_idx < next; base_idx++) {
133622 auto lentry = ldata[LEFT_CONSTANT ? 0 : base_idx];
133623 auto rentry = rdata[RIGHT_CONSTANT ? 0 : base_idx];
133624 result_data[base_idx] =
133625 OPWRAPPER::template Operation<FUNC, OP, LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE>(
133626 fun, lentry, rentry, mask, base_idx);
133627 }
133628 } else if (ValidityMask::NoneValid(validity_entry)) {
133629
133630 base_idx = next;
133631 continue;
133632 } else {
133633
133634 idx_t start = base_idx;
133635 for (; base_idx < next; base_idx++) {
133636 if (ValidityMask::RowIsValid(validity_entry, base_idx - start)) {
133637 auto lentry = ldata[LEFT_CONSTANT ? 0 : base_idx];
133638 auto rentry = rdata[RIGHT_CONSTANT ? 0 : base_idx];
133639 result_data[base_idx] =
133640 OPWRAPPER::template Operation<FUNC, OP, LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE>(
133641 fun, lentry, rentry, mask, base_idx);
133642 }
133643 }
133644 }
133645 }
133646 } else {
133647 for (idx_t i = 0; i < count; i++) {
133648 auto lentry = ldata[LEFT_CONSTANT ? 0 : i];
133649 auto rentry = rdata[RIGHT_CONSTANT ? 0 : i];
133650 result_data[i] = OPWRAPPER::template Operation<FUNC, OP, LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE>(
133651 fun, lentry, rentry, mask, i);
133652 }
133653 }
133654 }
133655#endif
133656
133657 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE, class OPWRAPPER, class OP, class FUNC>
133658 static void ExecuteConstant(Vector &left, Vector &right, Vector &result, FUNC fun) {
133659 result.SetVectorType(VectorType::CONSTANT_VECTOR);
133660
133661 auto ldata = ConstantVector::GetData<LEFT_TYPE>(left);
133662 auto rdata = ConstantVector::GetData<RIGHT_TYPE>(right);
133663 auto result_data = ConstantVector::GetData<RESULT_TYPE>(result);
133664
133665 if (ConstantVector::IsNull(left) || ConstantVector::IsNull(right)) {
133666 ConstantVector::SetNull(result, true);
133667 return;
133668 }
133669 *result_data = OPWRAPPER::template Operation<FUNC, OP, LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE>(
133670 fun, *ldata, *rdata, ConstantVector::Validity(result), 0);
133671 }
133672
133673#ifndef DUCKDB_SMALLER_BINARY
133674 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE, class OPWRAPPER, class OP, class FUNC,
133675 bool LEFT_CONSTANT, bool RIGHT_CONSTANT>
133676 static void ExecuteFlat(Vector &left, Vector &right, Vector &result, idx_t count, FUNC fun) {
133677 auto ldata = FlatVector::GetData<LEFT_TYPE>(left);
133678 auto rdata = FlatVector::GetData<RIGHT_TYPE>(right);
133679
133680 if ((LEFT_CONSTANT && ConstantVector::IsNull(left)) || (RIGHT_CONSTANT && ConstantVector::IsNull(right))) {
133681
133682 result.SetVectorType(VectorType::CONSTANT_VECTOR);
133683 ConstantVector::SetNull(result, true);
133684 return;
133685 }
133686
133687 result.SetVectorType(VectorType::FLAT_VECTOR);
133688 auto result_data = FlatVector::GetData<RESULT_TYPE>(result);
133689 auto &result_validity = FlatVector::Validity(result);
133690 if (LEFT_CONSTANT) {
133691 if (OPWRAPPER::AddsNulls()) {
133692 result_validity.Copy(FlatVector::Validity(right), count);
133693 } else {
133694 FlatVector::SetValidity(result, FlatVector::Validity(right));
133695 }
133696 } else if (RIGHT_CONSTANT) {
133697 if (OPWRAPPER::AddsNulls()) {
133698 result_validity.Copy(FlatVector::Validity(left), count);
133699 } else {
133700 FlatVector::SetValidity(result, FlatVector::Validity(left));
133701 }
133702 } else {
133703 if (OPWRAPPER::AddsNulls()) {
133704 result_validity.Copy(FlatVector::Validity(left), count);
133705 if (result_validity.AllValid()) {
133706 result_validity.Copy(FlatVector::Validity(right), count);
133707 } else {
133708 result_validity.Combine(FlatVector::Validity(right), count);
133709 }
133710 } else {
133711 FlatVector::SetValidity(result, FlatVector::Validity(left));
133712 result_validity.Combine(FlatVector::Validity(right), count);
133713 }
133714 }
133715 ExecuteFlatLoop<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, OPWRAPPER, OP, FUNC, LEFT_CONSTANT, RIGHT_CONSTANT>(
133716 ldata, rdata, result_data, count, result_validity, fun);
133717 }
133718#endif
133719
133720 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE, class OPWRAPPER, class OP, class FUNC>
133721 static void ExecuteGenericLoop(const LEFT_TYPE *__restrict ldata, const RIGHT_TYPE *__restrict rdata,
133722 RESULT_TYPE *__restrict result_data, const SelectionVector *__restrict lsel,
133723 const SelectionVector *__restrict rsel, idx_t count, ValidityMask &lvalidity,
133724 ValidityMask &rvalidity, ValidityMask &result_validity, FUNC fun) {
133725 if (!lvalidity.AllValid() || !rvalidity.AllValid()) {
133726 for (idx_t i = 0; i < count; i++) {
133727 auto lindex = lsel->get_index(i);
133728 auto rindex = rsel->get_index(i);
133729 if (lvalidity.RowIsValid(lindex) && rvalidity.RowIsValid(rindex)) {
133730 auto lentry = ldata[lindex];
133731 auto rentry = rdata[rindex];
133732 result_data[i] = OPWRAPPER::template Operation<FUNC, OP, LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE>(
133733 fun, lentry, rentry, result_validity, i);
133734 } else {
133735 result_validity.SetInvalid(i);
133736 }
133737 }
133738 } else {
133739 for (idx_t i = 0; i < count; i++) {
133740 auto lentry = ldata[lsel->get_index(i)];
133741 auto rentry = rdata[rsel->get_index(i)];
133742 result_data[i] = OPWRAPPER::template Operation<FUNC, OP, LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE>(
133743 fun, lentry, rentry, result_validity, i);
133744 }
133745 }
133746 }
133747
133748 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE, class OPWRAPPER, class OP, class FUNC>
133749 static void ExecuteGeneric(Vector &left, Vector &right, Vector &result, idx_t count, FUNC fun) {
133750 UnifiedVectorFormat ldata, rdata;
133751
133752 left.ToUnifiedFormat(count, ldata);
133753 right.ToUnifiedFormat(count, rdata);
133754
133755 result.SetVectorType(VectorType::FLAT_VECTOR);
133756 auto result_data = FlatVector::GetData<RESULT_TYPE>(result);
133757 ExecuteGenericLoop<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, OPWRAPPER, OP, FUNC>(
133758 UnifiedVectorFormat::GetData<LEFT_TYPE>(ldata), UnifiedVectorFormat::GetData<RIGHT_TYPE>(rdata),
133759 result_data, ldata.sel, rdata.sel, count, ldata.validity, rdata.validity, FlatVector::Validity(result),
133760 fun);
133761 }
133762
133763 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE, class OPWRAPPER, class OP, class FUNC>
133764 static void ExecuteSwitch(Vector &left, Vector &right, Vector &result, idx_t count, FUNC fun) {
133765 auto left_vector_type = left.GetVectorType();
133766 auto right_vector_type = right.GetVectorType();
133767 if (left_vector_type == VectorType::CONSTANT_VECTOR && right_vector_type == VectorType::CONSTANT_VECTOR) {
133768 ExecuteConstant<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, OPWRAPPER, OP, FUNC>(left, right, result, fun);
133769#ifndef DUCKDB_SMALLER_BINARY
133770 } else if (left_vector_type == VectorType::FLAT_VECTOR && right_vector_type == VectorType::CONSTANT_VECTOR) {
133771 ExecuteFlat<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, OPWRAPPER, OP, FUNC, false, true>(left, right, result,
133772 count, fun);
133773 } else if (left_vector_type == VectorType::CONSTANT_VECTOR && right_vector_type == VectorType::FLAT_VECTOR) {
133774 ExecuteFlat<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, OPWRAPPER, OP, FUNC, true, false>(left, right, result,
133775 count, fun);
133776 } else if (left_vector_type == VectorType::FLAT_VECTOR && right_vector_type == VectorType::FLAT_VECTOR) {
133777 ExecuteFlat<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, OPWRAPPER, OP, FUNC, false, false>(left, right, result,
133778 count, fun);
133779#endif
133780 } else {
133781 ExecuteGeneric<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, OPWRAPPER, OP, FUNC>(left, right, result, count, fun);
133782 }
133783 }
133784
133785public:
133786 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE,
133787 class FUNC = std::function<RESULT_TYPE(LEFT_TYPE, RIGHT_TYPE)>>
133788 static void Execute(Vector &left, Vector &right, Vector &result, idx_t count, FUNC fun) {
133789 ExecuteSwitch<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, BinaryLambdaWrapper, bool, FUNC>(left, right, result, count,
133790 fun);
133791 }
133792
133793 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE, class OP,
133794 class OPWRAPPER = BinarySingleArgumentOperatorWrapper>
133795 static void Execute(Vector &left, Vector &right, Vector &result, idx_t count) {
133796 ExecuteSwitch<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, OPWRAPPER, OP, bool>(left, right, result, count, false);
133797 }
133798
133799 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE, class OP>
133800 static void ExecuteStandard(Vector &left, Vector &right, Vector &result, idx_t count) {
133801 ExecuteSwitch<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, BinaryStandardOperatorWrapper, OP, bool>(left, right, result,
133802 count, false);
133803 }
133804
133805 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE,
133806 class FUNC = std::function<RESULT_TYPE(LEFT_TYPE, RIGHT_TYPE, ValidityMask &, idx_t)>>
133807 static void ExecuteWithNulls(Vector &left, Vector &right, Vector &result, idx_t count, FUNC fun) {
133808 ExecuteSwitch<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, BinaryLambdaWrapperWithNulls, bool, FUNC>(left, right, result,
133809 count, fun);
133810 }
133811
133812public:
133813 template <class LEFT_TYPE, class RIGHT_TYPE, class OP>
133814 static idx_t SelectConstant(Vector &left, Vector &right,
const SelectionVector *sel, idx_t count,
133815 SelectionVector *true_sel, SelectionVector *false_sel) {
133816 auto ldata = ConstantVector::GetData<LEFT_TYPE>(left);
133817 auto rdata = ConstantVector::GetData<RIGHT_TYPE>(right);
133818
133819
133820
133821 if (ConstantVector::IsNull(left) || ConstantVector::IsNull(right) || !OP::Operation(*ldata, *rdata)) {
133822 if (false_sel) {
133823 for (idx_t i = 0; i < count; i++) {
133824 false_sel->set_index(i, sel->get_index(i));
133825 }
133826 }
133827 return 0;
133828 } else {
133829 if (true_sel) {
133830 for (idx_t i = 0; i < count; i++) {
133831 true_sel->set_index(i, sel->get_index(i));
133832 }
133833 }
133834 return count;
133835 }
133836 }
133837
133838#ifndef DUCKDB_SMALLER_BINARY
133839 template <class LEFT_TYPE, class RIGHT_TYPE, class OP, bool LEFT_CONSTANT, bool RIGHT_CONSTANT, bool HAS_TRUE_SEL,
133840 bool HAS_FALSE_SEL>
133841 static inline idx_t SelectFlatLoop(
const LEFT_TYPE *__restrict ldata,
const RIGHT_TYPE *__restrict rdata,
133842 const SelectionVector *sel, idx_t count, ValidityMask &validity_mask,
133843 SelectionVector *true_sel, SelectionVector *false_sel) {
133844 idx_t true_count = 0, false_count = 0;
133845 idx_t base_idx = 0;
133846 auto entry_count = ValidityMask::EntryCount(count);
133847 for (idx_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
133848 auto validity_entry = validity_mask.GetValidityEntry(entry_idx);
133849 idx_t next = MinValue<idx_t>(base_idx + ValidityMask::BITS_PER_VALUE, count);
133850 if (ValidityMask::AllValid(validity_entry)) {
133851
133852 for (; base_idx < next; base_idx++) {
133853 idx_t result_idx = sel->get_index(base_idx);
133854 idx_t lidx = LEFT_CONSTANT ? 0 : base_idx;
133855 idx_t ridx = RIGHT_CONSTANT ? 0 : base_idx;
133856 bool comparison_result = OP::Operation(ldata[lidx], rdata[ridx]);
133857 if (HAS_TRUE_SEL) {
133858 true_sel->set_index(true_count, result_idx);
133859 true_count += comparison_result;
133860 }
133861 if (HAS_FALSE_SEL) {
133862 false_sel->set_index(false_count, result_idx);
133863 false_count += !comparison_result;
133864 }
133865 }
133866 } else if (ValidityMask::NoneValid(validity_entry)) {
133867
133868 if (HAS_FALSE_SEL) {
133869 for (; base_idx < next; base_idx++) {
133870 idx_t result_idx = sel->get_index(base_idx);
133871 false_sel->set_index(false_count, result_idx);
133872 false_count++;
133873 }
133874 }
133875 base_idx = next;
133876 continue;
133877 } else {
133878
133879 idx_t start = base_idx;
133880 for (; base_idx < next; base_idx++) {
133881 idx_t result_idx = sel->get_index(base_idx);
133882 idx_t lidx = LEFT_CONSTANT ? 0 : base_idx;
133883 idx_t ridx = RIGHT_CONSTANT ? 0 : base_idx;
133884 bool comparison_result = ValidityMask::RowIsValid(validity_entry, base_idx - start) &&
133885 OP::Operation(ldata[lidx], rdata[ridx]);
133886 if (HAS_TRUE_SEL) {
133887 true_sel->set_index(true_count, result_idx);
133888 true_count += comparison_result;
133889 }
133890 if (HAS_FALSE_SEL) {
133891 false_sel->set_index(false_count, result_idx);
133892 false_count += !comparison_result;
133893 }
133894 }
133895 }
133896 }
133897 if (HAS_TRUE_SEL) {
133898 return true_count;
133899 } else {
133900 return count - false_count;
133901 }
133902 }
133903
133904 template <class LEFT_TYPE, class RIGHT_TYPE, class OP, bool LEFT_CONSTANT, bool RIGHT_CONSTANT>
133905 static inline idx_t SelectFlatLoopSwitch(
const LEFT_TYPE *__restrict ldata,
const RIGHT_TYPE *__restrict rdata,
133906 const SelectionVector *sel, idx_t count, ValidityMask &mask,
133907 SelectionVector *true_sel, SelectionVector *false_sel) {
133908 if (true_sel && false_sel) {
133909 return SelectFlatLoop<LEFT_TYPE, RIGHT_TYPE, OP, LEFT_CONSTANT, RIGHT_CONSTANT, true, true>(
133910 ldata, rdata, sel, count, mask, true_sel, false_sel);
133911 } else if (true_sel) {
133912 return SelectFlatLoop<LEFT_TYPE, RIGHT_TYPE, OP, LEFT_CONSTANT, RIGHT_CONSTANT, true, false>(
133913 ldata, rdata, sel, count, mask, true_sel, false_sel);
133914 } else {
133915 D_ASSERT(false_sel);
133916 return SelectFlatLoop<LEFT_TYPE, RIGHT_TYPE, OP, LEFT_CONSTANT, RIGHT_CONSTANT, false, true>(
133917 ldata, rdata, sel, count, mask, true_sel, false_sel);
133918 }
133919 }
133920
133921 template <class LEFT_TYPE, class RIGHT_TYPE, class OP, bool LEFT_CONSTANT, bool RIGHT_CONSTANT>
133922 static idx_t SelectFlat(Vector &left, Vector &right,
const SelectionVector *sel, idx_t count,
133923 SelectionVector *true_sel, SelectionVector *false_sel) {
133924 auto ldata = FlatVector::GetData<LEFT_TYPE>(left);
133925 auto rdata = FlatVector::GetData<RIGHT_TYPE>(right);
133926
133927 if (LEFT_CONSTANT && ConstantVector::IsNull(left)) {
133928 if (false_sel) {
133929 for (idx_t i = 0; i < count; i++) {
133930 false_sel->set_index(i, sel->get_index(i));
133931 }
133932 }
133933 return 0;
133934 }
133935 if (RIGHT_CONSTANT && ConstantVector::IsNull(right)) {
133936 if (false_sel) {
133937 for (idx_t i = 0; i < count; i++) {
133938 false_sel->set_index(i, sel->get_index(i));
133939 }
133940 }
133941 return 0;
133942 }
133943
133944 if (LEFT_CONSTANT) {
133945 return SelectFlatLoopSwitch<LEFT_TYPE, RIGHT_TYPE, OP, LEFT_CONSTANT, RIGHT_CONSTANT>(
133946 ldata, rdata, sel, count, FlatVector::Validity(right), true_sel, false_sel);
133947 } else if (RIGHT_CONSTANT) {
133948 return SelectFlatLoopSwitch<LEFT_TYPE, RIGHT_TYPE, OP, LEFT_CONSTANT, RIGHT_CONSTANT>(
133949 ldata, rdata, sel, count, FlatVector::Validity(left), true_sel, false_sel);
133950 } else {
133951 ValidityMask combined_mask = FlatVector::Validity(left);
133952 combined_mask.Combine(FlatVector::Validity(right), count);
133953 return SelectFlatLoopSwitch<LEFT_TYPE, RIGHT_TYPE, OP, LEFT_CONSTANT, RIGHT_CONSTANT>(
133954 ldata, rdata, sel, count, combined_mask, true_sel, false_sel);
133955 }
133956 }
133957#endif
133958
133959#ifndef DUCKDB_SMALLER_BINARY
133960 template <class LEFT_TYPE, class RIGHT_TYPE, class OP, bool NO_NULL, bool HAS_TRUE_SEL, bool HAS_FALSE_SEL>
133961#else
133962 template <class LEFT_TYPE, class RIGHT_TYPE, class OP>
133963#endif
133964 static inline idx_t
133965 SelectGenericLoop(const LEFT_TYPE *__restrict ldata, const RIGHT_TYPE *__restrict rdata,
133966 const SelectionVector *__restrict lsel, const SelectionVector *__restrict rsel,
133967 const SelectionVector *__restrict result_sel, idx_t count, ValidityMask &lvalidity,
133968 ValidityMask &rvalidity, SelectionVector *true_sel, SelectionVector *false_sel) {
133969 idx_t true_count = 0, false_count = 0;
133970#ifdef DUCKDB_SMALLER_BINARY
133971 const bool HAS_TRUE_SEL = true_sel;
133972 const bool HAS_FALSE_SEL = false_sel;
133973 const bool NO_NULL = false;
133974#endif
133975 for (idx_t i = 0; i < count; i++) {
133976 auto result_idx = result_sel->get_index(i);
133977 auto lindex = lsel->get_index(i);
133978 auto rindex = rsel->get_index(i);
133979 if ((NO_NULL || (lvalidity.RowIsValid(lindex) && rvalidity.RowIsValid(rindex))) &&
133980 OP::Operation(ldata[lindex], rdata[rindex])) {
133981 if (HAS_TRUE_SEL) {
133982 true_sel->set_index(true_count++, result_idx);
133983 }
133984 } else {
133985 if (HAS_FALSE_SEL) {
133986 false_sel->set_index(false_count++, result_idx);
133987 }
133988 }
133989 }
133990 if (HAS_TRUE_SEL) {
133991 return true_count;
133992 } else {
133993 return count - false_count;
133994 }
133995 }
133996
133997#ifndef DUCKDB_SMALLER_BINARY
133998 template <class LEFT_TYPE, class RIGHT_TYPE, class OP, bool NO_NULL>
133999 static inline idx_t
134000 SelectGenericLoopSelSwitch(const LEFT_TYPE *__restrict ldata, const RIGHT_TYPE *__restrict rdata,
134001 const SelectionVector *__restrict lsel, const SelectionVector *__restrict rsel,
134002 const SelectionVector *__restrict result_sel, idx_t count, ValidityMask &lvalidity,
134003 ValidityMask &rvalidity, SelectionVector *true_sel, SelectionVector *false_sel) {
134004 if (true_sel && false_sel) {
134005 return SelectGenericLoop<LEFT_TYPE, RIGHT_TYPE, OP, NO_NULL, true, true>(
134006 ldata, rdata, lsel, rsel, result_sel, count, lvalidity, rvalidity, true_sel, false_sel);
134007 } else if (true_sel) {
134008 return SelectGenericLoop<LEFT_TYPE, RIGHT_TYPE, OP, NO_NULL, true, false>(
134009 ldata, rdata, lsel, rsel, result_sel, count, lvalidity, rvalidity, true_sel, false_sel);
134010 } else {
134011 D_ASSERT(false_sel);
134012 return SelectGenericLoop<LEFT_TYPE, RIGHT_TYPE, OP, NO_NULL, false, true>(
134013 ldata, rdata, lsel, rsel, result_sel, count, lvalidity, rvalidity, true_sel, false_sel);
134014 }
134015 }
134016#endif
134017
134018 template <class LEFT_TYPE, class RIGHT_TYPE, class OP>
134019 static inline idx_t
134020 SelectGenericLoopSwitch(const LEFT_TYPE *__restrict ldata, const RIGHT_TYPE *__restrict rdata,
134021 const SelectionVector *__restrict lsel, const SelectionVector *__restrict rsel,
134022 const SelectionVector *__restrict result_sel, idx_t count, ValidityMask &lvalidity,
134023 ValidityMask &rvalidity, SelectionVector *true_sel, SelectionVector *false_sel) {
134024#ifndef DUCKDB_SMALLER_BINARY
134025 if (!lvalidity.AllValid() || !rvalidity.AllValid()) {
134026 return SelectGenericLoopSelSwitch<LEFT_TYPE, RIGHT_TYPE, OP, false>(
134027 ldata, rdata, lsel, rsel, result_sel, count, lvalidity, rvalidity, true_sel, false_sel);
134028 } else {
134029 return SelectGenericLoopSelSwitch<LEFT_TYPE, RIGHT_TYPE, OP, true>(
134030 ldata, rdata, lsel, rsel, result_sel, count, lvalidity, rvalidity, true_sel, false_sel);
134031 }
134032#else
134033 return SelectGenericLoop<LEFT_TYPE, RIGHT_TYPE, OP>(ldata, rdata, lsel, rsel, result_sel, count, lvalidity,
134034 rvalidity, true_sel, false_sel);
134035#endif
134036 }
134037
134038 template <class LEFT_TYPE, class RIGHT_TYPE, class OP>
134039 static idx_t SelectGeneric(Vector &left, Vector &right,
const SelectionVector *sel, idx_t count,
134040 SelectionVector *true_sel, SelectionVector *false_sel) {
134041 UnifiedVectorFormat ldata, rdata;
134042
134043 left.ToUnifiedFormat(count, ldata);
134044 right.ToUnifiedFormat(count, rdata);
134045
134046 return SelectGenericLoopSwitch<LEFT_TYPE, RIGHT_TYPE, OP>(
134047 UnifiedVectorFormat::GetData<LEFT_TYPE>(ldata), UnifiedVectorFormat::GetData<RIGHT_TYPE>(rdata), ldata.sel,
134048 rdata.sel, sel, count, ldata.validity, rdata.validity, true_sel, false_sel);
134049 }
134050
134051 template <class LEFT_TYPE, class RIGHT_TYPE, class OP>
134052 static idx_t Select(Vector &left, Vector &right,
const SelectionVector *sel, idx_t count, SelectionVector *true_sel,
134053 SelectionVector *false_sel) {
134054 if (!sel) {
134055 sel = FlatVector::IncrementalSelectionVector();
134056 }
134057 if (left.GetVectorType() == VectorType::CONSTANT_VECTOR &&
134058 right.GetVectorType() == VectorType::CONSTANT_VECTOR) {
134059 return SelectConstant<LEFT_TYPE, RIGHT_TYPE, OP>(left, right, sel, count, true_sel, false_sel);
134060#ifndef DUCKDB_SMALLER_BINARY
134061 } else if (left.GetVectorType() == VectorType::CONSTANT_VECTOR &&
134062 right.GetVectorType() == VectorType::FLAT_VECTOR) {
134063 return SelectFlat<LEFT_TYPE, RIGHT_TYPE, OP, true, false>(left, right, sel, count, true_sel, false_sel);
134064 } else if (left.GetVectorType() == VectorType::FLAT_VECTOR &&
134065 right.GetVectorType() == VectorType::CONSTANT_VECTOR) {
134066 return SelectFlat<LEFT_TYPE, RIGHT_TYPE, OP, false, true>(left, right, sel, count, true_sel, false_sel);
134067 } else if (left.GetVectorType() == VectorType::FLAT_VECTOR &&
134068 right.GetVectorType() == VectorType::FLAT_VECTOR) {
134069 return SelectFlat<LEFT_TYPE, RIGHT_TYPE, OP, false, false>(left, right, sel, count, true_sel, false_sel);
134070#endif
134071 } else {
134072 return SelectGeneric<LEFT_TYPE, RIGHT_TYPE, OP>(left, right, sel, count, true_sel, false_sel);
134073 }
134074 }
134075};
134076
134077}
134078
134079
134080
134081
134082
134083
134084
134085
134086
134087
134088
134089
134090
134091
134092
134093#include <functional>
134094
134095namespace duckdb {
134096
134097template <class OP>
134098struct TernaryStandardOperatorWrapper {
134099 template <class FUN, class A_TYPE, class B_TYPE, class C_TYPE, class RESULT_TYPE>
134100 static inline RESULT_TYPE Operation(FUN fun, A_TYPE a, B_TYPE b, C_TYPE c, ValidityMask &mask, idx_t idx) {
134101 return OP::template Operation<A_TYPE, B_TYPE, C_TYPE, RESULT_TYPE>(a, b, c);
134102 }
134103};
134104
134105struct TernaryLambdaWrapper {
134106 template <class FUN, class A_TYPE, class B_TYPE, class C_TYPE, class RESULT_TYPE>
134107 static inline RESULT_TYPE Operation(FUN fun, A_TYPE a, B_TYPE b, C_TYPE c, ValidityMask &mask, idx_t idx) {
134108 return fun(a, b, c);
134109 }
134110};
134111
134112struct TernaryLambdaWrapperWithNulls {
134113 template <class FUN, class A_TYPE, class B_TYPE, class C_TYPE, class RESULT_TYPE>
134114 static inline RESULT_TYPE Operation(FUN fun, A_TYPE a, B_TYPE b, C_TYPE c, ValidityMask &mask, idx_t idx) {
134115 return fun(a, b, c, mask, idx);
134116 }
134117};
134118
134119struct TernaryExecutor {
134120private:
134121 template <class A_TYPE, class B_TYPE, class C_TYPE, class RESULT_TYPE, class OPWRAPPER, class FUN>
134122 static inline void ExecuteLoop(const A_TYPE *__restrict adata, const B_TYPE *__restrict bdata,
134123 const C_TYPE *__restrict cdata, RESULT_TYPE *__restrict result_data, idx_t count,
134124 const SelectionVector &asel, const SelectionVector &bsel,
134125 const SelectionVector &csel, ValidityMask &avalidity, ValidityMask &bvalidity,
134126 ValidityMask &cvalidity, ValidityMask &result_validity, FUN fun) {
134127 if (!avalidity.AllValid() || !bvalidity.AllValid() || !cvalidity.AllValid()) {
134128 for (idx_t i = 0; i < count; i++) {
134129 auto aidx = asel.get_index(i);
134130 auto bidx = bsel.get_index(i);
134131 auto cidx = csel.get_index(i);
134132 if (avalidity.RowIsValid(aidx) && bvalidity.RowIsValid(bidx) && cvalidity.RowIsValid(cidx)) {
134133 result_data[i] = OPWRAPPER::template Operation<FUN, A_TYPE, B_TYPE, C_TYPE, RESULT_TYPE>(
134134 fun, adata[aidx], bdata[bidx], cdata[cidx], result_validity, i);
134135 } else {
134136 result_validity.SetInvalid(i);
134137 }
134138 }
134139 } else {
134140 for (idx_t i = 0; i < count; i++) {
134141 auto aidx = asel.get_index(i);
134142 auto bidx = bsel.get_index(i);
134143 auto cidx = csel.get_index(i);
134144 result_data[i] = OPWRAPPER::template Operation<FUN, A_TYPE, B_TYPE, C_TYPE, RESULT_TYPE>(
134145 fun, adata[aidx], bdata[bidx], cdata[cidx], result_validity, i);
134146 }
134147 }
134148 }
134149
134150public:
134151 template <class A_TYPE, class B_TYPE, class C_TYPE, class RESULT_TYPE, class OPWRAPPER, class FUN>
134152 static void ExecuteGeneric(Vector &a, Vector &b, Vector &c, Vector &result, idx_t count, FUN fun) {
134153 if (a.GetVectorType() == VectorType::CONSTANT_VECTOR && b.GetVectorType() == VectorType::CONSTANT_VECTOR &&
134154 c.GetVectorType() == VectorType::CONSTANT_VECTOR) {
134155 result.SetVectorType(VectorType::CONSTANT_VECTOR);
134156 if (ConstantVector::IsNull(a) || ConstantVector::IsNull(b) || ConstantVector::IsNull(c)) {
134157 ConstantVector::SetNull(result, true);
134158 } else {
134159 auto adata = ConstantVector::GetData<A_TYPE>(a);
134160 auto bdata = ConstantVector::GetData<B_TYPE>(b);
134161 auto cdata = ConstantVector::GetData<C_TYPE>(c);
134162 auto result_data = ConstantVector::GetData<RESULT_TYPE>(result);
134163 auto &result_validity = ConstantVector::Validity(result);
134164 result_data[0] = OPWRAPPER::template Operation<FUN, A_TYPE, B_TYPE, C_TYPE, RESULT_TYPE>(
134165 fun, adata[0], bdata[0], cdata[0], result_validity, 0);
134166 }
134167 } else {
134168 result.SetVectorType(VectorType::FLAT_VECTOR);
134169
134170 UnifiedVectorFormat adata, bdata, cdata;
134171 a.ToUnifiedFormat(count, adata);
134172 b.ToUnifiedFormat(count, bdata);
134173 c.ToUnifiedFormat(count, cdata);
134174
134175 ExecuteLoop<A_TYPE, B_TYPE, C_TYPE, RESULT_TYPE, OPWRAPPER>(
134176 UnifiedVectorFormat::GetData<A_TYPE>(adata), UnifiedVectorFormat::GetData<B_TYPE>(bdata),
134177 UnifiedVectorFormat::GetData<C_TYPE>(cdata), FlatVector::GetData<RESULT_TYPE>(result), count,
134178 *adata.sel, *bdata.sel, *cdata.sel, adata.validity, bdata.validity, cdata.validity,
134179 FlatVector::Validity(result), fun);
134180 }
134181 }
134182
134183 template <class A_TYPE, class B_TYPE, class C_TYPE, class RESULT_TYPE,
134184 class FUN = std::function<RESULT_TYPE(A_TYPE, B_TYPE, C_TYPE)>>
134185 static void Execute(Vector &a, Vector &b, Vector &c, Vector &result, idx_t count, FUN fun) {
134186 ExecuteGeneric<A_TYPE, B_TYPE, C_TYPE, RESULT_TYPE, TernaryLambdaWrapper, FUN>(a, b, c, result, count, fun);
134187 }
134188
134189 template <class A_TYPE, class B_TYPE, class C_TYPE, class RESULT_TYPE, class OP>
134190 static void ExecuteStandard(Vector &a, Vector &b, Vector &c, Vector &result, idx_t count) {
134191 ExecuteGeneric<A_TYPE, B_TYPE, C_TYPE, RESULT_TYPE, TernaryStandardOperatorWrapper<OP>, bool>(a, b, c, result,
134192 count, false);
134193 }
134194
134195 template <class A_TYPE, class B_TYPE, class C_TYPE, class RESULT_TYPE,
134196 class FUN = std::function<RESULT_TYPE(A_TYPE, B_TYPE, C_TYPE, ValidityMask &, idx_t)>>
134197 static void ExecuteWithNulls(Vector &a, Vector &b, Vector &c, Vector &result, idx_t count, FUN fun) {
134198 ExecuteGeneric<A_TYPE, B_TYPE, C_TYPE, RESULT_TYPE, TernaryLambdaWrapperWithNulls, FUN>(a, b, c, result, count,
134199 fun);
134200 }
134201
134202private:
134203 template <class A_TYPE, class B_TYPE, class C_TYPE, class OP, bool NO_NULL, bool HAS_TRUE_SEL, bool HAS_FALSE_SEL>
134204 static inline idx_t SelectLoop(
const A_TYPE *__restrict adata,
const B_TYPE *__restrict bdata,
134205 const C_TYPE *__restrict cdata, const SelectionVector *result_sel, idx_t count,
134206 const SelectionVector &asel, const SelectionVector &bsel,
134207 const SelectionVector &csel, ValidityMask &avalidity, ValidityMask &bvalidity,
134208 ValidityMask &cvalidity, SelectionVector *true_sel, SelectionVector *false_sel) {
134209 idx_t true_count = 0, false_count = 0;
134210 for (idx_t i = 0; i < count; i++) {
134211 auto result_idx = result_sel->get_index(i);
134212 auto aidx = asel.get_index(i);
134213 auto bidx = bsel.get_index(i);
134214 auto cidx = csel.get_index(i);
134215 bool comparison_result =
134216 (NO_NULL || (avalidity.RowIsValid(aidx) && bvalidity.RowIsValid(bidx) && cvalidity.RowIsValid(cidx))) &&
134217 OP::Operation(adata[aidx], bdata[bidx], cdata[cidx]);
134218 if (HAS_TRUE_SEL) {
134219 true_sel->set_index(true_count, result_idx);
134220 true_count += comparison_result;
134221 }
134222 if (HAS_FALSE_SEL) {
134223 false_sel->set_index(false_count, result_idx);
134224 false_count += !comparison_result;
134225 }
134226 }
134227 if (HAS_TRUE_SEL) {
134228 return true_count;
134229 } else {
134230 return count - false_count;
134231 }
134232 }
134233
134234 template <class A_TYPE, class B_TYPE, class C_TYPE, class OP, bool NO_NULL>
134235 static inline idx_t SelectLoopSelSwitch(UnifiedVectorFormat &adata, UnifiedVectorFormat &bdata,
134236 UnifiedVectorFormat &cdata, const SelectionVector *sel, idx_t count,
134237 SelectionVector *true_sel, SelectionVector *false_sel) {
134238 if (true_sel && false_sel) {
134239 return SelectLoop<A_TYPE, B_TYPE, C_TYPE, OP, NO_NULL, true, true>(
134240 UnifiedVectorFormat::GetData<A_TYPE>(adata), UnifiedVectorFormat::GetData<B_TYPE>(bdata),
134241 UnifiedVectorFormat::GetData<C_TYPE>(cdata), sel, count, *adata.sel, *bdata.sel, *cdata.sel,
134242 adata.validity, bdata.validity, cdata.validity, true_sel, false_sel);
134243 } else if (true_sel) {
134244 return SelectLoop<A_TYPE, B_TYPE, C_TYPE, OP, NO_NULL, true, false>(
134245 UnifiedVectorFormat::GetData<A_TYPE>(adata), UnifiedVectorFormat::GetData<B_TYPE>(bdata),
134246 UnifiedVectorFormat::GetData<C_TYPE>(cdata), sel, count, *adata.sel, *bdata.sel, *cdata.sel,
134247 adata.validity, bdata.validity, cdata.validity, true_sel, false_sel);
134248 } else {
134249 D_ASSERT(false_sel);
134250 return SelectLoop<A_TYPE, B_TYPE, C_TYPE, OP, NO_NULL, false, true>(
134251 UnifiedVectorFormat::GetData<A_TYPE>(adata), UnifiedVectorFormat::GetData<B_TYPE>(bdata),
134252 UnifiedVectorFormat::GetData<C_TYPE>(cdata), sel, count, *adata.sel, *bdata.sel, *cdata.sel,
134253 adata.validity, bdata.validity, cdata.validity, true_sel, false_sel);
134254 }
134255 }
134256
134257 template <class A_TYPE, class B_TYPE, class C_TYPE, class OP>
134258 static inline idx_t SelectLoopSwitch(UnifiedVectorFormat &adata, UnifiedVectorFormat &bdata,
134259 UnifiedVectorFormat &cdata, const SelectionVector *sel, idx_t count,
134260 SelectionVector *true_sel, SelectionVector *false_sel) {
134261 if (!adata.validity.AllValid() || !bdata.validity.AllValid() || !cdata.validity.AllValid()) {
134262 return SelectLoopSelSwitch<A_TYPE, B_TYPE, C_TYPE, OP, false>(adata, bdata, cdata, sel, count, true_sel,
134263 false_sel);
134264 } else {
134265 return SelectLoopSelSwitch<A_TYPE, B_TYPE, C_TYPE, OP, true>(adata, bdata, cdata, sel, count, true_sel,
134266 false_sel);
134267 }
134268 }
134269
134270public:
134271 template <class A_TYPE, class B_TYPE, class C_TYPE, class OP>
134272 static idx_t Select(Vector &a, Vector &b, Vector &c,
const SelectionVector *sel, idx_t count,
134273 SelectionVector *true_sel, SelectionVector *false_sel) {
134274 if (!sel) {
134275 sel = FlatVector::IncrementalSelectionVector();
134276 }
134277 UnifiedVectorFormat adata, bdata, cdata;
134278 a.ToUnifiedFormat(count, adata);
134279 b.ToUnifiedFormat(count, bdata);
134280 c.ToUnifiedFormat(count, cdata);
134281
134282 return SelectLoopSwitch<A_TYPE, B_TYPE, C_TYPE, OP>(adata, bdata, cdata, sel, count, true_sel, false_sel);
134283 }
134284};
134285
134286}
134287
134288
134289
134290
134291
134292
134293
134294
134295
134296
134297
134298
134299
134300
134301
134302
134303
134304
134305
134306
134307
134308
134309
134310
134311
134312
134313namespace duckdb {
134314
134317
134318}
134319
134320
134321#include <functional>
134322
134323namespace duckdb {
134324
134325struct UnaryOperatorWrapper {
134326 template <class OP, class INPUT_TYPE, class RESULT_TYPE>
134327 static inline RESULT_TYPE Operation(INPUT_TYPE input, ValidityMask &mask, idx_t idx, void *dataptr) {
134328 return OP::template Operation<INPUT_TYPE, RESULT_TYPE>(input);
134329 }
134330};
134331
134332struct UnaryLambdaWrapper {
134333 template <class FUNC, class INPUT_TYPE, class RESULT_TYPE>
134334 static inline RESULT_TYPE Operation(INPUT_TYPE input, ValidityMask &mask, idx_t idx, void *dataptr) {
134335 auto fun = (FUNC *)dataptr;
134336 return (*fun)(input);
134337 }
134338};
134339
134340struct GenericUnaryWrapper {
134341 template <class OP, class INPUT_TYPE, class RESULT_TYPE>
134342 static inline RESULT_TYPE Operation(INPUT_TYPE input, ValidityMask &mask, idx_t idx, void *dataptr) {
134343 return OP::template Operation<INPUT_TYPE, RESULT_TYPE>(input, mask, idx, dataptr);
134344 }
134345};
134346
134347struct UnaryLambdaWrapperWithNulls {
134348 template <class FUNC, class INPUT_TYPE, class RESULT_TYPE>
134349 static inline RESULT_TYPE Operation(INPUT_TYPE input, ValidityMask &mask, idx_t idx, void *dataptr) {
134350 auto fun = (FUNC *)dataptr;
134351 return (*fun)(input,
mask, idx);
134352 }
134353};
134354
134355template <class OP>
134356struct UnaryStringOperator {
134357 template <class INPUT_TYPE, class RESULT_TYPE>
134358 static RESULT_TYPE Operation(INPUT_TYPE input, ValidityMask &mask, idx_t idx, void *dataptr) {
134359 auto vector = reinterpret_cast<Vector *>(dataptr);
134360 return OP::template Operation<INPUT_TYPE, RESULT_TYPE>(input, *vector);
134361 }
134362};
134363
134364struct UnaryExecutor {
134365private:
134366 template <class INPUT_TYPE, class RESULT_TYPE, class OPWRAPPER, class OP>
134367 static inline void ExecuteLoop(const INPUT_TYPE *__restrict ldata, RESULT_TYPE *__restrict result_data, idx_t count,
134368 const SelectionVector *__restrict sel_vector, ValidityMask &mask,
134369 ValidityMask &result_mask, void *dataptr, bool adds_nulls) {
134370#ifdef DEBUG
134371
134372 idx_t max_index = 0;
134373 for (idx_t i = 0; i < count; i++) {
134374 auto idx = sel_vector->get_index(i);
134375 max_index = MaxValue(max_index, idx);
134376 }
134377 ASSERT_RESTRICT(ldata, ldata + max_index, result_data, result_data + count);
134378#endif
134379
134380 if (!
mask.AllValid()) {
134381 for (idx_t i = 0; i < count; i++) {
134382 auto idx = sel_vector->get_index(i);
134383 if (
mask.RowIsValidUnsafe(idx)) {
134384 result_data[i] =
134385 OPWRAPPER::template Operation<OP, INPUT_TYPE, RESULT_TYPE>(ldata[idx], result_mask, i, dataptr);
134386 } else {
134387 result_mask.SetInvalid(i);
134388 }
134389 }
134390 } else {
134391 for (idx_t i = 0; i < count; i++) {
134392 auto idx = sel_vector->get_index(i);
134393 result_data[i] =
134394 OPWRAPPER::template Operation<OP, INPUT_TYPE, RESULT_TYPE>(ldata[idx], result_mask, i, dataptr);
134395 }
134396 }
134397 }
134398
134399#ifndef DUCKDB_SMALLER_BINARY
134400 template <class INPUT_TYPE, class RESULT_TYPE, class OPWRAPPER, class OP>
134401 static inline void ExecuteFlat(const INPUT_TYPE *__restrict ldata, RESULT_TYPE *__restrict result_data, idx_t count,
134402 ValidityMask &mask, ValidityMask &result_mask, void *dataptr, bool adds_nulls) {
134403 ASSERT_RESTRICT(ldata, ldata + count, result_data, result_data + count);
134404
134405 if (!
mask.AllValid()) {
134406 if (!adds_nulls) {
134407 result_mask.Initialize(mask);
134408 } else {
134409 result_mask.Copy(mask, count);
134410 }
134411 idx_t base_idx = 0;
134412 auto entry_count = ValidityMask::EntryCount(count);
134413 for (idx_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
134414 auto validity_entry =
mask.GetValidityEntry(entry_idx);
134415 idx_t next = MinValue<idx_t>(base_idx + ValidityMask::BITS_PER_VALUE, count);
134416 if (ValidityMask::AllValid(validity_entry)) {
134417
134418 for (; base_idx < next; base_idx++) {
134419 result_data[base_idx] = OPWRAPPER::template Operation<OP, INPUT_TYPE, RESULT_TYPE>(
134420 ldata[base_idx], result_mask, base_idx, dataptr);
134421 }
134422 } else if (ValidityMask::NoneValid(validity_entry)) {
134423
134424 base_idx = next;
134425 continue;
134426 } else {
134427
134428 idx_t start = base_idx;
134429 for (; base_idx < next; base_idx++) {
134430 if (ValidityMask::RowIsValid(validity_entry, base_idx - start)) {
134431 D_ASSERT(
mask.RowIsValid(base_idx));
134432 result_data[base_idx] = OPWRAPPER::template Operation<OP, INPUT_TYPE, RESULT_TYPE>(
134433 ldata[base_idx], result_mask, base_idx, dataptr);
134434 }
134435 }
134436 }
134437 }
134438 } else {
134439 for (idx_t i = 0; i < count; i++) {
134440 result_data[i] =
134441 OPWRAPPER::template Operation<OP, INPUT_TYPE, RESULT_TYPE>(ldata[i], result_mask, i, dataptr);
134442 }
134443 }
134444 }
134445#endif
134446
134447 template <class INPUT_TYPE, class RESULT_TYPE, class OPWRAPPER, class OP>
134448 static inline void ExecuteStandard(Vector &input, Vector &result, idx_t count, void *dataptr, bool adds_nulls,
134449 FunctionErrors errors = FunctionErrors::CAN_THROW_RUNTIME_ERROR) {
134450 switch (input.GetVectorType()) {
134451 case VectorType::CONSTANT_VECTOR: {
134452 result.SetVectorType(VectorType::CONSTANT_VECTOR);
134453 auto result_data = ConstantVector::GetData<RESULT_TYPE>(result);
134454 auto ldata = ConstantVector::GetData<INPUT_TYPE>(input);
134455
134456 if (ConstantVector::IsNull(input)) {
134457 ConstantVector::SetNull(result, true);
134458 } else {
134459 ConstantVector::SetNull(result, false);
134460 *result_data = OPWRAPPER::template Operation<OP, INPUT_TYPE, RESULT_TYPE>(
134461 *ldata, ConstantVector::Validity(result), 0, dataptr);
134462 }
134463 break;
134464 }
134465#ifndef DUCKDB_SMALLER_BINARY
134466 case VectorType::FLAT_VECTOR: {
134467 result.SetVectorType(VectorType::FLAT_VECTOR);
134468 auto result_data = FlatVector::GetData<RESULT_TYPE>(result);
134469 auto ldata = FlatVector::GetData<INPUT_TYPE>(input);
134470
134471 ExecuteFlat<INPUT_TYPE, RESULT_TYPE, OPWRAPPER, OP>(ldata, result_data, count, FlatVector::Validity(input),
134472 FlatVector::Validity(result), dataptr, adds_nulls);
134473 break;
134474 }
134475 case VectorType::DICTIONARY_VECTOR: {
134476
134477
134478
134479
134480 if (errors == FunctionErrors::CANNOT_ERROR) {
134481 static constexpr idx_t DICTIONARY_THRESHOLD = 2;
134482 auto dict_size = DictionaryVector::DictionarySize(input);
134483 if (dict_size.IsValid() && dict_size.GetIndex() * DICTIONARY_THRESHOLD <= count) {
134484
134485
134486 auto &dictionary_values = DictionaryVector::Child(input);
134487 if (dictionary_values.GetVectorType() == VectorType::FLAT_VECTOR) {
134488
134489 auto result_data = FlatVector::GetData<RESULT_TYPE>(result);
134490 auto ldata = FlatVector::GetData<INPUT_TYPE>(dictionary_values);
134491 ExecuteFlat<INPUT_TYPE, RESULT_TYPE, OPWRAPPER, OP>(
134492 ldata, result_data, dict_size.GetIndex(), FlatVector::Validity(dictionary_values),
134493 FlatVector::Validity(result), dataptr, adds_nulls);
134494
134495 auto &offsets = DictionaryVector::SelVector(input);
134496 result.Dictionary(result, dict_size.GetIndex(), offsets, count);
134497 break;
134498 }
134499 }
134500 }
134501 DUCKDB_EXPLICIT_FALLTHROUGH;
134502 }
134503#endif
134504 default: {
134505 UnifiedVectorFormat vdata;
134506 input.ToUnifiedFormat(count, vdata);
134507
134508 result.SetVectorType(VectorType::FLAT_VECTOR);
134509 auto result_data = FlatVector::GetData<RESULT_TYPE>(result);
134510 auto ldata = UnifiedVectorFormat::GetData<INPUT_TYPE>(vdata);
134511
134512 ExecuteLoop<INPUT_TYPE, RESULT_TYPE, OPWRAPPER, OP>(ldata, result_data, count, vdata.sel, vdata.validity,
134513 FlatVector::Validity(result), dataptr, adds_nulls);
134514 break;
134515 }
134516 }
134517 }
134518
134519public:
134520 template <class INPUT_TYPE, class RESULT_TYPE, class OP>
134521 static void Execute(Vector &input, Vector &result, idx_t count) {
134522 ExecuteStandard<INPUT_TYPE, RESULT_TYPE, UnaryOperatorWrapper, OP>(input, result, count, nullptr, false);
134523 }
134524
134525 template <class INPUT_TYPE, class RESULT_TYPE, class FUNC = std::function<RESULT_TYPE(INPUT_TYPE)>>
134526 static void Execute(Vector &input, Vector &result, idx_t count, FUNC fun,
134527 FunctionErrors errors = FunctionErrors::CAN_THROW_RUNTIME_ERROR) {
134528 ExecuteStandard<INPUT_TYPE, RESULT_TYPE, UnaryLambdaWrapper, FUNC>(
134529 input, result, count, reinterpret_cast<void *>(&fun), false, errors);
134530 }
134531
134532 template <class INPUT_TYPE, class RESULT_TYPE, class OP>
134533 static void GenericExecute(Vector &input, Vector &result, idx_t count, void *dataptr, bool adds_nulls = false) {
134534 ExecuteStandard<INPUT_TYPE, RESULT_TYPE, GenericUnaryWrapper, OP>(input, result, count, dataptr, adds_nulls);
134535 }
134536
134537 template <class INPUT_TYPE, class RESULT_TYPE,
134538 class FUNC = std::function<RESULT_TYPE(INPUT_TYPE, ValidityMask &, idx_t)>>
134539 static void ExecuteWithNulls(Vector &input, Vector &result, idx_t count, FUNC fun) {
134540 ExecuteStandard<INPUT_TYPE, RESULT_TYPE, UnaryLambdaWrapperWithNulls, FUNC>(input, result, count, (void *)&fun,
134541 true);
134542 }
134543
134544 template <class INPUT_TYPE, class RESULT_TYPE, class OP>
134545 static void ExecuteString(Vector &input, Vector &result, idx_t count) {
134546 UnaryExecutor::GenericExecute<INPUT_TYPE, RESULT_TYPE, UnaryStringOperator<OP>>(input, result, count,
134547 (void *)&result);
134548 }
134549
134550private:
134551
134552 template <class INPUT_TYPE, class FUNC = std::function<bool(INPUT_TYPE)>, bool NO_NULL, bool HAS_TRUE_SEL,
134553 bool HAS_FALSE_SEL>
134554 static inline idx_t SelectLoop(
const INPUT_TYPE *__restrict input_data,
const SelectionVector *result_sel,
134555 const idx_t count, FUNC fun, const SelectionVector &input_sel,
134556 ValidityMask &input_validity, SelectionVector *true_sel,
134557 SelectionVector *false_sel) {
134558 idx_t true_count = 0, false_count = 0;
134559 for (idx_t i = 0; i < count; i++) {
134560 const auto result_idx = result_sel->get_index(i);
134561 const auto idx = input_sel.get_index(i);
134562 const bool comparison_result = (NO_NULL || input_validity.RowIsValid(idx)) && fun(input_data[idx]);
134563 if (HAS_TRUE_SEL) {
134564 true_sel->set_index(true_count, result_idx);
134565 true_count += comparison_result;
134566 }
134567 if (HAS_FALSE_SEL) {
134568 false_sel->set_index(false_count, result_idx);
134569 false_count += !comparison_result;
134570 }
134571 }
134572 if (HAS_TRUE_SEL) {
134573 return true_count;
134574 } else {
134575 return count - false_count;
134576 }
134577 }
134578
134579 template <class INPUT_TYPE, class FUNC = std::function<bool(INPUT_TYPE)>, bool NO_NULL>
134580 static inline idx_t SelectLoopSelSwitch(UnifiedVectorFormat &input_data,
const SelectionVector *sel,
134581 const idx_t count, FUNC fun, SelectionVector *true_sel,
134582 SelectionVector *false_sel) {
134583 if (true_sel && false_sel) {
134584 return SelectLoop<INPUT_TYPE, FUNC, NO_NULL, true, true>(
134585 UnifiedVectorFormat::GetData<INPUT_TYPE>(input_data), sel, count, fun, *input_data.sel,
134586 input_data.validity, true_sel, false_sel);
134587 } else if (true_sel) {
134588 return SelectLoop<INPUT_TYPE, FUNC, NO_NULL, true, false>(
134589 UnifiedVectorFormat::GetData<INPUT_TYPE>(input_data), sel, count, fun, *input_data.sel,
134590 input_data.validity, true_sel, false_sel);
134591 } else {
134592 D_ASSERT(false_sel);
134593 return SelectLoop<INPUT_TYPE, FUNC, NO_NULL, false, true>(
134594 UnifiedVectorFormat::GetData<INPUT_TYPE>(input_data), sel, count, fun, *input_data.sel,
134595 input_data.validity, true_sel, false_sel);
134596 }
134597 }
134598
134599 template <class INPUT_TYPE, class FUNC = std::function<bool(INPUT_TYPE)>>
134600 static inline idx_t SelectLoopSwitch(UnifiedVectorFormat &input_data,
const SelectionVector *sel,
const idx_t count,
134601 FUNC fun, SelectionVector *true_sel, SelectionVector *false_sel) {
134602 if (!input_data.validity.AllValid()) {
134603 return SelectLoopSelSwitch<INPUT_TYPE, FUNC, false>(input_data, sel, count, fun, true_sel, false_sel);
134604 } else {
134605 return SelectLoopSelSwitch<INPUT_TYPE, FUNC, true>(input_data, sel, count, fun, true_sel, false_sel);
134606 }
134607 }
134608
134609public:
134610 template <class INPUT_TYPE, class FUNC = std::function<bool(INPUT_TYPE)>>
134611 static idx_t Select(Vector &input,
const SelectionVector *sel,
const idx_t count, FUNC fun,
134612 SelectionVector *true_sel, SelectionVector *false_sel) {
134613 if (!sel) {
134614 sel = FlatVector::IncrementalSelectionVector();
134615 }
134616 UnifiedVectorFormat input_data;
134617 input.ToUnifiedFormat(count, input_data);
134618
134619 return SelectLoopSwitch<INPUT_TYPE, FUNC>(input_data, sel, count, fun, true_sel, false_sel);
134620 }
134621};
134622
134623}
134624
134625
134626
134627
134628
134629
134630
134631
134632
134633
134634
134635
134636
134637
134638
134639
134640
134641
134642
134643
134644
134645
134646
134647
134648
134649
134650
134651
134652
134653
134654
134655
134656
134657
134658
134659
134660namespace duckdb {
134661
134662using named_parameter_type_map_t = case_insensitive_map_t<LogicalType>;
134663using named_parameter_map_t = case_insensitive_map_t<Value>;
134664
134665}
134666
134667
134668
134669
134670
134671
134672
134673
134674
134675
134676
134677
134678#include <functional>
134679
134680
134681
134682namespace duckdb {
134683
134684class DependencyItem {
134685public:
134686 virtual ~DependencyItem() {};
134687
134688public:
134689 template <class TARGET>
134690 TARGET &Cast() {
134691 DynamicCastCheck<TARGET>(this);
134692 return reinterpret_cast<TARGET &>(*this);
134693 }
134694 template <class TARGET>
134695 const TARGET &Cast() const {
134696 DynamicCastCheck<TARGET>(this);
134697 return reinterpret_cast<const TARGET &>(*this);
134698 }
134699};
134700
134701using dependency_scan_t = std::function<void(const string &name, shared_ptr<DependencyItem> item)>;
134702
134703class ExternalDependency {
134704public:
134705 explicit ExternalDependency() {
134706 }
134707 ~ExternalDependency() {
134708 }
134709
134710public:
134711 void AddDependency(const string &name, shared_ptr<DependencyItem> item) {
134712 objects[name] = std::move(item);
134713 }
134714 shared_ptr<DependencyItem> GetDependency(const string &name) const {
134715 auto it = objects.find(name);
134716 if (it == objects.end()) {
134717 return nullptr;
134718 }
134719 return it->second;
134720 }
134721 void ScanDependencies(const dependency_scan_t &callback) {
134722 for (auto &kv : objects) {
134723 callback(kv.first, kv.second);
134724 }
134725 }
134726
134727private:
134729 case_insensitive_map_t<shared_ptr<DependencyItem>> objects;
134730};
134731
134732}
134733
134734
134735
134736
134737
134738
134739
134740
134741
134742
134743
134744
134745
134746
134747
134748
134749
134750
134751
134752
134753
134754
134755
134756
134757
134758
134759
134760
134761
134762
134763
134764
134765
134766
134767
134768
134769
134770
134771
134772
134773
134774
134775
134776
134777
134778namespace duckdb {
134779
134780
134781
134782
134783enum class ExpressionType :
uint8_t {
134784 INVALID = 0,
134785
134786
134787 OPERATOR_CAST = 12,
134788
134789 OPERATOR_NOT = 13,
134790
134791 OPERATOR_IS_NULL = 14,
134792
134793 OPERATOR_IS_NOT_NULL = 15,
134794
134795 OPERATOR_UNPACK = 16,
134796
134797
134798
134799
134800
134801 COMPARE_EQUAL = 25,
134802
134803 COMPARE_BOUNDARY_START = COMPARE_EQUAL,
134804
134805 COMPARE_NOTEQUAL = 26,
134806
134807 COMPARE_LESSTHAN = 27,
134808
134809 COMPARE_GREATERTHAN = 28,
134810
134811 COMPARE_LESSTHANOREQUALTO = 29,
134812
134813 COMPARE_GREATERTHANOREQUALTO = 30,
134814
134815 COMPARE_IN = 35,
134816
134817 COMPARE_NOT_IN = 36,
134818
134819 COMPARE_DISTINCT_FROM = 37,
134820
134821 COMPARE_BETWEEN = 38,
134822 COMPARE_NOT_BETWEEN = 39,
134823
134824 COMPARE_NOT_DISTINCT_FROM = 40,
134825
134826 COMPARE_BOUNDARY_END = COMPARE_NOT_DISTINCT_FROM,
134827
134828
134829
134830
134831 CONJUNCTION_AND = 50,
134832 CONJUNCTION_OR = 51,
134833
134834
134835
134836
134837 VALUE_CONSTANT = 75,
134838 VALUE_PARAMETER = 76,
134839 VALUE_TUPLE = 77,
134840 VALUE_TUPLE_ADDRESS = 78,
134841 VALUE_NULL = 79,
134842 VALUE_VECTOR = 80,
134843 VALUE_SCALAR = 81,
134844 VALUE_DEFAULT = 82,
134845
134846
134847
134848
134849 AGGREGATE = 100,
134850 BOUND_AGGREGATE = 101,
134851 GROUPING_FUNCTION = 102,
134852
134853
134854
134855
134856 WINDOW_AGGREGATE = 110,
134857
134858 WINDOW_RANK = 120,
134859 WINDOW_RANK_DENSE = 121,
134860 WINDOW_NTILE = 122,
134861 WINDOW_PERCENT_RANK = 123,
134862 WINDOW_CUME_DIST = 124,
134863 WINDOW_ROW_NUMBER = 125,
134864
134865 WINDOW_FIRST_VALUE = 130,
134866 WINDOW_LAST_VALUE = 131,
134867 WINDOW_LEAD = 132,
134868 WINDOW_LAG = 133,
134869 WINDOW_NTH_VALUE = 134,
134870 WINDOW_FILL = 135,
134871
134872
134873
134874
134875 FUNCTION = 140,
134876 BOUND_FUNCTION = 141,
134877
134878
134879
134880
134881 CASE_EXPR = 150,
134882 OPERATOR_NULLIF = 151,
134883 OPERATOR_COALESCE = 152,
134884 ARRAY_EXTRACT = 153,
134885 ARRAY_SLICE = 154,
134886 STRUCT_EXTRACT = 155,
134887 ARRAY_CONSTRUCTOR = 156,
134888 ARROW = 157,
134889 OPERATOR_TRY = 158,
134890
134891
134892
134893
134894 SUBQUERY = 175,
134895
134896
134897
134898
134899 STAR = 200,
134900 TABLE_STAR = 201,
134901 PLACEHOLDER = 202,
134902 COLUMN_REF = 203,
134903 FUNCTION_REF = 204,
134904 TABLE_REF = 205,
134905 LAMBDA_REF = 206,
134907
134908
134909
134910
134911 CAST = 225,
134912 BOUND_REF = 227,
134913 BOUND_COLUMN_REF = 228,
134914 BOUND_UNNEST = 229,
134915 COLLATE = 230,
134916 LAMBDA = 231,
134917 POSITIONAL_REFERENCE = 232,
134918 BOUND_LAMBDA_REF = 233,
134919 BOUND_EXPANDED = 234
134920};
134921
134922
134923
134924
134925enum class ExpressionClass :
uint8_t {
134926 INVALID = 0,
134927
134928
134929
134930 AGGREGATE = 1,
134931 CASE = 2,
134932 CAST = 3,
134933 COLUMN_REF = 4,
134934 COMPARISON = 5,
134935 CONJUNCTION = 6,
134936 CONSTANT = 7,
134937 DEFAULT = 8,
134938 FUNCTION = 9,
134939 OPERATOR = 10,
134940 STAR = 11,
134941 SUBQUERY = 13,
134942 WINDOW = 14,
134943 PARAMETER = 15,
134944 COLLATE = 16,
134945 LAMBDA = 17,
134946 POSITIONAL_REFERENCE = 18,
134947 BETWEEN = 19,
134948 LAMBDA_REF = 20,
134950
134951
134952
134953 BOUND_AGGREGATE = 25,
134954 BOUND_CASE = 26,
134955 BOUND_CAST = 27,
134956 BOUND_COLUMN_REF = 28,
134957 BOUND_COMPARISON = 29,
134958 BOUND_CONJUNCTION = 30,
134959 BOUND_CONSTANT = 31,
134960 BOUND_DEFAULT = 32,
134961 BOUND_FUNCTION = 33,
134962 BOUND_OPERATOR = 34,
134963 BOUND_PARAMETER = 35,
134964 BOUND_REF = 36,
134965 BOUND_SUBQUERY = 37,
134966 BOUND_WINDOW = 38,
134967 BOUND_BETWEEN = 39,
134968 BOUND_UNNEST = 40,
134969 BOUND_LAMBDA = 41,
134970 BOUND_LAMBDA_REF = 42,
134971
134972
134973
134974 BOUND_EXPRESSION = 50,
134975 BOUND_EXPANDED = 51
134976};
134977
134978DUCKDB_API string ExpressionTypeToString(ExpressionType type);
134979string ExpressionTypeToOperator(ExpressionType type);
134980
134981
134982ExpressionType OperatorToExpressionType(const string &op);
134987
134988DUCKDB_API string ExpressionClassToString(ExpressionClass type);
134989
134990}
134991
134992
134993
134994
134995namespace duckdb {
134996
134999class BaseExpression {
135000public:
135002 BaseExpression(ExpressionType type, ExpressionClass expression_class)
135003 : type(type), expression_class(expression_class) {
135004 }
135005 virtual ~BaseExpression() {
135006 }
135007
135009 ExpressionClass GetExpressionClass() const {
135010 return expression_class;
135011 }
135012
135014 ExpressionType GetExpressionType() const {
135015 return type;
135016 }
135017
135020 void SetExpressionTypeUnsafe(ExpressionType new_type) {
135021 type = new_type;
135022 }
135023
135025 optional_idx GetQueryLocation() const {
135026 return query_location;
135027 }
135028
135030 void SetQueryLocation(optional_idx location) {
135031 query_location = location;
135032 }
135033
135035 bool HasAlias() const {
135036 return !alias.empty();
135037 }
135038
135040 const string &GetAlias() const {
135041 return alias;
135042 }
135043
135045 void SetAlias(const string &alias_p) {
135046 alias = alias_p;
135047 }
135048
135050 void SetAlias(string &&alias_p) {
135051 alias = std::move(alias_p);
135052 }
135053
135055 void ClearAlias() {
135056 alias.clear();
135057 }
135058
135059
135060
135061
135063 ExpressionType type;
135064
135066 ExpressionClass expression_class;
135067
135069 string alias;
135070
135072 optional_idx query_location;
135073
135074public:
135076
135083 virtual bool IsAggregate() const = 0;
135085 virtual bool IsWindow() const = 0;
135087 virtual bool HasSubquery() const = 0;
135089 virtual bool IsScalar() const = 0;
135091 virtual bool HasParameter() const = 0;
135092
135094 virtual string GetName() const;
135096 virtual string ToString() const = 0;
135098 void Print() const;
135099
135102 virtual hash_t Hash()
const = 0;
135104 virtual bool Equals(const BaseExpression &other) const;
135105
135106 static bool Equals(const BaseExpression &left, const BaseExpression &right) {
135107 return left.Equals(right);
135108 }
135109 bool operator==(
const BaseExpression &rhs)
const {
135110 return Equals(rhs);
135111 }
135112
135113 virtual void Verify() const;
135114
135115public:
135116 template <class TARGET>
135117 TARGET &Cast() {
135118 if (expression_class != TARGET::TYPE) {
135119 throw InternalException("Failed to cast expression to type - expression type mismatch");
135120 }
135121 return reinterpret_cast<TARGET &>(*this);
135122 }
135123
135124 template <class TARGET>
135125 const TARGET &Cast() const {
135126 if (expression_class != TARGET::TYPE) {
135127 throw InternalException("Failed to cast expression to type - expression type mismatch");
135128 }
135129 return reinterpret_cast<const TARGET &>(*this);
135130 }
135131};
135132
135133}
135134
135135
135136
135137
135138
135139
135140
135141
135142
135143
135144
135145
135146
135147
135148
135149
135150
135151
135152
135153
135154
135155
135156
135157
135158
135159namespace duckdb {
135160class StandardEntry;
135161
135162struct BindingAlias {
135163 BindingAlias();
135164 explicit BindingAlias(string alias);
135165 BindingAlias(string schema, string alias);
135166 BindingAlias(string catalog, string schema, string alias);
135167 explicit BindingAlias(const StandardEntry &entry);
135168
135169 bool IsSet() const;
135170 const string &GetAlias() const;
135171
135172 const string &GetCatalog() const {
135173 return catalog;
135174 }
135175 const string &GetSchema() const {
135176 return schema;
135177 }
135178
135179 bool Matches(const BindingAlias &other) const;
135180 bool operator==(
const BindingAlias &other)
const;
135181 string ToString() const;
135182
135183private:
135184 string catalog;
135185 string schema;
135186 string alias;
135187};
135188
135189}
135190
135191
135192
135193
135194
135195
135196
135197
135198
135199
135200
135201
135202
135203
135204
135205
135206
135207
135208
135209
135210
135211
135212
135213
135214namespace duckdb {
135215
135219 SIMPLIFIED_TOKEN_IDENTIFIER,
135220 SIMPLIFIED_TOKEN_NUMERIC_CONSTANT,
135221 SIMPLIFIED_TOKEN_STRING_CONSTANT,
135222 SIMPLIFIED_TOKEN_OPERATOR,
135223 SIMPLIFIED_TOKEN_KEYWORD,
135224 SIMPLIFIED_TOKEN_COMMENT,
135225 SIMPLIFIED_TOKEN_ERROR,
135226 SIMPLIFIED_TOKEN_ERROR_EMPHASIS,
135227 SIMPLIFIED_TOKEN_ERROR_SUGGESTION
135228};
135229
135230struct SimplifiedToken {
135233};
135234
135235enum class KeywordCategory :
uint8_t {
135236 KEYWORD_RESERVED,
135237 KEYWORD_UNRESERVED,
135238 KEYWORD_TYPE_FUNC,
135239 KEYWORD_COL_NAME,
135240 KEYWORD_NONE
135241};
135242
135243struct ParserKeyword {
135244 string name;
135245 KeywordCategory category;
135246};
135247
135248}
135249
135250
135251namespace duckdb {
135252
135253class KeywordHelper {
135254public:
135256 static bool IsKeyword(const string &text, KeywordCategory category = KeywordCategory::KEYWORD_NONE);
135257
135258 static KeywordCategory KeywordCategoryType(const string &text);
135259
135260 static string EscapeQuotes(const string &text, char quote = '"');
135261
135263 static bool RequiresQuotes(const string &text, bool allow_caps = true,
135264 KeywordCategory category = KeywordCategory::KEYWORD_NONE);
135265
135267 static string WriteQuoted(const string &text, char quote = '\'');
135268
135270 static string WriteOptionallyQuoted(const string &text, char quote = '"', bool allow_caps = true,
135271 KeywordCategory category = KeywordCategory::KEYWORD_NONE);
135272};
135273
135274}
135275
135276
135277namespace duckdb {
135278
135279struct QualifiedName {
135280 string catalog;
135281 string schema;
135282 string name;
135283
135286 static QualifiedName Parse(const string &input);
135287 static vector<string> ParseComponents(const string &input);
135288 string ToString() const;
135289};
135290
135291struct QualifiedColumnName {
135292 QualifiedColumnName();
135293 QualifiedColumnName(string column_p);
135294 QualifiedColumnName(string table_p, string column_p);
135295 QualifiedColumnName(const BindingAlias &alias, string column_p);
135296
135297 string catalog;
135298 string schema;
135299 string table;
135300 string column;
135301
135302 static QualifiedColumnName Parse(string &input);
135303
135304 string ToString() const;
135305
135306 void Serialize(Serializer &serializer) const;
135307 static QualifiedColumnName Deserialize(Deserializer &deserializer);
135308
135309 bool IsQualified() const;
135310
135311 bool operator==(
const QualifiedColumnName &rhs)
const;
135312};
135313
135314}
135315
135316
135317namespace duckdb {
135318class Deserializer;
135319class Serializer;
135320
135323
135330class ParsedExpression : public BaseExpression {
135331public:
135333 ParsedExpression(ExpressionType type, ExpressionClass expression_class) : BaseExpression(type, expression_class) {
135334 }
135335
135336public:
135337 bool IsAggregate() const override;
135338 bool IsWindow() const override;
135339 bool HasSubquery() const override;
135340 bool IsScalar() const override;
135341 bool HasParameter() const override;
135342
135343 bool Equals(const BaseExpression &other) const override;
135344 hash_t Hash()
const override;
135345
135347 virtual unique_ptr<ParsedExpression> Copy() const = 0;
135348
135349 virtual void Serialize(Serializer &serializer) const;
135350 static unique_ptr<ParsedExpression> Deserialize(Deserializer &deserializer);
135351
135352 static bool Equals(const unique_ptr<ParsedExpression> &left, const unique_ptr<ParsedExpression> &right);
135353 static bool ListEquals(const vector<unique_ptr<ParsedExpression>> &left,
135354 const vector<unique_ptr<ParsedExpression>> &right);
135355
135356protected:
135359 void CopyProperties(const ParsedExpression &other) {
135360 type = other.type;
135361 expression_class = other.expression_class;
135362 alias = other.alias;
135363 query_location = other.query_location;
135364 }
135365};
135366
135367}
135368
135369
135370
135371
135372
135373
135374
135375
135376
135377
135378
135379
135380
135381
135382
135383namespace duckdb {
135384
135385class StorageManager;
135386
135387enum class CompressionType :
uint8_t {
135388 COMPRESSION_AUTO = 0,
135389 COMPRESSION_UNCOMPRESSED = 1,
135390 COMPRESSION_CONSTANT = 2,
135391 COMPRESSION_RLE = 3,
135392 COMPRESSION_DICTIONARY = 4,
135393 COMPRESSION_PFOR_DELTA = 5,
135394 COMPRESSION_BITPACKING = 6,
135395 COMPRESSION_FSST = 7,
135396 COMPRESSION_CHIMP = 8,
135397 COMPRESSION_PATAS = 9,
135398 COMPRESSION_ALP = 10,
135399 COMPRESSION_ALPRD = 11,
135400 COMPRESSION_ZSTD = 12,
135401 COMPRESSION_ROARING = 13,
135402 COMPRESSION_EMPTY = 14,
135403 COMPRESSION_DICT_FSST = 15,
135404 COMPRESSION_COUNT
135405};
135406
135407struct CompressionAvailabilityResult {
135408private:
135409 enum class UnavailableReason :
uint8_t {
135410 AVAILABLE,
135412 NOT_AVAILABLE_YET,
135414 DEPRECATED
135415 };
135416
135417public:
135418 CompressionAvailabilityResult() = default;
135419 static CompressionAvailabilityResult Deprecated() {
135420 return CompressionAvailabilityResult(UnavailableReason::DEPRECATED);
135421 }
135422 static CompressionAvailabilityResult NotAvailableYet() {
135423 return CompressionAvailabilityResult(UnavailableReason::NOT_AVAILABLE_YET);
135424 }
135425
135426public:
135427 bool IsAvailable() const {
135428 return reason == UnavailableReason::AVAILABLE;
135429 }
135430 bool IsDeprecated() {
135431 D_ASSERT(!IsAvailable());
135432 return reason == UnavailableReason::DEPRECATED;
135433 }
135434 bool IsNotAvailableYet() {
135435 D_ASSERT(!IsAvailable());
135436 return reason == UnavailableReason::NOT_AVAILABLE_YET;
135437 }
135438
135439private:
135440 explicit CompressionAvailabilityResult(UnavailableReason reason) : reason(reason) {
135441 }
135442
135443public:
135444 UnavailableReason reason = UnavailableReason::AVAILABLE;
135445};
135446
135448 optional_ptr<StorageManager> storage_manager = nullptr);
135449vector<string> ListCompressionTypes(void);
135450string CompressionTypeToString(CompressionType type);
135451
135452}
135453
135454
135455
135456
135457
135458
135459
135460
135461
135462
135463
135464
135465
135466namespace duckdb {
135467
135468enum class TableColumnType :
uint8_t { STANDARD = 0, GENERATED = 1 };
135469
135470}
135471
135472
135473namespace duckdb {
135474
135475struct RenameColumnInfo;
135476struct RenameTableInfo;
135477
135478class ColumnDefinition;
135479
135481class ColumnDefinition {
135482public:
135483 DUCKDB_API ColumnDefinition(string name, LogicalType type);
135484 DUCKDB_API ColumnDefinition(string name, LogicalType type, unique_ptr<ParsedExpression> expression,
135485 TableColumnType category);
135486
135487public:
135489 const ParsedExpression &DefaultValue() const;
135490 bool HasDefaultValue() const;
135491 void SetDefaultValue(unique_ptr<ParsedExpression> default_value);
135492
135494 DUCKDB_API const LogicalType &Type() const;
135495 LogicalType &TypeMutable();
135496 void SetType(const LogicalType &type);
135497
135499 DUCKDB_API const string &Name() const;
135500 void SetName(const string &name);
135501
135503 DUCKDB_API const Value &Comment() const;
135504 void SetComment(const Value &comment);
135505
135507 const duckdb::CompressionType &CompressionType() const;
135508 void SetCompressionType(duckdb::CompressionType compression_type);
135509
135512 void SetStorageOid(storage_t storage_oid);
135513
135514 LogicalIndex Logical() const;
135515 PhysicalIndex Physical() const;
135516
135519 void SetOid(column_t oid);
135520
135522 const TableColumnType &Category() const;
135524 bool Generated() const;
135525 DUCKDB_API ColumnDefinition Copy() const;
135526
135527 DUCKDB_API void Serialize(Serializer &serializer) const;
135528 DUCKDB_API static ColumnDefinition Deserialize(Deserializer &deserializer);
135529
135530
135531
135532
135533
135534 ParsedExpression &GeneratedExpressionMutable();
135535 const ParsedExpression &GeneratedExpression() const;
135536 void SetGeneratedExpression(unique_ptr<ParsedExpression> expression);
135537 void ChangeGeneratedExpressionType(const LogicalType &type);
135538 void GetListOfDependencies(vector<string> &dependencies) const;
135539
135540 string GetName() const;
135541
135542 LogicalType GetType() const;
135543
135544private:
135546 string name;
135548 LogicalType type;
135550 duckdb::CompressionType compression_type = duckdb::CompressionType::COMPRESSION_AUTO;
135552 storage_t storage_oid = DConstants::INVALID_INDEX;
135554 idx_t oid = DConstants::INVALID_INDEX;
135556 TableColumnType category = TableColumnType::STANDARD;
135559 unique_ptr<ParsedExpression> expression;
135561 Value comment;
135563 unordered_map<string, string> tags;
135564};
135565
135566}
135567
135568
135569
135570namespace duckdb {
135571class CatalogEntry;
135572class Catalog;
135573class ClientContext;
135574class Expression;
135575class ExpressionExecutor;
135576class Transaction;
135577
135578class AggregateFunction;
135579class AggregateFunctionSet;
135580class CopyFunction;
135581class PragmaFunction;
135582class PragmaFunctionSet;
135583class ScalarFunctionSet;
135584class ScalarFunction;
135585class TableFunctionSet;
135586class TableFunction;
135587class SimpleFunction;
135588
135589struct PragmaInfo;
135590
135599
135605 PROPAGATE_COLLATIONS = 0,
135606 PUSH_COMBINABLE_COLLATIONS = 1,
135607 IGNORE_COLLATIONS = 2
135608};
135609
135610struct FunctionData {
135611 DUCKDB_API virtual ~FunctionData();
135612
135613 DUCKDB_API virtual unique_ptr<FunctionData> Copy() const = 0;
135614 DUCKDB_API virtual bool Equals(const FunctionData &other) const = 0;
135615 DUCKDB_API static bool Equals(const FunctionData *left, const FunctionData *right);
135616 DUCKDB_API virtual bool SupportStatementCache() const;
135617
135618 template <class TARGET>
135619 TARGET &Cast() {
135620 DynamicCastCheck<TARGET>(this);
135621 return reinterpret_cast<TARGET &>(*this);
135622 }
135623 template <class TARGET>
135624 const TARGET &Cast() const {
135625 DynamicCastCheck<TARGET>(this);
135626 return reinterpret_cast<const TARGET &>(*this);
135627 }
135628
135629 template <class TARGET>
135630 TARGET &CastNoConst() const {
135631 return const_cast<TARGET &>(Cast<TARGET>());
135632 }
135633};
135634
135635struct TableFunctionData : public FunctionData {
135636
135637 vector<idx_t> column_ids;
135638
135639 DUCKDB_API ~TableFunctionData() override;
135640
135641 DUCKDB_API unique_ptr<FunctionData> Copy() const override;
135642 DUCKDB_API bool Equals(const FunctionData &other) const override;
135643};
135644
135645struct FunctionParameters {
135646 vector<Value> values;
135647 named_parameter_map_t named_parameters;
135648};
135649
135651class Function {
135652public:
135653 DUCKDB_API explicit Function(string name);
135654 DUCKDB_API virtual ~Function();
135655
135657 string name;
135659 string extra_info;
135660
135661
135662 string catalog_name;
135663
135664
135665 string schema_name;
135666
135667public:
135669 DUCKDB_API static string CallToString(const string &catalog_name, const string &schema_name, const string &name,
135670 const vector<LogicalType> &arguments,
135671 const LogicalType &varargs = LogicalType::INVALID);
135673 DUCKDB_API static string CallToString(const string &catalog_name, const string &schema_name, const string &name,
135674 const vector<LogicalType> &arguments, const LogicalType &varargs,
135675 const LogicalType &return_type);
135677 DUCKDB_API static string CallToString(const string &catalog_name, const string &schema_name, const string &name,
135678 const vector<LogicalType> &arguments,
135679 const named_parameter_type_map_t &named_parameters);
135680
135682 DUCKDB_API static void EraseArgument(SimpleFunction &bound_function, vector<unique_ptr<Expression>> &arguments,
135683 idx_t argument_index);
135684};
135685
135686class SimpleFunction : public Function {
135687public:
135688 DUCKDB_API SimpleFunction(string name, vector<LogicalType> arguments,
135689 LogicalType varargs = LogicalType(LogicalTypeId::INVALID));
135690 DUCKDB_API ~SimpleFunction() override;
135691
135693 vector<LogicalType> arguments;
135696 vector<LogicalType> original_arguments;
135699 LogicalType varargs;
135700
135701public:
135702 DUCKDB_API virtual string ToString() const;
135703
135704 DUCKDB_API bool HasVarArgs() const;
135705};
135706
135707class SimpleNamedParameterFunction : public SimpleFunction {
135708public:
135709 DUCKDB_API SimpleNamedParameterFunction(string name, vector<LogicalType> arguments,
135710 LogicalType varargs = LogicalType(LogicalTypeId::INVALID));
135711 DUCKDB_API ~SimpleNamedParameterFunction() override;
135712
135714 named_parameter_type_map_t named_parameters;
135715
135716public:
135717 DUCKDB_API string ToString() const override;
135718 DUCKDB_API bool HasNamedParameters() const;
135719};
135720
135721class BaseScalarFunction : public SimpleFunction {
135722public:
135723 DUCKDB_API BaseScalarFunction(string name, vector<LogicalType> arguments, LogicalType return_type,
135724 FunctionStability stability,
135725 LogicalType varargs = LogicalType(LogicalTypeId::INVALID),
135726 FunctionNullHandling null_handling = FunctionNullHandling::DEFAULT_NULL_HANDLING,
135727 FunctionErrors errors = FunctionErrors::CANNOT_ERROR);
135728 DUCKDB_API ~BaseScalarFunction() override;
135729
135730public:
135731 void SetReturnType(LogicalType return_type_p) {
135732 return_type = std::move(return_type_p);
135733 }
135734 const LogicalType &GetReturnType() const {
135735 return return_type;
135736 }
135737 LogicalType &GetReturnType() {
135738 return return_type;
135739 }
135740
135742 return stability;
135743 }
135744 void SetStability(FunctionStability stability_p) {
135745 stability = stability_p;
135746 }
135747
135749 return null_handling;
135750 }
135751 void SetNullHandling(FunctionNullHandling null_handling_p) {
135752 null_handling = null_handling_p;
135753 }
135754
135756 return errors;
135757 }
135758 void SetErrorMode(FunctionErrors errors_p) {
135759 errors = errors_p;
135760 }
135761
135763 void SetFallible() {
135764 errors = FunctionErrors::CAN_THROW_RUNTIME_ERROR;
135765 }
135767 void SetVolatile() {
135768 stability = FunctionStability::VOLATILE;
135769 }
135770
135771 void SetCollationHandling(FunctionCollationHandling collation_handling_p) {
135772 collation_handling = collation_handling_p;
135773 }
135775 return collation_handling;
135776 }
135777
135778public:
135780 LogicalType return_type;
135789
135790 static BaseScalarFunction SetReturnsError(BaseScalarFunction &function) {
135791 function.errors = FunctionErrors::CAN_THROW_RUNTIME_ERROR;
135792 return function;
135793 }
135794
135795public:
135796 DUCKDB_API
hash_t Hash()
const;
135797
135798 DUCKDB_API string ToString() const override;
135799};
135800
135801}
135802
135803
135804namespace duckdb {
135805
135806class Expression;
135807class BoundFunctionExpression;
135808class ExpressionExecutor;
135809struct ExpressionExecutorState;
135810struct FunctionLocalState;
135811
135812struct ExpressionState {
135813 ExpressionState(const Expression &expr, ExpressionExecutorState &root);
135814 virtual ~ExpressionState() {
135815 }
135816
135817 const Expression &expr;
135818 ExpressionExecutorState &root;
135819 vector<unique_ptr<ExpressionState>> child_states;
135820 vector<LogicalType> types;
135821 DataChunk intermediate_chunk;
135822 vector<bool> initialize;
135823
135824public:
135825 void AddChild(Expression &child_expr);
135826 void Finalize();
135827 Allocator &GetAllocator();
135828 bool HasContext();
135829 DUCKDB_API ClientContext &GetContext();
135830
135831 void Verify(ExpressionExecutorState &root);
135832
135834 virtual void ResetDictionaryStates();
135835
135836public:
135837 template <class TARGET>
135838 TARGET &Cast() {
135839 DynamicCastCheck<TARGET>(this);
135840 return reinterpret_cast<TARGET &>(*this);
135841 }
135842 template <class TARGET>
135843 const TARGET &Cast() const {
135844 DynamicCastCheck<TARGET>(this);
135845 return reinterpret_cast<const TARGET &>(*this);
135846 }
135847};
135848
135849struct ExecuteFunctionState : public ExpressionState {
135850public:
135851 ExecuteFunctionState(const Expression &expr, ExpressionExecutorState &root);
135852 ~ExecuteFunctionState() override;
135853
135854public:
135855 static optional_ptr<FunctionLocalState> GetFunctionState(ExpressionState &state) {
135856 return state.Cast<ExecuteFunctionState>().local_state.get();
135857 }
135858
135859 bool TryExecuteDictionaryExpression(const BoundFunctionExpression &expr, DataChunk &args, ExpressionState &state,
135860 Vector &result);
135861
135862 void ResetDictionaryStates() override;
135863
135864public:
135865 unique_ptr<FunctionLocalState> local_state;
135866
135867private:
135871 optional_idx input_col_idx;
135873 buffer_ptr<VectorChildBuffer> output_dictionary;
135875 string current_input_dictionary_id;
135876};
135877
135878struct ExpressionExecutorState {
135879 ExpressionExecutorState();
135880
135881 unique_ptr<ExpressionState> root_state;
135882 ExpressionExecutor *executor = nullptr;
135883
135884 void Verify();
135885};
135886
135887}
135888
135889
135890
135891
135892
135893
135894
135895
135896
135897
135898
135899
135900
135901
135902
135903
135904
135905
135906
135907
135908
135909
135910
135911
135912
135913
135914
135915
135916
135917
135918
135919
135920
135921
135922
135923
135924
135925
135926
135927
135928namespace duckdb {
135929
135931class Hugeint {
135932public:
135933 constexpr static const char *HUGEINT_MINIMUM_STRING = "-170141183460469231731687303715884105728";
135934
135936 static string ToString(hugeint_t input);
135937
135938 template <class T>
135939 DUCKDB_API static bool TryCast(hugeint_t input, T &result);
135940
135941 template <class T>
135942 static T Cast(hugeint_t input) {
135943 T result = 0;
135944 TryCast(input, result);
135945 return result;
135946 }
135947
135948 template <class T>
135949 static bool TryConvert(T value, hugeint_t &result);
135950
135951 template <class T>
135952 static hugeint_t Convert(T value) {
135953 hugeint_t result;
135954 if (!TryConvert(value, result)) {
135955 throw OutOfRangeException(double(value), GetTypeId<T>(), GetTypeId<hugeint_t>());
135956 }
135957 return result;
135958 }
135959
135960 static bool TryNegate(hugeint_t input, hugeint_t &result);
135961
135962 template <bool CHECK_OVERFLOW = true>
135963 inline static void NegateInPlace(hugeint_t &input) {
135964 if (!TryNegate(input, input)) {
135965 throw OutOfRangeException("Negation of HUGEINT is out of range!");
135966 }
135967 }
135968
135969 template <bool CHECK_OVERFLOW = true>
135970 inline static hugeint_t Negate(hugeint_t input) {
135971 NegateInPlace<CHECK_OVERFLOW>(input);
135972 return input;
135973 }
135974
135975 static bool TryMultiply(hugeint_t lhs, hugeint_t rhs, hugeint_t &result);
135976
135977 template <bool CHECK_OVERFLOW = true>
135978 inline static hugeint_t Multiply(hugeint_t lhs, hugeint_t rhs) {
135979 hugeint_t result;
135980 if (!TryMultiply(lhs, rhs, result)) {
135981 throw OutOfRangeException("Overflow in HUGEINT multiplication: %s * %s", lhs.ToString(), rhs.ToString());
135982 }
135983 return result;
135984 }
135985
135986 static bool TryDivMod(hugeint_t lhs, hugeint_t rhs, hugeint_t &result, hugeint_t &remainder);
135987
135988 template <bool CHECK_OVERFLOW = true>
135989 inline static hugeint_t Divide(hugeint_t lhs, hugeint_t rhs) {
135990
135991 if (rhs == 0) {
135992 throw OutOfRangeException("Division of HUGEINT by zero: %s / %s", lhs.ToString(), rhs.ToString());
135993 }
135994
135995
135996 if (lhs == NumericLimits<hugeint_t>::Minimum() && rhs == -1) {
135997 throw OutOfRangeException("Overflow in HUGEINT division: %s / %s", lhs.ToString(), rhs.ToString());
135998 }
135999 return Divide<false>(lhs, rhs);
136000 }
136001
136002 template <bool CHECK_OVERFLOW = true>
136003 inline static hugeint_t Modulo(hugeint_t lhs, hugeint_t rhs) {
136004
136005 if (rhs == 0) {
136006 throw OutOfRangeException("Modulo of HUGEINT by zero: %s %% %s", lhs.ToString(), rhs.ToString());
136007 }
136008
136009
136010 if (lhs == NumericLimits<hugeint_t>::Minimum() && rhs == -1) {
136011 throw OutOfRangeException("Overflow in HUGEINT modulo: %s %% %s", lhs.ToString(), rhs.ToString());
136012 }
136013 return Modulo<false>(lhs, rhs);
136014 }
136015
136016 static bool TryAddInPlace(hugeint_t &lhs, hugeint_t rhs);
136017
136018 template <bool CHECK_OVERFLOW = true>
136019 inline static hugeint_t Add(hugeint_t lhs, hugeint_t rhs) {
136020 if (!TryAddInPlace(lhs, rhs)) {
136021 throw OutOfRangeException("Overflow in HUGEINT addition: %s + %s", lhs.ToString(), rhs.ToString());
136022 }
136023 return lhs;
136024 }
136025
136026 static bool TrySubtractInPlace(hugeint_t &lhs, hugeint_t rhs);
136027
136028 template <bool CHECK_OVERFLOW = true>
136029 inline static hugeint_t Subtract(hugeint_t lhs, hugeint_t rhs) {
136030 if (!TrySubtractInPlace(lhs, rhs)) {
136031 throw OutOfRangeException("Underflow in HUGEINT subtraction: %s - %s", lhs.ToString(), rhs.ToString());
136032 }
136033 return lhs;
136034 }
136035
136036
136037 static hugeint_t DivMod(hugeint_t lhs, hugeint_t rhs, hugeint_t &remainder);
136038
136039 static hugeint_t DivModPositive(hugeint_t lhs, uint64_t rhs, uint64_t &remainder);
136040
136041 static int Sign(hugeint_t n);
136042 static hugeint_t Abs(hugeint_t n);
136043
136044 static bool Equals(const hugeint_t &lhs, const hugeint_t &rhs) {
136045 bool lower_equals = lhs.lower == rhs.lower;
136046 bool upper_equals = lhs.upper == rhs.upper;
136047 return lower_equals && upper_equals;
136048 }
136049
136050 static bool NotEquals(const hugeint_t &lhs, const hugeint_t &rhs) {
136051 return !Equals(lhs, rhs);
136052 }
136053
136054 static bool GreaterThan(const hugeint_t &lhs, const hugeint_t &rhs) {
136055 bool upper_bigger = lhs.upper > rhs.upper;
136056 bool upper_equal = lhs.upper == rhs.upper;
136057 bool lower_bigger = lhs.lower > rhs.lower;
136058 return upper_bigger || (upper_equal && lower_bigger);
136059 }
136060
136061 static bool GreaterThanEquals(const hugeint_t &lhs, const hugeint_t &rhs) {
136062 bool upper_bigger = lhs.upper > rhs.upper;
136063 bool upper_equal = lhs.upper == rhs.upper;
136064 bool lower_bigger_equals = lhs.lower >= rhs.lower;
136065 return upper_bigger || (upper_equal && lower_bigger_equals);
136066 }
136067
136068 static bool LessThan(const hugeint_t &lhs, const hugeint_t &rhs) {
136069 bool upper_smaller = lhs.upper < rhs.upper;
136070 bool upper_equal = lhs.upper == rhs.upper;
136071 bool lower_smaller = lhs.lower < rhs.lower;
136072 return upper_smaller || (upper_equal && lower_smaller);
136073 }
136074
136075 static bool LessThanEquals(const hugeint_t &lhs, const hugeint_t &rhs) {
136076 bool upper_smaller = lhs.upper < rhs.upper;
136077 bool upper_equal = lhs.upper == rhs.upper;
136078 bool lower_smaller_equals = lhs.lower <= rhs.lower;
136079 return upper_smaller || (upper_equal && lower_smaller_equals);
136080 }
136081
136082 static constexpr uint8_t CACHED_POWERS_OF_TEN = 39;
136083 static const hugeint_t POWERS_OF_TEN[CACHED_POWERS_OF_TEN];
136084};
136085
136086template <>
136087DUCKDB_API bool Hugeint::TryCast(hugeint_t input, int8_t &result);
136088template <>
136089DUCKDB_API bool Hugeint::TryCast(hugeint_t input, int16_t &result);
136090template <>
136091DUCKDB_API bool Hugeint::TryCast(hugeint_t input, int32_t &result);
136092template <>
136093DUCKDB_API bool Hugeint::TryCast(hugeint_t input, int64_t &result);
136094template <>
136095DUCKDB_API bool Hugeint::TryCast(hugeint_t input, uint8_t &result);
136096template <>
136097DUCKDB_API bool Hugeint::TryCast(hugeint_t input, uint16_t &result);
136098template <>
136099DUCKDB_API bool Hugeint::TryCast(hugeint_t input, uint32_t &result);
136100template <>
136101DUCKDB_API bool Hugeint::TryCast(hugeint_t input, uint64_t &result);
136102template <>
136103DUCKDB_API bool Hugeint::TryCast(hugeint_t input, hugeint_t &result);
136104template <>
136105DUCKDB_API bool Hugeint::TryCast(hugeint_t input, uhugeint_t &result);
136106template <>
136107DUCKDB_API bool Hugeint::TryCast(hugeint_t input, float &result);
136108template <>
136109DUCKDB_API bool Hugeint::TryCast(hugeint_t input, double &result);
136110template <>
136111DUCKDB_API bool Hugeint::TryCast(hugeint_t input, long double &result);
136112
136113template <>
136114bool Hugeint::TryConvert(int8_t value, hugeint_t &result);
136115template <>
136116bool Hugeint::TryConvert(int16_t value, hugeint_t &result);
136117template <>
136118bool Hugeint::TryConvert(int32_t value, hugeint_t &result);
136119template <>
136120bool Hugeint::TryConvert(int64_t value, hugeint_t &result);
136121template <>
136122bool Hugeint::TryConvert(uint8_t value, hugeint_t &result);
136123template <>
136124bool Hugeint::TryConvert(uint16_t value, hugeint_t &result);
136125template <>
136126bool Hugeint::TryConvert(uint32_t value, hugeint_t &result);
136127template <>
136128bool Hugeint::TryConvert(uint64_t value, hugeint_t &result);
136129template <>
136130bool Hugeint::TryConvert(float value, hugeint_t &result);
136131template <>
136132bool Hugeint::TryConvert(double value, hugeint_t &result);
136133template <>
136134bool Hugeint::TryConvert(long double value, hugeint_t &result);
136135template <>
136136bool Hugeint::TryConvert(const char *value, hugeint_t &result);
136137
136138}
136139
136140
136141
136142
136143#include <cstring>
136144
136145namespace duckdb {
136146
136147
136148
136149
136150struct Equals {
136151 template <class T>
136152 static inline bool Operation(const T &left, const T &right) {
136153 return left == right;
136154 }
136155};
136156struct NotEquals {
136157 template <class T>
136158 static inline bool Operation(const T &left, const T &right) {
136159 return !Equals::Operation(left, right);
136160 }
136161};
136162
136163struct GreaterThan {
136164 template <class T>
136165 static inline bool Operation(const T &left, const T &right) {
136166 return left > right;
136167 }
136168};
136169
136170struct GreaterThanEquals {
136171 template <class T>
136172 static inline bool Operation(const T &left, const T &right) {
136173 return !GreaterThan::Operation(right, left);
136174 }
136175};
136176
136177struct LessThan {
136178 template <class T>
136179 static inline bool Operation(const T &left, const T &right) {
136180 return GreaterThan::Operation(right, left);
136181 }
136182};
136183
136184struct LessThanEquals {
136185 template <class T>
136186 static inline bool Operation(const T &left, const T &right) {
136187 return !GreaterThan::Operation(left, right);
136188 }
136189};
136190
136191template <>
136192DUCKDB_API bool Equals::Operation(const float &left, const float &right);
136193template <>
136194DUCKDB_API bool Equals::Operation(const double &left, const double &right);
136195
136196template <>
136197DUCKDB_API bool GreaterThan::Operation(const float &left, const float &right);
136198template <>
136199DUCKDB_API bool GreaterThan::Operation(const double &left, const double &right);
136200
136201template <>
136202DUCKDB_API bool GreaterThanEquals::Operation(const float &left, const float &right);
136203template <>
136204DUCKDB_API bool GreaterThanEquals::Operation(const double &left, const double &right);
136205
136206
136207
136208
136209struct DistinctFrom {
136210 template <class T>
136211 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
136212 if (left_null || right_null) {
136213 return left_null != right_null;
136214 }
136215 return NotEquals::Operation(left, right);
136216 }
136217};
136218
136219struct NotDistinctFrom {
136220 template <class T>
136221 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
136222 return !DistinctFrom::Operation(left, right, left_null, right_null);
136223 }
136224};
136225
136226struct DistinctGreaterThan {
136227 template <class T>
136228 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
136229 if (left_null || right_null) {
136230 return !right_null;
136231 }
136232 return GreaterThan::Operation(left, right);
136233 }
136234};
136235
136236struct DistinctGreaterThanNullsFirst {
136237 template <class T>
136238 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
136239 return DistinctGreaterThan::Operation(left, right, right_null, left_null);
136240 }
136241};
136242
136243struct DistinctGreaterThanEquals {
136244 template <class T>
136245 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
136246 return !DistinctGreaterThan::Operation(right, left, right_null, left_null);
136247 }
136248};
136249
136250struct DistinctLessThan {
136251 template <class T>
136252 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
136253 return DistinctGreaterThan::Operation(right, left, right_null, left_null);
136254 }
136255};
136256
136257struct DistinctLessThanNullsFirst {
136258 template <class T>
136259 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
136260 return DistinctGreaterThan::Operation(right, left, left_null, right_null);
136261 }
136262};
136263
136264struct DistinctLessThanEquals {
136265 template <class T>
136266 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
136267 return !DistinctGreaterThan::Operation(left, right, left_null, right_null);
136268 }
136269};
136270
136271
136272
136273
136274template <class OP>
136275struct ComparisonOperationWrapper {
136276 static constexpr const bool COMPARE_NULL = false;
136277
136278 template <class T>
136279 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
136280 if (right_null || left_null) {
136281 return false;
136282 }
136283 return OP::template Operation<T>(left, right);
136284 }
136285};
136286
136287template <>
136288struct ComparisonOperationWrapper<DistinctFrom> {
136289 static constexpr const bool COMPARE_NULL = true;
136290
136291 template <class T>
136292 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
136293 return DistinctFrom::template Operation<T>(left, right, left_null, right_null);
136294 }
136295};
136296
136297template <>
136298struct ComparisonOperationWrapper<NotDistinctFrom> {
136299 static constexpr const bool COMPARE_NULL = true;
136300
136301 template <class T>
136302 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
136303 return NotDistinctFrom::template Operation<T>(left, right, left_null, right_null);
136304 }
136305};
136306
136307
136308
136309
136310template <>
136311inline bool GreaterThan::Operation(const bool &left, const bool &right) {
136312 return !right && left;
136313}
136314
136315
136316
136317template <>
136318inline bool Equals::Operation(const string_t &left, const string_t &right) {
136319 return left == right;
136320}
136321
136322template <>
136323inline bool GreaterThan::Operation(const string_t &left, const string_t &right) {
136324 return left > right;
136325}
136326
136327
136328
136329
136330template <>
136331inline bool Equals::Operation(const interval_t &left, const interval_t &right) {
136332 return Interval::Equals(left, right);
136333}
136334template <>
136335inline bool GreaterThan::Operation(const interval_t &left, const interval_t &right) {
136336 return Interval::GreaterThan(left, right);
136337}
136338
136339}
136340
136341
136342
136343
136344
136345
136346
136347
136348
136349
136350
136351
136352
136353
136354
136355
136356
136357
136358
136359
136360
136361
136362
136363
136364
136365
136366
136367
136368
136369namespace duckdb {
136370
136372 INVALID,
136377};
136378
136379struct ColumnIndex {
136380public:
136383 }
136384 explicit ColumnIndex(idx_t index)
136386 }
136387 explicit ColumnIndex(const string &field)
136389 }
136390
136391 ColumnIndex(idx_t index, vector<ColumnIndex> child_indexes_p)
136393 child_indexes(std::move(child_indexes_p)) {
136394 }
136395 ColumnIndex(const string &field, vector<ColumnIndex> child_indexes_p)
136397 child_indexes(std::move(child_indexes_p)) {
136398 }
136399
136400 inline bool operator==(
const ColumnIndex &rhs)
const {
136401 if (has_index != rhs.has_index) {
136402 return false;
136403 }
136404 if (has_index) {
136405 if (index != rhs.index) {
136406 return false;
136407 }
136408 } else {
136409 if (field != rhs.field) {
136410 return false;
136411 }
136412 }
136413 if (type != rhs.type) {
136414 return false;
136415 }
136417 return false;
136418 }
136419
136420 if (child_indexes.size() != rhs.child_indexes.size()) {
136421 return false;
136422 }
136423 for (idx_t i = 0; i < child_indexes.size(); i++) {
136424 auto &a = child_indexes[i];
136425 auto &b = rhs.child_indexes[i];
136426 if (a != b) {
136427 return false;
136428 }
136429 }
136430 return true;
136431 }
136432 inline bool operator!=(
const ColumnIndex &rhs)
const {
136433 return !(*this == rhs);
136434 }
136435 inline bool operator<(
const ColumnIndex &rhs)
const {
136437 return index < rhs.index;
136438 }
136439
136440public:
136441 bool HasPrimaryIndex() const {
136442 return has_index;
136443 }
136444 idx_t GetPrimaryIndex()
const {
136445 if (!has_index) {
136446 throw InternalException("Attempted to get the primary index (numeric) for an index that consists of a "
136447 "field identifier (string: %s)",
136448 field);
136449 }
136451 }
136452 const string &GetFieldName() const {
136453 if (has_index) {
136454 throw InternalException("Attempted to get the field identifier (string) for an index that consists of a "
136455 "primary index (numeric: %d)",
136456 index);
136457 }
136458 return field;
136459 }
136460 LogicalIndex ToLogical() const {
136461 return LogicalIndex(GetPrimaryIndex());
136462 }
136463 bool HasChildren() const {
136464 return !child_indexes.empty();
136465 }
136466 bool HasType() const {
136467 return type.id() != LogicalTypeId::INVALID;
136468 }
136469 idx_t ChildIndexCount()
const {
136470 return child_indexes.size();
136471 }
136472 const ColumnIndex &GetChildIndex(idx_t idx) const {
136473 return child_indexes[idx];
136474 }
136475 ColumnIndex &GetChildIndex(idx_t idx) {
136476 return child_indexes[idx];
136477 }
136478 const vector<ColumnIndex> &GetChildIndexes() const {
136479 return child_indexes;
136480 }
136481 vector<ColumnIndex> &GetChildIndexesMutable() {
136482 return child_indexes;
136483 }
136484
136485 bool IsPushdownExtract() const {
136486 return index_type == ColumnIndexType::PUSHDOWN_EXTRACT;
136487 }
136488 void SetType(const LogicalType &type_information) {
136489 type = type_information;
136490 }
136491 void SetPushdownExtractType(const LogicalType &type_information,
136492 optional_ptr<const LogicalType> cast_type = nullptr) {
136494 index_type = ColumnIndexType::PUSHDOWN_EXTRACT;
136495 type = type_information;
136496 D_ASSERT(child_indexes.size() == 1);
136497
136498 auto &child = child_indexes[0];
136499 if (child.HasPrimaryIndex()) {
136500 auto &child_types = StructType::GetChildTypes(type);
136501 auto &child_type = child_types[child.GetPrimaryIndex()].second;
136502 if (child.child_indexes.empty()) {
136503 if (cast_type) {
136504 child.SetType(*cast_type);
136505 } else {
136506 child.SetType(child_type);
136507 }
136508 } else {
136509 child.SetPushdownExtractType(child_type, cast_type);
136510 }
136511 } else {
136512 D_ASSERT(type_information.id() == LogicalTypeId::VARIANT);
136513 if (child.child_indexes.empty()) {
136514 if (cast_type) {
136515 child.SetType(*cast_type);
136516 } else {
136518 child.SetType(type_information);
136519 }
136520 } else {
136521 child.SetPushdownExtractType(type_information, cast_type);
136522 }
136523 }
136524 }
136525 const LogicalType &GetScanType() const {
136526 D_ASSERT(HasType());
136527 if (IsPushdownExtract()) {
136528 return child_indexes[0].GetScanType();
136529 }
136530 return GetType();
136531 }
136532 const LogicalType &GetType() const {
136533 D_ASSERT(type.id() != LogicalTypeId::INVALID);
136534 return type;
136535 }
136536 void AddChildIndex(ColumnIndex new_index) {
136537 this->child_indexes.push_back(std::move(new_index));
136538 }
136539 bool IsRowIdColumn() const {
136540 if (!has_index) {
136541 return false;
136542 }
136544 }
136545 bool IsEmptyColumn() const {
136546 if (!has_index) {
136547 return false;
136548 }
136550 }
136551 bool IsVirtualColumn() const {
136552 if (!has_index) {
136553 return false;
136554 }
136555 return index >= VIRTUAL_COLUMN_START;
136556 }
136557 void VerifySinglePath() const {
136558 if (child_indexes.empty()) {
136559 return;
136560 }
136561 if (child_indexes.size() != 1) {
136562 throw InternalException(
136563 "We were expecting to find a single path in the index, meaning 0 or 1 children, found: %d",
136564 child_indexes.size());
136565 }
136566 child_indexes[0].VerifySinglePath();
136567 }
136568 bool IsChildPathOf(const ColumnIndex &path) const {
136569 VerifySinglePath();
136570 path.VerifySinglePath();
136571 reference<const ColumnIndex> a(*this);
136572 reference<const ColumnIndex> b(path);
136573
136574 while (true) {
136575 if (a.get().HasPrimaryIndex()) {
136576 if (!b.get().HasPrimaryIndex()) {
136577 return false;
136578 }
136579 if (a.get().GetPrimaryIndex() != b.get().GetPrimaryIndex()) {
136580 return false;
136581 }
136582 } else {
136583 if (b.get().HasPrimaryIndex()) {
136584 return false;
136585 }
136586 if (a.get().GetFieldName() != b.get().GetFieldName()) {
136587 return false;
136588 }
136589 }
136590 const bool a_has_children = a.get().HasChildren();
136591 const bool b_has_children = b.get().HasChildren();
136592 if (!a_has_children && !b_has_children) {
136593 return false;
136594 }
136595 if (!a_has_children) {
136597 return false;
136598 }
136599 if (!b_has_children) {
136601 return true;
136602 }
136603 a = a.get().GetChildIndexes()[0];
136604 b = b.get().GetChildIndexes()[0];
136605 }
136606 return true;
136607 }
136608
136609public:
136610 void Serialize(Serializer &serializer) const;
136611 static ColumnIndex Deserialize(Deserializer &deserializer);
136612
136613private:
136615 bool has_index = true;
136618 string field;
136619
136621 LogicalType type = LogicalType::INVALID;
136624 vector<ColumnIndex> child_indexes;
136625};
136626
136627}
136628
136629
136630namespace duckdb {
136631
136633
136634struct StorageIndex {
136635public:
136636 StorageIndex();
136637 explicit StorageIndex(idx_t index);
136638 explicit StorageIndex(const string &field);
136639 StorageIndex(idx_t index, vector<StorageIndex> child_indexes_p);
136640 StorageIndex(const string &field, vector<StorageIndex> child_indexes_p);
136641
136642 inline bool operator==(
const StorageIndex &rhs)
const {
136643 return index == rhs.index;
136644 }
136645 inline bool operator!=(
const StorageIndex &rhs)
const {
136646 return index != rhs.index;
136647 }
136648 inline bool operator<(
const StorageIndex &rhs)
const {
136649 return index < rhs.index;
136650 }
136651
136652public:
136653 static StorageIndex FromColumnIndex(const ColumnIndex &column_id);
136654
136655public:
136656 bool HasPrimaryIndex() const;
136657 idx_t GetPrimaryIndex()
const;
136658 const string &GetFieldName() const;
136659 PhysicalIndex ToPhysical() const;
136660 bool HasType() const;
136661 const LogicalType &GetScanType() const;
136662 const LogicalType &GetType() const;
136663 bool HasChildren() const;
136664 idx_t ChildIndexCount()
const;
136665 const StorageIndex &GetChildIndex(idx_t idx) const;
136666 StorageIndex &GetChildIndex(idx_t idx);
136667 const vector<StorageIndex> &GetChildIndexes() const;
136668 void AddChildIndex(StorageIndex new_index);
136669 void SetType(const LogicalType &type_information);
136670 void SetPushdownExtract();
136671 bool IsPushdownExtract() const;
136672 void SetIndex(idx_t new_index);
136673 bool IsRowIdColumn() const;
136674
136675 void Serialize(Serializer &serializer) const;
136676 static StorageIndex Deserialize(Deserializer &deserializer);
136677
136678private:
136679 bool has_index = true;
136681 string field;
136682
136683 LogicalType type = LogicalType::INVALID;
136685 vector<StorageIndex> child_indexes;
136686};
136687
136688}
136689
136690
136691
136692
136693
136694
136695
136696
136697
136698
136699
136700
136701
136702
136703
136704
136705
136706
136707
136708
136709
136710
136711
136712
136713
136714namespace duckdb {
136715
136716enum class FilterPropagateResult :
uint8_t {
136717 NO_PRUNING_POSSIBLE = 0,
136718 FILTER_ALWAYS_TRUE = 1,
136719 FILTER_ALWAYS_FALSE = 2,
136720 FILTER_TRUE_OR_NULL = 3,
136721 FILTER_FALSE_OR_NULL = 4
136722};
136723
136724}
136725
136726
136727
136728
136729
136730
136731
136732
136733
136734
136735
136736
136737
136738
136739
136740namespace duckdb {
136741
136742struct NumericValueUnion {
136743 union Val {
136744 bool boolean;
136753 hugeint_t hugeint;
136754 uhugeint_t uhugeint;
136755 float float_;
136756 double double_;
136757 } value_;
136758
136759 template <class T>
136760 T &GetReferenceUnsafe();
136761};
136762
136763template <>
136764DUCKDB_API inline bool &NumericValueUnion::GetReferenceUnsafe() {
136765 return value_.boolean;
136766}
136767
136768template <>
136769DUCKDB_API
inline int8_t &NumericValueUnion::GetReferenceUnsafe() {
136770 return value_.tinyint;
136771}
136772
136773template <>
136774DUCKDB_API
inline int16_t &NumericValueUnion::GetReferenceUnsafe() {
136775 return value_.smallint;
136776}
136777
136778template <>
136779DUCKDB_API
inline int32_t &NumericValueUnion::GetReferenceUnsafe() {
136780 return value_.integer;
136781}
136782
136783template <>
136784DUCKDB_API
inline int64_t &NumericValueUnion::GetReferenceUnsafe() {
136785 return value_.bigint;
136786}
136787
136788template <>
136789DUCKDB_API inline hugeint_t &NumericValueUnion::GetReferenceUnsafe() {
136790 return value_.hugeint;
136791}
136792
136793template <>
136794DUCKDB_API inline uhugeint_t &NumericValueUnion::GetReferenceUnsafe() {
136795 return value_.uhugeint;
136796}
136797
136798template <>
136799DUCKDB_API
inline uint8_t &NumericValueUnion::GetReferenceUnsafe() {
136800 return value_.utinyint;
136801}
136802
136803template <>
136804DUCKDB_API
inline uint16_t &NumericValueUnion::GetReferenceUnsafe() {
136805 return value_.usmallint;
136806}
136807
136808template <>
136809DUCKDB_API
inline uint32_t &NumericValueUnion::GetReferenceUnsafe() {
136810 return value_.uinteger;
136811}
136812
136813template <>
136814DUCKDB_API
inline uint64_t &NumericValueUnion::GetReferenceUnsafe() {
136815 return value_.ubigint;
136816}
136817
136818template <>
136819DUCKDB_API inline float &NumericValueUnion::GetReferenceUnsafe() {
136820 return value_.float_;
136821}
136822
136823template <>
136824DUCKDB_API inline double &NumericValueUnion::GetReferenceUnsafe() {
136825 return value_.double_;
136826}
136827
136828}
136829
136830
136831
136832
136833
136834
136835
136836
136837
136838
136839
136840
136841
136842
136843
136844namespace duckdb {
136845
136846template <class DATA_TYPE>
136847class array_ptr_iterator {
136848public:
136849 array_ptr_iterator(DATA_TYPE *ptr, idx_t index, idx_t size) : ptr(ptr),
index(
index),
size(
size) {
136850 }
136851
136852public:
136853 array_ptr_iterator<DATA_TYPE> &operator++() {
136855 if (index > size) {
136857 }
136858 return *this;
136859 }
136860 bool operator!=(
const array_ptr_iterator<DATA_TYPE> &other)
const {
136861 return ptr != other.ptr ||
index != other.index ||
size != other.size;
136862 }
136864 if (DUCKDB_UNLIKELY(index >= size)) {
136865 throw InternalException("array_ptr iterator dereferenced while iterator is out of range");
136866 }
136867 return ptr[
index];
136868 }
136869
136870private:
136871 DATA_TYPE *ptr;
136874};
136875
136877template <class DATA_TYPE, bool SAFE = true>
136878class array_ptr {
136879public:
136880 using iterator_type = array_ptr_iterator<DATA_TYPE>;
136881
136882private:
136883 static inline void AssertNotNull(const bool null) {
136884#if defined(DUCKDB_DEBUG_NO_SAFETY) || defined(DUCKDB_CLANG_TIDY)
136885 return;
136886#else
136887 if (DUCKDB_UNLIKELY(null)) {
136888 throw duckdb::InternalException("Attempted to construct an array_ptr from a NULL pointer");
136889 }
136890#endif
136891 }
136892
136893 static inline void AssertIndexInBounds(idx_t index, idx_t size) {
136894#if defined(DUCKDB_DEBUG_NO_SAFETY) || defined(DUCKDB_CLANG_TIDY)
136895 return;
136896#else
136897 if (DUCKDB_UNLIKELY(index >= size)) {
136898 throw InternalException("Attempted to access index %ld within array_ptr of size %ld", index, size);
136899 }
136900#endif
136901 }
136902
136903public:
136904 array_ptr(DATA_TYPE *ptr_p, idx_t count) : ptr(ptr_p), count(count) {
136905 if (MemorySafety<SAFE>::ENABLED) {
136906 AssertNotNull(!ptr);
136907 }
136908 }
136909 explicit array_ptr(DATA_TYPE &ref) : ptr(&ref), count(1) {
136910 }
136911
136912 const DATA_TYPE &operator[](idx_t idx) const {
136913 if (MemorySafety<SAFE>::ENABLED) {
136914 AssertIndexInBounds(idx, count);
136915 }
136916 return ptr[idx];
136917 }
136918
136919 DATA_TYPE &operator[](idx_t idx) {
136920 if (MemorySafety<SAFE>::ENABLED) {
136921 AssertIndexInBounds(idx, count);
136922 }
136923 return ptr[idx];
136924 }
136925
136927 return count;
136928 }
136929
136930 array_ptr_iterator<DATA_TYPE> begin() {
136931 return array_ptr_iterator<DATA_TYPE>(ptr, 0, count);
136932 }
136933 array_ptr_iterator<DATA_TYPE> begin() const {
136934 return array_ptr_iterator<const DATA_TYPE>(ptr, 0, count);
136935 }
136936 array_ptr_iterator<DATA_TYPE> cbegin() {
136937 return array_ptr_iterator<const DATA_TYPE>(ptr, 0, count);
136938 }
136939 array_ptr_iterator<DATA_TYPE> end() {
136940 return array_ptr_iterator<DATA_TYPE>(ptr, count, count);
136941 }
136942 array_ptr_iterator<DATA_TYPE> end() const {
136943 return array_ptr_iterator<const DATA_TYPE>(ptr, count, count);
136944 }
136945 array_ptr_iterator<DATA_TYPE> cend() {
136946 return array_ptr_iterator<const DATA_TYPE>(ptr, count, count);
136947 }
136948
136949private:
136950 DATA_TYPE *ptr;
136952};
136953
136954template <typename T>
136955using unsafe_array_ptr = array_ptr<T, false>;
136956
136957}
136958
136959
136960namespace duckdb {
136961class BaseStatistics;
136962struct SelectionVector;
136963class Vector;
136964
136965struct NumericStatsData {
136967 bool has_min;
136969 bool has_max;
136971 NumericValueUnion
min;
136973 NumericValueUnion
max;
136974};
136975
136976struct NumericStats {
136978 DUCKDB_API static BaseStatistics CreateUnknown(LogicalType type);
136980 DUCKDB_API static BaseStatistics CreateEmpty(LogicalType type);
136981
136983 DUCKDB_API static bool IsConstant(const BaseStatistics &stats);
136985 DUCKDB_API static bool HasMinMax(const BaseStatistics &stats);
136987 DUCKDB_API static bool HasMin(const BaseStatistics &stats);
136989 DUCKDB_API static bool HasMax(const BaseStatistics &stats);
136991 DUCKDB_API static Value Min(const BaseStatistics &stats);
136993 DUCKDB_API static Value Max(const BaseStatistics &stats);
136995 DUCKDB_API static void SetMin(BaseStatistics &stats, const Value &val);
136997 DUCKDB_API static void SetMax(BaseStatistics &stats, const Value &val);
136998
136999 template <class T>
137000 static void SetMax(BaseStatistics &stats, T val) {
137001 auto &nstats = GetDataUnsafe(stats);
137002 nstats.has_max = true;
137003 nstats.max.GetReferenceUnsafe<T>() = val;
137004 }
137005
137006 template <class T>
137007 static void SetMin(BaseStatistics &stats, T val) {
137008 auto &nstats = GetDataUnsafe(stats);
137009 nstats.has_min = true;
137010 nstats.min.GetReferenceUnsafe<T>() = val;
137011 }
137012
137014 DUCKDB_API static FilterPropagateResult CheckZonemap(const BaseStatistics &stats, ExpressionType comparison_type,
137015 array_ptr<const Value> constants);
137016
137017 DUCKDB_API static void Merge(BaseStatistics &stats, const BaseStatistics &other_p);
137018
137019 DUCKDB_API static void Serialize(const BaseStatistics &stats, Serializer &serializer);
137020 DUCKDB_API static void Deserialize(Deserializer &deserializer, BaseStatistics &stats);
137021
137022 DUCKDB_API static string ToString(const BaseStatistics &stats);
137023
137024 template <class T>
137025 static inline void UpdateValue(T new_value, T &
min, T &
max) {
137026 min = LessThan::Operation(new_value,
min) ? new_value :
min;
137027 max = GreaterThan::Operation(new_value,
max) ? new_value :
max;
137028 }
137029 template <class T>
137030 static inline void Update(NumericStatsData &nstats, T new_value) {
137031 UpdateValue<T>(new_value, nstats.min.GetReferenceUnsafe<T>(), nstats.max.GetReferenceUnsafe<T>());
137032 }
137033
137034 static void Verify(const BaseStatistics &stats, Vector &vector, const SelectionVector &sel, idx_t count);
137035
137036 template <class T>
137037 static T GetMin(const BaseStatistics &stats) {
137038 return NumericStats::Min(stats).GetValueUnsafe<T>();
137039 }
137040 template <class T>
137041 static T GetMax(const BaseStatistics &stats) {
137042 return NumericStats::Max(stats).GetValueUnsafe<T>();
137043 }
137044 template <class T>
137045 static T GetMinUnsafe(const BaseStatistics &stats);
137046 template <class T>
137047 static T GetMaxUnsafe(const BaseStatistics &stats);
137048
137049private:
137050 static NumericStatsData &GetDataUnsafe(BaseStatistics &stats);
137051 static const NumericStatsData &GetDataUnsafe(const BaseStatistics &stats);
137052 static Value MinOrNull(const BaseStatistics &stats);
137053 static Value MaxOrNull(const BaseStatistics &stats);
137054 template <class T>
137055 static void TemplatedVerify(const BaseStatistics &stats, Vector &vector, const SelectionVector &sel, idx_t count);
137056};
137057
137058}
137059
137060
137061
137062
137063
137064
137065
137066
137067
137068
137069
137070
137071
137072
137073
137074
137075
137076namespace duckdb {
137077class BaseStatistics;
137078struct SelectionVector;
137079class Vector;
137080
137081struct StringStatsData {
137082 constexpr static uint32_t MAX_STRING_MINMAX_SIZE = 8;
137083
137089 bool has_unicode;
137091 bool has_max_string_length;
137094};
137095
137096struct StringStats {
137098 DUCKDB_API static BaseStatistics CreateUnknown(LogicalType type);
137100 DUCKDB_API static BaseStatistics CreateEmpty(LogicalType type);
137102 DUCKDB_API static bool HasMaxStringLength(const BaseStatistics &stats);
137104 DUCKDB_API
static uint32_t MaxStringLength(
const BaseStatistics &stats);
137106 DUCKDB_API static bool CanContainUnicode(const BaseStatistics &stats);
137108 DUCKDB_API static string Min(const BaseStatistics &stats);
137110 DUCKDB_API static string Max(const BaseStatistics &stats);
137111
137113 DUCKDB_API static void ResetMaxStringLength(BaseStatistics &stats);
137115 DUCKDB_API static void SetMaxStringLength(BaseStatistics &stats, uint32_t length);
137117 DUCKDB_API static void SetContainsUnicode(BaseStatistics &stats);
137118
137119 DUCKDB_API static void Serialize(const BaseStatistics &stats, Serializer &serializer);
137120 DUCKDB_API static void Deserialize(Deserializer &deserializer, BaseStatistics &base);
137121
137122 DUCKDB_API static string ToString(const BaseStatistics &stats);
137123
137124 DUCKDB_API static FilterPropagateResult CheckZonemap(const BaseStatistics &stats, ExpressionType comparison_type,
137125 array_ptr<const Value> constants);
137126 DUCKDB_API static FilterPropagateResult CheckZonemap(const_data_ptr_t min_data, idx_t min_len,
137127 const_data_ptr_t max_data, idx_t max_len,
137128 ExpressionType comparison_type, const string &value);
137129
137130 DUCKDB_API static void Update(BaseStatistics &stats, const string_t &value);
137131 DUCKDB_API static void SetMin(BaseStatistics &stats, const string_t &value);
137132 DUCKDB_API static void SetMax(BaseStatistics &stats, const string_t &value);
137133 DUCKDB_API static void Merge(BaseStatistics &stats, const BaseStatistics &other);
137134 DUCKDB_API static void Verify(const BaseStatistics &stats, Vector &vector, const SelectionVector &sel, idx_t count);
137135
137136private:
137137 static StringStatsData &GetDataUnsafe(BaseStatistics &stats);
137138 static const StringStatsData &GetDataUnsafe(const BaseStatistics &stats);
137139};
137140
137141}
137142
137143
137144
137145
137146
137147
137148
137149
137150
137151
137152
137153
137154
137155
137156
137157
137158
137159
137160
137161
137162
137163
137164
137165
137166
137167
137168
137169#include <limits>
137170#include <cmath>
137171
137172namespace duckdb {
137173
137174struct GeometryStatsData;
137175
137176enum class GeometryType :
uint8_t {
137177 INVALID = 0,
137178 POINT = 1,
137179 LINESTRING = 2,
137181 MULTIPOINT = 4,
137182 MULTILINESTRING = 5,
137183 MULTIPOLYGON = 6,
137184 GEOMETRYCOLLECTION = 7,
137185};
137186
137187enum class VertexType :
uint8_t { XY = 0,
XYZ = 1, XYM = 2, XYZM = 3 };
137188
137189struct VertexXY {
137190 static constexpr auto TYPE = VertexType::XY;
137191 static constexpr auto HAS_Z = false;
137192 static constexpr auto HAS_M = false;
137193 static constexpr auto WIDTH = 2;
137194
137195 double x;
137196 double y;
137197
137198 bool AllNan() const {
137199 return std::isnan(x) && std::isnan(y);
137200 }
137201};
137202
137203struct VertexXYZ {
137204 static constexpr auto TYPE = VertexType::XYZ;
137205 static constexpr auto HAS_Z = true;
137206 static constexpr auto HAS_M = false;
137207 static constexpr auto WIDTH = 3;
137208
137209 double x;
137210 double y;
137212
137213 bool AllNan() const {
137214 return std::isnan(x) && std::isnan(y) && std::isnan(z);
137215 }
137216};
137217struct VertexXYM {
137218 static constexpr auto TYPE = VertexType::XYM;
137219 static constexpr auto HAS_M = true;
137220 static constexpr auto HAS_Z = false;
137221 static constexpr auto WIDTH = 3;
137222
137223 double x;
137224 double y;
137225 double m;
137226
137227 bool AllNan() const {
137228 return std::isnan(x) && std::isnan(y) && std::isnan(m);
137229 }
137230};
137231
137232struct VertexXYZM {
137233 static constexpr auto TYPE = VertexType::XYZM;
137234 static constexpr auto HAS_Z = true;
137235 static constexpr auto HAS_M = true;
137236 static constexpr auto WIDTH = 4;
137237
137238 double x;
137239 double y;
137241 double m;
137242
137243 bool AllNan() const {
137244 return std::isnan(x) && std::isnan(y) && std::isnan(z) && std::isnan(m);
137245 }
137246};
137247
137248class GeometryExtent {
137249public:
137250 static constexpr auto UNKNOWN_MIN = -std::numeric_limits<double>::infinity();
137251 static constexpr auto UNKNOWN_MAX = +std::numeric_limits<double>::infinity();
137252
137253 static constexpr auto EMPTY_MIN = +std::numeric_limits<double>::infinity();
137254 static constexpr auto EMPTY_MAX = -std::numeric_limits<double>::infinity();
137255
137256
137257
137258
137259 static GeometryExtent Unknown() {
137260 return GeometryExtent {UNKNOWN_MIN, UNKNOWN_MIN, UNKNOWN_MIN, UNKNOWN_MIN,
137261 UNKNOWN_MAX, UNKNOWN_MAX, UNKNOWN_MAX, UNKNOWN_MAX};
137262 }
137263
137264
137265
137266
137267 static GeometryExtent Empty() {
137268 return GeometryExtent {EMPTY_MIN, EMPTY_MIN, EMPTY_MIN, EMPTY_MIN, EMPTY_MAX, EMPTY_MAX, EMPTY_MAX, EMPTY_MAX};
137269 }
137270
137271
137272
137273 bool HasXY() const {
137274 return std::isfinite(x_min) && std::isfinite(y_min) && std::isfinite(x_max) && std::isfinite(y_max);
137275 }
137276
137277
137278 bool HasZ() const {
137279 return std::isfinite(z_min) && std::isfinite(z_max);
137280 }
137281
137282
137283 bool HasM() const {
137284 return std::isfinite(m_min) && std::isfinite(m_max);
137285 }
137286
137287 void Extend(const VertexXY &vertex) {
137288 x_min = MinValue(x_min, vertex.x);
137289 x_max = MaxValue(x_max, vertex.x);
137290 y_min = MinValue(y_min, vertex.y);
137291 y_max = MaxValue(y_max, vertex.y);
137292 }
137293
137294 void Extend(const VertexXYZ &vertex) {
137295 x_min = MinValue(x_min, vertex.x);
137296 x_max = MaxValue(x_max, vertex.x);
137297 y_min = MinValue(y_min, vertex.y);
137298 y_max = MaxValue(y_max, vertex.y);
137299 z_min = MinValue(z_min, vertex.z);
137300 z_max = MaxValue(z_max, vertex.z);
137301 }
137302
137303 void Extend(const VertexXYM &vertex) {
137304 x_min = MinValue(x_min, vertex.x);
137305 x_max = MaxValue(x_max, vertex.x);
137306 y_min = MinValue(y_min, vertex.y);
137307 y_max = MaxValue(y_max, vertex.y);
137308 m_min = MinValue(m_min, vertex.m);
137309 m_max = MaxValue(m_max, vertex.m);
137310 }
137311
137312 void Extend(const VertexXYZM &vertex) {
137313 x_min = MinValue(x_min, vertex.x);
137314 x_max = MaxValue(x_max, vertex.x);
137315 y_min = MinValue(y_min, vertex.y);
137316 y_max = MaxValue(y_max, vertex.y);
137317 z_min = MinValue(z_min, vertex.z);
137318 z_max = MaxValue(z_max, vertex.z);
137319 m_min = MinValue(m_min, vertex.m);
137320 m_max = MaxValue(m_max, vertex.m);
137321 }
137322
137323 void Merge(const GeometryExtent &other) {
137324 x_min = MinValue(x_min, other.x_min);
137325 y_min = MinValue(y_min, other.y_min);
137326 z_min = MinValue(z_min, other.z_min);
137327 m_min = MinValue(m_min, other.m_min);
137328
137329 x_max = MaxValue(x_max, other.x_max);
137330 y_max = MaxValue(y_max, other.y_max);
137331 z_max = MaxValue(z_max, other.z_max);
137332 m_max = MaxValue(m_max, other.m_max);
137333 }
137334
137335 bool IntersectsXY(const GeometryExtent &other) const {
137336 return !(x_min > other.x_max || x_max < other.x_min || y_min > other.y_max || y_max < other.y_min);
137337 }
137338
137339 bool IntersectsXYZM(const GeometryExtent &other) const {
137340 return !(x_min > other.x_max || x_max < other.x_min || y_min > other.y_max || y_max < other.y_min ||
137341 z_min > other.z_max || z_max < other.z_min || m_min > other.m_max || m_max < other.m_min);
137342 }
137343
137344 bool ContainsXY(const GeometryExtent &other) const {
137345 return x_min <= other.x_min && x_max >= other.x_max && y_min <= other.y_min && y_max >= other.y_max;
137346 }
137347
137348 double x_min;
137349 double y_min;
137350 double z_min;
137351 double m_min;
137352
137353 double x_max;
137354 double y_max;
137355 double z_max;
137356 double m_max;
137357};
137358
137359enum class GeometryStorageType :
uint8_t {
137360
137361 SPATIAL = 0,
137362 WKB = 1,
137363
137364
137365 POINT_XY = 17,
137366 LINESTRING_XY = 18,
137367 POLYGON_XY = 19,
137368 MULTIPOINT_XY = 20,
137369 MULTILINESTRING_XY = 21,
137370 MULTIPOLYGON_XY = 22,
137371
137372
137373 POINT_XYZ = 33,
137374 LINESTRING_XYZ = 34,
137375 POLYGON_XYZ = 35,
137376 MULTIPOINT_XYZ = 36,
137377 MULTILINESTRING_XYZ = 37,
137378 MULTIPOLYGON_XYZ = 38,
137379
137380
137381 POINT_XYM = 65,
137382 LINESTRING_XYM = 66,
137383 POLYGON_XYM = 67,
137384 MULTIPOINT_XYM = 68,
137385 MULTILINESTRING_XYM = 69,
137386 MULTIPOLYGON_XYM = 70,
137387
137388
137389 POINT_XYZM = 97,
137390 LINESTRING_XYZM = 98,
137391 POLYGON_XYZM = 99,
137392 MULTIPOINT_XYZM = 100,
137393 MULTILINESTRING_XYZM = 101,
137394 MULTIPOLYGON_XYZM = 102,
137395};
137396
137397class Geometry {
137398public:
137399 static constexpr idx_t MAX_RECURSION_DEPTH = 16;
137400 static constexpr idx_t VERSION_ADDED = 7;
137401
137403 static bool IsSpatialGeometryType(const LogicalType &type);
137405 static LogicalType GetSpatialGeometryType();
137406
137408 DUCKDB_API static bool FromString(const string_t &wkt_text, string_t &result, Vector &result_vector, bool strict);
137409 DUCKDB_API static bool FromString(const string_t &wkt_text, string_t &result, Vector &result_vector, bool strict,
137410 optional_idx query_location);
137411
137413 DUCKDB_API static string_t ToString(Vector &result, const string_t &geom);
137414
137416 DUCKDB_API static bool FromBinary(const string_t &wkb, string_t &result, Vector &result_vector, bool strict);
137417 DUCKDB_API static bool FromBinary(Vector &source, Vector &result, idx_t count, bool strict);
137418
137420 DUCKDB_API static void ToBinary(Vector &source, Vector &result, idx_t count);
137421
137423 DUCKDB_API static pair<GeometryType, VertexType> GetType(const string_t &wkb);
137424
137426 DUCKDB_API
static uint32_t GetExtent(
const string_t &wkb, GeometryExtent &extent);
137427 DUCKDB_API
static uint32_t GetExtent(
const string_t &wkb, GeometryExtent &extent,
bool &has_any_empty);
137428
137430 DUCKDB_API static void ToVectorizedFormat(Vector &source, Vector &target, idx_t count, GeometryType geom_type,
137431 VertexType vert_type);
137432 DUCKDB_API static void ToVectorizedFormat(Vector &source, Vector &target, idx_t count, GeometryStorageType type);
137434 DUCKDB_API static void FromVectorizedFormat(Vector &source, Vector &target, idx_t count, GeometryType geom_type,
137435 VertexType vert_type, idx_t result_offset);
137436 DUCKDB_API static void FromVectorizedFormat(Vector &source, Vector &target, idx_t count, GeometryStorageType type,
137437 idx_t result_offset);
137438
137440 DUCKDB_API static LogicalType GetVectorizedType(GeometryStorageType type);
137441 DUCKDB_API static LogicalType GetVectorizedType(GeometryType geom_type, VertexType vert_type);
137442
137443 DUCKDB_API static pair<GeometryType, VertexType> GetSpecializedType(GeometryStorageType type);
137444
137445 DUCKDB_API static void FromSpatialGeometry(const string_t &source, string_t &target, Vector &vector);
137446 DUCKDB_API static void FromSpatialGeometry(Vector &source, Vector &target, idx_t count, idx_t result_offset);
137447 DUCKDB_API static void FromSpatialGeometry(const string_t &source, string &target);
137448
137449 DUCKDB_API static void ToSpatialGeometry(const string_t &source, string_t &target, Vector &vector);
137450 DUCKDB_API static void ToSpatialGeometry(Vector &source, Vector &target, idx_t count);
137451 DUCKDB_API static void ToSpatialGeometry(const string_t &source, string &target);
137452};
137453
137454}
137455
137456
137457namespace duckdb {
137458class BaseStatistics;
137459struct SelectionVector;
137460
137461class GeometryTypeSet {
137462public:
137463 static constexpr auto VERT_TYPES = 4;
137464 static constexpr auto PART_TYPES = 8;
137465
137466 static GeometryTypeSet Unknown() {
137467 GeometryTypeSet result;
137468 for (idx_t i = 0; i < VERT_TYPES; i++) {
137469 result.sets[i] = 0xFF;
137470 }
137471 return result;
137472 }
137473 static GeometryTypeSet Empty() {
137474 GeometryTypeSet result;
137475 for (idx_t i = 0; i < VERT_TYPES; i++) {
137476 result.sets[i] = 0;
137477 }
137478 return result;
137479 }
137480
137481 bool IsEmpty() const {
137482 for (idx_t i = 0; i < VERT_TYPES; i++) {
137483 if (sets[i] != 0) {
137484 return false;
137485 }
137486 }
137487 return true;
137488 }
137489
137490 bool IsUnknown() const {
137491 for (idx_t i = 0; i < VERT_TYPES; i++) {
137492 if (sets[i] != 0xFF) {
137493 return false;
137494 }
137495 }
137496 return true;
137497 }
137498
137499 void Add(GeometryType geom_type, VertexType vert_type) {
137500 const auto vert_idx =
static_cast<uint8_t>(vert_type);
137501 const auto geom_idx =
static_cast<uint8_t>(geom_type);
137502 D_ASSERT(vert_idx < VERT_TYPES);
137503 D_ASSERT(geom_idx < PART_TYPES);
137504 sets[vert_idx] |= (1 << geom_idx);
137505 }
137506
137507 void Merge(const GeometryTypeSet &other) {
137508 for (idx_t i = 0; i < VERT_TYPES; i++) {
137509 sets[i] |= other.sets[i];
137510 }
137511 }
137512
137513 void Clear() {
137514 for (idx_t i = 0; i < VERT_TYPES; i++) {
137515 sets[i] = 0;
137516 }
137517 }
137518
137521 bool HasOnly(GeometryType geom_type, VertexType vert_type) const {
137522 const auto vert_idx =
static_cast<uint8_t>(vert_type);
137523 const auto geom_idx =
static_cast<uint8_t>(geom_type);
137524 D_ASSERT(vert_idx < VERT_TYPES);
137525 D_ASSERT(geom_idx < PART_TYPES);
137526 for (uint8_t v_idx = 0; v_idx < VERT_TYPES; v_idx++) {
137527 for (uint8_t g_idx = 1; g_idx < PART_TYPES; g_idx++) {
137528 if (v_idx == vert_idx && g_idx == geom_idx) {
137529 if (!(sets[v_idx] & (1 << g_idx))) {
137530 return false;
137531 }
137532 } else {
137533 if (sets[v_idx] & (1 << g_idx)) {
137534 return false;
137535 }
137536 }
137537 }
137538 }
137539 return true;
137540 }
137541
137542 bool HasSingleType() const {
137543 idx_t type_count = 0;
137544 for (uint8_t v_idx = 0; v_idx < VERT_TYPES; v_idx++) {
137545 for (uint8_t g_idx = 1; g_idx < PART_TYPES; g_idx++) {
137546 if (sets[v_idx] & (1 << g_idx)) {
137547 type_count++;
137548 if (type_count > 1) {
137549 return false;
137550 }
137551 }
137552 }
137553 }
137554 return type_count == 1;
137555 }
137556
137557 bool TryGetSingleType(GeometryType &geom_type, VertexType &vert_type) const {
137558 auto result_geom = GeometryType::INVALID;
137559 auto result_vert = VertexType::XY;
137560 auto result_found = false;
137561
137562 for (uint8_t v_idx = 0; v_idx < VERT_TYPES; v_idx++) {
137563 for (uint8_t g_idx = 1; g_idx < PART_TYPES; g_idx++) {
137564 if (sets[v_idx] & (1 << g_idx)) {
137565 if (result_found) {
137566
137567 return false;
137568 }
137569 result_found = true;
137570 result_geom = static_cast<GeometryType>(g_idx);
137571 result_vert = static_cast<VertexType>(v_idx);
137572 }
137573 }
137574 }
137575 if (result_found) {
137576 geom_type = result_geom;
137577 vert_type = result_vert;
137578 }
137579 return result_found;
137580 }
137581
137582 void AddWKBType(int32_t wkb_type) {
137583 const auto vert_idx =
static_cast<uint8_t>((wkb_type / 1000) % 10);
137584 const auto geom_idx =
static_cast<uint8_t>(wkb_type % 1000);
137585 D_ASSERT(vert_idx < VERT_TYPES);
137586 D_ASSERT(geom_idx < PART_TYPES);
137587 sets[vert_idx] |= (1 << geom_idx);
137588 }
137589
137590 vector<int32_t> ToWKBList() const {
137591 vector<int32_t> result;
137592 for (uint8_t vert_idx = 0; vert_idx < VERT_TYPES; vert_idx++) {
137593 for (uint8_t geom_idx = 1; geom_idx < PART_TYPES; geom_idx++) {
137594 if (sets[vert_idx] & (1 << geom_idx)) {
137595 result.push_back(geom_idx + vert_idx * 1000);
137596 }
137597 }
137598 }
137599 return result;
137600 }
137601
137602 vector<string> ToString(bool snake_case) const;
137603
137605};
137606
137607class GeometryStatsFlags {
137608public:
137609
137610
137611
137612
137613 static GeometryStatsFlags Unknown() {
137614 GeometryStatsFlags flags;
137615 flags.flags = 0xF;
137616 return flags;
137617 }
137618
137619 static GeometryStatsFlags Empty() {
137620 GeometryStatsFlags flags;
137621 flags.flags = 0x0;
137622 return flags;
137623 }
137624 void Clear() {
137625 flags = 0x0;
137626 }
137627 bool HasEmptyGeometry() const {
137628 return (flags & HAS_EMPTY_GEOM) != 0;
137629 }
137630 bool HasNonEmptyGeometry() const {
137631 return (flags & HAS_NON_EMPTY_GEOM) != 0;
137632 }
137633 bool HasEmptyPart() const {
137634 return (flags & HAS_EMPTY_PART) != 0;
137635 }
137636 bool HasNonEmptyPart() const {
137637 return (flags & HAS_NON_EMPTY_PART) != 0;
137638 }
137639 void SetHasEmptyGeometry() {
137640 flags |= HAS_EMPTY_GEOM;
137641 }
137642 void SetHasNonEmptyGeometry() {
137643 flags |= HAS_NON_EMPTY_GEOM;
137644 }
137645 void SetHasEmptyPart() {
137646 flags |= HAS_EMPTY_PART;
137647 }
137648 void SetHasNonEmptyPart() {
137649 flags |= HAS_NON_EMPTY_PART;
137650 }
137651
137652 void Merge(const GeometryStatsFlags &other) {
137653 flags |= other.flags;
137654 }
137655
137657
137658private:
137659 static constexpr auto HAS_EMPTY_GEOM = 0x1;
137660 static constexpr auto HAS_NON_EMPTY_GEOM = 0x2;
137661 static constexpr auto HAS_EMPTY_PART = 0x4;
137662 static constexpr auto HAS_NON_EMPTY_PART = 0x8;
137663};
137664
137665struct GeometryStatsData {
137666 GeometryTypeSet types;
137667 GeometryExtent extent;
137668 GeometryStatsFlags flags;
137669
137670 void SetEmpty() {
137671 types = GeometryTypeSet::Empty();
137672 extent = GeometryExtent::Empty();
137673 flags = GeometryStatsFlags::Empty();
137674 }
137675
137676 void SetUnknown() {
137677 types = GeometryTypeSet::Unknown();
137678 extent = GeometryExtent::Unknown();
137679 flags = GeometryStatsFlags::Unknown();
137680 }
137681
137682 void Merge(const GeometryStatsData &other) {
137683 types.Merge(other.types);
137684 extent.Merge(other.extent);
137685 flags.Merge(other.flags);
137686 }
137687
137688 void Update(const string_t &geom_blob) {
137689
137690 const auto type_info = Geometry::GetType(geom_blob);
137691 types.Add(type_info.first, type_info.second);
137692
137693
137694 bool has_any_empty = false;
137695 const auto vert_count = Geometry::GetExtent(geom_blob, extent, has_any_empty);
137696
137697
137698 if (has_any_empty) {
137699 flags.SetHasEmptyPart();
137700 } else {
137701 flags.SetHasNonEmptyPart();
137702 }
137703
137704 if (vert_count == 0) {
137705 flags.SetHasEmptyGeometry();
137706 } else {
137707 flags.SetHasNonEmptyGeometry();
137708 }
137709 }
137710};
137711
137712struct GeometryStats {
137714 DUCKDB_API static BaseStatistics CreateUnknown(LogicalType type);
137716 DUCKDB_API static BaseStatistics CreateEmpty(LogicalType type);
137717
137718 DUCKDB_API static void Serialize(const BaseStatistics &stats, Serializer &serializer);
137719 DUCKDB_API static void Deserialize(Deserializer &deserializer, BaseStatistics &base);
137720
137721 DUCKDB_API static string ToString(const BaseStatistics &stats);
137722
137723 DUCKDB_API static void Update(BaseStatistics &stats, const string_t &value);
137724 DUCKDB_API static void Merge(BaseStatistics &stats, const BaseStatistics &other);
137725 DUCKDB_API static void Verify(const BaseStatistics &stats, Vector &vector, const SelectionVector &sel, idx_t count);
137726
137728 DUCKDB_API static FilterPropagateResult CheckZonemap(const BaseStatistics &stats,
137729 const unique_ptr<Expression> &expr);
137730
137731 DUCKDB_API static GeometryExtent &GetExtent(BaseStatistics &stats);
137732 DUCKDB_API static const GeometryExtent &GetExtent(const BaseStatistics &stats);
137733 DUCKDB_API static GeometryTypeSet &GetTypes(BaseStatistics &stats);
137734 DUCKDB_API static const GeometryTypeSet &GetTypes(const BaseStatistics &stats);
137735 DUCKDB_API static GeometryStatsFlags &GetFlags(BaseStatistics &stats);
137736 DUCKDB_API static const GeometryStatsFlags &GetFlags(const BaseStatistics &stats);
137737
137738 static GeometryStatsData &GetDataUnsafe(BaseStatistics &stats);
137739 static const GeometryStatsData &GetDataUnsafe(const BaseStatistics &stats);
137740};
137741
137742}
137743
137744
137745
137746
137747
137748
137749
137750
137751
137752
137753namespace duckdb_yyjson {
137756}
137757
137758namespace duckdb {
137759class Vector;
137760struct ValidityMask;
137761struct UnifiedVariantVector;
137762struct RecursiveUnifiedVectorFormat;
137763struct UnifiedVectorFormat;
137764
137765enum class VariantChildLookupMode :
uint8_t { INVALID, BY_KEY, BY_INDEX };
137766
137767struct Variant {
137768public:
137769 static constexpr idx_t VERSION_ADDED = 7;
137770};
137771
137772struct VariantPathComponent {
137773public:
137774 explicit VariantPathComponent() : lookup_mode(VariantChildLookupMode::INVALID) {
137775 }
137776 explicit VariantPathComponent(const string &key) : lookup_mode(VariantChildLookupMode::BY_KEY), key(key) {
137777 }
137778 explicit VariantPathComponent(uint32_t index) : lookup_mode(VariantChildLookupMode::BY_INDEX),
index(
index) {
137779 }
137780
137781public:
137782 VariantChildLookupMode lookup_mode;
137783 string key;
137785};
137786
137787struct VariantNestedData {
137792};
137793
137794struct VariantDecimalData {
137795public:
137796 VariantDecimalData(uint32_t width, uint32_t scale, const_data_ptr_t value_ptr)
137797 : width(width),
scale(
scale), value_ptr(value_ptr) {
137798 }
137799
137800public:
137802
137803public:
137806 const_data_ptr_t value_ptr = nullptr;
137807};
137808
137809struct VariantVectorData {
137810public:
137811 explicit VariantVectorData(Vector &variant);
137812
137813public:
137814 Vector &variant;
137815
137817 string_t *blob_data;
137818
137822
137826 ValidityMask &keys_index_validity;
137827
137829 list_entry_t *values_data;
137830 list_entry_t *children_data;
137831 list_entry_t *keys_data;
137832
137833 Vector &keys;
137834};
137835
137836enum class VariantLogicalType :
uint8_t {
137837 VARIANT_NULL = 0,
137838 BOOL_TRUE = 1,
137839 BOOL_FALSE = 2,
137844 INT128 = 7,
137849 UINT128 = 12,
137852 DECIMAL = 15,
137853 VARCHAR = 16,
137854 BLOB = 17,
137855 UUID = 18,
137856 DATE = 19,
137857 TIME_MICROS = 20,
137858 TIME_NANOS = 21,
137859 TIMESTAMP_SEC = 22,
137860 TIMESTAMP_MILIS = 23,
137861 TIMESTAMP_MICROS = 24,
137862 TIMESTAMP_NANOS = 25,
137863 TIME_MICROS_TZ = 26,
137864 TIMESTAMP_MICROS_TZ = 27,
137865 INTERVAL = 28,
137866 OBJECT = 29,
137867 ARRAY = 30,
137868 BIGNUM = 31,
137869 BITSTRING = 32,
137870 GEOMETRY = 33,
137871 ENUM_SIZE
137872};
137873
137874struct UnifiedVariantVectorData {
137875public:
137876 explicit UnifiedVariantVectorData(const RecursiveUnifiedVectorFormat &variant);
137877
137878public:
137879 bool RowIsValid(idx_t row) const;
137880 bool KeysIndexIsValid(idx_t row, idx_t index) const;
137881 list_entry_t GetChildrenListEntry(idx_t row) const;
137882 list_entry_t GetValuesListEntry(idx_t row) const;
137883 const string_t &GetKey(idx_t row, idx_t index) const;
137884 uint32_t GetKeysIndex(idx_t row, idx_t child_index)
const;
137885 uint32_t GetValuesIndex(idx_t row, idx_t child_index)
const;
137886 VariantLogicalType
GetTypeId(idx_t row, idx_t value_index)
const;
137887 uint32_t GetByteOffset(idx_t row, idx_t value_index)
const;
137888 const string_t &GetData(idx_t row) const;
137889
137890public:
137891 const RecursiveUnifiedVectorFormat &variant;
137892 const UnifiedVectorFormat &keys;
137893 const UnifiedVectorFormat &keys_entry;
137894 const UnifiedVectorFormat &children;
137895 const UnifiedVectorFormat &keys_index;
137896 const UnifiedVectorFormat &values_index;
137897 const UnifiedVectorFormat &values;
137898 const UnifiedVectorFormat &type_id;
137899 const UnifiedVectorFormat &byte_offset;
137900 const UnifiedVectorFormat &data;
137901
137902 const list_entry_t *keys_data = nullptr;
137903 const string_t *keys_entry_data = nullptr;
137904 const list_entry_t *children_data = nullptr;
137905 const uint32_t *keys_index_data =
nullptr;
137906 const uint32_t *values_index_data =
nullptr;
137907 const list_entry_t *values_data = nullptr;
137908 const uint8_t *type_id_data =
nullptr;
137909 const uint32_t *byte_offset_data =
nullptr;
137910 const string_t *blob_data = nullptr;
137911
137912 const ValidityMask &keys_index_validity;
137913};
137914
137915struct VariantCasts {
137917 const RecursiveUnifiedVectorFormat &source, idx_t row,
137918 uint32_t values_idx);
137919};
137920
137921}
137922
137923
137924
137925
137926namespace duckdb {
137927class BaseStatistics;
137928
137931 UNINITIALIZED,
137938};
137939
137940struct VariantStatsData {
137943};
137944
137945struct VariantShreddedStats {
137946public:
137947 DUCKDB_API static bool IsFullyShredded(const BaseStatistics &stats);
137948 DUCKDB_API static optional_ptr<const BaseStatistics> FindChildStats(const BaseStatistics &stats,
137949 const VariantPathComponent &component);
137950};
137951
137956struct VariantStats {
137957public:
137958 static constexpr idx_t TYPED_VALUE_INDEX = 0;
137959 static constexpr idx_t UNTYPED_VALUE_INDEX = 1;
137960
137961public:
137962 DUCKDB_API static void Construct(BaseStatistics &stats);
137963
137964public:
137965 DUCKDB_API static BaseStatistics CreateUnknown(LogicalType type);
137966 DUCKDB_API static BaseStatistics CreateEmpty(LogicalType type);
137967 DUCKDB_API static BaseStatistics CreateShredded(const LogicalType &shredded_type);
137968
137969public:
137972 DUCKDB_API static void CreateUnshreddedStats(BaseStatistics &stats);
137973 DUCKDB_API static const BaseStatistics &GetUnshreddedStats(const BaseStatistics &stats);
137974 DUCKDB_API static BaseStatistics &GetUnshreddedStats(BaseStatistics &stats);
137975
137977 DUCKDB_API static const BaseStatistics &GetTypedStats(const BaseStatistics &stats);
137978 DUCKDB_API static const BaseStatistics &GetTypedStats(const BaseStatistics &&stats) = delete;
137979
137981 DUCKDB_API static optional_ptr<const BaseStatistics> GetUntypedStats(const BaseStatistics &stats);
137982 DUCKDB_API static optional_ptr<const BaseStatistics> GetUntypedStats(const BaseStatistics &&stats) = delete;
137983
137984 DUCKDB_API static void SetUnshreddedStats(BaseStatistics &stats, unique_ptr<BaseStatistics> new_stats);
137985 DUCKDB_API static void SetUnshreddedStats(BaseStatistics &stats, const BaseStatistics &new_stats);
137986 DUCKDB_API static void MarkAsNotShredded(BaseStatistics &stats);
137987
137988public:
137991 DUCKDB_API static LogicalType GetShreddedStructuredType(const BaseStatistics &stats);
137992 DUCKDB_API static void CreateShreddedStats(BaseStatistics &stats, const LogicalType &shredded_type);
137993 DUCKDB_API static bool IsShredded(const BaseStatistics &stats);
137994 DUCKDB_API static const BaseStatistics &GetShreddedStats(const BaseStatistics &stats);
137995 DUCKDB_API static BaseStatistics &GetShreddedStats(BaseStatistics &stats);
137996
137997 DUCKDB_API static void SetShreddedStats(BaseStatistics &stats, unique_ptr<BaseStatistics> new_stats);
137998 DUCKDB_API static void SetShreddedStats(BaseStatistics &stats, const BaseStatistics &new_stats);
137999
138000 DUCKDB_API static bool MergeShredding(const BaseStatistics &stats, const BaseStatistics &other,
138001 BaseStatistics &new_stats);
138002 DUCKDB_API static unique_ptr<BaseStatistics> WrapExtractedFieldAsVariant(const BaseStatistics &base_variant,
138003 const BaseStatistics &extracted_field);
138004
138005public:
138006 DUCKDB_API static void Serialize(const BaseStatistics &stats, Serializer &serializer);
138007 DUCKDB_API static void Deserialize(Deserializer &deserializer, BaseStatistics &base);
138008
138009 DUCKDB_API static string ToString(const BaseStatistics &stats);
138010
138011 DUCKDB_API static void Merge(BaseStatistics &stats, const BaseStatistics &other);
138012 DUCKDB_API static void Verify(const BaseStatistics &stats, Vector &vector, const SelectionVector &sel, idx_t count);
138013 DUCKDB_API static void Copy(BaseStatistics &stats, const BaseStatistics &other);
138014 DUCKDB_API static unique_ptr<BaseStatistics> PushdownExtract(const BaseStatistics &stats,
138015 const StorageIndex &index);
138016
138017private:
138018 static VariantStatsData &GetDataUnsafe(BaseStatistics &stats);
138019 static const VariantStatsData &GetDataUnsafe(const BaseStatistics &stats);
138020};
138021
138022}
138023
138024
138025namespace duckdb {
138026struct SelectionVector;
138027
138028class Serializer;
138029class Deserializer;
138030
138031class Vector;
138032struct UnifiedVectorFormat;
138033
138034enum class StatsInfo :
uint8_t {
138035 CAN_HAVE_NULL_VALUES = 0,
138036 CANNOT_HAVE_NULL_VALUES = 1,
138037 CAN_HAVE_VALID_VALUES = 2,
138038 CANNOT_HAVE_VALID_VALUES = 3,
138039 CAN_HAVE_NULL_AND_VALID_VALUES = 4
138040};
138041
138042enum class StatisticsType :
uint8_t {
138043 NUMERIC_STATS,
138044 STRING_STATS,
138045 LIST_STATS,
138046 STRUCT_STATS,
138047 BASE_STATS,
138048 ARRAY_STATS,
138049 GEOMETRY_STATS,
138050 VARIANT_STATS
138051};
138052
138053class BaseStatistics {
138054 friend struct NumericStats;
138055 friend struct StringStats;
138056 friend struct StructStats;
138057 friend struct ListStats;
138058 friend struct ArrayStats;
138059 friend struct GeometryStats;
138060 friend struct VariantStats;
138061
138062public:
138063 DUCKDB_API ~BaseStatistics();
138064
138065 BaseStatistics(const BaseStatistics &other) = delete;
138066 BaseStatistics &
operator=(
const BaseStatistics &) =
delete;
138068 DUCKDB_API BaseStatistics(BaseStatistics &&other) noexcept;
138069 DUCKDB_API BaseStatistics &
operator=(BaseStatistics &&) noexcept;
138070
138071public:
138075 static BaseStatistics CreateUnknown(LogicalType type);
138078 static BaseStatistics CreateEmpty(LogicalType type);
138079
138080 DUCKDB_API StatisticsType GetStatsType() const;
138081 DUCKDB_API static StatisticsType GetStatsType(const LogicalType &type);
138082
138083 DUCKDB_API bool CanHaveNull() const;
138084 DUCKDB_API bool CanHaveNoNull() const;
138085
138086 void SetDistinctCount(idx_t distinct_count);
138087
138088 bool IsConstant() const;
138089
138090 const LogicalType &GetType() const {
138091 return type;
138092 }
138093
138094 void Set(StatsInfo info);
138095 void CombineValidity(const BaseStatistics &left, const BaseStatistics &right);
138096 void CopyValidity(const BaseStatistics &stats);
138100 inline void SetHasNullFast() {
138101 has_null = true;
138102 }
138106 inline void SetHasNoNullFast() {
138107 has_no_null = true;
138108 }
138109 void SetHasNull();
138110 void SetHasNoNull();
138111
138112 void Merge(const BaseStatistics &other);
138113
138114 void Copy(const BaseStatistics &other);
138115
138116 unique_ptr<BaseStatistics> PushdownExtract(const StorageIndex &index) const;
138117 BaseStatistics Copy() const;
138118 unique_ptr<BaseStatistics> ToUnique() const;
138119 void CopyBase(const BaseStatistics &orig);
138120
138121 void Serialize(Serializer &serializer) const;
138122 static BaseStatistics Deserialize(Deserializer &deserializer);
138123
138125 void Verify(Vector &vector, const SelectionVector &sel, idx_t count, bool ignore_has_null = false) const;
138126 void Verify(Vector &vector, idx_t count) const;
138127
138128 string ToString() const;
138129
138130 idx_t GetDistinctCount();
138131 static BaseStatistics FromConstant(const Value &input);
138132
138133 template <class T>
138134 void UpdateNumericStats(T new_value) {
138135 D_ASSERT(GetStatsType() == StatisticsType::NUMERIC_STATS);
138136 NumericStats::Update(stats_union.numeric_data, new_value);
138137 }
138138
138139private:
138140 BaseStatistics();
138141 explicit BaseStatistics(LogicalType type);
138142
138143 static void Construct(BaseStatistics &stats, LogicalType type);
138144
138145 void InitializeUnknown();
138146 void InitializeEmpty();
138147
138148 static BaseStatistics CreateUnknownType(LogicalType type);
138149 static BaseStatistics CreateEmptyType(LogicalType type);
138150 static BaseStatistics FromConstantType(const Value &input);
138151
138152private:
138154 LogicalType type = LogicalType::INVALID;
138156 bool has_null;
138158 bool has_no_null;
138160 idx_t distinct_count;
138162 union {
138164 NumericStatsData numeric_data;
138166 StringStatsData string_data;
138168 GeometryStatsData geometry_data;
138170 VariantStatsData variant_data;
138171 } stats_union;
138173 unsafe_unique_array<BaseStatistics> child_stats;
138174};
138175
138176template <>
138177inline void BaseStatistics::UpdateNumericStats<interval_t>(interval_t new_value) {
138178}
138179template <>
138180inline void BaseStatistics::UpdateNumericStats<list_entry_t>(list_entry_t new_value) {
138181}
138182
138183}
138184
138185
138186
138187namespace duckdb {
138188
138189struct FunctionLocalState {
138190 DUCKDB_API virtual ~FunctionLocalState();
138191
138192 template <class TARGET>
138193 TARGET &Cast() {
138194 DynamicCastCheck<TARGET>(this);
138195 return reinterpret_cast<TARGET &>(*this);
138196 }
138197 template <class TARGET>
138198 const TARGET &Cast() const {
138199 DynamicCastCheck<TARGET>(this);
138200 return reinterpret_cast<const TARGET &>(*this);
138201 }
138202};
138203
138204struct ScalarFunctionInfo {
138205 DUCKDB_API virtual ~ScalarFunctionInfo();
138206
138207 template <class TARGET>
138208 TARGET &Cast() {
138209 DynamicCastCheck<TARGET>(this);
138210 return reinterpret_cast<TARGET &>(*this);
138211 }
138212 template <class TARGET>
138213 const TARGET &Cast() const {
138214 DynamicCastCheck<TARGET>(this);
138215 return reinterpret_cast<const TARGET &>(*this);
138216 }
138217};
138218
138219class Binder;
138220class BoundFunctionExpression;
138221class ScalarFunctionCatalogEntry;
138222
138223struct StatementProperties;
138224
138225struct FunctionStatisticsInput {
138226 FunctionStatisticsInput(BoundFunctionExpression &expr_p, optional_ptr<FunctionData> bind_data_p,
138227 vector<BaseStatistics> &child_stats_p, unique_ptr<Expression> *expr_ptr_p)
138228 : expr(expr_p), bind_data(bind_data_p), child_stats(child_stats_p), expr_ptr(expr_ptr_p) {
138229 }
138230
138231 BoundFunctionExpression &expr;
138232 optional_ptr<FunctionData> bind_data;
138233 vector<BaseStatistics> &child_stats;
138234 unique_ptr<Expression> *expr_ptr;
138235};
138236
138237struct FunctionModifiedDatabasesInput {
138238 FunctionModifiedDatabasesInput(optional_ptr<FunctionData> bind_data_p, StatementProperties &properties)
138239 : bind_data(bind_data_p), properties(properties) {
138240 }
138241
138242 optional_ptr<FunctionData> bind_data;
138243 StatementProperties &properties;
138244};
138245
138246struct FunctionBindExpressionInput {
138247 FunctionBindExpressionInput(ClientContext &context_p, optional_ptr<FunctionData> bind_data_p,
138248 vector<unique_ptr<Expression>> &children_p)
138249 : context(context_p), bind_data(bind_data_p), children(children_p) {
138250 }
138251
138252 ClientContext &context;
138253 optional_ptr<FunctionData> bind_data;
138254 vector<unique_ptr<Expression>> &children;
138255};
138256
138257struct ScalarFunctionBindInput {
138258 explicit ScalarFunctionBindInput(Binder &binder) : binder(binder) {
138259 }
138260
138261 Binder &binder;
138262};
138263
138265typedef std::function<void(DataChunk &, ExpressionState &, Vector &)>
scalar_function_t;
138267typedef unique_ptr<FunctionData> (*bind_scalar_function_t)(ClientContext &context, ScalarFunction &bound_function,
138268 vector<unique_ptr<Expression>> &arguments);
138269typedef unique_ptr<FunctionData> (*bind_scalar_function_extended_t)(ScalarFunctionBindInput &bind_input,
138270 ScalarFunction &bound_function,
138271 vector<unique_ptr<Expression>> &arguments);
138273typedef unique_ptr<FunctionLocalState> (*init_local_state_t)(ExpressionState &state,
138274 const BoundFunctionExpression &expr,
138275 FunctionData *bind_data);
138277typedef unique_ptr<BaseStatistics> (*function_statistics_t)(ClientContext &context, FunctionStatisticsInput &input);
138279typedef LogicalType (*bind_lambda_function_t)(ClientContext &context, const vector<LogicalType> &function_child_types,
138280 idx_t parameter_idx);
138281
138283typedef void (*get_modified_databases_t)(ClientContext &context, FunctionModifiedDatabasesInput &input);
138284
138285typedef void (*function_serialize_t)(Serializer &serializer, const optional_ptr<FunctionData> bind_data,
138286 const ScalarFunction &function);
138287typedef unique_ptr<FunctionData> (*function_deserialize_t)(Deserializer &deserializer, ScalarFunction &function);
138288
138290typedef unique_ptr<Expression> (*function_bind_expression_t)(FunctionBindExpressionInput &input);
138291
138292class ScalarFunction : public BaseScalarFunction {
138293public:
138294 DUCKDB_API ScalarFunction(string name, vector<LogicalType> arguments, LogicalType return_type,
138295 scalar_function_t function, bind_scalar_function_t bind = nullptr,
138296 bind_scalar_function_extended_t bind_extended = nullptr,
138297 function_statistics_t statistics = nullptr, init_local_state_t init_local_state = nullptr,
138298 LogicalType varargs = LogicalType(LogicalTypeId::INVALID),
138299 FunctionStability stability = FunctionStability::CONSISTENT,
138300 FunctionNullHandling null_handling = FunctionNullHandling::DEFAULT_NULL_HANDLING,
138301 bind_lambda_function_t bind_lambda = nullptr);
138302
138303 DUCKDB_API ScalarFunction(vector<LogicalType> arguments, LogicalType return_type, scalar_function_t function,
138304 bind_scalar_function_t bind = nullptr,
138305 bind_scalar_function_extended_t bind_extended = nullptr,
138306 function_statistics_t statistics = nullptr, init_local_state_t init_local_state = nullptr,
138307 LogicalType varargs = LogicalType(LogicalTypeId::INVALID),
138308 FunctionStability stability = FunctionStability::CONSISTENT,
138309 FunctionNullHandling null_handling = FunctionNullHandling::DEFAULT_NULL_HANDLING,
138310 bind_lambda_function_t bind_lambda = nullptr);
138311
138312
138313
138314 bool HasFunctionCallback() const { return function != nullptr; }
138316 void SetFunctionCallback(scalar_function_t callback) { function = std::move(callback); }
138317
138318 bool HasBindCallback()
const {
return bind !=
nullptr; };
138320 void SetBindCallback(bind_scalar_function_t callback) {
bind = callback; }
138321
138322 bool HasBindExtendedCallback() const { return bind_extended != nullptr; }
138323 bind_scalar_function_extended_t GetBindExtendedCallback() const { return bind_extended; }
138324 void SetBindExtendedCallback(bind_scalar_function_extended_t callback) { bind_extended = callback; }
138325
138326 bool HasBindLambdaCallback() const { return bind_lambda != nullptr; }
138328 void SetBindLambdaCallback(bind_lambda_function_t callback) { bind_lambda = callback; }
138329
138330 bool HasBindExpressionCallback() const { return bind_expression != nullptr; }
138332 void SetBindExpressionCallback(function_bind_expression_t callback) { bind_expression = callback; }
138333
138334 bool HasInitStateCallback() const { return init_local_state != nullptr; }
138336 void SetInitStateCallback(init_local_state_t callback) { init_local_state = callback; }
138337
138338 bool HasStatisticsCallback() const { return statistics != nullptr; }
138340 void SetStatisticsCallback(function_statistics_t callback) { statistics = callback; }
138341
138342 bool HasModifiedDatabasesCallback() const { return get_modified_databases != nullptr; }
138344 void SetModifiedDatabasesCallback(get_modified_databases_t callback) { get_modified_databases = callback; }
138345
138346 bool HasSerializationCallbacks()
const {
return serialize !=
nullptr &&
deserialize !=
nullptr; }
138347 void SetSerializeCallback(function_serialize_t callback) {
serialize = callback; }
138348 void SetDeserializeCallback(function_deserialize_t callback) {
deserialize = callback; }
138349 function_serialize_t GetSerializeCallback()
const {
return serialize; }
138350 function_deserialize_t GetDeserializeCallback()
const {
return deserialize; }
138351
138352
138353 bool HasExtraFunctionInfo() const {
138354 return function_info != nullptr;
138355 }
138356 ScalarFunctionInfo &GetExtraFunctionInfo() const {
138357 D_ASSERT(function_info.get());
138358 return *function_info;
138359 }
138360 void SetExtraFunctionInfo(shared_ptr<ScalarFunctionInfo> info) {
138361 function_info = std::move(info);
138362 }
138363 template <class T, class... ARGS>
138364 void SetExtraFunctionInfo(ARGS &&... args) {
138365 function_info = make_shared_ptr<T>(std::forward<ARGS>(args)...);
138366 }
138367
138368public:
138374 bind_scalar_function_extended_t bind_extended = nullptr;
138385
138389 shared_ptr<ScalarFunctionInfo> function_info;
138390
138391public:
138392 DUCKDB_API
bool operator==(
const ScalarFunction &rhs)
const;
138393 DUCKDB_API
bool operator!=(
const ScalarFunction &rhs)
const;
138394
138395 DUCKDB_API bool Equal(const ScalarFunction &rhs) const;
138396
138397public:
138398 DUCKDB_API static void NopFunction(DataChunk &input, ExpressionState &state, Vector &result);
138399
138400 template <class TA, class TR, class OP>
138401 static void UnaryFunction(DataChunk &input, ExpressionState &state, Vector &result) {
138402 D_ASSERT(input.ColumnCount() >= 1);
138403 UnaryExecutor::Execute<TA, TR, OP>(input.
data[0], result, input.size());
138404 }
138405
138406 template <class TA, class TB, class TR, class OP>
138407 static void BinaryFunction(DataChunk &input, ExpressionState &state, Vector &result) {
138408 D_ASSERT(input.ColumnCount() == 2);
138409 BinaryExecutor::ExecuteStandard<TA, TB, TR, OP>(input.
data[0], input.
data[1], result, input.size());
138410 }
138411
138412 template <class TA, class TB, class TC, class TR, class OP>
138413 static void TernaryFunction(DataChunk &input, ExpressionState &state, Vector &result) {
138414 D_ASSERT(input.ColumnCount() == 3);
138415 TernaryExecutor::ExecuteStandard<TA, TB, TC, TR, OP>(input.
data[0], input.
data[1], input.
data[2], result,
138416 input.size());
138417 }
138418
138419public:
138420 template <class OP>
138423 switch (type.id()) {
138424 case LogicalTypeId::TINYINT:
138425 function = &ScalarFunction::UnaryFunction<int8_t, int8_t, OP>;
138426 break;
138427 case LogicalTypeId::SMALLINT:
138428 function = &ScalarFunction::UnaryFunction<int16_t, int16_t, OP>;
138429 break;
138430 case LogicalTypeId::INTEGER:
138431 function = &ScalarFunction::UnaryFunction<int32_t, int32_t, OP>;
138432 break;
138433 case LogicalTypeId::BIGINT:
138434 function = &ScalarFunction::UnaryFunction<int64_t, int64_t, OP>;
138435 break;
138436 case LogicalTypeId::UTINYINT:
138437 function = &ScalarFunction::UnaryFunction<uint8_t, uint8_t, OP>;
138438 break;
138439 case LogicalTypeId::USMALLINT:
138440 function = &ScalarFunction::UnaryFunction<uint16_t, uint16_t, OP>;
138441 break;
138442 case LogicalTypeId::UINTEGER:
138443 function = &ScalarFunction::UnaryFunction<uint32_t, uint32_t, OP>;
138444 break;
138445 case LogicalTypeId::UBIGINT:
138446 function = &ScalarFunction::UnaryFunction<uint64_t, uint64_t, OP>;
138447 break;
138448 case LogicalTypeId::HUGEINT:
138449 function = &ScalarFunction::UnaryFunction<hugeint_t, hugeint_t, OP>;
138450 break;
138451 case LogicalTypeId::UHUGEINT:
138452 function = &ScalarFunction::UnaryFunction<uhugeint_t, uhugeint_t, OP>;
138453 break;
138454 case LogicalTypeId::FLOAT:
138455 function = &ScalarFunction::UnaryFunction<float, float, OP>;
138456 break;
138457 case LogicalTypeId::DOUBLE:
138458 function = &ScalarFunction::UnaryFunction<double, double, OP>;
138459 break;
138460 default:
138461 throw InternalException("Unimplemented type for GetScalarUnaryFunction");
138462 }
138463 return function;
138464 }
138465
138466 template <class TR, class OP>
138467 static scalar_function_t GetScalarUnaryFunctionFixedReturn(
const LogicalType &type) {
138469 switch (type.id()) {
138470 case LogicalTypeId::TINYINT:
138471 function = &ScalarFunction::UnaryFunction<int8_t, TR, OP>;
138472 break;
138473 case LogicalTypeId::SMALLINT:
138474 function = &ScalarFunction::UnaryFunction<int16_t, TR, OP>;
138475 break;
138476 case LogicalTypeId::INTEGER:
138477 function = &ScalarFunction::UnaryFunction<int32_t, TR, OP>;
138478 break;
138479 case LogicalTypeId::BIGINT:
138480 function = &ScalarFunction::UnaryFunction<int64_t, TR, OP>;
138481 break;
138482 case LogicalTypeId::UTINYINT:
138483 function = &ScalarFunction::UnaryFunction<uint8_t, TR, OP>;
138484 break;
138485 case LogicalTypeId::USMALLINT:
138486 function = &ScalarFunction::UnaryFunction<uint16_t, TR, OP>;
138487 break;
138488 case LogicalTypeId::UINTEGER:
138489 function = &ScalarFunction::UnaryFunction<uint32_t, TR, OP>;
138490 break;
138491 case LogicalTypeId::UBIGINT:
138492 function = &ScalarFunction::UnaryFunction<uint64_t, TR, OP>;
138493 break;
138494 case LogicalTypeId::HUGEINT:
138495 function = &ScalarFunction::UnaryFunction<hugeint_t, TR, OP>;
138496 break;
138497 case LogicalTypeId::UHUGEINT:
138498 function = &ScalarFunction::UnaryFunction<uhugeint_t, TR, OP>;
138499 break;
138500 case LogicalTypeId::FLOAT:
138501 function = &ScalarFunction::UnaryFunction<float, TR, OP>;
138502 break;
138503 case LogicalTypeId::DOUBLE:
138504 function = &ScalarFunction::UnaryFunction<double, TR, OP>;
138505 break;
138506 default:
138507 throw InternalException("Unimplemented type for GetScalarUnaryFunctionFixedReturn");
138508 }
138509 return function;
138510 }
138511};
138512
138513}
138514
138515
138516
138517
138518
138519
138520
138521
138522
138523
138524
138525
138526
138527
138528
138529
138530
138531
138532
138533
138534
138535#include <array>
138536
138537namespace duckdb {
138538using std::array;
138539}
138540
138541
138542
138543
138544
138545
138546
138547
138548
138549
138550
138551
138552
138553
138554
138555
138556
138557
138558
138559
138560
138561
138562
138563
138564
138565
138566
138567
138568
138569
138570
138571
138572
138573
138574
138575
138576
138577
138578namespace duckdb {
138579
138580class NodeStatistics {
138581public:
138582 NodeStatistics() : has_estimated_cardinality(false), has_max_cardinality(false) {
138583 }
138584 explicit NodeStatistics(idx_t estimated_cardinality)
138585 : has_estimated_cardinality(true), estimated_cardinality(estimated_cardinality), has_max_cardinality(false) {
138586 }
138587 NodeStatistics(idx_t estimated_cardinality, idx_t max_cardinality)
138588 : has_estimated_cardinality(true), estimated_cardinality(estimated_cardinality), has_max_cardinality(true),
138589 max_cardinality(max_cardinality) {
138590 }
138591
138593 bool has_estimated_cardinality;
138595 idx_t estimated_cardinality;
138597 bool has_max_cardinality;
138599 idx_t max_cardinality;
138600};
138601
138602}
138603
138604
138605namespace duckdb {
138606
138607enum class AggregateType :
uint8_t { NON_DISTINCT = 1, DISTINCT = 2 };
138614
138615class BoundAggregateExpression;
138616
138617struct AggregateInputData {
138618 AggregateInputData(optional_ptr<FunctionData> bind_data_p, ArenaAllocator &allocator_p,
138619 AggregateCombineType combine_type_p = AggregateCombineType::PRESERVE_INPUT)
138620 : bind_data(bind_data_p), allocator(allocator_p), combine_type(combine_type_p) {
138621 }
138622 optional_ptr<FunctionData> bind_data;
138623 ArenaAllocator &allocator;
138625};
138626
138627struct AggregateUnaryInput {
138628 AggregateUnaryInput(AggregateInputData &input_p, ValidityMask &input_mask_p)
138629 : input(input_p), input_mask(input_mask_p), input_idx(0) {
138630 }
138631
138632 AggregateInputData &input;
138633 ValidityMask &input_mask;
138635
138636 inline bool RowIsValid() {
138637 return input_mask.RowIsValid(input_idx);
138638 }
138639};
138640
138641struct AggregateBinaryInput {
138642 AggregateBinaryInput(AggregateInputData &input_p, ValidityMask &left_mask_p, ValidityMask &right_mask_p)
138643 : input(input_p), left_mask(left_mask_p), right_mask(right_mask_p) {
138644 }
138645
138646 AggregateInputData &input;
138647 ValidityMask &left_mask;
138648 ValidityMask &right_mask;
138651};
138652
138653struct AggregateFinalizeData {
138654 AggregateFinalizeData(Vector &result_p, AggregateInputData &input_p)
138655 : result(result_p), input(input_p), result_idx(0) {
138656 }
138657
138658 Vector &result;
138659 AggregateInputData &input;
138661
138662 inline void ReturnNull() {
138663 switch (result.GetVectorType()) {
138664 case VectorType::FLAT_VECTOR:
138665 FlatVector::SetNull(result, result_idx, true);
138666 break;
138667 case VectorType::CONSTANT_VECTOR:
138668 ConstantVector::SetNull(result, true);
138669 break;
138670 default:
138671 throw InternalException("Invalid result vector type for aggregate");
138672 }
138673 }
138674
138675 inline string_t ReturnString(string_t value) {
138676 return StringVector::AddStringOrBlob(result, value);
138677 }
138678};
138679
138680struct AggregateStatisticsInput {
138681 AggregateStatisticsInput(optional_ptr<FunctionData> bind_data_p, vector<BaseStatistics> &child_stats_p,
138682 optional_ptr<NodeStatistics> node_stats_p)
138683 : bind_data(bind_data_p), child_stats(child_stats_p), node_stats(node_stats_p) {
138684 }
138685
138686 optional_ptr<FunctionData> bind_data;
138687 vector<BaseStatistics> &child_stats;
138688 optional_ptr<NodeStatistics> node_stats;
138689};
138690
138691}
138692
138693
138694namespace duckdb {
138695
138696
138697struct AggregateInputData;
138698
138699
138700struct FrameBounds {
138701 FrameBounds() : start(0), end(0) {};
138702 FrameBounds(idx_t start, idx_t end) : start(start), end(end) {};
138705};
138706
138707
138708using SubFrames = vector<FrameBounds>;
138709
138710class AggregateExecutor {
138711private:
138712#ifndef DUCKDB_SMALLER_BINARY
138713 template <class STATE_TYPE, class OP>
138714 static inline void NullaryFlatLoop(STATE_TYPE **__restrict states, AggregateInputData &aggr_input_data,
138715 idx_t count) {
138716 for (idx_t i = 0; i < count; i++) {
138717 OP::template Operation<STATE_TYPE, OP>(*states[i], aggr_input_data, i);
138718 }
138719 }
138720#endif
138721
138722 template <class STATE_TYPE, class OP>
138723 static inline void NullaryScatterLoop(STATE_TYPE *__restrict const *__restrict const states,
138724 AggregateInputData &aggr_input_data, const SelectionVector &ssel,
138725 const idx_t count) {
138726 if (ssel.IsSet()) {
138727 for (idx_t i = 0; i < count; i++) {
138728 auto sidx = ssel.get_index_unsafe(i);
138729 OP::template Operation<STATE_TYPE, OP>(*states[sidx], aggr_input_data, sidx);
138730 }
138731 } else {
138732 for (idx_t i = 0; i < count; i++) {
138733 OP::template Operation<STATE_TYPE, OP>(*states[i], aggr_input_data, i);
138734 }
138735 }
138736 }
138737
138738#ifndef DUCKDB_SMALLER_BINARY
138739 template <class STATE_TYPE, class INPUT_TYPE, class OP>
138740 static inline void UnaryFlatLoop(const INPUT_TYPE *__restrict idata, AggregateInputData &aggr_input_data,
138741 STATE_TYPE **__restrict states, ValidityMask &mask, idx_t count) {
138742 if (OP::IgnoreNull() && !
mask.AllValid()) {
138743 AggregateUnaryInput input(aggr_input_data, mask);
138744 auto &base_idx = input.input_idx;
138745 base_idx = 0;
138746 auto entry_count = ValidityMask::EntryCount(count);
138747 for (idx_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
138748 auto validity_entry =
mask.GetValidityEntry(entry_idx);
138749 idx_t next = MinValue<idx_t>(base_idx + ValidityMask::BITS_PER_VALUE, count);
138750 if (ValidityMask::AllValid(validity_entry)) {
138751
138752 for (; base_idx < next; base_idx++) {
138753 OP::template Operation<INPUT_TYPE, STATE_TYPE, OP>(*states[base_idx], idata[base_idx], input);
138754 }
138755 } else if (ValidityMask::NoneValid(validity_entry)) {
138756
138757 base_idx = next;
138758 continue;
138759 } else {
138760
138761 idx_t start = base_idx;
138762 for (; base_idx < next; base_idx++) {
138763 if (ValidityMask::RowIsValid(validity_entry, base_idx - start)) {
138764 OP::template Operation<INPUT_TYPE, STATE_TYPE, OP>(*states[base_idx], idata[base_idx],
138765 input);
138766 }
138767 }
138768 }
138769 }
138770 } else {
138771 AggregateUnaryInput input(aggr_input_data, mask);
138772 auto &i = input.input_idx;
138773 for (i = 0; i < count; i++) {
138774 OP::template Operation<INPUT_TYPE, STATE_TYPE, OP>(*states[i], idata[i], input);
138775 }
138776 }
138777 }
138778#endif
138779
138780#ifndef DUCKDB_SMALLER_BINARY
138781 template <class STATE_TYPE, class INPUT_TYPE, class OP, bool HAS_ISEL, bool HAS_SSEL>
138782#else
138783 template <class STATE_TYPE, class INPUT_TYPE, class OP>
138784#endif
138785 static inline void UnaryScatterLoop(const INPUT_TYPE *__restrict idata, AggregateInputData &aggr_input_data,
138786 STATE_TYPE **__restrict states, const SelectionVector &isel,
138787 const SelectionVector &ssel, ValidityMask &mask, idx_t count) {
138788#ifdef DUCKDB_SMALLER_BINARY
138789 const auto HAS_ISEL = isel.IsSet();
138790 const auto HAS_SSEL = ssel.IsSet();
138791#endif
138792 if (OP::IgnoreNull() && !
mask.AllValid()) {
138793
138794 AggregateUnaryInput input(aggr_input_data, mask);
138795 for (idx_t i = 0; i < count; i++) {
138796 input.input_idx = HAS_ISEL ? isel.get_index_unsafe(i) : i;
138797 auto sidx = HAS_SSEL ? ssel.get_index_unsafe(i) : i;
138798 if (
mask.RowIsValidUnsafe(input.input_idx)) {
138799 OP::template Operation<INPUT_TYPE, STATE_TYPE, OP>(*states[sidx], idata[input.input_idx], input);
138800 }
138801 }
138802 } else {
138803
138804 AggregateUnaryInput input(aggr_input_data, mask);
138805 for (idx_t i = 0; i < count; i++) {
138806 input.input_idx = HAS_ISEL ? isel.get_index_unsafe(i) : i;
138807 auto sidx = HAS_SSEL ? ssel.get_index_unsafe(i) : i;
138808 OP::template Operation<INPUT_TYPE, STATE_TYPE, OP>(*states[sidx], idata[input.input_idx], input);
138809 }
138810 }
138811 }
138812
138813#ifndef DUCKDB_SMALLER_BINARY
138814 template <class STATE_TYPE, class INPUT_TYPE, class OP>
138815 static inline void UnaryFlatUpdateLoop(const INPUT_TYPE *__restrict idata, AggregateInputData &aggr_input_data,
138816 STATE_TYPE *__restrict state, idx_t count, ValidityMask &mask) {
138817 AggregateUnaryInput input(aggr_input_data, mask);
138818 auto &base_idx = input.input_idx;
138819 base_idx = 0;
138820 auto entry_count = ValidityMask::EntryCount(count);
138821 for (idx_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
138822 auto validity_entry =
mask.GetValidityEntry(entry_idx);
138823 idx_t next = MinValue<idx_t>(base_idx + ValidityMask::BITS_PER_VALUE, count);
138824 if (!OP::IgnoreNull() || ValidityMask::AllValid(validity_entry)) {
138825
138826 for (; base_idx < next; base_idx++) {
138827 OP::template Operation<INPUT_TYPE, STATE_TYPE, OP>(*state, idata[base_idx], input);
138828 }
138829 } else if (ValidityMask::NoneValid(validity_entry)) {
138830
138831 base_idx = next;
138832 continue;
138833 } else {
138834
138835 idx_t start = base_idx;
138836 for (; base_idx < next; base_idx++) {
138837 if (ValidityMask::RowIsValid(validity_entry, base_idx - start)) {
138838 OP::template Operation<INPUT_TYPE, STATE_TYPE, OP>(*state, idata[base_idx], input);
138839 }
138840 }
138841 }
138842 }
138843 }
138844#endif
138845
138846 template <class STATE_TYPE, class INPUT_TYPE, class OP>
138847 static inline void UnaryUpdateLoop(const INPUT_TYPE *__restrict idata, AggregateInputData &aggr_input_data,
138848 STATE_TYPE *__restrict state, idx_t count, ValidityMask &mask,
138849 const SelectionVector &__restrict sel_vector) {
138850 AggregateUnaryInput input(aggr_input_data, mask);
138851 if (OP::IgnoreNull() && !
mask.AllValid()) {
138852
138853 for (idx_t i = 0; i < count; i++) {
138854 input.input_idx = sel_vector.get_index(i);
138855 if (
mask.RowIsValid(input.input_idx)) {
138856 OP::template Operation<INPUT_TYPE, STATE_TYPE, OP>(*state, idata[input.input_idx], input);
138857 }
138858 }
138859 } else {
138860
138861 for (idx_t i = 0; i < count; i++) {
138862 input.input_idx = sel_vector.get_index(i);
138863 OP::template Operation<INPUT_TYPE, STATE_TYPE, OP>(*state, idata[input.input_idx], input);
138864 }
138865 }
138866 }
138867
138868 template <class STATE_TYPE, class A_TYPE, class B_TYPE, class OP>
138869 static inline void BinaryScatterLoop(const A_TYPE *__restrict adata, AggregateInputData &aggr_input_data,
138870 const B_TYPE *__restrict bdata, STATE_TYPE **__restrict states, idx_t count,
138871 const SelectionVector &asel, const SelectionVector &bsel,
138872 const SelectionVector &ssel, ValidityMask &avalidity,
138873 ValidityMask &bvalidity) {
138874 AggregateBinaryInput input(aggr_input_data, avalidity, bvalidity);
138875 if (OP::IgnoreNull() && (!avalidity.AllValid() || !bvalidity.AllValid())) {
138876
138877 for (idx_t i = 0; i < count; i++) {
138878 input.lidx = asel.get_index(i);
138879 input.ridx = bsel.get_index(i);
138880 auto sidx = ssel.get_index(i);
138881 if (avalidity.RowIsValid(input.lidx) && bvalidity.RowIsValid(input.ridx)) {
138882 OP::template Operation<A_TYPE, B_TYPE, STATE_TYPE, OP>(*states[sidx], adata[input.lidx],
138883 bdata[input.ridx], input);
138884 }
138885 }
138886 } else {
138887
138888 for (idx_t i = 0; i < count; i++) {
138889 input.lidx = asel.get_index(i);
138890 input.ridx = bsel.get_index(i);
138891 auto sidx = ssel.get_index(i);
138892 OP::template Operation<A_TYPE, B_TYPE, STATE_TYPE, OP>(*states[sidx], adata[input.lidx],
138893 bdata[input.ridx], input);
138894 }
138895 }
138896 }
138897
138898 template <class STATE_TYPE, class A_TYPE, class B_TYPE, class OP>
138899 static inline void BinaryUpdateLoop(const A_TYPE *__restrict adata, AggregateInputData &aggr_input_data,
138900 const B_TYPE *__restrict bdata, STATE_TYPE *__restrict state, idx_t count,
138901 const SelectionVector &asel, const SelectionVector &bsel,
138902 ValidityMask &avalidity, ValidityMask &bvalidity) {
138903 AggregateBinaryInput input(aggr_input_data, avalidity, bvalidity);
138904 if (OP::IgnoreNull() && (!avalidity.AllValid() || !bvalidity.AllValid())) {
138905
138906 for (idx_t i = 0; i < count; i++) {
138907 input.lidx = asel.get_index(i);
138908 input.ridx = bsel.get_index(i);
138909 if (avalidity.RowIsValid(input.lidx) && bvalidity.RowIsValid(input.ridx)) {
138910 OP::template Operation<A_TYPE, B_TYPE, STATE_TYPE, OP>(*state, adata[input.lidx], bdata[input.ridx],
138911 input);
138912 }
138913 }
138914 } else {
138915
138916 for (idx_t i = 0; i < count; i++) {
138917 input.lidx = asel.get_index(i);
138918 input.ridx = bsel.get_index(i);
138919 OP::template Operation<A_TYPE, B_TYPE, STATE_TYPE, OP>(*state, adata[input.lidx], bdata[input.ridx],
138920 input);
138921 }
138922 }
138923 }
138924
138925public:
138926 template <class STATE_TYPE, class OP>
138927 static void NullaryScatter(Vector &states, AggregateInputData &aggr_input_data, idx_t count) {
138928 if (states.GetVectorType() == VectorType::CONSTANT_VECTOR) {
138929 auto sdata = ConstantVector::GetData<STATE_TYPE *>(states);
138930 OP::template ConstantOperation<STATE_TYPE, OP>(**sdata, aggr_input_data, count);
138931#ifndef DUCKDB_SMALLER_BINARY
138932 } else if (states.GetVectorType() == VectorType::FLAT_VECTOR) {
138933 auto sdata = FlatVector::GetData<STATE_TYPE *>(states);
138934 NullaryFlatLoop<STATE_TYPE, OP>(sdata, aggr_input_data, count);
138935#endif
138936 } else {
138937 UnifiedVectorFormat sdata;
138938 states.ToUnifiedFormat(count, sdata);
138939 NullaryScatterLoop<STATE_TYPE, OP>((STATE_TYPE **)sdata.data, aggr_input_data, *sdata.sel, count);
138940 }
138941 }
138942
138943 template <class STATE_TYPE, class OP>
138944 static void NullaryUpdate(data_ptr_t state, AggregateInputData &aggr_input_data, idx_t count) {
138945 OP::template ConstantOperation<STATE_TYPE, OP>(*reinterpret_cast<STATE_TYPE *>(state), aggr_input_data, count);
138946 }
138947
138948 template <class STATE_TYPE, class INPUT_TYPE, class OP>
138949 static void UnaryScatter(Vector &input, Vector &states, AggregateInputData &aggr_input_data, idx_t count) {
138950 if (input.GetVectorType() == VectorType::CONSTANT_VECTOR &&
138951 states.GetVectorType() == VectorType::CONSTANT_VECTOR) {
138952 if (OP::IgnoreNull() && ConstantVector::IsNull(input)) {
138953
138954 return;
138955 }
138956
138957 auto idata = ConstantVector::GetData<INPUT_TYPE>(input);
138958 auto sdata = ConstantVector::GetData<STATE_TYPE *>(states);
138959 AggregateUnaryInput input_data(aggr_input_data, ConstantVector::Validity(input));
138960 OP::template ConstantOperation<INPUT_TYPE, STATE_TYPE, OP>(**sdata, *idata, input_data, count);
138961#ifndef DUCKDB_SMALLER_BINARY
138962 } else if (input.GetVectorType() == VectorType::FLAT_VECTOR &&
138963 states.GetVectorType() == VectorType::FLAT_VECTOR) {
138964 auto idata = FlatVector::GetData<INPUT_TYPE>(input);
138965 auto sdata = FlatVector::GetData<STATE_TYPE *>(states);
138966 UnaryFlatLoop<STATE_TYPE, INPUT_TYPE, OP>(idata, aggr_input_data, sdata, FlatVector::Validity(input),
138967 count);
138968#endif
138969 } else {
138970 UnifiedVectorFormat idata, sdata;
138971 input.ToUnifiedFormat(count, idata);
138972 states.ToUnifiedFormat(count, sdata);
138973#ifdef DUCKDB_SMALLER_BINARY
138974 UnaryScatterLoop<STATE_TYPE, INPUT_TYPE, OP>(UnifiedVectorFormat::GetData<INPUT_TYPE>(idata),
138975 aggr_input_data, (STATE_TYPE **)sdata.data, *idata.sel,
138976 *sdata.sel, idata.validity, count);
138977#else
138978 if (idata.sel->IsSet()) {
138979 if (sdata.sel->IsSet()) {
138980 UnaryScatterLoop<STATE_TYPE, INPUT_TYPE, OP, true, true>(
138981 UnifiedVectorFormat::GetData<INPUT_TYPE>(idata), aggr_input_data, (STATE_TYPE **)sdata.data,
138982 *idata.sel, *sdata.sel, idata.validity, count);
138983 } else {
138984 UnaryScatterLoop<STATE_TYPE, INPUT_TYPE, OP, true, false>(
138985 UnifiedVectorFormat::GetData<INPUT_TYPE>(idata), aggr_input_data, (STATE_TYPE **)sdata.data,
138986 *idata.sel, *sdata.sel, idata.validity, count);
138987 }
138988 } else {
138989 if (sdata.sel->IsSet()) {
138990 UnaryScatterLoop<STATE_TYPE, INPUT_TYPE, OP, false, true>(
138991 UnifiedVectorFormat::GetData<INPUT_TYPE>(idata), aggr_input_data, (STATE_TYPE **)sdata.data,
138992 *idata.sel, *sdata.sel, idata.validity, count);
138993 } else {
138994 UnaryScatterLoop<STATE_TYPE, INPUT_TYPE, OP, false, false>(
138995 UnifiedVectorFormat::GetData<INPUT_TYPE>(idata), aggr_input_data, (STATE_TYPE **)sdata.data,
138996 *idata.sel, *sdata.sel, idata.validity, count);
138997 }
138998 }
138999
139000#endif
139001 }
139002 }
139003
139004 template <class STATE_TYPE, class INPUT_TYPE, class OP>
139005 static void UnaryUpdate(Vector &input, AggregateInputData &aggr_input_data, data_ptr_t state, idx_t count) {
139006 switch (input.GetVectorType()) {
139007 case VectorType::CONSTANT_VECTOR: {
139008 if (OP::IgnoreNull() && ConstantVector::IsNull(input)) {
139009 return;
139010 }
139011 auto idata = ConstantVector::GetData<INPUT_TYPE>(input);
139012 AggregateUnaryInput input_data(aggr_input_data, ConstantVector::Validity(input));
139013 OP::template ConstantOperation<INPUT_TYPE, STATE_TYPE, OP>(*reinterpret_cast<STATE_TYPE *>(state), *idata,
139014 input_data, count);
139015 break;
139016 }
139017#ifndef DUCKDB_SMALLER_BINARY
139018 case VectorType::FLAT_VECTOR: {
139019 auto idata = FlatVector::GetData<INPUT_TYPE>(input);
139020 UnaryFlatUpdateLoop<STATE_TYPE, INPUT_TYPE, OP>(idata, aggr_input_data, (STATE_TYPE *)state, count,
139021 FlatVector::Validity(input));
139022 break;
139023 }
139024#endif
139025 default: {
139026 UnifiedVectorFormat idata;
139027 input.ToUnifiedFormat(count, idata);
139028 UnaryUpdateLoop<STATE_TYPE, INPUT_TYPE, OP>(UnifiedVectorFormat::GetData<INPUT_TYPE>(idata),
139029 aggr_input_data, (STATE_TYPE *)state, count, idata.validity,
139030 *idata.sel);
139031 break;
139032 }
139033 }
139034 }
139035
139036 template <class STATE_TYPE, class A_TYPE, class B_TYPE, class OP>
139037 static void BinaryScatter(AggregateInputData &aggr_input_data, Vector &a, Vector &b, Vector &states, idx_t count) {
139038 UnifiedVectorFormat adata, bdata, sdata;
139039
139040 a.ToUnifiedFormat(count, adata);
139041 b.ToUnifiedFormat(count, bdata);
139042 states.ToUnifiedFormat(count, sdata);
139043
139044 BinaryScatterLoop<STATE_TYPE, A_TYPE, B_TYPE, OP>(
139045 UnifiedVectorFormat::GetData<A_TYPE>(adata), aggr_input_data, UnifiedVectorFormat::GetData<B_TYPE>(bdata),
139046 (STATE_TYPE **)sdata.data, count, *adata.sel, *bdata.sel, *sdata.sel, adata.validity, bdata.validity);
139047 }
139048
139049 template <class STATE_TYPE, class A_TYPE, class B_TYPE, class OP>
139050 static void BinaryUpdate(AggregateInputData &aggr_input_data, Vector &a, Vector &b, data_ptr_t state, idx_t count) {
139051 UnifiedVectorFormat adata, bdata;
139052
139053 a.ToUnifiedFormat(count, adata);
139054 b.ToUnifiedFormat(count, bdata);
139055
139056 BinaryUpdateLoop<STATE_TYPE, A_TYPE, B_TYPE, OP>(
139057 UnifiedVectorFormat::GetData<A_TYPE>(adata), aggr_input_data, UnifiedVectorFormat::GetData<B_TYPE>(bdata),
139058 (STATE_TYPE *)state, count, *adata.sel, *bdata.sel, adata.validity, bdata.validity);
139059 }
139060
139061 template <class STATE_TYPE, class OP>
139062 static void Combine(Vector &source, Vector &target, AggregateInputData &aggr_input_data, idx_t count) {
139063 D_ASSERT(source.GetType().id() == LogicalTypeId::POINTER && target.GetType().id() == LogicalTypeId::POINTER);
139064 auto sdata = FlatVector::GetData<const STATE_TYPE *>(source);
139065 auto tdata = FlatVector::GetData<STATE_TYPE *>(target);
139066
139067 for (idx_t i = 0; i < count; i++) {
139068 OP::template Combine<STATE_TYPE, OP>(*sdata[i], *tdata[i], aggr_input_data);
139069 }
139070 }
139071
139072 template <class STATE_TYPE, class RESULT_TYPE, class OP>
139073 static void Finalize(Vector &states, AggregateInputData &aggr_input_data, Vector &result, idx_t count,
139074 idx_t offset) {
139075 if (states.GetVectorType() == VectorType::CONSTANT_VECTOR) {
139076 result.SetVectorType(VectorType::CONSTANT_VECTOR);
139077
139078 auto sdata = ConstantVector::GetData<STATE_TYPE *>(states);
139079 auto rdata = ConstantVector::GetData<RESULT_TYPE>(result);
139080 AggregateFinalizeData finalize_data(result, aggr_input_data);
139081 OP::template Finalize<RESULT_TYPE, STATE_TYPE>(**sdata, *rdata, finalize_data);
139082 } else {
139083 D_ASSERT(states.GetVectorType() == VectorType::FLAT_VECTOR);
139084 result.SetVectorType(VectorType::FLAT_VECTOR);
139085
139086 auto sdata = FlatVector::GetData<STATE_TYPE *>(states);
139087 auto rdata = FlatVector::GetData<RESULT_TYPE>(result);
139088 AggregateFinalizeData finalize_data(result, aggr_input_data);
139089 for (idx_t i = 0; i < count; i++) {
139090 finalize_data.result_idx = i + offset;
139091 OP::template Finalize<RESULT_TYPE, STATE_TYPE>(*sdata[i], rdata[finalize_data.result_idx],
139092 finalize_data);
139093 }
139094 }
139095 }
139096
139097 template <class STATE_TYPE, class OP>
139098 static void VoidFinalize(Vector &states, AggregateInputData &aggr_input_data, Vector &result, idx_t count,
139099 idx_t offset) {
139100 if (states.GetVectorType() == VectorType::CONSTANT_VECTOR) {
139101 result.SetVectorType(VectorType::CONSTANT_VECTOR);
139102
139103 auto sdata = ConstantVector::GetData<STATE_TYPE *>(states);
139104 AggregateFinalizeData finalize_data(result, aggr_input_data);
139105 OP::template Finalize<STATE_TYPE>(**sdata, finalize_data);
139106 } else {
139107 D_ASSERT(states.GetVectorType() == VectorType::FLAT_VECTOR);
139108 result.SetVectorType(VectorType::FLAT_VECTOR);
139109
139110 auto sdata = FlatVector::GetData<STATE_TYPE *>(states);
139111 AggregateFinalizeData finalize_data(result, aggr_input_data);
139112 for (idx_t i = 0; i < count; i++) {
139113 finalize_data.result_idx = i + offset;
139114 OP::template Finalize<STATE_TYPE>(*sdata[i], finalize_data);
139115 }
139116 }
139117 }
139118
139119 template <typename OP>
139120 static void IntersectFrames(const SubFrames &lefts, const SubFrames &rights, OP &op) {
139121 const auto cover_start = MinValue(rights[0].start, lefts[0].start);
139122 const auto cover_end = MaxValue(rights.back().end, lefts.back().end);
139123 const FrameBounds last(cover_end, cover_end);
139124
139125
139128 for (auto i = cover_start; i < cover_end;) {
139130
139131
139132 auto left = &last;
139133 if (l < lefts.size()) {
139134 left = &lefts[l];
139135 overlap |=
uint8_t(left->start <= i && i < left->end) << 0;
139136 }
139137
139138
139139 auto right = &last;
139140 if (r < rights.size()) {
139141 right = &rights[r];
139142 overlap |=
uint8_t(right->start <= i && i < right->end) << 1;
139143 }
139144
139145 auto limit = i;
139146 switch (overlap) {
139147 case 0x00:
139148
139149 limit = MinValue(right->start, left->start);
139150 op.Neither(i, limit);
139151 break;
139152 case 0x01:
139153
139154 limit = MinValue(left->end, right->start);
139155 op.Left(i, limit);
139156 break;
139157 case 0x02:
139158
139159 limit = MinValue(right->end, left->start);
139160 op.Right(i, limit);
139161 break;
139162 case 0x03:
139163 default:
139164 D_ASSERT(overlap == 0x03);
139165
139166 limit = MinValue(right->end, left->end);
139167 op.Both(i, limit);
139168 break;
139169 }
139170
139171
139172 i = limit;
139173 l += (i == left->end);
139174 r += (i == right->end);
139175 }
139176 }
139177
139178 template <class STATE_TYPE, class OP>
139179 static void Destroy(Vector &states, AggregateInputData &aggr_input_data, idx_t count) {
139180 auto sdata = FlatVector::GetData<STATE_TYPE *>(states);
139181 for (idx_t i = 0; i < count; i++) {
139182 OP::template Destroy<STATE_TYPE>(*sdata[i], aggr_input_data);
139183 }
139184 }
139185};
139186
139187}
139188
139189
139190
139191
139192
139193
139194
139195
139196
139197
139198
139199
139200
139201
139202
139203
139204
139205
139206
139207
139208
139209
139210
139211
139212
139213
139214
139215namespace duckdb {
139216
139217using GroupingSet = set<idx_t>;
139218
139219class GroupByNode {
139220public:
139222 vector<unique_ptr<ParsedExpression>> group_expressions;
139224 vector<GroupingSet> grouping_sets;
139225
139226public:
139227 GroupByNode Copy() {
139228 GroupByNode node;
139229 node.group_expressions.reserve(group_expressions.size());
139230 for (auto &expr : group_expressions) {
139231 node.group_expressions.push_back(expr->Copy());
139232 }
139233 node.grouping_sets = grouping_sets;
139234 return node;
139235 }
139236};
139237
139238}
139239
139240
139241
139242
139243
139244
139245
139246
139247
139248
139249
139250
139251
139252
139253
139254
139255
139256
139257
139258
139259
139260
139261
139262
139263
139264namespace duckdb {
139265
139266enum class OrderType :
uint8_t { INVALID = 0, ORDER_DEFAULT = 1, ASCENDING = 2, DESCENDING = 3 };
139267
139268enum class OrderByNullType :
uint8_t { INVALID = 0, ORDER_DEFAULT = 1, NULLS_FIRST = 2, NULLS_LAST = 3 };
139269
139270enum class DefaultOrderByNullType :
uint8_t {
139271 INVALID = 0,
139272 NULLS_FIRST = 2,
139273 NULLS_LAST = 3,
139274 NULLS_FIRST_ON_ASC_LAST_ON_DESC = 4,
139275 NULLS_LAST_ON_ASC_FIRST_ON_DESC = 5
139276};
139277
139278}
139279
139280
139281
139282namespace duckdb {
139283class Deserializer;
139284class Serializer;
139285
139286enum class ResultModifierType :
uint8_t {
139287 LIMIT_MODIFIER = 1,
139288 ORDER_MODIFIER = 2,
139289 DISTINCT_MODIFIER = 3,
139290 LIMIT_PERCENT_MODIFIER = 4
139291};
139292
139293const char *ToString(ResultModifierType value);
139294ResultModifierType ResultModifierFromString(const char *value);
139295
139297class ResultModifier {
139298public:
139299 explicit ResultModifier(ResultModifierType type) : type(type) {
139300 }
139301 virtual ~ResultModifier() {
139302 }
139303
139304 ResultModifierType type;
139305
139306public:
139308 virtual bool Equals(const ResultModifier &other) const;
139309
139311 virtual unique_ptr<ResultModifier> Copy() const = 0;
139312
139313 virtual void Serialize(Serializer &serializer) const;
139314 static unique_ptr<ResultModifier> Deserialize(Deserializer &deserializer);
139315
139316public:
139317 template <class TARGET>
139318 TARGET &Cast() {
139319 if (type != TARGET::TYPE) {
139320 throw InternalException("Failed to cast result modifier to type - result modifier type mismatch");
139321 }
139322 return reinterpret_cast<TARGET &>(*this);
139323 }
139324
139325 template <class TARGET>
139326 const TARGET &Cast() const {
139327 if (type != TARGET::TYPE) {
139328 throw InternalException("Failed to cast result modifier to type - result modifier type mismatch");
139329 }
139330 return reinterpret_cast<const TARGET &>(*this);
139331 }
139332};
139333
139335struct OrderByNode {
139336 OrderByNode(OrderType type, OrderByNullType null_order, unique_ptr<ParsedExpression> expression)
139337 : type(type), null_order(null_order), expression(std::move(expression)) {
139338 }
139339
139341 OrderType type;
139343 OrderByNullType null_order;
139345 unique_ptr<ParsedExpression> expression;
139346
139347public:
139348 string ToString() const;
139349
139350 void Serialize(Serializer &serializer) const;
139351 static OrderByNode Deserialize(Deserializer &deserializer);
139352};
139353
139354class LimitModifier : public ResultModifier {
139355public:
139356 static constexpr const ResultModifierType
TYPE = ResultModifierType::LIMIT_MODIFIER;
139357
139358public:
139359 LimitModifier() : ResultModifier(ResultModifierType::LIMIT_MODIFIER) {
139360 }
139361
139363 unique_ptr<ParsedExpression> limit;
139365 unique_ptr<ParsedExpression> offset;
139366
139367public:
139368 bool Equals(const ResultModifier &other) const override;
139369 unique_ptr<ResultModifier> Copy() const override;
139370
139371 void Serialize(Serializer &serializer) const override;
139372 static unique_ptr<ResultModifier> Deserialize(Deserializer &deserializer);
139373};
139374
139375class OrderModifier : public ResultModifier {
139376public:
139377 static constexpr const ResultModifierType
TYPE = ResultModifierType::ORDER_MODIFIER;
139378
139379public:
139380 OrderModifier() : ResultModifier(ResultModifierType::ORDER_MODIFIER) {
139381 }
139382
139384 vector<OrderByNode> orders;
139385
139386public:
139387 bool Equals(const ResultModifier &other) const override;
139388 unique_ptr<ResultModifier> Copy() const override;
139389
139390 void Serialize(Serializer &serializer) const override;
139391 static unique_ptr<ResultModifier> Deserialize(Deserializer &deserializer);
139392
139393 static bool Equals(const unique_ptr<OrderModifier> &left, const unique_ptr<OrderModifier> &right);
139394};
139395
139396class DistinctModifier : public ResultModifier {
139397public:
139398 static constexpr const ResultModifierType
TYPE = ResultModifierType::DISTINCT_MODIFIER;
139399
139400public:
139401 DistinctModifier() : ResultModifier(ResultModifierType::DISTINCT_MODIFIER) {
139402 }
139403
139405 vector<unique_ptr<ParsedExpression>> distinct_on_targets;
139406
139407public:
139408 bool Equals(const ResultModifier &other) const override;
139409 unique_ptr<ResultModifier> Copy() const override;
139410
139411 void Serialize(Serializer &serializer) const override;
139412 static unique_ptr<ResultModifier> Deserialize(Deserializer &deserializer);
139413};
139414
139415class LimitPercentModifier : public ResultModifier {
139416public:
139417 static constexpr const ResultModifierType
TYPE = ResultModifierType::LIMIT_PERCENT_MODIFIER;
139418
139419public:
139420 LimitPercentModifier() : ResultModifier(ResultModifierType::LIMIT_PERCENT_MODIFIER) {
139421 }
139422
139424 unique_ptr<ParsedExpression> limit;
139426 unique_ptr<ParsedExpression> offset;
139427
139428public:
139429 bool Equals(const ResultModifier &other) const override;
139430 unique_ptr<ResultModifier> Copy() const override;
139431
139432 void Serialize(Serializer &serializer) const override;
139433 static unique_ptr<ResultModifier> Deserialize(Deserializer &deserializer);
139434};
139435
139436}
139437
139438
139439
139440
139441
139442
139443
139444
139445
139446
139447
139448
139449
139450
139451
139452
139453
139454
139455
139456
139457
139458
139459
139460
139461
139462
139463namespace duckdb {
139464
139465enum class SetOperationType :
uint8_t { NONE = 0, UNION = 1, EXCEPT = 2, INTERSECT = 3, UNION_BY_NAME = 4 };
139466
139467}
139468
139469
139470
139471namespace duckdb {
139472
139473class LogicalOperator;
139474struct LogicalType;
139475struct BoundStatement;
139476class ParsedExpression;
139477class Binder;
139478
139479struct ExtraBoundInfo {
139480 SetOperationType setop_type = SetOperationType::NONE;
139481 vector<shared_ptr<Binder>> child_binders;
139482 vector<BoundStatement> bound_children;
139483 vector<unique_ptr<ParsedExpression>> original_expressions;
139484};
139485
139486struct BoundStatement {
139487 unique_ptr<LogicalOperator> plan;
139488 vector<LogicalType> types;
139489 vector<string> names;
139490 ExtraBoundInfo extra_info;
139491};
139492
139493}
139494
139495
139496
139497
139498
139499
139500
139501
139502
139503
139504
139505
139506
139507
139508namespace duckdb {
139509class BaseStatistics;
139510class ClientContext;
139511
139513class Expression : public BaseExpression {
139514public:
139515 Expression(ExpressionType type, ExpressionClass expression_class, LogicalType return_type);
139516 ~Expression() override;
139517
139519 LogicalType return_type;
139521 unique_ptr<BaseStatistics> verification_stats;
139522
139523public:
139524 bool IsAggregate() const override;
139525 bool IsWindow() const override;
139526 bool HasSubquery() const override;
139527 bool IsScalar() const override;
139528 bool HasParameter() const override;
139529
139530 virtual bool IsVolatile() const;
139531 virtual bool IsConsistent() const;
139532 virtual bool PropagatesNullValues() const;
139533 virtual bool IsFoldable() const;
139534 virtual bool CanThrow() const;
139535
139536 hash_t Hash()
const override;
139537
139538 bool Equals(const BaseExpression &other) const override {
139539 if (!BaseExpression::Equals(other)) {
139540 return false;
139541 }
139542 return return_type == reinterpret_cast<const Expression &>(other).return_type;
139543 }
139544 static bool Equals(const Expression &left, const Expression &right) {
139545 return left.Equals(right);
139546 }
139547 static bool Equals(const unique_ptr<Expression> &left, const unique_ptr<Expression> &right);
139548 static bool ListEquals(const vector<unique_ptr<Expression>> &left, const vector<unique_ptr<Expression>> &right);
139550 virtual unique_ptr<Expression> Copy() const = 0;
139551
139552 virtual void Serialize(Serializer &serializer) const;
139553 static unique_ptr<Expression> Deserialize(Deserializer &deserializer);
139554
139555protected:
139558 void CopyProperties(const Expression &other) {
139559 type = other.type;
139560 expression_class = other.expression_class;
139561 alias = other.alias;
139562 return_type = other.return_type;
139563 query_location = other.query_location;
139564 }
139565};
139566
139567}
139568
139569
139570
139571namespace duckdb {
139572
139574class BoundResultModifier {
139575public:
139576 explicit BoundResultModifier(ResultModifierType type);
139577 virtual ~BoundResultModifier();
139578
139579 ResultModifierType type;
139580
139581public:
139582 template <class TARGET>
139583 TARGET &Cast() {
139584 if (type != TARGET::TYPE) {
139585 throw InternalException("Failed to cast result modifier to type - result modifier type mismatch");
139586 }
139587 return reinterpret_cast<TARGET &>(*this);
139588 }
139589
139590 template <class TARGET>
139591 const TARGET &Cast() const {
139592 if (type != TARGET::TYPE) {
139593 throw InternalException("Failed to cast result modifier to type - result modifier type mismatch");
139594 }
139595 return reinterpret_cast<const TARGET &>(*this);
139596 }
139597};
139598
139599struct BoundOrderByNode {
139600public:
139601 static constexpr const ResultModifierType
TYPE = ResultModifierType::ORDER_MODIFIER;
139602
139603public:
139604 BoundOrderByNode(OrderType type, OrderByNullType null_order, unique_ptr<Expression> expression);
139605 BoundOrderByNode(OrderType type, OrderByNullType null_order, unique_ptr<Expression> expression,
139606 unique_ptr<BaseStatistics> stats);
139607
139608 OrderType type;
139609 OrderByNullType null_order;
139610 unique_ptr<Expression> expression;
139611 unique_ptr<BaseStatistics> stats;
139612
139613public:
139614 BoundOrderByNode Copy() const;
139615 bool Equals(const BoundOrderByNode &other) const;
139616 string GetOrderModifier() const;
139617 string ToString() const;
139618
139619 void Serialize(Serializer &serializer) const;
139620 static BoundOrderByNode Deserialize(Deserializer &deserializer);
139621};
139622
139623enum class LimitNodeType :
uint8_t {
139624 UNSET = 0,
139625 CONSTANT_VALUE = 1,
139626 CONSTANT_PERCENTAGE = 2,
139627 EXPRESSION_VALUE = 3,
139628 EXPRESSION_PERCENTAGE = 4
139629};
139630
139631struct BoundLimitNode {
139632public:
139633 BoundLimitNode();
139634 BoundLimitNode(LimitNodeType type, idx_t constant_integer, double constant_percentage,
139635 unique_ptr<Expression> expression);
139636
139637public:
139638 static BoundLimitNode ConstantValue(int64_t value);
139639 static BoundLimitNode ConstantPercentage(double percentage);
139640 static BoundLimitNode ExpressionValue(unique_ptr<Expression> expression);
139641 static BoundLimitNode ExpressionPercentage(unique_ptr<Expression> expression);
139642
139643 LimitNodeType Type() const {
139644 return type;
139645 }
139646
139648 idx_t GetConstantValue()
const;
139650 double GetConstantPercentage() const;
139652 const Expression &GetValueExpression() const;
139654 const Expression &GetPercentageExpression() const;
139655
139658 unique_ptr<Expression> &GetExpression() {
139659 return expression;
139660 }
139661
139662 void Serialize(Serializer &serializer) const;
139663 static BoundLimitNode Deserialize(Deserializer &deserializer);
139664
139665private:
139666 LimitNodeType type = LimitNodeType::UNSET;
139668 idx_t constant_integer = 0;
139670 double constant_percentage = -1;
139672 unique_ptr<Expression> expression;
139673
139674private:
139675 explicit BoundLimitNode(int64_t constant_value);
139676 explicit BoundLimitNode(double percentage_value);
139677 explicit BoundLimitNode(unique_ptr<Expression> expression, bool is_percentage);
139678};
139679
139680class BoundLimitModifier : public BoundResultModifier {
139681public:
139682 static constexpr const ResultModifierType
TYPE = ResultModifierType::LIMIT_MODIFIER;
139683
139684public:
139685 BoundLimitModifier();
139686
139688 BoundLimitNode limit_val;
139690 BoundLimitNode offset_val;
139691};
139692
139693class BoundOrderModifier : public BoundResultModifier {
139694public:
139695 static constexpr const ResultModifierType
TYPE = ResultModifierType::ORDER_MODIFIER;
139696
139697public:
139698 BoundOrderModifier();
139699
139701 vector<BoundOrderByNode> orders;
139702
139703 unique_ptr<BoundOrderModifier> Copy() const;
139704 static bool Equals(const BoundOrderModifier &left, const BoundOrderModifier &right);
139705 static bool Equals(const unique_ptr<BoundOrderModifier> &left, const unique_ptr<BoundOrderModifier> &right);
139706
139707 void Serialize(Serializer &serializer) const;
139708 static unique_ptr<BoundOrderModifier> Deserialize(Deserializer &deserializer);
139709
139712 static bool Simplify(vector<BoundOrderByNode> &orders, const vector<unique_ptr<Expression>> &groups,
139713 optional_ptr<vector<GroupingSet>> grouping_sets);
139714 bool Simplify(const vector<unique_ptr<Expression>> &groups, optional_ptr<vector<GroupingSet>> grouping_sets);
139715};
139716
139717enum class DistinctType :
uint8_t { DISTINCT = 0, DISTINCT_ON = 1 };
139718
139719class BoundDistinctModifier : public BoundResultModifier {
139720public:
139721 static constexpr const ResultModifierType
TYPE = ResultModifierType::DISTINCT_MODIFIER;
139722
139723public:
139724 BoundDistinctModifier();
139725
139727 DistinctType distinct_type;
139729 vector<unique_ptr<Expression>> target_distincts;
139730};
139731
139732}
139733
139734
139735
139736namespace duckdb {
139737
139738class BufferManager;
139739class InterruptState;
139740
139743struct FrameDelta {
139744 FrameDelta() : begin(0), end(0) {};
139745 FrameDelta(int64_t begin, int64_t end) : begin(begin), end(end) {};
139748};
139749
139752
139756class ColumnDataCollection;
139757struct WindowPartitionInput {
139758 WindowPartitionInput(ExecutionContext &context, const ColumnDataCollection *inputs, const idx_t count,
139759 const vector<column_t> &column_ids, const vector<bool> &all_valid,
139760 const ValidityMask &filter_mask, const FrameStats &stats, InterruptState &interrupt_state)
139761 : context(context), inputs(inputs), count(count), column_ids(column_ids), all_valid(all_valid),
139762 filter_mask(filter_mask), stats(stats), interrupt_state(interrupt_state) {
139763 }
139764 ExecutionContext &context;
139765 const ColumnDataCollection *inputs;
139766 const idx_t count;
139767 const vector<column_t> column_ids;
139768 const vector<bool> &all_valid;
139769 const ValidityMask &filter_mask;
139771 InterruptState &interrupt_state;
139772};
139773
139775typedef idx_t (*aggregate_size_t)(
const AggregateFunction &function);
139777typedef void (*aggregate_initialize_t)(const AggregateFunction &function, data_ptr_t state);
139779typedef void (*aggregate_update_t)(Vector inputs[], AggregateInputData &aggr_input_data,
idx_t input_count,
139780 Vector &state,
idx_t count);
139782typedef void (*aggregate_combine_t)(Vector &state, Vector &combined, AggregateInputData &aggr_input_data,
idx_t count);
139784typedef void (*aggregate_finalize_t)(Vector &state, AggregateInputData &aggr_input_data, Vector &result,
idx_t count,
139787typedef unique_ptr<BaseStatistics> (*aggregate_statistics_t)(ClientContext &context, BoundAggregateExpression &expr,
139788 AggregateStatisticsInput &input);
139790typedef unique_ptr<FunctionData> (*bind_aggregate_function_t)(ClientContext &context, AggregateFunction &function,
139791 vector<unique_ptr<Expression>> &arguments);
139793typedef void (*aggregate_destructor_t)(Vector &state, AggregateInputData &aggr_input_data,
idx_t count);
139794
139796typedef void (*aggregate_simple_update_t)(Vector inputs[], AggregateInputData &aggr_input_data,
idx_t input_count,
139797 data_ptr_t state,
idx_t count);
139798
139800typedef void (*aggregate_window_t)(AggregateInputData &aggr_input_data,
const WindowPartitionInput &
partition,
139801 const_data_ptr_t g_state, data_ptr_t l_state, const SubFrames &subframes,
139802 Vector &result,
idx_t rid);
139803
139805typedef void (*aggregate_wininit_t)(AggregateInputData &aggr_input_data,
const WindowPartitionInput &
partition,
139806 data_ptr_t g_state);
139807
139808typedef void (*aggregate_serialize_t)(Serializer &serializer, const optional_ptr<FunctionData> bind_data,
139809 const AggregateFunction &function);
139810typedef unique_ptr<FunctionData> (*aggregate_deserialize_t)(Deserializer &deserializer, AggregateFunction &function);
139811
139812struct AggregateFunctionInfo {
139813 DUCKDB_API virtual ~AggregateFunctionInfo();
139814
139815 template <class TARGET>
139816 TARGET &Cast() {
139817 DynamicCastCheck<TARGET>(this);
139818 return reinterpret_cast<TARGET &>(*this);
139819 }
139820 template <class TARGET>
139821 const TARGET &Cast() const {
139822 DynamicCastCheck<TARGET>(this);
139823 return reinterpret_cast<const TARGET &>(*this);
139824 }
139825};
139826
139827enum class AggregateDestructorType {
139828 STANDARD,
139829
139830
139831 LEGACY
139832};
139833
139834class AggregateFunction : public BaseScalarFunction {
139835public:
139836 AggregateFunction(const string &name, const vector<LogicalType> &arguments, const LogicalType &return_type,
139837 aggregate_size_t state_size, aggregate_initialize_t initialize, aggregate_update_t update,
139838 aggregate_combine_t combine, aggregate_finalize_t finalize,
139839 FunctionNullHandling null_handling = FunctionNullHandling::DEFAULT_NULL_HANDLING,
139840 aggregate_simple_update_t simple_update = nullptr, bind_aggregate_function_t bind = nullptr,
139841 aggregate_destructor_t destructor = nullptr, aggregate_statistics_t statistics = nullptr,
139842 aggregate_window_t window = nullptr, aggregate_serialize_t serialize = nullptr,
139843 aggregate_deserialize_t deserialize = nullptr)
139844 : BaseScalarFunction(name, arguments, return_type,
FunctionStability::CONSISTENT,
139846 state_size(state_size), initialize(initialize), update(update),
combine(
combine), finalize(finalize),
139847 simple_update(simple_update), window(window),
bind(
bind), destructor(destructor), statistics(statistics),
139850 }
139851
139852 AggregateFunction(const string &name, const vector<LogicalType> &arguments, const LogicalType &return_type,
139853 aggregate_size_t state_size, aggregate_initialize_t initialize, aggregate_update_t update,
139854 aggregate_combine_t combine, aggregate_finalize_t finalize,
139855 aggregate_simple_update_t simple_update = nullptr, bind_aggregate_function_t bind = nullptr,
139856 aggregate_destructor_t destructor = nullptr, aggregate_statistics_t statistics = nullptr,
139857 aggregate_window_t window = nullptr, aggregate_serialize_t serialize = nullptr,
139858 aggregate_deserialize_t deserialize = nullptr)
139859 : BaseScalarFunction(name, arguments, return_type,
FunctionStability::CONSISTENT,
139861 state_size(state_size), initialize(initialize), update(update),
combine(
combine), finalize(finalize),
139862 simple_update(simple_update), window(window),
bind(
bind), destructor(destructor), statistics(statistics),
139865 }
139866
139867 AggregateFunction(const vector<LogicalType> &arguments, const LogicalType &return_type, aggregate_size_t state_size,
139868 aggregate_initialize_t initialize, aggregate_update_t update, aggregate_combine_t combine,
139869 aggregate_finalize_t finalize,
139870 FunctionNullHandling null_handling = FunctionNullHandling::DEFAULT_NULL_HANDLING,
139871 aggregate_simple_update_t simple_update = nullptr, bind_aggregate_function_t bind = nullptr,
139872 aggregate_destructor_t destructor = nullptr, aggregate_statistics_t statistics = nullptr,
139873 aggregate_window_t window = nullptr, aggregate_serialize_t serialize = nullptr,
139874 aggregate_deserialize_t deserialize = nullptr)
139875 : AggregateFunction(string(), arguments, return_type, state_size, initialize, update,
combine, finalize,
139876 null_handling, simple_update,
bind, destructor, statistics, window,
serialize,
139878 }
139879
139880 AggregateFunction(const vector<LogicalType> &arguments, const LogicalType &return_type, aggregate_size_t state_size,
139881 aggregate_initialize_t initialize, aggregate_update_t update, aggregate_combine_t combine,
139882 aggregate_finalize_t finalize, aggregate_simple_update_t simple_update = nullptr,
139883 bind_aggregate_function_t bind = nullptr, aggregate_destructor_t destructor = nullptr,
139884 aggregate_statistics_t statistics = nullptr, aggregate_window_t window = nullptr,
139885 aggregate_serialize_t serialize = nullptr, aggregate_deserialize_t deserialize = nullptr)
139886 : AggregateFunction(string(), arguments, return_type, state_size, initialize, update,
combine, finalize,
139889 }
139890
139891
139892 AggregateFunction(const vector<LogicalType> &arguments, const LogicalType &return_type, aggregate_size_t state_size,
139893 aggregate_initialize_t initialize, aggregate_wininit_t window_init, aggregate_window_t window,
139894 bind_aggregate_function_t bind = nullptr, aggregate_destructor_t destructor = nullptr,
139895 aggregate_statistics_t statistics = nullptr, aggregate_serialize_t serialize = nullptr,
139896 aggregate_deserialize_t deserialize = nullptr)
139897 : BaseScalarFunction(name, arguments, return_type,
FunctionStability::CONSISTENT,
139899 state_size(state_size), initialize(initialize), update(nullptr),
combine(nullptr), finalize(nullptr),
139900 simple_update(nullptr), window(window), window_init(window_init),
bind(
bind), destructor(destructor),
139904 }
139905
139906
139907 bool HasBindCallback()
const {
return bind !=
nullptr; }
139909 void SetBindCallback(bind_aggregate_function_t callback) {
bind = callback; }
139910
139911 bool HasStateInitCallback() const { return initialize != nullptr; }
139913 void SetStateInitCallback(aggregate_initialize_t callback) { initialize = callback; }
139914
139915 bool HasStateSizeCallback() const { return state_size != nullptr; }
139917 void SetStateSizeCallback(aggregate_size_t callback) { state_size = callback; }
139918
139919 bool HasStateDestructorCallback() const { return destructor != nullptr; }
139921 void SetStateDestructorCallback(aggregate_destructor_t callback) { destructor = callback; }
139922
139923 bool HasStateUpdateCallback() const { return update != nullptr; }
139925 void SetStateUpdateCallback(aggregate_update_t callback) { update = callback; }
139926
139927 bool HasStateSimpleUpdateCallback() const { return simple_update != nullptr; }
139929 void SetStateSimpleUpdateCallback(aggregate_simple_update_t callback) { simple_update = callback; }
139930
139931 void SetStateCombineCallback(aggregate_combine_t callback) {
combine = callback; }
139933 bool HasStateCombineCallback()
const {
return combine !=
nullptr; }
139934
139935 void SetStateFinalizeCallback(aggregate_finalize_t callback) { finalize = callback; }
139937 bool HasStateFinalizeCallback() const { return finalize != nullptr; }
139938
139939 bool HasWindowCallback() const { return window != nullptr; }
139941 void SetWindowCallback(aggregate_window_t callback) { window = callback; }
139942
139943 void SetWindowInitCallback(aggregate_wininit_t callback) { window_init = callback; }
139945 bool HasWindowInitCallback() const { return window_init != nullptr; }
139946
139947 bool HasStatisticsCallback() const { return statistics != nullptr; }
139949 void SetStatisticsCallback(aggregate_statistics_t callback) { statistics = callback; }
139950
139951 bool HasSerializationCallbacks()
const {
return serialize !=
nullptr &&
deserialize !=
nullptr; }
139952 void SetSerializeCallback(aggregate_serialize_t callback) {
serialize = callback; }
139953 void SetDeserializeCallback(aggregate_deserialize_t callback) {
deserialize = callback; }
139954 aggregate_serialize_t GetSerializeCallback()
const {
return serialize; }
139955 aggregate_deserialize_t GetDeserializeCallback()
const {
return deserialize; }
139956
139957
139958public:
139975
139980
139983
139986
139991
139993 return order_dependent;
139994 }
139995 void SetOrderDependent(AggregateOrderDependent value) {
139996 order_dependent = value;
139997 }
139999 return distinct_dependent;
140000 }
140001 void SetDistinctDependent(AggregateDistinctDependent value) {
140002 distinct_dependent = value;
140003 }
140004
140006 shared_ptr<AggregateFunctionInfo> function_info;
140007
140008public:
140009 bool operator==(
const AggregateFunction &rhs)
const {
140010 return state_size == rhs.state_size && initialize == rhs.initialize && update == rhs.update &&
140011 combine == rhs.combine && finalize == rhs.finalize && window == rhs.window;
140012 }
140013 bool operator!=(
const AggregateFunction &rhs)
const {
140014 return !(*this == rhs);
140015 }
140016
140017 bool CanAggregate() const {
140018 return update ||
combine || finalize;
140019 }
140020 bool CanWindow() const {
140021 return window;
140022 }
140023
140024public:
140025 template <class STATE, class RESULT_TYPE, class OP>
140026 static AggregateFunction NullaryAggregate(LogicalType return_type) {
140027 return AggregateFunction(
140028 {}, return_type, AggregateFunction::StateSize<STATE>, AggregateFunction::StateInitialize<STATE, OP>,
140029 AggregateFunction::NullaryScatterUpdate<STATE, OP>, AggregateFunction::StateCombine<STATE, OP>,
140030 AggregateFunction::StateFinalize<STATE, RESULT_TYPE, OP>, AggregateFunction::NullaryUpdate<STATE, OP>);
140031 }
140032
140033 template <class STATE, class INPUT_TYPE, class RESULT_TYPE, class OP,
140034 AggregateDestructorType destructor_type = AggregateDestructorType::STANDARD>
140035 static AggregateFunction
140036 UnaryAggregate(const LogicalType &input_type, LogicalType return_type,
140037 FunctionNullHandling null_handling = FunctionNullHandling::DEFAULT_NULL_HANDLING) {
140038 return AggregateFunction({input_type}, return_type, AggregateFunction::StateSize<STATE>,
140039 AggregateFunction::StateInitialize<STATE, OP, destructor_type>,
140040 AggregateFunction::UnaryScatterUpdate<STATE, INPUT_TYPE, OP>,
140041 AggregateFunction::StateCombine<STATE, OP>,
140042 AggregateFunction::StateFinalize<STATE, RESULT_TYPE, OP>, null_handling,
140043 AggregateFunction::UnaryUpdate<STATE, INPUT_TYPE, OP>);
140044 }
140045
140046 template <class STATE, class INPUT_TYPE, class RESULT_TYPE, class OP,
140047 AggregateDestructorType destructor_type = AggregateDestructorType::STANDARD>
140048 static AggregateFunction UnaryAggregateDestructor(LogicalType input_type, LogicalType return_type) {
140049 auto aggregate = UnaryAggregate<STATE, INPUT_TYPE, RESULT_TYPE, OP, destructor_type>(input_type, return_type);
140050 aggregate.destructor = AggregateFunction::StateDestroy<STATE, OP>;
140051 return aggregate;
140052 }
140053
140054 template <class STATE, class A_TYPE, class B_TYPE, class RESULT_TYPE, class OP,
140055 AggregateDestructorType destructor_type = AggregateDestructorType::STANDARD>
140056 static AggregateFunction BinaryAggregate(const LogicalType &a_type, const LogicalType &b_type,
140057 LogicalType return_type) {
140058 return AggregateFunction({a_type, b_type}, return_type, AggregateFunction::StateSize<STATE>,
140059 AggregateFunction::StateInitialize<STATE, OP, destructor_type>,
140060 AggregateFunction::BinaryScatterUpdate<STATE, A_TYPE, B_TYPE, OP>,
140061 AggregateFunction::StateCombine<STATE, OP>,
140062 AggregateFunction::StateFinalize<STATE, RESULT_TYPE, OP>,
140063 AggregateFunction::BinaryUpdate<STATE, A_TYPE, B_TYPE, OP>);
140064 }
140065
140066public:
140067 template <class STATE>
140068 static idx_t StateSize(
const AggregateFunction &) {
140069 return sizeof(STATE);
140070 }
140071
140072 template <class STATE, class OP, AggregateDestructorType destructor_type = AggregateDestructorType::STANDARD>
140073 static void StateInitialize(const AggregateFunction &, data_ptr_t state) {
140074
140075#if !defined(__GNUC__) || (__GNUC__ >= 5)
140076 static_assert(std::is_trivially_move_constructible<STATE>::value ||
140077 destructor_type == AggregateDestructorType::LEGACY,
140078 "Aggregate state must be trivially move constructible");
140079#endif
140080 OP::Initialize(*reinterpret_cast<STATE *>(state));
140081 }
140082
140083 template <class STATE, class OP>
140084 static void NullaryScatterUpdate(Vector inputs[], AggregateInputData &aggr_input_data, idx_t input_count,
140085 Vector &states, idx_t count) {
140086 D_ASSERT(input_count == 0);
140087 AggregateExecutor::NullaryScatter<STATE, OP>(states, aggr_input_data, count);
140088 }
140089
140090 template <class STATE, class OP>
140091 static void NullaryUpdate(Vector inputs[], AggregateInputData &aggr_input_data, idx_t input_count, data_ptr_t state,
140092 idx_t count) {
140093 D_ASSERT(input_count == 0);
140094 AggregateExecutor::NullaryUpdate<STATE, OP>(state, aggr_input_data, count);
140095 }
140096
140097 template <class STATE, class T, class OP>
140098 static void UnaryScatterUpdate(Vector inputs[], AggregateInputData &aggr_input_data, idx_t input_count,
140099 Vector &states, idx_t count) {
140100 D_ASSERT(input_count == 1);
140101 AggregateExecutor::UnaryScatter<STATE, T, OP>(inputs[0], states, aggr_input_data, count);
140102 }
140103
140104 template <class STATE, class INPUT_TYPE, class OP>
140105 static void UnaryUpdate(Vector inputs[], AggregateInputData &aggr_input_data, idx_t input_count, data_ptr_t state,
140106 idx_t count) {
140107 D_ASSERT(input_count == 1);
140108 AggregateExecutor::UnaryUpdate<STATE, INPUT_TYPE, OP>(inputs[0], aggr_input_data, state, count);
140109 }
140110
140111 template <class STATE, class A_TYPE, class B_TYPE, class OP>
140112 static void BinaryScatterUpdate(Vector inputs[], AggregateInputData &aggr_input_data, idx_t input_count,
140113 Vector &states, idx_t count) {
140114 D_ASSERT(input_count == 2);
140115 AggregateExecutor::BinaryScatter<STATE, A_TYPE, B_TYPE, OP>(aggr_input_data, inputs[0], inputs[1], states,
140116 count);
140117 }
140118
140119 template <class STATE, class A_TYPE, class B_TYPE, class OP>
140120 static void BinaryUpdate(Vector inputs[], AggregateInputData &aggr_input_data, idx_t input_count, data_ptr_t state,
140121 idx_t count) {
140122 D_ASSERT(input_count == 2);
140123 AggregateExecutor::BinaryUpdate<STATE, A_TYPE, B_TYPE, OP>(aggr_input_data, inputs[0], inputs[1], state, count);
140124 }
140125
140126 template <class STATE, class OP>
140127 static void StateCombine(Vector &source, Vector &target, AggregateInputData &aggr_input_data, idx_t count) {
140128 AggregateExecutor::Combine<STATE, OP>(source, target, aggr_input_data, count);
140129 }
140130
140131 template <class STATE, class RESULT_TYPE, class OP>
140132 static void StateFinalize(Vector &states, AggregateInputData &aggr_input_data, Vector &result, idx_t count,
140133 idx_t offset) {
140134 AggregateExecutor::Finalize<STATE, RESULT_TYPE, OP>(states, aggr_input_data, result, count, offset);
140135 }
140136
140137 template <class STATE, class OP>
140138 static void StateVoidFinalize(Vector &states, AggregateInputData &aggr_input_data, Vector &result, idx_t count,
140139 idx_t offset) {
140140 AggregateExecutor::VoidFinalize<STATE, OP>(states, aggr_input_data, result, count, offset);
140141 }
140142
140143 template <class STATE, class OP>
140144 static void StateDestroy(Vector &states, AggregateInputData &aggr_input_data, idx_t count) {
140145 AggregateExecutor::Destroy<STATE, OP>(states, aggr_input_data, count);
140146 }
140147};
140148
140149}
140150
140151
140152namespace duckdb {
140153
140154
140155
140156struct UDFWrapper {
140157public:
140158 template <typename TR, typename... ARGS>
140159 inline static scalar_function_t CreateScalarFunction(
const string &name, TR (*udf_func)(ARGS...)) {
140160 const std::size_t num_template_argc = sizeof...(ARGS);
140161 switch (num_template_argc) {
140162 case 1:
140163 return CreateUnaryFunction<TR, ARGS...>(name, udf_func);
140164 case 2:
140165 return CreateBinaryFunction<TR, ARGS...>(name, udf_func);
140166 case 3:
140167 return CreateTernaryFunction<TR, ARGS...>(name, udf_func);
140168 default:
140169 throw std::runtime_error("UDF function only supported until ternary!");
140170 }
140171 }
140172
140173 template <typename TR, typename... ARGS>
140174 inline static scalar_function_t CreateScalarFunction(
const string &name,
const vector<LogicalType> &args,
140175 const LogicalType &ret_type, TR (*udf_func)(ARGS...)) {
140176 if (!TypesMatch<TR>(ret_type)) {
140177 throw std::runtime_error("Return type doesn't match with the first template type.");
140178 }
140179
140180 const std::size_t num_template_types = sizeof...(ARGS);
140181 if (num_template_types != args.size()) {
140182 throw std::runtime_error(
140183 "The number of templated types should be the same quantity of the LogicalType arguments.");
140184 }
140185
140186 switch (num_template_types) {
140187 case 1:
140188 return CreateUnaryFunction<TR, ARGS...>(name, args, ret_type, udf_func);
140189 case 2:
140190 return CreateBinaryFunction<TR, ARGS...>(name, args, ret_type, udf_func);
140191 case 3:
140192 return CreateTernaryFunction<TR, ARGS...>(name, args, ret_type, udf_func);
140193 default:
140194 throw std::runtime_error("UDF function only supported until ternary!");
140195 }
140196 }
140197
140198 template <typename TR, typename... ARGS>
140199 inline static void RegisterFunction(const string &name, scalar_function_t udf_function, ClientContext &context,
140200 LogicalType varargs = LogicalType(LogicalTypeId::INVALID)) {
140201 vector<LogicalType> arguments;
140202 GetArgumentTypesRecursive<ARGS...>(arguments);
140203
140204 LogicalType ret_type = GetArgumentType<TR>();
140205
140206 RegisterFunction(name, arguments, ret_type, std::move(udf_function), context, std::move(varargs));
140207 }
140208
140209 static void RegisterFunction(string name, vector<LogicalType> args, LogicalType ret_type,
140210 scalar_function_t udf_function, ClientContext &context,
140211 LogicalType varargs = LogicalType(LogicalTypeId::INVALID));
140212
140213
140214 template <typename UDF_OP, typename STATE, typename TR, typename TA>
140215 inline static AggregateFunction CreateAggregateFunction(const string &name) {
140216 return CreateUnaryAggregateFunction<UDF_OP, STATE, TR, TA>(name);
140217 }
140218
140219 template <typename UDF_OP, typename STATE, typename TR, typename TA, typename TB>
140220 inline static AggregateFunction CreateAggregateFunction(const string &name) {
140221 return CreateBinaryAggregateFunction<UDF_OP, STATE, TR, TA, TB>(name);
140222 }
140223
140224 template <typename UDF_OP, typename STATE, typename TR, typename TA>
140225 inline static AggregateFunction CreateAggregateFunction(const string &name, const LogicalType &ret_type,
140226 const LogicalType &input_type) {
140227 if (!TypesMatch<TR>(ret_type)) {
140228 throw std::runtime_error("The return argument don't match!");
140229 }
140230
140231 if (!TypesMatch<TA>(input_type)) {
140232 throw std::runtime_error("The input argument don't match!");
140233 }
140234
140235 return CreateUnaryAggregateFunction<UDF_OP, STATE, TR, TA>(name, ret_type, input_type);
140236 }
140237
140238 template <typename UDF_OP, typename STATE, typename TR, typename TA, typename TB>
140239 inline static AggregateFunction CreateAggregateFunction(const string &name, const LogicalType &ret_type,
140240 const LogicalType &input_type_a,
140241 const LogicalType &input_type_b) {
140242 if (!TypesMatch<TR>(ret_type)) {
140243 throw std::runtime_error("The return argument don't match!");
140244 }
140245
140246 if (!TypesMatch<TA>(input_type_a)) {
140247 throw std::runtime_error("The first input argument don't match!");
140248 }
140249
140250 if (!TypesMatch<TB>(input_type_b)) {
140251 throw std::runtime_error("The second input argument don't match!");
140252 }
140253
140254 return CreateBinaryAggregateFunction<UDF_OP, STATE, TR, TA, TB>(name, ret_type, input_type_a, input_type_b);
140255 }
140256
140258 inline static AggregateFunction
140259 CreateAggregateFunction(const string &name, const vector<LogicalType> &arguments, const LogicalType &return_type,
140260 aggregate_size_t state_size, aggregate_initialize_t initialize, aggregate_update_t update,
140261 aggregate_combine_t combine, aggregate_finalize_t finalize,
140262 aggregate_simple_update_t simple_update = nullptr, bind_aggregate_function_t bind = nullptr,
140263 aggregate_destructor_t destructor = nullptr) {
140264 AggregateFunction aggr_function(name, arguments, return_type, state_size, initialize, update, combine, finalize,
140265 simple_update, bind, destructor);
140266 aggr_function.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING);
140267 return aggr_function;
140268 }
140269
140270 static void RegisterAggrFunction(AggregateFunction aggr_function, ClientContext &context,
140271 LogicalType varargs = LogicalType(LogicalTypeId::INVALID));
140272
140273private:
140274
140275 struct UnaryUDFExecutor {
140276 template <class INPUT_TYPE, class RESULT_TYPE>
140277 static RESULT_TYPE Operation(INPUT_TYPE input, ValidityMask &mask, idx_t idx, void *dataptr) {
140278 typedef RESULT_TYPE (*unary_function_t)(INPUT_TYPE);
140279 auto udf = (unary_function_t)dataptr;
140280 return udf(input);
140281 }
140282 };
140283
140284 template <typename TR, typename TA>
140285 inline static scalar_function_t CreateUnaryFunction(
const string &name, TR (*udf_func)(TA)) {
140286 scalar_function_t udf_function = [=](DataChunk &input, ExpressionState &state, Vector &result) ->
void {
140287 UnaryExecutor::GenericExecute<TA, TR, UnaryUDFExecutor>(input.
data[0], result, input.size(),
140288 (void *)udf_func);
140289 };
140290 return udf_function;
140291 }
140292
140293 template <typename TR, typename TA, typename TB>
140294 inline static scalar_function_t CreateBinaryFunction(
const string &name, TR (*udf_func)(TA, TB)) {
140295 scalar_function_t udf_function = [=](DataChunk &input, ExpressionState &state, Vector &result) ->
void {
140296 BinaryExecutor::Execute<TA, TB, TR>(input.
data[0], input.
data[1], result, input.size(), udf_func);
140297 };
140298 return udf_function;
140299 }
140300
140301 template <typename TR, typename TA, typename TB, typename TC>
140302 inline static scalar_function_t CreateTernaryFunction(
const string &name, TR (*udf_func)(TA, TB, TC)) {
140303 scalar_function_t udf_function = [=](DataChunk &input, ExpressionState &state, Vector &result) ->
void {
140304 TernaryExecutor::Execute<TA, TB, TC, TR>(input.
data[0], input.
data[1], input.
data[2], result, input.size(),
140305 udf_func);
140306 };
140307 return udf_function;
140308 }
140309
140310 template <typename TR, typename... ARGS>
140312 TR (*udf_func)(ARGS...)) {
140313 throw std::runtime_error("Incorrect number of arguments for unary function");
140314 }
140315
140316 template <typename TR, typename... ARGS>
140318 TR (*udf_func)(ARGS...)) {
140319 throw std::runtime_error("Incorrect number of arguments for binary function");
140320 }
140321
140322 template <typename TR, typename... ARGS>
140324 TR (*udf_func)(ARGS...)) {
140325 throw std::runtime_error("Incorrect number of arguments for ternary function");
140326 }
140327
140328 template <typename T>
140329 inline static LogicalType GetArgumentType() {
140330 if (std::is_same<T, bool>()) {
140331 return LogicalType(LogicalTypeId::BOOLEAN);
140332 } else if (std::is_same<T, int8_t>()) {
140333 return LogicalType(LogicalTypeId::TINYINT);
140334 } else if (std::is_same<T, int16_t>()) {
140335 return LogicalType(LogicalTypeId::SMALLINT);
140336 } else if (std::is_same<T, int32_t>()) {
140337 return LogicalType(LogicalTypeId::INTEGER);
140338 } else if (std::is_same<T, int64_t>()) {
140339 return LogicalType(LogicalTypeId::BIGINT);
140340 } else if (std::is_same<T, float>()) {
140341 return LogicalType(LogicalTypeId::FLOAT);
140342 } else if (std::is_same<T, double>()) {
140343 return LogicalType(LogicalTypeId::DOUBLE);
140344 } else if (std::is_same<T, string_t>()) {
140345 return LogicalType(LogicalTypeId::VARCHAR);
140346 } else {
140347 throw std::runtime_error("Unrecognized type!");
140348 }
140349 }
140350
140351 template <typename TA, typename TB, typename... ARGS>
140352 inline static void GetArgumentTypesRecursive(vector<LogicalType> &arguments) {
140353 arguments.push_back(GetArgumentType<TA>());
140354 GetArgumentTypesRecursive<TB, ARGS...>(arguments);
140355 }
140356
140357 template <typename TA>
140358 inline static void GetArgumentTypesRecursive(vector<LogicalType> &arguments) {
140359 arguments.push_back(GetArgumentType<TA>());
140360 }
140361
140362private:
140363
140364
140365 template <typename TR, typename... ARGS>
140366 inline static scalar_function_t CreateUnaryFunction(
const string &name,
const vector<LogicalType> &args,
140367 const LogicalType &ret_type,
140368 TR (*udf_func)(ARGS...)) {
140369 throw std::runtime_error("Incorrect number of arguments for unary function");
140370 }
140371
140372 template <typename TR, typename TA>
140373 inline static scalar_function_t CreateUnaryFunction(
const string &name,
const vector<LogicalType> &args,
140374 const LogicalType &ret_type, TR (*udf_func)(TA)) {
140375 if (args.size() != 1) {
140376 throw std::runtime_error("The number of LogicalType arguments (\"args\") should be 1!");
140377 }
140378 if (!TypesMatch<TA>(args[0])) {
140379 throw std::runtime_error("The first arguments don't match!");
140380 }
140381
140382 scalar_function_t udf_function = [=](DataChunk &input, ExpressionState &state, Vector &result) ->
void {
140383 UnaryExecutor::GenericExecute<TA, TR, UnaryUDFExecutor>(input.
data[0], result, input.size(),
140384 (void *)udf_func);
140385 };
140386 return udf_function;
140387 }
140388
140389 template <typename TR, typename... ARGS>
140390 inline static scalar_function_t CreateBinaryFunction(
const string &name,
const vector<LogicalType> &args,
140391 const LogicalType &ret_type,
140392 TR (*udf_func)(ARGS...)) {
140393 throw std::runtime_error("Incorrect number of arguments for binary function");
140394 }
140395
140396 template <typename TR, typename TA, typename TB>
140397 inline static scalar_function_t CreateBinaryFunction(
const string &name,
const vector<LogicalType> &args,
140398 const LogicalType &ret_type, TR (*udf_func)(TA, TB)) {
140399 if (args.size() != 2) {
140400 throw std::runtime_error("The number of LogicalType arguments (\"args\") should be 2!");
140401 }
140402 if (!TypesMatch<TA>(args[0])) {
140403 throw std::runtime_error("The first arguments don't match!");
140404 }
140405 if (!TypesMatch<TB>(args[1])) {
140406 throw std::runtime_error("The second arguments don't match!");
140407 }
140408
140409 scalar_function_t udf_function = [=](DataChunk &input, ExpressionState &state, Vector &result) {
140410 BinaryExecutor::Execute<TA, TB, TR>(input.
data[0], input.
data[1], result, input.size(), udf_func);
140411 };
140412 return udf_function;
140413 }
140414
140415 template <typename TR, typename... ARGS>
140416 inline static scalar_function_t CreateTernaryFunction(
const string &name,
const vector<LogicalType> &args,
140417 const LogicalType &ret_type,
140418 TR (*udf_func)(ARGS...)) {
140419 throw std::runtime_error("Incorrect number of arguments for ternary function");
140420 }
140421
140422 template <typename TR, typename TA, typename TB, typename TC>
140423 inline static scalar_function_t CreateTernaryFunction(
const string &name,
const vector<LogicalType> &args,
140424 const LogicalType &ret_type, TR (*udf_func)(TA, TB, TC)) {
140425 if (args.size() != 3) {
140426 throw std::runtime_error("The number of LogicalType arguments (\"args\") should be 3!");
140427 }
140428 if (!TypesMatch<TA>(args[0])) {
140429 throw std::runtime_error("The first arguments don't match!");
140430 }
140431 if (!TypesMatch<TB>(args[1])) {
140432 throw std::runtime_error("The second arguments don't match!");
140433 }
140434 if (!TypesMatch<TC>(args[2])) {
140435 throw std::runtime_error("The second arguments don't match!");
140436 }
140437
140438 scalar_function_t udf_function = [=](DataChunk &input, ExpressionState &state, Vector &result) ->
void {
140439 TernaryExecutor::Execute<TA, TB, TC, TR>(input.
data[0], input.
data[1], input.
data[2], result, input.size(),
140440 udf_func);
140441 };
140442 return udf_function;
140443 }
140444
140445 template <typename T>
140446 inline static bool TypesMatch(const LogicalType &sql_type) {
140447 switch (sql_type.id()) {
140448 case LogicalTypeId::BOOLEAN:
140449 return std::is_same<T, bool>();
140450 case LogicalTypeId::TINYINT:
140451 return std::is_same<T, int8_t>();
140452 case LogicalTypeId::SMALLINT:
140453 return std::is_same<T, int16_t>();
140454 case LogicalTypeId::INTEGER:
140455 return std::is_same<T, int32_t>();
140456 case LogicalTypeId::BIGINT:
140457 return std::is_same<T, int64_t>();
140458 case LogicalTypeId::DATE:
140459 return std::is_same<T, date_t>();
140460 case LogicalTypeId::TIME:
140461 return std::is_same<T, dtime_t>();
140462 case LogicalTypeId::TIME_NS:
140463 return std::is_same<T, dtime_ns_t>();
140464 case LogicalTypeId::TIME_TZ:
140465 return std::is_same<T, dtime_tz_t>();
140466 case LogicalTypeId::TIMESTAMP:
140467 case LogicalTypeId::TIMESTAMP_MS:
140468 case LogicalTypeId::TIMESTAMP_NS:
140469 case LogicalTypeId::TIMESTAMP_SEC:
140470 case LogicalTypeId::TIMESTAMP_TZ:
140471 return std::is_same<T, timestamp_t>();
140472 case LogicalTypeId::FLOAT:
140473 return std::is_same<T, float>();
140474 case LogicalTypeId::DOUBLE:
140475 return std::is_same<T, double>();
140476 case LogicalTypeId::VARCHAR:
140477 case LogicalTypeId::CHAR:
140478 case LogicalTypeId::BLOB:
140479 return std::is_same<T, string_t>();
140480 default:
140481 throw std::runtime_error("Type is not supported!");
140482 }
140483 }
140484
140485private:
140486
140487 template <typename UDF_OP, typename STATE, typename TR, typename TA>
140488 inline static AggregateFunction CreateUnaryAggregateFunction(const string &name) {
140489 LogicalType return_type = GetArgumentType<TR>();
140490 LogicalType input_type = GetArgumentType<TA>();
140491 return CreateUnaryAggregateFunction<UDF_OP, STATE, TR, TA>(name, return_type, input_type);
140492 }
140493
140494 template <typename UDF_OP, typename STATE, typename TR, typename TA>
140495 inline static AggregateFunction CreateUnaryAggregateFunction(const string &name, const LogicalType &ret_type,
140496 const LogicalType &input_type) {
140497 AggregateFunction aggr_function =
140498 AggregateFunction::UnaryAggregate<STATE, TR, TA, UDF_OP>(input_type, ret_type);
140499 aggr_function.name = name;
140500 return aggr_function;
140501 }
140502
140503 template <typename UDF_OP, typename STATE, typename TR, typename TA, typename TB>
140504 inline static AggregateFunction CreateBinaryAggregateFunction(const string &name) {
140505 LogicalType return_type = GetArgumentType<TR>();
140506 LogicalType input_type_a = GetArgumentType<TA>();
140507 LogicalType input_type_b = GetArgumentType<TB>();
140508 return CreateBinaryAggregateFunction<UDF_OP, STATE, TR, TA, TB>(name, return_type, input_type_a, input_type_b);
140509 }
140510
140511 template <typename UDF_OP, typename STATE, typename TR, typename TA, typename TB>
140512 inline static AggregateFunction CreateBinaryAggregateFunction(const string &name, const LogicalType &ret_type,
140513 const LogicalType &input_type_a,
140514 const LogicalType &input_type_b) {
140515 AggregateFunction aggr_function =
140516 AggregateFunction::BinaryAggregate<STATE, TA, TB, TR, UDF_OP>(input_type_a, input_type_b, ret_type);
140517 aggr_function.name = name;
140518 return aggr_function;
140519 }
140520};
140521
140522
140523
140524}
140525
140526
140527
140528
140529
140530
140531
140532
140533
140534
140535
140536
140537
140538
140539
140540
140541
140542
140543
140544
140545
140546
140547
140548
140549
140550
140551
140552
140553
140554
140555
140556
140557
140558
140559
140560
140561
140562
140563
140564
140565
140566
140567
140568
140569
140570
140571namespace duckdb {
140572
140581};
140582
140584 INVALID,
140591};
140592
140595 REGULAR,
140599};
140600
140601struct ChunkManagementState {
140602 unordered_map<idx_t, BufferHandle> handles;
140604};
140605
140606struct ColumnDataAppendState {
140607 ChunkManagementState current_chunk_state;
140608 vector<UnifiedVectorFormat> vector_data;
140609};
140610
140611struct ColumnDataScanState {
140613 shared_ptr<DatabaseInstance>
db;
140614
140615 ChunkManagementState current_chunk_state;
140616 idx_t segment_index;
140617 idx_t chunk_index;
140618 idx_t current_row_index;
140619 idx_t next_row_index;
140621 vector<column_t> column_ids;
140622};
140623
140624struct ColumnDataParallelScanState {
140625 ColumnDataScanState scan_state;
140626 mutex lock;
140627};
140628
140629struct ColumnDataLocalScanState {
140630 ChunkManagementState current_chunk_state;
140631 idx_t current_segment_index = DConstants::INVALID_INDEX;
140632 idx_t current_row_index;
140633};
140634
140635class ColumnDataRow {
140636public:
140637 ColumnDataRow(DataChunk &chunk, idx_t row_index, idx_t base_index);
140638
140639 DataChunk &chunk;
140642
140643public:
140644 Value GetValue(idx_t column_index) const;
140645 idx_t RowIndex()
const;
140646};
140647
140648}
140649
140650
140651namespace duckdb {
140652class ColumnDataCollection;
140653
140654class ColumnDataChunkIterationHelper {
140655public:
140656 DUCKDB_API ColumnDataChunkIterationHelper(const ColumnDataCollection &collection, vector<column_t> column_ids);
140657
140658private:
140659 const ColumnDataCollection &collection;
140660 vector<column_t> column_ids;
140661
140662private:
140663 class ColumnDataChunkIterator;
140664
140665 class ColumnDataChunkIterator {
140666 public:
140667 DUCKDB_API ColumnDataChunkIterator(optional_ptr<const ColumnDataCollection> collection_p,
140668 vector<column_t> column_ids);
140670 DUCKDB_API ColumnDataChunkIterator(ColumnDataChunkIterator &&other) noexcept;
140671
140672 optional_ptr<const ColumnDataCollection> collection;
140673 ColumnDataScanState scan_state;
140674 unique_ptr<DataChunk> scan_chunk;
140676
140677 public:
140678 DUCKDB_API void Next();
140679
140680 DUCKDB_API ColumnDataChunkIterator &operator++();
140681 DUCKDB_API
bool operator!=(
const ColumnDataChunkIterator &other)
const;
140682 DUCKDB_API DataChunk &
operator*()
const;
140683 };
140684
140685public:
140686 ColumnDataChunkIterator begin() {
140687 return ColumnDataChunkIterator(&collection, column_ids);
140688 }
140689 ColumnDataChunkIterator end() {
140690 return ColumnDataChunkIterator(nullptr, vector<column_t>());
140691 }
140692};
140693
140694class ColumnDataRowIterationHelper {
140695public:
140696 DUCKDB_API explicit ColumnDataRowIterationHelper(const ColumnDataCollection &collection);
140697
140698private:
140699 const ColumnDataCollection &collection;
140700
140701private:
140702 class ColumnDataRowIterator;
140703
140704 class ColumnDataRowIterator {
140705 public:
140706 DUCKDB_API explicit ColumnDataRowIterator(
140707 const ColumnDataCollection *collection_p,
140708 ColumnDataScanProperties properties = ColumnDataScanProperties::DISALLOW_ZERO_COPY);
140709
140710 const ColumnDataCollection *collection;
140711 ColumnDataScanState scan_state;
140712 shared_ptr<DataChunk> scan_chunk;
140713 ColumnDataRow current_row;
140714
140715 public:
140716 void Next();
140717
140718 DUCKDB_API ColumnDataRowIterator &operator++();
140719 DUCKDB_API
bool operator!=(
const ColumnDataRowIterator &other)
const;
140720 DUCKDB_API
const ColumnDataRow &
operator*()
const;
140721 };
140722
140723public:
140724 DUCKDB_API ColumnDataRowIterator begin();
140725 DUCKDB_API ColumnDataRowIterator end();
140726};
140727
140728}
140729
140730
140731namespace duckdb {
140732
140733class BufferManager;
140734class BlockHandle;
140735class ClientContext;
140736struct ColumnDataCopyFunction;
140737class ColumnDataAllocator;
140738class ColumnDataCollection;
140739class ColumnDataCollectionSegment;
140740class ColumnDataRowCollection;
140741
140744class ColumnDataCollection {
140745public:
140747 DUCKDB_API ColumnDataCollection(Allocator &allocator, vector<LogicalType> types);
140749 DUCKDB_API explicit ColumnDataCollection(Allocator &allocator);
140751 DUCKDB_API
140752 ColumnDataCollection(BufferManager &buffer_manager, vector<LogicalType> types,
140753 ColumnDataCollectionLifetime lifetime = ColumnDataCollectionLifetime::REGULAR);
140755 DUCKDB_API
140756 ColumnDataCollection(ClientContext &context, vector<LogicalType> types,
140757 ColumnDataAllocatorType type = ColumnDataAllocatorType::BUFFER_MANAGER_ALLOCATOR,
140758 ColumnDataCollectionLifetime lifetime = ColumnDataCollectionLifetime::REGULAR);
140763 DUCKDB_API ColumnDataCollection(ColumnDataCollection &parent);
140764 DUCKDB_API ColumnDataCollection(shared_ptr<ColumnDataAllocator> allocator, vector<LogicalType> types);
140765 DUCKDB_API ~ColumnDataCollection();
140766
140767public:
140769 vector<LogicalType> &Types() {
140770 return types;
140771 }
140772 const vector<LogicalType> &Types() const {
140773 return types;
140774 }
140775
140777 const idx_t &Count()
const {
140778 return count;
140779 }
140780
140782 idx_t ColumnCount()
const {
140783 return types.size();
140784 }
140785
140787 idx_t SizeInBytes()
const;
140789 idx_t AllocationSize()
const;
140791 void SetPartitionIndex(idx_t index);
140792
140794 DUCKDB_API Allocator &GetAllocator() const;
140795
140797 DUCKDB_API void InitializeAppend(ColumnDataAppendState &state);
140799 DUCKDB_API void Append(ColumnDataAppendState &state, DataChunk &new_chunk);
140800
140802 DUCKDB_API void InitializeScanChunk(DataChunk &chunk) const;
140803 DUCKDB_API void InitializeScanChunk(Allocator &allocator, DataChunk &chunk) const;
140805 DUCKDB_API void InitializeScanChunk(ColumnDataScanState &state, DataChunk &chunk) const;
140807 DUCKDB_API void
140808 InitializeScan(ColumnDataScanState &state,
140809 ColumnDataScanProperties properties = ColumnDataScanProperties::ALLOW_ZERO_COPY) const;
140811 DUCKDB_API void
140812 InitializeScan(ColumnDataScanState &state, vector<column_t> column_ids,
140813 ColumnDataScanProperties properties = ColumnDataScanProperties::ALLOW_ZERO_COPY) const;
140815 DUCKDB_API void
140816 InitializeScan(ColumnDataParallelScanState &state,
140817 ColumnDataScanProperties properties = ColumnDataScanProperties::ALLOW_ZERO_COPY) const;
140819 DUCKDB_API void
140820 InitializeScan(ColumnDataParallelScanState &state, vector<column_t> column_ids,
140821 ColumnDataScanProperties properties = ColumnDataScanProperties::ALLOW_ZERO_COPY) const;
140823 DUCKDB_API bool Scan(ColumnDataScanState &state, DataChunk &result) const;
140825 DUCKDB_API bool Scan(ColumnDataParallelScanState &state, ColumnDataLocalScanState &lstate, DataChunk &result) const;
140826
140828 DUCKDB_API void Append(DataChunk &new_chunk);
140829
140831 DUCKDB_API void Combine(ColumnDataCollection &other);
140832
140833 DUCKDB_API void Verify();
140834
140835 DUCKDB_API string ToString() const;
140836 DUCKDB_API void Print() const;
140837
140838 DUCKDB_API void Reset();
140839
140841 DUCKDB_API
idx_t ChunkCount()
const;
140843 DUCKDB_API void FetchChunk(idx_t chunk_idx, DataChunk &result) const;
140844
140847 DUCKDB_API ColumnDataChunkIterationHelper Chunks() const;
140850 DUCKDB_API ColumnDataChunkIterationHelper Chunks(vector<column_t> column_ids) const;
140851
140854 DUCKDB_API ColumnDataRowIterationHelper Rows() const;
140855
140859 DUCKDB_API ColumnDataRowCollection GetRows() const;
140860
140864 static bool ResultEquals(const ColumnDataCollection &left, const ColumnDataCollection &right, string &error_message,
140865 bool ordered = false);
140866
140868 bool NextScanIndex(ColumnDataScanState &state, idx_t &chunk_index, idx_t &segment_index, idx_t &row_index) const;
140870 bool PrevScanIndex(ColumnDataScanState &state, idx_t &chunk_index, idx_t &segment_index, idx_t &row_index) const;
140872 void ScanAtIndex(ColumnDataParallelScanState &state, ColumnDataLocalScanState &lstate, DataChunk &result,
140873 idx_t chunk_index, idx_t segment_index, idx_t row_index) const;
140874
140878 bool Seek(idx_t row_idx, ColumnDataScanState &state, DataChunk &result) const;
140879
140881 void Initialize(vector<LogicalType> types);
140882
140884 vector<shared_ptr<StringHeap>> GetHeapReferences();
140888 BufferManager &GetBufferManager() const;
140889
140891 const vector<unique_ptr<ColumnDataCollectionSegment>> &GetSegments() const;
140892
140893 void Serialize(Serializer &serializer) const;
140894 static unique_ptr<ColumnDataCollection> Deserialize(Deserializer &deserializer);
140895
140896private:
140898 void CreateSegment();
140899
140900 static ColumnDataCopyFunction GetCopyFunction(const LogicalType &type);
140901
140902private:
140904 buffer_ptr<ColumnDataAllocator> allocator;
140906 vector<LogicalType> types;
140910 vector<unique_ptr<ColumnDataCollectionSegment>> segments;
140912 vector<ColumnDataCopyFunction> copy_functions;
140914 bool finished_append;
140916 optional_idx partition_index;
140917};
140918
140920class ColumnDataRowCollection {
140921public:
140922 DUCKDB_API explicit ColumnDataRowCollection(
140923 const ColumnDataCollection &collection,
140924 ColumnDataScanProperties properties = ColumnDataScanProperties::DISALLOW_ZERO_COPY);
140925
140926public:
140927 DUCKDB_API Value GetValue(idx_t column, idx_t index) const;
140928
140929public:
140930
140931 bool empty() const {
140932 return rows.empty();
140933 }
140935 return rows.size();
140936 }
140937
140938 DUCKDB_API ColumnDataRow &operator[](idx_t i);
140939 DUCKDB_API const ColumnDataRow &operator[](idx_t i) const;
140940
140941 vector<ColumnDataRow>::iterator begin() {
140942 return rows.begin();
140943 }
140944 vector<ColumnDataRow>::iterator end() {
140945 return rows.end();
140946 }
140947 vector<ColumnDataRow>::const_iterator cbegin() const {
140948 return rows.cbegin();
140949 }
140950 vector<ColumnDataRow>::const_iterator cend() const {
140951 return rows.cend();
140952 }
140953 vector<ColumnDataRow>::const_iterator begin() const {
140954 return rows.begin();
140955 }
140956 vector<ColumnDataRow>::const_iterator end() const {
140957 return rows.end();
140958 }
140959
140960private:
140961 vector<ColumnDataRow>
rows;
140962 vector<unique_ptr<DataChunk>> chunks;
140963 ColumnDataScanState scan_state;
140964};
140965
140966}
140967
140968
140969
140970
140971
140972
140973
140974
140975
140976
140977
140978
140979
140980
140981
140982
140983
140984
140985
140986
140987
140988
140989
140990
140991
140992
140993
140994
140995
140996
140997
140998
140999
141000
141001
141002
141003
141004namespace duckdb {
141005
141006enum class QueryResultOutputType :
uint8_t { FORCE_MATERIALIZED, ALLOW_STREAMING };
141007
141009
141010struct QueryParameters {
141011 QueryParameters() {
141012 }
141013 QueryParameters(bool allow_streaming)
141014 : output_type(allow_streaming ? QueryResultOutputType::ALLOW_STREAMING
141015 : QueryResultOutputType::FORCE_MATERIALIZED) {
141016 }
141017 QueryParameters(QueryResultOutputType output_type)
141018 : output_type(output_type) {
141019 }
141020 QueryResultOutputType output_type = QueryResultOutputType::FORCE_MATERIALIZED;
141021 QueryResultMemoryType memory_type = QueryResultMemoryType::IN_MEMORY;
141022};
141023
141024}
141025
141026
141027
141028
141029
141030
141031
141032
141033
141034
141035
141036
141037
141038namespace duckdb {
141039
141040struct DatabaseModificationType {
141041public:
141042 static constexpr idx_t INSERT_DATA = 1ULL << 0ULL;
141043 static constexpr idx_t DELETE_DATA = 1ULL << 1ULL;
141044 static constexpr idx_t UPDATE_DATA = 1ULL << 2ULL;
141045 static constexpr idx_t ALTER_TABLE = 1ULL << 3ULL;
141046 static constexpr idx_t CREATE_CATALOG_ENTRY = 1ULL << 4ULL;
141047 static constexpr idx_t DROP_CATALOG_ENTRY = 1ULL << 5ULL;
141048 static constexpr idx_t SEQUENCE = 1ULL << 6ULL;
141049 static constexpr idx_t CREATE_INDEX = 1ULL << 7ULL;
141050
141051 constexpr DatabaseModificationType() : value(0) {
141052 }
141053 constexpr DatabaseModificationType(idx_t value) : value(value) {
141054 }
141055
141056 inline constexpr DatabaseModificationType
operator|(DatabaseModificationType b)
const {
141057 return DatabaseModificationType(value | b.value);
141058 }
141059 inline DatabaseModificationType &
operator|=(DatabaseModificationType b) {
141060 value |= b.value;
141061 return *this;
141062 }
141063
141064 bool InsertData() const {
141065 return value & INSERT_DATA;
141066 }
141067 bool DeleteData() const {
141068 return value & DELETE_DATA;
141069 }
141070 bool UpdateData() const {
141071 return value & UPDATE_DATA;
141072 }
141073 bool AlterTable() const {
141074 return value & ALTER_TABLE;
141075 }
141076 bool CreateCatalogEntry() const {
141077 return value & CREATE_CATALOG_ENTRY;
141078 }
141079 bool DropCatalogEntry() const {
141080 return value & DROP_CATALOG_ENTRY;
141081 }
141082 bool Sequence() const {
141083 return value & SEQUENCE;
141084 }
141085 bool CreateIndex() const {
141086 return value & CREATE_INDEX;
141087 }
141088
141089private:
141091};
141092
141093}
141094
141095
141096namespace duckdb {
141097
141098
141099
141100
141101enum class StatementType :
uint8_t {
141102 INVALID_STATEMENT,
141103 SELECT_STATEMENT,
141104 INSERT_STATEMENT,
141105 UPDATE_STATEMENT,
141106 CREATE_STATEMENT,
141107 DELETE_STATEMENT,
141108 PREPARE_STATEMENT,
141109 EXECUTE_STATEMENT,
141110 ALTER_STATEMENT,
141111 TRANSACTION_STATEMENT,
141112 COPY_STATEMENT,
141113 ANALYZE_STATEMENT,
141114 VARIABLE_SET_STATEMENT,
141115 CREATE_FUNC_STATEMENT,
141116 EXPLAIN_STATEMENT,
141117 DROP_STATEMENT,
141118 EXPORT_STATEMENT,
141119 PRAGMA_STATEMENT,
141120 VACUUM_STATEMENT,
141121 CALL_STATEMENT,
141122 SET_STATEMENT,
141123 LOAD_STATEMENT,
141124 RELATION_STATEMENT,
141125 EXTENSION_STATEMENT,
141126 LOGICAL_PLAN_STATEMENT,
141127 ATTACH_STATEMENT,
141128 DETACH_STATEMENT,
141129 MULTI_STATEMENT,
141130 COPY_DATABASE_STATEMENT,
141131 UPDATE_EXTENSIONS_STATEMENT,
141132 MERGE_INTO_STATEMENT
141133};
141134
141135DUCKDB_API string StatementTypeToString(StatementType type);
141136
141137enum class StatementReturnType :
uint8_t {
141138 QUERY_RESULT,
141139 CHANGED_ROWS,
141140 NOTHING
141141};
141142
141143string StatementReturnTypeToString(StatementReturnType type);
141144
141145class Catalog;
141146class ClientContext;
141147
141149struct StatementProperties {
141150 StatementProperties()
141151 : requires_valid_transaction(true), output_type(QueryResultOutputType::FORCE_MATERIALIZED),
141152 bound_all_parameters(true), return_type(StatementReturnType::QUERY_RESULT), parameter_count(0),
141153 always_require_rebind(false) {
141154 }
141155
141156 struct CatalogIdentity {
141157 idx_t catalog_oid;
141158 optional_idx catalog_version;
141159
141160 bool operator==(
const CatalogIdentity &rhs)
const {
141161 return catalog_oid == rhs.catalog_oid && catalog_version == rhs.catalog_version;
141162 }
141163
141164 bool operator!=(
const CatalogIdentity &rhs)
const {
141166 }
141167 };
141168
141169 struct ModificationInfo {
141170 CatalogIdentity identity;
141171 DatabaseModificationType modifications;
141172 };
141173
141175 unordered_map<string, CatalogIdentity> read_databases;
141177 unordered_map<string, ModificationInfo> modified_databases;
141180 bool requires_valid_transaction;
141182 QueryResultOutputType output_type;
141184 bool bound_all_parameters;
141186 StatementReturnType return_type;
141188 idx_t parameter_count;
141190 bool always_require_rebind;
141191
141192 bool IsReadOnly() {
141193 return modified_databases.empty();
141194 }
141195
141196 void RegisterDBRead(Catalog &catalog, ClientContext &context);
141197 void RegisterDBModify(Catalog &catalog, ClientContext &context, DatabaseModificationType modification);
141198};
141199
141200}
141201
141202
141203
141204
141205
141206
141207
141208
141209
141210
141211
141212
141213
141214
141215
141216
141217
141218
141219
141220
141221
141222
141223
141224
141225
141226
141227
141228
141229namespace duckdb {
141230
141231enum class ArrowOffsetSize :
uint8_t { REGULAR, LARGE };
141232
141247};
141248
141249}
141250
141251
141252namespace duckdb {
141253
141255struct ClientProperties {
141256 ClientProperties(string time_zone_p, const ArrowOffsetSize arrow_offset_size_p, const bool arrow_use_list_view_p,
141257 const bool produce_arrow_string_view_p, const bool lossless_conversion,
141258 const ArrowFormatVersion arrow_output_version, const optional_ptr<ClientContext> client_context)
141259 : time_zone(std::move(time_zone_p)), arrow_offset_size(arrow_offset_size_p),
141260 arrow_use_list_view(arrow_use_list_view_p), produce_arrow_string_view(produce_arrow_string_view_p),
141261 arrow_lossless_conversion(lossless_conversion), arrow_output_version(arrow_output_version),
141262 client_context(client_context) {
141263 }
141264 ClientProperties() {};
141265
141266 string time_zone = "UTC";
141267 ArrowOffsetSize arrow_offset_size = ArrowOffsetSize::REGULAR;
141268 bool arrow_use_list_view = false;
141269 bool produce_arrow_string_view = false;
141270 bool arrow_lossless_conversion = false;
141272 optional_ptr<ClientContext> client_context;
141273};
141274}
141275
141276
141277namespace duckdb {
141278struct BoxRendererConfig;
141279
141280enum class QueryResultType :
uint8_t { MATERIALIZED_RESULT, STREAM_RESULT, PENDING_RESULT, ARROW_RESULT };
141281
141282class BaseQueryResult {
141283public:
141285 DUCKDB_API BaseQueryResult(QueryResultType type, StatementType statement_type, StatementProperties properties,
141286 vector<LogicalType> types, vector<string> names);
141288 DUCKDB_API BaseQueryResult(QueryResultType type, ErrorData error);
141289 DUCKDB_API virtual ~BaseQueryResult();
141290
141292 QueryResultType type;
141294 StatementType statement_type;
141296 StatementProperties properties;
141298 vector<LogicalType> types;
141300 vector<string> names;
141301
141302public:
141303 [[noreturn]] DUCKDB_API void ThrowError(const string &prepended_message = "") const;
141304 DUCKDB_API
void SetError(ErrorData error);
141305 DUCKDB_API bool HasError() const;
141306 DUCKDB_API const ExceptionType &GetErrorType() const;
141307 DUCKDB_API const std::string &GetError() const;
141308 DUCKDB_API ErrorData &GetErrorObject();
141309 DUCKDB_API
idx_t ColumnCount();
141310
141311protected:
141313 bool success;
141315 ErrorData error;
141316};
141317
141321class QueryResult : public BaseQueryResult {
141322public:
141324 DUCKDB_API QueryResult(QueryResultType type, StatementType statement_type, StatementProperties properties,
141325 vector<LogicalType> types, vector<string> names, ClientProperties client_properties);
141327 DUCKDB_API QueryResult(QueryResultType type, ErrorData error);
141328 DUCKDB_API ~QueryResult() override;
141329
141331 ClientProperties client_properties;
141333 unique_ptr<QueryResult> next;
141334
141335public:
141336 template <class TARGET>
141337 TARGET &Cast() {
141338 if (type != TARGET::TYPE) {
141339 throw InternalException("Failed to cast query result to type - query result type mismatch");
141340 }
141341 return reinterpret_cast<TARGET &>(*this);
141342 }
141343
141344 template <class TARGET>
141345 const TARGET &Cast() const {
141346 if (type != TARGET::TYPE) {
141347 throw InternalException("Failed to cast query result to type - query result type mismatch");
141348 }
141349 return reinterpret_cast<const TARGET &>(*this);
141350 }
141351
141352public:
141354 static void DeduplicateColumns(vector<string> &names);
141355
141356public:
141358 DUCKDB_API const string &ColumnName(idx_t index) const;
141361 DUCKDB_API unique_ptr<DataChunk> Fetch();
141364 DUCKDB_API unique_ptr<DataChunk> FetchRaw();
141366 DUCKDB_API virtual string ToString() = 0;
141368 DUCKDB_API virtual string ToBox(ClientContext &context, const BoxRendererConfig &config);
141370 DUCKDB_API void Print();
141373 DUCKDB_API bool Equals(QueryResult &other);
141374
141375 bool TryFetch(unique_ptr<DataChunk> &result, ErrorData &error) {
141376 try {
141377 result = Fetch();
141378 return success;
141379 } catch (std::exception &ex) {
141380 error = ErrorData(ex);
141381 return false;
141382 } catch (...) {
141383 error = ErrorData("Unknown error in Fetch");
141384 return false;
141385 }
141386 }
141387
141388protected:
141389 DUCKDB_API virtual unique_ptr<DataChunk> FetchInternal() = 0;
141390
141391private:
141392 class QueryResultIterator;
141393 class QueryResultRow {
141394 friend class QueryResultIterator;
141395
141396 public:
141397 explicit QueryResultRow() : row(0) {
141398 }
141399
141400 bool IsNull(idx_t col_idx) const {
141401 return chunk->GetValue(col_idx, row).IsNull();
141402 }
141403 template <class T>
141404 T GetValue(idx_t col_idx) const {
141405 return chunk->GetValue(col_idx, row).GetValue<T>();
141406 }
141407 Value GetBaseValue(idx_t col_idx) const {
141408 return chunk->GetValue(col_idx, row);
141409 }
141410 DataChunk &GetChunk() const {
141411 return *chunk;
141412 }
141413 idx_t GetRowInChunk()
const {
141414 return row;
141415 }
141416
141417 private:
141418 shared_ptr<DataChunk> chunk;
141420 };
141422 class QueryResultIterator {
141423 public:
141424 explicit QueryResultIterator(optional_ptr<QueryResult> result_p = nullptr) : result(result_p), base_row(0) {
141425 if (result) {
141426 current_row.chunk = shared_ptr<DataChunk>(result->Fetch().release());
141427 if (!current_row.chunk) {
141428 result = nullptr;
141429 }
141430 }
141431 }
141432
141433 QueryResultRow current_row;
141434 optional_ptr<QueryResult> result;
141436
141437 public:
141438 void Next() {
141439 if (!current_row.chunk) {
141440 return;
141441 }
141442 current_row.row++;
141443 if (current_row.row >= current_row.chunk->size()) {
141444 base_row += current_row.chunk->size();
141445 current_row.chunk = shared_ptr<DataChunk>(result->Fetch().release());
141446 current_row.row = 0;
141447 if (!current_row.chunk || current_row.chunk->size() == 0) {
141448
141449 base_row = 0;
141450 result = nullptr;
141451 current_row.chunk.reset();
141452 }
141453 }
141454 }
141455
141456 QueryResultIterator &operator++() {
141457 Next();
141458 return *this;
141459 }
141460 bool operator!=(
const QueryResultIterator &other)
const {
141461 return result != other.result || base_row != other.base_row || current_row.row != other.current_row.row;
141462 }
141463 bool operator==(
const QueryResultIterator &other)
const {
141464 return !(*this != other);
141465 }
141466 const QueryResultRow &
operator*()
const {
141467 return current_row;
141468 }
141469 };
141470
141471public:
141472 using iterator = QueryResultIterator;
141473
141474 iterator begin() {
141475 return QueryResultIterator(this);
141476 }
141477 iterator end() {
141478 return QueryResultIterator(nullptr);
141479 }
141480
141481protected:
141482 DUCKDB_API string HeaderToString();
141483
141484private:
141485 QueryResult(const QueryResult &) = delete;
141486};
141487
141488}
141489
141490
141491namespace duckdb {
141492
141493class ClientContext;
141494
141495class MaterializedQueryResult : public QueryResult {
141496public:
141497 static constexpr const QueryResultType
TYPE = QueryResultType::MATERIALIZED_RESULT;
141498
141499public:
141500 friend class ClientContext;
141502 DUCKDB_API MaterializedQueryResult(StatementType statement_type, StatementProperties properties,
141503 vector<string> names, unique_ptr<ColumnDataCollection> collection,
141504 ClientProperties client_properties);
141506 DUCKDB_API explicit MaterializedQueryResult(ErrorData error);
141507
141508public:
141510 DUCKDB_API string ToString() override;
141511 DUCKDB_API string ToBox(ClientContext &context, const BoxRendererConfig &config) override;
141512
141515 DUCKDB_API Value GetValue(idx_t column, idx_t index);
141516
141517 template <class T>
141518 T GetValue(idx_t column, idx_t index) {
141519 auto value = GetValue(column, index);
141520 return (T)value.GetValue<
int64_t>();
141521 }
141522
141523 DUCKDB_API
idx_t RowCount()
const;
141524
141526 ColumnDataCollection &Collection();
141527
141529 unique_ptr<ColumnDataCollection> TakeCollection();
141530
141531protected:
141532 DUCKDB_API unique_ptr<DataChunk> FetchInternal() override;
141533
141534private:
141535 unique_ptr<ColumnDataCollection> collection;
141537 unique_ptr<ColumnDataRowCollection> row_collection;
141539 ColumnDataScanState scan_state;
141540 bool scan_initialized;
141541};
141542
141543}
141544
141545
141546
141547
141548
141549
141550
141551
141552
141553
141554
141555
141556
141557
141558
141559
141560
141561
141562
141563
141564
141565
141566
141567
141568namespace duckdb {
141569
141570enum class PendingExecutionResult :
uint8_t {
141571 RESULT_READY,
141572 RESULT_NOT_READY,
141573 EXECUTION_ERROR,
141574 BLOCKED,
141575 NO_TASKS_AVAILABLE,
141576 EXECUTION_FINISHED
141577};
141578
141579}
141580
141581
141582
141583
141584
141585
141586
141587
141588
141589
141590
141591
141592
141593
141594
141595
141596
141597
141598
141599
141600
141601
141602
141603
141604
141605
141606
141607
141608
141609
141610
141611
141612namespace duckdb {
141613
141614class TaskErrorManager {
141615public:
141616 TaskErrorManager() : has_error(false) {
141617 }
141618
141619 void PushError(ErrorData error) {
141620 lock_guard<mutex> elock(error_lock);
141621 this->exceptions.push_back(std::move(error));
141622 has_error = true;
141623 }
141624
141625 ErrorData GetError() {
141626 lock_guard<mutex> elock(error_lock);
141627 D_ASSERT(!exceptions.empty());
141628
141629
141630
141631
141632 auto &entry = exceptions[0];
141633 return entry;
141634 }
141635
141636 bool HasError() {
141637 return has_error;
141638 }
141639
141640 void ThrowException() {
141641 lock_guard<mutex> elock(error_lock);
141642 D_ASSERT(!exceptions.empty());
141643 auto &entry = exceptions[0];
141644 entry.Throw();
141645 }
141646
141647 void Reset() {
141648 lock_guard<mutex> elock(error_lock);
141649 exceptions.clear();
141650 has_error = false;
141651 }
141652
141653private:
141654 mutex error_lock;
141656 vector<ErrorData> exceptions;
141658 atomic<bool> has_error;
141659};
141660}
141661
141662
141663
141664
141665
141666
141667
141668
141669
141670
141671
141672
141673
141674namespace duckdb {
141675
141676struct ProgressData {
141677 double done = 0.0;
141678 double total = 0.0;
141679 bool invalid = false;
141680
141681public:
141682 double ProgressDone() const {
141683
141684 D_ASSERT(IsValid());
141685
141686 return done / total;
141687 }
141688
141689 void Add(const ProgressData &other) {
141690
141691 done += other.done;
141692 total += other.total;
141693 invalid = invalid || other.invalid;
141694 }
141695 void Normalize(const double target = 1.0) {
141696
141697 D_ASSERT(target > 0.0);
141698 if (IsValid()) {
141699 if (total > 0.0) {
141700 done /= total;
141701 }
141702 total = 1.0;
141703 done *= target;
141704 total *= target;
141705 } else {
141706 SetInvalid();
141707 }
141708 }
141709 void SetInvalid() {
141710 invalid = true;
141711 done = 0.0;
141712 total = 1.0;
141713 }
141714 bool IsValid() const {
141715 return (!invalid) && (done >= 0.0) && (done <= total) && (total >= 0.0);
141716 }
141717};
141718
141719}
141720
141721
141722
141723
141724
141725
141726
141727
141728
141729
141730
141731
141732
141733
141734
141735
141736
141737
141738
141739
141740
141741
141742
141743
141744
141745
141746
141747
141748
141749#include <type_traits>
141750
141751namespace duckdb {
141752
141753template <class T>
141754class ArenaLinkedList {
141755public:
141756 static_assert(std::is_trivially_destructible<T>::value, "T must be trivially destructible");
141757
141758public:
141759 explicit ArenaLinkedList(ArenaAllocator &arena) : arena(arena) {
141760 }
141761
141762 ArenaLinkedList(const ArenaLinkedList &) = delete;
141763 ArenaLinkedList &
operator=(
const ArenaLinkedList &) =
delete;
141764
141765 ArenaLinkedList(ArenaLinkedList &&other) noexcept : head(other.head), tail(other.tail) {
141766 other.head = nullptr;
141767 other.tail = nullptr;
141768 }
141769 ArenaLinkedList &
operator=(ArenaLinkedList &&other)
noexcept {
141770 if (this != &other) {
141771 head = other.head;
141772 tail = other.tail;
141773 other.head = nullptr;
141774 other.tail = nullptr;
141775 }
141776 return *this;
141777 }
141778
141779public:
141780 bool empty() const {
141781 return head == nullptr;
141782 }
141783
141785 return _size;
141786 }
141787
141788 void push_back(const T &value) {
141789 auto node = arena.Make<Node>(value);
141790 auto ptr = head ? &tail->next : &head;
141791 *ptr = node;
141792 tail = node;
141793 _size++;
141794 }
141795
141796 template <class... ARGS>
141797 void emplace_back(ARGS &&... args) {
141798 auto node = arena.Make<Node>(std::forward<ARGS>(args)...);
141799 auto ptr = head ? &tail->next : &head;
141800 *ptr = node;
141801 tail = node;
141802 _size++;
141803 }
141804
141806 T &operator[](const idx_t index) {
141808 for (auto &elem : *this) {
141809 if (i == index) {
141810 return elem;
141811 }
141812 i++;
141813 }
141814 throw InternalException("index out of bounds in ArenaLinkedList");
141815 }
141816
141818 const T &operator[](const idx_t index) const {
141820 for (const auto &elem : *this) {
141821 if (i == index) {
141822 return elem;
141823 }
141824 i++;
141825 }
141826 throw InternalException("index out of bounds in ArenaLinkedList");
141827 }
141828
141829 struct Iterator;
141830 struct ConstIterator;
141831
141832 Iterator begin();
141833 Iterator end();
141834 ConstIterator begin() const;
141835 ConstIterator end() const;
141836
141837private:
141838 struct Node {
141839 explicit Node(const T &value_p) : next(nullptr), value(value_p) {
141840 }
141841 Node *next;
141842 T value;
141843 };
141844
141845 ArenaAllocator &arena;
141846 Node *head = nullptr;
141847 Node *tail = nullptr;
141849};
141850
141851template <class T>
141852struct ArenaLinkedList<T>::Iterator {
141853 Node *node;
141854
141855 explicit Iterator(Node *node_p) : node(node_p) {
141856 }
141857
141859 return node->value;
141860 }
141861
141862 Iterator &operator++() {
141863 node = node->next;
141864 return *this;
141865 }
141866
141867 bool operator!=(
const Iterator &other)
const {
141868 return node != other.node;
141869 }
141870};
141871
141872template <class T>
141873struct ArenaLinkedList<T>::ConstIterator {
141874 const Node *node;
141875
141876 explicit ConstIterator(const Node *node_p) : node(node_p) {
141877 }
141878
141880 return node->value;
141881 }
141882
141883 ConstIterator &operator++() {
141884 node = node->next;
141885 return *this;
141886 }
141887
141888 bool operator!=(
const ConstIterator &other)
const {
141889 return node != other.node;
141890 }
141891};
141892
141893template <class T>
141894typename ArenaLinkedList<T>::Iterator ArenaLinkedList<T>::begin() {
141895 return Iterator(head);
141896}
141897
141898template <class T>
141899typename ArenaLinkedList<T>::Iterator ArenaLinkedList<T>::end() {
141900 return Iterator(nullptr);
141901}
141902
141903template <class T>
141904typename ArenaLinkedList<T>::ConstIterator ArenaLinkedList<T>::begin() const {
141905 return ConstIterator(head);
141906}
141907
141908template <class T>
141909typename ArenaLinkedList<T>::ConstIterator ArenaLinkedList<T>::end() const {
141910 return ConstIterator(nullptr);
141911}
141912
141913}
141914
141915
141916
141917
141918
141919
141920
141921
141922
141923
141924
141925
141926
141927
141928
141929namespace duckdb {
141930
141931enum class ExplainFormat :
uint8_t { DEFAULT, TEXT, JSON, HTML, GRAPHVIZ, YAML, MERMAID };
141932
141933}
141934
141935
141936
141937
141938
141939
141940
141941
141942
141943
141944
141945
141946
141947namespace duckdb {
141948
141962
141967
141970
141978
141981 INVALID,
141982 IMPLICIT,
141983
141984 HAVE_MORE_OUTPUT,
141985
141986 FINISHED,
141987 BLOCKED
141988
141989};
141990
141991bool ExtractSourceResultType(AsyncResultType in, SourceResultType &out);
141992
141999
142000
142001enum class SinkCombineResultType :
uint8_t { FINISHED, BLOCKED };
142002
142009
142015
142016}
142017
142018
142019
142020
142021
142022
142023
142024
142025
142026
142027
142028
142029
142030namespace duckdb {
142031
142032
142033
142034
142035enum class OrderPreservationType :
uint8_t {
142036 NO_ORDER,
142037 INSERTION_ORDER,
142038 FIXED_ORDER
142039};
142040
142041}
142042
142043
142044
142045
142046
142047
142048
142049
142050
142051
142052
142053
142054
142055namespace duckdb {
142056
142057
142058
142059
142060enum class PhysicalOperatorType :
uint8_t {
142061 INVALID,
142062 ORDER_BY,
142063 LIMIT,
142064 STREAMING_LIMIT,
142065 LIMIT_PERCENT,
142066 TOP_N,
142067 WINDOW,
142068 UNNEST,
142069 UNGROUPED_AGGREGATE,
142070 HASH_GROUP_BY,
142071 PERFECT_HASH_GROUP_BY,
142072 PARTITIONED_AGGREGATE,
142073 FILTER,
142074 PROJECTION,
142075 COPY_TO_FILE,
142076 BATCH_COPY_TO_FILE,
142077 RESERVOIR_SAMPLE,
142078 STREAMING_SAMPLE,
142079 STREAMING_WINDOW,
142080 PIVOT,
142081 COPY_DATABASE,
142082
142083
142084
142085
142086 TABLE_SCAN,
142087 DUMMY_SCAN,
142088 COLUMN_DATA_SCAN,
142089 CHUNK_SCAN,
142090 RECURSIVE_CTE_SCAN,
142091 RECURSIVE_RECURRING_CTE_SCAN,
142092 CTE_SCAN,
142093 DELIM_SCAN,
142094 EXPRESSION_SCAN,
142095 POSITIONAL_SCAN,
142096
142097
142098
142099 BLOCKWISE_NL_JOIN,
142100 NESTED_LOOP_JOIN,
142101 HASH_JOIN,
142102 CROSS_PRODUCT,
142103 PIECEWISE_MERGE_JOIN,
142104 IE_JOIN,
142105 LEFT_DELIM_JOIN,
142106 RIGHT_DELIM_JOIN,
142107 POSITIONAL_JOIN,
142108 ASOF_JOIN,
142109
142110
142111
142112 UNION,
142113 RECURSIVE_CTE,
142114 RECURSIVE_KEY_CTE,
142115 CTE,
142116
142117
142118
142119
142120 INSERT,
142121 BATCH_INSERT,
142122 DELETE_OPERATOR,
142123 UPDATE,
142124 MERGE_INTO,
142125
142126
142127
142128
142129 CREATE_TABLE,
142130 CREATE_TABLE_AS,
142131 BATCH_CREATE_TABLE_AS,
142132 CREATE_INDEX,
142133 ALTER,
142134 CREATE_SEQUENCE,
142135 CREATE_VIEW,
142136 CREATE_SCHEMA,
142137 CREATE_MACRO,
142138 DROP,
142139 PRAGMA,
142140 TRANSACTION,
142141 CREATE_TYPE,
142142 ATTACH,
142143 DETACH,
142144
142145
142146
142147
142148 EXPLAIN,
142149 EXPLAIN_ANALYZE,
142150 EMPTY_RESULT,
142151 EXECUTE,
142152 PREPARE,
142153 VACUUM,
142154 EXPORT,
142155 SET,
142156 SET_VARIABLE,
142157 LOAD,
142158 INOUT_FUNCTION,
142159 RESULT_COLLECTOR,
142160 RESET,
142161 EXTENSION,
142162 VERIFY_VECTOR,
142163 UPDATE_EXTENSIONS,
142164
142165
142166
142167
142168 CREATE_SECRET,
142169};
142170
142171string PhysicalOperatorToString(PhysicalOperatorType type);
142172
142173}
142174
142175
142176
142177
142178
142179
142180
142181
142182
142183
142184
142185
142186
142187
142188
142189
142190namespace duckdb {
142191class ClientContext;
142192class ThreadContext;
142193class Pipeline;
142194
142195class ExecutionContext {
142196public:
142197 ExecutionContext(ClientContext &client_p, ThreadContext &thread_p, optional_ptr<Pipeline> pipeline_p)
142198 : client(client_p), thread(thread_p), pipeline(pipeline_p) {
142199 }
142200
142202 ClientContext &client;
142204 ThreadContext &thread;
142206 optional_ptr<Pipeline> pipeline;
142207};
142208
142209}
142210
142211
142212
142213
142214
142215
142216
142217
142218
142219
142220
142221
142222
142223
142224
142225namespace duckdb {
142226
142227enum class PartitionInfo { NONE, REQUIRES_BATCH_INDEX };
142228
142229struct ColumnPartitionData {
142230 explicit ColumnPartitionData(Value partition_val) : min_val(partition_val), max_val(std::move(partition_val)) {
142231 }
142232
142233 Value min_val;
142234 Value max_val;
142235};
142236
142237struct SourcePartitionInfo {
142243 optional_idx batch_index;
142245 optional_idx min_batch_index;
142247 vector<ColumnPartitionData> partition_data;
142248};
142249
142250struct OperatorPartitionInfo {
142251 OperatorPartitionInfo() = default;
142252 explicit OperatorPartitionInfo(bool batch_index) : batch_index(batch_index) {
142253 }
142254 explicit OperatorPartitionInfo(vector<column_t> partition_columns_p)
142255 : partition_columns(std::move(partition_columns_p)) {
142256 }
142257
142258 bool batch_index = false;
142259 vector<column_t> partition_columns;
142260
142261 static OperatorPartitionInfo NoPartitionInfo() {
142262 return OperatorPartitionInfo(false);
142263 }
142264 static OperatorPartitionInfo BatchIndex() {
142265 return OperatorPartitionInfo(true);
142266 }
142267 static OperatorPartitionInfo PartitionColumns(vector<column_t> columns) {
142268 return OperatorPartitionInfo(std::move(columns));
142269 }
142270 bool RequiresPartitionColumns() const {
142271 return !partition_columns.empty();
142272 }
142273 bool RequiresBatchIndex() const {
142274 return batch_index;
142275 }
142276 bool AnyRequired() const {
142277 return RequiresPartitionColumns() || RequiresBatchIndex();
142278 }
142279};
142280
142281struct OperatorPartitionData {
142282 explicit OperatorPartitionData(idx_t batch_index) : batch_index(batch_index) {
142283 }
142284
142285 idx_t batch_index;
142286 vector<ColumnPartitionData> partition_data;
142287};
142288
142289}
142290
142291
142292
142293
142294
142295
142296
142297
142298
142299
142300
142301
142302
142303
142304
142305
142306
142307
142308
142309
142310
142311
142312
142313
142314
142315
142316
142317
142318
142319
142320
142321
142322
142323
142324
142325
142326
142327
142328
142329
142330namespace duckdb {
142331
142333struct JoinRelationSet {
142334 JoinRelationSet(unsafe_unique_array<idx_t> relations, idx_t count) : relations(std::move(relations)), count(count) {
142335 }
142336
142337 string ToString() const;
142338
142339 unsafe_unique_array<idx_t> relations;
142341
142342 static bool IsSubset(JoinRelationSet &super, JoinRelationSet &sub);
142343};
142344
142347class JoinRelationSetManager {
142348public:
142350
142351 struct JoinRelationTreeNode {
142352 unique_ptr<JoinRelationSet> relation;
142353 unordered_map<idx_t, unique_ptr<JoinRelationTreeNode>> children;
142354 };
142355
142356public:
142358 JoinRelationSet &GetJoinRelation(idx_t index);
142360 JoinRelationSet &GetJoinRelation(const unordered_set<idx_t> &bindings);
142362 JoinRelationSet &GetJoinRelation(unsafe_unique_array<idx_t> relations, idx_t count);
142364 JoinRelationSet &Union(JoinRelationSet &left, JoinRelationSet &right);
142365
142366
142367 string ToString() const;
142368 void Print();
142369
142370private:
142371 JoinRelationTreeNode root;
142372};
142373
142374}
142375
142376
142377
142378
142379
142380
142381
142382
142383
142384
142385
142386
142387
142388
142389
142390
142391
142392
142393
142394
142395
142396
142397
142398
142399
142400
142401
142402
142403
142404
142405
142406
142407
142408
142409
142410
142411
142412
142413
142414
142415
142416
142417
142418
142419
142420
142421
142422
142423
142424
142425
142426
142427
142428
142429
142430
142431
142432
142433
142434
142435
142436
142437#include <functional>
142438
142439namespace duckdb {
142440class Serializer;
142441class Deserializer;
142442
142443struct ColumnBinding {
142444 idx_t table_index;
142445
142446 idx_t column_index;
142447
142448 ColumnBinding() : table_index(DConstants::INVALID_INDEX), column_index(DConstants::INVALID_INDEX) {
142449 }
142450 ColumnBinding(idx_t table, idx_t column) : table_index(table), column_index(column) {
142451 }
142452
142453 string ToString() const {
142455 }
142456
142457 bool operator==(
const ColumnBinding &rhs)
const {
142458 return table_index == rhs.table_index && column_index == rhs.column_index;
142459 }
142460
142461 bool operator!=(
const ColumnBinding &rhs)
const {
142462 return !(*this == rhs);
142463 }
142464
142465 void Serialize(Serializer &serializer) const;
142466 static ColumnBinding Deserialize(Deserializer &deserializer);
142467};
142468
142469}
142470
142471
142472namespace duckdb {
142473
142474struct ColumnBindingHashFunction {
142476 return CombineHash(Hash<idx_t>(a.table_index), Hash<idx_t>(a.column_index));
142477 }
142478};
142479
142480struct ColumnBindingEquality {
142481 bool operator()(
const ColumnBinding &a,
const ColumnBinding &b)
const {
142482 return a == b;
142483 }
142484};
142485
142486template <typename T>
142487using column_binding_map_t = unordered_map<ColumnBinding, T, ColumnBindingHashFunction, ColumnBindingEquality>;
142488
142489using column_binding_set_t = unordered_set<ColumnBinding, ColumnBindingHashFunction, ColumnBindingEquality>;
142490
142491}
142492
142493
142494
142495
142496
142497
142498
142499
142500
142501
142502
142503
142504
142505
142506
142507
142508
142509
142510
142511
142512
142513
142514
142515
142516
142517
142518
142519
142520
142521
142522
142523
142524
142525
142526
142527
142528
142529
142530
142531
142532
142533namespace duckdb {
142534class BaseStatistics;
142535class Expression;
142536class PhysicalOperator;
142537class PhysicalTableScan;
142538
142539enum class TableFilterType :
uint8_t {
142540 CONSTANT_COMPARISON = 0,
142541 IS_NULL = 1,
142542 IS_NOT_NULL = 2,
142543 CONJUNCTION_OR = 3,
142544 CONJUNCTION_AND = 4,
142545 STRUCT_EXTRACT = 5,
142546 OPTIONAL_FILTER = 6,
142547 IN_FILTER = 7,
142548 DYNAMIC_FILTER = 8,
142549 EXPRESSION_FILTER = 9,
142550 BLOOM_FILTER = 10,
142551};
142552
142554class TableFilter {
142555public:
142556 explicit TableFilter(TableFilterType filter_type_p) : filter_type(filter_type_p) {
142557 }
142558 virtual ~TableFilter() {
142559 }
142560
142561 TableFilterType filter_type;
142562
142563public:
142565 virtual FilterPropagateResult CheckStatistics(BaseStatistics &stats) const = 0;
142566 virtual string ToString(const string &column_name) const = 0;
142567 string DebugToString() const;
142568 virtual unique_ptr<TableFilter> Copy() const = 0;
142569 virtual bool Equals(const TableFilter &other) const {
142570 return filter_type == other.filter_type;
142571 }
142572 virtual unique_ptr<Expression> ToExpression(const Expression &column) const = 0;
142573
142574 virtual void Serialize(Serializer &serializer) const;
142575 static unique_ptr<TableFilter> Deserialize(Deserializer &deserializer);
142576
142577public:
142578 template <class TARGET>
142579 TARGET &Cast() {
142580 if (filter_type != TARGET::TYPE) {
142581 throw InternalException("Failed to cast to type - table filter type mismatch");
142582 }
142583 return reinterpret_cast<TARGET &>(*this);
142584 }
142585
142586 template <class TARGET>
142587 const TARGET &Cast() const {
142588 if (filter_type != TARGET::TYPE) {
142589 throw InternalException("Failed to cast to type - table filter type mismatch");
142590 }
142591 return reinterpret_cast<const TARGET &>(*this);
142592 }
142593};
142594
142597class TableFilterSet {
142598public:
142599 map<idx_t, unique_ptr<TableFilter>> filters;
142600
142601public:
142602 void PushFilter(const ColumnIndex &col_idx, unique_ptr<TableFilter> filter);
142603
142604 bool Equals(TableFilterSet &other) {
142605 if (filters.size() != other.filters.size()) {
142606 return false;
142607 }
142608 for (auto &entry : filters) {
142609 auto other_entry = other.filters.find(entry.first);
142610 if (other_entry == other.filters.end()) {
142611 return false;
142612 }
142613 if (!entry.second->Equals(*other_entry->second)) {
142614 return false;
142615 }
142616 }
142617 return true;
142618 }
142619 static bool Equals(TableFilterSet *left, TableFilterSet *right) {
142620 if (left == right) {
142621 return true;
142622 }
142623 if (!left || !right) {
142624 return false;
142625 }
142626 return left->Equals(*right);
142627 }
142628
142629 unique_ptr<TableFilterSet> Copy() const {
142630 auto copy = make_uniq<TableFilterSet>();
142631 for (auto &it : filters) {
142632 copy->filters.emplace(it.first, it.second->Copy());
142633 }
142634 return copy;
142635 }
142636
142637 void Serialize(Serializer &serializer) const;
142638 static TableFilterSet Deserialize(Deserializer &deserializer);
142639};
142640
142641class DynamicTableFilterSet {
142642public:
142643 void ClearFilters(const PhysicalOperator &op);
142644 void PushFilter(const PhysicalOperator &op, idx_t column_index, unique_ptr<TableFilter> filter);
142645
142646 bool HasFilters() const;
142647 unique_ptr<TableFilterSet> GetFinalTableFilters(const PhysicalTableScan &scan,
142648 optional_ptr<TableFilterSet> existing_filters) const;
142649
142650private:
142651 mutable mutex lock;
142652 reference_map_t<const PhysicalOperator, unique_ptr<TableFilterSet>> filters;
142653};
142654
142655}
142656
142657
142658
142659namespace duckdb {
142660
142661class ConjunctionFilter : public TableFilter {
142662public:
142663 explicit ConjunctionFilter(TableFilterType filter_type_p) : TableFilter(filter_type_p) {
142664 }
142665
142666 ~ConjunctionFilter() override {
142667 }
142668
142670 vector<unique_ptr<TableFilter>> child_filters;
142671
142672public:
142673 bool Equals(const TableFilter &other) const override {
142674 return TableFilter::Equals(other);
142675 }
142676};
142677
142678class ConjunctionOrFilter : public ConjunctionFilter {
142679public:
142680 static constexpr const TableFilterType
TYPE = TableFilterType::CONJUNCTION_OR;
142681
142682public:
142683 ConjunctionOrFilter();
142684 FilterPropagateResult CheckStatistics(BaseStatistics &stats) const override;
142685 string ToString(const string &column_name) const override;
142686 bool Equals(const TableFilter &other) const override;
142687 unique_ptr<TableFilter> Copy() const override;
142688 unique_ptr<Expression> ToExpression(const Expression &column) const override;
142689 void Serialize(Serializer &serializer) const override;
142690 static unique_ptr<TableFilter> Deserialize(Deserializer &deserializer);
142691};
142692
142693class ConjunctionAndFilter : public ConjunctionFilter {
142694public:
142695 static constexpr const TableFilterType
TYPE = TableFilterType::CONJUNCTION_AND;
142696
142697public:
142698 ConjunctionAndFilter();
142699
142700public:
142701 FilterPropagateResult CheckStatistics(BaseStatistics &stats) const override;
142702 string ToString(const string &column_name) const override;
142703 bool Equals(const TableFilter &other) const override;
142704 unique_ptr<TableFilter> Copy() const override;
142705 unique_ptr<Expression> ToExpression(const Expression &column) const override;
142706 void Serialize(Serializer &serializer) const override;
142707 static unique_ptr<TableFilter> Deserialize(Deserializer &deserializer);
142708};
142709
142710}
142711
142712
142713
142714
142715
142716
142717
142718
142719
142720
142721
142722
142723
142724
142725
142726
142727
142728
142729
142730
142731
142732
142733
142734
142735
142736namespace duckdb {
142737
142738
142739
142740
142741enum class LogicalOperatorType :
uint8_t {
142742 LOGICAL_INVALID = 0,
142743 LOGICAL_PROJECTION = 1,
142744 LOGICAL_FILTER = 2,
142745 LOGICAL_AGGREGATE_AND_GROUP_BY = 3,
142746 LOGICAL_WINDOW = 4,
142747 LOGICAL_UNNEST = 5,
142748 LOGICAL_LIMIT = 6,
142749 LOGICAL_ORDER_BY = 7,
142750 LOGICAL_TOP_N = 8,
142751 LOGICAL_COPY_TO_FILE = 10,
142752 LOGICAL_DISTINCT = 11,
142753 LOGICAL_SAMPLE = 12,
142754 LOGICAL_PIVOT = 14,
142755 LOGICAL_COPY_DATABASE = 15,
142756
142757
142758
142759
142760 LOGICAL_GET = 25,
142761 LOGICAL_CHUNK_GET = 26,
142762 LOGICAL_DELIM_GET = 27,
142763 LOGICAL_EXPRESSION_GET = 28,
142764 LOGICAL_DUMMY_SCAN = 29,
142765 LOGICAL_EMPTY_RESULT = 30,
142766 LOGICAL_CTE_REF = 31,
142767
142768
142769
142770 LOGICAL_JOIN = 50,
142771 LOGICAL_DELIM_JOIN = 51,
142772 LOGICAL_COMPARISON_JOIN = 52,
142773 LOGICAL_ANY_JOIN = 53,
142774 LOGICAL_CROSS_PRODUCT = 54,
142775 LOGICAL_POSITIONAL_JOIN = 55,
142776 LOGICAL_ASOF_JOIN = 56,
142777 LOGICAL_DEPENDENT_JOIN = 57,
142778
142779
142780
142781 LOGICAL_UNION = 75,
142782 LOGICAL_EXCEPT = 76,
142783 LOGICAL_INTERSECT = 77,
142784 LOGICAL_RECURSIVE_CTE = 78,
142785 LOGICAL_MATERIALIZED_CTE = 79,
142786
142787
142788
142789
142790 LOGICAL_INSERT = 100,
142791 LOGICAL_DELETE = 101,
142792 LOGICAL_UPDATE = 102,
142793 LOGICAL_MERGE_INTO = 103,
142794
142795
142796
142797
142798 LOGICAL_ALTER = 125,
142799 LOGICAL_CREATE_TABLE = 126,
142800 LOGICAL_CREATE_INDEX = 127,
142801 LOGICAL_CREATE_SEQUENCE = 128,
142802 LOGICAL_CREATE_VIEW = 129,
142803 LOGICAL_CREATE_SCHEMA = 130,
142804 LOGICAL_CREATE_MACRO = 131,
142805 LOGICAL_DROP = 132,
142806 LOGICAL_PRAGMA = 133,
142807 LOGICAL_TRANSACTION = 134,
142808 LOGICAL_CREATE_TYPE = 135,
142809 LOGICAL_ATTACH = 136,
142810 LOGICAL_DETACH = 137,
142811
142812
142813
142814
142815 LOGICAL_EXPLAIN = 150,
142816
142817
142818
142819
142820 LOGICAL_PREPARE = 175,
142821 LOGICAL_EXECUTE = 176,
142822 LOGICAL_EXPORT = 177,
142823 LOGICAL_VACUUM = 178,
142824 LOGICAL_SET = 179,
142825 LOGICAL_LOAD = 180,
142826 LOGICAL_RESET = 181,
142827 LOGICAL_UPDATE_EXTENSIONS = 182,
142828
142829
142830
142831
142832 LOGICAL_CREATE_SECRET = 190,
142833
142834 LOGICAL_EXTENSION_OPERATOR = 255
142835};
142836
142837DUCKDB_API string LogicalOperatorToString(LogicalOperatorType type);
142838
142839}
142840
142841
142842
142843
142844
142845
142846
142847
142848
142849
142850
142851
142852
142853
142854
142855
142856
142857
142858
142859
142860
142861
142862
142863
142864
142865namespace duckdb {
142866
142867
142868
142869
142870class BoundQueryNode;
142871class BoundSelectNode;
142872class BoundSetOperationNode;
142873
142874
142875
142876
142877class Expression;
142878
142879class BoundAggregateExpression;
142880class BoundBetweenExpression;
142881class BoundCaseExpression;
142882class BoundCastExpression;
142883class BoundColumnRefExpression;
142884class BoundComparisonExpression;
142885class BoundConjunctionExpression;
142886class BoundConstantExpression;
142887class BoundDefaultExpression;
142888class BoundFunctionExpression;
142889class BoundLambdaRefExpression;
142890class BoundOperatorExpression;
142891class BoundParameterExpression;
142892class BoundReferenceExpression;
142893class BoundSubqueryExpression;
142894class BoundUnnestExpression;
142895class BoundWindowExpression;
142896
142897
142898
142899
142900class BoundJoinRef;
142901class BoundMergeIntoAction;
142902
142903}
142904
142905
142906
142907
142908
142909
142910
142911
142912
142913
142914
142915namespace duckdb {
142916
142917class LogicalOperator;
142918
142919class LogicalAggregate;
142920class LogicalAnyJoin;
142921class LogicalColumnDataGet;
142922class LogicalComparisonJoin;
142923class LogicalCopyDatabase;
142924class LogicalCopyToFile;
142925class LogicalCreate;
142926class LogicalCreateTable;
142927class LogicalCreateIndex;
142928class LogicalCreateTable;
142929class LogicalCreateSecret;
142930class LogicalCrossProduct;
142931class LogicalCTERef;
142932class LogicalDelete;
142933class LogicalDelimGet;
142934class LogicalDistinct;
142935class LogicalDummyScan;
142936class LogicalEmptyResult;
142937class LogicalExecute;
142938class LogicalExplain;
142939class LogicalExport;
142940class LogicalExpressionGet;
142941class LogicalFilter;
142942class LogicalGet;
142943class LogicalInsert;
142944class LogicalJoin;
142945class LogicalLimit;
142946class LogicalMergeInto;
142947class LogicalOrder;
142948class LogicalPivot;
142949class LogicalPositionalJoin;
142950class LogicalPragma;
142951class LogicalPrepare;
142952class LogicalProjection;
142953class LogicalRecursiveCTE;
142954class LogicalMaterializedCTE;
142955class LogicalSetOperation;
142956class LogicalSample;
142957class LogicalSimple;
142958class LogicalVacuum;
142959class LogicalSet;
142960class LogicalReset;
142961class LogicalTopN;
142962class LogicalUnnest;
142963class LogicalUpdate;
142964class LogicalWindow;
142965
142966}
142967
142968
142969#include <functional>
142970
142971namespace duckdb {
142974class LogicalOperatorVisitor {
142975public:
142976 virtual ~LogicalOperatorVisitor() {
142977 }
142978
142979 virtual void VisitOperator(LogicalOperator &op);
142980 virtual void VisitExpression(unique_ptr<Expression> *expression);
142981
142982 static void EnumerateExpressions(LogicalOperator &op,
142983 const std::function<void(unique_ptr<Expression> *child)> &callback);
142984
142985protected:
142988 void VisitOperatorChildren(LogicalOperator &op);
142991 void VisitOperatorExpressions(LogicalOperator &op);
142993 void VisitOperatorWithProjectionMapChildren(LogicalOperator &op);
142994 void VisitChildOfOperatorWithProjectionMap(LogicalOperator &child, vector<idx_t> &projection_map);
142995
142996
142997
142998 virtual void VisitExpressionChildren(Expression &expression);
142999
143000 virtual unique_ptr<Expression> VisitReplace(BoundAggregateExpression &expr, unique_ptr<Expression> *expr_ptr);
143001 virtual unique_ptr<Expression> VisitReplace(BoundBetweenExpression &expr, unique_ptr<Expression> *expr_ptr);
143002 virtual unique_ptr<Expression> VisitReplace(BoundCaseExpression &expr, unique_ptr<Expression> *expr_ptr);
143003 virtual unique_ptr<Expression> VisitReplace(BoundCastExpression &expr, unique_ptr<Expression> *expr_ptr);
143004 virtual unique_ptr<Expression> VisitReplace(BoundColumnRefExpression &expr, unique_ptr<Expression> *expr_ptr);
143005 virtual unique_ptr<Expression> VisitReplace(BoundComparisonExpression &expr, unique_ptr<Expression> *expr_ptr);
143006 virtual unique_ptr<Expression> VisitReplace(BoundConjunctionExpression &expr, unique_ptr<Expression> *expr_ptr);
143007 virtual unique_ptr<Expression> VisitReplace(BoundConstantExpression &expr, unique_ptr<Expression> *expr_ptr);
143008 virtual unique_ptr<Expression> VisitReplace(BoundDefaultExpression &expr, unique_ptr<Expression> *expr_ptr);
143009 virtual unique_ptr<Expression> VisitReplace(BoundFunctionExpression &expr, unique_ptr<Expression> *expr_ptr);
143010 virtual unique_ptr<Expression> VisitReplace(BoundOperatorExpression &expr, unique_ptr<Expression> *expr_ptr);
143011 virtual unique_ptr<Expression> VisitReplace(BoundReferenceExpression &expr, unique_ptr<Expression> *expr_ptr);
143012 virtual unique_ptr<Expression> VisitReplace(BoundSubqueryExpression &expr, unique_ptr<Expression> *expr_ptr);
143013 virtual unique_ptr<Expression> VisitReplace(BoundParameterExpression &expr, unique_ptr<Expression> *expr_ptr);
143014 virtual unique_ptr<Expression> VisitReplace(BoundWindowExpression &expr, unique_ptr<Expression> *expr_ptr);
143015 virtual unique_ptr<Expression> VisitReplace(BoundUnnestExpression &expr, unique_ptr<Expression> *expr_ptr);
143016};
143017}
143018
143019
143020
143021
143022#include <algorithm>
143023#include <functional>
143024
143025namespace duckdb {
143026
143029class LogicalOperator {
143030public:
143031 explicit LogicalOperator(LogicalOperatorType type);
143032 LogicalOperator(LogicalOperatorType type, vector<unique_ptr<Expression>> expressions);
143033 virtual ~LogicalOperator();
143034
143036 LogicalOperatorType type;
143038 vector<unique_ptr<LogicalOperator>> children;
143040 vector<unique_ptr<Expression>> expressions;
143042 vector<LogicalType> types;
143044 idx_t estimated_cardinality;
143045 bool has_estimated_cardinality;
143046
143047public:
143048 virtual vector<ColumnBinding> GetColumnBindings();
143049 virtual idx_t GetRootIndex();
143050 static string ColumnBindingsToString(const vector<ColumnBinding> &bindings);
143051 void PrintColumnBindings();
143052 static vector<ColumnBinding> GenerateColumnBindings(idx_t table_idx, idx_t column_count);
143053 static vector<LogicalType> MapTypes(const vector<LogicalType> &types, const vector<idx_t> &projection_map);
143054 static vector<ColumnBinding> MapBindings(const vector<ColumnBinding> &types, const vector<idx_t> &projection_map);
143055
143057 void ResolveOperatorTypes();
143058
143059 virtual string GetName() const;
143060 virtual InsertionOrderPreservingMap<string> ParamsToString() const;
143061 virtual string ToString(ExplainFormat
format = ExplainFormat::DEFAULT)
const;
143062 DUCKDB_API void Print();
143064 virtual void Verify(ClientContext &context);
143065
143066 void AddChild(unique_ptr<LogicalOperator> child);
143067 virtual idx_t EstimateCardinality(ClientContext &context);
143068 void SetEstimatedCardinality(idx_t _estimated_cardinality);
143069 void SetParamsEstimatedCardinality(InsertionOrderPreservingMap<string> &result) const;
143070
143071 virtual void Serialize(Serializer &serializer) const;
143072 static unique_ptr<LogicalOperator> Deserialize(Deserializer &deserializer);
143073
143074 virtual unique_ptr<LogicalOperator> Copy(ClientContext &context) const;
143075
143076 virtual bool RequireOptimizer() const {
143077 return true;
143078 }
143079
143081 virtual bool SupportSerialization() const {
143082 return true;
143083 };
143084
143085 virtual bool HasProjectionMap() const {
143086 return false;
143087 }
143088
143090 virtual vector<idx_t> GetTableIndex() const;
143091
143092protected:
143094 virtual void ResolveTypes() = 0;
143095
143096public:
143097 template <class TARGET>
143098 TARGET &Cast() {
143099 if (TARGET::TYPE != LogicalOperatorType::LOGICAL_INVALID && type != TARGET::TYPE) {
143100 throw InternalException("Failed to cast logical operator to type - logical operator type mismatch");
143101 }
143102 return reinterpret_cast<TARGET &>(*this);
143103 }
143104
143105 template <class TARGET>
143106 const TARGET &Cast() const {
143107 if (TARGET::TYPE != LogicalOperatorType::LOGICAL_INVALID && type != TARGET::TYPE) {
143108 throw InternalException("Failed to cast logical operator to type - logical operator type mismatch");
143109 }
143110 return reinterpret_cast<const TARGET &>(*this);
143111 }
143112};
143113}
143114
143115
143116namespace duckdb {
143117
143118class CardinalityEstimator;
143119
143120struct DistinctCount {
143121 idx_t distinct_count;
143122 bool from_hll;
143123};
143124
143125struct ExpressionBinding {
143126public:
143127 bool FoundExpression() const {
143128 return expression;
143129 }
143130 bool FoundColumnRef() const {
143131 if (!FoundExpression()) {
143132 return false;
143133 }
143134 return expression->type == ExpressionType::BOUND_COLUMN_REF;
143135 }
143136
143137public:
143138 optional_ptr<Expression> expression;
143139 ColumnBinding child_binding;
143140 bool expression_is_constant = false;
143141};
143142
143143struct RelationStats {
143144
143145 vector<DistinctCount> column_distinct_count;
143146 idx_t cardinality;
143147 double filter_strength = 1;
143148 bool stats_initialized = false;
143149
143150
143151 vector<string> column_names;
143152 string table_name;
143153
143154 RelationStats() : cardinality(1), filter_strength(1), stats_initialized(false) {
143155 }
143156};
143157
143158class RelationStatisticsHelper {
143159public:
143160 static constexpr double DEFAULT_SELECTIVITY = 0.2;
143161
143162public:
143163 static idx_t InspectTableFilter(idx_t cardinality, idx_t column_index,
const TableFilter &filter,
143164 BaseStatistics &base_stats);
143165
143166
143168 static RelationStats ExtractGetStats(LogicalGet &
get, ClientContext &context);
143169 static RelationStats ExtractDelimGetStats(LogicalDelimGet &delim_get, ClientContext &context);
143172 static RelationStats ExtractDummyScanStats(LogicalDummyScan &dummy_scan, ClientContext &context);
143173 static RelationStats ExtractExpressionGetStats(LogicalExpressionGet &expression_get, ClientContext &context);
143175 static RelationStats ExtractProjectionStats(LogicalProjection &proj, RelationStats &child_stats);
143176 static RelationStats ExtractAggregationStats(LogicalAggregate &aggr, RelationStats &child_stats);
143177 static RelationStats ExtractWindowStats(LogicalWindow &window, RelationStats &child_stats);
143178 static RelationStats ExtractEmptyResultStats(LogicalEmptyResult &empty);
143180 static RelationStats CombineStatsOfReorderableOperator(vector<ColumnBinding> &bindings,
143181 vector<RelationStats> relation_stats);
143183 static RelationStats CombineStatsOfNonReorderableOperator(LogicalOperator &op,
143184 const vector<RelationStats> &child_stats);
143185 static void CopyRelationStats(RelationStats &to, const RelationStats &from);
143186
143187private:
143188 static idx_t GetDistinctCount(LogicalGet &
get, ClientContext &context,
const ColumnIndex &column_id);
143189};
143190
143191}
143192
143193
143194namespace duckdb {
143195
143196class FilterInfo;
143197
143198struct DenomInfo {
143199 DenomInfo(JoinRelationSet &numerator_relations, double filter_strength, double denominator)
143200 : numerator_relations(numerator_relations), filter_strength(filter_strength), denominator(denominator) {
143201 }
143202
143203 JoinRelationSet &numerator_relations;
143204 double filter_strength;
143205 double denominator;
143206};
143207
143208struct RelationsSetToStats {
143211 column_binding_set_t equivalent_relations;
143213 idx_t distinct_count_hll;
143215 idx_t distinct_count_no_hll;
143216 bool has_distinct_count_hll;
143217 vector<optional_ptr<FilterInfo>> filters;
143218 vector<string> column_names;
143219
143220 explicit RelationsSetToStats(const column_binding_set_t &column_binding_set)
143221 : equivalent_relations(column_binding_set), distinct_count_hll(0),
143222 distinct_count_no_hll(NumericLimits<
idx_t>::Maximum()), has_distinct_count_hll(false) {};
143223};
143224
143225
143226class FilterInfoWithTotalDomains {
143227public:
143228 FilterInfoWithTotalDomains(optional_ptr<FilterInfo> filter_info, RelationsSetToStats &relation_set_to_stats)
143229 : filter_info(filter_info), distinct_count_hll(relation_set_to_stats.distinct_count_hll),
143230 distinct_count_no_hll(relation_set_to_stats.distinct_count_no_hll),
143231 has_distinct_count_hll(relation_set_to_stats.has_distinct_count_hll) {
143232 }
143233
143234 optional_ptr<FilterInfo> filter_info;
143236 idx_t distinct_count_hll;
143238 idx_t distinct_count_no_hll;
143239 bool has_distinct_count_hll;
143240};
143241
143242struct Subgraph2Denominator {
143243 optional_ptr<JoinRelationSet> relations;
143244 optional_ptr<JoinRelationSet> numerator_relations;
143245 double denom;
143246
143247 Subgraph2Denominator() : relations(nullptr), numerator_relations(nullptr), denom(1) {};
143248};
143249
143250class CardinalityHelper {
143251public:
143252 CardinalityHelper() {
143253 }
143254 explicit CardinalityHelper(double cardinality_before_filters)
143255 : cardinality_before_filters(cardinality_before_filters) {};
143256
143257public:
143258
143259
143260
143261
143262
143263 double cardinality_before_filters;
143264
143265 vector<string> table_names_joined;
143266 vector<string> column_names;
143267};
143268
143269class CardinalityEstimator {
143270public:
143271 static constexpr double DEFAULT_SEMI_ANTI_SELECTIVITY = 5;
143272 explicit CardinalityEstimator() {};
143273
143274private:
143275 vector<RelationsSetToStats> relation_set_stats;
143276 unordered_map<string, CardinalityHelper> relation_set_2_cardinality;
143277 JoinRelationSetManager set_manager;
143278 vector<RelationStats> relation_stats;
143279
143280public:
143281 void RemoveEmptyTotalDomains();
143282 void UpdateTotalDomains(optional_ptr<JoinRelationSet> set, RelationStats &stats);
143283 void InitEquivalentRelations(const vector<unique_ptr<FilterInfo>> &filter_infos);
143284
143285 void InitCardinalityEstimatorProps(optional_ptr<JoinRelationSet> set, RelationStats &stats);
143286
143289 template <class T>
143290 T EstimateCardinalityWithSet(JoinRelationSet &new_set);
143291
143293 void AddRelationNamesToRelationStats(vector<RelationStats> &stats);
143294 void PrintRelationStats();
143295
143296private:
143297 double GetNumerator(JoinRelationSet &set);
143298 DenomInfo GetDenominator(JoinRelationSet &set);
143299
143300 bool SingleColumnFilter(FilterInfo &filter_info);
143301 vector<idx_t> DetermineMatchingEquivalentSets(optional_ptr<FilterInfo> filter_info);
143305 void AddToEquivalenceSets(optional_ptr<FilterInfo> filter_info, vector<idx_t> matching_equivalent_sets);
143306
143307 double CalculateUpdatedDenom(Subgraph2Denominator left, Subgraph2Denominator right,
143308 FilterInfoWithTotalDomains &filter);
143309 JoinRelationSet &UpdateNumeratorRelations(Subgraph2Denominator left, Subgraph2Denominator right,
143310 FilterInfoWithTotalDomains &filter);
143311
143312 void AddRelationStats(FilterInfo &filter_info);
143313 bool EmptyFilter(FilterInfo &filter_info);
143314};
143315
143316}
143317
143318
143319
143320
143321
143322
143323
143324
143325
143326
143327
143328
143329
143330
143331
143332
143333
143334
143335
143336namespace duckdb {
143337class Expression;
143338
143339template <class T>
143340struct ExpressionHashFunction {
143342 return (uint64_t)expr.get().Hash();
143343 }
143344};
143345
143346template <class T>
143347struct ExpressionEquality {
143348 bool operator()(
const reference<T> &a,
const reference<T> &b)
const {
143349 return a.get().Equals(b.get());
143350 }
143351};
143352
143353template <typename T>
143354using expression_map_t =
143355 unordered_map<reference<Expression>, T, ExpressionHashFunction<Expression>, ExpressionEquality<Expression>>;
143356
143357using expression_set_t =
143358 unordered_set<reference<Expression>, ExpressionHashFunction<Expression>, ExpressionEquality<Expression>>;
143359
143360template <typename T>
143361using parsed_expression_map_t = unordered_map<reference<ParsedExpression>, T, ExpressionHashFunction<ParsedExpression>,
143362 ExpressionEquality<ParsedExpression>>;
143363
143364using parsed_expression_set_t = unordered_set<reference<ParsedExpression>, ExpressionHashFunction<ParsedExpression>,
143365 ExpressionEquality<ParsedExpression>>;
143366
143367}
143368
143369
143370
143371
143372namespace duckdb {
143373
143374class JoinOrderOptimizer;
143375class FilterInfo;
143376
143378struct SingleJoinRelation {
143379 LogicalOperator &op;
143380 optional_ptr<LogicalOperator> parent;
143381 RelationStats stats;
143382
143383 SingleJoinRelation(LogicalOperator &op, optional_ptr<LogicalOperator> parent) : op(op), parent(parent) {
143384 }
143385 SingleJoinRelation(LogicalOperator &op, optional_ptr<LogicalOperator> parent, RelationStats stats)
143386 : op(op), parent(parent), stats(std::move(stats)) {
143387 }
143388};
143389
143390class RelationManager {
143391public:
143392 explicit RelationManager(ClientContext &context) : context(context) {
143393 }
143394
143395 idx_t NumRelations();
143396
143397 bool ExtractJoinRelations(JoinOrderOptimizer &optimizer, LogicalOperator &input_op,
143398 vector<reference<LogicalOperator>> &filter_operators,
143399 optional_ptr<LogicalOperator> parent = nullptr);
143400
143403 vector<unique_ptr<FilterInfo>> ExtractEdges(LogicalOperator &op,
143404 vector<reference<LogicalOperator>> &filter_operators,
143405 JoinRelationSetManager &set_manager);
143406
143408 bool ExtractBindings(Expression &expression, unordered_set<idx_t> &bindings);
143409 void AddRelation(LogicalOperator &op, optional_ptr<LogicalOperator> parent, const RelationStats &stats);
143411 void AddRelationWithChildren(JoinOrderOptimizer &optimizer, LogicalOperator &op, LogicalOperator &input_op,
143412 optional_ptr<LogicalOperator> parent, RelationStats &child_stats,
143413 optional_ptr<LogicalOperator> limit_op,
143414 vector<reference<LogicalOperator>> &datasource_filters);
143415 void AddAggregateOrWindowRelation(LogicalOperator &op, optional_ptr<LogicalOperator> parent,
143416 const RelationStats &stats, LogicalOperatorType op_type);
143417 vector<unique_ptr<SingleJoinRelation>> GetRelations();
143418
143419 const vector<RelationStats> GetRelationStats();
143421 unordered_map<idx_t, idx_t> relation_mapping;
143422
143423 bool CrossProductWithRelationAllowed(idx_t relation_id);
143424
143425 void PrintRelationStats();
143426
143427private:
143428 ClientContext &context;
143430 vector<unique_ptr<SingleJoinRelation>> relations;
143431 unordered_set<idx_t> no_cross_product_relations;
143432};
143433
143434}
143435
143436
143437
143438
143439
143440
143441
143442#include <functional>
143443
143444namespace duckdb {
143445
143446class FilterInfo;
143447
143448struct NeighborInfo {
143449 explicit NeighborInfo(optional_ptr<JoinRelationSet> neighbor) : neighbor(neighbor) {
143450 }
143451
143452 optional_ptr<JoinRelationSet> neighbor;
143453 vector<optional_ptr<FilterInfo>> filters;
143454};
143455
143457class QueryGraphEdges {
143458public:
143460 struct QueryEdge {
143461 vector<unique_ptr<NeighborInfo>> neighbors;
143462 unordered_map<idx_t, unique_ptr<QueryEdge>> children;
143463 };
143464
143465public:
143466 string ToString() const;
143467 void Print();
143468
143470 const vector<reference<NeighborInfo>> GetConnections(JoinRelationSet &node, JoinRelationSet &other) const;
143473 const vector<idx_t> GetNeighbors(JoinRelationSet &node, unordered_set<idx_t> &exclusion_set) const;
143474
143476 void EnumerateNeighbors(JoinRelationSet &node, const std::function<bool(NeighborInfo &)> &callback) const;
143478 void CreateEdge(JoinRelationSet &left, JoinRelationSet &right, optional_ptr<FilterInfo> info);
143479
143480private:
143482 optional_ptr<QueryEdge> GetQueryEdge(JoinRelationSet &left);
143483
143484 void EnumerateNeighborsDFS(JoinRelationSet &node, reference<QueryEdge> info, idx_t index,
143485 const std::function<bool(NeighborInfo &)> &callback) const;
143486
143487 QueryEdge root;
143488};
143489
143490}
143491
143492
143493namespace duckdb {
143494
143495struct NeighborInfo;
143496
143497class DPJoinNode {
143498public:
143500 JoinRelationSet &set;
143502 optional_ptr<NeighborInfo> info;
143503 bool is_leaf;
143505 JoinRelationSet &left_set;
143506 JoinRelationSet &right_set;
143507
143512 double cost;
143514 idx_t cardinality;
143515
143517 DPJoinNode(JoinRelationSet &set, optional_ptr<NeighborInfo> info, JoinRelationSet &left, JoinRelationSet &right,
143518 double cost);
143519
143523 explicit DPJoinNode(JoinRelationSet &set);
143524};
143525
143526}
143527
143528
143529
143530
143531
143532
143533
143534
143535
143536
143537
143538
143539
143540
143541
143542
143543
143544
143545
143546
143547
143548
143549
143550
143551
143552
143553
143554
143555namespace duckdb {
143556class ClientContext;
143557class Executor;
143558class Task;
143559class DatabaseInstance;
143560struct ProducerToken;
143561
143562enum class TaskExecutionMode :
uint8_t { PROCESS_ALL, PROCESS_PARTIAL };
143563
143564enum class TaskExecutionResult :
uint8_t { TASK_FINISHED, TASK_NOT_FINISHED, TASK_ERROR, TASK_BLOCKED };
143565
143567class Task : public enable_shared_from_this<Task> {
143568public:
143569 virtual ~Task() {
143570 }
143571
143572public:
143578 virtual TaskExecutionResult Execute(TaskExecutionMode mode) = 0;
143579
143583 virtual void Deschedule() {
143584 throw InternalException("Cannot deschedule task of base Task class");
143585 };
143586
143588 virtual void Reschedule() {
143589 throw InternalException("Cannot reschedule task of base Task class");
143590 }
143591
143592 virtual bool TaskBlockedOnResult() const {
143593 return false;
143594 }
143595
143596 virtual string TaskType() const {
143597 return "UnnamedTask";
143598 }
143599
143600public:
143601 optional_ptr<ProducerToken> token;
143602};
143603
143604}
143605
143606
143607#include <condition_variable>
143608
143609namespace duckdb {
143610
143619
143621struct InterruptDoneSignalState {
143623 void Signal();
143625 void Await();
143626
143627protected:
143628 mutex lock;
143629 std::condition_variable cv;
143630 bool done = false;
143631};
143632
143634class InterruptState {
143635public:
143637 InterruptState();
143639 explicit InterruptState(weak_ptr<Task> task);
143641 explicit InterruptState(weak_ptr<InterruptDoneSignalState> done_signal);
143642
143644 DUCKDB_API void Callback() const;
143645
143646protected:
143650 weak_ptr<Task> current_task;
143652 weak_ptr<InterruptDoneSignalState> signal_state;
143653};
143654
143655class StateWithBlockableTasks {
143656public:
143657 unique_lock<mutex> Lock() {
143658 return unique_lock<mutex>(lock);
143659 }
143660
143661 void PreventBlocking(const unique_lock<mutex> &guard) {
143662 VerifyLock(guard);
143663 can_block = false;
143664 }
143665
143667 bool BlockTask(const unique_lock<mutex> &guard, const InterruptState &interrupt_state) {
143668 VerifyLock(guard);
143669 if (can_block) {
143670 blocked_tasks.push_back(interrupt_state);
143671 return true;
143672 }
143673 return false;
143674 }
143675
143676 bool CanBlock(const unique_lock<mutex> &guard) const {
143677 VerifyLock(guard);
143678 return can_block;
143679 }
143680
143682 bool UnblockTasks(const unique_lock<mutex> &guard) {
143683 VerifyLock(guard);
143684 if (blocked_tasks.empty()) {
143685 return false;
143686 }
143687 for (auto &entry : blocked_tasks) {
143688 entry.Callback();
143689 }
143690 blocked_tasks.clear();
143691 return true;
143692 }
143693
143694 SinkResultType BlockSink(
const unique_lock<mutex> &guard,
const InterruptState &interrupt_state) {
143695 return BlockTask(guard, interrupt_state) ? SinkResultType::BLOCKED : SinkResultType::FINISHED;
143696 }
143697
143698 SourceResultType BlockSource(
const unique_lock<mutex> &guard,
const InterruptState &interrupt_state) {
143699 return BlockTask(guard, interrupt_state) ? SourceResultType::BLOCKED : SourceResultType::FINISHED;
143700 }
143701
143702 void VerifyLock(const unique_lock<mutex> &guard) const {
143703#ifdef DEBUG
143705#endif
143706 }
143707
143708private:
143710 atomic<bool> can_block {true};
143712 mutable mutex lock;
143714 mutable vector<InterruptState> blocked_tasks;
143715};
143716
143717}
143718
143719
143720
143721namespace duckdb {
143723class Executor;
143724class PhysicalOperator;
143725class Pipeline;
143726class PipelineBuildState;
143727class MetaPipeline;
143728class InterruptState;
143729
143730
143731class OperatorState {
143732public:
143733 virtual ~OperatorState() {
143734 }
143735
143736 virtual void Finalize(const PhysicalOperator &op, ExecutionContext &context) {
143737 }
143738
143739 template <class TARGET>
143740 TARGET &Cast() {
143741 DynamicCastCheck<TARGET>(this);
143742 return reinterpret_cast<TARGET &>(*this);
143743 }
143744 template <class TARGET>
143745 const TARGET &Cast() const {
143746 DynamicCastCheck<TARGET>(this);
143747 return reinterpret_cast<const TARGET &>(*this);
143748 }
143749};
143750
143751class GlobalOperatorState {
143752public:
143753 virtual ~GlobalOperatorState() {
143754 }
143755
143756 template <class TARGET>
143757 TARGET &Cast() {
143758 DynamicCastCheck<TARGET>(this);
143759 return reinterpret_cast<TARGET &>(*this);
143760 }
143761 template <class TARGET>
143762 const TARGET &Cast() const {
143763 DynamicCastCheck<TARGET>(this);
143764 return reinterpret_cast<const TARGET &>(*this);
143765 }
143766
143767 virtual idx_t MaxThreads(idx_t source_max_threads) {
143768 return source_max_threads;
143769 }
143770};
143771
143772class GlobalSinkState : public StateWithBlockableTasks {
143773public:
143775 }
143776 virtual ~GlobalSinkState() {
143777 }
143778
143780
143781 template <class TARGET>
143782 TARGET &Cast() {
143783 DynamicCastCheck<TARGET>(this);
143784 return reinterpret_cast<TARGET &>(*this);
143785 }
143786 template <class TARGET>
143787 const TARGET &Cast() const {
143788 DynamicCastCheck<TARGET>(this);
143789 return reinterpret_cast<const TARGET &>(*this);
143790 }
143791
143792 virtual idx_t MaxThreads(idx_t source_max_threads) {
143793 return source_max_threads;
143794 }
143795};
143796
143797class LocalSinkState {
143798public:
143799 virtual ~LocalSinkState() {
143800 }
143801
143803 SourcePartitionInfo partition_info;
143804
143805 template <class TARGET>
143806 TARGET &Cast() {
143807 DynamicCastCheck<TARGET>(this);
143808 return reinterpret_cast<TARGET &>(*this);
143809 }
143810 template <class TARGET>
143811 const TARGET &Cast() const {
143812 DynamicCastCheck<TARGET>(this);
143813 return reinterpret_cast<const TARGET &>(*this);
143814 }
143815};
143816
143817class GlobalSourceState : public StateWithBlockableTasks {
143818public:
143819 virtual ~GlobalSourceState() {
143820 }
143821
143822 virtual idx_t MaxThreads() {
143823 return 1;
143824 }
143825
143826 template <class TARGET>
143827 TARGET &Cast() {
143828 DynamicCastCheck<TARGET>(this);
143829 return reinterpret_cast<TARGET &>(*this);
143830 }
143831 template <class TARGET>
143832 const TARGET &Cast() const {
143833 DynamicCastCheck<TARGET>(this);
143834 return reinterpret_cast<const TARGET &>(*this);
143835 }
143836};
143837
143838class LocalSourceState {
143839public:
143840 virtual ~LocalSourceState() {
143841 }
143842
143843 template <class TARGET>
143844 TARGET &Cast() {
143845 DynamicCastCheck<TARGET>(this);
143846 return reinterpret_cast<TARGET &>(*this);
143847 }
143848 template <class TARGET>
143849 const TARGET &Cast() const {
143850 DynamicCastCheck<TARGET>(this);
143851 return reinterpret_cast<const TARGET &>(*this);
143852 }
143853};
143854
143855struct OperatorSinkInput {
143856 GlobalSinkState &global_state;
143857 LocalSinkState &local_state;
143858 InterruptState &interrupt_state;
143859};
143860
143861struct OperatorSourceInput {
143862 GlobalSourceState &global_state;
143863 LocalSourceState &local_state;
143864 InterruptState &interrupt_state;
143865};
143866
143867struct OperatorSinkCombineInput {
143868 GlobalSinkState &global_state;
143869 LocalSinkState &local_state;
143870 InterruptState &interrupt_state;
143871};
143872
143873struct OperatorSinkFinalizeInput {
143874 GlobalSinkState &global_state;
143875 InterruptState &interrupt_state;
143876};
143877
143878struct OperatorFinalizeInput {
143879 GlobalOperatorState &global_state;
143880 InterruptState &interrupt_state;
143881};
143882
143883struct OperatorSinkNextBatchInput {
143884 GlobalSinkState &global_state;
143885 LocalSinkState &local_state;
143886 InterruptState &interrupt_state;
143887};
143888
143889
143890
143891}
143892
143893
143894
143895
143896namespace duckdb {
143897
143899class Executor;
143900class PhysicalOperator;
143901class Pipeline;
143902class PipelineBuildState;
143903class MetaPipeline;
143904class PhysicalPlan;
143905
143906enum class OperatorCachingMode :
uint8_t { NONE, PARTITIONED, ORDERED, UNORDERED };
143907
143909class PhysicalOperator {
143910public:
143911 static constexpr const PhysicalOperatorType
TYPE = PhysicalOperatorType::INVALID;
143912
143913public:
143914 PhysicalOperator(PhysicalPlan &physical_plan, PhysicalOperatorType type, vector<LogicalType> types,
143915 idx_t estimated_cardinality);
143916 virtual ~PhysicalOperator() {
143917 }
143918
143920 PhysicalOperator(const PhysicalOperator &other) = delete;
143921 PhysicalOperator &
operator=(
const PhysicalOperator &) =
delete;
143922
143924 ArenaLinkedList<reference<PhysicalOperator>> children;
143926 PhysicalOperatorType type;
143928 vector<LogicalType> types;
143930 idx_t estimated_cardinality;
143931
143933 unique_ptr<GlobalSinkState> sink_state;
143935 unique_ptr<GlobalOperatorState> op_state;
143937 mutex lock;
143938
143939public:
143940 virtual string GetName() const;
143941 virtual InsertionOrderPreservingMap<string> ParamsToString() const {
143942 return InsertionOrderPreservingMap<string>();
143943 }
143944 static void SetEstimatedCardinality(InsertionOrderPreservingMap<string> &result, idx_t estimated_cardinality);
143945 virtual string ToString(ExplainFormat
format = ExplainFormat::DEFAULT)
const;
143946 void Print() const;
143947 virtual vector<const_reference<PhysicalOperator>> GetChildren() const;
143948
143950 const vector<LogicalType> &GetTypes() const {
143951 return types;
143952 }
143953
143954 virtual bool Equals(const PhysicalOperator &other) const {
143955 return false;
143956 }
143957
143959 idx_t EstimatedThreadCount()
const;
143960 bool CanSaturateThreads(ClientContext &context) const;
143961
143962 virtual void Verify();
143963
143964public:
143965
143966 virtual unique_ptr<OperatorState> GetOperatorState(ExecutionContext &context) const;
143967 virtual unique_ptr<GlobalOperatorState> GetGlobalOperatorState(ClientContext &context) const;
143968 virtual OperatorResultType Execute(ExecutionContext &context, DataChunk &input, DataChunk &chunk,
143969 GlobalOperatorState &gstate, OperatorState &state) const;
143971 GlobalOperatorState &gstate, OperatorState &state) const;
143973 OperatorFinalizeInput &input) const;
143974
143975 virtual bool ParallelOperator() const {
143976 return false;
143977 }
143978
143979 virtual bool RequiresFinalExecute() const {
143980 return false;
143981 }
143982
143983 virtual bool RequiresOperatorFinalize() const {
143984 return false;
143985 }
143986
143988 virtual OrderPreservationType OperatorOrder() const {
143989 return OrderPreservationType::INSERTION_ORDER;
143990 }
143991
143992public:
143993
143994 virtual unique_ptr<LocalSourceState> GetLocalSourceState(ExecutionContext &context,
143995 GlobalSourceState &gstate) const;
143996 virtual unique_ptr<GlobalSourceState> GetGlobalSourceState(ClientContext &context) const;
143997
143998protected:
143999 virtual SourceResultType GetDataInternal(ExecutionContext &context, DataChunk &chunk,
144000 OperatorSourceInput &input) const;
144001
144002public:
144003 SourceResultType GetData(ExecutionContext &context, DataChunk &chunk, OperatorSourceInput &input)
const;
144004
144005 virtual OperatorPartitionData GetPartitionData(ExecutionContext &context, DataChunk &chunk,
144006 GlobalSourceState &gstate, LocalSourceState &lstate,
144007 const OperatorPartitionInfo &partition_info) const;
144008
144009 virtual bool IsSource() const {
144010 return false;
144011 }
144012
144013 virtual bool ParallelSource() const {
144014 return false;
144015 }
144016
144017 virtual bool SupportsPartitioning(const OperatorPartitionInfo &partition_info) const {
144018 if (partition_info.AnyRequired()) {
144019 return false;
144020 }
144021 return true;
144022 }
144023
144025 virtual OrderPreservationType SourceOrder() const {
144026 return OrderPreservationType::INSERTION_ORDER;
144027 }
144028
144030 virtual ProgressData GetProgress(ClientContext &context, GlobalSourceState &gstate) const;
144031
144033 virtual ProgressData GetSinkProgress(ClientContext &context, GlobalSinkState &gstate,
144034 const ProgressData source_progress) const {
144035 return source_progress;
144036 }
144037
144038 virtual InsertionOrderPreservingMap<string> ExtraSourceParams(GlobalSourceState &gstate,
144039 LocalSourceState &lstate) const {
144040 return InsertionOrderPreservingMap<string>();
144041 }
144042
144043public:
144044
144045
144049 virtual SinkResultType Sink(ExecutionContext &context, DataChunk &chunk, OperatorSinkInput &input)
const;
144053 virtual SinkCombineResultType Combine(ExecutionContext &context, OperatorSinkCombineInput &input) const;
144056 virtual void PrepareFinalize(ClientContext &context, GlobalSinkState &sink_state) const;
144060 virtual SinkFinalizeType Finalize(Pipeline &pipeline, Event &event, ClientContext &context,
144061 OperatorSinkFinalizeInput &input) const;
144064 virtual SinkNextBatchType NextBatch(ExecutionContext &context, OperatorSinkNextBatchInput &input)
const;
144065
144066 virtual unique_ptr<LocalSinkState> GetLocalSinkState(ExecutionContext &context) const;
144067 virtual unique_ptr<GlobalSinkState> GetGlobalSinkState(ClientContext &context) const;
144068
144070 static idx_t GetMaxThreadMemory(ClientContext &context);
144071
144073 static OperatorCachingMode SelectOperatorCachingMode(ExecutionContext &context);
144074
144075 virtual bool IsSink() const {
144076 return false;
144077 }
144078
144079 virtual bool ParallelSink() const {
144080 return false;
144081 }
144082
144083 virtual OperatorPartitionInfo RequiredPartitionInfo() const {
144084 return OperatorPartitionInfo::NoPartitionInfo();
144085 }
144086
144089 virtual bool SinkOrderDependent() const {
144090 return false;
144091 }
144092
144093public:
144094
144095 virtual vector<const_reference<PhysicalOperator>> GetSources() const;
144096 bool AllSourcesSupportBatchIndex() const;
144097
144098 virtual void BuildPipelines(Pipeline ¤t, MetaPipeline &meta_pipeline);
144099
144100public:
144101 template <class TARGET>
144102 TARGET &Cast() {
144103 if (TARGET::TYPE != PhysicalOperatorType::INVALID && type != TARGET::TYPE) {
144104 throw InternalException("Failed to cast physical operator to type - physical operator type mismatch");
144105 }
144106 return reinterpret_cast<TARGET &>(*this);
144107 }
144108
144109 template <class TARGET>
144110 const TARGET &Cast() const {
144111 if (TARGET::TYPE != PhysicalOperatorType::INVALID && type != TARGET::TYPE) {
144112 throw InternalException("Failed to cast physical operator to type - physical operator type mismatch");
144113 }
144114 return reinterpret_cast<const TARGET &>(*this);
144115 }
144116};
144117
144119class CachingOperatorState : public OperatorState {
144120public:
144121 ~CachingOperatorState() override {
144122 }
144123
144124 void Finalize(const PhysicalOperator &op, ExecutionContext &context) override {
144125 }
144126
144127 unique_ptr<DataChunk> cached_chunk;
144128 bool initialized = false;
144130 OperatorCachingMode can_cache_chunk = OperatorCachingMode::NONE;
144131 bool must_return_continuation_chunk = false;
144133};
144134
144137class CachingPhysicalOperator : public PhysicalOperator {
144138public:
144139 static constexpr const idx_t CACHE_THRESHOLD = 64;
144140 CachingPhysicalOperator(PhysicalPlan &physical_plan, PhysicalOperatorType type, vector<LogicalType> types,
144141 idx_t estimated_cardinality);
144142
144143 bool caching_supported;
144144
144145public:
144148 OperatorResultType Execute(ExecutionContext &context, DataChunk &input, DataChunk &chunk,
144149 GlobalOperatorState &gstate, OperatorState &state) const final;
144153 OperatorState &state) const final;
144154
144155 bool RequiresFinalExecute() const final {
144156 return caching_supported;
144157 }
144158
144159protected:
144161 virtual OperatorResultType ExecuteInternal(ExecutionContext &context, DataChunk &input, DataChunk &chunk,
144162 GlobalOperatorState &gstate, OperatorState &state) const = 0;
144163
144164private:
144165 bool CanCacheType(const LogicalType &type);
144166};
144167
144168}
144169
144170
144171
144172
144173
144174
144175
144176
144177
144178
144179
144180
144181
144182
144183
144184
144185
144186
144187
144188
144189
144190
144191
144192
144193
144194
144195
144196
144197
144198
144199
144200
144201
144202
144203
144204
144205
144206
144207
144208
144209
144210
144211
144212
144213namespace duckdb {
144214
144217 NOT_PARTITIONED,
144218 SINGLE_VALUE_PARTITIONS,
144219 OVERLAPPING_PARTITIONS,
144220 DISJOINT_PARTITIONS
144221};
144222
144223enum class CountType { COUNT_EXACT, COUNT_APPROXIMATE };
144224
144225struct PartitionRowGroup {
144226 virtual ~PartitionRowGroup() = default;
144227 virtual unique_ptr<BaseStatistics> GetColumnStatistics(const StorageIndex &storage_index) = 0;
144228 virtual bool MinMaxIsExact(const BaseStatistics &stats, const StorageIndex &storage_index) = 0;
144229};
144230
144231struct PartitionStatistics {
144232 PartitionStatistics();
144233
144235 optional_idx row_start;
144239 CountType count_type;
144241 shared_ptr<PartitionRowGroup> partition_row_group;
144242};
144243
144244}
144245
144246
144247
144248
144249
144250
144251
144252
144253
144254
144255
144256
144257
144258
144259
144260
144261
144262
144263
144264
144265
144266
144267
144268
144269
144270
144271
144272
144273
144274
144275
144276
144277
144278
144279namespace duckdb {
144280
144281class IndexPointer {
144282public:
144284 static constexpr idx_t SHIFT_OFFSET = 32;
144285 static constexpr idx_t SHIFT_METADATA = 56;
144287 static constexpr idx_t AND_OFFSET = 0x0000000000FFFFFF;
144288 static constexpr idx_t AND_BUFFER_ID = 0x00000000FFFFFFFF;
144289 static constexpr idx_t AND_METADATA = 0xFF00000000000000;
144290
144291public:
144293 IndexPointer() : data(0) {};
144295 IndexPointer(const uint32_t buffer_id, const uint32_t offset) : data(0) {
144296 auto shifted_offset = UnsafeNumericCast<idx_t>(offset) << SHIFT_OFFSET;
144297 data += shifted_offset;
144298 data += buffer_id;
144299 };
144300
144301public:
144303 inline idx_t Get()
const {
144304 return data;
144305 }
144307 inline void Set(const idx_t data_p) {
144308 data = data_p;
144309 }
144310
144312 inline bool HasMetadata() const {
144313 return data & AND_METADATA;
144314 }
144316 inline uint8_t GetMetadata()
const {
144317 return data >> SHIFT_METADATA;
144318 }
144320 inline void SetMetadata(const uint8_t metadata) {
144321 data &= ~AND_METADATA;
144322 data |= UnsafeNumericCast<idx_t>(metadata) << SHIFT_METADATA;
144323 }
144324
144326 inline idx_t GetOffset()
const {
144327 auto offset = data >> SHIFT_OFFSET;
144328 return offset & AND_OFFSET;
144329 }
144331 inline idx_t GetBufferId()
const {
144332 return data & AND_BUFFER_ID;
144333 }
144334
144336 inline void Clear() {
144337 data = 0;
144338 }
144339
144341 inline void IncreaseBufferId(const idx_t summand) {
144342 data += summand;
144343 }
144344
144346 inline bool operator==(
const IndexPointer &ptr)
const {
144347 return data == ptr.data;
144348 }
144349
144350private:
144364};
144365
144366static_assert(
sizeof(IndexPointer) ==
sizeof(
idx_t),
"Invalid size for IndexPointer.");
144367
144368}
144369
144370
144371
144372
144373
144374
144375
144376
144377
144378
144379
144380
144381
144382
144383
144384
144385
144386
144387
144388
144389
144390
144391
144392
144393namespace duckdb {
144394class DuckTransaction;
144395class Transaction;
144396
144397struct TransactionData {
144398 TransactionData(DuckTransaction &transaction_p);
144399 TransactionData(transaction_t transaction_id_p, transaction_t start_time_p);
144400
144401 optional_ptr<DuckTransaction> transaction;
144404
144405 static TransactionData Committed() {
144406 return TransactionData(MAX_TRANSACTION_ID, 0);
144407 }
144408};
144409
144410}
144411
144412
144413namespace duckdb {
144414
144415enum class InsertedScanType {
144416
144417 STANDARD,
144418
144419 ALL_ROWS
144420};
144421
144424 STANDARD,
144429};
144430
144433 STANDARD,
144434
144435 DISALLOW_UPDATES
144436};
144437
144438struct ScanOptions {
144439 ScanOptions(TransactionData transaction);
144440
144441 TransactionData transaction;
144442 InsertedScanType insert_type = InsertedScanType::STANDARD;
144445};
144446
144455};
144456
144457}
144458
144459
144460namespace duckdb {
144461class RowGroup;
144462struct SelectionVector;
144463class Transaction;
144464struct TransactionData;
144465struct DeleteInfo;
144466class Serializer;
144467class Deserializer;
144468class FixedSizeAllocator;
144469
144470enum class ChunkInfoType :
uint8_t { CONSTANT_INFO, VECTOR_INFO, EMPTY_INFO };
144471
144472class ChunkInfo {
144473public:
144474 ChunkInfo(idx_t start, ChunkInfoType type) : start(start), type(type) {
144475 }
144476 virtual ~ChunkInfo() {
144477 }
144478
144482 ChunkInfoType type;
144483
144484public:
144487 virtual idx_t GetSelVector(ScanOptions options, optional_ptr<SelectionVector> sel_vector,
144488 idx_t max_count) const = 0;
144489 idx_t GetCheckpointRowCount(TransactionData transaction, idx_t max_count);
144491 virtual bool Fetch(TransactionData transaction, row_t row) = 0;
144492 virtual void CommitAppend(transaction_t commit_id, idx_t start, idx_t end) = 0;
144493 idx_t GetCommittedDeletedCount(idx_t max_count)
const;
144494 virtual bool Cleanup(transaction_t lowest_transaction) const;
144495 virtual string ToString(idx_t max_count) const = 0;
144496
144497 virtual bool HasDeletes(transaction_t transaction_id = MAX_TRANSACTION_ID) const = 0;
144498
144499 virtual void Write(WriteStream &writer, transaction_t transaction_id) const;
144500 static unique_ptr<ChunkInfo> Read(FixedSizeAllocator &allocator, ReadStream &reader);
144501
144502public:
144503 template <class TARGET>
144504 TARGET &Cast() {
144505 if (type != TARGET::TYPE) {
144506 throw InternalException("Failed to cast chunk info to type - query result type mismatch");
144507 }
144508 return reinterpret_cast<TARGET &>(*this);
144509 }
144510
144511 template <class TARGET>
144512 const TARGET &Cast() const {
144513 if (type != TARGET::TYPE) {
144514 throw InternalException("Failed to cast chunk info to type - query result type mismatch");
144515 }
144516 return reinterpret_cast<const TARGET &>(*this);
144517 }
144518};
144519
144520class ChunkConstantInfo : public ChunkInfo {
144521public:
144522 static constexpr const ChunkInfoType
TYPE = ChunkInfoType::CONSTANT_INFO;
144523
144524public:
144525 explicit ChunkConstantInfo(idx_t start);
144526
144529
144530public:
144531 idx_t GetSelVector(ScanOptions options, optional_ptr<SelectionVector> sel_vector, idx_t max_count)
const override;
144532 bool Fetch(TransactionData transaction, row_t row) override;
144533 void CommitAppend(transaction_t commit_id, idx_t start, idx_t end) override;
144534 bool Cleanup(transaction_t lowest_transaction) const override;
144535 string ToString(idx_t max_count) const override;
144536
144537 bool HasDeletes(transaction_t transaction_id = MAX_TRANSACTION_ID) const override;
144538
144539 void Write(WriteStream &writer, transaction_t transaction_id) const override;
144540 static unique_ptr<ChunkInfo> Read(ReadStream &reader);
144541
144542private:
144543 template <class INSERT_OP, class DELETE_OP>
144544 idx_t TemplatedGetSelVector(transaction_t start_time, transaction_t transaction_id, idx_t max_count)
const;
144545};
144546
144547class ChunkVectorInfo : public ChunkInfo {
144548public:
144549 static constexpr const ChunkInfoType
TYPE = ChunkInfoType::VECTOR_INFO;
144550
144551public:
144552 explicit ChunkVectorInfo(FixedSizeAllocator &allocator, idx_t start, transaction_t insert_id = 0);
144553 ~ChunkVectorInfo() override;
144554
144555public:
144556 idx_t GetSelVector(ScanOptions options, optional_ptr<SelectionVector> sel_vector, idx_t max_count)
const override;
144557 bool Fetch(TransactionData transaction, row_t row) override;
144558 void CommitAppend(transaction_t commit_id, idx_t start, idx_t end) override;
144559 bool Cleanup(transaction_t lowest_transaction) const override;
144560 string ToString(idx_t max_count) const override;
144561
144562 void Append(idx_t start, idx_t end, transaction_t commit_id);
144563
144569 idx_t Delete(transaction_t transaction_id, row_t
rows[], idx_t count);
144570 void CommitDelete(transaction_t commit_id, const DeleteInfo &info);
144571
144572 bool HasDeletes(transaction_t transaction_id = MAX_TRANSACTION_ID) const override;
144573 bool AnyDeleted() const;
144574 bool HasConstantInsertionId() const;
144576
144577 void Write(WriteStream &writer, transaction_t transaction_id) const override;
144578 static unique_ptr<ChunkInfo> Read(FixedSizeAllocator &allocator, ReadStream &reader);
144579
144580private:
144581 template <class INSERT_OP, class DELETE_OP>
144582 idx_t TemplatedGetSelVector(transaction_t start_time, transaction_t transaction_id,
144583 optional_ptr<SelectionVector> sel_vector, idx_t max_count) const;
144584
144585 IndexPointer GetInsertedPointer() const;
144586 IndexPointer GetDeletedPointer() const;
144587 IndexPointer GetInitializedInsertedPointer();
144588 IndexPointer GetInitializedDeletedPointer();
144589
144590private:
144591 FixedSizeAllocator &allocator;
144593 IndexPointer inserted_data;
144596
144598 IndexPointer deleted_data;
144599};
144600
144601}
144602
144603
144604
144605
144606
144607
144608
144609
144610
144611
144612
144613
144614
144615namespace duckdb {
144616
144617class SegmentStatistics {
144618public:
144619 explicit SegmentStatistics(LogicalType type);
144620 explicit SegmentStatistics(BaseStatistics statistics);
144621
144623 BaseStatistics statistics;
144624};
144625
144626}
144627
144628
144629
144630
144631
144632
144633
144634
144635
144636
144637
144638
144639
144640
144641
144642
144643namespace duckdb {
144644
144646class ColumnList {
144647public:
144648 class ColumnListIterator;
144649
144650public:
144651 DUCKDB_API explicit ColumnList(bool allow_duplicate_names = false);
144652 DUCKDB_API explicit ColumnList(vector<ColumnDefinition> columns, bool allow_duplicate_names = false);
144653
144654 DUCKDB_API void AddColumn(ColumnDefinition column);
144655 void Finalize();
144656
144657 DUCKDB_API const ColumnDefinition &GetColumn(LogicalIndex index) const;
144658 DUCKDB_API const ColumnDefinition &GetColumn(PhysicalIndex index) const;
144659 DUCKDB_API const ColumnDefinition &GetColumn(const string &name) const;
144660 DUCKDB_API ColumnDefinition &GetColumnMutable(LogicalIndex index);
144661 DUCKDB_API ColumnDefinition &GetColumnMutable(PhysicalIndex index);
144662 DUCKDB_API ColumnDefinition &GetColumnMutable(const string &name);
144663 DUCKDB_API vector<string> GetColumnNames() const;
144664 DUCKDB_API vector<LogicalType> GetColumnTypes() const;
144665
144666 DUCKDB_API bool ColumnExists(const string &name) const;
144667
144668 DUCKDB_API LogicalIndex GetColumnIndex(string &column_name) const;
144669 DUCKDB_API PhysicalIndex LogicalToPhysical(LogicalIndex index) const;
144670 DUCKDB_API LogicalIndex PhysicalToLogical(PhysicalIndex index) const;
144671
144672 idx_t LogicalColumnCount()
const {
144673 return columns.size();
144674 }
144675 idx_t PhysicalColumnCount()
const {
144676 return physical_columns.size();
144677 }
144678 bool empty() const {
144679 return columns.empty();
144680 }
144681
144682 ColumnList Copy() const;
144683 void Serialize(Serializer &serializer) const;
144684 static ColumnList Deserialize(Deserializer &deserializer);
144685
144686 DUCKDB_API ColumnListIterator Logical() const;
144687 DUCKDB_API ColumnListIterator Physical() const;
144688
144689 void SetAllowDuplicates(bool allow_duplicates) {
144690 allow_duplicate_names = allow_duplicates;
144691 }
144692
144693private:
144694 vector<ColumnDefinition> columns;
144696 case_insensitive_map_t<column_t> name_map;
144698 vector<idx_t> physical_columns;
144700 bool allow_duplicate_names;
144701
144702private:
144703 void AddToNameMap(ColumnDefinition &column);
144704
144705public:
144706
144707 class ColumnListIterator {
144708 public:
144709 ColumnListIterator(const ColumnList &list, bool physical) : list(list), physical(physical) {
144710 }
144711
144712 private:
144713 const ColumnList &list;
144714 bool physical;
144715
144716 private:
144717 class ColumnLogicalIteratorInternal {
144718 public:
144719 ColumnLogicalIteratorInternal(const ColumnList &list, bool physical, idx_t pos, idx_t end)
144720 : list(list), physical(physical), pos(pos), end(end) {
144721 }
144722
144723 const ColumnList &list;
144724 bool physical;
144727
144728 public:
144729 ColumnLogicalIteratorInternal &operator++() {
144730 pos++;
144731 return *this;
144732 }
144733 bool operator!=(
const ColumnLogicalIteratorInternal &other)
const {
144734 return pos != other.pos || end != other.end || &list != &other.list;
144735 }
144736 const ColumnDefinition &
operator*()
const {
144737 if (physical) {
144738 return list.GetColumn(PhysicalIndex(pos));
144739 } else {
144740 return list.GetColumn(LogicalIndex(pos));
144741 }
144742 }
144743 };
144744
144745 public:
144747 return physical ? list.PhysicalColumnCount() : list.LogicalColumnCount();
144748 }
144749
144750 ColumnLogicalIteratorInternal begin() {
144751 return ColumnLogicalIteratorInternal(list, physical, 0,
Size());
144752 }
144753 ColumnLogicalIteratorInternal end() {
144754 return ColumnLogicalIteratorInternal(list, physical,
Size(),
Size());
144755 }
144756 };
144757};
144758
144759}
144760
144761
144762
144763
144764
144765
144766
144767
144768
144769
144770
144771
144772
144773
144774namespace duckdb {
144775
144776template <class T>
144777class SegmentBase {
144778public:
144779 explicit SegmentBase(idx_t count) : count(count) {
144780 }
144781
144783 atomic<idx_t> count;
144784};
144785
144786}
144787
144788
144789
144790
144791
144792
144793
144794
144795
144796
144797
144798
144799
144800
144801namespace duckdb {
144802
144803class BlockAllocator;
144804class Serializer;
144805class Deserializer;
144806
144807class Block : public FileBuffer {
144808public:
144809 Block(BlockAllocator &allocator, const block_id_t id, const idx_t block_size, const idx_t block_header_size);
144810 Block(BlockAllocator &allocator, block_id_t id, uint32_t internal_size, idx_t block_header_size);
144811 Block(BlockAllocator &allocator, const block_id_t id, BlockManager &block_manager);
144812 Block(FileBuffer &source, block_id_t id, idx_t block_header_size);
144813
144814 block_id_t id;
144815};
144816
144817struct BlockPointer {
144818 BlockPointer(block_id_t block_id_p, uint32_t offset_p) : block_id(block_id_p), offset(offset_p) {
144819 }
144820 BlockPointer() : block_id(INVALID_BLOCK), offset(0) {
144821 }
144822
144823 block_id_t block_id;
144826
144827 bool IsValid() const {
144828 return block_id != INVALID_BLOCK;
144829 }
144830
144831 void Serialize(Serializer &serializer) const;
144832 static BlockPointer Deserialize(Deserializer &source);
144833};
144834
144835struct MetaBlockPointer {
144836 MetaBlockPointer(idx_t block_pointer, uint32_t offset_p) : block_pointer(block_pointer), offset(offset_p) {
144837 }
144838 MetaBlockPointer() : block_pointer(DConstants::INVALID_INDEX), offset(0) {
144839 }
144840
144841 idx_t block_pointer;
144844
144845 bool IsValid() const {
144846 return block_pointer != DConstants::INVALID_INDEX;
144847 }
144848 block_id_t GetBlockId() const;
144850
144851 bool operator==(
const MetaBlockPointer &rhs)
const {
144852 return block_pointer == rhs.block_pointer && offset == rhs.offset;
144853 }
144854
144855 friend std::ostream &
operator<<(std::ostream &os,
const MetaBlockPointer &obj) {
144856 return os << "{block_id: " << obj.GetBlockId() << " index: " << obj.GetBlockIndex() << " offset: " << obj.offset
144857 << "}";
144858 }
144859
144860 void Serialize(Serializer &serializer) const;
144861 static MetaBlockPointer Deserialize(Deserializer &source);
144862};
144863
144864}
144865
144866
144867
144868
144869
144870
144871
144872
144873
144874
144875
144876
144877
144878
144879
144880
144881
144882
144883
144884
144885
144886
144887
144888
144889namespace duckdb {
144890
144896};
144897
144903};
144904
144908 FULL_CHECKPOINT,
144914};
144915
144916}
144917
144918
144919
144920
144921namespace duckdb {
144922
144923struct CheckpointOptions {
144924 CheckpointOptions()
144926 type(
CheckpointType::FULL_CHECKPOINT), transaction_id(MAX_TRANSACTION_ID) {
144927 }
144928
144935 optional_ptr<lock_guard<mutex>> wal_lock;
144936};
144937
144938}
144939
144940
144941namespace duckdb {
144942class AttachedDatabase;
144943class BlockManager;
144944class ColumnData;
144945class DatabaseInstance;
144946class DataTable;
144947class PartialBlockManager;
144948struct DataTableInfo;
144949class ExpressionExecutor;
144950class RowGroupCollection;
144951class RowGroupWriter;
144952class UpdateSegment;
144953class TableStatistics;
144954struct ColumnSegmentInfo;
144955class Vector;
144956struct ColumnCheckpointState;
144957struct PartitionStatistics;
144958struct PersistentColumnData;
144959struct PersistentRowGroupData;
144960struct RowGroupPointer;
144961struct TransactionData;
144962class CollectionScanState;
144963class TableFilter;
144964class TableFilterSet;
144965struct ColumnFetchState;
144966struct RowGroupAppendState;
144967class MetadataManager;
144968class RowVersionManager;
144969class ScanFilterInfo;
144970class StorageCommitState;
144971template <class T>
144972struct SegmentNode;
144973enum class ColumnDataType;
144974
144975struct RowGroupWriteInfo {
144976 RowGroupWriteInfo(PartialBlockManager &manager, const vector<CompressionType> &compression_types,
144977 CheckpointOptions options = CheckpointOptions());
144978 RowGroupWriteInfo(PartialBlockManager &manager, const vector<CompressionType> &compression_types,
144979 vector<unique_ptr<PartialBlockManager>> &column_partial_block_managers_p);
144980
144981private:
144982 PartialBlockManager &manager;
144983
144984public:
144985 const vector<CompressionType> &compression_types;
144986 CheckpointOptions options;
144987
144988public:
144989 PartialBlockManager &GetPartialBlockManager(idx_t column_idx);
144990
144991private:
144992 optional_ptr<vector<unique_ptr<PartialBlockManager>>> column_partial_block_managers;
144993};
144994
144995struct RowGroupWriteData {
144996 shared_ptr<RowGroup> result_row_group;
144997 vector<unique_ptr<ColumnCheckpointState>> states;
144998 vector<BaseStatistics> statistics;
144999 bool reuse_existing_metadata_blocks = false;
145000 vector<idx_t> existing_extra_metadata_blocks;
145001 optional_idx write_count;
145002};
145003
145004class RowGroup : public SegmentBase<RowGroup> {
145005public:
145006 friend class ColumnData;
145007
145008public:
145009 RowGroup(RowGroupCollection &collection, idx_t count);
145010 RowGroup(RowGroupCollection &collection, RowGroupPointer pointer);
145011 RowGroup(RowGroupCollection &collection, PersistentRowGroupData &data);
145012 ~RowGroup();
145013
145014private:
145016 reference<RowGroupCollection> collection;
145018 atomic<optional_ptr<RowVersionManager>> version_info;
145020 shared_ptr<RowVersionManager> owned_version_info;
145022 mutable vector<shared_ptr<ColumnData>> columns;
145023
145024public:
145025 void MoveToCollection(RowGroupCollection &collection);
145026 RowGroupCollection &GetCollection() const {
145027 return collection.get();
145028 }
145030 vector<idx_t> GetOrComputeExtraMetadataBlocks(bool force_compute = false);
145031
145032 const vector<MetaBlockPointer> &GetColumnStartPointers() const;
145033
145034 BlockManager &GetBlockManager() const;
145035 DataTableInfo &GetTableInfo() const;
145036
145037 unique_ptr<RowGroup> AlterType(RowGroupCollection &collection, const LogicalType &target_type, idx_t changed_idx,
145038 ExpressionExecutor &executor, CollectionScanState &scan_state,
145039 SegmentNode<RowGroup> &node, DataChunk &scan_chunk);
145040 unique_ptr<RowGroup> AddColumn(RowGroupCollection &collection, ColumnDefinition &new_column,
145041 ExpressionExecutor &executor, Vector &intermediate);
145042 unique_ptr<RowGroup> RemoveColumn(RowGroupCollection &collection, idx_t removed_column);
145043
145044 void CommitDrop();
145045 void CommitDropColumn(const idx_t column_index);
145046
145047 void InitializeEmpty(const vector<LogicalType> &types, ColumnDataType data_type);
145048 bool HasChanges() const;
145049
145051 bool InitializeScan(CollectionScanState &state, SegmentNode<RowGroup> &node);
145052 bool InitializeScanWithOffset(CollectionScanState &state, SegmentNode<RowGroup> &node, idx_t vector_offset);
145055 bool CheckZonemap(ScanFilterInfo &filters);
145058 bool CheckZonemapSegments(CollectionScanState &state);
145059 void Scan(ScanOptions options, CollectionScanState &state, DataChunk &result);
145060 void Scan(CollectionScanState &state, DataChunk &result, TableScanType type);
145061
145062 idx_t GetSelVector(ScanOptions options, idx_t vector_idx, SelectionVector &sel_vector, idx_t max_count);
145063
145065 bool Fetch(TransactionData transaction, idx_t row);
145067 void FetchRow(TransactionData transaction, ColumnFetchState &state, const vector<StorageIndex> &column_ids,
145068 row_t row_id, DataChunk &result, idx_t result_idx);
145069
145071 void AppendVersionInfo(TransactionData transaction, idx_t count);
145073 void CommitAppend(transaction_t commit_id, idx_t start, idx_t count);
145075 void RevertAppend(idx_t new_count);
145077 void CleanupAppend(transaction_t lowest_transaction, idx_t start, idx_t count);
145078
145080 idx_t Delete(TransactionData transaction, DataTable &table, row_t *row_ids, idx_t count, idx_t row_group_start);
145081
145082 static vector<RowGroupWriteData> WriteToDisk(RowGroupWriteInfo &info,
145083 const vector<const_reference<RowGroup>> &row_groups);
145086 RowGroupWriteData WriteToDisk(RowGroupWriteInfo &info) const;
145088 idx_t GetCommittedRowCount();
145089 RowGroupWriteData WriteToDisk(RowGroupWriter &writer);
145090 RowGroupPointer Checkpoint(RowGroupWriteData write_data, RowGroupWriter &writer, TableStatistics &global_stats,
145091 idx_t row_group_start);
145092 bool IsPersistent() const;
145093 PersistentRowGroupData SerializeRowGroupInfo(idx_t row_group_start) const;
145094
145095 void InitializeAppend(RowGroupAppendState &append_state);
145096 void Append(RowGroupAppendState &append_state, DataChunk &chunk, idx_t append_count);
145097
145098 void Update(TransactionData transaction, DataTable &data_table, DataChunk &updates, row_t *ids, idx_t offset,
145099 idx_t count, const vector<PhysicalIndex> &column_ids, idx_t row_group_start);
145102 void UpdateColumn(TransactionData transaction, DataTable &data_table, DataChunk &updates, Vector &row_ids,
145103 idx_t offset, idx_t count, const vector<column_t> &column_path, idx_t row_group_start);
145104
145105 void MergeStatistics(idx_t column_idx, const BaseStatistics &other);
145106 void MergeIntoStatistics(idx_t column_idx, BaseStatistics &other);
145107 void MergeIntoStatistics(TableStatistics &other);
145108 unique_ptr<BaseStatistics> GetStatistics(idx_t column_idx) const;
145109 unique_ptr<BaseStatistics> GetStatistics(const StorageIndex &column_idx) const;
145110
145111 void GetColumnSegmentInfo(const QueryContext &context, idx_t row_group_index, vector<ColumnSegmentInfo> &result);
145112 static PartitionStatistics GetPartitionStats(SegmentNode<RowGroup> &row_group);
145113
145114 idx_t GetAllocationSize()
const {
145115 return allocation_size;
145116 }
145117
145118 void Verify();
145119
145120 void NextVector(CollectionScanState &state);
145121
145122 idx_t DeleteRows(idx_t vector_idx, transaction_t transaction_id, row_t
rows[], idx_t count);
145123 RowVersionManager &GetOrCreateVersionInfo();
145124
145125
145126 static void Serialize(RowGroupPointer &pointer, Serializer &serializer);
145127 static RowGroupPointer Deserialize(Deserializer &deserializer);
145128
145129 idx_t GetRowGroupSize()
const;
145130
145131 static FilterPropagateResult CheckRowIdFilter(const TableFilter &filter, idx_t beg_row, idx_t end_row);
145132 idx_t GetColumnCount()
const;
145133
145134 vector<MetaBlockPointer> CheckpointDeletes(RowGroupWriter &writer);
145135
145136private:
145137 optional_ptr<RowVersionManager> GetVersionInfo();
145138 optional_ptr<RowVersionManager> GetVersionInfoIfLoaded() const;
145139 shared_ptr<RowVersionManager> GetOrCreateVersionInfoPtr();
145140 shared_ptr<RowVersionManager> GetOrCreateVersionInfoInternal();
145141 void SetVersionInfo(shared_ptr<RowVersionManager> version);
145142
145143 ColumnData &GetColumn(storage_t c) const;
145144 void LoadColumn(storage_t c) const;
145145 ColumnData &GetColumn(const StorageIndex &c) const;
145146 vector<shared_ptr<ColumnData>> &GetColumns();
145147 void LoadRowIdColumnData() const;
145148 void SetCount(idx_t count);
145149
145150 bool HasUnloadedDeletes() const;
145151
145152private:
145153 mutable mutex row_group_lock;
145154 vector<MetaBlockPointer> column_pointers;
145156 mutable unique_ptr<atomic<bool>[]> is_loaded;
145157 vector<MetaBlockPointer> deletes_pointers;
145158 bool has_metadata_blocks = false;
145159 vector<idx_t> extra_metadata_blocks;
145160 atomic<bool> deletes_is_loaded;
145161 atomic<idx_t> allocation_size;
145163 mutable unique_ptr<ColumnData> row_id_column_data;
145165 mutable atomic<bool> row_id_is_loaded;
145166 atomic<bool> has_changes;
145167};
145168
145169}
145170
145171
145172
145173
145174
145175
145176
145177
145178
145179
145180
145181
145182
145183
145184
145185
145186
145187
145188
145189
145190
145191
145192
145193
145194
145195
145196
145197
145198
145199
145200
145201
145202
145203
145204
145205namespace duckdb {
145206struct StorageLockInternals;
145207
145208enum class StorageLockType { SHARED = 0, EXCLUSIVE = 1 };
145209
145210class StorageLockKey {
145211public:
145212 StorageLockKey(shared_ptr<StorageLockInternals> internals, StorageLockType type);
145213 ~StorageLockKey();
145214
145215 StorageLockType GetType() const {
145216 return type;
145217 }
145218
145219private:
145220 shared_ptr<StorageLockInternals> internals;
145221 StorageLockType type;
145222};
145223
145224class StorageLock {
145225public:
145226 StorageLock();
145227 ~StorageLock();
145228
145230 unique_ptr<StorageLockKey> GetExclusiveLock();
145232 unique_ptr<StorageLockKey> GetSharedLock();
145234 unique_ptr<StorageLockKey> TryGetExclusiveLock();
145239 unique_ptr<StorageLockKey> TryUpgradeCheckpointLock(StorageLockKey &lock);
145240
145241private:
145242 shared_ptr<StorageLockInternals> internals;
145243};
145244
145245}
145246
145247
145248
145249
145250
145251
145252
145253
145254
145255
145256
145257
145258
145259namespace duckdb {
145260
145261struct SegmentLock {
145262public:
145263 SegmentLock() {
145264 }
145265 explicit SegmentLock(mutex &lock) : lock(lock) {
145266 }
145267
145268 SegmentLock(const SegmentLock &other) = delete;
145269 SegmentLock &
operator=(
const SegmentLock &) =
delete;
145271 SegmentLock(SegmentLock &&other) noexcept {
145272 std::swap(lock, other.lock);
145273 }
145274 SegmentLock &
operator=(SegmentLock &&other)
noexcept {
145275 std::swap(lock, other.lock);
145276 return *this;
145277 }
145278
145279 void Release() {
145280 lock.unlock();
145281 }
145282
145283private:
145284 unique_lock<mutex> lock;
145285};
145286
145287}
145288
145289
145290
145291
145292
145293
145294namespace duckdb {
145295
145296template <class T>
145297struct SegmentNode {
145298 SegmentNode(idx_t row_start_p, shared_ptr<T> node_p, idx_t index_p)
145299 : row_start(row_start_p), node(std::move(node_p)), next(nullptr),
index(index_p) {
145300 }
145301
145302public:
145303 optional_ptr<SegmentNode<T>> Next() const {
145304#ifndef DUCKDB_R_BUILD
145305 return next.load();
145306#else
145307 return next;
145308#endif
145309 }
145310
145311 idx_t GetRowStart()
const {
145312 return row_start;
145313 }
145314 idx_t GetRowEnd()
const {
145315 return GetRowStart() + GetCount();
145316 }
145317 idx_t GetCount()
const {
145318 return GetNode().count;
145319 }
145320
145321 idx_t GetIndex()
const {
145323 }
145324
145325 T &GetNode() const {
145326 return *node;
145327 }
145328
145329 shared_ptr<T> MoveNode() {
145330 return std::move(node);
145331 }
145332 shared_ptr<T> &ReferenceNode() {
145333 return node;
145334 }
145335
145336 bool HasNode() const {
145337 return node.get();
145338 }
145339
145340 void SetNext(optional_ptr<SegmentNode<T>> next) {
145341 this->next = next.get();
145342 }
145343
145344 void SetNode(shared_ptr<T> new_node) {
145345 node = std::move(new_node);
145346 }
145347
145348private:
145350 shared_ptr<T> node;
145352#ifndef DUCKDB_R_BUILD
145353 atomic<SegmentNode<T> *> next;
145354#else
145355 SegmentNode<T> *next;
145356#endif
145359};
145360
145363
145364
145365
145366template <class T, bool SUPPORTS_LAZY_LOADING = false>
145367class SegmentTree {
145368private:
145369 class SegmentIterationHelper;
145370 class SegmentNodeIterationHelper;
145371
145372public:
145373 explicit SegmentTree(idx_t base_row_id = 0) : finished_loading(true), base_row_id(base_row_id) {
145374 }
145375 virtual ~SegmentTree() {
145376 }
145377
145380 SegmentLock Lock() const {
145381 return SegmentLock(node_lock);
145382 }
145383
145384 bool IsEmpty(SegmentLock &l) const {
145385 return GetRootSegment(l) == nullptr;
145386 }
145387
145389 optional_ptr<SegmentNode<T>> GetRootSegment() const {
145390 auto l = Lock();
145391 return GetRootSegment(l);
145392 }
145393
145394 optional_ptr<SegmentNode<T>> GetRootSegment(SegmentLock &l) const {
145395 if (nodes.empty()) {
145396 LoadNextSegment(l);
145397 }
145398 return GetRootSegmentInternal();
145399 }
145401 vector<unique_ptr<SegmentNode<T>>> MoveSegments(SegmentLock &l) {
145402 LoadAllSegments(l);
145403 return std::move(nodes);
145404 }
145405 vector<unique_ptr<SegmentNode<T>>> MoveSegments() {
145406 auto l = Lock();
145407 return MoveSegments(l);
145408 }
145409
145410 vector<unique_ptr<SegmentNode<T>>> &ReferenceLoadedSegmentsMutable(SegmentLock &l) {
145411 return nodes;
145412 }
145413
145414 idx_t GetSegmentCount()
const {
145415 auto l = Lock();
145416 return GetSegmentCount(l);
145417 }
145418 idx_t GetSegmentCount(SegmentLock &l)
const {
145419 LoadAllSegments(l);
145420 return nodes.size();
145421 }
145423 optional_ptr<SegmentNode<T>> GetSegmentByIndex(int64_t index) const {
145424 auto l = Lock();
145425 return GetSegmentByIndex(l, index);
145426 }
145427 optional_ptr<SegmentNode<T>> GetSegmentByIndex(SegmentLock &l, int64_t index) const {
145428 if (index < 0) {
145429
145430 LoadAllSegments(l);
145431 index += nodes.size();
145432 if (index < 0) {
145433 return nullptr;
145434 }
145435 return nodes[UnsafeNumericCast<idx_t>(index)].get();
145436 } else {
145437
145438 while (
idx_t(index) >= nodes.size() && LoadNextSegment(l)) {
145439 }
145440 if (
idx_t(index) >= nodes.size()) {
145441 return nullptr;
145442 }
145443 return nodes[UnsafeNumericCast<idx_t>(index)].get();
145444 }
145445 }
145447 optional_ptr<SegmentNode<T>> GetNextSegment(SegmentNode<T> &node) const {
145448 if (!SUPPORTS_LAZY_LOADING) {
145449 return node.Next();
145450 }
145451 if (finished_loading) {
145452 return node.Next();
145453 }
145454 auto l = Lock();
145455 return GetNextSegment(l, node);
145456 }
145457 optional_ptr<SegmentNode<T>> GetNextSegment(SegmentLock &l, SegmentNode<T> &node) const {
145458#ifdef DEBUG
145460#endif
145461 return GetSegmentByIndex(l, UnsafeNumericCast<int64_t>(node.GetIndex() + 1));
145462 }
145463
145465 optional_ptr<SegmentNode<T>> GetLastSegment(SegmentLock &l) const {
145466 LoadAllSegments(l);
145467 if (nodes.empty()) {
145468 return nullptr;
145469 }
145470 return nodes.back().get();
145471 }
145473 optional_ptr<SegmentNode<T>> GetSegment(idx_t row_number) const {
145474 auto l = Lock();
145475 return GetSegment(l, row_number);
145476 }
145477 optional_ptr<SegmentNode<T>> GetSegment(SegmentLock &l, idx_t row_number) const {
145478 return nodes[GetSegmentIndex(l, row_number)].get();
145479 }
145480
145481 void AppendSegment(shared_ptr<T> segment) {
145482 auto l = Lock();
145483 AppendSegment(l, std::move(segment));
145484 }
145485 void AppendSegment(SegmentLock &l, shared_ptr<T> segment) {
145486 LoadAllSegments(l);
145487 AppendSegmentInternal(l, std::move(segment));
145488 }
145489 void AppendSegment(SegmentLock &l, shared_ptr<T> segment, idx_t row_start) {
145490 LoadAllSegments(l);
145491 AppendSegmentInternal(l, std::move(segment), row_start);
145492 }
145494 bool HasSegment(SegmentNode<T> &segment) const {
145495 auto l = Lock();
145496 return HasSegment(l, segment);
145497 }
145498 bool HasSegment(SegmentLock &, SegmentNode<T> &segment) const {
145499 auto segment_idx = segment.GetIndex();
145500 return segment_idx < nodes.size() &&
RefersToSameObject(*nodes[segment_idx], segment);
145501 }
145502
145504 void EraseSegments(SegmentLock &l, idx_t segment_start) {
145505 LoadAllSegments(l);
145506 if (segment_start >= nodes.size()) {
145507 return;
145508 }
145509 nodes.erase(nodes.begin() + UnsafeNumericCast<int64_t>(segment_start), nodes.end());
145510 }
145511
145513 idx_t GetSegmentIndex(SegmentLock &l, idx_t row_number)
const {
145514 idx_t segment_index;
145515 if (TryGetSegmentIndex(l, row_number, segment_index)) {
145516 return segment_index;
145517 }
145518 string error;
145519 error =
StringUtil::Format(
"Attempting to find row number \"%lld\" in %lld nodes\n", row_number, nodes.size());
145520 for (idx_t i = 0; i < nodes.size(); i++) {
145521 error +=
StringUtil::Format(
"* Node %lld: Start %lld, Count %lld\n", i, nodes[i]->GetRowStart(),
145522 nodes[i]->GetCount());
145523 }
145524 throw InternalException("Could not find node in column segment tree!\n%s", error);
145525 }
145526
145527 bool TryGetSegmentIndex(SegmentLock &l, idx_t row_number, idx_t &result) const {
145528
145529 while (nodes.empty() || (row_number >= nodes.back()->GetRowEnd())) {
145530 if (!LoadNextSegment(l)) {
145531 break;
145532 }
145533 }
145534 if (nodes.empty()) {
145535 return false;
145536 }
145538 idx_t upper = nodes.size() - 1;
145539
145540 while (lower <= upper) {
145542 if (index >= nodes.size()) {
145543 string segments;
145544 for (auto &entry : nodes) {
145545 segments +=
StringUtil::Format(
"Start %d Count %d", entry->GetRowStart(), entry->GetCount());
145546 }
145547 throw InternalException("Segment tree index not found for row number %d\nSegments:%s", row_number,
145548 segments);
145549 }
145550 auto &entry = *nodes[
index];
145551 if (row_number < entry.GetRowStart()) {
145552 upper =
index - 1;
145553 } else if (row_number >= entry.GetRowEnd()) {
145554 lower =
index + 1;
145555 } else {
145557 return true;
145558 }
145559 }
145560 return false;
145561 }
145562
145563 void Verify(SegmentLock &) const {
145564#ifdef DEBUG
145565 idx_t base_start = nodes.empty() ? 0 : nodes[0]->GetRowStart();
145566 for (idx_t i = 0; i < nodes.size(); i++) {
145567 D_ASSERT(nodes[i]->GetRowStart() == base_start);
145568 base_start += nodes[i]->GetCount();
145569 }
145570#endif
145571 }
145572 void Verify() {
145573#ifdef DEBUG
145574 auto l = Lock();
145575 Verify(l);
145576#endif
145577 }
145578
145579 idx_t GetBaseRowId()
const {
145580 return base_row_id;
145581 }
145582
145583 SegmentIterationHelper Segments() const {
145584 return SegmentIterationHelper(*this);
145585 }
145586
145587 SegmentIterationHelper Segments(SegmentLock &l) const {
145588 return SegmentIterationHelper(*this, l);
145589 }
145590
145591 SegmentNodeIterationHelper SegmentNodes() const {
145592 return SegmentNodeIterationHelper(*this);
145593 }
145594
145595 SegmentNodeIterationHelper SegmentNodes(SegmentLock &l) const {
145596 return SegmentNodeIterationHelper(*this, l);
145597 }
145598
145599protected:
145600 mutable atomic<bool> finished_loading;
145601
145603 virtual shared_ptr<T> LoadSegment() const {
145604 return nullptr;
145605 }
145606
145607 optional_ptr<SegmentNode<T>> GetRootSegmentInternal() const {
145608 return nodes.empty() ? nullptr : nodes[0].get();
145609 }
145610
145611private:
145613 mutable vector<unique_ptr<SegmentNode<T>>> nodes;
145615 mutable mutex node_lock;
145617 idx_t base_row_id;
145618
145619private:
145620 class BaseSegmentIterator {
145621 public:
145622 BaseSegmentIterator(const SegmentTree &tree_p, optional_ptr<SegmentNode<T>> current_p,
145623 optional_ptr<SegmentLock> lock)
145624 : tree(tree_p), current(current_p), lock(lock) {
145625 }
145626
145627 const SegmentTree &tree;
145628 optional_ptr<SegmentNode<T>> current;
145629 optional_ptr<SegmentLock> lock;
145630
145631 public:
145632 void Next() {
145633 current = lock ? tree.GetNextSegment(*lock, *current) : tree.GetNextSegment(*current);
145634 }
145635
145636 BaseSegmentIterator &operator++() {
145637 Next();
145638 return *this;
145639 }
145640 bool operator!=(
const BaseSegmentIterator &other)
const {
145641 return current != other.current;
145642 }
145643 };
145644 class SegmentIterationHelper {
145645 public:
145646 explicit SegmentIterationHelper(const SegmentTree &tree) : tree(tree) {
145647 }
145648 SegmentIterationHelper(const SegmentTree &tree, SegmentLock &l) : tree(tree), lock(l) {
145649 }
145650
145651 private:
145652 const SegmentTree &tree;
145653 optional_ptr<SegmentLock> lock;
145654
145655 private:
145656 class SegmentIterator : public BaseSegmentIterator {
145657 public:
145658 SegmentIterator(const SegmentTree &tree_p, optional_ptr<SegmentNode<T>> current_p,
145659 optional_ptr<SegmentLock> lock)
145660 : BaseSegmentIterator(tree_p, current_p, lock) {
145661 }
145662
145664 return BaseSegmentIterator::current->GetNode();
145665 }
145666 };
145667
145668 public:
145669 SegmentIterator begin() {
145670 auto root = lock ? tree.GetRootSegment(*lock) : tree.GetRootSegment();
145671 return SegmentIterator(tree, root, lock);
145672 }
145673 SegmentIterator end() {
145674 return SegmentIterator(tree, nullptr, lock);
145675 }
145676 };
145677 class SegmentNodeIterationHelper {
145678 public:
145679 explicit SegmentNodeIterationHelper(const SegmentTree &tree) : tree(tree) {
145680 }
145681 SegmentNodeIterationHelper(const SegmentTree &tree, SegmentLock &l) : tree(tree), lock(l) {
145682 }
145683
145684 private:
145685 const SegmentTree &tree;
145686 optional_ptr<SegmentLock> lock;
145687
145688 private:
145689 class SegmentIterator : public BaseSegmentIterator {
145690 public:
145691 SegmentIterator(const SegmentTree &tree_p, optional_ptr<SegmentNode<T>> current_p,
145692 optional_ptr<SegmentLock> lock)
145693 : BaseSegmentIterator(tree_p, current_p, lock) {
145694 }
145695
145697 return *BaseSegmentIterator::current;
145698 }
145699 };
145700
145701 public:
145702 SegmentIterator begin() {
145703 auto root = lock ? tree.GetRootSegment(*lock) : tree.GetRootSegment();
145704 return SegmentIterator(tree, root, lock);
145705 }
145706 SegmentIterator end() {
145707 return SegmentIterator(tree, nullptr, lock);
145708 }
145709 };
145710
145712 bool LoadNextSegment(SegmentLock &l) const {
145713 if (!SUPPORTS_LAZY_LOADING) {
145714 return false;
145715 }
145716 if (finished_loading) {
145717 return false;
145718 }
145719 auto result = LoadSegment();
145720 if (result) {
145721 AppendSegmentInternal(l, std::move(result));
145722 return true;
145723 }
145724 return false;
145725 }
145726
145728 void LoadAllSegments(SegmentLock &l) const {
145729 if (!SUPPORTS_LAZY_LOADING) {
145730 return;
145731 }
145732 while (LoadNextSegment(l)) {
145733 }
145734 }
145735
145737 void AppendSegmentInternal(SegmentLock &l, shared_ptr<T> segment, idx_t row_start) const {
145738 D_ASSERT(segment);
145739
145740 auto node = make_uniq<SegmentNode<T>>(row_start, std::move(segment), nodes.size());
145741 if (!nodes.empty()) {
145742 nodes.back()->SetNext(*node);
145743 }
145744 nodes.push_back(std::move(node));
145745 }
145746 void AppendSegmentInternal(SegmentLock &l, shared_ptr<T> segment) const {
145748 if (nodes.empty()) {
145749 row_start = base_row_id;
145750 } else {
145751 auto &last_node = nodes.back();
145752 row_start = last_node->GetRowEnd();
145753 }
145754 AppendSegmentInternal(l, std::move(segment), row_start);
145755 }
145756};
145757
145758}
145759
145760
145761
145762namespace duckdb {
145763struct DataTableInfo;
145764class PersistentTableData;
145765class MetadataReader;
145766
145767class RowGroupSegmentTree : public SegmentTree<RowGroup, true> {
145768public:
145769 RowGroupSegmentTree(RowGroupCollection &collection, idx_t base_row_id);
145770 ~RowGroupSegmentTree() override;
145771
145772 void Initialize(PersistentTableData &data, optional_ptr<vector<MetaBlockPointer>> read_pointers = nullptr);
145773
145774 MetaBlockPointer GetRootPointer() const {
145775 return root_pointer;
145776 }
145777
145778protected:
145779 shared_ptr<RowGroup> LoadSegment() const override;
145780
145781 RowGroupCollection &collection;
145782 mutable idx_t current_row_group;
145783 mutable idx_t max_row_group;
145784 mutable unique_ptr<MetadataReader> reader;
145785 MetaBlockPointer root_pointer;
145786};
145787
145788}
145789
145790
145791
145792
145793namespace duckdb {
145794
145795enum class OrderByStatistics :
uint8_t { MIN, MAX };
145796enum class OrderByColumnType :
uint8_t { NUMERIC,
STRING };
145797
145798struct RowGroupOrderOptions {
145799 RowGroupOrderOptions(const StorageIndex &column_idx_p, OrderByStatistics order_by_p, OrderType order_type_p,
145800 OrderByNullType null_order_p, OrderByColumnType column_type_p,
145801 optional_idx row_limit_p = optional_idx(), idx_t row_group_offset_p = 0,
145802 idx_t leading_null_group_offset_p = 0)
145803 : column_idx(column_idx_p), order_by(order_by_p), order_type(order_type_p), null_order(null_order_p),
145804 column_type(column_type_p), row_limit(row_limit_p), row_group_offset(row_group_offset_p),
145805 leading_null_group_offset(leading_null_group_offset_p) {
145806 }
145807
145808 const StorageIndex column_idx;
145809 const OrderByStatistics order_by;
145810 const OrderType order_type;
145811 const OrderByNullType null_order;
145812 const OrderByColumnType column_type;
145813 const optional_idx row_limit;
145814 const idx_t row_group_offset;
145815 const idx_t leading_null_group_offset;
145816
145817 void Serialize(Serializer &serializer) const;
145818 static unique_ptr<RowGroupOrderOptions> Deserialize(Deserializer &deserializer);
145819};
145820
145821struct OffsetPruningResult {
145822 idx_t offset_remainder;
145823 idx_t pruned_row_group_count;
145824 idx_t leading_null_group_offset;
145825};
145826
145827class RowGroupReorderer {
145828public:
145829 explicit RowGroupReorderer(const RowGroupOrderOptions &options_p);
145830 optional_ptr<SegmentNode<RowGroup>> GetRootSegment(RowGroupSegmentTree &row_groups);
145831 optional_ptr<SegmentNode<RowGroup>> GetNextRowGroup(SegmentNode<RowGroup> &row_group);
145832
145833 static Value RetrieveStat(const BaseStatistics &stats, OrderByStatistics order_by, OrderByColumnType column_type);
145834 static OffsetPruningResult GetOffsetAfterPruning(OrderByStatistics order_by, OrderByColumnType column_type,
145835 OrderType order_type, OrderByNullType null_order,
145836 const StorageIndex &column_idx, idx_t row_offset,
145837 vector<PartitionStatistics> &stats);
145838
145839private:
145840 const RowGroupOrderOptions options;
145841
145843 bool initialized;
145844 vector<reference<SegmentNode<RowGroup>>> ordered_row_groups;
145845};
145846
145847}
145848
145849
145850
145851
145852
145853
145854
145855
145856
145857
145858
145859
145860
145861
145862
145863namespace duckdb {
145864
145865struct TableColumn {
145866 TableColumn() = default;
145867 TableColumn(string name_p, LogicalType type_p) : name(std::move(name_p)), type(std::move(type_p)) {
145868 }
145869
145870 string name;
145871 LogicalType type;
145872
145873 void Serialize(Serializer &serializer) const;
145874 static TableColumn Deserialize(Deserializer &deserializer);
145875};
145876
145877using virtual_column_map_t = unordered_map<column_t, TableColumn>;
145878
145879}
145880
145881
145882
145883
145884
145885
145886
145887
145888
145889
145890
145891
145892
145893
145894
145895
145896
145897
145898
145899
145900
145901
145902
145903
145904#include <stdint.h>
145905
145906
145907namespace duckdb {
145908
145909struct EnumUtil {
145910
145911 template <class T>
145912 static T FromString(const char *value) = delete;
145913
145914 template <class T>
145915 static T FromString(const string &value) { return FromString<T>(value.c_str()); }
145916
145917
145918 template <class T>
145919 static const char *ToChars(T value) = delete;
145920
145921 template <class T>
145922 static string ToString(T value) { return string(ToChars<T>(value)); }
145923};
145924
145925enum class ARTConflictType :
uint8_t;
145926
145927enum class ARTHandlingResult :
uint8_t;
145928
145929enum class ARTScanHandling :
uint8_t;
145930
145932
145933enum class AccessMode :
uint8_t;
145934
145936
145938
145939enum class AggregateHandling :
uint8_t;
145940
145942
145943enum class AggregateType :
uint8_t;
145944
145945enum class AllowParserOverride :
uint8_t;
145946
145947enum class AlterDatabaseType :
uint8_t;
145948
145949enum class AlterForeignKeyType :
uint8_t;
145950
145951enum class AlterScalarFunctionType :
uint8_t;
145952
145953enum class AlterTableFunctionType :
uint8_t;
145954
145955enum class AlterTableType :
uint8_t;
145956
145957enum class AlterType :
uint8_t;
145958
145959enum class AlterViewType :
uint8_t;
145960
145961enum class AppenderType :
uint8_t;
145962
145963enum class ArrowArrayPhysicalType :
uint8_t;
145964
145965enum class ArrowDateTimeType :
uint8_t;
145966
145968
145969enum class ArrowOffsetSize :
uint8_t;
145970
145971enum class ArrowTypeInfoType :
uint8_t;
145972
145973enum class ArrowVariableSizeType :
uint8_t;
145974
145976
145977enum class AsyncResultsExecutionMode :
uint8_t;
145978
145980
145981enum class BinderType :
uint8_t;
145982
145983enum class BindingMode :
uint8_t;
145984
145985enum class BitpackingMode :
uint8_t;
145986
145988
145989enum class BlockState :
uint8_t;
145990
145991enum class BufferedIndexReplay :
uint8_t;
145992
145993enum class CAPIResultSetType :
uint8_t;
145994
145996
145997enum class CTEMaterialize :
uint8_t;
145998
145999enum class CacheValidationMode :
uint8_t;
146000
146002
146004
146005enum class CatalogType :
uint8_t;
146006
146007enum class CheckpointAbort :
uint8_t;
146008
146009enum class ChunkInfoType :
uint8_t;
146010
146012
146014
146016
146017enum class ColumnSegmentType :
uint8_t;
146018
146020
146021enum class CompressionType :
uint8_t;
146022
146023enum class CompressionValidity :
uint8_t;
146024
146025enum class ConflictManagerMode :
uint8_t;
146026
146027enum class ConstraintType :
uint8_t;
146028
146030
146031enum class CopyFunctionReturnType :
uint8_t;
146032
146033enum class CopyOverwriteMode :
uint8_t;
146034
146035enum class CopyToType :
uint8_t;
146036
146037enum class DataFileType :
uint8_t;
146038
146039enum class DateCastResult :
uint8_t;
146040
146041enum class DatePartSpecifier :
uint8_t;
146042
146043enum class DebugInitialize :
uint8_t;
146044
146045enum class DebugVectorVerification :
uint8_t;
146046
146047enum class DecimalBitWidth :
uint8_t;
146048
146049enum class DefaultOrderByNullType :
uint8_t;
146050
146052
146053enum class DeprecatedIndexType :
uint8_t;
146054
146055enum class DeprecatedUsingKeySyntax :
uint8_t;
146056
146058
146059enum class DistinctType :
uint8_t;
146060
146062
146063enum class ExceptionFormatValueType :
uint8_t;
146064
146065enum class ExceptionType :
uint8_t;
146066
146067enum class ExplainFormat :
uint8_t;
146068
146069enum class ExplainOutputType :
uint8_t;
146070
146071enum class ExplainType :
uint8_t;
146072
146073enum class ExponentType :
uint8_t;
146074
146075enum class ExpressionClass :
uint8_t;
146076
146077enum class ExpressionType :
uint8_t;
146078
146080
146082
146083enum class ExtensionLoadResult :
uint8_t;
146084
146085enum class ExtensionUpdateResultTag :
uint8_t;
146086
146087enum class ExtraDropInfoType :
uint8_t;
146088
146089enum class ExtraPersistentColumnDataType :
uint8_t;
146090
146092
146093enum class FileBufferType :
uint8_t;
146094
146095enum class FileCompressionType :
uint8_t;
146096
146097enum class FileExpandResult :
uint8_t;
146098
146099enum class FileGlobOptions :
uint8_t;
146100
146101enum class FileLockType :
uint8_t;
146102
146103enum class FileNameSegmentType :
uint8_t;
146104
146105enum class FilterPropagateResult :
uint8_t;
146106
146107enum class ForeignKeyType :
uint8_t;
146108
146110
146112
146114
146116
146117enum class GateStatus :
uint8_t;
146118
146119enum class GeometryStorageType :
uint8_t;
146120
146121enum class GeometryType :
uint8_t;
146122
146124
146125enum class HTTPStatusCode :
uint16_t;
146126
146127enum class IndexAppendMode :
uint8_t;
146128
146130
146131enum class IndexConstraintType :
uint8_t;
146132
146133enum class InsertColumnOrder :
uint8_t;
146134
146136
146137enum class JoinRefType :
uint8_t;
146138
146139enum class JoinType :
uint8_t;
146140
146141enum class KeywordCategory :
uint8_t;
146142
146143enum class LambdaSyntax :
uint8_t;
146144
146145enum class LambdaSyntaxType :
uint8_t;
146146
146147enum class LimitNodeType :
uint8_t;
146148
146149enum class LoadType :
uint8_t;
146150
146151enum class LogContextScope :
uint8_t;
146152
146154
146155enum class LogMode :
uint8_t;
146156
146158
146159enum class LogicalOperatorType :
uint8_t;
146160
146162
146163enum class LookupResultType :
uint8_t;
146164
146165enum class MacroType :
uint8_t;
146166
146167enum class MapInvalidReason :
uint8_t;
146168
146169enum class MemoryTag :
uint8_t;
146170
146171enum class MergeActionCondition :
uint8_t;
146172
146173enum class MergeActionType :
uint8_t;
146174
146176
146177enum class MetricGroup :
uint8_t;
146178
146179enum class MetricType :
uint8_t;
146180
146181enum class MultiFileColumnMappingMode :
uint8_t;
146182
146183enum class MultiFileFileState :
uint8_t;
146184
146186
146187enum class NewLineIdentifier :
uint8_t;
146188
146189enum class OnConflictAction :
uint8_t;
146190
146191enum class OnCreateConflict :
uint8_t;
146192
146193enum class OnEntryNotFound :
uint8_t;
146194
146195enum class OperatorCachingMode :
uint8_t;
146196
146198
146200
146202
146203enum class OptimizerType :
uint32_t;
146204
146205enum class OrderByColumnType :
uint8_t;
146206
146207enum class OrderByNullType :
uint8_t;
146208
146209enum class OrderByStatistics :
uint8_t;
146210
146211enum class OrderPreservationType :
uint8_t;
146212
146213enum class OrderType :
uint8_t;
146214
146215enum class OrdinalityType :
uint8_t;
146216
146217enum class OutputStream :
uint8_t;
146218
146219enum class ParseInfoType :
uint8_t;
146220
146221enum class ParserExtensionResultType :
uint8_t;
146222
146224
146226
146227enum class PendingExecutionResult :
uint8_t;
146228
146229enum class PhysicalOperatorType :
uint8_t;
146230
146231enum class PhysicalTableScanExecutionStrategy :
uint8_t;
146232
146234
146235enum class PragmaType :
uint8_t;
146236
146237enum class PreparedParamType :
uint8_t;
146238
146239enum class PreparedStatementMode :
uint8_t;
146240
146241enum class PreserveOrderType :
uint8_t;
146242
146243enum class ProfilerPrintFormat :
uint8_t;
146244
146245enum class ProfilingCoverage :
uint8_t;
146246
146247enum class ProfilingParameterNames :
uint8_t;
146248
146249enum class PushdownExtractSupport :
uint8_t;
146250
146251enum class QuantileSerializationType :
uint8_t;
146252
146253enum class QueryNodeType :
uint8_t;
146254
146255enum class QueryResultMemoryType :
uint8_t;
146256
146257enum class QueryResultOutputType :
uint8_t;
146258
146259enum class QueryResultType :
uint8_t;
146260
146262
146263enum class RelationType :
uint8_t;
146264
146265enum class RenderMode :
uint8_t;
146266
146267enum class RequestType :
uint8_t;
146268
146269enum class ResultModifierType :
uint8_t;
146270
146271enum class SampleMethod :
uint8_t;
146272
146273enum class SampleType :
uint8_t;
146274
146275enum class SamplingState :
uint8_t;
146276
146277enum class ScanType :
uint8_t;
146278
146280
146282
146284
146285enum class SequenceInfo :
uint8_t;
146286
146287enum class SetOperationType :
uint8_t;
146288
146289enum class SetScope :
uint8_t;
146290
146291enum class SetType :
uint8_t;
146292
146294
146295enum class ShowType :
uint8_t;
146296
146298
146299enum class SinkCombineResultType :
uint8_t;
146300
146302
146304
146306
146308
146310
146311enum class StarExpressionType :
uint8_t;
146312
146313enum class StatementReturnType :
uint8_t;
146314
146315enum class StatementType :
uint8_t;
146316
146317enum class StatisticsType :
uint8_t;
146318
146319enum class StatsInfo :
uint8_t;
146320
146321enum class StorageBlockPrefetch :
uint8_t;
146322
146323enum class StorageIndexType :
uint8_t;
146324
146325enum class StrTimeSpecifier :
uint8_t;
146326
146327enum class StreamExecutionResult :
uint8_t;
146328
146329enum class SubqueryType :
uint8_t;
146330
146331enum class TableColumnType :
uint8_t;
146332
146333enum class TableFilterType :
uint8_t;
146334
146336
146337enum class TableReferenceType :
uint8_t;
146338
146339enum class TaskExecutionMode :
uint8_t;
146340
146341enum class TaskExecutionResult :
uint8_t;
146342
146343enum class TemporaryBufferSize :
uint64_t;
146344
146345enum class TemporaryCompressionLevel : int;
146346
146347enum class ThreadPinMode :
uint8_t;
146348
146349enum class TimestampCastResult :
uint8_t;
146350
146351enum class TransactionInvalidationPolicy :
uint8_t;
146352
146353enum class TransactionModifierType :
uint8_t;
146354
146355enum class TransactionType :
uint8_t;
146356
146357enum class TupleDataNestednessType :
uint8_t;
146358
146360
146361enum class TupleDataValidityType :
uint8_t;
146362
146364
146365enum class UnionInvalidReason :
uint8_t;
146366
146367enum class VariantChildLookupMode :
uint8_t;
146368
146369enum class VariantLogicalType :
uint8_t;
146370
146372
146373enum class VariantValueType :
uint8_t;
146374
146375enum class VectorAuxiliaryDataType :
uint8_t;
146376
146377enum class VectorBufferType :
uint8_t;
146378
146379enum class VectorType :
uint8_t;
146380
146381enum class VerificationType :
uint8_t;
146382
146383enum class VerifyExistenceType :
uint8_t;
146384
146385enum class VertexType :
uint8_t;
146386
146387enum class WALType :
uint8_t;
146388
146390
146391enum class WindowBoundary :
uint8_t;
146392
146394
146395enum class WindowMergeSortStage :
uint8_t;
146396
146397
146398template<>
146399const char* EnumUtil::ToChars<ARTConflictType>(ARTConflictType value);
146400
146401template<>
146402const char* EnumUtil::ToChars<ARTHandlingResult>(ARTHandlingResult value);
146403
146404template<>
146405const char* EnumUtil::ToChars<ARTScanHandling>(ARTScanHandling value);
146406
146407template<>
146408const char* EnumUtil::ToChars<ARTScanResult>(ARTScanResult value);
146409
146410template<>
146411const char* EnumUtil::ToChars<AccessMode>(AccessMode value);
146412
146413template<>
146414const char* EnumUtil::ToChars<AggregateCombineType>(AggregateCombineType value);
146415
146416template<>
146417const char* EnumUtil::ToChars<AggregateDistinctDependent>(AggregateDistinctDependent value);
146418
146419template<>
146420const char* EnumUtil::ToChars<AggregateHandling>(AggregateHandling value);
146421
146422template<>
146423const char* EnumUtil::ToChars<AggregateOrderDependent>(AggregateOrderDependent value);
146424
146425template<>
146426const char* EnumUtil::ToChars<AggregateType>(AggregateType value);
146427
146428template<>
146429const char* EnumUtil::ToChars<AllowParserOverride>(AllowParserOverride value);
146430
146431template<>
146432const char* EnumUtil::ToChars<AlterDatabaseType>(AlterDatabaseType value);
146433
146434template<>
146435const char* EnumUtil::ToChars<AlterForeignKeyType>(AlterForeignKeyType value);
146436
146437template<>
146438const char* EnumUtil::ToChars<AlterScalarFunctionType>(AlterScalarFunctionType value);
146439
146440template<>
146441const char* EnumUtil::ToChars<AlterTableFunctionType>(AlterTableFunctionType value);
146442
146443template<>
146444const char* EnumUtil::ToChars<AlterTableType>(AlterTableType value);
146445
146446template<>
146447const char* EnumUtil::ToChars<AlterType>(AlterType value);
146448
146449template<>
146450const char* EnumUtil::ToChars<AlterViewType>(AlterViewType value);
146451
146452template<>
146453const char* EnumUtil::ToChars<AppenderType>(AppenderType value);
146454
146455template<>
146456const char* EnumUtil::ToChars<ArrowArrayPhysicalType>(ArrowArrayPhysicalType value);
146457
146458template<>
146459const char* EnumUtil::ToChars<ArrowDateTimeType>(ArrowDateTimeType value);
146460
146461template<>
146462const char* EnumUtil::ToChars<ArrowFormatVersion>(ArrowFormatVersion value);
146463
146464template<>
146465const char* EnumUtil::ToChars<ArrowOffsetSize>(ArrowOffsetSize value);
146466
146467template<>
146468const char* EnumUtil::ToChars<ArrowTypeInfoType>(ArrowTypeInfoType value);
146469
146470template<>
146471const char* EnumUtil::ToChars<ArrowVariableSizeType>(ArrowVariableSizeType value);
146472
146473template<>
146474const char* EnumUtil::ToChars<AsyncResultType>(AsyncResultType value);
146475
146476template<>
146477const char* EnumUtil::ToChars<AsyncResultsExecutionMode>(AsyncResultsExecutionMode value);
146478
146479template<>
146480const char* EnumUtil::ToChars<BaseColumnPrunerMode>(BaseColumnPrunerMode value);
146481
146482template<>
146483const char* EnumUtil::ToChars<BinderType>(BinderType value);
146484
146485template<>
146486const char* EnumUtil::ToChars<BindingMode>(BindingMode value);
146487
146488template<>
146489const char* EnumUtil::ToChars<BitpackingMode>(BitpackingMode value);
146490
146491template<>
146492const char* EnumUtil::ToChars<BlockIteratorStateType>(BlockIteratorStateType value);
146493
146494template<>
146495const char* EnumUtil::ToChars<BlockState>(BlockState value);
146496
146497template<>
146498const char* EnumUtil::ToChars<BufferedIndexReplay>(BufferedIndexReplay value);
146499
146500template<>
146501const char* EnumUtil::ToChars<CAPIResultSetType>(CAPIResultSetType value);
146502
146503template<>
146504const char* EnumUtil::ToChars<CSVState>(CSVState value);
146505
146506template<>
146507const char* EnumUtil::ToChars<CTEMaterialize>(CTEMaterialize value);
146508
146509template<>
146510const char* EnumUtil::ToChars<CacheValidationMode>(CacheValidationMode value);
146511
146512template<>
146513const char* EnumUtil::ToChars<CachingMode>(CachingMode value);
146514
146515template<>
146516const char* EnumUtil::ToChars<CatalogLookupBehavior>(CatalogLookupBehavior value);
146517
146518template<>
146519const char* EnumUtil::ToChars<CatalogType>(CatalogType value);
146520
146521template<>
146522const char* EnumUtil::ToChars<CheckpointAbort>(CheckpointAbort value);
146523
146524template<>
146525const char* EnumUtil::ToChars<ChunkInfoType>(ChunkInfoType value);
146526
146527template<>
146528const char* EnumUtil::ToChars<ColumnDataAllocatorType>(ColumnDataAllocatorType value);
146529
146530template<>
146531const char* EnumUtil::ToChars<ColumnDataScanProperties>(ColumnDataScanProperties value);
146532
146533template<>
146534const char* EnumUtil::ToChars<ColumnIndexType>(ColumnIndexType value);
146535
146536template<>
146537const char* EnumUtil::ToChars<ColumnSegmentType>(ColumnSegmentType value);
146538
146539template<>
146540const char* EnumUtil::ToChars<CompressedMaterializationDirection>(CompressedMaterializationDirection value);
146541
146542template<>
146543const char* EnumUtil::ToChars<CompressionType>(CompressionType value);
146544
146545template<>
146546const char* EnumUtil::ToChars<CompressionValidity>(CompressionValidity value);
146547
146548template<>
146549const char* EnumUtil::ToChars<ConflictManagerMode>(ConflictManagerMode value);
146550
146551template<>
146552const char* EnumUtil::ToChars<ConstraintType>(ConstraintType value);
146553
146554template<>
146555const char* EnumUtil::ToChars<CoordinateReferenceSystemType>(CoordinateReferenceSystemType value);
146556
146557template<>
146558const char* EnumUtil::ToChars<CopyFunctionReturnType>(CopyFunctionReturnType value);
146559
146560template<>
146561const char* EnumUtil::ToChars<CopyOverwriteMode>(CopyOverwriteMode value);
146562
146563template<>
146564const char* EnumUtil::ToChars<CopyToType>(CopyToType value);
146565
146566template<>
146567const char* EnumUtil::ToChars<DataFileType>(DataFileType value);
146568
146569template<>
146570const char* EnumUtil::ToChars<DateCastResult>(DateCastResult value);
146571
146572template<>
146573const char* EnumUtil::ToChars<DatePartSpecifier>(DatePartSpecifier value);
146574
146575template<>
146576const char* EnumUtil::ToChars<DebugInitialize>(DebugInitialize value);
146577
146578template<>
146579const char* EnumUtil::ToChars<DebugVectorVerification>(DebugVectorVerification value);
146580
146581template<>
146582const char* EnumUtil::ToChars<DecimalBitWidth>(DecimalBitWidth value);
146583
146584template<>
146585const char* EnumUtil::ToChars<DefaultOrderByNullType>(DefaultOrderByNullType value);
146586
146587template<>
146588const char* EnumUtil::ToChars<DependencyEntryType>(DependencyEntryType value);
146589
146590template<>
146591const char* EnumUtil::ToChars<DeprecatedIndexType>(DeprecatedIndexType value);
146592
146593template<>
146594const char* EnumUtil::ToChars<DeprecatedUsingKeySyntax>(DeprecatedUsingKeySyntax value);
146595
146596template<>
146597const char* EnumUtil::ToChars<DestroyBufferUpon>(DestroyBufferUpon value);
146598
146599template<>
146600const char* EnumUtil::ToChars<DistinctType>(DistinctType value);
146601
146602template<>
146603const char* EnumUtil::ToChars<ErrorType>(ErrorType value);
146604
146605template<>
146606const char* EnumUtil::ToChars<ExceptionFormatValueType>(ExceptionFormatValueType value);
146607
146608template<>
146609const char* EnumUtil::ToChars<ExceptionType>(ExceptionType value);
146610
146611template<>
146612const char* EnumUtil::ToChars<ExplainFormat>(ExplainFormat value);
146613
146614template<>
146615const char* EnumUtil::ToChars<ExplainOutputType>(ExplainOutputType value);
146616
146617template<>
146618const char* EnumUtil::ToChars<ExplainType>(ExplainType value);
146619
146620template<>
146621const char* EnumUtil::ToChars<ExponentType>(ExponentType value);
146622
146623template<>
146624const char* EnumUtil::ToChars<ExpressionClass>(ExpressionClass value);
146625
146626template<>
146627const char* EnumUtil::ToChars<ExpressionType>(ExpressionType value);
146628
146629template<>
146630const char* EnumUtil::ToChars<ExtensionABIType>(ExtensionABIType value);
146631
146632template<>
146633const char* EnumUtil::ToChars<ExtensionInstallMode>(ExtensionInstallMode value);
146634
146635template<>
146636const char* EnumUtil::ToChars<ExtensionLoadResult>(ExtensionLoadResult value);
146637
146638template<>
146639const char* EnumUtil::ToChars<ExtensionUpdateResultTag>(ExtensionUpdateResultTag value);
146640
146641template<>
146642const char* EnumUtil::ToChars<ExtraDropInfoType>(ExtraDropInfoType value);
146643
146644template<>
146645const char* EnumUtil::ToChars<ExtraPersistentColumnDataType>(ExtraPersistentColumnDataType value);
146646
146647template<>
146648const char* EnumUtil::ToChars<ExtraTypeInfoType>(ExtraTypeInfoType value);
146649
146650template<>
146651const char* EnumUtil::ToChars<FileBufferType>(FileBufferType value);
146652
146653template<>
146654const char* EnumUtil::ToChars<FileCompressionType>(FileCompressionType value);
146655
146656template<>
146657const char* EnumUtil::ToChars<FileExpandResult>(FileExpandResult value);
146658
146659template<>
146660const char* EnumUtil::ToChars<FileGlobOptions>(FileGlobOptions value);
146661
146662template<>
146663const char* EnumUtil::ToChars<FileLockType>(FileLockType value);
146664
146665template<>
146666const char* EnumUtil::ToChars<FileNameSegmentType>(FileNameSegmentType value);
146667
146668template<>
146669const char* EnumUtil::ToChars<FilterPropagateResult>(FilterPropagateResult value);
146670
146671template<>
146672const char* EnumUtil::ToChars<ForeignKeyType>(ForeignKeyType value);
146673
146674template<>
146675const char* EnumUtil::ToChars<FunctionCollationHandling>(FunctionCollationHandling value);
146676
146677template<>
146678const char* EnumUtil::ToChars<FunctionErrors>(FunctionErrors value);
146679
146680template<>
146681const char* EnumUtil::ToChars<FunctionNullHandling>(FunctionNullHandling value);
146682
146683template<>
146684const char* EnumUtil::ToChars<FunctionStability>(FunctionStability value);
146685
146686template<>
146687const char* EnumUtil::ToChars<GateStatus>(GateStatus value);
146688
146689template<>
146690const char* EnumUtil::ToChars<GeometryStorageType>(GeometryStorageType value);
146691
146692template<>
146693const char* EnumUtil::ToChars<GeometryType>(GeometryType value);
146694
146695template<>
146696const char* EnumUtil::ToChars<HLLStorageType>(HLLStorageType value);
146697
146698template<>
146699const char* EnumUtil::ToChars<HTTPStatusCode>(HTTPStatusCode value);
146700
146701template<>
146702const char* EnumUtil::ToChars<IndexAppendMode>(IndexAppendMode value);
146703
146704template<>
146705const char* EnumUtil::ToChars<IndexBindState>(IndexBindState value);
146706
146707template<>
146708const char* EnumUtil::ToChars<IndexConstraintType>(IndexConstraintType value);
146709
146710template<>
146711const char* EnumUtil::ToChars<InsertColumnOrder>(InsertColumnOrder value);
146712
146713template<>
146714const char* EnumUtil::ToChars<InterruptMode>(InterruptMode value);
146715
146716template<>
146717const char* EnumUtil::ToChars<JoinRefType>(JoinRefType value);
146718
146719template<>
146720const char* EnumUtil::ToChars<JoinType>(JoinType value);
146721
146722template<>
146723const char* EnumUtil::ToChars<KeywordCategory>(KeywordCategory value);
146724
146725template<>
146726const char* EnumUtil::ToChars<LambdaSyntax>(LambdaSyntax value);
146727
146728template<>
146729const char* EnumUtil::ToChars<LambdaSyntaxType>(LambdaSyntaxType value);
146730
146731template<>
146732const char* EnumUtil::ToChars<LimitNodeType>(LimitNodeType value);
146733
146734template<>
146735const char* EnumUtil::ToChars<LoadType>(LoadType value);
146736
146737template<>
146738const char* EnumUtil::ToChars<LogContextScope>(LogContextScope value);
146739
146740template<>
146741const char* EnumUtil::ToChars<LogLevel>(LogLevel value);
146742
146743template<>
146744const char* EnumUtil::ToChars<LogMode>(LogMode value);
146745
146746template<>
146747const char* EnumUtil::ToChars<LoggingTargetTable>(LoggingTargetTable value);
146748
146749template<>
146750const char* EnumUtil::ToChars<LogicalOperatorType>(LogicalOperatorType value);
146751
146752template<>
146753const char* EnumUtil::ToChars<LogicalTypeId>(LogicalTypeId value);
146754
146755template<>
146756const char* EnumUtil::ToChars<LookupResultType>(LookupResultType value);
146757
146758template<>
146759const char* EnumUtil::ToChars<MacroType>(MacroType value);
146760
146761template<>
146762const char* EnumUtil::ToChars<MapInvalidReason>(MapInvalidReason value);
146763
146764template<>
146765const char* EnumUtil::ToChars<MemoryTag>(MemoryTag value);
146766
146767template<>
146768const char* EnumUtil::ToChars<MergeActionCondition>(MergeActionCondition value);
146769
146770template<>
146771const char* EnumUtil::ToChars<MergeActionType>(MergeActionType value);
146772
146773template<>
146774const char* EnumUtil::ToChars<MetaPipelineType>(MetaPipelineType value);
146775
146776template<>
146777const char* EnumUtil::ToChars<MetricGroup>(MetricGroup value);
146778
146779template<>
146780const char* EnumUtil::ToChars<MetricType>(MetricType value);
146781
146782template<>
146783const char* EnumUtil::ToChars<MultiFileColumnMappingMode>(MultiFileColumnMappingMode value);
146784
146785template<>
146786const char* EnumUtil::ToChars<MultiFileFileState>(MultiFileFileState value);
146787
146788template<>
146789const char* EnumUtil::ToChars<NType>(NType value);
146790
146791template<>
146792const char* EnumUtil::ToChars<NewLineIdentifier>(NewLineIdentifier value);
146793
146794template<>
146795const char* EnumUtil::ToChars<OnConflictAction>(OnConflictAction value);
146796
146797template<>
146798const char* EnumUtil::ToChars<OnCreateConflict>(OnCreateConflict value);
146799
146800template<>
146801const char* EnumUtil::ToChars<OnEntryNotFound>(OnEntryNotFound value);
146802
146803template<>
146804const char* EnumUtil::ToChars<OperatorCachingMode>(OperatorCachingMode value);
146805
146806template<>
146807const char* EnumUtil::ToChars<OperatorFinalResultType>(OperatorFinalResultType value);
146808
146809template<>
146810const char* EnumUtil::ToChars<OperatorFinalizeResultType>(OperatorFinalizeResultType value);
146811
146812template<>
146813const char* EnumUtil::ToChars<OperatorResultType>(OperatorResultType value);
146814
146815template<>
146816const char* EnumUtil::ToChars<OptimizerType>(OptimizerType value);
146817
146818template<>
146819const char* EnumUtil::ToChars<OrderByColumnType>(OrderByColumnType value);
146820
146821template<>
146822const char* EnumUtil::ToChars<OrderByNullType>(OrderByNullType value);
146823
146824template<>
146825const char* EnumUtil::ToChars<OrderByStatistics>(OrderByStatistics value);
146826
146827template<>
146828const char* EnumUtil::ToChars<OrderPreservationType>(OrderPreservationType value);
146829
146830template<>
146831const char* EnumUtil::ToChars<OrderType>(OrderType value);
146832
146833template<>
146834const char* EnumUtil::ToChars<OrdinalityType>(OrdinalityType value);
146835
146836template<>
146837const char* EnumUtil::ToChars<OutputStream>(OutputStream value);
146838
146839template<>
146840const char* EnumUtil::ToChars<ParseInfoType>(ParseInfoType value);
146841
146842template<>
146843const char* EnumUtil::ToChars<ParserExtensionResultType>(ParserExtensionResultType value);
146844
146845template<>
146846const char* EnumUtil::ToChars<PartitionedColumnDataType>(PartitionedColumnDataType value);
146847
146848template<>
146849const char* EnumUtil::ToChars<PartitionedTupleDataType>(PartitionedTupleDataType value);
146850
146851template<>
146852const char* EnumUtil::ToChars<PendingExecutionResult>(PendingExecutionResult value);
146853
146854template<>
146855const char* EnumUtil::ToChars<PhysicalOperatorType>(PhysicalOperatorType value);
146856
146857template<>
146858const char* EnumUtil::ToChars<PhysicalTableScanExecutionStrategy>(PhysicalTableScanExecutionStrategy value);
146859
146860template<>
146861const char* EnumUtil::ToChars<PhysicalType>(PhysicalType value);
146862
146863template<>
146864const char* EnumUtil::ToChars<PragmaType>(PragmaType value);
146865
146866template<>
146867const char* EnumUtil::ToChars<PreparedParamType>(PreparedParamType value);
146868
146869template<>
146870const char* EnumUtil::ToChars<PreparedStatementMode>(PreparedStatementMode value);
146871
146872template<>
146873const char* EnumUtil::ToChars<PreserveOrderType>(PreserveOrderType value);
146874
146875template<>
146876const char* EnumUtil::ToChars<ProfilerPrintFormat>(ProfilerPrintFormat value);
146877
146878template<>
146879const char* EnumUtil::ToChars<ProfilingCoverage>(ProfilingCoverage value);
146880
146881template<>
146882const char* EnumUtil::ToChars<ProfilingParameterNames>(ProfilingParameterNames value);
146883
146884template<>
146885const char* EnumUtil::ToChars<PushdownExtractSupport>(PushdownExtractSupport value);
146886
146887template<>
146888const char* EnumUtil::ToChars<QuantileSerializationType>(QuantileSerializationType value);
146889
146890template<>
146891const char* EnumUtil::ToChars<QueryNodeType>(QueryNodeType value);
146892
146893template<>
146894const char* EnumUtil::ToChars<QueryResultMemoryType>(QueryResultMemoryType value);
146895
146896template<>
146897const char* EnumUtil::ToChars<QueryResultOutputType>(QueryResultOutputType value);
146898
146899template<>
146900const char* EnumUtil::ToChars<QueryResultType>(QueryResultType value);
146901
146902template<>
146903const char* EnumUtil::ToChars<RecoveryMode>(RecoveryMode value);
146904
146905template<>
146906const char* EnumUtil::ToChars<RelationType>(RelationType value);
146907
146908template<>
146909const char* EnumUtil::ToChars<RenderMode>(RenderMode value);
146910
146911template<>
146912const char* EnumUtil::ToChars<RequestType>(RequestType value);
146913
146914template<>
146915const char* EnumUtil::ToChars<ResultModifierType>(ResultModifierType value);
146916
146917template<>
146918const char* EnumUtil::ToChars<SampleMethod>(SampleMethod value);
146919
146920template<>
146921const char* EnumUtil::ToChars<SampleType>(SampleType value);
146922
146923template<>
146924const char* EnumUtil::ToChars<SamplingState>(SamplingState value);
146925
146926template<>
146927const char* EnumUtil::ToChars<ScanType>(ScanType value);
146928
146929template<>
146930const char* EnumUtil::ToChars<SecretDisplayType>(SecretDisplayType value);
146931
146932template<>
146933const char* EnumUtil::ToChars<SecretPersistType>(SecretPersistType value);
146934
146935template<>
146936const char* EnumUtil::ToChars<SecretSerializationType>(SecretSerializationType value);
146937
146938template<>
146939const char* EnumUtil::ToChars<SequenceInfo>(SequenceInfo value);
146940
146941template<>
146942const char* EnumUtil::ToChars<SetOperationType>(SetOperationType value);
146943
146944template<>
146945const char* EnumUtil::ToChars<SetScope>(SetScope value);
146946
146947template<>
146948const char* EnumUtil::ToChars<SetType>(SetType value);
146949
146950template<>
146951const char* EnumUtil::ToChars<SettingScope>(SettingScope value);
146952
146953template<>
146954const char* EnumUtil::ToChars<ShowType>(ShowType value);
146955
146956template<>
146957const char* EnumUtil::ToChars<SimplifiedTokenType>(SimplifiedTokenType value);
146958
146959template<>
146960const char* EnumUtil::ToChars<SinkCombineResultType>(SinkCombineResultType value);
146961
146962template<>
146963const char* EnumUtil::ToChars<SinkFinalizeType>(SinkFinalizeType value);
146964
146965template<>
146966const char* EnumUtil::ToChars<SinkNextBatchType>(SinkNextBatchType value);
146967
146968template<>
146969const char* EnumUtil::ToChars<SinkResultType>(SinkResultType value);
146970
146971template<>
146972const char* EnumUtil::ToChars<SortKeyType>(SortKeyType value);
146973
146974template<>
146975const char* EnumUtil::ToChars<SourceResultType>(SourceResultType value);
146976
146977template<>
146978const char* EnumUtil::ToChars<StarExpressionType>(StarExpressionType value);
146979
146980template<>
146981const char* EnumUtil::ToChars<StatementReturnType>(StatementReturnType value);
146982
146983template<>
146984const char* EnumUtil::ToChars<StatementType>(StatementType value);
146985
146986template<>
146987const char* EnumUtil::ToChars<StatisticsType>(StatisticsType value);
146988
146989template<>
146990const char* EnumUtil::ToChars<StatsInfo>(StatsInfo value);
146991
146992template<>
146993const char* EnumUtil::ToChars<StorageBlockPrefetch>(StorageBlockPrefetch value);
146994
146995template<>
146996const char* EnumUtil::ToChars<StorageIndexType>(StorageIndexType value);
146997
146998template<>
146999const char* EnumUtil::ToChars<StrTimeSpecifier>(StrTimeSpecifier value);
147000
147001template<>
147002const char* EnumUtil::ToChars<StreamExecutionResult>(StreamExecutionResult value);
147003
147004template<>
147005const char* EnumUtil::ToChars<SubqueryType>(SubqueryType value);
147006
147007template<>
147008const char* EnumUtil::ToChars<TableColumnType>(TableColumnType value);
147009
147010template<>
147011const char* EnumUtil::ToChars<TableFilterType>(TableFilterType value);
147012
147013template<>
147014const char* EnumUtil::ToChars<TablePartitionInfo>(TablePartitionInfo value);
147015
147016template<>
147017const char* EnumUtil::ToChars<TableReferenceType>(TableReferenceType value);
147018
147019template<>
147020const char* EnumUtil::ToChars<TaskExecutionMode>(TaskExecutionMode value);
147021
147022template<>
147023const char* EnumUtil::ToChars<TaskExecutionResult>(TaskExecutionResult value);
147024
147025template<>
147026const char* EnumUtil::ToChars<TemporaryBufferSize>(TemporaryBufferSize value);
147027
147028template<>
147029const char* EnumUtil::ToChars<TemporaryCompressionLevel>(TemporaryCompressionLevel value);
147030
147031template<>
147032const char* EnumUtil::ToChars<ThreadPinMode>(ThreadPinMode value);
147033
147034template<>
147035const char* EnumUtil::ToChars<TimestampCastResult>(TimestampCastResult value);
147036
147037template<>
147038const char* EnumUtil::ToChars<TransactionInvalidationPolicy>(TransactionInvalidationPolicy value);
147039
147040template<>
147041const char* EnumUtil::ToChars<TransactionModifierType>(TransactionModifierType value);
147042
147043template<>
147044const char* EnumUtil::ToChars<TransactionType>(TransactionType value);
147045
147046template<>
147047const char* EnumUtil::ToChars<TupleDataNestednessType>(TupleDataNestednessType value);
147048
147049template<>
147050const char* EnumUtil::ToChars<TupleDataPinProperties>(TupleDataPinProperties value);
147051
147052template<>
147053const char* EnumUtil::ToChars<TupleDataValidityType>(TupleDataValidityType value);
147054
147055template<>
147056const char* EnumUtil::ToChars<UndoFlags>(UndoFlags value);
147057
147058template<>
147059const char* EnumUtil::ToChars<UnionInvalidReason>(UnionInvalidReason value);
147060
147061template<>
147062const char* EnumUtil::ToChars<VariantChildLookupMode>(VariantChildLookupMode value);
147063
147064template<>
147065const char* EnumUtil::ToChars<VariantLogicalType>(VariantLogicalType value);
147066
147067template<>
147068const char* EnumUtil::ToChars<VariantStatsShreddingState>(VariantStatsShreddingState value);
147069
147070template<>
147071const char* EnumUtil::ToChars<VariantValueType>(VariantValueType value);
147072
147073template<>
147074const char* EnumUtil::ToChars<VectorAuxiliaryDataType>(VectorAuxiliaryDataType value);
147075
147076template<>
147077const char* EnumUtil::ToChars<VectorBufferType>(VectorBufferType value);
147078
147079template<>
147080const char* EnumUtil::ToChars<VectorType>(VectorType value);
147081
147082template<>
147083const char* EnumUtil::ToChars<VerificationType>(VerificationType value);
147084
147085template<>
147086const char* EnumUtil::ToChars<VerifyExistenceType>(VerifyExistenceType value);
147087
147088template<>
147089const char* EnumUtil::ToChars<VertexType>(VertexType value);
147090
147091template<>
147092const char* EnumUtil::ToChars<WALType>(WALType value);
147093
147094template<>
147095const char* EnumUtil::ToChars<WindowAggregationMode>(WindowAggregationMode value);
147096
147097template<>
147098const char* EnumUtil::ToChars<WindowBoundary>(WindowBoundary value);
147099
147100template<>
147101const char* EnumUtil::ToChars<WindowExcludeMode>(WindowExcludeMode value);
147102
147103template<>
147104const char* EnumUtil::ToChars<WindowMergeSortStage>(WindowMergeSortStage value);
147105
147106
147107template<>
147108ARTConflictType EnumUtil::FromString<ARTConflictType>(const char *value);
147109
147110template<>
147111ARTHandlingResult EnumUtil::FromString<ARTHandlingResult>(const char *value);
147112
147113template<>
147114ARTScanHandling EnumUtil::FromString<ARTScanHandling>(const char *value);
147115
147116template<>
147117ARTScanResult EnumUtil::FromString<ARTScanResult>(
const char *value);
147118
147119template<>
147120AccessMode EnumUtil::FromString<AccessMode>(const char *value);
147121
147122template<>
147124
147125template<>
147127
147128template<>
147129AggregateHandling EnumUtil::FromString<AggregateHandling>(const char *value);
147130
147131template<>
147133
147134template<>
147135AggregateType EnumUtil::FromString<AggregateType>(const char *value);
147136
147137template<>
147138AllowParserOverride EnumUtil::FromString<AllowParserOverride>(const char *value);
147139
147140template<>
147141AlterDatabaseType EnumUtil::FromString<AlterDatabaseType>(const char *value);
147142
147143template<>
147144AlterForeignKeyType EnumUtil::FromString<AlterForeignKeyType>(const char *value);
147145
147146template<>
147147AlterScalarFunctionType EnumUtil::FromString<AlterScalarFunctionType>(const char *value);
147148
147149template<>
147150AlterTableFunctionType EnumUtil::FromString<AlterTableFunctionType>(const char *value);
147151
147152template<>
147153AlterTableType EnumUtil::FromString<AlterTableType>(const char *value);
147154
147155template<>
147156AlterType EnumUtil::FromString<AlterType>(const char *value);
147157
147158template<>
147159AlterViewType EnumUtil::FromString<AlterViewType>(const char *value);
147160
147161template<>
147162AppenderType EnumUtil::FromString<AppenderType>(const char *value);
147163
147164template<>
147165ArrowArrayPhysicalType EnumUtil::FromString<ArrowArrayPhysicalType>(const char *value);
147166
147167template<>
147168ArrowDateTimeType EnumUtil::FromString<ArrowDateTimeType>(const char *value);
147169
147170template<>
147172
147173template<>
147174ArrowOffsetSize EnumUtil::FromString<ArrowOffsetSize>(const char *value);
147175
147176template<>
147177ArrowTypeInfoType EnumUtil::FromString<ArrowTypeInfoType>(const char *value);
147178
147179template<>
147180ArrowVariableSizeType EnumUtil::FromString<ArrowVariableSizeType>(const char *value);
147181
147182template<>
147183AsyncResultType EnumUtil::FromString<AsyncResultType>(
const char *value);
147184
147185template<>
147186AsyncResultsExecutionMode EnumUtil::FromString<AsyncResultsExecutionMode>(const char *value);
147187
147188template<>
147190
147191template<>
147192BinderType EnumUtil::FromString<BinderType>(const char *value);
147193
147194template<>
147195BindingMode EnumUtil::FromString<BindingMode>(const char *value);
147196
147197template<>
147198BitpackingMode EnumUtil::FromString<BitpackingMode>(const char *value);
147199
147200template<>
147202
147203template<>
147204BlockState EnumUtil::FromString<BlockState>(const char *value);
147205
147206template<>
147207BufferedIndexReplay EnumUtil::FromString<BufferedIndexReplay>(const char *value);
147208
147209template<>
147210CAPIResultSetType EnumUtil::FromString<CAPIResultSetType>(const char *value);
147211
147212template<>
147213CSVState EnumUtil::FromString<CSVState>(
const char *value);
147214
147215template<>
147216CTEMaterialize EnumUtil::FromString<CTEMaterialize>(const char *value);
147217
147218template<>
147219CacheValidationMode EnumUtil::FromString<CacheValidationMode>(const char *value);
147220
147221template<>
147222CachingMode EnumUtil::FromString<CachingMode>(
const char *value);
147223
147224template<>
147226
147227template<>
147228CatalogType EnumUtil::FromString<CatalogType>(const char *value);
147229
147230template<>
147231CheckpointAbort EnumUtil::FromString<CheckpointAbort>(const char *value);
147232
147233template<>
147234ChunkInfoType EnumUtil::FromString<ChunkInfoType>(const char *value);
147235
147236template<>
147238
147239template<>
147241
147242template<>
147243ColumnIndexType EnumUtil::FromString<ColumnIndexType>(
const char *value);
147244
147245template<>
147246ColumnSegmentType EnumUtil::FromString<ColumnSegmentType>(const char *value);
147247
147248template<>
147250
147251template<>
147252CompressionType EnumUtil::FromString<CompressionType>(const char *value);
147253
147254template<>
147255CompressionValidity EnumUtil::FromString<CompressionValidity>(const char *value);
147256
147257template<>
147258ConflictManagerMode EnumUtil::FromString<ConflictManagerMode>(const char *value);
147259
147260template<>
147261ConstraintType EnumUtil::FromString<ConstraintType>(const char *value);
147262
147263template<>
147265
147266template<>
147267CopyFunctionReturnType EnumUtil::FromString<CopyFunctionReturnType>(const char *value);
147268
147269template<>
147270CopyOverwriteMode EnumUtil::FromString<CopyOverwriteMode>(const char *value);
147271
147272template<>
147273CopyToType EnumUtil::FromString<CopyToType>(const char *value);
147274
147275template<>
147276DataFileType EnumUtil::FromString<DataFileType>(const char *value);
147277
147278template<>
147279DateCastResult EnumUtil::FromString<DateCastResult>(const char *value);
147280
147281template<>
147282DatePartSpecifier EnumUtil::FromString<DatePartSpecifier>(const char *value);
147283
147284template<>
147285DebugInitialize EnumUtil::FromString<DebugInitialize>(const char *value);
147286
147287template<>
147288DebugVectorVerification EnumUtil::FromString<DebugVectorVerification>(const char *value);
147289
147290template<>
147291DecimalBitWidth EnumUtil::FromString<DecimalBitWidth>(const char *value);
147292
147293template<>
147294DefaultOrderByNullType EnumUtil::FromString<DefaultOrderByNullType>(const char *value);
147295
147296template<>
147298
147299template<>
147300DeprecatedIndexType EnumUtil::FromString<DeprecatedIndexType>(const char *value);
147301
147302template<>
147303DeprecatedUsingKeySyntax EnumUtil::FromString<DeprecatedUsingKeySyntax>(const char *value);
147304
147305template<>
147307
147308template<>
147309DistinctType EnumUtil::FromString<DistinctType>(const char *value);
147310
147311template<>
147312ErrorType EnumUtil::FromString<ErrorType>(const char *value);
147313
147314template<>
147315ExceptionFormatValueType EnumUtil::FromString<ExceptionFormatValueType>(const char *value);
147316
147317template<>
147318ExceptionType EnumUtil::FromString<ExceptionType>(const char *value);
147319
147320template<>
147321ExplainFormat EnumUtil::FromString<ExplainFormat>(const char *value);
147322
147323template<>
147324ExplainOutputType EnumUtil::FromString<ExplainOutputType>(const char *value);
147325
147326template<>
147327ExplainType EnumUtil::FromString<ExplainType>(const char *value);
147328
147329template<>
147330ExponentType EnumUtil::FromString<ExponentType>(const char *value);
147331
147332template<>
147333ExpressionClass EnumUtil::FromString<ExpressionClass>(const char *value);
147334
147335template<>
147336ExpressionType EnumUtil::FromString<ExpressionType>(const char *value);
147337
147338template<>
147339ExtensionABIType EnumUtil::FromString<ExtensionABIType>(
const char *value);
147340
147341template<>
147343
147344template<>
147345ExtensionLoadResult EnumUtil::FromString<ExtensionLoadResult>(const char *value);
147346
147347template<>
147348ExtensionUpdateResultTag EnumUtil::FromString<ExtensionUpdateResultTag>(const char *value);
147349
147350template<>
147351ExtraDropInfoType EnumUtil::FromString<ExtraDropInfoType>(const char *value);
147352
147353template<>
147354ExtraPersistentColumnDataType EnumUtil::FromString<ExtraPersistentColumnDataType>(const char *value);
147355
147356template<>
147358
147359template<>
147360FileBufferType EnumUtil::FromString<FileBufferType>(const char *value);
147361
147362template<>
147363FileCompressionType EnumUtil::FromString<FileCompressionType>(const char *value);
147364
147365template<>
147366FileExpandResult EnumUtil::FromString<FileExpandResult>(const char *value);
147367
147368template<>
147369FileGlobOptions EnumUtil::FromString<FileGlobOptions>(const char *value);
147370
147371template<>
147372FileLockType EnumUtil::FromString<FileLockType>(const char *value);
147373
147374template<>
147375FileNameSegmentType EnumUtil::FromString<FileNameSegmentType>(const char *value);
147376
147377template<>
147378FilterPropagateResult EnumUtil::FromString<FilterPropagateResult>(const char *value);
147379
147380template<>
147381ForeignKeyType EnumUtil::FromString<ForeignKeyType>(const char *value);
147382
147383template<>
147385
147386template<>
147387FunctionErrors EnumUtil::FromString<FunctionErrors>(
const char *value);
147388
147389template<>
147391
147392template<>
147394
147395template<>
147396GateStatus EnumUtil::FromString<GateStatus>(const char *value);
147397
147398template<>
147399GeometryStorageType EnumUtil::FromString<GeometryStorageType>(const char *value);
147400
147401template<>
147402GeometryType EnumUtil::FromString<GeometryType>(const char *value);
147403
147404template<>
147405HLLStorageType EnumUtil::FromString<HLLStorageType>(
const char *value);
147406
147407template<>
147408HTTPStatusCode EnumUtil::FromString<HTTPStatusCode>(const char *value);
147409
147410template<>
147411IndexAppendMode EnumUtil::FromString<IndexAppendMode>(const char *value);
147412
147413template<>
147414IndexBindState EnumUtil::FromString<IndexBindState>(
const char *value);
147415
147416template<>
147417IndexConstraintType EnumUtil::FromString<IndexConstraintType>(const char *value);
147418
147419template<>
147420InsertColumnOrder EnumUtil::FromString<InsertColumnOrder>(const char *value);
147421
147422template<>
147423InterruptMode EnumUtil::FromString<InterruptMode>(
const char *value);
147424
147425template<>
147426JoinRefType EnumUtil::FromString<JoinRefType>(const char *value);
147427
147428template<>
147429JoinType EnumUtil::FromString<JoinType>(const char *value);
147430
147431template<>
147432KeywordCategory EnumUtil::FromString<KeywordCategory>(const char *value);
147433
147434template<>
147435LambdaSyntax EnumUtil::FromString<LambdaSyntax>(const char *value);
147436
147437template<>
147438LambdaSyntaxType EnumUtil::FromString<LambdaSyntaxType>(const char *value);
147439
147440template<>
147441LimitNodeType EnumUtil::FromString<LimitNodeType>(const char *value);
147442
147443template<>
147444LoadType EnumUtil::FromString<LoadType>(const char *value);
147445
147446template<>
147447LogContextScope EnumUtil::FromString<LogContextScope>(const char *value);
147448
147449template<>
147450LogLevel EnumUtil::FromString<LogLevel>(
const char *value);
147451
147452template<>
147453LogMode EnumUtil::FromString<LogMode>(const char *value);
147454
147455template<>
147457
147458template<>
147459LogicalOperatorType EnumUtil::FromString<LogicalOperatorType>(const char *value);
147460
147461template<>
147462LogicalTypeId EnumUtil::FromString<LogicalTypeId>(
const char *value);
147463
147464template<>
147465LookupResultType EnumUtil::FromString<LookupResultType>(const char *value);
147466
147467template<>
147468MacroType EnumUtil::FromString<MacroType>(const char *value);
147469
147470template<>
147471MapInvalidReason EnumUtil::FromString<MapInvalidReason>(const char *value);
147472
147473template<>
147474MemoryTag EnumUtil::FromString<MemoryTag>(const char *value);
147475
147476template<>
147477MergeActionCondition EnumUtil::FromString<MergeActionCondition>(const char *value);
147478
147479template<>
147480MergeActionType EnumUtil::FromString<MergeActionType>(const char *value);
147481
147482template<>
147483MetaPipelineType EnumUtil::FromString<MetaPipelineType>(
const char *value);
147484
147485template<>
147486MetricGroup EnumUtil::FromString<MetricGroup>(const char *value);
147487
147488template<>
147489MetricType EnumUtil::FromString<MetricType>(const char *value);
147490
147491template<>
147492MultiFileColumnMappingMode EnumUtil::FromString<MultiFileColumnMappingMode>(const char *value);
147493
147494template<>
147495MultiFileFileState EnumUtil::FromString<MultiFileFileState>(const char *value);
147496
147497template<>
147498NType EnumUtil::FromString<NType>(const char *value);
147499
147500template<>
147501NewLineIdentifier EnumUtil::FromString<NewLineIdentifier>(const char *value);
147502
147503template<>
147504OnConflictAction EnumUtil::FromString<OnConflictAction>(const char *value);
147505
147506template<>
147507OnCreateConflict EnumUtil::FromString<OnCreateConflict>(const char *value);
147508
147509template<>
147510OnEntryNotFound EnumUtil::FromString<OnEntryNotFound>(const char *value);
147511
147512template<>
147513OperatorCachingMode EnumUtil::FromString<OperatorCachingMode>(const char *value);
147514
147515template<>
147517
147518template<>
147520
147521template<>
147523
147524template<>
147525OptimizerType EnumUtil::FromString<OptimizerType>(const char *value);
147526
147527template<>
147528OrderByColumnType EnumUtil::FromString<OrderByColumnType>(const char *value);
147529
147530template<>
147531OrderByNullType EnumUtil::FromString<OrderByNullType>(const char *value);
147532
147533template<>
147534OrderByStatistics EnumUtil::FromString<OrderByStatistics>(const char *value);
147535
147536template<>
147537OrderPreservationType EnumUtil::FromString<OrderPreservationType>(const char *value);
147538
147539template<>
147540OrderType EnumUtil::FromString<OrderType>(const char *value);
147541
147542template<>
147543OrdinalityType EnumUtil::FromString<OrdinalityType>(const char *value);
147544
147545template<>
147546OutputStream EnumUtil::FromString<OutputStream>(const char *value);
147547
147548template<>
147549ParseInfoType EnumUtil::FromString<ParseInfoType>(const char *value);
147550
147551template<>
147552ParserExtensionResultType EnumUtil::FromString<ParserExtensionResultType>(const char *value);
147553
147554template<>
147556
147557template<>
147559
147560template<>
147561PendingExecutionResult EnumUtil::FromString<PendingExecutionResult>(const char *value);
147562
147563template<>
147564PhysicalOperatorType EnumUtil::FromString<PhysicalOperatorType>(const char *value);
147565
147566template<>
147567PhysicalTableScanExecutionStrategy EnumUtil::FromString<PhysicalTableScanExecutionStrategy>(const char *value);
147568
147569template<>
147570PhysicalType EnumUtil::FromString<PhysicalType>(
const char *value);
147571
147572template<>
147573PragmaType EnumUtil::FromString<PragmaType>(const char *value);
147574
147575template<>
147576PreparedParamType EnumUtil::FromString<PreparedParamType>(const char *value);
147577
147578template<>
147579PreparedStatementMode EnumUtil::FromString<PreparedStatementMode>(const char *value);
147580
147581template<>
147582PreserveOrderType EnumUtil::FromString<PreserveOrderType>(const char *value);
147583
147584template<>
147585ProfilerPrintFormat EnumUtil::FromString<ProfilerPrintFormat>(const char *value);
147586
147587template<>
147588ProfilingCoverage EnumUtil::FromString<ProfilingCoverage>(const char *value);
147589
147590template<>
147591ProfilingParameterNames EnumUtil::FromString<ProfilingParameterNames>(const char *value);
147592
147593template<>
147594PushdownExtractSupport EnumUtil::FromString<PushdownExtractSupport>(const char *value);
147595
147596template<>
147597QuantileSerializationType EnumUtil::FromString<QuantileSerializationType>(const char *value);
147598
147599template<>
147600QueryNodeType EnumUtil::FromString<QueryNodeType>(const char *value);
147601
147602template<>
147603QueryResultMemoryType EnumUtil::FromString<QueryResultMemoryType>(const char *value);
147604
147605template<>
147606QueryResultOutputType EnumUtil::FromString<QueryResultOutputType>(const char *value);
147607
147608template<>
147609QueryResultType EnumUtil::FromString<QueryResultType>(const char *value);
147610
147611template<>
147612RecoveryMode EnumUtil::FromString<RecoveryMode>(
const char *value);
147613
147614template<>
147615RelationType EnumUtil::FromString<RelationType>(const char *value);
147616
147617template<>
147618RenderMode EnumUtil::FromString<RenderMode>(const char *value);
147619
147620template<>
147621RequestType EnumUtil::FromString<RequestType>(const char *value);
147622
147623template<>
147624ResultModifierType EnumUtil::FromString<ResultModifierType>(const char *value);
147625
147626template<>
147627SampleMethod EnumUtil::FromString<SampleMethod>(const char *value);
147628
147629template<>
147630SampleType EnumUtil::FromString<SampleType>(const char *value);
147631
147632template<>
147633SamplingState EnumUtil::FromString<SamplingState>(const char *value);
147634
147635template<>
147636ScanType EnumUtil::FromString<ScanType>(const char *value);
147637
147638template<>
147640
147641template<>
147643
147644template<>
147646
147647template<>
147648SequenceInfo EnumUtil::FromString<SequenceInfo>(const char *value);
147649
147650template<>
147651SetOperationType EnumUtil::FromString<SetOperationType>(const char *value);
147652
147653template<>
147654SetScope EnumUtil::FromString<SetScope>(const char *value);
147655
147656template<>
147657SetType EnumUtil::FromString<SetType>(const char *value);
147658
147659template<>
147660SettingScope EnumUtil::FromString<SettingScope>(
const char *value);
147661
147662template<>
147663ShowType EnumUtil::FromString<ShowType>(const char *value);
147664
147665template<>
147667
147668template<>
147669SinkCombineResultType EnumUtil::FromString<SinkCombineResultType>(const char *value);
147670
147671template<>
147672SinkFinalizeType EnumUtil::FromString<SinkFinalizeType>(
const char *value);
147673
147674template<>
147676
147677template<>
147678SinkResultType EnumUtil::FromString<SinkResultType>(
const char *value);
147679
147680template<>
147681SortKeyType EnumUtil::FromString<SortKeyType>(
const char *value);
147682
147683template<>
147684SourceResultType EnumUtil::FromString<SourceResultType>(
const char *value);
147685
147686template<>
147687StarExpressionType EnumUtil::FromString<StarExpressionType>(const char *value);
147688
147689template<>
147690StatementReturnType EnumUtil::FromString<StatementReturnType>(const char *value);
147691
147692template<>
147693StatementType EnumUtil::FromString<StatementType>(const char *value);
147694
147695template<>
147696StatisticsType EnumUtil::FromString<StatisticsType>(const char *value);
147697
147698template<>
147699StatsInfo EnumUtil::FromString<StatsInfo>(const char *value);
147700
147701template<>
147702StorageBlockPrefetch EnumUtil::FromString<StorageBlockPrefetch>(const char *value);
147703
147704template<>
147705StorageIndexType EnumUtil::FromString<StorageIndexType>(const char *value);
147706
147707template<>
147708StrTimeSpecifier EnumUtil::FromString<StrTimeSpecifier>(const char *value);
147709
147710template<>
147711StreamExecutionResult EnumUtil::FromString<StreamExecutionResult>(const char *value);
147712
147713template<>
147714SubqueryType EnumUtil::FromString<SubqueryType>(const char *value);
147715
147716template<>
147717TableColumnType EnumUtil::FromString<TableColumnType>(const char *value);
147718
147719template<>
147720TableFilterType EnumUtil::FromString<TableFilterType>(const char *value);
147721
147722template<>
147724
147725template<>
147726TableReferenceType EnumUtil::FromString<TableReferenceType>(const char *value);
147727
147728template<>
147729TaskExecutionMode EnumUtil::FromString<TaskExecutionMode>(const char *value);
147730
147731template<>
147732TaskExecutionResult EnumUtil::FromString<TaskExecutionResult>(const char *value);
147733
147734template<>
147735TemporaryBufferSize EnumUtil::FromString<TemporaryBufferSize>(const char *value);
147736
147737template<>
147738TemporaryCompressionLevel EnumUtil::FromString<TemporaryCompressionLevel>(const char *value);
147739
147740template<>
147741ThreadPinMode EnumUtil::FromString<ThreadPinMode>(const char *value);
147742
147743template<>
147744TimestampCastResult EnumUtil::FromString<TimestampCastResult>(const char *value);
147745
147746template<>
147747TransactionInvalidationPolicy EnumUtil::FromString<TransactionInvalidationPolicy>(const char *value);
147748
147749template<>
147750TransactionModifierType EnumUtil::FromString<TransactionModifierType>(const char *value);
147751
147752template<>
147753TransactionType EnumUtil::FromString<TransactionType>(const char *value);
147754
147755template<>
147756TupleDataNestednessType EnumUtil::FromString<TupleDataNestednessType>(const char *value);
147757
147758template<>
147760
147761template<>
147762TupleDataValidityType EnumUtil::FromString<TupleDataValidityType>(const char *value);
147763
147764template<>
147765UndoFlags EnumUtil::FromString<UndoFlags>(const char *value);
147766
147767template<>
147768UnionInvalidReason EnumUtil::FromString<UnionInvalidReason>(const char *value);
147769
147770template<>
147771VariantChildLookupMode EnumUtil::FromString<VariantChildLookupMode>(const char *value);
147772
147773template<>
147774VariantLogicalType EnumUtil::FromString<VariantLogicalType>(const char *value);
147775
147776template<>
147778
147779template<>
147780VariantValueType EnumUtil::FromString<VariantValueType>(const char *value);
147781
147782template<>
147783VectorAuxiliaryDataType EnumUtil::FromString<VectorAuxiliaryDataType>(const char *value);
147784
147785template<>
147786VectorBufferType EnumUtil::FromString<VectorBufferType>(const char *value);
147787
147788template<>
147789VectorType EnumUtil::FromString<VectorType>(const char *value);
147790
147791template<>
147792VerificationType EnumUtil::FromString<VerificationType>(const char *value);
147793
147794template<>
147795VerifyExistenceType EnumUtil::FromString<VerifyExistenceType>(const char *value);
147796
147797template<>
147798VertexType EnumUtil::FromString<VertexType>(const char *value);
147799
147800template<>
147801WALType EnumUtil::FromString<WALType>(const char *value);
147802
147803template<>
147805
147806template<>
147807WindowBoundary EnumUtil::FromString<WindowBoundary>(const char *value);
147808
147809template<>
147811
147812template<>
147813WindowMergeSortStage EnumUtil::FromString<WindowMergeSortStage>(const char *value);
147814
147815
147816}
147817
147818
147819
147820
147821
147822namespace duckdb {
147823
147824class InterruptState;
147825class TaskExecutor;
147826class Executor;
147827
147828enum class AsyncResultsExecutionMode :
uint8_t {
147829 SYNCHRONOUS,
147830 TASK_EXECUTOR
147831};
147832
147833class AsyncTask {
147834public:
147835 virtual ~AsyncTask() {};
147836 virtual void Execute() = 0;
147837};
147838
147839class AsyncResult {
147840 explicit AsyncResult(AsyncResultType t);
147841
147842public:
147843 AsyncResult() = default;
147844 AsyncResult(AsyncResult &&) = default;
147845 AsyncResult(SourceResultType t);
147846 explicit AsyncResult(vector<unique_ptr<AsyncTask>> &&task);
147847 AsyncResult &
operator=(SourceResultType t);
147848 AsyncResult &
operator=(AsyncResultType t);
147849 AsyncResult &
operator=(AsyncResult &&) noexcept;
147850
147851
147852
147853 void ScheduleTasks(InterruptState &interrupt_state, Executor &executor);
147854
147855
147856
147857 void ExecuteTasksSynchronously();
147858
147859 static AsyncResultType GetAsyncResultType(SourceResultType s);
147860
147861
147862 bool HasTasks() const;
147863 AsyncResultType GetResultType() const;
147864
147865 vector<unique_ptr<AsyncTask>> &&ExtractAsyncTasks();
147866
147867#ifdef DUCKDB_DEBUG_ASYNC_SINK_SOURCE
147868 static vector<unique_ptr<AsyncTask>> GenerateTestTasks();
147869#endif
147870
147871 static AsyncResultsExecutionMode
147872 ConvertToAsyncResultExecutionMode(const PhysicalTableScanExecutionStrategy &execution_mode);
147873
147874private:
147876 vector<unique_ptr<AsyncTask>> async_tasks {};
147877};
147878}
147879
147880
147881
147882
147883
147884
147885
147886
147887
147888
147889
147890
147891
147892
147893
147894
147895namespace duckdb {
147896
147897class BinderException : public Exception {
147898public:
147899 DUCKDB_API explicit BinderException(const string &msg);
147900
147901 DUCKDB_API explicit BinderException(const unordered_map<string, string> &extra_info, const string &msg);
147902
147903 template <typename... ARGS>
147904 explicit BinderException(const string &msg, ARGS &&...params)
147905 : BinderException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
147906 }
147907
147908 template <typename... ARGS>
147909 explicit BinderException(const TableRef &ref, const string &msg, ARGS &&...params)
147910 : BinderException(Exception::InitializeExtraInfo(ref), ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
147911 }
147912 template <typename... ARGS>
147913 explicit BinderException(const ParsedExpression &expr, const string &msg, ARGS &&...params)
147914 : BinderException(Exception::InitializeExtraInfo(expr), ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
147915 }
147916
147917 template <typename... ARGS>
147918 explicit BinderException(const Expression &expr, const string &msg, ARGS &&...params)
147919 : BinderException(Exception::InitializeExtraInfo(expr), ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
147920 }
147921
147922 template <typename... ARGS>
147923 explicit BinderException(QueryErrorContext error_context, const string &msg, ARGS &&...params)
147924 : BinderException(Exception::InitializeExtraInfo(error_context),
147925 ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
147926 }
147927
147928 template <typename... ARGS>
147929 explicit BinderException(optional_idx error_location, const string &msg, ARGS &&...params)
147930 : BinderException(Exception::InitializeExtraInfo(error_location),
147931 ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
147932 }
147933
147934 static BinderException ColumnNotFound(const string &name, const vector<string> &similar_bindings,
147935 QueryErrorContext context = QueryErrorContext());
147936 static BinderException NoMatchingFunction(const string &catalog_name, const string &schema_name, const string &name,
147937 const vector<LogicalType> &arguments, const vector<string> &candidates);
147938 static BinderException Unsupported(ParsedExpression &expr, const string &message);
147939};
147940
147941}
147942
147943
147944
147945namespace duckdb {
147946
147947class BaseStatistics;
147948class LogicalDependencyList;
147949class LogicalGet;
147950class TableFunction;
147951class TableFilterSet;
147952class TableFunctionRef;
147953class TableCatalogEntry;
147954class SampleOptions;
147955struct MultiFileReader;
147956struct OperatorPartitionData;
147957struct OperatorPartitionInfo;
147958enum class OrderByColumnType :
uint8_t;
147959enum class OrderType :
uint8_t;
147960enum class OrderByStatistics :
uint8_t;
147961
147962struct TableFunctionInfo {
147963 DUCKDB_API virtual ~TableFunctionInfo();
147964
147965 template <class TARGET>
147966 TARGET &Cast() {
147967 DynamicCastCheck<TARGET>(this);
147968 return reinterpret_cast<TARGET &>(*this);
147969 }
147970 template <class TARGET>
147971 const TARGET &Cast() const {
147972 DynamicCastCheck<TARGET>(this);
147973 return reinterpret_cast<const TARGET &>(*this);
147974 }
147975};
147976
147977struct GlobalTableFunctionState {
147978public:
147979
147980 constexpr static const int64_t MAX_THREADS = 999999999;
147981
147982public:
147983 DUCKDB_API virtual ~GlobalTableFunctionState();
147984
147985 virtual idx_t MaxThreads()
const {
147986 return 1;
147987 }
147988
147989 template <class TARGET>
147990 TARGET &Cast() {
147991 DynamicCastCheck<TARGET>(this);
147992 return reinterpret_cast<TARGET &>(*this);
147993 }
147994 template <class TARGET>
147995 const TARGET &Cast() const {
147996 DynamicCastCheck<TARGET>(this);
147997 return reinterpret_cast<const TARGET &>(*this);
147998 }
147999};
148000
148001struct LocalTableFunctionState {
148002 DUCKDB_API virtual ~LocalTableFunctionState();
148003
148004 template <class TARGET>
148005 TARGET &Cast() {
148006 DynamicCastCheck<TARGET>(this);
148007 return reinterpret_cast<TARGET &>(*this);
148008 }
148009 template <class TARGET>
148010 const TARGET &Cast() const {
148011 DynamicCastCheck<TARGET>(this);
148012 return reinterpret_cast<const TARGET &>(*this);
148013 }
148014};
148015
148016struct TableFunctionBindInput {
148017 TableFunctionBindInput(vector<Value> &inputs, named_parameter_map_t &named_parameters,
148018 vector<LogicalType> &input_table_types, vector<string> &input_table_names,
148019 optional_ptr<TableFunctionInfo> info, optional_ptr<Binder> binder,
148020 TableFunction &table_function, const TableFunctionRef &ref)
148021 : inputs(inputs), named_parameters(named_parameters), input_table_types(input_table_types),
148022 input_table_names(input_table_names), info(info), binder(binder), table_function(table_function), ref(ref) {
148023 }
148024
148025 vector<Value> &inputs;
148026 named_parameter_map_t &named_parameters;
148027 vector<LogicalType> &input_table_types;
148028 vector<string> &input_table_names;
148029 optional_ptr<TableFunctionInfo> info;
148030 optional_ptr<Binder> binder;
148031 TableFunction &table_function;
148032 const TableFunctionRef &ref;
148033};
148034
148035struct TableFunctionInitInput {
148036 TableFunctionInitInput(optional_ptr<const FunctionData> bind_data_p, vector<column_t> column_ids_p,
148037 const vector<idx_t> &projection_ids_p, optional_ptr<TableFilterSet> filters_p,
148038 optional_ptr<SampleOptions> sample_options_p = nullptr,
148039 optional_ptr<const PhysicalOperator> op_p = nullptr)
148040 : bind_data(bind_data_p), column_ids(std::move(column_ids_p)), projection_ids(projection_ids_p),
148041 filters(filters_p), sample_options(sample_options_p), op(op_p) {
148042 for (auto &col_id : column_ids) {
148043 column_indexes.emplace_back(col_id);
148044 }
148045 }
148046
148047 TableFunctionInitInput(optional_ptr<const FunctionData> bind_data_p, vector<ColumnIndex> column_indexes_p,
148048 const vector<idx_t> &projection_ids_p, optional_ptr<TableFilterSet> filters_p,
148049 optional_ptr<SampleOptions> sample_options_p = nullptr,
148050 optional_ptr<const PhysicalOperator> op_p = nullptr)
148051 : bind_data(bind_data_p), column_indexes(std::move(column_indexes_p)), projection_ids(projection_ids_p),
148052 filters(filters_p), sample_options(sample_options_p), op(op_p) {
148053 for (auto &col_id : column_indexes) {
148054 column_ids.emplace_back(col_id.GetPrimaryIndex());
148055 }
148056 }
148057
148058 optional_ptr<const FunctionData> bind_data;
148059 vector<column_t> column_ids;
148060 vector<ColumnIndex> column_indexes;
148061 const vector<idx_t> projection_ids;
148062 optional_ptr<TableFilterSet> filters;
148063 optional_ptr<SampleOptions> sample_options;
148064 optional_ptr<const PhysicalOperator> op;
148065
148066 bool CanRemoveFilterColumns() const {
148067 if (projection_ids.empty()) {
148068
148069 return false;
148070 }
148071 if (projection_ids.size() == column_ids.size()) {
148072
148073 return false;
148074 }
148075
148076 return true;
148077 }
148078};
148079
148080struct TableFunctionInput {
148081public:
148082 TableFunctionInput(optional_ptr<const FunctionData> bind_data_p,
148083 optional_ptr<LocalTableFunctionState> local_state_p,
148084 optional_ptr<GlobalTableFunctionState> global_state_p)
148085 : bind_data(bind_data_p), local_state(local_state_p), global_state(global_state_p), async_result() {
148086 }
148087
148088public:
148089 optional_ptr<const FunctionData> bind_data;
148090 optional_ptr<LocalTableFunctionState> local_state;
148091 optional_ptr<GlobalTableFunctionState> global_state;
148092 AsyncResult async_result {};
148093 AsyncResultsExecutionMode results_execution_mode {AsyncResultsExecutionMode::SYNCHRONOUS};
148094};
148095
148096struct TableFunctionPartitionInput {
148097 TableFunctionPartitionInput(optional_ptr<const FunctionData> bind_data_p, const vector<column_t> &partition_ids)
148098 : bind_data(bind_data_p), partition_ids(partition_ids) {
148099 }
148100
148101 optional_ptr<const FunctionData> bind_data;
148102 const vector<column_t> &partition_ids;
148103};
148104
148105struct TableFunctionToStringInput {
148106 TableFunctionToStringInput(const TableFunction &table_function_p, optional_ptr<const FunctionData> bind_data_p)
148107 : table_function(table_function_p), bind_data(bind_data_p) {
148108 }
148109 const TableFunction &table_function;
148110 optional_ptr<const FunctionData> bind_data;
148111};
148112
148113struct TableFunctionDynamicToStringInput {
148114 TableFunctionDynamicToStringInput(const TableFunction &table_function_p,
148115 optional_ptr<const FunctionData> bind_data_p,
148116 optional_ptr<LocalTableFunctionState> local_state_p,
148117 optional_ptr<GlobalTableFunctionState> global_state_p)
148118 : table_function(table_function_p), bind_data(bind_data_p), local_state(local_state_p),
148119 global_state(global_state_p) {
148120 }
148121 const TableFunction &table_function;
148122 optional_ptr<const FunctionData> bind_data;
148123 optional_ptr<LocalTableFunctionState> local_state;
148124 optional_ptr<GlobalTableFunctionState> global_state;
148125};
148126
148127struct TableFunctionGetPartitionInput {
148128public:
148129 TableFunctionGetPartitionInput(optional_ptr<const FunctionData> bind_data_p,
148130 optional_ptr<LocalTableFunctionState> local_state_p,
148131 optional_ptr<GlobalTableFunctionState> global_state_p,
148132 const OperatorPartitionInfo &partition_info_p)
148133 : bind_data(bind_data_p), local_state(local_state_p), global_state(global_state_p),
148134 partition_info(partition_info_p) {
148135 }
148136
148137public:
148138 optional_ptr<const FunctionData> bind_data;
148139 optional_ptr<LocalTableFunctionState> local_state;
148140 optional_ptr<GlobalTableFunctionState> global_state;
148141 const OperatorPartitionInfo &partition_info;
148142};
148143
148144struct TableFunctionGetStatisticsInput {
148145public:
148146 TableFunctionGetStatisticsInput(const FunctionData *bind_data, const ColumnIndex &column_index)
148147 : bind_data(bind_data), column_index(column_index) {
148148 }
148149
148150public:
148151 optional_ptr<const FunctionData> bind_data;
148152 ColumnIndex column_index;
148153};
148154
148155struct GetPartitionStatsInput {
148156 GetPartitionStatsInput(const TableFunction &table_function_p, optional_ptr<const FunctionData> bind_data_p)
148157 : table_function(table_function_p), bind_data(bind_data_p) {
148158 }
148159
148160 const TableFunction &table_function;
148161 optional_ptr<const FunctionData> bind_data;
148162};
148163
148164enum class ScanType :
uint8_t { TABLE, PARQUET, EXTERNAL };
148165
148166struct BindInfo {
148167public:
148168 explicit BindInfo(ScanType type_p) : type(type_p) {};
148169 explicit BindInfo(TableCatalogEntry &table) : type(ScanType::TABLE), table(&table) {};
148170
148171 unordered_map<string, Value> options;
148172 ScanType type;
148173 optional_ptr<TableCatalogEntry> table;
148174
148175 void InsertOption(const string &name, Value value) {
148176 if (options.find(name) != options.end()) {
148177 throw InternalException("This option already exists");
148178 }
148179 options.emplace(name, std::move(value));
148180 }
148181 template <class T>
148182 T GetOption(const string &name) {
148183 if (options.find(name) == options.end()) {
148184 throw InternalException("This option does not exist");
148185 }
148186 return options[name].GetValue<T>();
148187 }
148188 template <class T>
148189 vector<T> GetOptionList(const string &name) {
148190 if (options.find(name) == options.end()) {
148191 throw InternalException("This option does not exist");
148192 }
148193 auto option = options[name];
148194 if (option.type().id() != LogicalTypeId::LIST) {
148195 throw InternalException("This option is not a list");
148196 }
148197 vector<T> result;
148198 auto list_children = ListValue::GetChildren(option);
148199 for (auto &child : list_children) {
148200 result.emplace_back(child.GetValue<T>());
148201 }
148202 return result;
148203 }
148204};
148205
148206typedef unique_ptr<FunctionData> (*table_function_bind_t)(ClientContext &context, TableFunctionBindInput &input,
148207 vector<LogicalType> &return_types, vector<string> &names);
148208typedef unique_ptr<TableRef> (*table_function_bind_replace_t)(ClientContext &context, TableFunctionBindInput &input);
148209typedef unique_ptr<LogicalOperator> (*table_function_bind_operator_t)(ClientContext &context,
148210 TableFunctionBindInput &input,
idx_t bind_index,
148211 vector<string> &return_names);
148212typedef unique_ptr<GlobalTableFunctionState> (*table_function_init_global_t)(ClientContext &context,
148213 TableFunctionInitInput &input);
148214typedef unique_ptr<LocalTableFunctionState> (*table_function_init_local_t)(ExecutionContext &context,
148215 TableFunctionInitInput &input,
148216 GlobalTableFunctionState *global_state);
148217typedef unique_ptr<BaseStatistics> (*table_statistics_t)(ClientContext &context, const FunctionData *bind_data,
148219typedef unique_ptr<BaseStatistics> (*table_statistics_extended_t)(ClientContext &context,
148220 TableFunctionGetStatisticsInput &input);
148221typedef void (*table_function_t)(ClientContext &context, TableFunctionInput &data, DataChunk &output);
148222typedef OperatorResultType (*table_in_out_function_t)(ExecutionContext &context, TableFunctionInput &data,
148223 DataChunk &input, DataChunk &output);
148225 DataChunk &output);
148226typedef OperatorPartitionData (*table_function_get_partition_data_t)(ClientContext &context,
148227 TableFunctionGetPartitionInput &input);
148228
148229typedef BindInfo (*table_function_get_bind_info_t)(const optional_ptr<FunctionData> bind_data);
148230
148231typedef unique_ptr<MultiFileReader> (*table_function_get_multi_file_reader_t)(const TableFunction &);
148232
148233typedef bool (*table_function_supports_pushdown_type_t)(
const FunctionData &bind_data,
idx_t col_idx);
148234
148235typedef bool (*table_function_supports_pushdown_extract_t)(const FunctionData &bind_data, const LogicalIndex &col_idx);
148236
148237typedef double (*table_function_progress_t)(ClientContext &context, const FunctionData *bind_data,
148238 const GlobalTableFunctionState *global_state);
148239typedef void (*table_function_dependency_t)(LogicalDependencyList &dependencies, const FunctionData *bind_data);
148240typedef unique_ptr<NodeStatistics> (*table_function_cardinality_t)(ClientContext &context,
148241 const FunctionData *bind_data);
148242typedef idx_t (*table_function_rows_scanned_t)(GlobalTableFunctionState &global_state,
148243 LocalTableFunctionState &local_state);
148244typedef void (*table_function_pushdown_complex_filter_t)(ClientContext &context, LogicalGet &
get,
148245 FunctionData *bind_data,
148246 vector<unique_ptr<Expression>> &filters);
148247typedef bool (*table_function_pushdown_expression_t)(ClientContext &context,
const LogicalGet &
get, Expression &expr);
148248typedef InsertionOrderPreservingMap<string> (*table_function_to_string_t)(TableFunctionToStringInput &input);
148249typedef InsertionOrderPreservingMap<string> (*table_function_dynamic_to_string_t)(
148250 TableFunctionDynamicToStringInput &input);
148251
148252typedef void (*table_function_serialize_t)(Serializer &serializer, const optional_ptr<FunctionData> bind_data,
148253 const TableFunction &function);
148254typedef unique_ptr<FunctionData> (*table_function_deserialize_t)(Deserializer &deserializer, TableFunction &function);
148255
148256typedef void (*table_function_type_pushdown_t)(ClientContext &context, optional_ptr<FunctionData> bind_data,
148257 const unordered_map<idx_t, LogicalType> &new_column_types);
148258typedef TablePartitionInfo (*table_function_get_partition_info_t)(ClientContext &context,
148259 TableFunctionPartitionInput &input);
148260
148261typedef vector<PartitionStatistics> (*table_function_get_partition_stats_t)(ClientContext &context,
148262 GetPartitionStatsInput &input);
148263
148264typedef virtual_column_map_t (*table_function_get_virtual_columns_t)(ClientContext &context,
148265 optional_ptr<FunctionData> bind_data);
148266
148267typedef vector<column_t> (*table_function_get_row_id_columns)(ClientContext &context,
148268 optional_ptr<FunctionData> bind_data);
148269
148270typedef void (*table_function_set_scan_order)(unique_ptr<RowGroupOrderOptions> order_options,
148271 optional_ptr<FunctionData> bind_data);
148272
148275
148276class TableFunction : public SimpleNamedParameterFunction {
148277public:
148278 DUCKDB_API TableFunction();
148279
148280 DUCKDB_API
148281 TableFunction(string name, const vector<LogicalType> &arguments, table_function_t function,
148282 table_function_bind_t bind = nullptr, table_function_init_global_t init_global = nullptr,
148283 table_function_init_local_t init_local = nullptr);
148284 DUCKDB_API
148285 TableFunction(const vector<LogicalType> &arguments, table_function_t function, table_function_bind_t bind = nullptr,
148286 table_function_init_global_t init_global = nullptr, table_function_init_local_t init_local = nullptr);
148287
148288 DUCKDB_API
148289 TableFunction(string name, const vector<LogicalType> &arguments, std::nullptr_t function,
148290 table_function_bind_t bind = nullptr, table_function_init_global_t init_global = nullptr,
148291 table_function_init_local_t init_local = nullptr);
148292 DUCKDB_API
148293 TableFunction(const vector<LogicalType> &arguments, std::nullptr_t function, table_function_bind_t bind = nullptr,
148294 table_function_init_global_t init_global = nullptr, table_function_init_local_t init_local = nullptr);
148295
148296 bool HasBindCallback() const {
148297 return bind !=
nullptr;
148298 }
148299 table_function_bind_t GetBindCallback() const {
148301 }
148302 bool HasSerializationCallbacks() const {
148304 }
148305 void SetSerializeCallback(table_function_serialize_t callback) {
148307 }
148308 void SetDeserializeCallback(table_function_deserialize_t callback) {
148310 }
148311 table_function_serialize_t GetSerializeCallback() const {
148313 }
148314 table_function_deserialize_t GetDeserializeCallback() const {
148316 }
148317
148321 table_function_bind_t
bind;
148326 table_function_bind_replace_t bind_replace;
148330 table_function_bind_operator_t bind_operator;
148335 table_function_init_global_t init_global;
148339 table_function_init_local_t init_local;
148341 table_function_t function;
148343 table_in_out_function_t in_out_function;
148345 table_in_out_function_final_t in_out_function_final;
148348 table_statistics_t statistics;
148351 table_statistics_extended_t statistics_extended;
148354 table_function_dependency_t dependency;
148357 table_function_cardinality_t cardinality;
148359 table_function_rows_scanned_t rows_scanned;
148362 table_function_pushdown_complex_filter_t pushdown_complex_filter;
148364 table_function_pushdown_expression_t pushdown_expression;
148368 table_function_dynamic_to_string_t dynamic_to_string;
148370 table_function_progress_t table_scan_progress;
148372 table_function_get_partition_data_t get_partition_data;
148374 table_function_get_bind_info_t get_bind_info;
148376 table_function_type_pushdown_t type_pushdown;
148378 table_function_get_multi_file_reader_t get_multi_file_reader;
148380 table_function_supports_pushdown_type_t supports_pushdown_type;
148382 table_function_supports_pushdown_extract_t supports_pushdown_extract;
148384 table_function_get_partition_info_t get_partition_info;
148386 table_function_get_partition_stats_t get_partition_stats;
148388 table_function_get_virtual_columns_t get_virtual_columns;
148390 table_function_get_row_id_columns get_row_id_columns;
148392 table_function_set_scan_order set_scan_order;
148393
148396 bool verify_serialization = true;
148397
148400 bool projection_pushdown;
148403 bool filter_pushdown;
148406 bool filter_prune;
148409 bool sampling_pushdown;
148411 bool late_materialization;
148413 shared_ptr<TableFunctionInfo> function_info;
148415 OrderPreservationType order_preservation_type = OrderPreservationType::INSERTION_ORDER;
148416
148421
148422 DUCKDB_API bool Equal(const TableFunction &rhs) const;
148423 DUCKDB_API
bool operator==(
const TableFunction &rhs)
const;
148424 DUCKDB_API
bool operator!=(
const TableFunction &rhs)
const;
148425};
148426
148427}
148428
148429
148430
148431
148432
148433
148434
148435
148436
148437
148438
148439
148440
148441
148442
148443
148444
148445namespace duckdb {
148446
148447struct ConcurrentQueue;
148448struct QueueProducerToken;
148449class ClientContext;
148450class DatabaseInstance;
148451class TaskScheduler;
148452
148453struct SchedulerThread;
148454
148455struct ProducerToken {
148456 ProducerToken(TaskScheduler &scheduler, unique_ptr<QueueProducerToken> token);
148457 ~ProducerToken();
148458
148459 TaskScheduler &scheduler;
148460 unique_ptr<QueueProducerToken> token;
148461 mutex producer_lock;
148462};
148463
148465class TaskScheduler {
148466
148467 constexpr static int64_t TASK_TIMEOUT_USECS = 5000;
148468
148469public:
148470 explicit TaskScheduler(DatabaseInstance &db);
148471 ~TaskScheduler();
148472
148473 DUCKDB_API static TaskScheduler &GetScheduler(ClientContext &context);
148474 DUCKDB_API static TaskScheduler &GetScheduler(DatabaseInstance &db);
148475
148476 unique_ptr<ProducerToken> CreateProducer();
148478 void ScheduleTask(ProducerToken &producer, shared_ptr<Task> task);
148479 void ScheduleTasks(ProducerToken &producer, vector<shared_ptr<Task>> &tasks);
148481 bool GetTaskFromProducer(ProducerToken &token, shared_ptr<Task> &task);
148483 void ExecuteForever(atomic<bool> *marker);
148486 idx_t ExecuteTasks(atomic<bool> *marker, idx_t max_tasks);
148488 void ExecuteTasks(idx_t max_tasks);
148489
148493 void SetThreads(idx_t total_threads, idx_t external_threads);
148494
148495 void RelaunchThreads();
148496
148498 DUCKDB_API
int32_t NumberOfThreads();
148499
148500 idx_t GetNumberOfTasks()
const;
148501 idx_t GetProducerCount()
const;
148502 idx_t GetTaskCountForProducer(ProducerToken &token)
const;
148503
148505 void Signal(idx_t n);
148506
148508 static void YieldThread();
148509
148511 void SetAllocatorFlushTreshold(idx_t threshold);
148513 void SetAllocatorBackgroundThreads(bool enable);
148514
148518 static idx_t GetEstimatedCPUId();
148519
148520private:
148521 void RelaunchThreadsInternal(int32_t n, bool destroy);
148522
148523private:
148524 DatabaseInstance &
db;
148526 unique_ptr<ConcurrentQueue> queue;
148528 mutex thread_lock;
148530 vector<unique_ptr<SchedulerThread>> threads;
148532 vector<unique_ptr<atomic<bool>>> markers;
148534 atomic<idx_t> allocator_flush_threshold;
148536 atomic<bool> allocator_background_threads;
148538 atomic<int32_t> requested_thread_count;
148540 atomic<int32_t> current_thread_count;
148541};
148542
148543}
148544
148545
148546
148547
148548
148549
148550
148551
148552
148553
148554
148555
148556
148557
148558
148559namespace duckdb {
148561class PhysicalOperator;
148562class ThreadContext;
148563
148566class ExecutorTask : public Task {
148567public:
148568 ExecutorTask(Executor &executor, shared_ptr<Event> event);
148569 ExecutorTask(ClientContext &context, shared_ptr<Event> event, const PhysicalOperator &op);
148570 ~ExecutorTask() override;
148571
148572public:
148573 void Deschedule() override;
148574 void Reschedule() override;
148575
148576public:
148577 Executor &executor;
148578 shared_ptr<Event> event;
148579 unique_ptr<ThreadContext> thread_context;
148580 optional_ptr<const PhysicalOperator> op;
148581
148582private:
148583 ClientContext &context;
148584
148585public:
148586 virtual TaskExecutionResult ExecuteTask(TaskExecutionMode mode) = 0;
148587 TaskExecutionResult Execute(TaskExecutionMode mode) override;
148588};
148589
148590}
148591
148592
148593namespace duckdb {
148594
148595class Executor;
148596class MetaPipeline;
148597class PipelineExecutor;
148598class Pipeline;
148599
148600class PipelineTask : public ExecutorTask {
148601 static constexpr const idx_t PARTIAL_CHUNK_COUNT = 50;
148602
148603public:
148604 explicit PipelineTask(Pipeline &pipeline_p, shared_ptr<Event> event_p);
148605
148606 Pipeline &pipeline;
148607 unique_ptr<PipelineExecutor> pipeline_executor;
148608
148609 string TaskType() const override {
148610 return "PipelineTask";
148611 }
148612
148613public:
148614 const PipelineExecutor &GetPipelineExecutor() const;
148615 bool TaskBlockedOnResult() const override;
148616
148617public:
148618 TaskExecutionResult ExecuteTask(TaskExecutionMode mode) override;
148619};
148620
148621class PipelineBuildState {
148622public:
148624 constexpr static idx_t BATCH_INCREMENT = 10000000000000;
148625
148626public:
148628 reference_map_t<const PhysicalOperator, reference<Pipeline>> delim_join_dependencies;
148630 reference_map_t<const PhysicalOperator, reference<Pipeline>> cte_dependencies;
148631
148632public:
148633 void SetPipelineSource(Pipeline &pipeline, PhysicalOperator &op);
148634 void SetPipelineSink(Pipeline &pipeline, optional_ptr<PhysicalOperator> op, idx_t sink_pipeline_count);
148635 void SetPipelineOperators(Pipeline &pipeline, vector<reference<PhysicalOperator>> operators);
148636 void AddPipelineOperator(Pipeline &pipeline, PhysicalOperator &op);
148637 shared_ptr<Pipeline> CreateChildPipeline(Executor &executor, Pipeline &pipeline, PhysicalOperator &op);
148638
148639 optional_ptr<PhysicalOperator> GetPipelineSource(Pipeline &pipeline);
148640 optional_ptr<PhysicalOperator> GetPipelineSink(Pipeline &pipeline);
148641 vector<reference<PhysicalOperator>> GetPipelineOperators(Pipeline &pipeline);
148642};
148643
148645class Pipeline : public enable_shared_from_this<Pipeline> {
148646 friend class Executor;
148647 friend class PipelineExecutor;
148648 friend class PipelineEvent;
148649 friend class PipelineFinishEvent;
148650 friend class PipelineBuildState;
148651 friend class MetaPipeline;
148652
148653public:
148654 explicit Pipeline(Executor &execution_context);
148655
148656 Executor &executor;
148657
148658public:
148659 ClientContext &GetClientContext();
148660
148661 void AddDependency(shared_ptr<Pipeline> &pipeline);
148662 vector<weak_ptr<Pipeline>> GetDependencies() const;
148663
148664 void Ready();
148665 void Reset();
148666 void ResetSink();
148667 void ResetSource(bool force);
148668 void ClearSource();
148669 void Schedule(shared_ptr<Event> &event);
148670 void PrepareFinalize();
148671
148672 string ToString() const;
148673 void Print() const;
148674 void PrintDependencies() const;
148675
148677 bool GetProgress(ProgressData &progress_data);
148678
148680 vector<reference<PhysicalOperator>> GetOperators();
148681 vector<const_reference<PhysicalOperator>> GetOperators() const;
148682 const vector<reference<PhysicalOperator>> &GetIntermediateOperators() const;
148683
148684 optional_ptr<PhysicalOperator> GetSink() {
148685 return sink;
148686 }
148687
148688 optional_ptr<PhysicalOperator> GetSource() {
148689 return source;
148690 }
148691
148693 bool IsOrderDependent() const;
148694
148696 idx_t RegisterNewBatchIndex();
148697
148699 idx_t UpdateBatchIndex(idx_t old_index, idx_t new_index);
148700
148701private:
148703 bool ready;
148705 atomic<bool> initialized;
148707 optional_ptr<PhysicalOperator> source;
148709 vector<reference<PhysicalOperator>> operators;
148711 optional_ptr<PhysicalOperator> sink;
148712
148714 unique_ptr<GlobalSourceState> source_state;
148715
148717 vector<weak_ptr<Pipeline>> parents;
148719 vector<weak_ptr<Pipeline>> dependencies;
148720
148722 idx_t base_batch_index = 0;
148724 mutex batch_lock;
148729 multiset<idx_t> batch_indexes;
148730
148731private:
148732 void ScheduleSequentialTask(shared_ptr<Event> &event);
148733 bool LaunchScanTasks(shared_ptr<Event> &event, idx_t max_threads);
148734
148735 bool ScheduleParallel(shared_ptr<Event> &event);
148736};
148737
148738}
148739
148740
148741#include <condition_variable>
148742
148743namespace duckdb {
148744class ClientContext;
148745class DataChunk;
148746class PhysicalOperator;
148747class PipelineExecutor;
148748class OperatorState;
148749class QueryProfiler;
148750class ThreadContext;
148751class Task;
148752
148753struct PipelineEventStack;
148754struct ProducerToken;
148755struct ScheduleEventData;
148756
148757class Executor {
148758 friend class Pipeline;
148759 friend class PipelineTask;
148760 friend class PipelineBuildState;
148761
148762public:
148763 static constexpr idx_t WAIT_TIME = 20;
148764
148765public:
148766 explicit Executor(ClientContext &context);
148767 ~Executor();
148768
148769 ClientContext &context;
148770
148771public:
148772 static Executor &Get(ClientContext &context);
148773
148774 void Initialize(PhysicalOperator &physical_plan);
148775 void Initialize(unique_ptr<PhysicalOperator> physical_plan);
148776
148777 void CancelTasks();
148778 PendingExecutionResult ExecuteTask(bool dry_run = false);
148779 void WaitForTask();
148780 void SignalTaskRescheduled(lock_guard<mutex> &);
148781
148782 void Reset();
148783
148784 vector<LogicalType> GetTypes();
148785
148787 void PushError(ErrorData exception);
148788
148789 ErrorData GetError();
148790
148792 bool HasError();
148795 void ThrowException();
148796
148798 void WorkOnTasks();
148799
148801 void Flush(ThreadContext &context);
148802
148804 void RescheduleTask(shared_ptr<Task> &task);
148805
148807 void AddToBeRescheduled(shared_ptr<Task> &task);
148808
148810 idx_t GetPipelinesProgress(ProgressData &progress);
148811
148812 void CompletePipeline() {
148813 completed_pipelines++;
148814 }
148815 ProducerToken &GetToken() {
148816 return *producer;
148817 }
148818 void AddEvent(shared_ptr<Event> event);
148819
148820 void AddRecursiveCTE(PhysicalOperator &rec_cte);
148821 void ReschedulePipelines(const vector<shared_ptr<MetaPipeline>> &pipelines, vector<shared_ptr<Event>> &events);
148822
148824 bool HasResultCollector();
148826 bool HasStreamingResultCollector();
148828 unique_ptr<QueryResult> GetResult();
148829
148831 bool ExecutionIsFinished();
148832
148833 void RegisterTask() {
148834 executor_tasks++;
148835 }
148836 void UnregisterTask() {
148837 executor_tasks--;
148838 }
148839
148840 idx_t GetTotalPipelines()
const {
148841 return total_pipelines;
148842 }
148843
148844 idx_t GetCompletedPipelines()
const {
148845 return completed_pipelines.load();
148846 }
148847
148848private:
148850 bool ResultCollectorIsBlocked();
148851 void InitializeInternal(PhysicalOperator &physical_plan);
148852
148853 void ScheduleEvents(const vector<shared_ptr<MetaPipeline>> &meta_pipelines);
148854 void ScheduleEventsInternal(ScheduleEventData &event_data);
148855
148856 static void VerifyScheduledEvents(const ScheduleEventData &event_data);
148857 static void VerifyScheduledEventsInternal(const idx_t i, const vector<reference<Event>> &vertices,
148858 vector<bool> &visited, vector<bool> &recursion_stack);
148859
148860 void SchedulePipeline(const shared_ptr<MetaPipeline> &pipeline, ScheduleEventData &event_data);
148861
148862 bool NextExecutor();
148863
148864 shared_ptr<Pipeline> CreateChildPipeline(Pipeline ¤t, PhysicalOperator &op);
148865
148866 void VerifyPipeline(Pipeline &pipeline);
148867 void VerifyPipelines();
148868
148869private:
148870 optional_ptr<PhysicalOperator> physical_plan;
148871 unique_ptr<PhysicalOperator> owned_plan;
148872
148873 mutex executor_lock;
148875 vector<shared_ptr<Pipeline>> pipelines;
148877 vector<shared_ptr<Pipeline>> root_pipelines;
148879 vector<reference<PhysicalOperator>> recursive_ctes;
148881 unique_ptr<PipelineExecutor> root_executor;
148883 idx_t root_pipeline_idx;
148885 unique_ptr<ProducerToken> producer;
148887 vector<shared_ptr<Event>> events;
148889 shared_ptr<QueryProfiler> profiler;
148891 TaskErrorManager error_manager;
148892
148894 atomic<idx_t> completed_pipelines;
148896 idx_t total_pipelines;
148898 bool cancelled;
148899
148901 PendingExecutionResult execution_result;
148903 shared_ptr<Task> task;
148904
148906 unordered_map<Task *, shared_ptr<Task>> to_be_rescheduled_tasks;
148908 std::condition_variable task_reschedule;
148909
148911 atomic<idx_t> executor_tasks;
148912
148914 atomic<idx_t> blocked_thread_time;
148915};
148916}
148917
148918
148919namespace duckdb {
148920class ClientContext;
148921class ClientContextLock;
148922class PreparedStatementData;
148923
148924class PendingQueryResult : public BaseQueryResult {
148925 friend class ClientContext;
148926
148927public:
148928 static constexpr const QueryResultType
TYPE = QueryResultType::PENDING_RESULT;
148929
148930public:
148931 DUCKDB_API PendingQueryResult(shared_ptr<ClientContext> context, PreparedStatementData &statement,
148932 vector<LogicalType> types, bool allow_stream_result);
148933 DUCKDB_API explicit PendingQueryResult(ErrorData error_message);
148934 DUCKDB_API ~PendingQueryResult() override;
148935 DUCKDB_API bool AllowStreamResult() const;
148936 PendingQueryResult(const PendingQueryResult &) = delete;
148937 PendingQueryResult &
operator=(
const PendingQueryResult &) =
delete;
148938
148939public:
148947 DUCKDB_API PendingExecutionResult ExecuteTask();
148948 DUCKDB_API PendingExecutionResult CheckPulse();
148950 void WaitForTask();
148951
148954 DUCKDB_API unique_ptr<QueryResult> Execute();
148955
148956 DUCKDB_API void Close();
148957
148959 DUCKDB_API static bool IsResultReady(PendingExecutionResult result);
148960 DUCKDB_API static bool IsExecutionFinished(PendingExecutionResult result);
148961
148962private:
148963 shared_ptr<ClientContext> context;
148964 bool allow_stream_result;
148965
148966private:
148967 void CheckExecutableInternal(ClientContextLock &lock);
148968
148969 PendingExecutionResult ExecuteTaskInternal(ClientContextLock &lock);
148970 unique_ptr<QueryResult> ExecuteInternal(ClientContextLock &lock);
148971 unique_ptr<ClientContextLock> LockContext();
148972};
148973
148974}
148975
148976
148977
148978
148979
148980
148981
148982
148983
148984
148985
148986
148987
148988
148989
148990
148991
148992
148993
148994
148995
148996
148997
148998
148999
149000
149001
149002
149003
149004namespace duckdb {
149005
149006struct BoundParameterData {
149007public:
149008 BoundParameterData() {
149009 }
149010 explicit BoundParameterData(Value val) : value(std::move(val)), return_type(GetDefaultType(value.type())) {
149011 }
149012 BoundParameterData(Value val, LogicalType type_p) : value(std::move(val)), return_type(std::move(type_p)) {
149013 }
149014
149015private:
149016 Value value;
149017
149018public:
149019 LogicalType return_type;
149020
149021public:
149022 void SetValue(Value val) {
149023 value = std::move(val);
149024 }
149025
149026 const Value &GetValue() const {
149027 return value;
149028 }
149029
149030 void Serialize(Serializer &serializer) const;
149031 static shared_ptr<BoundParameterData> Deserialize(Deserializer &deserializer);
149032
149033private:
149034 LogicalType GetDefaultType(const LogicalType &type) {
149035 if (value.type().id() == LogicalTypeId::VARCHAR && StringType::GetCollation(type).empty()) {
149036 return LogicalTypeId::STRING_LITERAL;
149037 }
149038 return value.type();
149039 }
149040};
149041
149042}
149043
149044
149045namespace duckdb {
149046class ClientContext;
149047class PreparedStatementData;
149048
149050class PreparedStatement {
149051public:
149053 DUCKDB_API PreparedStatement(shared_ptr<ClientContext> context, shared_ptr<PreparedStatementData> data,
149054 string query, case_insensitive_map_t<idx_t> named_param_map);
149056 DUCKDB_API explicit PreparedStatement(ErrorData error);
149057
149058 DUCKDB_API ~PreparedStatement();
149059
149060public:
149062 shared_ptr<ClientContext> context;
149064 shared_ptr<PreparedStatementData> data;
149066 string query;
149068 bool success;
149070 ErrorData error;
149072 case_insensitive_map_t<idx_t> named_param_map;
149073
149074public:
149076 DUCKDB_API const string &GetError();
149078 DUCKDB_API ErrorData &GetErrorObject();
149080 DUCKDB_API bool HasError() const;
149082 DUCKDB_API
idx_t ColumnCount();
149084 DUCKDB_API StatementType GetStatementType();
149086 DUCKDB_API StatementProperties GetStatementProperties();
149088 DUCKDB_API const vector<LogicalType> &GetTypes();
149090 DUCKDB_API const vector<string> &GetNames();
149092 DUCKDB_API case_insensitive_map_t<LogicalType> GetExpectedParameterTypes() const;
149093
149095 template <typename... ARGS>
149096 unique_ptr<PendingQueryResult> PendingQuery(ARGS... args) {
149097 vector<Value> values;
149098 return PendingQueryRecursive(values, args...);
149099 }
149100
149102 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(vector<Value> &values, bool allow_stream_result = true);
149103
149105 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(case_insensitive_map_t<BoundParameterData> &named_values,
149106 bool allow_stream_result = true);
149107
149109 DUCKDB_API unique_ptr<QueryResult> Execute(vector<Value> &values, bool allow_stream_result = true);
149110
149112 DUCKDB_API unique_ptr<QueryResult> Execute(case_insensitive_map_t<BoundParameterData> &named_values,
149113 bool allow_stream_result = true);
149114
149116 template <typename... ARGS>
149117 unique_ptr<QueryResult> Execute(ARGS... args) {
149118 vector<Value> values;
149119 return ExecuteRecursive(values, args...);
149120 }
149121
149122 template <class PAYLOAD>
149123 static string ExcessValuesException(const case_insensitive_map_t<idx_t> ¶meters,
149124 const case_insensitive_map_t<PAYLOAD> &values) {
149125
149126 set<string> excess_set;
149127 for (auto &pair : values) {
149128 auto &name = pair.first;
149129 if (!parameters.count(name)) {
149130 excess_set.insert(name);
149131 }
149132 }
149133 vector<string> excess_values;
149134 for (auto &val : excess_set) {
149135 excess_values.push_back(val);
149136 }
149137 return StringUtil::Format(
"Parameter argument/count mismatch, identifiers of the excess parameters: %s",
149139 }
149140
149141 template <class PAYLOAD>
149142 static string MissingValuesException(const case_insensitive_map_t<idx_t> ¶meters,
149143 const case_insensitive_map_t<PAYLOAD> &values) {
149144
149145 set<string> missing_set;
149146 for (auto &pair : parameters) {
149147 auto &name = pair.first;
149148 if (!values.count(name)) {
149149 missing_set.insert(name);
149150 }
149151 }
149152 vector<string> missing_values;
149153 for (auto &val : missing_set) {
149154 missing_values.push_back(val);
149155 }
149156 return StringUtil::Format(
"Values were not provided for the following prepared statement parameters: %s",
149158 }
149159
149160 template <class PAYLOAD>
149161 static void VerifyParameters(const case_insensitive_map_t<PAYLOAD> &provided,
149162 const case_insensitive_map_t<idx_t> &expected) {
149163 if (expected.size() == provided.size()) {
149164
149165 for (auto &pair : expected) {
149166 auto &identifier = pair.first;
149167 if (!provided.count(identifier)) {
149168 throw InvalidInputException(MissingValuesException(expected, provided));
149169 }
149170 }
149171 return;
149172 }
149173
149174 if (expected.size() > provided.size()) {
149175 throw InvalidInputException(MissingValuesException(expected, provided));
149176 } else {
149177 D_ASSERT(provided.size() > expected.size());
149178 throw InvalidInputException(ExcessValuesException(expected, provided));
149179 }
149180 }
149181
149183 static bool CanCachePlan(const LogicalOperator &op);
149184
149185private:
149186 unique_ptr<PendingQueryResult> PendingQueryRecursive(vector<Value> &values) {
149187 return PendingQuery(values);
149188 }
149189
149190 template <typename T, typename... ARGS>
149191 unique_ptr<PendingQueryResult> PendingQueryRecursive(vector<Value> &values, T value, ARGS... args) {
149192 values.push_back(Value::CreateValue<T>(value));
149193 return PendingQueryRecursive(values, args...);
149194 }
149195
149196 unique_ptr<QueryResult> ExecuteRecursive(vector<Value> &values) {
149197 return Execute(values);
149198 }
149199
149200 template <typename T, typename... ARGS>
149201 unique_ptr<QueryResult> ExecuteRecursive(vector<Value> &values, T value, ARGS... args) {
149202 values.push_back(Value::CreateValue<T>(value));
149203 return ExecuteRecursive(values, args...);
149204 }
149205};
149206
149207}
149208
149209
149210
149211
149212
149213
149214
149215
149216
149217
149218
149219
149220
149221
149222
149223
149224
149225
149226
149227
149228
149229
149230
149231
149232
149233namespace duckdb {
149234
149235
149236
149237
149238enum class JoinType :
uint8_t {
149239 INVALID = 0,
149240 LEFT = 1,
149241 RIGHT = 2,
149242 INNER = 3,
149243 OUTER = 4,
149244 SEMI = 5,
149245 ANTI = 6,
149246 MARK = 7,
149247
149248 SINGLE = 8,
149249
149250 RIGHT_SEMI = 9,
149251
149252 RIGHT_ANTI = 10
149253
149254};
149255
149258
149261
149264
149267
149270
149271
149272string JoinTypeToString(JoinType type);
149273
149274}
149275
149276
149277
149278
149279
149280
149281
149282
149283
149284
149285
149286
149287
149288namespace duckdb {
149289
149290
149291
149292
149293enum class RelationType :
uint8_t {
149294 INVALID_RELATION,
149295 TABLE_RELATION,
149296 PROJECTION_RELATION,
149297 FILTER_RELATION,
149298 EXPLAIN_RELATION,
149299 CROSS_PRODUCT_RELATION,
149300 JOIN_RELATION,
149301 AGGREGATE_RELATION,
149302 SET_OPERATION_RELATION,
149303 DISTINCT_RELATION,
149304 LIMIT_RELATION,
149305 ORDER_RELATION,
149306 CREATE_VIEW_RELATION,
149307 CREATE_TABLE_RELATION,
149308 INSERT_RELATION,
149309 VALUE_LIST_RELATION,
149310 MATERIALIZED_RELATION,
149311 DELETE_RELATION,
149312 UPDATE_RELATION,
149313 WRITE_CSV_RELATION,
149314 WRITE_PARQUET_RELATION,
149315 READ_CSV_RELATION,
149316 SUBQUERY_RELATION,
149317 TABLE_FUNCTION_RELATION,
149318 VIEW_RELATION,
149319 QUERY_RELATION,
149320 DELIM_JOIN_RELATION,
149321 DELIM_GET_RELATION,
149322 EXTENSION_RELATION = 255
149323};
149324
149325string RelationTypeToString(RelationType type);
149326
149327}
149328
149329
149330
149331
149332
149333
149334
149335
149336
149337
149338
149339
149340
149341
149342namespace duckdb {
149343
149344
149345
149346
149347enum class JoinRefType :
uint8_t {
149348 REGULAR,
149349 NATURAL,
149350 CROSS,
149351 POSITIONAL,
149352 ASOF,
149353 DEPENDENT,
149354};
149355
149356const char *ToString(JoinRefType value);
149357
149358}
149359
149360
149361
149362
149363
149364
149365
149366
149367
149368
149369
149370
149371
149372
149373
149374
149375
149376
149377
149378
149379
149380
149381
149382
149383
149384
149385
149386
149387
149388
149389
149390
149391
149392
149393
149394
149395
149396
149397
149398
149399
149400
149401
149402
149403
149404
149405
149406
149407
149408namespace duckdb {
149409class ClientContext;
149410
149411class DefaultGenerator {
149412public:
149413 explicit DefaultGenerator(Catalog &catalog);
149414 virtual ~DefaultGenerator();
149415
149416 Catalog &catalog;
149417 atomic<bool> created_all_entries;
149418
149419public:
149421 virtual unique_ptr<CatalogEntry> CreateDefaultEntry(ClientContext &context, const string &entry_name);
149422 virtual unique_ptr<CatalogEntry> CreateDefaultEntry(CatalogTransaction transaction, const string &entry_name);
149424 virtual vector<string> GetDefaultEntries() = 0;
149428 virtual bool LockDuringCreate() const {
149429 return false;
149430 }
149431};
149432
149433}
149434
149435
149436
149437
149438
149439
149440
149441
149442
149443
149444
149445
149446
149447
149448
149449
149450
149451
149452
149453
149454
149455
149456
149457
149458
149459
149460
149461
149462
149463
149464
149465
149466
149467
149468
149469
149470
149471
149472
149473
149474
149475
149476
149477
149478
149479
149480
149481
149482
149483
149484
149485
149486
149487
149488
149489
149490
149491
149492
149493
149494
149495
149496namespace duckdb {
149497class CatalogEntry;
149498
149499struct CatalogEntryHashFunction {
149501 std::hash<void *> hash_func;
149502 return hash_func((void *)&a.get());
149503 }
149504};
149505
149506struct CatalogEntryEquality {
149507 bool operator()(
const reference<CatalogEntry> &a,
const reference<CatalogEntry> &b)
const {
149509 }
149510};
149511
149512using catalog_entry_set_t = unordered_set<reference<CatalogEntry>, CatalogEntryHashFunction, CatalogEntryEquality>;
149513
149514template <typename T>
149515using catalog_entry_map_t = unordered_map<reference<CatalogEntry>, T, CatalogEntryHashFunction, CatalogEntryEquality>;
149516
149517using catalog_entry_vector_t = vector<reference<CatalogEntry>>;
149518
149519}
149520
149521
149522
149523
149524
149525
149526
149527
149528
149529
149530
149531
149532
149533
149534
149535
149536
149537namespace duckdb {
149538class CatalogEntry;
149539
149540struct DependencyFlags {
149541public:
149542 DependencyFlags() : value(0) {
149543 }
149544 DependencyFlags(const DependencyFlags &other) : value(other.value) {
149545 }
149546 virtual ~DependencyFlags() = default;
149547 DependencyFlags &
operator=(
const DependencyFlags &other) {
149548 value = other.value;
149549 return *this;
149550 }
149551 bool operator==(
const DependencyFlags &other)
const {
149552 return other.value == value;
149553 }
149554 bool operator!=(
const DependencyFlags &other)
const {
149555 return !(*this == other);
149556 }
149557
149558public:
149559 virtual string ToString() const = 0;
149560
149561protected:
149562 template <uint8_t BIT>
149563 bool IsSet() const {
149564 static const uint8_t FLAG = (1 << BIT);
149565 return (value & FLAG) == FLAG;
149566 }
149567 template <uint8_t BIT>
149568 void Set() {
149569 static const uint8_t FLAG = (1 << BIT);
149570 value |= FLAG;
149571 }
149572 void Merge(uint8_t other) {
149573 value |= other;
149574 }
149576 return value;
149577 }
149578
149579private:
149581};
149582
149583struct DependencySubjectFlags : public DependencyFlags {
149584private:
149585 static constexpr uint8_t OWNERSHIP = 0;
149586
149587public:
149588 DependencySubjectFlags &Apply(DependencySubjectFlags other) {
149589 Merge(other.Value());
149590 return *this;
149591 }
149592
149593public:
149594 bool IsOwnership() const {
149595 return IsSet<OWNERSHIP>();
149596 }
149597
149598public:
149599 DependencySubjectFlags &SetOwnership() {
149600 Set<OWNERSHIP>();
149601 return *this;
149602 }
149603
149604public:
149605 string ToString() const override {
149606 string result;
149607 if (IsOwnership()) {
149608 result += "OWNS";
149609 }
149610 return result;
149611 }
149612};
149613
149614struct DependencyDependentFlags : public DependencyFlags {
149615private:
149616 static constexpr uint8_t BLOCKING = 0;
149617 static constexpr uint8_t OWNED_BY = 1;
149618
149619public:
149620 DependencyDependentFlags &Apply(DependencyDependentFlags other) {
149621 Merge(other.Value());
149622 return *this;
149623 }
149624
149625public:
149626 bool IsBlocking() const {
149627 return IsSet<BLOCKING>();
149628 }
149629 bool IsOwnedBy() const {
149630 return IsSet<OWNED_BY>();
149631 }
149632
149633public:
149634 DependencyDependentFlags &SetBlocking() {
149635 Set<BLOCKING>();
149636 return *this;
149637 }
149638 DependencyDependentFlags &SetOwnedBy() {
149639 Set<OWNED_BY>();
149640 return *this;
149641 }
149642
149643public:
149644 string ToString() const override {
149645 string result;
149646 if (IsBlocking()) {
149647 result += "REGULAR";
149648 } else {
149649 result += "AUTOMATIC";
149650 }
149651 result += " | ";
149652 if (IsOwnedBy()) {
149653 result += "OWNED BY";
149654 }
149655 return result;
149656 }
149657};
149658
149659struct CatalogEntryInfo {
149660public:
149661 CatalogType type;
149662 string schema;
149663 string name;
149664
149665public:
149666 bool operator==(
const CatalogEntryInfo &other)
const {
149667 if (other.type != type) {
149668 return false;
149669 }
149671 return false;
149672 }
149674 return false;
149675 }
149676 return true;
149677 }
149678
149679public:
149680 void Serialize(Serializer &serializer) const;
149681 static CatalogEntryInfo Deserialize(Deserializer &deserializer);
149682};
149683
149684struct Dependency {
149685 Dependency(CatalogEntry &entry,
149686 DependencyDependentFlags flags = DependencyDependentFlags().SetBlocking())
149687 : entry(entry), flags(std::move(flags)) {
149688 }
149689
149691 reference<CatalogEntry> entry;
149693 DependencyDependentFlags flags;
149694};
149695
149696struct DependencyHashFunction {
149698 std::hash<void *> hash_func;
149699 return hash_func((void *)&a.entry.get());
149700 }
149701};
149702
149703struct DependencyEquality {
149704 bool operator()(
const Dependency &a,
const Dependency &b)
const {
149706 }
149707};
149708using dependency_set_t = unordered_set<Dependency, DependencyHashFunction, DependencyEquality>;
149709
149710}
149711
149712
149713namespace duckdb {
149714class Catalog;
149715class CatalogEntry;
149716struct CreateInfo;
149717class SchemaCatalogEntry;
149718struct CatalogTransaction;
149719class LogicalDependencyList;
149720
149723struct LogicalDependency {
149724public:
149725 CatalogEntryInfo entry;
149726 string catalog;
149727
149728public:
149729 explicit LogicalDependency(CatalogEntry &entry);
149730 LogicalDependency();
149731 LogicalDependency(optional_ptr<Catalog> catalog, CatalogEntryInfo entry, string catalog_str);
149732 bool operator==(
const LogicalDependency &other)
const;
149733
149734public:
149735 void Serialize(Serializer &serializer) const;
149736 static LogicalDependency Deserialize(Deserializer &deserializer);
149737};
149738
149739struct LogicalDependencyHashFunction {
149741};
149742
149743struct LogicalDependencyEquality {
149744 bool operator()(
const LogicalDependency &a,
const LogicalDependency &b)
const;
149745};
149746
149748class LogicalDependencyList {
149749 using create_info_set_t =
149750 unordered_set<LogicalDependency, LogicalDependencyHashFunction, LogicalDependencyEquality>;
149751
149752public:
149753 DUCKDB_API void AddDependency(CatalogEntry &entry);
149754 DUCKDB_API void AddDependency(const LogicalDependency &entry);
149755 DUCKDB_API bool Contains(CatalogEntry &entry);
149756
149757public:
149758 DUCKDB_API void VerifyDependencies(Catalog &catalog, const string &name);
149759 void Serialize(Serializer &serializer) const;
149760 static LogicalDependencyList Deserialize(Deserializer &deserializer);
149761 bool operator==(
const LogicalDependencyList &other)
const;
149762 const create_info_set_t &Set() const;
149763
149764private:
149765 create_info_set_t set;
149766};
149767
149768}
149769
149770
149771namespace duckdb {
149772class SchemaCatalogEntry;
149773
149775class StandardEntry : public InCatalogEntry {
149776public:
149777 StandardEntry(CatalogType type, SchemaCatalogEntry &schema, Catalog &catalog, string name)
149778 : InCatalogEntry(type, catalog, std::move(name)), schema(schema) {
149779 }
149780 ~StandardEntry() override {
149781 }
149782
149784 SchemaCatalogEntry &schema;
149786 LogicalDependencyList dependencies;
149787
149788public:
149789 SchemaCatalogEntry &ParentSchema() override {
149790 return schema;
149791 }
149792 const SchemaCatalogEntry &ParentSchema() const override {
149793 return schema;
149794 }
149795};
149796
149797}
149798
149799
149800
149801
149802
149803
149804
149805
149806
149807
149808
149809
149810
149811
149812
149813
149814
149815
149816
149817
149818
149819
149820
149821
149822
149823
149824
149825
149826
149827
149828
149829
149830
149831
149832
149833
149834namespace duckdb {
149835
149836enum class CatalogType :
uint8_t;
149837
149838enum class ParseInfoType :
uint8_t {
149839 ALTER_INFO,
149840 ATTACH_INFO,
149841 COPY_INFO,
149842 CREATE_INFO,
149843 CREATE_SECRET_INFO,
149844 DETACH_INFO,
149845 DROP_INFO,
149846 BOUND_EXPORT_DATA,
149847 LOAD_INFO,
149848 PRAGMA_INFO,
149849 SHOW_SELECT_INFO,
149850 TRANSACTION_INFO,
149851 VACUUM_INFO,
149852 COMMENT_ON_INFO,
149853 COMMENT_ON_COLUMN_INFO,
149854 COPY_DATABASE_INFO,
149855 UPDATE_EXTENSIONS_INFO
149856};
149857
149858struct ParseInfo {
149859 explicit ParseInfo(ParseInfoType info_type) : info_type(info_type) {
149860 }
149861 virtual ~ParseInfo() {
149862 }
149863
149864 ParseInfoType info_type;
149865
149866public:
149867 template <class TARGET>
149868 TARGET &Cast() {
149869 DynamicCastCheck<TARGET>(this);
149870 return reinterpret_cast<TARGET &>(*this);
149871 }
149872
149873 template <class TARGET>
149874 const TARGET &Cast() const {
149875 DynamicCastCheck<TARGET>(this);
149876 return reinterpret_cast<const TARGET &>(*this);
149877 }
149878
149879 virtual void Serialize(Serializer &serializer) const;
149880 static unique_ptr<ParseInfo> Deserialize(Deserializer &deserializer);
149881 static string QualifierToString(const string &catalog, const string &schema, const string &name);
149882 static string TypeToString(CatalogType type);
149883};
149884
149885}
149886
149887
149888
149889
149890
149891
149892
149893
149894
149895
149896
149897
149898
149899
149900namespace duckdb {
149901
149902enum class OnCreateConflict :
uint8_t {
149903
149904 ERROR_ON_CONFLICT,
149905
149906 IGNORE_ON_CONFLICT,
149907
149908 REPLACE_ON_CONFLICT,
149909
149910 ALTER_ON_CONFLICT
149911};
149912
149913}
149914
149915
149916
149917
149918namespace duckdb {
149919struct AlterInfo;
149920
149921struct CreateInfo : public ParseInfo {
149922public:
149923 static constexpr const ParseInfoType
TYPE = ParseInfoType::CREATE_INFO;
149924
149925public:
149926 explicit CreateInfo(CatalogType type, string schema = DEFAULT_SCHEMA, string catalog_p = INVALID_CATALOG)
149927 : ParseInfo(
TYPE), type(type), catalog(std::move(catalog_p)), schema(std::move(schema)),
149928 on_conflict(OnCreateConflict::ERROR_ON_CONFLICT), temporary(false), internal(false) {
149929 }
149930 ~CreateInfo() override {
149931 }
149932
149934 CatalogType type;
149936 string catalog;
149938 string schema;
149940 OnCreateConflict on_conflict;
149942 bool temporary;
149944 bool internal;
149946 string sql;
149948 LogicalDependencyList dependencies;
149950 Value comment;
149952 InsertionOrderPreservingMap<string> tags;
149953
149954public:
149955 void Serialize(Serializer &serializer) const override;
149956 static unique_ptr<CreateInfo> Deserialize(Deserializer &deserializer);
149957
149958 virtual unique_ptr<CreateInfo> Copy() const = 0;
149959
149960 DUCKDB_API void CopyProperties(CreateInfo &other) const;
149962 DUCKDB_API virtual unique_ptr<AlterInfo> GetAlterInfo() const;
149964 DUCKDB_API string GetCreatePrefix(const string &entry) const;
149965
149966 virtual string ToString() const {
149967 throw NotImplementedException("ToString not supported for this type of CreateInfo: '%s'",
149968 EnumUtil::ToString(info_type));
149969 }
149970};
149971
149972}
149973
149974
149975namespace duckdb {
149976
149977enum class SequenceInfo :
uint8_t {
149978
149979 SEQ_START,
149980
149981 SEQ_INC,
149982
149983 SEQ_MIN,
149984
149985 SEQ_MAX,
149986
149987 SEQ_CYCLE,
149988
149989 SEQ_OWN
149990};
149991
149992struct CreateSequenceInfo : public CreateInfo {
149993 CreateSequenceInfo();
149994
149996 string name;
150008 bool cycle;
150009
150010public:
150011 unique_ptr<CreateInfo> Copy() const override;
150012
150013public:
150014 DUCKDB_API void Serialize(Serializer &serializer) const override;
150015 DUCKDB_API static unique_ptr<CreateInfo> Deserialize(Deserializer &deserializer);
150016
150017 string ToString() const override;
150018};
150019
150020}
150021
150022
150023
150024
150025
150026
150027
150028
150029
150030
150031
150032
150033
150034
150035
150036
150037
150038
150039
150040
150041
150042
150043
150044
150045
150046
150047namespace duckdb {
150048
150049enum class AlterType :
uint8_t {
150050 INVALID = 0,
150051 ALTER_TABLE = 1,
150052 ALTER_VIEW = 2,
150053 ALTER_SEQUENCE = 3,
150054 CHANGE_OWNERSHIP = 4,
150055 ALTER_SCALAR_FUNCTION = 5,
150056 ALTER_TABLE_FUNCTION = 6,
150057 SET_COMMENT = 7,
150058 SET_COLUMN_COMMENT = 8,
150059 ALTER_DATABASE = 9
150060};
150061
150062struct AlterEntryData {
150063 AlterEntryData() {
150064 }
150065 AlterEntryData(string catalog_p, string schema_p, string name_p, OnEntryNotFound if_not_found)
150066 : catalog(std::move(catalog_p)), schema(std::move(schema_p)), name(std::move(name_p)),
150067 if_not_found(if_not_found) {
150068 }
150069
150070 string catalog;
150071 string schema;
150072 string name;
150073 OnEntryNotFound if_not_found;
150074};
150075
150076struct AlterInfo : public ParseInfo {
150077public:
150078 static constexpr const ParseInfoType
TYPE = ParseInfoType::ALTER_INFO;
150079
150080public:
150081 AlterInfo(AlterType type, string catalog, string schema, string name, OnEntryNotFound if_not_found);
150082 ~AlterInfo() override;
150083
150084 AlterType type;
150086 OnEntryNotFound if_not_found;
150088 string catalog;
150090 string schema;
150092 string name;
150094 bool allow_internal;
150096 unique_ptr<LogicalDependencyList> new_dependencies;
150097
150098public:
150099 virtual CatalogType GetCatalogType() const = 0;
150100 virtual unique_ptr<AlterInfo> Copy() const = 0;
150101 virtual string ToString() const = 0;
150102
150103 void Serialize(Serializer &serializer) const override;
150104 static unique_ptr<ParseInfo> Deserialize(Deserializer &deserializer);
150105
150106 virtual string GetColumnName() const {
150107 return "";
150108 };
150109
150110 AlterEntryData GetAlterEntryData() const;
150111 bool IsAddPrimaryKey() const;
150112
150113protected:
150114 explicit AlterInfo(AlterType type);
150115};
150116
150117}
150118
150119
150120
150121
150122
150123
150124
150125
150126
150127
150128
150129
150130
150131
150132
150133
150134namespace duckdb {
150135
150136class Serializer;
150137class Deserializer;
150138
150139
150140
150141
150142enum class ConstraintType :
uint8_t {
150143 INVALID = 0,
150144 NOT_NULL = 1,
150145 CHECK = 2,
150146 UNIQUE = 3,
150147 FOREIGN_KEY = 4,
150148};
150149
150150enum class ForeignKeyType :
uint8_t {
150151 FK_TYPE_PRIMARY_KEY_TABLE = 0,
150152 FK_TYPE_FOREIGN_KEY_TABLE = 1,
150153 FK_TYPE_SELF_REFERENCE_TABLE = 2
150154};
150155
150156struct ForeignKeyInfo {
150157 ForeignKeyType type;
150158 string schema;
150161 string table;
150163 vector<PhysicalIndex> pk_keys;
150165 vector<PhysicalIndex> fk_keys;
150166
150167 bool IsDeleteConstraint() const {
150168 return type == ForeignKeyType::FK_TYPE_PRIMARY_KEY_TABLE ||
150169 type == ForeignKeyType::FK_TYPE_SELF_REFERENCE_TABLE;
150170 }
150171 bool IsAppendConstraint() const {
150172 return type == ForeignKeyType::FK_TYPE_FOREIGN_KEY_TABLE ||
150173 type == ForeignKeyType::FK_TYPE_SELF_REFERENCE_TABLE;
150174 }
150175};
150176
150178class Constraint {
150179public:
150180 DUCKDB_API explicit Constraint(ConstraintType type);
150181 DUCKDB_API virtual ~Constraint();
150182
150183 ConstraintType type;
150184
150185public:
150186 DUCKDB_API virtual string ToString() const = 0;
150187 DUCKDB_API void Print() const;
150188
150189 DUCKDB_API virtual unique_ptr<Constraint> Copy() const = 0;
150190
150191 DUCKDB_API virtual void Serialize(Serializer &serializer) const;
150192 DUCKDB_API static unique_ptr<Constraint> Deserialize(Deserializer &deserializer);
150193
150194public:
150195 template <class TARGET>
150196 TARGET &Cast() {
150197 if (type != TARGET::TYPE) {
150198 throw InternalException("Failed to cast constraint to type - constraint type mismatch");
150199 }
150200 return reinterpret_cast<TARGET &>(*this);
150201 }
150202
150203 template <class TARGET>
150204 const TARGET &Cast() const {
150205 if (type != TARGET::TYPE) {
150206 throw InternalException("Failed to cast constraint to type - constraint type mismatch");
150207 }
150208 return reinterpret_cast<const TARGET &>(*this);
150209 }
150210};
150211}
150212
150213
150214
150215namespace duckdb {
150216
150217enum class AlterForeignKeyType :
uint8_t { AFT_ADD = 0, AFT_DELETE = 1 };
150218
150219
150220
150221
150222struct ChangeOwnershipInfo : public AlterInfo {
150223 ChangeOwnershipInfo(CatalogType entry_catalog_type, string entry_catalog, string entry_schema, string entry_name,
150224 string owner_schema, string owner_name, OnEntryNotFound if_not_found);
150225
150226
150227
150228
150229 CatalogType entry_catalog_type;
150230
150231 string owner_schema;
150232 string owner_name;
150233
150234public:
150235 CatalogType GetCatalogType() const override;
150236 unique_ptr<AlterInfo> Copy() const override;
150237 string ToString() const override;
150238
150239 void Serialize(Serializer &serializer) const override;
150240 static unique_ptr<AlterInfo> Deserialize(Deserializer &deserializer);
150241
150242 explicit ChangeOwnershipInfo();
150243};
150244
150245
150246
150247
150248struct SetCommentInfo : public AlterInfo {
150249 SetCommentInfo(CatalogType entry_catalog_type, string entry_catalog, string entry_schema, string entry_name,
150250 Value new_comment_value_p, OnEntryNotFound if_not_found);
150251
150252 CatalogType entry_catalog_type;
150253 Value comment_value;
150254
150255public:
150256 CatalogType GetCatalogType() const override;
150257 unique_ptr<AlterInfo> Copy() const override;
150258 string ToString() const override;
150259
150260 void Serialize(Serializer &serializer) const override;
150261 static unique_ptr<AlterInfo> Deserialize(Deserializer &deserializer);
150262
150263 explicit SetCommentInfo();
150264};
150265
150266
150267
150268
150269enum class AlterTableType :
uint8_t {
150270 INVALID = 0,
150271 RENAME_COLUMN = 1,
150272 RENAME_TABLE = 2,
150273 ADD_COLUMN = 3,
150274 REMOVE_COLUMN = 4,
150275 ALTER_COLUMN_TYPE = 5,
150276 SET_DEFAULT = 6,
150277 FOREIGN_KEY_CONSTRAINT = 7,
150278 SET_NOT_NULL = 8,
150279 DROP_NOT_NULL = 9,
150280 SET_COLUMN_COMMENT = 10,
150281 ADD_CONSTRAINT = 11,
150282 SET_PARTITIONED_BY = 12,
150283 SET_SORTED_BY = 13,
150284 ADD_FIELD = 14,
150285 REMOVE_FIELD = 15,
150286 RENAME_FIELD = 16,
150287 SET_TABLE_OPTIONS = 17,
150288 RESET_TABLE_OPTIONS = 18,
150289};
150290
150291struct AlterTableInfo : public AlterInfo {
150292 AlterTableInfo(AlterTableType type, AlterEntryData data);
150293 ~AlterTableInfo() override;
150294
150295 AlterTableType alter_table_type;
150296
150297public:
150298 CatalogType GetCatalogType() const override;
150299
150300 void Serialize(Serializer &serializer) const override;
150301 static unique_ptr<AlterInfo> Deserialize(Deserializer &deserializer);
150302
150303protected:
150304 explicit AlterTableInfo(AlterTableType type);
150305};
150306
150307
150308
150309
150310struct RenameColumnInfo : public AlterTableInfo {
150311 RenameColumnInfo(AlterEntryData data, string old_name_p, string new_name_p);
150312 ~RenameColumnInfo() override;
150313
150315 string old_name;
150317 string new_name;
150318
150319public:
150320 unique_ptr<AlterInfo> Copy() const override;
150321 string ToString() const override;
150322
150323 void Serialize(Serializer &serializer) const override;
150324 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
150325
150326private:
150327 RenameColumnInfo();
150328};
150329
150330
150331
150332
150333struct RenameFieldInfo : public AlterTableInfo {
150334 RenameFieldInfo(AlterEntryData data, vector<string> column_path, string new_name_p);
150335 ~RenameFieldInfo() override;
150336
150338 vector<string> column_path;
150340 string new_name;
150341
150342public:
150343 unique_ptr<AlterInfo> Copy() const override;
150344 string ToString() const override;
150345 string GetColumnName() const override {
150346 return column_path[0];
150347 }
150348
150349 void Serialize(Serializer &serializer) const override;
150350 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
150351
150352private:
150353 RenameFieldInfo();
150354};
150355
150356
150357
150358
150359struct RenameTableInfo : public AlterTableInfo {
150360 RenameTableInfo(AlterEntryData data, string new_name);
150361 ~RenameTableInfo() override;
150362
150364 string new_table_name;
150365
150366public:
150367 unique_ptr<AlterInfo> Copy() const override;
150368 string ToString() const override;
150369
150370 void Serialize(Serializer &serializer) const override;
150371 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
150372
150373private:
150374 RenameTableInfo();
150375};
150376
150377
150378
150379
150380struct AddColumnInfo : public AlterTableInfo {
150381 AddColumnInfo(AlterEntryData data, ColumnDefinition new_column, bool if_column_not_exists);
150382 ~AddColumnInfo() override;
150383
150385 ColumnDefinition new_column;
150387 bool if_column_not_exists;
150388
150389public:
150390 unique_ptr<AlterInfo> Copy() const override;
150391 string ToString() const override;
150392
150393 void Serialize(Serializer &serializer) const override;
150394 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
150395
150396private:
150397 explicit AddColumnInfo(ColumnDefinition new_column);
150398};
150399
150400
150401
150402
150403struct AddFieldInfo : public AlterTableInfo {
150404 AddFieldInfo(AlterEntryData data, vector<string> column_path, ColumnDefinition new_field, bool if_field_not_exists);
150405 ~AddFieldInfo() override;
150406
150408 vector<string> column_path;
150410 ColumnDefinition new_field;
150412 bool if_field_not_exists;
150413
150414public:
150415 unique_ptr<AlterInfo> Copy() const override;
150416 string ToString() const override;
150417 string GetColumnName() const override {
150418 return column_path[0];
150419 }
150420
150421 void Serialize(Serializer &serializer) const override;
150422 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
150423
150424private:
150425 explicit AddFieldInfo(ColumnDefinition new_column);
150426};
150427
150428
150429
150430
150431struct RemoveColumnInfo : public AlterTableInfo {
150432 RemoveColumnInfo(AlterEntryData data, string removed_column, bool if_column_exists, bool cascade);
150433 ~RemoveColumnInfo() override;
150434
150436 string removed_column;
150438 bool if_column_exists;
150440 bool cascade;
150441
150442public:
150443 unique_ptr<AlterInfo> Copy() const override;
150444 string ToString() const override;
150445 void Serialize(Serializer &serializer) const override;
150446 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
150447 string GetColumnName() const override {
150448 return removed_column;
150449 }
150450
150451private:
150452 RemoveColumnInfo();
150453};
150454
150455
150456
150457
150458struct RemoveFieldInfo : public AlterTableInfo {
150459 RemoveFieldInfo(AlterEntryData data, vector<string> column_path, bool if_column_exists, bool cascade);
150460 ~RemoveFieldInfo() override;
150461
150463 vector<string> column_path;
150465 bool if_column_exists;
150467 bool cascade;
150468
150469public:
150470 unique_ptr<AlterInfo> Copy() const override;
150471 string ToString() const override;
150472 string GetColumnName() const override {
150473 return column_path[0];
150474 }
150475
150476 void Serialize(Serializer &serializer) const override;
150477 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
150478
150479private:
150480 RemoveFieldInfo();
150481};
150482
150483
150484
150485struct ChangeColumnTypeInfo : public AlterTableInfo {
150486 ChangeColumnTypeInfo(AlterEntryData data, string column_name, LogicalType target_type,
150487 unique_ptr<ParsedExpression> expression);
150488 ~ChangeColumnTypeInfo() override;
150489
150491 string column_name;
150493 LogicalType target_type;
150495 unique_ptr<ParsedExpression> expression;
150496
150497public:
150498 unique_ptr<AlterInfo> Copy() const override;
150499 string ToString() const override;
150500 void Serialize(Serializer &serializer) const override;
150501 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
150502 string GetColumnName() const override {
150503 return column_name;
150504 };
150505
150506private:
150507 ChangeColumnTypeInfo();
150508};
150509
150510
150511
150512
150513struct SetDefaultInfo : public AlterTableInfo {
150514 SetDefaultInfo(AlterEntryData data, string column_name, unique_ptr<ParsedExpression> new_default);
150515 ~SetDefaultInfo() override;
150516
150518 string column_name;
150520 unique_ptr<ParsedExpression> expression;
150521
150522public:
150523 unique_ptr<AlterInfo> Copy() const override;
150524 string ToString() const override;
150525 void Serialize(Serializer &serializer) const override;
150526 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
150527
150528private:
150529 SetDefaultInfo();
150530};
150531
150532
150533
150534
150535struct AlterForeignKeyInfo : public AlterTableInfo {
150536 AlterForeignKeyInfo(AlterEntryData data, string fk_table, vector<string> pk_columns, vector<string> fk_columns,
150537 vector<PhysicalIndex> pk_keys, vector<PhysicalIndex> fk_keys, AlterForeignKeyType type);
150538 ~AlterForeignKeyInfo() override;
150539
150540 string fk_table;
150541 vector<string> pk_columns;
150542 vector<string> fk_columns;
150543 vector<PhysicalIndex> pk_keys;
150544 vector<PhysicalIndex> fk_keys;
150545 AlterForeignKeyType type;
150546
150547public:
150548 unique_ptr<AlterInfo> Copy() const override;
150549 string ToString() const override;
150550 void Serialize(Serializer &serializer) const override;
150551 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
150552
150553private:
150554 AlterForeignKeyInfo();
150555};
150556
150557
150558
150559
150560struct SetNotNullInfo : public AlterTableInfo {
150561 SetNotNullInfo(AlterEntryData data, string column_name);
150562 ~SetNotNullInfo() override;
150563
150565 string column_name;
150566
150567public:
150568 unique_ptr<AlterInfo> Copy() const override;
150569 string ToString() const override;
150570 void Serialize(Serializer &serializer) const override;
150571 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
150572
150573private:
150574 SetNotNullInfo();
150575};
150576
150577
150578
150579
150580struct DropNotNullInfo : public AlterTableInfo {
150581 DropNotNullInfo(AlterEntryData data, string column_name);
150582 ~DropNotNullInfo() override;
150583
150585 string column_name;
150586
150587public:
150588 unique_ptr<AlterInfo> Copy() const override;
150589 string ToString() const override;
150590 void Serialize(Serializer &serializer) const override;
150591 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
150592
150593private:
150594 DropNotNullInfo();
150595};
150596
150597
150598
150599
150600enum class AlterViewType :
uint8_t { INVALID = 0, RENAME_VIEW = 1 };
150601
150602struct AlterViewInfo : public AlterInfo {
150603 AlterViewInfo(AlterViewType type, AlterEntryData data);
150604 ~AlterViewInfo() override;
150605
150606 AlterViewType alter_view_type;
150607
150608public:
150609 CatalogType GetCatalogType() const override;
150610 void Serialize(Serializer &serializer) const override;
150611 static unique_ptr<AlterInfo> Deserialize(Deserializer &deserializer);
150612
150613protected:
150614 explicit AlterViewInfo(AlterViewType type);
150615};
150616
150617
150618
150619
150620struct RenameViewInfo : public AlterViewInfo {
150621 RenameViewInfo(AlterEntryData data, string new_name);
150622 ~RenameViewInfo() override;
150623
150625 string new_view_name;
150626
150627public:
150628 unique_ptr<AlterInfo> Copy() const override;
150629 string ToString() const override;
150630 void Serialize(Serializer &serializer) const override;
150631 static unique_ptr<AlterViewInfo> Deserialize(Deserializer &deserializer);
150632
150633private:
150634 RenameViewInfo();
150635};
150636
150637
150638
150639
150640struct AddConstraintInfo : public AlterTableInfo {
150641 AddConstraintInfo(AlterEntryData data, unique_ptr<Constraint> constraint);
150642 ~AddConstraintInfo() override;
150643
150645 unique_ptr<Constraint> constraint;
150646
150647public:
150648 unique_ptr<AlterInfo> Copy() const override;
150649 string ToString() const override;
150650 void Serialize(Serializer &serializer) const override;
150651 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
150652
150653private:
150654 AddConstraintInfo();
150655};
150656
150657
150658
150659
150660struct SetPartitionedByInfo : public AlterTableInfo {
150661 SetPartitionedByInfo(AlterEntryData data, vector<unique_ptr<ParsedExpression>> partition_keys);
150662 ~SetPartitionedByInfo() override;
150663
150665 vector<unique_ptr<ParsedExpression>> partition_keys;
150666
150667public:
150668 unique_ptr<AlterInfo> Copy() const override;
150669 string ToString() const override;
150670 void Serialize(Serializer &serializer) const override;
150671 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
150672
150673private:
150674 SetPartitionedByInfo();
150675};
150676
150677
150678
150679
150680struct SetSortedByInfo : public AlterTableInfo {
150681 SetSortedByInfo(AlterEntryData data, vector<OrderByNode> orders);
150682 ~SetSortedByInfo() override;
150683
150685 vector<OrderByNode> orders;
150686
150687public:
150688 unique_ptr<AlterInfo> Copy() const override;
150689 string ToString() const override;
150690 void Serialize(Serializer &serializer) const override;
150691 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
150692
150693private:
150694 SetSortedByInfo();
150695};
150696
150697
150698
150699
150700struct SetTableOptionsInfo : public AlterTableInfo {
150701 SetTableOptionsInfo(AlterEntryData data, case_insensitive_map_t<unique_ptr<ParsedExpression>> table_options);
150702 ~SetTableOptionsInfo() override;
150703
150704 case_insensitive_map_t<unique_ptr<ParsedExpression>> table_options;
150705
150706public:
150707 unique_ptr<AlterInfo> Copy() const override;
150708 string ToString() const override;
150709
150710 void Serialize(Serializer &serializer) const override;
150711 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
150712
150713private:
150714 SetTableOptionsInfo();
150715};
150716
150717
150718
150719
150720struct ResetTableOptionsInfo : public AlterTableInfo {
150721 ResetTableOptionsInfo(AlterEntryData data, case_insensitive_set_t table_options);
150722 ~ResetTableOptionsInfo() override;
150723
150724 case_insensitive_set_t table_options;
150725
150726public:
150727 unique_ptr<AlterInfo> Copy() const override;
150728 string ToString() const override;
150729
150730 void Serialize(Serializer &serializer) const override;
150731 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
150732
150733private:
150734 ResetTableOptionsInfo();
150735};
150736
150737}
150738
150739
150740namespace duckdb {
150741class DuckTransaction;
150742class SequenceCatalogEntry;
150743
150744struct SequenceValue {
150745 SequenceCatalogEntry *entry;
150748};
150749
150750struct SequenceData {
150751 explicit SequenceData(CreateSequenceInfo &info);
150752
150768 bool cycle;
150769};
150770
150772class SequenceCatalogEntry : public StandardEntry {
150773public:
150774 static constexpr const CatalogType Type = CatalogType::SEQUENCE_ENTRY;
150775 static constexpr const char *Name = "sequence";
150776
150777public:
150779 SequenceCatalogEntry(Catalog &catalog, SchemaCatalogEntry &schema, CreateSequenceInfo &info);
150780
150781public:
150782 unique_ptr<CatalogEntry> Copy(ClientContext &context) const override;
150783 unique_ptr<CreateInfo> GetInfo() const override;
150784
150785 SequenceData GetData() const;
150787 int64_t NextValue(DuckTransaction &transaction);
150788 void ReplayValue(uint64_t usage_count, int64_t counter);
150789
150790 string ToSQL() const override;
150791
150792private:
150794 mutable mutex lock;
150796 SequenceData data;
150797};
150798}
150799
150800
150801
150802
150803
150804
150805namespace duckdb {
150806class Catalog;
150807class SequenceCatalogEntry;
150808class SchemaCatalogEntry;
150809
150810class AttachedDatabase;
150811class ColumnData;
150812class ClientContext;
150813class CatalogEntry;
150814class DataTable;
150815class DatabaseInstance;
150816class LocalStorage;
150817class MetaTransaction;
150818class TransactionManager;
150819class WriteAheadLog;
150820
150821class ChunkVectorInfo;
150822
150823struct DeleteInfo;
150824struct UpdateInfo;
150825struct DatabaseModificationType;
150826
150829class Transaction {
150830public:
150831 DUCKDB_API Transaction(TransactionManager &manager, ClientContext &context);
150832 DUCKDB_API virtual ~Transaction();
150833
150834 TransactionManager &manager;
150835 weak_ptr<ClientContext> context;
150838 atomic<transaction_t> active_query;
150839
150840public:
150841 DUCKDB_API static Transaction &Get(ClientContext &context, AttachedDatabase &db);
150842 DUCKDB_API static Transaction &Get(ClientContext &context, Catalog &catalog);
150844 DUCKDB_API static optional_ptr<Transaction> TryGet(ClientContext &context, AttachedDatabase &db);
150845
150847 DUCKDB_API bool IsReadOnly();
150849 DUCKDB_API virtual void SetReadWrite();
150851 DUCKDB_API virtual void SetModifications(DatabaseModificationType type);
150852
150853 virtual bool IsDuckTransaction() const {
150854 return false;
150855 }
150856
150857public:
150858 template <class TARGET>
150859 TARGET &Cast() {
150860 DynamicCastCheck<TARGET>(this);
150861 return reinterpret_cast<TARGET &>(*this);
150862 }
150863 template <class TARGET>
150864 const TARGET &Cast() const {
150865 DynamicCastCheck<TARGET>(this);
150866 return reinterpret_cast<const TARGET &>(*this);
150867 }
150868
150869private:
150870 bool is_read_only;
150871};
150872
150873}
150874
150875
150876
150877
150878
150879
150880
150881
150882
150883
150884
150885
150886
150887
150888
150889namespace duckdb {
150890class SchemaCatalogEntry;
150891
150893struct SimilarCatalogEntry {
150895 string name;
150897 double score = 0.0;
150899 optional_ptr<SchemaCatalogEntry> schema;
150900
150901 bool Found() const {
150902 return !name.empty();
150903 }
150904
150905 DUCKDB_API string GetQualifiedName(bool qualify_catalog, bool qualify_schema) const;
150906};
150907
150908}
150909
150910#include <functional>
150911#include <memory>
150912
150913namespace duckdb {
150914struct AlterInfo;
150915struct ChangeOwnershipInfo;
150916
150917class ClientContext;
150918class LogicalDependencyList;
150919
150920class DuckCatalog;
150921class TableCatalogEntry;
150922class SequenceCatalogEntry;
150923
150924class CatalogEntryMap {
150925public:
150926 CatalogEntryMap() {
150927 }
150928
150929public:
150930 void AddEntry(unique_ptr<CatalogEntry> entry);
150931 void UpdateEntry(unique_ptr<CatalogEntry> entry);
150932 void DropEntry(CatalogEntry &entry);
150933 case_insensitive_tree_t<unique_ptr<CatalogEntry>> &Entries();
150934 optional_ptr<CatalogEntry> GetEntry(const string &name);
150935
150936private:
150938 case_insensitive_tree_t<unique_ptr<CatalogEntry>> entries;
150939};
150940
150942class CatalogSet {
150943public:
150944 struct EntryLookup {
150945 enum class FailureReason { SUCCESS, DELETED, NOT_PRESENT, INVISIBLE };
150946 optional_ptr<CatalogEntry> result;
150947 FailureReason reason;
150948 };
150949
150950public:
150951 DUCKDB_API explicit CatalogSet(Catalog &catalog, unique_ptr<DefaultGenerator> defaults = nullptr);
150952 ~CatalogSet();
150953
150956 DUCKDB_API bool CreateEntry(CatalogTransaction transaction, const string &name, unique_ptr<CatalogEntry> value,
150957 const LogicalDependencyList &dependencies);
150958 DUCKDB_API bool CreateEntry(ClientContext &context, const string &name, unique_ptr<CatalogEntry> value,
150959 const LogicalDependencyList &dependencies);
150960
150961 DUCKDB_API bool AlterEntry(CatalogTransaction transaction, const string &name, AlterInfo &alter_info);
150962
150963 DUCKDB_API bool DropEntry(CatalogTransaction transaction, const string &name, bool cascade,
150964 bool allow_drop_internal = false);
150965 DUCKDB_API bool DropEntry(ClientContext &context, const string &name, bool cascade,
150966 bool allow_drop_internal = false);
150968 DUCKDB_API void VerifyExistenceOfDependency(transaction_t commit_id, CatalogEntry &entry);
150970 DUCKDB_API void CommitDrop(transaction_t commit_id, transaction_t start_time, CatalogEntry &entry);
150971
150972 DUCKDB_API DuckCatalog &GetCatalog();
150973
150974 bool AlterOwnership(CatalogTransaction transaction, ChangeOwnershipInfo &info);
150975
150976 void CleanupEntry(CatalogEntry &catalog_entry);
150977
150979 DUCKDB_API EntryLookup GetEntryDetailed(CatalogTransaction transaction, const string &name);
150980 DUCKDB_API optional_ptr<CatalogEntry> GetEntry(CatalogTransaction transaction, const string &name);
150981 DUCKDB_API optional_ptr<CatalogEntry> GetEntry(ClientContext &context, const string &name);
150982
150985 SimilarCatalogEntry SimilarEntry(CatalogTransaction transaction, const string &name);
150986
150989 void Undo(CatalogEntry &entry);
150990
150992 DUCKDB_API void Scan(const std::function<void(CatalogEntry &)> &callback);
150994 DUCKDB_API void ScanWithPrefix(CatalogTransaction transaction, const std::function<void(CatalogEntry &)> &callback,
150995 const string &prefix);
150996 DUCKDB_API void Scan(CatalogTransaction transaction, const std::function<void(CatalogEntry &)> &callback);
150997 DUCKDB_API void ScanWithReturn(CatalogTransaction transaction, const std::function<bool(CatalogEntry &)> &callback);
150998 DUCKDB_API void Scan(ClientContext &context, const std::function<void(CatalogEntry &)> &callback);
150999 DUCKDB_API void ScanWithReturn(ClientContext &context, const std::function<bool(CatalogEntry &)> &callback);
151000
151001 template <class T>
151002 vector<reference<T>> GetEntries(CatalogTransaction transaction) {
151003 vector<reference<T>> result;
151004 Scan(transaction, [&](CatalogEntry &entry) { result.push_back(entry.Cast<T>()); });
151005 return result;
151006 }
151007
151008 DUCKDB_API bool CreatedByOtherActiveTransaction(CatalogTransaction transaction, transaction_t timestamp);
151009 DUCKDB_API bool CommittedAfterStarting(CatalogTransaction transaction, transaction_t timestamp);
151010 DUCKDB_API bool HasConflict(CatalogTransaction transaction, transaction_t timestamp);
151011 DUCKDB_API bool UseTimestamp(CatalogTransaction transaction, transaction_t timestamp);
151012 static bool IsCommitted(transaction_t timestamp);
151013
151014 static void UpdateTimestamp(CatalogEntry &entry, transaction_t timestamp);
151015
151016 mutex &GetCatalogLock() {
151017 return catalog_lock;
151018 }
151019
151020 void Verify(Catalog &catalog);
151021
151023 void SetDefaultGenerator(unique_ptr<DefaultGenerator> defaults);
151024
151025private:
151026 bool DropDependencies(CatalogTransaction transaction, const string &name, bool cascade,
151027 bool allow_drop_internal = false);
151030 CatalogEntry &GetEntryForTransaction(CatalogTransaction transaction, CatalogEntry ¤t, bool &visible);
151032 CatalogEntry &GetEntryForTransaction(CatalogTransaction transaction, CatalogEntry ¤t);
151033 CatalogEntry &GetCommittedEntry(CatalogEntry ¤t);
151034 optional_ptr<CatalogEntry> GetEntryInternal(CatalogTransaction transaction, const string &name);
151035 optional_ptr<CatalogEntry> CreateCommittedEntry(unique_ptr<CatalogEntry> entry);
151036
151038 void CreateDefaultEntries(CatalogTransaction transaction, unique_lock<mutex> &lock);
151040 optional_ptr<CatalogEntry> CreateDefaultEntry(CatalogTransaction transaction, const string &name,
151041 unique_lock<mutex> &lock);
151042
151043 bool DropEntryInternal(CatalogTransaction transaction, const string &name, bool allow_drop_internal = false);
151044
151045 bool CreateEntryInternal(CatalogTransaction transaction, const string &name, unique_ptr<CatalogEntry> value,
151046 unique_lock<mutex> &read_lock, bool should_be_empty = true);
151047 void CheckCatalogEntryInvariants(CatalogEntry &value, const string &name);
151049 bool VerifyVacancy(CatalogTransaction transaction, CatalogEntry &entry);
151051 bool StartChain(CatalogTransaction transaction, const string &name, unique_lock<mutex> &read_lock);
151052 bool RenameEntryInternal(CatalogTransaction transaction, CatalogEntry &old, const string &new_name,
151053 AlterInfo &alter_info, unique_lock<mutex> &read_lock);
151054
151055private:
151056 DuckCatalog &catalog;
151058 mutex catalog_lock;
151059 CatalogEntryMap map;
151061 unique_ptr<DefaultGenerator> defaults;
151062};
151063}
151064
151065
151066
151067namespace duckdb {
151068class ClientContext;
151069
151070class StandardEntry;
151071class TableCatalogEntry;
151072class TableFunctionCatalogEntry;
151073class SequenceCatalogEntry;
151074
151075enum class OnCreateConflict :
uint8_t;
151076
151077struct AlterTableInfo;
151078struct CreateIndexInfo;
151079struct CreateFunctionInfo;
151080struct CreateCollationInfo;
151081struct CreateCoordinateSystemInfo;
151082struct CreateViewInfo;
151083struct BoundCreateTableInfo;
151084struct CreatePragmaFunctionInfo;
151085struct CreateSequenceInfo;
151086struct CreateSchemaInfo;
151087struct CreateTableFunctionInfo;
151088struct CreateCopyFunctionInfo;
151089struct CreateTypeInfo;
151090
151091struct DropInfo;
151092
151094class SchemaCatalogEntry : public InCatalogEntry {
151095public:
151096 static constexpr const CatalogType Type = CatalogType::SCHEMA_ENTRY;
151097 static constexpr const char *Name = "schema";
151098
151099public:
151100 SchemaCatalogEntry(Catalog &catalog, CreateSchemaInfo &info);
151101
151102public:
151103 unique_ptr<CreateInfo> GetInfo() const override;
151104
151106 virtual void Scan(ClientContext &context, CatalogType type,
151107 const std::function<void(CatalogEntry &)> &callback) = 0;
151109 virtual void Scan(CatalogType type, const std::function<void(CatalogEntry &)> &callback) = 0;
151110
151111 string ToSQL() const override;
151112
151114 virtual optional_ptr<CatalogEntry> CreateIndex(CatalogTransaction transaction, CreateIndexInfo &info,
151115 TableCatalogEntry &table) = 0;
151116 optional_ptr<CatalogEntry> CreateIndex(ClientContext &context, CreateIndexInfo &info, TableCatalogEntry &table);
151118 virtual optional_ptr<CatalogEntry> CreateFunction(CatalogTransaction transaction, CreateFunctionInfo &info) = 0;
151120 virtual optional_ptr<CatalogEntry> CreateTable(CatalogTransaction transaction, BoundCreateTableInfo &info) = 0;
151122 virtual optional_ptr<CatalogEntry> CreateView(CatalogTransaction transaction, CreateViewInfo &info) = 0;
151124 virtual optional_ptr<CatalogEntry> CreateSequence(CatalogTransaction transaction, CreateSequenceInfo &info) = 0;
151126 virtual optional_ptr<CatalogEntry> CreateTableFunction(CatalogTransaction transaction,
151127 CreateTableFunctionInfo &info) = 0;
151129 virtual optional_ptr<CatalogEntry> CreateCopyFunction(CatalogTransaction transaction,
151130 CreateCopyFunctionInfo &info) = 0;
151132 virtual optional_ptr<CatalogEntry> CreatePragmaFunction(CatalogTransaction transaction,
151133 CreatePragmaFunctionInfo &info) = 0;
151135 virtual optional_ptr<CatalogEntry> CreateCollation(CatalogTransaction transaction, CreateCollationInfo &info) = 0;
151137 virtual optional_ptr<CatalogEntry> CreateCoordinateSystem(CatalogTransaction transaction,
151138 CreateCoordinateSystemInfo &info) {
151139 throw NotImplementedException("Coordinate systems are not supported in schema '%s'", name);
151140 }
151141
151143 virtual optional_ptr<CatalogEntry> CreateType(CatalogTransaction transaction, CreateTypeInfo &info) = 0;
151144
151146 DUCKDB_API virtual optional_ptr<CatalogEntry> LookupEntry(CatalogTransaction transaction,
151147 const EntryLookupInfo &lookup_info) = 0;
151148 DUCKDB_API virtual CatalogSet::EntryLookup LookupEntryDetailed(CatalogTransaction transaction,
151149 const EntryLookupInfo &lookup_info);
151150 DUCKDB_API virtual SimilarCatalogEntry GetSimilarEntry(CatalogTransaction transaction,
151151 const EntryLookupInfo &lookup_info);
151152
151153 DUCKDB_API optional_ptr<CatalogEntry> GetEntry(CatalogTransaction transaction, CatalogType type,
151154 const string &name);
151155
151157 virtual void DropEntry(ClientContext &context, DropInfo &info) = 0;
151158
151160 virtual void Alter(CatalogTransaction transaction, AlterInfo &info) = 0;
151161
151162 CatalogTransaction GetCatalogTransaction(ClientContext &context);
151163};
151164}
151165
151166
151167
151168
151169
151170
151171
151172
151173
151174
151175
151176
151177
151178
151179
151180
151181
151182
151183#include <deque>
151184
151185namespace duckdb {
151186
151187template <class DATA_TYPE, bool SAFE = true>
151188class deque : public std::deque<DATA_TYPE, std::allocator<DATA_TYPE>> {
151189public:
151190 using original = std::deque<DATA_TYPE, std::allocator<DATA_TYPE>>;
151191 using original::original;
151192 using value_type =
typename original::value_type;
151193 using allocator_type = typename original::allocator_type;
151194 using size_type = typename original::size_type;
151195 using difference_type = typename original::difference_type;
151196 using reference = typename original::reference;
151197 using const_reference = typename original::const_reference;
151198 using pointer = typename original::pointer;
151199 using const_pointer = typename original::const_pointer;
151200 using iterator = typename original::iterator;
151201 using const_iterator = typename original::const_iterator;
151202 using reverse_iterator = typename original::reverse_iterator;
151203 using const_reverse_iterator = typename original::const_reverse_iterator;
151204
151205private:
151206 static inline void AssertIndexInBounds(idx_t index, idx_t size) {
151207#if defined(DUCKDB_DEBUG_NO_SAFETY) || defined(DUCKDB_CLANG_TIDY)
151208 return;
151209#else
151210 if (DUCKDB_UNLIKELY(index >= size)) {
151211 throw InternalException("Attempted to access index %ld within deque of size %ld", index, size);
151212 }
151213#endif
151214 }
151215
151216public:
151217#ifdef DUCKDB_CLANG_TIDY
151218 [[clang::reinitializes]]
151219#endif
151220 inline void
151221 clear() noexcept {
151222 original::clear();
151223 }
151224
151225
151226
151227 deque() = default;
151228 deque(original &&other) : original(std::move(other)) {
151229 }
151230 template <bool INTERNAL_SAFE>
151231 deque(deque<DATA_TYPE, INTERNAL_SAFE> &&other) : original(std::move(other)) {
151232 }
151233
151234 template <bool INTERNAL_SAFE = false>
151235 inline typename original::reference
get(
typename original::size_type __n) {
151236 if (MemorySafety<INTERNAL_SAFE>::ENABLED) {
151237 AssertIndexInBounds(__n, original::size());
151238 }
151239 return original::operator[](__n);
151240 }
151241
151242 template <bool INTERNAL_SAFE = false>
151243 inline typename original::const_reference
get(
typename original::size_type __n)
const {
151244 if (MemorySafety<INTERNAL_SAFE>::ENABLED) {
151245 AssertIndexInBounds(__n, original::size());
151246 }
151247 return original::operator[](__n);
151248 }
151249
151250 typename original::reference operator[](typename original::size_type __n) {
151252 }
151253 typename original::const_reference operator[](typename original::size_type __n) const {
151255 }
151256
151257 typename original::reference front() {
151258 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
151259 throw InternalException("'front' called on an empty deque!");
151260 }
151262 }
151263
151264 typename original::const_reference front() const {
151265 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
151266 throw InternalException("'front' called on an empty deque!");
151267 }
151269 }
151270
151271 typename original::reference back() {
151272 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
151273 throw InternalException("'back' called on an empty deque!");
151274 }
151275 return get<SAFE>(original::size() - 1);
151276 }
151277
151278 typename original::const_reference back() const {
151279 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
151280 throw InternalException("'back' called on an empty deque!");
151281 }
151282 return get<SAFE>(original::size() - 1);
151283 }
151284};
151285
151286template <typename T>
151287using unsafe_deque = deque<T, false>;
151288
151289}
151290
151291
151292
151293
151294
151295
151296
151297
151298
151299
151300
151301
151302
151303
151304namespace duckdb {
151305
151306enum class PreparedStatementMode :
uint8_t {
151307 PREPARE_ONLY,
151308 PREPARE_AND_EXECUTE,
151309};
151310
151311}
151312
151313
151314
151315
151316
151317
151318
151319
151320
151321
151322
151323
151324
151325
151326
151327
151328
151329
151330
151331
151332
151333
151334
151335
151336
151337
151338
151339
151340
151341namespace duckdb {
151342
151343enum class ExplainOutputType :
uint8_t { ALL = 0, OPTIMIZED_ONLY = 1, PHYSICAL_ONLY = 2 };
151344
151345}
151346
151347
151348
151349
151350
151351
151352
151353
151354
151355
151356
151357
151358
151359
151360
151361
151362
151363
151364
151365
151366
151367
151368
151369
151370
151371
151372
151373#ifndef DUCKDB_C_API
151374#ifdef _WIN32
151375#ifdef DUCKDB_STATIC_BUILD
151376#define DUCKDB_C_API
151377#else
151378#if defined(DUCKDB_BUILD_LIBRARY) && !defined(DUCKDB_BUILD_LOADABLE_EXTENSION)
151379#define DUCKDB_C_API __declspec(dllexport)
151380#else
151381#define DUCKDB_C_API __declspec(dllimport)
151382#endif
151383#endif
151384#else
151385#define DUCKDB_C_API
151386#endif
151387#endif
151388
151390#ifndef DUCKDB_EXTENSION_API
151391#ifdef _WIN32
151392#ifdef DUCKDB_STATIC_BUILD
151393#define DUCKDB_EXTENSION_API
151394#else
151395#define DUCKDB_EXTENSION_API __declspec(dllexport)
151396#endif
151397#else
151398#define DUCKDB_EXTENSION_API __attribute__((visibility("default")))
151399#endif
151400#endif
151401
151402#include <stdbool.h>
151403#include <stdint.h>
151404#include <stddef.h>
151405
151406#ifdef __cplusplus
151407extern "C" {
151408#endif
151409
151410
151411
151412
151413
151416
151418typedef enum DUCKDB_TYPE {
151419 DUCKDB_TYPE_INVALID = 0,
151420
151421 DUCKDB_TYPE_BOOLEAN = 1,
151422
151423 DUCKDB_TYPE_TINYINT = 2,
151424
151425 DUCKDB_TYPE_SMALLINT = 3,
151426
151427 DUCKDB_TYPE_INTEGER = 4,
151428
151429 DUCKDB_TYPE_BIGINT = 5,
151430
151431 DUCKDB_TYPE_UTINYINT = 6,
151432
151433 DUCKDB_TYPE_USMALLINT = 7,
151434
151435 DUCKDB_TYPE_UINTEGER = 8,
151436
151437 DUCKDB_TYPE_UBIGINT = 9,
151438
151439 DUCKDB_TYPE_FLOAT = 10,
151440
151441 DUCKDB_TYPE_DOUBLE = 11,
151442
151443 DUCKDB_TYPE_TIMESTAMP = 12,
151444
151445 DUCKDB_TYPE_DATE = 13,
151446
151447 DUCKDB_TYPE_TIME = 14,
151448
151449 DUCKDB_TYPE_INTERVAL = 15,
151450
151451 DUCKDB_TYPE_HUGEINT = 16,
151452
151453 DUCKDB_TYPE_UHUGEINT = 32,
151454
151455 DUCKDB_TYPE_VARCHAR = 17,
151456
151457 DUCKDB_TYPE_BLOB = 18,
151458
151459 DUCKDB_TYPE_DECIMAL = 19,
151460
151461 DUCKDB_TYPE_TIMESTAMP_S = 20,
151462
151463 DUCKDB_TYPE_TIMESTAMP_MS = 21,
151464
151465 DUCKDB_TYPE_TIMESTAMP_NS = 22,
151466
151467 DUCKDB_TYPE_ENUM = 23,
151468
151469 DUCKDB_TYPE_LIST = 24,
151470
151471 DUCKDB_TYPE_STRUCT = 25,
151472
151473 DUCKDB_TYPE_MAP = 26,
151474
151475 DUCKDB_TYPE_ARRAY = 33,
151476
151477 DUCKDB_TYPE_UUID = 27,
151478
151479 DUCKDB_TYPE_UNION = 28,
151480
151481 DUCKDB_TYPE_BIT = 29,
151482
151483 DUCKDB_TYPE_TIME_TZ = 30,
151484
151485 DUCKDB_TYPE_TIMESTAMP_TZ = 31,
151486
151487 DUCKDB_TYPE_ANY = 34,
151488
151489 DUCKDB_TYPE_BIGNUM = 35,
151490
151491 DUCKDB_TYPE_SQLNULL = 36,
151492
151493 DUCKDB_TYPE_STRING_LITERAL = 37,
151494
151495 DUCKDB_TYPE_INTEGER_LITERAL = 38,
151496
151497 DUCKDB_TYPE_TIME_NS = 39,
151498
151499 DUCKDB_TYPE_GEOMETRY = 40,
151500} duckdb_type;
151501
151503typedef enum duckdb_state { DuckDBSuccess = 0, DuckDBError = 1 } duckdb_state;
151504
151506typedef enum duckdb_pending_state {
151507 DUCKDB_PENDING_RESULT_READY = 0,
151508 DUCKDB_PENDING_RESULT_NOT_READY = 1,
151509 DUCKDB_PENDING_ERROR = 2,
151510 DUCKDB_PENDING_NO_TASKS_AVAILABLE = 3
151511} duckdb_pending_state;
151512
151514typedef enum duckdb_result_type {
151515 DUCKDB_RESULT_TYPE_INVALID = 0,
151516 DUCKDB_RESULT_TYPE_CHANGED_ROWS = 1,
151517 DUCKDB_RESULT_TYPE_NOTHING = 2,
151518 DUCKDB_RESULT_TYPE_QUERY_RESULT = 3,
151519} duckdb_result_type;
151520
151522typedef enum duckdb_statement_type {
151523 DUCKDB_STATEMENT_TYPE_INVALID = 0,
151524 DUCKDB_STATEMENT_TYPE_SELECT = 1,
151525 DUCKDB_STATEMENT_TYPE_INSERT = 2,
151526 DUCKDB_STATEMENT_TYPE_UPDATE = 3,
151527 DUCKDB_STATEMENT_TYPE_EXPLAIN = 4,
151528 DUCKDB_STATEMENT_TYPE_DELETE = 5,
151529 DUCKDB_STATEMENT_TYPE_PREPARE = 6,
151530 DUCKDB_STATEMENT_TYPE_CREATE = 7,
151531 DUCKDB_STATEMENT_TYPE_EXECUTE = 8,
151532 DUCKDB_STATEMENT_TYPE_ALTER = 9,
151533 DUCKDB_STATEMENT_TYPE_TRANSACTION = 10,
151534 DUCKDB_STATEMENT_TYPE_COPY = 11,
151535 DUCKDB_STATEMENT_TYPE_ANALYZE = 12,
151536 DUCKDB_STATEMENT_TYPE_VARIABLE_SET = 13,
151537 DUCKDB_STATEMENT_TYPE_CREATE_FUNC = 14,
151538 DUCKDB_STATEMENT_TYPE_DROP = 15,
151539 DUCKDB_STATEMENT_TYPE_EXPORT = 16,
151540 DUCKDB_STATEMENT_TYPE_PRAGMA = 17,
151541 DUCKDB_STATEMENT_TYPE_VACUUM = 18,
151542 DUCKDB_STATEMENT_TYPE_CALL = 19,
151543 DUCKDB_STATEMENT_TYPE_SET = 20,
151544 DUCKDB_STATEMENT_TYPE_LOAD = 21,
151545 DUCKDB_STATEMENT_TYPE_RELATION = 22,
151546 DUCKDB_STATEMENT_TYPE_EXTENSION = 23,
151547 DUCKDB_STATEMENT_TYPE_LOGICAL_PLAN = 24,
151548 DUCKDB_STATEMENT_TYPE_ATTACH = 25,
151549 DUCKDB_STATEMENT_TYPE_DETACH = 26,
151550 DUCKDB_STATEMENT_TYPE_MULTI = 27,
151551} duckdb_statement_type;
151552
151554typedef enum duckdb_error_type {
151555 DUCKDB_ERROR_INVALID = 0,
151556 DUCKDB_ERROR_OUT_OF_RANGE = 1,
151557 DUCKDB_ERROR_CONVERSION = 2,
151558 DUCKDB_ERROR_UNKNOWN_TYPE = 3,
151559 DUCKDB_ERROR_DECIMAL = 4,
151560 DUCKDB_ERROR_MISMATCH_TYPE = 5,
151561 DUCKDB_ERROR_DIVIDE_BY_ZERO = 6,
151562 DUCKDB_ERROR_OBJECT_SIZE = 7,
151563 DUCKDB_ERROR_INVALID_TYPE = 8,
151564 DUCKDB_ERROR_SERIALIZATION = 9,
151565 DUCKDB_ERROR_TRANSACTION = 10,
151566 DUCKDB_ERROR_NOT_IMPLEMENTED = 11,
151567 DUCKDB_ERROR_EXPRESSION = 12,
151568 DUCKDB_ERROR_CATALOG = 13,
151569 DUCKDB_ERROR_PARSER = 14,
151570 DUCKDB_ERROR_PLANNER = 15,
151571 DUCKDB_ERROR_SCHEDULER = 16,
151572 DUCKDB_ERROR_EXECUTOR = 17,
151573 DUCKDB_ERROR_CONSTRAINT = 18,
151574 DUCKDB_ERROR_INDEX = 19,
151575 DUCKDB_ERROR_STAT = 20,
151576 DUCKDB_ERROR_CONNECTION = 21,
151577 DUCKDB_ERROR_SYNTAX = 22,
151578 DUCKDB_ERROR_SETTINGS = 23,
151579 DUCKDB_ERROR_BINDER = 24,
151580 DUCKDB_ERROR_NETWORK = 25,
151581 DUCKDB_ERROR_OPTIMIZER = 26,
151582 DUCKDB_ERROR_NULL_POINTER = 27,
151583 DUCKDB_ERROR_IO = 28,
151584 DUCKDB_ERROR_INTERRUPT = 29,
151585 DUCKDB_ERROR_FATAL = 30,
151586 DUCKDB_ERROR_INTERNAL = 31,
151587 DUCKDB_ERROR_INVALID_INPUT = 32,
151588 DUCKDB_ERROR_OUT_OF_MEMORY = 33,
151589 DUCKDB_ERROR_PERMISSION = 34,
151590 DUCKDB_ERROR_PARAMETER_NOT_RESOLVED = 35,
151591 DUCKDB_ERROR_PARAMETER_NOT_ALLOWED = 36,
151592 DUCKDB_ERROR_DEPENDENCY = 37,
151593 DUCKDB_ERROR_HTTP = 38,
151594 DUCKDB_ERROR_MISSING_EXTENSION = 39,
151595 DUCKDB_ERROR_AUTOLOAD = 40,
151596 DUCKDB_ERROR_SEQUENCE = 41,
151597 DUCKDB_INVALID_CONFIGURATION = 42
151598} duckdb_error_type;
151599
151601typedef enum duckdb_cast_mode { DUCKDB_CAST_NORMAL = 0, DUCKDB_CAST_TRY = 1 } duckdb_cast_mode;
151602
151603typedef enum duckdb_file_flag {
151604 DUCKDB_FILE_FLAG_INVALID = 0,
151605
151606 DUCKDB_FILE_FLAG_READ = 1,
151607
151608 DUCKDB_FILE_FLAG_WRITE = 2,
151609
151610 DUCKDB_FILE_FLAG_CREATE = 3,
151611
151612 DUCKDB_FILE_FLAG_CREATE_NEW = 4,
151613
151614 DUCKDB_FILE_FLAG_APPEND = 5,
151615} duckdb_file_flag;
151616
151621typedef enum duckdb_config_option_scope {
151622 DUCKDB_CONFIG_OPTION_SCOPE_INVALID = 0,
151623
151624
151625 DUCKDB_CONFIG_OPTION_SCOPE_LOCAL = 1,
151626
151627 DUCKDB_CONFIG_OPTION_SCOPE_SESSION = 2,
151628
151629 DUCKDB_CONFIG_OPTION_SCOPE_GLOBAL = 3,
151630} duckdb_config_option_scope;
151631
151633typedef enum duckdb_catalog_entry_type {
151634 DUCKDB_CATALOG_ENTRY_TYPE_INVALID = 0,
151635 DUCKDB_CATALOG_ENTRY_TYPE_TABLE = 1,
151636 DUCKDB_CATALOG_ENTRY_TYPE_SCHEMA = 2,
151637 DUCKDB_CATALOG_ENTRY_TYPE_VIEW = 3,
151638 DUCKDB_CATALOG_ENTRY_TYPE_INDEX = 4,
151639 DUCKDB_CATALOG_ENTRY_TYPE_PREPARED_STATEMENT = 5,
151640 DUCKDB_CATALOG_ENTRY_TYPE_SEQUENCE = 6,
151641 DUCKDB_CATALOG_ENTRY_TYPE_COLLATION = 7,
151642 DUCKDB_CATALOG_ENTRY_TYPE_TYPE = 8,
151643 DUCKDB_CATALOG_ENTRY_TYPE_DATABASE = 9,
151644} duckdb_catalog_entry_type;
151645
151646
151647
151648
151649
151652
151655
151658typedef void (*duckdb_delete_callback_t)(void *data);
151659
151661typedef void *(*duckdb_copy_callback_t)(void *data);
151662
151665typedef void *duckdb_task_state;
151666
151667
151668
151669
151670
151673typedef struct {
151675} duckdb_date;
151676
151677typedef struct {
151681} duckdb_date_struct;
151682
151685typedef struct {
151687} duckdb_time;
151688
151689typedef struct {
151694} duckdb_time_struct;
151695
151697typedef struct {
151699} duckdb_time_ns;
151700
151703typedef struct {
151705} duckdb_time_tz;
151706
151707typedef struct {
151708 duckdb_time_struct time;
151710} duckdb_time_tz_struct;
151711
151714typedef struct {
151716} duckdb_timestamp;
151717
151718typedef struct {
151719 duckdb_date_struct date;
151720 duckdb_time_struct time;
151721} duckdb_timestamp_struct;
151722
151724typedef struct {
151726} duckdb_timestamp_s;
151727
151729typedef struct {
151731} duckdb_timestamp_ms;
151732
151734typedef struct {
151736} duckdb_timestamp_ns;
151737
151739typedef struct {
151743} duckdb_interval;
151744
151748typedef struct {
151751} duckdb_hugeint;
151752
151756typedef struct {
151759} duckdb_uhugeint;
151760
151763typedef struct {
151766 duckdb_hugeint value;
151767} duckdb_decimal;
151768
151770typedef struct {
151771 double percentage;
151774} duckdb_query_progress_type;
151775
151780typedef struct {
151781 union {
151782 struct {
151784 char prefix[4];
151785 char *ptr;
151786 } pointer;
151787 struct {
151789 char inlined[12];
151790 } inlined;
151791 } value;
151792} duckdb_string_t;
151793
151798typedef struct {
151801} duckdb_list_entry;
151802
151806typedef struct {
151807
151808 void *deprecated_data;
151809
151810 bool *deprecated_nullmask;
151811
151812 duckdb_type deprecated_type;
151813
151814 char *deprecated_name;
151815 void *internal_data;
151816} duckdb_column;
151817
151820typedef struct _duckdb_vector {
151821 void *internal_ptr;
151822} * duckdb_vector;
151823
151827typedef struct _duckdb_selection_vector {
151828 void *internal_ptr;
151829} * duckdb_selection_vector;
151830
151831
151832
151833
151834
151837typedef struct {
151838 char *data;
151840} duckdb_string;
151841
151844typedef struct {
151845 void *data;
151847} duckdb_blob;
151848
151854typedef struct {
151857} duckdb_bit;
151858
151862typedef struct {
151865 bool is_negative;
151866} duckdb_bignum;
151867
151870typedef struct {
151871
151872 idx_t deprecated_column_count;
151873
151874 idx_t deprecated_row_count;
151875
151876 idx_t deprecated_rows_changed;
151877
151878 duckdb_column *deprecated_columns;
151879
151880 char *deprecated_error_message;
151881 void *internal_data;
151882} duckdb_result;
151883
151885typedef struct _duckdb_instance_cache {
151886 void *internal_ptr;
151887} * duckdb_instance_cache;
151888
151890typedef struct _duckdb_database {
151891 void *internal_ptr;
151892} * duckdb_database;
151893
151895typedef struct _duckdb_connection {
151896 void *internal_ptr;
151897} * duckdb_connection;
151898
151900typedef struct _duckdb_client_context {
151901 void *internal_ptr;
151902} * duckdb_client_context;
151903
151906typedef struct _duckdb_prepared_statement {
151907 void *internal_ptr;
151908} * duckdb_prepared_statement;
151909
151911typedef struct _duckdb_extracted_statements {
151912 void *internal_ptr;
151913} * duckdb_extracted_statements;
151914
151917typedef struct _duckdb_pending_result {
151918 void *internal_ptr;
151919} * duckdb_pending_result;
151920
151923typedef struct _duckdb_appender {
151924 void *internal_ptr;
151925} * duckdb_appender;
151926
151929typedef struct _duckdb_table_description {
151930 void *internal_ptr;
151931} * duckdb_table_description;
151932
151935typedef struct _duckdb_config {
151936 void *internal_ptr;
151937} * duckdb_config;
151938
151941typedef struct _duckdb_config_option {
151942 void *internal_ptr;
151943} * duckdb_config_option;
151944
151947typedef struct _duckdb_logical_type {
151948 void *internal_ptr;
151949} * duckdb_logical_type;
151950
151953typedef struct _duckdb_create_type_info {
151954 void *internal_ptr;
151955} * duckdb_create_type_info;
151956
151959typedef struct _duckdb_data_chunk {
151960 void *internal_ptr;
151961} * duckdb_data_chunk;
151962
151965typedef struct _duckdb_value {
151966 void *internal_ptr;
151967} * duckdb_value;
151968
151971typedef struct _duckdb_profiling_info {
151972 void *internal_ptr;
151973} * duckdb_profiling_info;
151974
151977typedef struct _duckdb_error_data {
151978 void *internal_ptr;
151979} * duckdb_error_data;
151980
151983typedef struct _duckdb_expression {
151984 void *internal_ptr;
151985} * duckdb_expression;
151986
151987
151988
151989
151990
151992typedef struct _duckdb_extension_info {
151993 void *internal_ptr;
151994} * duckdb_extension_info;
151995
151996
151997
151998
151999
152002typedef struct _duckdb_function_info {
152003 void *internal_ptr;
152004} * duckdb_function_info;
152005
152008typedef struct _duckdb_bind_info {
152009 void *internal_ptr;
152010} * duckdb_bind_info;
152011
152014typedef struct _duckdb_init_info {
152015 void *internal_ptr;
152016} * duckdb_init_info;
152017
152018
152019
152020
152021
152023typedef struct _duckdb_scalar_function {
152024 void *internal_ptr;
152025} * duckdb_scalar_function;
152026
152028typedef struct _duckdb_scalar_function_set {
152029 void *internal_ptr;
152030} * duckdb_scalar_function_set;
152031
152033typedef void (*duckdb_scalar_function_bind_t)(duckdb_bind_info info);
152034
152036typedef void (*duckdb_scalar_function_init_t)(duckdb_init_info info);
152037
152039typedef void (*duckdb_scalar_function_t)(duckdb_function_info info, duckdb_data_chunk input, duckdb_vector output);
152040
152041
152042
152043
152044
152046typedef struct _duckdb_aggregate_function {
152047 void *internal_ptr;
152048} * duckdb_aggregate_function;
152049
152051typedef struct _duckdb_aggregate_function_set {
152052 void *internal_ptr;
152053} * duckdb_aggregate_function_set;
152054
152056typedef struct _duckdb_aggregate_state {
152057 void *internal_ptr;
152058} * duckdb_aggregate_state;
152059
152061typedef idx_t (*duckdb_aggregate_state_size)(duckdb_function_info info);
152062
152064typedef void (*duckdb_aggregate_init_t)(duckdb_function_info info, duckdb_aggregate_state state);
152065
152067typedef void (*duckdb_aggregate_destroy_t)(duckdb_aggregate_state *states,
idx_t count);
152068
152070typedef void (*duckdb_aggregate_update_t)(duckdb_function_info info, duckdb_data_chunk input,
152071 duckdb_aggregate_state *states);
152072
152074typedef void (*duckdb_aggregate_combine_t)(duckdb_function_info info, duckdb_aggregate_state *source,
152075 duckdb_aggregate_state *target,
idx_t count);
152076
152078typedef void (*duckdb_aggregate_finalize_t)(duckdb_function_info info, duckdb_aggregate_state *source,
152079 duckdb_vector result,
idx_t count,
idx_t offset);
152080
152081
152082
152083
152084
152086typedef struct _duckdb_table_function {
152087 void *internal_ptr;
152088} * duckdb_table_function;
152089
152091typedef void (*duckdb_table_function_bind_t)(duckdb_bind_info info);
152092
152094typedef void (*duckdb_table_function_init_t)(duckdb_init_info info);
152095
152097typedef void (*duckdb_table_function_t)(duckdb_function_info info, duckdb_data_chunk output);
152098
152099
152100
152101
152102
152104typedef struct _duckdb_copy_function {
152105 void *internal_ptr;
152106} * duckdb_copy_function;
152107
152109typedef struct _duckdb_copy_function_bind_info {
152110 void *internal_ptr;
152111} * duckdb_copy_function_bind_info;
152112
152114typedef struct _duckdb_copy_function_global_init_info {
152115 void *internal_ptr;
152116} * duckdb_copy_function_global_init_info;
152117
152119typedef struct _duckdb_copy_function_sink_info {
152120 void *internal_ptr;
152121} * duckdb_copy_function_sink_info;
152122
152124typedef struct _duckdb_copy_function_finalize_info {
152125 void *internal_ptr;
152126} * duckdb_copy_function_finalize_info;
152127
152129typedef void (*duckdb_copy_function_bind_t)(duckdb_copy_function_bind_info info);
152130
152132typedef void (*duckdb_copy_function_global_init_t)(duckdb_copy_function_global_init_info info);
152133
152135typedef void (*duckdb_copy_function_sink_t)(duckdb_copy_function_sink_info info, duckdb_data_chunk input);
152136
152138typedef void (*duckdb_copy_function_finalize_t)(duckdb_copy_function_finalize_info info);
152139
152140
152141
152142
152143
152145typedef struct _duckdb_cast_function {
152146 void *internal_ptr;
152147} * duckdb_cast_function;
152148
152150typedef bool (*duckdb_cast_function_t)(duckdb_function_info info,
idx_t count, duckdb_vector input,
152151 duckdb_vector output);
152152
152153
152154
152155
152156
152158typedef struct _duckdb_replacement_scan_info {
152159 void *internal_ptr;
152160} * duckdb_replacement_scan_info;
152161
152163typedef void (*duckdb_replacement_callback_t)(duckdb_replacement_scan_info info, const char *table_name, void *data);
152164
152165
152166
152167
152168
152172
152173struct ArrowArray;
152174
152175struct ArrowSchema;
152176
152178typedef struct _duckdb_arrow {
152179 void *internal_ptr;
152180} * duckdb_arrow;
152181
152183typedef struct _duckdb_arrow_stream {
152184 void *internal_ptr;
152185} * duckdb_arrow_stream;
152186
152188typedef struct _duckdb_arrow_schema {
152189 void *internal_ptr;
152190} * duckdb_arrow_schema;
152191
152196typedef struct _duckdb_arrow_converted_schema {
152197 void *internal_ptr;
152198} * duckdb_arrow_converted_schema;
152199
152201typedef struct _duckdb_arrow_array {
152202 void *internal_ptr;
152203} * duckdb_arrow_array;
152204
152207typedef struct _duckdb_arrow_options {
152208 void *internal_ptr;
152209} * duckdb_arrow_options;
152210
152211
152212
152213
152214
152215typedef struct _duckdb_file_open_options {
152216 void *internal_ptr;
152217} * duckdb_file_open_options;
152218
152219typedef struct _duckdb_file_system {
152220 void *internal_ptr;
152221} * duckdb_file_system;
152222
152223typedef struct _duckdb_file_handle {
152224 void *internal_ptr;
152225} * duckdb_file_handle;
152226
152227
152228
152229
152230
152233typedef struct _duckdb_catalog {
152234 void *internal_ptr;
152235} * duckdb_catalog;
152236
152239typedef struct _duckdb_catalog_entry {
152240 void *internal_ptr;
152241} * duckdb_catalog_entry;
152242
152243
152244
152245
152246
152248typedef struct _duckdb_log_storage {
152249 void *internal_ptr;
152250} * duckdb_log_storage;
152251
152253typedef void (*duckdb_logger_write_log_entry_t)(
void *extra_data, duckdb_timestamp *
timestamp,
const char *level,
152254 const char *log_type, const char *log_message);
152255
152256
152257
152258
152259
152261struct duckdb_extension_access {
152263 void (*set_error)(duckdb_extension_info info, const char *error);
152265 duckdb_database *(*get_database)(duckdb_extension_info info);
152267 const void *(*get_api)(duckdb_extension_info info, const char *version);
152268};
152269
152270#ifndef DUCKDB_API_EXCLUDE_FUNCTIONS
152271
152272
152273
152274
152275
152276
152277
152278
152279
152280
152281
152282
152291
152305 duckdb_database *out_database, duckdb_config config,
152306 char **out_error);
152307
152314
152324DUCKDB_C_API duckdb_state
duckdb_open(
const char *path, duckdb_database *out_database);
152325
152337DUCKDB_C_API duckdb_state
duckdb_open_ext(
const char *path, duckdb_database *out_database, duckdb_config config,
152338 char **out_error);
152339
152348DUCKDB_C_API
void duckdb_close(duckdb_database *database);
152349
152359DUCKDB_C_API duckdb_state
duckdb_connect(duckdb_database database, duckdb_connection *out_connection);
152360
152367
152375
152382
152390 duckdb_client_context *out_context);
152391
152398 duckdb_arrow_options *out_arrow_options);
152399
152407
152414
152421
152428
152439DUCKDB_C_API duckdb_value
duckdb_get_table_names(duckdb_connection connection,
const char *query,
bool qualified);
152440
152441
152442
152443
152444
152445
152446
152447
152462
152471
152483DUCKDB_C_API duckdb_state
duckdb_get_config_flag(
size_t index,
const char **out_name,
const char **out_description);
152484
152498DUCKDB_C_API duckdb_state
duckdb_set_config(duckdb_config config,
const char *name,
const char *option);
152499
152506
152507
152508
152509
152510
152511
152512
152513
152514
152524
152531
152539
152547
152555
152556
152557
152558
152559
152560
152561
152562
152576DUCKDB_C_API duckdb_state
duckdb_query(duckdb_connection connection,
const char *query, duckdb_result *out_result);
152577
152584
152596
152607
152615
152628
152637
152645
152646#ifndef DUCKDB_API_NO_DEPRECATED
152656
152657#endif
152658
152667
152668#ifndef DUCKDB_API_NO_DEPRECATED
152689
152712
152713#endif
152714
152724
152733
152734#ifndef DUCKDB_API_NO_DEPRECATED
152755
152765
152775
152776#endif
152777
152785
152786
152787
152788
152789
152790
152791
152792
152793
152794
152795
152796
152797
152798
152799
152800#ifndef DUCKDB_API_NO_DEPRECATED
152807
152814
152821
152828
152835
152841DUCKDB_C_API duckdb_hugeint
duckdb_value_hugeint(duckdb_result *result, idx_t col, idx_t row);
152842
152849
152855DUCKDB_C_API duckdb_decimal
duckdb_value_decimal(duckdb_result *result, idx_t col, idx_t row);
152856
152863
152870
152877
152884
152891
152898
152904DUCKDB_C_API duckdb_date
duckdb_value_date(duckdb_result *result, idx_t col, idx_t row);
152905
152911DUCKDB_C_API duckdb_time
duckdb_value_time(duckdb_result *result, idx_t col, idx_t row);
152912
152919
152926
152934
152940DUCKDB_C_API duckdb_string
duckdb_value_string(duckdb_result *result, idx_t col, idx_t row);
152941
152951
152961
152968DUCKDB_C_API duckdb_blob
duckdb_value_blob(duckdb_result *result, idx_t col, idx_t row);
152969
152976
152977#endif
152978
152979
152980
152981
152982
152983
152984
152985
152994
153002
153010
153017
153025
153033
153043
153044
153045
153046
153047
153048
153049
153050
153051
153059
153066DUCKDB_C_API duckdb_date
duckdb_to_date(duckdb_date_struct date);
153067
153075
153083
153092
153101
153108DUCKDB_C_API duckdb_time
duckdb_to_time(duckdb_time_struct time);
153109
153117
153125
153133
153141
153149
153157
153158
153159
153160
153161
153162
153163
153164
153172
153182
153190
153200
153201
153202
153203
153204
153205
153206
153207
153217
153225
153226
153227
153228
153229
153230
153231
153232
153233
153234
153235
153236
153237
153238
153239
153240
153254DUCKDB_C_API duckdb_state
duckdb_prepare(duckdb_connection connection,
const char *query,
153255 duckdb_prepared_statement *out_prepared_statement);
153256
153263
153274
153283
153292DUCKDB_C_API
const char *
duckdb_parameter_name(duckdb_prepared_statement prepared_statement, idx_t index);
153293
153303DUCKDB_C_API duckdb_type
duckdb_param_type(duckdb_prepared_statement prepared_statement, idx_t param_idx);
153304
153317 idx_t param_idx);
153318
153323
153331
153340
153352 idx_t col_idx);
153353
153364DUCKDB_C_API duckdb_logical_type
153366
153377 idx_t col_idx);
153378
153379
153380
153381
153382
153383
153384
153385
153386
153392DUCKDB_C_API duckdb_state
duckdb_bind_value(duckdb_prepared_statement prepared_statement, idx_t param_idx,
153393 duckdb_value val);
153394
153399 idx_t *param_idx_out, const char *name);
153400
153404DUCKDB_C_API duckdb_state
duckdb_bind_boolean(duckdb_prepared_statement prepared_statement, idx_t param_idx,
bool val);
153405
153409DUCKDB_C_API duckdb_state
duckdb_bind_int8(duckdb_prepared_statement prepared_statement, idx_t param_idx, int8_t val);
153410
153414DUCKDB_C_API duckdb_state
duckdb_bind_int16(duckdb_prepared_statement prepared_statement, idx_t param_idx, int16_t val);
153415
153419DUCKDB_C_API duckdb_state
duckdb_bind_int32(duckdb_prepared_statement prepared_statement, idx_t param_idx, int32_t val);
153420
153424DUCKDB_C_API duckdb_state
duckdb_bind_int64(duckdb_prepared_statement prepared_statement, idx_t param_idx, int64_t val);
153425
153429DUCKDB_C_API duckdb_state
duckdb_bind_hugeint(duckdb_prepared_statement prepared_statement, idx_t param_idx,
153430 duckdb_hugeint val);
153431
153435DUCKDB_C_API duckdb_state
duckdb_bind_uhugeint(duckdb_prepared_statement prepared_statement, idx_t param_idx,
153436 duckdb_uhugeint val);
153437
153441DUCKDB_C_API duckdb_state
duckdb_bind_decimal(duckdb_prepared_statement prepared_statement, idx_t param_idx,
153442 duckdb_decimal val);
153443
153447DUCKDB_C_API duckdb_state
duckdb_bind_uint8(duckdb_prepared_statement prepared_statement, idx_t param_idx, uint8_t val);
153448
153452DUCKDB_C_API duckdb_state
duckdb_bind_uint16(duckdb_prepared_statement prepared_statement, idx_t param_idx,
153453 uint16_t val);
153454
153458DUCKDB_C_API duckdb_state
duckdb_bind_uint32(duckdb_prepared_statement prepared_statement, idx_t param_idx,
153459 uint32_t val);
153460
153464DUCKDB_C_API duckdb_state
duckdb_bind_uint64(duckdb_prepared_statement prepared_statement, idx_t param_idx,
153465 uint64_t val);
153466
153470DUCKDB_C_API duckdb_state
duckdb_bind_float(duckdb_prepared_statement prepared_statement, idx_t param_idx,
float val);
153471
153475DUCKDB_C_API duckdb_state
duckdb_bind_double(duckdb_prepared_statement prepared_statement, idx_t param_idx,
double val);
153476
153480DUCKDB_C_API duckdb_state
duckdb_bind_date(duckdb_prepared_statement prepared_statement, idx_t param_idx,
153481 duckdb_date val);
153482
153486DUCKDB_C_API duckdb_state
duckdb_bind_time(duckdb_prepared_statement prepared_statement, idx_t param_idx,
153487 duckdb_time val);
153488
153492DUCKDB_C_API duckdb_state
duckdb_bind_timestamp(duckdb_prepared_statement prepared_statement, idx_t param_idx,
153493 duckdb_timestamp val);
153494
153499 duckdb_timestamp val);
153500
153504DUCKDB_C_API duckdb_state
duckdb_bind_interval(duckdb_prepared_statement prepared_statement, idx_t param_idx,
153505 duckdb_interval val);
153506
153512DUCKDB_C_API duckdb_state
duckdb_bind_varchar(duckdb_prepared_statement prepared_statement, idx_t param_idx,
153513 const char *val);
153514
153521 const char *val, idx_t length);
153522
153526DUCKDB_C_API duckdb_state
duckdb_bind_blob(duckdb_prepared_statement prepared_statement, idx_t param_idx,
153527 const void *data, idx_t length);
153528
153532DUCKDB_C_API duckdb_state
duckdb_bind_null(duckdb_prepared_statement prepared_statement, idx_t param_idx);
153533
153534
153535
153536
153537
153538
153539
153540
153554 duckdb_result *out_result);
153555
153556#ifndef DUCKDB_API_NO_DEPRECATED
153573 duckdb_result *out_result);
153574
153575#endif
153576
153577
153578
153579
153580
153581
153582
153583
153584
153598 duckdb_extracted_statements *out_extracted_statements);
153599
153614 duckdb_extracted_statements extracted_statements,
153615 idx_t index,
153616 duckdb_prepared_statement *out_prepared_statement);
153617
153626
153632
153633
153634
153635
153636
153637
153638
153639
153653 duckdb_pending_result *out_result);
153654
153655#ifndef DUCKDB_API_NO_DEPRECATED
153671 duckdb_pending_result *out_result);
153672
153673#endif
153674
153681
153691
153705
153717
153730DUCKDB_C_API duckdb_state
duckdb_execute_pending(duckdb_pending_result pending_result, duckdb_result *out_result);
153731
153740
153741
153742
153743
153744
153745
153746
153747
153748
153749
153756
153766
153775
153783
153791
153799
153807
153815
153823
153831
153839
153846
153854
153862
153870
153878
153886
153894
153902
153910
153918
153927
153935
153943
153951
153959
153967
153975
153984
153992
154000
154008
154016
154024
154032
154040
154048
154056
154064
154072
154080
154088
154097
154105
154113
154121
154129
154137
154145
154153
154161
154169
154177
154185
154193
154201
154210
154218
154227
154235
154244
154253
154263DUCKDB_C_API duckdb_value
duckdb_create_list_value(duckdb_logical_type type, duckdb_value *values, idx_t value_count);
154264
154274DUCKDB_C_API duckdb_value
duckdb_create_array_value(duckdb_logical_type type, duckdb_value *values, idx_t value_count);
154275
154287 duckdb_value *values, idx_t entry_count);
154288
154299 duckdb_value value);
154300
154308
154317
154326
154334
154341
154349
154358
154367
154375
154384
154392
154393
154394
154395
154396
154397
154398
154399
154411
154420
154428
154437
154447
154457
154467DUCKDB_C_API duckdb_logical_type
duckdb_create_union_type(duckdb_logical_type *member_types,
const char **member_names,
154468 idx_t member_count);
154469
154479DUCKDB_C_API duckdb_logical_type
duckdb_create_struct_type(duckdb_logical_type *member_types,
const char **member_names,
154480 idx_t member_count);
154481
154491
154501
154509
154517
154525
154533
154541
154549
154560
154569
154579
154587
154597
154607
154615
154626
154637
154645
154656
154667
154674
154684 duckdb_create_type_info info);
154685
154686
154687
154688
154689
154690
154691
154692
154693
154694
154695
154696
154697
154707
154714
154723
154731
154742
154750
154758
154759
154760
154761
154762
154763
154764
154765
154766
154775
154782
154792
154803
154825
154835
154847
154860 idx_t str_len);
154861
154874 idx_t str_len);
154875
154885
154893
154905
154917
154927
154937
154947DUCKDB_C_API
void duckdb_slice_vector(duckdb_vector vector, duckdb_selection_vector sel, idx_t len);
154948
154962DUCKDB_C_API
void duckdb_vector_copy_sel(duckdb_vector src, duckdb_vector dst, duckdb_selection_vector sel,
154963 idx_t src_count, idx_t src_offset, idx_t dst_offset);
154964
154972
154979DUCKDB_C_API void duckdb_vector_reference_vector(duckdb_vector to_vector, duckdb_vector from_vector);
154980
154981
154982
154983
154984
154985
154986
154987
154988
154997
155009
155019
155029
155030
155031
155032
155033
155034
155035
155036
155037
155038
155047
155054
155062
155072
155079
155087
155095 duckdb_logical_type type);
155096
155104 duckdb_logical_type type);
155105
155114 duckdb_delete_callback_t destroy);
155115
155123 duckdb_scalar_function_bind_t bind);
155124
155135 duckdb_delete_callback_t destroy);
155136
155144
155152
155160 duckdb_scalar_function_t function);
155161
155174 duckdb_scalar_function scalar_function);
155175
155183
155191
155200
155208
155216
155225
155231
155241 duckdb_scalar_function function);
155242
155255
155263
155272
155280
155288 duckdb_scalar_function_init_t init);
155289
155297
155306 duckdb_delete_callback_t destroy);
155307
155315 duckdb_client_context *out_context);
155316
155325
155333
155334
155335
155336
155337
155338
155339
155340
155341
155342
155351
155358
155366
155367
155368
155369
155370
155371
155372
155373
155374
155383
155389
155397
155405 duckdb_logical_type type);
155406
155414 duckdb_logical_type type);
155415
155427 duckdb_aggregate_state_size state_size,
155428 duckdb_aggregate_init_t state_init,
155429 duckdb_aggregate_update_t update,
155430 duckdb_aggregate_combine_t combine,
155431 duckdb_aggregate_finalize_t finalize);
155432
155440 duckdb_aggregate_destroy_t destroy);
155441
155453 duckdb_aggregate_function aggregate_function);
155454
155461
155470 void *extra_info, duckdb_delete_callback_t destroy);
155471
155479
155487
155496
155502
155512 duckdb_aggregate_function function);
155513
155526 duckdb_aggregate_function_set set);
155527
155528
155529
155530
155531
155532
155533
155534
155535
155544
155551
155559
155567
155576 duckdb_logical_type type);
155577
155586 duckdb_delete_callback_t destroy);
155587
155595 duckdb_table_function_bind_t bind);
155596
155604 duckdb_table_function_init_t init);
155605
155613 duckdb_table_function_init_t init);
155614
155622 duckdb_table_function_t function);
155623
155635 bool pushdown);
155636
155649
155650
155651
155652
155653
155654
155655
155656
155657
155665
155673
155682
155690
155701
155712
155722
155730
155738
155739
155740
155741
155742
155743
155744
155745
155746
155754
155765
155774
155784
155795
155803
155811
155812
155813
155814
155815
155816
155817
155818
155819
155827
155838
155846
155854
155862
155863
155864
155865
155866
155867
155868
155869
155870
155880 void *extra_data, duckdb_delete_callback_t delete_callback);
155881
155890 const char *function_name);
155891
155899
155907
155908
155909
155910
155911
155912
155913
155914
155922
155933
155942
155950
155959
155960
155961
155962
155963
155964
155965
155966
155967
155968
155969
155970
155971
155983DUCKDB_C_API duckdb_state
duckdb_appender_create(duckdb_connection connection,
const char *schema,
const char *table,
155984 duckdb_appender *out_appender);
155985
155999 const char *schema, const char *table,
156000 duckdb_appender *out_appender);
156001
156017 idx_t column_count, duckdb_logical_type *types,
156018 const char *table_name, const char **column_names,
156019 duckdb_appender *out_appender);
156020
156029
156041
156042#ifndef DUCKDB_API_NO_DEPRECATED
156056
156057#endif
156058
156067
156078
156087
156098
156110
156121
156130
156135
156143
156148
156161 idx_t row);
156162
156167
156171DUCKDB_C_API duckdb_state
duckdb_append_int8(duckdb_appender appender, int8_t value);
156172
156177
156182
156187
156192
156197
156202
156207
156212
156217
156222
156227
156231DUCKDB_C_API duckdb_state
duckdb_append_date(duckdb_appender appender, duckdb_date value);
156232
156236DUCKDB_C_API duckdb_state
duckdb_append_time(duckdb_appender appender, duckdb_time value);
156237
156242
156247
156252
156257
156261DUCKDB_C_API duckdb_state
duckdb_append_blob(duckdb_appender appender,
const void *data, idx_t length);
156262
156267
156271DUCKDB_C_API duckdb_state
duckdb_append_value(duckdb_appender appender, duckdb_value value);
156272
156282
156283
156284
156285
156286
156287
156288
156289
156301 const char *table, duckdb_table_description *out);
156302
156315 const char *schema, const char *table,
156316 duckdb_table_description *out);
156317
156324
156334
156343DUCKDB_C_API duckdb_state
duckdb_column_has_default(duckdb_table_description table_description, idx_t index,
bool *out);
156344
156352
156362
156372 idx_t index);
156373
156374
156375
156376
156377
156378
156379
156380
156391DUCKDB_C_API duckdb_error_data
duckdb_to_arrow_schema(duckdb_arrow_options arrow_options, duckdb_logical_type *types,
156392 const char **names, idx_t column_count,
156393 struct ArrowSchema *out_schema);
156394
156405 struct ArrowArray *out_arrow_array);
156406
156417 duckdb_arrow_converted_schema *out_types);
156418
156430 struct ArrowArray *arrow_array,
156431 duckdb_arrow_converted_schema converted_schema,
156432 duckdb_data_chunk *out_chunk);
156433
156440
156441#ifndef DUCKDB_API_NO_DEPRECATED
156457DUCKDB_C_API duckdb_state
duckdb_query_arrow(duckdb_connection connection,
const char *query, duckdb_arrow *out_result);
156458
156470
156482 duckdb_arrow_schema *out_schema);
156483
156495 duckdb_arrow_array *out_array);
156496
156511
156521
156531
156542
156555
156564
156573
156585 duckdb_arrow *out_result);
156586
156597DUCKDB_C_API duckdb_state
duckdb_arrow_scan(duckdb_connection connection,
const char *table_name,
156598 duckdb_arrow_stream arrow);
156599
156614 duckdb_arrow_schema arrow_schema, duckdb_arrow_array arrow_array,
156615 duckdb_arrow_stream *out_stream);
156616
156617#endif
156618
156619
156620
156621
156622
156623
156624
156625
156635
156646
156656
156670
156677
156685
156695
156702
156703
156704
156705
156706
156707
156708
156709
156710#ifndef DUCKDB_API_NO_DEPRECATED
156730
156731#endif
156732
156744
156745
156746
156747
156748
156749
156750
156751
156758
156766 duckdb_logical_type source_type);
156767
156775 duckdb_logical_type target_type);
156776
156784
156792 duckdb_cast_function_t function);
156793
156801 duckdb_delete_callback_t destroy);
156802
156810
156818
156826
156836 duckdb_vector output);
156837
156846
156853
156854
156855
156856
156857
156858
156859
156860
156861
156868
156876
156884
156893DUCKDB_C_API duckdb_error_data
duckdb_expression_fold(duckdb_client_context context, duckdb_expression expr,
156894 duckdb_value *out_value);
156895
156896
156897
156898
156899
156900
156901
156902
156903
156911
156917
156925
156938 duckdb_file_open_options options, duckdb_file_handle *out_file);
156939
156946
156957 bool value);
156958
156964
156972
156980
156990
157000
157008
157016
157025
157034
157043
157044
157045
157046
157047
157048
157049
157050
157057
157063
157071
157079
157089
157098 duckdb_config_option_scope default_scope);
157099
157107
157116
157128 duckdb_config_option_scope *out_scope);
157129
157130
157131
157132
157133
157134
157135
157136
157145
157153
157162 duckdb_delete_callback_t destructor);
157163
157171 duckdb_copy_function copy_function);
157172
157178
157185
157193
157201
157211
157219
157228 idx_t col_idx);
157229
157237
157246 duckdb_delete_callback_t destructor);
157247
157254 duckdb_copy_function_global_init_t init);
157255
157263 const char *error);
157264
157272
157281DUCKDB_C_API duckdb_client_context
157283
157291
157301
157310 void *global_state,
157311 duckdb_delete_callback_t destructor);
157312
157319 duckdb_copy_function_sink_t function);
157320
157328
157336
157346
157354
157362
157369 duckdb_copy_function_finalize_t finalize);
157370
157378
157386
157395DUCKDB_C_API duckdb_client_context
157397
157405
157413
157433 duckdb_table_function table_function);
157434
157445
157460
157474 idx_t col_idx);
157475
157476
157477
157478
157479
157480
157481
157482
157483
157484
157485
157496
157506
157520 duckdb_catalog_entry_type entry_type,
157521 const char *schema_name, const char *entry_name);
157522
157531
157539
157548
157557
157558
157559
157560
157561
157562
157563
157564
157565
157572
157579
157587 duckdb_logger_write_log_entry_t function);
157588
157597 duckdb_delete_callback_t delete_callback);
157598
157606
157615
157616
157617
157618
157619
157620
157621
157622
157631
157632#endif
157633
157634#ifdef __cplusplus
157635}
157636#endif
157637
157638
157639
157640
157641
157642
157643
157644
157645
157646
157647
157648
157649
157650
157651
157652
157653
157654
157655
157656
157657
157658
157659
157660#include <chrono>
157661
157662namespace duckdb {
157663using std::chrono::duration;
157664using std::chrono::duration_cast;
157665using std::chrono::high_resolution_clock;
157666using std::chrono::microseconds;
157667using std::chrono::milliseconds;
157668using std::chrono::nanoseconds;
157669using std::chrono::steady_clock;
157670using std::chrono::system_clock;
157671using std::chrono::time_point;
157672}
157673
157674
157675
157676namespace duckdb {
157677
157679template <typename T>
157680class BaseProfiler {
157681public:
157683 void Start() {
157684 finished = false;
157685 ran = true;
157686 start = Tick();
157687 }
157689 void End() {
157690 end = Tick();
157691 finished = true;
157692 }
157694 void Reset() {
157695 finished = false;
157696 ran = false;
157697 }
157698
157703 double Elapsed() const {
157704 if (!ran) {
157705 return 0;
157706 }
157707 auto measured_end = finished ? end : Tick();
157708 return std::chrono::duration_cast<std::chrono::duration<double>>(measured_end - start).count();
157709 }
157710
157711 idx_t ElapsedNanos()
const {
157712 if (!ran) {
157713 return 0;
157714 }
157715 auto measured_end = finished ? end : Tick();
157716 return static_cast<idx_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(measured_end - start).count());
157717 }
157718
157719private:
157721 time_point<T> Tick() const {
157722 return T::now();
157723 }
157725 time_point<T> start;
157727 time_point<T> end;
157729 bool finished = false;
157731 bool ran = false;
157732};
157733
157734using Profiler = BaseProfiler<steady_clock>;
157735
157736}
157737
157738
157739
157740
157741
157742
157743
157744
157745
157746
157747
157748namespace duckdb {
157749
157750class ProgressBarDisplay {
157751public:
157752 ProgressBarDisplay() {
157753 }
157754 virtual ~ProgressBarDisplay() {
157755 }
157756
157757public:
157758 virtual void Update(double percentage) = 0;
157759 virtual void Finish() = 0;
157760};
157761
157762}
157763
157764
157765namespace duckdb {
157766
157767struct ClientConfig;
157768typedef std::function<unique_ptr<ProgressBarDisplay>()> progress_bar_display_create_func_t;
157769
157770struct QueryProgress {
157771 friend class ProgressBar;
157772
157773public:
157774 QueryProgress();
157775 void Initialize();
157776 void Restart();
157777 double GetPercentage();
157779 uint64_t GetTotalRowsToProcess();
157780 QueryProgress &
operator=(
const QueryProgress &other);
157781 QueryProgress(const QueryProgress &other);
157782
157783private:
157784 atomic<double> percentage;
157785 atomic<uint64_t> rows_processed;
157786 atomic<uint64_t> total_rows_to_process;
157787};
157788
157789class ProgressBar {
157790public:
157791 static unique_ptr<ProgressBarDisplay> DefaultProgressBarDisplay();
157792 static void SystemOverrideCheck(ClientConfig &config);
157793
157794 explicit ProgressBar(
157795 Executor &executor, idx_t show_progress_after,
157796 progress_bar_display_create_func_t create_display_func = ProgressBar::DefaultProgressBarDisplay);
157797
157799 void Start();
157801 void Update(bool final);
157802 QueryProgress GetDetailedQueryProgress();
157803 void PrintProgress(double percentage);
157804 void FinishProgressBarPrint();
157805 bool ShouldPrint(bool final) const;
157806 bool PrintEnabled() const;
157807
157808private:
157810 Executor &executor;
157812 Profiler profiler;
157814 idx_t show_progress_after;
157816 QueryProgress query_progress;
157818 unique_ptr<ProgressBarDisplay> display;
157820 bool supported = true;
157822 bool finished = false;
157823};
157824}
157825
157826
157827
157828
157829
157830
157831
157832
157833
157834
157835
157836
157837
157838
157839
157840
157841
157842
157843
157844
157845
157846
157847
157848
157849
157850
157851
157852
157853
157854
157855
157856
157857
157858
157859
157860
157861
157862
157863
157864
157865
157866
157867
157868
157869
157870
157871
157872namespace duckdb {
157873
157874enum class OptimizerType :
uint32_t {
157875 INVALID = 0,
157876 EXPRESSION_REWRITER = 1,
157877 FILTER_PULLUP = 2,
157878 FILTER_PUSHDOWN = 3,
157879 EMPTY_RESULT_PULLUP = 4,
157880 CTE_FILTER_PUSHER = 5,
157881 REGEX_RANGE = 6,
157882 IN_CLAUSE = 7,
157883 JOIN_ORDER = 8,
157884 DELIMINATOR = 9,
157885 UNNEST_REWRITER = 10,
157886 UNUSED_COLUMNS = 11,
157887 STATISTICS_PROPAGATION = 12,
157888 COMMON_SUBEXPRESSIONS = 13,
157889 COMMON_AGGREGATE = 14,
157890 COLUMN_LIFETIME = 15,
157891 BUILD_SIDE_PROBE_SIDE = 16,
157892 LIMIT_PUSHDOWN = 17,
157893 TOP_N = 18,
157894 COMPRESSED_MATERIALIZATION = 19,
157895 DUPLICATE_GROUPS = 20,
157896 REORDER_FILTER = 21,
157897 SAMPLING_PUSHDOWN = 22,
157898 JOIN_FILTER_PUSHDOWN = 23,
157899 EXTENSION = 24,
157900 MATERIALIZED_CTE = 25,
157901 SUM_REWRITER = 26,
157902 LATE_MATERIALIZATION = 27,
157903 CTE_INLINING = 28,
157904 ROW_GROUP_PRUNER = 29,
157905 TOP_N_WINDOW_ELIMINATION = 30,
157906 COMMON_SUBPLAN = 31,
157907 JOIN_ELIMINATION = 32,
157908 WINDOW_SELF_JOIN = 33
157909};
157910
157911string OptimizerTypeToString(OptimizerType type);
157912OptimizerType OptimizerTypeFromString(const string &str);
157913vector<string> ListAllOptimizers();
157914
157915}
157916
157917
157918namespace duckdb {
157919
157920enum class MetricGroup :
uint8_t {
157921 ALL,
157922 CORE,
157923 DEFAULT,
157924 EXECUTION,
157925 FILE,
157926 OPERATOR,
157927 OPTIMIZER,
157928 PHASE_TIMING,
157929 INVALID,
157930};
157931
157932enum class MetricType :
uint8_t {
157933
157934 CPU_TIME = 2,
157935 CUMULATIVE_CARDINALITY = 4,
157936 CUMULATIVE_ROWS_SCANNED = 7,
157937 EXTRA_INFO = 3,
157938 LATENCY = 11,
157939 QUERY_NAME = 0,
157940 RESULT_SET_SIZE = 10,
157941 ROWS_RETURNED = 12,
157942
157943 BLOCKED_THREAD_TIME = 1,
157944 SYSTEM_PEAK_BUFFER_MEMORY = 14,
157945 SYSTEM_PEAK_TEMP_DIR_SIZE = 15,
157946 TOTAL_MEMORY_ALLOCATED = 91,
157947
157948 ATTACH_LOAD_STORAGE_LATENCY = 92,
157949 ATTACH_REPLAY_WAL_LATENCY = 93,
157950 CHECKPOINT_LATENCY = 94,
157951 COMMIT_LOCAL_STORAGE_LATENCY = 95,
157952 TOTAL_BYTES_READ = 16,
157953 TOTAL_BYTES_WRITTEN = 17,
157954 WAITING_TO_ATTACH_LATENCY = 96,
157955 WAL_REPLAY_ENTRY_COUNT = 97,
157956 WRITE_TO_WAL_LATENCY = 98,
157957
157958 OPERATOR_CARDINALITY = 6,
157959 OPERATOR_NAME = 13,
157960 OPERATOR_ROWS_SCANNED = 8,
157961 OPERATOR_TIMING = 9,
157962 OPERATOR_TYPE = 5,
157963
157964 OPTIMIZER_EXPRESSION_REWRITER = 26,
157965 OPTIMIZER_FILTER_PULLUP = 27,
157966 OPTIMIZER_FILTER_PUSHDOWN = 28,
157967 OPTIMIZER_EMPTY_RESULT_PULLUP = 29,
157968 OPTIMIZER_CTE_FILTER_PUSHER = 30,
157969 OPTIMIZER_REGEX_RANGE = 31,
157970 OPTIMIZER_IN_CLAUSE = 32,
157971 OPTIMIZER_JOIN_ORDER = 33,
157972 OPTIMIZER_DELIMINATOR = 34,
157973 OPTIMIZER_UNNEST_REWRITER = 35,
157974 OPTIMIZER_UNUSED_COLUMNS = 36,
157975 OPTIMIZER_STATISTICS_PROPAGATION = 37,
157976 OPTIMIZER_COMMON_SUBEXPRESSIONS = 38,
157977 OPTIMIZER_COMMON_AGGREGATE = 39,
157978 OPTIMIZER_COLUMN_LIFETIME = 40,
157979 OPTIMIZER_BUILD_SIDE_PROBE_SIDE = 41,
157980 OPTIMIZER_LIMIT_PUSHDOWN = 42,
157981 OPTIMIZER_TOP_N = 43,
157982 OPTIMIZER_COMPRESSED_MATERIALIZATION = 44,
157983 OPTIMIZER_DUPLICATE_GROUPS = 45,
157984 OPTIMIZER_REORDER_FILTER = 46,
157985 OPTIMIZER_SAMPLING_PUSHDOWN = 47,
157986 OPTIMIZER_JOIN_FILTER_PUSHDOWN = 48,
157987 OPTIMIZER_EXTENSION = 49,
157988 OPTIMIZER_MATERIALIZED_CTE = 50,
157989 OPTIMIZER_SUM_REWRITER = 51,
157990 OPTIMIZER_LATE_MATERIALIZATION = 52,
157991 OPTIMIZER_CTE_INLINING = 53,
157992 OPTIMIZER_ROW_GROUP_PRUNER = 54,
157993 OPTIMIZER_TOP_N_WINDOW_ELIMINATION = 55,
157994 OPTIMIZER_COMMON_SUBPLAN = 56,
157995 OPTIMIZER_JOIN_ELIMINATION = 57,
157996 OPTIMIZER_WINDOW_SELF_JOIN = 58,
157997
157998 ALL_OPTIMIZERS = 18,
157999 CUMULATIVE_OPTIMIZER_TIMING = 19,
158000 PHYSICAL_PLANNER = 22,
158001 PHYSICAL_PLANNER_COLUMN_BINDING = 23,
158002 PHYSICAL_PLANNER_CREATE_PLAN = 25,
158003 PHYSICAL_PLANNER_RESOLVE_TYPES = 24,
158004 PLANNER = 20,
158005 PLANNER_BINDING = 21,
158006};
158007
158008struct MetricTypeHashFunction {
158010 return std::hash<uint8_t>()(
static_cast<uint8_t>(
index));
158011 }
158012};
158013
158014typedef unordered_set<MetricType, MetricTypeHashFunction> profiler_settings_t;
158015typedef unordered_map<MetricType, Value, MetricTypeHashFunction> profiler_metrics_t;
158016
158017class MetricsUtils {
158018public:
158019 static constexpr uint8_t START_OPTIMIZER =
static_cast<uint8_t>(MetricType::OPTIMIZER_EXPRESSION_REWRITER);
158020 static constexpr uint8_t END_OPTIMIZER =
static_cast<uint8_t>(MetricType::OPTIMIZER_WINDOW_SELF_JOIN);
158021
158022public:
158023
158024
158025 static profiler_settings_t GetAllMetrics();
158026 static profiler_settings_t GetMetricsByGroupType(MetricGroup type);
158027
158028
158029 static profiler_settings_t GetCoreMetrics();
158030 static bool IsCoreMetric(MetricType type);
158031
158032
158033 static profiler_settings_t GetDefaultMetrics();
158034 static bool IsDefaultMetric(MetricType type);
158035
158036
158037 static profiler_settings_t GetExecutionMetrics();
158038 static bool IsExecutionMetric(MetricType type);
158039
158040
158041 static profiler_settings_t GetFileMetrics();
158042 static bool IsFileMetric(MetricType type);
158043
158044
158045 static profiler_settings_t GetOperatorMetrics();
158046 static bool IsOperatorMetric(MetricType type);
158047
158048
158049 static profiler_settings_t GetOptimizerMetrics();
158050 static bool IsOptimizerMetric(MetricType type);
158051 static MetricType GetOptimizerMetricByType(OptimizerType type);
158052 static OptimizerType GetOptimizerTypeByMetric(MetricType type);
158053
158054
158055 static profiler_settings_t GetPhaseTimingMetrics();
158056 static bool IsPhaseTimingMetric(MetricType type);
158057
158058
158059 static profiler_settings_t GetRootScopeMetrics();
158060 static bool IsRootScopeMetric(MetricType type);
158061};
158062}
158063
158064
158065namespace duckdb_yyjson {
158068}
158069
158070namespace duckdb {
158071enum class ProfilingParameterNames :
uint8_t { FORMAT, COVERAGE, SAVE_LOCATION, MODE, METRICS };
158072
158073class ProfilingInfo {
158074public:
158076 profiler_settings_t settings;
158078 profiler_settings_t expanded_settings;
158080 profiler_metrics_t metrics;
158081
158082public:
158083 ProfilingInfo() = default;
158084 explicit ProfilingInfo(const profiler_settings_t &n_settings, const idx_t depth = 0);
158085 ProfilingInfo(ProfilingInfo &) = default;
158086 ProfilingInfo &
operator=(ProfilingInfo
const &) =
default;
158087
158088public:
158089 void ResetMetrics();
158091 static bool Enabled(const profiler_settings_t &settings, const MetricType metric);
158093 static void Expand(profiler_settings_t &settings, const MetricType metric);
158094
158095public:
158096 string GetMetricAsString(const MetricType metric) const;
158097 void WriteMetricsToLog(ClientContext &context);
158098 void WriteMetricsToJSON(duckdb_yyjson::yyjson_mut_doc *doc, duckdb_yyjson::yyjson_mut_val *destination);
158099
158100public:
158101 template <class METRIC_TYPE>
158102 METRIC_TYPE GetMetricValue(const MetricType type) const {
158103 auto val = metrics.at(type);
158104 return val.GetValue<METRIC_TYPE>();
158105 }
158106
158107 template <class METRIC_TYPE>
158108 void MetricUpdate(const MetricType type, const Value &value,
158109 const std::function<METRIC_TYPE(const METRIC_TYPE &, const METRIC_TYPE &)> &update_fun) {
158110 if (metrics.find(type) == metrics.end()) {
158111 metrics[type] = value;
158112 return;
158113 }
158114 auto new_value = update_fun(metrics[type].GetValue<METRIC_TYPE>(), value.GetValue<METRIC_TYPE>());
158115 metrics[type] = Value::CreateValue(new_value);
158116 }
158117
158118 template <class METRIC_TYPE>
158119 void MetricUpdate(const MetricType type, const METRIC_TYPE &value,
158120 const std::function<METRIC_TYPE(const METRIC_TYPE &, const METRIC_TYPE &)> &update_fun) {
158121 auto new_value = Value::CreateValue(value);
158122 MetricUpdate<METRIC_TYPE>(type, new_value, update_fun);
158123 }
158124
158125 template <class METRIC_TYPE>
158126 void MetricSum(const MetricType type, const Value &value) {
158127 MetricUpdate<METRIC_TYPE>(type, value, [](const METRIC_TYPE &old_value, const METRIC_TYPE &new_value) {
158128 return old_value + new_value;
158129 });
158130 }
158131
158132 template <class METRIC_TYPE>
158133 void MetricSum(const MetricType type, const METRIC_TYPE &value) {
158134 auto new_value = Value::CreateValue(value);
158135 return MetricSum<METRIC_TYPE>(type, new_value);
158136 }
158137
158138 template <class METRIC_TYPE>
158139 void MetricMax(const MetricType type, const Value &value) {
158140 MetricUpdate<METRIC_TYPE>(type, value, [](const METRIC_TYPE &old_value, const METRIC_TYPE &new_value) {
158141 return MaxValue(old_value, new_value);
158142 });
158143 }
158144
158145 template <class METRIC_TYPE>
158146 void MetricMax(const MetricType type, const METRIC_TYPE &value) {
158147 auto new_value = Value::CreateValue(value);
158148 return MetricMax<METRIC_TYPE>(type, new_value);
158149 }
158150};
158151
158152
158153template <>
158154inline InsertionOrderPreservingMap<string>
158155ProfilingInfo::GetMetricValue<InsertionOrderPreservingMap<string>>(const MetricType type) const {
158156 auto val = metrics.at(type);
158157 InsertionOrderPreservingMap<string> result;
158158 auto children = MapValue::GetChildren(val);
158159 for (auto &child : children) {
158160 auto struct_children = StructValue::GetChildren(child);
158161 auto key = struct_children[0].GetValue<string>();
158162 auto value = struct_children[1].GetValue<string>();
158163 result.insert(key, value);
158164 }
158165 return result;
158166}
158167}
158168
158169
158170
158171
158172
158173
158174
158175
158176
158177
158178
158179
158180
158181
158182
158183
158184
158185
158186
158187
158188
158189
158190
158191
158192
158193
158194namespace duckdb {
158195
158196enum class LambdaSyntax :
uint8_t { DEFAULT = 0, ENABLE_SINGLE_ARROW = 1, DISABLE_SINGLE_ARROW = 2 };
158197
158198}
158199
158200
158201namespace duckdb {
158202
158203enum class LambdaSyntaxType :
uint8_t { SINGLE_ARROW_STORAGE = 0, SINGLE_ARROW = 1, LAMBDA_KEYWORD = 2 };
158204
158208class LambdaExpression : public ParsedExpression {
158209public:
158210 static constexpr const ExpressionClass
TYPE = ExpressionClass::LAMBDA;
158211
158212public:
158213 LambdaExpression(vector<string> named_parameters_p, unique_ptr<ParsedExpression> expr);
158214 LambdaExpression(unique_ptr<ParsedExpression> lhs, unique_ptr<ParsedExpression> expr);
158215
158217 LambdaSyntaxType syntax_type;
158220 unique_ptr<ParsedExpression> lhs;
158222 unique_ptr<ParsedExpression> expr;
158224 unique_ptr<ParsedExpression> copied_expr;
158225
158226public:
158229 vector<reference<const ParsedExpression>> ExtractColumnRefExpressions(string &error_message) const;
158231 static string InvalidParametersErrorMessage();
158233 static bool IsLambdaParameter(const vector<unordered_set<string>> &lambda_params, const string &column_name);
158234
158235 string ToString() const override;
158236 static bool Equal(const LambdaExpression &a, const LambdaExpression &b);
158237 hash_t Hash()
const override;
158238 unique_ptr<ParsedExpression> Copy() const override;
158239
158240 void Serialize(Serializer &serializer) const override;
158241 static unique_ptr<ParsedExpression> Deserialize(Deserializer &deserializer);
158242
158243private:
158244 LambdaExpression();
158245};
158246
158247}
158248
158249
158250
158251
158252
158253
158254
158255
158256
158257
158258
158259
158260
158261
158262
158263
158264
158265
158266
158267
158268
158269
158270
158271
158272
158273
158274
158275
158276
158277
158278
158279
158280
158281
158282
158283
158284
158285
158286
158287
158288
158289
158290
158291
158292
158293
158294
158295
158296
158297
158298
158299namespace duckdb {
158300
158302class ProfilingNode {
158303public:
158304 explicit ProfilingNode() {
158305 }
158306 virtual ~ProfilingNode() {};
158307
158308private:
158309 ProfilingInfo profiling_info;
158310
158311public:
158313 vector<unique_ptr<ProfilingNode>> children;
158314
158315public:
158316 idx_t GetChildCount() {
158317 return children.size();
158318 }
158319 ProfilingInfo &GetProfilingInfo() {
158320 return profiling_info;
158321 }
158322 const ProfilingInfo &GetProfilingInfo() const {
158323 return profiling_info;
158324 }
158325 optional_ptr<ProfilingNode> GetChild(idx_t idx) {
158326 return children[idx].get();
158327 }
158328 optional_ptr<ProfilingNode> AddChild(unique_ptr<ProfilingNode> child) {
158329 children.push_back(std::move(child));
158330 return children.back().get();
158331 }
158332};
158333
158334}
158335
158336
158337
158338
158339
158340
158341
158342
158343
158344
158345
158346
158347
158348
158349
158350
158351
158352
158353namespace duckdb_yyjson {
158356}
158357
158358namespace duckdb {
158359
158360struct ActiveTimer;
158361
158362
158363struct QueryMetrics {
158364public:
158365 QueryMetrics() {
158366 Reset();
158367 }
158368
158369 ProfilingInfo query_global_info;
158370
158371 std::string query_name;
158372 unique_ptr<ActiveTimer> latency_timer;
158373
158374public:
158375 void UpdateMetric(const MetricType metric, idx_t addition) {
158376 active_metrics[GetMetricsIndex(metric)] += addition;
158377 }
158378
158379 idx_t GetMetricValue(
const MetricType metric)
const {
158380 return active_metrics[GetMetricsIndex(metric)];
158381 }
158382
158383 double GetMetricInSeconds(const MetricType metric) const {
158384 return static_cast<double>(active_metrics[GetMetricsIndex(metric)]) / 1e9;
158385 }
158386
158387 void Reset() {
158388 for(idx_t i = 0; i < ACTIVELY_TRACKED_METRICS; i++) {
158389 active_metrics[i] = 0;
158390 }
158391
158392 latency_timer.reset();
158393 query_name = "";
158394 }
158395
158396 void Merge(const QueryMetrics &other) {
158397 for(idx_t i = 0; i < ACTIVELY_TRACKED_METRICS; i++) {
158398 active_metrics[i] += other.active_metrics[i];
158399 }
158400 }
158401
158402 static idx_t GetMetricsIndex(MetricType type) {
158403 switch(type) {
158404 case MetricType::ATTACH_LOAD_STORAGE_LATENCY: return 0;
158405 case MetricType::ATTACH_REPLAY_WAL_LATENCY: return 1;
158406 case MetricType::CHECKPOINT_LATENCY: return 2;
158407 case MetricType::COMMIT_LOCAL_STORAGE_LATENCY: return 3;
158408 case MetricType::LATENCY: return 4;
158409 case MetricType::WAITING_TO_ATTACH_LATENCY: return 5;
158410 case MetricType::WRITE_TO_WAL_LATENCY: return 6;
158411 case MetricType::TOTAL_BYTES_READ: return 7;
158412 case MetricType::TOTAL_BYTES_WRITTEN: return 8;
158413 case MetricType::TOTAL_MEMORY_ALLOCATED: return 9;
158414 case MetricType::WAL_REPLAY_ENTRY_COUNT: return 10;
158415 default:
158416 throw InternalException("MetricType %s is not actively tracked.", EnumUtil::ToString(type));
158417 }
158418 }
158419
158420private:
158421 static constexpr const idx_t ACTIVELY_TRACKED_METRICS = 11;
158422
158423 atomic<idx_t> active_metrics[ACTIVELY_TRACKED_METRICS];
158424};
158425
158426class ProfilingUtils {
158427public:
158428 static void SetMetricToDefault(profiler_metrics_t &metrics, const MetricType &type);
158429 static void MetricToJson(duckdb_yyjson::yyjson_mut_doc *doc, duckdb_yyjson::yyjson_mut_val *dest, const char *key_ptr, profiler_metrics_t &metrics, const MetricType &type);
158430 static void CollectMetrics(const MetricType &type, QueryMetrics &query_metrics, Value &metric, ProfilingNode &node, ProfilingInfo &child_info);
158431};
158432
158433struct ActiveTimer {
158434public:
158435 ActiveTimer() : metric(MetricType::EXTRA_INFO), is_active(false) {
158436 }
158437 ActiveTimer(QueryMetrics &query_metrics, const MetricType metric, const bool is_active = true) : query_metrics(query_metrics), metric(metric), is_active(is_active) {
158438
158439 if (!is_active) {
158440 return;
158441 }
158442 profiler.Start();
158443 }
158444 ~ActiveTimer() {
158445 if (is_active) {
158446
158447 EndTimer();
158448 }
158449 }
158450
158451 ActiveTimer(const ActiveTimer &other) = delete;
158452 ActiveTimer &
operator=(
const ActiveTimer &) =
delete;
158454 ActiveTimer(ActiveTimer &&other) noexcept : is_active(false) {
158455 std::swap(query_metrics, other.query_metrics);
158456 std::swap(metric, other.metric);
158457 std::swap(profiler, other.profiler);
158458 std::swap(is_active, other.is_active);
158459 }
158460 ActiveTimer &
operator=(ActiveTimer &&other)
noexcept {
158461 std::swap(query_metrics, other.query_metrics);
158462 std::swap(metric, other.metric);
158463 std::swap(profiler, other.profiler);
158464 std::swap(is_active, other.is_active);
158465 return *this;
158466 }
158467
158468
158469 void EndTimer() {
158470 if (!is_active) {
158471 return;
158472 }
158473
158474 is_active = false;
158475 profiler.End();
158476 query_metrics->UpdateMetric(metric, profiler.ElapsedNanos());
158477 }
158478
158479 void Reset() {
158480 if (!is_active) {
158481 return;
158482 }
158483 profiler.Reset();
158484 is_active = false;
158485 }
158486
158487private:
158488 optional_ptr<QueryMetrics> query_metrics;
158489 MetricType metric;
158490 Profiler profiler;
158491 bool is_active;
158492};
158493
158494}
158495
158496
158497namespace duckdb {
158498
158499class ClientContext;
158500class ExpressionExecutor;
158501class ProfilingNode;
158502class PhysicalOperator;
158503class SQLStatement;
158504struct ActiveTimer;
158505
158506enum class ProfilingCoverage :
uint8_t { SELECT = 0, ALL = 1 };
158507
158508struct OperatorInformation {
158509 explicit OperatorInformation() {
158510 }
158511
158512 string name;
158513
158514 double time = 0;
158515 idx_t elements_returned = 0;
158516 idx_t result_set_size = 0;
158517 idx_t system_peak_buffer_manager_memory = 0;
158518 idx_t system_peak_temp_directory_size = 0;
158519 idx_t rows_scanned = 0;
158520
158521 InsertionOrderPreservingMap<string> extra_info;
158522
158523 template <typename T>
158524 void AddMetric(MetricType type, T metric) {
158525 switch (type) {
158526 case MetricType::OPERATOR_TIMING:
158527 time += metric;
158528 break;
158529 case MetricType::OPERATOR_CARDINALITY:
158530 elements_returned += LossyNumericCast<idx_t>(metric);
158531 break;
158532 case MetricType::RESULT_SET_SIZE:
158533 result_set_size += LossyNumericCast<idx_t>(metric);
158534 break;
158535 case MetricType::SYSTEM_PEAK_BUFFER_MEMORY: {
158536 if (metric > system_peak_buffer_manager_memory) {
158537 system_peak_buffer_manager_memory += LossyNumericCast<idx_t>(metric);
158538 }
158539 break;
158540 }
158541 case MetricType::SYSTEM_PEAK_TEMP_DIR_SIZE: {
158542 if (metric > system_peak_temp_directory_size) {
158543 system_peak_temp_directory_size = LossyNumericCast<idx_t>(metric);
158544 }
158545 break;
158546 }
158547 case MetricType::OPERATOR_ROWS_SCANNED:
158548 rows_scanned = LossyNumericCast<idx_t>(metric);
158549 break;
158550 default:
158551 throw InternalException("OperatorProfiler: Unknown metric type");
158552 }
158553 }
158554};
158555
158558class OperatorProfiler {
158559 friend class QueryProfiler;
158560
158561public:
158562 DUCKDB_API explicit OperatorProfiler(ClientContext &context);
158563 ~OperatorProfiler() {
158564 }
158565
158566public:
158567 DUCKDB_API void StartOperator(optional_ptr<const PhysicalOperator> phys_op);
158568 DUCKDB_API void EndOperator(optional_ptr<DataChunk> chunk);
158569 DUCKDB_API void FinishSource(GlobalSourceState &gstate, LocalSourceState &lstate);
158570
158572 DUCKDB_API void Flush(const PhysicalOperator &phys_op);
158573 DUCKDB_API OperatorInformation &GetOperatorInfo(const PhysicalOperator &phys_op);
158574 DUCKDB_API bool OperatorInfoIsInitialized(const PhysicalOperator &phys_op);
158575
158576public:
158577 ClientContext &context;
158578
158579private:
158581 bool enabled;
158583 profiler_settings_t settings;
158584
158586 Profiler op;
158588 optional_ptr<const PhysicalOperator> active_operator;
158590 reference_map_t<const PhysicalOperator, OperatorInformation> operator_infos;
158591};
158592
158594class QueryProfiler {
158595public:
158596 using TreeMap = reference_map_t<const PhysicalOperator, reference<ProfilingNode>>;
158597
158598public:
158599 DUCKDB_API explicit QueryProfiler(ClientContext &context);
158600
158601public:
158602 DUCKDB_API bool IsEnabled() const;
158603 DUCKDB_API bool IsDetailedEnabled() const;
158604 DUCKDB_API ProfilerPrintFormat GetPrintFormat(ExplainFormat
format = ExplainFormat::DEFAULT)
const;
158605 DUCKDB_API bool PrintOptimizerOutput() const;
158606 DUCKDB_API string GetSaveLocation() const;
158607
158608 DUCKDB_API static QueryProfiler &Get(ClientContext &context);
158609
158610 DUCKDB_API void Start(const string &query);
158611 DUCKDB_API void Reset();
158612 DUCKDB_API void StartQuery(const string &query, bool is_explain_analyze = false, bool start_at_optimizer = false);
158613 DUCKDB_API void EndQuery();
158615 DUCKDB_API void FinalizeMetrics();
158616
158618 DUCKDB_API void AddToCounter(MetricType type, const idx_t amount);
158619
158621 DUCKDB_API ActiveTimer StartTimer(MetricType type);
158622
158623 DUCKDB_API void StartExplainAnalyze();
158624
158626 DUCKDB_API void Flush(OperatorProfiler &profiler);
158628 DUCKDB_API void SetBlockedTime(const double &blocked_thread_time);
158629
158630 DUCKDB_API void StartPhase(MetricType phase_metric);
158631 DUCKDB_API void EndPhase();
158632
158633 DUCKDB_API void Initialize(const PhysicalOperator &root);
158634
158635 DUCKDB_API string QueryTreeToString() const;
158636 DUCKDB_API void QueryTreeToStream(std::ostream &str) const;
158637 DUCKDB_API void Print();
158638
158641 DUCKDB_API
string ToString(ExplainFormat
format = ExplainFormat::DEFAULT)
const;
158642 DUCKDB_API
string ToString(ProfilerPrintFormat
format)
const;
158643
158644
158645 static Value JSONSanitize(const Value &input);
158646 static string JSONSanitize(const string &text);
158647 static string DrawPadded(const string &str, idx_t width);
158648 DUCKDB_API void ToLog() const;
158649 DUCKDB_API string ToJSON() const;
158650 DUCKDB_API void WriteToFile(const char *path, string &info) const;
158651 DUCKDB_API
idx_t GetBytesRead()
const;
158652 DUCKDB_API
idx_t GetBytesWritten()
const;
158653
158654 idx_t OperatorSize() {
158655 return tree_map.size();
158656 }
158657
158658 void Finalize(ProfilingNode &node);
158659
158661 optional_ptr<ProfilingNode> GetRoot() {
158662 return root.get();
158663 }
158664
158667 DUCKDB_API void GetRootUnderLock(const std::function<void(optional_ptr<ProfilingNode>)> &callback) {
158668 lock_guard<std::mutex> guard(lock);
158669 callback(GetRoot());
158670 }
158671
158672private:
158673 unique_ptr<ProfilingNode> CreateTree(const PhysicalOperator &root, const profiler_settings_t &settings,
158674 const idx_t depth = 0);
158675 void Render(const ProfilingNode &node, std::ostream &str) const;
158676 string RenderDisabledMessage(ProfilerPrintFormat
format)
const;
158677
158678private:
158679 ClientContext &context;
158680
158682 bool running;
158684 mutable std::mutex lock;
158685
158687 bool query_requires_profiling;
158688
158690 unique_ptr<ProfilingNode> root;
158691
158693 QueryMetrics query_metrics;
158694
158696 TreeMap tree_map;
158698 bool is_explain_analyze;
158700 bool metrics_finalized;
158701
158702public:
158703 const TreeMap &GetTreeMap() const {
158704 return tree_map;
158705 }
158706
158707private:
158709 Profiler phase_profiler;
158711 using PhaseTimingStorage = unordered_map<MetricType, double, MetricTypeHashFunction>;
158712 PhaseTimingStorage phase_timings;
158713 using PhaseTimingItem = PhaseTimingStorage::value_type;
158715 vector<MetricType> phase_stack;
158716
158717private:
158718 void MoveOptimizerPhasesToRoot();
158719 void FinalizeMetricsInternal();
158720
158723 bool OperatorRequiresProfiling(const PhysicalOperatorType op_type);
158724 ExplainFormat GetExplainFormat(ProfilerPrintFormat
format)
const;
158725};
158726
158727}
158728
158729
158730
158731
158732
158733
158734
158735
158736
158737
158738
158739
158740
158741
158742
158743
158744
158745
158746
158747
158748
158749
158750
158751
158752
158753
158754
158755
158756
158757
158758
158759
158760
158761
158762
158763
158764
158765
158766namespace duckdb {
158767
158768enum class SetScope :
uint8_t {
158769 AUTOMATIC = 0,
158770 LOCAL = 1,
158771 SESSION = 2,
158772 GLOBAL = 3,
158773 VARIABLE = 4
158774};
158775
158776}
158777
158778
158779namespace duckdb {
158780class ClientContext;
158781class DatabaseInstance;
158782struct DBConfig;
158783
158786 GLOBAL,
158788 LOCAL,
158790 SECRET,
158792 INVALID
158793};
158794
158796 INVALID,
158805};
158806
158807struct SettingLookupResult {
158808public:
158809 SettingLookupResult() : scope(
SettingScope::INVALID) {
158810 }
158811 explicit SettingLookupResult(SettingScope scope) : scope(scope) {
158812 D_ASSERT(scope != SettingScope::INVALID);
158813 }
158814
158815public:
158816 operator bool() {
158817 return scope != SettingScope::INVALID;
158818 }
158819
158820public:
158822 D_ASSERT(scope != SettingScope::INVALID);
158823 return scope;
158824 }
158825
158826private:
158828};
158829
158830struct SettingCallbackInfo {
158831 explicit SettingCallbackInfo(ClientContext &context, SetScope scope);
158832 explicit SettingCallbackInfo(DBConfig &config, optional_ptr<DatabaseInstance> db);
158833
158834 DBConfig &config;
158835 optional_ptr<DatabaseInstance>
db;
158836 optional_ptr<ClientContext> context;
158837 SetScope scope;
158838};
158839
158840typedef void (*set_callback_t)(SettingCallbackInfo &info, Value ¶meter);
158841typedef void (*set_global_function_t)(DatabaseInstance *
db, DBConfig &config,
const Value ¶meter);
158842typedef void (*set_local_function_t)(ClientContext &context, const Value ¶meter);
158843typedef void (*reset_global_function_t)(DatabaseInstance *
db, DBConfig &config);
158844typedef void (*reset_local_function_t)(ClientContext &context);
158845typedef Value (*get_setting_function_t)(const ClientContext &context);
158846
158847struct ConfigurationOption {
158848 const char *name;
158849 const char *description;
158850 const char *parameter_type;
158851 set_global_function_t set_global;
158852 set_local_function_t set_local;
158853 reset_global_function_t reset_global;
158854 reset_local_function_t reset_local;
158855 get_setting_function_t get_setting;
158857 const char *default_value;
158858 set_callback_t set_callback;
158859 optional_idx setting_idx;
158860};
158861
158862struct ConfigurationAlias {
158863 const char *alias;
158864 idx_t option_index;
158865};
158866
158867typedef void (*set_option_callback_t)(ClientContext &context, SetScope scope, Value ¶meter);
158868
158869struct ExtensionOption {
158870 ExtensionOption() : set_function(nullptr), default_scope(SetScope::AUTOMATIC) {
158871 }
158872
158873 ExtensionOption(string description_p, LogicalType type_p, set_option_callback_t set_function_p,
158874 Value default_value_p, SetScope default_scope_p)
158875 : description(std::move(description_p)), type(std::move(type_p)), set_function(set_function_p),
158876 default_value(std::move(default_value_p)), default_scope(default_scope_p) {
158877 }
158878
158879 string description;
158880 LogicalType type;
158881 set_option_callback_t set_function;
158882 Value default_value;
158883 SetScope default_scope;
158884 optional_idx setting_index;
158885};
158886
158887}
158888
158889
158890
158891namespace duckdb {
158892
158893struct GenericSetting {
158894 GenericSetting() : is_set(false) {
158895 }
158896
158897 bool is_set;
158898 Value value;
158899};
158900
158901struct UserSettingsMap {
158902public:
158903 void SetUserSetting(idx_t setting_index, Value target_value);
158904 void ClearSetting(idx_t setting_index);
158905 bool IsSet(idx_t setting_index) const;
158906 bool TryGetSetting(idx_t setting_index, Value &result_value) const;
158907
158908private:
158909 vector<GenericSetting> settings;
158910};
158911
158912#ifndef __MINGW32__
158913struct GlobalUserSettings;
158914
158915struct CachedGlobalSettings {
158916 CachedGlobalSettings();
158917 CachedGlobalSettings(const GlobalUserSettings &global_user_settings, idx_t version, UserSettingsMap settings);
158918
158919 optional_ptr<const GlobalUserSettings> global_user_settings;
158921 UserSettingsMap settings;
158922 hugeint_t uuid;
158923};
158924#endif
158925
158926struct GlobalUserSettings {
158927public:
158928 GlobalUserSettings();
158929
158930 GlobalUserSettings(const GlobalUserSettings &other);
158931 GlobalUserSettings &
operator=(
const GlobalUserSettings &);
158932
158933 void SetUserSetting(idx_t setting_index, Value target_value);
158934 void ClearSetting(idx_t setting_index);
158935 bool IsSet(idx_t setting_index) const;
158936 SettingLookupResult TryGetSetting(idx_t setting_index, Value &result_value) const;
158937 bool HasExtensionOption(const string &name) const;
158938 idx_t AddExtensionOption(
const string &name, ExtensionOption extension_option);
158939 case_insensitive_map_t<ExtensionOption> GetExtensionSettings() const;
158940 bool TryGetExtensionOption(
const String &name, ExtensionOption &result)
const;
158941 hugeint_t GetUUID() const;
158942
158943#ifndef __MINGW32__
158944 CachedGlobalSettings &GetSettings() const;
158945#endif
158946
158947private:
158948 mutable mutex lock;
158950 UserSettingsMap settings_map;
158952 case_insensitive_map_t<ExtensionOption> extension_parameters;
158954 atomic<idx_t> settings_version;
158956 hugeint_t uuid;
158957};
158958
158959struct LocalUserSettings {
158960public:
158961 ~LocalUserSettings();
158962
158963 void SetUserSetting(idx_t setting_index, Value target_value);
158964 void ClearSetting(idx_t setting_index);
158965 bool IsSet(idx_t setting_index) const;
158966 SettingLookupResult TryGetSetting(const GlobalUserSettings &global_settings, idx_t setting_index,
158967 Value &result_value) const;
158968
158969private:
158971 UserSettingsMap settings_map;
158972};
158973}
158974
158975
158976namespace duckdb {
158977
158978class ClientContext;
158979class PhysicalResultCollector;
158980class PreparedStatementData;
158981
158982typedef std::function<unique_ptr<PhysicalOperator>(ClientContext &context, PreparedStatementData &data)>
158983 get_result_collector_t;
158984
158985struct ClientConfig {
158987 bool enable_profiler = false;
158989 bool enable_detailed_profiling = false;
158991 ProfilerPrintFormat profiler_print_format = ProfilerPrintFormat::QUERY_TREE;
158994 string profiler_save_location;
158997 profiler_settings_t profiler_settings = MetricsUtils::GetDefaultMetrics();
158999 LogicalTypeId profiler_settings_type = LogicalTypeId::VARCHAR;
159000
159003 bool emit_profiler_output = true;
159004
159006 const char *system_progress_bar_disable_reason = nullptr;
159008 bool enable_progress_bar = false;
159010 bool print_progress_bar = true;
159012 int wait_time = 2000;
159013
159015 bool query_verification_enabled = false;
159017 bool verify_external = false;
159019 bool verify_fetch_row = false;
159021 bool verify_serializer = false;
159023 bool enable_optimizer = true;
159025 bool enable_caching_operators = true;
159027 bool verify_parallelism = false;
159029 bool force_external = false;
159031 bool force_fetch_row = false;
159034 bool use_replacement_scans = true;
159035
159037 idx_t streaming_buffer_size = 1000000;
159038
159040 progress_bar_display_create_func_t display_create_func = nullptr;
159041
159044 ProfilingCoverage profiling_coverage = ProfilingCoverage::SELECT;
159045
159047 LocalUserSettings user_settings;
159048
159050 case_insensitive_map_t<Value> user_variables;
159051
159053 get_result_collector_t get_result_collector = nullptr;
159054
159056 bool enable_http_logging = true;
159057
159060 string http_logging_output;
159061
159062public:
159063 static ClientConfig &GetConfig(ClientContext &context);
159064 static const ClientConfig &GetConfig(const ClientContext &context);
159065
159066 bool AnyVerification() const;
159067
159068 void SetUserVariable(
const String &name, Value value);
159069 bool GetUserVariable(const string &name, Value &result);
159070 void ResetUserVariable(
const String &name);
159071
159072public:
159073 void SetDefaultStreamingBufferSize();
159074};
159075
159076struct ScopedConfigSetting {
159077public:
159078 using config_modify_func_t = std::function<void(ClientConfig &config)>;
159079
159080public:
159081 explicit ScopedConfigSetting(ClientConfig &config, config_modify_func_t set_f = nullptr,
159082 config_modify_func_t unset_f = nullptr)
159083 : config(config), set(std::move(set_f)), unset(std::move(unset_f)) {
159084 if (set) {
159085 set(config);
159086 }
159087 }
159088 ~ScopedConfigSetting() {
159089 if (unset) {
159090 unset(config);
159091 }
159092 }
159093
159094public:
159095 ClientConfig &config;
159096 config_modify_func_t set;
159097 config_modify_func_t unset;
159098};
159099
159100}
159101
159102
159103
159104
159105
159106
159107
159108
159109
159110
159111
159112
159113
159114
159115
159116
159117
159118
159119
159120
159121
159122
159123
159124
159125namespace duckdb {
159126class TransactionException : public Exception {
159127public:
159128 DUCKDB_API explicit TransactionException(const string &msg);
159129
159130 template <typename... ARGS>
159131 explicit TransactionException(const string &msg, ARGS &&...params)
159132 : TransactionException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
159133 }
159134};
159135}
159136
159137
159138
159139
159140
159141
159142
159143
159144
159145
159146
159147
159148
159149
159150
159151
159152
159153
159154
159155
159156
159157
159158
159159
159160
159161
159162
159163
159164
159165
159166namespace duckdb {
159167
159168class DataChunk;
159169
159171class ChunkScanState {
159172public:
159173 explicit ChunkScanState();
159174 virtual ~ChunkScanState();
159175
159176public:
159177 ChunkScanState(const ChunkScanState &other) = delete;
159178 ChunkScanState(ChunkScanState &&other) = default;
159179 ChunkScanState &
operator=(
const ChunkScanState &other) =
delete;
159180 ChunkScanState &
operator=(ChunkScanState &&other) =
default;
159181
159182public:
159183 virtual bool LoadNextChunk(ErrorData &error) = 0;
159184 virtual bool HasError() const = 0;
159185 virtual ErrorData &GetError() = 0;
159186 virtual const vector<LogicalType> &Types() const = 0;
159187 virtual const vector<string> &Names() const = 0;
159188 idx_t CurrentOffset()
const;
159189 idx_t RemainingInChunk()
const;
159190 DataChunk &CurrentChunk();
159191 bool ChunkIsEmpty() const;
159192 bool Finished() const;
159193 bool ScanStarted() const;
159194 void IncreaseOffset(idx_t increment, bool unsafe = false);
159195
159196protected:
159198 bool finished = false;
159199 unique_ptr<DataChunk> current_chunk;
159200};
159201
159202}
159203
159204
159205
159206
159207
159208
159209
159210
159211
159212
159213
159214
159215
159216
159217
159218
159219
159220
159221
159222
159223
159224
159225
159226
159227
159228
159229
159230
159231
159232
159233
159234
159235#include <cstdint>
159236
159237namespace duckdb {
159238
159239enum class ArrowTypeInfoType :
uint8_t {
LIST, STRUCT, DATE_TIME,
STRING, ARRAY, DECIMAL };
159240
159241}
159242
159243
159244
159245namespace duckdb {
159246
159247
159248
159249
159250enum class ArrowDateTimeType :
uint8_t {
159251 MILLISECONDS,
159252 MICROSECONDS,
159253 NANOSECONDS,
159254 SECONDS,
159255 DAYS,
159256 MONTHS,
159257 MONTH_DAY_NANO
159258};
159259
159260}
159261
159262
159263
159264namespace duckdb {
159265
159266
159267
159268
159269enum class ArrowVariableSizeType :
uint8_t { NORMAL, FIXED_SIZE, SUPER_SIZE, VIEW };
159270
159271}
159272
159273
159274
159275namespace duckdb {
159276
159278
159279enum class ArrowArrayPhysicalType :
uint8_t { DICTIONARY_ENCODED, RUN_END_ENCODED, DEFAULT };
159280
159281struct ArrowTypeInfo {
159282public:
159283 explicit ArrowTypeInfo() : type() {
159284 }
159285
159286 explicit ArrowTypeInfo(ArrowTypeInfoType type);
159287 virtual ~ArrowTypeInfo();
159288
159289 ArrowTypeInfoType type;
159290
159291public:
159292 template <class TARGET>
159293 TARGET &Cast() {
159294 D_ASSERT(dynamic_cast<TARGET *>(this));
159295 if (type != TARGET::TYPE) {
159296 throw InternalException("Failed to cast ArrowTypeInfo, type mismatch (expected: %s, got: %s)",
159297 EnumUtil::ToString(TARGET::TYPE), EnumUtil::ToString(type));
159298 }
159299 return reinterpret_cast<TARGET &>(*this);
159300 }
159301 template <class TARGET>
159302 const TARGET &Cast() const {
159303 D_ASSERT(dynamic_cast<const TARGET *>(this));
159304 if (type != TARGET::TYPE) {
159305 throw InternalException("Failed to cast ArrowTypeInfo, type mismatch (expected: %s, got: %s)",
159306 EnumUtil::ToString(TARGET::TYPE), EnumUtil::ToString(type));
159307 }
159308 return reinterpret_cast<const TARGET &>(*this);
159309 }
159310};
159311
159312struct ArrowStructInfo : public ArrowTypeInfo {
159313public:
159314 static constexpr const ArrowTypeInfoType
TYPE = ArrowTypeInfoType::STRUCT;
159315
159316public:
159317 explicit ArrowStructInfo(vector<shared_ptr<ArrowType>> children);
159318 ~ArrowStructInfo() override;
159319
159320public:
159321 idx_t ChildCount()
const;
159322 const ArrowType &GetChild(idx_t index)
const;
159323 const vector<shared_ptr<ArrowType>> &GetChildren() const;
159324
159325private:
159326 vector<shared_ptr<ArrowType>> children;
159327};
159328
159329struct ArrowDateTimeInfo : public ArrowTypeInfo {
159330public:
159331 static constexpr const ArrowTypeInfoType
TYPE = ArrowTypeInfoType::DATE_TIME;
159332
159333public:
159334 explicit ArrowDateTimeInfo(ArrowDateTimeType size);
159335 ~ArrowDateTimeInfo() override;
159336
159337public:
159338 ArrowDateTimeType GetDateTimeType() const;
159339
159340private:
159341 ArrowDateTimeType size_type;
159342};
159343
159344enum class DecimalBitWidth :
uint8_t { DECIMAL_32, DECIMAL_64, DECIMAL_128, DECIMAL_256 };
159345
159346struct ArrowDecimalInfo final : public ArrowTypeInfo {
159347public:
159348 static constexpr const ArrowTypeInfoType
TYPE = ArrowTypeInfoType::DECIMAL;
159349
159350public:
159351 explicit ArrowDecimalInfo(DecimalBitWidth bit_width);
159352 ~ArrowDecimalInfo() override;
159353
159354public:
159355 DecimalBitWidth GetBitWidth() const;
159356
159357private:
159358 DecimalBitWidth bit_width;
159359};
159360
159361struct ArrowStringInfo : public ArrowTypeInfo {
159362public:
159363 static constexpr const ArrowTypeInfoType
TYPE = ArrowTypeInfoType::STRING;
159364
159365public:
159366 explicit ArrowStringInfo(ArrowVariableSizeType size);
159367 explicit ArrowStringInfo(idx_t fixed_size);
159368 ~ArrowStringInfo() override;
159369
159370public:
159371 ArrowVariableSizeType GetSizeType() const;
159372 idx_t FixedSize()
const;
159373
159374private:
159375 ArrowVariableSizeType size_type;
159377};
159378
159379struct ArrowListInfo : public ArrowTypeInfo {
159380public:
159381 static constexpr const ArrowTypeInfoType
TYPE = ArrowTypeInfoType::LIST;
159382
159383public:
159384 static unique_ptr<ArrowListInfo> ListView(shared_ptr<ArrowType> child, ArrowVariableSizeType size);
159385 static unique_ptr<ArrowListInfo> List(shared_ptr<ArrowType> child, ArrowVariableSizeType size);
159386 ~ArrowListInfo() override;
159387
159388public:
159389 ArrowVariableSizeType GetSizeType() const;
159390 bool IsView() const;
159392
159393private:
159394 explicit ArrowListInfo(shared_ptr<ArrowType> child, ArrowVariableSizeType size);
159395
159396private:
159397 ArrowVariableSizeType size_type;
159398 bool is_view = false;
159399 shared_ptr<ArrowType> child;
159400};
159401
159402struct ArrowArrayInfo : public ArrowTypeInfo {
159403public:
159404 static constexpr const ArrowTypeInfoType
TYPE = ArrowTypeInfoType::ARRAY;
159405
159406public:
159407 explicit ArrowArrayInfo(shared_ptr<ArrowType> child, idx_t fixed_size);
159408 ~ArrowArrayInfo() override;
159409
159410public:
159411 idx_t FixedSize()
const;
159413
159414private:
159415 shared_ptr<ArrowType> child;
159417};
159418
159419}
159420
159421
159422
159423namespace duckdb {
159424struct DBConfig;
159425
159426struct ArrowArrayScanState;
159427
159428typedef void (*cast_arrow_duck_t)(ClientContext &context, Vector &source, Vector &result,
idx_t count);
159429
159430typedef void (*cast_duck_arrow_t)(ClientContext &context, Vector &source, Vector &result,
idx_t count);
159431
159432class ArrowTypeExtensionData {
159433public:
159434 explicit ArrowTypeExtensionData(const LogicalType &duckdb_type, const LogicalType &internal_type_p,
159435 cast_arrow_duck_t arrow_to_duckdb = nullptr,
159436 cast_duck_arrow_t duckdb_to_arrow = nullptr)
159437 : arrow_to_duckdb(arrow_to_duckdb), duckdb_to_arrow(duckdb_to_arrow), duckdb_type(duckdb_type),
159438 internal_type(internal_type_p) {
159439 }
159440
159441 explicit ArrowTypeExtensionData(const LogicalType &duckdb_type)
159442 : duckdb_type(duckdb_type), internal_type(duckdb_type) {
159443 }
159444
159446 cast_arrow_duck_t arrow_to_duckdb = nullptr;
159448 cast_duck_arrow_t duckdb_to_arrow = nullptr;
159449
159450 LogicalType GetInternalType() const;
159451
159453 static unordered_map<idx_t, const shared_ptr<ArrowTypeExtensionData>>
159454 GetExtensionTypes(ClientContext &context, const vector<LogicalType> &duckdb_types);
159455 LogicalType GetDuckDBType() const;
159456
159457private:
159459 LogicalType duckdb_type;
159461 LogicalType internal_type;
159462};
159463
159465public:
159467 explicit ArrowType(LogicalType type_p, unique_ptr<ArrowTypeInfo> type_info =
nullptr)
159468 : type(std::move(type_p)), type_info(std::move(type_info)) {
159469 }
159470 explicit ArrowType(
string error_message_p,
bool not_implemented_p =
false)
159471 : type(
LogicalTypeId::INVALID), type_info(nullptr), error_message(std::move(error_message_p)),
159472 not_implemented(not_implemented_p) {
159473 }
159474
159475public:
159476 LogicalType GetDuckType(bool use_dictionary = false) const;
159477
159478 void SetDictionary(unique_ptr<ArrowType> dictionary);
159479 bool HasDictionary() const;
159480 const ArrowType &GetDictionary()
const;
159481
159482 bool RunEndEncoded() const;
159483 void SetRunEndEncoded();
159484
159485 template <class T>
159486 const T &GetTypeInfo() const {
159487 return type_info->Cast<T>();
159488 }
159489 void ThrowIfInvalid() const;
159490
159491 static unique_ptr<ArrowType> GetTypeFromFormat(
string &
format);
159492 static unique_ptr<ArrowType> GetTypeFromFormat(ClientContext &context, ArrowSchema &schema,
string &
format);
159493
159494 static unique_ptr<ArrowType> GetTypeFromSchema(ClientContext &context, ArrowSchema &schema);
159495
159496 static unique_ptr<ArrowType> CreateListType(ClientContext &context, ArrowSchema &child,
159497 ArrowVariableSizeType size_type, bool view);
159498
159499 static unique_ptr<ArrowType> GetArrowLogicalType(ClientContext &context, ArrowSchema &schema);
159500
159501 bool HasExtension() const;
159502
159503 ArrowArrayPhysicalType GetPhysicalType() const;
159504
159506 shared_ptr<ArrowTypeExtensionData> extension_data;
159507
159508protected:
159509 LogicalType type;
159511 unique_ptr<ArrowType> dictionary_type;
159513 bool run_end_encoded = false;
159514 unique_ptr<ArrowTypeInfo> type_info;
159516 string error_message;
159518 bool not_implemented = false;
159519};
159520
159521using arrow_column_map_t = unordered_map<idx_t, shared_ptr<ArrowType>>;
159522
159523struct ArrowTableSchema {
159524public:
159525 void AddColumn(idx_t index, shared_ptr<ArrowType> type, const string &name);
159526 const arrow_column_map_t &GetColumns() const;
159527 vector<LogicalType> &GetTypes();
159528 vector<string> &GetNames();
159529
159530private:
159531 arrow_column_map_t arrow_convert_data;
159532 vector<LogicalType> types;
159533 vector<string> column_names;
159534};
159535
159536}
159537
159538#include <mutex>
159539
159540namespace duckdb {
159541class ArrowSchemaMetadata;
159542struct DuckDBArrowSchemaHolder;
159543
159544struct DBConfig;
159545struct ArrowExtensionMetadata {
159546public:
159547 ArrowExtensionMetadata() {
159548 }
159549
159550 ArrowExtensionMetadata(string extension_name, string vendor_name, string type_name, string arrow_format);
159551
159552 hash_t GetHash()
const;
159553
159554 string ToString() const;
159555
159556 string GetExtensionName() const;
159557
159558 string GetVendorName() const;
159559
159560 string GetTypeName() const;
159561
159562 string GetArrowFormat() const;
159563
159564 void SetArrowFormat(string arrow_format);
159565
159566 bool IsCanonical() const;
159567
159568 bool operator==(
const ArrowExtensionMetadata &other)
const;
159569
159571 static constexpr const char *ARROW_EXTENSION_NON_CANONICAL = "arrow.opaque";
159572
159573private:
159575 string extension_name {};
159578 string vendor_name {};
159580 string type_name {};
159582 string arrow_format {};
159583};
159584
159585class ArrowTypeExtension;
159586
159587typedef void (*populate_arrow_schema_t)(DuckDBArrowSchemaHolder &root_holder, ArrowSchema &child,
159588 const LogicalType &type, ClientContext &context,
159589 const ArrowTypeExtension &extension);
159590
159591typedef unique_ptr<ArrowType> (*get_type_t)(ClientContext &context, const ArrowSchema &schema,
159592 const ArrowSchemaMetadata &schema_metadata);
159593
159594class ArrowTypeExtension {
159595public:
159596 ArrowTypeExtension() {};
159598 explicit ArrowTypeExtension(ArrowExtensionMetadata &extension_metadata, unique_ptr<ArrowType> type);
159600 ArrowTypeExtension(string extension_name, string arrow_format, shared_ptr<ArrowTypeExtensionData> type);
159601 ArrowTypeExtension(string vendor_name, string type_name, string arrow_format,
159602 shared_ptr<ArrowTypeExtensionData> type);
159603
159605 ArrowTypeExtension(string extension_name, populate_arrow_schema_t populate_arrow_schema, get_type_t get_type,
159606 shared_ptr<ArrowTypeExtensionData> type);
159607 ArrowTypeExtension(string vendor_name, string type_name, populate_arrow_schema_t populate_arrow_schema,
159608 get_type_t get_type, shared_ptr<ArrowTypeExtensionData> type, cast_arrow_duck_t arrow_to_duckdb,
159609 cast_duck_arrow_t duckdb_to_arrow);
159610
159611 ArrowExtensionMetadata GetInfo() const;
159612
159613 unique_ptr<ArrowType> GetType(ClientContext &context, const ArrowSchema &schema,
159614 const ArrowSchemaMetadata &schema_metadata) const;
159615
159616 shared_ptr<ArrowTypeExtensionData> GetTypeExtension() const;
159617
159619
159620 LogicalType GetLogicalType() const;
159621
159622 bool HasType() const;
159623
159624 static void PopulateArrowSchema(DuckDBArrowSchemaHolder &root_holder, ArrowSchema &child,
159625 const LogicalType &duckdb_type, ClientContext &context,
159626 const ArrowTypeExtension &extension);
159627
159629 populate_arrow_schema_t populate_arrow_schema = nullptr;
159631 get_type_t get_type = nullptr;
159632
159633private:
159635 ArrowExtensionMetadata extension_metadata;
159637 shared_ptr<ArrowTypeExtensionData> type_extension;
159638};
159639
159640struct HashArrowTypeExtension {
159641 size_t operator()(ArrowExtensionMetadata
const &arrow_extension_info)
const noexcept {
159642 return arrow_extension_info.GetHash();
159643 }
159644};
159645
159646struct TypeInfo {
159647 TypeInfo();
159648 explicit TypeInfo(const LogicalType &type);
159649 explicit TypeInfo(string alias);
159650 string alias;
159652 hash_t GetHash()
const;
159653 bool operator==(
const TypeInfo &other)
const;
159654};
159655
159656struct HashTypeInfo {
159657 size_t operator()(TypeInfo
const &type_info)
const noexcept {
159658 return type_info.GetHash();
159659 }
159660};
159661
159663struct ArrowTypeExtensionSet {
159664 ArrowTypeExtensionSet() {};
159665 static void Initialize(const DBConfig &config);
159666 std::mutex lock;
159667 unordered_map<ArrowExtensionMetadata, ArrowTypeExtension, HashArrowTypeExtension> type_extensions;
159668 unordered_map<TypeInfo, vector<ArrowExtensionMetadata>, HashTypeInfo> type_to_info;
159669};
159670
159671}
159672
159673
159674
159675
159676
159677
159678
159679
159680
159681
159682
159683
159684
159685
159686
159687
159688
159689
159690namespace duckdb {
159691
159692class CGroups {
159693public:
159694 static optional_idx GetMemoryLimit(FileSystem &fs);
159695 static idx_t GetCPULimit(FileSystem &fs, idx_t physical_cores);
159696};
159697
159698}
159699
159700
159701
159702
159703
159704
159705
159706
159707
159708
159709
159710
159711
159712
159713namespace duckdb {
159714
159715enum class AccessMode :
uint8_t {
UNDEFINED = 0, AUTOMATIC = 1, READ_ONLY = 2, READ_WRITE = 3 };
159716
159717}
159718
159719
159720
159721
159722
159723
159724
159725
159726
159727
159728
159729
159730
159731namespace duckdb {
159732
159733enum class CacheValidationMode :
uint8_t {
159734
159735 VALIDATE_ALL = 0,
159736
159737 VALIDATE_REMOTE = 1,
159738
159739 NO_VALIDATION = 2,
159740};
159741
159742}
159743
159744
159745
159746
159747
159748
159749
159750
159751
159752
159753
159754
159755
159756namespace duckdb {
159757
159758enum class ThreadPinMode :
uint8_t { OFF = 0, ON = 1, AUTO = 2 };
159759
159760}
159761
159762
159763
159764
159765
159766
159767
159768
159769
159770
159771
159772
159773
159774
159775
159776
159777
159778
159779
159780
159781
159782
159783
159784
159785
159786
159787
159788
159789
159790
159791
159792
159793
159794
159795
159796
159797
159798
159799
159800
159801
159802
159803
159804
159805
159806
159807
159808
159809
159810
159811
159812
159813
159814
159815
159816
159817
159818
159819
159820
159821
159822
159823
159824
159825namespace duckdb {
159826
159828struct JoinCondition {
159829public:
159830 JoinCondition() {
159831 }
159832
159835 static unique_ptr<Expression> CreateExpression(JoinCondition cond);
159836 static unique_ptr<Expression> CreateExpression(vector<JoinCondition> conditions);
159837
159838 void Serialize(Serializer &serializer) const;
159839 static JoinCondition Deserialize(Deserializer &deserializer);
159840
159841public:
159842 unique_ptr<Expression> left;
159843 unique_ptr<Expression> right;
159844 ExpressionType comparison;
159845};
159846
159847class JoinSide {
159848public:
159849 enum JoinValue :
uint8_t { NONE, LEFT, RIGHT, BOTH };
159850
159851 JoinSide() = default;
159852 constexpr JoinSide(JoinValue val) : value(val) {
159853 }
159854
159856 return value == a.value;
159857 }
159859 return value != a.value;
159860 }
159861
159862 static JoinSide CombineJoinSide(JoinSide left, JoinSide right);
159863 static JoinSide GetJoinSide(idx_t table_binding, const unordered_set<idx_t> &left_bindings,
159864 const unordered_set<uint64_t> &right_bindings);
159865 static JoinSide GetJoinSide(Expression &expression, const unordered_set<idx_t> &left_bindings,
159866 const unordered_set<idx_t> &right_bindings);
159867 static JoinSide GetJoinSide(const unordered_set<idx_t> &bindings, const unordered_set<idx_t> &left_bindings,
159868 const unordered_set<idx_t> &right_bindings);
159869
159870private:
159871 JoinValue value;
159872};
159873
159874}
159875
159876
159877
159878
159879
159880namespace duckdb {
159881class ClientContext;
159882class ColumnDataCollection;
159883
159884class PhysicalPlan {
159885public:
159886 explicit PhysicalPlan(Allocator &allocator) : arena(allocator) {};
159887
159888 ~PhysicalPlan() {
159889
159890 for (auto &op : ops) {
159891 auto &op_ref = op.get();
159892 op_ref.~PhysicalOperator();
159893 }
159894 }
159895
159896public:
159897 template <class T, class... ARGS>
159898 PhysicalOperator &Make(ARGS &&... args) {
159899 static_assert(std::is_base_of<PhysicalOperator, T>::value, "T must be a physical operator");
159900 auto ptr = arena.Make<T>(*this, std::forward<ARGS>(args)...);
159901 ops.push_back(*ptr);
159902 return *ptr;
159903 }
159904
159905 PhysicalOperator &Root() {
159906 D_ASSERT(root);
159907 return *root;
159908 }
159909 void SetRoot(PhysicalOperator &op) {
159910 root = op;
159911 }
159913 ArenaAllocator &ArenaRef() {
159914 return arena;
159915 }
159916
159917private:
159919 ArenaAllocator arena;
159921 vector<reference<PhysicalOperator>> ops;
159923 optional_ptr<PhysicalOperator> root;
159924};
159925
159927class PhysicalPlanGenerator {
159928public:
159929 explicit PhysicalPlanGenerator(ClientContext &context);
159930 ~PhysicalPlanGenerator();
159931
159932 LogicalDependencyList dependencies;
159935 unordered_map<idx_t, shared_ptr<ColumnDataCollection>> recursive_cte_tables;
159937 unordered_map<idx_t, shared_ptr<ColumnDataCollection>> recurring_cte_tables;
159939 unordered_map<idx_t, vector<const_reference<PhysicalOperator>>> materialized_ctes;
159941 idx_t delim_index = 0;
159942
159943public:
159946 unique_ptr<PhysicalPlan> Plan(unique_ptr<LogicalOperator> logical);
159947 PhysicalOperator &CreatePlan(LogicalOperator &op);
159948
159950 static bool UseBatchIndex(ClientContext &context, PhysicalOperator &plan);
159952 static bool PreserveInsertionOrder(ClientContext &context, PhysicalOperator &plan);
159954 static OrderPreservationType OrderPreservationRecursive(PhysicalOperator &op);
159955
159957 template <class T, class... ARGS>
159958 PhysicalOperator &Make(ARGS &&... args) {
159959 return physical_plan->Make<T>(std::forward<ARGS>(args)...);
159960 }
159961
159964 ArenaAllocator &ArenaRef();
159965
159966public:
159967 PhysicalOperator &ResolveDefaultsProjection(LogicalInsert &op, PhysicalOperator &child);
159968
159969protected:
159970 PhysicalOperator &CreatePlan(LogicalAggregate &op);
159971 PhysicalOperator &CreatePlan(LogicalAnyJoin &op);
159972 PhysicalOperator &CreatePlan(LogicalColumnDataGet &op);
159973 PhysicalOperator &CreatePlan(LogicalComparisonJoin &op);
159974 PhysicalOperator &CreatePlan(LogicalCopyDatabase &op);
159975 PhysicalOperator &CreatePlan(LogicalCreate &op);
159976 PhysicalOperator &CreatePlan(LogicalCreateTable &op);
159977 PhysicalOperator &CreatePlan(LogicalCreateIndex &op);
159978 PhysicalOperator &CreatePlan(LogicalCreateSecret &op);
159979 PhysicalOperator &CreatePlan(LogicalCrossProduct &op);
159980 PhysicalOperator &CreatePlan(LogicalDelete &op);
159981 PhysicalOperator &CreatePlan(LogicalDelimGet &op);
159982 PhysicalOperator &CreatePlan(LogicalDistinct &op);
159983 PhysicalOperator &CreatePlan(LogicalDummyScan &expr);
159984 PhysicalOperator &CreatePlan(LogicalEmptyResult &op);
159985 PhysicalOperator &CreatePlan(LogicalExpressionGet &op);
159986 PhysicalOperator &CreatePlan(LogicalExport &op);
159987 PhysicalOperator &CreatePlan(LogicalFilter &op);
159988 PhysicalOperator &CreatePlan(LogicalGet &op);
159989 PhysicalOperator &CreatePlan(LogicalLimit &op);
159990 PhysicalOperator &CreatePlan(LogicalMergeInto &op);
159991 PhysicalOperator &CreatePlan(LogicalOrder &op);
159992 PhysicalOperator &CreatePlan(LogicalTopN &op);
159993 PhysicalOperator &CreatePlan(LogicalPositionalJoin &op);
159994 PhysicalOperator &CreatePlan(LogicalProjection &op);
159995 PhysicalOperator &CreatePlan(LogicalInsert &op);
159996 PhysicalOperator &CreatePlan(LogicalCopyToFile &op);
159997 PhysicalOperator &CreatePlan(LogicalExplain &op);
159998 PhysicalOperator &CreatePlan(LogicalSetOperation &op);
159999 PhysicalOperator &CreatePlan(LogicalUpdate &op);
160000 PhysicalOperator &CreatePlan(LogicalPrepare &expr);
160001 PhysicalOperator &CreatePlan(LogicalWindow &expr);
160002 PhysicalOperator &CreatePlan(LogicalExecute &op);
160003 PhysicalOperator &CreatePlan(LogicalPragma &op);
160004 PhysicalOperator &CreatePlan(LogicalSample &op);
160005 PhysicalOperator &CreatePlan(LogicalSet &op);
160006 PhysicalOperator &CreatePlan(LogicalReset &op);
160007 PhysicalOperator &CreatePlan(LogicalSimple &op);
160008 PhysicalOperator &CreatePlan(LogicalVacuum &op);
160009 PhysicalOperator &CreatePlan(LogicalUnnest &op);
160010 PhysicalOperator &CreatePlan(LogicalRecursiveCTE &op);
160011 PhysicalOperator &CreatePlan(LogicalMaterializedCTE &op);
160012 PhysicalOperator &CreatePlan(LogicalCTERef &op);
160013 PhysicalOperator &CreatePlan(LogicalPivot &op);
160014
160015 PhysicalOperator &PlanAsOfJoin(LogicalComparisonJoin &op);
160016 PhysicalOperator &PlanComparisonJoin(LogicalComparisonJoin &op);
160017 PhysicalOperator &PlanDelimJoin(LogicalComparisonJoin &op);
160018 PhysicalOperator &ExtractAggregateExpressions(PhysicalOperator &child, vector<unique_ptr<Expression>> &expressions,
160019 vector<unique_ptr<Expression>> &groups,
160020 optional_ptr<vector<GroupingSet>> grouping_sets);
160021
160022private:
160023 ClientContext &context;
160024 unique_ptr<PhysicalPlan> physical_plan;
160025
160026private:
160027 PhysicalOperator &ResolveAndPlan(unique_ptr<LogicalOperator> logical);
160028 unique_ptr<PhysicalPlan> PlanInternal(LogicalOperator &logical);
160029 bool PreserveInsertionOrder(PhysicalOperator &plan);
160030 bool UseBatchIndex(PhysicalOperator &plan);
160031 optional_ptr<PhysicalOperator> PlanAsOfLoopJoin(LogicalComparisonJoin &op, PhysicalOperator &probe,
160032 PhysicalOperator &build);
160033};
160034}
160035
160036
160037namespace duckdb {
160038
160039class BoundIndex;
160040class PhysicalOperator;
160041class LogicalCreateIndex;
160042enum class IndexConstraintType :
uint8_t;
160043class Expression;
160044class TableIOManager;
160045class AttachedDatabase;
160046struct IndexStorageInfo;
160047class ClientContext;
160048
160049struct CreateIndexInput {
160050 ClientContext &context;
160051 TableIOManager &table_io_manager;
160052 AttachedDatabase &
db;
160053 IndexConstraintType constraint_type;
160054 const string &name;
160055 const vector<column_t> &column_ids;
160056 const vector<unique_ptr<Expression>> &unbound_expressions;
160057 const IndexStorageInfo &storage_info;
160058 const case_insensitive_map_t<Value> &options;
160059
160060 CreateIndexInput(ClientContext &context, TableIOManager &table_io_manager, AttachedDatabase &db,
160061 IndexConstraintType constraint_type, const string &name, const vector<column_t> &column_ids,
160062 const vector<unique_ptr<Expression>> &unbound_expressions, const IndexStorageInfo &storage_info,
160063 const case_insensitive_map_t<Value> &options)
160064 : context(context), table_io_manager(table_io_manager),
db(
db), constraint_type(constraint_type), name(name),
160065 column_ids(column_ids), unbound_expressions(unbound_expressions), storage_info(storage_info),
160066 options(options) {};
160067};
160068
160069struct IndexTypeInfo {
160070 DUCKDB_API virtual ~IndexTypeInfo() = default;
160071
160072 template <class TARGET>
160073 TARGET &Cast() {
160074 DynamicCastCheck<TARGET>(this);
160075 return reinterpret_cast<TARGET &>(*this);
160076 }
160077 template <class TARGET>
160078 const TARGET &Cast() const {
160079 DynamicCastCheck<TARGET>(this);
160080 return reinterpret_cast<const TARGET &>(*this);
160081 }
160082};
160083
160084struct IndexBuildBindData {
160085 DUCKDB_API virtual ~IndexBuildBindData() = default;
160086
160087 template <class TARGET>
160088 TARGET &Cast() {
160089 DynamicCastCheck<TARGET>(this);
160090 return reinterpret_cast<TARGET &>(*this);
160091 }
160092 template <class TARGET>
160093 const TARGET &Cast() const {
160094 DynamicCastCheck<TARGET>(this);
160095 return reinterpret_cast<const TARGET &>(*this);
160096 }
160097};
160098
160099struct IndexBuildGlobalState {
160100 DUCKDB_API virtual ~IndexBuildGlobalState() = default;
160101
160102 template <class TARGET>
160103 TARGET &Cast() {
160104 DynamicCastCheck<TARGET>(this);
160105 return reinterpret_cast<TARGET &>(*this);
160106 }
160107 template <class TARGET>
160108 const TARGET &Cast() const {
160109 DynamicCastCheck<TARGET>(this);
160110 return reinterpret_cast<const TARGET &>(*this);
160111 }
160112};
160113
160114struct IndexBuildLocalState {
160115 DUCKDB_API virtual ~IndexBuildLocalState() = default;
160116
160117 template <class TARGET>
160118 TARGET &Cast() {
160119 DynamicCastCheck<TARGET>(this);
160120 return reinterpret_cast<TARGET &>(*this);
160121 }
160122 template <class TARGET>
160123 const TARGET &Cast() const {
160124 DynamicCastCheck<TARGET>(this);
160125 return reinterpret_cast<const TARGET &>(*this);
160126 }
160127};
160128
160129class DuckTableEntry;
160130
160131struct IndexBuildInitLocalStateInput {
160132 optional_ptr<IndexBuildBindData> bind_data;
160133 ClientContext &context;
160134 DuckTableEntry &table;
160135 CreateIndexInfo &info;
160136 const vector<unique_ptr<Expression>> &expressions;
160137 const vector<column_t> storage_ids;
160138};
160139
160140struct IndexBuildInitGlobalStateInput {
160141 optional_ptr<IndexBuildBindData> bind_data;
160142 ClientContext &context;
160143 DuckTableEntry &table;
160144 CreateIndexInfo &info;
160145 const vector<unique_ptr<Expression>> &expressions;
160146 const vector<column_t> storage_ids;
160147};
160148
160149struct IndexBuildBindInput {
160150 ClientContext &context;
160151 DuckTableEntry &table;
160152 CreateIndexInfo &info;
160153 const vector<unique_ptr<Expression>> &expressions;
160154};
160155
160156struct IndexBuildSortInput {
160157 optional_ptr<IndexBuildBindData> bind_data;
160158};
160159
160160struct IndexBuildCombineInput {
160161 optional_ptr<IndexBuildBindData> bind_data;
160162 IndexBuildGlobalState &global_state;
160163 IndexBuildLocalState &local_state;
160164 DuckTableEntry &table;
160165 CreateIndexInfo &info;
160166};
160167
160168struct IndexBuildSinkInput {
160169 optional_ptr<IndexBuildBindData> bind_data;
160170 IndexBuildGlobalState &global_state;
160171 IndexBuildLocalState &local_state;
160172 DuckTableEntry &table;
160173 CreateIndexInfo &info;
160174};
160175
160176struct IndexBuildFinalizeInput {
160177 IndexBuildGlobalState &global_state;
160178};
160179
160180typedef unique_ptr<IndexBuildBindData> (*index_build_bind_t)(IndexBuildBindInput &input);
160181typedef bool (*index_build_sort_t)(IndexBuildSortInput &input);
160182typedef unique_ptr<IndexBuildGlobalState> (*index_build_global_init_t)(IndexBuildInitGlobalStateInput &input);
160183typedef unique_ptr<IndexBuildLocalState> (*index_build_local_init_t)(IndexBuildInitLocalStateInput &input);
160184typedef void (*index_build_sink_t)(IndexBuildSinkInput &input, DataChunk &key_chunk, DataChunk &row_chunk);
160185typedef void (*index_build_combine_t)(IndexBuildCombineInput &input);
160186typedef unique_ptr<BoundIndex> (*index_build_finalize_t)(IndexBuildFinalizeInput &input);
160187
160188struct PlanIndexInput {
160189 ClientContext &context;
160190 LogicalCreateIndex &op;
160191 PhysicalPlanGenerator &planner;
160192 PhysicalOperator &table_scan;
160193 shared_ptr<IndexTypeInfo> index_info;
160194
160195 PlanIndexInput(ClientContext &context_p, LogicalCreateIndex &op_p, PhysicalPlanGenerator &planner,
160196 PhysicalOperator &table_scan_p, shared_ptr<IndexTypeInfo> index_info_p = nullptr)
160197 : context(context_p), op(op_p), planner(planner), table_scan(table_scan_p),
160198 index_info(std::move(index_info_p)) {
160199 }
160200};
160201
160202typedef unique_ptr<BoundIndex> (*index_create_function_t)(CreateIndexInput &input);
160203typedef PhysicalOperator &(*index_build_plan_t)(PlanIndexInput &input);
160204
160206class IndexType {
160207public:
160208
160209 string name;
160210
160211
160212 index_build_bind_t build_bind = nullptr;
160213 index_build_sort_t build_sort = nullptr;
160214 index_build_global_init_t build_global_init = nullptr;
160215 index_build_local_init_t build_local_init = nullptr;
160216 index_build_sink_t build_sink = nullptr;
160217 index_build_combine_t build_combine = nullptr;
160218 index_build_finalize_t build_finalize = nullptr;
160219
160221 shared_ptr<IndexTypeInfo> index_info = nullptr;
160222
160223 index_build_plan_t create_plan = nullptr;
160224 index_create_function_t create_instance = nullptr;
160225};
160226
160227}
160228
160229
160230
160231
160232
160233
160234namespace duckdb {
160235
160236class IndexTypeSet {
160237 mutex lock;
160238 case_insensitive_tree_t<IndexType> functions;
160239
160240public:
160241 IndexTypeSet();
160242 DUCKDB_API optional_ptr<IndexType> FindByName(const string &name);
160243 DUCKDB_API
void RegisterIndexType(
const IndexType &
index_type);
160244};
160245
160246}
160247
160248
160249
160250
160251
160252
160253
160254
160255
160256
160257
160258
160259
160260
160261
160262
160263
160264namespace duckdb {
160265
160266class CastFunctionSet;
160267struct FunctionLocalState;
160268
160270struct BindCastInfo {
160271 DUCKDB_API virtual ~BindCastInfo();
160272
160273 template <class TARGET>
160274 TARGET &Cast() {
160275 DynamicCastCheck<TARGET>(this);
160276 return reinterpret_cast<TARGET &>(*this);
160277 }
160278 template <class TARGET>
160279 const TARGET &Cast() const {
160280 DynamicCastCheck<TARGET>(this);
160281 return reinterpret_cast<const TARGET &>(*this);
160282 }
160283};
160284
160286struct BoundCastData {
160287 DUCKDB_API virtual ~BoundCastData();
160288
160289 DUCKDB_API virtual unique_ptr<BoundCastData> Copy() const = 0;
160290
160291 template <class TARGET>
160292 TARGET &Cast() {
160293 DynamicCastCheck<TARGET>(this);
160294 return reinterpret_cast<TARGET &>(*this);
160295 }
160296 template <class TARGET>
160297 const TARGET &Cast() const {
160298 DynamicCastCheck<TARGET>(this);
160299 return reinterpret_cast<const TARGET &>(*this);
160300 }
160301};
160302
160303struct CastParameters {
160304 CastParameters() {
160305 }
160306 CastParameters(bool strict, string *error_message) : CastParameters(nullptr, strict, error_message, nullptr) {
160307 }
160308 CastParameters(BoundCastData *cast_data, bool strict, string *error_message,
160309 optional_ptr<FunctionLocalState> local_state, bool nullify_parent_p = false)
160310 : cast_data(cast_data), strict(strict), error_message(error_message), local_state(local_state),
160311 nullify_parent(nullify_parent_p) {
160312 }
160313 CastParameters(CastParameters &parent, optional_ptr<BoundCastData> cast_data,
160314 optional_ptr<FunctionLocalState> local_state)
160315 : cast_data(cast_data), strict(parent.strict), error_message(parent.error_message), local_state(local_state),
160316 query_location(parent.query_location) {
160317 }
160318
160320 optional_ptr<BoundCastData> cast_data;
160322 bool strict = false;
160323
160324 string *error_message = nullptr;
160326 optional_ptr<const Expression> cast_source;
160328 optional_ptr<const Expression> cast_target;
160330 optional_ptr<FunctionLocalState> local_state;
160332 optional_idx query_location;
160334 bool nullify_parent = false;
160335};
160336
160337struct CastLocalStateParameters {
160338 CastLocalStateParameters(optional_ptr<ClientContext> context_p, optional_ptr<BoundCastData> cast_data_p)
160339 : context(context_p), cast_data(cast_data_p) {
160340 }
160341 CastLocalStateParameters(ClientContext &context_p, optional_ptr<BoundCastData> cast_data_p)
160342 : context(&context_p), cast_data(cast_data_p) {
160343 }
160344 CastLocalStateParameters(CastLocalStateParameters &parent, optional_ptr<BoundCastData> cast_data_p)
160345 : context(parent.context), cast_data(cast_data_p) {
160346 }
160347
160348 optional_ptr<ClientContext> context;
160350 optional_ptr<BoundCastData> cast_data;
160351};
160352
160353typedef bool (*cast_function_t)(Vector &source, Vector &result,
idx_t count, CastParameters ¶meters);
160354typedef unique_ptr<FunctionLocalState> (*init_cast_local_state_t)(CastLocalStateParameters ¶meters);
160355
160356struct BoundCastInfo {
160357 DUCKDB_API
160358 BoundCastInfo(
160359 cast_function_t function, unique_ptr<BoundCastData> cast_data = nullptr,
160360 init_cast_local_state_t init_local_state = nullptr);
160361 cast_function_t function;
160362 init_cast_local_state_t init_local_state;
160363 unique_ptr<BoundCastData> cast_data;
160364
160365public:
160366 BoundCastInfo Copy() const;
160367};
160368
160369struct BindCastInput {
160370 DUCKDB_API BindCastInput(CastFunctionSet &function_set, optional_ptr<BindCastInfo> info,
160371 optional_ptr<ClientContext> context);
160372
160373 CastFunctionSet &function_set;
160374 optional_ptr<BindCastInfo> info;
160375 optional_ptr<ClientContext> context;
160376 optional_idx query_location;
160377
160378public:
160379 DUCKDB_API BoundCastInfo GetCastFunction(const LogicalType &source, const LogicalType &target);
160380};
160381
160382struct DefaultCasts {
160383 DUCKDB_API static BoundCastInfo GetDefaultCastFunction(BindCastInput &input, const LogicalType &source,
160384 const LogicalType &target);
160385
160386 DUCKDB_API static bool NopCast(Vector &source, Vector &result, idx_t count, CastParameters ¶meters);
160387 DUCKDB_API static bool TryVectorNullCast(Vector &source, Vector &result, idx_t count, CastParameters ¶meters);
160388 DUCKDB_API static bool ReinterpretCast(Vector &source, Vector &result, idx_t count, CastParameters ¶meters);
160389
160390private:
160391 static BoundCastInfo BlobCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160392 static BoundCastInfo BitCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160393 static BoundCastInfo DateCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160394 static BoundCastInfo DecimalCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160395 static BoundCastInfo EnumCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160396 static BoundCastInfo IntervalCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160397 static BoundCastInfo ListCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160398 static BoundCastInfo ArrayCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160399 static BoundCastInfo NumericCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160400 static BoundCastInfo MapCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160401 static BoundCastInfo PointerCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160402 static BoundCastInfo StringCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160403 static BoundCastInfo StructCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160404 static BoundCastInfo TimeCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160405 static BoundCastInfo TimeNsCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160406 static BoundCastInfo TimeTzCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160407 static BoundCastInfo TimestampCastSwitch(BindCastInput &input, const LogicalType &source,
160408 const LogicalType &target);
160409 static BoundCastInfo TimestampTzCastSwitch(BindCastInput &input, const LogicalType &source,
160410 const LogicalType &target);
160411 static BoundCastInfo TimestampNsCastSwitch(BindCastInput &input, const LogicalType &source,
160412 const LogicalType &target);
160413 static BoundCastInfo TimestampMsCastSwitch(BindCastInput &input, const LogicalType &source,
160414 const LogicalType &target);
160415 static BoundCastInfo TimestampSecCastSwitch(BindCastInput &input, const LogicalType &source,
160416 const LogicalType &target);
160417 static BoundCastInfo UnionCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160418 static BoundCastInfo VariantCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160419 static BoundCastInfo UUIDCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160420 static BoundCastInfo GeoCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160421 static BoundCastInfo TypeCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160422 static BoundCastInfo BignumCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
160423 static BoundCastInfo ImplicitToUnionCast(BindCastInput &input, const LogicalType &source,
160424 const LogicalType &target);
160425 static BoundCastInfo ImplicitToVariantCast(BindCastInput &input, const LogicalType &source,
160426 const LogicalType &target);
160427};
160428
160429}
160430
160431
160432
160433
160434
160435
160436
160437
160438
160439
160440
160441
160442
160443
160444
160445namespace duckdb {
160446
160447class ClientContext;
160448class TableRef;
160449
160450struct ReplacementScanData {
160451public:
160452 virtual ~ReplacementScanData() {
160453 }
160454
160455public:
160456 template <class TARGET>
160457 TARGET &Cast() {
160458 DynamicCastCheck<TARGET>(this);
160459 return reinterpret_cast<TARGET &>(*this);
160460 }
160461 template <class TARGET>
160462 const TARGET &Cast() const {
160463 DynamicCastCheck<TARGET>(this);
160464 return reinterpret_cast<const TARGET &>(*this);
160465 }
160466};
160467
160468struct ReplacementScanInput {
160469public:
160470 explicit ReplacementScanInput(const string &catalog_name, const string &schema_name, const string &table_name)
160471 : catalog_name(catalog_name), schema_name(schema_name), table_name(table_name) {
160472 }
160473
160474public:
160475 const string &catalog_name;
160476 const string &schema_name;
160477 const string &table_name;
160478};
160479
160480typedef unique_ptr<TableRef> (*replacement_scan_t)(ClientContext &context, ReplacementScanInput &input,
160481 optional_ptr<ReplacementScanData> data);
160482
160485struct ReplacementScan {
160486 explicit ReplacementScan(replacement_scan_t function, unique_ptr<ReplacementScanData> data_p = nullptr)
160487 : function(function), data(std::move(data_p)) {
160488 }
160489
160490 static bool CanReplace(const string &table_name, const vector<string> &extensions) {
160492
160493 if (
StringUtil::EndsWith(lower_name, CompressionExtensionFromType(FileCompressionType::GZIP))) {
160494 lower_name = lower_name.substr(0, lower_name.size() - 3);
160495 }
else if (
StringUtil::EndsWith(lower_name, CompressionExtensionFromType(FileCompressionType::ZSTD))) {
160496 lower_name = lower_name.substr(0, lower_name.size() - 4);
160497 }
160498
160499 for (auto &extension : extensions) {
160502 return true;
160503 }
160504 }
160505
160506 return false;
160507 }
160508
160509 static string GetFullPath(const string &catalog, const string &schema, const string &table) {
160510 string table_name = catalog;
160511 if (!schema.empty()) {
160512 table_name += (!table_name.empty() ? "." : "") + schema;
160513 }
160514 table_name += (!table_name.empty() ? "." : "") + table;
160515 return table_name;
160516 }
160517
160518 static string GetFullPath(ReplacementScanInput &input) {
160519 return GetFullPath(input.catalog_name, input.schema_name, input.table_name);
160520 }
160521
160522 replacement_scan_t function;
160523 unique_ptr<ReplacementScanData> data;
160524};
160525
160526}
160527
160528
160529
160530
160531
160532
160533
160534
160535
160536
160537
160538
160539
160540namespace duckdb {
160541
160542enum class BitpackingMode :
uint8_t { INVALID, AUTO, CONSTANT, CONSTANT_DELTA, DELTA_FOR, FOR };
160543
160544}
160545
160546
160547
160548
160549
160550
160551
160552
160553
160554
160555
160556
160557
160558
160559
160560
160561
160562
160563
160564
160565
160566
160567
160568
160569
160570
160571
160572
160573
160574
160575
160576
160577namespace duckdb {
160578
160579class Serializer;
160580class Deserializer;
160581class QueryContext;
160582
160583struct ColumnSegmentState {
160584 virtual ~ColumnSegmentState() {
160585 }
160586
160587 virtual void Serialize(Serializer &serializer) const = 0;
160588 static unique_ptr<ColumnSegmentState> Deserialize(Deserializer &deserializer);
160589
160590 template <class TARGET>
160591 TARGET &Cast() {
160592 DynamicCastCheck<TARGET>(this);
160593 return reinterpret_cast<TARGET &>(*this);
160594 }
160595 template <class TARGET>
160596 const TARGET &Cast() const {
160597 DynamicCastCheck<TARGET>(this);
160598 return reinterpret_cast<const TARGET &>(*this);
160599 }
160600
160601public:
160602 vector<block_id_t> blocks;
160603};
160604
160605struct DataPointer {
160606 explicit DataPointer(BaseStatistics stats);
160607
160608 DataPointer(const DataPointer &other) = delete;
160609 DataPointer &
operator=(
const DataPointer &) =
delete;
160611 DUCKDB_API DataPointer(DataPointer &&other) noexcept;
160612 DUCKDB_API DataPointer &
operator=(DataPointer &&) noexcept;
160613
160614 uint64_t row_start;
160615 uint64_t tuple_count;
160616 BlockPointer block_pointer;
160617 CompressionType compression_type;
160619 BaseStatistics statistics;
160621 unique_ptr<ColumnSegmentState> segment_state;
160622
160623 void Serialize(Serializer &serializer) const;
160624 static DataPointer Deserialize(Deserializer &source);
160625};
160626
160627struct RowGroupPointer {
160631 vector<MetaBlockPointer> data_pointers;
160633 vector<MetaBlockPointer> deletes_pointers;
160635 bool has_metadata_blocks = false;
160638 vector<idx_t> extra_metadata_blocks;
160639};
160640
160641}
160642
160643
160644
160645namespace duckdb {
160646
160647struct DBConfig;
160648
160649class EncodingFunction;
160650
160651struct CSVEncoderBuffer;
160653typedef void (*encode_t)(CSVEncoderBuffer &encoded_buffer,
char *decoded_buffer,
idx_t &decoded_buffer_current_position,
160654 const idx_t decoded_buffer_size,
char *remaining_bytes_buffer,
idx_t &remaining_bytes_size,
160655 EncodingFunction *encoding_function);
160656
160658typedef struct {
160659 size_t key_len;
160660 const char *key;
160661 size_t value_len;
160662 const char *value;
160663} map_entry_encoding;
160664
160665class EncodingFunction {
160666public:
160667 DUCKDB_API EncodingFunction() : encode_function(nullptr), max_bytes_per_iteration(0) {
160668 }
160669
160670 DUCKDB_API EncodingFunction(const string &encode_name, encode_t encode_function, const idx_t bytes_per_iteration,
160671 const idx_t lookup_bytes)
160672 : name(encode_name), encode_function(encode_function), max_bytes_per_iteration(bytes_per_iteration),
160673 lookup_bytes(lookup_bytes) {
160674 D_ASSERT(encode_function);
160675 D_ASSERT(bytes_per_iteration > 0);
160676 D_ASSERT(lookup_bytes > 0);
160677 };
160678
160679 DUCKDB_API EncodingFunction(const string &encode_name, encode_t encode_function, const idx_t bytes_per_iteration,
160680 const idx_t lookup_bytes, const map_entry_encoding *map, const size_t map_size)
160681 : conversion_map(map), map_size(map_size), name(encode_name), encode_function(encode_function),
160682 max_bytes_per_iteration(bytes_per_iteration), lookup_bytes(lookup_bytes) {
160683 D_ASSERT(encode_function);
160684 D_ASSERT(bytes_per_iteration > 0);
160685 D_ASSERT(lookup_bytes > 0);
160686 };
160687
160688 DUCKDB_API ~EncodingFunction() {};
160689
160690 DUCKDB_API string GetName() const {
160691 return name;
160692 }
160693 DUCKDB_API
encode_t GetFunction()
const {
160694 return encode_function;
160695 }
160696 DUCKDB_API
idx_t GetBytesPerIteration()
const {
160697 return max_bytes_per_iteration;
160698 }
160699 DUCKDB_API
idx_t GetLookupBytes()
const {
160700 return lookup_bytes;
160701 }
160702
160704 const map_entry_encoding *conversion_map {};
160705 size_t map_size {};
160706
160707protected:
160709 string name;
160715 idx_t max_bytes_per_iteration;
160717 idx_t lookup_bytes = 1;
160718};
160719
160721struct EncodingFunctionSet {
160722 EncodingFunctionSet() {};
160723 static void Initialize(DBConfig &config);
160724 mutex lock;
160725 case_insensitive_map_t<EncodingFunction> functions;
160726};
160727
160728}
160729
160730
160731
160732
160733
160734
160735
160736
160737
160738
160739
160740
160741
160742
160743
160744
160745
160746
160747
160748
160749
160750
160751
160752
160753
160754
160755
160756
160757
160758
160759
160760
160761
160762
160763
160764
160765
160766
160767
160768namespace duckdb {
160769
160770
160772 LOG_TRACE = 10,
160773 LOG_DEBUG = 20,
160774 LOG_INFO = 30,
160775 LOG_WARNING = 40,
160776 LOG_ERROR = 50,
160777 LOG_FATAL = 60
160778};
160779
160780enum class LogContextScope :
uint8_t { DATABASE = 10, CONNECTION = 20, THREAD = 30 };
160781
160782enum class LogMode :
uint8_t { LEVEL_ONLY = 0, DISABLE_SELECTED = 1, ENABLE_SELECTED = 2 };
160783
160784struct LogConfig {
160785 constexpr static const char *IN_MEMORY_STORAGE_NAME = "memory";
160786 constexpr static const char *STDOUT_STORAGE_NAME = "stdout";
160787 constexpr static const char *FILE_STORAGE_NAME = "file";
160788
160789 constexpr static LogLevel DEFAULT_LOG_LEVEL = LogLevel::LOG_INFO;
160790 constexpr static const char *DEFAULT_LOG_STORAGE = IN_MEMORY_STORAGE_NAME;
160791
160792 LogConfig();
160793
160794 DUCKDB_API bool IsConsistent() const;
160795
160796 bool enabled;
160797 LogMode mode;
160799 string storage;
160800
160801 unordered_set<string> enabled_log_types;
160802 unordered_set<string> disabled_log_types;
160803
160804protected:
160805 LogConfig(bool enabled, LogLevel level, LogMode mode, optional_ptr<unordered_set<string>> enabled_log_types,
160806 optional_ptr<unordered_set<string>> disable_loggers);
160807};
160808
160809struct LoggingContext {
160810 explicit LoggingContext(LogContextScope scope_p) : scope(scope_p) {
160811 }
160812
160813 LogContextScope scope;
160814
160815 optional_idx thread_id;
160816 optional_idx connection_id;
160817 optional_idx transaction_id;
160818 optional_idx query_id;
160819};
160820
160821struct RegisteredLoggingContext {
160823 LoggingContext context;
160824};
160825
160826}
160827
160828
160829
160830
160831
160832
160833
160834
160835
160836
160837
160838
160839
160840
160841namespace duckdb {
160842
160843struct FileHandle;
160844struct BaseRequest;
160845struct HTTPResponse;
160846class PhysicalOperator;
160847class AttachedDatabase;
160848class RowGroup;
160849struct DataTableInfo;
160850enum class MetricType :
uint8_t;
160851
160854class LogType {
160855public:
160857 LogType(const string &name_p, const LogLevel &level_p)
160858 : name(name_p), level(level_p), is_structured(false), type(LogicalType::VARCHAR) {
160859 }
160861 LogType(const string &name_p, const LogLevel &level_p, LogicalType structured_type)
160862 : name(name_p), level(level_p), is_structured(true), type(std::move(structured_type)) {
160863 if (!type.IsNested()) {
160864 throw InternalException("LogType must be nested if the type is explicitly set");
160865 }
160866 }
160867
160868 string name;
160870
160871 bool is_structured;
160872 LogicalType type;
160873};
160874
160875class DefaultLogType : public LogType {
160876public:
160877 static constexpr const char *NAME = "";
160878 static constexpr LogLevel LEVEL = LogLevel::LOG_INFO;
160879
160880 DefaultLogType() : LogType(NAME, LEVEL) {
160881 }
160882};
160883
160884class QueryLogType : public LogType {
160885public:
160886 static constexpr const char *NAME = "QueryLog";
160887 static constexpr LogLevel LEVEL = LogLevel::LOG_INFO;
160888
160889 QueryLogType() : LogType(NAME, LEVEL) {};
160890
160891 static string ConstructLogMessage(const string &str);
160892};
160893
160894class FileSystemLogType : public LogType {
160895public:
160896 static constexpr const char *NAME = "FileSystem";
160897 static constexpr LogLevel LEVEL = LogLevel::LOG_TRACE;
160898
160900 FileSystemLogType();
160901
160902 static LogicalType GetLogType();
160903
160904 static string ConstructLogMessage(const FileHandle &handle, const string &op, int64_t bytes, idx_t pos);
160905 static string ConstructLogMessage(const FileHandle &handle, const string &op);
160906};
160907
160908class HTTPLogType : public LogType {
160909public:
160910 static constexpr const char *NAME = "HTTP";
160911 static constexpr LogLevel LEVEL = LogLevel::LOG_DEBUG;
160912
160914 HTTPLogType();
160915
160916 static LogicalType GetLogType();
160917
160918 static string ConstructLogMessage(BaseRequest &request, optional_ptr<HTTPResponse> response);
160919
160920
160921 static string ConstructLogMessage(const string &str) {
160922 return str;
160923 }
160924};
160925
160926class PhysicalOperatorLogType : public LogType {
160927public:
160928 static constexpr const char *NAME = "PhysicalOperator";
160929 static constexpr LogLevel LEVEL = LogLevel::LOG_DEBUG;
160930
160932 PhysicalOperatorLogType();
160933
160934 static LogicalType GetLogType();
160935
160936 static string ConstructLogMessage(const PhysicalOperator &op, const string &class_p, const string &event,
160937 const vector<pair<string, string>> &info);
160938};
160939
160940class MetricsLogType : public LogType {
160941public:
160942 static constexpr const char *NAME = "Metrics";
160943 static constexpr LogLevel LEVEL = LogLevel::LOG_INFO;
160944
160946 MetricsLogType();
160947
160948 static LogicalType GetLogType();
160949
160950 static string ConstructLogMessage(const MetricType &type, const Value &value);
160951};
160952
160953class CheckpointLogType : public LogType {
160954public:
160955 static constexpr const char *NAME = "Checkpoint";
160956 static constexpr LogLevel LEVEL = LogLevel::LOG_DEBUG;
160957
160959 CheckpointLogType();
160960
160961 static LogicalType GetLogType();
160962
160964 static string ConstructLogMessage(const AttachedDatabase &db, DataTableInfo &table, idx_t segment_idx,
160965 idx_t merge_count, idx_t target_count, idx_t merge_rows, idx_t row_start);
160967 static string ConstructLogMessage(const AttachedDatabase &db, DataTableInfo &table, idx_t segment_idx,
160968 RowGroup &row_group, idx_t row_group_start);
160969
160970private:
160971 static string CreateLog(const AttachedDatabase &db, DataTableInfo &table, const char *op, vector<Value> map_keys,
160972 vector<Value> map_values);
160973};
160974
160975class TransactionLogType : public LogType {
160976public:
160977 static constexpr const char *NAME = "Transaction";
160978 static constexpr LogLevel LEVEL = LogLevel::LOG_DEBUG;
160979
160981 TransactionLogType();
160982
160983 static LogicalType GetLogType();
160984
160985 static string ConstructLogMessage(const AttachedDatabase &db, const char *log_type,
160986 transaction_t transaction_id = MAX_TRANSACTION_ID);
160987};
160988
160989}
160990
160991
160992
160993
160994namespace duckdb {
160995class TableDescription;
160996class DatabaseInstance;
160997class DataChunk;
160998class LogManager;
160999class ColumnDataCollection;
161000class ThreadContext;
161001class FileOpener;
161002class LogStorage;
161003class ExecutionContext;
161004struct FileHandle;
161005
161007#define DUCKDB_LOG_INTERNAL(SOURCE, TYPE, LEVEL, ...) \
161008 { \
161009 auto &logger_ref_ = Logger::Get(SOURCE); \
161010 if (logger_ref_.ShouldLog(TYPE, LEVEL)) { \
161011 logger_ref_.WriteLog(TYPE, LEVEL, __VA_ARGS__); \
161012 } \
161013 }
161014
161016#define DUCKDB_LOG_TRACE(SOURCE, ...) \
161017 DUCKDB_LOG_INTERNAL(SOURCE, DefaultLogType::NAME, LogLevel::LOG_TRACE, __VA_ARGS__)
161018#define DUCKDB_LOG_DEBUG(SOURCE, ...) \
161019 DUCKDB_LOG_INTERNAL(SOURCE, DefaultLogType::NAME, LogLevel::LOG_DEBUG, __VA_ARGS__)
161020#define DUCKDB_LOG_INFO(SOURCE, ...) DUCKDB_LOG_INTERNAL(SOURCE, DefaultLogType::NAME, LogLevel::LOG_INFO, __VA_ARGS__)
161021#define DUCKDB_LOG_WARNING(SOURCE, ...) \
161022 DUCKDB_LOG_INTERNAL(SOURCE, DefaultLogType::NAME, LogLevel::LOG_WARNING, __VA_ARGS__)
161023#define DUCKDB_LOG_ERROR(SOURCE, ...) \
161024 DUCKDB_LOG_INTERNAL(SOURCE, DefaultLogType::NAME, LogLevel::LOG_ERROR, __VA_ARGS__)
161025#define DUCKDB_LOG_FATAL(SOURCE, ...) \
161026 DUCKDB_LOG_INTERNAL(SOURCE, DefaultLogType::NAME, LogLevel::LOG_FATAL, __VA_ARGS__)
161027
161029#define DUCKDB_LOG(SOURCE, LOG_TYPE_CLASS, ...) \
161030 DUCKDB_LOG_INTERNAL(SOURCE, LOG_TYPE_CLASS::NAME, LOG_TYPE_CLASS::LEVEL, \
161031 LOG_TYPE_CLASS::ConstructLogMessage(__VA_ARGS__))
161032
161034class Logger {
161035public:
161036 DUCKDB_API explicit Logger(LogManager &manager) : manager(manager) {
161037 }
161038
161039 DUCKDB_API virtual ~Logger() = default;
161040
161041
161042 DUCKDB_API virtual bool ShouldLog(const char *log_type, LogLevel log_level) = 0;
161043 DUCKDB_API void WriteLog(const char *log_type, LogLevel log_level, const char *message);
161044
161045
161046 DUCKDB_API void WriteLog(const char *log_type, LogLevel log_level, const string &message);
161047 DUCKDB_API void WriteLog(const char *log_type, LogLevel log_level, const string_t &message);
161048
161049
161050 template <typename... ARGS>
161051 void WriteLog(const char *log_type, LogLevel log_level, const char *format_string, ARGS... params) {
161053 WriteLog(log_type, log_level, formatted_string.c_str());
161054 }
161055
161056 DUCKDB_API virtual void Flush() = 0;
161057
161058
161059
161060
161061 DUCKDB_API static Logger &Get(const ThreadContext &thread_context);
161062 DUCKDB_API static Logger &Get(const ExecutionContext &execution_context);
161063 DUCKDB_API static Logger &Get(const ClientContext &client_context);
161064 DUCKDB_API static Logger &Get(const FileOpener &opener);
161065 DUCKDB_API static Logger &Get(const DatabaseInstance &db);
161066 DUCKDB_API static Logger &Get(const shared_ptr<Logger> &logger);
161067
161068 template <class T>
161069 static void Flush(T &log_context_source) {
161070 Get(log_context_source).Flush();
161071 }
161072
161073 DUCKDB_API virtual bool IsThreadSafe() = 0;
161074 DUCKDB_API virtual bool IsMutable() {
161075 return false;
161076 };
161077 DUCKDB_API virtual void UpdateConfig(LogConfig &new_config) {
161078 throw InternalException("Cannot update the config of this logger!");
161079 }
161080 DUCKDB_API virtual const LogConfig &GetConfig() const = 0;
161081
161082protected:
161083 virtual void WriteLogInternal(const char *log_type, LogLevel log_level, const char *message) = 0;
161084
161085protected:
161086 LogManager &manager;
161087};
161088
161089
161090class ThreadSafeLogger : public Logger {
161091public:
161092 explicit ThreadSafeLogger(LogConfig &config_p, LoggingContext &context_p, LogManager &manager);
161093 explicit ThreadSafeLogger(LogConfig &config_p, RegisteredLoggingContext context_p, LogManager &manager);
161094
161095
161096 bool ShouldLog(const char *log_type, LogLevel log_level) override;
161097 void WriteLogInternal(const char *log_type, LogLevel log_level, const char *message) override;
161098
161099 void Flush() override;
161100 bool IsThreadSafe() override {
161101 return true;
161102 }
161103 const LogConfig &GetConfig() const override {
161104 return config;
161105 }
161106
161107protected:
161108 const LogConfig config;
161109 mutex lock;
161110 const RegisteredLoggingContext context;
161111};
161112
161113
161114
161115class ThreadLocalLogger : public Logger {
161116public:
161117 explicit ThreadLocalLogger(LogConfig &config_p, LoggingContext &context_p, LogManager &manager);
161118 explicit ThreadLocalLogger(LogConfig &config_p, RegisteredLoggingContext context_p, LogManager &manager);
161119
161120
161121 bool ShouldLog(const char *log_type, LogLevel log_level) override;
161122 void WriteLogInternal(const char *log_type, LogLevel log_level, const char *message) override;
161123 void Flush() override;
161124
161125 bool IsThreadSafe() override {
161126 return false;
161127 }
161128 const LogConfig &GetConfig() const override {
161129 return config;
161130 }
161131
161132protected:
161133 const LogConfig config;
161134 const RegisteredLoggingContext context;
161135};
161136
161137
161138class MutableLogger : public Logger {
161139public:
161140 explicit MutableLogger(LogConfig &config_p, LoggingContext &context_p, LogManager &manager);
161141 explicit MutableLogger(LogConfig &config_p, RegisteredLoggingContext context_p, LogManager &manager);
161142
161143
161144 bool ShouldLog(const char *log_type, LogLevel log_level) override;
161145 void WriteLogInternal(const char *log_type, LogLevel log_level, const char *message) override;
161146
161147 void Flush() override;
161148 bool IsThreadSafe() override {
161149 return true;
161150 }
161151 bool IsMutable() override {
161152 return true;
161153 }
161154 const LogConfig &GetConfig() const override {
161155 return config;
161156 }
161157 void UpdateConfig(LogConfig &new_config) override;
161158
161159protected:
161160
161161 atomic<bool> enabled;
161162 atomic<LogMode> mode;
161163 atomic<LogLevel> level;
161164
161165 mutex lock;
161166 LogConfig config;
161167 const RegisteredLoggingContext context;
161168};
161169
161170
161171class NopLogger : public Logger {
161172public:
161173 explicit NopLogger(LogManager &manager) : Logger(manager) {
161174 }
161175 bool ShouldLog(const char *log_type, LogLevel log_level) override {
161176 return false;
161177 }
161178 void WriteLogInternal(const char *log_type, LogLevel log_level, const char *message) override {};
161179 void Flush() override {
161180 }
161181 bool IsThreadSafe() override {
161182 return true;
161183 }
161184 const LogConfig &GetConfig() const override {
161185 throw InternalException("Called GetConfig on NopLogger");
161186 }
161187};
161188
161189}
161190
161191
161192
161193
161194
161195
161196
161197
161198
161199
161200
161201
161202
161203
161204
161205
161206
161207
161208
161209
161210
161211
161212
161213
161214
161215
161216
161217
161218
161219
161220
161221
161222namespace duckdb {
161223class ClientContext;
161224class Logger;
161225
161227class ThreadContext {
161228public:
161229 explicit ThreadContext(ClientContext &context);
161230 ~ThreadContext();
161231
161233 OperatorProfiler profiler;
161234 unique_ptr<Logger> logger;
161235};
161236
161237}
161238
161239
161240namespace duckdb {
161241struct RegisteredLoggingContext;
161242class ColumnDataCollection;
161243struct ColumnDataScanState;
161244class MemoryStream;
161245struct LogStorageConfig;
161246class CSVWriter;
161247struct CSVWriterState;
161248class BufferedFileWriter;
161249struct CSVWriterOptions;
161250struct CSVReaderOptions;
161251
161255 ALL_LOGS,
161256 LOG_ENTRIES,
161257 LOG_CONTEXTS,
161258};
161259
161260class LogStorageScanState {
161261public:
161262 explicit LogStorageScanState(LoggingTargetTable table_p) : table(table_p) {
161263 }
161264 virtual ~LogStorageScanState() = default;
161265
161266 template <class TARGET>
161267 TARGET &Cast() {
161268 DynamicCastCheck<TARGET>(this);
161269 return reinterpret_cast<TARGET &>(*this);
161270 }
161271 template <class TARGET>
161272 const TARGET &Cast() const {
161273 DynamicCastCheck<TARGET>(this);
161274 return reinterpret_cast<const TARGET &>(*this);
161275 }
161276
161278};
161279
161280
161281class LogStorage {
161282public:
161283 DUCKDB_API explicit LogStorage() {
161284 }
161285 DUCKDB_API virtual ~LogStorage() = default;
161286
161287 virtual const string GetStorageName() = 0;
161288
161289 static vector<LogicalType> GetSchema(LoggingTargetTable table);
161290 static vector<string> GetColumnNames(LoggingTargetTable table);
161291
161293 DUCKDB_API virtual void WriteLogEntry(timestamp_t timestamp, LogLevel level, const string &log_type,
161294 const string &log_message, const RegisteredLoggingContext &context) = 0;
161295 DUCKDB_API virtual void WriteLogEntries(DataChunk &chunk, const RegisteredLoggingContext &context) = 0;
161296 DUCKDB_API virtual void FlushAll() = 0;
161297 DUCKDB_API virtual void Flush(LoggingTargetTable table) = 0;
161298 DUCKDB_API virtual void Truncate();
161299 DUCKDB_API virtual bool IsEnabled(LoggingTargetTable table) = 0;
161300
161302 DUCKDB_API virtual bool CanScan(LoggingTargetTable table) {
161303 return false;
161304 }
161305
161306 DUCKDB_API virtual unique_ptr<LogStorageScanState> CreateScanState(LoggingTargetTable table) const;
161307 DUCKDB_API virtual bool Scan(LogStorageScanState &state, DataChunk &result) const;
161308 DUCKDB_API virtual void InitializeScan(LogStorageScanState &state) const;
161309
161310
161311 DUCKDB_API virtual unique_ptr<TableRef> BindReplace(ClientContext &context, TableFunctionBindInput &input,
161312 LoggingTargetTable table);
161313
161315 DUCKDB_API virtual void UpdateConfig(DatabaseInstance &db, case_insensitive_map_t<Value> &config);
161316};
161317
161320class BufferingLogStorage : public LogStorage {
161321public:
161322 explicit BufferingLogStorage(DatabaseInstance &db_p, idx_t buffer_size, bool normalize);
161323 ~BufferingLogStorage() override;
161324
161326
161328 void WriteLogEntry(timestamp_t timestamp, LogLevel level, const string &log_type, const string &log_message,
161329 const RegisteredLoggingContext &context) final;
161331 void WriteLogEntries(DataChunk &chunk, const RegisteredLoggingContext &context) final;
161333 void FlushAll() final;
161335 void Flush(LoggingTargetTable table) final;
161337 void Truncate() override;
161339 void UpdateConfig(DatabaseInstance &db, case_insensitive_map_t<Value> &config) override;
161341 bool IsEnabled(LoggingTargetTable table) override;
161342
161343protected:
161345
161347 virtual void FlushChunk(LoggingTargetTable table, DataChunk &chunk) = 0;
161350 virtual void UpdateConfigInternal(DatabaseInstance &db, case_insensitive_map_t<Value> &config);
161353 virtual void ResetAllBuffers();
161354
161356
161358 void FlushAllInternal();
161360 void FlushInternal(LoggingTargetTable table);
161362 bool IsEnabledInternal(LoggingTargetTable table);
161363
161364 idx_t GetBufferLimit() const;
161365
161368 mutable mutex lock;
161371 bool normalize_contexts = true;
161372
161373private:
161375 void ResetLogBuffers();
161377 void WriteLoggingContext(const RegisteredLoggingContext &context);
161378
161380 unordered_set<idx_t> registered_contexts;
161382 idx_t buffer_limit = 0;
161384 bool only_flush_on_full_buffer = false;
161386 map<LoggingTargetTable, unique_ptr<DataChunk>> buffers;
161389 bool flush_contexts_on_next_entry_flush = false;
161390};
161391
161396class CSVLogStorage : public BufferingLogStorage {
161397public:
161398 explicit CSVLogStorage(DatabaseInstance &db, bool normalize, idx_t buffer_size);
161399 ~CSVLogStorage() override;
161400
161401protected:
161403
161405 void FlushChunk(LoggingTargetTable table, DataChunk &chunk) final;
161407 void ResetAllBuffers() override;
161409 void UpdateConfigInternal(DatabaseInstance &db, case_insensitive_map_t<Value> &config) override;
161410
161412
161414 virtual void BeforeFlush(LoggingTargetTable table, DataChunk &chunk) {};
161415 virtual void AfterFlush(LoggingTargetTable table, DataChunk &chunk) {};
161416
161418
161420 void RegisterWriter(LoggingTargetTable table, unique_ptr<CSVWriter> writer);
161422 CSVWriter &GetWriter(LoggingTargetTable table);
161424 void SetWriterConfigs(CSVWriter &Writer, vector<string> column_names);
161426 CSVWriterOptions &GetCSVWriterOptions();
161428 CSVReaderOptions &GetCSVReaderOptions();
161429
161430private:
161432 void ExecuteCast(LoggingTargetTable table, DataChunk &chunk);
161434 void ResetCastChunk();
161436 void InitializeCastChunk(LoggingTargetTable table);
161437
161439 map<LoggingTargetTable, unique_ptr<DataChunk>> cast_buffers;
161441 map<LoggingTargetTable, unique_ptr<CSVWriter>> writers;
161442
161445 unique_ptr<CSVWriterOptions> writer_options;
161446 unique_ptr<CSVReaderOptions> reader_options;
161447};
161448
161451class StdOutLogStorage : public CSVLogStorage {
161452public:
161453 explicit StdOutLogStorage(DatabaseInstance &db);
161454 ~StdOutLogStorage() override;
161455
161456 const string GetStorageName() override {
161457 return "StdOutLogStorage";
161458 }
161459
161460private:
161461 class StdOutWriteStream : public WriteStream {
161462 void WriteData(const_data_ptr_t buffer, idx_t write_size) override;
161463 };
161464
161465 StdOutWriteStream stdout_stream;
161466};
161467
161471class FileLogStorage : public CSVLogStorage {
161472public:
161473 explicit FileLogStorage(DatabaseInstance &db);
161474 ~FileLogStorage() override;
161475
161476 const string GetStorageName() override {
161477 return "FileLogStorage";
161478 }
161479
161481
161483 void Truncate() override;
161485 unique_ptr<TableRef> BindReplace(ClientContext &context, TableFunctionBindInput &input,
161486 LoggingTargetTable table) override;
161487
161488protected:
161490
161492 void UpdateConfigInternal(DatabaseInstance &db, case_insensitive_map_t<Value> &config) override;
161494 void BeforeFlush(LoggingTargetTable table, DataChunk &chunk) override;
161496 void AfterFlush(LoggingTargetTable table, DataChunk &chunk) override;
161497
161498private:
161500 void InitializeFile(DatabaseInstance &db, LoggingTargetTable table);
161502 static unique_ptr<BufferedFileWriter> InitializeFileWriter(DatabaseInstance &db, const string &path);
161504 void Initialize(LoggingTargetTable table);
161506 unique_ptr<TableRef> BindReplaceInternal(ClientContext &context, TableFunctionBindInput &input, const string &path,
161507 const string &select_clause, const string &csv_columns);
161508
161510 DatabaseInstance &
db;
161511
161513 struct TableWriter {
161515 unique_ptr<BufferedFileWriter> file_writer;
161517 string path;
161519 bool initialized = false;
161520 };
161521
161523 map<LoggingTargetTable, TableWriter> tables;
161524
161526 string base_path;
161527
161528private:
161529 void SetPaths(const string &base_path);
161530};
161531
161533class InMemoryLogStorageScanState : public LogStorageScanState {
161534public:
161535 explicit InMemoryLogStorageScanState(LoggingTargetTable table);
161536 ~InMemoryLogStorageScanState() override;
161537
161538 ColumnDataScanState scan_state;
161539};
161540
161543class InMemoryLogStorage : public BufferingLogStorage {
161544public:
161545 explicit InMemoryLogStorage(DatabaseInstance &db);
161546 ~InMemoryLogStorage() override;
161547
161548 const string GetStorageName() override {
161549 return "InMemoryLogStorage";
161550 }
161551
161553 bool CanScan(LoggingTargetTable table) override;
161554 unique_ptr<LogStorageScanState> CreateScanState(LoggingTargetTable table) const override;
161555 bool Scan(LogStorageScanState &state, DataChunk &result) const override;
161556 void InitializeScan(LogStorageScanState &state) const override;
161557
161558protected:
161560
161562 void FlushChunk(LoggingTargetTable table, DataChunk &chunk) override;
161564 void ResetAllBuffers() override;
161565
161566private:
161568 ColumnDataCollection &GetBuffer(LoggingTargetTable table) const;
161569
161570 map<LoggingTargetTable, unique_ptr<ColumnDataCollection>> log_storage_buffers;
161571};
161572
161573}
161574
161575
161576
161577
161578namespace duckdb {
161579class LogType;
161580
161581
161582
161583
161584
161585
161586class LogManager {
161587 friend class ThreadSafeLogger;
161588 friend class ThreadLocalLogger;
161589 friend class MutableLogger;
161590
161591public:
161592
161593 explicit LogManager(DatabaseInstance &db, LogConfig config = LogConfig());
161594 ~LogManager();
161595 void Initialize();
161596
161597 DUCKDB_API static LogManager &Get(ClientContext &context);
161598 unique_ptr<Logger> CreateLogger(LoggingContext context, bool thread_safe = true, bool mutable_settings = false);
161599
161600 RegisteredLoggingContext RegisterLoggingContext(LoggingContext &context);
161601
161602 DUCKDB_API bool RegisterLogStorage(const string &name, shared_ptr<LogStorage> &storage);
161603
161605 DUCKDB_API Logger &GlobalLogger();
161606 DUCKDB_API shared_ptr<Logger> GlobalLoggerReference();
161607
161609 DUCKDB_API void Flush();
161610
161612 DUCKDB_API shared_ptr<LogStorage> GetLogStorage();
161613 DUCKDB_API bool CanScan(LoggingTargetTable table);
161614
161615 DUCKDB_API void SetConfig(DatabaseInstance &db, const LogConfig &config);
161616 DUCKDB_API void SetEnableLogging(bool enable);
161617 DUCKDB_API void SetLogMode(LogMode mode);
161618 DUCKDB_API void SetLogLevel(LogLevel level);
161619 DUCKDB_API void SetEnabledLogTypes(optional_ptr<unordered_set<string>> enabled_log_types);
161620 DUCKDB_API void SetDisabledLogTypes(optional_ptr<unordered_set<string>> disabled_log_types);
161621 DUCKDB_API void SetLogStorage(DatabaseInstance &db, const string &storage_name);
161622
161623 DUCKDB_API void UpdateLogStorageConfig(DatabaseInstance &db, case_insensitive_map_t<Value> &config_value);
161624
161625 DUCKDB_API void SetEnableStructuredLoggers(vector<string> &enabled_logger_types);
161626
161627 DUCKDB_API void TruncateLogStorage();
161628
161629 DUCKDB_API LogConfig GetConfig();
161630
161631 DUCKDB_API void RegisterLogType(unique_ptr<LogType> type);
161632 DUCKDB_API optional_ptr<const LogType> LookupLogType(const string &type);
161633 DUCKDB_API void RegisterDefaultLogTypes();
161634
161635protected:
161636 RegisteredLoggingContext RegisterLoggingContextInternal(LoggingContext &context);
161637
161638
161639 void WriteLogEntry(timestamp_t, const char *log_type, LogLevel log_level, const char *log_message,
161640 const RegisteredLoggingContext &context);
161641
161642 void FlushCachedLogEntries(DataChunk &chunk, const RegisteredLoggingContext &context);
161643
161644 void SetLogStorageInternal(DatabaseInstance &db, const string &storage_name);
161645
161646 optional_ptr<const LogType> LookupLogTypeInternal(const string &type);
161647
161648 void SetConfigInternal(LogConfig config);
161649
161650protected:
161651 mutex lock;
161652 LogConfig config;
161653
161654 shared_ptr<Logger> global_logger;
161655 shared_ptr<LogStorage> log_storage;
161656 DatabaseInstance &db_instance;
161657
161658 idx_t next_registered_logging_context_index = 0;
161659
161660
161661 case_insensitive_map_t<shared_ptr<LogStorage>> registered_log_storages;
161662 case_insensitive_map_t<unique_ptr<LogType>> registered_log_types;
161663};
161664
161665}
161666
161667
161668
161669
161670
161671
161672
161673
161674namespace duckdb {
161675
161676class ClientContext;
161677class DatabaseInstance;
161678class CastFunctionSet;
161679struct DBConfig;
161680
161681class TypeManager {
161682public:
161683 explicit TypeManager(DBConfig &config);
161684
161685 ~TypeManager();
161686
161688 CastFunctionSet &GetCastFunctions();
161689
161691 LogicalType ParseLogicalType(const string &type_str, ClientContext &context) const;
161692
161694 static TypeManager &Get(DatabaseInstance &db);
161695 static TypeManager &Get(ClientContext &context);
161696
161697private:
161700 LogicalType (*parse_function)(const string &, ClientContext &);
161701
161703 unique_ptr<CastFunctionSet> cast_functions;
161704};
161705
161706}
161707
161708
161709namespace duckdb {
161710
161711class BlockAllocator;
161712class BufferManager;
161713class BufferPool;
161714class CastFunctionSet;
161715class CollationBinding;
161716class ClientContext;
161717class ErrorManager;
161718class CompressionFunction;
161719class TableFunctionRef;
161720class OperatorExtension;
161721class StorageExtension;
161722class ExtensionCallback;
161723class SecretManager;
161724class CompressionInfo;
161725class EncryptionUtil;
161726class HTTPUtil;
161727class DatabaseFilePathManager;
161728class ExtensionCallbackManager;
161729class TypeManager;
161730
161731struct CompressionFunctionSet;
161732struct DatabaseCacheEntry;
161733struct DBConfig;
161734struct SettingLookupResult;
161735
161736class SerializationCompatibility {
161737public:
161738 static SerializationCompatibility FromDatabase(AttachedDatabase &db);
161739 static SerializationCompatibility FromIndex(idx_t serialization_version);
161740 static SerializationCompatibility FromString(const string &input);
161741 static SerializationCompatibility Default();
161742 static SerializationCompatibility Latest();
161743
161744public:
161745 bool Compare(idx_t property_version) const;
161746
161747public:
161749 string duckdb_version;
161751 idx_t serialization_version;
161753 bool manually_set;
161754
161755protected:
161756 SerializationCompatibility() = default;
161757};
161758
161762struct DBConfigOptions {
161764 string database_path;
161766 string database_type;
161768 AccessMode access_mode = AccessMode::AUTOMATIC;
161770 idx_t checkpoint_wal_size = 1 << 24;
161772 bool use_direct_io = false;
161774 bool load_extensions = true;
161776 idx_t maximum_memory = DConstants::INVALID_INDEX;
161778 idx_t maximum_swap_space = DConstants::INVALID_INDEX;
161780 idx_t maximum_threads = DConstants::INVALID_INDEX;
161782 bool use_temporary_directory = true;
161784 string temporary_directory;
161787 bool trim_free_blocks = false;
161789 bool buffer_manager_track_eviction_timestamps = false;
161791 bool force_checkpoint = false;
161793 bool checkpoint_on_shutdown = true;
161795 SerializationCompatibility serialization_compatibility = SerializationCompatibility::Default();
161798 bool initialize_default_database = true;
161800 bool force_mbedtls = false;
161802 set<OptimizerType> disabled_optimizers;
161804 LogicalType force_variant_shredding = LogicalType::INVALID;
161806 case_insensitive_map_t<Value> set_variable_defaults;
161808 vector<string> extension_directories;
161810 DebugInitialize debug_initialize = DebugInitialize::NO_INITIALIZE;
161812 case_insensitive_map_t<Value> user_options;
161814 case_insensitive_map_t<Value> unrecognized_options;
161816 static bool debug_print_bindings;
161818 idx_t allocator_flush_threshold = 134217728ULL;
161820 idx_t allocator_bulk_deallocation_flush_threshold = 536870912ULL;
161822 bool variant_legacy_encoding = false;
161824 string custom_user_agent;
161826 idx_t default_block_header_size = DEFAULT_BLOCK_HEADER_STORAGE_SIZE;
161828 bool abort_on_wal_failure = false;
161830 unordered_set<string> allowed_paths;
161832 set<string> allowed_directories;
161834 case_insensitive_set_t allowed_configs;
161836 LogConfig log_config = LogConfig();
161838 idx_t block_allocator_size = 0;
161839
161840 bool operator==(
const DBConfigOptions &other)
const;
161841};
161842
161843struct DBConfig {
161844 friend class DatabaseInstance;
161845 friend class StorageManager;
161846
161847public:
161848 DUCKDB_API DBConfig();
161849 explicit DUCKDB_API DBConfig(bool read_only);
161850 DUCKDB_API DBConfig(const case_insensitive_map_t<Value> &config_dict, bool read_only);
161851 DUCKDB_API ~DBConfig();
161852
161854 vector<ReplacementScan> replacement_scans;
161855
161858 unique_ptr<FileSystem> file_system;
161860 unique_ptr<SecretManager> secret_manager;
161862 unique_ptr<Allocator> allocator;
161864 unique_ptr<BlockAllocator> block_allocator;
161866 DBConfigOptions options;
161868 unique_ptr<ErrorManager> error_manager;
161870 shared_ptr<Allocator> default_allocator;
161872 shared_ptr<BufferPool> buffer_pool;
161874 shared_ptr<BufferManager> buffer_manager;
161876 shared_ptr<EncryptionUtil> encryption_util;
161878 shared_ptr<DatabaseCacheEntry> db_cache_entry;
161880 shared_ptr<DatabaseFilePathManager> path_manager;
161882 GlobalUserSettings user_settings;
161883
161884public:
161885 DUCKDB_API static DBConfig &GetConfig(ClientContext &context);
161886 DUCKDB_API static DBConfig &GetConfig(DatabaseInstance &db);
161887 DUCKDB_API static DBConfig &Get(AttachedDatabase &db);
161888 DUCKDB_API static const DBConfig &GetConfig(const ClientContext &context);
161889 DUCKDB_API static const DBConfig &GetConfig(const DatabaseInstance &db);
161890 DUCKDB_API static vector<ConfigurationOption> GetOptions();
161891 DUCKDB_API static vector<ConfigurationAlias> GetAliases();
161892 DUCKDB_API
static idx_t GetOptionCount();
161893 DUCKDB_API
static idx_t GetAliasCount();
161894 DUCKDB_API static vector<string> GetOptionNames();
161895 DUCKDB_API static bool IsInMemoryDatabase(const char *database_path);
161896
161897 DUCKDB_API void AddExtensionOption(const string &name, string description, LogicalType parameter,
161898 const Value &default_value = Value(), set_option_callback_t function = nullptr,
161899 SetScope default_scope = SetScope::SESSION);
161900 DUCKDB_API bool HasExtensionOption(const string &name) const;
161901 DUCKDB_API case_insensitive_map_t<ExtensionOption> GetExtensionSettings() const;
161902 DUCKDB_API
bool TryGetExtensionOption(
const String &name, ExtensionOption &result)
const;
161904 DUCKDB_API static optional_ptr<const ConfigurationOption> GetOptionByIndex(idx_t index);
161906 DUCKDB_API static optional_ptr<const ConfigurationAlias> GetAliasByIndex(idx_t index);
161908 DUCKDB_API
static optional_ptr<const ConfigurationOption> GetOptionByName(
const String &name);
161909 DUCKDB_API void SetOption(const ConfigurationOption &option, const Value &value);
161910 DUCKDB_API void SetOption(optional_ptr<DatabaseInstance> db, const ConfigurationOption &option, const Value &value);
161911 DUCKDB_API void SetOption(const string &name, Value value);
161912 DUCKDB_API void SetOption(idx_t setting_index, Value value);
161913 DUCKDB_API void SetOptionByName(const string &name, const Value &value);
161914 DUCKDB_API void SetOptionsByName(const case_insensitive_map_t<Value> &values);
161915 DUCKDB_API void ResetOption(optional_ptr<DatabaseInstance> db, const ConfigurationOption &option);
161916 DUCKDB_API void ResetOption(const ExtensionOption &extension_option);
161917 DUCKDB_API void ResetGenericOption(idx_t setting_index);
161918 DUCKDB_API optional_idx TryGetSettingIndex(
const String &name,
161919 optional_ptr<const ConfigurationOption> &option) const;
161920 static LogicalType ParseLogicalType(const string &type);
161921
161922 DUCKDB_API
void CheckLock(
const String &name);
161923
161924 DUCKDB_API
static idx_t ParseMemoryLimit(
const string &
arg);
161925
161927 DUCKDB_API vector<reference<const CompressionFunction>>
161928 GetCompressionFunctions(const PhysicalType physical_type) const;
161931 DUCKDB_API reference<const CompressionFunction> GetCompressionFunction(CompressionType type,
161932 const PhysicalType physical_type) const;
161933 DUCKDB_API optional_ptr<const CompressionFunction>
161934 TryGetCompressionFunction(CompressionType type, const PhysicalType physical_type) const;
161936 DUCKDB_API void SetDisabledCompressionMethods(const vector<CompressionType> &disabled_compression_methods);
161938 DUCKDB_API vector<CompressionType> GetDisabledCompressionMethods() const;
161939
161941 DUCKDB_API optional_ptr<EncodingFunction> GetEncodeFunction(const string &name) const;
161942 DUCKDB_API void RegisterEncodeFunction(const EncodingFunction &function) const;
161944 DUCKDB_API vector<reference<EncodingFunction>> GetLoadedEncodedFunctions() const;
161946 DUCKDB_API ArrowTypeExtension GetArrowExtension(ArrowExtensionMetadata info) const;
161947 DUCKDB_API ArrowTypeExtension GetArrowExtension(const LogicalType &type) const;
161948 DUCKDB_API bool HasArrowExtension(const LogicalType &type) const;
161949 DUCKDB_API bool HasArrowExtension(ArrowExtensionMetadata info) const;
161950 DUCKDB_API void RegisterArrowExtension(const ArrowTypeExtension &extension) const;
161951
161954
161955 DUCKDB_API CastFunctionSet &GetCastFunctions();
161956 DUCKDB_API TypeManager &GetTypeManager();
161957 DUCKDB_API CollationBinding &GetCollationBinding();
161958 DUCKDB_API IndexTypeSet &GetIndexTypes();
161959 static idx_t GetSystemMaxThreads(FileSystem &fs);
161960 static idx_t GetSystemAvailableMemory(FileSystem &fs);
161961 static optional_idx ParseMemoryLimitSlurm(
const string &
arg);
161962 void SetDefaultMaxMemory();
161963 void SetDefaultTempDirectory();
161964
161965 OrderType ResolveOrder(ClientContext &context, OrderType order_type) const;
161966 OrderByNullType ResolveNullOrder(ClientContext &context, OrderType order_type, OrderByNullType null_type) const;
161967 const string UserAgent() const;
161968
161970 SettingLookupResult TryGetCurrentSetting(const string &key, Value &result) const;
161972 SettingLookupResult TryGetCurrentUserSetting(idx_t setting_index, Value &result) const;
161974 static SettingLookupResult TryGetDefaultValue(optional_ptr<const ConfigurationOption> option, Value &result);
161975
161976 bool CanAccessFile(const string &path, FileType type);
161977 void AddAllowedConfig(const string &config_name);
161978 void AddAllowedDirectory(const string &path);
161979 void AddAllowedPath(const string &path);
161980 string SanitizeAllowedPath(const string &path) const;
161981 ExtensionCallbackManager &GetCallbackManager();
161982 const ExtensionCallbackManager &GetCallbackManager() const;
161983 void SetHTTPUtil(const shared_ptr<HTTPUtil> &new_http_util);
161984 HTTPUtil &GetHTTPUtil() const;
161985
161986private:
161987 mutable mutex config_lock;
161988 unique_ptr<CompressionFunctionSet> compression_functions;
161989 unique_ptr<EncodingFunctionSet> encoding_functions;
161990 unique_ptr<ArrowTypeExtensionSet> arrow_extensions;
161991 unique_ptr<TypeManager> type_manager;
161992 unique_ptr<CollationBinding> collation_bindings;
161993 unique_ptr<IndexTypeSet> index_types;
161994 unique_ptr<ExtensionCallbackManager> callback_manager;
161995 bool is_user_config = true;
161997 shared_ptr<HTTPUtil> http_util;
161998 vector<shared_ptr<HTTPUtil>> old_http_utils;
161999 mutex http_util_lock;
162000};
162001
162002}
162003
162004
162005
162006
162007
162008
162009
162010
162011
162012
162013
162014
162015
162016
162017
162018namespace duckdb {
162019class DatabaseInstance;
162020class MetaTransaction;
162021
162022class ValidChecker {
162023public:
162024 explicit ValidChecker(DatabaseInstance &db);
162025
162026 DUCKDB_API static ValidChecker &Get(DatabaseInstance &db);
162027 DUCKDB_API static ValidChecker &Get(MetaTransaction &transaction);
162028
162029 DUCKDB_API void Invalidate(string error);
162030 DUCKDB_API bool IsInvalidated();
162031 DUCKDB_API string InvalidatedMessage();
162032
162033 template <class T>
162034 static bool IsInvalidated(T &o) {
162035 return Get(o).IsInvalidated();
162036 }
162037 template <class T>
162038 static void Invalidate(T &o, string error) {
162039 Get(o).Invalidate(std::move(error));
162040 }
162041
162042 template <class T>
162043 static string InvalidatedMessage(T &o) {
162044 return Get(o).InvalidatedMessage();
162045 }
162046
162047private:
162048 mutex invalidate_lock;
162050 atomic<bool> is_invalidated;
162052 string invalidated_msg;
162054 DatabaseInstance &
db;
162055};
162056
162057}
162058
162059
162060
162061
162062
162063
162064
162065
162066
162067
162068
162069
162070
162071
162072
162073
162074
162075
162076
162077
162078
162079
162080
162081
162082
162083
162084
162085
162086
162087
162088
162089
162090namespace duckdb {
162091class Catalog;
162092class DatabaseInstance;
162093class StorageManager;
162094class TransactionManager;
162095class StorageExtension;
162096class DatabaseManager;
162097
162098struct AttachInfo;
162099struct StoredDatabasePath;
162100
162101enum class AttachedDatabaseType {
162102 READ_WRITE_DATABASE,
162103 READ_ONLY_DATABASE,
162104 SYSTEM_DATABASE,
162105 TEMP_DATABASE,
162106};
162107
162108enum class AttachVisibility { SHOWN, HIDDEN };
162109
162114
162118
162119class DatabaseFilePathManager;
162120
162121struct StoredDatabasePath {
162122 StoredDatabasePath(DatabaseManager &db_manager, DatabaseFilePathManager &manager, string path, const string &name);
162123 ~StoredDatabasePath();
162124
162125 DatabaseManager &db_manager;
162126 DatabaseFilePathManager &manager;
162127 string path;
162128
162129 void OnDetach();
162130};
162131
162134struct AttachOptions {
162136 explicit AttachOptions(const DBConfigOptions &options);
162138 AttachOptions(const unordered_map<string, Value> &options, const AccessMode default_access_mode);
162139
162141 AccessMode access_mode;
162145 string db_type;
162147 unordered_map<string, Value> options;
162149 QualifiedName default_table;
162151 bool is_main_database = false;
162153 AttachVisibility visibility = AttachVisibility::SHOWN;
162155 unique_ptr<StoredDatabasePath> stored_database_path;
162156};
162157
162159class AttachedDatabase : public CatalogEntry, public enable_shared_from_this<AttachedDatabase> {
162160public:
162162 explicit AttachedDatabase(DatabaseInstance &db, AttachedDatabaseType type = AttachedDatabaseType::SYSTEM_DATABASE);
162164 AttachedDatabase(DatabaseInstance &db, Catalog &catalog, string name, string file_path, AttachOptions &options);
162166 AttachedDatabase(DatabaseInstance &db, Catalog &catalog, StorageExtension &ext, ClientContext &context, string name,
162167 AttachInfo &info, AttachOptions &options);
162168 ~AttachedDatabase() override;
162169
162171 void Initialize(optional_ptr<ClientContext> context = nullptr);
162172 void FinalizeLoad(optional_ptr<ClientContext> context);
162174 void Close(const DatabaseCloseAction action);
162175
162176 Catalog &ParentCatalog() override;
162177 const Catalog &ParentCatalog() const override;
162178 bool HasStorageManager() const;
162179 StorageManager &GetStorageManager();
162180 const StorageManager &GetStorageManager() const;
162181 Catalog &GetCatalog();
162182 TransactionManager &GetTransactionManager();
162183 DatabaseInstance &GetDatabase() {
162185 }
162186
162187 optional_ptr<StorageExtension> GetStorageExtension() {
162188 return storage_extension;
162189 }
162190
162191 const string &GetName() const {
162192 return name;
162193 }
162194 void SetName(const string &new_name) {
162195 name = new_name;
162196 }
162197 bool IsSystem() const;
162198 bool IsTemporary() const;
162199 bool IsReadOnly() const;
162200 bool IsInitialDatabase() const;
162201 void SetInitialDatabase();
162202 void SetReadOnlyDatabase();
162203 void OnDetach(ClientContext &context);
162205 return recovery_mode;
162206 }
162207 AttachVisibility GetVisibility() const {
162208 return visibility;
162209 }
162210 const unordered_map<string, Value> &GetAttachOptions() const {
162211 return attach_options;
162212 }
162213 string StoredPath() const;
162214
162215 static bool NameIsReserved(const string &name);
162216 static string ExtractDatabaseName(const string &dbpath, FileSystem &fs);
162217
162218
162219 static void InvokeCloseIfLastReference(shared_ptr<AttachedDatabase> &attached_database);
162220
162221private:
162222 DatabaseInstance &
db;
162223 unique_ptr<StoredDatabasePath> stored_database_path;
162224 unique_ptr<StorageManager> storage;
162225 unique_ptr<Catalog> catalog;
162226 unique_ptr<TransactionManager> transaction_manager;
162227 AttachedDatabaseType type;
162228 optional_ptr<Catalog> parent_catalog;
162229 optional_ptr<StorageExtension> storage_extension;
162231 AttachVisibility visibility = AttachVisibility::SHOWN;
162232 bool is_initial_database = false;
162233 bool is_closed = false;
162234 shared_ptr<mutex> close_lock;
162235 unordered_map<string, Value> attach_options;
162236
162237private:
162239 void Cleanup();
162240};
162241
162242}
162243
162244
162245namespace duckdb {
162246class AttachedDatabase;
162247class ClientContext;
162248struct DatabaseModificationType;
162249class Transaction;
162250
162251enum class TransactionState { UNCOMMITTED, COMMITTED, ROLLED_BACK };
162252
162253struct TransactionReference {
162254 explicit TransactionReference(Transaction &transaction_p)
162255 : state(TransactionState::UNCOMMITTED), transaction(transaction_p) {
162256 }
162257
162258 TransactionState state;
162259 Transaction &transaction;
162260};
162261
162263class MetaTransaction {
162264public:
162265 DUCKDB_API MetaTransaction(ClientContext &context, timestamp_t start_timestamp,
162266 transaction_t global_transaction_id);
162267
162268 ClientContext &context;
162270 timestamp_t start_timestamp;
162274 ValidChecker transaction_validity;
162276 atomic<transaction_t> active_query;
162277
162278public:
162279 DUCKDB_API static MetaTransaction &Get(ClientContext &context);
162280 timestamp_t GetCurrentTransactionStartTimestamp() const {
162281 return start_timestamp;
162282 }
162283
162284 Transaction &GetTransaction(AttachedDatabase &db);
162285 optional_ptr<Transaction> TryGetTransaction(AttachedDatabase &db);
162286 void RemoveTransaction(AttachedDatabase &db);
162287
162288 ErrorData Commit();
162289 void Rollback();
162290
162291 void Finalize();
162292
162293 idx_t GetActiveQuery();
162294 void SetActiveQuery(transaction_t query_number);
162295
162296 void SetReadOnly();
162297 bool IsReadOnly() const;
162298 void ModifyDatabase(AttachedDatabase &db, DatabaseModificationType modification);
162299 optional_ptr<AttachedDatabase> ModifiedDatabase() {
162300 return modified_database;
162301 }
162302 const vector<reference<AttachedDatabase>> &OpenedTransactions() const {
162303 return all_transactions;
162304 }
162305 optional_ptr<AttachedDatabase> GetReferencedDatabase(const string &name);
162306 shared_ptr<AttachedDatabase> GetReferencedDatabaseOwning(const string &name);
162307 AttachedDatabase &UseDatabase(shared_ptr<AttachedDatabase> &database);
162308 void DetachDatabase(AttachedDatabase &database);
162309
162310private:
162312 mutex lock;
162314 reference_map_t<AttachedDatabase, TransactionReference> transactions;
162316 vector<reference<AttachedDatabase>> all_transactions;
162318 optional_ptr<AttachedDatabase> modified_database;
162320 bool is_read_only;
162322 mutex referenced_database_lock;
162324 reference_map_t<AttachedDatabase, shared_ptr<AttachedDatabase>> referenced_databases;
162326 case_insensitive_map_t<reference<AttachedDatabase>> used_databases;
162327};
162328
162329}
162330
162331
162332
162333
162334
162335
162336
162337
162338
162339
162340
162341
162342
162343
162344
162345
162346
162347
162348namespace duckdb {
162349
162350class AttachedDatabase;
162351class ClientContext;
162352class Catalog;
162353struct ClientLockWrapper;
162354class DatabaseInstance;
162355class Transaction;
162356
162359class TransactionManager {
162360public:
162361 explicit TransactionManager(AttachedDatabase &db);
162362 virtual ~TransactionManager();
162363
162365 virtual Transaction &StartTransaction(ClientContext &context) = 0;
162367 virtual ErrorData CommitTransaction(ClientContext &context, Transaction &transaction) = 0;
162369 virtual void RollbackTransaction(Transaction &transaction) = 0;
162370
162371 virtual void Checkpoint(ClientContext &context, bool force = false) = 0;
162372
162373 static TransactionManager &Get(AttachedDatabase &db);
162374
162375 virtual bool IsDuckTransactionManager() {
162376 return false;
162377 }
162378
162379 AttachedDatabase &GetDB() {
162381 }
162382
162383protected:
162385 AttachedDatabase &
db;
162386
162387public:
162388 template <class TARGET>
162389 TARGET &Cast() {
162390 DynamicCastCheck<TARGET>(this);
162391 return reinterpret_cast<TARGET &>(*this);
162392 }
162393 template <class TARGET>
162394 const TARGET &Cast() const {
162395 D_ASSERT(dynamic_cast<const TARGET *>(this));
162396 return reinterpret_cast<const TARGET &>(*this);
162397 }
162398};
162399
162400}
162401
162402
162403
162404
162405
162406
162407
162408
162409
162410
162411
162412
162413
162414
162415
162416
162417
162418
162419
162420
162421
162422
162423
162424
162425
162426
162427
162428
162429
162430
162431
162432namespace duckdb {
162433
162434struct AttachInfo : public ParseInfo {
162435public:
162436 static constexpr const ParseInfoType
TYPE = ParseInfoType::ATTACH_INFO;
162437
162438public:
162439 AttachInfo() : ParseInfo(
TYPE) {
162440 }
162441
162443 string name;
162445 string path;
162447 case_insensitive_map_t<unique_ptr<ParsedExpression>> parsed_options;
162449 unordered_map<string, Value> options;
162451 OnCreateConflict on_conflict = OnCreateConflict::ERROR_ON_CONFLICT;
162452
162453public:
162455 unique_ptr<AttachInfo> Copy() const;
162456 string ToString() const;
162457
162458 void Serialize(Serializer &serializer) const override;
162459 static unique_ptr<ParseInfo> Deserialize(Deserializer &deserializer);
162460};
162461
162462}
162463
162464
162465
162466
162467
162468
162469
162470
162471
162472
162473
162474
162475
162476
162477
162478
162479
162480
162481namespace duckdb {
162482struct AttachInfo;
162483struct AttachOptions;
162484class DatabaseManager;
162485
162486enum class InsertDatabasePathResult { SUCCESS, ALREADY_EXISTS };
162487
162488struct DatabasePathInfo {
162489 DatabasePathInfo(DatabaseManager &manager, string name_p, AccessMode access_mode);
162490
162491 string name;
162492 AccessMode access_mode;
162493 reference_set_t<DatabaseManager> attached_databases;
162494 idx_t reference_count = 1;
162495};
162496
162498class DatabaseFilePathManager {
162499public:
162500 idx_t ApproxDatabaseCount()
const;
162501 InsertDatabasePathResult InsertDatabasePath(DatabaseManager &manager, const string &path, const string &name,
162502 OnCreateConflict on_conflict, AttachOptions &options);
162504 void EraseDatabasePath(const string &path);
162506 void DetachDatabase(DatabaseManager &manager, const string &path);
162507
162508private:
162510 mutable mutex db_paths_lock;
162514#if defined(_WIN32) || defined(__APPLE__)
162515 case_insensitive_map_t<DatabasePathInfo> db_paths;
162516#else
162517 unordered_map<string, DatabasePathInfo> db_paths;
162518#endif
162519};
162520
162521}
162522
162523
162524namespace duckdb {
162525class AttachedDatabase;
162526class Catalog;
162527class CatalogEntryRetriever;
162528class CatalogSet;
162529class ClientContext;
162530class DatabaseInstance;
162531class TaskScheduler;
162532struct AttachOptions;
162533struct AlterInfo;
162534
162536class DatabaseManager {
162537 friend class Catalog;
162538
162539public:
162540 explicit DatabaseManager(DatabaseInstance &db);
162541 ~DatabaseManager();
162542
162543public:
162544 static DatabaseManager &Get(DatabaseInstance &db);
162545 static DatabaseManager &Get(ClientContext &db);
162546 static DatabaseManager &Get(AttachedDatabase &db);
162547
162548 DatabaseInstance &GetInstance() {
162550 }
162552 void InitializeSystemCatalog();
162554 void FinalizeStartup();
162556 optional_ptr<AttachedDatabase> GetDatabase(ClientContext &context, const string &name);
162557 shared_ptr<AttachedDatabase> GetDatabase(const string &name);
162559 shared_ptr<AttachedDatabase> AttachDatabase(ClientContext &context, AttachInfo &info, AttachOptions &options);
162560
162562 void DetachDatabase(ClientContext &context, const string &name, OnEntryNotFound if_not_found);
162564 void Alter(ClientContext &context, AlterInfo &info);
162566 shared_ptr<AttachedDatabase> DetachInternal(const string &name);
162568 Catalog &GetSystemCatalog();
162569
162570 static const string &GetDefaultDatabase(ClientContext &context);
162571 void SetDefaultDatabase(ClientContext &context, const string &new_value);
162572
162574 InsertDatabasePathResult InsertDatabasePath(const AttachInfo &info, AttachOptions &options);
162575
162579 void GetDatabaseType(ClientContext &context, AttachInfo &info, const DBConfig &config, AttachOptions &options);
162582 vector<shared_ptr<AttachedDatabase>> GetDatabases(ClientContext &context,
162583 const optional_idx max_db_count = optional_idx());
162585 vector<shared_ptr<AttachedDatabase>> GetDatabases();
162587 idx_t ApproxDatabaseCount();
162590 void ResetDatabases();
162591
162593 return current_query_number++;
162594 }
162596 return current_query_number;
162597 }
162599 return current_transaction_id++;
162600 }
162602 return current_transaction_id;
162603 }
162605 return next_oid++;
162606 }
162607 bool HasDefaultDatabase() {
162608 return !default_database.empty();
162609 }
162611 vector<string> GetAttachedDatabasePaths();
162612
162613 shared_ptr<AttachedDatabase> GetDatabaseInternal(const lock_guard<mutex> &, const string &name);
162614
162615private:
162616 optional_ptr<AttachedDatabase> FinalizeAttach(ClientContext &context, AttachInfo &info,
162617 shared_ptr<AttachedDatabase> database);
162618
162619private:
162620 DatabaseInstance &
db;
162622 shared_ptr<AttachedDatabase> system;
162624 mutex databases_lock;
162626 case_insensitive_map_t<shared_ptr<AttachedDatabase>> databases;
162628 atomic<idx_t> next_oid;
162630 atomic<transaction_t> current_query_number;
162632 atomic<transaction_t> current_transaction_id;
162634 string default_database;
162636 shared_ptr<DatabaseFilePathManager> path_manager;
162637
162638private:
162640 void RenameDatabase(ClientContext &context, const string &old_name, const string &new_name,
162641 OnEntryNotFound if_not_found);
162642};
162643
162644}
162645
162646
162647#include <mutex>
162648
162649namespace duckdb {
162650class ClientContext;
162651class ErrorData;
162652class MetaTransaction;
162653class PreparedStatementData;
162654class SQLStatement;
162655struct PendingQueryParameters;
162656class RegisteredStateManager;
162657
162658enum class RebindQueryInfo { DO_NOT_REBIND, ATTEMPT_TO_REBIND };
162659
162660struct PreparedStatementCallbackInfo {
162661 PreparedStatementCallbackInfo(PreparedStatementData &prepared_statement, const PendingQueryParameters ¶meters)
162662 : prepared_statement(prepared_statement), parameters(parameters) {
162663 }
162664
162665 PreparedStatementData &prepared_statement;
162666 const PendingQueryParameters ¶meters;
162667};
162668
162669struct BindPreparedStatementCallbackInfo {
162670 PreparedStatementData &prepared_statement;
162671 optional_ptr<case_insensitive_map_t<BoundParameterData>> parameters;
162672};
162673
162676class ClientContextState {
162677public:
162678 virtual ~ClientContextState() = default;
162679 virtual void QueryBegin(ClientContext &context) {
162680 }
162681 virtual void QueryEnd() {
162682 }
162683 virtual void QueryEnd(ClientContext &context) {
162684 QueryEnd();
162685 }
162686 virtual void QueryEnd(ClientContext &context, optional_ptr<ErrorData> error) {
162687 QueryEnd(context);
162688 }
162689 virtual void TransactionBegin(MetaTransaction &transaction, ClientContext &context) {
162690 }
162691 virtual void TransactionCommit(MetaTransaction &transaction, ClientContext &context) {
162692 }
162693 virtual void TransactionRollback(MetaTransaction &transaction, ClientContext &context) {
162694 }
162695 virtual void TransactionRollback(MetaTransaction &transaction, ClientContext &context,
162696 optional_ptr<ErrorData> error) {
162697 TransactionRollback(transaction, context);
162698 }
162699 virtual bool CanRequestRebind() {
162700 return false;
162701 }
162702 virtual RebindQueryInfo OnPlanningError(ClientContext &context, SQLStatement &statement, ErrorData &error) {
162703 return RebindQueryInfo::DO_NOT_REBIND;
162704 }
162705 virtual RebindQueryInfo OnFinalizePrepare(ClientContext &context, PreparedStatementData &prepared_statement,
162706 PreparedStatementMode mode) {
162707 return RebindQueryInfo::DO_NOT_REBIND;
162708 }
162709 virtual RebindQueryInfo OnExecutePrepared(ClientContext &context, PreparedStatementCallbackInfo &info,
162710 RebindQueryInfo current_rebind) {
162711 return RebindQueryInfo::DO_NOT_REBIND;
162712 }
162713 virtual RebindQueryInfo OnRebindPreparedStatement(ClientContext &context, BindPreparedStatementCallbackInfo &info,
162714 RebindQueryInfo current_rebind) {
162715 return RebindQueryInfo::DO_NOT_REBIND;
162716 }
162717 virtual void WriteProfilingInformation(std::ostream &ss) {
162718 }
162719 virtual void OnTaskStart(ClientContext &context) {
162720 }
162721 virtual void OnTaskStop(ClientContext &context) {
162722 }
162723
162724public:
162725 template <class TARGET>
162726 TARGET &Cast() {
162727 DynamicCastCheck<TARGET>(this);
162728 return reinterpret_cast<TARGET &>(*this);
162729 }
162730 template <class TARGET>
162731 const TARGET &Cast() const {
162732 DynamicCastCheck<TARGET>(this);
162733 return reinterpret_cast<const TARGET &>(*this);
162734 }
162735};
162736
162737class RegisteredStateManager {
162738public:
162739 template <class T, typename... ARGS>
162740 shared_ptr<T> GetOrCreate(const string &key, ARGS &&... args) {
162741 lock_guard<mutex> l(lock);
162742 auto lookup = registered_state.find(key);
162743 if (lookup != registered_state.end()) {
162744 return shared_ptr_cast<ClientContextState, T>(lookup->second);
162745 }
162746 auto cache = make_shared_ptr<T>(std::forward<ARGS>(args)...);
162747 registered_state[key] = cache;
162748 return cache;
162749 }
162750
162751 template <class T>
162752 shared_ptr<T> Get(const string &key) {
162753 lock_guard<mutex> l(lock);
162754 auto lookup = registered_state.find(key);
162755 if (lookup == registered_state.end()) {
162756 return nullptr;
162757 }
162758 return shared_ptr_cast<ClientContextState, T>(lookup->second);
162759 }
162760
162761 void Insert(const string &key, shared_ptr<ClientContextState> state_p) {
162762 lock_guard<mutex> l(lock);
162763 registered_state.insert(make_pair(key, std::move(state_p)));
162764 }
162765
162766 void Remove(const string &key) {
162767 lock_guard<mutex> l(lock);
162768 registered_state.erase(key);
162769 }
162770
162771 vector<shared_ptr<ClientContextState>>
States() {
162772 lock_guard<mutex> l(lock);
162773 vector<shared_ptr<ClientContextState>> states;
162774 for (auto &entry : registered_state) {
162775 states.push_back(entry.second);
162776 }
162777 return states;
162778 }
162779
162780private:
162781 mutex lock;
162782 unordered_map<string, shared_ptr<ClientContextState>> registered_state;
162783};
162784
162785}
162786
162787
162788
162789
162790
162791
162792
162793
162794
162795
162796
162797
162798
162799
162800
162801
162802
162803
162804
162805
162806
162807
162808
162809
162810
162811
162812
162813
162814
162815
162816
162817
162818
162819#include <queue>
162820
162821namespace duckdb {
162822
162823template <class DATA_TYPE, class CONTAINER = std::deque<DATA_TYPE>, bool SAFE = true>
162824class queue : public std::queue<DATA_TYPE, CONTAINER> {
162825public:
162826 using original = std::queue<DATA_TYPE, CONTAINER>;
162827 using original::original;
162828 using container_type = typename original::container_type;
162829 using value_type =
typename original::value_type;
162830 using size_type = typename container_type::size_type;
162831 using reference = typename container_type::reference;
162832 using const_reference = typename container_type::const_reference;
162833
162834public:
162835
162836
162837 queue() = default;
162838 queue(original &&other) : original(std::move(other)) {
162839 }
162840 template <bool INTERNAL_SAFE>
162841 queue(queue<DATA_TYPE, CONTAINER, INTERNAL_SAFE> &&other) : original(std::move(other)) {
162842 }
162843
162844 inline void clear() noexcept {
162845 original::c.clear();
162846 }
162847
162848 reference front() {
162849 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
162850 throw InternalException("'front' called on an empty queue!");
162851 }
162852 return original::front();
162853 }
162854
162855 const_reference front() const {
162856 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
162857 throw InternalException("'front' called on an empty queue!");
162858 }
162859 return original::front();
162860 }
162861
162862 reference back() {
162863 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
162864 throw InternalException("'back' called on an empty queue!");
162865 }
162866 return original::back();
162867 }
162868
162869 const_reference back() const {
162870 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
162871 throw InternalException("'back' called on an empty queue!");
162872 }
162873 return original::back();
162874 }
162875
162876 void pop() {
162877 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
162878 throw InternalException("'pop' called on an empty queue!");
162879 }
162880 original::pop();
162881 }
162882};
162883
162884template <typename T, typename Container = std::deque<T>>
162885using unsafe_queue = queue<T, Container, false>;
162886
162887}
162888
162889
162890
162891
162892
162893
162894
162895
162896
162897
162898
162899
162900
162901namespace duckdb {
162902
162903enum class StreamExecutionResult :
uint8_t {
162904 CHUNK_READY,
162905 CHUNK_NOT_READY,
162906 EXECUTION_ERROR,
162907 EXECUTION_CANCELLED,
162908 BLOCKED,
162909 NO_TASKS_AVAILABLE,
162910 EXECUTION_FINISHED
162911};
162912
162913}
162914
162915
162916
162917
162918
162919
162920
162921
162922
162923
162924
162925
162926
162927
162928
162929
162930
162931
162932
162933
162934
162935
162936
162937
162938
162939
162940
162941
162942
162943
162944
162945namespace duckdb {
162946
162947class StreamQueryResult;
162948class ClientContextLock;
162949
162950class BufferedData {
162951protected:
162952 enum class Type { SIMPLE, BATCHED };
162953
162954public:
162955 BufferedData(Type type, ClientContext &context);
162956 virtual ~BufferedData();
162957
162958public:
162959 StreamExecutionResult ReplenishBuffer(StreamQueryResult &result, ClientContextLock &context_lock);
162960 virtual StreamExecutionResult ExecuteTaskInternal(StreamQueryResult &result, ClientContextLock &context_lock) = 0;
162961 virtual unique_ptr<DataChunk> Scan() = 0;
162962 virtual void UnblockSinks() = 0;
162963 shared_ptr<ClientContext> GetContext() {
162964 return context.lock();
162965 }
162966 bool Closed() const {
162967 if (context.expired()) {
162968 return true;
162969 }
162970 auto c = context.lock();
162971 return c == nullptr;
162972 }
162973 void Close() {
162974 context.reset();
162975 }
162976
162977public:
162978 template <class TARGET>
162979 TARGET &Cast() {
162980 if (TARGET::TYPE != type) {
162981 throw InternalException("Failed to cast buffered data to type - buffered data type mismatch");
162982 }
162983 return reinterpret_cast<TARGET &>(*this);
162984 }
162985
162986 template <class TARGET>
162987 const TARGET &Cast() const {
162988 if (TARGET::TYPE != type) {
162989 throw InternalException("Failed to cast buffered data to type - buffered data type mismatch");
162990 }
162991 return reinterpret_cast<const TARGET &>(*this);
162992 }
162993
162994protected:
162995 Type type;
162997 weak_ptr<ClientContext> context;
162999 idx_t total_buffer_size;
163001 mutex glock;
163002};
163003
163004}
163005
163006
163007
163008
163009
163010
163011namespace duckdb {
163012
163013class StreamQueryResult;
163014class ClientContextLock;
163015
163016class SimpleBufferedData : public BufferedData {
163017public:
163018 static constexpr const BufferedData::Type
TYPE = BufferedData::Type::SIMPLE;
163019
163020public:
163021 explicit SimpleBufferedData(ClientContext &context);
163022 ~SimpleBufferedData() override;
163023
163024public:
163025 void Append(const DataChunk &chunk);
163026 void BlockSink(const InterruptState &blocked_sink);
163027 bool BufferIsFull();
163028 void UnblockSinks() override;
163029 StreamExecutionResult ExecuteTaskInternal(StreamQueryResult &result, ClientContextLock &context_lock) override;
163030 unique_ptr<DataChunk> Scan() override;
163031 inline idx_t BufferSize()
const {
163032 return buffer_size;
163033 }
163034
163035private:
163037 queue<InterruptState> blocked_sinks;
163039 queue<unique_ptr<DataChunk>> buffered_chunks;
163041 atomic<idx_t> buffered_count;
163043 idx_t buffer_size;
163044};
163045
163046}
163047
163048
163049namespace duckdb {
163050
163051class ClientContext;
163052class ClientContextLock;
163053class Executor;
163054class MaterializedQueryResult;
163055class PreparedStatementData;
163056
163057class StreamQueryResult : public QueryResult {
163058 friend class ClientContext;
163059
163060public:
163061 static constexpr const QueryResultType
TYPE = QueryResultType::STREAM_RESULT;
163062
163063public:
163066 DUCKDB_API StreamQueryResult(StatementType statement_type, StatementProperties properties,
163067 vector<LogicalType> types, vector<string> names, ClientProperties client_properties,
163068 shared_ptr<BufferedData> buffered_data);
163069 DUCKDB_API explicit StreamQueryResult(ErrorData error);
163070 DUCKDB_API ~StreamQueryResult() override;
163071
163072public:
163073 static bool IsChunkReady(StreamExecutionResult result);
163075 DUCKDB_API void WaitForTask();
163077 DUCKDB_API StreamExecutionResult ExecuteTask();
163079 DUCKDB_API string ToString() override;
163081 DUCKDB_API unique_ptr<MaterializedQueryResult> Materialize();
163082
163083 DUCKDB_API bool IsOpen();
163084
163086 DUCKDB_API void Close();
163087
163089 shared_ptr<ClientContext> context;
163090
163091protected:
163092 DUCKDB_API unique_ptr<DataChunk> FetchInternal() override;
163093
163094private:
163095 StreamExecutionResult ExecuteTaskInternal(ClientContextLock &lock);
163096 unique_ptr<DataChunk> FetchNextInternal(ClientContextLock &lock);
163097 unique_ptr<ClientContextLock> LockContext();
163098 void CheckExecutableInternal(ClientContextLock &lock);
163099 bool IsOpenInternal(ClientContextLock &lock);
163100
163101private:
163102 shared_ptr<BufferedData> buffered_data;
163103};
163104
163105}
163106
163107
163108
163109
163110
163111
163112
163113
163114
163115
163116
163117
163118
163119namespace duckdb {
163120
163121class TableDescription {
163122public:
163123 TableDescription(const string &database_name, const string &schema_name, const string &table_name)
163124 : database(database_name), schema(schema_name), table(table_name) {};
163125
163126 TableDescription() = delete;
163127
163128public:
163130 string database;
163132 string schema;
163134 string table;
163136 bool readonly;
163138 vector<ColumnDefinition> columns;
163139
163140public:
163141 idx_t PhysicalColumnCount()
const {
163143 for (auto &column : columns) {
163144 if (column.Generated()) {
163145 continue;
163146 }
163147 count++;
163148 }
163149 D_ASSERT(count != 0);
163150 return count;
163151 }
163152};
163153
163154}
163155
163156
163157
163158
163159
163160
163161
163162
163163
163164
163165
163166
163167
163168
163169
163170
163171
163172
163173
163174
163175
163176
163177
163178
163179
163180
163181
163182
163183
163184namespace duckdb {
163185
163186enum class TransactionType :
uint8_t { INVALID, BEGIN_TRANSACTION, COMMIT, ROLLBACK };
163187
163188enum class TransactionModifierType :
uint8_t {
163189 TRANSACTION_DEFAULT_MODIFIER,
163190 TRANSACTION_READ_ONLY,
163191 TRANSACTION_READ_WRITE
163192};
163193
163194enum class TransactionInvalidationPolicy :
uint8_t { STANDARD_POLICY, ALL_ERRORS_INVALIDATE_TRANSACTION };
163195
163196struct TransactionInfo : public ParseInfo {
163197public:
163198 static constexpr const ParseInfoType
TYPE = ParseInfoType::TRANSACTION_INFO;
163199
163200public:
163201 explicit TransactionInfo(
163202 TransactionType type,
163203 TransactionInvalidationPolicy invalidation_policy = TransactionInvalidationPolicy::STANDARD_POLICY,
163204 bool auto_rollback = false);
163205
163207 TransactionType type;
163209 TransactionModifierType modifier;
163211 TransactionInvalidationPolicy invalidation_policy;
163213 bool auto_rollback;
163214
163215public:
163216 void Serialize(Serializer &serializer) const override;
163217 static unique_ptr<ParseInfo> Deserialize(Deserializer &deserializer);
163218
163219 string ToString() const;
163220 unique_ptr<TransactionInfo> Copy() const;
163221
163222private:
163223 TransactionInfo();
163224};
163225
163226}
163227
163228
163229namespace duckdb {
163230
163231class ClientContext;
163232class MetaTransaction;
163233class Transaction;
163234class TransactionManager;
163235
163238class TransactionContext {
163239public:
163240 explicit TransactionContext(ClientContext &context);
163241 ~TransactionContext();
163242
163243 MetaTransaction &ActiveTransaction() {
163244 if (!current_transaction) {
163245 throw InternalException("TransactionContext::ActiveTransaction called without active transaction");
163246 }
163247 return *current_transaction;
163248 }
163249
163250 bool HasActiveTransaction() const {
163251 return current_transaction.get();
163252 }
163253
163254 void BeginTransaction();
163255 void Commit();
163256 void Rollback(optional_ptr<ErrorData>);
163257 void ClearTransaction();
163258
163259 void SetAutoCommit(bool value);
163260 bool IsAutoCommit() const {
163261 return auto_commit;
163262 }
163263
163264 void SetReadOnly();
163265
163266 idx_t GetActiveQuery();
163267 void ResetActiveQuery();
163268 void SetActiveQuery(transaction_t query_number);
163269
163270 void SetInvalidationPolicy(TransactionInvalidationPolicy new_invalidation_policy) {
163271 invalidation_policy = new_invalidation_policy;
163272 };
163273 TransactionInvalidationPolicy GetInvalidationPolicy() {
163274 return invalidation_policy;
163275 };
163276 void SetAutoRollback(bool new_auto_rollback) {
163277 auto_rollback = new_auto_rollback;
163278 };
163279 bool GetAutoRollback() {
163280 return auto_rollback;
163281 };
163282
163283private:
163284 ClientContext &context;
163285 bool auto_commit;
163286 TransactionInvalidationPolicy invalidation_policy;
163287 bool auto_rollback;
163288
163289 unique_ptr<MetaTransaction> current_transaction;
163290
163291 TransactionContext(const TransactionContext &) = delete;
163292};
163293
163294}
163295
163296
163297
163298namespace duckdb {
163299
163300class Appender;
163301class Catalog;
163302class CatalogSearchPath;
163303class ColumnDataCollection;
163304class DatabaseInstance;
163305class FileOpener;
163306class LogicalOperator;
163307class PreparedStatementData;
163308class Relation;
163309class BufferedFileWriter;
163310class QueryProfiler;
163311class ClientContextLock;
163312struct CreateScalarFunctionInfo;
163313class ScalarFunctionCatalogEntry;
163314struct ActiveQueryContext;
163315struct ParserOptions;
163316class SimpleBufferedData;
163317class BufferedData;
163318struct ClientData;
163319class ClientContextState;
163320class RegisteredStateManager;
163321
163322struct PendingQueryParameters {
163324 optional_ptr<case_insensitive_map_t<BoundParameterData>> parameters;
163326 QueryParameters query_parameters;
163327};
163328
163331class ClientContext : public enable_shared_from_this<ClientContext> {
163332 friend class PendingQueryResult;
163333 friend class BufferedData;
163334 friend class SimpleBufferedData;
163335 friend class BatchedBufferedData;
163336 friend class StreamQueryResult;
163337 friend class ConnectionManager;
163338
163339public:
163340 DUCKDB_API explicit ClientContext(shared_ptr<DatabaseInstance> db);
163341 DUCKDB_API ~ClientContext();
163342
163344 shared_ptr<DatabaseInstance>
db;
163346 atomic<bool> interrupted;
163348 unique_ptr<RegisteredStateManager> registered_state;
163350 shared_ptr<Logger> logger;
163352 ClientConfig config;
163354 unique_ptr<ClientData> client_data;
163356 TransactionContext transaction;
163357
163358public:
163359 MetaTransaction &ActiveTransaction() {
163360 return transaction.ActiveTransaction();
163361 }
163362
163364 DUCKDB_API void Interrupt();
163365 DUCKDB_API bool IsInterrupted() const;
163366 DUCKDB_API void ClearInterrupt();
163367 DUCKDB_API void CancelTransaction();
163368
163370 DUCKDB_API void EnableProfiling();
163372 DUCKDB_API void DisableProfiling();
163373
163377 DUCKDB_API unique_ptr<QueryResult> Query(const string &query, QueryParameters query_parameters);
163378 DUCKDB_API unique_ptr<QueryResult> Query(unique_ptr<SQLStatement> statement, QueryParameters query_parameters);
163379
163382 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(const string &query, QueryParameters query_parameters);
163384 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(unique_ptr<SQLStatement> statement,
163385 QueryParameters query_parameters);
163386
163388 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(unique_ptr<SQLStatement> statement,
163389 case_insensitive_map_t<BoundParameterData> &values,
163390 QueryParameters query_parameters);
163391 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(const string &query,
163392 case_insensitive_map_t<BoundParameterData> &values,
163393 QueryParameters query_parameters);
163394 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(const string &query, PendingQueryParameters parameters);
163395
163397 DUCKDB_API void Destroy();
163398
163400 DUCKDB_API unique_ptr<TableDescription> TableInfo(const string &database_name, const string &schema_name,
163401 const string &table_name);
163403 DUCKDB_API unique_ptr<TableDescription> TableInfo(const string &schema_name, const string &table_name);
163405 DUCKDB_API void Append(unique_ptr<SQLStatement> stmt);
163407 DUCKDB_API void Append(TableDescription &description, ColumnDataCollection &collection);
163408
163411 DUCKDB_API void TryBindRelation(Relation &relation, vector<ColumnDefinition> &result_columns);
163412
163414 DUCKDB_API void InternalTryBindRelation(Relation &relation, vector<ColumnDefinition> &result_columns);
163415
163417 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(const shared_ptr<Relation> &relation,
163418 QueryParameters query_parameters);
163419 DUCKDB_API unique_ptr<QueryResult> Execute(const shared_ptr<Relation> &relation);
163420
163422 DUCKDB_API unique_ptr<PreparedStatement> Prepare(const string &query);
163424 DUCKDB_API unique_ptr<PreparedStatement> Prepare(unique_ptr<SQLStatement> statement);
163425
163429 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(const string &query,
163430 shared_ptr<PreparedStatementData> &prepared,
163431 const PendingQueryParameters ¶meters);
163432
163436 DUCKDB_API unique_ptr<QueryResult>
163437 Execute(const string &query, shared_ptr<PreparedStatementData> &prepared,
163438 case_insensitive_map_t<BoundParameterData> &values,
163439 QueryParameters query_parameters = QueryResultOutputType::ALLOW_STREAMING);
163440 DUCKDB_API unique_ptr<QueryResult> Execute(const string &query, shared_ptr<PreparedStatementData> &prepared,
163441 const PendingQueryParameters ¶meters);
163442
163444 DUCKDB_API QueryProgress GetQueryProgress();
163445
163447 DUCKDB_API void RegisterFunction(CreateFunctionInfo &info);
163448
163450 DUCKDB_API vector<unique_ptr<SQLStatement>> ParseStatements(const string &query);
163451
163453 DUCKDB_API unique_ptr<LogicalOperator> ExtractPlan(const string &query);
163454 DUCKDB_API void PreprocessStatements(vector<unique_ptr<SQLStatement>> &statements);
163455
163458 DUCKDB_API void RunFunctionInTransaction(const std::function<void(void)> &fun,
163459 bool requires_valid_transaction = true);
163461 DUCKDB_API void RunFunctionInTransactionInternal(ClientContextLock &lock, const std::function<void(void)> &fun,
163462 bool requires_valid_transaction = true);
163463
163465 DUCKDB_API SettingLookupResult TryGetCurrentSetting(const string &key, Value &result) const;
163467 DUCKDB_API SettingLookupResult TryGetCurrentUserSetting(idx_t setting_index, Value &result) const;
163468
163470 DUCKDB_API ParserOptions GetParserOptions() const;
163471
163473 DUCKDB_API bool IsActiveResult(ClientContextLock &lock, BaseQueryResult &result);
163474
163476 Executor &GetExecutor();
163477
163479 Logger &GetLogger() const;
163480
163482 const string &GetCurrentQuery();
163483
163485
163489 DUCKDB_API unordered_set<string> GetTableNames(const string &query, const bool qualified = false);
163490
163491 DUCKDB_API ClientProperties GetClientProperties();
163492
163494 DUCKDB_API bool ExecutionIsFinished();
163495
163497 DUCKDB_API void ProcessError(ErrorData &error, const string &query) const;
163498
163499 DUCKDB_API LogicalType ParseLogicalType(const string &type);
163500
163501private:
163503 vector<unique_ptr<SQLStatement>> ParseStatements(ClientContextLock &lock, const string &query);
163505 unique_ptr<PendingQueryResult> PendingQueryInternal(ClientContextLock &lock, unique_ptr<SQLStatement> statement,
163506 const PendingQueryParameters ¶meters, bool verify = true);
163507 unique_ptr<QueryResult> ExecutePendingQueryInternal(ClientContextLock &lock, PendingQueryResult &query);
163508
163510 vector<unique_ptr<SQLStatement>> ParseStatementsInternal(ClientContextLock &lock, const string &query);
163513 ErrorData VerifyQuery(ClientContextLock &lock, const string &query, unique_ptr<SQLStatement> statement,
163514 PendingQueryParameters parameters);
163515
163516 void InitialCleanup(ClientContextLock &lock);
163518 void CleanupInternal(ClientContextLock &lock, BaseQueryResult *result = nullptr,
163519 bool invalidate_transaction = false);
163520 unique_ptr<PendingQueryResult> PendingStatementOrPreparedStatement(ClientContextLock &lock, const string &query,
163521 unique_ptr<SQLStatement> statement,
163522 shared_ptr<PreparedStatementData> &prepared,
163523 const PendingQueryParameters ¶meters);
163524 unique_ptr<PendingQueryResult> PendingPreparedStatement(ClientContextLock &lock, const string &query,
163525 shared_ptr<PreparedStatementData> statement_p,
163526 const PendingQueryParameters ¶meters);
163527 unique_ptr<PendingQueryResult> PendingPreparedStatementInternal(ClientContextLock &lock,
163528 shared_ptr<PreparedStatementData> statement_data_p,
163529 const PendingQueryParameters ¶meters);
163530 void CheckIfPreparedStatementIsExecutable(PreparedStatementData &statement);
163531
163533 shared_ptr<PreparedStatementData>
163534 CreatePreparedStatement(ClientContextLock &lock, const string &query, unique_ptr<SQLStatement> statement,
163535 PendingQueryParameters parameters,
163536 PreparedStatementMode mode = PreparedStatementMode::PREPARE_ONLY);
163537 unique_ptr<PendingQueryResult> PendingStatementInternal(ClientContextLock &lock, const string &query,
163538 unique_ptr<SQLStatement> statement,
163539 const PendingQueryParameters ¶meters);
163540 unique_ptr<QueryResult> RunStatementInternal(ClientContextLock &lock, const string &query,
163541 unique_ptr<SQLStatement> statement,
163542 const PendingQueryParameters ¶meters, bool verify = true);
163543 unique_ptr<PreparedStatement> PrepareInternal(ClientContextLock &lock, unique_ptr<SQLStatement> statement);
163544 void LogQueryInternal(ClientContextLock &lock, const string &query);
163545
163546 unique_ptr<QueryResult> FetchResultInternal(ClientContextLock &lock, PendingQueryResult &pending);
163547
163548 unique_ptr<ClientContextLock> LockContext();
163549
163550 void BeginQueryInternal(ClientContextLock &lock, const string &query);
163551 ErrorData EndQueryInternal(ClientContextLock &lock, bool success, bool invalidate_transaction,
163552 optional_ptr<ErrorData> previous_error);
163553
163555 void WaitForTask(ClientContextLock &lock, BaseQueryResult &result);
163556 PendingExecutionResult ExecuteTaskInternal(ClientContextLock &lock, BaseQueryResult &result, bool dry_run = false);
163557
163558 unique_ptr<PendingQueryResult> PendingStatementOrPreparedStatementInternal(
163559 ClientContextLock &lock, const string &query, unique_ptr<SQLStatement> statement,
163560 shared_ptr<PreparedStatementData> &prepared, const PendingQueryParameters ¶meters);
163561
163562 unique_ptr<PendingQueryResult> PendingQueryPreparedInternal(ClientContextLock &lock, const string &query,
163563 shared_ptr<PreparedStatementData> &prepared,
163564 const PendingQueryParameters ¶meters);
163565
163566 unique_ptr<PendingQueryResult> PendingQueryInternal(ClientContextLock &, const shared_ptr<Relation> &relation,
163567 QueryParameters query_parameters);
163568
163569 void RebindPreparedStatement(ClientContextLock &lock, const string &query,
163570 shared_ptr<PreparedStatementData> &prepared, const PendingQueryParameters ¶meters);
163571
163572 template <class T>
163573 unique_ptr<T> ErrorResult(ErrorData error, const string &query = string());
163574
163575 shared_ptr<PreparedStatementData> CreatePreparedStatementInternal(ClientContextLock &lock, const string &query,
163576 unique_ptr<SQLStatement> statement,
163577 PendingQueryParameters parameters);
163578
163579 bool ErrorInvalidatesTransaction(ExceptionType type);
163580
163581private:
163583 mutex context_lock;
163585 unique_ptr<ActiveQueryContext> active_query;
163587 QueryProgress query_progress;
163590};
163591
163592class ClientContextLock {
163593public:
163594 explicit ClientContextLock(mutex &context_lock) : client_guard(context_lock) {
163595 }
163596
163597 ~ClientContextLock() {
163598 }
163599
163600private:
163601 lock_guard<mutex> client_guard;
163602};
163603
163606class QueryContext {
163607public:
163608 QueryContext() : context(nullptr) {
163609 }
163610 QueryContext(optional_ptr<ClientContext> context) : context(context) {
163611 }
163612 QueryContext(ClientContext &context) : context(&context) {
163613 }
163614
163615public:
163616 bool Valid() const {
163617 return context != nullptr;
163618 }
163619 optional_ptr<ClientContext> GetClientContext() const {
163620 return context;
163621 }
163622
163623private:
163624 optional_ptr<ClientContext> context;
163625};
163626
163627}
163628
163629
163630
163631
163632
163633
163634
163635
163636
163637
163638
163639
163640
163641
163642namespace duckdb {
163643
163644class ClientContext;
163645
163646class Relation;
163647
163648class ClientContextWrapper {
163649public:
163650 virtual ~ClientContextWrapper() = default;
163651 explicit ClientContextWrapper(const shared_ptr<ClientContext> &context);
163652 shared_ptr<ClientContext> GetContext();
163653 shared_ptr<ClientContext> TryGetContext();
163654 virtual void TryBindRelation(Relation &relation, vector<ColumnDefinition> &columns);
163655
163656private:
163657 weak_ptr<ClientContext> client_context;
163658};
163659
163660}
163661
163662
163663
163664
163665
163666
163667
163668
163669
163670
163671
163672
163673
163674
163675
163676
163677
163678
163679
163680
163681
163682
163683
163684
163685
163686
163687
163688
163689
163690
163691
163692
163693
163694
163695
163696
163697
163698namespace duckdb {
163699
163700enum class OutputStream :
uint8_t { STREAM_STDOUT = 1, STREAM_STDERR = 2 };
163701
163702typedef void (*line_printer_f)(OutputStream stream, const string &str);
163703
163705class Printer {
163706public:
163708 DUCKDB_API static void Print(OutputStream stream, const string &str);
163710 DUCKDB_API static void Print(const string &str);
163712 template <typename... ARGS>
163713 static void PrintF(OutputStream stream, const string &str, ARGS... params) {
163715 }
163717 template <typename... ARGS>
163718 static void PrintF(const string &str, ARGS... params) {
163719 Printer::PrintF(OutputStream::STREAM_STDERR, str, std::forward<ARGS>(params)...);
163720 }
163722 DUCKDB_API static void RawPrint(OutputStream stream, const string &str);
163724 DUCKDB_API static void Flush(OutputStream stream);
163726 DUCKDB_API static bool IsTerminal(OutputStream stream);
163728 DUCKDB_API
static idx_t TerminalWidth();
163729
163730
163731 static line_printer_f line_printer;
163732
163733private:
163734 static void DefaultLinePrint(OutputStream stream, const string &str);
163735};
163736}
163737
163738
163739
163740namespace duckdb {
163741
163743class SQLStatement {
163744public:
163745 static constexpr const StatementType
TYPE = StatementType::INVALID_STATEMENT;
163746
163747public:
163748 explicit SQLStatement(StatementType type) : type(type) {
163749 }
163750 virtual ~SQLStatement() {
163751 }
163752
163754 StatementType type;
163756 idx_t stmt_location = 0;
163758 idx_t stmt_length = 0;
163760 case_insensitive_map_t<idx_t> named_param_map;
163762 string query;
163763
163764protected:
163765 SQLStatement(const SQLStatement &other) = default;
163766
163767public:
163768 virtual string ToString() const = 0;
163770 DUCKDB_API virtual unique_ptr<SQLStatement> Copy() const = 0;
163771
163772public:
163773public:
163774 template <class TARGET>
163775 TARGET &Cast() {
163776 if (type != TARGET::TYPE && TARGET::TYPE != StatementType::INVALID_STATEMENT) {
163777 throw InternalException("Failed to cast statement to type - statement type mismatch");
163778 }
163779 return reinterpret_cast<TARGET &>(*this);
163780 }
163781
163782 template <class TARGET>
163783 const TARGET &Cast() const {
163784 if (type != TARGET::TYPE && TARGET::TYPE != StatementType::INVALID_STATEMENT) {
163785 throw InternalException("Failed to cast statement to type - statement type mismatch");
163786 }
163787 return reinterpret_cast<const TARGET &>(*this);
163788 }
163789};
163790}
163791
163792
163793
163794namespace duckdb {
163795
163796enum class ExplainType :
uint8_t { EXPLAIN_STANDARD, EXPLAIN_ANALYZE };
163797
163798class ExplainStatement : public SQLStatement {
163799public:
163800 static constexpr const StatementType
TYPE = StatementType::EXPLAIN_STATEMENT;
163801
163802public:
163803 explicit ExplainStatement(unique_ptr<SQLStatement> stmt, ExplainType explain_type = ExplainType::EXPLAIN_STANDARD,
163804 ExplainFormat explain_format = ExplainFormat::DEFAULT);
163805
163806 unique_ptr<SQLStatement> stmt;
163807 ExplainType explain_type;
163808 ExplainFormat explain_format = ExplainFormat::DEFAULT;
163809
163810protected:
163811 ExplainStatement(const ExplainStatement &other);
163812
163813public:
163814 unique_ptr<SQLStatement> Copy() const override;
163815 string OptionsToString() const;
163816 string ToString() const override;
163817};
163818
163819}
163820
163821
163822
163823
163824
163825
163826
163827namespace duckdb {
163828struct BoundStatement;
163829
163830class Binder;
163831class LogicalOperator;
163832class QueryNode;
163833class TableRef;
163834
163835static string CreateRelationAlias(RelationType type, const string &alias) {
163836 if (!alias.empty()) {
163837 return alias;
163838 }
163839 return StringUtil::Format(
"%s_%s", EnumUtil::ToString(type), StringUtil::GenerateRandomName());
163840}
163841
163842class RelationContextWrapper : public ClientContextWrapper {
163843public:
163844 ~RelationContextWrapper() override = default;
163845 explicit RelationContextWrapper(const shared_ptr<ClientContext> &context) : ClientContextWrapper(context) {};
163846
163847 explicit RelationContextWrapper(const ClientContextWrapper &context) : ClientContextWrapper(context) {};
163848
163849 void TryBindRelation(Relation &relation, vector<ColumnDefinition> &columns) override {
163850 GetContext()->TryBindRelation(relation, columns);
163851 }
163852
163853private:
163854 weak_ptr<ClientContext> client_context;
163855};
163856
163857class Relation : public enable_shared_from_this<Relation> {
163858public:
163859 Relation(const shared_ptr<ClientContext> &context_p, const RelationType type) : type(type) {
163860 context = make_shared_ptr<ClientContextWrapper>(context_p);
163861 }
163862 Relation(const shared_ptr<ClientContextWrapper> &context, RelationType type, const string &alias_p = "")
163863 : context(context), type(type), alias(CreateRelationAlias(type, alias_p)) {
163864 }
163865
163866 Relation(const shared_ptr<RelationContextWrapper> &context, RelationType type, const string &alias_p = "")
163867 : context(context), type(type), alias(CreateRelationAlias(type, alias_p)) {
163868 }
163869
163870 virtual ~Relation() = default;
163871
163872 shared_ptr<ClientContextWrapper> context;
163873 RelationType type;
163874 const string alias;
163875 vector<shared_ptr<ExternalDependency>> external_dependencies;
163876
163877public:
163878 DUCKDB_API virtual const vector<ColumnDefinition> &Columns() = 0;
163879 DUCKDB_API virtual unique_ptr<QueryNode> GetQueryNode() = 0;
163880 DUCKDB_API virtual string GetQuery();
163881 DUCKDB_API virtual BoundStatement Bind(Binder &binder);
163882 DUCKDB_API virtual string GetAlias();
163883
163884 DUCKDB_API unique_ptr<QueryResult> ExecuteOrThrow();
163885 DUCKDB_API unique_ptr<QueryResult> Execute();
163886 DUCKDB_API string ToString();
163887 DUCKDB_API virtual string ToString(idx_t depth) = 0;
163888
163889 DUCKDB_API void Print();
163890 DUCKDB_API void Head(idx_t limit = 10);
163891
163892 DUCKDB_API shared_ptr<Relation> CreateView(const string &name, bool replace = true, bool temporary = false);
163893 DUCKDB_API shared_ptr<Relation> CreateView(const string &schema_name, const string &name, bool replace = true,
163894 bool temporary = false);
163895 DUCKDB_API unique_ptr<QueryResult> Query(const string &sql) const;
163896 DUCKDB_API unique_ptr<QueryResult> Query(const string &name, const string &sql);
163897
163899 DUCKDB_API unique_ptr<QueryResult> Explain(ExplainType type = ExplainType::EXPLAIN_STANDARD,
163900 ExplainFormat explain_format = ExplainFormat::DEFAULT);
163901
163902 DUCKDB_API virtual unique_ptr<TableRef> GetTableRef();
163903 virtual bool IsReadOnly() {
163904 return true;
163905 }
163906 DUCKDB_API void TryBindRelation(vector<ColumnDefinition> &columns);
163907
163908public:
163909
163910 DUCKDB_API shared_ptr<Relation> Project(const string &select_list);
163911 DUCKDB_API shared_ptr<Relation> Project(const string &expression, const string &alias);
163912 DUCKDB_API shared_ptr<Relation> Project(const string &select_list, const vector<string> &aliases);
163913 DUCKDB_API shared_ptr<Relation> Project(const vector<string> &expressions);
163914 DUCKDB_API shared_ptr<Relation> Project(const vector<string> &expressions, const vector<string> &aliases);
163915 DUCKDB_API shared_ptr<Relation> Project(vector<unique_ptr<ParsedExpression>> expressions,
163916 const vector<string> &aliases);
163917
163918
163919 DUCKDB_API shared_ptr<Relation> Filter(const string &expression);
163920 DUCKDB_API shared_ptr<Relation> Filter(unique_ptr<ParsedExpression> expression);
163921 DUCKDB_API shared_ptr<Relation> Filter(const vector<string> &expressions);
163922
163923
163924 DUCKDB_API shared_ptr<Relation> Limit(int64_t n, int64_t offset = 0);
163925
163926
163927 DUCKDB_API shared_ptr<Relation> Order(const string &expression);
163928 DUCKDB_API shared_ptr<Relation> Order(const vector<string> &expressions);
163929 DUCKDB_API shared_ptr<Relation> Order(vector<OrderByNode> expressions);
163930
163931
163932 DUCKDB_API shared_ptr<Relation> Join(const shared_ptr<Relation> &other, const string &condition,
163933 JoinType type = JoinType::INNER, JoinRefType ref_type = JoinRefType::REGULAR);
163934 shared_ptr<Relation> Join(const shared_ptr<Relation> &other, vector<unique_ptr<ParsedExpression>> condition,
163935 JoinType type = JoinType::INNER, JoinRefType ref_type = JoinRefType::REGULAR);
163936
163937
163938 DUCKDB_API shared_ptr<Relation> CrossProduct(const shared_ptr<Relation> &other,
163939 JoinRefType join_ref_type = JoinRefType::CROSS);
163940
163941
163942 DUCKDB_API shared_ptr<Relation> Union(const shared_ptr<Relation> &other);
163943 DUCKDB_API shared_ptr<Relation> Except(const shared_ptr<Relation> &other);
163944 DUCKDB_API shared_ptr<Relation> Intersect(const shared_ptr<Relation> &other);
163945
163946
163947 DUCKDB_API shared_ptr<Relation> Distinct();
163948
163949
163950 DUCKDB_API shared_ptr<Relation> Aggregate(const string &aggregate_list);
163951 DUCKDB_API shared_ptr<Relation> Aggregate(const vector<string> &aggregates);
163952 DUCKDB_API shared_ptr<Relation> Aggregate(vector<unique_ptr<ParsedExpression>> expressions);
163953 DUCKDB_API shared_ptr<Relation> Aggregate(const string &aggregate_list, const string &group_list);
163954 DUCKDB_API shared_ptr<Relation> Aggregate(const vector<string> &aggregates, const vector<string> &groups);
163955 DUCKDB_API shared_ptr<Relation> Aggregate(vector<unique_ptr<ParsedExpression>> expressions,
163956 const string &group_list);
163957
163958
163959 DUCKDB_API shared_ptr<Relation> Alias(const string &alias);
163960
163962 DUCKDB_API shared_ptr<Relation> InsertRel(const string &schema_name, const string &table_name);
163963 DUCKDB_API shared_ptr<Relation> InsertRel(const string &catalog_name, const string &schema_name,
163964 const string &table_name);
163965 DUCKDB_API void Insert(const string &table_name);
163966 DUCKDB_API void Insert(const string &schema_name, const string &table_name);
163967 DUCKDB_API void Insert(const string &catalog_name, const string &schema_name, const string &table_name);
163969 DUCKDB_API virtual void Insert(const vector<vector<Value>> &values);
163970 DUCKDB_API virtual void Insert(vector<vector<unique_ptr<ParsedExpression>>> &&expressions);
163972 DUCKDB_API shared_ptr<Relation> CreateRel(const string &schema_name, const string &table_name,
163973 bool temporary = false,
163974 OnCreateConflict on_conflict = OnCreateConflict::ERROR_ON_CONFLICT);
163975 DUCKDB_API shared_ptr<Relation> CreateRel(const string &catalog_name, const string &schema_name,
163976 const string &table_name, bool temporary = false,
163977 OnCreateConflict on_conflict = OnCreateConflict::ERROR_ON_CONFLICT);
163978 DUCKDB_API
void Create(
const string &table_name,
bool temporary =
false,
163979 OnCreateConflict on_conflict = OnCreateConflict::ERROR_ON_CONFLICT);
163980 DUCKDB_API
void Create(
const string &schema_name,
const string &table_name,
bool temporary =
false,
163981 OnCreateConflict on_conflict = OnCreateConflict::ERROR_ON_CONFLICT);
163982 DUCKDB_API
void Create(
const string &catalog_name,
const string &schema_name,
const string &table_name,
163983 bool temporary = false, OnCreateConflict on_conflict = OnCreateConflict::ERROR_ON_CONFLICT);
163984
163986 DUCKDB_API shared_ptr<Relation>
163987 WriteCSVRel(const string &csv_file,
163988 case_insensitive_map_t<vector<Value>> options = case_insensitive_map_t<vector<Value>>());
163989 DUCKDB_API void WriteCSV(const string &csv_file,
163990 case_insensitive_map_t<vector<Value>> options = case_insensitive_map_t<vector<Value>>());
163992 DUCKDB_API shared_ptr<Relation>
163993 WriteParquetRel(const string &parquet_file,
163994 case_insensitive_map_t<vector<Value>> options = case_insensitive_map_t<vector<Value>>());
163995 DUCKDB_API void
163996 WriteParquet(const string &parquet_file,
163997 case_insensitive_map_t<vector<Value>> options = case_insensitive_map_t<vector<Value>>());
163998
164000 DUCKDB_API virtual void Update(const string &update, const string &condition = string());
164001 DUCKDB_API virtual void Update(vector<string> column_names, vector<unique_ptr<ParsedExpression>> &&update,
164002 unique_ptr<ParsedExpression> condition = nullptr);
164004 DUCKDB_API virtual void Delete(const string &condition = string());
164007 DUCKDB_API shared_ptr<Relation> TableFunction(const std::string &fname, const vector<Value> &values);
164008 DUCKDB_API shared_ptr<Relation> TableFunction(const std::string &fname, const vector<Value> &values,
164009 const named_parameter_map_t &named_parameters);
164010
164011public:
164013 virtual bool InheritsColumnBindings() {
164014 return false;
164015 }
164016 virtual Relation *ChildRelation() {
164017 return nullptr;
164018 }
164019 void AddExternalDependency(shared_ptr<ExternalDependency> dependency);
164020 DUCKDB_API vector<shared_ptr<ExternalDependency>> GetAllDependencies();
164021
164022protected:
164023 DUCKDB_API static string RenderWhitespace(idx_t depth);
164024
164025public:
164026 template <class TARGET>
164027 TARGET &Cast() {
164028 DynamicCastCheck<TARGET>(this);
164029 return reinterpret_cast<TARGET &>(*this);
164030 }
164031 template <class TARGET>
164032 const TARGET &Cast() const {
164033 DynamicCastCheck<TARGET>(this);
164034 return reinterpret_cast<const TARGET &>(*this);
164035 }
164036};
164037
164038}
164039
164040
164041
164042
164043
164044
164045namespace duckdb {
164046
164047class ColumnDataCollection;
164048class ClientContext;
164049
164050class DatabaseInstance;
164051class DuckDB;
164052class LogicalOperator;
164053class SelectStatement;
164054struct CSVReaderOptions;
164055
164056typedef void (*warning_callback_t)(std::string);
164057
164060class Connection {
164061public:
164062 DUCKDB_API explicit Connection(DuckDB &database);
164063 DUCKDB_API explicit Connection(DatabaseInstance &database);
164064
164065 Connection(const Connection &other) = delete;
164066 Connection &
operator=(
const Connection &) =
delete;
164068 DUCKDB_API Connection(Connection &&other) noexcept;
164069 DUCKDB_API Connection &
operator=(Connection &&) noexcept;
164070 DUCKDB_API ~Connection();
164071
164072 shared_ptr<ClientContext> context;
164073
164074public:
164076 DUCKDB_API
string GetProfilingInformation(ProfilerPrintFormat
format = ProfilerPrintFormat::QUERY_TREE);
164077
164079 DUCKDB_API optional_ptr<ProfilingNode> GetProfilingTree();
164080
164082 DUCKDB_API void Interrupt();
164083
164085 DUCKDB_API double GetQueryProgress();
164086
164088 DUCKDB_API void EnableProfiling();
164090 DUCKDB_API void DisableProfiling();
164091
164093 DUCKDB_API void EnableQueryVerification();
164094 DUCKDB_API void DisableQueryVerification();
164096 DUCKDB_API void ForceParallelism();
164097
164102 DUCKDB_API unique_ptr<QueryResult>
164103 SendQuery(const string &query, QueryParameters query_parameters = QueryResultOutputType::ALLOW_STREAMING);
164104 DUCKDB_API unique_ptr<QueryResult>
164105 SendQuery(unique_ptr<SQLStatement> statement,
164106 QueryParameters query_parameters = QueryResultOutputType::ALLOW_STREAMING);
164109 DUCKDB_API unique_ptr<MaterializedQueryResult> Query(const string &query);
164112 DUCKDB_API unique_ptr<MaterializedQueryResult>
164113 Query(unique_ptr<SQLStatement> statement, QueryResultMemoryType memory_type = QueryResultMemoryType::IN_MEMORY);
164114
164115 template <typename... ARGS>
164116 unique_ptr<QueryResult> Query(const string &query, ARGS... args) {
164117 vector<Value> values;
164118 return QueryParamsRecursive(query, values, args...);
164119 }
164120
164123 DUCKDB_API unique_ptr<PendingQueryResult>
164124 PendingQuery(const string &query, QueryParameters query_parameters = QueryResultOutputType::FORCE_MATERIALIZED);
164126 DUCKDB_API unique_ptr<PendingQueryResult>
164127 PendingQuery(unique_ptr<SQLStatement> statement,
164128 QueryParameters query_parameters = QueryResultOutputType::FORCE_MATERIALIZED);
164129 DUCKDB_API unique_ptr<PendingQueryResult>
164130 PendingQuery(unique_ptr<SQLStatement> statement, case_insensitive_map_t<BoundParameterData> &named_values,
164131 QueryParameters query_parameters = QueryResultOutputType::FORCE_MATERIALIZED);
164132 DUCKDB_API unique_ptr<PendingQueryResult>
164133 PendingQuery(const string &query, case_insensitive_map_t<BoundParameterData> &named_values,
164134 QueryParameters query_parameters = QueryResultOutputType::FORCE_MATERIALIZED);
164135 DUCKDB_API unique_ptr<PendingQueryResult>
164136 PendingQuery(const string &query, vector<Value> &values,
164137 QueryParameters query_parameters = QueryResultOutputType::FORCE_MATERIALIZED);
164138 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(const string &query, PendingQueryParameters parameters);
164139 DUCKDB_API unique_ptr<PendingQueryResult>
164140 PendingQuery(unique_ptr<SQLStatement> statement, vector<Value> &values,
164141 QueryParameters query_parameters = QueryResultOutputType::FORCE_MATERIALIZED);
164142
164144 DUCKDB_API unique_ptr<PreparedStatement> Prepare(const string &query);
164146 DUCKDB_API unique_ptr<PreparedStatement> Prepare(unique_ptr<SQLStatement> statement);
164147
164149 DUCKDB_API unique_ptr<TableDescription> TableInfo(const string &database_name, const string &schema_name,
164150 const string &table_name);
164152 DUCKDB_API unique_ptr<TableDescription> TableInfo(const string &schema_name, const string &table_name);
164155 DUCKDB_API unique_ptr<TableDescription> TableInfo(const string &table_name);
164156
164158 DUCKDB_API vector<unique_ptr<SQLStatement>> ExtractStatements(const string &query);
164160 DUCKDB_API unique_ptr<LogicalOperator> ExtractPlan(const string &query);
164161
164163 DUCKDB_API void Append(TableDescription &description, ColumnDataCollection &collection);
164164
164166 DUCKDB_API shared_ptr<Relation> Table(const string &tname);
164167 DUCKDB_API shared_ptr<Relation> Table(const string &schema_name, const string &table_name);
164168 DUCKDB_API shared_ptr<Relation> Table(const string &catalog_name, const string &schema_name,
164169 const string &table_name);
164171 DUCKDB_API shared_ptr<Relation> View(const string &tname);
164172 DUCKDB_API shared_ptr<Relation> View(const string &schema_name, const string &table_name);
164174 DUCKDB_API shared_ptr<Relation> TableFunction(const string &tname);
164175 DUCKDB_API shared_ptr<Relation> TableFunction(const string &tname, const vector<Value> &values,
164176 const named_parameter_map_t &named_parameters);
164177 DUCKDB_API shared_ptr<Relation> TableFunction(const string &tname, const vector<Value> &values);
164179 DUCKDB_API shared_ptr<Relation> Values(const vector<vector<Value>> &values);
164180 DUCKDB_API shared_ptr<Relation> Values(vector<vector<unique_ptr<ParsedExpression>>> &&values);
164181 DUCKDB_API shared_ptr<Relation> Values(const vector<vector<Value>> &values, const vector<string> &column_names,
164182 const string &alias = "values");
164183 DUCKDB_API shared_ptr<Relation> Values(const string &values);
164184 DUCKDB_API shared_ptr<Relation> Values(const string &values, const vector<string> &column_names,
164185 const string &alias = "values");
164186
164188 DUCKDB_API shared_ptr<Relation> ReadCSV(const string &csv_file);
164189 DUCKDB_API shared_ptr<Relation> ReadCSV(const vector<string> &csv_input, named_parameter_map_t &&options);
164190 DUCKDB_API shared_ptr<Relation> ReadCSV(const string &csv_input, named_parameter_map_t &&options);
164191 DUCKDB_API shared_ptr<Relation> ReadCSV(const string &csv_file, const vector<string> &columns);
164192
164194 DUCKDB_API shared_ptr<Relation> ReadParquet(const string &parquet_file, bool binary_as_string);
164196 DUCKDB_API shared_ptr<Relation> RelationFromQuery(const string &query, const string &alias = "queryrelation",
164197 const string &error = "Expected a single SELECT statement");
164198 DUCKDB_API shared_ptr<Relation> RelationFromQuery(unique_ptr<SelectStatement> select_stmt,
164199 const string &alias = "queryrelation", const string &query = "");
164200
164201 DUCKDB_API void BeginTransaction();
164202 DUCKDB_API void Commit();
164203 DUCKDB_API void Rollback();
164204 DUCKDB_API void SetAutoCommit(bool auto_commit);
164205 DUCKDB_API bool IsAutoCommit();
164206 DUCKDB_API bool HasActiveTransaction();
164207
164211 DUCKDB_API unordered_set<string> GetTableNames(const string &query, const bool qualified = false);
164212
164213
164214 template <typename TR, typename... ARGS>
164215 void CreateScalarFunction(const string &name, TR (*udf_func)(ARGS...)) {
164216 scalar_function_t function = UDFWrapper::CreateScalarFunction<TR, ARGS...>(name, udf_func);
164217 UDFWrapper::RegisterFunction<TR, ARGS...>(name, function, *context);
164218 }
164219
164220 template <typename TR, typename... ARGS>
164221 void CreateScalarFunction(const string &name, vector<LogicalType> args, LogicalType ret_type,
164222 TR (*udf_func)(ARGS...)) {
164223 scalar_function_t function = UDFWrapper::CreateScalarFunction<TR, ARGS...>(name, args, ret_type, udf_func);
164224 UDFWrapper::RegisterFunction(name, args, ret_type, function, *context);
164225 }
164226
164227 template <typename TR, typename... ARGS>
164228 void CreateVectorizedFunction(const string &name, scalar_function_t udf_func,
164229 LogicalType varargs = LogicalType::INVALID) {
164230 UDFWrapper::RegisterFunction<TR, ARGS...>(name, udf_func, *context, std::move(varargs));
164231 }
164232
164233 void CreateVectorizedFunction(const string &name, vector<LogicalType> args, LogicalType ret_type,
164234 scalar_function_t udf_func, LogicalType varargs = LogicalType::INVALID) {
164235 UDFWrapper::RegisterFunction(name, std::move(args), std::move(ret_type), std::move(udf_func), *context,
164236 std::move(varargs));
164237 }
164238
164239
164240 template <typename UDF_OP, typename STATE, typename TR, typename TA>
164241 void CreateAggregateFunction(const string &name) {
164242 AggregateFunction function = UDFWrapper::CreateAggregateFunction<UDF_OP, STATE, TR, TA>(name);
164243 UDFWrapper::RegisterAggrFunction(function, *context);
164244 }
164245
164246 template <typename UDF_OP, typename STATE, typename TR, typename TA, typename TB>
164247 void CreateAggregateFunction(const string &name) {
164248 AggregateFunction function = UDFWrapper::CreateAggregateFunction<UDF_OP, STATE, TR, TA, TB>(name);
164249 UDFWrapper::RegisterAggrFunction(function, *context);
164250 }
164251
164252 template <typename UDF_OP, typename STATE, typename TR, typename TA>
164253 void CreateAggregateFunction(const string &name, LogicalType ret_type, LogicalType input_type_a) {
164254 AggregateFunction function =
164255 UDFWrapper::CreateAggregateFunction<UDF_OP, STATE, TR, TA>(name, ret_type, input_type_a);
164256 UDFWrapper::RegisterAggrFunction(function, *context);
164257 }
164258
164259 template <typename UDF_OP, typename STATE, typename TR, typename TA, typename TB>
164260 void CreateAggregateFunction(const string &name, LogicalType ret_type, LogicalType input_type_a,
164261 LogicalType input_type_b) {
164262 AggregateFunction function =
164263 UDFWrapper::CreateAggregateFunction<UDF_OP, STATE, TR, TA, TB>(name, ret_type, input_type_a, input_type_b);
164264 UDFWrapper::RegisterAggrFunction(function, *context);
164265 }
164266
164267 void CreateAggregateFunction(const string &name, const vector<LogicalType> &arguments,
164268 const LogicalType &return_type, aggregate_size_t state_size,
164269 aggregate_initialize_t initialize, aggregate_update_t update,
164270 aggregate_combine_t combine, aggregate_finalize_t finalize,
164271 aggregate_simple_update_t simple_update = nullptr,
164272 bind_aggregate_function_t bind = nullptr,
164273 aggregate_destructor_t destructor = nullptr) {
164274 AggregateFunction function =
164275 UDFWrapper::CreateAggregateFunction(name, arguments, return_type, state_size, initialize, update, combine,
164276 finalize, simple_update, bind, destructor);
164277 UDFWrapper::RegisterAggrFunction(function, *context);
164278 }
164279
164280
164281protected:
164284
164285private:
164286 unique_ptr<QueryResult> QueryParamsRecursive(const string &query, vector<Value> &values);
164287
164288 template <typename T, typename... ARGS>
164289 unique_ptr<QueryResult> QueryParamsRecursive(const string &query, vector<Value> &values, T value, ARGS... args) {
164290 values.push_back(Value::CreateValue<T>(value));
164291 return QueryParamsRecursive(query, values, args...);
164292 }
164293};
164294
164295}
164296
164297
164298
164299
164300
164301
164302
164303
164304
164305
164306
164307
164308
164309
164310
164311
164312
164313
164314
164315typedef struct {
164316
164317 duckdb_state (*
duckdb_open)(
const char *path, duckdb_database *out_database);
164318 duckdb_state (*
duckdb_open_ext)(
const char *path, duckdb_database *out_database, duckdb_config config,
164319 char **out_error);
164321 duckdb_state (*
duckdb_connect)(duckdb_database database, duckdb_connection *out_connection);
164325 const char *(*duckdb_library_version)();
164329 duckdb_state (*
duckdb_set_config)(duckdb_config config,
const char *name,
const char *option);
164331 duckdb_state (*
duckdb_query)(duckdb_connection connection,
const char *query, duckdb_result *out_result);
164333 const char *(*duckdb_column_name)(duckdb_result *result,
idx_t col);
164339 const char *(*duckdb_result_error)(duckdb_result *result);
164342 void *(*duckdb_malloc)(
size_t size);
164347 const char *(*duckdb_string_t_data)(duckdb_string_t *string);
164364 duckdb_state (*
duckdb_prepare)(duckdb_connection connection,
const char *query,
164365 duckdb_prepared_statement *out_prepared_statement);
164367 const char *(*duckdb_prepare_error)(duckdb_prepared_statement prepared_statement);
164369 const char *(*duckdb_parameter_name)(duckdb_prepared_statement prepared_statement,
idx_t index);
164374 duckdb_state (*
duckdb_bind_value)(duckdb_prepared_statement prepared_statement,
idx_t param_idx, duckdb_value val);
164376 const char *name);
164383 duckdb_hugeint val);
164385 duckdb_uhugeint val);
164387 duckdb_decimal val);
164392 duckdb_state (*
duckdb_bind_float)(duckdb_prepared_statement prepared_statement,
idx_t param_idx,
float val);
164393 duckdb_state (*
duckdb_bind_double)(duckdb_prepared_statement prepared_statement,
idx_t param_idx,
double val);
164394 duckdb_state (*
duckdb_bind_date)(duckdb_prepared_statement prepared_statement,
idx_t param_idx, duckdb_date val);
164395 duckdb_state (*
duckdb_bind_time)(duckdb_prepared_statement prepared_statement,
idx_t param_idx, duckdb_time val);
164397 duckdb_timestamp val);
164399 duckdb_timestamp val);
164401 duckdb_interval val);
164402 duckdb_state (*
duckdb_bind_varchar)(duckdb_prepared_statement prepared_statement,
idx_t param_idx,
const char *val);
164404 const char *val,
idx_t length);
164405 duckdb_state (*
duckdb_bind_blob)(duckdb_prepared_statement prepared_statement,
idx_t param_idx,
const void *data,
164408 duckdb_state (*
duckdb_execute_prepared)(duckdb_prepared_statement prepared_statement, duckdb_result *out_result);
164410 duckdb_extracted_statements *out_extracted_statements);
164412 duckdb_extracted_statements extracted_statements,
idx_t index,
164413 duckdb_prepared_statement *out_prepared_statement);
164414 const char *(*duckdb_extract_statements_error)(duckdb_extracted_statements extracted_statements);
164417 duckdb_pending_result *out_result);
164419 const char *(*duckdb_pending_error)(duckdb_pending_result pending_result);
164422 duckdb_state (*
duckdb_execute_pending)(duckdb_pending_result pending_result, duckdb_result *out_result);
164474 char *(*duckdb_get_varchar)(duckdb_value value);
164489 char *(*duckdb_logical_type_get_alias)(duckdb_logical_type type);
164495 idx_t member_count);
164497 idx_t member_count);
164506 char *(*duckdb_enum_dictionary_value)(duckdb_logical_type type,
idx_t index);
164513 char *(*duckdb_struct_type_child_name)(duckdb_logical_type type,
idx_t index);
164516 char *(*duckdb_union_type_member_name)(duckdb_logical_type type,
idx_t index);
164520 duckdb_create_type_info info);
164529 void *(*duckdb_vector_get_data)(duckdb_vector vector);
164530 uint64_t *(*duckdb_vector_get_validity)(duckdb_vector vector);
164553 duckdb_delete_callback_t destroy);
164555 duckdb_scalar_function_t function);
164557 void *(*duckdb_scalar_function_get_extra_info)(duckdb_function_info info);
164567 duckdb_logical_type type);
164569 duckdb_logical_type type);
164571 duckdb_aggregate_state_size state_size,
164572 duckdb_aggregate_init_t state_init,
164573 duckdb_aggregate_update_t update,
164574 duckdb_aggregate_combine_t
combine,
164575 duckdb_aggregate_finalize_t finalize);
164577 duckdb_aggregate_destroy_t destroy);
164579 duckdb_aggregate_function aggregate_function);
164582 duckdb_delete_callback_t destroy);
164583 void *(*duckdb_aggregate_function_get_extra_info)(duckdb_function_info info);
164588 duckdb_aggregate_function function);
164595 duckdb_logical_type type);
164597 duckdb_delete_callback_t destroy);
164601 duckdb_table_function_init_t init);
164605 void *(*duckdb_bind_get_extra_info)(duckdb_bind_info info);
164613 void *(*duckdb_init_get_extra_info)(duckdb_init_info info);
164614 void *(*duckdb_init_get_bind_data)(duckdb_init_info info);
164620 void *(*duckdb_function_get_extra_info)(duckdb_function_info info);
164621 void *(*duckdb_function_get_bind_data)(duckdb_function_info info);
164622 void *(*duckdb_function_get_init_data)(duckdb_function_info info);
164623 void *(*duckdb_function_get_local_init_data)(duckdb_function_info info);
164626 duckdb_delete_callback_t delete_callback);
164633 duckdb_state (*
duckdb_appender_create)(duckdb_connection connection,
const char *schema,
const char *table,
164634 duckdb_appender *out_appender);
164636 const char *table, duckdb_appender *out_appender);
164639 const char *(*duckdb_appender_error)(duckdb_appender appender);
164647 duckdb_table_description *out);
164649 const char *schema, const char *table,
164650 duckdb_table_description *out);
164652 const char *(*duckdb_table_description_error)(duckdb_table_description table_description);
164654 char *(*duckdb_table_description_get_column_name)(duckdb_table_description table_description,
idx_t index);
164670 duckdb_delete_callback_t destroy);
164671 void *(*duckdb_cast_function_get_extra_info)(duckdb_function_info info);
164675 duckdb_vector output);
164716
164717
164719 void *(*duckdb_column_data)(duckdb_result *result,
idx_t col);
164720 bool *(*duckdb_nullmask_data)(duckdb_result *result,
idx_t col);
164742 char *(*duckdb_value_varchar)(duckdb_result *result,
idx_t col,
idx_t row);
164744 char *(*duckdb_value_varchar_internal)(duckdb_result *result,
idx_t col,
idx_t row);
164749 duckdb_result *out_result);
164751 duckdb_pending_result *out_result);
164752 duckdb_state (*
duckdb_query_arrow)(duckdb_connection connection,
const char *query, duckdb_arrow *out_result);
164760 const char *(*duckdb_query_arrow_error)(duckdb_arrow result);
164764 duckdb_arrow *out_result);
164765 duckdb_state (*
duckdb_arrow_scan)(duckdb_connection connection,
const char *table_name, duckdb_arrow_stream arrow);
164767 duckdb_arrow_schema arrow_schema, duckdb_arrow_array arrow_array,
164768 duckdb_arrow_stream *out_stream);
164770
164771
164774 duckdb_database *out_database, duckdb_config config,
164775 char **out_error);
164777
164778
164783 duckdb_logical_type *types, const char *table_name,
164784 const char **column_names, duckdb_appender *out_appender);
164786
164787
164788 duckdb_error_data (*
duckdb_to_arrow_schema)(duckdb_arrow_options arrow_options, duckdb_logical_type *types,
164789 const char **names,
idx_t column_count,
struct ArrowSchema *out_schema);
164791 struct ArrowArray *out_arrow_array);
164793 duckdb_arrow_converted_schema *out_types);
164795 duckdb_arrow_converted_schema converted_schema,
164796 duckdb_data_chunk *out_chunk);
164798
164799
164801 const char *(*duckdb_catalog_get_type_name)(duckdb_catalog catalog);
164803 duckdb_catalog_entry_type entry_type, const char *schema_name,
164804 const char *entry_name);
164807 const char *(*duckdb_catalog_entry_get_name)(duckdb_catalog_entry entry);
164809
164810
164817 duckdb_config_option_scope default_scope);
164821 duckdb_config_option_scope *out_scope);
164822
164823
164827 duckdb_delete_callback_t destructor);
164832 void *(*duckdb_copy_function_bind_get_extra_info)(duckdb_copy_function_bind_info info);
164839 duckdb_delete_callback_t destructor);
164841 duckdb_copy_function_global_init_t init);
164843 void *(*duckdb_copy_function_global_init_get_extra_info)(duckdb_copy_function_global_init_info info);
164845 duckdb_copy_function_global_init_info info);
164846 void *(*duckdb_copy_function_global_init_get_bind_data)(duckdb_copy_function_global_init_info info);
164848 void *global_state, duckdb_delete_callback_t destructor);
164849 const char *(*duckdb_copy_function_global_init_get_file_path)(duckdb_copy_function_global_init_info info);
164852 void *(*duckdb_copy_function_sink_get_extra_info)(duckdb_copy_function_sink_info info);
164854 void *(*duckdb_copy_function_sink_get_bind_data)(duckdb_copy_function_sink_info info);
164855 void *(*duckdb_copy_function_sink_get_global_state)(duckdb_copy_function_sink_info info);
164857 duckdb_copy_function_finalize_t finalize);
164859 void *(*duckdb_copy_function_finalize_get_extra_info)(duckdb_copy_function_finalize_info info);
164861 void *(*duckdb_copy_function_finalize_get_bind_data)(duckdb_copy_function_finalize_info info);
164862 void *(*duckdb_copy_function_finalize_get_global_state)(duckdb_copy_function_finalize_info info);
164864 duckdb_table_function table_function);
164866 const char *(*duckdb_table_function_bind_get_result_column_name)(duckdb_bind_info info,
idx_t col_idx);
164868
164869
164873 const char *(*duckdb_error_data_message)(duckdb_error_data error_data);
164875
164876
164881 duckdb_value *out_value);
164882
164883
164887 duckdb_file_open_options options, duckdb_file_handle *out_file);
164891 bool value);
164902
164903
164904 char *(*duckdb_geometry_type_get_crs)(duckdb_logical_type type);
164905
164906
164910 duckdb_logger_write_log_entry_t function);
164912 duckdb_delete_callback_t delete_callback);
164915
164916
164920 duckdb_value (*
duckdb_get_table_names)(duckdb_connection connection,
const char *query,
bool qualified);
164923
164924
164926 const char *(*duckdb_prepared_statement_column_name)(duckdb_prepared_statement prepared_statement,
idx_t col_idx);
164930
164931
164933
164934
164939 duckdb_delete_callback_t destroy);
164940 void *(*duckdb_scalar_function_get_bind_data)(duckdb_function_info info);
164941 void *(*duckdb_scalar_function_bind_get_extra_info)(duckdb_bind_info info);
164945
164946
164947 void *(*duckdb_scalar_function_get_state)(duckdb_function_info info);
164952 void *(*duckdb_scalar_function_init_get_bind_data)(duckdb_init_info info);
164953 void *(*duckdb_scalar_function_init_get_extra_info)(duckdb_init_info info);
164954
164955
164956 char *(*duckdb_value_to_string)(duckdb_value value);
164958
164959
164963
164964
164966
164967
164968 duckdb_value (*
duckdb_create_map_value)(duckdb_logical_type map_type, duckdb_value *keys, duckdb_value *values,
164969 idx_t entry_count);
164973
164974
164979 void (*duckdb_vector_reference_vector)(duckdb_vector to_vector, duckdb_vector from_vector);
164982 sel_t *(*duckdb_selection_vector_get_data_ptr)(duckdb_selection_vector sel);
164987} duckdb_ext_api_v1;
164988
164989
164990
164991
164992inline duckdb_ext_api_v1 CreateAPIv1() {
164993 duckdb_ext_api_v1 result;
165534 result.duckdb_vector_reference_vector = duckdb_vector_reference_vector;
165540 return result;
165541}
165542
165543#define DUCKDB_EXTENSION_API_VERSION_MAJOR 1
165544#define DUCKDB_EXTENSION_API_VERSION_MINOR 2
165545#define DUCKDB_EXTENSION_API_VERSION_PATCH 0
165546#define DUCKDB_EXTENSION_API_VERSION_STRING "v1.2.0"
165547
165548
165549
165550
165551
165552
165553
165554
165555
165556
165557
165558
165559
165560
165561
165562namespace duckdb {
165563class ExtensionLoader;
165564
165566class Extension {
165567public:
165568 DUCKDB_API virtual ~Extension();
165569
165570 DUCKDB_API virtual void Load(ExtensionLoader &db) = 0;
165571 DUCKDB_API virtual std::string Name() = 0;
165572 DUCKDB_API virtual std::string Version() const {
165573 return "";
165574 }
165575 DUCKDB_API static const char *DefaultVersion();
165576};
165577
165579 UNKNOWN = 0,
165586};
165587
165589struct ParsedExtensionMetaData {
165590 static constexpr const idx_t FOOTER_SIZE = 512;
165591 static constexpr const idx_t SIGNATURE_SIZE = 256;
165592 static constexpr const char *EXPECTED_MAGIC_VALUE = {
165593 "4\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"};
165594
165595 string magic_value;
165596
165598
165599 string platform;
165600
165601
165602 string duckdb_version;
165603
165604
165605 string duckdb_capi_version;
165606 string extension_version;
165607 string signature;
165608 string extension_abi_metadata;
165609
165610 bool AppearsValid() {
165611 return magic_value == EXPECTED_MAGIC_VALUE;
165612 }
165613
165614
165615 string GetInvalidMetadataError();
165616};
165617
165618struct VersioningUtils {
165620 static bool ParseSemver(string &semver, idx_t &major_out, idx_t &minor_out, idx_t &patch_out);
165621
165623 static bool IsSupportedCAPIVersion(string &capi_version_string);
165624 static bool IsSupportedCAPIVersion(idx_t major, idx_t minor, idx_t patch);
165625};
165626
165627}
165628
165629
165630
165631
165632
165633
165634
165635
165636
165637
165638
165639
165640
165641
165642
165643
165644
165645
165646
165647
165648
165649
165650
165651
165652
165653namespace duckdb {
165654struct MapCastInfo;
165655struct MapCastNode;
165656struct DBConfig;
165657
165658typedef BoundCastInfo (*bind_cast_function_t)(BindCastInput &input, const LogicalType &source,
165659 const LogicalType &target);
165660typedef int64_t (*implicit_cast_cost_t)(
const LogicalType &from,
const LogicalType &to);
165661
165662struct GetCastFunctionInput {
165663 explicit GetCastFunctionInput(optional_ptr<ClientContext> context = nullptr) : context(context) {
165664 }
165665 explicit GetCastFunctionInput(ClientContext &context) : context(&context) {
165666 }
165667
165668 optional_ptr<ClientContext> context;
165669 optional_idx query_location;
165670};
165671
165672struct BindCastFunction {
165673 BindCastFunction(bind_cast_function_t function,
165674 unique_ptr<BindCastInfo> info = nullptr);
165675
165676 bind_cast_function_t function;
165677 unique_ptr<BindCastInfo> info;
165678};
165679
165680class CastFunctionSet {
165681public:
165682 CastFunctionSet();
165683 explicit CastFunctionSet(DBConfig &config);
165684
165685public:
165686 DUCKDB_API static CastFunctionSet &Get(ClientContext &context);
165687 DUCKDB_API static CastFunctionSet &Get(DatabaseInstance &db);
165688
165691 DUCKDB_API BoundCastInfo GetCastFunction(const LogicalType &source, const LogicalType &target,
165692 GetCastFunctionInput &input);
165695 DUCKDB_API
int64_t ImplicitCastCost(optional_ptr<ClientContext> context,
const LogicalType &source,
165696 const LogicalType &target);
165697 DUCKDB_API
static int64_t ImplicitCastCost(ClientContext &context,
const LogicalType &source,
165698 const LogicalType &target);
165699 DUCKDB_API
static int64_t ImplicitCastCost(DatabaseInstance &db,
const LogicalType &source,
165700 const LogicalType &target);
165702 DUCKDB_API void RegisterCastFunction(const LogicalType &source, const LogicalType &target, BoundCastInfo function,
165703 int64_t implicit_cast_cost = -1);
165704 DUCKDB_API void RegisterCastFunction(const LogicalType &source, const LogicalType &target,
165705 bind_cast_function_t bind, int64_t implicit_cast_cost = -1);
165706
165707private:
165708 optional_ptr<DBConfig> config;
165709 vector<BindCastFunction> bind_functions;
165711 optional_ptr<MapCastInfo> map_info;
165712
165713private:
165714 void RegisterCastFunction(const LogicalType &source, const LogicalType &target, MapCastNode node);
165715};
165716
165717}
165718
165719
165720
165721
165722
165723
165724
165725
165726
165727
165728
165729
165730
165731
165732
165733
165734
165735
165736
165737
165738
165739
165740
165741
165742
165743
165744
165745
165746
165747
165748
165749
165750
165751
165752
165753
165754
165755
165756
165757namespace duckdb {
165758
165759enum class PragmaType :
uint8_t { PRAGMA_STATEMENT, PRAGMA_CALL };
165760
165761struct PragmaInfo : public ParseInfo {
165762public:
165763 static constexpr const ParseInfoType
TYPE = ParseInfoType::PRAGMA_INFO;
165764
165765public:
165766 PragmaInfo() : ParseInfo(
TYPE) {
165767 }
165768
165770 string name;
165772 vector<unique_ptr<ParsedExpression>> parameters;
165774 case_insensitive_map_t<unique_ptr<ParsedExpression>> named_parameters;
165775
165776public:
165777 unique_ptr<PragmaInfo> Copy() const;
165778 string ToString() const;
165779
165780 void Serialize(Serializer &serializer) const override;
165781 static unique_ptr<ParseInfo> Deserialize(Deserializer &deserializer);
165782};
165783
165784}
165785
165786
165787
165788namespace duckdb {
165789class ClientContext;
165790
165792typedef string (*pragma_query_t)(ClientContext &context, const FunctionParameters ¶meters);
165794typedef void (*pragma_function_t)(ClientContext &context, const FunctionParameters ¶meters);
165795
165804class PragmaFunction : public SimpleNamedParameterFunction {
165805public:
165806
165807 DUCKDB_API static PragmaFunction PragmaCall(const string &name, pragma_query_t query, vector<LogicalType> arguments,
165808 LogicalType varargs = LogicalType::INVALID);
165809 DUCKDB_API static PragmaFunction PragmaCall(const string &name, pragma_function_t function,
165810 vector<LogicalType> arguments,
165811 LogicalType varargs = LogicalType::INVALID);
165812
165813 DUCKDB_API static PragmaFunction PragmaStatement(const string &name, pragma_query_t query);
165814 DUCKDB_API static PragmaFunction PragmaStatement(const string &name, pragma_function_t function);
165815
165816 DUCKDB_API string ToString() const override;
165817
165818public:
165819 PragmaType type;
165820
165823 named_parameter_type_map_t named_parameters;
165824
165825private:
165826 PragmaFunction(string name, PragmaType pragma_type, pragma_query_t query, pragma_function_t function,
165827 vector<LogicalType> arguments, LogicalType varargs);
165828};
165829
165830}
165831
165832
165833namespace duckdb {
165834
165835template <class T>
165836class FunctionSet {
165837public:
165838 explicit FunctionSet(string name) : name(std::move(name)) {
165839 }
165840
165842 string name;
165844 vector<T> functions;
165845
165846public:
165847 void AddFunction(T function) {
165848 functions.push_back(std::move(function));
165849 }
165851 return functions.size();
165852 }
165853 T GetFunctionByOffset(idx_t offset) {
165854 D_ASSERT(offset < functions.size());
165855 return functions[offset];
165856 }
165857 T &GetFunctionReferenceByOffset(idx_t offset) {
165858 D_ASSERT(offset < functions.size());
165859 return functions[offset];
165860 }
165861 bool MergeFunctionSet(FunctionSet<T> new_functions, bool override = false) {
165862 D_ASSERT(!new_functions.functions.empty());
165863 for (auto &new_func : new_functions.functions) {
165864 bool overwritten = false;
165865 for (auto &func : functions) {
165866 if (new_func.Equal(func)) {
165867
165868 if (override) {
165869
165870 overwritten = true;
165871 func = new_func;
165872 } else {
165873
165874 return false;
165875 }
165876 break;
165877 }
165878 }
165879 if (!overwritten) {
165880 functions.push_back(new_func);
165881 }
165882 }
165883 return true;
165884 }
165885};
165886
165887class ScalarFunctionSet : public FunctionSet<ScalarFunction> {
165888public:
165889 DUCKDB_API explicit ScalarFunctionSet();
165890 DUCKDB_API explicit ScalarFunctionSet(string name);
165891 DUCKDB_API explicit ScalarFunctionSet(ScalarFunction fun);
165892
165893 DUCKDB_API ScalarFunction GetFunctionByArguments(ClientContext &context, const vector<LogicalType> &arguments);
165894};
165895
165896class AggregateFunctionSet : public FunctionSet<AggregateFunction> {
165897public:
165898 DUCKDB_API explicit AggregateFunctionSet();
165899 DUCKDB_API explicit AggregateFunctionSet(string name);
165900 DUCKDB_API explicit AggregateFunctionSet(AggregateFunction fun);
165901
165902 DUCKDB_API AggregateFunction GetFunctionByArguments(ClientContext &context, const vector<LogicalType> &arguments);
165903};
165904
165905class TableFunctionSet : public FunctionSet<TableFunction> {
165906public:
165907 DUCKDB_API explicit TableFunctionSet(string name);
165908 DUCKDB_API explicit TableFunctionSet(TableFunction fun);
165909
165910 TableFunction GetFunctionByArguments(ClientContext &context, const vector<LogicalType> &arguments);
165911};
165912
165913class PragmaFunctionSet : public FunctionSet<PragmaFunction> {
165914public:
165915 DUCKDB_API explicit PragmaFunctionSet(string name);
165916 DUCKDB_API explicit PragmaFunctionSet(PragmaFunction fun);
165917};
165918
165919}
165920
165921
165922
165923
165924
165925
165926
165927
165928
165929
165930
165931
165932
165933
165934
165935
165936
165937
165938
165939
165940
165941
165942
165943
165944
165945
165946
165947
165948
165949
165950
165951
165952
165953
165954
165955
165956
165957
165958
165959
165960
165961
165962
165963
165964
165965#include <stack>
165966
165967namespace duckdb {
165968using std::stack;
165969}
165970
165971
165972
165973
165974
165975
165976
165977
165978
165979
165980
165981
165982
165983
165984
165985
165986namespace duckdb {
165987
165988class ParameterExpression;
165989class BoundParameterExpression;
165990
165991using bound_parameter_map_t = case_insensitive_map_t<shared_ptr<BoundParameterData>>;
165992
165993struct BoundParameterMap {
165994public:
165995 explicit BoundParameterMap(case_insensitive_map_t<BoundParameterData> ¶meter_data);
165996
165997public:
165998 LogicalType GetReturnType(const string &identifier);
165999
166000 bound_parameter_map_t *GetParametersPtr();
166001
166002 const bound_parameter_map_t &GetParameters();
166003
166004 const case_insensitive_map_t<BoundParameterData> &GetParameterData();
166005
166006 unique_ptr<BoundParameterExpression> BindParameterExpression(ParameterExpression &expr);
166007
166009 bool rebind = false;
166010
166011private:
166012 shared_ptr<BoundParameterData> CreateOrGetData(const string &identifier);
166013 void CreateNewParameter(const string &id, const shared_ptr<BoundParameterData> ¶m_data);
166014
166015private:
166016 bound_parameter_map_t parameters;
166017
166018 case_insensitive_map_t<BoundParameterData> ¶meter_data;
166019};
166020
166021}
166022
166023
166024
166025
166026
166027
166028namespace duckdb {
166029class ClientContext;
166030class Catalog;
166031class DatabaseInstance;
166032class CompressionInfo;
166033enum class ExpressionType :
uint8_t;
166034
166035struct SerializationData {
166036 struct CustomData {
166037 virtual ~CustomData() = default;
166038 };
166039
166040 stack<reference<ClientContext>> contexts;
166041 stack<reference<DatabaseInstance>> databases;
166042 stack<reference<Catalog>> catalogs;
166043 stack<idx_t> enums;
166044 stack<reference<bound_parameter_map_t>> parameter_data;
166045 stack<const_reference<LogicalType>> types;
166046 stack<const_reference<CompressionInfo>> compression_infos;
166047 duckdb::unordered_map<std::string, duckdb::stack<duckdb::reference<CustomData>>> customs;
166048
166049 template <class T>
166050 void Set(T entry) = delete;
166051
166052 template <class T>
166053 T Get() = delete;
166054
166055 template <class T>
166056 optional_ptr<T> TryGet() = delete;
166057
166058 template <class T>
166059 void Unset() = delete;
166060
166061 template <class T>
166062 inline void AssertNotEmpty(const stack<T> &e) {
166063 if (e.empty()) {
166064 throw InternalException("SerializationData - unexpected empty stack");
166065 }
166066 }
166067
166068 template <typename T>
166069 typename std::enable_if<std::is_base_of<CustomData, T>::value, T &>::type GetCustom() const {
166070 std::string type = T::GetType();
166071 auto iter = customs.find(type);
166072 if (iter == customs.end()) {
166073 throw duckdb::InternalException("SeserializationData - no stack for %s", type);
166074 }
166075 auto &stack = iter->second;
166076 if (stack.empty()) {
166077 throw duckdb::InternalException("SerializationData - unexpected empty stack for %s", type);
166078 }
166079 return dynamic_cast<T &
>(stack.top().
get());
166080 }
166081
166082 template <typename T>
166083 typename std::enable_if<std::is_base_of<CustomData, T>::value, void>::type SetCustom(T &data) {
166084 std::string type = T::GetType();
166085 auto iter = customs.find(type);
166086 if (iter == customs.end()) {
166087 iter = customs.emplace(type, duckdb::stack<duckdb::reference<CustomData>> {}).first;
166088 }
166089 auto &stack = iter->second;
166090 stack.push(data);
166091 }
166092};
166093
166094template <>
166095inline void SerializationData::Set(ExpressionType type) {
166096 enums.push(
idx_t(type));
166097}
166098
166099template <>
166100inline ExpressionType SerializationData::Get() {
166101 AssertNotEmpty(enums);
166102 return ExpressionType(enums.top());
166103}
166104
166105template <>
166106inline void SerializationData::Unset<ExpressionType>() {
166107 AssertNotEmpty(enums);
166108 enums.pop();
166109}
166110
166111template <>
166112inline void SerializationData::Set(LogicalOperatorType type) {
166113 enums.push(
idx_t(type));
166114}
166115
166116template <>
166117inline LogicalOperatorType SerializationData::Get() {
166118 AssertNotEmpty(enums);
166119 return LogicalOperatorType(enums.top());
166120}
166121
166122template <>
166123inline void SerializationData::Unset<LogicalOperatorType>() {
166124 AssertNotEmpty(enums);
166125 enums.pop();
166126}
166127
166128template <>
166129inline void SerializationData::Set(CompressionType type) {
166130 enums.push(
idx_t(type));
166131}
166132
166133template <>
166134inline CompressionType SerializationData::Get() {
166135 AssertNotEmpty(enums);
166136 return CompressionType(enums.top());
166137}
166138
166139template <>
166140inline void SerializationData::Unset<CompressionType>() {
166141 AssertNotEmpty(enums);
166142 enums.pop();
166143}
166144
166145template <>
166146inline void SerializationData::Set(CatalogType type) {
166147 enums.push(
idx_t(type));
166148}
166149
166150template <>
166151inline CatalogType SerializationData::Get() {
166152 AssertNotEmpty(enums);
166153 return CatalogType(enums.top());
166154}
166155
166156template <>
166157inline void SerializationData::Unset<CatalogType>() {
166158 AssertNotEmpty(enums);
166159 enums.pop();
166160}
166161
166162template <>
166163inline void SerializationData::Set(ClientContext &context) {
166164 contexts.emplace(context);
166165}
166166
166167template <>
166168inline ClientContext &SerializationData::Get() {
166169 AssertNotEmpty(contexts);
166170 return contexts.top();
166171}
166172
166173template <>
166174inline void SerializationData::Unset<ClientContext>() {
166175 AssertNotEmpty(contexts);
166176 contexts.pop();
166177}
166178
166179template <>
166180inline void SerializationData::Set(Catalog &catalog) {
166181 catalogs.emplace(catalog);
166182}
166183
166184template <>
166185inline Catalog &SerializationData::Get() {
166186 AssertNotEmpty(catalogs);
166187 return catalogs.top();
166188}
166189
166190template <>
166191inline optional_ptr<Catalog> SerializationData::TryGet() {
166192 return catalogs.empty() ? nullptr : &catalogs.top().get();
166193}
166194
166195template <>
166196inline void SerializationData::Unset<Catalog>() {
166197 AssertNotEmpty(catalogs);
166198 catalogs.pop();
166199}
166200template <>
166201inline void SerializationData::Set(DatabaseInstance &db) {
166202 databases.emplace(db);
166203}
166204
166205template <>
166206inline DatabaseInstance &SerializationData::Get() {
166207 AssertNotEmpty(databases);
166208 return databases.top();
166209}
166210
166211template <>
166212inline void SerializationData::Unset<DatabaseInstance>() {
166213 AssertNotEmpty(databases);
166214 databases.pop();
166215}
166216
166217template <>
166218inline void SerializationData::Set(bound_parameter_map_t &context) {
166219 parameter_data.emplace(context);
166220}
166221
166222template <>
166223inline bound_parameter_map_t &SerializationData::Get() {
166224 AssertNotEmpty(parameter_data);
166225 return parameter_data.top();
166226}
166227
166228template <>
166229inline void SerializationData::Unset<bound_parameter_map_t>() {
166230 AssertNotEmpty(parameter_data);
166231 parameter_data.pop();
166232}
166233
166234template <>
166235inline void SerializationData::Set(LogicalType &type) {
166236 types.emplace(type);
166237}
166238
166239template <>
166240inline void SerializationData::Unset<LogicalType>() {
166241 AssertNotEmpty(types);
166242 types.pop();
166243}
166244
166245template <>
166246inline void SerializationData::Set(const LogicalType &type) {
166247 types.emplace(type);
166248}
166249
166250template <>
166251inline const LogicalType &SerializationData::Get() {
166252 AssertNotEmpty(types);
166253 return types.top();
166254}
166255
166256template <>
166257inline void SerializationData::Unset<const LogicalType>() {
166258 AssertNotEmpty(types);
166259 types.pop();
166260}
166261
166262template <>
166263inline void SerializationData::Set(const CompressionInfo &compression_info) {
166264 compression_infos.emplace(compression_info);
166265}
166266
166267template <>
166268inline const CompressionInfo &SerializationData::Get() {
166269 AssertNotEmpty(compression_infos);
166270 return compression_infos.top();
166271}
166272
166273template <>
166274inline void SerializationData::Unset<const CompressionInfo>() {
166275 AssertNotEmpty(compression_infos);
166276 compression_infos.pop();
166277}
166278
166279}
166280
166281
166282#include <type_traits>
166283#include <cstdint>
166284#include <atomic>
166285
166286
166287
166288
166289
166290
166291
166292
166293
166294
166295
166296
166297
166298
166299
166300
166301
166302
166303
166304
166305
166306
166307
166308
166309namespace duckdb {
166310
166311template <class T>
166312class optionally_owned_ptr {
166313public:
166314 optionally_owned_ptr() {
166315 }
166316 optionally_owned_ptr(T *ptr_p) : ptr(ptr_p) {
166317 }
166318 optionally_owned_ptr(T &ref) : ptr(&ref) {
166319 }
166320 optionally_owned_ptr(unique_ptr<T> &&owned_p)
166321 : owned(std::move(owned_p)), ptr(owned) {
166322 }
166323 optionally_owned_ptr(shared_ptr<T> owned_p)
166324 : owned_shared(std::move(owned_p)), ptr(*owned_shared) {
166325 }
166326
166327 optionally_owned_ptr(optionally_owned_ptr &&other) noexcept
166328 : owned(std::move(other.owned)), owned_shared(std::move(other.owned_shared)), ptr(other.ptr) {
166329 other.ptr = nullptr;
166330 }
166331
166332 optionally_owned_ptr(const optionally_owned_ptr &other) = delete;
166333
166334 operator bool() const {
166335 return ptr;
166336 }
166338 return *ptr;
166339 }
166341 return *ptr;
166342 }
166343 T *operator->() {
166344 return ptr.get();
166345 }
166346 const T *operator->() const {
166347 return ptr.get();
166348 }
166350 return ptr.get();
166351 }
166352 const T *
get()
const {
166353 return ptr.get();
166354 }
166355 bool is_owned() const {
166356 return owned != nullptr || owned_shared != nullptr;
166357 }
166358 const unique_ptr<T> &get_owned_unique() const {
166359 return owned;
166360 }
166361 const shared_ptr<T> &get_owned_shared() const {
166362 return owned_shared;
166363 }
166364
166365 T *get_mutable() const {
166366 return ptr.get();
166367 }
166368
166369 optionally_owned_ptr<T> &
operator=(T &ref) {
166370 owned = nullptr;
166371 owned_shared = nullptr;
166372 ptr = optional_ptr<T>(ref);
166373 return *this;
166374 }
166375 optionally_owned_ptr<T> &
operator=(T *ref) {
166376 owned = nullptr;
166377 owned_shared = nullptr;
166378 ptr = optional_ptr<T>(ref);
166379 return *this;
166380 }
166381
166382 bool operator==(
const optionally_owned_ptr<T> &rhs)
const {
166383 if (owned != rhs.owned) {
166384 return false;
166385 }
166386 if (owned_shared != rhs.owned_shared) {
166387 return false;
166388 }
166389 return ptr == rhs.ptr;
166390 }
166391
166392 bool operator!=(
const optionally_owned_ptr<T> &rhs)
const {
166393 return !(*this == rhs);
166394 }
166395
166396private:
166397 unique_ptr<T> owned;
166398 shared_ptr<T> owned_shared;
166399 optional_ptr<T> ptr;
166400};
166401
166402}
166403
166404
166405
166406
166407namespace duckdb {
166408
166409class Serializer;
166410class Deserializer;
166411
166413const field_id_t MESSAGE_TERMINATOR_FIELD_ID = 0xFFFF;
166414
166415
166416template <class...>
166417using void_t = void;
166418
166419
166420
166421template <typename T, typename = T>
166422struct has_serialize : std::false_type {};
166423
166424template <typename T>
166425struct has_serialize<
166426 T, typename std::enable_if<
166427 std::is_same<decltype(std::declval<T>().Serialize(std::declval<Serializer &>())), void>::value, T>::type>
166428 : std::true_type {};
166429
166430template <typename T, typename = T>
166431struct has_deserialize : std::false_type {};
166432
166433
166434template <typename T>
166435struct has_deserialize<
166436 T, typename std::enable_if<std::is_same<decltype(T::Deserialize), unique_ptr<T>(Deserializer &)>::value, T>::type>
166437 : std::true_type {};
166438
166439
166440template <typename T>
166441struct has_deserialize<
166442 T, typename std::enable_if<std::is_same<decltype(T::Deserialize), shared_ptr<T>(Deserializer &)>::value, T>::type>
166443 : std::true_type {};
166444
166445
166446template <typename T>
166447struct has_deserialize<
166448 T,
166449 typename std::enable_if<std::is_same<decltype(T::Deserialize), std::shared_ptr<T>(Deserializer &)>::value, T>::type>
166450 : std::true_type {};
166451
166452
166453template <typename T>
166454struct has_deserialize<
166455 T, typename std::enable_if<std::is_same<decltype(T::Deserialize), T(Deserializer &)>::value, T>::type>
166456 : std::true_type {};
166457
166458
166459template <typename T>
166460struct is_vector : std::false_type {};
166461template <typename T>
166462struct is_vector<typename duckdb::vector<T>> : std::true_type {
166463 typedef T ELEMENT_TYPE;
166464};
166465
166466template <typename T>
166467struct is_unsafe_vector : std::false_type {};
166468template <typename T>
166469struct is_unsafe_vector<typename duckdb::unsafe_vector<T>> : std::true_type {
166470 typedef T ELEMENT_TYPE;
166471};
166472
166473
166474template <typename T>
166475struct is_unordered_map : std::false_type {};
166476template <typename... Args>
166477struct is_unordered_map<typename duckdb::unordered_map<Args...>> : std::true_type {
166478 typedef typename std::tuple_element<0, std::tuple<Args...>>::type KEY_TYPE;
166479 typedef typename std::tuple_element<1, std::tuple<Args...>>::type VALUE_TYPE;
166480 typedef typename std::tuple_element<2, std::tuple<Args...>>::type HASH_TYPE;
166481 typedef typename std::tuple_element<3, std::tuple<Args...>>::type EQUAL_TYPE;
166482};
166483
166484template <typename T>
166485struct is_map : std::false_type {};
166486template <typename... Args>
166487struct is_map<typename duckdb::map<Args...>> : std::true_type {
166488 typedef typename std::tuple_element<0, std::tuple<Args...>>::type KEY_TYPE;
166489 typedef typename std::tuple_element<1, std::tuple<Args...>>::type VALUE_TYPE;
166490 typedef typename std::tuple_element<2, std::tuple<Args...>>::type HASH_TYPE;
166491 typedef typename std::tuple_element<3, std::tuple<Args...>>::type EQUAL_TYPE;
166492};
166493
166494template <typename T>
166495struct is_insertion_preserving_map : std::false_type {};
166496template <typename... Args>
166497struct is_insertion_preserving_map<typename duckdb::InsertionOrderPreservingMap<Args...>> : std::true_type {
166498 typedef typename std::tuple_element<0, std::tuple<Args...>>::type VALUE_TYPE;
166499};
166500
166501template <typename T>
166502struct is_queue : std::false_type {};
166503template <typename T>
166504struct is_queue<typename std::priority_queue<T>> : std::true_type {
166505 typedef T ELEMENT_TYPE;
166506};
166507
166508template <typename T>
166509struct is_unique_ptr : std::false_type {};
166510template <typename T>
166511struct is_unique_ptr<unique_ptr<T>> : std::true_type {
166512 typedef T ELEMENT_TYPE;
166513};
166514
166515template <typename T>
166516struct is_shared_ptr : std::false_type {};
166517template <typename T>
166518struct is_shared_ptr<shared_ptr<T>> : std::true_type {
166519 typedef T ELEMENT_TYPE;
166520};
166521template <typename T>
166522struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {
166523 typedef T ELEMENT_TYPE;
166524};
166525
166526template <typename T>
166527struct is_optional_ptr : std::false_type {};
166528template <typename T>
166529struct is_optional_ptr<optional_ptr<T>> : std::true_type {
166530 typedef T ELEMENT_TYPE;
166531};
166532
166533template <typename T>
166534struct is_optionally_owned_ptr : std::false_type {};
166535template <typename T>
166536struct is_optionally_owned_ptr<optionally_owned_ptr<T>> : std::true_type {
166537 typedef T ELEMENT_TYPE;
166538};
166539
166540template <typename T>
166541struct is_pair : std::false_type {};
166542template <typename T, typename U>
166543struct is_pair<std::pair<T, U>> : std::true_type {
166544 typedef T FIRST_TYPE;
166545 typedef U SECOND_TYPE;
166546};
166547
166548template <typename T>
166549struct is_unordered_set : std::false_type {};
166550template <typename... Args>
166551struct is_unordered_set<duckdb::unordered_set<Args...>> : std::true_type {
166552 typedef typename std::tuple_element<0, std::tuple<Args...>>::type ELEMENT_TYPE;
166553 typedef typename std::tuple_element<1, std::tuple<Args...>>::type HASH_TYPE;
166554 typedef typename std::tuple_element<2, std::tuple<Args...>>::type EQUAL_TYPE;
166555};
166556
166557template <typename T>
166558struct is_set : std::false_type {};
166559template <typename... Args>
166560struct is_set<duckdb::set<Args...>> : std::true_type {
166561 typedef typename std::tuple_element<0, std::tuple<Args...>>::type ELEMENT_TYPE;
166562 typedef typename std::tuple_element<1, std::tuple<Args...>>::type HASH_TYPE;
166563 typedef typename std::tuple_element<2, std::tuple<Args...>>::type EQUAL_TYPE;
166564};
166565
166566template <typename T>
166567struct is_atomic : std::false_type {};
166568
166569template <typename T>
166570struct is_atomic<std::atomic<T>> : std::true_type {
166572};
166573
166574
166575
166576struct SerializationDefaultValue {
166577 template <typename T = void>
166578 static inline typename std::enable_if<is_atomic<T>::value, T>::type GetDefault() {
166579 using INNER = typename is_atomic<T>::TYPE;
166580 return static_cast<T>(GetDefault<INNER>());
166581 }
166582
166583 template <typename T = void>
166584 static inline bool IsDefault(const typename std::enable_if<is_atomic<T>::value, T>::type &value) {
166585 using INNER = typename is_atomic<T>::TYPE;
166586 return value == GetDefault<INNER>();
166587 }
166588
166589 template <typename T = void>
166590 static inline typename std::enable_if<std::is_arithmetic<T>::value, T>::type GetDefault() {
166591 return static_cast<T>(0);
166592 }
166593
166594 template <typename T = void>
166595 static inline bool IsDefault(const typename std::enable_if<std::is_arithmetic<T>::value, T>::type &value) {
166596 return value == static_cast<T>(0);
166597 }
166598
166599 template <typename T = void>
166600 static inline typename std::enable_if<is_unique_ptr<T>::value, T>::type GetDefault() {
166601 return T();
166602 }
166603
166604 template <typename T = void>
166605 static inline bool IsDefault(const typename std::enable_if<is_unique_ptr<T>::value, T>::type &value) {
166606 return !value;
166607 }
166608
166609 template <typename T = void>
166610 static inline typename std::enable_if<is_optional_ptr<T>::value, T>::type GetDefault() {
166611 return T();
166612 }
166613
166614 template <typename T = void>
166615 static inline bool IsDefault(const typename std::enable_if<is_optional_ptr<T>::value, T>::type &value) {
166616 return !value;
166617 }
166618
166619 template <typename T = void>
166620 static inline typename std::enable_if<is_optionally_owned_ptr<T>::value, T>::type GetDefault() {
166621 return T();
166622 }
166623
166624 template <typename T = void>
166625 static inline bool IsDefault(const typename std::enable_if<is_optionally_owned_ptr<T>::value, T>::type &value) {
166626 return !value;
166627 }
166628
166629 template <typename T = void>
166630 static inline typename std::enable_if<is_shared_ptr<T>::value, T>::type GetDefault() {
166631 return T();
166632 }
166633
166634 template <typename T = void>
166635 static inline bool IsDefault(const typename std::enable_if<is_shared_ptr<T>::value, T>::type &value) {
166636 return !value;
166637 }
166638
166639 template <typename T = void>
166640 static inline typename std::enable_if<is_vector<T>::value, T>::type GetDefault() {
166641 return T();
166642 }
166643
166644 template <typename T = void>
166645 static inline bool IsDefault(const typename std::enable_if<is_vector<T>::value, T>::type &value) {
166646 return value.empty();
166647 }
166648
166649 template <typename T = void>
166650 static inline typename std::enable_if<is_queue<T>::value, T>::type GetDefault() {
166651 return T();
166652 }
166653
166654 template <typename T = void>
166655 static inline bool IsDefault(const typename std::enable_if<is_queue<T>::value, T>::type &value) {
166656 return value.empty();
166657 }
166658
166659 template <typename T = void>
166660 static inline typename std::enable_if<is_unsafe_vector<T>::value, T>::type GetDefault() {
166661 return T();
166662 }
166663
166664 template <typename T = void>
166665 static inline bool IsDefault(const typename std::enable_if<is_unsafe_vector<T>::value, T>::type &value) {
166666 return value.empty();
166667 }
166668
166669 template <typename T = void>
166670 static inline typename std::enable_if<is_unordered_set<T>::value, T>::type GetDefault() {
166671 return T();
166672 }
166673
166674 template <typename T = void>
166675 static inline bool IsDefault(const typename std::enable_if<is_unordered_set<T>::value, T>::type &value) {
166676 return value.empty();
166677 }
166678
166679 template <typename T = void>
166680 static inline typename std::enable_if<is_unordered_map<T>::value, T>::type GetDefault() {
166681 return T();
166682 }
166683
166684 template <typename T = void>
166685 static inline bool IsDefault(const typename std::enable_if<is_unordered_map<T>::value, T>::type &value) {
166686 return value.empty();
166687 }
166688
166689 template <typename T = void>
166690 static inline typename std::enable_if<is_map<T>::value, T>::type GetDefault() {
166691 return T();
166692 }
166693
166694 template <typename T = void>
166695 static inline bool IsDefault(const typename std::enable_if<is_map<T>::value, T>::type &value) {
166696 return value.empty();
166697 }
166698
166699 template <typename T = void>
166700 static inline typename std::enable_if<is_insertion_preserving_map<T>::value, T>::type GetDefault() {
166701 return T();
166702 }
166703
166704 template <typename T = void>
166705 static inline bool IsDefault(const typename std::enable_if<is_insertion_preserving_map<T>::value, T>::type &value) {
166706 return value.empty();
166707 }
166708
166709 template <typename T = void>
166710 static inline typename std::enable_if<std::is_same<T, string>::value, T>::type GetDefault() {
166711 return T();
166712 }
166713
166714 template <typename T = void>
166715 static inline bool IsDefault(const typename std::enable_if<std::is_same<T, string>::value, T>::type &value) {
166716 return value.empty();
166717 }
166718
166719 template <typename T = void>
166720 static inline typename std::enable_if<std::is_same<T, optional_idx>::value, T>::type GetDefault() {
166721 return optional_idx();
166722 }
166723
166724 template <typename T = void>
166725 static inline bool IsDefault(const typename std::enable_if<std::is_same<T, optional_idx>::value, T>::type &value) {
166726 return !value.IsValid();
166727 }
166728};
166729
166730}
166731
166732
166733
166734
166735
166736
166737
166738
166739
166740
166741
166742
166743
166744
166745
166746
166747
166748
166749
166750
166751
166752
166753
166754
166755
166756
166757
166758
166759
166760
166761
166762
166763
166764
166765
166766
166767
166768
166769
166770
166771
166772
166773
166774
166775
166776
166777
166778
166779
166780
166781
166782
166783
166784
166785
166786
166787namespace duckdb {
166788
166789struct DBConfig;
166790
166792struct CSVEncoderBuffer {
166793 CSVEncoderBuffer() : encoded_buffer_size(0) {};
166794 void Initialize(idx_t encoded_buffer_size);
166795
166796 char *
Ptr()
const;
166797
166798 idx_t GetCapacity()
const;
166799
166800 idx_t GetSize()
const;
166801
166802 void SetSize(const idx_t buffer_size);
166803
166804 bool HasDataToRead() const;
166805
166806 void Reset();
166807 idx_t cur_pos = 0;
166809 idx_t actual_encoded_buffer_size = 0;
166811 bool last_buffer = false;
166812
166813private:
166815 duckdb::unique_ptr<char[]> encoded_buffer;
166817 idx_t encoded_buffer_size;
166818};
166819
166820class CSVEncoder {
166821public:
166823 CSVEncoder(ClientContext &context, const string &encoding_name, idx_t buffer_size);
166825 idx_t Encode(FileHandle &file_handle_input,
char *output_buffer,
const idx_t decoded_buffer_size);
166826 string encoding_name;
166827
166828private:
166829 QueryContext context;
166830
166832 CSVEncoderBuffer encoded_buffer;
166834 CSVEncoderBuffer remaining_bytes_buffer;
166836 optional_ptr<EncodingFunction> encoding_function;
166838 char pass_on_byte;
166839 bool has_pass_on_byte = false;
166840};
166841}
166842
166843
166844
166845namespace duckdb {
166846class Allocator;
166847class FileSystem;
166848struct CSVReaderOptions;
166849
166850class CSVFileHandle {
166851public:
166852 CSVFileHandle(ClientContext &context, unique_ptr<FileHandle> file_handle_p, const OpenFileInfo &file,
166853 const CSVReaderOptions &options);
166854
166855 mutex main_mutex;
166856
166857 bool CanSeek() const;
166858 void Seek(idx_t position) const;
166859 bool OnDiskFile() const;
166860 bool IsPipe() const;
166861
166862 void Reset();
166863
166864 idx_t FileSize()
const;
166865
166866 bool FinishedReading() const;
166867
166868 idx_t Read(
void *buffer, idx_t nr_bytes);
166869
166870 string ReadLine();
166871
166872 string GetFilePath();
166873
166874 static unique_ptr<FileHandle> OpenFileHandle(FileSystem &fs, Allocator &allocator, const OpenFileInfo &file,
166875 FileCompressionType compression);
166876 static unique_ptr<CSVFileHandle> OpenFile(ClientContext &context, const OpenFileInfo &file,
166877 const CSVReaderOptions &options);
166878 FileCompressionType compression_type;
166879
166880 double GetProgress() const;
166881
166882private:
166883 QueryContext context;
166884 unique_ptr<FileHandle> file_handle;
166885 CSVEncoder encoder;
166886 const OpenFileInfo file;
166887 bool can_seek = false;
166888 bool on_disk_file = false;
166889 bool is_pipe = false;
166890 idx_t uncompressed_bytes_read = 0;
166891
166892 idx_t file_size = 0;
166893
166894 idx_t requested_bytes = 0;
166896 bool finished = false;
166897};
166898
166899}
166900
166901
166902
166903
166904
166905
166906
166907
166908
166909
166910
166911
166912
166913
166914
166915
166916
166917
166918
166919
166920
166921
166922
166923namespace duckdb {
166924
166925enum class MemoryTag :
uint8_t {
166926 BASE_TABLE = 0,
166927 HASH_TABLE = 1,
166928 PARQUET_READER = 2,
166929 CSV_READER = 3,
166930 ORDER_BY = 4,
166931 ART_INDEX = 5,
166932 COLUMN_DATA = 6,
166933 METADATA = 7,
166934 OVERFLOW_STRINGS = 8,
166935 IN_MEMORY_TABLE = 9,
166936 ALLOCATOR = 10,
166937 EXTENSION = 11,
166938 TRANSACTION = 12,
166939 EXTERNAL_FILE_CACHE = 13,
166940 WINDOW = 14,
166941 OBJECT_CACHE = 15,
166942
166943 UNKNOWN = 16,
166944};
166945
166946static constexpr const idx_t MEMORY_TAG_COUNT =
static_cast<idx_t>(MemoryTag::UNKNOWN);
166947
166948}
166949
166950
166951
166952
166953
166954
166955
166956
166957
166958
166959
166960
166961
166962
166963
166964
166965
166966
166967
166968
166969namespace duckdb {
166970
166971class BlockHandle;
166972class BufferHandle;
166973class BufferManager;
166974class ClientContext;
166975class DatabaseInstance;
166976class MetadataManager;
166977
166978enum class ConvertToPersistentMode { DESTRUCTIVE, THREAD_SAFE };
166979
166982class BlockManager {
166983public:
166984 BlockManager() = delete;
166985 BlockManager(BufferManager &buffer_manager, const optional_idx block_alloc_size_p,
166986 const optional_idx block_header_size_p);
166987 virtual ~BlockManager() = default;
166988
166990 BufferManager &buffer_manager;
166991
166992public:
166993 BufferManager &GetBufferManager() const {
166994 return buffer_manager;
166995 }
166997 virtual unique_ptr<Block> ConvertBlock(block_id_t block_id, FileBuffer &source_buffer) = 0;
166998 virtual unique_ptr<Block> CreateBlock(block_id_t block_id, FileBuffer *source_buffer) = 0;
167000 virtual block_id_t GetFreeBlockId() = 0;
167001 virtual block_id_t PeekFreeBlockId() = 0;
167003
167004 virtual block_id_t GetFreeBlockIdForCheckpoint() = 0;
167005
167007 virtual bool IsRootBlock(MetaBlockPointer root) = 0;
167009 virtual void MarkBlockAsCheckpointed(block_id_t block_id) = 0;
167011 virtual void MarkBlockAsUsed(block_id_t block_id) = 0;
167014 virtual void MarkBlockAsModified(block_id_t block_id) = 0;
167017 virtual void IncreaseBlockReferenceCount(block_id_t block_id) = 0;
167019 virtual idx_t GetMetaBlock() = 0;
167021 virtual void Read(QueryContext context, Block &block) = 0;
167022
167024 virtual void ReadBlocks(FileBuffer &buffer, block_id_t start_block, idx_t block_count) = 0;
167026 virtual void Write(FileBuffer &block, block_id_t block_id) = 0;
167027 virtual void Write(QueryContext context, FileBuffer &block, block_id_t block_id);
167029 void Write(Block &block) {
167030 Write(block, block.id);
167031 }
167033 virtual void WriteHeader(QueryContext context, DatabaseHeader header) = 0;
167034
167036 virtual idx_t TotalBlocks() = 0;
167038 virtual idx_t FreeBlocks() = 0;
167040 virtual bool IsRemote() {
167041 return false;
167042 }
167044 virtual bool InMemory() = 0;
167046 virtual bool Prefetch() {
167047 return false;
167048 }
167049
167051 virtual void FileSync() = 0;
167053 virtual void Truncate();
167054
167056 shared_ptr<BlockHandle> RegisterBlock(block_id_t block_id);
167061 shared_ptr<BlockHandle> ConvertToPersistent(QueryContext context, block_id_t block_id,
167062 shared_ptr<BlockHandle> old_block, BufferHandle old_handle,
167063 ConvertToPersistentMode mode = ConvertToPersistentMode::DESTRUCTIVE);
167064 shared_ptr<BlockHandle> ConvertToPersistent(QueryContext context, block_id_t block_id,
167065 shared_ptr<BlockHandle> old_block,
167066 ConvertToPersistentMode mode = ConvertToPersistentMode::DESTRUCTIVE);
167067
167068 void UnregisterPersistentBlock(BlockHandle &block);
167070 virtual void UnregisterBlock(block_id_t id);
167071
167073 MetadataManager &GetMetadataManager();
167074
167076 idx_t GetBlockAllocSize()
const {
167077 return block_alloc_size.GetIndex();
167078 }
167080 inline optional_idx GetOptionalBlockAllocSize() const {
167081 return block_alloc_size;
167082 }
167084 inline optional_idx GetOptionalBlockHeaderSize() const {
167085 return block_header_size;
167086 }
167088 idx_t GetBlockHeaderSize()
const {
167089 if (!block_header_size.IsValid()) {
167090 return Storage::DEFAULT_BLOCK_HEADER_SIZE;
167091 }
167092 return block_header_size.GetIndex();
167093 }
167095 idx_t GetBlockSize()
const {
167096 return block_alloc_size.GetIndex() - block_header_size.GetIndex();
167097 }
167101 void SetBlockAllocSize(const optional_idx block_alloc_size_p) {
167102 if (block_alloc_size.IsValid()) {
167103 throw InternalException("the block allocation size must be set once");
167104 }
167105 block_alloc_size = block_alloc_size_p.GetIndex();
167106 }
167110 void SetBlockHeaderSize(const optional_idx block_header_size_p) {
167111 if (block_header_size.IsValid()) {
167112 throw InternalException("block header size already set, must be set once");
167113 }
167114 block_header_size = block_header_size_p.GetIndex();
167115 }
167117 virtual void VerifyBlocks(const unordered_map<block_id_t, idx_t> &block_usage_count) {
167118 }
167119
167120protected:
167121 bool BlockIsRegistered(block_id_t block_id);
167122 shared_ptr<BlockHandle> TryGetBlock(block_id_t block_id);
167123
167124public:
167125 template <class TARGET>
167126 TARGET &Cast() {
167127 DynamicCastCheck<TARGET>(this);
167128 return reinterpret_cast<TARGET &>(*this);
167129 }
167130 template <class TARGET>
167131 const TARGET &Cast() const {
167132 DynamicCastCheck<TARGET>(this);
167133 return reinterpret_cast<const TARGET &>(*this);
167134 }
167135
167136protected:
167139 bool in_destruction = false;
167140
167141private:
167143 mutex blocks_lock;
167145 unordered_map<block_id_t, weak_ptr<BlockHandle>> blocks;
167147 unique_ptr<MetadataManager> metadata_manager;
167151 optional_idx block_alloc_size;
167155 optional_idx block_header_size;
167156};
167157
167158struct BlockIdVisitor {
167159 virtual ~BlockIdVisitor() = default;
167160
167161 virtual void Visit(block_id_t block_id) = 0;
167162};
167163
167164}
167165
167166
167167
167168
167169
167170
167171
167172
167173
167174
167175
167176
167177
167178
167179
167180namespace duckdb {
167181
167182struct MemoryInformation {
167183 MemoryTag tag;
167185 idx_t evicted_data;
167186};
167187
167188struct TemporaryFileInformation {
167189 string path;
167191};
167192
167193struct CachedFileInformation {
167194 string path;
167197 bool loaded;
167198};
167199
167200}
167201
167202
167203
167204namespace duckdb {
167205class BlockMemory;
167206class Allocator;
167207class BufferPool;
167208class TemporaryMemoryManager;
167209
167210class BufferManager {
167211 friend class BufferHandle;
167212 friend class BlockHandle;
167213 friend class BlockManager;
167214
167215public:
167216 BufferManager() {
167217 }
167218 virtual ~BufferManager() {
167219 }
167220
167221public:
167222 DUCKDB_API static BufferManager &GetBufferManager(DatabaseInstance &db);
167223 DUCKDB_API static const BufferManager &GetBufferManager(const DatabaseInstance &db);
167224 DUCKDB_API static BufferManager &GetBufferManager(ClientContext &context);
167225 DUCKDB_API static const BufferManager &GetBufferManager(const ClientContext &context);
167226 DUCKDB_API static BufferManager &GetBufferManager(AttachedDatabase &db);
167227 DUCKDB_API
static idx_t GetAllocSize(
const idx_t alloc_size);
167228
167229public:
167231 virtual shared_ptr<BlockHandle> AllocateTemporaryMemory(MemoryTag tag, idx_t block_size,
167232 bool can_destroy = true) = 0;
167236 virtual shared_ptr<BlockHandle> AllocateMemory(MemoryTag tag, BlockManager *block_manager,
167237 bool can_destroy = true) = 0;
167239 virtual BufferHandle Allocate(MemoryTag tag, idx_t block_size, bool can_destroy = true) = 0;
167241 virtual BufferHandle Allocate(MemoryTag tag, BlockManager *block_manager, bool can_destroy = true) = 0;
167243 virtual BufferHandle Pin(shared_ptr<BlockHandle> &handle) = 0;
167244 virtual BufferHandle Pin(const QueryContext &context, shared_ptr<BlockHandle> &handle) = 0;
167247 virtual void Prefetch(vector<shared_ptr<BlockHandle>> &handles) = 0;
167249 virtual void Unpin(shared_ptr<BlockHandle> &handle) = 0;
167250
167252 virtual idx_t GetUsedMemory()
const = 0;
167254 virtual idx_t GetMaxMemory()
const = 0;
167256 virtual idx_t GetUsedSwap()
const = 0;
167258 virtual optional_idx GetMaxSwap() const = 0;
167260 virtual idx_t GetBlockAllocSize()
const = 0;
167262 virtual idx_t GetBlockSize()
const = 0;
167264 virtual idx_t GetQueryMaxMemory()
const = 0;
167265
167267 virtual shared_ptr<BlockHandle> RegisterTransientMemory(const idx_t size, BlockManager &block_manager);
167269 virtual shared_ptr<BlockHandle> RegisterSmallMemory(const idx_t size);
167271 virtual shared_ptr<BlockHandle> RegisterSmallMemory(MemoryTag tag, const idx_t size);
167272
167274 virtual DUCKDB_API Allocator &GetBufferAllocator();
167276 virtual DUCKDB_API void ReserveMemory(idx_t size);
167278 virtual DUCKDB_API void FreeReservedMemory(idx_t size);
167280 virtual vector<MemoryInformation> GetMemoryUsageInfo() const = 0;
167283 virtual void SetMemoryLimit(idx_t limit = (idx_t)-1);
167285 virtual void SetSwapLimit(optional_idx limit = optional_idx());
167286
167288 virtual BlockManager &GetTemporaryBlockManager() = 0;
167290 virtual vector<TemporaryFileInformation> GetTemporaryFiles();
167292 virtual const string &GetTemporaryDirectory() const;
167294 virtual void SetTemporaryDirectory(const string &new_dir);
167296 virtual bool HasTemporaryDirectory() const;
167298 virtual bool HasFilesInTemporaryDirectory() const;
167299
167301 virtual unique_ptr<FileBuffer> ConstructManagedBuffer(idx_t size, idx_t block_header_size,
167302 unique_ptr<FileBuffer> &&source,
167303 FileBufferType type = FileBufferType::MANAGED_BUFFER);
167305 virtual BufferPool &GetBufferPool() const;
167307 virtual const DatabaseInstance &GetDatabase() const = 0;
167309 virtual DatabaseInstance &GetDatabase() = 0;
167311 virtual TemporaryMemoryManager &GetTemporaryMemoryManager();
167312
167314 virtual void PurgeQueue(const BlockHandle &handle) = 0;
167316 virtual void AddToEvictionQueue(shared_ptr<BlockHandle> &handle);
167318 virtual void WriteTemporaryBuffer(MemoryTag tag, block_id_t block_id, FileBuffer &buffer);
167320 virtual unique_ptr<FileBuffer> ReadTemporaryBuffer(QueryContext context, MemoryTag tag, BlockHandle &block,
167321 unique_ptr<FileBuffer> buffer);
167323 virtual void DeleteTemporaryFile(BlockMemory &memory);
167324};
167325
167326}
167327
167328
167329
167330
167331
167332
167333
167334
167335
167336
167337
167338
167339
167340
167341
167342
167343
167344
167345
167346
167347
167348
167349
167350
167351
167352namespace duckdb {
167353
167355 BLOCK = 0,
167358};
167359
167360}
167361
167362
167363
167364
167365
167366
167367
167368
167369
167370
167371
167372
167373
167374
167375
167376
167377
167378
167379namespace duckdb {
167380
167381enum class BlockState :
uint8_t { BLOCK_UNLOADED = 0, BLOCK_LOADED = 1 };
167382
167383
167384class BufferPool;
167385
167386struct BufferPoolReservation {
167387 MemoryTag tag;
167389 BufferPool &pool;
167390
167391 BufferPoolReservation(MemoryTag tag, BufferPool &pool);
167392 BufferPoolReservation(const BufferPoolReservation &) = delete;
167393 BufferPoolReservation &
operator=(
const BufferPoolReservation &) =
delete;
167394
167395 BufferPoolReservation(BufferPoolReservation &&) noexcept;
167396 BufferPoolReservation &operator=(BufferPoolReservation &&) noexcept;
167397
167398 virtual ~BufferPoolReservation();
167399
167400 void Resize(idx_t new_size);
167401 void Merge(BufferPoolReservation src);
167402};
167403
167404struct TempBufferPoolReservation : BufferPoolReservation {
167405 TempBufferPoolReservation(MemoryTag tag, BufferPool &pool, idx_t size) : BufferPoolReservation(tag, pool) {
167406 Resize(size);
167407 }
167408 TempBufferPoolReservation(TempBufferPoolReservation &&) = default;
167409 ~TempBufferPoolReservation() override {
167410 Resize(0);
167411 }
167412};
167413
167414}
167415
167416
167417
167418namespace duckdb {
167419
167420
167421class BlockManager;
167422class BufferHandle;
167423class BufferManager;
167424class DatabaseInstance;
167425class BlockHandle;
167426
167427using BlockLock = unique_lock<mutex>;
167428
167429class BlockMemory : public enable_shared_from_this<BlockMemory> {
167430public:
167431 BlockMemory(BufferManager &buffer_manager, block_id_t block_id_p, MemoryTag tag_p, idx_t block_alloc_size);
167432 BlockMemory(BufferManager &buffer_manager, block_id_t block_id_p, MemoryTag tag_p, unique_ptr<FileBuffer> buffer_p,
167433 DestroyBufferUpon destroy_buffer_upon_p, idx_t size_p, BufferPoolReservation &&reservation);
167434 ~BlockMemory();
167435
167436public:
167438 const BufferManager &GetBufferManager() const {
167439 return buffer_manager;
167440 }
167442 BufferManager &GetBufferManager() {
167443 return buffer_manager;
167444 }
167446 block_id_t BlockId() const {
167447 return block_id;
167448 }
167450 BlockLock GetLock() {
167451 return BlockLock(lock);
167452 }
167454 void VerifyMutex(BlockLock &l) const {
167455 D_ASSERT(l.owns_lock());
167456 D_ASSERT(l.mutex() == &lock);
167457 }
167459 BlockState GetState() const {
167460 return state;
167461 }
167463 void SetState(BlockState state_p) {
167464 state = state_p;
167465 }
167467 bool IsUnloaded() const {
167468 return state == BlockState::BLOCK_UNLOADED;
167469 }
167471 int32_t GetReaders()
const {
167472 return readers;
167473 }
167475 int32_t IncrementReaders() {
167476 return ++readers;
167477 }
167479 int32_t DecrementReaders() {
167480 return --readers;
167481 }
167483 void SetReaders(int32_t n) {
167484 readers = n;
167485 }
167487 MemoryTag GetMemoryTag() const {
167488 return tag;
167489 }
167491 FileBufferType GetBufferType() const {
167492 return buffer_type;
167493 }
167495 unique_ptr<FileBuffer> &GetBuffer(BlockLock &l) {
167496 VerifyMutex(l);
167497 return GetBuffer();
167498 }
167500 unique_ptr<FileBuffer> &GetBuffer() {
167501 return buffer;
167502 }
167504 void SetBuffer(unique_ptr<FileBuffer> buffer_p) {
167505 buffer = std::move(buffer_p);
167506 }
167508 idx_t GetEvictionSequenceNumber()
const {
167509 return eviction_seq_num;
167510 }
167512 idx_t NextEvictionSequenceNumber() {
167513 return ++eviction_seq_num;
167514 }
167516 int64_t GetLRUTimestamp()
const {
167517 return lru_timestamp_msec;
167518 }
167520 void SetLRUTimestamp(int64_t timestamp_msec) {
167521 lru_timestamp_msec = timestamp_msec;
167522 }
167524 void SetDestroyBufferUpon(DestroyBufferUpon destroy_buffer_upon_p) {
167525 destroy_buffer_upon = destroy_buffer_upon_p;
167526 }
167528 bool MustAddToEvictionQueue() const {
167529 return destroy_buffer_upon != DestroyBufferUpon::UNPIN;
167530 }
167532 bool MustWriteToTemporaryFile() const {
167533 return destroy_buffer_upon == DestroyBufferUpon::BLOCK;
167534 }
167536 idx_t GetMemoryUsage()
const {
167537 return memory_usage;
167538 }
167540 void SetMemoryUsage(idx_t usage) {
167541 memory_usage = usage;
167542 }
167544 BufferPoolReservation &GetMemoryCharge(BlockLock &l) {
167545 VerifyMutex(l);
167546 return GetMemoryCharge();
167547 }
167549 BufferPoolReservation &GetMemoryCharge() {
167550 return memory_charge;
167551 }
167553 void ResizeMemory(BlockLock &l, idx_t alloc_size) {
167554 VerifyMutex(l);
167555 memory_charge.Resize(alloc_size);
167556 }
167558 void MergeMemoryReservation(BlockLock &l, BufferPoolReservation reservation) {
167559 VerifyMutex(l);
167560 memory_charge.Merge(std::move(reservation));
167561 }
167563 bool IsSwizzled() const {
167564 return !unswizzled;
167565 }
167567 void SetSwizzling(const char *unswizzler) {
167568 unswizzled = unswizzler;
167569 }
167571 void SetEvictionQueueIndex(const idx_t index) {
167572
167573 D_ASSERT(eviction_queue_idx == DConstants::INVALID_INDEX);
167574
167575 D_ASSERT(GetBufferType() == FileBufferType::MANAGED_BUFFER);
167576 eviction_queue_idx =
index;
167577 }
167579 idx_t GetEvictionQueueIndex()
const {
167580 return eviction_queue_idx;
167581 }
167582
167583public:
167584 void ChangeMemoryUsage(BlockLock &l, int64_t delta);
167585 void ConvertToPersistent(BlockLock &l, BlockHandle &new_block, unique_ptr<FileBuffer> new_buffer);
167586 void ResizeBuffer(BlockLock &l, idx_t block_size, idx_t block_header_size, int64_t memory_delta);
167590 bool CanUnload() const;
167591 unique_ptr<FileBuffer> UnloadAndTakeBlock(BlockLock &l);
167592 void Unload(BlockLock &l);
167593
167594private:
167596 BufferManager &buffer_manager;
167598 const block_id_t block_id;
167600 mutex lock;
167602 atomic<BlockState> state;
167604 atomic<int32_t> readers;
167606 const MemoryTag tag;
167608 const FileBufferType buffer_type;
167610 unique_ptr<FileBuffer> buffer;
167612 atomic<idx_t> eviction_seq_num;
167614 atomic<int64_t> lru_timestamp_msec;
167616 atomic<DestroyBufferUpon> destroy_buffer_upon;
167619 atomic<idx_t> memory_usage;
167621 BufferPoolReservation memory_charge;
167623 const char *unswizzled;
167625 atomic<idx_t> eviction_queue_idx;
167626};
167627
167628class BlockHandle : public enable_shared_from_this<BlockHandle> {
167629public:
167630 BlockHandle(BlockManager &block_manager, block_id_t block_id, MemoryTag tag);
167631 BlockHandle(BlockManager &block_manager, block_id_t block_id, MemoryTag tag, unique_ptr<FileBuffer> buffer,
167632 DestroyBufferUpon destroy_buffer_upon, idx_t size, BufferPoolReservation &&reservation);
167633 ~BlockHandle();
167634
167635public:
167637 BlockManager &GetBlockManager() const {
167638 return block_manager;
167639 }
167641 block_id_t BlockId() const {
167642 return block_id;
167643 }
167645 idx_t GetBlockAllocSize()
const {
167646 return block_alloc_size;
167647 }
167649 idx_t GetBlockHeaderSize()
const {
167650 return block_header_size;
167651 }
167655 idx_t GetBlockSize()
const {
167656 return block_alloc_size - block_header_size;
167657 }
167659 const BlockMemory &GetMemory() const {
167660 return memory;
167661 }
167663 BlockMemory &GetMemory() {
167664 return memory;
167665 }
167667 weak_ptr<BlockMemory> GetMemoryWeak() const {
167668 return weak_ptr<BlockMemory>(memory_p);
167669 }
167670
167671public:
167672 BufferHandle LoadFromBuffer(BlockLock &l, data_ptr_t data, unique_ptr<FileBuffer> reusable_buffer,
167673 BufferPoolReservation reservation);
167674 BufferHandle Load(QueryContext context, unique_ptr<FileBuffer> buffer = nullptr);
167675
167676private:
167678 BlockManager &block_manager;
167679
167684 idx_t block_alloc_size;
167686 idx_t block_header_size;
167688 const block_id_t block_id;
167689
167691 const shared_ptr<BlockMemory> memory_p;
167693 BlockMemory &memory;
167694};
167695
167696}
167697
167698
167699namespace duckdb {
167700
167701class CSVBufferHandle {
167702public:
167703 CSVBufferHandle(BufferHandle handle_p, idx_t actual_size_p, idx_t requested_size_p, const bool is_final_buffer_p,
167704 idx_t buffer_index_p)
167705 : handle(std::move(handle_p)), actual_size(actual_size_p), requested_size(requested_size_p),
167706 is_last_buffer(is_final_buffer_p), buffer_idx(buffer_index_p) {};
167707 CSVBufferHandle() : actual_size(0), requested_size(0), is_last_buffer(false), buffer_idx(0) {};
167708 ~CSVBufferHandle() {
167709 }
167711 BufferHandle handle;
167712 const idx_t actual_size;
167713 const idx_t requested_size;
167714 const bool is_last_buffer;
167715 const idx_t buffer_idx;
167716 inline char *
Ptr() {
167717 return char_ptr_cast(handle.Ptr());
167718 }
167719};
167720
167725class CSVBuffer {
167726public:
167728 CSVBuffer(ClientContext &context, idx_t buffer_size_p, CSVFileHandle &file_handle,
167729 const idx_t &global_csv_current_position);
167730
167732 CSVBuffer(CSVFileHandle &file_handle, ClientContext &context, idx_t buffer_size, idx_t global_csv_current_position,
167733 idx_t buffer_idx);
167734
167736 shared_ptr<CSVBuffer> Next(CSVFileHandle &file_handle, idx_t buffer_size, bool &has_seeked) const;
167737
167739 idx_t GetBufferSize()
const;
167740
167742 bool IsCSVFileLastBuffer() const;
167743
167745 void AllocateBuffer(idx_t buffer_size);
167746
167747 void Reload(CSVFileHandle &file_handle);
167750 shared_ptr<CSVBufferHandle> Pin(CSVFileHandle &file_handle, bool &has_seeked);
167752 void Unpin();
167754 return char_ptr_cast(handle.Ptr());
167755 }
167756 bool IsUnloaded() const {
167757 return block->GetMemory().IsUnloaded();
167758 }
167759
167761 static constexpr idx_t ROWS_PER_BUFFER = 16;
167762 static constexpr idx_t MIN_ROWS_PER_BUFFER = 4;
167763
167764 bool last_buffer = false;
167765
167766private:
167767 ClientContext &context;
167769 idx_t actual_buffer_size;
167770 idx_t requested_size;
167772 idx_t global_csv_start = 0;
167774 bool can_seek;
167776 bool is_pipe;
167778 idx_t buffer_idx = 0;
167781 shared_ptr<BlockHandle> block;
167782 BufferHandle handle;
167783};
167784}
167785
167786
167787
167788
167789
167790
167791
167792
167793
167794
167795
167796
167797
167798
167799
167800
167801
167802
167803
167804
167805
167806
167807
167808
167809#include <algorithm>
167810
167811namespace duckdb {
167812
167813enum class StrTimeSpecifier :
uint8_t {
167814 ABBREVIATED_WEEKDAY_NAME = 0,
167815 FULL_WEEKDAY_NAME = 1,
167816 WEEKDAY_DECIMAL = 2,
167817 DAY_OF_MONTH_PADDED = 3,
167818 DAY_OF_MONTH = 4,
167819 ABBREVIATED_MONTH_NAME = 5,
167820 FULL_MONTH_NAME = 6,
167821 MONTH_DECIMAL_PADDED = 7,
167822 MONTH_DECIMAL = 8,
167823 YEAR_WITHOUT_CENTURY_PADDED = 9,
167824 YEAR_WITHOUT_CENTURY = 10,
167825 YEAR_DECIMAL = 11,
167826 HOUR_24_PADDED = 12,
167827 HOUR_24_DECIMAL = 13,
167828 HOUR_12_PADDED = 14,
167829 HOUR_12_DECIMAL = 15,
167830 AM_PM = 16,
167831 MINUTE_PADDED = 17,
167832 MINUTE_DECIMAL = 18,
167833 SECOND_PADDED = 19,
167834 SECOND_DECIMAL = 20,
167835 MICROSECOND_PADDED = 21,
167836 MILLISECOND_PADDED = 22,
167837 UTC_OFFSET = 23,
167838 TZ_NAME = 24,
167839 DAY_OF_YEAR_PADDED = 25,
167840 DAY_OF_YEAR_DECIMAL = 26,
167841 WEEK_NUMBER_PADDED_SUN_FIRST =
167842 27,
167843
167844 WEEK_NUMBER_PADDED_MON_FIRST =
167845 28,
167846
167847 LOCALE_APPROPRIATE_DATE_AND_TIME =
167848 29,
167849 LOCALE_APPROPRIATE_DATE = 30,
167850 LOCALE_APPROPRIATE_TIME = 31,
167851 NANOSECOND_PADDED = 32,
167852
167853 YEAR_ISO =
167854 33,
167855 WEEKDAY_ISO = 34,
167856 WEEK_NUMBER_ISO = 35,
167857
167858};
167859
167860struct StrTimeFormat {
167861public:
167862 virtual ~StrTimeFormat() {
167863 }
167864
167865 DUCKDB_API
static string ParseFormatSpecifier(
const string &format_string, StrTimeFormat &
format);
167866
167867 inline bool HasFormatSpecifier(StrTimeSpecifier s) const {
167868 return std::find(specifiers.begin(), specifiers.end(), s) != specifiers.end();
167869 }
167871 DUCKDB_API bool Empty() const;
167872
167874 string format_specifier;
167875
167876protected:
167878 vector<StrTimeSpecifier> specifiers;
167882 vector<string> literals;
167884 idx_t constant_size = 0;
167886 vector<int> numeric_width;
167887
167888protected:
167889 void AddLiteral(string literal);
167890 DUCKDB_API virtual void AddFormatSpecifier(string preceding_literal, StrTimeSpecifier specifier);
167891};
167892
167893struct StrfTimeFormat : public StrTimeFormat {
167894 DUCKDB_API
idx_t GetLength(date_t date, dtime_t time, int32_t utc_offset,
const char *tz_name);
167895
167896 DUCKDB_API void FormatStringNS(date_t date, int32_t data[8], const char *tz_name, char *target) const;
167897 DUCKDB_API void FormatString(date_t date, int32_t data[8], const char *tz_name, char *target);
167898 void FormatString(date_t date, dtime_t time, char *target);
167899
167900 DUCKDB_API
static string Format(timestamp_t timestamp,
const string &
format);
167901
167902 DUCKDB_API void ConvertDateVector(Vector &input, Vector &result, idx_t count);
167903 DUCKDB_API void ConvertTimestampVector(Vector &input, Vector &result, idx_t count);
167904 DUCKDB_API void ConvertTimestampNSVector(Vector &input, Vector &result, idx_t count);
167905
167906protected:
167908 vector<StrTimeSpecifier> var_length_specifiers;
167911 vector<bool> is_date_specifier;
167912
167913protected:
167914 DUCKDB_API void AddFormatSpecifier(string preceding_literal, StrTimeSpecifier specifier) override;
167915 static idx_t GetSpecifierLength(StrTimeSpecifier specifier, date_t date, int32_t data[8],
const char *tz_name);
167916 idx_t GetLength(date_t date, int32_t data[8],
const char *tz_name)
const;
167917
167918 string_t ConvertTimestampValue(const timestamp_t &input, Vector &result) const;
167919 string_t ConvertTimestampValue(const timestamp_ns_t &input, Vector &result) const;
167920
167921 char *WriteString(char *target, const string_t &str) const;
167922 char *Write2(char *target, uint8_t value) const;
167923 char *WritePadded2(char *target, uint32_t value) const;
167924 char *WritePadded3(char *target, uint32_t value) const;
167925 char *WritePadded(char *target, uint32_t value, size_t padding) const;
167926 bool IsDateSpecifier(StrTimeSpecifier specifier);
167927 char *WriteDateSpecifier(StrTimeSpecifier specifier, date_t date, char *target) const;
167928 char *WriteStandardSpecifier(StrTimeSpecifier specifier, int32_t data[], const char *tz_name, size_t tz_len,
167929 char *target) const;
167930};
167931
167932struct StrpTimeFormat : public StrTimeFormat {
167933public:
167934 StrpTimeFormat();
167935
167937 struct ParseResult {
167939 string tz;
167940 string error_message;
167941 optional_idx error_position;
167942
167943 bool is_special;
167944 date_t special;
167945
167947
167948 date_t ToDate();
167949 dtime_t ToTime();
167951 timestamp_t ToTimestamp();
167952 timestamp_ns_t ToTimestampNS();
167953
167954 bool TryToDate(date_t &result);
167955 bool TryToTime(dtime_t &result);
167956 bool TryToTimestamp(timestamp_t &result);
167957 bool TryToTimestampNS(timestamp_ns_t &result);
167958
167959 DUCKDB_API string FormatError(string_t input, const string &format_specifier);
167960 };
167961
167962public:
167963 bool operator!=(
const StrpTimeFormat &other)
const {
167964 return format_specifier != other.format_specifier;
167965 }
167966 DUCKDB_API
static ParseResult Parse(
const string &
format,
const string &text);
167967 DUCKDB_API
static bool TryParse(
const string &
format,
const string &text, ParseResult &result);
167968
167969 DUCKDB_API bool Parse(string_t str, ParseResult &result, bool strict = false) const;
167970
167971 DUCKDB_API bool Parse(const char *data, size_t size, ParseResult &result, bool strict = false) const;
167972
167973 DUCKDB_API bool TryParseDate(const char *data, size_t size, date_t &result) const;
167974 DUCKDB_API bool TryParseTimestamp(const char *data, size_t size, timestamp_t &result) const;
167975 DUCKDB_API bool TryParseTimestampNS(const char *data, size_t size, timestamp_ns_t &result) const;
167976
167977 DUCKDB_API bool TryParseDate(string_t str, date_t &result, string &error_message) const;
167978 DUCKDB_API bool TryParseTime(string_t str, dtime_t &result, string &error_message) const;
167979 DUCKDB_API bool TryParseTimestamp(string_t str, timestamp_t &result, string &error_message) const;
167980 DUCKDB_API bool TryParseTimestampNS(string_t str, timestamp_ns_t &result, string &error_message) const;
167981
167982 void Serialize(Serializer &serializer) const;
167983 static StrpTimeFormat Deserialize(Deserializer &deserializer);
167984
167985protected:
167986 static string FormatStrpTimeError(const string &input, optional_idx position);
167987 DUCKDB_API void AddFormatSpecifier(string preceding_literal, StrTimeSpecifier specifier) override;
167988 int NumericSpecifierWidth(StrTimeSpecifier specifier);
167989 int32_t TryParseCollection(
const char *data, idx_t &pos, idx_t size,
const string_t collection[],
167990 idx_t collection_count) const;
167991
167992private:
167993 explicit StrpTimeFormat(const string &format_string);
167994};
167995
167996}
167997
167998
167999namespace duckdb {
168000
168001enum class NewLineIdentifier :
uint8_t {
168002 SINGLE_N = 1,
168003 CARRY_ON = 2,
168005 SINGLE_R = 4
168006
168007};
168008
168009class Serializer;
168010class Deserializer;
168011
168014template <typename T>
168015struct CSVOption {
168016public:
168017 CSVOption(T value_p) : value(value_p) {
168018 }
168019 CSVOption(T value_p, bool set_by_user_p) : set_by_user(set_by_user_p), value(value_p) {
168020 }
168021
168022 CSVOption() {};
168023
168026 void Set(T value_p, bool by_user = true) {
168027 D_ASSERT(!(by_user && set_by_user));
168028 if (!set_by_user) {
168029
168030 value = value_p;
168031 set_by_user = by_user;
168032 }
168033 }
168034
168037 void Set(CSVOption value_p, bool by_user = true) {
168038 D_ASSERT(!(by_user && set_by_user));
168039 if (!set_by_user) {
168040
168041 value = value_p;
168042 set_by_user = by_user;
168043 }
168044 }
168045
168046
168047 void ChangeSetByUserTrue() {
168048 set_by_user = true;
168049 }
168050
168051 bool operator==(
const CSVOption &other)
const {
168052 return value == other.value;
168053 }
168054
168055 bool operator!=(
const CSVOption &other)
const {
168056 return value != other.value;
168057 }
168058
168060 return value == other;
168061 }
168062
168064 return value != other;
168065 }
168067 inline const T &GetValue() const {
168068 return value;
168069 }
168070 bool IsSetByUser() const {
168071 return set_by_user;
168072 }
168073
168075 string FormatSet() const {
168076 if (set_by_user) {
168077 return "(Set By User)";
168078 }
168079 return "(Auto-Detected)";
168080 }
168081
168083 string FormatValue() const {
168084 return FormatValueInternal(value);
168085 }
168086
168088 DUCKDB_API void Serialize(Serializer &serializer) const;
168089
168091 DUCKDB_API static CSVOption<T> Deserialize(Deserializer &deserializer);
168092
168093private:
168095 bool set_by_user = false;
168096 T value;
168097
168101
168102 template <typename U>
168103 std::string FormatValueInternal(const U &val) const {
168104 throw InternalException("Type not accepted as CSV Option.");
168105 }
168106
168107 std::string FormatValueInternal(const std::string &val) const {
168108 return val;
168109 }
168110
168111 std::string FormatValueInternal(const idx_t &val) const {
168113 }
168114
168115 std::string FormatValueInternal(const char &val) const {
168116 string char_val;
168117 if (val == '\0') {
168118 char_val = "(empty)";
168119 return char_val;
168120 }
168121 char_val += val;
168122 return char_val;
168123 }
168124
168125 std::string FormatValueInternal(const NewLineIdentifier &val) const {
168126 switch (val) {
168127 case NewLineIdentifier::SINGLE_N:
168128 return "\\n";
168129 case NewLineIdentifier::SINGLE_R:
168130 return "\\r";
168131 case NewLineIdentifier::CARRY_ON:
168132 return "\\r\\n";
168133 case NewLineIdentifier::NOT_SET:
168134 return "Single-Line File";
168135 default:
168136 throw InternalException("Invalid Newline Detected.");
168137 }
168138 }
168139
168140 std::string FormatValueInternal(const StrpTimeFormat &val) const {
168141 return val.format_specifier;
168142 }
168143
168144 std::string FormatValueInternal(const bool &val) const {
168145 if (val) {
168146 return "true";
168147 }
168148 return "false";
168149 }
168150};
168151
168152}
168153
168154
168155
168156
168157
168158
168159
168160
168161
168162
168163
168164
168165
168166namespace duckdb {
168169struct CSVStateMachineOptions {
168170 CSVStateMachineOptions() {};
168171 CSVStateMachineOptions(string delimiter_p, char quote_p, char escape_p, char comment_p,
168172 NewLineIdentifier new_line_p, bool strict_mode_p)
168173 : delimiter(std::move(delimiter_p)), quote(quote_p), escape(escape_p), comment(comment_p), new_line(new_line_p),
168174 strict_mode(strict_mode_p) {};
168175
168177 CSVOption<string> delimiter {","};
168179 CSVOption<char> quote = '\"';
168181 CSVOption<char> escape = '\0';
168183 CSVOption<char> comment = '\0';
168185 CSVOption<NewLineIdentifier> new_line = NewLineIdentifier::NOT_SET;
168187 CSVOption<bool> strict_mode = true;
168188
168189 bool operator==(
const CSVStateMachineOptions &other)
const {
168190 return delimiter == other.delimiter && quote == other.quote && escape == other.escape &&
168191 new_line == other.new_line && comment == other.comment && strict_mode == other.strict_mode;
168192 }
168193};
168194}
168195
168196
168197
168198
168199
168200
168201
168202
168203
168204
168205
168206
168207
168208
168209
168210
168211
168212
168213
168214
168215
168216
168217
168218
168219
168220
168221
168222
168223
168224
168225
168226
168227
168228
168229
168230
168231
168232
168233
168234
168235
168236
168237
168238
168239
168240
168241
168242
168243
168244
168245
168246
168247
168248
168249
168250
168251
168252
168253
168254
168255
168256namespace duckdb {
168257
168258struct PerfectHash {
168259 std::size_t
operator()(
const idx_t &h)
const {
168260 return h;
168261 }
168262};
168263
168264struct PerfectEquality {
168265 bool operator()(
const idx_t &a,
const idx_t &b)
const {
168266 return a == b;
168267 }
168268};
168269
168270template <typename T>
168271using perfect_map_t = unordered_map<idx_t, T, PerfectHash, PerfectEquality>;
168272
168273using perfect_set_t = unordered_set<idx_t, PerfectHash, PerfectEquality>;
168274
168275}
168276
168277
168278
168279namespace duckdb {
168280
168281template <class T, bool is_const>
168282class fixed_size_map_iterator;
168283
168285template <class T>
168286class fixed_size_map_t {
168287 friend class fixed_size_map_iterator<T, false>;
168288 friend class fixed_size_map_iterator<T, true>;
168289
168290public:
168291 using key_type =
idx_t;
168292 using mapped_type = T;
168293 using occupied_mask = TemplatedValidityMask<uint8_t>;
168294 using iterator = fixed_size_map_iterator<mapped_type, false>;
168295 using const_iterator = fixed_size_map_iterator<mapped_type, true>;
168296
168297public:
168298 explicit fixed_size_map_t(idx_t capacity_p = 0) : capacity(capacity_p) {
168300 }
168301
168303 return count;
168304 }
168305
168306 void resize(idx_t capacity_p) {
168307 capacity = capacity_p;
168308 occupied = occupied_mask(capacity);
168309 values = make_unsafe_uniq_array_uninitialized<mapped_type>(capacity + 1);
168310 clear();
168311 }
168312
168313 void clear() {
168314 count = 0;
168315 occupied.SetAllInvalid(capacity);
168316 }
168317
168318 mapped_type &operator[](const key_type &key) {
168319 D_ASSERT(key < capacity);
168320 count += 1 - occupied.RowIsValidUnsafe(key);
168321 occupied.SetValidUnsafe(key);
168322 return values[key];
168323 }
168324
168325 const mapped_type &operator[](const key_type &key) const {
168326 D_ASSERT(key < capacity);
168327 return values[key];
168328 }
168329
168330 iterator begin() {
168331 iterator result(*this, 0);
168332 if (!occupied_mask::RowIsValid(occupied.GetValidityEntryUnsafe(0), 0)) {
168333 ++result;
168334 }
168335 return result;
168336 }
168337
168338 const_iterator begin() const {
168339 const_iterator result(*this, 0);
168340 if (!occupied_mask::RowIsValid(occupied.GetValidityEntryUnsafe(0), 0)) {
168341 ++result;
168342 }
168343 return result;
168344 }
168345
168346 iterator end() {
168347 return iterator(*this, capacity);
168348 }
168349
168350 const_iterator end() const {
168351 return const_iterator(*this, capacity);
168352 }
168353
168354 iterator find(const key_type &index) {
168355 return occupied.RowIsValidUnsafe(index) ? iterator(*this, index) : end();
168356 }
168357
168358 const_iterator find(const key_type &index) const {
168359 return occupied.RowIsValidUnsafe(index) ? const_iterator(*this, index) : end();
168360 }
168361
168362private:
168365
168366 occupied_mask occupied;
168367 unsafe_unique_array<mapped_type> values;
168368};
168369
168370template <class T, bool is_const>
168371class fixed_size_map_iterator {
168372public:
168373 using key_type =
idx_t;
168374 using mapped_type = T;
168375 using fixed_size_map_type = fixed_size_map_t<mapped_type>;
168376 using map_type = typename std::conditional<is_const, const fixed_size_map_type, fixed_size_map_type>::type;
168377 using occupied_mask = typename fixed_size_map_t<mapped_type>::occupied_mask;
168378
168379public:
168380 fixed_size_map_iterator(map_type &map_p, key_type index) : map(map_p) {
168381 occupied_mask::GetEntryIndex(index, entry_idx, idx_in_entry);
168382 }
168383
168384 fixed_size_map_iterator &operator++() {
168385
168386 if (++idx_in_entry == occupied_mask::BITS_PER_VALUE) {
168387 NextEntry();
168388 }
168389
168390 auto end = map.end();
168391 while (*this < end) {
168392 const auto &entry = map.occupied.GetValidityEntryUnsafe(entry_idx);
168393 if (entry ==
static_cast<uint8_t>(~occupied_mask::ValidityBuffer::MAX_ENTRY)) {
168394
168395 if (entry_idx == end.entry_idx) {
168396
168397 idx_in_entry = end.idx_in_entry;
168398 break;
168399 }
168400 NextEntry();
168401 } else {
168402
168403 const auto idx_to = entry_idx == end.entry_idx ? end.idx_in_entry : occupied_mask::BITS_PER_VALUE;
168404 for (; idx_in_entry < idx_to; idx_in_entry++) {
168405 if (map.occupied.RowIsValid(entry, idx_in_entry)) {
168406
168407 return *this;
168408 }
168409 }
168410
168411 if (*this != end) {
168412 NextEntry();
168413 }
168414 }
168415 }
168416 return *this;
168417 }
168418
168419 fixed_size_map_iterator operator++(int) {
168420 fixed_size_map_iterator tmp = *this;
168421 ++(*this);
168422 return tmp;
168423 }
168424
168425 key_type GetKey() const {
168426 return entry_idx * occupied_mask::BITS_PER_VALUE + idx_in_entry;
168427 }
168428
168429 mapped_type &GetValue() {
168430 return map.values[GetKey()];
168431 }
168432
168433 const mapped_type &GetValue() const {
168434 return map.values[GetKey()];
168435 }
168436
168437 friend bool operator==(
const fixed_size_map_iterator &a,
const fixed_size_map_iterator &b) {
168438 return a.entry_idx == b.entry_idx && a.idx_in_entry == b.idx_in_entry;
168439 }
168440
168441 friend bool operator!=(
const fixed_size_map_iterator &a,
const fixed_size_map_iterator &b) {
168442 return !(a == b);
168443 }
168444
168445 friend bool operator<(
const fixed_size_map_iterator &a,
const fixed_size_map_iterator &b) {
168446 if (a.entry_idx < b.entry_idx) {
168447 return true;
168448 }
168449 if (a.entry_idx == b.entry_idx) {
168450 return a.idx_in_entry < b.idx_in_entry;
168451 }
168452 return false;
168453 }
168454
168455private:
168456 void NextEntry() {
168457 entry_idx++;
168458 idx_in_entry = 0;
168459 }
168460
168461private:
168462 map_type ↦
168464 idx_t idx_in_entry;
168465};
168466
168468
168469
168470template <class T, bool fixed>
168471struct TemplatedMapGetter {
168472private:
168473 using key_type =
idx_t;
168474 using mapped_type = T;
168475 using fixed_size_map_type = fixed_size_map_t<mapped_type>;
168476 using perfect_map_type = perfect_map_t<mapped_type>;
168477 using map_type = typename std::conditional<fixed, fixed_size_map_type, perfect_map_type>::type;
168478 using iterator = typename map_type::iterator;
168479 using const_iterator = typename map_type::const_iterator;
168480
168481public:
168482 static key_type GetKey(const iterator &it) {
168483 return GetKeyInternal(it);
168484 }
168485
168486 static key_type GetKey(const const_iterator &it) {
168487 return GetKeyInternal(it);
168488 }
168489
168490 static mapped_type &GetValue(iterator &it) {
168491 return GetValueInternal(it);
168492 }
168493
168494 static const mapped_type &GetValue(const const_iterator &it) {
168495 return GetValueInternal(it);
168496 }
168497
168498private:
168499
168500
168501
168502
168503 static key_type GetKeyInternal(const typename perfect_map_type::iterator &it) {
168504 return it->first;
168505 }
168506
168507 static key_type GetKeyInternal(const typename perfect_map_type::const_iterator &it) {
168508 return it->first;
168509 }
168510
168511 static mapped_type &GetValueInternal(typename perfect_map_type::iterator &it) {
168512 return it->second;
168513 }
168514
168515 static const mapped_type &GetValueInternal(const typename perfect_map_type::const_iterator &it) {
168516 return it->second;
168517 }
168518
168519 static key_type GetKeyInternal(const typename fixed_size_map_type::iterator &it) {
168520 return it.GetKey();
168521 }
168522
168523 static key_type GetKeyInternal(const typename fixed_size_map_type::const_iterator &it) {
168524 return it.GetKey();
168525 }
168526
168527 static mapped_type &GetValueInternal(typename fixed_size_map_type::iterator &it) {
168528 return it.GetValue();
168529 }
168530
168531 static const mapped_type &GetValueInternal(const typename fixed_size_map_type::const_iterator &it) {
168532 return it.GetValue();
168533 }
168534};
168535
168536
168537}
168538
168539
168540
168541
168542
168543
168544
168545
168546
168547
168548
168549
168550
168551
168552
168553
168554
168555
168556
168557
168558
168559
168560
168561
168562
168563
168564
168565
168566
168567namespace duckdb {
168568
168569class DatabaseInstance;
168570class ClientContext;
168571class BlockHandle;
168572class ColumnDataAllocator;
168573
168574class ManagedResultSet : public enable_shared_from_this<ManagedResultSet> {
168575public:
168576 ManagedResultSet();
168577 ManagedResultSet(const weak_ptr<DatabaseInstance> &db, vector<shared_ptr<BlockHandle>> &handles);
168578
168579public:
168580 bool IsValid() const;
168581 shared_ptr<DatabaseInstance> GetDatabase() const;
168582 vector<shared_ptr<BlockHandle>> &GetHandles();
168583
168584private:
168585 bool valid;
168586 weak_ptr<DatabaseInstance>
db;
168587 optional_ptr<vector<shared_ptr<BlockHandle>>> handles;
168588};
168589
168590class ResultSetManager {
168591public:
168592 explicit ResultSetManager(DatabaseInstance &db);
168593
168594public:
168595 static ResultSetManager &Get(ClientContext &context);
168596 static ResultSetManager &Get(DatabaseInstance &db);
168597 ManagedResultSet Add(ColumnDataAllocator &allocator);
168598 void Remove(ColumnDataAllocator &allocator);
168599
168600private:
168601 mutex lock;
168602 weak_ptr<DatabaseInstance>
db;
168603 reference_map_t<ColumnDataAllocator, unique_ptr<vector<shared_ptr<BlockHandle>>>> open_results;
168604};
168605
168606}
168607
168608
168609namespace duckdb {
168610
168611struct ChunkMetaData;
168612struct VectorMetaData;
168613struct SwizzleMetaData;
168614
168615struct BlockMetaData {
168616public:
168621
168622private:
168624 shared_ptr<BlockHandle> handle;
168626 weak_ptr<BlockHandle> weak_handle;
168627
168628public:
168629 shared_ptr<BlockHandle> GetHandle() const;
168630 void SetHandle(ManagedResultSet &managed_result_set, shared_ptr<BlockHandle> handle);
168632};
168633
168634class ColumnDataAllocator {
168635public:
168636 explicit ColumnDataAllocator(Allocator &allocator);
168637 explicit ColumnDataAllocator(BufferManager &buffer_manager,
168638 ColumnDataCollectionLifetime lifetime = ColumnDataCollectionLifetime::REGULAR);
168639 ColumnDataAllocator(ClientContext &context, ColumnDataAllocatorType allocator_type,
168640 ColumnDataCollectionLifetime lifetime = ColumnDataCollectionLifetime::REGULAR);
168641 ColumnDataAllocator(ColumnDataAllocator &allocator);
168642 ~ColumnDataAllocator();
168643
168646 Allocator &GetAllocator();
168648 BufferManager &GetBufferManager();
168651 return type;
168652 }
168653 void MakeShared() {
168654 shared = true;
168655 }
168656 bool IsShared() const {
168657 return shared;
168658 }
168659 idx_t BlockCount()
const {
168660 return blocks.size();
168661 }
168662 idx_t SizeInBytes()
const {
168663 idx_t total_size = 0;
168664 for (const auto &block : blocks) {
168665 total_size += block.size;
168666 }
168667 return total_size;
168668 }
168669 idx_t AllocationSize()
const {
168670 return allocated_size;
168671 }
168673 void SetPartitionIndex(idx_t index) {
168674 D_ASSERT(!partition_index.IsValid());
168675 D_ASSERT(blocks.empty() && allocated_data.empty());
168676 partition_index =
index;
168677 }
168678
168679public:
168680 void AllocateData(idx_t size, uint32_t &block_id, uint32_t &offset, ChunkManagementState *chunk_state);
168681
168682 void Initialize(ColumnDataAllocator &other);
168683 void InitializeChunkState(ChunkManagementState &state, ChunkMetaData &meta_data);
168684 data_ptr_t GetDataPointer(ChunkManagementState &state, uint32_t block_id, uint32_t offset);
168685 void UnswizzlePointers(ChunkManagementState &state, Vector &result, SwizzleMetaData &swizzle_segment,
168686 const VectorMetaData &string_heap_segment, const idx_t &v_offset, const bool &copied);
168687
168689 void SetDestroyBufferUponUnpin(uint32_t block_id);
168691 shared_ptr<DatabaseInstance> GetDatabase() const;
168692
168693private:
168694 void AllocateEmptyBlock(idx_t size);
168695 BufferHandle AllocateBlock(idx_t size);
168696 BufferHandle Pin(uint32_t block_id);
168697
168698 bool HasBlocks() const {
168699 return !blocks.empty();
168700 }
168701
168702private:
168703 void AllocateBuffer(idx_t size, uint32_t &block_id, uint32_t &offset, ChunkManagementState *chunk_state);
168704 void AllocateMemory(idx_t size, uint32_t &block_id, uint32_t &offset, ChunkManagementState *chunk_state);
168705 void AssignPointer(uint32_t &block_id, uint32_t &offset, data_ptr_t pointer);
168706
168707private:
168709 union {
168711 Allocator *allocator;
168713 BufferManager *buffer_manager;
168714 } alloc;
168716 vector<BlockMetaData> blocks;
168718 vector<AllocatedData> allocated_data;
168720 bool shared = false;
168722 mutex lock;
168724 idx_t allocated_size = 0;
168726 optional_idx partition_index;
168728 ManagedResultSet managed_result_set;
168729};
168730
168731}
168732
168733
168734
168735namespace duckdb {
168736
168738struct PartitionedColumnDataAppendState {
168739public:
168740 PartitionedColumnDataAppendState() : partition_indices(LogicalType::UBIGINT) {
168741 }
168742
168743public:
168744 Vector partition_indices;
168745 SelectionVector partition_sel;
168746
168747 static constexpr idx_t MAP_THRESHOLD = 256;
168748 perfect_map_t<list_entry_t> partition_entries;
168749 fixed_size_map_t<list_entry_t> fixed_partition_entries;
168750
168751 DataChunk slice_chunk;
168752
168753 vector<unique_ptr<DataChunk>> partition_buffers;
168754 vector<unique_ptr<ColumnDataAppendState>> partition_append_states;
168755
168756public:
168757 template <bool fixed>
168758 typename std::conditional<fixed, fixed_size_map_t<list_entry_t>, perfect_map_t<list_entry_t>>::type &GetMap() {
168759 throw NotImplementedException("PartitionedColumnDataAppendState::GetMap for boolean value");
168760 }
168761
168762 optional_idx GetPartitionIndexIfSinglePartition(const bool use_fixed_size_map) {
168763 optional_idx result;
168764 if (use_fixed_size_map) {
168765 if (fixed_partition_entries.size() == 1) {
168766 result = fixed_partition_entries.begin().GetKey();
168767 }
168768 } else {
168769 if (partition_entries.size() == 1) {
168770 result = partition_entries.begin()->first;
168771 }
168772 }
168773 return result;
168774 }
168775};
168776
168777template <>
168778inline perfect_map_t<list_entry_t> &PartitionedColumnDataAppendState::GetMap<false>() {
168779 return partition_entries;
168780}
168781
168782template <>
168783inline fixed_size_map_t<list_entry_t> &PartitionedColumnDataAppendState::GetMap<true>() {
168784 return fixed_partition_entries;
168785}
168786
168788 INVALID,
168793};
168794
168796struct PartitionColumnDataAllocators {
168797 mutex lock;
168798 vector<shared_ptr<ColumnDataAllocator>> allocators;
168799};
168800
168803class PartitionedColumnData {
168804public:
168805 unique_ptr<PartitionedColumnData> CreateShared();
168806 virtual ~PartitionedColumnData();
168807
168808public:
168810 void InitializeAppendState(PartitionedColumnDataAppendState &state) const;
168812 void Append(PartitionedColumnDataAppendState &state, DataChunk &input);
168814 void FlushAppendState(PartitionedColumnDataAppendState &state);
168816 void Combine(PartitionedColumnData &other);
168818 vector<unique_ptr<ColumnDataCollection>> &GetPartitions();
168819
168820protected:
168821
168822
168823
168825 virtual idx_t BufferSize()
const {
168826 return MinValue<idx_t>(128, STANDARD_VECTOR_SIZE);
168827 }
168829 virtual void InitializeAppendStateInternal(PartitionedColumnDataAppendState &state) const {
168830 }
168834 virtual void ComputePartitionIndices(PartitionedColumnDataAppendState &state, DataChunk &input) {
168835 throw NotImplementedException("ComputePartitionIndices for this type of PartitionedColumnData");
168836 }
168838
168840 virtual idx_t MaxPartitionIndex()
const {
168841 return DConstants::INVALID_INDEX;
168842 }
168843
168844protected:
168846 PartitionedColumnData(PartitionedColumnDataType type, ClientContext &context, vector<LogicalType> types);
168847 PartitionedColumnData(const PartitionedColumnData &other);
168848
168850 inline idx_t HalfBufferSize()
const {
168851 D_ASSERT(IsPowerOfTwo(BufferSize()));
168852 return BufferSize() / 2;
168853 }
168855 void CreateAllocator();
168857 bool UseFixedSizeMap() const;
168860 void BuildPartitionSel(PartitionedColumnDataAppendState &state, const idx_t append_count) const;
168861 template <bool fixed>
168862 static void BuildPartitionSel(PartitionedColumnDataAppendState &state, const idx_t append_count);
168864 template <bool fixed>
168865 void AppendInternal(PartitionedColumnDataAppendState &state, DataChunk &input);
168867 unique_ptr<ColumnDataCollection> CreatePartitionCollection(idx_t partition_index) const {
168868 return make_uniq<ColumnDataCollection>(allocators->allocators[partition_index], types);
168869 }
168871 unique_ptr<DataChunk> CreatePartitionBuffer() const;
168872
168873protected:
168875 ClientContext &context;
168876 vector<LogicalType> types;
168877
168878 mutex lock;
168879 shared_ptr<PartitionColumnDataAllocators> allocators;
168880 vector<unique_ptr<ColumnDataCollection>> partitions;
168881
168882public:
168883 template <class TARGET>
168884 TARGET &Cast() {
168885 DynamicCastCheck<TARGET>(this);
168886 return reinterpret_cast<TARGET &>(*this);
168887 }
168888 template <class TARGET>
168889 const TARGET &Cast() const {
168890 DynamicCastCheck<TARGET>(this);
168891 return reinterpret_cast<const TARGET &>(*this);
168892 }
168893};
168894
168895}
168896
168897
168898
168899
168900
168901
168902
168903
168904
168905
168906
168907
168908
168909
168910
168911
168912
168913
168914
168915
168916
168917
168918
168919
168920
168921
168922
168923
168924namespace duckdb {
168925
168926enum class DebugVectorVerification :
uint8_t {
168927 NONE,
168928 DICTIONARY_EXPRESSION,
168929 DICTIONARY_OPERATOR,
168930 CONSTANT_OPERATOR,
168931 SEQUENCE_OPERATOR,
168932 NESTED_SHUFFLE,
168933 VARIANT_VECTOR
168934};
168935
168936}
168937
168938
168939namespace duckdb {
168940class Allocator;
168941class ExecutionContext;
168942
168944class ExpressionExecutor {
168945 friend class BoundIndex;
168946
168947public:
168948 DUCKDB_API explicit ExpressionExecutor(ClientContext &context);
168949 DUCKDB_API ExpressionExecutor(ClientContext &context, const Expression *expression);
168950 DUCKDB_API ExpressionExecutor(ClientContext &context, const Expression &expression);
168951 DUCKDB_API ExpressionExecutor(ClientContext &context, const vector<unique_ptr<Expression>> &expressions);
168952 ExpressionExecutor(ExpressionExecutor &&) = delete;
168953
168955 vector<const Expression *> expressions;
168958 DataChunk *chunk = nullptr;
168959
168960public:
168961 bool HasContext();
168962 ClientContext &GetContext();
168963 Allocator &GetAllocator();
168964
168966 DUCKDB_API void AddExpression(const Expression &expr);
168967 void ClearExpressions();
168968
168970 DUCKDB_API void Execute(DataChunk *input, DataChunk &result);
168971 inline void Execute(DataChunk &input, DataChunk &result) {
168972 Execute(&input, result);
168973 }
168974 inline void Execute(DataChunk &result) {
168975 Execute(nullptr, result);
168976 }
168977
168980 DUCKDB_API void ExecuteExpression(DataChunk &input, Vector &result);
168983 DUCKDB_API void ExecuteExpression(Vector &result);
168986 DUCKDB_API
idx_t SelectExpression(DataChunk &input, SelectionVector &sel);
168987
168988 DUCKDB_API
idx_t SelectExpression(DataChunk &input, SelectionVector &result_sel,
168989 optional_ptr<SelectionVector> current_sel, idx_t current_count);
168990
168991 DUCKDB_API
idx_t SelectExpression(DataChunk &input, optional_ptr<SelectionVector> true_sel,
168992 optional_ptr<SelectionVector> false_sel,
168993 optional_ptr<SelectionVector> current_sel, idx_t current_count);
168994
168996 DUCKDB_API void ExecuteExpression(idx_t expr_idx, Vector &result);
168998 DUCKDB_API static Value EvaluateScalar(ClientContext &context, const Expression &expr,
168999 bool allow_unfoldable = false);
169001 DUCKDB_API static bool TryEvaluateScalar(ClientContext &context, const Expression &expr, Value &result);
169002
169004 static unique_ptr<ExpressionState> InitializeState(const Expression &expr, ExpressionExecutorState &state);
169005
169006 inline void SetChunk(DataChunk *chunk) {
169007 this->chunk = chunk;
169008 }
169009 inline void SetChunk(DataChunk &chunk) {
169010 SetChunk(&chunk);
169011 }
169012
169013 DUCKDB_API vector<unique_ptr<ExpressionExecutorState>> &GetStates();
169014
169015protected:
169016 void Initialize(const Expression &expr, ExpressionExecutorState &state);
169017
169018 static unique_ptr<ExpressionState> InitializeState(const BoundReferenceExpression &expr,
169019 ExpressionExecutorState &state);
169020 static unique_ptr<ExpressionState> InitializeState(const BoundBetweenExpression &expr,
169021 ExpressionExecutorState &state);
169022 static unique_ptr<ExpressionState> InitializeState(const BoundCaseExpression &expr, ExpressionExecutorState &state);
169023 static unique_ptr<ExpressionState> InitializeState(const BoundCastExpression &expr, ExpressionExecutorState &state);
169024 static unique_ptr<ExpressionState> InitializeState(const BoundComparisonExpression &expr,
169025 ExpressionExecutorState &state);
169026 static unique_ptr<ExpressionState> InitializeState(const BoundConjunctionExpression &expr,
169027 ExpressionExecutorState &state);
169028 static unique_ptr<ExpressionState> InitializeState(const BoundConstantExpression &expr,
169029 ExpressionExecutorState &state);
169030 static unique_ptr<ExpressionState> InitializeState(const BoundFunctionExpression &expr,
169031 ExpressionExecutorState &state);
169032 static unique_ptr<ExpressionState> InitializeState(const BoundOperatorExpression &expr,
169033 ExpressionExecutorState &state);
169034 static unique_ptr<ExpressionState> InitializeState(const BoundParameterExpression &expr,
169035 ExpressionExecutorState &state);
169036
169037 void Execute(const Expression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
169038 Vector &result);
169039
169040 void Execute(const BoundBetweenExpression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
169041 Vector &result);
169042 void Execute(const BoundCaseExpression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
169043 Vector &result);
169044 void Execute(const BoundCastExpression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
169045 Vector &result);
169046
169047 void Execute(const BoundComparisonExpression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
169048 Vector &result);
169049 void Execute(const BoundConjunctionExpression &expr, ExpressionState *state, const SelectionVector *sel,
169050 idx_t count, Vector &result);
169051 void Execute(const BoundConstantExpression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
169052 Vector &result);
169053 void Execute(const BoundFunctionExpression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
169054 Vector &result);
169055 void Execute(const BoundOperatorExpression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
169056 Vector &result);
169057 void Execute(const BoundParameterExpression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
169058 Vector &result);
169059 void Execute(const BoundReferenceExpression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
169060 Vector &result);
169061
169064 idx_t Select(
const Expression &expr, ExpressionState *state,
const SelectionVector *sel, idx_t count,
169065 SelectionVector *true_sel, SelectionVector *false_sel);
169066 idx_t DefaultSelect(
const Expression &expr, ExpressionState *state,
const SelectionVector *sel, idx_t count,
169067 SelectionVector *true_sel, SelectionVector *false_sel);
169068
169069 idx_t Select(
const BoundBetweenExpression &expr, ExpressionState *state,
const SelectionVector *sel, idx_t count,
169070 SelectionVector *true_sel, SelectionVector *false_sel);
169071 idx_t Select(
const BoundComparisonExpression &expr, ExpressionState *state,
const SelectionVector *sel, idx_t count,
169072 SelectionVector *true_sel, SelectionVector *false_sel);
169073 idx_t Select(
const BoundConjunctionExpression &expr, ExpressionState *state,
const SelectionVector *sel,
169074 idx_t count, SelectionVector *true_sel, SelectionVector *false_sel);
169075
169077 void Verify(const Expression &expr, Vector &result, idx_t count);
169078
169079 void FillSwitch(Vector &vector, Vector &result, const SelectionVector &sel, sel_t count);
169080
169081private:
169083 optional_ptr<ClientContext> context;
169085 vector<unique_ptr<ExpressionExecutorState>> states;
169087 DebugVectorVerification debug_vector_verification = DebugVectorVerification::NONE;
169088
169089private:
169090
169091 DUCKDB_API ExpressionExecutor();
169092 DUCKDB_API explicit ExpressionExecutor(const vector<unique_ptr<Expression>> &exprs);
169093};
169094}
169095
169096
169097
169098
169099
169100
169101
169102
169103
169104
169105
169106
169107
169108
169109
169110
169111
169112
169113
169114
169115
169116
169117
169118
169119
169120
169121
169122
169123
169124
169125namespace duckdb {
169126
169127class ConstantFilter : public TableFilter {
169128public:
169129 static constexpr const TableFilterType
TYPE = TableFilterType::CONSTANT_COMPARISON;
169130
169131public:
169132 ConstantFilter(ExpressionType comparison_type, Value constant);
169133
169135 ExpressionType comparison_type;
169137 Value constant;
169138
169139public:
169140 bool Compare(const Value &value) const;
169141 FilterPropagateResult CheckStatistics(BaseStatistics &stats) const override;
169142 string ToString(const string &column_name) const override;
169143 bool Equals(const TableFilter &other) const override;
169144 unique_ptr<TableFilter> Copy() const override;
169145 unique_ptr<Expression> ToExpression(const Expression &column) const override;
169146 void Serialize(Serializer &serializer) const override;
169147 static unique_ptr<TableFilter> Deserialize(Deserializer &deserializer);
169148};
169149
169150}
169151
169152
169153
169154
169155
169156
169157
169158
169159
169160
169161
169162
169163
169164
169165
169166
169167
169168
169169
169170
169171
169172
169173
169174
169175namespace duckdb {
169176
169177
169178
169179
169180enum class IndexConstraintType :
uint8_t {
169181 NONE = 0,
169182 UNIQUE = 1,
169183 PRIMARY = 2,
169184 FOREIGN = 3
169185};
169186
169187
169188
169189
169190
169191enum class DeprecatedIndexType :
uint8_t {
169192 INVALID = 0,
169193 ART = 1,
169194 EXTENSION = 100
169195};
169196
169197}
169198
169199
169200
169201
169202
169203
169204
169205
169206
169207
169208
169209
169210
169211
169212
169213
169214
169215
169216
169217namespace duckdb {
169218
169219class Index;
169220
169222class ConflictInfo {
169223public:
169224 explicit ConflictInfo(const unordered_set<column_t> &column_ids, bool only_check_unique = true)
169225 : column_ids(column_ids), only_check_unique(only_check_unique) {
169226 }
169227
169228 const unordered_set<column_t> &column_ids;
169229 bool only_check_unique = true;
169230
169231public:
169232 bool ConflictTargetMatches(Index &index) const;
169234 bool SingleIndexTarget() const {
169235 return !column_ids.empty();
169236 }
169237};
169238
169239}
169240
169241
169242
169243
169244
169245
169246
169247
169248
169249
169250
169251
169252
169253
169254
169255
169256
169257
169258
169259
169260
169261
169262
169263
169264
169265
169266
169267namespace duckdb {
169268
169270struct FixedSizeAllocatorInfo {
169271 idx_t segment_size;
169272 vector<idx_t> buffer_ids;
169273 vector<BlockPointer> block_pointers;
169274 vector<idx_t> segment_counts;
169275 vector<idx_t> allocation_sizes;
169276 vector<idx_t> buffers_with_free_space;
169277
169278 void Serialize(Serializer &serializer) const;
169279 static FixedSizeAllocatorInfo Deserialize(Deserializer &deserializer);
169280};
169281
169283struct IndexBufferInfo {
169284 IndexBufferInfo(data_ptr_t buffer_ptr, const idx_t allocation_size)
169286 }
169287
169289 idx_t allocation_size;
169290};
169291
169293struct IndexStorageInfo {
169294 IndexStorageInfo() {};
169295 explicit IndexStorageInfo(const string &name) : name(name) {};
169296
169298 IndexStorageInfo(const IndexStorageInfo &) = delete;
169299 IndexStorageInfo &
operator=(
const IndexStorageInfo &) =
delete;
169300
169301 IndexStorageInfo(IndexStorageInfo &&) = default;
169302 IndexStorageInfo &
operator=(IndexStorageInfo &&) =
default;
169303
169305 string name;
169309 case_insensitive_map_t<Value> options;
169311 vector<FixedSizeAllocatorInfo> allocator_infos;
169312
169316 vector<vector<IndexBufferInfo>> buffers;
169317
169319 BlockPointer root_block_ptr;
169320
169326 bool IsValid() const {
169327 return root_block_ptr.IsValid() || !allocator_infos.empty();
169328 }
169329
169330 void Serialize(Serializer &serializer) const;
169331 static IndexStorageInfo Deserialize(Deserializer &deserializer);
169332};
169333
169335struct IndexInfo {
169336 bool is_unique;
169337 bool is_primary;
169338 bool is_foreign;
169339 unordered_set<column_t> column_set;
169340};
169341
169342}
169343
169344
169345
169346
169347
169348
169349
169350
169351
169352
169353
169354
169355
169356
169357
169358
169359
169360
169361
169362
169363
169364
169365
169366
169367
169368
169369
169370
169371
169372
169373
169374
169375
169376
169377
169378
169379
169380
169381
169382
169383
169384
169385
169386
169387
169388
169389
169390
169391
169392
169393
169394
169395
169396
169397
169398
169399
169400
169401
169402
169403#include <random>
169404
169405namespace duckdb {
169406class ClientContext;
169407struct RandomState;
169408
169409class RandomEngine {
169410public:
169411 explicit RandomEngine(int64_t seed = -1);
169412 ~RandomEngine();
169413
169415 double NextRandom(
double min,
double max);
169416
169418 double NextRandom();
169420 double NextRandom32();
169421 double NextRandom32(
double min,
double max);
169426
169427 void SetSeed(uint64_t seed);
169428
169429 void RandomData(duckdb::data_ptr_t data,
duckdb::idx_t len);
169430
169431 static RandomEngine &Get(ClientContext &context);
169432
169433 mutex lock;
169434
169435private:
169436 unique_ptr<RandomState> random_state;
169437};
169438
169439}
169440
169441
169442
169443
169444
169445
169446
169447
169448
169449
169450
169451
169452
169453#ifdef WIN32
169454
169455#ifdef min
169456#undef min
169457#endif
169458
169459#ifdef max
169460#undef max
169461#endif
169462
169463#ifdef ERROR
169464#undef ERROR
169465#endif
169466
169467#ifdef small
169468#undef small
169469#endif
169470
169471#ifdef CreateDirectory
169472#undef CreateDirectory
169473#endif
169474
169475#ifdef MoveFile
169476#undef MoveFile
169477#endif
169478
169479#ifdef RemoveDirectory
169480#undef RemoveDirectory
169481#endif
169482
169483#ifdef UUID
169484#undef UUID
169485#endif
169486
169487#ifdef interface
169488#undef interface
169489#endif
169490
169491#ifdef DELETE
169492#undef DELETE
169493#endif
169494
169495#endif
169496
169497
169498
169499
169500
169501
169502#define FIXED_SAMPLE_SIZE 2048
169503
169504namespace duckdb {
169505
169506enum class SampleType :
uint8_t { BLOCKING_SAMPLE = 0, RESERVOIR_SAMPLE = 1, RESERVOIR_PERCENTAGE_SAMPLE = 2 };
169507
169508enum class SamplingState :
uint8_t { RANDOM = 0, RESERVOIR = 1 };
169509
169510class ReservoirRNG : public RandomEngine {
169511public:
169512
169514
169515 explicit ReservoirRNG(int64_t seed) : RandomEngine(seed) {};
169516
169518 return NextRandomInteger();
169519 };
169520
169521 static constexpr result_type
min() {
169522 return NumericLimits<result_type>::Minimum();
169523 };
169524 static constexpr result_type
max() {
169525 return NumericLimits<result_type>::Maximum();
169526 };
169527};
169528
169530class BaseReservoirSampling {
169531public:
169532 explicit BaseReservoirSampling(int64_t seed);
169533 BaseReservoirSampling();
169534
169535 void InitializeReservoirWeights(idx_t cur_size, idx_t sample_size);
169536
169537 void SetNextEntry();
169538
169539 void ReplaceElementWithIndex(idx_t entry_index, double with_weight, bool pop = true);
169540 void ReplaceElement(double with_weight = -1);
169541
169542 void UpdateMinWeightThreshold();
169543
169547 void FillWeights(SelectionVector &sel, idx_t &sel_size);
169548
169549 unique_ptr<BaseReservoirSampling> Copy();
169550
169552 ReservoirRNG random;
169553
169555 idx_t next_index_to_sample;
169557 double min_weight_threshold;
169559 idx_t min_weighted_entry_index;
169562 idx_t num_entries_to_skip_b4_next_sample;
169565 idx_t num_entries_seen_total;
169567 std::priority_queue<std::pair<double, idx_t>> reservoir_weights;
169568
169569 void Serialize(Serializer &serializer) const;
169570 static unique_ptr<BaseReservoirSampling> Deserialize(Deserializer &deserializer);
169571
169572
169573
169574
169575
169576 friend class BlockingSample;
169577};
169578
169579class BlockingSample {
169580public:
169581 static constexpr const SampleType
TYPE = SampleType::BLOCKING_SAMPLE;
169582
169583 unique_ptr<BaseReservoirSampling> base_reservoir_sample;
169585 SampleType type;
169587 bool destroyed;
169588
169589public:
169590 explicit BlockingSample(int64_t seed = -1)
169591 : base_reservoir_sample(make_uniq<BaseReservoirSampling>(seed)), type(SampleType::BLOCKING_SAMPLE),
169592 destroyed(false) {
169593 }
169594 virtual ~BlockingSample() {
169595 }
169596
169598 virtual void AddToReservoir(DataChunk &input) = 0;
169599 virtual unique_ptr<BlockingSample> Copy() const = 0;
169600 virtual void Finalize() = 0;
169601 virtual void Destroy();
169602
169605 virtual unique_ptr<DataChunk> GetChunk() = 0;
169606
169607 virtual void Serialize(Serializer &serializer) const;
169608 static unique_ptr<BlockingSample> Deserialize(Deserializer &deserializer);
169609
169611 std::pair<double, idx_t> PopFromWeightQueue();
169612 double GetMinWeightThreshold();
169613 idx_t GetPriorityQueueSize();
169614
169615public:
169616 template <class TARGET>
169617 TARGET &Cast() {
169618 if (type != TARGET::TYPE && TARGET::TYPE != SampleType::BLOCKING_SAMPLE) {
169619 throw InternalException("Failed to cast sample to type - sample type mismatch");
169620 }
169621 return reinterpret_cast<TARGET &>(*this);
169622 }
169623
169624 template <class TARGET>
169625 const TARGET &Cast() const {
169626 if (type != TARGET::TYPE && TARGET::TYPE != SampleType::BLOCKING_SAMPLE) {
169627 throw InternalException("Failed to cast sample to type - sample type mismatch");
169628 }
169629 return reinterpret_cast<const TARGET &>(*this);
169630 }
169631};
169632
169633class ReservoirChunk {
169634public:
169635 ReservoirChunk() {
169636 }
169637
169638 DataChunk chunk;
169639 void Serialize(Serializer &serializer) const;
169640 static unique_ptr<ReservoirChunk> Deserialize(Deserializer &deserializer);
169641
169642 unique_ptr<ReservoirChunk> Copy() const;
169643};
169644
169645struct SelectionVectorHelper {
169646 SelectionVector sel;
169648};
169649
169650class ReservoirSample : public BlockingSample {
169651public:
169652 static constexpr const SampleType
TYPE = SampleType::RESERVOIR_SAMPLE;
169653
169654 constexpr static idx_t FIXED_SAMPLE_SIZE_MULTIPLIER = 10;
169655
169656
169657
169658
169659
169660
169661 constexpr static idx_t FAST_TO_SLOW_THRESHOLD = MinValue<idx_t>(STANDARD_VECTOR_SIZE, 60);
169662
169663
169664
169665 constexpr static double SAVE_PERCENTAGE = 0.01;
169666
169667 ReservoirSample(Allocator &allocator, idx_t sample_count, int64_t seed = 1);
169668 explicit ReservoirSample(idx_t sample_count, unique_ptr<ReservoirChunk> = nullptr);
169669
169671 void EvictOverBudgetSamples();
169672 void ExpandSerializedSample();
169673
169674 SamplingState GetSamplingState() const;
169675
169678 void Vacuum();
169679
169681 void ConvertToReservoirSample();
169682
169684 template <typename T>
169685 T GetReservoirChunkCapacity() const;
169686
169689 unique_ptr<BlockingSample> Copy() const override;
169690
169692 idx_t FillReservoir(DataChunk &chunk);
169694 void AddToReservoir(DataChunk &input) override;
169696 void Merge(unique_ptr<BlockingSample> other);
169697
169698 void ShuffleSel(SelectionVector &sel, idx_t range, idx_t size) const;
169699
169702 void UpdateSampleAppend(DataChunk &this_, DataChunk &other, SelectionVector &other_sel, idx_t append_count) const;
169703
169704 idx_t GetTuplesSeen()
const;
169705 idx_t NumSamplesCollected()
const;
169706 idx_t GetActiveSampleCount()
const;
169707 static bool ValidSampleType(const LogicalType &type);
169708
169709
169710 DataChunk &Chunk();
169711
169714
169715 unique_ptr<DataChunk> GetChunk() override;
169716 void Destroy() override;
169717 void Finalize() override;
169718 void Verify();
169719
169720 idx_t GetSampleCount();
169721
169722
169723
169724
169725
169726
169727
169729 SelectionVectorHelper GetReplacementIndexes(idx_t sample_chunk_offset, idx_t theoretical_chunk_length);
169730
169731 void Serialize(Serializer &serializer) const override;
169732 static unique_ptr<BlockingSample> Deserialize(Deserializer &deserializer);
169733
169734private:
169735
169736
169737
169738
169739 void NormalizeWeights();
169740
169741 SelectionVectorHelper GetReplacementIndexesSlow(const idx_t sample_chunk_offset, const idx_t chunk_length);
169742 SelectionVectorHelper GetReplacementIndexesFast(const idx_t sample_chunk_offset, const idx_t chunk_length);
169743 void SimpleMerge(ReservoirSample &other);
169744 void WeightedMerge(ReservoirSample &other_sample);
169745
169746
169747
169748
169749
169750 unique_ptr<ReservoirChunk> CreateNewSampleChunk(vector<LogicalType> &types, idx_t size) const;
169751
169752
169753
169754 vector<uint32_t> GetRandomizedVector(uint32_t range, uint32_t size) const;
169755
169756 idx_t sample_count;
169757 Allocator &allocator;
169758 unique_ptr<ReservoirChunk> reservoir_chunk;
169759 bool stats_sample;
169760 SelectionVector sel;
169762};
169763
169765class ReservoirSamplePercentage : public BlockingSample {
169766 constexpr static idx_t RESERVOIR_THRESHOLD = 100000;
169767
169768public:
169769 static constexpr const SampleType
TYPE = SampleType::RESERVOIR_PERCENTAGE_SAMPLE;
169770
169771 ReservoirSamplePercentage(Allocator &allocator, double percentage, int64_t seed = -1);
169772 ReservoirSamplePercentage(double percentage, int64_t seed, idx_t reservoir_sample_size);
169773 explicit ReservoirSamplePercentage(double percentage, int64_t seed = -1);
169774
169776 void AddToReservoir(DataChunk &input) override;
169777
169778 unique_ptr<BlockingSample> Copy() const override;
169779
169781 unique_ptr<DataChunk> GetChunk() override;
169782 void Finalize() override;
169783
169784 void Serialize(Serializer &serializer) const override;
169785 static unique_ptr<BlockingSample> Deserialize(Deserializer &deserializer);
169786
169787private:
169788 Allocator &allocator;
169790 double sample_percentage;
169792 idx_t reservoir_sample_size;
169793
169795 unique_ptr<ReservoirSample> current_sample;
169796
169798 vector<unique_ptr<ReservoirSample>> finished_samples;
169799
169801 idx_t current_count = 0;
169804 bool is_finalized;
169805};
169806
169807}
169808
169809
169810
169811
169812
169813
169814
169815
169816
169817
169818
169819
169820
169821
169822
169823
169824
169825
169826
169827
169828
169829
169830
169831
169832
169833
169834
169835
169836
169837
169838
169839
169840
169841
169842
169843
169844
169845
169846
169847
169848
169849
169850
169851
169852
169853
169854
169855
169856namespace duckdb {
169857
169858template <class T>
169859struct CountZeros {};
169860
169861template <>
169863
169864 inline static idx_t Leading(
const uint64_t value_in) {
169865 if (!value_in) {
169866 return 64;
169867 }
169868
169870
169871 constexpr uint64_t index64msb[] = {0, 47, 1, 56, 48, 27, 2, 60, 57, 49, 41, 37, 28, 16, 3, 61,
169872 54, 58, 35, 52, 50, 42, 21, 44, 38, 32, 29, 23, 17, 11, 4, 62,
169873 46, 55, 26, 59, 40, 36, 15, 53, 34, 51, 20, 43, 31, 22, 10, 45,
169874 25, 39, 14, 33, 19, 30, 9, 24, 13, 18, 8, 12, 7, 6, 5, 63};
169875
169876 constexpr uint64_t debruijn64msb = 0X03F79D71B4CB0A89;
169877
169878 value |= value >> 1;
169879 value |= value >> 2;
169880 value |= value >> 4;
169881 value |= value >> 8;
169882 value |= value >> 16;
169883 value |= value >> 32;
169884 auto result = 63 - index64msb[(value * debruijn64msb) >> 58];
169885#ifdef __clang__
169886 D_ASSERT(result ==
static_cast<uint64_t>(__builtin_clzl(value_in)));
169887#endif
169888 return result;
169889 }
169890 inline static idx_t Trailing(uint64_t value_in) {
169891 if (!value_in) {
169892 return 64;
169893 }
169895
169896 constexpr uint64_t index64lsb[] = {63, 0, 58, 1, 59, 47, 53, 2, 60, 39, 48, 27, 54, 33, 42, 3,
169897 61, 51, 37, 40, 49, 18, 28, 20, 55, 30, 34, 11, 43, 14, 22, 4,
169898 62, 57, 46, 52, 38, 26, 32, 41, 50, 36, 17, 19, 29, 10, 13, 21,
169899 56, 45, 25, 31, 35, 16, 9, 12, 44, 24, 15, 8, 23, 7, 6, 5};
169900 constexpr uint64_t debruijn64lsb = 0x07EDD5E59A4E28C2ULL;
169901 auto result = index64lsb[((value & -value) * debruijn64lsb) >> 58];
169902#ifdef __clang__
169903 D_ASSERT(result ==
static_cast<uint64_t>(__builtin_ctzl(value_in)));
169904#endif
169905 return result;
169906 }
169907};
169908
169909template <>
169911 inline static idx_t Leading(uint32_t value) {
169912 return CountZeros<uint64_t>::Leading(
static_cast<uint64_t>(value)) - 32;
169913 }
169914 inline static idx_t Trailing(uint32_t value) {
169915 return CountZeros<uint64_t>::Trailing(
static_cast<uint64_t>(value));
169916 }
169917};
169918
169919template <>
169920struct CountZeros<hugeint_t> {
169921 inline static idx_t Leading(hugeint_t value) {
169923 const uint64_t lower = value.lower;
169924
169925 if (upper) {
169926 return CountZeros<uint64_t>::Leading(upper);
169927 } else if (lower) {
169928 return 64 + CountZeros<uint64_t>::Leading(lower);
169929 } else {
169930 return 128;
169931 }
169932 }
169933
169934 inline static idx_t Trailing(hugeint_t value) {
169936 const uint64_t lower = value.lower;
169937
169938 if (lower) {
169939 return CountZeros<uint64_t>::Trailing(lower);
169940 } else if (upper) {
169941 return 64 + CountZeros<uint64_t>::Trailing(upper);
169942 } else {
169943 return 128;
169944 }
169945 }
169946};
169947
169948template <>
169949struct CountZeros<uhugeint_t> {
169950 inline static idx_t Leading(uhugeint_t value) {
169952 const uint64_t lower = value.lower;
169953
169954 if (upper) {
169955 return CountZeros<uint64_t>::Leading(upper);
169956 } else if (lower) {
169957 return 64 + CountZeros<uint64_t>::Leading(lower);
169958 } else {
169959 return 128;
169960 }
169961 }
169962
169963 inline static idx_t Trailing(uhugeint_t value) {
169965 const uint64_t lower = value.lower;
169966
169967 if (lower) {
169968 return CountZeros<uint64_t>::Trailing(lower);
169969 } else if (upper) {
169970 return 64 + CountZeros<uint64_t>::Trailing(upper);
169971 } else {
169972 return 128;
169973 }
169974 }
169975};
169976
169977}
169978
169979
169980
169981
169982
169983
169984
169985
169986
169987
169988
169989
169990#include <algorithm>
169991#include <cmath>
169992
169993
169994namespace duckdb {
169995
169997 HLL_V1 = 1,
169999};
170000
170001class Serializer;
170002class Deserializer;
170003
170007class HyperLogLog {
170008public:
170009 static constexpr idx_t P = 6;
170010 static constexpr idx_t Q = 64 - P;
170011 static constexpr idx_t M = 1 << P;
170012 static constexpr double ALPHA = 0.721347520444481703680;
170013
170014 static double GetErrorRate() {
170015 return std::sqrt(PI / 2.0) /
sqrt(M);
170016 }
170017
170018public:
170019 HyperLogLog() {
170020 memset(k, 0, sizeof(k));
170021 }
170022
170024 inline void InsertElement(hash_t h) {
170025 const auto i = h & ((1 << P) - 1);
170026 h >>= P;
170028 const uint8_t z = UnsafeNumericCast<uint8_t>(CountZeros<hash_t>::Trailing(h) + 1);
170029 Update(i, z);
170030 }
170031
170032 inline void Update(const idx_t &i, const uint8_t &z) {
170033 k[i] = MaxValue<uint8_t>(k[i], z);
170034 }
170035
170036 inline uint8_t GetRegister(
const idx_t &i)
const {
170037 return k[i];
170038 }
170039
170040 idx_t Count()
const;
170041
170043 void Merge(const HyperLogLog &other);
170044
170045public:
170047 void Update(Vector &input, Vector &hashes, idx_t count);
170049 unique_ptr<HyperLogLog> Copy() const;
170050
170051 void Serialize(Serializer &serializer) const;
170052 static unique_ptr<HyperLogLog> Deserialize(Deserializer &deserializer);
170053
170055 void ExtractCounts(uint32_t *c) const;
170057 static int64_t EstimateCardinality(uint32_t *c);
170058
170059private:
170061};
170062
170063}
170064
170065
170066namespace duckdb {
170067class Vector;
170068class Serializer;
170069class Deserializer;
170070
170071class DistinctStatistics {
170072public:
170073 DistinctStatistics();
170074 explicit DistinctStatistics(unique_ptr<HyperLogLog> log, idx_t sample_count, idx_t total_count);
170075
170077 unique_ptr<HyperLogLog>
log;
170079 atomic<idx_t> sample_count;
170081 atomic<idx_t> total_count;
170082
170083public:
170084 void Merge(const DistinctStatistics &other);
170085
170086 unique_ptr<DistinctStatistics> Copy() const;
170087
170088 void UpdateSample(Vector &new_data, idx_t count, Vector &hashes);
170089 void Update(Vector &new_data, idx_t count, Vector &hashes);
170090
170091 string ToString() const;
170092 idx_t GetCount()
const;
170093
170094 static bool TypeIsSupported(const LogicalType &type);
170095
170096 void Serialize(Serializer &serializer) const;
170097 static unique_ptr<DistinctStatistics> Deserialize(Deserializer &deserializer);
170098
170099private:
170100 void UpdateInternal(Vector &update, idx_t count, Vector &hashes);
170101
170102private:
170104 static constexpr double BASE_SAMPLE_RATE = 0.1;
170106 static constexpr double INTEGRAL_SAMPLE_RATE = 0.3;
170107};
170108
170109}
170110
170111
170112namespace duckdb {
170113class Serializer;
170114
170115class ColumnStatistics {
170116public:
170117 explicit ColumnStatistics(BaseStatistics stats_p);
170118 ColumnStatistics(BaseStatistics stats_p, unique_ptr<DistinctStatistics> distinct_stats_p);
170119
170120public:
170121 static shared_ptr<ColumnStatistics> CreateEmptyStats(const LogicalType &type);
170122
170123 void Merge(ColumnStatistics &other);
170124
170125 void UpdateDistinctStatistics(Vector &
v, idx_t count, Vector &hashes);
170126
170127 BaseStatistics &Statistics();
170128
170129 bool HasDistinctStats();
170130 DistinctStatistics &DistinctStats();
170131 void SetDistinct(unique_ptr<DistinctStatistics> distinct_stats);
170132
170133 shared_ptr<ColumnStatistics> Copy() const;
170134
170135 void Serialize(Serializer &serializer) const;
170136 static shared_ptr<ColumnStatistics> Deserialize(Deserializer &source);
170137
170138private:
170139 BaseStatistics stats;
170141 unique_ptr<DistinctStatistics> distinct_stats;
170142};
170143
170144}
170145
170146
170147
170148namespace duckdb {
170149class ColumnList;
170150class PersistentTableData;
170151class Serializer;
170152class Deserializer;
170153
170154class TableStatisticsLock {
170155public:
170156 explicit TableStatisticsLock(mutex &l) : guard(l) {
170157 }
170158
170159 lock_guard<mutex> guard;
170160};
170161
170162class TableStatistics {
170163public:
170164 void Initialize(const vector<LogicalType> &types, PersistentTableData &data);
170165 void InitializeEmpty(const vector<LogicalType> &types);
170166 void InitializeEmpty(const TableStatistics &other);
170167
170168 void InitializeAddColumn(TableStatistics &parent, const LogicalType &new_column_type);
170169 void InitializeRemoveColumn(TableStatistics &parent, idx_t removed_column);
170170 void InitializeAlterType(TableStatistics &parent, idx_t changed_idx, const LogicalType &new_type);
170171 void InitializeAddConstraint(TableStatistics &parent);
170172
170173 void MergeStats(TableStatistics &other);
170174 void MergeStats(idx_t i, BaseStatistics &stats);
170175 void MergeStats(TableStatisticsLock &lock, idx_t i, BaseStatistics &stats);
170176
170177 void SetStats(TableStatistics &other);
170178 void CopyStats(TableStatistics &other);
170179 void CopyStats(TableStatisticsLock &lock, TableStatistics &other);
170180 unique_ptr<BaseStatistics> CopyStats(const StorageIndex &i);
170183 ColumnStatistics &GetStats(TableStatisticsLock &lock, idx_t i);
170185
170187 unique_ptr<BlockingSample> GetTableSample(TableStatisticsLock &lock);
170188 void SetTableSample(TableStatisticsLock &lock, unique_ptr<BlockingSample> sample);
170189
170190 void DestroyTableSample(TableStatisticsLock &lock) const;
170191 void AppendToTableSample(TableStatisticsLock &lock, unique_ptr<BlockingSample> sample);
170192
170193 bool Empty();
170194
170195 unique_ptr<TableStatisticsLock> GetLock();
170196
170197 void Serialize(Serializer &serializer) const;
170198 void Deserialize(Deserializer &deserializer, ColumnList &columns);
170199
170200private:
170202 shared_ptr<mutex> stats_lock;
170204 vector<shared_ptr<ColumnStatistics>> column_stats;
170206 unique_ptr<BlockingSample> table_sample;
170207};
170208
170209}
170210
170211
170212
170213
170214
170215
170216
170217
170218
170219
170220
170221
170222
170223
170224
170225
170226
170227namespace duckdb {
170228class DatabaseInstance;
170229struct MetadataBlockInfo;
170230
170231struct MetadataBlock {
170232 MetadataBlock();
170233
170234 MetadataBlock(const MetadataBlock &other) = delete;
170235 MetadataBlock &
operator=(
const MetadataBlock &) =
delete;
170237 DUCKDB_API MetadataBlock(MetadataBlock &&other) noexcept;
170238 DUCKDB_API MetadataBlock &
operator=(MetadataBlock &&) noexcept;
170239
170240 shared_ptr<BlockHandle> block;
170241 block_id_t block_id;
170242 vector<uint8_t> free_blocks;
170243 atomic<bool> dirty;
170244
170245 void Write(WriteStream &sink);
170246 static MetadataBlock Read(ReadStream &source);
170247
170248 idx_t FreeBlocksToInteger();
170249 void FreeBlocksFromInteger(idx_t blocks);
170250 static vector<uint8_t> BlocksFromInteger(idx_t free_list);
170251
170252 string ToString() const;
170253};
170254
170255struct MetadataPointer {
170256 idx_t block_index : 56;
170258};
170259
170260struct MetadataHandle {
170261 MetadataPointer pointer;
170262 BufferHandle handle;
170263};
170264
170265class MetadataManager {
170266public:
170268 static constexpr const idx_t METADATA_BLOCK_COUNT = 64;
170269
170270public:
170271 MetadataManager(BlockManager &block_manager, BufferManager &buffer_manager);
170272 ~MetadataManager();
170273
170274 BufferManager &GetBufferManager() const {
170275 return buffer_manager;
170276 }
170277
170278 MetadataHandle AllocateHandle();
170279 MetadataHandle Pin(const MetadataPointer &pointer);
170280
170281 MetadataHandle Pin(const QueryContext &context, const MetadataPointer &pointer);
170282
170283 MetaBlockPointer GetDiskPointer(const MetadataPointer &pointer, uint32_t offset = 0);
170284 MetadataPointer FromDiskPointer(MetaBlockPointer pointer);
170285 MetadataPointer RegisterDiskPointer(MetaBlockPointer pointer);
170286
170287 static BlockPointer ToBlockPointer(MetaBlockPointer meta_pointer, const idx_t metadata_block_size);
170288 static MetaBlockPointer FromBlockPointer(BlockPointer block_pointer, const idx_t metadata_block_size);
170289
170291 void Flush();
170292
170293 bool BlockHasBeenCleared(const MetaBlockPointer &ptr);
170294
170295 void MarkBlocksAsModified();
170296 void ClearModifiedBlocks(const vector<MetaBlockPointer> &pointers);
170297
170298 vector<MetadataBlockInfo> GetMetadataInfo() const;
170299 vector<shared_ptr<BlockHandle>> GetBlocks() const;
170300 idx_t BlockCount();
170301
170302 void Write(WriteStream &sink);
170303 void Read(ReadStream &source);
170304
170305 idx_t GetMetadataBlockSize()
const;
170306
170307protected:
170308 BlockManager &block_manager;
170309 BufferManager &buffer_manager;
170310 mutable mutex block_lock;
170311 unordered_map<block_id_t, MetadataBlock> blocks;
170312 unordered_map<block_id_t, idx_t> modified_blocks;
170313
170314protected:
170315 block_id_t AllocateNewBlock(unique_lock<mutex> &block_lock);
170316 block_id_t PeekNextBlockId() const;
170317 block_id_t GetNextBlockId() const;
170318
170319 void AddBlock(unique_lock<mutex> &block_lock, MetadataBlock new_block, bool if_exists = false);
170320 void AddAndRegisterBlock(unique_lock<mutex> &block_lock, MetadataBlock block);
170321 void ConvertToTransient(unique_lock<mutex> &block_lock, MetadataBlock &block);
170322 MetadataPointer FromDiskPointerInternal(unique_lock<mutex> &block_lock, MetaBlockPointer pointer);
170323};
170324
170325}
170326
170327
170328namespace duckdb {
170329class BaseStatistics;
170330
170331class PersistentTableData {
170332public:
170333 explicit PersistentTableData(idx_t column_count);
170334 ~PersistentTableData();
170335
170336 MetaBlockPointer base_table_pointer;
170337 vector<MetaBlockPointer> read_metadata_pointers;
170338 TableStatistics table_stats;
170340 idx_t row_group_count;
170341 MetaBlockPointer block_pointer;
170342};
170343
170344}
170345
170346
170347
170348
170349
170350
170351
170352
170353
170354
170355
170356
170357
170358
170359
170360
170361
170362
170363
170364
170365
170366
170367
170368
170369
170370
170371
170372
170373
170374
170375
170376
170377
170378
170379
170380
170381namespace duckdb {
170382
170383enum class ScanVectorType { SCAN_ENTIRE_VECTOR, SCAN_FLAT_VECTOR };
170384
170385}
170386
170387
170388
170389
170390
170391
170392
170393
170394
170395
170396
170397
170398
170399
170400
170401
170402
170403
170404
170405
170406
170407
170408
170409
170410
170411namespace duckdb {
170412class DatabaseInstance;
170413class ColumnData;
170414struct ColumnDataCheckpointData;
170415class ColumnSegment;
170416class SegmentStatistics;
170417class TableFilter;
170418struct TableFilterState;
170419struct ColumnSegmentState;
170420struct ColumnFetchState;
170421struct ColumnScanState;
170422struct PrefetchState;
170423struct SegmentScanState;
170424
170425class CompressionInfo {
170426public:
170427 explicit CompressionInfo(BlockManager &block_manager) : block_manager(block_manager) {
170428 }
170429
170430public:
170432 idx_t GetCompactionFlushLimit()
const {
170433 return block_manager.GetBlockSize() / 5 * 4;
170434 }
170436 idx_t GetBlockSize()
const {
170437 return block_manager.GetBlockSize();
170438 }
170439
170441 idx_t GetBlockHeaderSize()
const {
170442 return block_manager.GetBlockHeaderSize();
170443 }
170444
170445 BlockManager &GetBlockManager() const {
170446 return block_manager;
170447 }
170448
170449private:
170450 BlockManager &block_manager;
170451};
170452
170453struct AnalyzeState {
170454 explicit AnalyzeState(const CompressionInfo &info) : info(info) {};
170455 virtual ~AnalyzeState() {
170456 }
170457
170458 template <class TARGET>
170459 TARGET &Cast() {
170460 DynamicCastCheck<TARGET>(this);
170461 return reinterpret_cast<TARGET &>(*this);
170462 }
170463 template <class TARGET>
170464 const TARGET &Cast() const {
170465 DynamicCastCheck<TARGET>(this);
170466 return reinterpret_cast<const TARGET &>(*this);
170467 }
170468
170469 CompressionInfo info;
170470};
170471
170472struct CompressionState {
170473 explicit CompressionState(const CompressionInfo &info) : info(info) {};
170474 virtual ~CompressionState() {
170475 }
170476
170477 template <class TARGET>
170478 TARGET &Cast() {
170479 DynamicCastCheck<TARGET>(this);
170480 return reinterpret_cast<TARGET &>(*this);
170481 }
170482 template <class TARGET>
170483 const TARGET &Cast() const {
170484 DynamicCastCheck<TARGET>(this);
170485 return reinterpret_cast<const TARGET &>(*this);
170486 }
170487
170488 CompressionInfo info;
170489};
170490
170491struct CompressedSegmentState {
170492 virtual ~CompressedSegmentState() {
170493 }
170494
170496 virtual string GetSegmentInfo() const {
170497 return "";
170498 }
170499
170500 template <class TARGET>
170501 TARGET &Cast() {
170502 DynamicCastCheck<TARGET>(this);
170503 return reinterpret_cast<TARGET &>(*this);
170504 }
170505 template <class TARGET>
170506 const TARGET &Cast() const {
170507 DynamicCastCheck<TARGET>(this);
170508 return reinterpret_cast<const TARGET &>(*this);
170509 }
170510};
170511
170512struct CompressionAppendState {
170513 explicit CompressionAppendState(BufferHandle handle_p) : handle(std::move(handle_p)) {
170514 }
170515 virtual ~CompressionAppendState() {
170516 }
170517
170518 BufferHandle handle;
170519
170520 template <class TARGET>
170521 TARGET &Cast() {
170522 DynamicCastCheck<TARGET>(this);
170523 return reinterpret_cast<TARGET &>(*this);
170524 }
170525 template <class TARGET>
170526 const TARGET &Cast() const {
170527 DynamicCastCheck<TARGET>(this);
170528 return reinterpret_cast<const TARGET &>(*this);
170529 }
170530};
170531
170532
170533
170534
170542
170544typedef unique_ptr<AnalyzeState> (*compression_init_analyze_t)(ColumnData &col_data,
PhysicalType type);
170545typedef bool (*compression_analyze_t)(AnalyzeState &state, Vector &input,
idx_t count);
170546typedef idx_t (*compression_final_analyze_t)(AnalyzeState &state);
170547
170548
170549
170550
170551typedef unique_ptr<CompressionState> (*compression_init_compression_t)(ColumnDataCheckpointData &checkpoint_data,
170552 unique_ptr<AnalyzeState> state);
170553typedef void (*compression_compress_data_t)(CompressionState &state, Vector &scan_vector,
idx_t count);
170554typedef void (*compression_compress_finalize_t)(CompressionState &state);
170555
170556
170557
170558
170559typedef void (*compression_init_prefetch_t)(ColumnSegment &segment, PrefetchState &prefetch_state);
170560typedef unique_ptr<SegmentScanState> (*compression_init_segment_scan_t)(const QueryContext &context,
170561 ColumnSegment &segment);
170562
170564typedef void (*compression_scan_vector_t)(ColumnSegment &segment, ColumnScanState &state,
idx_t scan_count,
170565 Vector &result);
170567typedef void (*compression_scan_partial_t)(ColumnSegment &segment, ColumnScanState &state,
idx_t scan_count,
170568 Vector &result,
idx_t result_offset);
170570typedef void (*compression_select_t)(ColumnSegment &segment, ColumnScanState &state,
idx_t vector_count, Vector &result,
170571 const SelectionVector &sel,
idx_t sel_count);
170573typedef void (*compression_filter_t)(ColumnSegment &segment, ColumnScanState &state,
idx_t vector_count, Vector &result,
170574 SelectionVector &sel,
idx_t &sel_count,
const TableFilter &
filter,
170575 TableFilterState &filter_state);
170577typedef void (*compression_fetch_row_t)(ColumnSegment &segment, ColumnFetchState &state,
row_t row_id, Vector &result,
170578 idx_t result_idx);
170581typedef void (*compression_skip_t)(ColumnSegment &segment, ColumnScanState &state,
idx_t skip_count);
170582
170583
170584
170585
170586typedef unique_ptr<CompressedSegmentState> (*compression_init_segment_t)(
170587 ColumnSegment &segment, block_id_t block_id, optional_ptr<ColumnSegmentState> segment_state);
170588typedef unique_ptr<CompressionAppendState> (*compression_init_append_t)(ColumnSegment &segment);
170589typedef idx_t (*compression_append_t)(CompressionAppendState &append_state, ColumnSegment &segment,
170590 SegmentStatistics &stats, UnifiedVectorFormat &data,
idx_t offset,
idx_t count);
170591typedef idx_t (*compression_finalize_append_t)(ColumnSegment &segment, SegmentStatistics &stats);
170592typedef void (*compression_revert_append_t)(ColumnSegment &segment,
idx_t new_count);
170593
170594
170595
170596
170598typedef unique_ptr<ColumnSegmentState> (*compression_serialize_state_t)(ColumnSegment &segment);
170600typedef unique_ptr<ColumnSegmentState> (*compression_deserialize_state_t)(Deserializer &deserializer);
170602typedef void (*compression_visit_block_ids_t)(const ColumnSegment &segment, BlockIdVisitor &visitor);
170603
170604
170605
170606
170608typedef InsertionOrderPreservingMap<string> (*compression_get_segment_info_t)(QueryContext context,
170609 ColumnSegment &segment);
170610
170611enum class CompressionValidity :
uint8_t { REQUIRES_VALIDITY, NO_VALIDITY_REQUIRED };
170612
170613class CompressionFunction {
170614public:
170615 CompressionFunction(CompressionType type, PhysicalType data_type, compression_init_analyze_t init_analyze,
170616 compression_analyze_t analyze, compression_final_analyze_t final_analyze,
170617 compression_init_compression_t init_compression, compression_compress_data_t compress,
170618 compression_compress_finalize_t compress_finalize, compression_init_segment_scan_t init_scan,
170619 compression_scan_vector_t scan_vector, compression_scan_partial_t scan_partial,
170620 compression_fetch_row_t fetch_row, compression_skip_t skip,
170621 compression_init_segment_t init_segment = nullptr,
170622 compression_init_append_t init_append = nullptr, compression_append_t append = nullptr,
170623 compression_finalize_append_t finalize_append = nullptr,
170624 compression_revert_append_t revert_append = nullptr,
170625 compression_serialize_state_t serialize_state = nullptr,
170626 compression_deserialize_state_t deserialize_state = nullptr,
170627 compression_visit_block_ids_t visit_block_ids = nullptr,
170628 compression_init_prefetch_t init_prefetch = nullptr, compression_select_t select = nullptr,
170629 compression_filter_t filter = nullptr)
170630 : type(type), data_type(data_type), init_analyze(init_analyze), analyze(analyze), final_analyze(final_analyze),
170631 init_compression(init_compression), compress(compress), compress_finalize(compress_finalize),
170632 init_prefetch(init_prefetch), init_scan(init_scan), scan_vector(scan_vector), scan_partial(scan_partial),
170634 init_append(init_append), append(append), finalize_append(finalize_append), revert_append(revert_append),
170635 serialize_state(serialize_state), deserialize_state(deserialize_state), visit_block_ids(visit_block_ids) {
170636 }
170637
170639 CompressionType type;
170642
170649 compression_analyze_t analyze;
170654 compression_final_analyze_t final_analyze;
170655
170658 compression_init_compression_t init_compression;
170660 compression_compress_data_t compress;
170662 compression_compress_finalize_t compress_finalize;
170663
170665 compression_init_prefetch_t init_prefetch;
170667 compression_init_segment_scan_t init_scan;
170683
170684
170686
170688 compression_init_segment_t init_segment;
170690 compression_init_append_t init_append;
170692 compression_append_t append;
170694 compression_finalize_append_t finalize_append;
170696 compression_revert_append_t revert_append;
170697
170698
170700
170707
170708
170711
170714
170717 CompressionValidity validity = CompressionValidity::REQUIRES_VALIDITY;
170718};
170719
170721struct CompressionFunctionSet {
170722 static constexpr idx_t COMPRESSION_TYPE_COUNT = 16;
170723 static constexpr idx_t PHYSICAL_TYPE_COUNT = 19;
170724
170725public:
170726 CompressionFunctionSet();
170727
170728 vector<reference<const CompressionFunction>> GetCompressionFunctions(PhysicalType physical_type);
170729 optional_ptr<const CompressionFunction> GetCompressionFunction(CompressionType type, PhysicalType physical_type);
170730 void SetDisabledCompressionMethods(const vector<CompressionType> &methods);
170731 vector<CompressionType> GetDisabledCompressionMethods() const;
170732
170733private:
170734 atomic<bool> is_disabled[COMPRESSION_TYPE_COUNT];
170735 vector<vector<CompressionFunction>> functions;
170736
170737private:
170738 static idx_t GetCompressionIndex(PhysicalType physical_type);
170739 static idx_t GetCompressionIndex(CompressionType type);
170740 void ResetDisabledMethods();
170741};
170742
170743}
170744
170745
170746
170747
170748
170749
170750namespace duckdb {
170751
170752class BaseStatistics;
170753class BlockManager;
170754class ColumnData;
170755class ColumnSegment;
170756class DatabaseInstance;
170757class TableFilter;
170758class Transaction;
170759class UpdateSegment;
170760struct ColumnAppendState;
170761struct ColumnFetchState;
170762struct ColumnScanState;
170763struct PrefetchState;
170764struct TableFilterState;
170765
170766enum class ColumnSegmentType :
uint8_t { TRANSIENT, PERSISTENT };
170768
170769class ColumnSegment : public SegmentBase<ColumnSegment> {
170770public:
170772 ColumnSegment(DatabaseInstance &db, shared_ptr<BlockHandle> block, const LogicalType &type,
170773 const ColumnSegmentType segment_type, const idx_t count, const CompressionFunction &function_p,
170774 BaseStatistics statistics, const block_id_t block_id_p, const idx_t offset,
170775 const idx_t segment_size_p, unique_ptr<ColumnSegmentState> segment_state_p = nullptr);
170778 ColumnSegment(ColumnSegment &other);
170779 ~ColumnSegment();
170780
170781public:
170782 static unique_ptr<ColumnSegment> CreatePersistentSegment(DatabaseInstance &db, BlockManager &block_manager,
170783 block_id_t id, idx_t offset, const LogicalType &type_p,
170784 idx_t count, CompressionType compression_type,
170785 BaseStatistics statistics,
170786 unique_ptr<ColumnSegmentState> segment_state);
170787 static unique_ptr<ColumnSegment> CreateTransientSegment(DatabaseInstance &db, const CompressionFunction &function,
170788 const LogicalType &type, const idx_t segment_size,
170789 BlockManager &block_manager);
170790
170791public:
170792 void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state);
170793 void InitializeScan(ColumnScanState &state);
170795 void Scan(ColumnScanState &state, idx_t scan_count, Vector &result, idx_t result_offset, ScanVectorType scan_type);
170797 void Select(ColumnScanState &state, idx_t scan_count, Vector &result, const SelectionVector &sel, idx_t sel_count);
170799 void Filter(ColumnScanState &state, idx_t scan_count, Vector &result, SelectionVector &sel, idx_t &sel_count,
170800 const TableFilter &filter, TableFilterState &filter_state);
170802 void FetchRow(ColumnFetchState &state, row_t row_id, Vector &result, idx_t result_idx);
170803
170804 static idx_t FilterSelection(SelectionVector &sel, Vector &vector, UnifiedVectorFormat &vdata,
170805 const TableFilter &filter, TableFilterState &filter_state, idx_t scan_count,
170806 idx_t &approved_tuple_count);
170807
170809 void Skip(ColumnScanState &state);
170810
170811
170812 idx_t SegmentSize()
const;
170814 void Resize(idx_t segment_size);
170815 const CompressionFunction &GetCompressionFunction();
170816
170818 void InitializeAppend(ColumnAppendState &state);
170820 idx_t Append(ColumnAppendState &state, UnifiedVectorFormat &data, idx_t offset, idx_t count);
170824 idx_t FinalizeAppend(ColumnAppendState &state);
170826 void RevertAppend(idx_t new_count);
170827
170830 void ConvertToPersistent(QueryContext context, optional_ptr<BlockManager> block_manager, const block_id_t block_id);
170833 void MarkAsPersistent(shared_ptr<BlockHandle> block, uint32_t offset_in_block);
170834 void SetBlock(shared_ptr<BlockHandle> block, uint32_t offset);
170836 DataPointer GetDataPointer(idx_t row_start);
170837
170838 block_id_t GetBlockId() {
170839 D_ASSERT(segment_type == ColumnSegmentType::PERSISTENT);
170840 return block_id;
170841 }
170842
170844 idx_t GetBlockSize()
const {
170845 return block->GetBlockSize();
170846 }
170847
170848 idx_t GetBlockOffset() {
170849 D_ASSERT(segment_type == ColumnSegmentType::PERSISTENT || offset == 0);
170850 return offset;
170851 }
170852
170853 optional_ptr<CompressedSegmentState> GetSegmentState() const {
170854 return segment_state.get();
170855 }
170856
170857 void VisitBlockIds(BlockIdVisitor &visitor) const;
170858
170859private:
170860 void Scan(ColumnScanState &state, idx_t scan_count, Vector &result);
170861 void ScanPartial(ColumnScanState &state, idx_t scan_count, Vector &result, idx_t result_offset);
170862
170863public:
170865 DatabaseInstance &
db;
170867 LogicalType type;
170871 ColumnSegmentType segment_type;
170873 SegmentStatistics stats;
170875 shared_ptr<BlockHandle> block;
170876
170877private:
170879 reference<const CompressionFunction> function;
170881 block_id_t block_id;
170885 idx_t segment_size;
170887 unique_ptr<CompressedSegmentState> segment_state;
170888};
170889
170890}
170891
170892
170893namespace duckdb {
170894
170895class ColumnSegmentTree : public SegmentTree<ColumnSegment> {};
170896
170897}
170898
170899
170900
170901
170902
170903
170904
170905
170906
170907
170908
170909
170910
170911
170912
170913
170914
170915
170916
170917namespace duckdb {
170918
170919template <class T, bool SAFE = true>
170920class atomic_ptr {
170921public:
170922 atomic_ptr() noexcept : ptr(nullptr) {
170923 }
170924 atomic_ptr(T *ptr_p) : ptr(ptr_p) {
170925 }
170926 atomic_ptr(T &ref) : ptr(&ref) {
170927 }
170928 atomic_ptr(
const unique_ptr<T> &ptr_p) : ptr(ptr_p.
get()) {
170929 }
170930 atomic_ptr(
const shared_ptr<T> &ptr_p) : ptr(ptr_p.
get()) {
170931 }
170932
170933 void CheckValid(const T *ptr) const {
170934 if (MemorySafety<SAFE>::ENABLED) {
170935 return;
170936 }
170937 if (!ptr) {
170938 throw InternalException("Attempting to dereference an optional pointer that is not set");
170939 }
170940 }
170941
170942 T *GetPointer() {
170943 auto res = ptr.load();
170944 CheckValid(res);
170945 return res;
170946 }
170947
170948 const T *GetPointer() const {
170949 auto res = ptr.load();
170950 CheckValid(res);
170951 return res;
170952 }
170953
170954 operator bool() const {
170955 return ptr;
170956 }
170958 return *GetPointer();
170959 }
170961 return *GetPointer();
170962 }
170963 T *operator->() {
170964 return GetPointer();
170965 }
170966 const T *operator->() const {
170967 return GetPointer();
170968 }
170970 return GetPointer();
170971 }
170972 const T *
get()
const {
170973 return GetPointer();
170974 }
170975
170976 T *get_mutable() const {
170977 return GetPointer();
170978 }
170979
170980 void set(T &ref) {
170981 ptr = &ref;
170982 }
170983
170984 void reset() {
170985 ptr = nullptr;
170986 }
170987
170988 bool operator==(
const atomic_ptr<T> &rhs)
const {
170989 return ptr.load() == rhs.ptr.load();
170990 }
170991
170992 bool operator!=(
const atomic_ptr<T> &rhs)
const {
170993 return ptr.load() != rhs.ptr.load();
170994 }
170995
170996private:
170997 atomic<T *> ptr;
170998};
170999
171000template <typename T>
171001using unsafe_atomic_ptr = atomic_ptr<T, false>;
171002
171003}
171004
171005
171006namespace duckdb {
171007class ColumnData;
171008class ColumnSegment;
171009class DatabaseInstance;
171010class RowGroup;
171011class RowGroupWriter;
171012class StorageManager;
171013class TableDataWriter;
171014class TableStorageInfo;
171015struct DataTableInfo;
171016struct PrefetchState;
171017struct RowGroupWriteInfo;
171018struct TableScanOptions;
171019struct TransactionData;
171020struct PersistentColumnData;
171021class ValidityColumnData;
171022
171023using column_segment_vector_t = vector<SegmentNode<ColumnSegment>>;
171024
171025struct ColumnCheckpointInfo {
171026 ColumnCheckpointInfo(RowGroupWriteInfo &info, idx_t column_idx);
171027
171029
171030public:
171031 PartialBlockManager &GetPartialBlockManager();
171032 CompressionType GetCompressionType();
171033
171034private:
171035 RowGroupWriteInfo &info;
171036};
171037
171038enum class ColumnDataType { MAIN_TABLE, INITIAL_TRANSACTION_LOCAL, TRANSACTION_LOCAL, CHECKPOINT_TARGET };
171039
171040class ColumnData : public enable_shared_from_this<ColumnData> {
171041 friend class ColumnDataCheckpointer;
171042
171043public:
171044 ColumnData(BlockManager &block_manager, DataTableInfo &info, idx_t column_index, LogicalType type,
171045 ColumnDataType data_type, optional_ptr<ColumnData> parent);
171046 virtual ~ColumnData();
171047
171049 atomic<idx_t> count;
171051 BlockManager &block_manager;
171053 DataTableInfo &info;
171055 idx_t column_index;
171057 LogicalType type;
171058
171059public:
171060 virtual FilterPropagateResult CheckZonemap(ColumnScanState &state, TableFilter &filter);
171061
171062 BlockManager &GetBlockManager() const {
171063 return block_manager;
171064 }
171065 DatabaseInstance &GetDatabase() const;
171066 DataTableInfo &GetTableInfo() const;
171067 StorageManager &GetStorageManager() const;
171068 virtual idx_t GetMaxEntry();
171069
171070 idx_t GetAllocationSize()
const {
171071 return allocation_size;
171072 }
171073 optional_ptr<const CompressionFunction> GetCompressionFunction() const {
171074 return compression.get();
171075 }
171076 virtual void SetDataType(ColumnDataType data_type);
171077 ColumnDataType GetDataType() const {
171078 return data_type;
171079 }
171080
171081 bool HasParent() const {
171082 return parent;
171083 }
171084 void SetParent(optional_ptr<ColumnData> parent) {
171085 this->parent = parent;
171086 }
171087 const ColumnData &Parent() const {
171088 D_ASSERT(HasParent());
171089 return *parent;
171090 }
171091
171092 virtual const BaseStatistics &GetChildStats(const ColumnData &child) const;
171093
171094 const LogicalType &GetType() const {
171095 return type;
171096 }
171097 ColumnSegmentTree &GetSegmentTree() {
171098 return data;
171099 }
171100 void SetCount(idx_t new_count) {
171101 this->count = new_count;
171102 }
171103
171105 bool HasUpdates() const;
171106 bool HasChanges(idx_t start_row, idx_t end_row) const;
171108 bool HasChanges() const;
171109
171111 virtual bool HasAnyChanges() const;
171113 virtual ScanVectorType GetVectorScanType(ColumnScanState &state, idx_t scan_count, Vector &result);
171114
171116 virtual void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t
rows);
171118 virtual void InitializeScan(ColumnScanState &state);
171120 virtual void InitializeScanWithOffset(ColumnScanState &state, idx_t row_idx);
171122 idx_t Scan(TransactionData transaction, idx_t vector_index, ColumnScanState &state, Vector &result);
171123 virtual idx_t Scan(TransactionData transaction, idx_t vector_index, ColumnScanState &state, Vector &result,
171124 idx_t scan_count);
171125
171126 virtual void ScanCommittedRange(idx_t row_group_start, idx_t offset_in_row_group, idx_t count, Vector &result);
171127 virtual idx_t ScanCount(ColumnScanState &state, Vector &result, idx_t count, idx_t result_offset = 0);
171128
171130 virtual void Filter(TransactionData transaction, idx_t vector_index, ColumnScanState &state, Vector &result,
171131 SelectionVector &sel, idx_t &count, const TableFilter &filter, TableFilterState &filter_state);
171132 virtual void Select(TransactionData transaction, idx_t vector_index, ColumnScanState &state, Vector &result,
171133 SelectionVector &sel, idx_t count);
171134
171136 virtual void Skip(ColumnScanState &state, idx_t count = STANDARD_VECTOR_SIZE);
171137
171139 virtual void InitializeAppend(ColumnAppendState &state);
171141 virtual void Append(BaseStatistics &stats, ColumnAppendState &state, Vector &vector, idx_t count);
171143 void Append(ColumnAppendState &state, Vector &vector, idx_t count);
171144 virtual void AppendData(BaseStatistics &stats, ColumnAppendState &state, UnifiedVectorFormat &vdata, idx_t count);
171146 virtual void RevertAppend(row_t new_count);
171147
171149 virtual idx_t Fetch(ColumnScanState &state, row_t row_id, Vector &result);
171151 virtual void FetchRow(TransactionData transaction, ColumnFetchState &state, const StorageIndex &storage_index,
171152 row_t row_id, Vector &result, idx_t result_idx);
171153
171154 virtual void Update(TransactionData transaction, DataTable &data_table, idx_t column_index, Vector &update_vector,
171155 row_t *row_ids, idx_t update_count, idx_t row_group_start);
171156 virtual void UpdateColumn(TransactionData transaction, DataTable &data_table, const vector<column_t> &column_path,
171157 Vector &update_vector, row_t *row_ids, idx_t update_count, idx_t depth,
171158 idx_t row_group_start);
171159 virtual unique_ptr<BaseStatistics> GetUpdateStatistics();
171160
171161 virtual void VisitBlockIds(BlockIdVisitor &visitor) const;
171162
171163 virtual unique_ptr<ColumnCheckpointState> CreateCheckpointState(const RowGroup &row_group,
171164 PartialBlockManager &partial_block_manager);
171167 unique_ptr<ColumnCheckpointState> Checkpoint(const RowGroup &row_group, ColumnCheckpointInfo &info);
171168 virtual unique_ptr<ColumnCheckpointState> Checkpoint(const RowGroup &row_group, ColumnCheckpointInfo &info,
171169 const BaseStatistics &stats);
171170
171171 virtual void CheckpointScan(ColumnSegment &segment, ColumnScanState &state, idx_t count, Vector &scan_vector) const;
171172
171173 virtual bool IsPersistent();
171174 vector<DataPointer> GetDataPointers();
171175
171176 virtual PersistentColumnData Serialize();
171177 void InitializeColumn(PersistentColumnData &column_data);
171178 virtual void InitializeColumn(PersistentColumnData &column_data, BaseStatistics &target_stats);
171179 static shared_ptr<ColumnData> Deserialize(BlockManager &block_manager, DataTableInfo &info, idx_t column_index,
171180 ReadStream &source, const LogicalType &type);
171181
171182 virtual void GetColumnSegmentInfo(const QueryContext &context, idx_t row_group_index, vector<idx_t> col_path,
171183 vector<ColumnSegmentInfo> &result);
171184 virtual void Verify(RowGroup &parent);
171185
171186 FilterPropagateResult CheckZonemap(const StorageIndex &index, TableFilter &filter);
171187
171188 static shared_ptr<ColumnData> CreateColumn(BlockManager &block_manager, DataTableInfo &info, idx_t column_index,
171189 const LogicalType &type,
171190 ColumnDataType data_type = ColumnDataType::MAIN_TABLE,
171191 optional_ptr<ColumnData> parent = nullptr);
171192
171193 void MergeStatistics(const BaseStatistics &other);
171194 void MergeIntoStatistics(BaseStatistics &other);
171195 unique_ptr<BaseStatistics> GetStatistics() const;
171196 const BaseStatistics &GetStatisticsRef() const;
171197
171198protected:
171200 void AppendTransientSegment(SegmentLock &l, idx_t start_row);
171201 void AppendSegment(SegmentLock &l, unique_ptr<ColumnSegment> segment);
171202
171203 void BeginScanVectorInternal(ColumnScanState &state);
171205 idx_t ScanVector(ColumnScanState &state, Vector &result, idx_t remaining, ScanVectorType scan_type,
171206 idx_t result_offset = 0);
171208 idx_t ScanVector(TransactionData transaction, idx_t vector_index, ColumnScanState &state, Vector &result,
171209 idx_t target_scan, ScanVectorType scan_type, UpdateScanType update_type);
171210 idx_t ScanVector(TransactionData transaction, idx_t vector_index, ColumnScanState &state, Vector &result,
171211 idx_t target_scan, UpdateScanType update_type);
171212 void SelectVector(ColumnScanState &state, Vector &result, idx_t target_count, const SelectionVector &sel,
171213 idx_t sel_count);
171214 void FilterVector(ColumnScanState &state, Vector &result, idx_t target_count, SelectionVector &sel,
171215 idx_t &sel_count, const TableFilter &filter, TableFilterState &filter_state);
171216
171217 void FetchUpdates(TransactionData transaction, idx_t vector_index, Vector &result, idx_t scan_count,
171218 UpdateScanType update_type);
171219 void FetchUpdateRow(TransactionData transaction, row_t row_id, Vector &result, idx_t result_idx);
171220 void UpdateInternal(TransactionData transaction, DataTable &data_table, idx_t column_index, Vector &update_vector,
171221 row_t *row_ids, idx_t update_count, Vector &base_vector, idx_t row_group_start);
171222 idx_t FetchUpdateData(ColumnScanState &state, row_t *row_ids, Vector &base_vector, idx_t row_group_start);
171223
171224 idx_t GetVectorCount(idx_t vector_index)
const;
171225
171226private:
171227 void UpdateCompressionFunction(SegmentLock &l, const CompressionFunction &function);
171228
171229protected:
171231 ColumnSegmentTree data;
171233 mutable mutex update_lock;
171235 unique_ptr<UpdateSegment> updates;
171237 mutable mutex stats_lock;
171239 atomic<idx_t> allocation_size;
171241 unique_ptr<SegmentStatistics> stats;
171242
171243private:
171245 atomic<ColumnDataType> data_type;
171247 optional_ptr<ColumnData> parent;
171250 atomic_ptr<const CompressionFunction> compression;
171251
171252public:
171253 template <class TARGET>
171254 TARGET &Cast() {
171255 DynamicCastCheck<TARGET>(this);
171256 return reinterpret_cast<TARGET &>(*this);
171257 }
171258 template <class TARGET>
171259 const TARGET &Cast() const {
171260 DynamicCastCheck<TARGET>(this);
171261 return reinterpret_cast<const TARGET &>(*this);
171262 }
171263};
171264
171265enum class ExtraPersistentColumnDataType :
uint8_t {
171266 INVALID = 0,
171267 VARIANT = 1,
171268 GEOMETRY = 2,
171269};
171270
171271class ExtraPersistentColumnData {
171272public:
171273 ExtraPersistentColumnDataType GetType() const {
171274 return type;
171275 }
171276
171277 virtual ~ExtraPersistentColumnData() = default;
171278
171279 template <class TARGET>
171280 TARGET &Cast() {
171281 D_ASSERT(type == TARGET::TYPE);
171282 DynamicCastCheck<TARGET>(this);
171283 return reinterpret_cast<TARGET &>(*this);
171284 }
171285 template <class TARGET>
171286 const TARGET &Cast() const {
171287 D_ASSERT(type == TARGET::TYPE);
171288 DynamicCastCheck<TARGET>(this);
171289 return reinterpret_cast<const TARGET &>(*this);
171290 }
171291
171292 void Serialize(Serializer &serializer) const;
171293 static unique_ptr<ExtraPersistentColumnData> Deserialize(Deserializer &deserializer);
171294
171295protected:
171296 explicit ExtraPersistentColumnData(ExtraPersistentColumnDataType type_p) : type(type_p) {
171297 }
171298
171299private:
171300 ExtraPersistentColumnDataType type;
171301};
171302
171303class VariantPersistentColumnData final : public ExtraPersistentColumnData {
171304public:
171305 static constexpr auto TYPE = ExtraPersistentColumnDataType::VARIANT;
171306 VariantPersistentColumnData() : ExtraPersistentColumnData(
TYPE) {
171307 }
171308 explicit VariantPersistentColumnData(const LogicalType &storage_type)
171309 : ExtraPersistentColumnData(
TYPE), logical_type(storage_type) {
171310 }
171311
171312 LogicalType logical_type;
171313};
171314
171315class GeometryPersistentColumnData final : public ExtraPersistentColumnData {
171316public:
171317 static constexpr auto TYPE = ExtraPersistentColumnDataType::GEOMETRY;
171318 GeometryPersistentColumnData() : ExtraPersistentColumnData(
TYPE) {
171319 }
171320 explicit GeometryPersistentColumnData(GeometryStorageType storage_type)
171321 : ExtraPersistentColumnData(
TYPE), storage_type(storage_type) {
171322 }
171323
171324 GeometryStorageType storage_type;
171325};
171326
171327struct PersistentColumnData {
171328public:
171329 explicit PersistentColumnData(const LogicalType &logical_type);
171330 PersistentColumnData(const LogicalType &logical_type, vector<DataPointer> pointers);
171331
171332 PersistentColumnData(const PersistentColumnData &other) = delete;
171333 PersistentColumnData &
operator=(
const PersistentColumnData &) =
delete;
171335 PersistentColumnData(PersistentColumnData &&other) noexcept = default;
171336 PersistentColumnData &
operator=(PersistentColumnData &&) =
default;
171337 ~PersistentColumnData();
171338
171339public:
171340 void Serialize(Serializer &serializer) const;
171341 static PersistentColumnData Deserialize(Deserializer &deserializer);
171342 void DeserializeField(Deserializer &deserializer, field_id_t field_idx, const char *field_name,
171343 const LogicalType &type);
171344 bool HasUpdates() const;
171345
171346public:
171347 LogicalType logical_type;
171348 vector<DataPointer> pointers;
171349 vector<PersistentColumnData> child_columns;
171350 bool has_updates = false;
171351
171353 unique_ptr<ExtraPersistentColumnData> extra_data;
171354};
171355
171356struct PersistentRowGroupData {
171357 explicit PersistentRowGroupData(vector<LogicalType> types);
171358 PersistentRowGroupData() = default;
171359
171360 PersistentRowGroupData(const PersistentRowGroupData &other) = delete;
171361 PersistentRowGroupData &
operator=(
const PersistentRowGroupData &) =
delete;
171363 PersistentRowGroupData(PersistentRowGroupData &&other) noexcept = default;
171364 PersistentRowGroupData &
operator=(PersistentRowGroupData &&) =
default;
171365 ~PersistentRowGroupData() = default;
171366
171367 vector<LogicalType> types;
171368 vector<PersistentColumnData> column_data;
171371
171372 void Serialize(Serializer &serializer) const;
171373 static PersistentRowGroupData Deserialize(Deserializer &deserializer);
171374 bool HasUpdates() const;
171375};
171376
171377struct PersistentCollectionData {
171378 PersistentCollectionData() = default;
171379
171380 PersistentCollectionData(const PersistentCollectionData &other) = delete;
171381 PersistentCollectionData &
operator=(
const PersistentCollectionData &) =
delete;
171383 PersistentCollectionData(PersistentCollectionData &&other) noexcept = default;
171384 PersistentCollectionData &
operator=(PersistentCollectionData &&) =
default;
171385 ~PersistentCollectionData() = default;
171386
171387 vector<PersistentRowGroupData> row_group_data;
171388
171389 void Serialize(Serializer &serializer) const;
171390 static PersistentCollectionData Deserialize(Deserializer &deserializer);
171391 bool HasUpdates() const;
171392 vector<block_id_t> GetBlockIds() const;
171393};
171394
171395}
171396
171397
171398
171399namespace duckdb {
171400
171402struct ColumnSegmentInfo {
171403 idx_t row_group_index;
171405 string column_path;
171406 idx_t segment_idx;
171407 string segment_type;
171408 idx_t segment_start;
171409 idx_t segment_count;
171410 string compression_type;
171411 string segment_stats;
171412 bool has_updates;
171413 bool persistent;
171414 block_id_t block_id;
171415 vector<block_id_t> additional_blocks;
171416 idx_t block_offset;
171417 string segment_info;
171418};
171419
171421class TableStorageInfo {
171422public:
171424 optional_idx cardinality;
171426 vector<IndexInfo> index_info;
171427};
171428
171429}
171430
171431
171432namespace duckdb {
171433
171434class ClientContext;
171435class TableIOManager;
171436class Transaction;
171437class ConflictManager;
171438
171439struct IndexLock;
171440struct IndexScanState;
171441
171443class Index {
171444protected:
171445 Index(const vector<column_t> &column_ids, TableIOManager &table_io_manager, AttachedDatabase &db);
171446
171454 vector<column_t> column_ids;
171456 unordered_set<column_t> column_id_set;
171457
171458public:
171460 TableIOManager &table_io_manager;
171462 AttachedDatabase &
db;
171463
171464public:
171465 virtual ~Index() = default;
171466
171468 virtual bool IsBound() const = 0;
171469
171471 virtual const string &GetIndexType() const = 0;
171472
171474 virtual const string &GetIndexName() const = 0;
171475
171477 virtual IndexConstraintType GetConstraintType() const = 0;
171478
171480 bool IsUnique() const {
171481 auto type = GetConstraintType();
171482 return type == IndexConstraintType::UNIQUE || type == IndexConstraintType::PRIMARY;
171483 }
171484
171486 bool IsPrimary() const {
171487 auto index_constraint_type = GetConstraintType();
171488 return (index_constraint_type == IndexConstraintType::PRIMARY);
171489 }
171490
171492 bool IsForeign() const {
171493 auto index_constraint_type = GetConstraintType();
171494 return (index_constraint_type == IndexConstraintType::FOREIGN);
171495 }
171496
171497 const vector<column_t> &GetColumnIds() const {
171498 return column_ids;
171499 }
171500
171501 const unordered_set<column_t> &GetColumnIdSet() const {
171502 return column_id_set;
171503 }
171504
171505
171506 virtual void CommitDrop() = 0;
171507
171508public:
171509 template <class TARGET>
171510 TARGET &Cast() {
171511 DynamicCastCheck<TARGET>(this);
171512 return reinterpret_cast<TARGET &>(*this);
171513 }
171514
171515 template <class TARGET>
171516 const TARGET &Cast() const {
171517 DynamicCastCheck<TARGET>(this);
171518 return reinterpret_cast<const TARGET &>(*this);
171519 }
171520};
171521
171522}
171523
171524
171525
171526
171527
171528
171529
171530
171531
171532
171533
171534
171535
171536
171537
171538
171539
171540
171541
171542
171543
171544
171545
171546
171547
171548
171549
171550
171551
171552
171553
171554
171555
171556
171557
171558
171559
171560
171561
171562
171563
171564
171565
171566
171567
171568
171569
171570
171571
171572
171573
171574
171575
171576
171577
171578
171579
171580
171581
171582
171583
171584namespace duckdb {
171585
171586struct CreateIndexInfo : public CreateInfo {
171587 CreateIndexInfo();
171588 CreateIndexInfo(const CreateIndexInfo &info);
171589
171591 string table;
171593 string index_name;
171594
171596 case_insensitive_map_t<Value> options;
171597
171601 IndexConstraintType constraint_type;
171603 vector<column_t> column_ids;
171605 vector<unique_ptr<ParsedExpression>> expressions;
171606 vector<unique_ptr<ParsedExpression>> parsed_expressions;
171607
171609 vector<LogicalType> scan_types;
171611 vector<string> names;
171612
171613public:
171614 DUCKDB_API unique_ptr<CreateInfo> Copy() const override;
171615 string ToString() const override;
171616 void Serialize(Serializer &serializer) const override;
171617 static unique_ptr<CreateInfo> Deserialize(Deserializer &deserializer);
171618
171619 vector<string> ExpressionsToList() const;
171620 string ExpressionsToString() const;
171621};
171622
171623}
171624
171625
171626
171627
171628namespace duckdb {
171629
171630class ColumnDataCollection;
171631
171632enum class BufferedIndexReplay :
uint8_t { INSERT_ENTRY = 0, DEL_ENTRY = 1 };
171633
171634struct ReplayRange {
171635 BufferedIndexReplay type;
171636
171637
171640 explicit ReplayRange(const BufferedIndexReplay replay_type, const idx_t start_p, const idx_t end_p)
171641 : type(replay_type), start(start_p), end(end_p) {
171642 }
171643};
171644
171645
171646
171647
171648
171649
171650
171651
171652
171653
171654struct BufferedIndexReplays {
171655 vector<ReplayRange> ranges;
171656 unique_ptr<ColumnDataCollection> buffered_inserts;
171657 unique_ptr<ColumnDataCollection> buffered_deletes;
171658
171659 BufferedIndexReplays() = default;
171660
171661 unique_ptr<ColumnDataCollection> &GetBuffer(const BufferedIndexReplay replay_type) {
171662 if (replay_type == BufferedIndexReplay::INSERT_ENTRY) {
171663 return buffered_inserts;
171664 }
171665 return buffered_deletes;
171666 }
171667
171668 bool HasBufferedReplays() const {
171669 return !ranges.empty();
171670 }
171671};
171672
171673class UnboundIndex final : public Index {
171674private:
171676 unique_ptr<CreateInfo> create_info;
171678 IndexStorageInfo storage_info;
171679
171681 BufferedIndexReplays buffered_replays;
171682
171687 vector<StorageIndex> mapped_column_ids;
171688
171689public:
171690 UnboundIndex(unique_ptr<CreateInfo> create_info, IndexStorageInfo storage_info, TableIOManager &table_io_manager,
171691 AttachedDatabase &db);
171692
171693public:
171694 bool IsBound() const override {
171695 return false;
171696 }
171697 const string &GetIndexType() const override {
171698 return GetCreateInfo().index_type;
171699 }
171700 const string &GetIndexName() const override {
171701 return GetCreateInfo().index_name;
171702 }
171703 IndexConstraintType GetConstraintType() const override {
171704 return GetCreateInfo().constraint_type;
171705 }
171706 const CreateIndexInfo &GetCreateInfo() const {
171707 return create_info->Cast<CreateIndexInfo>();
171708 }
171709 const IndexStorageInfo &GetStorageInfo() const {
171710 return storage_info;
171711 }
171712 const vector<unique_ptr<ParsedExpression>> &GetParsedExpressions() const {
171713 return GetCreateInfo().parsed_expressions;
171714 }
171715 const string &GetTableName() const {
171716 return GetCreateInfo().table;
171717 }
171718
171719 void CommitDrop() override;
171720
171724 void BufferChunk(DataChunk &index_column_chunk, Vector &row_ids, const vector<StorageIndex> &mapped_column_ids_p,
171725 BufferedIndexReplay replay_type);
171726 bool HasBufferedReplays() const {
171727 return buffered_replays.HasBufferedReplays();
171728 }
171729
171730 BufferedIndexReplays &GetBufferedReplays() {
171731 return buffered_replays;
171732 }
171733
171734 const vector<StorageIndex> &GetMappedColumnIds() const {
171735 return mapped_column_ids;
171736 }
171737};
171738
171739}
171740
171741
171742
171743
171744
171745
171746
171747
171748
171749
171750
171751namespace duckdb {
171752
171753class ClientContext;
171754class TableIOManager;
171755class Transaction;
171756class ConflictManager;
171757
171758struct IndexLock;
171759struct IndexScanState;
171760
171761enum class IndexAppendMode :
uint8_t { DEFAULT = 0, IGNORE_DUPLICATES = 1, INSERT_DUPLICATES = 2 };
171762
171763class IndexAppendInfo {
171764public:
171765 IndexAppendInfo() : append_mode(IndexAppendMode::DEFAULT) {
171766 }
171767 IndexAppendInfo(const IndexAppendMode append_mode, optional_ptr<BoundIndex> delete_index)
171768 : append_mode(append_mode) {
171769 if (delete_index) {
171770 delete_indexes.push_back(*delete_index);
171771 }
171772 }
171773
171774public:
171775 IndexAppendMode append_mode;
171776 vector<reference<BoundIndex>> delete_indexes;
171777};
171778
171779enum class DeltaIndexType {
171780 NONE,
171781 LOCAL_APPEND,
171782 LOCAL_DELETE,
171783 ADDED_DURING_CHECKPOINT,
171784 REMOVED_DURING_CHECKPOINT,
171785 DELETED_ROWS_IN_USE
171786};
171787
171789class BoundIndex : public Index {
171790public:
171791 BoundIndex(
const string &name,
const string &
index_type, IndexConstraintType index_constraint_type,
171792 const vector<column_t> &column_ids, TableIOManager &table_io_manager,
171793 const vector<unique_ptr<Expression>> &unbound_expressions, AttachedDatabase &db);
171794
171796 vector<PhysicalType> types;
171798 vector<LogicalType> logical_types;
171799
171801 string name;
171805 IndexConstraintType index_constraint_type;
171806
171817 vector<unique_ptr<Expression>> unbound_expressions;
171818
171820 DeltaIndexType delta_index_type = DeltaIndexType::NONE;
171821
171822public:
171823 bool IsBound() const override {
171824 return true;
171825 }
171826 const string &GetIndexType() const override {
171828 }
171829 const string &GetIndexName() const override {
171830 return name;
171831 }
171832 IndexConstraintType GetConstraintType() const override {
171833 return index_constraint_type;
171834 }
171835
171836public:
171838 void InitializeLock(IndexLock &state);
171840 virtual ErrorData Append(IndexLock &l, DataChunk &chunk, Vector &row_ids) = 0;
171842 ErrorData Append(DataChunk &chunk, Vector &row_ids);
171844 virtual ErrorData Append(IndexLock &l, DataChunk &chunk, Vector &row_ids, IndexAppendInfo &info);
171846 ErrorData Append(DataChunk &chunk, Vector &row_ids, IndexAppendInfo &info);
171847
171849 virtual void VerifyAppend(DataChunk &chunk, IndexAppendInfo &info, optional_ptr<ConflictManager> manager);
171851 virtual void VerifyConstraint(DataChunk &chunk, IndexAppendInfo &info, ConflictManager &manager);
171852
171854 virtual void CommitDrop(IndexLock &index_lock) = 0;
171855
171857
171858 void CommitDrop() override;
171862 virtual idx_t TryDelete(IndexLock &state, DataChunk &entries, Vector &row_identifiers,
171863 optional_ptr<SelectionVector> deleted_sel = nullptr,
171864 optional_ptr<SelectionVector> non_deleted_sel = nullptr);
171866 idx_t TryDelete(DataChunk &entries, Vector &row_identifiers, optional_ptr<SelectionVector> deleted_sel =
nullptr,
171867 optional_ptr<SelectionVector> non_deleted_sel = nullptr);
171870 virtual void Delete(IndexLock &state, DataChunk &entries, Vector &row_identifiers);
171872 void Delete(DataChunk &entries, Vector &row_identifiers);
171873
171875 virtual ErrorData Insert(IndexLock &l, DataChunk &chunk, Vector &row_ids) = 0;
171877 virtual ErrorData Insert(IndexLock &l, DataChunk &chunk, Vector &row_ids, IndexAppendInfo &info);
171878
171881 virtual bool MergeIndexes(IndexLock &state, BoundIndex &other_index) = 0;
171883 bool MergeIndexes(BoundIndex &other_index);
171884
171887 virtual void Vacuum(IndexLock &l) = 0;
171889 void Vacuum();
171890
171892 virtual bool SupportsDeltaIndexes() const;
171895 virtual unique_ptr<BoundIndex> CreateDeltaIndex(DeltaIndexType delta_index_type) const;
171896
171898 virtual idx_t GetInMemorySize(IndexLock &state) = 0;
171900 idx_t GetInMemorySize();
171901
171903 virtual void Verify(IndexLock &l) = 0;
171905 void Verify();
171906
171908 virtual string ToString(IndexLock &l, bool display_ascii = false) = 0;
171910 string ToString(bool display_ascii = false);
171911
171913 virtual void VerifyAllocations(IndexLock &l) = 0;
171915 void VerifyAllocations();
171916
171918 virtual void VerifyBuffers(IndexLock &l);
171920 void VerifyBuffers();
171921
171923 bool IndexIsUpdated(const vector<PhysicalIndex> &column_ids) const;
171924
171926 virtual IndexStorageInfo SerializeToDisk(QueryContext context, const case_insensitive_map_t<Value> &options);
171928 virtual IndexStorageInfo SerializeToWAL(const case_insensitive_map_t<Value> &options);
171929
171931 void ExecuteExpressions(DataChunk &input, DataChunk &result);
171932 static string AppendRowError(DataChunk &input, idx_t index);
171933
171935 virtual string GetConstraintViolationMessage(VerifyExistenceType verify_type, idx_t failed_index,
171936 DataChunk &input) = 0;
171937
171941 void ApplyBufferedReplays(const vector<LogicalType> &table_types, BufferedIndexReplays &buffered_replays,
171942 const vector<StorageIndex> &mapped_column_ids);
171943
171944protected:
171946 mutex lock;
171947
171954 vector<unique_ptr<Expression>> bound_expressions;
171955
171956private:
171958 ExpressionExecutor executor;
171959
171961 unique_ptr<Expression> BindExpression(unique_ptr<Expression> expr);
171962};
171963
171964}
171965
171966
171967
171968namespace duckdb {
171969
171970class ConflictManager;
171971class LocalTableStorage;
171972struct IndexStorageInfo;
171973struct DataTableInfo;
171974template <class T>
171975class TableIndexIterationHelper;
171976
171979
171981struct IndexEntry {
171982 explicit IndexEntry(unique_ptr<Index> index);
171983
171984 atomic<IndexBindState> bind_state;
171986 mutex lock;
171987 unique_ptr<Index>
index;
171988 unique_ptr<BoundIndex> deleted_rows_in_use;
171990 unique_ptr<BoundIndex> added_data_during_checkpoint;
171992 unique_ptr<BoundIndex> removed_data_during_checkpoint;
171994 optional_idx last_written_checkpoint;
171995};
171996
171997struct IndexSerializationInfo {
171998 case_insensitive_map_t<Value> options;
172000};
172001
172002
172003
172004
172005
172006
172007
172008
172009
172010struct IndexSerializationResult {
172012 vector<reference<const IndexStorageInfo>> ordered_infos;
172014 vector<IndexStorageInfo> bound_infos;
172015};
172016
172017class TableIndexList {
172018public:
172019 TableIndexIterationHelper<IndexEntry> IndexEntries() const;
172020 TableIndexIterationHelper<Index> Indexes() const;
172022 void AddIndex(unique_ptr<Index> index);
172024 void RemoveIndex(const string &name);
172026 void CommitDrop(const string &name);
172028 bool NameIsUnique(const string &name);
172030 optional_ptr<BoundIndex> Find(const string &name);
172032 void Bind(ClientContext &context, DataTableInfo &table_info,
const char *
index_type =
nullptr);
172034 bool Empty() const {
172035 return Count() == 0;
172036 }
172038 idx_t Count()
const {
172039 lock_guard<mutex> lock(index_entries_lock);
172040 return index_entries.size();
172041 }
172043 bool HasUnbound() const {
172044 lock_guard<mutex> lock(index_entries_lock);
172045 return unbound_count != 0;
172046 }
172048 unordered_set<string> DistinctIndexTypes() const;
172050 void Move(TableIndexList &other) {
172051 D_ASSERT(index_entries.empty());
172052 index_entries = std::move(other.index_entries);
172053 }
172055 void MergeCheckpointDeltas(transaction_t checkpoint_id);
172058 optional_ptr<IndexEntry> FindForeignKeyIndex(const vector<PhysicalIndex> &fk_keys, const ForeignKeyType fk_type);
172060 void VerifyForeignKey(optional_ptr<LocalTableStorage> storage, const vector<PhysicalIndex> &fk_keys,
172061 DataChunk &chunk, ConflictManager &conflict_manager);
172063 unordered_set<column_t> GetRequiredColumns();
172065 IndexSerializationResult SerializeToDisk(QueryContext context, const IndexSerializationInfo &info);
172066
172067public:
172069 static void InitializeIndexChunk(DataChunk &index_chunk, const vector<LogicalType> &table_types,
172070 vector<StorageIndex> &mapped_column_ids, DataTableInfo &data_table_info);
172072 static void ReferenceIndexChunk(DataChunk &table_chunk, DataChunk &index_chunk,
172073 vector<StorageIndex> &mapped_column_ids);
172074
172075private:
172077 mutable mutex index_entries_lock;
172079 vector<unique_ptr<IndexEntry>> index_entries;
172081 idx_t unbound_count = 0;
172082};
172083
172084template <class T>
172085class TableIndexIterationHelper {
172086public:
172087 TableIndexIterationHelper(mutex &index_lock, const vector<unique_ptr<IndexEntry>> &index_entries);
172088
172089private:
172090 unique_lock<mutex> lock;
172091 const vector<unique_ptr<IndexEntry>> &index_entries;
172092
172093private:
172094 class TableIndexIterator {
172095 public:
172096 explicit TableIndexIterator(optional_ptr<const vector<unique_ptr<IndexEntry>>> index_entries);
172097
172098 optional_ptr<const vector<unique_ptr<IndexEntry>>> index_entries;
172099 optional_idx
index;
172100
172101 public:
172102 TableIndexIterator &operator++();
172103 bool operator!=(
const TableIndexIterator &other)
const;
172105 };
172106
172107public:
172108 TableIndexIterator begin() {
172109 return TableIndexIterator(&index_entries);
172110 }
172111 TableIndexIterator end() {
172112 return TableIndexIterator(nullptr);
172113 }
172114};
172115
172116template <>
172117IndexEntry &TableIndexIterationHelper<IndexEntry>::TableIndexIterator::operator*() const;
172118template <>
172119Index &TableIndexIterationHelper<Index>::TableIndexIterator::operator*() const;
172120
172121}
172122
172123
172124
172125namespace duckdb {
172126class DatabaseInstance;
172127class TableIOManager;
172128
172129struct DataTableInfo {
172130 friend class DataTable;
172131
172132public:
172133 DataTableInfo(AttachedDatabase &db, shared_ptr<TableIOManager> table_io_manager_p, string schema, string table);
172134
172137 void BindIndexes(ClientContext &context,
const char *
index_type =
nullptr);
172138
172140 bool IsTemporary() const;
172141
172142 AttachedDatabase &GetDB() {
172144 }
172145
172146 TableIOManager &GetIOManager() {
172147 return *table_io_manager;
172148 }
172149
172150 TableIndexList &GetIndexes() {
172151 return indexes;
172152 }
172154 IndexStorageInfo ExtractIndexStorageInfo(const string &name);
172155 unique_ptr<StorageLockKey> GetSharedLock() {
172156 return checkpoint_lock.GetSharedLock();
172157 }
172158 bool AppendRequiresNewRowGroup(RowGroupCollection &collection, transaction_t checkpoint_id);
172159 optional_idx CheckpointRowGroupCount(const CheckpointOptions &options) const;
172160 void VerifyIndexBuffers();
172161
172162 string GetSchemaName();
172163 string GetTableName();
172164 void SetTableName(string name);
172165
172166private:
172168 AttachedDatabase &
db;
172170 shared_ptr<TableIOManager> table_io_manager;
172172 mutex name_lock;
172174 string schema;
172176 string table;
172178 TableIndexList indexes;
172180 vector<IndexStorageInfo> index_storage_infos;
172182 StorageLock checkpoint_lock;
172184 optional_idx last_seen_checkpoint;
172186 optional_idx checkpoint_row_group_count;
172187};
172188
172189}
172190
172191
172192
172193
172194
172195
172196
172197
172198
172199
172200
172201
172202
172203
172204
172205
172206
172207
172208
172209
172210
172211
172212
172213
172214
172215
172216
172217
172218namespace duckdb {
172219
172230 DELETED_ROWS_IN_USE
172231};
172232
172233}
172234
172235
172236namespace duckdb {
172237
172238struct ParallelTableScanState;
172239struct ParallelCollectionScanState;
172240class CreateIndexScanState;
172241class CollectionScanState;
172242class PersistentTableData;
172243class TableDataWriter;
172244class TableIndexList;
172245class TableStatistics;
172246struct TableAppendState;
172247class DuckTransaction;
172248class BoundConstraint;
172249class RowGroupSegmentTree;
172250class StorageCommitState;
172251struct ColumnSegmentInfo;
172252class MetadataManager;
172253struct VacuumState;
172254struct CollectionCheckpointState;
172255struct PersistentCollectionData;
172256class CheckpointTask;
172257class TableIOManager;
172258class DataTable;
172259class RowGroupIterationHelper;
172260class TableScanState;
172261
172262class RowGroupCollection {
172263public:
172264 RowGroupCollection(shared_ptr<DataTableInfo> info, TableIOManager &io_manager, vector<LogicalType> types,
172265 idx_t row_start, idx_t total_rows = 0);
172266 RowGroupCollection(shared_ptr<DataTableInfo> info, BlockManager &block_manager, vector<LogicalType> types,
172267 idx_t row_start, idx_t total_rows, idx_t row_group_size);
172268
172269public:
172270 idx_t GetTotalRows()
const;
172271 idx_t GetRowGroupCount()
const;
172272 Allocator &GetAllocator() const;
172273
172274 void Initialize(PersistentCollectionData &data);
172275 void Initialize(PersistentTableData &data);
172276 void InitializeEmpty();
172277 void FinalizeCheckpoint(MetaBlockPointer pointer, const vector<MetaBlockPointer> &existing_pointers);
172278
172279 bool IsEmpty() const;
172280
172281 void AppendRowGroup(SegmentLock &l, idx_t start_row);
172283 optional_ptr<RowGroup> GetRowGroup(int64_t index);
172285 void SetRowGroup(int64_t index, shared_ptr<RowGroup> new_row_group);
172286 void Verify();
172287 void Destroy();
172288
172289 void InitializeScan(const QueryContext &context, CollectionScanState &state, const vector<StorageIndex> &column_ids,
172290 optional_ptr<TableFilterSet> table_filters);
172291 void InitializeCreateIndexScan(CreateIndexScanState &state);
172292 void InitializeScanWithOffset(const QueryContext &context, CollectionScanState &state,
172293 const vector<StorageIndex> &column_ids, idx_t start_row, idx_t end_row);
172294 static bool InitializeScanInRowGroup(ClientContext &context, CollectionScanState &state,
172295 RowGroupCollection &collection, SegmentNode<RowGroup> &row_group,
172296 idx_t vector_index, idx_t max_row);
172297 void InitializeParallelScan(ParallelCollectionScanState &state);
172298 bool NextParallelScan(ClientContext &context, ParallelCollectionScanState &state, CollectionScanState &scan_state);
172299
172300 RowGroupIterationHelper Chunks(DuckTransaction &transaction);
172301 RowGroupIterationHelper Chunks(DuckTransaction &transaction, const vector<StorageIndex> &column_ids);
172302
172303 void Fetch(TransactionData transaction, DataChunk &result, const vector<StorageIndex> &column_ids,
172304 const Vector &row_identifiers, idx_t fetch_count, ColumnFetchState &state);
172305
172307 bool CanFetch(TransactionData, const row_t row_id);
172308
172310 void InitializeAppend(TableAppendState &state);
172313 void InitializeAppend(TransactionData transaction, TableAppendState &state);
172315 bool Append(DataChunk &chunk, TableAppendState &state);
172317 void FinalizeAppend(TransactionData transaction, TableAppendState &state);
172318 void CommitAppend(transaction_t commit_id, idx_t row_start, idx_t count);
172319 void RevertAppendInternal(idx_t start_row);
172320 void CleanupAppend(transaction_t lowest_transaction, idx_t start, idx_t count);
172321
172322 void MergeStorage(RowGroupCollection &data, optional_ptr<DataTable> table,
172323 optional_ptr<StorageCommitState> commit_state);
172324 bool IsPersistent() const;
172325
172326 void RemoveFromIndexes(const QueryContext &context, TableIndexList &indexes, Vector &row_identifiers, idx_t count,
172327 IndexRemovalType removal_type, optional_idx active_checkpoint = optional_idx());
172328
172329 idx_t Delete(TransactionData transaction, DataTable &table, row_t *ids, idx_t count);
172330 void Update(TransactionData transaction, DataTable &table, row_t *ids, const vector<PhysicalIndex> &column_ids,
172331 DataChunk &updates);
172332 void UpdateColumn(TransactionData transaction, DataTable &table, Vector &row_ids,
172333 const vector<column_t> &column_path, DataChunk &updates);
172334
172335 void Checkpoint(TableDataWriter &writer, TableStatistics &global_stats);
172336
172337 void InitializeVacuumState(CollectionCheckpointState &checkpoint_state, VacuumState &state,
172338 optional_idx checkpoint_row_group_count);
172339 bool ScheduleVacuumTasks(CollectionCheckpointState &checkpoint_state, VacuumState &state, idx_t segment_idx,
172340 bool schedule_vacuum);
172341 unique_ptr<CheckpointTask> GetCheckpointTask(CollectionCheckpointState &checkpoint_state, idx_t segment_idx);
172342
172343 void CommitDropColumn(const idx_t column_index);
172344 void CommitDropTable();
172345
172346 vector<PartitionStatistics> GetPartitionStats() const;
172347 vector<ColumnSegmentInfo> GetColumnSegmentInfo(const QueryContext &context);
172348 const vector<LogicalType> &GetTypes() const;
172349
172350 shared_ptr<RowGroupCollection> AddColumn(ClientContext &context, ColumnDefinition &new_column,
172351 ExpressionExecutor &default_executor);
172352 shared_ptr<RowGroupCollection> RemoveColumn(idx_t col_idx);
172353 shared_ptr<RowGroupCollection> AlterType(ClientContext &context, idx_t changed_idx, const LogicalType &target_type,
172354 vector<StorageIndex> bound_columns, Expression &cast_expr);
172355 void VerifyNewConstraint(const QueryContext &context, DataTable &parent, const BoundConstraint &constraint);
172356
172357 void SetStats(TableStatistics &new_stats);
172358 void CopyStats(TableStatistics &stats);
172359 unique_ptr<BaseStatistics> CopyStats(const StorageIndex &column_id);
172360 unique_ptr<BlockingSample> GetSample();
172361 void SetDistinct(column_t column_id, unique_ptr<DistinctStatistics> distinct_stats);
172362
172363 AttachedDatabase &GetAttached();
172364 BlockManager &GetBlockManager() {
172365 return block_manager;
172366 }
172367 MetadataManager &GetMetadataManager();
172368 DataTableInfo &GetTableInfo() {
172369 return *info;
172370 }
172371
172372 idx_t GetAllocationSize()
const {
172373 return allocation_size;
172374 }
172375
172376 idx_t GetRowGroupSize()
const {
172377 return row_group_size;
172378 }
172379 void SetAppendRequiresNewRowGroup();
172381 idx_t GetSegmentCount();
172382
172383private:
172384 optional_ptr<SegmentNode<RowGroup>> NextUpdateRowGroup(RowGroupSegmentTree &row_groups, row_t *ids, idx_t &pos,
172385 idx_t count) const;
172386
172387 shared_ptr<RowGroupSegmentTree> GetRowGroups() const;
172388 void SetRowGroups(shared_ptr<RowGroupSegmentTree> row_groups);
172389
172390private:
172392 BlockManager &block_manager;
172394 const idx_t row_group_size;
172396 atomic<idx_t> total_rows;
172398 shared_ptr<DataTableInfo> info;
172400 vector<LogicalType> types;
172402 mutable mutex row_group_pointer_lock;
172404 shared_ptr<RowGroupSegmentTree> owned_row_groups;
172406 TableStatistics stats;
172408 atomic<idx_t> allocation_size;
172410 MetaBlockPointer metadata_pointer;
172412 vector<MetaBlockPointer> metadata_pointers;
172414 bool requires_new_row_group;
172415};
172416
172417class RowGroupIterationHelper {
172418public:
172419 RowGroupIterationHelper(RowGroupCollection &collection, DuckTransaction &transaction,
172420 vector<StorageIndex> column_ids);
172421
172422private:
172423 RowGroupCollection &collection;
172424 DuckTransaction &transaction;
172425 vector<StorageIndex> column_ids;
172426
172427private:
172428 class RowGroupIterator {
172429 public:
172430 RowGroupIterator(optional_ptr<RowGroupCollection> collection, optional_ptr<DuckTransaction> transaction,
172431 const vector<StorageIndex> &column_ids);
172432 ~RowGroupIterator();
172434 RowGroupIterator(RowGroupIterator &&other) noexcept;
172435
172436 optional_ptr<RowGroupCollection> collection;
172437 optional_ptr<DuckTransaction> transaction;
172438 unique_ptr<DataChunk> chunk;
172439 unique_ptr<TableScanState> state;
172440
172441 public:
172442 RowGroupIterator &operator++();
172443 bool operator!=(
const RowGroupIterator &other)
const;
172445 };
172446
172447public:
172448 RowGroupIterator begin();
172449 RowGroupIterator end();
172450};
172451
172452}
172453
172454
172455
172456
172457
172458
172459
172460
172461
172462
172463
172464
172465
172466
172467
172468
172469
172470
172471
172472
172473
172474
172475
172476
172477
172478
172479
172480
172481namespace duckdb {
172482class PartialBlockManager;
172483
172484struct OptimisticWriteCollection {
172485 ~OptimisticWriteCollection();
172486
172487 shared_ptr<RowGroupCollection> collection;
172488 set<idx_t> unflushed_row_groups;
172489 idx_t complete_row_groups = 0;
172490 vector<unique_ptr<PartialBlockManager>> partial_block_managers;
172491
172492 void MergeStorage(OptimisticWriteCollection &collection);
172493};
172494
172495enum class OptimisticWritePartialManagers { PER_COLUMN, GLOBAL };
172496
172497class OptimisticDataWriter {
172498public:
172499 OptimisticDataWriter(ClientContext &context, DataTable &table);
172500 OptimisticDataWriter(DataTable &table, OptimisticDataWriter &parent);
172501 ~OptimisticDataWriter();
172502
172504 unique_ptr<OptimisticWriteCollection>
172505 CreateCollection(DataTable &storage, const vector<LogicalType> &insert_types,
172506 OptimisticWritePartialManagers type = OptimisticWritePartialManagers::PER_COLUMN);
172508 void WriteNewRowGroup(OptimisticWriteCollection &row_groups);
172510 void WriteUnflushedRowGroups(OptimisticWriteCollection &row_groups);
172512 void FinalFlush();
172514 void Merge(OptimisticDataWriter &other);
172515 void Merge(unique_ptr<PartialBlockManager> &other_manager);
172517 void Rollback();
172518
172520 ClientContext &GetClientContext() {
172521 return context;
172522 }
172523
172524private:
172526 bool PrepareWrite();
172528 void FlushToDisk(OptimisticWriteCollection &collection, const vector<const_reference<RowGroup>> &row_groups,
172529 const vector<int64_t> &segment_indexes);
172530
172531private:
172533 ClientContext &context;
172535 DataTable &table;
172537 unique_ptr<PartialBlockManager> partial_manager;
172538};
172539
172540}
172541
172542
172543
172544
172545namespace duckdb {
172546class AttachedDatabase;
172547class Catalog;
172548class DataTable;
172549class StorageCommitState;
172550class Transaction;
172551class WriteAheadLog;
172552struct LocalAppendState;
172553struct TableAppendState;
172554
172555class LocalTableStorage : public enable_shared_from_this<LocalTableStorage> {
172556public:
172557
172558 explicit LocalTableStorage(ClientContext &context, DataTable &table);
172560 LocalTableStorage(ClientContext &context, DataTable &new_data_table, LocalTableStorage &parent,
172561 const idx_t alter_column_index, const LogicalType &target_type,
172562 const vector<StorageIndex> &bound_columns, Expression &cast_expr);
172564 LocalTableStorage(DataTable &new_data_table, LocalTableStorage &parent, const idx_t drop_column_index);
172565
172566 LocalTableStorage(ClientContext &context, DataTable &table, LocalTableStorage &parent, ColumnDefinition &new_column,
172567 ExpressionExecutor &default_executor);
172568 ~LocalTableStorage();
172569
172570 QueryContext context;
172571
172572 reference<DataTable> table_ref;
172573
172574 Allocator &allocator;
172576 unique_ptr<OptimisticWriteCollection> row_groups;
172578 TableIndexList append_indexes;
172580 TableIndexList delete_indexes;
172582 IndexAppendMode index_append_mode = IndexAppendMode::DEFAULT;
172584 idx_t deleted_rows;
172585
172587 vector<unique_ptr<OptimisticWriteCollection>> optimistic_collections;
172589 OptimisticDataWriter optimistic_writer;
172590
172592 bool is_dropped = false;
172593
172594public:
172595 void InitializeScan(CollectionScanState &state, optional_ptr<TableFilterSet> table_filters = nullptr);
172597 void WriteNewRowGroup();
172598 void FlushBlocks();
172599 void Rollback();
172600 idx_t EstimatedSize();
172601
172602 void AppendToIndexes(DuckTransaction &transaction, TableAppendState &append_state);
172603 void AppendToTable(DuckTransaction &transaction, TableAppendState &append_state);
172604 ErrorData AppendToIndexes(DuckTransaction &transaction, RowGroupCollection &source, TableIndexList &index_list,
172605 const vector<LogicalType> &table_types, row_t &start_row);
172606 void AppendToDeleteIndexes(Vector &row_ids, DataChunk &delete_chunk);
172607
172610 PhysicalIndex CreateOptimisticCollection(unique_ptr<OptimisticWriteCollection> collection);
172612 OptimisticWriteCollection &GetOptimisticCollection(const PhysicalIndex collection_index);
172614 void ResetOptimisticCollection(const PhysicalIndex collection_index);
172616 OptimisticDataWriter &GetOptimisticWriter();
172617
172618 RowGroupCollection &GetCollection();
172619 OptimisticWriteCollection &GetPrimaryCollection();
172620
172621private:
172622 mutex collections_lock;
172623};
172624
172625class LocalTableManager {
172626public:
172627 shared_ptr<LocalTableStorage> MoveEntry(DataTable &table);
172628 reference_map_t<DataTable, shared_ptr<LocalTableStorage>> MoveEntries();
172629 optional_ptr<LocalTableStorage> GetStorage(DataTable &table) const;
172630 LocalTableStorage &GetOrCreateStorage(ClientContext &context, DataTable &table);
172631 idx_t EstimatedSize()
const;
172632 bool IsEmpty() const;
172633 void InsertEntry(DataTable &table, shared_ptr<LocalTableStorage> entry);
172634
172635private:
172636 mutable mutex table_storage_lock;
172637 reference_map_t<DataTable, shared_ptr<LocalTableStorage>> table_storage;
172638};
172639
172641class LocalStorage {
172642public:
172643 struct CommitState {
172644 CommitState();
172645 ~CommitState();
172646
172647 reference_map_t<DataTable, unique_ptr<TableAppendState>> append_states;
172648 };
172649
172650public:
172651 explicit LocalStorage(ClientContext &context, DuckTransaction &transaction);
172652
172653 static LocalStorage &Get(DuckTransaction &transaction);
172654 static LocalStorage &Get(ClientContext &context, AttachedDatabase &db);
172655 static LocalStorage &Get(ClientContext &context, Catalog &catalog);
172656
172658 void InitializeScan(DataTable &table, CollectionScanState &state, optional_ptr<TableFilterSet> table_filters);
172660 void Scan(CollectionScanState &state, const vector<StorageIndex> &column_ids, DataChunk &result);
172661
172662 void InitializeParallelScan(DataTable &table, ParallelCollectionScanState &state);
172663 bool NextParallelScan(ClientContext &context, DataTable &table, ParallelCollectionScanState &state,
172664 CollectionScanState &scan_state);
172665
172667 void InitializeAppend(LocalAppendState &state, DataTable &table);
172669 void InitializeStorage(LocalAppendState &state, DataTable &table);
172671 static void Append(LocalAppendState &state, DataChunk &table_chunk, DataTableInfo &data_table_info);
172673 static void FinalizeAppend(LocalAppendState &state);
172675 void LocalMerge(DataTable &table, OptimisticWriteCollection &collection);
172678 PhysicalIndex CreateOptimisticCollection(DataTable &table, unique_ptr<OptimisticWriteCollection> collection);
172680 OptimisticWriteCollection &GetOptimisticCollection(DataTable &table, const PhysicalIndex collection_index);
172682 void ResetOptimisticCollection(DataTable &table, const PhysicalIndex collection_index);
172684 OptimisticDataWriter &GetOptimisticWriter(DataTable &table);
172685
172687 idx_t Delete(DataTable &table, Vector &row_ids, idx_t count);
172689 void Update(DataTable &table, Vector &row_ids, const vector<PhysicalIndex> &column_ids, DataChunk &data);
172690
172692 void Commit(optional_ptr<StorageCommitState> commit_state);
172694 void Rollback();
172695
172696 bool ChangesMade() noexcept;
172697 idx_t EstimatedSize();
172698
172699 void DropTable(DataTable &table);
172700 bool Find(DataTable &table);
172701
172702 idx_t AddedRows(DataTable &table);
172703 vector<PartitionStatistics> GetPartitionStats(DataTable &table) const;
172704
172705 void AddColumn(DataTable &old_dt, DataTable &new_dt, ColumnDefinition &new_column,
172706 ExpressionExecutor &default_executor);
172707 void DropColumn(DataTable &old_dt, DataTable &new_dt, const idx_t drop_column_index);
172708 void ChangeType(DataTable &old_dt, DataTable &new_dt, idx_t changed_idx, const LogicalType &target_type,
172709 const vector<StorageIndex> &bound_columns, Expression &cast_expr);
172710
172711 void MoveStorage(DataTable &old_dt, DataTable &new_dt);
172712 void FetchChunk(DataTable &table, const Vector &row_ids, idx_t count, const vector<StorageIndex> &col_ids,
172713 DataChunk &chunk, ColumnFetchState &fetch_state);
172715 bool CanFetch(DataTable &table, const row_t row_id);
172716 TableIndexList &GetIndexes(ClientContext &context, DataTable &table);
172717 optional_ptr<LocalTableStorage> GetStorage(DataTable &table);
172718
172719 void VerifyNewConstraint(DataTable &parent, const BoundConstraint &constraint);
172720
172721 ClientContext &GetClientContext() const {
172722 return context;
172723 }
172724
172725private:
172726 ClientContext &context;
172727 DuckTransaction &transaction;
172728 LocalTableManager table_manager;
172729
172730private:
172731 void Flush(DataTable &table, LocalTableStorage &storage, optional_ptr<StorageCommitState> commit_state);
172732};
172733
172734}
172735
172736
172737namespace duckdb {
172738
172739class BoundForeignKeyConstraint;
172740class ClientContext;
172741class ColumnDataCollection;
172742class ColumnDefinition;
172743class DataTable;
172744class DuckTransaction;
172745class RowGroup;
172746class StorageManager;
172747class TableCatalogEntry;
172748class TableIOManager;
172749class Transaction;
172750class WriteAheadLog;
172751class TableDataWriter;
172752class ConflictManager;
172753class TableScanState;
172754struct TableDeleteState;
172755struct ConstraintState;
172756struct TableUpdateState;
172757enum class VerifyExistenceType :
uint8_t;
172758struct OptimisticWriteCollection;
172759
172760enum class DataTableVersion {
172761 MAIN_TABLE,
172762 ALTERED,
172763 DROPPED
172764};
172765
172767class DataTable : public enable_shared_from_this<DataTable> {
172768public:
172770 DataTable(AttachedDatabase &db, shared_ptr<TableIOManager> table_io_manager, const string &schema,
172771 const string &table, vector<ColumnDefinition> column_definitions_p,
172772 unique_ptr<PersistentTableData> data = nullptr);
172774 DataTable(ClientContext &context, DataTable &parent, ColumnDefinition &new_column, Expression &default_value);
172776 DataTable(ClientContext &context, DataTable &parent, idx_t removed_column);
172778 DataTable(ClientContext &context, DataTable &parent, idx_t changed_idx, const LogicalType &target_type,
172779 const vector<StorageIndex> &bound_columns, Expression &cast_expr);
172781 DataTable(ClientContext &context, DataTable &parent, BoundConstraint &constraint);
172782
172784 AttachedDatabase &
db;
172785
172786public:
172787 AttachedDatabase &GetAttached();
172788 TableIOManager &GetTableIOManager();
172789
172790 bool IsTemporary() const;
172791
172793 vector<LogicalType> GetTypes();
172794 const vector<ColumnDefinition> &Columns() const;
172795
172796 void InitializeScan(ClientContext &context, DuckTransaction &transaction, TableScanState &state,
172797 const vector<StorageIndex> &column_ids, optional_ptr<TableFilterSet> table_filters = nullptr);
172798
172800 idx_t MaxThreads(ClientContext &context)
const;
172801 void InitializeParallelScan(ClientContext &context, ParallelTableScanState &state,
172802 const vector<ColumnIndex> &column_indexes);
172803 idx_t NextParallelScan(ClientContext &context, ParallelTableScanState &state, TableScanState &scan_state);
172804
172809 void Scan(DuckTransaction &transaction, DataChunk &result, TableScanState &state);
172810
172812 void Fetch(DuckTransaction &transaction, DataChunk &result, const vector<StorageIndex> &column_ids,
172813 const Vector &row_ids, idx_t fetch_count, ColumnFetchState &state);
172814 void FetchCommitted(DataChunk &result, const vector<StorageIndex> &column_ids, const Vector &row_identifiers,
172815 idx_t fetch_count, ColumnFetchState &state);
172817 bool CanFetch(DuckTransaction &transaction, const row_t row_id);
172818
172820 void InitializeLocalAppend(LocalAppendState &state, TableCatalogEntry &table, ClientContext &context,
172821 const vector<unique_ptr<BoundConstraint>> &bound_constraints);
172823 void InitializeLocalStorage(LocalAppendState &state, TableCatalogEntry &table, ClientContext &context,
172824 const vector<unique_ptr<BoundConstraint>> &bound_constraints);
172826 void LocalAppend(LocalAppendState &state, ClientContext &context, DataChunk &chunk, bool unsafe);
172828 void FinalizeLocalAppend(LocalAppendState &state);
172830 void LocalAppend(TableCatalogEntry &table, ClientContext &context, DataChunk &chunk,
172831 const vector<unique_ptr<BoundConstraint>> &bound_constraints, Vector &row_ids,
172832 DataChunk &delete_chunk);
172834 void LocalAppend(TableCatalogEntry &table, ClientContext &context, DataChunk &chunk,
172835 const vector<unique_ptr<BoundConstraint>> &bound_constraints);
172837 void LocalWALAppend(TableCatalogEntry &table, ClientContext &context, DataChunk &chunk,
172838 const vector<unique_ptr<BoundConstraint>> &bound_constraints);
172840 void LocalAppend(TableCatalogEntry &table, ClientContext &context, ColumnDataCollection &collection,
172841 const vector<unique_ptr<BoundConstraint>> &bound_constraints,
172842 optional_ptr<const vector<LogicalIndex>> column_ids);
172844 void LocalMerge(ClientContext &context, OptimisticWriteCollection &collection);
172847 PhysicalIndex CreateOptimisticCollection(ClientContext &context, unique_ptr<OptimisticWriteCollection> collection);
172849 OptimisticWriteCollection &GetOptimisticCollection(ClientContext &context, const PhysicalIndex collection_index);
172851 void ResetOptimisticCollection(ClientContext &context, const PhysicalIndex collection_index);
172853 OptimisticDataWriter &GetOptimisticWriter(ClientContext &context);
172854
172855 unique_ptr<TableDeleteState> InitializeDelete(TableCatalogEntry &table, ClientContext &context,
172856 const vector<unique_ptr<BoundConstraint>> &bound_constraints);
172858 idx_t Delete(TableDeleteState &state, ClientContext &context, Vector &row_ids, idx_t count);
172859
172860 unique_ptr<TableUpdateState> InitializeUpdate(TableCatalogEntry &table, ClientContext &context,
172861 const vector<unique_ptr<BoundConstraint>> &bound_constraints);
172863 void Update(TableUpdateState &state, ClientContext &context, Vector &row_ids,
172864 const vector<PhysicalIndex> &column_ids, DataChunk &data);
172874 void UpdateColumn(TableCatalogEntry &table, ClientContext &context, Vector &row_ids,
172875 const vector<column_t> &column_path, DataChunk &updates);
172876
172878 void AppendLock(DuckTransaction &transaction, TableAppendState &state);
172880 void InitializeAppend(DuckTransaction &transaction, TableAppendState &state);
172882 void Append(DataChunk &chunk, TableAppendState &state);
172884 void FinalizeAppend(DuckTransaction &transaction, TableAppendState &state);
172886 void CommitAppend(transaction_t commit_id, idx_t row_start, idx_t count);
172888 void WriteToLog(DuckTransaction &transaction, WriteAheadLog &log, idx_t row_start, idx_t count,
172889 optional_ptr<StorageCommitState> commit_state);
172892 void RevertAppend(DuckTransaction &transaction, idx_t start_row, idx_t count);
172893 void RevertAppendInternal(idx_t start_row);
172894
172895 void ScanTableSegment(DuckTransaction &transaction, idx_t start_row, idx_t count,
172896 const std::function<void(DataChunk &chunk)> &function);
172897
172899 void MergeStorage(RowGroupCollection &data, optional_ptr<StorageCommitState> commit_state);
172900
172903 static ErrorData AppendToIndexes(TableIndexList &indexes, optional_ptr<TableIndexList> delete_indexes,
172904 DataChunk &table_chunk, DataChunk &index_chunk,
172905 const vector<StorageIndex> &mapped_column_ids, row_t row_start,
172906 const IndexAppendMode index_append_mode, optional_idx active_checkpoint);
172907 ErrorData AppendToIndexes(optional_ptr<TableIndexList> delete_indexes, DataChunk &table_chunk,
172908 DataChunk &index_chunk, const vector<StorageIndex> &mapped_column_ids, row_t row_start,
172909 const IndexAppendMode index_append_mode);
172911 void RevertIndexAppend(TableAppendState &state, DataChunk &chunk, row_t row_start);
172913 void RevertIndexAppend(TableAppendState &state, DataChunk &chunk, Vector &row_identifiers);
172915 void RemoveFromIndexes(const QueryContext &context, Vector &row_identifiers, idx_t count,
172916 IndexRemovalType removal_type, optional_idx checkpoint_id = optional_idx());
172917
172918 void SetAsMainTable() {
172919 this->version = DataTableVersion::MAIN_TABLE;
172920 }
172921
172922 void SetAsDropped() {
172923 this->version = DataTableVersion::DROPPED;
172924 }
172925
172926 bool IsMainTable() const {
172927 return this->version == DataTableVersion::MAIN_TABLE;
172928 }
172929 bool IsRoot() const {
172930 return IsMainTable();
172931 }
172932 string TableModification() const;
172933
172935 unique_ptr<BaseStatistics> GetStatistics(ClientContext &context, const StorageIndex &column_id);
172936
172938 unique_ptr<BlockingSample> GetSample();
172940 void SetDistinct(column_t column_id, unique_ptr<DistinctStatistics> distinct_stats);
172941
172943 unique_ptr<StorageLockKey> GetCheckpointLock();
172945 void Checkpoint(TableDataWriter &writer, Serializer &serializer);
172946 void CommitDropTable();
172947 void CommitDropColumn(const idx_t column_index);
172948
172949 idx_t ColumnCount()
const;
172950 idx_t GetTotalRows()
const;
172951
172952 vector<ColumnSegmentInfo> GetColumnSegmentInfo(const QueryContext &context);
172953
172955 bool CreateIndexScan(TableScanState &state, DataChunk &result);
172958 bool IndexNameIsUnique(const string &name);
172959
172961 unique_ptr<ConstraintState> InitializeConstraintState(TableCatalogEntry &table,
172962 const vector<unique_ptr<BoundConstraint>> &bound_constraints);
172964 void VerifyAppendConstraints(ConstraintState &constraint_state, ClientContext &context, DataChunk &chunk,
172965 optional_ptr<LocalTableStorage> local_storage, optional_ptr<ConflictManager> manager);
172966
172967 shared_ptr<DataTableInfo> &GetDataTableInfo();
172968
172969 void BindIndexes(ClientContext &context);
172970 bool HasIndexes() const;
172971 bool HasUniqueIndexes() const;
172972 bool HasForeignKeyIndex(const vector<PhysicalIndex> &keys, ForeignKeyType type);
172973 void SetIndexStorageInfo(vector<IndexStorageInfo> index_storage_info);
172974 void VacuumIndexes();
172975 void VerifyIndexBuffers();
172976 void CleanupAppend(transaction_t lowest_transaction, idx_t start, idx_t count);
172977 void Destroy();
172978
172979 string GetTableName() const;
172980 void SetTableName(string new_name);
172981
172982 TableStorageInfo GetStorageInfo();
172983
172984 idx_t GetRowGroupSize()
const;
172985
172987 void VerifyUniqueIndexes(TableIndexList &indexes, optional_ptr<LocalTableStorage> storage, DataChunk &chunk,
172988 optional_ptr<ConflictManager> manager);
172991 void AddIndex(const ColumnList &columns, const vector<LogicalIndex> &column_indexes, const IndexConstraintType type,
172992 IndexStorageInfo index_info);
172994 void AddIndex(unique_ptr<Index> index);
172995
172997 vector<PartitionStatistics> GetPartitionStats(ClientContext &context);
172998
172999private:
173001 void VerifyNewConstraint(LocalStorage &local_storage, DataTable &parent, const BoundConstraint &constraint);
173002
173004 void VerifyUpdateConstraints(ConstraintState &state, ClientContext &context, DataChunk &chunk,
173005 const vector<PhysicalIndex> &column_ids);
173007 void VerifyDeleteConstraints(optional_ptr<LocalTableStorage> storage, TableDeleteState &state,
173008 ClientContext &context, DataChunk &chunk);
173009
173010 void InitializeScanWithOffset(DuckTransaction &transaction, TableScanState &state,
173011 const vector<StorageIndex> &column_ids, idx_t start_row, idx_t end_row);
173012
173014 void RebuildIndexes();
173015
173016 void VerifyForeignKeyConstraint(optional_ptr<LocalTableStorage> storage,
173017 const BoundForeignKeyConstraint &bound_foreign_key, ClientContext &context,
173018 DataChunk &chunk, VerifyExistenceType type);
173019 void VerifyAppendForeignKeyConstraint(optional_ptr<LocalTableStorage> storage,
173020 const BoundForeignKeyConstraint &bound_foreign_key, ClientContext &context,
173021 DataChunk &chunk);
173022 void VerifyDeleteForeignKeyConstraint(optional_ptr<LocalTableStorage> storage,
173023 const BoundForeignKeyConstraint &bound_foreign_key, ClientContext &context,
173024 DataChunk &chunk);
173025
173026private:
173028 shared_ptr<DataTableInfo> info;
173030 vector<ColumnDefinition> column_definitions;
173032 mutex append_lock;
173034 shared_ptr<RowGroupCollection> row_groups;
173036 atomic<DataTableVersion> version;
173037};
173038}
173039
173040#include <functional>
173041#include <map>
173042
173043namespace duckdb {
173044class Optimizer;
173045
173046enum class ValueComparisonResult { PRUNE_LEFT, PRUNE_RIGHT, UNSATISFIABLE_CONDITION, PRUNE_NOTHING };
173047enum class FilterResult { UNSATISFIABLE, SUCCESS, UNSUPPORTED };
173048enum class FilterPushdownResult { NO_PUSHDOWN, PUSHED_DOWN_PARTIALLY, PUSHED_DOWN_FULLY };
173049
173055class FilterCombiner {
173056public:
173057 explicit FilterCombiner(ClientContext &context);
173058 explicit FilterCombiner(Optimizer &optimizer);
173059
173060 ClientContext &context;
173061
173062public:
173063 struct ExpressionValueInformation {
173064 Value constant;
173065 ExpressionType comparison_type;
173066 };
173067
173068 FilterResult AddFilter(unique_ptr<Expression> expr);
173069
173072 static bool IsDenseRange(vector<Value> &in_list);
173073 static bool ContainsNull(vector<Value> &in_list);
173074 static bool FindNextLegalUTF8(string &prefix_string);
173075
173076 void GenerateFilters(const std::function<void(unique_ptr<Expression> filter)> &callback);
173077 bool HasFilters();
173078 TableFilterSet GenerateTableScanFilters(const vector<ColumnIndex> &column_ids,
173079 vector<FilterPushdownResult> &pushdown_results);
173080
173081 FilterPushdownResult TryPushdownGenericExpression(LogicalGet &
get, Expression &expr);
173082
173083private:
173084 FilterResult AddFilter(Expression &expr);
173085 FilterResult AddBoundComparisonFilter(Expression &expr);
173086 FilterResult AddTransitiveFilters(BoundComparisonExpression &comparison, bool is_root = true);
173087 unique_ptr<Expression> FindTransitiveFilter(Expression &expr);
173088 Expression &GetNode(Expression &expr);
173089 idx_t GetEquivalenceSet(Expression &expr);
173090 FilterResult AddConstantComparison(vector<ExpressionValueInformation> &info_list, ExpressionValueInformation info);
173091
173092 FilterPushdownResult TryPushdownConstantFilter(TableFilterSet &table_filters, const vector<ColumnIndex> &column_ids,
173093 column_t column_id, vector<ExpressionValueInformation> &info_list);
173094 FilterPushdownResult TryPushdownExpression(TableFilterSet &table_filters, const vector<ColumnIndex> &column_ids,
173095 Expression &expr);
173096 FilterPushdownResult TryPushdownPrefixFilter(TableFilterSet &table_filters, const vector<ColumnIndex> &column_ids,
173097 Expression &expr);
173098 FilterPushdownResult TryPushdownLikeFilter(TableFilterSet &table_filters, const vector<ColumnIndex> &column_ids,
173099 Expression &expr);
173100 FilterPushdownResult TryPushdownInFilter(TableFilterSet &table_filters, const vector<ColumnIndex> &column_ids,
173101 Expression &expr);
173102 FilterPushdownResult TryPushdownOrClause(TableFilterSet &table_filters, const vector<ColumnIndex> &column_ids,
173103 Expression &expr);
173104
173105private:
173106 vector<unique_ptr<Expression>> remaining_filters;
173107
173108 expression_map_t<unique_ptr<Expression>> stored_expressions;
173109 expression_map_t<idx_t> equivalence_set_map;
173110 map<idx_t, vector<ExpressionValueInformation>> constant_values;
173111 map<idx_t, vector<reference<Expression>>> equivalence_map;
173112 idx_t set_index = 0;
173113};
173114
173115}
173116
173117
173118
173119
173120
173121
173122
173123
173124
173125
173126
173127
173128
173129
173130
173131
173132
173133
173134
173135
173136namespace duckdb {
173137
173138class Optimizer;
173139class ClientContext;
173140class LogicalOperator;
173141class TableFilter;
173142struct BoundOrderByNode;
173143
173144class StatisticsPropagator {
173145public:
173146 StatisticsPropagator(Optimizer &optimizer, LogicalOperator &root);
173147
173148 unique_ptr<NodeStatistics> PropagateStatistics(unique_ptr<LogicalOperator> &node_ptr);
173149
173150 column_binding_map_t<unique_ptr<BaseStatistics>> GetStatisticsMap() {
173151 return std::move(statistics_map);
173152 }
173153
173155 static bool CanPropagateCast(const LogicalType &source, const LogicalType &target);
173156 static unique_ptr<BaseStatistics> TryPropagateCast(const BaseStatistics &stats, const LogicalType &source,
173157 const LogicalType &target);
173158
173159private:
173161 unique_ptr<NodeStatistics> PropagateStatistics(LogicalOperator &node, unique_ptr<LogicalOperator> &node_ptr);
173162
173163 unique_ptr<NodeStatistics> PropagateStatistics(LogicalFilter &op, unique_ptr<LogicalOperator> &node_ptr);
173164 unique_ptr<NodeStatistics> PropagateStatistics(LogicalGet &op, unique_ptr<LogicalOperator> &node_ptr);
173165 unique_ptr<NodeStatistics> PropagateStatistics(LogicalJoin &op, unique_ptr<LogicalOperator> &node_ptr);
173166 unique_ptr<NodeStatistics> PropagateStatistics(LogicalPositionalJoin &op, unique_ptr<LogicalOperator> &node_ptr);
173167 unique_ptr<NodeStatistics> PropagateStatistics(LogicalProjection &op, unique_ptr<LogicalOperator> &node_ptr);
173168 void PropagateStatistics(LogicalComparisonJoin &op, unique_ptr<LogicalOperator> &node_ptr);
173169 void PropagateStatistics(LogicalAnyJoin &op, unique_ptr<LogicalOperator> &node_ptr);
173170 unique_ptr<NodeStatistics> PropagateStatistics(LogicalSetOperation &op, unique_ptr<LogicalOperator> &node_ptr);
173171 unique_ptr<NodeStatistics> PropagateStatistics(LogicalAggregate &op, unique_ptr<LogicalOperator> &node_ptr);
173172 unique_ptr<NodeStatistics> PropagateStatistics(LogicalCrossProduct &op, unique_ptr<LogicalOperator> &node_ptr);
173173 unique_ptr<NodeStatistics> PropagateStatistics(LogicalLimit &op, unique_ptr<LogicalOperator> &node_ptr);
173174 unique_ptr<NodeStatistics> PropagateStatistics(LogicalOrder &op, unique_ptr<LogicalOperator> &node_ptr);
173175 unique_ptr<NodeStatistics> PropagateStatistics(LogicalWindow &op, unique_ptr<LogicalOperator> &node_ptr);
173176
173177 unique_ptr<NodeStatistics> PropagateChildren(LogicalOperator &node, unique_ptr<LogicalOperator> &node_ptr);
173178
173180 unique_ptr<BaseStatistics> StatisticsFromValue(const Value &input);
173182 FilterPropagateResult PropagateComparison(BaseStatistics &left, BaseStatistics &right, ExpressionType comparison);
173183
173185 void UpdateFilterStatistics(BaseStatistics &input, ExpressionType comparison_type, const Value &constant);
173187 void UpdateFilterStatistics(BaseStatistics &lstats, BaseStatistics &rstats, ExpressionType comparison_type);
173189 void UpdateFilterStatistics(Expression &left, Expression &right, ExpressionType comparison_type);
173191 void UpdateFilterStatistics(Expression &condition);
173193 void SetStatisticsNotNull(ColumnBinding binding);
173195 FilterPropagateResult HandleFilter(unique_ptr<Expression> &condition);
173196
173198 FilterPropagateResult PropagateTableFilter(ColumnBinding stats_binding, BaseStatistics &stats, TableFilter &filter);
173200 void UpdateFilterStatistics(BaseStatistics &input, const TableFilter &filter);
173201
173203 void AddCardinalities(unique_ptr<NodeStatistics> &stats, NodeStatistics &new_stats);
173206 void MultiplyCardinalities(unique_ptr<NodeStatistics> &stats, NodeStatistics &new_stats);
173208 void CreateFilterFromJoinStats(unique_ptr<LogicalOperator> &child, unique_ptr<Expression> &expr,
173209 const BaseStatistics &stats_before, const BaseStatistics &stats_after);
173210
173211 unique_ptr<BaseStatistics> PropagateExpression(unique_ptr<Expression> &expr);
173212 unique_ptr<BaseStatistics> PropagateExpression(Expression &expr, unique_ptr<Expression> &expr_ptr);
173214 unique_ptr<BaseStatistics> PropagateExpression(BoundAggregateExpression &expr, unique_ptr<Expression> &expr_ptr);
173215 unique_ptr<BaseStatistics> PropagateExpression(BoundBetweenExpression &expr, unique_ptr<Expression> &expr_ptr);
173216 unique_ptr<BaseStatistics> PropagateExpression(BoundCaseExpression &expr, unique_ptr<Expression> &expr_ptr);
173217 unique_ptr<BaseStatistics> PropagateExpression(BoundCastExpression &expr, unique_ptr<Expression> &expr_ptr);
173218 unique_ptr<BaseStatistics> PropagateExpression(BoundConjunctionExpression &expr, unique_ptr<Expression> &expr_ptr);
173219 unique_ptr<BaseStatistics> PropagateExpression(BoundFunctionExpression &expr, unique_ptr<Expression> &expr_ptr);
173220 unique_ptr<BaseStatistics> PropagateExpression(BoundComparisonExpression &expr, unique_ptr<Expression> &expr_ptr);
173221 unique_ptr<BaseStatistics> PropagateExpression(BoundConstantExpression &expr, unique_ptr<Expression> &expr_ptr);
173222 unique_ptr<BaseStatistics> PropagateExpression(BoundColumnRefExpression &expr, unique_ptr<Expression> &expr_ptr);
173223 unique_ptr<BaseStatistics> PropagateExpression(BoundOperatorExpression &expr, unique_ptr<Expression> &expr_ptr);
173224
173226 void TryExecuteAggregates(LogicalAggregate &op, unique_ptr<LogicalOperator> &node_ptr);
173227 void ReplaceWithEmptyResult(unique_ptr<LogicalOperator> &node);
173228
173229 bool ExpressionIsConstant(Expression &expr, const Value &val);
173230 bool ExpressionIsConstantOrNull(Expression &expr, const Value &val);
173231
173232 unique_ptr<NodeStatistics> PropagateUnion(LogicalSetOperation &setop, unique_ptr<LogicalOperator> &node_ptr);
173233
173234private:
173235 Optimizer &optimizer;
173236 ClientContext &context;
173238 optional_ptr<LogicalOperator> root;
173240 column_binding_map_t<unique_ptr<BaseStatistics>> statistics_map;
173242 unique_ptr<NodeStatistics> node_stats;
173243};
173244
173245}
173246
173247
173248
173249
173250
173251
173252
173253
173254
173255
173256
173257
173258
173259
173260#include <functional>
173261
173262namespace duckdb {
173263
173264class ExpressionIterator {
173265public:
173266 static void EnumerateChildren(const Expression &expression,
173267 const std::function<void(const Expression &child)> &callback);
173268 static void EnumerateChildren(Expression &expression, const std::function<void(Expression &child)> &callback);
173269 static void EnumerateChildren(Expression &expression,
173270 const std::function<void(unique_ptr<Expression> &child)> &callback);
173271
173272 static void EnumerateExpression(unique_ptr<Expression> &expr,
173273 const std::function<void(Expression &child)> &callback);
173274 static void EnumerateExpression(unique_ptr<Expression> &expr,
173275 const std::function<void(unique_ptr<Expression> &child)> &callback);
173276
173277 static void VisitExpressionClass(const Expression &expr, ExpressionClass expr_class,
173278 const std::function<void(const Expression &child)> &callback);
173279 static void VisitExpressionClassMutable(unique_ptr<Expression> &expr, ExpressionClass expr_class,
173280 const std::function<void(unique_ptr<Expression> &child)> &callback);
173281
173282 template <class T>
173283 static void VisitExpressionMutable(unique_ptr<Expression> &expr,
173284 const std::function<void(T &child, unique_ptr<Expression> &)> &callback) {
173285 VisitExpressionClassMutable(expr, T::TYPE,
173286 [&](unique_ptr<Expression> &child) { callback(child->Cast<T>(), child); });
173287 }
173288 template <class T>
173289 static void VisitExpression(const Expression &expr, const std::function<void(const T &child)> &callback) {
173290 VisitExpressionClass(expr, T::TYPE, [&](const Expression &child) { callback(child.Cast<T>()); });
173291 }
173292};
173293
173294}
173295
173296
173297
173298
173299
173300#include <iostream>
173301
173302namespace duckdb {
173303struct MultiFilePushdownInfo;
173304
173305struct HivePartitioningFilterInfo {
173306 unordered_map<string, column_t> column_map;
173307 bool hive_enabled;
173308 bool filename_enabled;
173309};
173310
173311class HivePartitioning {
173312public:
173314 DUCKDB_API static std::map<string, string> Parse(const string &filename);
173318 DUCKDB_API static void ApplyFiltersToFileList(ClientContext &context, vector<OpenFileInfo> &files,
173319 vector<unique_ptr<Expression>> &filters,
173320 const HivePartitioningFilterInfo &filter_info,
173321 MultiFilePushdownInfo &info);
173322
173323 DUCKDB_API static Value GetValue(ClientContext &context, const string &key, const string &value,
173324 const LogicalType &type);
173326 DUCKDB_API static string Escape(const string &input);
173328 DUCKDB_API static string Unescape(const string &input);
173330 DUCKDB_API static bool IsNull(const string &input);
173331};
173332
173333struct HivePartitionKey {
173335 vector<Value> values;
173338
173339 struct Hash {
173340 std::size_t
operator()(
const HivePartitionKey &k)
const {
173341 return k.hash;
173342 }
173343 };
173344
173345 struct Equality {
173346 bool operator()(
const HivePartitionKey &a,
const HivePartitionKey &b)
const {
173347 if (a.values.size() != b.values.size()) {
173348 return false;
173349 }
173350 for (idx_t i = 0; i < a.values.size(); i++) {
173352 return false;
173353 }
173354 }
173355 return true;
173356 }
173357 };
173358};
173359
173361typedef unordered_map<HivePartitionKey, idx_t, HivePartitionKey::Hash, HivePartitionKey::Equality>
hive_partition_map_t;
173362
173365class GlobalHivePartitionState {
173366public:
173367 mutex lock;
173369};
173370
173371class HivePartitionedColumnData : public PartitionedColumnData {
173372public:
173373 HivePartitionedColumnData(ClientContext &context, vector<LogicalType> types, vector<idx_t> partition_by_cols,
173374 shared_ptr<GlobalHivePartitionState> global_state = nullptr);
173375 void ComputePartitionIndices(PartitionedColumnDataAppendState &state, DataChunk &input) override;
173376
173378 std::map<idx_t, const HivePartitionKey *> GetReverseMap();
173379
173380protected:
173382 idx_t RegisterNewPartition(HivePartitionKey key, PartitionedColumnDataAppendState &state);
173384 void AddNewPartition(HivePartitionKey key, idx_t partition_id, PartitionedColumnDataAppendState &state);
173385
173386private:
173387 void InitializeKeys();
173388
173389protected:
173391 shared_ptr<GlobalHivePartitionState> global_state;
173395 vector<idx_t> group_by_columns;
173397 Vector hashes_v;
173399 vector<HivePartitionKey> keys;
173400};
173401
173402}
173403
173404
173405
173406
173407namespace duckdb {
173408struct BindInfo;
173409class MultiFileList;
173410
173411enum class MultiFileColumnMappingMode :
uint8_t { BY_NAME, BY_FIELD_ID };
173412
173413struct MultiFileOptions {
173414 bool filename = false;
173415 bool hive_partitioning = false;
173416 bool auto_detect_hive_partitioning = true;
173417 bool union_by_name = false;
173418 bool hive_types_autocast = true;
173419 MultiFileColumnMappingMode mapping = MultiFileColumnMappingMode::BY_NAME;
173420
173421 case_insensitive_map_t<LogicalType> hive_types_schema;
173422
173423
173424 static constexpr const char *DEFAULT_FILENAME_COLUMN = "filename";
173425 string filename_column = DEFAULT_FILENAME_COLUMN;
173426
173427 case_insensitive_map_t<Value> custom_options;
173428
173429 DUCKDB_API void Serialize(Serializer &serializer) const;
173430 DUCKDB_API static MultiFileOptions Deserialize(Deserializer &source);
173431 DUCKDB_API void AddBatchInfo(BindInfo &bind_info) const;
173432 DUCKDB_API void AutoDetectHivePartitioning(MultiFileList &files, ClientContext &context);
173433 DUCKDB_API static bool AutoDetectHivePartitioningInternal(MultiFileList &files, ClientContext &context);
173434 DUCKDB_API void AutoDetectHiveTypesInternal(MultiFileList &files, ClientContext &context);
173435 DUCKDB_API void VerifyHiveTypesArePartitions(const std::map<string, string> &partitions) const;
173436 DUCKDB_API LogicalType GetHiveLogicalType(const string &hive_partition_column) const;
173437 DUCKDB_API Value GetHivePartitionValue(const string &base, const string &entry, ClientContext &context) const;
173438 DUCKDB_API bool AnySet() const;
173439};
173440
173441}
173442
173443
173444
173445
173446
173447
173448
173449
173450
173451
173452
173453
173454namespace duckdb {
173457struct SetColumns {
173458 SetColumns(const vector<LogicalType> *types_p, const vector<string> *names_p);
173459 SetColumns();
173461 const vector<LogicalType> *types = nullptr;
173463 const vector<string> *names = nullptr;
173465 bool IsSet() const;
173469 bool IsCandidateUnacceptable(const idx_t num_cols, bool null_padding, bool ignore_errors,
173470 bool last_value_always_empty) const;
173471
173472 string ToString() const;
173473};
173474
173475}
173476
173477
173478namespace duckdb {
173479
173480struct DialectOptions {
173481 CSVStateMachineOptions state_machine_options;
173483 idx_t num_cols = 0;
173485 CSVOption<bool> header = false;
173487 map<LogicalTypeId, CSVOption<StrpTimeFormat>> date_format = {{LogicalTypeId::DATE, {}},
173488 {LogicalTypeId::TIMESTAMP, {}}};
173490 CSVOption<idx_t> skip_rows = 0;
173491 idx_t rows_until_header = 0;
173492};
173493
173494struct CSVReaderOptions {
173495 CSVReaderOptions() {
173496 }
173497 CSVReaderOptions(CSVOption<char> single_byte_delimiter, const CSVOption<string> &multi_byte_delimiter);
173498
173499
173500
173502 DialectOptions dialect_options;
173504 CSVOption<bool> ignore_errors = false;
173506 CSVOption<bool> store_rejects = false;
173508 CSVOption<string> rejects_table_name = {"reject_errors"};
173510 CSVOption<string> rejects_scan_name = {"reject_scans"};
173512 idx_t rejects_limit = 0;
173514 idx_t buffer_sample_size =
static_cast<idx_t>(STANDARD_VECTOR_SIZE * 50);
173516 vector<string> null_str = {""};
173519 FileCompressionType compression = FileCompressionType::AUTO_DETECT;
173521 bool allow_quoted_nulls = true;
173522 char comment = '\0';
173523
173525 char thousands_separator = '\0';
173526
173527
173528
173529
173531 case_insensitive_map_t<idx_t> sql_types_per_column;
173533 vector<LogicalType> sql_type_list;
173535 vector<string> name_list;
173537 bool columns_set = false;
173539 vector<LogicalType> auto_type_candidates = {
173540 LogicalType::VARCHAR, LogicalType::DOUBLE, LogicalType::BIGINT,
173541 LogicalType::TIMESTAMP_TZ, LogicalType::TIMESTAMP, LogicalType::DATE,
173542 LogicalType::TIME, LogicalType::BOOLEAN, LogicalType::SQLNULL};
173544 string sniffer_user_mismatch_error;
173546 vector<bool> was_type_manually_set;
173547
173548
173549
173552 static constexpr idx_t max_line_size_default = 2000000;
173553 CSVOption<idx_t> maximum_line_size = max_line_size_default;
173555 bool normalize_names = false;
173557 unordered_set<string> force_not_null_names;
173559 vector<bool> force_not_null;
173561 static constexpr idx_t sniff_size = 2048;
173562
173565 int64_t files_to_sniff = 10;
173566
173568 idx_t sample_size_chunks = 20480 / sniff_size;
173570 bool all_varchar = false;
173572 bool auto_detect = true;
173574 string file_path;
173576 CSVOption<idx_t> buffer_size_option = CSVBuffer::ROWS_PER_BUFFER * max_line_size_default;
173578 string decimal_separator = ".";
173580 bool null_padding = false;
173582 bool parallel = true;
173583
173585 string encoding = "utf-8";
173587 map<string, string> user_defined_parameters;
173588
173590 string GetUserDefinedParameters() const;
173591
173592
173593
173594
173596 vector<bool> force_quote;
173598 string prefix;
173599 string suffix;
173600 string write_newline;
173601
173603 map<LogicalTypeId, Value> write_date_format = {{LogicalTypeId::DATE, Value()}, {LogicalTypeId::TIMESTAMP, Value()}};
173605 map<LogicalTypeId, bool> has_format = {{LogicalTypeId::DATE, false}, {LogicalTypeId::TIMESTAMP, false}};
173607 bool multi_file_reader = false;
173608
173609 void SetCompression(const string &compression);
173610
173611 bool GetHeader() const;
173612 void SetHeader(bool has_header);
173613
173614 string GetEscape() const;
173615 void SetEscape(const string &escape);
173616
173617 idx_t GetSkipRows()
const;
173618 void SetSkipRows(int64_t
rows);
173619
173620 void SetQuote(const string "e);
173621 string GetQuote() const;
173622 void SetComment(const string &comment);
173623 string GetComment() const;
173624 void SetDelimiter(const string &delimiter);
173625 string GetDelimiter() const;
173626
173628 bool IgnoreErrors() const;
173629
173630 string GetNewline() const;
173631 void SetNewline(const string &input);
173632
173633 bool GetRFC4180() const;
173634 void SetRFC4180(bool rfc4180);
173635
173636 CSVOption<char> GetSingleByteDelimiter() const;
173637 CSVOption<string> GetMultiByteDelimiter() const;
173638
173641 bool SetBaseOption(const string &loption, const Value &value, bool write_option = false);
173642
173646 void SetReadOption(const string &loption, const Value &value, vector<string> &expected_names);
173647 void SetWriteOption(const string &loption, const Value &value);
173648 void SetDateFormat(LogicalTypeId type,
const string &
format,
bool read_format);
173649 void ToNamedParameters(named_parameter_map_t &out) const;
173650 void FromNamedParameters(const named_parameter_map_t &in, ClientContext &context, MultiFileOptions &file_options);
173651 void ParseOption(ClientContext &context, const string &key, const Value &val);
173653 void Verify(MultiFileOptions &file_options);
173654
173655 string ToString(
const String ¤t_file_path)
const;
173657 bool WasTypeManuallySet(idx_t i) const;
173658
173659 string NewLineIdentifierToString() const {
173660 switch (dialect_options.state_machine_options.new_line.GetValue()) {
173661 case NewLineIdentifier::SINGLE_N:
173662 return "\\n";
173663 case NewLineIdentifier::SINGLE_R:
173664 return "\\r";
173665 case NewLineIdentifier::CARRY_ON:
173666 return "\\r\\n";
173667 default:
173668 return "";
173669 }
173670 }
173671};
173672}
173673
173674
173675namespace duckdb {
173676
173677class Deserializer {
173678protected:
173679 bool deserialize_enum_from_string = false;
173680 SerializationData data;
173681
173682public:
173683 virtual ~Deserializer() {
173684 }
173685
173686 class List {
173687 friend Deserializer;
173688
173689 private:
173690 Deserializer &deserializer;
173691 explicit List(Deserializer &deserializer) : deserializer(deserializer) {
173692 }
173693
173694 public:
173695
173696 template <class T>
173697 T ReadElement();
173698
173700 template <class T>
173701 void ReadElement(data_ptr_t &ptr, idx_t size);
173702
173703
173704 template <class FUNC>
173705 void ReadObject(FUNC f);
173706 };
173707
173708public:
173709 virtual bool CanDeserializeProperty(const field_id_t field_id, const char *tag) = 0;
173710
173711
173712 template <typename T>
173713 inline void ReadProperty(const field_id_t field_id, const char *tag, T &ret) {
173714 OnPropertyBegin(field_id, tag);
173715 ret = Read<T>();
173716 OnPropertyEnd();
173717 }
173718
173719
173720 template <typename T>
173721 inline T ReadProperty(const field_id_t field_id, const char *tag) {
173722 OnPropertyBegin(field_id, tag);
173723 auto ret = Read<T>();
173724 OnPropertyEnd();
173725 return ret;
173726 }
173727
173728
173729 template <typename T>
173730 inline T ReadPropertyWithDefault(const field_id_t field_id, const char *tag) {
173731 if (!OnOptionalPropertyBegin(field_id, tag)) {
173732 OnOptionalPropertyEnd(false);
173733 return std::forward<T>(SerializationDefaultValue::GetDefault<T>());
173734 }
173735 auto ret = Read<T>();
173736 OnOptionalPropertyEnd(true);
173737 return ret;
173738 }
173739
173740 template <typename T>
173741 inline T ReadPropertyWithExplicitDefault(const field_id_t field_id, const char *tag, T default_value) {
173742 if (!OnOptionalPropertyBegin(field_id, tag)) {
173743 OnOptionalPropertyEnd(false);
173744 return std::forward<T>(default_value);
173745 }
173746 auto ret = Read<T>();
173747 OnOptionalPropertyEnd(true);
173748 return ret;
173749 }
173750
173751
173752 template <typename T>
173753 inline void ReadPropertyWithDefault(const field_id_t field_id, const char *tag, T &ret) {
173754 if (!OnOptionalPropertyBegin(field_id, tag)) {
173755 ret = std::forward<T>(SerializationDefaultValue::GetDefault<T>());
173756 OnOptionalPropertyEnd(false);
173757 return;
173758 }
173759 ret = Read<T>();
173760 OnOptionalPropertyEnd(true);
173761 }
173762
173763 template <typename T>
173764 inline void ReadPropertyWithExplicitDefault(const field_id_t field_id, const char *tag, T &ret, T default_value) {
173765 if (!OnOptionalPropertyBegin(field_id, tag)) {
173766 ret = std::forward<T>(default_value);
173767 OnOptionalPropertyEnd(false);
173768 return;
173769 }
173770 ret = Read<T>();
173771 OnOptionalPropertyEnd(true);
173772 }
173773
173774 template <typename T>
173775 inline void ReadPropertyWithExplicitDefault(const field_id_t field_id, const char *tag, CSVOption<T> &ret,
173776 T default_value) {
173777 if (!OnOptionalPropertyBegin(field_id, tag)) {
173778 ret = std::forward<T>(default_value);
173779 OnOptionalPropertyEnd(false);
173780 return;
173781 }
173782 ret = Read<T>();
173783 OnOptionalPropertyEnd(true);
173784 }
173785
173786
173787
173788 inline void ReadProperty(const field_id_t field_id, const char *tag, data_ptr_t ret, idx_t count) {
173789 OnPropertyBegin(field_id, tag);
173790 ReadDataPtr(ret, count);
173791 OnPropertyEnd();
173792 }
173793
173794
173795 template <typename T>
173796 inline void ReadDeletedProperty(const field_id_t field_id, const char *tag) {
173797
173798 if (!OnOptionalPropertyBegin(field_id, tag)) {
173799 OnOptionalPropertyEnd(false);
173800 return;
173801 }
173802
173803 (void)Read<T>();
173804 OnOptionalPropertyEnd(true);
173805 }
173806
173808 template <class T>
173809 void Set(T entry) {
173810 return data.Set<T>(entry);
173811 }
173812
173814 template <class T>
173815 T Get() {
173816 return data.Get<T>();
173817 }
173818
173819 template <class T>
173820 optional_ptr<T> TryGet() {
173821 return data.TryGet<T>();
173822 }
173823
173825 template <class T>
173826 void Unset() {
173827 return data.Unset<T>();
173828 }
173829
173830 SerializationData &GetSerializationData() {
173831 return data;
173832 }
173833
173834 void SetSerializationData(const SerializationData &other) {
173835 data = other;
173836 }
173837
173838 template <class FUNC>
173839 void ReadListInternal(FUNC func) {
173840 auto size = OnListBegin();
173841 List list {*this};
173842 for (idx_t i = 0; i <
size; i++) {
173843 func(list, i);
173844 }
173845 OnListEnd();
173846 }
173847
173848 template <class FUNC>
173849 void ReadList(const field_id_t field_id, const char *tag, FUNC func) {
173850 OnPropertyBegin(field_id, tag);
173851 ReadListInternal(func);
173852 OnPropertyEnd();
173853 }
173854
173855 template <class FUNC>
173856 void ReadOptionalList(const field_id_t field_id, const char *tag, FUNC func) {
173857 if (!OnOptionalPropertyBegin(field_id, tag)) {
173858 OnOptionalPropertyEnd(false);
173859 return;
173860 }
173861 ReadListInternal(func);
173862 OnOptionalPropertyEnd(true);
173863 }
173864
173865 template <class FUNC>
173866 void ReadObject(const field_id_t field_id, const char *tag, FUNC func) {
173867 OnPropertyBegin(field_id, tag);
173868 OnObjectBegin();
173869 func(*this);
173870 OnObjectEnd();
173871 OnPropertyEnd();
173872 }
173873
173874private:
173875
173876 template <typename T = void>
173877 inline typename std::enable_if<has_deserialize<T>::value, T>::type Read() {
173878 OnObjectBegin();
173879 auto val = T::Deserialize(*this);
173880 OnObjectEnd();
173881 return val;
173882 }
173883
173884
173885 template <class T, typename ELEMENT_TYPE = typename is_optionally_owned_ptr<T>::ELEMENT_TYPE>
173886 inline typename std::enable_if<is_optionally_owned_ptr<T>::value, T>::type Read() {
173887 return optionally_owned_ptr<ELEMENT_TYPE>(Read<unique_ptr<ELEMENT_TYPE>>());
173888 }
173889
173890
173891 template <class T, typename ELEMENT_TYPE = typename is_unique_ptr<T>::ELEMENT_TYPE>
173892 inline typename std::enable_if<is_unique_ptr<T>::value && has_deserialize<ELEMENT_TYPE>::value, T>::type Read() {
173893 unique_ptr<ELEMENT_TYPE> ptr = nullptr;
173894 auto is_present = OnNullableBegin();
173895 if (is_present) {
173896 OnObjectBegin();
173897 ptr = ELEMENT_TYPE::Deserialize(*this);
173898 OnObjectEnd();
173899 }
173900 OnNullableEnd();
173901 return ptr;
173902 }
173903
173904
173905 template <class T, typename ELEMENT_TYPE = typename is_unique_ptr<T>::ELEMENT_TYPE>
173906 inline typename std::enable_if<is_unique_ptr<T>::value && !has_deserialize<ELEMENT_TYPE>::value, T>::type Read() {
173907 unique_ptr<ELEMENT_TYPE> ptr = nullptr;
173908 auto is_present = OnNullableBegin();
173909 if (is_present) {
173910 OnObjectBegin();
173911 ptr = make_uniq<ELEMENT_TYPE>(Read<ELEMENT_TYPE>());
173912 OnObjectEnd();
173913 }
173914 OnNullableEnd();
173915 return ptr;
173916 }
173917
173918
173919 template <typename T = void>
173920 inline typename std::enable_if<is_shared_ptr<T>::value, T>::type Read() {
173921 using ELEMENT_TYPE = typename is_shared_ptr<T>::ELEMENT_TYPE;
173922 shared_ptr<ELEMENT_TYPE> ptr = nullptr;
173923 auto is_present = OnNullableBegin();
173924 if (is_present) {
173925 OnObjectBegin();
173926 ptr = ELEMENT_TYPE::Deserialize(*this);
173927 OnObjectEnd();
173928 }
173929 OnNullableEnd();
173930 return ptr;
173931 }
173932
173933
173934 template <typename T = void>
173935 inline typename std::enable_if<is_vector<T>::value, T>::type Read() {
173936 using ELEMENT_TYPE = typename is_vector<T>::ELEMENT_TYPE;
173937 T vec;
173938 auto size = OnListBegin();
173939 for (idx_t i = 0; i <
size; i++) {
173940 vec.push_back(Read<ELEMENT_TYPE>());
173941 }
173942 OnListEnd();
173943 return vec;
173944 }
173945
173946 template <typename T = void>
173947 inline typename std::enable_if<is_unsafe_vector<T>::value, T>::type Read() {
173948 using ELEMENT_TYPE = typename is_unsafe_vector<T>::ELEMENT_TYPE;
173949 T vec;
173950 auto size = OnListBegin();
173951 for (idx_t i = 0; i <
size; i++) {
173952 vec.push_back(Read<ELEMENT_TYPE>());
173953 }
173954 OnListEnd();
173955
173956 return vec;
173957 }
173958
173959
173960 template <typename T = void>
173961 inline typename std::enable_if<is_unordered_map<T>::value, T>::type Read() {
173962 using KEY_TYPE = typename is_unordered_map<T>::KEY_TYPE;
173963 using VALUE_TYPE = typename is_unordered_map<T>::VALUE_TYPE;
173964
173965 T map;
173966 auto size = OnListBegin();
173967 for (idx_t i = 0; i <
size; i++) {
173968 OnObjectBegin();
173969 auto key = ReadProperty<KEY_TYPE>(0, "key");
173970 auto value = ReadProperty<VALUE_TYPE>(1, "value");
173971 OnObjectEnd();
173972 map[std::move(key)] = std::move(value);
173973 }
173974 OnListEnd();
173975 return map;
173976 }
173977
173978 template <typename T = void>
173979 inline typename std::enable_if<is_map<T>::value, T>::type Read() {
173980 using KEY_TYPE = typename is_map<T>::KEY_TYPE;
173981 using VALUE_TYPE = typename is_map<T>::VALUE_TYPE;
173982
173983 T map;
173984 auto size = OnListBegin();
173985 for (idx_t i = 0; i <
size; i++) {
173986 OnObjectBegin();
173987 auto key = ReadProperty<KEY_TYPE>(0, "key");
173988 auto value = ReadProperty<VALUE_TYPE>(1, "value");
173989 OnObjectEnd();
173990 map[std::move(key)] = std::move(value);
173991 }
173992 OnListEnd();
173993 return map;
173994 }
173995
173996 template <typename T = void>
173997 inline typename std::enable_if<is_insertion_preserving_map<T>::value, T>::type Read() {
173998 using VALUE_TYPE = typename is_insertion_preserving_map<T>::VALUE_TYPE;
173999
174000 T map;
174001 auto size = OnListBegin();
174002 for (idx_t i = 0; i <
size; i++) {
174003 OnObjectBegin();
174004 auto key = ReadProperty<string>(0, "key");
174005 auto value = ReadProperty<VALUE_TYPE>(1, "value");
174006 OnObjectEnd();
174007 map[key] = std::move(value);
174008 }
174009 OnListEnd();
174010 return map;
174011 }
174012
174013
174014 template <typename T = void>
174015 inline typename std::enable_if<is_unordered_set<T>::value, T>::type Read() {
174016 using ELEMENT_TYPE = typename is_unordered_set<T>::ELEMENT_TYPE;
174017 auto size = OnListBegin();
174018 T set;
174019 for (idx_t i = 0; i <
size; i++) {
174020 set.insert(Read<ELEMENT_TYPE>());
174021 }
174022 OnListEnd();
174023 return set;
174024 }
174025
174026
174027 template <typename T = void>
174028 inline typename std::enable_if<is_set<T>::value, T>::type Read() {
174029 using ELEMENT_TYPE = typename is_set<T>::ELEMENT_TYPE;
174030 auto size = OnListBegin();
174031 T set;
174032 for (idx_t i = 0; i <
size; i++) {
174033 set.insert(Read<ELEMENT_TYPE>());
174034 }
174035 OnListEnd();
174036 return set;
174037 }
174038
174039
174040 template <typename T = void>
174041 inline typename std::enable_if<is_pair<T>::value, T>::type Read() {
174042 using FIRST_TYPE = typename is_pair<T>::FIRST_TYPE;
174043 using SECOND_TYPE = typename is_pair<T>::SECOND_TYPE;
174044 OnObjectBegin();
174045 auto first = ReadProperty<FIRST_TYPE>(0, "first");
174046 auto second = ReadProperty<SECOND_TYPE>(1, "second");
174047 OnObjectEnd();
174048 return std::make_pair(first, second);
174049 }
174050
174051
174052 template <typename T = void>
174053 inline typename std::enable_if<is_queue<T>::value, T>::type Read() {
174054 using ELEMENT_TYPE = typename is_queue<T>::ELEMENT_TYPE;
174055 T queue;
174056 auto size = OnListBegin();
174057 for (idx_t i = 0; i <
size; i++) {
174058 queue.emplace(Read<ELEMENT_TYPE>());
174059 }
174060 OnListEnd();
174061 return queue;
174062 }
174063
174064
174065
174066 template <typename T = void>
174067 inline typename std::enable_if<std::is_same<T, bool>::value, T>::type Read() {
174068 return ReadBool();
174069 }
174070
174071
174072 template <typename T = void>
174073 inline typename std::enable_if<std::is_same<T, char>::value, T>::type Read() {
174074 return ReadChar();
174075 }
174076
174077
174078 template <typename T = void>
174079 inline typename std::enable_if<std::is_same<T, int8_t>::value, T>::type Read() {
174080 return ReadSignedInt8();
174081 }
174082
174083
174084 template <typename T = void>
174085 inline typename std::enable_if<std::is_same<T, uint8_t>::value, T>::type Read() {
174086 return ReadUnsignedInt8();
174087 }
174088
174089
174090 template <typename T = void>
174091 inline typename std::enable_if<std::is_same<T, int16_t>::value, T>::type Read() {
174092 return ReadSignedInt16();
174093 }
174094
174095
174096 template <typename T = void>
174097 inline typename std::enable_if<std::is_same<T, uint16_t>::value, T>::type Read() {
174098 return ReadUnsignedInt16();
174099 }
174100
174101
174102 template <typename T = void>
174103 inline typename std::enable_if<std::is_same<T, int32_t>::value, T>::type Read() {
174104 return ReadSignedInt32();
174105 }
174106
174107
174108 template <typename T = void>
174109 inline typename std::enable_if<std::is_same<T, uint32_t>::value, T>::type Read() {
174110 return ReadUnsignedInt32();
174111 }
174112
174113
174114 template <typename T = void>
174115 inline typename std::enable_if<std::is_same<T, int64_t>::value, T>::type Read() {
174116 return ReadSignedInt64();
174117 }
174118
174119
174120 template <typename T = void>
174121 inline typename std::enable_if<std::is_same<T, uint64_t>::value, T>::type Read() {
174122 return ReadUnsignedInt64();
174123 }
174124
174125
174126 template <typename T = void>
174127 inline typename std::enable_if<std::is_same<T, float>::value, T>::type Read() {
174128 return ReadFloat();
174129 }
174130
174131
174132 template <typename T = void>
174133 inline typename std::enable_if<std::is_same<T, double>::value, T>::type Read() {
174134 return ReadDouble();
174135 }
174136
174137
174138 template <typename T = void>
174139 inline typename std::enable_if<std::is_same<T, string>::value, T>::type Read() {
174140 return ReadString();
174141 }
174142
174143
174144 template <typename T = void>
174145 inline typename std::enable_if<std::is_enum<T>::value, T>::type Read() {
174146 if (deserialize_enum_from_string) {
174147 auto str = ReadString();
174148 return EnumUtil::FromString<T>(str.c_str());
174149 } else {
174150 return (T)Read<typename std::underlying_type<T>::type>();
174151 }
174152 }
174153
174154
174155 template <typename T = void>
174156 inline typename std::enable_if<std::is_same<T, hugeint_t>::value, T>::type Read() {
174157 return ReadHugeInt();
174158 }
174159
174160
174161 template <typename T = void>
174162 inline typename std::enable_if<std::is_same<T, uhugeint_t>::value, T>::type Read() {
174163 return ReadUhugeInt();
174164 }
174165
174166
174167 template <typename T = void>
174168 inline typename std::enable_if<std::is_same<T, LogicalIndex>::value, T>::type Read() {
174169 return LogicalIndex(ReadUnsignedInt64());
174170 }
174171
174172
174173 template <typename T = void>
174174 inline typename std::enable_if<std::is_same<T, PhysicalIndex>::value, T>::type Read() {
174175 return PhysicalIndex(ReadUnsignedInt64());
174176 }
174177
174178
174179 template <typename T = void>
174180 inline typename std::enable_if<std::is_same<T, optional_idx>::value, T>::type Read() {
174181 auto idx = ReadUnsignedInt64();
174182 return idx == DConstants::INVALID_INDEX ? optional_idx() : optional_idx(idx);
174183 }
174184
174185protected:
174186
174187 virtual void OnPropertyBegin(const field_id_t field_id, const char *tag) = 0;
174188 virtual void OnPropertyEnd() = 0;
174189 virtual bool OnOptionalPropertyBegin(const field_id_t field_id, const char *tag) = 0;
174190 virtual void OnOptionalPropertyEnd(bool present) = 0;
174191
174192 virtual void OnObjectBegin() = 0;
174193 virtual void OnObjectEnd() = 0;
174194 virtual idx_t OnListBegin() = 0;
174195 virtual void OnListEnd() = 0;
174196 virtual bool OnNullableBegin() = 0;
174197 virtual void OnNullableEnd() = 0;
174198
174199
174200 virtual bool ReadBool() = 0;
174201 virtual char ReadChar() {
174202 throw NotImplementedException("ReadChar not implemented");
174203 }
174204 virtual int8_t ReadSignedInt8() = 0;
174205 virtual uint8_t ReadUnsignedInt8() = 0;
174206 virtual int16_t ReadSignedInt16() = 0;
174207 virtual uint16_t ReadUnsignedInt16() = 0;
174208 virtual int32_t ReadSignedInt32() = 0;
174209 virtual uint32_t ReadUnsignedInt32() = 0;
174210 virtual int64_t ReadSignedInt64() = 0;
174211 virtual uint64_t ReadUnsignedInt64() = 0;
174212 virtual hugeint_t ReadHugeInt() = 0;
174213 virtual uhugeint_t ReadUhugeInt() = 0;
174214 virtual float ReadFloat() = 0;
174215 virtual double ReadDouble() = 0;
174216 virtual string ReadString() = 0;
174217 virtual void ReadDataPtr(data_ptr_t &ptr, idx_t count) = 0;
174218};
174219
174220template <class FUNC>
174221void Deserializer::List::ReadObject(FUNC f) {
174222 deserializer.OnObjectBegin();
174223 f(deserializer);
174224 deserializer.OnObjectEnd();
174225}
174226
174227template <class T>
174228T Deserializer::List::ReadElement() {
174229 return deserializer.Read<T>();
174230}
174231
174232template <class T>
174233void Deserializer::List::ReadElement(data_ptr_t &ptr, idx_t size) {
174234 deserializer.ReadDataPtr(ptr, size);
174235}
174236
174237}
174238
174239
174240
174241
174242
174243
174244
174245
174246
174247
174248
174249
174250
174251
174252
174253
174254
174255
174256
174257
174258
174259
174260
174261
174262
174263
174264
174265
174266
174267
174268
174269
174270namespace duckdb {
174271
174273class Uhugeint {
174274public:
174276 static string ToString(uhugeint_t input);
174277
174278 template <class T>
174279 DUCKDB_API static bool TryCast(uhugeint_t input, T &result);
174280
174281 template <class T>
174282 static T Cast(uhugeint_t input) {
174283 T result = 0;
174284 TryCast(input, result);
174285 return result;
174286 }
174287
174288 template <class T>
174289 static bool TryConvert(T value, uhugeint_t &result);
174290
174291 template <class T>
174292 static uhugeint_t Convert(T value) {
174293 uhugeint_t result;
174294 if (!TryConvert(value, result)) {
174295 throw OutOfRangeException(double(value), GetTypeId<T>(), GetTypeId<uhugeint_t>());
174296 }
174297 return result;
174298 }
174299
174300 static bool TryNegate(uhugeint_t input, uhugeint_t &result);
174301
174302
174303
174304 template <bool CHECK_OVERFLOW = true>
174305 inline static void NegateInPlace(uhugeint_t &input) {
174306 if (!TryNegate(input, input)) {
174307 throw OutOfRangeException("UHUGEINT is out of range");
174308 }
174309 }
174310
174311 template <bool CHECK_OVERFLOW = true>
174312 inline static uhugeint_t Negate(uhugeint_t input) {
174313 NegateInPlace<CHECK_OVERFLOW>(input);
174314 return input;
174315 }
174316
174317 static bool TryMultiply(uhugeint_t lhs, uhugeint_t rhs, uhugeint_t &result);
174318
174319 template <bool CHECK_OVERFLOW = true>
174320 inline static uhugeint_t Multiply(uhugeint_t lhs, uhugeint_t rhs) {
174321 uhugeint_t result;
174322 if (!TryMultiply(lhs, rhs, result)) {
174323 throw OutOfRangeException("Overflow in UHUGEINT multiplication: %s * %s", lhs.ToString(), rhs.ToString());
174324 }
174325 return result;
174326 }
174327
174328 static bool TryDivMod(uhugeint_t lhs, uhugeint_t rhs, uhugeint_t &result, uhugeint_t &remainder);
174329
174330 template <bool CHECK_OVERFLOW = true>
174331 inline static uhugeint_t Divide(uhugeint_t lhs, uhugeint_t rhs) {
174332
174333 if (rhs == 0) {
174334 throw OutOfRangeException("Division of UHUGEINT by zero: %s / %s", lhs.ToString(), rhs.ToString());
174335 }
174336 return Divide<false>(lhs, rhs);
174337 }
174338
174339 template <bool CHECK_OVERFLOW = true>
174340 inline static uhugeint_t Modulo(uhugeint_t lhs, uhugeint_t rhs) {
174341 if (rhs == 0) {
174342 throw OutOfRangeException("Modulo of UHUGEINT by zero: %s %% %s", lhs.ToString(), rhs.ToString());
174343 }
174344 return Modulo<false>(lhs, rhs);
174345 }
174346
174347 static bool TryAddInPlace(uhugeint_t &lhs, uhugeint_t rhs);
174348
174349 template <bool CHECK_OVERFLOW = true>
174350 inline static uhugeint_t Add(uhugeint_t lhs, uhugeint_t rhs) {
174351 if (!TryAddInPlace(lhs, rhs)) {
174352 throw OutOfRangeException("Overflow in UHUGEINT addition: %s + %s", lhs.ToString(), rhs.ToString());
174353 }
174354 return lhs;
174355 }
174356
174357 static bool TrySubtractInPlace(uhugeint_t &lhs, uhugeint_t rhs);
174358
174359 template <bool CHECK_OVERFLOW = true>
174360 inline static uhugeint_t Subtract(uhugeint_t lhs, uhugeint_t rhs) {
174361 if (!TrySubtractInPlace(lhs, rhs)) {
174362 throw OutOfRangeException("Underflow in HUGEINT subtraction: %s - %s", lhs.ToString(), rhs.ToString());
174363 }
174364 return lhs;
174365 }
174366
174367
174368 static uhugeint_t DivMod(uhugeint_t lhs, uhugeint_t rhs, uhugeint_t &remainder);
174369
174370 static int Sign(hugeint_t n);
174371 static hugeint_t Abs(hugeint_t n);
174372
174373
174374 static bool Equals(uhugeint_t lhs, uhugeint_t rhs) {
174375 bool lower_equals = lhs.lower == rhs.lower;
174376 bool upper_equals = lhs.upper == rhs.upper;
174377 return lower_equals && upper_equals;
174378 }
174379
174380 static bool NotEquals(uhugeint_t lhs, uhugeint_t rhs) {
174381 return !Equals(lhs, rhs);
174382 }
174383
174384 static bool GreaterThan(uhugeint_t lhs, uhugeint_t rhs) {
174385 bool upper_bigger = lhs.upper > rhs.upper;
174386 bool upper_equal = lhs.upper == rhs.upper;
174387 bool lower_bigger = lhs.lower > rhs.lower;
174388 return upper_bigger || (upper_equal && lower_bigger);
174389 }
174390
174391 static bool GreaterThanEquals(uhugeint_t lhs, uhugeint_t rhs) {
174392 bool upper_bigger = lhs.upper > rhs.upper;
174393 bool upper_equal = lhs.upper == rhs.upper;
174394 bool lower_bigger_equals = lhs.lower >= rhs.lower;
174395 return upper_bigger || (upper_equal && lower_bigger_equals);
174396 }
174397
174398 static bool LessThan(uhugeint_t lhs, uhugeint_t rhs) {
174399 bool upper_smaller = lhs.upper < rhs.upper;
174400 bool upper_equal = lhs.upper == rhs.upper;
174401 bool lower_smaller = lhs.lower < rhs.lower;
174402 return upper_smaller || (upper_equal && lower_smaller);
174403 }
174404
174405 static bool LessThanEquals(uhugeint_t lhs, uhugeint_t rhs) {
174406 bool upper_smaller = lhs.upper < rhs.upper;
174407 bool upper_equal = lhs.upper == rhs.upper;
174408 bool lower_smaller_equals = lhs.lower <= rhs.lower;
174409 return upper_smaller || (upper_equal && lower_smaller_equals);
174410 }
174411
174412 static constexpr uint8_t CACHED_POWERS_OF_TEN = 39;
174413 static const uhugeint_t POWERS_OF_TEN[CACHED_POWERS_OF_TEN];
174414};
174415
174416template <>
174417DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, int8_t &result);
174418template <>
174419DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, int16_t &result);
174420template <>
174421DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, int32_t &result);
174422template <>
174423DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, int64_t &result);
174424template <>
174425DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, uint8_t &result);
174426template <>
174427DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, uint16_t &result);
174428template <>
174429DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, uint32_t &result);
174430template <>
174431DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, uint64_t &result);
174432template <>
174433DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, hugeint_t &result);
174434template <>
174435DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, uhugeint_t &result);
174436template <>
174437DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, float &result);
174438template <>
174439DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, double &result);
174440
174441template <>
174442bool Uhugeint::TryConvert(int8_t value, uhugeint_t &result);
174443template <>
174444bool Uhugeint::TryConvert(int16_t value, uhugeint_t &result);
174445template <>
174446bool Uhugeint::TryConvert(int32_t value, uhugeint_t &result);
174447template <>
174448bool Uhugeint::TryConvert(int64_t value, uhugeint_t &result);
174449template <>
174450bool Uhugeint::TryConvert(uint8_t value, uhugeint_t &result);
174451template <>
174452bool Uhugeint::TryConvert(uint16_t value, uhugeint_t &result);
174453template <>
174454bool Uhugeint::TryConvert(uint32_t value, uhugeint_t &result);
174455template <>
174456bool Uhugeint::TryConvert(uint64_t value, uhugeint_t &result);
174457template <>
174458bool Uhugeint::TryConvert(float value, uhugeint_t &result);
174459template <>
174460bool Uhugeint::TryConvert(double value, uhugeint_t &result);
174461template <>
174462bool Uhugeint::TryConvert(long double value, uhugeint_t &result);
174463template <>
174464bool Uhugeint::TryConvert(const char *value, uhugeint_t &result);
174465
174466}
174467
174468
174469
174470
174471
174472
174473
174474
174475
174476
174477
174478
174479
174480
174481
174482
174483
174484
174485namespace duckdb {
174486
174487struct ValueOperations {
174488
174489
174490
174491
174492 static bool Equals(const Value &left, const Value &right);
174493
174494 static bool NotEquals(const Value &left, const Value &right);
174495
174496 static bool GreaterThan(const Value &left, const Value &right);
174497
174498 static bool GreaterThanEquals(const Value &left, const Value &right);
174499
174500 static bool LessThan(const Value &left, const Value &right);
174501
174502 static bool LessThanEquals(const Value &left, const Value &right);
174503
174504
174505
174506
174507 static bool NotDistinctFrom(const Value &left, const Value &right);
174508
174509 static bool DistinctFrom(const Value &left, const Value &right);
174510
174511 static bool DistinctGreaterThan(const Value &left, const Value &right);
174512
174513 static bool DistinctGreaterThanEquals(const Value &left, const Value &right);
174514
174515 static bool DistinctLessThan(const Value &left, const Value &right);
174516
174517 static bool DistinctLessThanEquals(const Value &left, const Value &right);
174518};
174519}
174520
174521
174522
174523
174524
174525namespace duckdb {
174526
174527class SerializationOptions {
174528public:
174529 SerializationOptions() = default;
174530 explicit SerializationOptions(AttachedDatabase &db);
174531
174532 bool serialize_enum_as_string = false;
174533 bool serialize_default_values = false;
174534 SerializationCompatibility serialization_compatibility = SerializationCompatibility::Default();
174535};
174536
174537class Serializer {
174538protected:
174539 SerializationOptions options;
174540 SerializationData data;
174541
174542public:
174543 virtual ~Serializer() {
174544 }
174545
174546 bool ShouldSerialize(idx_t version_added) {
174547 return options.serialization_compatibility.Compare(version_added);
174548 }
174549
174550 class List {
174551 friend Serializer;
174552
174553 private:
174554 Serializer &serializer;
174555 explicit List(Serializer &serializer) : serializer(serializer) {
174556 }
174557
174558 public:
174559
174560 template <class T>
174561 void WriteElement(const T &value);
174562
174564 void WriteElement(data_ptr_t ptr, idx_t size);
174565
174566
174567 template <class FUNC>
174568 void WriteObject(FUNC f);
174569 };
174570
174571public:
174572 SerializationOptions GetOptions() {
174573 return options;
174574 }
174575 SerializationData &GetSerializationData() {
174576 return data;
174577 }
174578
174579 void SetSerializationData(const SerializationData &other) {
174580 data = other;
174581 }
174582
174583
174584 template <class T>
174585 void WriteProperty(const field_id_t field_id, const char *tag, const T &value) {
174586 OnPropertyBegin(field_id, tag);
174587 WriteValue(value);
174588 OnPropertyEnd();
174589 }
174590
174591
174592 template <class T>
174593 void WritePropertyWithDefault(const field_id_t field_id, const char *tag, const T &value) {
174594
174595 if (!options.serialize_default_values && SerializationDefaultValue::IsDefault<T>(value)) {
174596 OnOptionalPropertyBegin(field_id, tag, false);
174597 OnOptionalPropertyEnd(false);
174598 return;
174599 }
174600 OnOptionalPropertyBegin(field_id, tag, true);
174601 WriteValue(value);
174602 OnOptionalPropertyEnd(true);
174603 }
174604
174605 template <class T>
174606 void WritePropertyWithDefault(const field_id_t field_id, const char *tag, const T &value, const T &default_value) {
174607
174608 if (!options.serialize_default_values && (value == default_value)) {
174609 OnOptionalPropertyBegin(field_id, tag, false);
174610 OnOptionalPropertyEnd(false);
174611 return;
174612 }
174613 OnOptionalPropertyBegin(field_id, tag, true);
174614 WriteValue(value);
174615 OnOptionalPropertyEnd(true);
174616 }
174617
174618
174619 template <class T>
174620 void WritePropertyWithDefault(const field_id_t field_id, const char *tag, const CSVOption<T> &value,
174621 const T &default_value) {
174622
174623 if (!options.serialize_default_values && (value == default_value)) {
174624 OnOptionalPropertyBegin(field_id, tag, false);
174625 OnOptionalPropertyEnd(false);
174626 return;
174627 }
174628 OnOptionalPropertyBegin(field_id, tag, true);
174629 WriteValue(value.GetValue());
174630 OnOptionalPropertyEnd(true);
174631 }
174632
174633
174634 void WriteProperty(const field_id_t field_id, const char *tag, const_data_ptr_t ptr, idx_t count) {
174635 OnPropertyBegin(field_id, tag);
174636 WriteDataPtr(ptr, count);
174637 OnPropertyEnd();
174638 }
174639
174640
174641 template <class FUNC>
174642 void WriteObject(const field_id_t field_id, const char *tag, FUNC f) {
174643 OnPropertyBegin(field_id, tag);
174644 OnObjectBegin();
174645 f(*this);
174646 OnObjectEnd();
174647 OnPropertyEnd();
174648 }
174649
174650 template <class FUNC>
174651 void WriteList(const field_id_t field_id, const char *tag, idx_t count, FUNC func) {
174652 OnPropertyBegin(field_id, tag);
174653 OnListBegin(count);
174654 List list {*this};
174655 for (idx_t i = 0; i < count; i++) {
174656 func(list, i);
174657 }
174658 OnListEnd();
174659 OnPropertyEnd();
174660 }
174661
174662protected:
174663 template <typename T>
174664 typename std::enable_if<std::is_enum<T>::value, void>::type WriteValue(const T value) {
174665 if (options.serialize_enum_as_string) {
174666
174667 auto str = EnumUtil::ToChars(value);
174668 WriteValue(str);
174669 } else {
174670
174671 WriteValue(static_cast<typename std::underlying_type<T>::type>(value));
174672 }
174673 }
174674
174675
174676 template <typename T>
174677 void WriteValue(const optionally_owned_ptr<T> &ptr) {
174678 WriteValue(ptr.get());
174679 }
174680
174681
174682 template <typename T>
174683 void WriteValue(const unique_ptr<T> &ptr) {
174684 WriteValue(ptr.get());
174685 }
174686
174687
174688 template <typename T>
174689 void WriteValue(const shared_ptr<T> &ptr) {
174690 WriteValue(ptr.get());
174691 }
174692
174693
174694 template <typename T>
174695 void WriteValue(const T *ptr) {
174696 if (ptr == nullptr) {
174697 OnNullableBegin(false);
174698 OnNullableEnd();
174699 } else {
174700 OnNullableBegin(true);
174701 WriteValue(*ptr);
174702 OnNullableEnd();
174703 }
174704 }
174705
174706
174707 template <class K, class V>
174708 void WriteValue(const std::pair<K, V> &pair) {
174709 OnObjectBegin();
174710 WriteProperty(0, "first", pair.first);
174711 WriteProperty(1, "second", pair.second);
174712 OnObjectEnd();
174713 }
174714
174715
174716 template <class T>
174717 void WriteValue(const reference<T> ref) {
174718 WriteValue(ref.get());
174719 }
174720
174721
174722 template <class T>
174723 void WriteValue(const vector<T> &vec) {
174724 auto count = vec.size();
174725 OnListBegin(count);
174726 for (auto &item : vec) {
174727 WriteValue(item);
174728 }
174729 OnListEnd();
174730 }
174731
174732 template <class T>
174733 void WriteValue(const unsafe_vector<T> &vec) {
174734 auto count = vec.size();
174735 OnListBegin(count);
174736 for (auto &item : vec) {
174737 WriteValue(item);
174738 }
174739 OnListEnd();
174740 }
174741
174742
174743
174744 template <class T, class HASH, class CMP>
174745 void WriteValue(const duckdb::unordered_set<T, HASH, CMP> &set) {
174746 auto count = set.size();
174747 OnListBegin(count);
174748 for (auto &item : set) {
174749 WriteValue(item);
174750 }
174751 OnListEnd();
174752 }
174753
174754
174755
174756 template <class T, class HASH, class CMP>
174757 void WriteValue(const duckdb::set<T, HASH, CMP> &set) {
174758 auto count = set.size();
174759 OnListBegin(count);
174760 for (auto &item : set) {
174761 WriteValue(item);
174762 }
174763 OnListEnd();
174764 }
174765
174766
174767
174768 template <class K, class V, class HASH, class CMP>
174769 void WriteValue(const duckdb::unordered_map<K, V, HASH, CMP> &map) {
174770 auto count = map.size();
174771 OnListBegin(count);
174772 for (auto &item : map) {
174773 OnObjectBegin();
174774 WriteProperty(0, "key", item.first);
174775 WriteProperty(1, "value", item.second);
174776 OnObjectEnd();
174777 }
174778 OnListEnd();
174779 }
174780
174781
174782
174783 template <class K, class V, class HASH, class CMP>
174784 void WriteValue(const duckdb::map<K, V, HASH, CMP> &map) {
174785 auto count = map.size();
174786 OnListBegin(count);
174787 for (auto &item : map) {
174788 OnObjectBegin();
174789 WriteProperty(0, "key", item.first);
174790 WriteProperty(1, "value", item.second);
174791 OnObjectEnd();
174792 }
174793 OnListEnd();
174794 }
174795
174796
174797
174798 template <class V>
174799 void WriteValue(const duckdb::InsertionOrderPreservingMap<V> &map) {
174800 auto count = map.size();
174801 OnListBegin(count);
174802 for (auto &entry : map) {
174803 OnObjectBegin();
174804 WriteProperty(0, "key", entry.first);
174805 WriteProperty(1, "value", entry.second);
174806 OnObjectEnd();
174807 }
174808 OnListEnd();
174809 }
174810
174811
174812 template <typename T>
174813 void WriteValue(const std::priority_queue<T> &queue) {
174814 vector<T> placeholder;
174815 auto queue_copy = std::priority_queue<T>(queue);
174816 while (queue_copy.size() > 0) {
174817 placeholder.emplace_back(queue_copy.top());
174818 queue_copy.pop();
174819 }
174820 WriteValue(placeholder);
174821 }
174822
174823
174824 template <typename T>
174825 typename std::enable_if<has_serialize<T>::value>::type WriteValue(const T &value) {
174826 OnObjectBegin();
174827 value.Serialize(*this);
174828 OnObjectEnd();
174829 }
174830
174831protected:
174832
174833 virtual void OnPropertyBegin(const field_id_t field_id, const char *tag) = 0;
174834 virtual void OnPropertyEnd() = 0;
174835 virtual void OnOptionalPropertyBegin(const field_id_t field_id, const char *tag, bool present) = 0;
174836 virtual void OnOptionalPropertyEnd(bool present) = 0;
174837 virtual void OnObjectBegin() = 0;
174838 virtual void OnObjectEnd() = 0;
174839 virtual void OnListBegin(idx_t count) = 0;
174840 virtual void OnListEnd() = 0;
174841 virtual void OnNullableBegin(bool present) = 0;
174842 virtual void OnNullableEnd() = 0;
174843
174844
174845 virtual void WriteNull() = 0;
174846 virtual void WriteValue(char value) {
174847 throw NotImplementedException("Write char value not implemented");
174848 }
174849 virtual void WriteValue(bool value) = 0;
174850 virtual void WriteValue(uint8_t value) = 0;
174851 virtual void WriteValue(int8_t value) = 0;
174852 virtual void WriteValue(uint16_t value) = 0;
174853 virtual void WriteValue(int16_t value) = 0;
174854 virtual void WriteValue(uint32_t value) = 0;
174855 virtual void WriteValue(int32_t value) = 0;
174856 virtual void WriteValue(uint64_t value) = 0;
174857 virtual void WriteValue(int64_t value) = 0;
174858 virtual void WriteValue(hugeint_t value) = 0;
174859 virtual void WriteValue(uhugeint_t value) = 0;
174860 virtual void WriteValue(float value) = 0;
174861 virtual void WriteValue(double value) = 0;
174862 virtual void WriteValue(const string_t value) = 0;
174863 virtual void WriteValue(const string &value) = 0;
174864 virtual void WriteValue(const char *str) = 0;
174865 virtual void WriteDataPtr(const_data_ptr_t ptr, idx_t count) = 0;
174866 void WriteValue(LogicalIndex value) {
174867 WriteValue(value.index);
174868 }
174869 void WriteValue(PhysicalIndex value) {
174870 WriteValue(value.index);
174871 }
174872 void WriteValue(optional_idx value) {
174873 WriteValue(value.IsValid() ? value.GetIndex() : DConstants::INVALID_INDEX);
174874 }
174875};
174876
174877
174878template <>
174879void Serializer::WriteValue(const vector<bool> &vec);
174880
174881
174882template <>
174883void Serializer::WritePropertyWithDefault<Value>(const field_id_t field_id, const char *tag, const Value &value,
174884 const Value &default_value);
174885
174886
174887template <class FUNC>
174888void Serializer::List::WriteObject(FUNC f) {
174889 serializer.OnObjectBegin();
174890 f(serializer);
174891 serializer.OnObjectEnd();
174892}
174893
174894template <class T>
174895void Serializer::List::WriteElement(const T &value) {
174896 serializer.WriteValue(value);
174897}
174898
174899}
174900
174901
174902
174903namespace duckdb {
174904class BaseSecret;
174905struct SecretEntry;
174906struct FileOpenerInfo;
174907struct CreateSecretInfo;
174908
174911
174913struct CreateSecretInput {
174915 string type;
174917 string provider;
174919 string storage_type;
174921 string name;
174923 vector<string> scope;
174925 case_insensitive_map_t<Value> options;
174927 OnCreateConflict on_conflict;
174930};
174931
174932typedef unique_ptr<BaseSecret> (*secret_deserializer_t)(Deserializer &deserializer, BaseSecret base_secret);
174933typedef unique_ptr<BaseSecret> (*create_secret_function_t)(ClientContext &context, CreateSecretInput &input);
174934
174936class CreateSecretFunction {
174937public:
174938 string secret_type;
174939 string provider;
174940 create_secret_function_t function;
174941 named_parameter_type_map_t named_parameters;
174942};
174943
174946class CreateSecretFunctionSet {
174947public:
174948 explicit CreateSecretFunctionSet(string &name) : name(name) {};
174949
174950public:
174951 bool ProviderExists(const string &provider_name);
174952 void AddFunction(CreateSecretFunction &function, OnCreateConflict on_conflict);
174953 CreateSecretFunction &GetFunction(const string &provider);
174954
174955protected:
174957 string name;
174959 case_insensitive_map_t<CreateSecretFunction> functions;
174960};
174961
174964
174966struct SecretType {
174968 string name;
174970 secret_deserializer_t deserializer;
174972 string default_provider;
174974 string extension;
174975};
174976
174982};
174983
174985class BaseSecret {
174986 friend class SecretManager;
174987
174988public:
174989 BaseSecret(vector<string> prefix_paths_p, string type_p, string provider_p, string name_p)
174990 : prefix_paths(std::move(prefix_paths_p)), type(std::move(type_p)), provider(std::move(provider_p)),
174991 name(std::move(name_p)), serializable(false) {
174992 D_ASSERT(!type.empty());
174993 }
174994 BaseSecret(const BaseSecret &other)
174995 : prefix_paths(other.prefix_paths), type(other.type), provider(other.provider), name(other.name),
174996 serializable(other.serializable) {
174997 D_ASSERT(!type.empty());
174998 }
174999 virtual ~BaseSecret() = default;
175000
175003 virtual int64_t MatchScore(
const string &path)
const;
175005 virtual string ToString(SecretDisplayType mode = SecretDisplayType::REDACTED) const;
175007 virtual void Serialize(Serializer &serializer) const;
175008
175009 virtual unique_ptr<const BaseSecret> Clone() const {
175010 D_ASSERT(typeid(BaseSecret) == typeid(*this));
175011 return make_uniq<BaseSecret>(*this);
175012 }
175013
175015 const vector<string> &GetScope() const {
175016 return prefix_paths;
175017 }
175018 const string &GetType() const {
175019 return type;
175020 }
175021 const string &GetProvider() const {
175022 return provider;
175023 }
175024 const string &GetName() const {
175025 return name;
175026 }
175027 bool IsSerializable() const {
175028 return serializable;
175029 }
175030
175031protected:
175033 virtual void SerializeBaseSecret(Serializer &serializer) const final;
175034
175036 vector<string> prefix_paths;
175037
175039 string type;
175041 string provider;
175043 string name;
175045 bool serializable;
175046};
175047
175050class KeyValueSecret : public BaseSecret {
175051public:
175052 KeyValueSecret(const vector<string> &prefix_paths, const string &type, const string &provider, const string &name)
175053 : BaseSecret(prefix_paths, type, provider, name) {
175054 D_ASSERT(!type.empty());
175055 serializable = true;
175056 }
175057 explicit KeyValueSecret(const BaseSecret &secret)
175058 : BaseSecret(secret.GetScope(), secret.GetType(), secret.GetProvider(), secret.GetName()) {
175059 serializable = true;
175060 };
175061 KeyValueSecret(const KeyValueSecret &secret)
175062 : BaseSecret(secret.GetScope(), secret.GetType(), secret.GetProvider(), secret.GetName()) {
175063 secret_map = secret.secret_map;
175064 redact_keys = secret.redact_keys;
175065 serializable = true;
175066 };
175067 KeyValueSecret(KeyValueSecret &&secret) noexcept
175068 : BaseSecret(std::move(secret.prefix_paths), std::move(secret.type), std::move(secret.provider),
175069 std::move(secret.name)) {
175070 secret_map = std::move(secret.secret_map);
175071 redact_keys = std::move(secret.redact_keys);
175072 serializable = true;
175073 };
175074
175076 string ToString(SecretDisplayType mode = SecretDisplayType::REDACTED) const override;
175077 void Serialize(Serializer &serializer) const override;
175078
175080 Value TryGetValue(const string &key, bool error_on_missing = false) const;
175081
175082
175083 template <class TYPE>
175084 static unique_ptr<BaseSecret> Deserialize(Deserializer &deserializer, BaseSecret base_secret) {
175085 auto result = make_uniq<TYPE>(base_secret);
175086 Value secret_map_value;
175087 deserializer.ReadProperty(201, "secret_map", secret_map_value);
175088
175089 for (const auto &entry : ListValue::GetChildren(secret_map_value)) {
175090 auto kv_struct = StructValue::GetChildren(entry);
175091 result->secret_map[kv_struct[0].ToString()] = kv_struct[1];
175092 }
175093
175094 Value redact_set_value;
175095 deserializer.ReadProperty(202, "redact_keys", redact_set_value);
175096 for (const auto &entry : ListValue::GetChildren(redact_set_value)) {
175097 result->redact_keys.insert(entry.ToString());
175098 }
175099
175100 return duckdb::unique_ptr_cast<TYPE, BaseSecret>(std::move(result));
175101 }
175102
175103 unique_ptr<const BaseSecret> Clone() const override {
175104 return make_uniq<KeyValueSecret>(*this);
175105 }
175106
175107
175108 bool TryGetValue(const string &key, Value &result) const {
175109 auto lookup = secret_map.find(key);
175110 if (lookup == secret_map.end()) {
175111 return false;
175112 }
175113 result = lookup->second;
175114 return true;
175115 }
175116
175117 bool TrySetValue(const string &key, const CreateSecretInput &input) {
175118 auto lookup = input.options.find(key);
175119 if (lookup != input.options.end()) {
175120 secret_map[key] = lookup->second;
175121 return true;
175122 }
175123 return false;
175124 }
175125
175127 case_insensitive_tree_t<Value> secret_map;
175129 case_insensitive_set_t redact_keys;
175130};
175131
175132
175133
175134
175135
175136
175137
175138class KeyValueSecretReader {
175139public:
175141 KeyValueSecretReader(const KeyValueSecret &secret_p, FileOpener &opener_p);
175142
175144 KeyValueSecretReader(FileOpener &opener_p, optional_ptr<FileOpenerInfo> info, const char **secret_types,
175145 idx_t secret_types_len);
175146 KeyValueSecretReader(FileOpener &opener_p, optional_ptr<FileOpenerInfo> info, const char *secret_type);
175147
175149 KeyValueSecretReader(DatabaseInstance &db, const char **secret_types, idx_t secret_types_len, string path);
175150 KeyValueSecretReader(DatabaseInstance &db, const char *secret_type, string path);
175151
175152
175153 KeyValueSecretReader(ClientContext &context, const char **secret_types, idx_t secret_types_len, string path);
175154 KeyValueSecretReader(ClientContext &context, const char *secret_type, string path);
175155
175156 ~KeyValueSecretReader();
175157
175159 SettingLookupResult TryGetSecretKey(const string &secret_key, Value &result);
175161 SettingLookupResult TryGetSecretKeyOrSetting(const string &secret_key, const string &setting_name, Value &result);
175163 Value GetSecretKey(const string &secret_key);
175165 Value GetSecretKeyOrSetting(const string &secret_key, const string &setting_name);
175166
175168 template <class TYPE>
175169 SettingLookupResult TryGetSecretKey(const string &secret_key, TYPE &value_out) {
175170 Value result;
175171 auto lookup_result = TryGetSecretKey(secret_key, result);
175172 if (lookup_result) {
175173 value_out = result.GetValue<
TYPE>();
175174 }
175175 return lookup_result;
175176 }
175177
175179 template <class TYPE>
175180 SettingLookupResult TryGetSecretKeyOrSetting(const string &secret_key, const string &setting_name,
175181 TYPE &value_out) {
175182 Value result;
175183 auto lookup_result = TryGetSecretKeyOrSetting(secret_key, setting_name, result);
175184 if (lookup_result) {
175185 if (!result.IsNull()) {
175186 value_out = result.GetValue<
TYPE>();
175187 }
175188 }
175189 return lookup_result;
175190 }
175191
175192
175193 template <class TYPE>
175194 TYPE GetSecretKeyOrSettingOrDefault(
const string &secret_key,
const string &setting_name, TYPE default_value) {
175196 if (TryGetSecretKeyOrSetting(secret_key, setting_name, result)) {
175197 return result;
175198 }
175199 return default_value;
175200 }
175201
175202protected:
175203 void Initialize(const char **secret_types, idx_t secret_types_len);
175204
175205 [[noreturn]] void ThrowNotFoundError(const string &secret_key);
175206 [[noreturn]] void ThrowNotFoundError(const string &secret_key, const string &setting_name);
175207
175209 optional_ptr<const KeyValueSecret> secret;
175211 shared_ptr<SecretEntry> secret_entry;
175212
175215 optional_ptr<DatabaseInstance>
db;
175216 optional_ptr<ClientContext> context;
175217
175218 string path;
175219};
175220
175221}
175222
175223
175224
175225
175226
175227
175228
175229
175230
175231
175232
175233
175234
175235
175236
175237
175238
175239
175240
175241
175242
175243
175244
175245
175246
175247
175248
175249
175250
175251
175252
175253
175254
175255
175256
175257
175258
175259
175260
175261
175262
175263
175264
175265
175266
175267
175268
175269
175270
175271
175272
175273
175274
175275
175276
175277
175278
175279namespace duckdb {
175280
175281enum class CTEMaterialize :
uint8_t {
175282 CTE_MATERIALIZE_DEFAULT = 1,
175283 CTE_MATERIALIZE_ALWAYS = 2,
175284 CTE_MATERIALIZE_NEVER = 3
175285};
175286
175287}
175288
175289
175290namespace duckdb {
175291
175292class SelectStatement;
175293
175294struct CommonTableExpressionInfo {
175295 ~CommonTableExpressionInfo();
175296
175297 vector<string> aliases;
175298 vector<unique_ptr<ParsedExpression>> key_targets;
175299 unique_ptr<SelectStatement> query;
175300 CTEMaterialize materialized = CTEMaterialize::CTE_MATERIALIZE_DEFAULT;
175301
175302public:
175303 void Serialize(Serializer &serializer) const;
175304 static unique_ptr<CommonTableExpressionInfo> Deserialize(Deserializer &deserializer);
175305 unique_ptr<CommonTableExpressionInfo> Copy();
175306
175307private:
175308 CTEMaterialize GetMaterializedForSerialization(Serializer &serializer) const;
175309};
175310
175311}
175312
175313
175314
175315
175316namespace duckdb {
175317
175318class Deserializer;
175319class Serializer;
175320
175321enum class QueryNodeType :
uint8_t {
175322 SELECT_NODE = 1,
175323 SET_OPERATION_NODE = 2,
175324 BOUND_SUBQUERY_NODE = 3,
175325 RECURSIVE_CTE_NODE = 4,
175326 CTE_NODE = 5,
175327 STATEMENT_NODE = 6
175328};
175329
175330struct CommonTableExpressionInfo;
175331
175332class CommonTableExpressionMap {
175333public:
175334 CommonTableExpressionMap();
175335
175336 InsertionOrderPreservingMap<unique_ptr<CommonTableExpressionInfo>> map;
175337
175338public:
175339 string ToString() const;
175340 CommonTableExpressionMap Copy() const;
175341
175342 void Serialize(Serializer &serializer) const;
175343 static CommonTableExpressionMap Deserialize(Deserializer &deserializer);
175344};
175345
175346class QueryNode {
175347public:
175348 explicit QueryNode(QueryNodeType type) : type(type) {
175349 }
175350 virtual ~QueryNode() {
175351 }
175352
175354 QueryNodeType type;
175356 vector<unique_ptr<ResultModifier>> modifiers;
175358 CommonTableExpressionMap cte_map;
175359
175360public:
175362 virtual string ToString() const = 0;
175363
175364 virtual bool Equals(const QueryNode *other) const;
175365
175367 virtual unique_ptr<QueryNode> Copy() const = 0;
175368
175369 string ResultModifiersToString() const;
175370
175372 void AddDistinct();
175373
175374 virtual void Serialize(Serializer &serializer) const;
175375 static unique_ptr<QueryNode> Deserialize(Deserializer &deserializer);
175376
175377protected:
175380 void CopyProperties(QueryNode &other) const;
175381
175382public:
175383 template <class TARGET>
175384 TARGET &Cast() {
175385 if (type != TARGET::TYPE) {
175386 throw InternalException("Failed to cast query node to type - query node type mismatch");
175387 }
175388 return reinterpret_cast<TARGET &>(*this);
175389 }
175390
175391 template <class TARGET>
175392 const TARGET &Cast() const {
175393 if (type != TARGET::TYPE) {
175394 throw InternalException("Failed to cast query node to type - query node type mismatch");
175395 }
175396 return reinterpret_cast<const TARGET &>(*this);
175397 }
175398};
175399
175400}
175401
175402
175403
175404
175405
175406
175407
175408
175409
175410
175411
175412
175413
175414
175415
175416
175417
175418
175419
175420
175421
175422
175423
175424
175425
175426
175427namespace duckdb {
175428
175429
175430
175431
175432enum class TableReferenceType :
uint8_t {
175433 INVALID = 0,
175434 BASE_TABLE = 1,
175435 SUBQUERY = 2,
175436 JOIN = 3,
175437 TABLE_FUNCTION = 5,
175438 EXPRESSION_LIST = 6,
175439 CTE = 7,
175440 EMPTY_FROM = 8,
175441 PIVOT = 9,
175442 SHOW_REF = 10,
175443 COLUMN_DATA = 11,
175444 DELIM_GET = 12,
175445 BOUND_TABLE_REF = 13
175446};
175447
175448}
175449
175450
175451
175452
175453
175454
175455
175456
175457
175458
175459
175460
175461
175462
175463namespace duckdb {
175464
175465
175466
175467enum class SampleMethod :
uint8_t { SYSTEM_SAMPLE = 0, BERNOULLI_SAMPLE = 1, RESERVOIR_SAMPLE = 2, INVALID = 255 };
175468
175469
175470string SampleMethodToString(SampleMethod method);
175471
175472class SampleOptions {
175473public:
175474
175475 static constexpr idx_t MAX_SAMPLE_ROWS = 1000000000;
175476
175477public:
175478 explicit SampleOptions(int64_t seed_ = -1);
175479
175480 Value sample_size;
175481 bool is_percentage;
175482 SampleMethod method;
175483 optional_idx seed = optional_idx::Invalid();
175484 bool repeatable;
175485
175486 unique_ptr<SampleOptions> Copy();
175487 void SetSeed(idx_t new_seed);
175488 static bool Equals(SampleOptions *a, SampleOptions *b);
175489 void Serialize(Serializer &serializer) const;
175490 static unique_ptr<SampleOptions> Deserialize(Deserializer &deserializer);
175492};
175493
175494}
175495
175496
175497
175498namespace duckdb {
175499
175501class TableRef {
175502public:
175503 static constexpr const TableReferenceType
TYPE = TableReferenceType::INVALID;
175504
175505public:
175506 explicit TableRef(TableReferenceType type) : type(type) {
175507 }
175508 virtual ~TableRef() {
175509 }
175510
175511 TableReferenceType type;
175512 string alias;
175514 unique_ptr<SampleOptions> sample;
175516 optional_idx query_location;
175518 shared_ptr<ExternalDependency> external_dependency;
175520 vector<string> column_name_alias;
175521
175522public:
175524 virtual string ToString() const = 0;
175525 void Print();
175526
175527 virtual bool Equals(const TableRef &other) const;
175528 static bool Equals(const unique_ptr<TableRef> &left, const unique_ptr<TableRef> &right);
175529
175530 virtual unique_ptr<TableRef> Copy() = 0;
175531
175533 void CopyProperties(TableRef &target) const;
175534
175535 virtual void Serialize(Serializer &serializer) const;
175536 static unique_ptr<TableRef> Deserialize(Deserializer &deserializer);
175537
175538public:
175539 template <class TARGET>
175540 TARGET &Cast() {
175541 if (type != TARGET::TYPE && TARGET::TYPE != TableReferenceType::INVALID) {
175542 throw InternalException("Failed to cast constraint to type - constraint type mismatch");
175543 }
175544 return reinterpret_cast<TARGET &>(*this);
175545 }
175546
175547 template <class TARGET>
175548 const TARGET &Cast() const {
175549 if (type != TARGET::TYPE && TARGET::TYPE != TableReferenceType::INVALID) {
175550 throw InternalException("Failed to cast constraint to type - constraint type mismatch");
175551 }
175552 return reinterpret_cast<const TARGET &>(*this);
175553 }
175554
175555protected:
175556 string BaseToString(string result) const;
175557 string BaseToString(string result, const vector<string> &column_name_alias) const;
175558 string AliasToString(const vector<string> &column_name_alias) const;
175559 string SampleToString() const;
175560};
175561}
175562
175563
175564namespace duckdb {
175565
175566class QueryNode;
175567class Serializer;
175568class Deserializer;
175569
175571class SelectStatement : public SQLStatement {
175572public:
175573 static constexpr const StatementType
TYPE = StatementType::SELECT_STATEMENT;
175574
175575public:
175576 SelectStatement() : SQLStatement(StatementType::SELECT_STATEMENT) {
175577 }
175578
175580 unique_ptr<QueryNode> node;
175581
175582protected:
175583 SelectStatement(const SelectStatement &other);
175584
175585public:
175587
175588 DUCKDB_API string ToString() const override;
175590 DUCKDB_API unique_ptr<SQLStatement> Copy() const override;
175592 bool Equals(const SQLStatement &other) const;
175593
175594 void Serialize(Serializer &serializer) const;
175595 static unique_ptr<SelectStatement> Deserialize(Deserializer &deserializer);
175596};
175597}
175598
175599
175600namespace duckdb {
175601
175602class TypeArgument {
175603public:
175604 TypeArgument(string name_p, Value value_p) : name(std::move(name_p)), value(std::move(value_p)) {
175605 }
175606 const string &GetName() const {
175607 return name;
175608 }
175609 const Value &GetValue() const {
175610 return value;
175611 }
175612 bool HasName() const {
175613 return !name.empty();
175614 }
175615 bool IsNamed(const char *name_to_check) const {
175617 }
175618 bool IsNotNull() const {
175619 return !value.IsNull();
175620 }
175621 const LogicalType &GetType() const {
175622 return value.type();
175623 }
175624
175625private:
175626 string name;
175627 Value value;
175628};
175629
175630struct BindLogicalTypeInput {
175631 optional_ptr<ClientContext> context;
175632 const LogicalType &base_type;
175633 const vector<TypeArgument> &modifiers;
175634};
175635
175637typedef LogicalType (*bind_logical_type_function_t)(BindLogicalTypeInput &input);
175638
175639struct CreateTypeInfo : public CreateInfo {
175640 CreateTypeInfo();
175641 CreateTypeInfo(string name_p, LogicalType type_p, bind_logical_type_function_t bind_function_p = nullptr);
175642
175644 string name;
175646 LogicalType type;
175648 unique_ptr<SQLStatement> query;
175651
175652public:
175653 unique_ptr<CreateInfo> Copy() const override;
175654
175655 DUCKDB_API void Serialize(Serializer &serializer) const override;
175656 DUCKDB_API static unique_ptr<CreateInfo> Deserialize(Deserializer &deserializer);
175657
175658 string ToString() const override;
175659};
175660
175661}
175662
175663
175664
175665
175666
175667
175668
175669
175670
175671
175672
175673
175674
175675
175676namespace duckdb {
175677class FileSystem;
175678
175680
175681 UNKNOWN = 0,
175689 NOT_INSTALLED = 4
175690};
175691
175692struct ExtensionLoadedInfo {
175693 string description;
175694};
175695
175696class ExtensionInstallInfo {
175697public:
175701 string full_path;
175703 string repository_url;
175705 string version;
175707 string etag;
175708
175709 void Serialize(Serializer &serializer) const;
175710
175712 static unique_ptr<ExtensionInstallInfo> TryReadInfoFile(FileSystem &fs, const string &info_file_path,
175713 const string &extension_name);
175714
175715 static unique_ptr<ExtensionInstallInfo> Deserialize(Deserializer &deserializer);
175716};
175717
175718struct ExtensionRepository {
175720 static constexpr const char *CORE_REPOSITORY_URL = "http://extensions.duckdb.org";
175721 static constexpr const char *CORE_NIGHTLY_REPOSITORY_URL = "http://nightly-extensions.duckdb.org";
175722 static constexpr const char *COMMUNITY_REPOSITORY_URL = "http://community-extensions.duckdb.org";
175723
175725 static constexpr const char *BUILD_DEBUG_REPOSITORY_PATH = "./build/debug/repository";
175726 static constexpr const char *BUILD_RELEASE_REPOSITORY_PATH = "./build/release/repository";
175727
175729 static constexpr const char *DEFAULT_REPOSITORY_URL = CORE_REPOSITORY_URL;
175730
175732 static string GetRepository(const string &repository_url);
175734 static string TryGetRepositoryUrl(const string &repository);
175736 static string TryConvertUrlToKnownRepository(const string &url);
175737
175739 static ExtensionRepository GetDefaultRepository(optional_ptr<DBConfig> config);
175740 static ExtensionRepository GetDefaultRepository(ClientContext &context);
175741
175742 static ExtensionRepository GetCoreRepository();
175743 static ExtensionRepository GetRepositoryByUrl(const string &url);
175744
175745 ExtensionRepository();
175746 ExtensionRepository(const string &name, const string &url);
175747
175749 string ToReadableString();
175750
175752 string name;
175754 string path;
175755};
175756
175757}
175758
175759
175760
175761
175762
175763
175764
175765
175766
175767
175768
175769
175770
175771
175772namespace duckdb {
175773class ErrorData;
175774
175775class ExtensionInfo {
175776public:
175777 ExtensionInfo();
175778
175779 mutex lock;
175780 atomic<bool> is_loaded;
175781 unique_ptr<ExtensionInstallInfo> install_info;
175782 unique_ptr<ExtensionLoadedInfo> load_info;
175783};
175784
175785class ExtensionActiveLoad {
175786public:
175787 ExtensionActiveLoad(DatabaseInstance &db, ExtensionInfo &info, string extension_name);
175788
175789 DatabaseInstance &
db;
175790 unique_lock<mutex> load_lock;
175791 ExtensionInfo &info;
175792 string extension_name;
175793
175794public:
175795 void FinishLoad(ExtensionInstallInfo &install_info);
175796 void LoadFail(const ErrorData &error);
175797};
175798
175799class ExtensionManager {
175800public:
175801 explicit ExtensionManager(DatabaseInstance &db);
175802
175803 DUCKDB_API bool ExtensionIsLoaded(const string &name);
175804 DUCKDB_API vector<string> GetExtensions();
175805 DUCKDB_API optional_ptr<ExtensionInfo> GetExtensionInfo(const string &name);
175806 DUCKDB_API unique_ptr<ExtensionActiveLoad> BeginLoad(const string &extension);
175807
175808 DUCKDB_API static ExtensionManager &Get(DatabaseInstance &db);
175809 DUCKDB_API static ExtensionManager &Get(ClientContext &context);
175810
175811private:
175812 DatabaseInstance &
db;
175813 mutex lock;
175814 unordered_map<string, unique_ptr<ExtensionInfo>> loaded_extensions_info;
175815};
175816
175817}
175818
175819
175820namespace duckdb {
175821
175822class DatabaseInstance;
175823struct CreateMacroInfo;
175824struct CreateCollationInfo;
175825struct CreateAggregateFunctionInfo;
175826struct CreateScalarFunctionInfo;
175827struct CreateTableFunctionInfo;
175828
175829class ExtensionLoader {
175830 friend class DuckDB;
175831 friend class ExtensionHelper;
175832
175833public:
175834 explicit ExtensionLoader(ExtensionActiveLoad &load_info);
175835 ExtensionLoader(DatabaseInstance &db, const string &extension_name);
175836
175838 DUCKDB_API DatabaseInstance &GetDatabaseInstance();
175839
175840public:
175842 DUCKDB_API void SetDescription(const string &description);
175843
175844public:
175846 DUCKDB_API void RegisterFunction(ScalarFunction function);
175847 DUCKDB_API void RegisterFunction(ScalarFunctionSet function);
175848 DUCKDB_API void RegisterFunction(CreateScalarFunctionInfo info);
175849
175851 DUCKDB_API void RegisterFunction(AggregateFunction function);
175852 DUCKDB_API void RegisterFunction(AggregateFunctionSet function);
175853 DUCKDB_API void RegisterFunction(CreateAggregateFunctionInfo info);
175854
175856 DUCKDB_API void RegisterFunction(TableFunction function);
175857 DUCKDB_API void RegisterFunction(TableFunctionSet function);
175858 DUCKDB_API void RegisterFunction(CreateTableFunctionInfo info);
175859
175861 DUCKDB_API void RegisterFunction(PragmaFunction function);
175862
175864 DUCKDB_API void RegisterFunction(PragmaFunctionSet function);
175865
175867 DUCKDB_API void RegisterFunction(CreateSecretFunction function);
175868
175870 DUCKDB_API void RegisterFunction(CopyFunction function);
175872 DUCKDB_API void RegisterFunction(CreateMacroInfo &info);
175873
175875 DUCKDB_API void RegisterCollation(CreateCollationInfo &info);
175876
175878 DUCKDB_API void RegisterCoordinateSystem(CreateCoordinateSystemInfo &info);
175879
175881 DUCKDB_API ScalarFunctionCatalogEntry &GetFunction(const string &name);
175882 DUCKDB_API TableFunctionCatalogEntry &GetTableFunction(const string &name);
175883 DUCKDB_API optional_ptr<CatalogEntry> TryGetFunction(const string &name);
175884 DUCKDB_API optional_ptr<CatalogEntry> TryGetTableFunction(const string &name);
175885
175887 DUCKDB_API void AddFunctionOverload(ScalarFunction function);
175888 DUCKDB_API void AddFunctionOverload(ScalarFunctionSet function);
175889 DUCKDB_API void AddFunctionOverload(TableFunctionSet function);
175890
175892 DUCKDB_API void RegisterType(string type_name, LogicalType type,
175893 bind_logical_type_function_t bind_function = nullptr);
175894
175896 DUCKDB_API void RegisterSecretType(SecretType secret_type);
175897
175899 DUCKDB_API void RegisterCastFunction(const LogicalType &source, const LogicalType &target,
175900 bind_cast_function_t function, int64_t implicit_cast_cost = -1);
175901 DUCKDB_API void RegisterCastFunction(const LogicalType &source, const LogicalType &target, BoundCastInfo function,
175902 int64_t implicit_cast_cost = -1);
175903
175904private:
175905 void FinalizeLoad();
175906
175907private:
175908 DatabaseInstance &
db;
175909 string extension_name;
175910 string extension_description;
175911 optional_ptr<ExtensionInfo> extension_info;
175912};
175913
175914}
175915
175923#define DUCKDB_CPP_EXTENSION_ENTRY(EXTENSION_NAME, LOADER_NAME) \
175924 DUCKDB_EXTENSION_API void EXTENSION_NAME##_duckdb_cpp_init(duckdb::ExtensionLoader &LOADER_NAME)
175925
175926
175927
175928namespace duckdb {
175929
175930class BufferManager;
175931class DatabaseManager;
175932class StorageManager;
175933class Catalog;
175934class TransactionManager;
175935class ConnectionManager;
175936class ExtensionManager;
175937class FileSystem;
175938class TaskScheduler;
175939class ObjectCache;
175940struct AttachInfo;
175941struct AttachOptions;
175942class DatabaseFileSystem;
175943struct DatabaseCacheEntry;
175944class LogManager;
175945class ExternalFileCache;
175946class ResultSetManager;
175947
175948class DatabaseInstance : public enable_shared_from_this<DatabaseInstance> {
175949 friend class DuckDB;
175950
175951public:
175952 DUCKDB_API DatabaseInstance();
175953 DUCKDB_API ~DatabaseInstance();
175954
175955 DBConfig config;
175956
175957public:
175958 BufferPool &GetBufferPool() const;
175959 DUCKDB_API SecretManager &GetSecretManager();
175960 DUCKDB_API BufferManager &GetBufferManager();
175961 DUCKDB_API const BufferManager &GetBufferManager() const;
175962 DUCKDB_API DatabaseManager &GetDatabaseManager();
175963 DUCKDB_API FileSystem &GetFileSystem();
175964 DUCKDB_API ExternalFileCache &GetExternalFileCache();
175965 DUCKDB_API ResultSetManager &GetResultSetManager();
175966 DUCKDB_API TaskScheduler &GetScheduler();
175967 DUCKDB_API ObjectCache &GetObjectCache();
175968 DUCKDB_API ConnectionManager &GetConnectionManager();
175969 DUCKDB_API ExtensionManager &GetExtensionManager();
175970 DUCKDB_API ValidChecker &GetValidChecker();
175971 DUCKDB_API LogManager &GetLogManager() const;
175972
175973 DUCKDB_API const duckdb_ext_api_v1 GetExtensionAPIV1();
175974
175975 idx_t NumberOfThreads();
175976
175977 DUCKDB_API static DatabaseInstance &GetDatabase(ClientContext &context);
175978 DUCKDB_API static const DatabaseInstance &GetDatabase(const ClientContext &context);
175979
175980 DUCKDB_API bool ExtensionIsLoaded(const string &name);
175981
175982 DUCKDB_API SettingLookupResult TryGetCurrentSetting(const string &key, Value &result) const;
175983
175984 DUCKDB_API shared_ptr<EncryptionUtil> GetEncryptionUtil(bool read_only = false);
175985 shared_ptr<EncryptionUtil> GetMbedTLSUtil(bool force_mbedtls) const;
175986
175987 shared_ptr<AttachedDatabase> CreateAttachedDatabase(ClientContext &context, AttachInfo &info,
175988 AttachOptions &options);
175989
175990private:
175991 void Initialize(const char *path, DBConfig *config);
175992 void LoadExtensionSettings();
175993 void CreateMainDatabase();
175994
175995 void Configure(DBConfig &config, const char *path);
175996
175997private:
175998 shared_ptr<BufferManager> buffer_manager;
175999 unique_ptr<DatabaseManager> db_manager;
176000 unique_ptr<TaskScheduler> scheduler;
176001 unique_ptr<ObjectCache> object_cache;
176002 unique_ptr<ConnectionManager> connection_manager;
176003 unique_ptr<ExtensionManager> extension_manager;
176004 ValidChecker db_validity;
176005 unique_ptr<DatabaseFileSystem> db_file_system;
176006 unique_ptr<LogManager> log_manager;
176007 unique_ptr<ExternalFileCache> external_file_cache;
176008 unique_ptr<ResultSetManager> result_set_manager;
176009
176010 duckdb_ext_api_v1 (*create_api_v1)();
176011};
176012
176015class DuckDB {
176016public:
176017 DUCKDB_API explicit DuckDB(const char *path = nullptr, DBConfig *config = nullptr);
176018 DUCKDB_API explicit DuckDB(const string &path, DBConfig *config = nullptr);
176019 DUCKDB_API explicit DuckDB(DatabaseInstance &instance);
176020
176021 DUCKDB_API ~DuckDB();
176022
176024 shared_ptr<DatabaseInstance> instance;
176025
176026public:
176027
176028 template <class T>
176029 void LoadStaticExtension() {
176030 T extension;
176031 auto &manager = ExtensionManager::Get(*instance);
176032 auto load_info = manager.BeginLoad(extension.Name());
176033 if (!load_info) {
176034
176035 return;
176036 }
176037
176038
176039 ExtensionLoader loader(*load_info);
176040
176041
176042 extension.Load(loader);
176043
176044
176045 loader.FinalizeLoad();
176046
176047 ExtensionInstallInfo install_info;
176048 install_info.mode = ExtensionInstallMode::STATICALLY_LINKED;
176049 install_info.version = extension.Version();
176050 load_info->FinishLoad(install_info);
176051 }
176052
176053 DUCKDB_API FileSystem &GetFileSystem();
176054
176055 DUCKDB_API
idx_t NumberOfThreads();
176056 DUCKDB_API static const char *SourceID();
176057 DUCKDB_API static const char *LibraryVersion();
176058 DUCKDB_API static const char *ReleaseCodename();
176059 DUCKDB_API
static idx_t StandardVectorSize();
176060 DUCKDB_API static string Platform();
176061 DUCKDB_API bool ExtensionIsLoaded(const string &name);
176062};
176063
176064}
176065
176066
176067
176068
176069
176070
176071
176072
176073
176074
176075
176076
176077
176078
176079
176080
176081namespace duckdb {
176082
176083class ClientContext;
176084class ColumnDataCollection;
176085class Connection;
176086class DuckDB;
176087class SQLStatement;
176088class TableCatalogEntry;
176089
176090enum class AppenderType :
uint8_t {
176091 LOGICAL,
176092 PHYSICAL
176093};
176094
176096class BaseAppender {
176097public:
176099 static constexpr const idx_t DEFAULT_FLUSH_COUNT = STANDARD_VECTOR_SIZE * 100ULL;
176100
176101public:
176103 static unique_ptr<TableRef> GetColumnDataTableRef(ColumnDataCollection &collection, const string &table_name,
176104 const vector<string> &expected_names);
176106 static unique_ptr<SQLStatement> ParseStatement(unique_ptr<TableRef> table_ref, const string &query,
176107 const string &table_name);
176108
176109protected:
176111 Allocator &allocator;
176113 vector<LogicalType> types;
176115 vector<LogicalType> active_types;
176117 unique_ptr<ColumnDataCollection> collection;
176119 DataChunk chunk;
176123 AppenderType appender_type;
176125 idx_t flush_count = DEFAULT_FLUSH_COUNT;
176127 optional_idx flush_memory_threshold;
176128
176129protected:
176130 DUCKDB_API BaseAppender(Allocator &allocator, const AppenderType type);
176131 DUCKDB_API BaseAppender(Allocator &allocator, vector<LogicalType> types, const AppenderType type,
176132 const idx_t flush_count = DEFAULT_FLUSH_COUNT);
176133
176134public:
176135 DUCKDB_API virtual ~BaseAppender();
176136
176140 DUCKDB_API void BeginRow();
176142 DUCKDB_API void EndRow();
176143
176144
176145 template <class T>
176146 void Append(T value) = delete;
176147 DUCKDB_API void Append(DataChunk &target, const Value &value, idx_t col, idx_t row);
176148
176149 DUCKDB_API void Append(const char *value, uint32_t length);
176150
176151
176152 template <typename... ARGS>
176153 void AppendRow(ARGS... args) {
176154 BeginRow();
176155 AppendRowRecursive(args...);
176156 }
176157
176159 DUCKDB_API void Flush();
176161 DUCKDB_API void Close();
176163 DUCKDB_API void Clear();
176165 const vector<LogicalType> &GetActiveTypes() const;
176166
176167 idx_t CurrentColumn()
const {
176168 return column;
176169 }
176170 DUCKDB_API void AppendDataChunk(DataChunk &value);
176171
176172 virtual void AppendDefault();
176173 virtual void AppendDefault(DataChunk &chunk, idx_t col, idx_t row);
176176 virtual void AddColumn(const string &name);
176179 virtual void ClearColumns();
176180
176181protected:
176182 void Destructor();
176183 virtual void FlushInternal(ColumnDataCollection &collection) = 0;
176184 void InitializeChunk();
176185 void FlushChunk();
176186
176187 bool ShouldFlushChunk() const;
176188 bool ShouldFlush() const;
176189
176190 template <class T>
176191 void AppendValueInternal(T value);
176192 template <class SRC, class DST>
176193 void AppendValueInternal(Vector &vector, SRC input);
176194 template <class SRC, class DST>
176195 void AppendDecimalValueInternal(Vector &vector, SRC input);
176196
176197 void AppendRowRecursive() {
176198 EndRow();
176199 }
176200
176201 template <typename T, typename... ARGS>
176202 void AppendRowRecursive(T value, ARGS... args) {
176203 Append<T>(value);
176204 AppendRowRecursive(args...);
176205 }
176206
176207 void AppendValue(const Value &value);
176208 void AppendValue(DataChunk target, const Value &value);
176209};
176210
176211class Appender : public BaseAppender {
176212public:
176213 DUCKDB_API Appender(Connection &con, const string &database_name, const string &schema_name,
176214 const string &table_name, const idx_t flush_memory_threshold = DConstants::INVALID_INDEX);
176215 DUCKDB_API Appender(Connection &con, const string &schema_name, const string &table_name,
176216 const idx_t flush_memory_threshold = DConstants::INVALID_INDEX);
176217 DUCKDB_API Appender(Connection &con, const string &table_name,
176218 const idx_t flush_memory_threshold = DConstants::INVALID_INDEX);
176219 DUCKDB_API ~Appender() override;
176220
176221public:
176222 void AppendDefault() override;
176223 void AppendDefault(DataChunk &chunk, idx_t col, idx_t row) override;
176224 void AddColumn(const string &name) override;
176225 void ClearColumns() override;
176227 vector<string> GetExpectedNames();
176229 static string ConstructQuery(TableDescription &description_p, const string &table_name,
176230 const vector<string> &expected_names);
176231
176232private:
176234 weak_ptr<ClientContext> context;
176236 unique_ptr<TableDescription> description;
176238 unordered_map<column_t, Value> default_values;
176239
176242 vector<LogicalIndex> column_ids;
176243
176244protected:
176245 void FlushInternal(ColumnDataCollection &collection) override;
176246 Value GetDefaultValue(idx_t column);
176247};
176248
176249class QueryAppender : public BaseAppender {
176250public:
176251 DUCKDB_API QueryAppender(Connection &con, string query, vector<LogicalType> types,
176252 vector<string> names = vector<string>(), string table_name = string(),
176253 const idx_t flush_memory_threshold = DConstants::INVALID_INDEX);
176254 DUCKDB_API ~QueryAppender() override;
176255
176256private:
176258 weak_ptr<ClientContext> context;
176260 string query;
176262 vector<string> names;
176264 string table_name;
176265
176266protected:
176267 void FlushInternal(ColumnDataCollection &collection) override;
176268};
176269
176270class InternalAppender : public BaseAppender {
176272 ClientContext &context;
176274 TableCatalogEntry &table;
176275
176276public:
176277 DUCKDB_API InternalAppender(ClientContext &context, TableCatalogEntry &table,
176278 const idx_t flush_count = DEFAULT_FLUSH_COUNT,
176279 const idx_t flush_memory_threshold = DConstants::INVALID_INDEX);
176280 DUCKDB_API ~InternalAppender() override;
176281
176282protected:
176283 void FlushInternal(ColumnDataCollection &collection) override;
176284};
176285
176286template <>
176287DUCKDB_API void BaseAppender::Append(bool value);
176288template <>
176289DUCKDB_API void BaseAppender::Append(int8_t value);
176290template <>
176291DUCKDB_API void BaseAppender::Append(int16_t value);
176292template <>
176293DUCKDB_API void BaseAppender::Append(int32_t value);
176294template <>
176295DUCKDB_API void BaseAppender::Append(int64_t value);
176296template <>
176297DUCKDB_API void BaseAppender::Append(hugeint_t value);
176298template <>
176299DUCKDB_API void BaseAppender::Append(uhugeint_t value);
176300template <>
176301DUCKDB_API void BaseAppender::Append(uint8_t value);
176302template <>
176303DUCKDB_API void BaseAppender::Append(uint16_t value);
176304template <>
176305DUCKDB_API void BaseAppender::Append(uint32_t value);
176306template <>
176307DUCKDB_API void BaseAppender::Append(uint64_t value);
176308template <>
176309DUCKDB_API void BaseAppender::Append(float value);
176310template <>
176311DUCKDB_API void BaseAppender::Append(double value);
176312template <>
176313DUCKDB_API void BaseAppender::Append(date_t value);
176314template <>
176315DUCKDB_API void BaseAppender::Append(dtime_t value);
176316template <>
176317DUCKDB_API void BaseAppender::Append(timestamp_t value);
176318template <>
176319DUCKDB_API void BaseAppender::Append(interval_t value);
176320template <>
176321DUCKDB_API void BaseAppender::Append(const char *value);
176322template <>
176323DUCKDB_API void BaseAppender::Append(string_t value);
176324template <>
176325DUCKDB_API void BaseAppender::Append(Value value);
176326template <>
176327DUCKDB_API void BaseAppender::Append(std::nullptr_t value);
176328
176329}
176330
176333
176336
176337
176338
176339
176340
176341
176342
176343
176344
176345
176346
176347
176348
176349
176350
176351
176352
176353
176375
176376
176377
176378#include <stddef.h>
176379#include <stdint.h>
176380
176381
176388
176390#ifdef __cplusplus
176391extern "C" {
176392#endif
176393
176394
176395#ifndef ARROW_FLAG_DICTIONARY_ORDERED
176396
176397#ifndef ARROW_C_DATA_INTERFACE
176398#define ARROW_C_DATA_INTERFACE
176399
176400#define ARROW_FLAG_DICTIONARY_ORDERED 1
176401#define ARROW_FLAG_NULLABLE 2
176402#define ARROW_FLAG_MAP_KEYS_SORTED 4
176403
176404struct ArrowSchema {
176405
176407 const char *name;
176408 const char *metadata;
176411 struct ArrowSchema **children;
176412 struct ArrowSchema *dictionary;
176413
176414
176415 void (*release)(struct ArrowSchema *);
176416
176417 void *private_data;
176418};
176419
176420struct ArrowArray {
176421
176427 const void **buffers;
176428 struct ArrowArray **children;
176429 struct ArrowArray *dictionary;
176430
176431
176432 void (*release)(struct ArrowArray *);
176433
176434 void *private_data;
176435};
176436
176437#endif
176438
176439#ifndef ARROW_C_STREAM_INTERFACE
176440#define ARROW_C_STREAM_INTERFACE
176441
176442struct ArrowArrayStream {
176443
176444
176445
176446
176447
176448
176449 int (*get_schema)(struct ArrowArrayStream *, struct ArrowSchema *out);
176450
176451
176452
176453
176454
176455
176456
176457 int (*get_next)(struct ArrowArrayStream *, struct ArrowArray *out);
176458
176459
176460
176461
176462
176463
176464
176465
176466
176467
176468 const char *(*get_last_error)(struct ArrowArrayStream *);
176469
176470
176471
176472 void (*release)(struct ArrowArrayStream *);
176473
176474
176475 void *private_data;
176476};
176477
176478#endif
176479#endif
176480
176482
176484
176485#ifndef ADBC_EXPORTING
176486#define ADBC_EXPORTING
176487
176488
176489
176490#if !defined(ADBC_EXPORT)
176491#if defined(_WIN32)
176492#if defined(ADBC_EXPORTING)
176493#define ADBC_EXPORT __declspec(dllexport)
176494#else
176495#define ADBC_EXPORT __declspec(dllimport)
176496#endif
176497#else
176498#define ADBC_EXPORT
176499#endif
176500#endif
176501
176510
176513
176515#define ADBC_STATUS_OK 0
176519#define ADBC_STATUS_UNKNOWN 1
176523#define ADBC_STATUS_NOT_IMPLEMENTED 2
176527#define ADBC_STATUS_NOT_FOUND 3
176531#define ADBC_STATUS_ALREADY_EXISTS 4
176537#define ADBC_STATUS_INVALID_ARGUMENT 5
176545#define ADBC_STATUS_INVALID_STATE 6
176552#define ADBC_STATUS_INVALID_DATA 7
176559#define ADBC_STATUS_INTEGRITY 8
176563#define ADBC_STATUS_INTERNAL 9
176569#define ADBC_STATUS_IO 10
176573#define ADBC_STATUS_CANCELLED 11
176577#define ADBC_STATUS_TIMEOUT 12
176581#define ADBC_STATUS_UNAUTHENTICATED 13
176585#define ADBC_STATUS_UNAUTHORIZED 14
176586
176593#define ADBC_ERROR_VENDOR_CODE_PRIVATE_DATA INT32_MIN
176594
176605struct ADBC_EXPORT AdbcError {
176607 char *message;
176608
176611
176615 char sqlstate[5];
176616
176621 void (*release)(struct AdbcError *error);
176622
176630 void *private_data;
176631
176639 struct AdbcDriver *private_driver;
176640};
176641
176642#ifdef __cplusplus
176646#define ADBC_ERROR_INIT \
176647 (AdbcError {nullptr, ADBC_ERROR_VENDOR_CODE_PRIVATE_DATA, {0, 0, 0, 0, 0}, nullptr, nullptr, nullptr})
176648#else
176652#define ADBC_ERROR_INIT \
176653 ((struct AdbcError) {NULL, ADBC_ERROR_VENDOR_CODE_PRIVATE_DATA, {0, 0, 0, 0, 0}, NULL, NULL, NULL})
176654#endif
176655
176663#define ADBC_ERROR_1_0_0_SIZE (offsetof(struct AdbcError, private_data))
176671#define ADBC_ERROR_1_1_0_SIZE (sizeof(struct AdbcError))
176672
176680struct ADBC_EXPORT AdbcErrorDetail {
176682 const char *key;
176686 size_t value_length;
176687};
176688
176692ADBC_EXPORT
176694
176701ADBC_EXPORT
176703
176718ADBC_EXPORT
176720
176722
176725
176730#define ADBC_VERSION_1_0_0 1000000
176731
176738#define ADBC_VERSION_1_1_0 1001000
176739
176743#define ADBC_OPTION_VALUE_ENABLED "true"
176747#define ADBC_OPTION_VALUE_DISABLED "false"
176748
176757#define ADBC_OPTION_URI "uri"
176766#define ADBC_OPTION_USERNAME "username"
176775#define ADBC_OPTION_PASSWORD "password"
176776
176781#define ADBC_INFO_VENDOR_NAME 0
176785#define ADBC_INFO_VENDOR_VERSION 1
176790#define ADBC_INFO_VENDOR_ARROW_VERSION 2
176791
176795#define ADBC_INFO_DRIVER_NAME 100
176799#define ADBC_INFO_DRIVER_VERSION 101
176803#define ADBC_INFO_DRIVER_ARROW_VERSION 102
176812#define ADBC_INFO_DRIVER_ADBC_VERSION 103
176813
176817#define ADBC_OBJECT_DEPTH_ALL 0
176821#define ADBC_OBJECT_DEPTH_CATALOGS 1
176825#define ADBC_OBJECT_DEPTH_DB_SCHEMAS 2
176829#define ADBC_OBJECT_DEPTH_TABLES 3
176833#define ADBC_OBJECT_DEPTH_COLUMNS ADBC_OBJECT_DEPTH_ALL
176834
176838
176840#define ADBC_STATISTIC_AVERAGE_BYTE_WIDTH_KEY 0
176846#define ADBC_STATISTIC_AVERAGE_BYTE_WIDTH_NAME "adbc.statistic.byte_width"
176848#define ADBC_STATISTIC_DISTINCT_COUNT_KEY 1
176852#define ADBC_STATISTIC_DISTINCT_COUNT_NAME "adbc.statistic.distinct_count"
176854#define ADBC_STATISTIC_MAX_BYTE_WIDTH_KEY 2
176860#define ADBC_STATISTIC_MAX_BYTE_WIDTH_NAME "adbc.statistic.byte_width"
176862#define ADBC_STATISTIC_MAX_VALUE_KEY 3
176864#define ADBC_STATISTIC_MAX_VALUE_NAME "adbc.statistic.byte_width"
176866#define ADBC_STATISTIC_MIN_VALUE_KEY 4
176868#define ADBC_STATISTIC_MIN_VALUE_NAME "adbc.statistic.byte_width"
176870#define ADBC_STATISTIC_NULL_COUNT_KEY 5
176874#define ADBC_STATISTIC_NULL_COUNT_NAME "adbc.statistic.null_count"
176876#define ADBC_STATISTIC_ROW_COUNT_KEY 6
176880#define ADBC_STATISTIC_ROW_COUNT_NAME "adbc.statistic.row_count"
176882
176889#define ADBC_CONNECTION_OPTION_AUTOCOMMIT "adbc.connection.autocommit"
176890
176897#define ADBC_CONNECTION_OPTION_READ_ONLY "adbc.connection.readonly"
176898
176906#define ADBC_CONNECTION_OPTION_CURRENT_CATALOG "adbc.connection.catalog"
176907
176915#define ADBC_CONNECTION_OPTION_CURRENT_DB_SCHEMA "adbc.connection.db_schema"
176916
176932#define ADBC_STATEMENT_OPTION_INCREMENTAL "adbc.statement.exec.incremental"
176933
176947#define ADBC_STATEMENT_OPTION_PROGRESS "adbc.statement.exec.progress"
176948
176960#define ADBC_STATEMENT_OPTION_MAX_PROGRESS "adbc.statement.exec.max_progress"
176961
176973#define ADBC_CONNECTION_OPTION_ISOLATION_LEVEL "adbc.connection.transaction.isolation_level"
176974
176978#define ADBC_OPTION_ISOLATION_LEVEL_DEFAULT "adbc.connection.transaction.isolation.default"
176979
176984#define ADBC_OPTION_ISOLATION_LEVEL_READ_UNCOMMITTED "adbc.connection.transaction.isolation.read_uncommitted"
176985
176999#define ADBC_OPTION_ISOLATION_LEVEL_READ_COMMITTED "adbc.connection.transaction.isolation.read_committed"
177000
177008#define ADBC_OPTION_ISOLATION_LEVEL_REPEATABLE_READ "adbc.connection.transaction.isolation.repeatable_read"
177009
177016#define ADBC_OPTION_ISOLATION_LEVEL_SNAPSHOT "adbc.connection.transaction.isolation.snapshot"
177017
177024#define ADBC_OPTION_ISOLATION_LEVEL_SERIALIZABLE "adbc.connection.transaction.isolation.serializable"
177025
177036#define ADBC_OPTION_ISOLATION_LEVEL_LINEARIZABLE "adbc.connection.transaction.isolation.linearizable"
177037
177049
177058#define ADBC_INGEST_OPTION_TARGET_TABLE "adbc.ingest.target_table"
177062#define ADBC_INGEST_OPTION_MODE "adbc.ingest.mode"
177064#define ADBC_INGEST_OPTION_MODE_CREATE "adbc.ingest.mode.create"
177068#define ADBC_INGEST_OPTION_MODE_APPEND "adbc.ingest.mode.append"
177072#define ADBC_INGEST_OPTION_MODE_REPLACE "adbc.ingest.mode.replace"
177077#define ADBC_INGEST_OPTION_MODE_CREATE_APPEND "adbc.ingest.mode.create_append"
177078
177080
177082
177089
177093struct ADBC_EXPORT AdbcDatabase {
177096 void *private_data;
177099 struct AdbcDriver *private_driver;
177100};
177101
177103
177107
177116struct ADBC_EXPORT AdbcConnection {
177119 void *private_data;
177122 struct AdbcDriver *private_driver;
177123};
177124
177126
177135
177154struct ADBC_EXPORT AdbcStatement {
177157 void *private_data;
177158
177161 struct AdbcDriver *private_driver;
177162};
177163
177180
177182struct AdbcPartitions {
177184 size_t num_partitions;
177185
177190
177192 const size_t *partition_lengths;
177193
177196 void *private_data;
177197
177202 void (*release)(struct AdbcPartitions *partitions);
177203};
177204
177206
177208
177214
177221struct ADBC_EXPORT AdbcDriver {
177225 void *private_data;
177229 void *private_manager;
177230
177235 AdbcStatusCode (*release)(
struct AdbcDriver *driver,
struct AdbcError *error);
177236
177237 AdbcStatusCode (*DatabaseInit)(
struct AdbcDatabase *,
struct AdbcError *);
177238 AdbcStatusCode (*DatabaseNew)(
struct AdbcDatabase *,
struct AdbcError *);
177239 AdbcStatusCode (*DatabaseSetOption)(
struct AdbcDatabase *,
const char *,
const char *,
struct AdbcError *);
177240 AdbcStatusCode (*DatabaseRelease)(
struct AdbcDatabase *,
struct AdbcError *);
177241
177242 AdbcStatusCode (*ConnectionCommit)(
struct AdbcConnection *,
struct AdbcError *);
177243 AdbcStatusCode (*ConnectionGetInfo)(
struct AdbcConnection *,
const uint32_t *, size_t,
struct ArrowArrayStream *,
177244 struct AdbcError *);
177245 AdbcStatusCode (*ConnectionGetObjects)(
struct AdbcConnection *, int,
const char *,
const char *,
const char *,
177246 const char **, const char *, struct ArrowArrayStream *, struct AdbcError *);
177247 AdbcStatusCode (*ConnectionGetTableSchema)(
struct AdbcConnection *,
const char *,
const char *,
const char *,
177248 struct ArrowSchema *, struct AdbcError *);
177249 AdbcStatusCode (*ConnectionGetTableTypes)(
struct AdbcConnection *,
struct ArrowArrayStream *,
struct AdbcError *);
177250 AdbcStatusCode (*ConnectionInit)(
struct AdbcConnection *,
struct AdbcDatabase *,
struct AdbcError *);
177251 AdbcStatusCode (*ConnectionNew)(
struct AdbcConnection *,
struct AdbcError *);
177252 AdbcStatusCode (*ConnectionSetOption)(
struct AdbcConnection *,
const char *,
const char *,
struct AdbcError *);
177254 struct ArrowArrayStream *, struct AdbcError *);
177255 AdbcStatusCode (*ConnectionRelease)(
struct AdbcConnection *,
struct AdbcError *);
177256 AdbcStatusCode (*ConnectionRollback)(
struct AdbcConnection *,
struct AdbcError *);
177257
177258 AdbcStatusCode (*StatementBind)(
struct AdbcStatement *,
struct ArrowArray *,
struct ArrowSchema *,
177259 struct AdbcError *);
177260 AdbcStatusCode (*StatementBindStream)(
struct AdbcStatement *,
struct ArrowArrayStream *,
struct AdbcError *);
177261 AdbcStatusCode (*StatementExecuteQuery)(
struct AdbcStatement *,
struct ArrowArrayStream *,
int64_t *,
177262 struct AdbcError *);
177263 AdbcStatusCode (*StatementExecutePartitions)(
struct AdbcStatement *,
struct ArrowSchema *,
struct AdbcPartitions *,
177264 int64_t *,
struct AdbcError *);
177265 AdbcStatusCode (*StatementGetParameterSchema)(
struct AdbcStatement *,
struct ArrowSchema *,
struct AdbcError *);
177266 AdbcStatusCode (*StatementNew)(
struct AdbcConnection *,
struct AdbcStatement *,
struct AdbcError *);
177267 AdbcStatusCode (*StatementPrepare)(
struct AdbcStatement *,
struct AdbcError *);
177268 AdbcStatusCode (*StatementRelease)(
struct AdbcStatement *,
struct AdbcError *);
177269 AdbcStatusCode (*StatementSetOption)(
struct AdbcStatement *,
const char *,
const char *,
struct AdbcError *);
177270 AdbcStatusCode (*StatementSetSqlQuery)(
struct AdbcStatement *,
const char *,
struct AdbcError *);
177271 AdbcStatusCode (*StatementSetSubstraitPlan)(
struct AdbcStatement *,
const uint8_t *, size_t,
struct AdbcError *);
177272
177294
177295 int (*ErrorGetDetailCount)(const struct AdbcError *error);
177296 struct AdbcErrorDetail (*ErrorGetDetail)(const struct AdbcError *error, int index);
177297 const struct AdbcError *(*ErrorFromArrayStream)(
struct ArrowArrayStream *stream,
AdbcStatusCode *status);
177298
177299 AdbcStatusCode (*DatabaseGetOption)(
struct AdbcDatabase *,
const char *,
char *,
size_t *,
struct AdbcError *);
177300 AdbcStatusCode (*DatabaseGetOptionBytes)(
struct AdbcDatabase *,
const char *,
uint8_t *,
size_t *,
177301 struct AdbcError *);
177302 AdbcStatusCode (*DatabaseGetOptionDouble)(
struct AdbcDatabase *,
const char *,
double *,
struct AdbcError *);
177303 AdbcStatusCode (*DatabaseGetOptionInt)(
struct AdbcDatabase *,
const char *,
int64_t *,
struct AdbcError *);
177304 AdbcStatusCode (*DatabaseSetOptionBytes)(
struct AdbcDatabase *,
const char *,
const uint8_t *, size_t,
177305 struct AdbcError *);
177306 AdbcStatusCode (*DatabaseSetOptionDouble)(
struct AdbcDatabase *,
const char *, double,
struct AdbcError *);
177307 AdbcStatusCode (*DatabaseSetOptionInt)(
struct AdbcDatabase *,
const char *,
int64_t,
struct AdbcError *);
177308
177309 AdbcStatusCode (*ConnectionCancel)(
struct AdbcConnection *,
struct AdbcError *);
177310 AdbcStatusCode (*ConnectionGetOption)(
struct AdbcConnection *,
const char *,
char *,
size_t *,
struct AdbcError *);
177311 AdbcStatusCode (*ConnectionGetOptionBytes)(
struct AdbcConnection *,
const char *,
uint8_t *,
size_t *,
177312 struct AdbcError *);
177313 AdbcStatusCode (*ConnectionGetOptionDouble)(
struct AdbcConnection *,
const char *,
double *,
struct AdbcError *);
177314 AdbcStatusCode (*ConnectionGetOptionInt)(
struct AdbcConnection *,
const char *,
int64_t *,
struct AdbcError *);
177315 AdbcStatusCode (*ConnectionGetStatistics)(
struct AdbcConnection *,
const char *,
const char *,
const char *, char,
177316 struct ArrowArrayStream *, struct AdbcError *);
177317 AdbcStatusCode (*ConnectionGetStatisticNames)(
struct AdbcConnection *,
struct ArrowArrayStream *,
177318 struct AdbcError *);
177319 AdbcStatusCode (*ConnectionSetOptionBytes)(
struct AdbcConnection *,
const char *,
const uint8_t *, size_t,
177320 struct AdbcError *);
177321 AdbcStatusCode (*ConnectionSetOptionDouble)(
struct AdbcConnection *,
const char *, double,
struct AdbcError *);
177322 AdbcStatusCode (*ConnectionSetOptionInt)(
struct AdbcConnection *,
const char *,
int64_t,
struct AdbcError *);
177323
177324 AdbcStatusCode (*StatementCancel)(
struct AdbcStatement *,
struct AdbcError *);
177325 AdbcStatusCode (*StatementExecuteSchema)(
struct AdbcStatement *,
struct ArrowSchema *,
struct AdbcError *);
177326 AdbcStatusCode (*StatementGetOption)(
struct AdbcStatement *,
const char *,
char *,
size_t *,
struct AdbcError *);
177327 AdbcStatusCode (*StatementGetOptionBytes)(
struct AdbcStatement *,
const char *,
uint8_t *,
size_t *,
177328 struct AdbcError *);
177329 AdbcStatusCode (*StatementGetOptionDouble)(
struct AdbcStatement *,
const char *,
double *,
struct AdbcError *);
177330 AdbcStatusCode (*StatementGetOptionInt)(
struct AdbcStatement *,
const char *,
int64_t *,
struct AdbcError *);
177331 AdbcStatusCode (*StatementSetOptionBytes)(
struct AdbcStatement *,
const char *,
const uint8_t *, size_t,
177332 struct AdbcError *);
177333 AdbcStatusCode (*StatementSetOptionDouble)(
struct AdbcStatement *,
const char *, double,
struct AdbcError *);
177334 AdbcStatusCode (*StatementSetOptionInt)(
struct AdbcStatement *,
const char *,
int64_t,
struct AdbcError *);
177335
177337};
177338
177345#define ADBC_DRIVER_1_0_0_SIZE (offsetof(struct AdbcDriver, ErrorGetDetailCount))
177346
177353#define ADBC_DRIVER_1_1_0_SIZE (sizeof(struct AdbcDriver))
177354
177356
177359
177367ADBC_EXPORT
177369
177406ADBC_EXPORT
177408 struct AdbcError *error);
177409
177445ADBC_EXPORT
177447 size_t *length, struct AdbcError *error);
177448
177468ADBC_EXPORT
177470 struct AdbcError *error);
177471
177491ADBC_EXPORT
177493 struct AdbcError *error);
177494
177506ADBC_EXPORT
177508 struct AdbcError *error);
177509
177520ADBC_EXPORT
177522 size_t length, struct AdbcError *error);
177523
177533ADBC_EXPORT
177535 struct AdbcError *error);
177536
177546ADBC_EXPORT
177548 struct AdbcError *error);
177549
177554ADBC_EXPORT
177556
177561ADBC_EXPORT
177563
177565
177568
177576ADBC_EXPORT
177578
177590ADBC_EXPORT
177592 struct AdbcError *error);
177593
177604ADBC_EXPORT
177606 size_t length, struct AdbcError *error);
177607
177620ADBC_EXPORT
177622 struct AdbcError *error);
177623
177636ADBC_EXPORT
177638 struct AdbcError *error);
177639
177644ADBC_EXPORT
177646 struct AdbcError *error);
177647
177653ADBC_EXPORT
177655
177676ADBC_EXPORT
177678
177702
177739ADBC_EXPORT
177741 size_t info_codes_length, struct ArrowArrayStream *out, struct AdbcError *error);
177742
177847ADBC_EXPORT
177849 const char *db_schema, const char *table_name, const char **table_type,
177850 const char *column_name, struct ArrowArrayStream *out, struct AdbcError *error);
177851
177880ADBC_EXPORT
177882 struct AdbcError *error);
177883
177919ADBC_EXPORT
177921 size_t *length, struct AdbcError *error);
177922
177942ADBC_EXPORT
177944 struct AdbcError *error);
177945
177965ADBC_EXPORT
177967 struct AdbcError *error);
177968
178029ADBC_EXPORT
178031 const char *db_schema, const char *table_name, char approximate,
178032 struct ArrowArrayStream *out, struct AdbcError *error);
178033
178047ADBC_EXPORT
178049 struct AdbcError *error);
178050
178059ADBC_EXPORT
178061 const char *db_schema, const char *table_name, struct ArrowSchema *schema,
178062 struct AdbcError *error);
178063
178077ADBC_EXPORT
178079 struct AdbcError *error);
178080
178082
178095
178109ADBC_EXPORT
178111 size_t serialized_length, struct ArrowArrayStream *out,
178112 struct AdbcError *error);
178113
178115
178123
178129ADBC_EXPORT
178131
178137ADBC_EXPORT
178139
178141
178143
178146
178154ADBC_EXPORT
178156 struct AdbcError *error);
178157
178162ADBC_EXPORT
178164
178180ADBC_EXPORT
178182 int64_t *rows_affected, struct AdbcError *error);
178183
178200ADBC_EXPORT
178202 struct AdbcError *error);
178203
178208ADBC_EXPORT
178210
178217
178227ADBC_EXPORT
178229
178231
178238
178249ADBC_EXPORT
178251 struct AdbcError *error);
178252
178254
178265ADBC_EXPORT
178267 struct AdbcError *error);
178268
178277ADBC_EXPORT
178279 struct AdbcError *error);
178280
178301ADBC_EXPORT
178303
178340ADBC_EXPORT
178342 struct AdbcError *error);
178343
178379ADBC_EXPORT
178381 size_t *length, struct AdbcError *error);
178382
178402ADBC_EXPORT
178404 struct AdbcError *error);
178405
178425ADBC_EXPORT
178427 struct AdbcError *error);
178428
178444ADBC_EXPORT
178446 struct AdbcError *error);
178447
178455ADBC_EXPORT
178457 struct AdbcError *error);
178458
178469ADBC_EXPORT
178471 size_t length, struct AdbcError *error);
178472
178482ADBC_EXPORT
178484 struct AdbcError *error);
178485
178495ADBC_EXPORT
178497 struct AdbcError *error);
178498
178501
178514ADBC_EXPORT
178516 struct AdbcPartitions *partitions, int64_t *rows_affected,
178517 struct AdbcError *error);
178518
178520
178522
178525
178553
178555
178556#endif
178557
178558#ifdef __cplusplus
178559}
178560#endif
178561
178562
178563
178564
178565
178566
178567
178568
178569
178570
178571
178572
178573
178574
178575
178576
178577
178578
178579
178580
178581
178582
178583
178584
178585
178586
178587
178588
178589
178590
178591
178592
178593
178594
178595
178596
178597
178598
178599
178600
178601
178602
178603
178604
178605
178606
178607
178608
178609
178610
178611
178612
178613
178614
178615
178616namespace duckdb {
178617class ClientContext;
178618class DatabaseInstance;
178619class Connection;
178620
178621class ConnectionManager {
178622public:
178623 ConnectionManager();
178624
178625 void AddConnection(ClientContext &context);
178626 void RemoveConnection(ClientContext &context);
178627
178628 vector<shared_ptr<ClientContext>> GetConnectionList();
178629 const reference_map_t<ClientContext, weak_ptr<ClientContext>> &GetConnectionListReference() const {
178630 return connections;
178631 }
178632 idx_t GetConnectionCount()
const;
178633
178634 void AssignConnectionId(Connection &connection);
178635
178636 static ConnectionManager &Get(DatabaseInstance &db);
178637 static ConnectionManager &Get(ClientContext &context);
178638
178639private:
178640 mutex connections_lock;
178641 reference_map_t<ClientContext, weak_ptr<ClientContext>> connections;
178642 atomic<idx_t> connection_count;
178643 atomic<connection_t> current_connection_id;
178644};
178645
178646}
178647
178648
178649
178650#include <functional>
178651
178652namespace duckdb {
178653class DBInstanceCache;
178654class DatabaseFilePathManager;
178655
178656struct DatabaseCacheEntry {
178657 DatabaseCacheEntry();
178658 explicit DatabaseCacheEntry(const shared_ptr<DuckDB> &database);
178659 ~DatabaseCacheEntry();
178660
178661 weak_ptr<DuckDB> database;
178662 mutex update_database_mutex;
178663};
178664
178665enum class CacheBehavior { AUTOMATIC, ALWAYS_CACHE, NEVER_CACHE };
178666
178667class DBInstanceCache {
178668public:
178669 DBInstanceCache();
178670 ~DBInstanceCache();
178671
178673 shared_ptr<DuckDB> GetInstance(const string &database, const DBConfig &config_dict);
178674
178676 shared_ptr<DuckDB> CreateInstance(const string &database, DBConfig &config_dict, bool cache_instance = true,
178677 const std::function<void(DuckDB &)> &on_create = nullptr);
178678
178680 shared_ptr<DuckDB> GetOrCreateInstance(const string &database, DBConfig &config_dict, bool cache_instance,
178681 const std::function<void(DuckDB &)> &on_create = nullptr);
178682 shared_ptr<DuckDB> GetOrCreateInstance(const string &database, DBConfig &config_dict,
178683 CacheBehavior cache_behavior = CacheBehavior::AUTOMATIC,
178684 const std::function<void(DuckDB &)> &on_create = nullptr);
178685
178686private:
178687 shared_ptr<DatabaseFilePathManager> path_manager;
178689 unordered_map<string, weak_ptr<DatabaseCacheEntry>> db_instances;
178690
178692 mutex cache_lock;
178693
178694private:
178695 shared_ptr<DuckDB> GetInstanceInternal(const string &database, const DBConfig &config,
178696 std::unique_lock<std::mutex> &db_instances_lock);
178697 shared_ptr<DuckDB> CreateInstanceInternal(const string &database, DBConfig &config_dict, bool cache_instance,
178698 std::unique_lock<std::mutex> db_instances_lock,
178699 const std::function<void(DuckDB &)> &on_create);
178700};
178701}
178702
178703
178704#include <cstring>
178705#include <cassert>
178706
178707#ifdef _WIN32
178708#ifndef strdup
178709#define strdup _strdup
178710#endif
178711#endif
178712
178713namespace duckdb {
178714
178715struct DBInstanceCacheWrapper {
178716 unique_ptr<DBInstanceCache> instance_cache;
178717};
178718
178719struct DatabaseWrapper {
178720 shared_ptr<DuckDB> database;
178721};
178722
178723struct CClientContextWrapper {
178724 explicit CClientContextWrapper(ClientContext &context) : context(context) {};
178725 ClientContext &context;
178726};
178727
178728struct CClientArrowOptionsWrapper {
178729 explicit CClientArrowOptionsWrapper(ClientProperties &properties) : properties(properties) {};
178730 ClientProperties properties;
178731};
178732
178733struct PreparedStatementWrapper {
178735 case_insensitive_map_t<BoundParameterData> values;
178736 unique_ptr<PreparedStatement> statement;
178737 bool success = true;
178738 ErrorData error_data;
178739 unordered_map<idx_t, string> param_index_to_name;
178740};
178741
178742struct ExtractStatementsWrapper {
178743 vector<unique_ptr<SQLStatement>> statements;
178744 string error;
178745};
178746
178747struct PendingStatementWrapper {
178748 unique_ptr<PendingQueryResult> statement;
178749 bool allow_streaming;
178750};
178751
178752struct ArrowResultWrapper {
178753 unique_ptr<MaterializedQueryResult> result;
178754 unique_ptr<DataChunk> current_chunk;
178755};
178756
178757struct AppenderWrapper {
178758 unique_ptr<BaseAppender> appender;
178759 ErrorData error_data;
178760};
178761
178762struct TableDescriptionWrapper {
178763 unique_ptr<TableDescription> description;
178764 string error;
178765};
178766
178767struct ErrorDataWrapper {
178768 ErrorData error_data;
178769};
178770
178771struct ExpressionWrapper {
178772 unique_ptr<Expression> expr;
178773};
178774
178775enum class CAPIResultSetType :
uint8_t {
178776 CAPI_RESULT_TYPE_NONE = 0,
178777 CAPI_RESULT_TYPE_MATERIALIZED,
178778 CAPI_RESULT_TYPE_STREAMING,
178779 CAPI_RESULT_TYPE_DEPRECATED
178780};
178781
178782struct DuckDBResultData {
178784 unique_ptr<QueryResult> result;
178785
178786
178787 CAPIResultSetType result_set_type;
178788};
178789
178790duckdb_type LogicalTypeIdToC(const LogicalTypeId type);
178792idx_t GetCTypeSize(
const duckdb_type type);
178793duckdb_statement_type StatementTypeToC(const StatementType type);
178794duckdb_error_type ErrorTypeToC(const ExceptionType type);
178795ExceptionType ErrorTypeFromC(const duckdb_error_type type);
178796
178797duckdb_state DuckDBTranslateResult(unique_ptr<QueryResult> result, duckdb_result *out);
178798bool DeprecatedMaterializeResult(duckdb_result *result);
178799
178800}
178801
178802
178803#include <string>
178804
178805namespace duckdb_adbc {
178806
178807class AppenderWrapper {
178808public:
178809 AppenderWrapper(duckdb_connection conn, const char *catalog, const char *schema, const char *table)
178810 : appender(nullptr) {
178811
178812
178813 auto created = duckdb_appender(nullptr);
178815 if (created) {
178817 }
178818 return;
178819 }
178820 appender = created;
178821 }
178822 ~AppenderWrapper() {
178823 if (appender) {
178825 }
178826 }
178827
178828 duckdb_appender Get() const {
178829 return appender;
178830 }
178831 bool Valid() const {
178832 return appender != nullptr;
178833 }
178834
178835private:
178836 duckdb_appender appender;
178837};
178838
178839class DataChunkWrapper {
178840public:
178841 DataChunkWrapper() : chunk(nullptr) {
178842 }
178843
178844 ~DataChunkWrapper() {
178845 if (chunk) {
178847 }
178848 }
178849
178850 explicit operator duckdb_data_chunk() const {
178851 return chunk;
178852 }
178853
178854 duckdb_data_chunk chunk;
178855};
178856
178857class ConvertedSchemaWrapper {
178858public:
178859 ConvertedSchemaWrapper() : schema(nullptr) {
178860 }
178861 ~ConvertedSchemaWrapper() {
178862 if (schema) {
178864 }
178865 }
178866 duckdb_arrow_converted_schema *GetPtr() {
178867 return &schema;
178868 }
178869
178870 explicit operator duckdb_arrow_converted_schema() const {
178871 return schema;
178872 }
178873 duckdb_arrow_converted_schema Get() const {
178874 return schema;
178875 }
178876
178877private:
178878 duckdb_arrow_converted_schema schema;
178879};
178880
178881AdbcStatusCode DatabaseNew(
struct AdbcDatabase *database,
struct AdbcError *error);
178882
178883AdbcStatusCode DatabaseSetOption(
struct AdbcDatabase *database,
const char *key,
const char *value,
178884 struct AdbcError *error);
178885
178886AdbcStatusCode DatabaseInit(
struct AdbcDatabase *database,
struct AdbcError *error);
178887
178888AdbcStatusCode DatabaseRelease(
struct AdbcDatabase *database,
struct AdbcError *error);
178889
178890AdbcStatusCode ConnectionNew(
struct AdbcConnection *connection,
struct AdbcError *error);
178891
178892AdbcStatusCode ConnectionSetOption(
struct AdbcConnection *connection,
const char *key,
const char *value,
178893 struct AdbcError *error);
178894
178895AdbcStatusCode ConnectionInit(
struct AdbcConnection *connection,
struct AdbcDatabase *database,
178896 struct AdbcError *error);
178897
178898AdbcStatusCode ConnectionRelease(
struct AdbcConnection *connection,
struct AdbcError *error);
178899
178900AdbcStatusCode ConnectionGetInfo(
struct AdbcConnection *connection,
const uint32_t *info_codes,
178901 size_t info_codes_length, struct ArrowArrayStream *out, struct AdbcError *error);
178902
178903AdbcStatusCode ConnectionGetObjects(
struct AdbcConnection *connection,
int depth,
const char *catalog,
178904 const char *db_schema, const char *table_name, const char **table_type,
178905 const char *column_name, struct ArrowArrayStream *out, struct AdbcError *error);
178906
178907AdbcStatusCode ConnectionGetTableSchema(
struct AdbcConnection *connection,
const char *catalog,
const char *db_schema,
178908 const char *table_name, struct ArrowSchema *schema, struct AdbcError *error);
178909
178910AdbcStatusCode ConnectionGetTableTypes(
struct AdbcConnection *connection,
struct ArrowArrayStream *out,
178911 struct AdbcError *error);
178912
178913AdbcStatusCode ConnectionReadPartition(
struct AdbcConnection *connection,
const uint8_t *serialized_partition,
178914 size_t serialized_length, struct ArrowArrayStream *out, struct AdbcError *error);
178915
178916AdbcStatusCode ConnectionCommit(
struct AdbcConnection *connection,
struct AdbcError *error);
178917
178918AdbcStatusCode ConnectionRollback(
struct AdbcConnection *connection,
struct AdbcError *error);
178919
178920AdbcStatusCode ConnectionCancel(
struct AdbcConnection *connection,
struct AdbcError *error);
178921
178922
178923AdbcStatusCode DatabaseGetOption(
struct AdbcDatabase *database,
const char *key,
char *value,
size_t *length,
178924 struct AdbcError *error);
178925AdbcStatusCode DatabaseGetOptionBytes(
struct AdbcDatabase *database,
const char *key, uint8_t *value,
size_t *length,
178926 struct AdbcError *error);
178927AdbcStatusCode DatabaseGetOptionDouble(
struct AdbcDatabase *database,
const char *key,
double *value,
178928 struct AdbcError *error);
178929AdbcStatusCode DatabaseGetOptionInt(
struct AdbcDatabase *database,
const char *key, int64_t *value,
178930 struct AdbcError *error);
178931AdbcStatusCode DatabaseSetOptionBytes(
struct AdbcDatabase *database,
const char *key,
const uint8_t *value,
178932 size_t length, struct AdbcError *error);
178933AdbcStatusCode DatabaseSetOptionInt(
struct AdbcDatabase *database,
const char *key, int64_t value,
178934 struct AdbcError *error);
178935AdbcStatusCode DatabaseSetOptionDouble(
struct AdbcDatabase *database,
const char *key,
double value,
178936 struct AdbcError *error);
178937
178938
178939AdbcStatusCode ConnectionGetOption(
struct AdbcConnection *connection,
const char *key,
char *value,
size_t *length,
178940 struct AdbcError *error);
178941AdbcStatusCode ConnectionGetOptionBytes(
struct AdbcConnection *connection,
const char *key, uint8_t *value,
178942 size_t *length, struct AdbcError *error);
178943AdbcStatusCode ConnectionGetOptionDouble(
struct AdbcConnection *connection,
const char *key,
double *value,
178944 struct AdbcError *error);
178945AdbcStatusCode ConnectionGetOptionInt(
struct AdbcConnection *connection,
const char *key, int64_t *value,
178946 struct AdbcError *error);
178947AdbcStatusCode ConnectionSetOptionBytes(
struct AdbcConnection *connection,
const char *key,
const uint8_t *value,
178948 size_t length, struct AdbcError *error);
178949AdbcStatusCode ConnectionSetOptionInt(
struct AdbcConnection *connection,
const char *key, int64_t value,
178950 struct AdbcError *error);
178951AdbcStatusCode ConnectionSetOptionDouble(
struct AdbcConnection *connection,
const char *key,
double value,
178952 struct AdbcError *error);
178953
178954
178955AdbcStatusCode StatementGetOption(
struct AdbcStatement *statement,
const char *key,
char *value,
size_t *length,
178956 struct AdbcError *error);
178957AdbcStatusCode StatementGetOptionBytes(
struct AdbcStatement *statement,
const char *key, uint8_t *value,
size_t *length,
178958 struct AdbcError *error);
178959AdbcStatusCode StatementGetOptionDouble(
struct AdbcStatement *statement,
const char *key,
double *value,
178960 struct AdbcError *error);
178961AdbcStatusCode StatementGetOptionInt(
struct AdbcStatement *statement,
const char *key, int64_t *value,
178962 struct AdbcError *error);
178963AdbcStatusCode StatementSetOptionBytes(
struct AdbcStatement *statement,
const char *key,
const uint8_t *value,
178964 size_t length, struct AdbcError *error);
178965AdbcStatusCode StatementSetOptionInt(
struct AdbcStatement *statement,
const char *key, int64_t value,
178966 struct AdbcError *error);
178967AdbcStatusCode StatementSetOptionDouble(
struct AdbcStatement *statement,
const char *key,
double value,
178968 struct AdbcError *error);
178969
178970const AdbcError *ErrorFromArrayStream(
struct ArrowArrayStream *stream,
AdbcStatusCode *status);
178971
178972AdbcStatusCode StatementNew(
struct AdbcConnection *connection,
struct AdbcStatement *statement,
178973 struct AdbcError *error);
178974
178975AdbcStatusCode StatementRelease(
struct AdbcStatement *statement,
struct AdbcError *error);
178976
178977AdbcStatusCode StatementExecuteQuery(
struct AdbcStatement *statement,
struct ArrowArrayStream *out,
178978 int64_t *rows_affected, struct AdbcError *error);
178979
178980AdbcStatusCode StatementCancel(
struct AdbcStatement *statement,
struct AdbcError *error);
178981
178982AdbcStatusCode StatementPrepare(
struct AdbcStatement *statement,
struct AdbcError *error);
178983
178984AdbcStatusCode StatementSetSqlQuery(
struct AdbcStatement *statement,
const char *query,
struct AdbcError *error);
178985
178986AdbcStatusCode StatementSetSubstraitPlan(
struct AdbcStatement *statement,
const uint8_t *plan,
size_t length,
178987 struct AdbcError *error);
178988
178989AdbcStatusCode StatementBind(
struct AdbcStatement *statement,
struct ArrowArray *values,
struct ArrowSchema *schema,
178990 struct AdbcError *error);
178991
178992AdbcStatusCode StatementBindStream(
struct AdbcStatement *statement,
struct ArrowArrayStream *stream,
178993 struct AdbcError *error);
178994
178995AdbcStatusCode StatementGetParameterSchema(
struct AdbcStatement *statement,
struct ArrowSchema *schema,
178996 struct AdbcError *error);
178997
178998AdbcStatusCode StatementSetOption(
struct AdbcStatement *statement,
const char *key,
const char *value,
178999 struct AdbcError *error);
179000
179001AdbcStatusCode StatementExecutePartitions(
struct AdbcStatement *statement,
struct ArrowSchema *schema,
179002 struct AdbcPartitions *partitions, int64_t *rows_affected,
179003 struct AdbcError *error);
179004
179005void InitializeADBCError(AdbcError *error);
179006
179007}
179008
179010void SetError(
struct AdbcError *error,
const std::string &message);
179011
179012
179013
179014
179015
179016
179017
179018
179019
179020
179021
179022
179023
179024#include <list>
179025
179026namespace duckdb {
179027class ArrowTypeExtensionData;
179028struct DBConfig;
179029struct ArrowConverter {
179030 DUCKDB_API static void ToArrowSchema(ArrowSchema *out_schema, const vector<LogicalType> &types,
179031 const vector<string> &names, ClientProperties &options);
179032 DUCKDB_API static void
179033 ToArrowArray(DataChunk &input, ArrowArray *out_array, ClientProperties options,
179034 const unordered_map<idx_t, const shared_ptr<ArrowTypeExtensionData>> &extension_type_cast);
179035};
179036
179037
179038
179039
179040struct DuckDBArrowSchemaHolder {
179041
179042 vector<ArrowSchema> children;
179043
179044 vector<ArrowSchema *> children_ptrs;
179046 std::list<vector<ArrowSchema>> nested_children;
179047 std::list<vector<ArrowSchema *>> nested_children_ptr;
179049 vector<unsafe_unique_array<char>> owned_type_names;
179050 vector<unsafe_unique_array<char>> owned_column_names;
179052 vector<unsafe_unique_array<char>> metadata_info;
179053 vector<unsafe_unique_array<char>> extension_format;
179054};
179055
179056}
179057
179058
179059
179060
179061
179062
179063
179064
179065
179066
179067
179068
179069
179070namespace duckdb {
179071struct CastParameters;
179072
179074class Blob {
179075public:
179076
179077 static constexpr const char *HEX_TABLE = "0123456789ABCDEF";
179078
179079 static const int HEX_MAP[256];
179081 static constexpr const char *BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
179083 static constexpr const char BASE64_PADDING = '=';
179084
179085public:
179087 DUCKDB_API
static idx_t GetStringSize(string_t blob);
179090 DUCKDB_API static void ToString(string_t blob, char *output);
179092 DUCKDB_API static string ToString(string_t blob);
179093
179095 DUCKDB_API static bool TryGetBlobSize(string_t str, idx_t &result_size, CastParameters ¶meters);
179096 DUCKDB_API
static idx_t GetBlobSize(string_t str);
179097 DUCKDB_API
static idx_t GetBlobSize(string_t str, CastParameters ¶meters);
179100 DUCKDB_API static void ToBlob(string_t str, data_ptr_t output);
179102 DUCKDB_API static string ToBlob(string_t str);
179103 DUCKDB_API static string ToBlob(string_t str, CastParameters ¶meters);
179104
179105
179106 DUCKDB_API static string ToBase64(string_t blob);
179108 DUCKDB_API
static idx_t ToBase64Size(string_t blob);
179110 DUCKDB_API static void ToBase64(string_t blob, char *output);
179111
179112 DUCKDB_API static string FromBase64(string_t blob);
179114 DUCKDB_API
static idx_t FromBase64Size(string_t str);
179116 DUCKDB_API static void FromBase64(string_t str, data_ptr_t output, idx_t output_size);
179117};
179118}
179119
179120
179121
179122
179123
179124
179125
179126
179127
179128
179129
179130
179131namespace duckdb {
179132
179133template <class PHYSICAL_TYPE>
179134struct DecimalWidth {};
179135
179136template <>
179137struct DecimalWidth<
int16_t> {
179139};
179140
179141template <>
179142struct DecimalWidth<
int32_t> {
179144};
179145
179146template <>
179147struct DecimalWidth<
int64_t> {
179149};
179150
179151template <>
179152struct DecimalWidth<hugeint_t> {
179154};
179155
179157class Decimal {
179158public:
179159 static constexpr uint8_t MAX_WIDTH_INT16 = DecimalWidth<int16_t>::max;
179160 static constexpr uint8_t MAX_WIDTH_INT32 = DecimalWidth<int32_t>::max;
179161 static constexpr uint8_t MAX_WIDTH_INT64 = DecimalWidth<int64_t>::max;
179162 static constexpr uint8_t MAX_WIDTH_INT128 = DecimalWidth<hugeint_t>::max;
179163 static constexpr uint8_t MAX_WIDTH_DECIMAL = MAX_WIDTH_INT128;
179164
179165public:
179166 static string ToString(int16_t value, uint8_t width, uint8_t scale);
179167 static string ToString(int32_t value, uint8_t width, uint8_t scale);
179168 static string ToString(int64_t value, uint8_t width, uint8_t scale);
179169 static string ToString(hugeint_t value, uint8_t width, uint8_t scale);
179170};
179171}
179172
179173
179174
179175
179176
179177
179178
179179
179180
179181
179182#include <array>
179183
179184
179185
179186
179187namespace duckdb {
179188class RandomEngine;
179189
179191class BaseUUID {
179192public:
179193 constexpr static const uint8_t STRING_SIZE = 36;
179195 static bool FromString(const string &str, hugeint_t &result, bool strict = false);
179197 static bool FromCString(const char *str, idx_t len, hugeint_t &result) {
179198 return FromString(string(str, 0, len), result);
179199 }
179201 static void ToString(hugeint_t input, char *buf);
179202
179204 static hugeint_t FromUHugeint(uhugeint_t input);
179206 static uhugeint_t ToUHugeint(hugeint_t input);
179207
179209 static hugeint_t FromBlob(const_data_ptr_t input);
179211 static void ToBlob(hugeint_t input, data_ptr_t output);
179212
179214 static string ToString(hugeint_t input) {
179215 char buff[STRING_SIZE];
179216 ToString(input, buff);
179217 return string(buff, STRING_SIZE);
179218 }
179219
179220 static hugeint_t FromString(const string &str) {
179221 hugeint_t result;
179222 FromString(str, result);
179223 return result;
179224 }
179225
179226protected:
179228 static hugeint_t Convert(const std::array<uint8_t, 16> &bytes);
179229};
179230
179232class UUID : public BaseUUID {
179233public:
179235 static hugeint_t GenerateRandomUUID(RandomEngine &engine);
179236 static hugeint_t GenerateRandomUUID();
179237};
179238
179239using UUIDv4 = UUID;
179240
179242class UUIDv7 : public BaseUUID {
179243public:
179245 static hugeint_t GenerateRandomUUID(RandomEngine &engine);
179246 static hugeint_t GenerateRandomUUID();
179247};
179248
179249}
179250
179251
179252
179253
179254
179255
179256
179257
179258
179259
179260
179261
179262
179263
179264namespace duckdb {
179265
179266struct dtime_t;
179267struct dtime_tz_t;
179268
179271class Time {
179272public:
179274 DUCKDB_API static dtime_t FromString(const string &str, bool strict = false, optional_ptr<int32_t> nanos = nullptr);
179275 DUCKDB_API static dtime_t FromCString(const char *buf, idx_t len, bool strict = false,
179276 optional_ptr<int32_t> nanos = nullptr);
179277 DUCKDB_API static bool TryConvertTime(const char *buf, idx_t len, idx_t &pos, dtime_t &result, bool strict = false,
179278 optional_ptr<int32_t> nanos = nullptr);
179279 DUCKDB_API static bool TryConvertTimeTZ(const char *buf, idx_t len, idx_t &pos, dtime_tz_t &result,
179280 bool &has_offset, bool strict = false,
179281 optional_ptr<int32_t> nanos = nullptr);
179282
179283 DUCKDB_API static bool TryConvertInterval(const char *buf, idx_t len, idx_t &pos, dtime_t &result,
179284 bool strict = false, optional_ptr<int32_t> nanos = nullptr);
179285
179287 DUCKDB_API static string ToString(dtime_t time);
179289 DUCKDB_API static string ToUTCOffset(int hour_offset, int minute_offset);
179290
179291 DUCKDB_API static dtime_t FromTime(int32_t hour, int32_t minute, int32_t second, int32_t microseconds = 0);
179292 DUCKDB_API
static int64_t ToNanoTime(int32_t hour, int32_t minute, int32_t second, int32_t nanoseconds = 0);
179293
179295 DUCKDB_API static dtime_t NormalizeTimeTZ(dtime_tz_t timetz);
179296
179298 DUCKDB_API static void Convert(dtime_t time, int32_t &out_hour, int32_t &out_min, int32_t &out_sec,
179299 int32_t &out_micros);
179300
179301 DUCKDB_API static string ConversionError(const string &str);
179302 DUCKDB_API static string ConversionError(string_t str);
179303
179304 DUCKDB_API static dtime_t FromTimeMs(int64_t time_ms);
179305 DUCKDB_API static dtime_t FromTimeNs(int64_t time_ns);
179306
179307 DUCKDB_API static bool IsValidTime(int32_t hour, int32_t minute, int32_t second, int32_t microseconds);
179308
179309private:
179310 static bool TryConvertInternal(const char *buf, idx_t len, idx_t &pos, dtime_t &result, bool strict,
179311 optional_ptr<int32_t> nanos = nullptr);
179312};
179313
179314}
179315
179316
179317
179318
179319
179320
179321
179322
179323
179324
179325
179326
179327
179328
179329
179330
179331
179332
179333
179334
179335
179336
179337
179338
179339
179340
179341
179342#include <type_traits>
179343
179344namespace duckdb {
179345
179346class ReadStream {
179347public:
179348
179349 virtual void ReadData(data_ptr_t buffer, idx_t read_size) = 0;
179350 virtual void ReadData(QueryContext context, data_ptr_t buffer, idx_t read_size) = 0;
179351
179352
179353
179354 template <class T>
179355 T Read() {
179356 return Read<T>(QueryContext());
179357 }
179358
179359 template <class T>
179360 T Read(QueryContext context) {
179361 static_assert(std::is_standard_layout<T>(), "Read element must be a standard layout data type");
179362 T value;
179363 ReadData(context, data_ptr_cast(&value), sizeof(T));
179364 return value;
179365 }
179366
179367 virtual ~ReadStream() {
179368 }
179369};
179370
179371}
179372
179373
179374
179375namespace duckdb {
179376class Allocator;
179377
179378class MemoryStream : public WriteStream, public ReadStream {
179379private:
179380 optional_ptr<Allocator> allocator;
179383 data_ptr_t data;
179384
179385public:
179386 static constexpr idx_t DEFAULT_INITIAL_CAPACITY = 512;
179387
179390 explicit MemoryStream(Allocator &allocator, idx_t capacity = DEFAULT_INITIAL_CAPACITY);
179391
179394 explicit MemoryStream(idx_t capacity = DEFAULT_INITIAL_CAPACITY);
179395
179399 explicit MemoryStream(data_ptr_t buffer, idx_t capacity);
179400
179402 MemoryStream(const MemoryStream &) = delete;
179403 MemoryStream &
operator=(
const MemoryStream &) =
delete;
179404
179405 MemoryStream(MemoryStream &&other) noexcept;
179406 MemoryStream &
operator=(MemoryStream &&other)
noexcept;
179407
179408 ~MemoryStream() override;
179409
179412 void WriteData(const_data_ptr_t buffer, idx_t write_size) override;
179413 void GrowCapacity(idx_t write_size);
179414
179417 void ReadData(data_ptr_t buffer, idx_t read_size) override;
179418 void ReadData(QueryContext context, data_ptr_t buffer, idx_t read_size) override;
179419
179421 void Rewind();
179422
179426 void Release();
179427
179429 data_ptr_t GetData() const;
179430
179432 idx_t GetPosition()
const;
179433
179435 idx_t GetCapacity()
const;
179436
179438 void SetPosition(idx_t position);
179439};
179440
179441}
179442
179443
179444
179445
179446
179447
179448
179449
179450
179451
179452
179453
179454
179455
179456
179457
179458
179459
179460
179461
179462
179463
179464namespace duckdb {
179465
179466struct FunctionDescription {
179468 vector<LogicalType> parameter_types;
179470 vector<string> parameter_names;
179472 string description;
179474 vector<string> examples;
179476 vector<string> categories;
179477};
179478
179479struct CreateFunctionInfo : public CreateInfo {
179480 explicit CreateFunctionInfo(CatalogType type, string schema = DEFAULT_SCHEMA);
179481
179483 string name;
179485 string alias_of;
179487 vector<FunctionDescription> descriptions;
179488
179489 DUCKDB_API void CopyFunctionProperties(CreateFunctionInfo &other) const;
179490};
179491
179492}
179493
179494
179495
179496namespace duckdb {
179497
179498struct CreateTableFunctionInfo : public CreateFunctionInfo {
179499 DUCKDB_API explicit CreateTableFunctionInfo(TableFunction function);
179500 DUCKDB_API explicit CreateTableFunctionInfo(TableFunctionSet set);
179501
179503 TableFunctionSet functions;
179504
179505public:
179506 DUCKDB_API unique_ptr<CreateInfo> Copy() const override;
179507 DUCKDB_API unique_ptr<AlterInfo> GetAlterInfo() const override;
179508};
179509
179510}
179511
179512
179513
179514
179515
179516
179517
179518
179519
179520
179521
179522
179523
179524
179525
179526
179527
179528
179529
179530
179531
179532
179533
179534
179535
179536
179537
179538
179539
179540
179541
179542
179543
179544
179545
179546
179547
179548
179549
179550
179551namespace duckdb {
179552
179553class QueryNode;
179554
179555struct CopyInfo : public ParseInfo {
179556public:
179557 static constexpr const ParseInfoType
TYPE = ParseInfoType::COPY_INFO;
179558
179559public:
179560 CopyInfo();
179561
179563 string catalog;
179565 string schema;
179567 string table;
179569 vector<string> select_list;
179571 bool is_from;
179575 bool is_format_auto_detected;
179577 unique_ptr<ParsedExpression> file_path_expression;
179579 string file_path;
179581 case_insensitive_map_t<unique_ptr<ParsedExpression>> parsed_options;
179583 case_insensitive_map_t<vector<Value>> options;
179585 unique_ptr<QueryNode> select_statement;
179586
179587public:
179588 string CopyOptionsToString() const;
179589
179590public:
179591 unique_ptr<CopyInfo> Copy() const;
179592 string ToString() const;
179593 string TablePartToString() const;
179594
179595 void Serialize(Serializer &serializer) const override;
179596 static unique_ptr<ParseInfo> Deserialize(Deserializer &deserializer);
179597};
179598
179599}
179600
179601
179602
179603
179604
179605
179606
179607
179608
179609
179610
179611
179612
179613
179614
179615namespace duckdb {
179616
179617enum class CopyToType :
uint8_t { COPY_TO_FILE, EXPORT_DATABASE };
179618
179619class CopyStatement : public SQLStatement {
179620public:
179621 static constexpr const StatementType
TYPE = StatementType::COPY_STATEMENT;
179622
179623public:
179624 CopyStatement();
179625
179626 unique_ptr<CopyInfo> info;
179627
179628 string ToString() const override;
179629
179630protected:
179631 CopyStatement(const CopyStatement &other);
179632
179633public:
179634 DUCKDB_API unique_ptr<SQLStatement> Copy() const override;
179635
179636private:
179637};
179638}
179639
179640
179641
179642
179643
179644
179645
179646
179647
179648
179649
179650
179651
179652namespace duckdb {
179653
179654enum class CopyOptionMode { WRITE_ONLY, READ_ONLY, READ_WRITE };
179655
179656}
179657
179658
179659namespace duckdb {
179660
179661struct BoundStatement;
179662struct CopyFunctionFileStatistics;
179663class Binder;
179664class ColumnDataCollection;
179665class ExecutionContext;
179666class PhysicalOperatorLogger;
179667
179668struct CopyFunctionInfo {
179669 virtual ~CopyFunctionInfo() = default;
179670
179671 template <class TARGET>
179672 TARGET &Cast() {
179673 DynamicCastCheck<TARGET>(this);
179674 return reinterpret_cast<TARGET &>(*this);
179675 }
179676 template <class TARGET>
179677 const TARGET &Cast() const {
179678 DynamicCastCheck<TARGET>(this);
179679 return reinterpret_cast<const TARGET &>(*this);
179680 }
179681};
179682
179683struct LocalFunctionData {
179684 virtual ~LocalFunctionData() = default;
179685
179686 template <class TARGET>
179687 TARGET &Cast() {
179688 DynamicCastCheck<TARGET>(this);
179689 return reinterpret_cast<TARGET &>(*this);
179690 }
179691 template <class TARGET>
179692 const TARGET &Cast() const {
179693 DynamicCastCheck<TARGET>(this);
179694 return reinterpret_cast<const TARGET &>(*this);
179695 }
179696};
179697
179698struct GlobalFunctionData {
179699 virtual ~GlobalFunctionData() = default;
179700
179701 template <class TARGET>
179702 TARGET &Cast() {
179703 DynamicCastCheck<TARGET>(this);
179704 return reinterpret_cast<TARGET &>(*this);
179705 }
179706 template <class TARGET>
179707 const TARGET &Cast() const {
179708 DynamicCastCheck<TARGET>(this);
179709 return reinterpret_cast<const TARGET &>(*this);
179710 }
179711};
179712
179713struct PreparedBatchData {
179714 virtual ~PreparedBatchData() = default;
179715
179716 template <class TARGET>
179717 TARGET &Cast() {
179718 DynamicCastCheck<TARGET>(this);
179719 return reinterpret_cast<TARGET &>(*this);
179720 }
179721 template <class TARGET>
179722 const TARGET &Cast() const {
179723 DynamicCastCheck<TARGET>(this);
179724 return reinterpret_cast<const TARGET &>(*this);
179725 }
179726};
179727
179728struct CopyFunctionBindInput {
179729 explicit CopyFunctionBindInput(const CopyInfo &info_p, shared_ptr<CopyFunctionInfo> function_info = nullptr)
179730 : info(info_p), function_info(std::move(function_info)) {
179731 }
179732
179733 const CopyInfo &info;
179734 shared_ptr<CopyFunctionInfo> function_info;
179735 string file_extension;
179736};
179737
179738struct CopyFromFunctionBindInput {
179739 explicit CopyFromFunctionBindInput(const CopyInfo &info_p, TableFunction &tf_p) : info(info_p), tf(tf_p) {
179740 }
179741
179742 const CopyInfo &info;
179743 TableFunction &tf;
179744};
179745
179746struct CopyToSelectInput {
179747 ClientContext &context;
179748 case_insensitive_map_t<vector<Value>> &options;
179749 vector<unique_ptr<Expression>> select_list;
179750 CopyToType copy_to_type;
179751};
179752
179753struct CopyOption {
179754 CopyOption();
179755 explicit CopyOption(LogicalType type_p, CopyOptionMode mode = CopyOptionMode::READ_WRITE);
179756
179757 LogicalType type;
179758 CopyOptionMode mode;
179759};
179760
179761struct CopyOptionsInput {
179762 explicit CopyOptionsInput(case_insensitive_map_t<CopyOption> &options) : options(options) {
179763 }
179764
179765 case_insensitive_map_t<CopyOption> &options;
179766};
179767
179768enum class CopyFunctionExecutionMode { REGULAR_COPY_TO_FILE, PARALLEL_COPY_TO_FILE, BATCH_COPY_TO_FILE };
179769
179770typedef BoundStatement (*copy_to_plan_t)(Binder &binder, CopyStatement &stmt);
179771typedef void (*copy_options_t)(ClientContext &context, CopyOptionsInput &input);
179772typedef unique_ptr<FunctionData> (*copy_to_bind_t)(ClientContext &context, CopyFunctionBindInput &input,
179773 const vector<string> &names, const vector<LogicalType> &sql_types);
179774typedef unique_ptr<LocalFunctionData> (*copy_to_initialize_local_t)(ExecutionContext &context, FunctionData &bind_data);
179775typedef unique_ptr<GlobalFunctionData> (*copy_to_initialize_global_t)(ClientContext &context, FunctionData &bind_data,
179776 const string &file_path);
179777typedef void (*copy_to_sink_t)(ExecutionContext &context, FunctionData &bind_data, GlobalFunctionData &gstate,
179778 LocalFunctionData &lstate, DataChunk &input);
179779typedef void (*copy_to_combine_t)(ExecutionContext &context, FunctionData &bind_data, GlobalFunctionData &gstate,
179780 LocalFunctionData &lstate);
179781typedef void (*copy_to_finalize_t)(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate);
179782
179783typedef void (*copy_to_serialize_t)(Serializer &serializer, const FunctionData &bind_data,
179784 const CopyFunction &function);
179785
179786typedef unique_ptr<FunctionData> (*copy_to_deserialize_t)(Deserializer &deserializer, CopyFunction &function);
179787
179788typedef unique_ptr<FunctionData> (*copy_from_bind_t)(ClientContext &context, CopyFromFunctionBindInput &info,
179789 vector<string> &expected_names,
179790 vector<LogicalType> &expected_types);
179791typedef CopyFunctionExecutionMode (*copy_to_execution_mode_t)(bool preserve_insertion_order, bool supports_batch_index);
179792
179793typedef unique_ptr<PreparedBatchData> (*copy_prepare_batch_t)(ClientContext &context, FunctionData &bind_data,
179794 GlobalFunctionData &gstate,
179795 unique_ptr<ColumnDataCollection> collection);
179796typedef void (*copy_flush_batch_t)(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate,
179797 PreparedBatchData &batch);
179798typedef idx_t (*copy_desired_batch_size_t)(ClientContext &context, FunctionData &bind_data);
179799
179800typedef bool (*copy_rotate_files_t)(FunctionData &bind_data, const optional_idx &file_size_bytes);
179801
179802typedef bool (*copy_rotate_next_file_t)(GlobalFunctionData &gstate, FunctionData &bind_data,
179803 const optional_idx &file_size_bytes);
179804
179805typedef void (*copy_to_get_written_statistics_t)(ClientContext &context, FunctionData &bind_data,
179806 GlobalFunctionData &gstate, CopyFunctionFileStatistics &statistics);
179807
179808typedef vector<unique_ptr<Expression>> (*copy_to_select_t)(CopyToSelectInput &input);
179809
179810typedef void (*copy_to_initialize_operator_t)(GlobalFunctionData &gstate, const PhysicalOperator &op);
179811
179812enum class CopyFunctionReturnType :
uint8_t {
179813 CHANGED_ROWS = 0,
179814 CHANGED_ROWS_AND_FILE_LIST = 1,
179815 WRITTEN_FILE_STATISTICS = 2
179816};
179817vector<string> GetCopyFunctionReturnNames(CopyFunctionReturnType return_type);
179819
179820struct CopyFunctionFileStatistics {
179821 idx_t row_count = 0;
179822 idx_t file_size_bytes = 0;
179823 Value footer_size_bytes;
179824
179825 case_insensitive_map_t<case_insensitive_map_t<Value>> column_statistics;
179826};
179827
179828class CopyFunction : public Function {
179829public:
179830 explicit CopyFunction(const string &name);
179831
179833 copy_to_plan_t plan;
179834 copy_to_select_t copy_to_select;
179835 copy_to_bind_t copy_to_bind;
179836 copy_options_t copy_options;
179837 copy_to_initialize_local_t copy_to_initialize_local;
179838 copy_to_initialize_global_t copy_to_initialize_global;
179839 copy_to_get_written_statistics_t copy_to_get_written_statistics;
179840 copy_to_sink_t copy_to_sink;
179841 copy_to_combine_t copy_to_combine;
179842 copy_to_finalize_t copy_to_finalize;
179843 copy_to_execution_mode_t execution_mode;
179844 copy_to_initialize_operator_t initialize_operator;
179845
179846 copy_prepare_batch_t prepare_batch;
179847 copy_flush_batch_t flush_batch;
179848 copy_desired_batch_size_t desired_batch_size;
179849
179850 copy_rotate_files_t rotate_files;
179851 copy_rotate_next_file_t rotate_next_file;
179852
179855
179856 copy_from_bind_t copy_from_bind;
179857 TableFunction copy_from_function;
179858
179859 string extension;
179860
179862 shared_ptr<CopyFunctionInfo> function_info;
179863};
179864
179865}
179866
179867
179868namespace duckdb {
179869
179870struct CreateCopyFunctionInfo : public CreateInfo {
179871 DUCKDB_API explicit CreateCopyFunctionInfo(CopyFunction function);
179872
179874 string name;
179876 CopyFunction function;
179877
179878public:
179879 unique_ptr<CreateInfo> Copy() const override;
179880};
179881
179882}
idx_t capacity
The amount of tuples that can be stored in the data chunk.
Definition duckdb.hpp:11566
vector< Vector > data
The vectors owned by the DataChunk.
Definition duckdb.hpp:11445
static string ToString(hugeint_t input)
Convert a hugeint object to a string.
Definition duckdb.cpp:121920
static DUCKDB_API bool Contains(const string &haystack, const string &needle)
Returns true if the needle string exists in the haystack.
Definition duckdb.cpp:109323
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
static DUCKDB_API bool CILessThan(const string &l1, const string &l2)
Case insensitive compare.
Definition duckdb.cpp:109707
static DUCKDB_API bool CIEquals(const string &l1, const string &l2)
Case insensitive equals.
Definition duckdb.cpp:109696
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
static DUCKDB_API bool StartsWith(string str, string prefix)
Returns true if the target string starts with the given prefix.
Definition duckdb.cpp:109377
static DUCKDB_API uint64_t CIHash(const string &str)
Case insensitive hash.
Definition duckdb.cpp:109666
static DUCKDB_API bool EndsWith(const string &str, const string &suffix)
Returns true if the target string ends with the given suffix.
Definition duckdb.cpp:109384
DUCKDB_API string ToString() const
Convert this value to a string.
Definition duckdb.cpp:133318
static DUCKDB_API Value BLOB(const_data_ptr_t data, idx_t len)
Create a blob Value from a data pointer and a length: no bytes are interpreted.
Definition duckdb.cpp:132586
static DUCKDB_API bool NotDistinctFrom(const Value &lvalue, const Value &rvalue)
Returns true if the values are not distinct from each other, following SQL semantics for NOT DISTINCT...
Definition duckdb.cpp:134034
static constexpr uint64_t ENCRYPTED_DATABASE_FLAG
Indicates whether database is encrypted or not.
Definition duckdb.hpp:9747
void duckdb_destroy_instance_cache(duckdb_instance_cache *instance_cache)
Definition duckdb.cpp:266353
void duckdb_scalar_function_set_error(duckdb_function_info info, const char *error)
Definition duckdb.cpp:270682
idx_t duckdb_nparams(duckdb_prepared_statement prepared_statement)
Definition duckdb.cpp:269189
duckdb_value duckdb_create_map_value(duckdb_logical_type map_type, duckdb_value *keys, duckdb_value *values, idx_t entry_count)
Definition duckdb.cpp:266985
duckdb_state duckdb_bind_int8(duckdb_prepared_statement prepared_statement, idx_t param_idx, int8_t val)
Definition duckdb.cpp:269352
duckdb_state duckdb_bind_uhugeint(duckdb_prepared_statement prepared_statement, idx_t param_idx, duckdb_uhugeint val)
Definition duckdb.cpp:269391
void * duckdb_copy_function_global_init_get_extra_info(duckdb_copy_function_global_init_info info)
Definition duckdb.cpp:265462
duckdb_logical_type duckdb_copy_function_bind_get_column_type(duckdb_copy_function_bind_info info, idx_t col_idx)
Definition duckdb.cpp:265342
void duckdb_validity_set_row_invalid(uint64_t *validity, idx_t row)
Definition duckdb.cpp:266165
duckdb_decimal duckdb_value_decimal(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271810
duckdb_decimal duckdb_get_decimal(duckdb_value val)
Definition duckdb.cpp:266731
void * duckdb_copy_function_sink_get_bind_data(duckdb_copy_function_sink_info info)
Definition duckdb.cpp:265603
duckdb_state duckdb_bind_uint8(duckdb_prepared_statement prepared_statement, idx_t param_idx, uint8_t val)
Definition duckdb.cpp:269396
void * duckdb_malloc(size_t size)
Definition duckdb.cpp:268084
duckdb_client_context duckdb_copy_function_sink_get_client_context(duckdb_copy_function_sink_info info)
Definition duckdb.cpp:265594
void duckdb_data_chunk_reset(duckdb_data_chunk chunk)
Definition duckdb.cpp:265958
duckdb_value duckdb_profiling_info_get_metrics(duckdb_profiling_info info)
Definition duckdb.cpp:269595
void duckdb_config_option_set_type(duckdb_config_option option, duckdb_logical_type type)
Definition duckdb.cpp:264902
duckdb_state duckdb_appender_clear_columns(duckdb_appender appender_p)
Definition duckdb.cpp:263253
void duckdb_table_function_add_parameter(duckdb_table_function function, duckdb_logical_type type)
Definition duckdb.cpp:271273
void duckdb_aggregate_function_add_parameter(duckdb_aggregate_function function, duckdb_logical_type type)
Definition duckdb.cpp:262963
duckdb_arrow_options duckdb_result_get_arrow_options(duckdb_result *result)
Definition duckdb.cpp:270185
const char * duckdb_parameter_name(duckdb_prepared_statement prepared_statement, idx_t index)
Definition duckdb.cpp:269210
char * duckdb_union_type_member_name(duckdb_logical_type type, idx_t index)
Definition duckdb.cpp:268807
char * duckdb_table_description_get_column_name(duckdb_table_description table_description, idx_t index)
Definition duckdb.cpp:271043
duckdb_logical_type duckdb_get_value_type(duckdb_value val)
Definition duckdb.cpp:266879
idx_t duckdb_extract_statements(duckdb_connection connection, const char *query, duckdb_extracted_statements *out_extracted_statements)
Definition duckdb.cpp:269096
duckdb_hugeint duckdb_get_hugeint(duckdb_value val)
Definition duckdb.cpp:266694
duckdb_state duckdb_file_system_open(duckdb_file_system fs, const char *path, duckdb_file_open_options options, duckdb_file_handle *out_file)
Definition duckdb.cpp:267410
duckdb_state duckdb_query_arrow(duckdb_connection connection, const char *query, duckdb_arrow *out_result)
Definition duckdb.cpp:263648
void duckdb_destroy_scalar_function_set(duckdb_scalar_function_set *set)
Definition duckdb.cpp:270843
const char * duckdb_library_version()
Definition duckdb.cpp:266539
void duckdb_table_function_supports_projection_pushdown(duckdb_table_function table_function, bool pushdown)
Definition duckdb.cpp:271339
duckdb_vector duckdb_struct_vector_get_child(duckdb_vector vector, idx_t index)
Definition duckdb.cpp:266132
duckdb_client_context duckdb_copy_function_finalize_get_client_context(duckdb_copy_function_finalize_info info)
Definition duckdb.cpp:265708
void duckdb_table_function_get_client_context(duckdb_bind_info info, duckdb_client_context *out_context)
Definition duckdb.cpp:271395
void duckdb_replacement_scan_add_parameter(duckdb_replacement_scan_info info_p, duckdb_value parameter)
Definition duckdb.cpp:269721
int64_t duckdb_get_int64(duckdb_value val)
Definition duckdb.cpp:266688
void duckdb_config_option_set_description(duckdb_config_option option, const char *description)
Definition duckdb.cpp:264953
duckdb_profiling_info duckdb_profiling_info_get_child(duckdb_profiling_info info, idx_t index)
Definition duckdb.cpp:269630
duckdb_timestamp duckdb_value_timestamp(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271870
idx_t duckdb_arrow_column_count(duckdb_arrow result)
Definition duckdb.cpp:263754
duckdb_state duckdb_get_or_create_from_cache(duckdb_instance_cache instance_cache, const char *path, duckdb_database *out_database, duckdb_config config, char **out_error)
Definition duckdb.cpp:266404
void duckdb_destroy_expression(duckdb_expression *expr)
Definition duckdb.cpp:267262
duckdb_value duckdb_get_map_key(duckdb_value value, idx_t index)
Definition duckdb.cpp:267065
void duckdb_scalar_function_init_set_state(duckdb_init_info info, void *local_state, duckdb_delete_callback_t destroy)
Definition duckdb.cpp:270790
duckdb_state duckdb_execute_prepared(duckdb_prepared_statement prepared_statement, duckdb_result *out_result)
Definition duckdb.cpp:269494
duckdb_state duckdb_appender_begin_row(duckdb_appender appender)
Definition duckdb.cpp:263279
duckdb_vector duckdb_list_vector_get_child(duckdb_vector vector)
Definition duckdb.cpp:266098
duckdb_time_tz duckdb_create_time_tz(int64_t micros, int32_t offset)
Definition duckdb.cpp:266283
duckdb_logical_type duckdb_column_logical_type(duckdb_result *result, idx_t col)
Definition duckdb.cpp:270177
duckdb_timestamp_ns duckdb_get_timestamp_ns(duckdb_value val)
Definition duckdb.cpp:266832
void duckdb_destroy_file_handle(duckdb_file_handle *file)
Definition duckdb.cpp:267457
void duckdb_close(duckdb_database *database)
Definition duckdb.cpp:266424
uint32_t duckdb_value_uint32(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271842
void duckdb_destroy_config(duckdb_config *config)
Definition duckdb.cpp:264853
duckdb_aggregate_function duckdb_create_aggregate_function()
Definition duckdb.cpp:262933
const char * duckdb_extract_statements_error(duckdb_extracted_statements extracted_statements)
Definition duckdb.cpp:269146
duckdb_state duckdb_bind_time(duckdb_prepared_statement prepared_statement, idx_t param_idx, duckdb_time val)
Definition duckdb.cpp:269431
void duckdb_init_set_error(duckdb_init_info info, const char *error)
Definition duckdb.cpp:271508
void duckdb_replacement_scan_set_function_name(duckdb_replacement_scan_info info_p, const char *function_name)
Definition duckdb.cpp:269713
duckdb_type duckdb_prepared_statement_column_type(duckdb_prepared_statement prepared_statement, idx_t col_idx)
Definition duckdb.cpp:269298
uint8_t duckdb_decimal_width(duckdb_logical_type type)
Definition duckdb.cpp:268661
uint16_t duckdb_value_uint16(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271838
duckdb_state duckdb_register_cast_function(duckdb_connection connection, duckdb_cast_function cast_function)
Definition duckdb.cpp:264556
const char * duckdb_string_t_data(duckdb_string_t *string_p)
Definition duckdb.cpp:268110
duckdb_state duckdb_register_log_storage(duckdb_database database, duckdb_log_storage log_storage)
Definition duckdb.cpp:268457
duckdb_state duckdb_appender_flush(duckdb_appender appender_p)
Definition duckdb.cpp:263436
duckdb_state duckdb_bind_decimal(duckdb_prepared_statement prepared_statement, idx_t param_idx, duckdb_decimal val)
Definition duckdb.cpp:269472
double duckdb_uhugeint_to_double(duckdb_uhugeint val)
Definition duckdb.cpp:268289
duckdb_state duckdb_append_time(duckdb_appender appender, duckdb_time value)
Definition duckdb.cpp:263403
void duckdb_finish_execution(duckdb_task_state state_p)
Definition duckdb.cpp:271641
duckdb_logical_type duckdb_array_type_child_type(duckdb_logical_type type)
Definition duckdb.cpp:268743
int16_t duckdb_get_int16(duckdb_value val)
Definition duckdb.cpp:266658
uint8_t duckdb_get_uint8(duckdb_value val)
Definition duckdb.cpp:266652
duckdb_state duckdb_append_uhugeint(duckdb_appender appender, duckdb_uhugeint value)
Definition duckdb.cpp:263384
duckdb_state duckdb_append_double(duckdb_appender appender, double value)
Definition duckdb.cpp:263395
duckdb_client_context duckdb_copy_function_bind_get_client_context(duckdb_copy_function_bind_info info)
Definition duckdb.cpp:265325
duckdb_timestamp_s duckdb_get_timestamp_s(duckdb_value val)
Definition duckdb.cpp:266808
duckdb_value duckdb_create_union_value(duckdb_logical_type union_type, idx_t tag_index, duckdb_value value)
Definition duckdb.cpp:267023
duckdb_value duckdb_create_timestamp_ns(duckdb_timestamp_ns input)
Definition duckdb.cpp:266827
duckdb_error_data duckdb_to_arrow_schema(duckdb_arrow_options arrow_options, duckdb_logical_type *types, const char **names, idx_t column_count, struct ArrowSchema *out_schema)
Definition duckdb.cpp:263505
duckdb_logical_type duckdb_create_list_type(duckdb_logical_type type)
Definition duckdb.cpp:268533
duckdb_state duckdb_register_scalar_function(duckdb_connection connection, duckdb_scalar_function function)
Definition duckdb.cpp:270825
duckdb_value duckdb_create_decimal(duckdb_decimal input)
Definition duckdb.cpp:266720
duckdb_state duckdb_appender_close(duckdb_appender appender_p)
Definition duckdb.cpp:263444
duckdb_value duckdb_create_time_ns(duckdb_time_ns input)
Definition duckdb.cpp:266772
void duckdb_free(void *ptr)
Definition duckdb.cpp:268088
int32_t duckdb_value_int32(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271789
const char * duckdb_prepared_statement_column_name(duckdb_prepared_statement prepared_statement, idx_t col_idx)
Definition duckdb.cpp:269272
duckdb_type duckdb_enum_internal_type(duckdb_logical_type type)
Definition duckdb.cpp:268696
void duckdb_replacement_scan_set_error(duckdb_replacement_scan_info info_p, const char *error)
Definition duckdb.cpp:269730
duckdb_value duckdb_create_uint8(uint8_t input)
Definition duckdb.cpp:266649
duckdb_string duckdb_value_string(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271889
duckdb_state duckdb_append_uint64(duckdb_appender appender, uint64_t value)
Definition duckdb.cpp:263380
internal::named_arg< T, Char > arg(const S &name, const T &arg)
Definition duckdb.cpp:16242
duckdb_error_data duckdb_data_chunk_to_arrow(duckdb_arrow_options arrow_options, duckdb_data_chunk chunk, struct ArrowArray *out_arrow_array)
Definition duckdb.cpp:263534
int64_t duckdb_file_handle_write(duckdb_file_handle file, const void *buffer, int64_t size)
Definition duckdb.cpp:267493
duckdb_state duckdb_append_timestamp(duckdb_appender appender, duckdb_timestamp value)
Definition duckdb.cpp:263407
duckdb_state duckdb_arrow_array_scan(duckdb_connection connection, const char *table_name, duckdb_arrow_schema arrow_schema, duckdb_arrow_array arrow_array, duckdb_arrow_stream *out_stream)
Definition duckdb.cpp:263956
duckdb_type duckdb_decimal_internal_type(duckdb_logical_type type)
Definition duckdb.cpp:268677
float duckdb_value_float(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271850
void duckdb_copy_function_bind_set_bind_data(duckdb_copy_function_bind_info info, void *bind_data, duckdb_delete_callback_t destructor)
Definition duckdb.cpp:265366
const char * duckdb_table_function_bind_get_result_column_name(duckdb_bind_info bind_info, idx_t col_idx)
Definition duckdb.cpp:265857
duckdb_state duckdb_table_description_create_ext(duckdb_connection connection, const char *catalog, const char *schema, const char *table, duckdb_table_description *out)
Definition duckdb.cpp:270947
const char * duckdb_column_name(duckdb_result *result, idx_t col)
Definition duckdb.cpp:270161
void duckdb_log_storage_set_name(duckdb_log_storage log_storage, const char *name)
Definition duckdb.cpp:268449
bool duckdb_expression_is_foldable(duckdb_expression expr)
Definition duckdb.cpp:267280
char * duckdb_struct_type_child_name(duckdb_logical_type type, idx_t index)
Definition duckdb.cpp:268830
void * duckdb_aggregate_function_get_extra_info(duckdb_function_info info_p)
Definition duckdb.cpp:263041
char * duckdb_enum_dictionary_value(duckdb_logical_type type, idx_t index)
Definition duckdb.cpp:268721
void duckdb_destroy_log_storage(duckdb_log_storage *log_storage)
Definition duckdb.cpp:268418
void SetError(struct AdbcError *error, const std::string &message)
This method should only be called when the string is guaranteed to not be NULL.
Definition duckdb.cpp:30076
duckdb_state duckdb_column_has_default(duckdb_table_description table_description, idx_t index, bool *out)
Definition duckdb.cpp:271017
void * duckdb_copy_function_finalize_get_global_state(duckdb_copy_function_finalize_info info)
Definition duckdb.cpp:265727
uint8_t duckdb_decimal_scale(duckdb_logical_type type)
Definition duckdb.cpp:268669
void duckdb_destroy_data_chunk(duckdb_data_chunk *chunk)
Definition duckdb.cpp:265950
bool duckdb_value_is_null(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271926
duckdb_task_state duckdb_create_task_state(duckdb_database database)
Definition duckdb.cpp:271613
duckdb_state duckdb_query_arrow_array(duckdb_arrow result, duckdb_arrow_array *out_array)
Definition duckdb.cpp:263714
duckdb_state duckdb_execute_prepared_streaming(duckdb_prepared_statement prepared_statement, duckdb_result *out_result)
Definition duckdb.cpp:269509
void duckdb_table_function_set_name(duckdb_table_function function, const char *name)
Definition duckdb.cpp:271265
duckdb_state duckdb_append_varchar_length(duckdb_appender appender, const char *val, idx_t length)
Definition duckdb.cpp:263427
duckdb_value duckdb_create_null_value()
Definition duckdb.cpp:267112
duckdb_file_system duckdb_client_context_get_file_system(duckdb_client_context context)
Definition duckdb.cpp:267350
duckdb_selection_vector duckdb_create_selection_vector(idx_t size)
Definition duckdb.cpp:266183
duckdb_value duckdb_copy_function_bind_get_options(duckdb_copy_function_bind_info info)
Definition duckdb.cpp:265353
void duckdb_data_chunk_set_size(duckdb_data_chunk chunk, idx_t size)
Definition duckdb.cpp:266008
duckdb_state duckdb_appender_end_row(duckdb_appender appender_p)
Definition duckdb.cpp:263283
uint16_t duckdb_get_uint16(duckdb_value val)
Definition duckdb.cpp:266664
char * duckdb_value_varchar(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271885
duckdb_log_storage duckdb_create_log_storage()
Definition duckdb.cpp:268413
duckdb_state duckdb_table_description_create(duckdb_connection connection, const char *schema, const char *table, duckdb_table_description *out)
Definition duckdb.cpp:270942
void duckdb_table_description_destroy(duckdb_table_description *table)
Definition duckdb.cpp:270984
duckdb_state duckdb_append_float(duckdb_appender appender, float value)
Definition duckdb.cpp:263391
void * duckdb_scalar_function_get_extra_info(duckdb_function_info info)
Definition duckdb.cpp:270649
duckdb_state duckdb_appender_clear(duckdb_appender appender_p)
Definition duckdb.cpp:263440
duckdb_catalog_entry duckdb_catalog_get_entry(duckdb_catalog catalog, duckdb_client_context context, duckdb_catalog_entry_type entry_type, const char *schema_name, const char *entry_name)
Definition duckdb.cpp:264721
void duckdb_destroy_file_open_options(duckdb_file_open_options *options)
Definition duckdb.cpp:267401
duckdb_statement_type duckdb_result_statement_type(duckdb_result result)
Definition duckdb.cpp:270349
void duckdb_execute_tasks(duckdb_database database, idx_t max_tasks)
Definition duckdb.cpp:271604
duckdb_logical_type duckdb_struct_type_child_type(duckdb_logical_type type, idx_t index)
Definition duckdb.cpp:268848
duckdb_state duckdb_bind_uint16(duckdb_prepared_statement prepared_statement, idx_t param_idx, uint16_t val)
Definition duckdb.cpp:269401
duckdb_aggregate_function_set duckdb_create_aggregate_function_set(const char *name)
Definition duckdb.cpp:263052
void * duckdb_column_data(duckdb_result *result, idx_t col)
Definition duckdb.cpp:270242
duckdb_state duckdb_bind_uint32(duckdb_prepared_statement prepared_statement, idx_t param_idx, uint32_t val)
Definition duckdb.cpp:269406
duckdb_state duckdb_file_handle_close(duckdb_file_handle file)
Definition duckdb.cpp:267575
duckdb_logical_type duckdb_prepared_statement_column_logical_type(duckdb_prepared_statement prepared_statement, idx_t col_idx)
Definition duckdb.cpp:269285
duckdb_date_struct duckdb_from_date(duckdb_date date)
Definition duckdb.cpp:266237
idx_t duckdb_struct_type_child_count(duckdb_logical_type type)
Definition duckdb.cpp:268788
void duckdb_log_storage_set_extra_data(duckdb_log_storage log_storage, void *extra_data, duckdb_delete_callback_t delete_callback)
Definition duckdb.cpp:268438
const char * duckdb_table_description_error(duckdb_table_description table)
Definition duckdb.cpp:270993
duckdb_state duckdb_appender_create(duckdb_connection connection, const char *schema, const char *table, duckdb_appender *out_appender)
Definition duckdb.cpp:263137
duckdb_vector duckdb_data_chunk_get_vector(duckdb_data_chunk chunk, idx_t col_idx)
Definition duckdb.cpp:265992
char * duckdb_value_to_string(duckdb_value val)
Definition duckdb.cpp:267196
duckdb_state duckdb_bind_timestamp(duckdb_prepared_statement prepared_statement, idx_t param_idx, duckdb_timestamp val)
Definition duckdb.cpp:269436
void duckdb_cast_function_set_target_type(duckdb_cast_function cast_function, duckdb_logical_type target_type)
Definition duckdb.cpp:264492
void duckdb_table_function_set_function(duckdb_table_function table_function, duckdb_table_function_t function)
Definition duckdb.cpp:271330
void duckdb_copy_function_sink_set_error(duckdb_copy_function_sink_info info, const char *error)
Definition duckdb.cpp:265574
duckdb_state duckdb_bind_hugeint(duckdb_prepared_statement prepared_statement, idx_t param_idx, duckdb_hugeint val)
Definition duckdb.cpp:269386
duckdb_timestamp duckdb_get_timestamp(duckdb_value val)
Definition duckdb.cpp:266784
char * duckdb_get_varchar(duckdb_value value)
Definition duckdb.cpp:266884
void duckdb_copy_function_set_extra_info(duckdb_copy_function function, void *extra_info, duckdb_delete_callback_t destroy)
Definition duckdb.cpp:265208
bool duckdb_is_finite_timestamp(duckdb_timestamp ts)
Definition duckdb.cpp:266321
void duckdb_destroy_arrow_converted_schema(duckdb_arrow_converted_schema *arrow_converted_schema)
Definition duckdb.cpp:263640
duckdb_data_chunk duckdb_fetch_chunk(duckdb_result result)
Definition duckdb.cpp:270913
void duckdb_destroy_file_system(duckdb_file_system *file_system)
Definition duckdb.cpp:267359
idx_t duckdb_client_context_get_connection_id(duckdb_client_context context)
Definition duckdb.cpp:266508
duckdb_logical_type duckdb_create_enum_type(const char **member_names, idx_t member_count)
Definition duckdb.cpp:268606
void * duckdb_copy_function_finalize_get_extra_info(duckdb_copy_function_finalize_info info)
Definition duckdb.cpp:265697
idx_t duckdb_execute_n_tasks_state(duckdb_task_state state_p, idx_t max_tasks)
Definition duckdb.cpp:271632
duckdb_error_data duckdb_appender_error_data(duckdb_appender appender)
Definition duckdb.cpp:263268
idx_t duckdb_arrow_row_count(duckdb_arrow result)
Definition duckdb.cpp:263746
duckdb_state duckdb_bind_int16(duckdb_prepared_statement prepared_statement, idx_t param_idx, int16_t val)
Definition duckdb.cpp:269357
void duckdb_destroy_pending(duckdb_pending_result *pending_result)
Definition duckdb.cpp:268949
duckdb_state duckdb_bind_uint64(duckdb_prepared_statement prepared_statement, idx_t param_idx, uint64_t val)
Definition duckdb.cpp:269411
duckdb_profiling_info duckdb_get_profiling_info(duckdb_connection connection)
Definition duckdb.cpp:269562
duckdb_config_option duckdb_create_config_option()
Definition duckdb.cpp:264879
void duckdb_destroy_arrow(duckdb_arrow *result)
Definition duckdb.cpp:263781
void * duckdb_scalar_function_get_bind_data(duckdb_function_info info)
Definition duckdb.cpp:270665
duckdb_state duckdb_append_date(duckdb_appender appender, duckdb_date value)
Definition duckdb.cpp:263399
int8_t duckdb_get_int8(duckdb_value val)
Definition duckdb.cpp:266646
void duckdb_bind_add_result_column(duckdb_bind_info info, const char *name, duckdb_logical_type type)
Definition duckdb.cpp:271404
duckdb_logical_type duckdb_vector_get_column_type(duckdb_vector vector)
Definition duckdb.cpp:266016
void * duckdb_copy_function_bind_get_extra_info(duckdb_copy_function_bind_info info)
Definition duckdb.cpp:265317
duckdb_state duckdb_append_int8(duckdb_appender appender, int8_t value)
Definition duckdb.cpp:263345
void duckdb_table_function_set_bind(duckdb_table_function function, duckdb_table_function_bind_t bind)
Definition duckdb.cpp:271303
void duckdb_scalar_function_set_bind_data(duckdb_bind_info info, void *bind_data, duckdb_delete_callback_t destroy)
Definition duckdb.cpp:270738
bool duckdb_result_is_streaming(duckdb_result result)
Definition duckdb.cpp:270321
const char * duckdb_result_error(duckdb_result *result)
Definition duckdb.cpp:270262
duckdb_state duckdb_prepare(duckdb_connection connection, const char *query, duckdb_prepared_statement *out_prepared_statement)
Definition duckdb.cpp:269154
void duckdb_vector_assign_string_element(duckdb_vector vector, idx_t index, const char *str)
Definition duckdb.cpp:266056
void duckdb_vector_copy_sel(duckdb_vector src, duckdb_vector dst, duckdb_selection_vector sel, idx_t src_count, idx_t src_offset, idx_t dst_offset)
Definition duckdb.cpp:266201
duckdb_state duckdb_list_vector_reserve(duckdb_vector vector, idx_t required_capacity)
Definition duckdb.cpp:266123
duckdb_state duckdb_arrow_scan(duckdb_connection connection, const char *table_name, duckdb_arrow_stream arrow)
Definition duckdb.cpp:263927
uint32_t duckdb_get_uint32(duckdb_value val)
Definition duckdb.cpp:266676
void duckdb_bind_set_bind_data(duckdb_bind_info info, void *bind_data, duckdb_delete_callback_t destroy)
Definition duckdb.cpp:271448
void duckdb_scalar_function_init_get_client_context(duckdb_init_info info, duckdb_client_context *out_context)
Definition duckdb.cpp:270799
void duckdb_connection_get_arrow_options(duckdb_connection connection, duckdb_arrow_options *out_arrow_options)
Definition duckdb.cpp:266494
duckdb_state duckdb_appender_add_column(duckdb_appender appender_p, const char *name)
Definition duckdb.cpp:263249
duckdb_date duckdb_value_date(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271858
duckdb_state duckdb_file_handle_seek(duckdb_file_handle file, int64_t position)
Definition duckdb.cpp:267541
duckdb_state duckdb_bind_date(duckdb_prepared_statement prepared_statement, idx_t param_idx, duckdb_date val)
Definition duckdb.cpp:269426
duckdb_logical_type duckdb_list_type_child_type(duckdb_logical_type type)
Definition duckdb.cpp:268731
struct yyjson_mut_doc yyjson_mut_doc
Definition duckdb.cpp:37762
duckdb_pending_state duckdb_pending_execute_task(duckdb_pending_result pending_result)
Definition duckdb.cpp:269003
duckdb_error_data duckdb_data_chunk_from_arrow(duckdb_connection connection, struct ArrowArray *arrow_array, duckdb_arrow_converted_schema converted_schema, duckdb_data_chunk *out_chunk)
Definition duckdb.cpp:263580
void duckdb_result_arrow_array(duckdb_result result, duckdb_data_chunk chunk, duckdb_arrow_array *out_array)
Definition duckdb.cpp:263733
void duckdb_copy_function_set_name(duckdb_copy_function copy_function, const char *name)
Definition duckdb.cpp:265192
void duckdb_scalar_function_set_bind_data_copy(duckdb_bind_info info, duckdb_copy_callback_t copy)
Definition duckdb.cpp:270747
duckdb_state duckdb_append_value(duckdb_appender appender, duckdb_value value)
Definition duckdb.cpp:263475
idx_t duckdb_prepared_statement_column_count(duckdb_prepared_statement prepared_statement)
Definition duckdb.cpp:269264
duckdb_state duckdb_appender_create_query(duckdb_connection connection, const char *query, idx_t column_count, duckdb_logical_type *types_p, const char *table_name_p, const char **column_names_p, duckdb_appender *out_appender)
Definition duckdb.cpp:263170
duckdb_error_data duckdb_create_error_data(duckdb_error_type type, const char *message)
Definition duckdb.cpp:267214
void duckdb_table_function_set_local_init(duckdb_table_function function, duckdb_table_function_init_t init)
Definition duckdb.cpp:271321
void duckdb_destroy_task_state(duckdb_task_state state_p)
Definition duckdb.cpp:271662
char * duckdb_value_varchar_internal(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271893
void duckdb_scalar_function_set_init(duckdb_scalar_function function, duckdb_scalar_function_init_t init_func)
Definition duckdb.cpp:270772
char * duckdb_logical_type_get_alias(duckdb_logical_type type)
Definition duckdb.cpp:268838
duckdb_value duckdb_create_varchar_length(const char *text, idx_t length)
Definition duckdb.cpp:266611
duckdb_value duckdb_create_timestamp_ms(duckdb_timestamp_ms input)
Definition duckdb.cpp:266815
bool duckdb_value_boolean(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271777
duckdb_logical_type duckdb_create_array_type(duckdb_logical_type type, idx_t array_size)
Definition duckdb.cpp:268546
duckdb_logical_type duckdb_map_type_value_type(duckdb_logical_type type)
Definition duckdb.cpp:268777
duckdb_uhugeint duckdb_get_uhugeint(duckdb_value val)
Definition duckdb.cpp:266701
duckdb_state duckdb_bind_boolean(duckdb_prepared_statement prepared_statement, idx_t param_idx, bool val)
Definition duckdb.cpp:269347
double duckdb_decimal_to_double(duckdb_decimal val)
Definition duckdb.cpp:268342
const char * duckdb_catalog_entry_get_name(duckdb_catalog_entry entry)
Definition duckdb.cpp:264754
void duckdb_scalar_function_set_return_type(duckdb_scalar_function function, duckdb_logical_type type)
Definition duckdb.cpp:270640
duckdb_value duckdb_create_bignum(duckdb_bignum input)
Definition duckdb.cpp:266705
duckdb_expression duckdb_scalar_function_bind_get_argument(duckdb_bind_info info, idx_t index)
Definition duckdb.cpp:270708
duckdb_date duckdb_to_date(duckdb_date_struct date)
Definition duckdb.cpp:266248
duckdb_logical_type duckdb_create_logical_type(duckdb_type type)
Definition duckdb.cpp:268522
duckdb_type duckdb_param_type(duckdb_prepared_statement prepared_statement, idx_t param_idx)
Definition duckdb.cpp:269218
duckdb_value duckdb_create_timestamp(duckdb_timestamp input)
Definition duckdb.cpp:266779
const char * duckdb_prepare_error(duckdb_prepared_statement prepared_statement)
Definition duckdb.cpp:269175
duckdb_value duckdb_create_hugeint(duckdb_hugeint input)
Definition duckdb.cpp:266691
duckdb_state duckdb_add_scalar_function_to_set(duckdb_scalar_function_set set, duckdb_scalar_function function)
Definition duckdb.cpp:270851
void duckdb_destroy_config_option(duckdb_config_option *option)
Definition duckdb.cpp:264884
duckdb_time_tz duckdb_get_time_tz(duckdb_value val)
Definition duckdb.cpp:266769
duckdb_blob duckdb_get_blob(duckdb_value val)
Definition duckdb.cpp:266849
duckdb_state duckdb_open_ext(const char *path, duckdb_database *out, duckdb_config config, char **error)
Definition duckdb.cpp:266416
void duckdb_destroy_error_data(duckdb_error_data *error_data)
Definition duckdb.cpp:267220
void duckdb_scalar_function_set_volatile(duckdb_scalar_function function)
Definition duckdb.cpp:270623
uint32_t duckdb_string_t_length(duckdb_string_t string_p)
Definition duckdb.cpp:268103
void * duckdb_scalar_function_get_state(duckdb_function_info info)
Definition duckdb.cpp:270764
void duckdb_scalar_function_set_bind(duckdb_scalar_function scalar_function, duckdb_scalar_function_bind_t bind)
Definition duckdb.cpp:270729
duckdb_state duckdb_prepared_arrow_schema(duckdb_prepared_statement prepared, duckdb_arrow_schema *out_schema)
Definition duckdb.cpp:263675
duckdb_scalar_function_set duckdb_create_scalar_function_set(const char *name)
Definition duckdb.cpp:270835
duckdb_value duckdb_create_array_value(duckdb_logical_type type, duckdb_value *values, idx_t value_count)
Definition duckdb.cpp:266954
void duckdb_unsafe_vector_assign_string_element_len(duckdb_vector vector, idx_t index, const char *str, idx_t str_len)
Definition duckdb.cpp:266089
void duckdb_logical_type_set_alias(duckdb_logical_type type, const char *alias)
Definition duckdb.cpp:268843
duckdb_state duckdb_bind_varchar_length(duckdb_prepared_statement prepared_statement, idx_t param_idx, const char *val, idx_t length)
Definition duckdb.cpp:269462
double duckdb_value_double(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271854
duckdb_file_open_options duckdb_create_file_open_options()
Definition duckdb.cpp:267368
void duckdb_copy_function_set_finalize(duckdb_copy_function copy_function, duckdb_copy_function_finalize_t finalize)
Definition duckdb.cpp:265674
duckdb_time_struct duckdb_from_time(duckdb_time time)
Definition duckdb.cpp:266258
void * duckdb_copy_function_sink_get_global_state(duckdb_copy_function_sink_info info)
Definition duckdb.cpp:265613
duckdb_state duckdb_append_varchar(duckdb_appender appender, const char *val)
Definition duckdb.cpp:263423
void duckdb_destroy_logical_type(duckdb_logical_type *type)
Definition duckdb.cpp:268653
duckdb_value duckdb_create_uint32(uint32_t input)
Definition duckdb.cpp:266673
duckdb_state duckdb_append_hugeint(duckdb_appender appender, duckdb_hugeint value)
Definition duckdb.cpp:263361
void duckdb_cast_function_set_function(duckdb_cast_function cast_function, duckdb_cast_function_t function)
Definition duckdb.cpp:264509
duckdb_date duckdb_get_date(duckdb_value val)
Definition duckdb.cpp:266757
duckdb_state duckdb_bind_double(duckdb_prepared_statement prepared_statement, idx_t param_idx, double val)
Definition duckdb.cpp:269421
duckdb_value duckdb_create_int32(int32_t input)
Definition duckdb.cpp:266667
idx_t duckdb_bind_get_parameter_count(duckdb_bind_info info)
Definition duckdb.cpp:271419
bool duckdb_is_finite_timestamp_ms(duckdb_timestamp_ms ts)
Definition duckdb.cpp:266329
duckdb_instance_cache duckdb_create_instance_cache()
Definition duckdb.cpp:266347
duckdb_logical_type duckdb_create_decimal_type(uint8_t width, uint8_t scale)
Definition duckdb.cpp:268641
void duckdb_destroy_arrow_stream(duckdb_arrow_stream *stream_p)
Definition duckdb.cpp:263789
bool duckdb_string_is_inlined(duckdb_string_t string_p)
Definition duckdb.cpp:268096
duckdb_state duckdb_list_vector_set_size(duckdb_vector vector, idx_t size)
Definition duckdb.cpp:266114
void duckdb_destroy_value(duckdb_value *value)
Definition duckdb.cpp:266603
void duckdb_slice_vector(duckdb_vector dict, duckdb_selection_vector sel, idx_t len)
Definition duckdb.cpp:266195
idx_t duckdb_table_function_bind_get_result_column_count(duckdb_bind_info bind_info)
Definition duckdb.cpp:265838
duckdb_state duckdb_register_logical_type(duckdb_connection connection, duckdb_logical_type type, duckdb_create_type_info info)
Definition duckdb.cpp:268860
duckdb_state duckdb_prepare_extracted_statement(duckdb_connection connection, duckdb_extracted_statements extracted_statements, idx_t index, duckdb_prepared_statement *out_prepared_statement)
Definition duckdb.cpp:269122
uint64_t * duckdb_vector_get_validity(duckdb_vector vector)
Definition duckdb.cpp:266032
void duckdb_aggregate_function_set_extra_info(duckdb_aggregate_function function, void *extra_info, duckdb_delete_callback_t destroy)
Definition duckdb.cpp:263025
void duckdb_cast_function_set_extra_info(duckdb_cast_function cast_function, void *extra_info, duckdb_delete_callback_t destroy)
Definition duckdb.cpp:264537
duckdb_value duckdb_create_bit(duckdb_bit input)
Definition duckdb.cpp:266857
duckdb_logical_type duckdb_map_type_key_type(duckdb_logical_type type)
Definition duckdb.cpp:268766
void duckdb_aggregate_function_set_name(duckdb_aggregate_function function, const char *name)
Definition duckdb.cpp:262955
duckdb_interval duckdb_value_interval(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271876
const char * duckdb_pending_error(duckdb_pending_result pending_result)
Definition duckdb.cpp:268961
duckdb_state duckdb_create_config(duckdb_config *out_config)
Definition duckdb.cpp:264779
duckdb_value duckdb_create_uint16(uint16_t input)
Definition duckdb.cpp:266661
void duckdb_copy_function_set_copy_from_function(duckdb_copy_function copy_function, duckdb_table_function table_function)
Definition duckdb.cpp:265805
int printf(const S &format_str, const Args &... args)
Definition duckdb.cpp:71838
void duckdb_init_set_max_threads(duckdb_init_info info, idx_t max_threads)
Definition duckdb.cpp:271536
duckdb_type duckdb_get_type_id(duckdb_logical_type type)
Definition duckdb.cpp:268645
bool duckdb_validity_row_is_valid(uint64_t *validity, idx_t row)
Definition duckdb.cpp:266148
void duckdb_aggregate_function_set_return_type(duckdb_aggregate_function function, duckdb_logical_type type)
Definition duckdb.cpp:262972
void duckdb_bind_set_error(duckdb_bind_info info, const char *error)
Definition duckdb.cpp:271469
void duckdb_scalar_function_init_set_error(duckdb_init_info info, const char *error)
Definition duckdb.cpp:270781
idx_t duckdb_profiling_info_get_child_count(duckdb_profiling_info info)
Definition duckdb.cpp:269622
void duckdb_destroy_client_context(duckdb_client_context *context)
Definition duckdb.cpp:266513
duckdb_state duckdb_register_copy_function(duckdb_connection connection, duckdb_copy_function copy_function)
Definition duckdb.cpp:265871
void duckdb_log_storage_set_write_log_entry(duckdb_log_storage log_storage, duckdb_logger_write_log_entry_t function)
Definition duckdb.cpp:268429
uint64_t duckdb_value_uint64(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271846
duckdb_state duckdb_bind_value(duckdb_prepared_statement prepared_statement, idx_t param_idx, duckdb_value val)
Definition duckdb.cpp:269310
void duckdb_execute_tasks_state(duckdb_task_state state_p)
Definition duckdb.cpp:271622
duckdb_logical_type duckdb_table_description_get_column_type(duckdb_table_description table_description, idx_t index)
Definition duckdb.cpp:271060
uint8_t duckdb_value_uint8(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271834
void duckdb_bind_set_cardinality(duckdb_bind_info info, idx_t cardinality, bool is_exact)
Definition duckdb.cpp:271457
duckdb_timestamp_struct duckdb_from_timestamp(duckdb_timestamp ts)
Definition duckdb.cpp:266295
void duckdb_destroy_scalar_function(duckdb_scalar_function *function)
Definition duckdb.cpp:270590
const char * duckdb_catalog_get_type_name(duckdb_catalog catalog)
Definition duckdb.cpp:264713
void * duckdb_copy_function_sink_get_extra_info(duckdb_copy_function_sink_info info)
Definition duckdb.cpp:265584
void duckdb_scalar_function_set_special_handling(duckdb_scalar_function function)
Definition duckdb.cpp:270615
duckdb_value duckdb_create_uhugeint(duckdb_uhugeint input)
Definition duckdb.cpp:266698
duckdb_state duckdb_set_config(duckdb_config config, const char *name, const char *option)
Definition duckdb.cpp:264839
duckdb_data_chunk duckdb_create_data_chunk(duckdb_logical_type *column_types, idx_t column_count)
Definition duckdb.cpp:265925
int64_t duckdb_value_int64(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271793
duckdb_state duckdb_bind_blob(duckdb_prepared_statement prepared_statement, idx_t param_idx, const void *data, idx_t length)
Definition duckdb.cpp:269483
double duckdb_hugeint_to_double(duckdb_hugeint val)
Definition duckdb.cpp:268282
void duckdb_destroy_aggregate_function(duckdb_aggregate_function *function)
Definition duckdb.cpp:262947
idx_t duckdb_init_get_column_index(duckdb_init_info info, idx_t column_index)
Definition duckdb.cpp:271525
duckdb_state duckdb_append_interval(duckdb_appender appender, duckdb_interval value)
Definition duckdb.cpp:263411
duckdb_string duckdb_value_string_internal(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271897
duckdb_value duckdb_create_timestamp_s(duckdb_timestamp_s input)
Definition duckdb.cpp:266803
duckdb_error_data duckdb_file_system_error_data(duckdb_file_system fs)
Definition duckdb.cpp:267447
idx_t duckdb_list_vector_get_size(duckdb_vector vector)
Definition duckdb.cpp:266106
duckdb_state duckdb_append_blob(duckdb_appender appender, const void *data, idx_t length)
Definition duckdb.cpp:263431
void duckdb_destroy_cast_function(duckdb_cast_function *cast_function)
Definition duckdb.cpp:264596
duckdb_state duckdb_append_uint32(duckdb_appender appender, uint32_t value)
Definition duckdb.cpp:263376
void duckdb_scalar_function_set_function(duckdb_scalar_function function, duckdb_scalar_function_t execute_func)
Definition duckdb.cpp:270755
void duckdb_vector_reference_value(duckdb_vector vector, duckdb_value value)
Definition duckdb.cpp:266209
duckdb_timestamp duckdb_to_timestamp(duckdb_timestamp_struct ts)
Definition duckdb.cpp:266312
duckdb_state duckdb_get_config_flag(size_t index, const char **out_name, const char **out_description)
Definition duckdb.cpp:264799
duckdb_logical_type duckdb_create_struct_type(duckdb_logical_type *member_types_p, const char **member_names, idx_t member_count)
Definition duckdb.cpp:268581
duckdb_cast_function duckdb_create_cast_function()
Definition duckdb.cpp:264478
void * duckdb_function_get_extra_info(duckdb_function_info info)
Definition duckdb.cpp:271549
duckdb_scalar_function duckdb_create_scalar_function()
Definition duckdb.cpp:270582
idx_t duckdb_copy_function_bind_get_column_count(duckdb_copy_function_bind_info info)
Definition duckdb.cpp:265334
duckdb_value duckdb_profiling_info_get_value(duckdb_profiling_info info, const char *key)
Definition duckdb.cpp:269580
int16_t duckdb_value_int16(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271785
float duckdb_get_float(duckdb_value val)
Definition duckdb.cpp:266745
duckdb_time duckdb_value_time(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271864
duckdb_error_type duckdb_error_data_error_type(duckdb_error_data error_data)
Definition duckdb.cpp:267229
duckdb_state duckdb_bind_int32(duckdb_prepared_statement prepared_statement, idx_t param_idx, int32_t val)
Definition duckdb.cpp:269362
duckdb_blob duckdb_value_blob(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271913
duckdb_state duckdb_append_bool(duckdb_appender appender, bool value)
Definition duckdb.cpp:263341
duckdb_error_type duckdb_result_error_type(duckdb_result *result)
Definition duckdb.cpp:270270
duckdb_value duckdb_create_blob(const uint8_t *data, idx_t length)
Definition duckdb.cpp:266846
duckdb_state duckdb_pending_prepared(duckdb_prepared_statement prepared_statement, duckdb_pending_result *out_result)
Definition duckdb.cpp:268940
duckdb_value duckdb_get_table_names(duckdb_connection connection, const char *query, bool qualified)
Definition duckdb.cpp:266543
duckdb_value duckdb_get_map_value(duckdb_value value, idx_t index)
Definition duckdb.cpp:267085
duckdb_state duckdb_bind_parameter_index(duckdb_prepared_statement prepared_statement, idx_t *param_idx_out, const char *name_p)
Definition duckdb.cpp:269328
void duckdb_destroy_extracted(duckdb_extracted_statements *extracted_statements)
Definition duckdb.cpp:269546
void duckdb_copy_function_set_global_init(duckdb_copy_function copy_function, duckdb_copy_function_global_init_t init)
Definition duckdb.cpp:265440
duckdb_uhugeint duckdb_value_uhugeint(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271826
duckdb_error_data duckdb_expression_fold(duckdb_client_context context, duckdb_expression expr, duckdb_value *out_value)
Definition duckdb.cpp:267288
int64_t duckdb_file_handle_size(duckdb_file_handle file)
Definition duckdb.cpp:267525
duckdb_state duckdb_register_scalar_function_set(duckdb_connection connection, duckdb_scalar_function_set set)
Definition duckdb.cpp:270861
void duckdb_destroy_arrow_options(duckdb_arrow_options *arrow_options)
Definition duckdb.cpp:266521
sel_t * duckdb_selection_vector_get_data_ptr(duckdb_selection_vector sel)
Definition duckdb.cpp:266191
duckdb_logical_type duckdb_appender_column_type(duckdb_appender appender, idx_t col_idx)
Definition duckdb.cpp:263461
void duckdb_validity_set_row_validity(uint64_t *validity, idx_t row, bool valid)
Definition duckdb.cpp:266157
duckdb_hugeint duckdb_value_hugeint(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271818
idx_t duckdb_arrow_rows_changed(duckdb_arrow result)
Definition duckdb.cpp:263759
void duckdb_add_replacement_scan(duckdb_database db, duckdb_replacement_callback_t replacement, void *extra_data, duckdb_delete_callback_t delete_callback)
Definition duckdb.cpp:269697
const char * duckdb_error_data_message(duckdb_error_data error_data)
Definition duckdb.cpp:267238
duckdb_state duckdb_append_data_chunk(duckdb_appender appender_p, duckdb_data_chunk chunk)
Definition duckdb.cpp:263479
void duckdb_table_function_add_named_parameter(duckdb_table_function function, const char *name, duckdb_logical_type type)
Definition duckdb.cpp:271282
void duckdb_destroy_prepare(duckdb_prepared_statement *prepared_statement)
Definition duckdb.cpp:269550
duckdb_time_tz_struct duckdb_from_time_tz(duckdb_time_tz input)
Definition duckdb.cpp:266270
duckdb_uhugeint duckdb_double_to_uhugeint(double val)
Definition duckdb.cpp:268329
duckdb_value duckdb_create_double(double input)
Definition duckdb.cpp:266748
void duckdb_config_option_set_default_value(duckdb_config_option option, duckdb_value default_value)
Definition duckdb.cpp:264910
idx_t duckdb_vector_size()
Definition duckdb.cpp:268092
void duckdb_config_option_set_default_scope(duckdb_config_option option, duckdb_config_option_scope scope)
Definition duckdb.cpp:264931
duckdb_timestamp_ms duckdb_get_timestamp_ms(duckdb_value val)
Definition duckdb.cpp:266820
void * duckdb_init_get_extra_info(duckdb_init_info info)
Definition duckdb.cpp:271483
void duckdb_destroy_catalog_entry(duckdb_catalog_entry *entry)
Definition duckdb.cpp:264762
duckdb_value duckdb_create_timestamp_tz(duckdb_timestamp input)
Definition duckdb.cpp:266791
duckdb_value duckdb_create_time(duckdb_time input)
Definition duckdb.cpp:266760
void duckdb_config_option_set_name(duckdb_config_option option, const char *name)
Definition duckdb.cpp:264894
int8_t duckdb_value_int8(duckdb_result *result, idx_t col, idx_t row)
Definition duckdb.cpp:271781
idx_t duckdb_rows_changed(duckdb_result *result)
Definition duckdb.cpp:270221
duckdb_value duckdb_create_uint64(uint64_t input)
Definition duckdb.cpp:266679
duckdb_client_context duckdb_copy_function_global_init_get_client_context(duckdb_copy_function_global_init_info info)
Definition duckdb.cpp:265472
bool duckdb_pending_execution_is_finished(duckdb_pending_state pending_state)
Definition duckdb.cpp:269035
duckdb_value duckdb_create_interval(duckdb_interval input)
Definition duckdb.cpp:266839
duckdb_state duckdb_file_open_options_set_flag(duckdb_file_open_options options, duckdb_file_flag flag, bool value)
Definition duckdb.cpp:267373
bool * duckdb_nullmask_data(duckdb_result *result, idx_t col)
Definition duckdb.cpp:270252
const char * duckdb_appender_error(duckdb_appender appender)
Definition duckdb.cpp:263257
duckdb_statement_type duckdb_prepared_statement_type(duckdb_prepared_statement statement)
Definition duckdb.cpp:269524
duckdb_state duckdb_clear_bindings(duckdb_prepared_statement prepared_statement)
Definition duckdb.cpp:269255
double duckdb_get_double(duckdb_value val)
Definition duckdb.cpp:266751
void * duckdb_bind_get_extra_info(duckdb_bind_info info)
Definition duckdb.cpp:271387
void duckdb_aggregate_function_set_functions(duckdb_aggregate_function function, duckdb_aggregate_state_size state_size, duckdb_aggregate_init_t state_init, duckdb_aggregate_update_t update, duckdb_aggregate_combine_t combine, duckdb_aggregate_finalize_t finalize)
Definition duckdb.cpp:262981
duckdb_state duckdb_bind_timestamp_tz(duckdb_prepared_statement prepared_statement, idx_t param_idx, duckdb_timestamp val)
Definition duckdb.cpp:269442
void duckdb_table_function_set_extra_info(duckdb_table_function function, void *extra_info, duckdb_delete_callback_t destroy)
Definition duckdb.cpp:271292
void duckdb_destroy_table_function(duckdb_table_function *function)
Definition duckdb.cpp:271257
void duckdb_copy_function_set_sink(duckdb_copy_function copy_function, duckdb_copy_function_sink_t function)
Definition duckdb.cpp:265563
duckdb_value duckdb_create_list_value(duckdb_logical_type type, duckdb_value *values, idx_t value_count)
Definition duckdb.cpp:266926
duckdb_logical_type duckdb_table_function_bind_get_result_column_type(duckdb_bind_info bind_info, idx_t col_idx)
Definition duckdb.cpp:265846
void duckdb_cast_function_set_error(duckdb_function_info info, const char *error)
Definition duckdb.cpp:264522
idx_t duckdb_get_list_size(duckdb_value value)
Definition duckdb.cpp:267116
void duckdb_scalar_function_bind_set_error(duckdb_bind_info info, const char *error)
Definition duckdb.cpp:270691
duckdb_state duckdb_append_int64(duckdb_appender appender, int64_t value)
Definition duckdb.cpp:263357
idx_t duckdb_array_type_array_size(duckdb_logical_type type)
Definition duckdb.cpp:268755
duckdb_value duckdb_bind_get_named_parameter(duckdb_bind_info info, const char *name)
Definition duckdb.cpp:271435
bool duckdb_is_finite_date(duckdb_date date)
Definition duckdb.cpp:266254
void duckdb_copy_function_set_bind(duckdb_copy_function copy_function, duckdb_copy_function_bind_t bind)
Definition duckdb.cpp:265294
uint32_t duckdb_enum_dictionary_size(duckdb_logical_type type)
Definition duckdb.cpp:268713
idx_t duckdb_data_chunk_get_size(duckdb_data_chunk chunk)
Definition duckdb.cpp:266000
uint64_t duckdb_get_enum_value(duckdb_value value)
Definition duckdb.cpp:267165
duckdb_state duckdb_add_aggregate_function_to_set(duckdb_aggregate_function_set set, duckdb_aggregate_function function)
Definition duckdb.cpp:263072
const char * duckdb_copy_function_global_init_get_file_path(duckdb_copy_function_global_init_info info)
Definition duckdb.cpp:265501
idx_t duckdb_result_chunk_count(duckdb_result result)
Definition duckdb.cpp:270281
bool duckdb_task_state_is_finished(duckdb_task_state state_p)
Definition duckdb.cpp:271654
duckdb_value duckdb_create_struct_value(duckdb_logical_type type, duckdb_value *values)
Definition duckdb.cpp:266894
duckdb_logical_type duckdb_union_type_member_type(duckdb_logical_type type, idx_t index)
Definition duckdb.cpp:268818
duckdb_hugeint duckdb_double_to_hugeint(double val)
Definition duckdb.cpp:268316
void duckdb_validity_set_row_valid(uint64_t *validity, idx_t row)
Definition duckdb.cpp:266174
duckdb_state duckdb_execute_pending(duckdb_pending_result pending_result, duckdb_result *out_result)
Definition duckdb.cpp:269050
void duckdb_destroy_result(duckdb_result *result)
Definition duckdb.cpp:270147
duckdb_type duckdb_column_type(duckdb_result *result, idx_t col)
Definition duckdb.cpp:270169
duckdb_state duckdb_execute_prepared_arrow(duckdb_prepared_statement prepared_statement, duckdb_arrow *out_result)
Definition duckdb.cpp:263803
idx_t duckdb_table_description_get_column_count(duckdb_table_description table_description)
Definition duckdb.cpp:271033
duckdb_value duckdb_create_time_tz_value(duckdb_time_tz input)
Definition duckdb.cpp:266766
duckdb_state duckdb_pending_prepared_streaming(duckdb_prepared_statement prepared_statement, duckdb_pending_result *out_result)
Definition duckdb.cpp:268944
char * duckdb_geometry_type_get_crs(duckdb_logical_type type)
Definition duckdb.cpp:268894
duckdb_state duckdb_bind_null(duckdb_prepared_statement prepared_statement, idx_t param_idx)
Definition duckdb.cpp:269489
void duckdb_scalar_function_set_varargs(duckdb_scalar_function function, duckdb_logical_type type)
Definition duckdb.cpp:270606
void duckdb_interrupt(duckdb_connection connection)
Definition duckdb.cpp:266449
duckdb_state duckdb_query_arrow_schema(duckdb_arrow result, duckdb_arrow_schema *out_schema)
Definition duckdb.cpp:263661
duckdb_state duckdb_register_table_function(duckdb_connection connection, duckdb_table_function function)
Definition duckdb.cpp:271347
void duckdb_scalar_function_set_name(duckdb_scalar_function function, const char *name)
Definition duckdb.cpp:270598
idx_t duckdb_scalar_function_bind_get_argument_count(duckdb_bind_info info)
Definition duckdb.cpp:270700
duckdb_value duckdb_get_list_child(duckdb_value value, idx_t index)
Definition duckdb.cpp:267130
void duckdb_scalar_function_get_client_context(duckdb_bind_info info, duckdb_client_context *out_context)
Definition duckdb.cpp:270673
ArrowType
Arrow type enumerator.
Definition duckdb.cpp:26806
void * duckdb_scalar_function_init_get_bind_data(duckdb_init_info info)
Definition duckdb.cpp:270809
duckdb_state duckdb_register_aggregate_function(duckdb_connection connection, duckdb_aggregate_function function)
Definition duckdb.cpp:263006
void * duckdb_function_get_bind_data(duckdb_function_info info)
Definition duckdb.cpp:271557
void * duckdb_function_get_init_data(duckdb_function_info info)
Definition duckdb.cpp:271565
duckdb_query_progress_type duckdb_query_progress(duckdb_connection connection)
Definition duckdb.cpp:266457
duckdb_value duckdb_create_int8(int8_t input)
Definition duckdb.cpp:266643
duckdb_value duckdb_create_bool(bool input)
Definition duckdb.cpp:266637
duckdb_logical_type duckdb_create_union_type(duckdb_logical_type *member_types_p, const char **member_names, idx_t member_count)
Definition duckdb.cpp:268562
size_t duckdb_config_count()
Definition duckdb.cpp:264794
void duckdb_copy_function_global_init_set_error(duckdb_copy_function_global_init_info info, const char *error)
Definition duckdb.cpp:265451
duckdb_value duckdb_create_int16(int16_t input)
Definition duckdb.cpp:266655
duckdb_state duckdb_register_config_option(duckdb_connection connection, duckdb_config_option option)
Definition duckdb.cpp:264961
void duckdb_disconnect(duckdb_connection *connection)
Definition duckdb.cpp:266473
idx_t duckdb_column_count(duckdb_result *result)
Definition duckdb.cpp:270197
duckdb_state duckdb_bind_float(duckdb_prepared_statement prepared_statement, idx_t param_idx, float val)
Definition duckdb.cpp:269416
duckdb_state duckdb_connect(duckdb_database database, duckdb_connection *out)
Definition duckdb.cpp:266432
uint64_t duckdb_get_uint64(duckdb_value val)
Definition duckdb.cpp:266682
bool duckdb_execution_is_finished(duckdb_connection con)
Definition duckdb.cpp:271670
duckdb_interval duckdb_get_interval(duckdb_value val)
Definition duckdb.cpp:266842
duckdb_catalog_entry_type duckdb_catalog_entry_get_type(duckdb_catalog_entry entry)
Definition duckdb.cpp:264745
duckdb_copy_function duckdb_create_copy_function()
Definition duckdb.cpp:265184
duckdb_value duckdb_create_enum_value(duckdb_logical_type type, uint64_t value)
Definition duckdb.cpp:267148
duckdb_state duckdb_query(duckdb_connection connection, const char *query, duckdb_result *out)
Definition duckdb.cpp:266529
void * duckdb_copy_function_global_init_get_bind_data(duckdb_copy_function_global_init_info info)
Definition duckdb.cpp:265481
duckdb_result_type duckdb_result_return_type(duckdb_result result)
Definition duckdb.cpp:270332
void * duckdb_scalar_function_init_get_extra_info(duckdb_init_info info)
Definition duckdb.cpp:270817
void duckdb_scalar_function_set_extra_info(duckdb_scalar_function function, void *extra_info, duckdb_delete_callback_t destroy)
Definition duckdb.cpp:270718
duckdb_logical_type duckdb_expression_return_type(duckdb_expression expr)
Definition duckdb.cpp:267271
duckdb_data_chunk duckdb_stream_fetch_chunk(duckdb_result result)
Definition duckdb.cpp:270901
void duckdb_destroy_copy_function(duckdb_copy_function *copy_function)
Definition duckdb.cpp:265200
duckdb_state duckdb_file_handle_sync(duckdb_file_handle file)
Definition duckdb.cpp:267558
duckdb_state duckdb_append_null(duckdb_appender appender)
Definition duckdb.cpp:263419
duckdb_time duckdb_to_time(duckdb_time_struct time)
Definition duckdb.cpp:266289
duckdb_state duckdb_append_int32(duckdb_appender appender, int32_t value)
Definition duckdb.cpp:263353
duckdb_data_chunk duckdb_result_get_chunk(duckdb_result result, idx_t chunk_idx)
Definition duckdb.cpp:270297
duckdb_timestamp duckdb_get_timestamp_tz(duckdb_value val)
Definition duckdb.cpp:266796
bool duckdb_is_null_value(duckdb_value value)
Definition duckdb.cpp:267105
int64_t duckdb_file_handle_tell(duckdb_file_handle file)
Definition duckdb.cpp:267509
std::basic_string< Char > format(const S &format_str, Args &&... args)
Definition duckdb.cpp:16295
duckdb_vector duckdb_create_vector(duckdb_logical_type type, idx_t capacity)
Definition duckdb.cpp:265966
int64_t duckdb_file_handle_read(duckdb_file_handle file, void *buffer, int64_t size)
Definition duckdb.cpp:267477
duckdb_pending_state duckdb_pending_execute_check_state(duckdb_pending_result pending_result)
Definition duckdb.cpp:268972
idx_t duckdb_appender_column_count(duckdb_appender appender)
Definition duckdb.cpp:263448
duckdb_vector duckdb_array_vector_get_child(duckdb_vector vector)
Definition duckdb.cpp:266140
const char * duckdb_query_arrow_error(duckdb_arrow result)
Definition duckdb.cpp:263776
void duckdb_cast_function_set_source_type(duckdb_cast_function cast_function, duckdb_logical_type source_type)
Definition duckdb.cpp:264483
duckdb_state duckdb_append_default(duckdb_appender appender)
Definition duckdb.cpp:263304
bool duckdb_is_finite_timestamp_ns(duckdb_timestamp_ns ts)
Definition duckdb.cpp:266333
duckdb_value duckdb_client_context_get_config_option(duckdb_client_context context, const char *option_name, duckdb_config_option_scope *out_scope)
Definition duckdb.cpp:264988
duckdb_logical_type duckdb_param_logical_type(duckdb_prepared_statement prepared_statement, idx_t param_idx)
Definition duckdb.cpp:269230
void duckdb_scalar_function_add_parameter(duckdb_scalar_function function, duckdb_logical_type type)
Definition duckdb.cpp:270631
duckdb_state duckdb_bind_interval(duckdb_prepared_statement prepared_statement, idx_t param_idx, duckdb_interval val)
Definition duckdb.cpp:269448
void * duckdb_vector_get_data(duckdb_vector vector)
Definition duckdb.cpp:266024
idx_t duckdb_get_map_size(duckdb_value value)
Definition duckdb.cpp:267051
duckdb_state duckdb_register_aggregate_function_set(duckdb_connection connection, duckdb_aggregate_function_set function_set)
Definition duckdb.cpp:263083
void duckdb_copy_function_global_init_set_global_state(duckdb_copy_function_global_init_info info, void *global_state, duckdb_delete_callback_t destructor)
Definition duckdb.cpp:265491
duckdb_value duckdb_create_varchar(const char *text)
Definition duckdb.cpp:266619
void * duckdb_copy_function_finalize_get_bind_data(duckdb_copy_function_finalize_info info)
Definition duckdb.cpp:265717
void * duckdb_cast_function_get_extra_info(duckdb_function_info info)
Definition duckdb.cpp:264547
void duckdb_table_function_set_init(duckdb_table_function function, duckdb_table_function_init_t init)
Definition duckdb.cpp:271312
void duckdb_init_set_init_data(duckdb_init_info info, void *init_data, duckdb_delete_callback_t destroy)
Definition duckdb.cpp:271499
void * duckdb_scalar_function_bind_get_extra_info(duckdb_bind_info info)
Definition duckdb.cpp:270657
void duckdb_cast_function_set_implicit_cast_cost(duckdb_cast_function cast_function, int64_t cost)
Definition duckdb.cpp:264501
idx_t duckdb_init_get_column_count(duckdb_init_info info)
Definition duckdb.cpp:271517
duckdb_error_data duckdb_file_handle_error_data(duckdb_file_handle file)
Definition duckdb.cpp:267467
void duckdb_aggregate_function_set_destructor(duckdb_aggregate_function function, duckdb_aggregate_destroy_t destroy)
Definition duckdb.cpp:262996
duckdb_bignum duckdb_get_bignum(duckdb_value val)
Definition duckdb.cpp:266709
void duckdb_function_set_error(duckdb_function_info info, const char *error)
Definition duckdb.cpp:271581
duckdb_state duckdb_open(const char *path, duckdb_database *out)
Definition duckdb.cpp:266420
bool duckdb_error_data_has_error(duckdb_error_data error_data)
Definition duckdb.cpp:267247
duckdb_state duckdb_append_default_to_chunk(duckdb_appender appender, duckdb_data_chunk chunk, idx_t col, idx_t row)
Definition duckdb.cpp:263321
duckdb_error_data duckdb_valid_utf8_check(const char *str, idx_t len)
Definition duckdb.cpp:268117
duckdb_catalog duckdb_client_context_get_catalog(duckdb_client_context context, const char *name)
Definition duckdb.cpp:264683
void duckdb_destroy_selection_vector(duckdb_selection_vector sel)
Definition duckdb.cpp:266187
duckdb_time duckdb_get_time(duckdb_value val)
Definition duckdb.cpp:266763
void duckdb_destroy_catalog(duckdb_catalog *catalog)
Definition duckdb.cpp:264704
duckdb_error_data duckdb_schema_from_arrow(duckdb_connection connection, struct ArrowSchema *schema, duckdb_arrow_converted_schema *out_types)
Definition duckdb.cpp:263557
void duckdb_destroy_aggregate_function_set(duckdb_aggregate_function_set *set)
Definition duckdb.cpp:263064
duckdb_state duckdb_bind_int64(duckdb_prepared_statement prepared_statement, idx_t param_idx, int64_t val)
Definition duckdb.cpp:269367
void duckdb_destroy_vector(duckdb_vector *vector)
Definition duckdb.cpp:265976
void duckdb_copy_function_finalize_set_error(duckdb_copy_function_finalize_info info, const char *error)
Definition duckdb.cpp:265686
duckdb_value duckdb_bind_get_parameter(duckdb_bind_info info, idx_t index)
Definition duckdb.cpp:271427
duckdb_state duckdb_appender_destroy(duckdb_appender *appender)
Definition duckdb.cpp:263214
duckdb_cast_mode duckdb_cast_function_get_cast_mode(duckdb_function_info info)
Definition duckdb.cpp:264517
void duckdb_vector_ensure_validity_writable(duckdb_vector vector)
Definition duckdb.cpp:266047
duckdb_value duckdb_get_struct_child(duckdb_value value, idx_t index)
Definition duckdb.cpp:267178
duckdb_state duckdb_append_uint8(duckdb_appender appender, uint8_t value)
Definition duckdb.cpp:263368
void * duckdb_init_get_bind_data(duckdb_init_info info)
Definition duckdb.cpp:271491
duckdb_table_function duckdb_create_table_function()
Definition duckdb.cpp:271249
int32_t duckdb_get_int32(duckdb_value val)
Definition duckdb.cpp:266670
duckdb_state duckdb_bind_varchar(duckdb_prepared_statement prepared_statement, idx_t param_idx, const char *val)
Definition duckdb.cpp:269453
duckdb_logical_type duckdb_create_map_type(duckdb_logical_type key_type, duckdb_logical_type value_type)
Definition duckdb.cpp:268628
duckdb_decimal duckdb_double_to_decimal(double val, uint8_t width, uint8_t scale)
Definition duckdb.cpp:268309
bool duckdb_get_bool(duckdb_value val)
Definition duckdb.cpp:266640
struct yyjson_mut_val yyjson_mut_val
Definition duckdb.cpp:37769
void duckdb_vector_assign_string_element_len(duckdb_vector vector, idx_t index, const char *str, idx_t str_len)
Definition duckdb.cpp:266071
duckdb_state duckdb_append_int16(duckdb_appender appender, int16_t value)
Definition duckdb.cpp:263349
duckdb_value duckdb_create_int64(int64_t input)
Definition duckdb.cpp:266685
void duckdb_aggregate_function_set_error(duckdb_function_info info_p, const char *error)
Definition duckdb.cpp:263046
bool duckdb_is_finite_timestamp_s(duckdb_timestamp_s ts)
Definition duckdb.cpp:266325
duckdb_state duckdb_append_uint16(duckdb_appender appender, uint16_t value)
Definition duckdb.cpp:263372
duckdb_uhugeint duckdb_get_uuid(duckdb_value val)
Definition duckdb.cpp:266872
void * duckdb_function_get_local_init_data(duckdb_function_info info)
Definition duckdb.cpp:271573
duckdb_value duckdb_create_uuid(duckdb_uhugeint input)
Definition duckdb.cpp:266868
void duckdb_cast_function_set_row_error(duckdb_function_info info, const char *error, idx_t row, duckdb_vector output)
Definition duckdb.cpp:264527
duckdb_value duckdb_create_float(float input)
Definition duckdb.cpp:266742
void duckdb_copy_function_bind_set_error(duckdb_copy_function_bind_info info, const char *error)
Definition duckdb.cpp:265306
duckdb_time_ns duckdb_get_time_ns(duckdb_value val)
Definition duckdb.cpp:266775
duckdb_state duckdb_appender_create_ext(duckdb_connection connection, const char *catalog, const char *schema, const char *table, duckdb_appender *out_appender)
Definition duckdb.cpp:263142
void duckdb_aggregate_function_set_special_handling(duckdb_aggregate_function function)
Definition duckdb.cpp:263017
idx_t duckdb_union_type_member_count(duckdb_logical_type type)
Definition duckdb.cpp:268796
duckdb_value duckdb_create_date(duckdb_date input)
Definition duckdb.cpp:266754
duckdb_bit duckdb_get_bit(duckdb_value val)
Definition duckdb.cpp:266860
std::string to_string(const T &value)
Definition duckdb.cpp:19425
idx_t duckdb_data_chunk_get_column_count(duckdb_data_chunk chunk)
Definition duckdb.cpp:265984
idx_t duckdb_row_count(duckdb_result *result)
Definition duckdb.cpp:270208
void duckdb_connection_get_client_context(duckdb_connection connection, duckdb_client_context *out_context)
Definition duckdb.cpp:266481
#define TABLE_ENTRY(type)
ADBC_EXPORT AdbcStatusCode AdbcConnectionReadPartition(struct AdbcConnection *connection, const uint8_t *serialized_partition, size_t serialized_length, struct ArrowArrayStream *out, struct AdbcError *error)
Construct a statement for a partition of a query. The results can then be read independently.
ADBC_EXPORT AdbcStatusCode AdbcConnectionCommit(struct AdbcConnection *connection, struct AdbcError *error)
Commit any pending transactions. Only used if autocommit is disabled.
ADBC_EXPORT AdbcStatusCode AdbcConnectionRollback(struct AdbcConnection *connection, struct AdbcError *error)
Roll back any pending transactions. Only used if autocommit is disabled.
ADBC_EXPORT AdbcStatusCode AdbcConnectionSetOptionInt(struct AdbcConnection *connection, const char *key, int64_t value, struct AdbcError *error)
Set an integer option.
ADBC_EXPORT AdbcStatusCode AdbcConnectionSetOptionBytes(struct AdbcConnection *connection, const char *key, const uint8_t *value, size_t length, struct AdbcError *error)
Set a bytestring option on a connection.
ADBC_EXPORT AdbcStatusCode AdbcConnectionCancel(struct AdbcConnection *connection, struct AdbcError *error)
Cancel the in-progress operation on a connection.
ADBC_EXPORT AdbcStatusCode AdbcConnectionRelease(struct AdbcConnection *connection, struct AdbcError *error)
Destroy this connection.
ADBC_EXPORT AdbcStatusCode AdbcConnectionSetOption(struct AdbcConnection *connection, const char *key, const char *value, struct AdbcError *error)
Set a char* option.
ADBC_EXPORT AdbcStatusCode AdbcConnectionNew(struct AdbcConnection *connection, struct AdbcError *error)
Allocate a new (but uninitialized) connection.
ADBC_EXPORT AdbcStatusCode AdbcConnectionInit(struct AdbcConnection *connection, struct AdbcDatabase *database, struct AdbcError *error)
Finish setting options and initialize the connection.
ADBC_EXPORT AdbcStatusCode AdbcConnectionSetOptionDouble(struct AdbcConnection *connection, const char *key, double value, struct AdbcError *error)
Set a double option.
ADBC_EXPORT AdbcStatusCode AdbcDatabaseNew(struct AdbcDatabase *database, struct AdbcError *error)
Allocate a new (but uninitialized) database.
ADBC_EXPORT AdbcStatusCode AdbcDatabaseGetOptionInt(struct AdbcDatabase *database, const char *key, int64_t *value, struct AdbcError *error)
Get an integer option of the database.
ADBC_EXPORT AdbcStatusCode AdbcDatabaseGetOptionBytes(struct AdbcDatabase *database, const char *key, uint8_t *value, size_t *length, struct AdbcError *error)
Get a bytestring option of the database.
ADBC_EXPORT AdbcStatusCode AdbcDatabaseInit(struct AdbcDatabase *database, struct AdbcError *error)
Finish setting options and initialize the database.
ADBC_EXPORT AdbcStatusCode AdbcDatabaseSetOption(struct AdbcDatabase *database, const char *key, const char *value, struct AdbcError *error)
Set a char* option.
ADBC_EXPORT AdbcStatusCode AdbcDatabaseGetOption(struct AdbcDatabase *database, const char *key, char *value, size_t *length, struct AdbcError *error)
Get a string option of the database.
ADBC_EXPORT AdbcStatusCode AdbcDatabaseSetOptionDouble(struct AdbcDatabase *database, const char *key, double value, struct AdbcError *error)
Set a double option on a database.
ADBC_EXPORT AdbcStatusCode AdbcDatabaseSetOptionBytes(struct AdbcDatabase *database, const char *key, const uint8_t *value, size_t length, struct AdbcError *error)
Set a bytestring option on a database.
ADBC_EXPORT AdbcStatusCode AdbcDatabaseRelease(struct AdbcDatabase *database, struct AdbcError *error)
Destroy this database. No connections may exist.
ADBC_EXPORT AdbcStatusCode AdbcDatabaseGetOptionDouble(struct AdbcDatabase *database, const char *key, double *value, struct AdbcError *error)
Get a double option of the database.
ADBC_EXPORT AdbcStatusCode AdbcDatabaseSetOptionInt(struct AdbcDatabase *database, const char *key, int64_t value, struct AdbcError *error)
Set an integer option on a database.
AdbcStatusCode(* AdbcDriverInitFunc)(int version, void *driver, struct AdbcError *error)
Common entry point for drivers via the driver manager (which uses dlopen(3)/LoadLibrary)....
Definition duckdb.hpp:56776
ADBC_EXPORT const struct AdbcError * AdbcErrorFromArrayStream(struct ArrowArrayStream *stream, AdbcStatusCode *status)
Get an ADBC error from an ArrowArrayStream created by a driver.
uint8_t AdbcStatusCode
Error codes for operations that may fail.
Definition duckdb.cpp:26657
ADBC_EXPORT int AdbcErrorGetDetailCount(const struct AdbcError *error)
Get the number of metadata values available in an error.
ADBC_EXPORT struct AdbcErrorDetail AdbcErrorGetDetail(const struct AdbcError *error, int index)
Get a metadata value in an error by index.
ADBC_EXPORT AdbcStatusCode AdbcStatementExecutePartitions(struct AdbcStatement *statement, struct ArrowSchema *schema, struct AdbcPartitions *partitions, int64_t *rows_affected, struct AdbcError *error)
Execute a statement and get the results as a partitioned result set.
ADBC_EXPORT AdbcStatusCode AdbcStatementSetSqlQuery(struct AdbcStatement *statement, const char *query, struct AdbcError *error)
Set the SQL query to execute.
ADBC_EXPORT AdbcStatusCode AdbcStatementSetSubstraitPlan(struct AdbcStatement *statement, const uint8_t *plan, size_t length, struct AdbcError *error)
Set the Substrait plan to execute.
ADBC_EXPORT AdbcStatusCode AdbcStatementExecuteQuery(struct AdbcStatement *statement, struct ArrowArrayStream *out, int64_t *rows_affected, struct AdbcError *error)
Execute a statement and get the results.
ADBC_EXPORT AdbcStatusCode AdbcStatementSetOption(struct AdbcStatement *statement, const char *key, const char *value, struct AdbcError *error)
Set a string option on a statement.
ADBC_EXPORT AdbcStatusCode AdbcStatementSetOptionDouble(struct AdbcStatement *statement, const char *key, double value, struct AdbcError *error)
Set a double option on a statement.
ADBC_EXPORT AdbcStatusCode AdbcStatementGetOptionInt(struct AdbcStatement *statement, const char *key, int64_t *value, struct AdbcError *error)
Get an integer option of the statement.
ADBC_EXPORT AdbcStatusCode AdbcStatementBindStream(struct AdbcStatement *statement, struct ArrowArrayStream *stream, struct AdbcError *error)
Bind Arrow data. This can be used for bulk inserts or prepared statements.
ADBC_EXPORT AdbcStatusCode AdbcStatementRelease(struct AdbcStatement *statement, struct AdbcError *error)
Destroy a statement.
ADBC_EXPORT AdbcStatusCode AdbcStatementNew(struct AdbcConnection *connection, struct AdbcStatement *statement, struct AdbcError *error)
Create a new statement for a given connection.
ADBC_EXPORT AdbcStatusCode AdbcStatementCancel(struct AdbcStatement *statement, struct AdbcError *error)
Cancel execution of an in-progress query.
ADBC_EXPORT AdbcStatusCode AdbcStatementPrepare(struct AdbcStatement *statement, struct AdbcError *error)
Turn this statement into a prepared statement to be executed multiple times.
ADBC_EXPORT AdbcStatusCode AdbcStatementGetParameterSchema(struct AdbcStatement *statement, struct ArrowSchema *schema, struct AdbcError *error)
Get the schema for bound parameters.
ADBC_EXPORT AdbcStatusCode AdbcStatementSetOptionBytes(struct AdbcStatement *statement, const char *key, const uint8_t *value, size_t length, struct AdbcError *error)
Set a bytestring option on a statement.
ADBC_EXPORT AdbcStatusCode AdbcStatementBind(struct AdbcStatement *statement, struct ArrowArray *values, struct ArrowSchema *schema, struct AdbcError *error)
Bind Arrow data. This can be used for bulk inserts or prepared statements.
ADBC_EXPORT AdbcStatusCode AdbcStatementGetOptionDouble(struct AdbcStatement *statement, const char *key, double *value, struct AdbcError *error)
Get a double option of the statement.
ADBC_EXPORT AdbcStatusCode AdbcStatementGetOptionBytes(struct AdbcStatement *statement, const char *key, uint8_t *value, size_t *length, struct AdbcError *error)
Get a bytestring option of the statement.
ADBC_EXPORT AdbcStatusCode AdbcStatementExecuteSchema(struct AdbcStatement *statement, struct ArrowSchema *schema, struct AdbcError *error)
Get the schema of the result set of a query without executing it.
ADBC_EXPORT AdbcStatusCode AdbcStatementGetOption(struct AdbcStatement *statement, const char *key, char *value, size_t *length, struct AdbcError *error)
Get a string option of the statement.
ADBC_EXPORT AdbcStatusCode AdbcStatementSetOptionInt(struct AdbcStatement *statement, const char *key, int64_t value, struct AdbcError *error)
Set an integer option on a statement.
void sqrt(InputArray src, OutputArray dst)
void log(InputArray src, OutputArray dst)
std::shared_ptr< _Tp > Ptr
int partition(const std::vector< _Tp > &_vec, std::vector< int > &labels, _EqPredicate predicate=_EqPredicate())
v_reg< _Tp, n > & operator+=(v_reg< _Tp, n > &a, const v_reg< _Tp, n > &b)
v_reg< _Tp, n > & operator/=(v_reg< _Tp, n > &a, const v_reg< _Tp, n > &b)
v_reg< _Tp, n > & operator|=(v_reg< _Tp, n > &a, const v_reg< _Tp, n > &b)
v_reg< _Tp, n > operator>>(const v_reg< _Tp, n > &a, int imm)
v_reg< _Tp, n > & operator-=(v_reg< _Tp, n > &a, const v_reg< _Tp, n > &b)
v_reg< _Tp, n > & operator^=(v_reg< _Tp, n > &a, const v_reg< _Tp, n > &b)
v_reg< _Tp, n > & operator*=(v_reg< _Tp, n > &a, const v_reg< _Tp, n > &b)
v_reg< _Tp, n > & operator&=(v_reg< _Tp, n > &a, const v_reg< _Tp, n > &b)
softfloat & operator%=(const softfloat &a)
softfloat & operator=(const softfloat &c)
softfloat operator-() const
void swap(Mat &a, Mat &b)
std::ostream & operator<<(std::ostream &, const DualQuat< _Tp > &)
__device__ __forceinline__ uchar2 operator|(const uchar2 &a, const uchar2 &b)
__device__ __forceinline__ uchar1 operator!(const uchar1 &a)
__device__ __forceinline__ uchar1 operator<(const uchar1 &a, const uchar1 &b)
__device__ __forceinline__ R operator()(index_type y, index_type x) const
__device__ __forceinline__ uchar4 operator^(const uchar4 &a, const uchar4 &b)
__device__ __forceinline__ uchar1 operator~(const uchar1 &a)
__device__ __forceinline__ uchar1 operator!=(const uchar1 &a, const uchar1 &b)
__device__ __forceinline__ int4 operator/(const uchar4 &a, const uchar4 &b)
__device__ __forceinline__ uchar1 operator&(const uchar1 &a, const uchar1 &b)
__device__ __forceinline__ int1 operator*(const uchar1 &a, const uchar1 &b)
__device__ __forceinline__ uchar1 operator>(const uchar1 &a, const uchar1 &b)
__device__ __forceinline__ int3 operator+(const uchar3 &a, const uchar3 &b)
__device__ __forceinline__ uchar4 operator==(const uchar4 &a, const uchar4 &b)
__device__ __forceinline__ uchar3 operator<=(const uchar3 &a, const uchar3 &b)
__host__ Expr< BinaryTransformPtrSz< typename PtrTraits< GpuMat_< T > >::ptr_type, typename PtrTraits< GpuMat_< T > >::ptr_type, modulus< T > > > operator%(const GpuMat_< T > &src1, const GpuMat_< T > &src2)
__host__ cudaTextureObject_t get() const noexcept
__device__ __forceinline__ uchar1 operator>=(const uchar1 &a, const uchar1 &b)
void filter(InputArray image, InputArray kernel, OutputArray output)
static cv::MediaFrame Create(Args &&... args)
GMat mask(const GMat &src, const GMat &mask)
GMat select(const GMat &src1, const GMat &src2, const GMat &mask)
std::vector< char > serialize(const cv::GComputation &c)
cv::GRunArgsP bind(cv::GRunArgs &out_args)
cv::GComputation deserialize(const std::vector< char > &bytes)
void resize(int src_type, const uchar *src_data, size_t src_step, int src_width, int src_height, uchar *dst_data, size_t dst_step, int dst_width, int dst_height, double inv_scale_x, double inv_scale_y, int interpolation)
double depth(InputArray R, InputArray t, InputArray X)
T & at(int idx, std::vector< T > &items)
PyParams params(const std::string &tag, const std::string &model, const std::string &weights, const std::string &device)
GOpaque< Size > size(const GMat &src)
cv::GOpaque< int64_t > timestamp(G g)
cv::GKernelPackage combine(const cv::GKernelPackage &lhs, const cv::GKernelPackage &rhs)
void scale(cv::Mat &mat, const cv::Mat &range, const T min, const T max)
DestroyBufferUpon
Definition duckdb.hpp:45578
@ EVICTION
Destroy the data buffer upon destroying the associated BlockHandle (block can be evicted).
Definition duckdb.hpp:45580
@ UNPIN
Destroy the data buffer upon eviction to storage (destroy instead of evict).
Definition duckdb.hpp:45581
unique_ptr< Expression >(* function_bind_expression_t)(FunctionBindExpressionInput &input)
The type to bind lambda-specific parameter types.
Definition duckdb.hpp:16514
DatabaseCloseAction
CHECKPOINT: Throws, if the checkpoint fails. Always cleans up. TRY_CHECKPOINT: Does not throw when fa...
Definition duckdb.hpp:40341
FunctionStability
Definition duckdb.hpp:13822
idx_t(* aggregate_size_t)(const AggregateFunction &function)
The type used for sizing hashed aggregate function states.
Definition duckdb.hpp:17999
void(* compression_fetch_row_t)(ColumnSegment &segment, ColumnFetchState &state, row_t row_id, Vector &result, idx_t result_idx)
Function prototype used for reading a single value.
Definition duckdb.hpp:48801
bool IsRightOuterJoin(JoinType type)
True if join is rght or full outer join.
Definition duckdb.cpp:68423
WindowExcludeMode
Represents the window exclusion mode.
Definition duckdb.cpp:60837
bool HasInverseJoinType(JoinType type)
Whether the JoinType has an inverse.
Definition duckdb.cpp:68432
void(* aggregate_finalize_t)(Vector &state, AggregateInputData &aggr_input_data, Vector &result, idx_t count, idx_t offset)
The type used for finalizing hashed aggregate function payloads.
Definition duckdb.hpp:18008
TupleDataPinProperties
Definition duckdb.cpp:56596
uint64_t hash_t
The type used for hashes.
Definition duckdb.hpp:243
unique_ptr< ColumnSegmentState >(* compression_serialize_state_t)(ColumnSegment &segment)
Function prototype for serializing the segment state.
Definition duckdb.hpp:48822
WindowAggregationMode
Definition duckdb.cpp:52962
SecretPersistType
Whether a secret is persistent or temporary.
Definition duckdb.hpp:53134
void(* aggregate_simple_update_t)(Vector inputs[], AggregateInputData &aggr_input_data, idx_t input_count, data_ptr_t state, idx_t count)
The type used for updating simple (non-grouped) aggregate functions.
Definition duckdb.hpp:18020
TableFunctionInitialization
When to call init_global to initialize the table function.
Definition duckdb.hpp:26498
void(* compression_filter_t)(ColumnSegment &segment, ColumnScanState &state, idx_t vector_count, Vector &result, SelectionVector &sel, idx_t &sel_count, const TableFilter &filter, TableFilterState &filter_state)
Function prototype used for applying a filter to a vector while scanning that vector.
Definition duckdb.hpp:48797
MetaPipelineType
Definition duckdb.cpp:60632
JoinType InverseJoinType(JoinType type)
Gets the inverse JoinType, e.g., LEFT -> RIGHT.
Definition duckdb.cpp:68436
CompressionAvailabilityResult CompressionTypeIsAvailable(CompressionType compression_type, optional_ptr< StorageManager > storage_manager)
Definition duckdb.cpp:67573
CheckpointWALAction
Definition duckdb.hpp:23115
@ DELETE_WAL
Delete the WAL file after the checkpoint completes - generally done on shutdown.
Definition duckdb.hpp:23117
@ DONT_DELETE_WAL
Leave the WAL file alone.
Definition duckdb.hpp:23119
LogicalTypeId
Definition duckdb.hpp:2860
@ TIMESTAMP_NS
us
Definition duckdb.hpp:2886
const column_t COLUMN_IDENTIFIER_EMPTY
Special value used to signify an empty column (used for e.g. COUNT(*)).
Definition duckdb.cpp:50304
SinkNextBatchType
Definition duckdb.hpp:20238
IndexRemovalType
Definition duckdb.hpp:50444
@ MAIN_INDEX
Remove from main index, insert into deleted_rows_in_use.
Definition duckdb.hpp:50446
@ MAIN_INDEX_ONLY
Remove from main index only.
Definition duckdb.hpp:50448
@ REVERT_MAIN_INDEX_ONLY
Revert MAIN_INDEX_ONLY, i.e. append to main index.
Definition duckdb.hpp:50452
@ REVERT_MAIN_INDEX
Revert MAIN_INDEX, i.e. append to main index and remove from deleted_rows_in_use.
Definition duckdb.hpp:50450
SortKeyType
Definition duckdb.cpp:55335
LogicalType(* bind_logical_type_function_t)(BindLogicalTypeInput &input)
The type to bind type modifiers to a type.
Definition duckdb.hpp:53861
DependencyEntryType
Definition duckdb.cpp:8892
uint8_t data_t
data pointers
Definition duckdb.hpp:246
int64_t row_t
The type used for row identifiers.
Definition duckdb.hpp:240
SecretSerializationType
Definition duckdb.hpp:53201
@ KEY_VALUE_SECRET
The secret has been serialized as a KeyValueSecret.
Definition duckdb.hpp:53205
@ CUSTOM
The secret is serialized with a custom serialization function.
Definition duckdb.hpp:53203
void(* compression_scan_partial_t)(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result, idx_t result_offset)
Function prototype used for reading an arbitrary ('scan_count') number of values.
Definition duckdb.hpp:48791
SettingScope
Definition duckdb.hpp:37008
void(* aggregate_destructor_t)(Vector &state, AggregateInputData &aggr_input_data, idx_t count)
The type used for the aggregate destructor method. NOTE: this method is used in destructors and MAY N...
Definition duckdb.hpp:18017
AsyncResultType
AsyncResultType is used to indicate the result of a AsyncResult, in the context of a wider operation ...
Definition duckdb.hpp:20204
ColumnDataAllocatorType
Definition duckdb.hpp:18797
@ BUFFER_MANAGER_ALLOCATOR
Use a buffer manager to allocate large chunks of memory that vectors then use.
Definition duckdb.hpp:18799
@ HYBRID
Use a buffer manager to allocate vectors, but use a StringHeap for strings.
Definition duckdb.hpp:18804
@ IN_MEMORY_ALLOCATOR
Definition duckdb.hpp:18802
InsertionOrderPreservingMap< string >(* compression_get_segment_info_t)(QueryContext context, ColumnSegment &segment)
Function prototype for retrieving segment information straight from the column segment.
Definition duckdb.hpp:48832
void(* compression_skip_t)(ColumnSegment &segment, ColumnScanState &state, idx_t skip_count)
Function prototype used for skipping 'skip_count' values, non-trivial if random-access is not support...
Definition duckdb.hpp:48805
CachingMode
Definition duckdb.hpp:7704
void(* aggregate_initialize_t)(const AggregateFunction &function, data_ptr_t state)
The type used for initializing hashed aggregate function states.
Definition duckdb.hpp:18001
SinkResultType
Definition duckdb.hpp:20222
LoggingTargetTable
Logging storage can store entries normalized or denormalized. This enum describes what a single table...
Definition duckdb.hpp:39478
ARTScanResult
Definition duckdb.cpp:59088
vector< LogicalType > GetCopyFunctionReturnLogicalTypes(CopyFunctionReturnType return_type)
Definition duckdb.cpp:220611
InterruptMode
Definition duckdb.hpp:21842
unique_ptr< ColumnSegmentState >(* compression_deserialize_state_t)(Deserializer &deserializer)
Function prototype for deserializing the segment state.
Definition duckdb.hpp:48824
const column_t COLUMN_IDENTIFIER_ROW_ID
Special value used to signify the ROW ID of a table.
Definition duckdb.cpp:50303
TablePartitionInfo
How a table is partitioned by a given set of columns.
Definition duckdb.hpp:22440
OperatorFinalResultType
OperatorFinalResultType is used for the final call.
Definition duckdb.hpp:20193
unique_ptr< FunctionLocalState >(* init_local_state_t)(ExpressionState &state, const BoundFunctionExpression &expr, FunctionData *bind_data)
The type to initialize a thread local state for the scalar function.
Definition duckdb.hpp:16497
CheckpointType
Definition duckdb.hpp:23129
@ CONCURRENT_CHECKPOINT
Definition duckdb.hpp:23135
@ VACUUM_ONLY
Only run vacuum - this can be triggered for in-memory tables.
Definition duckdb.hpp:23137
FunctionErrors
Whether or not a function can throw an error or not.
Definition duckdb.hpp:12540
ColumnIndexType
Definition duckdb.hpp:14595
@ PUSHDOWN_EXTRACT
This index references a struct/variant field that MUST be extracted by the scan and emitted directly.
Definition duckdb.hpp:14600
@ FULL_READ
Regular column index, refers to a column in its entirety.
Definition duckdb.hpp:14598
shared_ptr< T > buffer_ptr
FIXME: this should be a single_thread_ptr.
Definition duckdb.hpp:2709
unordered_map< HivePartitionKey, idx_t, HivePartitionKey::Hash, HivePartitionKey::Equality > hive_partition_map_t
Maps hive partitions to partition_ids.
Definition duckdb.hpp:51585
void(* compression_visit_block_ids_t)(const ColumnSegment &segment, BlockIdVisitor &visitor)
Function prototype for cleaning up the segment state when the column data is dropped.
Definition duckdb.hpp:48826
FunctionCollationHandling
Definition duckdb.hpp:13828
void AssignSharedPointer(shared_ptr< T > &target, const shared_ptr< T > &source)
Definition duckdb.hpp:2180
CoordinateReferenceSystemType
Definition duckdb.cpp:20437
SettingScopeTarget
Definition duckdb.hpp:37019
@ LOCAL_ONLY
Setting can be set in local scope only.
Definition duckdb.hpp:37024
@ GLOBAL_ONLY
Setting can be set in global scope only.
Definition duckdb.hpp:37022
@ GLOBAL_DEFAULT
Setting can be set in both scopes - but defaults to global.
Definition duckdb.hpp:37026
@ LOCAL_DEFAULT
Setting can be set in both scopes - but defaults to local.
Definition duckdb.hpp:37028
unique_ptr< FunctionData >(* bind_aggregate_function_t)(ClientContext &context, AggregateFunction &function, vector< unique_ptr< Expression > > &arguments)
Binds the scalar function and creates the function data.
Definition duckdb.hpp:18014
ColumnDataScanProperties
Definition duckdb.hpp:18807
@ DISALLOW_ZERO_COPY
Definition duckdb.hpp:18814
@ ALLOW_ZERO_COPY
Definition duckdb.hpp:18811
CSVState
All States of CSV parsing.
Definition duckdb.cpp:59173
@ NOT_SET
Got to an Invalid State, this should error.
Definition duckdb.cpp:59187
constexpr T ClampValue(T v, T min, T max)
Like std::clamp (C++17), returns v if within bounds, else nearest bound.
Definition duckdb.hpp:2115
void(* aggregate_update_t)(Vector inputs[], AggregateInputData &aggr_input_data, idx_t input_count, Vector &state, idx_t count)
The type used for updating hashed aggregate functions.
Definition duckdb.hpp:18003
void(* get_modified_databases_t)(ClientContext &context, FunctionModifiedDatabasesInput &input)
The type to bind lambda-specific parameter types.
Definition duckdb.hpp:16507
ExtraTypeInfoType
Extra Type Info Type.
Definition duckdb.cpp:20559
idx_t column_t
Type used for column identifiers.
Definition duckdb.hpp:259
unique_ptr< BaseStatistics >(* function_statistics_t)(ClientContext &context, FunctionStatisticsInput &input)
The type to propagate statistics for this scalar function.
Definition duckdb.hpp:16501
const row_t MAX_ROW_ID
The maximum row identifier used in tables.
Definition duckdb.cpp:50301
SimplifiedTokenType
Definition duckdb.hpp:13442
idx_t connection_t
Type used to identify connections.
Definition duckdb.hpp:256
void(* encode_t)(CSVEncoderBuffer &encoded_buffer, char *decoded_buffer, idx_t &decoded_buffer_current_position, const idx_t decoded_buffer_size, char *remaining_bytes_buffer, idx_t &remaining_bytes_size, EncodingFunction *encoding_function)
Decode function, basically takes information about the decoded and the encoded buffers.
Definition duckdb.hpp:38877
FunctionNullHandling
The default null handling is NULL in, NULL out.
Definition duckdb.hpp:13816
void(* aggregate_combine_t)(Vector &state, Vector &combined, AggregateInputData &aggr_input_data, idx_t count)
The type used for combining hashed aggregate states.
Definition duckdb.hpp:18006
void(* compression_select_t)(ColumnSegment &segment, ColumnScanState &state, idx_t vector_count, Vector &result, const SelectionVector &sel, idx_t sel_count)
Function prototype used for reading a subset of the values of a vector indicated by a selection vecto...
Definition duckdb.hpp:48794
unique_ptr< FunctionData >(* bind_scalar_function_t)(ClientContext &context, ScalarFunction &bound_function, vector< unique_ptr< Expression > > &arguments)
The type to bind the scalar function and to create the function data.
Definition duckdb.hpp:16491
BlockIteratorStateType
Definition duckdb.cpp:57026
@ IN_MEMORY
For InMemoryBlockIteratorState.
Definition duckdb.cpp:57028
const row_t MAX_ROW_ID_LOCAL
Transaction-local row IDs start at MAX_ROW_ID.
Definition duckdb.cpp:50302
std::function< void(DataChunk &, ExpressionState &, Vector &)> scalar_function_t
The scalar function type.
Definition duckdb.hpp:16489
CheckpointAction
Definition duckdb.hpp:23122
@ ALWAYS_CHECKPOINT
Always checkpoint regardless of whether or not there is data in the WAL to flush.
Definition duckdb.hpp:23126
@ CHECKPOINT_IF_REQUIRED
Checkpoint only if a checkpoint is required (i.e. the WAL has data in it that can be flushed).
Definition duckdb.hpp:23124
ColumnDataCollectionLifetime
Definition duckdb.hpp:18817
@ THROW_ERROR_AFTER_DATABASE_CLOSES
Definition duckdb.hpp:18822
PartitionedTupleDataType
Definition duckdb.cpp:57600
@ RADIX
Radix partitioning on a hash column.
Definition duckdb.cpp:57603
SinkFinalizeType
Definition duckdb.hpp:20232
bool IsLeftOuterJoin(JoinType type)
True if join is left or full outer join.
Definition duckdb.cpp:68419
VariantStatsShreddingState
Definition duckdb.hpp:16153
@ INCONSISTENT
Result from combining incompatible shreddings.
Definition duckdb.hpp:16161
@ SHREDDED
Shredded consistently.
Definition duckdb.hpp:16159
@ NOT_SHREDDED
No shredding applied yet.
Definition duckdb.hpp:16157
CompressedMaterializationDirection
Needed for (de)serialization without binding.
Definition duckdb.cpp:59255
ExtensionInstallMode
Definition duckdb.hpp:53903
@ CUSTOM_PATH
Extension was install from a custom path, this could be either local or remote.
Definition duckdb.hpp:53909
@ STATICALLY_LINKED
Extension was statically linked.
Definition duckdb.hpp:53911
@ REPOSITORY
Extension was installed using a url deduced from a repository base url.
Definition duckdb.hpp:53907
ExpressionType FlipComparisonExpression(ExpressionType type)
Flip a comparison expression, turning e.g. < into >, or = into =.
Definition duckdb.cpp:68052
PartitionedColumnDataType
Definition duckdb.hpp:47011
@ HIVE
Hive-style multi-field partitioning.
Definition duckdb.hpp:47016
idx_t transaction_t
Type used for transaction timestamps.
Definition duckdb.hpp:253
AggregateOrderDependent
Whether or not the input order influences the result of the aggregate.
Definition duckdb.hpp:16833
bool RefersToSameObject(const reference< T > &a, const reference< T > &b)
Returns whether or not two reference wrappers refer to the same object.
Definition duckdb.hpp:2191
PhysicalType
Definition duckdb.hpp:2738
@ LIST
A list of some logical data type.
Definition duckdb.hpp:2813
@ 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
@ BOOL
Boolean as 8 bit "bool" value.
Definition duckdb.hpp:2743
@ INT8
Signed 8-bit little-endian integer.
Definition duckdb.hpp:2749
@ DOUBLE
8-byte floating point value
Definition duckdb.hpp:2776
unique_ptr< AnalyzeState >(* compression_init_analyze_t)(ColumnData &col_data, PhysicalType type)
The analyze functions are used to determine whether or not to use this compression method The system ...
Definition duckdb.hpp:48768
uint32_t sel_t
Type used for the selection vector.
Definition duckdb.hpp:251
hash_t CombineHash(hash_t left, hash_t right)
Combine two hashes by XORing them.
Definition duckdb.hpp:4635
idx_t storage_t
Type used for storage (column) identifiers.
Definition duckdb.hpp:261
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237
unique_ptr< BaseStatistics >(* aggregate_statistics_t)(ClientContext &context, BoundAggregateExpression &expr, AggregateStatisticsInput &input)
The type used for propagating statistics in aggregate functions (optional).
Definition duckdb.hpp:18011
RecoveryMode
DEFAULT is the standard ACID crash recovery mode. NO_WAL_WRITES disables the WAL for the attached dat...
Definition duckdb.hpp:40337
PhysicalType GetTypeId()
Returns the PhysicalType for the given type.
Definition duckdb.hpp:10381
OperatorFinalizeResultType
Definition duckdb.hpp:20190
const uint64_t VERSION_NUMBER
The version number default, lower and upper bounds of the database storage format.
Definition duckdb.cpp:425834
void(* compression_scan_vector_t)(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, Vector &result)
Function prototype used for reading an entire vector (STANDARD_VECTOR_SIZE).
Definition duckdb.hpp:48788
ExtensionABIType
Definition duckdb.hpp:43802
@ CPP
Uses C++ ABI, version needs to match precisely.
Definition duckdb.hpp:43805
@ C_STRUCT
Uses C ABI using the duckdb_ext_api_v1 struct, version needs to be equal or higher.
Definition duckdb.hpp:43807
@ C_STRUCT_UNSTABLE
Uses C ABI using the duckdb_ext_api_v1 struct including "unstable" functions, version needs to match ...
Definition duckdb.hpp:43809
UpdateScanType
Definition duckdb.hpp:22655
ExpressionType NegateComparisonExpression(ExpressionType type)
Negate a comparison expression, turning e.g. = into !=, or < into >=.
Definition duckdb.cpp:68019
static T AlignValue(T n)
Align value (ceiling) (not for pointer types).
Definition duckdb.hpp:2126
ArrowFormatVersion
Definition duckdb.hpp:19457
@ V1_3
Added Run-End Encoded Layout.
Definition duckdb.hpp:19465
@ V1_2
Added MonthDayNano interval type.
Definition duckdb.hpp:19463
@ V1_1
Added 256-bit Decimal type.
Definition duckdb.hpp:19461
@ V1_5
Expanded Decimal type bit widths to allow 32-bit and 64-bit types.
Definition duckdb.hpp:19470
@ V1_0
Base Version.
Definition duckdb.hpp:19459
@ V1_4
Definition duckdb.hpp:19468
AggregateDistinctDependent
Whether or not the input distinctness influences the result of the aggregate.
Definition duckdb.hpp:16835
BaseColumnPrunerMode
Definition duckdb.cpp:60509
void(* pragma_function_t)(ClientContext &context, const FunctionParameters ¶meters)
Execute the main pragma function.
Definition duckdb.hpp:44018
TableScanType
Definition duckdb.hpp:22671
@ TABLE_SCAN_COMMITTED_ROWS
Scan the latest committed rows.
Definition duckdb.hpp:22678
@ TABLE_SCAN_OMIT_PERMANENTLY_DELETED
Definition duckdb.hpp:22676
@ TABLE_SCAN_ALL_ROWS
Scan all rows, including any deleted rows. Committed updates are merged in.
Definition duckdb.hpp:22673
OperatorResultType
Definition duckdb.hpp:20185
FileType
Definition duckdb.hpp:8110
@ FILE_TYPE_INVALID
Unknown or invalid file handle.
Definition duckdb.hpp:8126
@ FILE_TYPE_DIR
Directory.
Definition duckdb.hpp:8114
@ FILE_TYPE_LINK
Symbolic link.
Definition duckdb.hpp:8120
@ FILE_TYPE_SOCKET
Socket.
Definition duckdb.hpp:8118
@ FILE_TYPE_REGULAR
Regular file.
Definition duckdb.hpp:8112
@ FILE_TYPE_BLOCKDEV
Block device.
Definition duckdb.hpp:8122
@ FILE_TYPE_CHARDEV
Character device.
Definition duckdb.hpp:8124
@ FILE_TYPE_FIFO
FIFO named pipe.
Definition duckdb.hpp:8116
array< FrameDelta, 2 > FrameStats
The half-open ranges of frame boundary values relative to the current row.
Definition duckdb.hpp:17975
DeletedScanType
Definition duckdb.hpp:22646
@ INCLUDE_ALL_DELETED
include all rows, including all deleted rows
Definition duckdb.hpp:22650
@ OMIT_COMMITTED_DELETES
omit only deleted rows that have been committed and have a commit ts lower than the transaction start
Definition duckdb.hpp:22652
const PhysicalType ROW_TYPE
The PhysicalType used by the row identifiers column.
Definition duckdb.cpp:139304
void(* aggregate_wininit_t)(AggregateInputData &aggr_input_data, const WindowPartitionInput &partition, data_ptr_t g_state)
The type used for initializing shared complex/custom windowed aggregate state (optional).
Definition duckdb.hpp:18029
LogicalType(* bind_lambda_function_t)(ClientContext &context, const vector< LogicalType > &function_child_types, idx_t parameter_idx)
The type to bind lambda-specific parameter types.
Definition duckdb.hpp:16503
SourceResultType
Definition duckdb.hpp:20201
IndexBindState
IndexBindState to transition index binding phases preventing lock order inversion.
Definition duckdb.hpp:50202
SecretDisplayType
Determines whether the secrets are allowed to be shown.
Definition duckdb.hpp:53187
AggregateCombineType
Whether or not the combiner needs to preserve the source.
Definition duckdb.hpp:16837
CatalogLookupBehavior
Enum used for indicating lookup behavior of specific catalog types.
Definition duckdb.hpp:6461
hash_t MurmurHash64(uint64_t x)
Definition duckdb.hpp:4650
HLLStorageType
Definition duckdb.hpp:48220
@ HLL_V2
Redis HLL.
Definition duckdb.hpp:48222
bool PropagatesBuildSide(JoinType type)
Whether the build side is propagated out of the join.
Definition duckdb.cpp:68427
string(* pragma_query_t)(ClientContext &context, const FunctionParameters ¶meters)
Return a substitute query to execute instead of this pragma statement.
Definition duckdb.hpp:44016
void(* aggregate_window_t)(AggregateInputData &aggr_input_data, const WindowPartitionInput &partition, const_data_ptr_t g_state, data_ptr_t l_state, const SubFrames &subframes, Vector &result, idx_t rid)
The type used for computing complex/custom windowed aggregate functions (optional).
Definition duckdb.hpp:18024
Event
The events that can be triggered in the state machine.
Definition State.hpp:52
States
The states that the state machine can be in.
Definition State.hpp:31
void(* release)(struct ArrowArray *)
Release callback.
Definition duckdb.hpp:11299
int64_t length
Array data description.
Definition duckdb.hpp:11289
void(* release)(struct ArrowSchema *)
Release callback.
Definition duckdb.hpp:11274